�����    �   huggingface�{"info": {"features": {"id": {"dtype": "string", "_type": "Value"}, "text": {"dtype": "string", "_type": "Value"}, "dataset_id": {"dtype": "string", "_type": "Value"}}}}p4���� dataset_id��������text���� id����  �Mj   �� ���X*X*�:��i��i��i�0j�>���!(/6=DKRY_fmt{������������������� "(/6=CJQX_fmsz������������������� !(/6=CJQX]dkry������������������� %,3:AHNT[bipw}������������������ ")07>ELSZahot{������������������� &-3:AHOU[bipw~������������������ %,39@GNU\cjqw~������������������ &-3:AHOV]dkqx������������������ #*18?FMT[bipv}������������������    ! ( / 6 = D J Q X ^ e l s z � � � � � � � � � � � � � � � � � � � �    ' . 5 ; @ F L S Z a h o v | � � � � � � � � � � � � � � � � � � �    " ) 0 7 > E L R Y ` g n u | � � � � � � � � � � � � � � � � � � �     $ + 2 8 ? F L S Z a g m t { � � � � � � � � � � � � � � � � � � �     % , 3 : A H O V ] d j q x  � � � � � � � � � � � � � � � � � � $+29@GNU\bipw~�������������������  '.5<CJOV]dkry�������������������� ")07>ELRY`gnu|�������������������  '.5<CIPW^dkry������������������� %,39@GNU[bipw~������������������")07>EKQX_fmsz������������������� &-4;AHOV]bipw~������������������$+28?FMT[bipw}�������������������  '.39@GNU\cjqx������������������ ")07>ELSZ`gnu|������������������� $+29@GNU[ahov}������������������!(/6<CJQX_fmtz������������������� &-4:AHOV]djpw}�������38765814016188562818627387386932823380814471317183347651403264495972415001213271073714172844081358316637160383506360134462343844574776468238688810306874273099349181343585344792597390166486333719682973648700103339821663374995113143377618609351570587408878247851654953423339241022443574588575417084372601930771486063081529153308261420485931719620323345020981922249285551804564052321949422745003469746225385282028495503541639906962078760191725372757445651053956529441664445062814049235131121021012295298308421290827319191635747393419659429822750981525568745529762348999284373958804161346903034180114302058194364071724674773578722149854217714272561038283302742026464545219720441114780333320949015865127021426397926913174040117217793014073756972522621969621515947253043857259236359921870735966109281267123012655051350246972838319872048936240994364333933488929812246057415262531250466773233462756792460963462494241202986621675339764012873762604452913762392783512741596478571720210225913957201162575251562114873432087571121630537959527945562377306167457615325190191167352815078791318407140125821665851531781347816516059884167639232418659061656010310999196096379376871011070225250396286662157716519099516224123472688649391589687053964783277529191751156245092544023126895097955755450774326556408009530022873843205378362145651834429536724645532115534635182227031627778983607870138929560404153977525510234488251941570411034126381272692332454608112225454481862302613350387564171748244480185808130197224717819459685147956672014957462340510660623127629339507135949214184739618619123422361718740345886571824613496282757614633070861711884054815361167321794873720270235199487218915039932917475724347962140481110351108324212428525979675222159899622352024116133434270632733781558923016933513706569550862351918151176752757855552538761093959616304181119574674504352078422555371245349372173243534417430262735320922303103014757031620452669157359298448303791986728137185460223485196681560680393301110949297151852816977489714033063225721142476945257595093431793375004847460721741508425042114878662676293672213015434224469348027284093904319187046728122410328424073557800364875656456436437582558496804732905326569441942146053392185241410203665098636337937644401362412050344902347163603163687277210811839145463153024253762756245387034056323741401169402873497484237845164404919539206615150221923959263366588153045836252076990111468292549515052026875612284789449210897941838692729326385588513399813562242493525793291046064102232749958090256113625317637843349055498319255289233442225212672221642113837711856382221494165591115924986191950116630920811842806627961315251559646912435342720836231890548673881214954361635333521059446295954869377174867774049588481923550598612532364762712424194372920790866042624464626945203102212210640705549558024666193167187279638922791513299443322539712248914511952220650538333232797972581058139752533404753055316454131225189432633287572879334301724072796413280425369569719117276523773433012481245113438368451799601704071248034117412601109338200798054613408963441078875100136321673776094957255360752929104177911901976292000434170192656611914973651275167115217560011212704222991502131891717524954725538152886803589900873392512550859577732589610624985869325527016102481032632490256922511248847486982219132846239572535762173451856100625965072192201185165733582383604327250518037325024824159382049852116215414794532179361636114089173889508296899149711824874297265202599468411731631024525487824642228732172791561850374973115640572423902178648151267955367201400912719158158884852064645172409758166923790352585251661516793967384298868455872853038076114236323147644750710341844923081642171205111260630226725422132183294251591514908957732338022096119977171131350402522772797359121246519473498771933101619533503279342363661359793646714190550635619321599225643907323544921935083063760338145251722734515389243986125411331137914325903773355144354661245226034538154287124440291412808313730231788256508402506331161003091861429496739453942961151238713756886489839588960259438381997284331096335475673483275405095422902911907585279864333889894808783553893146630775990697287730156097982192388552260620522543645993631121431906659381515782275492506211544232578975807596443276546754275939213141423406080480031660448294527012144528812182951875849413784042983374265769228292097175837563162995170304566052374895671384607669142334443368284343309952978246143424074832255533650915137218035900992408252517735903656652301708647391471878609313907828494065426328434145840804333314534408224415083170015720772501013311397833533943245943376422093052272572094138342451352201215947366234176581386964980042195363136367458714353643288326453782168145613840292785013922407275525738521414842961366328058560895072903612105231646922303228212261865712635568401540045672848241107577347002441442809321265327075152847487523471694142339313602109140480161633798672116958572362352295946164547072941217756445100953006856252375430339225604129311652045562252433361508631906655786516204364012769472678426525148156747145126682629048834664662187568556512653036523303210193361344103200073859113482168757231793749706784099927279987645622422967721155369337873440042374085097261233108804275322218274555282010132704550859243516701481752365405710254623126781359973121214905846397628500855947441538864193108348547694883212673189234894338671816102831480778159021001427245292630221581026084124428481460075016722941134455213691641857946334310367893312985953843104333367268207229123875092541726204632479111391820103424430161153684021230282267088395679350342748112594036714434067037363133067828464181331936912303493504884862863469667842442795231776101189853744640042439464041174341090552548437452035054205788307802344701443132423239628355396115352850184313048513472809129992241370229939132943103999963124570370462685714892324206190755619323753744547586000608186887763069216762565656586104979923677546089995520860045641464874742464431630916873703725431021100408313908041371770521956016380912979963155240462008050519120042686018816239081013421031884881429723261023391463757381642261646844579651892191457209049906853517275715572844937554884349013895034717577881987963289126016843193881116118845845937103242753353311868892121320039235872023408335015854431973161851479416846368351583190259626457131283478738501294220429853378835125739254832246270954943014032744360943339187054434752588567587231309582736776071269206581208044615656749165259372475415236627222546949589979254287674282124592697246907448831815219621246709832823544610291114735458773554850302406756602723343388425278922744911263126557705005082094623115030432801333414564962041263124473042392993517424122680232246089511129040573113728922189764550079951626355951412538448932138614429934065459822795614027169419251301804300619162958249793485228278�U X�^�v� ���� �&�C�GO�Y7a6���2=nC�^�e$py�����p�Y�,�Y���u�����O�d 2S�Sa[7z_�͟-�<���$�~������n����������&@�G$X(t+�9EUK�T׮�3�������c��F�S�v���{�����K3�����1 3a=�=�N�X]q��� � f" G% !' f) a �u Ā � �� � � u� �� }� T� �� �� (� �� � � � � �! " B) U Z �d 9l r G� � 3� �� _� � � �� n� �� � w  -S �T -c "k �� � # �$ u: M< mB �T '_ �� � ǰ ˹ �� l �s �� �� C� �� E� � B� �� �� �(��������O�n� � 5�l.@������y��)�38BA�S"��ڞ�׬�y��������������[S� y_:`e{h�l��������>���P���A����+ +p�������0: ��=>�?�KLjM����� � ; <N=�K�V�o�t]������j�����f�>�����d�;�=Z>�t��W�r�6���M�����v��]6Z<�G�]�h�i%n ����7�������v $(~:=H�O�W�X9^������M��. �&3�4�9�?�Q�T�]nq(w ���t���:�]�&��������������'>/25�F7W�H�"]�ݘu���ޯ۰]�_�|�C�������a���I��$7�bk*�w�0�c��� J Y j Ik �� � �� 'P"̢"��"&�"Ό#��#i�#{�#%�$��$,�$e�$�$��$�O%Z_%{d%��%ĕ%E�%#�%R�%l�%�&]s&-~&��&O�&8�& �,��,S�,H�,��,��,��,}%-�5-�Z-0^-%�-ث-��-��-+.� .] .� .�N.\^.4k./r.M{.0�."/`#/g8/#9/�B/�E/!I/�Q/�o/;q/Cs/�/��/�/��/�/J�/*�/";0�D02U0!j0��0[�0��09�0��2��2 -3�>3/J3U3Dq3�}3Հ3��3�3G�34�3��3)�3�3�4��4/�4��4�5275:@5sB5��54�5�5��5��5�66�6=66�6��6��6��6c�6@7�7~7n7od7�i7��7?�7��7[�7:�7��7��7 �7�8�!8��8�8M97L9ɛ9��9��9��9E:�:�:�:�#:2::�;:=<:�K:N:L;�&;�*;�8;�?;�;��;��;+�;�;��;̶;b�;W@<=g<u<Q�<Ǖ<#�<b�</�</�<H�<��<==�"=�7=\\=�g=Gk=-�=ȶ=��=��=��=��=\�=��=��=�>�>�> >�>D">�/>�C>�G>oK>1S>U>�\>n`>�e>��>�}?!�?q�?�?+�?1�?��?�@F @j(@"R@c[@�r@��@�@��@��@WA�AQAA��A��AB�3B�ABFB�IB�pBv�B��B{�Bm�B�=CrACwHC�NC�RC�TC�`ClcC��C�C��C��C��C��C D\!Dg+D��D��DH�D��D�D��D�D2 E�\E*gE;tEzE��E9�E~�E�ED�E��E�E��E�F�F�F� F�F!F�=FgGF�cF�oFsF�|F]�F�FßF��F�F'�F��F�wG�G��Gi�G�G��Gs�G��G��Gl/Hh:Hajustremotephone/android_external_chromium_org // Copyright 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 "chrome/renderer/extensions/cast_streaming_native_handler.h" #include #include #include "base/logging.h" #include "base/message_loop/message_loop.h" #include "base/strings/string_number_conversions.h" #include "chrome/common/extensions/api/cast_streaming_rtp_stream.h" #include "chrome/common/extensions/api/cast_streaming_udp_transport.h" #include "chrome/renderer/media/cast_rtp_stream.h" #include "chrome/renderer/media/cast_session.h" #include "chrome/renderer/media/cast_udp_transport.h" #include "content/public/renderer/v8_value_converter.h" #include "extensions/renderer/script_context.h" #include "net/base/host_port_pair.h" #include "third_party/WebKit/public/platform/WebMediaStreamTrack.h" #include "third_party/WebKit/public/web/WebDOMMediaStreamTrack.h" using content::V8ValueConverter; // Extension types. using extensions::api::cast_streaming_rtp_stream::CodecSpecificParams; using extensions::api::cast_streaming_rtp_stream::RtpParams; using extensions::api::cast_streaming_rtp_stream::RtpPayloadParams; using extensions::api::cast_streaming_udp_transport::IPEndPoint; namespace extensions { namespace { const char kRtpStreamNotFound[] = "The RTP stream cannot be found"; const char kUdpTransportNotFound[] = "The UDP transport cannot be found"; const char kInvalidDestination[] = "Invalid destination"; const char kInvalidRtpParams[] = "Invalid value for RTP params"; const char kInvalidAesKey[] = "Invalid value for AES key"; const char kInvalidAesIvMask[] = "Invalid value for AES IV mask"; const char kUnableToConvertArgs[] = "Unable to convert arguments"; const char kUnableToConvertParams[] = "Unable to convert params"; // These helper methods are used to convert between Extension API // types and Cast types. void ToCastCodecSpecificParams(const CodecSpecificParams& ext_params, CastCodecSpecificParams* cast_params) { cast_params->key = ext_params.key; cast_params->value = ext_params.value; } void FromCastCodecSpecificParams(const CastCodecSpecificParams& cast_params, CodecSpecificParams* ext_params) { ext_params->key = cast_params.key; ext_params->value = cast_params.value; } namespace { bool HexDecode(const std::string& input, std::string* output) { std::vector bytes; if (!base::HexStringToBytes(input, &bytes)) return false; output->assign(reinterpret_cast(&bytes[0]), bytes.size()); return true; } } // namespace bool ToCastRtpPayloadParamsOrThrow(v8::Isolate* isolate, const RtpPayloadParams& ext_params, CastRtpPayloadParams* cast_params) { cast_params->payload_type = ext_params.payload_type; cast_params->max_latency_ms = ext_params.max_latency; cast_params->codec_name = ext_params.codec_name; cast_params->ssrc = ext_params.ssrc; cast_params->feedback_ssrc = ext_params.feedback_ssrc; cast_params->clock_rate = ext_params.clock_rate ? *ext_params.clock_rate : 0; cast_params->min_bitrate = ext_params.min_bitrate ? *ext_params.min_bitrate : 0; cast_params->max_bitrate = ext_params.max_bitrate ? *ext_params.max_bitrate : 0; cast_params->channels = ext_params.channels ? *ext_params.channels : 0; cast_params->width = ext_params.width ? *ext_params.width : 0; cast_params->height = ext_params.height ? *ext_params.height : 0; if (ext_params.aes_key && !HexDecode(*ext_params.aes_key, &cast_params->aes_key)) { isolate->ThrowException(v8::Exception::Error( v8::String::NewFromUtf8(isolate, kInvalidAesKey))); return false; } if (ext_params.aes_iv_mask && !HexDecode(*ext_params.aes_iv_mask, &cast_params->aes_iv_mask)) { isolate->ThrowException(v8::Exception::Error( v8::String::NewFromUtf8(isolate, kInvalidAesIvMask))); return false; } for (size_t i = 0; i < ext_params.codec_specific_params.size(); ++i) { CastCodecSpecificParams cast_codec_params; ToCastCodecSpecificParams(*ext_params.codec_specific_params[i], &cast_codec_params); cast_params->codec_specific_params.push_back(cast_codec_params); } return true; } void FromCastRtpPayloadParams(const CastRtpPayloadParams& cast_params, RtpPayloadParams* ext_params) { ext_params->payload_type = cast_params.payload_type; ext_params->max_latency = cast_params.max_latency_ms; ext_params->codec_name = cast_params.codec_name; ext_params->ssrc = cast_params.ssrc; ext_params->feedback_ssrc = cast_params.feedback_ssrc; if (cast_params.clock_rate) ext_params->clock_rate.reset(new int(cast_params.clock_rate)); if (cast_params.min_bitrate) ext_params->min_bitrate.reset(new int(cast_params.min_bitrate)); if (cast_params.max_bitrate) ext_params->max_bitrate.reset(new int(cast_params.max_bitrate)); if (cast_params.channels) ext_params->channels.reset(new int(cast_params.channels)); if (cast_params.width) ext_params->width.reset(new int(cast_params.width)); if (cast_params.height) ext_params->height.reset(new int(cast_params.height)); for (size_t i = 0; i < cast_params.codec_specific_params.size(); ++i) { linked_ptr ext_codec_params( new CodecSpecificParams()); FromCastCodecSpecificParams(cast_params.codec_specific_params[i], ext_codec_params.get()); ext_params->codec_specific_params.push_back(ext_codec_params); } } void FromCastRtpParams(const CastRtpParams& cast_params, RtpParams* ext_params) { std::copy(cast_params.rtcp_features.begin(), cast_params.rtcp_features.end(), std::back_inserter(ext_params->rtcp_features)); FromCastRtpPayloadParams(cast_params.payload, &ext_params->payload); } bool ToCastRtpParamsOrThrow(v8::Isolate* isolate, const RtpParams& ext_params, CastRtpParams* cast_params) { std::copy(ext_params.rtcp_features.begin(), ext_params.rtcp_features.end(), std::back_inserter(cast_params->rtcp_features)); if (!ToCastRtpPayloadParamsOrThrow(isolate, ext_params.payload, &cast_params->payload)) { return false; } return true; } } // namespace CastStreamingNativeHandler::CastStreamingNativeHandler(ScriptContext* context) : ObjectBackedNativeHandler(context), last_transport_id_(1), weak_factory_(this) { RouteFunction("CreateSession", base::Bind(&CastStreamingNativeHandler::CreateCastSession, base::Unretained(this))); RouteFunction("DestroyCastRtpStream", base::Bind(&CastStreamingNativeHandler::DestroyCastRtpStream, base::Unretained(this))); RouteFunction("GetSupportedParamsCastRtpStream", base::Bind(&CastStreamingNativeHandler::GetSupportedParamsCastRtpStream, base::Unretained(this))); RouteFunction("StartCastRtpStream", base::Bind(&CastStreamingNativeHandler::StartCastRtpStream, base::Unretained(this))); RouteFunction("StopCastRtpStream", base::Bind(&CastStreamingNativeHandler::StopCastRtpStream, base::Unretained(this))); RouteFunction("DestroyCastUdpTransport", base::Bind(&CastStreamingNativeHandler::DestroyCastUdpTransport, base::Unretained(this))); RouteFunction("SetDestinationCastUdpTransport", base::Bind(&CastStreamingNativeHandler::SetDestinationCastUdpTransport, base::Unretained(this))); RouteFunction("ToggleLogging", base::Bind(&CastStreamingNativeHandler::ToggleLogging, base::Unretained(this))); RouteFunction("GetRawEvents", base::Bind(&CastStreamingNativeHandler::GetRawEvents, base::Unretained(this))); RouteFunction("GetStats", base::Bind(&CastStreamingNativeHandler::GetStats, base::Unretained(this))); } CastStreamingNativeHandler::~CastStreamingNativeHandler() { } void CastStreamingNativeHandler::CreateCastSession( const v8::FunctionCallbackInfo& args) { CHECK_EQ(3, args.Length()); CHECK(args[0]->IsObject()); CHECK(args[1]->IsObject()); CHECK(args[2]->IsFunction()); blink::WebDOMMediaStreamTrack track1 = blink::WebDOMMediaStreamTrack::fromV8Value(args[0]); if (track1.isNull()) return; blink::WebDOMMediaStreamTrack track2 = blink::WebDOMMediaStreamTrack::fromV8Value(args[1]); if (track2.isNull()) return; scoped_refptr session(new CastSession()); scoped_ptr stream1( new CastRtpStream(track1.component(), session)); scoped_ptr stream2( new CastRtpStream(track2.component(), session)); scoped_ptr udp_transport( new CastUdpTransport(session)); // TODO(imcheng): Use a weak reference to ensure we don't call into an // invalid context when the callback is invoked. create_callback_.reset(args[2].As()); base::MessageLoop::current()->PostTask( FROM_HERE, base::Bind( &CastStreamingNativeHandler::CallCreateCallback, weak_factory_.GetWeakPtr(), base::Passed(&stream1), base::Passed(&stream2), base::Passed(&udp_transport))); } void CastStreamingNativeHandler::CallCreateCallback( scoped_ptr stream1, scoped_ptr stream2, scoped_ptr udp_transport) { v8::Isolate* isolate = context()->isolate(); v8::HandleScope handle_scope(isolate); v8::Context::Scope context_scope(context()->v8_context()); const int stream1_id = last_transport_id_++; rtp_stream_map_[stream1_id] = linked_ptr(stream1.release()); const int stream2_id = last_transport_id_++; rtp_stream_map_[stream2_id] = linked_ptr(stream2.release()); const int udp_id = last_transport_id_++; udp_transport_map_[udp_id] = linked_ptr(udp_transport.release()); v8::Handle callback_args[3]; callback_args[0] = v8::Integer::New(isolate, stream1_id); callback_args[1] = v8::Integer::New(isolate, stream2_id); callback_args[2] = v8::Integer::New(isolate, udp_id); context()->CallFunction(create_callback_.NewHandle(isolate), 3, callback_args); create_callback_.reset(); } void CastStreamingNativeHandler::CallStartCallback(int stream_id) { v8::Isolate* isolate = context()->isolate(); v8::HandleScope handle_scope(isolate); v8::Context::Scope context_scope(context()->v8_context()); v8::Handle event_args = v8::Array::New(isolate, 1); event_args->Set(0, v8::Integer::New(isolate, stream_id)); context()->DispatchEvent("cast.streaming.rtpStream.onStarted", event_args); } void CastStreamingNativeHandler::CallStopCallback(int stream_id) { v8::Isolate* isolate = context()->isolate(); v8::HandleScope handle_scope(isolate); v8::Context::Scope context_scope(context()->v8_context()); v8::Handle event_args = v8::Array::New(isolate, 1); event_args->Set(0, v8::Integer::New(isolate, stream_id)); context()->DispatchEvent("cast.streaming.rtpStream.onStopped", event_args); } void CastStreamingNativeHandler::CallErrorCallback(int stream_id, const std::string& message) { v8::Isolate* isolate = context()->isolate(); v8::HandleScope handle_scope(isolate); v8::Context::Scope context_scope(context()->v8_context()); v8::Handle event_args = v8::Array::New(isolate, 2); event_args->Set(0, v8::Integer::New(isolate, stream_id)); event_args->Set( 1, v8::String::NewFromUtf8( isolate, message.data(), v8::String::kNormalString, message.size())); context()->DispatchEvent("cast.streaming.rtpStream.onError", event_args); } void CastStreamingNativeHandler::DestroyCastRtpStream( const v8::FunctionCallbackInfo& args) { CHECK_EQ(1, args.Length()); CHECK(args[0]->IsInt32()); const int transport_id = args[0]->ToInt32()->Value(); if (!GetRtpStreamOrThrow(transport_id)) return; rtp_stream_map_.erase(transport_id); } void CastStreamingNativeHandler::GetSupportedParamsCastRtpStream( const v8::FunctionCallbackInfo& args) { CHECK_EQ(1, args.Length()); CHECK(args[0]->IsInt32()); const int transport_id = args[0]->ToInt32()->Value(); CastRtpStream* transport = GetRtpStreamOrThrow(transport_id); if (!transport) return; scoped_ptr converter(V8ValueConverter::create()); std::vector cast_params = transport->GetSupportedParams(); v8::Handle result = v8::Array::New(args.GetIsolate(), static_cast(cast_params.size())); for (size_t i = 0; i < cast_params.size(); ++i) { RtpParams params; FromCastRtpParams(cast_params[i], ¶ms); scoped_ptr params_value = params.ToValue(); result->Set( static_cast(i), converter->ToV8Value(params_value.get(), context()->v8_context())); } args.GetReturnValue().Set(result); } void CastStreamingNativeHandler::StartCastRtpStream( const v8::FunctionCallbackInfo& args) { CHECK_EQ(2, args.Length()); CHECK(args[0]->IsInt32()); CHECK(args[1]->IsObject()); const int transport_id = args[0]->ToInt32()->Value(); CastRtpStream* transport = GetRtpStreamOrThrow(transport_id); if (!transport) return; scoped_ptr converter(V8ValueConverter::create()); scoped_ptr params_value( converter->FromV8Value(args[1], context()->v8_context())); if (!params_value) { args.GetIsolate()->ThrowException(v8::Exception::TypeError( v8::String::NewFromUtf8(args.GetIsolate(), kUnableToConvertParams))); return; } scoped_ptr params = RtpParams::FromValue(*params_value); if (!params) { args.GetIsolate()->ThrowException(v8::Exception::TypeError( v8::String::NewFromUtf8(args.GetIsolate(), kInvalidRtpParams))); return; } CastRtpParams cast_params; v8::Isolate* isolate = context()->v8_context()->GetIsolate(); if (!ToCastRtpParamsOrThrow(isolate, *params, &cast_params)) return; base::Closure start_callback = base::Bind(&CastStreamingNativeHandler::CallStartCallback, weak_factory_.GetWeakPtr(), transport_id); base::Closure stop_callback = base::Bind(&CastStreamingNativeHandler::CallStopCallback, weak_factory_.GetWeakPtr(), transport_id); CastRtpStream::ErrorCallback error_callback = base::Bind(&CastStreamingNativeHandler::CallErrorCallback, weak_factory_.GetWeakPtr(), transport_id); transport->Start(cast_params, start_callback, stop_callback, error_callback); } void CastStreamingNativeHandler::StopCastRtpStream( const v8::FunctionCallbackInfo& args) { CHECK_EQ(1, args.Length()); CHECK(args[0]->IsInt32()); const int transport_id = args[0]->ToInt32()->Value(); CastRtpStream* transport = GetRtpStreamOrThrow(transport_id); if (!transport) return; transport->Stop(); } void CastStreamingNativeHandler::DestroyCastUdpTransport( const v8::FunctionCallbackInfo& args) { CHECK_EQ(1, args.Length()); CHECK(args[0]->IsInt32()); const int transport_id = args[0]->ToInt32()->Value(); if (!GetUdpTransportOrThrow(transport_id)) return; udp_transport_map_.erase(transport_id); } void CastStreamingNativeHandler::SetDestinationCastUdpTransport( const v8::FunctionCallbackInfo& args) { CHECK_EQ(2, args.Length()); CHECK(args[0]->IsInt32()); CHECK(args[1]->IsObject()); const int transport_id = args[0]->ToInt32()->Value(); CastUdpTransport* transport = GetUdpTransportOrThrow(transport_id); if (!transport) return; scoped_ptr converter(V8ValueConverter::create()); scoped_ptr destination_value( converter->FromV8Value(args[1], context()->v8_context())); if (!destination_value) { args.GetIsolate()->ThrowException(v8::Exception::TypeError( v8::String::NewFromUtf8(args.GetIsolate(), kUnableToConvertArgs))); return; } scoped_ptr destination = IPEndPoint::FromValue(*destination_value); if (!destination) { args.GetIsolate()->ThrowException(v8::Exception::TypeError( v8::String::NewFromUtf8(args.GetIsolate(), kInvalidDestination))); return; } net::IPAddressNumber ip; if (!net::ParseIPLiteralToNumber(destination->address, &ip)) { args.GetIsolate()->ThrowException(v8::Exception::TypeError( v8::String::NewFromUtf8(args.GetIsolate(), kInvalidDestination))); return; } transport->SetDestination(net::IPEndPoint(ip, destination->port)); } void CastStreamingNativeHandler::ToggleLogging( const v8::FunctionCallbackInfo& args) { CHECK_EQ(2, args.Length()); CHECK(args[0]->IsInt32()); CHECK(args[1]->IsBoolean()); const int stream_id = args[0]->ToInt32()->Value(); CastRtpStream* stream = GetRtpStreamOrThrow(stream_id); if (!stream) return; const bool enable = args[1]->ToBoolean()->Value(); stream->ToggleLogging(enable); } void CastStreamingNativeHandler::GetRawEvents( const v8::FunctionCallbackInfo& args) { CHECK_EQ(3, args.Length()); CHECK(args[0]->IsInt32()); CHECK(args[1]->IsNull() || args[1]->IsString()); CHECK(args[2]->IsFunction()); const int transport_id = args[0]->ToInt32()->Value(); // TODO(imcheng): Use a weak reference to ensure we don't call into an // invalid context when the callback is invoked. linked_ptr > callback( new ScopedPersistent(args[2].As())); std::string extra_data; if (!args[1]->IsNull()) { extra_data = *v8::String::Utf8Value(args[1]); } CastRtpStream* transport = GetRtpStreamOrThrow(transport_id); if (!transport) return; get_raw_events_callbacks_.insert(std::make_pair(transport_id, callback)); transport->GetRawEvents( base::Bind(&CastStreamingNativeHandler::CallGetRawEventsCallback, weak_factory_.GetWeakPtr(), transport_id), extra_data); } void CastStreamingNativeHandler::GetStats( const v8::FunctionCallbackInfo& args) { CHECK_EQ(2, args.Length()); CHECK(args[0]->IsInt32()); CHECK(args[1]->IsFunction()); const int transport_id = args[0]->ToInt32()->Value(); CastRtpStream* transport = GetRtpStreamOrThrow(transport_id); if (!transport) return; // TODO(imcheng): Use a weak reference to ensure we don't call into an // invalid context when the callback is invoked. linked_ptr > callback( new ScopedPersistent(args[1].As())); get_stats_callbacks_.insert(std::make_pair(transport_id, callback)); transport->GetStats( base::Bind(&CastStreamingNativeHandler::CallGetStatsCallback, weak_factory_.GetWeakPtr(), transport_id)); } void CastStreamingNativeHandler::CallGetRawEventsCallback( int transport_id, scoped_ptr raw_events) { v8::Isolate* isolate = context()->isolate(); v8::HandleScope handle_scope(isolate); v8::Context::Scope context_scope(context()->v8_context()); RtpStreamCallbackMap::iterator it = get_raw_events_callbacks_.find(transport_id); if (it == get_raw_events_callbacks_.end()) return; v8::Handle callback_args[1]; scoped_ptr converter(V8ValueConverter::create()); callback_args[0] = converter->ToV8Value(raw_events.get(), context()->v8_context()); context()->CallFunction(it->second->NewHandle(isolate), 1, callback_args); get_raw_events_callbacks_.erase(it); } void CastStreamingNativeHandler::CallGetStatsCallback( int transport_id, scoped_ptr stats) { v8::Isolate* isolate = context()->isolate(); v8::HandleScope handle_scope(isolate); v8::Context::Scope context_scope(context()->v8_context()); RtpStreamCallbackMap::iterator it = get_stats_callbacks_.find(transport_id); if (it == get_stats_callbacks_.end()) return; scoped_ptr converter(V8ValueConverter::create()); v8::Handle callback_args[1]; callback_args[0] = converter->ToV8Value(stats.get(), context()->v8_context()); context()->CallFunction(it->second->NewHandle(isolate), 1, callback_args); get_stats_callbacks_.erase(it); } CastRtpStream* CastStreamingNativeHandler::GetRtpStreamOrThrow( int transport_id) const { RtpStreamMap::const_iterator iter = rtp_stream_map_.find( transport_id); if (iter != rtp_stream_map_.end()) return iter->second.get(); v8::Isolate* isolate = context()->v8_context()->GetIsolate(); isolate->ThrowException(v8::Exception::RangeError(v8::String::NewFromUtf8( isolate, kRtpStreamNotFound))); return NULL; } CastUdpTransport* CastStreamingNativeHandler::GetUdpTransportOrThrow( int transport_id) const { UdpTransportMap::const_iterator iter = udp_transport_map_.find( transport_id); if (iter != udp_transport_map_.end()) return iter->second.get(); v8::Isolate* isolate = context()->v8_context()->GetIsolate(); isolate->ThrowException(v8::Exception::RangeError( v8::String::NewFromUtf8(isolate, kUdpTransportNotFound))); return NULL; } } // namespace extensions intel/compute-benchmarkssource/framework/utility/windows/working_directory_helper_windows.cpp /* * Copyright (C) 2022 Intel Corporation * * SPDX-License-Identifier: MIT * */ #include "framework/utility/error.h" #include "framework/utility/windows/windows.h" #include "framework/utility/working_directory_helper.h" FileSystem::path WorkingDirectoryHelper::getExeLocation() { char buffer[4096]; FATAL_ERROR_IF_SYS_CALL_FAILED(GetModuleFileNameA(nullptr, buffer, sizeof(buffer)), "retrieving .exe location"); return FileSystem::path{buffer}; } #include "stdafx.h" #include "MeshLoader.h" #include "MeshLoaderHelper.h" #include "SkinnedMesh.h" #include "AnimatedMeshSceneNode.h" using namespace irr; using namespace System; namespace IrrlichtLime { namespace Scene { MeshLoaderHelper^ MeshLoaderHelper::Wrap(scene::IMeshLoaderHelper *ref) { if (ref == nullptr) return nullptr; return gcnew MeshLoaderHelper (ref); } MeshLoaderHelper::MeshLoaderHelper(scene::IMeshLoaderHelper* ref) : ReferenceCounted(ref) { LIME_ASSERT(ref != nullptr); m_MeshLoaderHelper = ref; } List^ MeshLoaderHelper::loadAnimation(String^ filename, SkinnedMesh^ mesh) { LIME_ASSERT(filename != nullptr); core::array ret = m_MeshLoaderHelper->loadAnimation(Lime::StringToPath(filename), LIME_SAFEREF(mesh, m_SkinnedMesh)); List^ a = gcnew List; for (u32 i = 0; i < ret.size(); ++i) { a->Add(gcnew String(ret[i].c_str())); } return a; } SkinnedMesh^ MeshLoaderHelper::loadRig(String^ filename, AnimatedMesh^ mesh) { LIME_ASSERT(filename != nullptr); scene::ISkinnedMesh* s = m_MeshLoaderHelper->loadRig(Lime::StringToPath(filename), LIME_SAFEREF(mesh, m_AnimatedMesh)); return SkinnedMesh::Wrap(s); } SkinnedMesh^ MeshLoaderHelper::applyAnimation(String^ animName, SkinnedMesh^ mesh) { LIME_ASSERT(animName != nullptr); scene::ISkinnedMesh* m = m_MeshLoaderHelper->applyAnimation(LIME_SAFESTRINGTOSTRINGC_C_STR(animName), LIME_SAFEREF(mesh, m_SkinnedMesh)); return SkinnedMesh::Wrap(m); } MeshLoader^ MeshLoaderHelper::getMeshLoader() { scene::IMeshLoader* l = m_MeshLoaderHelper->getMeshLoader(); return MeshLoader::Wrap(l); } } // namespace Scene } // namespace IrrlichtLimeMacTest/controls/treeview_file_explorer.cpp // // treeview_file_explorer.h // GacOSX // // Created by on 12/14/14. // Copyright (c) 2014 . All rights reserved. // #ifndef GacOSX_treeview_file_explorer_h #define GacOSX_treeview_file_explorer_h #include "../shared/gac_include.h" #include "../shared/osx_shared.h" #include "../shared/UnixFileSystemInfo.h" class FileExplorerWindow : public GuiWindow { private: GuiTreeView* treeView; void OnNodeExpanded(GuiGraphicsComposition* sender, GuiNodeEventArgs& arguments) { tree::MemoryNodeProvider* parent=treeView->Nodes()->GetMemoryNode(arguments.node); if(parent->Children().Count()==1) { tree::MemoryNodeProvider* child=parent->Children()[0].Obj(); Ptr childItem=child->GetData().Cast(); if(childItem->text==L"Loading...") { GetApplication()->InvokeAsync([=]() { // get back the full path from the item Ptr item=parent->GetData().Cast(); WString path=vl::reflection::description::UnboxValue(item->tag); if(path[path.Length()-1]!=L'/') { path+=L"/"; } // add sub folders and sub files List directories, files; SearchDirectoriesAndFiles(path, directories, files); GetApplication()->InvokeInMainThreadAndWait([=, &directories, &files]() { FOREACH(WString, file, directories) { FileExplorerWindow::AddFolder(parent, path+file); } FOREACH(WString, file, files) { FileExplorerWindow::AddFile(parent, path+file); } // remove the "Loading..." node parent->Children().RemoveAt(0); }); }); } } } static vint AddFile(tree::MemoryNodeProvider* parent, const WString& path) { Ptr item=new tree::TreeViewItem; // set the item text using the display name of the file item->text=osx::GetFileDisplayName(path); // set the image using the file icon item->image=new GuiImageData(osx::GetFileIconImage(path, Size(16, 16)), 0); // tag the full path to the item item->tag = vl::reflection::description::BoxValue(path); vint index=parent->Children().Add(new tree::MemoryNodeProvider(item)); return index; } static void AddFolder(tree::MemoryNodeProvider* parent, const WString& path) { vint index=AddFile(parent, path); // Add the "loading" item under a folder Ptr loading=new tree::TreeViewItem; loading->text=L"Loading..."; parent->Children()[index]->Children().Add(new tree::MemoryNodeProvider(loading)); } void InitializeFileSystem() { AddFolder(treeView->Nodes().Obj(), L"/"); } public: FileExplorerWindow() :GuiWindow(GetCurrentTheme()->CreateWindowStyle()) { this->SetText(L"Controls.TreeView.FileExplorerWindow"); // create tree view control to display the local file system treeView=g::NewTreeView(); treeView->SetHorizontalAlwaysVisible(false); treeView->SetVerticalAlwaysVisible(false); treeView->GetBoundsComposition()->SetAlignmentToParent(Margin(4, 4, 4, 4)); // listen to the NodeExpanded event to load the folder content when a folder node is opened treeView->NodeExpanded.AttachMethod(this, &FileExplorerWindow::OnNodeExpanded); this->AddChild(treeView); InitializeFileSystem(); // set the preferred minimum client size this->GetBoundsComposition()->SetPreferredMinSize(Size(640, 480)); // call this to calculate the size immediately if any indirect content in the table changes // so that the window can calcaulte its correct size before calling the MoveToScreenCenter() this->ForceCalculateSizeImmediately(); // move to the screen center this->MoveToScreenCenter(); } ~FileExplorerWindow() { } }; int main(int argc, const char * argv[]) { SetupOSXCoreGraphicsRenderer(); return 0; } void GuiMain() { RunGacWindow(); } #endif src/lib/d2srv/testutils/nc_test_utils.cc // Copyright (C) 2013-2021 Internet Systems Consortium, Inc. ("ISC") // // 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 #include #include #include #include #include #include #include using namespace std; using namespace isc; using namespace isc::d2; namespace ph = std::placeholders; namespace isc { namespace d2 { const char* valid_d2_config = "{ " "\"ip-address\" : \"127.0.0.1\" , " "\"port\" : 5031, " "\"tsig-keys\": [" "{ \"name\": \"d2_key.example.com\" , " " \"algorithm\": \"HMAC-MD5\" ," " \"secret\": \"LS " "} ]," "\"forward-ddns\" : {" "\"ddns-domains\": [ " "{ \"name\": \"example.com.\" , " " \"key-name\": \"d2_key.example.com\" , " " \"dns-servers\" : [ " " { \"ip-address\": \"127.0.0.101\" } " "] } ] }, " "\"reverse-ddns\" : {" "\"ddns-domains\": [ " "{ \"name\": \" 0.168.192.in.addr.arpa.\" , " " \"key-name\": \"d2_key.example.com\" , " " \"dns-servers\" : [ " " { \"ip-address\": \"127.0.0.101\" , " " \"port\": 100 } ] } " "] } }"; const char* TEST_DNS_SERVER_IP = "127.0.0.1"; size_t TEST_DNS_SERVER_PORT = 5301; //const bool HAS_RDATA = true; const bool NO_RDATA = false; //*************************** FauxServer class *********************** FauxServer::FauxServer(asiolink::IOService& io_service, asiolink::IOAddress& address, size_t port) :io_service_(io_service), address_(address), port_(port), server_socket_(), receive_pending_(false), perpetual_receive_(true), tsig_key_() { server_socket_.reset(new boost::asio::ip::udp::socket(io_service_.get_io_service(), boost::asio::ip::udp::v4())); server_socket_->set_option(boost::asio::socket_base::reuse_address(true)); isc::asiolink::UDPEndpoint endpoint(address_, port_); server_socket_->bind(endpoint.getASIOEndpoint()); } FauxServer::FauxServer(asiolink::IOService& io_service, DnsServerInfo& server) :io_service_(io_service), address_(server.getIpAddress()), port_(server.getPort()), server_socket_(), receive_pending_(false), perpetual_receive_(true), tsig_key_() { server_socket_.reset(new boost::asio::ip::udp::socket(io_service_.get_io_service(), boost::asio::ip::udp::v4())); server_socket_->set_option(boost::asio::socket_base::reuse_address(true)); isc::asiolink::UDPEndpoint endpoint(address_, port_); server_socket_->bind(endpoint.getASIOEndpoint()); } FauxServer::~FauxServer() { } void FauxServer::receive (const ResponseMode& response_mode, const dns::Rcode& response_rcode) { if (receive_pending_) { return; } receive_pending_ = true; server_socket_->async_receive_from(boost::asio::buffer(receive_buffer_, sizeof(receive_buffer_)), remote_, std::bind(&FauxServer::requestHandler, this, ph::_1, ph::_2, response_mode, response_rcode)); } void FauxServer::requestHandler(const boost::system::error_code& error, std::size_t bytes_recvd, const ResponseMode& response_mode, const dns::Rcode& response_rcode) { receive_pending_ = false; // If we encountered an error or received no data then fail. // We expect the client to send good requests. if (error.value() != 0 || bytes_recvd < 1) { ADD_FAILURE() << "FauxServer receive failed: " << error.message(); return; } // If TSIG key isn't NULL, create a context and use to verify the // request and sign the response. dns::TSIGContextPtr context; if (tsig_key_) { context.reset(new dns::TSIGContext(*tsig_key_)); } // We have a successfully received data. We need to turn it into // a request in order to build a proper response. // Note D2UpdateMessage is geared towards making requests and // reading responses. This is the opposite perspective so we have // to a bit of roll-your-own here. dns::Message request(dns::Message::PARSE); util::InputBuffer request_buf(receive_buffer_, bytes_recvd); try { request.fromWire(request_buf); // If context is not NULL, then we need to verify the message. if (context) { dns::TSIGError error = context->verify(request.getTSIGRecord(), receive_buffer_, bytes_recvd); if (error != dns::TSIGError::NOERROR()) { isc_throw(TSIGVerifyError, "TSIG verification failed: " << error.toText()); } } } catch (const std::exception& ex) { // If the request cannot be parsed, then fail the test. // We expect the client to send good requests. ADD_FAILURE() << "FauxServer request is corrupt:" << ex.what(); return; } // The request parsed OK, so let's build a response. // We must use the QID we received in the response or IOFetch will // toss the response out, resulting in eventual timeout. // We fill in the zone with data we know is from the "server". dns::Message response(dns::Message::RENDER); response.setQid(request.getQid()); dns::Question question(dns::Name("response.example.com"), dns::RRClass::ANY(), dns::RRType::SOA()); response.addQuestion(question); response.setOpcode(dns::Opcode(dns::Opcode::UPDATE_CODE)); response.setHeaderFlag(dns::Message::HEADERFLAG_QR, true); // Set the response Rcode to value passed in, default is NOERROR. response.setRcode(response_rcode); // Render the response to a buffer. dns::MessageRenderer renderer; util::OutputBuffer response_buf(TEST_MSG_MAX); renderer.setBuffer(&response_buf); if (response_mode == INVALID_TSIG) { // Create a different key to sign the response. std::string secret ("key that doesn't match"); D2TsigKeyPtr key; ASSERT_NO_THROW(key.reset(new D2TsigKey(dns::Name("badkey"), dns::TSIGKey::HMACMD5_NAME(), secret.c_str(), secret.size()))); context.reset(new dns::TSIGContext(*key)); } response.toWire(renderer, context.get()); // If mode is to ship garbage, then stomp on part of the rendered // message. if (response_mode == CORRUPT_RESP) { response_buf.writeUint16At(0xFFFF, 2); } // Ship the response via synchronous send. try { int cnt = server_socket_->send_to(boost::asio:: buffer(response_buf.getData(), response_buf.getLength()), remote_); // Make sure we sent what we expect to send. if (cnt != response_buf.getLength()) { ADD_FAILURE() << "FauxServer sent: " << cnt << " expected: " << response_buf.getLength(); } } catch (const std::exception& ex) { ADD_FAILURE() << "FauxServer send failed: " << ex.what(); } if (perpetual_receive_) { // Schedule the next receive receive (response_mode, response_rcode); } } //********************** TimedIO class *********************** TimedIO::TimedIO() : io_service_(new isc::asiolink::IOService()), timer_(*io_service_), run_time_(0) { } TimedIO::~TimedIO() { } int TimedIO::runTimedIO(int run_time) { run_time_ = run_time; int cnt = io_service_->get_io_service().poll(); if (cnt == 0) { timer_.setup(std::bind(&TimedIO::timesUp, this), run_time_); cnt = io_service_->get_io_service().run_one(); timer_.cancel(); } return (cnt); } void TimedIO::timesUp() { io_service_->stop(); FAIL() << "Test Time: " << run_time_ << " expired"; } //********************** TransactionTest class *********************** const unsigned int TransactionTest::FORWARD_CHG = 0x01; const unsigned int TransactionTest::REVERSE_CHG = 0x02; const unsigned int TransactionTest::FWD_AND_REV_CHG = REVERSE_CHG | FORWARD_CHG; TransactionTest::TransactionTest() : ncr_(), cfg_mgr_(new D2CfgMgr()) { } TransactionTest::~TransactionTest() { } void TransactionTest::setupForIPv4Transaction(dhcp_ddns::NameChangeType chg_type, int change_mask, const TSIGKeyInfoPtr& tsig_key_info) { const char* msg_str = "{" " \"change-type\" : 0 , " " \"forward-change\" : true , " " \"reverse-change\" : true , " " \"fqdn\" : \"my.forward.example.com.\" , " " \"ip-address\" : \"192.168.2.1\" , " " \"dhcid\" : \"0102030405060708\" , " " \"lease-expires-on\" : \"20130121132405\" , " " \"lease-length\" : 1300, " " \"use-conflict-resolution\" : true " "}"; // Create NameChangeRequest from JSON string. ncr_ = dhcp_ddns::NameChangeRequest::fromJSON(msg_str); // Set the change type. ncr_->setChangeType(chg_type); // If the change mask does not include a forward change clear the // forward domain; otherwise create the domain and its servers. if (!(change_mask & FORWARD_CHG)) { ncr_->setForwardChange(false); forward_domain_.reset(); } else { // Create the forward domain and then its servers. forward_domain_ = makeDomain("example.com.", tsig_key_info); addDomainServer(forward_domain_, "forward.example.com", "127.0.0.1", 5301, tsig_key_info); addDomainServer(forward_domain_, "forward2.example.com", "127.0.0.1", 5302, tsig_key_info); } // If the change mask does not include a reverse change clear the // reverse domain; otherwise create the domain and its servers. if (!(change_mask & REVERSE_CHG)) { ncr_->setReverseChange(false); reverse_domain_.reset(); } else { // Create the reverse domain and its server. reverse_domain_ = makeDomain("2.168.192.in.addr.arpa.", tsig_key_info); addDomainServer(reverse_domain_, "reverse.example.com", "127.0.0.1", 5301, tsig_key_info); addDomainServer(reverse_domain_, "reverse2.example.com", "127.0.0.1", 5302, tsig_key_info); } } void TransactionTest::setupForIPv4Transaction(dhcp_ddns::NameChangeType chg_type, int change_mask, const std::string& key_name) { setupForIPv4Transaction(chg_type, change_mask, makeTSIGKeyInfo(key_name)); } void TransactionTest::setupForIPv6Transaction(dhcp_ddns::NameChangeType chg_type, int change_mask, const TSIGKeyInfoPtr& tsig_key_info) { const char* msg_str = "{" " \"change-type\" : 0 , " " \"forward-change\" : true , " " \"reverse-change\" : true , " " \"fqdn\" : \"my6.forward.example.com.\" , " " \"ip-address\" : \"2001:1::100\" , " " \"dhcid\" : \"0102030405060708\" , " " \"lease-expires-on\" : \"20130121132405\" , " " \"lease-length\" : 1300, " " \"use-conflict-resolution\" : true " "}"; // Create NameChangeRequest from JSON string. ncr_ = makeNcrFromString(msg_str); // Set the change type. ncr_->setChangeType(chg_type); // If the change mask does not include a forward change clear the // forward domain; otherwise create the domain and its servers. if (!(change_mask & FORWARD_CHG)) { ncr_->setForwardChange(false); forward_domain_.reset(); } else { // Create the forward domain and then its servers. forward_domain_ = makeDomain("example.com.", tsig_key_info); addDomainServer(forward_domain_, "fwd6-server.example.com", "::1", 5301, tsig_key_info); addDomainServer(forward_domain_, "fwd6-server2.example.com", "::1", 5302, tsig_key_info); } // If the change mask does not include a reverse change clear the // reverse domain; otherwise create the domain and its servers. if (!(change_mask & REVERSE_CHG)) { ncr_->setReverseChange(false); reverse_domain_.reset(); } else { // Create the reverse domain and its server. reverse_domain_ = makeDomain("1.2001.ip6.arpa.", tsig_key_info); addDomainServer(reverse_domain_, "rev6-server.example.com", "::1", 5301, tsig_key_info); addDomainServer(reverse_domain_, "rev6-server2.example.com", "::1", 5302, tsig_key_info); } } void TransactionTest::setupForIPv6Transaction(dhcp_ddns::NameChangeType chg_type, int change_mask, const std::string& key_name) { setupForIPv6Transaction(chg_type, change_mask, makeTSIGKeyInfo(key_name)); } //********************** Functions **************************** void checkRRCount(const D2UpdateMessagePtr& request, D2UpdateMessage::UpdateMsgSection section, int count) { dns::RRsetIterator rrset_it = request->beginSection(section); dns::RRsetIterator rrset_end = request->endSection(section); ASSERT_EQ(count, std::distance(rrset_it, rrset_end)); } void checkZone(const D2UpdateMessagePtr& request, const std::string& exp_zone_name) { // Verify the zone section info. D2ZonePtr zone = request->getZone(); EXPECT_TRUE(zone); EXPECT_EQ(exp_zone_name, zone->getName().toText()); EXPECT_EQ(dns::RRClass::IN().getCode(), zone->getClass().getCode()); } void checkRR(dns::RRsetPtr rrset, const std::string& exp_name, const dns::RRClass& exp_class, const dns::RRType& exp_type, unsigned int exp_ttl, dhcp_ddns::NameChangeRequestPtr ncr, bool has_rdata) { // Verify the FQDN/DHCID RR fields. EXPECT_EQ(exp_name, rrset->getName().toText()); EXPECT_EQ(exp_class.getCode(), rrset->getClass().getCode()); EXPECT_EQ(exp_type.getCode(), rrset->getType().getCode()); EXPECT_EQ(exp_ttl, rrset->getTTL().getValue()); if ((!has_rdata) || (exp_type == dns::RRType::ANY() || exp_class == dns::RRClass::ANY())) { // ANY types do not have RData ASSERT_EQ(0, rrset->getRdataCount()); return; } ASSERT_EQ(1, rrset->getRdataCount()); dns::RdataIteratorPtr rdata_it = rrset->getRdataIterator(); ASSERT_TRUE(rdata_it); if ((exp_type == dns::RRType::A()) || (exp_type == dns::RRType::AAAA())) { // should have lease rdata EXPECT_EQ(ncr->getIpAddress(), rdata_it->getCurrent().toText()); } else if (exp_type == dns::RRType::PTR()) { // should have PTR rdata EXPECT_EQ(ncr->getFqdn(), rdata_it->getCurrent().toText()); } else if (exp_type == dns::RRType::DHCID()) { // should have DHCID rdata const std::vector& ncr_dhcid = ncr->getDhcid().getBytes(); util::InputBuffer buffer(ncr_dhcid.data(), ncr_dhcid.size()); dns::rdata::in::DHCID rdata_ref(buffer, ncr_dhcid.size()); EXPECT_EQ(0, rdata_ref.compare(rdata_it->getCurrent())); } else { // we got a problem FAIL(); } } dns::RRsetPtr getRRFromSection(const D2UpdateMessagePtr& request, D2UpdateMessage::UpdateMsgSection section, int index) { dns::RRsetIterator rrset_it = request->beginSection(section); dns::RRsetIterator rrset_end = request->endSection(section); if (std::distance(rrset_it, rrset_end) <= index) { // Return an empty pointer if index is out of range. return (dns::RRsetPtr()); } std::advance(rrset_it, index); return (*rrset_it); } dhcp_ddns::NameChangeRequestPtr makeNcrFromString(const std::string& ncr_str) { return (dhcp_ddns::NameChangeRequest::fromJSON(ncr_str)); } DdnsDomainPtr makeDomain(const std::string& zone_name, const std::string& key_name) { DnsServerInfoStoragePtr servers(new DnsServerInfoStorage()); DdnsDomainPtr domain(new DdnsDomain(zone_name, servers, key_name)); return (domain); } DdnsDomainPtr makeDomain(const std::string& zone_name, const TSIGKeyInfoPtr &tsig_key_info) { DdnsDomainPtr domain; DnsServerInfoStoragePtr servers(new DnsServerInfoStorage()); std::string key_name; if (tsig_key_info) { key_name = tsig_key_info->getName(); } domain.reset(new DdnsDomain(zone_name, servers, key_name)); return (domain); } TSIGKeyInfoPtr makeTSIGKeyInfo(const std::string& key_name, const std::string& secret, const std::string& algorithm) { TSIGKeyInfoPtr key_info; if (!key_name.empty()) { if (!secret.empty()) { key_info.reset(new TSIGKeyInfo(key_name, algorithm, secret)); } else { // Since secret was left blank, we'll convert key_name into a // base64 encoded string and use that. const uint8_t* bytes = reinterpret_cast (key_name.c_str()); size_t len = key_name.size(); const vector key_name_v(bytes, bytes + len); std::string key_name64 = isc::util::encode::encodeBase64(key_name_v); // Now, make the TSIGKeyInfo with a real base64 secret. key_info.reset(new TSIGKeyInfo(key_name, algorithm, key_name64)); } } return (key_info); } void addDomainServer(DdnsDomainPtr& domain, const std::string& name, const std::string& ip, const size_t port, const TSIGKeyInfoPtr &tsig_key_info) { DnsServerInfoPtr server(new DnsServerInfo(name, asiolink::IOAddress(ip), port, true, tsig_key_info)); domain->getServers()->push_back(server); } // Verifies that the contents of the given transaction's DNS update request // is correct for adding a forward DNS entry void checkAddFwdAddressRequest(NameChangeTransaction& tran) { const D2UpdateMessagePtr& request = tran.getDnsUpdateRequest(); ASSERT_TRUE(request); // Safety check. dhcp_ddns::NameChangeRequestPtr ncr = tran.getNcr(); ASSERT_TRUE(ncr); std::string exp_zone_name = tran.getForwardDomain()->getName(); std::string exp_fqdn = ncr->getFqdn(); const dns::RRType& exp_ip_rr_type = tran.getAddressRRType(); // Verify the zone section. checkZone(request, exp_zone_name); // Verify the PREREQUISITE SECTION // Should be 1 which tests for FQDN does not exist. dns::RRsetPtr rrset; checkRRCount(request, D2UpdateMessage::SECTION_PREREQUISITE, 1); ASSERT_TRUE(rrset = getRRFromSection(request, D2UpdateMessage:: SECTION_PREREQUISITE, 0)); checkRR(rrset, exp_fqdn, dns::RRClass::NONE(), dns::RRType::ANY(), 0, ncr); // Verify the UPDATE SECTION // Should be 2 RRs: 1 to add the FQDN/IP and one to add the DHCID RR checkRRCount(request, D2UpdateMessage::SECTION_UPDATE, 2); // Fetch ttl. uint32_t ttl = ncr->getLeaseLength(); // First, Verify the FQDN/IP add RR. ASSERT_TRUE(rrset = getRRFromSection(request, D2UpdateMessage:: SECTION_UPDATE, 0)); checkRR(rrset, exp_fqdn, dns::RRClass::IN(), exp_ip_rr_type, ttl, ncr); // Now, verify the DHCID add RR. ASSERT_TRUE(rrset = getRRFromSection(request, D2UpdateMessage:: SECTION_UPDATE, 1)); checkRR(rrset, exp_fqdn, dns::RRClass::IN(), dns::RRType::DHCID(), ttl, ncr); // Verify there are no RRs in the ADDITIONAL Section. checkRRCount(request, D2UpdateMessage::SECTION_ADDITIONAL, 0); // Verify that it will render toWire without throwing. dns::MessageRenderer renderer; ASSERT_NO_THROW(request->toWire(renderer)); } // Verifies that the contents of the given transaction's DNS update request // is correct for replacing a forward DNS entry void checkReplaceFwdAddressRequest(NameChangeTransaction& tran) { const D2UpdateMessagePtr& request = tran.getDnsUpdateRequest(); ASSERT_TRUE(request); // Safety check. dhcp_ddns::NameChangeRequestPtr ncr = tran.getNcr(); ASSERT_TRUE(ncr); std::string exp_zone_name = tran.getForwardDomain()->getName(); std::string exp_fqdn = ncr->getFqdn(); const dns::RRType& exp_ip_rr_type = tran.getAddressRRType(); // Verify the zone section. checkZone(request, exp_zone_name); // Verify the PREREQUISITE SECTION // Should be 2, 1 which tests for FQDN does exist and the other // checks for a matching DHCID. dns::RRsetPtr rrset; checkRRCount(request, D2UpdateMessage::SECTION_PREREQUISITE, 2); // Verify the FQDN test RR. ASSERT_TRUE(rrset = getRRFromSection(request, D2UpdateMessage:: SECTION_PREREQUISITE, 0)); checkRR(rrset, exp_fqdn, dns::RRClass::ANY(), dns::RRType::ANY(), 0, ncr); // Verify the DHCID test RR. ASSERT_TRUE(rrset = getRRFromSection(request, D2UpdateMessage:: SECTION_PREREQUISITE, 1)); checkRR(rrset, exp_fqdn, dns::RRClass::IN(), dns::RRType::DHCID(), 0, ncr); // Verify the UPDATE SECTION // Should be 2, 1 which deletes the existing FQDN/IP and one that // adds the new one. checkRRCount(request, D2UpdateMessage::SECTION_UPDATE, 2); // Fetch ttl. uint32_t ttl = ncr->getLeaseLength(); // Verify the FQDN delete RR. ASSERT_TRUE(rrset = getRRFromSection(request, D2UpdateMessage:: SECTION_UPDATE, 0)); checkRR(rrset, exp_fqdn, dns::RRClass::ANY(), exp_ip_rr_type, 0, ncr); // Verify the FQDN/IP add RR. ASSERT_TRUE(rrset = getRRFromSection(request, D2UpdateMessage:: SECTION_UPDATE, 1)); checkRR(rrset, exp_fqdn, dns::RRClass::IN(), exp_ip_rr_type, ttl, ncr); // Verify there are no RRs in the ADDITIONAL Section. checkRRCount(request, D2UpdateMessage::SECTION_ADDITIONAL, 0); // Verify that it will render toWire without throwing. dns::MessageRenderer renderer; ASSERT_NO_THROW(request->toWire(renderer)); } // Verifies that the contents of the given transaction's DNS update request // is correct for replacing a reverse DNS entry void checkReplaceRevPtrsRequest(NameChangeTransaction& tran) { const D2UpdateMessagePtr& request = tran.getDnsUpdateRequest(); ASSERT_TRUE(request); // Safety check. dhcp_ddns::NameChangeRequestPtr ncr = tran.getNcr(); ASSERT_TRUE(ncr); std::string exp_zone_name = tran.getReverseDomain()->getName(); std::string exp_rev_addr = D2CfgMgr::reverseIpAddress(ncr->getIpAddress()); // Verify the zone section. checkZone(request, exp_zone_name); // Verify there are no RRs in the PREREQUISITE Section. checkRRCount(request, D2UpdateMessage::SECTION_PREREQUISITE, 0); // Fetch ttl. uint32_t ttl = ncr->getLeaseLength(); // Verify the UPDATE Section. // It should contain 4 RRs: // 1. A delete all PTR RRs for the given IP // 2. A delete of all DHCID RRs for the given IP // 3. An add of the new PTR RR // 4. An add of the new DHCID RR dns::RRsetPtr rrset; checkRRCount(request, D2UpdateMessage::SECTION_UPDATE, 4); // Verify the PTR delete RR. ASSERT_TRUE(rrset = getRRFromSection(request, D2UpdateMessage:: SECTION_UPDATE, 0)); checkRR(rrset, exp_rev_addr, dns::RRClass::ANY(), dns::RRType::PTR(), 0, ncr); // Verify the DHCID delete RR. ASSERT_TRUE(rrset = getRRFromSection(request, D2UpdateMessage:: SECTION_UPDATE, 1)); checkRR(rrset, exp_rev_addr, dns::RRClass::ANY(), dns::RRType::DHCID(), 0, ncr); // Verify the PTR add RR. ASSERT_TRUE(rrset = getRRFromSection(request, D2UpdateMessage:: SECTION_UPDATE, 2)); checkRR(rrset, exp_rev_addr, dns::RRClass::IN(), dns::RRType::PTR(), ttl, ncr); // Verify the DHCID add RR. ASSERT_TRUE(rrset = getRRFromSection(request, D2UpdateMessage:: SECTION_UPDATE, 3)); checkRR(rrset, exp_rev_addr, dns::RRClass::IN(), dns::RRType::DHCID(), ttl, ncr); // Verify there are no RRs in the ADDITIONAL Section. checkRRCount(request, D2UpdateMessage::SECTION_ADDITIONAL, 0); // Verify that it will render toWire without throwing. dns::MessageRenderer renderer; ASSERT_NO_THROW(request->toWire(renderer)); } void checkRemoveFwdAddressRequest(NameChangeTransaction& tran) { const D2UpdateMessagePtr& request = tran.getDnsUpdateRequest(); ASSERT_TRUE(request); // Safety check. dhcp_ddns::NameChangeRequestPtr ncr = tran.getNcr(); ASSERT_TRUE(ncr); std::string exp_zone_name = tran.getForwardDomain()->getName(); std::string exp_fqdn = ncr->getFqdn(); // Verify the zone section. checkZone(request, exp_zone_name); // Verify there is 1 RR in the PREREQUISITE Section. checkRRCount(request, D2UpdateMessage::SECTION_PREREQUISITE, 1); // Verify the DHCID matching assertion RR. dns::RRsetPtr rrset; ASSERT_TRUE(rrset = getRRFromSection(request, D2UpdateMessage:: SECTION_PREREQUISITE, 0)); checkRR(rrset, exp_fqdn, dns::RRClass::IN(), dns::RRType::DHCID(), 0, ncr); // Verify there is 1 RR in the UPDATE Section. checkRRCount(request, D2UpdateMessage::SECTION_UPDATE, 1); // Verify the FQDN/IP delete RR. const dns::RRType& exp_ip_rr_type = tran.getAddressRRType(); ASSERT_TRUE(rrset = getRRFromSection(request, D2UpdateMessage:: SECTION_UPDATE, 0)); checkRR(rrset, exp_fqdn, dns::RRClass::NONE(), exp_ip_rr_type, 0, ncr); // Verify that it will render toWire without throwing. dns::MessageRenderer renderer; ASSERT_NO_THROW(request->toWire(renderer)); } void checkRemoveFwdRRsRequest(NameChangeTransaction& tran) { const D2UpdateMessagePtr& request = tran.getDnsUpdateRequest(); ASSERT_TRUE(request); // Safety check. dhcp_ddns::NameChangeRequestPtr ncr = tran.getNcr(); ASSERT_TRUE(ncr); std::string exp_zone_name = tran.getForwardDomain()->getName(); std::string exp_fqdn = ncr->getFqdn(); // Verify the zone section. checkZone(request, exp_zone_name); // Verify there is 1 RR in the PREREQUISITE Section. checkRRCount(request, D2UpdateMessage::SECTION_PREREQUISITE, 3); // Verify the DHCID matches assertion. dns::RRsetPtr rrset; ASSERT_TRUE(rrset = getRRFromSection(request, D2UpdateMessage:: SECTION_PREREQUISITE, 0)); checkRR(rrset, exp_fqdn, dns::RRClass::IN(), dns::RRType::DHCID(), 0, ncr); // Verify the NO A RRs assertion. ASSERT_TRUE(rrset = getRRFromSection(request, D2UpdateMessage:: SECTION_PREREQUISITE, 1)); checkRR(rrset, exp_fqdn, dns::RRClass::NONE(), dns::RRType::A(), 0, ncr, NO_RDATA); // Verify the NO AAAA RRs assertion. ASSERT_TRUE(rrset = getRRFromSection(request, D2UpdateMessage:: SECTION_PREREQUISITE, 2)); checkRR(rrset, exp_fqdn, dns::RRClass::NONE(), dns::RRType::AAAA(), 0, ncr, NO_RDATA); // Verify there is 1 RR in the UPDATE Section. checkRRCount(request, D2UpdateMessage::SECTION_UPDATE, 1); // Verify the delete all for the FQDN RR. ASSERT_TRUE(rrset = getRRFromSection(request, D2UpdateMessage:: SECTION_UPDATE, 0)); checkRR(rrset, exp_fqdn, dns::RRClass::ANY(), dns::RRType::ANY(), 0, ncr); // Verify that it will render toWire without throwing. dns::MessageRenderer renderer; ASSERT_NO_THROW(request->toWire(renderer)); } void checkRemoveRevPtrsRequest(NameChangeTransaction& tran) { const D2UpdateMessagePtr& request = tran.getDnsUpdateRequest(); ASSERT_TRUE(request); // Safety check. dhcp_ddns::NameChangeRequestPtr ncr = tran.getNcr(); ASSERT_TRUE(ncr); std::string exp_zone_name = tran.getReverseDomain()->getName(); std::string exp_rev_addr = D2CfgMgr::reverseIpAddress(ncr->getIpAddress()); // Verify the zone section. checkZone(request, exp_zone_name); // Verify there is 1 RR in the PREREQUISITE Section. checkRRCount(request, D2UpdateMessage::SECTION_PREREQUISITE, 1); // Verify the FQDN-PTRNAME assertion RR. dns::RRsetPtr rrset; ASSERT_TRUE(rrset = getRRFromSection(request, D2UpdateMessage:: SECTION_PREREQUISITE, 0)); checkRR(rrset, exp_rev_addr, dns::RRClass::IN(), dns::RRType::PTR(), 0, ncr); // Verify there is 1 RR in the UPDATE Section. checkRRCount(request, D2UpdateMessage::SECTION_UPDATE, 1); // Verify the delete all for the FQDN RR. ASSERT_TRUE(rrset = getRRFromSection(request, D2UpdateMessage:: SECTION_UPDATE, 0)); checkRR(rrset, exp_rev_addr, dns::RRClass::ANY(), dns::RRType::ANY(), 0, ncr); // Verify that it will render toWire without throwing. dns::MessageRenderer renderer; ASSERT_NO_THROW(request->toWire(renderer)); } std::string toHexText(const uint8_t* data, size_t len) { std::ostringstream stream; stream << "Data length is: " << len << std::endl; for (int i = 0; i < len; ++i) { if (i > 0 && ((i % 16) == 0)) { stream << std::endl; } stream << setfill('0') << setw(2) << setbase(16) << static_cast(data[i]) << " "; } return (stream.str()); } // Verifies that the contents of the given transaction's DNS update request // is correct for replacing a forward DNS entry when not using conflict // resolution. void checkSimpleReplaceFwdAddressRequest(NameChangeTransaction& tran) { const D2UpdateMessagePtr& request = tran.getDnsUpdateRequest(); ASSERT_TRUE(request); // Safety check. dhcp_ddns::NameChangeRequestPtr ncr = tran.getNcr(); ASSERT_TRUE(ncr); std::string exp_zone_name = tran.getForwardDomain()->getName(); std::string exp_fqdn = ncr->getFqdn(); const dns::RRType& exp_ip_rr_type = tran.getAddressRRType(); // Verify the zone section. checkZone(request, exp_zone_name); // Verify the PREREQUISITE SECTION // There should be no prerequisites. dns::RRsetPtr rrset; checkRRCount(request, D2UpdateMessage::SECTION_PREREQUISITE, 0); // Verify the UPDATE SECTION // Should be 4 // 1. delete of the FQDN/IP RR // 2. delete of the DHCID RR // 3. add of the FQDN/IP RR // 4. add of the DHCID RR checkRRCount(request, D2UpdateMessage::SECTION_UPDATE, 4); // Fetch ttl. uint32_t ttl = ncr->getLeaseLength(); // Verify the FQDN delete RR. ASSERT_TRUE(rrset = getRRFromSection(request, D2UpdateMessage:: SECTION_UPDATE, 0)); checkRR(rrset, exp_fqdn, dns::RRClass::ANY(), exp_ip_rr_type, 0, ncr); // Verify the DHCID delete RR. ASSERT_TRUE(rrset = getRRFromSection(request, D2UpdateMessage:: SECTION_UPDATE, 1)); checkRR(rrset, exp_fqdn, dns::RRClass::ANY(), dns::RRType::DHCID(), 0, ncr); // Verify the FQDN/IP add RR. ASSERT_TRUE(rrset = getRRFromSection(request, D2UpdateMessage:: SECTION_UPDATE, 2)); checkRR(rrset, exp_fqdn, dns::RRClass::IN(), exp_ip_rr_type, ttl, ncr); // Now, verify the DHCID add RR. ASSERT_TRUE(rrset = getRRFromSection(request, D2UpdateMessage:: SECTION_UPDATE, 3)); checkRR(rrset, exp_fqdn, dns::RRClass::IN(), dns::RRType::DHCID(), ttl, ncr); // Verify there are no RRs in the ADDITIONAL Section. checkRRCount(request, D2UpdateMessage::SECTION_ADDITIONAL, 0); // Verify that it will render toWire without throwing. dns::MessageRenderer renderer; ASSERT_NO_THROW(request->toWire(renderer)); } void checkSimpleRemoveFwdRRsRequest(NameChangeTransaction& tran) { const D2UpdateMessagePtr& request = tran.getDnsUpdateRequest(); ASSERT_TRUE(request); // Safety check. dhcp_ddns::NameChangeRequestPtr ncr = tran.getNcr(); ASSERT_TRUE(ncr); std::string exp_zone_name = tran.getForwardDomain()->getName(); std::string exp_fqdn = ncr->getFqdn(); const dns::RRType& exp_ip_rr_type = tran.getAddressRRType(); // Verify the zone section. checkZone(request, exp_zone_name); // Verify there no prerequisites. checkRRCount(request, D2UpdateMessage::SECTION_PREREQUISITE, 0); // Verify there are 2 RRs in the UPDATE Section. checkRRCount(request, D2UpdateMessage::SECTION_UPDATE, 2); // Verify the FQDN delete RR. dns::RRsetPtr rrset; ASSERT_TRUE(rrset = getRRFromSection(request, D2UpdateMessage:: SECTION_UPDATE, 0)); checkRR(rrset, exp_fqdn, dns::RRClass::ANY(), exp_ip_rr_type, 0, ncr); // Verify the DHCID delete RR. ASSERT_TRUE(rrset = getRRFromSection(request, D2UpdateMessage:: SECTION_UPDATE, 1)); checkRR(rrset, exp_fqdn, dns::RRClass::ANY(), dns::RRType::DHCID(), 0, ncr); // Verify that it will render toWire without throwing. dns::MessageRenderer renderer; ASSERT_NO_THROW(request->toWire(renderer)); } // Verifies that the contents of the given transaction's DNS update request // is correct for removing a reverse DNS entry when not using conflict // resolution. void checkSimpleRemoveRevPtrsRequest(NameChangeTransaction& tran) { const D2UpdateMessagePtr& request = tran.getDnsUpdateRequest(); ASSERT_TRUE(request); // Safety check. dhcp_ddns::NameChangeRequestPtr ncr = tran.getNcr(); ASSERT_TRUE(ncr); std::string exp_zone_name = tran.getReverseDomain()->getName(); std::string exp_rev_addr = D2CfgMgr::reverseIpAddress(ncr->getIpAddress()); // Verify the zone section. checkZone(request, exp_zone_name); // Verify there are no RRs in the PREREQUISITE Section. checkRRCount(request, D2UpdateMessage::SECTION_PREREQUISITE, 0); // Verify there is 2 RRs in the UPDATE Section. checkRRCount(request, D2UpdateMessage::SECTION_UPDATE, 2); // Verify the FQDN delete RR. dns::RRsetPtr rrset; ASSERT_TRUE(rrset = getRRFromSection(request, D2UpdateMessage:: SECTION_UPDATE, 0)); checkRR(rrset, exp_rev_addr, dns::RRClass::ANY(), dns::RRType::PTR(), 0, ncr); // Verify the DHCID delete RR. ASSERT_TRUE(rrset = getRRFromSection(request, D2UpdateMessage:: SECTION_UPDATE, 1)); checkRR(rrset, exp_rev_addr, dns::RRClass::ANY(), dns::RRType::DHCID(), 0, ncr); // Verify that it will render toWire without throwing. dns::MessageRenderer renderer; ASSERT_NO_THROW(request->toWire(renderer)); } // Verifies the current state and next event in a transaction void checkContext(NameChangeTransactionPtr trans, const int exp_state, const int exp_evt, const std::string& file, int line) { ASSERT_TRUE(trans); ASSERT_TRUE(exp_state == trans->getCurrState() && exp_evt == trans->getNextEvent()) << "expected state: " << trans->getStateLabel(exp_state) << " event: " << trans->getEventLabel(exp_evt) << ", actual context: " << trans->getContextStr() << " at " << file << ":" << line; } } // namespace isc::d2 } // namespace isc #include "SpeedControl.h" #include SpeedControl::SpeedControl(volatile double* leftSpeed, volatile double* rightSpeed, MotorDriver* motors) : leftSpeed(leftSpeed), rightSpeed(rightSpeed), motors(motors), myPID(&input, &output, &setpoint, kp, ki, kd, DIRECT) { myPID.SetSampleTime(50); myPID.SetOutputLimits(-15, 15); } void SpeedControl::enable() { enabled = true; myPID.SetMode(AUTOMATIC); myPID.SetTunings(kp, ki, kd); } void SpeedControl::disable() { myPID.SetMode(MANUAL); enabled = false; } void SpeedControl::updatePID() { if (!enabled) return; auto diff = *leftSpeed - *rightSpeed; input = diff;//abs(diff); if (!myPID.Compute()) return; output = abs(output); auto newLeft = motors->leftPulseLength + ( diff > 0 ? -(output) : output ); auto newRight = motors->rightPulseLength + ( diff > 0 ? output : -(output) ); if (newLeft > maxPwm) newLeft = maxPwm; else if (newLeft < minPwm) newLeft = minPwm; if (newRight > maxPwm) newRight = maxPwm; else if (newRight < minPwm) newRight = minPwm; // Serial.print("i: "); // Serial.print(input); // Serial.print("o: "); // Serial.print(output); // Serial.print(" lv: "); // Serial.print(*leftSpeed); // Serial.print(" rv: "); // Serial.print(*rightSpeed); // Serial.print(" nl: "); // Serial.print(newLeft); // Serial.print(" nr: "); // Serial.println(newRight); motors->setLeftPulseLength(newLeft); motors->setRightPulseLength(newRight); } // Copyright 2019 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 "tink/streamingaead/streaming_aead_config.h" #include "absl/memory/memory.h" #include "tink/config.h" #include "tink/registry.h" #include "tink/streamingaead/streaming_aead_catalogue.h" #include "tink/util/status.h" #include "proto/config.pb.h" using google::crypto::tink::RegistryConfig; namespace crypto { namespace tink { namespace { google::crypto::tink::RegistryConfig* GenerateRegistryConfig() { google::crypto::tink::RegistryConfig* config = new google::crypto::tink::RegistryConfig(); config->add_entry()->MergeFrom(*Config::GetTinkKeyTypeEntry( StreamingAeadConfig::kCatalogueName, StreamingAeadConfig::kPrimitiveName, "AesGcmHkdfStreamingKey", 0, true)); config->set_config_name("TINK_STREAMING_AEAD"); return config; } } // anonymous namespace constexpr char StreamingAeadConfig::kCatalogueName[]; constexpr char StreamingAeadConfig::kPrimitiveName[]; // static const google::crypto::tink::RegistryConfig& StreamingAeadConfig::Latest() { static const auto config = GenerateRegistryConfig(); return *config; } // static util::Status StreamingAeadConfig::Register() { auto status = Registry::AddCatalogue( kCatalogueName, absl::make_unique()); if (!status.ok()) return status; return Config::Register(Latest()); } } // namespace tink } // namespace crypto #include "tracker.h" #include Tracker::Tracker() { try { dlib::deserialize("shape_predictor_68_face_landmarks.dat") >> m_pose_model; } catch (dlib::serialization_error& e) { std::cout << std::endl << e.what() << std::endl; } } std::vector Tracker::getSparseFeatures(const cv::Mat& frame) { std::vector sparse_features; try { dlib::cv_image cimg(frame); std::vector faces = m_detector(cimg); // Consider only one face for the processing if (faces.empty()) { return sparse_features; } dlib::full_object_detection shape = m_pose_model(cimg, faces[0]); //const dlib::rgb_pixel color = dlib::rgb_pixel(0, 255, 0); //std::vector circles; auto frame_size = frame.size(); auto two_over_width = 2.0f / static_cast(frame_size.width); auto two_over_height = 2.0f / static_cast(frame_size.height); for (unsigned long i = 0; i < 60; ++i) { const dlib::point& point = shape.part(i); //circles.emplace_back(point, 2, color); //Normalize sparse feature positions such that left-bottom corner is (-1, -1) and top-right corner is (+1, +1). //This is the OpenGL convention. sparse_features.emplace_back(point.x() * two_over_width - 1.0f, 1.0f - point.y() * two_over_height); } //m_window.clear_overlay(); //m_window.set_image(cimg); //m_window.add_overlay(circles); //m_window.add_overlay(render_face_detections(shape)); } catch (std::exception& e) { std::cout << e.what() << std::endl; } return sparse_features; } #include #include #include //#include #include "ledValueSelect.h" #include "sceneRunner.h" #define PIFACE 200 #define LED (PIFACE + 2) int main(int argc, char** argv) { printf("Starting Up TV Emulator\n"); printf("=========================\n"); wiringPiSetupSys(); // Setup the PiFace board piFaceSetup(PIFACE); ledValueSelect valueSelect; sceneRunner runner; for(;;) { valueSelect.selectNextValue(); runner.runCurrentScene(valueSelect); } return 0; } Wiserlightning/pros_okapi_lib_comp #include "main.h" #ifndef GLOBALS_H #define GLOBALS_H //Miscellaneous Libraries #include //Initialization Variables extern const std::vector drive_modes; extern std::string sel_drive_mode; //Hardware Prototypes #define DRV_L_TOP 19 #define DRV_L_BTM 9 #define DRV_R_TOP -2 #define DRV_R_BTM -1 extern okapi::Motor intk_lf; extern okapi::Motor intk_rt; extern okapi::MotorGroup intk_grp; extern okapi::Motor angler; extern okapi::Motor arm; extern okapi::Controller master_ctrl; //Hardware Enums, Constants, Etc. #define GRN_CART okapi::Motor::gearset::green #define RED_CART okapi::Motor::gearset::red #define ENC_TIC okapi::Motor::encoderUnits::counts #define BRKE_COAST okapi::Motor::brakeMode::coast #define JOY_LX okapi::ControllerAnalog::leftX #define JOY_LY okapi::ControllerAnalog::leftY #define JOY_RX okapi::ControllerAnalog::rightX #define JOY_RY okapi::ControllerAnalog::rightY #define BUT_L1 okapi::ControllerDigital::L1 #define BUT_L2 okapi::ControllerDigital::L2 #define BUT_R1 okapi::ControllerDigital::R1 #define BUT_R2 okapi::ControllerDigital::R2 #define BUT_A okapi::ControllerDigital::A #define BUT_B okapi::ControllerDigital::B #define BUT_X okapi::ControllerDigital::X #define BUT_Y okapi::ControllerDigital::Y #define BUT_UP okapi::ControllerDigital::up #define BUT_DWN okapi::ControllerDigital::down #define BUT_LEFT okapi::ControllerDigital::left #define BUT_RIGHT okapi::ControllerDigital::right #endif//-----------------------------------------------------------------------------| // Authorship //-----------------------------------------------------------------------------| // // // // Created: 2018.07.15 // Modified: 2018.08.21 // /* 1.2 - CheckPermutation() - P.90 Given two strings, write a method to decide if one is a permutation of the other. //-----------------------------------------------------------------------------| // PROBLEM SETUP AND ASSUMPTIONS //-----------------------------------------------------------------------------| A string may be represented as an array or linked list of chars. Many languages also support the string as a class A permutation is a rearrangement of characters in a string. //-----------------------------------------------------------------------------| // NAIVE, BRUTE FORCE, TERRIBAD APPROACH //-----------------------------------------------------------------------------| Compare all permutations of one string against the other for equivalence. The time complexity may be represented by the number of comparisons required based on N, the length of the strings. As a string of length N will in the worst case require a quantity of comparisons matching the number of permutations available, the pattern will be as follows: (1) char == 1 combination (a) (2) chars == 2 combinations (ab, ba) (3) chars == 6 combinations (abc, acb, bac, bca, cab, cba) More broadly, we may say that the number of combinations is factorial in nature: O(N!) 1 * 2 * 3 ... * n However, this only represents the number of string comparisons to perform. As such comparisons are char-by-char comparisons down the string, we may expect a time complexity closer to: O(N! * N) Note that this ignores issues of repeated characters or discussions of alphabet size. //-----------------------------------------------------------------------------| // OPTIMIZATIONS //-----------------------------------------------------------------------------| 1) If the string size is an O(1) accessible field, it may be checked first. - Any strings with differing lengths may bypass comparisons - They cannot be permutations of each other. 2) Sorting the two strings (an O(NlogN) operation) may allow us to traverse the sorted strings char-by-char looking for discrepancies. - To be permutations, the quantity of all characters must be the same - So if a mismatch is found in the sorted sequence, the quantities differ and the strings cannot be permutations of each other 3) However, since we only require a count of the characters involved, we can avoid sorting the strings and merely take a tally - 2 tables will be required representing the frequency of characters within each string - After traversing the string to populate these frequency tables, we can compare the tables for discrepancies - The time complexity may be represented as: - O(N) to traverse the first string - O(N) to traverse the second string - O(A) to traverse the frequency table (where A represent the length of the alphabet) - This has the additional advantage that the strings need not be modified or copied 4) A single frequency table may be used by counting up for the first string, then down for the second. This yields a couple advantages: - A slight improvement to memory requirements of the frequency table, as only one alphabet need be stored. - The algorithm may shortcut its comparisons if the decrement value ever drops below 0 (representing more of that character in the second string than the first) //-----------------------------------------------------------------------------| // TIME COMPLEXITY //-----------------------------------------------------------------------------| The time complexity may be represented as: O( n ) to traverse the first string O( n ) to traverse the second string Which simplifies to a time complexity of: O( n ) //-----------------------------------------------------------------------------| // PSEUDOLOGIC //-----------------------------------------------------------------------------| Compare string lengths for equality Declare alphabet table charCounts For each character in string1 Add 1 to the appropriate cell in charCounts For each character in string2 Subtract 1 from the appropriate cell in charCounts If any of the cells is non-zero Return false //-----------------------------------------------------------------------------| // CODE (C++) //-----------------------------------------------------------------------------| */ // Compile with: // $ g++ --std=c++11 01_02_checkPermutations.cpp -o checkPermutations // Run with: // $ ./checkPermutations #include #include // (+) --------------------------------| // #checkPermutations(string) // ------------------------------------| // Desc: Determines whether two strings are permutations of one another or not // Params: string arg1 - The first string to compare // string arg2 - The second string to compare // PreCons: None // PosCons: None // RetVal: bool true - The received strings are permutations of each other // bool false - The received strings are not permutations of each other bool checkPermutations( std::string string1, std::string string2 ) { // Compare string lengths for equality if ( string1.length( ) != string2.length( ) ) { return( false ); } // Declare and initialize alphabet table charCounts int charCounts[ 256 ]; for ( int i = 0 ; i < 256 ; i++ ) { charCounts[ i ] = 0; } // For each character in string1 char currChar; for ( int i = 0 ; i < string1.length( ) ; i++ ) { // Add 1 to the appropriate table in charCounts currChar = string1.at( i ); charCounts[ ( int )currChar ] += 1; } // Closing for - Frequency table loaded // For each character in string2 for ( int i = 0 ; i < string2.length( ) ; i++ ) { // Subtract 1 from the appropriate table in charCounts currChar = string2.at( i ); charCounts[ ( int )currChar ] -= 1; // If the result is <0, then more of a character exist in string 2 than string 1 if ( charCounts[ ( int )currChar ] < 0 ) { // Return false (shortcut) return( false ); } } // Closing for - All comparisons performed // No discrepancies found in the two strings, so... return( true ); } //-----------------------------------------------------------------------------| // DRIVER //-----------------------------------------------------------------------------| // (+) --------------------------------| // #main( int, char* ) // ------------------------------------| // Desc: Code driver // Params: int arg1 - The number of command line arguments passed in // char* arg2 - The content of the command line arguments // PreCons: None // PosCons: None // RetVal: int - The exit code (0 for normal, -1 for error) int main( int argc, char* argv[ ] ) { std::cout << "Test of checkPermutations( )" << std::endl; bool test1 = checkPermutations( "abcdefghijklmnop", "ponmlkjihgfedcba" ); bool test2 = checkPermutations( "abcdefghijklmnopqrstuvwxyz", "abcdefghijklmnopqrstuvwxyy" ); std::cout << "Test 1 (expected: 1) : " << test1 << std::endl; std::cout << "Test 2 (expected: 0) : " << test2 << std::endl; return( 0 ); } // Closing main( int, char* ) // End of file 01_02_checkPermutations.cppDEM/Src/nebula2/src/anim2/nanimeventhandler.cc1-10 //------------------------------------------------------------------------------ // nanimeventhandler.cc // (C) 2005 Radon Labs GmbH //------------------------------------------------------------------------------ #include "anim2/nanimeventhandler.h" //------------------------------------------------------------------------------ /** */ nAnimEventHandler::nAnimEventHandler() { // empty } //------------------------------------------------------------------------------ /** */ nAnimEventHandler::~nAnimEventHandler() { // empty } //------------------------------------------------------------------------------ /** */ void nAnimEventHandler::HandleEvent(const nAnimEventTrack& track, int eventIndex) { n_printf("nAnimEventHandler::HandleEvent(%s, %f)\n", track.GetName().Get(), track.GetEvent(eventIndex).GetTime()); } include/GaussianMarkov_noise.hpp /** * @brief GaussianMarkov_noise * @file GaussianMarkov_noise.hpp * @author <> * @copyright Copyright (c) 2018, Swift Engineering Inc. * @license Licensed under the MIT license. See LICENSE for details. */ #pragma once #include #include namespace avionics_sim { class GaussianMarkov_noise { public: /// /// Init class /// Picks a random rng seed from a random device /// \param [in] tau - GM time constant, in seconds /// \param [in] sigma - GM std dev, if 0 GM will return 0 /// \param [in] initial_output - GM inital value GaussianMarkov_noise(const double tau, const double sigma, const double initial_output); /// /// Init class /// \param [in] tau - GM time constant, in seconds /// \param [in] sigma - GM std dev, if 0 GM will return 0 /// \param [in] initial_output - GM inital value /// \param [in] seed - RNG seed /// \param [in] seed_len - Length of RNG seed /// GaussianMarkov_noise(const double tau, const double sigma, const double initial_output, const uint32_t seed[], const size_t seed_len); /// /// Reset distribution and RNG to initial state /// void reset(); /// /// Time since reset /// \param [in] dT - Timestep, in seconds /// \return return next value in sequence /// double update(const double dT); protected: void initialize(const double tau, const double sigma, const double initial_output, const uint32_t seed[], const size_t seed_len); double m_tau; double m_sigma; double m_initial_output; std::mt19937_64 m_rand_gen; std::normal_distribution m_normal_dist; double m_last_output; std::stringstream m_init_rng_state; }; } // namespace avionics_sim // Simplex.cpp: Implementation for the Simplex class. // Copyright (c) 2017-2018 Extreme Computation Technology and Solutions, LLC // All rights reserved // see file License.txt for license details ////////////////////////////////////////////////////////////////////// #include "./Simplex.h" namespace Geometry { namespace Utils { Simplex::Simplex(){} Simplex::Simplex( const vector &rhs_x) : n((unsigned int)rhs_x.size()-1), npp((unsigned int)rhs_x.size()), x(rhs_x) { assert(n > 0); } Simplex::~Simplex(){} double Simplex::CircumRadius() { Set::VectorSpace::Vector xc = CircumCenter(); Set::VectorSpace::Vector u = x[0] - xc; return sqrt(u(u)); } Set::VectorSpace::Vector Simplex::CircumCenter() { unsigned int i, a; Set::VectorSpace::Hom A(npp); for (a=0; a Simplex::Lambda(const point_type &P) { unsigned int i, a; vector N(npp,0.0); Set::VectorSpace::Hom A(npp); for (a=0; a Simplex::DLambda() { unsigned int i, a; Set::VectorSpace::Vector O(n); vector DN(npp,O); Set::VectorSpace::Vector P(n), Q(n); vector NP = Lambda(P); for (i=0; i NQ = Lambda(Q); for (a=0; aDomino2/main.cpp10-100 #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; const char infile[] = "domino2.in"; const char outfile[] = "domino2.out"; ifstream fin(infile); ofstream fout(outfile); const int MAXN = 100005; const int oo = 0x3f3f3f3f; typedef vector Graph[MAXN]; typedef vector :: iterator It; const inline int min(const int &a, const int &b) { if( a > b ) return b; return a; } const inline int max(const int &a, const int &b) { if( a < b ) return b; return a; } const inline void Get_min(int &a, const int b) { if( a > b ) a = b; } const inline void Get_max(int &a, const int b) { if( a < b ) a = b; } int N; inline void Solve(const int &p) { fout << 2*p - 1 << ' ' << 2*p << '\n'; fout << 2*p << " 1\n"; fout << 1 << ' ' << 2*p+1 << '\n'; fout << 2*p+1<<' '<<2<<'\n'; for(int i=1; i> N; if(N == 1) { fout << "1 1\n"; return 0; } if(N == 2) { fout << "1 1\n1 2\n2 2"; return 0; } if(!(N & 1)) { fout << "-1\n"; return 0; } fout << "3 3\n3 1\n1 1\n1 2\n2 2\n2 3\n"; if(N > 3) Solve(2); fin.close(); fout.close(); return 0; } // (c) Facebook, Inc. and its affiliates. Confidential and proprietary. #include "fboss/qsfp_service/platforms/wedge/WedgeManager.h" #include "fboss/agent/FbossError.h" #include "fboss/lib/CommonFileUtils.h" #include "fboss/lib/config/PlatformConfigUtils.h" #include "fboss/lib/fpga/MultiPimPlatformSystemContainer.h" #include "fboss/qsfp_service/QsfpConfig.h" #include "fboss/qsfp_service/if/gen-cpp2/qsfp_service_config_types.h" #include "fboss/qsfp_service/if/gen-cpp2/transceiver_types.h" #include "fboss/qsfp_service/module/QsfpModule.h" #include "fboss/qsfp_service/module/cmis/CmisModule.h" #include "fboss/qsfp_service/module/sff/SffModule.h" #include "fboss/qsfp_service/platforms/wedge/WedgeQsfp.h" #include "folly/futures/Future.h" #include #include #include #include #include #include #include // allow us to configure the qsfp_service dir so that the qsfp cold boot test // can run concurrently with itself DEFINE_string( qsfp_service_volatile_dir, "/dev/shm/fboss/qsfp_service", "Path to the directory in which we store the qsfp_service's cold boot flag"); DEFINE_bool( init_pim_xphys, false, "Initialize pim xphys after creating xphy map"); namespace { constexpr int kSecAfterModuleOutOfReset = 2; constexpr auto kForceColdBootFileName = "cold_boot_once_qsfp_service"; constexpr auto kWarmbootStateFileName = "qsfp_service_state"; constexpr auto kPhyStateKey = "phy"; } // namespace namespace facebook { namespace fboss { using LockedTransceiversPtr = folly::Synchronized< std::map>>::WLockedPtr; WedgeManager::WedgeManager( std::unique_ptr api, std::unique_ptr platformMapping, PlatformMode mode) : TransceiverManager(std::move(api), std::move(platformMapping)), platformMode_(mode) { /* Constructor for WedgeManager class: * Get the TransceiverPlatformApi object from the creator of this object, * this object will be used for controlling the QSFP devices on board. * Going foward the qsfpPlatApi_ will be used to controll the QSFP devices * on FPGA managed platforms and the wedgeI2cBus_ will be used to control * the QSFP devices on I2C/CPLD managed platforms */ // Cache the map of port name (like eth2/1/1) to the software port id so that // we don't have to do O(n) lookup everytime if (platformMapping_.get()) { auto allPlatformPorts = platformMapping_->getPlatformPorts(); for (auto platformPortIt : allPlatformPorts) { portNameToSwPort_[*platformPortIt.second.mapping_ref()->name_ref()] = platformPortIt.first; } } forceColdBoot_ = removeFile(forceColdBootFileName()); std::string warmBootJson; if (folly::readFile(warmbootStateFileName().c_str(), warmBootJson)) { qsfpServiceState_ = folly::parseJson(warmBootJson); } else { XLOG(INFO) << "Warmboot state filename:" << warmbootStateFileName() << " doesn't exit."; // Simply assign cached state to an empty object qsfpServiceState_ = folly::dynamic::object; } } WedgeManager::~WedgeManager() { // Store necessary information of qsfp_service state into the warmboot state // file. This can be the lane id vector of each port from PhyManager or // transciever info. // Right now, we only need to store phy related info. if (!phyManager_) { return; } folly::dynamic qsfpServiceState = folly::dynamic::object; qsfpServiceState[kPhyStateKey] = phyManager_->getWarmbootState(); folly::writeFile( folly::toPrettyJson(qsfpServiceState), warmbootStateFileName().c_str()); } std::string WedgeManager::forceColdBootFileName() { return folly::to( FLAGS_qsfp_service_volatile_dir, "/", kForceColdBootFileName); } std::string WedgeManager::warmbootStateFileName() { return folly::to( FLAGS_qsfp_service_volatile_dir, "/", kWarmbootStateFileName); } void WedgeManager::loadConfig() { const auto& platformPorts = platformMapping_->getPlatformPorts(); agentConfig_ = AgentConfig::fromDefaultFile(); // Process agent config info here. for (const auto& port : *agentConfig_->thrift.sw_ref()->ports_ref()) { // Get the transceiver id based on the port info from config. auto portId = *port.logicalID_ref(); auto itPlatformPort = platformPorts.find(portId); if (itPlatformPort == platformPorts.end()) { XLOG(ERR) << "Did not find platform port for sw port " << portId; continue; } auto transceiverId = utility::getTransceiverId( itPlatformPort->second, platformMapping_->getChips()); if (!transceiverId) { XLOG(ERR) << "Did not find transceiver id for port id " << portId; continue; } // Add the port to the transceiver indexed port group. auto portGroupIt = portGroupMap_.find(transceiverId.value()); if (portGroupIt == portGroupMap_.end()) { portGroupMap_[transceiverId.value()] = std::set{port}; } else { portGroupIt->second.insert(port); } std::string portName = ""; if (auto name = port.name_ref()) { portName = *name; portNameToModule_[portName] = transceiverId.value(); } XLOG(INFO) << "Added port " << portName << " with portId " << portId << " to transceiver " << transceiverId.value(); } // Process QSFP config here qsfpConfig_ = QsfpConfig::fromDefaultFile(); } void WedgeManager::initTransceiverMap() { // If we can't get access to the USB devices, don't bother to // create the QSFP objects; this is likely to be a permanent // error. try { wedgeI2cBus_ = getI2CBus(); } catch (const I2cError& ex) { XLOG(ERR) << "failed to initialize I2C interface: " << ex.what(); return; } // Initialize port status map for transceivers. for (int idx = 0; idx < getNumQsfpModules(); idx++) { ports_.wlock()->emplace( TransceiverID(idx), std::map()); } // Check if a cold boot has been forced if (!canWarmboot()) { XLOG(INFO) << "Forced cold boot"; for (int idx = 0; idx < getNumQsfpModules(); idx++) { try { // Force hard resets on the transceivers which forces a cold boot of the // modules. triggerQsfpHardReset(idx); } catch (const std::exception& ex) { XLOG(ERR) << "failed to triggerQsfpHardReset at idx " << idx << ": " << ex.what(); } } } else { XLOG(INFO) << "Attempting a warm boot"; } // Also try to load the config file here so that we have transceiver to port // mapping and port name recognization. loadConfig(); refreshTransceivers(); } void WedgeManager::getTransceiversInfo( std::map& info, std::unique_ptr> ids) { XLOG(INFO) << "Received request for getTransceiverInfo, with ids: " << (ids->size() > 0 ? folly::join(",", *ids) : "None"); if (ids->empty()) { folly::gen::range(0, getNumQsfpModules()) | folly::gen::appendTo(*ids); } auto lockedTransceivers = transceivers_.rlock(); for (const auto& i : *ids) { if (!isValidTransceiver(i)) { // If the transceiver idx is not valid, // just skip and continue to the next. continue; } TransceiverInfo trans; if (auto it = lockedTransceivers->find(TransceiverID(i)); it != lockedTransceivers->end()) { try { trans = it->second->getTransceiverInfo(); } catch (const std::exception& ex) { XLOG(ERR) << "Transceiver " << i << ": Error calling getTransceiverInfo(): " << ex.what(); } } else { trans.present_ref() = false; trans.port_ref() = i; } info[i] = trans; } } void WedgeManager::getTransceiversRawDOMData( std::map& info, std::unique_ptr> ids) { XLOG(INFO) << "Received request for getTransceiversRawDOMData, with ids: " << (ids->size() > 0 ? folly::join(",", *ids) : "None"); if (ids->empty()) { folly::gen::range(0, getNumQsfpModules()) | folly::gen::appendTo(*ids); } auto lockedTransceivers = transceivers_.rlock(); for (const auto& i : *ids) { if (!isValidTransceiver(i)) { // If the transceiver idx is not valid, // just skip and continue to the next. continue; } RawDOMData data; if (auto it = lockedTransceivers->find(TransceiverID(i)); it != lockedTransceivers->end()) { try { data = it->second->getRawDOMData(); } catch (const std::exception& ex) { XLOG(ERR) << "Transceiver " << i << ": Error calling getRawDOMData(): " << ex.what(); } info[i] = data; } } } void WedgeManager::getTransceiversDOMDataUnion( std::map& info, std::unique_ptr> ids) { XLOG(INFO) << "Received request for getTransceiversDOMDataUnion, with ids: " << (ids->size() > 0 ? folly::join(",", *ids) : "None"); if (ids->empty()) { folly::gen::range(0, getNumQsfpModules()) | folly::gen::appendTo(*ids); } auto lockedTransceivers = transceivers_.rlock(); for (const auto& i : *ids) { if (!isValidTransceiver(i)) { // If the transceiver idx is not valid, // just skip and continue to the next. continue; } DOMDataUnion data; if (auto it = lockedTransceivers->find(TransceiverID(i)); it != lockedTransceivers->end()) { try { data = it->second->getDOMDataUnion(); } catch (const std::exception& ex) { XLOG(ERR) << "Transceiver " << i << ": Error calling getDOMDataUnion(): " << ex.what(); } info[i] = data; } } } void WedgeManager::readTransceiverRegister( std::map& responses, std::unique_ptr request) { auto ids = *(request->ids_ref()); XLOG(INFO) << "Received request for reading transceiver registers for ids: " << (ids.size() > 0 ? folly::join(",", ids) : "None"); auto lockedTransceivers = transceivers_.rlock(); std::vector>>> futResponses; for (const auto& i : ids) { // Initialize responses with valid = false. This will be overwritten with // the correct valid flag later responses[i].valid_ref() = false; if (isValidTransceiver(i)) { if (auto it = lockedTransceivers->find(TransceiverID(i)); it != lockedTransceivers->end()) { auto param = *(request->parameter_ref()); futResponses.push_back(it->second->futureReadTransceiver(param)); } } } folly::collectAllUnsafe(futResponses) .thenValue([&responses]( const std::vector>>>& tries) { for (const auto& tryResponse : tries) { ReadResponse resp; auto tcvrId = tryResponse.value().first; resp.data_ref() = *(tryResponse.value().second); resp.valid_ref() = resp.data_ref()->length() > 0; responses[tcvrId] = resp; } }) .wait(); } void WedgeManager::writeTransceiverRegister( std::map& responses, std::unique_ptr request) { auto ids = *(request->ids_ref()); XLOG(INFO) << "Received request for writing transceiver register for ids: " << (ids.size() > 0 ? folly::join(",", ids) : "None"); auto lockedTransceivers = transceivers_.rlock(); for (const auto& i : ids) { WriteResponse resp; resp.success_ref() = false; if (isValidTransceiver(i)) { if (auto it = lockedTransceivers->find(TransceiverID(i)); it != lockedTransceivers->end()) { try { auto param = *(request->parameter_ref()); resp.success_ref() = it->second->writeTransceiver(param, *(request->data_ref())); } catch (const std::exception& ex) { XLOG(ERR) << "Transceiver " << i << ": Error writing to transceiver " << ex.what(); } } } responses[i] = resp; } } void WedgeManager::customizeTransceiver(int32_t idx, cfg::PortSpeed speed) { if (!isValidTransceiver(idx)) { return; } auto lockedTransceivers = transceivers_.rlock(); if (auto it = lockedTransceivers->find(TransceiverID(idx)); it != lockedTransceivers->end()) { try { it->second->customizeTransceiver(speed); } catch (const std::exception& ex) { XLOG(ERR) << "Transceiver " << idx << ": Error calling customizeTransceiver(): " << ex.what(); } } } void WedgeManager::syncPorts( std::map& info, std::unique_ptr> ports) { auto groups = folly::gen::from(*ports) | folly::gen::filter([](const std::pair& item) { return item.second.transceiverIdx_ref(); }) | folly::gen::groupBy([](const std::pair& item) { return *item.second.transceiverIdx_ref() .value_unchecked() .transceiverId_ref(); }) | folly::gen::as(); auto lockedTransceivers = transceivers_.rlock(); auto lockedPorts = ports_.wlock(); for (auto& group : groups) { int32_t transceiverIdx = group.key(); auto tcvrID = TransceiverID(transceiverIdx); XLOG(INFO) << "Syncing ports of transceiver " << transceiverIdx; if (!isValidTransceiver(transceiverIdx)) { continue; } // Update the PortStatus map in WedgeManager. for (auto portStatus : group.values()) { lockedPorts->at(tcvrID)[portStatus.first] = portStatus.second; } if (auto it = lockedTransceivers->find(tcvrID); it != lockedTransceivers->end()) { try { auto transceiver = it->second.get(); transceiver->transceiverPortsChanged(lockedPorts->at(tcvrID)); info[transceiverIdx] = transceiver->getTransceiverInfo(); } catch (const std::exception& ex) { XLOG(ERR) << "Transceiver " << transceiverIdx << ": Error calling syncPorts(): " << ex.what(); } } else { XLOG(ERR) << "Syncing ports to a transceiver that is not present."; } } } std::vector WedgeManager::refreshTransceivers() { std::vector transceiverIds; try { wedgeI2cBus_->verifyBus(false); } catch (const std::exception& ex) { XLOG(ERR) << "Error calling verifyBus(): " << ex.what(); return transceiverIds; } clearAllTransceiverReset(); // Since transceivers may appear or disappear, we need to update our // transceiver mapping and type here. updateTransceiverMap(); std::vector> futs; XLOG(INFO) << "Start refreshing all transceivers..."; auto lockedTransceivers = transceivers_.rlock(); for (const auto& transceiver : *lockedTransceivers) { XLOG(DBG3) << "Fired to refresh transceiver " << transceiver.second->getID(); transceiverIds.push_back(TransceiverID(transceiver.second->getID())); futs.push_back(transceiver.second->futureRefresh()); } folly::collectAll(futs.begin(), futs.end()).wait(); XLOG(INFO) << "Finished refreshing all transceivers"; return transceiverIds; } int WedgeManager::scanTransceiverPresence( std::unique_ptr> ids) { // If the id list is empty, we default to scan the presence of all the // transcievers. if (ids->empty()) { folly::gen::range(0, getNumQsfpModules()) | folly::gen::appendTo(*ids); } std::map presenceUpdate; for (auto id : *ids) { presenceUpdate[id] = ModulePresence::UNKNOWN; } wedgeI2cBus_->scanPresence(presenceUpdate); int numTransceiversUp = 0; for (const auto& presence : presenceUpdate) { if (presence.second == ModulePresence::PRESENT) { numTransceiversUp++; } } return numTransceiversUp; } void WedgeManager::clearAllTransceiverReset() { qsfpPlatApi_->clearAllTransceiverReset(); // Required delay time between a transceiver getting out of reset and fully // functional. sleep(kSecAfterModuleOutOfReset); } void WedgeManager::triggerQsfpHardReset(int idx) { auto lockedTransceivers = transceivers_.wlock(); triggerQsfpHardResetLocked(idx, lockedTransceivers); } void WedgeManager::triggerQsfpHardResetLocked( int idx, LockedTransceiversPtr& lockedTransceivers) { // This api accepts 1 based module id however the module id in // WedgeManager is 0 based. qsfpPlatApi_->triggerQsfpHardReset(idx + 1); if (auto it = lockedTransceivers->find(TransceiverID(idx)); it != lockedTransceivers->end()) { lockedTransceivers->erase(it); } } std::unique_ptr WedgeManager::getI2CBus() { return std::make_unique(std::make_unique()); } void WedgeManager::updateTransceiverMap() { std::vector> futInterfaces; std::vector> qsfpImpls; for (int idx = 0; idx < getNumQsfpModules(); idx++) { qsfpImpls.push_back(std::make_unique(idx, wedgeI2cBus_.get())); futInterfaces.push_back( qsfpImpls[idx]->futureGetTransceiverManagementInterface()); } folly::collectAllUnsafe(futInterfaces.begin(), futInterfaces.end()).wait(); // After we have collected all transceivers, get the write lock on // transceivers_ before updating it auto lockedTransceivers = transceivers_.wlock(); auto lockedPorts = ports_.rlock(); for (int idx = 0; idx < getNumQsfpModules(); idx++) { if (!futInterfaces[idx].isReady()) { XLOG(ERR) << "failed getting TransceiverManagementInterface at " << idx; continue; } auto it = lockedTransceivers->find(TransceiverID(idx)); if (it != lockedTransceivers->end()) { // In the case where we already have a transceiver recorded, try to check // whether they match the transceiver type. if (it->second->managementInterface() == futInterfaces[idx].value()) { // The management interface matches. Nothing needs to be done. continue; } else { // The management changes. Need to Delete the old module to make place // for the new one. lockedTransceivers->erase(it); } } // Either we don't have a transceiver here before or we had a new one since // the management interface changed, we want to create a new module here. int portsPerTransceiver = (portGroupMap_.size() == 0 ? numPortsPerTransceiver() : portGroupMap_[idx].size()); if (futInterfaces[idx].value() == TransceiverManagementInterface::CMIS) { XLOG(INFO) << "making CMIS QSFP for " << idx; lockedTransceivers->emplace( TransceiverID(idx), std::make_unique( this, std::move(qsfpImpls[idx]), portsPerTransceiver)); } else if ( futInterfaces[idx].value() == TransceiverManagementInterface::SFF) { XLOG(INFO) << "making Sff QSFP for " << idx; lockedTransceivers->emplace( TransceiverID(idx), std::make_unique( this, std::move(qsfpImpls[idx]), portsPerTransceiver)); } else { XLOG(ERR) << "Unknown Transceiver interface: " << static_cast(futInterfaces[idx].value()) << " at idx " << idx; try { if (!qsfpImpls[idx]->detectTransceiver()) { XLOG(DBG3) << "Transceiver is not present at idx " << idx; continue; } } catch (const std::exception& ex) { XLOG(ERR) << "failed to detect transceiver at idx " << idx << ": " << ex.what(); continue; } // There are times when a module cannot be read however it's present. // Try to reset here since that may be able to bring it back. bool safeToReset = false; if (auto iter = lockedPorts->find(TransceiverID(idx)); iter != lockedPorts->end()) { // Check if we have expected ports info synced over and if all of // the port is down. If any of them is not true then we will not // perform the reset. safeToReset = (iter->second.size() == portsPerTransceiver) && std::all_of( iter->second.begin(), iter->second.end(), [](const auto& port) { return !(*port.second.up_ref()); }); } if (safeToReset && (std::time(nullptr) > pauseRemediationUntil_)) { XLOG(INFO) << "A present transceiver with unknown interface at " << idx << " Try reset."; try { triggerQsfpHardResetLocked(idx, lockedTransceivers); } catch (const std::exception& ex) { XLOG(ERR) << "failed to triggerQsfpHardReset at idx " << idx << ": " << ex.what(); continue; } } else { XLOG(ERR) << "Unknown interface of transceiver with ports up at " << idx; } continue; } // Feed its port status to the newly constructed transceiver. // However skip if ports have not been synced initially. // transceiverPortsChanged will call refreshLocked which takes close to a // second for a transceiver. Calling it for every transceiver at // initialization is time consuming. Leaving that for refreshTransceivers // which runs concurrently for each transceiver. if (auto iter = lockedPorts->find(TransceiverID(idx)); iter != lockedPorts->end() && !iter->second.empty()) { try { lockedTransceivers->at(TransceiverID(idx)) ->transceiverPortsChanged(iter->second); } catch (const std::exception& ex) { XLOG(ERR) << "Transceiver " << idx << ": Error calling transceiverPortsChanged: " << ex.what(); } } } } /* Get the i2c transaction counters from TranscieverManager base class * and update to fbagent. The TransceieverManager base class is inherited * by platform speficic Transaceiver Manager class like WedgeManager. * That class has the function to get the I2c transaction status. */ void WedgeManager::publishI2cTransactionStats() { // Get the i2c transaction stats from TransactionManager class (its // sub-class having platform specific implementation) auto counters = getI2cControllerStats(); if (counters.size() == 0) return; // Populate the i2c stats per pim and per controller for (const I2cControllerStats& counter : counters) { // Publish all the counters to FbAgent auto statName = folly::to( "qsfp.", *counter.controllerName__ref(), ".readTotal"); tcData().setCounter(statName, *counter.readTotal__ref()); statName = folly::to( "qsfp.", *counter.controllerName__ref(), ".readFailed"); tcData().setCounter(statName, *counter.readFailed__ref()); statName = folly::to( "qsfp.", *counter.controllerName__ref(), ".readBytes"); tcData().setCounter(statName, *counter.readBytes__ref()); statName = folly::to( "qsfp.", *counter.controllerName__ref(), ".writeTotal"); tcData().setCounter(statName, *counter.writeTotal__ref()); statName = folly::to( "qsfp.", *counter.controllerName__ref(), ".writeFailed"); tcData().setCounter(statName, *counter.writeFailed__ref()); statName = folly::to( "qsfp.", *counter.controllerName__ref(), ".writeBytes"); tcData().setCounter(statName, *counter.writeBytes__ref()); } } /* * This is introduced mainly due to the mismatch of ODS reporting frequency * and the interval of us reading transceiver data. Some of the clear on read * information may be lost in this process and not being captured in the ODS * time series. This would bring difficulty in root cause link issues. Thus * here we provide a way of read and clear the data for the purpose of ODS * data reporting. */ void WedgeManager::getAndClearTransceiversSignalFlags( std::map& signalFlagsMap, std::unique_ptr> ids) { XLOG(INFO) << "getAndClearTransceiversSignalFlags, with ids: " << (ids->size() > 0 ? folly::join(",", *ids) : "None"); if (ids->empty()) { folly::gen::range(0, getNumQsfpModules()) | folly::gen::appendTo(*ids); } auto lockedTransceivers = transceivers_.rlock(); for (const auto& i : *ids) { if (!isValidTransceiver(i)) { // If the transceiver idx is not valid, // just skip and continue to the next. continue; } SignalFlags signalFlags; if (auto it = lockedTransceivers->find(TransceiverID(i)); it != lockedTransceivers->end()) { signalFlags = it->second->readAndClearCachedSignalFlags(); signalFlagsMap[i] = signalFlags; } } } void WedgeManager::getAndClearTransceiversMediaSignals( std::map>& mediaSignalsMap, std::unique_ptr> ids) { XLOG(INFO) << "getAndClearTransceiversMediaSignals, with ids: " << (ids->size() > 0 ? folly::join(",", *ids) : "None"); if (ids->empty()) { folly::gen::range(0, getNumQsfpModules()) | folly::gen::appendTo(*ids); } auto lockedTransceivers = transceivers_.rlock(); for (const auto& i : *ids) { if (!isValidTransceiver(i)) { // If the transceiver idx is not valid, // just skip and continue to the next. continue; } std::map mediaSignals; if (auto it = lockedTransceivers->find(TransceiverID(i)); it != lockedTransceivers->end()) { mediaSignals = it->second->readAndClearCachedMediaLaneSignals(); mediaSignalsMap[i] = mediaSignals; } } } /* * getPhyPortConfigValues * * This function takes the portId and port profile id. Based on these it looks * into the platform mapping for the given platform and extracts information * to fill in the phy port config. The output of this function is phy port * config structure which can be used later to send to External Phy functions */ std::optional WedgeManager::getPhyPortConfigValues( int32_t portId, cfg::PortProfileID portProfileId) { phy::PhyPortConfig phyPortConfig; // First verify if the platform mapping exist for this platform if (platformMapping_.get() == nullptr) { XLOG(INFO) << "Platform mapping is not present for this platform, exiting"; return std::nullopt; } // String value of profile id for printing in log std::string portProfileIdStr = apache::thrift::util::enumNameSafe(portProfileId); // Get port profile config for the given port profile id auto portProfileConfig = platformMapping_->getPortProfileConfig( PlatformPortProfileConfigMatcher(portProfileId, PortID(portId))); if (!portProfileConfig.has_value()) { XLOG(INFO) << "For port profile id " << portProfileIdStr << ", the supported profile not found in platform mapping"; return std::nullopt; } // Get the platform port entry for the given port id auto platformPortEntry = platformMapping_->getPlatformPorts().find(portId); if (platformPortEntry == platformMapping_->getPlatformPorts().end()) { XLOG(INFO) << "For port " << portId << ", the platform port not found in platform mapping"; return std::nullopt; } // From the above platform port entry, get the port config for the given port // profile id auto platformPortConfig = platformPortEntry->second.supportedProfiles_ref()->find(portProfileId); if (platformPortConfig == platformPortEntry->second.supportedProfiles_ref()->end()) { XLOG(INFO) << "For port id " << portId << " port profile id " << portProfileIdStr << ", the supported profile not found in platform mapping"; return std::nullopt; } // Get the line polarity swap map auto linePolaritySwapMap = utility::getXphyLinePolaritySwapMap( *platformPortEntry->second.get_mapping().pins_ref(), platformMapping_->getChips()); // Build the PhyPortConfig using platform port config pins list, polrity swap // map, port profile config phyPortConfig.config = phy::ExternalPhyConfig::fromConfigeratorTypes( *platformPortConfig->second.pins_ref(), linePolaritySwapMap); phyPortConfig.profile = phy::ExternalPhyProfileConfig::fromPortProfileConfig(*portProfileConfig); // Return true return phyPortConfig; } void WedgeManager::programXphyPort( int32_t portId, cfg::PortProfileID portProfileId) { if (phyManager_ == nullptr) { throw FbossError("Unable to program xphy port when PhyManager is not set"); } // Get the transceiver id for the given port id auto platformPortEntry = platformMapping_->getPlatformPorts().find(portId); if (platformPortEntry == platformMapping_->getPlatformPorts().end()) { throw FbossError( "Can't find the platform port entry in platform mapping for port:", portId); } auto tcvrID = utility::getTransceiverId( platformPortEntry->second, platformMapping_->getChips()); if (!tcvrID) { throw FbossError( "Can't find the transceiver id in platform mapping for port:", portId); } if (!isValidTransceiver(*tcvrID)) { throw FbossError("Port:", portId, " has invalid transceiver id:", *tcvrID); } std::optional itTcvr; auto lockedTransceivers = transceivers_.rlock(); if (auto it = lockedTransceivers->find(*tcvrID); it != lockedTransceivers->end()) { itTcvr = it->second->getTransceiverInfo(); } else { XLOG(WARNING) << "Port:" << portId << " doesn't have transceiver info for transceiver id:" << *tcvrID; } phyManager_->programOnePort(PortID(portId), portProfileId, itTcvr); } /* * getSwPortByPortName * * This function takes the port name string (eth2/1/1) and returns the software * port id (or the agent port id) for that */ std::optional WedgeManager::getSwPortByPortName( const std::string& portName) { auto portMapIt = portNameToSwPort_.find(portName); if (portMapIt != portNameToSwPort_.end()) { return portMapIt->second; } return std::nullopt; } bool WedgeManager::shouldInitializePimXphy() const { return FLAGS_init_pim_xphys; } bool WedgeManager::initExternalPhyMap() { if (!phyManager_) { // If there's no PhyManager for such platform, skip init xphy map return true; } // First call PhyManager::initExternalPhyMap() to create xphy map auto rb = phyManager_->initExternalPhyMap(); bool warmboot = canWarmboot(); // And then initialize the xphy for each pim if (shouldInitializePimXphy()) { std::vector> initPimTasks; std::chrono::steady_clock::time_point begin = std::chrono::steady_clock::now(); for (int pimIndex = 0; pimIndex < phyManager_->getNumOfSlot(); ++pimIndex) { auto pimID = PimID(pimIndex + phyManager_->getSystemContainer()->getPimStartNum()); XLOG(DBG1) << "Initializing PIM " << static_cast(pimID); if (auto* pimEventBase = phyManager_->getPimEventBase(pimID)) { initPimTasks.push_back( folly::via(pimEventBase) .thenValue([&, pimID, warmboot](auto&&) { phyManager_->initializeSlotPhys(pimID, warmboot); }) .thenError( folly::tag_t{}, [pimID](const std::exception& e) { XLOG(WARNING) << "Exception in initializeSlotPhys() for pim:" << static_cast(pimID) << ", " << folly::exceptionStr(e); })); } else { // If the pim EventBase doesn't exist, call such function directly phyManager_->initializeSlotPhys(pimID, warmboot); } } folly::collectAll(initPimTasks).wait(); XLOG(DBG2) << "Initialized all pims xphy took " << std::chrono::duration_cast( std::chrono::steady_clock::now() - begin) .count() << " seconds"; if (warmboot && qsfpServiceState_.find(kPhyStateKey) != qsfpServiceState_.items().end()) { phyManager_->restoreFromWarmbootState(qsfpServiceState_[kPhyStateKey]); } } else { XLOG(WARN) << "Skip intializing pim xphy"; } return rb; } void WedgeManager::programXphyPortPrbs( PortID portID, phy::Side side, const phy::PortPrbsState& prbs) { phyManager_->setPortPrbs(portID, side, prbs); } phy::PortPrbsState WedgeManager::getXphyPortPrbs( PortID portID, phy::Side side) { return phyManager_->getPortPrbs(portID, side); } void WedgeManager::updateAllXphyPortsStats() { if (!phyManager_) { // If there's no PhyManager for such platform, skip updating xphy stats return; } // For now, we only need to update xphy ports stats if we support // initializing the pim xphy so that if this flag is still disabled, which // means wedge_agent is still the service to program xphy, we don't need // to collect xphy stats in qsfp_service if (!shouldInitializePimXphy()) { return; } // Then we need to update all the programmed port xphy stats phyManager_->updateAllXphyPortsStats(); } std::vector WedgeManager::getMacsecCapablePorts() const { if (!phyManager_) { return {}; } return phyManager_->getPortsSupportingFeature( phy::ExternalPhy::Feature::MACSEC); } } // namespace fboss } // namespace facebook LilPidgey/NotOsu #include "MapParser.h" MapParser::MapParser( const char* osuDirectory ) { this->osuDirectory = osuDirectory; } MapParser::MapParser() { osuDirectory = "D:\osu\Songs"; } Beatmap* MapParser::Parse( const char* fullPath) { std::string absolutePath = fullPath; return Parse(absolutePath); } Beatmap* MapParser::Parse( const char* songName, const char* mapName ) { std::string absolutePath; absolutePath.append( osuDirectory ); absolutePath.append( "/" ); absolutePath.append( songName ); absolutePath.append( "/" ); absolutePath.append( mapName ); return Parse(absolutePath); } Beatmap* MapParser::Parse( std::string absolutePath ) { std::vector< char > buffer; ReadFile( &buffer, absolutePath.c_str( ) ); Beatmap* beatmap = new Beatmap( ); std::vector< char > sectionData; if ( GetSection( &buffer, §ionData, "[General]" ) ) { if ( !ParseGeneral( §ionData, beatmap->General ) ) std::cout << "Error parsing General section" << std::endl; } else std::cout << "Error reading General section" << std::endl; if ( GetSection( &buffer, §ionData, "[Editor]" ) ) { if ( !ParseEditor( §ionData, beatmap->Editor ) ) std::cout << "Error parsing Editor section" << std::endl; } else std::cout << "Error reading Editor section" << std::endl; if ( GetSection( &buffer, §ionData, "[Metadata]" ) ) { if ( !ParseMetadata( §ionData, beatmap->Metadata )) std::cout << "Error parsing Metadata section" << std::endl; } else std::cout << "Error reading Metadata section" << std::endl; if ( GetSection( &buffer, §ionData, "[Difficulty]" ) ) { if ( !ParseDifficulty( §ionData, beatmap->Difficulty ) ) std::cout << "Error parsing Difficulty section" << std::endl; } else std::cout << "Error reading Difficulty section" << std::endl; if ( GetSection( &buffer, §ionData, "[Events]" ) ) { if ( !ParseEvents( §ionData, beatmap->Events ) ) std::cout << "Error parsing Events section" << std::endl; } else std::cout << "Error reading Events section" << std::endl; if ( GetSection( &buffer, §ionData, "[TimingPoints]" ) ) { if ( !ParseTimingPoints( §ionData, beatmap->TimingPoints ) ) std::cout << "Error parsing TimingPoints section" << std::endl; } else std::cout << "Error reading TimingPoints section" << std::endl; if ( GetSection( &buffer, §ionData, "[Colours]" ) ) { if ( !ParseColours( §ionData, beatmap->Colours ) ) std::cout << "Error parsing Colours section" << std::endl; } else std::cout << "Error reading Colours section" << std::endl; if ( GetSection( &buffer, §ionData, "[HitObjects]" ) ) { if ( !ParseHitObjects( §ionData, beatmap->HitObjects) ) std::cout << "Error parsing HitObjects section" << std::endl; } else std::cout << "Error reading HitObjects section" << std::endl; return beatmap; } bool MapParser::ReadFile( std::vector< char >* buffer, const char* path ) { std::ifstream* fileStream = new std::ifstream( path ); fileStream->seekg( 0, std::ios::end ); const size_t fileSize = fileStream->tellg( ); fileStream->seekg( 0, std::ios::beg ); if ( fileSize > 0 ) { buffer->resize( fileSize ); fileStream->read( &buffer->at( 0 ), fileSize ); } return true; } bool MapParser::GetSection( std::vector< char >* mapData, std::vector< char >* sectionData, std::string name ) { int bytesRead = 0; sectionData->clear( ); while ( bytesRead != mapData->size( ) - 1 ) { for ( auto character : name ) { if ( mapData->at( bytesRead ) == character ) bytesRead++; else goto completed; } //Section Found bytesRead ++; while ( mapData->at( bytesRead ) != '[' && bytesRead != mapData->size( ) - 1 ) { sectionData->push_back( mapData->at( bytesRead ) ); bytesRead++; } mapData->erase( mapData->begin( ), mapData->begin( ) + bytesRead ); return true; completed: bytesRead++; } return false; } template bool MapParser::ParseKvp( std::vector* sectionData, std::string kvpName, void* outValue, int extraValuePadding = 2 ) { int bytesRead = 0; std::vector valueData; while ( bytesRead != sectionData->size( ) - 1 ) { for ( auto character : kvpName ) { if ( sectionData->at( bytesRead ) == character ) bytesRead++; else goto completed; } //Found section bytesRead += extraValuePadding; while ( sectionData->at( bytesRead ) != 0x0a && bytesRead != sectionData->size( ) - 1 ) { valueData.push_back( sectionData->at( bytesRead ) ); bytesRead++; } if(std::is_same::value || std::is_same::value) { *static_cast< int* >( outValue ) = std::stoi(valueData.data( )); } else if(std::is_same::value || std::is_same::value) { static_cast< std::string* >( outValue )->append( valueData.data( ) ); } else if(std::is_same::value) { *static_cast< float* >( outValue ) = std::stof( valueData.data( )); } valueData.clear( ); sectionData->erase( sectionData->begin( ), sectionData->begin( ) + bytesRead ); return true; completed: bytesRead++; } return false; } bool MapParser::ParseNextHitObject( std::vector< char >* sectionData, HitObject*& hitObject ) const { if(sectionData->at( 0 ) == 0) return false; std::vector hitObjectData; int bytesRead = 0; hitObject = new HitObject(); while(sectionData->at( bytesRead ) != 0x0a && bytesRead != sectionData->size( ) - 1) { hitObjectData.push_back( sectionData->at( bytesRead ) ); bytesRead++; } sectionData->erase( sectionData->begin( ), sectionData->begin( ) + bytesRead + 1 ); auto something = std::string ((const char*)hitObjectData.data( )); something.resize(hitObjectData.size()); std::vector params = Split(something, "," ); hitObject->position.x = std::stoi( params[0] ); hitObject->position.y = std::stoi( params[1] ); hitObject->time = std::stoll( params[2] ); hitObject->type = static_cast< HitObjectType >( std::stoll( params[3] ) ); hitObject->hitSound = static_cast< HitObjectSound >( static_cast< HitObjectType >( std::stoi( params[4] ) ) ); if((hitObject->type & HIT_CIRCLE) != 0) { } if ((hitObject->type & SLIDER) != 0 ) { SliderHitObject* sliderHitObject = new SliderHitObject(); hitObject->objectParams = static_cast< void* >( sliderHitObject ); std::vector curves = Split( params[5], "|" ); sliderHitObject->curveType = curves[0][0] ; curves.erase (curves.begin()); for ( auto point : curves ) { std::vector xyPoint = Split( point, ":" ); sliderHitObject->curvePoints.push_back( BeatmapPoint(std::stoi( xyPoint[0] ) , std::stoi( xyPoint[1] ) ) ); } sliderHitObject->slides = std::stoi( params[ 6 ] ); sliderHitObject->length = std::stof( params[ 7 ] ); if(params.size( ) >= 9 ) { std::vector edgeSounds = Split( params[8], "|" ); for ( auto sound : edgeSounds ) { sliderHitObject->edgeSounds.push_back( std::stoi( sound ) ); } if(params.size( ) == 10) { std::vector edgeSets = Split( params[9], "|" ); for ( auto set : edgeSets ) { sliderHitObject->edgeSounds.push_back( std::stoi( set ) ); } } } } if ((hitObject->type & SPINNER) != 0 ) { SpinnerHitObject* spinnerHitObject = new SpinnerHitObject(); hitObject->objectParams = static_cast< void* >( spinnerHitObject ); spinnerHitObject->endTime = std::stoi( params[ 5 ] ); //Hit sample } if ((hitObject->type & OSU_MANIA_HOLD) != 0 ) { } return true; } bool MapParser::ParseNextTimingPoint( std::vector* sectionData, TimingPoint*& timingPoint) const { if(sectionData->at( 0 ) == 0 || sectionData->at( 0 ) == 0x0a) return false; std::vector timingPointData; int bytesRead = 0; timingPoint = new TimingPoint; while(sectionData->at( bytesRead ) != 0x0a && bytesRead != sectionData->size( ) - 1) { timingPointData.push_back( sectionData->at( bytesRead ) ); bytesRead++; } sectionData->erase( sectionData->begin( ), sectionData->begin( ) + bytesRead + 1 ); std::vector params = Split( (char*)timingPointData.data( ), "," ); timingPoint->time = std::stoll( params[0] ); timingPoint->beatLength = std::stod( params[1] ); timingPoint->meter = std::stoll( params[2] ); timingPoint->sampleSet = std::stoll( params[3] ); timingPoint->sampleIndex = std::stoll( params[4] ); timingPoint->volume = std::stoll( params[5] ); timingPoint->uninherited = std::stoll( params[6] ); timingPoint->effects = std::stoll( params[7] ); return true; } bool MapParser::ParseGeneral( std::vector< char >* sectionData, General* generalSection ) { //I dont care enough to handle the true/falses sorry /shrug ParseKvp( sectionData, "AudioFilename", &generalSection->audioFileName ); ParseKvp( sectionData, "AudioLeadIn", &generalSection->audioLeadIn ); ParseKvp( sectionData, "AudioHash", &generalSection->audioHash ); ParseKvp( sectionData, "PreviewTime", &generalSection->previewTime ); ParseKvp( sectionData, "Countdown", &generalSection->countdown ); ParseKvp( sectionData, "SampleSet", &generalSection->sampleSet ); ParseKvp( sectionData, "StackLeniency", &generalSection->stackLeniency ); ParseKvp( sectionData, "Mode", &generalSection->mode ); ParseKvp( sectionData, "LetterboxInBreaks", &generalSection->letterboxInBreaks ); ParseKvp( sectionData, "StoryFireInFront", &generalSection->storyFireInFront ); ParseKvp( sectionData, "UseSkinSprites", &generalSection->useSkinSprites ); ParseKvp( sectionData, "AlwaysShowPlayfield", &generalSection->alwaysShowPlayfield ); ParseKvp( sectionData, "OverlayPosition", &generalSection->overlayPosition ); ParseKvp( sectionData, "SkinPreference", &generalSection->skinPreference ); ParseKvp( sectionData, "EpilepsyWarning", &generalSection->epilepsyWarning ); ParseKvp( sectionData, "CountdownOffset", &generalSection->countdownOffset ); ParseKvp( sectionData, "SpecialStyle", &generalSection->specialStyle ); ParseKvp( sectionData, "WidescreenStoryboard", &generalSection->widescreenStoryboard ); ParseKvp( sectionData, "SamplesMatchPlaybackRate", &generalSection->samplesMatchPlaybackRate ); return true; } bool MapParser::ParseEditor( std::vector< char >* sectionData, Editor* generalSection ) { return true; } bool MapParser::ParseMetadata( std::vector< char >* sectionData, Metadata* generalSection ) { return true; } bool MapParser::ParseDifficulty( std::vector< char >* sectionData, Difficulty* difficultySection ) { ParseKvp( sectionData, "HPDrainRate", &difficultySection->hpDrainRate, 1 ); ParseKvp( sectionData, "CircleSize", &difficultySection->circleSize, 1 ); ParseKvp( sectionData, "OverallDifficulty", &difficultySection->overallDifficulty, 1 ); ParseKvp( sectionData, "ApproachRate", &difficultySection->approachRate, 1 ); ParseKvp( sectionData, "SliderMultiplier", &difficultySection->sliderMultiplier, 1 ); ParseKvp( sectionData, "SliderTickRate", &difficultySection->sliderTickRate, 1 ); return true; } bool MapParser::ParseEvents( std::vector< char >* sectionData, Events* generalSection ) { return true; } bool MapParser::ParseTimingPoints( std::vector< char >* sectionData, std::vector& timingPoints ) { TimingPoint* timingPoint; while ( ParseNextTimingPoint( sectionData, timingPoint ) ) timingPoints.push_back( timingPoint ); return true; } bool MapParser::ParseColours( std::vector< char >* sectionData, Colours* generalSection ) { return true; } bool MapParser::ParseHitObjects( std::vector< char >* sectionData, std::vector& hitObjects ) { HitObject* object; while( ParseNextHitObject ( sectionData, object ) ) hitObjects.push_back( object ); return true; }#include "utils.h" #include std::string Utils::floatToString(const float value) { std::stringstream out; out << value; return out.str(); } std::string Utils::intToString(const int value) { std::stringstream out; out << value; return out.str(); } #ifndef GRID_HXX #define GRID_HXX #include #include #include #include "matrix.hxx" class BaseGrid { protected: BaseGrid(std::size_t rows, std::size_t cols): h(rows), w(cols) {} public: inline std::size_t rows() const { return h; } inline std::size_t cols() const { return w; } inline bool validCoords(std::size_t row, std::size_t col) const { return row < h && col < w; } static const int DELTAS[8][2]; private: std::size_t h; std::size_t w; }; template class SimpleGrid : public BaseGrid { public: explicit SimpleGrid(const Matrix &m): BaseGrid(m.getMatrixHeight(), m.getMatrixWidth()), m(m) {} inline bool isDense() const { return true; } inline int getColor(std::size_t row, std::size_t col) const { return m.getNumber(row, col); } template inline void forEachNeighbor(std::size_t row, std::size_t col, Action &action) const { for (int i = 0; i < 8; ++i) tryTouchNeighbor(row, col, action, i); } template inline void forEachUpperNeighbor(std::size_t row, std::size_t col, Action &action) const { for (int i = 0; i < 4; ++i) tryTouchNeighbor(row, col, action, i); } inline bool canGo(std::size_t row, std::size_t col, int dir) const { std::size_t nr = row + DELTAS[dir][0], nc = col + DELTAS[dir][1]; return validCoords(nr, nc) && getColor(nr, nc); } protected: template inline void tryTouchNeighbor(std::size_t row, std::size_t col, Action &action, int dir) const { if (canGo(row, col, dir)) { std::size_t nr = row + DELTAS[dir][0], nc = col + DELTAS[dir][1]; action(row, col, nr, nc); } } private: const Matrix &m; }; class Base2x2Grid { public: static const int DELTA_MASKS[8][2]; }; template class Viewing2x2Grid : public BaseGrid, public Base2x2Grid { public: explicit Viewing2x2Grid(const Matrix &bitmap): BaseGrid( (bitmap.getMatrixHeight() + 1) / 2, (bitmap.getMatrixWidth() + 1) / 2), bitmap(bitmap), oldRows(bitmap.getMatrixHeight()), oldCols(bitmap.getMatrixWidth()) { } inline bool isDense() const { return false; } inline int getColor(std::size_t row, std::size_t col) const { std::size_t i = row * 2, j = col * 2; return bitmap.getNumber(i, j) | (j+1 < oldCols ? bitmap.getNumber(i, j+1) << 1 : 0) | (i+1 < oldRows ? bitmap.getNumber(i+1, j) << 2 : 0) | (i+1 < oldRows && j+1 < oldCols ? bitmap.getNumber(i + 1, j + 1) << 3 : 0); } template inline void forEachNeighbor(std::size_t row, std::size_t col, Action &action) const { for (int i = 0; i < 8; ++i) tryTouchNeighbor(row, col, action, i); } template inline void forEachUpperNeighbor(std::size_t row, std::size_t col, Action &action) const { for (int i = 0; i < 4; ++i) tryTouchNeighbor(row, col, action, i); } inline bool canGo(std::size_t row, std::size_t col, int dir) const { std::size_t nr = row + DELTAS[dir][0], nc = col + DELTAS[dir][1]; return (getColor(row, col) & DELTA_MASKS[dir][0]) && validCoords(nr, nc) && (getColor(nr, nc) & DELTA_MASKS[dir][1]); } protected: template inline void tryTouchNeighbor(std::size_t row, std::size_t col, Action &action, int dir) const { if (canGo(row, col, dir)) { std::size_t nr = row + DELTAS[dir][0], nc = col + DELTAS[dir][1]; action(row, col, nr, nc); } } private: const Matrix &bitmap; std::size_t oldRows, oldCols; }; template class Compressing2x2Grid : public BaseGrid, public Base2x2Grid { public: explicit Compressing2x2Grid(const GivenMatrix &bitmap): BaseGrid( (bitmap.getMatrixHeight() + 1) / 2, (bitmap.getMatrixWidth() + 1) / 2), m(compressBitmap(bitmap)) {} inline std::size_t rows() const { return m.getMatrixHeight(); } inline std::size_t cols() const { return m.getMatrixWidth(); } inline bool isDense() const { return false; } inline int getColor(std::size_t row, std::size_t col) const { return m.getNumber(row, col); } inline bool validCoords(std::size_t row, std::size_t col) const { return row >= 0 && col >= 0 && row < rows() && col < cols(/*row*/); } template inline void forEachNeighbor(std::size_t row, std::size_t col, Action &action) const { for (int i = 0; i < 8; ++i) tryTouchNeighbor(row, col, action, i); } template inline void forEachUpperNeighbor(std::size_t row, std::size_t col, Action &action) const { for (int i = 0; i < 4; ++i) tryTouchNeighbor(row, col, action, i); } inline bool canGo(std::size_t row, std::size_t col, int dir) const { std::size_t nr = row + DELTAS[dir][0], nc = col + DELTAS[dir][1]; return (getColor(row, col) & DELTA_MASKS[dir][0]) && validCoords(nr, nc) && (getColor(nr, nc) & DELTA_MASKS[dir][1]); } static ArrayMatrix compressBitmap(const GivenMatrix &bitmap) { std::size_t oldRows = bitmap.getMatrixHeight(); std::size_t oldCols = bitmap.getMatrixWidth(); std::size_t newRows = (oldRows + 1) / 2; std::size_t newCols = (oldCols + 1) / 2; std::unique_ptr compressedOwned{new char[newRows * newCols]}; char* compressIter = compressedOwned.get(); for (std::size_t i = 0; i < oldRows; i += 2) { for (std::size_t j = 0; j < oldCols; j += 2) *(compressIter++) = bitmap.getNumber(i, j) | (j+1 < oldCols ? bitmap.getNumber(i, j+1) << 1 : 0) | (i+1 < oldRows ? bitmap.getNumber(i+1, j) << 2 : 0) | (i+1 < oldRows && j+1 < oldCols ? bitmap.getNumber(i + 1, j + 1) << 3 : 0); } return ArrayMatrix(newRows, newCols, std::move(compressedOwned)); } protected: template inline void tryTouchNeighbor(std::size_t row, std::size_t col, Action &action, int dir) const { if (canGo(row, col, dir)) { std::size_t nr = row + DELTAS[dir][0], nc = col + DELTAS[dir][1]; action(row, col, nr, nc); } } private: const ArrayMatrix m; }; #endif perfectrecall/aws-sdk-cpp /** * 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 VoiceID { namespace Model { SpeakerSummary::SpeakerSummary() : m_createdAtHasBeenSet(false), m_customerSpeakerIdHasBeenSet(false), m_domainIdHasBeenSet(false), m_generatedSpeakerIdHasBeenSet(false), m_status(SpeakerStatus::NOT_SET), m_statusHasBeenSet(false), m_updatedAtHasBeenSet(false) { } SpeakerSummary::SpeakerSummary(JsonView jsonValue) : m_createdAtHasBeenSet(false), m_customerSpeakerIdHasBeenSet(false), m_domainIdHasBeenSet(false), m_generatedSpeakerIdHasBeenSet(false), m_status(SpeakerStatus::NOT_SET), m_statusHasBeenSet(false), m_updatedAtHasBeenSet(false) { *this = jsonValue; } SpeakerSummary& SpeakerSummary::operator =(JsonView jsonValue) { if(jsonValue.ValueExists("CreatedAt")) { m_createdAt = jsonValue.GetDouble("CreatedAt"); m_createdAtHasBeenSet = true; } if(jsonValue.ValueExists("CustomerSpeakerId")) { m_customerSpeakerId = jsonValue.GetString("CustomerSpeakerId"); m_customerSpeakerIdHasBeenSet = true; } if(jsonValue.ValueExists("DomainId")) { m_domainId = jsonValue.GetString("DomainId"); m_domainIdHasBeenSet = true; } if(jsonValue.ValueExists("GeneratedSpeakerId")) { m_generatedSpeakerId = jsonValue.GetString("GeneratedSpeakerId"); m_generatedSpeakerIdHasBeenSet = true; } if(jsonValue.ValueExists("Status")) { m_status = SpeakerStatusMapper::GetSpeakerStatusForName(jsonValue.GetString("Status")); m_statusHasBeenSet = true; } if(jsonValue.ValueExists("UpdatedAt")) { m_updatedAt = jsonValue.GetDouble("UpdatedAt"); m_updatedAtHasBeenSet = true; } return *this; } JsonValue SpeakerSummary::Jsonize() const { JsonValue payload; if(m_createdAtHasBeenSet) { payload.WithDouble("CreatedAt", m_createdAt.SecondsWithMSPrecision()); } if(m_customerSpeakerIdHasBeenSet) { payload.WithString("CustomerSpeakerId", m_customerSpeakerId); } if(m_domainIdHasBeenSet) { payload.WithString("DomainId", m_domainId); } if(m_generatedSpeakerIdHasBeenSet) { payload.WithString("GeneratedSpeakerId", m_generatedSpeakerId); } if(m_statusHasBeenSet) { payload.WithString("Status", SpeakerStatusMapper::GetNameForSpeakerStatus(m_status)); } if(m_updatedAtHasBeenSet) { payload.WithDouble("UpdatedAt", m_updatedAt.SecondsWithMSPrecision()); } return payload; } } // namespace Model } // namespace VoiceID } // namespace Aws flightlib/src/common/logger.cpp100-1000 #include "flightlib/common/logger.hpp" namespace flightlib { Logger::Logger(const std::string& name, const bool color) : sink_(std::cout.rdbuf()), colored_(color) { name_ = "[" + name + "]"; if (name_.size() < NAME_PADDING) name_ = name_ + std::string(NAME_PADDING - name_.size(), ' '); else name_ = name_ + " "; sink_.precision(DEFAULT_PRECISION); } Logger::Logger(const std::string& name, const std::string& filename) : Logger(name, false) { if (!filename.empty()) { std::filebuf* fbuf = new std::filebuf; if (fbuf->open(filename, std::ios::out)) sink_.rdbuf(fbuf); else warn("Could not open file %s. Logging to console!", filename); } sink_.precision(DEFAULT_PRECISION); } Logger::~Logger() {} inline std::streamsize Logger::precision(const std::streamsize n) { return sink_.precision(n); } inline void Logger::scientific(const bool on) { if (on) sink_ << std::scientific; else sink_ << std::fixed; } void Logger::info(const std::string& message) const { if (colored_) sink_ << name_ << message << std::endl; else sink_ << name_ << INFO << message << std::endl; } void Logger::warn(const std::string& message) const { if (colored_) sink_ << YELLOW << name_ << message << RESET << std::endl; else sink_ << name_ << WARN << message << std::endl; } void Logger::error(const std::string& message) const { if (colored_) sink_ << RED << name_ << message << RESET << std::endl; else sink_ << name_ << ERROR << message << std::endl; } } // namespace flightlibsrc/virtualization/tests/virtio_sound_tests.cc1-10 // Copyright 2022 The Fuchsia 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 #include #include #include #include #include #include #include #include #include "lib/sys/cpp/testing/enclosing_environment.h" #include "src/lib/files/path.h" #include "src/media/audio/lib/format/audio_buffer.h" #include "src/media/audio/lib/format/format.h" #include "src/media/audio/lib/format/traits.h" #include "src/media/audio/lib/test/hermetic_audio_environment.h" #include "src/media/audio/lib/test/hermetic_audio_test.h" #include "src/media/audio/lib/test/virtual_device.h" #include "src/virtualization/tests/enclosed_guest.h" namespace { using ::fuchsia::media::AudioSampleFormat; using ::media::audio::AudioBuffer; using ::media::audio::AudioBufferSlice; using ::media::audio::Format; using ::media::audio::SampleFormatTraits; using ::media::audio::test::HermeticAudioEnvironment; using ::media::audio::test::HermeticAudioTest; using ::media::audio::test::VirtualOutput; constexpr int32_t kOutputFrameRate = 48000; constexpr int32_t kStereoChannelCount = 2; constexpr AudioSampleFormat kSampleFormat = AudioSampleFormat::FLOAT; constexpr audio_stream_unique_id_t kOutputId = AUDIO_STREAM_UNIQUE_ID_BUILTIN_SPEAKERS; constexpr char kEnvironmentLabel[] = "virtio-sound-guest-test"; // TODO(fxbug.dev/87646): Consider creating a `virtio_audio_test_util` that directly communicates // with ALSA instead to have better control over the output buffer. constexpr char kAplayBinPath[] = "/tmp/vm_extras/aplay"; // TODO(fxbug.dev/87646): Consider creating a `virtio_audio_test_util` that directly generates this // audio files on-the-fly. constexpr char kTestFilePath[] = "/tmp/extras/stereo_ramp_48khz_16bit.wav"; constexpr int32_t kRampFrameCount = 65536; constexpr int32_t kZeroPaddingFrameCount = 1024; template class VirtioSoundGuestTest : public HermeticAudioTest { public: static void SetUpTestSuite() { // Set `HermeticAudioEnvironment` to install guest services. HermeticAudioEnvironment::Options options = { .install_additional_services_fn = [&](sys::testing::EnvironmentServices& services) -> zx_status_t { return GetEnclosedGuest().InstallV1(services); }, .label = kEnvironmentLabel}; HermeticAudioTest::SetTestSuiteEnvironmentOptions(std::move(options)); } static GuestType& GetEnclosedGuest() { FX_CHECK(enclosed_guest_.has_value()); return enclosed_guest_.value(); } protected: void SetUp() override { enclosed_guest_.emplace(loop()); HermeticAudioTest::SetUp(); const auto format = Format::Create(kStereoChannelCount, kOutputFrameRate).take_value(); // Add some padding to ensure that there is enough headroom in the ring buffer. output_ = CreateOutput(kOutputId, format, kRampFrameCount + kZeroPaddingFrameCount + 10 * kOutputFrameRate); ASSERT_EQ(GetEnclosedGuest().LaunchV1(environment()->GetEnvironment(), kEnvironmentLabel, zx::time::infinite()), ZX_OK) << "Failed to launch guest"; } void TearDown() override { EXPECT_EQ(GetEnclosedGuest().Stop(zx::time::infinite()), ZX_OK); enclosed_guest_.reset(); if constexpr (kEnableAllOverflowAndUnderflowChecksInRealtimeTests) { ExpectNoOverflowsOrUnderflows(); } HermeticAudioTest::TearDown(); } zx_status_t Execute(const std::vector& argv) { return GetEnclosedGuest().Execute(argv, {}, zx::time::infinite(), nullptr, nullptr); } std::optional GetFirstNonSilentFrame(const AudioBuffer& buffer) const { for (int64_t frame = 0; frame < buffer.NumFrames(); ++frame) { if (buffer.SampleAt(frame, 0) != SampleFormatTraits::kSilentValue) { return frame; } } return std::nullopt; } AudioBuffer GetOutputRingBuffer() { return output_->SnapshotRingBuffer(); } bool OutputHasUnderflows() { return DeviceHasUnderflows(output_); } private: static inline std::optional enclosed_guest_; VirtualOutput* output_ = nullptr; }; class TerminaEnclosedGuestV1 : public TerminaEnclosedGuest { public: explicit TerminaEnclosedGuestV1(async::Loop& loop) : TerminaEnclosedGuest(loop) {} bool UsingCFv1() const override { return true; } }; // We only support `TerminaEnclosedGuest` since the tests require `virtio-sound` and `alsa-lib`. TYPED_TEST_SUITE(VirtioSoundGuestTest, ::testing::Types, GuestTestNameGenerator); TYPED_TEST(VirtioSoundGuestTest, OutputFidelity) { // The input audio file consists of a stereo linear ramp that covers the entire 16-bit range of // values with opposing direction in each channel. It is calculated for each frame as follows: // `buffer[frame][0] = 0x7FFF - frame` // `buffer[frame][1] = -0x8000 + frame` // Note that the file consists of `kZeroPaddingFrameCount` frames of zeros at the beginning in // order to compensate for the initial gain ramp, which is then followed by the `kRampFrameCount` // ramp frames as described above. ASSERT_EQ(this->Execute({kAplayBinPath, kTestFilePath}), ZX_OK); const auto ring_buffer = this->GetOutputRingBuffer(); ASSERT_EQ(ring_buffer.format().channels(), kStereoChannelCount); // TODO(fxbug.dev/80003): Remove workarounds when underflow conditions are fixed. if (this->OutputHasUnderflows()) { GTEST_SKIP() << "Skipping fidelity checks due to underflows"; __builtin_unreachable(); } const std::optional start_frame = this->GetFirstNonSilentFrame(ring_buffer); ASSERT_TRUE(start_frame.has_value()) << "Could not find non-silent frame"; FX_LOGS(INFO) << "First non-silent frame: " << *start_frame; const int64_t end_frame = *start_frame + kRampFrameCount; ASSERT_LE(end_frame, ring_buffer.NumFrames()) << "Not enough frames in ring buffer"; const auto buffer_slice = AudioBufferSlice(&ring_buffer, *start_frame, end_frame); // TODO(fxbug.dev/95106): Temporarily limit the end frame to `24000 - kZeroPaddingFrameCount` // until the buffer repetition issue is resolved (to be replaced by `kRampFrameCount`). for (int32_t frame = 0; frame < 24000 - kZeroPaddingFrameCount; ++frame) { EXPECT_FLOAT_EQ(buffer_slice.SampleAt(frame, 0), static_cast(0x7FFF - frame) / static_cast(kRampFrameCount / 2)) << "at (" << frame << ", 0)"; EXPECT_FLOAT_EQ(buffer_slice.SampleAt(frame, 1), static_cast(-0x8000 + frame) / static_cast(kRampFrameCount / 2)) << "at (" << frame << ", 1)"; } } } // namespace 0 #pragma once #include #define DMP_ETH_TYPE 0x8ae namespace Tins { class DMP : public PDU { public: /* * Unique protocol identifier. For user-defined PDUs, you **must** * use values greater or equal to PDU::USER_DEFINED_PDU; */ static const PDU::PDUType pdu_flag = PDU::USER_DEFINED_PDU; /* * Constructor from buffer. This constructor will be called while * sniffing packets, whenever a PDU of this type is found. * * The "data" parameter points to a buffer of length "sz". */ DMP(const uint8_t* data, uint32_t sz) : buffer(data, data + sz) { } DMP() {} /* * Clones the PDU. This method is used when copying PDUs. */ DMP *clone() const { return new DMP(*this); } /* * Retrieves the size of this PDU. */ uint32_t header_size() const { return buffer.size(); } /* * This method must return pdu_flag. */ PDUType pdu_type() const { return pdu_flag; } /* * Serializes the PDU. The serialization output should be written * to the buffer pointed to by "data", which is of size "sz". The * "sz" parameter will be equal to the value returned by * DummyPDU::header_size. * * The third parameter is a pointer to the parent PDU. You shouldn't * normally need to use this. */ void write_serialization(uint8_t *data, uint32_t sz, const PDU *parent) { std::copy(buffer.begin(), buffer.end(), data); } // This is just a getter to retrieve the buffer member. const std::vector &get_buffer() const { return buffer; } private: std::vector buffer; }; }#include #include "json_spirit.h" /** * @brief Loads a simple JSON string and verify */ TEST ( json_spirit, load_simple ) { const std::string value = "{ \"house_number\" : 42, \"road\" : \"East Street\", \"town\" : \"Newtown\" }"; json_spirit::Value jsonv; { const bool ret = json_spirit::read ( value, jsonv ); ASSERT_TRUE ( ret ); } ASSERT_EQ ( jsonv.type(), json_spirit::obj_type ); const json_spirit::Object &top = jsonv.get_obj(); ASSERT_EQ ( top.size(), 3u ); ASSERT_EQ ( top.at ( 0 ).name_, "house_number" ); ASSERT_EQ ( top.at ( 0 ).value_, 42 ); ASSERT_EQ ( top.at ( 1 ).name_, "road" ); ASSERT_EQ ( top.at ( 1 ).value_, "East Street" ); ASSERT_EQ ( top.at ( 2 ).name_, "town" ); ASSERT_EQ ( top.at ( 2 ).value_, "Newtown" ); } /** * @brief Generates and then loads a simple JSON string to verify generated string */ TEST ( json_spirit, generate_simple ) { json_spirit::Object obj; obj.push_back ( json_spirit::Pair ( "house_number", 42 ) ); obj.push_back ( json_spirit::Pair ( "road", "East \"Street\"" ) ); obj.push_back ( json_spirit::Pair ( "town", "Newtown" ) ); //std::string out = json_spirit::write(obj, json_spirit::raw_utf8); const std::string output = json_spirit::write_formatted ( obj ); ASSERT_GT ( output.size(), 0u ); json_spirit::Value jsonv; { const bool ret = json_spirit::read ( output, jsonv ); ASSERT_TRUE ( ret ); } ASSERT_EQ ( jsonv.type(), json_spirit::obj_type ); const json_spirit::Object &top = jsonv.get_obj(); ASSERT_EQ ( top.size(), 3u ); ASSERT_EQ ( top.at ( 0 ).name_, "house_number" ); ASSERT_EQ ( top.at ( 0 ).value_, 42 ); ASSERT_EQ ( top.at ( 1 ).name_, "road" ); ASSERT_EQ ( top.at ( 1 ).value_, "East \"Street\"" ); ASSERT_EQ ( top.at ( 2 ).name_, "town" ); ASSERT_EQ ( top.at ( 2 ).value_, "Newtown" ); } /** * @brief Loads a invalid JSON string using both read methods */ TEST ( json_spirit, load_invalid ) { const std::string value = "{ \"ho\"use_num\"ber\" : 42, \"road\" : \"East Street\", \"town\" : \"Newtown\" }"; json_spirit::Value jsonv; { const bool ret = json_spirit::read ( value, jsonv ); ASSERT_FALSE ( ret ); } { try { json_spirit::read_or_throw ( value, jsonv ); //should never reach here ASSERT_TRUE ( false ); } catch ( json_spirit::Error_position json_err ) { ASSERT_EQ ( json_err.line_, 1u ); } catch ( ... ) { //should never reach here ASSERT_TRUE ( false ); } } } thenomuser/csso-src //========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // //=============================================================================// #include "cbase.h" #include "weapon_csbasegun.h" #if defined( CLIENT_DLL ) #define CWeaponGalilAR C_WeaponGalilAR #include "c_cs_player.h" #else #include "cs_player.h" #endif class CWeaponGalilAR : public CWeaponCSBaseGun { public: DECLARE_CLASS( CWeaponGalilAR, CWeaponCSBaseGun ); DECLARE_NETWORKCLASS(); DECLARE_PREDICTABLE(); CWeaponGalilAR(); virtual void Spawn(); virtual void PrimaryAttack(); virtual CSWeaponID GetCSWeaponID( void ) const { return WEAPON_GALILAR; } private: CWeaponGalilAR( const CWeaponGalilAR & ); void GalilFire( float flSpread ); }; IMPLEMENT_NETWORKCLASS_ALIASED( WeaponGalilAR, DT_WeaponGalilAR ) BEGIN_NETWORK_TABLE( CWeaponGalilAR, DT_WeaponGalilAR ) END_NETWORK_TABLE() BEGIN_PREDICTION_DATA( CWeaponGalilAR ) END_PREDICTION_DATA() LINK_ENTITY_TO_CLASS( weapon_galilar, CWeaponGalilAR ); #ifdef GAME_DLL LINK_ENTITY_TO_CLASS( weapon_galil, CWeaponGalilAR ); // for backwards compatibility #endif PRECACHE_WEAPON_REGISTER( weapon_galilar ); CWeaponGalilAR::CWeaponGalilAR() { } void CWeaponGalilAR::PrimaryAttack() { CCSPlayer *pPlayer = GetPlayerOwner(); if ( !pPlayer ) return; // don't fire underwater if (pPlayer->GetWaterLevel() == 3) { PlayEmptySound( ); m_flNextPrimaryAttack = gpGlobals->curtime + 0.15; return; } if ( !CSBaseGunFire( GetCSWpnData().m_flCycleTime, Primary_Mode ) ) return; // CSBaseGunFire can kill us, forcing us to drop our weapon, if we shoot something that explodes pPlayer = GetPlayerOwner(); if ( !pPlayer ) return; if (pPlayer->GetAbsVelocity().Length2D() > 5) pPlayer->KickBack (1.0, 0.45, 0.28, 0.045, 3.75, 3, 7); else if ( !FBitSet( pPlayer->GetFlags(), FL_ONGROUND ) ) pPlayer->KickBack (1.2, 0.5, 0.23, 0.15, 5.5, 3.5, 6); else if ( FBitSet( pPlayer->GetFlags(), FL_DUCKING ) ) pPlayer->KickBack (0.6, 0.3, 0.2, 0.0125, 3.25, 2, 7); else pPlayer->KickBack (0.65, 0.35, 0.25, 0.015, 3.5, 2.25, 7); } void CWeaponGalilAR::Spawn() { SetClassname( "weapon_galilar" ); // for backwards compatibility BaseClass::Spawn(); }1000+ // This file is part of CAF, the C++ Actor Framework. See the file LICENSE in // the main distribution directory for license terms and copyright or visit // https://github.com/actor-framework/actor-framework/blob/master/LICENSE. #pragma once #include #include "caf/actor.hpp" #include "caf/detail/type_list.hpp" #include "caf/fwd.hpp" namespace caf::detail { template struct mtl_util; template struct mtl_util(Ts...)> { template static bool send(Self& self, const actor& dst, Adapter& adapter, Inspector& f, Ts... xs) { f.revert(); if (adapter.read(f, xs...)) { self->send(dst, std::move(xs)...); return true; } else { return false; } } template static bool send(Self& self, const actor& dst, Adapter& adapter, Inspector& f) { return send(self, dst, adapter, f, Ts{}...); } template static bool request(Self& self, const actor& dst, Timeout timeout, Adapter& adapter, Inspector& f, OnResult& on_result, OnError& on_error, Ts... xs) { f.revert(); if (adapter.read(f, xs...)) { if constexpr (std::is_same, type_list>::value) self->request(dst, timeout, std::move(xs)...) .then([f{std::move(on_result)}]() mutable { f(); }, std::move(on_error)); else self->request(dst, timeout, std::move(xs)...) .then([f{std::move(on_result)}](Rs&... res) mutable { f(res...); }, std::move(on_error)); return true; } else { return false; } } template static bool request(Self& self, const actor& dst, Timeout timeout, Adapter& adapter, Inspector& f, OnResult& on_result, OnError& on_error) { return request(self, dst, timeout, adapter, f, on_result, on_error, Ts{}...); } }; } // namespace caf::detail // ARKSurvivalEvolved (329.9) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "ARKSurvivalEvolved_Buff_Stunned_TekPistol_parameters.hpp" namespace sdk { //--------------------------------------------------------------------------- //Functions //--------------------------------------------------------------------------- // Function Buff_Stunned_TekPistol.Buff_Stunned_TekPistol_C.BPCheckPreventInput // () // Parameters: // TEnumAsByte* inputType (Parm, ZeroConstructor, IsPlainOldData) // bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) bool ABuff_Stunned_TekPistol_C::BPCheckPreventInput(TEnumAsByte* inputType) { static auto fn = UObject::FindObject("Function Buff_Stunned_TekPistol.Buff_Stunned_TekPistol_C.BPCheckPreventInput"); ABuff_Stunned_TekPistol_C_BPCheckPreventInput_Params params; params.inputType = inputType; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, ¶ms); fn->FunctionFlags = flags; return params.ReturnValue; } // Function Buff_Stunned_TekPistol.Buff_Stunned_TekPistol_C.BPCustomAllowAddBuff // () // Parameters: // class APrimalCharacter** forCharacter (Parm, ZeroConstructor, IsPlainOldData) // class AActor** DamageCauser (Parm, ZeroConstructor, IsPlainOldData) // bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) bool ABuff_Stunned_TekPistol_C::BPCustomAllowAddBuff(class APrimalCharacter** forCharacter, class AActor** DamageCauser) { static auto fn = UObject::FindObject("Function Buff_Stunned_TekPistol.Buff_Stunned_TekPistol_C.BPCustomAllowAddBuff"); ABuff_Stunned_TekPistol_C_BPCustomAllowAddBuff_Params params; params.forCharacter = forCharacter; params.DamageCauser = DamageCauser; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, ¶ms); fn->FunctionFlags = flags; return params.ReturnValue; } // Function Buff_Stunned_TekPistol.Buff_Stunned_TekPistol_C.BPDeactivated // () // Parameters: // class AActor** ForInstigator (Parm, ZeroConstructor, IsPlainOldData) void ABuff_Stunned_TekPistol_C::BPDeactivated(class AActor** ForInstigator) { static auto fn = UObject::FindObject("Function Buff_Stunned_TekPistol.Buff_Stunned_TekPistol_C.BPDeactivated"); ABuff_Stunned_TekPistol_C_BPDeactivated_Params params; params.ForInstigator = ForInstigator; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, ¶ms); fn->FunctionFlags = flags; } // Function Buff_Stunned_TekPistol.Buff_Stunned_TekPistol_C.BPSetupForInstigator // () // Parameters: // class AActor** ForInstigator (Parm, ZeroConstructor, IsPlainOldData) void ABuff_Stunned_TekPistol_C::BPSetupForInstigator(class AActor** ForInstigator) { static auto fn = UObject::FindObject("Function Buff_Stunned_TekPistol.Buff_Stunned_TekPistol_C.BPSetupForInstigator"); ABuff_Stunned_TekPistol_C_BPSetupForInstigator_Params params; params.ForInstigator = ForInstigator; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, ¶ms); fn->FunctionFlags = flags; } // Function Buff_Stunned_TekPistol.Buff_Stunned_TekPistol_C.UserConstructionScript // () void ABuff_Stunned_TekPistol_C::UserConstructionScript() { static auto fn = UObject::FindObject("Function Buff_Stunned_TekPistol.Buff_Stunned_TekPistol_C.UserConstructionScript"); ABuff_Stunned_TekPistol_C_UserConstructionScript_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, ¶ms); fn->FunctionFlags = flags; } // Function Buff_Stunned_TekPistol.Buff_Stunned_TekPistol_C.ExecuteUbergraph_Buff_Stunned_TekPistol // () // Parameters: // int EntryPoint (Parm, ZeroConstructor, IsPlainOldData) void ABuff_Stunned_TekPistol_C::ExecuteUbergraph_Buff_Stunned_TekPistol(int EntryPoint) { static auto fn = UObject::FindObject("Function Buff_Stunned_TekPistol.Buff_Stunned_TekPistol_C.ExecuteUbergraph_Buff_Stunned_TekPistol"); ABuff_Stunned_TekPistol_C_ExecuteUbergraph_Buff_Stunned_TekPistol_Params params; params.EntryPoint = EntryPoint; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, ¶ms); fn->FunctionFlags = flags; } } #ifdef _MSC_VER #pragma pack(pop) #endif #include "tests/gtest/gtest.h" #include "pbrt.h" #include "point-line-mis/triangle.h" using namespace pbrt; TEST(TriangleAbove, TriangleClipping) { niels::Triangle t0(Point3f(0, 0, 1), Point3f(1, 0, 1), Point3f(1, 1, 1)); std::vector clipped; t0.Clip(Point3f(0, 0, 0), Normal3f(0, 0, 1), clipped); EXPECT_EQ(1u, clipped.size()); EXPECT_EQ(t0[0], clipped[0][0]); EXPECT_EQ(t0[1], clipped[0][1]); EXPECT_EQ(t0[2], clipped[0][2]); } TEST(TriangleOne, TriangleClipping) { niels::Triangle t0(Point3f(0, 0, 0), Point3f(1, 0, 1), Point3f(1, 0, -1)); std::vector clipped; t0.Clip(Point3f(0, 0, 0), Normal3f(0, 0, 1), clipped); EXPECT_EQ(1u, clipped.size()); const niels::Triangle clippedTriangle = clipped[0]; EXPECT_EQ(true, clippedTriangle.HasVertex(Point3f(0, 0, 0), 1e-6)); EXPECT_EQ(true, clippedTriangle.HasVertex(Point3f(1, 0, 1), 1e-6)); EXPECT_EQ(true, clippedTriangle.HasVertex(Point3f(1, 0, 0), 1e-6)); } TEST(TriangleTwo, TriangleClipping) { niels::Triangle t0(Point3f(0, 0, -1), Point3f(4, 0, -1), Point3f(2, 0, 1)); std::vector clipped; t0.Clip(Point3f(0, 0, 0), Normal3f(0, 0, 1), clipped); EXPECT_EQ(1u, clipped.size()); const niels::Triangle clippedTriangle = clipped[0]; EXPECT_EQ(true, clippedTriangle.HasVertex(Point3f(1, 0, 0), 1e-6)); EXPECT_EQ(true, clippedTriangle.HasVertex(Point3f(3, 0, 0), 1e-6)); EXPECT_EQ(true, clippedTriangle.HasVertex(Point3f(2, 0, 1), 1e-6)); } TEST(TriangleThree, TriangleClipping) { niels::Triangle t0(Point3f(0, 0, 1), Point3f(4, 0, 1), Point3f(2, 0, -1)); std::vector clipped; t0.Clip(Point3f(0, 0, 0), Normal3f(0, 0, 1), clipped); EXPECT_EQ(2u, clipped.size()); const niels::Triangle& firstTriangle = clipped[0]; const niels::Triangle& secondTriangle = clipped[1]; firstTriangle.Print(stdout); secondTriangle.Print(stdout); EXPECT_EQ(true, firstTriangle.HasVertex(Point3f(4, 0, 1), 1e-6)); EXPECT_EQ(true, firstTriangle.HasVertex(Point3f(1, 0, 0), 1e-6)); EXPECT_EQ(true, firstTriangle.HasVertex(Point3f(0, 0, 1), 1e-6)); EXPECT_EQ(true, secondTriangle.HasVertex(Point3f(4, 0, 1), 1e-6)); EXPECT_EQ(true, secondTriangle.HasVertex(Point3f(3, 0, 0), 1e-6)); EXPECT_EQ(true, secondTriangle.HasVertex(Point3f(1, 0, 0), 1e-6)); } 1-10 /* * wallaby.hpp * * Created on: Nov 5, 2015 * Author: */ #ifndef INCLUDE_WALLABY_WALLABY_HPP_ #define INCLUDE_WALLABY_WALLABY_HPP_ #include "accel.hpp" #include "analog.hpp" #include "battery.hpp" #include "botball.h" #include "button.hpp" #include "camera.hpp" #include "compass.hpp" #include "console.hpp" #include "create.hpp" #include "digital.hpp" #include "display.h" #include "general.h" #include "graphics.h" #include "graphics_characters.h" #include "graphics_key_code.h" #include "gyro.hpp" #include "ir.hpp" #include "magneto.hpp" #include "motors.hpp" #include "robot.hpp" #include "servo.hpp" #include "thread.hpp" #include "util.hpp" #endif /* INCLUDE_WALLABY_WALLABY_HPP_ */ /* Write indexes coded on 24 bits with 8 bit CRC, inject errors, and read them back. */ // We use a Zero compatible board #define Serial SERIAL_PORT_USBVIRTUAL // compile with: // pio ci .\test\RecordData --board=zeroUSB --lib lib/SPIMemory --lib lib/FastCRC --project-option="targets=upload" --keep-build-dir // monitor with: // pio device monitor --port COM5 --baud 115200 #include #include const uint32_t kInvalidInt24 = 0x00FFFFFE; SPIFlash flash(4); FastCRC8 CRC8; class Int24Crc8 { public: static uint32_t Create(uint32_t data) { // zero MSB data &= 0x00FFFFFF; // compute crc uint8_t *addr = (uint8_t *)(&data); uint8_t crc_write = crc8.maxim(addr, 3); // assemble code word return data | ((uint32_t)crc_write << 24); } static bool Check(uint32_t code) { uint8_t *addr = (uint8_t *)(&code); uint8_t crc_check = crc8.maxim(addr, 3); if (crc_check != (code >> 24)) { // Serial.print("CRC8 do not match for Int24 "); // Serial.print(code, DEC); // Serial.println(" !"); return false; } return true; } static uint32_t Data(uint32_t code) { return code & 0x00FFFFFF; } private: static FastCRC8 crc8; }; FastCRC8 Int24Crc8::crc8; uint32_t ReadCheckInt24(uint32_t addr) { uint32_t first = flash.readLong(addr, false); uint32_t second = flash.readLong(addr + 4, false); bool first_crc = Int24Crc8::Check(first); bool second_crc = Int24Crc8::Check(second); if (!first_crc && !second_crc) { Serial.println("Both indexes CRC are wrong (cannot thrust either value)!"); return kInvalidInt24; } if (!first_crc) { Serial.println("CRC for first index is wrong!"); return Int24Crc8::Data(second); } if (!second_crc) { Serial.println("CRC for second index is wrong!"); return Int24Crc8::Data(first); } if (first != second) { Serial.println( "Double double fault (CRC are correct but number do not match)!"); return kInvalidInt24; } return Int24Crc8::Data(first); } bool DoubleWriteInt24(uint32_t addr, uint32_t value) { uint32_t code = Int24Crc8::Create(value); // This version of the code corrupt the data // before writing it for sectors 2, 3, 4 and 5! uint32_t code2 = code; if (addr == 2 * KB(4) || addr == 4 * KB(4)) { code &= 0xFFFFFFF0; code |= 0xA; } if (flash.writeLong(addr, code, true)) { if (addr == 3 * KB(4) || addr == 4 * KB(4)) { code2 &= 0xFFFFFFF0; code2 |= 0xA; } if (addr == 5 * KB(4)) { code2 = Int24Crc8::Create(0xABABAA); } if (flash.writeLong(addr + 4, code2, true)) { return true; } } return false; } void setup() { Serial.begin(115200); while (!Serial) ; flash.begin(); // Prepare the first sectors for the test Serial.print("Erasing first 32K.. ."); uint32_t start = micros(); flash.eraseBlock32K(0); uint32_t stop = micros(); Serial.print((stop - start) / 1000); Serial.println("ms."); uint32_t index = 0xABABAB; Serial.print("Testing with index = "); Serial.println(index); Serial.println(); Serial.print("Writing indexes... "); start = micros(); for (int i = 1; i <= 5; i++) { DoubleWriteInt24(i * KB(4), index); } stop = micros(); Serial.print((stop - start) / 1000); Serial.println("ms."); for (int i = 1; i <= 5; i++) { index = ReadCheckInt24(i * KB(4)); Serial.print("Index on sector "); Serial.print(i); Serial.print(" = "); Serial.println(index); } } void loop() {}dtylman/ion /* * File: EventsSubsystem.cpp * Author: danny * * Created on February 4, 2015, 9:04 AM */ #include "EventsSubsystem.h" #include "EventDataObject.h" #include "DataSubsystem.h" #include "SendMail.h" #include "Syslog.h" #include #include #include #include #include #include #include #include #include EventsSubsystem::EventsSubsystem() : _activity(this, &EventsSubsystem::runActivity), _logger(Poco::Logger::get("EventsSubsystem")) { } EventsSubsystem::~EventsSubsystem() { } void EventsSubsystem::initialize(Poco::Util::Application& app) { _logger.debug("EventsSubsystem::initialize"); Poco::SharedPtr cert(new Poco::Net::AcceptCertificateHandler(true)); Poco::Net::Context::Ptr context = new Poco::Net::Context(Poco::Net::Context::CLIENT_USE, "", "", "", Poco::Net::Context::VERIFY_RELAXED, 9, true, "ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH"); Poco::Net::SSLManager::instance().initializeClient(nullptr, cert, context); _activity.start(); } const char* EventsSubsystem::name() const { return "EventsSubsystem"; } void EventsSubsystem::uninitialize() { _logger.debug("EventsSubsystem::uninitialize"); _activity.stop(); _queue.wakeUpAll(); _activity.wait(2500); Poco::Net::uninitializeSSL(); } void EventsSubsystem::notify(EventNotification::Ptr notif) { _queue.enqueueNotification(notif); } void EventsSubsystem::persistEvent(const EventData& eventData) { DataSubsystem& data = Poco::Util::Application::instance().getSubsystem(); EventDataObject edo(data.createSession()); edo.insert(eventData); } void EventsSubsystem::processEvent(const EventData& eventData) { if (_logger.debug()) { _logger.debug("Event: %s", eventData.toString()); } Poco::Util::AbstractConfiguration& config = Poco::Util::Application::instance().config(); const std::string& eventName = eventData.name(); if (config.getBool(Poco::format("ion.events.%s.save", eventName), true)) { persistEvent(eventData); } if (config.getBool(Poco::format("ion.events.%s.mail", eventName), false)) { mailEvent(eventData); } if (config.getBool(Poco::format("ion.events.%s.syslog", eventName), false)) { syslogEvent(eventData); } } void EventsSubsystem::runActivity() { _logger.information("Activity Started"); while (!_activity.isStopped()) { try { Poco::Notification::Ptr notif(_queue.waitDequeueNotification(2500), true); EventNotification::Ptr event = notif.cast(); if (!event.isNull()) { processEvent(event->event()); } } catch (Poco::Exception& ex) { _logger.error(ex.displayText()); } catch (std::exception& ex) { _logger.error(std::string(ex.what())); } catch (...) { _logger.error("Unknown exception in EventsSubsystem::runActivity"); } } _logger.information("Activity Ended"); } void EventsSubsystem::mailEvent(const EventData & eventData) { try { SendMail mail; mail.sendEvent(eventData); } catch (Poco::Exception& ex) { _logger.error("Failed to send mail: %s", ex.displayText()); } } void EventsSubsystem::syslogEvent(const EventData& eventData) { try { _syslog.log(eventData); } catch (Poco::Exception& ex) { _logger.error("Failed to write syslog event: %s", ex.displayText()); } } /* * Copyright (C) 2005-2019 Centre National d'Etudes Spatiales (CNES) * * This file is part of Orfeo Toolbox * * https://www.orfeo-toolbox.org/ * * 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 "otbSarImageMetadataInterface.h" #include "otbRadarsat2ImageMetadataInterface.h" #include "otbMacro.h" #include "itkMetaDataObject.h" #include "otbImageKeywordlist.h" // useful constants #include namespace otb { Radarsat2ImageMetadataInterface::Radarsat2ImageMetadataInterface() { } bool Radarsat2ImageMetadataInterface::CanRead() const { std::string sensorID = GetSensorID(); if (sensorID.find("RADARSAT-2") != std::string::npos) { return true; } else return false; } void Radarsat2ImageMetadataInterface::CreateCalibrationLookupData(const short type) { std::string lut = "SigmaNought"; switch (type) { case SarCalibrationLookupData::BETA: { lut = "BetaNought"; } break; case SarCalibrationLookupData::GAMMA: { lut = "GammaNought"; } break; case SarCalibrationLookupData::DN: { lut = "DN"; } break; case SarCalibrationLookupData::SIGMA: default: { lut = "SigmaNought"; } break; } const ImageKeywordlistType imageKeywordlist = this->GetImageKeywordlist(); const std::string key = "referenceNoiseLevel[" + lut + "].gain"; Radarsat2CalibrationLookupData::GainListType glist; int offset = 0; Utils::ConvertStringToVector(imageKeywordlist.GetMetadataByKey("referenceNoiseLevel[" + lut + "].gain"), glist, "referenceNoiseLevel[" + lut + "].gain"); Utils::LexicalCast(imageKeywordlist.GetMetadataByKey("referenceNoiseLevel[" + lut + "].offset"), "referenceNoiseLevel[" + lut + "].offset"); Radarsat2CalibrationLookupData::Pointer sarLut; sarLut = Radarsat2CalibrationLookupData::New(); sarLut->InitParameters(type, offset, glist); this->SetCalibrationLookupData(sarLut); } void Radarsat2ImageMetadataInterface::ParseDateTime(const char* key, std::vector& dateFields) const { if (dateFields.size() < 1) { // parse from keyword list if (!this->CanRead()) { itkExceptionMacro(<< "Invalid Metadata, not a valid product"); } const ImageKeywordlistType imageKeywordlist = this->GetImageKeywordlist(); if (!imageKeywordlist.HasKey(key)) { itkExceptionMacro(<< "no key named '" << key << "'"); } std::string date_time_str = imageKeywordlist.GetMetadataByKey(key); date_time_str.resize(date_time_str.size() - 1); Utils::ConvertStringToVector(date_time_str, dateFields, key, "-T:."); } } int Radarsat2ImageMetadataInterface::GetYear() const { int value = 0; ParseDateTime("support_data.image_date", m_AcquisitionDateFields); if (m_AcquisitionDateFields.size() > 0) { value = Utils::LexicalCast(m_AcquisitionDateFields[0], "support_data.image_date(year)"); } return value; } int Radarsat2ImageMetadataInterface::GetMonth() const { int value = 0; ParseDateTime("support_data.image_date", m_AcquisitionDateFields); if (m_AcquisitionDateFields.size() > 1) { value = Utils::LexicalCast(m_AcquisitionDateFields[1], "support_data.image_date(month)"); } return value; } int Radarsat2ImageMetadataInterface::GetDay() const { int value = 0; ParseDateTime("support_data.image_date", m_AcquisitionDateFields); if (m_AcquisitionDateFields.size() > 2) { value = Utils::LexicalCast(m_AcquisitionDateFields[2], "support_data.image_date(day)"); } return value; } int Radarsat2ImageMetadataInterface::GetHour() const { int value = 0; ParseDateTime("support_data.image_date", m_AcquisitionDateFields); if (m_AcquisitionDateFields.size() > 3) { value = Utils::LexicalCast(m_AcquisitionDateFields[3], "support_data.image_date(hour)"); } return value; } int Radarsat2ImageMetadataInterface::GetMinute() const { int value = 0; ParseDateTime("support_data.image_date", m_AcquisitionDateFields); if (m_AcquisitionDateFields.size() > 4) { value = Utils::LexicalCast(m_AcquisitionDateFields[4], "support_data.image_date(minute)"); } return value; } int Radarsat2ImageMetadataInterface::GetProductionYear() const { int value = 0; ParseDateTime("support_data.date", m_ProductionDateFields); if (m_ProductionDateFields.size() > 0) { value = Utils::LexicalCast(m_ProductionDateFields[0], "support_data.image_date(year)"); } return value; } int Radarsat2ImageMetadataInterface::GetProductionMonth() const { int value = 0; ParseDateTime("support_data.date", m_ProductionDateFields); if (m_ProductionDateFields.size() > 1) { value = Utils::LexicalCast(m_ProductionDateFields[1], "support_data.image_date(production month)"); } return value; } int Radarsat2ImageMetadataInterface::GetProductionDay() const { int value = 0; ParseDateTime("support_data.date", m_ProductionDateFields); if (m_ProductionDateFields.size() > 2) { value = Utils::LexicalCast(m_ProductionDateFields[2], "support_data.image_date(production day)"); } return value; } double Radarsat2ImageMetadataInterface::GetPRF() const { return 0; } double Radarsat2ImageMetadataInterface::GetRSF() const { return 0; } double Radarsat2ImageMetadataInterface::GetRadarFrequency() const { return 0; } double Radarsat2ImageMetadataInterface::GetCenterIncidenceAngle() const { return 0; } Radarsat2ImageMetadataInterface::UIntVectorType Radarsat2ImageMetadataInterface::GetDefaultDisplay() const { UIntVectorType rgb(3); rgb[0] = 0; rgb[1] = 0; rgb[2] = 0; return rgb; } } // end namespace otb #include #include "test013.h" char test013::dat[] = { 0xaa, 0xbb, 0xcc, 0x00, 0xdd, 0xcc, 0xbb, 0xaa, }; hefen1/chromium // 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 "chrome/browser/sync/test/integration/p2p_sync_refresher.h" #include "chrome/browser/chrome_notification_types.h" #include "chrome/browser/sync/profile_sync_service.h" #include "chrome/browser/sync/test/integration/sync_datatype_helper.h" #include "chrome/browser/sync/test/integration/sync_test.h" #include "content/public/browser/notification_service.h" #include "sync/internal_api/public/sessions/sync_session_snapshot.h" P2PSyncRefresher::P2PSyncRefresher(ProfileSyncService* sync_service) : sync_service_(sync_service){ sync_service_->AddObserver(this); } P2PSyncRefresher::~P2PSyncRefresher() { sync_service_->RemoveObserver(this); } void P2PSyncRefresher::OnStateChanged() {} void P2PSyncRefresher::OnSyncCycleCompleted() { const syncer::sessions::SyncSessionSnapshot& snap = sync_service_->GetLastSessionSnapshot(); bool is_notifiable_commit = (snap.model_neutral_state().num_successful_commits > 0); if (is_notifiable_commit) { syncer::ModelTypeSet model_types = snap.model_neutral_state().commit_request_types; SyncTest* test = sync_datatype_helper::test(); for (int i = 0; i < test->num_clients(); ++i) { if (sync_service_->profile() != test->GetProfile(i)) { content::NotificationService::current()->Notify( chrome::NOTIFICATION_SYNC_REFRESH_LOCAL, content::Source(test->GetProfile(i)), content::Details(&model_types)); } } } } zjcs/PKVIO #include "TrackByOpticalFlow.h" #include #include #include #include #include #include #include #include #include int load_state = 0; std::string process_name = "oriwotw.exe"; std::string base_path = "C:\\moon\\"; std::string log_path = "loader_log.txt"; // Load order is top to bottom. std::array dll_paths = { "InjectDll.dll" }; int load_inject_dlls() { std::vector loaded_libraries; bool failed = false; std::ofstream log(base_path + log_path); log.clear(); { log << "starting dll load" << std::endl; for (auto const& dll : dll_paths) { auto handle = LoadLibraryA((base_path + dll).c_str()); if (handle == nullptr) { log << "failed to load library, aborting: " << GetLastError() << std::endl; failed = true; break; } else { log << "successfully loaded dll '" << dll << "'" << std::endl; loaded_libraries.push_back(handle); } } if (failed) { for (auto handle : loaded_libraries) { FreeLibrary(handle); } load_state = 0; log.close(); return -1; } } auto injectdll_handle = loaded_libraries[0]; auto proc_address = GetProcAddress(injectdll_handle, "injection_entry"); if (proc_address == nullptr) { log << "failed to get address of injection_entry: " << GetLastError() << std::endl; load_state = 0; log.close(); return -3; } log << "starting InjectDLL main function." << std::endl; log.close(); load_state = 2; auto injection_entry = reinterpret_cast(proc_address); injection_entry(); return 0; } BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) { if ((ul_reason_for_call == DLL_PROCESS_ATTACH || ul_reason_for_call == DLL_THREAD_ATTACH) && load_state == 0) { load_state = 1; CreateThread(0, 0, (LPTHREAD_START_ROUTINE)load_inject_dlls, 0, 0, 0); } return 1; } /*========================================================================= * * Copyright , 2012 * * * 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.txt * * 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 MOORETRACING_HPP #define MOORETRACING_HPP #include "MooreTracing.h" #include "itkImageRegionConstIterator.h" template bool FindNeighborWithValue(const TImage* const image, itk::Index<2> queryPixel, unsigned char queryValue, itk::Offset<2>& neighbor) { for(int i = -1; i <= 1; ++i) { for(int j = -1; j <= 1; ++j) { itk::Offset<2> offset; offset[0] = i; offset[1] = j; if(!image->GetLargestPossibleRegion().IsInside(queryPixel + offset)) { continue; } if(image->GetPixel(queryPixel + offset) == queryValue) { neighbor = offset; return true; } } } return false; } template itk::Index<2> FindNextPixel(const TImage* const image, itk::Index<2> currentPixel, itk::Offset<2>& backtrack) { itk::Offset<2> startingOffset = backtrack; std::vector< itk::Offset<2> > orderedOffsets = GetOrdered8NeighborOffsets(startingOffset); for(unsigned int i = 0; i < orderedOffsets.size(); ++i) { if(image->GetPixel(currentPixel + orderedOffsets[i])) { if(i != 0) { backtrack = (currentPixel + orderedOffsets[i-1]) - (currentPixel + orderedOffsets[i]); } else { backtrack = (currentPixel + startingOffset) - (currentPixel + orderedOffsets[i]); } return currentPixel + orderedOffsets[i]; } } std::stringstream ss; ss << "Pixel " << currentPixel << " has no next pixel - this means there was a pixel that is not connected to anything!"; throw std::runtime_error(ss.str()); // This is just so there are no warnings about no return value, it should never be run. (Maybe we don't need it now that we throw?) itk::Index<2> zeroPixel; zeroPixel.Fill(0); return zeroPixel; } template itk::Index<2> FindFirstPixel(const TImage* const image) { itk::ImageRegionConstIterator imageIterator(image, image->GetLargestPossibleRegion()); itk::Index<2> firstPixelIndex; while(!imageIterator.IsAtEnd()) { // Get the value of the current pixel if(imageIterator.Get()) { firstPixelIndex = imageIterator.GetIndex(); break; } ++imageIterator; } return firstPixelIndex; } template std::vector< itk::Index<2> > MooreTrace(const TImage* const image, const itk::Index<2>& startingPixel, const itk::Index<2>& endingPixel) { // Need to find a nonzero pixel around startingPixel. If there is not one, throw an error and quit. itk::Offset<2> backtrack; bool validStart = FindNeighborWithValue(image, startingPixel, 0, backtrack); if(!validStart) { std::cerr << "Cannot trace from " << startingPixel << " - it is not a boundary pixel!" << std::endl; exit(-1); } itk::Index<2> currentPixel = startingPixel; std::vector< itk::Index<2> > path; do { path.push_back(currentPixel); currentPixel = FindNextPixel(image, currentPixel, backtrack); //std::cout << numberOfPixelsTraced << " pixels have been traced." << std::endl; //std::cout << "Current pixel: " << currentPixel << " with backtrack: " << backtrack << std::endl; } while(currentPixel != endingPixel); return path; } template unsigned int CountNonZeroPixels(const TImage* const image) { itk::ImageRegionConstIterator imageIterator(image, image->GetLargestPossibleRegion()); unsigned int numberOfNonZeroPixels = 0; while(!imageIterator.IsAtEnd()) { if(imageIterator.Get()) { numberOfNonZeroPixels++; } ++imageIterator; } return numberOfNonZeroPixels; } #endif 1-10 #include "LuaReader.h" #include #include namespace RoTool { enum ELuaIndexType { ELIT_INT, // 整数类型的index ELIT_STRING, // 字符串类型的index }; class CLuaIndexHelper::_implCLuaIndexHelper { public : ELuaIndexType m_xIndexType; std::string m_strIndex; int m_iIndex; public : _implCLuaIndexHelper(ELuaIndexType xIndexType, const std::string& strIndex, int iIndex) { m_xIndexType = xIndexType; m_strIndex = strIndex; m_iIndex = iIndex; } }; class CLuaReader::_implCLuaReader { public : lua_State *m_pLuaState; public : _implCLuaReader() { m_pLuaState = luaL_newstate(); luaL_openlibs(m_pLuaState); assert( m_pLuaState ); } ~_implCLuaReader() { lua_close( m_pLuaState ); } bool Open(const char *szFileName) { int ret = luaL_loadfile(m_pLuaState, szFileName); if ( ret != 0 ) { return false; } int ret2 = lua_pcall(m_pLuaState, 0, 0, 0 ); return ret2 == 0; } void Begin(const char *szVarName) { int cnt = lua_gettop(m_pLuaState); if ( cnt == 0 ) { lua_getglobal(m_pLuaState, szVarName); } else { lua_getfield(m_pLuaState, -1, szVarName); } } void Begin(int iIndex) { int cnt = lua_gettop(m_pLuaState); assert(cnt > 0 ); lua_rawgeti(m_pLuaState, -1, iIndex); } void Begin(CLuaIndexHelper::_implCLuaIndexHelper *pIndex) { if ( pIndex->m_xIndexType == ELIT_STRING ) { Begin(pIndex->m_strIndex.c_str()); } else { Begin(pIndex->m_iIndex); } } void End() { if ( lua_gettop(m_pLuaState) != 0 ) { lua_remove(m_pLuaState, -1); } } class CLuaEnder { public : CLuaEnder(_implCLuaReader *pReader) { m_pImplReader = pReader; } ~CLuaEnder() { m_pImplReader->End(); } private: _implCLuaReader *m_pImplReader; }; }; CLuaReader::CLuaReader() { m_pImpl = NULL; } CLuaReader::~CLuaReader() { Close(); } bool CLuaReader::Open(const std::string &strFileName) { assert( m_pImpl == NULL ); m_pImpl = new _implCLuaReader; if ( !m_pImpl->Open( strFileName.c_str() ) ) { Close(); return false; } return true; } bool CLuaReader::IsOpen() const { return m_pImpl != NULL; } void CLuaReader::Close() { if ( m_pImpl ) { delete m_pImpl; m_pImpl = NULL; } } bool CLuaReader::GetValue(const CLuaIndexHelper &xIndex, int &iVarStore) { assert(m_pImpl); m_pImpl->Begin( xIndex.m_pImpl ); _implCLuaReader::CLuaEnder ender(m_pImpl); if ( !lua_isinteger(m_pImpl->m_pLuaState, -1) ) { return false; } iVarStore = lua_tointeger(m_pImpl->m_pLuaState, -1); return true; } bool CLuaReader::GetValue(const CLuaIndexHelper &xIndex, bool &bVarStore) { assert( m_pImpl ); m_pImpl->Begin(xIndex.m_pImpl); _implCLuaReader::CLuaEnder ender(m_pImpl); if ( !lua_isboolean(m_pImpl->m_pLuaState, -1) ) { return false; } bVarStore = lua_toboolean(m_pImpl->m_pLuaState, -1); return true; } bool CLuaReader::GetValue(const CLuaIndexHelper &xIndex, double &dVarStore) { assert( m_pImpl ); m_pImpl->Begin(xIndex.m_pImpl); _implCLuaReader::CLuaEnder ender(m_pImpl); if ( !lua_isnumber(m_pImpl->m_pLuaState, -1) ) { return false; } dVarStore = lua_tonumber(m_pImpl->m_pLuaState, -1); return true; } bool CLuaReader::GetValue(const CLuaIndexHelper &xIndex, std::string &strVarStore) { assert( m_pImpl ); m_pImpl->Begin(xIndex.m_pImpl); _implCLuaReader::CLuaEnder ender(m_pImpl); if ( !lua_isstring(m_pImpl->m_pLuaState, -1) ) { return false; } size_t len = -1; const char *xStart = lua_tolstring(m_pImpl->m_pLuaState, -1, &len); strVarStore.assign(xStart, xStart + len); return true; } bool CLuaReader::EnterTable(const CLuaIndexHelper &xIndex) { assert( m_pImpl ); m_pImpl->Begin(xIndex.m_pImpl); if ( !lua_istable(m_pImpl->m_pLuaState, -1) ) { m_pImpl->End(); return false; } return true; } void CLuaReader::ExitTable() { assert(m_pImpl); m_pImpl->End(); } int CLuaReader::GetDepth() { assert(m_pImpl); return lua_gettop(m_pImpl->m_pLuaState); } CLuaIndexHelper::CLuaIndexHelper(const char *szFieldName) { assert(szFieldName); m_pImpl = new _implCLuaIndexHelper(ELIT_STRING, szFieldName, 0); } CLuaIndexHelper::CLuaIndexHelper(const std::string &strFieldName) { m_pImpl = new _implCLuaIndexHelper(ELIT_STRING, strFieldName, 0); } CLuaIndexHelper::CLuaIndexHelper(int iFiledIndex) { m_pImpl = new _implCLuaIndexHelper(ELIT_INT, "", iFiledIndex); } CLuaIndexHelper::~CLuaIndexHelper() { delete m_pImpl; } } /* * Copyright (c) 2018 Isetta */ #include "Networking/NetworkManager.h" #include "Core/Config/Config.h" namespace Isetta { NetworkingModule* NetworkManager::networkingModule{nullptr}; void NetworkManager::SendHandleMessageFromClient(int handle) { HandleMessage* message = static_cast( networkingModule->client->CreateMessage(HANDLE_MESSAGE)); message->handle = handle; networkingModule->AddClientToServerMessage(message); } void NetworkManager::SendStringMessageFromClient(std::string string) { StringMessage* message = static_cast( networkingModule->client->CreateMessage(STRING_MESSAGE)); message->string = string; networkingModule->AddClientToServerMessage(message); } void NetworkManager::SendHandleMessageFromServer(int clientIdx, int handle) { if (!networkingModule->server->IsClientConnected(clientIdx)) { return; } HandleMessage* message = static_cast( networkingModule->server->CreateMessage(clientIdx, HANDLE_MESSAGE)); message->handle = handle; networkingModule->AddServerToClientMessage(clientIdx, message); } void NetworkManager::SendStringMessageFromServer(int clientIdx, std::string string) { if (!networkingModule->server->IsClientConnected(clientIdx)) { return; } StringMessage* message = static_cast( networkingModule->server->CreateMessage(clientIdx, STRING_MESSAGE)); message->string = string; networkingModule->AddServerToClientMessage(clientIdx, message); } void NetworkManager::ConnectToServer(const char* serverAddress, std::function callback) { networkingModule->Connect( serverAddress, Config::Instance().networkConfig.serverPort.GetVal(), callback); } void NetworkManager::DisconnectFromServer() { networkingModule->Disconnect(); } void NetworkManager::CreateServer(const char* address) { networkingModule->CreateServer( address, Config::Instance().networkConfig.serverPort.GetVal()); } bool NetworkManager::ClientIsConnected() { return networkingModule->client->IsConnected(); } bool NetworkManager::ServerIsRunning() { return networkingModule->server && networkingModule->server->IsRunning(); } int NetworkManager::GetMaxClients() { return !ServerIsRunning() ? -1 : networkingModule->server->GetMaxClients(); } void NetworkManager::CloseServer() { networkingModule->CloseServer(); } }src/server/services/transfers/ReuseTransfersService.cpp /* * Copyright (c) CERN 2013-2015 * * Copyright (c) Members of the EMI Collaboration. 2010-2013 * See http://www.eu-emi.eu/partners for details on the copyright * holders. * * 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 "ReuseTransfersService.h" #include #include "common/DaemonTools.h" #include "config/ServerConfig.h" #include "cred/DelegCred.h" #include "ExecuteProcess.h" #include "server/DrainMode.h" #include "SingleTrStateInstance.h" #include "CloudStorageConfig.h" #include "ThreadSafeList.h" #include "VoShares.h" using namespace fts3::common; using fts3::config::ServerConfig; namespace fts3 { namespace server { extern time_t retrieveRecords; ReuseTransfersService::ReuseTransfersService() { setServiceName("ReuseTransfersService"); } void ReuseTransfersService::runService() { while (!boost::this_thread::interruption_requested()) { retrieveRecords = time(0); try { boost::this_thread::sleep(schedulingInterval); if (DrainMode::instance()) { FTS3_COMMON_LOGGER_NEWLOG(INFO) << "Set to drain mode, no more transfers for this instance!" << commit; boost::this_thread::sleep(boost::posix_time::seconds(15)); continue; } executeUrlcopy(); } catch (boost::thread_interrupted&) { FTS3_COMMON_LOGGER_NEWLOG(INFO) << "Thread interruption requested" << commit; break; } catch (std::exception& e) { FTS3_COMMON_LOGGER_NEWLOG(ERR) << "Exception in ReuseTransfersService " << e.what() << commit; } catch (...) { FTS3_COMMON_LOGGER_NEWLOG(ERR) << "Exception in ReuseTransfersService!" << commit; } } } void ReuseTransfersService::writeJobFile(const std::string& jobId, const std::vector& files) { std::ofstream fout; try { std::vector::const_iterator iter; std::string filename = ServerConfig::instance().get("MessagingDirectory") + "/" + jobId; fout.open(filename.c_str(), std::ios::out); for (iter = files.begin(); iter != files.end(); ++iter) { fout << *iter << std::endl; } } catch (...) { // pass } } std::map ReuseTransfersService::generateJobFile( const std::string& jobId, const std::list& files) { std::vector urls; std::map fileIds; std::ostringstream line; for (auto it = files.begin(); it != files.end(); ++it) { fileIds.insert(std::make_pair(it->fileId, it->jobId)); std::string fileMetadata = UrlCopyCmd::prepareMetadataString( it->fileMetadata); if (fileMetadata.empty()) fileMetadata = "x"; std::string bringOnlineToken = it->bringOnlineToken; if (bringOnlineToken.empty()) bringOnlineToken = "x"; std::string checksum = it->checksum; if (checksum.empty()) checksum = "x"; line << std::fixed << it->fileId << " " << it->sourceSurl << " " << it->destSurl << " " << checksum << " " << boost::lexical_cast(it->userFilesize) << " " << fileMetadata << " " << bringOnlineToken; urls.push_back(line.str()); line.str(std::string()); } writeJobFile(jobId, urls); return fileIds; } void ReuseTransfersService::getFiles(const std::vector& queues, int availableUrlCopySlots) { auto db = DBSingleton::instance().getDBObjectInstance(); //now get files to be scheduled std::map > > > voQueues; db->getReadySessionReuseTransfers(queues, voQueues); std::map slotsLeftForSource, slotsLeftForDestination; for (auto i = queues.begin(); i != queues.end(); ++i) { // To reduce queries, fill in one go limits as source and as destination if (slotsLeftForDestination.count(i->destSe) == 0) { StorageConfig seConfig = db->getStorageConfig(i->destSe); slotsLeftForDestination[i->destSe] = seConfig.inboundMaxActive>0?seConfig.inboundMaxActive:60; slotsLeftForSource[i->destSe] = seConfig.outboundMaxActive>0?seConfig.outboundMaxActive:60; } if (slotsLeftForSource.count(i->sourceSe) == 0) { StorageConfig seConfig = db->getStorageConfig(i->sourceSe); slotsLeftForDestination[i->sourceSe] = seConfig.inboundMaxActive>0?seConfig.inboundMaxActive:60; slotsLeftForSource[i->sourceSe] = seConfig.outboundMaxActive>0?seConfig.outboundMaxActive:60; } // Once it is filled, decrement slotsLeftForDestination[i->destSe] -= i->activeCount; slotsLeftForSource[i->sourceSe] -= i->activeCount; } bool empty = false; while (!empty) { empty = true; for (auto vo_it = voQueues.begin(); vo_it != voQueues.end(); ++vo_it) { std::queue > > & vo_jobs = vo_it->second; if (!vo_jobs.empty()) { empty = false; //< if we are here there are still some data std::pair > const job = vo_jobs.front(); vo_jobs.pop(); if (job.second.size() <= 0) { FTS3_COMMON_LOGGER_NEWLOG(ERR) << "Empty job " << job.first << commit; continue; } if (slotsLeftForDestination[job.second.front().destSe] <= 0) { FTS3_COMMON_LOGGER_NEWLOG(WARNING) << "Reached limitation for destination " << job.second.front().destSe << commit; } else if (slotsLeftForSource[job.second.front().sourceSe] <= 0) { FTS3_COMMON_LOGGER_NEWLOG(WARNING) << "Reached limitation for source " << job.second.front().sourceSe << commit; } else if (availableUrlCopySlots <= 0) { FTS3_COMMON_LOGGER_NEWLOG(WARNING) << "Reached limitation of MaxUrlCopyProcesses" << commit; return; } else { startUrlCopy(job.first, job.second); --availableUrlCopySlots; --slotsLeftForDestination[job.second.front().destSe]; --slotsLeftForSource[job.second.front().sourceSe]; } } } } } void ReuseTransfersService::startUrlCopy(std::string const & job_id, std::list const & files) { GenericDbIfce *db = DBSingleton::instance().getDBObjectInstance(); UrlCopyCmd cmdBuilder; // Set log directory std::string logsDir = ServerConfig::instance().get("TransferLogDirectory"); cmdBuilder.setLogDir(logsDir); // Messaging std::string msgDir = ServerConfig::instance().get("MessagingDirectory"); cmdBuilder.setMonitoring(monitoringMessages, msgDir); // Set parameters from the "representative", without using the source and destination url, and other data // that is per transfer TransferFile const & representative = files.front(); cmdBuilder.setFromTransfer(representative, true, db->publishUserDn(representative.voName), msgDir); // Generate the file containing the list of transfers std::map fileIds = generateJobFile(representative.jobId, files); // Can we run? int currentActive = 0; if (!db->isTrAllowed(representative.sourceSe, representative.destSe, currentActive)) { return; } // Set parameters int secPerMB = db->getSecPerMb(representative.voName); if (secPerMB > 0) { cmdBuilder.setSecondsPerMB(secPerMB); } TransferFile::ProtocolParameters protocolParams = representative.getProtocolParameters(); if (representative.internalFileParams.empty()) { protocolParams.nostreams = db->getStreamsOptimization(representative.sourceSe, representative.destSe); protocolParams.timeout = db->getGlobalTimeout(representative.voName); protocolParams.ipv6 = db->isProtocolIPv6(representative.sourceSe, representative.destSe); protocolParams.udt = db->isProtocolUDT(representative.sourceSe, representative.destSe); //protocolParams.buffersize } cmdBuilder.setFromProtocol(protocolParams); std::string proxy_file = DelegCred::getProxyFile(representative.userDn, representative.credId); if (!proxy_file.empty()) cmdBuilder.setProxy(proxy_file); std::string cloudConfigFile = fts3::generateCloudStorageConfigFile(db, representative); if (!cloudConfigFile.empty()) { cmdBuilder.setOAuthFile(cloudConfigFile); } // Set all to ready, special case for session reuse int updatedFiles = db->updateFileStatusReuse(representative, "READY"); if (updatedFiles <= 0) { FTS3_COMMON_LOGGER_NEWLOG(WARNING) << "Transfer " << representative.jobId << " with session reuse enabled" << " not updated. Probably picked by another node" << commit; return; } // Debug level unsigned debugLevel = db->getDebugLevel(representative.sourceSe, representative.destSe); if (debugLevel > 0) { cmdBuilder.setDebugLevel(debugLevel); } // Infosystem cmdBuilder.setInfosystem(infosys); // FTS3 name cmdBuilder.setFTSName(ftsHostName); // Current number of actives cmdBuilder.setNumberOfActive(currentActive); // Number of retries and maximum number allowed int retry_times = db->getRetryTimes(representative.jobId, representative.fileId); cmdBuilder.setNumberOfRetries(retry_times < 0 ? 0 : retry_times); int retry_max = db->getRetry(representative.jobId); cmdBuilder.setMaxNumberOfRetries(retry_max < 0 ? 0 : retry_max); // Log and run std::string params = cmdBuilder.generateParameters(); FTS3_COMMON_LOGGER_NEWLOG(INFO) << "Transfer params: " << cmdBuilder << commit; ExecuteProcess pr(cmd, params); // Check if fork failed , check if execvp failed std::string forkMessage; if (-1 == pr.executeProcessShell(forkMessage)) { if (forkMessage.empty()) { FTS3_COMMON_LOGGER_NEWLOG(ERR) << "Transfer failed to spawn " << commit; db->forkFailed(job_id); } else { FTS3_COMMON_LOGGER_NEWLOG(ERR) << "Transfer failed to spawn " << forkMessage << commit; db->forkFailed(job_id); } } else { db->setPidForJob(job_id, pr.getPid()); } std::map::const_iterator iterFileIds; std::vector protoMsgs; for (iterFileIds = fileIds.begin(); iterFileIds != fileIds.end(); ++iterFileIds) { fts3::events::MessageUpdater msg2; msg2.set_job_id(job_id); msg2.set_file_id(iterFileIds->first); msg2.set_process_id(pr.getPid()); msg2.set_timestamp(millisecondsSinceEpoch()); ThreadSafeList::get_instance().push_back(msg2); events::Message protoMsg; protoMsg.set_file_id(iterFileIds->first); protoMsg.set_transfer_status("UPDATE"); protoMsg.set_timeout(cmdBuilder.getTimeout()); protoMsg.set_buffersize(cmdBuilder.getBuffersize()); protoMsg.set_nostreams(cmdBuilder.getNoStreams()); protoMsgs.push_back(protoMsg); } // Set known protocol settings db::DBSingleton::instance().getDBObjectInstance()->updateProtocol(protoMsgs); } /** * Transfers in uneschedulable queues must be set to fail */ static void failUnschedulable(const std::vector &unschedulable) { Producer producer(config::ServerConfig::instance().get("MessagingDirectory")); std::map > > > voQueues; DBSingleton::instance().getDBObjectInstance()->getReadySessionReuseTransfers(unschedulable, voQueues); for (auto mapIter = voQueues.begin(); mapIter != voQueues.end(); ++mapIter) { std::queue>> &queues = mapIter->second; while (!queues.empty()) { std::pair> &job = queues.front(); for (auto iterTransfer = job.second.begin(); iterTransfer != job.second.end(); ++iterTransfer) { events::Message status; status.set_transfer_status("FAILED"); status.set_timestamp(millisecondsSinceEpoch()); status.set_process_id(0); status.set_job_id(job.first); status.set_file_id(iterTransfer->fileId); status.set_source_se(iterTransfer->sourceSe); status.set_dest_se(iterTransfer->destSe); status.set_transfer_message("No share configured for this VO"); status.set_retry(false); status.set_errcode(EPERM); producer.runProducerStatus(status); } queues.pop(); } } } void ReuseTransfersService::executeUrlcopy() { // Bail out as soon as possible if there are too many url-copy processes int maxUrlCopy = config::ServerConfig::instance().get("MaxUrlCopyProcesses"); int urlCopyCount = countProcessesWithName("fts_url_copy"); int availableUrlCopySlots = maxUrlCopy - urlCopyCount; if (availableUrlCopySlots <= 0) { FTS3_COMMON_LOGGER_NEWLOG(WARNING) << "Reached limitation of MaxUrlCopyProcesses" << commit; return; } try { std::vector queues, unschedulable; DBSingleton::instance().getDBObjectInstance()->getQueuesWithSessionReusePending(queues); // Breaking determinism. See FTS-704 for an explanation. std::random_shuffle(queues.begin(), queues.end()); queues = applyVoShares(queues, unschedulable); // Fail all that are unschedulable failUnschedulable(unschedulable); if (queues.empty()) { return; } getFiles(queues, availableUrlCopySlots); } catch (std::exception& e) { FTS3_COMMON_LOGGER_NEWLOG(ERR) << "Exception in ReuseTransfersService " << e.what() << commit; } catch (...) { FTS3_COMMON_LOGGER_NEWLOG(ERR) << "Exception in ReuseTransfersService!" << commit; } } } // end namespace server } // end namespace fts3 #include "MenuEvent.hpp" namespace mad::core { MenuEvent::MenuEvent(Type new_type) : Event(Event::Type::Menu), type(new_type) {} } 1-10 // GAMBIT: Global and Modular BSM Inference Tool // ********************************************* /// \file /// /// A Mathematica backend example. /// /// ********************************************* /// /// Authors (add name and sate if you modify): /// /// \author /// \date 2016 Nov /// /// ********************************************* #include "gambit/Backends/frontend_macros.hpp" #include "gambit/Backends/frontends/LibMathematicaTest_1_0.hpp" // Convenience functions (definitions) BE_NAMESPACE { double run_Mathematica_Test(const int& val1, const int& val2) { double result1 = CalculateSquare(val1); double result2 = CalculateSquare(val2); cout << "result1 = " << result1 << endl; cout << "restul2 = " << result2 << endl; cout << "Var = " << PrintVar() << endl; *Var = 121; cout << "Var = " << PrintVar() << endl; *Var = *Var + 7; cout << "Var = " << PrintVar() << endl; cout << "Var2 = " << *Var2 << endl; cout << "Sum of Var and Var2 = " << CalculateSum(*Var, *Var2) << endl; cout << PrintVarorVar2(true) << endl; cout << PrintVarorVar2(false) << endl; cout << "Var == Var2? " << VarEqualVar2() << endl; *Var2 = *Var; cout << "Var == Var2? " << VarEqualVar2() << endl; cout << StringTest("You") << endl; VoidTest(); cout << PrintVar() << endl; cout << *Var << endl; MList list = {1,2,3,4,5,6}; cout << list << endl; cout << ExtractElement(list, 3) << endl; cout << SquareList(list) << endl; cout << "deltavar = " << *deltavar << endl; *deltavar = 1001; cout << "deltavar = " << *deltavar << endl; cout << "deltavar + 2 = " << *deltavar + 2 << endl; cout << Gammafunc(*Var) << endl; return CalculateSum(result1,result2); } } END_BE_NAMESPACE // Initialisation function (definition) BE_INI_FUNCTION { } END_BE_INI_FUNCTION 1-10 /* * Copyright (c) 2012 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 "webrtc/common_video/interface/incoming_video_stream.h" #include #if defined(_WIN32) #include #elif defined(WEBRTC_LINUX) #include #include #else #include #endif #include "webrtc/common_video/libyuv/include/webrtc_libyuv.h" #include "webrtc/common_video/video_render_frames.h" #include "webrtc/system_wrappers/interface/critical_section_wrapper.h" #include "webrtc/system_wrappers/interface/event_wrapper.h" #include "webrtc/system_wrappers/interface/thread_wrapper.h" #include "webrtc/system_wrappers/interface/tick_util.h" #include "webrtc/system_wrappers/interface/trace.h" namespace webrtc { IncomingVideoStream::IncomingVideoStream(uint32_t stream_id) : stream_id_(stream_id), stream_critsect_(CriticalSectionWrapper::CreateCriticalSection()), thread_critsect_(CriticalSectionWrapper::CreateCriticalSection()), buffer_critsect_(CriticalSectionWrapper::CreateCriticalSection()), incoming_render_thread_(), deliver_buffer_event_(EventTimerWrapper::Create()), running_(false), external_callback_(nullptr), render_callback_(nullptr), render_buffers_(new VideoRenderFrames()), incoming_rate_(0), last_rate_calculation_time_ms_(0), num_frames_since_last_calculation_(0), last_render_time_ms_(0), temp_frame_(), start_image_(), timeout_image_(), timeout_time_() { } IncomingVideoStream::~IncomingVideoStream() { Stop(); } VideoRenderCallback* IncomingVideoStream::ModuleCallback() { CriticalSectionScoped cs(stream_critsect_.get()); return this; } int32_t IncomingVideoStream::RenderFrame(const uint32_t stream_id, const VideoFrame& video_frame) { CriticalSectionScoped csS(stream_critsect_.get()); if (!running_) { return -1; } // Rate statistics. num_frames_since_last_calculation_++; int64_t now_ms = TickTime::MillisecondTimestamp(); if (now_ms >= last_rate_calculation_time_ms_ + kFrameRatePeriodMs) { incoming_rate_ = static_cast(1000 * num_frames_since_last_calculation_ / (now_ms - last_rate_calculation_time_ms_)); num_frames_since_last_calculation_ = 0; last_rate_calculation_time_ms_ = now_ms; } // Insert frame. CriticalSectionScoped csB(buffer_critsect_.get()); if (render_buffers_->AddFrame(video_frame) == 1) deliver_buffer_event_->Set(); return 0; } int32_t IncomingVideoStream::SetStartImage(const VideoFrame& video_frame) { CriticalSectionScoped csS(thread_critsect_.get()); return start_image_.CopyFrame(video_frame); } int32_t IncomingVideoStream::SetTimeoutImage(const VideoFrame& video_frame, const uint32_t timeout) { CriticalSectionScoped csS(thread_critsect_.get()); timeout_time_ = timeout; return timeout_image_.CopyFrame(video_frame); } void IncomingVideoStream::SetRenderCallback( VideoRenderCallback* render_callback) { CriticalSectionScoped cs(thread_critsect_.get()); render_callback_ = render_callback; } int32_t IncomingVideoStream::SetExpectedRenderDelay( int32_t delay_ms) { CriticalSectionScoped csS(stream_critsect_.get()); if (running_) { return -1; } CriticalSectionScoped cs(buffer_critsect_.get()); return render_buffers_->SetRenderDelay(delay_ms); } void IncomingVideoStream::SetExternalCallback( VideoRenderCallback* external_callback) { CriticalSectionScoped cs(thread_critsect_.get()); external_callback_ = external_callback; } int32_t IncomingVideoStream::Start() { CriticalSectionScoped csS(stream_critsect_.get()); if (running_) { return 0; } CriticalSectionScoped csT(thread_critsect_.get()); assert(incoming_render_thread_ == NULL); incoming_render_thread_ = ThreadWrapper::CreateThread( IncomingVideoStreamThreadFun, this, "IncomingVideoStreamThread"); if (!incoming_render_thread_) { return -1; } if (incoming_render_thread_->Start()) { } else { return -1; } incoming_render_thread_->SetPriority(kRealtimePriority); deliver_buffer_event_->StartTimer(false, kEventStartupTimeMs); running_ = true; return 0; } int32_t IncomingVideoStream::Stop() { CriticalSectionScoped cs_stream(stream_critsect_.get()); if (!running_) { return 0; } ThreadWrapper* thread = NULL; { CriticalSectionScoped cs_thread(thread_critsect_.get()); if (incoming_render_thread_) { // Setting the incoming render thread to NULL marks that we're performing // a shutdown and will make IncomingVideoStreamProcess abort after wakeup. thread = incoming_render_thread_.release(); deliver_buffer_event_->StopTimer(); // Set the event to allow the thread to wake up and shut down without // waiting for a timeout. deliver_buffer_event_->Set(); } } if (thread) { if (thread->Stop()) { delete thread; } else { assert(false); } } running_ = false; return 0; } int32_t IncomingVideoStream::Reset() { CriticalSectionScoped cs_buffer(buffer_critsect_.get()); render_buffers_->ReleaseAllFrames(); return 0; } uint32_t IncomingVideoStream::StreamId() const { return stream_id_; } uint32_t IncomingVideoStream::IncomingRate() const { CriticalSectionScoped cs(stream_critsect_.get()); return incoming_rate_; } bool IncomingVideoStream::IncomingVideoStreamThreadFun(void* obj) { return static_cast(obj)->IncomingVideoStreamProcess(); } bool IncomingVideoStream::IncomingVideoStreamProcess() { if (kEventError != deliver_buffer_event_->Wait(kEventMaxWaitTimeMs)) { CriticalSectionScoped cs(thread_critsect_.get()); if (incoming_render_thread_ == NULL) { // Terminating return false; } // Get a new frame to render and the time for the frame after this one. VideoFrame frame_to_render; uint32_t wait_time; { CriticalSectionScoped cs(buffer_critsect_.get()); frame_to_render = render_buffers_->FrameToRender(); wait_time = render_buffers_->TimeToNextFrameRelease(); } // Set timer for next frame to render. if (wait_time > kEventMaxWaitTimeMs) { wait_time = kEventMaxWaitTimeMs; } deliver_buffer_event_->StartTimer(false, wait_time); if (frame_to_render.IsZeroSize()) { if (render_callback_) { if (last_render_time_ms_ == 0 && !start_image_.IsZeroSize()) { // We have not rendered anything and have a start image. temp_frame_.CopyFrame(start_image_); render_callback_->RenderFrame(stream_id_, temp_frame_); } else if (!timeout_image_.IsZeroSize() && last_render_time_ms_ + timeout_time_ < TickTime::MillisecondTimestamp()) { // Render a timeout image. temp_frame_.CopyFrame(timeout_image_); render_callback_->RenderFrame(stream_id_, temp_frame_); } } // No frame. return true; } // Send frame for rendering. if (external_callback_) { external_callback_->RenderFrame(stream_id_, frame_to_render); } else if (render_callback_) { render_callback_->RenderFrame(stream_id_, frame_to_render); } // We're done with this frame. if (!frame_to_render.IsZeroSize()) last_render_time_ms_ = frame_to_render.render_time_ms(); } return true; } } // namespace webrtc src/roseExtensions/roseHPCToolkit/src/sage/metric.cc // -*- mode:C++; tab-width:8; indent-tabs-mode:nil -*- /*! * \file src/sage/metric.cc * \brief Implements metric attribute support for Sage III trees. * \ingroup ROSEHPCT_SAGE * * $Id: metric.cc,v 1.1 2008/01/08 02:56:43 dquinlan Exp $ */ /* * This software was produced with support in part from the Defense Advanced * Research Projects Agency (DARPA) through AFRL Contract FA8650-09-C-1915. * Nothing in this work should be construed as reflecting the official policy * or position of the Defense Department, the United States government, * or Rice University. */ #include "sage3basic.h" #include "rosehpct/util/general.hh" #include "rosehpct/sage/sage.hh" /* ---------------------------------------------------------------- */ using namespace std; using namespace GenUtil; using namespace RoseHPCT; /* ---------------------------------------------------------------- */ MetricAttr * RoseHPCT::getMetric (const string& metric_name, SgNode* node) { if (node->attributeExists (metric_name)) { AstAttribute* raw_attr = node->getAttribute (metric_name); return dynamic_cast (raw_attr); } return 0; // not found } /* ---------------------------------------------------------------- */ MetricAttr::MetricAttr (void) : name_ ("") { } MetricAttr::MetricAttr (const std::string& name, double value, bool is_derived) // : MetricAttribute(value,false), name_ (name) : MetricAttribute(value, is_derived), name_ (name) // DXN { } MetricAttr * MetricAttr::clone (void) const { return new MetricAttr (*this); } MetricAttr& MetricAttr::operator+= (const MetricAttr& b) { if (name_ == "") name_ = b.name_; else if (b.name_ != "" && b.name_ != name_) { name_ = ""; // this is an error, so turn self into empty attribute value_ = 0; is_derived_ = false; return *this; } value_ += b.value_; is_derived_ = true; return *this; } std::string MetricAttr::getName () const { return name_; } /*! * * The sum is the simple sum, value(a) + value(b), if and only if * name(a) equals name(b), or one or both of name(a), name(b) is * the empty string. Otherwise, the returned metric has an empty * name and a value of 0. * * \note By the condition above, the sum of many attributes with * differing names is not well-defined. */ MetricAttr RoseHPCT::operator+ (const MetricAttr& a, const MetricAttr& b) { MetricAttr sum_attr (a); sum_attr += b; return sum_attr; } /* eof */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include int main(int, char*[]) { vtkNew colors; // A nifty way of setting backgrounds in multiple renderers vtkNew colorSeries; colorSeries->SetColorSchemeByName("Brewer Qualitative Pastel2"); colors->SetColor("ren0", colorSeries->GetColor(0)); colors->SetColor("ren1", colorSeries->GetColor(1)); colors->SetColor("ren2", colorSeries->GetColor(2)); colors->SetColor("ren3", colorSeries->GetColor(3)); vtkNew pointSource; pointSource->SetNumberOfPoints(50); pointSource->Update(); std::cout << "There are " << pointSource->GetOutput()->GetNumberOfPoints() << " input points." << std::endl; vtkNew ids1; ids1->SetNumberOfComponents(1); // Set values for (unsigned int i = 10; i < 20; i++) { ids1->InsertNextValue(i); } vtkNew ids2; ids2->SetNumberOfComponents(1); for (unsigned int i = 15; i < 30; i++) { ids2->InsertNextValue(i); } vtkNew selectionNode1; selectionNode1->SetFieldType(vtkSelectionNode::POINT); selectionNode1->SetContentType(vtkSelectionNode::INDICES); selectionNode1->SetSelectionList(ids1); vtkNew selectionNode2; selectionNode2->SetFieldType(vtkSelectionNode::POINT); selectionNode2->SetContentType(vtkSelectionNode::INDICES); selectionNode2->SetSelectionList(ids2); vtkNew selection1; selection1->AddNode(selectionNode1); vtkNew selection2; selection2->AddNode(selectionNode2); vtkNew selectionCombined; selectionCombined->AddNode(selectionNode1); selectionCombined->Union(selectionNode2); std::cout << "There are " << selectionCombined->GetNumberOfNodes() << " nodes." << std::endl; vtkNew extractSelection1; extractSelection1->SetInputConnection(0, pointSource->GetOutputPort()); extractSelection1->SetInputData(1, selection1); extractSelection1->Update(); vtkNew extractSelection2; extractSelection2->SetInputConnection(0, pointSource->GetOutputPort()); extractSelection2->SetInputData(1, selection2); extractSelection2->Update(); vtkNew extractSelectionCombined; extractSelectionCombined->SetInputConnection(0, pointSource->GetOutputPort()); extractSelectionCombined->SetInputData(1, selectionCombined); extractSelectionCombined->Update(); // In selection vtkDataSet* ds = dynamic_cast(extractSelectionCombined->GetOutput()); std::cout << "There are " << ds->GetNumberOfPoints() << " points in the selection." << std::endl; std::cout << "There are " << ds->GetNumberOfCells() << " cells in the selection." << std::endl; /* // Not in selection selectionNode1->GetProperties()->Set(vtkSelectionNode::INVERSE(), 1); //invert the selection selectionNode2->GetProperties()->Set(vtkSelectionNode::INVERSE(), 1); //invert the selection extractSelection->Update(); std::cout << "There are " << dynamic_cast (extractSelection->GetOutput())->GetNumberOfPoints() << " points not in the selection." << std::endl; */ // Visualize vtkNew mapperOriginal; mapperOriginal->SetInputConnection(pointSource->GetOutputPort()); mapperOriginal->ScalarVisibilityOff(); vtkNew mapper1; mapper1->SetInputConnection(extractSelection1->GetOutputPort()); mapper1->ScalarVisibilityOff(); vtkNew mapper2; mapper2->SetInputConnection(extractSelection2->GetOutputPort()); mapper2->ScalarVisibilityOff(); vtkNew mapperCombined; mapperCombined->SetInputConnection(extractSelectionCombined->GetOutputPort()); mapperCombined->ScalarVisibilityOff(); vtkNew originalActor; originalActor->SetMapper(mapperOriginal); originalActor->GetProperty()->SetPointSize(5); originalActor->GetProperty()->SetColor(colors->GetColor3d("Black").GetData()); vtkNew actor1; actor1->SetMapper(mapper1); actor1->GetProperty()->SetPointSize(5); actor1->GetProperty()->SetColor(colors->GetColor3d("Black").GetData()); vtkNew actor2; actor2->SetMapper(mapper2); actor2->GetProperty()->SetPointSize(5); actor2->GetProperty()->SetColor(colors->GetColor3d("Black").GetData()); vtkNew actorCombined; actorCombined->SetMapper(mapperCombined); actorCombined->GetProperty()->SetPointSize(5); actorCombined->GetProperty()->SetColor(colors->GetColor3d("Black").GetData()); vtkNew renderWindow; renderWindow->SetSize(1000, 250); renderWindow->SetWindowName("MergeSelections"); vtkNew renderWindowInteractor; renderWindowInteractor->SetRenderWindow(renderWindow); double originalViewport[4] = {0.0, 0.0, 0.25, 1.0}; double selection1Viewport[4] = {0.25, 0.0, 0.5, 1.0}; double selection2Viewport[4] = {0.5, 0.0, 0.75, 1.0}; double selectionCombinedViewport[4] = {0.75, 0.0, 1.0, 1.0}; // Create a camera for all renderers vtkNew camera; vtkNew originalRenderer; originalRenderer->SetViewport(originalViewport); originalRenderer->SetBackground(colors->GetColor3d("Ren0").GetData()); originalRenderer->SetActiveCamera(camera); vtkNew selection1Renderer; selection1Renderer->SetViewport(selection1Viewport); selection1Renderer->SetBackground(colors->GetColor3d("Ren1").GetData()); selection1Renderer->SetActiveCamera(camera); vtkNew selection2Renderer; selection2Renderer->SetViewport(selection2Viewport); selection2Renderer->SetBackground(colors->GetColor3d("Ren2").GetData()); selection2Renderer->SetActiveCamera(camera); vtkNew selectionCombinedRenderer; selectionCombinedRenderer->SetViewport(selectionCombinedViewport); selectionCombinedRenderer->SetBackground( colors->GetColor3d("Ren3").GetData()); selectionCombinedRenderer->SetActiveCamera(camera); renderWindow->AddRenderer(originalRenderer); renderWindow->AddRenderer(selection1Renderer); renderWindow->AddRenderer(selection2Renderer); renderWindow->AddRenderer(selectionCombinedRenderer); originalRenderer->AddActor(originalActor); selection1Renderer->AddActor(actor1); selection2Renderer->AddActor(actor2); selectionCombinedRenderer->AddActor(actorCombined); originalRenderer->ResetCamera(); renderWindow->Render(); renderWindowInteractor->Start(); return EXIT_SUCCESS; } 1-10 #include "vn/port.h" namespace vn { namespace xplat { IPort::~IPort() { } } } 10-100 #include #include #include #include #include #include #include #include #ifdef __unix__ #include #define MAX_PATH 255 #else //windows #include #include #define getpid _getpid #endif //windows #include "metalicensor/base/logger.h" static FILE *logFile = NULL; static void timenow(char * buffer) { time_t rawtime; struct tm *timeinfo; time(&rawtime); timeinfo = localtime(&rawtime); strftime(buffer, 64, "%Y-%m-%d %H:%M:%S", timeinfo); } static std::string getLogFileName() { #ifdef __unix__ char const* folder = getenv("TMPDIR"); if(folder==0) folder = "/tmp"; return std::string(folder)+"/open-license.log"; #else wchar_t acBuffer[MAX_PATH]; int plen = GetTempPath(MAX_PATH,acBuffer); if(plen==0) { fprintf(stderr,"Error getting temporary directory path"); return std::string("open-license.log"); } const std::string sPath = std::wstring_convert>().to_bytes(acBuffer); return sPath+"/open-license.log"; #endif } void _log(const char* format, ...) { va_list args; char * buffer; if (logFile == NULL) { logFile = fopen(getLogFileName().c_str(), "a"); if (logFile == NULL) { //what shall we do here? return; } } buffer = (char *) malloc(sizeof(char) * strlen(format) + 64); timenow(buffer); sprintf(&buffer[strlen(buffer) - 1], "-[%d]-", getpid()); strcat(buffer, format); va_start(args, format); vfprintf(logFile, buffer, args); va_end(args); free(buffer); } void _shutdown_log() { if (logFile != NULL) { fclose(logFile); logFile = NULL; } } /*----------------------------------------------------------------------- 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. -----------------------------------------------------------------------*/ #include "RockFluidUnitFeature.h" #include "BoundaryFeature.h" #include "../prodml2_1/FluidCharacterization.h" #include "../tools/Misc.h" using namespace std; using namespace RESQML2_0_1_NS; using namespace gsoap_resqml2_0_1; const char* RockFluidUnitFeature::XML_TAG = "RockFluidUnitFeature"; RockFluidUnitFeature::RockFluidUnitFeature(COMMON_NS::DataObjectRepository* repo, const string & guid, const string & title, gsoap_resqml2_0_1::resqml20__Phase phase, BoundaryFeature* top, BoundaryFeature* bottom) { if (repo == nullptr) throw invalid_argument("The repo cannot be null."); gsoapProxy2_0_1 = soap_new_resqml20__obj_USCORERockFluidUnitFeature(repo->getGsoapContext()); _resqml20__RockFluidUnitFeature* rfuf = static_cast<_resqml20__RockFluidUnitFeature*>(gsoapProxy2_0_1); rfuf->Phase = phase; initMandatoryMetadata(); setMetadata(guid, title, std::string(), -1, std::string(), std::string(), -1, std::string()); repo->addOrReplaceDataObject(this); setTop(top); setBottom(bottom); } void RockFluidUnitFeature::setTop(BoundaryFeature* top) { getRepository()->addRelationship(this, top); static_cast<_resqml20__RockFluidUnitFeature*>(gsoapProxy2_0_1)->FluidBoundaryTop = top->newResqmlReference(); } BoundaryFeature* RockFluidUnitFeature::getTop() const { return repository->getDataObjectByUuid(static_cast<_resqml20__RockFluidUnitFeature*>(gsoapProxy2_0_1)->FluidBoundaryTop->UUID); } void RockFluidUnitFeature::setBottom(BoundaryFeature* bottom) { getRepository()->addRelationship(this, bottom); static_cast<_resqml20__RockFluidUnitFeature*>(gsoapProxy2_0_1)->FluidBoundaryBottom = bottom->newResqmlReference(); } BoundaryFeature* RockFluidUnitFeature::getBottom() const { return repository->getDataObjectByUuid(static_cast<_resqml20__RockFluidUnitFeature*>(gsoapProxy2_0_1)->FluidBoundaryBottom->UUID); } std::vector RockFluidUnitFeature::getFluidCharacterizationSet() const { return repository->getSourceObjects(this); } void RockFluidUnitFeature::loadTargetRelationships() { GeologicUnitFeature::loadTargetRelationships(); _resqml20__RockFluidUnitFeature* interp = static_cast<_resqml20__RockFluidUnitFeature*>(gsoapProxy2_0_1); gsoap_resqml2_0_1::eml20__DataObjectReference const * dor = interp->FluidBoundaryTop; if(dor != nullptr) { convertDorIntoRel(dor); } dor = interp->FluidBoundaryBottom; if(dor != nullptr) { convertDorIntoRel(dor); } } #ifndef Pds_HSD_FlashController_hh #define Pds_HSD_FlashController_hh #include "Globals.hh" #include #include namespace Pds { namespace HSD { class FlashController { public: void write (const char*); void verify(const char*); std::vector read(unsigned nwords); void test (); static void verbose(bool); static void useFifo(bool); public: void _write (const unsigned* p, unsigned nwords); void _write (const std::vector&); int _verify(const unsigned* p, unsigned nwords); int _verify(const std::vector&); void _read (std::vector&, unsigned nwords); private: vuint32_t _reserved0[3]; vuint32_t _destn; // user=0, safe=0xff vuint32_t _bytes_to_prog; vuint32_t _prog_fifo_cnt; vuint32_t _bytes_to_read; vuint32_t _reserved7[9]; vuint32_t _command; // b0 = flash_init/fifo_reset // b15 = start_read (unnecessary) // b17 = start_prog (unnecessary) vuint32_t _reserved17[15]; vuint32_t _data; }; }; }; #endif chessbot108/solved-problems //code by me #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include //#include //#include #include #define max_v 22000 #define int_max 0x3f3f3f3f #define cont continue #define pow_2(n) (1 << (n)) //tree #define lsb(n) ((n)&(-(n))) #define LC(n) (((n) << 1) + 1) #define RC(n) (((n) << 1) + 2) #define LOG2(n) ((int)(ceil(log2((n))))) using namespace std; void setIO(const string& file_name){ freopen((file_name+".in").c_str(), "r", stdin); freopen((file_name+".out").c_str(), "w+", stdout); } vector adj[max_v]; int ans[max_v], sum[max_v]; int n; int dfs(int cur, int p){ for(int u : adj[cur]){ if(u == p) cont; int temp = dfs(u, cur); if(temp > n/2) ans[cur] = true; sum[cur] += temp; } sum[cur]++; if(n - sum[cur] > n/2) ans[cur] = true; return sum[cur]; } int main(){ scanf("%d", &n); for(int i = 1; i class Map { private: char **rawMatrix; int column, row; int stage; public: Map(); char **getRawMatrix(); char **allocRawMatrix(); char positionMatrix(int posx, int posy); int getColumn(); void setColumn(int column); int getRow(); void setRow(int row); void addElement(int posx, int posy, char sprite); void importMap(); int getStage(); void setStage(int stage); }; #endif pythran/pythonic/include/cmath/tan.hpp #ifndef PYTHONIC_INCLUDE_CMATH_TAN_HPP #define PYTHONIC_INCLUDE_CMATH_TAN_HPP #include "pythonic/include/utils/functor.hpp" #include "pythonic/include/types/complex.hpp" #include PYTHONIC_NS_BEGIN namespace cmath { DEFINE_FUNCTOR_2(tan, std::tan); } PYTHONIC_NS_END #endif //Returns a sorted vector after sorting using priority queue vector HeapSortbypriorityQ (vector v) { priority_queue Q; vector ans(v.size()); for(int i=0;i #include #include "base/memory/ref_counted.h" #include "base/memory/scoped_ptr.h" #include "chrome/browser/safe_browsing/database_manager.h" #include "chrome/browser/safe_browsing/safe_browsing_service.h" #include "content/public/test/test_browser_thread_bundle.h" #include "testing/gtest/include/gtest/gtest.h" #include "testing/platform_test.h" #include "url/gurl.h" using content::TestBrowserThreadBundle; class SafeBrowsingDatabaseManagerTest : public PlatformTest { public: bool RunSBHashTest(const safe_browsing_util::ListType list_type, const std::vector& expected_threats, const std::string& result_list); private: TestBrowserThreadBundle thread_bundle_; }; bool SafeBrowsingDatabaseManagerTest::RunSBHashTest( const safe_browsing_util::ListType list_type, const std::vector& expected_threats, const std::string& result_list) { scoped_refptr sb_service_( SafeBrowsingService::CreateSafeBrowsingService()); scoped_refptr db_manager_( new SafeBrowsingDatabaseManager(sb_service_)); const SBFullHash same_full_hash = {}; SafeBrowsingDatabaseManager::SafeBrowsingCheck* check = new SafeBrowsingDatabaseManager::SafeBrowsingCheck( std::vector(), std::vector(1, same_full_hash), NULL, list_type, expected_threats); db_manager_->checks_.insert(check); const SBFullHashResult full_hash_result = { same_full_hash, safe_browsing_util::GetListId(result_list) }; std::vector fake_results(1, full_hash_result); bool result = db_manager_->HandleOneCheck(check, fake_results); db_manager_->checks_.erase(check); delete check; return result; } TEST_F(SafeBrowsingDatabaseManagerTest, CheckCorrespondsListType) { std::vector malware_threat(1, SB_THREAT_TYPE_BINARY_MALWARE_URL); EXPECT_FALSE(RunSBHashTest(safe_browsing_util::BINURL, malware_threat, safe_browsing_util::kMalwareList)); EXPECT_TRUE(RunSBHashTest(safe_browsing_util::BINURL, malware_threat, safe_browsing_util::kBinUrlList)); // Check for multiple threats std::vector multiple_threats; multiple_threats.push_back(SB_THREAT_TYPE_URL_MALWARE); multiple_threats.push_back(SB_THREAT_TYPE_URL_PHISHING); EXPECT_FALSE(RunSBHashTest(safe_browsing_util::MALWARE, multiple_threats, safe_browsing_util::kBinUrlList)); EXPECT_TRUE(RunSBHashTest(safe_browsing_util::MALWARE, multiple_threats, safe_browsing_util::kMalwareList)); } TEST_F(SafeBrowsingDatabaseManagerTest, GetUrlThreatType) { std::vector full_hashes; const GURL kMalwareUrl("http://www.malware.com/page.html"); const GURL kPhishingUrl("http://www.phishing.com/page.html"); const GURL kSafeUrl("http://www.safe.com/page.html"); const SBFullHash kMalwareHostHash = SBFullHashForString("malware.com/"); const SBFullHash kPhishingHostHash = SBFullHashForString("phishing.com/"); const SBFullHash kSafeHostHash = SBFullHashForString("www.safe.com/"); { SBFullHashResult full_hash; full_hash.hash = kMalwareHostHash; full_hash.list_id = static_cast(safe_browsing_util::MALWARE); full_hashes.push_back(full_hash); } { SBFullHashResult full_hash; full_hash.hash = kPhishingHostHash; full_hash.list_id = static_cast(safe_browsing_util::PHISH); full_hashes.push_back(full_hash); } EXPECT_EQ(SB_THREAT_TYPE_URL_MALWARE, SafeBrowsingDatabaseManager::GetHashThreatType( kMalwareHostHash, full_hashes)); EXPECT_EQ(SB_THREAT_TYPE_URL_PHISHING, SafeBrowsingDatabaseManager::GetHashThreatType( kPhishingHostHash, full_hashes)); EXPECT_EQ(SB_THREAT_TYPE_SAFE, SafeBrowsingDatabaseManager::GetHashThreatType( kSafeHostHash, full_hashes)); size_t index = 100; EXPECT_EQ(SB_THREAT_TYPE_URL_MALWARE, SafeBrowsingDatabaseManager::GetUrlThreatType( kMalwareUrl, full_hashes, &index)); EXPECT_EQ(0U, index); EXPECT_EQ(SB_THREAT_TYPE_URL_PHISHING, SafeBrowsingDatabaseManager::GetUrlThreatType( kPhishingUrl, full_hashes, &index)); EXPECT_EQ(1U, index); index = 100; EXPECT_EQ(SB_THREAT_TYPE_SAFE, SafeBrowsingDatabaseManager::GetUrlThreatType( kSafeUrl, full_hashes, &index)); EXPECT_EQ(100U, index); } /* * vi:ts=4:shiftwidth=4:expandtab * * iconvert.cpp - simple iconv() wrapper class * * Copyright (C) 2002 by <> * Begin : 02-Aug-2002 * Last Change : 24-Apr-2004. * * 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. */ #ifdef HAVE_CONFIG_H #include #endif #include #include #include #include "iconvert.hpp" #ifndef ICONV_CONST #warning ICONV_CONST not defined in config.h?. guessing from platform #if defined(__CYGWIN__) || defined(__FreeBSD__) || defined(WIN32) // mingw defines WIN32 #define ICONV_CONST const #endif #if defined(__linux__) #define ICONV_CONST #endif #endif // ICONV_CONST #if defined (WORDS_BIGENDIAN) #if (SIZEOF_UCHAR_T == 2) #define UCS_INTERNAL "UCS-2BE" #elif (SIZEOF_UCHAR_T == 4) #define UCS_INTERNAL "UCS-4BE" #else #warning unknown uchar_t size #endif #else // default is LITTLE-ENDIAN #if (SIZEOF_UCHAR_T == 2) #define UCS_INTERNAL "UCS-2LE" #elif (SIZEOF_UCHAR_T == 4) #define UCS_INTERNAL "UCS-4LE" #else #warning unknown uchar_t size #endif #endif IConvert::IConvert(const string& encoding) { m_iconv_from_unicode = iconv_open(encoding.c_str(),UCS_INTERNAL); m_iconv_to_unicode = iconv_open(UCS_INTERNAL,encoding.c_str()); if (m_iconv_from_unicode == (iconv_t)(-1) || m_iconv_to_unicode == (iconv_t)(-1)) { perror("iconv_open() failed"); throw std::runtime_error("iconv_open() failed"); } m_buffer = new char[BUFFER_SIZE]; } //IConvert::IConvert(const IConvert& rhs) { // m_encoding = rhs.m_encoding; // m_iconv_from_unicode = iconv_open(m_encoding.c_str(),UCS_INTERNAL); // m_iconv_to_unicode = iconv_open(UCS_INTERNAL,m_encoding.c_str()); // // if (m_iconv_from_unicode == (iconv_t)(-1) || // m_iconv_to_unicode == (iconv_t)(-1)) { // perror("iconv_open() failed"); // throw std::runtime_error("iconv_open() failed"); // } // m_buffer = new char[BUFFER_SIZE]; //} IConvert::~IConvert() { iconv_close(m_iconv_from_unicode); iconv_close(m_iconv_to_unicode); delete[] m_buffer; } bool IConvert::convert(const string& from, ustring& to) { size_t insize = 0; size_t outsize = 0; iconv(m_iconv_to_unicode, NULL, &insize, NULL, &outsize); insize = from.size(); outsize = BUFFER_SIZE; size_t ret; char* psrc = (char *)from.c_str(); char* pdest = m_buffer; ret = iconv(m_iconv_to_unicode, &psrc, &insize, &pdest, &outsize); if (ret == (size_t)(-1)) { return false; } else { to.assign((uchar_t*)m_buffer,(uchar_t*)pdest); //to.assign((wchar_t*)m_buffer,(BUFFER_SIZE - outsize)/(sizeof(wchar_t)*2)); return true; } } bool IConvert::convert(const ustring& from,string& to) { assert(!from.empty()); size_t insize = 0; size_t outsize = 0; iconv(m_iconv_from_unicode, NULL, &insize, NULL, &outsize); insize = from.size() * sizeof(uchar_t); outsize = BUFFER_SIZE; size_t ret; char* psrc = (char*)from.data(); char* pdest = m_buffer; ret = iconv(m_iconv_from_unicode, &psrc, &insize, &pdest, &outsize); if (ret == (size_t)(-1)) return false; else { to.assign(m_buffer,pdest); //to.assign(m_buffer,(BUFFER_SIZE - outsize)/sizeof(char)); return true; } } #pragma once #include #include #include #include "../global.hpp" class PapyrusFunctionRegistry { using VirtualMachine = RE::BSScript::Internal::VirtualMachine; const std::string className_; VirtualMachine* const vm_; public: explicit PapyrusFunctionRegistry( std::string_view className, VirtualMachine* const vm) : className_(className) , vm_(vm) {} template void registerFunction(std::string_view name, T fn) { LOG_INFO_FMT("Registering function: {}.{}()", className_, name); vm_->RegisterFunction(name, className_, fn); } }; #include using namespace std; int factorial(int n) { if(n==1||n==0) return 1; return n*factorial(n-1); } int fact(int n) { int f=1; for(int i=1;i<=n;i++) { f=f*i; } return f; } int main(void) { int x; cin>>x; cout<0 template class Pair{ T x; V y; public: void setX(T x) { this->x =x; } T getX() { return x; } void setY(V y) { this->y =y; } V getY() { return y; } };#include "Tetris.hpp" #include #include #include #include #include int const wBox = 32; int const hBox = 32; static int const gs_wGrid = 13; static int const gs_hGrid = 20; Color getColor(char block) { if (block == 0) { return {0, 0, 0}; } Color c = {uint8_t(block*25 + 70), uint8_t(block*25 + 70), uint8_t(block*25 + 70)}; return c; } void drawBlocks(SDL_Surface* screen, GridWithOffset& grid) { for (int y = 0; y < grid.getHeight(); y++) { for (int x = 0; x < grid.getWidth(); x++) { char block = grid(x, y); if (block == 0) { continue; } SDL_Rect r; r.w = wBox; r.h = hBox; r.x = (grid.getOffsetX() + x)*wBox; r.y = (grid.getOffsetY() + y)*hBox; Color color_raw = getColor(block); int R = color_raw.r; int G = color_raw.g; int B = color_raw.b; uint32_t color = SDL_MapRGB(screen->format, R, G, B); uint32_t color_lighter = SDL_MapRGB(screen->format, int(R*255.0/205), int(G*255.0/205), int(B*255.0/205)); uint32_t color_darker = SDL_MapRGB(screen->format, int(R*165.0/205), int(G*165.0/205), int(B*165.0/205)); SDL_FillRect(screen, &r, color); r.h = 5; SDL_FillRect(screen, &r, color_lighter); r.y += hBox - 5; SDL_FillRect(screen, &r, color_darker); r.h = hBox; r.w = 5; r.y = (grid.getOffsetY() + y)*hBox; SDL_FillRect(screen, &r, color_darker); r.x += wBox - 5; SDL_FillRect(screen, &r, color_lighter); } } } bool isPieceColliding(GridWithOffset const & background, GridWithOffset const & piece) { assert(background.getOffsetY() == 0); for (int y = 0; y < piece.getHeight(); y++) { for (int x = 0; x < piece.getWidth(); x++) { if (piece(x, y) != EMPTY) { int i = x + piece.getOffsetX(); int j = y + piece.getOffsetY(); if (background.isInside(i, j) && background(i, j) != EMPTY) { return true; } if (j >= background.getHeight()) { return true; } } } } return false; } bool isPieceOutsideBackground(GridWithOffset const & background, GridWithOffset const & piece) { for (int y = 0; y < piece.getHeight(); y++) { for (int x = 0; x < piece.getWidth(); x++) { if (piece(x, y) != EMPTY) { int i = x + piece.getOffsetX(); int j = y + piece.getOffsetY(); if (j < 0) { j = 0; } // allow piece above playing field if (!background.isInside(i, j)) { return true; } } } } return false; } std::vector getCompletedLines(GridWithOffset const & background) { assert(background.getOffsetX() == 0); assert(background.getOffsetY() == 0); std::vector completed; for (int y = 0; y < background.getHeight(); y++) { bool isFinished = true; for (int x = 0; x < background.getWidth(); x++) { if (background(x, y) == EMPTY) { isFinished = false; break; } } if (isFinished) { completed.push_back(y); } } return completed; } void copyToBackground(GridWithOffset& background, GridWithOffset const & grid) { for (int y = 0; y < grid.getHeight(); y++) { for (int x = 0; x < grid.getWidth(); x++) { if (grid(x, y) != EMPTY) { int i = x + grid.getOffsetX(); int j = y + grid.getOffsetY(); if (background.isInside(i, j)) { background(i, j) = grid(x, y); } } } } } int countVoidsNotFillableFromAbove(GridWithOffset const & background) { int numVoids = 0; for (int x = 0; x < background.getWidth(); x++) { bool haveHitFirstBlock = false; for (int y = 0; y < background.getHeight(); y++) { if (haveHitFirstBlock && background(x, y) == EMPTY) { numVoids++; } if (background(x, y) != EMPTY) { haveHitFirstBlock = true; } } } return numVoids; } bool Wanted::isOtherBetter(Wanted const & other) { return std::tie(other.voidPenalty, other.heightPenalty, other.xOffset, other.rotation) < std::tie(voidPenalty, heightPenalty, xOffset, rotation); } std::ostream & operator<<(std::ostream& out, Wanted const & w) { out << "{ \"voidPenalty\":" << w.voidPenalty << ", \"heightPenalty\":" << w.heightPenalty << ", \"xOffset\":" << w.xOffset << ", \"rotation\":" << w.rotation << "}"; return out; } Wanted getWanted(GridWithOffset const & background, std::vector piece) { // std::cout // << "\n========== getWanted(..) ==========\n" // << "Piece:" << piece << "\n" // << "Background:\n" << background << "\n"; // 1) Create as few voids as possible // 2) of those solutions, get the bit as low as possible int maxVoidPenalty = background.getWidth() * background.getHeight(); Wanted solution = {0, 0, maxVoidPenalty, background.getHeight()}; for (int x = -5; x < background.getWidth() + 5; x++) { for (int rotation = 0; rotation < int(piece.size()); rotation++) { GridWithOffset tmp = piece[rotation]; tmp.setOffset(x, 0); if (isPieceColliding(background, tmp)) { continue; } for (int y = 0; y < background.getHeight(); y++) // TODO: start from 0 { tmp.setOffset(x, y); if (isPieceColliding(background, tmp)) { break; } if (isPieceOutsideBackground(background, tmp)) { continue; } GridWithOffset bgCopy = background; copyToBackground(bgCopy, tmp); // The previous height was the last working one Wanted alternative = {rotation, x, countVoidsNotFillableFromAbove(bgCopy), bgCopy.getHeight() - 1 - tmp.getOffsetY()}; if (solution.isOtherBetter(alternative)) { // std::cout // << " solution: " << solution << " replaced by " << alternative << ":" // << bgCopy << "\n\n"; solution = alternative; } } } } // std::cout << "Winner: " << solution << "\n"; return solution; // TODO: throw exception if not possible??? } void tetris() { int w = gs_wGrid * wBox + 2; int h = gs_hGrid * hBox + 2; SDL_Surface* screen = setup_sdl(w, h); Slock(screen); GridWithOffset background(0, 0, gs_wGrid, gs_hGrid); // Add random blocks for (int y = background.getHeight() - 1; y < background.getHeight(); y++) { for (int x = 0; x < background.getWidth(); x++) { background(x, y) = rand() % 6; } } SDL_FillRect(screen, nullptr,SDL_MapRGB(screen->format, 0, 0, 0)); drawBlocks(screen, background); Sulock(screen); std::vector currentPiece = getRandomPiece(); GridWithOffset lastPiece(0, 0, 1, 1); int rotation = 0; int y = 0; int x = (gs_wGrid + 1) / 2; bool autoPlay = true; enum State { IS_ROTATING, IS_MOVING_SIDEWAYS, IS_FALLING, } state = IS_ROTATING; int cntr = 0; while (true) { //keyPresses=1; int const numMicroSleeps = 48; for (int j = 0; j < numMicroSleeps; j++) { cntr++; usleep(5000); if (keyPresses) { break; } if (autoPlay && state == IS_FALLING) { break; } } Slock(screen); SDL_FillRect(screen, nullptr, SDL_MapRGB(screen->format, 0, 0, 0)); // Get suggestion Wanted wanted = {}; if (autoPlay && state != IS_FALLING) { wanted = getWanted(background, currentPiece); } if (cntr > numMicroSleeps || state == IS_FALLING) { y++; cntr = std::max( 0, cntr - numMicroSleeps); } else { if (autoPlay) { if (keyPresses) { std::cout << "======================================\n"; if (state == IS_ROTATING) { if (rotation != wanted.rotation) { int newRotation = (rotation + 1) % currentPiece.size(); GridWithOffset & piece = currentPiece[newRotation]; piece.setOffset(x, y); if (!isPieceColliding(background, piece)) { rotation = newRotation; } } else { state = IS_MOVING_SIDEWAYS; } } if (state == IS_MOVING_SIDEWAYS) { if (x == wanted.xOffset) { state = IS_FALLING; } else { GridWithOffset & piece = currentPiece[rotation]; bool goRight = x < wanted.xOffset; piece.setOffset(goRight ? x + 1 : x - 1, y); if (!isPieceColliding(background, piece)) { x = piece.getOffsetX(); } } } if (state == IS_FALLING) { // } keyPresses = 0; } } else { int newRotation = (rotation+1) % currentPiece.size(); GridWithOffset & piece = currentPiece[newRotation]; piece.setOffset(x, y); if (!isPieceColliding(background, piece)) { rotation = newRotation; } } } GridWithOffset & piece = currentPiece[rotation]; piece.setOffset(x, y); if (isPieceColliding(background, piece)) { copyToBackground(background, lastPiece); currentPiece = getRandomPiece(); y = 0; x = (gs_wGrid + 1) / 2; rotation = 0; lastPiece = currentPiece[rotation]; if (isPieceColliding(background, lastPiece)) { quitting = true; usleep(500000); return; } state = IS_ROTATING; } else { drawBlocks(screen, piece); lastPiece = piece; } drawBlocks(screen, background); Sulock(screen); SDL_Flip(screen); std::vector completed = getCompletedLines(background); for (int const row : completed) { // move everything above row down one step, and put empty fields on top for (int x = 0; x < background.getWidth(); x++) { for (int y = row; y > 0; y--) { background(x, y) = background(x, y - 1); } background(x, 0) = EMPTY; } } drawBlocks(screen, background); Sulock(screen); SDL_Flip(screen); } sleep(1); } bluebackblue/brownie0  /** * Copyright (c) blueback * Released under the MIT License * https://github.com/bluebackblue/brownie/blob/master/LICENSE.txt * http://bbbproject.sakura.ne.jp/wordpress/mitlicense * @brief ファイルハンドル。 */ /** include */ #include /** include */ #include "./types.h" #include "./platform.h" /** include */ #include "./sharedptr.h" #include "./filehandle.h" #include "./filehandle_impl.h" #include "./stlstring.h" /** warning 4710 : この関数はインライン展開のために選択されましたが、コンパイラはインライン展開を実行しませんでした。 */ #pragma warning(disable:4710) /** NBlib */ namespace NBlib { /** constructor */ FileHandle::FileHandle() { this->impl.reset(new FileHandle_Impl()); } /** GetImpl */ sharedptr& FileHandle::GetImpl() { return this->impl; } /** destructor */ FileHandle::~FileHandle() { this->impl.reset(); } /** 読み込みモードで開く。 */ bool FileHandle::ReadOpen(const STLWString& a_filename) { return this->impl->ReadOpen(a_filename); } /** 書き込みモードで開く。 */ bool FileHandle::WriteOpen(const STLWString& a_filename) { return this->impl->WriteOpen(a_filename); } /** 閉じる。 */ void FileHandle::Close() { return this->impl->Close(); } /** 読み込み。 */ bool FileHandle::Read(u8* a_buffer,s64 a_size,s64 a_offset) { return this->impl->Read(a_buffer,a_size,a_offset); } /** 書き込み。 */ bool FileHandle::Write(const u8* a_buffer,s64 a_size,s64 a_offset) { return this->impl->Write(a_buffer,a_size,a_offset); } /** ファイルサイズ取得。 */ s64 FileHandle::GetSize() const { return this->impl->GetSize(); } /** ファイルオープンチェック。 */ bool FileHandle::IsOpen() const { return this->impl->IsOpen(); } /** EOF設定。 */ void FileHandle::SetEOF(s64 a_offset) { this->impl->SetEOF(a_offset); } } #include #include "arduinoserialwriter.h" int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); ArduinoSerialWriter arduino; if(arduino.connect()){ arduino.startLoop(); }else{ exit(0); } return a.exec(); } #include "apphost.h" #include "mmap.h" #include "simd\\SimdXml.hpp" typedef Simd::Xml::File File; typedef Simd::Xml::Document Document; typedef Simd::Xml::Node Node; void processXml() { auto xmlFile = mmap::create_shared("sample.xml"); if (nullptr == xmlFile) return; // open XML file char* xmlTmp = new char[xmlFile->size() + 1]; memcpy_s(xmlTmp, xmlFile->size(), xmlFile->data(), xmlFile->size()); xmlTmp[xmlFile->size()] = 0; Document doc; doc.Parse<0>(xmlTmp); //Simd::Xml::Detail::Print, char>(doc.FirstNode()); } void onLoad() { processXml(); } #include #include #include #include using namespace std; class Solution { private: // only used by dfs int *memo; int cols; public: // 1. dfs int numDistinct(string S, string T) { int ret = 0; cols = T.length(); int msize = S.length() * cols; memo = new int[msize]; memset(memo, -1, msize * sizeof(int)); ret = dfs(S, 0, T, 0); delete[] memo; return ret; } int dfs(string& S, int pa, string& T, int pb) { if (pb >= T.size()) { return 1; } if (pa >= S.size()) return 0; if (memo[pa * cols + pb] != -1) return memo[pa * cols + pb]; int r = 0; if (S[pa] == T[pb]) { r += dfs(S, pa + 1, T, pb + 1); } r += dfs(S, pa + 1, T, pb); memo[pa * cols + pb] = r; return r; } // 2. dynamic programming int _numDistinct(string S, string T) { int ret = 0; int rows = S.length() + 1; int cols = T.length() + 1; int* dp = new int[rows * cols]; for (int i=0; ix = x; this->y = y; } const std::string Vector2Int::toString() const { std::ostringstream str; str << "(" << x << "," << y << ")"; return str.str(); } satu0king/Leetcode-Solutions class Solution { public: int rob(vector &nums) { int n = nums.size(); if (n == 0) return 0; vector dp(n); for (int i = 0; i < n; i++) { // Lets rob i int ans1 = nums[i]; if (i >= 2) ans1 += dp[i - 2]; // and rob i - 2 or before // Lets not rob i int ans2 = 0; if (i >= 1) ans2 += dp[i - 1]; // and rob i - 1 or before dp[i] = max(ans1, ans2); } return dp[n - 1]; } }; // robIndex(n) // will call robIndex(n - 1) and robIndex(n - 2) // robIndex(n - 1) will call robIndex(n - 2) and robIndex(n - 3) // We are calling robIndex(n - 2) twice -> overhead // every function call splits into 2, and this happens N times // so complexity is 2 ^ N // 100 1 1 100 PowerOlive/mindsporemindspore/core/ops/embedding_lookup.cc /** * Copyright 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 #include "ops/embedding_lookup.h" #include "ops/op_utils.h" #include "utils/check_convert_utils.h" #include "abstract/primitive_infer_map.h" namespace mindspore { namespace ops { void EmbeddingLookup::Init(const bool setattr_flag) { this->set_setattr_flag(setattr_flag); } void EmbeddingLookup::set_setattr_flag(const bool setattr_flag) { (void)this->AddAttr(kSetattrFlag, MakeValue(setattr_flag)); } bool EmbeddingLookup::get_setattr_flag() const { auto value_ptr = GetAttr(kSetattrFlag); return GetValue(value_ptr); } AbstractBasePtr EmbeddingLookupInfer(const abstract::AnalysisEnginePtr &, const PrimitivePtr &primitive, const std::vector &input_args) { MS_EXCEPTION_IF_NULL(primitive); auto prim_name = primitive->name(); const int64_t input_num = 3; (void)CheckAndConvertUtils::CheckInteger("input number", SizeToLong(input_args.size()), kEqual, input_num, prim_name); for (const auto &item : input_args) { MS_EXCEPTION_IF_NULL(item); } auto params = input_args[0]->cast(); MS_EXCEPTION_IF_NULL(params); auto indices = input_args[1]->cast(); MS_EXCEPTION_IF_NULL(indices); const std::set int_valid_types = {kInt8, kInt16, kInt32, kInt64}; (void)CheckAndConvertUtils::CheckTensorTypeValid("indices type", indices->BuildType(), int_valid_types, prim_name); (void)CheckAndConvertUtils::CheckTensorTypeValid("offset", input_args[kInputIndex2]->BuildType(), int_valid_types, prim_name); MS_EXCEPTION_IF_NULL(params->shape()); auto params_shp = params->shape()->shape(); MS_EXCEPTION_IF_NULL(indices->shape()); auto indices_shp = indices->shape()->shape(); ShapeVector shape; (void)shape.insert(shape.end(), indices_shp.begin(), indices_shp.end()); (void)shape.insert(shape.end(), params_shp.begin() + 1, params_shp.end()); auto indices_max_shape = indices->shape()->max_shape(); ShapeVector max_shape; if (!indices_max_shape.empty()) { (void)max_shape.insert(max_shape.end(), indices_max_shape.begin(), indices_max_shape.end()); (void)max_shape.insert(max_shape.end(), params_shp.begin() + 1, params_shp.end()); } else { max_shape = shape; } auto indices_min_shape = indices->shape()->min_shape(); ShapeVector min_shape; if (!indices_min_shape.empty()) { (void)min_shape.insert(min_shape.end(), indices_min_shape.begin(), indices_min_shape.end()); (void)min_shape.insert(min_shape.end(), params_shp.begin() + 1, params_shp.end()); } else { min_shape = shape; } return std::make_shared(params->element(), std::make_shared(shape, min_shape, max_shape)); } REGISTER_PRIMITIVE_C(kNameEmbeddingLookup, EmbeddingLookup); } // namespace ops } // namespace mindspore #include "square.hpp" namespace Shogi { // clang-format off const std::array SquareList = { SQ11, SQ12, SQ13, SQ14, SQ15, SQ16, SQ17, SQ18, SQ19, SQ21, SQ22, SQ23, SQ24, SQ25, SQ26, SQ27, SQ28, SQ29, SQ31, SQ32, SQ33, SQ34, SQ35, SQ36, SQ37, SQ38, SQ39, SQ41, SQ42, SQ43, SQ44, SQ45, SQ46, SQ47, SQ48, SQ49, SQ51, SQ52, SQ53, SQ54, SQ55, SQ56, SQ57, SQ58, SQ59, SQ61, SQ62, SQ63, SQ64, SQ65, SQ66, SQ67, SQ68, SQ69, SQ71, SQ72, SQ73, SQ74, SQ75, SQ76, SQ77, SQ78, SQ79, SQ81, SQ82, SQ83, SQ84, SQ85, SQ86, SQ87, SQ88, SQ89, SQ91, SQ92, SQ93, SQ94, SQ95, SQ96, SQ97, SQ98, SQ99 }; const int32_t SquareToNum[] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, -1, -1, 9, 10, 11, 12, 13, 14, 15, 16, 17, -1, -1, 18, 19, 20, 21, 22, 23, 24, 25, 26, -1, -1, 27, 28, 29, 30, 31, 32, 33, 34, 35, -1, -1, 36, 37, 38, 39, 40, 41, 42, 43, 44, -1, -1, 45, 46, 47, 48, 49, 50, 51, 52, 53, -1, -1, 54, 55, 56, 57, 58, 59, 60, 61, 62, -1, -1, 63, 64, 65, 66, 67, 68, 69, 70, 71, -1, -1, 72, 73, 74, 75, 76, 77, 78, 79, 80, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, }; const Square InvSquare[] = { WALL00, WALL01, WALL02, WALL03, WALL04, WALL05, WALL06, WALL07, WALL08, WALL09, WALL0A, WALL10, SQ99, SQ98, SQ97, SQ96, SQ95, SQ94, SQ93, SQ92, SQ91, WALL1A, WALL20, SQ89, SQ88, SQ87, SQ86, SQ85, SQ84, SQ83, SQ82, SQ81, WALL2A, WALL30, SQ79, SQ78, SQ77, SQ76, SQ75, SQ74, SQ73, SQ72, SQ71, WALL3A, WALL40, SQ69, SQ68, SQ67, SQ66, SQ65, SQ64, SQ63, SQ62, SQ61, WALL4A, WALL50, SQ59, SQ58, SQ57, SQ56, SQ55, SQ54, SQ53, SQ52, SQ51, WALL5A, WALL60, SQ49, SQ48, SQ47, SQ46, SQ45, SQ44, SQ43, SQ42, SQ41, WALL6A, WALL70, SQ39, SQ38, SQ37, SQ36, SQ35, SQ34, SQ33, SQ32, SQ31, WALL7A, WALL80, SQ29, SQ28, SQ27, SQ26, SQ25, SQ24, SQ23, SQ22, SQ21, WALL8A, WALL90, SQ19, SQ18, SQ17, SQ16, SQ15, SQ14, SQ13, SQ12, SQ11, WALL9A, WALLA0, WALLA1, WALLA2, WALLA3, WALLA4, WALLA5, WALLA6, WALLA7, WALLA8, WALLA9, WALLAA, }; const ArrayMap fileToString({ { File1, "1" }, { File2, "2" }, { File3, "3" }, { File4, "4" }, { File5, "5" }, { File6, "6" }, { File7, "7" }, { File8, "8" }, { File9, "9" } }); const ArrayMap rankToString({ { Rank1, "一" }, { Rank2, "二" }, { Rank3, "三" }, { Rank4, "四" }, { Rank5, "五" }, { Rank6, "六" }, { Rank7, "七" }, { Rank8, "八" }, { Rank9, "九" } }); // clang-format on std::ostream& operator<<(std::ostream& os, Square sq) { os << SquareToFile[sq] << SquareToRank[sq]; return os; } } // namespace ShogiCode0100Food/CuteEngine #include "camera.h" #include #include #include Camera::Camera(int width, int height) { viewport_width = width; viewport_height = height; } QVector4D Camera::GetLeftRightBottomTop() { const float aspectRatio = float(viewport_width/viewport_height); const float alpha = qDegreesToRadians(fov * 0.5f); const float top = z_near * qTan(alpha); const float bottom = -top; const float right = top * aspectRatio; const float left = -right; QVector4D params(left,right,bottom,top); return params; } QVector3D Camera::ScreenPointToWorldRay(int x, int y) { QVector4D lrbt = GetLeftRightBottomTop(); const float l = lrbt.x(); const float r = lrbt.y(); const float b = lrbt.z(); const float t = lrbt.w(); const float ray_x = l +(r-l) * x/ viewport_width; const float ray_y = b + (t - b) * (viewport_height - y - 1) / viewport_height; const float ray_z = -z_near; QVector3D ray_viewspace = QVector3D(ray_x,ray_y,ray_z); PrepareMatrices(); QVector3D ray_world_space = QVector3D(world_matrix * QVector4D(ray_viewspace, 0.0f)); return ray_world_space; } void Camera::PrepareMatrices() { world_matrix.setToIdentity(); world_matrix.translate(position); world_matrix.rotate(yaw, QVector3D(0.0f,1.0f,0.0f)); world_matrix.rotate(pitch, QVector3D(1.0f,0.0f,0.0f)); view_matrix = world_matrix.inverted(); projection_matrix.setToIdentity(); projection_matrix.perspective(fov,float(viewport_width)/viewport_height, z_near, z_far); } /* *************************************************************************** Copyright (c): 2013 Hericus Software, Inc. License: The MIT License (MIT) Authors: *************************************************************************** */ #include "DataObjectTestMap.h" #include "DataObjectTestClass.h" using namespace Helix::Glob; #include #include #include #include using namespace SLib; static DataObjectTestMap* m_dotestmap = NULL; DataObjectTestMap::DataObjectTestMap(void) { EnEx ee(FL, "DataObjectTestMap::DataObjectTestMap(void)"); m_mut = new Mutex(); clearMap(); } DataObjectTestMap::DataObjectTestMap(const DataObjectTestMap& c) { EnEx ee(FL, "DataObjectTestMap::DataObjectTestMap(const DataObjectTestMap& c)"); // does nothing } DataObjectTestMap& DataObjectTestMap::operator=(const DataObjectTestMap& c) { EnEx ee(FL, "DataObjectTestMap::operator=(const DataObjectTestMap& c)"); // does nothing return *this; } DataObjectTestMap::~DataObjectTestMap(void) { EnEx ee(FL, "DataObjectTestMap::~DataObjectTestMap()"); clearMap(); delete m_mut; } DataObjectTestMap& DataObjectTestMap::getInstance() { EnEx ee(FL, "DataObjectTestMap::getInstance()"); if(m_dotestmap == NULL){ m_dotestmap = new DataObjectTestMap(); } return *m_dotestmap; } void DataObjectTestMap::addDataObjectTest(twine name, twine handler) { EnEx ee(FL, "DataObjectTestMap::addDataObjectTest()"); Lock theLock(m_mut); if(m_tests.count(name) > 0){ m_tests.erase(name); // replace it. } m_tests[name] = handler; } void DataObjectTestMap::clearMap() { EnEx ee(FL, "DataObjectTestMap::clearMap()"); Lock theLock(m_mut); m_tests.clear(); } DataObjectTestClass* DataObjectTestMap::findDOTest(twine name) { EnEx ee(FL, "DataObjectTestMap::findAction()"); Lock theLock(m_mut); if(m_tests.count(name) > 0){ twine doTestHandler = m_tests[name]; DataObjectTestClass* ret = DataObjectTestClassFactory::createInstance(doTestHandler); return ret; } else { return NULL; } } vector > DataObjectTestMap::listHandlers() { EnEx ee(FL, "DataObjectTestMap::listHandlers()"); Lock theLock(m_mut); vector > ret; map::iterator it; for(it = m_tests.begin(); it != m_tests.end(); it++){ pair elem; elem.first = it->second; elem.second = it->first; ret.push_back( elem ); } return ret; } tracer/Helpers.cpp /** * This file defines helper functions and instrumentation functions that may be useful for any trace format. * This includes functions to get the source/function names, get source/destination operand information for * an instruction. Additionally the image instrumentation function which is called whenever an image is * loaded by the executable is defined in here. This is because we typically don't need to do any format * specific processing in there, unlike the instruction instrumentation. **/ #include #include #include #include #include #include #include "RegVector.h" #include "Helpers.h" extern "C" { #include "LynxReg.h" #include "XedLynxReg.h" #include "xed-interface.h" #include "xed-flags.h" #include "xed-decoded-inst-api.h" } using std::map; using std::cerr; ADDRINT entryPoint; map apiMap; string unknownStr = "Unknown"; string emptyStr = ""; ShadowMemory mem; PIN_MUTEX traceLock; PIN_MUTEX dataLock; PIN_MUTEX errorLock; TLS_KEY tlsKey; /** * Function: extraceFilename * Description: Extracts a file name from a path by looking for the last instance of a '/' or '\' * Output: String with paths removed **/ std::string extractFilename(const std::string &filename) { unsigned long lastBackslash = #ifdef TARGET_WINDOWS filename.rfind("\\"); #else filename.rfind("/"); #endif return (lastBackslash == std::string::npos) ? filename : filename.substr(lastBackslash + 1); } /** * Function: getSrcDestInfo * Description: Gets information about the sources and destinations of a function. There's a lot of code here * to do this, but it's necessary. I've tried my best to include comments outlining what each part is doing. * Note, we can get the exact registers that will be used, but we won't know memory addresses until runtime, * so we can only count the number of times a particular a memory read/write occurs * Side Effects: Populates srcRegs, destRegs, memReadOps, memWriteOps and destFlags * Output: None **/ void getSrcDestInfo(INS &ins, RegVector *srcRegs, RegVector *destRegs, UINT32 &memReadOps, UINT32 &memWriteOps, UINT32 &destFlags) { xed_decoded_inst_t* xedIns = INS_XedDec(ins); const xed_simple_flag_t *flags = xed_decoded_inst_get_rflags_info(xedIns); if(flags != NULL) { //srcFlags = (unsigned int)(flags->read.flat) & 0x3fffff; destFlags = (unsigned int) (flags->written.flat) & 0x3fffff; } if(INS_Opcode(ins) != XED_ICLASS_NOP) { int numOps = INS_OperandCount(ins); for(int i = 0; i < numOps; ++i) { //If memory, increment memory counters and add base, index and segment registers to srcRegs if(INS_OperandIsMemory(ins, i)) { if(INS_OperandReadAndWritten(ins, i)) { ++memWriteOps; ++memReadOps; } else if(INS_OperandWritten(ins, i)) { ++memWriteOps; } else { ++memReadOps; } REG r = INS_OperandMemoryBaseReg(ins, i); if(REG_valid(r) && r != REG_INST_PTR) { srcRegs->insert(r); } r = INS_OperandMemoryIndexReg(ins, i); if(REG_valid(r) && r != REG_INST_PTR) { srcRegs->insert(r); } r = INS_OperandMemorySegmentReg(ins, i); if(REG_valid(r) && r != REG_INST_PTR) { srcRegs->insert(r); } } //If register, just add reg to approprate list else if(INS_OperandIsReg(ins, i)) { REG r = INS_OperandReg(ins, i); if(r != REG_INST_PTR && r != REG_GFLAGS) { if(INS_OperandReadAndWritten(ins, i)) { srcRegs->insert(r); destRegs->insert(r); } else if(INS_OperandWritten(ins, i)) { destRegs->insert(r); } else { srcRegs->insert(r); } } } //We don't need immediate values else if(INS_OperandIsImmediate(ins, i)) { // immediateVals.push_back(INS_OperandImmediate(ins, i)); } //Stuff gets complicated here. Some instructions have side effects and implicitly read/write // particular values. These values are fetched here. Unfortunately we cannot interface with // pin to get these values, they come from XED. So we first try to transform easy registers. // If we can't then there are some architecture specific registers that we deal with // separately (some need to be added to xedReg2LynxReg). If we still can't find the register // we print out an error so it can be added else if(INS_OperandIsImplicit(ins, i)) { const xed_operand_t *op = xed_inst_operand(xedIns->_inst, i); if(op->_type == XED_OPERAND_TYPE_REG) { LynxReg r = xedReg2LynxReg_nopseudo(op->_u._reg); if(r == LYNX_INVALID) { if(op->_u._reg == XED_REG_STACKPUSH || op->_u._reg == XED_REG_STACKPOP) { #if defined(TARGET_IA32E) || defined(TARGET_MIC) srcRegs->insert(LYNX_RSP); destRegs->insert(LYNX_RSP); #else srcRegs->insert(LYNX_ESP); destRegs->insert(LYNX_ESP); #endif } else if(op->_u._reg == XED_REG_X87STATUS) { if(op->_rw == XED_OPERAND_ACTION_R || op->_rw == XED_OPERAND_ACTION_CR) { srcRegs->insert(LYNX_FPSW); } else if(op->_rw == XED_OPERAND_ACTION_W || op->_rw == XED_OPERAND_ACTION_CW) { destRegs->insert(LYNX_FPSW); } else if(op->_rw == XED_OPERAND_ACTION_RW || op->_rw == XED_OPERAND_ACTION_CRW || op->_rw == XED_OPERAND_ACTION_RCW) { srcRegs->insert(LYNX_FPSW); destRegs->insert(LYNX_FPSW); } else { fprintf(errorFile, "invalid operand action for %s %s\n", INS_Disassemble(ins).c_str(), xed_reg_enum_t2str(op->_u._reg)); } } else if(op->_u._reg == XED_REG_X87CONTROL) { if(op->_rw == XED_OPERAND_ACTION_R || op->_rw == XED_OPERAND_ACTION_CR) { srcRegs->insert(LYNX_FPCW); } else if(op->_rw == XED_OPERAND_ACTION_W || op->_rw == XED_OPERAND_ACTION_CW) { destRegs->insert(LYNX_FPCW); } else if(op->_rw == XED_OPERAND_ACTION_RW || op->_rw == XED_OPERAND_ACTION_CRW || op->_rw == XED_OPERAND_ACTION_RCW) { srcRegs->insert(LYNX_FPCW); destRegs->insert(LYNX_FPCW); } else { fprintf(errorFile, "invalid operand action for %s %s\n", INS_Disassemble(ins).c_str(), xed_reg_enum_t2str(op->_u._reg)); } } else if(op->_u._reg == XED_REG_X87TAG) { if(op->_rw == XED_OPERAND_ACTION_R || op->_rw == XED_OPERAND_ACTION_CR) { srcRegs->insert(LYNX_FPTAG_FULL); } else if(op->_rw == XED_OPERAND_ACTION_W || op->_rw == XED_OPERAND_ACTION_CW) { destRegs->insert(LYNX_FPTAG_FULL); } else if(op->_rw == XED_OPERAND_ACTION_RW || op->_rw == XED_OPERAND_ACTION_CRW || op->_rw == XED_OPERAND_ACTION_RCW) { srcRegs->insert(LYNX_FPTAG_FULL); destRegs->insert(LYNX_FPTAG_FULL); } else { fprintf(errorFile, "invalid operand action for %s %s\n", INS_Disassemble(ins).c_str(), xed_reg_enum_t2str(op->_u._reg)); } } else if(op->_u._reg == XED_REG_X87PUSH) { destRegs->insert(LYNX_ST0); destRegs->insert(LYNX_FPSW); } else if(op->_u._reg == XED_REG_X87POP) { srcRegs->insert(LYNX_ST0); destRegs->insert(LYNX_FPSW); } else if(op->_u._reg == XED_REG_TSC || op->_u._reg == XED_REG_TMP3) { //skip } else { fprintf(errorFile, "Unknown Register in %s: %s\n", INS_Disassemble(ins).c_str(), xed_reg_enum_t2str(op->_u._reg)); } } else { fprintf(errorFile, "%s: %s\n", INS_Disassemble(ins).c_str(), xed_reg_enum_t2str(op->_u._reg)); if(op->_rw == XED_OPERAND_ACTION_R || op->_rw == XED_OPERAND_ACTION_CR) { srcRegs->insert(r); } else if(op->_rw == XED_OPERAND_ACTION_W || op->_rw == XED_OPERAND_ACTION_CW) { destRegs->insert(r); } else if(op->_rw == XED_OPERAND_ACTION_RW || op->_rw == XED_OPERAND_ACTION_CRW || op->_rw == XED_OPERAND_ACTION_RCW) { srcRegs->insert(r); destRegs->insert(r); } else { fprintf(errorFile, "invalid operand action for %s %s\n", INS_Disassemble(ins).c_str(), xed_reg_enum_t2str(op->_u._reg)); } } } //I don't know why, but sometimes XED doesn't treat these like registers, and we have to // interpret the non-terminal else if(op->_type == XED_OPERAND_TYPE_NT_LOOKUP_FN) { LynxReg r = LYNX_INVALID; switch(op->_u._nt) { case XED_NONTERMINAL_AR10: #if defined(TARGET_IA32E) || defined(TARGET_MIC) r = LYNX_R10; #else assert(0); #endif break; case XED_NONTERMINAL_AR11: #if defined(TARGET_IA32E) || defined(TARGET_MIC) r = LYNX_R11; #else assert(0); #endif break; case XED_NONTERMINAL_AR12: #if defined(TARGET_IA32E) || defined(TARGET_MIC) r = LYNX_R12; #else assert(0); #endif break; case XED_NONTERMINAL_AR13: #if defined(TARGET_IA32E) || defined(TARGET_MIC) r = LYNX_R13; #else assert(0); #endif break; case XED_NONTERMINAL_AR14: #if defined(TARGET_IA32E) || defined(TARGET_MIC) r = LYNX_R14; #else assert(0); #endif break; case XED_NONTERMINAL_AR15: #if defined(TARGET_IA32E) || defined(TARGET_MIC) r = LYNX_R15; #else assert(0); #endif break; case XED_NONTERMINAL_AR8: #if defined(TARGET_IA32E) || defined(TARGET_MIC) r = LYNX_R8; #else assert(0); #endif break; case XED_NONTERMINAL_AR9: #if defined(TARGET_IA32E) || defined(TARGET_MIC) r = LYNX_R9; #else assert(0); #endif break; case XED_NONTERMINAL_ARAX: #if defined(TARGET_IA32E) || defined(TARGET_MIC) r = LYNX_RAX; #else r = LYNX_EAX; #endif break; case XED_NONTERMINAL_ARBP: #if defined(TARGET_IA32E) || defined(TARGET_MIC) r = LYNX_RBP; #else r = LYNX_EBP; #endif break; case XED_NONTERMINAL_ARBX: #if defined(TARGET_IA32E) || defined(TARGET_MIC) r = LYNX_RBX; #else r = LYNX_EBX; #endif break; case XED_NONTERMINAL_ARCX: #if defined(TARGET_IA32E) || defined(TARGET_MIC) r = LYNX_RCX; #else r = LYNX_ECX; #endif break; case XED_NONTERMINAL_ARDI: #if defined(TARGET_IA32E) || defined(TARGET_MIC) r = LYNX_RDI; #else r = LYNX_EDI; #endif break; case XED_NONTERMINAL_ARDX: #if defined(TARGET_IA32E) || defined(TARGET_MIC) r = LYNX_RDX; #else r = LYNX_EDX; #endif break; case XED_NONTERMINAL_ARSI: #if defined(TARGET_IA32E) || defined(TARGET_MIC) r = LYNX_RSI; #else r = LYNX_ESI; #endif break; case XED_NONTERMINAL_ARSP: case XED_NONTERMINAL_SRSP: #if defined(TARGET_IA32E) || defined(TARGET_MIC) r = LYNX_RSP; #else r = LYNX_ESP; #endif break; default: break; } // if we can't find the register, print an error if(r == LYNX_INVALID) { fprintf(errorFile, "implicit NT operand %s %s %d %d\n", INS_Disassemble(ins).c_str(), xed_operand_enum_t2str((xed_operand_enum_t)op->_name), op->_rw, op->_u._nt); } else { if(op->_rw == XED_OPERAND_ACTION_R || op->_rw == XED_OPERAND_ACTION_CR) { srcRegs->insert(r); } else if(op->_rw == XED_OPERAND_ACTION_W || op->_rw == XED_OPERAND_ACTION_CW) { destRegs->insert(r); } else if(op->_rw == XED_OPERAND_ACTION_RW || op->_rw == XED_OPERAND_ACTION_CRW || op->_rw == XED_OPERAND_ACTION_RCW) { srcRegs->insert(r); destRegs->insert(r); } else { fprintf(errorFile, "invalid operand action for %s %s\n", INS_Disassemble(ins).c_str(), xed_nonterminal_enum_t2str(op->_u._nt)); } } } //if not a register or a non-terminal, print an error else { fprintf(errorFile, "implicit operand %s %s %d\n", INS_Disassemble(ins).c_str(), xed_operand_enum_t2str((xed_operand_enum_t)op->_name), op->_type); } } //This doesn't need to be in the trace else if(INS_OperandIsBranchDisplacement(ins, i)) { //fprintf(errorFile, "Branch Displacement\n"); } //Have never seen this pop up, I think it's handled by the memory case but I'm not sure else if(INS_OperandIsFixedMemop(ins, i)) { fprintf(errorFile, "Fixed Memory Op\n"); //skip } //This is used for the lea instruction. We just need to get the base, index and segment register else if(INS_OperandIsAddressGenerator(ins, i)) { REG r = INS_OperandMemoryBaseReg(ins, i); if(REG_valid(r) && r != REG_INST_PTR) { srcRegs->insert(r); } r = INS_OperandMemoryIndexReg(ins, i); if(REG_valid(r) && r != REG_INST_PTR) { srcRegs->insert(r); } r = INS_OperandMemorySegmentReg(ins, i); if(REG_valid(r) && r != REG_INST_PTR) { srcRegs->insert(r); } } //anything else is caught here else { fprintf(errorFile, "UNKNOWN OPERAND: %s\n", INS_Disassemble(ins).c_str()); } } /**Set XED corrections here**/ if(INS_Opcode(ins) == XED_ICLASS_FNSTENV) { srcRegs->insert(LYNX_FPCW); srcRegs->insert(LYNX_FPSW); srcRegs->insert(LYNX_FPTAG_FULL); srcRegs->insert(LYNX_FPIP_SEL); srcRegs->insert(LYNX_FPIP_OFF); srcRegs->insert(LYNX_FPDP_SEL); srcRegs->insert(LYNX_FPDP_OFF); srcRegs->insert(LYNX_FPOPCODE); destRegs->insert(LYNX_FPCW); } if(INS_Opcode(ins) == XED_ICLASS_FLDENV) { destRegs->insert(LYNX_FPCW); destRegs->insert(LYNX_FPSW); destRegs->insert(LYNX_FPTAG_FULL); destRegs->insert(LYNX_FPIP_SEL); destRegs->insert(LYNX_FPIP_OFF); destRegs->insert(LYNX_FPDP_SEL); destRegs->insert(LYNX_FPDP_OFF); destRegs->insert(LYNX_FPOPCODE); } } } /** * Function: getSrcName * Description: Extracts the name of the executable/library that was the source of the instruction. If * PIN can't determine the source, uses Unknown (dynamically modified code). * Side Effects: Fills in srcStr (that way srcStr can be dynamically allocated if required) * Outputs: none **/ void getSrcName(IMG img, string &srcStr) { if(IMG_Valid(img)) { srcStr = extractFilename(IMG_Name(img)); } else { srcStr = unknownStr; } } /** * Function getFnName * Description: Extracts the name of the function that the instruction belongs to. If the function can't be * found, uses the empty string * Side Effects: Fills in fnStr (that way it can be dynamically allocated if necessary) * Outputs: None **/ void getFnName(RTN rtn, IMG img, string &fnStr) { if(IMG_Valid(img)) { ADDRINT rtnAddr = RTN_Address(rtn); if(apiMap.find(rtnAddr) != apiMap.end()) { fnStr = apiMap[rtnAddr]; } else { fnStr = emptyStr; } } else { fnStr = emptyStr; } } /** * Function: imgInstrumentation * Description: The instrumentation for when an image is loaded. Currently all this does is iterate over the * symbols loaded by the image, and puts the addresses and names in a map. If we execute this address, then * we say we are executing that function (It seems like PIN is only giving me the symbols for functions * anyway? It's a big thing, I'd rather not get into it). Currently there is some commented out code, I'm * leaving that in there because it's part of the process of trying to figure out how to get global/dynamic * data. * Side Effects: populates apiMap with function names * Outputs: None * void imgInstrumentation(IMG img, void *v) { printf("img %s %llx %lx\n", IMG_Name(img).c_str(), (unsigned long long) IMG_LoadOffset(img), (unsigned long) IMG_SizeMapped(img)); if(IMG_SecHead(img) == IMG_SecTail(img)) { printf("No sections\n"); } for(SEC sec = IMG_SecHead(img); sec != IMG_SecTail(img); sec = SEC_Next(sec)) { printf("%llx %lx %d ", (unsigned long long) SEC_Address(sec), (unsigned long) SEC_Size(sec), SEC_Type(sec)); if(SEC_IsReadable(sec)) { printf("r"); } if(SEC_IsWriteable(sec)) { printf("w"); } if(SEC_IsExecutable(sec)) { printf("x"); } printf("\n"); } for(SYM sym = IMG_RegsymHead(img); SYM_Valid(sym); sym = SYM_Next(sym)) { string undFuncName = PIN_UndecorateSymbolName(SYM_Name(sym), UNDECORATION_NAME_ONLY); ADDRINT symAddr = SYM_Address(sym); if(apiMap.find(symAddr) == apiMap.end()) { apiMap[symAddr] = undFuncName.c_str(); } } if(IMG_IsMainExecutable(img)) { int fd = fopen(IMG_NAME(img).c_str(), "rb"); Elf *elf = elf_begin(fd, ELF_C_READ, NULL); if(elf == NULL) { fprintf(stderr, "panic\n"); } GElf_Ehdr elfHeader; if(gelf_getehdr(elf, &elfHeader) == NULL) { fprintf(stderr, "panic\n"); } uint64_t elfEntry = elfHeader.e_entry(); entryPoint = IMG_EntryAddress(img); uint64_t reloc = entryPoint - elfEntry; int numSegments; if(elf_getphdrnum(elf, &n)) { fprintf(stderr, "panic\n"); } segmentInfo = ; for(int i = 0; i < n; i++) { GElf_Phdr segment; if(gelf_getphdr (elf, i, &segment) != &segment) { if(segment.p_type == PT_LOAD) { segment.p_vaddr + reloc; segment.p_memsz; segment.p_align; segment.p_flags; } } } } }*/ /** * Function: setupLocks * Description: Sets up file locks. * Output: None **/ void setupLocks() { PIN_MutexInit(&traceLock); PIN_MutexInit(&dataLock); PIN_MutexInit(&errorLock); } #include using namespace std; typedef struct Point{ double x; double y; void Initialiser(double , double); void Afficher(); void Deplacer(double, double); }Point; void Point :: Initialiser(double a, double b){ x=a; y=b; } void Point :: Deplacer(double dx, double dy){ x+=dx; y+=dy; } void Point :: Afficher(){ cout << "(" << x << "," << y << ")\n" ; } int main(){ Point P; P.Initialiser(12.2,12.1122); P.Afficher(); P.y= 12.2; P.Afficher(); P.Deplacer(1,1); P.Afficher(); return 0; } #include "ghthread.h" #include void setList(std::vector &task_list){ task_list.push_back(task{false,"测试_定位","../config/disc/task_disc/TEST_LOCATE.ghs",SCRIPT::TEST_LOCATE,nullptr}); task_list.push_back(task{false,"测试_传送","../config/disc/task_disc/TEST_TP.ghs",SCRIPT::TEST_TP,nullptr}); task_list.push_back(task{false,"测试_实时定位","../config/disc/task_disc/TEST_TRACK.ghs",SCRIPT::TEST_TRACK,nullptr}); task_list.push_back(task{false,"测试_截一张图","../config/disc/task_disc/TEST_CAP.ghs",SCRIPT::TEST_CAP,nullptr}); task_list.push_back(task{false,"钓鱼自动提杆","../config/disc/task_disc/AUTO_FISH.ghs",SCRIPT::AUTO_FISH,nullptr}); } GHthread::GHthread() { } void GHthread::setup(TransparentWidget *log){ this->GHwindow.setup(log); this->GHmap.setup(&(this->GHwindow)); } void GHthread::test() { cv::Mat test = cv::Mat::zeros(100, 100, CV_8UC3);; cv::imwrite("in.png",test); } bool GHthread::start_task(std::vector task_list){ if (running){ running = false; busy = true; this->GHwindow.push_log("正在结束任务..."); this->_ending = std::thread([this]{ wait_task_end(); }); return false; }else{ if(busy){ this->GHwindow.push_log("结束当前步骤后程序将停止,请等待..."); return false; } running = true; this->GHwindow.push_log("开始运行任务"); if(this->_ending.joinable()){ _ending.join(); } if(this->_task.joinable()){ _task.join(); } this->_task = std::thread([this,task_list]{ thread_task(task_list); }); return true; } } void GHthread::wait_task_end(){ this ->_task.join(); this->GHwindow.push_log("任务被强制结束!"); busy = false; } void GHthread::thread_task(const std::vector &task_list){ bool set = this->GHwindow.set_window(); if(!set){this->GHwindow.push_log("请按提示调整窗口");running = false;return;} for(auto &_task:task_list){ bool reg = true; switch (_task->index) { case SCRIPT::TEST_LOCATE: reg=TASK_testLOCATE(); break; case SCRIPT::TEST_TP: reg=TASK_testTP(); break; case SCRIPT::TEST_TRACK: reg=TASK_testTRACK(); break; case SCRIPT::TEST_CAP: reg=TASK_testCAP(); break; case SCRIPT::AUTO_FISH: reg=TASK_AUTOFISH(); break; case SCRIPT::USER_SCRIPT: break; } if(!reg){ running = false; return; } } running = false; this->GHwindow.push_log("[finish]所有任务完成!"); } bool GHthread::TASK_testLOCATE(){ this->GHmap.loadmap(TEYVAT); this->GHwindow.start_grab(10); while(running){ this->GHmap.match_map(); this->GHmap.print_pos(); //Sleep(100); } this->GHmap.clear_load(); this->GHwindow.stop_grab(); this->GHwindow.push_log("[finish]测试定位完成"); return false; } bool GHthread::TASK_testCAP(){ this->GHwindow.push_log("使用Ctrl+F9/F10截图..."); cv::Mat cap; while(running){ Sleep(10); } this->GHwindow.get_one_frame(cap); cv::Mat bgr(cap.rows,cap.cols,CV_8UC3); cv::Mat alpha(cap.rows,cap.cols,CV_8UC1); cv::Mat out[] = {bgr ,alpha}; int fromTo[] = {0,0,1,1,2,2,3,3}; cv::mixChannels(&cap,1,out,2,fromTo,4); //cv::cvtColor(cap,cap,cv::COLOR_BGRA2BGR); time_t nowtime; time(&nowtime); char ch[64]; strftime(ch,sizeof (ch),"../out/%Y-%m-%d %H-%M-%S.png",localtime(&nowtime)); cv::imwrite(ch,bgr); strftime(ch,sizeof (ch),"../out/%Y-%m-%d %H-%M-%SA.png",localtime(&nowtime)); cv::imwrite(ch,alpha); this->GHwindow.push_log("[finish]截图成功"); return false; } bool GHthread::TASK_testTP(){ this->GHmap.loadmap(TEYVAT); this->GHwindow.start_grab(10); this->GHmap.TPmap(8310,7939); this->GHmap.clear_load(); this->GHwindow.stop_grab(); this->GHwindow.push_log("[finish]测试传送完成"); return true; } bool GHthread::TASK_AUTOFISH(){ this->GHwindow.start_grab(20); fisher fish(&GHwindow); while (running) { Sleep(1000); } fish.quit(); this->GHwindow.stop_grab(); this->GHwindow.push_log("[finish]退出钓鱼"); return true; } bool GHthread::TASK_testTRACK(){ this->GHmap.loadmap(TEYVAT); this->GHwindow.start_grab(10); this->GHmap.start_track(); while(true){ QUIT_CHECK Sleep(1000); } } justinctlam/MarbleStrike #ifndef TEXTURE_HPP #define TEXTURE_HPP ////////////////////////////////////////////////////// // INCLUDES ////////////////////////////////////////////////////// #include "common/engine/system/stringutilities.hpp" ////////////////////////////////////////////////////// // FORWARD DECLARATIONS ////////////////////////////////////////////////////// class Image; ////////////////////////////////////////////////////// // GLOBALS ////////////////////////////////////////////////////// const int MAX_TEXTURE_NAME = 256; ////////////////////////////////////////////////////// // STRUCTURES ////////////////////////////////////////////////////// ////////////////////////////////////////////////////// // CONSTANTS ////////////////////////////////////////////////////// enum TextureType { TEXTURE_TYPE_2D, TEXTURE_TYPE_CUBEMAP }; enum TextureFileType { TEXTURE_FILE_NORMAL, TEXTURE_FILE_HDR }; enum TextureFormat { TEXTURE_FORMAT_RGBA8, TEXTURE_FORMAT_RGBA16, TEXTURE_FORMAT_RGBA32, TEXTURE_FORMAT_RG32, TEXTURE_FORMAT_R32, TEXTURE_FORMAT_DXT1, TEXTURE_FORMAT_DXT3, TEXTURE_FORMAT_DXT5, TEXTURE_FORMAT_DEPTH }; ////////////////////////////////////////////////////// // CLASSES ////////////////////////////////////////////////////// class Texture { public: Texture(); virtual ~Texture(); virtual void CreateTextureWithImage( const Image &image ) = 0; virtual void CreateTexture( int width, int height, TextureFormat textureFormat ) = 0; virtual void LoadTextureImage( const char* filename, TextureFileType mTextureFileType = TEXTURE_FILE_NORMAL ) = 0; virtual void LoadTextureCubeImage( const char* filename ) = 0; void SetName( const char* name ) { System::StringCopy( mName, MAX_TEXTURE_NAME, name ); } const char* GetName() const { return mName; } int GetWidth() const { return mWidth; } int GetHeight() const { return mHeight; } TextureType GetTextureType() const { return mTextureType; } protected: int mWidth; int mHeight; TextureType mTextureType; private: char mName[MAX_TEXTURE_NAME]; }; #endif dav23r/Jimara #include "Component.h" #include "Transform.h" #include namespace Jimara { Component::Component(SceneContext* context, const std::string& name) : m_context(context), m_name(name), m_parent(nullptr) { m_context->ComponentInstantiated(this); } Component::Component(Component* parent, const std::string& name) : Component(parent->Context(), name) { SetParent(parent); } Component::~Component() { Destroy(); } std::string& Component::Name() { return m_name; } const std::string& Component::Name()const { return m_name; } SceneContext* Component::Context()const { return m_context; } Component* Component::RootObject() { Component* root = this; while (root->m_parent != nullptr) root = root->m_parent; return root; } const Component* Component::RootObject()const { const Component* root = this; while (root->m_parent != nullptr) root = root->m_parent; return root; } Component* Component::Parent()const { return m_parent; } void Component::SetParent(Component* newParent) { // First, let us make sure, we don't end up orphaned after this operation: if (newParent == nullptr) newParent = RootObject(); if (m_parent == newParent || newParent == this) return; // To make sure, the parent is not the only one holding the reference: Reference self(this); Reference parent(newParent); // This lets us avoid circular dependencies: { Component* ptr = newParent->m_parent; while (ptr != nullptr) { if (ptr == this) { newParent->SetParent(m_parent); break; } else ptr = ptr->m_parent; } } // Main reparenting operation: if (m_parent != nullptr) ((Component*)m_parent)->m_children.erase(this); m_parent = newParent; if (m_parent != nullptr) newParent->m_children.insert(this); // Inform heirarchy change listeners: NotifyParentChange(); } void Component::ClearParent() { SetParent(RootObject()); } Event& Component::OnParentChanged()const { return m_onParentChanged; } Transform* Component::GetTransfrom() { return GetComponentInParents(); } const Transform* Component::GetTransfrom()const { return GetComponentInParents(); } void Component::Destroy() { // Signal listeners that this object is no longer valid (we may actually prefer to keep the call after child Destroy() calls, but whatever...) m_onDestroyed(this); // But what about children? std::vector> children; for (std::set>::const_iterator it = m_children.begin(); it != m_children.end(); ++it) children.push_back(*it); for (size_t i = 0; i < children.size(); i++) children[i]->Destroy(); // Let's tell the parents... const bool hadParent = (m_parent != nullptr); if (hadParent) { AddRef(); ((Component*)m_parent)->m_children.erase(this); m_parent = nullptr; } // Just in case... We won't get wrecked the second time :) m_onDestroyed.Clear(); if (hadParent) ReleaseRef(); } Event& Component::OnDestroyed()const { return m_onDestroyed; } void Component::NotifyParentChange()const { m_onParentChanged(this); m_referenceBuffer.clear(); GetComponentsInChildren(m_referenceBuffer, true); for (size_t i = 0; i < m_referenceBuffer.size(); i++) m_referenceBuffer[i]->m_onParentChanged(m_referenceBuffer[i]); } } shankari/sgx-trust-management0 /* * Copyright (C) 2011-2018 Intel Corporation. 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 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 OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include #include #include # include # include # define MAX_PATH FILENAME_MAX #include "sgx_urts.h" #include "App.h" #include "Enclave_u.h" /* Global EID shared by multiple threads */ sgx_enclave_id_t global_eid = 0; typedef struct _sgx_errlist_t { sgx_status_t err; const char *msg; const char *sug; /* Suggestion */ } sgx_errlist_t; /* Error code returned by sgx_create_enclave */ static sgx_errlist_t sgx_errlist[] = { { SGX_ERROR_UNEXPECTED, "Unexpected error occurred.", NULL }, { SGX_ERROR_INVALID_PARAMETER, "Invalid parameter.", NULL }, { SGX_ERROR_OUT_OF_MEMORY, "Out of memory.", NULL }, { SGX_ERROR_ENCLAVE_LOST, "Power transition occurred.", "Please refer to the sample \"PowerTransition\" for details." }, { SGX_ERROR_INVALID_ENCLAVE, "Invalid enclave image.", NULL }, { SGX_ERROR_INVALID_ENCLAVE_ID, "Invalid enclave identification.", NULL }, { SGX_ERROR_INVALID_SIGNATURE, "Invalid enclave signature.", NULL }, { SGX_ERROR_OUT_OF_EPC, "Out of EPC memory.", NULL }, { SGX_ERROR_NO_DEVICE, "Invalid SGX device.", "Please make sure SGX module is enabled in the BIOS, and install SGX driver afterwards." }, { SGX_ERROR_MEMORY_MAP_CONFLICT, "Memory map conflicted.", NULL }, { SGX_ERROR_INVALID_METADATA, "Invalid enclave metadata.", NULL }, { SGX_ERROR_DEVICE_BUSY, "SGX device was busy.", NULL }, { SGX_ERROR_INVALID_VERSION, "Enclave version was invalid.", NULL }, { SGX_ERROR_INVALID_ATTRIBUTE, "Enclave was not authorized.", NULL }, { SGX_ERROR_ENCLAVE_FILE_ACCESS, "Can't open enclave file.", NULL }, }; /* Check error conditions for loading enclave */ void print_error_message(sgx_status_t ret) { size_t idx = 0; size_t ttl = sizeof sgx_errlist/sizeof sgx_errlist[0]; for (idx = 0; idx < ttl; idx++) { if(ret == sgx_errlist[idx].err) { if(NULL != sgx_errlist[idx].sug) printf("Info: %s\n", sgx_errlist[idx].sug); printf("Error: %s\n", sgx_errlist[idx].msg); break; } } if (idx == ttl) printf("Error code is 0x%X. Please refer to the \"Intel SGX SDK Developer Reference\" for more details.\n", ret); } /* Initialize the enclave: * Call sgx_create_enclave to initialize an enclave instance */ int initialize_enclave(void) { sgx_launch_token_t token = {0}; sgx_status_t ret = SGX_ERROR_UNEXPECTED; int updated = 0; /* Call sgx_create_enclave to initialize an enclave instance */ /* Debug Support: set 2nd parameter to 1 */ ret = sgx_create_enclave(ENCLAVE_FILENAME, SGX_DEBUG_FLAG, &token, &updated, &global_eid, NULL); if (ret != SGX_SUCCESS) { print_error_message(ret); return -1; } return 0; } /* OCall functions */ void ocall_print_string(const char *str) { /* Proxy/Bridge will check the length and null-terminate * the input string to prevent buffer overflow. */ printf("%s", str); } /* Application entry */ int SGX_CDECL main(int argc, char *argv[]) { (void)(argc); (void)(argv); /* Initialize the enclave */ if(initialize_enclave() < 0){ printf("Enter a character before exit ...\n"); getchar(); return -1; } /* Utilize edger8r attributes */ edger8r_array_attributes(); edger8r_pointer_attributes(); edger8r_type_attributes(); edger8r_function_attributes(); /* Utilize trusted libraries */ ecall_libc_functions(); ecall_libcxx_functions(); ecall_thread_functions(); /* Destroy the enclave */ sgx_destroy_enclave(global_eid); printf("Info: SampleEnclave successfully returned.\n"); printf("Enter a character before exit ...\n"); getchar(); return 0; } 100-1000 // 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 "components/light.h" #include "components/services.h" #include "flatbuffers/flatbuffers.h" #include "fplbase/flatbuffer_utils.h" #include "fplbase/utilities.h" CORGI_DEFINE_COMPONENT(fpl::zooshi::LightComponent, fpl::zooshi::LightData) namespace fpl { namespace zooshi { using fplbase::ColorRGBA; using fplbase::Vec4ToColorRGBA; using mathfu::vec3; using scene_lab::SceneLab; void LightComponent::AddFromRawData(corgi::EntityRef& entity, const void* raw_data) { auto light_def = static_cast(raw_data); LightData* data = AddEntity(entity); data->shadow_intensity = light_def->shadow_intensity(); data->diffuse_color = LoadColorRGBA(light_def->diffuse_color()); data->ambient_color = LoadColorRGBA(light_def->ambient_color()); data->specular_color = LoadColorRGBA(light_def->specular_color()); data->specular_exponent = light_def->specular_exponent(); data->diffuse_intensity = light_def->diffuse_intensity(); data->ambient_intensity = light_def->ambient_intensity(); data->specular_intensity = light_def->specular_intensity(); } corgi::ComponentInterface::RawDataUniquePtr LightComponent::ExportRawData( const corgi::EntityRef& entity) const { const LightData* data = GetComponentData(entity); if (data == nullptr) return nullptr; flatbuffers::FlatBufferBuilder fbb; LightDefBuilder builder(fbb); builder.add_shadow_intensity(data->shadow_intensity); ColorRGBA diffuse = Vec4ToColorRGBA(data->diffuse_color); builder.add_diffuse_color(&diffuse); ColorRGBA ambient = Vec4ToColorRGBA(data->ambient_color); builder.add_ambient_color(&ambient); ColorRGBA specular = Vec4ToColorRGBA(data->specular_color); builder.add_specular_color(&specular); builder.add_specular_exponent(data->specular_exponent); builder.add_diffuse_intensity(data->diffuse_intensity); builder.add_ambient_intensity(data->ambient_intensity); builder.add_specular_intensity(data->specular_intensity); fbb.Finish(builder.Finish()); return fbb.ReleaseBufferPointer(); } } // zooshi } // fpl 0 /* * Copyright (C) 2011, 2012, Sony Ericsson Mobile Communications AB * Copyright (C) 2012 Sony Mobile Communications AB * 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 Sony Ericsson Mobile Communications AB 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 SONY ERICSSON MOBILE COMMUNICATIONS AB 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" #if ENABLE(WEBGL) #include "BitmapImage.h" #include "text/CString.h" #include "GraphicsContext3D.h" #include "GraphicsContext3DInternal.h" #include "Image.h" #include "ImageData.h" #include "ImageDecoder.h" #include "SkBitmap.h" #include "SkBitmapRef.h" namespace WebCore { PassRefPtr GraphicsContext3D::create(HTMLCanvasElement* canvas, Attributes attrs, HostWindow *win, RenderStyle style) { GraphicsContext3D *context = new GraphicsContext3D(canvas, attrs, win, false); if (!context->m_internal->isValid()) { // Something failed during initialization delete context; return 0; } return adoptRef(context); } GraphicsContext3D::GraphicsContext3D(HTMLCanvasElement* canvas, Attributes attrs, HostWindow* hostWindow, bool renderDirectlyToHostWindow) : m_internal(new GraphicsContext3DInternal(canvas, attrs, hostWindow)) { LOGWEBGL("GraphicsContext3D() = %p", this); m_currentWidth = m_internal->width(); m_currentHeight = m_internal->height(); } GraphicsContext3D::~GraphicsContext3D() { LOGWEBGL("~GraphicsContext3D()"); } PlatformLayer* GraphicsContext3D::platformLayer() const { return m_internal->platformLayer(); } void GraphicsContext3D::makeContextCurrent() { m_internal->makeContextCurrent(); } bool GraphicsContext3D::isGLES2Compliant() const { return true; } void GraphicsContext3D::synthesizeGLError(GC3Denum error) { m_internal->synthesizeGLError(error); } Extensions3D* GraphicsContext3D::getExtensions() { return m_internal->getExtensions(); } void GraphicsContext3D::paintRenderingResultsToCanvas(CanvasRenderingContext* context) { makeContextCurrent(); m_internal->paintRenderingResultsToCanvas(context); } PassRefPtr GraphicsContext3D::paintRenderingResultsToImageData() { makeContextCurrent(); return m_internal->paintRenderingResultsToImageData(); } bool GraphicsContext3D::paintCompositedResultsToCanvas(CanvasRenderingContext* context) { makeContextCurrent(); return m_internal->paintCompositedResultsToCanvas(context); } bool GraphicsContext3D::getImageData(Image* image, unsigned int format, unsigned int type, bool premultiplyAlpha, bool ignoreGammaAndColorProfile, Vector& outputVector) { LOGWEBGL("getImageData(%p, %u, %u, %s, %s)", image, format, type, premultiplyAlpha ? "true" : "false", ignoreGammaAndColorProfile ? "true" : "false"); if (!image) return false; AlphaOp neededAlphaOp = AlphaDoNothing; bool hasAlpha = (image->data() && image->isBitmapImage()) ? static_cast(image)->frameHasAlphaAtIndex(0) : true; ImageDecoder* decoder = 0; ImageFrame* buf = 0; if ((ignoreGammaAndColorProfile || (hasAlpha && !premultiplyAlpha)) && image->data()) { // Attempt to get raw unpremultiplied image data decoder = ImageDecoder::create(*(image->data()), premultiplyAlpha ? ImageSource::AlphaPremultiplied : ImageSource::AlphaNotPremultiplied, ignoreGammaAndColorProfile ? ImageSource::GammaAndColorProfileIgnored : ImageSource::GammaAndColorProfileApplied); if (decoder) { decoder->setData(image->data(), true); buf = decoder->frameBufferAtIndex(0); if (buf && buf->hasAlpha() && premultiplyAlpha) neededAlphaOp = AlphaDoPremultiply; } } SkBitmapRef* bitmapRef = 0; if (!buf) { bitmapRef = image->nativeImageForCurrentFrame(); if (!bitmapRef) return false; if (!premultiplyAlpha && hasAlpha) neededAlphaOp = AlphaDoUnmultiply; } SkBitmap& bitmap = buf ? buf->bitmap() : bitmapRef->bitmap(); unsigned char* pixels = 0; int rowBytes = 0; uint32_t* tmpPixels = 0; int width = bitmap.width(); int height = bitmap.height(); int iwidth = image->width(); int iheight = image->height(); LOGWEBGL(" bitmap.width() = %d, image->width() = %d, bitmap.height = %d, image->height() = %d", width, iwidth, height, iheight); if (width != iwidth || height != iheight) { // This image has probably been subsampled because it was too big. // Currently, we cannot handle this in WebGL: give up. return false; } SkBitmap::Config skiaConfig = bitmap.getConfig(); bitmap.lockPixels(); if (skiaConfig == SkBitmap::kARGB_8888_Config) { LOGWEBGL(" skiaConfig = kARGB_8888_Config"); pixels = reinterpret_cast(bitmap.getPixels()); rowBytes = bitmap.rowBytes(); if (!pixels) { bitmap.unlockPixels(); return false; } } else if (skiaConfig == SkBitmap::kIndex8_Config) { LOGWEBGL(" skiaConfig = kIndex8_Config"); rowBytes = width * 4; tmpPixels = (uint32_t*)fastMalloc(width * height * 4); if (!tmpPixels) { bitmap.unlockPixels(); return false; } for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { SkPMColor c = bitmap.getIndex8Color(j, i); tmpPixels[i * width + j] = c;//SkExpand_8888(c); } } pixels = (unsigned char*)tmpPixels; } outputVector.resize(rowBytes * height); LOGWEBGL("rowBytes() = %d, width() = %d, height() = %d", rowBytes, width, height); bool res = packPixels(pixels, SourceFormatRGBA8, width, height, 0, format, type, neededAlphaOp, outputVector.data()); bitmap.unlockPixels(); if (decoder) delete decoder; if (tmpPixels) fastFree(tmpPixels); return res; } unsigned GraphicsContext3D::createBuffer() { LOGWEBGL("glCreateBuffer()"); makeContextCurrent(); GLuint b = 0; glGenBuffers(1, &b); return b; } unsigned GraphicsContext3D::createFramebuffer() { LOGWEBGL("glCreateFramebuffer()"); makeContextCurrent(); GLuint fb = 0; glGenFramebuffers(1, &fb); return fb; } unsigned GraphicsContext3D::createProgram() { LOGWEBGL("glCreateProgram()"); makeContextCurrent(); return glCreateProgram(); } unsigned GraphicsContext3D::createRenderbuffer() { LOGWEBGL("glCreateRenderbuffer()"); makeContextCurrent(); GLuint rb = 0; glGenRenderbuffers(1, &rb); return rb; } unsigned GraphicsContext3D::createShader(GC3Denum type) { LOGWEBGL("glCreateShader()"); makeContextCurrent(); return glCreateShader((type == FRAGMENT_SHADER) ? GL_FRAGMENT_SHADER : GL_VERTEX_SHADER); } unsigned GraphicsContext3D::createTexture() { LOGWEBGL("glCreateTexture()"); makeContextCurrent(); GLuint t = 0; glGenTextures(1, &t); return t; } void GraphicsContext3D::deleteBuffer(unsigned buffer) { LOGWEBGL("glDeleteBuffers()"); makeContextCurrent(); glDeleteBuffers(1, &buffer); } void GraphicsContext3D::deleteFramebuffer(unsigned framebuffer) { LOGWEBGL("glDeleteFramebuffers()"); makeContextCurrent(); glDeleteFramebuffers(1, &framebuffer); } void GraphicsContext3D::deleteProgram(unsigned program) { LOGWEBGL("glDeleteProgram()"); makeContextCurrent(); glDeleteProgram(program); } void GraphicsContext3D::deleteRenderbuffer(unsigned renderbuffer) { LOGWEBGL("glDeleteRenderbuffers()"); makeContextCurrent(); glDeleteRenderbuffers(1, &renderbuffer); } void GraphicsContext3D::deleteShader(unsigned shader) { LOGWEBGL("glDeleteShader()"); makeContextCurrent(); glDeleteShader(shader); } void GraphicsContext3D::deleteTexture(unsigned texture) { LOGWEBGL("glDeleteTextures()"); makeContextCurrent(); glDeleteTextures(1, &texture); } void GraphicsContext3D::activeTexture(GC3Denum texture) { LOGWEBGL("glActiveTexture(%ld)", texture); makeContextCurrent(); glActiveTexture(texture); } void GraphicsContext3D::attachShader(Platform3DObject program, Platform3DObject shader) { LOGWEBGL("glAttachShader(%d, %d)", program, shader); makeContextCurrent(); glAttachShader(program, shader); } void GraphicsContext3D::bindAttribLocation(Platform3DObject program, GC3Duint index, const String& name) { CString cs = name.utf8(); LOGWEBGL("glBindAttribLocation(%d, %d, %s)", program, index, cs.data()); if (!program) return; makeContextCurrent(); glBindAttribLocation(program, index, cs.data()); } void GraphicsContext3D::bindBuffer(GC3Denum target, Platform3DObject buffer) { LOGWEBGL("glBindBuffer(%d, %d)", target, buffer); makeContextCurrent(); glBindBuffer(target, buffer); } void GraphicsContext3D::bindFramebuffer(GC3Denum target, Platform3DObject framebuffer) { LOGWEBGL("bindFrameBuffer(%d, %d)", target, framebuffer); m_internal->bindFramebuffer(target, framebuffer); } void GraphicsContext3D::bindRenderbuffer(GC3Denum target, Platform3DObject renderbuffer) { LOGWEBGL("glBindRenderBuffer(%d, %d)", target, renderbuffer); makeContextCurrent(); glBindRenderbuffer(target, renderbuffer); } void GraphicsContext3D::bindTexture(GC3Denum target, Platform3DObject texture) { LOGWEBGL("glBindTexture(%d, %d)", target, texture); makeContextCurrent(); glBindTexture(target, texture); } void GraphicsContext3D::blendColor(GC3Dclampf red, GC3Dclampf green, GC3Dclampf blue, GC3Dclampf alpha) { LOGWEBGL("glBlendColor(%lf, %lf, %lf, %lf)", red, green, blue, alpha); makeContextCurrent(); glBlendColor(CLAMP(red), CLAMP(green), CLAMP(blue), CLAMP(alpha)); } void GraphicsContext3D::blendEquation(GC3Denum mode) { LOGWEBGL("glBlendEquation(%d)", mode); makeContextCurrent(); glBlendEquation(mode); } void GraphicsContext3D::blendEquationSeparate(GC3Denum modeRGB, GC3Denum modeAlpha) { LOGWEBGL("glBlendEquationSeparate(%d, %d)", modeRGB, modeAlpha); makeContextCurrent(); glBlendEquationSeparate(modeRGB, modeAlpha); } void GraphicsContext3D::blendFunc(GC3Denum sfactor, GC3Denum dfactor) { LOGWEBGL("glBlendFunc(%d, %d)", sfactor, dfactor); makeContextCurrent(); glBlendFunc(sfactor, dfactor); } void GraphicsContext3D::blendFuncSeparate(GC3Denum srcRGB, GC3Denum dstRGB, GC3Denum srcAlpha, GC3Denum dstAlpha) { LOGWEBGL("glBlendFuncSeparate(%lu, %lu, %lu, %lu)", srcRGB, dstRGB, srcAlpha, dstAlpha); makeContextCurrent(); glBlendFuncSeparate(srcRGB, dstRGB, srcAlpha, dstAlpha); } void GraphicsContext3D::bufferData(GC3Denum target, GC3Dsizeiptr size, GC3Denum usage) { LOGWEBGL("glBufferData(%lu, %d, %lu)", target, size, usage); makeContextCurrent(); glBufferData(target, size, 0, usage); } void GraphicsContext3D::bufferData(GC3Denum target, GC3Dsizeiptr size, const void* data, GC3Denum usage) { LOGWEBGL("glBufferData(%lu, %d, %p, %lu)", target, size, data, usage); makeContextCurrent(); glBufferData(target, size, data, usage); } void GraphicsContext3D::bufferSubData(GC3Denum target, GC3Dintptr offset, GC3Dsizeiptr size, const void* data) { LOGWEBGL("glBufferSubData(%lu, %ld, %d, %p)", target, offset, size, data); makeContextCurrent(); glBufferSubData(target, offset, size, data); } GC3Denum GraphicsContext3D::checkFramebufferStatus(GC3Denum target) { LOGWEBGL("glCheckFramebufferStatus(%lu)", target); makeContextCurrent(); return glCheckFramebufferStatus(target); } void GraphicsContext3D::clear(GC3Dbitfield mask) { LOGWEBGL("glClear(%lu)", mask); makeContextCurrent(); glClear(mask); } void GraphicsContext3D::clearColor(GC3Dclampf red, GC3Dclampf green, GC3Dclampf blue, GC3Dclampf alpha) { LOGWEBGL("glClearColor(%.2lf, %.2lf, %.2lf, %.2lf)", red, green, blue, alpha); makeContextCurrent(); glClearColor(CLAMP(red), CLAMP(green), CLAMP(blue), CLAMP(alpha)); } void GraphicsContext3D::clearDepth(GC3Dclampf depth) { LOGWEBGL("glClearDepthf(%.2lf)", depth); makeContextCurrent(); glClearDepthf(CLAMP(depth)); } void GraphicsContext3D::clearStencil(GC3Dint s) { LOGWEBGL("glClearStencil(%ld)", s); makeContextCurrent(); glClearStencil(s); } void GraphicsContext3D::colorMask(GC3Dboolean red, GC3Dboolean green, GC3Dboolean blue, GC3Dboolean alpha) { LOGWEBGL("glColorMask(%s, %s, %s, %s)", red ? "true" : "false", green ? "true" : "false", blue ? "true" : "false", alpha ? "true" : "false"); makeContextCurrent(); glColorMask(red, green, blue, alpha); } void GraphicsContext3D::compileShader(Platform3DObject shader) { LOGWEBGL("compileShader(%lu)", shader); makeContextCurrent(); m_internal->compileShader(shader); } void GraphicsContext3D::copyTexImage2D(GC3Denum target, GC3Dint level, GC3Denum internalformat, GC3Dint x, GC3Dint y, GC3Dsizei width, GC3Dsizei height, GC3Dint border) { LOGWEBGL("glCopyTexImage2D(%lu, %ld, %lu, %ld, %ld, %lu, %lu, %ld", target, level, internalformat, x, y, width, height, border); makeContextCurrent(); glCopyTexImage2D(target, level, internalformat, x, y, width, height, border); } void GraphicsContext3D::copyTexSubImage2D(GC3Denum target, GC3Dint level, GC3Dint xoffset, GC3Dint yoffset, GC3Dint x, GC3Dint y, GC3Dsizei width, GC3Dsizei height) { LOGWEBGL("glCopyTexSubImage2D(%lu, %ld, %ld, %ld, %ld, %ld, %lu, %lu)", target, level, xoffset, yoffset, x, y, width, height); makeContextCurrent(); glCopyTexSubImage2D(target, level, xoffset, yoffset, x, y, width, height); } void GraphicsContext3D::cullFace(GC3Denum mode) { LOGWEBGL("glCullFace(%lu)", mode); makeContextCurrent(); glCullFace(mode); } void GraphicsContext3D::depthFunc(GC3Denum func) { LOGWEBGL("glDepthFunc(%lu)", func); makeContextCurrent(); glDepthFunc(func); } void GraphicsContext3D::depthMask(GC3Dboolean flag) { LOGWEBGL("glDepthMask(%s)", flag ? "true" : "false"); makeContextCurrent(); glDepthMask(flag); } void GraphicsContext3D::depthRange(GC3Dclampf zNear, GC3Dclampf zFar) { LOGWEBGL("glDepthRangef(%.2lf, %.2lf)", zNear, zFar); makeContextCurrent(); glDepthRangef(CLAMP(zNear), CLAMP(zFar)); } void GraphicsContext3D::detachShader(Platform3DObject program, Platform3DObject shader) { LOGWEBGL("glDetachShader(%lu, %lu)", program, shader); makeContextCurrent(); glDetachShader(program, shader); } void GraphicsContext3D::disable(GC3Denum cap) { LOGWEBGL("glDisable(%lu)", cap); makeContextCurrent(); glDisable(cap); } void GraphicsContext3D::disableVertexAttribArray(GC3Duint index) { LOGWEBGL("glDisableVertexAttribArray(%lu)", index); makeContextCurrent(); glDisableVertexAttribArray(index); } void GraphicsContext3D::drawArrays(GC3Denum mode, GC3Dint first, GC3Dsizei count) { LOGWEBGL("glDrawArrays(%lu, %ld, %ld)", mode, first, count); makeContextCurrent(); glDrawArrays(mode, first, count); } void GraphicsContext3D::drawElements(GC3Denum mode, GC3Dsizei count, GC3Denum type, GC3Dintptr offset) { LOGWEBGL("glDrawElements(%lu, %lu, %lu, %ld)", mode, count, type, offset); makeContextCurrent(); glDrawElements(mode, count, type, reinterpret_cast(static_cast(offset))); } void GraphicsContext3D::enable(GC3Denum cap) { LOGWEBGL("glEnable(0x%04x)", cap); makeContextCurrent(); glEnable(cap); } void GraphicsContext3D::enableVertexAttribArray(GC3Duint index) { LOGWEBGL("glEnableVertexAttribArray(%lu)", index); makeContextCurrent(); glEnableVertexAttribArray(index); } void GraphicsContext3D::finish() { LOGWEBGL("glFinish()"); makeContextCurrent(); glFinish(); } void GraphicsContext3D::flush() { LOGWEBGL("glFlush()"); makeContextCurrent(); glFlush(); } void GraphicsContext3D::framebufferRenderbuffer(GC3Denum target, GC3Denum attachment, GC3Denum renderbuffertarget, Platform3DObject renderbuffer) { LOGWEBGL("glFramebufferRenderbuffer(%lu, %lu, %lu, %lu)", target, attachment, renderbuffertarget, renderbuffer); makeContextCurrent(); glFramebufferRenderbuffer(target, attachment, renderbuffertarget, renderbuffer); } void GraphicsContext3D::framebufferTexture2D(GC3Denum target, GC3Denum attachment, GC3Denum textarget, Platform3DObject texture, GC3Dint level) { LOGWEBGL("glFramebufferTexture2D(%lu, %lu, %lu, %lu, %ld)", target, attachment, textarget, texture, level); makeContextCurrent(); glFramebufferTexture2D(target, attachment, textarget, texture, level); } void GraphicsContext3D::frontFace(GC3Denum mode) { LOGWEBGL("glFrontFace(%lu)", mode); makeContextCurrent(); glFrontFace(mode); } void GraphicsContext3D::generateMipmap(GC3Denum target) { LOGWEBGL("glGenerateMipmap(%lu)", target); makeContextCurrent(); glGenerateMipmap(target); } bool GraphicsContext3D::getActiveAttrib(Platform3DObject program, GC3Duint index, ActiveInfo& info) { LOGWEBGL("glGetActiveAttrib(%lu, %lu)", program, index); if (!program) { synthesizeGLError(INVALID_VALUE); return false; } makeContextCurrent(); GLint maxAttributeSize = 0; glGetProgramiv(program, GL_ACTIVE_ATTRIBUTE_MAX_LENGTH, &maxAttributeSize); GLchar name[maxAttributeSize]; GLsizei nameLength = 0; GLint size = 0; GLenum type = 0; glGetActiveAttrib(program, index, maxAttributeSize, &nameLength, &size, &type, name); if (!nameLength) return false; info.name = String(name, nameLength); info.type = type; info.size = size; return true; } bool GraphicsContext3D::getActiveUniform(Platform3DObject program, GC3Duint index, ActiveInfo& info) { LOGWEBGL("glGetActiveUniform(%lu, %lu)", program, index); if (!program) { synthesizeGLError(INVALID_VALUE); return false; } makeContextCurrent(); GLint maxUniformSize = 0; glGetProgramiv(program, GL_ACTIVE_UNIFORM_MAX_LENGTH, &maxUniformSize); GLchar name[maxUniformSize]; GLsizei nameLength = 0; GLint size = 0; GLenum type = 0; glGetActiveUniform(program, index, maxUniformSize, &nameLength, &size, &type, name); if (!nameLength) return false; info.name = String(name, nameLength); info.type = type; info.size = size; return true; } void GraphicsContext3D::getAttachedShaders(Platform3DObject program, GC3Dsizei maxCount, GC3Dsizei* count, Platform3DObject* shaders) { LOGWEBGL("glGetAttachedShaders(%lu, %d, %p, %p)", program, maxCount, count, shaders); if (!program) { synthesizeGLError(INVALID_VALUE); return; } makeContextCurrent(); glGetAttachedShaders(program, maxCount, count, shaders); } GC3Dint GraphicsContext3D::getAttribLocation(Platform3DObject program, const String& name) { CString cs = name.utf8(); LOGWEBGL("glGetAttribLocation(%lu, %s)", program, cs.data()); if (!program) { return -1; } makeContextCurrent(); return glGetAttribLocation(program, cs.data()); } void GraphicsContext3D::getBooleanv(GC3Denum pname, GC3Dboolean* value) { LOGWEBGL("glGetBooleanv(%lu, %p)", pname, value); makeContextCurrent(); glGetBooleanv(pname, value); } void GraphicsContext3D::getBufferParameteriv(GC3Denum target, GC3Denum pname, GC3Dint* value) { LOGWEBGL("glGetBufferParameteriv(%lu, %lu, %p)", target, pname, value); makeContextCurrent(); glGetBufferParameteriv(target, pname, value); } GraphicsContext3D::Attributes GraphicsContext3D::getContextAttributes() { LOGWEBGL("getContextAttributes()"); return m_internal->getContextAttributes(); } GC3Denum GraphicsContext3D::getError() { LOGWEBGL("getError()"); return m_internal->getError(); } void GraphicsContext3D::getFloatv(GC3Denum pname, GC3Dfloat* value) { LOGWEBGL("glGetFloatv(%lu, %p)", pname, value); makeContextCurrent(); glGetFloatv(pname, value); } void GraphicsContext3D::getFramebufferAttachmentParameteriv(GC3Denum target, GC3Denum attachment, GC3Denum pname, GC3Dint* value) { LOGWEBGL("glGetFramebufferAttachmentParameteriv(%lu, %lu, %lu, %p)", target, attachment, pname, value); makeContextCurrent(); if (attachment == DEPTH_STENCIL_ATTACHMENT) attachment = DEPTH_ATTACHMENT; glGetFramebufferAttachmentParameteriv(target, attachment, pname, value); } void GraphicsContext3D::getIntegerv(GC3Denum pname, GC3Dint* value) { LOGWEBGL("glGetIntegerv(%lu, %p)", pname, value); makeContextCurrent(); glGetIntegerv(pname, value); } void GraphicsContext3D::getProgramiv(Platform3DObject program, GC3Denum pname, GC3Dint* value) { LOGWEBGL("glGetProgramiv(%lu, %lu, %p)", program, pname, value); makeContextCurrent(); glGetProgramiv(program, pname, value); } String GraphicsContext3D::getProgramInfoLog(Platform3DObject program) { LOGWEBGL("glGetProgramInfoLog(%lu)", program); makeContextCurrent(); GLint length; glGetProgramiv(program, GL_INFO_LOG_LENGTH, &length); if (!length) return ""; GLsizei size; GLchar* info = (GLchar*)fastMalloc(length); glGetProgramInfoLog(program, length, &size, info); String s(info); fastFree(info); return s; } void GraphicsContext3D::getRenderbufferParameteriv(GC3Denum target, GC3Denum pname, GC3Dint* value) { LOGWEBGL("glGetRenderbufferParameteriv(%lu, %lu, %p)", target, pname, value); makeContextCurrent(); glGetRenderbufferParameteriv(target, pname, value); } void GraphicsContext3D::getShaderiv(Platform3DObject shader, GC3Denum pname, GC3Dint* value) { LOGWEBGL("glGetShaderiv(%lu, %lu, %p)", shader, pname, value); makeContextCurrent(); glGetShaderiv(shader, pname, value); } String GraphicsContext3D::getShaderInfoLog(Platform3DObject shader) { LOGWEBGL("getShaderInfoLog(%lu)", shader); makeContextCurrent(); return m_internal->getShaderInfoLog(shader); } String GraphicsContext3D::getShaderSource(Platform3DObject shader) { LOGWEBGL("getShaderSource(%lu)", shader); makeContextCurrent(); return m_internal->getShaderSource(shader); } String GraphicsContext3D::getString(GC3Denum name) { LOGWEBGL("glGetString(%lu)", name); makeContextCurrent(); return String(reinterpret_cast(glGetString(name))); } void GraphicsContext3D::getTexParameterfv(GC3Denum target, GC3Denum pname, GC3Dfloat* value) { LOGWEBGL("glGetTexParameterfv(%lu, %lu, %p)", target, pname, value); makeContextCurrent(); glGetTexParameterfv(target, pname, value); } void GraphicsContext3D::getTexParameteriv(GC3Denum target, GC3Denum pname, GC3Dint* value) { LOGWEBGL("glGetTexParameteriv(%lu, %lu, %p)", target, pname, value); makeContextCurrent(); glGetTexParameteriv(target, pname, value); } void GraphicsContext3D::getUniformfv(Platform3DObject program, GC3Dint location, GC3Dfloat* value) { LOGWEBGL("glGetUniformfv(%lu, %ld, %p)", program, location, value); makeContextCurrent(); glGetUniformfv(program, location, value); } void GraphicsContext3D::getUniformiv(Platform3DObject program, GC3Dint location, GC3Dint* value) { LOGWEBGL("glGetUniformiv(%lu, %ld, %p)", program, location, value); makeContextCurrent(); glGetUniformiv(program, location, value); } GC3Dint GraphicsContext3D::getUniformLocation(Platform3DObject program, const String& name) { CString cs = name.utf8(); LOGWEBGL("glGetUniformLocation(%lu, %s)", program, cs.data()); makeContextCurrent(); return glGetUniformLocation(program, cs.data()); } void GraphicsContext3D::getVertexAttribfv(GC3Duint index, GC3Denum pname, GC3Dfloat* value) { LOGWEBGL("glGetVertexAttribfv(%lu, %lu, %p)", index, pname, value); makeContextCurrent(); glGetVertexAttribfv(index, pname, value); } void GraphicsContext3D::getVertexAttribiv(GC3Duint index, GC3Denum pname, GC3Dint* value) { LOGWEBGL("glGetVertexAttribiv(%lu, %lu, %p)", index, pname, value); makeContextCurrent(); glGetVertexAttribiv(index, pname, value); } GC3Dsizeiptr GraphicsContext3D::getVertexAttribOffset(GC3Duint index, GC3Denum pname) { LOGWEBGL("glGetVertexAttribOffset(%lu, %lu)", index, pname); GLvoid* pointer = 0; glGetVertexAttribPointerv(index, pname, &pointer); return static_cast(reinterpret_cast(pointer)); } void GraphicsContext3D::hint(GC3Denum target, GC3Denum mode) { LOGWEBGL("glHint(%lu, %lu)", target, mode); makeContextCurrent(); glHint(target, mode); } GC3Dboolean GraphicsContext3D::isBuffer(Platform3DObject buffer) { LOGWEBGL("glIsBuffer(%lu)", buffer); if (!buffer) return GL_FALSE; makeContextCurrent(); return glIsBuffer(buffer); } GC3Dboolean GraphicsContext3D::isEnabled(GC3Denum cap) { LOGWEBGL("glIsEnabled(%lu)", cap); makeContextCurrent(); return glIsEnabled(cap); } GC3Dboolean GraphicsContext3D::isFramebuffer(Platform3DObject framebuffer) { LOGWEBGL("glIsFramebuffer(%lu)", framebuffer); if (!framebuffer) return GL_FALSE; makeContextCurrent(); return glIsFramebuffer(framebuffer); } GC3Dboolean GraphicsContext3D::isProgram(Platform3DObject program) { LOGWEBGL("glIsProgram(%lu)", program); if (!program) return GL_FALSE; makeContextCurrent(); return glIsProgram(program); } GC3Dboolean GraphicsContext3D::isRenderbuffer(Platform3DObject renderbuffer) { LOGWEBGL("glIsRenderbuffer(%lu)", renderbuffer); if (!renderbuffer) return GL_FALSE; makeContextCurrent(); return glIsRenderbuffer(renderbuffer); } GC3Dboolean GraphicsContext3D::isShader(Platform3DObject shader) { LOGWEBGL("glIsShader(%lu)", shader); if (!shader) return GL_FALSE; makeContextCurrent(); return glIsShader(shader); } GC3Dboolean GraphicsContext3D::isTexture(Platform3DObject texture) { LOGWEBGL("glIsTexture(%lu)", texture); if (!texture) return GL_FALSE; makeContextCurrent(); return glIsTexture(texture); } void GraphicsContext3D::lineWidth(GC3Dfloat width) { LOGWEBGL("glLineWidth(%.2lf)", width); makeContextCurrent(); glLineWidth((GLfloat)width); } void GraphicsContext3D::linkProgram(Platform3DObject program) { LOGWEBGL("glLinkProgram(%lu)", program); makeContextCurrent(); glLinkProgram(program); } void GraphicsContext3D::pixelStorei(GC3Denum pname, GC3Dint param) { LOGWEBGL("glPixelStorei(%lu, %ld)", pname, param); makeContextCurrent(); glPixelStorei(pname, param); } void GraphicsContext3D::polygonOffset(GC3Dfloat factor, GC3Dfloat units) { LOGWEBGL("glPolygonOffset(%.2lf, %.2lf)", factor, units); makeContextCurrent(); glPolygonOffset((GLfloat)factor, (GLfloat)units); } void GraphicsContext3D::readPixels(GC3Dint x, GC3Dint y, GC3Dsizei width, GC3Dsizei height, GC3Denum format, GC3Denum type, void* data) { LOGWEBGL("glReadPixels(%ld, %ld, %lu, %lu, %lu, %lu, %p)", x, y, width, height, format, type, data); makeContextCurrent(); glReadPixels(x, y, width, height, format, type, data); } void GraphicsContext3D::releaseShaderCompiler() { LOGWEBGL("glReleaseShaderCompiler()"); makeContextCurrent(); glReleaseShaderCompiler(); } void GraphicsContext3D::renderbufferStorage(GC3Denum target, GC3Denum internalformat, GC3Dsizei width, GC3Dsizei height) { LOGWEBGL("glRenderbufferStorage(%lu, %lu, %lu, %lu)", target, internalformat, width, height); makeContextCurrent(); glRenderbufferStorage(target, internalformat, width, height); } void GraphicsContext3D::sampleCoverage(GC3Dclampf value, GC3Dboolean invert) { LOGWEBGL("glSampleCoverage(%.2lf, %s)", value, invert ? "true" : "false"); makeContextCurrent(); glSampleCoverage(CLAMP(value), invert); } void GraphicsContext3D::scissor(GC3Dint x, GC3Dint y, GC3Dsizei width, GC3Dsizei height) { LOGWEBGL("glScissor(%ld, %ld, %lu, %lu)", x, y, width, height); makeContextCurrent(); glScissor(x, y, width, height); } void GraphicsContext3D::shaderSource(Platform3DObject shader, const String& source) { LOGWEBGL("shaderSource(%lu, %s)", shader, source.utf8().data()); makeContextCurrent(); m_internal->shaderSource(shader, source); } void GraphicsContext3D::stencilFunc(GC3Denum func, GC3Dint ref, GC3Duint mask) { LOGWEBGL("glStencilFunc(%lu, %ld, %lu)", func, ref, mask); makeContextCurrent(); glStencilFunc(func, ref, mask); } void GraphicsContext3D::stencilFuncSeparate(GC3Denum face, GC3Denum func, GC3Dint ref, GC3Duint mask) { LOGWEBGL("glStencilFuncSeparate(%lu, %lu, %ld, %lu)", face, func, ref, mask); makeContextCurrent(); glStencilFuncSeparate(face, func, ref, mask); } void GraphicsContext3D::stencilMask(GC3Duint mask) { LOGWEBGL("glStencilMask(%lu)", mask); makeContextCurrent(); glStencilMask(mask); } void GraphicsContext3D::stencilMaskSeparate(GC3Denum face, GC3Duint mask) { LOGWEBGL("glStencilMaskSeparate(%lu, %lu)", face, mask); makeContextCurrent(); glStencilMaskSeparate(face, mask); } void GraphicsContext3D::stencilOp(GC3Denum fail, GC3Denum zfail, GC3Denum zpass) { LOGWEBGL("glStencilOp(%lu, %lu, %lu)", fail, zfail, zpass); makeContextCurrent(); glStencilOp(fail, zfail, zpass); } void GraphicsContext3D::stencilOpSeparate(GC3Denum face, GC3Denum fail, GC3Denum zfail, GC3Denum zpass) { LOGWEBGL("glStencilOpSeparate(%lu, %lu, %lu, %lu)", face, fail, zfail, zpass); makeContextCurrent(); glStencilOpSeparate(face, fail, zfail, zpass); } bool GraphicsContext3D::texImage2D(GC3Denum target, GC3Dint level, GC3Denum internalformat, GC3Dsizei width, GC3Dsizei height, GC3Dint border, GC3Denum format, GC3Denum type, const void* pixels) { LOGWEBGL("glTexImage2D(%u, %u, %u, %u, %u, %u, %u, %u, %p)", target, level, internalformat, width, height, border, format, type, pixels); if (width && height && !pixels) { synthesizeGLError(INVALID_VALUE); return false; } makeContextCurrent(); glTexImage2D(target, level, internalformat, width, height, border, format, type, pixels); return true; } void GraphicsContext3D::texParameterf(GC3Denum target, GC3Denum pname, GC3Dfloat param) { LOGWEBGL("glTexParameterf(%u, %u, %f)", target, pname, param); makeContextCurrent(); glTexParameterf(target, pname, param); } void GraphicsContext3D::texParameteri(GC3Denum target, GC3Denum pname, GC3Dint param) { LOGWEBGL("glTexParameteri(%u, %u, %d)", target, pname, param); makeContextCurrent(); glTexParameteri(target, pname, param); } void GraphicsContext3D::texSubImage2D(GC3Denum target, GC3Dint level, GC3Dint xoffset, GC3Dint yoffset, GC3Dsizei width, GC3Dsizei height, GC3Denum format, GC3Denum type, const void* pixels) { LOGWEBGL("glTexSubImage2D(%u, %u, %u, %u, %u, %u, %u, %u, %p)", target, level, xoffset, yoffset, width, height, format, type, pixels); if (width && height && !pixels) { synthesizeGLError(INVALID_VALUE); return; } makeContextCurrent(); glTexSubImage2D(target, level, xoffset, yoffset, width, height, format, type, pixels); } void GraphicsContext3D::uniform1f(GC3Dint location, GC3Dfloat x) { LOGWEBGL("glUniform1f(%ld, %f)", location, x); makeContextCurrent(); glUniform1f(location, x); } void GraphicsContext3D::uniform1fv(GC3Dint location, GC3Dfloat* v, GC3Dsizei size) { LOGWEBGL("glUniform1fv(%ld, %p, %d)", location, v, size); makeContextCurrent(); glUniform1fv(location, size, v); } void GraphicsContext3D::uniform1i(GC3Dint location, GC3Dint x) { LOGWEBGL("glUniform1i(%ld, %d)", location, x); makeContextCurrent(); glUniform1i(location, x); } void GraphicsContext3D::uniform1iv(GC3Dint location, GC3Dint* v, GC3Dsizei size) { LOGWEBGL("glUniform1iv(%ld, %p, %d)", location, v, size); makeContextCurrent(); glUniform1iv(location, size, v); } void GraphicsContext3D::uniform2f(GC3Dint location, GC3Dfloat x, float y) { LOGWEBGL("glUniform2f(%ld, %f, %f)", location, x, y); makeContextCurrent(); glUniform2f(location, x, y); } void GraphicsContext3D::uniform2fv(GC3Dint location, GC3Dfloat* v, GC3Dsizei size) { LOGWEBGL("glUniform2fv(%ld, %p, %d)", location, v, size); makeContextCurrent(); glUniform2fv(location, size, v); } void GraphicsContext3D::uniform2i(GC3Dint location, GC3Dint x, GC3Dint y) { LOGWEBGL("glUniform2i(%ld, %d, %d)", location, x, y); makeContextCurrent(); glUniform2i(location, x, y); } void GraphicsContext3D::uniform2iv(GC3Dint location, GC3Dint* v, GC3Dsizei size) { LOGWEBGL("glUniform2iv(%ld, %p, %d)", location, v, size); makeContextCurrent(); glUniform2iv(location, size, v); } void GraphicsContext3D::uniform3f(GC3Dint location, GC3Dfloat x, GC3Dfloat y, GC3Dfloat z) { LOGWEBGL("glUniform3f(%ld, %f, %f, %f)", location, x, y, z); makeContextCurrent(); glUniform3f(location, x, y, z); } void GraphicsContext3D::uniform3fv(GC3Dint location, GC3Dfloat* v, GC3Dsizei size) { LOGWEBGL("glUniform3fv(%ld, %p, %d)", location, v, size); makeContextCurrent(); glUniform3fv(location, size, v); } void GraphicsContext3D::uniform3i(GC3Dint location, GC3Dint x, GC3Dint y, GC3Dint z) { LOGWEBGL("glUniform3i(%ld, %d, %d, %d)", location, x, y, z); makeContextCurrent(); glUniform3i(location, x, y, z); } void GraphicsContext3D::uniform3iv(GC3Dint location, GC3Dint* v, GC3Dsizei size) { LOGWEBGL("glUniform3iv(%ld, %p, %d)", location, v, size); makeContextCurrent(); glUniform3iv(location, size, v); } void GraphicsContext3D::uniform4f(GC3Dint location, GC3Dfloat x, GC3Dfloat y, GC3Dfloat z, GC3Dfloat w) { LOGWEBGL("glUniform4f(%ld, %f, %f, %f, %f)", location, x, y, z, w); makeContextCurrent(); glUniform4f(location, x, y, z, w); } void GraphicsContext3D::uniform4fv(GC3Dint location, GC3Dfloat* v, GC3Dsizei size) { LOGWEBGL("glUniform4fv(%ld, %p, %d)", location, v, size); makeContextCurrent(); glUniform4fv(location, size, v); } void GraphicsContext3D::uniform4i(GC3Dint location, GC3Dint x, GC3Dint y, GC3Dint z, GC3Dint w) { LOGWEBGL("glUniform4i(%ld, %d, %d, %d, %d)", location, x, y, z, w); makeContextCurrent(); glUniform4i(location, x, y, z, w); } void GraphicsContext3D::uniform4iv(GC3Dint location, GC3Dint* v, GC3Dsizei size) { LOGWEBGL("glUniform4iv(%ld, %p, %d)", location, v, size); makeContextCurrent(); glUniform4iv(location, size, v); } void GraphicsContext3D::uniformMatrix2fv(GC3Dint location, GC3Dboolean transpose, GC3Dfloat* value, GC3Dsizei size) { LOGWEBGL("glUniformMatrix2fv(%ld, %s, %p, %d)", location, transpose ? "true" : "false", value, size); makeContextCurrent(); glUniformMatrix2fv(location, size, transpose, value); } void GraphicsContext3D::uniformMatrix3fv(GC3Dint location, GC3Dboolean transpose, GC3Dfloat* value, GC3Dsizei size) { LOGWEBGL("glUniformMatrix3fv(%ld, %s, %p, %d)", location, transpose ? "true" : "false", value, size); makeContextCurrent(); glUniformMatrix3fv(location, size, transpose, value); } void GraphicsContext3D::uniformMatrix4fv(GC3Dint location, GC3Dboolean transpose, GC3Dfloat* value, GC3Dsizei size) { LOGWEBGL("glUniformMatrix4fv(%ld, %s, %p, %d)", location, transpose ? "true" : "false", value, size); makeContextCurrent(); glUniformMatrix4fv(location, size, transpose, value); } void GraphicsContext3D::useProgram(Platform3DObject program) { LOGWEBGL("glUseProgram(%lu)", program); makeContextCurrent(); glUseProgram(program); } void GraphicsContext3D::validateProgram(Platform3DObject program) { LOGWEBGL("glValidateProgram(%lu)", program); makeContextCurrent(); glValidateProgram(program); } void GraphicsContext3D::vertexAttrib1f(GC3Duint index, GC3Dfloat x) { LOGWEBGL("glVertexAttrib1f(%lu, %f)", index, x); makeContextCurrent(); glVertexAttrib1f(index, x); } void GraphicsContext3D::vertexAttrib1fv(GC3Duint index, GC3Dfloat* values) { LOGWEBGL("glVertexAttrib1fv(%lu, %p)", index, values); makeContextCurrent(); glVertexAttrib1fv(index, values); } void GraphicsContext3D::vertexAttrib2f(GC3Duint index, GC3Dfloat x, GC3Dfloat y) { LOGWEBGL("glVertexAttrib2f(%lu, %f, %f)", index, x, y); makeContextCurrent(); glVertexAttrib2f(index, x, y); } void GraphicsContext3D::vertexAttrib2fv(GC3Duint index, GC3Dfloat* values) { LOGWEBGL("glVertexAttrib2fv(%lu, %p)", index, values); makeContextCurrent(); glVertexAttrib2fv(index, values); } void GraphicsContext3D::vertexAttrib3f(GC3Duint index, GC3Dfloat x, GC3Dfloat y, GC3Dfloat z) { LOGWEBGL("glVertexAttrib3f(%lu, %f, %f, %f)", index, x, y, z); makeContextCurrent(); glVertexAttrib3f(index, x, y, z); } void GraphicsContext3D::vertexAttrib3fv(GC3Duint index, GC3Dfloat* values) { LOGWEBGL("glVertexAttrib3fv(%lu, %p)", index, values); makeContextCurrent(); glVertexAttrib3fv(index, values); } void GraphicsContext3D::vertexAttrib4f(GC3Duint index, GC3Dfloat x, GC3Dfloat y, GC3Dfloat z, GC3Dfloat w) { LOGWEBGL("glVertexAttrib4f(%lu, %f, %f, %f, %f)", index, x, y, z, w); makeContextCurrent(); glVertexAttrib4f(index, x, y, z, w); } void GraphicsContext3D::vertexAttrib4fv(GC3Duint index, GC3Dfloat* values) { LOGWEBGL("glVertexAttrib4fv(%lu, %p)", index, values); makeContextCurrent(); glVertexAttrib4fv(index, values); } void GraphicsContext3D::vertexAttribPointer(GC3Duint index, GC3Dint size, GC3Denum type, GC3Dboolean normalized, GC3Dsizei stride, GC3Dintptr offset) { LOGWEBGL("glVertexAttribPointer(%lu, %d, %d, %s, %lu, %lu)", index, size, type, normalized ? "true" : "false", stride, offset); makeContextCurrent(); glVertexAttribPointer(index, size, type, normalized, stride, reinterpret_cast(static_cast(offset))); } void GraphicsContext3D::viewport(GC3Dint x, GC3Dint y, GC3Dsizei width, GC3Dsizei height) { LOGWEBGL("viewport(%ld, %ld, %lu, %lu)", x, y, width, height); makeContextCurrent(); m_internal->viewport(x, y, width, height); } void GraphicsContext3D::reshape(int width, int height) { LOGWEBGL("reshape(%d, %d)", width, height); if ((width == m_currentWidth) && (height == m_currentHeight)) { return; } m_internal->reshape(width, height); m_currentWidth = m_internal->width(); m_currentHeight = m_internal->height(); } void GraphicsContext3D::recreateSurface() { LOGWEBGL("recreateSurface()"); m_internal->recreateSurface(); } void GraphicsContext3D::releaseSurface() { LOGWEBGL("releaseSurface()"); m_internal->releaseSurface(); } IntSize GraphicsContext3D::getInternalFramebufferSize() { return IntSize(m_currentWidth, m_currentHeight); } void GraphicsContext3D::markContextChanged() { LOGWEBGL("markContextChanged()"); m_internal->markContextChanged(); } void GraphicsContext3D::markLayerComposited() { LOGWEBGL("markLayerComposited()"); m_internal->markLayerComposited(); } bool GraphicsContext3D::layerComposited() const { LOGWEBGL("layerComposited()"); return m_internal->layerComposited(); } void GraphicsContext3D::setContextLostCallback(PassOwnPtr) { } } #endif #include #include // std::setfill, std::setw #include "LiteMath.h" using namespace LiteMath; template static void PrintRR(const char* name1, const char* name2, T res[], T ref[], int size = 4) { std::cout << name1 << ": "; for(int i=0;i 1e-6f || fabs(result2[i] - expr2[i]) > 1e-6f || fabs(result3[i] - expr3[i]) > 1e-6f) passed = false; } if(!passed) { PrintRR("exp1_res", "exp2_res", result1, expr1, 3); PrintRR("exp2_res", "exp2_res", result2, expr2, 3); PrintRR("exp3_res", "exp3_res", result3, expr3, 3); } return passed; } bool test151_basek_float3() { const float3 Cx1( float(-1), float(2), float(-3)); const float Cx2 = float(3); const float3 Cx3 = Cx2*(Cx2 + Cx1) - float(2); const float3 Cx4 = float(1) + (Cx1 + Cx2)*Cx2; const float3 Cx5 = float(3) - Cx2/(Cx2 - Cx1); const float3 Cx6 = (Cx2 + Cx1)/Cx2 + float(5)/Cx1; CVEX_ALIGNED(16) float result1[4]; CVEX_ALIGNED(16) float result2[4]; CVEX_ALIGNED(16) float result3[4]; CVEX_ALIGNED(16) float result4[4]; store(result1, Cx3); store(result2, Cx4); store(result3, Cx5); store(result4, Cx6); bool passed = true; for(int i=0;i<3;i++) { const float expr1 = Cx2*(Cx2 + Cx1[i]) - float(2); const float expr2 = float(1) + (Cx1[i] + Cx2)*Cx2; const float expr3 = float(3) - Cx2/(Cx2 - Cx1[i]); const float expr4 = (Cx2 + Cx1[i])/Cx2 + float(5)/Cx1[i]; if(fabs(result1[i] - expr1) > 1e-6f || fabs(result2[i] - expr2) > 1e-6f || fabs(result3[i] - expr3) > 1e-6f || fabs(result4[i] - expr4) > 1e-6f ) passed = false; } return passed; } bool test152_unaryv_float3() { const float3 Cx1( float(-1), float(2), float(-3)); const float3 Cx2( float(3), float(-4), float(4)); auto Cx3 = Cx1; auto Cx4 = Cx1; auto Cx5 = Cx1; auto Cx6 = Cx1; Cx3 += Cx2; Cx4 -= Cx2; Cx5 *= Cx2; Cx6 /= Cx2; float result1[3]; float result2[3]; float result3[3]; float result4[3]; store_u(result1, Cx3); store_u(result2, Cx4); store_u(result3, Cx5); store_u(result4, Cx6); float expr1[3], expr2[3], expr3[3], expr4[3]; bool passed = true; for(int i=0;i<3;i++) { expr1[i] = Cx1[i] + Cx2[i]; expr2[i] = Cx1[i] - Cx2[i]; expr3[i] = Cx1[i] * Cx2[i]; expr4[i] = Cx1[i] / Cx2[i]; if(fabs(result1[i] - expr1[i]) > 1e-6f || fabs(result2[i] - expr2[i]) > 1e-6f || fabs(result3[i] - expr3[i]) > 1e-6f) passed = false; } if(!passed) { PrintRR("exp1_res", "exp2_res", result1, expr1, 3); PrintRR("exp2_res", "exp2_res", result2, expr2, 3); PrintRR("exp3_res", "exp3_res", result3, expr3, 3); PrintRR("exp4_res", "exp4_res", result4, expr4, 3); } return passed; } bool test152_unaryk_float3() { const float3 Cx1( float(-1), float(2), float(-3)); const float Cx2 = float(3); auto Cx3 = Cx1; auto Cx4 = Cx1; auto Cx5 = Cx1; auto Cx6 = Cx1; Cx3 += Cx2; Cx4 -= Cx2; Cx5 *= Cx2; Cx6 /= Cx2; float result1[3]; float result2[3]; float result3[3]; float result4[3]; store_u(result1, Cx3); store_u(result2, Cx4); store_u(result3, Cx5); store_u(result4, Cx6); float expr1[3], expr2[3], expr3[3], expr4[3]; bool passed = true; for(int i=0;i<3;i++) { expr1[i] = Cx1[i] + Cx2; expr2[i] = Cx1[i] - Cx2; expr3[i] = Cx1[i] * Cx2; expr4[i] = Cx1[i] / Cx2; if(fabs(result1[i] - expr1[i]) > 1e-6f || fabs(result2[i] - expr2[i]) > 1e-6f || fabs(result3[i] - expr3[i]) > 1e-6f) passed = false; } if(!passed) { PrintRR("exp1_res", "exp2_res", result1, expr1, 3); PrintRR("exp2_res", "exp2_res", result2, expr2, 3); PrintRR("exp3_res", "exp3_res", result3, expr3, 3); PrintRR("exp4_res", "exp4_res", result4, expr4, 3); } return passed; } bool test153_cmpv_float3() { const float3 Cx1( float(-1), float(2), float(-3)); const float3 Cx2( float(3), float(-4), float(4)); auto Cx3 = (Cx1 < Cx2 ); auto Cx4 = (Cx1 > Cx2 ); auto Cx5 = (Cx1 <= Cx2); auto Cx6 = (Cx1 >= Cx2); auto Cx7 = (Cx1 == Cx2); auto Cx8 = (Cx1 != Cx2); const auto Cx9 = blend(Cx1, Cx2, Cx3); const auto Cx10 = blend(Cx1, Cx2, Cx6); uint32_t result1[3]; uint32_t result2[3]; uint32_t result3[3]; uint32_t result4[3]; uint32_t result5[3]; uint32_t result6[3]; float result7[3]; float result8[3]; store_u(result1, Cx3); store_u(result2, Cx4); store_u(result3, Cx5); store_u(result4, Cx6); store_u(result5, Cx7); store_u(result6, Cx8); store_u(result7, Cx9); store_u(result8, Cx10); uint32_t expr1[3], expr2[3], expr3[3], expr4[3], expr5[3], expr6[3]; float expr7[3], expr8[3]; bool passed = true; for(int i=0;i<3;i++) { expr1[i] = Cx1[i] < Cx2[i] ? 0xFFFFFFFF : 0; expr2[i] = Cx1[i] > Cx2[i] ? 0xFFFFFFFF : 0; expr3[i] = Cx1[i] <= Cx2[i] ? 0xFFFFFFFF : 0; expr4[i] = Cx1[i] >= Cx2[i] ? 0xFFFFFFFF : 0; expr5[i] = Cx1[i] == Cx2[i] ? 0xFFFFFFFF : 0; expr6[i] = Cx1[i] != Cx2[i] ? 0xFFFFFFFF : 0; expr7[i] = Cx1[i] < Cx2[i] ? Cx1[i] : Cx2[i]; expr8[i] = Cx1[i] >= Cx2[i] ? Cx1[i] : Cx2[i]; if(result1[i] != expr1[i] || result2[i] != expr2[i] || result3[i] != expr3[i] || result4[i] != expr4[i] || result5[i] != expr5[i] || result6[i] != expr6[i] || result7[i] != expr7[i] || result8[i] != expr8[i]) passed = false; } if(!passed) { PrintRR("exp1_res", "exp2_res", result1, expr1, 3); PrintRR("exp2_res", "exp2_res", result2, expr2, 3); PrintRR("exp3_res", "exp3_res", result3, expr3, 3); PrintRR("exp4_res", "exp4_res", result4, expr4, 3); PrintRR("exp5_res", "exp5_res", result5, expr5, 3); PrintRR("exp6_res", "exp6_res", result6, expr6, 3); PrintRR("exp7_res", "exp7_res", result7, expr7, 3); PrintRR("exp8_res", "exp8_res", result8, expr8, 3); } return passed; } bool test154_shuffle_float3() { const float3 Cx1( float(-1), float(2), float(-3)); const float3 Cr1 = shuffle_zyx(Cx1); const float3 Cr2 = shuffle_zxy(Cx1); const float3 Cr3 = shuffle_yzx(Cx1); const float3 Cr4 = shuffle_yxz(Cx1); const float3 Cr5 = shuffle_xzy(Cx1); CVEX_ALIGNED(16) float result1[4]; CVEX_ALIGNED(16) float result2[4]; CVEX_ALIGNED(16) float result3[4]; CVEX_ALIGNED(16) float result4[4]; CVEX_ALIGNED(16) float result5[4]; store(result1, Cr1); store(result2, Cr2); store(result3, Cr3); store(result4, Cr4); store(result5, Cr5); const bool b1 = (result1[0] == Cx1[2]) && (result1[1] == Cx1[1]) && (result1[2] == Cx1[0]); const bool b2 = (result2[0] == Cx1[2]) && (result2[1] == Cx1[0]) && (result2[2] == Cx1[1]); const bool b3 = (result3[0] == Cx1[1]) && (result3[1] == Cx1[2]) && (result3[2] == Cx1[0]); const bool b4 = (result4[0] == Cx1[1]) && (result4[1] == Cx1[0]) && (result4[2] == Cx1[2]); const bool b5 = (result5[0] == Cx1[0]) && (result5[1] == Cx1[2]) && (result5[2] == Cx1[1]); const bool passed = (b1 && b2 && b3 && b4 && b5); if(!passed) { std::cout << result1[0] << " " << result1[1] << " " << result1[2] << std::endl; std::cout << result2[0] << " " << result2[1] << " " << result2[2] << std::endl; std::cout << result3[0] << " " << result3[1] << " " << result3[2] << std::endl; std::cout << result4[0] << " " << result4[1] << " " << result4[2] << std::endl; std::cout << result5[0] << " " << result5[1] << " " << result5[2] << std::endl; } return passed; } bool test155_exsplat_float3() { const float3 Cx1( float(-1), float(2), float(-3)); const float3 Cr0 = splat_0(Cx1); const float3 Cr1 = splat_1(Cx1); const float3 Cr2 = splat_2(Cx1); const float s0 = extract_0(Cx1); const float s1 = extract_1(Cx1); const float s2 = extract_2(Cx1); float result0[3]; float result1[3]; float result2[3]; store_u(result0, Cr0); store_u(result1, Cr1); store_u(result2, Cr2); bool passed = true; for (int i = 0; i<3; i++) { if((result0[i] != Cx1[0])) passed = false; if((result1[i] != Cx1[1])) passed = false; if((result2[i] != Cx1[2])) passed = false; } if(s0 != Cx1[0]) passed = false; if(s1 != Cx1[1]) passed = false; if(s2 != Cx1[2]) passed = false; return passed; } bool test157_funcv_float3() { const float3 Cx1( float(-1), float(2), float(-3)); const float3 Cx2( float(3), float(-4), float(4)); auto Cx3 = sign(Cx1); auto Cx4 = abs(Cx1); auto Cx5 = clamp(Cx1, float(2), float(3) ); auto Cx6 = min(Cx1, Cx2); auto Cx7 = max(Cx1, Cx2); float Cm = hmin(Cx1); float CM = hmax(Cx1); float horMinRef = Cx1[0]; float horMaxRef = Cx1[0]; for(int i=0;i<3;i++) { horMinRef = std::min(horMinRef, Cx1[i]); horMaxRef = std::max(horMaxRef, Cx1[i]); } bool passed = true; for(int i=0;i<3;i++) { if(Cx3[i] != sign(Cx1[i])) passed = false; if(Cx4[i] != abs(Cx1[i])) passed = false; if(Cx5[i] != clamp(Cx1[i], float(2), float(3) )) passed = false; if(Cx6[i] != min(Cx1[i], Cx2[i])) passed = false; if(Cx7[i] != max(Cx1[i], Cx2[i])) passed = false; } if(horMinRef != Cm) passed = false; if(horMaxRef != CM) passed = false; return passed; } bool test158_funcfv_float3() { const float3 Cx1( float(-1), float(2), float(-3)); const float3 Cx2( float(3), float(-4), float(4)); auto Cx3 = mod(Cx1, Cx2); auto Cx4 = fract(Cx1); auto Cx5 = ceil(Cx1); auto Cx6 = floor(Cx1); auto Cx7 = sign(Cx1); auto Cx8 = abs(Cx1); auto Cx9 = clamp(Cx1, -2.0f, 2.0f); auto Cx10 = min(Cx1, Cx2); auto Cx11 = max(Cx1, Cx2); auto Cx12 = mix (Cx1, Cx2, 0.5f); auto Cx13 = lerp(Cx1, Cx2, 0.5f); auto Cx14 = sqrt(Cx8); auto Cx15 = inversesqrt(Cx8); auto Cx18 = rcp(Cx1); float ref[19][3]; float res[19][3]; memset(ref, 0, 19*sizeof(float)*3); memset(res, 0, 19*sizeof(float)*3); store_u(res[3], Cx3); store_u(res[4], Cx4); store_u(res[5], Cx5); store_u(res[6], Cx6); store_u(res[7], Cx7); store_u(res[8], Cx8); store_u(res[9], Cx9); store_u(res[10], Cx10); store_u(res[11], Cx11); store_u(res[12], Cx12); store_u(res[13], Cx13); store_u(res[14], Cx14); store_u(res[15], Cx15); store_u(res[18], Cx18); for(int i=0;i<3;i++) { ref[3][i] = mod(Cx1[i], Cx2[i]); ref[4][i] = fract(Cx1[i]); ref[5][i] = ceil(Cx1[i]); ref[6][i] = floor(Cx1[i]); ref[7][i] = sign(Cx1[i]); ref[8][i] = abs(Cx1[i]); ref[9][i] = clamp(Cx1[i], float(-2), float(2) ); ref[10][i] = min(Cx1[i], Cx2[i]); ref[11][i] = max(Cx1[i], Cx2[i]); ref[12][i] = mix (Cx1[i], Cx2[i], 0.5f); ref[13][i] = lerp(Cx1[i], Cx2[i], 0.5f); ref[14][i] = sqrt(Cx8[i]); ref[15][i] = inversesqrt(Cx8[i]); ref[18][i] = rcp(Cx1[i]); } bool passed = true; for(int i=0;i<3;i++) { for(int j=3;j<=18;j++) { if(abs( res[j][i]-ref[j][i]) > 1e-6f) { if(j == 15 || j == 18) { if(abs(res[j][i]-ref[j][i]) > 5e-4f) { passed = false; break; } } else { passed = false; break; } } } } return passed; } bool test159_cstcnv_float3() { const float3 Cx1( float(-1), float(2), float(-3)); const int3 Cr1 = to_int32(Cx1); const uint3 Cr2 = to_uint32(Cx1); const int3 Cr3 = as_int32(Cx1); const uint3 Cr4 = as_uint32(Cx1); int result1[3]; unsigned int result2[3]; int result3[3]; unsigned int result4[3]; store_u(result1, Cr1); store_u(result2, Cr2); store_u(result3, Cr3); store_u(result4, Cr4); int ref1[3]; unsigned int ref2[3]; for(int i=0;i<3;i++) { ref1[i] = int(Cx1[i]); ref2[i] = (unsigned int)(Cx1[i]); } int ref3[3]; unsigned int ref4[3]; memcpy(ref3, &Cr3, sizeof(int)*3); memcpy(ref4, &Cr4, sizeof(uint)*3); bool passed = true; for (int i=0; i<3; i++) { if (result1[i] != ref1[i] || result2[i] != ref2[i] || result3[i] != ref3[i] || result4[i] != ref4[i]) { passed = false; break; } } return passed; } bool test160_other_float3() // dummy test { const float CxData[3] = { float(-1), float(2), float(-3)}; const float3 Cx1(CxData); const float3 Cx2(float3(1)); const float3 Cx3 = Cx1 + Cx2; float result1[3]; float result2[3]; float result3[3]; store_u(result1, Cx1); store_u(result2, Cx2); store_u(result3, Cx3); bool passed = true; for (int i=0; i<3; i++) { if (fabs(result1[i] + float(1) - result3[i]) > 1e-10f || fabs(result2[i] - float(1) > 1e-10f) ) { passed = false; break; } } const float dat5 = dot (Cx1, Cx2); const float3 crs3 = cross(Cx1, Cx2); const float crs_ref[3] = { Cx1[1]*Cx2[2] - Cx1[2]*Cx2[1], Cx1[2]*Cx2[0] - Cx1[0]*Cx2[2], Cx1[0]*Cx2[1] - Cx1[1]*Cx2[0] }; { float sum = float(0); for(int i=0;i<3;i++) sum += Cx1[i]*Cx2[i]; passed = passed && (std::abs(sum - dat5) < 1e-6f); for(int i=0;i<3;i++) passed = passed && (std::abs(crs3[i] - crs_ref[i]) < 1e-6f); } return passed; } #include #include #include using namespace std; using namespace __gnu_pbds; typedef long long ll; typedef vector vi; typedef pair pii; template using Tree = tree, rb_tree_tag,tree_order_statistics_node_update>; #define FOR(i, a, b) for (int i=a; i<(b); i++) #define F0R(i, a) for (int i=0; i<(a); i++) #define FORd(i,a,b) for (int i = (b)-1; i >= a; i--) #define F0Rd(i,a) for (int i = (a)-1; i >= 0; i--) #define sz(x) (int)(x).size() #define mp make_pair #define pb push_back #define f first #define s second #define lb lower_bound #define ub upper_bound #define all(x) x.begin(), x.end() const int MOD = 1000000007; const int MX = 100000; int G,S,C, buy; vector ans; int main() { ios_base::sync_with_stdio(0);cin.tie(0); cin >> G >> S >> C; buy = 3*G+2*S+1*C; if (buy >= 8) ans.pb("Province"); else if (buy >= 5) ans.pb("Duchy"); else if (buy >= 2) ans.pb("Estate"); if (buy >= 6) ans.pb("Gold"); else if (buy >= 3) ans.pb("Silver"); else ans.pb("Copper"); if (ans.size() == 2) cout << ans[0] << " or " << ans[1]; else cout << ans[0]; } // read!read!read!read!read!read!read!read!read!read!read!read!read!read!read!read! // ll vs. int!#include QV_NODE_SOURCE(QvIndexedLineSet); QvIndexedLineSet::QvIndexedLineSet() { QV_NODE_CONSTRUCTOR(QvIndexedLineSet); isBuiltIn = TRUE; QV_NODE_ADD_FIELD(coordIndex); QV_NODE_ADD_FIELD(materialIndex); QV_NODE_ADD_FIELD(normalIndex); QV_NODE_ADD_FIELD(textureCoordIndex); coordIndex.values[0] = 0; materialIndex.values[0] = QV_END_LINE_INDEX; normalIndex.values[0] = QV_END_LINE_INDEX; textureCoordIndex.values[0] = QV_END_LINE_INDEX; } QvIndexedLineSet::~QvIndexedLineSet() { } /* Copyright 2019-2021 natinusala Copyright 2019 p-sam 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 using namespace brls::literals; namespace brls { static bool endsWith(const std::string& data, const std::string& suffix) { return data.find(suffix, data.size() - suffix.size()) != std::string::npos; } static bool startsWith(const std::string& data, const std::string& prefix) { return data.rfind(prefix, 0) == 0; } View::View() { // Instantiate and prepare YGNode this->ygNode = YGNodeNew(); YGNodeSetContext(this->ygNode, this); YGNodeStyleSetWidthAuto(this->ygNode); YGNodeStyleSetHeightAuto(this->ygNode); // Register common XML attributes this->registerCommonAttributes(); // Default values Style style = Application::getStyle(); this->highlightCornerRadius = style["brls/highlight/corner_radius"]; } static int shakeAnimation(float t, float a) // a = amplitude { // Damped sine wave float w = 0.8f; // period float c = 0.35f; // damp factor return roundf(a * exp(-(c * t)) * sin(w * t)); } void View::shakeHighlight(FocusDirection direction) { this->highlightShaking = true; this->highlightShakeStart = getCPUTimeUsec() / 1000; this->highlightShakeDirection = direction; this->highlightShakeAmplitude = std::rand() % 15 + 10; } float View::getAlpha(bool child) { return this->alpha * (this->parent ? this->parent->getAlpha(true) : 1.0f); } NVGcolor View::a(NVGcolor color) { NVGcolor newColor = color; // copy newColor.a *= this->getAlpha(); return newColor; } NVGpaint View::a(NVGpaint paint) { NVGpaint newPaint = paint; // copy newPaint.innerColor.a *= this->getAlpha(); newPaint.outerColor.a *= this->getAlpha(); return newPaint; } void View::frame(FrameContext* ctx) { if (this->visibility != Visibility::VISIBLE) return; Style style = Application::getStyle(); Theme oldTheme = ctx->theme; nvgSave(ctx->vg); // Theme override if (this->themeOverride) ctx->theme = *themeOverride; float x = this->getX(); float y = this->getY(); float width = this->getWidth(); float height = this->getHeight(); if (this->alpha > 0.0f && this->collapseState != 0.0f) { // Draw background this->drawBackground(ctx->vg, ctx, style); // Draw shadow if (this->shadowType != ShadowType::NONE && this->showShadow) this->drawShadow(ctx->vg, ctx, style, x, y, width, height); // Draw border if (this->borderThickness > 0.0f) this->drawBorder(ctx->vg, ctx, style, x, y, width, height); // Draw highlight background if (this->highlightAlpha > 0.0f && !this->hideHighlightBackground) this->drawHighlight(ctx->vg, ctx->theme, this->highlightAlpha, style, true); // Draw click animation if (this->clickAlpha > 0.0f) this->drawClickAnimation(ctx->vg, ctx, x, y, width, height); // Collapse clipping if (this->collapseState < 1.0f) { nvgSave(ctx->vg); nvgIntersectScissor(ctx->vg, x, y, width, height * this->collapseState); } // Draw the view this->draw(ctx->vg, x, y, width, height, style, ctx); // Draw highlight if (this->highlightAlpha > 0.0f) this->drawHighlight(ctx->vg, ctx->theme, this->highlightAlpha, style, false); if (this->wireframeEnabled) this->drawWireframe(ctx, x, y, width, height); this->drawLine(ctx, x, y, width, height); //Reset clipping if (this->collapseState < 1.0f) nvgRestore(ctx->vg); } // Cleanup if (this->themeOverride) ctx->theme = oldTheme; nvgRestore(ctx->vg); } void View::resetClickAnimation() { this->clickAlpha.stop(); } void View::playClickAnimation(bool reverse) { this->resetClickAnimation(); Style style = Application::getStyle(); this->clickAlpha.reset(reverse ? 1.0f : 0.0f); this->clickAlpha.addStep( reverse ? 0.0f : 1.0f, style["brls/animations/highlight"], reverse ? EasingFunction::quadraticOut : EasingFunction::quadraticIn); this->clickAlpha.setEndCallback([this, reverse](bool finished) { if (reverse) return; this->playClickAnimation(true); }); this->clickAlpha.start(); } void View::drawClickAnimation(NVGcontext* vg, FrameContext* ctx, float x, float y, float width, float height) { Theme theme = ctx->theme; NVGcolor color = theme["brls/click_pulse"]; color.a *= this->clickAlpha; nvgFillColor(vg, a(color)); nvgBeginPath(vg); if (this->cornerRadius > 0.0f) nvgRoundedRect(vg, x, y, width, height, this->cornerRadius); else nvgRect(vg, x, y, width, height); nvgFill(vg); } void View::drawLine(FrameContext* ctx, float x, float y, float width, float height) { // Don't setup and draw empty nvg path if there is no line to draw if (this->lineTop <= 0 && this->lineRight <= 0 && this->lineBottom <= 0 && this->lineLeft <= 0) return; nvgBeginPath(ctx->vg); nvgFillColor(ctx->vg, a(this->lineColor)); if (this->lineTop > 0) nvgRect(ctx->vg, x, y, width, this->lineTop); if (this->lineRight > 0) nvgRect(ctx->vg, x + width, y, this->lineRight, height); if (this->lineBottom > 0) nvgRect(ctx->vg, x, y + height - this->lineBottom, width, this->lineBottom); if (this->lineLeft > 0) nvgRect(ctx->vg, x - this->lineLeft, y, this->lineLeft, height); nvgFill(ctx->vg); } void View::drawWireframe(FrameContext* ctx, float x, float y, float width, float height) { nvgStrokeWidth(ctx->vg, 1); // Outline nvgBeginPath(ctx->vg); nvgStrokeColor(ctx->vg, nvgRGB(0, 0, 255)); nvgRect(ctx->vg, x, y, width, height); nvgStroke(ctx->vg); if (this->hasParent()) { // Diagonals nvgFillColor(ctx->vg, nvgRGB(0, 0, 255)); nvgBeginPath(ctx->vg); nvgMoveTo(ctx->vg, x, y); nvgLineTo(ctx->vg, x + width, y + height); nvgFill(ctx->vg); nvgBeginPath(ctx->vg); nvgMoveTo(ctx->vg, x + width, y); nvgLineTo(ctx->vg, x, y + height); nvgFill(ctx->vg); } // Padding nvgBeginPath(ctx->vg); nvgStrokeColor(ctx->vg, nvgRGB(0, 255, 0)); float paddingTop = ntz(YGNodeLayoutGetPadding(this->ygNode, YGEdgeTop)); float paddingLeft = ntz(YGNodeLayoutGetPadding(this->ygNode, YGEdgeLeft)); float paddingBottom = ntz(YGNodeLayoutGetPadding(this->ygNode, YGEdgeBottom)); float paddingRight = ntz(YGNodeLayoutGetPadding(this->ygNode, YGEdgeRight)); // Top if (paddingTop > 0) nvgRect(ctx->vg, x, y, width, paddingTop); // Right if (paddingRight > 0) nvgRect(ctx->vg, x + width - paddingRight, y, paddingRight, height); // Bottom if (paddingBottom > 0) nvgRect(ctx->vg, x, y + height - paddingBottom, width, paddingBottom); // Left if (paddingLeft > 0) nvgRect(ctx->vg, x, y, paddingLeft, height); nvgStroke(ctx->vg); // Margins nvgBeginPath(ctx->vg); nvgStrokeColor(ctx->vg, nvgRGB(255, 0, 0)); float marginTop = ntz(YGNodeLayoutGetMargin(this->ygNode, YGEdgeTop)); float marginLeft = ntz(YGNodeLayoutGetMargin(this->ygNode, YGEdgeLeft)); float marginBottom = ntz(YGNodeLayoutGetMargin(this->ygNode, YGEdgeBottom)); float marginRight = ntz(YGNodeLayoutGetMargin(this->ygNode, YGEdgeRight)); // Top if (marginTop > 0) nvgRect(ctx->vg, x - marginLeft, y - marginTop, width + marginLeft + marginRight, marginTop); // Right if (marginRight > 0) nvgRect(ctx->vg, x + width, y - marginTop, marginRight, height + marginTop + marginBottom); // Bottom if (marginBottom > 0) nvgRect(ctx->vg, x - marginLeft, y + height, width + marginLeft + marginRight, marginBottom); // Left if (marginLeft > 0) nvgRect(ctx->vg, x - marginLeft, y - marginTop, marginLeft, height + marginTop + marginBottom); nvgStroke(ctx->vg); } void View::drawBorder(NVGcontext* vg, FrameContext* ctx, Style style, float x, float y, float width, float height) { nvgBeginPath(vg); nvgStrokeColor(vg, this->borderColor); nvgStrokeWidth(vg, this->borderThickness); nvgRoundedRect(vg, x, y, width, height, this->cornerRadius); nvgStroke(vg); } void View::drawShadow(NVGcontext* vg, FrameContext* ctx, Style style, float x, float y, float width, float height) { float shadowWidth = 0.0f; float shadowFeather = 0.0f; float shadowOpacity = 0.0f; float shadowOffset = 0.0f; switch (this->shadowType) { case ShadowType::GENERIC: shadowWidth = style["brls/shadow/width"]; shadowFeather = style["brls/shadow/feather"]; shadowOpacity = style["brls/shadow/opacity"]; shadowOffset = style["brls/shadow/offset"]; break; case ShadowType::CUSTOM: break; case ShadowType::NONE: break; } NVGpaint shadowPaint = nvgBoxGradient( vg, x, y + shadowWidth, width, height, this->cornerRadius * 2, shadowFeather, RGBA(0, 0, 0, shadowOpacity * alpha), TRANSPARENT); nvgBeginPath(vg); nvgRect( vg, x - shadowOffset, y - shadowOffset, width + shadowOffset * 2, height + shadowOffset * 3); nvgRoundedRect(vg, x, y, width, height, this->cornerRadius); nvgPathWinding(vg, NVG_HOLE); nvgFillPaint(vg, shadowPaint); nvgFill(vg); } void View::collapse(bool animated) { if (animated) { Style style = Application::getStyle(); this->collapseState.reset(); this->collapseState.addStep(0.0f, style["brls/animations/collapse"], EasingFunction::quadraticOut); this->collapseState.setTickCallback([this] { if (this->hasParent()) this->getParent()->invalidate(); }); this->collapseState.start(); } else { this->collapseState = 0.0f; } } bool View::isCollapsed() { return this->collapseState < 1.0f; } void View::expand(bool animated) { if (animated) { Style style = Application::getStyle(); this->collapseState.reset(); this->collapseState.addStep(1.0f, style["brls/animations/collapse"], EasingFunction::quadraticOut); this->collapseState.setTickCallback([this] { if (this->hasParent()) this->getParent()->invalidate(); }); this->collapseState.start(); } else { this->collapseState = 1.0f; } } void View::setAlpha(float alpha) { this->alpha = alpha; } void View::drawHighlight(NVGcontext* vg, Theme theme, float alpha, Style style, bool background) { nvgSave(vg); nvgResetScissor(vg); float padding = this->highlightPadding; float cornerRadius = this->highlightCornerRadius; float strokeWidth = style["brls/highlight/stroke_width"]; float x = this->getX() - padding - strokeWidth / 2; float y = this->getY() - padding - strokeWidth / 2; float width = this->getWidth() + padding * 2 + strokeWidth; float height = this->getHeight() + padding * 2 + strokeWidth; // Shake animation if (this->highlightShaking) { Time curTime = getCPUTimeUsec() / 1000; Time t = (curTime - highlightShakeStart) / 10; if (t >= style["brls/animations/highlight_shake"]) { this->highlightShaking = false; } else { switch (this->highlightShakeDirection) { case FocusDirection::RIGHT: x += shakeAnimation(t, this->highlightShakeAmplitude); break; case FocusDirection::LEFT: x -= shakeAnimation(t, this->highlightShakeAmplitude); break; case FocusDirection::DOWN: y += shakeAnimation(t, this->highlightShakeAmplitude); break; case FocusDirection::UP: y -= shakeAnimation(t, this->highlightShakeAmplitude); break; } } } // Draw if (background) { // Background NVGcolor highlightBackgroundColor = theme["brls/highlight/background"]; nvgFillColor(vg, RGBAf(highlightBackgroundColor.r, highlightBackgroundColor.g, highlightBackgroundColor.b, this->highlightAlpha)); nvgBeginPath(vg); nvgRoundedRect(vg, x, y, width, height, cornerRadius); nvgFill(vg); } else { float shadowOffset = style["brls/highlight/shadow_offset"]; // Shadow NVGpaint shadowPaint = nvgBoxGradient(vg, x, y + style["brls/highlight/shadow_width"], width, height, cornerRadius * 2, style["brls/highlight/shadow_feather"], RGBA(0, 0, 0, style["brls/highlight/shadow_opacity"] * alpha), TRANSPARENT); nvgBeginPath(vg); nvgRect(vg, x - shadowOffset, y - shadowOffset, width + shadowOffset * 2, height + shadowOffset * 3); nvgRoundedRect(vg, x, y, width, height, cornerRadius); nvgPathWinding(vg, NVG_HOLE); nvgFillPaint(vg, shadowPaint); nvgFill(vg); // Border float gradientX, gradientY, color; getHighlightAnimation(&gradientX, &gradientY, &color); NVGcolor highlightColor1 = theme["brls/highlight/color1"]; NVGcolor pulsationColor = RGBAf((color * highlightColor1.r) + (1 - color) * highlightColor1.r, (color * highlightColor1.g) + (1 - color) * highlightColor1.g, (color * highlightColor1.b) + (1 - color) * highlightColor1.b, alpha); NVGcolor borderColor = theme["brls/highlight/color2"]; borderColor.a = 0.5f * alpha * this->getAlpha(); float strokeWidth = style["brls/highlight/stroke_width"]; NVGpaint border1Paint = nvgRadialGradient(vg, x + gradientX * width, y + gradientY * height, strokeWidth * 10, strokeWidth * 40, borderColor, TRANSPARENT); NVGpaint border2Paint = nvgRadialGradient(vg, x + (1 - gradientX) * width, y + (1 - gradientY) * height, strokeWidth * 10, strokeWidth * 40, borderColor, TRANSPARENT); nvgBeginPath(vg); nvgStrokeColor(vg, pulsationColor); nvgStrokeWidth(vg, strokeWidth); nvgRoundedRect(vg, x, y, width, height, cornerRadius); nvgStroke(vg); nvgBeginPath(vg); nvgStrokePaint(vg, border1Paint); nvgStrokeWidth(vg, strokeWidth); nvgRoundedRect(vg, x, y, width, height, cornerRadius); nvgStroke(vg); nvgBeginPath(vg); nvgStrokePaint(vg, border2Paint); nvgStrokeWidth(vg, strokeWidth); nvgRoundedRect(vg, x, y, width, height, cornerRadius); nvgStroke(vg); } nvgRestore(vg); } void View::setBackground(ViewBackground background) { this->background = background; } void View::drawBackground(NVGcontext* vg, FrameContext* ctx, Style style) { float x = this->getX(); float y = this->getY(); float width = this->getWidth(); float height = this->getHeight(); Theme theme = ctx->theme; switch (this->background) { case ViewBackground::SIDEBAR: { float backdropHeight = style["brls/sidebar/border_height"]; NVGcolor sidebarColor = theme["brls/sidebar/background"]; // Solid color nvgBeginPath(vg); nvgFillColor(vg, a(sidebarColor)); nvgRect(vg, x, y + backdropHeight, width, height - backdropHeight * 2); nvgFill(vg); //Borders gradient // Top NVGpaint topGradient = nvgLinearGradient(vg, x, y + backdropHeight, x, y, a(sidebarColor), TRANSPARENT); nvgBeginPath(vg); nvgFillPaint(vg, topGradient); nvgRect(vg, x, y, width, backdropHeight); nvgFill(vg); // Bottom NVGpaint bottomGradient = nvgLinearGradient(vg, x, y + height - backdropHeight, x, y + height, a(sidebarColor), TRANSPARENT); nvgBeginPath(vg); nvgFillPaint(vg, bottomGradient); nvgRect(vg, x, y + height - backdropHeight, width, backdropHeight); nvgFill(vg); break; } case ViewBackground::BACKDROP: { nvgFillColor(vg, a(theme["brls/backdrop"])); nvgBeginPath(vg); nvgRect(vg, x, y, width, height); nvgFill(vg); } case ViewBackground::SHAPE_COLOR: { nvgFillColor(vg, a(this->backgroundColor)); nvgBeginPath(vg); if (this->cornerRadius > 0.0f) nvgRoundedRect(vg, x, y, width, height, this->cornerRadius); else nvgRect(vg, x, y, width, height); nvgFill(vg); } case ViewBackground::NONE: break; } } ActionIdentifier View::registerAction(std::string hintText, enum ControllerButton button, ActionListener actionListener, bool hidden, enum Sound sound) { ActionIdentifier nextIdentifier = (this->actions.size() == 0) ? 1 : this->actions.back().identifier + 1; if (auto it = std::find(this->actions.begin(), this->actions.end(), button); it != this->actions.end()) *it = { button, nextIdentifier, hintText, true, hidden, sound, actionListener }; else this->actions.push_back({ button, nextIdentifier, hintText, true, hidden, sound, actionListener }); return nextIdentifier; } void View::unregisterAction(ActionIdentifier identifier) { auto is_matched_action = [identifier](Action action) { return action.identifier == identifier; }; if (auto it = std::find_if(this->actions.begin(), this->actions.end(), is_matched_action); it != this->actions.end()) this->actions.erase(it); } void View::registerClickAction(ActionListener actionListener) { this->registerAction("brls/hints/ok"_i18n, BUTTON_A, actionListener, false, SOUND_CLICK); } void View::updateActionHint(enum ControllerButton button, std::string hintText) { if (auto it = std::find(this->actions.begin(), this->actions.end(), button); it != this->actions.end()) it->hintText = hintText; Application::getGlobalHintsUpdateEvent()->fire(); } void View::setActionAvailable(enum ControllerButton button, bool available) { if (auto it = std::find(this->actions.begin(), this->actions.end(), button); it != this->actions.end()) it->available = available; } void View::setParent(Box* parent, void* parentUserdata) { this->parent = parent; this->parentUserdata = parentUserdata; } void* View::getParentUserData() { return this->parentUserdata; } bool View::isFocused() { return this->focused; } enum Sound View::getFocusSound() { return this->focusSound; } Box* View::getParent() { return this->parent; } bool View::hasParent() { return this->parent; } void View::setDimensions(float width, float height) { YGNodeStyleSetMinWidthPercent(this->ygNode, 0); YGNodeStyleSetMinHeightPercent(this->ygNode, 0); if (width == View::AUTO) { YGNodeStyleSetWidthAuto(this->ygNode); YGNodeStyleSetMinWidth(this->ygNode, YGUndefined); } else { YGNodeStyleSetWidth(this->ygNode, width); YGNodeStyleSetMinWidth(this->ygNode, width); } if (height == View::AUTO) { YGNodeStyleSetHeightAuto(this->ygNode); YGNodeStyleSetMinHeight(this->ygNode, YGUndefined); } else { YGNodeStyleSetHeight(this->ygNode, height); YGNodeStyleSetMinHeight(this->ygNode, height); } this->invalidate(); } void View::setWidth(float width) { YGNodeStyleSetMinWidthPercent(this->ygNode, 0); if (width == View::AUTO) { YGNodeStyleSetWidthAuto(this->ygNode); YGNodeStyleSetMinWidth(this->ygNode, YGUndefined); } else { YGNodeStyleSetWidth(this->ygNode, width); YGNodeStyleSetMinWidth(this->ygNode, width); } this->invalidate(); } void View::setHeight(float height) { YGNodeStyleSetMinHeightPercent(this->ygNode, 0); if (height == View::AUTO) { YGNodeStyleSetHeightAuto(this->ygNode); YGNodeStyleSetMinHeight(this->ygNode, YGUndefined); } else { YGNodeStyleSetHeight(this->ygNode, height); YGNodeStyleSetMinHeight(this->ygNode, height); } this->invalidate(); } void View::setWidthPercentage(float percentage) { YGNodeStyleSetWidthPercent(this->ygNode, percentage); YGNodeStyleSetMinWidthPercent(this->ygNode, percentage); this->invalidate(); } void View::setHeightPercentage(float percentage) { YGNodeStyleSetHeightPercent(this->ygNode, percentage); YGNodeStyleSetMinHeightPercent(this->ygNode, percentage); this->invalidate(); } void View::setMaxWidth(float maxWidth) { if (maxWidth == View::AUTO) YGNodeStyleSetMaxWidth(this->ygNode, YGUndefined); else YGNodeStyleSetMaxWidth(this->ygNode, maxWidth); this->invalidate(); } void View::setMaxWidthPercentage(float percentage) { YGNodeStyleSetMaxWidthPercent(this->ygNode, percentage); this->invalidate(); } void View::setMaxHeight(float maxHeight) { if (maxHeight == View::AUTO) YGNodeStyleSetMaxHeight(this->ygNode, YGUndefined); else YGNodeStyleSetMaxHeight(this->ygNode, maxHeight); this->invalidate(); } void View::setMaxHeightPercentage(float percentage) { YGNodeStyleSetMaxHeightPercent(this->ygNode, percentage); this->invalidate(); } void View::setMarginTop(float top) { if (top == brls::View::AUTO) YGNodeStyleSetMarginAuto(this->ygNode, YGEdgeTop); else YGNodeStyleSetMargin(this->ygNode, YGEdgeTop, top); this->invalidate(); } void View::setMarginRight(float right) { if (right == brls::View::AUTO) YGNodeStyleSetMarginAuto(this->ygNode, YGEdgeRight); else YGNodeStyleSetMargin(this->ygNode, YGEdgeRight, right); this->invalidate(); } float View::getMarginRight() { return ntz(YGNodeStyleGetMargin(this->ygNode, YGEdgeRight).value); } float View::getMarginLeft() { return ntz(YGNodeStyleGetMargin(this->ygNode, YGEdgeRight).value); } void View::setMarginBottom(float bottom) { if (bottom == brls::View::AUTO) YGNodeStyleSetMarginAuto(this->ygNode, YGEdgeBottom); else YGNodeStyleSetMargin(this->ygNode, YGEdgeBottom, bottom); this->invalidate(); } void View::setMarginLeft(float left) { if (left == brls::View::AUTO) YGNodeStyleSetMarginAuto(this->ygNode, YGEdgeLeft); else YGNodeStyleSetMargin(this->ygNode, YGEdgeLeft, left); this->invalidate(); } void View::setMargins(float top, float right, float bottom, float left) { if (top == brls::View::AUTO) YGNodeStyleSetMarginAuto(this->ygNode, YGEdgeTop); else YGNodeStyleSetMargin(this->ygNode, YGEdgeTop, top); if (right == brls::View::AUTO) YGNodeStyleSetMarginAuto(this->ygNode, YGEdgeRight); else YGNodeStyleSetMargin(this->ygNode, YGEdgeRight, right); if (bottom == brls::View::AUTO) YGNodeStyleSetMarginAuto(this->ygNode, YGEdgeBottom); else YGNodeStyleSetMargin(this->ygNode, YGEdgeBottom, bottom); if (left == brls::View::AUTO) YGNodeStyleSetMarginAuto(this->ygNode, YGEdgeLeft); else YGNodeStyleSetMargin(this->ygNode, YGEdgeLeft, left); this->invalidate(); } void View::setPositionTop(float pos) { if (pos == View::AUTO) YGNodeStyleSetPosition(this->ygNode, YGEdgeTop, YGUndefined); else YGNodeStyleSetPosition(this->ygNode, YGEdgeTop, pos); this->invalidate(); } void View::setPositionRight(float pos) { if (pos == View::AUTO) YGNodeStyleSetPosition(this->ygNode, YGEdgeRight, YGUndefined); else YGNodeStyleSetPosition(this->ygNode, YGEdgeRight, pos); this->invalidate(); } void View::setPositionBottom(float pos) { if (pos == View::AUTO) YGNodeStyleSetPosition(this->ygNode, YGEdgeBottom, YGUndefined); else YGNodeStyleSetPosition(this->ygNode, YGEdgeBottom, pos); this->invalidate(); } void View::setPositionLeft(float pos) { if (pos == View::AUTO) YGNodeStyleSetPosition(this->ygNode, YGEdgeLeft, YGUndefined); else YGNodeStyleSetPosition(this->ygNode, YGEdgeLeft, pos); this->invalidate(); } void View::setPositionTopPercentage(float percentage) { YGNodeStyleSetPositionPercent(this->ygNode, YGEdgeTop, percentage); this->invalidate(); } void View::setPositionRightPercentage(float percentage) { YGNodeStyleSetPositionPercent(this->ygNode, YGEdgeRight, percentage); this->invalidate(); } void View::setPositionBottomPercentage(float percentage) { YGNodeStyleSetPositionPercent(this->ygNode, YGEdgeBottom, percentage); this->invalidate(); } void View::setPositionLeftPercentage(float percentage) { YGNodeStyleSetPositionPercent(this->ygNode, YGEdgeLeft, percentage); this->invalidate(); } void View::setPositionType(PositionType type) { switch (type) { case PositionType::RELATIVE: YGNodeStyleSetPositionType(this->ygNode, YGPositionTypeRelative); break; case PositionType::ABSOLUTE: YGNodeStyleSetPositionType(this->ygNode, YGPositionTypeAbsolute); break; } this->invalidate(); } void View::setGrow(float grow) { YGNodeStyleSetFlexGrow(this->ygNode, grow); this->invalidate(); } void View::setShrink(float shrink) { YGNodeStyleSetFlexShrink(this->ygNode, shrink); this->invalidate(); } void View::setAlignSelf(AlignSelf alignSelf) { switch (alignSelf) { case AlignSelf::AUTO: YGNodeStyleSetAlignSelf(this->ygNode, YGAlignAuto); break; case AlignSelf::FLEX_START: YGNodeStyleSetAlignSelf(this->ygNode, YGAlignFlexStart); break; case AlignSelf::CENTER: YGNodeStyleSetAlignSelf(this->ygNode, YGAlignCenter); break; case AlignSelf::FLEX_END: YGNodeStyleSetAlignSelf(this->ygNode, YGAlignFlexEnd); break; case AlignSelf::STRETCH: YGNodeStyleSetAlignSelf(this->ygNode, YGAlignStretch); break; case AlignSelf::BASELINE: YGNodeStyleSetAlignSelf(this->ygNode, YGAlignBaseline); break; case AlignSelf::SPACE_BETWEEN: YGNodeStyleSetAlignSelf(this->ygNode, YGAlignSpaceBetween); break; case AlignSelf::SPACE_AROUND: YGNodeStyleSetAlignSelf(this->ygNode, YGAlignSpaceAround); break; } this->invalidate(); } void View::invalidate() { if (YGNodeHasMeasureFunc(this->ygNode)) YGNodeMarkDirty(this->ygNode); if (this->hasParent() && !this->detached) this->getParent()->invalidate(); else YGNodeCalculateLayout(this->ygNode, YGUndefined, YGUndefined, YGDirectionLTR); } float View::getX() { if (this->detached) return this->detachedOriginX + this->translationX; else if (this->hasParent()) return this->getParent()->getX() + YGNodeLayoutGetLeft(this->ygNode) + this->translationX; else return YGNodeLayoutGetLeft(this->ygNode) + this->translationX; } float View::getY() { if (this->detached) return this->detachedOriginY + this->translationY; else if (this->hasParent()) return this->getParent()->getY() + YGNodeLayoutGetTop(this->ygNode) + this->translationY; else return YGNodeLayoutGetTop(this->ygNode) + this->translationY; } float View::getHeight(bool includeCollapse) { return YGNodeLayoutGetHeight(this->ygNode) * (includeCollapse ? this->collapseState.getValue() : 1.0f); } float View::getWidth() { return YGNodeLayoutGetWidth(this->ygNode); } void View::detach() { this->detached = true; } void View::setDetachedPosition(float x, float y) { this->detachedOriginX = x; this->detachedOriginY = y; } bool View::isDetached() { return this->detached; } void View::onFocusGained() { this->focused = true; Style style = Application::getStyle(); this->highlightAlpha.reset(); this->highlightAlpha.addStep(1.0f, style["brls/animations/highlight"], EasingFunction::quadraticOut); this->highlightAlpha.start(); this->focusEvent.fire(this); if (this->hasParent()) this->getParent()->onChildFocusGained(this, this); } GenericEvent* View::getFocusEvent() { return &this->focusEvent; } void View::onFocusLost() { this->focused = false; Style style = Application::getStyle(); this->highlightAlpha.reset(); this->highlightAlpha.addStep(0.0f, style["brls/animations/highlight"], EasingFunction::quadraticOut); this->highlightAlpha.start(); if (this->hasParent()) this->getParent()->onChildFocusLost(this, this); } void View::setInFadeAnimation(bool inFadeAnimation) { this->inFadeAnimation = inFadeAnimation; } bool View::isTranslucent() { return this->fadeIn || this->inFadeAnimation; } void View::show(std::function cb) { this->show(cb, true, this->getShowAnimationDuration(TransitionAnimation::FADE)); } void View::show(std::function cb, bool animate, float animationDuration) { if (!this->hidden) { this->onShowAnimationEnd(); cb(); return; } brls::Logger::debug("Showing {}", this->describe()); this->hidden = false; this->fadeIn = true; if (animate) { this->alpha.reset(0.0f); this->alpha.addStep(1.0f, animationDuration, EasingFunction::quadraticOut); this->alpha.setEndCallback([this, cb](bool finished) { this->fadeIn = false; this->onShowAnimationEnd(); cb(); }); this->alpha.start(); } else { this->alpha = 1.0f; this->fadeIn = false; this->onShowAnimationEnd(); cb(); } } void View::hide(std::function cb) { this->hide(cb, true, this->getShowAnimationDuration(TransitionAnimation::FADE)); } void View::hide(std::function cb, bool animated, float animationDuration) { if (this->hidden) { cb(); return; } brls::Logger::debug("Hiding {}", this->describe()); this->hidden = true; this->fadeIn = false; if (animated) { this->alpha.reset(1.0f); this->alpha.addStep(0.0f, animationDuration, EasingFunction::quadraticOut); this->alpha.setEndCallback([cb](bool finished) { cb(); }); this->alpha.start(); } else { this->alpha = 0.0f; cb(); } } float View::getShowAnimationDuration(TransitionAnimation animation) { Style style = Application::getStyle(); if (animation == TransitionAnimation::SLIDE_LEFT || animation == TransitionAnimation::SLIDE_RIGHT) fatal("Slide animation is not supported on views"); return style["brls/animations/show"]; } bool View::isHidden() { return this->hidden; } void View::overrideTheme(Theme* newTheme) { this->themeOverride = newTheme; } void View::onParentFocusGained(View* focusedView) { } void View::onParentFocusLost(View* focusedView) { } void View::setCustomNavigationRoute(FocusDirection direction, View* target) { if (!this->focusable) fatal("Only focusable views can have a custom navigation route"); this->customFocusByPtr[direction] = target; } void View::setCustomNavigationRoute(FocusDirection direction, std::string targetId) { if (!this->focusable) fatal("Only focusable views can have a custom navigation route"); this->customFocusById[direction] = targetId; } bool View::hasCustomNavigationRouteByPtr(FocusDirection direction) { return this->customFocusByPtr.count(direction) > 0; } bool View::hasCustomNavigationRouteById(FocusDirection direction) { return this->customFocusById.count(direction) > 0; } View* View::getCustomNavigationRoutePtr(FocusDirection direction) { return this->customFocusByPtr[direction]; } std::string View::getCustomNavigationRouteId(FocusDirection direction) { return this->customFocusById[direction]; } View::~View() { this->resetClickAnimation(); // Parent userdata if (this->parentUserdata) { free(this->parentUserdata); this->parentUserdata = nullptr; } // Focus sanity check if (Application::getCurrentFocus() == this) Application::giveFocus(nullptr); for (tinyxml2::XMLDocument* document : this->boundDocuments) delete document; } std::string View::getStringXMLAttributeValue(std::string value) { if (startsWith(value, "@i18n/")) { std::string stringName = value.substr(6); return getStr(stringName); } return value; } std::string View::getFilePathXMLAttributeValue(std::string value) { if (startsWith(value, "@res/")) { std::string resPath = value.substr(5); return std::string(BRLS_RESOURCES) + resPath; } return value; } bool View::applyXMLAttribute(std::string name, std::string value) { // String -> string if (this->stringAttributes.count(name) > 0) { if (startsWith(value, "@i18n/")) { this->stringAttributes[name](View::getStringXMLAttributeValue(value)); return true; } this->stringAttributes[name](value); return true; } // File path -> file path if (startsWith(value, "@res/")) { std::string path = View::getFilePathXMLAttributeValue(value); if (this->filePathAttributes.count(name) > 0) { this->filePathAttributes[name](path); return true; } else { return false; // unknown res } } else { if (this->filePathAttributes.count(name) > 0) { this->filePathAttributes[name](value); return true; } // don't return false as it can be anything else } // Auto -> auto if (value == "auto") { if (this->autoAttributes.count(name) > 0) { this->autoAttributes[name](); return true; } else { return false; } } // Ends with px -> float if (endsWith(value, "px")) { // Strip the px and parse the float value std::string newFloat = value.substr(0, value.length() - 2); try { float floatValue = std::stof(newFloat); if (this->floatAttributes.count(name) > 0) { this->floatAttributes[name](floatValue); return true; } else { return false; } } catch (const std::invalid_argument& exception) { return false; } } // Ends with % -> percentage if (endsWith(value, "%")) { // Strip the % and parse the float value std::string newFloat = value.substr(0, value.length() - 1); try { float floatValue = std::stof(newFloat); if (floatValue < -100 || floatValue > 100) return false; if (this->percentageAttributes.count(name) > 0) { this->percentageAttributes[name](floatValue); return true; } else { return false; } } catch (const std::invalid_argument& exception) { return false; } } // Starts with @style -> float else if (startsWith(value, "@style/")) { // Parse the style name std::string styleName = value.substr(7); // length of "@style/" float value = Application::getStyle()[styleName]; // will throw logic_error if the metric doesn't exist if (this->floatAttributes.count(name) > 0) { this->floatAttributes[name](value); return true; } else { return false; } } // Starts with with # -> color else if (startsWith(value, "#")) { // Parse the color // #RRGGBB format if (value.size() == 7) { unsigned char r, g, b; int result = sscanf(value.c_str(), "#%02hhx%02hhx%02hhx", &r, &g, &b); if (result != 3) return false; else if (this->colorAttributes.count(name) > 0) { this->colorAttributes[name](nvgRGB(r, g, b)); return true; } else { return false; } } // #RRGGBBAA format else if (value.size() == 9) { unsigned char r, g, b, a; int result = sscanf(value.c_str(), "#%02hhx%02hhx%02hhx%02hhx", &r, &g, &b, &a); if (result != 4) return false; else if (this->colorAttributes.count(name) > 0) { this->colorAttributes[name](nvgRGBA(r, g, b, a)); return true; } else { return false; } } else { return false; } } // Starts with @theme -> color else if (startsWith(value, "@theme/")) { // Parse the color name std::string colorName = value.substr(7); // length of "@theme/" NVGcolor value = Application::getTheme()[colorName]; // will throw logic_error if the color doesn't exist if (this->colorAttributes.count(name) > 0) { this->colorAttributes[name](value); return true; } else { return false; } } // Equals true or false -> bool else if (value == "true" || value == "false") { bool boolValue = value == "true" ? true : false; if (this->boolAttributes.count(name) > 0) { this->boolAttributes[name](boolValue); return true; } else { return false; } } // Valid float -> float, otherwise unknown attribute try { float newValue = std::stof(value); if (this->floatAttributes.count(name) > 0) { this->floatAttributes[name](newValue); return true; } else { return false; } } catch (const std::invalid_argument& exception) { return false; } } void View::applyXMLAttributes(tinyxml2::XMLElement* element) { if (!element) return; for (const tinyxml2::XMLAttribute* attribute = element->FirstAttribute(); attribute != nullptr; attribute = attribute->Next()) { std::string name = attribute->Name(); std::string value = std::string(attribute->Value()); if (!this->applyXMLAttribute(name, value)) this->printXMLAttributeErrorMessage(element, name, value); } } bool View::isXMLAttributeValid(std::string attributeName) { return this->knownAttributes.count(attributeName) > 0; } View* View::createFromXMLResource(std::string name) { return View::createFromXMLFile(std::string(BRLS_RESOURCES) + "xml/" + name); } View* View::createFromXMLString(std::string xml) { tinyxml2::XMLDocument* document = new tinyxml2::XMLDocument(); tinyxml2::XMLError error = document->Parse(xml.c_str()); if (error != tinyxml2::XMLError::XML_SUCCESS) fatal("Invalid XML when creating View from XML: error " + std::to_string(error)); tinyxml2::XMLElement* root = document->RootElement(); if (!root) fatal("Invalid XML: no element found"); View* view = View::createFromXMLElement(root); view->bindXMLDocument(document); return view; } View* View::createFromXMLFile(std::string path) { tinyxml2::XMLDocument* document = new tinyxml2::XMLDocument(); tinyxml2::XMLError error = document->LoadFile(path.c_str()); if (error != tinyxml2::XMLError::XML_SUCCESS) fatal("Unable to load XML file \"" + path + "\": error " + std::to_string(error)); tinyxml2::XMLElement* element = document->RootElement(); if (!element) fatal("Unable to load XML file \"" + path + "\": no root element found, is the file empty?"); View* view = View::createFromXMLElement(element); view->bindXMLDocument(document); return view; } View* View::createFromXMLElement(tinyxml2::XMLElement* element) { if (!element) return nullptr; std::string viewName = element->Name(); // Instantiate the view View* view = nullptr; // Special case where element name is brls:View: create from given XML file. // XML attributes are explicitely not passed down to the created view. // To create a custom view from XML that you can reuse in other XML files, // make a class inheriting brls::Box and use the inflateFromXML* methods. if (viewName == "brls:View") { const tinyxml2::XMLAttribute* xmlAttribute = element->FindAttribute("xml"); if (xmlAttribute) view = View::createFromXMLFile(View::getFilePathXMLAttributeValue(xmlAttribute->Value())); else fatal("brls:View XML tag must have an \"xml\" attribute"); } // Otherwise look in the register else { if (!Application::XMLViewsRegisterContains(viewName)) fatal("Unknown XML tag \"" + viewName + "\""); view = Application::getXMLViewCreator(viewName)(); view->applyXMLAttributes(element); } unsigned count = 0; unsigned max = view->getMaximumAllowedXMLElements(); for (tinyxml2::XMLElement* child = element->FirstChildElement(); child != nullptr; child = child->NextSiblingElement()) { if (count >= max) fatal("View \"" + view->describe() + "\" is only allowed to have " + std::to_string(max) + " children XML elements"); else view->handleXMLElement(child); count++; } return view; } void View::handleXMLElement(tinyxml2::XMLElement* element) { fatal("Raw views cannot have child XML tags"); } void View::setMaximumAllowedXMLElements(unsigned max) { this->maximumAllowedXMLElements = max; } unsigned View::getMaximumAllowedXMLElements() { return this->maximumAllowedXMLElements; } void View::registerCommonAttributes() { // Width this->registerAutoXMLAttribute("width", [this] { this->setWidth(View::AUTO); }); this->registerFloatXMLAttribute("width", [this](float value) { this->setWidth(value); }); this->registerPercentageXMLAttribute("width", [this](float value) { this->setWidthPercentage(value); }); // Height this->registerAutoXMLAttribute("height", [this] { this->setHeight(View::AUTO); }); this->registerFloatXMLAttribute("height", [this](float value) { this->setHeight(value); }); this->registerPercentageXMLAttribute("height", [this](float value) { this->setHeightPercentage(value); }); // Max width this->registerAutoXMLAttribute("maxWidth", [this] { this->setMaxWidth(View::AUTO); }); this->registerFloatXMLAttribute("maxWidth", [this](float value) { this->setMaxWidth(value); }); this->registerPercentageXMLAttribute("maxWidth", [this](float percentage) { this->setMaxWidthPercentage(percentage); }); // Max height this->registerAutoXMLAttribute("maxHeight", [this] { this->setMaxHeight(View::AUTO); }); this->registerFloatXMLAttribute("maxHeight", [this](float value) { this->setMaxHeight(value); }); this->registerPercentageXMLAttribute("maxHeight", [this](float percentage) { this->setMaxHeightPercentage(percentage); }); // Grow and shrink this->registerFloatXMLAttribute("grow", [this](float value) { this->setGrow(value); }); this->registerFloatXMLAttribute("shrink", [this](float value) { this->setShrink(value); }); // Alignment BRLS_REGISTER_ENUM_XML_ATTRIBUTE( "alignSelf", AlignSelf, this->setAlignSelf, { { "auto", AlignSelf::AUTO }, { "flexStart", AlignSelf::FLEX_START }, { "center", AlignSelf::CENTER }, { "flexEnd", AlignSelf::FLEX_END }, { "stretch", AlignSelf::STRETCH }, { "baseline", AlignSelf::BASELINE }, { "spaceBetween", AlignSelf::SPACE_BETWEEN }, { "spaceAround", AlignSelf::SPACE_AROUND }, }); // Margins top this->registerFloatXMLAttribute("marginTop", [this](float value) { this->setMarginTop(value); }); this->registerAutoXMLAttribute("marginTop", [this] { this->setMarginTop(View::AUTO); }); // Margin right this->registerFloatXMLAttribute("marginRight", [this](float value) { this->setMarginRight(value); }); this->registerAutoXMLAttribute("marginRight", [this] { this->setMarginRight(View::AUTO); }); // Margin bottom this->registerFloatXMLAttribute("marginBottom", [this](float value) { this->setMarginBottom(value); }); this->registerAutoXMLAttribute("marginBottom", [this] { this->setMarginBottom(View::AUTO); }); // Margin left this->registerFloatXMLAttribute("marginLeft", [this](float value) { this->setMarginLeft(value); }); this->registerAutoXMLAttribute("marginLeft", [this] { this->setMarginLeft(View::AUTO); }); // Line this->registerColorXMLAttribute("lineColor", [this](NVGcolor color) { this->setLineColor(color); }); this->registerFloatXMLAttribute("lineTop", [this](float value) { this->setLineTop(value); }); this->registerFloatXMLAttribute("lineRight", [this](float value) { this->setLineRight(value); }); this->registerFloatXMLAttribute("lineBottom", [this](float value) { this->setLineBottom(value); }); this->registerFloatXMLAttribute("lineLeft", [this](float value) { this->setLineLeft(value); }); // Position this->registerFloatXMLAttribute("positionTop", [this](float value) { this->setPositionTop(value); }); this->registerFloatXMLAttribute("positionRight", [this](float value) { this->setPositionRight(value); }); this->registerFloatXMLAttribute("positionBottom", [this](float value) { this->setPositionBottom(value); }); this->registerFloatXMLAttribute("positionLeft", [this](float value) { this->setPositionLeft(value); }); this->registerPercentageXMLAttribute("positionTop", [this](float value) { this->setPositionTopPercentage(value); }); this->registerPercentageXMLAttribute("positionRight", [this](float value) { this->setPositionRightPercentage(value); }); this->registerPercentageXMLAttribute("positionBottom", [this](float value) { this->setPositionBottomPercentage(value); }); this->registerPercentageXMLAttribute("positionLeft", [this](float value) { this->setPositionLeftPercentage(value); }); BRLS_REGISTER_ENUM_XML_ATTRIBUTE( "positionType", PositionType, this->setPositionType, { { "relative", PositionType::RELATIVE }, { "absolute", PositionType::ABSOLUTE }, }); // Custom focus routes this->registerStringXMLAttribute("focusUp", [this](std::string value) { this->setCustomNavigationRoute(FocusDirection::UP, value); }); this->registerStringXMLAttribute("focusRight", [this](std::string value) { this->setCustomNavigationRoute(FocusDirection::RIGHT, value); }); this->registerStringXMLAttribute("focusDown", [this](std::string value) { this->setCustomNavigationRoute(FocusDirection::DOWN, value); }); this->registerStringXMLAttribute("focusLeft", [this](std::string value) { this->setCustomNavigationRoute(FocusDirection::LEFT, value); }); // Shape this->registerColorXMLAttribute("backgroundColor", [this](NVGcolor value) { this->setBackgroundColor(value); }); this->registerColorXMLAttribute("borderColor", [this](NVGcolor value) { this->setBorderColor(value); }); this->registerFloatXMLAttribute("borderThickness", [this](float value) { this->setBorderThickness(value); }); this->registerFloatXMLAttribute("cornerRadius", [this](float value) { this->setCornerRadius(value); }); BRLS_REGISTER_ENUM_XML_ATTRIBUTE( "shadowType", ShadowType, this->setShadowType, { { "none", ShadowType::NONE, }, { "generic", ShadowType::GENERIC, }, { "custom", ShadowType::CUSTOM, }, }); // Misc BRLS_REGISTER_ENUM_XML_ATTRIBUTE( "visibility", Visibility, this->setVisibility, { { "visible", Visibility::VISIBLE }, { "invisible", Visibility::INVISIBLE }, { "gone", Visibility::GONE }, }); this->registerStringXMLAttribute("id", [this](std::string value) { this->setId(value); }); BRLS_REGISTER_ENUM_XML_ATTRIBUTE( "background", ViewBackground, this->setBackground, { { "sidebar", ViewBackground::SIDEBAR }, { "backdrop", ViewBackground::BACKDROP }, }); this->registerBoolXMLAttribute("focusable", [this](bool value) { this->setFocusable(value); }); this->registerBoolXMLAttribute("wireframe", [this](bool value) { this->setWireframeEnabled(value); }); // Highlight this->registerBoolXMLAttribute("hideHighlightBackground", [this](bool value) { this->setHideHighlightBackground(value); }); this->registerFloatXMLAttribute("highlightPadding", [this](float value) { this->setHighlightPadding(value); }); this->registerFloatXMLAttribute("highlightCornerRadius", [this](float value) { this->setHighlightCornerRadius(value); }); } void View::setTranslationY(float translationY) { this->translationY = translationY; } void View::setTranslationX(float translationX) { this->translationX = translationX; } void View::setVisibility(Visibility visibility) { // Only change YG properties and invalidate if going from or to GONE if ((this->visibility == Visibility::GONE && visibility != Visibility::GONE) || (this->visibility != Visibility::GONE && visibility == Visibility::GONE)) { if (visibility == Visibility::GONE) YGNodeStyleSetDisplay(this->ygNode, YGDisplayNone); else YGNodeStyleSetDisplay(this->ygNode, YGDisplayFlex); this->invalidate(); } this->visibility = visibility; if (visibility == Visibility::VISIBLE) this->willAppear(); else this->willDisappear(); } void View::printXMLAttributeErrorMessage(tinyxml2::XMLElement* element, std::string name, std::string value) { if (this->knownAttributes.find(name) != this->knownAttributes.end()) fatal("Illegal value \"" + value + "\" for \"" + std::string(element->Name()) + "\" XML attribute \"" + name + "\""); else fatal("Unknown XML attribute \"" + name + "\" for tag \"" + std::string(element->Name()) + "\" (with value \"" + value + "\")"); } void View::registerFloatXMLAttribute(std::string name, FloatAttributeHandler handler) { this->floatAttributes[name] = handler; this->knownAttributes.insert(name); } void View::registerPercentageXMLAttribute(std::string name, FloatAttributeHandler handler) { this->percentageAttributes[name] = handler; this->knownAttributes.insert(name); } void View::registerAutoXMLAttribute(std::string name, AutoAttributeHandler handler) { this->autoAttributes[name] = handler; this->knownAttributes.insert(name); } void View::registerStringXMLAttribute(std::string name, StringAttributeHandler handler) { this->stringAttributes[name] = handler; this->knownAttributes.insert(name); } void View::registerColorXMLAttribute(std::string name, ColorAttributeHandler handler) { this->colorAttributes[name] = handler; this->knownAttributes.insert(name); } void View::registerBoolXMLAttribute(std::string name, BoolAttributeHandler handler) { this->boolAttributes[name] = handler; this->knownAttributes.insert(name); } void View::registerFilePathXMLAttribute(std::string name, FilePathAttributeHandler handler) { this->filePathAttributes[name] = handler; this->knownAttributes.insert(name); } float ntz(float value) { return std::isnan(value) ? 0.0f : value; } View* View::getView(std::string id) { if (id == this->id) return this; return nullptr; } View* View::getNearestView(std::string id) { // First try a children of ours View* child = this->getView(id); if (child) return child; // Then go up one level and try again if (this->hasParent()) return this->getParent()->getNearestView(id); return nullptr; } void View::setId(std::string id) { if (id == "") fatal("ID cannot be empty"); this->id = id; } bool View::isFocusable() { return this->focusable && this->visibility == Visibility::VISIBLE; } View* View::getDefaultFocus() { if (this->isFocusable()) return this; return nullptr; } void View::bindXMLDocument(tinyxml2::XMLDocument* document) { this->boundDocuments.push_back(document); } void View::setWireframeEnabled(bool wireframe) { this->wireframeEnabled = wireframe; } bool View::isWireframeEnabled() { return this->wireframeEnabled; } } // namespace brls #include #include "avhttp.hpp" int main(int argc, char* argv[]) { std::vector unreserved_chars; for(char i = 'a'; i <= 'z'; ++i) { unreserved_chars.push_back(i); } for(char i = 'A'; i <= 'Z'; ++i) { unreserved_chars.push_back(i); } for(char i = '0'; i <= '9'; ++i) { unreserved_chars.push_back(i); } unreserved_chars.push_back('-'); unreserved_chars.push_back('_'); unreserved_chars.push_back('.'); unreserved_chars.push_back('~'); std::set unescaped_chars_set(unreserved_chars.begin(), unreserved_chars.end()); std::vector all_asci_vector; for(size_t i = 0; i <= 0xff; ++i) { all_asci_vector.push_back(static_cast(i)); } std::string str(&all_asci_vector[0], all_asci_vector.size()); auto encoded = avhttp::detail::escape_string(str); assert(encoded.size() == (all_asci_vector.size() - unreserved_chars.size()) * 3 + unreserved_chars.size()); int position = 0; for(size_t i = 0; i < all_asci_vector.size(); ++i) { char ch = all_asci_vector[i]; if (unescaped_chars_set.end() != unescaped_chars_set.find(ch)) { assert(encoded[position] == ch); position += 1; } else { char out_str[3]; avhttp::detail::to_hex(&ch, 1, out_str); assert(encoded[position] == '%'); assert(encoded[position+1] == out_str[0]); assert(encoded[position+2] == out_str[1]); position += 3; } } std::string decoded; bool res = avhttp::detail::unescape_path(encoded, decoded); assert(res); assert(decoded == str); return 0; } scignscape/PGVMextra/facs/data/Dataset.cpp0 // // license___here_h #include "Dataset.h" #include "ChannelInfo.h" #include "bridge/qvector-matrix-r8.h" #include #include Dataset::Dataset(QVector_Matrix_R8* eventsFloat) : eventsFloat_(eventsFloat) { if(eventsFloat_) numChannel_ = eventsFloat_->n_cols(); else numChannel_ = 0; numPc_ = 0; numCompensated_ = 0; if(eventsFloat_) eventsFloatCompensated_ = eventsFloat_->new_from_dimensions(); else eventsFloatCompensated_ = nullptr; if(eventsFloat_) { test_compensation_matrix_ = new QVector_Matrix_R8( eventsFloat_->n_cols(), eventsFloat_->n_cols()); test_compensation_matrix_->fill_diagonal(); do_preliminary_compensation(); } } void Dataset::do_preliminary_compensation() { for(u4 r = 1; r <= eventsFloat_->n_rows(); ++r) { QVector row; eventsFloat_->get_row(r, row); QVector mrow; test_compensation_matrix_->multiply(row, mrow); eventsFloatCompensated_->merge_row(row, r); } // qDebug() << "getting extrema ..." << eventsFloat_->n_cols() // << ", " << eventsFloat_->n_rows() // << ", " << eventsFloatCompensated_->n_cols() // << ", " << eventsFloatCompensated_->n_rows() ; /* for(u4 c = 1; c <= eventsFloat_->n_cols(); ++c) { QPair pr = eventsFloat_->get_extrema_in_column(c); qDebug() << "Min, Max for EF col " << c << ": " << pr; } for(u4 c = 1; c <= eventsFloatCompensated_->n_cols(); ++c) { QPair pr = eventsFloatCompensated_->get_extrema_in_column(c); qDebug() << "Min, Max for EFC col " << c << ": " << pr; } */ eventsFloatCompensated_->get_column_extrema(extrema_); qDebug() << "Extrema: " << extrema_; // // temp ... numCompensated_ = numChannel_; } QList Dataset::getChannelInfo() { return channelInfo_; } int Dataset::getNumObservations() { // return eventsFloat_.size(); return eventsFloat_->n_rows(); } int Dataset::getNumChannels() { return numCompensated_; // return numChannel+numPc; } int Dataset::getNumLengthProfiles() { return lengthprofsInfo_.size(); } QString Dataset::getName() { return source_.fileName(); } QString Dataset::get_file_source_name() { // // ok? return source_.fileName(); } double Dataset::getAsFloatCompensated(int obs, int indexChan) { qDebug() << "Ef: " << eventsFloat_->at(obs, indexChan); //? return (*eventsFloatCompensated_)[obs](indexChan); //return eventsFloat_->at(obs, indexChan); //return eventsFloat.get(obs)[indexChan]; } QVector Dataset::getAsFloatCompensated(int obs) { QVector result; eventsFloatCompensated_->get_row(obs, result); return result; // return eventsFloat.get(obs); } // // Compute profile channels. or only one if not null void Dataset::computeProfChannel(FacsanaduProject* proj, ProfChannel* forPc) { Q_UNUSED(proj) Q_UNUSED(forPc) /* //If deleting or adding a channel... I find it fine enough to recompute everything. But this should //not be done if just modifying a gate HashSet oldPc=new HashSet(); for(ChannelInfo i:channelInfo) if(i.pc!=null) oldPc.add(i.pc); if(!oldPc.equals(new HashSet(proj.profchan))) { //System.out.println("Recomp all chan"); //Recompute all channels for(ChannelInfo i:new ArrayList(channelInfo)) if(i.pc!=null) channelInfo.remove(i); for(ProfChannel pc:proj.profchan) { ChannelInfo i=new ChannelInfo(); i.label=pc.getName(); i.pc=pc; channelInfo.add(i); } //Add new channels numPc=proj.profchan.size(); resizeEvents(numChannel+numPc); for(int i=0;ipc() == pc) return ci; } //throw new RuntimeException("No channel info for prof channel"); return nullptr; } void Dataset::setEvents(QVector_Matrix_R8* e) // QList> e) { eventsFloat_ = e; //? numChannel_ = 0; //? if(getNumObservations() > 0) //? numChannel_ = eventsFloat_.first().length(); numChannel_ = eventsFloat_->n_cols(); } // // Resize the events. Used to make space for virtual channels void Dataset::resizeEvents(int newsize) { QList> newEventsFloat; // =new ArrayList(eventsFloat.size()); /* for(QList o : eventsFloat_) { QVector n(newsize); // =new double[newsize]; std::copy_n(o.begin(), numChannel_, n.begin()); //?System.arraycopy(o, 0, n, 0, numChannel); newEventsFloat.push_back(n.toList()); } //? eventsFloat_ = newEventsFloat; */ } grafika-komputer/titik.cpp /* Praktikum Grafika Komputer Laboratorium Komputer Universitas Pakuan 2022 */ #include #define WINDOW_WIDTH 360 #define WINDOW_HEIGHT 360 void createPoint(float x, float y, float point_size) { glPointSize(point_size); glBegin(GL_POINTS); glColor3f(1.0f, 1.0f, 1.0f); glVertex2f(x, y); glEnd(); } void draw() { glClearColor(0.0f, 0.0f, 0.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); createPoint(0.0f, 0.0f, 10.0f); glFlush(); } void window(int width, int height) { glutReshapeWindow(WINDOW_WIDTH, WINDOW_HEIGHT); } int main(int argc, char **argv) { glutInit(&argc, argv); glutInitWindowSize(WINDOW_WIDTH, WINDOW_HEIGHT); glutInitDisplayMode(GLUT_SINGLE | GLUT_RGBA); glutCreateWindow("Grafkom LABKOM: Titik"); glutReshapeFunc(window); glutDisplayFunc(draw); glutMainLoop(); return 0; }#pragma once // math_classify.hpp: classification functions for fixed-points // // Copyright (C) 2017-2021 Stillwater Supercomputing, Inc. // // This file is part of the universal numbers project, which is released under an MIT Open Source license. namespace sw::universal { // STD LIB function for IEEE floats: Categorizes floating point value arg into the following categories: zero, subnormal, normal, infinite, NAN, or implementation-defined category. template int fpclassify(const fixpnt& a) { return std::fpclassify((long double)(a)); } // STD LIB function for IEEE floats: Determines if the given floating point number arg has finite value i.e. it is normal, subnormal or zero, but not infinite or NaN. // specialized for fixpnts template inline bool isfinite(const fixpnt& a) { return true; } // STD LIB function for IEEE floats: Determines if the given floating point number arg is a fixpntive or negative infinity. // specialized for fixpnts template inline bool isinf(const fixpnt& a) { return false; } // STD LIB function for IEEE floats: Determines if the given floating point number arg is a not-a-number (NaN) value. // specialized for fixpnts template inline bool isnan(const fixpnt& a) { return false; } // STD LIB function for IEEE floats: Determines if the given floating point number arg is normal, i.e. is neither zero, subnormal, infinite, nor NaN. // specialized for fixpnts template inline bool isnormal(const fixpnt& a) { return true; } } // namespace sw::universal 1-10 #pragma once #include #include #include #include #include #include #include #include #include #include #include #include #include #include "data_structures/sparse_prefix_sum.hpp" #include "data_structures/csr_matrix.hpp" /** * @brief This namespace contains required functions for * the Subgradient Optimization algorithm. This algorithm * requires the sparse-prefix-sum data-structure. **/ #if defined(ENABLE_CPP_PARALLEL) namespace sarma::subgradient_method { #else namespace sarma{ namespace subgradient_method { #endif template auto uniform_init(const Int P, const Value total_load) { std::vector pi(P - 1, 0.0); for (Int i = 0; i < pi.size(); i++) pi[i] = total_load * (i + 1.0) / P; return pi; } template auto random_init(const Int P, const Value total_load, Gen &gen) { std::uniform_real_distribution rnd(0, total_load); std::vector pi(P - 1, 0.0); for (auto &x: pi) x = rnd(gen); std::sort(std::begin(pi), std::end(pi)); return pi; } /** * @brief Implements the SubGradient Optimization algorithm. * This algorithm initializes the cut vectors randomly and * tries to refine them at each iteration by moving all the * cuts in the negative direction of the gradient to minimize * the maximum load. * * @param pis vector of cut vector parametrizations * @param to_rs lambda function to compute gradients given pis * @param C number of iterations to wait when objective value flattens * @param eps the improvement in the optimization objective expected * @return vector of cut vector parametrizations */ template auto partition(std::vector> &pis, pis_to_rs_t to_rs, const std::size_t C = 10, const double eps = 0.001) { using Value = typename decltype(to_rs(pis))::value_type::value_type; const auto t1 = std::vector(pis.size(), 1); auto t = [&](std::size_t m, std::size_t i) -> double { return t1[i] / std::sqrt(m + 100); }; auto best_pis = std::make_pair(pis, std::numeric_limits::max()); std::size_t p_best_m = 1; auto p_best_pis = best_pis; for (std::size_t m = 1;; m++) { const auto rs = to_rs(pis); const auto maxLoad = *std::max_element(std::begin(rs[0]), std::end(rs[0])); if (best_pis.second > maxLoad) best_pis = {pis, maxLoad}; auto minLoad = std::numeric_limits::max(); for (std::size_t k = 0; k < rs.size(); k++) { std::vector u; const auto avg = std::accumulate(std::begin(rs[k]), std::end(rs[k]), (double)0) / rs[k].size(); std::transform(std::begin(rs[k]), std::end(rs[k]), std::back_inserter(u), [avg] (const auto r_i) { return r_i - avg; }); std::partial_sum(std::begin(u), std::end(u), std::begin(u)); std::for_each(std::begin(pis[k]), std::end(pis[k]), [&](auto &pi_i) { const auto i = std::distance(pis[k].data(), &pi_i); pi_i -= t(m / (pis[k].size() + 2), k) * u[i]; }); std::sort(std::begin(pis[k]), std::end(pis[k])); minLoad = std::min(minLoad, *std::min_element(std::begin(rs[k]), std::end(rs[k]))); } const auto err = (maxLoad - minLoad) * 1.0 / minLoad; #ifdef DEBUG for (auto r: rs) { for (auto x: r) std::cerr << x << ' '; std::cerr << std::endl; } std::cerr << m << ' ' << maxLoad << ' ' << err << ' ' << eps << '\n'; #endif std::size_t PQ = 0; for (const auto &pi: pis) PQ += pi.size() + 2; if (err < eps) break; else if (m - p_best_m > C * PQ) { if (best_pis.second * (1 + eps) >= p_best_pis.second) break; p_best_pis = best_pis; p_best_m = m; } } return best_pis.first; } /** * @brief An easy to use wrapper for the the SubGradient Optimization algorithm. * This algorithm initializes the cut vectors randomly and * tries to refine them at each iteration by moving all the * cuts in the negative direction of the gradient to minimize * the maximum load. The first parameter, the string s describes * the optimization objective. Each term in the optimization objective * is made up of a digit indicating the index of the matrix, the name of * the first dimension of the matrix and the name of the second dimension * of the matrix separated by "+" signs inbetween. As examples, sgo_2dr -> "0ij", * sgo_2ds -> "0ij,i=j", sgo_3ds -> "0ij+0jk+0ik" and sgo_3dr -> * "0ij+1jk". As one can guess, the part before the comma represents * the optimization objective and after the comma includes constraints * that can't be derived automatically from the optimization objective. * As an example, for sgo_2ds, we had to explicitly put the constraint * that the two cut vectors in the two dimensions need to be the same via * stating "i=j". However, sgo_3ds can do that automatically because the same * matrix dimension is named different letters "i" and "j" etc. that that causes * all the dimensions to collapse into one removing the need to put the constraints * explicitly. * * @param s a string describing the optimization objective * @param A a vector of references to matrices used in the optimization objective * @param P number of parts in each dimension of the resulting cut vectors * @param seed * @return a vector of cut vectors */ template auto partition(const std::string s, const std::vector>> As, const std::vector Ps, int seed = 1) { std::vector> terms; std::set cs; std::map id; std::vector> rid; std::map>> rjd; Int N = 0; { std::map, std::set> m; std::map>> n; #if defined(ENABLE_CPP_PARALLEL) for (auto [i, s_end, constr] = std::make_tuple(s.c_str(), s.c_str() + s.size(), false); i < s_end; i++) { #else auto i = s.c_str(); auto s_end = s.c_str() + s.size(); auto constr = false; for (; i < s_end; i++) { #endif const auto j = std::find(i, s_end, ','); i = std::find_if(i, s_end, static_cast(std::isdigit)); if (j < i || constr) { constr = true; i = j; i = std::find_if(i + 1, s_end, static_cast(std::isalpha)); assert(i < s_end); const auto c1 = *i; i = std::find(i + 1, s_end, '='); assert(i < s_end); i = std::find_if(i + 1, s_end, static_cast(std::isalpha)); assert(i < s_end); const auto c2 = *i; assert(cs.count(c1) > 0 && cs.count(c2) > 0); const auto j = *n[c1].begin(); n[c2].insert(j); m[j].insert(c2); } else { assert(i < s_end); const Int j = *i - '0'; i = std::find_if(i + 1, s_end, static_cast(std::isalpha)); assert(i < s_end); const auto c1 = *i; i = std::find_if(i + 1, s_end, static_cast(std::isalpha)); assert(i < s_end); const auto c2 = *i; assert(j < As.size()); terms.emplace_back(j, c1, c2); m[{j, 0}].insert(c1); m[{j, 1}].insert(c2); cs.insert(c1); cs.insert(c2); n[c1].emplace(j, 0); n[c2].emplace(j, 1); } } for (const auto c: cs) { if (id.count(c)) continue; std::vector st; st.push_back(c); std::vector rid_N; while (!st.empty()) { auto c = st.back(); st.pop_back(); if (id.count(c)) continue; id[c] = N; if (std::find(rid_N.begin(), rid_N.end(), c) == rid_N.end()) rid_N.push_back(c); for (const auto j: n[c]) { rjd[N].insert(j); for (const auto tc: m[j]) st.push_back(tc); } } if (!rid_N.empty()) { rid.emplace_back(std::move(rid_N)); N++; } } assert(N == Ps.size()); } auto get_dim = [&] (auto j) { return j.second == 0 ? As[j.first].get().N() : As[j.first].get().M; }; std::vector sizes; for (Int i = 0; i < rid.size(); i++) { std::set szs; for (auto j: rjd[i]) szs.insert(get_dim(j)); assert(szs.size() == 1); sizes.push_back(*szs.begin()); } std::vector> pis; std::mt19937_64 gen(seed); for (Int i = 0; i < N; i++) { Value total = 0; for (auto j: rjd[i]) total += As[j.first].get().get_sps().total_load(); pis.emplace_back(random_init(Ps[i], total, gen)); } auto m_to_nnz = [&](const auto i, const auto m) { Value nnz = 0; for (auto j: rjd[i]) nnz += As[j.first].get().get_sps().query(j.second == 0 ? m : sizes[i], j.second == 0 ? sizes[i] : m); return nnz; }; auto pi_to_p = [&](const auto i, const double pi) { Int l = 0, r = sizes[i]; while (l < r) { const auto m = l + (r - l) / 2; if (pi <= m_to_nnz(i, m)) r = m; else l = m + 1; } return l; }; auto to_ps = [&](const auto pis) { assert(N == pis.size()); std::vector> ps; std::vector>> temp; for (Int i = 0; i < pis.size(); i++) { assert(Ps[i] == pis[i].size() + 1); std::vector p(pis[i].size() + 2); p.back() = sizes[i]; ps.push_back(p); for (Int j = 0; j < pis[i].size(); j++) temp.emplace_back(i, pis[i][j], std::ref(ps[i][j + 1])); } std::for_each( std::begin(temp), std::end(temp), [&](const auto item) { #if defined(ENABLE_CPP_PARALLEL) auto [i, pi, p] = item; #else auto i = std::get<0>(item); auto pi = std::get<1>(item); auto p = std::get<2>(item); #endif p.get() = pi_to_p(i, pi); }); return ps; }; std::vector> terms_converted; std::transform(terms.begin(), terms.end(), std::back_inserter(terms_converted), [&](auto term) { #if defined(ENABLE_CPP_PARALLEL) const auto [A_idx, c1, c2] = term; #else const auto A_idx = std::get<0>(term); const auto c1 = std::get<1>(term); const auto c2 = std::get<2>(term); #endif return std::make_tuple(A_idx, std::distance(cs.begin(), cs.find(c1)), std::distance(cs.begin(), cs.find(c2))); }); std::vector> rid_converted; std::transform(rid.begin(), rid.end(), std::back_inserter(rid_converted), [&](auto rid_i) { std::vector rid_i_converted; std::transform(rid_i.begin(), rid_i.end(), std::back_inserter(rid_i_converted), [&](auto c) { return std::distance(cs.begin(), cs.find(c)); }); return rid_i_converted; }); std::vector Ps_cs; std::transform(cs.begin(), cs.end(), std::back_inserter(Ps_cs), [&](auto c) { return Ps[id[c]]; }); auto to_rs = [&](const auto pis) { const auto ps = to_ps(pis); std::map, std::vector>> Qs; #if defined(ENABLE_CPP_PARALLEL) for (const auto [A_idx, c1, c2]: terms) { #else for (const auto term: terms) { const auto A_idx = std::get<0>(term); const auto c1 = std::get<1>(term); const auto c2 = std::get<2>(term); #endif if (Qs.count({A_idx, id[c1], id[c2]})) continue; Qs[{A_idx, id[c1], id[c2]}] = As[A_idx].get().get_sps().compute_loads(ps[id[c1]], ps[id[c2]]); } std::vector>>> Qv; std::transform(terms.begin(), terms.end(), std::back_inserter(Qv), [&](auto term) { #if defined(ENABLE_CPP_PARALLEL) const auto [A_idx, c1, c2] = term; #else const auto A_idx = std::get<0>(term); const auto c1 = std::get<1>(term); const auto c2 = std::get<2>(term); #endif return std::ref(Qs[{A_idx, id[c1], id[c2]}]); }); std::vector> rs; for (const auto p: ps) rs.emplace_back(p.size() - 1); std::vector v(cs.size()); for (Int i = 0; i < Ps_cs.size();) { for (i = 0; i < Ps_cs.size(); i++) { v[i]++; if (v[i] >= Ps_cs[i]) v[i] = 0; else break; } Int k = 0; Value sum = 0; #if defined(ENABLE_CPP_PARALLEL) for (const auto [A_idx, i1, i2]: terms_converted){ #else for (const auto term: terms_converted){ // const auto A_idx = std::get<0>(term); const auto i1 = std::get<1>(term); const auto i2 = std::get<2>(term); #endif sum += Qv[k++].get()[v[i1]][v[i2]]; } for (Int i = 0; i < rs.size(); i++) for (auto j: rid_converted[i]) rs[i][v[j]] = std::max(rs[i][v[j]], sum); } return rs; }; return to_ps(partition(pis, to_rs)); } template auto partition_spmv(const Matrix &A, const Int P, const double alpha, const double beta, const int seed = 1) { std::vector> pis; std::mt19937_64 gen(seed); const auto total = A.get_sps().total_load() + alpha * A.N() + beta * A.M; pis.emplace_back(random_init(P, total, gen)); auto m_to_nnz = [&](const auto m) { auto nnz = A.get_sps().query(m, A.M) + alpha * m; nnz += A.get_sps().query(A.N(), m) + beta * m; return nnz; }; auto pi_to_p = [&](const double pi) { Int l = 0, r = A.N(); while (l < r) { const auto m = l + (r - l) / 2; if (pi <= m_to_nnz(m)) r = m; else l = m + 1; } return l; }; auto to_ps = [&](const auto pis) { std::vector> ps; std::vector>> temp; for (Int i = 0; i < pis.size(); i++) { std::vector p(pis[i].size() + 2); p.back() = A.N(); ps.push_back(p); for (Int j = 0; j < pis[i].size(); j++) temp.emplace_back(i, pis[i][j], std::ref(ps[i][j + 1])); } #ifdef ENABLE_CPP_PARALLEL std::for_each(exec_policy, std::begin(temp), std::end(temp), [&](const auto item) { #else std::for_each(std::begin(temp), std::end(temp), [&](const auto item) { #endif #ifdef ENABLE_CPP_PARALLEL auto [i, pi, p] = item; #else auto pi = std::get<1>(item); auto p = std::get<2>(item); #endif p.get() = pi_to_p(pi); }); return ps; }; auto to_rs = [&](const auto pis) { const auto ps = to_ps(pis); auto loads = A.get_sps().compute_loads(ps[0], ps[0]); for (Int i = 0; i < P; i++) for (Int j = 0; j < P; j++) loads[i][j] += alpha * (ps[0][i + 1] - ps[0][i]) + beta * (ps[0][j + 1] - ps[0][j]); std::vector> rs; for (const auto p: ps) rs.emplace_back(p.size() - 1); for (Int i = 0; i < P; i++) for (Int j = 0; j < P; j++) { rs[0][i] = std::max(rs[0][i], loads[i][j]); rs[0][j] = std::max(rs[0][j], loads[i][j]); } return rs; }; return to_ps(partition(pis, to_rs))[0]; } /** * @brief Implements the SubGradient Optimization algorithm, * where each task is made of 3 tiles and tries to minimize task size. * This algorithm initializes the cut vectors randomly and * tries to refine them at each iteration by moving all the * cuts in the negative direction of the gradient to minimize * the maximum load. * * @param A Matrix * @param P number of parts * @param seed * @return a cut vector */ template auto partition_tri(const Matrix &A, const Int P, const int seed = 1) { return partition("0ij+0jk+0ik", std::vector>>{A}, std::vector{P}, seed)[0]; } /** * @brief Implements the SubGradient Optimization algorithm, * where each task is made up of 2 tiles from each matrix * in SpGEMM matrix multiplication and tries to minimize task size. * This algorithm initializes the cut vectors randomly and * tries to refine them at each iteration by moving all the * cuts in the negative direction of the gradient to minimize * the maximum load. * * @param A Matrix * @param B Matrix * @param P number of parts in 1st dimension * @param Q number of parts in 2nd dimension * @param R number of parts in 3rd dimension * @param seed * @return a cut vector */ template auto partition(const Matrix &A, const Matrix &B, const Int P, const Int Q, const Int R, int seed = 1) { const auto ps = partition("0ij+1jk", std::vector>>{A, B}, std::vector{P, Q, R}, seed); return std::make_tuple(ps[0], ps[1], ps[2]); } /** * @brief Implements the SubGradient Optimization algorithm. * This algorithm initializes the cut vectors randomly and * tries to refine them at each iteration by moving all the * cuts in the negative direction of the gradient to minimize * the maximum load. * * @param A Matrix * @param P number of parts * @param seed * @return a cut vector */ template auto partition(const Matrix &A, const Int P, const int seed = 1) { return partition("0ij,i=j", std::vector>>{A}, std::vector{P}, seed)[0]; } /** * @brief Implements the SubGradient Optimization algorithm. * This algorithm initializes the cut vectors randomly and * tries to refine them at each iteration by moving all the * cuts in the negative direction of the gradient to minimize * the maximum load. * * @param A Matrix * @param P number of parts in row dimension * @param Q number of parts in column dimension * @param seed * @return a cut vector */ template auto partition(const Matrix &A, const Int P, const Int Q, const int seed = 1) { const auto ps = partition("0ij", std::vector>>{A}, std::vector{P, Q}, seed); return std::make_pair(ps[0], ps[1]); } } #if !defined(ENABLE_CPP_PARALLEL) } // nested namespace #endif0 // Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using std::shared_ptr; using config::ConfigGetter; using document::DocumenttypesConfig; using config::FileSpec; using document::test::makeDocumentBucket; using document::BucketId; using namespace ::testing; namespace storage::distributor { struct GetOperationTest : Test, DistributorTestUtil { std::shared_ptr _repo; document::DocumentId docId; BucketId bucketId; std::unique_ptr op; GetOperationTest(); ~GetOperationTest() override; void SetUp() override { _repo.reset( new document::DocumentTypeRepo(*ConfigGetter:: getConfig("config-doctypes", FileSpec("../config-doctypes.cfg")))); createLinks(); docId = document::DocumentId("id:ns:text/html::uri"); bucketId = operation_context().make_split_bit_constrained_bucket_id(docId); }; void TearDown() override { close(); op.reset(); } void sendGet(api::InternalReadConsistency consistency = api::InternalReadConsistency::Strong) { auto msg = std::make_shared(makeDocumentBucket(BucketId(0)), docId, document::AllFields::NAME); op = std::make_unique( node_context(), getDistributorBucketSpace(), getDistributorBucketSpace().getBucketDatabase().acquire_read_guard(), msg, getDistributor().getMetrics().gets, consistency); op->start(_sender, framework::MilliSecTime(0)); } static constexpr uint32_t LastCommand = UINT32_MAX; void sendReply(uint32_t idx, api::ReturnCode::Result result, std::string authorVal, uint32_t timestamp, bool is_tombstone = false) { if (idx == LastCommand) { idx = _sender.commands().size() - 1; } std::shared_ptr msg2 = _sender.command(idx); ASSERT_EQ(api::MessageType::GET, msg2->getType()); auto* tmp = dynamic_cast(msg2.get()); assert(tmp != nullptr); document::Document::SP doc; if (!authorVal.empty()) { const document::DocumentType* type(_repo->getDocumentType("text/html")); doc = std::make_unique(*type, docId); doc->setValue(doc->getField("author"), document::StringFieldValue(authorVal)); } auto reply = std::make_shared(*tmp, doc, timestamp, false, is_tombstone); reply->setResult(result); op->receive(_sender, reply); } void reply_with_tombstone(uint32_t idx, uint32_t tombstone_ts) { sendReply(idx, api::ReturnCode::OK, "", tombstone_ts, true); } void replyWithFailure() { sendReply(LastCommand, api::ReturnCode::IO_FAILURE, "", 0); } void replyWithNotFound() { sendReply(LastCommand, api::ReturnCode::OK, "", 0); } void replyWithDocument() { sendReply(LastCommand, api::ReturnCode::OK, "foo", 100); } std::string getLastReplyAuthor() { api::StorageMessage& msg = *_sender.replies().back(); if (msg.getType() == api::MessageType::GET_REPLY) { document::Document::SP doc( dynamic_cast(msg).getDocument()); return doc->getValue(doc->getField("author"))->toString(); } else { std::ostringstream ost; ost << "Last reply was not a GET reply, but " << msg; return ost.str(); } } bool last_reply_had_consistent_replicas() { assert(!_sender.replies().empty()); auto& msg = *_sender.replies().back(); assert(msg.getType() == api::MessageType::GET_REPLY); return dynamic_cast(msg).had_consistent_replicas(); } bool last_reply_has_document() { assert(!_sender.replies().empty()); auto& msg = *_sender.replies().back(); assert(msg.getType() == api::MessageType::GET_REPLY); return (dynamic_cast(msg).getDocument().get() != nullptr); } void setClusterState(const std::string& clusterState) { enableDistributorClusterState(clusterState); } void do_test_read_consistency_is_propagated(api::InternalReadConsistency consistency); }; GetOperationTest::GetOperationTest() = default; GetOperationTest::~GetOperationTest() = default; namespace { NewestReplica replica_of(api::Timestamp ts, const document::BucketId& bucket_id, uint16_t node, bool is_tombstone) { return NewestReplica::of(ts, bucket_id, node, is_tombstone); } } TEST_F(GetOperationTest, simple) { setClusterState("distributor:1 storage:2"); addNodesToBucketDB(bucketId, "0=4,1=4"); sendGet(); ASSERT_EQ("Get => 0", _sender.getCommands(true)); ASSERT_NO_FATAL_FAILURE(replyWithDocument()); EXPECT_EQ("GetReply(BucketId(0x0000000000000000), id:ns:text/html::uri, " "timestamp 100) ReturnCode(NONE)", _sender.getLastReply()); EXPECT_FALSE(op->any_replicas_failed()); EXPECT_TRUE(last_reply_had_consistent_replicas()); ASSERT_TRUE(op->newest_replica().has_value()); EXPECT_EQ(replica_of(api::Timestamp(100), bucketId, 0, false), *op->newest_replica()); } TEST_F(GetOperationTest, ask_all_checksum_groups_if_inconsistent_even_if_trusted_replica_available) { setClusterState("distributor:1 storage:4"); addNodesToBucketDB(bucketId, "0=100/3/10,1=200/4/12/t"); sendGet(); ASSERT_EQ("Get => 0,Get => 1", _sender.getCommands(true)); ASSERT_NO_FATAL_FAILURE(sendReply(0, api::ReturnCode::OK, "newauthor", 2)); ASSERT_NO_FATAL_FAILURE(sendReply(1, api::ReturnCode::OK, "oldauthor", 1)); EXPECT_EQ("GetReply(BucketId(0x0000000000000000), id:ns:text/html::uri, " "timestamp 2) ReturnCode(NONE)", _sender.getLastReply()); EXPECT_FALSE(op->any_replicas_failed()); EXPECT_FALSE(last_reply_had_consistent_replicas()); ASSERT_TRUE(op->newest_replica().has_value()); EXPECT_EQ(replica_of(api::Timestamp(2), bucketId, 0, false), *op->newest_replica()); } TEST_F(GetOperationTest, ask_all_nodes_if_bucket_is_inconsistent) { setClusterState("distributor:1 storage:4"); addNodesToBucketDB(bucketId, "0=100/3/10,1=200/4/12"); sendGet(); ASSERT_EQ("Get => 0,Get => 1", _sender.getCommands(true)); ASSERT_NO_FATAL_FAILURE(sendReply(1, api::ReturnCode::OK, "newauthor", 2)); ASSERT_NO_FATAL_FAILURE(sendReply(0, api::ReturnCode::OK, "oldauthor", 1)); ASSERT_EQ("GetReply(BucketId(0x0000000000000000), id:ns:text/html::uri, " "timestamp 2) ReturnCode(NONE)", _sender.getLastReply()); EXPECT_EQ("newauthor", getLastReplyAuthor()); EXPECT_FALSE(op->any_replicas_failed()); EXPECT_FALSE(last_reply_had_consistent_replicas()); ASSERT_TRUE(op->newest_replica().has_value()); EXPECT_EQ(replica_of(api::Timestamp(2), bucketId, 1, false), *op->newest_replica()); } TEST_F(GetOperationTest, send_to_all_invalid_copies) { setClusterState("distributor:1 storage:4"); addNodesToBucketDB(bucketId, "2=0/0/1,3=0/0/1"); sendGet(); ASSERT_EQ("Get => 2,Get => 3", _sender.getCommands(true)); ASSERT_NO_FATAL_FAILURE(sendReply(0, api::ReturnCode::OK, "newauthor", 2)); ASSERT_NO_FATAL_FAILURE(sendReply(1, api::ReturnCode::OK, "oldauthor", 1)); ASSERT_EQ("GetReply(BucketId(0x0000000000000000), id:ns:text/html::uri, " "timestamp 2) ReturnCode(NONE)", _sender.getLastReply()); EXPECT_EQ("newauthor", getLastReplyAuthor()); EXPECT_FALSE(op->any_replicas_failed()); EXPECT_FALSE(last_reply_had_consistent_replicas()); } TEST_F(GetOperationTest, send_to_all_invalid_nodes_when_inconsistent) { setClusterState("distributor:1 storage:4"); addNodesToBucketDB(bucketId, "0=100,1=200,2=0/0/1,3=0/0/1"); sendGet(); ASSERT_EQ("Get => 2,Get => 3,Get => 0,Get => 1", _sender.getCommands(true)); ASSERT_NO_FATAL_FAILURE(sendReply(0, api::ReturnCode::OK, "newauthor", 2)); ASSERT_NO_FATAL_FAILURE(sendReply(1, api::ReturnCode::OK, "oldauthor", 1)); ASSERT_NO_FATAL_FAILURE(sendReply(2, api::ReturnCode::OK, "oldauthor", 1)); ASSERT_NO_FATAL_FAILURE(sendReply(3, api::ReturnCode::OK, "oldauthor", 1)); ASSERT_EQ("GetReply(BucketId(0x0000000000000000), id:ns:text/html::uri, " "timestamp 2) ReturnCode(NONE)", _sender.getLastReply()); EXPECT_EQ("newauthor", getLastReplyAuthor()); } TEST_F(GetOperationTest, inconsistent_split) { setClusterState("distributor:1 storage:4"); addNodesToBucketDB(BucketId(16, 0x0593), "0=100"); addNodesToBucketDB(BucketId(17, 0x10593), "1=200"); sendGet(); ASSERT_EQ("Get => 0,Get => 1", _sender.getCommands(true)); ASSERT_NO_FATAL_FAILURE(sendReply(0, api::ReturnCode::OK, "newauthor", 2)); ASSERT_NO_FATAL_FAILURE(sendReply(1, api::ReturnCode::OK, "oldauthor", 1)); ASSERT_EQ("GetReply(BucketId(0x0000000000000000), id:ns:text/html::uri, " "timestamp 2) ReturnCode(NONE)", _sender.getLastReply()); EXPECT_EQ("newauthor", getLastReplyAuthor()); EXPECT_FALSE(op->any_replicas_failed()); EXPECT_FALSE(last_reply_had_consistent_replicas()); // Bucket with highest timestamp should be returned. In this case it's the one on node 0. ASSERT_TRUE(op->newest_replica().has_value()); EXPECT_EQ(replica_of(api::Timestamp(2), BucketId(16, 0x0593), 0, false), *op->newest_replica()); } TEST_F(GetOperationTest, multi_inconsistent_bucket_not_found) { setClusterState("distributor:1 storage:4"); addNodesToBucketDB(bucketId, "0=100,2=100,1=200,3=200"); sendGet(); ASSERT_EQ("Get => 0,Get => 1", _sender.getCommands(true)); ASSERT_NO_FATAL_FAILURE(sendReply(0, api::ReturnCode::OK, "newauthor", 2)); ASSERT_NO_FATAL_FAILURE(sendReply(1, api::ReturnCode::OK, "", 0)); ASSERT_EQ("GetReply(BucketId(0x0000000000000000), id:ns:text/html::uri, " "timestamp 2) ReturnCode(NONE)", _sender.getLastReply()); EXPECT_FALSE(op->any_replicas_failed()); EXPECT_FALSE(last_reply_had_consistent_replicas()); } TEST_F(GetOperationTest, multi_inconsistent_bucket_not_found_deleted) { setClusterState("distributor:1 storage:4"); addNodesToBucketDB(bucketId, "0=100,2=100,1=200,3=200"); sendGet(); ASSERT_EQ("Get => 0,Get => 1", _sender.getCommands(true)); ASSERT_NO_FATAL_FAILURE(sendReply(0, api::ReturnCode::OK, "newauthor", 2)); // This signifies that the latest change was that the document was deleted // at timestamp 3. ASSERT_NO_FATAL_FAILURE(sendReply(1, api::ReturnCode::OK, "", 3)); ASSERT_EQ("GetReply(BucketId(0x0000000000000000), id:ns:text/html::uri, " "timestamp 3) ReturnCode(NONE)", _sender.getLastReply()); EXPECT_FALSE(op->any_replicas_failed()); EXPECT_FALSE(last_reply_had_consistent_replicas()); ASSERT_TRUE(op->newest_replica().has_value()); EXPECT_EQ(replica_of(api::Timestamp(3), bucketId, 1, false), *op->newest_replica()); } TEST_F(GetOperationTest, multi_inconsistent_bucket) { setClusterState("distributor:1 storage:4"); addNodesToBucketDB(bucketId, "0=100,2=100,1=200,3=200"); sendGet(); ASSERT_EQ("Get => 0,Get => 1", _sender.getCommands(true)); ASSERT_NO_FATAL_FAILURE(sendReply(0, api::ReturnCode::OK, "newauthor", 2)); ASSERT_NO_FATAL_FAILURE(sendReply(1, api::ReturnCode::OK, "oldauthor", 1)); ASSERT_EQ("GetReply(BucketId(0x0000000000000000), id:ns:text/html::uri, " "timestamp 2) ReturnCode(NONE)", _sender.getLastReply()); EXPECT_EQ("newauthor", getLastReplyAuthor()); EXPECT_FALSE(op->any_replicas_failed()); EXPECT_FALSE(last_reply_had_consistent_replicas()); } TEST_F(GetOperationTest, multi_inconsistent_bucket_fail) { setClusterState("distributor:1 storage:4"); addNodesToBucketDB(bucketId, "0=100,2=100,1=200,3=200"); sendGet(); ASSERT_EQ("Get => 0,Get => 1", _sender.getCommands(true)); ASSERT_NO_FATAL_FAILURE(sendReply(0, api::ReturnCode::OK, "newauthor", 1)); ASSERT_NO_FATAL_FAILURE(sendReply(1, api::ReturnCode::DISK_FAILURE, "", 0)); ASSERT_EQ("Get(BucketId(0x4000000000000593), id:ns:text/html::uri) => 3", _sender.getLastCommand()); ASSERT_NO_FATAL_FAILURE(replyWithDocument()); ASSERT_EQ("GetReply(BucketId(0x0000000000000000), id:ns:text/html::uri, " "timestamp 100) ReturnCode(NONE)", _sender.getLastReply()); EXPECT_TRUE(op->any_replicas_failed()); EXPECT_FALSE(last_reply_had_consistent_replicas()); ASSERT_TRUE(op->newest_replica().has_value()); // First send to node 2 fails, second is to node 3 which returned the highest timestamp EXPECT_EQ(replica_of(api::Timestamp(100), bucketId, 3, false), *op->newest_replica()); } TEST_F(GetOperationTest, return_not_found_when_bucket_not_in_db) { setClusterState("distributor:1 storage:1"); sendGet(); ASSERT_EQ("GetReply(BucketId(0x0000000000000000), id:ns:text/html::uri, " "timestamp 0) ReturnCode(NONE)", _sender.getLastReply()); EXPECT_FALSE(op->any_replicas_failed()); EXPECT_TRUE(last_reply_had_consistent_replicas()); // Nothing in the bucket, so nothing to be inconsistent with. } TEST_F(GetOperationTest, not_found) { setClusterState("distributor:1 storage:1"); addNodesToBucketDB(bucketId, "0=100"); sendGet(); ASSERT_EQ("Get(BucketId(0x4000000000000593), id:ns:text/html::uri) => 0", _sender.getLastCommand()); ASSERT_NO_FATAL_FAILURE(replyWithNotFound()); ASSERT_EQ("GetReply(BucketId(0x0000000000000000), id:ns:text/html::uri, " "timestamp 0) ReturnCode(NONE)", _sender.getLastReply()); EXPECT_EQ(1, getDistributor().getMetrics().gets.failures.notfound.getValue()); EXPECT_FALSE(op->any_replicas_failed()); // "Not found" is not a failure. EXPECT_TRUE(last_reply_had_consistent_replicas()); EXPECT_TRUE(op->newest_replica().has_value()); // "Not found" is still a success with a timestamp of 0. This is because // the caller may want to perform special logic if all replicas are in sync // but are missing the document. // FIXME make sure all callers are aware of this! EXPECT_EQ(replica_of(api::Timestamp(0), bucketId, 0, false), *op->newest_replica()); } TEST_F(GetOperationTest, not_found_on_subset_of_replicas_marks_get_as_inconsistent) { setClusterState("distributor:1 storage:2"); addNodesToBucketDB(bucketId, "0=100,1=200"); sendGet(); ASSERT_EQ("Get => 0,Get => 1", _sender.getCommands(true)); ASSERT_NO_FATAL_FAILURE(sendReply(0, api::ReturnCode::OK, "newauthor", 101)); ASSERT_NO_FATAL_FAILURE(sendReply(1, api::ReturnCode::OK, "", 0)); // Not found. ASSERT_EQ("GetReply(BucketId(0x0000000000000000), id:ns:text/html::uri, " "timestamp 101) ReturnCode(NONE)", _sender.getLastReply()); EXPECT_FALSE(last_reply_had_consistent_replicas()); } TEST_F(GetOperationTest, resend_on_storage_failure) { setClusterState("distributor:1 storage:3"); // Add two nodes that are not trusted. GET should retry each one of them // if one fails. addNodesToBucketDB(bucketId, "1=100,2=100"); sendGet(); ASSERT_EQ("Get(BucketId(0x4000000000000593), id:ns:text/html::uri) => 1", _sender.getLastCommand()); ASSERT_NO_FATAL_FAILURE(replyWithFailure()); ASSERT_EQ("Get(BucketId(0x4000000000000593), id:ns:text/html::uri) => 2", _sender.getLastCommand()); ASSERT_NO_FATAL_FAILURE(replyWithDocument()); ASSERT_EQ("GetReply(BucketId(0x0000000000000000), id:ns:text/html::uri, " "timestamp 100) ReturnCode(NONE)", _sender.getLastReply()); EXPECT_TRUE(op->any_replicas_failed()); // Replica had read failure, but they're still in sync. An immutable Get won't change that fact. EXPECT_TRUE(last_reply_had_consistent_replicas()); ASSERT_TRUE(op->newest_replica().has_value()); EXPECT_EQ(replica_of(api::Timestamp(100), bucketId, 2, false), *op->newest_replica()); } TEST_F(GetOperationTest, storage_failure_of_out_of_sync_replica_is_tracked_as_inconsistent) { setClusterState("distributor:1 storage:3"); addNodesToBucketDB(bucketId, "1=100,2=200"); sendGet(); ASSERT_EQ("Get => 1,Get => 2", _sender.getCommands(true)); ASSERT_NO_FATAL_FAILURE(sendReply(0, api::ReturnCode::TIMEOUT, "", 0)); ASSERT_NO_FATAL_FAILURE(sendReply(1, api::ReturnCode::OK, "newestauthor", 3)); ASSERT_EQ("GetReply(BucketId(0x0000000000000000), id:ns:text/html::uri, " "timestamp 3) ReturnCode(NONE)", _sender.getLastReply()); EXPECT_TRUE(op->any_replicas_failed()); EXPECT_FALSE(last_reply_had_consistent_replicas()); ASSERT_TRUE(op->newest_replica().has_value()); EXPECT_EQ(replica_of(api::Timestamp(3), bucketId, 2, false), *op->newest_replica()); } TEST_F(GetOperationTest, resend_on_storage_failure_all_fail) { setClusterState("distributor:1 storage:3"); // Add two nodes that are not trusted. GET should retry each one of them // if one fails. addNodesToBucketDB(bucketId, "1=100,2=100"); sendGet(); ASSERT_EQ("Get(BucketId(0x4000000000000593), id:ns:text/html::uri) => 1", _sender.getLastCommand()); ASSERT_NO_FATAL_FAILURE(replyWithFailure()); ASSERT_EQ("Get(BucketId(0x4000000000000593), id:ns:text/html::uri) => 2", _sender.getLastCommand()); ASSERT_NO_FATAL_FAILURE(replyWithFailure()); ASSERT_EQ("GetReply(BucketId(0x0000000000000000), id:ns:text/html::uri, " "timestamp 0) ReturnCode(IO_FAILURE)", _sender.getLastReply()); EXPECT_TRUE(op->any_replicas_failed()); EXPECT_TRUE(last_reply_had_consistent_replicas()); // Doesn't really matter since operation itself failed EXPECT_FALSE(op->newest_replica().has_value()); } TEST_F(GetOperationTest, send_to_ideal_copy_if_bucket_in_sync) { setClusterState("distributor:1 storage:4"); addNodesToBucketDB(bucketId, "1=100,2=100,3=100"); sendGet(); // Should always send to node 1 (follow bucket db order) ASSERT_EQ("Get(BucketId(0x4000000000000593), id:ns:text/html::uri) => 1", _sender.getLastCommand()); ASSERT_NO_FATAL_FAILURE(replyWithDocument()); ASSERT_EQ("GetReply(BucketId(0x0000000000000000), id:ns:text/html::uri, " "timestamp 100) ReturnCode(NONE)", _sender.getLastReply()); EXPECT_TRUE(last_reply_had_consistent_replicas()); ASSERT_TRUE(op->newest_replica().has_value()); EXPECT_EQ(replica_of(api::Timestamp(100), bucketId, 1, false), *op->newest_replica()); } TEST_F(GetOperationTest, multiple_copies_with_failure_on_local_node) { setClusterState("distributor:1 storage:4"); // Node 0 is local copy to distributor 0 and will be preferred when // sending initially. addNodesToBucketDB(BucketId(16, 0x0593), "2=100,0=100"); sendGet(); ASSERT_EQ("Get => 0", _sender.getCommands(true)); // Fail local node; no reply must be sent yet since we've got more nodes // to try. ASSERT_NO_FATAL_FAILURE(sendReply(0, api::ReturnCode::TIMEOUT, "", 0)); // Retry with remaining copy on node 2. ASSERT_EQ("Get => 0,Get => 2", _sender.getCommands(true)); ASSERT_NO_FATAL_FAILURE(sendReply(1, api::ReturnCode::OK, "newestauthor", 3)); ASSERT_EQ("GetReply(BucketId(0x0000000000000000), id:ns:text/html::uri, " "timestamp 3) ReturnCode(NONE)", _sender.getLastReply()); EXPECT_EQ("newestauthor", getLastReplyAuthor()); EXPECT_TRUE(op->any_replicas_failed()); EXPECT_TRUE(last_reply_had_consistent_replicas()); ASSERT_TRUE(op->newest_replica().has_value()); EXPECT_EQ(replica_of(api::Timestamp(3), BucketId(16, 0x0593), 2, false), *op->newest_replica()); } TEST_F(GetOperationTest, can_get_documents_when_all_replica_nodes_retired) { setClusterState("distributor:1 storage:2 .0.s:r .1.s:r"); addNodesToBucketDB(bucketId, "0=4,1=4"); sendGet(); EXPECT_EQ("Get => 0", _sender.getCommands(true)); } void GetOperationTest::do_test_read_consistency_is_propagated(api::InternalReadConsistency consistency) { setClusterState("distributor:1 storage:1"); addNodesToBucketDB(bucketId, "0=4"); sendGet(consistency); ASSERT_TRUE(op); EXPECT_EQ(dynamic_cast(*op).desired_read_consistency(), consistency); ASSERT_EQ("Get => 0", _sender.getCommands(true)); auto& cmd = dynamic_cast(*_sender.command(0)); EXPECT_EQ(cmd.internal_read_consistency(), consistency); } TEST_F(GetOperationTest, can_send_gets_with_strong_internal_read_consistency) { do_test_read_consistency_is_propagated(api::InternalReadConsistency::Strong); } TEST_F(GetOperationTest, can_send_gets_with_weak_internal_read_consistency) { do_test_read_consistency_is_propagated(api::InternalReadConsistency::Weak); } TEST_F(GetOperationTest, replicas_considered_consistent_if_all_equal_tombstone_timestamps) { setClusterState("distributor:1 storage:4"); addNodesToBucketDB(bucketId, "0=100,2=100,1=200,3=200"); sendGet(); ASSERT_EQ("Get => 0,Get => 1", _sender.getCommands(true)); ASSERT_NO_FATAL_FAILURE(reply_with_tombstone(0, 100)); ASSERT_NO_FATAL_FAILURE(reply_with_tombstone(1, 100)); ASSERT_EQ("GetReply(BucketId(0x0000000000000000), id:ns:text/html::uri, timestamp 0) ReturnCode(NONE)", _sender.getLastReply()); EXPECT_FALSE(op->any_replicas_failed()); EXPECT_TRUE(last_reply_had_consistent_replicas()); EXPECT_FALSE(last_reply_has_document()); EXPECT_EQ(replica_of(api::Timestamp(100), bucketId, 0, true), *op->newest_replica()); } TEST_F(GetOperationTest, newer_tombstone_hides_older_document) { setClusterState("distributor:1 storage:4"); addNodesToBucketDB(bucketId, "0=100,2=100,1=200,3=200"); sendGet(); ASSERT_EQ("Get => 0,Get => 1", _sender.getCommands(true)); ASSERT_NO_FATAL_FAILURE(reply_with_tombstone(1, 200)); ASSERT_NO_FATAL_FAILURE(sendReply(0, api::ReturnCode::OK, "newauthor", 100)); ASSERT_EQ("GetReply(BucketId(0x0000000000000000), id:ns:text/html::uri, timestamp 0) ReturnCode(NONE)", _sender.getLastReply()); EXPECT_FALSE(op->any_replicas_failed()); EXPECT_FALSE(last_reply_had_consistent_replicas()); EXPECT_FALSE(last_reply_has_document()); EXPECT_EQ(replica_of(api::Timestamp(200), bucketId, 1, true), *op->newest_replica()); } TEST_F(GetOperationTest, older_tombstone_does_not_hide_newer_document) { setClusterState("distributor:1 storage:4"); addNodesToBucketDB(bucketId, "0=100,2=100,1=200,3=200"); sendGet(); ASSERT_EQ("Get => 0,Get => 1", _sender.getCommands(true)); ASSERT_NO_FATAL_FAILURE(reply_with_tombstone(1, 100)); ASSERT_NO_FATAL_FAILURE(sendReply(0, api::ReturnCode::OK, "newauthor", 200)); ASSERT_EQ("GetReply(BucketId(0x0000000000000000), id:ns:text/html::uri, timestamp 200) ReturnCode(NONE)", _sender.getLastReply()); EXPECT_FALSE(op->any_replicas_failed()); EXPECT_FALSE(last_reply_had_consistent_replicas()); EXPECT_TRUE(last_reply_has_document()); EXPECT_EQ(replica_of(api::Timestamp(200), bucketId, 0, false), *op->newest_replica()); } } TITLE("NTL algorithms") REF("::Swap(T&,T&)") REF("template void IterSwap(I a, I b)") REF("template int sgn(T a)") REF("template int FindLowerBound(const C& v, const T& val, const L& less)") REF("template int FindLowerBound(const C& v, const T& val)") REF("template int FindUpperBound(const C& v, int l, int h, const T& val, const L& less)") REF("template int FindUpperBound(const C& v, const T& val, const L& less)") REF("template int FindUpperBound(const C& v, const T& val)") REF("template int FindBinary(const C& v, const T& val, int l, int h, const L& less)") REF("template int FindBinary(const C& v, const T& val, const L& less)") REF("template int FindBinary(const C& v, const T& val)") REF("template C& AppendSorted(C& dest, const C& src)") REF("template C& UnionSorted(C& dest, const C& src)") REF("template C& RemoveSorted(C& from, const C& what)") REF("template D& IntersectSorted(D& dest, const S& src, const L& less)") REF("template D& IntersectSorted(D& dest, const S& src)") REF("template void StreamContainer(Stream& s, T& cont)") REF("template void Sort(T& c)") REF("template void __IndexSort(II begin, II end, VI pair, const Less& less, const K *)") REF("template void IndexSort(KC& keys, VC& values)") REF("template void __SortOrder(int *begin, int *end, I data, const Less& less, const V *)") REF("template Vector GetSortOrder(const C& container)") REF("template void GetFieldContainer(DC& dest, I begin, I end, F field)") REF("template MethodRelationCls MethodRelation(O (T::*method)(), const R& relation)") REF("template MethodRelationCls MethodRelation(O (T::*method)() const, const R& relation)") TOPIC_TEXT( "[2 $$0,0#00000000000000000000000000000000:Default][l288;i704;a17;O9;~~~.992;2 $$" "1,0#10431211400427159095818037425705:param][a83;*R6 $$2,5#31310162474203024125188" "417583966:caption][b83;* $$3,5#07864147445237544204411237157677:title][b167;a42;C" "2 $$4,6#40027414424643823182269349404212:item][b42;a42; $$5,5#4541300047534217475" "4091244180557:text][l288;a17;2 $$6,6#27521748481378242620020725143825:desc][l321;" "t246;C@5;1 $$7,7#20902679421464641399138805415013:code][b2503; $$8,0#651423754561" "00023862071332075487:separator][*@(0.0.255) $$9,0#8343346941035416104274160818152" "8:base][t4167;C $$10,0#37138531426314131251341829483380:class][l288;a17;*1 $$11,1" "1#70004532496200323422659154056402:requirement][i416;b42;a42;O9;~~~.416; $$12,12#" "10566046415157235020018451313112:tparam][b167;C2 $$13,13#924304594434604619111080" "80531343:item1][i288;a42;O9;C2 $$14,14#77422149456609303542238260500223:item2][*@" "2$(0.128.128) $$15,15#34511555403152284025741354420178:NewsDate][l321;*C$7;2 $$16" ",16#03451589433145915344929335295360:result][l321;b83;a83;*C$7;2 $$17,17#07531550" "463529505371228428965313:result`-line][l160;t4167;*C+117 $$18,5#88603949442205825" "958800053222425:package`-title][{_}%EN-US [s13;%00-00 [%00-00 template]&][s14;:`:`:Swap`(T`&`,T`&`):%00-00 [%00-00 void ][%00-00* Sw" "ap][%00-00 (][%00-00*@4 T][%00-00 `& ][%00-00*@3 a][%00-00 , ][%00-00*@4 T][%00-0" "0 `& ][%00-00*@3 b][%00-00 )]&][s6;%00-00 [%00-00 Swaps values. Specific types mi" "ght specialize ][%00-00* Swap][%00-00 with more effective variants.]&][s11; T mu" "st have either deep copy operator or pick operator.&][s1;%00-00 [%00-00*C@4 T][%0" "0-00 -|Type of values.]&][s1;%00-00 [%00-00*C@3 a][%00-00 -|First value to swap.]" "&][s1;%00-00 [%00-00*C@3 b][%00-00 -|Second value to swap.]&][s13;:template` void IterSwap`(I a`, I b`):%00-00 [%00-00 template]&][s14;:template` void IterSwap`(I a`, I b`):%00-00 [%00-00 void " "][%00-00* IterSwap][%00-00 (][%00-00*@4 I][%00-00* ][%00") TOPIC_TEXT( "-00*@3 a][%00-00 , ][%00-00*@4 I][%00-00* ][%00-00*@3 b][%00-00 )]&][s6;%00-00 " "[%00-00 Swaps values pointed to by iterators. Specific types might specialize ][%" "00-00* IterSwap][%00-00 with more effective variants.]&][s11; Swap must be defin" "ed for type pointed to by I.&][s1;%00-00 [%00-00*C@4 I][%00-00 -|Iterator type.]&" "][s1;%00-00 [%00-00*C@3 a][%00-00 -|Iterator pointing to first value.]&][s1;%00-0" "0 [%00-00*C@3 b][%00-00 -|Iterator pointing to second value.]&][s13;%00-00 [%00-0" "0 template]&][s14;:template` int sgn`(T a`):%00-00 [%00-00 int" " ][%00-00* FindLowerBound][%00-00 (const ][%00-00*@4 C][%00-00 `& ][%00-00*@3 v][" "%00-00 , int ][%00-00*@3 pos][%00-00 , int ][%00-00*@3 count][%00-00 , const ][%0" "0-00*@4 T][%00-00 `& ][%00-00*@3 val][%00-00 , const ][%00-00*@4 L][%00-00 `& ][%" "00-00*@3 less][%00-00 )]&][s6;%00-00 [%00-00 Finds first position in range of con" "tainer sorted by ][%00-00* less][%00-00 predicate where ][%00-00* val][%00-00 c" "an be inserted without breaking the ordering.]&][s1;%00-00 [%00-00*C@4 C][%00-00 " "-|Type of container.]&][s1;%00-00 [%00-00*C@4 T][%00-00 -|Type of value.]&][s1;%0" "0-00 [%00-00*C@3 v][%00-00 -|Container.]&][s1;%00-00 [%00-00*C@3 pos][%00-00 -|Be" "ginning of range.]&][s1;%00-00 [%00-00*C@3 count][%00-00 -|Number of elements in " "range.]&][s1;%00-00 [%00-00*C@3 val][%00-00 -|Value to find.]&][s1;%00-00 [%00-00" "*C@3 less][%00-00 -|Ordering predicate.]&][s1;%00-00 [%00-00*/ Return value][%00-" "00 -|Position in container.]&][s13;:template` int F" "indLowerBound`(const C`& v`, const T`& val`, const L`& less`):%00-00 [%00-00 temp" "late]&][s14;:template` int FindLowerBound`" "(const C`& v`, const T`& val`, const L`& less`):%00-00 [%00-00 int ][%00-00* Find" "LowerBound][%00-00 (const ][%00-00*@4 C][%00-00 `& ][%00-") TOPIC_TEXT( "00*@3 v][%00-00 , const ][%00-00*@4 T][%00-00 `& ][%00-00*@3 val][%00-00 , const" " ][%00-00*@4 L][%00-00 `& ][%00-00*@3 less][%00-00 )]&][s6;%00-00 [%00-00 Finds f" "irst position in sorted by ][%00-00* less][%00-00 predicate where ][%00-00* val]" "[%00-00 can be inserted without breaking the ordering.]&][s1;%00-00 [%00-00*C@4 " "C][%00-00 -|Type of container.]&][s1;%00-00 [%00-00*C@4 T][%00-00 -|Type of value" ".]&][s1;%00-00 [%00-00*C@3 v][%00-00 -|Container.]&][s1;%00-00 [%00-00*C@3 val][%" "00-00 -|Value to find.]&][s1;%00-00 [%00-00*C@3 less][%00-00 -|Ordering predicate" ".]&][s1;%00-00 [%00-00*/ Return value][%00-00 -|Position in container.]&][s13;:te" "mplate` int FindLowerBound`(const C`& v`, const T`& val`):%00" "-00 [%00-00 template]" "&][s14;:template` int FindLowerBound`(const C`& v`, const T`&" " val`):%00-00 [%00-00 int ][%00-00* FindLowerBound][%00-00 (const ][%00-00*@4 C][" "%00-00 `& ][%00-00*@3 v][%00-00 , const ][%00-00*@4 T][%00-00 `& ][%00-00*@3 val]" "[%00-00 )]&][s6;%00-00 [%00-00 Finds first position in sorted by ][%00-00*/ opera" "tor<][%00-00 predicate where ][%00-00* val][%00-00 can be inserted without brea" "king the ordering.]&][s1;%00-00 [%00-00*C@4 C][%00-00 -|Type of container.]&][s1;" "%00-00 [%00-00*C@4 T][%00-00 -|Type of value.]&][s1;%00-00 [%00-00*C@3 v][%00-00 " "-|Container.]&][s1;%00-00 [%00-00*C@3 val][%00-00 -|Value to find.]&][s1;%00-00 [" "%00-00*/ Return value][%00-00 -|Position in container.]&][s13;:template` int FindUpperBound`(const C`& v`, int l`, int h`, const T`&" " val`, const L`& less`):%00-00 [%00-00 template]&][s14;:template` int FindUpperBound`(const C`& v`, int l`, int h`, const T" "`& val`, const L`& less`):%00-00 [%00-00 int ][%00-00* FindUpperBound][%00-00 (co" "nst ][%00-00*@4 C][%00-00 `& ][%00-00*@3 v][%00-00 , int ") TOPIC_TEXT( "][%00-00*@3 pos][%00-00 , int ][%00-00*@3 count][%00-00 , const ][%00-00*@4 T][%" "00-00 `& ][%00-00*@3 val][%00-00 , const ][%00-00*@4 L][%00-00 `& ][%00-00*@3 les" "s][%00-00 )]&][s6;%00-00 [%00-00 Finds last position in range of container sorted" " by ][%00-00* less][%00-00 predicate where ][%00-00* val][%00-00 can be inserte" "d without breaking the ordering.]&][s1;%00-00 [%00-00*C@4 C][%00-00 -|Type of con" "tainer.]&][s1;%00-00 [%00-00*C@4 T][%00-00 -|Type of value.]&][s1;%00-00 [%00-00*" "C@3 v][%00-00 -|Container.]&][s1;%00-00 [%00-00*C@3 pos][%00-00 -|Beginning of ra" "nge.]&][s1;%00-00 [%00-00*C@3 count][%00-00 -|Number of elements in range.]&][s1;" "%00-00 [%00-00*C@3 val][%00-00 -|Value to find.]&][s1;%00-00 [%00-00*C@3 less][%0" "0-00 -|Ordering predicate.]&][s1;%00-00 [%00-00*/ Return value][%00-00 -|Position" " in container.]&][s13;:template` int FindUpperBound" "`(const C`& v`, const T`& val`, const L`& less`):%00-00 [%00-00 template" "]&][s14;:template` int FindUpperBound`(const C`& v`" ", const T`& val`, const L`& less`):%00-00 [%00-00 int ][%00-00* FindUpperBound][%" "00-00 (const ][%00-00*@4 C][%00-00 `& ][%00-00*@3 v][%00-00 , const ][%00-00*@4 T" "][%00-00 `& ][%00-00*@3 val][%00-00 , const ][%00-00*@4 L][%00-00 `& ][%00-00*@3 " "less][%00-00 )]&][s6;%00-00 [%00-00 Finds last position in sorted by ][%00-00* le" "ss][%00-00 predicate where ][%00-00* val][%00-00 can be inserted without breaki" "ng the ordering.]&][s1;%00-00 [%00-00*C@4 C][%00-00 -|Type of container.]&][s1;%0" "0-00 [%00-00*C@4 T][%00-00 -|Type of value.]&][s1;%00-00 [%00-00*C@3 v][%00-00 -|" "Container.]&][s1;%00-00 [%00-00*C@3 val][%00-00 -|Value to find.]&][s1;%00-00 [%0" "0-00*C@3 less][%00-00 -|Ordering predicate.]&][s1;%00-00 [%00-00*/ Return value][" "%00-00 -|Position in container.]&][s13;:template` int FindUpp" "erBound`(const C`& v`, const T`& val`):%00-00 [%00-00 tem") TOPIC_TEXT( "plate]&][s14;:templa" "te` int FindUpperBound`(const C`& v`, const T`& val`):%00-00 " "[%00-00 int ][%00-00* FindUpperBound][%00-00 (const ][%00-00*@4 C][%00-00 `& ][%0" "0-00*@3 v][%00-00 , const ][%00-00*@4 T][%00-00 `& ][%00-00*@3 val][%00-00 )]&][s" "6;%00-00 [%00-00 Finds last position in sorted by ][%00-00*/ operator<][%00-00 p" "redicate where ][%00-00* val][%00-00 can be inserted without breaking the orderi" "ng.]&][s1;%00-00 [%00-00*C@4 C][%00-00 -|Type of container.]&][s1;%00-00 [%00-00*" "C@4 T][%00-00 -|Type of value.]&][s1;%00-00 [%00-00*C@3 v][%00-00 -|Container.]&]" "[s1;%00-00 [%00-00*C@3 val][%00-00 -|Value to find.]&][s1;%00-00 [%00-00*/ Return" " value][%00-00 -|Position in container.]&][s13;:template` int FindBinary`(const C`& v`, const T`& val`, int l`, int h`, const L`& le" "ss`):%00-00 [%00-00 template]&][s14;:template` int FindBinary`(const C`& v`, const T`& val`, int l`, int h`, const L`& less" "`):%00-00 [%00-00 int ][%00-00* FindBinary][%00-00 (const ][%00-00*@4 C][%00-00 `" "& ][%00-00*@3 v][%00-00 , const ][%00-00*@4 T][%00-00 `& ][%00-00*@3 val][%00-00 " ", int ][%00-00*@3 pos][%00-00 , int ][%00-00*@3 count][%00-00 , const ][%00-00*@4" " L][%00-00 `& ][%00-00*@3 less][%00-00 )]&][s6;%00-00 [%00-00 Finds position of e" "lement with specified value in a range of container sorted by ][%00-00* less][%00" "-00 predicate. If no such element exists, negative value is returned.]&][s1;%00-" "00 [%00-00*C@4 C][%00-00 -|Type of container.]&][s1;%00-00 [%00-00*C@4 T][%00-00 " "-|Type of value.]&][s1;%00-00 [%00-00*C@3 v][%00-00 -|Container.]&][s1;%00-00 [%0" "0-00*C@3 pos][%00-00 -|Beginning of range.]&][s1;%00-00 [%00-00*C@3 count][%00-00" " -|Number of elements in range.]&][s1;%00-00 [%00-00*C@3 val][%00-00 -|Value to f" "ind.]&][s1;%00-00 [%00-00*C@3 less][%00-00 -|Ordering pre") TOPIC_TEXT( "dicate.]&][s1;%00-00 [%00-00*/ Return value][%00-00 -|Position in container.]&][" "s13;:template` int FindBinary`(const C`& v`, const " "T`& val`, const L`& less`):%00-00 [%00-00 template]&][s14;:template` int FindBinary`(const C`& v`, const T`& val`, const L`" "& less`):%00-00 [%00-00 int ][%00-00* FindBinary][%00-00 (const ][%00-00*@4 C][%0" "0-00 `& ][%00-00*@3 v][%00-00 , const ][%00-00*@4 T][%00-00 `& ][%00-00*@3 val][%" "00-00 , const ][%00-00*@4 L][%00-00 `& ][%00-00*@3 less][%00-00 )]&][s6;%00-00 [%" "00-00 Finds position of element with specified value in the container sorted by ]" "[%00-00* less][%00-00 predicate. If no such element exists, negative value is re" "turned.]&][s1;%00-00 [%00-00*C@4 C][%00-00 -|Type of container.]&][s1;%00-00 [%00" "-00*C@4 T][%00-00 -|Type of value.]&][s1;%00-00 [%00-00*C@3 v][%00-00 -|Container" ".]&][s1;%00-00 [%00-00*C@3 val][%00-00 -|Value to find.]&][s1;%00-00 [%00-00*C@3 " "less][%00-00 -|Ordering predicate.]&][s1;%00-00 [%00-00*/ Return value][%00-00 -|" "Position in container.]&][s13;:template` int FindBinary`(cons" "t C`& v`, const T`& val`):%00-00 [%00-00 template]&][s14;:template` int FindBinary" "`(const C`& v`, const T`& val`):%00-00 [%00-00 int ][%00-00* FindBinary][%00-00 (" "const ][%00-00*@4 C][%00-00 `& ][%00-00*@3 v][%00-00 , const ][%00-00*@4 T][%00-0" "0 `& ][%00-00*@3 val][%00-00 )]&][s6;%00-00 [%00-00 Finds position of element wit" "h specified value in the container sorted by ][%00-00*/ operator<][%00-00 predic" "ate. If no such element exists, negative value is returned.]&][s1;%00-00 [%00-00*" "C@4 C][%00-00 -|Type of container.]&][s1;%00-00 [%00-00*C@4 T][%00-00 -|Type of v" "alue.]&][s1;%00-00 [%00-00*C@3 v][%00-00 -|Container.]&][s1;%00-00 [%00-00*C@3 va" "l][%00-00 -|Value to find.]&][s1;%00-00 [%00-00*/ Return ") TOPIC_TEXT( "value][%00-00 -|Position in container.]&][s13;:template` C`& AppendSor" "ted`(C`& dest`, const C`& src`):~~~.992;%00-00 [%00-00 template]&][s14;:template` C`& AppendSorted`(C`& dest`, const C`& s" "rc`):~~~.992;%00-00 [%00-00*@4 C][%00-00 `& ][%00-00* AppendSorted][%00-00 (][%00" "-00*@4 C][%00-00 `& ][%00-00*@3 dest][%00-00 , const ][%00-00*@4 C][%00-00 `& ][%" "00-00*@3 src][%00-00 , const ][%00-00*@4 L][%00-00 `& ][%00-00*@3 less][%00-00 )]" "&][s6;%00-00 [%00-00 Adds source NTL container to destination NTL container. Both" " containers must be sorted in ascending order. After operation, destination conta" "iner is sorted in ascending order and contains values from both containers. Dupli" "cate values are preserved. Ordering predicate is determined by ][%00-00* less][%0" "0-00 .]&][s1;%00-00 [%00-00*C@4 C][%00-00 -|Type of container.]&][s1;%00-00 [%00-" "00*C@3 dest][%00-00 -|Destination container.]&][s1;%00-00 [%00-00*C@3 src][%00-00" " -|Source container.]&][s1;%00-00 [%00-00*C@3 less][%00-00 -|Ordering predicate.]" "&][s1;%00-00C [%00-00*/A Return value][%00-00A -|Destination container.][%00-00 t" "emplate]&][s13;:template` C`& AppendSorte" "d`(C`& dest`, const C`& src`):~~~.992;%00-00 [%00-00 template]&][s14;~~~.992;%00-00 [%00-00*@4 C][%00-00 `& ][%00-00* AppendSorted][" "%00-00 (][%00-00*@4 C][%00-00 `& ][%00-00*@3 dest][%00-00 , const ][%00-00*@4 C][" "%00-00 `& ][%00-00*@3 src][%00-00 )]&][s6;~~~.992;%00-00 [%00-00 Adds source NTL " "container to destination NTL container. Both containers must be sorted in ascendi" "ng order. After operation, destination container is sorted in ascending order and" " contains values from both containers. Duplicate values are preserved. Ordering i" "s determined by ][%00-00*/ operator<][%00-00 .]&][s1;%00-00 [%00-00*C@4 C][%00-00" " -|Type of container.]&][s1;%00-00 [%00-00*C@3 dest][%00-00 -|Destination contain" "er.]&][s1;%00-00 [%00-00*C@3 src][%00-00 -|Source contain") TOPIC_TEXT( "er.]&][s1;%00-00C [%00-00*/A Return value][%00-00A -|Destination container.][%00" "-00 template]&][s13;%00-00 [%00-00 template]&][s14;%00-00 [%00-00*@4 C][" "%00-00 `& ][%00-00* UnionSorted][%00-00 (][%00-00*@4 C][%00-00 `& ][%00-00*@3 des" "t][%00-00 , const ][%00-00*@4 C][%00-00 `& ][%00-00*@3 src][%00-00 , const ][%00-" "00*@4 L][%00-00 `& ][%00-00*@3 less][%00-00 )]&][s6;%00-00 [%00-00 Adds source NT" "L container to destination NTL container. Both containers must be sorted in ascen" "ding order and values must be unique. After operation, destination container is s" "orted in ascending order and contains unique values from both containers. Orderin" "g is determined by ][%00-00* less][%00-00 .]&][s1;%00-00 [%00-00*C@4 C][%00-00 -|" "Type of container.]&][s1;%00-00 [%00-00*C@3 dest][%00-00 -|Destination container." "]&][s1;%00-00 [%00-00*C@3 src][%00-00 -|Source container.]&][s1;%00-00 [%00-00*C@" "3 less][%00-00 -|Ordering predicate.]&][s1;%00-00 [%00-00*/ Return value][%00-00 " "-|Destination container.]&][s13;:template` C`& UnionSorted`(C`& dest`, " "const C`& src`):%00-00 [%00-00 template]&][s14;:tem" "plate` C`& UnionSorted`(C`& dest`, const C`& src`):~~~.992;%00-00 [%00-" "00*@4 C][%00-00 `& ][%00-00* UnionSorted][%00-00 (][%00-00*@4 C][%00-00 `& ][%00-" "00*@3 dest][%00-00 , const ][%00-00*@4 C][%00-00 `& ][%00-00*@3 src][%00-00 )]&][" "s6;%00-00 [%00-00 Adds source NTL container to destination NTL container. Both co" "ntainers must be sorted in ascending order and values must be unique. After opera" "tion, destination container is sorted in ascending order and contains unique valu" "es from both containers. Ordering is determined by ][%00-00*/ operator<][%00-00 ." "]&][s1;%00-00 [%00-00*C@4 C][%00-00 -|Type of container.]&][s1;%00-00 [%00-00*C@3" " dest][%00-00 -|Destination container.]&][s1;%00-00 [%00-00*C@3 src][%00-00 -|Sou" "rce container.]&][s1;%00-00 [%00-00*/ Return value][%00-0") TOPIC_TEXT( "0 -|Destination container.]&][s13;%00-00 [%00-00 template]&][s14;%00-00 [%00-00*@4 C][%00-00 `& ][%00" "-00* RemoveSorted][%00-00 (][%00-00*@4 C][%00-00 `& ][%00-00*@3 from][%00-00 , co" "nst ][%00-00*@4 C][%00-00 `& ][%00-00*@3 what][%00-00 , const ][%00-00*@4 L][%00-" "00 `& ][%00-00*@3 less][%00-00 )]&][s6;%00-00 [%00-00 Removes elements of source " "container from destination container. Both containers must be sorted in ascending" " order and values must be unique. Ordering is determined by ][%00-00* less][%00-0" "0 .]&][s1;%00-00 [%00-00*C@4 C][%00-00 -|Type of container.]&][s1;%00-00 [%00-00*" "C@3 from][%00-00 -|Destination container.]&][s1;%00-00 [%00-00*C@3 what][%00-00 -" "|Source container.]&][s1;%00-00 [%00-00*C@3 less][%00-00 -|Ordering predicate.]&]" "[s1;%00-00 [%00-00*/ Return value][%00-00 -|Destination container.]&][s13;:templa" "te` C`& RemoveSorted`(C`& from`, const C`& what`):%00-00 [%00-00 templa" "te]&][s14;:template` C`& RemoveSorted`(C`" "& from`, const C`& what`):%00-00 [%00-00*@4 C][%00-00 `& ][%00-00* RemoveSorted][" "%00-00 (][%00-00*@4 C][%00-00 `& ][%00-00*@3 from][%00-00 , const ][%00-00*@4 C][" "%00-00 `& ][%00-00*@3 what][%00-00 )]&][s6;%00-00 [%00-00 Removes elements of sou" "rce container from destination container. Both containers must be sorted in ascen" "ding order and values must be unique. Ordering is determined by ][%00-00*/ operat" "or<][%00-00 .]&][s1;%00-00 [%00-00*C@4 C][%00-00 -|Type of container.]&][s1;%00-0" "0 [%00-00*C@3 from][%00-00 -|Destination container.]&][s1;%00-00 [%00-00*C@3 what" "][%00-00 -|Source container.]&][s1;%00-00 [%00-00*/ Return value][%00-00 -|Destin" "ation container.]&][s13;:template` D`& IntersectSor" "ted`(D`& dest`, const S`& src`, const L`& less`):%00-00 [%00-00 template" "]&][s14;:template` D`& Inte") TOPIC_TEXT( "rsectSorted`(D`& dest`, const S`& src`, const L`& less`):%00-00 [%00-00*@4 D][%0" "0-00 `& ][%00-00* IntersectSorted][%00-00 (][%00-00*@4 D][%00-00 `& ][%00-00*@3 d" "est][%00-00 , const ][%00-00*@4 S][%00-00 `& ][%00-00*@3 src][%00-00 , const ][%0" "0-00*@4 L][%00-00 `& ][%00-00*@3 less][%00-00 )]&][s6;%00-00 [%00-00 Removes elem" "ents from destination container that are not contained in source container. Both " "containers must be sorted in ascending order and values must be unique. Ordering " "is determined by ][%00-00* less][%00-00 .]&][s1;%00-00 [%00-00*C@4 D][%00-00 -|Ty" "pe of destination container.]&][s1;%00-00 [%00-00*C@4 S][%00-00 -|Type of source " "container.]&][s1;%00-00 [%00-00*C@3 dest][%00-00 -|Destination container.]&][s1;%" "00-00 [%00-00*C@3 src][%00-00 -|Source container.]&][s1;%00-00 [%00-00*C@3 less][" "%00-00 -|Destination container.]&][s13;:template` D`& Interse" "ctSorted`(D`& dest`, const S`& src`):%00-00 [%00-00 template]&][s14;:template` D`&" " IntersectSorted`(D`& dest`, const S`& src`):%00-00 [%00-00*@4 D][%00-00 `& ][%00" "-00* IntersectSorted][%00-00 (][%00-00*@4 D][%00-00 `& ][%00-00*@3 dest][%00-00 ," " const ][%00-00*@4 S][%00-00 `& ][%00-00*@3 src][%00-00 )]&][s6;%00-00 [%00-00 Re" "moves elements from destination container that are not contained in source contai" "ner. Both containers must be sorted in ascending order and values must be unique." " Ordering is determined by ][%00-00*/ operator<][%00-00 .]&][s1;%00-00 [%00-00*C@" "4 D][%00-00 -|Type of destination container.]&][s1;%00-00 [%00-00*C@4 S][%00-00 -" "|Type of source container.]&][s1;%00-00 [%00-00*C@3 dest][%00-00 -|Destination co" "ntainer.]&][s1;%00-00 [%00-00*C@3 src][%00-00 -|Source container.]&][s1;%00-00 [%" "00-00*/ Return value][%00-00 -|Destination container.]&][s13;:template`" " void StreamContainer`(Stream`& s`, T`& cont`):%00-00 [%00-00 template]&][s") TOPIC_TEXT( "14;:template` void StreamContainer`(Stream`& s`, T`& cont`):%00-00 [%0" "0-00 void ][%00-00* Sort][%00-00 (][%00-00*@4 T][%00-00 `& ][%00-00*@3 c][%00-00 " ", const ][%00-00*@4 Less][%00-00 `& ][%00-00*@3 less][%00-00 )]&][s6;%00-00 [%00-" "00 Sorts container. Ordering is determined by ][%00-00* less][%00-00 .]&][s11; It" "erSwap must be defined for T`::Iterator.&][s1;%00-00 [%00-00*C@4 T][%00-00 -|Type" " of container.]&][s1;%00-00 [%00-00*C@3 c][%00-00 -|Container.]&][s1;%00-00 [%00-" "00*C@3 less][%00-00 -|Ordering predicate.]&][s13;:template` void Sort`(" "T`& c`):%00-00 [%00-00 template]&][s14;:template` void Sort`(T`& c`):%00-00 [%00-00 void ][%00-00* Sort][%00-00 (][%00-00*" "@4 T][%00-00 `& ][%00-00*@3 c][%00-00 )]&][s6;%00-00 [%00-00 Sorts container. Ord" "ering is determined by ][%00-00*/ operato<][%00-00 .]&][s6;%00-00*1 [%00-00 IterS" "wap must be defined for T`::Iterator.]&][s1;%00-00 [%00-00*C@4 T][%00-00 -|Type o" "f container.]&][s1;%00-00 [%00-00*C@3 c][%00-00 -|Container.]&][s13;:template` void `_`_IndexSort`(II begin`, II end`" ", VI pair`, const Less`& less`, const K `*`):%00-00 [%00-00 template]&][s14;:template` void `_`_IndexSo" "rt`(II begin`, II end`, VI pair`, const Less`& less`, const K `*`):%00-00 [%00-00" " void ][%00-00* IndexSort][%00-00 (][%00-00*@4 KC][%00-00 `& ][%00-00*@3 keys][%0" "0-00 , ][%00-00*@4 VC][%00-00 `& ][%00-00*@3 values][%00-00 , const ][%00-00*@4 L" "ess][%00-00 `& ][%00-00*@3 less][%00-00 )]&][s6;%00-00 [%00-00 Sorts pair of cont" "ainers. Both containers must have same number of items. Resulting order is determ" "ined by ][%00-00* keys][%00-00 container. Ordering is determined by ][%00-00* le" "ss][%00-00 .]&][s1;%00-00 [%00-00*C@4 KC][%00-00 -|Type of keys container.]&][s1;" "%00-00 [%00-00*C@4 VC][%00-00 -|Type of values.]&][s1;%00") TOPIC_TEXT( "-00 [%00-00*C@3 keys][%00-00 -|Container of keys.]&][s1;%00-00 [%00-00*C@3 value" "s][%00-00 -|Container of values.]&][s1;%00-00 [%00-00*C@3 less][%00-00 -|Ordering" " predicate.]&][s13;:template` void IndexSort`(KC`& keys`, V" "C`& values`):%00-00 [%00-00 template]&][s14;:template` void IndexSort`(KC`& ke" "ys`, VC`& values`):%00-00 [%00-00 void ][%00-00* IndexSort][%00-00 (][%00-00*@4 K" "C][%00-00 `& ][%00-00*@3 keys][%00-00 , ][%00-00*@4 VC][%00-00 `& ][%00-00*@3 val" "ues][%00-00 )]&][s6;%00-00 [%00-00 Sorts pair of containers. Both containers must" " have same number of items. Resulting order is determined by ][%00-00* keys][%00-" "00 container. Ordering is determined by ][%00-00*/ operator<][%00-00 .]&][s1;%00" "-00 [%00-00*C@4 KC][%00-00 -|Type of keys container.]&][s1;%00-00 [%00-00*C@4 VC]" "[%00-00 -|Type of values container.]&][s1;%00-00 [%00-00*C@3 keys][%00-00 -|Conta" "iner of keys.]&][s1;%00-00 [%00-00*C@3 values][%00-00 -|Container of values.]&][s" "13;:template` void `_`_SortOrder`(int `*begin`, " "int `*end`, I data`, const Less`& less`, const V `*`):%00-00 [%00-00 template]&][s14;:template` void `_`_SortOrder`(int `*begin`, int `*end`, I dat" "a`, const Less`& less`, const V `*`):%00-00 [%00-00 Vector ][%00-00* GetSort" "Order][%00-00 (const ][%00-00*@4 C][%00-00 `& ][%00-00*@3 container][%00-00 , con" "st ][%00-00*@4 Less][%00-00 `& ][%00-00*@3 less][%00-00 )]&][s6;%00-00 [%00-00 Cr" "eates ascending order of values in container. Ordering is determined by ][%00-00*" " less][%00-00 .]&][s1;%00-00 [%00-00*C@4 C][%00-00 -|Type of container.]&][s1;%00" "-00 [%00-00*C@3 container][%00-00 -|Source container.]&][s1;%00-00 [%00-00*C@3 le" "ss][%00-00 -|Ordering predicate.]&][s1;%00-00 [%00-00*/ Return value][%00-00 -|Ve" "ctor of positions of source container in sorted order.]&]") TOPIC_TEXT( "[s13;:template` Vector` GetSortOrder`(const C`& container`):%00-" "00 [%00-00 template]&][s14;:template` Vec" "tor` GetSortOrder`(const C`& container`):%00-00 [%00-00 Vector ][%00-0" "0* GetSortOrder][%00-00 (const ][%00-00*@4 C][%00-00 `& ][%00-00*@3 container][%0" "0-00 )]&][s6;%00-00 [%00-00 Creates ascending order of values in container. Order" "ing is determined by ][%00-00*/ operator<][%00-00 .]&][s1;%00-00 [%00-00*C@4 C][%" "00-00 -|Type of container.]&][s1;%00-00 [%00-00*C@3 container][%00-00 -|Source co" "ntainer.]&][s1;%00-00 [%00-00*/ Return value][%00-00 -|Vector of positions of sou" "rce container in sorted order.]&][s13;:template` v" "oid GetFieldContainer`(DC`& dest`, I begin`, I end`, F field`):%00-00 [%00-00 tem" "plate]&][s14;:template` void GetFieldCont" "ainer`(DC`& dest`, I begin`, I end`, F field`):%00-00 [%00-00/ type][%00-00 ][%0" "0-00* FieldRelation][%00-00 (][%00-00*@4 O][%00-00 (][%00-00*@4 T][%00-00 `::*][" "%00-00*@3 member][%00-00 ), const ][%00-00*@4 R][%00-00 `& ][%00-00*@3 relation][" "%00-00 )]&][s6;%00-00 [%00-00 Creates ordering predicate for ][%00-00* T][%00-00 " " based on value of member variable of][%00-00* T][%00-00 .]&][s1;%00-00 [%00-00*" "C@4 T][%00-00 -|Type of element.]&][s1;%00-00 [%00-00*C@3 member][%00-00 -|Member" " variable of T.]&][s1;%00-00 [%00-00*C@3 relation][%00-00 -|Ordering relation for" " ][%00-00* member][%00-00 .]&][s1;%00-00 [%00-00*/ Return value][%00-00 -|Orderin" "g predicate.]&][s13;:template` MethodRelationCls` MethodRelation`(O `(T`:`:`*method`)`(`)`, const R`& re" "lation`):%00-00 [%00-00 template]&][s14;:template` MethodRelationCls` M") TOPIC_TEXT( "ethodRelation`(O `(T`:`:`*method`)`(`)`, const R`& relation`):%00-00 [%00-00/ ty" "pe][%00-00 ][%00-00* MethodRelation][%00-00 (][%00-00*@4 O][%00-00 (][%00-00*@4" " T][%00-00 `::*][%00-00*@3 method][%00-00 )(), const ][%00-00*@4 R][%00-00 `& ][%" "00-00*@3 relation][%00-00 )]&][s6;%00-00 [%00-00 Creates ordering predicate for ]" "[%00-00* T][%00-00 based on value returned by non-const method of ][%00-00* T][%" "00-00 .]&][s1;%00-00 [%00-00*C@4 T][%00-00 -|Type of element.]&][s1;%00-00 [%00-0" "0*C@3 method][%00-00 -|Method of T.]&][s1;%00-00 [%00-00*C@3 relation][%00-00 -|O" "rdering relation for value returned by method.]&][s1;%00-00 [%00-00*/ Return valu" "e][%00-00 -|Ordering predicate.]&][s13;:template` M" "ethodRelationCls` MethodRelation`(O `(T`:`:`*me" "thod`)`(`) const`, const R`& relation`):%00-00 [%00-00 template]&][s14;:" "template` MethodRelationCls` MethodRelation`(O `(T`:`:`*method`)`(`) const`, const R`& relation`):" "%00-00 [%00-00/ type][%00-00 ][%00-00* MethodRelation][%00-00 (][%00-00*@4 O][%0" "0-00 (][%00-00*@4 T][%00-00 `::*][%00-00*@3 method][%00-00 )() const, const ][%0" "0-00*@4 R][%00-00 `& ][%00-00*@3 relation][%00-00 )]&][s6;%00-00 [%00-00 Creates " "ordering predicate for ][%00-00* T][%00-00 based on value returned by const meth" "od of ][%00-00* T][%00-00 .]&][s1;%00-00 [%00-00*C@4 T][%00-00 -|Type of element." "]&][s1;%00-00 [%00-00*C@3 method][%00-00 -|Method of T.]&][s1;%00-00 [%00-00*C@3 " "relation][%00-00 -|Ordering relation for value returned by method.]&][s1;%00-00 [" "%00-00*/ Return value][%00-00 -|Ordering predicate.]") /******************************************************************************/ /*! \file SetFullscreenCommand.h \author \par email: \par Mach5 Game Engine \date 2016/10/16 Creates a command to change the resolution */ /******************************************************************************/ #include "SetFullscreenCommand.h" #include "M5App.h" #include "M5IniFile.h" SetFullscreenCommand::SetFullscreenCommand(void) :m_isFullscreen(false) { } void SetFullscreenCommand::Execute(void) { M5App::SetFullScreen(m_isFullscreen); } SetFullscreenCommand* SetFullscreenCommand::Clone(void) const { SetFullscreenCommand* pClone = new SetFullscreenCommand(); pClone->m_isFullscreen = m_isFullscreen; return pClone; } void SetFullscreenCommand::FromFile(M5IniFile& iniFile) { iniFile.SetToSection("SetFullscreenCommand"); iniFile.GetValue("isFullscreen", m_isFullscreen); }sumon08/Counter /* * flashstring.h * * Created: 4/20/2020 12:32:55 AM * Author: Asus */ #ifndef FLASHSTRING_H_ #define FLASHSTRING_H_ namespace Shrine { template class FlashString { const char * str; }; } #endif /* FLASHSTRING_H_ */1-10 #include #include #include #include #include #include "DSSE.h" #include #include "zmq.hpp" #include using namespace std; int nTime = 100; int nUpdateTime = 50; vector gt; void printMenu(); typedef std::numeric_limits dbl; string exec(const char* cmd); bool fexists(string filename_with_path) { ifstream ifile(filename_with_path.c_str()); if(!ifile.is_open()) return false; return true; } void reset(int dim) { zmq::context_t context(1); zmq::socket_t socket(context,ZMQ_REQ); int CMD_SAVE = 123455; double res[15]; for(int i = 0 ; i < 15; i++) { if(Client_DSSE::stats[i].size()>0) { Client_DSSE::stats[i].erase(Client_DSSE::stats[i].begin()); } res[i] = 0.0 ; for(int j = 0 ; j < Client_DSSE::stats[i].size(); j++) { res[i] += Client_DSSE::stats[i][j] ; } if(Client_DSSE::stats[i].size()>0) { res[i] = res[i]/(Client_DSSE::stats[i].size()); } //cout<stats[i].reserve(nTime); } while (1) { int selection =-1; do { printMenu(); cout<<"Select your choice: "; while(!(cin>>selection)) { cin.clear(); cin.ignore(numeric_limits::max(),'\n'); cout<<"Invalid input. Try again: "; } }while(selection < 0 && selection >4); switch(selection) { case 0: client_dsse->genMaster_key(); break; case 1: start = time_now; client_dsse->createEncrypted_data_structure(); end = time_now; cout<<"Elapsed time: "<(end-start).count()<<" ms"<>str_keyword; std::transform(str_keyword.begin(),str_keyword.end(),str_keyword.begin(),::tolower); for(int i = 0 ; i <= nTime; i ++) { cout<searchKeyword(str_keyword,search_result); // cout<addFile(updating_filename,gcsUpdateFilepath); client_dsse->delFile(updating_filename,gcsUpdateFilepath); } reset(COL); //end = tClient_DSSEime_now; /* cout<<"Total Elapsed time: "<(end-start).count()<<" ms"<0) { cout<<"See "<>updating_filename; if(!fexists(gcsUpdateFilepath+updating_filename)) { cout<addFile(updating_filename,gcsUpdateFilepath); client_dsse->delFile(updating_filename,gcsUpdateFilepath); } reset(COL); //end = time_now; //cout<<"Total Elapsed time: "<(end-start).count()<<" ms"<addFile(updating_filename,gcsUpdateFilepath); client_dsse->delFile(updating_filename,gcsUpdateFilepath); } reset(COL); break; /*case 4: cout<<"Specify the filename want to delete: "; cin>>updating_filename; start = time_now; client_dsse->delFile(updating_filename,gcsUpdateFilepath); end = time_now; cout<<"Total Elapsed time: "<(end-start).count()<<" ms"<andrei-sa/aspen #include "Aspen/Python/Box.hpp" using namespace Aspen; using namespace pybind11; void Aspen::export_box(pybind11::module& module) { export_box(module, ""); export_box(module, "None"); implicitly_convertible, SharedBox>(); } /* * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies) * Copyright (C) 2009 University of Szeged * * 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. * * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. 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 "urlloader.h" #include #include UrlLoader::UrlLoader(QWebFrame* frame, const QString& inputFileName) : m_frame(frame) , m_stdOut(stdout) , m_loaded(0) { init(inputFileName); } void UrlLoader::loadNext() { QString qstr; if (getUrl(qstr)) { QUrl url(qstr, QUrl::StrictMode); if (url.isValid()) { m_stdOut << "Loading " << qstr << " ......" << ++m_loaded << endl; m_frame->load(url); } else loadNext(); } else disconnect(m_frame, 0, this, 0); } void UrlLoader::init(const QString& inputFileName) { QFile inputFile(inputFileName); if (inputFile.open(QIODevice::ReadOnly | QIODevice::Text)) { QTextStream stream(&inputFile); QString line; while (true) { line = stream.readLine(); if (line.isNull()) break; m_urls.append(line); } } else { qDebug() << "Can't open list file"; exit(0); } m_index = 0; inputFile.close(); } bool UrlLoader::getUrl(QString& qstr) { if (m_index == m_urls.size()) return false; qstr = m_urls[m_index++]; return true; } #include "CondicionalComposta.h" CondicionalComposta::CondicionalComposta() { //ctor } CondicionalComposta::~CondicionalComposta() { //dtor } 10-100 //----------------------------------*-C++-*----------------------------------// // Copyright 2020 UT-Battelle, LLC, and other Celeritas developers. // See the top-level COPYRIGHT file for details. // SPDX-License-Identifier: (Apache-2.0 OR MIT) //---------------------------------------------------------------------------// //! \file Quantity.test.cc //---------------------------------------------------------------------------// #include "base/Quantity.hh" #include #include "base/Constants.hh" #include "celeritas_test.hh" using celeritas::native_value_from; using celeritas::native_value_to; using celeritas::Quantity; using celeritas::value_as; using celeritas::zero_quantity; using celeritas::constants::pi; // One revolution = 2pi radians struct TwoPi { static double value() { return 2 * celeritas::constants::pi; } }; using Revolution = Quantity; struct DozenUnit { static int value() { return 12; } }; //---------------------------------------------------------------------------// // TESTS //---------------------------------------------------------------------------// TEST(QuantityTest, simplicity) { EXPECT_EQ(sizeof(Revolution), sizeof(double)); EXPECT_TRUE(std::is_standard_layout::value); EXPECT_TRUE(std::is_default_constructible::value); } TEST(QuantityTest, usage) { // Since powers of 2 are exactly represented in IEEE arithimetic, we can // exactly operate on data (e.g. in this case where a user wants a radial // mesh that spans half a turn, i.e. pi) Revolution user_input{0.5}; double dtheta = user_input.value() / 8; EXPECT_EQ(1.0 / 16.0, dtheta); // Hypothetical return value for user Revolution spacing{dtheta}; EXPECT_SOFT_EQ(2 * pi / 16, native_value_from(spacing)); // Create a quantity from a literal value in the native unit system auto half_rev = native_value_to(celeritas::constants::pi); EXPECT_TRUE((std::is_same::value)); EXPECT_DOUBLE_EQ(0.5, value_as(half_rev)); } TEST(QuantityTest, zeros) { // Construct a quantity with value of zero Revolution zero_turn; EXPECT_EQ(0, zero_turn.value()); zero_turn = Revolution{10}; // Construct from a "zero" sentinel type zero_turn = zero_quantity(); EXPECT_EQ(0, value_as(zero_turn)); } TEST(QuantityTest, comparators) { EXPECT_TRUE(zero_quantity() < Revolution{4}); EXPECT_TRUE(zero_quantity() <= Revolution{4}); EXPECT_TRUE(zero_quantity() != Revolution{4}); EXPECT_FALSE(zero_quantity() > Revolution{4}); EXPECT_FALSE(zero_quantity() >= Revolution{4}); EXPECT_FALSE(zero_quantity() == Revolution{4}); EXPECT_TRUE(Revolution{3} < Revolution{4}); EXPECT_TRUE(Revolution{3} <= Revolution{4}); EXPECT_TRUE(Revolution{3} != Revolution{4}); EXPECT_FALSE(Revolution{3} > Revolution{4}); EXPECT_FALSE(Revolution{3} >= Revolution{4}); EXPECT_FALSE(Revolution{3} == Revolution{4}); EXPECT_FALSE(Revolution{5} < Revolution{4}); EXPECT_FALSE(Revolution{5} <= Revolution{4}); EXPECT_TRUE(Revolution{5} != Revolution{4}); EXPECT_TRUE(Revolution{5} > Revolution{4}); EXPECT_TRUE(Revolution{5} >= Revolution{4}); EXPECT_FALSE(Revolution{5} == Revolution{4}); } TEST(QuantityTest, infinities) { using celeritas::max_quantity; using celeritas::neg_max_quantity; EXPECT_TRUE(neg_max_quantity() < Revolution{-1e300}); EXPECT_TRUE(neg_max_quantity() < zero_quantity()); EXPECT_TRUE(zero_quantity() < max_quantity()); EXPECT_TRUE(max_quantity() > Revolution{1e300}); } TEST(QuantityTest, swappiness) { using Dozen = Quantity; Dozen dozen{1}, gross{12}; { // ADL should prefer celeritas::swap implementation using std::swap; swap(dozen, gross); EXPECT_EQ(1, gross.value()); EXPECT_EQ(12, dozen.value()); } { // Should still work without std swap(dozen, gross); EXPECT_EQ(12, value_as(gross)); EXPECT_EQ(1, value_as(dozen)); } EXPECT_EQ(12, native_value_from(dozen)); EXPECT_EQ(144, native_value_from(gross)); } kedixa/workflow /* Copyright (c) 2019 Sogou, 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. Author: (;) */ #include #include #include "workflow/WFTaskFactory.h" #include "workflow/WFFacilities.h" using namespace algorithm; static WFFacilities::WaitGroup wait_group(1); bool use_parallel_sort = false; void callback(WFSortTask *task) { /* Sort task's input and output are identical. */ SortInput *input = task->get_input(); int *first = input->first; int *last = input->last; /* You may remove this output to test speed. */ int *p = first; while (p < last) printf("%d ", *p++); printf("\n"); if (task->user_data == NULL) { auto cmp = [](int a1, int a2)->bool{return a2 *reverse; if (use_parallel_sort) reverse = WFAlgoTaskFactory::create_psort_task("sort", first, last, cmp, callback); else reverse = WFAlgoTaskFactory::create_sort_task("sort", first, last, cmp, callback); reverse->user_data = (void *)1; /* as a flag */ series_of(task)->push_back(reverse); printf("Sort reversely:\n"); } else wait_group.done(); } int main(int argc, char *argv[]) { size_t count; int *array; int *end; size_t i; if (argc != 2 && argc != 3) { fprintf(stderr, "USAGE: %s [p]\n", argv[0]); exit(1); } count = atoi(argv[1]); array = (int *)malloc(count * sizeof (int)); if (!array) { perror("malloc"); exit(1); } if (argc == 3 && (*argv[2] == 'p' || *argv[2] == 'P')) use_parallel_sort = true; for (i = 0; i < count; i++) array[i] = rand() % 65536; end = &array[count]; WFSortTask *task; if (use_parallel_sort) task = WFAlgoTaskFactory::create_psort_task("sort", array, end, callback); else task = WFAlgoTaskFactory::create_sort_task("sort", array, end, callback); if (use_parallel_sort) printf("Start sorting parallelly...\n"); else printf("Start sorting...\n"); printf("Sort result:\n"); task->start(); wait_group.wait(); free(array); return 0; } /* Copyright (c) 2007-2009, 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 developer 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 D ''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 D 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 "ofxOscSender.h" #include "ofUtils.h" #include "ofParameterGroup.h" #include "UdpSocket.h" #include ofxOscSender::ofxOscSender() { socket = NULL; } ofxOscSender::~ofxOscSender() { if ( socket ) shutdown(); } void ofxOscSender::setup( std::string hostname, int port ) { if ( socket ) shutdown(); socket = new UdpTransmitSocket( IpEndpointName( hostname.c_str(), port ) ); } void ofxOscSender::shutdown() { if ( socket ) delete socket; socket = NULL; } void ofxOscSender::sendBundle( ofxOscBundle& bundle ) { //setting this much larger as it gets trimmed down to the size its using before being sent. //TODO: much better if we could make this dynamic? Maybe have ofxOscBundle return its size? static const int OUTPUT_BUFFER_SIZE = 327680; char buffer[OUTPUT_BUFFER_SIZE]; osc::OutboundPacketStream p(buffer, OUTPUT_BUFFER_SIZE ); // serialise the bundle appendBundle( bundle, p ); socket->Send( p.Data(), p.Size() ); } void ofxOscSender::sendMessage( ofxOscMessage& message, bool wrapInBundle ) { //setting this much larger as it gets trimmed down to the size its using before being sent. //TODO: much better if we could make this dynamic? Maybe have ofxOscMessage return its size? static const int OUTPUT_BUFFER_SIZE = 327680; char buffer[OUTPUT_BUFFER_SIZE]; osc::OutboundPacketStream p( buffer, OUTPUT_BUFFER_SIZE ); // serialise the message if(wrapInBundle) p << osc::BeginBundleImmediate; appendMessage( message, p ); if(wrapInBundle) p << osc::EndBundle; socket->Send( p.Data(), p.Size() ); } void ofxOscSender::sendParameter( const ofAbstractParameter & parameter){ if(!parameter.isSerializable()) return; if(parameter.type()==typeid(ofParameterGroup).name()){ string address = "/"; const vector hierarchy = parameter.getGroupHierarchyNames(); for(int i=0;i<(int)hierarchy.size()-1;i++){ address+=hierarchy[i] + "/"; } ofxOscBundle bundle; appendParameter(bundle,parameter,address); sendBundle(bundle); }else{ string address = ""; const vector hierarchy = parameter.getGroupHierarchyNames(); for(int i=0;i<(int)hierarchy.size()-1;i++){ address+= "/" + hierarchy[i]; } if(address.length()) address += "/"; ofxOscMessage msg; appendParameter(msg,parameter,address); sendMessage(msg, false); } } void ofxOscSender::appendParameter( ofxOscBundle & _bundle, const ofAbstractParameter & parameter, string address){ if(parameter.type()==typeid(ofParameterGroup).name()){ ofxOscBundle bundle; const ofParameterGroup & group = static_cast(parameter); for(int i=0;i).name()){ msg.addIntArg(parameter.cast()); }else if(parameter.type()==typeid(ofParameter).name()){ msg.addFloatArg(parameter.cast()); }else if(parameter.type()==typeid(ofParameter).name()){ msg.addIntArg(parameter.cast()); }else{ msg.addStringArg(parameter.toString()); } } void ofxOscSender::appendBundle( ofxOscBundle& bundle, osc::OutboundPacketStream& p ) { // recursively serialise the bundle p << osc::BeginBundleImmediate; for ( int i=0; i1-10 /**************************************************************************** ** ** Copyright (C) 2017 TU Wien, ACIN, Vision 4 Robotics (V4R) group ** Contact: v4r.acin.tuwien.ac.at ** ** This file is part of V4R ** ** V4R is distributed under dual licenses - GPLv3 or closed source. ** ** GNU General Public License Usage ** V4R 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. ** ** V4R 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. ** ** Please review the following information to ensure the GNU General Public ** License requirements will be met: https://www.gnu.org/licenses/gpl-3.0.html. ** ** ** Commercial License Usage ** If GPL is not suitable for your project, you must purchase a commercial ** license to use V4R. Licensees holding valid commercial V4R licenses may ** use this file in accordance with the commercial license agreement ** provided with the Software or, alternatively, in accordance with the ** terms contained in a written agreement between you and TU Wien, ACIN, V4R. ** For licensing terms and conditions please contact officeacin.tuwien.ac.at. ** ** ** The copyright holder additionally grants the author(s) of the file the right ** to use, copy, modify, merge, publish, distribute, sublicense, and/or ** sell copies of their contributions without any restrictions. ** ****************************************************************************/ /** * @file Graph.cpp * @author * @date July 2011 * @version 0.1 * @brief Create graph from relations. */ #include "v4r/attention_segmentation/Graph.h" #include #ifndef GC_DEBUG #define GC_DEBUG true #endif namespace gc { template inline T1 Dot3(const T1 v1[3], const T2 v2[3]) { return v1[0] * v2[0] + v1[1] * v2[1] + v1[2] * v2[2]; } template inline void Add3(const T1 v1[3], const T2 v2[3], T3 r[3]) { r[0] = v1[0] + v2[0]; r[1] = v1[1] + v2[1]; r[2] = v1[2] + v2[2]; } /** * @brief Constructor of Graph */ Graph::Graph() { nodes = 0; relations.clear(); } /** * @brief Constructor of Graph */ Graph::Graph(unsigned nrNodes, std::vector &rel) { nodes = nrNodes; relations = rel; } /** * @brief Constructor of Graph */ Graph::Graph(std::vector &surf, std::vector &rel) { surfaces = surf; relations = rel; } /** * @brief Destructor of GraphCut */ Graph::~Graph() {} /** * @brief Build graph from results of the SVM-Predictor. * @param e Vector of edges * @param num_edges Number of created edges. */ void Graph::BuildFromSVM(std::vector &e, unsigned &num_edges, std::vector &surfaces_reindex2) { if (GC_DEBUG) { for (unsigned i = 0; i < relations.size(); i++) printf("[Graph::BuildFromSVM] Relation %u: %u-%u\n", i, relations[i].id_0, relations[i].id_1); } // Connectivity check for graph //@ep: create connected graph? bool find_sink = false; int sink = 0; for (unsigned i = 0; i < surfaces.size(); i++) { if (!(surfaces.at(i)->selected)) continue; if (!find_sink) { sink = i; find_sink = true; } bool node_found = false; for (unsigned j = 0; j < relations.size(); j++) { if (relations[j].id_0 == sink && relations[j].id_1 == ((int)i)) { node_found = true; } } if (!node_found) { if (GC_DEBUG) printf("[Graph::BuildFromSVM] Warning: Node without relation: Add relation: %u-%u.\n", 0, i); v4r::Relation r; r.id_0 = sink; r.id_1 = i; r.groundTruth = -1; r.type = 1; r.rel_probability.push_back(1.0); r.rel_probability.push_back(0.0); relations.push_back(r); } } if (GC_DEBUG) { for (unsigned i = 0; i < relations.size(); i++) printf("[Graph::BuildFromSVM] Relation %u: %u-%u\n", i, relations[i].id_0, relations[i].id_1); } // create maping from real surface to artificial surfaces surfaces_reindex.clear(); for (unsigned i = 0; i < surfaces.size(); i++) { if (!(surfaces.at(i)->selected)) continue; surfaces_reindex.push_back(i); } surfaces_reindex2.resize(surfaces.size()); int num_valid_surfaces = 0; for (unsigned i = 0; i < surfaces.size(); i++) { surfaces_reindex2.at(i) = -1; if (!(surfaces.at(i)->selected)) continue; surfaces_reindex2.at(i) = num_valid_surfaces; num_valid_surfaces++; } for (unsigned i = 0; i < relations.size(); i++) { gc::Edge e; e.a = surfaces_reindex2.at(relations[i].id_0); e.b = surfaces_reindex2.at(relations[i].id_1); e.type = 1; e.w = relations[i].rel_probability[0]; if (GC_DEBUG) printf("[Graph::BuildFromSVM] New edge (type: %i): %i-%i: %8.8f\n", e.type, e.a, e.b, e.w); edges.push_back(e); } num_edges = edges.size(); e = edges; if (GC_DEBUG) printf("[Graph::BuildFromSVM] Created %lu edges from %lu relations\n", edges.size(), relations.size()); } /** * @brief Build graph from point cloud with 4-neighborhood. * @param pcl_cloud * @param e Vector of edges * @param num_edges Number of created edges. */ void Graph::BuildFromPointCloud(pcl::PointCloud::Ptr &_pcl_cloud, pcl::PointCloud::Ptr &_normals, std::vector &e, unsigned &num_edges) { float z_adapt = 0.01; pcl_cloud = _pcl_cloud; normals = _normals; edges.clear(); // normalization of curvature float max_curv = 0.0; for (unsigned i = 0; i < normals->points.size(); i++) if (!std::isnan(pcl_cloud->points[i].z)) if (normals->points[i].curvature > max_curv) max_curv = normals->points[i].curvature; VLOG(1) << "Max curvature: << " << max_curv; // pre-calculate color distance float color_dist[pcl_cloud->points.size()][4]; float max_color = 0.0f; // #pragma omp parallel for for (unsigned row = 0; row < pcl_cloud->height - 1; row++) { for (unsigned col = 0; col < pcl_cloud->width - 1; col++) { int idx = GetIdx(col, row); pcl::PointXYZRGB pt_0 = pcl_cloud->points[idx]; // Check also the distance of the points! pcl::PointXYZRGB pt_1 = pcl_cloud->points[idx + 1]; color_dist[idx][0] = sqrt(((float)pt_0.r / 255. - (float)pt_1.r / 255.) * ((float)pt_0.r / 255. - (float)pt_1.r / 255.) + ((float)pt_0.g / 255. - (float)pt_1.g / 255.) * ((float)pt_0.g / 255. - (float)pt_1.g / 255.) + ((float)pt_0.b / 255. - (float)pt_1.b / 255.) * ((float)pt_0.b / 255. - (float)pt_1.b / 255.)); if (color_dist[idx][0] > max_color) max_color = color_dist[idx][0]; pt_0 = pcl_cloud->points[idx]; pt_1 = pcl_cloud->points[idx + pcl_cloud->width]; color_dist[idx][1] = sqrt(((float)pt_0.r / 255. - (float)pt_1.r / 255.) * ((float)pt_0.r / 255. - (float)pt_1.r / 255.) + ((float)pt_0.g / 255. - (float)pt_1.g / 255.) * ((float)pt_0.g / 255. - (float)pt_1.g / 255.) + ((float)pt_0.b / 255. - (float)pt_1.b / 255.) * ((float)pt_0.b / 255. - (float)pt_1.b / 255.)); if (color_dist[idx][1] > max_color) max_color = color_dist[idx][1]; pt_0 = pcl_cloud->points[idx]; pt_1 = pcl_cloud->points[idx + pcl_cloud->width + 1]; color_dist[idx][2] = sqrt(((float)pt_0.r / 255. - (float)pt_1.r / 255.) * ((float)pt_0.r / 255. - (float)pt_1.r / 255.) + ((float)pt_0.g / 255. - (float)pt_1.g / 255.) * ((float)pt_0.g / 255. - (float)pt_1.g / 255.) + ((float)pt_0.b / 255. - (float)pt_1.b / 255.) * ((float)pt_0.b / 255. - (float)pt_1.b / 255.)); if (color_dist[idx][2] > max_color) max_color = color_dist[idx][2]; if (col != 0) { pt_0 = pcl_cloud->points[idx]; pt_1 = pcl_cloud->points[idx + pcl_cloud->width - 1]; color_dist[idx][3] = sqrt(((float)pt_0.r / 255. - (float)pt_1.r / 255.) * ((float)pt_0.r / 255. - (float)pt_1.r / 255.) + ((float)pt_0.g / 255. - (float)pt_1.g / 255.) * ((float)pt_0.g / 255. - (float)pt_1.g / 255.) + ((float)pt_0.b / 255. - (float)pt_1.b / 255.) * ((float)pt_0.b / 255. - (float)pt_1.b / 255.)); if (color_dist[idx][3] > max_color) max_color = color_dist[idx][3]; } else color_dist[idx][3] = 1.0; } } // /// YUV conversion // for(unsigned i=0; i < pcl_cloud->points.size(); i++) { // pcl::PointXYZRGB pt_o = pcl_cloud->points[i]; // pcl::PointXYZRGB pt_n; // pt_n.r = (0.257 * pt_o.r) + (0.504 * pt_o.g) + (0.098 * pt_o.b) + 16; // R = Y // pt_n.g = -(0.148 * pt_o.r) - (0.291 * pt_o.g) + (0.439 * pt_o.b) + 128; // G = U // pt_n.b = (0.439 * pt_o.r) - (0.368 * pt_o.g) - (0.071 * pt_o.b) + 128; // B = V // } // // // pre-calculate color distance // float color_dist[pcl_cloud->points.size()][4]; // float max_color = 0.0f; // // #pragma omp parallel for // for(unsigned row=0; row < pcl_cloud->height-1; row++) { // for(unsigned col=0; col < pcl_cloud->width-1; col++) { // int idx = GetIdx(col, row); // pcl::PointXYZRGB pt_0 = pcl_cloud->points[idx]; // Check also the // distance of the points! // pcl::PointXYZRGB pt_1 = pcl_cloud->points[idx+1]; // color_dist[idx][0] = sqrt(((float)pt_0.g/255.-(float)pt_1.g/255.)*((float)pt_0.g/255.-(float)pt_1.g/255.) + // ((float)pt_0.b/255.-(float)pt_1.b/255.)*((float)pt_0.b/255.-(float)pt_1.b/255.)); // if(color_dist[idx][0] > max_color) // max_color = color_dist[idx][0]; // // printf("color dist[0]: %4.3f\n", color_dist[idx][0]); // pt_0 = pcl_cloud->points[idx]; // pt_1 = pcl_cloud->points[idx+pcl_cloud->width]; // color_dist[idx][1] = sqrt(((float)pt_0.g/255.-(float)pt_1.g/255.)*((float)pt_0.g/255.-(float)pt_1.g/255.) + // ((float)pt_0.b/255.-(float)pt_1.b/255.)*((float)pt_0.b/255.-(float)pt_1.b/255.)); // if(color_dist[idx][1] > max_color) // max_color = color_dist[idx][1]; // // printf("color dist[1]: %4.3f\n", color_dist[idx][1]); // pt_0 = pcl_cloud->points[idx]; // pt_1 = pcl_cloud->points[idx+pcl_cloud->width+1]; // color_dist[idx][2] = sqrt(((float)pt_0.g/255.-(float)pt_1.g/255.)*((float)pt_0.g/255.-(float)pt_1.g/255.) + // ((float)pt_0.b/255.-(float)pt_1.b/255.)*((float)pt_0.b/255.-(float)pt_1.b/255.)); // if(color_dist[idx][2] > max_color) // max_color = color_dist[idx][2]; // // printf("color dist[2]: %4.3f\n", color_dist[idx][2]); // if(col != 0) { // pt_0 = pcl_cloud->points[idx]; // pt_1 = pcl_cloud->points[idx+pcl_cloud->width-1]; // color_dist[idx][3] = sqrt(((float)pt_0.g/255.-(float)pt_1.g/255.)*((float)pt_0.g/255.-(float)pt_1.g/255.) + // ((float)pt_0.b/255.-(float)pt_1.b/255.)*((float)pt_0.b/255.-(float)pt_1.b/255.)); // if(color_dist[idx][3] > max_color) // max_color = color_dist[idx][3]; // } // else // color_dist[idx][3] = 1.0; // // printf("color dist[3]: %4.3f\n", color_dist[idx][3]); // } // } // Create Graph for (unsigned row = 0; row < pcl_cloud->height - 1; row++) { /// TODO Könnte man auch parallelisieren for (unsigned col = 0; col < pcl_cloud->width - 1; col++) { int idx = GetIdx(col, row); /// RIGHT gc::Edge e; e.a = idx; e.b = idx + 1; e.type = 1; e.w = color_dist[idx][0] / max_color; // normals angle double angle = 0.0; if (std::isnan(pcl_cloud->points[idx].z)) angle = 1.57; else angle = acos(Dot3(&normals->points[idx].normal[0], &normals->points[idx + 1].normal[0])); if (!std::isnan(angle)) e.w2 = angle; else e.w2 = 1.57; float z_dist = fabs(pcl_cloud->points[idx].z - pcl_cloud->points[idx + 1].z); if (!std::isnan(pcl_cloud->points[idx].z) && !std::isnan(pcl_cloud->points[idx + 1].z) && z_dist < (z_adapt * pcl_cloud->points[idx].z)) edges.push_back(e); /// BOTTOM e.a = idx; e.b = idx + pcl_cloud->width; e.type = 1; e.w = color_dist[idx][1] / max_color; // normals angle angle = 0.0; if (std::isnan(pcl_cloud->points[idx].z)) angle = 1.57; else angle = acos(Dot3(&normals->points[idx].normal[0], &normals->points[idx + pcl_cloud->width].normal[0])); if (!std::isnan(angle)) e.w2 = angle; else e.w2 = 1.57; z_dist = fabs(pcl_cloud->points[idx].z - pcl_cloud->points[idx + pcl_cloud->width].z); if (!std::isnan(pcl_cloud->points[idx].z) && !std::isnan(pcl_cloud->points[idx + pcl_cloud->width].z) && z_dist < (z_adapt * pcl_cloud->points[idx].z)) edges.push_back(e); /// BOTTOM-RIGHT e.a = idx; e.b = idx + pcl_cloud->width + 1; e.type = 1; e.w = color_dist[idx][2] / max_color; // normals angle angle = 0.0; if (std::isnan(pcl_cloud->points[idx].z)) angle = 1.57; else angle = acos(Dot3(&normals->points[idx].normal[0], &normals->points[idx + pcl_cloud->width + 1].normal[0])); if (!std::isnan(angle)) e.w2 = angle; else e.w2 = 1.57; z_dist = fabs(pcl_cloud->points[idx].z - pcl_cloud->points[idx + pcl_cloud->width + 1].z); if (!std::isnan(pcl_cloud->points[idx].z) && !std::isnan(pcl_cloud->points[idx + pcl_cloud->width + 1].z) && z_dist < (z_adapt * pcl_cloud->points[idx].z)) edges.push_back(e); /// BOTTOM-LEFT if (idx % pcl_cloud->width != 0) { e.a = idx; e.b = idx + pcl_cloud->width - 1; e.type = 1; e.w = color_dist[idx][3] / max_color; // normals angle angle = 0.0; if (std::isnan(pcl_cloud->points[idx].z)) angle = 1.57; else angle = acos(Dot3(&normals->points[idx].normal[0], &normals->points[idx + pcl_cloud->width - 1].normal[0])); if (!std::isnan(angle)) e.w2 = angle; else e.w2 = 1.57; z_dist = fabs(pcl_cloud->points[idx].z - pcl_cloud->points[idx + pcl_cloud->width - 1].z); if (!std::isnan(pcl_cloud->points[idx].z) && !std::isnan(pcl_cloud->points[idx + pcl_cloud->width - 1].z) && z_dist < (z_adapt * pcl_cloud->points[idx].z)) edges.push_back(e); } else { e.w = 1.0; z_dist = fabs(pcl_cloud->points[idx].z - pcl_cloud->points[idx + pcl_cloud->width - 1].z); if (!std::isnan(pcl_cloud->points[idx].z) && !std::isnan(pcl_cloud->points[idx + pcl_cloud->width - 1].z) && z_dist < (z_adapt * pcl_cloud->points[idx].z)) edges.push_back(e); } } } num_edges = edges.size(); e = edges; } } // namespace gc /* * This is a filesystem wrapper driver. To use it, mount it on top of another filesystem at a * different mountpoint. For example, mount the local path "d:/" as a normal directory to * /cdrom-native: * * FILEMAN->Mount( "dir", "d:/", "/cdrom-native" ); * * and then mount a timeout filesystem on top of that: * * FILEMAN->Mount( "timeout", "/cdrom-native", "/cdrom-timeout" ); * * and do all access to the device at /cdrom-timeout. * * A common problem with accessing devices, such as CDROMs or flaky pen drives, is that they * can take a very long time to fail under error conditions. A single request may have a * timeout of 500ms, but a single operation may do many requests. The system will usually * retry operations, and we want to allow it to do so, but we don't want the high-level * operation to take too long as a whole. * * There's no portable way to abort a running filesystem operation. In Unix, you may be * able to use SIGALRM, which should cause a running operation to fail with EINTR, but * I don't trust that, and it's not portable. * * This driver abstracts all access to another driver, and enforces high-level timeouts. * Operations are run in a separate thread. If an operation takes too long to complete, * the main thread will see it fail. The operation in the thread will actually continue; * it will time out for real eventually. To prevent accumulation of failed threads, if * an operation times out, we'll refuse all further access until all operations have * finished and exited. (Load a separate driver for each device, so if one device fails, * others continue to function.) * * All operations must run in the thread, including retrieving directory lists, Open() * and deleting file objects. Read/write operations are copied through an intermediate * buffer, so we don't clobber stuff if the operation times out, the call returns and the * operation then completes. * * Unmounting the filesystem will wait for all timed-out operations to complete. * * This class is not threadsafe; do not access files on this filesystem from multiple * threads simultaneously. */ #include "global.h" #include "RageFileDriverTimeout.h" #include "RageFile.h" #include "RageUtil.h" #include "RageUtil_FileDB.h" #include "RageUtil_WorkerThread.h" #include "RageLog.h" #include enum ThreadRequest { REQ_OPEN, REQ_CLOSE, REQ_GET_FILE_SIZE, REQ_GET_FD, REQ_READ, REQ_WRITE, REQ_SEEK, REQ_FLUSH, REQ_COPY, REQ_POPULATE_FILE_SET, REQ_FLUSH_DIR_CACHE, REQ_MOVE, REQ_REMOVE, }; /* This is the class that does most of the work. */ class ThreadedFileWorker: public RageWorkerThread { public: ThreadedFileWorker( RString sPath ); ~ThreadedFileWorker(); /* Threaded operations. If a file operation times out, the caller loses all access * to the file and should fail all future operations; this is because the thread * is still trying to finish the operation. The thread will clean up afterwards. */ RageFileBasic *Open( const RString &sPath, int iMode, int &iErr ); void Close( RageFileBasic *pFile ); int GetFileSize( RageFileBasic *&pFile ); int GetFD( RageFileBasic *&pFile ); int Seek( RageFileBasic *&pFile, int iPos, RString &sError ); int Read( RageFileBasic *&pFile, void *pBuf, int iSize, RString &sError ); int Write( RageFileBasic *&pFile, const void *pBuf, int iSize, RString &sError ); int Flush( RageFileBasic *&pFile, RString &sError ); RageFileBasic *Copy( RageFileBasic *&pFile, RString &sError ); bool FlushDirCache( const RString &sPath ); int Move( const RString &sOldPath, const RString &sNewPath ); int Remove( const RString &sPath ); bool PopulateFileSet( FileSet &fs, const RString &sPath ); protected: void HandleRequest( int iRequest ); void RequestTimedOut(); private: /* All requests: */ RageFileDriver *m_pChildDriver; /* List of files to delete: */ vector m_apDeletedFiles; RageMutex m_DeletedFilesLock; /* REQ_OPEN, REQ_POPULATE_FILE_SET, REQ_FLUSH_DIR_CACHE, REQ_REMOVE, REQ_MOVE: */ RString m_sRequestPath; /* in */ /* REQ_MOVE: */ RString m_sRequestPath2; /* in */ /* REQ_OPEN, REQ_COPY: */ RageFileBasic *m_pResultFile; /* out */ /* REQ_POPULATE_FILE_SET: */ FileSet m_ResultFileSet; /* out */ /* REQ_OPEN: */ int m_iRequestMode; /* in */ /* REQ_CLOSE, REQ_GET_FILE_SIZE, REQ_COPY: */ RageFileBasic *m_pRequestFile; /* in */ /* REQ_OPEN, REQ_GET_FILE_SIZE, REQ_READ, REQ_SEEK */ int m_iResultRequest; /* out */ /* REQ_READ, REQ_WRITE */ int m_iRequestSize; /* in */ RString m_sResultError; /* out */ /* REQ_SEEK */ int m_iRequestPos; /* in */ /* REQ_READ */ char *m_pResultBuffer; /* out */ /* REQ_WRITE */ char *m_pRequestBuffer; /* in */ }; static vector g_apWorkers; static RageMutex g_apWorkersMutex("WorkersMutex"); /* Set the timeout length, and reset the timer. */ void RageFileDriverTimeout::SetTimeout( float fSeconds ) { g_apWorkersMutex.Lock(); for( unsigned i = 0; i < g_apWorkers.size(); ++i ) g_apWorkers[i]->SetTimeout( fSeconds ); g_apWorkersMutex.Unlock(); } ThreadedFileWorker::ThreadedFileWorker( RString sPath ): RageWorkerThread( sPath ), m_DeletedFilesLock( sPath + "DeletedFilesLock" ) { /* Grab a reference to the child driver. We'll operate on it directly. */ m_pChildDriver = FILEMAN->GetFileDriver( sPath ); if( m_pChildDriver == nullptr ) WARN( ssprintf("ThreadedFileWorker: Mountpoint \"%s\" not found", sPath.c_str()) ); m_pResultFile = nullptr; m_pRequestFile = nullptr; m_pResultBuffer = nullptr; m_pRequestBuffer = nullptr; g_apWorkersMutex.Lock(); g_apWorkers.push_back( this ); g_apWorkersMutex.Unlock(); StartThread(); } ThreadedFileWorker::~ThreadedFileWorker() { StopThread(); if( m_pChildDriver != nullptr ) FILEMAN->ReleaseFileDriver( m_pChildDriver ); /* Unregister ourself. */ g_apWorkersMutex.Lock(); for( unsigned i = 0; i < g_apWorkers.size(); ++i ) { if( g_apWorkers[i] == this ) { g_apWorkers.erase( g_apWorkers.begin()+i ); break; } } g_apWorkersMutex.Unlock(); } void ThreadedFileWorker::HandleRequest( int iRequest ) { { m_DeletedFilesLock.Lock(); vector apDeletedFiles = m_apDeletedFiles; m_apDeletedFiles.clear(); m_DeletedFilesLock.Unlock(); for( unsigned i = 0; i < apDeletedFiles.size(); ++i ) delete apDeletedFiles[i]; } /* We have a request. */ switch( iRequest ) { case REQ_OPEN: ASSERT( m_pResultFile == nullptr ); ASSERT( !m_sRequestPath.empty() ); m_iResultRequest = 0; m_pResultFile = m_pChildDriver->Open( m_sRequestPath, m_iRequestMode, m_iResultRequest ); break; case REQ_CLOSE: ASSERT( m_pRequestFile != nullptr ); delete m_pRequestFile; /* Clear m_pRequestFile, so RequestTimedOut doesn't double-delete. */ m_pRequestFile = nullptr; break; case REQ_GET_FILE_SIZE: ASSERT( m_pRequestFile != nullptr ); m_iResultRequest = m_pRequestFile->GetFileSize(); break; case REQ_SEEK: ASSERT( m_pRequestFile != nullptr ); m_iResultRequest = m_pRequestFile->Seek( m_iRequestPos ); m_sResultError = m_pRequestFile->GetError(); break; case REQ_READ: ASSERT( m_pRequestFile != nullptr ); ASSERT( m_pResultBuffer != nullptr ); m_iResultRequest = m_pRequestFile->Read( m_pResultBuffer, m_iRequestSize ); m_sResultError = m_pRequestFile->GetError(); break; case REQ_WRITE: ASSERT( m_pRequestFile != nullptr ); ASSERT( m_pRequestBuffer != nullptr ); m_iResultRequest = m_pRequestFile->Write( m_pRequestBuffer, m_iRequestSize ); m_sResultError = m_pRequestFile->GetError(); break; case REQ_FLUSH: ASSERT( m_pRequestFile != nullptr ); m_iResultRequest = m_pRequestFile->Flush(); m_sResultError = m_pRequestFile->GetError(); break; case REQ_COPY: ASSERT( m_pRequestFile != nullptr ); m_pResultFile = m_pRequestFile->Copy(); break; case REQ_POPULATE_FILE_SET: ASSERT( !m_sRequestPath.empty() ); m_ResultFileSet = FileSet(); m_pChildDriver->FDB->GetFileSetCopy( m_sRequestPath, m_ResultFileSet ); break; case REQ_FLUSH_DIR_CACHE: m_pChildDriver->FlushDirCache( m_sRequestPath ); break; case REQ_REMOVE: ASSERT( !m_sRequestPath.empty() ); m_iResultRequest = m_pChildDriver->Remove( m_sRequestPath )? 0:-1; break; case REQ_MOVE: ASSERT( !m_sRequestPath.empty() ); ASSERT( !m_sRequestPath2.empty() ); m_iResultRequest = m_pChildDriver->Move( m_sRequestPath, m_sRequestPath2 )? 0:-1; break; default: FAIL_M( ssprintf("%i", iRequest) ); } } void ThreadedFileWorker::RequestTimedOut() { /* The event timed out. Clean up any residue from the last action. */ SAFE_DELETE( m_pRequestFile ); SAFE_DELETE( m_pResultFile ); SAFE_DELETE_ARRAY( m_pRequestBuffer ); SAFE_DELETE_ARRAY( m_pResultBuffer ); } RageFileBasic *ThreadedFileWorker::Open( const RString &sPath, int iMode, int &iErr ) { if( m_pChildDriver == nullptr ) { iErr = ENODEV; return nullptr; } /* If we're currently in a timed-out state, fail. */ if( IsTimedOut() ) { iErr = EFAULT; /* Win32 has no ETIMEDOUT */ return nullptr; } m_sRequestPath = sPath; m_iRequestMode = iMode; if( !DoRequest(REQ_OPEN) ) { LOG->Trace( "Open(%s) timed out", sPath.c_str() ); iErr = EFAULT; /* Win32 has no ETIMEDOUT */ return nullptr; } iErr = m_iResultRequest; RageFileBasic *pRet = m_pResultFile; m_pResultFile = nullptr; return pRet; } void ThreadedFileWorker::Close( RageFileBasic *pFile ) { ASSERT( m_pChildDriver != nullptr ); /* how did you get a file to begin with? */ if( pFile == nullptr ) return; if( !IsTimedOut() ) { /* If we're not in a timed-out state, try to wait for the deletion to complete * before continuing. */ m_pRequestFile = pFile; if( !DoRequest(REQ_CLOSE) ) return; m_pRequestFile = nullptr; } else { /* Delete the file when the timeout completes. */ m_DeletedFilesLock.Lock(); m_apDeletedFiles.push_back( pFile ); m_DeletedFilesLock.Unlock(); } } int ThreadedFileWorker::GetFileSize( RageFileBasic *&pFile ) { ASSERT( m_pChildDriver != nullptr ); /* how did you get a file to begin with? */ /* If we're currently in a timed-out state, fail. */ if( IsTimedOut() ) { this->Close( pFile ); pFile = nullptr; } if( pFile == nullptr ) return -1; m_pRequestFile = pFile; if( !DoRequest(REQ_GET_FILE_SIZE) ) { /* If we time out, we can no longer access pFile. */ pFile = nullptr; return -1; } m_pRequestFile = nullptr; return m_iResultRequest; } int ThreadedFileWorker::GetFD( RageFileBasic *&pFile ) { ASSERT( m_pChildDriver != nullptr ); /* how did you get a file to begin with? */ /* If we're currently in a timed-out state, fail. */ if( IsTimedOut() ) { this->Close( pFile ); pFile = nullptr; } if( pFile == nullptr ) return -1; m_pRequestFile = pFile; if( !DoRequest(REQ_GET_FD) ) { /* If we time out, we can no longer access pFile. */ pFile = nullptr; return -1; } m_pRequestFile = nullptr; return m_iResultRequest; } int ThreadedFileWorker::Seek( RageFileBasic *&pFile, int iPos, RString &sError ) { ASSERT( m_pChildDriver != nullptr ); /* how did you get a file to begin with? */ /* If we're currently in a timed-out state, fail. */ if( IsTimedOut() ) { this->Close( pFile ); pFile = nullptr; } if( pFile == nullptr ) { sError = "Operation timed out"; return -1; } m_pRequestFile = pFile; m_iRequestPos = iPos; /* in */ if( !DoRequest(REQ_SEEK) ) { /* If we time out, we can no longer access pFile. */ sError = "Operation timed out"; pFile = nullptr; return -1; } if( m_iResultRequest == -1 ) sError = m_sResultError; m_pRequestFile = nullptr; return m_iResultRequest; } int ThreadedFileWorker::Read( RageFileBasic *&pFile, void *pBuf, int iSize, RString &sError ) { ASSERT( m_pChildDriver != nullptr ); /* how did you get a file to begin with? */ /* If we're currently in a timed-out state, fail. */ if( IsTimedOut() ) { this->Close( pFile ); pFile = nullptr; } if( pFile == nullptr ) { sError = "Operation timed out"; return -1; } m_pRequestFile = pFile; m_iRequestSize = iSize; m_pResultBuffer = new char[iSize]; if( !DoRequest(REQ_READ) ) { /* If we time out, we can no longer access pFile. */ sError = "Operation timed out"; pFile = nullptr; return -1; } int iGot = m_iResultRequest; if( iGot == -1 ) sError = m_sResultError; else memcpy( pBuf, m_pResultBuffer, iGot ); m_pRequestFile = nullptr; delete [] m_pResultBuffer; m_pResultBuffer = nullptr; return iGot; } int ThreadedFileWorker::Write( RageFileBasic *&pFile, const void *pBuf, int iSize, RString &sError ) { ASSERT( m_pChildDriver != nullptr ); /* how did you get a file to begin with? */ /* If we're currently in a timed-out state, fail. */ if( IsTimedOut() ) { this->Close( pFile ); pFile = nullptr; } if( pFile == nullptr ) { sError = "Operation timed out"; return -1; } m_pRequestFile = pFile; m_iRequestSize = iSize; m_pRequestBuffer = new char[iSize]; memcpy( m_pRequestBuffer, pBuf, iSize ); if( !DoRequest(REQ_WRITE) ) { /* If we time out, we can no longer access pFile. */ sError = "Operation timed out"; pFile = nullptr; return -1; } int iGot = m_iResultRequest; if( m_iResultRequest == -1 ) sError = m_sResultError; m_pRequestFile = nullptr; delete [] m_pRequestBuffer; m_pRequestBuffer = nullptr; return iGot; } int ThreadedFileWorker::Flush( RageFileBasic *&pFile, RString &sError ) { ASSERT( m_pChildDriver != nullptr ); /* how did you get a file to begin with? */ /* If we're currently in a timed-out state, fail. */ if( IsTimedOut() ) { this->Close( pFile ); pFile = nullptr; } if( pFile == nullptr ) { sError = "Operation timed out"; return -1; } m_pRequestFile = pFile; if( !DoRequest(REQ_FLUSH) ) { /* If we time out, we can no longer access pFile. */ sError = "Operation timed out"; pFile = nullptr; return -1; } if( m_iResultRequest == -1 ) sError = m_sResultError; m_pRequestFile = nullptr; return m_iResultRequest; } RageFileBasic *ThreadedFileWorker::Copy( RageFileBasic *&pFile, RString &sError ) { ASSERT( m_pChildDriver != nullptr ); /* how did you get a file to begin with? */ /* If we're currently in a timed-out state, fail. */ if( IsTimedOut() ) { this->Close( pFile ); pFile = nullptr; } if( pFile == nullptr ) { sError = "Operation timed out"; return nullptr; } m_pRequestFile = pFile; if( !DoRequest(REQ_COPY) ) { /* If we time out, we can no longer access pFile. */ sError = "Operation timed out"; pFile = nullptr; return nullptr; } RageFileBasic *pRet = m_pResultFile; m_pRequestFile = nullptr; m_pResultFile = nullptr; return pRet; } bool ThreadedFileWorker::PopulateFileSet( FileSet &fs, const RString &sPath ) { if( m_pChildDriver == nullptr ) return false; /* If we're currently in a timed-out state, fail. */ if( IsTimedOut() ) return false; /* Fill in a different FileSet; copy the results in on success. */ m_sRequestPath = sPath; /* Kick off the worker thread, and wait for it to finish. */ if( !DoRequest(REQ_POPULATE_FILE_SET) ) { LOG->Trace( "PopulateFileSet(%s) timed out", sPath.c_str() ); return false; } fs = m_ResultFileSet; return true; } int ThreadedFileWorker::Move( const RString &sOldPath, const RString &sNewPath ) { ASSERT( m_pChildDriver != nullptr ); /* how did you get a file to begin with? */ /* If we're currently in a timed-out state, fail. */ if( IsTimedOut() ) return -1; m_sRequestPath = sOldPath; m_sRequestPath2 = sNewPath; if( !DoRequest(REQ_MOVE) ) { /* If we time out, we can no longer access pFile. */ return -1; } return m_iResultRequest; } int ThreadedFileWorker::Remove( const RString &sPath ) { ASSERT( m_pChildDriver != nullptr ); /* how did you get a file to begin with? */ /* If we're currently in a timed-out state, fail. */ if( IsTimedOut() ) return -1; m_sRequestPath = sPath; if( !DoRequest(REQ_REMOVE) ) { /* If we time out, we can no longer access pFile. */ return -1; } return m_iResultRequest; } bool ThreadedFileWorker::FlushDirCache( const RString &sPath ) { /* FlushDirCache() is often called globally, on all drivers, which means it's called with * no timeout. Temporarily enable a timeout if needed. */ bool bTimeoutEnabled = TimeoutEnabled(); if( !bTimeoutEnabled ) SetTimeout(1); if( m_pChildDriver == nullptr ) return false; /* If we're currently in a timed-out state, fail. */ if( IsTimedOut() ) return false; m_sRequestPath = sPath; /* Kick off the worker thread, and wait for it to finish. */ if( !DoRequest(REQ_FLUSH_DIR_CACHE) ) { if( !bTimeoutEnabled ) SetTimeout(-1); LOG->Trace( "FlushDirCache(%s) timed out", sPath.c_str() ); return false; } if( !bTimeoutEnabled ) SetTimeout(-1); return true; } class RageFileObjTimeout: public RageFileObj { public: /* pFile will be freed by passing it to pWorker. */ RageFileObjTimeout( ThreadedFileWorker *pWorker, RageFileBasic *pFile, int iSize, int iMode ) { m_pWorker = pWorker; m_pFile = pFile; m_iFileSize = iSize; m_iMode = iMode; /* We have a lot of overhead per read and write operation, since we send * commands to the worker thread. Buffer these operations. */ if( iMode & RageFile::WRITE ) EnableWriteBuffering(); if( iMode & RageFile::READ ) EnableReadBuffering(); } ~RageFileObjTimeout() { if( m_pFile != nullptr ) { Flush(); m_pWorker->Close( m_pFile ); } } int GetFileSize() const { return m_iFileSize; } int GetFD() { RString sError; int iRet = m_pWorker->GetFD( m_pFile ); if( m_pFile == nullptr ) { SetError( "Operation timed out" ); return -1; } if( iRet == -1 ) SetError( sError ); return iRet; } RageFileBasic *Copy() const { RString sError; RageFileBasic *pCopy = m_pWorker->Copy( m_pFile, sError ); if( m_pFile == nullptr ) { // SetError( "Operation timed out" ); return nullptr; } if( pCopy == nullptr ) { // SetError( sError ); return nullptr; } return new RageFileObjTimeout( m_pWorker, pCopy, m_iFileSize, m_iMode ); } protected: int SeekInternal( int iPos ) { RString sError; int iRet = m_pWorker->Seek( m_pFile, iPos, sError ); if( m_pFile == nullptr ) { SetError( "Operation timed out" ); return -1; } if( iRet == -1 ) SetError( sError ); return iRet; } int ReadInternal( void *pBuffer, size_t iBytes ) { RString sError; int iRet = m_pWorker->Read( m_pFile, pBuffer, iBytes, sError ); if( m_pFile == nullptr ) { SetError( "Operation timed out" ); return -1; } if( iRet == -1 ) SetError( sError ); return iRet; } int WriteInternal( const void *pBuffer, size_t iBytes ) { RString sError; int iRet = m_pWorker->Write( m_pFile, pBuffer, iBytes, sError ); if( m_pFile == nullptr ) { SetError( "Operation timed out" ); return -1; } if( iRet == -1 ) SetError( sError ); return iRet; } int FlushInternal() { RString sError; int iRet = m_pWorker->Flush( m_pFile, sError ); if( m_pFile == nullptr ) { SetError( "Operation timed out" ); return -1; } if( iRet == -1 ) SetError( sError ); return iRet; } /* Mutable because the const operation Copy() timing out results in the original * object no longer being available. */ mutable RageFileBasic *m_pFile; ThreadedFileWorker *m_pWorker; /* GetFileSize isn't allowed to fail, so cache the file size on load. */ int m_iFileSize; //cache filemode int m_iMode; }; /* This FilenameDB runs PopulateFileSet in the worker thread. */ class TimedFilenameDB: public FilenameDB { public: TimedFilenameDB() { ExpireSeconds = -1; m_pWorker = nullptr; } void SetWorker( ThreadedFileWorker *pWorker ) { ASSERT( pWorker != nullptr ); m_pWorker = pWorker; } void PopulateFileSet( FileSet &fs, const RString &sPath ) { ASSERT( m_pWorker != nullptr ); m_pWorker->PopulateFileSet( fs, sPath ); } private: ThreadedFileWorker *m_pWorker; }; RageFileDriverTimeout::RageFileDriverTimeout( const RString &sPath ): RageFileDriver( new TimedFilenameDB() ) { m_pWorker = new ThreadedFileWorker( sPath ); ((TimedFilenameDB *) FDB)->SetWorker( m_pWorker ); } RageFileBasic *RageFileDriverTimeout::Open( const RString &sPath, int iMode, int &iErr ) { RageFileBasic *pChildFile = m_pWorker->Open( sPath, iMode, iErr ); if( pChildFile == nullptr ) return nullptr; /* RageBasicFile::GetFileSize isn't allowed to fail, but we are; grab the file * size now and store it. */ int iSize = 0; if( iMode & RageFile::READ ) { iSize = m_pWorker->GetFileSize( pChildFile ); if( iSize == -1 ) { /* When m_pWorker->GetFileSize fails, it takes ownership of pChildFile. */ ASSERT( pChildFile == nullptr ); iErr = EFAULT; return nullptr; } } return new RageFileObjTimeout( m_pWorker, pChildFile, iSize, iMode ); } void RageFileDriverTimeout::FlushDirCache( const RString &sPath ) { RageFileDriver::FlushDirCache( sPath ); m_pWorker->FlushDirCache( sPath ); } bool RageFileDriverTimeout::Move( const RString &sOldPath, const RString &sNewPath ) { int iRet = m_pWorker->Move( sOldPath, sNewPath ); if( iRet == -1 ) { WARN( ssprintf("RageFileDriverTimeout::Move(%s,%s) failed", sOldPath.c_str(), sNewPath.c_str()) ); return false; } return true; } bool RageFileDriverTimeout::Remove( const RString &sPath ) { int iRet = m_pWorker->Remove( sPath ); if( iRet == -1 ) { WARN( ssprintf("RageFileDriverTimeout::Remove(%s) failed", sPath.c_str()) ); return false; } return true; } RageFileDriverTimeout::~RageFileDriverTimeout() { delete m_pWorker; } static struct FileDriverEntry_Timeout: public FileDriverEntry { FileDriverEntry_Timeout(): FileDriverEntry( "TIMEOUT" ) { } RageFileDriver *Create( const RString &sRoot ) const { return new RageFileDriverTimeout( sRoot ); } } const g_RegisterDriver; /* * Copyright (c) 2005 * 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, and/or sell copies of the Software, and to permit persons to * whom the Software is furnished to do so, provided that the above * copyright notice(s) and this permission notice appear in all copies of * the Software and that both the above copyright notice(s) and this * permission notice appear in supporting documentation. * * 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 OF * THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS * INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR 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. */ #include "catch.hpp" #include "emb/net/async_socket_server.hpp" #include "emb/net/uds_client_socket.hpp" #include "emb/net/uds_server_socket.hpp" #include #include TEST_CASE("a test", "[component][scratch]") { constexpr auto socket_path = "/tmp/test.socket"; emb::net::uds_server_socket srv_socket{socket_path}; emb::net::async_socket_server async{srv_socket}; std::thread th { [&] { std::array arr{'T', 'e', 's', 't', 0}; async.on_accept = [&](emb::net::async_core::node_id id) { async.write( id, emb::contiguous_buffer(arr), [] {} ); }; async.run_once(); async.run_once(); } }; emb::net::uds_client_socket cli{socket_path}; auto [size, data] = cli.read_some<64>(); std::cout << data.data() << std::endl; th.join(); } // Copyright 2017 // // 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 "linux_file_impl.hpp" #include #include #include #include #include #include #include #include #include #include #include namespace memoria { namespace reactor { BufferedFileImpl::BufferedFileImpl(filesystem::path file_path, FileFlags flags, FileMode mode): FileImplBase(file_path) { int errno0 = 0; std::tie(fd_, errno0) = engine().run_in_thread_pool([&]{ auto fd = ::open(file_path.c_str(), (int)flags, (mode_t)mode); return std::make_tuple(fd, errno); }); if (fd_ < 0) { MMA_THROW(SystemException(errno0)) << format_ex("Can't open file {}", file_path); } } BufferedFileImpl::~BufferedFileImpl() noexcept { if (!closed_) { ::close(fd_); } } void BufferedFileImpl::close() { if ((!closed_) && (::close(fd_) < 0)) { MMA_THROW(SystemException()) << format_ex("Can't close file {}", path_); } closed_ = true; } uint64_t BufferedFileImpl::seek(uint64_t position) { off64_t res; int errno0; std::tie(res, errno0) = engine().run_in_thread_pool([&]{ off64_t r = lseek64(fd_, position, SEEK_SET); return std::make_tuple(r, errno); }); if (res >= 0) { return res; } else { MMA_THROW(SystemException(errno0)) << format_ex("Can't seek into the file {}", path_); } } uint64_t BufferedFileImpl::fpos() { off64_t res; int errno0; std::tie(res, errno0) = engine().run_in_thread_pool([&]{ off64_t r = lseek64(fd_, 0, SEEK_CUR); return std::make_tuple(r, errno); }); if (res >= 0) { return res; } else { MMA_THROW(SystemException(errno0)) << format_ex("Can't seek into the file {}", path_); } } size_t BufferedFileImpl::read(uint8_t* buffer, uint64_t offset, size_t size) { off64_t res; int errno0; std::tie(res, errno0) = engine().run_in_thread_pool([&]{ off64_t r = lseek64(fd_, offset, SEEK_SET); if (r >= 0) { r = ::read(fd_, buffer, size); } return std::make_tuple(r, errno); }); if (res >= 0) { return res; } else { MMA_THROW(SystemException(errno0)) << format_ex("Can't read from file {}", path_); } } size_t BufferedFileImpl::read(uint8_t* buffer, size_t size) { off64_t res; int errno0; std::tie(res, errno0) = engine().run_in_thread_pool([&]{ off64_t r = ::read(fd_, buffer, size); return std::make_tuple(r, errno); }); if (res >= 0) { return res; } else { MMA_THROW(SystemException(errno0)) << format_ex("Can't read from file {}", path_); } } size_t BufferedFileImpl::write(const uint8_t* buffer, uint64_t offset, size_t size) { off64_t res; int errno0 = 0; std::tie(res, errno0) = engine().run_in_thread_pool([&]{ off64_t r = lseek64(fd_, offset, SEEK_SET); if (r >= 0) { r = ::write(fd_, buffer, size); } return std::make_tuple(r, errno); }); if (res >= 0) { return res; } else { MMA_THROW(SystemException(errno0)) << format_ex("Can't write to file {}", path_); } } size_t BufferedFileImpl::write(const uint8_t* buffer, size_t size) { off64_t res; int errno0 = 0; std::tie(res, errno0) = engine().run_in_thread_pool([&]{ off64_t r = ::write(fd_, buffer, size); return std::make_tuple(r, errno); }); if (res >= 0) { return res; } else { MMA_THROW(SystemException(errno0)) << format_ex("Can't write to file {}", path_); } } void BufferedFileImpl::fsync() { int res; int errno0 = 0; std::tie(res, errno) = engine().run_in_thread_pool([&]{ int r = ::fsync(fd_); return std::make_tuple(r, errno); }); if (res < 0) { MMA_THROW(SystemException(errno0)) << format_ex("Can't fsync file {}", path_); } } void BufferedFileImpl::fdsync() { int res; int errno0 = 0; std::tie(res, errno) = engine().run_in_thread_pool([&]{ int r = ::fdatasync(fd_); return std::make_tuple(r, errno); }); if (res < 0) { MMA_THROW(SystemException(errno0)) << format_ex("Can't fsync file {}", path_); } } File open_buffered_file(filesystem::path file_path, FileFlags flags, FileMode mode) { return MakeLocalShared(file_path, flags, mode); } }} libtrack/platform/arm/libother_init.cpp /* * libc_init.cpp * Derived from bionic/libc_init_* from the Android Open Source Project * */ #include #include #include #include #include #include #include #include #include #include #define _REALLY_INCLUDE_SYS__SYSTEM_PROPERTIES_H_ #include #include "wrap_lib.h" void *real_libc_dso = NULL; extern const char *progname; /* ------------------------------------------------------------------- * * From bionic/libc_init_dynamic.cpp * */ __attribute__((constructor)) static void __libc_preinit() { init_libc_iface(&libc, LIBC_PATH); } skia/docs/examples/IRect_width64.cpp // 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=63977f97999bbd6eecfdcc7575d75492 REG_FIDDLE(IRect_width64, 256, 256, true, 0) { void draw(SkCanvas* canvas) { SkIRect large = { -2147483647, 1, 2147483644, 2 }; SkDebugf("width: %d width64: %lld\n", large.width(), large.width64()); } } // END FIDDLE namespace lift { template auto EventLoop::StartRequests( Container requests) -> void { // We'll prepare now since it won't block the event loop thread. // Since this might not be cheap do it outside the lock for (auto& request : requests) { request->prepareForPerform(); } // Lock scope { std::lock_guard guard(m_pending_requests_lock); for (auto& request : requests) { m_pending_requests.emplace_back(std::move(request)); } } uv_async_send(&m_async); } } // lift src/dawn/CodeGen/CodeGen.cpp #include "dawn/CodeGen/CodeGen.h" #include "dawn/CodeGen/StencilFunctionAsBCGenerator.h" namespace dawn { namespace codegen { size_t CodeGen::getVerticalTmpHaloSize(iir::Stencil const& stencil) { boost::optional tmpInterval = stencil.getEnclosingIntervalTemporaries(); return (tmpInterval.is_initialized()) ? std::max(tmpInterval->overEnd(), tmpInterval->belowBegin()) : 0; } size_t CodeGen::getVerticalTmpHaloSizeForMultipleStencils( const std::vector>& stencils) const { boost::optional fullIntervals; for(const auto& stencil : stencils) { auto tmpInterval = stencil->getEnclosingIntervalTemporaries(); if(tmpInterval.is_initialized()) { if(!fullIntervals.is_initialized()) fullIntervals = tmpInterval; else fullIntervals->merge((*tmpInterval)); } } return (fullIntervals.is_initialized()) ? std::max(fullIntervals->overEnd(), fullIntervals->belowBegin()) : 0; } std::string CodeGen::generateGlobals(std::shared_ptr const& sir, std::string namespace_) const { const auto& globalsMap = *(sir->GlobalVariableMap); if(globalsMap.empty()) return ""; std::stringstream ss; Namespace cudaNamespace(namespace_, ss); Struct GlobalsStruct("globals", ss); for(const auto& globalsPair : globalsMap) { sir::Value& value = *globalsPair.second; if(value.isConstexpr()) { continue; } std::string Name = globalsPair.first; std::string Type = sir::Value::typeToString(value.getType()); GlobalsStruct.addMember(Type, Name); } auto ctr = GlobalsStruct.addConstructor(); for(const auto& globalsPair : globalsMap) { sir::Value& value = *globalsPair.second; if(value.isConstexpr()) { continue; } std::string Name = globalsPair.first; if(!value.empty()) { ctr.addInit(Name + "(" + value.toString() + ")"); } } ctr.startBody(); ctr.commit(); GlobalsStruct.commit(); cudaNamespace.commit(); return ss.str(); } void CodeGen::generateGlobalsAPI(const iir::StencilInstantiation& stencilInstantiation, Class& stencilWrapperClass, const sir::GlobalVariableMap& globalsMap, const CodeGenProperties& codeGenProperties) const { stencilWrapperClass.addComment("Access-wrapper for globally defined variables"); for(const auto& globalProp : globalsMap) { auto globalValue = globalProp.second; if(globalValue->isConstexpr()) { continue; } auto getter = stencilWrapperClass.addMemberFunction( sir::Value::typeToString(globalValue->getType()), "get_" + globalProp.first); getter.finishArgs(); getter.addStatement("return m_globals." + globalProp.first); getter.commit(); auto setter = stencilWrapperClass.addMemberFunction("void", "set_" + globalProp.first); setter.addArg(std::string(sir::Value::typeToString(globalValue->getType())) + " " + globalProp.first); setter.finishArgs(); setter.addStatement("m_globals." + globalProp.first + "=" + globalProp.first); setter.commit(); } } void CodeGen::generateBoundaryConditionFunctions( Class& stencilWrapperClass, const std::shared_ptr stencilInstantiation) const { // Functions for boundary conditions const auto& metadata = stencilInstantiation->getMetaData(); for(auto usedBoundaryCondition : metadata.getFieldNameToBCMap()) { for(const auto& sf : stencilInstantiation->getIIR()->getStencilFunctions()) { if(sf->Name == usedBoundaryCondition.second->getFunctor()) { Structure BoundaryCondition = stencilWrapperClass.addStruct(Twine(sf->Name)); std::string templatefunctions = "typename Direction "; std::string functionargs = "Direction "; // A templated datafield for every function argument for(int i = 0; i < usedBoundaryCondition.second->getFields().size(); i++) { templatefunctions += dawn::format(",typename DataField_%i", i); functionargs += dawn::format(", DataField_%i &data_field_%i", i, i); } functionargs += ", int i , int j, int k"; auto BC = BoundaryCondition.addMemberFunction( Twine("GT_FUNCTION void"), Twine("operator()"), Twine(templatefunctions)); BC.isConst(true); BC.addArg(functionargs); BC.startBody(); StencilFunctionAsBCGenerator reader(stencilInstantiation->getMetaData(), sf); sf->Asts[0]->accept(reader); std::string output = reader.getCodeAndResetStream(); BC << output; BC.commit(); break; } } } } void CodeGen::generateBCHeaders(std::vector& ppDefines) const { auto hasBCFold = [](bool res, const std::pair>& si) { return res || si.second->getMetaData().hasBC(); }; if(std::accumulate(context_->getStencilInstantiationMap().begin(), context_->getStencilInstantiationMap().end(), false, hasBCFold)) { ppDefines.push_back("#include \n"); } } CodeGenProperties CodeGen::computeCodeGenProperties(const iir::StencilInstantiation* stencilInstantiation) const { CodeGenProperties codeGenProperties; const auto& metadata = stencilInstantiation->getMetaData(); int idx = 0; std::unordered_set generatedStencilFun; for(const auto& stencilFun : metadata.getStencilFunctionInstantiations()) { std::string stencilFunName = iir::StencilFunctionInstantiation::makeCodeGenName(*stencilFun); if(generatedStencilFun.emplace(stencilFunName).second) { auto stencilProperties = codeGenProperties.insertStencil(StencilContext::SC_StencilFunction, idx, stencilFunName); auto& paramNameToType = stencilProperties->paramNameToType_; // Field declaration const auto& fields = stencilFun->getCalleeFields(); // list of template names of the stencil function declaration std::vector stencilFnTemplates(fields.size()); int n = 0; std::generate(stencilFnTemplates.begin(), stencilFnTemplates.end(), [n]() mutable { return "StorageType" + std::to_string(n++); }); int m = 0; for(const auto& field : fields) { std::string paramName = stencilFun->getOriginalNameFromCallerAccessID(field.getAccessID()); paramNameToType.emplace(paramName, stencilFnTemplates[m++]); } } idx++; } for(const auto& stencil : stencilInstantiation->getIIR()->getChildren()) { std::string stencilName = "stencil_" + std::to_string(stencil->getStencilID()); auto stencilProperties = codeGenProperties.insertStencil(StencilContext::SC_Stencil, stencil->getStencilID(), stencilName); auto& paramNameToType = stencilProperties->paramNameToType_; // fields used in the stencil const auto& StencilFields = stencil->getFields(); auto nonTempFields = makeRange( StencilFields, std::function const&)>( [](std::pair const& p) { return !p.second.IsTemporary; })); auto tempFields = makeRange( StencilFields, std::function const&)>( [](std::pair const& p) { return p.second.IsTemporary; })); // list of template for storages used in the stencil class std::vector StencilTemplates(nonTempFields.size()); int cnt = 0; std::generate(StencilTemplates.begin(), StencilTemplates.end(), [cnt]() mutable { return "StorageType" + std::to_string(cnt++); }); for(auto fieldIt : nonTempFields) { paramNameToType.emplace((*fieldIt).second.Name, getStorageType((*fieldIt).second.Dimensions)); } for(auto fieldIt : tempFields) { paramNameToType.emplace((*fieldIt).second.Name, c_gtc().str() + "storage_t"); } } int i = 0; for(const auto& fieldID : metadata.getAccessesOfType()) { codeGenProperties.insertParam(i, metadata.getFieldNameFromAccessID(fieldID), getStorageType(metadata.getFieldDimensionsMask(fieldID))); ++i; } for(auto usedBoundaryCondition : metadata.getFieldNameToBCMap()) { for(const auto& field : usedBoundaryCondition.second->getFields()) { codeGenProperties.setParamBC(field->Name); } } for(int accessID : metadata.getAccessesOfType()) { codeGenProperties.insertAllocateField(metadata.getFieldNameFromAccessID(accessID)); } return codeGenProperties; } std::string CodeGen::getStorageType(Array3i dimensions) { std::string storageType = "storage_"; storageType += dimensions[0] ? "i" : ""; storageType += dimensions[1] ? "j" : ""; storageType += dimensions[2] ? "k" : ""; storageType += "_t"; return storageType; } std::string CodeGen::getStorageType(const sir::Field& field) { return getStorageType(field.fieldDimensions); } std::string CodeGen::getStorageType(const iir::Stencil::FieldInfo& field) { return getStorageType(field.Dimensions); } void CodeGen::addTempStorageTypedef(Structure& stencilClass, iir::Stencil const& stencil) const { stencilClass.addTypeDef("tmp_halo_t") .addType("gridtools::halo< GRIDTOOLS_CLANG_HALO_EXTEND, GRIDTOOLS_CLANG_HALO_EXTEND, " + std::to_string(getVerticalTmpHaloSize(stencil)) + ">"); stencilClass.addTypeDef(tmpMetadataTypename_) .addType("storage_traits_t::storage_info_t< 0, 3, tmp_halo_t >"); stencilClass.addTypeDef(tmpStorageTypename_) .addType("storage_traits_t::data_store_t< float_type, " + tmpMetadataTypename_ + ">"); } void CodeGen::addTmpStorageDeclaration( Structure& stencilClass, IndexRange>& tempFields) const { if(!(tempFields.empty())) { stencilClass.addMember(tmpMetadataTypename_, tmpMetadataName_); for(auto field : tempFields) { stencilClass.addMember(tmpStorageTypename_, "m_" + (*field).second.Name); } } } void CodeGen::addTmpStorageInit( MemberFunction& ctr, iir::Stencil const& stencil, IndexRange>& tempFields) const { if(!(tempFields.empty())) { ctr.addInit(tmpMetadataName_ + "(dom_.isize(), dom_.jsize(), dom_.ksize() + 2*" + std::to_string(getVerticalTmpHaloSize(stencil)) + ")"); for(auto fieldIt : tempFields) { ctr.addInit("m_" + (*fieldIt).second.Name + "(" + tmpMetadataName_ + ")"); } } } void CodeGen::addTmpStorageInitStencilWrapperCtr( MemberFunction& ctr, const std::vector>& stencils, const std::vector& tempFields) const { if(!(tempFields.empty())) { auto verticalExtent = getVerticalTmpHaloSizeForMultipleStencils(stencils); ctr.addInit(bigWrapperMetadata_ + "(dom.isize(), dom.jsize(), dom.ksize() /*+ 2 *" + std::to_string(verticalExtent) + "*/ + 1)"); for(auto fieldName : tempFields) { ctr.addInit("m_" + fieldName + " (" + bigWrapperMetadata_ + ", \"" + fieldName + "\")"); } } } void CodeGen::addBCFieldInitStencilWrapperCtr(MemberFunction& ctr, const CodeGenProperties& codeGenProperties) const { // Initialize storages that require boundary conditions for(const auto& param : codeGenProperties.getParameterNameToType()) { if(!codeGenProperties.isParamBC(param.first)) continue; ctr.addInit("m_" + param.first + "(" + param.first + ")"); } } void CodeGen::generateBCFieldMembers( Class& stencilWrapperClass, const std::shared_ptr stencilInstantiation, const CodeGenProperties& codeGenProperties) const { const auto& metadata = stencilInstantiation->getMetaData(); if(metadata.hasBC()) stencilWrapperClass.addComment("Fields that require Boundary Conditions"); // add all fields that require a boundary condition as members since they need to be called from // this class and not from individual stencils for(const auto& field : codeGenProperties.getParameterNameToType()) { if(!codeGenProperties.isParamBC(field.first)) continue; stencilWrapperClass.addMember(field.second, "m_" + field.first); } } void CodeGen::addMplIfdefs(std::vector& ppDefines, int mplContainerMaxSize, int MaxHaloPoints) const { auto makeIfNotDefined = [](std::string define, int value) { return "#ifndef " + define + "\n #define " + define + " " + std::to_string(value) + "\n#endif"; }; auto makeIfNotDefinedString = [](std::string define, std::string value) { return "#ifndef " + define + "\n #define " + define + " " + value + "\n#endif"; }; ppDefines.push_back(makeIfNotDefined("BOOST_RESULT_OF_USE_TR1", 1)); ppDefines.push_back(makeIfNotDefined("BOOST_NO_CXX11_DECLTYPE", 1)); ppDefines.push_back(makeIfNotDefined("GRIDTOOLS_CLANG_HALO_EXTEND", MaxHaloPoints)); ppDefines.push_back(makeIfNotDefined("BOOST_PP_VARIADICS", 1)); ppDefines.push_back(makeIfNotDefined("BOOST_FUSION_DONT_USE_PREPROCESSED_FILES", 1)); ppDefines.push_back(makeIfNotDefined("BOOST_MPL_CFG_NO_PREPROCESSED_HEADERS", 1)); ppDefines.push_back(makeIfNotDefined("GT_VECTOR_LIMIT_SIZE", mplContainerMaxSize)); ppDefines.push_back( makeIfNotDefinedString("BOOST_FUSION_INVOKE_MAX_ARITY", "GT_VECTOR_LIMIT_SIZE")); ppDefines.push_back(makeIfNotDefinedString("FUSION_MAX_VECTOR_SIZE", "GT_VECTOR_LIMIT_SIZE")); ppDefines.push_back(makeIfNotDefinedString("FUSION_MAX_MAP_SIZE", "GT_VECTOR_LIMIT_SIZE")); ppDefines.push_back( makeIfNotDefinedString("BOOST_MPL_LIMIT_VECTOR_SIZE", "GT_VECTOR_LIMIT_SIZE")); } } // namespace codegen } // namespace dawn include/glcxx/Buffer.hpp /** * @file * * C++ wrapper for an OpenGL buffer object. */ #ifndef GLCXX_BUFFER_HPP #define GLCXX_BUFFER_HPP #include "glcxx/gl.hpp" #include #include namespace glcxx { /** * C++ wrapper for an OpenGL buffer object. */ class Buffer { public: /** * Construct and allocate an OpenGL buffer object. */ Buffer(); /** * Destroy the buffer object. */ ~Buffer(); /** * Set the buffer's data, target, and usage. * * @param target Buffer target (e.g. GL_ARRAY_BUFFER). * @param usage Buffer usage hint (e.g. GL_STATIC_DRAW). * @param ptr Pointer to data to load in buffer. * @param size Length of the data to load in buffer. */ void set_buffer_data(GLenum target, GLenum usage, const void * ptr, size_t size); /** * Set the buffer's data, target, and usage. * * @param target Buffer target (e.g. GL_ARRAY_BUFFER). * @param usage Buffer usage hint (e.g. GL_STATIC_DRAW). * @param data Data to load in buffer. */ void set_buffer_data(GLenum target, GLenum usage, std::initializer_list data) { set_buffer_data(target, usage, &*data.begin(), (uintptr_t)&*data.end() - (uintptr_t)&*data.begin()); } /** * Set the buffer's data, target, and usage. * * @param target Buffer target (e.g. GL_ARRAY_BUFFER). * @param usage Buffer usage hint (e.g. GL_STATIC_DRAW). * @param data Data to load in buffer. */ void set_buffer_data_d(GLenum target, GLenum usage, std::initializer_list data) { set_buffer_data(target, usage, &*data.begin(), (uintptr_t)&*data.end() - (uintptr_t)&*data.begin()); } /** * Get the buffer object's ID. * * @return The buffer object's ID. */ GLuint id() const { return m_id; } /** * Bind the buffer object. */ void bind() const { glBindBuffer(m_target, m_id); } /** * Factory method to construct a Buffer. * * This method does not fill the buffer with any data. * * @return std::shared_ptr to the created Buffer. */ static std::shared_ptr create() { return std::make_shared(); } /** * Factory method to construct a Buffer and fill it with data. * * @param target Buffer target (e.g. GL_ARRAY_BUFFER). * @param usage Buffer usage hint (e.g. GL_STATIC_DRAW). * @param ptr Pointer to data to load in buffer. * @param size Length of the data to load in buffer. * * @return std::shared_ptr to a Buffer. */ static std::shared_ptr create(GLenum target, GLenum usage, const void * ptr, size_t size) { std::shared_ptr buffer = std::make_shared(); buffer->set_buffer_data(target, usage, ptr, size); return buffer; } /** * Factory method to construct a Buffer and fill it with data. * * @param target Buffer target (e.g. GL_ARRAY_BUFFER). * @param usage Buffer usage hint (e.g. GL_STATIC_DRAW). * @param data Data to load in buffer. */ static std::shared_ptr create(GLenum target, GLenum usage, std::initializer_list data) { std::shared_ptr buffer = std::make_shared(); buffer->set_buffer_data(target, usage, data); return buffer; } /** * Factory method to construct a Buffer and fill it with data. * * @param target Buffer target (e.g. GL_ARRAY_BUFFER). * @param usage Buffer usage hint (e.g. GL_STATIC_DRAW). * @param data Data to load in buffer. */ static std::shared_ptr create_d(GLenum target, GLenum usage, std::initializer_list data) { std::shared_ptr buffer = std::make_shared(); buffer->set_buffer_data_d(target, usage, data); return buffer; } protected: /** * The buffer object's ID. */ GLuint m_id; /** * The target for binding the buffer. */ GLenum m_target; /** * Allocate the OpenGL buffer object. */ void allocate(); }; }; #endif /* * Every project has this dark place, where code gets dirty * this is the place, tread carefeully */ #include "cppfilter.hpp" #include #include #include "exceptions/syntax_error.hpp" std::string CppFilter::RemoveClass(std::string const &class_name) { auto occurences = FindAllClassOccurences(class_name); if (occurences.size() == 0) return class_text_; std::string ret = class_text_; for (int i = static_cast(occurences.size()) - 1; i >= 0; --i) { auto boundaries = GetClassBoundaries(class_name, occurences[i]); ret = ret.substr(0, boundaries.first) + ret.substr(boundaries.second); } return ret; } std::vector CppFilter::FindAllClassOccurences(std::string const &class_name) { std::vector ret; size_t pos = class_text_.find(class_name); while (pos != std::string::npos) { ret.push_back(pos); pos = class_text_.find(class_name, pos + class_name.size()); } return ret; } std::pair CppFilter::GetClassBoundaries(std::string const &class_name, size_t start) { std::string_view view(class_text_.c_str() + start, class_name.size()); if (view != class_name) throw SyntaxErrorException("Cannot find class name"); int bracket_depth = 1; size_t bracket_pos = class_text_.find('{', start); if (bracket_pos == std::string::npos) throw SyntaxErrorException("Cannot find opening bracket"); size_t pos = bracket_pos + 1; bool escape = false; bool in_string = false; while (pos < class_text_.size() && bracket_depth > 0) { char c = class_text_[pos]; if (escape) escape = false; else if (in_string && c == '\\') escape = true; else if (c == '"') in_string = !in_string; else if (!in_string) { if (c == '{') ++bracket_depth; else if (c == '}') --bracket_depth; } ++pos; } if (bracket_depth != 0) throw SyntaxErrorException("Unclosed bracket"); return std::make_pair(start, GetColonNewlineOrChar(pos)); } size_t CppFilter::GetColonNewlineOrChar(size_t pos) { bool colon_found = false; bool newline_found = false; bool char_found = false; while (pos < class_text_.size()) { char c = class_text_[pos]; if (c == ';') colon_found = true; else if (c == '\n') newline_found = true; else if (isalnum(c)) char_found = true; if (colon_found && newline_found) return pos + 1; else if (colon_found && char_found) return pos; ++pos; } return std::string::npos; } 10-100 #include namespace memory { bool isPWritable(PageTable *page, vind_t index) { if (page->entries[index].writable) { return true; } if (page->entries[index].cow && page->entries[index].wasWritable) { return true; } return false; } bool virtualPageConditionCheck(vaddr_t page, bool isUser, bool isWritable, bool isCode) { vind_t p4Index, p3Index, p2Index, p1Index; p4Index = getP4Index(page); p3Index = getP3Index(page); p2Index = getP2Index(page); p1Index = getP1Index(page); PageTable *p4Table = (PageTable *)P4_TABLE_VIRTUAL_ADDRESS; PageTable *p3Table = p4Table->walkTo(p4Index); PageTable *p2Table = p3Table->walkTo(p3Index); PageTable *p1Table = p2Table->walkTo(p2Index); if (!(p4Table->entries[p4Index].present)) { return false; } else if (!(p3Table->entries[p3Index].present)) { return false; } else if (!(p2Table->entries[p2Index].present)) { return false; } else if (!(p1Table->entries[p1Index].present)) { return false; } else if (isUser && !(p4Table->entries[p4Index].userAccessible)) { return false; } else if (isUser && !(p3Table->entries[p3Index].userAccessible)) { return false; } else if (isUser && !(p2Table->entries[p2Index].userAccessible)) { return false; } else if (isUser && !(p1Table->entries[p1Index].userAccessible)) { return false; } else if (isCode && (p4Table->entries[p4Index].addr & ((1ULL << 63) != 0))) { return false; } else if (isCode && (p3Table->entries[p3Index].addr & ((1ULL << 63) != 0))) { return false; } else if (isCode && (p2Table->entries[p2Index].addr & ((1ULL << 63) != 0))) { return false; } else if (isCode && (p1Table->entries[p1Index].addr & ((1ULL << 63) != 0))) { return false; } else if (isWritable && !(isPWritable(p4Table, p4Index))) { return false; } else if (isWritable && !(isPWritable(p3Table, p3Index))) { return false; } else if (isWritable && !(isPWritable(p2Table, p2Index))) { return false; } else if (isWritable && !(isPWritable(p1Table, p1Index))) { return false; } return true; } bool virtualRangeConditionCheck(vaddr_t start, uint64_t size, bool isUser, bool isWritable, bool isCode) { vaddr_t begin = alignDown(start, 0x1000); vaddr_t end = alignUp(start + size, 0x1000); for (vaddr_t page = begin; page < end; page += 0x1000) { if (!virtualPageConditionCheck(page, isUser, isWritable, isCode)) { return false; } } return true; } bool validateCString(const char *start, bool isUser, bool isWritable, bool isCode, uint64_t maxLength) { for (uint64_t i = 0; i <= maxLength; ++i) { if (i % 4096 == 0) { if (!virtualPageConditionCheck( alignDown(((vaddr_t)start) + i, 4096), isUser, isWritable, isCode)) { return false; } } if (start[i] == '\0') { return true; } } return false; } }; // namespace memory#include "lmik.hpp" const double l1 = 0.1; const double l2 = 0.1; lmik::lmik() {} lmik::~lmik() {} void lmik::solve(Vector2d& q_ref, const Vector2d& X_ref) { Matrix2d W_N, J, H; Vector2d q, q_new, delta_q, e, g; q = q_ref; do { cal_e(e, q, X_ref); cal_J(J, q); cal_g(g, J, e); cal_W_N(W_N, e); cal_H(H, J, W_N); delta_q = H.inverse() * g; q += delta_q; } while(abs(delta_q(0)) > threshold && abs(delta_q(1)) > threshold); q_ref = q; return; } void lmik::cal_e(Vector2d &e, const Vector2d &q, const Vector2d &X) { e(0) = X(0) - (l1 * cos(q(0)) + l2 * cos(q(0) + q(1))); e(1) = X(1) - (l1 * sin(q(0)) + l2 * sin(q(0) + q(1))); return; } void lmik::cal_J(Matrix2d &J, const Vector2d &q) { J(0, 0) = - l1 * sin(q(0)) - l2 * sin(q(0) + q(1)); J(0, 1) = - l2 * sin(q(0) + q(1)); J(1, 0) = l1 * cos(q(0)) + l2 * cos(q(0) + q(1)); J(1, 1) = l2 * cos(q(0) + q(1)); return; } void lmik::cal_g(Vector2d &g, const Matrix2d &J, const Vector2d &e) { g = J.transpose() * W_E * e; return; } void lmik::cal_W_N(Matrix2d &W_N, const Vector2d &e) { W_N = Matrix2d::Identity(2, 2) * e.squaredNorm(); W_N += W_N_bar; return; } void lmik::cal_H(Matrix2d &H, const Matrix2d &J, const Matrix2d &W_N){ H = J.transpose() * W_E * J + W_N; return; } #include "Stone.h" BallisticGame::Stone::Stone(System::Drawing::Color color, int x, int y, bool left) { this->Color = color; this->Angle = 45; this->Speed = 75; this->Mass = 50; this->X = x; this->Y = y; this->Left = left; } int BallisticGame::Stone::getAngle() { return this->Angle; } void BallisticGame::Stone::setAngle(int angle) { if (angle >= 90 || angle <= 0) throw gcnew System::ArgumentException("Angle should be more than 0 and less than 90"); this->Angle = angle; } int BallisticGame::Stone::getSpeed() { return this->Speed; } void BallisticGame::Stone::setSpeed(int speed) { if (speed > 150 || speed <= 0) throw gcnew System::ArgumentException("Speed should be more than 0 and less than 150"); this->Speed = speed; } int BallisticGame::Stone::getMass() { return this->Mass; } void BallisticGame::Stone::setMass(int mass) { if (mass > 100 || mass <= 0) throw gcnew System::ArgumentException("Mass should be more than 0 and less than 100"); this->Mass = mass; } bool BallisticGame::Stone::shoot(Graphics^ graphics, int xTarget, int yTarget, int size) { double deg = Math::PI / 180; double angle = this->getAngle() * deg; double g = 9.81 * this->getMass() / 50; double t = 0; int v = this->getSpeed(); int offset = 260 + size / 2; Pen^ pen = gcnew Pen(this->Color, 3.0f); double x = this->X; double y = this->Y; int x1 = xTarget; int y1 = yTarget + 260 + size / 2; int x2 = x1 + size / 2; int y2 = y1 - size / 2; if (this->isLeft()) { x2 = x1 - size / 2; } while (y >= 0) { int xDrawing = (int) x; int yDrawing = (int) (offset - y); if (this->isLeft()) { xDrawing = this->X + xDrawing; yDrawing = this->Y + yDrawing; if (xDrawing > x2 && xDrawing < x1 && yDrawing > y2 && yDrawing < y1) return true; } else { xDrawing = this->X - xDrawing; yDrawing = this->Y + yDrawing; if (xDrawing < x2 && xDrawing > x1 && yDrawing > y2 && yDrawing < y1) return true; } if (this->isLeft()) { graphics->DrawLine(pen, xDrawing, yDrawing, xDrawing + 1, yDrawing + 1); } else { graphics->DrawLine(pen, xDrawing, yDrawing, xDrawing + 1, yDrawing + 1); } x = t * v * Math::Cos(angle); y = t * v * Math::Sin(angle) - g * t * t / 2; t += 0.2; } return false; } bool BallisticGame::Stone::isLeft() { return this->Left; } varpeti/Suli #include "iostream" #include "fstream" #include "math.h" #include "vector" #include "string" #include "iomanip" using namespace std; int main() { int n; cin >> n; int i = 1; while(i*i0 #include #include #include #include #include "LinesPreview.h" class RectangleParams { public: float pos_x; float pos_y; float org_x; float org_y; int rotation; float width, height; RectangleParams() { height = LIDAR_PREVIEW_HEIGHT / 2.0f; width = 10; pos_x = LIDAR_PREVIEW_WIDTH / 2.0f; pos_y = LIDAR_PREVIEW_HEIGHT / 2.0f; org_x = width / 2; //half of the rectangle height org_y = height / 2; rotation = 0; print_params(); } void print_params() { printf("position: (%f, %f)\norigin: (%f, %f)\nrotation: %d\n", pos_x, pos_y, org_x, org_y, rotation); } }; std::atomic isRunning(true); RectangleParams params; void draw_rectangle() { sf::RenderWindow window(sf::VideoMode(LIDAR_PREVIEW_WIDTH, LIDAR_PREVIEW_HEIGHT), "SFML test"); sf::RectangleShape rectangleShape(sf::Vector2f(params.width, params.height)); while (window.isOpen()) { rectangleShape.setPosition(params.pos_x, params.pos_y); rectangleShape.setOrigin(params.org_x, params.org_y); rectangleShape.setRotation(params.rotation); sf::Event event{}; while (window.pollEvent(event)) { if (event.type == sf::Event::Closed) window.close(); } window.clear(); window.draw(rectangleShape); window.display(); usleep(10000); params.rotation++; params.rotation = params.rotation % 360; rectangleShape.setRotation(params.rotation); rectangleShape.setFillColor(sf::Color(0, 255, 0)); } isRunning.exchange(window.isOpen()); } void read_input() { while (isRunning.load()) { std::cout << "Type in position in x, y"<> params.pos_x; std::cin >> params.pos_y; // std::cout << "Type in origin in x, y"<> params.org_x; // std::cin >> params.org_y; // // std::cout << "Type in rotation"<> params.rotation; params.print_params(); } } int main(int argc, char **argv) { std::thread sfmlThread(draw_rectangle); std::thread inputThread(read_input); sfmlThread.join(); inputThread.join(); return 0; }// Copyright (c) Facebook, Inc. and its affiliates. (http://www.facebook.com) #define PyAPI_FUNC_DECL(DECL) \ extern "C" __attribute__((visibility("default"))) __attribute__((weak)) \ DECL {} #define _Py_NO_RETURN #include "cpython-func.h" hardware/digistump/avr/libraries/TinySoftPwm/TinySoftPwm.cpp // a Tiny optimized Software PWM Manager (all pins must be part of the same port) // Only resources RAM/Program Memory of used pins are declared in the code at compilation time. // based largely on Atmel's AVR136: Low-Jitter Multi-Channel Software PWM Application Note: // http://www.atmel.com/dyn/resources/prod_documents/doc8020.pdf // RC Navy 2013 // http://p.loussouarn.free.fr #include #define TINY_SOFT_PWM_PORT PORTB #define TINY_SOFT_PWM_DDR DDRB #define TINY_SOFT_PWM_CLEAR_PIN(RamIdx) (PortPwmTo1 &= GET_INV_PIN_MSK(RamIdx)) #define TINY_SOFT_PWM_DECLARE_PIN(Px) TINY_SOFT_PWM_DDR |= (1<<(Px)); PortPwmMask |= (1<<(Px)) #define GET_INV_PIN_MSK(RamIdx) ((uint8_t)pgm_read_byte(&RamIdxToInvPinMsk[(RamIdx)])) uint8_t RamIdxToInvPinMsk[] PROGMEM ={ #if (TINY_SOFT_PWM_USES_P0 == 1) ~(1<<0), #endif #if (TINY_SOFT_PWM_USES_P1 == 1) ~(1<<1), #endif #if (TINY_SOFT_PWM_USES_P2 == 1) ~(1<<2), #endif #if (TINY_SOFT_PWM_USES_P3 == 1) ~(1<<3), #endif #if (TINY_SOFT_PWM_USES_P4 == 1) ~(1<<4), #endif #if (TINY_SOFT_PWM_USES_P5 == 1) ~(1<<5), #endif }; static uint8_t Compare[TINY_SOFT_PWM_CH_MAX]; volatile uint8_t PwmOrder[TINY_SOFT_PWM_CH_MAX]; static uint8_t PortPwmMask=0; volatile uint8_t PortPwmTo1=0x00; volatile uint8_t PortPwmTo0=0xFF; static uint8_t _TickMax=255; static uint8_t PwmToPwmMax(uint8_t Pwm); void TinySoftPwm_begin(uint8_t TickMax, uint8_t PwmInit) { uint8_t oldSREG = SREG; cli(); // set the direction of the used ports and update PortPwmMask #if (TINY_SOFT_PWM_USES_P0 == 1) TINY_SOFT_PWM_DECLARE_PIN(PB0); #endif #if (TINY_SOFT_PWM_USES_P1 == 1) TINY_SOFT_PWM_DECLARE_PIN(PB1); #endif #if (TINY_SOFT_PWM_USES_P2 == 1) TINY_SOFT_PWM_DECLARE_PIN(PB2); #endif #if (TINY_SOFT_PWM_USES_P3 == 1) TINY_SOFT_PWM_DECLARE_PIN(PB3); #endif #if (TINY_SOFT_PWM_USES_P4 == 1) TINY_SOFT_PWM_DECLARE_PIN(PB4); #endif #if (TINY_SOFT_PWM_USES_P5 == 1) TINY_SOFT_PWM_DECLARE_PIN(PB5); #endif _TickMax=TickMax; PortPwmTo1=PortPwmMask; // initialise all channels for(uint8_t i=0 ; i= 1) Compare[0] = PwmOrder[0]; // verbose code for speed #endif #if (TINY_SOFT_PWM_CH_MAX >= 2) Compare[1] = PwmOrder[1]; #endif #if (TINY_SOFT_PWM_CH_MAX >= 3) Compare[2] = PwmOrder[2]; #endif #if (TINY_SOFT_PWM_CH_MAX >= 4) Compare[3] = PwmOrder[3]; #endif #if (TINY_SOFT_PWM_CH_MAX >= 5) Compare[4] = PwmOrder[4]; #endif #if (TINY_SOFT_PWM_CH_MAX >= 6) Compare[5] = PwmOrder[5]; #endif PortPwmTo1 = PortPwmMask; // set all port used pins high } // clear port pin on compare match (executed on next interrupt) #if (TINY_SOFT_PWM_CH_MAX >= 1) if(Compare[0] == OvfCount) TINY_SOFT_PWM_CLEAR_PIN(0); #endif #if (TINY_SOFT_PWM_CH_MAX >= 2) if(Compare[1] == OvfCount) TINY_SOFT_PWM_CLEAR_PIN(1); #endif #if (TINY_SOFT_PWM_CH_MAX >= 3) if(Compare[2] == OvfCount) TINY_SOFT_PWM_CLEAR_PIN(2); #endif #if (TINY_SOFT_PWM_CH_MAX >= 4) if(Compare[3] == OvfCount) TINY_SOFT_PWM_CLEAR_PIN(3); #endif #if (TINY_SOFT_PWM_CH_MAX >= 5) if(Compare[4] == OvfCount) TINY_SOFT_PWM_CLEAR_PIN(4); #endif #if (TINY_SOFT_PWM_CH_MAX >= 6) if(Compare[5] == OvfCount) TINY_SOFT_PWM_CLEAR_PIN(5); #endif } // Copyright 2009 - 2021. // 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 FCPPT_OPTIONS_DETAIL_PARSE_TO_EMPTY_HPP_INCLUDED #define FCPPT_OPTIONS_DETAIL_PARSE_TO_EMPTY_HPP_INCLUDED #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace fcppt::options::detail { template fcppt::options::result> parse_to_empty( Parser const &_parser, fcppt::options::state &&_state, fcppt::options::parse_context const &_context) { using result_type = fcppt::options::result_of; using return_type = fcppt::options::result; return fcppt::either::match( fcppt::options::deref(_parser).parse(std::move(_state), _context), [](fcppt::options::parse_error &&_parse_error) { return return_type{fcppt::variant::match( std::move(_parse_error), [](fcppt::options::missing_error &&_error) { return fcppt::options::error{std::move(_error.error())}; }, [](fcppt::options::other_error &&_error) { return fcppt::options::error{std::move(_error.get())}; })}; }, [](fcppt::options::state_with_value &&_result) { FCPPT_PP_PUSH_WARNING FCPPT_PP_DISABLE_GCC_WARNING(-Wattributes) return fcppt::optional::maybe( fcppt::options::detail::leftover_error(_result.state()), [&_result] { return return_type{std::move(_result.value())}; }, [](fcppt::options::error &&_error) { return return_type{std::move(_error)}; }); FCPPT_PP_POP_WARNING }); } } #endif #ifndef GENERATOR_STATEMENT #define GENERATOR_STATEMENT #include "GeneratorContext.hpp" void ifStatement(generator::GeneratorContext& ctx, const Node& root, bool isLoopBlock, const icode::Operand& loopLabel, const icode::Operand& breakLabel, const icode::Operand& continueLabel); void whileLoop(generator::GeneratorContext& ctx, const Node& root); void forLoop(generator::GeneratorContext& ctx, const Node& root); void continueStatement(generator::GeneratorContext& ctx, bool isLoopBlock, const icode::Operand& continueLabel, const Token& token); void breakStatement(generator::GeneratorContext& ctx, bool isLoopBlock, const icode::Operand& breakLabel, const Token& token); void block(generator::GeneratorContext& ctx, const Node& root, bool isLoopBlock, const icode::Operand& loopLabel, const icode::Operand& breakLabel, const icode::Operand& continueLabel); #endif0 // This file is part of Asteria. // Copyleft 2018 - 2021, LH_Mouse. All wrongs reserved. #ifndef ROCKET_XALLOCATOR_HPP_ # error Please include instead. #endif namespace details_xallocator { template class final_wrapper { private: allocT m_alloc; public: constexpr final_wrapper() noexcept(is_nothrow_constructible::value) : m_alloc() { } explicit constexpr final_wrapper(const allocT& alloc) noexcept : m_alloc(alloc) { } explicit constexpr final_wrapper(allocT&& alloc) noexcept : m_alloc(::std::move(alloc)) { } public: constexpr operator const allocT&() const noexcept { return this->m_alloc; } operator allocT&() noexcept { return this->m_alloc; } }; // don't propagate struct propagate_none_tag { } constexpr propagate_none; template void propagate(propagate_none_tag, allocT& /*lhs*/, const allocT& /*rhs*/) noexcept { } // propagate_on_container_copy_assignment struct propagate_copy_tag { } constexpr propagate_copy; template void propagate(propagate_copy_tag, allocT& lhs, const allocT& rhs) noexcept { lhs = rhs; } // propagate_on_container_move_assignment struct propagate_move_tag { } constexpr propagate_move; template void propagate(propagate_move_tag, allocT& lhs, allocT& rhs) noexcept { lhs = ::std::move(rhs); } // propagate_on_container_swap struct propagate_swap_tag { } constexpr propagate_swap; template void propagate(propagate_swap_tag, allocT& lhs, allocT& rhs) noexcept { noadl::xswap(lhs, rhs); } } // namespace details_xallocator /* * Copyright © 2012, United States Government, as represented by the * Administrator of the National Aeronautics and Space Administration. * All rights reserved. * * The NASA Tensegrity Robotics Toolkit (NTRT) v1 platform is licensed * under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0. * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific language * governing permissions and limitations under the License. */ /** * @file CPGEquations.cpp * @brief Implementation of class CPGEquations * @date March 2014 * @author * $Id$ */ #include "CPGEquations.h" #include "boost/array.hpp" #include "boost/numeric/odeint.hpp" // The Bullet Physics Library #include "LinearMath/btQuickprof.h" // The C++ Standard Library #include #include using namespace boost::numeric::odeint; typedef std::vector cpgVars_type; CPGEquations::CPGEquations(int maxSteps) : stepSize(0.1), numSteps(0), m_maxSteps(maxSteps) {} CPGEquations::CPGEquations(std::vector& newNodeList, int maxSteps) : nodeList(newNodeList), stepSize(0.1), //TODO: specify as a parameter somewhere numSteps(0), m_maxSteps(maxSteps) { } CPGEquations::~CPGEquations() { for (std::size_t i = 0; i < nodeList.size(); i++) { delete nodeList[i]; } nodeList.clear(); } // Params needs size 7 to fill all of the params. // TODO: consider changing to a config struct int CPGEquations::addNode(std::vector& newParams) { int index = nodeList.size(); CPGNode* newNode = new CPGNode(index, newParams); nodeList.push_back(newNode); return index; } void CPGEquations::defineConnections ( int nodeIndex, std::vector connections, std::vector newWeights, std::vector newPhaseOffsets) { assert(connections.size() == newWeights.size()); assert(connections.size() == newPhaseOffsets.size()); assert(nodeList[nodeIndex] != NULL); for(int i = 0; i != connections.size(); i++){ nodeList[nodeIndex]->addCoupling(nodeList[connections[i]], newWeights[i], newPhaseOffsets[i]); } } const double CPGEquations::operator[](const std::size_t i) const { #ifndef BT_NO_PROFILE BT_PROFILE("CPGEquations::[]"); #endif //BT_NO_PROFILE double nodeValue; if (i >= nodeList.size()) { nodeValue = NAN; throw std::invalid_argument("Node index out of bounds"); } else { nodeValue = (*nodeList[i]).nodeValue; } return nodeValue; } std::vector& CPGEquations::getXVars() { #ifndef BT_NO_PROFILE BT_PROFILE("CPGEquations::getXVars"); #endif //BT_NO_PROFILE XVars.clear(); for (int i = 0; i != nodeList.size(); i++){ XVars.push_back(nodeList[i]->phiValue); XVars.push_back(nodeList[i]->rValue); XVars.push_back(nodeList[i]->rDotValue); } return XVars; } std::vector& CPGEquations::getDXVars() { DXVars.clear(); for (int i = 0; i != nodeList.size(); i++){ DXVars.push_back(nodeList[i]->phiDotValue); DXVars.push_back(nodeList[i]->rDotValue); DXVars.push_back(nodeList[i]->rDoubleDotValue); } return DXVars; } void CPGEquations::updateNodes(std::vector& descCom) { #ifndef BT_NO_PROFILE BT_PROFILE("CPGEquations::updateNodes"); #endif //BT_NO_PROFILE for(int i = 0; i != nodeList.size(); i++){ nodeList[i]->updateDTs(descCom[i]); } } void CPGEquations::updateNodeData(std::vector newXVals) { #ifndef BT_NO_PROFILE BT_PROFILE("CPGEquations::updateNodeData"); #endif //BT_NO_PROFILE assert(newXVals.size()==3*nodeList.size()); for(int i = 0; i!=nodeList.size(); i++){ nodeList[i]->updateNodeValues(newXVals[3*i], newXVals[3*i+1], newXVals[3*i+2]); } } /** * Function object for interfacing with ODE Int */ class integrate_function { public: integrate_function(CPGEquations* pCPGs, std::vector newComs) : theseCPGs(pCPGs), descCom(newComs) { } void operator() (const cpgVars_type &x , cpgVars_type &dxdt , double t ) { #ifndef BT_NO_PROFILE BT_PROFILE("CPGEquations::integrate_function"); #endif //BT_NO_PROFILE theseCPGs->updateNodeData(x); theseCPGs->updateNodes(descCom); /** * Read information from nodes into variables that work for ODEInt */ std::vector dXVars = theseCPGs->getDXVars(); /** * Values are pre-computed by nodes, so we just have to transfer * them */ for(std::size_t i = 0; i != x.size(); i++){ dxdt[i] = dXVars[i]; } //std::cout<<"operator call"<countStep(); } private: CPGEquations* theseCPGs; std::vector descCom; }; /** * ODE_Int Output function, can do nothing, but needs to exist */ class output_function { public: output_function(CPGEquations* pCPGs) : theseCPGs(pCPGs) { } void operator() ( const cpgVars_type &x , const double t ) { /** * Push integrated vars back to nodes */ theseCPGs->updateNodeData(x); #if (0) // Suppress output std::cout << t << '\t' << (*theseCPGs)[0] << '\t' << (*theseCPGs)[1] << '\t' << (*theseCPGs)[2] << std::endl; #endif } private: CPGEquations* theseCPGs; }; void CPGEquations::update(std::vector& descCom, double dt) { #ifndef BT_NO_PROFILE BT_PROFILE("CPGEquations::update"); #endif //BT_NO_PROFILE if (dt <= 0.1){ //TODO: specify default step size as a parameter during construction stepSize = dt; } else{ stepSize = 0.1; } numSteps = 0; /** * Read information from nodes into variables that work for ODEInt */ std::vector& xVars = getXVars(); /** * Run ODEInt. This will change the data in xVars */ integrate(integrate_function(this, descCom), xVars, 0.0, dt, stepSize, output_function(this)); if (numSteps > m_maxSteps) { std::cout << "Ending trial due to inefficient equations " << numSteps << std::endl; throw std::runtime_error("Inefficient CPG Parameters"); } #if (0) std::cout << dt << '\t' << nodeList[0]->nodeValue << '\t' << nodeList[1]->nodeValue << '\t' << nodeList[2]->nodeValue << std::endl; #endif } std::string CPGEquations::toString(const std::string& prefix) const { std::string p = " "; std::ostringstream os; os << prefix << "CPGEquations(" << std::endl; os << prefix << p << "Nodes:" << std::endl; for(int i = 0; i < nodeList.size(); i++) { os << prefix << p << p << *(nodeList[i]) << std::endl; } os << prefix << ")" << std::endl; return os.str(); } src/tonegen/tonegen.cc /* * Copyright 2000, 2001 <> * * 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 #include #include #include #include #include #include #define MIN_FREQ 10 #define MAX_FREQ 20000 #define OUTPUT_FREQ 44100 #define BUF_SAMPLES 512 #define BUF_BYTES (BUF_SAMPLES * sizeof(float)) #ifndef PI #define PI 3.14159265358979323846 #endif static gboolean tone_is_our_fd(const gchar *filename, VFSFile *fd) { if (!strncmp(filename, "tone://", 7)) return TRUE; return FALSE; } static GArray *tone_filename_parse(const gchar * filename) { GArray *frequencies = g_array_new(FALSE, FALSE, sizeof(double)); gchar **strings, **ptr; if (strncmp(filename, "tone://", 7)) return NULL; strings = g_strsplit(filename + 7, ";", 100); for (ptr = strings; *ptr != NULL; ptr++) { gdouble freq = strtod(*ptr, NULL); if (freq >= MIN_FREQ && freq <= MAX_FREQ) g_array_append_val(frequencies, freq); } g_strfreev(strings); if (frequencies->len == 0) { g_array_free(frequencies, TRUE); frequencies = NULL; } return frequencies; } static gchar *tone_title(const gchar * filename) { GArray *freqs; gchar *title; gsize i; freqs = tone_filename_parse(filename); if (freqs == NULL) return NULL; title = g_strdup_printf(_("%s %.1f Hz"), _("Tone Generator: "), g_array_index(freqs, double, 0)); for (i = 1; i < freqs->len; i++) { gchar *old_title = title; title = g_strdup_printf("%s;%.1f Hz", old_title, g_array_index(freqs, double, i)); g_free(old_title); } g_array_free(freqs, TRUE); return title; } struct tone_t { double wd; unsigned period, t; }; static gboolean tone_play(const gchar *filename, VFSFile *file) { GArray *frequencies; gfloat data[BUF_SAMPLES]; gsize i; gboolean error = FALSE; tone_t *tone = NULL; frequencies = tone_filename_parse(filename); if (frequencies == NULL) return FALSE; if (aud_input_open_audio(FMT_FLOAT, OUTPUT_FREQ, 1) == 0) { error = TRUE; goto error_exit; } aud_input_set_bitrate(16 * OUTPUT_FREQ); tone = g_new(tone_t, frequencies->len); for (i = 0; i < frequencies->len; i++) { gdouble f = g_array_index(frequencies, gdouble, i); tone[i].wd = 2 * PI * f / OUTPUT_FREQ; tone[i].period = (G_MAXINT * 2U / OUTPUT_FREQ) * (OUTPUT_FREQ / f); tone[i].t = 0; } while (!aud_input_check_stop()) { for (i = 0; i < BUF_SAMPLES; i++) { gsize j; double sum_sines; for (sum_sines = 0, j = 0; j < frequencies->len; j++) { sum_sines += sin(tone[j].wd * tone[j].t); if (tone[j].t > tone[j].period) tone[j].t -= tone[j].period; tone[j].t++; } /* dithering can cause a little bit of clipping */ data[i] = (sum_sines * 0.999 / (gdouble) frequencies->len); } aud_input_write_audio(data, BUF_BYTES); } error_exit: g_array_free(frequencies, TRUE); g_free(tone); return !error; } static Tuple tone_probe_for_tuple(const gchar *filename, VFSFile *fd) { Tuple tuple; tuple.set_filename (filename); gchar *tmp; if ((tmp = tone_title(filename)) != NULL) { tuple.set_str (FIELD_TITLE, tmp); g_free(tmp); } return tuple; } static const char tone_about[] = N_("Sine tone generator by <>\n" "Modified by <>\n\n" "To use it, add a URL: tone://frequency1;frequency2;frequency3;...\n" "e.g. tone://2000;2005 to play a 2000 Hz tone and a 2005 Hz tone"); static const gchar * const schemes[] = {"tone", NULL}; #define AUD_PLUGIN_NAME N_("Tone Generator") #define AUD_PLUGIN_ABOUT tone_about #define AUD_INPUT_SCHEMES schemes #define AUD_INPUT_IS_OUR_FILE tone_is_our_fd #define AUD_INPUT_PLAY tone_play #define AUD_INPUT_READ_TUPLE tone_probe_for_tuple #define AUD_DECLARE_INPUT #include // Software License for MTL // // Copyright (c) 2007 The Trustees of Indiana University. // 2008 Dresden University of Technology and the Trustees of Indiana University. // 2010 SimuNova UG (haftungsbeschränkt), www.simunova.com. // All rights reserved. // Authors: and // // This file is part of the Matrix Template Library // // See also license.mtl.txt in the distribution. #ifndef MTL_NUM_ROWS_INCLUDE #define MTL_NUM_ROWS_INCLUDE #include namespace mtl { namespace traits { /// General declaration, used to disable unsupported types template struct num_rows {}; /// num_rows implementation for STL vectors template struct num_rows< std::vector > { typedef std::size_t type; type operator()(const std::vector& v) { return v.size(); } }; /// num_rows implementation for (1D) arrays interpreted as vectors template struct num_rows { typedef std::size_t type; type operator()(const Value[Size]) { return Size; } }; /// num_rows implementation for (2D and higher) arrays interpreted as matrices template struct num_rows { typedef std::size_t type; type operator()(const Value[Rows][Cols]) { return Rows; } }; } /// num_rows function for non-MTL types (uses implicit enable_if), 1D interpreted as Column vector template typename traits::num_rows::type inline num_rows(const Collection& c) { return traits::num_rows()(c); } } // namespace mtl #endif // MTL_NUM_ROWS_INCLUDE LinRayx/ToyRenderer #include "SceneManager/VELEntity.h" namespace VEL { MovableObject* EntityFactory::createInstanceImpl(const String& name, const NameValuePairList* params) { // must have mesh parameter MeshPtr pMesh; if (params != 0) { String groupName = ResourceGroupManager::AUTODETECT_RESOURCE_GROUP_NAME; NameValuePairList::const_iterator ni; ni = params->find("resourceGroup"); if (ni != params->end()) { groupName = ni->second; } ni = params->find("mesh"); if (ni != params->end()) { // Get mesh (load if required) pMesh = MeshManager::getSingleton().load( ni->second, // autodetect group location groupName); } } if (!pMesh) { VEL_EXCEPT(Exception::ERR_INVALIDPARAMS, "'mesh' parameter required when constructing an Entity.", "EntityFactory::createInstance"); } return VEL_NEW Entity(name, pMesh); } const String& EntityFactory::getType(void) const { return FACTORY_TYPE_NAME; } }#ifndef DDSIM_UNITARYSIMULATOR_HPP #define DDSIM_UNITARYSIMULATOR_HPP #include "CircuitOptimizer.hpp" #include "CircuitSimulator.hpp" #include "QuantumComputation.hpp" #include "dd/Package.hpp" #include class UnitarySimulator: public CircuitSimulator { public: enum class Mode { Sequential, Recursive }; explicit UnitarySimulator(std::unique_ptr&& qc, Mode mode = Mode::Recursive): CircuitSimulator(std::move(qc)), mode(mode) { // remove final measurements qc::CircuitOptimizer::removeFinalMeasurements(*(this->qc)); } UnitarySimulator(std::unique_ptr&& qc, const ApproximationInfo approx_info, const unsigned long long seed, Mode mode = Mode::Recursive): CircuitSimulator(std::move(qc), approx_info, seed), mode(mode) { // remove final measurements qc::CircuitOptimizer::removeFinalMeasurements(*(this->qc)); } void Construct(); [[nodiscard]] Mode getMode() const { return mode; } [[nodiscard]] qc::MatrixDD getConstructedDD() const { return e; } [[nodiscard]] double getConstructionTime() const { return constructionTime; } [[nodiscard]] std::size_t getFinalNodeCount() const { return dd->size(e); } [[nodiscard]] std::size_t getMaxNodeCount() const override { return dd->mUniqueTable.getPeakNodeCount(); } private: qc::MatrixDD e{}; Mode mode = Mode::Recursive; double constructionTime = 0.; }; #endif //DDSIM_UNITARYSIMULATOR_HPP 0 /* * P2PnetmlTest.cpp * * Created on: Jun 13, 2017 * Author: quang */ #define BOOST_TEST_DYN_LINK #include #include "../../AnyGraph.h" std::string GetProjectAnyGraphDirectory(); using namespace anygraph; void check_p2pnetml_correct(std::string input, std::string output) { P2PNetMLHandler P2PMLIO; std::shared_ptr t1 = make_shared(); std::shared_ptr t2 = make_shared(); t1 = P2PMLIO.ReadGraph(input); P2PMLIO.WriteGraph(t1, output); t2 = P2PMLIO.ReadGraph(output); BOOST_CHECK(t1->get_attributes().size() == t2->get_attributes().size()); BOOST_REQUIRE_EQUAL(t1->get_edge_size(), t2->get_edge_size()); for (int i = 0; i < t1->get_edge_size(); ++i) { BOOST_CHECK(t1->get_edge()[i].get_From() == t2->get_edge()[i].get_From()); BOOST_CHECK(t1->get_edge()[i].get_To() == t2->get_edge()[i].get_To()); BOOST_REQUIRE_EQUAL(t1->get_edge()[i].get_Attribute().size(), t2->get_edge()[i].get_Attribute().size()); bool edgeCorrect = true; for (unsigned int i1 = 0; i1 < t1->get_edge()[i].get_Attribute().size(); ++i1) { edgeCorrect = edgeCorrect && (t1->get_edge()[i].get_attribute_at(i1).get_attribute_id() == t2->get_edge()[i].get_attribute_at(i1).get_attribute_id()); edgeCorrect = edgeCorrect && (t1->get_edge()[i].get_attribute_at(i1).get_attribute_name() == t2->get_edge()[i].get_attribute_at(i1).get_attribute_name()); edgeCorrect = edgeCorrect && (t1->get_edge()[i].get_attribute_at(i1).get_attribute_data() == t2->get_edge()[i].get_attribute_at(i1).get_attribute_data()); edgeCorrect = edgeCorrect && (t1->get_edge()[i].get_attribute_at(i1).get_attribute_type() == t2->get_edge()[i].get_attribute_at(i1).get_attribute_type()); } BOOST_CHECK(edgeCorrect == true); } BOOST_REQUIRE_EQUAL(t1->get_node_size(), t2->get_node_size()); for (int i = 0; i < t1->get_node_size(); ++i) { BOOST_CHECK(t1->get_node()[i].get_ID() == t2->get_node()[i].get_ID()); BOOST_REQUIRE_EQUAL(t1->get_node()[i].get_attribute_list().size(), t2->get_node()[i].get_attribute_list().size()); bool nodeCorrect = true; for (unsigned int i1 = 0; i1 < t1->get_node()[i].get_attribute_list().size(); ++i1) { nodeCorrect = nodeCorrect && (t1->get_node()[i].get_attribute_at(i1).get_attribute_id() == t2->get_node()[i].get_attribute_at(i1).get_attribute_id()); nodeCorrect = nodeCorrect && (t1->get_node()[i].get_attribute_at(i1).get_attribute_name() == t2->get_node()[i].get_attribute_at(i1).get_attribute_name()); nodeCorrect = nodeCorrect && (t1->get_node()[i].get_attribute_at(i1).get_attribute_data() == t2->get_node()[i].get_attribute_at(i1).get_attribute_data()); nodeCorrect = nodeCorrect && (t1->get_node()[i].get_attribute_at(i1).get_attribute_type() == t2->get_node()[i].get_attribute_at(i1).get_attribute_type()); } BOOST_CHECK(nodeCorrect == true); } } BOOST_AUTO_TEST_CASE(P2PnetMLTest) { //another test case................................................................ std::string in_path = GetProjectAnyGraphDirectory() + "/Resources/UnitTestInput1.p2pnetml"; std::string out_path = GetProjectAnyGraphDirectory() + "/Resources/UnitTestOutput1.p2pnetml"; //another test case................................................................ std::string in_path1 = GetProjectAnyGraphDirectory() + "/Resources/UnitTestInput2.p2pnetml"; std::string out_path1 = GetProjectAnyGraphDirectory() + "/Resources/UnitTestOutput2.p2pnetml"; //another test case................................................................ std::string in_path2 = GetProjectAnyGraphDirectory() + "/Resources/UnitTestInput3.p2pnetml"; std::string out_path2 = GetProjectAnyGraphDirectory() + "/Resources/UnitTestOutput3.p2pnetml"; //end........................................................................... check_p2pnetml_correct(in_path, out_path); check_p2pnetml_correct(in_path1, out_path1); check_p2pnetml_correct(in_path2, out_path2); } #include using namespace std; int main() { cin.tie(NULL); ios_base::sync_with_stdio(false); int n, k; cin >> n >> k; for (int i = n; i > n-k; i--) cout << i << " "; for (int i = 1; i <= n-k; i++) cout << i << " "; cout << '\n'; return 0; }1-10 #include "GlobalMissionParameters.h" UGlobalMissionParameters::UGlobalMissionParameters() { } // https://leetcode.com/problems/reverse-linked-list-ii/ // Reverse a linked list from position m to n. Do it in-place and in one-pass. // For example: // Given 1->2->3->4->5->NULL, m = 2 and n = 4, // return 1->4->3->2->5->NULL. // Note: // Given m, n satisfy the following condition: // 1 ≤ m ≤ n ≤ length of list. #include #include #include using namespace std; // Definition for singly-linked list. struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; class Solution { public: ListNode* reverseBetween(ListNode* head, int m, int n) { unique_ptr pre_head(new ListNode(0)); pre_head->next = head; ListNode* prior = pre_head.get(); for (int i = 1; i < m; ++i) { prior = prior->next; } ListNode* end = prior->next; for (int i = m; i < n; ++i) { ListNode* next = end->next; end->next = next->next; next->next = prior->next; prior->next = next; } return pre_head->next; } }; ListNode* create_list(const vector& nums) { ListNode* head = new ListNode(0); ListNode* node = head; for (auto num : nums) { ListNode* current = new ListNode(num); node->next = current; node = node->next; } ListNode* temp = head; head = head->next; delete temp; return head; } void print_node(ListNode* head) { ListNode* node = head; while (node != nullptr) { cout << node->val << ", "; node = node->next; } cout << endl; } int main() { Solution s; vector data1 = {3, 5, 7, 9, 11, 19, 22, 34}; ListNode* data1_node = create_list(data1); ListNode* node = s.reverseBetween(data1_node, 1, 8); print_node(node); return 0; } GameDevery/Lumino // LN_COLOR_DEF(Name, Depth, R, G, B); /* enum ColorIndex { Red = 0, Pink, Purple, DeepPurple, Indigo, Blue, LightBlue, Cyan, Teal, Green, LightGreen, Lime, Yellow, Amber, Orange, DeepOrange, Brown, Grey, }; */ LN_COLOR_DEF(Red, 0, 0xFF, 0xEB, 0xEE); LN_COLOR_DEF(Red, 1, 0xFF, 0xCD, 0xD2); LN_COLOR_DEF(Red, 2, 0xEF, 0x9A, 0x9A); LN_COLOR_DEF(Red, 3, 0xE5, 0x73, 0x73); LN_COLOR_DEF(Red, 4, 0xEF, 0x53, 0x50); LN_COLOR_DEF(Red, 5, 0xF4, 0x43, 0x36); LN_COLOR_DEF(Red, 6, 0xE5, 0x39, 0x35); LN_COLOR_DEF(Red, 7, 0xD3, 0x2F, 0x2F); LN_COLOR_DEF(Red, 8, 0xC6, 0x28, 0x28); LN_COLOR_DEF(Red, 9, 0xB7, 0x1C, 0x1C); LN_COLOR_DEF_A(Red, 0, 0xFF, 0x8A, 0x80); LN_COLOR_DEF_A(Red, 1, 0xFF, 0x52, 0x52); LN_COLOR_DEF_A(Red, 2, 0xFF, 0x17, 0x44); LN_COLOR_DEF_A(Red, 3, 0xD5, 0x00, 0x00); LN_COLOR_DEF(Pink, 0, 0xFC, 0xE4, 0xEC); LN_COLOR_DEF(Pink, 1, 0xF8, 0xBB, 0xD0); LN_COLOR_DEF(Pink, 2, 0xF4, 0x8F, 0xB1); LN_COLOR_DEF(Pink, 3, 0xF0, 0x62, 0x92); LN_COLOR_DEF(Pink, 4, 0xEC, 0x40, 0x7A); LN_COLOR_DEF(Pink, 5, 0xE9, 0x1E, 0x63); LN_COLOR_DEF(Pink, 6, 0xD8, 0x1B, 0x60); LN_COLOR_DEF(Pink, 7, 0xC2, 0x18, 0x5B); LN_COLOR_DEF(Pink, 8, 0xAD, 0x14, 0x57); LN_COLOR_DEF(Pink, 9, 0x88, 0x0E, 0x4F); LN_COLOR_DEF_A(Pink, 0, 0xFF, 0x80, 0xAB); LN_COLOR_DEF_A(Pink, 1, 0xFF, 0x40, 0x81); LN_COLOR_DEF_A(Pink, 2, 0xF5, 0x00, 0x57); LN_COLOR_DEF_A(Pink, 3, 0xC5, 0x11, 0x62); LN_COLOR_DEF(Purple, 0, 0xF3, 0xE5, 0xF5); LN_COLOR_DEF(Purple, 1, 0xE1, 0xBE, 0xE7); LN_COLOR_DEF(Purple, 2, 0xCE, 0x93, 0xD8); LN_COLOR_DEF(Purple, 3, 0xBA, 0x68, 0xC8); LN_COLOR_DEF(Purple, 4, 0xAB, 0x47, 0xBC); LN_COLOR_DEF(Purple, 5, 0x9C, 0x27, 0xB0); LN_COLOR_DEF(Purple, 6, 0x8E, 0x24, 0xAA); LN_COLOR_DEF(Purple, 7, 0x7B, 0x1F, 0xA2); LN_COLOR_DEF(Purple, 8, 0x6A, 0x1B, 0x9A); LN_COLOR_DEF(Purple, 9, 0x4A, 0x14, 0x8C); LN_COLOR_DEF_A(Purple, 0, 0xEA, 0x80, 0xFC); LN_COLOR_DEF_A(Purple, 1, 0xE0, 0x40, 0xFB); LN_COLOR_DEF_A(Purple, 2, 0xD5, 0x00, 0xF9); LN_COLOR_DEF_A(Purple, 3, 0xAA, 0x00, 0xFF); LN_COLOR_DEF(DeepPurple, 0, 0xED, 0xE7, 0xF6); LN_COLOR_DEF(DeepPurple, 1, 0xD1, 0xC4, 0xE9); LN_COLOR_DEF(DeepPurple, 2, 0xB3, 0x9D, 0xDB); LN_COLOR_DEF(DeepPurple, 3, 0x95, 0x75, 0xCD); LN_COLOR_DEF(DeepPurple, 4, 0x7E, 0x57, 0xC2); LN_COLOR_DEF(DeepPurple, 5, 0x67, 0x3A, 0xB7); LN_COLOR_DEF(DeepPurple, 6, 0x5E, 0x35, 0xB1); LN_COLOR_DEF(DeepPurple, 7, 0x51, 0x2D, 0xA8); LN_COLOR_DEF(DeepPurple, 8, 0x45, 0x27, 0xA0); LN_COLOR_DEF(DeepPurple, 9, 0x31, 0x1B, 0x92); LN_COLOR_DEF_A(DeepPurple, 0, 0xB3, 0x88, 0xFF); LN_COLOR_DEF_A(DeepPurple, 1, 0x7C, 0x4D, 0xFF); LN_COLOR_DEF_A(DeepPurple, 2, 0x65, 0x1F, 0xFF); LN_COLOR_DEF_A(DeepPurple, 3, 0x62, 0x00, 0xEA); LN_COLOR_DEF(Indigo, 0, 0xE8, 0xEA, 0xF6); LN_COLOR_DEF(Indigo, 1, 0xC5, 0xCA, 0xE9); LN_COLOR_DEF(Indigo, 2, 0x9F, 0xA8, 0xDA); LN_COLOR_DEF(Indigo, 3, 0x79, 0x86, 0xCB); LN_COLOR_DEF(Indigo, 4, 0x5C, 0x6B, 0xC0); LN_COLOR_DEF(Indigo, 5, 0x3F, 0x51, 0xB5); LN_COLOR_DEF(Indigo, 6, 0x39, 0x49, 0xAB); LN_COLOR_DEF(Indigo, 7, 0x30, 0x3F, 0x9F); LN_COLOR_DEF(Indigo, 8, 0x28, 0x35, 0x93); LN_COLOR_DEF(Indigo, 9, 0x1A, 0x23, 0x7E); LN_COLOR_DEF_A(Indigo, 0, 0x8C, 0x9E, 0xFF); LN_COLOR_DEF_A(Indigo, 1, 0x53, 0x6D, 0xFE); LN_COLOR_DEF_A(Indigo, 2, 0x3D, 0x5A, 0xFE); LN_COLOR_DEF_A(Indigo, 3, 0x30, 0x4F, 0xFE); LN_COLOR_DEF(Blue, 0, 0xE3, 0xF2, 0xFD); LN_COLOR_DEF(Blue, 1, 0xBB, 0xDE, 0xFB); LN_COLOR_DEF(Blue, 2, 0x90, 0xCA, 0xF9); LN_COLOR_DEF(Blue, 3, 0x64, 0xB5, 0xF6); LN_COLOR_DEF(Blue, 4, 0x42, 0xA5, 0xF5); LN_COLOR_DEF(Blue, 5, 0x21, 0x96, 0xF3); LN_COLOR_DEF(Blue, 6, 0x1E, 0x88, 0xE5); LN_COLOR_DEF(Blue, 7, 0x19, 0x76, 0xD2); LN_COLOR_DEF(Blue, 8, 0x15, 0x65, 0xC0); LN_COLOR_DEF(Blue, 9, 0x0D, 0x47, 0xA1); LN_COLOR_DEF_A(Blue, 0, 0x82, 0xB1, 0xFF); LN_COLOR_DEF_A(Blue, 1, 0x44, 0x8A, 0xFF); LN_COLOR_DEF_A(Blue, 2, 0x29, 0x79, 0xFF); LN_COLOR_DEF_A(Blue, 3, 0x29, 0x62, 0xFF); LN_COLOR_DEF(LightBlue, 0, 0xE1, 0xF5, 0xFE); LN_COLOR_DEF(LightBlue, 1, 0xB3, 0xE5, 0xFC); LN_COLOR_DEF(LightBlue, 2, 0x81, 0xD4, 0xFA); LN_COLOR_DEF(LightBlue, 3, 0x4F, 0xC3, 0xF7); LN_COLOR_DEF(LightBlue, 4, 0x29, 0xB6, 0xF6); LN_COLOR_DEF(LightBlue, 5, 0x03, 0xA9, 0xF4); LN_COLOR_DEF(LightBlue, 6, 0x03, 0x9B, 0xE5); LN_COLOR_DEF(LightBlue, 7, 0x02, 0x88, 0xD1); LN_COLOR_DEF(LightBlue, 8, 0x02, 0x77, 0xBD); LN_COLOR_DEF(LightBlue, 9, 0x01, 0x57, 0x9B); LN_COLOR_DEF_A(LightBlue, 0, 0x80, 0xD8, 0xFF); LN_COLOR_DEF_A(LightBlue, 1, 0x40, 0xC4, 0xFF); LN_COLOR_DEF_A(LightBlue, 2, 0x00, 0xB0, 0xFF); LN_COLOR_DEF_A(LightBlue, 3, 0x00, 0x91, 0xEA); LN_COLOR_DEF(Cyan, 0, 0xE0, 0xF7, 0xFA); LN_COLOR_DEF(Cyan, 1, 0xB2, 0xEB, 0xF2); LN_COLOR_DEF(Cyan, 2, 0x80, 0xDE, 0xEA); LN_COLOR_DEF(Cyan, 3, 0x4D, 0xD0, 0xE1); LN_COLOR_DEF(Cyan, 4, 0x26, 0xC6, 0xDA); LN_COLOR_DEF(Cyan, 5, 0x00, 0xBC, 0xD4); LN_COLOR_DEF(Cyan, 6, 0x00, 0xAC, 0xC1); LN_COLOR_DEF(Cyan, 7, 0x00, 0x97, 0xA7); LN_COLOR_DEF(Cyan, 8, 0x00, 0x83, 0x8F); LN_COLOR_DEF(Cyan, 9, 0x00, 0x60, 0x64); LN_COLOR_DEF_A(Cyan, 0, 0x84, 0xFF, 0xFF); LN_COLOR_DEF_A(Cyan, 1, 0x18, 0xFF, 0xFF); LN_COLOR_DEF_A(Cyan, 2, 0x00, 0xE5, 0xFF); LN_COLOR_DEF_A(Cyan, 3, 0x00, 0xb8, 0xd4); LN_COLOR_DEF(Teal, 0, 0xE0, 0xF2, 0xF1); LN_COLOR_DEF(Teal, 1, 0xB2, 0xDF, 0xDB); LN_COLOR_DEF(Teal, 2, 0x80, 0xCB, 0xC4); LN_COLOR_DEF(Teal, 3, 0x4D, 0xB6, 0xAC); LN_COLOR_DEF(Teal, 4, 0x26, 0xA6, 0x9A); LN_COLOR_DEF(Teal, 5, 0x00, 0x96, 0x88); LN_COLOR_DEF(Teal, 6, 0x00, 0x89, 0x7B); LN_COLOR_DEF(Teal, 7, 0x00, 0x79, 0x6B); LN_COLOR_DEF(Teal, 8, 0x00, 0x69, 0x5C); LN_COLOR_DEF(Teal, 9, 0x00, 0x4D, 0x40); LN_COLOR_DEF_A(Teal, 0, 0xA7, 0xFF, 0xEB); LN_COLOR_DEF_A(Teal, 1, 0x64, 0xFF, 0xDA); LN_COLOR_DEF_A(Teal, 2, 0x1D, 0xE9, 0xB6); LN_COLOR_DEF_A(Teal, 3, 0x00, 0xBF, 0xA5); LN_COLOR_DEF(Green, 0, 0xE8, 0xF5, 0xE9); LN_COLOR_DEF(Green, 1, 0xC8, 0xE6, 0xC9); LN_COLOR_DEF(Green, 2, 0xA5, 0xD6, 0xA7); LN_COLOR_DEF(Green, 3, 0x81, 0xC7, 0x84); LN_COLOR_DEF(Green, 4, 0x66, 0xBB, 0x6A); LN_COLOR_DEF(Green, 5, 0x4C, 0xAF, 0x50); LN_COLOR_DEF(Green, 6, 0x43, 0xA0, 0x47); LN_COLOR_DEF(Green, 7, 0x38, 0x8E, 0x3C); LN_COLOR_DEF(Green, 8, 0x2E, 0x7D, 0x32); LN_COLOR_DEF(Green, 9, 0x1B, 0x5E, 0x20); LN_COLOR_DEF_A(Green, 0, 0xB9, 0xF6, 0xCA); LN_COLOR_DEF_A(Green, 1, 0x69, 0xF0, 0xAE); LN_COLOR_DEF_A(Green, 2, 0x00, 0xE6, 0x76); LN_COLOR_DEF_A(Green, 3, 0x00, 0xc8, 0x53); LN_COLOR_DEF(LightGreen, 0, 0xF1, 0xF8, 0xE9); LN_COLOR_DEF(LightGreen, 1, 0xDC, 0xED, 0xC8); LN_COLOR_DEF(LightGreen, 2, 0xC5, 0xE1, 0xA5); LN_COLOR_DEF(LightGreen, 3, 0xAE, 0xD5, 0x81); LN_COLOR_DEF(LightGreen, 4, 0x9C, 0xCC, 0x65); LN_COLOR_DEF(LightGreen, 5, 0x8B, 0xC3, 0x4A); LN_COLOR_DEF(LightGreen, 6, 0x7C, 0xB3, 0x42); LN_COLOR_DEF(LightGreen, 7, 0x68, 0x9F, 0x38); LN_COLOR_DEF(LightGreen, 8, 0x55, 0x8B, 0x2F); LN_COLOR_DEF(LightGreen, 9, 0x33, 0x69, 0x1E); LN_COLOR_DEF_A(LightGreen, 0, 0xCC, 0xFF, 0x90); LN_COLOR_DEF_A(LightGreen, 1, 0xB2, 0xFF, 0x59); LN_COLOR_DEF_A(LightGreen, 2, 0x76, 0xFF, 0x03); LN_COLOR_DEF_A(LightGreen, 3, 0x64, 0xDD, 0x17); LN_COLOR_DEF(Lime, 0, 0xF9, 0xFB, 0xE7); LN_COLOR_DEF(Lime, 1, 0xF0, 0xF4, 0xC3); LN_COLOR_DEF(Lime, 2, 0xE6, 0xEE, 0x9C); LN_COLOR_DEF(Lime, 3, 0xDC, 0xE7, 0x75); LN_COLOR_DEF(Lime, 4, 0xD4, 0xE1, 0x57); LN_COLOR_DEF(Lime, 5, 0xCD, 0xDC, 0x39); LN_COLOR_DEF(Lime, 6, 0xC0, 0xCA, 0x33); LN_COLOR_DEF(Lime, 7, 0xAF, 0xB4, 0x2B); LN_COLOR_DEF(Lime, 8, 0x9E, 0x9D, 0x24); LN_COLOR_DEF(Lime, 9, 0x82, 0x77, 0x17); LN_COLOR_DEF_A(Lime, 0, 0xF4, 0xFF, 0x81); LN_COLOR_DEF_A(Lime, 1, 0xEE, 0xFF, 0x41); LN_COLOR_DEF_A(Lime, 2, 0xC6, 0xFF, 0x00); LN_COLOR_DEF_A(Lime, 3, 0xAE, 0xEA, 0x00); LN_COLOR_DEF(Yellow, 0, 0xFF, 0xFD, 0xE7); LN_COLOR_DEF(Yellow, 1, 0xFF, 0xF9, 0xC4); LN_COLOR_DEF(Yellow, 2, 0xFF, 0xF5, 0x9D); LN_COLOR_DEF(Yellow, 3, 0xFF, 0xF1, 0x76); LN_COLOR_DEF(Yellow, 4, 0xFF, 0xEE, 0x58); LN_COLOR_DEF(Yellow, 5, 0xFF, 0xEB, 0x3B); LN_COLOR_DEF(Yellow, 6, 0xFD, 0xD8, 0x35); LN_COLOR_DEF(Yellow, 7, 0xFB, 0xC0, 0x2D); LN_COLOR_DEF(Yellow, 8, 0xF9, 0xA8, 0x25); LN_COLOR_DEF(Yellow, 9, 0xF5, 0x7F, 0x17); LN_COLOR_DEF_A(Yellow, 0, 0xFF, 0xFF, 0x8D); LN_COLOR_DEF_A(Yellow, 1, 0xFF, 0xFF, 0x00); LN_COLOR_DEF_A(Yellow, 2, 0xFF, 0xEA, 0x00); LN_COLOR_DEF_A(Yellow, 3, 0xFF, 0xD6, 0x00); LN_COLOR_DEF(Amber, 0, 0xFF, 0xF8, 0xE1); LN_COLOR_DEF(Amber, 1, 0xFF, 0xEC, 0xB3); LN_COLOR_DEF(Amber, 2, 0xFF, 0xE0, 0x82); LN_COLOR_DEF(Amber, 3, 0xFF, 0xD5, 0x4F); LN_COLOR_DEF(Amber, 4, 0xFF, 0xCA, 0x28); LN_COLOR_DEF(Amber, 5, 0xFF, 0xC1, 0x07); LN_COLOR_DEF(Amber, 6, 0xFF, 0xB3, 0x00); LN_COLOR_DEF(Amber, 7, 0xFF, 0xA0, 0x00); LN_COLOR_DEF(Amber, 8, 0xFF, 0x8F, 0x00); LN_COLOR_DEF(Amber, 9, 0xFF, 0x6F, 0x00); LN_COLOR_DEF_A(Amber, 0, 0xFF, 0xE5, 0x7F); LN_COLOR_DEF_A(Amber, 1, 0xFF, 0xD7, 0x40); LN_COLOR_DEF_A(Amber, 2, 0xFF, 0xC4, 0x00); LN_COLOR_DEF_A(Amber, 3, 0xFF, 0xAB, 0x00); LN_COLOR_DEF(Orange, 0, 0xFF, 0xF3, 0xE0); LN_COLOR_DEF(Orange, 1, 0xFF, 0xE0, 0xB2); LN_COLOR_DEF(Orange, 2, 0xFF, 0xCC, 0x80); LN_COLOR_DEF(Orange, 3, 0xFF, 0xB7, 0x4D); LN_COLOR_DEF(Orange, 4, 0xFF, 0xA7, 0x26); LN_COLOR_DEF(Orange, 5, 0xFF, 0x98, 0x00); LN_COLOR_DEF(Orange, 6, 0xFB, 0x8C, 0x00); LN_COLOR_DEF(Orange, 7, 0xF5, 0x7C, 0x00); LN_COLOR_DEF(Orange, 8, 0xEF, 0x6C, 0x00); LN_COLOR_DEF(Orange, 9, 0xE6, 0x51, 0x00); LN_COLOR_DEF_A(Orange, 0, 0xFF, 0xD1, 0x80); LN_COLOR_DEF_A(Orange, 1, 0xFF, 0xAB, 0x40); LN_COLOR_DEF_A(Orange, 2, 0xFF, 0x91, 0x00); LN_COLOR_DEF_A(Orange, 3, 0xFF, 0x6D, 0x00); LN_COLOR_DEF(DeepOrange, 0, 0xFB, 0xE9, 0xE7); LN_COLOR_DEF(DeepOrange, 1, 0xFF, 0xCC, 0xBC); LN_COLOR_DEF(DeepOrange, 2, 0xFF, 0xAB, 0x91); LN_COLOR_DEF(DeepOrange, 3, 0xFF, 0x8A, 0x65); LN_COLOR_DEF(DeepOrange, 4, 0xFF, 0x70, 0x43); LN_COLOR_DEF(DeepOrange, 5, 0xFF, 0x57, 0x22); LN_COLOR_DEF(DeepOrange, 6, 0xF4, 0x51, 0x1E); LN_COLOR_DEF(DeepOrange, 7, 0xE6, 0x4A, 0x19); LN_COLOR_DEF(DeepOrange, 8, 0xD8, 0x43, 0x15); LN_COLOR_DEF(DeepOrange, 9, 0xBF, 0x36, 0x0C); LN_COLOR_DEF_A(DeepOrange, 0, 0xFF, 0x9E, 0x80); LN_COLOR_DEF_A(DeepOrange, 1, 0xFF, 0x6E, 0x40); LN_COLOR_DEF_A(DeepOrange, 2, 0xFF, 0x3D, 0x00); LN_COLOR_DEF_A(DeepOrange, 3, 0xDD, 0x2C, 0x00); LN_COLOR_DEF(Brown, 0, 0xEF, 0xEB, 0xE9); LN_COLOR_DEF(Brown, 1, 0xD7, 0xCC, 0xC8); LN_COLOR_DEF(Brown, 2, 0xBC, 0xAA, 0xA4); LN_COLOR_DEF(Brown, 3, 0xA1, 0x88, 0x7F); LN_COLOR_DEF(Brown, 4, 0x8D, 0x6E, 0x63); LN_COLOR_DEF(Brown, 5, 0x79, 0x55, 0x48); LN_COLOR_DEF(Brown, 6, 0x6D, 0x4C, 0x41); LN_COLOR_DEF(Brown, 7, 0x5D, 0x40, 0x37); LN_COLOR_DEF(Brown, 8, 0x4E, 0x34, 0x2E); LN_COLOR_DEF(Brown, 9, 0x3E, 0x27, 0x23); LN_COLOR_DEF_A(Brown, 0, 0x00, 0x00, 0x00); LN_COLOR_DEF_A(Brown, 1, 0x00, 0x00, 0x00); LN_COLOR_DEF_A(Brown, 2, 0x00, 0x00, 0x00); LN_COLOR_DEF_A(Brown, 3, 0x00, 0x00, 0x00); LN_COLOR_DEF(Grey, 0, 0xFA, 0xFA, 0xFA); LN_COLOR_DEF(Grey, 1, 0xF5, 0xF5, 0xF5); LN_COLOR_DEF(Grey, 2, 0xEE, 0xEE, 0xEE); LN_COLOR_DEF(Grey, 3, 0xE0, 0xE0, 0xE0); LN_COLOR_DEF(Grey, 4, 0xBD, 0xBD, 0xBD); LN_COLOR_DEF(Grey, 5, 0x9E, 0x9E, 0x9E); LN_COLOR_DEF(Grey, 6, 0x75, 0x75, 0x75); LN_COLOR_DEF(Grey, 7, 0x61, 0x61, 0x61); LN_COLOR_DEF(Grey, 8, 0x42, 0x42, 0x42); LN_COLOR_DEF(Grey, 9, 0x21, 0x21, 0x21); LN_COLOR_DEF_A(Grey, 0, 0x00, 0x00, 0x00); LN_COLOR_DEF_A(Grey, 1, 0x00, 0x00, 0x00); LN_COLOR_DEF_A(Grey, 2, 0x00, 0x00, 0x00); LN_COLOR_DEF_A(Grey, 3, 0x00, 0x00, 0x00); Diego999/Artificial-Neural-NetworkNeuralNetwork/neuron.cpp1-10 #include "neuron.h" #include "../Utils/utils.h" #include #include #include const double Neuron::MAXIMUM_WEIGHT = 1.0; const double Neuron::MINIMUM_WEIGHT = -1.0; double Neuron::squashingFunction(double x) { return 1.0/(1.0+exp(-x)); } Neuron::Neuron(int nbInputs):m_nbInputs(nbInputs), m_delta(0), m_output(0), m_weights(nbInputs+1), m_prevDeltaWeights(nbInputs+1) { assert(nbInputs > 0); initializeWeights(); initializePrevDeltaWeights(); } Neuron::~Neuron() { } double Neuron::computeOutput(const std::vector& inputs) { double sum = 0.0; for(size_t i = 0; i < inputs.size(); ++i) sum += m_weights[i+1]*inputs[i]; // i+1 -> avoid threshold sum += m_weights[0]; //xi = 1.0 m_output = squashingFunction(sum); return m_output; } void Neuron::initializeWeights() { m_weights.clear(); for(auto& val : ann_random::randDoubleList(MINIMUM_WEIGHT, MAXIMUM_WEIGHT, m_nbInputs+1)) m_weights.push_back(val); } void Neuron::initializePrevDeltaWeights() { m_prevDeltaWeights.clear(); for(size_t i = 0; i < m_weights.size(); ++i) m_prevDeltaWeights.push_back(0); } #ifndef FLYCONTROLS #define FLYCONTROLS // MARE #include "Components/Rigidbody.hpp" #include "Components/Transform.hpp" #include "Mare.hpp" #include "Systems.hpp" namespace mare { /** * @brief A ControlsSystem that operates on Transform and Rigidbody Components. * @details The FlyControls System will allow the user to change the view of on * Entity by using the mouse movements to look around and the W,A,S,and D keys * to move the Entity. Any Entity that uses this System must inherit from the * Transform and Rigidbody Components. * */ class FlyControls : public ControlsSystem { float speed = 1.0f; bool on_key(const RendererInput &input, Transform *transform, Rigidbody *rigidbody) override { if (rigidbody) { if (input.LEFT_SHIFT_PRESSED) { speed = 2.5f; } else { speed = 1.0f; } float x = 0.0f; float y = 0.0f; if (input.W_PRESSED) { y += 1.0f; } if (input.S_PRESSED) { y -= 1.0f; } if (input.D_PRESSED) { x += 1.0f; } if (input.A_PRESSED) { x -= 1.0f; } if (x || y) { x /= sqrtf(x * x + y * y); y /= sqrtf(x * x + y * y); } glm::vec3 dir = transform->get_forward_vector(); glm::vec3 up = transform->get_up_vector(); glm::vec3 right = glm::normalize(glm::cross(dir, up)); glm::vec3 velocity = (dir * y + right * x) * speed; rigidbody->linear_velocity = velocity; } // pass though to next callback return false; } bool on_mouse_move(const RendererInput &input, Transform *transform, Rigidbody *rigidbody) override { float sensitivity = 300.0f; float dtheta = float(input.mouse_vel.y) / sensitivity; float dphi = -float(input.mouse_vel.x) / sensitivity; glm::vec3 dir = transform->get_forward_vector(); float theta = acosf(dir.z); float phi = atan2f(dir.y, dir.x); theta = glm::clamp(theta + dtheta, 0.01f, math::PI - 0.01f); phi += dphi; dir = glm::vec3(sinf(theta) * cosf(phi), sinf(theta) * sinf(phi), cosf(theta)); transform->face_towards(dir, {0.0f, 0.0f, 1.0f}); return false; } bool on_mouse_button(const RendererInput &input, Transform *transform, Rigidbody *rigidbody) override { return false; } bool on_mouse_wheel(const RendererInput &input, Transform *transform, Rigidbody *rigidbody) override { return false; } bool on_resize(const RendererInput &input, Transform *transform, Rigidbody *rigidbody) override { return false; } }; } // namespace mare #endifybbhwxfj/block-db #include "common/error_code.h" template<> enum_strings::e2s_t enum_strings::enum2str = { {EC_OK, "EC_OK"}, {EC_TX_ABORT, "EC_TX_ABORT"}, {EC_MARSHALL_ERROR, "EC_MARSHALL_ERROR"}, {EC_BUFFER_OVERFLOW, "EC_BUFFER_OVERFLOW"}, {EC_INSUFFICIENT_SPACE, "EC_INSUFFICIENT_SPACE"}, {EC_MESSAGE_SIZE_TOO_LARGE, "EC_MESSAGE_SIZE_TOO_LARGE"}, {EC_LOCK_ERROR, "EC_LOCK_ERROR"}, {EC_EXSISTING_TRANSACTION, "EC_EXSISTING_TRANSACTION"}, {EC_NO_SUCH_TRANSACTION, "EC_NO_SUCH_TRANSACTION"}, {EC_IO_ERROR, "EC_IO_ERROR"}, {EC_CONFIG_ERROR, "EC_CONFIG_ERROR"}, {EC_UNKNOWN_TABLE_ID, "EC_UNKNOWN_TABLE_ID"}, {EC_NOT_LEADER, "EC_NOT_LEADER"}, {EC_FLOW_CONTROL, "EC_FLOW_CONTROL"}, {EC_UNKNOWN, "EC_UNKNOWN"}, {EC_SYSTEM_ERROR, "EC_SYSTEM_ERROR"}, {EC_NOT_IMPLEMENTED, "EC_NOT_IMPLEMENTED"}, {EC_PRECONDITION_ERROR, "EC_PRECONDITION_ERROR"}, {EC_INVALID_ARGUMENT, "EC_INVALID_ARGUMENT"}, {EC_CANCELED_ERROR, "EC_CANCELED_ERROR"}, {EC_NOT_FOUND_ERROR, "EC_NOT_FOUND_ERROR"}, {EC_PERMISSION_ERROR, "EC_PERMISSION_ERROR"}, {EC_INFEASIBLE_ERROR, "EC_INFEASIBLE_ERROR"}, {EC_DUPLICATION_ERROR, "EC_DUPLICATION_ERROR"}, {EC_BROKEN_DATA_ERROR, "EC_BROKEN_DATA_ERROR"}, {EC_NETWORK_ERROR, "EC_NETWORK_ERROR"}, {EC_NET_UNCONNECTED, "EC_NET_UNCONNECTED"}, {EC_NET_CANNOT_FIND_CONNECTION, "EC_NET_CANNOT_FIND_CONNECTION"}, {EC_NET_RESOLVE_ADDRESS_FAIL, "EC_NET_RESOLVE_ADDRESS_FAIL"}, {EC_UNKNOWN_MESSAGE_TYPE, "EC_UNKNOWN_MESSAGE_TYPE"}, {EC_APPLICATION_ERROR, "EC_APPLICATION_ERROR"}, {EC_MESSAGE_HASH_ERROR, "EC_MESSAGE_HASH_ERROR"}, {EC_MESSAGE_LENGTH_ERROR, "EC_MESSAGE_LENGTH_ERROR"}, {EC_MESSAGE_MAGIC_ERROR, "EC_MESSAGE_MAGIC_ERROR"}, {EC_MESSAGE_ID_ERROR, "EC_MESSAGE_ID_ERROR"}, {EC_CASCADE, "EC_CASCADE"}, {EC_DEADLOCK, "EC_DEADLOCK"}, {EC_APPEND_LOG_ERROR, "EC_APPEND_LOG_ERROR"}, }; #include "pch.h" #include "ZenUnitTestUtils/EqualizersAndRandoms/TestPhaseResultEqualizerAndRandom.h" #include "ZenUnitTestUtils/EqualizersAndRandoms/AnomalyOrExceptionEqualizerAndRandom.h" namespace ZenUnit { void Equalizer::AssertEqual( const TestPhaseResult& expectedTestPhaseResult, const TestPhaseResult& actualTestPhaseResult) { FIELDS_ARE_EQUAL(expectedTestPhaseResult, actualTestPhaseResult, testPhase); FIELDS_ARE_EQUAL(expectedTestPhaseResult, actualTestPhaseResult, testOutcome); FIELDS_ARE_EQUAL(expectedTestPhaseResult, actualTestPhaseResult, elapsedMicroseconds); POINTEES_ARE_EQUAL(expectedTestPhaseResult.anomalyOrException, actualTestPhaseResult.anomalyOrException); } TestPhaseResult TestableRandomTestPhaseResult(const RandomGenerator* randomGenerator) { TestPhaseResult randomTestPhaseResult; randomTestPhaseResult.testPhase = static_cast(randomGenerator->Enum(static_cast(TestPhase::MaxValue))); randomTestPhaseResult.testOutcome = static_cast(randomGenerator->Enum(static_cast(TestOutcome::MaxValue))); randomTestPhaseResult.elapsedMicroseconds = randomGenerator->Unsigned(); randomTestPhaseResult.anomalyOrException = nullptr; return randomTestPhaseResult; } template<> TestPhaseResult Random() { return TestableRandomTestPhaseResult(RandomGenerator::Instance()); } } // ------------------------------------------------------------------------------------------------ // Copyright (c) 2016 Patrick "Rick" Gilliland // // 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. // // This license shall be perpetual and irrevocable. // ------------------------------------------------------------------------------------------------ #include "precompiled.h" #include "SlickWICGUIDs.h" namespace Slick { // -------------------------------------------------------------------------------------------- void GUIDToString( GUID id, std::wstring &str ) { OLECHAR* chars; ::StringFromCLSID( id, &chars ); std::wstringstream stream; stream << chars; ::CoTaskMemFree( chars ); str = stream.str(); } // -------------------------------------------------------------------------------------------- // Vendor // -------------------------------------------------------------------------------------------- const wchar_t * WICGUID::Str::Vendor = L"{B27648CC-7DBD-4632-B5F1-C3CFBC05E753}"; const GUID WICGUID::ID::Vendor = { 0xb27648cc, 0x7dbd, 0x4632, { 0xb5, 0xf1, 0xc3, 0xcf, 0xbc, 0x5, 0xe7, 0x53 } }; // -------------------------------------------------------------------------------------------- // Decoder // -------------------------------------------------------------------------------------------- const wchar_t * WICGUID::Str::Decoder = L"{6C7FB17C-A1B0-4919-98D7-95271ACE5260}"; const GUID WICGUID::ID::Decoder = { 0x6c7fb17c, 0xa1b0, 0x4919, { 0x98, 0xd7, 0x95, 0x27, 0x1a, 0xce, 0x52, 0x60 } }; // -------------------------------------------------------------------------------------------- // Decoder_TGA // -------------------------------------------------------------------------------------------- const wchar_t * WICGUID::Str::Decoder_TGA = L"{8710BE66-B01A-4025-8FC2-36027496B887}"; const GUID WICGUID::ID::Decoder_TGA = { 0x8710be66, 0xb01a, 0x4025, { 0x8f, 0xc2, 0x36, 0x2, 0x74, 0x96, 0xb8, 0x87 } }; // -------------------------------------------------------------------------------------------- // File_TGA // -------------------------------------------------------------------------------------------- const wchar_t * WICGUID::Str::File_TGA = L"{C750FDD0-F191-4903-A1BE-87B80471440B}"; const GUID WICGUID::ID::File_TGA = { 0xc750fdd0, 0xf191, 0x4903, { 0xa1, 0xbe, 0x87, 0xb8, 0x4, 0x71, 0x44, 0xb } }; // -------------------------------------------------------------------------------------------- // Decoder_PSD // -------------------------------------------------------------------------------------------- const wchar_t * WICGUID::Str::Decoder_PSD = L"{646F563B-4F45-4EB0-AB29-D261BAD55818}"; const GUID WICGUID::ID::Decoder_PSD = { 0x646f563b, 0x4f45, 0x4eb0, { 0xab, 0x29, 0xd2, 0x61, 0xba, 0xd5, 0x58, 0x18 } }; // -------------------------------------------------------------------------------------------- // File_PSD // -------------------------------------------------------------------------------------------- const wchar_t * WICGUID::Str::File_PSD = L"{E0958E58-50F5-45BD-99CA-8B5DC05770D8}"; const GUID WICGUID::ID::File_PSD = { 0xe0958e58, 0x50f5, 0x45bd, { 0x99, 0xca, 0x8b, 0x5d, 0xc0, 0x57, 0x70, 0xd8 } }; // -------------------------------------------------------------------------------------------- // Decoder_DDS // -------------------------------------------------------------------------------------------- const wchar_t * WICGUID::Str::Decoder_DDS = L"{58CBFCB6-0645-48D8-8912-E2F5A9F7C060}"; const GUID WICGUID::ID::Decoder_DDS = { 0x58cbfcb6, 0x645, 0x48d8, { 0x89, 0x12, 0xe2, 0xf5, 0xa9, 0xf7, 0xc0, 0x60 } }; // -------------------------------------------------------------------------------------------- // File_DDS // -------------------------------------------------------------------------------------------- const wchar_t * WICGUID::Str::File_DDS = L"{F7C9AB44-C00E-4321-A1CC-D35DFBC12E9A}"; const GUID WICGUID::ID::File_DDS = { 0xf7c9ab44, 0xc00e, 0x4321, { 0xa1, 0xcc, 0xd3, 0x5d, 0xfb, 0xc1, 0x2e, 0x9a } }; // -------------------------------------------------------------------------------------------- // Explorer // -------------------------------------------------------------------------------------------- const wchar_t * CommonGUID::Str::Explorer = L"{e357fccd-a995-4576-b01f-234630154e96}"; const wchar_t * CommonGUID::Str::WIC = L"{7ED96837-96F0-4812-B211-F13C24117ED3}"; const wchar_t * CommonGUID::Str::Thumbnail = L"{C7657C4A-9F68-40fa-A4DF-96BC08EB3551}";\ const wchar_t * CommonGUID::Str::Gallery = L"{FFE2A43C-56B9-4bf5-9A79-CC6D4285608A}"; const wchar_t * CommonGUID::Str::WICID_32BitRGBAlpha = L"{6fddc324-4e03-4bfe-b185-3d77768dc92e}"; const wchar_t * CommonGUID::Str::WICID_24BitRGB = L"{6fddc324-4e03-4bfe-b185-3d77768dc920}"; } 100-1000 #include "HelloPolycodeApp.h" HelloPolycodeApp::HelloPolycodeApp(PolycodeView *view) : EventHandler() { core = new POLYCODE_CORE(view, 640,480,false,true,6,16,90, 0, true); CoreServices::getInstance()->getResourceManager()->addArchive("Resources/default.pak"); CoreServices::getInstance()->getResourceManager()->addDirResource("default", false); CoreServices::getInstance()->getResourceManager()->addDirResource("Resources", false); scene = new Scene(); ScenePrimitive *ground = new ScenePrimitive(ScenePrimitive::TYPE_PLANE, 5,5); ground->setMaterialByName("GroundMaterial"); scene->addEntity(ground); torus = new ScenePrimitive(ScenePrimitive::TYPE_TORUS, 0.8,0.3,30,20); torus->setMaterialByName("CubeMaterial"); torus->setPosition(0.0, 0.5, 0.0); scene->addEntity(torus); SceneLight *light = new SceneLight(SceneLight::POINT_LIGHT, scene, 5); light->setPosition(3,2,3); light->setLightColor(1,0,0); scene->addLight(light); light = new SceneLight(SceneLight::POINT_LIGHT, scene, 5); light->setPosition(-3,2,3); light->setLightColor(0,1,0); scene->addLight(light); light = new SceneLight(SceneLight::POINT_LIGHT, scene, 5); light->setPosition(-3,2,-3); light->setLightColor(0,0,1); scene->addLight(light); light = new SceneLight(SceneLight::POINT_LIGHT, scene, 5); light->setPosition(3,2,-3); light->setLightColor(1,0,1); scene->addLight(light); lights = new Entity(); scene->addChild(lights); light = new SceneLight(SceneLight::SPOT_LIGHT, scene, 4); light->setPosition(0,4,1); light->setLightColor(1,1,0); scene->addLight(light); lights->addChild(light); light->lookAt(Vector3(0,0,0)); light->enableShadows(true); light->getSpotlightCamera()->frustumCulling = false; light = new SceneLight(SceneLight::SPOT_LIGHT, scene, 4); light->setPosition(0,4,-1); light->setLightColor(0,1,1); scene->addLight(light); lights->addChild(light); light->lookAt(Vector3(0,0,0)); light->enableShadows(true); light->getSpotlightCamera()->frustumCulling = false; cameraRotation = 0.0; } HelloPolycodeApp::~HelloPolycodeApp() { } bool HelloPolycodeApp::Update() { lights->Yaw(core->getElapsed() * 10.0); torus->Roll(core->getElapsed() * 10.0); cameraRotation += core->getElapsed() * 0.1; scene->getDefaultCamera()->setPosition(sin(cameraRotation) * 7.0, 7.0,cos(cameraRotation) * 7.0); scene->getDefaultCamera()->lookAt(Vector3(0,0,0)); return core->updateAndRender(); } 0 /* Reading.cpp - Library for sensor measurement. Created by , January 20, 2015. Released into the public domain. */ #include "Arduino.h" #include "Reading.h" // constructs a standard averaged reading Reading::Reading(byte pin, MeasureFunc mf, unsigned long period) { _sensorPin = pin; _fnMeasure = mf; _period = period; setup(); } // constructs a averaged reading with a custom smoothing factor Reading::Reading(byte pin, MeasureFunc mf, unsigned long period, byte smooth) { _sensorPin = pin; _fnMeasure = mf; _period = period; _smooth = smooth; setup(); } // performs common constructor setup void Reading::setup() { _firstTime = true; _lastMillis = 0; } //------------------------------------------------------------------------------ // loop to perform delagate measurement // void Reading::measure() { unsigned long timePassed = millis() - _lastMillis; if (timePassed < 0) { _lastMillis = millis(); } if (timePassed < 0 || timePassed > _period) { int data = _fnMeasure(_sensorPin); _reading = (_smooth != NO_SMOOTHING) ? smoothedAverage(_reading, data) : data; } } //------------------------------------------------------------------------------ // returns the current reading // int Reading::reading() { return _reading; } //------------------------------------------------------------------------------ // perform simple smoothing as a running average // int Reading::smoothedAverage(int prev, int next) { return (_firstTime) ? next : ((_smooth - 1) * prev + next + _smooth / 2) / _smooth; } // // 116_populating_next_right_pointers_in_each_node.cpp // leetcode_tree // // Created by Hadley on 13.07.20. // Copyright © 2020 Hadley. All rights reserved. // #include #include #include #include #include #include #include #include #include #include #include using namespace std; // Definition for a Node. class Node { public: int val; Node* left; Node* right; Node* next; Node() : val(0), left(NULL), right(NULL), next(NULL) {} Node(int _val) : val(_val), left(NULL), right(NULL), next(NULL) {} Node(int _val, Node* _left, Node* _right, Node* _next) : val(_val), left(_left), right(_right), next(_next) {} }; class Solution { public: Node* connect(Node* root) { vector> res; if(root==NULL) return {}; queue q; q.push(root); while(!q.empty()){ vector v; auto size=q.size(); while(size--){ Node *node=q.front(); q.pop(); v.push_back(node); if(node->left){ q.push(node->left); } if(node->right){ q.push(node->right); } } res.push_back(v); } for(auto &x:res){ vector r=x; for(int i=0;inext=r[i+1]; } } return root; } }; cccc/cccc_ext.cc /* CCCC - C and C++ Code Counter Copyright (C) 1994-2005 () 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 St, Fifth Floor, Boston, MA 02110-1301 USA */ /* * cccc_ext.cc */ #include "cccc_itm.h" #include "cccc_ext.h" #include "cccc_db.h" #include "cccc_utl.h" unsigned int CCCC_Extent::nextkey=0; CCCC_Extent::CCCC_Extent() { v=vINVALID; ut=utINVALID; extkey=++nextkey; } CCCC_Extent::CCCC_Extent(CCCC_Item& is) { char v_as_char='!', ut_as_char='!'; if( is.Extract(filename) && is.Extract(linenumber) && is.Extract(description) && is.Extract(flags) && is.Extract(count_buffer) && is.Extract(v_as_char) && is.Extract(ut_as_char) ) { v=(Visibility) v_as_char; ut=(UseType) ut_as_char; } else { // we can trust the string constructor to give us empty strings, // but we need to initialise these v=vDONTKNOW; ut=utDONTKNOW; } extkey=++nextkey; } int CCCC_Extent::AddToItem(CCCC_Item& item) { int retval=FALSE; if( item.Insert(filename) && item.Insert(linenumber) && item.Insert(description) && item.Insert(flags) && item.Insert(count_buffer) && item.Insert((char) v) && item.Insert((char) ut) ) { retval=TRUE; } return retval; } int CCCC_Extent::GetFromItem(CCCC_Item &item) { int retval=FALSE; char v_as_char, ut_as_char; if( item.Extract(filename) && item.Extract(linenumber) && item.Extract(description) && item.Extract(flags) && item.Extract(count_buffer) && item.Extract(v_as_char) && item.Extract(ut_as_char) ) { v = (Visibility) v_as_char; ut = (UseType) ut_as_char; retval=TRUE; } return retval; } string CCCC_Extent::name(int level) const { string rtnbuf; rtnbuf=""; switch(level) { case nlFILENAME: rtnbuf=filename; break; case nlLINENUMBER: rtnbuf=linenumber; break; case nlDESCRIPTION: rtnbuf=description; break; case nlSEARCH: case nlRANK: // Extents have no meaningful internal primary key. // We never want two extents to have the same // key, so we use the running number extkey // which is initialized in both constructors. // This should cause extents to sort in order of // their creation, which is fine. char buf[16]; sprintf(buf,"%015d",extkey); rtnbuf=buf; break; default: rtnbuf+=filename; rtnbuf+=":"; rtnbuf+=linenumber; } return rtnbuf.c_str(); } string CCCC_Extent::key() const { return name(nlRANK); } int CCCC_Extent::get_count(const char* count_tag) { int retval=0; char local_count_buffer[100], *count_tag_ptr, *count_value_ptr; strcpy(local_count_buffer,count_buffer.c_str()); count_tag_ptr=strtok(local_count_buffer,":"); while(count_tag_ptr!=NULL) { count_value_ptr=strtok(NULL," "); if(strcmp(count_tag_ptr, count_tag) ==0) { retval+=atoi(count_value_ptr); } count_tag_ptr=strtok(NULL,":"); } return retval; } VersiraSec/epsilon-cfw #include #include namespace Poincare { bool NAryInfixExpressionNode::childAtIndexNeedsUserParentheses(const Expression & child, int childIndex) const { /* Expressions like "-2" require parentheses in Addition/Multiplication except * when they are the first operand. */ if (childIndex != 0 && ((child.isNumber() && static_cast(child).sign() == Sign::Negative) || child.type() == Type::Opposite)) { return true; } if (child.type() == Type::Conjugate) { return childAtIndexNeedsUserParentheses(child.childAtIndex(0), childIndex); } return false; } int NAryInfixExpressionNode::simplificationOrderSameType(const ExpressionNode * e, bool ascending, bool ignoreParentheses) const { int m = numberOfChildren(); int n = e->numberOfChildren(); for (int i = 1; i <= m; i++) { // The NULL node is the least node type. if (n < i) { return 1; } int order = SimplificationOrder(childAtIndex(m-i), e->childAtIndex(n-i), ascending, ignoreParentheses); if (order != 0) { return order; } } // The NULL node is the least node type. if (n > m) { return ascending ? -1 : 1; } return 0; } int NAryInfixExpressionNode::simplificationOrderGreaterType(const ExpressionNode * e, bool ascending, bool ignoreParentheses) const { int m = numberOfChildren(); if (m == 0) { return -1; } /* Compare e to last term of hierarchy. */ int order = SimplificationOrder(childAtIndex(m-1), e, ascending, ignoreParentheses); if (order != 0) { return order; } if (m > 1) { return ascending ? 1 : -1; } return 0; } } #include "../../../def_submodule.hpp" #include "IceRay/material/compute/instruction.hpp" #include "IceRay/material/compute/illumination/hs_phong.hpp" void expose_IceRay_material_illumination_hs_phong() { typedef GS_DDMRM::S_IceRay::S_type::GT_size GTs_size; typedef GS_DDMRM::S_IceRay::S_type::GT_scalar GTs_scalar; typedef GS_DDMRM::S_IceRay::S_type::S_color::GT_scalar GTs_color; typedef GS_DDMRM::S_IceRay::S_type::S_coord::GT_scalar3D GTs_coord3D; typedef GS_DDMRM::S_IceRay::S_material::S_compute::GC_instruction GTs_instruction; typedef GS_DDMRM::S_IceRay::S_material::S_compute::S_illumination::S_HeidrichSeidel::GC_Phong GTs_HeidrichSeidelPhong; //MAKE_SUBMODULE( IceRay ); MAKE_SUBMODULE( core ); MAKE_SUBMODULE( material ); MAKE_SUBMODULE( illumination ); typedef bool (GTs_HeidrichSeidelPhong::*Tf_setScalar )( GTs_scalar const& ); typedef GTs_scalar const& (GTs_HeidrichSeidelPhong::*Tf_getScalar )( void ) const; typedef bool (GTs_HeidrichSeidelPhong::*Tf_setColor )( GTs_color const& ); typedef GTs_color const& (GTs_HeidrichSeidelPhong::*Tf_getColor )( void ) const; typedef bool (GTs_HeidrichSeidelPhong::*Tf_setCoord3D )( GTs_coord3D const& ); typedef GTs_coord3D const& (GTs_HeidrichSeidelPhong::*Tf_getCoord3D )( void ) const; typedef boost::python::class_ > Tf_this; boost::python::object I_this = Tf_this( "MaterialIlluminationHSPhong") .def( boost::python::init<>() ) .def( boost::python::init() ) //.def( "interval", >s_HeidrichSeidelPhong::F_get, boost::python::return_value_policy() ) //.def( "interval", >s_HeidrichSeidelPhong::F_set ) ; boost::python::scope I_scope = I_this; boost::python::enum_( "Input" ) .value( "SpotBegin", GTs_HeidrichSeidelPhong::En_inSize_SpotBegin ) .value( "SpotEnd", GTs_HeidrichSeidelPhong::En_inSize_SpotEnd ) .value( "Specular", GTs_HeidrichSeidelPhong::En_inColor_Specular ) .value( "Shininess", GTs_HeidrichSeidelPhong::En_inColor_Shininess ) .value( "Groove", GTs_HeidrichSeidelPhong::En_inCoord_Groove ) .value( "point", GTs_HeidrichSeidelPhong::En_inCoord_Point ) .value( "normal", GTs_HeidrichSeidelPhong::En_inCoord_Normal ) .export_values() ; boost::python::enum_( "Output" ) .value( "result", GTs_HeidrichSeidelPhong::En_outColor_result ) ; } CodeRancher/offcenter_oanda /** * 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 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 HomeConversions.hpp * @author * * @date 12-07-2020 */ #ifndef OANDA_V20_PRICING_HOMECONVERSIONS_HPP #define OANDA_V20_PRICING_HOMECONVERSIONS_HPP #include #include #include "oanda/v20/primitives/PrimitivesDefinitions.hpp" namespace oanda { namespace v20 { namespace pricing { /** * HomeConversions represents the factors to use to convert quantities of a given currency into the Account’s home currency. The conversion factor depends on the scenario the conversion is required for. * HomeConversions is an application/json object with the following Schema: */ struct HomeConversions { /** * The currency to be converted into the home currency. */ oanda::v20::primitives::Currency currency; /** * The factor used to convert any gains for an Account in the specified * currency into the Account’s home currency. This would include positive * realized P/L and positive financing amounts. Conversion is performed by * multiplying the positive P/L by the conversion factor. */ oanda::v20::primitives::DecimalNumber accountGain; /** * The factor used to convert any losses for an Account in the specified * currency into the Account’s home currency. This would include negative * realized P/L and negative financing amounts. Conversion is performed by * multiplying the positive P/L by the conversion factor. */ oanda::v20::primitives::DecimalNumber accountLoss; /** * The factor used to convert a Position or Trade Value in the specified * currency into the Account’s home currency. Conversion is performed by * multiplying the Position or Trade Value by the conversion factor. */ oanda::v20::primitives::DecimalNumber positionValue; }; } /* namespace pricing */ } /* namespace v20 */ } /* namespace oanda */ #endif /* OANDA_V20_PRICING_HOMECONVERSIONS_HPP */ #include #include #include "SkColorFilter.h" #include "SkImageFilter.h" #include "SkMaskFilter.h" #include "SkPaint.h" #include "SkPathEffect.h" #include "SkShader.h" #include "interop.hh" static void deletePaint(SkPaint* paint) { delete paint; } extern "C" JNIEXPORT jlong JNICALL Java_org_jetbrains_skia_PaintKt_Paint_1nGetFinalizer (JNIEnv* env, jclass jclass) { return static_cast(reinterpret_cast(&deletePaint)); } extern "C" JNIEXPORT jlong JNICALL Java_org_jetbrains_skia_PaintKt_Paint_1nMake (JNIEnv* env, jclass jclass) { SkPaint* obj = new SkPaint(); obj->setAntiAlias(true); return reinterpret_cast(obj); } extern "C" JNIEXPORT jlong JNICALL Java_org_jetbrains_skia_PaintKt_Paint_1nMakeClone (JNIEnv* env, jclass jclass, jlong ptr) { SkPaint* instance = reinterpret_cast(static_cast(ptr)); SkPaint* obj = new SkPaint(*instance); return reinterpret_cast(obj); } extern "C" JNIEXPORT jboolean JNICALL Java_org_jetbrains_skia_PaintKt_Paint_1nEquals (JNIEnv* env, jclass jclass, jlong aPtr, jlong bPtr) { SkPaint* a = reinterpret_cast(static_cast(aPtr)); SkPaint* b = reinterpret_cast(static_cast(bPtr)); return *a == *b; } extern "C" JNIEXPORT void JNICALL Java_org_jetbrains_skia_PaintKt_Paint_1nReset (JNIEnv* env, jclass jclass, jlong ptr) { SkPaint* instance = reinterpret_cast(static_cast(ptr)); instance->reset(); } extern "C" JNIEXPORT jboolean JNICALL Java_org_jetbrains_skia_PaintKt__1nIsAntiAlias (JNIEnv* env, jclass jclass, jlong ptr) { SkPaint* instance = reinterpret_cast(static_cast(ptr)); return instance->isAntiAlias(); } extern "C" JNIEXPORT void JNICALL Java_org_jetbrains_skia_PaintKt__1nSetAntiAlias (JNIEnv* env, jclass jclass, jlong ptr, jboolean value) { SkPaint* instance = reinterpret_cast(static_cast(ptr)); instance->setAntiAlias(value); } extern "C" JNIEXPORT jboolean JNICALL Java_org_jetbrains_skia_PaintKt__1nIsDither (JNIEnv* env, jclass jclass, jlong ptr) { SkPaint* instance = reinterpret_cast(static_cast(ptr)); return instance->isDither(); } extern "C" JNIEXPORT void JNICALL Java_org_jetbrains_skia_PaintKt__1nSetDither (JNIEnv* env, jclass jclass, jlong ptr, jboolean value) { SkPaint* instance = reinterpret_cast(static_cast(ptr)); instance->setDither(value); } extern "C" JNIEXPORT jint JNICALL Java_org_jetbrains_skia_PaintKt_Paint_1nGetColor (JNIEnv* env, jclass jclass, jlong ptr) { SkPaint* instance = reinterpret_cast(static_cast(ptr)); return instance->getColor(); } extern "C" JNIEXPORT void JNICALL Java_org_jetbrains_skia_PaintKt__1nSetColor (JNIEnv* env, jclass jclass, jlong ptr, jint color) { SkPaint* instance = reinterpret_cast(static_cast(ptr)); instance->setColor(color); } extern "C" JNIEXPORT jobject JNICALL Java_org_jetbrains_skia_PaintKt__1nGetColor4f (JNIEnv* env, jclass jclass, jlong ptr) { SkPaint* instance = reinterpret_cast(static_cast(ptr)); SkColor4f color = instance->getColor4f(); return env->NewObject(skija::Color4f::cls, skija::Color4f::ctor, color.fR, color.fG, color.fB, color.fA); } extern "C" JNIEXPORT void JNICALL Java_org_jetbrains_skia_PaintKt__1nSetColor4f (JNIEnv* env, jclass jclass, jlong ptr, jfloat r, jfloat g, jfloat b, jfloat a, jlong colorSpacePtr) { SkPaint* instance = reinterpret_cast(static_cast(ptr)); SkColorSpace* colorSpace = reinterpret_cast(static_cast(colorSpacePtr)); instance->setColor4f({r, g, b, a}, colorSpace); } extern "C" JNIEXPORT jint JNICALL Java_org_jetbrains_skia_PaintKt__1nGetMode (JNIEnv* env, jclass jclass, jlong ptr) { SkPaint* instance = reinterpret_cast(static_cast(ptr)); return static_cast(instance->getStyle()); } extern "C" JNIEXPORT void JNICALL Java_org_jetbrains_skia_PaintKt__1nSetMode (JNIEnv* env, jclass jclass, jlong ptr, jint mode) { SkPaint* instance = reinterpret_cast(static_cast(ptr)); instance->setStyle(static_cast(mode)); } extern "C" JNIEXPORT jfloat JNICALL Java_org_jetbrains_skia_PaintKt__1nGetStrokeWidth (JNIEnv* env, jclass jclass, jlong ptr) { SkPaint* instance = reinterpret_cast(static_cast(ptr)); return instance->getStrokeWidth(); } extern "C" JNIEXPORT void JNICALL Java_org_jetbrains_skia_PaintKt__1nSetStrokeWidth (JNIEnv* env, jclass jclass, jlong ptr, jfloat width) { SkPaint* instance = reinterpret_cast(static_cast(ptr)); instance->setStrokeWidth(width); } extern "C" JNIEXPORT jfloat JNICALL Java_org_jetbrains_skia_PaintKt__1nGetStrokeMiter (JNIEnv* env, jclass jclass, jlong ptr) { SkPaint* instance = reinterpret_cast(static_cast(ptr)); return instance->getStrokeMiter(); } extern "C" JNIEXPORT void JNICALL Java_org_jetbrains_skia_PaintKt__1nSetStrokeMiter (JNIEnv* env, jclass jclass, jlong ptr, jfloat miter) { SkPaint* instance = reinterpret_cast(static_cast(ptr)); instance->setStrokeMiter(miter); } extern "C" JNIEXPORT jint JNICALL Java_org_jetbrains_skia_PaintKt__1nGetStrokeCap (JNIEnv* env, jclass jclass, jlong ptr) { SkPaint* instance = reinterpret_cast(static_cast(ptr)); return static_cast(instance->getStrokeCap()); } extern "C" JNIEXPORT void JNICALL Java_org_jetbrains_skia_PaintKt__1nSetStrokeCap (JNIEnv* env, jclass jclass, jlong ptr, jint cap) { SkPaint* instance = reinterpret_cast(static_cast(ptr)); instance->setStrokeCap(static_cast(cap)); } extern "C" JNIEXPORT jint JNICALL Java_org_jetbrains_skia_PaintKt__1nGetStrokeJoin (JNIEnv* env, jclass jclass, jlong ptr) { SkPaint* instance = reinterpret_cast(static_cast(ptr)); return static_cast(instance->getStrokeJoin()); } extern "C" JNIEXPORT void JNICALL Java_org_jetbrains_skia_PaintKt__1nSetStrokeJoin (JNIEnv* env, jclass jclass, jlong ptr, jint join) { SkPaint* instance = reinterpret_cast(static_cast(ptr)); instance->setStrokeJoin(static_cast(join)); } extern "C" JNIEXPORT jlong JNICALL Java_org_jetbrains_skia_PaintKt__1nGetFillPath (JNIEnv* env, jclass jclass, jlong ptr, jlong srcPtr, jfloat resScale) { SkPaint* instance = reinterpret_cast(static_cast(ptr)); SkPath* src = reinterpret_cast(static_cast(srcPtr)); SkPath* dst = new SkPath(); instance->getFillPath(*src, dst, nullptr, resScale); return reinterpret_cast(dst); } extern "C" JNIEXPORT jlong JNICALL Java_org_jetbrains_skia_PaintKt__1nGetFillPathCull (JNIEnv* env, jclass jclass, jlong ptr, jlong srcPtr, jfloat left, jfloat top, jfloat right, jfloat bottom, jfloat resScale) { SkPaint* instance = reinterpret_cast(static_cast(ptr)); SkPath* src = reinterpret_cast(static_cast(srcPtr)); SkPath* dst = new SkPath(); SkRect cull {left, top, right, bottom}; instance->getFillPath(*src, dst, &cull, resScale); return reinterpret_cast(dst); } extern "C" JNIEXPORT jlong JNICALL Java_org_jetbrains_skia_PaintKt__1nGetMaskFilter (JNIEnv* env, jclass jclass, jlong ptr) { SkPaint* instance = reinterpret_cast(static_cast(ptr)); return reinterpret_cast(instance->refMaskFilter().release()); } extern "C" JNIEXPORT void JNICALL Java_org_jetbrains_skia_PaintKt__1nSetMaskFilter (JNIEnv* env, jclass jclass, jlong ptr, jlong filterPtr) { SkPaint* instance = reinterpret_cast(static_cast(ptr)); SkMaskFilter* filter = reinterpret_cast(static_cast(filterPtr)); instance->setMaskFilter(sk_ref_sp(filter)); } extern "C" JNIEXPORT jlong JNICALL Java_org_jetbrains_skia_PaintKt__1nGetImageFilter (JNIEnv* env, jclass jclass, jlong ptr) { SkPaint* instance = reinterpret_cast(static_cast(ptr)); return reinterpret_cast(instance->refImageFilter().release()); } extern "C" JNIEXPORT void JNICALL Java_org_jetbrains_skia_PaintKt__1nSetImageFilter (JNIEnv* env, jclass jclass, jlong ptr, jlong filterPtr) { SkPaint* instance = reinterpret_cast(static_cast(ptr)); SkImageFilter* filter = reinterpret_cast(static_cast(filterPtr)); instance->setImageFilter(sk_ref_sp(filter)); } extern "C" JNIEXPORT jint JNICALL Java_org_jetbrains_skia_PaintKt__1nGetBlendMode (JNIEnv* env, jclass jclass, jlong ptr) { SkPaint* instance = reinterpret_cast(static_cast(ptr)); return static_cast(instance->getBlendMode_or(SkBlendMode::kSrcOver)); } extern "C" JNIEXPORT void JNICALL Java_org_jetbrains_skia_PaintKt__1nSetBlendMode (JNIEnv* env, jclass jclass, jlong ptr, jint mode) { SkPaint* instance = reinterpret_cast(static_cast(ptr)); instance->setBlendMode(static_cast(mode)); } extern "C" JNIEXPORT jlong JNICALL Java_org_jetbrains_skia_PaintKt__1nGetPathEffect (JNIEnv* env, jclass jclass, jlong ptr) { SkPaint* instance = reinterpret_cast(static_cast(ptr)); return reinterpret_cast(instance->refPathEffect().release()); } extern "C" JNIEXPORT void JNICALL Java_org_jetbrains_skia_PaintKt__1nSetPathEffect (JNIEnv* env, jclass jclass, jlong ptr, jlong pathEffectPtr) { SkPaint* instance = reinterpret_cast(static_cast(ptr)); SkPathEffect* pathEffect = reinterpret_cast(static_cast(pathEffectPtr)); instance->setPathEffect(sk_ref_sp(pathEffect)); } extern "C" JNIEXPORT jlong JNICALL Java_org_jetbrains_skia_PaintKt__1nGetShader (JNIEnv* env, jclass jclass, jlong ptr) { SkPaint* instance = reinterpret_cast(static_cast(ptr)); return reinterpret_cast(instance->refShader().release()); } extern "C" JNIEXPORT void JNICALL Java_org_jetbrains_skia_PaintKt__1nSetShader (JNIEnv* env, jclass jclass, jlong ptr, jlong shaderPtr) { SkPaint* instance = reinterpret_cast(static_cast(ptr)); SkShader* shader = reinterpret_cast(static_cast(shaderPtr)); instance->setShader(sk_ref_sp(shader)); } extern "C" JNIEXPORT jlong JNICALL Java_org_jetbrains_skia_PaintKt__1nGetColorFilter (JNIEnv* env, jclass jclass, jlong ptr) { SkPaint* instance = reinterpret_cast(static_cast(ptr)); return reinterpret_cast(instance->refColorFilter().release()); } extern "C" JNIEXPORT void JNICALL Java_org_jetbrains_skia_PaintKt__1nSetColorFilter (JNIEnv* env, jclass jclass, jlong ptr, jlong colorFilterPtr) { SkPaint* instance = reinterpret_cast(static_cast(ptr)); SkColorFilter* colorFilter = reinterpret_cast(static_cast(colorFilterPtr)); instance->setColorFilter(sk_ref_sp(colorFilter)); } extern "C" JNIEXPORT jboolean JNICALL Java_org_jetbrains_skia_PaintKt__1nHasNothingToDraw (JNIEnv* env, jclass jclass, jlong ptr) { SkPaint* instance = reinterpret_cast(static_cast(ptr)); return instance->nothingToDraw(); } 10-100 #ifndef EE_UI_DOC_TEXTPOSITION_HPP #define EE_UI_DOC_TEXTPOSITION_HPP #include #include #include namespace EE { namespace UI { namespace Doc { class EE_API TextPosition { public: TextPosition() {} TextPosition( Int64 line, Int64 column ) : mLine( line ), mColumn( column ) {} bool isValid() const { return mLine != 0xffffffff && mColumn != 0xffffffff; } Int64 line() const { return mLine; } Int64 column() const { return mColumn; } void setLine( Int64 line ) { mLine = line; } void setColumn( Int64 column ) { mColumn = column; } bool operator==( const TextPosition& other ) const { return mLine == other.mLine && mColumn == other.mColumn; } bool operator!=( const TextPosition& other ) const { return mLine != other.mLine || mColumn != other.mColumn; } bool operator<( const TextPosition& other ) const { return mLine < other.mLine || ( mLine == other.mLine && mColumn < other.mColumn ); } bool operator>( const TextPosition& other ) const { return mLine > other.mLine || ( mLine == other.mLine && mColumn > other.mColumn ); } TextPosition operator+( const TextPosition& other ) const { return {mLine + other.line(), mColumn + other.column()}; } TextPosition operator+=( const TextPosition& other ) const { return {mLine + other.line(), mColumn + other.column()}; } TextPosition operator-( const TextPosition& other ) const { return {mLine - other.line(), mColumn - other.column()}; } TextPosition operator-=( const TextPosition& other ) const { return {mLine - other.line(), mColumn - other.column()}; } std::string toString() { return String::format( "L%lld,C%lld", mLine, mColumn ); } private: Int64 mLine{0xffffffff}; Int64 mColumn{0xffffffff}; }; }}} // namespace EE::UI::Doc #endif // EE_UI_DOC_TEXTPOSITION_HPP 1-10 // OpenVPN -- An application to securely tunnel IP networks // over a single port, with support for SSL/TLS-based // session authentication and key exchange, // packet encryption, packet authentication, and // packet compression. // // Copyright (C) 2012-2017 OpenVPN 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 in the COPYING file. // If not, see . // This code implements an OpenSSL BIO object for streams based on the // MemQ buffer queue object. #pragma once #include // for std::strlen and others #include #include #include #include #include #include #include namespace openvpn { namespace bmq_stream { class MemQ : public MemQStream { public: MemQ() {} long ctrl (BIO *b, int cmd, long num, void *ptr) { long ret = 1; switch (cmd) { case BIO_CTRL_RESET: clear(); break; case BIO_CTRL_EOF: ret = (long)empty(); break; case BIO_C_SET_BUF_MEM_EOF_RETURN: return_eof_on_empty = (num == 0); break; case BIO_CTRL_GET_CLOSE: ret = BIO_get_shutdown(b); break; case BIO_CTRL_SET_CLOSE: BIO_set_shutdown(b, (int) num); break; case BIO_CTRL_WPENDING: ret = 0L; break; case BIO_CTRL_PENDING: ret = (long)pending(); break; case BIO_CTRL_DUP: case BIO_CTRL_FLUSH: ret = 1; break; default: //OPENVPN_LOG("*** MemQ-stream unimplemented ctrl method=" << cmd); ret = 0; break; } return (ret); } bool return_eof_on_empty = false; }; class bio_memq_internal { public: static int memq_method_type; static BIO_METHOD* memq_method; static inline int memq_new (BIO *b) { MemQ *bmq = new(std::nothrow) MemQ(); if (!bmq) return 0; BIO_set_shutdown(b, 1); BIO_set_init(b, 1); BIO_set_data(b, (void *)bmq); return 1; } static inline int memq_free (BIO *b) { if (b == nullptr) return (0); if (BIO_get_shutdown (b)) { MemQ *bmq = (MemQ*) (BIO_get_data (b)); if (BIO_get_init (b) && (bmq != nullptr)) { delete bmq; BIO_set_data (b, nullptr); } } return 1; } static inline int memq_write (BIO *b, const char *in, int len) { MemQ *bmq = (MemQ*)(BIO_get_data(b)); if (in) { BIO_clear_retry_flags (b); try { if (len) bmq->write((const unsigned char *)in, (size_t)len); return len; } catch (...) { BIOerr(BIO_F_MEM_WRITE, BIO_R_INVALID_ARGUMENT); return -1; } } else { BIOerr(BIO_F_MEM_WRITE, BIO_R_NULL_PARAMETER); return -1; } } static inline int memq_read (BIO *b, char *out, int size) { MemQ *bmq = (MemQ*)(BIO_get_data(b)); int ret = -1; BIO_clear_retry_flags (b); if (!bmq->empty()) { try { ret = (int)bmq->read((unsigned char *)out, (size_t)size); } catch (...) { BIOerr(memq_method_type, BIO_R_INVALID_ARGUMENT); return -1; } } else { if (!bmq->return_eof_on_empty) BIO_set_retry_read (b); } return ret; } static inline long memq_ctrl (BIO *b, int cmd, long arg1, void *arg2) { MemQ *bmq = (MemQ*)(BIO_get_data(b)); return bmq->ctrl(b, cmd, arg1, arg2); } static inline int memq_puts (BIO *b, const char *str) { const int len = std::strlen (str); const int ret = memq_write (b, str, len); return ret; } static inline void init_static () { memq_method_type = BIO_get_new_index (); memq_method = BIO_meth_new (memq_method_type, "stream memory queue"); BIO_meth_set_write (memq_method, memq_write); BIO_meth_set_read (memq_method, memq_read); BIO_meth_set_puts (memq_method, memq_puts); BIO_meth_set_create (memq_method, memq_new); BIO_meth_set_destroy (memq_method, memq_free); BIO_meth_set_gets (memq_method, nullptr); BIO_meth_set_ctrl (memq_method, memq_ctrl); } static inline void free_bio_method() { BIO_meth_free (memq_method); memq_method = nullptr; } }; // class bio_memq_internal #if defined(OPENVPN_NO_EXTERN) int bio_memq_internal::memq_method_type = -1; BIO_METHOD* bio_memq_internal::memq_method = nullptr; #endif inline void init_static() { bio_memq_internal::init_static(); } inline BIO_METHOD *BIO_s_memq(void) { return (bio_memq_internal::memq_method); } inline MemQ *memq_from_bio(BIO *b) { if (BIO_method_type(b) == bio_memq_internal::memq_method_type) return (MemQ *)(BIO_get_data (b)); else return nullptr; } inline const MemQ *const_memq_from_bio(const BIO *b) { if (BIO_method_type(b) == bio_memq_internal::memq_method_type) return (const MemQ *)(BIO_get_data (const_cast(b))); else return nullptr; } } // namespace bmq_dgram } // namespace openvpn // (C) Copyright 2000. // Use, modification and distribution are subject to 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) #ifdef TEST_STD # include #else # include # include #endif #include "test.hpp" #include "check_integral_constant.hpp" TT_TEST_BEGIN(tricky_abstract_type_test) BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_empty::value, false); #ifndef TEST_STD BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_stateless::value, false); #endif TT_TEST_END xorz57/clay #include #include #include using namespace clay::cryptography; using namespace clay::charset; TEST_CASE("Lower Case") { REQUIRE(trithemius::decode(trithemius::encode(lowercase)) == lowercase); } TEST_CASE("Upper Case") { REQUIRE(trithemius::decode(trithemius::encode(uppercase)) == uppercase); } /** * * \section COPYRIGHT * * Copyright 2013-2017 Software Radio Systems Limited * * \section LICENSE * * This file is part of srsLTE. * * srsUE is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of * the License, or (at your option) any later version. * * srsUE 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. * * A copy of the GNU Affero General Public License can be found in * the LICENSE file in the top-level directory of this distribution * and at http://www.gnu.org/licenses/. * */ #include #include #include "srslte/interfaces/enb_interfaces.h" #include "srsenb/hdr/mac/ue.h" #define Error(fmt, ...) log_h->error(fmt, ##__VA_ARGS__) #define Warning(fmt, ...) log_h->warning(fmt, ##__VA_ARGS__) #define Info(fmt, ...) log_h->info(fmt, ##__VA_ARGS__) #define Debug(fmt, ...) log_h->debug(fmt, ##__VA_ARGS__) namespace srsenb { void ue::config(uint16_t rnti_, uint32_t nof_prb, sched_interface *sched_, rrc_interface_mac *rrc_, rlc_interface_mac *rlc_, srslte::log *log_h_) { rnti = rnti_; rlc = rlc_; rrc = rrc_; log_h = log_h_; sched = sched_; pdus.init(this, log_h); for (int i=0;i 0) { if (!pending_buffers[tti%NOF_HARQ_PROCESSES]) { ret = pdus.request(len); pending_buffers[tti%NOF_HARQ_PROCESSES] = ret; } else { log_h->console("Error requesting buffer for pid %d, not pushed yet\n", tti%NOF_HARQ_PROCESSES); log_h->error("Requesting buffer for pid %d, not pushed yet\n", tti%NOF_HARQ_PROCESSES); } } else { log_h->warning("Requesting buffer for zero bytes\n"); } return ret; } bool ue::process_pdus() { return pdus.process_pdus(); } void ue::set_tti(uint32_t tti) { last_tti = tti; } #include void ue::process_pdu(uint8_t* pdu, uint32_t nof_bytes, srslte::pdu_queue::channel_t channel, uint32_t tstamp) { // Unpack ULSCH MAC PDU mac_msg_ul.init_rx(nof_bytes, true); mac_msg_ul.parse_packet(pdu); if (pcap) { pcap->write_ul_crnti(pdu, nof_bytes, rnti, true, last_tti); } pdus.deallocate(pdu); uint32_t lcid_most_data = 0; int most_data = -99; while(mac_msg_ul.next()) { assert(mac_msg_ul.get()); if (mac_msg_ul.get()->is_sdu()) { // Route logical channel log_h->debug_hex(mac_msg_ul.get()->get_sdu_ptr(), mac_msg_ul.get()->get_payload_size(), "PDU: rnti=0x%x, lcid=%d, %d bytes\n", rnti, mac_msg_ul.get()->get_sdu_lcid(), mac_msg_ul.get()->get_payload_size()); /* In some cases, an uplink transmission with only CQI has all zeros and gets routed to RRC * Compute the checksum if lcid=0 and avoid routing in that case */ bool route_pdu = true; if (mac_msg_ul.get()->get_sdu_lcid() == 0) { uint8_t *x = mac_msg_ul.get()->get_sdu_ptr(); uint32_t sum = 0; for (uint32_t i = 0; i < mac_msg_ul.get()->get_payload_size(); i++) { sum += x[i]; } if (sum == 0) { route_pdu = false; Warning("Received all zero PDU\n"); } } if (route_pdu) { rlc->write_pdu(rnti, mac_msg_ul.get()->get_sdu_lcid(), mac_msg_ul.get()->get_sdu_ptr(), mac_msg_ul.get()->get_payload_size()); } // Indicate scheduler to update BSR counters //sched->ul_recv_len(rnti, mac_msg_ul.get()->get_sdu_lcid(), mac_msg_ul.get()->get_payload_size()); // Indicate RRC about successful activity if valid RLC message is received if (mac_msg_ul.get()->get_payload_size() > 64) { // do not count RLC status messages only rrc->set_activity_user(rnti); log_h->debug("UL activity rnti=0x%x, n_bytes=%d\n", rnti, nof_bytes); } if ((int) mac_msg_ul.get()->get_payload_size() > most_data) { most_data = (int) mac_msg_ul.get()->get_payload_size(); lcid_most_data = mac_msg_ul.get()->get_sdu_lcid(); } // Save contention resolution if lcid == 0 if (mac_msg_ul.get()->get_sdu_lcid() == 0 && route_pdu) { int nbytes = srslte::sch_subh::MAC_CE_CONTRES_LEN; if (mac_msg_ul.get()->get_payload_size() >= (uint32_t)nbytes) { uint8_t *ue_cri_ptr = (uint8_t *) &conres_id; uint8_t *pkt_ptr = mac_msg_ul.get()->get_sdu_ptr(); // Warning here: we want to include the for (int i = 0; i < nbytes; i++) { ue_cri_ptr[nbytes - i - 1] = pkt_ptr[i]; } } else { Error("Received CCCH UL message of invalid size=%d bytes\n", mac_msg_ul.get()->get_payload_size()); } } } } mac_msg_ul.reset(); /* Process CE after all SDUs because we need to update BSR after */ bool bsr_received = false; while(mac_msg_ul.next()) { assert(mac_msg_ul.get()); if (!mac_msg_ul.get()->is_sdu()) { // Process MAC Control Element bsr_received |= process_ce(mac_msg_ul.get()); } } // If BSR is not received means that new data has arrived and there is no space for BSR transmission if (!bsr_received && lcid_most_data > 2) { // Add BSR to the LCID for which most data was received sched->ul_bsr(rnti, lcid_most_data, 256, false); // false adds BSR instead of setting Debug("BSR not received. Giving extra grant\n"); } Debug("MAC PDU processed\n"); } void ue::deallocate_pdu(uint32_t tti) { if (pending_buffers[tti%NOF_HARQ_PROCESSES]) { pdus.deallocate(pending_buffers[tti%NOF_HARQ_PROCESSES]); pending_buffers[tti%NOF_HARQ_PROCESSES] = NULL; } else { log_h->console("Error deallocating buffer for pid=%d. Not requested\n", tti%NOF_HARQ_PROCESSES); } } void ue::push_pdu(uint32_t tti, uint32_t len) { if (pending_buffers[tti%NOF_HARQ_PROCESSES]) { pdus.push(pending_buffers[tti%NOF_HARQ_PROCESSES], len); pending_buffers[tti%NOF_HARQ_PROCESSES] = NULL; } else { log_h->console("Error pushing buffer for pid=%d. Not requested\n", tti%NOF_HARQ_PROCESSES); } } bool ue::process_ce(srslte::sch_subh *subh) { uint32_t buff_size[4] = {0, 0, 0, 0}; float phr = 0; int32_t idx = 0; uint16_t old_rnti = 0; bool is_bsr = false; switch(subh->ce_type()) { case srslte::sch_subh::PHR_REPORT: phr = subh->get_phr(); Info("CE: Received PHR from rnti=0x%x, value=%.0f\n", rnti, phr); sched->ul_phr(rnti, (int) phr); metrics_phr(phr); break; case srslte::sch_subh::CRNTI: old_rnti = subh->get_c_rnti(); Info("CE: Received C-RNTI from temp_rnti=0x%x, rnti=0x%x\n", rnti, old_rnti); if (sched->ue_exists(old_rnti)) { rrc->upd_user(rnti, old_rnti); rnti = old_rnti; } else { Error("Updating user C-RNTI: rnti=0x%x already released\n", old_rnti); } break; case srslte::sch_subh::TRUNC_BSR: case srslte::sch_subh::SHORT_BSR: idx = subh->get_bsr(buff_size); if(idx == -1){ Error("Invalid Index Passed to lc groups\n"); break; } for (uint32_t i=0;iul_bsr(rnti, lc_groups[idx][i], buff_size[idx]); } Info("CE: Received %s BSR rnti=0x%x, lcg=%d, value=%d\n", subh->ce_type()==srslte::sch_subh::SHORT_BSR?"Short":"Trunc", rnti, idx, buff_size[idx]); is_bsr = true; break; case srslte::sch_subh::LONG_BSR: subh->get_bsr(buff_size); for (idx=0;idx<4;idx++) { for (uint32_t i=0;iul_bsr(rnti, lc_groups[idx][i], buff_size[idx]); } } is_bsr = true; Info("CE: Received Long BSR rnti=0x%x, value=%d,%d,%d,%d\n", rnti, buff_size[0], buff_size[1], buff_size[2], buff_size[3]); break; case srslte::sch_subh::PADDING: Debug("CE: Received padding for rnti=0x%x\n", rnti); break; default: Error("CE: Invalid lcid=0x%x\n", subh->ce_type()); break; } return is_bsr; } int ue::read_pdu(uint32_t lcid, uint8_t *payload, uint32_t requested_bytes) { return rlc->read_pdu(rnti, lcid, payload, requested_bytes); } void ue::allocate_sdu(srslte::sch_pdu *pdu, uint32_t lcid, uint32_t total_sdu_len) { int sdu_space = pdu->get_sdu_space(); if (sdu_space > 0) { int sdu_len = SRSLTE_MIN(total_sdu_len, (uint32_t) sdu_space); int n=1; while(sdu_len > 3 && n > 0) { if (pdu->new_subh()) { // there is space for a new subheader log_h->debug("SDU: set_sdu(), lcid=%d, sdu_len=%d, sdu_space=%d\n", lcid, sdu_len, sdu_space); n = pdu->get()->set_sdu(lcid, sdu_len, this); if (n > 0) { // new SDU could be added sdu_len -= n; log_h->debug("SDU: rnti=0x%x, lcid=%d, nbytes=%d, rem_len=%d\n", rnti, lcid, n, sdu_len); } else { Debug("Could not add SDU lcid=%d nbytes=%d, space=%d\n", lcid, sdu_len, sdu_space); pdu->del_subh(); } } else { n=0; } } } } void ue::allocate_ce(srslte::sch_pdu *pdu, uint32_t lcid) { switch((srslte::sch_subh::cetype) lcid) { case srslte::sch_subh::CON_RES_ID: if (pdu->new_subh()) { if (pdu->get()->set_con_res_id(conres_id)) { Info("CE: Added Contention Resolution ID=0x%lx\n", conres_id); } else { Error("CE: Setting Contention Resolution ID CE\n"); } } else { Error("CE: Setting Contention Resolution ID CE. No space for a subheader\n"); } break; default: Error("CE: Allocating CE=0x%x. Not supported\n", lcid); break; } } uint8_t* ue::generate_pdu(uint32_t tb_idx, sched_interface::dl_sched_pdu_t pdu[sched_interface::MAX_RLC_PDU_LIST], uint32_t nof_pdu_elems, uint32_t grant_size) { uint8_t *ret = NULL; pthread_mutex_lock(&mutex); if (rlc) { mac_msg_dl.init_tx(tx_payload_buffer[tb_idx], grant_size, false); for (uint32_t i=0;iset_next_mch_sched_info(sched.mtch_sched[i].lcid,sched.mtch_sched[i].stop); } else if (sched.pdu[i].lcid == 0) { mch_mac_msg_dl.new_subh(); mch_mac_msg_dl.get()->set_sdu(0, sched.pdu[i].nbytes, sched.mcch_payload); } else if (sched.pdu[i].lcid <= srslte::mch_subh::MTCH_MAX_LCID) { mch_mac_msg_dl.new_subh(); mch_mac_msg_dl.get()->set_sdu(sched.pdu[i].lcid, sched.pdu[i].nbytes,sched.mtch_sched[i].mtch_payload); } } ret = mch_mac_msg_dl.write_packet(log_h); pthread_mutex_unlock(&mutex); return ret; } /******* METRICS interface ***************/ void ue::metrics_read(mac_metrics_t* metrics_) { metrics.rnti = rnti; metrics.ul_buffer = sched->get_ul_buffer(rnti); metrics.dl_buffer = sched->get_dl_buffer(rnti); memcpy(metrics_, &metrics, sizeof(mac_metrics_t)); phr_counter = 0; dl_cqi_counter = 0; bzero(&metrics, sizeof(mac_metrics_t)); } void ue::metrics_phr(float phr) { metrics.phr = SRSLTE_VEC_CMA(phr, metrics.phr, phr_counter); phr_counter++; } void ue::metrics_dl_ri(uint32_t dl_ri) { if (metrics.dl_ri == 0.0f) { metrics.dl_ri = (float) dl_ri + 1.0f; } else { metrics.dl_ri = SRSLTE_VEC_EMA((float) dl_ri + 1.0f, metrics.dl_ri, 0.5f); } dl_ri_counter++; } void ue::metrics_dl_pmi(uint32_t dl_ri) { metrics.dl_pmi = SRSLTE_VEC_CMA((float) dl_ri, metrics.dl_pmi, dl_pmi_counter); dl_pmi_counter++; } void ue::metrics_dl_cqi(uint32_t dl_cqi) { metrics.dl_cqi = SRSLTE_VEC_CMA((float) dl_cqi, metrics.dl_cqi, dl_cqi_counter); dl_cqi_counter++; } void ue::metrics_rx(bool crc, uint32_t tbs) { if (crc) { metrics.rx_brate += tbs*8; } else { metrics.rx_errors++; } metrics.rx_pkts++; } void ue::metrics_tx(bool crc, uint32_t tbs) { if (crc) { metrics.tx_brate += tbs*8; } else { metrics.tx_errors++; } metrics.tx_pkts++; } } 1-10 #include #include #include using namespace std; int n, x, r = 1; int main() { cin >> n; vector> v; v.push_back({0,1}); for (int i = 1; i <= n; i++) { cin >> x; v.push_back({x,i}); } sort(v.begin(),v.end()); for (int i = 0; i < n; i++) { if (v[i].second > v[i+1].second) r++; } cout << r << "\n"; }moos-ivp/ivp/src/lib_geometry/XYFormatUtilsRangePulse.cpp /*****************************************************************/ /* NAME: */ /* ORGN: Dept of Mechanical Eng / CSAIL, MIT Cambridge MA */ /* FILE: XYFormatUtilsRangePulse.cpp */ /* DATE: Feb 5th, 2011 */ /* */ /* This file is part of IvP Helm Core Libs */ /* */ /* IvP Helm Core Libs is free software: you can redistribute it */ /* and/or modify it under the terms of the Lesser GNU General */ /* Public License as published by the Free Software Foundation, */ /* either version 3 of the License, or (at your option) any */ /* later version. */ /* */ /* IvP Helm Core Libs 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 Lesser GNU General Public License for more */ /* details. */ /* */ /* You should have received a copy of the Lesser GNU General */ /* Public License along with MOOS-IvP. If not, see */ /* . */ /*****************************************************************/ #include #include #include "XYFormatUtilsRangePulse.h" #include "MBUtils.h" using namespace std; //--------------------------------------------------------------- // Procedure: string2RangePulse (Method #0) // Example: Create a point from a string representation. XYRangePulse string2RangePulse(string str) { return(stringStandard2RangePulse(str)); } //--------------------------------------------------------------- // Procedure: stringStandard2RangePulse (Method #1) // Note: This function is standard because it processes the // string format used when a string is created from an // existing XYRangePulse instance. // Example: label=one,x=4,y=2,radius=50,duration=5,fill=0.3, // fill_color=yellow,edge_color=green // XYRangePulse stringStandard2RangePulse(string str) { XYRangePulse null_pulse; XYRangePulse new_pulse; str = stripBlankEnds(str); vector mvector = parseString(str, ','); unsigned int i, vsize = mvector.size(); for(i=0; i MSB // p0: (e0, e1, e2, e3) // p1: (1, e23, e31, e12) // p2: (e0123, e01, e02, e03) // p3: (e123, e032, e013, e021) // Reflect a plane through another plane // b * a * b KLN_INLINE void KLN_VEC_CALL sw00(__m128 a, __m128 b, __m128& p0_out) { // (2a0(a2 b2 + a3 b3 + a1 b1) - b0(a1^2 + a2^2 + a3^2)) e0 + // (2a1(a2 b2 + a3 b3) + b1(a1^2 - a2^2 - a3^2)) e1 + // (2a2(a3 b3 + a1 b1) + b2(a2^2 - a3^2 - a1^2)) e2 + // (2a3(a1 b1 + a2 b2) + b3(a3^2 - a1^2 - a2^2)) e3 __m128 a_zzwy = KLN_SWIZZLE(a, 1, 3, 2, 2); __m128 a_wwyz = KLN_SWIZZLE(a, 2, 1, 3, 3); // Left block __m128 tmp = _mm_mul_ps(a_zzwy, KLN_SWIZZLE(b, 1, 3, 2, 2)); tmp = _mm_add_ps(tmp, _mm_mul_ps(a_wwyz, KLN_SWIZZLE(b, 2, 1, 3, 3))); __m128 a1 = _mm_movehdup_ps(a); __m128 b1 = _mm_movehdup_ps(b); tmp = _mm_add_ss(tmp, _mm_mul_ss(a1, b1)); tmp = _mm_mul_ps(tmp, _mm_add_ps(a, a)); // Right block __m128 a_yyzw = KLN_SWIZZLE(a, 3, 2, 1, 1); __m128 tmp2 = _mm_xor_ps(_mm_mul_ps(a_yyzw, a_yyzw), _mm_set_ss(-0.f)); tmp2 = _mm_sub_ps(tmp2, _mm_mul_ps(a_zzwy, a_zzwy)); tmp2 = _mm_sub_ps(tmp2, _mm_mul_ps(a_wwyz, a_wwyz)); tmp2 = _mm_mul_ps(tmp2, b); p0_out = _mm_add_ps(tmp, tmp2); } KLN_INLINE void KLN_VEC_CALL sw10(__m128 a, __m128 b, __m128& KLN_RESTRICT p1, __m128& KLN_RESTRICT p2) { // b0(a1^2 + a2^2 + a3^2) + // (2a3(a1 b1 + a2 b2) + b3(a3^2 - a1^2 - a2^2)) e12 + // (2a1(a2 b2 + a3 b3) + b1(a1^2 - a2^2 - a3^2)) e23 + // (2a2(a3 b3 + a1 b1) + b2(a2^2 - a3^2 - a1^2)) e31 + // // 2a0(a1 b2 - a2 b1) e03 // 2a0(a2 b3 - a3 b2) e01 + // 2a0(a3 b1 - a1 b3) e02 + __m128 a_zyzw = KLN_SWIZZLE(a, 3, 2, 1, 2); __m128 a_ywyz = KLN_SWIZZLE(a, 2, 1, 3, 1); __m128 a_wzwy = KLN_SWIZZLE(a, 1, 3, 2, 3); __m128 b_xzwy = KLN_SWIZZLE(b, 1, 3, 2, 0); __m128 two_zero = _mm_set_ps(2.f, 2.f, 2.f, 0.f); p1 = _mm_mul_ps(a, b); p1 = _mm_add_ps(p1, _mm_mul_ps(a_wzwy, b_xzwy)); p1 = _mm_mul_ps(p1, _mm_mul_ps(a_ywyz, two_zero)); __m128 tmp = _mm_mul_ps(a_zyzw, a_zyzw); tmp = _mm_add_ps(tmp, _mm_mul_ps(a_wzwy, a_wzwy)); tmp = _mm_xor_ps(tmp, _mm_set_ss(-0.f)); tmp = _mm_sub_ps(_mm_mul_ps(a_ywyz, a_ywyz), tmp); tmp = _mm_mul_ps(KLN_SWIZZLE(b, 2, 1, 3, 0), tmp); p1 = KLN_SWIZZLE(_mm_add_ps(p1, tmp), 1, 3, 2, 0); p2 = _mm_mul_ps(a_zyzw, b_xzwy); p2 = _mm_sub_ps(p2, _mm_mul_ps(a_wzwy, b)); p2 = _mm_mul_ps(p2, _mm_mul_ps(KLN_SWIZZLE(a, 0, 0, 0, 0), two_zero)); p2 = KLN_SWIZZLE(p2, 1, 3, 2, 0); } KLN_INLINE void KLN_VEC_CALL sw20(__m128 a, __m128 b, __m128& p2) { // -b0(a1^2 + a2^2 + a3^2) e0123 + // (-2a3(a1 b1 + a2 b2) + b3(a1^2 + a2^2 - a3^2)) e03 // (-2a1(a2 b2 + a3 b3) + b1(a2^2 + a3^2 - a1^2)) e01 + // (-2a2(a3 b3 + a1 b1) + b2(a3^2 + a1^2 - a2^2)) e02 + __m128 a_zzwy = KLN_SWIZZLE(a, 1, 3, 2, 2); __m128 a_wwyz = KLN_SWIZZLE(a, 2, 1, 3, 3); p2 = _mm_mul_ps(a, b); p2 = _mm_add_ps(p2, _mm_mul_ps(a_zzwy, KLN_SWIZZLE(b, 1, 3, 2, 0))); p2 = _mm_mul_ps( p2, _mm_mul_ps(a_wwyz, _mm_set_ps(-2.f, -2.f, -2.f, 0.f))); __m128 a_yyzw = KLN_SWIZZLE(a, 3, 2, 1, 1); __m128 tmp = _mm_mul_ps(a_yyzw, a_yyzw); tmp = _mm_xor_ps( _mm_set_ss(-0.f), _mm_add_ps(tmp, _mm_mul_ps(a_zzwy, a_zzwy))); tmp = _mm_sub_ps(tmp, _mm_mul_ps(a_wwyz, a_wwyz)); p2 = _mm_add_ps(p2, _mm_mul_ps(tmp, KLN_SWIZZLE(b, 2, 1, 3, 0))); p2 = KLN_SWIZZLE(p2, 1, 3, 2, 0); } KLN_INLINE void KLN_VEC_CALL sw30(__m128 a, __m128 b, __m128& p3_out) { // b0(a1^2 + a2^2 + a3^2) e123 + // (-2a1(a0 b0 + a3 b3 + a2 b2) + b1(a2^2 + a3^2 - a1^2)) e032 + // (-2a2(a0 b0 + a1 b1 + a3 b3) + b2(a3^2 + a1^2 - a2^2)) e013 + // (-2a3(a0 b0 + a2 b2 + a1 b1) + b3(a1^2 + a2^2 - a3^2)) e021 __m128 a_zwyz = KLN_SWIZZLE(a, 2, 1, 3, 2); __m128 a_yzwy = KLN_SWIZZLE(a, 1, 3, 2, 1); p3_out = _mm_mul_ps(KLN_SWIZZLE(a, 0, 0, 0, 0), KLN_SWIZZLE(b, 0, 0, 0, 0)); p3_out = _mm_add_ps(p3_out, _mm_mul_ps(a_zwyz, KLN_SWIZZLE(b, 2, 1, 3, 0))); p3_out = _mm_add_ps(p3_out, _mm_mul_ps(a_yzwy, KLN_SWIZZLE(b, 1, 3, 2, 0))); p3_out = _mm_mul_ps( p3_out, _mm_mul_ps(a, _mm_set_ps(-2.f, -2.f, -2.f, 0.f))); __m128 tmp = _mm_mul_ps(a_yzwy, a_yzwy); tmp = _mm_add_ps(tmp, _mm_mul_ps(a_zwyz, a_zwyz)); __m128 a_wyzw = KLN_SWIZZLE(a, 3, 2, 1, 3); tmp = _mm_sub_ps( tmp, _mm_xor_ps(_mm_mul_ps(a_wyzw, a_wyzw), _mm_set_ss(-0.f))); p3_out = _mm_add_ps(p3_out, _mm_mul_ps(b, tmp)); } // Apply a translator to a plane. // Assumes e0123 component of p2 is exactly 0 // p0: (e0, e1, e2, e3) // p2: (e0123, e01, e02, e03) // b * a * ~b // The low component of p2 is expected to be the scalar component instead KLN_INLINE __m128 KLN_VEC_CALL sw02(__m128 a, __m128 b) { // (a0 b0^2 + 2a1 b0 b1 + 2a2 b0 b2 + 2a3 b0 b3) e0 + // (a1 b0^2) e1 + // (a2 b0^2) e2 + // (a3 b0^2) e3 // // Because the plane is projectively equivalent on multiplication by a // scalar, we can divide the result through by b0^2 // // (a0 + 2a1 b1 / b0 + 2a2 b2 / b0 + 2a3 b3 / b0) e0 + // a1 e1 + // a2 e2 + // a3 e3 // // The additive term clearly contains a dot product between the plane's // normal and the translation axis, demonstrating that the plane // "doesn't care" about translations along its span. More precisely, the // plane translates by the projection of the translator on the plane's // normal. // a1*b1 + a2*b2 + a3*b3 stored in the low component of tmp __m128 tmp = hi_dp(a, b); __m128 inv_b = rcp_nr1(b); // 2 / b0 inv_b = _mm_add_ss(inv_b, inv_b); inv_b = _mm_and_ps(inv_b, _mm_castsi128_ps(_mm_set_epi32(0, 0, 0, -1))); tmp = _mm_mul_ss(tmp, inv_b); // Add to the plane return _mm_add_ps(a, tmp); } // Apply a translator to a line // a := p1 input // d := p2 input // c := p2 translator // out points to the start address of a line (p1, p2) KLN_INLINE void KLN_VEC_CALL swL2(__m128 a, __m128 d, __m128 c, __m128* out) { // a0 + // a1 e23 + // a2 e31 + // a3 e12 + // // (2a0 c0 + d0) e0123 + // (2(a2 c3 - a3 c2 - a1 c0) + d1) e01 + // (2(a3 c1 - a1 c3 - a2 c0) + d2) e02 + // (2(a1 c2 - a2 c1 - a3 c0) + d3) e03 __m128& p1_out = *out; __m128& p2_out = *(out + 1); p1_out = a; p2_out = _mm_mul_ps(KLN_SWIZZLE(a, 1, 3, 2, 0), KLN_SWIZZLE(c, 2, 1, 3, 0)); // Add and subtract the same quantity in the low component to produce a // cancellation p2_out = _mm_sub_ps( p2_out, _mm_mul_ps(KLN_SWIZZLE(a, 2, 1, 3, 0), KLN_SWIZZLE(c, 1, 3, 2, 0))); p2_out = _mm_sub_ps(p2_out, _mm_xor_ps(_mm_mul_ps(a, KLN_SWIZZLE(c, 0, 0, 0, 0)), _mm_set_ss(-0.f))); p2_out = _mm_add_ps(p2_out, p2_out); p2_out = _mm_add_ps(p2_out, d); } // Apply a translator to a point. // Assumes e0123 component of p2 is exactly 0 // p2: (e0123, e01, e02, e03) // p3: (e123, e032, e013, e021) // b * a * ~b KLN_INLINE __m128 KLN_VEC_CALL sw32(__m128 a, __m128 b) noexcept { // a0 e123 + // (a1 - 2 a0 b1) e032 + // (a2 - 2 a0 b2) e013 + // (a3 - 2 a0 b3) e021 __m128 tmp = _mm_mul_ps(KLN_SWIZZLE(a, 0, 0, 0, 0), b); tmp = _mm_mul_ps(_mm_set_ps(-2.f, -2.f, -2.f, 0.f), tmp); tmp = _mm_add_ps(a, tmp); return tmp; } #if __cplusplus >= 201703L // Apply a motor to a motor (works on lines as well) // in points to the start of an array of motor inputs (alternating p1 and // p2) out points to the start of an array of motor outputs (alternating p1 // and p2) // // Note: in and out are permitted to alias iff a == out. template KLN_INLINE void KLN_VEC_CALL swMM(__m128 const* KLN_RESTRICT in, __m128 const& KLN_RESTRICT b, [[maybe_unused]] __m128 const* KLN_RESTRICT c, __m128* out, size_t count = 0) noexcept { // p1 block // a0(b0^2 + b1^2 + b2^2 + b3^2) + // (a1(b1^2 + b0^2 - b3^2 - b2^2) + // 2a2(b0 b3 + b1 b2) + 2a3(b1 b3 - b0 b2)) e23 + // (a2(b2^2 + b0^2 - b1^2 - b3^2) + // 2a3(b0 b1 + b2 b3) + 2a1(b2 b1 - b0 b3)) e31 // (a3(b3^2 + b0^2 - b2^2 - b1^2) + // 2a1(b0 b2 + b3 b1) + 2a2(b3 b2 - b0 b1)) e12 + __m128 b_xwyz = KLN_SWIZZLE(b, 2, 1, 3, 0); __m128 b_xzwy = KLN_SWIZZLE(b, 1, 3, 2, 0); __m128 b_yxxx = KLN_SWIZZLE(b, 0, 0, 0, 1); __m128 b_yxxx_2 = _mm_mul_ps(b_yxxx, b_yxxx); __m128 tmp = _mm_mul_ps(b, b); tmp = _mm_add_ps(tmp, b_yxxx_2); __m128 b_tmp = KLN_SWIZZLE(b, 2, 1, 3, 2); __m128 tmp2 = _mm_mul_ps(b_tmp, b_tmp); b_tmp = KLN_SWIZZLE(b, 1, 3, 2, 3); tmp2 = _mm_add_ps(tmp2, _mm_mul_ps(b_tmp, b_tmp)); tmp = _mm_sub_ps(tmp, _mm_xor_ps(tmp2, _mm_set_ss(-0.f))); // tmp needs to be scaled by a and set to p1_out __m128 b_xxxx = KLN_SWIZZLE(b, 0, 0, 0, 0); __m128 scale = _mm_set_ps(2.f, 2.f, 2.f, 0.f); tmp2 = _mm_mul_ps(b_xxxx, b_xwyz); tmp2 = _mm_add_ps(tmp2, _mm_mul_ps(b, b_xzwy)); tmp2 = _mm_mul_ps(tmp2, scale); // tmp2 needs to be scaled by (a0, a2, a3, a1) and added to p1_out __m128 tmp3 = _mm_mul_ps(b, b_xwyz); tmp3 = _mm_sub_ps(tmp3, _mm_mul_ps(b_xxxx, b_xzwy)); tmp3 = _mm_mul_ps(tmp3, scale); // tmp3 needs to be scaled by (a0, a3, a1, a2) and added to p1_out // p2 block // (d coefficients are the components of the input line p2) // (2a0(b0 c0 - b1 c1 - b2 c2 - b3 c3) + // d0(b1^2 + b0^2 + b2^2 + b3^2)) e0123 + // // (2a1(b1 c1 - b0 c0 - b3 c3 - b2 c2) + // 2a3(b1 c3 + b2 c0 + b3 c1 - b0 c2) + // 2a2(b1 c2 + b0 c3 + b2 c1 - b3 c0) + // 2d2(b0 b3 + b2 b1) + // 2d3(b1 b3 - b0 b2) + // d1(b0^2 + b1^2 - b3^2 - b2^2)) e01 + // // (2a2(b2 c2 - b0 c0 - b3 c3 - b1 c1) + // 2a1(b2 c1 + b3 c0 + b1 c2 - b0 c3) + // 2a3(b2 c3 + b0 c1 + b3 c2 - b1 c0) + // 2d3(b0 b1 + b3 b2) + // 2d1(b2 b1 - b0 b3) + // d2(b0^2 + b2^2 - b1^2 - b3^2)) e02 + // // (2a3(b3 c3 - b0 c0 - b1 c1 - b2 c2) + // 2a2(b3 c2 + b1 c0 + b2 c3 - b0 c1) + // 2a1(b3 c1 + b0 c2 + b1 c3 - b2 c0) + // 2d1(b0 b2 + b1 b3) + // 2d2(b3 b2 - b0 b1) + // d3(b0^2 + b3^2 - b2^2 - b1^2)) e03 // Rotation // tmp scaled by d and added to p2 // tmp2 scaled by (d0, d2, d3, d1) and added to p2 // tmp3 scaled by (d0, d3, d1, d2) and added to p2 // Translation [[maybe_unused]] __m128 tmp4; // scaled by a and added to p2 [[maybe_unused]] __m128 tmp5; // scaled by (a0, a3, a1, a2), added to p2 [[maybe_unused]] __m128 tmp6; // scaled by (a0, a2, a3, a1), added to p2 if constexpr (Translate) { __m128 czero = KLN_SWIZZLE(*c, 0, 0, 0, 0); __m128 c_xzwy = KLN_SWIZZLE(*c, 1, 3, 2, 0); __m128 c_xwyz = KLN_SWIZZLE(*c, 2, 1, 3, 0); tmp4 = _mm_mul_ps(b, *c); tmp4 = _mm_sub_ps( tmp4, _mm_mul_ps(b_yxxx, KLN_SWIZZLE(*c, 0, 0, 0, 1))); tmp4 = _mm_sub_ps(tmp4, _mm_mul_ps(KLN_SWIZZLE(b, 1, 3, 3, 2), KLN_SWIZZLE(*c, 1, 3, 3, 2))); tmp4 = _mm_sub_ps(tmp4, _mm_mul_ps(KLN_SWIZZLE(b, 2, 1, 2, 3), KLN_SWIZZLE(*c, 2, 1, 2, 3))); tmp4 = _mm_add_ps(tmp4, tmp4); tmp5 = _mm_mul_ps(b, c_xwyz); tmp5 = _mm_add_ps(tmp5, _mm_mul_ps(b_xzwy, czero)); tmp5 = _mm_add_ps(tmp5, _mm_mul_ps(b_xwyz, *c)); tmp5 = _mm_sub_ps(tmp5, _mm_mul_ps(b_xxxx, c_xzwy)); tmp5 = _mm_mul_ps(tmp5, scale); tmp6 = _mm_mul_ps(b, c_xzwy); tmp6 = _mm_add_ps(tmp6, _mm_mul_ps(b_xxxx, c_xwyz)); tmp6 = _mm_add_ps(tmp6, _mm_mul_ps(b_xzwy, *c)); tmp6 = _mm_sub_ps(tmp6, _mm_mul_ps(b_xwyz, czero)); tmp6 = _mm_mul_ps(tmp6, scale); } size_t limit = Variadic ? count : 1; constexpr size_t stride = InputP2 ? 2 : 1; for (size_t i = 0; i != limit; ++i) { __m128 const& p1_in = in[stride * i]; // a __m128 p1_in_xzwy = KLN_SWIZZLE(p1_in, 1, 3, 2, 0); __m128 p1_in_xwyz = KLN_SWIZZLE(p1_in, 2, 1, 3, 0); __m128& p1_out = out[stride * i]; p1_out = _mm_mul_ps(tmp, p1_in); p1_out = _mm_add_ps(p1_out, _mm_mul_ps(tmp2, p1_in_xzwy)); p1_out = _mm_add_ps(p1_out, _mm_mul_ps(tmp3, p1_in_xwyz)); if constexpr (InputP2) { __m128 const& p2_in = in[2 * i + 1]; // d __m128& p2_out = out[2 * i + 1]; p2_out = _mm_mul_ps(tmp, p2_in); p2_out = _mm_add_ps( p2_out, _mm_mul_ps(tmp2, KLN_SWIZZLE(p2_in, 1, 3, 2, 0))); p2_out = _mm_add_ps( p2_out, _mm_mul_ps(tmp3, KLN_SWIZZLE(p2_in, 2, 1, 3, 0))); } // If what is being applied is a rotor, the non-directional // components of the line are left untouched if constexpr (Translate) { __m128& p2_out = out[2 * i + 1]; p2_out = _mm_add_ps(p2_out, _mm_mul_ps(tmp4, p1_in)); p2_out = _mm_add_ps(p2_out, _mm_mul_ps(tmp5, p1_in_xwyz)); p2_out = _mm_add_ps(p2_out, _mm_mul_ps(tmp6, p1_in_xzwy)); } } } // Apply a motor to a plane // a := p0 // b := p1 // c := p2 // If Translate is false, c is ignored (rotor application). // If Variadic is true, a and out must point to a contiguous block of memory // equivalent to __m128[count] template KLN_INLINE void KLN_VEC_CALL sw012(__m128 const* KLN_RESTRICT a, __m128 b, [[maybe_unused]] __m128 const* KLN_RESTRICT c, __m128* out, size_t count = 0) noexcept { // LSB // // (2a3(b0 c3 + b1 c2 + b3 c0 - b2 c1) + // 2a2(b0 c2 + b3 c1 + b2 c0 - b1 c3) + // 2a1(b0 c1 + b2 c3 + b1 c0 - b3 c2) + // a0 (b2^2 + b1^2 + b0^2 + b3^2)) e0 + // // (2a2(b0 b3 + b2 b1) + // 2a3(b1 b3 - b0 b2) + // a1 (b0^2 + b1^2 - b3^2 - b2^2)) e1 + // // (2a3(b0 b1 + b3 b2) + // 2a1(b2 b1 - b0 b3) + // a2 (b0^2 + b2^2 - b1^2 - b3^2)) e2 + // // (2a1(b0 b2 + b1 b3) + // 2a2(b3 b2 - b0 b1) + // a3 (b0^2 + b3^2 - b2^2 - b1^2)) e3 // // MSB // // Note the similarity between the results here and the rotor and // translator applied to the plane. The e1, e2, and e3 components do not // participate in the translation and are identical to the result after // the rotor was applied to the plane. The e0 component is displaced // similarly to the manner in which it is displaced after application of // a translator. // Double-cover scale __m128 dc_scale = _mm_set_ps(2.f, 2.f, 2.f, 1.f); __m128 b_xwyz = KLN_SWIZZLE(b, 2, 1, 3, 0); __m128 b_xzwy = KLN_SWIZZLE(b, 1, 3, 2, 0); __m128 b_xxxx = KLN_SWIZZLE(b, 0, 0, 0, 0); __m128 tmp1 = _mm_mul_ps(KLN_SWIZZLE(b, 0, 0, 0, 2), KLN_SWIZZLE(b, 2, 1, 3, 2)); tmp1 = _mm_add_ps( tmp1, _mm_mul_ps(KLN_SWIZZLE(b, 1, 3, 2, 1), KLN_SWIZZLE(b, 3, 2, 1, 1))); // Scale later with (a0, a2, a3, a1) tmp1 = _mm_mul_ps(tmp1, dc_scale); __m128 tmp2 = _mm_mul_ps(b, b_xwyz); tmp2 = _mm_sub_ps(tmp2, _mm_xor_ps(_mm_set_ss(-0.f), _mm_mul_ps(KLN_SWIZZLE(b, 0, 0, 0, 3), KLN_SWIZZLE(b, 1, 3, 2, 3)))); // Scale later with (a0, a3, a1, a2) tmp2 = _mm_mul_ps(tmp2, dc_scale); // Alternately add and subtract to improve low component stability __m128 tmp3 = _mm_mul_ps(b, b); tmp3 = _mm_sub_ps(tmp3, _mm_mul_ps(b_xwyz, b_xwyz)); tmp3 = _mm_add_ps(tmp3, _mm_mul_ps(b_xxxx, b_xxxx)); tmp3 = _mm_sub_ps(tmp3, _mm_mul_ps(b_xzwy, b_xzwy)); // Scale later with a // Compute // 0 * _ + // 2a1(b0 c1 + b2 c3 + b1 c0 - b3 c2) + // 2a2(b0 c2 + b3 c1 + b2 c0 - b1 c3) + // 2a3(b0 c3 + b1 c2 + b3 c0 - b2 c1) // by decomposing into four vectors, factoring out the a components [[maybe_unused]] __m128 tmp4; if constexpr (Translate) { tmp4 = _mm_mul_ps(b_xxxx, *c); tmp4 = _mm_add_ps( tmp4, _mm_mul_ps(b_xzwy, KLN_SWIZZLE(*c, 2, 1, 3, 0))); tmp4 = _mm_add_ps(tmp4, _mm_mul_ps(b, KLN_SWIZZLE(*c, 0, 0, 0, 0))); // NOTE: The high component of tmp4 is meaningless here tmp4 = _mm_sub_ps( tmp4, _mm_mul_ps(b_xwyz, KLN_SWIZZLE(*c, 1, 3, 2, 0))); tmp4 = _mm_mul_ps(tmp4, dc_scale); } // The temporaries (tmp1, tmp2, tmp3, tmp4) strictly only have a // dependence on b and c. size_t limit = Variadic ? count : 1; for (size_t i = 0; i != limit; ++i) { // Compute the lower block for components e1, e2, and e3 __m128& p = out[i]; p = _mm_mul_ps(tmp1, KLN_SWIZZLE(a[i], 1, 3, 2, 0)); p = _mm_add_ps(p, _mm_mul_ps(tmp2, KLN_SWIZZLE(a[i], 2, 1, 3, 0))); p = _mm_add_ps(p, _mm_mul_ps(tmp3, a[i])); if constexpr (Translate) { __m128 tmp5 = hi_dp(tmp4, a[i]); p = _mm_add_ps(p, tmp5); } } } // Apply a motor to a point template KLN_INLINE void KLN_VEC_CALL sw312(__m128 const* KLN_RESTRICT a, __m128 b, [[maybe_unused]] __m128 const* KLN_RESTRICT c, __m128* out, size_t count = 0) noexcept { // LSB // a0(b1^2 + b0^2 + b2^2 + b3^2) e123 + // // (2a0(b2 c3 - b0 c1 - b3 c2 - b1 c0) + // 2a3(b1 b3 - b0 b2) + // 2a2(b0 b3 + b2 b1) + // a1(b0^2 + b1^2 - b3^2 - b2^2)) e032 // // (2a0(b3 c1 - b0 c2 - b1 c3 - b2 c0) + // 2a1(b2 b1 - b0 b3) + // 2a3(b0 b1 + b3 b2) + // a2(b0^2 + b2^2 - b1^2 - b3^2)) e013 + // // (2a0(b1 c2 - b0 c3 - b2 c1 - b3 c0) + // 2a2(b3 b2 - b0 b1) + // 2a1(b0 b2 + b1 b3) + // a3(b0^2 + b3^2 - b2^2 - b1^2)) e021 + // MSB // // Sanity check: For c1 = c2 = c3 = 0, the computation becomes // indistinguishable from a rotor application and the homogeneous // coordinate a0 does not participate. As an additional sanity check, // note that for a normalized rotor and homogenous point, the e123 // component will remain unity. __m128 two = _mm_set_ps(2.f, 2.f, 2.f, 0.f); __m128 b_xxxx = KLN_SWIZZLE(b, 0, 0, 0, 0); __m128 b_xwyz = KLN_SWIZZLE(b, 2, 1, 3, 0); __m128 b_xzwy = KLN_SWIZZLE(b, 1, 3, 2, 0); __m128 tmp1 = _mm_mul_ps(b, b_xwyz); tmp1 = _mm_sub_ps(tmp1, _mm_mul_ps(b_xxxx, b_xzwy)); tmp1 = _mm_mul_ps(tmp1, two); // tmp1 needs to be scaled by (_, a3, a1, a2) __m128 tmp2 = _mm_mul_ps(b_xxxx, b_xwyz); tmp2 = _mm_add_ps(tmp2, _mm_mul_ps(b_xzwy, b)); tmp2 = _mm_mul_ps(tmp2, two); // tmp2 needs to be scaled by (_, a2, a3, a1) __m128 tmp3 = _mm_mul_ps(b, b); __m128 b_tmp = KLN_SWIZZLE(b, 0, 0, 0, 1); tmp3 = _mm_add_ps(tmp3, _mm_mul_ps(b_tmp, b_tmp)); b_tmp = KLN_SWIZZLE(b, 2, 1, 3, 2); __m128 tmp4 = _mm_mul_ps(b_tmp, b_tmp); b_tmp = KLN_SWIZZLE(b, 1, 3, 2, 3); tmp4 = _mm_add_ps(tmp4, _mm_mul_ps(b_tmp, b_tmp)); tmp3 = _mm_sub_ps(tmp3, _mm_xor_ps(tmp4, _mm_set_ss(-0.f))); // tmp3 needs to be scaled by (a0, a1, a2, a3) if constexpr (Translate) { tmp4 = _mm_mul_ps(b_xzwy, KLN_SWIZZLE(*c, 2, 1, 3, 0)); tmp4 = _mm_sub_ps(tmp4, _mm_mul_ps(b_xxxx, *c)); tmp4 = _mm_sub_ps( tmp4, _mm_mul_ps(b_xwyz, KLN_SWIZZLE(*c, 1, 3, 2, 0))); tmp4 = _mm_sub_ps(tmp4, _mm_mul_ps(b, KLN_SWIZZLE(*c, 0, 0, 0, 0))); // Mask low component and scale other components by 2 tmp4 = _mm_mul_ps(tmp4, two); // tmp4 needs to be scaled by (_, a0, a0, a0) } size_t limit = Variadic ? count : 1; for (size_t i = 0; i != limit; ++i) { __m128& p = out[i]; p = _mm_mul_ps(tmp1, KLN_SWIZZLE(a[i], 2, 1, 3, 0)); p = _mm_add_ps(p, _mm_mul_ps(tmp2, KLN_SWIZZLE(a[i], 1, 3, 2, 0))); p = _mm_add_ps(p, _mm_mul_ps(tmp3, a[i])); if constexpr (Translate) { p = _mm_add_ps( p, _mm_mul_ps(tmp4, KLN_SWIZZLE(a[i], 0, 0, 0, 0))); } } } #else // Use header that avoids `if constexpr` usage # include "x86_sandwich_cxx11.inl" #endif // Conjugate origin with motor. Unlike other operations the motor MUST be // normalized prior to usage b is the rotor component (p1) c is the // translator component (p2) KLN_INLINE __m128 swo12(__m128 b, __m128 c) { // (b0^2 + b1^2 + b2^2 + b3^2) e123 + // 2(b2 c3 - b1 c0 - b0 c1 - b3 c2) e032 + // 2(b3 c1 - b2 c0 - b0 c2 - b1 c3) e013 + // 2(b1 c2 - b3 c0 - b0 c3 - b2 c1) e021 __m128 tmp = _mm_mul_ps(b, KLN_SWIZZLE(c, 0, 0, 0, 0)); tmp = _mm_add_ps(tmp, _mm_mul_ps(KLN_SWIZZLE(b, 0, 0, 0, 0), c)); tmp = _mm_add_ps( tmp, _mm_mul_ps(KLN_SWIZZLE(b, 2, 1, 3, 0), KLN_SWIZZLE(c, 1, 3, 2, 0))); tmp = _mm_sub_ps( _mm_mul_ps(KLN_SWIZZLE(b, 1, 3, 2, 0), KLN_SWIZZLE(c, 2, 1, 3, 0)), tmp); tmp = _mm_mul_ps(tmp, _mm_set_ps(2.f, 2.f, 2.f, 0.f)); // b0^2 + b1^2 + b2^2 + b3^2 assumed to equal 1 // Set the low component to unity return _mm_add_ps(tmp, _mm_set_ss(1.f)); } } // namespace detail } // namespace kln#include "engine_startup.h" #include "system_manager.h" #include "event_system.h" #include "job_system.h" #include "input_system.h" #include "render_system.h" #include "script_system.h" #include "graphics_system.h" #include "debug_gui_system.h" #include "physics_system.h" #include "sdf_mesh_system.h" #include "camera_system.h" #include "raycast_system.h" #include "entity/entity_system.h" #include "platform.h" #include "core/log.h" #include "core/timer.h" #include "core/random.h" #include namespace Engine { class EngineSystemRegister : public SystemRegister { public: EngineSystemRegister(SystemManager& sys) : m_systemManager(sys) {} virtual void Register(const char* systemName, System* theSystem) { m_systemManager.RegisterSystem(systemName, theSystem); } SystemManager& m_systemManager; }; // Application entry point int Run(std::function systemCreation, int argc, char* args[]) { // Initialise platform stuff Platform::InitResult result = Platform::Initialise(argc, args); assert(result == Platform::InitResult::InitOK); if (result == Platform::InitResult::InitFailed) { return 1; } // Init random number generator Core::Random::ResetGlobalSeed(); auto physics = new PhysicsSystem; auto render = new RenderSystem; auto raycaster = new RaycastSystem; SystemManager sysManager; sysManager.RegisterSystem("Events", new EventSystem); sysManager.RegisterSystem("Jobs", new JobSystem); sysManager.RegisterSystem("Input", new InputSystem); sysManager.RegisterSystem("Script", new ScriptSystem); sysManager.RegisterSystem("DebugGui", new DebugGuiSystem); sysManager.RegisterSystem("PhysicsEntities", physics->MakeUpdater()); sysManager.RegisterSystem("RaycastResults", raycaster->MakeResultProcessor()); EngineSystemRegister registerSystems(sysManager); systemCreation(registerSystems); sysManager.RegisterSystem("Entities", new EntitySystem); sysManager.RegisterSystem("SDFMeshes", new SDFMeshSystem); sysManager.RegisterSystem("Graphics", new GraphicsSystem); sysManager.RegisterSystem("Raycasts", raycaster); sysManager.RegisterSystem("Physics", physics); sysManager.RegisterSystem("Cameras", new CameraSystem); sysManager.RegisterSystem("Render", render); sysManager.RegisterSystem("RenderPresent", render->MakePresenter()); // Run the engine SDE_LOGC(Engine, "Initialising systems..."); bool initResult = sysManager.Initialise(); assert(initResult); if (initResult == true) { SDE_LOGC(Engine, "Running engine main loop"); Core::Timer engineTime; double startTime = engineTime.GetSeconds(); double lastTickTime = startTime; bool running = true; while (running) { double thisTime = engineTime.GetSeconds(); double deltaTime = glm::clamp(thisTime - lastTickTime, 0.0047, 0.033); lastTickTime = thisTime; running = sysManager.Tick(deltaTime); } } SDE_LOGC(Engine, "Shutting down systems"); sysManager.Shutdown(); // Shutdown auto shutdownResult = Platform::Shutdown(); assert(shutdownResult == Platform::ShutdownResult::ShutdownOK); return shutdownResult == Platform::ShutdownResult::ShutdownOK ? 0 : 1; } }menghanl/traffic-director-grpc-examples10-100 /* * * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include #include #include #include #include "grpcpp/ext/proto_server_reflection_plugin.h" #include "grpcpp/grpcpp.h" #include "grpcpp/health_check_service_interface.h" #include "grpcpp/opencensus.h" #include "opencensus/exporters/stats/stackdriver/stackdriver_exporter.h" #include "opencensus/exporters/trace/stackdriver/stackdriver_exporter.h" #include "opencensus/trace/with_span.h" #include "proto/grpc/examples/wallet/account/account.grpc.pb.h" #include "proto/grpc/examples/wallet/stats/stats.grpc.pb.h" #include "proto/grpc/examples/wallet/wallet.grpc.pb.h" #include "utility.h" using grpc::Channel; using grpc::ChannelArguments; using grpc::ClientContext; using grpc::ClientReader; using grpc::Server; using grpc::ServerBuilder; using grpc::ServerContext; using grpc::ServerWriter; using grpc::Status; using grpc::StatusCode; using grpc::examples::wallet::BalanceRequest; using grpc::examples::wallet::BalanceResponse; using grpc::examples::wallet::Wallet; using grpc::examples::wallet::account::Account; using grpc::examples::wallet::account::GetUserInfoRequest; using grpc::examples::wallet::account::GetUserInfoResponse; using grpc::examples::wallet::account::MembershipType; using grpc::examples::wallet::stats::PriceRequest; using grpc::examples::wallet::stats::PriceResponse; using grpc::examples::wallet::stats::Stats; class WalletServiceImpl final : public Wallet::Service { public: WalletServiceImpl(const std::string& hostname, const bool v1_behavior) : hostname_(hostname), v1_behavior_(v1_behavior) {} void SetStatsClientStub(std::unique_ptr stub) { stats_stub_ = std::move(stub); } void SetAccountClientStub(std::unique_ptr stub) { account_stub_ = std::move(stub); } private: Status ObtainAndValidateUserAndMembership(ServerContext* server_context) { const std::multimap metadata = server_context->client_metadata(); for (auto iter = metadata.begin(); iter != metadata.end(); ++iter) { if (iter->first == "authorization") token_ = std::string(iter->second.data(), iter->second.size()); else if (iter->first == "membership") membership_ = std::string(iter->second.data(), iter->second.size()); else if (iter->first == "route") route_ = std::string(iter->second.data(), iter->second.size()); } GetUserInfoRequest request; request.set_token(token_); ClientContext context; context.set_wait_for_ready(true); if (!route_.empty()) context.AddMetadata("route", route_); GetUserInfoResponse response; Status status = account_stub_->GetUserInfo(&context, request, &response); if (status.ok()) { auto metadata_hostname = context.GetServerInitialMetadata().find("hostname"); if (metadata_hostname != context.GetServerInitialMetadata().end()) { std::cout << "server host: " << std::string(metadata_hostname->second.data(), metadata_hostname->second.length()) << std::endl; } } else { std::cout << status.error_code() << ": " << status.error_message() << std::endl; return status; } user_ = response.name(); // User requested premium service, but the user is not a premium user, // reject the request. if (membership_ == "premium" && response.membership() != MembershipType::PREMIUM) { std::cout << "token: " << token_ << ", name: " << user_ << ", membership: " << response.membership() << "," << std::endl; std::cout << "requested membership: " << membership_ << ", authentication FAILED" << std::endl; return Status(StatusCode::UNAUTHENTICATED, "membership authentication failed"); } std::cout << "token: " << token_ << ", name: " << user_ << ", membership: " << response.membership() << "," << std::endl; std::cout << "requested membership: " << membership_ << ", authentication success true" << std::endl; return Status::OK; } int ObtainAndBuildPerAddressResponse(const int price, const BalanceRequest* request, BalanceResponse* response) { int total_balance = 0; for (auto& address_entry : user_coin_map_[user_]) { int per_address_balance = address_entry.second * price; total_balance += per_address_balance; if (!v1_behavior_ && request->include_balance_per_address()) { auto* address = response->add_addresses(); address->set_address(address_entry.first); address->set_balance(per_address_balance); } } return total_balance; } Status FetchBalance(ServerContext* context, const BalanceRequest* request, BalanceResponse* response) override { opencensus::trace::Span span = context->census_context() == nullptr ? opencensus::trace::Span::BlankSpan() : grpc::GetSpanFromServerContext(context); { // Run in OpenCensus span received from the client to correlate the traces // in Cloud Monitoring. opencensus::trace::WithSpan ws(span); auto status = ObtainAndValidateUserAndMembership(context); if (!status.ok()) { return status; } context->AddInitialMetadata("hostname", hostname_); ClientContext stats_context; stats_context.set_wait_for_ready(true); stats_context.AddMetadata("authorization", token_); stats_context.AddMetadata("membership", membership_); PriceRequest stats_request; PriceResponse stats_response; // Call Stats Server to fetch the price to calculate the balance. Status stats_status = stats_stub_->FetchPrice( &stats_context, stats_request, &stats_response); if (stats_status.ok()) { auto metadata_hostname = stats_context.GetServerInitialMetadata().find("hostname"); if (metadata_hostname != stats_context.GetServerInitialMetadata().end()) { std::cout << "server host: " << std::string(metadata_hostname->second.data(), metadata_hostname->second.length()) << std::endl; } std::cout << "grpc-coin price " << stats_response.price() << std::endl; } else { std::cout << stats_status.error_code() << ": " << stats_status.error_message() << std::endl; } int total_balance = ObtainAndBuildPerAddressResponse( stats_response.price(), request, response); response->set_balance(total_balance); return Status::OK; } } Status WatchBalance(ServerContext* context, const BalanceRequest* request, ServerWriter* writer) override { opencensus::trace::Span span = context->census_context() == nullptr ? opencensus::trace::Span::BlankSpan() : grpc::GetSpanFromServerContext(context); { // Run in OpenCensus span received from the client to correlate the traces // in Cloud Monitoring. opencensus::trace::WithSpan ws(span); auto status = ObtainAndValidateUserAndMembership(context); if (!status.ok()) { return status; } context->AddInitialMetadata("hostname", hostname_); ClientContext stats_context; stats_context.set_wait_for_ready(true); stats_context.AddMetadata("authorization", token_); stats_context.AddMetadata("membership", membership_); PriceRequest stats_request; PriceResponse stats_response; // Open a streaming price watching with Stats Server. // Every time a response // is received, use the price to calculate the balance. // Send every updated balance in a stream back to the client. std::unique_ptr> stats_reader( stats_stub_->WatchPrice(&stats_context, stats_request)); bool first_read = true; while (stats_reader->Read(&stats_response)) { if (first_read) { auto metadata_hostname = stats_context.GetServerInitialMetadata().find("hostname"); if (metadata_hostname != stats_context.GetServerInitialMetadata().end()) { std::cout << "server host: " << std::string(metadata_hostname->second.data(), metadata_hostname->second.length()) << std::endl; } first_read = false; } std::cout << "grpc-coin price: " << stats_response.price() << std::endl; BalanceResponse response; int total_balance = ObtainAndBuildPerAddressResponse( stats_response.price(), request, &response); response.set_balance(total_balance); if (!writer->Write(response)) { break; } } return Status::OK; } } std::string hostname_; bool v1_behavior_ = false; std::unique_ptr stats_stub_; std::unique_ptr account_stub_; std::string token_; std::string user_ = "Alice"; std::string membership_ = "premium"; std::string route_; std::map> user_coin_map_ = { {"Alice", {{"cd0aa985", 314}, {"454349e4", 159}}}, {"Bob", {{"148de9c5", 271}, {"2e7d2c03", 828}}}}; }; void RunServer(const std::string& port, const std::string& account_server, const std::string& stats_server, const std::string& hostname_suffix, const bool v1_behavior, const std::string& creds_type) { char base_hostname[256]; if (gethostname(base_hostname, 256) != 0) { sprintf(base_hostname, "%s-%d", "generated", rand() % 1000); } std::string hostname(base_hostname); hostname += hostname_suffix; std::string server_address("0.0.0.0:"); server_address += port; WalletServiceImpl service(hostname, v1_behavior); // Instantiate the client stubs. It requires a channel, out of which the // actual RPCs are created. The channel models a connection to an endpoint // (Stats Server and Account Server in this case). We indicate that the // channel isn't authenticated (use of InsecureChannelCredentials()). ChannelArguments args; service.SetStatsClientStub(Stats::NewStub(grpc::CreateCustomChannel( stats_server, traffic_director_grpc_examples::GetChannelCredetials(creds_type), args))); service.SetAccountClientStub(Account::NewStub(grpc::CreateCustomChannel( account_server, traffic_director_grpc_examples::GetChannelCredetials(creds_type), args))); // Listen on the given address without any authentication mechanism. std::cout << "Wallet server listening on " << server_address << std::endl; grpc::EnableDefaultHealthCheckService(true); grpc::reflection::InitProtoReflectionServerBuilderPlugin(); auto builder = traffic_director_grpc_examples::GetServerBuilder(creds_type); builder->AddListeningPort( server_address, traffic_director_grpc_examples::GetServerCredentials(creds_type)); // Register "service" as the instance through which we'll communicate with // clients. In this case it corresponds to an *synchronous* service. builder->RegisterService(&service); // Finally assemble the server. std::unique_ptr server(builder->BuildAndStart()); // Wait for the server to shutdown. Note that some other thread must be // responsible for shutting down the server for this call to ever return. server->Wait(); } int main(int argc, char** argv) { std::string port = "18881"; std::string admin_port = "28881"; std::string account_server = "localhost:18882"; std::string stats_server = "localhost:18883"; std::string hostname_suffix = ""; bool v1_behavior = false; std::string gcp_client_project = ""; std::string arg_str_port("--port"); std::string arg_str_admin_port("--admin_port"); std::string arg_str_account_server("--account_server"); std::string arg_str_stats_server("--stats_server"); std::string arg_str_hostname_suffix("--hostname_suffix"); std::string arg_str_v1_behavior("--v1_behavior"); std::string arg_str_gcp_client_project("--gcp_client_project"); std::string creds_type = traffic_director_grpc_examples::ParseCommandLineArgForCredsType(argc, argv); for (int i = 1; i < argc; ++i) { std::string arg_val = argv[i]; size_t start_pos = arg_val.find(arg_str_port); if (start_pos != std::string::npos) { start_pos += arg_str_port.size(); if (arg_val[start_pos] == '=') { port = arg_val.substr(start_pos + 1); continue; } else { std::cout << "The only correct argument syntax is --port=" << std::endl; return 1; } } start_pos = arg_val.find(arg_str_admin_port); if (start_pos != std::string::npos) { start_pos += arg_str_admin_port.size(); if (arg_val[start_pos] == '=') { admin_port = arg_val.substr(start_pos + 1); continue; } else { std::cout << "The only correct argument syntax is --admin_port=" << std::endl; return 1; } } start_pos = arg_val.find(arg_str_account_server); if (start_pos != std::string::npos) { start_pos += arg_str_account_server.size(); if (arg_val[start_pos] == '=') { account_server = arg_val.substr(start_pos + 1); continue; } else { std::cout << "The only correct argument syntax is --account_server=" << std::endl; return 1; } } start_pos = arg_val.find(arg_str_stats_server); if (start_pos != std::string::npos) { start_pos += arg_str_stats_server.size(); if (arg_val[start_pos] == '=') { stats_server = arg_val.substr(start_pos + 1); continue; } else { std::cout << "The only correct argument syntax is --stats_server=" << std::endl; return 1; } } start_pos = arg_val.find(arg_str_hostname_suffix); if (start_pos != std::string::npos) { start_pos += arg_str_hostname_suffix.size(); if (arg_val[start_pos] == '=') { hostname_suffix = arg_val.substr(start_pos + 1); continue; } else { std::cout << "The only correct argument syntax is --hostname_suffix=" << std::endl; return 1; } } start_pos = arg_val.find(arg_str_v1_behavior); if (start_pos != std::string::npos) { start_pos += arg_str_v1_behavior.size(); if (arg_val[start_pos] == '=') { if (arg_val.substr(start_pos + 1) == "true") { v1_behavior = true; continue; } else if (arg_val.substr(start_pos + 1) == "false") { v1_behavior = false; continue; } else { std::cout << "The only correct value for argument --v1_behavior is " "true or false" << std::endl; return 1; } } else { std::cout << "The only correct argument syntax is --v1_behavior=" << std::endl; return 1; } } start_pos = arg_val.find(arg_str_gcp_client_project); if (start_pos != std::string::npos) { start_pos += arg_str_gcp_client_project.size(); if (arg_val[start_pos] == '=') { gcp_client_project = arg_val.substr(start_pos + 1); continue; } else { std::cout << "The only correct argument syntax is --gcp_client_project=" << std::endl; return 1; } } } std::cout << "Wallet Server arguments: port: " << port << ", account_server: " << account_server << ", stats_server: " << stats_server << ", hostname_suffix: " << hostname_suffix << ", v1_behavior: " << v1_behavior << ", gcp_client_project: " << gcp_client_project << ", creds: " << creds_type << std::endl; if (!gcp_client_project.empty()) { grpc::RegisterOpenCensusPlugin(); grpc::RegisterOpenCensusViewsForExport(); opencensus::trace::TraceConfig::SetCurrentTraceParams( {128, 128, 128, 128, opencensus::trace::ProbabilitySampler(1.0)}); opencensus::exporters::trace::StackdriverOptions trace_opts; trace_opts.project_id = gcp_client_project; opencensus::exporters::trace::StackdriverExporter::Register( std::move(trace_opts)); opencensus::exporters::stats::StackdriverOptions stats_opts; stats_opts.project_id = gcp_client_project; // This must be unique among all processes exporting to Stackdriver stats_opts.opencensus_task = "wallet-server-" + std::to_string(getpid()); opencensus::exporters::stats::StackdriverExporter::Register( std::move(stats_opts)); } auto admin_server = traffic_director_grpc_examples::StartAdminServer(admin_port); RunServer(port, account_server, stats_server, hostname_suffix, v1_behavior, creds_type); return 0; } // Copyright (c) 2017-2022, Mudita .o.o. All rights reserved. // For licensing, see https://github.com/mudita/MuditaOS/LICENSE.md #pragma once #include namespace cellular::service { class URCCounter { public: void count(); void clearCounter(); auto getCounter() -> uint32_t; private: uint32_t urcOccurences = 0; }; } // namespace cellular::service 0 /** * grading_lock_manager_test_1.cpp */ #include #include //NOLINT #include #include //NOLINT #include "common/logger.h" #include "concurrency/transaction.h" #include "concurrency/transaction_manager.h" #include "gtest/gtest.h" namespace bustub { #define TEST_TIMEOUT_BEGIN \ std::promise promisedFinished; \ auto futureResult = promisedFinished.get_future(); \ std::thread([](std::promise& finished) { #define TEST_TIMEOUT_FAIL_END(X) \ finished.set_value(true); \ }, std::ref(promisedFinished)).detach(); \ EXPECT_TRUE(futureResult.wait_for(std::chrono::milliseconds(X)) != std::future_status::timeout) \ << "Test Failed Due to Time Out"; // --- Helper functions --- void CheckGrowing(Transaction *txn) { if(txn->GetState() != TransactionState::GROWING) { assert(false); } EXPECT_EQ(txn->GetState(), TransactionState::GROWING); } void CheckShrinking(Transaction *txn) { EXPECT_EQ(txn->GetState(), TransactionState::SHRINKING); } void CheckAborted(Transaction *txn) { EXPECT_EQ(txn->GetState(), TransactionState::ABORTED); } void CheckCommitted(Transaction *txn) { EXPECT_EQ(txn->GetState(), TransactionState::COMMITTED); } void CheckTxnLockSize(Transaction *txn, size_t shared_size, size_t exclusive_size) { EXPECT_EQ(txn->GetSharedLockSet()->size(), shared_size); EXPECT_EQ(txn->GetExclusiveLockSet()->size(), exclusive_size); } // --- Real tests --- // Basic shared lock test under REPEATABLE_READ void BasicTest1() { LockManager lock_mgr{}; TransactionManager txn_mgr{&lock_mgr}; std::vector rids; std::vector txns; int num_rids = 10; for (int i = 0; i < num_rids; i++) { RID rid{i, static_cast(i)}; rids.push_back(rid); txns.push_back(txn_mgr.Begin()); EXPECT_EQ(i, txns[i]->GetTransactionId()); } // test auto task = [&](int txn_id) { bool res; for (const RID &rid : rids) { res = lock_mgr.LockShared(txns[txn_id], rid); EXPECT_TRUE(res); if(txns[txn_id]->GetState() != TransactionState::GROWING) { assert(false); } CheckGrowing(txns[txn_id]); } for (const RID &rid : rids) { res = lock_mgr.Unlock(txns[txn_id], rid); EXPECT_TRUE(res); CheckShrinking(txns[txn_id]); } txn_mgr.Commit(txns[txn_id]); CheckCommitted(txns[txn_id]); }; std::vector threads; threads.reserve(num_rids); for (int i = 0; i < num_rids; i++) { threads.emplace_back(std::thread{task, i}); } for (int i = 0; i < num_rids; i++) { threads[i].join(); } for (int i = 0; i < num_rids; i++) { delete txns[i]; } } // Basic shared lock test under READ_COMMITTED void BasicTest2() { LockManager lock_mgr{}; TransactionManager txn_mgr{&lock_mgr}; std::vector rids; std::vector txns; int num_rids = 10; for (int i = 0; i < num_rids; i++) { RID rid{i, static_cast(i)}; rids.push_back(rid); txns.push_back(txn_mgr.Begin(nullptr, IsolationLevel::READ_COMMITTED)); EXPECT_EQ(i, txns[i]->GetTransactionId()); } // test auto task = [&](int txn_id) { bool res; for (const RID &rid : rids) { res = lock_mgr.LockShared(txns[txn_id], rid); EXPECT_TRUE(res); CheckGrowing(txns[txn_id]); } for (const RID &rid : rids) { res = lock_mgr.Unlock(txns[txn_id], rid); EXPECT_TRUE(res); CheckGrowing(txns[txn_id]); } txn_mgr.Commit(txns[txn_id]); CheckCommitted(txns[txn_id]); }; std::vector threads; threads.reserve(num_rids); for (int i = 0; i < num_rids; i++) { threads.emplace_back(std::thread{task, i}); } for (int i = 0; i < num_rids; i++) { threads[i].join(); } for (int i = 0; i < num_rids; i++) { delete txns[i]; } } // Basic shared lock test under READ_UNCOMMITTED void BasicTest3() { LockManager lock_mgr{}; TransactionManager txn_mgr{&lock_mgr}; std::vector rids; std::vector txns; int num_rids = 10; for (int i = 0; i < num_rids; i++) { RID rid{i, static_cast(i)}; rids.push_back(rid); txns.push_back(txn_mgr.Begin(nullptr, IsolationLevel::READ_UNCOMMITTED)); EXPECT_EQ(i, txns[i]->GetTransactionId()); } // test auto task = [&](int txn_id) { for (const RID &rid : rids) { try { lock_mgr.LockShared(txns[txn_id], rid); } catch (TransactionAbortException &e) { CheckAborted(txns[txn_id]); } } }; std::vector threads; threads.reserve(num_rids); for (int i = 0; i < num_rids; i++) { threads.emplace_back(std::thread{task, i}); } for (int i = 0; i < num_rids; i++) { threads[i].join(); } for (int i = 0; i < num_rids; i++) { delete txns[i]; } } // Correct case /**************************** * Basic Tests (15 pts) ****************************/ const size_t NUM_ITERS = 10; /* * Score: 5 * Description: Basic tests for LockShared and Unlock operations * on small amount of rids. */ TEST(LockManagerTest, BasicTest) { TEST_TIMEOUT_BEGIN for (size_t i = 0; i < NUM_ITERS; i++) { BasicTest1(); BasicTest2(); BasicTest3(); } TEST_TIMEOUT_FAIL_END(1000 * 30 * 3600) } } // namespace bustub0 #ifndef SHAPE_HPP #define SHAPE_HPP #include #include "color.hpp" #include class Shape{ public: Shape(); Shape(std::string name, Color color); virtual ~Shape(); virtual float area() const = 0; virtual float volume() const = 0; virtual std::ostream& print( std::ostream& os) const; protected: std::string name_; Color colour_; }; std::ostream& operator<<(std::ostream& os ,Shape const& s); #endiftunki/lang-training0 #include #include using namespace std; // Se declara la existencia de las // funciones con el fin de poder usarlas // desde main() (Problema dado en C++) void fun1(); int fun2(); void fun3(); void fun4(); void fun5(); int main() { fun5(); //int a = fun2(); //cout << a << '\n'; //endl; return 0; } void fun5() { char string [256]; printf ("Ingrese su direccion: "); gets (string); printf ("Tu direccion es:"); puts(string); printf("\n"); } void fun4() { int c; puts ("Ingrese texto. Incluya un punto ('.') para terminar el texto:"); do { c = getchar(); //putchar (c); } while (c != '.'); } void fun3() { /* ejemplos de printf */ printf("EJEMPLO DE LOS TIPOS DE VARIABLES\n\n"); printf ("Variables de Caracteres(char): %c %c \n", 'a', 65); printf ("Variables Decimales (int ylong int): %d %ld\n", 1977, 650000L); printf ("Precedido de espacios: %10d \n", 1977); //Se agregan por la izquierda. printf ("Precedido de zeros: %010d \n", 1977); // Se agregan ceros por la izquierda. printf ("Algunas bases diferentes: %d %x %o %#x %#o \n", 100, 100, 100, 100, 100); printf ("Variables floats: %4.2f %+.0e %E \n", 3.1416, 3.1416, 3.1416); printf ("Cortando Ancho: %*d \n", 5, 10); // Al 5to espacio se escribe la variable. } int fun2(){ // TADA!! Se puede declarar // y asignar al mismo tiempo int a = 5, b = 2; a = a + 1; int result = a - b; return result; } void fun1() { cout << "Hola CCPP-UNI!" << endl; } #include "treeitem.h" #include QPointer TreeItem::s_selected = 0; QPointer TreeItem::s_highlighted = 0; TreeItem::TreeItem(TreeItem *parent, const QString &content, const QColor &color, const QUrl &imageUrl, const QUrl &imageOpenUrl, bool isOpen) : QObject(parent), m_parentItem(parent), m_content(content), m_color(color), m_selected(false), m_highlighted(false), m_level(-1), m_childItems(QList()), m_isOpen(isOpen), m_var("vds://factory1.plant1.0.0/value.toString"), m_imageUrl(imageUrl), m_imageOpenUrl(imageOpenUrl), m_subSelected(false) { if (parent) { parent->addChildItem(this); setLevel(parent->level() + 1); } } const QString &TreeItem::content() const { return m_content; } void TreeItem::setContent(const QString &content) { //qDebug() << "TreeItem::setContent" << content; if (content != m_content) { m_content = content; emit contentChanged(); } } QColor TreeItem::color() { return m_color; } void TreeItem::setColor(QColor color) { if (color != m_color){ m_color = color; emit colorChanged(); } } QUrl TreeItem::imageOpenUrl() const { return m_imageOpenUrl; } QUrl TreeItem::imageUrl() const { return m_imageUrl; } bool TreeItem::selected() const { return m_selected; } void TreeItem::setSelected(bool selected) { if (selected != m_selected) { if (s_selected && (s_selected != this) && selected) s_selected->setSelected(false); m_selected = selected; s_selected = this; setSelectedItem(this); emit selectedChanged(); if (m_parentItem) m_parentItem->setSubSelected(selected); } } bool TreeItem::highlighted() const { return m_highlighted; } void TreeItem::setHighlighted(bool highlighted) { if (highlighted != m_highlighted) { if (s_highlighted && (s_highlighted != this) && highlighted) s_highlighted->setHighlighted(false); m_highlighted = highlighted; s_highlighted = this; emit highlightedChanged(); } } TreeItem *TreeItem::selectedItem() const { return s_selected; } void TreeItem::setSelectedItem(TreeItem *selectedItem) { //qDebug() << "TreeItem::setSelectedItem" << selectedItem << s_selected; s_selected = selectedItem; emit selectedItemChanged(s_selected); } TreeItem *TreeItem::parentItem() const { return m_parentItem; } int TreeItem::level() const { return m_level; } void TreeItem::setLevel(int level) { if(level != m_level){ m_level = level; emit levelChanged(); } } int TreeItem::childCount() const { return m_childItems.count(); } int TreeItem::isLeaf() const { return childCount() > 0; } //! индекс в parent->m_childItems int TreeItem::index() const { if (!m_parentItem) return -1; else { TreeItem *p = m_parentItem; int inx = p->m_childItems.indexOf(const_cast(this)); return inx; } } const QList &TreeItem::childItems() const { return m_childItems; } const QList TreeItem::childItemsAsQObject() const{ QList res; res.reserve(m_childItems.count()); for(auto i : m_childItems) res.append(i); return res; } void TreeItem::addChildItem(TreeItem *childItem, bool silent){ m_childItems.append(childItem); setIsOpen(true); if (!silent) { emit childItemsChanged(); emit hasChildChanged(); } } bool TreeItem::isOpen() const{ return m_isOpen; //return m_childItems.count() == 0 ? true : m_isOpen; } void TreeItem::setIsOpen(bool isOpen){ if(isOpen != m_isOpen){ m_isOpen = isOpen; emit isOpenChanged(); } } bool TreeItem::hasChild() const{ return !m_childItems.isEmpty(); } QString TreeItem::variable() const { return m_var; } void TreeItem::setVariable(QString variable) { if (variable != m_var) { m_var = variable; emit variableChanged(); } } bool TreeItem::subSelected() const { return m_subSelected; } void TreeItem::setSubSelected(bool subSelected) { if (subSelected != m_subSelected) { m_subSelected = subSelected; if (m_parentItem) { m_parentItem->setSubSelected(m_subSelected); } emit subSelectedChanged(); } } void TreeItem::silentClear() { foreach (TreeItem* ti, childItems()) { //delete ti; } m_childItems.clear(); } void TreeItem::removeChild(TreeItem *child) { m_childItems.removeAll(child); delete child; emit childCountChanged(); emit childItemsChanged(); } #include "testApp.hpp" #include "rubykokuban/BindInput.hpp" //-------------------------------------------------------------- testApp::testApp(const char* aScriptPath) : mInput() , mScriptEngine(aScriptPath) { rubykokuban::BindInput::Setup(mInput); } //-------------------------------------------------------------- void testApp::setup() { // setup openFrameworks ofSetFrameRate(60); ofSetVerticalSync(true); ofEnableAlphaBlending(); // ofBackground(255, 255, 255); // bind & call function mScriptEngine.setup(); } //-------------------------------------------------------------- void testApp::update() { mInput.update(); mScriptEngine.funcallIf("update"); } //-------------------------------------------------------------- void testApp::draw() { mScriptEngine.draw(); ofSetColor(255, 255, 255); } //-------------------------------------------------------------- void testApp::keyPressed(int key) { if (key == 18) { // Ctrl+R mScriptEngine.reload(); } // cout << "keyPressed " << key << endl; } //-------------------------------------------------------------- void testApp::keyReleased(int key) { // cout << "keyReleased " << key << endl; } //-------------------------------------------------------------- void testApp::mouseMoved(int x, int y) { mInput.mouse().setInternalPos(x, y); mScriptEngine.funcallIf("mouse_moved", mrb_fixnum_value(x), mrb_fixnum_value(y)); } //-------------------------------------------------------------- void testApp::mouseDragged(int x, int y, int button) { mInput.mouse().setInternalPos(x, y); } //-------------------------------------------------------------- void testApp::mousePressed(int x, int y, int button) { mInput.mouse().setInternalPos(x, y); mInput.mouse().setInternalPress(button); mScriptEngine.funcallIf("mouse_pressed", mrb_fixnum_value(x), mrb_fixnum_value(y), mrb_fixnum_value(button)); } //-------------------------------------------------------------- void testApp::mouseReleased(int x, int y, int button) { mInput.mouse().setInternalPos(x, y); mInput.mouse().setInternalRelease(button); mScriptEngine.funcallIf("mouse_released", mrb_fixnum_value(x), mrb_fixnum_value(y), mrb_fixnum_value(button)); } //-------------------------------------------------------------- void testApp::windowResized(int w, int h) { } //-------------------------------------------------------------- void testApp::gotMessage(ofMessage msg) { } //-------------------------------------------------------------- void testApp::dragEvent(ofDragInfo dragInfo) { } //EOF Tool/kvsview/Histogram.cpp /*****************************************************************************/ /** * @file Histogram.cpp * @author */ /*****************************************************************************/ #include "Histogram.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "CommandName.h" #include "FileChecker.h" namespace { // Default parameters. const kvs::RGBColor DefaultBackgroundColor( 212, 221, 229 ); const kvs::RGBColor DefaultHistogramColor( 100, 100, 100 ); const float DefaultBiasParameter( 0.5f ); const size_t DefaultScreenWidth( 512 ); const size_t DefaultScreenHeight( 150 ); } namespace kvsview { namespace Histogram { /*===========================================================================*/ /** * @brief Parameter set. */ /*===========================================================================*/ struct Parameters { kvs::Vector2i mouse; ///< mouse position for 2D operation kvs::FrequencyTable frequency_table; ///< frequency table float bias_parameter; ///< bias parameter [0,1] kvs::Texture2D histogram_texture; ///< histogram texture Parameters( Argument& arg ) { bias_parameter = arg.biasParameter(); } bool createFrequencyTable( const std::string& filename ) { if ( kvsview::FileChecker::ImportableStructuredVolume( filename ) ) { kvs::StructuredVolumeObject* object = new kvs::StructuredVolumeImporter( filename ); if ( !object ) { kvsMessageError("Cannot import a structured volume object."); return false; } object->updateMinMaxValues(); this->frequency_table.create( object ); } else if ( kvsview::FileChecker::ImportableUnstructuredVolume( filename ) ) { kvs::UnstructuredVolumeObject* object = new kvs::UnstructuredVolumeImporter( filename ); if ( !object ) { kvsMessageError("Cannot import a unstructured volume object."); return false; } object->updateMinMaxValues(); this->frequency_table.create( object ); } return true; } void createHistogramTexture() { const size_t nchannels = 4; const size_t width = static_cast( this->frequency_table.numberOfBins() ); const size_t height = width; this->histogram_texture.setPixelFormat( nchannels, sizeof( kvs::UInt8 ) ); this->histogram_texture.create( width, height ); this->histogram_texture.load( width, height, this->histogramImage().data() ); } void updateHistogramTexture() { this->histogram_texture.release(); this->createHistogramTexture(); } const kvs::ValueArray histogramImage() { const size_t nchannels = 4; const size_t width = static_cast( frequency_table.numberOfBins() ); const size_t height = width; const size_t npixels = width * height; kvs::ValueArray data( npixels * nchannels ); data.fill( 0 ); const float g = bias_parameter; // bias parameter const kvs::Real32 normalized_factor = 1.0f / ( frequency_table.maxCount() ); for ( size_t i = 0; i < width; i++ ) { const size_t n = frequency_table.bin().at(i); // frequency count const float f = n * normalized_factor; // normalized frequency count in [0,1] const float b = std::pow( f, static_cast( std::log(g) / std::log(0.5) ) ); const size_t h = static_cast( b * height + 0.5f ); for ( size_t j = 0; j < h; j++ ) { const size_t index = i + j * width; data[ 4 * index + 0 ] = ::DefaultHistogramColor.r(); data[ 4 * index + 1 ] = ::DefaultHistogramColor.g(); data[ 4 * index + 2 ] = ::DefaultHistogramColor.b(); data[ 4 * index + 3 ] = kvs::UInt8( 255 ); } } return data; } }; /*===========================================================================*/ /** * @brief Initialize event. */ /*===========================================================================*/ class InitializeEvent : public kvs::InitializeEventListener { private: kvsview::Histogram::Parameters* m_parameters; public: InitializeEvent( kvsview::Histogram::Parameters* parameters ): m_parameters( parameters ) {} void update() { m_parameters->createHistogramTexture(); } }; /*===========================================================================*/ /** * @brief Paint event. */ /*===========================================================================*/ class PaintEvent : public kvs::PaintEventListener { private: kvsview::Histogram::Parameters* m_parameters; public: PaintEvent( kvsview::Histogram::Parameters* parameters ): m_parameters( parameters ) {} void update() { kvs::Screen* s = static_cast( screen() ); s->scene()->background()->setColor( ::DefaultBackgroundColor ); GLint vp[4]; glGetIntegerv( GL_VIEWPORT, vp ); const GLint left = vp[0]; const GLint bottom = vp[1]; const GLint right = vp[2]; const GLint top = vp[3]; const float front = 0.0f; const float back = 2000.0f; glPushAttrib( GL_CURRENT_BIT | GL_ENABLE_BIT ); { glDisable( GL_LIGHTING ); glDisable( GL_DEPTH_TEST ); glEnable( GL_BLEND ); glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ); // Set 2D view. glMatrixMode( GL_MODELVIEW ); glPushMatrix(); glLoadIdentity(); glMatrixMode( GL_PROJECTION ); glPushMatrix(); glLoadIdentity(); glOrtho( left, right, bottom, top, front, back ); { this->draw_histogram_texture(); } glPopMatrix(); glMatrixMode( GL_MODELVIEW ); glPopMatrix(); } glPopAttrib(); } private: void draw_histogram_texture() { const GLfloat x = 0; const GLfloat y = 0; const GLfloat width = static_cast( screen()->width() ); const GLfloat height = static_cast( screen()->height() ); glEnable( GL_TEXTURE_2D ); m_parameters->histogram_texture.bind(); { glBegin( GL_QUADS ); { glTexCoord2f( 0.0f, 0.0f ); glVertex2f( x, y ); glTexCoord2f( 1.0f, 0.0f ); glVertex2f( x + width, y ); glTexCoord2f( 1.0f, 1.0f ); glVertex2f( x + width, y + height ); glTexCoord2f( 0.0f, 1.0f ); glVertex2f( x, y + height ); } glEnd(); } m_parameters->histogram_texture.unbind(); } }; /*===========================================================================*/ /** * @brief Mouse press event. */ /*===========================================================================*/ class MousePressEvent : public kvs::MousePressEventListener { private: kvsview::Histogram::Parameters* m_parameters; public: MousePressEvent( kvsview::Histogram::Parameters* parameters ): m_parameters( parameters ) {} void update( kvs::MouseEvent* event ) { if ( event->button() == kvs::MouseButton::Left ) { m_parameters->mouse.set( event->x(), event->y() ); } } }; /*===========================================================================*/ /** * @brief Mouse move event. */ /*===========================================================================*/ class MouseMoveEvent : public kvs::MouseMoveEventListener { private: kvsview::Histogram::Parameters* m_parameters; public: MouseMoveEvent( kvsview::Histogram::Parameters* parameters ): m_parameters( parameters ) {} void update( kvs::MouseEvent* event ) { const kvs::Vector2i diff = kvs::Vector2i( event->x(), event->y() ) - m_parameters->mouse; m_parameters->mouse.set( event->x(), event->y() ); m_parameters->bias_parameter -= diff.y() * 0.005f; m_parameters->bias_parameter = kvs::Math::Clamp( m_parameters->bias_parameter, 0.0f, 0.99999f ); m_parameters->updateHistogramTexture(); screen()->redraw(); } }; /*===========================================================================*/ /** * @brief Key press event. */ /*===========================================================================*/ class KeyPressEvent : public kvs::KeyPressEventListener { private: kvsview::Histogram::Parameters* m_parameters; public: KeyPressEvent( kvsview::Histogram::Parameters* parameters ): m_parameters( parameters ) {} void update( kvs::KeyEvent* event ) { if ( event->key() == kvs::Key::Home ) { m_parameters->bias_parameter = 0.5f; m_parameters->updateHistogramTexture(); screen()->redraw(); } } }; /*===========================================================================*/ /** * @brief Constructs a new Argument class for a transfer function renderer. * @param argc [in] argument count * @param argv [in] argument values */ /*===========================================================================*/ Argument::Argument( int argc, char** argv ): kvsview::Argument::Common( argc, argv, kvsview::Histogram::CommandName ) { // Parameters for the transfer function renderer class. addOption( kvsview::Histogram::CommandName, kvsview::Histogram::Description, 0 ); addOption( "b", "Bias parameter in [0,1]. (defalt: 0.5)", 1, false ); } /*===========================================================================*/ /** * @brief Returns the bias parameter. * @return bias parameter */ /*===========================================================================*/ const float Argument::biasParameter( void ) { if ( this->hasOption("b") ) return( kvs::Math::Clamp( this->optionValue("b"), 0.0f, 1.0f ) ); else return( ::DefaultBiasParameter ); } /*===========================================================================*/ /** * @brief Executes main process. */ /*===========================================================================*/ int Main::exec() { // Setup viewer application. kvs::Application app( m_argc, m_argv ); // Commandline arguments. kvsview::Histogram::Argument arg( m_argc, m_argv ); if ( !arg.parse() ) exit( EXIT_FAILURE ); m_input_name = arg.value(); // Parameters. kvsview::Histogram::Parameters params( arg ); if ( !params.createFrequencyTable( m_input_name ) ) exit( EXIT_FAILURE ); // Verbose information. if ( arg.verboseMode() ) { std::cout << std::endl; std::cout << "HISTOGRAM INFORMATION" << std::endl; std::cout << " min range: " << params.frequency_table.minRange() << std::endl; std::cout << " max range: " << params.frequency_table.maxRange() << std::endl; std::cout << " number of bins: " << params.frequency_table.numberOfBins() << std::endl; std::cout << " max count: " << params.frequency_table.maxCount() << std::endl; } // Viewer events. kvsview::Histogram::InitializeEvent initialize_event( ¶ms ); kvsview::Histogram::PaintEvent paint_event( ¶ms ); kvsview::Histogram::MousePressEvent mouse_press_event( ¶ms ); kvsview::Histogram::MouseMoveEvent mouse_move_event( ¶ms ); kvsview::Histogram::KeyPressEvent key_press_event( ¶ms ); // Rendering screen. kvs::Screen screen( &app ); screen.addEvent( &initialize_event ); screen.addEvent( &paint_event ); screen.setEvent( &mouse_press_event ); screen.setEvent( &mouse_move_event ); screen.addEvent( &key_press_event ); screen.setGeometry( 0, 0, ::DefaultScreenWidth, ::DefaultScreenHeight ); screen.setTitle( kvsview::CommandName + " - " + kvsview::Histogram::CommandName ); screen.show(); return ( arg.clear(), app.run() ); } } // end of namespace Histogram } // end of namespace kvsview 10-100 /* Copyright (c) 2020, tevador <> 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 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 "utility.h" #include "service.h" void printUsage(const char* exe) { std::cout << "RandomX Service v" RANDOMX_SERVICE_VERSION << std::endl; std::cout << "Usage: " << exe << " [OPTIONS]" << std::endl; std::cout << "Supported options:" << std::endl; std::cout << " -host Bind to a specific address (default: localhost)" << std::endl << " -port Bind to a specific port (default: 39093)" << std::endl << " -threads Use a specific number of threads (default: all CPU threads)" << std::endl << " -flags Use specific RandomX flags (default: auto)" << std::endl << " -origin Allow cross-origin requests from a specific web page" << std::endl << " -log Log all HTTP requests to stdout" << std::endl << " -help Display this message" << std::endl; } int main(int argc, char** argv) { std::string host, origin; int port, threads, flags; bool help, log; readStringOption("-host", argc, argv, host, "localhost"); readIntOption("-port", argc, argv, port, 39093); readIntOption("-threads", argc, argv, threads, randomx::Service::getMachineThreads()); readIntOption("-flags", argc, argv, flags, randomx::Service::getAutoFlags()); readStringOption("-origin", argc, argv, origin, ""); readOption("-log", argc, argv, log); readOption("-help", argc, argv, help); if (help) { printUsage(argv[0]); return 0; } try { std::cout << "Initializing service..." << std::endl; randomx::Service svc(threads, flags); std::cout << "Threads: " << threads << ", Flags: " << svc.getFlags() << std::endl; if (!origin.empty()) { std::cout << "Setting origin to " << origin << std::endl; svc.setOrigin(origin); } if (log) { std::cout << "Logging is enabled" << std::endl; svc.enableLog(); } std::cout << "Binding to " << host << ":" << port << "..." << std::endl; if (!svc.run(host.data(), port)) { throw std::runtime_error("Failed to bind"); } } catch (const std::exception & e) { std::cout << "ERROR: " << e.what() << std::endl; return 1; } return 0; }vjeranc/ifcplusplusIfcPlusPlus/src/ifcpp/IFC4/lib/IfcConstructionEquipmentResourceTypeEnum.cpp /* Code generated by IfcQuery EXPRESS generator, www.ifcquery.com */ #include #include #include #include "ifcpp/reader/ReaderUtil.h" #include "ifcpp/writer/WriterUtil.h" #include "ifcpp/model/BasicTypes.h" #include "ifcpp/model/BuildingException.h" #include "ifcpp/IFC4/include/IfcConstructionEquipmentResourceTypeEnum.h" // TYPE IfcConstructionEquipmentResourceTypeEnum = ENUMERATION OF (DEMOLISHING ,EARTHMOVING ,ERECTING ,HEATING ,LIGHTING ,PAVING ,PUMPING ,TRANSPORTING ,USERDEFINED ,NOTDEFINED); shared_ptr IfcConstructionEquipmentResourceTypeEnum::getDeepCopy( BuildingCopyOptions& options ) { shared_ptr copy_self( new IfcConstructionEquipmentResourceTypeEnum() ); copy_self->m_enum = m_enum; return copy_self; } void IfcConstructionEquipmentResourceTypeEnum::getStepParameter( std::stringstream& stream, bool is_select_type ) const { if( is_select_type ) { stream << "IFCCONSTRUCTIONEQUIPMENTRESOURCETYPEENUM("; } switch( m_enum ) { case ENUM_DEMOLISHING: stream << ".DEMOLISHING."; break; case ENUM_EARTHMOVING: stream << ".EARTHMOVING."; break; case ENUM_ERECTING: stream << ".ERECTING."; break; case ENUM_HEATING: stream << ".HEATING."; break; case ENUM_LIGHTING: stream << ".LIGHTING."; break; case ENUM_PAVING: stream << ".PAVING."; break; case ENUM_PUMPING: stream << ".PUMPING."; break; case ENUM_TRANSPORTING: stream << ".TRANSPORTING."; break; case ENUM_USERDEFINED: stream << ".USERDEFINED."; break; case ENUM_NOTDEFINED: stream << ".NOTDEFINED."; break; } if( is_select_type ) { stream << ")"; } } const std::wstring IfcConstructionEquipmentResourceTypeEnum::toString() const { switch( m_enum ) { case ENUM_DEMOLISHING: return L"DEMOLISHING"; case ENUM_EARTHMOVING: return L"EARTHMOVING"; case ENUM_ERECTING: return L"ERECTING"; case ENUM_HEATING: return L"HEATING"; case ENUM_LIGHTING: return L"LIGHTING"; case ENUM_PAVING: return L"PAVING"; case ENUM_PUMPING: return L"PUMPING"; case ENUM_TRANSPORTING: return L"TRANSPORTING"; case ENUM_USERDEFINED: return L"USERDEFINED"; case ENUM_NOTDEFINED: return L"NOTDEFINED"; } return L""; } shared_ptr IfcConstructionEquipmentResourceTypeEnum::createObjectFromSTEP( const std::wstring& arg, const std::map >& map ) { if( arg.compare( L"$" ) == 0 ) { return shared_ptr(); } if( arg.compare( L"*" ) == 0 ) { return shared_ptr(); } shared_ptr type_object( new IfcConstructionEquipmentResourceTypeEnum() ); if( boost::iequals( arg, L".DEMOLISHING." ) ) { type_object->m_enum = IfcConstructionEquipmentResourceTypeEnum::ENUM_DEMOLISHING; } else if( boost::iequals( arg, L".EARTHMOVING." ) ) { type_object->m_enum = IfcConstructionEquipmentResourceTypeEnum::ENUM_EARTHMOVING; } else if( boost::iequals( arg, L".ERECTING." ) ) { type_object->m_enum = IfcConstructionEquipmentResourceTypeEnum::ENUM_ERECTING; } else if( boost::iequals( arg, L".HEATING." ) ) { type_object->m_enum = IfcConstructionEquipmentResourceTypeEnum::ENUM_HEATING; } else if( boost::iequals( arg, L".LIGHTING." ) ) { type_object->m_enum = IfcConstructionEquipmentResourceTypeEnum::ENUM_LIGHTING; } else if( boost::iequals( arg, L".PAVING." ) ) { type_object->m_enum = IfcConstructionEquipmentResourceTypeEnum::ENUM_PAVING; } else if( boost::iequals( arg, L".PUMPING." ) ) { type_object->m_enum = IfcConstructionEquipmentResourceTypeEnum::ENUM_PUMPING; } else if( boost::iequals( arg, L".TRANSPORTING." ) ) { type_object->m_enum = IfcConstructionEquipmentResourceTypeEnum::ENUM_TRANSPORTING; } else if( boost::iequals( arg, L".USERDEFINED." ) ) { type_object->m_enum = IfcConstructionEquipmentResourceTypeEnum::ENUM_USERDEFINED; } else if( boost::iequals( arg, L".NOTDEFINED." ) ) { type_object->m_enum = IfcConstructionEquipmentResourceTypeEnum::ENUM_NOTDEFINED; } return type_object; } galilov/youtube-microcontrollers // // Created by on 12.04.2020. // E-Mail: #include "main.h" #include "TOTPSelector.h" #include "Hardware.h" #include "TOTP.h" #include "KeyConfigurator.h" #include TOTPSelectorClass::TOTPSelectorClass() : _state(INITIAL), _keyCount(0), _prevKeyIndex(-1) { } void TOTPSelectorClass::reset() { int8_t j = 0; for (int8_t i = 0; i < MAX_TOTP_KEY_COUNT; i++) { if (Storage::hasKeyAtIndex(i)) { _keyIndexes[j++] = i; } } _keyCount = j; _prevKeyIndex = -1; _currentTotpCode = nullptr; _state = INITIAL; } bool TOTPSelectorClass::tick() { switch (_state) { case INITIAL: if (_keyCount == 0) { KeyConfigurator.reset(); _state = RECEIVE_CONFIG; return false; } uint8_t keyIndex; if (_keyCount > 1) { keyIndex = _keyIndexes[Hardware.getEncoderPosition(0, _keyCount - 1)]; } else { keyIndex = _keyIndexes[0]; } //Serial.println(Hardware.getEncoderPosition(0, _keyCount - 1)); if (_prevKeyIndex != keyIndex) { _prevKeyIndex = keyIndex; Storage::getKey(_key, keyIndex); TOTP.setup(_key.key, _key.keyLength, _key.step); _currentTotpCode = TOTP.getCode(Hardware.getRtc().now().unixtime(), _key.totpLength); sprintf(_buf, "%u.%s", keyIndex, _currentTotpCode); Hardware.getLed().print(_buf); } if (Hardware.getButton().isHolded()) { Hardware.getButton().resetStates(); KeyConfigurator.reset(); _state = RECEIVE_CONFIG; } else if (Hardware.getButton().isClick()) { Hardware.getButton().resetStates(); _state = SEND_TOTP_TO_HOST; } break; case SEND_TOTP_TO_HOST: Keyboard.println(_currentTotpCode); return true; case RECEIVE_CONFIG: if (KeyConfigurator.tick()) { _state = INITIAL; reset(); } break; } return false; } TOTPSelectorClass TOTPSelector; src/WEDCore/WED_Sign_Parser.cpp0 #include "WED_Sign_Parser.h" #include struct glyph_info_t { parser_glyph_t glyph; const char * inside_name; const char * outside_name; // NULL if not legal outside {} int yellow_ok; int red_ok; int location_ok; int black_ok; int independent_ok; }; static const glyph_info_t k_glyph_metadata[] = { /* glyph inside name outside name Y R L B I */ glyph_A, "A", "A", 1, 1, 1, 0, 0, glyph_B, "B", "B", 1, 1, 1, 0, 0, glyph_C, "C", "C", 1, 1, 1, 0, 0, glyph_D, "D", "D", 1, 1, 1, 0, 0, glyph_E, "E", "E", 1, 1, 1, 0, 0, glyph_F, "F", "F", 1, 1, 1, 0, 0, glyph_G, "G", "G", 1, 1, 1, 0, 0, glyph_H, "H", "H", 1, 1, 1, 0, 0, glyph_I, "I", "I", 1, 1, 1, 0, 0, glyph_J, "J", "J", 1, 1, 1, 0, 0, glyph_K, "K", "K", 1, 1, 1, 0, 0, glyph_L, "L", "L", 1, 1, 1, 0, 0, glyph_M, "M", "M", 1, 1, 1, 0, 0, glyph_N, "N", "N", 1, 1, 1, 0, 0, glyph_O, "O", "O", 1, 1, 1, 0, 0, glyph_P, "P", "P", 1, 1, 1, 0, 0, glyph_Q, "Q", "Q", 1, 1, 1, 0, 0, glyph_R, "R", "R", 1, 1, 1, 0, 0, glyph_S, "S", "S", 1, 1, 1, 0, 0, glyph_T, "T", "T", 1, 1, 1, 0, 0, glyph_U, "U", "U", 1, 1, 1, 0, 0, glyph_V, "V", "V", 1, 1, 1, 0, 0, glyph_W, "W", "W", 1, 1, 1, 0, 0, glyph_X, "X", "X", 1, 1, 1, 0, 0, glyph_Y, "Y", "Y", 1, 1, 1, 0, 0, glyph_Z, "Z", "Z", 1, 1, 1, 0, 0, glyph_0, "0", "0", 1, 1, 1, 1, 0, glyph_1, "1", "1", 1, 1, 1, 1, 0, glyph_2, "2", "2", 1, 1, 1, 1, 0, glyph_3, "3", "3", 1, 1, 1, 1, 0, glyph_4, "4", "4", 1, 1, 1, 1, 0, glyph_5, "5", "5", 1, 1, 1, 1, 0, glyph_6, "6", "6", 1, 1, 1, 1, 0, glyph_7, "7", "7", 1, 1, 1, 1, 0, glyph_8, "8", "8", 1, 1, 1, 1, 0, glyph_9, "9", "9", 1, 1, 1, 1, 0, glyph_dash, "-", "-", 1, 1, 0, 0, 0, glyph_dot, "*", "*", 1, 1, 0, 0, 0, glyph_period, ".", ".", 1, 1, 0, 0, 0, glyph_slash, "/", "/", 1, 1, 0, 0, 0, glyph_space, "_", "_", 1, 1, 0, 0, 0, glyph_separator,"|", "|", 1, 1, 1, 0, 0, glyph_comma, "comma", ",", 1, 1, 0, 0, 0, glyph_up, "^u", NULL, 1, 1, 0, 0, 0, glyph_down, "^d", NULL, 1, 1, 0, 0, 0, glyph_left, "^l", NULL, 1, 1, 0, 0, 0, glyph_right, "^r", NULL, 1, 1, 0, 0, 0, glyph_leftup, "^lu", NULL, 1, 1, 0, 0, 0, glyph_rightup, "^ru", NULL, 1, 1, 0, 0, 0, glyph_leftdown, "^ld", NULL, 1, 1, 0, 0, 0, glyph_rightdown,"^rd", NULL, 1, 1, 0, 0, 0, glyph_critical, "critical", NULL, 0, 0, 0, 0, 1, glyph_hazard, "hazard", NULL, 0, 0, 0, 0, 1, glyph_no_entry, "no-entry", NULL, 0, 0, 0, 0, 1, glyph_safety, "safety", NULL, 0, 0, 0, 0, 1, glyph_r1, "r1", NULL, 1, 1, 0, 0, 0, glyph_r2, "r2", NULL, 1, 1, 0, 0, 0, glyph_r3, "r3", NULL, 1, 1, 0, 0, 0 }; static const char * k_err_msgs[parser_error_count] = { "Invalid @ instruction", "Not a real glyph", "Not a single-character real glyph", "@ outside of {}", "Expected } or ,", "Empty glyph", "Missing { at end of sign", "Nested {", "} is not after }", "Sign side begins with a separator", "Color mismatch around separator", "Double separator", "Sign ends with separator", "Illegal color for glyph", "Too many side switches" }; static const int k_glyph_info_count = sizeof(k_glyph_metadata) / sizeof(k_glyph_metadata[0]); static const glyph_info_t * get_glyph_info(parser_glyph_t glyph) { for(int i = 0; i < k_glyph_info_count; ++i) if(k_glyph_metadata[i].glyph == glyph) return k_glyph_metadata+i; return NULL; } string parser_name_for_glyph(parser_glyph_t glyph) { const glyph_info_t * i = get_glyph_info(glyph); return i ? i->inside_name : ""; } string short_name_for_glyph(parser_glyph_t glyph) { const glyph_info_t * i = get_glyph_info(glyph); if(!i) return string(); if(i->outside_name == NULL) return string(); return i->outside_name; } bool parser_is_color_legal(parser_glyph_t glyph, parser_color_t c) { const glyph_info_t * i = get_glyph_info(glyph); if(!i) return false; switch(c) { case sign_color_yellow: return i->yellow_ok; case sign_color_red: return i->red_ok; case sign_color_location: return i->location_ok; case sign_color_black: return i->black_ok; case sign_color_independent: return i->independent_ok; default: return false; } } parser_glyph_t glyph_for_short_name(const string& s) { for(int i = 0; i < k_glyph_info_count; ++i) if(k_glyph_metadata[i].inside_name && s == k_glyph_metadata[i].inside_name) return k_glyph_metadata[i].glyph; return glyph_Invalid; } //--WED_Sign_Parser class decleration-------------------------- class WED_Sign_Parser { public: WED_Sign_Parser(const parser_in_info & input, parser_out_info & output); ~WED_Sign_Parser(void); void MainLoop(); private: // An important note on glyph buffer handling: // If the parser is in state I_ACCUM_GLYPHS, all output is dumped into the glyph buffer until we're ready to flush it. // In all other states, the glyph buffer is empty. // Therefore at any given time when we need to accumulate an error, either: // // (a) we are working on the glyph buffer, which is non-emtpy, and the current position is at the NEXT character after the glyph // buf's characters. We thus know where in the source string the glyph buffer came from and we can attribute the error to the // glyph buffer or // // (b) we are parsing a single character at mPosition. // // Code that does both (e.g. if we hit a { inside a {} expression with the glyph buf non-emtpy in I_ACCUM_GLYPHS) makes sure to // (1) first flush the glyph buf, attributing any errors to that buffer, e.g. if the glyph name is silly or the color is wrong // and (2) then clears the glyph buf and copes with additional errors (e.g. nested braces), attributing that to the separatolr. enum FSM { //The inside curly braces portion, starts with I_ I_COMMA, // We just hit a comma inside braces and are now expecting some kind of multi-glyph or command token I_INCUR, // We are inside curly braces - we can accept a } or a token I_ACCUM_GLYPHS, // We have at least one char and are possibly collecting more for multi-char glyphs in {} I_ANY_CONTROL, // We parsed @ and are waiting for the control letter I_WAITING_SEPERATOR,//For when it is waiting for a , or } after finishing a known control, e.g. @@ //The outside curly braces portion, starts with O_ O_ACCUM_GLYPHS, // We are consuming single-char glyphs - we don't have any yet. // (Since they are single char, each scanned char is immediately turned into a glyph and we // fall back into this state. This is different from inside {} where I_ACCUM_GLYPHS is only // when we are mid-glyph) }; // Appends an error code for the current parse. If the glyph buf is not empty, we attribute the buf to // the error; otherwise we attribute the single char at the current position. void append_error(parser_error_t code); // These check a glyph, and either accumulate errors _or_ return the valid glyph. parser_glyph_t check_multi_glyph(const string & inGlyph); parser_glyph_t check_single_glyph(char inGlyph); // Given a valid glyph in the current glyph buf _or_ position (if glyph buf empty), // accumulate it, and add any semantic errors that we hit along the way void append_parser_out_info(parser_glyph_t glyph); // Given the current state, consume the current character and return the new state, taking all actions needed. FSM LookUpTable(FSM curState); //--------------------------------------------------------- //--FSM data members--------------------------------------- parser_color_t mCurColor; // Current color as we parse bool mOnFront; // True if in sign front, false if in sign back string mGlyphBuf; // Accumulated chars for multi-char glyph int mPosition; // Index into input string const parser_in_info& mInput; parser_out_info& mOutput; }; //------------------------------------------------------------------------ WED_Sign_Parser::WED_Sign_Parser(const parser_in_info & input, parser_out_info & output) : mCurColor(sign_color_invalid), mOnFront(true), mPosition(0), mInput(input), mOutput(output) { } WED_Sign_Parser::~WED_Sign_Parser() { } void WED_Sign_Parser::append_error(parser_error_t code) { parser_error_info e; e.err_code = code; if(mGlyphBuf.empty()) { e.position = mPosition; e.length = 1; } else { // When the glyph buf is in-tact, it's the post-glyph-buf terminating character that provkes us. // so if we have: // 01234567 // {@Y,FOO, // position is 7, the cur char is , and we get called with FOO in our buffer and detemrine that 4-7 // is the bad glyph. // If the code wants us to push an err on 7, it'll clear out the glyph buf first. e.position = mPosition - mGlyphBuf.size(); e.length = mGlyphBuf.size(); } stringstream str; str << "Chars " << e.position << " to " << e.position + e.length - 1 << ": " << k_err_msgs[code] << " " << mInput.input.substr(e.position,e.length); e.msg = str.str(); mOutput.errors.push_back(e); } //Check a multi glyph //Returns true if there was an error parser_glyph_t WED_Sign_Parser::check_multi_glyph(const string & inGlyph) { for(int i = 0; i < k_glyph_info_count; ++i) if(k_glyph_metadata[i].inside_name) if(inGlyph == k_glyph_metadata[i].inside_name) { return k_glyph_metadata[i].glyph; } append_error(syn_not_real_multiglyph); return glyph_Invalid; } parser_glyph_t WED_Sign_Parser::check_single_glyph(const char inGlyph) { for(int i = 0; i < k_glyph_info_count; ++i) if(k_glyph_metadata[i].outside_name) if(k_glyph_metadata[i].outside_name[0] == inGlyph) { return k_glyph_metadata[i].glyph; } append_error(syn_not_real_singleglyph); return glyph_Invalid; } //Attempts to add a collection of letters void WED_Sign_Parser::append_parser_out_info(parser_glyph_t glyph) { //Before actually appending them see if they're parser_color_t glyphColor = mCurColor; if(parser_is_color_legal(glyph, sign_color_independent)) glyphColor = sign_color_independent; if(!parser_is_color_legal(glyph, glyphColor)) { append_error(sem_glyph_color_mismatch); glyphColor = sign_color_invalid; } vector& side(mOnFront ? mOutput.out_sign.front : mOutput.out_sign.back); if(side.empty()) { // For the first char in a side, do the start-with-pipe check. if(glyph == glyph_separator) { return; // silently drop unwanted separator at very front of sign // append_error(sem_pipe_begins_sign); } } else { // For all others do adjaceny checks. if(side.back().glyph_name == glyph_separator && glyph == glyph_separator) { return; // silently drop unwanted separator next to existing separator // append_error(sem_pipe_double_juxed); } if(side.back().glyph_name == glyph_separator || glyph == glyph_separator) if(side.back().glyph_color != glyphColor) { return; // silently drop unwanted separator next to a color change in the sign // append_error(sem_pipe_color_mismatch); } } side.push_back(parser_glyph_info(glyphColor, glyph)); } //Take in the current (and soon to be past) state and the current letter being processed //The heart of all this //Takes in the current state of the FSM, the current character being processes //The position, Outstr, and msgBuf are all part of reporting errors and are not integral to the FSM WED_Sign_Parser::FSM WED_Sign_Parser::LookUpTable(FSM curState) { char curChar = mInput.input[mPosition]; parser_glyph_t glyph; // Important: we should not have gotten out of I_ACCUM_GLYPHS without flushing the glyph buf, // and we should not have added to the glyph buf without going into I_ACCUM_GLYPHS. assert(mGlyphBuf.empty() || curState == I_ACCUM_GLYPHS); switch(curState) { case I_COMMA: switch(curChar) { case '{': append_error(syn_curly_pair_nested); return I_COMMA; case '}': append_error(syn_empty_multiglyph); return O_ACCUM_GLYPHS; case ',': append_error(syn_empty_multiglyph); return I_COMMA; case '@': return I_ANY_CONTROL; default: //if it was able to accumulate the the glyph mGlyphBuf += curChar; return I_ACCUM_GLYPHS; } break; case I_INCUR: switch(curChar) { case '{': append_error(syn_curly_pair_nested); return I_INCUR; case '}': return O_ACCUM_GLYPHS; case ',': append_error(syn_empty_multiglyph); return I_COMMA; case '@': return I_ANY_CONTROL; default: mGlyphBuf += curChar; return I_ACCUM_GLYPHS; } break; case I_ACCUM_GLYPHS: switch(curChar) { case '{': glyph = check_multi_glyph(mGlyphBuf); if(glyph != glyph_Invalid) append_parser_out_info(glyph); mGlyphBuf.clear(); append_error(syn_curly_pair_nested); return I_ACCUM_GLYPHS; case '}': glyph = check_multi_glyph(mGlyphBuf); if(glyph != glyph_Invalid) append_parser_out_info(glyph); mGlyphBuf.clear(); return O_ACCUM_GLYPHS; case ',': glyph = check_multi_glyph(mGlyphBuf); if(glyph != glyph_Invalid) append_parser_out_info(glyph); mGlyphBuf.clear(); return I_COMMA; case '@': default: mGlyphBuf += curChar; return I_ACCUM_GLYPHS; } break; case I_ANY_CONTROL: switch(curChar) { case '{': append_error(syn_curly_pair_nested); return I_ANY_CONTROL; case '}': append_error(syn_not_real_instruction); return O_ACCUM_GLYPHS; case ',': append_error(syn_not_real_instruction); return I_COMMA; case '@': if(mOnFront == true) { if(!mOutput.out_sign.front.empty()) if(mOutput.out_sign.front.back().glyph_name == glyph_separator) append_error(sem_pipe_ends_sign); mOnFront = false; } else append_error(sem_mutiple_side_switches); return I_WAITING_SEPERATOR; case 'Y': mCurColor = sign_color_yellow; return I_WAITING_SEPERATOR; case 'L': mCurColor = sign_color_location; return I_WAITING_SEPERATOR; case 'R': mCurColor = sign_color_red; return I_WAITING_SEPERATOR; case 'B': mCurColor = sign_color_black; return I_WAITING_SEPERATOR; default: append_error(syn_not_real_instruction); return I_WAITING_SEPERATOR; } break; case I_WAITING_SEPERATOR: switch(curChar) { case '{': append_error(syn_curly_pair_nested); return I_INCUR; case '}': return O_ACCUM_GLYPHS; case ',': return I_COMMA; case '@': append_error(syn_expected_seperator); return I_WAITING_SEPERATOR; default: append_error(syn_expected_seperator); return I_WAITING_SEPERATOR; } break; case O_ACCUM_GLYPHS: switch(curChar) { case '{': return I_INCUR; case '}': append_error(syn_curly_unbalanced); return O_ACCUM_GLYPHS; case '@': append_error(syn_found_at_symbol_outside_curly); return O_ACCUM_GLYPHS; case ',': default: glyph = check_single_glyph(curChar); if(glyph != glyph_Invalid) { append_parser_out_info(glyph); } return O_ACCUM_GLYPHS; } break; } } //--------------------------------------------------------- void WED_Sign_Parser::MainLoop() { // //Validate if there is any whitesapce or non printable ASCII characters (33-126) // if(WED_Sign_Parser::ValidateBasics(input,output) == true) // { // return; // } FSM FSM_MODE = O_ACCUM_GLYPHS; mPosition = 0; while(mPosition < mInput.input.size()) { //Look up the transition FSM transition = WED_Sign_Parser::LookUpTable(FSM_MODE); FSM_MODE = transition; ++mPosition; } // When we hit end of text, if we are accumulating glyphs, // use the EOF as a hint to flush the glyph buffer if needed. // That way if the user writes {hazard // we flush hazard as a valid sign, and clear the glyph buf. if(FSM_MODE == I_ACCUM_GLYPHS) { assert(!mGlyphBuf.empty()); parser_glyph_t glyph = check_multi_glyph(mGlyphBuf); if(glyph != glyph_Invalid) append_parser_out_info(glyph); mGlyphBuf.clear(); } // Now with the glyph buf if we haven't sealed off a { sequence, // the glyph buf is empty and we can squawk that our end position is fubar. if(FSM_MODE != O_ACCUM_GLYPHS) { append_error(syn_curly_pair_missing); } if(mOnFront) { if( !mOutput.out_sign.front.empty() && mOutput.out_sign.front.back().glyph_name == glyph_separator ) { mOutput.out_sign.front.pop_back(); // silently delete undesired separator // append_error(sem_pipe_ends_sign); } } else { if( !mOutput.out_sign.back.empty() && mOutput.out_sign.back.back().glyph_name == glyph_separator ) { mOutput.out_sign.back.pop_back(); // silently delete undesired separator // append_error(sem_pipe_ends_sign); } } // bool foundError = preform_final_semantic_checks(); } //--------------------------------------------------------- void ParserTaxiSign(const parser_in_info & input, parser_out_info & output) { WED_Sign_Parser parser(input,output); parser.MainLoop(); } // license:GPL-2.0+ // copyright-holders: /*************************************************************************** Lazer Command memory map (preliminary) driver by 0000-0bff ROM 1c00-1c1f RAM CPU scratch pad is first 32 bytes of video RAM(not displayed) 1c20-1eff RAM video buffer xxxx D0 - D5 character select D6 horz line below character (row #9) D7 vert line right of character (bit #0) 1f00-1f03 R/W hardware 1f00 W audio channels D4 gun fire D5 explosion D6 tank engine D7 running man 1f00 R player 1 joystick D0 up D1 down D2 right D3 left 1f01 W D0 - D7 marker y position 1f01 R player 2 joystick D0 up D1 down D2 right D3 left 1f02 W D0 - D7 marker x position 1f02 R player 1 + 2 buttons D0 button 1 player 2 D1 button 1 player 1 D2 button 2 player 2 D3 button 2 player 1 1f03 W attract mode D0 toggle on attract mode (attract mode switched off by coin detected) D4 clear coin detected toggle 1f03 R coinage, coin detected and start buttons D0 coin 1/2 (DIP switch 4) D1 start 'expert' D2 start 'novice' D3 coin detected 1f04-1f07 Read only hardware 1f04 R vertical scan counter D0 60 Hz D1 120 Hz D2 240 Hz D3 480 Hz 1f05 R vertical scan counter D0 7.860 KHz D1 3.960 KHz D2 1.980 KHz D3 960 Hz 1f06 R D0 - D7 readback of marker x position 1f07 R D0 - D7 readback of marker y position I/O ports: 'data' R game time D0 - D1 60,90,120,180 seconds (DIP switch 1 - 2) ***************************************************************************/ /*************************************************************************** Meadows Lanes memory map (preliminary) 0000-0bff ROM 0c00-0c1f RAM CPU scratch pad is first 32 bytes of video RAM(not displayed) 0c20-0eff RAM video buffer xxxx D0 - D5 character select D6 horz line below character (row #9) D7 vert line right of character (bit #0) 1000-17ff ROM 1f00-1f03 R/W hardware 1f00 W audio control bits D0 - D3 not used D4 bowl and hit D5 hit D6 - D7 not used 1f00 R bowl ball D0 fast D1 slow joystick D2 right D3 left 1f01 W D0 - D7 marker y position 1f01 R hook control D0 left D1 right D2 - D3 not used 1f02 W D0 - D7 marker x position 1f02 R D0 - D3 not used 1f03 W attract mode D0 toggle on attract mode (attract mode switched off by coin detected) D4 clear coin detected toggle D5 can be jumpered to control inverse video D6 - D7 not used 1f03 R coinage, coin detected and start buttons D0 coin 1/2 (DIP switch 4) D1 start D2 not used D3 coin detected 1f04-1f07 Read only hardware 1f04 R vertical scan counter D0 60 Hz D1 120 Hz D2 240 Hz D3 480 Hz 1f05 R vertical scan counter D0 7.860 KHz D1 3.960 KHz D2 1.980 KHz D3 960 Hz 1f06 R D0 - D7 readback of marker x position 1f07 R D0 - D7 readback of marker y position I/O ports: 'data' R game time D0 time on (DIP switch 1) D1 3,5 seconds (DIP switch 2) ***************************************************************************/ /*************************************************************************** Bigfoot Bonkers memory map (preliminary) driver by 0000-07ff ROM 1c00-1c1f RAM CPU scratch pad is first 32 bytes of video RAM(not displayed) 1c20-1eff RAM video buffer xxxx D0 - D5 character select D6 horz line below character (row #9) D7 vert line right of character (bit #0) 1f00-1f03 R/W hardware 1f00 W audio channels D4 unused D5 tone 1 D6 tone 2 D7 unused 1f00 R player 1 joystick D0 up D1 down D2 right D3 left 1f01 W D0 - D7 unused 1f01 R player 2 joystick D0 up D1 down D2 right D3 left 1f02 W D0 - D7 unused 1f02 R player 1 + 2 buttons D0 unused D1 unused D2 unused D3 unused 1f03 W attract mode D0 toggle on attract mode (attract mode switched off by coin detected) D4 clear coin detected toggle 1f03 R coinage, coin detected and start buttons D0 coin 1/2 (DIP switch 4) D1 start D2 start D3 coin detected 1f04-1f07 Read only hardware 1f04 R vertical scan counter D0 60 Hz D1 120 Hz D2 240 Hz D3 480 Hz 1f05 R vertical scan counter D0 7.860 KHz D1 3.960 KHz D2 1.980 KHz D3 960 Hz 1f06 R D0 - D7 unused 1f07 R D0 - D7 unused ***************************************************************************/ /*************************************************************************** TODO - how does video invert exactly work? the hardware can control it, for example in bbonk death sequence - bbonk video on youtube shows a 1-pixel gap horizontally between tiles, maybe the characters are 9*10 or it differs per game - improve sound emulation ***************************************************************************/ #include "emu.h" #include "includes/lazercmd.h" #include "sound/volt_reg.h" #include "screen.h" #include "speaker.h" // color overlays, bbonk does not have an overlay #include "lazercmd.lh" #include "medlanes.lh" #define MASTER_CLOCK XTAL(8'000'000) /************************************************************* * Interrupt for the cpu * Fake something toggling the sense input line of the S2650 * The rate should be at about 1 Hz *************************************************************/ TIMER_DEVICE_CALLBACK_MEMBER(lazercmd_state::lazercmd_timer) { int scanline = param; if((scanline % 2) == 1) return; if (++m_timer_count >= 64 * 128) { m_timer_count = 0; m_sense_state ^= 1; m_maincpu->set_input_line(S2650_SENSE_LINE, m_sense_state ? ASSERT_LINE : CLEAR_LINE); } } TIMER_DEVICE_CALLBACK_MEMBER(lazercmd_state::bbonk_timer) { int scanline = param; if((scanline % 2) == 1) return; if (++m_timer_count >= 64 * 128) m_timer_count = 0; } /************************************************************* * * IO port read/write * *************************************************************/ /* triggered by WRTC,r opcode */ WRITE8_MEMBER(lazercmd_state::lazercmd_ctrl_port_w) { } /* triggered by REDC,r opcode */ READ8_MEMBER(lazercmd_state::lazercmd_ctrl_port_r) { uint8_t data = 0; return data; } /* triggered by WRTD,r opcode */ WRITE8_MEMBER(lazercmd_state::lazercmd_data_port_w) { } /* triggered by REDD,r opcode */ READ8_MEMBER(lazercmd_state::lazercmd_data_port_r) { uint8_t data = ioport("DSW")->read() & 0x0f; return data; } WRITE8_MEMBER(lazercmd_state::lazercmd_hardware_w) { switch (offset) { case 0: /* audio channels */ m_dac0->write(BIT(data, 7)); m_dac1->write(BIT(data, 6)); m_dac2->write(BIT(data, 5)); m_dac3->write(BIT(data, 4)); break; case 1: /* marker Y position */ m_marker_y = data; break; case 2: /* marker X position */ m_marker_x = data; break; case 3: /* D4 clears coin detected and D0 toggles on attract mode */ m_attract = data; break; } } WRITE8_MEMBER(lazercmd_state::medlanes_hardware_w) { switch (offset) { case 0: /* audio control */ /* bits 4 and 5 are used to control a sound board */ /* these could be used to control sound samples */ /* at the moment they are routed through the dac */ m_dac2->write(BIT(data, 5)); m_dac3->write(BIT(data, 4)); break; case 1: /* marker Y position */ m_marker_y = data; break; case 2: /* marker X position */ m_marker_x = data; break; case 3: /* D4 clears coin detected and D0 toggles on attract mode */ m_attract = data; break; } } WRITE8_MEMBER(lazercmd_state::bbonk_hardware_w) { switch (offset) { case 0: /* audio control */ /* bits 4 and 5 are used to control a sound board */ /* these could be used to control sound samples */ /* at the moment they are routed through the dac */ m_dac2->write(BIT(data, 5)); m_dac3->write(BIT(data, 4)); break; case 3: /* D5 inverts video?, D4 clears coin detected and D0 toggles on attract mode */ m_attract = data; break; } } READ8_MEMBER(lazercmd_state::lazercmd_hardware_r) { uint8_t data = 0; switch (offset) { case 0: /* player 1 joysticks */ data = ioport("IN0")->read(); break; case 1: /* player 2 joysticks */ data = ioport("IN1")->read(); break; case 2: /* player 1 + 2 buttons */ data = ioport("IN3")->read(); break; case 3: /* coin slot + start buttons */ data = ioport("IN2")->read(); break; case 4: /* vertical scan counter */ data = ((m_timer_count & 0x10) >> 1) | ((m_timer_count & 0x20) >> 3) | ((m_timer_count & 0x40) >> 5) | ((m_timer_count & 0x80) >> 7); break; case 5: /* vertical scan counter */ data = m_timer_count & 0x0f; break; case 6: /* 1f02 readback */ data = m_marker_x; break; case 7: /* 1f01 readback */ data = m_marker_y; break; } return data; } /************************************************************* * * Memory maps * *************************************************************/ void lazercmd_state::lazercmd_map(address_map &map) { map(0x0000, 0x0bff).rom(); map(0x1c00, 0x1c1f).ram(); map(0x1c20, 0x1eff).ram().share("videoram"); map(0x1f00, 0x1f03).w(this, FUNC(lazercmd_state::lazercmd_hardware_w)); map(0x1f00, 0x1f07).r(this, FUNC(lazercmd_state::lazercmd_hardware_r)); } void lazercmd_state::medlanes_map(address_map &map) { map(0x0000, 0x0bff).rom(); map(0x1000, 0x17ff).rom(); map(0x1c00, 0x1c1f).ram(); map(0x1c20, 0x1eff).ram().share("videoram"); map(0x1f00, 0x1f03).w(this, FUNC(lazercmd_state::medlanes_hardware_w)); map(0x1f00, 0x1f07).r(this, FUNC(lazercmd_state::lazercmd_hardware_r)); } void lazercmd_state::bbonk_map(address_map &map) { map(0x0000, 0x0bff).rom(); map(0x1c00, 0x1c1f).ram(); map(0x1c20, 0x1eff).ram().share("videoram"); map(0x1f00, 0x1f03).w(this, FUNC(lazercmd_state::bbonk_hardware_w)); map(0x1f00, 0x1f07).r(this, FUNC(lazercmd_state::lazercmd_hardware_r)); } void lazercmd_state::lazercmd_portmap(address_map &map) { map(S2650_CTRL_PORT, S2650_CTRL_PORT).rw(this, FUNC(lazercmd_state::lazercmd_ctrl_port_r), FUNC(lazercmd_state::lazercmd_ctrl_port_w)); map(S2650_DATA_PORT, S2650_DATA_PORT).rw(this, FUNC(lazercmd_state::lazercmd_data_port_r), FUNC(lazercmd_state::lazercmd_data_port_w)); } static INPUT_PORTS_START( lazercmd ) PORT_START("IN0") PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_JOYSTICK_UP ) PORT_PLAYER(1) PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN ) PORT_PLAYER(1) PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT ) PORT_PLAYER(1) PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT ) PORT_PLAYER(1) PORT_BIT( 0xf0, IP_ACTIVE_LOW, IPT_UNUSED ) PORT_START("IN1") PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_JOYSTICK_UP ) PORT_PLAYER(2) PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN ) PORT_PLAYER(2) PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT ) PORT_PLAYER(2) PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT ) PORT_PLAYER(2) PORT_BIT( 0xf0, IP_ACTIVE_LOW, IPT_UNUSED ) PORT_START("DSW") PORT_DIPNAME( 0x03, 0x03, DEF_STR( Game_Time ) ) PORT_DIPLOCATION("SW1:!1,!2") PORT_DIPSETTING( 0x00, "60 seconds" ) PORT_DIPSETTING( 0x01, "90 seconds" ) PORT_DIPSETTING( 0x02, "120 seconds" ) PORT_DIPSETTING( 0x03, "180 seconds" ) PORT_BIT( 0x98, IP_ACTIVE_LOW, IPT_UNUSED ) PORT_DIPNAME( 0x20, 0x20, "Video Invert" ) PORT_DIPSETTING( 0x00, DEF_STR( Off ) ) PORT_DIPSETTING( 0x20, DEF_STR( On ) ) PORT_DIPNAME( 0x40, 0x40, "Marker Size" ) // jumper PORT_DIPSETTING( 0x00, "Small" ) PORT_DIPSETTING( 0x40, "Large" ) PORT_START("IN2") PORT_DIPNAME( 0x01, 0x01, DEF_STR( Coinage ) ) PORT_DIPLOCATION("SW1:4") PORT_DIPSETTING( 0x00, DEF_STR( 2C_1C ) ) PORT_DIPSETTING( 0x01, DEF_STR( 1C_1C ) ) PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_START2 ) PORT_NAME("Start Expert") PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_START1 ) PORT_NAME("Start Novice") PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_COIN1 ) PORT_BIT( 0xf0, IP_ACTIVE_HIGH, IPT_UNUSED ) PORT_START("IN3") PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_PLAYER(2) PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_PLAYER(1) PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_BUTTON2 ) PORT_PLAYER(2) PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_BUTTON2 ) PORT_PLAYER(1) PORT_BIT( 0xf0, IP_ACTIVE_LOW, IPT_UNUSED ) INPUT_PORTS_END static INPUT_PORTS_START( medlanes ) PORT_START("IN0") // note: real cpanel has 2 buttons for left/right, no joystick. 6 buttons total (excluding start) // layout is: move left, move right - throw fast, throw slow - hook right, hook left PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_NAME("Throw Fast") PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_BUTTON2 ) PORT_NAME("Throw Slow") PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT ) PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT ) PORT_BIT( 0xf0, IP_ACTIVE_LOW, IPT_UNUSED ) PORT_START("IN1") PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_BUTTON4 ) PORT_NAME("Hook Left") PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_BUTTON3 ) PORT_NAME("Hook Right") PORT_BIT( 0xfc, IP_ACTIVE_LOW, IPT_UNUSED ) PORT_START("DSW") PORT_DIPNAME( 0x03, 0x03, "Throw Time" ) PORT_DIPLOCATION("SW1:!1,!2") PORT_DIPSETTING( 0x01, "3 seconds" ) PORT_DIPSETTING( 0x03, "5 seconds" ) PORT_DIPSETTING( 0x00, DEF_STR( Off ) ) // PORT_DIPSETTING( 0x02, DEF_STR( Off ) ) // dupe PORT_BIT( 0x9C, IP_ACTIVE_LOW, IPT_UNUSED ) PORT_DIPNAME( 0x20, 0x00, "Video Invert" ) PORT_DIPSETTING( 0x00, DEF_STR( Off ) ) PORT_DIPSETTING( 0x20, DEF_STR( On ) ) PORT_DIPNAME( 0x40, 0x00, "Marker Size" ) // jumper PORT_DIPSETTING( 0x00, "Small" ) PORT_DIPSETTING( 0x40, "Large" ) PORT_START("IN2") PORT_DIPNAME( 0x01, 0x01, DEF_STR( Coinage ) ) PORT_DIPLOCATION("SW1:4") PORT_DIPSETTING( 0x00, DEF_STR( 2C_1C ) ) PORT_DIPSETTING( 0x01, DEF_STR( 1C_1C ) ) PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_START1 ) PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_COIN1 ) PORT_BIT( 0xf4, IP_ACTIVE_HIGH, IPT_UNUSED ) PORT_START("IN3") PORT_BIT( 0xff, IP_ACTIVE_LOW, IPT_UNUSED ) INPUT_PORTS_END static INPUT_PORTS_START( bbonk ) PORT_START("IN0") PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_JOYSTICK_UP ) PORT_PLAYER(2) PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN ) PORT_PLAYER(2) PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT ) PORT_PLAYER(2) PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT ) PORT_PLAYER(2) PORT_BIT( 0xf0, IP_ACTIVE_LOW, IPT_UNUSED ) PORT_START("IN1") PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_JOYSTICK_UP ) PORT_PLAYER(1) PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN ) PORT_PLAYER(1) PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT ) PORT_PLAYER(1) PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT ) PORT_PLAYER(1) PORT_BIT( 0xf0, IP_ACTIVE_LOW, IPT_UNUSED ) PORT_START("DSW") PORT_DIPNAME( 0x03, 0x03, "Games to win" ) PORT_DIPLOCATION("SW1:!1,!2") PORT_DIPSETTING( 0x02, "2" ) PORT_DIPSETTING( 0x03, "3" ) PORT_DIPSETTING( 0x00, "4" ) PORT_DIPSETTING( 0x01, "5" ) PORT_BIT( 0x9C, IP_ACTIVE_LOW, IPT_UNUSED ) PORT_DIPNAME( 0x20, 0x00, "Video Invert" ) PORT_DIPSETTING( 0x00, DEF_STR( Off ) ) PORT_DIPSETTING( 0x20, DEF_STR( On ) ) PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_UNUSED ) // marker is not used in this game PORT_START("IN2") PORT_DIPNAME( 0x01, 0x01, DEF_STR( Coinage ) ) PORT_DIPLOCATION("SW1:4") PORT_DIPSETTING( 0x00, DEF_STR( 2C_1C ) ) PORT_DIPSETTING( 0x01, DEF_STR( 1C_1C ) ) PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_START1 ) PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_START2 ) PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_COIN1 ) PORT_BIT( 0xf0, IP_ACTIVE_HIGH, IPT_UNUSED ) PORT_START("IN3") PORT_DIPNAME( 0x01, 0x00, DEF_STR( Demo_Sounds ) ) PORT_DIPLOCATION("SW1:3") PORT_DIPSETTING( 0x00, "Partial" ) PORT_DIPSETTING( 0x01, DEF_STR( On ) ) PORT_BIT( 0xfe, IP_ACTIVE_LOW, IPT_UNUSED ) INPUT_PORTS_END static const gfx_layout charlayout = { 8, 10, /* 8*10 characters */ 4*64, /* 4 * 64 characters */ 1, /* 1 bit per pixel */ { 0 }, /* no bitplanes */ { 0, 1, 2, 3, 4, 5, 6, 7 }, { 0*8, 1*8, 2*8, 3*8, 4*8, 5*8, 6*8, 7*8, 8*8, 9*8 }, 10*8 /* every char takes 10 bytes */ }; static GFXDECODE_START( lazercmd ) GFXDECODE_ENTRY( "gfx1", 0, charlayout, 0, 2 ) GFXDECODE_END PALETTE_INIT_MEMBER(lazercmd_state, lazercmd) { palette.set_pen_color(0, rgb_t(0xb0, 0xb0, 0xb0)); /* white */ palette.set_pen_color(1, rgb_t(0x00, 0x00, 0x00)); /* black */ palette.set_pen_color(2, rgb_t(0x00, 0x00, 0x00)); /* black */ palette.set_pen_color(3, rgb_t(0xb0, 0xb0, 0xb0)); /* white */ palette.set_pen_color(4, rgb_t(0xff, 0xff, 0xff)); /* bright white */ } void lazercmd_state::machine_start() { save_item(NAME(m_marker_x)); save_item(NAME(m_marker_y)); save_item(NAME(m_timer_count)); save_item(NAME(m_sense_state)); save_item(NAME(m_attract)); } void lazercmd_state::machine_reset() { m_marker_x = 0; m_marker_y = 0; m_timer_count = 0; m_sense_state = 0; m_attract = 0; } MACHINE_CONFIG_START(lazercmd_state::lazercmd) /* basic machine hardware */ MCFG_CPU_ADD("maincpu", S2650, MASTER_CLOCK/12) /* 666 kHz? */ /* Main Clock is 8MHz divided by 12 but memory and IO access is only possible within the line and frame blanking period thus requiring an extra loading of approx 3-5 */ MCFG_CPU_PROGRAM_MAP(lazercmd_map) MCFG_CPU_DATA_MAP(lazercmd_portmap) MCFG_TIMER_DRIVER_ADD_SCANLINE("scantimer", lazercmd_state, lazercmd_timer, "screen", 0, 1) /* video hardware */ MCFG_SCREEN_ADD("screen", RASTER) MCFG_SCREEN_REFRESH_RATE(60) MCFG_SCREEN_VBLANK_TIME(ATTOSECONDS_IN_USEC(2500) /* not accurate */) MCFG_SCREEN_SIZE(HORZ_RES * HORZ_CHR, VERT_RES * VERT_CHR + 16) MCFG_SCREEN_VISIBLE_AREA(0 * HORZ_CHR, HORZ_RES * HORZ_CHR - 1, 0 * VERT_CHR, (VERT_RES - 1) * VERT_CHR - 1) MCFG_SCREEN_UPDATE_DRIVER(lazercmd_state, screen_update_lazercmd) MCFG_SCREEN_PALETTE("palette") MCFG_GFXDECODE_ADD("gfxdecode", "palette", lazercmd) MCFG_PALETTE_ADD("palette", 5) MCFG_PALETTE_INIT_OWNER(lazercmd_state, lazercmd) /* sound hardware */ MCFG_SPEAKER_STANDARD_MONO("speaker") MCFG_SOUND_ADD("dac0", DAC_1BIT, 0) MCFG_SOUND_ROUTE(ALL_OUTPUTS, "speaker", 0.99) MCFG_SOUND_ADD("dac1", DAC_1BIT, 0) MCFG_SOUND_ROUTE(ALL_OUTPUTS, "speaker", 0.99) MCFG_SOUND_ADD("dac2", DAC_1BIT, 0) MCFG_SOUND_ROUTE(ALL_OUTPUTS, "speaker", 0.99) MCFG_SOUND_ADD("dac3", DAC_1BIT, 0) MCFG_SOUND_ROUTE(ALL_OUTPUTS, "speaker", 0.99) MCFG_DEVICE_ADD("vref", VOLTAGE_REGULATOR, 0) MCFG_VOLTAGE_REGULATOR_OUTPUT(5.0) MCFG_SOUND_ROUTE_EX(0, "dac0", 1.0, DAC_VREF_POS_INPUT) MCFG_SOUND_ROUTE_EX(0, "dac1", 1.0, DAC_VREF_POS_INPUT) MCFG_SOUND_ROUTE_EX(0, "dac2", 1.0, DAC_VREF_POS_INPUT) MCFG_SOUND_ROUTE_EX(0, "dac3", 1.0, DAC_VREF_POS_INPUT) MACHINE_CONFIG_END MACHINE_CONFIG_START(lazercmd_state::medlanes) /* basic machine hardware */ MCFG_CPU_ADD("maincpu", S2650, MASTER_CLOCK/12) /* 666 kHz */ /* Main Clock is 8MHz divided by 12 but memory and IO access is only possible within the line and frame blanking period thus requiring an extra loading of approx 3-5 */ MCFG_CPU_PROGRAM_MAP(medlanes_map) MCFG_CPU_DATA_MAP(lazercmd_portmap) MCFG_TIMER_DRIVER_ADD_SCANLINE("scantimer", lazercmd_state, lazercmd_timer, "screen", 0, 1) /* video hardware */ MCFG_SCREEN_ADD("screen", RASTER) MCFG_SCREEN_REFRESH_RATE(60) MCFG_SCREEN_VBLANK_TIME(ATTOSECONDS_IN_USEC(2500) /* not accurate */) MCFG_SCREEN_SIZE(HORZ_RES * HORZ_CHR, VERT_RES * VERT_CHR) MCFG_SCREEN_VISIBLE_AREA(0 * HORZ_CHR, HORZ_RES * HORZ_CHR - 1, 0 * VERT_CHR, VERT_RES * VERT_CHR - 1) MCFG_SCREEN_UPDATE_DRIVER(lazercmd_state, screen_update_lazercmd) MCFG_SCREEN_PALETTE("palette") MCFG_GFXDECODE_ADD("gfxdecode", "palette", lazercmd) MCFG_PALETTE_ADD("palette", 5) MCFG_PALETTE_INIT_OWNER(lazercmd_state, lazercmd) /* sound hardware */ MCFG_SPEAKER_STANDARD_MONO("speaker") MCFG_SOUND_ADD("dac2", DAC_1BIT, 0) MCFG_SOUND_ROUTE(ALL_OUTPUTS, "speaker", 0.99) MCFG_SOUND_ADD("dac3", DAC_1BIT, 0) MCFG_SOUND_ROUTE(ALL_OUTPUTS, "speaker", 0.99) MCFG_DEVICE_ADD("vref", VOLTAGE_REGULATOR, 0) MCFG_VOLTAGE_REGULATOR_OUTPUT(5.0) MCFG_SOUND_ROUTE_EX(0, "dac2", 1.0, DAC_VREF_POS_INPUT) MCFG_SOUND_ROUTE_EX(0, "dac3", 1.0, DAC_VREF_POS_INPUT) MACHINE_CONFIG_END MACHINE_CONFIG_START(lazercmd_state::bbonk) /* basic machine hardware */ MCFG_CPU_ADD("maincpu", S2650, MASTER_CLOCK/12) /* 666 kHz */ /* Main Clock is 8MHz divided by 12 but memory and IO access is only possible within the line and frame blanking period thus requiring an extra loading of approx 3-5 */ MCFG_CPU_PROGRAM_MAP(bbonk_map) MCFG_CPU_DATA_MAP(lazercmd_portmap) MCFG_TIMER_DRIVER_ADD_SCANLINE("scantimer", lazercmd_state, bbonk_timer, "screen", 0, 1) /* video hardware */ MCFG_SCREEN_ADD("screen", RASTER) MCFG_SCREEN_REFRESH_RATE(60) MCFG_SCREEN_VBLANK_TIME(ATTOSECONDS_IN_USEC(2500) /* not accurate */) MCFG_SCREEN_SIZE(HORZ_RES * HORZ_CHR, VERT_RES * VERT_CHR) MCFG_SCREEN_VISIBLE_AREA(0 * HORZ_CHR, HORZ_RES * HORZ_CHR - 1, 0 * VERT_CHR, (VERT_RES - 1) * VERT_CHR - 1) MCFG_SCREEN_UPDATE_DRIVER(lazercmd_state, screen_update_lazercmd) MCFG_SCREEN_PALETTE("palette") MCFG_GFXDECODE_ADD("gfxdecode", "palette", lazercmd) MCFG_PALETTE_ADD("palette", 5) MCFG_PALETTE_INIT_OWNER(lazercmd_state, lazercmd) /* sound hardware */ MCFG_SPEAKER_STANDARD_MONO("speaker") MCFG_SOUND_ADD("dac2", DAC_1BIT, 0) MCFG_SOUND_ROUTE(ALL_OUTPUTS, "speaker", 0.99) MCFG_SOUND_ADD("dac3", DAC_1BIT, 0) MCFG_SOUND_ROUTE(ALL_OUTPUTS, "speaker", 0.99) MCFG_DEVICE_ADD("vref", VOLTAGE_REGULATOR, 0) MCFG_VOLTAGE_REGULATOR_OUTPUT(5.0) MCFG_SOUND_ROUTE_EX(0, "dac2", 1.0, DAC_VREF_POS_INPUT) MCFG_SOUND_ROUTE_EX(0, "dac3", 1.0, DAC_VREF_POS_INPUT) MACHINE_CONFIG_END /*************************************************************************** Game driver(s) ***************************************************************************/ ROM_START( lazercmd ) ROM_REGION( 0x0c00, "maincpu", ROMREGION_INVERT ) /* 32K cpu, 4K for ROM/RAM */ ROM_LOAD_NIB_HIGH( "lc.e5", 0x0000, 0x0400, CRC(56dc7a40) SHA1(1324d5d6a44d7314723a0b5745d89f8e27f49d25) ) ROM_LOAD_NIB_LOW( "lc.f5", 0x0000, 0x0400, CRC(fc5b38a4) SHA1(bff670d7b78c6b9324d2bf4b2d8a4f9dbfe82158) ) ROM_LOAD_NIB_HIGH( "lc.e6", 0x0400, 0x0400, CRC(b1ef0aa2) SHA1(3edeaa4d4f4e18536066898284d430a1ac00512e) ) ROM_LOAD_NIB_LOW( "lc.f6", 0x0400, 0x0400, CRC(26eaee21) SHA1(9c0a4a22abb0b0466378f067ef52a45f86cc4369) ) ROM_LOAD_NIB_HIGH( "lc.e7", 0x0800, 0x0400, CRC(8e6ffc97) SHA1(d5243ce88585db91573b6586d3d47d13b5b473c8) ) ROM_LOAD_NIB_LOW( "lc.f7", 0x0800, 0x0400, CRC(9ec3534d) SHA1(98f15c5828ad2743bf205f71b8e69abd4db78a58) ) ROM_REGION( 0x0c00, "gfx1", 0 ) ROM_LOAD( "lc.b8", 0x0a00, 0x0200, CRC(6d708edd) SHA1(85a45a292eb7bca288b06a118658bf754f828a92) ) ROM_END ROM_START( medlanes ) ROM_REGION( 0x1800, "maincpu", ROMREGION_INVERT ) /* 32K cpu, 4K for ROM/RAM */ ROM_LOAD_NIB_HIGH( "medlanes.2a", 0x0000, 0x0400, CRC(9c77566a) SHA1(60e1820012b47da8b86d54f00b6f60d2d0123745) ) ROM_LOAD_NIB_LOW( "medlanes.3a", 0x0000, 0x0400, CRC(22bc56a6) SHA1(7444170c19274d9d889df61796e6f61af2361f3e) ) ROM_LOAD_NIB_HIGH( "medlanes.2b", 0x0400, 0x0400, CRC(7841b1a9) SHA1(80621d30995dad42ae44c62494922ca8b75415cf) ) ROM_LOAD_NIB_LOW( "medlanes.3b", 0x0400, 0x0400, CRC(6616dbef) SHA1(9506177315883b7d87a9bfada712ddeea12fd446) ) ROM_LOAD_NIB_HIGH( "medlanes.2c", 0x0800, 0x0400, CRC(a359b5b8) SHA1(dbc3c286951c50e3465132fc0d6054f06026425d) ) ROM_LOAD_NIB_LOW( "medlanes.3c", 0x0800, 0x0400, CRC(b3db0f3d) SHA1(57c28a54f7a1f17df3a24b61dd0cf37f9f6bc7d8) ) ROM_LOAD_NIB_HIGH( "medlanes.1a", 0x1000, 0x0400, CRC(0d57c596) SHA1(f3ce4802fc777c57f75fe691c93b7062903bdf06) ) ROM_LOAD_NIB_LOW( "medlanes.4a", 0x1000, 0x0400, CRC(30d495e9) SHA1(4f2414bf60ef91093bedf5e9ae16833e9e135aa7) ) ROM_LOAD_NIB_HIGH( "medlanes.1b", 0x1400, 0x0400, CRC(1d451630) SHA1(bf9de3096e98685355c906ab7e1dc2628dce79d6) ) ROM_LOAD_NIB_LOW( "medlanes.4b", 0x1400, 0x0400, CRC(a4abb5db) SHA1(a20da872b0f7d6b16b9551233af4269db9d1b55f) ) ROM_REGION( 0x0c00, "gfx1", 0 ) ROM_LOAD( "medlanes.8b", 0x0a00, 0x0200, CRC(44e5de8f) SHA1(fc797fa137f0c11a15caf9c0013aac668fd69a3c) ) ROM_END ROM_START( bbonk ) ROM_REGION( 0x0c00, "maincpu", ROMREGION_INVERT ) /* 32K cpu, 4K for ROM/RAM */ ROM_LOAD_NIB_HIGH( "bbonk.e5", 0x0000, 0x0400, CRC(d032baa0) SHA1(09cba16f6a2b7d8a8c501db639bd5eeefb63dc0f) ) ROM_LOAD_NIB_LOW( "bbonk.f5", 0x0000, 0x0400, CRC(748e8c7f) SHA1(99e4e182ee41c246e31f656411a9f09d7b617f92) ) ROM_LOAD_NIB_HIGH( "bbonk.e6", 0x0400, 0x0400, CRC(71df0e25) SHA1(c2f78490816add1296923861a89df15be9822fed) ) ROM_LOAD_NIB_LOW( "bbonk.f6", 0x0400, 0x0400, CRC(5ce183ed) SHA1(7c78dfa463a37605e8423104426af2f5906fae24) ) ROM_REGION( 0x0c00, "gfx1", 0 ) ROM_LOAD( "bbonk.b8", 0x0a00, 0x0200, CRC(5ac34260) SHA1(7c2b1e378d2b9fed27117f9adab1381507f5d554) ) ROM_END DRIVER_INIT_MEMBER(lazercmd_state,lazercmd) { int i, y; uint8_t *gfx = memregion("gfx1")->base(); /****************************************************************** * To show the maze bit #6 and #7 of the video ram are used. * Bit #7: add a vertical line to the right of the character * Bit #6: add a horizontal line below the character * The video logic generates 10 lines per character row, but the * character generator only contains 8 rows, so we expand the * font to 8x10. ******************************************************************/ for (i = 0; i < 0x40; i++) { uint8_t *d = &gfx[0 * 64 * 10 + i * VERT_CHR]; uint8_t *s = &gfx[4 * 64 * 10 + i * VERT_FNT]; for (y = 0; y < VERT_CHR; y++) { d[0 * 64 * 10] = (y < VERT_FNT) ? *s++ : 0xff; d[1 * 64 * 10] = (y == VERT_CHR - 1) ? 0 : *d; d[2 * 64 * 10] = *d & 0xfe; d[3 * 64 * 10] = (y == VERT_CHR - 1) ? 0 : *d & 0xfe; d++; } } } GAMEL( 1976, lazercmd, 0, lazercmd, lazercmd, lazercmd_state, lazercmd, ROT0, "Meadows Games, Inc.", "Lazer Command", MACHINE_SUPPORTS_SAVE, layout_lazercmd ) GAMEL( 1977, medlanes, 0, medlanes, medlanes, lazercmd_state, lazercmd, ROT0, "Meadows Games, Inc.", "Meadows Lanes", MACHINE_IMPERFECT_SOUND | MACHINE_SUPPORTS_SAVE, layout_medlanes ) GAME ( 1976, bbonk, 0, bbonk, bbonk, lazercmd_state, lazercmd, ROT0, "Meadows Games, Inc.", "Bigfoot Bonkers", MACHINE_SUPPORTS_SAVE ) #include template T gcd(T a, T b) { if(!b) return a; return gcd(b, a % b); } template T lcm(T a, T b) { return a * b / gcd(a, b); } template void chmin(T& a, T b) { a = (a > b) ? b : a; } template void chmax(T& a, T b) { a = (a < b) ? b : a; } int in() { int x; scanf("%d", &x); return x; } using namespace std; typedef long long Int; typedef unsigned uint; const int MAXN = 110; int T, N, M; int mat[MAXN][MAXN]; struct edge { int a, b; int len; edge(){} edge(int a, int b, int len): a(a), b(b), len(len){} bool operator<(const edge& other) const { return len < other.len; } }; struct UnionFind { int N, *id, *sz; UnionFind(int _N) { id = new int[_N]; sz = new int[_N]; for(int i = 0; i < _N; i++) { id[i] = i; sz[i] = 1; } N = _N; } int root(int i) { while(i != id[i]) { id[i] = id[id[i]]; i = id[i]; } return i; } bool find(int p, int q) { return root(p) == root(q); } void unite(int p, int q) { int i = root(p); int j = root(q); if(i == j) return; if(sz[i] < sz[j]) { id[i] = j; sz[j] += sz[i]; } else { id[j] = i; sz[i] += sz[j]; } } }; int main(void) { cin >> T; for (int t = 0; t < T; t++) { cin >> N >> M; int A, B; UnionFind uf(N); vector ve; memset(mat, 0, sizeof(mat)); for (int i = 0; i < M; i++) { cin >> A >> B; mat[A][B] = mat[B][A] = 1; } for (int i = 0; i < N; i++) { for (int j = i; j < N; j++) { ve.push_back(edge(i, j, mat[i][j])); } } sort(ve.begin(), ve.end()); int ans = 0; for (int i = 0; i < (int) ve.size(); i++) { if (!uf.find(ve[i].a, ve[i].b)) { uf.unite(ve[i].a, ve[i].b); ans += ve[i].len; } } cout << ans << "\n"; } return 0; } 1-10 // ReactivePlusPlus library // // Copyright 2022 - present. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // https://www.boost.org/LICENSE_1_0.txt) // // Project home: https://github.com/victimsnino/ReactivePlusPlus // #include "copy_count_tracker.hpp" #include "mock_observer.hpp" #include #include #include #include #include SCENARIO("merge for observable of observables", "[operators][merge]") { auto mock = mock_observer(); GIVEN("observable of observables") { auto obs= rpp::source::just(rpp::source::just(1), rpp::source::just(2)); WHEN("subscribe on merge of observable") { obs.merge().subscribe(mock); THEN("observer obtains values FROM underlying observables") { CHECK(mock.get_received_values() == std::vector{ 1,2 }); CHECK(mock.get_on_completed_count() == 1); } } } GIVEN("observable of observables with first never") { auto obs = rpp::source::just(rpp::source::never().as_dynamic(), rpp::source::just(2).as_dynamic()); WHEN("subscribe on merge of observable") { obs.merge().subscribe(mock); THEN("observer obtains values from second observable even if first emits nothing") { CHECK(mock.get_received_values() == std::vector{ 2 }); CHECK(mock.get_on_completed_count() == 0); //no complete due to first observable sends nothing } } } GIVEN("observable of observables without complete") { auto obs = rpp::source::create>([](const auto& sub) { sub.on_next(rpp::source::just(1).as_dynamic()); sub.on_next(rpp::source::just(2).as_dynamic()); }); WHEN("subscribe on merge of observable") { obs.merge().subscribe(mock); THEN("observer obtains values from second observable even if first emits nothing") { CHECK(mock.get_received_values() == std::vector{ 1, 2 }); CHECK(mock.get_on_completed_count() == 0); //no complete due to root observable is not completed } } } GIVEN("observable of observables one with error") { auto obs = rpp::source::create>([](const auto& sub) { sub.on_next(rpp::source::just(1).as_dynamic()); sub.on_next(rpp::source::error(std::make_exception_ptr(std::runtime_error{""})).as_dynamic()); sub.on_next(rpp::source::just(2).as_dynamic()); }); WHEN("subscribe on merge of observable") { obs.merge().subscribe(mock); THEN("observer obtains values from second observable even if first emits nothing") { CHECK(mock.get_received_values() == std::vector{ 1 }); CHECK(mock.get_on_error_count() == 1); CHECK(mock.get_on_completed_count() == 0); //no complete due to error } } } GIVEN("observable of observables with error") { auto obs = rpp::source::create>([](const auto& sub) { sub.on_error(std::make_exception_ptr(std::runtime_error{""})); sub.on_next(rpp::source::just(1).as_dynamic()); }); WHEN("subscribe on merge of observable") { obs.merge().subscribe(mock); THEN("observer obtains values from second observable even if first emits nothing") { CHECK(mock.get_total_on_next_count() == 0); CHECK(mock.get_on_error_count() == 1); CHECK(mock.get_on_completed_count() == 0); //no complete due to error } } } } SCENARIO("merge_with", "[operators][merge]") { auto mock = mock_observer(); GIVEN("2 observables") { auto obs_1 = rpp::source::just(1); auto obs_2 = rpp::source::just(2); WHEN("subscribe on merge of this observables") { obs_1.merge_with(obs_2).subscribe(mock); THEN("observer obtains values FROM both observables") { CHECK(mock.get_received_values() == std::vector{ 1,2 }); CHECK(mock.get_on_completed_count() == 1); } } } GIVEN("never observable with just observable") { auto obs_1 = rpp::source::never(); auto obs_2 = rpp::source::just(2); WHEN("subscribe on merge of this observables") { obs_1.merge_with(obs_2).subscribe(mock); THEN("observer obtains values FROM both observables") { CHECK(mock.get_received_values() == std::vector{ 2 }); CHECK(mock.get_on_completed_count() == 0); // first observable never completes } } WHEN("subscribe on merge of this observables in reverse oreder") { obs_2.merge_with(obs_1).subscribe(mock); THEN("observer obtains values FROM both observables") { CHECK(mock.get_received_values() == std::vector{ 2 }); CHECK(mock.get_on_completed_count() == 0); // first observable never completes } } } GIVEN("error observable with just observable") { auto obs_1 = rpp::source::error(std::make_exception_ptr(std::runtime_error{""})); auto obs_2 = rpp::source::just(2); WHEN("subscribe on merge of this observables") { obs_1.merge_with(obs_2).subscribe(mock); THEN("observer obtains values FROM both observables") { CHECK(mock.get_total_on_next_count()==0); CHECK(mock.get_on_error_count() == 1); CHECK(mock.get_on_completed_count() == 0); } } } } SCENARIO("merge serializes emissions", "[operators][merge]") { GIVEN("observables from different threads") { auto s1 = rpp::source::just(rpp::schedulers::new_thread{}, 1); auto s2 = rpp::source::just(rpp::schedulers::new_thread{}, 2); WHEN("subscribe on merge of this observables") { THEN("resulting observable emits items sequentially") { std::atomic_size_t counter{}; size_t max_value = 0; s1.merge_with(s2).as_blocking().subscribe([&](const auto&) { CHECK(++counter < 2); max_value = std::max(counter.load(), max_value); std::this_thread::sleep_for(std::chrono::seconds{1}); max_value = std::max(counter.load(), max_value); --counter; }); CHECK(max_value == 1); } } } } SCENARIO("merge doesn't produce extra copies", "[operators][merge][track_copy]") { GIVEN("observable and subscriber") { copy_count_tracker verifier{}; auto obs = rpp::source::just(verifier.get_observable()).merge(); WHEN("subscribe") { obs.subscribe([](copy_count_tracker){}); THEN("no extra copies") { // 1 copy to final lambda REQUIRE(verifier.get_copy_count() == 1); REQUIRE(verifier.get_move_count() == 0); } } } } SCENARIO("merge doesn't produce copies for move", "[operators][merge][track_copy]") { GIVEN("observable and subscriber") { copy_count_tracker verifier{}; auto obs = rpp::source::just(verifier.get_observable_for_move()).merge(); WHEN("subscribe") { obs.subscribe([](copy_count_tracker) {}); THEN("no extra copies") { REQUIRE(verifier.get_copy_count() == 0); // 1 move to final lambda REQUIRE(verifier.get_move_count() == 1); } } } } /** * 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 AmplifyBackend { namespace Model { CreateBackendAuthUserPoolConfig::CreateBackendAuthUserPoolConfig() : m_forgotPasswordHasBeenSet(false), m_mfaHasBeenSet(false), m_oAuthHasBeenSet(false), m_passwordPolicyHasBeenSet(false), m_requiredSignUpAttributesHasBeenSet(false), m_signInMethod(SignInMethod::NOT_SET), m_signInMethodHasBeenSet(false), m_userPoolNameHasBeenSet(false), m_verificationMessageHasBeenSet(false) { } CreateBackendAuthUserPoolConfig::CreateBackendAuthUserPoolConfig(JsonView jsonValue) : m_forgotPasswordHasBeenSet(false), m_mfaHasBeenSet(false), m_oAuthHasBeenSet(false), m_passwordPolicyHasBeenSet(false), m_requiredSignUpAttributesHasBeenSet(false), m_signInMethod(SignInMethod::NOT_SET), m_signInMethodHasBeenSet(false), m_userPoolNameHasBeenSet(false), m_verificationMessageHasBeenSet(false) { *this = jsonValue; } CreateBackendAuthUserPoolConfig& CreateBackendAuthUserPoolConfig::operator =(JsonView jsonValue) { if(jsonValue.ValueExists("forgotPassword")) { m_forgotPassword = jsonValue.GetObject("forgotPassword"); m_forgotPasswordHasBeenSet = true; } if(jsonValue.ValueExists("mfa")) { m_mfa = jsonValue.GetObject("mfa"); m_mfaHasBeenSet = true; } if(jsonValue.ValueExists("oAuth")) { m_oAuth = jsonValue.GetObject("oAuth"); m_oAuthHasBeenSet = true; } if(jsonValue.ValueExists("passwordPolicy")) { m_passwordPolicy = jsonValue.GetObject("passwordPolicy"); m_passwordPolicyHasBeenSet = true; } if(jsonValue.ValueExists("requiredSignUpAttributes")) { Array requiredSignUpAttributesJsonList = jsonValue.GetArray("requiredSignUpAttributes"); for(unsigned requiredSignUpAttributesIndex = 0; requiredSignUpAttributesIndex < requiredSignUpAttributesJsonList.GetLength(); ++requiredSignUpAttributesIndex) { m_requiredSignUpAttributes.push_back(RequiredSignUpAttributesElementMapper::GetRequiredSignUpAttributesElementForName(requiredSignUpAttributesJsonList[requiredSignUpAttributesIndex].AsString())); } m_requiredSignUpAttributesHasBeenSet = true; } if(jsonValue.ValueExists("signInMethod")) { m_signInMethod = SignInMethodMapper::GetSignInMethodForName(jsonValue.GetString("signInMethod")); m_signInMethodHasBeenSet = true; } if(jsonValue.ValueExists("userPoolName")) { m_userPoolName = jsonValue.GetString("userPoolName"); m_userPoolNameHasBeenSet = true; } if(jsonValue.ValueExists("verificationMessage")) { m_verificationMessage = jsonValue.GetObject("verificationMessage"); m_verificationMessageHasBeenSet = true; } return *this; } JsonValue CreateBackendAuthUserPoolConfig::Jsonize() const { JsonValue payload; if(m_forgotPasswordHasBeenSet) { payload.WithObject("forgotPassword", m_forgotPassword.Jsonize()); } if(m_mfaHasBeenSet) { payload.WithObject("mfa", m_mfa.Jsonize()); } if(m_oAuthHasBeenSet) { payload.WithObject("oAuth", m_oAuth.Jsonize()); } if(m_passwordPolicyHasBeenSet) { payload.WithObject("passwordPolicy", m_passwordPolicy.Jsonize()); } if(m_requiredSignUpAttributesHasBeenSet) { Array requiredSignUpAttributesJsonList(m_requiredSignUpAttributes.size()); for(unsigned requiredSignUpAttributesIndex = 0; requiredSignUpAttributesIndex < requiredSignUpAttributesJsonList.GetLength(); ++requiredSignUpAttributesIndex) { requiredSignUpAttributesJsonList[requiredSignUpAttributesIndex].AsString(RequiredSignUpAttributesElementMapper::GetNameForRequiredSignUpAttributesElement(m_requiredSignUpAttributes[requiredSignUpAttributesIndex])); } payload.WithArray("requiredSignUpAttributes", std::move(requiredSignUpAttributesJsonList)); } if(m_signInMethodHasBeenSet) { payload.WithString("signInMethod", SignInMethodMapper::GetNameForSignInMethod(m_signInMethod)); } if(m_userPoolNameHasBeenSet) { payload.WithString("userPoolName", m_userPoolName); } if(m_verificationMessageHasBeenSet) { payload.WithObject("verificationMessage", m_verificationMessage.Jsonize()); } return payload; } } // namespace Model } // namespace AmplifyBackend } // namespace Aws #include "action.h" bool linklayer::Action::is_within(const Action &action) const { return this->start >= action.start && this->end <= action.end; } bool linklayer::Action::operator==(const linklayer::Action &rhs) const { return state == rhs.state && id == rhs.id && chn == rhs.chn; } bool linklayer::Action::operator!=(const linklayer::Action &rhs) const { return !(rhs == *this); } jayrulez/eepp #ifndef EE_GRAPHICS_VBOHELPER_HPP #define EE_GRAPHICS_VBOHELPER_HPP namespace EE { namespace Graphics { /// VBO default usage type enum class VertexBufferUsageType : int { Static, Dynamic, Stream, }; enum VertexFlags { VERTEX_FLAG_POSITION = 0, VERTEX_FLAG_TEXTURE0 = 1, VERTEX_FLAG_TEXTURE1 = 2, VERTEX_FLAG_TEXTURE2 = 3, VERTEX_FLAG_TEXTURE3 = 4, VERTEX_FLAG_COLOR = 5, VERTEX_FLAG_USE_INDICES = 6 }; #define VERTEX_FLAGS_COUNT_ARR ( 5 ) #define VERTEX_FLAGS_COUNT ( 6 ) const int VertexElementCount[] = { 2, // Position 2, // Texture0 2, // Texture1 2, // Texture2 2, // Texture3 4 // Color0 }; #define VERTEX_FLAG_GET( X ) ( 1 << ( X ) ) #define VERTEX_FLAG_SET( F, X ) \ if ( !( F & VERTEX_FLAG_GET( X ) ) ) \ F |= VERTEX_FLAG_GET( X ); #define VERTEX_FLAG_QUERY( F, X ) ( F & VERTEX_FLAG_GET( X ) ) /// Vertex data will have position, color and texture UV. #define VERTEX_FLAGS_DEFAULT \ ( VERTEX_FLAG_GET( VERTEX_FLAG_POSITION ) | VERTEX_FLAG_GET( VERTEX_FLAG_TEXTURE0 ) | \ VERTEX_FLAG_GET( VERTEX_FLAG_COLOR ) ) /// Vertex data will have position and color. #define VERTEX_FLAGS_PRIMITIVE \ ( VERTEX_FLAG_GET( VERTEX_FLAG_POSITION ) | VERTEX_FLAG_GET( VERTEX_FLAG_COLOR ) ) }} // namespace EE::Graphics #endif // // FILE NAME: CQCKit_EvMonCfg.hpp // // AUTHOR: // // CREATED: 11/08/2014 // // COPYRIGHT: Charmed Quark Systems, Ltd @ 2020 // // This software is copyrighted by 'Charmed Quark Systems, Ltd' and // the author (.) It is licensed under the MIT Open Source // license: // // https://opensource.org/licenses/MIT // // DESCRIPTION: // // This file defines a class used to contain the configuration for event monitors. // This is what we store away in the config server and use to reload the monitors // upon system restart. // // We define a simple derivative that includes the path it was loaded from, which is // often useful, such as by the event server, when a list of events keyed by the path // is needed. // // // CAVEATS/GOTCHAS: // // 1) As of 5.0, we moved them to the standard hierarchical storage. They used to have // a unique id that was the actual id, plus a human readable name, and actions // referred to them via the id. Now the path is the unique id. During the upgrade // process the old id will be read in and the events will be moved to their new // location under the /User section of the triggered events scope, with the id // as the name. // // Actions that reference the ids will be updated so put that path prefix before // the id, making them now correctly refer to them in the new scheme. The user can // rename them after the ugprade if they want to give them more meaningful names. // // LOG: // #pragma once #pragma CIDLIB_PACK(CIDLIBPACK) // --------------------------------------------------------------------------- // CLASS: TCQCEvMonCfg // PREFIX: emonc // --------------------------------------------------------------------------- class CQCKITEXPORT TCQCEvMonCfg : public TObject, public MStreamable { public : // ------------------------------------------------------------------- // Constructors and Destructor // ------------------------------------------------------------------- TCQCEvMonCfg(); TCQCEvMonCfg(const TCQCEvMonCfg&) = default; TCQCEvMonCfg(TCQCEvMonCfg&&) = default; ~TCQCEvMonCfg(); // ------------------------------------------------------------------- // Public operators // ------------------------------------------------------------------- TCQCEvMonCfg& operator=(const TCQCEvMonCfg&) = default; TCQCEvMonCfg& operator=(TCQCEvMonCfg&&) = default; tCIDLib::TBoolean operator== ( const TCQCEvMonCfg& emoncSrc ) const; tCIDLib::TBoolean operator!= ( const TCQCEvMonCfg& emoncSrc ) const; // ------------------------------------------------------------------- // Public, non-virtual methods // ------------------------------------------------------------------- [[nodiscard]] tCIDLib::TBoolean bFailed() const; tCIDLib::TBoolean bFailed ( const tCIDLib::TBoolean bToSet ); [[nodiscard]] tCIDLib::TBoolean bPaused() const; tCIDLib::TBoolean bPaused ( const tCIDLib::TBoolean bToSet ); [[nodiscard]] const TString& strClassPath() const; const TString& strClassPath ( const TString& strToSet ); [[nodiscard]] const TString& strDescr() const; [[nodiscard]] const TString& strParams() const; tCIDLib::TVoid Set ( const TString& strClassPath , const TString& strDescr , const TString& strParams ); // ------------------------------------------------------------------- // Only required for the 5.0 upgrade process // ------------------------------------------------------------------- const TString& strId() const; protected : // ------------------------------------------------------------------- // Protected, inherited methods // ------------------------------------------------------------------- tCIDLib::TVoid StreamFrom ( TBinInStream& strmToReadFrom ) final; tCIDLib::TVoid StreamTo ( TBinOutStream& strmToWriteTo ) const final; private : // ------------------------------------------------------------------- // Private data members // // m_bFailed // This is only used at runtime by the server. Since this is the info // returned to clients by the server, we want to be able to return this // info as well, so it is streamed, but the actual persisted value // doesn't have any meaning. // // m_bPaused // To allow monitors to be paused/resumed as needed, without having to // remove them from the list of configured monitors. // // m_strClassPath // The CML class path to the class that provides the code for this // monitor. It is in the hierarchical format. // // m_strDescr // A short description, for human consumption, to make it easier to // remember what a given monitor is for. // // m_strId // In the pre-5.0 world, events were identified by a unique generated // id. Now they are hierarchical. We just keep this around in order to // do the upgrade process. See the class notes above. // // m_strParams // Parameters that can be passed to the monitor class. // ------------------------------------------------------------------- tCIDLib::TBoolean m_bFailed; tCIDLib::TBoolean m_bPaused; TString m_strClassPath; TString m_strDescr; TString m_strId; TString m_strParams; // ------------------------------------------------------------------- // Magic macros // ------------------------------------------------------------------- RTTIDefs(TCQCEvMonCfg, TObject) }; // --------------------------------------------------------------------------- // CLASS: TKeyedCQCEvMonCfg // PREFIX: csrc // // A convenience for folks who need to keep a list of these events, keyed by // the path. // --------------------------------------------------------------------------- class CQCKITEXPORT TKeyedCQCEvMonCfg : public TCQCEvMonCfg { public : // ------------------------------------------------------------------- // Constructors and destructor // ------------------------------------------------------------------- TKeyedCQCEvMonCfg(); TKeyedCQCEvMonCfg ( const TString& strPath , const TCQCEvMonCfg& csrcBase ); TKeyedCQCEvMonCfg(const TKeyedCQCEvMonCfg&) = default; TKeyedCQCEvMonCfg(TKeyedCQCEvMonCfg&&) = default; ~TKeyedCQCEvMonCfg(); // ------------------------------------------------------------------- // Public operators // ------------------------------------------------------------------- TKeyedCQCEvMonCfg& operator=(const TKeyedCQCEvMonCfg&) = default; TKeyedCQCEvMonCfg& operator=(TKeyedCQCEvMonCfg&&) = default; // ------------------------------------------------------------------- // Public, non-virtual methods // ------------------------------------------------------------------- [[nodiscard]] const TString& strPath() const; const TString& strPath ( const TString& strToSet ); private : // ------------------------------------------------------------------- // Private data members // // m_strPath // The path from which this event was loaded. It could change if the // user does a rename. // ------------------------------------------------------------------- TString m_strPath; }; #pragma CIDLIB_POPPACK 1-10 // Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved. // // Licensed under the BSD 3-Clause License (the "License"); you may not use this // file except in compliance with the License. You may obtain a copy of the // License at // // https://opensource.org/licenses/BSD-3-Clause // // 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 "flare/base/monitoring/dispatcher.h" #include #include #include #include #include #include #include #include #include "flare/base/chrono.h" #include "flare/base/internal/time_keeper.h" #include "flare/base/monitoring/monitoring_system.h" #include "flare/base/never_destroyed.h" using namespace std::literals; DEFINE_int32( flare_monitoring_minimum_report_interval, 1000, "Interval between two reports to monitoring system, in milliseconds. " "Setting it too low can hurt performance. Note that we don't always " "respect this parameter. If all monitoring systems in use require a " "greater \"minimum interval\", their request is respected instead."); namespace flare::monitoring { namespace { template std::optional TryRemapKey(const T& config, const std::string_view& key) { if (!config.remap_keys) { return std::string(key); } if (auto opt = config.key_mapping.TryGet(key)) { return *opt; } if (!config.drop_unknown_keys) { return std::string(key); } FLARE_LOG_WARNING_ONCE( "At least one of keys reported (e.g. [{}]) is not found in remap file of " "monitoring system [{}]. Ignoring.", key, config.name); return std::nullopt; } template void MoveReports(const V& config, T* to, U* from) { to->reserve(from->size()); for (auto&& [key, events] : *from) { to->push_back(std::move(events)); if (auto opt = TryRemapKey(config, key.first)) { to->back().key = *opt; } else { to->pop_back(); } } } } // namespace Dispatcher* Dispatcher::Instance() { static NeverDestroyed dispatcher; return dispatcher.Get(); } void Dispatcher::ReportEvents(const std::vector& events) { for (auto&& per_sys : pending_events_) { auto&& e = per_sys.events; std::scoped_lock _(e->lock); e->discrete_events.insert(e->discrete_events.end(), events.begin(), events.end()); } } void Dispatcher::ReportCoalescedEvent(const CoalescedCounterEvent& event) { for (auto&& per_sys : pending_events_) { auto&& e = per_sys.events; std::scoped_lock _(e->lock); auto&& key = std::pair(event.key, event.tags); auto iter = e->counter_events.find(key); if (iter == e->counter_events.end()) { e->counter_events[key] = event; } else { auto&& entry = iter->second; entry.sum += event.sum; entry.times += event.times; } } } void Dispatcher::ReportCoalescedEvent(const CoalescedGaugeEvent& event) { for (auto&& per_sys : pending_events_) { auto&& e = per_sys.events; std::scoped_lock _(e->lock); auto&& key = std::pair(event.key, event.tags); auto iter = e->gauge_events.find(key); if (iter == e->gauge_events.end()) { e->gauge_events[key] = event; } else { auto&& entry = iter->second; entry.sum += event.sum; entry.times += event.times; } } } void Dispatcher::ReportCoalescedEvent(const CoalescedTimerEvent& event) { for (auto&& per_sys : pending_events_) { auto&& e = per_sys.events; std::scoped_lock _(e->lock); auto&& key = std::pair(event.key, event.tags); auto iter = e->timer_events.find(key); if (iter == e->timer_events.end()) { e->timer_events[key] = event; } else { auto&& entry = iter->second; FLARE_CHECK(entry.unit == entry.unit); // How can the unit change? // FIXME: This is slow. std::map merged; for (auto&& [k, v] : entry.times) { merged[k] += v; } for (auto&& [k, v] : event.times) { merged[k] += v; } entry.times.clear(); for (auto&& [k, v] : merged) { entry.times.emplace_back(k, v); } } } } void Dispatcher::AddMonitoringSystem(std::string name, MonitoringSystem* system) { FLARE_LOG_INFO("Enabled monitoring system [{}].", name); pending_events_.emplace_back( PerSystemEvents{.name = name, .system = system, .events = std::make_unique(), .remap_keys = false}); } void Dispatcher::AddMonitoringSystem( std::string name, MonitoringSystem* system, internal::HashMap key_mapping, bool drop_unknown_keys) { FLARE_LOG_INFO("Enabled monitoring system [{}] (with keys remapped).", name); pending_events_.emplace_back( PerSystemEvents{.name = name, .system = system, .events = std::make_unique(), .remap_keys = true, .key_mapping = std::move(key_mapping), .drop_unknown_keys = drop_unknown_keys}); } void Dispatcher::Start() { std::chrono::nanoseconds interval = 10000s; // ... // Use lowest interval among the enabled monitoring systems. for (auto&& e : pending_events_) { interval = std::min(e.system->GetPersonality().minimum_report_interval, interval); } // But if its too low, respect our own limit. interval = std::max( interval, FLAGS_flare_monitoring_minimum_report_interval * 1ms); timer_id_ = internal::TimeKeeper::Instance()->AddTimer( ReadCoarseSteadyClock(), interval, [this](auto) { OnTimerProc(); }, true); } void Dispatcher::Stop() { internal::TimeKeeper::Instance()->KillTimer(timer_id_); } void Dispatcher::Join() { // NOTHING. } void Dispatcher::OnTimerProc() { for (auto&& per_sys_env : pending_events_) { auto&& events = per_sys_env.events; MonitoringSystem::EventBuffers buffer; { std::scoped_lock _(events->lock); if (events->next_flush_at > ReadCoarseSteadyClock()) { continue; } events->next_flush_at = ReadCoarseSteadyClock() + per_sys_env.system->GetPersonality().minimum_report_interval; // Move reports to `buffer`. buffer.discrete_events.reserve(events->discrete_events.size()); for (auto&& e : events->discrete_events) { if (auto opt = TryRemapKey(per_sys_env, e.GetKey())) { buffer.discrete_events.push_back(std::move(e)); buffer.discrete_events.back().key = *opt; } // Ignored otherwise. } events->discrete_events.clear(); // Key remapping is done by `MoveReports`. MoveReports(per_sys_env, &buffer.counter_events, &events->counter_events); events->counter_events.clear(); MoveReports(per_sys_env, &buffer.gauge_events, &events->gauge_events); events->gauge_events.clear(); MoveReports(per_sys_env, &buffer.timer_events, &events->timer_events); events->timer_events.clear(); } // Don't call monitoring system provider if we have nothing to report. if (!buffer.discrete_events.empty() || !buffer.counter_events.empty() || !buffer.gauge_events.empty() || !buffer.timer_events.empty()) { per_sys_env.system->Report(buffer); // Report events with lock released. } } } } // namespace flare::monitoring Spidey01/sxe /*- * Copyright (c) 2019-current, <> * * 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 "./SubsystemTest.hpp" #include #include #include #include #include using std::string; using sxe::GameEngine; using sxe::common::Subsystem; using sxe::config::Settings; using sxe::sys::FileSystem::path; static const string TAG = "SubsystemTest"; static GameEngine sGameEngine; CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(SubsystemTest, TAG); CPPUNIT_REGISTRY_ADD_TO_DEFAULT(TAG); class TestSubsystem : public Subsystem { public: TestSubsystem() : Subsystem("TestSubsystem") { } string_type lastSettingChanged; protected: void onSettingChanged(string_type key) override { lastSettingChanged = key; } }; void SubsystemTest::name() { Log::xtrace(TAG, "name()"); TestSubsystem subsystem; CPPUNIT_ASSERT_MESSAGE("Subsystem::name() should match its ctor.", subsystem.name() == "TestSubsystem"); } void SubsystemTest::initialization() { Log::xtrace(TAG, "initialization()"); TestSubsystem subsystem; CPPUNIT_ASSERT_MESSAGE("isInitialized() is false until initialize() is called.", subsystem.isInitialized() == false); CPPUNIT_ASSERT_NO_THROW(subsystem.initialize(sGameEngine)); CPPUNIT_ASSERT_MESSAGE("isInitialized() is true until uninitialize() is called.", subsystem.isInitialized() == true); CPPUNIT_ASSERT_NO_THROW(subsystem.reinitialize(sGameEngine)); CPPUNIT_ASSERT_MESSAGE("isInitialized() is true after reinitialize() is called.", subsystem.isInitialized() == true); CPPUNIT_ASSERT_NO_THROW(subsystem.uninitialize()); CPPUNIT_ASSERT_MESSAGE("isInitialized() is false after uninitialize() is called.", subsystem.isInitialized() == false); } void SubsystemTest::onSettingChanged() { Log::xtrace(TAG, "onSettingChanged()"); TestSubsystem subsystem; Settings& settings = sGameEngine.getSettings(); settings.setString("no", "one listening"); CPPUNIT_ASSERT_MESSAGE("No notifications before initialize.", subsystem.lastSettingChanged.empty()); subsystem.initialize(sGameEngine); settings.setString("any", "key"); CPPUNIT_ASSERT(subsystem.lastSettingChanged == "any"); subsystem.lastSettingChanged.clear(); subsystem.getSettingsListener().setFilter("specific"); settings.setString("not", "it"); CPPUNIT_ASSERT_MESSAGE("SettingsListener::setFilter is broken if this doesn't work.", subsystem.lastSettingChanged.empty()); subsystem.lastSettingChanged.clear(); subsystem.uninitialize(); settings.setString("any", "key"); CPPUNIT_ASSERT_MESSAGE("No notifications after uninitialize.", subsystem.lastSettingChanged.empty()); } #include #include using namespace std; int main() { string s1, s2; cin >> s1 >> s2; transform(begin(s1), end(s1), begin(s1), [](char c){return tolower(c);}); transform(begin(s2), end(s2), begin(s2), [](char c){return tolower(c);}); if (string(s1) > s2) cout << 1; else if (string(s1) == s2) cout << 0; else cout << -1; return 0; } 0 #include #include #include #include #include namespace Poplin { void PhysicsContactListener::BeginContact(b2Contact* contact) { RigidBodyComponent::RigidBodyUserData* userDataA{ (RigidBodyComponent::RigidBodyUserData*)contact->GetFixtureA()->GetBody()->GetUserData().pointer }; RigidBodyComponent::RigidBodyUserData* userDataB{ (RigidBodyComponent::RigidBodyUserData*)contact->GetFixtureB()->GetBody()->GetUserData().pointer }; if (userDataA->m_Entity.HasComponent()) { SpriteComponent& sprite{ userDataA->m_Entity.GetComponent() }; if (sprite.SpriteTexture && sprite.SpriteTexture->GetAssetID() == 123) { sprite.SpriteTexture = std::dynamic_pointer_cast(AssetLocator::Get().FindAsset((AssetID)321)); } } if (userDataB->m_Entity.HasComponent()) { SpriteComponent& sprite{ userDataB->m_Entity.GetComponent() }; if (sprite.SpriteTexture && sprite.SpriteTexture->GetAssetID() == 123) { sprite.SpriteTexture = std::dynamic_pointer_cast(AssetLocator::Get().FindAsset((AssetID)321)); } } } void PhysicsContactListener::EndContact(b2Contact* contact) { RigidBodyComponent::RigidBodyUserData* userDataA{ (RigidBodyComponent::RigidBodyUserData*)contact->GetFixtureA()->GetBody()->GetUserData().pointer }; RigidBodyComponent::RigidBodyUserData* userDataB{ (RigidBodyComponent::RigidBodyUserData*)contact->GetFixtureB()->GetBody()->GetUserData().pointer }; if (userDataA->m_Entity.HasComponent()) { SpriteComponent& sprite{ userDataA->m_Entity.GetComponent() }; if (sprite.SpriteTexture && sprite.SpriteTexture->GetAssetID() == 321) { sprite.SpriteTexture = std::dynamic_pointer_cast(AssetLocator::Get().FindAsset((AssetID)123)); } } if (userDataB->m_Entity.HasComponent()) { SpriteComponent& sprite{ userDataB->m_Entity.GetComponent() }; if (sprite.SpriteTexture && sprite.SpriteTexture->GetAssetID() == 321) { sprite.SpriteTexture = std::dynamic_pointer_cast(AssetLocator::Get().FindAsset((AssetID)123)); } } } }#include "StdAfx.h" #include "GGSceneNotify.h" using namespace Packets; uint GGSceneNotifyHandler::Execute( GGSceneNotify* pPacket, Player* pPlayer ) { __ENTER_FUNCTION return PACKET_EXE_CONTINUE ; __LEAVE_FUNCTION return PACKET_EXE_ERROR ; } 0 // Copyright 2020 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ml_benchmark/memory_sampler.h" #include #include namespace ml_benchmark { class PeakMemorySamplerTest : public ::testing::Test { public: PeakMemorySamplerTest() = default; protected: base::test::TaskEnvironment task_environment_{ base::test::TaskEnvironment::TimeSource::MOCK_TIME}; base::TimeDelta sampling_interval_ = base::Seconds(1); }; TEST_F(PeakMemorySamplerTest, BasicFunctions) { scoped_refptr sampler = new PeakMemorySampler(); // No samples should mean zero EXPECT_EQ(sampler->GetMaxSample(), 0); EXPECT_EQ(sampler->sample_counter_, 0); PeakMemorySampler::StartSampling(sampler); task_environment_.FastForwardBy(sampling_interval_); const int64_t initial_peak = sampler->GetMaxSample(); // StartSampling causes a sample, plus the interval is two samples. EXPECT_EQ(sampler->sample_counter_, 2); task_environment_.FastForwardBy(sampling_interval_ * 2); // Allocate 100MB const int hundred_mb_bytes = 1024 * 1024 * 100; char* allocate = new char[hundred_mb_bytes]; // Zero it out and read so the compiler doesn't optimize the variable away. memset(allocate, 0, hundred_mb_bytes); EXPECT_EQ(allocate[hundred_mb_bytes - 1], 0); task_environment_.FastForwardBy(sampling_interval_); const int64_t higher_peak = sampler->GetMaxSample(); EXPECT_GT(higher_peak, initial_peak); // Free the memory and make sure the peak doesn't drop delete[] allocate; task_environment_.FastForwardBy(sampling_interval_); EXPECT_EQ(higher_peak, sampler->GetMaxSample()); // Stop sampling, allocate a bunch more memory PeakMemorySampler::StopSampling(sampler); EXPECT_EQ(sampler->sample_counter_, 6); // Allocate 200MB const int two_hundred_mb_bytes = 1024 * 1024 * 200; allocate = new char[two_hundred_mb_bytes]; // Zero it out and read so the compiler doesn't optimize the variable away. memset(allocate, 0, two_hundred_mb_bytes); EXPECT_EQ(allocate[two_hundred_mb_bytes - 1], 0); // We're not sampling so the peak should stay the same. task_environment_.FastForwardBy(sampling_interval_ * 2); EXPECT_EQ(higher_peak, sampler->GetMaxSample()); EXPECT_EQ(sampler->sample_counter_, 6); // Start sampling again and check it grows PeakMemorySampler::StartSampling(sampler); task_environment_.FastForwardBy(sampling_interval_); EXPECT_GT(sampler->GetMaxSample(), higher_peak); // StartSampling causes a sample, plus the interval is two samples. EXPECT_EQ(sampler->sample_counter_, 8); delete[] allocate; } TEST_F(PeakMemorySamplerTest, LifeCycle) { scoped_refptr sampler = new PeakMemorySampler(); PeakMemorySampler::StartSampling(sampler); task_environment_.FastForwardBy(sampling_interval_); EXPECT_GT(sampler->GetMaxSample(), 0); // At this point another task has been scheduled in t+1, so // delete the object and move forward in time. We expect this // to 'just work' and not crash due to some dangling pointer. sampler.reset(); task_environment_.FastForwardBy(sampling_interval_ * 2); } } // namespace ml_benchmark #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; using namespace boost; using namespace Passenger; using namespace Passenger::ApplicationPool2; namespace tut { struct RequestHandlerTest { ServerInstanceDirPtr serverInstanceDir; ServerInstanceDir::GenerationPtr generation; string serverFilename; FileDescriptor requestSocket; AgentOptions agentOptions; BackgroundEventLoop bg; SpawnerFactoryPtr spawnerFactory; PoolPtr pool; shared_ptr handler; FileDescriptor connection; map defaultHeaders; string root; string rackAppPath, wsgiAppPath; RequestHandlerTest() { createServerInstanceDirAndGeneration(serverInstanceDir, generation); spawnerFactory = make_shared(bg.safe, *resourceLocator, generation); pool = make_shared(bg.safe.get(), spawnerFactory); pool->initialize(); serverFilename = generation->getPath() + "/server"; requestSocket = createUnixServer(serverFilename); setNonBlocking(requestSocket); setLogLevel(LVL_ERROR); // TODO: set to LVL_WARN agentOptions.passengerRoot = resourceLocator->getRoot(); agentOptions.defaultUser = testConfig["default_user"].asString(); agentOptions.defaultGroup = testConfig["default_group"].asString(); root = resourceLocator->getRoot(); rackAppPath = root + "/test/stub/rack"; wsgiAppPath = root + "/test/stub/wsgi"; defaultHeaders["PASSENGER_LOAD_SHELL_ENVVARS"] = "false"; defaultHeaders["PASSENGER_APP_TYPE"] = "wsgi"; defaultHeaders["PASSENGER_SPAWN_METHOD"] = "direct"; defaultHeaders["REQUEST_METHOD"] = "GET"; } ~RequestHandlerTest() { setLogLevel(DEFAULT_LOG_LEVEL); unlink(serverFilename.c_str()); handler.reset(); pool->destroy(); pool.reset(); } void init() { handler = make_shared(bg.safe, requestSocket, pool, agentOptions); bg.start(); } FileDescriptor &connect() { connection = connectToUnixServer(serverFilename); return connection; } void sendHeaders(const map &headers, ...) { va_list ap; const char *arg; map::const_iterator it; vector args; for (it = headers.begin(); it != headers.end(); it++) { args.push_back(StaticString(it->first.data(), it->first.size() + 1)); args.push_back(StaticString(it->second.data(), it->second.size() + 1)); } va_start(ap, headers); while ((arg = va_arg(ap, const char *)) != NULL) { args.push_back(StaticString(arg, strlen(arg) + 1)); } va_end(ap); shared_array args_array(new StaticString[args.size() + 2]); unsigned int totalSize = 0; for (unsigned int i = 0; i < args.size(); i++) { args_array[i + 1] = args[i]; totalSize += args[i].size(); } char totalSizeString[10]; snprintf(totalSizeString, sizeof(totalSizeString), "%u:", totalSize); args_array[0] = StaticString(totalSizeString); args_array[args.size() + 1] = ","; gatheredWrite(connection, args_array.get(), args.size() + 2, NULL); } string stripHeaders(const string &str) { string::size_type pos = str.find("\r\n\r\n"); if (pos == string::npos) { return str; } else { string result = str; result.erase(0, pos + 4); return result; } } string inspect() { string result; bg.safe->runSync(boost::bind(&RequestHandlerTest::real_inspect, this, &result)); return result; } void real_inspect(string *result) { stringstream stream; handler->inspect(stream); *result = stream.str(); } static void writeBody(FileDescriptor conn, string body) { try { writeExact(conn, body); } catch (const SystemException &e) { if (e.code() == EPIPE) { // Ignore. } else { throw; } } } }; DEFINE_TEST_GROUP(RequestHandlerTest); TEST_METHOD(1) { // Test one normal request. init(); connect(); sendHeaders(defaultHeaders, "PASSENGER_APP_ROOT", wsgiAppPath.c_str(), "PATH_INFO", "/", NULL); string response = readAll(connection); string body = stripHeaders(response); ensure("Status line is correct", containsSubstring(response, "HTTP/1.1 200 OK\r\n")); ensure("Headers are correct", containsSubstring(response, "Content-Type: text/html\r\n")); ensure("Contains a Status header", containsSubstring(response, "Status: 200 OK\r\n")); ensure_equals(body, "hello world"); } TEST_METHOD(2) { // Test multiple normal requests. init(); for (int i = 0; i < 10; i++) { connect(); sendHeaders(defaultHeaders, "PASSENGER_APP_ROOT", wsgiAppPath.c_str(), "PATH_INFO", "/", NULL); string response = readAll(connection); string body = stripHeaders(response); ensure("Status line is correct", containsSubstring(response, "HTTP/1.1 200 OK\r\n")); ensure("Headers are correct", containsSubstring(response, "Content-Type: text/html\r\n")); ensure("Contains a Status header", containsSubstring(response, "Status: 200 OK\r\n")); ensure_equals(body, "hello world"); } } TEST_METHOD(3) { // Test sending request data in pieces. defaultHeaders["PASSENGER_APP_ROOT"] = wsgiAppPath; defaultHeaders["PATH_INFO"] = "/"; string request; map::const_iterator it, end = defaultHeaders.end(); for (it = defaultHeaders.begin(); it != end; it++) { request.append(it->first); request.append(1, '\0'); request.append(it->second); request.append(1, '\0'); } request = toString(request.size()) + ":" + request; request.append(","); init(); connect(); string::size_type i = 0; while (i < request.size()) { const string piece = const_cast(request).substr(i, 5); writeExact(connection, piece); usleep(10000); i += piece.size(); } string response = readAll(connection); string body = stripHeaders(response); ensure("Status line is correct", containsSubstring(response, "HTTP/1.1 200 OK\r\n")); ensure("Headers are correct", containsSubstring(response, "Content-Type: text/html\r\n")); ensure("Contains a Status header", containsSubstring(response, "Status: 200 OK\r\n")); ensure_equals(body, "hello world"); } TEST_METHOD(4) { // It denies access if the connect password is wrong. agentOptions.requestSocketPassword = ""; setLogLevel(-1); init(); connect(); writeExact(connection, "hello world"); sendHeaders(defaultHeaders, "PASSENGER_APP_ROOT", wsgiAppPath.c_str(), "PATH_INFO", "/", NULL ); ensure(containsSubstring(readAll(connection), "hello world")); connect(); try { sendHeaders(defaultHeaders, "PASSENGER_APP_ROOT", wsgiAppPath.c_str(), "PATH_INFO", "/", NULL ); } catch (const SystemException &e) { ensure_equals(e.code(), EPIPE); return; } string response; try { response = readAll(connection); } catch (const SystemException &e) { ensure_equals(e.code(), ECONNRESET); return; } ensure_equals(response, ""); } TEST_METHOD(5) { // It disconnects us if the connect password is not sent within a certain time. agentOptions.requestSocketPassword = ""; setLogLevel(-1); handler = make_shared(bg.safe, requestSocket, pool, agentOptions); handler->connectPasswordTimeout = 40; bg.start(); connect(); Timer timer; readAll(connection); timer.stop(); ensure(timer.elapsed() <= 60); } TEST_METHOD(6) { // It works correct if the connect password is sent in pieces. agentOptions.requestSocketPassword = ""; init(); connect(); writeExact(connection, "hello"); usleep(10000); writeExact(connection, " world"); usleep(10000); sendHeaders(defaultHeaders, "PASSENGER_APP_ROOT", wsgiAppPath.c_str(), "PATH_INFO", "/", NULL ); ensure(containsSubstring(readAll(connection), "hello world")); } TEST_METHOD(7) { // It closes the connection with the application if the client has closed the connection. init(); connect(); sendHeaders(defaultHeaders, "PASSENGER_APP_ROOT", wsgiAppPath.c_str(), "PATH_INFO", "/stream", NULL ); BufferedIO io(connection); ensure_equals(io.readLine(), "HTTP/1.1 200 OK\r\n"); ProcessPtr process; { LockGuard l(pool->syncher); ensure_equals(pool->getProcessCount(false), 1u); SuperGroupPtr superGroup = pool->superGroups.get(wsgiAppPath); process = superGroup->defaultGroup->enabledProcesses.front(); ensure_equals(process->sessions, 1); } connection.close(); EVENTUALLY(5, LockGuard l(pool->syncher); result = process->sessions == 0; ); } TEST_METHOD(10) { // If the app crashes at startup without an error page then it renders // a generic error page. TempDir tempdir("tmp.handler"); writeFile("tmp.handler/start.rb", "STDERR.puts 'I have failed'"); setLogLevel(-2); spawnerFactory->getConfig()->forwardStderr = false; init(); connect(); sendHeaders(defaultHeaders, "PASSENGER_APP_ROOT", (root + "/test/tmp.handler").c_str(), "PASSENGER_APP_TYPE", "", "PASSENGER_START_COMMAND", ("ruby\1" + root + "/test/tmp.handler/start.rb").c_str(), "PATH_INFO", "/", NULL); string response = readAll(connection); ensure(containsSubstring(response, "HTTP/1.1 500 Internal Server Error\r\n")); ensure(containsSubstring(response, "Status: 500 Internal Server Error\r\n")); ensure(containsSubstring(response, "I have failed")); } TEST_METHOD(11) { // If the app crashes at startup with an error page then it renders // a friendly error page. TempDir tempdir("tmp.handler"); writeFile("tmp.handler/start.rb", "STDERR.puts 'Error'\n" "STDERR.puts\n" "STDERR.puts 'I have failed'\n"); setLogLevel(-2); spawnerFactory->getConfig()->forwardStderr = false; init(); connect(); sendHeaders(defaultHeaders, "PASSENGER_APP_ROOT", (root + "/test/tmp.handler").c_str(), "PASSENGER_APP_TYPE", "", "PASSENGER_START_COMMAND", ("ruby\1" + root + "/test/tmp.handler/start.rb").c_str(), "PATH_INFO", "/", NULL); string response = readAll(connection); ensure(containsSubstring(response, "HTTP/1.1 500 Internal Server Error\r\n")); ensure(containsSubstring(response, "Status: 500 Internal Server Error\r\n")); ensure(containsSubstring(response, "Content-Type: text/html; charset=UTF-8\r\n")); ensure(containsSubstring(response, "")); ensure(containsSubstring(response, "I have failed")); } TEST_METHOD(12) { // If spawning fails because of an internal error then it reports the error appropriately. TempDir tempdir("tmp.handler"); writeFile("tmp.handler/start.rb", ""); setLogLevel(-2); spawnerFactory->getConfig()->forwardStderr = false; init(); connect(); sendHeaders(defaultHeaders, "PASSENGER_APP_ROOT", (root + "/test/tmp.handler").c_str(), "PASSENGER_APP_TYPE", "", "PASSENGER_START_COMMAND", ("ruby\1" + root + "/test/tmp.handler/start.rb").c_str(), "PASSENGER_RAISE_INTERNAL_ERROR", "true", "PATH_INFO", "/", NULL); string response = readAll(connection); ensure(containsSubstring(response, "HTTP/1.1 500 Internal Server Error\r\n")); ensure(containsSubstring(response, "Status: 500 Internal Server Error\r\n")); ensure(containsSubstring(response, "Content-Type: text/html; charset=UTF-8\r\n")); ensure(containsSubstring(response, "")); ensure(containsSubstring(response, "An internal error occurred while trying to spawn the application.")); ensure(containsSubstring(response, "Passenger::RuntimeException")); ensure(containsSubstring(response, "An internal error!")); ensure(containsSubstring(response, "Spawner.h")); } TEST_METHOD(13) { // Error pages respect the PASSENGER_STATUS_LINE option. TempDir tempdir("tmp.handler"); writeFile("tmp.handler/start.rb", "STDERR.puts 'I have failed'"); setLogLevel(-2); spawnerFactory->getConfig()->forwardStderr = false; init(); connect(); sendHeaders(defaultHeaders, "PASSENGER_APP_ROOT", (root + "/test/tmp.handler").c_str(), "PASSENGER_APP_TYPE", "", "PASSENGER_START_COMMAND", ("ruby\1" + root + "/test/tmp.handler/start.rb").c_str(), "PASSENGER_STATUS_LINE", "false", "PATH_INFO", "/", NULL); string response = readAll(connection); ensure(!containsSubstring(response, "HTTP/1.1 ")); ensure(containsSubstring(response, "Status: 500 Internal Server Error\r\n")); ensure(containsSubstring(response, "I have failed")); } TEST_METHOD(14) { // If PASSENGER_FRIENDLY_ERROR_PAGES is false then it does not render // a friendly error page. TempDir tempdir("tmp.handler"); writeFile("tmp.handler/start.rb", "STDERR.puts 'Error'\n" "STDERR.puts\n" "STDERR.puts 'I have failed'\n"); setLogLevel(-2); spawnerFactory->getConfig()->forwardStderr = false; init(); connect(); sendHeaders(defaultHeaders, "PASSENGER_APP_ROOT", (root + "/test/tmp.handler").c_str(), "PASSENGER_APP_TYPE", "", "PASSENGER_START_COMMAND", ("ruby\1" + root + "/test/tmp.handler/start.rb").c_str(), "PASSENGER_FRIENDLY_ERROR_PAGES", "false", "PATH_INFO", "/", NULL); string response = readAll(connection); ensure(containsSubstring(response, "HTTP/1.1 500 Internal Server Error\r\n")); ensure(containsSubstring(response, "Status: 500 Internal Server Error\r\n")); ensure(containsSubstring(response, "Content-Type: text/html; charset=UTF-8\r\n")); ensure(containsSubstring(response, "")); ensure(!containsSubstring(response, "I have failed")); ensure(containsSubstring(response, "We're sorry, but something went wrong")); } TEST_METHOD(20) { // It streams the request body to the application. DeleteFileEventually file("tmp.output"); init(); connect(); sendHeaders(defaultHeaders, "PASSENGER_APP_ROOT", wsgiAppPath.c_str(), "PATH_INFO", "/upload", "HTTP_X_OUTPUT", (root + "/test/tmp.output").c_str(), NULL); writeExact(connection, "hello\n"); EVENTUALLY(5, result = fileExists("tmp.output") && readAll("tmp.output") == "hello\n"; ); writeExact(connection, "world\n"); EVENTUALLY(3, result = readAll("tmp.output") == "hello\nworld\n"; ); shutdown(connection, SHUT_WR); ensure_equals(stripHeaders(readAll(connection)), "ok"); } TEST_METHOD(21) { // It buffers the request body if PASSENGER_BUFFERING is true. DeleteFileEventually file("tmp.output"); init(); connect(); sendHeaders(defaultHeaders, "PASSENGER_APP_ROOT", wsgiAppPath.c_str(), "PASSENGER_BUFFERING", "true", "PATH_INFO", "/upload", "HTTP_X_OUTPUT", (root + "/test/tmp.output").c_str(), NULL); writeExact(connection, "hello\n"); SHOULD_NEVER_HAPPEN(200, result = fileExists("tmp.output"); ); writeExact(connection, "world\n"); SHOULD_NEVER_HAPPEN(200, result = fileExists("tmp.output"); ); shutdown(connection, SHUT_WR); ensure_equals(stripHeaders(readAll(connection)), "ok"); } TEST_METHOD(22) { set_test_name("Test buffering of large request bodies that fit in neither the socket " "buffer nor the FileBackedPipe memory buffer, and that the application " "cannot read quickly enough."); DeleteFileEventually d1("/tmp/wait.txt"); DeleteFileEventually d2("/tmp/output.txt"); // 2.6 MB of request body. Guaranteed not to fit in any socket buffer. string requestBody; for (int i = 0; i < 204800; i++) { requestBody.append("hello world!\n"); } init(); connect(); sendHeaders(defaultHeaders, "PASSENGER_APP_ROOT", wsgiAppPath.c_str(), "PATH_INFO", "/upload", "PASSENGER_BUFFERING", "true", "HTTP_X_WAIT_FOR_FILE", "/tmp/wait.txt", "HTTP_X_OUTPUT", "/tmp/output.txt", NULL); // Should not block. writeExact(connection, requestBody); shutdown(connection, SHUT_WR); EVENTUALLY(5, result = containsSubstring(inspect(), "session initiated = true"); ); touchFile("/tmp/wait.txt"); string result = stripHeaders(readAll(connection)); ensure_equals(result, "ok"); struct stat buf; ensure(stat("/tmp/output.txt", &buf) == 0); ensure_equals(buf.st_size, (off_t) requestBody.size()); } TEST_METHOD(30) { // It replaces HTTP_CONTENT_LENGTH with CONTENT_LENGTH. init(); connect(); sendHeaders(defaultHeaders, "PASSENGER_APP_ROOT", wsgiAppPath.c_str(), "PATH_INFO", "/env", "HTTP_CONTENT_LENGTH", "5", NULL); writeExact(connection, "hello"); string response = readAll(connection); ensure(containsSubstring(response, "CONTENT_LENGTH = 5\n")); ensure(!containsSubstring(response, "HTTP_CONTENT_LENGTH")); } TEST_METHOD(31) { // It replaces HTTP_CONTENT_TYPE with CONTENT_TYPE. init(); connect(); sendHeaders(defaultHeaders, "PASSENGER_APP_ROOT", wsgiAppPath.c_str(), "PATH_INFO", "/env", "HTTP_CONTENT_TYPE", "application/json", NULL); string response = readAll(connection); ensure(containsSubstring(response, "CONTENT_TYPE = application/json\n")); ensure(!containsSubstring(response, "HTTP_CONTENT_TYPE")); } TEST_METHOD(35) { // The response doesn't contain an HTTP status line if PASSENGER_STATUS_LINE is false. init(); connect(); sendHeaders(defaultHeaders, "PASSENGER_APP_ROOT", wsgiAppPath.c_str(), "PASSENGER_STATUS_LINE", "false", "PATH_INFO", "/", NULL); string response = readAll(connection); ensure(!containsSubstring(response, "HTTP/1.1 ")); ensure(containsSubstring(response, "Status: 200 OK\r\n")); } TEST_METHOD(36) { // If the application outputs a status line without a reason phrase, // then a reason phrase is automatically appended. init(); connect(); sendHeaders(defaultHeaders, "PASSENGER_APP_ROOT", wsgiAppPath.c_str(), "PATH_INFO", "/custom_status", "HTTP_X_CUSTOM_STATUS", "201", NULL); string response = readAll(connection); ensure(containsSubstring(response, "HTTP/1.1 201 Created\r\n")); ensure(containsSubstring(response, "Status: 201 Created\r\n")); } TEST_METHOD(37) { // If the application outputs a status line with a custom reason phrase, // then that reason phrase is used. init(); connect(); sendHeaders(defaultHeaders, "PASSENGER_APP_ROOT", wsgiAppPath.c_str(), "PATH_INFO", "/custom_status", "HTTP_X_CUSTOM_STATUS", "201 Bunnies Jump", NULL); string response = readAll(connection); ensure(containsSubstring(response, "HTTP/1.1 201 Bunnies Jump\r\n")); ensure(containsSubstring(response, "Status: 201 Bunnies Jump\r\n")); } TEST_METHOD(38) { // If the application doesn't output a status line then it rejects the application response. // TODO } TEST_METHOD(39) { // Test handling of slow clients that can't receive response data fast enough (response buffering). init(); connect(); sendHeaders(defaultHeaders, "PASSENGER_APP_ROOT", wsgiAppPath.c_str(), "PATH_INFO", "/blob", "HTTP_X_SIZE", "10485760", NULL); EVENTUALLY(10, result = containsSubstring(inspect(), "appInput reachedEnd = true"); ); string result = stripHeaders(readAll(connection)); ensure_equals(result.size(), 10485760u); const char *data = result.data(); const char *end = result.data() + result.size(); while (data < end) { ensure_equals(*data, 'x'); data++; } } TEST_METHOD(40) { set_test_name("Test that RequestHandler does not read more than CONTENT_LENGTH bytes " "from the client body (when buffering is on and request body is large)."); DeleteFileEventually d("/tmp/output.txt"); // 2.6 MB of request body. Guaranteed not to fit in any socket buffer. string requestBody; for (int i = 0; i < 204800; i++) { requestBody.append("hello world!\n"); } init(); connect(); sendHeaders(defaultHeaders, "PASSENGER_APP_ROOT", wsgiAppPath.c_str(), "PATH_INFO", "/upload", "CONTENT_LENGTH", toString(requestBody.size()).c_str(), "PASSENGER_BUFFERING", "true", "HTTP_X_OUTPUT", "/tmp/output.txt", NULL); writeExact(connection, requestBody); string result = stripHeaders(readAll(connection)); ensure_equals(result, "ok"); struct stat buf; ensure(stat("/tmp/output.txt", &buf) == 0); ensure_equals(buf.st_size, (off_t) requestBody.size()); } TEST_METHOD(41) { set_test_name("Test that RequestHandler does not read more than CONTENT_LENGTH bytes " "from the client body (when buffering is on and request body is small)."); DeleteFileEventually d("/tmp/output.txt"); string requestBody = "hello world"; init(); connect(); sendHeaders(defaultHeaders, "PASSENGER_APP_ROOT", wsgiAppPath.c_str(), "PATH_INFO", "/upload", "CONTENT_LENGTH", toString(requestBody.size()).c_str(), "PASSENGER_BUFFERING", "true", "HTTP_X_OUTPUT", "/tmp/output.txt", NULL); writeExact(connection, requestBody); string result = stripHeaders(readAll(connection)); ensure_equals(result, "ok"); struct stat buf; ensure(stat("/tmp/output.txt", &buf) == 0); ensure_equals(buf.st_size, (off_t) requestBody.size()); } TEST_METHOD(42) { set_test_name("Test that RequestHandler does not read more than CONTENT_LENGTH bytes " "from the client body (when buffering is off and request body is large)."); DeleteFileEventually d("/tmp/output.txt"); // 2 MB of request body. Guaranteed not to fit in any socket buffer. string requestBody; for (int i = 0; i < 102400; i++) { char buf[100]; snprintf(buf, sizeof(buf), "%06d: hello world!\n", i); requestBody.append(buf); } init(); connect(); sendHeaders(defaultHeaders, "PASSENGER_APP_ROOT", wsgiAppPath.c_str(), "PATH_INFO", "/upload", "CONTENT_LENGTH", toString(requestBody.size()).c_str(), "HTTP_X_OUTPUT", "/tmp/output.txt", NULL); TempThread thr(boost::bind(RequestHandlerTest::writeBody, connection, requestBody)); string result = stripHeaders(readAll(connection)); ensure_equals(result, "ok"); struct stat buf; ensure(stat("/tmp/output.txt", &buf) == 0); ensure_equals(buf.st_size, (off_t) requestBody.size()); } TEST_METHOD(43) { set_test_name("Test that RequestHandler does not read more than CONTENT_LENGTH bytes " "from the client body (when buffering is off and request body is small)."); DeleteFileEventually d("/tmp/output.txt"); string requestBody = "hello world"; init(); connect(); sendHeaders(defaultHeaders, "PASSENGER_APP_ROOT", wsgiAppPath.c_str(), "PATH_INFO", "/upload", "CONTENT_LENGTH", toString(requestBody.size()).c_str(), "HTTP_X_OUTPUT", "/tmp/output.txt", NULL); TempThread thr(boost::bind(RequestHandlerTest::writeBody, connection, requestBody)); string result = stripHeaders(readAll(connection)); ensure_equals(result, "ok"); struct stat buf; ensure(stat("/tmp/output.txt", &buf) == 0); ensure_equals(buf.st_size, (off_t) requestBody.size()); } TEST_METHOD(44) { set_test_name("Test that RequestHandler does not pass any client body data when CONTENT_LENGTH == 0 (when buffering is on)."); DeleteFileEventually d("/tmp/output.txt"); init(); connect(); sendHeaders(defaultHeaders, "PASSENGER_APP_ROOT", wsgiAppPath.c_str(), "PATH_INFO", "/upload", "CONTENT_LENGTH", "0", "PASSENGER_BUFFERING", "true", "HTTP_X_OUTPUT", "/tmp/output.txt", NULL); writeExact(connection, "hello world"); string result = stripHeaders(readAll(connection)); ensure_equals(result, "ok"); struct stat buf; ensure(stat("/tmp/output.txt", &buf) == 0); ensure_equals(buf.st_size, (off_t) 0); } TEST_METHOD(45) { set_test_name("Test that RequestHandler does not pass any client body data when CONTENT_LENGTH == 0 (when buffering is off)."); DeleteFileEventually d("/tmp/output.txt"); init(); connect(); sendHeaders(defaultHeaders, "PASSENGER_APP_ROOT", wsgiAppPath.c_str(), "PATH_INFO", "/upload", "CONTENT_LENGTH", "0", "HTTP_X_OUTPUT", "/tmp/output.txt", NULL); writeExact(connection, "hello world"); string result = stripHeaders(readAll(connection)); ensure_equals(result, "ok"); struct stat buf; ensure(stat("/tmp/output.txt", &buf) == 0); ensure_equals(buf.st_size, (off_t) 0); } TEST_METHOD(46) { // If the application outputs a request oobw header, handler should remove the header, mark // the process as oobw requested. The process should continue to process requests until the // spawner spawns another process (to avoid the group being empty). As soon as the new // process is spawned, the original process will make the oobw request. Afterwards, the // original process is re-enabled. init(); connect(); sendHeaders(defaultHeaders, "PASSENGER_APP_ROOT", wsgiAppPath.c_str(), "PATH_INFO", "/oobw", NULL); string response = readAll(connection); ensure("status is not 200", containsSubstring(response, "Status: 200 OK\r\n")); ensure("contains oowb header", !containsSubstring(response, "X-Passenger-Request-OOB-Work:")); pid_t origPid = atoi(stripHeaders(response)); // Get a reference to the orignal process and verify oobw has been requested. ProcessPtr origProcess; { unique_lock lock(pool->syncher); origProcess = pool->superGroups.get(wsgiAppPath)->defaultGroup->disablingProcesses.front(); ensure(origProcess->oobwStatus == Process::OOBW_REQUESTED); } ensure("sanity check", origPid == origProcess->pid); // just a sanity check // Issue requests until the new process handles it. pid_t pid; EVENTUALLY(2, connect(); sendHeaders(defaultHeaders, "PASSENGER_APP_ROOT", wsgiAppPath.c_str(), "PATH_INFO", "/pid", NULL); string response = readAll(connection); ensure(containsSubstring(response, "Status: 200 OK\r\n")); pid = atoi(stripHeaders(response)); result = (pid != origPid); ); // Wait for the original process to finish oobw request. EVENTUALLY(2, unique_lock lock(pool->syncher); result = origProcess->oobwStatus == Process::OOBW_NOT_ACTIVE; ); // Final asserts. { unique_lock lock(pool->syncher); ensure_equals("2 enabled processes", pool->superGroups.get(wsgiAppPath)->defaultGroup->enabledProcesses.size(), 2u); ensure_equals("oobw is reset", origProcess->oobwStatus, Process::OOBW_NOT_ACTIVE); ensure_equals("process is enabled", origProcess->enabled, Process::ENABLED); } } TEST_METHOD(47) { set_test_name("The RequestHandler should append a Date header if the app doesn't output one."); init(); connect(); sendHeaders(defaultHeaders, "PASSENGER_APP_ROOT", wsgiAppPath.c_str(), "PATH_INFO", "/pid", NULL); string result = readAll(connection); ensure(result.find("Date: ") != string::npos); } // Test small response buffering. // Test large response buffering. } init/usermode-helper.cc1-10 // Copyright 2018 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // This program is run directly by the kernel for all programs the kernel runs. // See the CONFIG_STATIC_USERMODEHELPER setting. #include "init/usermode-helper.h" #include #include #include #include #include #include int main(int argc, const char* argv[]) { brillo::InitLog(brillo::kLogToSyslog | brillo::kLogToStderrIfTty); // When running locally for testing, argv[0] will be usermode-helper itself. // When the kernel invokes us, argv[0] will be set to the program it wants // us to run. So only shift argv when it makes sense. if (strcmp(basename(argv[0]), "usermode-helper") == 0) { // Allow users to run this directly and figure out what it is. It's not // uncommon for curious people to run it directly or pass --help. if (argc == 1 || strcmp(argv[1], "-h") == 0 || strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-help") == 0) { LOG(INFO) << "usermode-helper securely filters the programs the kernel " << "is allowed to run."; return 0; } --argc; ++argv; } if (argc < 1) LOG(FATAL) << "missing program to run"; // Validate the program and its arguments, and reject all others. if (!usermode_helper::ValidateProgramArgs(argc, argv)) { base::CommandLine cmdline(argc, argv); LOG(FATAL) << "program invocation not permitted: " << cmdline.GetCommandLineString(); } // We could use execveat(), but it's not a clear win. // Pros: // - We guarantee the program is in the rootfs (/) and people can't bind // mount over paths to confuse us. // - The kernel doesn't allow scripts (i.e. files with #! shebangs) to be // executed through execveat. Might be a bug? // - We could require all programs not be symlinked. // Cons: // - Some programs we permit are actually symlinks (e.g. modprobe is a // symlink to kmod). We have an image test that verifies all symlinks in // the rootfs are sane, so not exactly a win. // - Some standard programs use #! to redirect themselves (e.g. coreutils // uses it for all of its programs). Not clear that banning scripts when // we've already validated the argv is a win. // // So we stick with execv for now. execv(argv[0], const_cast(argv)); if (errno == ENOENT) { // If the exec failed because the program doesn't exist, we've already // checked that the invocation was OK above, so just exit silently here. // We use 127 to semi-mimic POSIX shell behavior which exits 127 when a // program is not found. return 127; } PLOG(FATAL) << "execing program failed: " << argv[0]; } Dominicsjc/CaesarDB1-10 // // Created by dominic on 11/20/19. // #include "dbInstance.h" dbInstance::dbInstance(const std::string &host, const std::string &user, const std::string &passwd, const std::string &db) { conn = mysql_init(nullptr); if (mysql_real_connect( conn, host.c_str(), user.c_str(), passwd.c_str(), db.c_str(), 0, NULL, CLIENT_MULTI_RESULTS) == nullptr) { std::cerr << "Connect to MySQL failed!" << std::endl; } proceduresInitial(); lowEnrollmentTriggerInitial(); } dbInstance::~dbInstance() { mysql_close(conn); conn = nullptr; } MYSQL_RES *dbInstance::retrievalQuery(const std::string &myQuery) { MYSQL_RES *res_set; const char *tmpQ = myQuery.c_str(); if(mysql_query(conn, tmpQ) != 0) return nullptr; else res_set = mysql_store_result(conn); return res_set; } bool dbInstance::alterQuery(const std::string &myQuery){ const char *tmpQ = myQuery.c_str(); return mysql_query(conn, tmpQ) == 0; } void dbInstance::proceduresInitial() { enrollInitial(); withdrawInitial(); changePasswdInitial(); changeAddressInitial(); } void dbInstance::enrollInitial() { if(!this->alterQuery("DROP PROCEDURE IF EXISTS enrollProcedure;")){ std::cerr << "Sometime wrong in the enrollProcedure drop." << std::endl; return; } std::string procedureQuery = "CREATE PROCEDURE enrollProcedure (IN id int(11), IN c char(20), IN s char(2), IN y int(11), IN d date, OUT status_code tinyint(1))\n" "BEGIN\n" "\tDECLARE pre_c char(8);\n" " DECLARE pre_req tinyint(1) DEFAULT 1;\n" " DECLARE done tinyint(1) DEFAULT 0;\n" " DECLARE c CURSOR FOR (SELECT PrereqUoSCode FROM requires WHERE UoSCode = c AND d > EnforcedSince);\n" " DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET done = 1;\n" " DECLARE EXIT HANDLER FOR SQLEXCEPTION\n" " BEGIN\n" " -- error\n" " SET status_code = 1;\n" " ROLLBACK;\n" " END;\n" "\n" " DECLARE EXIT HANDLER FOR SQLWARNING\n" " BEGIN\n" " -- warning\n" " SET status_code = 2;\n" " ROLLBACK;\n" " END;\n" " START TRANSACTION;\n" "\t\t-- Unknow terminate\n" "\t\tSET status_code = 7;\n" " IF EXISTS ( SELECT * FROM transcript WHERE StudId = id AND UoSCode = c AND Semester = s AND Year = y) THEN\n" "\t\t\t-- Already enrolled\n" " SET status_code = 3;\n" "\t\tELSEIF NOT EXISTS ( SELECT * FROM uosoffering WHERE UoSCode = c AND Semester = s AND Year = y ) THEN\n" " -- invalid course\n" " SET status_code = 4;\n" " ELSEIF EXISTS ( SELECT * FROM uosoffering WHERE UoSCode = c AND Semester = s AND year = y ) AND NOT EXISTS ( SELECT * FROM uosoffering WHERE UoSCode = c AND Semester = s AND year = y AND Enrollment < MaxEnrollment ) THEN\n" " -- Already full\n" " SET status_code = 5;\n" " ELSE\n" " OPEN c;\n" " requireLoop: LOOP\n" "\t\t\t\tFETCH c INTO pre_c;\n" " IF done = 1 THEN LEAVE requireLoop; END IF;\n" " IF NOT EXISTS (SELECT * FROM transcript WHERE StudId = id AND UoSCode = pre_c AND Grade is NOT NULL AND Grade IN ('D', 'P', 'CR')) THEN\n" " -- Prerequistes not be cleared\n" "\t\t\t\t\tSET status_code = 6;\n" " SET pre_req = 0;\n" "\t\t\t\tEND IF;\n" " END LOOP;\n" " CLOSE c;\n" " IF pre_req = 0 THEN\n" " DROP TEMPORARY TABLE IF EXISTS tmp;\n" "\t\t\t\tCREATE TEMPORARY TABLE tmp SELECT PrereqUoSCode FROM requires WHERE UoSCode = c AND d > EnforcedSince;\n" "\t\t\tELSE\n" " INSERT INTO transcript VALUES (id, c, s, y, NULL);\n" " UPDATE uosoffering SET Enrollment = Enrollment + 1 WHERE UoSCode = c AND Semester = s AND Year = y;\n" " SET status_code = 0;\n" "\t\t\tEND IF;\n" " END IF;\n" " COMMIT;\n" "\n" "END"; if(!this->alterQuery(procedureQuery)) { std::cerr << "Sometime wrong in the enrollProcedure create." << std::endl; return; } } void dbInstance::withdrawInitial() { if(!this->alterQuery("DROP PROCEDURE IF EXISTS withdrawProcedure;")){ std::cerr << "Sometime wrong in the withdrawProcedure drop." << std::endl; return; } std::string procedureQuery = "CREATE PROCEDURE withdrawProcedure(IN id int(11), IN c char(20), IN s char(2), IN y int(11), IN cs char(2), IN cy int (11), OUT status_code tinyint(1))\n" "BEGIN\n" "\tDECLARE EXIT HANDLER FOR SQLEXCEPTION\n" " BEGIN\n" " -- error\n" " SET status_code = 1;\n" " ROLLBACK;\n" " END;\n" "\n" " DECLARE EXIT HANDLER FOR SQLWARNING\n" " BEGIN\n" " -- warning\n" " SET status_code = 2;\n" " ROLLBACK;\n" " END;\n" " START TRANSACTION;\n" "\t\tIF y < cy OR (y = cy AND s <> cs) OR NOT EXISTS ( SELECT * FROM transcript WHERE StudId = id AND UoSCode = c AND Semester = s AND Year = y AND Grade IS NULL ) THEN\n" "\t\t\t-- invalid course\n" " SET status_code = 3;\n" "\t\tELSE\n" "\t\t\tDELETE FROM transcript WHERE StudId = id AND UoSCode = c AND Semester = s AND Year = y;\n" " UPDATE uosoffering SET Enrollment = Enrollment -1 WHERE UoSCode = c AND Semester = s AND Year = y;\n" " -- success\n" " SET status_code = 0;\n" " END IF;\n" " COMMIT;\n" "END"; if(!this->alterQuery(procedureQuery)) { std::cerr << "Sometime wrong in the withdrawProcedure create." << std::endl; return; } } void dbInstance::changePasswdInitial() { if(!this->alterQuery("DROP PROCEDURE IF EXISTS changePasswdProcedure;")){ std::cerr << "Sometime wrong in the changePasswdProcedure drop." << std::endl; return; } std::string procedureQuery = "CREATE PROCEDURE changePasswdProcedure(IN i int(11), IN p varchar(10), OUT status_code tinyint(1))\n" "BEGIN\n" "\tDECLARE EXIT HANDLER FOR SQLEXCEPTION\n" " BEGIN\n" " -- error\n" " SET status_code = 1;\n" " ROLLBACK;\n" " END;\n" "\n" " DECLARE EXIT HANDLER FOR SQLWARNING\n" " BEGIN\n" " -- warning\n" " SET status_code = 2;\n" " ROLLBACK;\n" " END;\n" " START TRANSACTION;\n" "\t\tIF NOT EXISTS ( SELECT * FROM student WHERE Id = i ) THEN\n" "\t\t\t-- wrong id\n" "\t\t\tSET status_code = 3;\n" "\t\tELSE\n" "\t\t\tUPDATE student SET Password = p WHERE Id = i;\n" " SET status_code = 0;\n" "\t\tEND IF;\n" " COMMIT;\n" "END"; if(!this->alterQuery(procedureQuery)) { std::cerr << "Sometime wrong in the changePasswdProcedure create." << std::endl; return; } } void dbInstance::changeAddressInitial() { if(!this->alterQuery("DROP PROCEDURE IF EXISTS changeAddressProcedure;")){ std::cerr << "Sometime wrong in the changeAddressProcedure drop." << std::endl; return; } std::string procedureQuery = "CREATE PROCEDURE changeAddressProcedure(IN i int(11), IN a varchar(50), OUT status_code tinyint(1))\n" "BEGIN\n" "\tDECLARE EXIT HANDLER FOR SQLEXCEPTION\n" " BEGIN\n" " -- error\n" " SET status_code = 1;\n" " ROLLBACK;\n" " END;\n" "\n" " DECLARE EXIT HANDLER FOR SQLWARNING\n" " BEGIN\n" " -- warning\n" " SET status_code = 2;\n" " ROLLBACK;\n" " END;\n" " START TRANSACTION;\n" "\t\tIF NOT EXISTS ( SELECT * FROM student WHERE Id = i ) THEN\n" "\t\t\t-- wrong id\n" "\t\t\tSET status_code = 3;\n" "\t\tELSE\n" "\t\t\tUPDATE student SET Address = a WHERE Id = i;\n" " SET status_code = 0;\n" "\t\tEND IF;\n" " COMMIT;\n" "END"; if(!this->alterQuery(procedureQuery)) { std::cerr << "Sometime wrong in the changeAddressProcedure create." << std::endl; return; } } void dbInstance::lowEnrollmentTriggerInitial() { if(!this->alterQuery("DROP TRIGGER IF EXISTS lowEnrollmentTrigger;")){ std::cerr << "Sometime wrong in the lowEnrollmentTrigger drop." << std::endl; return; } std::string triggerQuery = "CREATE TRIGGER lowEnrollmentTrigger AFTER UPDATE ON uosoffering\n" "\tFOR EACH ROW\n" " BEGIN\n" "\t\tSET @low = 0;\n" " IF NEW.Enrollment < NEW.MaxEnrollment / 2 THEN\n" "\t\t\tSET @low = 1;\n" "\t\tEND IF;\n" " END"; if(!this->alterQuery(triggerQuery)){ std::cerr << "Sometime wrong in the lowEnrollmentTrigger create." << std::endl; return; } }#include "DeityDecisionConstants.hpp" #include "DeityTextKeys.hpp" #include "Game.hpp" #include "RemoveStatusEffect.hpp" #include "RestoreStatusDeityDecisionStrategyHandler.hpp" #include "StatusTypes.hpp" using namespace std; RestoreStatusDeityDecisionStrategyHandler::RestoreStatusDeityDecisionStrategyHandler(const string& new_deity_id) : DeityDecisionStrategyHandler(new_deity_id), piety_loss(0) { initialize_watched_statuses(); } // Set the list of statuses that will be used to determine if the deity will // restore the player. void RestoreStatusDeityDecisionStrategyHandler::initialize_watched_statuses() { watched_statuses.clear(); const int statusSize = 11; const string statuses[] = {StatusIdentifiers::STATUS_ID_BLINDED, StatusIdentifiers::STATUS_ID_BLOODIED, StatusIdentifiers::STATUS_ID_DISFIGURED, StatusIdentifiers::STATUS_ID_EXPOSED, StatusIdentifiers::STATUS_ID_MUTE, StatusIdentifiers::STATUS_ID_PARALYSIS, StatusIdentifiers::STATUS_ID_POISON, StatusIdentifiers::STATUS_ID_SLOWNESS, StatusIdentifiers::STATUS_ID_SPELLBOUND, StatusIdentifiers::STATUS_ID_STONE, StatusIdentifiers::STATUS_ID_STUNNED}; vector array_vec(&statuses[0], &statuses[statusSize]); watched_statuses.insert(watched_statuses.end(), array_vec.begin(), array_vec.end()); } // Restore status if at least one watched status is present. bool RestoreStatusDeityDecisionStrategyHandler::decide(CreaturePtr creature) { if (creature) { for (const string& status : watched_statuses) { if (creature->has_status(status)) { return true; } } } return false; } DeityDecisionImplications RestoreStatusDeityDecisionStrategyHandler::handle_decision(CreaturePtr creature, TilePtr tile) { // Always reset the piety cost. piety_loss = 0; if (creature) { Game& game = Game::instance(); ActionManager& am = game.get_action_manager_ref(); MapPtr current_map = game.get_current_map(); if (current_map != nullptr) { Coordinate affected_coord = current_map->get_location(creature->get_id()); TilePtr affected_tile = current_map->at(affected_coord); // The piety loss for the first status. The piety loss for each subsequent // status is half of the previous. int current_piety_loss = 200; for (const string& status : watched_statuses) { if (creature->has_status(status)) { // Remove the status using the standard methods to ensure that for more // complex statuses, like slowness, things are restored properly. RemoveStatusEffect deity_decision(status); deity_decision.effect(creature, &am, ItemStatus::ITEM_STATUS_UNCURSED, affected_coord, affected_tile); piety_loss += current_piety_loss; current_piety_loss /= 2; } } } } return get_deity_decision_implications(creature, tile); } // Piety loss is based on the number of statuses that were lifted by // the prayer. int RestoreStatusDeityDecisionStrategyHandler::get_piety_loss() const { return piety_loss; } string RestoreStatusDeityDecisionStrategyHandler::get_message_sid() const { return DeityTextKeys::PRAYER_RESTORE_STATUS; } 10-100 #include "fetcher.h" #include "interpolate.h" #include "logger.h" #include "plugin_factory.h" #include "statistics.h" #include "util.h" #include #include #include #include #include "cache.h" #include "csv.h" #include "geotiff.h" #include "grib.h" #include "param.h" #include "querydata.h" #include "radon.h" using namespace himan; using namespace himan::plugin; using namespace std; // A flag to guard that we read auxiliary files only once static once_flag oflag; string GetOtherVectorComponentName(const string& name); // If multiple plugins are executed using auxiliary files, prevent // each plugin execution from re-reading the aux files to memory. static std::atomic auxiliaryFilesRead(false); namespace { // Sticky param cache will store the producer that provided data. // With this information we can skip the regular producer loop cycle // (try prod 1, data not found, try prod 2) which will improve fetching // times when reading from database. std::string UniqueName(const himan::producer& prod, const himan::param& par, const himan::level& lev) { return fmt::format("{}_{}_{}", prod.Id(), par.Name(), lev.Type()); } void AmendParamWithAggregationAndProcessingType(param& p, const forecast_time& ftime) { if (p.ProcessingType().Type() == kUnknownProcessingType) { p.ProcessingType(util::GetProcessingTypeFromParamName(p.Name())); } if (p.Aggregation().Type() == kUnknownAggregationType && p.ProcessingType().Type() != kEnsembleMean) { p.Aggregation(util::GetAggregationFromParamName(p.Name(), ftime)); } } } static vector stickyParamCache; static mutex stickyMutex; // Container to store shared mutexes for data fetch for a single grid. // The idea is that if multiple threads fetch the *same* data, they // will be synchronized so that one thread fetches the data and updates // cache while the other threads will wait for the completion of that task. static mutex singleFetcherMutex; map singleFetcherMap; string CreateNotFoundString(const vector& prods, const forecast_type& ftype, const forecast_time& time, const level& lev, const vector& params) { vector prodIds; for_each(prods.begin(), prods.end(), [&prodIds](const producer& prod) { prodIds.push_back(prod.Id()); }); vector paramNames; for_each(params.begin(), params.end(), [¶mNames](const param& par) { paramNames.push_back(par.Name()); }); return fmt::format( "No valid data found for producer(s): {}, origintime: {}, step: {}, param(s): {}, level: {}, forecast_type: {}", fmt::join(prodIds, ","), time.OriginDateTime().ToSQLTime(), static_cast(time.Step()), fmt::join(paramNames, ","), static_cast(lev), static_cast(ftype)); } namespace { template shared_ptr> ConvertTo(shared_ptr> in) { return make_shared>(*in); } template <> shared_ptr> ConvertTo(shared_ptr> in) { return in; } /* template shared_ptr> ConvertTo(shared_ptr>&); template <> shared_ptr> ConvertTo(shared_ptr>& anInfo) { return anInfo; } template <> shared_ptr> ConvertTo(shared_ptr>& anInfo) { return make_shared>(*anInfo); } */ } // namespace fetcher::fetcher() : itsDoLevelTransform(true), itsDoInterpolation(true), itsDoVectorComponentRotation(false), itsUseCache(true), itsApplyLandSeaMask(false), itsLandSeaMaskThreshold(0.5) { itsLogger = logger("fetcher"); } shared_ptr> fetcher::Fetch(shared_ptr config, forecast_time requestedTime, level requestedLevel, const params& requestedParams, forecast_type requestedType, bool readPackedData) { return Fetch(config, requestedTime, requestedLevel, requestedParams, requestedType, readPackedData); } template shared_ptr> fetcher::Fetch(shared_ptr config, forecast_time requestedTime, level requestedLevel, const params& requestedParams, forecast_type requestedType, bool readPackedData) { shared_ptr> ret; for (size_t i = 0; i < requestedParams.size(); i++) { try { return Fetch(config, requestedTime, requestedLevel, requestedParams[i], requestedType, readPackedData, true); } catch (const HPExceptionType& e) { if (e != kFileDataNotFound) { throw; } } } itsLogger.Warning( CreateNotFoundString(config->SourceProducers(), requestedType, requestedTime, requestedLevel, requestedParams)); throw kFileDataNotFound; } template shared_ptr> fetcher::Fetch(shared_ptr, forecast_time, level, const params&, forecast_type, bool); template shared_ptr> fetcher::Fetch(shared_ptr, forecast_time, level, const params&, forecast_type, bool); template shared_ptr> fetcher::Fetch(shared_ptr, forecast_time, level, const params&, forecast_type, bool); template shared_ptr> fetcher::Fetch(shared_ptr, forecast_time, level, const params&, forecast_type, bool); shared_ptr> fetcher::Fetch(shared_ptr config, forecast_time requestedTime, level requestedLevel, param requestedParam, forecast_type requestedType, bool readPackedData, bool suppressLogging) { return Fetch(config, requestedTime, requestedLevel, requestedParam, requestedType, readPackedData, suppressLogging); } template shared_ptr> fetcher::Fetch(shared_ptr config, forecast_time requestedTime, level requestedLevel, param requestedParam, forecast_type requestedType, bool readPackedData, bool suppressLogging) { timer t(true); AmendParamWithAggregationAndProcessingType(requestedParam, requestedTime); // Check sticky param cache first shared_ptr> ret; for (const auto& prod : config->SourceProducers()) { bool found = false; { const auto uName = UniqueName(prod, requestedParam, requestedLevel); lock_guard lock(stickyMutex); // Linear search, size of stickyParamCache should be relatively small if (find(stickyParamCache.begin(), stickyParamCache.end(), uName) != stickyParamCache.end()) { // oh,goody found = true; } } if (found) { search_options opts(requestedTime, requestedParam, requestedLevel, prod, requestedType, config); ret = FetchFromProducer(opts, readPackedData, suppressLogging); if (ret) { break; } } } if (!ret) { // first time fetch (not in sticky cache) for (const auto& prod : config->SourceProducers()) { search_options opts(requestedTime, requestedParam, requestedLevel, prod, requestedType, config); ret = FetchFromProducer(opts, readPackedData, suppressLogging); if (ret) { const auto uName = UniqueName(prod, requestedParam, requestedLevel); lock_guard lock(stickyMutex); if (find(stickyParamCache.begin(), stickyParamCache.end(), uName) == stickyParamCache.end()) { itsLogger.Trace("Updating sticky param cache: " + UniqueName(opts.prod, opts.param, opts.level)); stickyParamCache.push_back(uName); } break; } } } if (config->StatisticsEnabled()) { t.Stop(); config->Statistics()->AddToFetchingTime(t.GetTime()); } if (!ret) { if (!suppressLogging) { itsLogger.Warning(CreateNotFoundString(config->SourceProducers(), requestedType, requestedTime, requestedLevel, {requestedParam})); } throw kFileDataNotFound; } return ret; } template shared_ptr> fetcher::Fetch(shared_ptr, forecast_time, level, param, forecast_type, bool, bool); template shared_ptr> fetcher::Fetch(shared_ptr, forecast_time, level, param, forecast_type, bool, bool); template shared_ptr> fetcher::Fetch(shared_ptr, forecast_time, level, param, forecast_type, bool, bool); template shared_ptr> fetcher::Fetch(shared_ptr, forecast_time, level, param, forecast_type, bool, bool); template shared_ptr> fetcher::FetchFromProducerSingle(search_options& opts, bool readPackedData, bool suppressLogging) { level newLevel = opts.level; if (itsDoLevelTransform && opts.configuration->DatabaseType() != kNoDatabase && (opts.level.Type() != kHybrid && opts.level.Type() != kPressure && opts.level.Type() != kHeightLayer)) { newLevel = LevelTransform(opts.configuration, opts.prod, opts.param, opts.level); if (newLevel != opts.level || newLevel.Value() != opts.level.Value()) { itsLogger.Trace(fmt::format("Transform level {} to {} for producer {}, param {}", static_cast(opts.level), static_cast(newLevel), opts.prod.Id(), opts.param.Name())); opts.level = newLevel; } } auto ret = FetchFromAllSources(opts, readPackedData); auto theInfos = ret.second; if (theInfos.empty()) { return shared_ptr>(); } else if (ret.first == HPDataFoundFrom::kCache) { return theInfos[0]; } RotateVectorComponents(theInfos, opts.configuration->BaseGrid(), opts.configuration, opts.prod); if (itsDoInterpolation) { if (!interpolate::Interpolate(opts.configuration->BaseGrid(), theInfos)) { // interpolation failed throw kFileDataNotFound; } } else { itsLogger.Trace("Interpolation disabled"); } if (itsApplyLandSeaMask) { if (!ApplyLandSeaMask(opts.configuration, theInfos[0], opts.time, opts.ftype)) { itsLogger.Warning("Land sea mask apply failed"); } } /* * Insert interpolated data to cache if * 1. Cache is not disabled locally (itsUseCache) AND * 2. Cache is not disabled globally (config->UseCache()) AND * 3. Data is not packed */ if (ret.first != HPDataFoundFrom::kCache && itsUseCache && opts.configuration->UseCacheForReads() && !theInfos[0]->PackedData()->HasData()) { auto c = GET_PLUGIN(cache); c->Insert(theInfos[0]); } ASSERT((theInfos[0]->Time()) == opts.time); ASSERT((theInfos[0]->Param()) == opts.param); return theInfos[0]; } template shared_ptr> fetcher::FetchFromProducerSingle(search_options&, bool, bool); template shared_ptr> fetcher::FetchFromProducerSingle(search_options&, bool, bool); template shared_ptr> fetcher::FetchFromProducerSingle(search_options&, bool, bool); template shared_ptr> fetcher::FetchFromProducerSingle(search_options&, bool, bool); template shared_ptr> fetcher::FetchFromProducer(search_options& opts, bool readPackedData, bool suppressLogging) { // When reading packed data, data is not pushed to cache because it's only unpacked // later. Therefore there is no reason to synchronize thread access. // TODO: *should* data be unpacked and pushed to cache (it's done so anyway later)? if (readPackedData) { return FetchFromProducerSingle(opts, readPackedData, suppressLogging); } const auto uname = util::UniqueName(opts); pair::iterator, bool> muret; // First acquire mutex to (possibly) modify map unique_lock sflock(singleFetcherMutex); muret = singleFetcherMap.emplace(piecewise_construct, forward_as_tuple(uname), forward_as_tuple()); if (muret.second == true) { // first time this data is being fetched: take exclusive lock to prevent // other threads from fetching the same data at the same time boost::unique_lock uniqueLock(muret.first->second); sflock.unlock(); return FetchFromProducerSingle(opts, readPackedData, suppressLogging); } sflock.unlock(); // this data is being fetched right now by other thread, or it has been fetched // earlier boost::shared_lock lock(muret.first->second); return FetchFromProducerSingle(opts, readPackedData, suppressLogging); } template shared_ptr> fetcher::FetchFromProducer(search_options&, bool, bool); template shared_ptr> fetcher::FetchFromProducer(search_options&, bool, bool); template shared_ptr> fetcher::FetchFromProducer(search_options&, bool, bool); template shared_ptr> fetcher::FetchFromProducer(search_options&, bool, bool); template vector>> fetcher::FromFile(const vector& files, search_options& options, bool readPackedData, bool readIfNotMatching) { vector>> allInfos; for (const auto& inputFile : files) { if (inputFile.storage_type == HPFileStorageType::kLocalFileSystem && !boost::filesystem::exists(inputFile.file_location)) { itsLogger.Error("Input file '" + inputFile.file_location + "' does not exist"); continue; } vector>> curInfos; switch (inputFile.file_type) { case kGRIB: case kGRIB1: case kGRIB2: { auto g = GET_PLUGIN(grib); curInfos = g->FromFile(inputFile, options, readPackedData, readIfNotMatching); break; } case kQueryData: throw runtime_error("QueryData as input is not supported"); case kNetCDF: throw runtime_error("NetCDF as input is not supported"); case kCSV: { auto c = GET_PLUGIN(csv); auto anInfo = c->FromFile(inputFile.file_location, options, readIfNotMatching); curInfos.push_back(anInfo); break; } case kGeoTIFF: { auto g = GET_PLUGIN(geotiff); curInfos = g->FromFile(inputFile, options); break; } default: // Unknown file type, cannot proceed throw runtime_error("Input file is neither GRIB, NetCDF, QueryData nor CSV"); break; } allInfos.insert(allInfos.end(), curInfos.begin(), curInfos.end()); } return allInfos; } template vector>> fetcher::FromCache(search_options& options) { auto c = GET_PLUGIN(cache); return c->GetInfo(options); } himan::level fetcher::LevelTransform(const shared_ptr& conf, const producer& sourceProducer, const param& targetParam, const level& targetLevel) const { level ret = targetLevel; HPDatabaseType dbtype = conf->DatabaseType(); if (ret == targetLevel && dbtype == kRadon) { auto r = GET_PLUGIN(radon); auto levelInfo = r->RadonDB().GetLevelFromDatabaseName(boost::to_upper_copy(HPLevelTypeToString.at(targetLevel.Type()))); if (levelInfo.empty()) { itsLogger.Warning("Level type '" + HPLevelTypeToString.at(targetLevel.Type()) + "' not found from radon"); return ret; } auto paramInfo = r->RadonDB().GetParameterFromDatabaseName(sourceProducer.Id(), targetParam.Name(), stoi(levelInfo["id"]), targetLevel.Value()); if (paramInfo.empty()) { itsLogger.Trace("Level transform failed: no parameter information for param " + targetParam.Name()); return ret; } auto levelXrefInfo = r->RadonDB().GetLevelTransform(sourceProducer.Id(), stoi(paramInfo["id"]), stoi(levelInfo["id"]), targetLevel.Value()); if (!levelXrefInfo.empty()) { double lvlValue; try { lvlValue = stod(levelXrefInfo["value"]); } catch (const invalid_argument& e) { lvlValue = targetLevel.Value(); } HPLevelType lvlType = HPStringToLevelType.at(boost::to_lower_copy(levelXrefInfo["name"])); if (lvlType == kGround) { lvlValue = 0; } ret = level(lvlType, lvlValue); } } return ret; } void fetcher::DoLevelTransform(bool theDoLevelTransform) { itsDoLevelTransform = theDoLevelTransform; } bool fetcher::DoLevelTransform() const { return itsDoLevelTransform; } void fetcher::DoInterpolation(bool theDoInterpolation) { itsDoInterpolation = theDoInterpolation; } bool fetcher::DoInterpolation() const { return itsDoInterpolation; } void fetcher::UseCache(bool theUseCache) { itsUseCache = theUseCache; } bool fetcher::UseCache() const { return itsUseCache; } template pair>>> fetcher::FetchFromAllSources(search_options& opts, bool readPackedData) { auto fromCache = FetchFromCache(opts); if (!fromCache.empty()) { return make_pair(HPDataFoundFrom::kCache, fromCache); } if (!auxiliaryFilesRead) { // second ret, different from first auto fromAux = FetchFromAuxiliaryFiles(opts, readPackedData); if (!fromAux.second.empty()) { return make_pair(fromAux.first, vector>>({ConvertTo(fromAux.second[0])})); } } return make_pair(HPDataFoundFrom::kDatabase, FetchFromDatabase(opts, readPackedData)); } template pair>>> fetcher::FetchFromAllSources(search_options&, bool); template pair>>> fetcher::FetchFromAllSources(search_options&, bool); template pair>>> fetcher::FetchFromAllSources(search_options&, bool); template pair>>> fetcher::FetchFromAllSources( search_options&, bool); template vector>> fetcher::FetchFromCache(search_options& opts) { vector>> ret; if (itsUseCache && opts.configuration->UseCacheForReads()) { // 1. Fetch data from cache ret = FromCache(opts); if (ret.size()) { if (dynamic_pointer_cast(opts.configuration)->StatisticsEnabled()) { dynamic_pointer_cast(opts.configuration) ->Statistics() ->AddToCacheHitCount(1); } } } return ret; } template vector>> fetcher::FetchFromCache(search_options&); template vector>> fetcher::FetchFromCache(search_options&); template vector>> fetcher::FetchFromCache(search_options&); template vector>> fetcher::FetchFromCache(search_options&); template vector>> fetcher::FetchFromDatabase(search_options& opts, bool readPackedData) { vector>> ret; HPDatabaseType dbtype = opts.configuration->DatabaseType(); if (!opts.configuration->ReadFromDatabase() || dbtype == kNoDatabase) { return ret; } if (opts.prod.Class() == kGridClass) { vector files; if (dbtype == kRadon) { auto r = GET_PLUGIN(radon); files = r->Files(opts); } if (files.size() == 0) { const string ref_prod = opts.prod.Name(); const string analtime = opts.time.OriginDateTime().String("%Y%m%d%H%M"); const vector sourceGeoms = opts.configuration->SourceGeomNames(); itsLogger.Trace( fmt::format("No geometries found for producer {}, analysistime {}, source geom name(s) {}, param {}", ref_prod, analtime, fmt::join(sourceGeoms, ","), opts.param.Name())); } else { ret = FromFile(files, opts, readPackedData, false); if (dynamic_pointer_cast(opts.configuration)->StatisticsEnabled()) { dynamic_pointer_cast(opts.configuration) ->Statistics() ->AddToCacheMissCount(1); } return ret; } } else if (opts.prod.Class() == kPreviClass) { auto r = GET_PLUGIN(radon); auto csv_forecasts = r->CSV(opts); auto _ret = util::CSVToInfo(csv_forecasts); if (_ret) { ret.push_back(_ret); } } return ret; } template vector>> fetcher::FetchFromDatabase(search_options&, bool); template vector>> fetcher::FetchFromDatabase(search_options&, bool); template vector>> fetcher::FetchFromDatabase(search_options&, bool); template vector>> fetcher::FetchFromDatabase(search_options&, bool); pair>>> fetcher::FetchFromAuxiliaryFiles(search_options& opts, bool readPackedData) { vector>> ret; HPDataFoundFrom source = HPDataFoundFrom::kAuxFile; if (!opts.configuration->AuxiliaryFiles().empty()) { vector files; files.reserve(opts.configuration->AuxiliaryFiles().size()); for (const auto& file : opts.configuration->AuxiliaryFiles()) { file_information f; f.file_location = file; f.file_type = util::FileType(file); f.offset = boost::none; f.length = boost::none; f.message_no = boost::none; f.storage_type = (file.find("s3://") != string::npos) ? HPFileStorageType::kS3ObjectStorageSystem : HPFileStorageType::kLocalFileSystem; files.push_back(f); } if (itsUseCache && opts.configuration->UseCacheForReads() && opts.configuration->ReadAllAuxiliaryFilesToCache()) { if (itsApplyLandSeaMask) { itsLogger.Fatal("Land sea mask cannot be applied when reading all auxiliary files to cache"); itsLogger.Fatal("Restart himan with command line option --no-auxiliary-file-full-cache-read"); himan::Abort(); } auto c = GET_PLUGIN(cache); call_once(oflag, [&]() { itsLogger.Debug("Start full auxiliary files read"); timer t(true); ret = FromFile(files, opts, readPackedData, true); AuxiliaryFilesRotateAndInterpolate(opts, ret); #ifdef HAVE_CUDA if (readPackedData && opts.configuration->UseCudaForUnpacking()) { util::Unpack(ret, false); } #endif for (const auto& info : ret) { info->First(); info->Reset(); while (info->Next()) { c->Insert(info); } } t.Stop(); itsLogger.Debug( fmt::format("Auxiliary files read finished in {} ms, cache size: {}", t.GetTime(), c->Size())); }); auxiliaryFilesRead = true; source = HPDataFoundFrom::kCache; ret = FromCache(opts); } else { ret = FromFile(files, opts, readPackedData, false); } if (!ret.empty()) { itsLogger.Trace("Data found from auxiliary file(s)"); if (dynamic_pointer_cast(opts.configuration)->StatisticsEnabled()) { dynamic_pointer_cast(opts.configuration) ->Statistics() ->AddToCacheMissCount(1); } } else { itsLogger.Trace("Data not found from auxiliary file(s)"); } } return make_pair(source, ret); } void fetcher::AuxiliaryFilesRotateAndInterpolate(const search_options& opts, vector>>& infos) { // Step 1. Rotate if needed const grid* baseGrid = opts.configuration->BaseGrid(); auto eq = [](const shared_ptr>& a, const shared_ptr>& b) { return a->Param() == b->Param() && a->Level() == b->Level() && a->Time() == b->Time() && a->ForecastType() == b->ForecastType(); }; vector>> skip; for (const auto& component : infos) { const HPGridType to = baseGrid->Type(); const HPGridType from = component->Grid()->Type(); const auto name = component->Param().Name(); if (interpolate::IsVectorComponent(name) && count_if(skip.begin(), skip.end(), [&](const shared_ptr>& info) { return eq(info, component); }) == 0 && interpolate::IsSupportedGridForRotation(from) && component->Grid()->UVRelativeToGrid() && to != from) { auto otherName = GetOtherVectorComponentName(name); shared_ptr> u, v, other; for (const auto temp : infos) { if (temp->Param().Name() == otherName && temp->Level() == component->Level() && temp->Time() == component->Time() && temp->ForecastType() == component->ForecastType()) { other = temp; break; } } if (!other) { // Other component not found continue; } if (name.find("U-MS") != std::string::npos) { u = component; v = other; } else if (name.find("V-MS") != std::string::npos) { u = other; v = component; } else { itsLogger.Fatal("Unrecognized vector component parameter: " + name); himan::Abort(); } #ifdef HAVE_CUDA if (opts.configuration->UseCudaForPacking()) { util::Unpack({u, v}, false); } #endif interpolate::RotateVectorComponents(component->Grid().get(), baseGrid, *u, *v, opts.configuration->UseCuda()); auto c = GET_PLUGIN(cache); c->Replace(u); c->Replace(v); // RotateVectorComponent modifies both components, so make sure we don't re-rotate the other // component. skip.push_back(other); } } // Step 2. Interpolate if needed if (itsDoInterpolation) { if (!interpolate::Interpolate(opts.configuration->BaseGrid(), infos)) { itsLogger.Fatal("Interpolation failed"); himan::Abort(); } } else { itsLogger.Trace("Interpolation disabled"); } } template bool fetcher::ApplyLandSeaMask(std::shared_ptr config, shared_ptr> theInfo, const forecast_time& requestedTime, const forecast_type& requestedType) { raw_time originTime = requestedTime.OriginDateTime(); forecast_time firstTime(originTime, originTime); itsLogger.Trace(fmt::format("Applying land-sea mask with threshold {}", itsLandSeaMaskThreshold)); try { itsApplyLandSeaMask = false; auto lsmInfo = Fetch(config, firstTime, level(kHeight, 0), param("LC-0TO1"), requestedType, false); itsApplyLandSeaMask = true; lsmInfo->First(); ASSERT(*lsmInfo->Grid() == *theInfo->Grid()); ASSERT(itsLandSeaMaskThreshold >= -1 && itsLandSeaMaskThreshold <= 1); ASSERT(itsLandSeaMaskThreshold != 0); #ifdef HAVE_CUDA if (theInfo->PackedData()->HasData()) { // We need to unpack util::Unpack({theInfo}, false); } #endif ASSERT(theInfo->PackedData()->HasData() == false); double multiplier = (itsLandSeaMaskThreshold > 0) ? 1. : -1.; for (lsmInfo->ResetLocation(), theInfo->ResetLocation(); lsmInfo->NextLocation() && theInfo->NextLocation();) { T lsm = lsmInfo->Value(); if (multiplier * lsm <= itsLandSeaMaskThreshold) { theInfo->Value(MissingValue()); } } } catch (HPExceptionType& e) { itsApplyLandSeaMask = true; return false; } return true; } template bool fetcher::ApplyLandSeaMask(std::shared_ptr, shared_ptr>, const forecast_time&, const forecast_type&); template bool fetcher::ApplyLandSeaMask(std::shared_ptr, shared_ptr>, const forecast_time&, const forecast_type&); template bool fetcher::ApplyLandSeaMask(std::shared_ptr, shared_ptr>, const forecast_time&, const forecast_type&); template bool fetcher::ApplyLandSeaMask(std::shared_ptr, shared_ptr>, const forecast_time&, const forecast_type&); bool fetcher::ApplyLandSeaMask() const { return itsApplyLandSeaMask; } void fetcher::ApplyLandSeaMask(bool theApplyLandSeaMask) { itsApplyLandSeaMask = theApplyLandSeaMask; } double fetcher::LandSeaMaskThreshold() const { return itsLandSeaMaskThreshold; } void fetcher::LandSeaMaskThreshold(double theLandSeaMaskThreshold) { if (theLandSeaMaskThreshold < -1 || theLandSeaMaskThreshold > 1) { itsLogger.Fatal(fmt::format("Invalid value for land sea mask threshold: {}", theLandSeaMaskThreshold)); himan::Abort(); } itsLandSeaMaskThreshold = theLandSeaMaskThreshold; } bool fetcher::DoVectorComponentRotation() const { return itsDoVectorComponentRotation; } void fetcher::DoVectorComponentRotation(bool theDoVectorComponentRotation) { itsDoVectorComponentRotation = theDoVectorComponentRotation; } string GetOtherVectorComponentName(const string& name) { // wind if (name == "U-MS") return "V-MS"; else if (name == "V-MS") return "U-MS"; // wind gust else if (name == "WGU-MS") return "WGV-MS"; else if (name == "WGV-MS") return "WGU-MS"; // ice else if (name == "IVELU-MS") return "IVELV-MS"; else if (name == "IVELV-MS") return "IVELU-MS"; // sea else if (name == "WVELU-MS") return "WVELV-MS"; else if (name == "WVELV-MS") return "WVELU-MS"; throw runtime_error("Unable to find component pair for " + name); } template void fetcher::RotateVectorComponents(vector>>& components, const grid* target, shared_ptr config, const producer& sourceProd) { for (auto& component : components) { const HPGridType from = component->Grid()->Type(); const HPGridType to = target->Type(); const auto name = component->Param().Name(); if (interpolate::IsVectorComponent(name) && itsDoVectorComponentRotation && to != from && interpolate::IsSupportedGridForRotation(from)) { auto otherName = GetOtherVectorComponentName(name); search_options opts(component->Time(), param(otherName), component->Level(), sourceProd, component->ForecastType(), config); itsLogger.Trace("Fetching " + otherName + " for U/V rotation"); auto ret = FetchFromAllSources(opts, component->PackedData()->HasData()); auto otherVec = ret.second; if (otherVec.empty()) { // Other component not found continue; } shared_ptr> u, v, other = otherVec[0]; if (name.find("U-MS") != std::string::npos) { u = component; v = other; } else if (name.find("V-MS") != std::string::npos) { u = other; v = component; } else { throw runtime_error("Unrecognized vector component parameter: " + name); } interpolate::RotateVectorComponents(component->Grid().get(), target, *u, *v, config->UseCuda()); // Most likely both U&V are requested, so interpolate the other one now // and put it to cache. std::vector>> list({other}); if (itsDoInterpolation) { if (interpolate::Interpolate(target, list)) { if (itsUseCache && config->UseCacheForReads() && !other->PackedData()->HasData()) { auto c = GET_PLUGIN(cache); c->Insert(other); } } } else { itsLogger.Trace("Interpolation disabled"); } } } } template void fetcher::RotateVectorComponents(vector>>&, const grid*, shared_ptr, const producer&); template void fetcher::RotateVectorComponents(vector>>&, const grid*, shared_ptr, const producer&); template void fetcher::RotateVectorComponents(vector>>&, const grid*, shared_ptr, const producer&); template void fetcher::RotateVectorComponents(vector>>&, const grid*, shared_ptr, const producer&); /**************************************************************************** ** ** Copyright (C) 2015 The Qt Company Ltd. ** Contact: http://www.qt.io/licensing/ ** ** This file is part of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL21$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see http://www.qt.io/terms-conditions. For further ** information use the contact form at http://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** As a special exception, The Qt Company gives you certain additional ** rights. These rights are described in The Qt Company LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qgstreamervideowidget_p.h" #include #include #include QT_BEGIN_NAMESPACE class QGstreamerVideoWidget : public QWidget { public: QGstreamerVideoWidget(QWidget *parent = 0) :QWidget(parent) { setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); QPalette palette; palette.setColor(QPalette::Background, Qt::black); setPalette(palette); } virtual ~QGstreamerVideoWidget() {} QSize sizeHint() const { return m_nativeSize; } void setNativeSize( const QSize &size) { if (size != m_nativeSize) { m_nativeSize = size; if (size.isEmpty()) setMinimumSize(0,0); else setMinimumSize(160,120); updateGeometry(); } } void paint_helper() { QPainter painter(this); painter.fillRect(rect(), palette().background()); } protected: void paintEvent(QPaintEvent *) { paint_helper(); } QSize m_nativeSize; }; QGstreamerVideoWidgetControl::QGstreamerVideoWidgetControl(QObject *parent, const QByteArray &elementName) : QVideoWidgetControl(parent) , m_videoOverlay(this, !elementName.isEmpty() ? elementName : qgetenv("QT_GSTREAMER_WIDGET_VIDEOSINK")) , m_widget(0) , m_stopped(false) , m_windowId(0) , m_fullScreen(false) { connect(&m_videoOverlay, &QGstreamerVideoOverlay::activeChanged, this, &QGstreamerVideoWidgetControl::onOverlayActiveChanged); connect(&m_videoOverlay, &QGstreamerVideoOverlay::nativeVideoSizeChanged, this, &QGstreamerVideoWidgetControl::onNativeVideoSizeChanged); connect(&m_videoOverlay, &QGstreamerVideoOverlay::brightnessChanged, this, &QGstreamerVideoWidgetControl::brightnessChanged); connect(&m_videoOverlay, &QGstreamerVideoOverlay::contrastChanged, this, &QGstreamerVideoWidgetControl::contrastChanged); connect(&m_videoOverlay, &QGstreamerVideoOverlay::hueChanged, this, &QGstreamerVideoWidgetControl::hueChanged); connect(&m_videoOverlay, &QGstreamerVideoOverlay::saturationChanged, this, &QGstreamerVideoWidgetControl::saturationChanged); } QGstreamerVideoWidgetControl::~QGstreamerVideoWidgetControl() { delete m_widget; } void QGstreamerVideoWidgetControl::createVideoWidget() { if (m_widget) return; m_widget = new QGstreamerVideoWidget; m_widget->installEventFilter(this); m_videoOverlay.setWindowHandle(m_windowId = m_widget->winId()); } GstElement *QGstreamerVideoWidgetControl::videoSink() { return m_videoOverlay.videoSink(); } void QGstreamerVideoWidgetControl::onOverlayActiveChanged() { updateWidgetAttributes(); } void QGstreamerVideoWidgetControl::stopRenderer() { m_stopped = true; updateWidgetAttributes(); m_widget->setNativeSize(QSize()); } void QGstreamerVideoWidgetControl::onNativeVideoSizeChanged() { const QSize &size = m_videoOverlay.nativeVideoSize(); if (size.isValid()) m_stopped = false; if (m_widget) m_widget->setNativeSize(size); } bool QGstreamerVideoWidgetControl::eventFilter(QObject *object, QEvent *e) { if (m_widget && object == m_widget) { if (e->type() == QEvent::ParentChange || e->type() == QEvent::Show || e->type() == QEvent::WinIdChange) { WId newWId = m_widget->winId(); if (newWId != m_windowId) m_videoOverlay.setWindowHandle(m_windowId = newWId); } if (e->type() == QEvent::Paint) { if (m_videoOverlay.isActive()) m_videoOverlay.expose(); // triggers a repaint of the last frame else m_widget->paint_helper(); // paints the black background return true; } } return false; } void QGstreamerVideoWidgetControl::updateWidgetAttributes() { // When frames are being rendered (sink is active), we need the WA_PaintOnScreen attribute to // be set in order to avoid flickering when the widget is repainted (for example when resized). // We need to clear that flag when the the sink is inactive to allow the widget to paint its // background, otherwise some garbage will be displayed. if (m_videoOverlay.isActive() && !m_stopped) { m_widget->setAttribute(Qt::WA_NoSystemBackground, true); m_widget->setAttribute(Qt::WA_PaintOnScreen, true); } else { m_widget->setAttribute(Qt::WA_NoSystemBackground, false); m_widget->setAttribute(Qt::WA_PaintOnScreen, false); m_widget->update(); } } bool QGstreamerVideoWidgetControl::processSyncMessage(const QGstreamerMessage &message) { return m_videoOverlay.processSyncMessage(message); } bool QGstreamerVideoWidgetControl::processBusMessage(const QGstreamerMessage &message) { return m_videoOverlay.processBusMessage(message); } QWidget *QGstreamerVideoWidgetControl::videoWidget() { createVideoWidget(); return m_widget; } Qt::AspectRatioMode QGstreamerVideoWidgetControl::aspectRatioMode() const { return m_videoOverlay.aspectRatioMode(); } void QGstreamerVideoWidgetControl::setAspectRatioMode(Qt::AspectRatioMode mode) { m_videoOverlay.setAspectRatioMode(mode); } bool QGstreamerVideoWidgetControl::isFullScreen() const { return m_fullScreen; } void QGstreamerVideoWidgetControl::setFullScreen(bool fullScreen) { emit fullScreenChanged(m_fullScreen = fullScreen); } int QGstreamerVideoWidgetControl::brightness() const { return m_videoOverlay.brightness(); } void QGstreamerVideoWidgetControl::setBrightness(int brightness) { m_videoOverlay.setBrightness(brightness); } int QGstreamerVideoWidgetControl::contrast() const { return m_videoOverlay.contrast(); } void QGstreamerVideoWidgetControl::setContrast(int contrast) { m_videoOverlay.setContrast(contrast); } int QGstreamerVideoWidgetControl::hue() const { return m_videoOverlay.hue(); } void QGstreamerVideoWidgetControl::setHue(int hue) { m_videoOverlay.setHue(hue); } int QGstreamerVideoWidgetControl::saturation() const { return m_videoOverlay.saturation(); } void QGstreamerVideoWidgetControl::setSaturation(int saturation) { m_videoOverlay.setSaturation(saturation); } QT_END_NAMESPACE // mojo/public/interfaces/bindings/tests/math_calculator.mojom.cc is auto generated by mojom_bindings_generator.py, do not edit // Copyright 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. #if defined(__clang__) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wunused-private-field" #endif #include "mojo/public/interfaces/bindings/tests/math_calculator.mojom.h" #include #include #include #include "base/hash/md5_constexpr.h" #include "base/run_loop.h" #include "base/strings/string_number_conversions.h" #include "base/task/common/task_annotator.h" #include "base/trace_event/trace_event.h" #include "mojo/public/cpp/bindings/lib/generated_code_util.h" #include "mojo/public/cpp/bindings/lib/message_internal.h" #include "mojo/public/cpp/bindings/lib/serialization_util.h" #include "mojo/public/cpp/bindings/lib/unserialized_message_context.h" #include "mojo/public/cpp/bindings/lib/validate_params.h" #include "mojo/public/cpp/bindings/lib/validation_context.h" #include "mojo/public/cpp/bindings/lib/validation_errors.h" #include "mojo/public/cpp/bindings/mojo_buildflags.h" #include "mojo/public/interfaces/bindings/interface_control_messages.mojom.h" #include "third_party/perfetto/include/perfetto/tracing/traced_value.h" #include "mojo/public/interfaces/bindings/tests/math_calculator.mojom-params-data.h" #include "mojo/public/interfaces/bindings/tests/math_calculator.mojom-shared-message-ids.h" #include "mojo/public/interfaces/bindings/tests/math_calculator.mojom-import-headers.h" #ifndef MOJO_PUBLIC_INTERFACES_BINDINGS_TESTS_MATH_CALCULATOR_MOJOM_JUMBO_H_ #define MOJO_PUBLIC_INTERFACES_BINDINGS_TESTS_MATH_CALCULATOR_MOJOM_JUMBO_H_ #endif namespace math { const char Calculator::Name_[] = "math.Calculator"; class Calculator_Clear_ForwardToCallback : public mojo::MessageReceiver { public: Calculator_Clear_ForwardToCallback( Calculator::ClearCallback callback ) : callback_(std::move(callback)) { } bool Accept(mojo::Message* message) override; private: Calculator::ClearCallback callback_; DISALLOW_COPY_AND_ASSIGN(Calculator_Clear_ForwardToCallback); }; class Calculator_Add_ForwardToCallback : public mojo::MessageReceiver { public: Calculator_Add_ForwardToCallback( Calculator::AddCallback callback ) : callback_(std::move(callback)) { } bool Accept(mojo::Message* message) override; private: Calculator::AddCallback callback_; DISALLOW_COPY_AND_ASSIGN(Calculator_Add_ForwardToCallback); }; class Calculator_Multiply_ForwardToCallback : public mojo::MessageReceiver { public: Calculator_Multiply_ForwardToCallback( Calculator::MultiplyCallback callback ) : callback_(std::move(callback)) { } bool Accept(mojo::Message* message) override; private: Calculator::MultiplyCallback callback_; DISALLOW_COPY_AND_ASSIGN(Calculator_Multiply_ForwardToCallback); }; CalculatorProxy::CalculatorProxy(mojo::MessageReceiverWithResponder* receiver) : receiver_(receiver) { } class CalculatorProxy_Clear_Message : public mojo::internal::UnserializedMessageContext { public: static const mojo::internal::UnserializedMessageContext::Tag kMessageTag; explicit CalculatorProxy_Clear_Message( uint32_t message_flags ) : mojo::internal::UnserializedMessageContext( &kMessageTag, internal::kCalculator_Clear_Name, message_flags){} ~CalculatorProxy_Clear_Message() override = default; static mojo::Message Build( bool serialize, bool expects_response, bool is_sync) { const uint32_t kFlags = ((expects_response) ? mojo::Message::kFlagExpectsResponse : 0) | ((is_sync) ? mojo::Message::kFlagIsSync : 0); if (!serialize) { return mojo::Message(std::make_unique( kFlags ), MOJO_CREATE_MESSAGE_FLAG_NONE); } DCHECK(serialize); mojo::Message message( internal::kCalculator_Clear_Name, kFlags, 0, 0, nullptr); mojo::internal::MessageFragment< ::math::internal::Calculator_Clear_Params_Data> params( message); params.Allocate(); return message; } void Dispatch( mojo::Message* message, Calculator* impl, Calculator::ClearCallback callback) { if (message->receiver_connection_group()) { } impl->Clear(std::move(callback)); } private: // mojo::internal::UnserializedMessageContext: void Serialize(mojo::Message& message) override { mojo::internal::MessageFragment< ::math::internal::Calculator_Clear_Params_Data> params( message); params.Allocate(); } DISALLOW_COPY_AND_ASSIGN(CalculatorProxy_Clear_Message); }; const mojo::internal::UnserializedMessageContext::Tag CalculatorProxy_Clear_Message::kMessageTag = {}; void CalculatorProxy::Clear( ClearCallback callback) { #if BUILDFLAG(MOJO_TRACE_ENABLED) TRACE_EVENT0("mojom", "math::Calculator::Clear"); #endif const bool kExpectsResponse = true; const bool kIsSync = false; const bool kSerialize = receiver_->PrefersSerializedMessages(); auto message = CalculatorProxy_Clear_Message::Build( kSerialize, kExpectsResponse, kIsSync); #if defined(ENABLE_IPC_FUZZER) message.set_interface_name(Calculator::Name_); message.set_method_name("Clear"); #endif std::unique_ptr responder( new Calculator_Clear_ForwardToCallback( std::move(callback))); ignore_result(receiver_->AcceptWithResponder(&message, std::move(responder))); } class CalculatorProxy_Add_Message : public mojo::internal::UnserializedMessageContext { public: static const mojo::internal::UnserializedMessageContext::Tag kMessageTag; explicit CalculatorProxy_Add_Message( uint32_t message_flags , double param_value ) : mojo::internal::UnserializedMessageContext( &kMessageTag, internal::kCalculator_Add_Name, message_flags) , param_value_(std::move(param_value)){} ~CalculatorProxy_Add_Message() override = default; static mojo::Message Build( bool serialize, bool expects_response, bool is_sync, double param_value) { const uint32_t kFlags = ((expects_response) ? mojo::Message::kFlagExpectsResponse : 0) | ((is_sync) ? mojo::Message::kFlagIsSync : 0); if (!serialize) { return mojo::Message(std::make_unique( kFlags , std::move(param_value) ), MOJO_CREATE_MESSAGE_FLAG_NONE); } DCHECK(serialize); mojo::Message message( internal::kCalculator_Add_Name, kFlags, 0, 0, nullptr); mojo::internal::MessageFragment< ::math::internal::Calculator_Add_Params_Data> params( message); params.Allocate(); params->value = param_value; return message; } void Dispatch( mojo::Message* message, Calculator* impl, Calculator::AddCallback callback) { if (message->receiver_connection_group()) { } impl->Add( std::move(param_value_), std::move(callback)); } private: // mojo::internal::UnserializedMessageContext: void Serialize(mojo::Message& message) override { mojo::internal::MessageFragment< ::math::internal::Calculator_Add_Params_Data> params( message); params.Allocate(); params->value = param_value_; } double param_value_; DISALLOW_COPY_AND_ASSIGN(CalculatorProxy_Add_Message); }; const mojo::internal::UnserializedMessageContext::Tag CalculatorProxy_Add_Message::kMessageTag = {}; void CalculatorProxy::Add( double in_value, AddCallback callback) { #if BUILDFLAG(MOJO_TRACE_ENABLED) TRACE_EVENT1( "mojom", "math::Calculator::Add", "input_parameters", [&](perfetto::TracedValue context){ auto dict = std::move(context).WriteDictionary(); perfetto::WriteIntoTracedValueWithFallback( dict.AddItem("value"), in_value, ""); }); #endif const bool kExpectsResponse = true; const bool kIsSync = false; const bool kSerialize = receiver_->PrefersSerializedMessages(); auto message = CalculatorProxy_Add_Message::Build( kSerialize, kExpectsResponse, kIsSync, std::move(in_value)); #if defined(ENABLE_IPC_FUZZER) message.set_interface_name(Calculator::Name_); message.set_method_name("Add"); #endif std::unique_ptr responder( new Calculator_Add_ForwardToCallback( std::move(callback))); ignore_result(receiver_->AcceptWithResponder(&message, std::move(responder))); } class CalculatorProxy_Multiply_Message : public mojo::internal::UnserializedMessageContext { public: static const mojo::internal::UnserializedMessageContext::Tag kMessageTag; explicit CalculatorProxy_Multiply_Message( uint32_t message_flags , double param_value ) : mojo::internal::UnserializedMessageContext( &kMessageTag, internal::kCalculator_Multiply_Name, message_flags) , param_value_(std::move(param_value)){} ~CalculatorProxy_Multiply_Message() override = default; static mojo::Message Build( bool serialize, bool expects_response, bool is_sync, double param_value) { const uint32_t kFlags = ((expects_response) ? mojo::Message::kFlagExpectsResponse : 0) | ((is_sync) ? mojo::Message::kFlagIsSync : 0); if (!serialize) { return mojo::Message(std::make_unique( kFlags , std::move(param_value) ), MOJO_CREATE_MESSAGE_FLAG_NONE); } DCHECK(serialize); mojo::Message message( internal::kCalculator_Multiply_Name, kFlags, 0, 0, nullptr); mojo::internal::MessageFragment< ::math::internal::Calculator_Multiply_Params_Data> params( message); params.Allocate(); params->value = param_value; return message; } void Dispatch( mojo::Message* message, Calculator* impl, Calculator::MultiplyCallback callback) { if (message->receiver_connection_group()) { } impl->Multiply( std::move(param_value_), std::move(callback)); } private: // mojo::internal::UnserializedMessageContext: void Serialize(mojo::Message& message) override { mojo::internal::MessageFragment< ::math::internal::Calculator_Multiply_Params_Data> params( message); params.Allocate(); params->value = param_value_; } double param_value_; DISALLOW_COPY_AND_ASSIGN(CalculatorProxy_Multiply_Message); }; const mojo::internal::UnserializedMessageContext::Tag CalculatorProxy_Multiply_Message::kMessageTag = {}; void CalculatorProxy::Multiply( double in_value, MultiplyCallback callback) { #if BUILDFLAG(MOJO_TRACE_ENABLED) TRACE_EVENT1( "mojom", "math::Calculator::Multiply", "input_parameters", [&](perfetto::TracedValue context){ auto dict = std::move(context).WriteDictionary(); perfetto::WriteIntoTracedValueWithFallback( dict.AddItem("value"), in_value, ""); }); #endif const bool kExpectsResponse = true; const bool kIsSync = false; const bool kSerialize = receiver_->PrefersSerializedMessages(); auto message = CalculatorProxy_Multiply_Message::Build( kSerialize, kExpectsResponse, kIsSync, std::move(in_value)); #if defined(ENABLE_IPC_FUZZER) message.set_interface_name(Calculator::Name_); message.set_method_name("Multiply"); #endif std::unique_ptr responder( new Calculator_Multiply_ForwardToCallback( std::move(callback))); ignore_result(receiver_->AcceptWithResponder(&message, std::move(responder))); } class Calculator_Clear_ProxyToResponder { public: static Calculator::ClearCallback CreateCallback( uint64_t request_id, bool is_sync, std::unique_ptr* responder) { std::unique_ptr proxy( new Calculator_Clear_ProxyToResponder( request_id, is_sync, responder)); return base::BindOnce(&Calculator_Clear_ProxyToResponder::Run, std::move(proxy)); } ~Calculator_Clear_ProxyToResponder() { #if DCHECK_IS_ON() if (responder_) { // If we're being destroyed without being run, we want to ensure the // binding endpoint has been closed. This checks for that asynchronously. // We pass a bound generated callback to handle the response so that any // resulting DCHECK stack will have useful interface type information. responder_->IsConnectedAsync(base::BindOnce(&OnIsConnectedComplete)); } #endif // If the Callback was dropped then deleting the responder will close // the pipe so the calling application knows to stop waiting for a reply. responder_ = nullptr; } private: Calculator_Clear_ProxyToResponder( uint64_t request_id, bool is_sync, std::unique_ptr* responder) : request_id_(request_id), is_sync_(is_sync), responder_(std::move(*responder)) { } #if DCHECK_IS_ON() static void OnIsConnectedComplete(bool connected) { DCHECK(!connected) << "Calculator::ClearCallback was destroyed without " << "first either being run or its corresponding binding being closed. " << "It is an error to drop response callbacks which still correspond " << "to an open interface pipe."; } #endif void Run( double in_value); uint64_t request_id_; bool is_sync_; std::unique_ptr responder_; DISALLOW_COPY_AND_ASSIGN(Calculator_Clear_ProxyToResponder); }; class Calculator_Clear_Response_Message : public mojo::internal::UnserializedMessageContext { public: static const mojo::internal::UnserializedMessageContext::Tag kMessageTag; explicit Calculator_Clear_Response_Message( uint32_t message_flags , double param_value ) : mojo::internal::UnserializedMessageContext( &kMessageTag, internal::kCalculator_Clear_Name, message_flags) , param_value_(std::move(param_value)){} ~Calculator_Clear_Response_Message() override = default; static mojo::Message Build( bool serialize, bool is_sync, double param_value) { const uint32_t kFlags = mojo::Message::kFlagIsResponse | ((is_sync) ? mojo::Message::kFlagIsSync : 0); if (!serialize) { return mojo::Message(std::make_unique( kFlags , std::move(param_value) ), MOJO_CREATE_MESSAGE_FLAG_NONE); } DCHECK(serialize); mojo::Message message( internal::kCalculator_Clear_Name, kFlags, 0, 0, nullptr); mojo::internal::MessageFragment< ::math::internal::Calculator_Clear_ResponseParams_Data> params( message); params.Allocate(); params->value = param_value; return message; } void Dispatch(mojo::Message* message, Calculator::ClearCallback* callback) { if (message->receiver_connection_group()) { } std::move(*callback).Run( std::move(param_value_)); } private: // mojo::internal::UnserializedMessageContext: void Serialize(mojo::Message& message) override { mojo::internal::MessageFragment< ::math::internal::Calculator_Clear_ResponseParams_Data> params( message); params.Allocate(); params->value = param_value_; } double param_value_; DISALLOW_COPY_AND_ASSIGN(Calculator_Clear_Response_Message); }; const mojo::internal::UnserializedMessageContext::Tag Calculator_Clear_Response_Message::kMessageTag = {}; bool Calculator_Clear_ForwardToCallback::Accept( mojo::Message* message) { #if BUILDFLAG(MOJO_TRACE_ENABLED) TRACE_EVENT1("mojom", "math::Calculator::ClearCallback", "message", message->name()); #endif if (!message->is_serialized()) { auto context = message->TakeUnserializedContext(); if (!context) { // The Message was not of the expected type. It may be a valid message // which was build using a different variant of these bindings. Force // serialization before dispatch in this case. message->SerializeIfNecessary(); } else { if (!callback_.is_null()) context->Dispatch(message, &callback_); return true; } } DCHECK(message->is_serialized()); internal::Calculator_Clear_ResponseParams_Data* params = reinterpret_cast< internal::Calculator_Clear_ResponseParams_Data*>( message->mutable_payload()); bool success = true; double p_value{}; Calculator_Clear_ResponseParamsDataView input_data_view(params, message); if (success) p_value = input_data_view.value(); if (!success) { ReportValidationErrorForMessage( message, mojo::internal::VALIDATION_ERROR_DESERIALIZATION_FAILED, Calculator::Name_, 0, true); return false; } if (!callback_.is_null()) std::move(callback_).Run( std::move(p_value)); return true; } void Calculator_Clear_ProxyToResponder::Run( double in_value) { #if BUILDFLAG(MOJO_TRACE_ENABLED) TRACE_EVENT_BEGIN1( "mojom", "(Impl)math::Calculator::ClearCallback", "async_response_parameters", [&](perfetto::TracedValue context){ auto dict = std::move(context).WriteDictionary(); perfetto::WriteIntoTracedValueWithFallback( dict.AddItem("value"), in_value, ""); }); #endif const bool kSerialize = responder_->PrefersSerializedMessages(); auto message = Calculator_Clear_Response_Message::Build(kSerialize, is_sync_, std::move(in_value)); #if BUILDFLAG(MOJO_TRACE_ENABLED) TRACE_EVENT_END1("mojom", "(Impl)math::Calculator::ClearCallback", "message", message.name()); #endif #if defined(ENABLE_IPC_FUZZER) message.set_interface_name(Calculator::Name_); message.set_method_name("Clear"); #endif message.set_request_id(request_id_); ignore_result(responder_->Accept(&message)); // TODO(darin): Accept() returning false indicates a malformed message, and // that may be good reason to close the connection. However, we don't have a // way to do that from here. We should add a way. responder_ = nullptr; } class Calculator_Add_ProxyToResponder { public: static Calculator::AddCallback CreateCallback( uint64_t request_id, bool is_sync, std::unique_ptr* responder) { std::unique_ptr proxy( new Calculator_Add_ProxyToResponder( request_id, is_sync, responder)); return base::BindOnce(&Calculator_Add_ProxyToResponder::Run, std::move(proxy)); } ~Calculator_Add_ProxyToResponder() { #if DCHECK_IS_ON() if (responder_) { // If we're being destroyed without being run, we want to ensure the // binding endpoint has been closed. This checks for that asynchronously. // We pass a bound generated callback to handle the response so that any // resulting DCHECK stack will have useful interface type information. responder_->IsConnectedAsync(base::BindOnce(&OnIsConnectedComplete)); } #endif // If the Callback was dropped then deleting the responder will close // the pipe so the calling application knows to stop waiting for a reply. responder_ = nullptr; } private: Calculator_Add_ProxyToResponder( uint64_t request_id, bool is_sync, std::unique_ptr* responder) : request_id_(request_id), is_sync_(is_sync), responder_(std::move(*responder)) { } #if DCHECK_IS_ON() static void OnIsConnectedComplete(bool connected) { DCHECK(!connected) << "Calculator::AddCallback was destroyed without " << "first either being run or its corresponding binding being closed. " << "It is an error to drop response callbacks which still correspond " << "to an open interface pipe."; } #endif void Run( double in_value); uint64_t request_id_; bool is_sync_; std::unique_ptr responder_; DISALLOW_COPY_AND_ASSIGN(Calculator_Add_ProxyToResponder); }; class Calculator_Add_Response_Message : public mojo::internal::UnserializedMessageContext { public: static const mojo::internal::UnserializedMessageContext::Tag kMessageTag; explicit Calculator_Add_Response_Message( uint32_t message_flags , double param_value ) : mojo::internal::UnserializedMessageContext( &kMessageTag, internal::kCalculator_Add_Name, message_flags) , param_value_(std::move(param_value)){} ~Calculator_Add_Response_Message() override = default; static mojo::Message Build( bool serialize, bool is_sync, double param_value) { const uint32_t kFlags = mojo::Message::kFlagIsResponse | ((is_sync) ? mojo::Message::kFlagIsSync : 0); if (!serialize) { return mojo::Message(std::make_unique( kFlags , std::move(param_value) ), MOJO_CREATE_MESSAGE_FLAG_NONE); } DCHECK(serialize); mojo::Message message( internal::kCalculator_Add_Name, kFlags, 0, 0, nullptr); mojo::internal::MessageFragment< ::math::internal::Calculator_Add_ResponseParams_Data> params( message); params.Allocate(); params->value = param_value; return message; } void Dispatch(mojo::Message* message, Calculator::AddCallback* callback) { if (message->receiver_connection_group()) { } std::move(*callback).Run( std::move(param_value_)); } private: // mojo::internal::UnserializedMessageContext: void Serialize(mojo::Message& message) override { mojo::internal::MessageFragment< ::math::internal::Calculator_Add_ResponseParams_Data> params( message); params.Allocate(); params->value = param_value_; } double param_value_; DISALLOW_COPY_AND_ASSIGN(Calculator_Add_Response_Message); }; const mojo::internal::UnserializedMessageContext::Tag Calculator_Add_Response_Message::kMessageTag = {}; bool Calculator_Add_ForwardToCallback::Accept( mojo::Message* message) { #if BUILDFLAG(MOJO_TRACE_ENABLED) TRACE_EVENT1("mojom", "math::Calculator::AddCallback", "message", message->name()); #endif if (!message->is_serialized()) { auto context = message->TakeUnserializedContext(); if (!context) { // The Message was not of the expected type. It may be a valid message // which was build using a different variant of these bindings. Force // serialization before dispatch in this case. message->SerializeIfNecessary(); } else { if (!callback_.is_null()) context->Dispatch(message, &callback_); return true; } } DCHECK(message->is_serialized()); internal::Calculator_Add_ResponseParams_Data* params = reinterpret_cast< internal::Calculator_Add_ResponseParams_Data*>( message->mutable_payload()); bool success = true; double p_value{}; Calculator_Add_ResponseParamsDataView input_data_view(params, message); if (success) p_value = input_data_view.value(); if (!success) { ReportValidationErrorForMessage( message, mojo::internal::VALIDATION_ERROR_DESERIALIZATION_FAILED, Calculator::Name_, 1, true); return false; } if (!callback_.is_null()) std::move(callback_).Run( std::move(p_value)); return true; } void Calculator_Add_ProxyToResponder::Run( double in_value) { #if BUILDFLAG(MOJO_TRACE_ENABLED) TRACE_EVENT_BEGIN1( "mojom", "(Impl)math::Calculator::AddCallback", "async_response_parameters", [&](perfetto::TracedValue context){ auto dict = std::move(context).WriteDictionary(); perfetto::WriteIntoTracedValueWithFallback( dict.AddItem("value"), in_value, ""); }); #endif const bool kSerialize = responder_->PrefersSerializedMessages(); auto message = Calculator_Add_Response_Message::Build(kSerialize, is_sync_, std::move(in_value)); #if BUILDFLAG(MOJO_TRACE_ENABLED) TRACE_EVENT_END1("mojom", "(Impl)math::Calculator::AddCallback", "message", message.name()); #endif #if defined(ENABLE_IPC_FUZZER) message.set_interface_name(Calculator::Name_); message.set_method_name("Add"); #endif message.set_request_id(request_id_); ignore_result(responder_->Accept(&message)); // TODO(darin): Accept() returning false indicates a malformed message, and // that may be good reason to close the connection. However, we don't have a // way to do that from here. We should add a way. responder_ = nullptr; } class Calculator_Multiply_ProxyToResponder { public: static Calculator::MultiplyCallback CreateCallback( uint64_t request_id, bool is_sync, std::unique_ptr* responder) { std::unique_ptr proxy( new Calculator_Multiply_ProxyToResponder( request_id, is_sync, responder)); return base::BindOnce(&Calculator_Multiply_ProxyToResponder::Run, std::move(proxy)); } ~Calculator_Multiply_ProxyToResponder() { #if DCHECK_IS_ON() if (responder_) { // If we're being destroyed without being run, we want to ensure the // binding endpoint has been closed. This checks for that asynchronously. // We pass a bound generated callback to handle the response so that any // resulting DCHECK stack will have useful interface type information. responder_->IsConnectedAsync(base::BindOnce(&OnIsConnectedComplete)); } #endif // If the Callback was dropped then deleting the responder will close // the pipe so the calling application knows to stop waiting for a reply. responder_ = nullptr; } private: Calculator_Multiply_ProxyToResponder( uint64_t request_id, bool is_sync, std::unique_ptr* responder) : request_id_(request_id), is_sync_(is_sync), responder_(std::move(*responder)) { } #if DCHECK_IS_ON() static void OnIsConnectedComplete(bool connected) { DCHECK(!connected) << "Calculator::MultiplyCallback was destroyed without " << "first either being run or its corresponding binding being closed. " << "It is an error to drop response callbacks which still correspond " << "to an open interface pipe."; } #endif void Run( double in_value); uint64_t request_id_; bool is_sync_; std::unique_ptr responder_; DISALLOW_COPY_AND_ASSIGN(Calculator_Multiply_ProxyToResponder); }; class Calculator_Multiply_Response_Message : public mojo::internal::UnserializedMessageContext { public: static const mojo::internal::UnserializedMessageContext::Tag kMessageTag; explicit Calculator_Multiply_Response_Message( uint32_t message_flags , double param_value ) : mojo::internal::UnserializedMessageContext( &kMessageTag, internal::kCalculator_Multiply_Name, message_flags) , param_value_(std::move(param_value)){} ~Calculator_Multiply_Response_Message() override = default; static mojo::Message Build( bool serialize, bool is_sync, double param_value) { const uint32_t kFlags = mojo::Message::kFlagIsResponse | ((is_sync) ? mojo::Message::kFlagIsSync : 0); if (!serialize) { return mojo::Message(std::make_unique( kFlags , std::move(param_value) ), MOJO_CREATE_MESSAGE_FLAG_NONE); } DCHECK(serialize); mojo::Message message( internal::kCalculator_Multiply_Name, kFlags, 0, 0, nullptr); mojo::internal::MessageFragment< ::math::internal::Calculator_Multiply_ResponseParams_Data> params( message); params.Allocate(); params->value = param_value; return message; } void Dispatch(mojo::Message* message, Calculator::MultiplyCallback* callback) { if (message->receiver_connection_group()) { } std::move(*callback).Run( std::move(param_value_)); } private: // mojo::internal::UnserializedMessageContext: void Serialize(mojo::Message& message) override { mojo::internal::MessageFragment< ::math::internal::Calculator_Multiply_ResponseParams_Data> params( message); params.Allocate(); params->value = param_value_; } double param_value_; DISALLOW_COPY_AND_ASSIGN(Calculator_Multiply_Response_Message); }; const mojo::internal::UnserializedMessageContext::Tag Calculator_Multiply_Response_Message::kMessageTag = {}; bool Calculator_Multiply_ForwardToCallback::Accept( mojo::Message* message) { #if BUILDFLAG(MOJO_TRACE_ENABLED) TRACE_EVENT1("mojom", "math::Calculator::MultiplyCallback", "message", message->name()); #endif if (!message->is_serialized()) { auto context = message->TakeUnserializedContext(); if (!context) { // The Message was not of the expected type. It may be a valid message // which was build using a different variant of these bindings. Force // serialization before dispatch in this case. message->SerializeIfNecessary(); } else { if (!callback_.is_null()) context->Dispatch(message, &callback_); return true; } } DCHECK(message->is_serialized()); internal::Calculator_Multiply_ResponseParams_Data* params = reinterpret_cast< internal::Calculator_Multiply_ResponseParams_Data*>( message->mutable_payload()); bool success = true; double p_value{}; Calculator_Multiply_ResponseParamsDataView input_data_view(params, message); if (success) p_value = input_data_view.value(); if (!success) { ReportValidationErrorForMessage( message, mojo::internal::VALIDATION_ERROR_DESERIALIZATION_FAILED, Calculator::Name_, 2, true); return false; } if (!callback_.is_null()) std::move(callback_).Run( std::move(p_value)); return true; } void Calculator_Multiply_ProxyToResponder::Run( double in_value) { #if BUILDFLAG(MOJO_TRACE_ENABLED) TRACE_EVENT_BEGIN1( "mojom", "(Impl)math::Calculator::MultiplyCallback", "async_response_parameters", [&](perfetto::TracedValue context){ auto dict = std::move(context).WriteDictionary(); perfetto::WriteIntoTracedValueWithFallback( dict.AddItem("value"), in_value, ""); }); #endif const bool kSerialize = responder_->PrefersSerializedMessages(); auto message = Calculator_Multiply_Response_Message::Build(kSerialize, is_sync_, std::move(in_value)); #if BUILDFLAG(MOJO_TRACE_ENABLED) TRACE_EVENT_END1("mojom", "(Impl)math::Calculator::MultiplyCallback", "message", message.name()); #endif #if defined(ENABLE_IPC_FUZZER) message.set_interface_name(Calculator::Name_); message.set_method_name("Multiply"); #endif message.set_request_id(request_id_); ignore_result(responder_->Accept(&message)); // TODO(darin): Accept() returning false indicates a malformed message, and // that may be good reason to close the connection. However, we don't have a // way to do that from here. We should add a way. responder_ = nullptr; } // static bool CalculatorStubDispatch::Accept( Calculator* impl, mojo::Message* message) { switch (message->header()->name) { case internal::kCalculator_Clear_Name: { break; } case internal::kCalculator_Add_Name: { break; } case internal::kCalculator_Multiply_Name: { break; } } return false; } // static bool CalculatorStubDispatch::AcceptWithResponder( Calculator* impl, mojo::Message* message, std::unique_ptr responder) { const bool message_is_sync = message->has_flag(mojo::Message::kFlagIsSync); const uint64_t request_id = message->request_id(); ALLOW_UNUSED_LOCAL(message_is_sync); ALLOW_UNUSED_LOCAL(request_id); switch (message->header()->name) { case internal::kCalculator_Clear_Name: { #if BUILDFLAG(MOJO_TRACE_ENABLED) TRACE_EVENT1( "mojom", "(Impl)math::Calculator::Clear", "message", message->name()); #endif static constexpr uint32_t kMessageHash = base::MD5Hash32Constexpr( "(Impl)math::Calculator::Clear"); base::TaskAnnotator::ScopedSetIpcHash scoped_ipc_hash(kMessageHash); if (!message->is_serialized()) { auto context = message->TakeUnserializedContext< CalculatorProxy_Clear_Message>(); if (!context) { // The Message was not of the expected type. It may be a valid message // which was built using a different variant of these bindings. Force // serialization before dispatch in this case. message->SerializeIfNecessary(); } else { Calculator::ClearCallback callback = Calculator_Clear_ProxyToResponder::CreateCallback( message->request_id(), message_is_sync, &responder); context->Dispatch(message, impl, std::move(callback)); return true; } } internal::Calculator_Clear_Params_Data* params = reinterpret_cast< internal::Calculator_Clear_Params_Data*>( message->mutable_payload()); bool success = true; Calculator_Clear_ParamsDataView input_data_view(params, message); if (!success) { ReportValidationErrorForMessage( message, mojo::internal::VALIDATION_ERROR_DESERIALIZATION_FAILED, Calculator::Name_, 0, false); return false; } Calculator::ClearCallback callback = Calculator_Clear_ProxyToResponder::CreateCallback( message->request_id(), message_is_sync, &responder); // A null |impl| means no implementation was bound. DCHECK(impl); impl->Clear(std::move(callback)); return true; } case internal::kCalculator_Add_Name: { #if BUILDFLAG(MOJO_TRACE_ENABLED) TRACE_EVENT1( "mojom", "(Impl)math::Calculator::Add", "message", message->name()); #endif static constexpr uint32_t kMessageHash = base::MD5Hash32Constexpr( "(Impl)math::Calculator::Add"); base::TaskAnnotator::ScopedSetIpcHash scoped_ipc_hash(kMessageHash); if (!message->is_serialized()) { auto context = message->TakeUnserializedContext< CalculatorProxy_Add_Message>(); if (!context) { // The Message was not of the expected type. It may be a valid message // which was built using a different variant of these bindings. Force // serialization before dispatch in this case. message->SerializeIfNecessary(); } else { Calculator::AddCallback callback = Calculator_Add_ProxyToResponder::CreateCallback( message->request_id(), message_is_sync, &responder); context->Dispatch(message, impl, std::move(callback)); return true; } } internal::Calculator_Add_Params_Data* params = reinterpret_cast< internal::Calculator_Add_Params_Data*>( message->mutable_payload()); bool success = true; double p_value{}; Calculator_Add_ParamsDataView input_data_view(params, message); if (success) p_value = input_data_view.value(); if (!success) { ReportValidationErrorForMessage( message, mojo::internal::VALIDATION_ERROR_DESERIALIZATION_FAILED, Calculator::Name_, 1, false); return false; } Calculator::AddCallback callback = Calculator_Add_ProxyToResponder::CreateCallback( message->request_id(), message_is_sync, &responder); // A null |impl| means no implementation was bound. DCHECK(impl); impl->Add( std::move(p_value), std::move(callback)); return true; } case internal::kCalculator_Multiply_Name: { #if BUILDFLAG(MOJO_TRACE_ENABLED) TRACE_EVENT1( "mojom", "(Impl)math::Calculator::Multiply", "message", message->name()); #endif static constexpr uint32_t kMessageHash = base::MD5Hash32Constexpr( "(Impl)math::Calculator::Multiply"); base::TaskAnnotator::ScopedSetIpcHash scoped_ipc_hash(kMessageHash); if (!message->is_serialized()) { auto context = message->TakeUnserializedContext< CalculatorProxy_Multiply_Message>(); if (!context) { // The Message was not of the expected type. It may be a valid message // which was built using a different variant of these bindings. Force // serialization before dispatch in this case. message->SerializeIfNecessary(); } else { Calculator::MultiplyCallback callback = Calculator_Multiply_ProxyToResponder::CreateCallback( message->request_id(), message_is_sync, &responder); context->Dispatch(message, impl, std::move(callback)); return true; } } internal::Calculator_Multiply_Params_Data* params = reinterpret_cast< internal::Calculator_Multiply_Params_Data*>( message->mutable_payload()); bool success = true; double p_value{}; Calculator_Multiply_ParamsDataView input_data_view(params, message); if (success) p_value = input_data_view.value(); if (!success) { ReportValidationErrorForMessage( message, mojo::internal::VALIDATION_ERROR_DESERIALIZATION_FAILED, Calculator::Name_, 2, false); return false; } Calculator::MultiplyCallback callback = Calculator_Multiply_ProxyToResponder::CreateCallback( message->request_id(), message_is_sync, &responder); // A null |impl| means no implementation was bound. DCHECK(impl); impl->Multiply( std::move(p_value), std::move(callback)); return true; } } return false; } static const mojo::internal::GenericValidationInfo kCalculatorValidationInfo[] = { {&internal::Calculator_Clear_Params_Data::Validate, &internal::Calculator_Clear_ResponseParams_Data::Validate}, {&internal::Calculator_Add_Params_Data::Validate, &internal::Calculator_Add_ResponseParams_Data::Validate}, {&internal::Calculator_Multiply_Params_Data::Validate, &internal::Calculator_Multiply_ResponseParams_Data::Validate}, }; bool CalculatorRequestValidator::Accept(mojo::Message* message) { const char* name = ::math::Calculator::Name_; return mojo::internal::ValidateRequestGenericPacked(message, name, kCalculatorValidationInfo); } bool CalculatorResponseValidator::Accept(mojo::Message* message) { const char* name = ::math::Calculator::Name_; return mojo::internal::ValidateResponseGenericPacked(message, name, kCalculatorValidationInfo); } } // namespace math namespace mojo { } // namespace mojo #if defined(__clang__) #pragma clang diagnostic pop #endifclass Solution { public: int countKDifference(vector& nums, int k) { const int N = nums.size(); vector sortedNums(nums.begin(), nums.end()); sort(sortedNums.begin(), sortedNums.end()); int pairsCount = 0; for(int i = 0; i < N; ++i){ auto it1 = lower_bound(sortedNums.begin() + i, sortedNums.end(), sortedNums[i] + k); auto it2 = upper_bound(sortedNums.begin() + i, sortedNums.end(), sortedNums[i] + k); if(it1 != sortedNums.end() && *it1 == sortedNums[i] + k){ pairsCount += (it2 - it1); } } return pairsCount; } };/* * Copyright (c) 2001-2008 * DecisionSoft Limited. All rights reserved. * Copyright (c) 2004-2008 * Oracle. 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. * * $Id$ */ #ifndef XQDOCUMENTCONSTRUCTOR_HPP #define XQDOCUMENTCONSTRUCTOR_HPP #include #include class XQILLA_API XQDocumentConstructor : public XQDOMConstructor { public: XQDocumentConstructor(ASTNode *value, XPath2MemoryManager* expr); virtual EventGenerator::Ptr generateEvents(EventHandler *events, DynamicContext *context, bool preserveNS, bool preserveType) const; virtual ASTNode *staticResolution(StaticContext *context); virtual ASTNode *staticTypingImpl(StaticContext *context); virtual const XMLCh* getNodeType() const; virtual ASTNode *getValue() const; virtual void setValue(ASTNode *value); protected: ASTNode *m_value; }; class DocConstructFilter : public EventFilter { public: DocConstructFilter(EventHandler *next, const LocationInfo *location); virtual void startElementEvent(const XMLCh *prefix, const XMLCh *uri, const XMLCh *localname); virtual void endElementEvent(const XMLCh *prefix, const XMLCh *uri, const XMLCh *localname, const XMLCh *typeURI, const XMLCh *typeName); virtual void attributeEvent(const XMLCh *prefix, const XMLCh *uri, const XMLCh *localname, const XMLCh *value, const XMLCh *typeURI, const XMLCh *typeName); virtual void namespaceEvent(const XMLCh *prefix, const XMLCh *uri); private: const LocationInfo *location_; unsigned int level_; }; #endif RAVL2/MSVC/include/Ravl/Image/PointTrack.hh0 #include "../.././Image/Processing/Tracking/PointTrack.hh" // Functions for the class to manage projected // benefit increases stored in arrays. // // $Id: biprojnf.cpp 1.81 2019/10/28 10:27:09EDT 277133 Development $ #include #include "BiprojNonFile.h" #include "Resource.h" #include "PiaException.h" #include "AssumptionType.h" #include "BaseYearNonFile.h" #include "AwbiDataNonFile.h" #include "oactcnst.h" using namespace std; // Titles for 2019 Trustees Report const string BiprojNonFile::titletrOriginal[NUMASSUMSETS] = { "2019 Trustees Report Alternative I, updated October 10, 2019", "2019 Trustees Report Alternative II, updated October 10, 2019", "2019 Trustees Report Alternative III, updated October 10, 2019", "No increase beginning with 2020 benefit increase" }; // Benefit increases for 2019 Trustees Report, 2020 to 2034 const double BiprojNonFile::biprojtrOriginal[NUMASSUMSETS][NUMPROJYEARS] = { { 3.2, 3.2, 3.2, 3.2, 3.2, 3.2, 3.2, 3.2, 3.2, 3.2, 3.2, 3.2, 3.2, 3.2, 3.2 }, { 2.7, 2.6, 2.6, 2.6, 2.6, 2.6, 2.6, 2.6, 2.6, 2.6, 2.6, 2.6, 2.6, 2.6, 2.6 }, { 2.1, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.1 }, { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 } }; // Ultimate benefit increases for 2019 Trustees Report. const double BiprojNonFile::biult[NUMASSUMSETS] = { 3.2, 2.6, 2.0, 0.0 }; /// Initializes projected benefit increase info for latest Trustees /// Report. /// /// Creates the arrays of Trustees Report benefit increases. /// /// Starting year of benefit increases. /// Maximum projected year. BiprojNonFile::BiprojNonFile( int newIstart, int newMaxyear ) : Biproj(newIstart, newMaxyear) { // Set last year of projected benefit increases, inclusive of YEAR. const int LASTYEAR = BaseYearNonFile::YEAR + NUMPROJYEARS - 1; // ensure bounds are great enough to hold data const int i1 = min(YEAR79, newIstart); const int i2 = max(LASTYEAR, newMaxyear); for (int i = 0; i < NUMASSUMSETS; i++) { biprojtr[i] = new DoubleAnnual(i1, i2); DoubleAnnual& temp = *biprojtr[i]; // Set historical data for (int year = YEAR79; year < BaseYearNonFile::YEAR; year++) { temp[year] = AwbiDataNonFile::getCpiincData(year); } // set title and projected values read(i+1); } } /// Destructor. /// /// Deletes the arrays of Trustees Report benefit increases. BiprojNonFile::~BiprojNonFile() { for (int i = 0; i < NUMASSUMSETS; i++) { delete biprojtr[i]; } } /// Restore values to original values. /// /// Desired alternative number (1-4). void BiprojNonFile::read( int altNum ) { try { // set title titletr[altNum - 1] = titletrOriginal[altNum - 1]; // Set last year of projected benefit increases, inclusive of YEAR. const int LASTYEAR = BaseYearNonFile::YEAR + NUMPROJYEARS - 1; // set values in short-range DoubleAnnual& temp = *biprojtr[altNum - 1]; for (int year = BaseYearNonFile::YEAR; year <= LASTYEAR; year++) { temp[year] = biprojtrOriginal[altNum - 1][year - BaseYearNonFile::YEAR]; } // set values in long-range for (int year = LASTYEAR + 1; year <= temp.getLastYear(); year++) { temp[year] = biult[altNum - 1]; } } catch (PiaException& e) { throw PiaException(string("In BiprojNonFile::read: ") + e.what()); } } /// Dummy function. void BiprojNonFile::write( int ) { } /// Sets data for one alternative. /// /// This version has one argument uses the data stored /// for the specified alternative. /// /// Desired alternative number (1-7). void BiprojNonFile::setData( int altNum ) { const int i1 = max(getFirstYear(), theData.getBaseYear()); if (AssumptionType::isTR(altNum)) { theData.assign(*biprojtr[altNum - 1], i1, theData.getLastYear()); } else { theData.assign(0.0, i1, theData.getLastYear()); } } /// Sets data for one alternative. /// /// This version has two arguments stores the data for the /// specified alternative, then sets the current data to that data. /// /// Desired alternative number (1-7). /// Data to use. void BiprojNonFile::setData( int altNum, const DoubleAnnual& newData ) { if (AssumptionType::isTR(altNum)) { biprojtr[altNum - 1]->assign(newData, getFirstYear(), biprojtr[altNum - 1]->getLastYear()); } setData(altNum); } /// Sets the current title. /// /// This version has one argument uses the title stored /// for the specified alternative. /// /// Desired alternative number (1-7). void BiprojNonFile::setTitle( int altNum ) { if (AssumptionType::isNotTR(altNum)) { biprojTitle = beninc[altNum - AssumptionType::FLAT]; } else { biprojTitle = titletr[altNum - 1]; } } /// Sets the current title. /// /// This version has two arguments stores the title for /// the specified alternative, then sets the current title to /// that title. /// /// Desired alternative number (1-7). /// Title to use. void BiprojNonFile::setTitle( int altNum, const std::string& newTitle ) { if (AssumptionType::isNotTR(altNum)) { biprojTitle = beninc[altNum - AssumptionType::FLAT]; } else { titletr[altNum - 1] = newTitle; biprojTitle = titletr[altNum - 1]; } } /* Copyright (C) 2018, Accelize 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 "accelize/drm/session_manager.h" #include "accelize/drm/version.h" #include "ws_client.h" #include "log.h" #include "utils.h" #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-parameter" #include "HAL/DrmControllerOperations.hpp" #pragma GCC diagnostic pop namespace Accelize { namespace DRMLib { class DRMLIB_LOCAL MeteringSessionManager::Impl { protected: //helper typedef typedef std::chrono::steady_clock Clock; // use steady clock to be monotonic (were are not affected by clock adjustements) //compisition std::unique_ptr mWsClient; std::unique_ptr mDrmController; std::mutex mDrmControllerMutex; //function callbacks MeteringSessionManager::ReadReg32ByOffsetHandler f_read32_offset; MeteringSessionManager::WriteReg32ByOffsetHandler f_write32_offset; MeteringSessionManager::ReadReg32ByNameHandler f_read32_name; MeteringSessionManager::WriteReg32ByNameHandler f_write32_name; MeteringSessionManager::ErrorCallBackHandler f_error_cb; //params std::chrono::seconds minimum_license_duration; //state // of licenses on DRM controller Clock::duration next_license_duration = Clock::duration::zero(); bool next_license_duration_exact=false; Clock::duration current_license_duration = Clock::duration::zero(); bool current_license_duration_exact=false; Clock::time_point sync_license_timepoint; bool sync_license_timepoint_exact=false; //session state bool sessionStarted{false}; std::string sessionID; std::string udid; std::string boardType; // thread to maintain alive std::future threadKeepAlive; std::mutex threadKeepAlive_mtx; std::condition_variable threadKeepAlive_cv; bool threadKeepAlive_stop{false}; Impl(ErrorCallBackHandler f_error_cb) : f_error_cb(f_error_cb) { } Impl(const std::string& conf_file_path, const std::string& cred_file_path, ErrorCallBackHandler f_error_cb) : f_error_cb(f_error_cb) { Json::Reader reader; Json::Value conf_json; std::ifstream conf_fd(conf_file_path); if(!reader.parse(conf_fd, conf_json)) Throw(DRMBadFormat, "Cannot parse ", conf_file_path, " : ", reader.getFormattedErrorMessages()); Json::Value conf_server_json = JVgetRequired(conf_json, "webservice", Json::objectValue); minimum_license_duration = std::chrono::seconds( JVgetOptional(conf_server_json, "minimum_license_duration", Json::uintValue, 300).asUInt() ); Json::Value conf_design = JVgetOptional(conf_json, "design", Json::objectValue); if(!conf_design.isNull()) { udid = JVgetOptional(conf_design, "udid", Json::stringValue, "").asString(); boardType = JVgetOptional(conf_design, "boardType", Json::stringValue, "").asString(); } Json::Value credentials; std::ifstream cred_fd(cred_file_path); if(!reader.parse(cred_fd, credentials)) Throw(DRMBadFormat, "Cannot parse ", cred_file_path, " : ", reader.getFormattedErrorMessages()); mWsClient.reset(new MeteringWSClient(conf_server_json, credentials)); } DrmControllerLibrary::DrmControllerOperations& getDrmController() { Assert(mDrmController); return *mDrmController; } MeteringWSClient& getMeteringWSClient() { if(!mWsClient) Throw(DRMBadUsage, "Metering Session Manager constructed with no WebService configuration"); return *mWsClient; } static uint32_t drm_register_name_to_offset(const std::string& regName) { if(regName == "DrmPageRegister") return 0; if(regName.substr(0, 15) == "DrmRegisterLine") return std::stoi(regName.substr(15))*4+4; Unreachable(); } unsigned int drm_read_register(const std::string& regName, unsigned int& value) { unsigned int ret = 0; if(f_read32_name) { ret = f_read32_name(regName, &value); } else if(f_read32_offset) { ret = f_read32_offset(drm_register_name_to_offset(regName), &value); } else { Unreachable(); } if(ret != 0) { Error("Error in read register callback, errcode = ", ret); return -1; } else { Debug2("Read DRM register @", regName, " = 0x", std::hex, value); return 0; } } unsigned int drm_write_register(const std::string& regName, unsigned int value) { unsigned int ret = 0; if(f_write32_name) { ret = f_write32_name(regName, value); } else if(f_write32_offset) { ret = f_write32_offset(drm_register_name_to_offset(regName), value); } else { Unreachable(); } if(ret != 0) { Error("Error in write register callback, errcode = ", ret); return -1; } else { Debug2("Write DRM register @", regName, " = 0x", std::hex, value); return 0; } } void checkDRMCtlrRet(unsigned int errcode) { if(errcode) Throw(DRMExternFail, "Error in DRMCtlrLib function call : ", errcode); } void getMeteringHead(Json::Value& json_output) { std::lock_guard lk(mDrmControllerMutex); unsigned int nbOfDetectedIps; std::string drmVersion, dna; std::vector vlnvFile; // Get common info checkDRMCtlrRet( getDrmController().extractDrmVersion( drmVersion ) ); checkDRMCtlrRet( getDrmController().extractDna( dna ) ); checkDRMCtlrRet( getDrmController().extractVlnvFile( nbOfDetectedIps, vlnvFile ) ); // Put it in Json output val json_output["drmlibVersion"] = getVersion(); json_output["lgdnVersion"] = drmVersion; json_output["dna"] = dna; for(unsigned int i=0; i lk(mDrmControllerMutex); unsigned int numberOfDetectedIps; std::string saasChallenge; std::vector meteringFile; checkDRMCtlrRet( getDrmController().initialization( numberOfDetectedIps, saasChallenge, meteringFile ) ); json_output["saasChallenge"] = saasChallenge; json_output["meteringFile"] = std::accumulate(meteringFile.begin(), meteringFile.end(), std::string("")); json_output["request"] = "open"; } void getMeteringStop(Json::Value& json_output) { std::lock_guard lk(mDrmControllerMutex); unsigned int numberOfDetectedIps; std::string saasChallenge; std::vector meteringFile; checkDRMCtlrRet( getDrmController().endSessionAndExtractMeteringFile( numberOfDetectedIps, saasChallenge, meteringFile ) ); json_output["saasChallenge"] = saasChallenge; json_output["meteringFile"] = std::accumulate(meteringFile.begin(), meteringFile.end(), std::string("")); json_output["request"] = "close"; } void getMeteringWait(unsigned int timeOut, Json::Value& json_output) { std::lock_guard lk(mDrmControllerMutex); unsigned int numberOfDetectedIps; std::string saasChallenge; std::vector meteringFile; checkDRMCtlrRet( getDrmController().extractMeteringFile( timeOut, numberOfDetectedIps, saasChallenge, meteringFile ) ); json_output["saasChallenge"] = saasChallenge; json_output["meteringFile"] = std::accumulate(meteringFile.begin(), meteringFile.end(), std::string("")); json_output["request"] = "running"; } #define DO_WITH_LOCK(expr) [this](){ \ std::lock_guard lk(mDrmControllerMutex); \ return expr; \ }() bool isReadyForNewLicense_no_lock() { bool ret; checkDRMCtlrRet( getDrmController().writeRegistersPageRegister() ); checkDRMCtlrRet( getDrmController().readStatusRegister(DrmControllerLibrary::mDrmStatusLicenseTimerInitLoaded, DrmControllerLibrary::mDrmStatusMaskLicenseTimerInitLoaded, ret)); return !ret; } void setLicense(const Json::Value& json_license) { Debug("Installing next license on DRM controller"); std::lock_guard lk(mDrmControllerMutex); // get DNA std::string dna; checkDRMCtlrRet( getDrmController().extractDna( dna ) ); // Get license/license timer from webservice response std::string license = json_license["license"][dna]["key"].asString(); std::string licenseTimer = json_license["license"][dna]["licenseTimer"].asString(); if( license.empty() ) Throw(DRMWSRespError, "Malformed response from Accelize WebService : license key is empty"); if( licenseTimer.empty() ) Throw(DRMWSRespError, "Malformed response from Accelize WebService : LicenseTimer is empty"); // Activate bool activationDone = false; unsigned char activationErrorCode; checkDRMCtlrRet( getDrmController().activate( license, activationDone, activationErrorCode ) ); if( activationErrorCode ) { Throw(DRMCtlrError, "Failed to activate license on DRM controller, activationErr: 0x", std::hex, activationErrorCode); } // Load license timer bool licenseTimerEnabled = false; checkDRMCtlrRet( getDrmController().loadLicenseTimerInit( licenseTimer, licenseTimerEnabled ) ); if ( !licenseTimerEnabled ) { Throw(DRMCtlrError, "Failed to load license timer on DRM controller, licenseTimerEnabled: 0x", std::hex, licenseTimerEnabled); } WarningAssertGreaterEqual(json_license["metering"]["timeoutSecond"].asUInt(), minimum_license_duration.count()); next_license_duration = std::chrono::seconds(json_license["metering"]["timeoutSecond"].asUInt()); next_license_duration_exact = true; debug_print_drm_hw_report(); } void clearLicense() { std::lock_guard lk(mDrmControllerMutex); static const std::string nullLicense(352, '0'); checkDRMCtlrRet( getDrmController().writeLicenseFilePageRegister() ); checkDRMCtlrRet( getDrmController().writeLicenseFileRegister(nullLicense) ); Assert(!isLicense_no_lock()); } bool isLicense_no_lock() { checkDRMCtlrRet( getDrmController().writeRegistersPageRegister() ); unsigned char err; checkDRMCtlrRet( getDrmController().readErrorRegister( DrmControllerLibrary::mDrmActivationErrorPosition, DrmControllerLibrary::mDrmActivationErrorMask, err)); return (err == DrmControllerLibrary::mDrmErrorNoError); } void debug_print_drm_hw_report() { /* This function must be used with mDrmControllerMutex locked */ if(!isDebug()) return; std::stringstream ss; getDrmController().printHwReport(ss); Debug("Dump DRM controller : ", ss.str()); } template< class Clock, class Duration > bool thread_wait_until_is_stop(const std::chrono::time_point& timeout_time) { std::unique_lock lk(threadKeepAlive_mtx); return threadKeepAlive_cv.wait_until(lk, timeout_time, [this]{return threadKeepAlive_stop;}); } template< class Rep, class Period > bool thread_wait_for_is_stop( const std::chrono::duration& rel_time ) { std::unique_lock lk(threadKeepAlive_mtx); return threadKeepAlive_cv.wait_for(lk, rel_time, [this]{return threadKeepAlive_stop;}); } bool thread_notwait_is_stop() { std::lock_guard lk(threadKeepAlive_mtx); return threadKeepAlive_stop; } void thread_start() { if(threadKeepAlive.valid()) Error("Thread already started"); threadKeepAlive = std::async(std::launch::async, [this](){ try{ while(1) { bool wbtd_expected_time_exact = false; // wbtd = wrong board type detection Clock::time_point wbtd_expected_time; bool waited_readiness = false; Clock::time_point time_of_synchro; if(next_license_duration_exact && sync_license_timepoint_exact) { wbtd_expected_time = sync_license_timepoint + next_license_duration; wbtd_expected_time_exact = true; } while(!DO_WITH_LOCK(isReadyForNewLicense_no_lock())) { waited_readiness = true; if(thread_wait_for_is_stop(std::chrono::seconds(1))) return; } if(waited_readiness) time_of_synchro = Clock::now(); // Step the license model { if(waited_readiness) { sync_license_timepoint = time_of_synchro; sync_license_timepoint_exact = true; } else { sync_license_timepoint += current_license_duration; sync_license_timepoint_exact = sync_license_timepoint_exact && current_license_duration_exact; } current_license_duration = next_license_duration; current_license_duration_exact = next_license_duration_exact; } // Wrong board type detection if(waited_readiness && wbtd_expected_time_exact) { auto diff = wbtd_expected_time - time_of_synchro; auto diff_abs = diff >= diff.zero() ? diff : -diff; if( diff_abs > std::chrono::seconds(2) ) Warning("Wrong board type detection, please check your configuration"); } if(thread_notwait_is_stop()) return; Json::Value json_req; Debug("Get metering from session on DRM controller"); getMeteringHead(json_req); try{ getMeteringWait(1, json_req); } catch(const DrmControllerLibrary::DrmControllerTimeOutException& e) { Unreachable(); //we have checked isReadyForNewLicense_no_lock, should not block } json_req["sessionId"] = sessionID; Json::Value json_license; Clock::time_point min_polling_deadline = sync_license_timepoint + current_license_duration; /* we can try polling until this deadline */ unsigned int retry_index = 0; Clock::time_point start_of_retry = Clock::now(); while(1) { /* Retry WS request */ if(min_polling_deadline <= Clock::now()) { Throw(DRMWSError, "Failed to obtain license from WS on time, the protected IP may have been locked"); } if(thread_notwait_is_stop()) return; std::string retry_msg; try { json_license = getMeteringWSClient().getLicense(json_req, min_polling_deadline); break; }catch(const Exception& e) { if(e.getErrCode() != DRMWSMayRetry) throw; else { retry_msg = e.what(); } } retry_index++; Clock::duration retry_wait_duration; if((Clock::now() - start_of_retry) <= std::chrono::seconds(60)) retry_wait_duration = std::chrono::seconds(2); else retry_wait_duration = std::chrono::seconds(30); if((Clock::now() + retry_wait_duration + std::chrono::seconds(2)) >= min_polling_deadline) retry_wait_duration = min_polling_deadline - Clock::now() - std::chrono::seconds(2); if(retry_wait_duration <= decltype(retry_wait_duration)::zero()) retry_wait_duration = std::chrono::seconds(0); Warning("Failed to obtain license from WS (", retry_msg, "), will retry in ", std::chrono::duration_cast(retry_wait_duration).count(), " seconds"); if(thread_wait_for_is_stop(retry_wait_duration)) return; } setLicense(json_license); if(!sessionID.empty() && sessionID!=json_license["metering"]["sessionId"].asString()) { Error("sessionID has changed since begininning of sessions (old=", sessionID, " new=", json_license["metering"]["sessionId"].asString(),")"); } sessionID = json_license["metering"]["sessionId"].asString(); unsigned int licenseTimeout = json_license["metering"]["timeoutSecond"].asUInt(); Info("Uploaded metering for sessionId ", sessionID, " and set next license with duration of ", std::dec, licenseTimeout, " seconds"); if(thread_notwait_is_stop()) return; } } catch(const std::exception& e) { Error(e.what()); f_error_cb(std::string(e.what())); } }); } void thread_stop() { if(!threadKeepAlive.valid()) return; { std::lock_guard lk(threadKeepAlive_mtx); threadKeepAlive_stop = true; } threadKeepAlive_cv.notify_all(); threadKeepAlive.wait(); } public: Impl(const std::string& conf_file_path, const std::string& cred_file_path, ReadReg32ByOffsetHandler f_drm_read32, WriteReg32ByOffsetHandler f_drm_write32, ErrorCallBackHandler f_error_cb) : Impl(conf_file_path, cred_file_path, f_error_cb) { f_read32_offset = f_drm_read32; f_write32_offset = f_drm_write32; init(); } Impl(const std::string& conf_file_path, const std::string& cred_file_path, ReadReg32ByNameHandler f_drm_read32, WriteReg32ByNameHandler f_drm_write32, ErrorCallBackHandler f_error_cb) : Impl(conf_file_path, cred_file_path, f_error_cb) { f_read32_name = f_drm_read32; f_write32_name = f_drm_write32; init(); } Impl(ReadReg32ByOffsetHandler f_drm_read32, WriteReg32ByOffsetHandler f_drm_write32, ErrorCallBackHandler f_error_cb) : Impl(f_error_cb) { f_read32_offset = f_drm_read32; f_write32_offset = f_drm_write32; init(); } Impl(ReadReg32ByNameHandler f_drm_read32, WriteReg32ByNameHandler f_drm_write32, ErrorCallBackHandler f_error_cb) : Impl(f_error_cb) { f_read32_name = f_drm_read32; f_write32_name = f_drm_write32; init(); } ~Impl() { thread_stop(); } //non copyable non movable as we create closure with "this" Impl(const Impl&) = delete; Impl(Impl&&) = delete; void setUdid(const std::string& _udid){ udid = _udid; } void setBoardType(const std::string& _boardType){ boardType = _boardType; } void init() { if(mDrmController) return; // create instance mDrmController.reset( new DrmControllerLibrary::DrmControllerOperations( std::bind(&MeteringSessionManager::Impl::drm_read_register, this, std::placeholders::_1, std::placeholders::_2), std::bind(&MeteringSessionManager::Impl::drm_write_register, this, std::placeholders::_1, std::placeholders::_2 ) )); } void auto_start_session() { // Detect if session was previously stopped if(!DO_WITH_LOCK(isLicense_no_lock())) start_session(); else resume_session(); } void start_session() { if(sessionStarted) Throw(DRMBadArg, "Error : session already started"); Json::Value json_req; Info("Starting metering session..."); getMeteringHead(json_req); getMeteringStart(json_req); Json::Value json_license = getMeteringWSClient().getLicense(json_req); setLicense(json_license); sessionID = json_license["metering"]["sessionId"].asString(); //init license model sync_license_timepoint = Clock::now(); sync_license_timepoint_exact = true; current_license_duration = decltype(current_license_duration)::zero(); current_license_duration_exact = true; unsigned int licenseTimeout = json_license["metering"]["timeoutSecond"].asUInt(); Info("Started new metering session with sessionId ", sessionID, " and set first license with duration of ", std::dec, licenseTimeout, " seconds"); sessionStarted = true; thread_start(); } void stop_session() { Info("Stopping metering session..."); thread_stop(); Json::Value json_req; Debug("Get last metering data from session on DRM controller"); getMeteringHead(json_req); getMeteringStop(json_req); json_req["sessionId"] = sessionID; getMeteringWSClient().getLicense(json_req); clearLicense(); Info("Stopped metering session with sessionId ", sessionID, " and uploaded last metering data"); sessionStarted = false; } void resume_session() { Info("Resuming metering session..."); if(DO_WITH_LOCK(isReadyForNewLicense_no_lock())) { Json::Value json_req; getMeteringHead(json_req); try{ getMeteringWait(1, json_req); } catch(const DrmControllerLibrary::DrmControllerTimeOutException& e) { Unreachable(); //we have checked isReadyForNewLicense, should not block } json_req["sessionId"] = sessionID; Json::Value json_license = getMeteringWSClient().getLicense(json_req); setLicense(json_license); sessionID = json_license["metering"]["sessionId"].asString(); sync_license_timepoint = Clock::now(); sync_license_timepoint_exact = false; current_license_duration_exact = false; unsigned int licenseTimeout = json_license["metering"]["timeoutSecond"].asUInt(); Info("Resumed metering session with sessionId ", sessionID, " and set first license with duration of ", std::dec, licenseTimeout, " seconds"); } else { next_license_duration = minimum_license_duration; next_license_duration_exact = false; sync_license_timepoint = Clock::now(); sync_license_timepoint_exact = false; current_license_duration_exact = false; } sessionStarted = true; thread_start(); } void pause_session() { Info("Pausing metering session..."); thread_stop(); sessionStarted = false; } void dump_drm_hw_report(std::ostream& os) { std::lock_guard lk(mDrmControllerMutex); getDrmController().printHwReport(os); } }; MeteringSessionManager::MeteringSessionManager(const std::string& conf_file_path, const std::string& cred_file_path, ReadReg32ByOffsetHandler f_drm_read32, WriteReg32ByOffsetHandler f_drm_write32, ErrorCallBackHandler f_error_cb) : pImpl(new Impl(conf_file_path, cred_file_path, f_drm_read32, f_drm_write32, f_error_cb)) { } MeteringSessionManager::MeteringSessionManager(const std::string& conf_file_path, const std::string& cred_file_path, ReadReg32ByNameHandler f_drm_read32, WriteReg32ByNameHandler f_drm_write32, ErrorCallBackHandler f_error_cb) : pImpl(new Impl(conf_file_path, cred_file_path, f_drm_read32, f_drm_write32, f_error_cb)) { } MeteringSessionManager::MeteringSessionManager(ReadReg32ByOffsetHandler f_drm_read32, WriteReg32ByOffsetHandler f_drm_write32, ErrorCallBackHandler f_error_cb) : pImpl(new Impl(f_drm_read32, f_drm_write32, f_error_cb)) { } MeteringSessionManager::MeteringSessionManager(ReadReg32ByNameHandler f_drm_read32, WriteReg32ByNameHandler f_drm_write32, ErrorCallBackHandler f_error_cb) : pImpl(new Impl(f_drm_read32, f_drm_write32, f_error_cb)) { } MeteringSessionManager::~MeteringSessionManager() { delete pImpl; } void MeteringSessionManager::start_session() { pImpl->start_session(); } void MeteringSessionManager::auto_start_session() { pImpl->auto_start_session(); } void MeteringSessionManager::resume_session() { pImpl->resume_session(); } void MeteringSessionManager::pause_session() { pImpl->pause_session(); } void MeteringSessionManager::stop_session() { pImpl->stop_session(); } void MeteringSessionManager::dump_drm_hw_report(std::ostream& os) { pImpl->dump_drm_hw_report(os); } void MeteringSessionManager::setUdid(const std::string& udid){ pImpl->setUdid(udid); } void MeteringSessionManager::setBoardType(const std::string& boardType){ pImpl->setBoardType(boardType); } } } danielga/multilibrary /************************************************************************* * MultiLibrary - https://danielga.github.io/multilibrary/ * A C++ library that covers multiple low level systems. *------------------------------------------------------------------------ * Copyright (c) 2014-2022, * 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 #if defined _WIN32 #include #include #include #define GetSocketError( ) WSAGetLastError( ) #elif defined __APPLE__ || defined __linux #include #include #include #include #include #include #include #include #define INVALID_SOCKET ( -1 ) #define SOCKET_ERROR ( -1 ) #define GetSocketError( ) errno #define closesocket close #define ioctlsocket ioctl #endif namespace MultiLibrary { #if defined _WIN32 namespace Internal { class WSAInitializer { public: WSAInitializer( ) { WSADATA wsa_data; if( WSAStartup( MAKEWORD( 2, 2 ), &wsa_data ) != 0 ) throw std::runtime_error( "WSAStartup failed" ); else if( LOBYTE( wsa_data.wVersion ) != 2 || HIBYTE( wsa_data.wVersion ) != 2 ) throw std::runtime_error( "could not find a usable version of winsock.dll" ); } ~WSAInitializer( ) { WSACleanup( ); } }; static WSAInitializer wsa_init; } #endif // _WIN32 Socket::Socket( IPAddressFamily family ) : socket_id( INVALID_SOCKET ), address_family( family ), is_blocking( true ) { } Socket::~Socket( ) { Close( ); } SocketError Socket::Accept( Socket &socket, IPAddress &address ) { if( !IsValid( ) ) return ENOTSOCK; address.SetFamily( address_family ); socklen_t address_size = static_cast( address.GetAddressSize( ) ); SocketHandle newSocket = accept( socket_id, address.GetSocketAddress( ), &address_size ); if( newSocket != INVALID_SOCKET ) socket.socket_id = newSocket; return newSocket == INVALID_SOCKET ? GetSocketError( ) : 0; } SocketError Socket::Bind( const IPAddress &address ) { if( !IsValid( ) ) return ENOTSOCK; int32_t ret = bind( socket_id, address.ToSocketAddress( ), static_cast( address.GetAddressSize( ) ) ); return ret == SOCKET_ERROR ? GetSocketError( ) : 0; } bool Socket::CanRead( ) { if( !IsValid( ) ) return false; fd_set set; FD_ZERO( &set ); FD_SET( socket_id, &set ); timeval wait = { 0, 0 }; return select( static_cast( socket_id ) + 1, &set, 0, 0, &wait ) > 0; } bool Socket::CanWrite( ) { if( !IsValid( ) ) return false; fd_set set; FD_ZERO( &set ); FD_SET( socket_id, &set ); timeval wait = { 0, 0 }; return select( static_cast( socket_id ) + 1, 0, &set, 0, &wait ) > 0; } SocketError Socket::Close( ) { if( !IsValid( ) ) return ENOTSOCK; Shutdown( 2 ); int32_t ret = closesocket( socket_id ); socket_id = INVALID_SOCKET; return ret == SOCKET_ERROR ? GetSocketError( ) : 0; } SocketError Socket::Connect( const IPAddress &address ) { if( !IsValid( ) ) return ENOTSOCK; int32_t ret = connect( socket_id, address.ToSocketAddress( ), static_cast( address.GetAddressSize( ) ) ); return ret == SOCKET_ERROR ? GetSocketError( ) : 0; } IPAddressFamily Socket::GetAddressFamily( ) const { return address_family; } bool Socket::IsValid( ) const { return socket_id != INVALID_SOCKET; } Socket::operator bool( ) const { return IsValid( ); } bool Socket::operator!( ) const { return !IsValid( ); } SocketError Socket::Listen( int32_t max_con_requests ) { if( !IsValid( ) ) return ENOTSOCK; return listen( socket_id, max_con_requests ) == SOCKET_ERROR ? GetSocketError( ) : 0; } bool Socket::Open( ) { return false; } SocketError Socket::Receive( void *buffer, int32_t size, int32_t flags, int32_t *received_bytes ) { if( !IsValid( ) ) return ENOTSOCK; int32_t ret = recv( socket_id, static_cast( buffer ), size, flags ); if( ret != SOCKET_ERROR && received_bytes != nullptr ) *received_bytes = ret; return ret == SOCKET_ERROR ? GetSocketError( ) : 0; } SocketError Socket::Receive( ByteBuffer &buffer, int32_t flags ) { if( !IsValid( ) ) return ENOTSOCK; char *buf = reinterpret_cast( buffer.GetBuffer( ) ); int32_t ret = recv( socket_id, buf, static_cast( buffer.Size( ) ), flags ); if( ret != SOCKET_ERROR ) buffer.Resize( ret ); return ret == SOCKET_ERROR ? GetSocketError( ) : 0; } SocketError Socket::ReceiveFrom( void *buffer, int32_t size, int32_t flags, IPAddress &address, int32_t *received_bytes ) { if( !IsValid( ) ) return ENOTSOCK; address.SetFamily( address_family ); sockaddr *addr = address.GetSocketAddress( ); socklen_t addr_size = static_cast( address.GetAddressSize( ) ); int32_t ret = recvfrom( socket_id, static_cast( buffer ), size, flags, addr, &addr_size ); if( ret != SOCKET_ERROR && received_bytes != nullptr ) *received_bytes = ret; return ret == SOCKET_ERROR ? GetSocketError( ) : 0; } SocketError Socket::ReceiveFrom( ByteBuffer &buffer, int32_t flags, IPAddress &address ) { if( !IsValid( ) ) return ENOTSOCK; char *buf = reinterpret_cast( buffer.GetBuffer( ) ); address.SetFamily( address_family ); sockaddr *addr = address.GetSocketAddress( ); socklen_t addr_size = static_cast( address.GetAddressSize( ) ); int32_t ret = recvfrom( socket_id, buf, static_cast( buffer.Size( ) ), flags, addr, &addr_size ); if( ret != SOCKET_ERROR ) buffer.Resize( ret ); return ret == SOCKET_ERROR ? GetSocketError( ) : 0; } std::string Socket::RemoteAddress( ) const { if( !IsValid( ) ) return ""; return RemoteIPAddress( ).ToString( ); } uint16_t Socket::RemotePort( ) const { if( !IsValid( ) ) return 0; return RemoteIPAddress( ).GetPort( ); } IPAddress Socket::RemoteIPAddress( ) const { if( !IsValid( ) ) return IPAddress( ); IPAddress addr( address_family ); socklen_t addr_size = static_cast( addr.GetAddressSize( ) ); if( getpeername( socket_id, addr.GetSocketAddress( ), &addr_size ) != SOCKET_ERROR ) return addr; return IPAddress( ); } SocketError Socket::Send( const void *buffer, int32_t size, int32_t flags, int32_t *sent_bytes ) { if( !IsValid( ) ) return ENOTSOCK; int32_t ret = send( socket_id, static_cast( buffer ), size, flags ); if( ret != SOCKET_ERROR && sent_bytes != nullptr ) *sent_bytes = ret; return ret == SOCKET_ERROR ? GetSocketError( ) : 0; } SocketError Socket::Send( const ByteBuffer &buffer, int32_t flags, int32_t *sent_bytes ) { if( !IsValid( ) ) return ENOTSOCK; const char *buf = reinterpret_cast( buffer.GetBuffer( ) ); int32_t ret = send( socket_id, buf, static_cast( buffer.Size( ) ), flags ); if( ret != SOCKET_ERROR && sent_bytes != nullptr ) *sent_bytes = ret; return ret == SOCKET_ERROR ? GetSocketError( ) : 0; } SocketError Socket::SendTo( const void *buffer, int32_t size, int32_t flags, const IPAddress &address, int32_t *sent_bytes ) { if( !IsValid( ) ) return ENOTSOCK; const sockaddr *addr = address.ToSocketAddress( ); socklen_t addr_size = static_cast( address.GetAddressSize( ) ); int32_t ret = sendto( socket_id, static_cast( buffer ), size, flags, addr, addr_size ); if( ret != SOCKET_ERROR && sent_bytes != nullptr ) *sent_bytes = ret; return ret == SOCKET_ERROR ? GetSocketError( ) : 0; } SocketError Socket::SendTo( const ByteBuffer &buffer, int32_t flags, const IPAddress &address, int32_t *sent_bytes ) { if( !IsValid( ) ) return ENOTSOCK; const char *buf = reinterpret_cast( buffer.GetBuffer( ) ); const sockaddr *addr = address.ToSocketAddress( ); socklen_t addr_size = static_cast( address.GetAddressSize( ) ); int32_t ret = sendto( socket_id, buf, static_cast( buffer.Size( ) ), flags, addr, addr_size ); if( ret != SOCKET_ERROR && sent_bytes != nullptr ) *sent_bytes = ret; return ret == SOCKET_ERROR ? GetSocketError( ) : 0; } SocketError Socket::SetBlocking( bool block ) { if( !IsValid( ) ) return ENOTSOCK; u_long shouldblock = block ? 0 : 1; int32_t ret = ioctlsocket( socket_id, FIONBIO, &shouldblock ); if( ret != SOCKET_ERROR ) is_blocking = block; return ret == SOCKET_ERROR ? GetSocketError( ) : 0; } SocketError Socket::SetTimeout( uint32_t timeout ) { if( !IsValid( ) ) return ENOTSOCK; #if defined _WIN32 uint32_t time = timeout; #else struct timeval time; time.tv_sec = timeout % 1000; time.tv_usec = ( timeout - time.tv_sec * 1000 ) * 1000; #endif const char *t = reinterpret_cast( &time ); int32_t ret = setsockopt( socket_id, SOL_SOCKET, SO_RCVTIMEO, t, sizeof( time ) ); return ret == SOCKET_ERROR ? GetSocketError( ) : 0; } SocketError Socket::Shutdown( int32_t flags ) { if( !IsValid( ) ) return ENOTSOCK; return shutdown( socket_id, flags ) == SOCKET_ERROR ? GetSocketError( ) : 0; } SocketType Socket::Type( ) const { return INVALID; } } // namespace MultiLibrary // ROS header file #include // Google test header file #include // To be tested header file #include "ros-class-node/node_class.hpp" class node_class_utest : public ::testing::Test { protected: NODE_CLASS::node_class test_node; }; TEST_F(node_class_utest, threshold_test_true) { // Test threshold function int data = 21; bool result = test_node.threshold_function(data); ASSERT_TRUE(result); } TEST_F(node_class_utest, threshold_test_false) { // Test threshold function int data = 20; bool result = test_node.threshold_function(data); ASSERT_FALSE(result); } int main(int argc, char ** argv) { testing::InitGoogleTest(&argc, argv); ros::init(argc, argv, "node_class_test"); return RUN_ALL_TESTS(); }brechtmann/raysrc/ray/core_worker/context.cc // Copyright 2017 The Ray Authors. // // 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 "ray/core_worker/context.h" namespace ray { /// per-thread context for core worker. struct WorkerThreadContext { WorkerThreadContext() : current_task_id_(TaskID::ForFakeTask()), task_index_(0), put_index_(0) {} int GetNextTaskIndex() { return ++task_index_; } int GetNextPutIndex() { return ++put_index_; } const TaskID &GetCurrentTaskID() const { return current_task_id_; } std::shared_ptr GetCurrentTask() const { return current_task_; } void SetCurrentTaskId(const TaskID &task_id) { current_task_id_ = task_id; } void SetCurrentTask(const TaskSpecification &task_spec) { RAY_CHECK(task_index_ == 0); RAY_CHECK(put_index_ == 0); SetCurrentTaskId(task_spec.TaskId()); current_task_ = std::make_shared(task_spec); } void ResetCurrentTask(const TaskSpecification &task_spec) { SetCurrentTaskId(TaskID::Nil()); task_index_ = 0; put_index_ = 0; } private: /// The task ID for current task. TaskID current_task_id_; /// The current task. std::shared_ptr current_task_; /// Number of tasks that have been submitted from current task. int task_index_; /// Number of objects that have been put from current task. int put_index_; }; thread_local std::unique_ptr WorkerContext::thread_context_ = nullptr; WorkerContext::WorkerContext(WorkerType worker_type, const JobID &job_id) : worker_type_(worker_type), worker_id_(worker_type_ == WorkerType::DRIVER ? ComputeDriverIdFromJob(job_id) : WorkerID::FromRandom()), current_job_id_(worker_type_ == WorkerType::DRIVER ? job_id : JobID::Nil()), current_actor_id_(ActorID::Nil()), main_thread_id_(boost::this_thread::get_id()) { // For worker main thread which initializes the WorkerContext, // set task_id according to whether current worker is a driver. // (For other threads it's set to random ID via GetThreadContext). GetThreadContext().SetCurrentTaskId((worker_type_ == WorkerType::DRIVER) ? TaskID::ForDriverTask(job_id) : TaskID::Nil()); } const WorkerType WorkerContext::GetWorkerType() const { return worker_type_; } const WorkerID &WorkerContext::GetWorkerID() const { return worker_id_; } int WorkerContext::GetNextTaskIndex() { return GetThreadContext().GetNextTaskIndex(); } int WorkerContext::GetNextPutIndex() { return GetThreadContext().GetNextPutIndex(); } const JobID &WorkerContext::GetCurrentJobID() const { return current_job_id_; } const TaskID &WorkerContext::GetCurrentTaskID() const { return GetThreadContext().GetCurrentTaskID(); } void WorkerContext::SetCurrentJobId(const JobID &job_id) { current_job_id_ = job_id; } void WorkerContext::SetCurrentTaskId(const TaskID &task_id) { GetThreadContext().SetCurrentTaskId(task_id); } void WorkerContext::SetCurrentTask(const TaskSpecification &task_spec) { GetThreadContext().SetCurrentTask(task_spec); if (task_spec.IsNormalTask()) { RAY_CHECK(current_job_id_.IsNil()); SetCurrentJobId(task_spec.JobId()); current_task_is_direct_call_ = task_spec.IsDirectCall(); } else if (task_spec.IsActorCreationTask()) { RAY_CHECK(current_job_id_.IsNil()); SetCurrentJobId(task_spec.JobId()); RAY_CHECK(current_actor_id_.IsNil()); current_actor_id_ = task_spec.ActorCreationId(); current_actor_is_direct_call_ = task_spec.IsDirectActorCreationCall(); current_actor_max_concurrency_ = task_spec.MaxActorConcurrency(); current_actor_is_asyncio_ = task_spec.IsAsyncioActor(); } else if (task_spec.IsActorTask()) { RAY_CHECK(current_job_id_ == task_spec.JobId()); RAY_CHECK(current_actor_id_ == task_spec.ActorId()); } else { RAY_CHECK(false); } } void WorkerContext::ResetCurrentTask(const TaskSpecification &task_spec) { GetThreadContext().ResetCurrentTask(task_spec); if (task_spec.IsNormalTask()) { SetCurrentJobId(JobID::Nil()); } } std::shared_ptr WorkerContext::GetCurrentTask() const { return GetThreadContext().GetCurrentTask(); } const ActorID &WorkerContext::GetCurrentActorID() const { return current_actor_id_; } bool WorkerContext::CurrentThreadIsMain() const { return boost::this_thread::get_id() == main_thread_id_; } bool WorkerContext::ShouldReleaseResourcesOnBlockingCalls() const { // Check if we need to release resources when we block: // - Driver doesn't acquire resources and thus doesn't need to release. // - We only support lifetime resources for direct actors, which can be // acquired when the actor is created, per call resources are not supported, // thus we don't need to release resources for direct actor call. return worker_type_ != WorkerType::DRIVER && !CurrentActorIsDirectCall() && CurrentThreadIsMain(); } bool WorkerContext::CurrentActorIsDirectCall() const { return current_actor_is_direct_call_; } bool WorkerContext::CurrentTaskIsDirectCall() const { return current_task_is_direct_call_ || current_actor_is_direct_call_; } int WorkerContext::CurrentActorMaxConcurrency() const { return current_actor_max_concurrency_; } bool WorkerContext::CurrentActorIsAsync() const { return current_actor_is_asyncio_; } WorkerThreadContext &WorkerContext::GetThreadContext() { if (thread_context_ == nullptr) { thread_context_ = std::unique_ptr(new WorkerThreadContext()); } return *thread_context_; } } // namespace ray #include using namespace std; int nz(int n){ int s=0, div=5; while(div<=n){ s+=(n/div); div*=5; } return s; } int main() { int n; cin>>n; cout<immsocket/ImmSocketClient.cpp #include #include #include #include #include #include #include #include #include #include #include #include "WorkerThread.h" #include "ImmSocketClient.h" #include "Utils.h" namespace ImmSocket { #if 0 CImmSocketClient::CImmSocketClient (void) : mIsStop (false), mState (EN_RECEIVE_STATE_STANDBY__WAIT_SOH), mFdClientSocket (0), mCurrentPacketWritePos (0), mCurrentPacketDataSize(0), mpPacketHandler (NULL), mPort (DEFAULT_TCP_SERVER_PORT) { init (); memset (mSocketEndpointPath, 0x00, sizeof(mSocketEndpointPath)); strncpy (mSocketEndpointPath, DEFAULT_IMMSOCKET_ENDPOINT_PATH, sizeof(mSocketEndpointPath)-1); memset (mIpAddr, 0x00, sizeof(mIpAddr)); memcpy (mIpAddr, DEFAULT_TCP_SERVER_ADDR, strlen(DEFAULT_TCP_SERVER_ADDR)); setLocalSocket (); } #endif // for client single // local CImmSocketClient::CImmSocketClient (const char *pPath) : mIsStop (false), mState (EN_RECEIVE_STATE_STANDBY__WAIT_SOH), mFdClientSocket (0), mCurrentPacketWritePos (0), mCurrentPacketDataSize(0), mpPacketHandler (NULL), mPort (DEFAULT_TCP_SERVER_PORT) { init (); memset (mSocketEndpointPath, 0x00, sizeof(mSocketEndpointPath)); if ((pPath) && (strlen(pPath) > 0)) { strncpy (mSocketEndpointPath, pPath, sizeof (mSocketEndpointPath) -1); } memset (mIpAddr, 0x00, sizeof(mIpAddr)); memcpy (mIpAddr, DEFAULT_TCP_SERVER_ADDR, strlen(DEFAULT_TCP_SERVER_ADDR)); setLocalSocket (); } // for client single // local CImmSocketClient::CImmSocketClient (const char *pPath, CImmSocketClient::IPacketHandler *pHandler) : mIsStop (false), mState (EN_RECEIVE_STATE_STANDBY__WAIT_SOH), mFdClientSocket (0), mCurrentPacketWritePos (0), mCurrentPacketDataSize(0), mpPacketHandler (NULL), mPort (DEFAULT_TCP_SERVER_PORT) { init (); if (pHandler) { mpPacketHandler = pHandler; } memset (mSocketEndpointPath, 0x00, sizeof(mSocketEndpointPath)); if ((pPath) && (strlen(pPath) > 0)) { strncpy (mSocketEndpointPath, pPath, sizeof (mSocketEndpointPath) -1); } memset (mIpAddr, 0x00, sizeof(mIpAddr)); memcpy (mIpAddr, DEFAULT_TCP_SERVER_ADDR, strlen(DEFAULT_TCP_SERVER_ADDR)); setLocalSocket (); } // for client single // tcp CImmSocketClient::CImmSocketClient (const char *pszIpAddr, uint16_t port) : mIsStop (false), mState (EN_RECEIVE_STATE_STANDBY__WAIT_SOH), mFdClientSocket (0), mCurrentPacketWritePos (0), mCurrentPacketDataSize(0), mpPacketHandler (NULL), mPort (DEFAULT_TCP_SERVER_PORT) { init (); memset (mSocketEndpointPath, 0x00, sizeof(mSocketEndpointPath)); strncpy (mSocketEndpointPath, DEFAULT_IMMSOCKET_ENDPOINT_PATH, sizeof(mSocketEndpointPath)-1); memset (mIpAddr, 0x00, sizeof(mIpAddr)); if (pszIpAddr && (strlen(pszIpAddr) > 0)) { memcpy (mIpAddr, pszIpAddr, sizeof(mIpAddr) -1); } mPort = port; setTcpSocket (); } // for client single // tcp CImmSocketClient::CImmSocketClient (const char *pszIpAddr, uint16_t port, CImmSocketClient::IPacketHandler *pHandler) : mIsStop (false), mState (EN_RECEIVE_STATE_STANDBY__WAIT_SOH), mFdClientSocket (0), mCurrentPacketWritePos (0), mCurrentPacketDataSize(0), mpPacketHandler (NULL), mPort (DEFAULT_TCP_SERVER_PORT) { init (); if (pHandler) { mpPacketHandler = pHandler; } memset (mSocketEndpointPath, 0x00, sizeof(mSocketEndpointPath)); strncpy (mSocketEndpointPath, DEFAULT_IMMSOCKET_ENDPOINT_PATH, sizeof(mSocketEndpointPath)-1); memset (mIpAddr, 0x00, sizeof(mIpAddr)); if (pszIpAddr && (strlen(pszIpAddr) > 0)) { memcpy (mIpAddr, pszIpAddr, sizeof(mIpAddr) -1); } mPort = port; setTcpSocket (); } // for server side CImmSocketClient::CImmSocketClient (int fdClientSocket) : mIsStop (false), mState (EN_RECEIVE_STATE_STANDBY__WAIT_SOH), mFdClientSocket (0), mCurrentPacketWritePos (0), mCurrentPacketDataSize(0), mpPacketHandler (NULL), mPort (DEFAULT_TCP_SERVER_PORT) { init (); mFdClientSocket = fdClientSocket; memset (mSocketEndpointPath, 0x00, sizeof(mSocketEndpointPath)); strncpy (mSocketEndpointPath, DEFAULT_IMMSOCKET_ENDPOINT_PATH, sizeof(mSocketEndpointPath)-1); memset (mIpAddr, 0x00, sizeof(mIpAddr)); memcpy (mIpAddr, DEFAULT_TCP_SERVER_ADDR, strlen(DEFAULT_TCP_SERVER_ADDR)); setLocalSocket (); } // for server side CImmSocketClient::CImmSocketClient (int fdClientSocket, CImmSocketClient::IPacketHandler *pHandler) : mIsStop (false), mState (EN_RECEIVE_STATE_STANDBY__WAIT_SOH), mFdClientSocket (0), mCurrentPacketWritePos (0), mCurrentPacketDataSize(0), mpPacketHandler (NULL), mPort (DEFAULT_TCP_SERVER_PORT) { init (); mFdClientSocket = fdClientSocket; if (pHandler) { mpPacketHandler = pHandler; } memset (mSocketEndpointPath, 0x00, sizeof(mSocketEndpointPath)); strncpy (mSocketEndpointPath, DEFAULT_IMMSOCKET_ENDPOINT_PATH, sizeof(mSocketEndpointPath)-1); memset (mIpAddr, 0x00, sizeof(mIpAddr)); memcpy (mIpAddr, DEFAULT_TCP_SERVER_ADDR, strlen(DEFAULT_TCP_SERVER_ADDR)); setLocalSocket (); } CImmSocketClient::~CImmSocketClient (void) { finaliz (); } void CImmSocketClient::init (void) { memset (mCurrentPacket, 0x00, sizeof (mCurrentPacket)); pthread_mutex_init (&mMutex, NULL); pthread_mutex_init (&mMutexSend, NULL); } void CImmSocketClient::finaliz (void) { pthread_mutex_destroy (&mMutex); pthread_mutex_destroy (&mMutexSend); } bool CImmSocketClient::startReceiver (void) { CUtils::CScopedMutex scopedMutex (&mMutex); if (isAlive()) { _IMMSOCK_LOG_W ("already started\n"); return true; } mIsStop = false; return create (); } void CImmSocketClient::stopReceiver (void) { CUtils::CScopedMutex scopedMutex (&mMutex); mIsStop = true; } void CImmSocketClient::syncStopReceiver (void) { CUtils::CScopedMutex scopedMutex (&mMutex); mIsStop = true; waitDestroy (); } int CImmSocketClient::setupClientSocket (void) { int fd = 0; struct sockaddr_un stClientAddr; if ((fd = socket(PF_UNIX, SOCK_STREAM, 0)) < 0) { _IMMSOCK_PERROR ("socket"); return -1; } memset (&stClientAddr, 0x00, sizeof(stClientAddr)); stClientAddr.sun_family = AF_UNIX; strcpy (stClientAddr.sun_path, mSocketEndpointPath); if (connect (fd, (struct sockaddr*)&stClientAddr, sizeof(stClientAddr.sun_family)+strlen(mSocketEndpointPath)) < 0) { _IMMSOCK_PERROR ("connect"); return -1; } return fd; } int CImmSocketClient::setupClientSocket_Tcp (void) { int fd = 0; int rtn = 0; struct sockaddr_in stClientAddr; memset (&stClientAddr, 0x00, sizeof(struct sockaddr_in)); stClientAddr.sin_family = AF_INET; stClientAddr.sin_port = htons (mPort); // stClientAddr.sin_addr.s_addr = inet_addr (mIpAddr); rtn = inet_aton (mIpAddr, &stClientAddr.sin_addr); if (rtn == 0) { _IMMSOCK_PERROR ("inet_aton()"); return -1; } fd = socket (AF_INET, SOCK_STREAM, 0); if (fd < 0) { _IMMSOCK_PERROR ("socket()"); return -1; } rtn = connect (fd, (struct sockaddr*)&stClientAddr, sizeof(struct sockaddr)); if( rtn < 0 ){ _IMMSOCK_PERROR ("connect()"); close (fd); return -1; } return fd; } bool CImmSocketClient::connectToServer (void) { CUtils::CScopedMutex scopedMutex (&mMutex); if (mFdClientSocket != 0) { _IMMSOCK_LOG_W ("already connected\n"); return true; } int fd = (this->*mpfnSetupClientSocket) (); if (fd < 0) { return false; } mFdClientSocket = fd; return true; } void CImmSocketClient::disconnectFromServer (void) { CUtils::CScopedMutex scopedMutex (&mMutex); if (mFdClientSocket != 0) { close (mFdClientSocket); mFdClientSocket = 0; } } bool CImmSocketClient::isConnected (void) { CUtils::CScopedMutex scopedMutex (&mMutex); if (mFdClientSocket == 0) { return false; } else { return true; } } void CImmSocketClient::onThreadMainRoutine (void) { setName ((char*)"ImmSocketReceiver"); _IMMSOCK_LOG_I ("%s %s\n", __FILE__, __func__); if (mpPacketHandler) { mpPacketHandler->onSetup (this); } // don't use receiveOnce and receiveLoop together receiveLoop (mFdClientSocket); if (mpPacketHandler) { mpPacketHandler->onTeardown (this); } _IMMSOCK_LOG_W ("%s %s end\n", __FILE__, __func__); // thread end } int CImmSocketClient::receiveWrapper (int fdClientSocket, uint8_t *pBuff, int size) { int rtn = read (fdClientSocket, pBuff, size); if (rtn < 0) { _IMMSOCK_PERROR ("read()"); } return rtn; } int CImmSocketClient::receiveWrapper_Tcp (int fdClientSocket, uint8_t *pBuff, int size) { int rtn = recv (fdClientSocket, pBuff, size, 0); if (rtn < 0) { _IMMSOCK_PERROR ("recv()"); } return rtn; } void CImmSocketClient::receiveLoop (int fdClientSocket) { uint8_t buff[1024]; int rtn = 0; int chk = 0; fd_set stFds; struct timeval stTimeout; // clear member clearReceiveDependVals (); while (1) { // _IMMSOCK_LOG_I ("select(read) blocking..."); FD_ZERO (&stFds); FD_SET (fdClientSocket, &stFds); stTimeout.tv_sec = 1; stTimeout.tv_usec = 0; rtn = select (fdClientSocket+1, &stFds, NULL, NULL, &stTimeout); if (rtn < 0) { _IMMSOCK_PERROR ("select()"); continue; } else if (rtn == 0) { // timeout if (mIsStop) { _IMMSOCK_LOG_W ("stop --> receiveLoop break\n"); break; } } if (FD_ISSET (fdClientSocket, &stFds)) { memset (buff, 0x00, sizeof(buff)); rtn = (this->*mpfnReceiveWrapper) (fdClientSocket, buff, sizeof(buff)); if (rtn == 0) { _IMMSOCK_LOG_N ("disconnect."); break; } else if (rtn < 0) { _IMMSOCK_PERROR ("read()/recv()"); continue; } else { _IMMSOCK_LOG_I ("data come size[%d]\n", rtn); if (getLogLevel() <= EN_LOG_LEVEL_I) { CUtils::dumper ((const uint8_t*)buff, rtn); } chk = checkData (buff, rtn); if (chk == -1) { _IMMSOCK_LOG_E ("checkData() error\n"); continue; } else if (chk == -2) { _IMMSOCK_LOG_E ("checkData() buffer over\n"); continue; } else { _IMMSOCK_LOG_I ("continue\n"); continue; } } } } } int CImmSocketClient::receiveOnce (int fdClientSocket, uint32_t nTimeoutMsec) { uint8_t buff[1024]; int rtn = 0; int chk = 0; fd_set stFds; struct timeval stTimeout; if (nTimeoutMsec < 0) { nTimeoutMsec = 0; } else if (nTimeoutMsec > RECEIVE_PACKET_ONCE_TIMEOUT_MAX) { nTimeoutMsec = RECEIVE_PACKET_ONCE_TIMEOUT_MAX; } // clear member clearReceiveDependVals (); while (1) { FD_ZERO (&stFds); FD_SET (fdClientSocket, &stFds); if (nTimeoutMsec == 0) { rtn = select (fdClientSocket+1, &stFds, NULL, NULL, NULL); } else { stTimeout.tv_sec = nTimeoutMsec / 1000; stTimeout.tv_usec = nTimeoutMsec % 1000; rtn = select (fdClientSocket+1, &stFds, NULL, NULL, &stTimeout); } if (rtn < 0) { _IMMSOCK_PERROR ("select()"); return -1; } else if (rtn == 0) { // timeout _IMMSOCK_LOG_W ("receiveOnce timeout\n"); return 0; } if (FD_ISSET (fdClientSocket, &stFds)) { memset (buff, 0x00, sizeof(buff)); rtn = (this->*mpfnReceiveWrapper) (fdClientSocket, buff, sizeof(buff)); if (rtn == 0) { _IMMSOCK_LOG_N ("disconnect."); return -2; } else if (rtn < 0) { _IMMSOCK_PERROR ("read()"); return -1; } else { _IMMSOCK_LOG_I ("data come size[%d]\n", rtn); if (getLogLevel() <= EN_LOG_LEVEL_I) { CUtils::dumper ((const uint8_t*)buff, rtn); } chk = checkData (buff, rtn, true); if (chk == -1) { _IMMSOCK_LOG_E ("checkData() error\n"); return -1; } else if (chk == -2) { _IMMSOCK_LOG_E ("checkData() buffer over\n"); return -1; } else if (chk == 1) { // packet complete return 1; } else { _IMMSOCK_LOG_I ("continue\n"); continue; } } } } } void CImmSocketClient::syncReceivePacketLoop (void) { if (mpPacketHandler) { mpPacketHandler->onSetup (this); } // don't use receiveOnce and receiveLoop together receiveLoop (mFdClientSocket); if (mpPacketHandler) { mpPacketHandler->onTeardown (this); } } int CImmSocketClient::syncReceivePacketOnce (uint8_t *pBuff, int size, uint32_t nTimeoutMsec) { if (!pBuff || size <= 0) { return -1; } if (nTimeoutMsec < 0) { nTimeoutMsec = 0; } else if (nTimeoutMsec > RECEIVE_PACKET_ONCE_TIMEOUT_MAX) { nTimeoutMsec = RECEIVE_PACKET_ONCE_TIMEOUT_MAX; } // don't use receiveOnce and receiveLoop together int rtn = receiveOnce (mFdClientSocket, nTimeoutMsec); if (rtn > 0) { int cpsize = size > mCurrentPacketWritePos ? mCurrentPacketWritePos : size; memcpy (pBuff, mCurrentPacket, cpsize); return cpsize; } else if (rtn == 0) { // timeout return 0; } else { // error return -1; } } void CImmSocketClient::clearReceiveDependVals (void) { mState = EN_RECEIVE_STATE_STANDBY__WAIT_SOH; memset (mCurrentPacket, 0x00, sizeof (mCurrentPacket)); mCurrentPacketWritePos = 0; mCurrentPacketDataSize = 0; } int CImmSocketClient::checkData (uint8_t *pBuff, int size, bool isOnce) { if ((!pBuff) || (size == 0)) { return -1; } while (size > 0) { if (mState == EN_RECEIVE_STATE_STANDBY__WAIT_SOH) { // wait SOH if (*pBuff == SOH) { mState = EN_RECEIVE_STATE_WORKING__CHECK_RESERVE_0; } else { _IMMSOCK_LOG_W ("unexpected data --> drop\n"); } } else if (mState == EN_RECEIVE_STATE_WORKING__CHECK_RESERVE_0) { mState = EN_RECEIVE_STATE_WORKING__CHECK_RESERVE_1; } else if (mState == EN_RECEIVE_STATE_WORKING__CHECK_RESERVE_1) { mState = EN_RECEIVE_STATE_WORKING__CHECK_SIZE; } else if (mState == EN_RECEIVE_STATE_WORKING__CHECK_SIZE) { mCurrentPacketDataSize = *pBuff; if (mCurrentPacketDataSize > 0) { // data exist mState = EN_RECEIVE_STATE_WORKING__CHECK_DATA; } else { // data nothing mState = EN_RECEIVE_STATE_WORKING__CHECK_EOT; } } else if (mState == EN_RECEIVE_STATE_WORKING__CHECK_DATA) { /** mCurrentPacket [mCurrentPacketWritePos] = *pBuff; ++ mCurrentPacketWritePos; mCurrentPacketDataSize --; if (mCurrentPacketDataSize == 0) { mState = EN_RECEIVE_STATE_WORKING__CHECK_EOT; } **/ if (mCurrentPacketDataSize <= (size - 1)) { //puts ("EN_RECEIVE_STATE_WORKING__CHECK_DATA aaaa bef"); //printf ("mCurrentPacketDataSize %d\n", mCurrentPacketDataSize); //printf ("size %d\n", size); //printf ("mCurrentPacketWritePos %d\n", mCurrentPacketWritePos); memcpy (mCurrentPacket + mCurrentPacketWritePos, pBuff, mCurrentPacketDataSize); size -= mCurrentPacketDataSize; mCurrentPacketWritePos += mCurrentPacketDataSize; pBuff += mCurrentPacketDataSize; mCurrentPacketDataSize = 0; //puts ("EN_RECEIVE_STATE_WORKING__CHECK_DATA aaaa aft"); //printf ("mCurrentPacketDataSize %d\n", mCurrentPacketDataSize); //printf ("size %d\n", size); //printf ("mCurrentPacketWritePos %d\n", mCurrentPacketWritePos); } else { //puts ("EN_RECEIVE_STATE_WORKING__CHECK_DATA bbbb bef"); //printf ("mCurrentPacketDataSize %d\n", mCurrentPacketDataSize); //printf ("size %d\n", size); //printf ("mCurrentPacketWritePos %d\n", mCurrentPacketWritePos); memcpy (mCurrentPacket + mCurrentPacketWritePos, pBuff, size); pBuff += size; mCurrentPacketDataSize -= size; mCurrentPacketWritePos += size; size = 0; //puts ("EN_RECEIVE_STATE_WORKING__CHECK_DATA bbbb aft"); //printf ("mCurrentPacketDataSize %d\n", mCurrentPacketDataSize); //printf ("size %d\n", size); //printf ("mCurrentPacketWritePos %d\n", mCurrentPacketWritePos); } if (mCurrentPacketDataSize == 0) { mState = EN_RECEIVE_STATE_WORKING__CHECK_EOT; } continue; } else if (mState == EN_RECEIVE_STATE_WORKING__CHECK_EOT) { if (*pBuff == EOT) { // EOT if (mCurrentPacketWritePos > 0) { _IMMSOCK_LOG_N ("packet complete\n"); if (getLogLevel() <= EN_LOG_LEVEL_I) { CUtils::dumper ((const uint8_t*)mCurrentPacket, mCurrentPacketWritePos); } if (isOnce) { return 1; } if (mpPacketHandler) { mpPacketHandler->onReceivePacket (this, mCurrentPacket, mCurrentPacketWritePos); } else { // default echo sendToConnection (mCurrentPacket, mCurrentPacketWritePos); } } else { _IMMSOCK_LOG_N ("null packet\n"); } // clear member clearReceiveDependVals (); } else { // invalid packet(invalid EOT) _IMMSOCK_LOG_E ("invalid packet(invalid EOT)\n"); // clear member clearReceiveDependVals (); } } if (mCurrentPacketWritePos >= RECEIVED_SIZE_MAX) { // buffer over _IMMSOCK_LOG_E ("buffer over(mCurrentPacket)\n"); // clear member clearReceiveDependVals (); return -2; } ++ pBuff; -- size; } return 0; } int CImmSocketClient::getFd (void) { return mFdClientSocket; } bool CImmSocketClient::sendToConnection (const uint8_t *pData, int size) { CUtils::CScopedMutex scopedMutex (&mMutexSend); if ((!pData) || (size <= 0) || (size > 0xff)) { return false; } int totalsize = size + 5; // append 5bytes area => (SOH, reserve, reserve, size, EOT) uint8_t buff [totalsize]; memset (buff, 0x00, sizeof(buff)); if (!setPacket (pData, size, buff, totalsize)) { _IMMSOCK_LOG_E ("setPacket() is failure.\n"); return false; } int rtn = (this->*mpfnSendWrapper) (mFdClientSocket, buff, totalsize); if (rtn < 0) { _IMMSOCK_PERROR ("write()/send()"); return false; } return true; } bool CImmSocketClient::setPacket (const uint8_t *pIn, int insize, uint8_t *pOut, int outsize) { if ((!pIn) || (insize <= 0) || (insize > 0xff)) { return false; } if ((!pOut) || (outsize < (insize+5))) { return false; } *(pOut+0) = SOH; *(pOut+1) = 0x00; // reserve *(pOut+2) = 0x00; // reserve *(pOut+3) = (uint8_t)insize; memcpy (pOut+4, pIn, insize); pOut [outsize -1] = EOT; return true; } int CImmSocketClient::sendWrapper (int fdClientSocket, const uint8_t *pData, int size) { int rtn = write (fdClientSocket, pData, size); if (rtn < 0) { _IMMSOCK_PERROR ("write"); } return rtn; } int CImmSocketClient::sendWrapper_Tcp (int fdClientSocket, const uint8_t *pData, int size) { int rtn = send (fdClientSocket, pData, size, 0); if (rtn < 0) { _IMMSOCK_PERROR ("send"); } return rtn; } CImmSocketClient::IPacketHandler *CImmSocketClient::getPacketHandler (void) { return mpPacketHandler; } // socket config void CImmSocketClient::setLocalSocket (void) { mpfnSetupClientSocket = &CImmSocketClient::setupClientSocket; mpfnReceiveWrapper = &CImmSocketClient::receiveWrapper; mpfnSendWrapper = &CImmSocketClient::sendWrapper; } // socket config void CImmSocketClient::setTcpSocket (void) { mpfnSetupClientSocket = &CImmSocketClient::setupClientSocket_Tcp; mpfnReceiveWrapper = &CImmSocketClient::receiveWrapper_Tcp; mpfnSendWrapper = &CImmSocketClient::sendWrapper_Tcp; } } // namespace ImmSocket /* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* Copyright (C) 2008 Master IMAFA - Polytech'Nice Sophia - Université de Nice Sophia Antipolis This file is part of QuantLib, a free-software/open-source library for financial quantitative analysts and developers - http://quantlib.org/ QuantLib is free software: you can redistribute it and/or modify it under the terms of the QuantLib license. You should have received a copy of the license along with this program; if not, please email <>. The license is also available online at . 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 license for more details. */ #include #include namespace QuantLib { EverestOption::EverestOption(Real notional, Rate guarantee, const ext::shared_ptr& exercise) : MultiAssetOption(ext::shared_ptr(new NullPayoff), exercise), notional_(notional), guarantee_(guarantee) {} Rate EverestOption::yield() const { calculate(); QL_REQUIRE(yield_ != Null(), "yield not provided"); return yield_; } void EverestOption::setupArguments(PricingEngine::arguments* args) const { MultiAssetOption::setupArguments(args); auto* arguments = dynamic_cast(args); QL_REQUIRE(arguments != nullptr, "wrong argument type"); arguments->notional = notional_; arguments->guarantee= guarantee_; } void EverestOption::fetchResults(const PricingEngine::results* r) const { MultiAssetOption::fetchResults(r); const auto* results = dynamic_cast(r); QL_ENSURE(results != nullptr, "no results returned from pricing engine"); yield_ = results->yield; } EverestOption::arguments::arguments() : notional(Null()), guarantee(Null()) {} void EverestOption::arguments::validate() const { MultiAssetOption::arguments::validate(); QL_REQUIRE(notional != Null(), "no notional given"); QL_REQUIRE(notional != 0.0, "null notional given"); QL_REQUIRE(guarantee != Null(), "no guarantee given"); } void EverestOption::results::reset() { MultiAssetOption::results::reset(); yield = Null(); } } #ifndef __TPC_LOG_HPP #define __TPC_LOG_HPP #include #include #include #include "TPC/Filesystem.hpp" namespace TPC { namespace Log { enum class Level : uint8_t { SILENT, IMPORTANT, INFO, DEBUG, DEBUG_VERBOSE, }; void init(); void writeChar(char c); void writeNewline(); void writeString(const char * str); void writeString(const char * str, uint8_t len); void writeStringP(PGM_P str); void writeFilename(TPC::Filesystem::DirectoryEntry * entry); void writeHex4(uint8_t val); void writeHex8(uint8_t val); void writeHex16(uint16_t val); bool shouldLog(Level level); void log(PGM_P str); void log(PGM_P str, uint8_t val); void log(PGM_P str, uint16_t val); void log(PGM_P str, const char * val); void log(PGM_P str, TPC::Filesystem::DirectoryEntry * entry); } } #define LOG(LEVEL, STR, ...) if (TPC::Log::shouldLog(TPC::Log::Level::LEVEL)) { \ static const char str[] PROGMEM = STR; \ TPC::Log::log(str,##__VA_ARGS__); \ } #endif #include "ee/ads/MultiFullScreenAd.hpp" #include #include #include namespace ee { namespace ads { using Self = MultiFullScreenAd; Self::MultiFullScreenAd() { handle_ = std::make_unique(); } Self::~MultiFullScreenAd() = default; Self& Self::addItem(const std::shared_ptr& item) { items_.push_back(item); (*handle_).bind(*item).addObserver({ .onLoaded = [this] { // Propagation. dispatchEvent([](auto&& observer) { if (observer.onLoaded) { observer.onLoaded(); } }); }, .onLoadResult = [this](const AdLoadResult& result) { // Propagation. dispatchEvent([result](auto&& observer) { if (observer.onLoadResult) { observer.onLoadResult(result); } }); }, .onClicked = [this] { // Propagation. dispatchEvent([](auto&& observer) { if (observer.onClicked) { observer.onClicked(); } }); }, }); return *this; } void Self::destroy() { for (auto&& item : items_) { item->destroy(); } items_.clear(); handle_->clear(); } bool Self::isLoaded() const { for (auto&& item : items_) { if (item->isLoaded()) { return true; } } return false; } Task Self::load() { bool result = false; for (auto&& item : items_) { if (item->isLoaded()) { continue; } if (co_await item->load()) { result = true; } } co_return result; } Task Self::show() { auto result = AdResult::Failed; for (auto&& item : items_) { if (result == AdResult::Failed) { // Only process if there isn't any successfully displayed ad. result = co_await item->show(); } if (not item->isLoaded()) { // Load in background. noAwait(item->load()); } } co_return result; } } // namespace ads } // namespace ee #ifndef MJI_HASHER_HPP_INCLUDED_ #define MJI_HASHER_HPP_INCLUDED_ #include #include #include #include #include #include #include #include #include // only need libcrypto, not libssl #include /******************************************************************************* Note about CRC32 code: This implementation is based on the algorithm from Annex D of the Portable Network Graphics (PNG) Specification (Second Edition) *******************************************************************************/ namespace mji::xmph { constexpr std::size_t hash_max_custom_digest_size = 4; // CRC32 constexpr auto hash_max_digest_size = std::max( EVP_MAX_MD_SIZE, hash_max_custom_digest_size ); bool initHashSubsystem(); class Hasher { public: Hasher(); virtual ~Hasher() = default; bool consume(const void* data, std::size_t count); bool finalize(void* buf, std::size_t count); std::size_t getDigestSize() const; // the returned pointer should not be used past the lifetime of this object const char* getName() const; bool reset(); private: bool isFinalized_; virtual bool consumeImpl(const void* data, std::size_t count) = 0; virtual bool finalizeImpl(void* buf) = 0; virtual bool resetImpl() = 0; virtual std::size_t getDigestSizeImpl() const = 0; virtual const char* getNameImpl() const = 0; }; /// Lookup table to speed up CRC32 class Crc32Lut { public: constexpr static std::size_t length = 256; constexpr Crc32Lut() : data() { constexpr std::uint32_t poly = 0xedb88320u; for (std::uint32_t i = 0; i < length; i++) { uint32_t pre = i; for (int j = 0; j < 8; j++) { if (pre & 1) { pre = poly ^ (pre >> 1); } else { pre >>= 1; } } data[i] = pre; } } constexpr std::uint32_t operator[](size_t idx) const { return data[idx]; } private: std::uint32_t data[length]; }; inline constexpr Crc32Lut crc32Lut{}; class Crc32Hasher final : public Hasher { public: Crc32Hasher(); ~Crc32Hasher(); Crc32Hasher(const Crc32Hasher& other) = default; Crc32Hasher(Crc32Hasher&& other) = default; Crc32Hasher& operator=(const Crc32Hasher& other) = default; Crc32Hasher& operator=(Crc32Hasher&& other) = default; private: static constexpr std::uint32_t base = 0xffffffffu; std::uint32_t partial_; bool consumeImpl(const void* data, std::size_t count) override; bool finalizeImpl(void* buf) override; bool resetImpl() override; std::size_t getDigestSizeImpl() const override; const char* getNameImpl() const override; }; // RAII class EvpMdCtxWrapper final { public: EvpMdCtxWrapper(); ~EvpMdCtxWrapper(); EvpMdCtxWrapper(const EvpMdCtxWrapper& other); EvpMdCtxWrapper(EvpMdCtxWrapper&& other); EvpMdCtxWrapper& operator=(const EvpMdCtxWrapper& other); EvpMdCtxWrapper& operator=(EvpMdCtxWrapper&& other); ::EVP_MD_CTX* get(); const ::EVP_MD_CTX* get() const; private: ::EVP_MD_CTX* context_; }; class EvpHasher final : public Hasher { public: EvpHasher(const char* name); EvpHasher(std::string&& name); ~EvpHasher() = default; EvpHasher(const EvpHasher& other) = default; EvpHasher(EvpHasher&& other) = default; EvpHasher& operator=(const EvpHasher& other) = default; EvpHasher& operator=(EvpHasher&& other) = default; private: EvpMdCtxWrapper context_; std::string name_; // we don't own this, just treat it as an ID const ::EVP_MD* digest_type_; bool consumeImpl(const void* data, std::size_t count) override; bool finalizeImpl(void* buf) override; bool resetImpl() override; std::size_t getDigestSizeImpl() const override; const char* getNameImpl() const override; void initContext(); }; /// Converts a string of hexadecimal digits into a byte vector. The string must /// have an even number of characters and each character must be a valid hex /// digit (this will produce a byte vector of length sv.length()/2). Returns an /// empty optional on failure. std::optional> strToBytes(std::string_view sv); std::string bytesToStr(unsigned char* buf, std::size_t count); /// The returned vector always has size >= 1 std::vector splitOnChar(const char* s, char delim); std::optional> parseNameDigestPair(const char* c); } // namespace mji::xmph #endif // MJI_HASHER_HPP_INCLUDED_ Calibration/HcalCalibAlgos/plugins/HcalHBHENewMuonAnalyzer.cc #include #include #include #include #include #include #include "TPRegexp.h" // user include files #include "FWCore/Framework/interface/Frameworkfwd.h" #include "FWCore/Framework/interface/one/EDAnalyzer.h" #include "FWCore/Framework/interface/Event.h" #include "FWCore/MessageLogger/interface/MessageLogger.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" #include "FWCore/ParameterSet/interface/ConfigurationDescriptions.h" #include "FWCore/ServiceRegistry/interface/Service.h" #include "FWCore/Common/interface/TriggerNames.h" #include "CommonTools/UtilAlgos/interface/TFileService.h" #include "DataFormats/HcalCalibObjects/interface/HcalHBHEMuonVariables.h" //#define EDM_ML_DEBUG class HcalHBHENewMuonAnalyzer : public edm::one::EDAnalyzer { public: explicit HcalHBHENewMuonAnalyzer(const edm::ParameterSet&); ~HcalHBHENewMuonAnalyzer() override = default; static void fillDescriptions(edm::ConfigurationDescriptions& descriptions); private: void beginJob() override; void analyze(edm::Event const&, edm::EventSetup const&) override; // ----------member data --------------------------- edm::Service fs; const edm::InputTag labelHBHEMuonVar_; const int useRaw_; int maxDepth_, kount_; const edm::EDGetTokenT tokHBHEMuonVar_; ////////////////////////////////////////////////////// static const int depthMax_ = 7; TTree* tree_; unsigned int runNumber_, eventNumber_, lumiNumber_, bxNumber_; unsigned int goodVertex_; bool muon_is_good_, muon_global_, muon_tracker_; bool muon_is_tight_, muon_is_medium_; double ptGlob_, etaGlob_, phiGlob_, energyMuon_, pMuon_; float muon_trkKink_, muon_chi2LocalPosition_, muon_segComp_; int trackerLayer_, numPixelLayers_, tight_PixelHits_; bool innerTrack_, outerTrack_, globalTrack_; double chiTracker_, dxyTracker_, dzTracker_; double innerTrackpt_, innerTracketa_, innerTrackphi_; double tight_validFraction_, outerTrackChi_; double outerTrackPt_, outerTrackEta_, outerTrackPhi_; int outerTrackHits_, outerTrackRHits_; double globalTrckPt_, globalTrckEta_, globalTrckPhi_; int globalMuonHits_, matchedStat_; double chiGlobal_, tight_LongPara_, tight_TransImpara_; double isolationR04_, isolationR03_; double ecalEnergy_, hcalEnergy_, hoEnergy_; bool matchedId_, hcalHot_; double ecal3x3Energy_, hcal1x1Energy_; unsigned int ecalDetId_, hcalDetId_, ehcalDetId_; int hcal_ieta_, hcal_iphi_; double hcalDepthEnergy_[depthMax_]; double hcalDepthActiveLength_[depthMax_]; double hcalDepthEnergyHot_[depthMax_]; double hcalDepthActiveLengthHot_[depthMax_]; double hcalDepthChargeHot_[depthMax_]; double hcalDepthChargeHotBG_[depthMax_]; double hcalDepthEnergyCorr_[depthMax_]; double hcalDepthEnergyHotCorr_[depthMax_]; bool hcalDepthMatch_[depthMax_]; bool hcalDepthMatchHot_[depthMax_]; double hcalActiveLength_, hcalActiveLengthHot_; std::vector all_triggers_; std::vector hltresults_; //////////////////////////////////////////////////////////// }; HcalHBHENewMuonAnalyzer::HcalHBHENewMuonAnalyzer(const edm::ParameterSet& iConfig) : labelHBHEMuonVar_(iConfig.getParameter("hbheMuonLabel")), useRaw_(iConfig.getParameter("useRaw")), tokHBHEMuonVar_(consumes(labelHBHEMuonVar_)) { usesResource(TFileService::kSharedResource); //now do what ever initialization is needed kount_ = 0; maxDepth_ = iConfig.getUntrackedParameter("maxDepth", 4); if (maxDepth_ > depthMax_) maxDepth_ = depthMax_; else if (maxDepth_ < 1) maxDepth_ = 4; edm::LogVerbatim("HBHEMuon") << "Parameters read from config file \n\t maxDepth__ " << maxDepth_ << "\n\t Labels " << labelHBHEMuonVar_; } // // member functions // // ------------ method called for each event ------------ void HcalHBHENewMuonAnalyzer::analyze(const edm::Event& iEvent, const edm::EventSetup& iSetup) { ++kount_; runNumber_ = iEvent.id().run(); eventNumber_ = iEvent.id().event(); lumiNumber_ = iEvent.id().luminosityBlock(); bxNumber_ = iEvent.bunchCrossing(); #ifdef EDM_ML_DEBUG edm::LogVerbatim("HBHEMuon") << "Run " << runNumber_ << " Event " << eventNumber_ << " Lumi " << lumiNumber_ << " BX " << bxNumber_ << std::endl; #endif auto const& hbheMuonColl = iEvent.getHandle(tokHBHEMuonVar_); if (hbheMuonColl.isValid()) { auto hbheMuon = hbheMuonColl.product(); for (auto itr = hbheMuon->begin(); itr != hbheMuon->end(); ++itr) { goodVertex_ = itr->goodVertex_; muon_is_good_ = itr->muonGood_; muon_global_ = itr->muonGlobal_; muon_tracker_ = itr->muonTracker_; muon_is_tight_ = itr->muonTight_; muon_is_medium_ = itr->muonMedium_; ptGlob_ = itr->ptGlob_; etaGlob_ = itr->etaGlob_; phiGlob_ = itr->phiGlob_; energyMuon_ = itr->energyMuon_; pMuon_ = itr->pMuon_; muon_trkKink_ = itr->muonTrkKink_; muon_chi2LocalPosition_ = itr->muonChi2LocalPosition_; muon_segComp_ = itr->muonSegComp_; trackerLayer_ = itr->trackerLayer_; numPixelLayers_ = itr->numPixelLayers_; tight_PixelHits_ = itr->tightPixelHits_; innerTrack_ = itr->innerTrack_; outerTrack_ = itr->outerTrack_; globalTrack_ = itr->globalTrack_; chiTracker_ = itr->chiTracker_; dxyTracker_ = itr->dxyTracker_; dzTracker_ = itr->dzTracker_; innerTrackpt_ = itr->innerTrackPt_; innerTracketa_ = itr->innerTrackEta_; innerTrackphi_ = itr->innerTrackPhi_; tight_validFraction_ = itr->tightValidFraction_; outerTrackChi_ = itr->outerTrackChi_; outerTrackPt_ = itr->outerTrackPt_; outerTrackEta_ = itr->outerTrackEta_; outerTrackPhi_ = itr->outerTrackPhi_; outerTrackHits_ = itr->outerTrackHits_; outerTrackRHits_ = itr->outerTrackRHits_; globalTrckPt_ = itr->globalTrackPt_; globalTrckEta_ = itr->globalTrackEta_; globalTrckPhi_ = itr->globalTrackPhi_; globalMuonHits_ = itr->globalMuonHits_; matchedStat_ = itr->matchedStat_; chiGlobal_ = itr->chiGlobal_; tight_LongPara_ = itr->tightLongPara_; tight_TransImpara_ = itr->tightTransImpara_; isolationR04_ = itr->isolationR04_; isolationR03_ = itr->isolationR03_; ecalEnergy_ = itr->ecalEnergy_; hcalEnergy_ = itr->hcalEnergy_; hoEnergy_ = itr->hoEnergy_; matchedId_ = itr->matchedId_; hcalHot_ = itr->hcalHot_; ecal3x3Energy_ = itr->ecal3x3Energy_; ecalDetId_ = itr->ecalDetId_; hcalDetId_ = itr->hcalDetId_; ehcalDetId_ = itr->ehcalDetId_; hcal_ieta_ = itr->hcalIeta_; hcal_iphi_ = itr->hcalIphi_; if (useRaw_ == 1) hcal1x1Energy_ = itr->hcal1x1EnergyAux_; else if (useRaw_ == 2) hcal1x1Energy_ = itr->hcal1x1EnergyRaw_; else hcal1x1Energy_ = itr->hcal1x1Energy_; for (unsigned int i = 0; i < itr->hcalDepthEnergy_.size(); ++i) { hcalDepthActiveLength_[i] = itr->hcalDepthActiveLength_[i]; hcalDepthActiveLengthHot_[i] = itr->hcalDepthActiveLengthHot_[i]; if (useRaw_ == 1) { hcalDepthEnergy_[i] = itr->hcalDepthEnergyAux_[i]; hcalDepthEnergyHot_[i] = itr->hcalDepthEnergyHotAux_[i]; hcalDepthEnergyCorr_[i] = itr->hcalDepthEnergyCorrAux_[i]; hcalDepthEnergyHotCorr_[i] = itr->hcalDepthEnergyHotCorrAux_[i]; hcalDepthChargeHot_[i] = itr->hcalDepthChargeHotAux_[i]; hcalDepthChargeHotBG_[i] = itr->hcalDepthChargeHotBGAux_[i]; } else if (useRaw_ == 2) { hcalDepthEnergy_[i] = itr->hcalDepthEnergyRaw_[i]; hcalDepthEnergyHot_[i] = itr->hcalDepthEnergyHotRaw_[i]; hcalDepthEnergyCorr_[i] = itr->hcalDepthEnergyCorrRaw_[i]; hcalDepthEnergyHotCorr_[i] = itr->hcalDepthEnergyHotCorrRaw_[i]; hcalDepthChargeHot_[i] = itr->hcalDepthChargeHotRaw_[i]; hcalDepthChargeHotBG_[i] = itr->hcalDepthChargeHotBGRaw_[i]; } else { hcalDepthEnergy_[i] = itr->hcalDepthEnergy_[i]; hcalDepthEnergyHot_[i] = itr->hcalDepthEnergyHot_[i]; hcalDepthEnergyCorr_[i] = itr->hcalDepthEnergyCorr_[i]; hcalDepthEnergyHotCorr_[i] = itr->hcalDepthEnergyHotCorr_[i]; hcalDepthChargeHot_[i] = itr->hcalDepthChargeHot_[i]; hcalDepthChargeHotBG_[i] = itr->hcalDepthChargeHotBG_[i]; } hcalDepthMatch_[i] = itr->hcalDepthMatch_[i]; hcalDepthMatchHot_[i] = itr->hcalDepthMatchHot_[i]; } hcalActiveLength_ = itr->hcalActiveLength_; hcalActiveLengthHot_ = itr->hcalActiveLengthHot_; all_triggers_ = itr->allTriggers_; hltresults_ = itr->hltResults_; tree_->Fill(); } } } // ------------ method called once each job just before starting event loop ------------ void HcalHBHENewMuonAnalyzer::beginJob() { tree_ = fs->make("TREE", "TREE"); tree_->Branch("Event_No", &eventNumber_); tree_->Branch("Run_No", &runNumber_); tree_->Branch("LumiNumber", &lumiNumber_); tree_->Branch("BXNumber", &bxNumber_); tree_->Branch("GoodVertex", &goodVertex_); tree_->Branch("PF_Muon", &muon_is_good_); tree_->Branch("Global_Muon", &muon_global_); tree_->Branch("Tracker_muon", &muon_tracker_); tree_->Branch("MuonIsTight", &muon_is_tight_); tree_->Branch("MuonIsMedium", &muon_is_medium_); tree_->Branch("pt_of_muon", &ptGlob_); tree_->Branch("eta_of_muon", &etaGlob_); tree_->Branch("phi_of_muon", &phiGlob_); tree_->Branch("energy_of_muon", &energyMuon_); tree_->Branch("p_of_muon", &pMuon_); tree_->Branch("muon_trkKink", &muon_trkKink_); tree_->Branch("muon_chi2LocalPosition", &muon_chi2LocalPosition_); tree_->Branch("muon_segComp", &muon_segComp_); tree_->Branch("TrackerLayer", &trackerLayer_); tree_->Branch("NumPixelLayers", &numPixelLayers_); tree_->Branch("InnerTrackPixelHits", &tight_PixelHits_); tree_->Branch("innerTrack", &innerTrack_); tree_->Branch("chiTracker", &chiTracker_); tree_->Branch("DxyTracker", &dxyTracker_); tree_->Branch("DzTracker", &dzTracker_); tree_->Branch("innerTrackpt", &innerTrackpt_); tree_->Branch("innerTracketa", &innerTracketa_); tree_->Branch("innerTrackphi", &innerTrackphi_); tree_->Branch("tight_validFraction", &tight_validFraction_); tree_->Branch("OuterTrack", &outerTrack_); tree_->Branch("OuterTrackChi", &outerTrackChi_); tree_->Branch("OuterTrackPt", &outerTrackPt_); tree_->Branch("OuterTrackEta", &outerTrackEta_); tree_->Branch("OuterTrackPhi", &outerTrackPhi_); tree_->Branch("OuterTrackHits", &outerTrackHits_); tree_->Branch("OuterTrackRHits", &outerTrackRHits_); tree_->Branch("GlobalTrack", &globalTrack_); tree_->Branch("GlobalTrckPt", &globalTrckPt_); tree_->Branch("GlobalTrckEta", &globalTrckEta_); tree_->Branch("GlobalTrckPhi", &globalTrckPhi_); tree_->Branch("Global_Muon_Hits", &globalMuonHits_); tree_->Branch("MatchedStations", &matchedStat_); tree_->Branch("GlobTrack_Chi", &chiGlobal_); tree_->Branch("Tight_LongitudinalImpactparameter", &tight_LongPara_); tree_->Branch("Tight_TransImpactparameter", &tight_TransImpara_); tree_->Branch("IsolationR04", &isolationR04_); tree_->Branch("IsolationR03", &isolationR03_); tree_->Branch("ecal_3into3", &ecalEnergy_); tree_->Branch("hcal_3into3", &hcalEnergy_); tree_->Branch("tracker_3into3", &hoEnergy_); tree_->Branch("matchedId", &matchedId_); tree_->Branch("hcal_cellHot", &hcalHot_); tree_->Branch("ecal_3x3", &ecal3x3Energy_); tree_->Branch("hcal_1x1", &hcal1x1Energy_); tree_->Branch("ecal_detID", &ecalDetId_); tree_->Branch("hcal_detID", &hcalDetId_); tree_->Branch("ehcal_detID", &ehcalDetId_); tree_->Branch("hcal_ieta", &hcal_ieta_); tree_->Branch("hcal_iphi", &hcal_iphi_); char name[100]; for (int k = 0; k < maxDepth_; ++k) { sprintf(name, "hcal_edepth%d", (k + 1)); tree_->Branch(name, &hcalDepthEnergy_[k]); sprintf(name, "hcal_activeL%d", (k + 1)); tree_->Branch(name, &hcalDepthActiveLength_[k]); sprintf(name, "hcal_edepthHot%d", (k + 1)); tree_->Branch(name, &hcalDepthEnergyHot_[k]); sprintf(name, "hcal_activeHotL%d", (k + 1)); tree_->Branch(name, &hcalDepthActiveLengthHot_[k]); sprintf(name, "hcal_cdepthHot%d", (k + 1)); tree_->Branch(name, &hcalDepthChargeHot_[k]); sprintf(name, "hcal_cdepthHotBG%d", (k + 1)); tree_->Branch(name, &hcalDepthChargeHotBG_[k]); sprintf(name, "hcal_edepthCorrect%d", (k + 1)); tree_->Branch(name, &hcalDepthEnergyCorr_[k]); sprintf(name, "hcal_edepthHotCorrect%d", (k + 1)); tree_->Branch(name, &hcalDepthEnergyHotCorr_[k]); sprintf(name, "hcal_depthMatch%d", (k + 1)); tree_->Branch(name, &hcalDepthMatch_[k]); sprintf(name, "hcal_depthMatchHot%d", (k + 1)); tree_->Branch(name, &hcalDepthMatchHot_[k]); } tree_->Branch("activeLength", &hcalActiveLength_); tree_->Branch("activeLengthHot", &hcalActiveLengthHot_); tree_->Branch("hltresults", &hltresults_); tree_->Branch("all_triggers", &all_triggers_); } // ------------ method fills 'descriptions' with the allowed parameters for the module ------------ void HcalHBHENewMuonAnalyzer::fillDescriptions(edm::ConfigurationDescriptions& descriptions) { edm::ParameterSetDescription desc; desc.add("hbheMuonLabel", edm::InputTag("alcaHcalHBHEMuonProducer", "hbheMuon")); desc.add("useRaw", 0); desc.addUntracked("maxDepth", 4); descriptions.add("hcalHBHEMuonAnalysis", desc); } //define this as a plug-in #include "FWCore/Framework/interface/MakerMacros.h" DEFINE_FWK_MODULE(HcalHBHENewMuonAnalyzer); // Copyright 2006–2020. Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE.txt) #include "ExampleMode.h" #include "Tridiagonal.tcc" void aJump (StateVectorLow& psi, double kappa_nPlus1) { double fact=sqrt(2.*kappa_nPlus1); int ubound=psi.ubound(0); for (int n=0; n0; --n) psi(n)=fact*sqrt(n)*psi(n-1); psi(0)=0; } namespace { double photonNumber(const LazyDensityOperator& matrix) { double res=0; for (size_t n=1; n(&mode)) return furnishWithFreqs(aop(dim),mainDiagonal(modeIP->get_z(),dim)); else return aop(dim); } /*========================================================================= Program: ALBA (Agile Library for Biomedical Applications) Module: albaVMESurfaceEditorTest Authors: Copyright (c) BIC All rights reserved. See Copyright.txt or 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 "albaDefines.h" //---------------------------------------------------------------------------- // NOTE: Every CPP file in the ALBA must include "albaDefines.h" as first. // This force to include Window,wxWidgets and VTK exactly in this order. // Failing in doing this will result in a run-time error saying: // "Failure#0: The value of ESP was not properly saved across a function call" //---------------------------------------------------------------------------- #include #include "albaVMESurfaceEditorTest.h" #include #include "albaOpImporterVTK.h" #include "albaVMEStorage.h" #include "albaVMERoot.h" #include "vtkALBASmartPointer.h" #include "vtkPolyData.h" //#include "vtkdataSet.h" #include "albaVMESurfaceEditor.h" #define TEST_RESULT CPPUNIT_ASSERT(m_Result) //--------------------------------------------------------- void albaVMESurfaceEditorTest::TestDynamicAllocation() //--------------------------------------------------------- { albaVMESurfaceEditor *editor = NULL; albaNEW(editor); albaDEL(editor); } //--------------------------------------------------------- void albaVMESurfaceEditorTest::TestSetData() //--------------------------------------------------------- { //Create storage albaVMEStorage *storage = albaVMEStorage::New(); storage->GetRoot()->SetName("root"); storage->GetRoot()->Initialize(); //import surface albaOpImporterVTK *importer1=new albaOpImporterVTK("importer"); albaString filename=ALBA_DATA_ROOT; filename<<"/Test_SurfaceEditor/surface.vtk"; importer1->TestModeOn(); importer1->SetFileName(filename); importer1->SetInput(storage->GetRoot()); importer1->ImportVTK(); albaSmartPointer surface = albaVMESurface::SafeDownCast(importer1->GetOutput()); surface->Update(); surface->GetOutput()->GetVTKData()->Update(); albaVMESurfaceEditor *editor = NULL; albaNEW(editor); vtkALBASmartPointer inputPolydata; inputPolydata->DeepCopy(vtkPolyData::SafeDownCast(surface->GetOutput()->GetVTKData())); int pointsNumberIn = inputPolydata->GetNumberOfPoints(); editor->SetData(inputPolydata,0.0); editor->Modified(); editor->Update(); vtkALBASmartPointer outputPolydata=vtkPolyData::SafeDownCast(editor->GetOutput()->GetVTKData()); outputPolydata->Modified(); outputPolydata->Update(); int pointsNumberOut = outputPolydata->GetNumberOfPoints(); m_Result = pointsNumberIn == pointsNumberOut; m_Result = true; TEST_RESULT; albaDEL(editor); albaDEL(importer1); albaDEL(storage); } //--------------------------------------------------------- void albaVMESurfaceEditorTest::TestSetGetVisualPipe() //--------------------------------------------------------- { albaVMESurfaceEditor *editor = NULL; albaNEW(editor); albaString pipeIn = "albaPipeSurfaceEditor"; editor->SetVisualPipe(pipeIn); albaString pipeOut = editor->GetVisualPipe(); m_Result = pipeIn.Compare(pipeOut) == 0; TEST_RESULT; albaDEL(editor); } /** * a2sdn packet.cpp * * @author (nklapste) * @version 0.0.0 */ #include #include #include #include "packet.h" /** * Constructor for a packet. Using a raw packet string representation. * * Useful for reconstructing a packets from a received packet string. * * @param packetRaw {@code std::string} */ Packet::Packet(string &packetRaw) { string delimiter = ":"; string typeRaw = packetRaw.substr(0, packetRaw.find(delimiter)); type = parseType(typeRaw); // we have no message if (packetRaw.length() == packetRaw.find(delimiter) + 1) { message = Message(); } else { string messageRaw = packetRaw.substr(packetRaw.find(delimiter) + 2, packetRaw.length()); message = parseMessage(messageRaw); } } /** * Constructor for a packet using a packet type and a {@code Message}. * * Useful for constructing a packet from raw data. * * @param type {@code std::string} * @param message {@code Message} */ Packet::Packet(string type, Message message) { Packet::type = parseType(type); Packet::message = std::move(message); } /** * Getter for a packets {@code type}. * * @return {@code std::string} */ string Packet::getType() { return type; } /** * Parse a string to check if it is a valid packet type. * * Valid strings include: * - "OPEN" * - "ACK" * - "QUERY" * - "ADD" * - "RELAY" * * @param type {@code std::string} * @return {@code std::string} */ string Packet::parseType(string &type) { if (type == OPEN || type == ACK || type == QUERY || type == ADD || type == RELAY) { // valid packet type } else { errno = EINVAL; perror("ERROR: Invalid type for packet"); exit(EINVAL); } return type; } /** * Getter method for a {@code Packet}'s {@code Message}. * * @return {@code Message} */ Message Packet::getMessage() { return message; } /** * Parse a string into a valid {@code Message}. * * @param messageRaw {@code std::string} * @return {@code Message} */ Message Packet::parseMessage(string &messageRaw) { Message message; istringstream iss(messageRaw); vector messageArgsRaw((istream_iterator(iss)), istream_iterator()); for (auto const &messageArgRaw: messageArgsRaw) { // TODO: ensure that only one colon std::string delimiter = ":"; std::string key = messageArgRaw.substr(0, messageArgRaw.find(delimiter)); std::string val = messageArgRaw.substr(messageArgRaw.find(delimiter) + 1, messageArgRaw.length()); MessageArg messageArg = make_tuple(key, val); message.emplace_back(messageArg); } return message; } /** * Get a serial string version of the packet ready to be written out. * * @return {@code std::string} the serial string version of a {@code Packet}. */ string Packet::toString() { string packetStr = type + ":"; for (auto const &MessageArg: message) { packetStr.append(" " + get<0>(MessageArg) + ":" + get<1>(MessageArg)); } return packetStr; } #include using namespace std; int main(){ string type; int rows ,columns; double price; cin >> type >> rows >> columns; if(type == "Premiere"){ price = rows * columns * 12.00; } else if(type == "Normal"){ price = rows * columns * 7.50; } else{ price = rows * columns * 5.00; } cout.setf(ios::fixed); cout.precision(2); cout << price << " leva" << endl; return 0; } approximator/filcompare #ifndef SRC_FCFILEINFO_HPP_ #define SRC_FCFILEINFO_HPP_ /** * @file FCFileInfo.hpp * * @brief class to store info on files * * @ingroup filcomp * * @author * Contact: * */ #include #include #include //for std::hash #include //for tuple #include enum class FCFileType : char { REG_FILE = 'r', DIR = 'd', CHAR_DEVICE = 'c', BLOCK_DEVICE = 'b', FIFO = 'f', LINK = 'l', SOCKET = 's', ERR = '?' }; inline std::ostream &operator<<(std::ostream &os, const FCFileType &type) { return os << static_cast::type>(type); } class FCFileInfoFactory; class FCFileInfo { private: friend class FCFileInfoFactory; friend std ::ostream &operator<<(std ::ostream &output, const FCFileInfo &f); friend bool operator<(const FCFileInfo &lhs, const FCFileInfo &rhs); friend bool operator==(const FCFileInfo &lhs, const FCFileInfo &rhs); friend bool operator>(const FCFileInfo &a, const FCFileInfo &b); friend bool operator<=(const FCFileInfo &a, const FCFileInfo &b); friend bool operator>=(const FCFileInfo &a, const FCFileInfo &b); friend bool operator!=(const FCFileInfo &a, const FCFileInfo &b); FCFileInfo(const std::string &t_FilePath, const std::string &t_FileAcls, const std::string &t_FileCaps, const uint64_t t_FileSize, const uint64_t t_FileCrc, const uint32_t t_FilePerms, const FCFileType t_FileType, const uint32_t t_FileOwner, const uint32_t t_FileOwnerGroup) : fileSize{ t_FileSize }, fileCrc{ t_FileCrc }, filePerms{ t_FilePerms }, fileType{ t_FileType }, fileOwner{ t_FileOwner }, fileOwnerGroup{ t_FileOwnerGroup }, filePath{ t_FilePath }, fileAcls{ t_FileAcls }, fileCaps{ t_FileCaps }, filePathHash{ std::hash{}(t_FilePath) }, fileCrcHash{ std::hash{}(t_FileCrc) } { } uint64_t fileSize; uint64_t fileCrc; uint32_t filePerms; FCFileType fileType; uint32_t fileOwner; uint32_t fileOwnerGroup; std::string filePath; std::string fileAcls; std::string fileCaps; std::size_t filePathHash; std::size_t fileCrcHash; //implementation of reflect solution to iterate over class t_embers [[nodiscard]] auto reflect() const; public: using FCFiles = std::vector; class FCFileInfoFactory { public: static FCFileInfo constructFCFileInfoFromFs(const std::string &fileName); static FCFileInfo constructFCFileInfo(const std::string &t_FilePath, const std::string &t_FileAcls, const std::string &t_FileCaps, const uint64_t t_FileSize, const uint64_t t_FileCrc, const uint32_t t_FilePerms, const FCFileType t_FileType, const uint32_t t_FileOwner, const uint32_t t_FileOwnerGroup); static FCFileInfo constructFCFileInfo(const std::string &t_FilePath, const std::string &t_FileAcls, const std::string &t_FileCaps, const uint64_t t_FileSize, const uint64_t t_FileCrc, const uint32_t t_FilePerms, const char t_FileType, const uint32_t t_FileOwner, const uint32_t t_FileOwnerGroup); }; virtual ~FCFileInfo() = default; FCFileInfo() = delete; [[nodiscard]] uint64_t getFileCrc() const noexcept; [[nodiscard]] uint64_t getFileSize() const noexcept; [[nodiscard]] uint32_t getFilePerms() const noexcept; [[nodiscard]] FCFileType getFileType() const noexcept; [[nodiscard]] char getFileTypeChar() const noexcept; [[nodiscard]] uint32_t getFileOwner() const noexcept; [[nodiscard]] uint32_t getFileOwnerGroup() const noexcept; [[nodiscard]] std::string getFilePath() const noexcept; [[nodiscard]] std::string getFileAcls() const noexcept; [[nodiscard]] std::string getFileCaps() const noexcept; static FCFileInfoFactory factory; FCFileInfo(const FCFileInfo &) = default; FCFileInfo &operator=(const FCFileInfo &) = default; FCFileInfo(FCFileInfo &&) = default; FCFileInfo &operator=(FCFileInfo &&) = default; }; template constexpr auto to_integral_type(E e) -> typename std::underlying_type::type { return static_cast::type>(e); } #endif // SRC_FCFILEINFO_HPP_cjayho/pgadmin3 /* * M_APM - mapm_rcp.c * * Copyright (C) 2000 - 2007 * * Permission to use, copy, and distribute this software and its * documentation for any purpose with or without fee is hereby granted, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. * * Permission to modify the software is granted. Permission to distribute * the modified code is granted. Modifications are to be distributed by * using the file 'license.txt' as a template to modify the file header. * 'license.txt' is available in the official MAPM distribution. * * This software is provided "as is" without express or implied warranty. */ /* * * This file contains the fast division and reciprocal functions * */ #include "pgAdmin3.h" #include "pgscript/utilities/mapm-lib/m_apm_lc.h" /****************************************************************************/ void m_apm_divide(M_APM rr, int places, M_APM aa, M_APM bb) { M_APM tmp0, tmp1; int sn, nexp, dplaces; sn = aa->m_apm_sign * bb->m_apm_sign; if (sn == 0) /* one number is zero, result is zero */ { if (bb->m_apm_sign == 0) { M_apm_log_error_msg(M_APM_RETURN, "\'m_apm_divide\', Divide by 0"); } M_set_to_zero(rr); return; } /* * Use the original 'Knuth' method for smaller divides. On the * author's system, this was the *approx* break even point before * the reciprocal method used below became faster. */ if (places < 250) { M_apm_sdivide(rr, places, aa, bb); return; } /* mimic the decimal place behavior of the original divide */ nexp = aa->m_apm_exponent - bb->m_apm_exponent; if (nexp > 0) dplaces = nexp + places; else dplaces = places; tmp0 = M_get_stack_var(); tmp1 = M_get_stack_var(); m_apm_reciprocal(tmp0, (dplaces + 8), bb); m_apm_multiply(tmp1, tmp0, aa); m_apm_round(rr, dplaces, tmp1); M_restore_stack(2); } /****************************************************************************/ void m_apm_reciprocal(M_APM rr, int places, M_APM aa) { M_APM last_x, guess, tmpN, tmp1, tmp2; char sbuf[32]; int ii, bflag, dplaces, nexp, tolerance; if (aa->m_apm_sign == 0) { M_apm_log_error_msg(M_APM_RETURN, "\'m_apm_reciprocal\', Input = 0"); M_set_to_zero(rr); return; } last_x = M_get_stack_var(); guess = M_get_stack_var(); tmpN = M_get_stack_var(); tmp1 = M_get_stack_var(); tmp2 = M_get_stack_var(); m_apm_absolute_value(tmpN, aa); /* normalize the input number (make the exponent 0) so the 'guess' below will not over/under flow on large magnitude exponents. */ nexp = aa->m_apm_exponent; tmpN->m_apm_exponent -= nexp; m_apm_to_string(sbuf, 15, tmpN); m_apm_set_double(guess, (1.0 / atof(sbuf))); tolerance = places + 4; dplaces = places + 16; bflag = FALSE; m_apm_negate(last_x, MM_Ten); /* Use the following iteration to calculate the reciprocal : X = X * [ 2 - N * X ] n+1 */ ii = 0; while (TRUE) { m_apm_multiply(tmp1, tmpN, guess); m_apm_subtract(tmp2, MM_Two, tmp1); m_apm_multiply(tmp1, tmp2, guess); if (bflag) break; m_apm_round(guess, dplaces, tmp1); /* force at least 2 iterations so 'last_x' has valid data */ if (ii != 0) { m_apm_subtract(tmp2, guess, last_x); if (tmp2->m_apm_sign == 0) break; /* * if we are within a factor of 4 on the error term, * we will be accurate enough after the *next* iteration * is complete. */ if ((-4 * tmp2->m_apm_exponent) > tolerance) bflag = TRUE; } m_apm_copy(last_x, guess); ii++; } m_apm_round(rr, places, tmp1); rr->m_apm_exponent -= nexp; rr->m_apm_sign = aa->m_apm_sign; M_restore_stack(5); } /****************************************************************************/ soerenbnoergaard/gunshot #ifndef CONVOLVER_H #define CONVOLVER_H #include #include #include "extra/Thread.hpp" #include "extra/Mutex.hpp" #include "fftconvolver/TwoStageFFTConvolver.h" // Subclass of Thread to get rid of some annoying descrutor error caused by unique_ptr. class MyThread : public Thread { public: MyThread(const char *name) : Thread(name) {}; }; // Convolver based on KlangFalter's Convolver class, converted from Juce to // DPF. class Convolver : public fftconvolver::TwoStageFFTConvolver { public: Convolver(); virtual ~Convolver(); protected: virtual void startBackgroundProcessing(); virtual void waitForBackgroundProcessing(); private: friend class ConvolverBackgroundThread; std::unique_ptr _thread; Signal _backgroundProcessingFinishedEvent; Signal _backgroundProcessingStartedEvent; }; #endif #include "WordBeamSearch.hpp" #include "Beam.hpp" #include #include #include std::vector wordBeamSearch(const IMatrix& mat, size_t beamWidth, const std::shared_ptr& lm, LanguageModelType lmType) { static int num = 0; ++num; if (num % 20 == 0) { std::cout << "checking sentence " << num << std::endl; } // dim0: T, dim1: C const size_t maxT = mat.rows(); const size_t maxC = mat.cols(); const size_t blank = maxC - 1; // initialise with genesis beam BeamList curr; BeamList last; const bool useNGrams = lmType == LanguageModelType::NGrams || lmType == LanguageModelType::NGramsForecast || lmType==LanguageModelType::NGramsForecastAndSample; const bool forcastNGrams = lmType == LanguageModelType::NGramsForecast || lmType == LanguageModelType::NGramsForecastAndSample; const bool sampleNGrams = lmType == LanguageModelType::NGramsForecastAndSample; // const bool useNGrams = true; // const bool forcastNGrams = false; // const bool sampleNGrams = false; last.addBeam(std::make_shared(lm, useNGrams, forcastNGrams, sampleNGrams)); // go over all time steps for (size_t t = 0; t < maxT; ++t) { // get k best beams and iterate const std::vector> bestBeams = last.getBestBeams(beamWidth); for (const auto& beam : bestBeams) { double prBlank=0.0, prNonBlank=0.0; // calc prob that path ends with a non-blank prNonBlank = beam->getText().empty() ? 0.0 : beam->getNonBlankProb() * mat.getAt(t, beam->getText().back()); // calc prob that path ends with a blank prBlank = beam->getTotalProb() * mat.getAt(t, blank); // add copy of original beam to current time step curr.addBeam(beam->createChildBeam(prBlank, prNonBlank)); // extend current beam const std::vector nextChars = beam->getNextChars(); for (const auto c : nextChars) { prBlank = 0.0; prNonBlank = 0.0; // last char in beam equals new char: path must end with blank if (!beam->getText().empty() && beam->getText().back() == c) { prNonBlank = mat.getAt(t, c) * beam->getBlankProb(); } // last char in beam and new char different else { prNonBlank = mat.getAt(t, c) * beam->getTotalProb(); } curr.addBeam(beam->createChildBeam(prBlank, prNonBlank, c)); } } last = std::move(curr); } // return best entry const auto bestBeam = last.getBestBeams(1)[0]; bestBeam->completeText(); return bestBeam->getText(); } Teles1/LuniaAsio #include "LogicDB.h" #include using namespace Lunia::XRated::Database; using namespace Lunia::XRated::Database::Info; namespace Lunia { namespace XRated { namespace Logic { LogicDB::LogicDB() { Init(); } NonPlayer* LogicDB::CreateNPC(IGameStateDatabase* db, NonPlayerInfo* info, uint8 team, int partyCnt, const Database::Info::StageInfo* stageInfo) { NonPlayer* npc = objectPool.CreateNPC(db, info, team, partyCnt, stageInfo); return npc; } Misc* LogicDB::CreateMisc(IGameStateDatabase* db, uint32 id) { return objectPool.CreateMisc(db, id); } Misc* LogicDB::CreateMisc(IGameStateDatabase* db, uint32 id, float duration) { Misc* obj = objectPool.CreateMisc(db, id); obj->SetDuration(duration); return obj; } uint32 LogicDB::CreateNPC(IGameStateDatabase* db, uint32 id, const float3& pos, const float3& dir, uint8 team , StageInfo::Npc::IdleStateType idleType, int pathGroupIndex, int defenceLocation, Serial owner, StageInfo::Npc::TransferType transferType, int partyCnt) { return objectThread.CreateNPC(db, id, pos, dir, team, idleType, pathGroupIndex, defenceLocation, owner, transferType, partyCnt); } uint32 LogicDB::CreateMisc(IGameStateDatabase* db, uint32 id, const float3& pos, const float3& dir, uint8 team, float duration, float hp) { return objectThread.CreateMisc(db, id, pos, dir, team, duration, hp); } TombStone* LogicDB::CreateTombstone(IGameStateDatabase* db, const ObjectData& objData) { return objectPool.CreateTombstone(db, objData); } Player* LogicDB::CreatePlayerPvpItem(IGameStateDatabase* db, const ILogic::PlayerInitialData& data) { return objectPool.CreatePlayerPvpItem(db, data); } Player* LogicDB::CreatePlayer(IGameStateDatabase* db, const ILogic::PlayerInitialData& data) { return objectPool.CreatePlayer(db, data); } void LogicDB::ReleasePlayerPvpItem(Player* obj) { objectPool.Release((PlayerPvpItem*)obj); } void LogicDB::ReleasePlayer(Player* obj) { objectPool.Release(obj); } void LogicDB::ReleaseNPC(NonPlayer* obj) { objectPool.Release(obj); } void LogicDB::ReleaseMisc(Misc* obj) { objectPool.Release(obj); } void LogicDB::Init() { actionDB.Init(); objectPool.Init( &actionDB ); stateDB.Init(); } } } } 10-100 class Solution { public: bool isIsomorphic(string s, string t) { if (s.size() != t.size()) { return false; } vector table1(256); vector table2(256); for (int i = 0; i < s.size(); ++i) { if (table1[s[i]] == 0 && table2[t[i]] == 0) { table1[s[i]] = t[i]; table2[t[i]] = s[i]; } else if (table1[s[i]] != t[i]) { return false; } } return true; } }; saranshbht/bsc-codes #include using namespace std; int main(){ int n; bool flag=true; bool adjflag=true; bool **adjm; int **adjl; cout<<"Enter the number of vertices of the graph:"; cin>>n; adjm=new bool*[n]; adjl=new int*[n]; for(int i=0;i>d; cout< "; for(int j=0;j>adjl[i][j]; adjm[i][adjl[i][j]]=1; } cout<ComicSansMS/GhulbusMathinclude/gbMath/RationalIO.hpp #ifndef GHULBUS_LIBRARY_INCLUDE_GUARD_MATH_RATIONAL_IO_HPP #define GHULBUS_LIBRARY_INCLUDE_GUARD_MATH_RATIONAL_IO_HPP /** @file * * @brief ostream inserter functions for rational type. * @author () */ #include #include #include namespace GHULBUS_MATH_NAMESPACE { template inline std::ostream& operator<<(std::ostream& os, Rational const& rhs) { return os << rhs.numerator() << '/' << rhs.denominator(); } inline std::ostream& operator<<(std::ostream& os, Rational const& rhs) { return os << static_cast(rhs.numerator()) << '/' << static_cast(rhs.denominator()); } inline std::ostream& operator<<(std::ostream& os, Rational const& rhs) { return os << static_cast(rhs.numerator()) << '/' << static_cast(rhs.denominator()); } inline std::ostream& operator<<(std::ostream& os, Rational const& rhs) { return os << static_cast(rhs.numerator()) << '/' << static_cast(rhs.denominator()); } } #endif // Assignment 1: Alternating disks problem, left-to-right algorithm // // Given 2n alternating disks (dark, dark, light, light) // the program reads the number of single color disks (light or dark), // arranges the disks in the correct order and outputs the number of swaps // INPUT: an even positive integer n and a list of 2n disks of alternating // colors dark-dark-light-light, starting with dark // OUTPUT: a list of 2n disks, the first n disks are light and the next n // disks are dark, and an integer m representing the number of moves necessary // to move the dark ones before the light ones #include #include #include using namespace std; // YOU NEED TO IMPLEMENT THIS FUNCTION // function to print the list of disks, given the number of single color disks // and the actual list // n represents the number of single color disks // disks represents the list of disks (index 0 being the first disk) where // 0 = a dark color disk // 1 = a light color disk void print_disks(int n, char *disks) { cout << "List of disks\n"; for (int i = 0; i < 2*n; ++i) { if (disks[i] == 0) { cout << "D "; } else { cout << "L "; } } cout << endl; } int main() { int n, m, i, k; char *disks; // display the header cout << endl << "CPSC 335-x - Programming Assignment #1" << endl; cout << "The alternating disks problem: left-to-right algorithm" << endl; cout << "Enter an even number of single color disks (light or dark)" << endl; // read the number of disks cin >> n; // allocate space for the disks disks = new char[n*2]; // set the initial configurations for the disks to alternate for( i=0; i < n/2; i++) { disks[4*i ] = 0; disks[4*i+1] = 0; disks[4*i+2] = 1; disks[4*i+3] = 1; } // print the initial configuration of the list of disks cout << "Initial configuration" << endl; print_disks(n,disks); // reset the number of moves to 0; m = 0; // loop to push dark ones before light ones for (k=0; k < 2*n ; k++) { for (int j = 0; j < 2*n - 1; j++) { if (disks[j] > disks[j+1]) { disks[j] = 0; disks[j+1] = 1; m++; } } } // after shuffling them cout << "After moving darker ones to the left" << endl; print_disks(n, disks); // print the total number of moves cout << "Number of swaps is " << m << endl; // de-allocate the dynamic memory space delete [] disks; //return EXIT_SUCCESS; return EXIT_SUCCESS; } #pragma once #include #include #include "npy_types.hpp" #include "Descriptor.hpp" class Shape { private: size_t _size; unsigned *_dims = nullptr; public: template Shape(size_t nDims, arg_t... dims): _size(nDims) { _dims = new unsigned[_size]{(unsigned)dims...}; } Shape(); Shape(const Shape&); Shape(Shape&&); Shape& operator=(const Shape&); Shape& operator=(Shape&&); ~Shape(); const unsigned& operator[](size_t index) const; const unsigned* begin() const; const unsigned* end() const; size_t dimensions() const; size_t nElements() const; friend std::ostream& operator<<(std::ostream& s, const Shape& shape); static Shape noShape(); }; struct FieldDescriptor: public Descriptor { FieldType type; size_t align; Shape shape=Shape(); FieldDescriptor(){}; FieldDescriptor(FieldType t, size_t a, Shape&& s=Shape::noShape()); std::string toString() const; size_t size() const { return shape.nElements()*type.size; }; }; struct Field { FieldDescriptor _descr; size_t _size, _padding=0, _offset=0; Field(){} Field(const FieldDescriptor& d): _descr(d){} };/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: TreeNode* constructMaximumBinaryTree(vector& nums) { // See https://leetcode.com/problems/maximum-binary-tree/discuss/106146/C%2B%2B-O(N)-solution deque stack; for (int n : nums) { TreeNode* node = new TreeNode(n); while (!stack.empty() && stack.back()->val < n) { node->left = stack.back(); stack.pop_back(); } if (!stack.empty()) { stack.back()->right = node; } stack.push_back(node); } return stack.front(); } }; /* Programa que indica si un numero es Par o Impar */ #include int main() { short numero; std::cout << "Numero: "; std::cin >> numero; if (numero/2 * 2 == numero) { std::cout << "El numero es PAR!!" << std::endl; } else { std::cout << "El numero es IMPAR!!" << std::endl; } return 0; } test/cctest/test-field-type-tracking.cc // Copyright 2015 the V8 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. #include #include #include "test/cctest/test-api.h" #include "src/v8.h" #include "src/compilation-cache.h" #include "src/execution.h" #include "src/factory.h" #include "src/field-type.h" #include "src/global-handles.h" #include "src/ic/stub-cache.h" #include "src/macro-assembler.h" using namespace v8::internal; // TODO(ishell): fix this once TransitionToPrototype stops generalizing // all field representations (similar to crbug/448711 where elements kind // and observed transitions caused generalization of all field representations). const bool IS_PROTO_TRANS_ISSUE_FIXED = false; // TODO(ishell): fix this once TransitionToAccessorProperty is able to always // keep map in fast mode. const bool IS_ACCESSOR_FIELD_SUPPORTED = false; // Number of properties used in the tests. const int kPropCount = 7; // // Helper functions. // static Handle MakeString(const char* str) { Isolate* isolate = CcTest::i_isolate(); Factory* factory = isolate->factory(); return factory->InternalizeUtf8String(str); } static Handle MakeName(const char* str, int suffix) { EmbeddedVector buffer; SNPrintF(buffer, "%s%d", str, suffix); return MakeString(buffer.start()); } static Handle CreateAccessorPair(bool with_getter, bool with_setter) { Isolate* isolate = CcTest::i_isolate(); Factory* factory = isolate->factory(); Handle pair = factory->NewAccessorPair(); Handle empty_string = factory->empty_string(); if (with_getter) { Handle func = factory->NewFunction(empty_string); pair->set_getter(*func); } if (with_setter) { Handle func = factory->NewFunction(empty_string); pair->set_setter(*func); } return pair; } static bool EqualDetails(DescriptorArray* descriptors, int descriptor, PropertyType type, PropertyAttributes attributes, Representation representation, int field_index = -1) { PropertyDetails details = descriptors->GetDetails(descriptor); if (details.type() != type) return false; if (details.attributes() != attributes) return false; if (!details.representation().Equals(representation)) return false; if (field_index >= 0 && details.field_index() != field_index) return false; return true; } class Expectations { static const int MAX_PROPERTIES = 10; Isolate* isolate_; ElementsKind elements_kind_; PropertyType types_[MAX_PROPERTIES]; PropertyAttributes attributes_[MAX_PROPERTIES]; Representation representations_[MAX_PROPERTIES]; // FieldType for kField, value for DATA_CONSTANT and getter for // ACCESSOR_CONSTANT. Handle values_[MAX_PROPERTIES]; // Setter for ACCESSOR_CONSTANT. Handle setter_values_[MAX_PROPERTIES]; int number_of_properties_; public: explicit Expectations(Isolate* isolate, ElementsKind elements_kind) : isolate_(isolate), elements_kind_(elements_kind), number_of_properties_(0) {} explicit Expectations(Isolate* isolate) : Expectations( isolate, isolate->object_function()->initial_map()->elements_kind()) {} void Init(int index, PropertyType type, PropertyAttributes attributes, Representation representation, Handle value) { CHECK(index < MAX_PROPERTIES); types_[index] = type; attributes_[index] = attributes; representations_[index] = representation; values_[index] = value; } void Print() const { OFStream os(stdout); os << "Expectations: #" << number_of_properties_ << "\n"; for (int i = 0; i < number_of_properties_; i++) { os << " " << i << ": "; os << "Descriptor @ "; if (types_[i] == ACCESSOR_CONSTANT) { os << "(get: " << Brief(*values_[i]) << ", set: " << Brief(*setter_values_[i]) << ") "; } else { os << Brief(*values_[i]); } os << " ("; switch (types_[i]) { case DATA_CONSTANT: os << "immutable "; // Fall through. case DATA: os << "data"; break; case ACCESSOR_CONSTANT: os << "immutable "; // Fall through. case ACCESSOR: os << "accessor"; break; } os << ": " << representations_[i].Mnemonic(); os << ", attrs: " << attributes_[i] << ")\n"; } os << "\n"; } void SetElementsKind(ElementsKind elements_kind) { elements_kind_ = elements_kind; } Handle GetFieldType(int index) { CHECK(index < MAX_PROPERTIES); CHECK(types_[index] == DATA || types_[index] == ACCESSOR); return Handle::cast(values_[index]); } void SetDataField(int index, PropertyAttributes attrs, Representation representation, Handle value) { Init(index, DATA, attrs, representation, value); } void SetDataField(int index, Representation representation, Handle value) { SetDataField(index, attributes_[index], representation, value); } void SetAccessorField(int index, PropertyAttributes attrs) { Init(index, ACCESSOR, attrs, Representation::Tagged(), FieldType::Any(isolate_)); } void SetAccessorField(int index) { SetAccessorField(index, attributes_[index]); } void SetDataConstant(int index, PropertyAttributes attrs, Handle value) { Init(index, DATA_CONSTANT, attrs, Representation::HeapObject(), value); } void SetDataConstant(int index, Handle value) { SetDataConstant(index, attributes_[index], value); } void SetAccessorConstant(int index, PropertyAttributes attrs, Handle getter, Handle setter) { Init(index, ACCESSOR_CONSTANT, attrs, Representation::Tagged(), getter); setter_values_[index] = setter; } void SetAccessorConstantComponent(int index, PropertyAttributes attrs, AccessorComponent component, Handle accessor) { CHECK_EQ(ACCESSOR_CONSTANT, types_[index]); CHECK(index < number_of_properties_); if (component == ACCESSOR_GETTER) { values_[index] = accessor; } else { setter_values_[index] = accessor; } } void SetAccessorConstant(int index, PropertyAttributes attrs, Handle pair) { Handle getter = handle(pair->getter(), isolate_); Handle setter = handle(pair->setter(), isolate_); SetAccessorConstant(index, attrs, getter, setter); } void SetAccessorConstant(int index, Handle getter, Handle setter) { SetAccessorConstant(index, attributes_[index], getter, setter); } void SetAccessorConstant(int index, Handle pair) { Handle getter = handle(pair->getter(), isolate_); Handle setter = handle(pair->setter(), isolate_); SetAccessorConstant(index, getter, setter); } void GeneralizeRepresentation(int index) { CHECK(index < number_of_properties_); representations_[index] = Representation::Tagged(); if (types_[index] == DATA || types_[index] == ACCESSOR) { values_[index] = FieldType::Any(isolate_); } } bool Check(DescriptorArray* descriptors, int descriptor) const { PropertyType type = types_[descriptor]; if (!EqualDetails(descriptors, descriptor, type, attributes_[descriptor], representations_[descriptor])) { return false; } Object* value = descriptors->GetValue(descriptor); Object* expected_value = *values_[descriptor]; switch (type) { case DATA: case ACCESSOR: { FieldType* type = descriptors->GetFieldType(descriptor); return FieldType::cast(expected_value) == type; } case DATA_CONSTANT: return value == expected_value; case ACCESSOR_CONSTANT: { if (value == expected_value) return true; if (!value->IsAccessorPair()) return false; AccessorPair* pair = AccessorPair::cast(value); return pair->Equals(expected_value, *setter_values_[descriptor]); } } UNREACHABLE(); return false; } bool Check(Map* map, int expected_nof) const { CHECK_EQ(elements_kind_, map->elements_kind()); CHECK(number_of_properties_ <= MAX_PROPERTIES); CHECK_EQ(expected_nof, map->NumberOfOwnDescriptors()); CHECK(!map->is_dictionary_map()); DescriptorArray* descriptors = map->instance_descriptors(); CHECK(expected_nof <= number_of_properties_); for (int i = 0; i < expected_nof; i++) { if (!Check(descriptors, i)) { Print(); #ifdef OBJECT_PRINT descriptors->Print(); #endif Check(descriptors, i); return false; } } return true; } bool Check(Map* map) const { return Check(map, number_of_properties_); } // // Helper methods for initializing expectations and adding properties to // given |map|. // Handle AsElementsKind(Handle map, ElementsKind elements_kind) { elements_kind_ = elements_kind; map = Map::AsElementsKind(map, elements_kind); CHECK_EQ(elements_kind_, map->elements_kind()); return map; } Handle AddDataField(Handle map, PropertyAttributes attributes, Representation representation, Handle heap_type) { CHECK_EQ(number_of_properties_, map->NumberOfOwnDescriptors()); int property_index = number_of_properties_++; SetDataField(property_index, attributes, representation, heap_type); Handle name = MakeName("prop", property_index); return Map::CopyWithField(map, name, heap_type, attributes, representation, INSERT_TRANSITION) .ToHandleChecked(); } Handle AddDataConstant(Handle map, PropertyAttributes attributes, Handle value) { CHECK_EQ(number_of_properties_, map->NumberOfOwnDescriptors()); int property_index = number_of_properties_++; SetDataConstant(property_index, attributes, value); Handle name = MakeName("prop", property_index); return Map::CopyWithConstant(map, name, value, attributes, INSERT_TRANSITION) .ToHandleChecked(); } Handle TransitionToDataField(Handle map, PropertyAttributes attributes, Representation representation, Handle heap_type, Handle value) { CHECK_EQ(number_of_properties_, map->NumberOfOwnDescriptors()); int property_index = number_of_properties_++; SetDataField(property_index, attributes, representation, heap_type); Handle name = MakeName("prop", property_index); return Map::TransitionToDataProperty( map, name, value, attributes, Object::CERTAINLY_NOT_STORE_FROM_KEYED); } Handle TransitionToDataConstant(Handle map, PropertyAttributes attributes, Handle value) { CHECK_EQ(number_of_properties_, map->NumberOfOwnDescriptors()); int property_index = number_of_properties_++; SetDataConstant(property_index, attributes, value); Handle name = MakeName("prop", property_index); return Map::TransitionToDataProperty( map, name, value, attributes, Object::CERTAINLY_NOT_STORE_FROM_KEYED); } Handle FollowDataTransition(Handle map, PropertyAttributes attributes, Representation representation, Handle heap_type) { CHECK_EQ(number_of_properties_, map->NumberOfOwnDescriptors()); int property_index = number_of_properties_++; SetDataField(property_index, attributes, representation, heap_type); Handle name = MakeName("prop", property_index); Map* target = TransitionArray::SearchTransition(*map, kData, *name, attributes); CHECK(target != NULL); return handle(target); } Handle AddAccessorConstant(Handle map, PropertyAttributes attributes, Handle pair) { CHECK_EQ(number_of_properties_, map->NumberOfOwnDescriptors()); int property_index = number_of_properties_++; SetAccessorConstant(property_index, attributes, pair); Handle name = MakeName("prop", property_index); AccessorConstantDescriptor new_desc(name, pair, attributes); return Map::CopyInsertDescriptor(map, &new_desc, INSERT_TRANSITION); } Handle AddAccessorConstant(Handle map, PropertyAttributes attributes, Handle getter, Handle setter) { CHECK_EQ(number_of_properties_, map->NumberOfOwnDescriptors()); int property_index = number_of_properties_++; SetAccessorConstant(property_index, attributes, getter, setter); Handle name = MakeName("prop", property_index); CHECK(!getter->IsNull(isolate_) || !setter->IsNull(isolate_)); Factory* factory = isolate_->factory(); if (!getter->IsNull(isolate_)) { Handle pair = factory->NewAccessorPair(); pair->SetComponents(*getter, *factory->null_value()); AccessorConstantDescriptor new_desc(name, pair, attributes); map = Map::CopyInsertDescriptor(map, &new_desc, INSERT_TRANSITION); } if (!setter->IsNull(isolate_)) { Handle pair = factory->NewAccessorPair(); pair->SetComponents(*getter, *setter); AccessorConstantDescriptor new_desc(name, pair, attributes); map = Map::CopyInsertDescriptor(map, &new_desc, INSERT_TRANSITION); } return map; } Handle TransitionToAccessorConstant(Handle map, PropertyAttributes attributes, Handle pair) { CHECK_EQ(number_of_properties_, map->NumberOfOwnDescriptors()); int property_index = number_of_properties_++; SetAccessorConstant(property_index, attributes, pair); Handle name = MakeName("prop", property_index); Isolate* isolate = CcTest::i_isolate(); Handle getter(pair->getter(), isolate); Handle setter(pair->setter(), isolate); int descriptor = map->instance_descriptors()->SearchWithCache(isolate, *name, *map); map = Map::TransitionToAccessorProperty(isolate, map, name, descriptor, getter, setter, attributes); CHECK(!map->is_deprecated()); CHECK(!map->is_dictionary_map()); return map; } }; //////////////////////////////////////////////////////////////////////////////// // A set of tests for property reconfiguration that makes new transition tree // branch. // TEST(ReconfigureAccessorToNonExistingDataField) { CcTest::InitializeVM(); v8::HandleScope scope(CcTest::isolate()); Isolate* isolate = CcTest::i_isolate(); Handle any_type = FieldType::Any(isolate); Handle none_type = FieldType::None(isolate); Handle pair = CreateAccessorPair(true, true); Expectations expectations(isolate); // Create a map, add required properties to it and initialize expectations. Handle initial_map = Map::Create(isolate, 0); Handle map = initial_map; map = expectations.AddAccessorConstant(map, NONE, pair); CHECK(!map->is_deprecated()); CHECK(map->is_stable()); CHECK(expectations.Check(*map)); Handle new_map = Map::ReconfigureProperty( map, 0, kData, NONE, Representation::None(), none_type, FORCE_FIELD); // |map| did not change except marked unstable. CHECK(!map->is_deprecated()); CHECK(!map->is_stable()); CHECK(expectations.Check(*map)); expectations.SetDataField(0, NONE, Representation::None(), none_type); CHECK(!new_map->is_deprecated()); CHECK(new_map->is_stable()); CHECK(expectations.Check(*new_map)); Handle new_map2 = Map::ReconfigureProperty( map, 0, kData, NONE, Representation::None(), none_type, FORCE_FIELD); CHECK_EQ(*new_map, *new_map2); Handle value(Smi::FromInt(0), isolate); Handle prepared_map = Map::PrepareForDataProperty(new_map, 0, value); // None to Smi generalization is trivial, map does not change. CHECK_EQ(*new_map, *prepared_map); expectations.SetDataField(0, NONE, Representation::Smi(), any_type); CHECK(prepared_map->is_stable()); CHECK(expectations.Check(*prepared_map)); // Now create an object with |map|, migrate it to |prepared_map| and ensure // that the data property is uninitialized. Factory* factory = isolate->factory(); Handle obj = factory->NewJSObjectFromMap(map); JSObject::MigrateToMap(obj, prepared_map); FieldIndex index = FieldIndex::ForDescriptor(*prepared_map, 0); CHECK(obj->RawFastPropertyAt(index)->IsUninitialized(isolate)); #ifdef VERIFY_HEAP obj->ObjectVerify(); #endif } // This test checks that the LookupIterator machinery involved in // JSObject::SetOwnPropertyIgnoreAttributes() does not try to migrate object // to a map with a property with None representation. TEST(ReconfigureAccessorToNonExistingDataFieldHeavy) { CcTest::InitializeVM(); Isolate* isolate = CcTest::i_isolate(); Factory* factory = isolate->factory(); v8::HandleScope scope(CcTest::isolate()); CompileRun( "function getter() { return 1; };" "function setter() {};" "var o = {};" "Object.defineProperty(o, 'foo', " " { get: getter, set: setter, " " configurable: true, enumerable: true});"); Handle foo_str = factory->InternalizeUtf8String("foo"); Handle obj_name = factory->InternalizeUtf8String("o"); Handle obj_value = Object::GetProperty(isolate->global_object(), obj_name).ToHandleChecked(); CHECK(obj_value->IsJSObject()); Handle obj = Handle::cast(obj_value); CHECK_EQ(1, obj->map()->NumberOfOwnDescriptors()); CHECK(obj->map()->instance_descriptors()->GetValue(0)->IsAccessorPair()); Handle value(Smi::FromInt(42), isolate); JSObject::SetOwnPropertyIgnoreAttributes(obj, foo_str, value, NONE).Check(); // Check that the property contains |value|. CHECK_EQ(1, obj->map()->NumberOfOwnDescriptors()); FieldIndex index = FieldIndex::ForDescriptor(obj->map(), 0); Object* the_value = obj->RawFastPropertyAt(index); CHECK(the_value->IsSmi()); CHECK_EQ(42, Smi::cast(the_value)->value()); } //////////////////////////////////////////////////////////////////////////////// // A set of tests for representation generalization case. // // This test ensures that representation/field type generalization at // |property_index| is done correctly independently of the fact that the |map| // is detached from transition tree or not. // // {} - p0 - p1 - p2: |detach_point_map| // | // X - detached at |detach_property_at_index| // | // + - p3 - p4: |map| // // Detaching does not happen if |detach_property_at_index| is -1. // static void TestGeneralizeRepresentation( int detach_property_at_index, int property_index, Representation from_representation, Handle from_type, Representation to_representation, Handle to_type, Representation expected_representation, Handle expected_type, bool expected_deprecation, bool expected_field_type_dependency) { Isolate* isolate = CcTest::i_isolate(); Handle any_type = FieldType::Any(isolate); CHECK(detach_property_at_index >= -1 && detach_property_at_index < kPropCount); CHECK(property_index < kPropCount); CHECK_NE(detach_property_at_index, property_index); const bool is_detached_map = detach_property_at_index >= 0; Expectations expectations(isolate); // Create a map, add required properties to it and initialize expectations. Handle initial_map = Map::Create(isolate, 0); Handle map = initial_map; Handle detach_point_map; for (int i = 0; i < kPropCount; i++) { if (i == property_index) { map = expectations.AddDataField(map, NONE, from_representation, from_type); } else { map = expectations.AddDataField(map, NONE, Representation::Smi(), any_type); if (i == detach_property_at_index) { detach_point_map = map; } } } CHECK(!map->is_deprecated()); CHECK(map->is_stable()); CHECK(expectations.Check(*map)); Zone zone(isolate->allocator()); if (is_detached_map) { detach_point_map = Map::ReconfigureProperty( detach_point_map, detach_property_at_index, kData, NONE, Representation::Tagged(), any_type, FORCE_FIELD); expectations.SetDataField(detach_property_at_index, Representation::Tagged(), any_type); CHECK(map->is_deprecated()); CHECK(expectations.Check(*detach_point_map, detach_point_map->NumberOfOwnDescriptors())); } // Create new maps by generalizing representation of propX field. Handle field_owner(map->FindFieldOwner(property_index), isolate); CompilationInfo info(ArrayVector("testing"), isolate, &zone); CHECK(!info.dependencies()->HasAborted()); info.dependencies()->AssumeFieldType(field_owner); Handle new_map = Map::ReconfigureProperty(map, property_index, kData, NONE, to_representation, to_type, FORCE_FIELD); expectations.SetDataField(property_index, expected_representation, expected_type); CHECK(!new_map->is_deprecated()); CHECK(expectations.Check(*new_map)); if (is_detached_map) { CHECK(!map->is_stable()); CHECK(map->is_deprecated()); CHECK_NE(*map, *new_map); CHECK_EQ(expected_field_type_dependency && !field_owner->is_deprecated(), info.dependencies()->HasAborted()); } else if (expected_deprecation) { CHECK(!map->is_stable()); CHECK(map->is_deprecated()); CHECK(field_owner->is_deprecated()); CHECK_NE(*map, *new_map); CHECK(!info.dependencies()->HasAborted()); } else { CHECK(!field_owner->is_deprecated()); CHECK(map->is_stable()); // Map did not change, must be left stable. CHECK_EQ(*map, *new_map); CHECK_EQ(expected_field_type_dependency, info.dependencies()->HasAborted()); } { // Check that all previous maps are not stable. Map* tmp = *new_map; while (true) { Object* back = tmp->GetBackPointer(); if (back->IsUndefined(isolate)) break; tmp = Map::cast(back); CHECK(!tmp->is_stable()); } } info.dependencies()->Rollback(); // Properly cleanup compilation info. // Update all deprecated maps and check that they are now the same. Handle updated_map = Map::Update(map); CHECK_EQ(*new_map, *updated_map); } static void TestGeneralizeRepresentation( Representation from_representation, Handle from_type, Representation to_representation, Handle to_type, Representation expected_representation, Handle expected_type, bool expected_deprecation, bool expected_field_type_dependency) { // Check the cases when the map being reconfigured is a part of the // transition tree. STATIC_ASSERT(kPropCount > 4); int indices[] = {0, 2, kPropCount - 1}; for (int i = 0; i < static_cast(arraysize(indices)); i++) { TestGeneralizeRepresentation( -1, indices[i], from_representation, from_type, to_representation, to_type, expected_representation, expected_type, expected_deprecation, expected_field_type_dependency); } if (!from_representation.IsNone()) { // Check the cases when the map being reconfigured is NOT a part of the // transition tree. "None -> anything" representation changes make sense // only for "attached" maps. int indices[] = {0, kPropCount - 1}; for (int i = 0; i < static_cast(arraysize(indices)); i++) { TestGeneralizeRepresentation( indices[i], 2, from_representation, from_type, to_representation, to_type, expected_representation, expected_type, expected_deprecation, expected_field_type_dependency); } // Check that reconfiguration to the very same field works correctly. Representation representation = from_representation; Handle type = from_type; TestGeneralizeRepresentation(-1, 2, representation, type, representation, type, representation, type, false, false); } } static void TestGeneralizeRepresentation(Representation from_representation, Handle from_type, Representation to_representation, Handle to_type, Representation expected_representation, Handle expected_type) { const bool expected_deprecation = true; const bool expected_field_type_dependency = false; TestGeneralizeRepresentation( from_representation, from_type, to_representation, to_type, expected_representation, expected_type, expected_deprecation, expected_field_type_dependency); } static void TestGeneralizeRepresentationTrivial( Representation from_representation, Handle from_type, Representation to_representation, Handle to_type, Representation expected_representation, Handle expected_type, bool expected_field_type_dependency = true) { const bool expected_deprecation = false; TestGeneralizeRepresentation( from_representation, from_type, to_representation, to_type, expected_representation, expected_type, expected_deprecation, expected_field_type_dependency); } TEST(GeneralizeRepresentationSmiToDouble) { CcTest::InitializeVM(); v8::HandleScope scope(CcTest::isolate()); Isolate* isolate = CcTest::i_isolate(); Handle any_type = FieldType::Any(isolate); TestGeneralizeRepresentation(Representation::Smi(), any_type, Representation::Double(), any_type, Representation::Double(), any_type); } TEST(GeneralizeRepresentationSmiToTagged) { CcTest::InitializeVM(); v8::HandleScope scope(CcTest::isolate()); Isolate* isolate = CcTest::i_isolate(); Handle any_type = FieldType::Any(isolate); Handle value_type = FieldType::Class(Map::Create(isolate, 0), isolate); TestGeneralizeRepresentation(Representation::Smi(), any_type, Representation::HeapObject(), value_type, Representation::Tagged(), any_type); } TEST(GeneralizeRepresentationDoubleToTagged) { CcTest::InitializeVM(); v8::HandleScope scope(CcTest::isolate()); Isolate* isolate = CcTest::i_isolate(); Handle any_type = FieldType::Any(isolate); Handle value_type = FieldType::Class(Map::Create(isolate, 0), isolate); TestGeneralizeRepresentation(Representation::Double(), any_type, Representation::HeapObject(), value_type, Representation::Tagged(), any_type); } TEST(GeneralizeRepresentationHeapObjectToTagged) { CcTest::InitializeVM(); v8::HandleScope scope(CcTest::isolate()); Isolate* isolate = CcTest::i_isolate(); Handle any_type = FieldType::Any(isolate); Handle value_type = FieldType::Class(Map::Create(isolate, 0), isolate); TestGeneralizeRepresentation(Representation::HeapObject(), value_type, Representation::Smi(), any_type, Representation::Tagged(), any_type); } TEST(GeneralizeRepresentationHeapObjectToHeapObject) { CcTest::InitializeVM(); v8::HandleScope scope(CcTest::isolate()); Isolate* isolate = CcTest::i_isolate(); Handle any_type = FieldType::Any(isolate); Handle current_type = FieldType::Class(Map::Create(isolate, 0), isolate); Handle new_type = FieldType::Class(Map::Create(isolate, 0), isolate); Handle expected_type = any_type; TestGeneralizeRepresentationTrivial( Representation::HeapObject(), current_type, Representation::HeapObject(), new_type, Representation::HeapObject(), expected_type); current_type = expected_type; new_type = FieldType::Class(Map::Create(isolate, 0), isolate); TestGeneralizeRepresentationTrivial( Representation::HeapObject(), any_type, Representation::HeapObject(), new_type, Representation::HeapObject(), any_type, false); } TEST(GeneralizeRepresentationNoneToSmi) { CcTest::InitializeVM(); v8::HandleScope scope(CcTest::isolate()); Isolate* isolate = CcTest::i_isolate(); Handle none_type = FieldType::None(isolate); Handle any_type = FieldType::Any(isolate); // None -> Smi representation change is trivial. TestGeneralizeRepresentationTrivial(Representation::None(), none_type, Representation::Smi(), any_type, Representation::Smi(), any_type); } TEST(GeneralizeRepresentationNoneToDouble) { CcTest::InitializeVM(); v8::HandleScope scope(CcTest::isolate()); Isolate* isolate = CcTest::i_isolate(); Handle none_type = FieldType::None(isolate); Handle any_type = FieldType::Any(isolate); // None -> Double representation change is NOT trivial. TestGeneralizeRepresentation(Representation::None(), none_type, Representation::Double(), any_type, Representation::Double(), any_type); } TEST(GeneralizeRepresentationNoneToHeapObject) { CcTest::InitializeVM(); v8::HandleScope scope(CcTest::isolate()); Isolate* isolate = CcTest::i_isolate(); Handle none_type = FieldType::None(isolate); Handle value_type = FieldType::Class(Map::Create(isolate, 0), isolate); // None -> HeapObject representation change is trivial. TestGeneralizeRepresentationTrivial(Representation::None(), none_type, Representation::HeapObject(), value_type, Representation::HeapObject(), value_type); } TEST(GeneralizeRepresentationNoneToTagged) { CcTest::InitializeVM(); v8::HandleScope scope(CcTest::isolate()); Isolate* isolate = CcTest::i_isolate(); Handle none_type = FieldType::None(isolate); Handle any_type = FieldType::Any(isolate); // None -> HeapObject representation change is trivial. TestGeneralizeRepresentationTrivial(Representation::None(), none_type, Representation::Tagged(), any_type, Representation::Tagged(), any_type); } //////////////////////////////////////////////////////////////////////////////// // A set of tests for representation generalization case with kAccessor // properties. // TEST(GeneralizeRepresentationWithAccessorProperties) { CcTest::InitializeVM(); v8::HandleScope scope(CcTest::isolate()); Isolate* isolate = CcTest::i_isolate(); Handle any_type = FieldType::Any(isolate); Handle pair = CreateAccessorPair(true, true); const int kAccessorProp = kPropCount / 2; Expectations expectations(isolate); // Create a map, add required properties to it and initialize expectations. Handle initial_map = Map::Create(isolate, 0); Handle map = initial_map; for (int i = 0; i < kPropCount; i++) { if (i == kAccessorProp) { map = expectations.AddAccessorConstant(map, NONE, pair); } else { map = expectations.AddDataField(map, NONE, Representation::Smi(), any_type); } } CHECK(!map->is_deprecated()); CHECK(map->is_stable()); CHECK(expectations.Check(*map)); // Create new maps by generalizing representation of propX field. Handle maps[kPropCount]; for (int i = 0; i < kPropCount; i++) { if (i == kAccessorProp) { // Skip accessor property reconfiguration. maps[i] = maps[i - 1]; continue; } Handle new_map = Map::ReconfigureProperty( map, i, kData, NONE, Representation::Double(), any_type, FORCE_FIELD); maps[i] = new_map; expectations.SetDataField(i, Representation::Double(), any_type); CHECK(!map->is_stable()); CHECK(map->is_deprecated()); CHECK_NE(*map, *new_map); CHECK(i == 0 || maps[i - 1]->is_deprecated()); CHECK(!new_map->is_deprecated()); CHECK(expectations.Check(*new_map)); } Handle active_map = maps[kPropCount - 1]; CHECK(!active_map->is_deprecated()); // Update all deprecated maps and check that they are now the same. Handle updated_map = Map::Update(map); CHECK_EQ(*active_map, *updated_map); for (int i = 0; i < kPropCount; i++) { updated_map = Map::Update(maps[i]); CHECK_EQ(*active_map, *updated_map); } } //////////////////////////////////////////////////////////////////////////////// // A set of tests for attribute reconfiguration case. // // This test ensures that representation/field type generalization is correctly // propagated from one branch of transition tree (|map2|) to another (|map|). // // + - p2B - p3 - p4: |map2| // | // {} - p0 - p1 - p2A - p3 - p4: |map| // // where "p2A" and "p2B" differ only in the attributes. // static void TestReconfigureDataFieldAttribute_GeneralizeRepresentation( Representation from_representation, Handle from_type, Representation to_representation, Handle to_type, Representation expected_representation, Handle expected_type) { Isolate* isolate = CcTest::i_isolate(); Expectations expectations(isolate); // Create a map, add required properties to it and initialize expectations. Handle initial_map = Map::Create(isolate, 0); Handle map = initial_map; for (int i = 0; i < kPropCount; i++) { map = expectations.AddDataField(map, NONE, from_representation, from_type); } CHECK(!map->is_deprecated()); CHECK(map->is_stable()); CHECK(expectations.Check(*map)); // Create another branch in transition tree (property at index |kSplitProp| // has different attributes), initialize expectations. const int kSplitProp = kPropCount / 2; Expectations expectations2(isolate); Handle map2 = initial_map; for (int i = 0; i < kSplitProp; i++) { map2 = expectations2.FollowDataTransition(map2, NONE, from_representation, from_type); } map2 = expectations2.AddDataField(map2, READ_ONLY, to_representation, to_type); for (int i = kSplitProp + 1; i < kPropCount; i++) { map2 = expectations2.AddDataField(map2, NONE, to_representation, to_type); } CHECK(!map2->is_deprecated()); CHECK(map2->is_stable()); CHECK(expectations2.Check(*map2)); Zone zone(isolate->allocator()); Handle field_owner(map->FindFieldOwner(kSplitProp), isolate); CompilationInfo info(ArrayVector("testing"), isolate, &zone); CHECK(!info.dependencies()->HasAborted()); info.dependencies()->AssumeFieldType(field_owner); // Reconfigure attributes of property |kSplitProp| of |map2| to NONE, which // should generalize representations in |map1|. Handle new_map = Map::ReconfigureExistingProperty(map2, kSplitProp, kData, NONE); // |map2| should be left unchanged but marked unstable. CHECK(!map2->is_stable()); CHECK(!map2->is_deprecated()); CHECK_NE(*map2, *new_map); CHECK(expectations2.Check(*map2)); // |map| should be deprecated and |new_map| should match new expectations. for (int i = kSplitProp; i < kPropCount; i++) { expectations.SetDataField(i, expected_representation, expected_type); } CHECK(map->is_deprecated()); CHECK(!info.dependencies()->HasAborted()); info.dependencies()->Rollback(); // Properly cleanup compilation info. CHECK_NE(*map, *new_map); CHECK(!new_map->is_deprecated()); CHECK(expectations.Check(*new_map)); // Update deprecated |map|, it should become |new_map|. Handle updated_map = Map::Update(map); CHECK_EQ(*new_map, *updated_map); } // This test ensures that trivial representation/field type generalization // (from HeapObject to HeapObject) is correctly propagated from one branch of // transition tree (|map2|) to another (|map|). // // + - p2B - p3 - p4: |map2| // | // {} - p0 - p1 - p2A - p3 - p4: |map| // // where "p2A" and "p2B" differ only in the attributes. // static void TestReconfigureDataFieldAttribute_GeneralizeRepresentationTrivial( Representation from_representation, Handle from_type, Representation to_representation, Handle to_type, Representation expected_representation, Handle expected_type, bool expected_field_type_dependency = true) { Isolate* isolate = CcTest::i_isolate(); Expectations expectations(isolate); // Create a map, add required properties to it and initialize expectations. Handle initial_map = Map::Create(isolate, 0); Handle map = initial_map; for (int i = 0; i < kPropCount; i++) { map = expectations.AddDataField(map, NONE, from_representation, from_type); } CHECK(!map->is_deprecated()); CHECK(map->is_stable()); CHECK(expectations.Check(*map)); // Create another branch in transition tree (property at index |kSplitProp| // has different attributes), initialize expectations. const int kSplitProp = kPropCount / 2; Expectations expectations2(isolate); Handle map2 = initial_map; for (int i = 0; i < kSplitProp; i++) { map2 = expectations2.FollowDataTransition(map2, NONE, from_representation, from_type); } map2 = expectations2.AddDataField(map2, READ_ONLY, to_representation, to_type); for (int i = kSplitProp + 1; i < kPropCount; i++) { map2 = expectations2.AddDataField(map2, NONE, to_representation, to_type); } CHECK(!map2->is_deprecated()); CHECK(map2->is_stable()); CHECK(expectations2.Check(*map2)); Zone zone(isolate->allocator()); Handle field_owner(map->FindFieldOwner(kSplitProp), isolate); CompilationInfo info(ArrayVector("testing"), isolate, &zone); CHECK(!info.dependencies()->HasAborted()); info.dependencies()->AssumeFieldType(field_owner); // Reconfigure attributes of property |kSplitProp| of |map2| to NONE, which // should generalize representations in |map1|. Handle new_map = Map::ReconfigureExistingProperty(map2, kSplitProp, kData, NONE); // |map2| should be left unchanged but marked unstable. CHECK(!map2->is_stable()); CHECK(!map2->is_deprecated()); CHECK_NE(*map2, *new_map); CHECK(expectations2.Check(*map2)); // In trivial case |map| should be returned as a result of the property // reconfiguration, respective field types should be generalized and // respective code dependencies should be invalidated. |map| should be NOT // deprecated and it should match new expectations. for (int i = kSplitProp; i < kPropCount; i++) { expectations.SetDataField(i, expected_representation, expected_type); } CHECK(!map->is_deprecated()); CHECK_EQ(*map, *new_map); CHECK_EQ(expected_field_type_dependency, info.dependencies()->HasAborted()); info.dependencies()->Rollback(); // Properly cleanup compilation info. CHECK(!new_map->is_deprecated()); CHECK(expectations.Check(*new_map)); Handle updated_map = Map::Update(map); CHECK_EQ(*new_map, *updated_map); } TEST(ReconfigureDataFieldAttribute_GeneralizeRepresentationSmiToDouble) { CcTest::InitializeVM(); v8::HandleScope scope(CcTest::isolate()); Isolate* isolate = CcTest::i_isolate(); Handle any_type = FieldType::Any(isolate); TestReconfigureDataFieldAttribute_GeneralizeRepresentation( Representation::Smi(), any_type, Representation::Double(), any_type, Representation::Double(), any_type); } TEST(ReconfigureDataFieldAttribute_GeneralizeRepresentationSmiToTagged) { CcTest::InitializeVM(); v8::HandleScope scope(CcTest::isolate()); Isolate* isolate = CcTest::i_isolate(); Handle any_type = FieldType::Any(isolate); Handle value_type = FieldType::Class(Map::Create(isolate, 0), isolate); TestReconfigureDataFieldAttribute_GeneralizeRepresentation( Representation::Smi(), any_type, Representation::HeapObject(), value_type, Representation::Tagged(), any_type); } TEST(ReconfigureDataFieldAttribute_GeneralizeRepresentationDoubleToTagged) { CcTest::InitializeVM(); v8::HandleScope scope(CcTest::isolate()); Isolate* isolate = CcTest::i_isolate(); Handle any_type = FieldType::Any(isolate); Handle value_type = FieldType::Class(Map::Create(isolate, 0), isolate); TestReconfigureDataFieldAttribute_GeneralizeRepresentation( Representation::Double(), any_type, Representation::HeapObject(), value_type, Representation::Tagged(), any_type); } TEST(ReconfigureDataFieldAttribute_GeneralizeRepresentationHeapObjToHeapObj) { CcTest::InitializeVM(); v8::HandleScope scope(CcTest::isolate()); Isolate* isolate = CcTest::i_isolate(); Handle any_type = FieldType::Any(isolate); Handle current_type = FieldType::Class(Map::Create(isolate, 0), isolate); Handle new_type = FieldType::Class(Map::Create(isolate, 0), isolate); Handle expected_type = any_type; TestReconfigureDataFieldAttribute_GeneralizeRepresentationTrivial( Representation::HeapObject(), current_type, Representation::HeapObject(), new_type, Representation::HeapObject(), expected_type); current_type = expected_type; new_type = FieldType::Class(Map::Create(isolate, 0), isolate); TestReconfigureDataFieldAttribute_GeneralizeRepresentationTrivial( Representation::HeapObject(), any_type, Representation::HeapObject(), new_type, Representation::HeapObject(), any_type, false); } TEST(ReconfigureDataFieldAttribute_GeneralizeRepresentationHeapObjectToTagged) { CcTest::InitializeVM(); v8::HandleScope scope(CcTest::isolate()); Isolate* isolate = CcTest::i_isolate(); Handle any_type = FieldType::Any(isolate); Handle value_type = FieldType::Class(Map::Create(isolate, 0), isolate); TestReconfigureDataFieldAttribute_GeneralizeRepresentation( Representation::HeapObject(), value_type, Representation::Smi(), any_type, Representation::Tagged(), any_type); } // Checks that given |map| is deprecated and that it updates to given |new_map| // which in turn should match expectations. struct CheckDeprecated { void Check(Handle map, Handle new_map, const Expectations& expectations) { CHECK(map->is_deprecated()); CHECK_NE(*map, *new_map); CHECK(!new_map->is_deprecated()); CHECK(expectations.Check(*new_map)); // Update deprecated |map|, it should become |new_map|. Handle updated_map = Map::Update(map); CHECK_EQ(*new_map, *updated_map); } }; // Checks that given |map| is NOT deprecated, equals to given |new_map| and // matches expectations. struct CheckSameMap { void Check(Handle map, Handle new_map, const Expectations& expectations) { // |map| was not reconfigured, therefore it should stay stable. CHECK(map->is_stable()); CHECK(!map->is_deprecated()); CHECK_EQ(*map, *new_map); CHECK(!new_map->is_deprecated()); CHECK(expectations.Check(*new_map)); // Update deprecated |map|, it should become |new_map|. Handle updated_map = Map::Update(map); CHECK_EQ(*new_map, *updated_map); } }; // Checks that given |map| is NOT deprecated and matches expectations. // |new_map| is unrelated to |map|. struct CheckUnrelated { void Check(Handle map, Handle new_map, const Expectations& expectations) { CHECK(!map->is_deprecated()); CHECK_NE(*map, *new_map); CHECK(expectations.Check(*map)); CHECK(new_map->is_stable()); CHECK(!new_map->is_deprecated()); } }; // Checks that given |map| is NOT deprecated, and |new_map| is a result of // copy-generalize-all-representations. struct CheckCopyGeneralizeAllRepresentations { void Check(Handle map, Handle new_map, Expectations& expectations) { CHECK(!map->is_deprecated()); CHECK_NE(*map, *new_map); CHECK(new_map->GetBackPointer()->IsUndefined(map->GetIsolate())); for (int i = 0; i < kPropCount; i++) { expectations.GeneralizeRepresentation(i); } CHECK(!new_map->is_deprecated()); CHECK(expectations.Check(*new_map)); } }; // This test ensures that representation/field type generalization is correctly // propagated from one branch of transition tree (|map2|) to another (|map1|). // // + - p2B - p3 - p4: |map2| // | // {} - p0 - p1: |map| // | // + - p2A - p3 - p4: |map1| // | // + - the property customized by the TestConfig provided // // where "p2A" and "p2B" differ only in the attributes. // template static void TestReconfigureProperty_CustomPropertyAfterTargetMap( TestConfig& config, Checker& checker) { Isolate* isolate = CcTest::i_isolate(); Handle any_type = FieldType::Any(isolate); const int kCustomPropIndex = kPropCount - 2; Expectations expectations(isolate); const int kSplitProp = 2; CHECK(kSplitProp < kCustomPropIndex); const Representation representation = Representation::Smi(); // Create common part of transition tree. Handle initial_map = Map::Create(isolate, 0); Handle map = initial_map; for (int i = 0; i < kSplitProp; i++) { map = expectations.AddDataField(map, NONE, representation, any_type); } CHECK(!map->is_deprecated()); CHECK(map->is_stable()); CHECK(expectations.Check(*map)); // Create branch to |map1|. Handle map1 = map; Expectations expectations1 = expectations; for (int i = kSplitProp; i < kCustomPropIndex; i++) { map1 = expectations1.AddDataField(map1, NONE, representation, any_type); } map1 = config.AddPropertyAtBranch(1, expectations1, map1); for (int i = kCustomPropIndex + 1; i < kPropCount; i++) { map1 = expectations1.AddDataField(map1, NONE, representation, any_type); } CHECK(!map1->is_deprecated()); CHECK(map1->is_stable()); CHECK(expectations1.Check(*map1)); // Create another branch in transition tree (property at index |kSplitProp| // has different attributes), initialize expectations. Handle map2 = map; Expectations expectations2 = expectations; map2 = expectations2.AddDataField(map2, READ_ONLY, representation, any_type); for (int i = kSplitProp + 1; i < kCustomPropIndex; i++) { map2 = expectations2.AddDataField(map2, NONE, representation, any_type); } map2 = config.AddPropertyAtBranch(2, expectations2, map2); for (int i = kCustomPropIndex + 1; i < kPropCount; i++) { map2 = expectations2.AddDataField(map2, NONE, representation, any_type); } CHECK(!map2->is_deprecated()); CHECK(map2->is_stable()); CHECK(expectations2.Check(*map2)); // Reconfigure attributes of property |kSplitProp| of |map2| to NONE, which // should generalize representations in |map1|. Handle new_map = Map::ReconfigureExistingProperty(map2, kSplitProp, kData, NONE); // |map2| should be left unchanged but marked unstable. CHECK(!map2->is_stable()); CHECK(!map2->is_deprecated()); CHECK_NE(*map2, *new_map); CHECK(expectations2.Check(*map2)); config.UpdateExpectations(kCustomPropIndex, expectations1); checker.Check(map1, new_map, expectations1); } TEST(ReconfigureDataFieldAttribute_SameDataConstantAfterTargetMap) { CcTest::InitializeVM(); v8::HandleScope scope(CcTest::isolate()); struct TestConfig { Handle js_func_; TestConfig() { Isolate* isolate = CcTest::i_isolate(); Factory* factory = isolate->factory(); js_func_ = factory->NewFunction(factory->empty_string()); } Handle AddPropertyAtBranch(int branch_id, Expectations& expectations, Handle map) { CHECK(branch_id == 1 || branch_id == 2); // Add the same data constant property at both transition tree branches. return expectations.AddDataConstant(map, NONE, js_func_); } void UpdateExpectations(int property_index, Expectations& expectations) { // Expectations stay the same. } }; TestConfig config; // Two branches are "compatible" so the |map1| should NOT be deprecated. CheckSameMap checker; TestReconfigureProperty_CustomPropertyAfterTargetMap(config, checker); } TEST(ReconfigureDataFieldAttribute_DataConstantToDataFieldAfterTargetMap) { CcTest::InitializeVM(); v8::HandleScope scope(CcTest::isolate()); struct TestConfig { Handle js_func1_; Handle js_func2_; TestConfig() { Isolate* isolate = CcTest::i_isolate(); Factory* factory = isolate->factory(); js_func1_ = factory->NewFunction(factory->empty_string()); js_func2_ = factory->NewFunction(factory->empty_string()); } Handle AddPropertyAtBranch(int branch_id, Expectations& expectations, Handle map) { CHECK(branch_id == 1 || branch_id == 2); Handle js_func = branch_id == 1 ? js_func1_ : js_func2_; return expectations.AddDataConstant(map, NONE, js_func); } void UpdateExpectations(int property_index, Expectations& expectations) { Isolate* isolate = CcTest::i_isolate(); Handle function_type = FieldType::Class(isolate->sloppy_function_map(), isolate); expectations.SetDataField(property_index, Representation::HeapObject(), function_type); } }; TestConfig config; // Two branches are "incompatible" so the |map1| should be deprecated. CheckDeprecated checker; TestReconfigureProperty_CustomPropertyAfterTargetMap(config, checker); } TEST(ReconfigureDataFieldAttribute_DataConstantToAccConstantAfterTargetMap) { CcTest::InitializeVM(); v8::HandleScope scope(CcTest::isolate()); struct TestConfig { Handle js_func_; Handle pair_; TestConfig() { Isolate* isolate = CcTest::i_isolate(); Factory* factory = isolate->factory(); js_func_ = factory->NewFunction(factory->empty_string()); pair_ = CreateAccessorPair(true, true); } Handle AddPropertyAtBranch(int branch_id, Expectations& expectations, Handle map) { CHECK(branch_id == 1 || branch_id == 2); if (branch_id == 1) { return expectations.AddDataConstant(map, NONE, js_func_); } else { return expectations.AddAccessorConstant(map, NONE, pair_); } } void UpdateExpectations(int property_index, Expectations& expectations) {} }; TestConfig config; // These are completely separate branches in transition tree. CheckUnrelated checker; TestReconfigureProperty_CustomPropertyAfterTargetMap(config, checker); } TEST(ReconfigureDataFieldAttribute_SameAccessorConstantAfterTargetMap) { CcTest::InitializeVM(); v8::HandleScope scope(CcTest::isolate()); struct TestConfig { Handle pair_; TestConfig() { pair_ = CreateAccessorPair(true, true); } Handle AddPropertyAtBranch(int branch_id, Expectations& expectations, Handle map) { CHECK(branch_id == 1 || branch_id == 2); // Add the same accessor constant property at both transition tree // branches. return expectations.AddAccessorConstant(map, NONE, pair_); } void UpdateExpectations(int property_index, Expectations& expectations) { // Two branches are "compatible" so the |map1| should NOT be deprecated. } }; TestConfig config; CheckSameMap checker; TestReconfigureProperty_CustomPropertyAfterTargetMap(config, checker); } TEST(ReconfigureDataFieldAttribute_AccConstantToAccFieldAfterTargetMap) { CcTest::InitializeVM(); v8::HandleScope scope(CcTest::isolate()); struct TestConfig { Handle pair1_; Handle pair2_; TestConfig() { pair1_ = CreateAccessorPair(true, true); pair2_ = CreateAccessorPair(true, true); } Handle AddPropertyAtBranch(int branch_id, Expectations& expectations, Handle map) { CHECK(branch_id == 1 || branch_id == 2); Handle pair = branch_id == 1 ? pair1_ : pair2_; return expectations.AddAccessorConstant(map, NONE, pair); } void UpdateExpectations(int property_index, Expectations& expectations) { if (IS_ACCESSOR_FIELD_SUPPORTED) { expectations.SetAccessorField(property_index); } else { // Currently we have a copy-generalize-all-representations case and // ACCESSOR property becomes ACCESSOR_CONSTANT. expectations.SetAccessorConstant(property_index, pair2_); } } }; TestConfig config; if (IS_ACCESSOR_FIELD_SUPPORTED) { CheckCopyGeneralizeAllRepresentations checker; TestReconfigureProperty_CustomPropertyAfterTargetMap(config, checker); } else { // Currently we have a copy-generalize-all-representations case. CheckCopyGeneralizeAllRepresentations checker; TestReconfigureProperty_CustomPropertyAfterTargetMap(config, checker); } } TEST(ReconfigureDataFieldAttribute_AccConstantToDataFieldAfterTargetMap) { CcTest::InitializeVM(); v8::HandleScope scope(CcTest::isolate()); struct TestConfig { Handle pair_; TestConfig() { pair_ = CreateAccessorPair(true, true); } Handle AddPropertyAtBranch(int branch_id, Expectations& expectations, Handle map) { CHECK(branch_id == 1 || branch_id == 2); if (branch_id == 1) { return expectations.AddAccessorConstant(map, NONE, pair_); } else { Isolate* isolate = CcTest::i_isolate(); Handle any_type = FieldType::Any(isolate); return expectations.AddDataField(map, NONE, Representation::Smi(), any_type); } } void UpdateExpectations(int property_index, Expectations& expectations) {} }; TestConfig config; // These are completely separate branches in transition tree. CheckUnrelated checker; TestReconfigureProperty_CustomPropertyAfterTargetMap(config, checker); } //////////////////////////////////////////////////////////////////////////////// // A set of tests for elements kind reconfiguration case. // // This test ensures that representation/field type generalization is correctly // propagated from one branch of transition tree (|map2) to another (|map|). // // + - p0 - p1 - p2A - p3 - p4: |map| // | // ek // | // {} - p0 - p1 - p2B - p3 - p4: |map2| // // where "p2A" and "p2B" differ only in the representation/field type. // static void TestReconfigureElementsKind_GeneralizeRepresentation( Representation from_representation, Handle from_type, Representation to_representation, Handle to_type, Representation expected_representation, Handle expected_type) { Isolate* isolate = CcTest::i_isolate(); Expectations expectations(isolate, FAST_SMI_ELEMENTS); // Create a map, add required properties to it and initialize expectations. Handle initial_map = Map::Create(isolate, 0); initial_map->set_elements_kind(FAST_SMI_ELEMENTS); Handle map = initial_map; map = expectations.AsElementsKind(map, FAST_ELEMENTS); for (int i = 0; i < kPropCount; i++) { map = expectations.AddDataField(map, NONE, from_representation, from_type); } CHECK(!map->is_deprecated()); CHECK(map->is_stable()); CHECK(expectations.Check(*map)); // Create another branch in transition tree (property at index |kDiffProp| // has different representatio/field type), initialize expectations. const int kDiffProp = kPropCount / 2; Expectations expectations2(isolate, FAST_SMI_ELEMENTS); Handle map2 = initial_map; for (int i = 0; i < kPropCount; i++) { if (i == kDiffProp) { map2 = expectations2.AddDataField(map2, NONE, to_representation, to_type); } else { map2 = expectations2.AddDataField(map2, NONE, from_representation, from_type); } } CHECK(!map2->is_deprecated()); CHECK(map2->is_stable()); CHECK(expectations2.Check(*map2)); Zone zone(isolate->allocator()); Handle field_owner(map->FindFieldOwner(kDiffProp), isolate); CompilationInfo info(ArrayVector("testing"), isolate, &zone); CHECK(!info.dependencies()->HasAborted()); info.dependencies()->AssumeFieldType(field_owner); // Reconfigure elements kinds of |map2|, which should generalize // representations in |map|. Handle new_map = Map::ReconfigureElementsKind(map2, FAST_ELEMENTS); // |map2| should be left unchanged but marked unstable. CHECK(!map2->is_stable()); CHECK(!map2->is_deprecated()); CHECK_NE(*map2, *new_map); CHECK(expectations2.Check(*map2)); // |map| should be deprecated and |new_map| should match new expectations. expectations.SetDataField(kDiffProp, expected_representation, expected_type); CHECK(map->is_deprecated()); CHECK(!info.dependencies()->HasAborted()); info.dependencies()->Rollback(); // Properly cleanup compilation info. CHECK_NE(*map, *new_map); CHECK(!new_map->is_deprecated()); CHECK(expectations.Check(*new_map)); // Update deprecated |map|, it should become |new_map|. Handle updated_map = Map::Update(map); CHECK_EQ(*new_map, *updated_map); // Ensure Map::FindElementsKindTransitionedMap() is able to find the // transitioned map. { MapHandleList map_list; map_list.Add(updated_map); Map* transitioned_map = map2->FindElementsKindTransitionedMap(&map_list); CHECK_EQ(*updated_map, transitioned_map); } } // This test ensures that trivial representation/field type generalization // (from HeapObject to HeapObject) is correctly propagated from one branch of // transition tree (|map2|) to another (|map|). // // + - p0 - p1 - p2A - p3 - p4: |map| // | // ek // | // {} - p0 - p1 - p2B - p3 - p4: |map2| // // where "p2A" and "p2B" differ only in the representation/field type. // static void TestReconfigureElementsKind_GeneralizeRepresentationTrivial( Representation from_representation, Handle from_type, Representation to_representation, Handle to_type, Representation expected_representation, Handle expected_type, bool expected_field_type_dependency = true) { Isolate* isolate = CcTest::i_isolate(); Expectations expectations(isolate, FAST_SMI_ELEMENTS); // Create a map, add required properties to it and initialize expectations. Handle initial_map = Map::Create(isolate, 0); initial_map->set_elements_kind(FAST_SMI_ELEMENTS); Handle map = initial_map; map = expectations.AsElementsKind(map, FAST_ELEMENTS); for (int i = 0; i < kPropCount; i++) { map = expectations.AddDataField(map, NONE, from_representation, from_type); } CHECK(!map->is_deprecated()); CHECK(map->is_stable()); CHECK(expectations.Check(*map)); // Create another branch in transition tree (property at index |kDiffProp| // has different attributes), initialize expectations. const int kDiffProp = kPropCount / 2; Expectations expectations2(isolate, FAST_SMI_ELEMENTS); Handle map2 = initial_map; for (int i = 0; i < kPropCount; i++) { if (i == kDiffProp) { map2 = expectations2.AddDataField(map2, NONE, to_representation, to_type); } else { map2 = expectations2.AddDataField(map2, NONE, from_representation, from_type); } } CHECK(!map2->is_deprecated()); CHECK(map2->is_stable()); CHECK(expectations2.Check(*map2)); Zone zone(isolate->allocator()); Handle field_owner(map->FindFieldOwner(kDiffProp), isolate); CompilationInfo info(ArrayVector("testing"), isolate, &zone); CHECK(!info.dependencies()->HasAborted()); info.dependencies()->AssumeFieldType(field_owner); // Reconfigure elements kinds of |map2|, which should generalize // representations in |map|. Handle new_map = Map::ReconfigureElementsKind(map2, FAST_ELEMENTS); // |map2| should be left unchanged but marked unstable. CHECK(!map2->is_stable()); CHECK(!map2->is_deprecated()); CHECK_NE(*map2, *new_map); CHECK(expectations2.Check(*map2)); // In trivial case |map| should be returned as a result of the elements // kind reconfiguration, respective field types should be generalized and // respective code dependencies should be invalidated. |map| should be NOT // deprecated and it should match new expectations. expectations.SetDataField(kDiffProp, expected_representation, expected_type); CHECK(!map->is_deprecated()); CHECK_EQ(*map, *new_map); CHECK_EQ(expected_field_type_dependency, info.dependencies()->HasAborted()); info.dependencies()->Rollback(); // Properly cleanup compilation info. CHECK(!new_map->is_deprecated()); CHECK(expectations.Check(*new_map)); Handle updated_map = Map::Update(map); CHECK_EQ(*new_map, *updated_map); // Ensure Map::FindElementsKindTransitionedMap() is able to find the // transitioned map. { MapHandleList map_list; map_list.Add(updated_map); Map* transitioned_map = map2->FindElementsKindTransitionedMap(&map_list); CHECK_EQ(*updated_map, transitioned_map); } } TEST(ReconfigureElementsKind_GeneralizeRepresentationSmiToDouble) { CcTest::InitializeVM(); v8::HandleScope scope(CcTest::isolate()); Isolate* isolate = CcTest::i_isolate(); Handle any_type = FieldType::Any(isolate); TestReconfigureElementsKind_GeneralizeRepresentation( Representation::Smi(), any_type, Representation::Double(), any_type, Representation::Double(), any_type); } TEST(ReconfigureElementsKind_GeneralizeRepresentationSmiToTagged) { CcTest::InitializeVM(); v8::HandleScope scope(CcTest::isolate()); Isolate* isolate = CcTest::i_isolate(); Handle any_type = FieldType::Any(isolate); Handle value_type = FieldType::Class(Map::Create(isolate, 0), isolate); TestReconfigureElementsKind_GeneralizeRepresentation( Representation::Smi(), any_type, Representation::HeapObject(), value_type, Representation::Tagged(), any_type); } TEST(ReconfigureElementsKind_GeneralizeRepresentationDoubleToTagged) { CcTest::InitializeVM(); v8::HandleScope scope(CcTest::isolate()); Isolate* isolate = CcTest::i_isolate(); Handle any_type = FieldType::Any(isolate); Handle value_type = FieldType::Class(Map::Create(isolate, 0), isolate); TestReconfigureElementsKind_GeneralizeRepresentation( Representation::Double(), any_type, Representation::HeapObject(), value_type, Representation::Tagged(), any_type); } TEST(ReconfigureElementsKind_GeneralizeRepresentationHeapObjToHeapObj) { CcTest::InitializeVM(); v8::HandleScope scope(CcTest::isolate()); Isolate* isolate = CcTest::i_isolate(); Handle any_type = FieldType::Any(isolate); Handle current_type = FieldType::Class(Map::Create(isolate, 0), isolate); Handle new_type = FieldType::Class(Map::Create(isolate, 0), isolate); Handle expected_type = any_type; TestReconfigureElementsKind_GeneralizeRepresentationTrivial( Representation::HeapObject(), current_type, Representation::HeapObject(), new_type, Representation::HeapObject(), expected_type); current_type = expected_type; new_type = FieldType::Class(Map::Create(isolate, 0), isolate); TestReconfigureElementsKind_GeneralizeRepresentationTrivial( Representation::HeapObject(), any_type, Representation::HeapObject(), new_type, Representation::HeapObject(), any_type, false); } TEST(ReconfigureElementsKind_GeneralizeRepresentationHeapObjectToTagged) { CcTest::InitializeVM(); v8::HandleScope scope(CcTest::isolate()); Isolate* isolate = CcTest::i_isolate(); Handle any_type = FieldType::Any(isolate); Handle value_type = FieldType::Class(Map::Create(isolate, 0), isolate); TestReconfigureElementsKind_GeneralizeRepresentation( Representation::HeapObject(), value_type, Representation::Smi(), any_type, Representation::Tagged(), any_type); } //////////////////////////////////////////////////////////////////////////////// // A set of tests checking split map deprecation. // TEST(ReconfigurePropertySplitMapTransitionsOverflow) { CcTest::InitializeVM(); v8::HandleScope scope(CcTest::isolate()); Isolate* isolate = CcTest::i_isolate(); Handle any_type = FieldType::Any(isolate); Expectations expectations(isolate); // Create a map, add required properties to it and initialize expectations. Handle initial_map = Map::Create(isolate, 0); Handle map = initial_map; for (int i = 0; i < kPropCount; i++) { map = expectations.AddDataField(map, NONE, Representation::Smi(), any_type); } CHECK(!map->is_deprecated()); CHECK(map->is_stable()); // Generalize representation of property at index |kSplitProp|. const int kSplitProp = kPropCount / 2; Handle split_map; Handle map2 = initial_map; { for (int i = 0; i < kSplitProp + 1; i++) { if (i == kSplitProp) { split_map = map2; } Handle name = MakeName("prop", i); Map* target = TransitionArray::SearchTransition(*map2, kData, *name, NONE); CHECK(target != NULL); map2 = handle(target); } map2 = Map::ReconfigureProperty(map2, kSplitProp, kData, NONE, Representation::Double(), any_type, FORCE_FIELD); expectations.SetDataField(kSplitProp, Representation::Double(), any_type); CHECK(expectations.Check(*split_map, kSplitProp)); CHECK(expectations.Check(*map2, kSplitProp + 1)); } // At this point |map| should be deprecated and disconnected from the // transition tree. CHECK(map->is_deprecated()); CHECK(!split_map->is_deprecated()); CHECK(map2->is_stable()); CHECK(!map2->is_deprecated()); // Fill in transition tree of |map2| so that it can't have more transitions. for (int i = 0; i < TransitionArray::kMaxNumberOfTransitions; i++) { CHECK(TransitionArray::CanHaveMoreTransitions(map2)); Handle name = MakeName("foo", i); Map::CopyWithField(map2, name, any_type, NONE, Representation::Smi(), INSERT_TRANSITION) .ToHandleChecked(); } CHECK(!TransitionArray::CanHaveMoreTransitions(map2)); // Try to update |map|, since there is no place for propX transition at |map2| // |map| should become "copy-generalized". Handle updated_map = Map::Update(map); CHECK(updated_map->GetBackPointer()->IsUndefined(isolate)); for (int i = 0; i < kPropCount; i++) { expectations.SetDataField(i, Representation::Tagged(), any_type); } CHECK(expectations.Check(*updated_map)); } //////////////////////////////////////////////////////////////////////////////// // A set of tests involving special transitions (such as elements kind // transition, observed transition or prototype transition). // // This test ensures that representation/field type generalization is correctly // propagated from one branch of transition tree (|map2|) to another (|map|). // // p4B: |map2| // | // * - special transition // | // {} - p0 - p1 - p2A - p3 - p4A: |map| // // where "p4A" and "p4B" are exactly the same properties. // // TODO(ishell): unify this test template with // TestReconfigureDataFieldAttribute_GeneralizeRepresentation once // IS_PROTO_TRANS_ISSUE_FIXED and IS_NON_EQUIVALENT_TRANSITION_SUPPORTED are // fixed. template static void TestGeneralizeRepresentationWithSpecialTransition( TestConfig& config, Representation from_representation, Handle from_type, Representation to_representation, Handle to_type, Representation expected_representation, Handle expected_type) { Isolate* isolate = CcTest::i_isolate(); Expectations expectations(isolate); // Create a map, add required properties to it and initialize expectations. Handle initial_map = Map::Create(isolate, 0); Handle map = initial_map; for (int i = 0; i < kPropCount; i++) { map = expectations.AddDataField(map, NONE, from_representation, from_type); } CHECK(!map->is_deprecated()); CHECK(map->is_stable()); CHECK(expectations.Check(*map)); Expectations expectations2 = expectations; // Apply some special transition to |map|. CHECK(map->owns_descriptors()); Handle map2 = config.Transition(map, expectations2); // |map| should still match expectations. CHECK(!map->is_deprecated()); CHECK(expectations.Check(*map)); if (config.generalizes_representations()) { for (int i = 0; i < kPropCount; i++) { expectations2.GeneralizeRepresentation(i); } } CHECK(!map2->is_deprecated()); CHECK(map2->is_stable()); CHECK(expectations2.Check(*map2)); // Create new maps by generalizing representation of propX field. Handle maps[kPropCount]; for (int i = 0; i < kPropCount; i++) { Handle new_map = Map::ReconfigureProperty( map, i, kData, NONE, to_representation, to_type, FORCE_FIELD); maps[i] = new_map; expectations.SetDataField(i, expected_representation, expected_type); CHECK(map->is_deprecated()); CHECK_NE(*map, *new_map); CHECK(i == 0 || maps[i - 1]->is_deprecated()); CHECK(expectations.Check(*new_map)); Handle new_map2 = Map::Update(map2); CHECK(!new_map2->is_deprecated()); CHECK(!new_map2->is_dictionary_map()); Handle tmp_map; if (Map::TryUpdate(map2).ToHandle(&tmp_map)) { // If Map::TryUpdate() manages to succeed the result must match the result // of Map::Update(). CHECK_EQ(*new_map2, *tmp_map); } if (config.is_non_equevalent_transition()) { // In case of non-equivalent transition currently we generalize all // representations. for (int i = 0; i < kPropCount; i++) { expectations2.GeneralizeRepresentation(i); } CHECK(new_map2->GetBackPointer()->IsUndefined(isolate)); CHECK(expectations2.Check(*new_map2)); } else { CHECK(!new_map2->GetBackPointer()->IsUndefined(isolate)); CHECK(expectations2.Check(*new_map2)); } } Handle active_map = maps[kPropCount - 1]; CHECK(!active_map->is_deprecated()); // Update all deprecated maps and check that they are now the same. Handle updated_map = Map::Update(map); CHECK_EQ(*active_map, *updated_map); for (int i = 0; i < kPropCount; i++) { updated_map = Map::Update(maps[i]); CHECK_EQ(*active_map, *updated_map); } } TEST(ElementsKindTransitionFromMapOwningDescriptor) { CcTest::InitializeVM(); v8::HandleScope scope(CcTest::isolate()); Isolate* isolate = CcTest::i_isolate(); Handle any_type = FieldType::Any(isolate); Handle value_type = FieldType::Class(Map::Create(isolate, 0), isolate); struct TestConfig { Handle Transition(Handle map, Expectations& expectations) { Handle frozen_symbol(map->GetHeap()->frozen_symbol()); expectations.SetElementsKind(DICTIONARY_ELEMENTS); return Map::CopyForPreventExtensions(map, NONE, frozen_symbol, "CopyForPreventExtensions"); } // TODO(ishell): remove once IS_PROTO_TRANS_ISSUE_FIXED is removed. bool generalizes_representations() const { return false; } bool is_non_equevalent_transition() const { return true; } }; TestConfig config; TestGeneralizeRepresentationWithSpecialTransition( config, Representation::Smi(), any_type, Representation::HeapObject(), value_type, Representation::Tagged(), any_type); } TEST(ElementsKindTransitionFromMapNotOwningDescriptor) { CcTest::InitializeVM(); v8::HandleScope scope(CcTest::isolate()); Isolate* isolate = CcTest::i_isolate(); Handle any_type = FieldType::Any(isolate); Handle value_type = FieldType::Class(Map::Create(isolate, 0), isolate); struct TestConfig { Handle Transition(Handle map, Expectations& expectations) { Isolate* isolate = CcTest::i_isolate(); Handle any_type = FieldType::Any(isolate); // Add one more transition to |map| in order to prevent descriptors // ownership. CHECK(map->owns_descriptors()); Map::CopyWithField(map, MakeString("foo"), any_type, NONE, Representation::Smi(), INSERT_TRANSITION) .ToHandleChecked(); CHECK(!map->owns_descriptors()); Handle frozen_symbol(map->GetHeap()->frozen_symbol()); expectations.SetElementsKind(DICTIONARY_ELEMENTS); return Map::CopyForPreventExtensions(map, NONE, frozen_symbol, "CopyForPreventExtensions"); } // TODO(ishell): remove once IS_PROTO_TRANS_ISSUE_FIXED is removed. bool generalizes_representations() const { return false; } bool is_non_equevalent_transition() const { return true; } }; TestConfig config; TestGeneralizeRepresentationWithSpecialTransition( config, Representation::Smi(), any_type, Representation::HeapObject(), value_type, Representation::Tagged(), any_type); } TEST(PrototypeTransitionFromMapOwningDescriptor) { CcTest::InitializeVM(); v8::HandleScope scope(CcTest::isolate()); Isolate* isolate = CcTest::i_isolate(); Handle any_type = FieldType::Any(isolate); Handle value_type = FieldType::Class(Map::Create(isolate, 0), isolate); struct TestConfig { Handle prototype_; TestConfig() { Isolate* isolate = CcTest::i_isolate(); Factory* factory = isolate->factory(); prototype_ = factory->NewJSObjectFromMap(Map::Create(isolate, 0)); } Handle Transition(Handle map, Expectations& expectations) { return Map::TransitionToPrototype(map, prototype_, REGULAR_PROTOTYPE); } // TODO(ishell): remove once IS_PROTO_TRANS_ISSUE_FIXED is removed. bool generalizes_representations() const { return !IS_PROTO_TRANS_ISSUE_FIXED; } bool is_non_equevalent_transition() const { return true; } }; TestConfig config; TestGeneralizeRepresentationWithSpecialTransition( config, Representation::Smi(), any_type, Representation::HeapObject(), value_type, Representation::Tagged(), any_type); } TEST(PrototypeTransitionFromMapNotOwningDescriptor) { CcTest::InitializeVM(); v8::HandleScope scope(CcTest::isolate()); Isolate* isolate = CcTest::i_isolate(); Handle any_type = FieldType::Any(isolate); Handle value_type = FieldType::Class(Map::Create(isolate, 0), isolate); struct TestConfig { Handle prototype_; TestConfig() { Isolate* isolate = CcTest::i_isolate(); Factory* factory = isolate->factory(); prototype_ = factory->NewJSObjectFromMap(Map::Create(isolate, 0)); } Handle Transition(Handle map, Expectations& expectations) { Isolate* isolate = CcTest::i_isolate(); Handle any_type = FieldType::Any(isolate); // Add one more transition to |map| in order to prevent descriptors // ownership. CHECK(map->owns_descriptors()); Map::CopyWithField(map, MakeString("foo"), any_type, NONE, Representation::Smi(), INSERT_TRANSITION) .ToHandleChecked(); CHECK(!map->owns_descriptors()); return Map::TransitionToPrototype(map, prototype_, REGULAR_PROTOTYPE); } // TODO(ishell): remove once IS_PROTO_TRANS_ISSUE_FIXED is removed. bool generalizes_representations() const { return !IS_PROTO_TRANS_ISSUE_FIXED; } bool is_non_equevalent_transition() const { return true; } }; TestConfig config; TestGeneralizeRepresentationWithSpecialTransition( config, Representation::Smi(), any_type, Representation::HeapObject(), value_type, Representation::Tagged(), any_type); } //////////////////////////////////////////////////////////////////////////////// // A set of tests for higher level transitioning mechanics. // struct TransitionToDataFieldOperator { Representation representation_; PropertyAttributes attributes_; Handle heap_type_; Handle value_; TransitionToDataFieldOperator(Representation representation, Handle heap_type, Handle value, PropertyAttributes attributes = NONE) : representation_(representation), attributes_(attributes), heap_type_(heap_type), value_(value) {} Handle DoTransition(Expectations& expectations, Handle map) { return expectations.TransitionToDataField(map, attributes_, representation_, heap_type_, value_); } }; struct TransitionToDataConstantOperator { PropertyAttributes attributes_; Handle value_; TransitionToDataConstantOperator(Handle value, PropertyAttributes attributes = NONE) : attributes_(attributes), value_(value) {} Handle DoTransition(Expectations& expectations, Handle map) { return expectations.TransitionToDataConstant(map, attributes_, value_); } }; struct TransitionToAccessorConstantOperator { PropertyAttributes attributes_; Handle pair_; TransitionToAccessorConstantOperator(Handle pair, PropertyAttributes attributes = NONE) : attributes_(attributes), pair_(pair) {} Handle DoTransition(Expectations& expectations, Handle map) { return expectations.TransitionToAccessorConstant(map, attributes_, pair_); } }; struct ReconfigureAsDataPropertyOperator { int descriptor_; Representation representation_; PropertyAttributes attributes_; Handle heap_type_; ReconfigureAsDataPropertyOperator(int descriptor, Representation representation, Handle heap_type, PropertyAttributes attributes = NONE) : descriptor_(descriptor), representation_(representation), attributes_(attributes), heap_type_(heap_type) {} Handle DoTransition(Expectations& expectations, Handle map) { expectations.SetDataField(descriptor_, representation_, heap_type_); return Map::ReconfigureExistingProperty(map, descriptor_, kData, attributes_); } }; struct ReconfigureAsAccessorPropertyOperator { int descriptor_; PropertyAttributes attributes_; ReconfigureAsAccessorPropertyOperator(int descriptor, PropertyAttributes attributes = NONE) : descriptor_(descriptor), attributes_(attributes) {} Handle DoTransition(Expectations& expectations, Handle map) { expectations.SetAccessorField(descriptor_); return Map::ReconfigureExistingProperty(map, descriptor_, kAccessor, attributes_); } }; // Checks that representation/field type generalization happened. struct FieldGeneralizationChecker { int descriptor_; Representation representation_; PropertyAttributes attributes_; Handle heap_type_; FieldGeneralizationChecker(int descriptor, Representation representation, Handle heap_type, PropertyAttributes attributes = NONE) : descriptor_(descriptor), representation_(representation), attributes_(attributes), heap_type_(heap_type) {} void Check(Expectations& expectations2, Handle map1, Handle map2) { CHECK(!map2->is_deprecated()); CHECK(map1->is_deprecated()); CHECK_NE(*map1, *map2); Handle updated_map = Map::Update(map1); CHECK_EQ(*map2, *updated_map); expectations2.SetDataField(descriptor_, attributes_, representation_, heap_type_); CHECK(expectations2.Check(*map2)); } }; // Checks that existing transition was taken as is. struct SameMapChecker { void Check(Expectations& expectations, Handle map1, Handle map2) { CHECK(!map2->is_deprecated()); CHECK_EQ(*map1, *map2); CHECK(expectations.Check(*map2)); } }; // Checks that both |map1| and |map2| should stays non-deprecated, this is // the case when property kind is change. struct PropertyKindReconfigurationChecker { void Check(Expectations& expectations, Handle map1, Handle map2) { CHECK(!map1->is_deprecated()); CHECK(!map2->is_deprecated()); CHECK_NE(*map1, *map2); CHECK(expectations.Check(*map2)); } }; // This test transitions to various property types under different // circumstances. // Plan: // 1) create a |map| with p0..p3 properties. // 2) create |map1| by adding "p4" to |map0|. // 3) create |map2| by transition to "p4" from |map0|. // // + - p4B: |map2| // | // {} - p0 - p1 - pA - p3: |map| // | // + - p4A: |map1| // // where "p4A" and "p4B" differ only in the attributes. // template static void TestTransitionTo(TransitionOp1& transition_op1, TransitionOp2& transition_op2, Checker& checker) { Isolate* isolate = CcTest::i_isolate(); Handle any_type = FieldType::Any(isolate); Expectations expectations(isolate); // Create a map, add required properties to it and initialize expectations. Handle initial_map = Map::Create(isolate, 0); Handle map = initial_map; for (int i = 0; i < kPropCount - 1; i++) { map = expectations.AddDataField(map, NONE, Representation::Smi(), any_type); } CHECK(expectations.Check(*map)); Expectations expectations1 = expectations; Handle map1 = transition_op1.DoTransition(expectations1, map); CHECK(expectations1.Check(*map1)); Expectations expectations2 = expectations; Handle map2 = transition_op2.DoTransition(expectations2, map); // Let the test customization do the check. checker.Check(expectations2, map1, map2); } TEST(TransitionDataFieldToDataField) { CcTest::InitializeVM(); v8::HandleScope scope(CcTest::isolate()); Isolate* isolate = CcTest::i_isolate(); Handle any_type = FieldType::Any(isolate); Handle value1 = handle(Smi::FromInt(0), isolate); TransitionToDataFieldOperator transition_op1(Representation::Smi(), any_type, value1); Handle value2 = isolate->factory()->NewHeapNumber(0); TransitionToDataFieldOperator transition_op2(Representation::Double(), any_type, value2); FieldGeneralizationChecker checker(kPropCount - 1, Representation::Double(), any_type); TestTransitionTo(transition_op1, transition_op2, checker); } TEST(TransitionDataConstantToSameDataConstant) { CcTest::InitializeVM(); v8::HandleScope scope(CcTest::isolate()); Isolate* isolate = CcTest::i_isolate(); Factory* factory = isolate->factory(); Handle js_func = factory->NewFunction(factory->empty_string()); TransitionToDataConstantOperator transition_op(js_func); SameMapChecker checker; TestTransitionTo(transition_op, transition_op, checker); } TEST(TransitionDataConstantToAnotherDataConstant) { CcTest::InitializeVM(); v8::HandleScope scope(CcTest::isolate()); Isolate* isolate = CcTest::i_isolate(); Factory* factory = isolate->factory(); Handle function_type = FieldType::Class(isolate->sloppy_function_map(), isolate); Handle js_func1 = factory->NewFunction(factory->empty_string()); TransitionToDataConstantOperator transition_op1(js_func1); Handle js_func2 = factory->NewFunction(factory->empty_string()); TransitionToDataConstantOperator transition_op2(js_func2); FieldGeneralizationChecker checker( kPropCount - 1, Representation::HeapObject(), function_type); TestTransitionTo(transition_op1, transition_op2, checker); } TEST(TransitionDataConstantToDataField) { CcTest::InitializeVM(); v8::HandleScope scope(CcTest::isolate()); Isolate* isolate = CcTest::i_isolate(); Factory* factory = isolate->factory(); Handle any_type = FieldType::Any(isolate); Handle js_func1 = factory->NewFunction(factory->empty_string()); TransitionToDataConstantOperator transition_op1(js_func1); Handle value2 = isolate->factory()->NewHeapNumber(0); TransitionToDataFieldOperator transition_op2(Representation::Double(), any_type, value2); FieldGeneralizationChecker checker(kPropCount - 1, Representation::Tagged(), any_type); TestTransitionTo(transition_op1, transition_op2, checker); } TEST(TransitionAccessorConstantToSameAccessorConstant) { CcTest::InitializeVM(); v8::HandleScope scope(CcTest::isolate()); Handle pair = CreateAccessorPair(true, true); TransitionToAccessorConstantOperator transition_op(pair); SameMapChecker checker; TestTransitionTo(transition_op, transition_op, checker); } // TODO(ishell): add this test once IS_ACCESSOR_FIELD_SUPPORTED is supported. // TEST(TransitionAccessorConstantToAnotherAccessorConstant) 10-100 /* * pkmAudioPlayer.cpp * memoryMosaic * * Created by on 5/24/11. * Copyright 2011 __MyCompanyName__. All rights reserved. * */ #include "pkmAudioPlayer.h" lusee-night/refspec #include "RefSpectrometer.h" #include "SignalGenerator.h" #include "SpecConfig.h" #include "SpecOutput.h" #include #include #include int main() { SpecConfig cfg; cfg.Ntaps = 8; cfg.Nchannels = 4; double fundamental = cfg.fundamental_frequency(); // Let's do 1 second worth of data size_t blocks = int(cfg.sampling_rate/cfg.Nfft); float Ampl = 0; float noiseA = 0.0; std::cout << "prefilling signal generator " << std::endl; // ask for more blocks than we actually need SignalGenerator signal(cfg.Nfft, cfg.Nchannels, blocks+2*(cfg.Ntaps+cfg.AverageSize), 10*fundamental, cfg.sampling_rate, Ampl, noiseA); RefSpectrometer S(&signal,&cfg); SpecOutput O(&cfg); std::cout << "running" << std::endl; auto start = std::chrono::high_resolution_clock::now(); while (S.blocks_processed()( elapsed).count(); double rate = (S.blocks_processed()*cfg.Nfft)/(microseconds*1e-6); std::cout << "processing rate " << rate << " samples / s" << std::endl; return 0; } spec_test.cc #include "spec.h" #include "gtest/gtest.h" namespace spec { namespace { TEST(ToStringTest, Smoke) { // Date when FOO reached max price: Stage max_foo = AggregatedTable{ .filters = {Filter{.regexp = {.what = Expr{1}, .regexp = "FOO"}}}, .components = {{Max{.what = {3}, .output = {Expr{2}}}}}}; EXPECT_EQ(ToString(Pipeline{max_foo}), "filter(_1~FOO) max(_3, _2)"); // Number of unique tickers: Pipeline num_tickers = { Stage{AggregatedTable{.components = {{Key{Expr{1}}}}}}, Stage{AggregatedTable{.components = {{Count{}}}}}}; EXPECT_EQ(ToString(num_tickers), "key(_1) => count"); // Alternative for the same num_tickers = { Stage{AggregatedTable{.components = {{CountDistinct{Expr{1}}}}}}}; EXPECT_EQ(ToString(num_tickers), "count(distinct, _1)"); } } // namespace } // namespace spec #pragma once #include "pch.h" #include "RenderContext.h" #include "SpriteBatch.h" namespace ThunderRumble { RenderContext::RenderContext() { } void RenderContext::Begin(DirectX::FXMMATRIX transformMatrix, DirectX::SpriteSortMode sortMode) { } void RenderContext::End() { } void RenderContext::Draw(const TextureHandle &texture, const DirectX::XMFLOAT2 &position, float rotation, float scale, DirectX::FXMVECTOR color, TexturePosition texturePosition) { } void RenderContext::Draw(const TextureHandle &texture, const RECT &destinationRect, DirectX::FXMVECTOR color) { } void RenderContext::DrawString(std::shared_ptr font, const std::wstring &message, const DirectX::XMFLOAT2 &position, DirectX::FXMVECTOR color, float rotation, const DirectX::XMFLOAT2 &origin, float scale) { } const DirectX::XMMATRIX RenderContext::MatrixIdentity = DirectX::XMMatrixIdentity(); const DirectX::XMFLOAT2 RenderContext::Float2Zero = { 0,0 }; }/* Support for MPU6050 IMU Adapted from https://github.com/kriswiner/MPU6050 Copyright (c) 2021 MIT License */ #include namespace hf { class MPU6050 : public Sensor { friend class HackflightFull; public: typedef enum { AFS_2G = 0, AFS_4G, AFS_8G, AFS_16G } ascale_t; typedef enum { GFS_250DPS = 0, GFS_500DPS, GFS_1000DPS, GFS_2000DPS } gscale_t; MPU6050(ascale_t ascale, gscale_t gscale) { _ascale = ascale; _gscale = gscale; _aRes = (1 << ((uint8_t)ascale + 1)) / 32768.0; _gRes = (250 * ((uint8_t)ascale + 1)) / 32768.0; } private: static const uint8_t MPU6050_ADDRESS = 0x68; static const uint8_t SMPLRT_DIV = 0x19; static const uint8_t CONFIG = 0x1A; static const uint8_t GYRO_CONFIG = 0x1B; static const uint8_t ACCEL_CONFIG = 0x1C; static const uint8_t INT_PIN_CFG = 0x37; static const uint8_t INT_ENABLE = 0x38; static const uint8_t DMP_INT_STATUS = 0x39; static const uint8_t INT_STATUS = 0x3A; static const uint8_t ACCEL_XOUT_H = 0x3B; static const uint8_t GYRO_XOUT_H = 0x43; static const uint8_t PWR_MGMT_1 = 0x6B; // gyroscope measurement error in rads/s (start at 60 deg/s), then // reduce after ~10 s to 3 static constexpr float GYRO_ERROR = PI * (40.0f / 180.0f); // gyroscope measurement drift in rad/s/s (start at 0.0 deg/s/s) static constexpr float GYRO_DRIFT = PI * (2.0f / 180.0f); // beta parameter for Madgwick quaternion filter static constexpr float BETA = sqrt(3.0f / 4.0f) * GYRO_ERROR; // zeta parameter for Madgwick quaternion filter static constexpr float ZETA = sqrt(3.0f / 4.0f) * GYRO_DRIFT; ascale_t _ascale; gscale_t _gscale; float _aRes = 0; float _gRes = 0; uint32_t _usec = 0; MadgwickQuaternionFilter6DOF madgwick = MadgwickQuaternionFilter6DOF(BETA, ZETA); void readData(float &x, float &y, float &z, uint8_t rgstr, float res) { uint8_t rawData[6]; readBytes(MPU6050_ADDRESS, rgstr, 6, &rawData[0]); x = (int16_t)((rawData[0] << 8) | rawData[1]) * res; y = (int16_t)((rawData[2] << 8) | rawData[3]) * res; z = (int16_t)((rawData[4] << 8) | rawData[5]) * res; } void writeByte(uint8_t address, uint8_t subAddress, uint8_t data) { Wire.beginTransmission(address); Wire.write(subAddress); Wire.write(data); Wire.endTransmission(); } uint8_t readByte(uint8_t address, uint8_t subAddress) { uint8_t data; readBytes(address, subAddress, 1, &data); return data; } void readBytes(uint8_t address, uint8_t subAddress, uint8_t count, uint8_t * dest) { Wire.beginTransmission(address); Wire.write(subAddress); Wire.endTransmission(false); uint8_t i = 0; Wire.requestFrom(address, count); while (Wire.available()) { dest[i++] = Wire.read(); } } protected: void begin() { // Wake up device writeByte(MPU6050_ADDRESS, PWR_MGMT_1, 0x00); // Delay 100 ms for PLL to get established on x-axis gyro; // should check for PLL ready interrupt delay(100); // Get stable time source: set clock source to be PLL with // x-axis gyroscope reference, bits 2:0 = 001 writeByte(MPU6050_ADDRESS, PWR_MGMT_1, 0x01); // Configure Gyro and Accelerometer Disable FSYNC and set // accelerometer and gyro bandwidth to 44 and 42 Hz, // respectively; DLPF_CFG = bits 2:0 = 010; this sets the // sample rate at 1 kHz for both Maximum delay time is 4.9 ms // corresponding to just over 200 Hz sample rate writeByte(MPU6050_ADDRESS, CONFIG, 0x03); // Set sample rate = gyroscope output rate/(1 + SMPLRT_DIV) // Use a 200 Hz rate; the same rate set in CONFIG above writeByte(MPU6050_ADDRESS, SMPLRT_DIV, 0x04); // Set gyroscope full scale range // Range selects FS_SEL and AFS_SEL are 0 - 3, so 2-bit values // are left-shifted into positions 4:3 uint8_t c = readByte(MPU6050_ADDRESS, GYRO_CONFIG); writeByte(MPU6050_ADDRESS, GYRO_CONFIG, c & ~0xE0); writeByte(MPU6050_ADDRESS, GYRO_CONFIG, c & ~0x18); writeByte(MPU6050_ADDRESS, GYRO_CONFIG, c | _gscale << 3); // Set accelerometer configuration c = readByte(MPU6050_ADDRESS, ACCEL_CONFIG); writeByte(MPU6050_ADDRESS, ACCEL_CONFIG, c & ~0xE0); writeByte(MPU6050_ADDRESS, ACCEL_CONFIG, c & ~0x18); writeByte(MPU6050_ADDRESS, ACCEL_CONFIG, c | _ascale << 3); // Configure Interrupts and Bypass Enable Set interrupt pin // active high, push-pull, and clear on read of INT_STATUS, // enable I2C_BYPASS_EN so additional chips can join the I2C // bus and all can be controlled by the Arduino as master writeByte(MPU6050_ADDRESS, INT_PIN_CFG, 0x22); writeByte(MPU6050_ADDRESS, INT_ENABLE, 0x01); // Initialize clock for Madgwick filter _usec = 0; } virtual void modifyState(State * state, float time) { State * hfstate = (State *)state; (void)time; // Check data ready if (!(readByte(MPU6050_ADDRESS, INT_STATUS) & 0x01)) { return; } // Get accelerometer float ax = 0, ay = 0, az = 0; readData(ax, ay, az, ACCEL_XOUT_H, _aRes); // Get gyrometer float gx = 0, gy = 0, gz = 0; readData(gx, gy, gz, GYRO_XOUT_H, _gRes); // Get current time difference for Madgwick filter uint32_t usec = micros(); float deltat = (usec - _usec) / 1000000.0f; _usec = usec; // Use Madgwick filter to fuse accelerometer and gyrometer into quaternion madgwick.update(ax, ay, az, gx * PI / 180.0f, gy * PI / 180.0f, gz * PI / 180.0f, deltat); // Convert quaternion to Euler angles Filter::quat2euler( madgwick.q1, madgwick.q2, madgwick.q3, madgwick.q4, hfstate->x[State::PHI], hfstate->x[State::THETA], hfstate->x[State::PSI]); // Adjust rotation so that nose-up is positive hfstate->x[State::THETA] = -hfstate->x[State::THETA]; // Convert heading from [-pi,+pi] to [0,2*pi] if (hfstate->x[State::PSI] < 0) { hfstate->x[State::PSI] += 2*M_PI; } } // modifyState }; // class MPU6050 } // namespace hf /* * Copyright (C) 2019 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 "fuse_provider.h" #include #include #include #include #include #include #include #include #include #include "fuse_sideload.h" FuseFileDataProvider::FuseFileDataProvider(const std::string& path, uint32_t block_size) { struct stat sb; if (stat(path.c_str(), &sb) == -1) { fprintf(stderr, "failed to stat %s: %s\n", path.c_str(), strerror(errno)); return; } fd_.reset(open(path.c_str(), O_RDONLY)); if (fd_ == -1) { fprintf(stderr, "failed to open %s: %s\n", path.c_str(), strerror(errno)); return; } file_size_ = sb.st_size; fuse_block_size_ = block_size; } bool FuseFileDataProvider::ReadBlockAlignedData(uint8_t* buffer, uint32_t fetch_size, uint32_t start_block) const { uint64_t offset = static_cast(start_block) * fuse_block_size_; if (fetch_size > file_size_ || offset > file_size_ - fetch_size) { fprintf(stderr, "Out of bound read, start block: %" PRIu32 ", fetch size: %" PRIu32 ", file size %" PRIu64 "\n", start_block, fetch_size, file_size_); return false; } if (!android::base::ReadFullyAtOffset(fd_, buffer, fetch_size, offset)) { fprintf(stderr, "Failed to read fetch size: %" PRIu32 " bytes data at offset %" PRIu64 ": %s\n", fetch_size, offset, strerror(errno)); return false; } return true; } void FuseFileDataProvider::Close() { fd_.reset(); } src/device/vulkan/VulkanContext.hpp #pragma once #include "core/Pool.hpp" #include "device/Context.hpp" #include "device/vulkan/VulkanDevice.hpp" #include "VulkanCommon.hpp" namespace lucent { class VulkanContext : public Context { public: explicit VulkanContext(VulkanDevice& device); ~VulkanContext(); VulkanContext(const Context&) = delete; Context& operator=(const Context&) = delete; void Begin() override; void End() override; void BeginRenderPass(const Framebuffer* framebuffer) override; void EndRenderPass() override; void Clear(Color color, float depth) override; void Viewport(uint32 width, uint32 height) override; void BindPipeline(const Pipeline* pipeline) override; void BindBuffer(const Buffer* buffer) override; void BindBuffer(Descriptor* descriptor, const Buffer* buffer) override; void BindBuffer(Descriptor* descriptor, const Buffer* buffer, uint32 dynamicOffset) override; void BindTexture(Descriptor* descriptor, const Texture* texture, int level = -1) override; void BindImage(Descriptor* descriptor, const Texture* texture, int level = -1) override; void Uniform(Descriptor* descriptor, const uint8* data, size_t size) override; void Uniform(Descriptor* descriptor, uint32 arrayIndex, const uint8* data, size_t size) override; void Draw(uint32 indexCount) override; void Dispatch(uint32 x, uint32 y, uint32 z) override; void CopyTexture( Texture* src, uint32 srcLayer, uint32 srcLevel, Texture* dst, uint32 dstLayer, uint32 dstLevel, uint32 width, uint32 height) override; void CopyTexture( Texture* src, uint32 srcLayer, uint32 srcLevel, Buffer* dst, uint32 offset, uint32 width, uint32 height) override; void CopyTexture( Buffer* src, uint32 offset, Texture* dst, uint32 dstLayer, uint32 dstLevel, uint32 width, uint32 height) override; void BlitTexture( Texture* src, uint32 srcLayer, uint32 srcLevel, Texture* dst, uint32 dstLayer, uint32 dstLevel) override; void GenerateMips(Texture* texture) override; const Pipeline* BoundPipeline() override; Device* GetDevice() override; private: struct Binding { enum Type { kNone, kUniformBuffer, kUniformBufferDynamic, kStorageBuffer, kTexture, kImage }; Type type; union { const void* data; const VulkanBuffer* buffer; const VulkanTexture* texture; }; int level = -1; bool operator==(const Binding& rhs) const; }; using BindingArray = std::array; // Represents an actively bound set of descriptors struct BoundSet { BindingArray bindings; Array dynamicOffsets; bool dirty = false; }; struct BindingHash { size_t operator()(const BindingArray& bindings) const; }; struct ScratchAllocation { uint32 set; uint32 binding; uint32 offset; uint32 size; }; friend class VulkanDevice; private: VkDescriptorSet FindDescriptorSet(const BindingArray& bindings, VkDescriptorSetLayout layout); VkDescriptorPool AllocateDescriptorPool() const; void BindDescriptorSets(); uint32 GetUniformBufferOffset(uint32 arg, uint32 binding); Buffer* AllocateUniformBuffer(); void ResetScratchAllocations(); void ResetUniformBuffers(); void BindBuffer(uint32 set, uint32 binding, const Buffer* buffer, uint32 dynamicOffset); void TransitionLayout(const Texture* generalTexture, VkPipelineStageFlags stage, VkAccessFlags access, VkImageLayout layout, uint32 layer = ~0u, uint32 level = ~0u) const; void RestoreLayout(const Texture* texture, VkPipelineStageFlags stage, VkAccessFlags access, VkImageLayout layout, uint32 layer = ~0u, uint32 level = ~0u) const; public: VulkanDevice& m_Device; VkCommandPool m_CommandPool{}; VkCommandBuffer m_CommandBuffer{}; VkFence m_ReadyFence{}; Pool m_DescriptorPools; std::unordered_map m_DescriptorSets; // Scratch uniform allocations static constexpr auto kMaxScratchAllocations = 8; static constexpr auto kScratchBufferSize = 65536; Pool m_ScratchUniformBuffers; uint32 m_ScratchDrawOffset = 0; Array m_ScratchAllocations{}; // Active state const VulkanPipeline* m_BoundPipeline{}; const VulkanFramebuffer* m_BoundFramebuffer{}; std::array m_BoundSets{}; }; } CoutinhoDeSousa/hypertrieinclude/Dice/hypertrie/boolhypertrie.hpp #ifndef HYPERTRIE_BOOLHYPERTRIE_HPP #define HYPERTRIE_BOOLHYPERTRIE_HPP #include "Dice/hypertrie/internal/BoolHypertrie.hpp" #include "Dice/hypertrie/internal/RawBoolHypertrie.hpp" #include "Dice/hypertrie/internal/Join.hpp" #include "Dice/hypertrie/internal/HashJoin_impl.hpp" #include #include #include #include "Dice/hypertrie/boolhypertrie.hpp" #include "Dice/hypertrie/internal/util/FrontSkipIterator.hpp" #include "Dice/einsum/internal/Einsum.hpp" namespace hypertrie { using Subscript = ::einsum::internal::Subscript; using RawSubscript = ::einsum::internal::RawSubscript; template class map_type = hypertrie::internal::container::tsl_sparse_map, template class set_type = hypertrie::internal::container::boost_flat_set> struct boolhypertrie { using pos_type = hypertrie::internal::pos_type; using BoolHypertrie = typename ::hypertrie::internal::interface::boolhypertrie::BoolHypertrie; using const_BoolHypertrie = typename ::hypertrie::internal::interface::boolhypertrie::const_BoolHypertrie; using OrderedDiagonal = typename ::hypertrie::internal::interface::boolhypertrie::OrderedDiagonal; using HashDiagonal = typename ::hypertrie::internal::interface::boolhypertrie::HashDiagonal; using OrderedJoin = typename ::hypertrie::internal::interface::join::OrderedJoin; using HashJoin = typename ::hypertrie::internal::interface::join::HashJoin; template using Einsum = typename ::einsum::internal::Einsum; template using RawBoolhypertrie = typename ::hypertrie::internal::interface::rawboolhypertrie::template RawBoolHypertrie; template using EinsumEntry = ::einsum::internal::Entry; using KeyHash = ::einsum::internal::KeyHash; using TimePoint = ::einsum::internal::TimePoint; template static auto einsum2map(const std::shared_ptr &subscript, const std::vector &operands, const TimePoint &time_point = TimePoint::max()) { tsl::hopscotch_map, value_type, KeyHash> results{}; for (const auto &operand : operands) if (operand.size() == 0) return results; Einsum einsum{subscript, operands, time_point}; for (auto &&entry : einsum) { results[entry.key] += entry.value; } return results; } }; } #endif //HYPERTRIE_BOOLHYPERTRIE_HPP KevinTheBarbarian/octo0 #ifndef __CONTEXT_HH__ #define __CONTEXT_HH__ #include "common.hh" #include "ParseTree.hh" #include "Rule.hh" #include "Slice.hh" namespace parsing { class GrammarParser; class Context { public: Context(GrammarParser* parser, RuleRef whitespace, general::CharSlice rest, size_t line, size_t offset, bool debug); general::CharSlice getRest() const; size_t getLine() const; size_t getOffset() const; Rule getWhitespaceRule() const; Context consume(size_t bytes) const; const Rule* findRule(const std::string& name) const; // gets a short block of the parse location for error messages or similar. std::string getContextHint() const; bool isDebug() const; private: static void updatePosition_(general::CharSlice bytes, size_t& line, size_t& offset); GrammarParser* parser_; Rule whitespace_; general::CharSlice rest_; size_t line_; size_t offset_; bool debug_; }; } #endif #include #include #include #include #include using namespace std; int next(int n, int k) { stringstream ss; ss << (long long) k * k; string s = ss.str(); if(s.length() > n) s = s.substr(0, n); int ans; // initial stringstream constructor stringstream ss2(s); ss2 >> ans; return ans; } int main() { //freopen("11549.in", "r", stdin); //freopen("11549.out", "w", stdout); int t, n, k; scanf("%d", &t); while(t--) { scanf("%d%d", &n, &k); set S; int ans = k; // 判斷數值 k 在不在 set 裡面(set 為集合,內部元素唯一),在就回傳 1,不在就回傳 0 while(!S.count(k)) { S.insert(k); if(k > ans) ans = k; k = next(n, k); } printf("%d\n", ans); } }// Copyright (c) 2015-2017, The Bytecoin developers // Copyright (c) 2017-2018, The Karbo developers // Copyright (c) 2019, The Qwertycoin developers // // This file is part of Qwertycoin. // // Qwertycoin is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Qwertycoin 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 Qwertycoin. If not, see . #include #include #include #include #include "WalletSplashScreen.h" #include "Settings/Settings.h" #include "Style/Style.h" namespace WalletGui { namespace { const char HIDE_BUTTON_STYLE_SHEET_TEMPLATE[] = "* {" "font-family: %fontFamily%;" "}" "QPushButton {" "border: none;" "font-size: %fontSizeLarge%;" "min-width: 5px;" "min-height: 5px;" "color: #ffffff;" "}" "QPushButton:hover {" "color: #222222;" "}"; } WalletSplashScreen::WalletSplashScreen(QWidget* _parent) : QSplashScreen(_parent, QPixmap(":images/splash"), Qt::WindowStaysOnTopHint | Qt::X11BypassWindowManagerHint) { QFont font; font.setPixelSize(Style::FONT_LARGE); setFont(font); if (Settings::instance().isSystemTrayAvailable() && QSystemTrayIcon::isSystemTrayAvailable()) { QHBoxLayout* layout = new QHBoxLayout(this); QPushButton* hideButton = new QPushButton(this); hideButton->setStyleSheet(Settings::instance().getCurrentStyle().makeStyleSheet(HIDE_BUTTON_STYLE_SHEET_TEMPLATE)); hideButton->setText(tr("Minimize to tray")); hideButton->setCursor(Qt::PointingHandCursor); hideButton->setSizePolicy(QSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum)); hideButton->adjustSize(); setLayout(layout); layout->setContentsMargins(0, 0, 5, 5); layout->addWidget(hideButton, 0, Qt::AlignBottom | Qt::AlignRight); connect(hideButton, &QPushButton::clicked, this, &WalletSplashScreen::hide); } } WalletSplashScreen::~WalletSplashScreen() { } void WalletSplashScreen::mousePressEvent(QMouseEvent* _event) { if (Settings::instance().isSystemTrayAvailable() && QSystemTrayIcon::isSystemTrayAvailable()) { _event->ignore(); } else { #ifdef Q_OS_MAC QSplashScreen::mousePressEvent(_event); #endif } } } /* * Author : * Date : 16/06/2018 * * Editor : Dev c++ 5.11 * Compiler : g++ 5.1.0 * flags : -std=c++11 * Question : find pivot, min, max element in a ascending sorted rotated array link - https://www.geeksforgeeks.org/find-minimum-element-in-a-sorted-and-rotated-array/ NOTE : Array is ASCENDING */ #include using namespace std; /* standard find pivot. Default to findMax First half checked first Returns index of pivot */ int findPivot(vector A, int l, int h){ if(l>h){ return -1; } if(l==h){ return l; } int mid = (l+h)/2; // anomaly check at mid if( mid+1 <= h && A[mid] > A[mid+1]){ return mid; } if( mid-1 >= l && A[mid-1] > A[mid]){ return mid-1; } // first half is checked first => Because we wanna max ( default pivot = max ) // check for bug in first half if(A[l] > A[mid]){ return findPivot(A, l, mid-1); } else{ return findPivot(A, mid+1, h); } } /* findMax ( same as findPivot ) First half checked first Returns max (pivot) element */ int findMax(vector A, int l, int h){ // no pivot - array sorted // last element is max if(l>h){ return A[A.size()-1]; } if(l==h){ return A[l]; } int mid = (l+h)/2; if(mid+1 <= h && A[mid] > A[mid+1]){ return A[mid]; } if(mid-1 >= l && A[mid-1] > A[mid]){ return A[mid-1]; } // first half is checked first => Because we wanna max ( default pivot = max ) // check for bug in first half if(A[l] > A[mid]){ return findMax(A, l, mid-1); } else{ return findMax(A, mid+1, h); } } /* findMin ( looks same as findPivot but slight diff ) second half half checked first Min = next to pivot (max) so 1 is added to almost all indexes, but not in base cases. Look base cases carefully Returns min (next to pivot) element */ int findMin(vector A, int l, int h){ // no pivot - array sorted // first element is min if(l>h){ return A[0]; } if(l==h){ return A[l]; } int mid = (l+h)/2; if(mid+1 <= h && A[mid] > A[mid+1]){ return A[mid+1]; } if(mid-1 >= l && A[mid-1] > A[mid]){ return A[mid]; } // check for bug in second half if(A[mid] > A[h]){ return findMin(A, mid+1, h); } else{ return findMin(A, l, mid-1); } } int main(){ vector A = { 4, 5, 6, 7, 8, 9, 1, 2, 3 // 1, 2, 3, 4, 5, 6 // 3,4,5,6,7,8, 1,2 // 2, 3, 4, 5, 6 // 1, 2, 3 // 5, 4, 3, 2, 1 // not valid because we are assuming ascending world }; cout << "\nPivot index : " << findPivot(A, 0, A.size()-1); cout << "\nMax element : " << findMax(A, 0, A.size()-1); cout << "\nMin element : " << findMin(A, 0, A.size()-1); // can be simply done if i find the pivot and use it properly return 0; } 1-10 #include "post.h" namespace verifEye { Post::Post(string filename):Base(filename) { cout << "Post image: " << filename << endl; } int Post::calculateEyepatch() { if (face_box.size()>0 && eyepatch_box.size()>0) { int patch_mid_x = (eyepatch_box[0].left() + eyepatch_box[0].width() / 2); int l_eye_dist = abs(face_box[0].right() - patch_mid_x); int r_eye_dist = abs(face_box[0].left() - patch_mid_x); if (l_eye_dist < r_eye_dist) return 1; else return 2; } return 3; } /* std::vector Post::get_face_chip_details(unsigned long, double padding) { std::vector result; std::vector from_points, to_points; for (auto a : face_land) { for (int i = 0; i < a.num_parts(); i++) { if (i == chin || i == head_top) continue; dpoint p; p.x() = (padding + mean_face_shape_x[i]) / (2 * padding + 1); p.y() = (padding + mean_face_shape_y[i]) / (2 * padding + 1); from_points.push_back(p*size); to_points.push_back(a.part(i)); result.push_back(chip_details(from_points, to_points, chip_dims(size, size))); } } return result; }*/ }#ifndef SIPLASPLAS_SERIALIZATION_SERIALIZATION_HPP #define SIPLASPLAS_SERIALIZATION_SERIALIZATION_HPP #include #include #include namespace cpp { SIPLASPLAS_SERIALIZATION_EXPORT cpp::json serialize(const cpp::dynamic_reflection::Object& object); SIPLASPLAS_SERIALIZATION_EXPORT cpp::dynamic_reflection::Object deserialize(const cpp::json& json); template cpp::json serialize(const T& object) { return serialize(cpp::dynamic_reflection::Object{object}); } template T deserialize(const cpp::json& json) { return deserialize(json).get(); } template std::ostream& operator<<(std::ostream& os, const std::vector& vector) { return os << cpp::json(vector); } } #endif // SIPLASPLAS_SERIALIZATION_SERIALIZATION_HPP shigengtian/caffe2modules/detectron/batch_permutation_op.cc /** * Copyright (c) 2016-present, Facebook, 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 "batch_permutation_op.h" namespace caffe2 { REGISTER_CPU_OPERATOR(BatchPermutation, BatchPermutationOp); REGISTER_CPU_OPERATOR( BatchPermutationGradient, BatchPermutationGradientOp); OPERATOR_SCHEMA(BatchPermutation) .NumInputs(2) .NumOutputs(1) .SetDoc(R"DOC( Permute the batch elements of the input tensor X according to the permutation specified in the input indices. Warning: this op does not verify that indices is a valid permutation; gradient comptuation is only correct if indices is a permutation. )DOC") .Input( 0, "X", "Tensor of at least 1D shape (N, D0, D1, ...).") .Input( 1, "indices", "1D tensor of type int with shape (N, ) specifying a valid permutation " "of the indices in [0, N - 1] (inclusive).") .Output( 0, "Y", "Tensor with the same shape as X where the (D0, D1, ...) dimensional " "batch elements of X are permuted according to the input indices."); OPERATOR_SCHEMA(BatchPermutationGradient) .NumInputs(2) .NumOutputs(1) .Input( 0, "indices", "See BatchPermutation.") .Input( 1, "dY", "Gradient of forward output 0 (Y).") .Output( 0, "dX", "Gradient of forward input 0 (X)."); class GetBatchPermutationGradient : public GradientMakerBase { using GradientMakerBase::GradientMakerBase; vector GetGradientDefs() override { return SingleGradientDef( "BatchPermutationGradient", "", vector{I(1), GO(0)}, vector{GI(0)}); } }; REGISTER_GRADIENT(BatchPermutation, GetBatchPermutationGradient); } // namespace caffe2 ArekSredzki/bitserytests/serialization_context.cpp //MIT License // //Copyright (c) 2017 // //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 "serialization_test_utils.h" using testing::Eq; template struct ConfigWithContext: bitsery::DefaultConfig { using InternalContext = std::tuple; }; template using SerializerConfigWithContext = bitsery::BasicSerializer< bitsery::AdapterWriter, ConfigWithContext>, Context>; template using DeserializerConfigWithContext = bitsery::BasicDeserializer< bitsery::AdapterReader, ConfigWithContext>, Context>; template using MySerializer = bitsery::BasicSerializer; template using MyDeserializer = bitsery::BasicDeserializer; using SingleTypeContext = int; using MultipleTypesContext = std::tuple; TEST(SerializationContext, WhenUsingContextThenReturnsUnderlyingPointerOrNull) { Buffer buf{}; MySerializer ser1{buf, nullptr}; EXPECT_THAT(ser1.context(), ::testing::IsNull()); MySerializer ser2{buf, nullptr}; EXPECT_THAT(ser2.context(), ::testing::IsNull()); SingleTypeContext sctx{}; MyDeserializer des1{InputAdapter{buf.begin(), 1}, &sctx}; EXPECT_THAT(des1.context(), Eq(&sctx)); MultipleTypesContext mctx{}; MyDeserializer des2{InputAdapter{buf.begin(), 1}, &mctx}; EXPECT_THAT(des2.context(), Eq(&mctx)); } TEST(SerializationContext, WhenContextIsTupleThenContextCastOverloadCastsToIndividualTupleTypes) { Buffer buf{}; MySerializer ser1{buf, nullptr}; EXPECT_THAT(ser1.context(), ::testing::IsNull()); EXPECT_THAT(ser1.context(), ::testing::IsNull()); EXPECT_THAT(ser1.context(), ::testing::IsNull()); } TEST(SerializationContext, WhenContextIsNotTupleThenContextCastOverloadReturnSameType) { Buffer buf{}; SingleTypeContext ctx{}; MySerializer ser1{buf, &ctx}; EXPECT_THAT(ser1.context(), Eq(&ctx)); } TEST(SerializationContext, SerializerDeserializerCanHaveInternalContextViaConfig) { Buffer buf{}; SerializerConfigWithContext ser{buf}; EXPECT_THAT(ser.context(), ::testing::NotNull()); EXPECT_THAT(*ser.context(), Eq(0)); *ser.context() = 10; EXPECT_THAT(*ser.context(), Eq(10)); DeserializerConfigWithContext des{InputAdapter{buf.begin(), 1}}; EXPECT_THAT(des.context(), ::testing::NotNull()); EXPECT_THAT(*des.context(), Eq(0)); *des.context() = 10; EXPECT_THAT(*des.context(), Eq(10)); //new instance has new context SerializerConfigWithContext ser2{buf}; EXPECT_THAT(ser2.context(), ::testing::NotNull()); EXPECT_THAT(*ser2.context(), Eq(0)); } TEST(SerializationContext, WhenInternalAndExternalContextIsTheSamePriorityGoesToInternalContext) { Buffer buf{}; int externalCtx = 5; SerializerConfigWithContext ser{buf, &externalCtx}; EXPECT_THAT(ser.context(), ::testing::NotNull()); EXPECT_THAT(*ser.context(), Eq(0)); *ser.context() = 2; DeserializerConfigWithContext des{InputAdapter{buf.begin(), 1}, &externalCtx}; EXPECT_THAT(des.context(), ::testing::NotNull()); EXPECT_THAT(*des.context(), Eq(0)); *des.context() = 3; EXPECT_THAT(externalCtx, Eq(5)); } TEST(SerializationContext, ContextIfExistsReturnsNullWhenTypeDoesntExists) { Buffer buf{}; std::tuple extCtx1{}; SerializerConfigWithContext, float, int> ser{buf, &extCtx1}; EXPECT_THAT(ser.contextOrNull(), ::testing::NotNull()); EXPECT_THAT(ser.contextOrNull(), ::testing::IsNull()); double extCtx2{}; DeserializerConfigWithContext des{InputAdapter{buf.begin(), 1}, &extCtx2}; EXPECT_THAT(des.contextOrNull(), ::testing::NotNull()); EXPECT_THAT(des.contextOrNull(), ::testing::IsNull()); }10-100 /*=========================================================================== * * File: SrDualRecord.CPP * Author: () * Created On: 5 December 2011 * * Description * *=========================================================================*/ /* Include Files */ #include "srDualrecord.h" /*=========================================================================== * * Begin Subrecord Creation Array * *=========================================================================*/ BEGIN_SRSUBRECCREATE(CSrDualRecord, CSrIdRecord) DEFINE_SRSUBRECCREATE(SR_NAME_DATA, CSrDataSubrecord::Create) END_SRSUBRECCREATE() /*=========================================================================== * End of Subrecord Creation Array *=========================================================================*/ /*=========================================================================== * * Begin CSrRecord Field Map * *=========================================================================*/ BEGIN_SRFIELDMAP(CSrDualRecord, CSrIdRecord) END_SRFIELDMAP() /*=========================================================================== * End of CObRecord Field Map *=========================================================================*/ /*=========================================================================== * * Class CSrDualRecord Constructor * *=========================================================================*/ CSrDualRecord::CSrDualRecord () { } /*=========================================================================== * End of Class CSrDualRecord Constructor *=========================================================================*/ /*=========================================================================== * * Class CSrDualRecord Method - void Destroy (void); * *=========================================================================*/ void CSrDualRecord::Destroy (void) { CSrIdRecord::Destroy(); } /*=========================================================================== * End of Class Method CSrDualRecord::Destroy() *=========================================================================*/ /*=========================================================================== * * Class CSrDualRecord Method - void InitializeNew (void); * *=========================================================================*/ void CSrDualRecord::InitializeNew (void) { CSrIdRecord::InitializeNew(); } /*=========================================================================== * End of Class Method CSrDualRecord::InitializeNew() *=========================================================================*/ /*=========================================================================== * * Class CSrDualRecord Event - void OnAddSubrecord (pSubrecord); * *=========================================================================*/ void CSrDualRecord::OnAddSubrecord (CSrSubrecord* pSubrecord) { if (pSubrecord->GetRecordType() == SR_NAME_DATA) { m_pDataData = SrCastClass(CSrDataSubrecord, pSubrecord); } else { CSrIdRecord::OnAddSubrecord(pSubrecord); } } /*=========================================================================== * End of Class Event CSrDualRecord::OnAddSubRecord() *=========================================================================*/ /*=========================================================================== * * Class CSrDualRecord Event - void OnDeleteSubrecord (pSubrecord); * *=========================================================================*/ void CSrDualRecord::OnDeleteSubrecord (CSrSubrecord* pSubrecord) { if (m_pDataData == pSubrecord) m_pDataData = NULL; else CSrIdRecord::OnDeleteSubrecord(pSubrecord); } /*=========================================================================== * End of Class Event CSrDualRecord::OnDeleteSubrecord() *=========================================================================*/ /*=========================================================================== * * Begin CSrDualRecord Get Field Methods * *=========================================================================*/ /*=========================================================================== * End of CSrDualRecord Get Field Methods *=========================================================================*/ /*=========================================================================== * * Begin CSrDualRecord Compare Field Methods * *=========================================================================*/ /*=========================================================================== * End of CSrDualRecord Compare Field Methods *=========================================================================*/ /*=========================================================================== * * Begin CSrDualRecord Set Field Methods * *=========================================================================*/ /*=========================================================================== * End of CSrDualRecord Set Field Methods *=========================================================================*/ danielfrascarelli/esys-particle0 ///////////////////////////////////////////////////////////// // // // Copyright (c) 2003-2017 by The University of Queensland // // Centre for Geoscience Computing // // http://earth.uq.edu.au/centre-geoscience-computing // // // // Primary Business: Brisbane, Queensland, Australia // // Licensed under the Open Software License version 3.0 // // http://www.apache.org/licenses/LICENSE-2.0 // // // ///////////////////////////////////////////////////////////// //-- STL includes -- #include #include using std::vector; using std::pair; // -- IO includes -- #include using std::cout; using std::endl; /*! constructor \param comm the TML communicator used for sending the data back to the master \param pis a pointer to the interaction storage \param rdf the particle member function to access the data */ template CheckedScalarInteractionFieldSlaveTagged::CheckedScalarInteractionFieldSlaveTagged(TML_Comm* comm,TParallelInteractionStorage* pis,typename T::CheckedScalarFieldFunction rdf,int tag,int mask):CheckedScalarInteractionFieldSlave(comm,pis,rdf) { m_tag=tag; m_mask=mask; } /*! send full field data and position of the interaction */ template void CheckedScalarInteractionFieldSlaveTagged::SendDataFull() { vector > > raw_data; vector > data; // get raw field data from interaction storage raw_data=this->m_pis->forAllTaggedInnerInteractionsGetWithPos(this->m_rdf,m_tag,m_mask); // filter data for(vector > >::iterator iter=raw_data.begin(); iter!=raw_data.end(); iter++){ if(iter->second.first){ data.push_back(make_pair(iter->first,iter->second.second)); } } // send data to master this->m_comm->send_gather(data,0); } /*! send sum only */ template void CheckedScalarInteractionFieldSlaveTagged::SendDataSum() { vector >data_vec; // get data from interactions this->m_pis->forAllTaggedInnerInteractionsGet(data_vec,this->m_rdf,m_tag,m_mask); // sum data double sum=0.0; for(vector >::iterator iter=data_vec.begin(); iter!=data_vec.end(); iter++) { if(iter->first) sum+=iter->second; } vector sum_vec; sum_vec.push_back(sum); this->m_comm->send_gather(sum_vec,0); } /*! send maximum only */ template void CheckedScalarInteractionFieldSlaveTagged::SendDataMax() { vector >data_vec; // get data from interactions this->m_pis->forAllTaggedInnerInteractionsGet(data_vec,this->m_rdf,m_tag,m_mask); // get max double max; bool is_set=false; for(vector >::iterator iter=data_vec.begin(); iter!=data_vec.end(); iter++){ if(iter->first) { if(is_set){ max=(iter->second > max) ? iter->second : max; } else { max=iter->second; is_set=true; } } } vector max_vec; max_vec.push_back(max); this->m_comm->send_gather(max_vec,0); } projects/cudatest/cuda_buffer.cpp #include "cuda_buffer.h" /* Copyright 2010-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 //#include #include #include #include #include #include #include "nkit/dynamic_json.h" #include #include using namespace nkit; namespace nkit { namespace detail { std::string __PROGRAMM_DIR; } } const std::string & PROGRAMM_DIR_ = nkit::detail::__PROGRAMM_DIR; #if defined(NKIT_POSIX_PLATFORM) char path_delimiter_ = '/'; #elif defined(NKIT_WINNT_PLATFORM) char path_delimiter_ = '\\'; #else # error "Unknown platform" #endif //------------------------------------------------------------------------------ bool run_write_statement(sqlite3 * db, const std::string & st, std::string * error = NULL) { char * _error = NULL; int rc = sqlite3_exec(db, st.c_str(), NULL, NULL, &_error); if (rc != SQLITE_OK || _error != NULL) { if (_error != NULL) { if (error) *error = _error; sqlite3_free(_error); } else *error = "ERROR while executing '" + st + ";"; return false; } return true; } //------------------------------------------------------------------------------ class SqliteTransaction; class SqliteTable; class SqliteMemoryDb { friend class SqliteTransaction; friend class SqliteTable; public: typedef detail::ref_count_ptr Ptr; static Ptr Create(std::string * error) { sqlite3 * db; int rc = sqlite3_open(":memory:", &db); if (rc) return Ptr(); if (!run_write_statement(db, "PRAGMA synchronous = OFF", error)) return Ptr(); if (!run_write_statement(db, "PRAGMA journal_mode = MEMORY", error)) return Ptr(); return Ptr(new SqliteMemoryDb(db)); } ~SqliteMemoryDb() { sqlite3_close(db_); db_ = NULL; } detail::ref_count_ptr CreateTransaction(std::string * error); detail::ref_count_ptr CreateTable(const std::string & name, const std::string & columns_def, std::string * error); detail::ref_count_ptr CreateTable(const std::string & name, const Dynamic & src, std::string * error); private: SqliteMemoryDb(sqlite3 * db) : db_(db) {} private: sqlite3 * db_; }; //------------------------------------------------------------------------------ struct TypeMapping { std::string sqlite_column_type_; std::string dynamic_type_; }; static const TypeMapping sqlite3_type_to_dynamic_type[] = { {"text", "STRING"} , {"primary", "UNSIGNED_INTEGER"} , {"unsigned", "UNSIGNED_INTEGER"} , {"int", "INTEGER"} , {"real", "FLOAT"} , {"double", "FLOAT"} , {"float", "FLOAT"} , {"boolean", "BOOL"} , {"datetime", "DATE_TIME"} , {"", ""} }; static const TypeMapping dynamic_type_to_sqlite3_type[] = { {"TEXT", "STRING"} , {"UNSIGNED", "UNSIGNED_INTEGER"} , {"INT", "INTEGER"} , {"DOUBLE", "FLOAT"} , {"BOOLEAN", "BOOL"} , {"DATETIME", "DATE_TIME"} , {"", ""} }; const std::string & get_sqlite3_type_by_dynamic_type(const std::string & type) { size_t i = 0; while (!dynamic_type_to_sqlite3_type[i].dynamic_type_.empty()) { if (dynamic_type_to_sqlite3_type[i].dynamic_type_ == type) return dynamic_type_to_sqlite3_type[i].sqlite_column_type_; i++; } return dynamic_type_to_sqlite3_type[0].sqlite_column_type_; } class SqliteTable { friend class SqliteMemoryDb; public: typedef detail::ref_count_ptr Ptr; public: ~SqliteTable() {} Dynamic Group(const std::string & aggr_def, const std::string & _group_def, std::string * error) { data_of_current_select_ = Dynamic(); data_types_of_current_select_.clear(); std::string group_def; std::string order_def; if (_group_def.find('-') != _group_def.npos) { StringVector group_def_list, order_def_list; simple_split(_group_def, ",", &group_def_list); size_t size = group_def_list.size(); for (size_t i=0; idb_, sql.c_str(), callback, this, &_error); if( rc != SQLITE_OK ) { if (error) *error = _error; sqlite3_free(_error); return Dynamic(); } return data_of_current_select_; } operator Dynamic() { data_of_current_select_ = Dynamic(); data_types_of_current_select_.clear(); char *_error; std::string select_from("SELECT * FROM "); int rc = sqlite3_exec(db_->db_, (select_from + name_).c_str(), callback, this, &_error); if( rc != SQLITE_OK ) { sqlite3_free(_error); return Dynamic(); } return data_of_current_select_; } bool InsertRow(const StringVector & values, std::string * error) { if (insert_row_values_.capacity() < insert_row_values_.size()) insert_row_values_.reserve(insert_row_values_.size()); insert_row_values_.clear(); join(values, ", ", "\"", "\"", &insert_row_values_); const std::string stmt = insert_row_begin_ + insert_row_values_ + ");"; //CINFO(stmt); return run_write_statement(db_->db_, stmt.c_str(), error); } bool CreateIndex(const std::string & name, const std::string & index_columns, std::string * error) { if (name.empty()) { if (error) *error = "Empty index name"; return false; } if (index_columns.empty()) { if (error) *error = "Empty columns definition for index '" + name + "'"; return false; } StringVector columns; nkit::simple_split(index_columns, ",", &columns); std::string sql; join(columns, ", ", "", "", &sql); std::string stmt = "CREATE INDEX " + name + " ON " + name_ + " (" + sql + ");"; return run_write_statement(db_->db_, stmt.c_str(), error); } private: static Ptr Create(SqliteMemoryDb * db, const std::string & name, const Dynamic & src, std::string * error); static Ptr Create(SqliteMemoryDb * db, const std::string & name, const std::string & columns_def, std::string * error) { if (name.empty()) { if (error) *error = "Empty table name"; return Ptr(); } if (columns_def.empty()) { if (error) *error = "Empty columns definition"; return Ptr(); } StringVector _columns; StringVector column_names, column_types, column_defs; nkit::simple_split(columns_def, ",", &_columns); StringVector::const_iterator it = _columns.begin(), end = _columns.end(); for (; it != end; ++it) { std::string column_name, column_type; nkit::simple_split(*it, ":", &column_name, &column_type); if (column_type.empty()) column_type = "TEXT"; column_names.push_back(column_name); column_types.push_back(column_type); } std::string sql_defs; join_pairs(column_names, column_types, " ", ", ", "", "", &sql_defs); if (!run_write_statement(db->db_, "CREATE TABLE IF NOT EXISTS " + name + " (" + sql_defs + ");", error)) return Ptr(); return Ptr(new SqliteTable(db, name, column_names, column_types)); } SqliteTable(SqliteMemoryDb * db, const std::string & name, const StringVector & column_names, const StringVector & column_types) : db_(db) , name_(name) , column_names_(column_names) , column_types_(column_types) { std::string column_names_sql; join(column_names_, ", ", "", "", &column_names_sql); insert_row_begin_ = "INSERT INTO " + name_ + "(" + column_names_sql + ") VALUES ("; } std::string GetColumnTypeByName(const std::string & name, uint64_t * dynamic_type) const { static std::string COUNT_("COUNT(*)"); static std::string MAX_("MAX("); static std::string MIN_("MIN("); static std::string SUM_("SUM("); for (size_t i=0; i < column_names_.size(); ++i) { if (stristr(name, COUNT_) == 0) { *dynamic_type = detail::UNSIGNED_INTEGER; return detail::dynamic_type_to_string(*dynamic_type); } std::string column_name; size_t begin = stristr(name, MAX_); if (begin != std::string::npos) { begin += MAX_.size(); size_t end = name.find(')', begin); column_name = name.substr(begin, end - begin); } if (column_name.empty()) { size_t begin = stristr(name, MIN_); if (begin != std::string::npos) { begin += MIN_.size(); size_t end = name.find(')', begin); column_name = name.substr(begin, end - begin); } } if (column_name.empty()) { size_t begin = stristr(name, SUM_); if (begin != std::string::npos) { begin += SUM_.size(); size_t end = name.find(')', begin); column_name = name.substr(begin, end - begin); } } if (column_name.empty()) column_name = name; if (column_names_[i] == column_name) { const std::string & sqlite_type = column_types_[i]; size_t tmi = 0; while (!sqlite3_type_to_dynamic_type[tmi].sqlite_column_type_.empty()) { if (stristr(sqlite_type, sqlite3_type_to_dynamic_type[tmi].sqlite_column_type_) != std::string::npos) { *dynamic_type = detail::string_to_dynamic_type( sqlite3_type_to_dynamic_type[tmi].dynamic_type_); return sqlite3_type_to_dynamic_type[tmi].dynamic_type_; } ++tmi; } } } *dynamic_type = detail::STRING; return detail::dynamic_type_to_string(*dynamic_type); } static int callback(void * _self, int argc, char **argv, char **column_names) { std::string error; SqliteTable * self = static_cast(_self); if (unlikely(self->data_of_current_select_.IsUndef())) { StringVector table_def_list; detail::DynamicTypeVector data_types_of_current_select; for (int i = 0; i < argc; ++i) { std::string name = column_names[i]; uint64_t dynamic_type; std::string type = self->GetColumnTypeByName(name, &dynamic_type); data_types_of_current_select.push_back(dynamic_type); table_def_list.push_back(name + ":" + type); } std::string table_def; join(table_def_list, ",", "", "", &table_def); //std::cout << table_def << '\n'; self->data_of_current_select_ = Dynamic::Table(table_def, &error); if (self->data_of_current_select_.IsUndef()) return 1; self->data_types_of_current_select_ = data_types_of_current_select; } DynamicVector row; for(int i=0; idata_types_of_current_select_[i]) { case detail::INTEGER: cell = Dynamic(static_cast(NKIT_STRTOLL(value, NULL, 10))); break; case detail::UNSIGNED_INTEGER: cell = Dynamic::UInt64( static_cast(NKIT_STRTOULL(value, NULL, 10))); break; case detail::FLOAT: cell = Dynamic(std::strtod(value, NULL)); break; case detail::BOOL: cell = Dynamic(NKIT_STRTOLL(value, NULL, 10) != 0); break; case detail::DATE_TIME: cell = Dynamic::DateTimeFromTimestamp(NKIT_STRTOULL(value, NULL, 10)); break; default: cell = Dynamic(value); break; } } row.push_back(cell); } return self->data_of_current_select_.AppendRow(row) ? 0 : 1; } private: SqliteMemoryDb * db_; std::string name_; StringVector column_names_; StringVector column_types_; std::string insert_row_begin_; std::string insert_row_values_; Dynamic data_of_current_select_; detail::DynamicTypeVector data_types_of_current_select_; }; //------------------------------------------------------------------------------ class SqliteTransaction { friend class SqliteMemoryDb; public: typedef detail::ref_count_ptr Ptr; public: ~SqliteTransaction() { Commit(); } bool Commit(std::string * error = NULL) { if (commited_) return true; commited_ = true; return run_write_statement(db_->db_, "END TRANSACTION", error); } private: static Ptr Create(SqliteMemoryDb * db, std::string * error) { if (!run_write_statement(db->db_, "BEGIN TRANSACTION", error)) return Ptr(); return Ptr(new SqliteTransaction(db)); } SqliteTransaction(SqliteMemoryDb * db) : db_(db) , commited_(false) {} private: SqliteMemoryDb * db_; bool commited_; }; //------------------------------------------------------------------------------ detail::ref_count_ptr SqliteMemoryDb::CreateTransaction( std::string * error) { return SqliteTransaction::Create(this, error); } detail::ref_count_ptr SqliteMemoryDb::CreateTable( const std::string & name, const std::string & columns_def, std::string * error) { return SqliteTable::Create(this, name, columns_def, error); } detail::ref_count_ptr SqliteMemoryDb::CreateTable( const std::string & name, const Dynamic & src, std::string * error) { return SqliteTable::Create(this, name, src, error); } detail::ref_count_ptr SqliteTable::Create(SqliteMemoryDb * db, const std::string & name, const Dynamic & src, std::string * error) { StringVector column_names = src.GetColumnNames(); StringVector column_types = src.GetColumnTypes(); StringVector::iterator it = column_types.begin(), end = column_types.end(); for (; it != end; ++it) it->assign(get_sqlite3_type_by_dynamic_type(*it)); column_names.insert(column_names.begin(), "k"); column_types.insert(column_types.begin(), "INTEGER PRIMARY KEY"); std::string sql_defs; join_pairs(column_names, column_types, " ", ", ", "", "", &sql_defs); if (!run_write_statement(db->db_, "CREATE TABLE IF NOT EXISTS " + name + " (" + sql_defs + ");", error)) return Ptr(); Ptr dst(new SqliteTable(db, name, column_names, column_types)); SqliteTransaction::Ptr tr = db->CreateTransaction(error); if (!tr) return Ptr(); size_t width = src.width(); size_t k(0); Dynamic::TableIterator row = src.begin_t(), tend = src.end_t(); for (; row != tend; ++row) { StringVector srow; srow.push_back(string_cast(k++)); for (size_t c = 0; c < width; ++c) srow.push_back(row[c].GetString()); if (!dst->InsertRow(srow, error)) return Ptr(); } if (!tr->Commit(error)) return Ptr(); return dst; } //------------------------------------------------------------------------------ const size_t ITER_SIZE = 2000000; const size_t FACTOR = ITER_SIZE / 40; static int rnumbers[ITER_SIZE]; //------------------------------------------------------------------------------ void Init() { #ifdef NKIT_WINNT srand ((unsigned int)time(NULL)); #else srand (time(NULL)); #endif for (size_t i = 0; i < ITER_SIZE; i++) rnumbers[i] = rand() % FACTOR + 1; } //------------------------------------------------------------------------------ #define METRIC(expr_, duration) \ do \ {\ TimeMeter tm; \ tm.Start(); \ { expr_; } \ tm.Stop(); \ *duration = tm.GetTotal(); \ } while(0) //-------------------------------------------------------------------------- void GetMinusPlusPermutations(size_t count, StringList * minus_plus_permutatins) { minus_plus_permutatins->push_back(std::string(count, ' ')); for (size_t i = 1; i < count; ++i) { std::string signes(i, '-'); signes.append(count - i, ' '); std::sort(signes.begin(), signes.end()); do { minus_plus_permutatins->push_back(signes); } while (std::next_permutation(signes.begin(), signes.end())); } minus_plus_permutatins->push_back(std::string(count, '-')); } void GetIndexCombinations(const StringVector & fields, StringVector * combinations) { uint64_t count = 0; UniqueCombinationGenerator ucgen(fields); while (true) { StringSet combination; if (!ucgen.GetNext(&combination)) break; Dynamic tmp = Dynamic::List(combination); StringVector permutation; tmp.SaveTo(&permutation); std::sort(permutation.begin(), permutation.end()); do { StringList minus_plus_permutatins; GetMinusPlusPermutations(combination.size(), &minus_plus_permutatins); StringList::const_iterator it = minus_plus_permutatins.begin(), end = minus_plus_permutatins.end(); for (; it != end; ++it) { count++; std::string joined; join_pairs(*it, permutation, "", ",", "", "", &joined); combinations->push_back(joined); } } while (std::next_permutation(permutation.begin(), permutation.end())); } } /* void PrepareData(std::vector * rows) { std::string error; std::string filename = PROGRAMM_DIR_ + "../../data/CrimeStatebyState.csv"; //+ "../../data/CrimeStatebyStateSmall.csv"; std::ifstream file(filename.c_str()); NKIT_TEST_ASSERT(file.good()); size_t c = 1; CSVIterator _row(file); CSVIterator end; if (_row != end) ++_row; for (; _row != end; ++_row) { StringVector & row = *_row; row.insert(row.begin(), string_cast(c++)); std::string s = row[4] + "-12-31 00:00:00"; Dynamic dt = Dynamic::DateTimeFromDefault(s, &error); NKIT_TEST_ASSERT_WITH_TEXT(dt, error); row.push_back(string_cast(dt.timestamp())); rows->push_back(row); } std::random_shuffle(rows->begin(), rows->end()); } */ const size_t REPEAT_COUNT = 10000; const size_t ARRAY_SIZE = 5; const size_t TOTAL = REPEAT_COUNT * ARRAY_SIZE; template void populate(const T src[ARRAY_SIZE], DynamicVector * vv) { for (size_t i1 = 0; i1 < ARRAY_SIZE; ++i1) { for (size_t i2 = 0; i2 < REPEAT_COUNT; ++i2) vv->push_back(Dynamic(src[i1])); } } void populate(const uint64_t src[ARRAY_SIZE], DynamicVector * vv) { for (size_t i1 = 0; i1 < ARRAY_SIZE; ++i1) { for (size_t i2 = 0; i2 < REPEAT_COUNT; ++i2) vv->push_back(Dynamic::UInt64(src[i1])); } } void shift(size_t offset, DynamicVector * vv) { assert(offset < vv->size()); DynamicVector tmp(vv->size(), Dynamic()); std::copy(vv->begin() + (vv->size() - offset), vv->end(), tmp.begin()); std::copy(vv->begin(), vv->begin() + (vv->size() - offset), tmp.begin() + offset); *vv = tmp; } Dynamic PrepareData() { std::string error; const char * browser[ARRAY_SIZE] = { "chrome", "opera", "firefox", "safari", "ie"}; DynamicVector browsers; populate(browser, &browsers); size_t offset = 0; shift(++offset, &browsers); const char * os[ARRAY_SIZE] = { "Windows", "MacOS", "Ubuntu", "Debian", "iOS"}; DynamicVector oses; populate(os, &oses); shift(++offset, &oses); const int64_t year[ARRAY_SIZE] = { 2014, 2013, 2012, 2011, 2010}; DynamicVector years; populate(year, &years); shift(++offset, &years); const double rate[ARRAY_SIZE] = { 0.1, 0.2, 0.3, 0.4, 0.5}; DynamicVector rates; populate(rate, &rates); shift(++offset, &rates); const int64_t likes[ARRAY_SIZE] = { MAX_INT64_VALUE - 1, MAX_INT64_VALUE - 2, MAX_INT64_VALUE - 3, MAX_INT64_VALUE - 4, MAX_INT64_VALUE - 5}; DynamicVector likess; populate(likes, &likess); shift(++offset, &likess); const bool flag[ARRAY_SIZE] = { true, false, true, false, true}; DynamicVector flags; populate(flag, &flags); shift(++offset, &flags); std::vector rows; for (size_t i = 0; i < TOTAL; ++i) { DynamicVector row; row.push_back(browsers[i]); row.push_back(oses[i]); row.push_back(years[i]); row.push_back(rates[i]); row.push_back(likess[i]); row.push_back(flags[i]); rows.push_back(row); } std::random_shuffle(rows.begin(), rows.end()); Dynamic table = Dynamic::Table("browser:STRING, os:STRING, year:INTEGER," "rate:FLOAT, likes:INTEGER, flag:BOOL", &error); for (size_t i = 0; i < TOTAL; ++i) table.AppendRow(rows[i]); return table; } void TestGroup(Dynamic dynamic_table, SqliteTable::Ptr sqlite_table, const std::string & index_def) { CINFO(index_def); TimeMeter tm; std::string error; std::string aggr_def("COUNT, MIN(flag), MAX(likes), SUM(year)"); //----------------------------------------------- // grouping dynamic table by builder GroupedTableBuilder::Ptr builder = Dynamic::CreateGroupedTableBuilder( "browser:STRING, os:STRING, year:INTEGER," "rate:FLOAT, likes:INTEGER, flag:BOOL", index_def, aggr_def, &error); NKIT_TEST_ASSERT_WITH_TEXT(builder, error); size_t count = dynamic_table.height(); size_t width = dynamic_table.width(); DynamicVector row(width); tm.Start(); for (size_t i = 0; i < count; ++i) { for (size_t c = 0; c < width; ++c) row[c] = dynamic_table.GetCellValue(i, c); NKIT_TEST_ASSERT(builder->InsertRow(row)); } Dynamic grouped_by_builder = builder->GetResult(); tm.Stop(); NKIT_TEST_ASSERT(grouped_by_builder.IsTable()); double grouped_by_builder_time = tm.GetTotal(); tm.Clear(); //----------------------------------------------- // grouping dynamic table by method Group() tm.Start(); //CALLGRIND_START_INSTRUMENTATION; Dynamic grouped_table = dynamic_table.Group(index_def, aggr_def, &error); //CALLGRIND_STOP_INSTRUMENTATION; tm.Stop(); NKIT_TEST_ASSERT_WITH_TEXT(grouped_table.IsTable(), error); double dynamic_group_time = tm.GetTotal(); tm.Clear(); if (grouped_by_builder != grouped_table) { CINFO("-----------------------------------------------------"); CINFO(grouped_table); CINFO("-----------------------------------------------------"); CINFO(grouped_by_builder); NKIT_TEST_ASSERT(false); } //----------------------------------------------- // grouping sqlite3 table tm.Start(); Dynamic sqlite_grouped_table = sqlite_table->Group( "COUNT(*), MIN(flag), MAX(likes), SUM(year)", index_def, &error); tm.Stop(); NKIT_TEST_ASSERT_WITH_TEXT(sqlite_grouped_table.IsTable(), error); if (sqlite_grouped_table != grouped_table) { CINFO("-----------------------------------------------------"); CINFO(grouped_table); CINFO("-----------------------------------------------------"); CINFO(sqlite_grouped_table); NKIT_TEST_ASSERT(false); } double sqlite3_group_time = tm.GetTotal(); tm.Clear(); if (dynamic_table.height() > grouped_table.height()) { std::cout << "builder/method: " << grouped_by_builder_time / dynamic_group_time << '\n'; std::cout << "Sqlite/Dynamic: " << sqlite3_group_time / dynamic_group_time << '\n'; std::cout << "Factor: " << std::setprecision(2) << dynamic_table.height() / grouped_table.height() << '\n'; //NKIT_TEST_ASSERT(sqlite3_group_time / dynamic_group_time > 1.0); } } _NKIT_TEST_CASE(TestGroupBuilder) { std::string error; Dynamic dynamic_table = PrepareData(); std::string index_def("browser,os"); std::string aggr_def("COUNT, MIN(flag), MAX(likes), SUM(year)"); GroupedTableBuilder::Ptr builder = Dynamic::CreateGroupedTableBuilder( "browser:STRING, os:STRING, year:INTEGER," "rate:FLOAT, likes:INTEGER, flag:BOOL", index_def, aggr_def, &error); size_t count = dynamic_table.height(); size_t width = dynamic_table.width(); DynamicVector row(width); for (size_t i = 0; i < count; ++i) { for (size_t c = 0; c < width; ++c) row[c] = dynamic_table.GetCellValue(i, c); NKIT_TEST_ASSERT(builder->InsertRow(row)); } Dynamic grouped_by_builder = builder->GetResult(); Dynamic grouped_by_method = dynamic_table.Group(index_def, aggr_def, &error); NKIT_TEST_ASSERT_WITH_TEXT(grouped_by_method.IsTable(), error); NKIT_TEST_ASSERT(grouped_by_builder = grouped_by_method); } _NKIT_TEST_CASE(TestCompare) { std::string error; detail::IndexKey k1, k2; //0, 1, 1960, 1960, //0, 1, 2005, 2005, //more k1.key_[0].i64_ = 0; k1.key_[1].i64_ = 1; k1.key_[2].ui64_ = 1960; k1.key_[3].i64_ = 1960; k1.size_ = 4; k2.key_[0].i64_ = 0; k2.key_[1].i64_ = 1; k2.key_[2].ui64_ = 2005; k2.key_[3].i64_ = 2005; k2.size_ = 4; StringVector mask; mask.push_back("1"); mask.push_back("1"); mask.push_back("-2"); mask.push_back("1"); nkit::detail::IndexCompare compare; NKIT_TEST_ASSERT_WITH_TEXT( nkit::detail::GetComparator(mask, &compare, &error), error); compare(k1, k2); return; } /* _NKIT_TEST_CASE(TestIndex) { std::string error; typedef std::map IndexMap; StringVector mask; mask.push_back("1"); mask.push_back("1"); mask.push_back("-2"); mask.push_back("1"); nkit::detail::IndexCompare compare; NKIT_TEST_ASSERT_WITH_TEXT( nkit::detail::GetComparator(mask, &compare, &error), error); IndexMap index_map(compare); Dynamic dt1960(1960,1,1,0,0,0); Dynamic dt1962(1962,1,1,0,0,0); Dynamic dt2005(2005,1,1,0,0,0); Dynamic dt1971(1971,1,1,0,0,0); dt1960 = Dynamic::UInt64(1960); dt1962 = Dynamic::UInt64(1962); dt2005 = Dynamic::UInt64(2005); dt1971 = Dynamic::UInt64(1); Dynamic t = DTBL("state:INTEGER," "type:INTEGER," "dt:UNSIGNED_INTEGER," "year:INTEGER," "year2:INTEGER", 0 << 1 << dt1960 << 1960 << 1960 << 0 << 2 << dt2005 << 2005 << 2005 << 0 << 1 << dt2005 << 2005 << 2005 << 0 << 1 << dt2005 << 1 << 1 << 0 << 1 << dt1962 << 1962 << 1962); CINFO(t); Dynamic::TableIterator tbl_it = t.begin_t(), tbl_end = t.end_t(); for (; tbl_it != tbl_end; ++tbl_it) { detail::IndexKey key(4); Dynamic tmp(tbl_it[0]); CINFO(tmp); key.key_[0] = KeyFromData(tmp.data_, tmp.type_); tmp = tbl_it[1]; CINFO(tmp); key.key_[1] = KeyFromData(tmp.data_, tmp.type_); tmp = tbl_it[2]; CINFO(tmp); key.key_[2] = KeyFromData(tmp.data_, tmp.type_); tmp = tbl_it[3]; CINFO(tmp); key.key_[3] = KeyFromData(tmp.data_, tmp.type_); index_map[key] = SizeVector(); CINFO("---"); } CINFO(index_map.size()); IndexMap::const_iterator it = index_map.begin(), end = index_map.end(); for (; it != end; ++it) { std::cout << it->first.key_[0].i64_ << ", " << it->first.key_[1].i64_ << ", " << it->first.key_[2].ui64_ << ", " << it->first.key_[3].i64_ << ", " << '\n'; } } */ _NKIT_TEST_CASE(TestEmptyTableGroup) { std::string error; Dynamic table = Dynamic::Table("c1:STRING, c2:INTEGER, c3:DATE_TIME", &error); Dynamic grouped_table = table.Group("c1", "COUNT, SUM(c2)", &error); NKIT_TEST_ASSERT_WITH_TEXT(grouped_table.IsTable(), error); NKIT_TEST_ASSERT(grouped_table.empty()); } NKIT_TEST_CASE(TestGroup) { std::string error; Dynamic dynamic_table = PrepareData(); //----------------------------------------------- // getting sqlite3 table from dynamic table SqliteMemoryDb::Ptr db = SqliteMemoryDb::Create(&error); NKIT_TEST_ASSERT_WITH_TEXT(db, error); SqliteTable::Ptr sqlite_table = db->CreateTable("t", dynamic_table, &error); NKIT_TEST_ASSERT_WITH_TEXT(sqlite_table, error); //TestGroup(dynamic_table, sqlite_table, "browser, -year"); //return; StringVector fields; //fields.push_back("browser"); fields.push_back("year"); fields.push_back("os"); fields.push_back("likes"); fields.push_back("flag"); fields.push_back("rate"); StringVector index_combinations; GetIndexCombinations(fields, &index_combinations); size_t total = index_combinations.size(); StringVector::const_iterator it = index_combinations.begin(), comb_end = index_combinations.end(); for (size_t i=0; it != comb_end; ++it, ++i) { TestGroup(dynamic_table, sqlite_table, *it); std::cout << i << "/" << total << '\n'; } } _NKIT_TEST_CASE(TestSelectFromSqlite3) { Init(); std::string error; CINFO("Creating sqlite3 table"); TimeMeter tm; SqliteMemoryDb::Ptr db = SqliteMemoryDb::Create(&error); NKIT_TEST_ASSERT_WITH_TEXT(db, error); SqliteTable::Ptr sqlite_table = db->CreateTable("t", "k:INTEGER PRIMARY KEY," "name1:DATETIME, name2:TEXT, name3:INTEGER, name4:TEXT," " name5:INTEGER", &error); NKIT_TEST_ASSERT_WITH_TEXT(sqlite_table, error); SqliteTransaction::Ptr tr = db->CreateTransaction(&error); NKIT_TEST_ASSERT_WITH_TEXT(tr, error); StringVector row; row.reserve(6); for (size_t it_factor = 0; it_factor < ITER_SIZE; ++it_factor) { const size_t uniq = rnumbers[it_factor]; row.clear(); row.push_back(string_cast(it_factor)); row.push_back(string_cast(1386000000 + uniq)); row.push_back("name_" + string_cast(uniq)); row.push_back(string_cast(uniq + FACTOR)); row.push_back(std::string("name_" + string_cast(uniq + FACTOR))); row.push_back(string_cast(uniq + FACTOR + 1)); NKIT_TEST_ASSERT_WITH_TEXT(sqlite_table->InsertRow(row, &error), error); } NKIT_TEST_ASSERT_WITH_TEXT(tr->Commit(&error), error); tm.Start(); Dynamic table = *sqlite_table; tm.Stop(); double sqlite3_select_time = tm.GetTotal(); tm.Clear(); std::cout << "sqlite3_select_time: " << sqlite3_select_time << '\n'; tm.Start(); table = table.Clone(); size_t col_count = table.width(); size_t tmp_count = 0; Dynamic::TableIterator it = table.begin_t(), end = table.end_t(); for (; it != end; ++it) { for (size_t c = 0; c < col_count; ++c) { Dynamic tmp = it[c]; tmp_count += tmp.size(); } } tm.Stop(); double dynamic_select_time = tm.GetTotal(); tm.Clear(); std::cout << "dynamic_select_time: " << dynamic_select_time << '\n'; CINFO(tmp_count); tm.Start(); Dynamic grouped_table = table.Group("name1,name2", "COUNT,MIN(name3),MAX(name5),SUM(name5)", &error); tm.Stop(); NKIT_TEST_ASSERT_WITH_TEXT(grouped_table.IsTable(), error); double dynamic_group_time = tm.GetTotal(); tm.Clear(); std::cout << "dynamic_group_time: " << dynamic_group_time << '\n'; //CINFO(table); //CINFO(grouped_table); tm.Start(); Dynamic sqlite_grouped_table = sqlite_table->Group( "COUNT(*), MIN(name3), MAX(name5), SUM(name5)", "name1, name2", &error); tm.Stop(); NKIT_TEST_ASSERT_WITH_TEXT(sqlite_grouped_table.IsTable(), error); //CINFO(sqlite_grouped_table); NKIT_TEST_ASSERT(sqlite_grouped_table == grouped_table); double sqlite3_group_time = tm.GetTotal(); tm.Clear(); std::cout << "sqlite3_group_time: " << sqlite3_group_time << '\n'; std::cout << "Dynamic group(3/4) is faster then " "sqlite3 group(4) by " << sqlite3_group_time / dynamic_group_time << " times" << '\n'; } //------------------------------------------------------------------------------ _NKIT_TEST_CASE(PerfCreateIndex) { Init(); std::string error; TimeMeter tm; // Creating dynamic table std::string table_def( "name1:INTEGER,name2:STRING,name3:INTEGER,name4:STRING,name5:DATE_TIME"); Dynamic table = Dynamic::Table(table_def, &error); tm.Start(); for (size_t it_factor = 0; it_factor < ITER_SIZE; ++it_factor) { const uint64_t uniq = rnumbers[it_factor]; NKIT_TEST_ASSERT( table.AppendRow(Dynamic(uniq), Dynamic(std::string("name_" + string_cast(uniq))), Dynamic(uniq + FACTOR), Dynamic(std::string("name_" + string_cast(uniq + FACTOR))), Dynamic::DateTimeFromTimestamp(1386000000 + uniq + FACTOR + 1))); } tm.Stop(); double dynamic_create_table_time = tm.GetTotal(); tm.Clear(); // Creating sqlite3 table SqliteMemoryDb::Ptr db = SqliteMemoryDb::Create(&error); NKIT_TEST_ASSERT_WITH_TEXT(db, error); SqliteTable::Ptr sqlite_table = db->CreateTable("t", "k:INTEGER PRIMARY KEY," "name1:INTEGER, name2:TEXT, name3:INTEGER, name4:TEXT," "name5:DATETIME", &error); NKIT_TEST_ASSERT_WITH_TEXT(sqlite_table, error); SqliteTransaction::Ptr tr = db->CreateTransaction(&error); NKIT_TEST_ASSERT_WITH_TEXT(tr, error); tm.Start(); StringVector row; row.reserve(6); for (size_t it_factor = 0; it_factor < ITER_SIZE; ++it_factor) { const size_t uniq = rnumbers[it_factor]; row.clear(); row.push_back(string_cast(it_factor)); row.push_back(string_cast(uniq)); row.push_back("name_" + string_cast(uniq)); row.push_back(string_cast(uniq + FACTOR)); row.push_back(std::string("name_" + string_cast(uniq + FACTOR))); row.push_back(string_cast(uniq + FACTOR + 1)); NKIT_TEST_ASSERT_WITH_TEXT(sqlite_table->InsertRow(row, &error), error); } NKIT_TEST_ASSERT_WITH_TEXT(tr->Commit(&error), error); tm.Stop(); double sqlite3_create_table_time = tm.GetTotal(); tm.Clear(); NKIT_TEST_ASSERT(sqlite3_create_table_time / dynamic_create_table_time > 1.0); std::cout << "Dynamic create table if faster then sqlite3 create table by: " << sqlite3_create_table_time / dynamic_create_table_time << '\n'; nkit::TableIndex::Ptr index; double dynamic_create_index_time; METRIC(index = table.CreateIndex("name1", &error), &dynamic_create_index_time); NKIT_TEST_ASSERT_WITH_TEXT(index, error); double sqlite3_create_index_time; METRIC( NKIT_TEST_ASSERT_WITH_TEXT( sqlite_table->CreateIndex( "idx1", "name5", &error), error), &sqlite3_create_index_time); NKIT_TEST_ASSERT(sqlite3_create_index_time / dynamic_create_index_time > 1.0); std::cout << "Dynamic create index(1) if faster then " "sqlite3 create index(1) by: " << sqlite3_create_index_time / dynamic_create_index_time << '\n'; METRIC(index = table.CreateIndex("name1,name2", &error), &dynamic_create_index_time); NKIT_TEST_ASSERT_WITH_TEXT(index, error); METRIC( NKIT_TEST_ASSERT_WITH_TEXT( sqlite_table->CreateIndex( "idx2", "name1, name2", &error), error), &sqlite3_create_index_time); NKIT_TEST_ASSERT(sqlite3_create_index_time / dynamic_create_index_time > 1.0); std::cout << "Dynamic create index(2) if faster then " "sqlite3 create index(2) by: " << sqlite3_create_index_time / dynamic_create_index_time << '\n'; METRIC(index = table.CreateIndex("name1,name2,name3", &error), &dynamic_create_index_time); NKIT_TEST_ASSERT_WITH_TEXT(index, error); METRIC( NKIT_TEST_ASSERT_WITH_TEXT( sqlite_table->CreateIndex( "idx3", "name1, name2, name3", &error), error), &sqlite3_create_index_time); NKIT_TEST_ASSERT(sqlite3_create_index_time / dynamic_create_index_time > 1.0); std::cout << "Dynamic create index(3) if faster then " "sqlite3 create index(3) by: " << sqlite3_create_index_time / dynamic_create_index_time << '\n'; } int main(int argc, char ** argv) { if (argc >= 1) { detail::__PROGRAMM_DIR = argv[0]; size_t pos = detail::__PROGRAMM_DIR.rfind(path_delimiter_); if (pos != detail::__PROGRAMM_DIR.npos) detail::__PROGRAMM_DIR.erase(pos + 1); } return nkit::test::run_all_tests(); } 100-1000 /* * Roadmap.cpp * RVO2 Library * * Copyright 2008 University of North Carolina at Chapel Hill * * 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. * * Please send all bug reports to <>. * * The authors may be contacted via: * * , , , , * Dept. of Computer Science * 201 S. Columbia St. * , Jr. Computer Science Bldg. * Chapel Hill, N.C. 27599-3175 * United States of America * * */ /* * Example file showing a demo with 100 agents split in four groups initially * positioned in four corners of the environment. Each agent attempts to move to * other side of the environment through a narrow passage generated by four * obstacles. There is a roadmap to guide the agents around the obstacles. */ #ifndef RVO_OUTPUT_TIME_AND_POSITIONS #define RVO_OUTPUT_TIME_AND_POSITIONS 1 #endif #ifndef RVO_SEED_RANDOM_NUMBER_GENERATOR #define RVO_SEED_RANDOM_NUMBER_GENERATOR 1 #endif #include #include #include #include #if RVO_OUTPUT_TIME_AND_POSITIONS #include #endif #if RVO_SEED_RANDOM_NUMBER_GENERATOR #include #endif #if _OPENMP #include #endif #include #ifndef M_PI const float M_PI = 3.14159265358979323846f; #endif class RoadmapVertex { public: RVO::Vector2 position; std::vector neighbors; std::vector distToGoal; }; /* Store the roadmap. */ std::vector roadmap; /* Store the goals of the agents. */ std::vector goals; void setupScenario(RVO::RVOSimulator *sim) { #if RVO_SEED_RANDOM_NUMBER_GENERATOR std::srand(static_cast(std::time(NULL))); #endif /* Specify the global time step of the simulation. */ sim->setTimeStep(0.25f); /* * Add (polygonal) obstacles, specifying their vertices in counterclockwise * order. */ std::vector obstacle1, obstacle2, obstacle3, obstacle4; obstacle1.push_back(RVO::Vector2(-10.0f, 40.0f)); obstacle1.push_back(RVO::Vector2(-40.0f, 40.0f)); obstacle1.push_back(RVO::Vector2(-40.0f, 10.0f)); obstacle1.push_back(RVO::Vector2(-10.0f, 10.0f)); obstacle2.push_back(RVO::Vector2(10.0f, 40.0f)); obstacle2.push_back(RVO::Vector2(10.0f, 10.0f)); obstacle2.push_back(RVO::Vector2(40.0f, 10.0f)); obstacle2.push_back(RVO::Vector2(40.0f, 40.0f)); obstacle3.push_back(RVO::Vector2(10.0f, -40.0f)); obstacle3.push_back(RVO::Vector2(40.0f, -40.0f)); obstacle3.push_back(RVO::Vector2(40.0f, -10.0f)); obstacle3.push_back(RVO::Vector2(10.0f, -10.0f)); obstacle4.push_back(RVO::Vector2(-10.0f, -40.0f)); obstacle4.push_back(RVO::Vector2(-10.0f, -10.0f)); obstacle4.push_back(RVO::Vector2(-40.0f, -10.0f)); obstacle4.push_back(RVO::Vector2(-40.0f, -40.0f)); sim->addObstacle(obstacle1); sim->addObstacle(obstacle2); sim->addObstacle(obstacle3); sim->addObstacle(obstacle4); /* Process the obstacles so that they are accounted for in the simulation. */ sim->processObstacles(); /* Add roadmap vertices. */ RoadmapVertex v; /* Add the goal positions of agents. */ v.position = RVO::Vector2(-75.0f, -75.0f); roadmap.push_back(v); v.position = RVO::Vector2(75.0f, -75.0f); roadmap.push_back(v); v.position = RVO::Vector2(-75.0f, 75.0f); roadmap.push_back(v); v.position = RVO::Vector2(75.0f, 75.0f); roadmap.push_back(v); /* Add roadmap vertices around the obstacles. */ v.position = RVO::Vector2(-42.0f, -42.0f); roadmap.push_back(v); v.position = RVO::Vector2(-42.0f, -8.0f); roadmap.push_back(v); v.position = RVO::Vector2(-42.0f, 8.0f); roadmap.push_back(v); v.position = RVO::Vector2(-42.0f, 42.0f); roadmap.push_back(v); v.position = RVO::Vector2(-8.0f, -42.0f); roadmap.push_back(v); v.position = RVO::Vector2(-8.0f, -8.0f); roadmap.push_back(v); v.position = RVO::Vector2(-8.0f, 8.0f); roadmap.push_back(v); v.position = RVO::Vector2(-8.0f, 42.0f); roadmap.push_back(v); v.position = RVO::Vector2(8.0f, -42.0f); roadmap.push_back(v); v.position = RVO::Vector2(8.0f, -8.0f); roadmap.push_back(v); v.position = RVO::Vector2(8.0f, 8.0f); roadmap.push_back(v); v.position = RVO::Vector2(8.0f, 42.0f); roadmap.push_back(v); v.position = RVO::Vector2(42.0f, -42.0f); roadmap.push_back(v); v.position = RVO::Vector2(42.0f, -8.0f); roadmap.push_back(v); v.position = RVO::Vector2(42.0f, 8.0f); roadmap.push_back(v); v.position = RVO::Vector2(42.0f, 42.0f); roadmap.push_back(v); /* Specify the default parameters for agents that are subsequently added. */ sim->setAgentDefaults(15.0f, 10, 5.0f, 5.0f, 2.0f, 2.0f); /* * Add agents, specifying their start position, and store goals on the * opposite side of the environment (roadmap vertices). */ for (size_t i = 0; i < 5; ++i) { for (size_t j = 0; j < 5; ++j) { sim->addAgent(RVO::Vector2(55.0f + i * 10.0f, 55.0f + j * 10.0f)); goals.push_back(0); sim->addAgent(RVO::Vector2(-55.0f - i * 10.0f, 55.0f + j * 10.0f)); goals.push_back(1); sim->addAgent(RVO::Vector2(55.0f + i * 10.0f, -55.0f - j * 10.0f)); goals.push_back(2); sim->addAgent(RVO::Vector2(-55.0f - i * 10.0f, -55.0f - j * 10.0f)); goals.push_back(3); } } } #if RVO_OUTPUT_TIME_AND_POSITIONS void updateVisualization(RVO::RVOSimulator *sim) { /* Output the current global time. */ std::cout << sim->getGlobalTime(); /* Output the current position of all the agents. */ for (size_t i = 0; i < sim->getNumAgents(); ++i) { std::cout << " " << sim->getAgentPosition(i); } std::cout << std::endl; } #endif void buildRoadmap(RVO::RVOSimulator *sim) { /* Connect the roadmap vertices by edges if mutually visible. */ #ifdef _OPENMP #pragma omp parallel for #endif for (int i = 0; i < static_cast(roadmap.size()); ++i) { for (int j = 0; j < static_cast(roadmap.size()); ++j) { if (sim->queryVisibility(roadmap[i].position, roadmap[j].position, sim->getAgentRadius(0))) { roadmap[i].neighbors.push_back(j); } } /* * Initialize the distance to each of the four goal vertices at infinity * (9e9f). */ roadmap[i].distToGoal.resize(4, 9e9f); } /* * Compute the distance to each of the four goals (the first four vertices) * for all vertices using Dijkstra's algorithm. */ #ifdef _OPENMP #pragma omp parallel for #endif for (int i = 0; i < 4; ++i) { std::multimap Q; std::vector::iterator> posInQ(roadmap.size(), Q.end()); roadmap[i].distToGoal[i] = 0.0f; posInQ[i] = Q.insert(std::make_pair(0.0f, i)); while (!Q.empty()) { const int u = Q.begin()->second; Q.erase(Q.begin()); posInQ[u] = Q.end(); for (int j = 0; j < static_cast(roadmap[u].neighbors.size()); ++j) { const int v = roadmap[u].neighbors[j]; const float dist_uv = RVO::abs(roadmap[v].position - roadmap[u].position); if (roadmap[v].distToGoal[i] > roadmap[u].distToGoal[i] + dist_uv) { roadmap[v].distToGoal[i] = roadmap[u].distToGoal[i] + dist_uv; if (posInQ[v] == Q.end()) { posInQ[v] = Q.insert(std::make_pair(roadmap[v].distToGoal[i], v)); } else { Q.erase(posInQ[v]); posInQ[v] = Q.insert(std::make_pair(roadmap[v].distToGoal[i], v)); } } } } } } void setPreferredVelocities(RVO::RVOSimulator *sim) { /* * Set the preferred velocity to be a vector of unit magnitude (speed) in the * direction of the visible roadmap vertex that is on the shortest path to the * goal. */ #ifdef _OPENMP #pragma omp parallel for #endif for (int i = 0; i < static_cast(sim->getNumAgents()); ++i) { float minDist = 9e9f; int minVertex = -1; for (int j = 0; j < static_cast(roadmap.size()); ++j) { if (RVO::abs(roadmap[j].position - sim->getAgentPosition(i)) + roadmap[j].distToGoal[goals[i]] < minDist && sim->queryVisibility(sim->getAgentPosition(i), roadmap[j].position, sim->getAgentRadius(i))) { minDist = RVO::abs(roadmap[j].position - sim->getAgentPosition(i)) + roadmap[j].distToGoal[goals[i]]; minVertex = j; } } if (minVertex == -1) { /* No roadmap vertex is visible; should not happen. */ sim->setAgentPrefVelocity(i, RVO::Vector2(0, 0)); } else { if (RVO::absSq(roadmap[minVertex].position - sim->getAgentPosition(i)) == 0.0f) { if (minVertex == goals[i]) { sim->setAgentPrefVelocity(i, RVO::Vector2()); } else { sim->setAgentPrefVelocity(i, RVO::normalize(roadmap[goals[i]].position - sim->getAgentPosition(i))); } } else { sim->setAgentPrefVelocity(i, RVO::normalize(roadmap[minVertex].position - sim->getAgentPosition(i))); } } /* * Perturb a little to avoid deadlocks due to perfect symmetry. */ float angle = std::rand() * 2.0f * M_PI / RAND_MAX; float dist = std::rand() * 0.0001f / RAND_MAX; sim->setAgentPrefVelocity(i, sim->getAgentPrefVelocity(i) + dist * RVO::Vector2(std::cos(angle), std::sin(angle))); } } bool reachedGoal(RVO::RVOSimulator *sim) { /* Check if all agents have reached their goals. */ for (size_t i = 0; i < sim->getNumAgents(); ++i) { if (RVO::absSq(sim->getAgentPosition(i) - roadmap[goals[i]].position) > 20.0f * 20.0f) { return false; } } return true; } int main() { /* Create a new simulator instance. */ RVO::RVOSimulator *sim = new RVO::RVOSimulator(); /* Set up the scenario. */ setupScenario(sim); /* Build the roadmap. */ buildRoadmap(sim); /* Perform (and manipulate) the simulation. */ do { #if RVO_OUTPUT_TIME_AND_POSITIONS updateVisualization(sim); #endif setPreferredVelocities(sim); sim->doStep(); } while (!reachedGoal(sim)); delete sim; return 0; } masrtis/shiny-computing-machine #include "stdio.h" #include "framebuffer.h" #include "string.h" #include #include namespace { template constexpr int printf_process_format_char_get_number_of_digits(UnsignedNumeric argument, int base) { int total_digits = 1; while (argument != 0) { argument /= base; ++total_digits; } return total_digits; } template constexpr int printf_process_format_char_get_number_of_digits(const T* argument) { // print pointers as hex (0x prefix) static_assert(sizeof(uintptr_t) >= sizeof(argument)); constexpr int total_hex_chars = 2; return total_hex_chars + printf_process_format_char_get_number_of_digits(reinterpret_cast(argument), 16); } constexpr int printf_process_format_char_get_number_of_digits(int argument, int base) { int total_written = 0; if (argument < 0) { ++total_written; argument = -argument; } return total_written + printf_process_format_char_get_number_of_digits(argument, base); } int printf_process_format_char(const char* format, va_list arguments) { switch (*format) { case '%': { framebuffer::write('%', framebuffer::vga_color::Light_Gray, framebuffer::vga_color::Black); return 1; } case 'c': { const unsigned char char_argument = (unsigned char)va_arg(arguments, int); framebuffer::write(char_argument, framebuffer::vga_color::Light_Gray, framebuffer::vga_color::Black); return 1; } case 's': { const char* string_argument = va_arg(arguments, const char*); framebuffer::write(string_argument, framebuffer::vga_color::Light_Gray, framebuffer::vga_color::Black); return strlen(string_argument); } case 'd': { int int_argument = va_arg(arguments, int); framebuffer::write(int_argument, framebuffer::vga_color::Light_Gray, framebuffer::vga_color::Black); return printf_process_format_char_get_number_of_digits(int_argument, 10); } case 'u': { const unsigned int unsigned_argument = va_arg(arguments, int); framebuffer::write(static_cast(unsigned_argument), framebuffer::vga_color::Light_Gray, framebuffer::vga_color::Black); return printf_process_format_char_get_number_of_digits(unsigned_argument, 10); } case 'p': { const void* pointer_argument = va_arg(arguments, void*); framebuffer::write(pointer_argument, framebuffer::vga_color::Light_Gray, framebuffer::vga_color::Black); return printf_process_format_char_get_number_of_digits(pointer_argument); } } // [HALT] undefined, skip for now return 0; } } int printf(const char* format, ...) { va_list arguments; va_start(arguments, format); int total_printed = 0; while (*format != '\0') { if (*format == '%') { ++format; total_printed += printf_process_format_char(format, arguments); } else { framebuffer::write(*format, framebuffer::vga_color::Light_Gray, framebuffer::vga_color::Black); ++total_printed; } ++format; } va_end(arguments); return total_printed; } tests/flur/Mt.cpp0 #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace OP::utest; using namespace OP::flur; using namespace std::string_literals; using namespace std::chrono_literals; struct SlowSrc : OP::flur::Sequence { int _current; int _limit; int _start; constexpr SlowSrc(int limit, int start = 0) noexcept : _limit(limit) , _start(start) , _current(start) { } /** Start iteration from the beginning. If iteration was already in progress it resets. */ virtual void start() { std::this_thread::sleep_for(200ms); _current = _start; } /** Check if Sequence is in valid position and may call `next` safely */ virtual bool in_range() const { return _current < _limit; } /** Return current item */ virtual element_t current() const { return _current; } /** Position iterable to the next step */ virtual void next() { std::this_thread::sleep_for(200ms); ++_current; } }; namespace beam { template constexpr auto transient(T t) noexcept { //return TransientFactory(std::move(t)); return SimpleFactory(std::move(t)); } } /** Find "Greatest Common Divisor" by Euclidian algorithm as very slow algorithm */ int gcd(int a, int b) { while (b != 0) { auto t = b; b = a % b; a = t; } return a; } void test_Mt(OP::utest::TestResult& tresult) { //(src::of_iota(20, 114) >> then::mapping([](auto i) { // return std::async(std::launch::async, [=]() { // std::this_thread::sleep_for(200ms); // return i; // }); // })).for_each([](auto& i) { // std::cout << "inp>" << i.get() << "\n"; // }); OP::utils::ThreadPool tp; QueueSrc tee; constexpr int i_start = 20, i_end = 114; auto teepipeline = src::of_iota(i_start, i_end) >> then::mapping([&tp](auto i) ->std::future { return tp.async( [i]() -> int { std::this_thread::sleep_for(200ms); return i; })/*.share()*/; }) >> then::cartesian( src::outer(std::ref(tee)) >> then::mapping([](auto i) { std::ios_base::fmtflags out_flag(std::cout.flags()); std::cout << "\t>inner:(" << i <<")"<< std::hex << i << "\n"; std::cout.flags(out_flag); return i; }) >> then::repeater() , [&tp](std::future outer, int inner) { return tp.async( [](std::future a, int b) -> std::tuple { int v = a.get(); return std::make_tuple(v, b, gcd(v, b)); }, std::move(outer), inner); }) >> then::minibatch<16>(tp) >> then::mapping([](const auto& future) { using t_t = std::decay_t; return const_cast( future ).get(); }) ; //following array contains big ints that on 0xFFF00 bitmask provides 0 const int big_int_mask_c = 0xFFF00; constexpr std::array big_int_basis{ 1+(2 << 23), 11+ (2 << 24), 13 + (2 << 25), 17 + (2 << 26), 19 + (2 << 27) }; size_t count_out = 0; auto back_work = tp.async([&]() { teepipeline.for_each([&](const auto& gcd_args) { count_out++; tresult.assert_false(big_int_mask_c & std::get<1>(gcd_args), "Wrong bigint collected"); std::ios_base::fmtflags out_flag(std::cout.flags()); tresult.debug() << std::hex << std::get<0>(gcd_args) << ", " << std::get<1>(gcd_args) << " = " << std::get<2>(gcd_args) << "\n"; std::cout.flags(out_flag); }); }); for(auto i : big_int_basis) tee.push(i); tee.stop(); back_work.wait(); //future1.wait(); tresult.assert_that(count_out, (i_end - i_start) * big_int_basis.size(), "Wrong num of rows produced"); } void test_mt_exceptions(OP::utest::TestResult& tresult) { tresult.info() << "Exception of async consumption...\n"; OP::utils::ThreadPool tp; auto pipeline = src::of_iota(0, 10) >> then::mapping([&tp](auto i) ->std::future { return tp.async([i]() -> int { std::this_thread::sleep_for(200ms); return (i & 1) ? throw std::runtime_error("-"):i; })/*.share()*/; }) >> then::mapping([](auto fi) { return fi.get(); }) >> then::minibatch<16>(tp) ; tresult.assert_exception([&](){ pipeline.for_each([&](auto i) { tresult.assert_that(0, i);//only once }); }); tresult.info() << "check exception during asyn queue consumption...\n"; QueueSrc> queue_for_pipeline2; auto pipeline2 = src::outer(std::ref(queue_for_pipeline2)) >> then::mapping([](const auto& fut) { return const_cast&>(fut).get(); }) ; queue_for_pipeline2.push(tp.async([&]() -> int { return 0; })); queue_for_pipeline2.push(tp.async([&]() ->int { throw std::runtime_error("instead of 1"); })); queue_for_pipeline2.stop(); tresult.assert_exception([&]() { pipeline2.for_each([&](auto i) { tresult.assert_that(0, i);//only once }); }); tresult.info() << "check async exception during 'next'...\n"; std::atomic i3{ 0 }; auto pipeline3 = src::generator([&]() { if (i3 > 0) { throw std::runtime_error("generation fail emulation"); } //don't do optional of future in real code return (i3 > 3) ? std::optional>{} : std::make_optional (tp.async([&]() { ++i3; return i3.load(); })); }) >> then::mapping([](const auto& fi) { return const_cast&>(fi).get(); }) ; tresult.assert_exception([&]() { pipeline3.count(); /* pipeline.for_each([&](auto i) { tresult.assert_that(0, i);//only once }); */ }); } static auto module_suite = OP::utest::default_test_suite("flur.multithread") ->declare(test_Mt, "mt") ->declare(test_mt_exceptions, "exceptions") ;openharmony-gitee-mirror/distributeddatamgr_datamgr /* * Copyright (c) 2021 Huawei Device 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. */ #ifndef OMIT_MULTI_VER #include "multi_ver_natural_store_snapshot.h" #include "db_constant.h" #include "db_errno.h" #include "log_print.h" #include "multi_ver_storage_executor.h" namespace DistributedDB { MultiVerNaturalStoreSnapshot::MultiVerNaturalStoreSnapshot(StorageExecutor *handle) : databaseHandle_(handle) {} MultiVerNaturalStoreSnapshot::~MultiVerNaturalStoreSnapshot() { databaseHandle_ = nullptr; } int MultiVerNaturalStoreSnapshot::Get(const Key &key, Value &value) const { if (databaseHandle_ == nullptr) { return -E_INVALID_DB; } if (key.empty() || key.size() > DBConstant::MAX_KEY_SIZE) { LOGE("[MultiSnapshot] Invalid key[%zu]", key.size()); return -E_INVALID_ARGS; } return static_cast(databaseHandle_)->Get(key, value); } int MultiVerNaturalStoreSnapshot::GetEntries(const Key &keyPrefix, std::vector &entries) const { if (databaseHandle_ == nullptr) { return -E_INVALID_DB; } if (keyPrefix.size() > DBConstant::MAX_KEY_SIZE) { LOGE("[MultiSnapshot] Invalid prefix[%zu]", keyPrefix.size()); return -E_INVALID_ARGS; } return static_cast(databaseHandle_)->GetEntries(keyPrefix, entries); } void MultiVerNaturalStoreSnapshot::Close() { if (databaseHandle_ != nullptr) { static_cast(databaseHandle_)->Close(); databaseHandle_ = nullptr; } } } // namespace DistributedDB #endif 1-10 /******************************************************************************* * Copyright (C) 2016 Maxim Integrated Products, Inc., 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 MAXIM INTEGRATED 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. * * Except as contained in this notice, the name of Maxim Integrated * Products, Inc. shall not be used except as stated in the Maxim Integrated * Products, Inc. Branding Policy. * * The mere transfer of this software does not imply any licenses * of trade secrets, proprietary technology, copyrights, patents, * trademarks, maskwork rights, or any other form of intellectual * property whatsoever. Maxim Integrated Products, Inc. retains all * ownership rights. ******************************************************************************* */ #include "RpcFifo.h" #include "Streaming.h" #include "RpcServer.h" // this will create a packet and insert it on the "jFifo" to be streamed out or // saved in flash void PacketFifo_InsertPacket(uint32_t packetId, uint32_t *buffer, uint32_t numberInBuffer) { StreamPacketUint32(packetId, buffer, numberInBuffer); } // clears the packet fifo "jFifo" void PacketFifo_Clear(void) { fifo_clear(GetStreamOutFifo()); } // returns one if fifo is empty, zero if not empty int PacketFifo_Empty(void) { return fifo_empty(GetStreamOutFifo()); } // returns a uint32 from the fifo, this uint32 is destined to be streamed out // USB or saved in flash uint32_t PacketFifo_GetUint32(void) { uint32_t val; fifo_get32(GetStreamOutFifo(), &val); return val; } /* Do not remove this header/ copyright information. * * Copyright © Trilobyte Software Engineering GmbH, Berlin, Germany 2010-2011. * You are allowed to modify and use the source code from * Trilobyte Software Engineering GmbH, Berlin, Germany for free if you are not * making profit with it or its adaption. Else you may contact Trilobyte SE. */ /* * UsageGetterAndControllerBase.hpp * * Created on: Jun 13, 2010 * Author: Stefan */ #ifndef USAGEGETTERANDCONTROLLERBASE_HPP_ #define USAGEGETTERANDCONTROLLERBASE_HPP_ #include //ULONGLONG namespace PentiumM { class UsageGetterAndControllerBase { ULONGLONG m_ullMaximumPerfCounterValue ; public: UsageGetterAndControllerBase() ; protected: ULONGLONG PerformanceCounterValueDiff( ULONGLONG ullPerformanceCounterCurrent , ULONGLONG ullPerformanceCounterPrevious ) ; }; } #endif /* USAGEGETTERANDCONTROLLERBASE_HPP_ */ #include #include #include #include #include #include #include #include struct Point { int x, y; auto operator<=>(const Point &a) const = default; Point operator-(const Point &a) const { return {x - a.x, y - a.y}; } Point &operator-=(const Point &a) { return *this = *this - a; } Point operator+(const Point &a) const { return {x + a.x, y + a.y}; } Point &operator+=(const Point &a) { return *this = *this + a; } Point operator/(int d) const { return {x / d, y / d}; } }; struct Line { Point a, b; bool operator<=>(const Line &a) const = default; void for_each_coord(auto fn) const { if (a == b) { fn(a); return; } Point delta = b - a; int gcd = std::gcd(delta.x, delta.y); Point delta_step = delta / gcd; for (Point p = a;; p += delta_step) { fn(p); if (p == b) { break; } } } bool is_axis_aligned() const { return a.x == b.x || a.y == b.y; } static std::optional read() { std::string input_line; std::getline(std::cin, input_line); if (!std::cin) { return std::nullopt; } input_line = std::regex_replace(input_line, std::regex{"[,\\->]"}, " "); int ax, ay, bx, by; std::istringstream input_line_ss{input_line}; input_line_ss >> ax >> ay >> bx >> by; if (!input_line_ss) { return std::nullopt; } return Line{{ax, ay}, {bx, by}}; } }; int main() { std::vector lines; while (true) { if (auto line = Line::read()) { // std::cout << "DEBUG: " << line->a.x << " " << line->a.y << " " << line->b.x << " " << line->b.y << "\n"; lines.push_back(*line); } else { break; } } // std::cout << "finished input" << "\n"; std::initializer_list> cases = {{"part 1", true}, {"part 2", false}}; for (const auto &[test_title, needs_axis_aligned] : cases) { std::map coord_counts; for (const auto &line : lines) { if (!needs_axis_aligned || line.is_axis_aligned()) { line.for_each_coord([&](Point p) { coord_counts[p] += 1; }); } } int intersection_count = std::count_if(coord_counts.begin(), coord_counts.end(), [](auto pair) { const auto [coord, count] = pair; return count >= 2; }); std::cout << test_title << " answer: " << intersection_count << '\n'; } } Tobias-Fischer/rviz-1 /* * Copyright (c) 2018, Bosch Software Innovations GmbH. * 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 Willow Garage, 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 #include #include #include #include #include // NOLINT: cpplint cannot handle include order here #include "rviz_rendering/objects/movable_text.hpp" #include "../ogre_testing_environment.hpp" #include "../matcher.hpp" using namespace ::testing; // NOLINT class MovableTextTestFixture : public ::testing::Test { protected: void SetUp() { testing_environment_ = std::make_shared(); testing_environment_->setUpOgreTestEnvironment(); } std::shared_ptr testing_environment_; }; float getCharWidth(std::shared_ptr movable_text, char character) { auto font = Ogre::FontManager::getSingleton().getByName("Liberation Sans", "rviz_rendering").get(); font->load(); float char_height = movable_text->getCharacterHeight(); float additional_space = 2.0f; return font->getGlyphAspectRatio(character) * char_height * additional_space; } TEST_F(MovableTextTestFixture, setCaption_changes_displayed_text) { auto movable_text = std::make_shared("TestCaption"); movable_text->setCaption("NewCaption"); ASSERT_EQ(movable_text->getCaption(), "NewCaption"); } TEST_F(MovableTextTestFixture, bounding_box_for_one_character_text_depends_on_glyp_ratio) { auto movable_text = std::make_shared("W"); float char_width = getCharWidth(movable_text, 'W'); ASSERT_THAT( movable_text->getBoundingBox(), AllOf(HasMinimum(Ogre::Vector3(0, -2, 0)), HasMaximum(Ogre::Vector3(char_width, 0, 0)))); } TEST_F(MovableTextTestFixture, bounding_box_space_is_given_by_bounding_box_for_A) { auto movable_text = std::make_shared("A A"); float char_width = getCharWidth(movable_text, 'A'); ASSERT_THAT( movable_text->getBoundingBox(), AllOf(HasMinimum(Ogre::Vector3(0, -2, 0)), HasMaximum(Ogre::Vector3(3 * char_width, 0, 0)))); } TEST_F(MovableTextTestFixture, new_line_creates_a_new_line_making_bounding_box_larger) { auto movable_text = std::make_shared("A\nA"); float char_width = getCharWidth(movable_text, 'A'); ASSERT_THAT( movable_text->getBoundingBox(), AllOf( HasMinimum(Ogre::Vector3(0, -4 - 0.01f, 0)), HasMaximum(Ogre::Vector3(char_width, 0, 0)) )); } TEST_F(MovableTextTestFixture, larger_char_height_makes_characters_wider) { auto movable_text = std::make_shared("A", "Liberation Sans", 2.0f); float char_width = getCharWidth(movable_text, 'A'); ASSERT_THAT( movable_text->getBoundingBox(), AllOf( HasMinimum(Ogre::Vector3(0, -2 * 2.0f, 0)), HasMaximum(Ogre::Vector3(char_width, 0, 0)) )); } TEST_F(MovableTextTestFixture, horizontal_alignment_center_centers_x_coordinate) { auto movable_text = std::make_shared("W"); movable_text->setTextAlignment( rviz_rendering::MovableText::HorizontalAlignment::H_CENTER, rviz_rendering::MovableText::VerticalAlignment::V_BELOW); movable_text->update(); float char_width = getCharWidth(movable_text, 'W'); ASSERT_THAT( movable_text->getBoundingBox(), AllOf( HasMinimum(Ogre::Vector3(-char_width / 2, -2, 0)), HasMaximum(Ogre::Vector3(char_width / 2, 0, 0)) )); } TEST_F(MovableTextTestFixture, vertical_alignment_center_centers_y_coordinate) { auto movable_text = std::make_shared("W"); movable_text->setTextAlignment( rviz_rendering::MovableText::HorizontalAlignment::H_LEFT, rviz_rendering::MovableText::VerticalAlignment::V_CENTER); movable_text->update(); float char_width = getCharWidth(movable_text, 'W'); ASSERT_THAT( movable_text->getBoundingBox(), AllOf( HasMinimum(Ogre::Vector3(0, -1, 0)), HasMaximum(Ogre::Vector3(char_width, 1, 0)) )); } TEST_F(MovableTextTestFixture, vertical_alignment_above_puts_y_coordinate_above_zero) { auto movable_text = std::make_shared("W"); movable_text->setTextAlignment( rviz_rendering::MovableText::HorizontalAlignment::H_LEFT, rviz_rendering::MovableText::VerticalAlignment::V_ABOVE); movable_text->update(); float char_width = getCharWidth(movable_text, 'W'); ASSERT_THAT( movable_text->getBoundingBox(), AllOf( HasMinimum(Ogre::Vector3(0, 0, 0)), HasMaximum(Ogre::Vector3(char_width, 2, 0)) )); } TEST_F(MovableTextTestFixture, vertical_alignment_above_puts_y_coordinate_above) { auto movable_text = std::make_shared("W\nW"); movable_text->setTextAlignment( rviz_rendering::MovableText::HorizontalAlignment::H_LEFT, rviz_rendering::MovableText::VerticalAlignment::V_ABOVE); movable_text->update(); float char_width = getCharWidth(movable_text, 'W'); ASSERT_THAT( movable_text->getBoundingBox(), AllOf( HasMinimum(Ogre::Vector3(0, 0, 0)), HasMaximum(Ogre::Vector3(char_width, 4.01f, 0)) )); } TEST_F(MovableTextTestFixture, setSpaceWidth_changes_width_of_space_character) { auto movable_text = std::make_shared("A A"); float new_space_width = 0.5f; movable_text->setSpaceWidth(new_space_width); movable_text->update(); float char_width = getCharWidth(movable_text, 'A'); ASSERT_THAT( movable_text->getBoundingBox(), AllOf( HasMinimum(Ogre::Vector3(0, -2, 0)), HasMaximum(Ogre::Vector3(2 * char_width + new_space_width, 0, 0)) )); } TEST_F(MovableTextTestFixture, setLineSpacing_changes_space_between_lines) { auto movable_text = std::make_shared("A\nA"); float new_line_spacing = 0.5f; movable_text->setLineSpacing(new_line_spacing); movable_text->update(); float char_width = getCharWidth(movable_text, 'A'); ASSERT_THAT( movable_text->getBoundingBox(), AllOf( HasMinimum(Ogre::Vector3(0, -2 * 2 - new_line_spacing, 0)), HasMaximum(Ogre::Vector3(char_width, 0, 0)) )); } TEST_F(MovableTextTestFixture, horizontal_alignment_works_correctly_with_spaces) { auto movable_text = std::make_shared("A A"); movable_text->setTextAlignment( rviz_rendering::MovableText::HorizontalAlignment::H_CENTER, rviz_rendering::MovableText::VerticalAlignment::V_BELOW); movable_text->update(); float char_width = getCharWidth(movable_text, 'A'); ASSERT_THAT( movable_text->getBoundingBox(), AllOf( HasMinimum(Ogre::Vector3(-3 * char_width / 2, -2, 0)), HasMaximum(Ogre::Vector3(3 * char_width / 2, 0, 0)) )); } TEST_F(MovableTextTestFixture, getBoundingRadius_gets_squared_length_from_origin_to_box_corner) { auto movable_text = std::make_shared("A A"); float char_width = getCharWidth(movable_text, 'A'); Ogre::Vector3 farthest_point = Ogre::Vector3(3 * char_width, -2.0f, 0); ASSERT_THAT( movable_text->getBoundingRadius(), Eq(Ogre::Math::Sqrt(farthest_point.squaredLength()))); } Redx93/BH0 #include #include "SaveSysteam.h" #include "DataSysteam.h" int main() { _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF); SaveSysteam* save = new SaveSysteam(); Inventory inventory; Item item(1); item.SetName("Laser"); inventory.AddItem(item); Item item2(2); item2.SetName("bajs"); inventory.AddItem(item2); inventory.Save(); delete save; system("pause"); return 0; } /* Copyright (c) 2021-Present Advanced Micro Devices, Inc. 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. */ #include static __global__ void f1(float *a) { *a = 1.0; } template static __global__ void f2(T *a) { *a = 1; } TEST_CASE("Unit_hipOccupancyMaxPotentialBlockSize_Negative") { hipError_t ret; int blockSize = 0; int gridSize = 0; // Validate each argument ret = hipOccupancyMaxPotentialBlockSize(NULL, &blockSize, f1, 0, 0); REQUIRE(ret != hipSuccess); ret = hipOccupancyMaxPotentialBlockSize(&gridSize, NULL, f1, 0, 0); REQUIRE(ret != hipSuccess); #ifndef __HIP_PLATFORM_NVIDIA__ // nvcc doesnt support kernelfunc(NULL) for api ret = hipOccupancyMaxPotentialBlockSize(&gridSize, &blockSize, NULL, 0, 0); REQUIRE(ret != hipSuccess); #endif } TEST_CASE("Unit_hipOccupancyMaxPotentialBlockSize_rangeValidation") { hipDeviceProp_t devProp; int blockSize = 0; int gridSize = 0; // Get potential blocksize HIP_CHECK(hipOccupancyMaxPotentialBlockSize(&gridSize, &blockSize, f1, 0, 0)); HIP_CHECK(hipGetDeviceProperties(&devProp, 0)); // Check if blockSize doen't exceed maxThreadsPerBlock REQUIRE(gridSize > 0); REQUIRE(blockSize > 0); REQUIRE(blockSize <= devProp.maxThreadsPerBlock); // Pass dynSharedMemPerBlk, blockSizeLimit and check out param blockSize = 0; gridSize = 0; HIP_CHECK(hipOccupancyMaxPotentialBlockSize(&gridSize, &blockSize, f1, devProp.sharedMemPerBlock, devProp.maxThreadsPerBlock)); // Check if blockSize doen't exceed maxThreadsPerBlock REQUIRE(gridSize > 0); REQUIRE(blockSize > 0); REQUIRE(blockSize <= devProp.maxThreadsPerBlock); } TEST_CASE("Unit_hipOccupancyMaxPotentialBlockSize_templateInvocation") { int gridSize = 0, blockSize = 0; HIP_CHECK(hipOccupancyMaxPotentialBlockSize(&gridSize, &blockSize, f2, 0, 0)); REQUIRE(gridSize > 0); REQUIRE(blockSize > 0); } #include "sai_vs.h" VS_GENERIC_QUAD(IPSEC,my_mac); const sai_my_mac_api_t vs_my_mac_api = { VS_GENERIC_QUAD_API(my_mac) }; sjnov11/Baekjoon-Online-Judge #include using namespace std; int dp[100001]; int main() { int N; cin >> N; dp[0] = 0; for (int i = 1; i <= N; i++) { dp[i] = 99999999; } for (int n = 1; n <= N; n++) { for (int i = 1; i * i <= n; i++) { if (dp[n] > dp[n - i * i]) dp[n] = dp[n - i * i] + 1; } } cout << dp[N] << endl; }PeculiarOvertones/artemis #include "WarpX.H" #include "BoundaryConditions/PML.H" #include "Evolve/WarpXDtType.H" #include "Utils/WarpXConst.H" #include "Utils/WarpXUtil.H" #include #include using namespace amrex; /** * \brief externalfieldtype determines which field component the external excitation is applied on * externalfieldtype == ExternalFieldType::AllExternal : external field excitation applied to all three field components, E, B and H * externalfieldtype == ExternalFieldType::EfieldExternal : external field excitation applied to E field only * externalfieldtype == ExternalFieldType::BfieldExternal : external field excitation applied to B field only * externalfieldtype == ExternalFieldType::HfieldExternal : external field excitation applied to H field only; this option is only valid when USE_LLG == TRUE */ void WarpX::ApplyExternalFieldExcitationOnGrid (int const externalfieldtype, DtType a_dt_type) { for (int lev = 0; lev <= finest_level; ++lev) { if (externalfieldtype == ExternalFieldType::AllExternal || externalfieldtype == ExternalFieldType::EfieldExternal) { if (E_excitation_grid_s == "parse_e_excitation_grid_function") { ApplyExternalFieldExcitationOnGrid(Efield_fp[lev][0].get(), Efield_fp[lev][1].get(), Efield_fp[lev][2].get(), Exfield_xt_grid_parser->compile<4>(), Eyfield_xt_grid_parser->compile<4>(), Ezfield_xt_grid_parser->compile<4>(), Exfield_flag_parser->compile<3>(), Eyfield_flag_parser->compile<3>(), Ezfield_flag_parser->compile<3>(), lev, a_dt_type ); } } // The excitation, especially when used to set an internal PEC, will be extended // to the PML region with user-defined parser. // As clarified in the documentation, it is important that the parser is valid in the pml region if (WarpX::isAnyBoundaryPML() and externalfieldtype == ExternalFieldType::EfieldExternalPML) { if (E_excitation_grid_s == "parse_e_excitation_grid_function") { ApplyExternalFieldExcitationOnGrid(pml[lev]->GetE_fp(0), pml[lev]->GetE_fp(1), pml[lev]->GetE_fp(2), Exfield_xt_grid_parser->compile<4>(), Eyfield_xt_grid_parser->compile<4>(), Ezfield_xt_grid_parser->compile<4>(), Exfield_flag_parser->compile<3>(), Eyfield_flag_parser->compile<3>(), Ezfield_flag_parser->compile<3>(), lev, a_dt_type ); } } if (externalfieldtype == ExternalFieldType::AllExternal || externalfieldtype == ExternalFieldType::BfieldExternal) { if (B_excitation_grid_s == "parse_b_excitation_grid_function") { ApplyExternalFieldExcitationOnGrid(Bfield_fp[lev][0].get(), Bfield_fp[lev][1].get(), Bfield_fp[lev][2].get(), Bxfield_xt_grid_parser->compile<4>(), Byfield_xt_grid_parser->compile<4>(), Bzfield_xt_grid_parser->compile<4>(), Bxfield_flag_parser->compile<3>(), Byfield_flag_parser->compile<3>(), Bzfield_flag_parser->compile<3>(), lev, a_dt_type ); } } #ifdef WARPX_MAG_LLG if (externalfieldtype == ExternalFieldType::AllExternal || externalfieldtype == ExternalFieldType::HfieldExternal) { if (H_excitation_grid_s == "parse_h_excitation_grid_function") { ApplyExternalFieldExcitationOnGrid(Hfield_fp[lev][0].get(), Hfield_fp[lev][1].get(), Hfield_fp[lev][2].get(), Hxfield_xt_grid_parser->compile<4>(), Hyfield_xt_grid_parser->compile<4>(), Hzfield_xt_grid_parser->compile<4>(), Hxfield_flag_parser->compile<3>(), Hyfield_flag_parser->compile<3>(), Hzfield_flag_parser->compile<3>(), lev, a_dt_type ); } } if (externalfieldtype == ExternalFieldType::AllExternal || externalfieldtype == ExternalFieldType::HbiasfieldExternal) { if (H_bias_excitation_grid_s == "parse_h_bias_excitation_grid_function") { ApplyExternalFieldExcitationOnGrid(H_biasfield_fp[lev][0].get(), H_biasfield_fp[lev][1].get(), H_biasfield_fp[lev][2].get(), Hx_biasfield_xt_grid_parser->compile<4>(), Hy_biasfield_xt_grid_parser->compile<4>(), Hz_biasfield_xt_grid_parser->compile<4>(), Hx_biasfield_flag_parser->compile<3>(), Hy_biasfield_flag_parser->compile<3>(), Hz_biasfield_flag_parser->compile<3>(), lev, a_dt_type ); } } #endif } // for loop over level } void WarpX::ApplyExternalFieldExcitationOnGrid ( amrex::MultiFab *mfx, amrex::MultiFab *mfy, amrex::MultiFab *mfz, ParserExecutor<4> const& xfield_parser, ParserExecutor<4> const& yfield_parser, ParserExecutor<4> const& zfield_parser, ParserExecutor<3> const& xflag_parser, ParserExecutor<3> const& yflag_parser, ParserExecutor<3> const& zflag_parser, const int lev, DtType a_dt_type ) { // This function adds the contribution from an external excitation to the fields. // A flag is used to determine the type of excitation. // If flag == 1, it is a hard source and the field = excitation // If flag == 2, if is a soft source and the field += excitation // If flag == 0, the excitation parser is not computed and the field is unchanged. // If flag is not 0, or 1, or 2, the code will Abort! // Gpu vector to store Ex-Bz staggering (Hx-Hz for LLG) GpuArray mfx_stag, mfy_stag, mfz_stag; for (int idim = 0; idim < AMREX_SPACEDIM; ++idim) { mfx_stag[idim] = mfx->ixType()[idim]; mfy_stag[idim] = mfy->ixType()[idim]; mfz_stag[idim] = mfz->ixType()[idim]; } amrex::Real t = gett_new(lev); const auto problo = Geom(lev).ProbLoArray(); const auto dx = Geom(lev).CellSizeArray(); amrex::IntVect x_nodal_flag = mfx->ixType().toIntVect(); amrex::IntVect y_nodal_flag = mfy->ixType().toIntVect(); amrex::IntVect z_nodal_flag = mfz->ixType().toIntVect(); // For each multifab, apply excitation to ncomponents // If not split pml fields, the excitation is applied to the regular Efield used in Maxwell's eq. // If pml field, then the excitation is applied to all the split field components. const int nComp_x = mfx->nComp(); const int nComp_y = mfy->nComp(); const int nComp_z = mfz->nComp(); // Multiplication factor for field parser depending on dt_type // If Full, then 1 (default), if FirstHalf or SecondHalf then 0.5 int dt_type_flag = 0; if (a_dt_type == DtType::FirstHalf or a_dt_type == DtType::SecondHalf ) { dt_type_flag = 1; } #ifdef AMREX_USE_OMP #pragma omp parallel if (Gpu::notInLaunchRegion()) #endif for ( MFIter mfi(*mfx, TilingIfNotGPU()); mfi.isValid(); ++mfi) { // Extract field data for this grid/tile amrex::Array4 const& Fx = mfx->array(mfi); amrex::Array4 const& Fy = mfy->array(mfi); amrex::Array4 const& Fz = mfz->array(mfi); const amrex::Box& tbx = mfi.tilebox( x_nodal_flag, mfx->nGrowVect() ); const amrex::Box& tby = mfi.tilebox( y_nodal_flag, mfy->nGrowVect() ); const amrex::Box& tbz = mfi.tilebox( z_nodal_flag, mfz->nGrowVect() ); // Loop over the cells and update the fields amrex::ParallelFor(tbx, nComp_x, [=] AMREX_GPU_DEVICE (int i, int j, int k, int n) { amrex::Real x, y, z; WarpXUtilAlgo::getCellCoordinates(i, j, k, mfx_stag, problo, dx, x, y, z); auto flag_type = xflag_parser(x,y,z); amrex::Real dt_type_factor = 1._rt; // For soft source and FirstHalf/SecondHalf evolve // the excitation is split with a prefector of 0.5 if (flag_type == 2._rt and dt_type_flag == 1) { dt_type_factor = 0.5_rt; } if (flag_type != 0._rt && flag_type != 1._rt && flag_type != 2._rt) { amrex::Abort("flag type for excitation must be 0, or 1, or 2!"); } else if ( flag_type > 0._rt ) { Fx(i, j, k, n) = Fx(i,j,k,n)*(flag_type-1.0_rt) + dt_type_factor * xfield_parser(x,y,z,t); } }, tby, nComp_y, [=] AMREX_GPU_DEVICE (int i, int j, int k, int n) { amrex::Real x, y, z; WarpXUtilAlgo::getCellCoordinates(i, j, k, mfy_stag, problo, dx, x, y, z); auto flag_type = yflag_parser(x,y,z); amrex::Real dt_type_factor = 1._rt; // For soft source and FirstHalf/SecondHalf evolve // the excitation is split with a prefector of 0.5 if (flag_type == 2._rt and dt_type_flag == 1) { dt_type_factor = 0.5_rt; } if (flag_type != 0._rt && flag_type != 1._rt && flag_type != 2._rt) { amrex::Abort("flag type for excitation must be 0, or 1, or 2!"); } else if ( flag_type > 0._rt ) { Fy(i, j, k, n) = Fy(i,j,k,n)*(flag_type-1.0_rt) + dt_type_factor * yfield_parser(x,y,z,t); } }, tbz, nComp_z, [=] AMREX_GPU_DEVICE (int i, int j, int k, int n) { amrex::Real x, y, z; WarpXUtilAlgo::getCellCoordinates(i, j, k, mfz_stag, problo, dx, x, y, z); auto flag_type = zflag_parser(x,y,z); amrex::Real dt_type_factor = 1._rt; // For soft source and FirstHalf/SecondHalf evolve // the excitation is split with a prefector of 0.5 if (flag_type == 2._rt and dt_type_flag == 1) { dt_type_factor = 0.5_rt; } if (flag_type != 0._rt && flag_type != 1._rt && flag_type != 2._rt) { amrex::Abort("flag type for excitation must be 0, or 1, or 2!"); } else if ( flag_type > 0._rt ) { Fz(i, j, k,n) = Fz(i,j,k,n)*(flag_type-1.0_rt) + dt_type_factor * zfield_parser(x,y,z,t); } } ); } } void WarpX::ReadExcitationParser () { ParmParse pp_warpx("warpx"); // Query for type of external space-time (xt) varying excitation pp_warpx.query("B_excitation_on_grid_style", B_excitation_grid_s); std::transform(B_excitation_grid_s.begin(), B_excitation_grid_s.end(), B_excitation_grid_s.begin(), ::tolower); #ifdef WARPX_MAG_LLG if (pp_warpx.query("B_excitation_on_grid_style", B_excitation_grid_s)) { amrex::Abort("ERROR: Excitation of B field is not allowed in the LLG simulation! \nThe excited magnetic field must be H field! \n"); } #endif pp_warpx.query("E_excitation_on_grid_style", E_excitation_grid_s); std::transform(E_excitation_grid_s.begin(), E_excitation_grid_s.end(), E_excitation_grid_s.begin(), ::tolower); #ifdef WARPX_MAG_LLG pp_warpx.query("H_excitation_on_grid_style", H_excitation_grid_s); std::transform(H_excitation_grid_s.begin(), H_excitation_grid_s.end(), H_excitation_grid_s.begin(), ::tolower); pp_warpx.query("H_bias_excitation_on_grid_style", H_bias_excitation_grid_s); std::transform(H_bias_excitation_grid_s.begin(), H_bias_excitation_grid_s.end(), H_bias_excitation_grid_s.begin(), ::tolower); #endif if (E_excitation_grid_s == "parse_e_excitation_grid_function") { // if E excitation type is set to parser then the corresponding // source type (hard=1, soft=2) must be specified for all components // using the flag function. Note that a flag value of 0 will not update // the field with the excitation. Store_parserString(pp_warpx, "Ex_excitation_flag_function(x,y,z)", str_Ex_excitation_flag_function); Store_parserString(pp_warpx, "Ey_excitation_flag_function(x,y,z)", str_Ey_excitation_flag_function); Store_parserString(pp_warpx, "Ez_excitation_flag_function(x,y,z)", str_Ez_excitation_flag_function); Exfield_flag_parser = std::make_unique( makeParser(str_Ex_excitation_flag_function,{"x","y","z"})); Eyfield_flag_parser = std::make_unique( makeParser(str_Ey_excitation_flag_function,{"x","y","z"})); Ezfield_flag_parser = std::make_unique( makeParser(str_Ez_excitation_flag_function,{"x","y","z"})); pp_warpx.query("Apply_E_excitation_in_pml_region", ApplyExcitationInPML); } if (B_excitation_grid_s == "parse_b_excitation_grid_function") { // if B excitation type is set to parser then the corresponding // source type (hard=1, soft=2) must be specified for all components // using the flag function. Note that a flag value of 0 will not update // the field with the excitation. Store_parserString(pp_warpx, "Bx_excitation_flag_function(x,y,z)", str_Bx_excitation_flag_function); Store_parserString(pp_warpx, "By_excitation_flag_function(x,y,z)", str_By_excitation_flag_function); Store_parserString(pp_warpx, "Bz_excitation_flag_function(x,y,z)", str_Bz_excitation_flag_function); Bxfield_flag_parser = std::make_unique( makeParser(str_Bx_excitation_flag_function,{"x","y","z"})); Byfield_flag_parser = std::make_unique( makeParser(str_By_excitation_flag_function,{"x","y","z"})); Bzfield_flag_parser = std::make_unique( makeParser(str_Bz_excitation_flag_function,{"x","y","z"})); } #ifdef WARPX_MAG_LLG if (H_excitation_grid_s == "parse_h_excitation_grid_function") { // if H excitation type is set to parser then the corresponding // source type (hard=1, soft=2) must be specified for all components // using the flag function. Note that a flag value of 0 will not update // the field with the excitation. Store_parserString(pp_warpx, "Hx_excitation_flag_function(x,y,z)", str_Hx_excitation_flag_function); Store_parserString(pp_warpx, "Hy_excitation_flag_function(x,y,z)", str_Hy_excitation_flag_function); Store_parserString(pp_warpx, "Hz_excitation_flag_function(x,y,z)", str_Hz_excitation_flag_function); Hxfield_flag_parser = std::make_unique( makeParser(str_Hx_excitation_flag_function,{"x","y","z"})); Hyfield_flag_parser = std::make_unique( makeParser(str_Hy_excitation_flag_function,{"x","y","z"})); Hzfield_flag_parser = std::make_unique( makeParser(str_Hz_excitation_flag_function,{"x","y","z"})); } if (H_bias_excitation_grid_s == "parse_h_bias_excitation_grid_function") { // if H bias_excitation type is set to parser then the corresponding // source type (hard=1, soft=2) must be specified for all components // using the flag function. Note that a flag value of 0 will not update // the field with the excitation. Store_parserString(pp_warpx, "Hx_bias_excitation_flag_function(x,y,z)", str_Hx_bias_excitation_flag_function); Store_parserString(pp_warpx, "Hy_bias_excitation_flag_function(x,y,z)", str_Hy_bias_excitation_flag_function); Store_parserString(pp_warpx, "Hz_bias_excitation_flag_function(x,y,z)", str_Hz_bias_excitation_flag_function); Hx_biasfield_flag_parser = std::make_unique( makeParser(str_Hx_bias_excitation_flag_function,{"x","y","z"})); Hy_biasfield_flag_parser = std::make_unique( makeParser(str_Hy_bias_excitation_flag_function,{"x","y","z"})); Hz_biasfield_flag_parser = std::make_unique( makeParser(str_Hz_bias_excitation_flag_function,{"x","y","z"})); } #endif // make parser for the external B-excitation in space-time if (B_excitation_grid_s == "parse_b_excitation_grid_function") { #ifdef WARPX_DIM_RZ amrex::Abort("E and B parser for external fields does not work with RZ -- TO DO"); #endif Store_parserString(pp_warpx, "Bx_excitation_grid_function(x,y,z,t)", str_Bx_excitation_grid_function); Store_parserString(pp_warpx, "By_excitation_grid_function(x,y,z,t)", str_By_excitation_grid_function); Store_parserString(pp_warpx, "Bz_excitation_grid_function(x,y,z,t)", str_Bz_excitation_grid_function); Bxfield_xt_grid_parser = std::make_unique( makeParser(str_Bx_excitation_grid_function,{"x","y","z","t"})); Byfield_xt_grid_parser = std::make_unique( makeParser(str_By_excitation_grid_function,{"x","y","z","t"})); Bzfield_xt_grid_parser = std::make_unique( makeParser(str_Bz_excitation_grid_function,{"x","y","z","t"})); } // make parser for the external E-excitation in space-time if (E_excitation_grid_s == "parse_e_excitation_grid_function") { #ifdef WARPX_DIM_RZ amrex::Abort("E and B parser for external fields does not work with RZ -- TO DO"); #endif Store_parserString(pp_warpx, "Ex_excitation_grid_function(x,y,z,t)", str_Ex_excitation_grid_function); Store_parserString(pp_warpx, "Ey_excitation_grid_function(x,y,z,t)", str_Ey_excitation_grid_function); Store_parserString(pp_warpx, "Ez_excitation_grid_function(x,y,z,t)", str_Ez_excitation_grid_function); Exfield_xt_grid_parser = std::make_unique( makeParser(str_Ex_excitation_grid_function,{"x","y","z","t"})); Eyfield_xt_grid_parser = std::make_unique( makeParser(str_Ey_excitation_grid_function,{"x","y","z","t"})); Ezfield_xt_grid_parser = std::make_unique( makeParser(str_Ez_excitation_grid_function,{"x","y","z","t"})); } #ifdef WARPX_MAG_LLG // make parser for the external H-excitation in space-time if (H_excitation_grid_s == "parse_h_excitation_grid_function") { #ifdef WARPX_DIM_RZ amrex::Abort("H parser for external fields does not work with RZ -- TO DO"); #endif Store_parserString(pp_warpx, "Hx_excitation_grid_function(x,y,z,t)", str_Hx_excitation_grid_function); Store_parserString(pp_warpx, "Hy_excitation_grid_function(x,y,z,t)", str_Hy_excitation_grid_function); Store_parserString(pp_warpx, "Hz_excitation_grid_function(x,y,z,t)", str_Hz_excitation_grid_function); Hxfield_xt_grid_parser = std::make_unique( makeParser(str_Hx_excitation_grid_function,{"x","y","z","t"})); Hyfield_xt_grid_parser = std::make_unique( makeParser(str_Hy_excitation_grid_function,{"x","y","z","t"})); Hzfield_xt_grid_parser = std::make_unique( makeParser(str_Hz_excitation_grid_function,{"x","y","z","t"})); } // make parser for the external H-biasexcitation in space-time if (H_bias_excitation_grid_s == "parse_h_bias_excitation_grid_function") { #ifdef WARPX_DIM_RZ amrex::Abort("H parser for external fields does not work with RZ -- TO DO"); #endif Store_parserString(pp_warpx, "Hx_bias_excitation_grid_function(x,y,z,t)", str_Hx_bias_excitation_grid_function); Store_parserString(pp_warpx, "Hy_bias_excitation_grid_function(x,y,z,t)", str_Hy_bias_excitation_grid_function); Store_parserString(pp_warpx, "Hz_bias_excitation_grid_function(x,y,z,t)", str_Hz_bias_excitation_grid_function); Hx_biasfield_xt_grid_parser = std::make_unique( makeParser(str_Hx_bias_excitation_grid_function,{"x","y","z","t"})); Hy_biasfield_xt_grid_parser = std::make_unique( makeParser(str_Hy_bias_excitation_grid_function,{"x","y","z","t"})); Hz_biasfield_xt_grid_parser = std::make_unique( makeParser(str_Hz_bias_excitation_grid_function,{"x","y","z","t"})); } #endif } dreamsxin/ultimateppbazaar/RasterCtrlTest/RasterCtrlTest.cpp #include "RasterCtrlTest.h" //////////////////////////////////////////////////////////////////////////////////////////////// void RasterCtrlTestWindow::Menu_File_Open_cb() { String fileName; FileSelector fs; fs.ReadOnlyOption(); if(fs.ExecuteOpen("Please select a graphic file to view:")) rasterCtrl.Open(fs); } // END RasterCtrlTestWindow::Menu_File_Open() //////////////////////////////////////////////////////////////////////////////////////////////// void RasterCtrlTestWindow::Menu_File_Exit_cb() { if ( PromptOKCancel( "Exit RasterCtrlTest ?" ) ) Break(); } // END RasterCtrlTestWindow::Menu_File_Exit_cb() //////////////////////////////////////////////////////////////////////////////////////////////// void RasterCtrlTestWindow::Menu_File( Bar& bar ) { bar.Add( "Open", THISBACK( Menu_File_Open_cb ) ); bar.Add( "Exit", THISBACK( Menu_File_Exit_cb ) ); } // END RasterCtrlTestWindow::Menu_File() //////////////////////////////////////////////////////////////////////////////////////////////// void RasterCtrlTestWindow::Menu_View_cb(int i) { switch(i) { case -1 : rasterCtrl.ZoomWidth(); break; case -2 : rasterCtrl.ZoomPage(); break; case -3: rasterCtrl.ShowThumbnails(!rasterCtrl.HasThumbnails()); break; default : rasterCtrl.Zoom(i); break; } } // END RasterCtrlTestWindow::Menu_View_cb() //////////////////////////////////////////////////////////////////////////////////////////////// void RasterCtrlTestWindow::Menu_View( Bar& bar ) { bar.Add( "Page width", THISBACK1( Menu_View_cb, -1 ) ); bar.Add( "Full page", THISBACK1( Menu_View_cb, -2 ) ); bar.Add( "Zoom 10%", THISBACK1( Menu_View_cb, 10 ) ); bar.Add( "Zoom 20%", THISBACK1( Menu_View_cb, 20 ) ); bar.Add( "Zoom 50%", THISBACK1( Menu_View_cb, 50 ) ); bar.Add( "Zoom 100%", THISBACK1( Menu_View_cb, 100 ) ); bar.Add( "Zoom 150%", THISBACK1( Menu_View_cb, 150 ) ); bar.Add( "Toggle thumbnails" , THISBACK1( Menu_View_cb, -3 ) ); } // END RasterCtrlTestWindow::ViewMenu() //////////////////////////////////////////////////////////////////////////////////////////////// void RasterCtrlTestWindow::MainMenu( Bar& bar ) { bar.Add( "File", THISBACK( Menu_File ) ); bar.Add( "View", THISBACK( Menu_View ) ); } // END RasterCtrlTestWindow::MainMenu() RasterCtrlTestWindow::RasterCtrlTestWindow() { // sets up frame, menu and statusbar AddFrame( menu ); AddFrame( TopSeparatorFrame() ); AddFrame( status ); AddFrame( InsetFrame() ); // populates menu menu.Set( THISBACK( MainMenu ) ); // adds raster control Add(rasterCtrl.HSizePos().VSizePos()); Sizeable().Zoomable(); BackPaint(); // view.Open("/home/massimo/sources/uppdev/gatofax/fax000000002.tif"); // view.Open("/home/massimo/pluto.tif"); Refresh(); } GUI_APP_MAIN { RasterCtrlTestWindow().Run(); } #define CATCH_CONFIG_MAIN #include #include "../include/CeresTask/Executor.h" #include "../include/CeresTask/TaskGroup.h" #include "../include/CeresTask/Task.h" #include "TestTask.h" TEST_CASE("Single task executes correctly", "[tasking][usage]") { auto exec = Executor(1); auto taskGroup = std::make_unique("simpleTasks"); auto testTask = std::make_unique("simpleTestTask1"); SECTION("Check successfull tasks") { taskGroup->addTask(std::move(testTask)); auto future = exec.submit(std::move(taskGroup)); auto done = future.wait_for(std::chrono::milliseconds(1000)); REQUIRE(done == std::future_status::ready); REQUIRE(future.valid()); REQUIRE(future.get()); } SECTION("Check failing tasks") { testTask->setShouldFail(); taskGroup->addTask(std::move(testTask)); auto future = exec.submit(std::move(taskGroup)); auto done = future.wait_for(std::chrono::milliseconds(1000)); REQUIRE(done == std::future_status::ready); REQUIRE(future.valid()); REQUIRE(!future.get()); } } TEST_CASE("Two tasks behave correctly", "[tasking][usage]") { auto exec = Executor(1); auto taskGroup = std::make_unique("simpleTasks"); auto testTask1 = std::make_unique("simpleTestTask1"); auto testTask2 = std::make_unique("simpleTestTask2"); auto id1 = testTask1->getID(); auto id2 = testTask2->getID(); SECTION("Completely parallel both successfull") { taskGroup->addTask(std::move(testTask1)); taskGroup->addTask(std::move(testTask2)); auto future = exec.submit(std::move(taskGroup)); auto done = future.wait_for(std::chrono::milliseconds(1000)); REQUIRE(done == std::future_status::ready); REQUIRE(future.valid()); REQUIRE(future.get()); } SECTION("Completely parallel one fails") { testTask2->setShouldFail(); taskGroup->addTask(std::move(testTask1)); taskGroup->addTask(std::move(testTask2)); auto future = exec.submit(std::move(taskGroup)); auto done = future.wait_for(std::chrono::milliseconds(1000)); REQUIRE(done == std::future_status::ready); REQUIRE(future.valid()); REQUIRE(!future.get()); } SECTION("Sequential both successfull") { taskGroup->addTask(std::move(testTask1)); taskGroup->addTask(std::move(testTask2)); taskGroup->addWaitOnEdge(id1, id2); auto future = exec.submit(std::move(taskGroup)); auto done = future.wait_for(std::chrono::milliseconds(1000)); REQUIRE(done == std::future_status::ready); REQUIRE(future.valid()); REQUIRE(future.get()); } SECTION("Sequential first fails") { testTask1->setShouldFail(); taskGroup->addTask(std::move(testTask1)); taskGroup->addTask(std::move(testTask2)); taskGroup->addWaitOnEdge(id1, id2); auto future = exec.submit(std::move(taskGroup)); auto done = future.wait_for(std::chrono::milliseconds(1000)); REQUIRE(done == std::future_status::ready); REQUIRE(future.valid()); REQUIRE(future.get()); } SECTION("Sequential second fails") { testTask2->setShouldFail(); taskGroup->addTask(std::move(testTask1)); taskGroup->addTask(std::move(testTask2)); taskGroup->addWaitOnEdge(id1, id2); auto future = exec.submit(std::move(taskGroup)); auto done = future.wait_for(std::chrono::milliseconds(1000)); REQUIRE(done == std::future_status::ready); REQUIRE(future.valid()); REQUIRE(!future.get()); } SECTION("Sequential failure ripples through") { testTask1->setShouldFail(); testTask2->setShouldFailIfBeforeFailed(); taskGroup->addTask(std::move(testTask1)); taskGroup->addTask(std::move(testTask2)); taskGroup->addWaitOnEdge(id1, id2); auto future = exec.submit(std::move(taskGroup)); auto done = future.wait_for(std::chrono::milliseconds(1000)); REQUIRE(done == std::future_status::ready); REQUIRE(future.valid()); REQUIRE(!future.get()); } } TEST_CASE("Wait on works correctly", "[tasking][usage]") { auto exec = Executor(1); auto taskGroup = std::make_unique("interlockingTasks"); auto testTask1 = std::make_unique("simpleTestTask1"); auto testTask2 = std::make_unique("simpleTestTask2"); auto testTask3 = std::make_unique("simpleTestTask3"); auto testTask4 = std::make_unique("simpleTestTask4"); auto testTask5 = std::make_unique("simpleTestTask5"); auto testTask6 = std::make_unique("simpleTestTask6"); std::atomic_uint stage1 = 0, stage2 = 0, stage3 = 0; auto id1 = testTask1->getID(); auto id2 = testTask2->getID(); auto id3 = testTask3->getID(); auto id4 = testTask4->getID(); auto id5 = testTask5->getID(); auto id6 = testTask6->getID(); auto stage1Func = [&stage1,&stage2,&stage3](bool) { stage1++; return stage2 == 0 && stage3 == 0; }; auto stage2Func = [&stage1, &stage2, &stage3](bool before) { stage2++; return (stage1 == 1 && stage3 == 0) || before; }; auto stage3Func = [&stage1, &stage2, &stage3](bool before) { stage3++; return (stage1 == 1 && stage2 == 2) || before; }; auto stage4Func = [&stage1, &stage2, &stage3](bool before) { return (stage1 == 1 && stage2 == 2 && stage3 == 2) || before; }; /* Dependency Graph: 1 Stage1 / \ ------ 2 3 Stage2 |\ /| | X | ------ |/ \| 4 5 Stage3 \ / ------ 6 Stage4 */ testTask1->setCustomRunFunction(stage1Func); taskGroup->addTask(std::move(testTask1)); testTask2->setCustomRunFunction(stage2Func); taskGroup->addTask(std::move(testTask2)); testTask3->setCustomRunFunction(stage2Func); taskGroup->addTask(std::move(testTask3)); testTask4->setCustomRunFunction(stage3Func); taskGroup->addTask(std::move(testTask4)); testTask5->setCustomRunFunction(stage3Func); taskGroup->addTask(std::move(testTask5)); testTask6->setCustomRunFunction(stage4Func); taskGroup->addTask(std::move(testTask6)); taskGroup->addWaitOnEdge(id1, id2); taskGroup->addWaitOnEdge(id1, id3); taskGroup->addWaitOnEdge(id2, id4); taskGroup->addWaitOnEdge(id2, id5); taskGroup->addWaitOnEdge(id3, id4); taskGroup->addWaitOnEdge(id3, id5); taskGroup->addWaitOnEdge(id4, id6); taskGroup->addWaitOnEdge(id5, id6); auto future = exec.submit(std::move(taskGroup)); auto done = future.wait_for(std::chrono::milliseconds(1000)); REQUIRE(done == std::future_status::ready); REQUIRE(future.valid()); REQUIRE(future.get()); REQUIRE(stage1 == 1); REQUIRE(stage2 == 2); REQUIRE(stage3 == 2); }0 /* This file is part of: NoahFrame https://github.com/ketoo/NoahGameFrame Copyright 2009 - 2020 NoahFrame(NoahGameFrame) File creator: lvsheng.huang NoahFrame is open-source software and you can redistribute it and/or modify it under the terms of the License; besides, anyone who use this file/software must include this copyright announcement. 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 "NFGameServerPlugin.h" #include "NFGameServerModule.h" #include "NFComm/NFKernelPlugin/NFSceneModule.h" vector raceType = { "Saber","Archer","Wizard" }; vector elementType = { "Aurum", "Wood", "Water", "Fire", "Earth" }; bool NFGameServerModule::Init() { m_pKernelModule = pPluginManager->FindModule(); m_pClassModule = pPluginManager->FindModule(); m_pSceneModule = pPluginManager->FindModule(); m_pNetModule = pPluginManager->FindModule(); m_pGameServerNet_ServerModule = pPluginManager->FindModule(); return true; } bool NFGameServerModule::Shut() { return true; } bool NFGameServerModule::Execute() { #ifdef _DEBUG /* char szContent[MAX_PATH] = { 0 }; if (kbhit() && gets(szContent)) { NFDataList val(szContent, ","); if (val.GetCount() > 0) { //const char* pstrCmd = val.String( 0 ); m_pKernelModule->Command(val); } } */ #endif int64_t currentTime = NFGetTimeS(); int deltaTime = currentTime - preTime; preTime = currentTime; vector groups = m_pSceneModule->GetGroups(3); for (int& id : groups) { if (id != 1) continue; NF_SHARE_PTR groupChessPlaneOne = m_pSceneModule->FindRecord(3, id, NFrame::Group::ChessPlane1::ThisName()); int gameState = m_pSceneModule->GetPropertyInt(3, id, NFrame::Group::GameState()); NFDataList playerList; m_pKernelModule->GetGroupObjectList(3, id, playerList, true); // come in preparation stage if (!gameState) { int currentTime = m_pSceneModule->GetPropertyInt(3, id, NFrame::Group::GameTime()); currentTime += deltaTime; if(currentTime < preparationDuration) m_pSceneModule->SetPropertyInt(3, id, NFrame::Group::GameTime(), currentTime); else { NF_SHARE_PTR playerTwoPlane = m_pKernelModule->FindRecord(playerList.Object(0), NFrame::Player::ChessPlane::ThisName()); for (int col = 0; col < 7; col++) { NFGUID id = playerTwoPlane->GetObjectA(col, 0); groupChessPlaneOne->SetObject(col, 7, id); id = playerTwoPlane->GetObjectA(col, 1); groupChessPlaneOne->SetObject(col, 6, id); id = playerTwoPlane->GetObjectA(col, 2); groupChessPlaneOne->SetObject(col, 5, id); id = playerTwoPlane->GetObjectA(col, 3); groupChessPlaneOne->SetObject(col, 4, id); } NF_SHARE_PTR playerPlane = m_pKernelModule->FindRecord(playerList.Object(1), NFrame::Player::ChessPlane::ThisName()); for (int row = 0; row < 4; row++) { for (int col = 0; col < 7; col++) { const NFGUID id = playerPlane->GetObjectA(row, col); groupChessPlaneOne->SetObject(row, col, id); } } m_pSceneModule->SetPropertyObject(3, id, NFrame::Group::PlayerOne(), playerList.Object(0)); m_pSceneModule->SetPropertyObject(3, id, NFrame::Group::PlayerTwo(), playerList.Object(1)); m_pSceneModule->SetPropertyInt(3, id, NFrame::Group::PlaneOne(),0); m_pSceneModule->SetPropertyInt(3, id, NFrame::Group::GameState(), 1); m_pSceneModule->SetPropertyInt(3, id, NFrame::Group::GameTime(), 0); } } else { int planeOne = m_pSceneModule->GetPropertyInt(3, id, NFrame::Group::PlaneOne()); if (!planeOne) { fight(id, groupChessPlaneOne); } else { for (int i = 0; i < playerList.GetCount(); i++) { const NFGUID& playerId = playerList.Object(i); refreshShopItem(playerId); } NF_SHARE_PTR groupChessPlaneOne = m_pSceneModule->FindRecord(3, id, NFrame::Group::ChessPlane1::ThisName()); NFGUID playerOne = m_pSceneModule->GetPropertyObject(3, id, NFrame::Group::PlayerOne()); NFGUID playerTwo = m_pSceneModule->GetPropertyObject(3, id, NFrame::Group::PlayerTwo()); int countOne = 0, countTwo = 0; for (int col = 0; col < 7; col++) { for (int row = 0; row < 8; row++) { const NFGUID id = groupChessPlaneOne->GetObjectA(col, row); if (!id.IsNull()) { NFGUID masterID = m_pKernelModule->GetPropertyObject(id, NFrame::NPC::MasterID()); double hpValue = m_pKernelModule->GetPropertyFloat(id, NFrame::NPC::HP()); if (masterID == playerOne && hpValue) countOne++; if (masterID == playerTwo && hpValue) countTwo++; } } } int damage = abs(countOne - countTwo); if (!countOne) { int playerHp = m_pKernelModule->GetPropertyInt(playerOne, NFrame::Player::HP()); playerHp -= damage; if (playerHp < 0) playerHp = 0; m_pKernelModule->SetPropertyInt(playerOne, NFrame::Player::HP(), playerHp); } else if (!countTwo) { int playerHp = m_pKernelModule->GetPropertyInt(playerTwo, NFrame::Player::HP()); playerHp -= damage; if (playerHp < 0) playerHp = 0; m_pKernelModule->SetPropertyInt(playerTwo, NFrame::Player::HP(), playerHp); } NF_SHARE_PTR playerOneRecord = m_pKernelModule->FindRecord(playerOne, NFrame::Player::ChessPlane::ThisName()); RecoverChessState(playerOneRecord); NF_SHARE_PTR playerTwoRecord = m_pKernelModule->FindRecord(playerTwo, NFrame::Player::ChessPlane::ThisName()); RecoverChessState(playerTwoRecord); m_pSceneModule->SetPropertyInt(3, id, NFrame::Group::GameState(), 0); } } } return true; } bool NFGameServerModule::AfterInit() { m_pNetModule->AddReceiveCallBack(NFMsg::EVENT_REFRESH_SHOP, this, &NFGameServerModule::OnRefreshShop); m_pNetModule->AddReceiveCallBack(NFMsg::EVENT_BUY_LEVEL, this, &NFGameServerModule::OnBuyLvL); m_pNetModule->AddReceiveCallBack(NFMsg::EVENT_BUY_CHAMPION, this, &NFGameServerModule::OnBuyChampion); m_pSceneModule->AddGroupPropertyCallBack(NFrame::Group::GameState(),this,&NFGameServerModule::OnGameStateChange); return true; } bool NFGameServerModule::BeforeShut() { return true; } void NFGameServerModule::refreshShopItem(const NFGUID& id) { std::shared_ptr record = m_pKernelModule->FindRecord(id, NFrame::Player::ChampionShop::ThisName()); int rows = record->GetUsedRows(); if (rows < 5) { for (int i = 0; i < 5; i++) { record->AddRow(-1); } } for (int i = 0; i < 5; i++) { string race = raceType[(int)m_pKernelModule->Random(0, 3)]; string element = elementType[(int)m_pKernelModule->Random(0, 5)]; record->SetString(i, NFrame::Player::ChampionShop::ElementType, element); record->SetString(i, NFrame::Player::ChampionShop::RaceType, race); record->SetInt(i, NFrame::Player::ChampionShop::Cost, 3); } cout << record->GetUsedRows(); cout << record->ToString() << endl; std::shared_ptr ownRecord = m_pKernelModule->FindRecord(id, NFrame::Player::ownInventory::ThisName()); cout << ownRecord->ToString() << endl; std::shared_ptr planeRecord = m_pKernelModule->FindRecord(id, NFrame::Player::ChessPlane::ThisName()); cout << planeRecord->ToString() << endl; } void NFGameServerModule::OnRefreshShop(const NFSOCK sockIndex, const int msgID, const char* msg, const uint32_t len) { NFGUID clientID; NFMsg::ReqAckSwapScene xMsg; if (!m_pNetModule->ReceivePB(msgID, msg, len, xMsg, clientID)) { return; } int goldVal = m_pKernelModule->GetPropertyInt(clientID, NFrame::Player::GameGold()); if (goldVal >= 2) { goldVal -= 2; if (goldVal < 0) goldVal = 0; m_pKernelModule->SetPropertyInt(clientID, NFrame::Player::GameGold(), goldVal); refreshShopItem(clientID); } } void NFGameServerModule::OnBuyLvL(const NFSOCK sockIndex, const int msgID, const char* msg, const uint32_t len) { NFGUID clientID; NFMsg::ReqAckSwapScene xMsg; if (!m_pNetModule->ReceivePB(msgID, msg, len, xMsg, clientID)) { return; } int goldVal = m_pKernelModule->GetPropertyInt(clientID, NFrame::Player::GameGold()); if (goldVal >= 4) { goldVal -= 4; if (goldVal < 0) goldVal = 0; m_pKernelModule->SetPropertyInt(clientID, NFrame::Player::GameGold(), goldVal); int lvlVal = m_pKernelModule->GetPropertyInt(clientID, NFrame::Player::GameLVL()); m_pKernelModule->SetPropertyInt(clientID, NFrame::Player::GameLVL(), ++lvlVal); } } void NFGameServerModule::OnBuyChampion(const NFSOCK sockIndex, const int msgID, const char* msg, const uint32_t len) { NFGUID clientID; NFMsg::ReqAckSwapScene xMsg; if (!m_pNetModule->ReceivePB(msgID, msg, len, xMsg, clientID)) { return; } int index = xMsg.x(); std::shared_ptr championShops = m_pKernelModule->FindRecord(clientID, NFrame::Player::ChampionShop::ThisName()); string element = championShops->GetString(index, NFrame::Player::ChampionShop::ElementType); string race = championShops->GetString(index, NFrame::Player::ChampionShop::RaceType); int goldVal = m_pKernelModule->GetPropertyInt(clientID, NFrame::Player::GameGold()); if (goldVal >= 3 && SetHeroOnInventory(clientID, element, race)) { goldVal -= 3; m_pKernelModule->SetPropertyInt(clientID, NFrame::Player::GameGold(), goldVal); m_pGameServerNet_ServerModule->SendMsgPBToGate(NFMsg::ACK_EVENT_BUY_CHAMPION, xMsg, clientID); } } bool NFGameServerModule::SetHeroOnInventory(NFGUID self, const string& element, const string& race) { std::shared_ptr ownInventory = m_pKernelModule->FindRecord(self, NFrame::Player::ownInventory::ThisName()); int rows = ownInventory->GetUsedRows(); if (rows >= 9)return false; int groupID = m_pKernelModule->GetPropertyInt32(self, NFrame::Player::GroupID()); NF_SHARE_PTR pSceneInfo = m_pSceneModule->GetElement(3); if (!pSceneInfo) { return false; } string name = element; name += race; NFGUID npcID = m_pKernelModule->CreateGUID(); m_pKernelModule->CreateObject(npcID, 3, groupID, NFrame::NPC::ThisName(), name, NFDataList::Empty()); m_pKernelModule->SetPropertyObject(npcID, NFrame::NPC::MasterID(), self); m_pKernelModule->SetPropertyInt(npcID, NFrame::NPC::State(), 1); double maxHp = m_pKernelModule->GetPropertyFloat(npcID, NFrame::NPC::MAXHP()); m_pKernelModule->SetPropertyFloat(npcID, NFrame::NPC::HP(), maxHp); NFGUID clonedNpcID = m_pKernelModule->CreateGUID(); m_pKernelModule->CreateObject(clonedNpcID, 3, groupID, NFrame::NPC::ThisName(), name, NFDataList::Empty()); m_pKernelModule->SetPropertyInt(clonedNpcID, NFrame::NPC::State(), 0); m_pKernelModule->SetPropertyObject(clonedNpcID, NFrame::NPC::MasterID(), self); m_pKernelModule->SetPropertyFloat(clonedNpcID, NFrame::NPC::HP(), maxHp); m_pKernelModule->SetPropertyObject(npcID, NFrame::NPC::Mirror(), clonedNpcID); NFDataList data; data.Add(npcID); ownInventory->AddRow(-1, data); return true; } void NFGameServerModule::fight(int group, const NF_SHARE_PTR& record) { for (int row = 0; row < 7; row++) { for (int col = 0; col < 8; col++) { NFGUID id = record->GetObjectA(row, col); if (!id.IsNull()) { NFGUID target = m_pKernelModule->GetPropertyObject(id, NFrame::NPC::Target()); if (target.IsNull()) { target = SearchEnemy(id, record); } else { int hpValue = m_pKernelModule->GetPropertyInt(target, NFrame::NPC::HP()); if (hpValue <= 0) { target = SearchEnemy(id, record); } else continue; } m_pKernelModule->SetPropertyObject(id, NFrame::NPC::Target(), target, 0); if (target.IsNull()) m_pSceneModule->SetPropertyInt(3, group, NFrame::Group::PlaneOne(), 1); } } } } NFGUID NFGameServerModule::SearchEnemy(const NFGUID& self, const NF_SHARE_PTR& record) { NFGUID selfMaster = m_pKernelModule->GetPropertyObject(self, NFrame::NPC::MasterID()); for (int row = 0; row < 7; row++) { for (int col = 0; col < 8; col++) { NFGUID id = record->GetObjectA(row, col); if (!id.IsNull()) { NFGUID masterID = m_pKernelModule->GetPropertyObject(id, NFrame::NPC::MasterID()); double hpValue = m_pKernelModule->GetPropertyFloat(id, NFrame::NPC::HP()); if (selfMaster != masterID && hpValue > 0) return id; } } } return NFGUID(0,0); } void NFGameServerModule::RecoverChessState(const NF_SHARE_PTR& record) { NFGUID empty(0, 0); for (int col = 0; col < 7; col++) { for (int row = 0; row < 8; row++) { const NFGUID id = record->GetObjectA(col, row); if (!id.IsNull()) { double maxHp = m_pKernelModule->GetPropertyFloat(id, NFrame::NPC::MAXHP()); m_pKernelModule->SetPropertyFloat(id, NFrame::NPC::HP(), maxHp); m_pKernelModule->SetPropertyInt(id, NFrame::NPC::MP(), 0); m_pKernelModule->SetPropertyObject(id, NFrame::NPC::Target(), empty, 0); const NFGUID clonedNPC = m_pKernelModule->GetPropertyObject(id, NFrame::NPC::Mirror()); m_pKernelModule->SetPropertyFloat(clonedNPC, NFrame::NPC::HP(), maxHp); m_pKernelModule->SetPropertyInt(clonedNPC, NFrame::NPC::MP(), 0); m_pKernelModule->SetPropertyObject(clonedNPC, NFrame::NPC::Target(), empty, 0); } } } } int NFGameServerModule::OnGameStateChange(const NFGUID& self, const std::string& propertyName, const NFData& oldVal, const NFData& newVal) { /*int gameState = newVal.GetInt(); int groupId = m_pKernelModule->GetPropertyInt(self, NFrame::Group::GroupID()); if (gameState == 0) { NFDataList playerList; m_pKernelModule->GetGroupObjectList(3, groupId, playerList, true); for (int i = 0; i < playerList.GetCount(); i++) { const NFGUID& playerId = playerList.Object(i); refreshShopItem(playerId); } NF_SHARE_PTR groupChessPlaneOne = m_pSceneModule->FindRecord(3, groupId, NFrame::Group::ChessPlane1::ThisName()); NFGUID playerOne = m_pSceneModule->GetPropertyObject(3, groupId, NFrame::Group::PlayerOne()); NFGUID playerTwo = m_pSceneModule->GetPropertyObject(3, groupId, NFrame::Group::PlayerTwo()); int countOne = 0, countTwo = 0; for (int col = 0; col < 7; col++) { for (int row = 0; row < 8; row++) { const NFGUID id = groupChessPlaneOne->GetObjectA(col, row); if (!id.IsNull()) { NFGUID masterID = m_pKernelModule->GetPropertyObject(id, NFrame::NPC::MasterID()); double hpValue = m_pKernelModule->GetPropertyFloat(id, NFrame::NPC::HP()); if (masterID == playerOne && hpValue) countOne++; if (masterID == playerTwo && hpValue) countTwo++; } } } int damage = abs(countOne - countTwo); if (!countOne) { int playerHp = m_pKernelModule->GetPropertyInt(playerOne, NFrame::Player::HP()); playerHp -= damage; if (playerHp < 0) playerHp = 0; m_pKernelModule->SetPropertyInt(playerOne, NFrame::Player::HP(), playerHp); } else if(!countTwo) { int playerHp = m_pKernelModule->GetPropertyInt(playerTwo, NFrame::Player::HP()); playerHp -= damage; if (playerHp < 0) playerHp = 0; m_pKernelModule->SetPropertyInt(playerTwo, NFrame::Player::HP(), playerHp); } NF_SHARE_PTR playerOneRecord = m_pKernelModule->FindRecord(playerOne, NFrame::Player::ChessPlane::ThisName()); RecoverChessState(playerOneRecord); NF_SHARE_PTR playerTwoRecord = m_pKernelModule->FindRecord(playerTwo, NFrame::Player::ChessPlane::ThisName()); RecoverChessState(playerTwoRecord); }*/ return 0; } Scr/mp_parse/src/binary_op.cpp0 #include #include #include #include "binary_op.h" #include "plus.h" #include "minus.h" #include "times.h" #include "divide.h" #include "exponent.h" namespace cs225 { binary_op::binary_op(std::unique_ptr left, std::unique_ptr right) : left_{std::move(left)}, right_{std::move(right)} { // nothing to do } double binary_op::value() const { return combine(left_->value(), right_->value()); } std::unique_ptr make_binary_op(const std::string& op, std::unique_ptr left, std::unique_ptr right) { if(op == "+") { return std::unique_ptr{new plus{std::move(left), std::move(right)}}; } else if (op == "-") { return std::unique_ptr{new minus{std::move(left), std::move(right)}}; } else if (op == "*") { return std::unique_ptr{new times{std::move(left), std::move(right)}}; } else if (op == "/") { return std::unique_ptr{new divide{std::move(left), std::move(right)}}; } else if (op == "^") { return std::unique_ptr{new exponent{std::move(left), std::move(right)}}; } else { throw std::runtime_error("operation string does not represent a binary operation"); } } } // 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 "content/child/service_worker/service_worker_provider_context.h" #include "base/bind.h" #include "base/message_loop/message_loop_proxy.h" #include "base/stl_util.h" #include "content/child/child_thread.h" #include "content/child/service_worker/service_worker_dispatcher.h" #include "content/child/service_worker/service_worker_handle_reference.h" #include "content/child/service_worker/service_worker_registration_handle_reference.h" #include "content/child/thread_safe_sender.h" #include "content/child/worker_task_runner.h" #include "content/common/service_worker/service_worker_messages.h" namespace content { ServiceWorkerProviderContext::ServiceWorkerProviderContext(int provider_id) : provider_id_(provider_id), main_thread_loop_proxy_(base::MessageLoopProxy::current()) { if (!ChildThread::current()) return; // May be null in some tests. thread_safe_sender_ = ChildThread::current()->thread_safe_sender(); ServiceWorkerDispatcher* dispatcher = ServiceWorkerDispatcher::GetOrCreateThreadSpecificInstance( thread_safe_sender_.get()); DCHECK(dispatcher); dispatcher->AddProviderContext(this); } ServiceWorkerProviderContext::~ServiceWorkerProviderContext() { if (ServiceWorkerDispatcher* dispatcher = ServiceWorkerDispatcher::GetThreadSpecificInstance()) { dispatcher->RemoveProviderContext(this); } } ServiceWorkerHandleReference* ServiceWorkerProviderContext::installing() { DCHECK(main_thread_loop_proxy_->RunsTasksOnCurrentThread()); return installing_.get(); } ServiceWorkerHandleReference* ServiceWorkerProviderContext::waiting() { DCHECK(main_thread_loop_proxy_->RunsTasksOnCurrentThread()); return waiting_.get(); } ServiceWorkerHandleReference* ServiceWorkerProviderContext::active() { DCHECK(main_thread_loop_proxy_->RunsTasksOnCurrentThread()); return active_.get(); } ServiceWorkerHandleReference* ServiceWorkerProviderContext::controller() { DCHECK(main_thread_loop_proxy_->RunsTasksOnCurrentThread()); return controller_.get(); } ServiceWorkerRegistrationHandleReference* ServiceWorkerProviderContext::registration() { DCHECK(main_thread_loop_proxy_->RunsTasksOnCurrentThread()); return registration_.get(); } ServiceWorkerVersionAttributes ServiceWorkerProviderContext::GetVersionAttributes() { ServiceWorkerVersionAttributes attrs; if (installing()) attrs.installing = installing()->info(); if (waiting()) attrs.waiting = waiting()->info(); if (active()) attrs.active = active()->info(); return attrs; } void ServiceWorkerProviderContext::OnAssociateRegistration( const ServiceWorkerRegistrationObjectInfo& info, const ServiceWorkerVersionAttributes& attrs) { DCHECK(!registration_); DCHECK_NE(kInvalidServiceWorkerRegistrationHandleId, info.handle_id); registration_ = ServiceWorkerRegistrationHandleReference::Adopt( info, thread_safe_sender_.get()); installing_ = ServiceWorkerHandleReference::Adopt( attrs.installing, thread_safe_sender_.get()); waiting_ = ServiceWorkerHandleReference::Adopt( attrs.waiting, thread_safe_sender_.get()); active_ = ServiceWorkerHandleReference::Adopt( attrs.active, thread_safe_sender_.get()); } void ServiceWorkerProviderContext::OnDisassociateRegistration() { controller_.reset(); active_.reset(); waiting_.reset(); installing_.reset(); registration_.reset(); } void ServiceWorkerProviderContext::OnServiceWorkerStateChanged( int handle_id, blink::WebServiceWorkerState state) { ServiceWorkerHandleReference* which = NULL; if (handle_id == controller_handle_id()) which = controller_.get(); else if (handle_id == active_handle_id()) which = active_.get(); else if (handle_id == waiting_handle_id()) which = waiting_.get(); else if (handle_id == installing_handle_id()) which = installing_.get(); // We should only get messages for ServiceWorkers associated with // this provider. DCHECK(which); which->set_state(state); // TODO(kinuko): We can forward the message to other threads here // when we support navigator.serviceWorker in dedicated workers. } void ServiceWorkerProviderContext::OnSetInstallingServiceWorker( int registration_handle_id, const ServiceWorkerObjectInfo& info) { DCHECK(IsAssociatedWithRegistration(registration_handle_id)); installing_ = ServiceWorkerHandleReference::Adopt(info, thread_safe_sender_.get()); } void ServiceWorkerProviderContext::OnSetWaitingServiceWorker( int registration_handle_id, const ServiceWorkerObjectInfo& info) { DCHECK(IsAssociatedWithRegistration(registration_handle_id)); waiting_ = ServiceWorkerHandleReference::Adopt(info, thread_safe_sender_.get()); } void ServiceWorkerProviderContext::OnSetActiveServiceWorker( int registration_handle_id, const ServiceWorkerObjectInfo& info) { DCHECK(IsAssociatedWithRegistration(registration_handle_id)); active_ = ServiceWorkerHandleReference::Adopt(info, thread_safe_sender_.get()); } void ServiceWorkerProviderContext::OnSetControllerServiceWorker( int registration_handle_id, const ServiceWorkerObjectInfo& info) { DCHECK(IsAssociatedWithRegistration(registration_handle_id)); // This context is is the primary owner of this handle, keeps the // initial reference until it goes away. controller_ = ServiceWorkerHandleReference::Adopt(info, thread_safe_sender_.get()); // TODO(kinuko): We can forward the message to other threads here // when we support navigator.serviceWorker in dedicated workers. } int ServiceWorkerProviderContext::installing_handle_id() const { DCHECK(main_thread_loop_proxy_->RunsTasksOnCurrentThread()); return installing_ ? installing_->info().handle_id : kInvalidServiceWorkerHandleId; } int ServiceWorkerProviderContext::waiting_handle_id() const { DCHECK(main_thread_loop_proxy_->RunsTasksOnCurrentThread()); return waiting_ ? waiting_->info().handle_id : kInvalidServiceWorkerHandleId; } int ServiceWorkerProviderContext::active_handle_id() const { DCHECK(main_thread_loop_proxy_->RunsTasksOnCurrentThread()); return active_ ? active_->info().handle_id : kInvalidServiceWorkerHandleId; } int ServiceWorkerProviderContext::controller_handle_id() const { DCHECK(main_thread_loop_proxy_->RunsTasksOnCurrentThread()); return controller_ ? controller_->info().handle_id : kInvalidServiceWorkerHandleId; } int ServiceWorkerProviderContext::registration_handle_id() const { DCHECK(main_thread_loop_proxy_->RunsTasksOnCurrentThread()); return registration_ ? registration_->info().handle_id : kInvalidServiceWorkerRegistrationHandleId; } bool ServiceWorkerProviderContext::IsAssociatedWithRegistration( int registration_handle_id) const { if (!registration_) return false; if (registration_handle_id == kInvalidServiceWorkerRegistrationHandleId) return false; return registration_->info().handle_id == registration_handle_id; } } // namespace content #include #include #include #include "list.h" void StudentList::load() { std::ifstream fin("ContactEmail.txt"); std::string id, email; while (fin >> id >> email) { this->list.push_back(id + " " + email); } fin.close(); } include/ebiten_frame/native_frame.hpp #ifndef EBITEN_FRAME_NATIVE_FRAME_HPP #define EBITEN_FRAME_NATIVE_FRAME_HPP #include "ebiten/platform.hpp" #ifdef EBITEN_MACOSX #include "ebiten_frame/detail/macosx/native_frame.hpp" #endif namespace ebiten_frame { typedef detail::native_frame native_frame; } #endif 1-10 // 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 "pdf/ppapi_migration/value_conversions.h" #include #include "base/containers/span.h" #include "base/notreached.h" #include "base/values.h" #include "ppapi/cpp/var.h" #include "ppapi/cpp/var_array.h" #include "ppapi/cpp/var_array_buffer.h" #include "ppapi/cpp/var_dictionary.h" namespace chrome_pdf { pp::Var VarFromValue(const base::Value& value) { switch (value.type()) { case base::Value::Type::NONE: return pp::Var::Null(); case base::Value::Type::BOOLEAN: return pp::Var(value.GetBool()); case base::Value::Type::INTEGER: return pp::Var(value.GetInt()); case base::Value::Type::DOUBLE: return pp::Var(value.GetDouble()); case base::Value::Type::STRING: return pp::Var(value.GetString()); case base::Value::Type::BINARY: { const base::Value::BlobStorage& blob = value.GetBlob(); pp::VarArrayBuffer buffer(blob.size()); std::copy(blob.begin(), blob.end(), static_cast(buffer.Map())); return buffer; } case base::Value::Type::DICTIONARY: { pp::VarDictionary var_dict; for (const auto& value_pair : value.DictItems()) { var_dict.Set(value_pair.first, VarFromValue(value_pair.second)); } return var_dict; } case base::Value::Type::LIST: { pp::VarArray var_array; uint32_t i = 0; for (const auto& val : value.GetList()) { var_array.Set(i, VarFromValue(val)); i++; } return var_array; } } } base::Value ValueFromVar(const pp::Var& var) { switch (var.pp_var().type) { case PP_VARTYPE_UNDEFINED: return base::Value(); case PP_VARTYPE_NULL: return base::Value(); case PP_VARTYPE_BOOL: return base::Value(var.AsBool()); case PP_VARTYPE_INT32: return base::Value(var.AsInt()); case PP_VARTYPE_DOUBLE: return base::Value(var.AsDouble()); case PP_VARTYPE_STRING: return base::Value(var.AsString()); case PP_VARTYPE_OBJECT: // There is no valid conversion from PP_VARTYPE_OBJECT to a base::Value // type. This should not be called to convert this type. NOTREACHED(); return base::Value(); case PP_VARTYPE_ARRAY: { pp::VarArray var_array(var); base::Value::ListStorage list_storage(var_array.GetLength()); for (uint32_t i = 0; i < var_array.GetLength(); ++i) { list_storage[i] = ValueFromVar(var_array.Get(i)); } return base::Value(std::move(list_storage)); } case PP_VARTYPE_DICTIONARY: { base::Value val_dictionary(base::Value::Type::DICTIONARY); pp::VarDictionary var_dict(var); pp::VarArray dict_keys = var_dict.GetKeys(); for (uint32_t i = 0; i < dict_keys.GetLength(); ++i) { pp::Var key = dict_keys.Get(i); val_dictionary.SetKey(key.AsString(), ValueFromVar(var_dict.Get(key))); } return val_dictionary; } case PP_VARTYPE_ARRAY_BUFFER: { pp::VarArrayBuffer var_array_buffer(var); base::Value value( base::make_span(static_cast(var_array_buffer.Map()), var_array_buffer.ByteLength())); var_array_buffer.Unmap(); return value; } case PP_VARTYPE_RESOURCE: // There is no valid conversion from PP_VARTYPE_RESOURCE to a base::Value // type. This should not be called to convert this type. NOTREACHED(); return base::Value(); } } } // namespace chrome_pdf components/libm8r/Task.cpp /*------------------------------------------------------------------------- This source file is a part of m8rscript For the latest info, see http:www.marrin.org/ Copyright (c) 2018-2019, All rights reserved. Use of this source code is governed by the MIT license that can be found in the LICENSE file. -------------------------------------------------------------------------*/ #include "Defines.h" #include "Task.h" #include "FileStream.h" #include "ScriptingLanguage.h" #include "SystemInterface.h" #include using namespace m8r; void Task::print(const char* s) const { if (_executable) { _executable->print(s); } else { system()->print(s); } } Task::~Task() { } bool Task::load(const char* filename) { Vector parts = String(filename).split("."); if (parts.size() < 2) { // Try appending known suffixes String baseFilename = filename; system()->printf("***** Missing suffix for '%s'\n\n", filename); return false; } Error error(Error::Code::NoFS); Mad file; if (system()->fileSystem()) { file = system()->fileSystem()->open(filename, FS::FileOpenMode::Read); error = file->error(); } if (error) { print(Error::formatError(error.code(), "Unable to open '%s' for execution", filename).c_str()); _error = error; return false; } bool ret = load(FileStream(file), parts.back()); if (file->error() != Error::Code::OK) { print(Error::formatError(file->error().code(), "Error reading '%s'", filename).c_str()); } file.destroy(MemoryType::Native); return ret; } bool Task::load(const Stream& stream, const String& type) { #ifndef NDEBUG _name = String::format("Task(%p)", this); #endif for (uint32_t i = 0; ; ++i) { const ScriptingLanguage* lang = system()->scriptingLanguage(i); if (!lang) { break; } if (String(lang->suffix()) == type) { _executable = lang->create(); _executable->load(stream); // FIXME: Check for errors const ParseErrorList* errors = _executable->parseErrors(); if (errors && errors->size() > 0) { _executable->print("\n"); for (const auto& it : *errors) { _executable->print(it.format().c_str()); } _executable->print(String::format("%d parse error%s\n\n", errors->size(), (errors->size() == 1) ? "" : "s").c_str()); return false; } return true; } } system()->printf("***** Unknown suffix '%s'.\n\n", type.c_str()); return false; } /********** This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. (See .) 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 **********/ // Copyright (c) 1996-2011, Live Networks, Inc. All rights reserved // A test program that reads a MPEG-4 Video Elementary Stream file, // and streams both using RTP, through a remote Darwin Streaming Server. // main program ////////// NOTE ////////// // This demo software is provided only as a courtesy to those developers who - for whatever reason - wish // to send outgoing streams through a separate Darwin Streaming Server. However, it is not necessary to use // a Darwin Streaming Server in order to serve streams using RTP/RTSP. Instead, the "LIVE555 Streaming Media" // software includes its own RTSP/RTP server implementation, which you should use instead. For tips on using // our RTSP/RTP server implementation, see the "testOnDemandRTSPServer" demo application, and/or the // "live555MediaServer" application (in the "mediaServer") directory. ////////////////////////// #include "liveMedia.hh" #include "BasicUsageEnvironment.hh" UsageEnvironment* env; char const* inputFileName = "test.m4e"; char const* remoteStreamName = "test.sdp"; // the stream name, as served by the DSS MPEG4VideoStreamFramer* videoSource; RTPSink* videoSink; char const* programName; void usage() { *env << "usage: " << programName << " \n"; exit(1); } Boolean awaitConfigInfo(RTPSink* sink); // forward void play(); // forward int main(int argc, char** argv) { // Begin by setting up our usage environment: TaskScheduler* scheduler = BasicTaskScheduler::createNew(); env = BasicUsageEnvironment::createNew(*scheduler); // Parse command-line arguments: programName = argv[0]; if (argc != 2) usage(); char const* dssNameOrAddress = argv[1]; // Create a 'Darwin injector' object: DarwinInjector* injector = DarwinInjector::createNew(*env, programName); // Create 'groupsocks' for RTP and RTCP. // (Note: Because we will actually be streaming through a remote Darwin server, // via TCP, we just use dummy destination addresses, port numbers, and TTLs here.) struct in_addr dummyDestAddress; dummyDestAddress.s_addr = 0; Groupsock rtpGroupsockVideo(*env, dummyDestAddress, 0, 0); Groupsock rtcpGroupsockVideo(*env, dummyDestAddress, 0, 0); // Create a 'MPEG-4 Video RTP' sink from the RTP 'groupsock': videoSink = MPEG4ESVideoRTPSink::createNew(*env, &rtpGroupsockVideo, 96); // HACK, specifically for MPEG-4 video: // Before we can use this RTP sink, we need its MPEG-4 'config' information (for // use in the SDP description). Unfortunately, this config information depends // on the the properties of the MPEG-4 input data. Therefore, we need to start // 'playing' this RTP sink from the input source now, and wait until we get // the needed config information, before continuing: // that we need: *env << "Beginning streaming...\n"; play(); if (!awaitConfigInfo(videoSink)) { *env << "Failed to get MPEG-4 'config' information from input file: " << env->getResultMsg() << "\n"; exit(1); } // Create (and start) a 'RTCP instance' for this RTP sink: const unsigned estimatedSessionBandwidthVideo = 500; // in kbps; for RTCP b/w share const unsigned maxCNAMElen = 100; unsigned char CNAME[maxCNAMElen+1]; gethostname((char*)CNAME, maxCNAMElen); CNAME[maxCNAMElen] = '\0'; // just in case RTCPInstance* videoRTCP = RTCPInstance::createNew(*env, &rtcpGroupsockVideo, estimatedSessionBandwidthVideo, CNAME, videoSink, NULL /* we're a server */); // Note: This starts RTCP running automatically // Add these to our 'Darwin injector': injector->addStream(videoSink, videoRTCP); // Next, specify the destination Darwin Streaming Server: if (!injector->setDestination(dssNameOrAddress, remoteStreamName, programName, "LIVE555 Streaming Media")) { *env << "injector->setDestination() failed: " << env->getResultMsg() << "\n"; exit(1); } *env << "Play this stream (from the Darwin Streaming Server) using the URL:\n" << "\trtsp://" << dssNameOrAddress << "/" << remoteStreamName << "\n"; env->taskScheduler().doEventLoop(); // does not return return 0; // only to prevent compiler warning } void afterPlaying(void* clientData) { *env << "...done reading from file\n"; Medium::close(videoSource); // Note: This also closes the input file that this source read from. // Start playing once again: play(); } void play() { // Open the input file as a 'byte-stream file source': ByteStreamFileSource* fileSource = ByteStreamFileSource::createNew(*env, inputFileName); if (fileSource == NULL) { *env << "Unable to open file \"" << inputFileName << "\" as a byte-stream file source\n"; exit(1); } FramedSource* videoES = fileSource; // Create a framer for the Video Elementary Stream: FramedSource* videoSource = MPEG4VideoStreamFramer::createNew(*env, videoES); // Finally, start playing: *env << "Beginning to read from file...\n"; videoSink->startPlaying(*videoSource, afterPlaying, videoSink); } static char doneFlag = 0; static void checkForAuxSDPLine(void* clientData) { RTPSink* sink = (RTPSink*)clientData; if (sink->auxSDPLine() != NULL) { // Signal the event loop that we're done: doneFlag = ~0; } else { // No luck yet. Try again, after a brief delay: int uSecsToDelay = 100000; // 100 ms env->taskScheduler().scheduleDelayedTask(uSecsToDelay, (TaskFunc*)checkForAuxSDPLine, sink); } } Boolean awaitConfigInfo(RTPSink* sink) { // Check whether the sink's 'auxSDPLine()' is ready: checkForAuxSDPLine(sink); env->taskScheduler().doEventLoop(&doneFlag); char const* auxSDPLine = sink->auxSDPLine(); return auxSDPLine != NULL; } HANS-2002/Jab-sab-aapki-le-rahe-ho-tab-aap-bhi-kuch-leloOOP Lab/Lab7/LE/LE7_9.cpp // Write a program to create a class player having data members as player number, name, score. // Now enter details of player by overloading extraction operator (>>) and display all the details // by overloading insertion operator (<<). #include using namespace std; class player { int pno, score; string name; public: player(int a, int b, string s) { pno = a; score = b; name = s; } friend ostream &operator<<(ostream &out, const player &p); friend istream &operator>>(istream &in, player &p); }; ostream & operator << (ostream &out, const player &c) { out<<"Player number: "<> (istream &in, player &c) { cout<<"Player number: "; in>>c.pno; cout<<"Player name: "; in>>c.name; cout<<"Player score: "; in>>c.score; return in; } int main() { player p(1,120,"Virat"); cin>>p; cout<<"Player details: \n"; cout< on 5/3/12. // Copyright (c) 2012 __MyCompanyName__. All rights reserved. // #include "cinder/app/AppBasic.h" #include "cinder/gl/gl.h" #include "cinder/Rand.h" #include "Controller.h" using namespace ci; using std::vector; using std::list; Controller::Controller() { } void Controller::init( Room *room ) { mRoom = room; mPerlin = Perlin( 4 ); mTimeSinceBang = 0.0f; createSphere( mBalloonsVbo, 3 ); mPresetIndex = 1; } void Controller::createSphere( gl::VboMesh &vbo, int res ) { float X = 0.525731112119f; float Z = 0.850650808352f; static Vec3f verts[12] = { Vec3f( -X, 0.0f, Z ), Vec3f( X, 0.0f, Z ), Vec3f( -X, 0.0f, -Z ), Vec3f( X, 0.0f, -Z ), Vec3f( 0.0f, Z, X ), Vec3f( 0.0f, Z, -X ), Vec3f( 0.0f, -Z, X ), Vec3f( 0.0f, -Z, -X ), Vec3f( Z, X, 0.0f ), Vec3f( -Z, X, 0.0f ), Vec3f( Z, -X, 0.0f ), Vec3f( -Z, -X, 0.0f ) }; static GLuint triIndices[20][3] = { {0,4,1}, {0,9,4}, {9,5,4}, {4,5,8}, {4,8,1}, {8,10,1}, {8,3,10}, {5,3,8}, {5,2,3}, {2,7,3}, {7,10,3}, {7,6,10}, {7,11,6}, {11,0,6}, {0,1,6}, {6,1,10}, {9,0,11}, {9,11,2}, {9,2,5}, {7,2,11} }; gl::VboMesh::Layout layout; layout.setStaticPositions(); layout.setStaticNormals(); mPosCoords.clear(); mNormals.clear(); for( int i=0; i<20; i++ ){ drawSphereTri( verts[triIndices[i][0]], verts[triIndices[i][1]], verts[triIndices[i][2]], res ); } float z = 0.0f; float s = 0.05f; float y1 = -0.975f; float y2 = -1.1f; Vec3f v0 = Vec3f( z, y1, z ); Vec3f v1 = Vec3f( s, y2, s ); Vec3f v2 = Vec3f(-s, y2, s ); Vec3f v3 = Vec3f(-s, y2,-s ); Vec3f v4 = Vec3f( s, y2,-s ); mPosCoords.push_back( v1 ); // back mPosCoords.push_back( v2 ); mPosCoords.push_back( v0 ); mPosCoords.push_back( v4 ); // right mPosCoords.push_back( v1 ); mPosCoords.push_back( v0 ); mPosCoords.push_back( v3 ); // front mPosCoords.push_back( v4 ); mPosCoords.push_back( v0 ); mPosCoords.push_back( v2 ); // left mPosCoords.push_back( v3 ); mPosCoords.push_back( v0 ); mPosCoords.push_back( v1 ); // bottom mPosCoords.push_back( v2 ); mPosCoords.push_back( v3 ); mPosCoords.push_back( v1 ); // bottom mPosCoords.push_back( v3 ); mPosCoords.push_back( v4 ); mNormals.push_back( Vec3f::zAxis() ); // back mNormals.push_back( Vec3f::zAxis() ); mNormals.push_back( Vec3f::zAxis() ); mNormals.push_back( Vec3f::xAxis() ); // right mNormals.push_back( Vec3f::xAxis() ); mNormals.push_back( Vec3f::xAxis() ); mNormals.push_back(-Vec3f::zAxis() ); // front mNormals.push_back(-Vec3f::zAxis() ); mNormals.push_back(-Vec3f::zAxis() ); mNormals.push_back( Vec3f::xAxis() ); // left mNormals.push_back( Vec3f::xAxis() ); mNormals.push_back( Vec3f::xAxis() ); mNormals.push_back( Vec3f::yAxis() ); // bottom mNormals.push_back( Vec3f::yAxis() ); mNormals.push_back( Vec3f::yAxis() ); mNormals.push_back( Vec3f::yAxis() ); // bottom mNormals.push_back( Vec3f::yAxis() ); mNormals.push_back( Vec3f::yAxis() ); vbo = gl::VboMesh( mPosCoords.size(), 0, layout, GL_TRIANGLES ); vbo.bufferPositions( mPosCoords ); vbo.bufferNormals( mNormals ); } void Controller::modVert( Vec3f *v ) { float yPer = 1.0f; yPer = pow( v->y * 0.5f + 0.5f, 0.3f ); v->x *= 0.9f * yPer; v->z *= 0.9f * yPer; } void Controller::drawSphereTri( Vec3f va, Vec3f vb, Vec3f vc, int div ) { // TURNS THE SPHERE INTO A BALLOON // BUT ULTIMATELY MESSES UP THE NORMALS if( div <= 0 ){ modVert( &va ); modVert( &vb ); modVert( &vc ); mPosCoords.push_back( va ); mPosCoords.push_back( vb ); mPosCoords.push_back( vc ); Vec3f vn = ( va + vb + vc ) * 0.3333f; mNormals.push_back( va.normalized() ); mNormals.push_back( vb.normalized() ); mNormals.push_back( vc.normalized() ); } else { Vec3f vab = ( ( va + vb ) * 0.5f ).normalized(); Vec3f vac = ( ( va + vc ) * 0.5f ).normalized(); Vec3f vbc = ( ( vb + vc ) * 0.5f ).normalized(); drawSphereTri( va, vab, vac, div-1 ); drawSphereTri( vb, vbc, vab, div-1 ); drawSphereTri( vc, vac, vbc, div-1 ); drawSphereTri( vab, vbc, vac, div-1 ); } } void Controller::bang() { int numConfettis = 2000; int numStreamers = 250; int numBalloons = 1; if( mPresetIndex == 4 ){ numBalloons = 500; } addConfettis( numConfettis, Vec3f::zero(), 1.0f ); addStreamers( numStreamers, Vec3f::zero() ); addBalloons( numBalloons, Vec3f::zero() ); // PLAY A BIG BANG SOUND HERE mTimeSinceBang = 0.0f; } void Controller::checkForBalloonPop( const Vec2f &mousePos ) { for( vector::reverse_iterator it = mBalloons.rbegin(); it != mBalloons.rend(); ++it ){ Vec2f dir = mousePos - it->mScreenPos; float distSqrd = dir.lengthSquared(); if( distSqrd < 1000.0f ){ Vec3f pos = it->mPos; float lifespan = 12.0f; float speed = 20.0f; mShockwaves.push_back( Shockwave( it->mPos, Vec3f::yAxis(), lifespan, speed ) ); int numConfettis = 250; addConfettis( numConfettis, pos, 0.5f ); // PLAY A BALLOON POP AUDIO FILE HERE it->mIsDead = true; break; } } } void Controller::update( const Camera &cam ) { float dt = mRoom->getTimeDelta(); mTimeSinceBang += dt; if( mTimeSinceBang > 10.0f ) applyBalloonCollisions(); // SHOCKWAVES for( vector::iterator it = mShockwaves.begin(); it != mShockwaves.end(); ){ if( it->mIsDead ){ it = mShockwaves.erase( it ); } else { it->update( dt ); ++it; } } // CONFETTIS for( vector::iterator it = mConfettis.begin(); it != mConfettis.end(); ){ if( it->mIsDead ){ it = mConfettis.erase( it ); } else { it->update( mRoom->getDims(), dt ); ++it; } } // STREAMERS for( vector::iterator it = mStreamers.begin(); it != mStreamers.end(); ){ if( it->mIsDead ){ it = mStreamers.erase( it ); } else { it->update( mRoom->getDims(), dt, mRoom->getTick() ); ++it; } } // BALLOONS for( vector::iterator it = mBalloons.begin(); it != mBalloons.end(); ){ if( it->mIsDead ){ it = mBalloons.erase( it ); } else { it->update( cam, mRoom->getDims(), dt ); ++it; } } // SORT BALLOONS sort( mBalloons.begin(), mBalloons.end(), depthSortFunc ); } void Controller::applyBalloonCollisions() { for( vector::iterator it1 = mBalloons.begin(); it1 != mBalloons.end(); ++it1 ) { // APPLY SHOCKWAVES TO BALLOONS for( vector::iterator shockIt = mShockwaves.begin(); shockIt != mShockwaves.end(); ++shockIt ) { Vec3f dirToParticle = shockIt->mPos - it1->mPos; float dist = dirToParticle.length(); if( dist > shockIt->mRadiusPrev && dist < shockIt->mRadius ){ Vec3f dirToParticleNorm = dirToParticle.normalized(); it1->mAcc -= dirToParticleNorm * shockIt->mImpulse * 2.5f; } } vector::iterator it2 = it1; for( std::advance( it2, 1 ); it2 != mBalloons.end(); ++it2 ) { Vec3f dir = it1->mPos - it2->mPos; Vec3f dirNormal = dir.normalized(); float dist = dir.length(); Vec3f moveVec = it2->mVel - it1->mVel; float sumRadii = ( it1->mRadius * 0.7f + it2->mRadius * 0.7f ); float sumRadiiSqrd = sumRadii * sumRadii; bool collision = didParticlesCollide( dir, dirNormal, dist, sumRadii, sumRadiiSqrd, &moveVec ); if( collision ) { float a1 = it1->mVel.dot( dirNormal ); float a2 = it2->mVel.dot( dirNormal ); float pVar = ( 2.0f * ( a1 - a2 ) ); dist -= sumRadii; if( dist < 0.0f ){ Vec3f off = dirNormal * dist; it1->mPos -= off * 0.25f; it1->mVel -= off * 0.125f; it2->mPos += off * 0.25f; it2->mVel += off * 0.125f; } float collisionDecay = 0.375f; Vec3f newDir = pVar * dirNormal * collisionDecay; it1->mVel -= newDir; it2->mVel += newDir; } } } } bool Controller::didParticlesCollide( const ci::Vec3f &dir, const ci::Vec3f &dirNormal, const float dist, const float sumRadii, const float sumRadiiSqrd, ci::Vec3f *moveVec ) { float moveVecLength = sqrtf( moveVec->x * moveVec->x + moveVec->y * moveVec->y + moveVec->z * moveVec->z ); float newDist = dist - sumRadii; if( newDist < 0 ) return true; if( moveVecLength < dist ) return false; moveVec->normalize(); float D = moveVec->dot(dir); if( D <= 0 ) return false; float F = ( newDist * newDist ) - ( D * D ); if( F >= sumRadiiSqrd ) return false; float T = sumRadiiSqrd - F; if( T < 0 ) return false; float distance = D - sqrtf(T); if( moveVecLength < distance ) return false; *moveVec *= distance; // moveVec->set( moveVec * distance ); // moveVec->set( moveVec->normalized() * distance ); return true; } void Controller::draw() { } void Controller::drawConfettis( gl::GlslProg *shader ) { for( vector::iterator it = mConfettis.begin(); it != mConfettis.end(); ++it ){ shader->uniform( "color", it->mColor ); shader->uniform( "matrix", it->mMatrix ); it->draw(); } } void Controller::drawStreamers() { for( vector::iterator it = mStreamers.begin(); it != mStreamers.end(); ++it ){ gl::color( it->mColor ); it->draw(); } } void Controller::drawBalloons( gl::GlslProg *shader ) { for( vector::iterator it = mBalloons.begin(); it != mBalloons.end(); ++it ){ shader->uniform( "matrix", it->mMatrix ); shader->uniform( "color", it->mColor ); gl::draw( mBalloonsVbo ); } } void Controller::drawPhysics() { gl::color( Color( 1.0f, 0.0f, 0.0f ) ); for( vector::iterator it = mBalloons.begin(); it != mBalloons.end(); ++it ){ gl::drawCube( it->mPos, Vec3f( it->mRadius, it->mRadius, it->mRadius ) * 0.2f ); gl::drawCube( it->mSpringPos, Vec3f( it->mRadius, it->mRadius, it->mRadius ) * 0.1f ); gl::drawLine( it->mPos, it->mSpringPos ); } gl::color( Color( 0.0f, 1.0f, 0.0f ) ); for( vector::iterator it = mConfettis.begin(); it != mConfettis.end(); ++it ){ gl::drawCube( it->mPos, Vec3f( 2.0f, 2.0f, 2.0f ) ); } gl::color( Color( 0.0f, 0.0f, 1.0f ) ); for( vector::iterator it = mStreamers.begin(); it != mStreamers.end(); ++it ){ gl::drawCube( it->mPos, Vec3f( 4.0f, 4.0f, 4.0f ) ); it->draw(); } } void Controller::addConfettis( int amt, const Vec3f &pos, float speedMulti ) { for( int i=0; i b.mPos.z; } /************************************************************** * * 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. * *************************************************************/ #ifndef _XMLOFF_ATTRLIST_HXX #define _XMLOFF_ATTRLIST_HXX #include "sal/config.h" #include "xmloff/dllapi.h" #include #include #include #include #include #include #include #include #include /** Implementation of the XML attribute list. * * It is based on std::vector. */ struct SvXMLAttributeList_Impl; /** Container for XML tag attributes. */ class XMLOFF_DLLPUBLIC SvXMLAttributeList : public ::cppu::WeakImplHelper3< ::com::sun::star::xml::sax::XAttributeList, ::com::sun::star::util::XCloneable, ::com::sun::star::lang::XUnoTunnel> { SvXMLAttributeList_Impl *m_pImpl; public: SvXMLAttributeList(); SvXMLAttributeList( const SvXMLAttributeList& ); SvXMLAttributeList( const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList> & rAttrList ); ~SvXMLAttributeList(); static const ::com::sun::star::uno::Sequence< sal_Int8 > & getUnoTunnelId() throw(); static SvXMLAttributeList* getImplementation( ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > ) throw(); // XUnoTunnel virtual sal_Int64 SAL_CALL getSomething( const ::com::sun::star::uno::Sequence< sal_Int8 >& aIdentifier ) throw(::com::sun::star::uno::RuntimeException); /** Return the number of attributes. * * Required by ::com::sun::star::xml::sax::XAttributeList */ virtual sal_Int16 SAL_CALL getLength(void) throw( ::com::sun::star::uno::RuntimeException ); /** Return the name of the i-th attribute. * * @param i index starting from zero. * * @return the name of the i-th attribute, or empty string if i is * not a valid index. */ virtual ::rtl::OUString SAL_CALL getNameByIndex(sal_Int16 i) throw( ::com::sun::star::uno::RuntimeException ); /** Returns the type of the i-th attribute. * * @param i index starting from zero. * * @return CDATA for any value of i. */ virtual ::rtl::OUString SAL_CALL getTypeByIndex(sal_Int16 i) throw( ::com::sun::star::uno::RuntimeException ); /** Returns the type of an attribute. * * @param aName name of the attribute to look for. * * @return CDATA for any value of aName. */ virtual ::rtl::OUString SAL_CALL getTypeByName(const ::rtl::OUString& aName) throw( ::com::sun::star::uno::RuntimeException ); /** Return the value of the i-th attribute. * * @param i index starting from zero. * * @return the value of the i-th attribute, or empty string if i is * not a valid index. */ virtual ::rtl::OUString SAL_CALL getValueByIndex(sal_Int16 i) throw( ::com::sun::star::uno::RuntimeException ); /** Return the value of an attribute. * * @param aName name of the attribute to look for. * * @return the value of the attribute named aName, or empty string * if no attributes are named aName. */ virtual ::rtl::OUString SAL_CALL getValueByName(const ::rtl::OUString& aName) throw( ::com::sun::star::uno::RuntimeException ); /** Make a clone of this object. * * Required by ::com::sun::star::util::XCloneable * * @return a clone of the current object. */ virtual ::com::sun::star::uno::Reference< ::com::sun::star::util::XCloneable > SAL_CALL createClone() throw( ::com::sun::star::uno::RuntimeException ); // methods that are not contained in any interface /** Add an attribute. * * @param sName name of the attribute. * @param sValue value of the attribute. * * @exception com::sun::star::uno::RuntimeException thrown if the * attribute already exists. */ void AddAttribute( const ::rtl::OUString &sName , const ::rtl::OUString &sValue ); /** Clear the attributes list. */ void Clear(); /** Remove an attribute from the list. * * @param sName name of the attribute to remove. * * If no attribute named sName is found, this method does not do anything. */ void RemoveAttribute( const ::rtl::OUString sName ); /** Reset the attributes list. * * @param r list to read the attributes from. * * The internal list is cleared and reset from r. */ void SetAttributeList( const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList > &r ); /** Add attributes. * * @param r attributes to add. * * @exception com::sun::star::uno::RuntimeException thrown if any * of the attributes in r already exists. Previous attributes may * have been added. */ void AppendAttributeList( const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList > &r ); /** Set the value of the i-th attribute. * * @param i index starting from zero. * @param rValue value to set. * * If i is out of range, this method does nothing. */ void SetValueByIndex( sal_Int16 i, const ::rtl::OUString& rValue ); /** Remove the i-th attribute. * * @param i index starting from zero. * * If i is out of range, this method does nothing. */ void RemoveAttributeByIndex( sal_Int16 i ); /** Rename the i-th attribute. * * @param i index starting from zero. * @param rNewName new name to set. * * If i is out of range, this method does nothing. */ void RenameAttributeByIndex( sal_Int16 i, const ::rtl::OUString& rNewName ); /** Find an attribute from its name. * * @param rName attribute name to look for. * * @return the index of attribute named rName (starting from * zero), or -1 if no attributes were found. */ sal_Int16 GetIndexByName( const ::rtl::OUString& rName ) const; private: /** "CDATA" string */ const ::rtl::OUString sType; }; #endif // _XMLOFF_ATTRLIST_HXX #include "Animations.hpp" /** * @brief Ambiently glow with a soft white * */ void Animations::Standby::solidSoftWhite(void) { for (uint8_t z = zone_t::RIGHT; z <= zone_t::TOP; z++) { for (uint16_t y = 0; y < lcm->zoneHeight((zone_t) z); y++) { for (uint16_t x = 0; x < lcm->zoneWidth((zone_t) z); x++) { lcm->setPixelColorByZone((zone_t) z, x, y, COLOR_DIM_OFF_WHITE); Serial.print(x); Serial.print(", "); Serial.println(y); } } } lcm->show(); } void Animations::Standby::whiteWave(void) { } void Animations::Standby::cloudToCloudLighting(void) { } void Animations::Standby::rainbowWash(void) { } void Animations::Standby::rainbowFade(void) { } dyarob/ubiquitous-turtle0 #ifndef GAME_CLASS_HPP # define GAME_CLASS_HPP #include "CONST.h" #include "Player.class.hpp" #include "EnemyBase.class.hpp" #include "BlockBase.class.hpp" #include "AsteroidField.class.hpp" #include "Level.class.hpp" #include "Spawner.class.hpp" #include "WinUI_screen.class.hpp" #include "WinUI_dialogBox.class.hpp" #include #include "objlist.class.hpp" #include #include #include #include #include #include class Game { private: //bool sigwinchReceived; int lvlId; std::vector lvls; objlist objects; Player *player; Spawner spawner; WinUI_dialogBox *topBox; WinUI_dialogBox *bottBox; WinUI_screen *gameScreen; void lvlInit(); void keyEvent(Player *player, std::list &l); void updatePositions(objlist &units, int const currFrame); void exitGame(void); public: ~Game(); Game(); void update(int const currFrame); }; #endif //!GAME_CLASS_HPP jodavis42/PhysicsSandbox #pragma once #include "SandboxGeometryStandard.hpp" #include "SandboxGeometry/Intersection2d/RayIntersectionPoint2d.hpp" namespace SandboxGeometry { //-------------------------------------------------------------------RayResult2d class RayResult2d { public: RayIntersectionPoint2d& GetPoint(size_t index); const RayIntersectionPoint2d& GetPoint(size_t index) const; RayIntersectionPoint2d& operator[](size_t index); const RayIntersectionPoint2d& operator[](size_t index) const; size_t Size() const; void TransformPoints(const Matrix2& rotation, const Vector2& translation); char mPointCount = 0; RayIntersectionPoint2d mPoints[2]{}; }; }//namespace SandboxGeometry 10-100 //////////////////////////////////////////////////////////////////////////////// // Distributed under the Boost Software License, Version 1.0. // // (See accompanying file LICENSE or copy at // // https://www.boost.org/LICENSE_1_0.txt) // //////////////////////////////////////////////////////////////////////////////// #include "networking/windows/winsock.h" #include #include #pragma comment(lib, "Ws2_32.lib") #include "core/error_handling.h" namespace iris { Winsock::Winsock() { WSADATA data = {0}; ensure(::WSAStartup(MAKEWORD(2, 2), &data) == 0, "failed to init winsock"); } /** * Cleanup winsock. */ Winsock::~Winsock() { ::WSACleanup(); } } 1-10 #include #include #define lli long long int #define mod 1000000007 using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); int M,t2,t3,t4; cin>>M>>t2>>t3>>t4; multimap > m; for (int i = 0; i < M; ++i){ int nIngrediants; cin>>nIngrediants; string str; for (int j = 0; j < nIngrediants; ++j) cin>>str; m.insert({nIngrediants, i}); } int nt3 = 0, nt2 = 0, nt4 = 0; int D = 0; int Q = 0; Q = M/4; M = M % 4; if(Q > t4) M += 4*(Q-t4), D += t4, nt4 = t4; else D += Q, nt4 = Q; Q = 0; Q = M/2; M = M % 2; if(Q > t2) M += 2*(Q-t2), D += t2, nt2 = t2; else D += Q, nt2 = Q; Q = 0; Q = M/3; M = M % 3; if(Q > t3) M += 3*(Q-t3), D += t3, nt3 = t3; else D += Q, nt3 = Q; cout<not522/Competitive-Programmingold/Codeforces/58/A.cpp #include "template.hpp" int main() { string s, t = "hello"; cin >> s; size_t i = 0; for (char c : s) { if (c == t[i]) ++i; } cout << (i == t.size() ? "YES" : "NO") << endl; } mcx/kindr /* * Copyright (c) 2013, , , , * 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 Autonomous Systems Lab, ETH Zurich 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 , , , * 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 "kindr/poses/PoseDiff.hpp" #include "kindr/poses/PoseDiffBase.hpp" #include "kindr/phys_quant/PhysicalQuantities.hpp" namespace pose = kindr; namespace pos = kindr; namespace rot = kindr; typedef ::testing::Types< pose::TwistLinearVelocityRotationQuaternionDiffD, pose::TwistLinearVelocityRotationQuaternionDiffF > Types; template struct TwistTest: public ::testing::Test { typedef PoseImplementation PoseDiff; }; TYPED_TEST_CASE(TwistTest, Types); TYPED_TEST(TwistTest, testConstructor) { } TYPED_TEST(TwistTest, testInitial) { typedef typename TestFixture::PoseDiff PoseDiff; typedef typename TestFixture::PoseDiff::Scalar Scalar; typedef rot::RotationQuaternion Rotation; typename PoseDiff::PositionDiff linearVelocity(0.1, 0.2, 0.3); rot::LocalAngularVelocityD angularVelocity; typename PoseDiff::RotationDiff rquatDiff(1, 2, 3, 4); PoseDiff twist(linearVelocity, rquatDiff); std::cout << twist << std::endl; Rotation rot; std::cout << twist.getVector(rot) << std::endl; } TYPED_TEST(TwistTest, testSetZero) { typedef typename TestFixture::PoseDiff PoseDiff; PoseDiff twist(typename PoseDiff::PositionDiff(0.1, 0.2, 0.3), typename PoseDiff::RotationDiff(1, 2, 3, 4)); twist.setZero(); ASSERT_EQ(twist.getTranslationalVelocity().vector().x(), 0); ASSERT_EQ(twist.getTranslationalVelocity().vector().y(), 0); ASSERT_EQ(twist.getTranslationalVelocity().vector().z(), 0); ASSERT_EQ(twist.getRotationalVelocity().w(), 0); ASSERT_EQ(twist.getRotationalVelocity().x(), 0); ASSERT_EQ(twist.getRotationalVelocity().y(), 0); ASSERT_EQ(twist.getRotationalVelocity().z(), 0); } /* Siconos is a program dedicated to modeling, simulation and control * of non smooth dynamical systems. * * Copyright 2016 INRIA. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /*!\file FrictionalContact3D.cpp A very simple example to chow how to use SiconosNumerics to solve the time--discretized FrictionalContact3D problem with a dense storage. The problem: Find \f$(reaction,velocity)\f$ such that:\n \f$ \left\lbrace \begin{array}{l} M \ reaction + q = velocity \\ 0 \le reaction_n \perp velocity_n \ge 0 \\ -velocity_t \in \partial\psi_{D_(\mu reaction_n)}(reaction_t)\\ D_(\mu reaction_n) = \{ reaction_t \mid \|reaction_t\| \leq \mu reaction_n \} \end{array} \right. \f$ \f$ reaction, velocity, q\f$ are vectors of size n and \f$ M \f$ is a nXn matrix, with \f$ n = 2*nc or 3*nc \f$, nc being the number of contacts. \n \f$ reaction_n\f$ represents the normal part of the reaction while \f$ reaction_t\f$ is its tangential part. \f$ \mu \f$ is the friction coefficient (it may be different for each contact). Use the generic function frictionContact3D_driver() to call one the the specific solvers listed below: - frictionContact3D_nsgs() : non-smooth Gauss-Seidel solver (see the functions/solvers list in FrictionContact3D_Solvers.h) FrictionContact3D problems needs some specific parameters, given to the FrictionContact3D_driver() function thanks to a SolverOptions structure. \n They are:\n - the name of the solver (ex: NSGS), used to switch to the right solver function - isStorageSparse: 1 if a SparseBlockStructuredMatrix is used for M, else 0 (double* storage) \brief */ #include "SiconosNumerics.h" #include "FrictionContactProblem.h" #include "NumericsMatrix.h" #include "SolverOptions.h" #include "Friction_cst.h" #include "fc3d_Solvers.h" #include int main(int argc, char* argv[]) { // Problem Definition int NC = 3;//Number of contacts double M[81] = {1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}; double q[9] = { -1, 1, 3, -1, 1, 3, -1, 1, 3}; double mu[3] = {0.1, 0.1, 0.1}; int k; /* for (j =0 ; j<9; j++){ */ /* for (k =0 ; k<9; k++) */ /* M[j][k]=0.0; */ /* } */ /* for (i =0 ; istorageType = 0; MM->matrix0 = M; MM->size0 = 3 * NC; MM->size1 = 3 * NC; NumericsProblem.M = MM; // Unknown Declaration double *reaction = (double*)calloc(3 * NC, sizeof(double)); double *velocity = (double*)calloc(3 * NC, sizeof(double)); // Numerics and Solver Options SolverOptions *numerics_solver_options = (SolverOptions *)malloc(sizeof(SolverOptions)); fc3d_setDefaultSolverOptions(numerics_solver_options, SICONOS_FRICTION_3D_NSGS); numerics_solver_options->dparam[0] = 100*DBL_EPSILON; //Driver call fc3d_driver(&NumericsProblem, reaction , velocity, numerics_solver_options); solver_options_delete(numerics_solver_options); // Solver output printf("\n"); for (k = 0 ; k < 3 * NC; k++) printf("Velocity[%i] = %12.8e \t \t Reaction[%i] = %12.8e \n ", k, velocity[k], k , reaction[k]); printf("\n"); free(numerics_solver_options); free(reaction); free(velocity); free(MM); } /* * Copyright (c) 2020, NVIDIA 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. */ #pragma once #include #include #include #include #include #include #include namespace HugeCTR { /** * @brief Data reading controller. * * Control the data reading from data set to embedding. * An instance of DataReader will maintain independent * threads for data reading (IDataReaderWorker) * from dataset to heap. Meanwhile one independent * thread consumes the data (DataCollector), * and copy the data to GPU buffer. */ class IDataReader { public: virtual ~IDataReader() {} virtual TensorScalarType get_scalar_type() const = 0; virtual long long read_a_batch_to_device() = 0; virtual long long read_a_batch_to_device_delay_release() = 0; virtual long long get_current_batchsize_per_device(size_t local_id) = 0; virtual long long get_full_batchsize() const = 0; virtual void ready_to_collect() = 0; virtual bool is_started() const = 0; virtual void start() = 0; virtual void create_drwg_norm(std::string file_list, Check_t check_type, bool start_reading_from_beginning = true) = 0; virtual void create_drwg_raw( std::string file_name, long long num_samples, const std::vector slot_offset, bool float_label_dense, bool data_shuffle, bool start_reading_from_beginning = true) = 0; virtual void create_drwg_parquet( std::string file_list, const std::vector slot_offset, bool start_reading_from_beginning = true) = 0; // TODO(xiaoleis, 01182021): add SourceType_t to allow user to change the type virtual void set_source(std::string file_name = std::string()) = 0; }; } // namespace HugeCTR // Generated by Haxe 4.0.0-rc.2+77068e10c #include #ifndef INCLUDED_openfl__internal_renderer_DrawCommandBuffer #include #endif #ifndef INCLUDED_openfl__internal_renderer_DrawCommandReader #include #endif #ifndef INCLUDED_openfl__internal_renderer__DrawCommandReader_OverrideMatrixView_Impl_ #include #endif #ifndef INCLUDED_openfl_geom_Matrix #include #endif HX_LOCAL_STACK_FRAME(_hx_pos_28b4f2743b357018_1004__new,"openfl._internal.renderer._DrawCommandReader.OverrideMatrixView_Impl_","_new",0x139046f5,"openfl._internal.renderer._DrawCommandReader.OverrideMatrixView_Impl_._new","openfl/_internal/renderer/DrawCommandReader.hx",1004,0xbbdbd1ae) HX_LOCAL_STACK_FRAME(_hx_pos_28b4f2743b357018_1013_get_matrix,"openfl._internal.renderer._DrawCommandReader.OverrideMatrixView_Impl_","get_matrix",0x91a43e9e,"openfl._internal.renderer._DrawCommandReader.OverrideMatrixView_Impl_.get_matrix","openfl/_internal/renderer/DrawCommandReader.hx",1013,0xbbdbd1ae) namespace openfl{ namespace _internal{ namespace renderer{ namespace _DrawCommandReader{ void OverrideMatrixView_Impl__obj::__construct() { } Dynamic OverrideMatrixView_Impl__obj::__CreateEmpty() { return new OverrideMatrixView_Impl__obj; } void *OverrideMatrixView_Impl__obj::_hx_vtable = 0; Dynamic OverrideMatrixView_Impl__obj::__Create(hx::DynamicArray inArgs) { hx::ObjectPtr< OverrideMatrixView_Impl__obj > _hx_result = new OverrideMatrixView_Impl__obj(); _hx_result->__construct(); return _hx_result; } bool OverrideMatrixView_Impl__obj::_hx_isInstanceOf(int inClassId) { return inClassId==(int)0x00000001 || inClassId==(int)0x2e4b2cac; } ::openfl::_internal::renderer::DrawCommandReader OverrideMatrixView_Impl__obj::_new( ::openfl::_internal::renderer::DrawCommandReader d){ HX_STACKFRAME(&_hx_pos_28b4f2743b357018_1004__new) HXDLIN(1004) ::openfl::_internal::renderer::DrawCommandReader this1 = d; HXDLIN(1004) return this1; } STATIC_HX_DEFINE_DYNAMIC_FUNC1(OverrideMatrixView_Impl__obj,_new,return ) ::openfl::geom::Matrix OverrideMatrixView_Impl__obj::get_matrix( ::openfl::_internal::renderer::DrawCommandReader this1){ HX_STACKFRAME(&_hx_pos_28b4f2743b357018_1013_get_matrix) HXDLIN(1013) return ( ( ::openfl::geom::Matrix)(this1->buffer->o->__get(this1->oPos)) ); } STATIC_HX_DEFINE_DYNAMIC_FUNC1(OverrideMatrixView_Impl__obj,get_matrix,return ) OverrideMatrixView_Impl__obj::OverrideMatrixView_Impl__obj() { } bool OverrideMatrixView_Impl__obj::__GetStatic(const ::String &inName, Dynamic &outValue, hx::PropertyAccess inCallProp) { switch(inName.length) { case 4: if (HX_FIELD_EQ(inName,"_new") ) { outValue = _new_dyn(); return true; } break; case 10: if (HX_FIELD_EQ(inName,"get_matrix") ) { outValue = get_matrix_dyn(); return true; } } return false; } #ifdef HXCPP_SCRIPTABLE static hx::StorageInfo *OverrideMatrixView_Impl__obj_sMemberStorageInfo = 0; static hx::StaticInfo *OverrideMatrixView_Impl__obj_sStaticStorageInfo = 0; #endif hx::Class OverrideMatrixView_Impl__obj::__mClass; static ::String OverrideMatrixView_Impl__obj_sStaticFields[] = { HX_("_new",61,15,1f,3f), HX_("get_matrix",0a,a6,4f,ac), ::String(null()) }; void OverrideMatrixView_Impl__obj::__register() { OverrideMatrixView_Impl__obj _hx_dummy; OverrideMatrixView_Impl__obj::_hx_vtable = *(void **)&_hx_dummy; hx::Static(__mClass) = new hx::Class_obj(); __mClass->mName = HX_("openfl._internal.renderer._DrawCommandReader.OverrideMatrixView_Impl_",5a,97,98,60); __mClass->mSuper = &super::__SGetClass(); __mClass->mConstructEmpty = &__CreateEmpty; __mClass->mConstructArgs = &__Create; __mClass->mGetStaticField = &OverrideMatrixView_Impl__obj::__GetStatic; __mClass->mSetStaticField = &hx::Class_obj::SetNoStaticField; __mClass->mStatics = hx::Class_obj::dupFunctions(OverrideMatrixView_Impl__obj_sStaticFields); __mClass->mMembers = hx::Class_obj::dupFunctions(0 /* sMemberFields */); __mClass->mCanCast = hx::TCanCast< OverrideMatrixView_Impl__obj >; #ifdef HXCPP_SCRIPTABLE __mClass->mMemberStorageInfo = OverrideMatrixView_Impl__obj_sMemberStorageInfo; #endif #ifdef HXCPP_SCRIPTABLE __mClass->mStaticStorageInfo = OverrideMatrixView_Impl__obj_sStaticStorageInfo; #endif hx::_hx_RegisterClass(__mClass->mName, __mClass); } } // end namespace openfl } // end namespace _internal } // end namespace renderer } // end namespace _DrawCommandReader /// GENERATED BY SDK TOOL. /// DON'T MODIFY THIS FILE UNLESS YOU'RE FULLY UNDERSTANDING WHAT YOU ARE DOING!!! #include "../PubSub/MessageCreator.h" using namespace Ruyi; std::map MessageCreator::ccs; void MessageCreator::Initialize() { REGIST_CREATION_FUNCTION("Ruyi.SDK.InputManager.RuyiGamePadInput", Ruyi::SDK::InputManager::RuyiGamePadInput); REGIST_CREATION_FUNCTION("Ruyi.SDK.InputManager.RuyiKeyboardInput", Ruyi::SDK::InputManager::RuyiKeyboardInput); REGIST_CREATION_FUNCTION("Ruyi.SDK.InputManager.RuyiMouseInput", Ruyi::SDK::InputManager::RuyiMouseInput); REGIST_CREATION_FUNCTION("Ruyi.SDK.InputManager.RuyiJoystickInput", Ruyi::SDK::InputManager::RuyiJoystickInput); REGIST_CREATION_FUNCTION("Ruyi.SDK.InputManager.InputActionTriggered", Ruyi::SDK::InputManager::InputActionTriggered); REGIST_CREATION_FUNCTION("Ruyi.SDK.InputManager.AxisActionTriggered", Ruyi::SDK::InputManager::AxisActionTriggered); REGIST_CREATION_FUNCTION("Ruyi.SDK.InputManager.GamepadInfo", Ruyi::SDK::InputManager::GamepadInfo); REGIST_CREATION_FUNCTION("Ruyi.SDK.StorageLayer.GetLocalPathResult", Ruyi::SDK::StorageLayer::GetLocalPathResult); REGIST_CREATION_FUNCTION("Ruyi.SDK.SettingSystem.Api.RuyiNetworkSettingNameValue", Ruyi::SDK::SettingSystem::Api::RuyiNetworkSettingNameValue); REGIST_CREATION_FUNCTION("Ruyi.SDK.SettingSystem.Api.RuyiNetworkTestItem", Ruyi::SDK::SettingSystem::Api::RuyiNetworkTestItem); REGIST_CREATION_FUNCTION("Ruyi.SDK.SettingSystem.Api.RuyiNetworkSettings", Ruyi::SDK::SettingSystem::Api::RuyiNetworkSettings); REGIST_CREATION_FUNCTION("Ruyi.SDK.SettingSystem.Api.RuyiNetworkStatus", Ruyi::SDK::SettingSystem::Api::RuyiNetworkStatus); REGIST_CREATION_FUNCTION("Ruyi.SDK.SettingSystem.Api.RuyiNetworkTestResult", Ruyi::SDK::SettingSystem::Api::RuyiNetworkTestResult); REGIST_CREATION_FUNCTION("Ruyi.SDK.SettingSystem.Api.NetworkConnectionStatus", Ruyi::SDK::SettingSystem::Api::NetworkConnectionStatus); REGIST_CREATION_FUNCTION("Ruyi.SDK.SettingSystem.Api.NetworkSettings", Ruyi::SDK::SettingSystem::Api::NetworkSettings); REGIST_CREATION_FUNCTION("Ruyi.SDK.SettingSystem.Api.CategoryNode", Ruyi::SDK::SettingSystem::Api::CategoryNode); REGIST_CREATION_FUNCTION("Ruyi.SDK.SettingSystem.Api.SettingSearchResult", Ruyi::SDK::SettingSystem::Api::SettingSearchResult); REGIST_CREATION_FUNCTION("Ruyi.SDK.SettingSystem.Api.SettingTree", Ruyi::SDK::SettingSystem::Api::SettingTree); REGIST_CREATION_FUNCTION("Ruyi.SDK.SettingSystem.Api.NodeList", Ruyi::SDK::SettingSystem::Api::NodeList); REGIST_CREATION_FUNCTION("Ruyi.SDK.SettingSystem.Api.WifiEntity", Ruyi::SDK::SettingSystem::Api::WifiEntity); REGIST_CREATION_FUNCTION("Ruyi.SDK.BrainCloudApi.BCServiceStartedNotification", Ruyi::SDK::BrainCloudApi::BCServiceStartedNotification); REGIST_CREATION_FUNCTION("Ruyi.SDK.BrainCloudApi.FileUploadSuccessResult", Ruyi::SDK::BrainCloudApi::FileUploadSuccessResult); REGIST_CREATION_FUNCTION("Ruyi.SDK.BrainCloudApi.FileUploadFailedResult", Ruyi::SDK::BrainCloudApi::FileUploadFailedResult); REGIST_CREATION_FUNCTION("Ruyi.SDK.LocalizationService.LanguageChangedMsg", Ruyi::SDK::LocalizationService::LanguageChangedMsg); REGIST_CREATION_FUNCTION("Ruyi.SDK.UserServiceExternal.TriggerKeys", Ruyi::SDK::UserServiceExternal::TriggerKeys); REGIST_CREATION_FUNCTION("Ruyi.SDK.UserServiceExternal.InputActionEvent", Ruyi::SDK::UserServiceExternal::InputActionEvent); REGIST_CREATION_FUNCTION("Ruyi.SDK.UserServiceExternal.UserEvent", Ruyi::SDK::UserServiceExternal::UserEvent); REGIST_CREATION_FUNCTION("Ruyi.SDK.UserServiceExternal.UserInfo_Public", Ruyi::SDK::UserServiceExternal::UserInfo_Public); REGIST_CREATION_FUNCTION("Ruyi.SDK.OverlayManagerExternal.NotifyTakeScreenShot", Ruyi::SDK::OverlayManagerExternal::NotifyTakeScreenShot); }swot3563941/my_project #include #include #include "Leader.h" using namespace enviro; // Implement in .h file0 // Copyright 2010 Google Inc. All Rights Reserved. // Author: () /////////////////////////////////////////////////////////////////////// // File: intfeaturemap.cpp // Description: Encapsulation of IntFeatureSpace with IndexMapBiDi // to provide a subspace mapping and fast feature lookup. // Created: Tue Oct 26 08:58:30 PDT 2010 // // 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 "intfeaturemap.h" #include "intfeaturespace.h" #include "intfx.h" // These includes do not exist yet, but will be coming soon. //#include "sampleiterator.h" //#include "trainingsample.h" //#include "trainingsampleset.h" namespace tesseract { const int kMaxOffsetDist = 32; IntFeatureMap::IntFeatureMap() : mapping_changed_(true), compact_size_(0) { for (int dir = 0; dir < kNumOffsetMaps; ++dir) { offset_plus_[dir] = NULL; offset_minus_[dir] = NULL; } } IntFeatureMap::~IntFeatureMap() { Clear(); } // Pseudo-accessors. int IntFeatureMap::IndexFeature(const INT_FEATURE_STRUCT& f) const { return feature_space_.Index(f); } int IntFeatureMap::MapFeature(const INT_FEATURE_STRUCT& f) const { return feature_map_.SparseToCompact(feature_space_.Index(f)); } int IntFeatureMap::MapIndexFeature(int index_feature) const { return feature_map_.SparseToCompact(index_feature); } INT_FEATURE_STRUCT IntFeatureMap::InverseIndexFeature(int index_feature) const { return feature_space_.PositionFromIndex(index_feature); } INT_FEATURE_STRUCT IntFeatureMap::InverseMapFeature(int map_feature) const { int index = feature_map_.CompactToSparse(map_feature); return feature_space_.PositionFromIndex(index); } void IntFeatureMap::DeleteMapFeature(int map_feature) { feature_map_.Merge(-1, map_feature); mapping_changed_ = true; } bool IntFeatureMap::IsMapFeatureDeleted(int map_feature) const { return feature_map_.IsCompactDeleted(map_feature); } // Copies the given feature_space and uses it as the index feature map // from INT_FEATURE_STRUCT. void IntFeatureMap::Init(const IntFeatureSpace& feature_space) { feature_space_ = feature_space; mapping_changed_ = false; int sparse_size = feature_space_.Size(); feature_map_.Init(sparse_size, true); feature_map_.Setup(); compact_size_ = feature_map_.CompactSize(); // Initialize look-up tables if needed. FCOORD dir = FeatureDirection(0); if (dir.x() == 0.0f && dir.y() == 0.0f) InitIntegerFX(); // Compute look-up tables to generate offset features. for (int dir = 0; dir < kNumOffsetMaps; ++dir) { delete [] offset_plus_[dir]; delete [] offset_minus_[dir]; offset_plus_[dir] = new int[sparse_size]; offset_minus_[dir] = new int[sparse_size]; } for (int dir = 1; dir <= kNumOffsetMaps; ++dir) { for (int i = 0; i < sparse_size; ++i) { int offset_index = ComputeOffsetFeature(i, dir); offset_plus_[dir - 1][i] = offset_index; offset_index = ComputeOffsetFeature(i, -dir); offset_minus_[dir - 1][i] = offset_index; } } } // Helper to return an offset index feature. In this context an offset // feature with a dir of +/-1 is a feature of a similar direction, // but shifted perpendicular to the direction of the feature. An offset // feature with a dir of +/-2 is feature at the same position, but rotated // by +/- one [compact] quantum. Returns the index of the generated offset // feature, or -1 if it doesn't exist. Dir should be in // [-kNumOffsetMaps, kNumOffsetMaps] to indicate the relative direction. // A dir of 0 is an identity transformation. // Both input and output are from the index(sparse) feature space, not // the mapped/compact feature space, but the offset feature is the minimum // distance moved from the input to guarantee that it maps to the next // available quantum in the mapped/compact space. int IntFeatureMap::OffsetFeature(int index_feature, int dir) const { if (dir > 0 && dir <= kNumOffsetMaps) return offset_plus_[dir - 1][index_feature]; else if (dir < 0 && -dir <= kNumOffsetMaps) return offset_minus_[-dir - 1][index_feature]; else if (dir == 0) return index_feature; else return -1; } //#define EXPERIMENT_ON #ifdef EXPERIMENT_ON // This code is commented out as SampleIterator and // TrainingSample are not reviewed/checked in yet, but these functions are a // useful indicator of how an IntFeatureMap is setup. // Computes the features used by the subset of samples defined by // the iterator and sets up the feature mapping. // Returns the size of the compacted feature space. int IntFeatureMap::FindNZFeatureMapping(SampleIterator* it) { feature_map_.Init(feature_space_.Size(), false); int total_samples = 0; for (it->Begin(); !it->AtEnd(); it->Next()) { const TrainingSample& sample = it->GetSample(); GenericVector features; feature_space_.IndexAndSortFeatures(sample.features(), sample.num_features(), &features); int num_features = features.size(); for (int f = 0; f < num_features; ++f) feature_map_.SetMap(features[f], true); ++total_samples; } feature_map_.Setup(); compact_size_ = feature_map_.CompactSize(); mapping_changed_ = true; FinalizeMapping(it); tprintf("%d non-zero features found in %d samples\n", compact_size_, total_samples); return compact_size_; } #endif // After deleting some features, finish setting up the mapping, and map // all the samples. Returns the size of the compacted feature space. int IntFeatureMap::FinalizeMapping(SampleIterator* it) { if (mapping_changed_) { feature_map_.CompleteMerges(); compact_size_ = feature_map_.CompactSize(); #ifdef EXPERIMENT_ON it->MapSampleFeatures(*this); #endif mapping_changed_ = false; } return compact_size_; } // Prints the map features from the set in human-readable form. void IntFeatureMap::DebugMapFeatures( const GenericVector& map_features) const { for (int i = 0; i < map_features.size(); ++i) { INT_FEATURE_STRUCT f = InverseMapFeature(map_features[i]); f.print(); } } void IntFeatureMap::Clear() { for (int dir = 0; dir < kNumOffsetMaps; ++dir) { delete [] offset_plus_[dir]; delete [] offset_minus_[dir]; offset_plus_[dir] = NULL; offset_minus_[dir] = NULL; } } // Helper to compute an offset index feature. In this context an offset // feature with a dir of +/-1 is a feature of a similar direction, // but shifted perpendicular to the direction of the feature. An offset // feature with a dir of +/-2 is feature at the same position, but rotated // by +/- one [compact] quantum. Returns the index of the generated offset // feature, or -1 if it doesn't exist. Dir should be in // [-kNumOffsetMaps, kNumOffsetMaps] to indicate the relative direction. // A dir of 0 is an identity transformation. // Both input and output are from the index(sparse) feature space, not // the mapped/compact feature space, but the offset feature is the minimum // distance moved from the input to guarantee that it maps to the next // available quantum in the mapped/compact space. int IntFeatureMap::ComputeOffsetFeature(int index_feature, int dir) const { INT_FEATURE_STRUCT f = InverseIndexFeature(index_feature); ASSERT_HOST(IndexFeature(f) == index_feature); if (dir == 0) { return index_feature; } else if (dir == 1 || dir == -1) { FCOORD feature_dir = FeatureDirection(f.Theta); FCOORD rotation90(0.0f, 1.0f); feature_dir.rotate(rotation90); // Find the nearest existing feature. for (int m = 1; m < kMaxOffsetDist; ++m) { double x_pos = f.X + feature_dir.x() * (m * dir); double y_pos = f.Y + feature_dir.y() * (m * dir); int x = IntCastRounded(x_pos); int y = IntCastRounded(y_pos); if (x >= 0 && x <= UINT8_MAX && y >= 0 && y <= UINT8_MAX) { INT_FEATURE_STRUCT offset_f; offset_f.X = x; offset_f.Y = y; offset_f.Theta = f.Theta; int offset_index = IndexFeature(offset_f); if (offset_index != index_feature && offset_index >= 0) return offset_index; // Found one. } else { return -1; // Hit the edge of feature space. } } } else if (dir == 2 || dir == -2) { // Find the nearest existing index_feature. for (int m = 1; m < kMaxOffsetDist; ++m) { int theta = f.Theta + m * dir / 2; INT_FEATURE_STRUCT offset_f; offset_f.X = f.X; offset_f.Y = f.Y; offset_f.Theta = Modulo(theta, 256); int offset_index = IndexFeature(offset_f); if (offset_index != index_feature && offset_index >= 0) return offset_index; // Found one. } } return -1; // Nothing within the max distance. } } // namespace tesseract. #pragma once #include "SQLStatement.hpp" // Note: Implementations of constructors and destructors can be found in statements.cpp. namespace zsql { enum ShowType { kShowColumns, kShowTables }; // Represents SQL SHOW statements. // Example "SHOW TABLES;" struct ShowStatement : SQLStatement { explicit ShowStatement(ShowType type); ~ShowStatement() override; ShowType type; char* schema; char* name; }; }src/arch/ppu/locked_mem.cc #include "arch/ppu/locked_mem.hh" #include #include "base/types.hh" namespace PpuISA { std::unordered_map> locked_addrs; } jeikabu/lumberyarddev/Code/Sandbox/Plugins/CryDesigner/Tools/Select/LoopSelectionTool.cpp /* * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or * its licensors. * * For complete copyright and license terms please see the LICENSE at the root of this * distribution (the "License"). All use of this software is governed by the License, * or, if provided, by the license below or the license accompanying this file. Do not * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * */ // Original file Copyright Crytek GMBH or its affiliates, used under license. #include "StdAfx.h" #include "LoopSelectionTool.h" #include "Tools/DesignerTool.h" #include "Util/ElementManager.h" namespace { int s_nMaximumRepeatCount = 0; } using namespace CD; void LoopSelectionTool::LoopSelection(const SMainContext& mc) { ElementManager copiedSelected = *mc.pSelected; int nSelectedElementCount = copiedSelected.GetCount(); if (nSelectedElementCount >= 2) { const SElement& firstElement = copiedSelected[nSelectedElementCount - 2]; const SElement& secondElement = copiedSelected[nSelectedElementCount - 1]; if (firstElement.IsFace() && secondElement.IsFace()) { SelectFaceLoop(mc, firstElement.m_pPolygon, secondElement.m_pPolygon); SelectFaceLoop(mc, secondElement.m_pPolygon, firstElement.m_pPolygon); return; } } mc.pSelected->Clear(); s_nMaximumRepeatCount = CountAllEdges(mc) * 50; for (int i = 0; i < nSelectedElementCount; ++i) { if (!copiedSelected[i].IsEdge()) { continue; } if (!SelectLoop(mc, copiedSelected[i].GetEdge())) { mc.pSelected->Clear(); if (SelectBorderInOnePolygon(mc, copiedSelected[i].GetEdge())) { continue; } ElementManager elements; if (SelectBorder(mc, copiedSelected[i].GetEdge(), elements)) { mc.pSelected->Add(elements); mc.pSelected->Add(SElement(mc.pObject, copiedSelected[i].GetEdge())); } } } } void AddEdgeToList(std::vector& edgeList, const BrushEdge3D& edge) { BrushEdge3D invEdge = edge.GetInverted(); for (int i = 0, iEdgeCount(edgeList.size()); i < iEdgeCount; ++i) { if (edgeList[i].IsEquivalent(edge) || edgeList[i].IsEquivalent(invEdge)) { return; } } edgeList.push_back(edge); } void LoopSelectionTool::Enter() { LoopSelection(GetMainContext()); CD::GetDesigner()->SwitchToPrevTool(); } bool HasEdge(std::vector& polygonList, const BrushEdge3D& edge) { for (int i = 0, iPolygonCount(polygonList.size()); i < iPolygonCount; ++i) { if (polygonList[i]->HasEdge(edge)) { return true; } } return false; } bool FindNextEdge(const SMainContext& mc, const BrushEdge3D& edge, BrushEdge3D& outEdge) { ModelDB* pDB = mc.pModel->GetDB(); ModelDB::QueryResult queryResult; if (!pDB->QueryAsVertex(edge.m_v[1], queryResult)) { return false; } if (queryResult.size() != 1) { return false; } if (queryResult[0].m_MarkList.size() != 4) { return false; } std::vector invalidPolygons; std::vector validPolygons; for (int i = 0; i < 4; ++i) { PolygonPtr pPolygon = queryResult[0].m_MarkList[i].m_pPolygon; if (pPolygon->HasEdge(edge)) { invalidPolygons.push_back(pPolygon); } else { validPolygons.push_back(pPolygon); } } for (int i = 0, iPolygonCount(validPolygons.size()); i < iPolygonCount; ++i) { PolygonPtr pPolygon = validPolygons[i]; for (int k = 0, iEdgeCount(pPolygon->GetEdgeCount()); k < iEdgeCount; ++k) { BrushEdge3D e = pPolygon->GetEdge(k); if (IsEquivalent(e.m_v[0], edge.m_v[1]) && !HasEdge(invalidPolygons, e)) { outEdge = e; return true; } } } return false; } bool LoopSelectionTool::SelectLoop(const SMainContext& mc, const BrushEdge3D& initialEdge) { BrushEdge3D edge = initialEdge; ElementManager edgeElements; int nCount = 0; bool bLoop = false; for (int i = 0; i < 2; ++i) { while (!bLoop) { edgeElements.Add(SElement(mc.pObject, edge)); BrushEdge3D nextEdge; if (!FindNextEdge(mc, edge, nextEdge)) { break; } bLoop = nextEdge.IsEquivalent(initialEdge); edge = nextEdge; } if (bLoop) { break; } edge = initialEdge.GetInverted(); } if (edgeElements.IsEmpty() || (edgeElements.GetCount() == 1 && edgeElements[0].IsEdge() && edgeElements[0].GetEdge().IsEquivalent(initialEdge))) { return false; } ElementManager* pSelected = CD::GetDesigner()->GetSelectedElements(); pSelected->Add(edgeElements); return true; } bool LoopSelectionTool::SelectBorderInOnePolygon(const SMainContext& mc, const BrushEdge3D& edge) { ElementManager* pSelected = CD::GetDesigner()->GetSelectedElements(); std::vector adjacentPolygons; mc.pModel->QueryPolygonsSharingEdge(edge, adjacentPolygons); if (adjacentPolygons.size() == 1) { std::vector outerPolygons; adjacentPolygons[0]->GetSeparatedPolygons(outerPolygons, eSP_OuterHull); for (int i = 0, outerPolygonCount(outerPolygons.size()); i < outerPolygonCount; ++i) { if (!outerPolygons[i]->HasEdge(edge)) { continue; } int nAddedCount = 0; int iEdgeCount(outerPolygons[i]->GetEdgeCount()); for (int k = 0; k < iEdgeCount; ++k) { BrushEdge3D e = outerPolygons[i]->GetEdge(k); if (e.IsEquivalent(edge)) { continue; } if (GetPolygonCountSharingEdge(mc, e) == 1) { ++nAddedCount; pSelected->Add(SElement(mc.pObject, e)); } } if (nAddedCount != iEdgeCount) { pSelected->Clear(); return false; } return true; } } for (int a = 0, iAdjacentPolygonCount(adjacentPolygons.size()); a < iAdjacentPolygonCount; ++a) { std::vector innterPolygons; adjacentPolygons[a]->GetSeparatedPolygons(innterPolygons, eSP_InnerHull); for (int i = 0, innerPolygonCount(innterPolygons.size()); i < innerPolygonCount; ++i) { if (!innterPolygons[i]->HasEdge(edge)) { continue; } for (int k = 0, iEdgeCount(innterPolygons[i]->GetEdgeCount()); k < iEdgeCount; ++k) { BrushEdge3D e = innterPolygons[i]->GetEdge(k); if (GetPolygonCountSharingEdge(mc, e, &(innterPolygons[i]->GetPlane())) == 1) { pSelected->Add(SElement(mc.pObject, e)); } } return true; } } return false; } bool LoopSelectionTool::SelectBorder(const SMainContext& mc, const BrushEdge3D& edge, ElementManager& outElementInfos) { BrushEdge3D e(edge); int nCount = 0; while (nCount++ < s_nMaximumRepeatCount) { std::vector edgeList; mc.pModel->QueryEdgesHavingVertex(e.m_v[1], edgeList); bool bAdded = false; for (int i = 0, iEdgeCount(edgeList.size()); i < iEdgeCount; ++i) { if (e.IsEquivalent(edgeList[i]) || e.GetInverted().IsEquivalent(edgeList[i])) { continue; } if (GetPolygonCountSharingEdge(mc, edgeList[i]) != 1) { continue; } outElementInfos.Add(SElement(mc.pObject, edgeList[i])); e = edgeList[i]; bAdded = true; break; } if (!bAdded) { break; } if (IsEquivalent(e.m_v[1], edge.m_v[0])) { return true; } } return false; } int LoopSelectionTool::GetPolygonCountSharingEdge(const SMainContext& mc, const BrushEdge3D& edge, const BrushPlane* pPlane) { std::vector polygons; mc.pModel->QueryPolygonsSharingEdge(edge, polygons); int nCount = 0; for (int i = 0, iCount(polygons.size()); i < iCount; ++i) { if (!pPlane || polygons[i]->GetPlane().IsEquivalent(*pPlane)) { ++nCount; } } return nCount; } int LoopSelectionTool::CountAllEdges(const SMainContext& mc) { int nEdgeCount = 0; for (int i = 0, iPolygonCount(mc.pModel->GetPolygonCount()); i < iPolygonCount; ++i) { nEdgeCount += mc.pModel->GetPolygon(i)->GetEdgeCount(); } return nEdgeCount; } bool LoopSelectionTool::SelectFaceLoop(const SMainContext& mc, PolygonPtr pFirstPolygon, PolygonPtr pSecondPolygon) { std::vector polygons; GetLoopPolygons(mc, pFirstPolygon, pSecondPolygon, polygons); if (polygons.empty()) { return false; } for (int i = 0, iPolygonCount(polygons.size()); i < iPolygonCount; ++i) { mc.pSelected->Add(SElement(mc.pObject, polygons[i])); } return true; } bool LoopSelectionTool::GetLoopPolygons(const SMainContext& mc, PolygonPtr pFirstPolygon, PolygonPtr pSecondPolygon, std::vector& outPolygons) { bool bAdded = false; int nCount = 0; PolygonPtr pInitPolygon = pFirstPolygon; while (pSecondPolygon && pInitPolygon != pSecondPolygon && pSecondPolygon->GetEdgeCount() == 4 && (nCount++) < mc.pModel->GetPolygonCount()) { PolygonPtr pAdjacentPolygon = FindAdjacentNextPolygon(mc, pFirstPolygon, pSecondPolygon); pFirstPolygon = pSecondPolygon; pSecondPolygon = pAdjacentPolygon; if (pAdjacentPolygon && pAdjacentPolygon != pInitPolygon) { bAdded = true; outPolygons.push_back(pAdjacentPolygon); } } return bAdded; } bool LoopSelectionTool::GetLoopPolygonsInBothWays(const SMainContext& mc, PolygonPtr pFirstPolygon, PolygonPtr pSecondPolygon, std::vector& outPolygons) { std::vector polygonOneWay; std::vector polygonTheOtherWay; bool bAdded0 = GetLoopPolygons(mc, pFirstPolygon, pSecondPolygon, polygonOneWay); bool bAdded1 = GetLoopPolygons(mc, pSecondPolygon, pFirstPolygon, polygonTheOtherWay); if (!bAdded0 && !bAdded1) { return false; } if (!polygonOneWay.empty()) { outPolygons.insert(outPolygons.end(), polygonOneWay.begin(), polygonOneWay.end()); } std::vector::iterator ii = polygonTheOtherWay.begin(); for (; ii != polygonTheOtherWay.end(); ) { bool bErased = false; for (int k = 0, iPolygonCount(polygonOneWay.size()); k < iPolygonCount; ++k) { if (polygonOneWay[k] == *ii) { ii = polygonTheOtherWay.erase(ii); bErased = true; break; } } if (!bErased) { ++ii; } } if (!polygonTheOtherWay.empty()) { outPolygons.insert(outPolygons.begin(), polygonTheOtherWay.rbegin(), polygonTheOtherWay.rend()); } return true; } PolygonPtr LoopSelectionTool::FindAdjacentNextPolygon(const SMainContext& mc, PolygonPtr pFristPolygon, PolygonPtr pSecondPolygon) { int nFirstEdgeCount = pFristPolygon->GetEdgeCount(); int nSecondEdgeCount = pSecondPolygon->GetEdgeCount(); if ((nFirstEdgeCount != 3 && nFirstEdgeCount != 4) || (nSecondEdgeCount != 3 && nSecondEdgeCount != 4)) { return NULL; } std::vector firstVs; std::vector secondVs; pFristPolygon->GetLinkedVertices(firstVs); pSecondPolygon->GetLinkedVertices(secondVs); for (int i = 0; i < nFirstEdgeCount; ++i) { BrushEdge3D first_e(firstVs[i].pos, firstVs[(i + 1) % nFirstEdgeCount].pos); for (int k = 0; k < nSecondEdgeCount; ++k) { BrushEdge3D second_e(secondVs[(k + 1) % nSecondEdgeCount].pos, secondVs[k].pos); if (first_e.IsEquivalent(second_e)) { if (nSecondEdgeCount != 4) { continue; } int nSecondEdgeCount_Half = nSecondEdgeCount / 2; BrushEdge3D oppositeEdge(secondVs[(k + nSecondEdgeCount_Half) % nSecondEdgeCount].pos, secondVs[(k + nSecondEdgeCount_Half + 1) % nSecondEdgeCount].pos); std::vector polygonsSharingEdge; mc.pModel->QueryPolygonsSharingEdge(oppositeEdge, polygonsSharingEdge); int nPolygonCount(polygonsSharingEdge.size()); for (int a = 0; a < nPolygonCount; ++a) { int nEdgeCount = polygonsSharingEdge[a]->GetEdgeCount(); if (polygonsSharingEdge[a] != pSecondPolygon && (nEdgeCount == 3 || nEdgeCount == 4)) { return polygonsSharingEdge[a]; } } } } } return NULL; } REGISTER_DESIGNER_TOOL(CD::eDesigner_Loop, CD::eToolGroup_Selection, "Loop", LoopSelectionTool)// Copyright 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 "chrome/browser/web_applications/web_app_helpers.h" #include "base/base64.h" #include "base/strings/strcat.h" #include "base/strings/string_number_conversions.h" #include "base/strings/utf_string_conversions.h" #include "chrome/browser/web_applications/web_app_provider.h" #include "chrome/browser/web_applications/web_app_registrar.h" #include "components/crx_file/id_util.h" #include "crypto/sha2.h" #include "third_party/blink/public/mojom/manifest/manifest.mojom.h" #include "url/gurl.h" #include "url/url_constants.h" namespace web_app { namespace { // The following string is used to build the directory name for // shortcuts to chrome applications (the kind which are installed // from a CRX). Application shortcuts to URLs use the {host}_{path} // for the name of this directory. Hosts can't include an underscore. // By starting this string with an underscore, we ensure that there // are no naming conflicts. const char kCrxAppPrefix[] = "_crx_"; } // namespace std::string GenerateApplicationNameFromURL(const GURL& url) { return base::StrCat({url.host_piece(), "_", url.path_piece()}); } std::string GenerateApplicationNameFromAppId(const AppId& app_id) { std::string t(kCrxAppPrefix); t.append(app_id); return t; } AppId GetAppIdFromApplicationName(const std::string& app_name) { std::string prefix(kCrxAppPrefix); if (app_name.substr(0, prefix.length()) != prefix) return std::string(); return app_name.substr(prefix.length()); } std::string GenerateAppIdUnhashed( const absl::optional& manifest_id, const GURL& start_url) { // When manifest_id is specified, the app id is generated from // /. // Note: start_url.DeprecatedGetOriginAsURL().spec() returns the origin ending // with slash. if (manifest_id.has_value()) { GURL app_id(start_url.DeprecatedGetOriginAsURL().spec() + manifest_id.value()); DCHECK(app_id.is_valid()); return app_id.spec(); } return start_url.spec(); } AppId GenerateAppId(const absl::optional& manifest_id, const GURL& start_url) { return crx_file::id_util::GenerateId( crypto::SHA256HashString(GenerateAppIdUnhashed(manifest_id, start_url))); } std::string GenerateAppIdUnhashedFromManifest( const blink::mojom::Manifest& manifest) { return GenerateAppIdUnhashed( manifest.id.has_value() ? absl::optional(base::UTF16ToUTF8(manifest.id.value())) : absl::nullopt, manifest.start_url); } AppId GenerateAppIdFromManifest(const blink::mojom::Manifest& manifest) { return crx_file::id_util::GenerateId( crypto::SHA256HashString(GenerateAppIdUnhashedFromManifest(manifest))); } std::string GenerateRecommendedId(const GURL& start_url) { if (!start_url.is_valid()) { return base::EmptyString(); } std::string full_url = start_url.spec(); std::string origin = start_url.DeprecatedGetOriginAsURL().spec(); DCHECK(!full_url.empty() && !origin.empty() && origin.size() <= full_url.size()); // Make recommended id starts with a leading slash so it's clear to developers // that it's a root-relative url path. In reality it's always root-relative // because the base_url is the origin. return full_url.substr(origin.size() - 1); } bool IsValidWebAppUrl(const GURL& app_url) { if (app_url.is_empty() || app_url.inner_url()) return false; // TODO(crbug.com/1253234): Remove chrome-extension scheme and use // SchemeIsHTTPOrHTTPS() instead of IsValidWebAppUrl(); return app_url.SchemeIs(url::kHttpScheme) || app_url.SchemeIs(url::kHttpsScheme) || app_url.SchemeIs("chrome-extension"); } absl::optional FindInstalledAppWithUrlInScope(Profile* profile, const GURL& url, bool window_only) { auto* provider = WebAppProvider::GetForLocalAppsUnchecked(profile); return provider ? provider->registrar().FindInstalledAppWithUrlInScope( url, window_only) : absl::nullopt; } } // namespace web_app Ty3uK/nodegui #include "core/FlexLayout/flexlayout.hpp" #include #include #include "Extras/Utils/nutils.h" #include "core/FlexLayout/flexitem.h" #include "core/FlexLayout/flexutils.h" #include "core/YogaWidget/yogawidget.h" FlexLayout::FlexLayout(QWidget* parentWidget, YGNodeRef parentNode) : QLayout(parentWidget) { this->node = parentNode; // Throttle the setGeometry calls that may happen when dealing with huge // lists. this->throttleTimer.setTimerType(Qt::PreciseTimer); this->throttleTimer.setSingleShot(true); QObject::connect(&this->throttleTimer, &QTimer::timeout, this, &FlexLayout::performLayout); } FlexLayout::~FlexLayout() { if (!this->node) { return; } const uint32_t childCount = YGNodeGetChildCount(this->node); for (uint32_t i = 0; i < childCount; i++) { const YGNodeRef oldChild = YGNodeGetChild(this->node, i); FlexNodeContext* childCtx = flexutils::getFlexNodeContext(oldChild); if (childCtx->layoutItem()) { delete childCtx->layoutItem(); childCtx->setLayoutItem(nullptr); } } YGNodeRemoveAllChildren(this->node); } void FlexLayout::addItem(QLayoutItem* item) { // Noop: We already have addWidget doing all the hard work. return; } void FlexLayout::addWidget(QWidget* childWidget, YGNodeRef childNode) { if (!this->node) { qWarning() << "Flex layout's parent yoga node not set yet. Set it using " "setFlexNode. \n" << "Child widget will not be added to Flex Layout"; return; } uint count = YGNodeGetChildCount(this->node); YGNodeInsertChild(this->node, childNode, count); FlexNodeContext* childCtx = flexutils::getFlexNodeContext(childNode); auto layoutitem = new QWidgetItem(childWidget); childCtx->setLayoutItem(layoutitem); QLayout::addWidget(childWidget); this->invalidate(); } void FlexLayout::insertChildBefore(QWidget* childWidget, YGNodeRef beforeChildNode, YGNodeRef childNode) { if (!this->node) { qWarning() << "Flex layout's parent yoga node not set yet. Set it using " "setFlexNode. \n" << "childwidget cant be inserted"; return; } uint count = YGNodeGetChildCount(this->node); uint indexToInsert = 0; for (uint i = 0; i < count; i += 1) { if (beforeChildNode == YGNodeGetChild(this->node, i)) { indexToInsert = i; break; } } YGNodeInsertChild(this->node, childNode, indexToInsert); FlexNodeContext* ctx = flexutils::getFlexNodeContext(childNode); ctx->setLayoutItem(new QWidgetItem(childWidget)); QLayout::addWidget(childWidget); this->invalidate(); } QLayoutItem* FlexLayout::itemAt(int index) const { if (!this->node || index >= static_cast(YGNodeGetChildCount(this->node))) { return nullptr; } YGNodeRef childNode = YGNodeGetChild(this->node, static_cast(index)); FlexNodeContext* childCtx = flexutils::getFlexNodeContext(childNode); return childCtx->layoutItem(); } QLayoutItem* FlexLayout::takeAt(int index) { if (!this->node || index >= static_cast(YGNodeGetChildCount(this->node))) { return nullptr; } YGNodeRef childNode = YGNodeGetChild(this->node, static_cast(index)); FlexNodeContext* ctx = flexutils::getFlexNodeContext(childNode); QLayoutItem* childLayoutItem = ctx->layoutItem(); ctx->setLayoutItem(nullptr); YGNodeRemoveChild(this->node, childNode); return childLayoutItem; } int FlexLayout::count() const { if (!this->node) { return 0; } float childCount = YGNodeGetChildCount(this->node); return static_cast(childCount); } void FlexLayout::removeWidget(QWidget* childWidget, YGNodeRef childNode) { if (!this->node) { qWarning() << "Flex layout's parent yoga node not set yet. Set it using " "setFlexNode. " << "childwidget cant be removed"; return; } FlexNodeContext* ctx = flexutils::getFlexNodeContext(childNode); if (ctx->layoutItem()) { delete ctx->layoutItem(); ctx->setLayoutItem(nullptr); } YGNodeRemoveChild(this->node, childNode); QLayout::removeWidget(childWidget); this->invalidate(); } YGNodeRef FlexLayout::getRootNode(YGNodeRef node) const { YGNodeRef parent = node->getOwner(); if (!parent) { return node; } else { return getRootNode(parent); } } bool FlexLayout::hasHeightForWidth() const { return false; } QSize FlexLayout::sizeHint() const { calculateLayout(); return QSize(YGNodeLayoutGetWidth(this->node), YGNodeLayoutGetHeight(this->node)); } QSize FlexLayout::minimumSize() const { calculateLayout(); QSize minSize = QSize(YGNodeLayoutGetWidth(this->node), YGNodeLayoutGetHeight(this->node)); return minSize; } void FlexLayout::setGeometry(const QRect& rect) { this->cachedRect = rect; if (this->throttleTimer.isActive()) { return; } this->throttleTimer.start(10); // This will call performLayout and throttle requests between 10ms. } void FlexLayout::performLayout() { if (!this->node) { return; } QRect rect = this->cachedRect; if (!rect.isValid() || rect != geometry()) { bool isSizeControlled = flexutils::isFlexNodeSizeControlled(this->node); YGValue prevStyleMinWidth = YGNodeStyleGetMinWidth(this->node); YGValue prevStyleMinHeight = YGNodeStyleGetMinHeight(this->node); if (isSizeControlled) { YGNodeMarkDirtyAndPropogateToDescendants(this->node); YGNodeStyleSetMinHeight(this->node, rect.height()); YGNodeStyleSetMinWidth(this->node, rect.width()); } calculateLayout(); uint count = YGNodeGetChildCount(this->node); for (uint i = 0; i < count; ++i) { YGNode* childNode = YGNodeGetChild(this->node, i); QRect childRect = flexutils::getFlexNodeGeometry(childNode); FlexNodeContext* ctx = flexutils::getFlexNodeContext(childNode); QLayoutItem* childItem = ctx->layoutItem(); childItem->setGeometry(childRect); } if (isSizeControlled) { restoreNodeMinStyle(prevStyleMinWidth, prevStyleMinHeight); } } QLayout::setGeometry(rect); } void FlexLayout::setFlexNode(YGNodeRef parentNode) { this->node = parentNode; } void FlexLayout::calculateLayout() const { if (YGNodeIsDirty(this->node)) { YGNodeRef rootNode = getRootNode(this->node); YGDirection rootDirection = YGNodeStyleGetDirection(rootNode); YGNodeCalculateLayout(rootNode, YGUndefined, YGUndefined, rootDirection); } } void FlexLayout::restoreNodeMinStyle(YGValue& previousMinWidth, YGValue& previousMinHeight) { if (previousMinHeight.unit == YGUnitPercent) { YGNodeStyleSetMinHeightPercent(this->node, previousMinHeight.value); } else { YGNodeStyleSetMinHeight(this->node, previousMinHeight.value); } if (previousMinWidth.unit == YGUnitPercent) { YGNodeStyleSetMinWidthPercent(this->node, previousMinWidth.value); } else { YGNodeStyleSetMinWidth(this->node, previousMinWidth.value); } }// // Copyright 2016 Pixar // // Licensed under the Apache License, Version 2.0 (the "Apache License") // with the following modification; you may not use this file except in // compliance with the Apache License and the following modification to it: // Section 6. Trademarks. is deleted and replaced with: // // 6. Trademarks. This License does not grant permission to use the trade // names, trademarks, service marks, or product names of the Licensor // and its affiliates, except as required to comply with Section 4(c) of // the License and to reproduce the content of the NOTICE file. // // You may obtain a copy of the Apache License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the Apache License with the above modification is // distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the Apache License for the specific // language governing permissions and limitations under the Apache License. // #include "pxr/usd/usdSkel/tokens.h" PXR_NAMESPACE_OPEN_SCOPE UsdSkelTokensType::UsdSkelTokensType() : bindTransforms("bindTransforms", TfToken::Immortal), blendShapes("blendShapes", TfToken::Immortal), blendShapeWeights("blendShapeWeights", TfToken::Immortal), joints("joints", TfToken::Immortal), offsets("offsets", TfToken::Immortal), pointIndices("pointIndices", TfToken::Immortal), primvarsSkelGeomBindTransform("primvars:skel:geomBindTransform", TfToken::Immortal), primvarsSkelJointIndices("primvars:skel:jointIndices", TfToken::Immortal), primvarsSkelJointWeights("primvars:skel:jointWeights", TfToken::Immortal), restTransforms("restTransforms", TfToken::Immortal), rotations("rotations", TfToken::Immortal), scales("scales", TfToken::Immortal), skelAnimationSource("skel:animationSource", TfToken::Immortal), skelBlendShapes("skel:blendShapes", TfToken::Immortal), skelBlendShapeTargets("skel:blendShapeTargets", TfToken::Immortal), skelJoints("skel:joints", TfToken::Immortal), skelSkeleton("skel:skeleton", TfToken::Immortal), translations("translations", TfToken::Immortal), weight("weight", TfToken::Immortal), allTokens({ bindTransforms, blendShapes, blendShapeWeights, joints, offsets, pointIndices, primvarsSkelGeomBindTransform, primvarsSkelJointIndices, primvarsSkelJointWeights, restTransforms, rotations, scales, skelAnimationSource, skelBlendShapes, skelBlendShapeTargets, skelJoints, skelSkeleton, translations, weight }) { } TfStaticData UsdSkelTokens; PXR_NAMESPACE_CLOSE_SCOPE #include #include #include #include "xlogger.h" #include "address.h" #include "tcpserver.h" #include "connection.h" #include "httpserver.h" #include "httprequest.h" #include "httpresponse.h" #include "httpconnection.h" using namespace std; using namespace tnet; using namespace std::placeholders; void onHandler(const HttpConnectionPtr_t& conn, const HttpRequest& request) { HttpResponse resp; resp.statusCode = 200; resp.setContentType("text/html"); resp.setKeepAlive(true); resp.enableDate(); resp.body.append("Hello World"); conn->send(resp); } int main(int argc, char* argv[]) { XLOGGER(argv[0]).StdErr(true).Colour(true).Dir("./logs"); TcpServer s; HttpServer httpd(&s); httpd.setHttpCallback("/change", std::bind(&onHandler, _1, _2)); httpd.listen(Address(11181)); XINFO("start tcp server"); s.start(4); XINFO("stop server"); return 0; } src/arch/x86/info/cr.cpp #include "arch/x86.h" #include "screen.h" #include "klib.h" static const char * cr0_flags_str[32] { "PE -- protected mode enable bit", "MP -- monitor co-processor", "EM -- x87 is present", "TS -- x87 task switched", "ET -- x87 type", "NE -- x87 numeric error", FORC8("reserved -- unused"), "reserved -- unused", "reserved -- unused", "WP -- ring 0 write protect", "reserved -- unused", "AM -- ring 3 alignment check", FORC8("reserved -- unused"), "reserved -- unused", "reserved -- unused", "NW -- write-through caching disable bit", "CD -- memory caching disable bit", "PG -- paging enable bit", }; static const char * cr4_flags_str[32] { "VME -- V8086 mode virtual interrupt support", "PVI -- protected mode virtual interrupt support", "TSD -- RDTSC only in ring0?", "DE -- debugging extensions enabled", "PSE -- is Page Size Extension (page size 4MB) enabled?", "PAE -- is Physical Address Extension enabled?", "MCE -- enable machine check interrupts", "PGE -- page global enabled", "PCE -- RDPCM at any priviledge?", "OSFXSR -- enable FXSAVE FXRSTOR", "OSXMMEXCPT -- enable unmasked SSE exceptions", "UMIP -- prevent usermode access to SGDT, SIDT, SLDT, SMSW and STR", "LA57 -- enable 5-level paging", "VMXE -- VT-x, Intel Virtualization Technology", "SMXE -- Intel Trusted Execution Technology", "reserved -- unused", "FSGSBASE -- enable RDFSBASE RDGSBASE WRFSBASE WRGSBASE", "PCIDE -- enable PCID", "OSXAVE -- enable XSAVE", "reserved -- unused", "SMEP -- enable Supervisor Mode Execution Protection", "SMAP -- enable Supervisor Mode Access Prevention", "PKE -- enable Protection Key", FORC8("reserved -- unused"), "reserved -- unused", }; void CR::cmd_crdump(){ uint32_t lines=0; Screen::setfgcolor(Screen::LIGHT_CYAN); k_puts("\nCR0"); Screen::setfgcolor(Screen::WHITE); lines++; uint32_t cr0=CR0::get(); for(uint32_t i=0;i<32;i++){ if(cr0&(1<20){ k_puts("\npress any key to continue..."); k_getch_extended(); lines=0; } Screen::setfgcolor(Screen::LIGHT_CYAN); k_puts("CR3"); Screen::setfgcolor(Screen::WHITE); k_putc('='); k_puth(CR3::get()); k_putc('\n'); Screen::setfgcolor(Screen::LIGHT_CYAN); k_puts("CR4"); Screen::setfgcolor(Screen::WHITE); lines++; uint32_t cr4=CR4::get(); for(uint32_t i=0;i<32;i++){ if(cr4&(1<().c_str()); vbs.checkpointId = std::stoull(j.at("checkpoint_id").get()); vbs.maxDeletedSeqno = std::stoull(j.at("max_deleted_seqno").get()); vbs.highSeqno = std::stoll(j.at("high_seqno").get()); vbs.purgeSeqno = std::stoull(j.at("purge_seqno").get()); vbs.lastSnapStart = std::stoull(j.at("snap_start").get()); vbs.lastSnapEnd = std::stoull(j.at("snap_end").get()); vbs.maxCas = std::stoull(j.at("max_cas").get()); vbs.hlcCasEpochSeqno = std::stoll(j.at("hlc_epoch").get()); vbs.mightContainXattrs = j.at("might_contain_xattrs").get(); vbs.supportsNamespaces = j.at("namespaces_supported").get(); // Now parse optional fields. auto failoverIt = j.find("failover_table"); if (failoverIt != j.end()) { vbs.failovers = failoverIt->dump(); } auto topologyIt = j.find("replication_topology"); if (topologyIt != j.end()) { vbs.replicationTopology = *topologyIt; } auto version = j.find("version"); if (version != j.end()) { vbs.version = (*version).get(); } else { vbs.version = 1; } } #include #include #include #include #include using namespace std; int main(int argc, char *argv[]) { int numValid = 0; vector totals; if (argc != 2) { cout << "Incorrect number of arguments" << endl; return -1; } ifstream infile(argv[1]); string line; while (getline(infile, line)) { stringstream stream(line); vector words; while(stream) { string currWord; stream >> currWord; words.push_back(currWord); } bool validPhrase = true; for (uint i = 0; i < words.size(); i++) { for (uint j = i+1; j < words.size(); j++) { if (!words[i].compare(words[j])) { validPhrase = false; break; } } if (!validPhrase) break; } if (validPhrase) numValid++; } cout << "Total number of valid passphrases = " << numValid << endl; return 0; } gerickson/openhlx /* * Copyright (c) 2021 * 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. * */ /** * @file * This file implements a derivable object for realizing a HLX * infrared remote control interface controller, in a server. * */ #include "InfraredControllerBasis.hpp" #include #include using namespace HLX::Common; using namespace HLX::Model; using namespace HLX::Utilities; using namespace Nuovations; namespace HLX { namespace Server { // Class-scoped Command Request Regular Expression Data /** * Class-scoped server infrared query command request regular expression. * */ Server::Command::Infrared::QueryRequest InfraredControllerBasis::kQueryRequest; /** * Class-scoped server infrared set disabled state command request * regular expression. * */ Server::Command::Infrared::SetDisabledRequest InfraredControllerBasis::kSetDisabledRequest; /** * @brief * This is a class constructor. * * This constructs the infrared controller with the specified * infrared model. * * @param[in] aInfraredModel A mutable reference to the infrared * model to construct the controller * with. This is retained by a weak * pointer reference and, consequently, * must remain in scope for the lifetime * of the controller. * */ InfraredControllerBasis :: InfraredControllerBasis(Model::InfraredModel &aInfraredModel) : Server::ObjectControllerBasis(), mInfraredModel(aInfraredModel) { return; } /** * @brief * This is the class destructor. * */ InfraredControllerBasis :: ~InfraredControllerBasis(void) { return; } // MARK: Initializer(s) /** * @brief * This is the class initializer. * * This initializes the class with the specified command manager. * * @param[in] aCommandManager A reference to the command manager * instance to initialize the controller * with. * * @retval kStatus_Success If successful. * @retval -EINVAL If an internal parameter was * invalid. * @retval -ENOMEM If memory could not be allocated. * @retval kError_NotInitialized The base class was not properly * initialized. * @retval kError_InitializationFailed If initialization otherwise failed. * */ Status InfraredControllerBasis :: Init(CommandManager &aCommandManager) { DeclareScopedFunctionTracer(lTracer); Status lRetval = kStatus_Success; lRetval = RequestInit(); nlREQUIRE_SUCCESS(lRetval, done); lRetval = ObjectControllerBasis::Init(aCommandManager); nlREQUIRE_SUCCESS(lRetval, done); done: return (lRetval); } // MARK: Implementation Status InfraredControllerBasis :: RequestInit(void) { Status lRetval = kStatus_Success; // Initialize static command request regular expression pattern data. lRetval = kQueryRequest.Init(); nlREQUIRE_SUCCESS(lRetval, done); lRetval = kSetDisabledRequest.Init(); nlREQUIRE_SUCCESS(lRetval, done); done: return (lRetval); } // MARK: Observation (Query) Command Request Handlers // MARK: Observation (Query) Command Request Instance Handlers /** * @brief * Handle and generate the server command response for an infrared * query request. * * This handles and generates the server command response for an * infrared query request. * * @param[in,out] aBuffer A mutable reference to the shared * pointer into which the response is to be * generated. * * @retval kStatus_Success If successful. * @retval kError_NotInitialized If the infrared model has * not been completely and successfully * initialized. * @retval -ENOMEM If the buffer-owned backing store * cannot be allocated. * @retval -ENOSPC If the requested size exceeds the * buffer capacity. * */ Status InfraredControllerBasis :: HandleQueryReceived(Common::ConnectionBuffer::MutableCountedPointer &aBuffer) const { InfraredModel::DisabledType lDisabled; Status lRetval; lRetval = mInfraredModel.GetDisabled(lDisabled); nlREQUIRE_SUCCESS(lRetval, done); lRetval = HandleDisabledResponse(lDisabled, aBuffer); nlREQUIRE_SUCCESS(lRetval, done); done: return (lRetval); } // MARK: Observation (Query) Command Request Class (Static) Handlers // MARK: Command Response Handlers // MARK: Command Response Class (Static) Handlers /** * @brief * Handle and generate the server command response for an infrared * disabled state request. * * This handles and generates the server command response for an * infrared disabled state request. * * @param[in] aDisabled An immutable reference to the infrared * disabled state for which the response * is to be formed. * @param[in,out] aBuffer A mutable reference to the shared * pointer into which the response is to * be generated. * * @retval kStatus_Success If successful. * @retval -ENOMEM If the buffer-owned backing store * cannot be allocated. * @retval -ENOSPC If the requested size exceeds the * buffer capacity. * */ /* static */ Status InfraredControllerBasis :: HandleDisabledResponse(const InfraredModel::DisabledType &aDisabled, ConnectionBuffer::MutableCountedPointer &aBuffer) { Server::Command::Infrared::DisabledResponse lDisabledResponse; const uint8_t * lBuffer; size_t lSize; Status lStatus; lStatus = lDisabledResponse.Init(aDisabled); nlREQUIRE_SUCCESS(lStatus, done); lBuffer = lDisabledResponse.GetBuffer(); lSize = lDisabledResponse.GetSize(); lStatus = Common::Utilities::Put(*aBuffer.get(), lBuffer, lSize); nlREQUIRE_SUCCESS(lStatus, done); done: return (lStatus); } }; // namespace Server }; // namespace HLX // This file was generated by Rcpp::compileAttributes // Generator token: #include using namespace Rcpp; // metadataFeather List metadataFeather(const std::string& path); RcppExport SEXP feather_metadataFeather(SEXP pathSEXP) { BEGIN_RCPP Rcpp::RObject __result; Rcpp::RNGScope __rngScope; Rcpp::traits::input_parameter< const std::string& >::type path(pathSEXP); __result = Rcpp::wrap(metadataFeather(path)); return __result; END_RCPP } // readFeather List readFeather(const std::string& path); RcppExport SEXP feather_readFeather(SEXP pathSEXP) { BEGIN_RCPP Rcpp::RObject __result; Rcpp::RNGScope __rngScope; Rcpp::traits::input_parameter< const std::string& >::type path(pathSEXP); __result = Rcpp::wrap(readFeather(path)); return __result; END_RCPP } // writeFeather void writeFeather(DataFrame df, const std::string& path); RcppExport SEXP feather_writeFeather(SEXP dfSEXP, SEXP pathSEXP) { BEGIN_RCPP Rcpp::RNGScope __rngScope; Rcpp::traits::input_parameter< DataFrame >::type df(dfSEXP); Rcpp::traits::input_parameter< const std::string& >::type path(pathSEXP); writeFeather(df, path); return R_NilValue; END_RCPP } 0 // // Created by Ciaran on 09/11/2020. // #include "omexmeta/UriHandler.h" #include "omexmeta/OmexMetaUtils.h" #include namespace omexmeta { const std::string &UriHandler::getRepository() const { return repository_; } UriHandler &UriHandler::setRepository(const std::string &repository) { // we need to remember to update the strings that depend on repository_ if (OmexMetaUtils::endsWith(repository, "/")) { model_ = OmexMetaUtils::stringReplace(model_, repository_, repository); archive_ = OmexMetaUtils::stringReplace(archive_, repository_, repository); local_ = OmexMetaUtils::stringReplace(local_, repository_, repository); repository_ = repository; } else { model_ = OmexMetaUtils::stringReplace(model_, repository_, repository + "/"); archive_ = OmexMetaUtils::stringReplace(archive_, repository_, repository + "/"); local_ = OmexMetaUtils::stringReplace(local_, repository_, repository + "/"); repository_ = repository + "/"; } return *this; } const std::string &UriHandler::getArchive() const { return archive_; } UriHandler &UriHandler::setArchive(const std::string &archiveName) { if (OmexMetaUtils::startsWith(archiveName, "http")) { throw std::invalid_argument("std::invalid_argument: RDF::setArchiveUri: " "Specified \"archiveName\" argument \"" + archiveName + "\" begins with \"http\". Since the archive url is built " "using the repositoryName argument, please only specify " "the name of the omex archive. Like \"myOmexFile.omex\""); } // remove the repository uri section from archive uri std::string archive_without_repository = OmexMetaUtils::stringReplace(archive_, repository_, ""); // now we replace the archive minus repository name part of model and local if (OmexMetaUtils::endsWith(archiveName, "/")) { model_ = OmexMetaUtils::stringReplace(model_, archive_without_repository, archiveName); local_ = OmexMetaUtils::stringReplace(local_, archive_without_repository, archiveName); archive_ = repository_ + archiveName + "/"; } else { model_ = OmexMetaUtils::stringReplace(model_, archive_without_repository, archiveName + "/"); local_ = OmexMetaUtils::stringReplace(local_, archive_without_repository, archiveName + "/"); archive_ = repository_ + archiveName + "/"; } return *this; } const std::string &UriHandler::getModel() const { return model_; } UriHandler &UriHandler::setModel(std::string modelName) { if (OmexMetaUtils::startsWith(modelName, "http")) { throw std::invalid_argument("std::invalid_argument: RDF::setModelUri: " "Specified \"modelName\" argument \"" + modelName + "\" begins with \"http\". Since the model url is built " "using the repositoryName argument, please only specify " "the name of the model. Like \"NewModel.sbml\""); } // first we make sure the suffix ends with a "#" if (!OmexMetaUtils::endsWith(modelName, "#")) { modelName += "#"; } // Now we check for file extension std::vector suffexes = {".xml#", ".sbml#", ".cellml#"}; bool good = false; for (auto &it : suffexes) { if (OmexMetaUtils::endsWith(modelName, it)) { good = true; } } // automatically add .xml if one of the above suffixes was not detected if (!good) { // remember to remove the trailing "#" modelName.pop_back(); modelName += ".xml#"; } // concatonate archive and model, being sensitive to ending "/" if (OmexMetaUtils::endsWith(getArchive(), "/")) { model_ = getArchive() + modelName; } else { model_ = getArchive() + "/" + modelName; } // Since the model name is also used for the local name we // figure that out here. We know modelName definitely contains // a suffux like .xml. // we need to remove it so we can add .rdf. // We do this in a way that enables multiple "." in a model_name std::vector split = OmexMetaUtils::splitStringBy(modelName, '.'); if (split.size() <= 1) { throw std::logic_error("std::logic_error: RDF::setModelUri: You should never get a " "a value less than 2 here because you are splitting a string. " "If you are seeing this message this is a bug. Please report " "it as a github issue (https://github.com/sys-bio/libOmexMeta/issues)"); } // remove the last element which should contain the extension. split.pop_back(); // docs-build up the string again with any dots that appeared before the final std::ostringstream os; for (auto &it : split) { os << it << "."; } // Now we can docs-build up the local string if (OmexMetaUtils::endsWith(getArchive(), "/")) { local_ = getArchive() + os.str() + "rdf#"; } else { local_ = getArchive() + "/" + os.str() + "rdf#"; } return *this; } const std::string &UriHandler::getLocal() const { return local_; } std::string UriHandler::uriModifier(std::string uri_to_modify, eUriType type) const { switch (type) { case NONE: return uri_to_modify; case LOCAL_URI: return OmexMetaUtils::concatMetaIdAndUri(uri_to_modify, getLocal()); case MODEL_URI: return OmexMetaUtils::concatMetaIdAndUri(uri_to_modify, getModel()); case IDENTIFIERS_URI: return OmexMetaUtils::concatMetaIdAndUri(uri_to_modify, "https://identifiers.org/"); } } }// namespace omexmetafrannuca/quantlib /* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* Copyright (C) 2006, 2007, 2009, 2010 This file is part of QuantLib, a free-software/open-source library for financial quantitative analysts and developers - http://quantlib.org/ QuantLib is free software: you can redistribute it and/or modify it under the terms of the QuantLib license. You should have received a copy of the license along with this program; if not, please email <>. The license is also available online at . 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 license for more details. */ #if defined(HAVE_CONFIG_H) #include #endif #include #include #include #include #include using std::pair; using std::vector; using boost::shared_ptr; using boost::dynamic_pointer_cast; using ObjectHandler::ValueObject; using ObjectHandler::Create; using QuantLib::Real; using QuantLib::Size; using QuantLib::EndCriteria; using QuantLib::OptimizationMethod; using QuantLib::Handle; using QuantLib::Quote; namespace QuantLibAddin { namespace { class QuoteHandleSorter { public: bool operator()(const pair >& h1, const pair >& h2) const { if (h1.first >= h2.first) return false; return true; } }; } Interpolation::Interpolation(const shared_ptr& prop, const vector& x, const vector >& yh, bool permanent) : Extrapolator(prop, permanent) { QL_REQUIRE(!x.empty(), "empty x vector"); Size n = x.size(); QL_REQUIRE(n==yh.size(), "unmatched size between x (" << n << ") and y(" << yh.size() << ")"); x_.reserve(n); yh_.reserve(n); y_.reserve(n); vector > > pairs(n); for (Size i=0; i > >::iterator j=pairs.begin(); x_.push_back(j->first); yh_.push_back(j->second); registerWith(yh_.back()); yh_.back()->isValid() ? y_.push_back(yh_.back()->value()) : y_.push_back(1.0); for (j=pairs.begin()+1; jfirst) { QL_ENSURE(yh_.back() == j->second, "duplicated x value (" << j->first << ") with different y values"); } else { x_.push_back(j->first); yh_.push_back(j->second); registerWith(yh_.back()); yh_.back()->isValid() ? y_.push_back(yh_.back()->value()) : y_.push_back(1.0); } } n_ = x_.size(); } void Interpolation::performCalculations() const { for (Size i=0; ivalue(); qlInterpolation_->update(); } GenericInterp::GenericInterp(const shared_ptr& p, const std::string& type, const vector& x, const vector >& yh, bool permanent) : Interpolation(p, x, yh, permanent) { libraryObject_ = Create >() (type, x_.begin(), x_.end(), y_.begin()); qlInterpolation_ = dynamic_pointer_cast( libraryObject_); } MixedLinearCubicInterpolation::MixedLinearCubicInterpolation( const shared_ptr& properties, const vector& x, const vector >& yh, QuantLib::Size n, QuantLib::CubicInterpolation::DerivativeApprox da, bool monotonic, QuantLib::CubicInterpolation::BoundaryCondition leftCondition, Real leftValue, QuantLib::CubicInterpolation::BoundaryCondition rightCondition, Real rightValue, bool permanent) : Interpolation(properties, x, yh, permanent) { libraryObject_ = shared_ptr(new QuantLib::MixedLinearCubicInterpolation( x_.begin(), x_.end(), y_.begin(), n, da, monotonic, leftCondition, leftValue, rightCondition, rightValue)); qlInterpolation_ = dynamic_pointer_cast(libraryObject_); qlMixedLinearCubicInterpolation_ = dynamic_pointer_cast(libraryObject_); } CubicInterpolation::CubicInterpolation( const shared_ptr& properties, const vector& x, const vector >& yh, QuantLib::CubicInterpolation::DerivativeApprox da, bool monotonic, QuantLib::CubicInterpolation::BoundaryCondition leftCondition, Real leftValue, QuantLib::CubicInterpolation::BoundaryCondition rightCondition, Real rightValue, bool permanent) : Interpolation(properties, x, yh, permanent) { libraryObject_ = shared_ptr(new QuantLib::CubicInterpolation(x_.begin(), x_.end(), y_.begin(), da, monotonic, leftCondition, leftValue, rightCondition, rightValue)); qlInterpolation_ = dynamic_pointer_cast( libraryObject_); qlCubicInterpolation_ = dynamic_pointer_cast( libraryObject_); } AbcdInterpolation::AbcdInterpolation( const shared_ptr& properties, const vector& x, const vector >& yh, Real a, Real b, Real c, Real d, bool aIsFixed, bool bIsFixed, bool cIsFixed, bool dIsFixed, bool vegaWeighted, const shared_ptr& ec, const shared_ptr& om, bool permanent) : Interpolation(properties, x, yh, permanent) { libraryObject_ = shared_ptr(new QuantLib::AbcdInterpolation(x_.begin(), x_.end(), y_.begin(), a, b, c, d, aIsFixed, bIsFixed, cIsFixed, dIsFixed, vegaWeighted, ec, om)); qlInterpolation_ = dynamic_pointer_cast( libraryObject_); qlAbcdInterpolation_ = dynamic_pointer_cast( libraryObject_); } SABRInterpolation::SABRInterpolation( const shared_ptr& p, const vector& x, const vector >& yh, QuantLib::Time t, Handle forwardh, Real alpha, Real beta, Real nu, Real rho, bool isAlphaFixed, bool isBetaFixed, bool isNuFixed, bool isRhoFixed, bool vegaWeighted, const shared_ptr& ec, const shared_ptr& om, bool permanent) : Interpolation(p, x, yh, permanent), forwardh_(forwardh), forward_(0.01) { libraryObject_ = shared_ptr(new QuantLib::SABRInterpolation(x_.begin(), x_.end(), y_.begin(), t, forward_, alpha, beta, nu, rho, isAlphaFixed, isBetaFixed, isNuFixed, isRhoFixed, vegaWeighted, ec, om)); qlInterpolation_ = dynamic_pointer_cast( libraryObject_); qlSABRInterpolation_ = dynamic_pointer_cast( libraryObject_); } } components/common/sources/strlib/str_buffer_compression.cpp #include #include namespace common { /* Компрессия / декомпрессия последовательности байт в символы */ void decompress_buffer (size_t buffer_size, const void* src_buffer, char* dst_buffer) { if (buffer_size) { if (!src_buffer) throw xtl::make_null_argument_exception ("common::decompress_buffer", "src_buffer"); if (!dst_buffer) throw xtl::make_null_argument_exception ("common::decompress_buffer", "dst_buffer"); } const char* src = (const char*)src_buffer; char* dst = dst_buffer; for (size_t i=0; iCleanRender/Gui.cpp #include "Gui.h" #include #include #include #include "Engine.h" #include "Window.h" #include "EntityManager.h" #include "Input.h" #include "Time.h" #include "Mesh.h" #include "ShaderProgram.h" #include "PhysicsWorld.h" Gui::Gui(Window* window) : window(window) { IMGUI_CHECKVERSION(); ImGui::CreateContext(); ImGuiIO& io = ImGui::GetIO(); (void) io; ImGui::StyleColorsDark(); ImGui_ImplGlfw_InitForOpenGL(window->glfwWindow(), true); ImGui_ImplOpenGL3_Init("#version 400"); } Gui::~Gui() { ImGui_ImplOpenGL3_Shutdown(); ImGui_ImplGlfw_Shutdown(); ImGui::DestroyContext(); } void Gui::update() { ImGui_ImplOpenGL3_NewFrame(); ImGui_ImplGlfw_NewFrame(); ImGui::NewFrame(); if (Input::getKeyDown(KeyCode::GRAVE_ACCENT)) { debugDisplayed = !debugDisplayed; } if (debugDisplayed) { if (Input::getKeyDown(KeyCode::F1)) { statsDisplayed = !statsDisplayed; } if (Input::getKeyDown(KeyCode::F2)) { sceneDisplayed = !sceneDisplayed; } if (Input::getKeyDown(KeyCode::F3)) { shadersDisplayed = !shadersDisplayed; } if (Input::getKeyDown(KeyCode::F4)) { physicsDisplayed = !physicsDisplayed; Engine::physicsWorld->debug = physicsDisplayed; } } onUpdate(); Mesh::triangleCount = 0; } void Gui::onUpdate() { if (debugDisplayed) { ImGui::BeginMainMenuBar(); if (ImGui::MenuItem("Stats")) { statsDisplayed = !statsDisplayed; } if (ImGui::MenuItem("Scene")) { sceneDisplayed = !sceneDisplayed; } if (ImGui::MenuItem("Shaders")) { shadersDisplayed = !shadersDisplayed; } if (ImGui::MenuItem("Physics")) { physicsDisplayed = !physicsDisplayed; Engine::physicsWorld->debug = physicsDisplayed; } ImGui::EndMainMenuBar(); if (statsDisplayed) { ImGui::Begin("Engine Stats"); addFrameTime(Time::deltaTime); ImGui::PlotLines("Delta Times", frameTimes, 300, 0, '\0', 0, maxFrameTime); ImGui::Indent(); ImGui::Text("(max: %.3fms)", maxFrameTime * 1000); ImGui::Unindent(); ImGui::Text("Average Frame time: %.3fms", 1000.0f / ImGui::GetIO().Framerate); ImGui::Text("FPS: %.1f", ImGui::GetIO().Framerate); ImGui::Text("Triangles: %i", Mesh::triangleCount); ImGui::End(); } if (sceneDisplayed) { ImGui::Begin("Scene"); Engine::entityManager->gui(); ImGui::End(); } if (shadersDisplayed) { ImGui::Begin("ShaderPrograms"); ShaderProgram::guiAll(); ImGui::End(); } } } void Gui::render() { ImGui::Render(); ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData()); } void Gui::initFrameTimes() { for (int i = 0; i < 300; i++) { frameTimes[i] = 0; } } void Gui::addFrameTime(float time) { maxFrameTime = 0; for (int i = 0; i < 299; i++) { frameTimes[i] = frameTimes[i + 1]; if (frameTimes[i] > maxFrameTime) { maxFrameTime = frameTimes[i]; } } frameTimes[299] = time; if (time > maxFrameTime) { maxFrameTime = time; } } #pragma once #include #include #include #include // hash #include #include #ifdef _WIN32 struct _GUID; // GUID and UUID. #endif namespace stud { // Universally-unique identifier (UUID), RFC4122: // // https://tools.ietf.org/html/rfc4122 // The UUID variant (type). Nil UUID is DCE. // enum class uuid_variant { ncs, // NCS backward compatibility. dce, // DCE 1.1/RFC4122. microsoft, // Microsoft backward compatibility. other // Currently reserved for possible future definition. }; // The DCE UUID version (sub-type). Nil UUID is random. // enum class uuid_version { time = 1, // Time-based. security = 2, // DCE Security with embedded POSIX UIDs. md5 = 3, // Name-based with MD5 hashing. random = 4, // Randomly or pseudo-randomly generated. sha1 = 5 // Name-based with SHA1 hashing. }; class LIBSTUD_UUID_SYMEXPORT uuid_system_generator; struct LIBSTUD_UUID_SYMEXPORT uuid { // Normally not accessed directly (see RFC4122 Section 4.1.2). // std::uint32_t time_low = 0; std::uint16_t time_mid = 0; std::uint16_t time_hiv = 0; // hi_and_version std::uint8_t clock_seq_hir = 0; // hi_and_reserved std::uint8_t clock_seq_low = 0; std::uint8_t node[6] = {0, 0, 0, 0, 0, 0}; // System UUID generator. See the uuid_generator interface for details. // // Note: system generator cannot be called during static initialization. // static uuid_system_generator system_generator; static uuid generate (bool strong = true); // Create a nil UUID (all members are 0). // uuid () = default; bool nil () const; explicit operator bool () const; // Create a UUID from a 16-octet binary representation with the sizes and // order of the fields as defined in RFC4122 Section 4.1.2 and with each // field encoded with the most significant byte first (also known as // big-endian or network byte order). // using binary_type = std::array; explicit uuid (const binary_type&); void assign (const binary_type&); binary_type binary () const noexcept; // Note that this constructor is compatible with libuuid's uuid_t type. // explicit uuid (const std::uint8_t (&)[16]); void assign (const std::uint8_t (&)[16]); #ifdef _WIN32 // Create a UUID from Win32 GUID. // uuid (const _GUID&); void assign (const _GUID&); template G guid () const; #endif // Create a UUID from a 36-character string representation in the // // xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx // // form which can be in lower or upper case. Throw std::invalid_argument // if the representation is invalid. // // The returned string representation is by default in lower case. // explicit uuid (const std::string&); explicit uuid (const char*); void assign (const std::string&); void assign (const char*); std::string string (bool upper = false) const; std::array c_string (bool upper = false) const; // UUID variant (type) and version (sub-type). // using variant_type = uuid_variant; using version_type = uuid_version; variant_type variant () const; version_type version () const; // UUID comparison. // int compare (const uuid&) const; // Swapping and moving. On move we make the moved-from instance nil. // void swap (uuid&); uuid (uuid&&); uuid (const uuid&) = default; uuid& operator= (uuid&&); uuid& operator= (const uuid&) = default; }; bool operator== (const uuid&, const uuid&); bool operator!= (const uuid&, const uuid&); bool operator< (const uuid&, const uuid&); bool operator> (const uuid&, const uuid&); bool operator<= (const uuid&, const uuid&); bool operator>= (const uuid&, const uuid&); // For iostream operators see uuid-io.hxx. // UUID generator interface. // class LIBSTUD_UUID_SYMEXPORT uuid_generator { public: virtual ~uuid_generator () = default; // Generate a UUID. If strong is true (default), generate a strongly- // unique UUID. Throw std::runtime_error to report errors, including if // strong uniqueness cannot be guaranteed. // // A weak UUID is not guaranteed to be unique, neither universialy nor // locally (that is, on the machine it has been generated). // virtual uuid generate (bool strong = true) = 0; }; // System UUID generator. // class LIBSTUD_UUID_SYMEXPORT uuid_system_generator: public uuid_generator { public: // Throw std::system_error with the generic category and ENOTSUP error // code if strong uniqueness cannot be guaranteed. // virtual uuid generate (bool strong = true) override; // Optional explicit initialization and termination. Note that it is not // thread-safe and must only be performed once (normally from main()) // before/after any calls to generate(), respectively. Both functions may // throw std::runtime_error to report errors. // static void initialize (); static void terminate (); }; } namespace std { template <> struct hash { using argument_type = stud::uuid; using result_type = size_t; size_t operator() (const stud::uuid&) const noexcept; }; } #include //------------------------------------------------------------------------------ // d3d9vertexbuffer.cc // (C) 2007 Radon Labs GmbH //------------------------------------------------------------------------------ #include "stdneb.h" #include "coregraphics/win360/d3d9vertexbuffer.h" namespace Direct3D9 { __ImplementClass(Direct3D9::D3D9VertexBuffer, 'D9VB', Base::VertexBufferBase); using namespace CoreGraphics; //------------------------------------------------------------------------------ /** */ D3D9VertexBuffer::D3D9VertexBuffer() : d3d9VertexBuffer(0), mapCount(0) { // empty } //------------------------------------------------------------------------------ /** */ D3D9VertexBuffer::~D3D9VertexBuffer() { n_assert(0 == this->d3d9VertexBuffer); n_assert(0 == this->mapCount); } //------------------------------------------------------------------------------ /** */ void D3D9VertexBuffer::Unload() { n_assert(0 == this->mapCount); if (0 != this->d3d9VertexBuffer) { this->d3d9VertexBuffer->Release(); this->d3d9VertexBuffer = 0; } VertexBufferBase::Unload(); } //------------------------------------------------------------------------------ /** */ void* D3D9VertexBuffer::Map(MapType mapType) { n_assert(0 != this->d3d9VertexBuffer); DWORD lockFlags = 0; switch (mapType) { case MapRead: // deactivated by Georg granted by Floh //n_assert(((UsageDynamic == this->usage) || (UsageCpu == this->usage)) && (AccessRead == this->access)); break; case MapWrite: n_assert(((UsageDynamic == this->usage) || (UsageCpu == this->usage)) && (AccessWrite == this->access)); break; case MapReadWrite: n_assert(((UsageDynamic == this->usage) || (UsageCpu == this->usage)) && (AccessReadWrite == this->access)); break; case MapWriteDiscard: n_assert((UsageDynamic == this->usage) && (AccessWrite == this->access)); #if __WIN32__ lockFlags |= D3DLOCK_DISCARD; #endif break; case MapWriteNoOverwrite: n_assert((UsageDynamic == this->usage) && (AccessWrite == this->access)); lockFlags |= D3DLOCK_NOOVERWRITE; break; } void* ptr = 0; HRESULT hr = this->d3d9VertexBuffer->Lock(0, 0, &ptr, lockFlags); n_assert(SUCCEEDED(hr)); this->mapCount++; return ptr; } //------------------------------------------------------------------------------ /** */ void D3D9VertexBuffer::Unmap() { n_assert(0 != this->d3d9VertexBuffer); n_assert(this->mapCount > 0); HRESULT hr = this->d3d9VertexBuffer->Unlock(); n_assert(SUCCEEDED(hr)); this->mapCount--; } } // namespace Win360 #include "chjpch.h" #include "CherryJamApplication.h" #include "EditorLayer.h" #include "CherriesX/Core/EntryPoint.h" namespace Cherries { CherriesJamApplication::CherriesJamApplication() { PushOverlay(new EditorLayer()); } CherriesJamApplication::~CherriesJamApplication() { } }/** @file t100_test1.cpp @note Copyright (c) 2008 <>. Distributed under the Boost Software License, Version 1.0. See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt See http://www.boost.org/libs/smart_ptr/doc/index.html for documentation. */ #include #include #include #include #include #include "t100.h" using namespace std; using namespace boost; using boost::detail::sh::neuron_sight; int main(int argv, char * argc[]) { proxy_ptr t100; t100 = new block(t100, "I eat ([a-z]+) then drink ([a-z]+)"); t100->sub_[0].second = new block(t100, "beef|chicken"); t100->sub_[1].second = new block(t100, "vodka|water"); cout << (* t100)("I eat beef then drink vodka") << endl; cout << (* t100)("I eat beef then drink wine") << endl; cout << (* t100)("I eat fish then drink wine") << endl; cout << (* t100)("I eat fish then drink beer") << endl; } 100-1000 // Copyright (C) 2019-2021 Internet Systems Consortium, Inc. ("ISC") // // 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 #include #include #include using namespace isc::asiolink; namespace ph = std::placeholders; namespace isc { namespace http { HttpListenerImpl::HttpListenerImpl(IOService& io_service, const asiolink::IOAddress& server_address, const unsigned short server_port, const TlsContextPtr& tls_context, const HttpResponseCreatorFactoryPtr& creator_factory, const long request_timeout, const long idle_timeout) : io_service_(io_service), tls_context_(tls_context), acceptor_(), endpoint_(), connections_(), creator_factory_(creator_factory), request_timeout_(request_timeout), idle_timeout_(idle_timeout) { // Create the TCP or TLS acceptor. if (!tls_context) { acceptor_.reset(new HttpAcceptor(io_service)); } else { acceptor_.reset(new HttpsAcceptor(io_service)); } // Try creating an endpoint. This may cause exceptions. try { endpoint_.reset(new TCPEndpoint(server_address, server_port)); } catch (...) { isc_throw(HttpListenerError, "unable to create TCP endpoint for " << server_address << ":" << server_port); } // The factory must not be null. if (!creator_factory_) { isc_throw(HttpListenerError, "HttpResponseCreatorFactory must not" " be null"); } // Request timeout is signed and must be greater than 0. if (request_timeout_ <= 0) { isc_throw(HttpListenerError, "Invalid desired HTTP request timeout " << request_timeout_); } // Idle persistent connection timeout is signed and must be greater than 0. if (idle_timeout_ <= 0) { isc_throw(HttpListenerError, "Invalid desired HTTP idle persistent connection" " timeout " << idle_timeout_); } } const TCPEndpoint& HttpListenerImpl::getEndpoint() const { return (*endpoint_); } void HttpListenerImpl::start() { try { acceptor_->open(*endpoint_); acceptor_->setOption(HttpAcceptor::ReuseAddress(true)); acceptor_->bind(*endpoint_); acceptor_->listen(); } catch (const boost::system::system_error& ex) { stop(); isc_throw(HttpListenerError, "unable to setup TCP acceptor for " "listening to the incoming HTTP requests: " << ex.what()); } accept(); } void HttpListenerImpl::stop() { connections_.stopAll(); acceptor_->close(); } void HttpListenerImpl::accept() { // In some cases we may need HttpResponseCreator instance per connection. // But, the factory may also return the same instance each time. It // depends on the use case. HttpResponseCreatorPtr response_creator = creator_factory_->create(); HttpAcceptorCallback acceptor_callback = std::bind(&HttpListenerImpl::acceptHandler, this, ph::_1); HttpConnectionPtr conn = createConnection(response_creator, acceptor_callback); // Add this new connection to the pool. connections_.start(conn); } void HttpListenerImpl::acceptHandler(const boost::system::error_code&) { // The new connection has arrived. Set the acceptor to continue // accepting new connections. accept(); } HttpConnectionPtr HttpListenerImpl::createConnection(const HttpResponseCreatorPtr& response_creator, const HttpAcceptorCallback& callback) { HttpConnectionPtr conn(new HttpConnection(io_service_, acceptor_, tls_context_, connections_, response_creator, callback, request_timeout_, idle_timeout_)); return (conn); } } // end of namespace isc::http } // end of namespace isc YJBeetle/QtAndroidAPIandroid-31/java/security/cert/CertPathValidatorException.cpp #include "../../io/ObjectInputStream.hpp" #include "../../../JString.hpp" #include "../../../JThrowable.hpp" #include "./CertPath.hpp" #include "./CertPathValidatorException.hpp" namespace java::security::cert { // Fields // QJniObject forward CertPathValidatorException::CertPathValidatorException(QJniObject obj) : java::security::GeneralSecurityException(obj) {} // Constructors CertPathValidatorException::CertPathValidatorException() : java::security::GeneralSecurityException( "java.security.cert.CertPathValidatorException", "()V" ) {} CertPathValidatorException::CertPathValidatorException(JString arg0) : java::security::GeneralSecurityException( "java.security.cert.CertPathValidatorException", "(Ljava/lang/String;)V", arg0.object() ) {} CertPathValidatorException::CertPathValidatorException(JThrowable arg0) : java::security::GeneralSecurityException( "java.security.cert.CertPathValidatorException", "(Ljava/lang/Throwable;)V", arg0.object() ) {} CertPathValidatorException::CertPathValidatorException(JString arg0, JThrowable arg1) : java::security::GeneralSecurityException( "java.security.cert.CertPathValidatorException", "(Ljava/lang/String;Ljava/lang/Throwable;)V", arg0.object(), arg1.object() ) {} CertPathValidatorException::CertPathValidatorException(JString arg0, JThrowable arg1, java::security::cert::CertPath arg2, jint arg3) : java::security::GeneralSecurityException( "java.security.cert.CertPathValidatorException", "(Ljava/lang/String;Ljava/lang/Throwable;Ljava/security/cert/CertPath;I)V", arg0.object(), arg1.object(), arg2.object(), arg3 ) {} CertPathValidatorException::CertPathValidatorException(JString arg0, JThrowable arg1, java::security::cert::CertPath arg2, jint arg3, JObject arg4) : java::security::GeneralSecurityException( "java.security.cert.CertPathValidatorException", "(Ljava/lang/String;Ljava/lang/Throwable;Ljava/security/cert/CertPath;ILjava/security/cert/CertPathValidatorException$Reason;)V", arg0.object(), arg1.object(), arg2.object(), arg3, arg4.object() ) {} // Methods java::security::cert::CertPath CertPathValidatorException::getCertPath() const { return callObjectMethod( "getCertPath", "()Ljava/security/cert/CertPath;" ); } jint CertPathValidatorException::getIndex() const { return callMethod( "getIndex", "()I" ); } JObject CertPathValidatorException::getReason() const { return callObjectMethod( "getReason", "()Ljava/security/cert/CertPathValidatorException$Reason;" ); } } // namespace java::security::cert #pragma once #include namespace gene::mutate { // 突然変異操作: 一様突然変異 template class Uniform { private: using value_t = T; value_t _min, _max; public: Uniform(const value_t& min, const value_t& max): _min(min), _max(max) { assert(min <= max); } template void operator()(RAND& rd, Gene& g) const { const auto randI = [&rd](auto... arg){ using UD = std::uniform_int_distribution; return UD(arg...)(rd); }; const auto len = g.length(); assert(len > 1); const size_t idx = randI(0, len-1); std::uniform_real_distribution dist(_min, _max); g[idx] = dist(rd); } }; } // C++ includes #include #include #include #include #include // CUDA includes #include // CMSSW includes #include "CUDACore/cudaCheck.h" #include "CUDACore/device_unique_ptr.h" #include "CUDACore/host_unique_ptr.h" #include "CUDADataFormats/gpuClusteringConstants.h" #include "CondFormats/SiPixelROCsStatusAndMappingWrapper.h" SiPixelROCsStatusAndMappingWrapper::SiPixelROCsStatusAndMappingWrapper(SiPixelROCsStatusAndMapping const& cablingMap, std::vector modToUnp) : modToUnpDefault(modToUnp.size()), hasQuality_(true) { cudaCheck(cudaMallocHost(&cablingMapHost, sizeof(SiPixelROCsStatusAndMapping))); std::memcpy(cablingMapHost, &cablingMap, sizeof(SiPixelROCsStatusAndMapping)); std::copy(modToUnp.begin(), modToUnp.end(), modToUnpDefault.begin()); } SiPixelROCsStatusAndMappingWrapper::~SiPixelROCsStatusAndMappingWrapper() { cudaCheck(cudaFreeHost(cablingMapHost)); } const SiPixelROCsStatusAndMapping* SiPixelROCsStatusAndMappingWrapper::getGPUProductAsync( cudaStream_t cudaStream) const { const auto& data = gpuData_.dataForCurrentDeviceAsync(cudaStream, [this](GPUData& data, cudaStream_t stream) { // allocate cudaCheck(cudaMalloc(&data.cablingMapDevice, sizeof(SiPixelROCsStatusAndMapping))); // transfer cudaCheck(cudaMemcpyAsync( data.cablingMapDevice, this->cablingMapHost, sizeof(SiPixelROCsStatusAndMapping), cudaMemcpyDefault, stream)); }); return data.cablingMapDevice; } const unsigned char* SiPixelROCsStatusAndMappingWrapper::getModToUnpAllAsync(cudaStream_t cudaStream) const { const auto& data = modToUnp_.dataForCurrentDeviceAsync(cudaStream, [this](ModulesToUnpack& data, cudaStream_t stream) { cudaCheck(cudaMalloc((void**)&data.modToUnpDefault, pixelgpudetails::MAX_SIZE_BYTE_BOOL)); cudaCheck(cudaMemcpyAsync(data.modToUnpDefault, this->modToUnpDefault.data(), this->modToUnpDefault.size() * sizeof(unsigned char), cudaMemcpyDefault, stream)); }); return data.modToUnpDefault; } SiPixelROCsStatusAndMappingWrapper::GPUData::~GPUData() { cudaCheck(cudaFree(cablingMapDevice)); } SiPixelROCsStatusAndMappingWrapper::ModulesToUnpack::~ModulesToUnpack() { cudaCheck(cudaFree(modToUnpDefault)); } danheeks/PyCADStep/ConversionTools.cpp // ConversionTools.cpp // Copyright (c) 2009, // This program is released under the BSD license. See the file COPYING for details. #include "stdafx.h" #include "ConversionTools.h" #include "MarkedList.h" #include "HEllipse.h" #include "HSpline.h" #include "Wire.h" #include "Face.h" #include "Edge.h" #include "Shape.h" #include "strconv.h" #include "Curve.h" #include "ShapeBuild_ReShape.hxx" #include #include #include #include static gp_Pnt GetStart(const TopoDS_Edge &edge) { BRepAdaptor_Curve curve(edge); double uStart = curve.FirstParameter(); gp_Pnt PS; gp_Vec VS; curve.D1(uStart, PS, VS); return(PS); } static gp_Pnt GetEnd(const TopoDS_Edge &edge) { BRepAdaptor_Curve curve(edge); double uEnd = curve.LastParameter(); gp_Pnt PE; gp_Vec VE; curve.D1(uEnd, PE, VE); return(PE); } struct EdgeComparison : public std::binary_function { EdgeComparison( const TopoDS_Edge & edge ) { m_reference_edge = edge; } bool operator()( const TopoDS_Edge & lhs, const TopoDS_Edge & rhs ) const { std::vector lhs_distances; lhs_distances.push_back( GetStart(m_reference_edge).Distance( GetStart(lhs) ) ); lhs_distances.push_back( GetStart(m_reference_edge).Distance( GetEnd(lhs) ) ); lhs_distances.push_back( GetEnd(m_reference_edge).Distance( GetStart(lhs) ) ); lhs_distances.push_back( GetEnd(m_reference_edge).Distance( GetEnd(lhs) ) ); std::sort(lhs_distances.begin(), lhs_distances.end()); std::vector rhs_distances; rhs_distances.push_back( GetStart(m_reference_edge).Distance( GetStart(rhs) ) ); rhs_distances.push_back( GetStart(m_reference_edge).Distance( GetEnd(rhs) ) ); rhs_distances.push_back( GetEnd(m_reference_edge).Distance( GetStart(rhs) ) ); rhs_distances.push_back( GetEnd(m_reference_edge).Distance( GetEnd(rhs) ) ); std::sort(rhs_distances.begin(), rhs_distances.end()); return(*(lhs_distances.begin()) < *(rhs_distances.begin())); } TopoDS_Edge m_reference_edge; }; void SortEdges( std::vector & edges ) { for (std::vector::iterator l_itEdge = edges.begin(); l_itEdge != edges.end(); l_itEdge++) { // We've already begun. Just sort based on the previous point's location. std::vector::iterator l_itNextEdge = l_itEdge; l_itNextEdge++; if (l_itNextEdge != edges.end()) { EdgeComparison compare( *l_itEdge ); std::sort( l_itNextEdge, edges.end(), compare ); } // End if - then } // End for } // End SortEdges() method static gp_Circ HArcGetCircle(HeeksObj* object) { Point3d c, a; object->GetCentrePoint(c); object->GetAxis(a); gp_Ax2 axis(P2G(c), P2D(a)); double r; object->GetRadius(r); return gp_Circ(axis, r); } bool ConvertLineArcsToWire2(const std::list &list, TopoDS_Wire &wire) { std::vector edges; std::list list2; std::list::const_iterator It; for(It = list.begin(); It != list.end(); It++){ HeeksObj* object = *It; if(object->GetType() == SketchType){ for(HeeksObj* child = object->GetFirstChild(); child; child = object->GetNextChild()) { list2.push_back(child); } } else{ list2.push_back(object); } } for(std::list::iterator It = list2.begin(); It != list2.end(); It++){ HeeksObj* object = *It; int t = object->GetType(); if (t == LineType) { Point3d s, e; object->GetStartPoint(s); object->GetEndPoint(e); edges.push_back(BRepBuilderAPI_MakeEdge(P2G(s), P2G(e))); } else if (t == ArcType) { Point3d s, e, c, a; object->GetStartPoint(s); object->GetEndPoint(e); edges.push_back(BRepBuilderAPI_MakeEdge(HArcGetCircle(object), P2G(s), P2G(e))); } else if (t == HSpline::m_type) { HSpline* spline = (HSpline*)object; edges.push_back(BRepBuilderAPI_MakeEdge(spline->m_spline)); } } if(edges.size() > 0){ wire = EdgesToWire(edges); return true; } return false; } bool ConvertSketchToEdges(HeeksObj *object, std::list< std::vector > &edges) { std::list line_arc_list; if(object->GetType() == SketchType) { std::list new_separate_sketches; theApp->SketchSplit(object, new_separate_sketches); if(new_separate_sketches.size() > 1) { // call again with each separate sketch for(std::list::iterator It = new_separate_sketches.begin(); It != new_separate_sketches.end(); It++) { HeeksObj* sketch = *It; if(!ConvertSketchToEdges(sketch, edges))return false; } return true; } else { for(HeeksObj* child = object->GetFirstChild(); child; child = object->GetNextChild()) { line_arc_list.push_back(child); } std::vector empty_list; edges.push_back(empty_list); } } else { line_arc_list.push_back(object); } if(edges.size() == 0) { std::vector empty_list; edges.push_back(empty_list); } const double max_tolerance = 10.0; for(std::list::const_iterator It = line_arc_list.begin(); It != line_arc_list.end(); It++){ try { HeeksObj* object = *It; if (object->GetType() == LineType){ bool done = false; double tolerance = TOLERANCE; while ((!done) && (tolerance < max_tolerance)) { Point3d s, e; object->GetStartPoint(s); object->GetEndPoint(e); if (!(s == e)) { BRep_Builder aBuilder; TopoDS_Vertex start, end; aBuilder.MakeVertex(start, P2G(s), TOLERANCE); start.Orientation(TopAbs_REVERSED); aBuilder.MakeVertex(end, P2G(e), TOLERANCE); end.Orientation(TopAbs_FORWARD); BRepBuilderAPI_MakeEdge edge(start, end); if (!edge.IsDone()) { // return(false); tolerance *= 10.0; } else { edges.back().push_back(edge.Edge()); done = true; } } else { break; } if (!done) { return(false); } } // End while } else if (object->GetType() == ArcType) { bool done = false; double tolerance = TOLERANCE; while ((!done) && (tolerance < max_tolerance)) { Point3d s, e; object->GetStartPoint(s); object->GetEndPoint(e); BRep_Builder aBuilder; TopoDS_Vertex start, end; aBuilder.MakeVertex(start, P2G(s), TOLERANCE); start.Orientation(TopAbs_REVERSED); aBuilder.MakeVertex(end, P2G(e), TOLERANCE); end.Orientation(TopAbs_FORWARD); BRepBuilderAPI_MakeEdge edge(HArcGetCircle(object), start, end); if (!edge.IsDone()) { // return(false); tolerance *= 10.0; } else { edges.back().push_back(edge.Edge()); done = true; } } // End while if (!done) { return(false); } } else if (object->GetType() == CircleType) { edges.back().push_back(BRepBuilderAPI_MakeEdge(HArcGetCircle(object))); } else if (object->GetType() == HEllipse::m_type) { HEllipse* ellipse = (HEllipse*)object; edges.back().push_back(BRepBuilderAPI_MakeEdge(ellipse->GetEllipse())); } else if (object->GetType() == HSpline::m_type) { HSpline* spline = (HSpline*)object; edges.back().push_back(BRepBuilderAPI_MakeEdge(spline->m_spline)); } else { std::wstring message; message.append(L"Cannot convert object type "); message.append(object->GetTypeString()); message.append(L" to edge"); theApp->DoMessageBox(message.c_str()); return(false); } } // End try catch(Standard_Failure) { Handle_Standard_Failure e = Standard_Failure::Caught(); theApp->DoMessageBox((std::wstring(L"Error converting sketch to face: ") + Ctt(e->GetMessageString())).c_str()); return false; } } return(true); } TopoDS_Wire EdgesToWire(const std::vector &edges) { BRepBuilderAPI_MakeWire wire_maker; for(std::vector::const_iterator It = edges.begin(); It != edges.end(); It++) { const TopoDS_Edge &edge = *It; wire_maker.Add(edge); } return wire_maker.Wire(); } bool SketchToWires(HeeksObj* sketch, std::list &wire_list) { std::list< std::vector > edges_list; if (!ConvertSketchToEdges(sketch, edges_list)) return false; for(std::list< std::vector >::iterator It = edges_list.begin(); It != edges_list.end(); It++) { std::vector &edges = *It; wire_list.push_back(EdgesToWire(edges)); } return true; } bool ConvertEdgesToFaceOrWire(const std::vector &edges, std::list &face_or_wire, bool face_not_wire) { // It's not enough to add the edges to the wire in an arbitrary order. If the adjacent edges // don't connect then the wire ends up losing one of the edges. We must sort the edge objects // so that they're connected (or best we can) before constructing the TopoDS_Wire object from // them. // So, please call SortEdges before getting to here. try { TopoDS_Wire wire = EdgesToWire(edges); if(face_not_wire) { BRepBuilderAPI_MakeFace make_face(wire); if(make_face.IsDone() == Standard_False)face_or_wire.push_back(wire); else face_or_wire.push_back(make_face.Face()); } else { face_or_wire.push_back(wire); } } catch (Standard_Failure) { Handle_Standard_Failure e = Standard_Failure::Caught(); std::wstring message(L"Error converting sketch to face: "); message.append(Ctt(e->GetMessageString())); theApp->DoMessageBox(message.c_str()); return false; } catch(...) { theApp->DoMessageBox(L"Fatal Error converting sketch to face"); return false; } return true; } bool ConvertSketchToFaceOrWire(HeeksObj* object, std::list &face_or_wire, bool face_not_wire) { std::list< std::vector > edges; if (! ConvertSketchToEdges(object, edges)) { return(false); } for(std::list< std::vector >::iterator It = edges.begin(); It != edges.end(); It++) { std::vector &list = *It; if(list.size() > 0) { SortEdges(list); if(!ConvertEdgesToFaceOrWire(list, face_or_wire, face_not_wire))return false; } } return true; } void SketchToFace() { std::list< std::vector > individual_edges; std::list objects; theApp->GetSelection(objects); std::list::const_iterator It; for (std::list::iterator It = objects.begin(); It != objects.end(); It++){ HeeksObj* object = *It; int t = object->GetType(); if (t == SketchType) { std::list faces; if (ConvertSketchToFaceOrWire(object, faces, true)) { for (std::list::iterator It2 = faces.begin(); It2 != faces.end(); It2++) { TopoDS_Shape& face = *It2; theApp->AddUndoably(new CFace(TopoDS::Face(face)), NULL, NULL); } } } if (t == LineType || t == ArcType || t == CircleType || t == HEllipse::m_type || t == HSpline::m_type) { if (!ConvertSketchToEdges(object, individual_edges))return; } } for (std::list< std::vector >::iterator It = individual_edges.begin(); It != individual_edges.end(); It++) { std::vector &edges = *It; if (edges.size() > 0) { SortEdges(edges); std::list faces; if (ConvertEdgesToFaceOrWire(edges, faces, true)) { for (std::list::iterator It2 = faces.begin(); It2 != faces.end(); It2++) { TopoDS_Shape& face = *It2; theApp->AddUndoably(new CFace(TopoDS::Face(face)), NULL, NULL); } } } } } bool ConvertFaceToSketch2(const TopoDS_Face& face, HeeksObj* sketch, double deviation) { // given a face, this adds lines and arcs to the given sketch // loop through all the loops TopoDS_Wire outerWire=BRepTools::OuterWire(face); for (TopExp_Explorer expWire(face, TopAbs_WIRE); expWire.More(); expWire.Next()) { const TopoDS_Shape &W = expWire.Current(); for(BRepTools_WireExplorer expEdge(TopoDS::Wire(W)); expEdge.More(); expEdge.Next()) { const TopoDS_Shape &E = expEdge.Current(); if(!ConvertEdgeToSketch2(TopoDS::Edge(E), sketch, deviation))return false; } } return true; // success } void ChangeFaceRadius(const TopoDS_Face& face, double new_radius) { TopoDS_Shape cmpnd; // already exists TopoDS_Shape theNewFace = face.Complemented(); Handle_ShapeBuild_ReShape rebuild = new ShapeBuild_ReShape; // remove it: rebuild->Remove(theOldFace); // or replace it: rebuild->Replace(face, theNewFace, Standard_False); TopoDS_Shape shcmpnd = rebuild->Apply(cmpnd, TopAbs_SHAPE, 1); } bool ConvertWireToSketch(const TopoDS_Wire& wire, HeeksObj* sketch, double deviation) { const TopoDS_Shape &W = wire; for(BRepTools_WireExplorer expEdge(TopoDS::Wire(W)); expEdge.More(); expEdge.Next()) { const TopoDS_Shape &E = expEdge.Current(); if(!ConvertEdgeToSketch2(TopoDS::Edge(E), sketch, deviation))return false; } return true; // success } static void AddLineOrArcToSketch(HeeksObj* sketch, HeeksObj* line_or_arc) { Point3d sketch_end; if (sketch->GetEndPoint(sketch_end)) { Point3d start; if (line_or_arc->GetStartPoint(start)) { if (start.Dist(sketch_end) <= 0.001) { line_or_arc->SetStartPoint(sketch_end); } } } sketch->Add(line_or_arc, NULL); } bool ConvertEdgeToSketch2(const TopoDS_Edge& edge, HeeksObj* sketch, double deviation, bool reverse) { // enum GeomAbs_CurveType // 0 - GeomAbs_Line // 1 - GeomAbs_Circle // 2 - GeomAbs_Ellipse // 3 - GeomAbs_Hyperbola // 4 - GeomAbs_Parabola // 5 - GeomAbs_BezierCurve // 6 - GeomAbs_BSplineCurve // 7 - GeomAbs_OtherCurve BRepAdaptor_Curve curve(edge); GeomAbs_CurveType curve_type = curve.GetType(); bool sense = (edge.Orientation() == TopAbs_FORWARD); if(reverse)sense = !sense; switch(curve_type) { case GeomAbs_Line: // make a line { double uStart = curve.FirstParameter(); double uEnd = curve.LastParameter(); gp_Pnt PS; gp_Vec VS; curve.D1(uStart, PS, VS); gp_Pnt PE; gp_Vec VE; curve.D1(uEnd, PE, VE); HeeksObj* new_object = theApp->CreateNewLine(G2P(sense ? PS : PE), G2P(sense ? PE : PS)); AddLineOrArcToSketch(sketch, new_object); } break; case GeomAbs_Circle: // make an arc { double uStart = curve.FirstParameter(); double uEnd = curve.LastParameter(); gp_Pnt PS; gp_Vec VS; curve.D1(uStart, PS, VS); gp_Pnt PE; gp_Vec VE; curve.D1(uEnd, PE, VE); gp_Circ circle = curve.Circle(); gp_Ax1 axis = circle.Axis(); if(!sense) { axis.SetDirection(-axis.Direction()); circle.SetAxis(axis); } if(curve.IsPeriodic()) { double period = curve.Period(); double uHalf = uStart + period/2; gp_Pnt PH; gp_Vec VH; curve.D1(uHalf, PH, VH); { HeeksObj* new_object = theApp->CreateNewArc(G2P(PS), G2P(PH), D2P(circle.Axis().Direction()), G2P(circle.Location())); AddLineOrArcToSketch(sketch, new_object); } { HeeksObj* new_object = theApp->CreateNewArc(G2P(PH), G2P(PE), D2P(circle.Axis().Direction()), G2P(circle.Location())); AddLineOrArcToSketch(sketch, new_object); } } else { HeeksObj* new_object = theApp->CreateNewArc(G2P(sense ? PS : PE), G2P(sense ? PE : PS), D2P(circle.Axis().Direction()), G2P(circle.Location())); AddLineOrArcToSketch(sketch, new_object); } } break; case GeomAbs_BSplineCurve: { std::list new_spans; #if 0 // to do HSpline::ToBiarcs(curve.BSpline(), new_spans, deviation, curve.FirstParameter(), curve.LastParameter()); #endif if(sense) { for(std::list::iterator It = new_spans.begin(); It != new_spans.end(); It++) AddLineOrArcToSketch(sketch, *It); } else { for(std::list::reverse_iterator It = new_spans.rbegin(); It != new_spans.rend(); It++) { HeeksObj* object = *It; object->Reverse(); AddLineOrArcToSketch(sketch, object); } } } break; default: { // make lots of small lines BRepTools::Clean(edge); BRepMesh_IncrementalMesh(edge, deviation); TopLoc_Location L; Handle(Poly_Polygon3D) Polyg = BRep_Tool::Polygon3D(edge, L); if (!Polyg.IsNull()) { const TColgp_Array1OfPnt& Points = Polyg->Nodes(); Standard_Integer po; gp_Pnt prev_p; int i = 0; for (po = sense ? Points.Lower():Points.Upper(); (sense && (po <= Points.Upper())) || (!sense && (po >= Points.Lower())); i++) { gp_Pnt p = (Points.Value(po)).Transformed(L); if(i != 0) { HeeksObj* new_object = theApp->CreateNewLine(G2P(prev_p), G2P(p)); AddLineOrArcToSketch(sketch, new_object); } prev_p = p; if(sense)po++; else po--; } } } break; } return true; } static void AddLineOrArc(HeeksObj* sketch, Span &span) { if(span.m_v.m_type == 0) { HeeksObj* new_object = theApp->CreateNewLine(Point3d(span.m_p.x, span.m_p.y, 0), Point3d(span.m_v.m_p.x, span.m_v.m_p.y, 0)); AddLineOrArcToSketch(sketch, new_object); } else { Point3d axis = (span.m_v.m_type > 0) ? Point3d(0, 0, 1) : Point3d(0, 0, -1); Point3d c(span.m_v.m_c); HeeksObj* new_object = theApp->CreateNewArc(Point3d(span.m_p.x, span.m_p.y, 0), Point3d(span.m_v.m_p.x, span.m_v.m_p.y, 0), axis, c); AddLineOrArcToSketch(sketch, new_object); } } #pragma once #include "API.hpp" #include "Graphics/Buffer.hpp" #include "Graphics/VertexLayout.hpp" #include "ParticleEmitterType.hpp" #include #include #include #include #include namespace jm { class JAPI ParticleEmitter { public: explicit ParticleEmitter(const struct ParticleEmitterType& type) : m_type(&type) { } bool enabled = true; glm::vec2 position; float rotation = 0; const struct ParticleEmitterType& Type() const { return *m_type; } private: const struct ParticleEmitterType* m_type; }; class JAPI ParticleManager { public: ParticleManager(); void AddEmitter(std::weak_ptr emitter); void KeepAlive(std::shared_ptr emitter, float time); void Update(float dt); void Draw(const glm::mat3& viewMatrix); size_t TotalParticles() const { return m_particleDrawData.size(); } private: pcg32_fast m_rng; static constexpr size_t PARTICLES_PER_PAGE = 1024; struct ParticlePage { uint32_t numParticles; ParticlePage* next; glm::vec2 pos[PARTICLES_PER_PAGE]; glm::vec2 vel[PARTICLES_PER_PAGE]; glm::vec2 sizeStartEnd[PARTICLES_PER_PAGE]; glm::vec2 opacityStartEnd[PARTICLES_PER_PAGE]; float rotation[PARTICLES_PER_PAGE]; float rotationVelocity[PARTICLES_PER_PAGE]; float elapsedLifeTime[PARTICLES_PER_PAGE]; float totalLifeTime[PARTICLES_PER_PAGE]; int textureArea[PARTICLES_PER_PAGE]; }; std::list m_allPages; ParticlePage* m_availablePages = nullptr; struct TextureArea { glm::vec4 area; float aspectRatio; }; struct EmitterEntry { std::weak_ptr weakEmitter; const ParticleEmitterType* type; std::vector textureAreas; ParticlePage* firstPage; uint32_t firstParticle; uint32_t totalParticles; float timeNotEmitted; bool available; bool hasOldData; glm::vec2 oldPosition; float oldRotation; }; std::vector m_emitters; #pragma pack(push, 1) struct ParticleDrawData { glm::vec4 textureArea; float opacity; glm::mat3x2 matrix; }; #pragma pack(pop) std::vector m_particleDrawData; Buffer m_particlesBuffer; VertexLayout m_vertexLayout; std::vector>> m_keepAlive; }; } src/GUI/HostSelector.cpp #include "HostSelector.hpp" #include HostSelector::HostSelector(QWidget *parent) : QDialog(parent) { ui.setupUi(this); setResult(QDialog::Accepted); } HostSelector::~HostSelector() { } void HostSelector::on_btnCancel_clicked() { reject(); } void HostSelector::on_btnConnect_clicked() { } malium/Greaper /*********************************************************************************** * Copyright 2021 . * * All Rights Reserved. * ***********************************************************************************/ #include #include #include #include #include #include #if PLT_WINDOWS #define PLT_NAME "Win" #else #define PLT_NAME "Lnx" #endif #if ARCHITECTURE_X64 #define ARCH_NAME "64" #else #define ARCH_NAME "32" #endif #if GREAPER_DEBUG #define CONF_NAME "DebugDLL" #else #define CONF_NAME "ReleaseDLL" #endif #define CORE_LIBRARY_NAME "Core" PLT_NAME ARCH_NAME "_" CONF_NAME GREAPER_DLLEXT constexpr greaper::StringView CORE_LIB_NAME = CORE_LIBRARY_NAME; constexpr greaper::StringView LibFnName = "_Greaper"; greaper::Library* gCoreLib = nullptr; greaper::IGreaperLibrary* gCore = nullptr; greaper::IApplication* gApplication = nullptr; #define APPLICATION_VERSION VERSION_SETTER(1, 0, 0, 0) #define TRYEXP(exp, msg) { if(!exp) { DEBUG_OUTPUT(msg); TRIGGER_BREAKPOINT(); exit(EXIT_FAILURE); } } static int MainCode(void* hInstance, int argc, char** argv); #if PLT_WINDOWS #ifdef _CONSOLE int main(int argc, char* argv[]) { void* hInstance = nullptr; hInstance = (void*)GetModuleHandleW(nullptr); return MainCode(hInstance, argc, argv); } #else /* !_CONSOLE */ class ArgvDestructor { public: constexpr ArgvDestructor() noexcept = default; void operator()(LPSTR* argv) { FreeArgvA(argv); } }; INT WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd) { UNUSED(nShowCmd); UNUSED(hPrevInstance); int argc = 0; auto argv = std::unique_ptr(CommandLineToArgvA(lpCmdLine, &argc)); if (argv == nullptr) return EXIT_FAILURE; int retVal = MainCode(hInstance, argc, argv.get()); return retVal; } #endif #else /* !PLT_WINDOWS */ int main(int argc, char* argv[]) { void* hInstance = nullptr; return MainCode(nullptr, argc, argv); } #endif int MainCode(void* hInstance, int argc, char** argv) { using namespace greaper; gCoreLib = Construct(CORE_LIB_NAME); TRYEXP(gCoreLib->IsOpen(), "Couldn't open " CORE_LIBRARY_NAME); auto libFN = gCoreLib->GetFunctionT(LibFnName); TRYEXP(libFN, CORE_LIBRARY_NAME " does not have the _Greaper function"); // init Greaper gCore = static_cast(libFN()); auto propAppInstance = CreateProperty(gCore, IApplication::AppInstanceName, (ptruint)hInstance, ""sv, true, true, nullptr); StringVec commandLine; commandLine.resize(argc); for (int32 i = 0; i < argc; ++i) commandLine[i] = String{ argv[i] }; auto propRes = CreateProperty(gCore, IApplication::CommandLineName, std::move(commandLine), ""sv, true, true, nullptr); gCore->Initialize(gCoreLib, nullptr); gApplication = gCore->GetApplication(); TRYEXP(gApplication, CORE_LIBRARY_NAME " does not have an Application."); gApplication->GetApplicationName()->SetValue(String{ "TestApplication"sv }); gApplication->GetApplicationVersion()->SetValue(APPLICATION_VERSION); gApplication->GetLoadedLibrariesNames()->SetValue({}); std::cout << "Successfully started!\n " << gApplication->GetApplicationName()->GetStringValue() << " Version " << gApplication->GetApplicationVersion()->GetStringValue() << std::endl; std::cout << "Enter anything to shutdown" << std::endl; achar a; std::cin >> a; gApplication->StopApplication(); gCore->Deinitialize(); gApplication = nullptr; gCore = nullptr; gCoreLib->Close(); Destroy(gCoreLib); gCoreLib = nullptr; return EXIT_SUCCESS; } inference-engine/src/vpu/graph_transformer/src/model/data_contents/hw_weights_content.cpp // Copyright (C) 2020 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include #include #include namespace vpu { HwWeightsContent::HwWeightsContent(const DataContent::Ptr& origContent, const DataDesc& origWeightsDesc, const DataDesc& resDesc, int numInputChannels, int channelStartIndex) : _origContent(origContent), _origDesc(origWeightsDesc), _resDesc(resDesc), _numInputChannels(numInputChannels), _channelStartIndex(channelStartIndex) { } size_t HwWeightsContent::byteSize() const { return checked_cast(_resDesc.totalDimSize()) * checked_cast(_resDesc.elemSize()); } void HwWeightsContent::fillTempBuf(void* tempBuf) const { VPU_PROFILE(HwWeightsContent); IE_ASSERT(_resDesc.type() == DataType::FP16); const auto KX = _origDesc.dim(Dim::W); const auto KY = _origDesc.dim(Dim::H); const auto IC = _origDesc.dim(Dim::C); const auto OC = _origDesc.dim(Dim::N); const auto origTotalSize = _origDesc.totalDimSize(); const auto HW_OC_inner = _resDesc.dim(Dim::W); const auto HW_OC_outer = _resDesc.dim(Dim::N); IE_ASSERT(HW_OC_outer * HW_OC_inner >= OC); const auto HW_K = _resDesc.dim(Dim::H); IE_ASSERT(HW_K == KX * KY); IE_ASSERT(_channelStartIndex < IC); const auto HW_IC = _resDesc.dim(Dim::C); const auto HW_IC_real = std::min(_numInputChannels, IC - _channelStartIndex); const auto srcData = _origContent->get(); IE_ASSERT(srcData != nullptr); auto dstData = static_cast(tempBuf); IE_ASSERT((_channelStartIndex + HW_IC_real) * HW_K + (OC - 1) * HW_K * IC - 1 < origTotalSize); IE_ASSERT((OC - 1) % HW_OC_inner + (HW_K - 1) * HW_OC_inner + (HW_IC_real - 1) * HW_OC_inner * HW_K + ((OC - 1) / 8) * HW_OC_inner * HW_K * HW_IC < _resDesc.totalDimSize()); if (KX == 1 && KY == 1) { ie::parallel_for(OC, [=](int oc) { const auto oc_inner = oc % HW_OC_inner; const auto oc_outer = oc / HW_OC_inner; for (int ic = 0; ic < HW_IC_real; ++ic) { const auto srcInd = (_channelStartIndex + ic) + oc * IC; const auto dstInd = oc_inner + ic * HW_OC_inner * HW_K + oc_outer * HW_OC_inner * HW_K * HW_IC; dstData[dstInd] = srcData[srcInd]; } }); } else { ie::parallel_for(OC, [=](int oc) { const auto oc_inner = oc % HW_OC_inner; const auto oc_outer = oc / HW_OC_inner; for (int ic = 0; ic < HW_IC_real; ++ic) { for (int ky = 0; ky < KY; ++ky) { for (int kx = 0; kx < KX; ++kx) { const auto srcInd = (kx + ky * KX) + (_channelStartIndex + ic) * HW_K + oc * HW_K * IC; const auto dstInd = oc_inner + (ky * KX + kx) * HW_OC_inner + ic * HW_OC_inner * HW_K + oc_outer * HW_OC_inner * HW_K * HW_IC; dstData[dstInd] = srcData[srcInd]; } } } }); } } } // namespace vpu media/mojo/services/cdm_service.cc // 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 "media/mojo/services/cdm_service.h" #include #include "base/bind.h" #include "base/logging.h" #include "base/memory/weak_ptr.h" #include "media/base/cdm_factory.h" #include "media/mojo/services/mojo_cdm_service.h" #include "media/mojo/services/mojo_cdm_service_context.h" #include "mojo/public/cpp/bindings/remote.h" #include "mojo/public/cpp/bindings/unique_receiver_set.h" namespace media { namespace { // Implementation of mojom::CdmFactory that creates and hosts MojoCdmServices // which then host CDMs created by the media::CdmFactory provided by the // CdmService::Client. // // Lifetime Note: // 1. CdmFactoryImpl instances are owned by a DeferredDestroyUniqueReceiverSet // directly, which is owned by CdmService. // 2. CdmFactoryImpl is destroyed in any of the following two cases: // - CdmService is destroyed. Because of (2) this should not happen except for // during browser shutdown, when the Cdservice could be destroyed directly, // ignoring any outstanding interface connections. // - mojo::CdmFactory disconnection happens, AND CdmFactoryImpl doesn't own // any CDMs (|cdm_receivers_| is empty). This is to prevent destroying the // CDMs too early (e.g. during page navigation) which could cause errors // (session closed) on the client side. See https://crbug.com/821171 for // details. class CdmFactoryImpl final : public DeferredDestroy { public: CdmFactoryImpl(CdmService::Client* client, mojo::PendingRemote interfaces) : client_(client), interfaces_(std::move(interfaces)) { DVLOG(1) << __func__; // base::Unretained is safe because |cdm_receivers_| is owned by |this|. If // |this| is destructed, |cdm_receivers_| will be destructed as well and the // error handler should never be called. cdm_receivers_.set_disconnect_handler(base::BindRepeating( &CdmFactoryImpl::OnReceiverDisconnect, base::Unretained(this))); } CdmFactoryImpl(const CdmFactoryImpl&) = delete; CdmFactoryImpl operator=(const CdmFactoryImpl&) = delete; ~CdmFactoryImpl() final { DVLOG(1) << __func__; } // mojom::CdmFactory implementation. void CreateCdm(const std::string& key_system, const CdmConfig& cdm_config, CreateCdmCallback callback) final { DVLOG(2) << __func__; auto* cdm_factory = GetCdmFactory(); if (!cdm_factory) { std::move(callback).Run(mojo::NullRemote(), nullptr, "CDM Factory creation failed"); return; } auto mojo_cdm_service = std::make_unique(&cdm_service_context_); auto* raw_mojo_cdm_service = mojo_cdm_service.get(); DCHECK(!pending_mojo_cdm_services_.count(raw_mojo_cdm_service)); pending_mojo_cdm_services_[raw_mojo_cdm_service] = std::move(mojo_cdm_service); raw_mojo_cdm_service->Initialize( cdm_factory, key_system, cdm_config, base::BindOnce(&CdmFactoryImpl::OnCdmServiceInitialized, weak_ptr_factory_.GetWeakPtr(), raw_mojo_cdm_service, std::move(callback))); } // DeferredDestroy implemenation. void OnDestroyPending(base::OnceClosure destroy_cb) final { destroy_cb_ = std::move(destroy_cb); if (cdm_receivers_.empty()) std::move(destroy_cb_).Run(); // else the callback will be called when |cdm_receivers_| become empty. } private: media::CdmFactory* GetCdmFactory() { if (!cdm_factory_) { cdm_factory_ = client_->CreateCdmFactory(interfaces_.get()); DLOG_IF(ERROR, !cdm_factory_) << "CdmFactory not available."; } return cdm_factory_.get(); } void OnReceiverDisconnect() { if (destroy_cb_ && cdm_receivers_.empty()) std::move(destroy_cb_).Run(); } void OnCdmServiceInitialized(MojoCdmService* raw_mojo_cdm_service, CreateCdmCallback callback, mojom::CdmContextPtr cdm_context, const std::string& error_message) { DCHECK(raw_mojo_cdm_service); // Remove pending MojoCdmService from the mapping in all cases. DCHECK(pending_mojo_cdm_services_.count(raw_mojo_cdm_service)); auto mojo_cdm_service = std::move(pending_mojo_cdm_services_[raw_mojo_cdm_service]); pending_mojo_cdm_services_.erase(raw_mojo_cdm_service); if (!cdm_context) { std::move(callback).Run(mojo::NullRemote(), nullptr, error_message); return; } mojo::PendingRemote remote; cdm_receivers_.Add(std::move(mojo_cdm_service), remote.InitWithNewPipeAndPassReceiver()); std::move(callback).Run(std::move(remote), std::move(cdm_context), ""); } // Must be declared before the receivers below because the bound objects might // take a raw pointer of |cdm_service_context_| and assume it's always // available. MojoCdmServiceContext cdm_service_context_; CdmService::Client* client_; mojo::Remote interfaces_; mojo::UniqueReceiverSet cdm_receivers_; std::unique_ptr cdm_factory_; base::OnceClosure destroy_cb_; // MojoCdmServices pending initialization. std::map> pending_mojo_cdm_services_; // NOTE: Weak pointers must be invalidated before all other member variables. base::WeakPtrFactory weak_ptr_factory_{this}; }; } // namespace CdmService::CdmService(std::unique_ptr client, mojo::PendingReceiver receiver) : receiver_(this, std::move(receiver)), client_(std::move(client)) { DVLOG(1) << __func__; DCHECK(client_); } CdmService::~CdmService() { DVLOG(1) << __func__; } void CdmService::CreateCdmFactory( mojo::PendingReceiver receiver, mojo::PendingRemote frame_interfaces) { // Ignore receiver if service has already stopped. if (!client_) return; cdm_factory_receivers_.AddReceiver( std::make_unique(client_.get(), std::move(frame_interfaces)), std::move(receiver)); } } // namespace media #include "FastSimulation/CTPPSFastGeometry/interface/CTPPSTrkDetector.h" #include CTPPSTrkDetector::CTPPSTrkDetector(double detw, double deth, double detin) : ppsDetectorWidth_(detw), ppsDetectorHeight_(deth), ppsDetectorPosition_(detin) { clear(); } void CTPPSTrkDetector::AddHit(unsigned int detID, double x, double y, double z) { // Detector is in the negative side, but DetectorPosition is a positive number // if (detID >0); if (x > 0) return; // The detector is on the negative side if (fabs(x) > ppsDetectorWidth_ + ppsDetectorPosition_) return; // hit beyond detector area (W) if (fabs(x) < ppsDetectorPosition_) return; // hit falls below detector area if (fabs(y) > ppsDetectorHeight_ * 0.5) return; // hit falls beyond detector area (H) ppsDetId_.push_back(detID); ppsX_.push_back(x); ppsY_.push_back(y); ppsZ_.push_back(z); ppsNHits_++; } jmasterx/StemwaterSpades1-10 #include "Game/UI/ToolTip.hpp" namespace cge { ToolTip::~ToolTip(void) { } ToolTip::ToolTip( agui::Image* tooltipBG ) :m_tooltipBG(tooltipBG), m_opacityRate(0.1f) { } void ToolTip::paintBackground( const agui::PaintEvent &paintEvent ) { paintEvent.graphics()->drawNinePatchImage( m_tooltipBG,agui::Point(0,0),getSize(),getOpacity()); } void ToolTip::showToolTip( const std::string& text, int width, int x, int y, Widget* invoker ) { agui::ToolTip::showToolTip(text,width,x,y, invoker); setOpacity(0.0f); } void ToolTip::logic( double timeElapsed ) { if(getOpacity() < 1.0f) { setOpacity(getOpacity() + m_opacityRate); } } void ToolTip::paintComponent( const agui::PaintEvent &paintEvent ) { agui::Color c = agui::Color( getFontColor().getR(),getFontColor().getG(), getFontColor().getB(),getOpacity()); resizableText.drawTextArea( paintEvent.graphics(),getFont(),getInnerRectangle(), c,getAreaText(),getTextAlignment()); } } #include #include #include #include #include "omp.h" #include #include "mpi.h" #include "occa.hpp" #include "meshBasis.hpp" #include "kernelHelper.cpp" static occa::kernel kernel; dfloat *drandAlloc(int N){ dfloat *v = (dfloat*) calloc(N, sizeof(dfloat)); for(int n=0;n=6) arch.assign(argv[5]); int Ntests = 1; if(argc>=7) Ntests = atoi(argv[6]); int kernelVersion = 0; if(argc>=8) kernelVersion = atoi(argv[7]); const int deviceId = 0; const int platformId = 0; const int Nq = N+1; const int cubNq = cubN+1; const int Np = Nq*Nq*Nq; const int cubNp = cubNq*cubNq*cubNq; const dlong offset = Nelements*Np; // build device occa::device device; char deviceConfig[BUFSIZ]; if(strstr(threadModel.c_str(), "CUDA")){ sprintf(deviceConfig, "mode: 'CUDA', device_id: %d",deviceId); } else if(strstr(threadModel.c_str(), "HIP")){ sprintf(deviceConfig, "mode: 'HIP', device_id: %d",deviceId); } else if(strstr(threadModel.c_str(), "OPENCL")){ sprintf(deviceConfig, "mode: 'OpenCL', device_id: %d, platform_id: %d", deviceId, platformId); } else if(strstr(threadModel.c_str(), "OPENMP")){ sprintf(deviceConfig, "mode: 'OpenMP' "); } else{ sprintf(deviceConfig, "mode: 'Serial' "); omp_set_num_threads(1); } int Nthreads = omp_get_max_threads(); std::string deviceConfigString(deviceConfig); device.setup(deviceConfigString); occa::env::OCCA_MEM_BYTE_ALIGN = USE_OCCA_MEM_BYTE_ALIGN; if(rank==0) { std::cout << "word size: " << sizeof(dfloat) << " bytes\n"; std::cout << "active occa mode: " << device.mode() << "\n"; } // load kernel std::string kernelName = "advCubatureHex3D"; kernelName += "_v" + std::to_string(kernelVersion); kernel = loadKernel(device, threadModel, arch, kernelName, N, cubN, Nelements); // populate device arrays dfloat *vgeo = drandAlloc(Np*Nelements*p_Nvgeo); dfloat *cubvgeo = drandAlloc(cubNp*Nelements*p_Nvgeo); dfloat *cubDiffInterpT = drandAlloc(3*cubNp*Nelements); dfloat *cubInterpT = drandAlloc(Np*cubNp); dfloat *u = drandAlloc(3*Np*Nelements); dfloat *adv = drandAlloc(3*Np*Nelements); occa::memory o_vgeo = device.malloc(Np*Nelements*p_Nvgeo*sizeof(dfloat), vgeo); occa::memory o_cubvgeo = device.malloc(cubNp*Nelements*p_Nvgeo*sizeof(dfloat), cubvgeo); occa::memory o_cubDiffInterpT = device.malloc(3*cubNp*Nelements*sizeof(dfloat), cubDiffInterpT); occa::memory o_cubInterpT = device.malloc(Np*cubNp*sizeof(dfloat), cubInterpT); occa::memory o_u = device.malloc(3*Np*Nelements*sizeof(dfloat), u); occa::memory o_adv = device.malloc(3*Np*Nelements*sizeof(dfloat), adv); // run kernel kernel( Nelements, o_vgeo, o_cubvgeo, o_cubDiffInterpT, o_cubInterpT, offset, o_u, o_adv); device.finish(); MPI_Barrier(MPI_COMM_WORLD); const double start = MPI_Wtime(); for(int test=0;testpellaeon/OpenCCsrc/UTF8Util.hpp /** * Open Chinese Convert * * Copyright 2013 BYVoid <> * * 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 "Common.hpp" namespace Opencc { class OPENCC_EXPORT UTF8Util { public: static void SkipUtf8Bom(FILE* fp); static size_t NextCharLength(const char* str) { char ch = *str; if ((ch & 0x80) == 0x00) { return 1; } else if ((ch & 0xE0) == 0xC0) { return 2; } else if ((ch & 0xF0) == 0xE0) { return 3; } else if ((ch & 0xF8) == 0xF0) { return 4; } else if ((ch & 0xFC) == 0xF8) { return 5; } else if ((ch & 0xFE) == 0xFC) { return 6; } // Invalid UTF8 string or in the middle of a UTF8 char return 0; } static size_t PrevCharLength(const char* str) { for (size_t i = 1; i <= 6; i++) { str--; size_t length = NextCharLength(str); if (length == i) { return length; } } // Invalid UTF8 string or in the middle of a UTF8 char return 0; } static const char* NextChar(const char* str) { return str + NextCharLength(str); } static const char* PrevChar(const char* str) { return str - PrevCharLength(str); } static bool Validate(const char* str) { // TODO implement this return true; } static const char* FindNextInline(const char* str, const char ch) { while (!IsLineEndingOrFileEnding(*str) && *str != ch) { str = NextChar(str); } return str; } static bool IsLineEndingOrFileEnding(const char ch) { return ch == '\0' || ch == '\n' || ch == '\r'; } static string FromSubstr(const char* str, size_t length) { string newStr; newStr.resize(length); for (size_t i = 0; i < length; i++, str++) { newStr[i] = *str; } return newStr; } static bool NotShorterThan(const char* str, size_t length) { while (length > 0) { if (*str == '\0') { return false; } length--; str++; } return true; } static string TruncateUTF8(const char* str, size_t maxLength) { string wordTrunc; if (NotShorterThan(str, maxLength)) { size_t len = 0; const char* pStr = str; while (len < maxLength) { size_t nextLen = NextCharLength(pStr); pStr += nextLen; len += nextLen; } wordTrunc = FromSubstr(str, len); } else { wordTrunc = str; } return wordTrunc; } static void ReplaceAll(string& str, const char* from, const char* to) { string::size_type pos = 0; string::size_type fromLen = strlen(from); string::size_type toLen = strlen(to); while((pos = str.find(from, pos)) != string::npos) { str.replace(pos, fromLen, to); pos += toLen; } } }; } 0 /* * TaskSpecContainerSpecFile1.cpp * * File represents a specific target that is backed by a file. <p><br /><p> > **Note**: `Configs.File` and `Configs.Runtime` are mutually exclusive */ #include "TaskSpecContainerSpecFile1.h" using namespace openapi; // macro should do the same job. Not really // OPENAP_JSON_CONVERT_FUNCS(TaskSpecContainerSpecFile1, Name, UID, GID, Mode) void TaskSpecContainerSpecFile1::ToJSON(Json & j) const { // OPENAPI_FOR_EACH(OPENAPI_TO_JSON_MEMBER, __VA_ARGS__) j.AddMembername)>(openapi::StringT(OPENAPI_LITERAL(Name)), this->name); j.AddMemberuid)>(openapi::StringT(OPENAPI_LITERAL(UID)), this->uid); j.AddMembergid)>(openapi::StringT(OPENAPI_LITERAL(GID)), this->gid); j.AddMembermode)>(openapi::StringT(OPENAPI_LITERAL(Mode)), this->mode); } void TaskSpecContainerSpecFile1::FromJSON(const Json & j) { // OPENAPI_FOR_EACH(OPENAPI_FROM_JSON_MEMBER, __VA_ARGS__) if(j.HasKey(openapi::StringT(OPENAPI_LITERAL(Name)))) { using V = remove_optionalname)>::type; this->name = j.GetMember(openapi::StringT(OPENAPI_LITERAL(Name))); } if(j.HasKey(openapi::StringT(OPENAPI_LITERAL(UID)))) { using V = remove_optionaluid)>::type; this->uid = j.GetMember(openapi::StringT(OPENAPI_LITERAL(UID))); } if(j.HasKey(openapi::StringT(OPENAPI_LITERAL(GID)))) { using V = remove_optionalgid)>::type; this->gid = j.GetMember(openapi::StringT(OPENAPI_LITERAL(GID))); } if(j.HasKey(openapi::StringT(OPENAPI_LITERAL(Mode)))) { using V = remove_optionalmode)>::type; this->mode = j.GetMember(openapi::StringT(OPENAPI_LITERAL(Mode))); } } #ifndef CAMERA_HPP #define CAMERA_HPP #include #include #include #include #include #include namespace GL3 { //! //! \brief FPS view Camera class //! //! This class provides view matrix and projection matrix getter for //! retrieving vertices which is transformed into camera space. //! Also provide UBO(UniformBufferObject) for binding camera to multiple shader. //! class Camera { public: //! Default constructor Camera(); //! Default destructor virtual ~Camera(); //! Initialize the camera bool SetupUniformBuffer(); //! Setup camera position, direction and up vector. void SetupCamera(const glm::vec3& pos, const glm::vec3& dir, const glm::vec3& up); //! Returns view matrix glm::mat4 GetViewMatrix(); //! Returns projection matrix glm::mat4 GetProjectionMatrix(); //! Bind the uniform buffer to the current context. void BindCamera(GLuint bindingPoint) const; //! Unbind camera //! declared as static because nothing related with member variables or //! method static void UnbindCamera(); //! Returns the uniform buffer ID GLuint GetUniformBuffer() const; //! Update the matrix with specific methods, such as perspective or //! orthogonal. void UpdateMatrix(); //! Process the continuous key input void ProcessInput(unsigned int key); //! Process the continuous mouse cursor position input void ProcessCursorPos(double xpos, double ypos); //! Cleanup the resources void CleanUp(); protected: virtual void OnUpdateMatrix(){}; glm::mat4 _projection, _view; glm::vec3 _position, _direction, _up; private: //! Returns the uniform variable location matched with given name. GLint GetUniformLocation(const std::string& name); std::unordered_map _uniformCache; DebugUtils _debug; float _speed; GLuint _uniformBuffer; }; }; // namespace GL3 #endif //! end of Camera.hpp#include "parse/actions/dispatch.hpp" #include using namespace Parse; TEST_CASE("Parse.Capture.Dispatch", "[Capture]") { // TODO single_dispatch tests // TODO multi_dispatch tests } wgsyd/wgtf #ifndef WG_DLINK_HPP_INCLUDED #define WG_DLINK_HPP_INCLUDED #include "core_common/assert.hpp" #include /** Calculate pointer to holder of the link. Example: @code // declare some object that holds a link typedef std::pair Holder; Holder holder; // declare an empty link that is used to manage list DLink list; // add object to the list list.append(&holder.second); // get object pointer from list Holder* deducedHolder = dlink_holder(Holder, second, list.next()); TF_ASSERT(deducedHolder == &holder); @endcode */ #define dlink_holder(HolderType, member, link) \ reinterpret_cast(reinterpret_cast(link) - offsetof(HolderType, member)) namespace wgt { /** Utility class to link objects into lists. Class invariants: @li both next() and prev() are always set and valid; @li this->next()->prev() == this->prev()->next() == this */ class DLink { public: DLink(); DLink(const DLink& v); ~DLink(); DLink& operator=(const DLink& v); /** Check if this link is linked with anything else but self. */ bool isLinked() const; /** Remove this link from list. */ void unlink(); /** Make the specified link to go before this one. */ void prepend(DLink* link); /** Make the specified link to go after this one. */ void append(DLink* link); DLink* next() const { return next_; } DLink* prev() const { return prev_; } private: DLink* next_; DLink* prev_; }; } #endif 0 // Code generated by stanc v2.25.0 #include namespace exponential_growth_model_namespace { inline void validate_positive_index(const char* var_name, const char* expr, int val) { if (val < 1) { std::stringstream msg; msg << "Found dimension size less than one in simplex declaration" << "; variable=" << var_name << "; dimension size expression=" << expr << "; expression value=" << val; std::string msg_str(msg.str()); throw std::invalid_argument(msg_str.c_str()); } } inline void validate_unit_vector_index(const char* var_name, const char* expr, int val) { if (val <= 1) { std::stringstream msg; if (val == 1) { msg << "Found dimension size one in unit vector declaration." << " One-dimensional unit vector is discrete" << " but the target distribution must be continuous." << " variable=" << var_name << "; dimension size expression=" << expr; } else { msg << "Found dimension size less than one in unit vector declaration" << "; variable=" << var_name << "; dimension size expression=" << expr << "; expression value=" << val; } std::string msg_str(msg.str()); throw std::invalid_argument(msg_str.c_str()); } } using std::istream; using std::string; using std::stringstream; using std::vector; using std::pow; using stan::io::dump; using stan::math::lgamma; using stan::model::model_base_crtp; using stan::model::rvalue; using stan::model::cons_list; using stan::model::index_uni; using stan::model::index_max; using stan::model::index_min; using stan::model::index_min_max; using stan::model::index_multi; using stan::model::index_omni; using stan::model::nil_index_list; using namespace stan::math; using stan::math::pow; static int current_statement__ = 0; static const std::vector locations_array__ = {" (found before start of program)", " (in '/Users/gchure/Dropbox/git/postdoc_projects/growth_curve_troubleshooting/code/stan/exponential_growth.stan', line 13, column 4 to column 24)", " (in '/Users/gchure/Dropbox/git/postdoc_projects/growth_curve_troubleshooting/code/stan/exponential_growth.stan', line 14, column 4 to column 24)", " (in '/Users/gchure/Dropbox/git/postdoc_projects/growth_curve_troubleshooting/code/stan/exponential_growth.stan', line 15, column 4 to column 21)", " (in '/Users/gchure/Dropbox/git/postdoc_projects/growth_curve_troubleshooting/code/stan/exponential_growth.stan', line 20, column 11 to column 12)", " (in '/Users/gchure/Dropbox/git/postdoc_projects/growth_curve_troubleshooting/code/stan/exponential_growth.stan', line 20, column 4 to column 62)", " (in '/Users/gchure/Dropbox/git/postdoc_projects/growth_curve_troubleshooting/code/stan/exponential_growth.stan', line 23, column 4 to column 27)", " (in '/Users/gchure/Dropbox/git/postdoc_projects/growth_curve_troubleshooting/code/stan/exponential_growth.stan', line 24, column 4 to column 31)", " (in '/Users/gchure/Dropbox/git/postdoc_projects/growth_curve_troubleshooting/code/stan/exponential_growth.stan', line 25, column 4 to column 26)", " (in '/Users/gchure/Dropbox/git/postdoc_projects/growth_curve_troubleshooting/code/stan/exponential_growth.stan', line 28, column 4 to column 32)", " (in '/Users/gchure/Dropbox/git/postdoc_projects/growth_curve_troubleshooting/code/stan/exponential_growth.stan', line 3, column 4 to column 19)", " (in '/Users/gchure/Dropbox/git/postdoc_projects/growth_curve_troubleshooting/code/stan/exponential_growth.stan', line 4, column 4 to column 19)", " (in '/Users/gchure/Dropbox/git/postdoc_projects/growth_curve_troubleshooting/code/stan/exponential_growth.stan', line 5, column 30 to column 31)", " (in '/Users/gchure/Dropbox/git/postdoc_projects/growth_curve_troubleshooting/code/stan/exponential_growth.stan', line 5, column 4 to column 33)", " (in '/Users/gchure/Dropbox/git/postdoc_projects/growth_curve_troubleshooting/code/stan/exponential_growth.stan', line 8, column 11 to column 12)", " (in '/Users/gchure/Dropbox/git/postdoc_projects/growth_curve_troubleshooting/code/stan/exponential_growth.stan', line 8, column 4 to column 19)", " (in '/Users/gchure/Dropbox/git/postdoc_projects/growth_curve_troubleshooting/code/stan/exponential_growth.stan', line 9, column 11 to column 12)", " (in '/Users/gchure/Dropbox/git/postdoc_projects/growth_curve_troubleshooting/code/stan/exponential_growth.stan', line 9, column 4 to column 22)", " (in '/Users/gchure/Dropbox/git/postdoc_projects/growth_curve_troubleshooting/code/stan/exponential_growth.stan', line 14, column 11 to column 12)", " (in '/Users/gchure/Dropbox/git/postdoc_projects/growth_curve_troubleshooting/code/stan/exponential_growth.stan', line 15, column 11 to column 12)"}; class exponential_growth_model final : public model_base_crtp { private: int N; int J; std::vector idx; Eigen::Matrix time; Eigen::Matrix density; public: ~exponential_growth_model() final { } std::string model_name() const final { return "exponential_growth_model"; } std::vector model_compile_info() const { std::vector stanc_info; stanc_info.push_back("stanc_version = stanc3 v2.25.0"); stanc_info.push_back("stancflags = "); return stanc_info; } exponential_growth_model(stan::io::var_context& context__, unsigned int random_seed__ = 0, std::ostream* pstream__ = nullptr) : model_base_crtp(0) { using local_scalar_t__ = double ; boost::ecuyer1988 base_rng__ = stan::services::util::create_rng(random_seed__, 0); (void) base_rng__; // suppress unused var warning static const char* function__ = "exponential_growth_model_namespace::exponential_growth_model"; (void) function__; // suppress unused var warning local_scalar_t__ DUMMY_VAR__(std::numeric_limits::quiet_NaN()); (void) DUMMY_VAR__; // suppress unused var warning try { int pos__; pos__ = std::numeric_limits::min(); pos__ = 1; current_statement__ = 10; context__.validate_dims("data initialization","N","int", context__.to_vec()); N = std::numeric_limits::min(); current_statement__ = 10; N = context__.vals_i("N")[(1 - 1)]; current_statement__ = 10; current_statement__ = 10; check_greater_or_equal(function__, "N", N, 1); current_statement__ = 11; context__.validate_dims("data initialization","J","int", context__.to_vec()); J = std::numeric_limits::min(); current_statement__ = 11; J = context__.vals_i("J")[(1 - 1)]; current_statement__ = 11; current_statement__ = 11; check_greater_or_equal(function__, "J", J, 1); current_statement__ = 12; validate_non_negative_index("idx", "N", N); current_statement__ = 13; context__.validate_dims("data initialization","idx","int", context__.to_vec(N)); idx = std::vector(N, std::numeric_limits::min()); current_statement__ = 13; assign(idx, nil_index_list(), context__.vals_i("idx"), "assigning variable idx"); current_statement__ = 13; for (int sym1__ = 1; sym1__ <= N; ++sym1__) { current_statement__ = 13; current_statement__ = 13; check_greater_or_equal(function__, "idx[sym1__]", idx[(sym1__ - 1)], 1);} current_statement__ = 13; for (int sym1__ = 1; sym1__ <= N; ++sym1__) { current_statement__ = 13; current_statement__ = 13; check_less_or_equal(function__, "idx[sym1__]", idx[(sym1__ - 1)], J); } current_statement__ = 14; validate_non_negative_index("time", "N", N); current_statement__ = 15; context__.validate_dims("data initialization","time","double", context__.to_vec(N)); time = Eigen::Matrix(N); stan::math::fill(time, std::numeric_limits::quiet_NaN()); { std::vector time_flat__; current_statement__ = 15; assign(time_flat__, nil_index_list(), context__.vals_r("time"), "assigning variable time_flat__"); current_statement__ = 15; pos__ = 1; current_statement__ = 15; for (int sym1__ = 1; sym1__ <= N; ++sym1__) { current_statement__ = 15; assign(time, cons_list(index_uni(sym1__), nil_index_list()), time_flat__[(pos__ - 1)], "assigning variable time"); current_statement__ = 15; pos__ = (pos__ + 1);} } current_statement__ = 16; validate_non_negative_index("density", "N", N); current_statement__ = 17; context__.validate_dims("data initialization","density","double", context__.to_vec(N)); density = Eigen::Matrix(N); stan::math::fill(density, std::numeric_limits::quiet_NaN()); { std::vector density_flat__; current_statement__ = 17; assign(density_flat__, nil_index_list(), context__.vals_r("density"), "assigning variable density_flat__"); current_statement__ = 17; pos__ = 1; current_statement__ = 17; for (int sym1__ = 1; sym1__ <= N; ++sym1__) { current_statement__ = 17; assign(density, cons_list(index_uni(sym1__), nil_index_list()), density_flat__[(pos__ - 1)], "assigning variable density"); current_statement__ = 17; pos__ = (pos__ + 1);} } current_statement__ = 18; validate_non_negative_index("density_0", "J", J); current_statement__ = 19; validate_non_negative_index("lambda", "J", J); } catch (const std::exception& e) { stan::lang::rethrow_located(e, locations_array__[current_statement__]); // Next line prevents compiler griping about no return throw std::runtime_error("*** IF YOU SEE THIS, PLEASE REPORT A BUG ***"); } num_params_r__ = 0U; try { num_params_r__ += 1; num_params_r__ += J; num_params_r__ += J; } catch (const std::exception& e) { stan::lang::rethrow_located(e, locations_array__[current_statement__]); // Next line prevents compiler griping about no return throw std::runtime_error("*** IF YOU SEE THIS, PLEASE REPORT A BUG ***"); } } template inline T__ log_prob(std::vector& params_r__, std::vector& params_i__, std::ostream* pstream__ = nullptr) const { using local_scalar_t__ = T__; T__ lp__(0.0); stan::math::accumulator lp_accum__; static const char* function__ = "exponential_growth_model_namespace::log_prob"; (void) function__; // suppress unused var warning stan::io::reader in__(params_r__, params_i__); local_scalar_t__ DUMMY_VAR__(std::numeric_limits::quiet_NaN()); (void) DUMMY_VAR__; // suppress unused var warning try { local_scalar_t__ sigma; sigma = DUMMY_VAR__; current_statement__ = 1; sigma = in__.scalar(); current_statement__ = 1; if (jacobian__) { current_statement__ = 1; sigma = stan::math::lb_constrain(sigma, 0, lp__); } else { current_statement__ = 1; sigma = stan::math::lb_constrain(sigma, 0); } Eigen::Matrix density_0; density_0 = Eigen::Matrix(J); stan::math::fill(density_0, DUMMY_VAR__); current_statement__ = 2; density_0 = in__.vector(J); Eigen::Matrix lambda; lambda = Eigen::Matrix(J); stan::math::fill(lambda, DUMMY_VAR__); current_statement__ = 3; lambda = in__.vector(J); { current_statement__ = 4; validate_non_negative_index("mu", "N", N); Eigen::Matrix mu; mu = Eigen::Matrix(N); stan::math::fill(mu, DUMMY_VAR__); current_statement__ = 5; assign(mu, nil_index_list(), elt_multiply( rvalue(density_0, cons_list(index_multi(idx), nil_index_list()), "density_0"), stan::math::exp( elt_multiply( rvalue(lambda, cons_list(index_multi(idx), nil_index_list()), "lambda"), time))), "assigning variable mu"); current_statement__ = 6; lp_accum__.add(normal_lpdf(sigma, 0, 0.1)); current_statement__ = 7; lp_accum__.add(normal_lpdf(density_0, 0, 0.1)); current_statement__ = 8; lp_accum__.add(normal_lpdf(lambda, 0, 1)); current_statement__ = 9; lp_accum__.add(normal_lpdf(density, mu, sigma)); } } catch (const std::exception& e) { stan::lang::rethrow_located(e, locations_array__[current_statement__]); // Next line prevents compiler griping about no return throw std::runtime_error("*** IF YOU SEE THIS, PLEASE REPORT A BUG ***"); } lp_accum__.add(lp__); return lp_accum__.sum(); } // log_prob() template inline void write_array(RNG& base_rng__, std::vector& params_r__, std::vector& params_i__, std::vector& vars__, bool emit_transformed_parameters__ = true, bool emit_generated_quantities__ = true, std::ostream* pstream__ = nullptr) const { using local_scalar_t__ = double; vars__.resize(0); stan::io::reader in__(params_r__, params_i__); static const char* function__ = "exponential_growth_model_namespace::write_array"; (void) function__; // suppress unused var warning (void) function__; // suppress unused var warning double lp__ = 0.0; (void) lp__; // dummy to suppress unused var warning stan::math::accumulator lp_accum__; local_scalar_t__ DUMMY_VAR__(std::numeric_limits::quiet_NaN()); (void) DUMMY_VAR__; // suppress unused var warning try { double sigma; sigma = std::numeric_limits::quiet_NaN(); current_statement__ = 1; sigma = in__.scalar(); current_statement__ = 1; sigma = stan::math::lb_constrain(sigma, 0); Eigen::Matrix density_0; density_0 = Eigen::Matrix(J); stan::math::fill(density_0, std::numeric_limits::quiet_NaN()); current_statement__ = 2; density_0 = in__.vector(J); Eigen::Matrix lambda; lambda = Eigen::Matrix(J); stan::math::fill(lambda, std::numeric_limits::quiet_NaN()); current_statement__ = 3; lambda = in__.vector(J); vars__.emplace_back(sigma); for (int sym1__ = 1; sym1__ <= J; ++sym1__) { vars__.emplace_back(density_0[(sym1__ - 1)]);} for (int sym1__ = 1; sym1__ <= J; ++sym1__) { vars__.emplace_back(lambda[(sym1__ - 1)]);} if (logical_negation((primitive_value(emit_transformed_parameters__) || primitive_value(emit_generated_quantities__)))) { return ; } if (logical_negation(emit_generated_quantities__)) { return ; } } catch (const std::exception& e) { stan::lang::rethrow_located(e, locations_array__[current_statement__]); // Next line prevents compiler griping about no return throw std::runtime_error("*** IF YOU SEE THIS, PLEASE REPORT A BUG ***"); } } // write_array() inline void transform_inits(const stan::io::var_context& context__, std::vector& params_i__, std::vector& vars__, std::ostream* pstream__) const final { using local_scalar_t__ = double; vars__.clear(); vars__.reserve(num_params_r__); try { int pos__; pos__ = std::numeric_limits::min(); pos__ = 1; double sigma; sigma = std::numeric_limits::quiet_NaN(); current_statement__ = 1; sigma = context__.vals_r("sigma")[(1 - 1)]; double sigma_free__; sigma_free__ = std::numeric_limits::quiet_NaN(); current_statement__ = 1; sigma_free__ = stan::math::lb_free(sigma, 0); Eigen::Matrix density_0; density_0 = Eigen::Matrix(J); stan::math::fill(density_0, std::numeric_limits::quiet_NaN()); { std::vector density_0_flat__; current_statement__ = 2; assign(density_0_flat__, nil_index_list(), context__.vals_r("density_0"), "assigning variable density_0_flat__"); current_statement__ = 2; pos__ = 1; current_statement__ = 2; for (int sym1__ = 1; sym1__ <= J; ++sym1__) { current_statement__ = 2; assign(density_0, cons_list(index_uni(sym1__), nil_index_list()), density_0_flat__[(pos__ - 1)], "assigning variable density_0"); current_statement__ = 2; pos__ = (pos__ + 1);} } Eigen::Matrix lambda; lambda = Eigen::Matrix(J); stan::math::fill(lambda, std::numeric_limits::quiet_NaN()); { std::vector lambda_flat__; current_statement__ = 3; assign(lambda_flat__, nil_index_list(), context__.vals_r("lambda"), "assigning variable lambda_flat__"); current_statement__ = 3; pos__ = 1; current_statement__ = 3; for (int sym1__ = 1; sym1__ <= J; ++sym1__) { current_statement__ = 3; assign(lambda, cons_list(index_uni(sym1__), nil_index_list()), lambda_flat__[(pos__ - 1)], "assigning variable lambda"); current_statement__ = 3; pos__ = (pos__ + 1);} } vars__.emplace_back(sigma_free__); for (int sym1__ = 1; sym1__ <= J; ++sym1__) { vars__.emplace_back(density_0[(sym1__ - 1)]);} for (int sym1__ = 1; sym1__ <= J; ++sym1__) { vars__.emplace_back(lambda[(sym1__ - 1)]);} } catch (const std::exception& e) { stan::lang::rethrow_located(e, locations_array__[current_statement__]); // Next line prevents compiler griping about no return throw std::runtime_error("*** IF YOU SEE THIS, PLEASE REPORT A BUG ***"); } } // transform_inits() inline void get_param_names(std::vector& names__) const { names__.clear(); names__.emplace_back("sigma"); names__.emplace_back("density_0"); names__.emplace_back("lambda"); } // get_param_names() inline void get_dims(std::vector>& dimss__) const final { dimss__.clear(); dimss__.emplace_back(std::vector{}); dimss__.emplace_back(std::vector{static_cast(J)}); dimss__.emplace_back(std::vector{static_cast(J)}); } // get_dims() inline void constrained_param_names( std::vector& param_names__, bool emit_transformed_parameters__ = true, bool emit_generated_quantities__ = true) const final { param_names__.emplace_back(std::string() + "sigma"); for (int sym1__ = 1; sym1__ <= J; ++sym1__) { { param_names__.emplace_back(std::string() + "density_0" + '.' + std::to_string(sym1__)); }} for (int sym1__ = 1; sym1__ <= J; ++sym1__) { { param_names__.emplace_back(std::string() + "lambda" + '.' + std::to_string(sym1__)); }} if (emit_transformed_parameters__) { } if (emit_generated_quantities__) { } } // constrained_param_names() inline void unconstrained_param_names( std::vector& param_names__, bool emit_transformed_parameters__ = true, bool emit_generated_quantities__ = true) const final { param_names__.emplace_back(std::string() + "sigma"); for (int sym1__ = 1; sym1__ <= J; ++sym1__) { { param_names__.emplace_back(std::string() + "density_0" + '.' + std::to_string(sym1__)); }} for (int sym1__ = 1; sym1__ <= J; ++sym1__) { { param_names__.emplace_back(std::string() + "lambda" + '.' + std::to_string(sym1__)); }} if (emit_transformed_parameters__) { } if (emit_generated_quantities__) { } } // unconstrained_param_names() inline std::string get_constrained_sizedtypes() const { stringstream s__; s__ << "[{\"name\":\"sigma\",\"type\":{\"name\":\"real\"},\"block\":\"parameters\"},{\"name\":\"density_0\",\"type\":{\"name\":\"vector\",\"length\":" << J << "},\"block\":\"parameters\"},{\"name\":\"lambda\",\"type\":{\"name\":\"vector\",\"length\":" << J << "},\"block\":\"parameters\"}]"; return s__.str(); } // get_constrained_sizedtypes() inline std::string get_unconstrained_sizedtypes() const { stringstream s__; s__ << "[{\"name\":\"sigma\",\"type\":{\"name\":\"real\"},\"block\":\"parameters\"},{\"name\":\"density_0\",\"type\":{\"name\":\"vector\",\"length\":" << J << "},\"block\":\"parameters\"},{\"name\":\"lambda\",\"type\":{\"name\":\"vector\",\"length\":" << J << "},\"block\":\"parameters\"}]"; return s__.str(); } // get_unconstrained_sizedtypes() // Begin method overload boilerplate template inline void write_array(RNG& base_rng__, Eigen::Matrix& params_r, Eigen::Matrix& vars, bool emit_transformed_parameters__ = true, bool emit_generated_quantities__ = true, std::ostream* pstream = nullptr) const { std::vector params_r_vec(params_r.size()); for (int i = 0; i < params_r.size(); ++i) params_r_vec[i] = params_r(i); std::vector vars_vec; std::vector params_i_vec; write_array(base_rng__, params_r_vec, params_i_vec, vars_vec, emit_transformed_parameters__, emit_generated_quantities__, pstream); vars.resize(vars_vec.size()); for (int i = 0; i < vars.size(); ++i) vars(i) = vars_vec[i]; } template inline T_ log_prob(Eigen::Matrix& params_r, std::ostream* pstream = nullptr) const { std::vector vec_params_r; vec_params_r.reserve(params_r.size()); for (int i = 0; i < params_r.size(); ++i) vec_params_r.push_back(params_r(i)); std::vector vec_params_i; return log_prob(vec_params_r, vec_params_i, pstream); } inline void transform_inits(const stan::io::var_context& context, Eigen::Matrix& params_r, std::ostream* pstream__ = nullptr) const { std::vector params_r_vec; std::vector params_i_vec; transform_inits(context, params_i_vec, params_r_vec, pstream__); params_r.resize(params_r_vec.size()); for (int i = 0; i < params_r.size(); ++i) params_r(i) = params_r_vec[i]; } }; } using stan_model = exponential_growth_model_namespace::exponential_growth_model; #ifndef USING_R // Boilerplate stan::model::model_base& new_model( stan::io::var_context& data_context, unsigned int seed, std::ostream* msg_stream) { stan_model* m = new stan_model(data_context, seed, msg_stream); return *m; } #endif // Copyright 2011 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 "trustedipsmanager.h" #ifndef _WIN32 #include #include #include #endif #include #include #include namespace { class TrustedipsmanagerTest : public ::testing::Test { protected: bool IsTrustedClient(const std::string& ip) { struct in_addr in; inet_aton(ip.c_str(), &in); return trusted_.IsTrustedClient(in); } devtools_goma::TrustedIpsManager trusted_; }; TEST_F(TrustedipsmanagerTest, Basic) { EXPECT_EQ("TrustedClients[127.0.0.1/ffffffff]", trusted_.DebugString()); EXPECT_TRUE(IsTrustedClient("127.0.0.1")); EXPECT_FALSE(IsTrustedClient("192.168.1.1")); EXPECT_FALSE(IsTrustedClient("192.168.1.2")); EXPECT_FALSE(IsTrustedClient("192.168.2.1")); EXPECT_FALSE(IsTrustedClient("10.0.0.1")); trusted_.AddAllow("192.168.1.1"); EXPECT_EQ("TrustedClients[127.0.0.1/ffffffff,192.168.1.1/ffffffff]", trusted_.DebugString()); EXPECT_TRUE(IsTrustedClient("192.168.1.1")); EXPECT_FALSE(IsTrustedClient("192.168.1.2")); trusted_.AddAllow("192.168.1.0/24"); EXPECT_EQ("TrustedClients[127.0.0.1/ffffffff,192.168.1.1/ffffffff," "192.168.1.0/ffffff00]", trusted_.DebugString()); EXPECT_TRUE(IsTrustedClient("192.168.1.1")); EXPECT_TRUE(IsTrustedClient("192.168.1.2")); EXPECT_FALSE(IsTrustedClient("192.168.2.1")); trusted_.AddAllow("0.0.0.0/0"); EXPECT_EQ("TrustedClients[127.0.0.1/ffffffff,192.168.1.1/ffffffff," "192.168.1.0/ffffff00,0.0.0.0/0]", trusted_.DebugString()); EXPECT_TRUE(IsTrustedClient("192.168.2.1")); EXPECT_TRUE(IsTrustedClient("10.0.0.1")); } } // namespace #include #include #include using namespace std; int n, i, j, c, l, nw[626], arr[26][26], gph[26][26]; vector v; void dfs(int x, int y, int b) { if (x > 0 && y > 0 && x <= n && y <= n && gph[x][y] == 0 && arr[x][y]) { gph[x][y] = b; dfs(x + 1, y, b); dfs(x - 1, y, b); dfs(x, y + 1, b); dfs(x, y - 1, b); } } int main() { scanf("%d", &n); for (i = 1; i <= n; i++) for (j = 1; j <= n; j++) scanf("%1d", &arr[i][j]); for (i = 1; i <= n; i++) for (j = 1; j <= n; j++) dfs(i, j, ++l); for (i = 1; i <= n; i++) { for (j = 1; j <= n; j++) { if (arr[i][j]) { if (nw[gph[i][j]] == 0) { c++; nw[gph[i][j]] = 1; } else nw[gph[i][j]]++; } } } cout << c << "\n"; for (i = 1; i <= n * n; i++) if (nw[i]) v.push_back(nw[i]); sort(v.begin(), v.end()); for (auto i: v) cout << i << "\n"; return 0; } 0 #include "Scene.h" Scene::Scene(Camera *camera) { Scene::camera = camera; head_diffuse = new Texture("obj/african_head/african_head_diffuse.tga", GL_TEXTURE_2D, GL_TEXTURE0, GL_RGB, GL_UNSIGNED_BYTE); white_tex = new Texture("obj/white_texture.png", GL_TEXTURE_2D, GL_TEXTURE0, GL_RGB, GL_UNSIGNED_BYTE); Mesh *head = new Mesh("obj/african_head/african_head.obj"); head->texture = head_diffuse; head->SetName("head"); AddObject(head); } Scene::~Scene() { for (int i = 0; i < objects.size(); i++) { delete objects[i]; } delete head_diffuse; delete white_tex; } Light *Scene::GetMainLight() { Light *mainLight = NULL; for (int i = 0; i < objects.size(); i++) { Object *object = objects[i]; if (object->GetType() == Type_Light && object->isEnabled) { Light *light = (Light*)object; if (mainLight == NULL || light->intensity > mainLight->intensity) mainLight = light; } } return mainLight; } void Scene::Draw(Shader *shader) { Light *mainLight = GetMainLight(); glm::vec3 lightPos; glm::vec3 lightColor; if (mainLight) { lightPos = mainLight->GetLightPosition(); lightColor = mainLight->color * mainLight->intensity; } else { lightPos = -camera->Orientation; lightColor = glm::vec3(1); } for (int i = 0; i < objects.size(); i++) { Object *object = objects[i]; if (object->GetType() == Type_Mesh && object->isEnabled) { Mesh *mesh = (Mesh*)object; mesh->Draw(*camera, lightPos, lightColor, shader); } } } int Scene::AddPrimitive(std::string name) { Mesh *mesh = new Mesh(("obj/" + name + ".obj").c_str()); mesh->texture = white_tex; strcpy(mesh->name, name.c_str()); return AddObject(mesh); } int Scene::AddObject(Object *object) { objects.push_back(object); return objects.size() - 1; } void Scene::RemoveObject(int index) { Object *object = objects[index]; objects.erase(objects.begin() + index); delete object; }/** * The MIT License (MIT) * * Copyright (c) 2014 athre0z * * 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 "Utils.hpp" #include "Settings.hpp" #include "Config.hpp" #include "Core.hpp" #include #include #include #include #include #include #include // ============================================================================ /** * @brief Initialization callback for IDA. * @return A @c PLUGIN_ constant from loader.hpp. */ int idaapi init() { if (!is_idaq()) return PLUGIN_SKIP; msg("[" PLUGIN_NAME "] " PLUGIN_TEXTUAL_VERSION " by athre0z loaded!\n"); try { Core::instance(); } catch (const std::runtime_error &e) { msg("[" PLUGIN_NAME "][ERROR] Cannot load plugin: %s\n", e.what()); return PLUGIN_UNL; } return PLUGIN_KEEP; } /** * @brief Run callback for IDA. */ void idaapi run(int /*arg*/) { Core::instance().runPlugin(); } /** * @brief Shutdown callback for IDA. */ void idaapi term() { if (Core::isInstantiated()) Core::freeInstance(); } plugin_t PLUGIN = { IDP_INTERFACE_VERSION, PLUGIN_FIX, &init, &term, &run, "Advanced IDA skinning", "Plugin providing advanced skinning features using Qt stylesheets.", PLUGIN_NAME ": Settings", "Ctrl-Shift-S" }; // ============================================================================ Wzzzx/chromium-crosswalkextensions/renderer/extension_frame_helper.cc // Copyright 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 "extensions/renderer/extension_frame_helper.h" #include "base/strings/string_util.h" #include "content/public/renderer/render_frame.h" #include "extensions/common/api/messaging/message.h" #include "extensions/common/constants.h" #include "extensions/common/extension_messages.h" #include "extensions/common/manifest_handlers/background_info.h" #include "extensions/renderer/console.h" #include "extensions/renderer/content_watcher.h" #include "extensions/renderer/dispatcher.h" #include "extensions/renderer/messaging_bindings.h" #include "extensions/renderer/script_context.h" #include "third_party/WebKit/public/platform/WebSecurityOrigin.h" #include "third_party/WebKit/public/web/WebConsoleMessage.h" #include "third_party/WebKit/public/web/WebDocument.h" #include "third_party/WebKit/public/web/WebLocalFrame.h" namespace extensions { namespace { base::LazyInstance> g_frame_helpers = LAZY_INSTANCE_INITIALIZER; // Returns true if the render frame corresponding with |frame_helper| matches // the given criteria. bool RenderFrameMatches(const ExtensionFrameHelper* frame_helper, ViewType match_view_type, int match_window_id, const std::string& match_extension_id) { if (match_view_type != VIEW_TYPE_INVALID && frame_helper->view_type() != match_view_type) return false; // Not all frames have a valid ViewType, e.g. devtools, most GuestViews, and // unclassified detached WebContents. if (frame_helper->view_type() == VIEW_TYPE_INVALID) return false; // This logic matches ExtensionWebContentsObserver::GetExtensionFromFrame. blink::WebSecurityOrigin origin = frame_helper->render_frame()->GetWebFrame()->getSecurityOrigin(); if (origin.isUnique() || !base::EqualsASCII(base::StringPiece16(origin.protocol()), kExtensionScheme) || !base::EqualsASCII(base::StringPiece16(origin.host()), match_extension_id.c_str())) return false; if (match_window_id != extension_misc::kUnknownWindowId && frame_helper->browser_window_id() != match_window_id) return false; return true; } // Runs every callback in |callbacks_to_be_run_and_cleared| while |frame_helper| // is valid, and clears |callbacks_to_be_run_and_cleared|. void RunCallbacksWhileFrameIsValid( base::WeakPtr frame_helper, std::vector* callbacks_to_be_run_and_cleared) { // The JavaScript code can cause re-entrancy. To avoid a deadlock, don't run // callbacks that are added during the iteration. std::vector callbacks; callbacks_to_be_run_and_cleared->swap(callbacks); for (auto& callback : callbacks) { callback.Run(); if (!frame_helper.get()) return; // Frame and ExtensionFrameHelper invalidated by callback. } } } // namespace ExtensionFrameHelper::ExtensionFrameHelper(content::RenderFrame* render_frame, Dispatcher* extension_dispatcher) : content::RenderFrameObserver(render_frame), content::RenderFrameObserverTracker(render_frame), view_type_(VIEW_TYPE_INVALID), tab_id_(-1), browser_window_id_(-1), extension_dispatcher_(extension_dispatcher), did_create_current_document_element_(false), weak_ptr_factory_(this) { g_frame_helpers.Get().insert(this); } ExtensionFrameHelper::~ExtensionFrameHelper() { g_frame_helpers.Get().erase(this); } // static std::vector ExtensionFrameHelper::GetExtensionFrames( const std::string& extension_id, int browser_window_id, ViewType view_type) { std::vector render_frames; for (const ExtensionFrameHelper* helper : g_frame_helpers.Get()) { if (RenderFrameMatches(helper, view_type, browser_window_id, extension_id)) render_frames.push_back(helper->render_frame()); } return render_frames; } // static content::RenderFrame* ExtensionFrameHelper::GetBackgroundPageFrame( const std::string& extension_id) { for (const ExtensionFrameHelper* helper : g_frame_helpers.Get()) { if (RenderFrameMatches(helper, VIEW_TYPE_EXTENSION_BACKGROUND_PAGE, extension_misc::kUnknownWindowId, extension_id)) { blink::WebLocalFrame* web_frame = helper->render_frame()->GetWebFrame(); // Check if this is the top frame. if (web_frame->top() == web_frame) return helper->render_frame(); } } return nullptr; } // static bool ExtensionFrameHelper::IsContextForEventPage(const ScriptContext* context) { content::RenderFrame* render_frame = context->GetRenderFrame(); return context->extension() && render_frame && BackgroundInfo::HasLazyBackgroundPage(context->extension()) && ExtensionFrameHelper::Get(render_frame)->view_type() == VIEW_TYPE_EXTENSION_BACKGROUND_PAGE; } void ExtensionFrameHelper::DidCreateDocumentElement() { did_create_current_document_element_ = true; extension_dispatcher_->DidCreateDocumentElement( render_frame()->GetWebFrame()); } void ExtensionFrameHelper::DidCreateNewDocument() { did_create_current_document_element_ = false; } void ExtensionFrameHelper::RunScriptsAtDocumentStart() { DCHECK(did_create_current_document_element_); RunCallbacksWhileFrameIsValid(weak_ptr_factory_.GetWeakPtr(), &document_element_created_callbacks_); // |this| might be dead by now. } void ExtensionFrameHelper::RunScriptsAtDocumentEnd() { RunCallbacksWhileFrameIsValid(weak_ptr_factory_.GetWeakPtr(), &document_load_finished_callbacks_); // |this| might be dead by now. } void ExtensionFrameHelper::ScheduleAtDocumentStart( const base::Closure& callback) { document_element_created_callbacks_.push_back(callback); } void ExtensionFrameHelper::ScheduleAtDocumentEnd( const base::Closure& callback) { document_load_finished_callbacks_.push_back(callback); } void ExtensionFrameHelper::DidMatchCSS( const blink::WebVector& newly_matching_selectors, const blink::WebVector& stopped_matching_selectors) { extension_dispatcher_->content_watcher()->DidMatchCSS( render_frame()->GetWebFrame(), newly_matching_selectors, stopped_matching_selectors); } void ExtensionFrameHelper::DidCreateScriptContext( v8::Local context, int extension_group, int world_id) { extension_dispatcher_->DidCreateScriptContext( render_frame()->GetWebFrame(), context, extension_group, world_id); } void ExtensionFrameHelper::WillReleaseScriptContext( v8::Local context, int world_id) { extension_dispatcher_->WillReleaseScriptContext( render_frame()->GetWebFrame(), context, world_id); } bool ExtensionFrameHelper::OnMessageReceived(const IPC::Message& message) { bool handled = true; IPC_BEGIN_MESSAGE_MAP(ExtensionFrameHelper, message) IPC_MESSAGE_HANDLER(ExtensionMsg_ValidateMessagePort, OnExtensionValidateMessagePort) IPC_MESSAGE_HANDLER(ExtensionMsg_DispatchOnConnect, OnExtensionDispatchOnConnect) IPC_MESSAGE_HANDLER(ExtensionMsg_DeliverMessage, OnExtensionDeliverMessage) IPC_MESSAGE_HANDLER(ExtensionMsg_DispatchOnDisconnect, OnExtensionDispatchOnDisconnect) IPC_MESSAGE_HANDLER(ExtensionMsg_SetTabId, OnExtensionSetTabId) IPC_MESSAGE_HANDLER(ExtensionMsg_UpdateBrowserWindowId, OnUpdateBrowserWindowId) IPC_MESSAGE_HANDLER(ExtensionMsg_NotifyRenderViewType, OnNotifyRendererViewType) IPC_MESSAGE_HANDLER(ExtensionMsg_Response, OnExtensionResponse) IPC_MESSAGE_HANDLER(ExtensionMsg_MessageInvoke, OnExtensionMessageInvoke) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() return handled; } void ExtensionFrameHelper::OnExtensionValidateMessagePort(int port_id) { MessagingBindings::ValidateMessagePort( extension_dispatcher_->script_context_set(), port_id, render_frame()); } void ExtensionFrameHelper::OnExtensionDispatchOnConnect( int target_port_id, const std::string& channel_name, const ExtensionMsg_TabConnectionInfo& source, const ExtensionMsg_ExternalConnectionInfo& info, const std::string& tls_channel_id) { MessagingBindings::DispatchOnConnect( extension_dispatcher_->script_context_set(), target_port_id, channel_name, source, info, tls_channel_id, render_frame()); } void ExtensionFrameHelper::OnExtensionDeliverMessage(int target_id, int source_tab_id, const Message& message) { MessagingBindings::DeliverMessage( extension_dispatcher_->script_context_set(), target_id, message, render_frame()); } void ExtensionFrameHelper::OnExtensionDispatchOnDisconnect( int port_id, const std::string& error_message) { MessagingBindings::DispatchOnDisconnect( extension_dispatcher_->script_context_set(), port_id, error_message, render_frame()); } void ExtensionFrameHelper::OnExtensionSetTabId(int tab_id) { CHECK_EQ(tab_id_, -1); CHECK_GE(tab_id, 0); tab_id_ = tab_id; } void ExtensionFrameHelper::OnUpdateBrowserWindowId(int browser_window_id) { browser_window_id_ = browser_window_id; } void ExtensionFrameHelper::OnNotifyRendererViewType(ViewType type) { // TODO(devlin): It'd be really nice to be able to // DCHECK_EQ(VIEW_TYPE_INVALID, view_type_) here. view_type_ = type; } void ExtensionFrameHelper::OnExtensionResponse(int request_id, bool success, const base::ListValue& response, const std::string& error) { extension_dispatcher_->OnExtensionResponse(request_id, success, response, error); } void ExtensionFrameHelper::OnExtensionMessageInvoke( const std::string& extension_id, const std::string& module_name, const std::string& function_name, const base::ListValue& args, bool user_gesture) { extension_dispatcher_->InvokeModuleSystemMethod(render_frame(), extension_id, module_name, function_name, args, user_gesture); } void ExtensionFrameHelper::OnDestruct() { delete this; } } // namespace extensions #ifndef _GLSSHADERCONSTEXPRTESTS_HPP #define _GLSSHADERCONSTEXPRTESTS_HPP /*------------------------------------------------------------------------- * drawElements Quality Program OpenGL Shared Module * ------------------------------------------------- * * Copyright 2014 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. * *//*! * \file * \brief Shared shader constant expression test components *//*--------------------------------------------------------------------*/ #include "tcuDefs.hpp" #include "gluShaderUtil.hpp" #include namespace tcu { class TestNode; class TestContext; } namespace glu { class RenderContext; } namespace deqp { namespace gls { namespace ShaderConstExpr { using glu::DataType; struct TestParams { const char* name; const char* expression; DataType inType; int minComponents; int maxComponents; DataType outType; float output; }; enum TestShaderStage { SHADER_VERTEX = 1<<0, SHADER_FRAGMENT = 1<<2, SHADER_BOTH = SHADER_VERTEX | SHADER_FRAGMENT, }; std::vector createTests (tcu::TestContext& testContext, glu::RenderContext& renderContext, const glu::ContextInfo& contextInfo, const TestParams* cases, int numCases, glu::GLSLVersion version, TestShaderStage testStage = SHADER_BOTH); } // ShaderConstExpr } // gls } // deqp #endif // _GLSSHADERCONSTEXPRTESTS_HPP /********************************************************************* File: FeatureDesc.hpp Description: FeatureDesc Header Part. Author: (, ) Created: 2016/09/28 Copyright (c) 2016, Team "FireBase", Open Robot Marathon, IRC. 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 "modinclude.hpp" #if defined(SET_CORE_ENGINE_MODULE_FEATURESEARCHER) #ifndef _FeatureDesc_hpp_ #define _FeatureDesc_hpp_ // dependent module param & mode. #include "FeatureDescParam.hpp" #include "FeatureDescMode.hpp" // System Defines. #include "SystemCommon.hpp" // Core-Engine Defines. #include "CoreDefines.hpp" // Library Supports. #include "OpenCVSupport.hpp" typedef struct _FeatureSets { Mat _Descriptor; vector _Keypoints; int _Cols, _Rows; _FeatureSets() { _Cols = -1; _Rows = -1; } void Set_ImageLength(int Cols, int Rows) { _Cols = Cols; _Rows = Rows; } } FeatureSets; typedef struct _FastParam { int _Threshold; bool _NonmaxSuppression; int _Type; _FastParam() { _Threshold = 10; _NonmaxSuppression = true; _Type = FastFeatureDetector::TYPE_9_16; } IMPLEMENT_GET(int, Threshold, _Threshold) IMPLEMENT_SET(int, Threshold, _Threshold) IMPLEMENT_GET(bool, NonmaxSuppression, _NonmaxSuppression) IMPLEMENT_SET(bool, NonmaxSuppression, _NonmaxSuppression) IMPLEMENT_GET(int, Type, _Type) IMPLEMENT_SET(int, Type, _Type) } FastParam; typedef struct _ORBParam { int _Nfeatures; float _ScaleFactor; int _Nlevels; int _EdgeThreshold; int _FirstLevel; int _WTA_K; int _ScoreType; int _PatchSize; int _FastThreshold; _ORBParam() { _Nfeatures=500; _ScaleFactor=1.2f; _Nlevels=8; _EdgeThreshold=31; _FirstLevel=0; _WTA_K=2; _ScoreType=ORB::HARRIS_SCORE; _PatchSize=31; _FastThreshold=20; } IMPLEMENT_GET(int, Nfeatures, _Nfeatures) IMPLEMENT_SET(int, Nfeatures, _Nfeatures) IMPLEMENT_GET(float, ScaleFactor, _ScaleFactor) IMPLEMENT_SET(float, ScaleFactor, _ScaleFactor) IMPLEMENT_GET(int, Nlevels, _Nlevels) IMPLEMENT_SET(int, Nlevels, _Nlevels) IMPLEMENT_GET(int, EdgeThreshold, _EdgeThreshold) IMPLEMENT_SET(int, EdgeThreshold, _EdgeThreshold) IMPLEMENT_GET(int, FirstLevel, _FirstLevel) IMPLEMENT_SET(int, FirstLevel, _FirstLevel) IMPLEMENT_GET(int, WTA_K, _WTA_K) IMPLEMENT_SET(int, WTA_K, _WTA_K) IMPLEMENT_GET(int, ScoreType, _ScoreType) IMPLEMENT_SET(int, ScoreType, _ScoreType) IMPLEMENT_GET(int, PatchSize, _PatchSize) IMPLEMENT_SET(int, PatchSize, _PatchSize) IMPLEMENT_GET(int, FastThreshold, _FastThreshold) IMPLEMENT_SET(int, FastThreshold, _FastThreshold) } ORBParam; namespace FeatureDescEnum { // for binary Detectors. enum SpicesDetector { S_FAST = 0, S_ORB = 1 }; enum SpicesMatcher { S_BF_L2 = 0, S_BF_L1 = 1, S_BF_H1 = 2, S_BF_H2 = 3, S_FLANN = 4 }; } class FeatureDesc { private: int _DetectorKind; #if !defined(MODE_ONLY_DETECTION) int _ExtractorKind; int _MatcherKind; #endif FastParam _FastParameter; ORBParam _ORBParameter; Ptr _Detector; #if !defined(MODE_ONLY_DETECTION) Ptr _Extractor; Ptr _Matcher; #endif void _Set_FAST(Ptr &__FastDetector); void _Set_ORB(Ptr &__ORBDetector); void _Initialize(int __DetectorKind #if !defined(MODE_ONLY_DETECTION) , int __ExtractorKind, int __MatcherKind #endif ); void _SetDetector(int __DetectorKind); #if !defined(MODE_ONLY_DETECTION) void _SetExtractor(int __ExtractorKind); void _SetMatcher(int __DescriptorMatcherKind); #endif public: FeatureDesc() : _DetectorKind( #if defined(SET_MODE_FAST_DETECTOR) FeatureDescEnum::S_FAST #elif defined(SET_MODE_ORB_DETECTOR) DetectorsEnum::S_ORB #endif ) #if !defined(MODE_ONLY_DETECTION) , _ExtractorKind( #if defined(SET_MODE_FAST_DETECTOR) FeatureDescEnum::S_FAST #elif defined(SET_MODE_ORB_DETECTOR) DetectorsEnum::S_ORB #endif ), _MatcherKind( #if defined(SET_MODE_BF_MATCHER) FeatureDescEnum::S_BF_H1 #endif ) #endif { _Initialize(_DetectorKind #if !defined(MODE_ONLY_DETECTION) , _ExtractorKind, _MatcherKind #endif ); } FeatureDesc(int __DetectorKind = FeatureDescEnum::S_ORB) : _DetectorKind(__DetectorKind #if !defined(MODE_ONLY_DETECTION) ), _ExtractorKind(FeatureDescEnum::S_ORB), _MatcherKind( #if (MATCHER_NEIGHBORS_K < 3) FeatureDescEnum::S_BF_H1 #else DetectorsEnum::S_BF_H2 #endif #endif ){} #if !defined(MODE_ONLY_DETECTION) FeatureDesc(int __DetectorKind = FeatureDescEnum::S_ORB, int __ExtractorKind = FeatureDescEnum::S_ORB) : _DetectorKind(__DetectorKind), _ExtractorKind(__ExtractorKind), _MatcherKind( #if (MATCHER_NEIGHBORS_K < 3) FeatureDescEnum::S_BF_H1 #else DetectorsEnum::S_BF_H2 #endif ){} FeatureDesc(int __DetectorKind = -1, int __ExtractorKind = -1, int __MatcherKind = -1) : _DetectorKind(__DetectorKind), _ExtractorKind(__ExtractorKind), _MatcherKind(__MatcherKind) {} #endif ~FeatureDesc() {} IMPLEMENT_GET(FastParam, FastParameter, _FastParameter) IMPLEMENT_SET(FastParam, FastParameter, _FastParameter) IMPLEMENT_GET(ORBParam, ORBParameter, _ORBParameter) IMPLEMENT_SET(ORBParam, ORBParameter, _ORBParameter) void Go_Initialize(); void Go_Detect(Mat &__Image, vector &__Keypoints); #if !defined(MODE_ONLY_DETECTION) void Go_Extract(Mat &__Image, vector &__Keypoints, Mat &__Descriptors); void Go_DetectAndExtract(Mat &__Image, vector &__Keypoints, Mat &__Descriptors); void Go_Matching(Mat &__Object, Mat &__Scene, #if defined(SET_MODE_FLANN_MATCHER) Mat &__Results, Mat &__Dists, #endif #if defined(SET_MODE_NORMAL_METHOD) vector #elif defined(SET_MODE_KNN_METHOD) vector > #endif &__Matches); bool Find_Matchs(FeatureSets &Object, FeatureSets &Scene, int &Scene_X, int &Scene_Y); #endif }; #endif #endif /* class ImageDetector { private: #if defined(SET_MODE_FAST_DETECTOR) int _DetectorThreshold; #endif #if defined(SET_MODE_BRIEF_EXTRACTOR) int _ExtractorThreshold; #endif double _NNDRatio; #if defined(SET_MODE_FAST_DETECTOR) FastFeatureDetector #elif defined(SET_MODE_ORB_DETECTOR) OrbFeatureDetector #endif _Detector; #if defined(SET_MODE_ORB_EXTRACTOR) ORB #endif _Extractor; public: ImageDetector() : #if defined(SET_MODE_FAST_DETECTOR) _DetectorThreshold(DETECTOR_THRESHOLD), #endif _NNDRatio(NNR_RATIO) {} ImageDetector( #if defined(SET_MODE_FAST_DETECTOR) int DetectorThreshold = DETECTOR_THRESHOLD, #endif double NNDRatio = NNR_RATIO); FeatureDetectoror(); void Go_Detect(Mat &__Image, vector &__Keypoints); void Go_Extract(Mat &__Image, vector &__Keypoints, Mat &__Descriptors); void Go_DetectAndExtract(Mat &__Image, vector &__Keypoints, Mat &__Descriptors); void Go_Matching(Mat &__Object, Mat &__Scene, #if defined(SET_MODE_FLANN_MATCHER) Mat &__Results, Mat &__Dists, #endif #if defined(SET_MODE_NORMAL_METHOD) vector #elif defined(SET_MODE_KNN_METHOD) vector > #endif &__Matches); bool Find_Matchs(FeatureSets &Object, FeatureSets &Scene, int &Scene_X, int &Scene_Y); }; */#pragma once #include #include double myF (std::int64_t iters){ double v = static_cast(iters); for (auto i=0; i < iters; i++){ for (auto i=0; i < iters; i++){ for (auto i=0; i < iters; i++){ v = sqrt(v); } } } return v; } void myFInC (void *d){ pthread_spinlock_t *s = (pthread_spinlock_t *) d; pthread_spin_unlock(s); return ; } #include #include #include #include #include #include #include int main(int argc, char **argv) { if (argc == 1) return -1; if (Widget::Application::initialize(argc, argv) != SUCCESS) return -1; Widget::Window *window = new Widget::Window(WINDOW_RESIZABLE); window->icon(Graphic::Icon::get("image")); window->title("Image Viewer"); window->size(Vec2i(700, 500)); window->root()->layout(VFLOW(0)); new Widget::TitleBar(window->root()); auto toolbar = new Widget::Panel(window->root()); toolbar->layout(HFLOW(0)); toolbar->insets(4); auto bitmap = Graphic::Bitmap::load_from_or_placeholder(argv[1]); auto set_has_wallaper = new Widget::Button(toolbar, Widget::Button::TEXT, Graphic::Icon::get("wallpaper"), "Set As Wallpaper"); set_has_wallaper->on(Widget::Event::ACTION, [&](auto) { Settings::Service::the()->write(Settings::Path::parse("appearance:wallpaper.image"), process_resolve(argv[1])); }); auto image = new Widget::Image(window->root(), bitmap); image->flags(Widget::Component::FILL); window->show(); return Widget::Application::run(); } // // ProcessInput.hpp // datalackey // // Created by on 10.1.18. // Copyright © 2018 . All rights reserved. // // Licensed under Universal Permissive License. See License.txt. #ifndef ProcessInput_hpp #define ProcessInput_hpp #include "RawData.hpp" #include "SimpleValue.hpp" #include "StringValue.hpp" #include "DataOwner.hpp" #include "Encoder.hpp" #include class ProcessInput { private: std::shared_ptr label; StringValue* plabel; std::shared_ptr data; std::shared_ptr name; StringValue* pname; public: // Both are expected to be StringValues. ProcessInput(std::shared_ptr& Label, std::shared_ptr& Name); // Value can be anything, the name is expected to be StringValue. ProcessInput(std::shared_ptr& Value, Encoder* E, std::shared_ptr& Name); // Special case used as end of file marker for output feeder thread. ProcessInput(); // For setting data from label. const StringValue* Label() const { return plabel; } void SetData(std::shared_ptr Data) { data = Data; } // For passing data onwards. const StringValue* Name() const { return pname; } std::shared_ptr Data() { return data; } // Needed in case of errors. std::shared_ptr& SharedLabel() { return label; } }; #endif /* ProcessInput_hpp */ //===- NameHashTable.cpp - PDB Name Hash Table ------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/DebugInfo/PDB/Raw/NameHashTable.h" #include "llvm/ADT/ArrayRef.h" #include "llvm/DebugInfo/PDB/Raw/ByteStream.h" #include "llvm/DebugInfo/PDB/Raw/RawError.h" #include "llvm/DebugInfo/PDB/Raw/StreamReader.h" #include "llvm/Support/Endian.h" using namespace llvm; using namespace llvm::support; using namespace llvm::pdb; static inline uint32_t HashStringV1(StringRef Str) { uint32_t Result = 0; uint32_t Size = Str.size(); ArrayRef Longs(reinterpret_cast(Str.data()), Size / 4); for (auto Value : Longs) Result ^= Value; const uint8_t *Remainder = reinterpret_cast(Longs.end()); uint32_t RemainderSize = Size - Longs.size() * 4; // Maximum of 3 bytes left. Hash a 2 byte word if possible, then hash the // possibly remaining 1 byte. if (RemainderSize >= 2) { uint16_t Value = *reinterpret_cast(Remainder); Result ^= static_cast(Value); Remainder += 2; RemainderSize -= 2; } // hash possible odd byte if (RemainderSize == 1) { Result ^= *(Remainder++); } const uint32_t toLowerMask = 0x20202020; Result |= toLowerMask; Result ^= (Result >> 11); return Result ^ (Result >> 16); } static inline uint32_t HashStringV2(StringRef Str) { uint32_t Hash = 0xb170a1bf; ArrayRef Buffer(Str.begin(), Str.end()); ArrayRef Items( reinterpret_cast(Buffer.data()), Buffer.size() / sizeof(ulittle32_t)); for (ulittle32_t Item : Items) { Hash += Item; Hash += (Hash << 10); Hash ^= (Hash >> 6); } Buffer = Buffer.slice(Items.size() * sizeof(ulittle32_t)); for (uint8_t Item : Buffer) { Hash += Item; Hash += (Hash << 10); Hash ^= (Hash >> 6); } return Hash * 1664525L + 1013904223L; } NameHashTable::NameHashTable() : Signature(0), HashVersion(0), NameCount(0) {} Error NameHashTable::load(StreamReader &Stream) { struct Header { support::ulittle32_t Signature; support::ulittle32_t HashVersion; support::ulittle32_t ByteSize; }; Header H; if (auto EC = Stream.readObject(&H)) return EC; if (H.Signature != 0xEFFEEFFE) return make_error(raw_error_code::corrupt_file, "Invalid hash table signature"); if (H.HashVersion != 1 && H.HashVersion != 2) return make_error(raw_error_code::corrupt_file, "Unsupported hash version"); Signature = H.Signature; HashVersion = H.HashVersion; if (auto EC = NamesBuffer.initialize(Stream, H.ByteSize)) return make_error(raw_error_code::corrupt_file, "Invalid hash table byte length"); support::ulittle32_t HashCount; if (auto EC = Stream.readObject(&HashCount)) return EC; std::vector BucketArray(HashCount); if (auto EC = Stream.readArray(BucketArray)) return make_error(raw_error_code::corrupt_file, "Could not read bucket array"); IDs.assign(BucketArray.begin(), BucketArray.end()); if (Stream.bytesRemaining() < sizeof(support::ulittle32_t)) return make_error(raw_error_code::corrupt_file, "Missing name count"); if (auto EC = Stream.readInteger(NameCount)) return EC; return Error::success(); } StringRef NameHashTable::getStringForID(uint32_t ID) const { if (ID == IDs[0]) return StringRef(); return StringRef(NamesBuffer.str().begin() + ID); } uint32_t NameHashTable::getIDForString(StringRef Str) const { uint32_t Hash = (HashVersion == 1) ? HashStringV1(Str) : HashStringV2(Str); size_t Count = IDs.size(); uint32_t Start = Hash % Count; for (size_t I = 0; I < Count; ++I) { // The hash is just a starting point for the search, but if it // doesn't work we should find the string no matter what, because // we iterate the entire array. uint32_t Index = (Start + I) % Count; uint32_t ID = IDs[Index]; StringRef S = getStringForID(ID); if (S == Str) return ID; } // IDs[0] contains the ID of the "invalid" entry. return IDs[0]; } ArrayRef NameHashTable::name_ids() const { return ArrayRef(IDs).slice(1, NameCount); } 1-10 #include // { Name, LastName } // { Name, LastName, 1992 } void serializeValues() { } template void serializeValues(T value) { std::cout << value; } template void serializeValues(T value, Args... args) { std::cout << value << ", "; serializeValues(args...); } template void serialize(Args... args) { std::cout << "{ " ; serializeValues(args...); std::cout << " }" << std::endl ; }; int main(int argc, const char** argv) { serialize("Name", "LastName"); serialize("Name", "LastName", 1992); std::cout << std::endl; return 0; }luacpp/coroutine.hpp #ifndef LUACPP_COROUTINE_HPP #define LUACPP_COROUTINE_HPP #include "luacpp/stack.hpp" #include "luacpp/reference.hpp" namespace lua { struct coroutine { coroutine() : m_thread(nullptr) , m_suspend_requested(nullptr) { } explicit coroutine(reference thread, bool *suspend_requested) : m_life(std::move(thread)) , m_suspend_requested(suspend_requested) { thread.push(*m_life.state()); m_thread = lua_tothread(m_life.state(), -1); assert(m_thread); lua_pop(m_life.state(), 1); } #if !SILICIUM_COMPILER_GENERATES_MOVES coroutine(coroutine &&other) BOOST_NOEXCEPT : m_thread(nullptr) , m_suspend_requested(nullptr) { swap(other); } coroutine &operator = (coroutine &&other) BOOST_NOEXCEPT { swap(other); return *this; } #endif lua_State &thread() const { assert(m_thread); return *m_thread; } void suspend() { assert(m_suspend_requested); assert(!*m_suspend_requested); assert(lua_status(m_thread) == 0); assert(m_thread); *m_suspend_requested = true; } void resume(int argument_count) { assert(lua_status(m_thread) == LUA_YIELD || lua_status(m_thread) == 0); int const rc = lua_resume(m_thread, argument_count); if (rc && (rc != LUA_YIELD)) { std::string message = lua_tostring(m_thread, -1); lua_pop(m_thread, 1); boost::throw_exception(lua_exception(rc, std::move(message))); } } bool empty() const BOOST_NOEXCEPT { return m_thread == nullptr; } void swap(coroutine &other) BOOST_NOEXCEPT { using boost::swap; swap(m_thread, other.m_thread); swap(m_life, other.m_life); swap(m_suspend_requested, other.m_suspend_requested); } private: lua_State *m_thread; reference m_life; bool *m_suspend_requested; #if !SILICIUM_COMPILER_GENERATES_MOVES SILICIUM_DELETED_FUNCTION(coroutine(coroutine const &)) SILICIUM_DELETED_FUNCTION(coroutine &operator = (coroutine const &)) #endif }; inline coroutine create_coroutine(main_thread thread) { assert(thread.get()); lua_newthread(thread.get()); stack_value thread_on_stack(*thread.get(), lua_gettop(thread.get())); return coroutine(create_reference(thread, thread_on_stack), nullptr); } inline stack_value xmove(stack_value from, lua_State &to) { lua_xmove(from.thread(), &to, 1); from.release(); return stack_value(to, lua_gettop(&to)); } } #endif #include #include #include #include struct node { int data; node *kiri; node *kanan; }; void tambah(node **root, int dataku) { if((*root) == NULL) { node *baru; baru = new node; baru->data = dataku; baru->kiri = NULL; baru->kanan = NULL; (*root) = baru; (*root)->kiri = NULL; (*root)->kanan = NULL; printf("Data bertambah!"); } //jika data yang akan dimasukkan lebih kecil daripada elemen root, maka akan diletakkan di node sebelah kiri. else if(dataku<(*root)->data) tambah(&(*root)->kiri, dataku); //jika data yang akan dimasukkan lebih besar daripada elemen root, maka akan diletakkan di node sebelah kanan else if(dataku>(*root)->data) tambah(&(*root)->kanan, dataku); //jika saat dicek data yang akan dimasukkan memiliki nilai yang sama dengan data pada root else if(dataku == (*root)->data) printf("Data sudah ada!"); } void preOrder(node *root) { if(root != NULL) { printf("%d ", root->data); preOrder(root->kiri); preOrder(root->kanan); } } void inOrder(node *root) { if(root != NULL) { inOrder(root->kiri); printf("%d ", root->data); inOrder(root->kanan); } } void postOrder(node *root) { if(root != NULL) { postOrder(root->kiri); postOrder(root->kanan); printf("%d ", root->data); } } /* void hapusdata(node **root, int dataku) { if((*root) != NULL) { node *baru; baru = new node; baru->data = dataku; baru->kiri = NULL; baru->kanan = NULL; (*root) = baru; (*root)->kiri = NULL; (*root)->kanan = NULL; printf("Data berhasil dibersihkan!\n"); } else printf("Data masih kosong!\n"); } */ void hapusdata(struct node **root, int data) { if (*root == NULL) return; if (strcmp((*root)->data, data) < 0) hapusdata(&(*root)->kiri, data); else if (strcmp((*root)->dataku, data) > 0) hapusdata(&(*root)->kanan, data); else { if ((*root)->kiri == NULL && (*root)->kanan == NULL) { free((*root)->data); free(*root); *root = NULL; } else if ((*root)->kiri == NULL) { struct node *temp = *root; *root = (*root)->kanan; free(temp->data); free(temp); } else if ((*root)->kanan == NULL) { struct node *temp = *root; *root = (*root)->kiri; free(temp->data); free(temp); } else { struct node *temp = (*root)->kanan; while (temp->kiri != NULL) temp = temp->kiri; char *temp_word = (*root)->data; (*root)->data = temp->data; temp->data = temp_word; hapusdata(&(*root)->kanan, temp_word); } } } int main() { int pil, data; node *tree; tree = NULL; do { system("cls"); //bersihkan layar printf("\tPROGRAM TREE Bahasa C"); printf("\n\t====================="); printf("\nMENU"); printf("\n----\n"); printf("1. Input Data\n"); printf("2. Lihat Pre-order\n"); printf("3. Lihat In-order\n"); printf("4. Lihat Post-order\n"); printf("5. Hapus Data\n"); printf("6. Keluar\n"); printf("Pilihan kamu? = "); scanf("%d", &pil); switch(pil) { case 1 : printf("\nINPUT : "); printf("\n-------"); printf("\nData baru : "); scanf("%d", &data); tambah(&tree, data); break; case 2 : printf("\nOUTPUT PRE ORDER : "); printf("\n------------------\n"); if(tree!=NULL) //panggil fungsi untuk mencetak data secara preOrder preOrder(tree); else printf("Masih kosong!"); break; case 3 : printf("\nOUTPUT IN ORDER : "); printf("\n-----------------\n"); if(tree!=NULL) //panggil fungsi untuk mencetak data secara preOrder inOrder(tree); else printf("Masih kosong!"); break; case 4 : printf("\nOUTPUT POST ORDER : "); printf("\n------------------\n"); if(tree!=NULL) //panggil fungsi untuk mencetak data secara postOrder postOrder(tree); else printf("Masih kosong!"); break; case 5: hapusdata(&tree, data); break; } getch(); } while(pil!=5); } /** * \file Sketcher_SnapLinePerpendicular.hxx * \brief Header file for the class Sketcher_SnapLinePerpendicular * \author */ #ifndef Sketcher_SnapLinePerpendicular_H #define Sketcher_SnapLinePerpendicular_H #include "Sketcher_SnapLine.hxx" #include DEFINE_STANDARD_HANDLE(Sketcher_SnapLinePerpendicular,Sketcher_SnapLine) //snap searching perpendicular lines class Sketcher_SnapLinePerpendicular : public Sketcher_SnapLine { public: // Type management DEFINE_STANDARD_RTTIEXT(Sketcher_SnapLinePerpendicular, Sketcher_SnapLine) /** * \fn Sketcher_SnapLinePerpendicular() * \brief Constructs a Sketcher_SnapLinePerpendicular */ Standard_EXPORT Sketcher_SnapLinePerpendicular(); /** * \fn ~Sketcher_SnapLinePerpendicular() * \brief Destructor */ Standard_EXPORT ~Sketcher_SnapLinePerpendicular(); /** * \fn SelectEvent() * \brief find new point * \return void */ Standard_EXPORT void SelectEvent(); /** * \fn GetSnapType() * \brief get Snap type * \return Sketcher_SnapType */ Standard_EXPORT Sketcher_SnapType GetSnapType(); /** * \fn DrawRelation() * \brief draw relation * \return void */ Standard_EXPORT void DrawRelation(); /** * \fn EraseRelation() * \brief erase relation * \return void */ Standard_EXPORT void EraseRelation(); private: //members Handle(AIS_PerpendicularRelation) myPerRelation; }; #endif/* Copyright (c) 2010-2016, - IntRoLab - Universite de Sherbrooke 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 Universite de Sherbrooke 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 "OrbitOrientedViewController.h" #include #include #include #include #include #include #include "rviz/properties/float_property.h" #include "rviz/properties/vector_property.h" #include "rviz/ogre_helpers/shape.h" namespace rtabmap_ros { void OrbitOrientedViewController::updateCamera() { float distance = distance_property_->getFloat(); float yaw = yaw_property_->getFloat(); float pitch = pitch_property_->getFloat(); Ogre::Matrix3 rot; reference_orientation_.ToRotationMatrix(rot); Ogre::Radian rollTarget, pitchTarget, yawTarget; rot.ToEulerAnglesXYZ(yawTarget, pitchTarget, rollTarget); yaw += rollTarget.valueRadians(); pitch += pitchTarget.valueRadians(); Ogre::Vector3 focal_point = focal_point_property_->getVector(); float x = distance * cos( yaw ) * cos( pitch ) + focal_point.x; float y = distance * sin( yaw ) * cos( pitch ) + focal_point.y; float z = distance * sin( pitch ) + focal_point.z; Ogre::Vector3 pos( x, y, z ); camera_->setPosition(pos); camera_->setFixedYawAxis(true, target_scene_node_->getOrientation() * Ogre::Vector3::UNIT_Z); camera_->setDirection(target_scene_node_->getOrientation() * (focal_point - pos)); focal_shape_->setPosition( focal_point ); } } #include PLUGINLIB_EXPORT_CLASS( rtabmap_ros::OrbitOrientedViewController, rviz::ViewController ) michaelweiss092/LillyMol10-100 #include #include "misc.h" template void copy_vector (float *, const float *, int); #include #include using namespace std; int max_sub_arr_sum(int a[], int size) { int max_so_far = INT_MIN, max_ending_here = 0; for (int i = 0; i < size; i++) { max_ending_here = max_ending_here + a[i]; if (max_so_far < max_ending_here) max_so_far = max_ending_here; if (max_ending_here < 0) max_ending_here = 0; } return max_so_far; } int main() { cout<<"enter no. of data you want to enter"; int n; cin>>n; int a[n]; cout<<"enter data"; for(int i=0;i>k; a[i]=k; } int max_sum = max_sub_arr_sum(a, n); cout << "Maximum contiguous sum is " << max_sum; return 0; }1-10 // -------------------------------------------------------------------------- // Citadel: MsgTab.CPP // // Message table related code. #include "ctdl.h" #pragma hdrstop #include "msg.h" #include "filemake.h" // -------------------------------------------------------------------------- // MsgTableC::Index(): Builds one message index from passed message. Bool MessageTableC::Index(Message *Msg) { if (roomBuild) { buildroom(Msg); } m_index OurID = atol(Msg->GetLocalID()); m_slot OurSlot = OurID - OldestMsgTab; // Should we handle this gracefully in the debugging version? assert(OurSlot >= 0 && OurSlot < Size); // This is about as gracefully as we can handle it. if (!OurSlot < 0 || OurSlot >= Size) { return (FALSE); } #ifdef REGULAR *((int *) &(Flags[OurSlot])) = 0; AuthHash[OurSlot] = 0; ToHash[OurSlot] = 0; OriginID[OurSlot] = 0; RoomNum[OurSlot] = DUMP; LocLO[OurSlot] = long_LO(Msg->GetHeadLoc()); LocHI[OurSlot] = long_HI(Msg->GetHeadLoc()); #define smt(x) x[OurSlot] #else MsgTabEntryS *MT = #ifdef AUXMEM (MsgTabEntryS *) (LoadAuxmemBlock(OurSlot, &mtList, MSGTABPERPAGE, sizeof(MsgTabEntryS))); #else &Table[OurSlot]; #endif *((int *) (&MT->Flags)) = 0; MT->AuthHash = 0; MT->ToHash = 0; MT->OriginID = 0; MT->RoomNum = DUMP; MT->Loc = Msg->GetHeadLoc(); #define smt(x) MT->x #endif if (*Msg->GetSourceID()) { m_index oid = atol(Msg->GetSourceID()); smt(OriginID) = (ushort) oid; smt(Flags).SetNetworked(TRUE); } smt(AuthHash) = hash(Msg->GetAuthor()); if (*Msg->GetToUser() && *Msg->GetGroup() && (SameString(Msg->GetToUser(), Msg->GetGroup()))) { smt(Flags).SetMassemail(TRUE); smt(ToHash) = hash(Msg->GetGroup()); } else { if (*Msg->GetToUser()) { smt(ToHash) = hash(Msg->GetToUser()); smt(Flags).SetMail(TRUE); if (*Msg->GetForward()) { smt(Flags).SetForwarded(TRUE); if (!*Msg->GetSourceID()) { // use the mtomesg field smt(OriginID) = hash(Msg->GetForward()); } else { // use the mttohash and lose the recipient smt(ToHash) = hash(Msg->GetForward()); } } } if (*Msg->GetGroup()) { smt(ToHash) = hash(Msg->GetGroup()); smt(Flags).SetLimited(TRUE); } } if (Msg->IsNetworkedMail() && !Msg->IsNetworkedMailForHere()) { smt(Flags).SetNet(TRUE); } if (*Msg->GetX() == 'Y') { smt(Flags).SetProblem(TRUE); } if (*Msg->GetX() == 'M') { smt(Flags).SetModerated(TRUE); } smt(Flags).SetReceived(Msg->IsReceived()); smt(Flags).SetReply(Msg->IsRepliedTo()); smt(Flags).SetCensored(Msg->IsCensored()); smt(Flags).SetMadevis(Msg->IsMadeVisible()); smt(Flags).SetLocal(Msg->IsLocal()); smt(Flags).SetInuse(TRUE); smt(RoomNum) = Msg->GetRoomNumber(); // This is special. if (*Msg->GetCopyOfMessage()) { smt(Flags).SetCopy(TRUE); // get the ID# m_index copy = atol(Msg->GetCopyOfMessage()); smt(ToHash) = long_LO(OurID - copy); smt(AuthHash) = long_HI(OurID - copy); } #if defined(AUXMEM) || defined(WINCIT) r_slot RoomNum = MT->RoomNum; assert(RoomNum < cfg.maxrooms && RoomNum >= 0); // insert it into room list in message table if (FirstMessageInRoom[RoomNum] == M_INDEX_ERROR) { // first message in this room... assert(LastMessageInRoom[RoomNum] == M_INDEX_ERROR); MT->PrevRoomMsg = M_INDEX_ERROR; MT->NextRoomMsg = M_INDEX_ERROR; FirstMessageInRoom[RoomNum] = OurID; LastMessageInRoom[RoomNum] = OurID; } else { assert(LastMessageInRoom[RoomNum] != M_INDEX_ERROR); assert(FirstMessageInRoom[RoomNum] != M_INDEX_ERROR); if (OurID < FirstMessageInRoom[RoomNum]) { // this message is older then the old first message in room... MT->NextRoomMsg = FirstMessageInRoom[RoomNum]; MT->PrevRoomMsg = M_INDEX_ERROR; // remember: if we put more than one other slot reference // here, we may lose MT in the Auxmem version, as it may have // to be swapped out. assert(IsValid(FirstMessageInRoom[RoomNum])); SetPrevRoomMsg(FirstMessageInRoom[RoomNum], OurID); FirstMessageInRoom[RoomNum] = OurID; } else if (OurID > LastMessageInRoom[RoomNum]) { // this message is newer than the old last message in room... MT->PrevRoomMsg = LastMessageInRoom[RoomNum]; MT->NextRoomMsg = M_INDEX_ERROR; // remember: if we put more than one other slot reference // here, we may lose MT in the Auxmem version, as it may have // to be swapped out. assert(IsValid(LastMessageInRoom[RoomNum])); SetNextRoomMsg(LastMessageInRoom[RoomNum], OurID); LastMessageInRoom[RoomNum] = OurID; } else { // insert it somewhere... m_index CurrentMessage, LastMessage; for (CurrentMessage = FirstMessageInRoom[RoomNum]; CurrentMessage < OurID; LastMessage = CurrentMessage, assert(IsValid(CurrentMessage)), CurrentMessage = GetNextRoomMsg(CurrentMessage)) { assert(CurrentMessage != M_INDEX_ERROR); } assert(LastMessage != OurID); // insert slot between LastMessage and CurrentMessage // remember: MT is no longer good in Auxmem, because // getNextRoomMsg() may have swapped it out of memory. assert(IsValid(CurrentMessage)); SetPrevRoomMsg(CurrentMessage, OurID); assert(IsValid(LastMessage)); SetNextRoomMsg(LastMessage, OurID); SetPrevRoomMsg(OurID, LastMessage); SetNextRoomMsg(OurID, CurrentMessage); } } #endif if (OurID > NewestMsg) { NewestMsg = OurID; } #if VERSION == ALPHA Verify(); #endif return (TRUE); } #ifndef NDEBUG #define CHECKINTERVAL 180*60 // how often to check table, maximum #include "cwindows.h" void MessageTableC::Verify(void) { #ifdef GOODBYE static time_t LastChecked; if (time(NULL) >= LastChecked + CHECKINTERVAL) { CITWINDOW *w = CitWindowsMsg(NULL, "Verifying message table..."); #if defined(AUXMEM) || defined(WINCIT) m_slot TableSize = sizetable(); m_slot CurrentMsg, LastMsg; r_slot CurrentRoom; for (CurrentMsg = 0; CurrentMsg < TableSize; CurrentMsg++) { getMsgTab(CurrentMsg)->Checked = !getFlags(CurrentMsg)->IsInuse(); } for (CurrentRoom = 0; CurrentRoom < cfg.maxrooms; CurrentRoom++) { if (FirstMessageInRoom[CurrentRoom] != M_SLOT_ERROR) { for (LastMsg = M_SLOT_ERROR, CurrentMsg = FirstMessageInRoom[CurrentRoom]; CurrentMsg != M_SLOT_ERROR; LastMsg = CurrentMsg, CurrentMsg = getNextRoomMsg(indexslot(CurrentMsg))) { m_slot CMSlot = indexslot(CurrentMsg); if (CMSlot == M_SLOT_ERROR) { if (w) { destroyCitWindow(w, FALSE); } #ifndef WINCIT doccr(); cPrintf("Bad: %ld", CurrentMsg); doccr(); #endif assert(FALSE); } if (getMsgTab(CMSlot)->Checked) { if (w) { destroyCitWindow(w, FALSE); } #ifndef WINCIT doccr(); cPrintf("Bad: %ld", CurrentMsg); doccr(); #endif assert(FALSE); } if (getRoomNum(CMSlot) != CurrentRoom) { if (w) { destroyCitWindow(w, FALSE); } #ifndef WINCIT doccr(); cPrintf("Bad: %ld; room: %d:%d", CurrentMsg, CurrentRoom, getRoomNum(CMSlot)); doccr(); #endif assert(FALSE); } getMsgTab(CMSlot)->Checked = TRUE; } if (LastMessageInRoom[CurrentRoom] != LastMsg) { if (w) { destroyCitWindow(w, FALSE); } #ifndef WINCIT doccr(); cPrintf("LMIR: %ld, LM: %ld, room: %d", LastMessageInRoom[CurrentRoom], LastMsg, CurrentRoom); doccr(); #endif assert(FALSE); } } else { if (LastMessageInRoom[CurrentRoom] != M_SLOT_ERROR) { if (w) { destroyCitWindow(w, FALSE); } #ifndef WINCIT doccr(); cPrintf("LMIR: %ld, Room: %d", LastMessageInRoom[CurrentRoom], CurrentRoom); doccr(); #endif assert(FALSE); } } } for (CurrentMsg = 0; CurrentMsg < TableSize; CurrentMsg++) { if (!getMsgTab(CurrentMsg)->Checked) { if (w) { destroyCitWindow(w, FALSE); } #ifndef WINCIT doccr(); cPrintf("Bad: %ld", CurrentMsg); doccr(); #endif assert(FALSE); } getMsgTab(CurrentMsg)->Checked = !getFlags(CurrentMsg)->IsInuse(); } for (CurrentRoom = 0; CurrentRoom < cfg.maxrooms; CurrentRoom++) { if (LastMessageInRoom[CurrentRoom] != M_SLOT_ERROR) { for (LastMsg = M_SLOT_ERROR, CurrentMsg = LastMessageInRoom[CurrentRoom]; CurrentMsg != M_SLOT_ERROR; LastMsg = CurrentMsg, CurrentMsg = getPrevRoomMsg(indexslot(CurrentMsg))) { m_slot CMSlot = indexslot(CurrentMsg); if (CMSlot == M_SLOT_ERROR) { if (w) { destroyCitWindow(w, FALSE); } #ifndef WINCIT doccr(); cPrintf("Bad: %ld", CurrentMsg); doccr(); #endif assert(FALSE); } if (getMsgTab(CMSlot)->Checked) { if (w) { destroyCitWindow(w, FALSE); } #ifndef WINCIT doccr(); cPrintf("Bad: %ld", CurrentMsg); doccr(); #endif assert(FALSE); } if (getRoomNum(CMSlot) != CurrentRoom) { if (w) { destroyCitWindow(w, FALSE); } #ifndef WINCIT doccr(); cPrintf("Bad: %ld; room: %d:%d", CurrentMsg, CurrentRoom, getRoomNum(CMSlot)); doccr(); #endif assert(FALSE); } getMsgTab(CMSlot)->Checked = TRUE; } if (FirstMessageInRoom[CurrentRoom] != LastMsg) { if (w) { destroyCitWindow(w, FALSE); } #ifndef WINCIT doccr(); cPrintf("LMIR: %ld, LM: %ld, room: %d", LastMessageInRoom[CurrentRoom], LastMsg, CurrentRoom); doccr(); #endif assert(FALSE); } } } for (CurrentMsg = 0; CurrentMsg < TableSize; CurrentMsg++) { if (!getMsgTab(CurrentMsg)->Checked) { if (w) { destroyCitWindow(w, FALSE); } #ifndef WINCIT doccr(); cPrintf("Bad: %ld", CurrentMsg); doccr(); #endif assert(FALSE); } } #else m_slot TableSize = sizetable(); m_slot CurrentMsg; for (CurrentMsg = 0; CurrentMsg < TableSize; CurrentMsg++) { if (w && (getRoomNum(CurrentMsg) >= cfg.maxrooms)) { destroyCitWindow(w, FALSE); } assert(FALSE); } #endif LastChecked = time(NULL); if (w) { destroyCitWindow(w, FALSE); } } #endif } #endif #include "import" _ text a; in s; in as; ringw true){ println "#"; sent a; ring a == "print" && sent a){ print a; } backring ring a == "ls"){ directorysystem } backring ring a == "texttospeech"&&sent a){ texttospeech(a); } backring ring a == "echo"&&sent a){ colorBlue texttospeech(a); print a; colorWhite } backring ring a == "clear"){ clears } backring ring a == "help"){ printf "__echo__\n"); printf "__write__[write file]\n"); printf "__print__\n"); printf "__file__ [Open File]\n"); printf "__exit__\n"); printf "__texttospeech__\n"); } backring ring a == "write"){ text str; texttospeech("write a Code"); system "notepad Source.plp"); system "copy Source.plp Source.cpp"); text Command10; Command10 += "clang++ Source.cpp -o out.exe"; system Command10.Cstr); ringf in i=0;i <= 3;i++){ Animation("Compiling<>",200); Animation("Compiling||",200); Animation("Compiling><",200); } text Command12; Command12 += "out.exe"; system Command12.Cstr); remove("Source.cpp"); } backring ring a == "file"){ text File; text str; texttospeech("openFile"); print "File PLP:"; sent File; str += "copy "+File; str += " "+File+".cpp"; system str.Cstr); text Command5; Command5 += "clang++ "+File+".cpp -o "+File+".exe"; system Command5.Cstr); ringf in i=0;i <= 3;i++){ Animation("Compiling<>",200); Animation("Compiling||",200); Animation("Compiling><",200); } text Command2; Command2 += "del "+File+".cpp"; system Command2.Cstr); FileOpen(File); colorGreen print "Successful Compiler"; colorWhite } backring ring a == "poweroff" || a == "shutdown"){ texttospeech("poweroff,computer"); poweroff } backring ring a == "exit"){ texttospeech("exit from Compiler"); _Exit(0); } backring print "not Command"; } Done // Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" // Including type: LiteNetLib.EventBasedNatPunchListener #include "LiteNetLib/EventBasedNatPunchListener.hpp" // Including type: System.MulticastDelegate #include "System/MulticastDelegate.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 namespace System::Net { // Forward declaring type: IPEndPoint class IPEndPoint; } // Forward declaring namespace: LiteNetLib namespace LiteNetLib { // Forward declaring type: NatAddressType struct NatAddressType; } // Forward declaring namespace: System namespace System { // Forward declaring type: IAsyncResult class IAsyncResult; // Forward declaring type: AsyncCallback class AsyncCallback; } // Completed forward declares // Type namespace: LiteNetLib namespace LiteNetLib { // Size: 0x70 #pragma pack(push, 1) // Autogenerated type: LiteNetLib.EventBasedNatPunchListener/OnNatIntroductionSuccess class EventBasedNatPunchListener::OnNatIntroductionSuccess : public System::MulticastDelegate { public: // Creating value type constructor for type: OnNatIntroductionSuccess OnNatIntroductionSuccess() noexcept {} // public System.Void .ctor(System.Object object, System.IntPtr method) // Offset: 0x1B1E6F0 template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static EventBasedNatPunchListener::OnNatIntroductionSuccess* New_ctor(::Il2CppObject* object, System::IntPtr method) { static auto ___internal__logger = ::Logger::get().WithContext("LiteNetLib::EventBasedNatPunchListener::OnNatIntroductionSuccess::.ctor"); return THROW_UNLESS((::il2cpp_utils::New(object, method))); } // public System.Void Invoke(System.Net.IPEndPoint targetEndPoint, LiteNetLib.NatAddressType type, System.String token) // Offset: 0x1B1E268 void Invoke(System::Net::IPEndPoint* targetEndPoint, LiteNetLib::NatAddressType type, ::Il2CppString* token); // public System.IAsyncResult BeginInvoke(System.Net.IPEndPoint targetEndPoint, LiteNetLib.NatAddressType type, System.String token, System.AsyncCallback callback, System.Object object) // Offset: 0x1B1E700 System::IAsyncResult* BeginInvoke(System::Net::IPEndPoint* targetEndPoint, LiteNetLib::NatAddressType type, ::Il2CppString* token, System::AsyncCallback* callback, ::Il2CppObject* object); // public System.Void EndInvoke(System.IAsyncResult result) // Offset: 0x1B1E7A0 void EndInvoke(System::IAsyncResult* result); }; // LiteNetLib.EventBasedNatPunchListener/OnNatIntroductionSuccess #pragma pack(pop) } DEFINE_IL2CPP_ARG_TYPE(LiteNetLib::EventBasedNatPunchListener::OnNatIntroductionSuccess*, "LiteNetLib", "EventBasedNatPunchListener/OnNatIntroductionSuccess"); Src/Chip8-Emu.cpp // Chip8-Emu.cpp : Questo file contiene la funzione 'main', in cui inizia e termina l'esecuzione del programma. // #include #include "AppWindow.h" #include "Emulator.h" int main(int argc, char* args[]) { //If no argument was passed when starting the program, then stop execution immediately if (argc < 2) { std::cout << "Specify a path to the rom you want to play as argument!"; return -1; } //Creates the actual Chip-8 Emulator/Interpreter Emulator* Chip8 = new Emulator; //Loads the ROM specified as argument Chip8->LoadRom(args[1]); const int CycleDelay = 3; int Pitch = sizeof(Chip8->ScreenPixels[0]) * 64; //Creates the actual window AppWindow* Window = new AppWindow(Chip8->GetRomName().c_str(), 64 * 10, 32 * 10, 64, 32); auto LastCycleTime = std::chrono::high_resolution_clock::now(); bool Quit = false; //Main loop while (!Quit) { Quit = Window->ProcessInput(Chip8->Keymap); auto CurrentTime = std::chrono::high_resolution_clock::now(); float DeltaTime = std::chrono::duration(CurrentTime - LastCycleTime).count(); if (DeltaTime > CycleDelay) { LastCycleTime = CurrentTime; Chip8->ExecuteCycle(); Window->Render(Chip8->ScreenPixels, Pitch); } } delete Chip8; delete Window; return 0; }#include #include #include using std::cin; using std::cout; using std::endl; using std::string; using std::vector; int main() { vector numbers(10, 3); for (auto &x : numbers){ cout << x << endl; } for (auto it = numbers.begin(); it != numbers.end(); ++it){ *it *= 2; } for (auto &x : numbers){ cout << x << endl; } }Lolik111/metasrc/lm/sentence.cpp /** * @file sentence.cpp * @author */ #include #include #include #include #include #include "meta/lm/sentence.h" #include "meta/utf/segmenter.h" namespace meta { namespace lm { sentence::sentence(const std::string& text, bool tokenize /* = true */) { if (tokenize) { utf::segmenter segmenter; segmenter.set_content(text); for (const auto& word : segmenter.words()) { auto str = segmenter.content(word); if (!str.empty() && !std::all_of(str.begin(), str.end(), ::isspace)) tokens_.emplace_back(std::move(str)); } if (tokens_.empty()) throw sentence_exception{"empty token stream"}; } else { std::istringstream iss{text}; std::copy(std::istream_iterator(iss), std::istream_iterator(), std::back_inserter(tokens_)); } } std::string sentence::to_string() const { std::string result{""}; if (tokens_.empty()) return result; for (auto& token : tokens_) result += token + " "; return result.substr(0, result.size() - 1); // remove trailing space } const std::string& sentence::operator[](size_type idx) const { return tokens_[idx]; } sentence sentence::operator()(size_type from, size_type to) const { sentence ret; if (from > to || to > tokens_.size()) throw sentence_exception{"operator() out of bounds: from = " + std::to_string(from) + ", to = " + std::to_string(to)}; using diff_type = iterator::difference_type; ret.tokens_.insert(ret.tokens_.begin(), tokens_.begin() + static_cast(from), tokens_.begin() + static_cast(to)); return ret; } void sentence::substitute(size_type idx, const std::string& token, double weight /* = 0.0 */) { ops_.push_back("substitute(" + tokens_[idx] + " -> " + token + ")"); tokens_[idx] = token; weights_.push_back(weight); } void sentence::remove(size_type idx, double weight /* = 0.0 */) { ops_.push_back("remove(" + (*this)[idx] + ")"); using diff_type = iterator::difference_type; tokens_.erase(tokens_.begin() + static_cast(idx)); weights_.push_back(weight); } void sentence::insert(size_type idx, const std::string& token, double weight /* = 0.0 */) { using diff_type = iterator::difference_type; tokens_.insert(tokens_.begin() + static_cast(idx), token); ops_.push_back("insert(" + token + ")"); weights_.push_back(weight); } double sentence::average_weight() const { if (weights_.empty()) return 0.0; double sum = std::accumulate(weights_.begin(), weights_.end(), 0.0); return sum / weights_.size(); } std::vector sentence::weights() const { return weights_; } const std::vector& sentence::operations() const { return ops_; } const std::vector& sentence::tokens() const { return tokens_; } const std::string& sentence::front() const { return tokens_.front(); } const std::string& sentence::back() const { return tokens_.back(); } void sentence::push_front(const std::string& token) { // we use a std::vector instead of a std::deque because sentence's // operator== (using std::vector) is significantly faster; push_front is not // called as much as operator== tokens_.insert(tokens_.begin(), token); } void sentence::pop_front() { // we use a std::vector instead of a std::deque because sentence's // operator== (using std::vector) is significantly faster; pop_front is not // called as much as operator== tokens_.erase(tokens_.begin()); } void sentence::push_back(const std::string& token) { tokens_.push_back(token); } void sentence::pop_back() { tokens_.pop_back(); } template void sentence::emplace_back(Args&&... args) { tokens_.emplace_back(std::forward(args)...); } sentence::iterator sentence::begin() { return tokens_.begin(); } sentence::iterator sentence::end() { return tokens_.end(); } sentence::const_iterator sentence::begin() const { return tokens_.cbegin(); } sentence::const_iterator sentence::end() const { return tokens_.cend(); } sentence::size_type sentence::size() const { return tokens_.size(); } } } 100-1000 // Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. // // Licensed under the BSD 3-Clause License (the "License"); you may not use this // file except in compliance with the License. You may obtain a copy of the // License at // // https://opensource.org/licenses/BSD-3-Clause // // 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 "flare/rpc/name_resolver/name_resolver_updater.h" #include #include #include #include "flare/base/logging.h" #include "flare/base/thread/attribute.h" using namespace std::literals; namespace flare::name_resolver { NameResolverUpdater::NameResolverUpdater() { Start(); } NameResolverUpdater::~NameResolverUpdater() { Stop(); } void NameResolverUpdater::Stop() { if (!std::atomic_exchange(&stopped_, true)) { cond_.notify_one(); work_waiter_.join(); } } void NameResolverUpdater::Start() { work_waiter_ = std::thread([this]() { SetCurrentThreadName("NameResolverUp"); WorkProc(); }); } void NameResolverUpdater::Register(const std::string& address, Function updater, std::chrono::seconds interval) { std::scoped_lock lk(updater_mutex_); if (auto iter = updater_.find(address); iter == updater_.end()) { updater_.insert( std::make_pair(address, UpdaterInfo(std::move(updater), interval))); } else { FLARE_LOG_ERROR("Duplicate Register for address {}", address); } } void NameResolverUpdater::WorkProc() { while (!stopped_.load(std::memory_order_relaxed)) { auto now = std::chrono::steady_clock::now(); std::vector need_update; { std::scoped_lock lk(updater_mutex_); for (auto&& [address, updater_info] : updater_) { if (now - updater_info.update_time > updater_info.interval) { need_update.push_back(&updater_info); } } } if (!need_update.empty()) { for (auto&& updater_info : need_update) { updater_info->updater(); // may be blocking updater_info->update_time = std::chrono::steady_clock::now(); } } std::unique_lock lk(updater_mutex_); cond_.wait_for(lk, 1s, [this] { return stopped_.load(std::memory_order_relaxed); }); } } } // namespace flare::name_resolver vol3/reorder-list/reorder-list.cpp /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode *reverseList(ListNode *head) { if(head == NULL || head->next == NULL) return head; ListNode *newHead = reverseList(head->next); head->next->next = head; head->next = NULL; return newHead; } void reorderList(ListNode *head) { if(head == NULL || head->next == NULL) return; ListNode *slow = head, *fast = head; while(fast != NULL) { fast = fast->next; if(fast) fast = fast->next; if(fast == NULL) break; slow = slow->next; } ListNode *head2 = reverseList(slow->next); slow->next = NULL; while(head != NULL && head2 != NULL) { ListNode *next = head->next; head->next = head2; head = next; next = head2->next; head2->next = head; head2 = next; } } };jonting/1Engine #include "glMainSystem.h" void glMainSystem::CreateBuffer ( uint* index, uint count ) { glGenBuffers( count, index ); } void glMainSystem::FreeBuffer ( uint* index, uint count ) { if ( *index != 0 ) { glDeleteBuffers( count, index ); *index = 0; } } void glMainSystem::BindBuffer ( uint target, uint index ) { glBindBuffer( target, index ); } void glMainSystem::UploadBuffer ( uint target, uint size, void* data, uint usage ) { glBufferData( target, size, NULL, usage ); glBufferSubData( target, 0, size, data ); } void glMainSystem::UnbindBuffer ( uint target ) { glBindBuffer( target, 0 ); } void glMainSystem::BindVertexArray ( uint target ) { glBindVertexArray( target ); } void glMainSystem::DrawElements ( uint type, int count, uint data, void* offset ) { glDrawElements( type, count, data, offset ); } sirikata/sirikata // Copyright (c) 2012 Sirikata 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 "UUIDSpeedBenchmark.hpp" #include #define ITERATIONS 10000 namespace Sirikata { UUIDSpeedBenchmark::UUIDSpeedBenchmark(const FinishedCallback& finished_cb) : Benchmark(finished_cb), mForceStop(false) { } String UUIDSpeedBenchmark::name() { return "uuid-speed"; } void UUIDSpeedBenchmark::start() { mForceStop = false; // Check throughput of timer calls Time start_time = Timer::now(); UUID dummy_u = UUID::null(); for(uint32 ii = 0; ii < ITERATIONS && !mForceStop; ii++) dummy_u = UUID::random(); if (mForceStop) return; Time end_time = Timer::now(); Duration dur = end_time - start_time; SILOG(benchmark,info, ITERATIONS << " random UUIDs, " << dur << ": " << (dur.toMicroseconds()*1000/float(ITERATIONS)) << "ns/call, " << float(ITERATIONS)/dur.toSeconds() << " calls/s"); notifyFinished(); } void UUIDSpeedBenchmark::stop() { mForceStop = true; } } // namespace Sirikata 1-10 /* * Copyright 2019 Xilinx, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef GQE_ISV_SCAN_COL_FOR_HP_HPP #define GQE_ISV_SCAN_COL_FOR_HP_HPP #ifndef __SYNTHESIS__ #include #endif #include #include #include "xf_database/types.hpp" #include "xf_database/utils.hpp" #include namespace xf { namespace database { namespace gqe { template void dup_config(int n_burst, hls::stream& col_id_strm, hls::stream config_copies[NCOL + 2]) { int en[8]; #pragma HLS array_partition variable = en complete for (ap_uint<4> i = 0; i < 8; i++) { en[i] = col_id_strm.read(); } // for vec read config_copies[0].write(n_burst); config_copies[1].write(n_burst); config_copies[2].write(n_burst); config_copies[3].write(n_burst); config_copies[4].write(n_burst); config_copies[5].write(n_burst); config_copies[6].write(n_burst); config_copies[7].write(n_burst); config_copies[0].write(en[0]); config_copies[1].write(en[1]); config_copies[2].write(en[2]); config_copies[3].write(en[3]); config_copies[4].write(en[4]); config_copies[5].write(en[5]); config_copies[6].write(en[6]); config_copies[7].write(en[7]); // for b_sync config_copies[8].write(n_burst); // for vecs_to_ch_col config_copies[9].write(n_burst); config_copies[9].write(en[0]); config_copies[9].write(en[1]); config_copies[9].write(en[2]); config_copies[9].write(en[3]); config_copies[9].write(en[4]); config_copies[9].write(en[5]); config_copies[9].write(en[6]); config_copies[9].write(en[7]); } template void read_3_vec(const ap_uint* ptr_1, hls::stream& config_copy_1, hls::stream >& vs_1, hls::stream& b_1, const ap_uint* ptr_2, hls::stream& config_copy_2, hls::stream >& vs_2, hls::stream& b_2, const ap_uint* ptr_3, hls::stream& config_copy_3, hls::stream >& vs_3, hls::stream& b_3) { int num_1 = config_copy_1.read(); int num_2 = config_copy_2.read(); int num_3 = config_copy_3.read(); int n_burst = (num_1 + VEC * BLEN - 1) / (VEC * BLEN); int en[3]; en[0] = config_copy_1.read(); en[1] = config_copy_2.read(); en[2] = config_copy_3.read(); int o = 0; const int hdr = 0; for (int i = 0; i < n_burst - 1; ++i) { #pragma HLS loop_flatten off if (en[0] >= 0) { for (int j = 0; j < BLEN; ++j) { #pragma HLS pipeline II = 1 ap_uint v_1 = ptr_1[hdr + i * BLEN + j + o]; vs_1.write(v_1); } } if (en[1] >= 0) { for (int j = 0; j < BLEN; ++j) { #pragma HLS pipeline II = 1 ap_uint v_2 = ptr_2[hdr + i * BLEN + j + o]; vs_2.write(v_2); } } if (en[2] >= 0) { for (int j = 0; j < BLEN; ++j) { #pragma HLS pipeline II = 1 ap_uint v_3 = ptr_3[hdr + i * BLEN + j + o]; vs_3.write(v_3); } } o = 1; // start sync b_1.write(true); b_2.write(true); b_3.write(true); while (b_1.full()) { #pragma HLS pipeline II = 1 ; } o = 0; // now all column has been read once. } const int len = (n_burst * BLEN * VEC > num_1) ? (num_1 - (n_burst - 1) * BLEN * VEC + VEC - 1) / VEC : BLEN; if (en[0] >= 0) { for (int j = 0; j < len; ++j) { #pragma HLS pipeline II = 1 ap_uint v_1 = ptr_1[hdr + (n_burst - 1) * BLEN + j + o]; vs_1.write(v_1); } } if (en[1] >= 0) { for (int j = 0; j < len; ++j) { #pragma HLS pipeline II = 1 ap_uint v_2 = ptr_2[hdr + (n_burst - 1) * BLEN + j + o]; vs_2.write(v_2); } } if (en[2] >= 0) { for (int j = 0; j < len; ++j) { #pragma HLS pipeline II = 1 ap_uint v_3 = ptr_3[hdr + (n_burst - 1) * BLEN + j + o]; vs_3.write(v_3); } } o = 1; // start sync b_1.write(true); b_2.write(true); b_3.write(true); while (b_1.full()) { #pragma HLS pipeline II = 1 ; } o = 0; } template void read_2_vec(const ap_uint* ptr_1, hls::stream& config_copy_1, hls::stream >& vs_1, hls::stream& b_1, const ap_uint* ptr_2, hls::stream& config_copy_2, hls::stream >& vs_2, hls::stream& b_2) { int num_1 = config_copy_1.read(); int num_2 = config_copy_2.read(); int n_burst = (num_1 + VEC * BLEN - 1) / (VEC * BLEN); int en[2]; en[0] = config_copy_1.read(); en[1] = config_copy_2.read(); int o = 0; const int hdr = 0; for (int i = 0; i < n_burst - 1; ++i) { #pragma HLS loop_flatten off if (en[0] >= 0) { for (int j = 0; j < BLEN; ++j) { #pragma HLS pipeline II = 1 ap_uint v_1 = ptr_1[hdr + i * BLEN + j + o]; vs_1.write(v_1); } } if (en[1] >= 0) { for (int j = 0; j < BLEN; ++j) { #pragma HLS pipeline II = 1 ap_uint v_2 = ptr_2[hdr + i * BLEN + j + o]; vs_2.write(v_2); } } o = 1; // start sync b_1.write(true); b_2.write(true); while (b_1.full()) { #pragma HLS pipeline II = 1 ; } o = 0; // now all column has been read once. } const int len = (n_burst * BLEN * VEC > num_1) ? (num_1 - (n_burst - 1) * BLEN * VEC + VEC - 1) / VEC : BLEN; if (en[0] >= 0) { for (int j = 0; j < len; ++j) { #pragma HLS pipeline II = 1 ap_uint v_1 = ptr_1[hdr + (n_burst - 1) * BLEN + j + o]; vs_1.write(v_1); } } if (en[1] >= 0) { for (int j = 0; j < len; ++j) { #pragma HLS pipeline II = 1 ap_uint v_2 = ptr_2[hdr + (n_burst - 1) * BLEN + j + o]; vs_2.write(v_2); } } o = 1; // start sync b_1.write(true); b_2.write(true); while (b_1.full()) { #pragma HLS pipeline II = 1 ; } o = 0; } template void vecs_to_ch_col(hls::stream > colvec_strm[NCOL], hls::stream& config_copy, hls::stream > col_strm[NCH][NCOL], hls::stream e_strm[NCH]) { enum { col_num = NCOL, ch_num = NCH, per_ch = VEC / NCH }; int nrow = config_copy.read(); int en[col_num]; for (int c = 0; c < col_num; ++c) { en[c] = config_copy.read(); } SPLIT_COL_VEC: for (int i = 0; i < nrow; i += VEC) { #pragma HLS pipeline II = per_ch ap_uint colvec[col_num]; for (int c = 0; c < col_num; ++c) { #pragma HLS unroll if (en[c] >= 0) colvec[c] = colvec_strm[c].read(); } int n = (i + VEC) > nrow ? (nrow - i) : VEC; XF_DATABASE_ASSERT((VEC % ch_num == 0) && (VEC >= ch_num)); // j for word in vec for (int j = 0; j < per_ch; ++j) { // ch for channel for (int ch = 0; ch < ch_num; ++ch) { #pragma HLS unroll ap_uint ct[col_num]; for (int c = 0; c < col_num; ++c) { #pragma HLS unroll if (en[c] >= 0) ct[c] = colvec[c].range(WD * (j * ch_num + ch + 1) - 1, WD * (j * ch_num + ch)); else if (en[c] == -1) ct[c] = 0; else if (en[c] == -2) ct[c] = i + j * ch_num + ch; } if ((j * ch_num + ch) < n) { for (int c = 0; c < col_num; ++c) { #pragma HLS unroll col_strm[ch][c].write(ct[c]); } e_strm[ch].write(false); } } } } for (int ch = 0; ch < ch_num; ++ch) { #pragma HLS unroll e_strm[ch].write(true); } } template inline bool andTree(bool flag[], int _o = 0) { #pragma HLS inline return andTree<_n / 2>(flag, _o) && andTree<_n / 2>(flag, _o + (_n / 2)); } template <> inline bool andTree<2>(bool flag[], int _o) { #pragma HLS inline return flag[_o] && flag[_o + 1]; } template inline bool orTree(bool flag[], int _o = 0) { #pragma HLS inline return orTree<_n / 2>(flag, _o) || orTree<_n / 2>(flag, _o + (_n / 2)); } template <> inline bool orTree<2>(bool flag[], int _o) { #pragma HLS inline return flag[_o] || flag[_o + 1]; } template void b_sync(hls::stream b[8], hls::stream& config_copy) { int num = config_copy.read(); int n_burst = (num + VEC * BLEN - 1) / (VEC * BLEN); for (int i = 0; i < n_burst; ++i) { bool has_empty = true; while (has_empty) { #pragma HLS pipeline II = 1 bool p[8]; #pragma HLS array_partition variable = p for (int i = 0; i < 8; ++i) { p[i] = b[i].empty(); } has_empty = orTree<8>(p); } // no empty, can proceed for (int j = 0; j < 8; ++j) { #pragma HLS unroll b[j].read(); } } } template void scan_cols(const ap_uint* ptr0, const ap_uint* ptr1, const ap_uint* ptr2, const ap_uint* ptr3, const ap_uint* ptr4, const ap_uint* ptr5, const ap_uint* ptr6, const ap_uint* ptr7, hls::stream& nrow_strm, hls::stream& col_id_strm, hls::stream > s[NCH][NCOL], hls::stream e_s[NCH]) { // clang-format off enum { burstLen = BURST_LEN, burstLen2 = (BURST_LEN * 2), nCol = NCOL, nCh = NCH }; #pragma HLS dataflow // need wide buffering for fast input, slow output, wide to narrow. hls::stream > vs[nCol]; #pragma HLS stream variable = vs depth = burstLen2 #pragma HLS bind_storage variable = vs type = fifo impl = lutram hls::stream config_copies[nCol + 2]; #pragma HLS stream variable = config_copies depth = 2 #pragma HLS bind_storage variable = config_copies type = fifo impl = lutram int nrowA = nrow_strm.read(); dup_config( nrowA, col_id_strm, config_copies); hls::stream b[nCol]; #pragma HLS stream variable = b depth = 1 #pragma HLS array_partition variable = b dim = 0 // TODO change with nCol read_3_vec<8*TPCH_INT_SZ, VEC_SCAN, BURST_LEN>(ptr0, config_copies[0], vs[0], b[0], ptr3, config_copies[3], vs[3], b[3], ptr6, config_copies[6], vs[6], b[6]); read_3_vec<8*TPCH_INT_SZ, VEC_SCAN, BURST_LEN>(ptr1, config_copies[1], vs[1], b[1], ptr4, config_copies[4], vs[4], b[4], ptr7, config_copies[7], vs[7], b[7]); read_2_vec<8*TPCH_INT_SZ, VEC_SCAN, BURST_LEN>(ptr2, config_copies[2], vs[2], b[2], ptr5, config_copies[5], vs[5], b[5]); b_sync(b, config_copies[nCol]); vecs_to_ch_col(vs, config_copies[nCol + 1], s, e_s); } } // namespace gqe } // namespace database } // namespace xf #endif // GQE_SCAN_TO_CHANNEL_HPP // © 2018 - All Rights Reserved #include #include #include #include using namespace gdk; static constexpr char TAG[] = "Vector2"; const Vector2 Vector2::Up = { 0.f, 1.f}; const Vector2 Vector2::Down = { 0.f,-1.f}; const Vector2 Vector2::Left = {-1.f, 0.f}; const Vector2 Vector2::Right = { 1.f, 0.f}; const Vector2 Vector2::Zero = { 0.f, 0.f}; std::ostream &gdk::operator<<(std::ostream &s, const gdk::Vector2 &a) { return s << nlohmann::json { {"Type", TAG}, {"x", a.x}, {"y", a.y}, } .dump(); } Vector2::Vector2(const float aX, const float aY) : x(aX) , y(aY) {} Vector2::Vector2(const float aScalar) : x(aScalar) , y(aScalar) {} bool Vector2::operator==(const Vector2 &a) const { return x == a.x && y == a.y ? true : false; } bool Vector2::operator!=(const Vector2 &a) const { return x != a.x || y != a.y ? true : false; } Vector2 Vector2::operator+(const Vector2 &aVector) const { return {aVector.x + x, aVector.y + y}; } Vector2 Vector2::operator-(const Vector2 &aVector) const { return {aVector.x - x, aVector.y - y}; } Vector2& Vector2::operator+=(const Vector2 &aVector) { x += aVector.x; y += aVector.y; return *this; } Vector2& Vector2::operator-=(const Vector2 &aVector) { x -= aVector.x; y -= aVector.y; return *this; } Vector2 Vector2::operator*(const float aScalar) const { return {x * aScalar, y * aScalar}; } Vector2& Vector2::operator*=(const float aScalar) { x *= aScalar; y *= aScalar; return *this; } float Vector2::length() const { return sqrtf( (x * x) + (y * y) ); } void Vector2::normalize() { float magnitude = Vector2::length(); if (magnitude == 0.0f) // n/0 case return; x /= magnitude; y /= magnitude; } float Vector2::getAspectRatio() const { return x / y; } // | / | // ' / __| _` | __| _ \ __| // . \ | ( | | ( |\__ ` // _|\_\_| \__,_|\__|\___/ ____/ // Multi-Physics // // License: BSD License // Kratos default license: kratos/license.txt // // Main authors: // // // System includes // External includes // Project includes #include "input_output/file_logger_output.h" namespace Kratos { FileLoggerOutput::FileLoggerOutput(const std::string& rFileName) : LoggerOutput(), mFileStream(rFileName) { SetStream(&mFileStream); } std::string FileLoggerOutput::Info() const { return "FileLoggerOutput"; } } // namespace Kratos. #include #include int main (int argc, char** argv) { // open a logical file saga::url u ("/replica_1"); saga::replica::logical_file lf (u, saga::replica::Create | saga::replica::ReadWrite); // get all attributes std::vector keys = lf.list_attributes (); // print the keys and values for ( unsigned int i = 0; i < keys.size (); i++ ) { std::string key = keys[i]; std::string val; if ( lf.attribute_is_vector (key) ) { std::vector vals = lf.get_vector_attribute (key); val = vals[0] + " ..."; } else { val = lf.get_attribute (key); } std::cout << key << " -> " << val << std::endl; } return (0); } // Copyright (c) 2009-2016 The Regents of the University of Michigan // This file is part of the HOOMD-blue project, released under the BSD 3-Clause License. // Maintainer: joaander #include "OneDConstraint.h" #include "EvaluatorConstraint.h" namespace py = pybind11; using namespace std; /*! \file OneDConstraint.cc \brief Contains code for the OneDConstraint class */ /*! \param sysdef SystemDefinition containing the ParticleData to compute forces on \param group Group of particles on which to apply this constraint */ OneDConstraint::OneDConstraint(std::shared_ptr sysdef, std::shared_ptr group, Scalar3 constraint_vec) : ForceConstraint(sysdef), m_group(group), m_vec(constraint_vec) { m_exec_conf->msg->notice(5) << "Constructing OneDConstraint" << endl; } OneDConstraint::~OneDConstraint() { m_exec_conf->msg->notice(5) << "Destroying OneDConstraint" << endl; } /*! \param constraint_vec direction that particles are constrained to */ void OneDConstraint::setVector(Scalar3 constraint_vec) { m_vec = constraint_vec; } /*! Computes the specified constraint forces \param timestep Current timestep */ void OneDConstraint::computeForces(unsigned int timestep) { unsigned int group_size = m_group->getNumMembers(); if (group_size == 0) return; if (m_prof) m_prof->push("OneDConstraint"); assert(m_pdata); // access the particle data arrays ArrayHandle h_pos(m_pdata->getPositions(), access_location::host, access_mode::read); ArrayHandle h_vel(m_pdata->getVelocities(), access_location::host, access_mode::read); const GPUArray< Scalar4 >& net_force = m_pdata->getNetForce(); ArrayHandle h_net_force(net_force, access_location::host, access_mode::read); ArrayHandle h_force(m_force,access_location::host, access_mode::overwrite); ArrayHandle h_virial(m_virial,access_location::host, access_mode::overwrite); unsigned int virial_pitch = m_virial.getPitch(); // Zero data for force calculation. memset((void*)h_force.data,0,sizeof(Scalar4)*m_force.getNumElements()); memset((void*)h_virial.data,0,sizeof(Scalar)*m_virial.getNumElements()); // there are enough other checks on the input data: but it doesn't hurt to be safe assert(h_force.data); assert(h_virial.data); // for each of the particles in the group for (unsigned int group_idx = 0; group_idx < group_size; group_idx++) { // get the current particle properties unsigned int j = m_group->getMemberIndex(group_idx); Scalar3 X = make_scalar3(h_pos.data[j].x, h_pos.data[j].y, h_pos.data[j].z); Scalar3 V = make_scalar3(h_vel.data[j].x, h_vel.data[j].y, h_vel.data[j].z); Scalar3 F = make_scalar3(h_net_force.data[j].x, h_net_force.data[j].y, h_net_force.data[j].z); Scalar m = h_vel.data[j].w; // evaluate the constraint position EvaluatorConstraint constraint(X, V, F, m, m_deltaT); Scalar3 U = constraint.evalU(); Scalar3 D = make_scalar3((U.x - X.x), (U.y - X.y), (U.z - X.z)); Scalar n = (D.x*m_vec.x + D.y*m_vec.y + D.z*m_vec.z)/(m_vec.x*m_vec.x + m_vec.y*m_vec.y + m_vec.z*m_vec.z); Scalar3 C = make_scalar3((n*m_vec.x + X.x), (n*m_vec.y + X.y), (n*m_vec.z + X.z)); // evaluate the constraint force Scalar3 FC; Scalar virial[6]; constraint.evalConstraintForce(FC, virial, C); // apply the constraint force h_force.data[j].x = FC.x; h_force.data[j].y = FC.y; h_force.data[j].z = FC.z; for (int k = 0; k < 6; k++) h_virial.data[k*virial_pitch+j] = virial[k]; } if (m_prof) m_prof->pop(); } /*! OneDCOnstraint removes 2 degrees of freedom per particle in the group */ unsigned int OneDConstraint::getNDOFRemoved() { return m_group->getNumMembersGlobal(); } void export_OneDConstraint(py::module& m) { py::class_< OneDConstraint, std::shared_ptr >(m, "OneDConstraint", py::base()) .def(py::init< std::shared_ptr, std::shared_ptr, Scalar3 >()) .def("getNDOFRemoved", &OneDConstraint::getNDOFRemoved) .def("setVector", &OneDConstraint::setVector) ; } 0 /* Copyright 2010-2016 Intel Corporation This software is licensed to you in accordance with the agreement between you and Intel Corporation. Alternatively, you can use this file in compliance with the Apache license, Version 2. Apache License, Version 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. */ /* * * @file bhp_platform_win32.cpp * @brief This file implements BHP platform dependent part on Win32 platform. * @author * @version * */ #include #include #include "bhp_platform.h" #ifdef TRACE_MALLOC struct { void* (*pm) (int size); void* (*pml) (int size, const char* file, int line); //malloc with filename and lineno void (*pf) (void* p); void (*pfl) (void* p, const char* file, int line); //free with filename and lineno } plat_mem_procs = {0}; void* bhp_trace_malloc (int size, const char* file, int line) { if (plat_mem_procs.pml) return plat_mem_procs.pml(size, file, line); return plat_mem_procs.pm(size); } void bhp_trace_free (void* p, const char* file, int line) { if (plat_mem_procs.pfl) return plat_mem_procs.pfl(p, file, line); return plat_mem_procs.pf(p); } __declspec(dllexport) void BHP_SetupAllocate(void* alloc_f, void* alloc_location_f, void* free_f, void* free_location_f) { plat_mem_procs.pm = (void* (*) (int)) alloc_f; plat_mem_procs.pml = (void* (*) (int, const char*, int)) alloc_location_f; plat_mem_procs.pf = (void (*) (void*)) free_f; plat_mem_procs.pfl = (void (*) (void*, const char*, int)) free_location_f; } #endif bhp_mutex_t bh_create_mutex(void) { return ::CreateMutex(NULL, FALSE, NULL); } void bh_close_mutex(bhp_mutex_t m) { ::CloseHandle(m); } void mutex_enter(bhp_mutex_t m) { ::WaitForSingleObject(m, INFINITE); } void mutex_exit(bhp_mutex_t m) { ::ReleaseMutex(m); } bhp_event_t bh_create_event(void) { return ::CreateEvent(NULL, FALSE, FALSE, NULL); } void bh_close_event(bhp_event_t evt) { ::CloseHandle(evt); } void bh_signal_event(bhp_event_t evt) { ::SetEvent(evt); } void bh_reset_event(bhp_event_t evt) { ::ResetEvent(evt); } void bh_wait_event(bhp_event_t evt) { ::WaitForSingleObject(evt, INFINITE); } bhp_thread_t bh_thread_create (void* (*func)(void*), void* args) { return (bhp_thread_t)::CreateThread (NULL, 0, (LPTHREAD_START_ROUTINE) func, args, 0, NULL); } void bh_thread_close (bhp_thread_t thread) { ::CloseHandle(thread); } void bh_thread_join (bhp_thread_t thread) { if (thread == NULL) return; //daoming: don't kill recv_thread, as the thread will exit automatically when heci disconnected. //TerminateThread((HANDLE) thread, 0); ::WaitForSingleObject(thread, INFINITE); } void bh_thread_cancel (bhp_thread_t thread) { // In Windows nothing needs to be done here. } /* unsigned int bh_atomic_inc(volatile unsigned int* pVal) { return InterlockedIncrement(pVal); } unsigned int bh_atomic_dec(volatile unsigned int* pVal) { return InterlockedDecrement(pVal); } */ /* static unsigned int bh_atomic_comp_and_swap(volatile unsigned int* dest, unsigned int exchange, unsigned int comparand) { return InterlockedCompareExchange(dest, exchange, comparand); } */ void bh_debug_print(int level, const char *format, ... ) { #define DEBUG_BUF_LEN 1024 if (level <= BHP_LOG_LEVEL) { char buffer[DEBUG_BUF_LEN]; va_list args; va_start(args, format); vsprintf_s(buffer, DEBUG_BUF_LEN, format, args); va_end(args); ::OutputDebugStringA(buffer); //fprintf(stderr, "%s", buffer); //for linux //fflush(stderr); //only fatal msg shown in the console if (level == LOG_LEVEL_FATAL) printf(buffer); } } /*========================================================================= * * Copyright NumFOCUS * * 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.txt * * 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. * *=========================================================================*/ /* * This is a test file for the itkImageMaskSpatialObject class. * the Bounding box for an itk::ImageMaskSpatialObject should * be related to the inside (axis aligned region) of the spatial object * It Tests both 2D and 3D cases */ /* * This test addresses bug * https://insightsoftwareconsortium.atlassian.net/browse/ITK-3153 * */ #include "itkSpatialObjectToImageFilter.h" #include "itkBoxSpatialObject.h" #include "itkImageMaskSpatialObject.h" namespace { int Test3dImageMask() { using BoxType = itk::BoxSpatialObject<3>; using TransformType = BoxType::TransformType; // Box1 --- // bounding box of [0,1] x [0,1] x [0,1] // then translate it by 7 in all directions // bounding box should by [7,8] x [7,8] x [7,8] auto box1 = BoxType::New(); BoxType::SizeType sizeArray; sizeArray[0] = 1; sizeArray[1] = 1; sizeArray[2] = 1; box1->SetSizeInObjectSpace(sizeArray); box1->SetDefaultInsideValue(1); box1->SetDefaultOutsideValue(0); auto transform = TransformType::New(); TransformType::OutputVectorType translation; transform->SetIdentity(); translation[0] = 7; translation[1] = 7; translation[2] = 7; transform->Translate(translation); box1->SetObjectToWorldTransform(transform); box1->Update(); const BoxType::BoundingBoxType::BoundsArrayType box1Bounds = box1->GetMyBoundingBoxInWorldSpace()->GetBounds(); if (itk::Math::NotAlmostEquals(box1Bounds[0], 7.0) || itk::Math::NotAlmostEquals(box1Bounds[2], 7.0) || itk::Math::NotAlmostEquals(box1Bounds[4], 7.0) || itk::Math::NotAlmostEquals(box1Bounds[1], 8.0) || itk::Math::NotAlmostEquals(box1Bounds[3], 8.0) || itk::Math::NotAlmostEquals(box1Bounds[5], 8.0)) { std::cout << "Box1 - Bounding box Error" << std::endl; std::cout << " Expecting a bounding box of [7 8 7 8 7 8]" << std::endl; std::cout << " But received one of " << box1Bounds << std::endl; return EXIT_FAILURE; } // Now generate an imageMaskSpatial Object from box1 // Should have the same bounding box. using ImageType = itk::Image; using ImageMaskSpatialObjectType = itk::ImageMaskSpatialObject<3>; using SpatialObjectToImageFilterType = itk::SpatialObjectToImageFilter; auto imageFilter = SpatialObjectToImageFilterType::New(); // note visual studio 2015 u1 (release mode) fails to exectute .Fill // properly here by not initializing the last member. With initializer it // is happy. itk::Size<3> size = { { 10, 10, 10 } }; // size.Fill(10) // The SpatialObjectToImageFilter requires that the user defines the grid // parameters of the output image. This includes the number of pixels along // each dimension, the pixel spacing, image direction and imageFilter->SetSize(size); double origin[3]; origin[0] = 5; origin[1] = 5; origin[2] = 5; imageFilter->SetOrigin(origin); ImageType::SpacingType spacing; spacing[0] = 5.0 / size[0]; spacing[1] = 5.0 / size[1]; spacing[2] = 5.0 / size[2]; imageFilter->SetSpacing(spacing); imageFilter->SetInsideValue(255); // white imageFilter->SetOutsideValue(0); imageFilter->SetInput(box1); imageFilter->Update(); auto maskSpatialObject = ImageMaskSpatialObjectType::New(); maskSpatialObject->SetImage(imageFilter->GetOutput()); maskSpatialObject->Update(); using MaskBoundsArrayType = ImageMaskSpatialObjectType::BoundingBoxType::BoundsArrayType; const MaskBoundsArrayType maskBounds = maskSpatialObject->GetMyBoundingBoxInWorldSpace()->GetBounds(); // Test a few points... ImageMaskSpatialObjectType::PointType point; std::cout << "Mask -- Bounds : " << maskBounds << std::endl; point[0] = 0; point[1] = 0; point[2] = 0; std::cout << " " << point << " isInside? : " << maskSpatialObject->IsInsideInWorldSpace(point) << std::endl; point[0] = 6; point[1] = 7; point[2] = 7; std::cout << " " << point << " isInside? : " << maskSpatialObject->IsInsideInWorldSpace(point) << std::endl; point[0] = 7; point[1] = 7; point[2] = 7; std::cout << " " << point << " isInside? : " << maskSpatialObject->IsInsideInWorldSpace(point) << std::endl; point[0] = 8; point[1] = 7; point[2] = 7; std::cout << " " << point << " isInside? : " << maskSpatialObject->IsInsideInWorldSpace(point) << std::endl; point[0] = 8; point[1] = 8; point[2] = 8; std::cout << " " << point << " isInside? : " << maskSpatialObject->IsInsideInWorldSpace(point) << std::endl; point[0] = 9; point[1] = 7; point[2] = 7; std::cout << " " << point << " isInside? : " << maskSpatialObject->IsInsideInWorldSpace(point) << std::endl; constexpr std::array expectedBounds{ { 6.75, 8.25, 6.75, 8.25, 6.75, 8.25 } }; for (unsigned int i = 0; i < MaskBoundsArrayType::Length; ++i) { if (itk::Math::NotAlmostEquals(maskBounds[i], expectedBounds[i])) { std::cout << "[FAILED] " << std::endl; std::cout << "Test returned : " << maskSpatialObject->GetMyBoundingBoxInWorldSpace()->GetBounds() << std::endl; std::cout << "Instead of : " << MaskBoundsArrayType{ expectedBounds } << std::endl; return EXIT_FAILURE; } } std::cout << "[Passed] -- 3D test" << std::endl; return EXIT_SUCCESS; } int Test2dImageMask() { using BoxType = itk::BoxSpatialObject<2>; using TransformType = BoxType::TransformType; // Box1 --- // bounding box of [0,1] x [0,1] // then translate it by 7 in all directions // bounding box should by [7,8] x [7,8] auto box1 = BoxType::New(); BoxType::SizeType sizeArray; sizeArray[0] = 1; sizeArray[1] = 1; box1->SetSizeInObjectSpace(sizeArray); box1->SetDefaultInsideValue(1); box1->SetDefaultOutsideValue(0); auto transform = TransformType::New(); TransformType::OutputVectorType translation; transform->SetIdentity(); translation[0] = 7; translation[1] = 7; transform->Translate(translation); box1->SetObjectToWorldTransform(transform); box1->Update(); const BoxType::BoundingBoxType::BoundsArrayType box1Bounds = box1->GetMyBoundingBoxInWorldSpace()->GetBounds(); if (itk::Math::NotAlmostEquals(box1Bounds[0], 7.0) || itk::Math::NotAlmostEquals(box1Bounds[2], 7.0) || itk::Math::NotAlmostEquals(box1Bounds[1], 8.0) || itk::Math::NotAlmostEquals(box1Bounds[3], 8.0)) { std::cout << "Box1 - Bounding box Error" << std::endl; std::cout << " Expecting a bounding box of [7 8 7 8]" << std::endl; std::cout << " But received one of " << box1Bounds << std::endl; return EXIT_FAILURE; } // Now generate an imageMaskSpatial Object from box1 // Should have the same bounding box. withing pixelation bounds using ImageType = itk::Image; using ImageMaskSpatialObjectType = itk::ImageMaskSpatialObject<2>; using SpatialObjectToImageFilterType = itk::SpatialObjectToImageFilter; auto imageFilter = SpatialObjectToImageFilterType::New(); itk::Size<2> size; size.Fill(10); // The SpatialObjectToImageFilter requires that the user defines the grid // parameters of the output image. This includes the number of pixels along // each dimension, the pixel spacing, and image direction imageFilter->SetSize(size); double origin[2]; origin[0] = 5; origin[1] = 5; imageFilter->SetOrigin(origin); ImageType::SpacingType spacing; spacing[0] = 7.0 / size[0]; spacing[1] = 7.0 / size[1]; imageFilter->SetSpacing(spacing); imageFilter->SetInsideValue(255); // white imageFilter->SetOutsideValue(0); imageFilter->SetInput(box1); imageFilter->Update(); auto maskSpatialObject = ImageMaskSpatialObjectType::New(); maskSpatialObject->SetImage(imageFilter->GetOutput()); maskSpatialObject->Update(); using MaskBoundsArrayType = ImageMaskSpatialObjectType::BoundingBoxType::BoundsArrayType; const MaskBoundsArrayType maskBounds = maskSpatialObject->GetMyBoundingBoxInWorldSpace()->GetBounds(); // Test a few points... ImageMaskSpatialObjectType::PointType point; std::cout << "Mask -- Bounds : " << maskBounds << std::endl; point[0] = 0; point[1] = 0; std::cout << " " << point << " isInside? : " << maskSpatialObject->IsInsideInWorldSpace(point) << std::endl; point[0] = 6; point[1] = 7.5; std::cout << " " << point << " isInside? : " << maskSpatialObject->IsInsideInWorldSpace(point) << std::endl; point[0] = 7.5; point[1] = 7.5; std::cout << " " << point << " isInside? : " << maskSpatialObject->IsInsideInWorldSpace(point) << std::endl; point[0] = 8; point[1] = 7.5; std::cout << " " << point << " isInside? : " << maskSpatialObject->IsInsideInWorldSpace(point) << std::endl; point[0] = 8; point[1] = 8; std::cout << " " << point << " isInside? : " << maskSpatialObject->IsInsideInWorldSpace(point) << std::endl; point[0] = 9; point[1] = 7.5; std::cout << " " << point << " isInside? : " << maskSpatialObject->IsInsideInWorldSpace(point) << std::endl; constexpr std::array expectedBounds{ { 6.75, 8.15, 6.75, 8.15 } }; for (unsigned int i = 0; i < MaskBoundsArrayType::Length; ++i) { if (itk::Math::NotAlmostEquals(maskBounds[i], expectedBounds[i])) { std::cout << "[FAILED] " << std::endl; std::cout << "Test returned : " << maskSpatialObject->GetMyBoundingBoxInWorldSpace()->GetBounds() << std::endl; std::cout << "Instead of : " << MaskBoundsArrayType{ expectedBounds } << std::endl; return EXIT_FAILURE; } } std::cout << "[Passed] -- 2D test" << std::endl; return EXIT_SUCCESS; } } // namespace int itkImageMaskSpatialObjectTest4(int, char *[]) { if (Test3dImageMask() == EXIT_FAILURE) { return EXIT_FAILURE; } if (Test2dImageMask() == EXIT_FAILURE) { return EXIT_FAILURE; } std::cout << "Test finished" << std::endl; return EXIT_SUCCESS; } qtdeclarative/src/quick/items/context2d/qquickcontext2dtile.cpp /**************************************************************************** ** ** Copyright (C) 2015 The Qt Company Ltd. ** Contact: http://www.qt.io/licensing/ ** ** This file is part of the QtQuick module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL21$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see http://www.qt.io/terms-conditions. For further ** information use the contact form at http://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** As a special exception, The Qt Company gives you certain additional ** rights. These rights are described in The Qt Company LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qquickcontext2dtile_p.h" #include #include #include QT_BEGIN_NAMESPACE QQuickContext2DTile::QQuickContext2DTile() : m_dirty(true) , m_rect(QRect(0, 0, 1, 1)) , m_device(0) { } QQuickContext2DTile::~QQuickContext2DTile() { if (m_painter.isActive()) m_painter.end(); } QPainter* QQuickContext2DTile::createPainter(bool smooth, bool antialiasing) { if (m_painter.isActive()) m_painter.end(); aboutToDraw(); if (m_device) { m_painter.begin(m_device); m_painter.resetTransform(); m_painter.setCompositionMode(QPainter::CompositionMode_Source); #ifdef QQUICKCONTEXT2D_DEBUG int v = 100; int gray = (m_rect.x() / m_rect.width() + m_rect.y() / m_rect.height()) % 2; if (gray) v = 150; m_painter.fillRect(QRect(0, 0, m_rect.width(), m_rect.height()), QColor(v, v, v, 255)); #endif if (antialiasing) m_painter.setRenderHints(QPainter::Antialiasing | QPainter::TextAntialiasing, true); else m_painter.setRenderHints(QPainter::Antialiasing | QPainter::TextAntialiasing, false); if (smooth) m_painter.setRenderHint(QPainter::SmoothPixmapTransform, true); else m_painter.setRenderHint(QPainter::SmoothPixmapTransform, false); m_painter.setCompositionMode(QPainter::CompositionMode_SourceOver); m_painter.translate(-m_rect.left(), -m_rect.top()); m_painter.setClipRect(m_rect); m_painter.setClipping(false); return &m_painter; } return 0; } QQuickContext2DFBOTile::QQuickContext2DFBOTile() : QQuickContext2DTile() , m_fbo(0) { } QQuickContext2DFBOTile::~QQuickContext2DFBOTile() { if (m_fbo) m_fbo->release(); delete m_fbo; } void QQuickContext2DFBOTile::aboutToDraw() { m_fbo->bind(); if (!m_device) { QOpenGLPaintDevice *gl_device = new QOpenGLPaintDevice(rect().size()); m_device = gl_device; QPainter p(m_device); p.fillRect(QRectF(0, 0, m_fbo->width(), m_fbo->height()), QColor(qRgba(0, 0, 0, 0))); p.end(); } } void QQuickContext2DFBOTile::drawFinished() { } void QQuickContext2DFBOTile::setRect(const QRect& r) { if (m_rect == r) return; m_rect = r; m_dirty = true; if (!m_fbo || m_fbo->size() != r.size()) { QOpenGLFramebufferObjectFormat format; format.setAttachment(QOpenGLFramebufferObject::CombinedDepthStencil); format.setInternalTextureFormat(GL_RGBA); format.setMipmap(false); if (m_painter.isActive()) m_painter.end(); delete m_fbo; m_fbo = new QOpenGLFramebufferObject(r.size(), format); } } QQuickContext2DImageTile::QQuickContext2DImageTile() : QQuickContext2DTile() { } QQuickContext2DImageTile::~QQuickContext2DImageTile() { } void QQuickContext2DImageTile::setRect(const QRect& r) { if (m_rect == r) return; m_rect = r; m_dirty = true; if (m_image.size() != r.size()) { m_image = QImage(r.size(), QImage::Format_ARGB32_Premultiplied); } m_device = &m_image; } QT_END_NAMESPACE /****************************************************************************** * $Id$ * * Project: CartoDB Translator * Purpose: Implements OGRCARTODBTableLayer class. * Author: , * ****************************************************************************** * Copyright (c) 2013, * * 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 "ogr_cartodb.h" #include "ogr_p.h" #include "ogr_pgdump.h" CPL_CVSID("$Id$"); /************************************************************************/ /* OGRCARTODBEscapeIdentifier( ) */ /************************************************************************/ CPLString OGRCARTODBEscapeIdentifier(const char* pszStr) { CPLString osStr; osStr += "\""; char ch; for(int i=0; (ch = pszStr[i]) != '\0'; i++) { if (ch == '"') osStr.append(1, ch); osStr.append(1, ch); } osStr += "\""; return osStr; } /************************************************************************/ /* OGRCARTODBEscapeLiteral( ) */ /************************************************************************/ CPLString OGRCARTODBEscapeLiteral(const char* pszStr) { CPLString osStr; char ch; for(int i=0; (ch = pszStr[i]) != '\0'; i++) { if (ch == '\'') osStr.append(1, ch); osStr.append(1, ch); } return osStr; } /************************************************************************/ /* OGRCARTODBTableLayer() */ /************************************************************************/ OGRCARTODBTableLayer::OGRCARTODBTableLayer(OGRCARTODBDataSource* poDSIn, const char* pszName) : OGRCARTODBLayer(poDSIn) { osName = pszName; SetDescription( osName ); bLaunderColumnNames = TRUE; bInDeferedInsert = poDS->DoBatchInsert(); eDeferedInsertState = INSERT_UNINIT; nNextFID = -1; bDeferedCreation = FALSE; bCartoDBify = FALSE; nMaxChunkSize = atoi(CPLGetConfigOption("CARTODB_MAX_CHUNK_SIZE", "15")) * 1024 * 1024; } /************************************************************************/ /* ~OGRCARTODBTableLayer() */ /************************************************************************/ OGRCARTODBTableLayer::~OGRCARTODBTableLayer() { if( bDeferedCreation ) RunDeferedCreationIfNecessary(); CPL_IGNORE_RET_VAL(FlushDeferedInsert()); RunDeferedCartoDBfy(); } /************************************************************************/ /* GetLayerDefnInternal() */ /************************************************************************/ OGRFeatureDefn * OGRCARTODBTableLayer::GetLayerDefnInternal(CPL_UNUSED json_object* poObjIn) { if( poFeatureDefn != NULL ) return poFeatureDefn; CPLString osCommand; if( poDS->IsAuthenticatedConnection() ) { // Get everything ! osCommand.Printf( "SELECT a.attname, t.typname, a.attlen, " "format_type(a.atttypid,a.atttypmod), " "a.attnum, " "a.attnotnull, " "i.indisprimary, " "pg_get_expr(def.adbin, c.oid) AS defaultexpr, " "postgis_typmod_dims(a.atttypmod) dim, " "postgis_typmod_srid(a.atttypmod) srid, " "postgis_typmod_type(a.atttypmod)::text geomtyp, " "srtext " "FROM pg_class c " "JOIN pg_attribute a ON a.attnum > 0 AND " "a.attrelid = c.oid AND c.relname = '%s' " "JOIN pg_type t ON a.atttypid = t.oid " "JOIN pg_namespace n ON c.relnamespace=n.oid AND n.nspname= '%s' " "LEFT JOIN pg_index i ON c.oid = i.indrelid AND " "i.indisprimary = 't' AND a.attnum = ANY(i.indkey) " "LEFT JOIN pg_attrdef def ON def.adrelid = c.oid AND " "def.adnum = a.attnum " "LEFT JOIN spatial_ref_sys srs ON srs.srid = postgis_typmod_srid(a.atttypmod) " "ORDER BY a.attnum", OGRCARTODBEscapeLiteral(osName).c_str(), OGRCARTODBEscapeLiteral(poDS->GetCurrentSchema()).c_str()); } else if( poDS->HasOGRMetadataFunction() != FALSE ) { osCommand.Printf( "SELECT * FROM ogr_table_metadata('%s', '%s')", OGRCARTODBEscapeLiteral(poDS->GetCurrentSchema()).c_str(), OGRCARTODBEscapeLiteral(osName).c_str() ); } if( osCommand.size() ) { if( !poDS->IsAuthenticatedConnection() && poDS->HasOGRMetadataFunction() < 0 ) CPLPushErrorHandler(CPLQuietErrorHandler); OGRLayer* poLyr = poDS->ExecuteSQLInternal(osCommand); if( !poDS->IsAuthenticatedConnection() && poDS->HasOGRMetadataFunction() < 0 ) { CPLPopErrorHandler(); if( poLyr == NULL ) { CPLDebug("CARTODB", "ogr_table_metadata(text, text) not available"); CPLErrorReset(); } else if( poLyr->GetLayerDefn()->GetFieldCount() != 12 ) { CPLDebug("CARTODB", "ogr_table_metadata(text, text) has unexpected column count"); poDS->ReleaseResultSet(poLyr); poLyr = NULL; } poDS->SetOGRMetadataFunction(poLyr != NULL); } if( poLyr ) { OGRFeature* poFeat; while( (poFeat = poLyr->GetNextFeature()) != NULL ) { if( poFeatureDefn == NULL ) { // We could do that outside of the while() loop, but // by doing that here, we are somewhat robust to // ogr_table_metadata() returning suddenly an empty result set // for example if CDB_UserTables() no longer works poFeatureDefn = new OGRFeatureDefn(osName); poFeatureDefn->Reference(); poFeatureDefn->SetGeomType(wkbNone); } const char* pszAttname = poFeat->GetFieldAsString("attname"); const char* pszType = poFeat->GetFieldAsString("typname"); int nWidth = poFeat->GetFieldAsInteger("attlen"); const char* pszFormatType = poFeat->GetFieldAsString("format_type"); int bNotNull = poFeat->GetFieldAsInteger("attnotnull"); int bIsPrimary = poFeat->GetFieldAsInteger("indisprimary"); int iDefaultExpr = poLyr->GetLayerDefn()->GetFieldIndex("defaultexpr"); const char* pszDefault = (iDefaultExpr >= 0 && poFeat->IsFieldSet(iDefaultExpr)) ? poFeat->GetFieldAsString(iDefaultExpr) : NULL; if( bIsPrimary && (EQUAL(pszType, "int2") || EQUAL(pszType, "int4") || EQUAL(pszType, "int8") || EQUAL(pszType, "serial") || EQUAL(pszType, "bigserial")) ) { osFIDColName = pszAttname; } else if( strcmp(pszAttname, "created_at") == 0 || strcmp(pszAttname, "updated_at") == 0 || strcmp(pszAttname, "the_geom_webmercator") == 0) { /* ignored */ } else { if( EQUAL(pszType,"geometry") ) { int nDim = poFeat->GetFieldAsInteger("dim"); int nSRID = poFeat->GetFieldAsInteger("srid"); const char* pszGeomType = poFeat->GetFieldAsString("geomtyp"); const char* pszSRText = (poFeat->IsFieldSet( poLyr->GetLayerDefn()->GetFieldIndex("srtext"))) ? poFeat->GetFieldAsString("srtext") : NULL; OGRwkbGeometryType eType = OGRFromOGCGeomType(pszGeomType); if( nDim == 3 ) eType = wkbSetZ(eType); OGRCartoDBGeomFieldDefn *poFieldDefn = new OGRCartoDBGeomFieldDefn(pszAttname, eType); if( bNotNull ) poFieldDefn->SetNullable(FALSE); OGRSpatialReference* l_poSRS = NULL; if( pszSRText != NULL ) { l_poSRS = new OGRSpatialReference(); char* pszTmp = (char* )pszSRText; if( l_poSRS->importFromWkt(&pszTmp) != OGRERR_NONE ) { delete l_poSRS; l_poSRS = NULL; } if( l_poSRS != NULL ) { poFieldDefn->SetSpatialRef(l_poSRS); l_poSRS->Release(); } } poFieldDefn->nSRID = nSRID; poFeatureDefn->AddGeomFieldDefn(poFieldDefn, FALSE); } else { OGRFieldDefn oField(pszAttname, OFTString); if( bNotNull ) oField.SetNullable(FALSE); OGRPGCommonLayerSetType(oField, pszType, pszFormatType, nWidth); if( pszDefault ) OGRPGCommonLayerNormalizeDefault(&oField, pszDefault); poFeatureDefn->AddFieldDefn( &oField ); } } delete poFeat; } poDS->ReleaseResultSet(poLyr); } } if( poFeatureDefn == NULL ) { osBaseSQL.Printf("SELECT * FROM %s", OGRCARTODBEscapeIdentifier(osName).c_str()); EstablishLayerDefn(osName, NULL); osBaseSQL = ""; } if( osFIDColName.size() > 0 ) { osBaseSQL = "SELECT "; osBaseSQL += OGRCARTODBEscapeIdentifier(osFIDColName); } for(int i=0; iGetGeomFieldCount(); i++) { if( osBaseSQL.size() == 0 ) osBaseSQL = "SELECT "; else osBaseSQL += ", "; osBaseSQL += OGRCARTODBEscapeIdentifier(poFeatureDefn->GetGeomFieldDefn(i)->GetNameRef()); } for(int i=0; iGetFieldCount(); i++) { if( osBaseSQL.size() == 0 ) osBaseSQL = "SELECT "; else osBaseSQL += ", "; osBaseSQL += OGRCARTODBEscapeIdentifier(poFeatureDefn->GetFieldDefn(i)->GetNameRef()); } if( osBaseSQL.size() == 0 ) osBaseSQL = "SELECT *"; osBaseSQL += " FROM "; osBaseSQL += OGRCARTODBEscapeIdentifier(osName); osSELECTWithoutWHERE = osBaseSQL; return poFeatureDefn; } /************************************************************************/ /* FetchNewFeatures() */ /************************************************************************/ json_object* OGRCARTODBTableLayer::FetchNewFeatures(GIntBig iNextIn) { if( osFIDColName.size() > 0 ) { CPLString osSQL; osSQL.Printf("%s WHERE %s%s >= " CPL_FRMT_GIB " ORDER BY %s ASC LIMIT %d", osSELECTWithoutWHERE.c_str(), ( osWHERE.size() ) ? CPLSPrintf("%s AND ", osWHERE.c_str()) : "", OGRCARTODBEscapeIdentifier(osFIDColName).c_str(), iNext, OGRCARTODBEscapeIdentifier(osFIDColName).c_str(), GetFeaturesToFetch()); return poDS->RunSQL(osSQL); } else return OGRCARTODBLayer::FetchNewFeatures(iNextIn); } /************************************************************************/ /* GetNextRawFeature() */ /************************************************************************/ OGRFeature *OGRCARTODBTableLayer::GetNextRawFeature() { if( bDeferedCreation && RunDeferedCreationIfNecessary() != OGRERR_NONE ) return NULL; if( FlushDeferedInsert() != OGRERR_NONE ) return NULL; return OGRCARTODBLayer::GetNextRawFeature(); } /************************************************************************/ /* SetAttributeFilter() */ /************************************************************************/ OGRErr OGRCARTODBTableLayer::SetAttributeFilter( const char *pszQuery ) { GetLayerDefn(); if( pszQuery == NULL ) osQuery = ""; else { osQuery = "("; osQuery += pszQuery; osQuery += ")"; } BuildWhere(); ResetReading(); return OGRERR_NONE; } /************************************************************************/ /* SetSpatialFilter() */ /************************************************************************/ void OGRCARTODBTableLayer::SetSpatialFilter( int iGeomField, OGRGeometry * poGeomIn ) { if( iGeomField < 0 || iGeomField >= GetLayerDefn()->GetGeomFieldCount() || GetLayerDefn()->GetGeomFieldDefn(iGeomField)->GetType() == wkbNone ) { if( iGeomField != 0 ) { CPLError(CE_Failure, CPLE_AppDefined, "Invalid geometry field index : %d", iGeomField); } return; } m_iGeomFieldFilter = iGeomField; if( InstallFilter( poGeomIn ) ) { BuildWhere(); ResetReading(); } } /************************************************************************/ /* RunDeferedCartoDBfy() */ /************************************************************************/ void OGRCARTODBTableLayer::RunDeferedCartoDBfy() { if( bCartoDBify ) { bCartoDBify = FALSE; CPLString osSQL; if( poDS->GetCurrentSchema() == "public" ) osSQL.Printf("SELECT cdb_cartodbfytable('%s')", OGRCARTODBEscapeLiteral(osName).c_str()); else osSQL.Printf("SELECT cdb_cartodbfytable('%s', '%s')", OGRCARTODBEscapeLiteral(poDS->GetCurrentSchema()).c_str(), OGRCARTODBEscapeLiteral(osName).c_str()); json_object* poObj = poDS->RunSQL(osSQL); if( poObj != NULL ) json_object_put(poObj); } } /************************************************************************/ /* FlushDeferedInsert() */ /************************************************************************/ OGRErr OGRCARTODBTableLayer::FlushDeferedInsert(bool bReset) { OGRErr eErr = OGRERR_NONE; if( bInDeferedInsert && osDeferedInsertSQL.size() > 0 ) { osDeferedInsertSQL = "BEGIN;" + osDeferedInsertSQL; if( eDeferedInsertState == INSERT_MULTIPLE_FEATURE ) { osDeferedInsertSQL += ";"; eDeferedInsertState = INSERT_UNINIT; } osDeferedInsertSQL += "COMMIT;"; json_object* poObj = poDS->RunSQL(osDeferedInsertSQL); if( poObj != NULL ) { json_object_put(poObj); } else { bInDeferedInsert = FALSE; eErr = OGRERR_FAILURE; } } osDeferedInsertSQL = ""; if( bReset ) { bInDeferedInsert = FALSE; nNextFID = -1; } return eErr; } /************************************************************************/ /* CreateField() */ /************************************************************************/ OGRErr OGRCARTODBTableLayer::CreateField( OGRFieldDefn *poFieldIn, CPL_UNUSED int bApproxOK ) { GetLayerDefn(); if (!poDS->IsReadWrite()) { CPLError(CE_Failure, CPLE_AppDefined, "Operation not available in read-only mode"); return OGRERR_FAILURE; } if( eDeferedInsertState == INSERT_MULTIPLE_FEATURE ) { if( FlushDeferedInsert() != OGRERR_NONE ) return OGRERR_FAILURE; } OGRFieldDefn oField(poFieldIn); if( bLaunderColumnNames ) { char* pszName = OGRPGCommonLaunderName(oField.GetNameRef()); oField.SetName(pszName); CPLFree(pszName); } /* -------------------------------------------------------------------- */ /* Create the new field. */ /* -------------------------------------------------------------------- */ if( !bDeferedCreation ) { CPLString osSQL; osSQL.Printf( "ALTER TABLE %s ADD COLUMN %s %s", OGRCARTODBEscapeIdentifier(osName).c_str(), OGRCARTODBEscapeIdentifier(oField.GetNameRef()).c_str(), OGRPGCommonLayerGetType(oField, FALSE, TRUE).c_str() ); if( !oField.IsNullable() ) osSQL += " NOT NULL"; if( oField.GetDefault() != NULL && !oField.IsDefaultDriverSpecific() ) { osSQL += " DEFAULT "; osSQL += OGRPGCommonLayerGetPGDefault(&oField); } json_object* poObj = poDS->RunSQL(osSQL); if( poObj == NULL ) return OGRERR_FAILURE; json_object_put(poObj); } poFeatureDefn->AddFieldDefn( &oField ); return OGRERR_NONE; } /************************************************************************/ /* DeleteField() */ /************************************************************************/ OGRErr OGRCARTODBTableLayer::DeleteField( int iField ) { CPLString osSQL; if (!poDS->IsReadWrite()) { CPLError(CE_Failure, CPLE_AppDefined, "Operation not available in read-only mode"); return OGRERR_FAILURE; } if (iField < 0 || iField >= poFeatureDefn->GetFieldCount()) { CPLError( CE_Failure, CPLE_NotSupported, "Invalid field index"); return OGRERR_FAILURE; } if( eDeferedInsertState == INSERT_MULTIPLE_FEATURE ) { if( FlushDeferedInsert() != OGRERR_NONE ) return OGRERR_FAILURE; } /* -------------------------------------------------------------------- */ /* Drop the field. */ /* -------------------------------------------------------------------- */ osSQL.Printf( "ALTER TABLE %s DROP COLUMN %s", OGRCARTODBEscapeIdentifier(osName).c_str(), OGRCARTODBEscapeIdentifier(poFeatureDefn->GetFieldDefn(iField)->GetNameRef()).c_str() ); json_object* poObj = poDS->RunSQL(osSQL); if( poObj == NULL ) return OGRERR_FAILURE; json_object_put(poObj); return poFeatureDefn->DeleteFieldDefn( iField ); } /************************************************************************/ /* ICreateFeature() */ /************************************************************************/ OGRErr OGRCARTODBTableLayer::ICreateFeature( OGRFeature *poFeature ) { int i; if( bDeferedCreation ) { if( RunDeferedCreationIfNecessary() != OGRERR_NONE ) return OGRERR_FAILURE; } GetLayerDefn(); int bHasUserFieldMatchingFID = FALSE; if( osFIDColName.size() ) bHasUserFieldMatchingFID = poFeatureDefn->GetFieldIndex(osFIDColName) >= 0; if (!poDS->IsReadWrite()) { CPLError(CE_Failure, CPLE_AppDefined, "Operation not available in read-only mode"); return OGRERR_FAILURE; } CPLString osSQL; int bHasJustGotNextFID = FALSE; if( !bHasUserFieldMatchingFID && bInDeferedInsert && nNextFID < 0 && osFIDColName.size() ) { osSQL.Printf("SELECT nextval('%s') AS nextid", OGRCARTODBEscapeLiteral(CPLSPrintf("%s_%s_seq", osName.c_str(), osFIDColName.c_str())).c_str()); json_object* poObj = poDS->RunSQL(osSQL); json_object* poRowObj = OGRCARTODBGetSingleRow(poObj); if( poRowObj != NULL ) { json_object* poID = json_object_object_get(poRowObj, "nextid"); if( poID != NULL && json_object_get_type(poID) == json_type_int ) { nNextFID = json_object_get_int64(poID); bHasJustGotNextFID = TRUE; } } if( poObj != NULL ) json_object_put(poObj); } // Check if we can go on with multiple insertion mode if( eDeferedInsertState == INSERT_MULTIPLE_FEATURE ) { if( !bHasUserFieldMatchingFID && osFIDColName.size() && (poFeature->GetFID() != OGRNullFID || (nNextFID >= 0 && bHasJustGotNextFID)) ) { if( FlushDeferedInsert(false) != OGRERR_NONE ) return OGRERR_FAILURE; } } bool bWriteInsertInto = (eDeferedInsertState != INSERT_MULTIPLE_FEATURE); bool bResetToUninitInsertStateAfterwards = false; if( eDeferedInsertState == INSERT_UNINIT ) { if( !bInDeferedInsert ) { eDeferedInsertState = INSERT_SINGLE_FEATURE; } else if( !bHasUserFieldMatchingFID && osFIDColName.size() && (poFeature->GetFID() != OGRNullFID || (nNextFID >= 0 && bHasJustGotNextFID)) ) { eDeferedInsertState = INSERT_SINGLE_FEATURE; bResetToUninitInsertStateAfterwards = true; } else { eDeferedInsertState = INSERT_MULTIPLE_FEATURE; for(i = 0; i < poFeatureDefn->GetFieldCount(); i++) { if( poFeatureDefn->GetFieldDefn(i)->GetDefault() != NULL ) eDeferedInsertState = INSERT_SINGLE_FEATURE; } } } int bMustComma = FALSE; if( bWriteInsertInto ) { osSQL.Printf("INSERT INTO %s ", OGRCARTODBEscapeIdentifier(osName).c_str()); for(i = 0; i < poFeatureDefn->GetFieldCount(); i++) { if( eDeferedInsertState != INSERT_MULTIPLE_FEATURE && !poFeature->IsFieldSet(i) ) continue; if( bMustComma ) osSQL += ", "; else { osSQL += "("; bMustComma = TRUE; } osSQL += OGRCARTODBEscapeIdentifier(poFeatureDefn->GetFieldDefn(i)->GetNameRef()); } for(i = 0; i < poFeatureDefn->GetGeomFieldCount(); i++) { if( eDeferedInsertState != INSERT_MULTIPLE_FEATURE && poFeature->GetGeomFieldRef(i) == NULL ) continue; if( bMustComma ) osSQL += ", "; else { osSQL += "("; bMustComma = TRUE; } osSQL += OGRCARTODBEscapeIdentifier(poFeatureDefn->GetGeomFieldDefn(i)->GetNameRef()); } if( !bHasUserFieldMatchingFID && osFIDColName.size() && (poFeature->GetFID() != OGRNullFID || (nNextFID >= 0 && bHasJustGotNextFID)) ) { if( bMustComma ) osSQL += ", "; else { osSQL += "("; bMustComma = TRUE; } osSQL += OGRCARTODBEscapeIdentifier(osFIDColName); } if( !bMustComma && eDeferedInsertState == INSERT_MULTIPLE_FEATURE ) eDeferedInsertState = INSERT_SINGLE_FEATURE; } if( !bMustComma && eDeferedInsertState == INSERT_SINGLE_FEATURE ) osSQL += "DEFAULT VALUES"; else { if( !bWriteInsertInto && eDeferedInsertState == INSERT_MULTIPLE_FEATURE ) osSQL += ", ("; else osSQL += ") VALUES ("; bMustComma = FALSE; for(i = 0; i < poFeatureDefn->GetFieldCount(); i++) { if( !poFeature->IsFieldSet(i) ) { if( eDeferedInsertState == INSERT_MULTIPLE_FEATURE ) { if( bMustComma ) osSQL += ", "; else bMustComma = TRUE; osSQL += "NULL"; } continue; } if( bMustComma ) osSQL += ", "; else bMustComma = TRUE; OGRFieldType eType = poFeatureDefn->GetFieldDefn(i)->GetType(); if( eType == OFTString || eType == OFTDateTime || eType == OFTDate || eType == OFTTime ) { osSQL += "'"; osSQL += OGRCARTODBEscapeLiteral(poFeature->GetFieldAsString(i)); osSQL += "'"; } else if( (eType == OFTInteger || eType == OFTInteger64) && poFeatureDefn->GetFieldDefn(i)->GetSubType() == OFSTBoolean ) { osSQL += poFeature->GetFieldAsInteger(i) ? "'t'" : "'f'"; } else osSQL += poFeature->GetFieldAsString(i); } for(i = 0; i < poFeatureDefn->GetGeomFieldCount(); i++) { OGRGeometry* poGeom = poFeature->GetGeomFieldRef(i); if( poGeom == NULL ) { if( eDeferedInsertState == INSERT_MULTIPLE_FEATURE ) { if( bMustComma ) osSQL += ", "; else bMustComma = TRUE; osSQL += "NULL"; } continue; } if( bMustComma ) osSQL += ", "; else bMustComma = TRUE; OGRCartoDBGeomFieldDefn* poGeomFieldDefn = (OGRCartoDBGeomFieldDefn *)poFeatureDefn->GetGeomFieldDefn(i); int nSRID = poGeomFieldDefn->nSRID; if( nSRID == 0 ) nSRID = 4326; char* pszEWKB; if( wkbFlatten(poGeom->getGeometryType()) == wkbPolygon && wkbFlatten(GetGeomType()) == wkbMultiPolygon ) { OGRMultiPolygon* poNewGeom = new OGRMultiPolygon(); poNewGeom->addGeometry(poGeom); pszEWKB = OGRGeometryToHexEWKB(poNewGeom, nSRID, poDS->GetPostGISMajor(), poDS->GetPostGISMinor()); delete poNewGeom; } else pszEWKB = OGRGeometryToHexEWKB(poGeom, nSRID, poDS->GetPostGISMajor(), poDS->GetPostGISMinor()); osSQL += "'"; osSQL += pszEWKB; osSQL += "'"; CPLFree(pszEWKB); } if( !bHasUserFieldMatchingFID ) { if( osFIDColName.size() && nNextFID >= 0 ) { if( bHasJustGotNextFID ) { if( bMustComma ) osSQL += ", "; else bMustComma = TRUE; osSQL += CPLSPrintf(CPL_FRMT_GIB, nNextFID); } } else if( osFIDColName.size() && poFeature->GetFID() != OGRNullFID ) { if( bMustComma ) osSQL += ", "; else bMustComma = TRUE; osSQL += CPLSPrintf(CPL_FRMT_GIB, poFeature->GetFID()); } } osSQL += ")"; } CPL_IGNORE_RET_VAL(bMustComma); if( !bHasUserFieldMatchingFID && osFIDColName.size() && nNextFID >= 0 ) { poFeature->SetFID(nNextFID); nNextFID ++; } if( bInDeferedInsert ) { OGRErr eRet = OGRERR_NONE; if( eDeferedInsertState == INSERT_SINGLE_FEATURE && /* in multiple mode, this would require rebuilding the osSQL buffer. Annoying... */ osDeferedInsertSQL.size() != 0 && (int)osDeferedInsertSQL.size() + (int)osSQL.size() > nMaxChunkSize ) { eRet = FlushDeferedInsert(false); } osDeferedInsertSQL += osSQL; if( eDeferedInsertState == INSERT_SINGLE_FEATURE ) osDeferedInsertSQL += ";"; if( (int)osDeferedInsertSQL.size() > nMaxChunkSize ) { eRet = FlushDeferedInsert(false); } if( bResetToUninitInsertStateAfterwards ) eDeferedInsertState = INSERT_UNINIT; return eRet; } if( osFIDColName.size() ) { osSQL += " RETURNING "; osSQL += OGRCARTODBEscapeIdentifier(osFIDColName); json_object* poObj = poDS->RunSQL(osSQL); json_object* poRowObj = OGRCARTODBGetSingleRow(poObj); if( poRowObj == NULL ) { if( poObj != NULL ) json_object_put(poObj); return OGRERR_FAILURE; } json_object* poID = json_object_object_get(poRowObj, osFIDColName); if( poID != NULL && json_object_get_type(poID) == json_type_int ) { poFeature->SetFID(json_object_get_int64(poID)); } if( poObj != NULL ) json_object_put(poObj); return OGRERR_NONE; } else { OGRErr eRet = OGRERR_FAILURE; json_object* poObj = poDS->RunSQL(osSQL); if( poObj != NULL ) { json_object* poTotalRows = json_object_object_get(poObj, "total_rows"); if( poTotalRows != NULL && json_object_get_type(poTotalRows) == json_type_int ) { int nTotalRows = json_object_get_int(poTotalRows); if( nTotalRows == 1 ) { eRet = OGRERR_NONE; } } json_object_put(poObj); } return eRet; } } /************************************************************************/ /* ISetFeature() */ /************************************************************************/ OGRErr OGRCARTODBTableLayer::ISetFeature( OGRFeature *poFeature ) { if( bDeferedCreation && RunDeferedCreationIfNecessary() != OGRERR_NONE ) return OGRERR_FAILURE; if( FlushDeferedInsert() != OGRERR_NONE ) return OGRERR_FAILURE; GetLayerDefn(); if (!poDS->IsReadWrite()) { CPLError(CE_Failure, CPLE_AppDefined, "Operation not available in read-only mode"); return OGRERR_FAILURE; } if (poFeature->GetFID() == OGRNullFID) { CPLError( CE_Failure, CPLE_AppDefined, "FID required on features given to SetFeature()." ); return OGRERR_FAILURE; } CPLString osSQL; osSQL.Printf("UPDATE %s SET ", OGRCARTODBEscapeIdentifier(osName).c_str()); int bMustComma = FALSE; for( int i = 0; i < poFeatureDefn->GetFieldCount(); i++ ) { if( bMustComma ) osSQL += ", "; else bMustComma = TRUE; osSQL += OGRCARTODBEscapeIdentifier(poFeatureDefn->GetFieldDefn(i)->GetNameRef()); osSQL += " = "; if( !poFeature->IsFieldSet(i) ) { osSQL += "NULL"; } else { OGRFieldType eType = poFeatureDefn->GetFieldDefn(i)->GetType(); if( eType == OFTString || eType == OFTDateTime || eType == OFTDate || eType == OFTTime ) { osSQL += "'"; osSQL += OGRCARTODBEscapeLiteral(poFeature->GetFieldAsString(i)); osSQL += "'"; } else if( (eType == OFTInteger || eType == OFTInteger64) && poFeatureDefn->GetFieldDefn(i)->GetSubType() == OFSTBoolean ) { osSQL += poFeature->GetFieldAsInteger(i) ? "'t'" : "'f'"; } else osSQL += poFeature->GetFieldAsString(i); } } for( int i = 0; i < poFeatureDefn->GetGeomFieldCount(); i++ ) { if( bMustComma ) osSQL += ", "; else bMustComma = TRUE; osSQL += OGRCARTODBEscapeIdentifier(poFeatureDefn->GetGeomFieldDefn(i)->GetNameRef()); osSQL += " = "; OGRGeometry* poGeom = poFeature->GetGeomFieldRef(i); if( poGeom == NULL ) { osSQL += "NULL"; } else { OGRCartoDBGeomFieldDefn* poGeomFieldDefn = (OGRCartoDBGeomFieldDefn *)poFeatureDefn->GetGeomFieldDefn(i); int nSRID = poGeomFieldDefn->nSRID; if( nSRID == 0 ) nSRID = 4326; char* pszEWKB = OGRGeometryToHexEWKB(poGeom, nSRID, poDS->GetPostGISMajor(), poDS->GetPostGISMinor()); osSQL += "'"; osSQL += pszEWKB; osSQL += "'"; CPLFree(pszEWKB); } } osSQL += CPLSPrintf(" WHERE %s = " CPL_FRMT_GIB, OGRCARTODBEscapeIdentifier(osFIDColName).c_str(), poFeature->GetFID()); OGRErr eRet = OGRERR_FAILURE; json_object* poObj = poDS->RunSQL(osSQL); if( poObj != NULL ) { json_object* poTotalRows = json_object_object_get(poObj, "total_rows"); if( poTotalRows != NULL && json_object_get_type(poTotalRows) == json_type_int ) { int nTotalRows = json_object_get_int(poTotalRows); if( nTotalRows > 0 ) { eRet = OGRERR_NONE; } else eRet = OGRERR_NON_EXISTING_FEATURE; } json_object_put(poObj); } return eRet; } /************************************************************************/ /* DeleteFeature() */ /************************************************************************/ OGRErr OGRCARTODBTableLayer::DeleteFeature( GIntBig nFID ) { if( bDeferedCreation && RunDeferedCreationIfNecessary() != OGRERR_NONE ) return OGRERR_FAILURE; if( FlushDeferedInsert() != OGRERR_NONE ) return OGRERR_FAILURE; GetLayerDefn(); if (!poDS->IsReadWrite()) { CPLError(CE_Failure, CPLE_AppDefined, "Operation not available in read-only mode"); return OGRERR_FAILURE; } if( osFIDColName.size() == 0 ) return OGRERR_FAILURE; CPLString osSQL; osSQL.Printf("DELETE FROM %s WHERE %s = " CPL_FRMT_GIB, OGRCARTODBEscapeIdentifier(osName).c_str(), OGRCARTODBEscapeIdentifier(osFIDColName).c_str(), nFID); OGRErr eRet = OGRERR_FAILURE; json_object* poObj = poDS->RunSQL(osSQL); if( poObj != NULL ) { json_object* poTotalRows = json_object_object_get(poObj, "total_rows"); if( poTotalRows != NULL && json_object_get_type(poTotalRows) == json_type_int ) { int nTotalRows = json_object_get_int(poTotalRows); if( nTotalRows > 0 ) { eRet = OGRERR_NONE; } else eRet = OGRERR_NON_EXISTING_FEATURE; } json_object_put(poObj); } return eRet; } /************************************************************************/ /* GetSRS_SQL() */ /************************************************************************/ CPLString OGRCARTODBTableLayer::GetSRS_SQL(const char* pszGeomCol) { CPLString osSQL; osSQL.Printf("SELECT srid, srtext FROM spatial_ref_sys WHERE srid IN " "(SELECT Find_SRID('%s', '%s', '%s'))", OGRCARTODBEscapeLiteral(poDS->GetCurrentSchema()).c_str(), OGRCARTODBEscapeLiteral(osName).c_str(), OGRCARTODBEscapeLiteral(pszGeomCol).c_str()); return osSQL; } /************************************************************************/ /* BuildWhere() */ /* */ /* Build the WHERE statement appropriate to the current set of */ /* criteria (spatial and attribute queries). */ /************************************************************************/ void OGRCARTODBTableLayer::BuildWhere() { osWHERE = ""; if( m_poFilterGeom != NULL && m_iGeomFieldFilter >= 0 && m_iGeomFieldFilter < poFeatureDefn->GetGeomFieldCount() ) { OGREnvelope sEnvelope; m_poFilterGeom->getEnvelope( &sEnvelope ); CPLString osGeomColumn(poFeatureDefn->GetGeomFieldDefn(m_iGeomFieldFilter)->GetNameRef()); char szBox3D_1[128]; char szBox3D_2[128]; char* pszComma; CPLsnprintf(szBox3D_1, sizeof(szBox3D_1), "%.18g %.18g", sEnvelope.MinX, sEnvelope.MinY); while((pszComma = strchr(szBox3D_1, ',')) != NULL) *pszComma = '.'; CPLsnprintf(szBox3D_2, sizeof(szBox3D_2), "%.18g %.18g", sEnvelope.MaxX, sEnvelope.MaxY); while((pszComma = strchr(szBox3D_2, ',')) != NULL) *pszComma = '.'; osWHERE.Printf("(%s && 'BOX3D(%s, %s)'::box3d)", OGRCARTODBEscapeIdentifier(osGeomColumn).c_str(), szBox3D_1, szBox3D_2 ); } if( strlen(osQuery) > 0 ) { if( osWHERE.size() > 0 ) osWHERE += " AND "; osWHERE += osQuery; } if( osFIDColName.size() == 0 ) { osBaseSQL = osSELECTWithoutWHERE; if( osWHERE.size() ) { osBaseSQL += " WHERE "; osBaseSQL += osWHERE; } } } /************************************************************************/ /* GetFeature() */ /************************************************************************/ OGRFeature* OGRCARTODBTableLayer::GetFeature( GIntBig nFeatureId ) { if( bDeferedCreation && RunDeferedCreationIfNecessary() != OGRERR_NONE ) return NULL; if( FlushDeferedInsert() != OGRERR_NONE ) return NULL; GetLayerDefn(); if( osFIDColName.size() == 0 ) return OGRCARTODBLayer::GetFeature(nFeatureId); CPLString osSQL = osSELECTWithoutWHERE; osSQL += " WHERE "; osSQL += OGRCARTODBEscapeIdentifier(osFIDColName).c_str(); osSQL += " = "; osSQL += CPLSPrintf(CPL_FRMT_GIB, nFeatureId); json_object* poObj = poDS->RunSQL(osSQL); json_object* poRowObj = OGRCARTODBGetSingleRow(poObj); if( poRowObj == NULL ) { if( poObj != NULL ) json_object_put(poObj); return OGRCARTODBLayer::GetFeature(nFeatureId); } OGRFeature* poFeature = BuildFeature(poRowObj); json_object_put(poObj); return poFeature; } /************************************************************************/ /* GetFeatureCount() */ /************************************************************************/ GIntBig OGRCARTODBTableLayer::GetFeatureCount(int bForce) { if( bDeferedCreation && RunDeferedCreationIfNecessary() != OGRERR_NONE ) return 0; if( FlushDeferedInsert() != OGRERR_NONE ) return 0; GetLayerDefn(); CPLString osSQL(CPLSPrintf("SELECT COUNT(*) FROM %s", OGRCARTODBEscapeIdentifier(osName).c_str())); if( osWHERE.size() ) { osSQL += " WHERE "; osSQL += osWHERE; } json_object* poObj = poDS->RunSQL(osSQL); json_object* poRowObj = OGRCARTODBGetSingleRow(poObj); if( poRowObj == NULL ) { if( poObj != NULL ) json_object_put(poObj); return OGRCARTODBLayer::GetFeatureCount(bForce); } json_object* poCount = json_object_object_get(poRowObj, "count"); if( poCount == NULL || json_object_get_type(poCount) != json_type_int ) { json_object_put(poObj); return OGRCARTODBLayer::GetFeatureCount(bForce); } GIntBig nRet = (GIntBig)json_object_get_int64(poCount); json_object_put(poObj); return nRet; } /************************************************************************/ /* GetExtent() */ /* */ /* For PostGIS use internal Extend(geometry) function */ /* in other cases we use standard OGRLayer::GetExtent() */ /************************************************************************/ OGRErr OGRCARTODBTableLayer::GetExtent( int iGeomField, OGREnvelope *psExtent, int bForce ) { CPLString osSQL; if( bDeferedCreation && RunDeferedCreationIfNecessary() != OGRERR_NONE ) return OGRERR_FAILURE; if( FlushDeferedInsert() != OGRERR_NONE ) return OGRERR_FAILURE; if( iGeomField < 0 || iGeomField >= GetLayerDefn()->GetGeomFieldCount() || GetLayerDefn()->GetGeomFieldDefn(iGeomField)->GetType() == wkbNone ) { if( iGeomField != 0 ) { CPLError(CE_Failure, CPLE_AppDefined, "Invalid geometry field index : %d", iGeomField); } return OGRERR_FAILURE; } OGRGeomFieldDefn* poGeomFieldDefn = poFeatureDefn->GetGeomFieldDefn(iGeomField); /* Do not take the spatial filter into account */ osSQL.Printf( "SELECT ST_Extent(%s) FROM %s", OGRCARTODBEscapeIdentifier(poGeomFieldDefn->GetNameRef()).c_str(), OGRCARTODBEscapeIdentifier(osName).c_str()); json_object* poObj = poDS->RunSQL(osSQL); json_object* poRowObj = OGRCARTODBGetSingleRow(poObj); if( poRowObj != NULL ) { json_object* poExtent = json_object_object_get(poRowObj, "st_extent"); if( poExtent != NULL && json_object_get_type(poExtent) == json_type_string ) { const char* pszBox = json_object_get_string(poExtent); const char * ptr, *ptrEndParenthesis; char szVals[64*6+6]; ptr = strchr(pszBox, '('); if (ptr) ptr ++; if (ptr == NULL || (ptrEndParenthesis = strchr(ptr, ')')) == NULL || ptrEndParenthesis - ptr > (int)(sizeof(szVals) - 1)) { CPLError( CE_Failure, CPLE_IllegalArg, "Bad extent representation: '%s'", pszBox); json_object_put(poObj); return OGRERR_FAILURE; } strncpy(szVals,ptr,ptrEndParenthesis - ptr); szVals[ptrEndParenthesis - ptr] = '\0'; char ** papszTokens = CSLTokenizeString2(szVals," ,",CSLT_HONOURSTRINGS); int nTokenCnt = 4; if ( CSLCount(papszTokens) != nTokenCnt ) { CPLError( CE_Failure, CPLE_IllegalArg, "Bad extent representation: '%s'", pszBox); CSLDestroy(papszTokens); json_object_put(poObj); return OGRERR_FAILURE; } // Take X,Y coords // For PostGIS ver >= 1.0.0 -> Tokens: X1 Y1 X2 Y2 (nTokenCnt = 4) // For PostGIS ver < 1.0.0 -> Tokens: X1 Y1 Z1 X2 Y2 Z2 (nTokenCnt = 6) // => X2 index calculated as nTokenCnt/2 // Y2 index calculated as nTokenCnt/2+1 psExtent->MinX = CPLAtof( papszTokens[0] ); psExtent->MinY = CPLAtof( papszTokens[1] ); psExtent->MaxX = CPLAtof( papszTokens[nTokenCnt/2] ); psExtent->MaxY = CPLAtof( papszTokens[nTokenCnt/2+1] ); CSLDestroy(papszTokens); json_object_put(poObj); return OGRERR_NONE; } } if( poObj != NULL ) json_object_put(poObj); if( iGeomField == 0 ) return OGRLayer::GetExtent( psExtent, bForce ); else return OGRLayer::GetExtent( iGeomField, psExtent, bForce ); } /************************************************************************/ /* TestCapability() */ /************************************************************************/ int OGRCARTODBTableLayer::TestCapability( const char * pszCap ) { if( EQUAL(pszCap, OLCFastFeatureCount) ) return TRUE; if( EQUAL(pszCap, OLCFastGetExtent) ) return TRUE; if( EQUAL(pszCap, OLCRandomRead) ) { GetLayerDefn(); return osFIDColName.size() != 0; } if( EQUAL(pszCap,OLCSequentialWrite) || EQUAL(pszCap,OLCRandomWrite) || EQUAL(pszCap,OLCDeleteFeature) || EQUAL(pszCap,OLCCreateField) || EQUAL(pszCap,OLCDeleteField) ) { return poDS->IsReadWrite(); } return OGRCARTODBLayer::TestCapability(pszCap); } /************************************************************************/ /* SetDeferedCreation() */ /************************************************************************/ void OGRCARTODBTableLayer::SetDeferedCreation (OGRwkbGeometryType eGType, OGRSpatialReference* poSRSIn, int bGeomNullable, int bCartoDBifyIn) { bDeferedCreation = TRUE; nNextFID = 1; CPLAssert(poFeatureDefn == NULL); this->bCartoDBify = bCartoDBifyIn; poFeatureDefn = new OGRFeatureDefn(osName); poFeatureDefn->Reference(); poFeatureDefn->SetGeomType(wkbNone); if( eGType == wkbPolygon ) eGType = wkbMultiPolygon; else if( eGType == wkbPolygon25D ) eGType = wkbMultiPolygon25D; if( eGType != wkbNone ) { OGRCartoDBGeomFieldDefn *poFieldDefn = new OGRCartoDBGeomFieldDefn("the_geom", eGType); poFieldDefn->SetNullable(bGeomNullable); poFeatureDefn->AddGeomFieldDefn(poFieldDefn, FALSE); if( poSRSIn != NULL ) { poFieldDefn->nSRID = poDS->FetchSRSId( poSRSIn ); poFeatureDefn->GetGeomFieldDefn( poFeatureDefn->GetGeomFieldCount() - 1)->SetSpatialRef(poSRSIn); } } osFIDColName = "cartodb_id"; osBaseSQL.Printf("SELECT * FROM %s", OGRCARTODBEscapeIdentifier(osName).c_str()); osSELECTWithoutWHERE = osBaseSQL; } /************************************************************************/ /* RunDeferedCreationIfNecessary() */ /************************************************************************/ OGRErr OGRCARTODBTableLayer::RunDeferedCreationIfNecessary() { if( !bDeferedCreation ) return OGRERR_NONE; bDeferedCreation = FALSE; CPLString osSQL; osSQL.Printf("CREATE TABLE %s ( %s SERIAL,", OGRCARTODBEscapeIdentifier(osName).c_str(), osFIDColName.c_str()); int nSRID = 0; OGRwkbGeometryType eGType = GetGeomType(); if( eGType != wkbNone ) { CPLString osGeomType = OGRToOGCGeomType(eGType); if( wkbHasZ(eGType) ) osGeomType += "Z"; OGRCartoDBGeomFieldDefn *poFieldDefn = (OGRCartoDBGeomFieldDefn *)poFeatureDefn->GetGeomFieldDefn(0); nSRID = poFieldDefn->nSRID; osSQL += CPLSPrintf("%s GEOMETRY(%s, %d)%s, %s GEOMETRY(%s, %d),", "the_geom", osGeomType.c_str(), nSRID, (!poFieldDefn->IsNullable()) ? " NOT NULL" : "", "the_geom_webmercator", osGeomType.c_str(), 3857); } for( int i = 0; i < poFeatureDefn->GetFieldCount(); i++ ) { OGRFieldDefn* poFieldDefn = poFeatureDefn->GetFieldDefn(i); if( strcmp(poFieldDefn->GetNameRef(), osFIDColName) != 0 ) { osSQL += OGRCARTODBEscapeIdentifier(poFieldDefn->GetNameRef()); osSQL += " "; osSQL += OGRPGCommonLayerGetType(*poFieldDefn, FALSE, TRUE); if( !poFieldDefn->IsNullable() ) osSQL += " NOT NULL"; if( poFieldDefn->GetDefault() != NULL && !poFieldDefn->IsDefaultDriverSpecific() ) { osSQL += " DEFAULT "; osSQL += poFieldDefn->GetDefault(); } osSQL += ","; } } osSQL += CPLSPrintf("PRIMARY KEY (%s) )", osFIDColName.c_str()); CPLString osSeqName(OGRCARTODBEscapeIdentifier(CPLSPrintf("%s_%s_seq", osName.c_str(), osFIDColName.c_str()))); osSQL += ";"; osSQL += CPLSPrintf("DROP SEQUENCE IF EXISTS %s CASCADE", osSeqName.c_str()); osSQL += ";"; osSQL += CPLSPrintf("CREATE SEQUENCE %s START 1", osSeqName.c_str()); osSQL += ";"; osSQL += CPLSPrintf("ALTER TABLE %s ALTER COLUMN %s SET DEFAULT nextval('%s')", OGRCARTODBEscapeIdentifier(osName).c_str(), osFIDColName.c_str(), osSeqName.c_str()); json_object* poObj = poDS->RunSQL(osSQL); if( poObj == NULL ) return OGRERR_FAILURE; json_object_put(poObj); return OGRERR_NONE; } 0 /* * AggregatedDensity.cpp * * Copyright (C) 2011 by Universitaet Stuttgart (VISUS). * Alle Rechte vorbehalten. */ #include "AggregatedDensity.h" #include "geometry_calls/VolumetricDataCall.h" #include "mmcore/AbstractGetData3DCall.h" #include #include #include #include #include #include #include #define _USE_MATH_DEFINES 1 /* * megamol::protein::AggregatedDensity::AggregatedDensity */ megamol::protein::AggregatedDensity::AggregatedDensity(void) : getDensitySlot("sendAggregatedDensity", "Sends the aggrated density data") , getZvelocitySlot("sendAggregatedZvelocity", "Sends the aggrated velocity data") , is_aggregated(false) , framecounter(0) , molDataCallerSlot("getMolecularData", "Connects the aggregation with molecule data storage") { this->getDensitySlot.SetCallback("VolumetricDataCall", "getData", &AggregatedDensity::getDensityCallback); this->getDensitySlot.SetCallback("VolumetricDataCall", "getExtent", &AggregatedDensity::getExtentCallback); this->MakeSlotAvailable(&this->getDensitySlot); this->getZvelocitySlot.SetCallback("VolumetricDataCall", "getData", &AggregatedDensity::getZvelocityCallback); this->getZvelocitySlot.SetCallback("VolumetricDataCall", "getExtent", &AggregatedDensity::getExtentCallback); this->MakeSlotAvailable(&this->getZvelocitySlot); this->molDataCallerSlot.SetCompatibleCall(); this->MakeSlotAvailable(&this->molDataCallerSlot); pdbfilename = "K.pdb"; xtcfilenames.push_back("K.xtc"); origin_x = 50; origin_y = 50; origin_z = 00; box_x = 50.; box_y = 50.; box_z = 50.; res = 1.; xbins = static_cast(ceil(box_x / res)); ybins = static_cast(ceil(box_y / res)); zbins = static_cast(ceil(box_z / res)); density = new float[xbins * ybins * zbins]; velocity = new float[3 * xbins * ybins * zbins]; memset(density, 0, xbins * ybins * zbins * sizeof(float)); memset(velocity, 0, 3 * xbins * ybins * zbins * sizeof(float)); } /* * megamol::protein::AggregatedDensity::~AggregatedDensity */ megamol::protein::AggregatedDensity::~AggregatedDensity(void) {} /* * megamol::protein::AggregatedDensity::create */ bool megamol::protein::AggregatedDensity::create(void) { return true; } /* * megamol::protein::AggregatedDensity::release */ void megamol::protein::AggregatedDensity::release(void) { ARY_SAFE_DELETE(this->vol); } /* * megamol::protein::AggregatedDensity::getDataCallback */ bool megamol::protein::AggregatedDensity::getDensityCallback(megamol::core::Call& caller) { geocalls::VolumetricDataCall* cvd = dynamic_cast(&caller); if (cvd == NULL) return false; if (!this->is_aggregated) if (!this->aggregate()) return false; //#pragma omp parallel for cvd->SetDataHash(1); cvd->SetFrameID(0); auto metadata = std::make_shared(); metadata->Resolution[0] = xbins; metadata->Resolution[1] = ybins; metadata->Resolution[2] = zbins; metadata->ScalarType = geocalls::VolumetricDataCall::ScalarType::FLOATING_POINT; cvd->SetMetadata(metadata.get()); cvd->SetData(this->density); return true; } /* * megamol::protein::AggregatedDensity::getDataCallback */ bool megamol::protein::AggregatedDensity::getZvelocityCallback(megamol::core::Call& caller) { geocalls::VolumetricDataCall* cvd = dynamic_cast(&caller); if (cvd == NULL) return false; if (!this->is_aggregated) if (!this->aggregate()) return false; //#pragma omp parallel for cvd->SetDataHash(1); cvd->SetFrameID(0); auto metadata = std::make_shared(); metadata->Resolution[0] = xbins; metadata->Resolution[1] = ybins; metadata->Resolution[2] = zbins; metadata->ScalarType = geocalls::VolumetricDataCall::ScalarType::FLOATING_POINT; cvd->SetMetadata(metadata.get()); cvd->SetData(this->velocity); return true; } /* * megamol::protein::AggregatedDensity::getExtentCallback */ bool megamol::protein::AggregatedDensity::getExtentCallback(megamol::core::Call& caller) { geocalls::VolumetricDataCall* cvd = dynamic_cast(&caller); if (cvd == NULL) return false; cvd->AccessBoundingBoxes().Clear(); cvd->AccessBoundingBoxes().SetObjectSpaceBBox( origin_x, origin_y, origin_z, origin_x + box_x, origin_y + box_y, origin_z + box_z); cvd->SetDataHash(1); cvd->SetFrameCount(1); return true; } bool megamol::protein::AggregatedDensity::aggregate() { megamol::protein_calls::MolecularDataCall* mol = this->molDataCallerSlot.CallAs(); if (!mol) { return false; } // set call time mol->SetCalltime(0); // set frame ID and call data mol->SetFrameID(0); if (!(*mol)(megamol::protein_calls::MolecularDataCall::CallForGetData)) return false; // this number must remain constant! unsigned int n_atoms = mol->AtomCount(); float* pos0 = new float[mol->AtomCount() * 3]; float* vel = new float[mol->AtomCount() * 3]; memcpy(pos0, mol->AtomPositions(), mol->AtomCount() * 3 * sizeof(float)); for (unsigned int frame = 0; frame < mol->FrameCount(); frame++) { mol->SetFrameID(frame); if (!(*mol)(megamol::protein_calls::MolecularDataCall::CallForGetData)) return false; if (mol->AtomCount() != n_atoms) { delete[] pos0, vel; return false; } const float* pos_new = mol->AtomPositions(); for (unsigned int i = 0; i < 3 * n_atoms; i++) { vel[i] = pos_new[i] - pos0[i]; } memcpy(pos0, mol->AtomPositions(), mol->AtomCount() * 3 * sizeof(float)); this->aggregate_frame(pos0, vel, n_atoms); framecounter++; } delete[] pos0, vel; is_aggregated = true; float maxdensity = 0; float minvelocity = FLT_MAX; float maxvelocity = FLT_MIN; for (unsigned int i = 0; i < xbins * ybins * zbins; i++) { density[i] *= 1.0f / framecounter / res / res / res * 1000.0f; if (density[i] > 0) { velocity[i] *= 1.0f / density[i] / framecounter; } else { velocity[i] = 0; } maxdensity = vislib::math::Max(density[i], maxdensity); maxvelocity = vislib::math::Max(velocity[i], maxvelocity); minvelocity = vislib::math::Min(velocity[i], minvelocity); } std::cout << "The max is " << maxdensity << std::endl; std::cout << "The max vel is " << maxvelocity << std::endl; std::cout << "The min vel is " << minvelocity << std::endl; return true; } bool megamol::protein::AggregatedDensity::aggregate_frame(float* pos, float* vel, unsigned int n_atoms) { float x, y, z, dx, dy, dz; unsigned int X, Y, Z; float weight; unsigned int linear_index; for (unsigned int i = 0; i < 3 * n_atoms; i++) { x = (pos[3 * i + 0] - origin_x) / res; // in lattice constants X = static_cast(floor(x)); dx = x - X; y = (pos[3 * i + 1] - origin_y) / res; // in lattice constants Y = static_cast(floor(y)); dy = y - Y; z = (pos[3 * i + 2] - origin_z) / res; // in lattice constants Z = static_cast(floor(z)); dz = z - Z; if (X > 0 && X < xbins - 1 && Y > 0 && Y < ybins - 1 && Z > 0 && Z < zbins - 1) { //weight=1; //density[X+xbins*Y+xbins*ybins*Z]+=weight; weight = (1 - dx) * (1 - dy) * (1 - dz); linear_index = (X + 0) + (Y + 0) * xbins + (Z + 0) * xbins * ybins; density[linear_index] += weight; velocity[3 * linear_index + 0] += weight * vel[3 * i + 0]; velocity[3 * linear_index + 1] += weight * vel[3 * i + 1]; velocity[3 * linear_index + 2] += weight * vel[3 * i + 2]; weight = (1 - dx) * (1 - dy) * (dz); linear_index = (X + 0) + (Y + 0) * xbins + (Z + 1) * xbins * ybins; density[linear_index] += weight; velocity[3 * linear_index + 0] += weight * vel[3 * i + 0]; velocity[3 * linear_index + 1] += weight * vel[3 * i + 1]; velocity[3 * linear_index + 2] += weight * vel[3 * i + 2]; weight = (1 - dx) * (dy) * (1 - dz); linear_index = (X + 0) + (Y + 1) * xbins + (Z + 0) * xbins * ybins; density[linear_index] += weight; velocity[3 * linear_index + 0] += weight * vel[3 * i + 0]; velocity[3 * linear_index + 1] += weight * vel[3 * i + 1]; velocity[3 * linear_index + 2] += weight * vel[3 * i + 2]; weight = (1 - dx) * (dy) * (dz); linear_index = (X + 0) + (Y + 1) * xbins + (Z + 1) * xbins * ybins; density[linear_index] += weight; velocity[3 * linear_index + 0] += weight * vel[3 * i + 0]; velocity[3 * linear_index + 1] += weight * vel[3 * i + 1]; velocity[3 * linear_index + 2] += weight * vel[3 * i + 2]; weight = (dx) * (1 - dy) * (1 - dz); linear_index = (X + 1) + (Y + 0) * xbins + (Z + 0) * xbins * ybins; density[linear_index] += weight; velocity[3 * linear_index + 0] += weight * vel[3 * i + 0]; velocity[3 * linear_index + 1] += weight * vel[3 * i + 1]; velocity[3 * linear_index + 2] += weight * vel[3 * i + 2]; weight = (dx) * (1 - dy) * (dz); linear_index = (X + 1) + (Y + 0) * xbins + (Z + 1) * xbins * ybins; density[linear_index] += weight; velocity[3 * linear_index + 0] += weight * vel[3 * i + 0]; velocity[3 * linear_index + 1] += weight * vel[3 * i + 1]; velocity[3 * linear_index + 2] += weight * vel[3 * i + 2]; weight = (dx) * (dy) * (1 - dz); linear_index = (X + 1) + (Y + 1) * xbins + (Z + 0) * xbins * ybins; density[linear_index] += weight; velocity[3 * linear_index + 0] += weight * vel[3 * i + 0]; velocity[3 * linear_index + 1] += weight * vel[3 * i + 1]; velocity[3 * linear_index + 2] += weight * vel[3 * i + 2]; weight = (dx) * (dy) * (dz); linear_index = (X + 1) + (Y + 1) * xbins + (Z + 1) * xbins * ybins; density[linear_index] += weight; velocity[3 * linear_index + 0] += weight * vel[3 * i + 0]; velocity[3 * linear_index + 1] += weight * vel[3 * i + 1]; velocity[3 * linear_index + 2] += weight * vel[3 * i + 2]; } } return true; } examples/slight_RotaryEncoder__advanced2/myinput.cpp // NOLINT(legal/copyright) /****************************************************************************** some description... libraries used: ~ slight_RotaryEncoder written by (s-light), , http://s-light.eu, https://github.com/s-light/ license: MIT written by (s-light), , http://s-light.eu, https://github.com/s-light/ ******************************************************************************/ /****************************************************************************** The MIT License (MIT) 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 Core Arduino functionality #include #include // include own headerfile // NOLINTNEXTLINE(build/include) #include "./myinput.h" // this polluts the global namespace.. // using namespace std::placeholders; // for `_1` // so we use std::placeholders::_1 // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // functions // MyInput::MyInput(Stream &out): out(out) { MyInput::MyInput() { ready = false; } MyInput::~MyInput() { end(); } void MyInput::begin(Stream &out, slight_RotaryEncoder::tCallbackFunctionISR funcISR) { // clean up.. end(); // start up... if (ready == false) { // setup out.println("MyInput begin:"); out.println(" myencoder.begin"); myencoder.begin(funcISR); out.println("done:"); // enable ready = true; } } void MyInput::end() { if (ready) { // nothing to do.. } } void MyInput::update() { if (ready) { myencoder.update(); if (counter != counter_last) { counter_last = counter; Serial.print("counter changed: "); Serial.print(counter); Serial.println(); } } } // ------------------------------------------ // slight_RotaryEncoder things void MyInput::myencoder_event(slight_RotaryEncoder *instance) { Serial.print(F("instance:")); Serial.print((*instance).id); Serial.print(F(" - event: ")); (*instance).printEventLast(Serial); Serial.println(); // react on event switch ((*instance).getEventLast()) { case slight_RotaryEncoder::event_StateChanged : { Serial.print(F("\t state: ")); (*instance).printState(Serial); Serial.println(); } break; // rotation case slight_RotaryEncoder::event_Rotated : { // get current data int16_t temp_steps = (*instance).getSteps(); int16_t temp_stepsAccel = (*instance).getStepsAccelerated(); // clear data (*instance).clearSteps(); Serial.print(F(" steps: ")); Serial.println(temp_steps); Serial.print(F(" steps accelerated: ")); Serial.println(temp_stepsAccel); counter += temp_stepsAccel; } break; // currently there are no other events fired. } // end switch } // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // THE END // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. #include #include "trace.h" #include "pal.h" #include "utils.h" #include "fx_ver.h" #include "fx_muxer.h" #include "error_codes.h" #include "libhost.h" #include "runtime_config.h" typedef int(*corehost_load_fn) (const host_interface_t* init); typedef int(*corehost_main_fn) (const int argc, const pal::char_t* argv[]); typedef int(*corehost_unload_fn) (); int load_host_library( const pal::string_t& lib_dir, pal::dll_t* h_host, corehost_load_fn* load_fn, corehost_main_fn* main_fn, corehost_unload_fn* unload_fn) { pal::string_t host_path; if (!library_exists_in_dir(lib_dir, LIBHOSTPOLICY_NAME, &host_path)) { return StatusCode::CoreHostLibMissingFailure; } // Load library if (!pal::load_library(host_path.c_str(), h_host)) { trace::info(_X("Load library of %s failed"), host_path.c_str()); return StatusCode::CoreHostLibLoadFailure; } // Obtain entrypoint symbols *load_fn = (corehost_load_fn)pal::get_symbol(*h_host, "corehost_load"); *main_fn = (corehost_main_fn)pal::get_symbol(*h_host, "corehost_main"); *unload_fn = (corehost_unload_fn)pal::get_symbol(*h_host, "corehost_unload"); return (*main_fn) && (*load_fn) && (*unload_fn) ? StatusCode::Success : StatusCode::CoreHostEntryPointFailure; } int execute_app( const pal::string_t& impl_dll_dir, corehost_init_t* init, const int argc, const pal::char_t* argv[]) { pal::dll_t corehost; corehost_main_fn host_main = nullptr; corehost_load_fn host_load = nullptr; corehost_unload_fn host_unload = nullptr; int code = load_host_library(impl_dll_dir, &corehost, &host_load, &host_main, &host_unload); if (code != StatusCode::Success) { trace::error(_X("An error occurred while loading required library %s from [%s]"), LIBHOSTPOLICY_NAME, impl_dll_dir.c_str()); return code; } const host_interface_t& intf = init->get_host_init_data(); if ((code = host_load(&intf)) == 0) { code = host_main(argc, argv); (void)host_unload(); } pal::unload_library(corehost); return code; } static char sccsid[] = "@(#)" \ HOST_PKG_VER \ "; Commit Hash: " \ REPO_COMMIT_HASH \ "; Built on: " \ __DATE__ \ " " \ __TIME__ \ ; SHARED_API int hostfxr_main(const int argc, const pal::char_t* argv[]) { trace::setup(); trace::info(_X("--- Invoked hostfxr [commit hash: %s] main"), _STRINGIFY(REPO_COMMIT_HASH)); fx_muxer_t muxer; return muxer.execute(argc, argv); } #include "XEngine.h" #include bool XEngine::Init() { videoSize = sf::Vector2u{512, 384}; window = new sf::RenderWindow{{videoSize.x, videoSize.y}, "Xici"}; window->setFramerateLimit(30); // Init script if (!g_XLua.Init()) { return false; } if (!m_pFont.loadFromFile("data/pkmnfl.ttf")) return false; if (!m_pBattle->Init(window->getDefaultView())) return false; if (!m_pSprites.LoadPokemon()) return false; m_pWriter.init("Init...", m_pFont, 16, 0.025); m_pWriter.setPosition({17, 316}); if (!window) return false; std::unique_ptr npc{new XNPC(sf::Vector2f(5, 2))}; m_vNPC.push_back(std::move(npc)); m_pSprites.LoadTexture("data/textskin.png", MENU_FRAME); // Init the other classes m_pMap->Init(); m_pMap->LoadMapFromFile("data/map.xmap", 0, 0); m_pMap->LoadMapFromFile("data/map.xmap", 640, 0); m_pMap->LoadMapFromFile("data/map.xmap", 640, 640); m_pMap->LoadMapFromFile("data/map.xmap", 0, 640); m_pMap->LoadMapFromFile("data/map.xmap", -640, 0); m_pMap->LoadMapFromFile("data/map.xmap", -640, -640); m_pMap->LoadMapFromFile("data/map.xmap", 0, -640); m_pPlayer->Init({videoSize.x / 2.0f, videoSize.y / 2.0f}, window->getDefaultView()); m_pPlayer->SetRelativePosition({-4, 0}); m_pState = m_pPlayer.get(); srand((uint) time(NULL)); return true; } void XEngine::Go() { if (!Init()) throw "Could not initialize Engine"; MainLoop(); } void XEngine::MainLoop() { //Loop until our window is closed while (window->isOpen()) { window->clear(sf::Color::Black); m_pState->Input(deltaTime); m_pState->Render(window, deltaTime); m_pState->Update(deltaTime); WindowEvents(); deltaTime = m_pClock.restart().asSeconds(); window->display(); } } int XEngine::rdmtest(int i) { switch (i) { case 0: return POKEMON_BEGIN; case 1: return POKEMON_SHINY_BEGIN; case 2: return POKEMON_BACK_BEGIN; case 3: return POKEMON_SHINY_BACK_BEGIN; default: return POKEMON_BACK_BEGIN; } } void XEngine::WindowEvents() { sf::Event evt; while (window->pollEvent(evt)) { if (evt.type == sf::Event::Closed) window->close(); if (evt.type == sf::Event::KeyPressed) { if (evt.key.code == sf::Keyboard::C) { Objects::Pokemon player(rand() % 151 + 1, rdmtest(rand() % 2 + 2)); Objects::Pokemon enemy(rand() % 151 + 1, rdmtest(rand() % 2)); m_pBattle->InitBattle(player, enemy); m_pState = m_pBattle.get(); } if (evt.key.code == sf::Keyboard::W) { m_pState = m_pPlayer.get(); } if (evt.key.code == sf::Keyboard::P) { std::cout << "Currently at absolute " << m_pPlayer->GetRelativePosition().x << "X : " << m_pPlayer->GetRelativePosition().y << "Y" << std::endl; m_vNPC[0]->Move(Objects::DOWN); } if (evt.key.code == sf::Keyboard::D) { m_vNPC[0]->SetPosition({5, 1}); m_pMap->SetDebug(); } } } }100-1000 #include "optimization_solve_qp2_using_smo.h"#include using namespace std; #define MAX(a,b,c) max(a,max(b,c)) typedef pair pii; //0xACCE97ED int main() { int t, n; scanf("%d", &t); while(t--) { scanf("%d", &n); printf("%d\n", (int)ceil(n / 2.0)); } return 0; }libs/maps/src/maps/CPointsMap.cpp /* +---------------------------------------------------------------------------+ | Mobile Robot Programming Toolkit (MRPT) | | http://www.mrpt.org/ | | | | Copyright (c) 2005-2017, Individual contributors, see AUTHORS file | | See: http://www.mrpt.org/Authors - All rights reserved. | | Released under BSD License. See details in http://www.mrpt.org/License | +---------------------------------------------------------------------------+ */ #include "maps-precomp.h" // Precomp header #include #include #include #include #include #include #include #include #include // Observations: #include #include #include #include #if MRPT_HAS_PCL # include # include //# include #endif #if MRPT_HAS_SSE2 # include # include #endif #if MRPT_HAS_MATLAB # include #endif using namespace mrpt::poses; using namespace mrpt::maps; using namespace mrpt::utils; using namespace mrpt::math; using namespace mrpt::obs; using namespace mrpt::system; using namespace std; float mrpt::global_settings::POINTSMAPS_3DOBJECT_POINTSIZE = 3.0f; IMPLEMENTS_VIRTUAL_SERIALIZABLE(CPointsMap, CMetricMap,mrpt::maps) float CPointsMap::COLOR_3DSCENE_R = 0; float CPointsMap::COLOR_3DSCENE_G = 0; float CPointsMap::COLOR_3DSCENE_B = 1; /*--------------------------------------------------------------- Constructor ---------------------------------------------------------------*/ CPointsMap::CPointsMap() : insertionOptions(), likelihoodOptions(), x(),y(),z(), m_largestDistanceFromOrigin(0), m_heightfilter_z_min(-10), m_heightfilter_z_max(10), m_heightfilter_enabled(false) { mark_as_modified(); } /*--------------------------------------------------------------- Destructor ---------------------------------------------------------------*/ CPointsMap::~CPointsMap() { } /*--------------------------------------------------------------- save2D_to_text_file Save to a text file. In each line there are a point coordinates. Returns false if any error occured, true elsewere. ---------------------------------------------------------------*/ bool CPointsMap::save2D_to_text_file(const string &file) const { FILE *f=os::fopen(file.c_str(),"wt"); if (!f) return false; for (unsigned int i=0;iclear(); while (!feof(f)) { // Read one string line: str[0] = 0; if (!fgets(str,sizeof(str),f)) break; // Find the first digit: ptr=str; while (ptr[0] && (ptr[0]==' ' || ptr[0]=='\t' || ptr[0]=='\r' || ptr[0]=='\n')) ptr++; // And try to parse it: float xx = strtod(ptr,&ptr1); if (ptr1!=str) { float yy = strtod(ptr1,&ptr2); if (ptr2!=ptr1) { if (!is_3D) { this->insertPoint(xx,yy,0); } else { float zz = strtod(ptr2,&ptr3); if (ptr3!=ptr2) { this->insertPoint(xx,yy,zz); } } } } } os::fclose(f); return true; MRPT_END } /*--------------------------------------------------------------- Implements the writing to a mxArray for Matlab ---------------------------------------------------------------*/ #if MRPT_HAS_MATLAB // Add to implement mexplus::from template specialization IMPLEMENTS_MEXPLUS_FROM( mrpt::maps::CPointsMap ) mxArray* CPointsMap::writeToMatlab() const { MRPT_TODO("Create 3xN array xyz of points coordinates") const char* fields[] = {"x","y","z"}; mexplus::MxArray map_struct( mexplus::MxArray::Struct(sizeof(fields)/sizeof(fields[0]),fields) ); map_struct.set("x", this->x); map_struct.set("y", this->y); map_struct.set("z", this->z); return map_struct.release(); } #endif /*--------------------------------------------------------------- getPoint Access to stored points coordinates: ---------------------------------------------------------------*/ unsigned long CPointsMap::getPoint(size_t index,float &x,float &y) const { ASSERT_BELOW_(index,this->x.size()) x = this->x[index]; y = this->y[index]; return getPointWeight(index); } unsigned long CPointsMap::getPoint(size_t index,float &x,float &y,float &z) const { ASSERT_BELOW_(index,this->x.size()) x = this->x[index]; y = this->y[index]; z = this->z[index]; return getPointWeight(index); } unsigned long CPointsMap::getPoint(size_t index,double &x,double &y) const { ASSERT_BELOW_(index,this->x.size()) x = this->x[index]; y = this->y[index]; return getPointWeight(index);; } unsigned long CPointsMap::getPoint(size_t index,double &x,double &y,double &z) const { ASSERT_BELOW_(index,this->x.size()) x = this->x[index]; y = this->y[index]; z = this->z[index]; return getPointWeight(index);; } /*--------------------------------------------------------------- getPointsBuffer ---------------------------------------------------------------*/ void CPointsMap::getPointsBuffer( size_t &outPointsCount, const float *&xs, const float *&ys, const float *&zs ) const { outPointsCount = size(); if (outPointsCount>0) { xs = &x[0]; ys = &y[0]; zs = &z[0]; } else { xs = ys = zs = NULL; } } /*--------------------------------------------------------------- clipOutOfRangeInZ ---------------------------------------------------------------*/ void CPointsMap::clipOutOfRangeInZ(float zMin, float zMax) { const size_t n=size(); vector deletionMask(n); // Compute it: for (size_t i=0;izMax ); // Perform deletion: applyDeletionMask(deletionMask); mark_as_modified(); } /*--------------------------------------------------------------- clipOutOfRange ---------------------------------------------------------------*/ void CPointsMap::clipOutOfRange(const TPoint2D &p, float maxRange) { size_t i,n=size(); vector deletionMask; // The deletion mask: deletionMask.resize(n); // Compute it: for (i=0;i maxRange; // Perform deletion: applyDeletionMask(deletionMask); mark_as_modified(); } void CPointsMap::determineMatching2D( const mrpt::maps::CMetricMap * otherMap2, const CPose2D & otherMapPose_, TMatchingPairList & correspondences, const TMatchingParams & params, TMatchingExtraResults & extraResults ) const { MRPT_START extraResults = TMatchingExtraResults(); // Clear output ASSERT_ABOVE_(params.decimation_other_map_points,0) ASSERT_BELOW_(params.offset_other_map_points, params.decimation_other_map_points) ASSERT_(otherMap2->GetRuntimeClass()->derivedFrom( CLASS_ID(CPointsMap) )); const CPointsMap *otherMap = static_cast( otherMap2 ); const TPose2D otherMapPose(otherMapPose_.x(),otherMapPose_.y(),otherMapPose_.phi()); const size_t nLocalPoints = otherMap->size(); const size_t nGlobalPoints = this->size(); float _sumSqrDist=0; size_t _sumSqrCount = 0; size_t nOtherMapPointsWithCorrespondence = 0; // Number of points with one corrs. at least float local_x_min= std::numeric_limits::max(), local_x_max= -std::numeric_limits::max(); float global_x_min=std::numeric_limits::max(), global_x_max= -std::numeric_limits::max(); float local_y_min= std::numeric_limits::max(), local_y_max= -std::numeric_limits::max(); float global_y_min=std::numeric_limits::max(), global_y_max= -std::numeric_limits::max(); double maxDistForCorrespondenceSquared; float x_local, y_local; unsigned int localIdx; const float *x_other_it,*y_other_it,*z_other_it; // *x_global_it,*y_global_it; //,*z_global_it; // Prepare output: no correspondences initially: correspondences.clear(); correspondences.reserve(nLocalPoints); extraResults.correspondencesRatio = 0; TMatchingPairList _correspondences; _correspondences.reserve(nLocalPoints); // Hay mapa global? if (!nGlobalPoints) return; // No // Hay mapa local? if (!nLocalPoints) return; // No const double sin_phi = sin(otherMapPose.phi); const double cos_phi = cos(otherMapPose.phi); // Do matching only there is any chance of the two maps to overlap: // ----------------------------------------------------------- // Translate and rotate all local points: #if MRPT_HAS_SSE2 // Number of 4-floats: size_t nPackets = nLocalPoints/4; if ( (nLocalPoints & 0x03)!=0) nPackets++; // Pad with zeros to make sure we have a number of points multiple of 4 size_t nLocalPoints_4align = nLocalPoints; size_t nExtraPad = 0; if (0!=(nLocalPoints & 0x03)) { nExtraPad = 4 - (nLocalPoints & 0x03); nLocalPoints_4align+=nExtraPad; } Eigen::Array x_locals(nLocalPoints_4align), y_locals(nLocalPoints_4align); // We'll assume that the real allocated memory in the source buffers at least have room for a maximum // of 3 more floats, and pad with zeroes there (yeah, fuck correct-constness....) // JLBC OCT/2016: resize() methods in maps have been modified to enforce capacities to be 4*N by design, // but will leave this code here just in case (for some edge cases?) if ( otherMap->x.capacity()y.capacity()*>(&otherMap->x)->reserve(nLocalPoints_4align+16); const_cast*>(&otherMap->y)->reserve(nLocalPoints_4align+16); } if (nExtraPad) { float *ptr_in_x = const_cast(&otherMap->x[0]); float *ptr_in_y = const_cast(&otherMap->y[0]); for (size_t k=nExtraPad;k; k--) { ptr_in_x[nLocalPoints+k]=0; ptr_in_y[nLocalPoints+k]=0; } } const __m128 cos_4val = _mm_set1_ps(cos_phi); // load 4 copies of the same value const __m128 sin_4val = _mm_set1_ps(sin_phi); const __m128 x0_4val = _mm_set1_ps(otherMapPose.x); const __m128 y0_4val = _mm_set1_ps(otherMapPose.y); // For the bounding box: __m128 x_mins = _mm_set1_ps( std::numeric_limits::max() ); __m128 x_maxs = _mm_set1_ps( std::numeric_limits::min() ); __m128 y_mins = x_mins; __m128 y_maxs = x_maxs; const float *ptr_in_x = &otherMap->x[0]; const float *ptr_in_y = &otherMap->y[0]; float *ptr_out_x = &x_locals[0]; float *ptr_out_y = &y_locals[0]; for( ; nPackets; nPackets--, ptr_in_x+=4, ptr_in_y+=4, ptr_out_x+=4, ptr_out_y+=4 ) { const __m128 xs = _mm_loadu_ps(ptr_in_x); // *Unaligned* load const __m128 ys = _mm_loadu_ps(ptr_in_y); const __m128 lxs = _mm_add_ps(x0_4val, _mm_sub_ps( _mm_mul_ps(xs,cos_4val), _mm_mul_ps(ys,sin_4val) ) ); const __m128 lys = _mm_add_ps(y0_4val, _mm_add_ps( _mm_mul_ps(xs,sin_4val), _mm_mul_ps(ys,cos_4val) ) ); _mm_store_ps(ptr_out_x, lxs ); _mm_store_ps(ptr_out_y, lys ); x_mins = _mm_min_ps(x_mins,lxs); x_maxs = _mm_max_ps(x_maxs,lxs); y_mins = _mm_min_ps(y_mins,lys); y_maxs = _mm_max_ps(y_maxs,lys); } // Recover the min/max: MRPT_ALIGN16 float temp_nums[4]; _mm_store_ps(temp_nums, x_mins); local_x_min=min(min(temp_nums[0],temp_nums[1]),min(temp_nums[2],temp_nums[3])); _mm_store_ps(temp_nums, y_mins); local_y_min=min(min(temp_nums[0],temp_nums[1]),min(temp_nums[2],temp_nums[3])); _mm_store_ps(temp_nums, x_maxs); local_x_max=max(max(temp_nums[0],temp_nums[1]),max(temp_nums[2],temp_nums[3])); _mm_store_ps(temp_nums, y_maxs); local_y_max=max(max(temp_nums[0],temp_nums[1]),max(temp_nums[2],temp_nums[3])); #else // Non SSE2 version: const Eigen::Map > x_org( const_cast(&otherMap->x[0]),otherMap->x.size(),1 ); const Eigen::Map > y_org( const_cast(&otherMap->y[0]),otherMap->y.size(),1 ); Eigen::Array x_locals = otherMapPose.x + cos_phi * x_org.array() - sin_phi * y_org.array() ; Eigen::Array y_locals = otherMapPose.y + sin_phi * x_org.array() + cos_phi * y_org.array() ; local_x_min=x_locals.minCoeff(); local_y_min=y_locals.minCoeff(); local_x_max=x_locals.maxCoeff(); local_y_max=y_locals.maxCoeff(); #endif // Find the bounding box: float global_z_min,global_z_max; this->boundingBox( global_x_min,global_x_max, global_y_min,global_y_max, global_z_min,global_z_max ); // Only try doing a matching if there exist any chance of both maps touching/overlaping: if (local_x_min>global_x_max || local_x_maxglobal_y_max || local_y_maxx[params.offset_other_map_points], y_other_it=&otherMap->y[params.offset_other_map_points], z_other_it=&otherMap->z[params.offset_other_map_points]; localIdx(_sumSqrCount); else extraResults.sumSqrDist = 0; // The ratio of points in the other map with corrs: extraResults.correspondencesRatio = params.decimation_other_map_points*nOtherMapPointsWithCorrespondence / static_cast(nLocalPoints); MRPT_END } /*--------------------------------------------------------------- changeCoordinatesReference ---------------------------------------------------------------*/ void CPointsMap::changeCoordinatesReference(const CPose2D &newBase) { const size_t N = x.size(); const CPose3D newBase3D(newBase); for (size_t i=0;i> version; switch(version) { case 0: { in >> minDistBetweenLaserPoints >> addToExistingPointsMap >> also_interpolate >> disableDeletion >> fuseWithExisting >> isPlanarMap >> horizontalTolerance >> maxDistForInterpolatePoints >> insertInvalidPoints; // v0 } break; default: MRPT_THROW_UNKNOWN_SERIALIZATION_VERSION(version) } } CPointsMap::TLikelihoodOptions::TLikelihoodOptions() : sigma_dist ( 0.0025 ), max_corr_distance ( 1.0 ), decimation ( 10 ) { } void CPointsMap::TLikelihoodOptions::writeToStream(mrpt::utils::CStream &out) const { const int8_t version = 0; out << version; out << sigma_dist << max_corr_distance << decimation; } void CPointsMap::TLikelihoodOptions::readFromStream(mrpt::utils::CStream &in) { int8_t version; in >> version; switch(version) { case 0: { in >> sigma_dist >> max_corr_distance >> decimation; } break; default: MRPT_THROW_UNKNOWN_SERIALIZATION_VERSION(version) } } /*--------------------------------------------------------------- dumpToTextStream ---------------------------------------------------------------*/ void CPointsMap::TInsertionOptions::dumpToTextStream(mrpt::utils::CStream &out) const { out.printf("\n----------- [CPointsMap::TInsertionOptions] ------------ \n\n"); LOADABLEOPTS_DUMP_VAR(minDistBetweenLaserPoints,double); LOADABLEOPTS_DUMP_VAR(maxDistForInterpolatePoints,double); LOADABLEOPTS_DUMP_VAR_DEG(horizontalTolerance); LOADABLEOPTS_DUMP_VAR(addToExistingPointsMap,bool); LOADABLEOPTS_DUMP_VAR(also_interpolate,bool); LOADABLEOPTS_DUMP_VAR(disableDeletion,bool); LOADABLEOPTS_DUMP_VAR(fuseWithExisting,bool); LOADABLEOPTS_DUMP_VAR(isPlanarMap,bool); LOADABLEOPTS_DUMP_VAR(insertInvalidPoints,bool); out.printf("\n"); } void CPointsMap::TLikelihoodOptions::dumpToTextStream(mrpt::utils::CStream &out) const { out.printf("\n----------- [CPointsMap::TLikelihoodOptions] ------------ \n\n"); LOADABLEOPTS_DUMP_VAR(sigma_dist,double); LOADABLEOPTS_DUMP_VAR(max_corr_distance,double); LOADABLEOPTS_DUMP_VAR(decimation,int); } /*--------------------------------------------------------------- loadFromConfigFile ---------------------------------------------------------------*/ void CPointsMap::TInsertionOptions::loadFromConfigFile( const mrpt::utils::CConfigFileBase &iniFile, const string §ion) { MRPT_LOAD_CONFIG_VAR(minDistBetweenLaserPoints,float, iniFile,section); MRPT_LOAD_CONFIG_VAR_DEGREES(horizontalTolerance, iniFile, section); MRPT_LOAD_CONFIG_VAR(addToExistingPointsMap, bool, iniFile,section); MRPT_LOAD_CONFIG_VAR(also_interpolate, bool, iniFile,section); MRPT_LOAD_CONFIG_VAR(disableDeletion, bool, iniFile,section); MRPT_LOAD_CONFIG_VAR(fuseWithExisting, bool, iniFile,section); MRPT_LOAD_CONFIG_VAR(isPlanarMap, bool, iniFile,section); MRPT_LOAD_CONFIG_VAR(maxDistForInterpolatePoints, float, iniFile,section); MRPT_LOAD_CONFIG_VAR(insertInvalidPoints,bool, iniFile,section); } void CPointsMap::TLikelihoodOptions::loadFromConfigFile( const mrpt::utils::CConfigFileBase &iniFile, const string §ion) { MRPT_LOAD_CONFIG_VAR(sigma_dist,double,iniFile,section); MRPT_LOAD_CONFIG_VAR(max_corr_distance,double,iniFile,section); MRPT_LOAD_CONFIG_VAR(decimation,int,iniFile,section); } /*--------------------------------------------------------------- getAs3DObject ---------------------------------------------------------------*/ void CPointsMap::getAs3DObject( mrpt::opengl::CSetOfObjectsPtr &outObj ) const { if (!genericMapParams.enableSaveAs3DObject) return; opengl::CPointCloudPtr obj = opengl::CPointCloud::Create(); obj->loadFromPointsMap(this); obj->setColor( CPointsMap::COLOR_3DSCENE_R, CPointsMap::COLOR_3DSCENE_G, CPointsMap::COLOR_3DSCENE_B, 1 ); obj->setPointSize( mrpt::global_settings::POINTSMAPS_3DOBJECT_POINTSIZE ); obj->enableColorFromZ(true); obj->setGradientColors( TColorf(0.0,0,0), TColorf(CPointsMap::COLOR_3DSCENE_R,CPointsMap::COLOR_3DSCENE_G,CPointsMap::COLOR_3DSCENE_B)); outObj->insert(obj); } float CPointsMap::compute3DMatchingRatio(const mrpt::maps::CMetricMap *otherMap2, const mrpt::poses::CPose3D &otherMapPose, const TMatchingRatioParams &mrp) const { TMatchingPairList correspondences; TMatchingParams params; TMatchingExtraResults extraResults; params.maxDistForCorrespondence = mrp.maxDistForCorr; this->determineMatching3D( otherMap2->getAsSimplePointsMap(), otherMapPose, correspondences, params, extraResults); return extraResults.correspondencesRatio; } /*--------------------------------------------------------------- getLargestDistanceFromOrigin ---------------------------------------------------------------*/ float CPointsMap::getLargestDistanceFromOrigin() const { // Updated? if (!m_largestDistanceFromOriginIsUpdated) { // NO: Update it: vector::const_iterator X,Y,Z; float maxDistSq = 0, d; for (X=x.begin(),Y=y.begin(),Z=z.begin();X!=x.end();++X,++Y,++Z) { d = square(*X)+square(*Y)+square(*Z); maxDistSq = max( d, maxDistSq ); } m_largestDistanceFromOrigin = sqrt( maxDistSq ); m_largestDistanceFromOriginIsUpdated = true; } return m_largestDistanceFromOrigin; } /*--------------------------------------------------------------- getAllPoints ---------------------------------------------------------------*/ void CPointsMap::getAllPoints( vector &xs, vector &ys, size_t decimation ) const { MRPT_START ASSERT_(decimation>0) if (decimation==1) { xs = x; ys = y; } else { size_t N = x.size() / decimation; xs.resize(N); ys.resize(N); vector::const_iterator X,Y; vector::iterator oX,oY; for (X=x.begin(),Y=y.begin(),oX=xs.begin(),oY=ys.begin();oX!=xs.end();X+=decimation,Y+=decimation,++oX,++oY) { *oX=*X; *oY=*Y; } } MRPT_END } /*--------------------------------------------------------------- squareDistanceToClosestCorrespondence ---------------------------------------------------------------*/ float CPointsMap::squareDistanceToClosestCorrespondence( float x0, float y0 ) const { // Just the closest point: #if 1 return kdTreeClosestPoint2DsqrError(x0,y0); #else // The distance to the line that interpolates the TWO closest points: float x1,y1, x2,y2, d1,d2; kdTreeTwoClosestPoint2D( x0, y0, // The query x1, y1, // Closest point #1 x2, y2, // Closest point #2 d1,d2); ASSERT_(d2>=d1); // If the two points are too far, do not interpolate: float d12 = square(x1-x2)+square(y1-y2); if (d12 > 0.20f*0.20f || d12 < 0.03f*0.03f) { return square( x1-x0 ) + square( y1-y0 ); } else { // Interpolate double interp_x, interp_y; //math::closestFromPointToSegment( math::closestFromPointToLine( x0,y0, // the point x1,y1, x2,y2, // The segment interp_x, interp_y // out ); return square( interp_x-x0 ) + square( interp_y-y0 ); } #endif } /*--------------------------------------------------------------- boundingBox ---------------------------------------------------------------*/ void CPointsMap::boundingBox( float &min_x, float &max_x, float &min_y, float &max_y, float &min_z, float &max_z ) const { const size_t nPoints = x.size(); if (!m_boundingBoxIsUpdated) { if (!nPoints) { m_bb_min_x = m_bb_max_x = m_bb_min_y = m_bb_max_y = m_bb_min_z = m_bb_max_z = 0; } else { #if MRPT_HAS_SSE2 // Vectorized version: ~ 9x times faster // Number of 4-floats: size_t nPackets = nPoints/4; if ( (nPoints & 0x03)!=0) nPackets++; // Pad with zeros to make sure we have a number of points multiple of 4 size_t nPoints_4align = nPoints; size_t nExtraPad = 0; if (0!=(nPoints & 0x03)) { nExtraPad = 4 - (nPoints & 0x03); nPoints_4align+=nExtraPad; } // We'll assume that the real allocated memory in the source buffers at least have room for a maximum // of 3 more floats, and pad with zeroes there (yeah, fuck correct-constness....) // JLBC OCT/2016: resize() methods in maps have been modified to enforce capacities to be 4*N by design, // but will leave this code here just in case (for some edge cases?) if ( x.capacity()*>(&x)->reserve(nPoints_4align+16); const_cast*>(&y)->reserve(nPoints_4align+16); const_cast*>(&z)->reserve(nPoints_4align+16); } if (nExtraPad) { float *ptr_in_x = const_cast(&x[0]); float *ptr_in_y = const_cast(&y[0]); float *ptr_in_z = const_cast(&z[0]); for (size_t k=nExtraPad;k; k--) { ptr_in_x[nPoints+k-1]=0; ptr_in_y[nPoints+k-1]=0; ptr_in_z[nPoints+k-1]=0; } } // For the bounding box: __m128 x_mins = _mm_set1_ps( std::numeric_limits::max() ); __m128 x_maxs = _mm_set1_ps( std::numeric_limits::min() ); __m128 y_mins = x_mins, y_maxs = x_maxs; __m128 z_mins = x_mins, z_maxs = x_maxs; const float *ptr_in_x = &this->x[0]; const float *ptr_in_y = &this->y[0]; const float *ptr_in_z = &this->z[0]; for( ; nPackets; nPackets--, ptr_in_x+=4, ptr_in_y+=4, ptr_in_z+=4 ) { const __m128 xs = _mm_loadu_ps(ptr_in_x); // *Unaligned* load x_mins = _mm_min_ps(x_mins,xs); x_maxs = _mm_max_ps(x_maxs,xs); const __m128 ys = _mm_loadu_ps(ptr_in_y); y_mins = _mm_min_ps(y_mins,ys); y_maxs = _mm_max_ps(y_maxs,ys); const __m128 zs = _mm_loadu_ps(ptr_in_z); z_mins = _mm_min_ps(z_mins,zs); z_maxs = _mm_max_ps(z_maxs,zs); } // Recover the min/max: MRPT_ALIGN16 float temp_nums[4]; _mm_store_ps(temp_nums, x_mins); m_bb_min_x=min(min(temp_nums[0],temp_nums[1]),min(temp_nums[2],temp_nums[3])); _mm_store_ps(temp_nums, y_mins); m_bb_min_y=min(min(temp_nums[0],temp_nums[1]),min(temp_nums[2],temp_nums[3])); _mm_store_ps(temp_nums, z_mins); m_bb_min_z=min(min(temp_nums[0],temp_nums[1]),min(temp_nums[2],temp_nums[3])); _mm_store_ps(temp_nums, x_maxs); m_bb_max_x=max(max(temp_nums[0],temp_nums[1]),max(temp_nums[2],temp_nums[3])); _mm_store_ps(temp_nums, y_maxs); m_bb_max_y=max(max(temp_nums[0],temp_nums[1]),max(temp_nums[2],temp_nums[3])); _mm_store_ps(temp_nums, z_maxs); m_bb_max_z=max(max(temp_nums[0],temp_nums[1]),max(temp_nums[2],temp_nums[3])); #else // Non vectorized version: m_bb_min_x = m_bb_min_y = m_bb_min_z = (std::numeric_limits::max)(); m_bb_max_x = m_bb_max_y = m_bb_max_z = -(std::numeric_limits::max)(); for (vector::const_iterator xi=x.begin(), yi=y.begin(), zi=z.begin(); xi!=x.end();xi++,yi++,zi++) { m_bb_min_x = min( m_bb_min_x, *xi ); m_bb_max_x = max( m_bb_max_x, *xi ); m_bb_min_y = min( m_bb_min_y, *yi ); m_bb_max_y = max( m_bb_max_y, *yi ); m_bb_min_z = min( m_bb_min_z, *zi ); m_bb_max_z = max( m_bb_max_z, *zi ); } #endif } m_boundingBoxIsUpdated = true; } min_x = m_bb_min_x; max_x = m_bb_max_x; min_y = m_bb_min_y; max_y = m_bb_max_y; min_z = m_bb_min_z; max_z = m_bb_max_z; } /*--------------------------------------------------------------- computeMatchingWith3D ---------------------------------------------------------------*/ void CPointsMap::determineMatching3D( const mrpt::maps::CMetricMap * otherMap2, const CPose3D & otherMapPose, TMatchingPairList & correspondences, const TMatchingParams & params, TMatchingExtraResults & extraResults ) const { MRPT_START extraResults = TMatchingExtraResults(); ASSERT_ABOVE_(params.decimation_other_map_points,0) ASSERT_BELOW_(params.offset_other_map_points, params.decimation_other_map_points) ASSERT_(otherMap2->GetRuntimeClass()->derivedFrom( CLASS_ID(CPointsMap) )); const CPointsMap *otherMap = static_cast( otherMap2 ); const size_t nLocalPoints = otherMap->size(); const size_t nGlobalPoints = this->size(); float _sumSqrDist=0; size_t _sumSqrCount = 0; size_t nOtherMapPointsWithCorrespondence = 0; // Number of points with one corrs. at least float local_x_min= std::numeric_limits::max(), local_x_max= -std::numeric_limits::max(); float local_y_min= std::numeric_limits::max(), local_y_max= -std::numeric_limits::max(); float local_z_min= std::numeric_limits::max(), local_z_max= -std::numeric_limits::max(); double maxDistForCorrespondenceSquared; // Prepare output: no correspondences initially: correspondences.clear(); correspondences.reserve(nLocalPoints); TMatchingPairList _correspondences; _correspondences.reserve(nLocalPoints); // Empty maps? Nothing to do if (!nGlobalPoints || !nLocalPoints) return; // Try to do matching only if the bounding boxes have some overlap: // Transform all local points: vector x_locals(nLocalPoints), y_locals(nLocalPoints), z_locals(nLocalPoints); for (unsigned int localIdx=params.offset_other_map_points;localIdxx[localIdx], otherMap->y[localIdx], otherMap->z[localIdx], x_local,y_local,z_local ); x_locals[localIdx] = x_local; y_locals[localIdx] = y_local; z_locals[localIdx] = z_local; // Find the bounding box: local_x_min = min(local_x_min,x_local); local_x_max = max(local_x_max,x_local); local_y_min = min(local_y_min,y_local); local_y_max = max(local_y_max,y_local); local_z_min = min(local_z_min,z_local); local_z_max = max(local_z_max,z_local); } // Find the bounding box: float global_x_min, global_x_max, global_y_min, global_y_max, global_z_min, global_z_max; this->boundingBox( global_x_min,global_x_max, global_y_min,global_y_max, global_z_min,global_z_max ); // Solo hacer matching si existe alguna posibilidad de que // los dos mapas se toquen: if (local_x_min>global_x_max || local_x_maxglobal_y_max || local_y_maxx[localIdx]; p.other_y = otherMap->y[localIdx]; p.other_z = otherMap->z[localIdx]; p.errorSquareAfterTransformation = tentativ_err_sq; // At least one: nOtherMapPointsWithCorrespondence++; // Accumulate the MSE: _sumSqrDist+= p.errorSquareAfterTransformation; _sumSqrCount++; } } // End of test_match } // For each local point // Additional consistency filter: "onlyKeepTheClosest" up to now // led to just one correspondence for each "local map" point, but // many of them may have as corresponding pair the same "global point"!! // ------------------------------------------------------------------------- if (params.onlyUniqueRobust) { ASSERTMSG_(params.onlyKeepTheClosest, "ERROR: onlyKeepTheClosest must be also set to true when onlyUniqueRobust=true."); _correspondences.filterUniqueRobustPairs(nGlobalPoints,correspondences); } else { correspondences.swap(_correspondences); } // If requested, copy sum of squared distances to output pointer: // ------------------------------------------------------------------- extraResults.sumSqrDist = (_sumSqrCount) ? _sumSqrDist / static_cast(_sumSqrCount) : 0; extraResults.correspondencesRatio = params.decimation_other_map_points*nOtherMapPointsWithCorrespondence / static_cast(nLocalPoints); MRPT_END } /*--------------------------------------------------------------- extractCylinder ---------------------------------------------------------------*/ void CPointsMap::extractCylinder( const TPoint2D ¢er, const double radius, const double zmin, const double zmax, CPointsMap *outMap ) { outMap->clear(); for( size_t k = 0; k < x.size(); k++ ) { if( (z[k] <= zmax && z[k] >= zmin) && ( sqrt(square(center.x-x[k])+square(center.y-y[k])) < radius ) ) outMap->insertPoint( x[k], y[k], z[k] ); } } /*--------------------------------------------------------------- extractPoints ---------------------------------------------------------------*/ void CPointsMap::extractPoints( const TPoint3D &corner1, const TPoint3D &corner2, CPointsMap *outMap, const double &R, const double &G, const double &B ) { outMap->clear(); double minX,maxX,minY,maxY,minZ,maxZ; minX = min(corner1.x,corner2.x); maxX = max(corner1.x,corner2.x); minY = min(corner1.y,corner2.y); maxY = max(corner1.y,corner2.y); minZ = min(corner1.z,corner2.z); maxZ = max(corner1.z,corner2.z); for( size_t k = 0; k < x.size(); k++ ) { if( (x[k] >= minX && x[k] <= maxX) && (y[k] >= minY && y[k] <= maxY) && (z[k] >= minZ && z[k] <= maxZ) ) outMap->insertPoint( x[k], y[k], z[k], R, G, B ); } } /*--------------------------------------------------------------- compute3DDistanceToMesh ---------------------------------------------------------------*/ void CPointsMap::compute3DDistanceToMesh( const mrpt::maps::CMetricMap *otherMap2, const CPose3D &otherMapPose, float maxDistForCorrespondence, TMatchingPairList &correspondences, float &correspondencesRatio ) { MRPT_START MRPT_UNUSED_PARAM(otherMapPose); const CPointsMap *otherMap = static_cast( otherMap2 ); const size_t nLocalPoints = otherMap->size(); const size_t nGlobalPoints = this->size(); size_t nOtherMapPointsWithCorrespondence = 0; // Number of points with one corrs. at least // Prepare output: no correspondences initially: correspondences.clear(); correspondences.reserve(nLocalPoints); correspondencesRatio = 0; // aux correspondence vector TMatchingPairList _correspondences; _correspondences.reserve(nLocalPoints); // Hay mapa global? if (!nGlobalPoints) return; // No // Hay mapa local? if (!nLocalPoints) return; // No // we'll assume by now both reference systems are the same float local_x_min, local_x_max, local_y_min, local_y_max, local_z_min, local_z_max; otherMap->boundingBox( local_x_min, local_x_max, local_y_min, local_y_max, local_z_min, local_z_max ); // Find the bounding box: float global_x_min, global_x_max, global_y_min, global_y_max, global_z_min, global_z_max; this->boundingBox( global_x_min,global_x_max, global_y_min,global_y_max, global_z_min,global_z_max ); // Solo hacer matching si existe alguna posibilidad de que // los dos mapas se toquen: if (local_x_min>global_x_max || local_x_maxglobal_y_max || local_y_max > vIdx; // Loop for each point in local map: // -------------------------------------------------- std::vector outX,outY,outZ,tentativeErrSq; std::vector outIdx; for (unsigned int localIdx = 0; localIdx < nLocalPoints; ++localIdx ) { // For speed-up: const float x_local = otherMap->x[localIdx]; const float y_local = otherMap->y[localIdx]; const float z_local = otherMap->z[localIdx]; { // KD-TREE implementation // Use a KD-tree to look for the nearnest neighbor of: // (x_local, y_local, z_local) // In "this" (global/reference) points map. kdTreeNClosestPoint3DWithIdx( x_local, y_local, z_local, // Look closest to this guy 3, // get the three closest points outX,outY,outZ, // output vectors outIdx, // output indexes tentativeErrSq // save here the min. distance squared ); // get the centroid const float mX = (outX[0]+outX[1]+outX[2])/3.0; const float mY = (outY[0]+outY[1]+outY[2])/3.0; const float mZ = (outZ[0]+outZ[1]+outZ[2])/3.0; const float distanceForThisPoint = fabs(mrpt::math::distance(TPoint3D(x_local,y_local,z_local),TPoint3D(mX,mY,mZ))); // Distance below the threshold?? if ( distanceForThisPoint < maxDistForCorrespondence ) { // Save all the correspondences: _correspondences.resize(_correspondences.size()+1); TMatchingPair & p = _correspondences.back(); p.this_idx = nOtherMapPointsWithCorrespondence++; // insert a consecutive index here p.this_x = mX; p.this_y = mY; p.this_z = mZ; p.other_idx = localIdx; p.other_x = otherMap->x[localIdx]; p.other_y = otherMap->y[localIdx]; p.other_z = otherMap->z[localIdx]; p.errorSquareAfterTransformation = distanceForThisPoint; // save the indexes std::sort(outIdx.begin(),outIdx.end()); vIdx.push_back(outIdx); } } // End of test_match } // For each local point // Additional consistency filter: "onlyKeepTheClosest" up to now // led to just one correspondence for each "local map" point, but // many of them may have as corresponding pair the same "global point"!! // ------------------------------------------------------------------------- std::map > > > best; // 3D associative map TMatchingPairList::iterator it; for (it = _correspondences.begin(); it != _correspondences.end(); ++it) { const size_t i0 = vIdx[it->this_idx][0]; const size_t i1 = vIdx[it->this_idx][1]; const size_t i2 = vIdx[it->this_idx][2]; if( best.find(i0) != best.end() && best[i0].find(i1) != best[i0].end() && best[i0][i1].find(i2) != best[i0][i1].end() ) // if there is a match, check if it is better { if( best[i0][i1][i2].second > it->errorSquareAfterTransformation ) { best[i0][i1][i2].first = it->this_idx; best[i0][i1][i2].second = it->errorSquareAfterTransformation; } } else // if there is no match { best[i0][i1][i2].first = it->this_idx; best[i0][i1][i2].second = it->errorSquareAfterTransformation; } } // end it correspondences for (it = _correspondences.begin(); it != _correspondences.end(); ++it) { const size_t i0 = vIdx[it->this_idx][0]; const size_t i1 = vIdx[it->this_idx][1]; const size_t i2 = vIdx[it->this_idx][2]; if( best[i0][i1][i2].first == it->this_idx ) correspondences.push_back(*it); } // The ratio of points in the other map with corrs: correspondencesRatio = nOtherMapPointsWithCorrespondence / static_cast(nLocalPoints); MRPT_END } /*--------------------------------------------------------------- Computes the likelihood that a given observation was taken from a given pose in the world being modeled with this map. takenFrom The robot's pose the observation is supposed to be taken from. obs The observation. This method returns a likelihood in the range [0,1]. ---------------------------------------------------------------*/ double CPointsMap::internal_computeObservationLikelihood( const CObservation *obs, const CPose3D &takenFrom ) { // If not, this map is standalone: Compute the likelihood: double ret = 0; // This function depends on the observation type: // ----------------------------------------------------- if ( obs->GetRuntimeClass() == CLASS_ID(CObservation2DRangeScan) ) { // Observation is a laser range scan: // ------------------------------------------- const CObservation2DRangeScan *o = static_cast(obs); // Build (if not done before) the points map representation of this observation: const CPointsMap *scanPoints = o->buildAuxPointsMap(); float sumSqrDist=0; const size_t N = scanPoints->x.size(); if (!N || !this->size() ) return -100; const float *xs = &scanPoints->x[0]; const float *ys = &scanPoints->y[0]; const float *zs = &scanPoints->z[0]; float closest_x,closest_y,closest_z; float closest_err; const float max_sqr_err = square(likelihoodOptions.max_corr_distance); int nPtsForAverage = 0; if (takenFrom.isHorizontal()) { // optimized 2D version --------------------------- TPose2D takenFrom2D = TPose2D(CPose2D(takenFrom)); const float ccos = cos(takenFrom2D.phi); const float csin = sin(takenFrom2D.phi); for (size_t i=0;i(out_map.pointer())->insertionOptions = *static_cast(insertOps); out_map->insertObservation(&obs,NULL); } struct TAuxLoadFunctor { TAuxLoadFunctor() { mrpt::obs::ptr_internal_build_points_map_from_scan2D = internal_build_points_map_from_scan2D; } }; TAuxLoadFunctor dummy_loader; // used just to set "ptr_internal_build_points_map_from_scan2D" // ================================ PLY files import & export virtual methods ================================ /** In a base class, will be called after PLY_import_set_vertex_count() once for each loaded point. * \param pt_color Will be NULL if the loaded file does not provide color info. */ void CPointsMap::PLY_import_set_vertex(const size_t idx, const mrpt::math::TPoint3Df &pt, const mrpt::utils::TColorf *pt_color) { MRPT_UNUSED_PARAM(pt_color); this->setPoint(idx,pt.x,pt.y,pt.z); } /** In a base class, return the number of vertices */ size_t CPointsMap::PLY_export_get_vertex_count() const { return this->size(); } /** In a base class, will be called after PLY_export_get_vertex_count() once for each exported point. * \param pt_color Will be NULL if the loaded file does not provide color info. */ void CPointsMap::PLY_export_get_vertex( const size_t idx, mrpt::math::TPoint3Df &pt, bool &pt_has_color, mrpt::utils::TColorf &pt_color) const { MRPT_UNUSED_PARAM(pt_color); pt_has_color=false; pt.x = x[idx]; pt.y = y[idx]; pt.z = z[idx]; } // Generic implementation (a more optimized one should exist in derived classes): void CPointsMap::addFrom(const CPointsMap &anotherMap) { const size_t nThis = this->size(); const size_t nOther = anotherMap.size(); const size_t nTot = nThis+nOther; this->resize(nTot); for (size_t i=0,j=nThis;ix[j]=anotherMap.x[i]; this->y[j]=anotherMap.y[i]; this->z[j]=anotherMap.z[i]; } // Also copy other data fields (color, ...) addFrom_classSpecific(anotherMap,nThis); mark_as_modified(); } /** Save the point cloud as a PCL PCD file, in either ASCII or binary format \return false on any error */ bool CPointsMap::savePCDFile(const std::string &filename, bool save_as_binary) const { #if MRPT_HAS_PCL pcl::PointCloud cloud; this->getPCLPointCloud(cloud); return 0 == pcl::io::savePCDFile(filename, cloud, save_as_binary); #else MRPT_UNUSED_PARAM(filename); MRPT_UNUSED_PARAM(save_as_binary); THROW_EXCEPTION("Operation not available: MRPT was built without PCL") #endif } /** Load the point cloud from a PCL PCD file (requires MRPT built against PCL) \return false on any error */ bool CPointsMap::loadPCDFile(const std::string &filename) { #if MRPT_HAS_PCL pcl::PointCloud cloud; if (0!=pcl::io::loadPCDFile(filename,cloud)) return false; this->getPCLPointCloud(cloud); return true; #else MRPT_UNUSED_PARAM(filename); THROW_EXCEPTION("Operation not available: MRPT was built without PCL") #endif } /*--------------------------------------------------------------- applyDeletionMask ---------------------------------------------------------------*/ void CPointsMap::applyDeletionMask( const std::vector &mask ) { ASSERT_EQUAL_( size(), mask.size() ) // Remove marked points: const size_t n = mask.size(); vector Pt; size_t i,j; for (i=0,j=0;igetPointAllFieldsFast(i,Pt); this->setPointAllFieldsFast(j++,Pt); } } // Set new correct size: this->resize(j); mark_as_modified(); } /*--------------------------------------------------------------- insertAnotherMap ---------------------------------------------------------------*/ void CPointsMap::insertAnotherMap( const CPointsMap *otherMap, const CPose3D &otherPose) { const size_t N_this = size(); const size_t N_other = otherMap->size(); // Set the new size: this->resize( N_this + N_other ); mrpt::math::TPoint3Df pt; size_t src,dst; for (src=0, dst=N_this; srcgetPointFast(src,pt.x,pt.y,pt.z); // Translation: double gx,gy,gz; otherPose.composePoint(pt.x,pt.y,pt.z, gx,gy,gz); // Add to this map: this->setPointFast(dst,gx,gy,gz); } // Also copy other data fields (color, ...) addFrom_classSpecific(*otherMap, N_this); mark_as_modified(); } /** Helper method for ::copyFrom() */ void CPointsMap::base_copyFrom(const CPointsMap &obj) { MRPT_START if (this==&obj) return; x = obj.x; y = obj.y; z = obj.z; m_largestDistanceFromOriginIsUpdated = obj.m_largestDistanceFromOriginIsUpdated; m_largestDistanceFromOrigin = obj.m_largestDistanceFromOrigin; // Fill missing fields (R,G,B,min_dist) with default values. this->resize(x.size()); kdtree_mark_as_outdated(); MRPT_END } /*--------------------------------------------------------------- internal_insertObservation Insert the observation information into this map. ---------------------------------------------------------------*/ bool CPointsMap::internal_insertObservation( const CObservation *obs, const CPose3D *robotPose) { MRPT_START CPose2D robotPose2D; CPose3D robotPose3D; if (robotPose) { robotPose2D = CPose2D(*robotPose); robotPose3D = (*robotPose); } else { // Default values are (0,0,0) } if (IS_CLASS(obs,CObservation2DRangeScan)) { /******************************************************************** OBSERVATION TYPE: CObservation2DRangeScan ********************************************************************/ mark_as_modified(); const CObservation2DRangeScan *o = static_cast(obs); // Insert only HORIZONTAL scans?? bool reallyInsertIt; if (insertionOptions.isPlanarMap) reallyInsertIt = o->isPlanarScan( insertionOptions.horizontalTolerance ); else reallyInsertIt = true; if (reallyInsertIt) { std::vector checkForDeletion; // 1) Fuse into the points map or add directly? // ---------------------------------------------- if (insertionOptions.fuseWithExisting) { CSimplePointsMap auxMap; // Fuse: auxMap.insertionOptions = insertionOptions; auxMap.insertionOptions.addToExistingPointsMap = false; auxMap.loadFromRangeScan( *o, // The laser range scan observation &robotPose3D // The robot pose ); fuseWith( &auxMap, // Fuse with this map insertionOptions.minDistBetweenLaserPoints, // Min dist. &checkForDeletion // Set to "false" if a point in "map" has been fused. ); if (! insertionOptions.disableDeletion ) { // 2) Delete points in newly added free // region, thus dynamic areas: // -------------------------------------- // Load scan as a polygon: CPolygon pol; const float *xs,*ys,*zs; size_t n; auxMap.getPointsBuffer( n, xs,ys,zs); pol.setAllVertices( n, xs, ys ); // Check for deletion of points in "map" n = size(); for (size_t i=0;i(obs); // Insert only HORIZONTAL scans?? bool reallyInsertIt; if (insertionOptions.isPlanarMap) reallyInsertIt = false; // Don't insert 3D range observation into planar map else reallyInsertIt = true; if (reallyInsertIt) { // 1) Fuse into the points map or add directly? // ---------------------------------------------- if (insertionOptions.fuseWithExisting) { // Fuse: CSimplePointsMap auxMap; auxMap.insertionOptions = insertionOptions; auxMap.insertionOptions.addToExistingPointsMap = false; auxMap.loadFromRangeScan( *o, // The laser range scan observation &robotPose3D // The robot pose ); fuseWith( &auxMap, // Fuse with this map insertionOptions.minDistBetweenLaserPoints, // Min dist. NULL // rather than &checkForDeletion which we don't need for 3D observations ); } else { // Don't fuse: Simply add insertionOptions.addToExistingPointsMap = true; loadFromRangeScan( *o, // The laser range scan observation &robotPose3D // The robot pose ); } // This could be implemented to check whether existing points fall into empty-space 3D polygon // but performance for standard Swissranger scans (176*144 points) may be too sluggish? //if (! insertionOptions.disableDeletion ) { // .... // } // JL -> Nope, it's ok like that ;-) return true; } // A planar map and a non-horizontal scan. else return false; } else if ( IS_CLASS(obs,CObservationRange)) { /******************************************************************** OBSERVATION TYPE: CObservationRange (IRs, Sonars, etc.) ********************************************************************/ mark_as_modified(); const CObservationRange* o = static_cast(obs); const double aper_2 = 0.5*o->sensorConeApperture; this->reserve( this->size() + o->sensedData.size()*30 ); // faster push_back's. for (CObservationRange::const_iterator it=o->begin();it!=o->end();++it) { const CPose3D sensorPose = robotPose3D + CPose3D(it->sensorPose); const double rang = it->sensedDistance; if (rang<=0 || rangminSensorDistance || rang>o->maxSensorDistance) continue; // Insert a few points with a given maximum separation between them: const double arc_len = o->sensorConeApperture*rang; const unsigned int nSteps = round(1+arc_len/0.05); const double Aa = o->sensorConeApperture/double(nSteps); TPoint3D loc, glob; for (double a1=-aper_2;a1insertPointFast(glob.x, glob.y, glob.z); } } } return true; } else if (IS_CLASS(obs,CObservationVelodyneScan)) { /******************************************************************** OBSERVATION TYPE: CObservationVelodyneScan ********************************************************************/ mark_as_modified(); const CObservationVelodyneScan *o = static_cast(obs); if (insertionOptions.fuseWithExisting) { // Fuse: CSimplePointsMap auxMap; auxMap.insertionOptions = insertionOptions; auxMap.insertionOptions.addToExistingPointsMap = false; auxMap.loadFromVelodyneScan(*o,&robotPose3D); fuseWith(&auxMap, insertionOptions.minDistBetweenLaserPoints, NULL /* rather than &checkForDeletion which we don't need for 3D observations */ ); } else { // Don't fuse: Simply add insertionOptions.addToExistingPointsMap = true; loadFromVelodyneScan(*o,&robotPose3D); } return true; } else { /******************************************************************** OBSERVATION TYPE: Unknown ********************************************************************/ return false; } MRPT_END } /*--------------------------------------------------------------- Insert the contents of another map into this one, fusing the previous content with the new one. This means that points very close to existing ones will be "fused", rather than "added". This prevents the unbounded increase in size of these class of maps. ---------------------------------------------------------------*/ void CPointsMap::fuseWith( CPointsMap *otherMap, float minDistForFuse, std::vector *notFusedPoints) { TMatchingPairList correspondences; TPoint3D a,b; const CPose2D nullPose(0,0,0); mark_as_modified(); //const size_t nThis = this->size(); const size_t nOther = otherMap->size(); // Find correspondences between this map and the other one: // ------------------------------------------------------------ TMatchingParams params; TMatchingExtraResults extraResults; params.maxAngularDistForCorrespondence = 0; params.maxDistForCorrespondence = minDistForFuse; determineMatching2D( otherMap,// The other map nullPose, // The other map's pose correspondences, params, extraResults); // Initially, all set to "true" -> "not fused". if (notFusedPoints) { notFusedPoints->clear(); notFusedPoints->reserve( x.size() + nOther ); notFusedPoints->resize( x.size(), true ); } // Speeds-up possible memory reallocations: reserve( x.size() + nOther ); // Merge matched points from both maps: // AND add new points which have been not matched: // ------------------------------------------------- for (size_t i=0;igetPoint(i,a); // Get "local" point into "a" // Find closest correspondence of "a": int closestCorr = -1; float minDist = std::numeric_limits::max(); for (TMatchingPairList::const_iterator corrsIt = correspondences.begin(); corrsIt!=correspondences.end(); ++corrsIt) { if (corrsIt->other_idx==i) { float dist = square( corrsIt->other_x - corrsIt->this_x ) + square( corrsIt->other_y - corrsIt->this_y ) + square( corrsIt->other_z - corrsIt->this_z ); if (distthis_idx; } } } // End of for each correspondence... if (closestCorr!=-1) { // Merge: FUSION unsigned long w_b = getPoint(closestCorr,b); ASSERT_((w_a+w_b)>0); const float F = 1.0f/(w_a+w_b); x[closestCorr]=F*(w_a*a.x+w_b*b.x); y[closestCorr]=F*(w_a*a.y+w_b*b.y); z[closestCorr]=F*(w_a*a.z+w_b*b.z); this->setPointWeight(closestCorr,w_a+w_b); // Append to fused points list if (notFusedPoints) (*notFusedPoints)[closestCorr] = false; } else { // New point: ADDITION this->insertPointFast(a.x,a.y,a.z); if (notFusedPoints) (*notFusedPoints).push_back(false); } } } void CPointsMap::loadFromVelodyneScan( const mrpt::obs::CObservationVelodyneScan & scan, const mrpt::poses::CPose3D *robotPose) { ASSERT_EQUAL_(scan.point_cloud.x.size(),scan.point_cloud.y.size()); ASSERT_EQUAL_(scan.point_cloud.x.size(),scan.point_cloud.z.size()); ASSERT_EQUAL_(scan.point_cloud.x.size(),scan.point_cloud.intensity.size()); if (scan.point_cloud.x.empty()) return; this->mark_as_modified(); // Insert vs. load and replace: if (!insertionOptions.addToExistingPointsMap) resize(0); // Resize to 0 instead of clear() so the std::vector<> memory is not actually deallocated and can be reused. // Alloc space: const size_t nOldPtsCount = this->size(); const size_t nScanPts = scan.point_cloud.size(); const size_t nNewPtsCount = nOldPtsCount + nScanPts; this->resize(nNewPtsCount); const float K = 1.0f / 255; // Intensity scale. // global 3D pose: CPose3D sensorGlobalPose; if (robotPose) sensorGlobalPose = *robotPose + scan.sensorPose; else sensorGlobalPose = scan.sensorPose; mrpt::math::CMatrixDouble44 HM; sensorGlobalPose.getHomogeneousMatrix(HM); const double m00 = HM.get_unsafe(0,0), m01 = HM.get_unsafe(0,1), m02 = HM.get_unsafe(0,2), m03 = HM.get_unsafe(0,3); const double m10 = HM.get_unsafe(1,0), m11 = HM.get_unsafe(1,1), m12 = HM.get_unsafe(1,2), m13 = HM.get_unsafe(1,3); const double m20 = HM.get_unsafe(2,0), m21 = HM.get_unsafe(2,1), m22 = HM.get_unsafe(2,2), m23 = HM.get_unsafe(2,3); // Copy points: for (size_t i=0;isetPoint(nOldPtsCount+i, gx,gy,gz, // XYZ inten,inten,inten // RGB ); } } ocr/src/v1/model/VINResult.cpp1-10 #include "huaweicloud/ocr/v1/model/VINResult.h" namespace HuaweiCloud { namespace Sdk { namespace Ocr { namespace V1 { namespace Model { VINResult::VINResult() { vin_ = ""; vinIsSet_ = false; } VINResult::~VINResult() = default; void VINResult::validate() { } web::json::value VINResult::toJson() const { web::json::value val = web::json::value::object(); if(vinIsSet_) { val[utility::conversions::to_string_t("vin")] = ModelBase::toJson(vin_); } return val; } bool VINResult::fromJson(const web::json::value& val) { bool ok = true; if(val.has_field(utility::conversions::to_string_t("vin"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("vin")); if(!fieldValue.is_null()) { std::string refVal; ok &= ModelBase::fromJson(fieldValue, refVal); setVin(refVal); } } return ok; } std::string VINResult::getVin() const { return vin_; } void VINResult::setVin(const std::string& value) { vin_ = value; vinIsSet_ = true; } bool VINResult::vinIsSet() const { return vinIsSet_; } void VINResult::unsetvin() { vinIsSet_ = false; } } } } } } Skemba/alt-integration-cpp // Copyright (c) 2019-2020 // https://www.veriblock.org // Distributed under the MIT software license, see the accompanying // file LICENSE or http://www.opensource.org/licenses/mit-license.php. #include #include #include namespace altintegration { bool PayloadsIndex::getValidity(Slice containingBlockHash, Slice payloadId) const { auto key = makeGlobalPid(containingBlockHash, payloadId); auto it = _cgValidity.find(key); if (it == _cgValidity.end()) { // we don't know if this payload is invalid, so assume it is valid return true; } return it->second; } void PayloadsIndex::setValidity(Slice containingBlockHash, Slice payloadId, bool validity) { auto key = makeGlobalPid(containingBlockHash, payloadId); if (!validity) { _cgValidity[key] = validity; return; } auto it = _cgValidity.find(key); if (it != _cgValidity.end()) { // this saves some memory, because we assume that // anything that is not in this map is valid by default _cgValidity.erase(it); } // do nothing. any entry that is not in this map is valid by default } const std::set& PayloadsIndex::getContainingAltBlocks( const std::vector& payloadId) const { static const std::set empty; auto it = payload_in_alt.find(payloadId); if (it == payload_in_alt.end()) { return empty; } return it->second; } const std::set& PayloadsIndex::getContainingVbkBlocks( const std::vector& payloadId) const { static const std::set empty; auto it = payload_in_vbk.find(payloadId); if (it == payload_in_vbk.end()) { return empty; } return it->second; } void PayloadsIndex::addBlockToIndex(const BlockIndex& block) { auto containing = block.getHash(); for (auto& pid : block.getPayloadIds()) { this->addAltPayloadIndex(containing, pid.asVector()); } for (auto& pid : block.getPayloadIds()) { this->addAltPayloadIndex(containing, pid.asVector()); } for (auto& pid : block.getPayloadIds()) { this->addAltPayloadIndex(containing, pid.asVector()); } } void PayloadsIndex::addBlockToIndex(const BlockIndex& block) { auto containing = block.getHash(); for (auto& pid : block.getPayloadIds()) { this->addVbkPayloadIndex(containing, pid.asVector()); } } void PayloadsIndex::addAltPayloadIndex(const AltBlock::hash_t& containing, const std::vector& payloadId) { payload_in_alt[payloadId].insert(containing); } void PayloadsIndex::addVbkPayloadIndex(const VbkBlock::hash_t& containing, const std::vector& payloadId) { payload_in_vbk[payloadId].insert(containing); } void PayloadsIndex::removeAltPayloadIndex( const AltBlock::hash_t& containing, const std::vector& payloadId) { payload_in_alt[payloadId].erase(containing); } void PayloadsIndex::removeVbkPayloadIndex( const VbkBlock::hash_t& containing, const std::vector& payloadId) { payload_in_vbk[payloadId].erase(containing); } void PayloadsIndex::removePayloadsIndex(const BlockIndex& block) { auto containingHash = block.getHash(); for (auto& c : block.getPayloadIds()) { removeAltPayloadIndex(containingHash, c.asVector()); } for (auto& c : block.getPayloadIds()) { removeAltPayloadIndex(containingHash, c.asVector()); } for (auto& c : block.getPayloadIds()) { removeAltPayloadIndex(containingHash, c.asVector()); } } void PayloadsIndex::removePayloadsIndex(const BlockIndex& block) { auto containingHash = block.getHash(); for (auto& c : block.getPayloadIds()) { removeVbkPayloadIndex(containingHash, c.asVector()); } } void PayloadsIndex::reindex(const AltBlockTree& tree) { payload_in_alt.clear(); payload_in_vbk.clear(); // reindex vbk blocks auto& vbkblocks = tree.vbk().getBlocks(); VBK_LOG_WARN("Reindexing %d VBK blocks...", vbkblocks.size()); for (auto& b : vbkblocks) { addBlockToIndex(*b.second); } // reindex alt blocks auto& altblocks = tree.getBlocks(); VBK_LOG_WARN("Reindexing %d ALT blocks...", altblocks.size()); for (auto& b : altblocks) { addBlockToIndex(*b.second); } VBK_LOG_WARN("Reindexing finished"); } std::vector PayloadsIndex::makeGlobalPid( Slice a, Slice b) const { std::vector key; key.reserve(a.size() + b.size()); key.insert(key.end(), a.begin(), a.end()); key.insert(key.end(), b.begin(), b.end()); VBK_ASSERT(key.size() == a.size() + b.size()); return key; } const std::map, std::set>& PayloadsIndex::getPayloadsInAlt() const { return payload_in_alt; } const std::map, std::set>& PayloadsIndex::getPayloadsInVbk() const { return payload_in_vbk; } const std::unordered_map, bool>& PayloadsIndex::getValidity() const { return _cgValidity; } } // namespace altintegration // Copyright 2019, Nawin #include "Workspace.h" #include void BankAccount::deposit(int amount) { balance_ += amount; std::cout << "deposited " << amount << " , balance is now " << balance_ << '\n'; } bool BankAccount::withdraw(int amount) { if (balance_ - amount >= overdraft_limit_) { balance_ -= amount; std::cout << "witdrew " << amount << " , balance is now " << balance_ << '\n'; return true; } return false; } void BankAccountCommand::call() { switch (action_) { case BankAccountCommand::deposit: account_.deposit(amount_); break; case BankAccountCommand::withdraw: withdrawal_succeeded_ = account_.withdraw(amount_); break; default: break; } } void BankAccountCommand::undo() { switch (action_) { case BankAccountCommand::deposit: account_.withdraw(amount_); break; case BankAccountCommand::withdraw: if (withdrawal_succeeded_) account_.deposit(amount_); break; default: break; } } void CompositeBankAccountCommand::call() { for (auto& cmd : *this) cmd.call(); } void CompositeBankAccountCommand::undo() { for (auto it = rbegin(); it != rend(); ++it) it->undo(); } void Creature::process_command(const CreatureCommand& cc) { int* ability; switch (cc.ability_) { case CreatureAbility::strenght: ability = &strength_; break; case CreatureAbility::agility: ability = &agility_; break; default: break; } switch (cc.action_) { case CreatureCommand::set: *ability = cc.amount_; break; case CreatureCommand::increaseBy: *ability += cc.amount_; break; case CreatureCommand::decreaseBy: *ability -= cc.amount_; default: break; } } int Creature::process_query(CreatureQuery& q) const { switch (q.ability_) { case CreatureAbility::agility: q.value_ = agility_; return agility_; case CreatureAbility::strenght: q.value_ = strength_; return strength_; default: return 0; break; } } void Creature::set_strength(int strength) { process_command(CreatureCommand{ CreatureCommand::set, CreatureAbility::strenght, strength }); }/*F*************************************************************************** * * openSMILE - the Munich open source Multimedia Interpretation by * Large-scale Extraction toolkit * * This file is part of openSMILE. * * openSMILE is copyright (c) by audEERING GmbH. All rights reserved. * * See file "COPYING" for details on usage rights and licensing terms. * By using, copying, editing, compiling, modifying, reading, etc. this * file, you agree to the licensing terms in the file COPYING. * If you do not agree to the licensing terms, * you must immediately destroy all copies of this file. * * THIS SOFTWARE COMES "AS IS", WITH NO WARRANTIES. THIS MEANS NO EXPRESS, * IMPLIED OR STATUTORY WARRANTY, INCLUDING WITHOUT LIMITATION, WARRANTIES OF * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ANY WARRANTY AGAINST * INTERFERENCE WITH YOUR ENJOYMENT OF THE SOFTWARE OR ANY WARRANTY OF TITLE * OR NON-INFRINGEMENT. THERE IS NO WARRANTY THAT THIS SOFTWARE WILL FULFILL * ANY OF YOUR PARTICULAR PURPOSES OR NEEDS. ALSO, YOU MUST PASS THIS * DISCLAIMER ON WHENEVER YOU DISTRIBUTE THE SOFTWARE OR DERIVATIVE WORKS. * NEITHER TUM NOR ANY CONTRIBUTOR TO THE SOFTWARE WILL BE LIABLE FOR ANY * DAMAGES RELATED TO THE SOFTWARE OR THIS LICENSE AGREEMENT, INCLUDING * DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL OR INCIDENTAL DAMAGES, TO THE * MAXIMUM EXTENT THE LAW PERMITS, NO MATTER WHAT LEGAL THEORY IT IS BASED ON. * ALSO, YOU MUST PASS THIS LIMITATION OF LIABILITY ON WHENEVER YOU DISTRIBUTE * THE SOFTWARE OR DERIVATIVE WORKS. * * Main authors: , , * , * * Copyright (c) 2008-2013, * Institute for Human-Machine Communication, * Technische Universitaet Muenchen, Germany * * Copyright (c) 2013-2015, * audEERING UG (haftungsbeschraenkt), * Gilching, Germany * * Copyright (c) 2016, * audEERING GmbH, * Gilching Germany ***************************************************************************E*/ /* openCV_OpticalFlow Author: */ #ifndef OPENCV_OPTICALFLOW_HPP_ #define OPENCV_OPTICALFLOW_HPP_ #ifdef HAVE_OPENCV #include "opencv2/objdetect/objdetect.hpp" #include "opencv2/highgui/highgui.hpp" #include "opencv2/imgproc/imgproc.hpp" #include "opencv2/video/video.hpp" namespace OpticalFlow { class FrameFtExtrParams{ public: //number of histogram bins for optical flow analysis int flo_bins; FLOAT_DMEM max_flow; //percentual maximum flow for histogram analysis (relative to image width) FLOAT_DMEM flow_downsample; //downsampling ratio for flow anaylsis (0.5 is half image size) }; /** * @function computeOpticalFlowHistogram * @brief Computes the optical flow histogram. */ inline std::vector computeOpticalFlowHistogram(cv::Mat& frame_gray_resized, cv::Mat& prevFrame_gray_resized, FrameFtExtrParams& params, int display, int normalize) { std::vector ft_vec; ft_vec.clear(); // ### OPTICAL FLOW ANALYSIS ########################################################################## //calculate optical flow histogram using current frame and previous frame. If no previous frame found, output empty histogram of suitable size. //TODO: How to distinguish between pan/zoom and character movement? cv::MatND flo_hist; cv::Scalar mean_flow(0, 0); cv::Scalar stddev_flow(0, 0); FLOAT_DMEM px_nrm_fact_x = 1.0f / static_cast(frame_gray_resized.cols); FLOAT_DMEM px_nrm_fact_y = 1.0f / static_cast(frame_gray_resized.rows); int fhist_size[] = {params.flo_bins}; FLOAT_DMEM f_ranges[] = {0.0, params.max_flow}; const FLOAT_DMEM *fhist_ranges[] = {f_ranges}; int fhist_channels[] = {0}; if (!prevFrame_gray_resized.empty()){ //std::cout << "Perform optical flow analysis\n"; cv::Mat flow_img, flo_abs; calcOpticalFlowFarneback(frame_gray_resized, prevFrame_gray_resized, flow_img, 0.5, 5, 10, 10, 5, 1.0, cv::OPTFLOW_FARNEBACK_GAUSSIAN); //convert into an image of screen-relative displacements for (int cidx = 0; cidx < flow_img.cols; cidx++){ for (int ridx = 0; ridx < flow_img.rows; ridx++){ cv::Point2f pixgrad = flow_img.at(ridx, cidx); pixgrad.x *= px_nrm_fact_x; pixgrad.y *= px_nrm_fact_y; flow_img.at(ridx, cidx) = pixgrad; } } cv::meanStdDev(flow_img, mean_flow, stddev_flow); //std::cout << mean_flow << ", " << stddev_flow << "\n"; flo_abs.create(flow_img.rows, flow_img.cols, CV_32FC1); FLOAT_DMEM max_x = 0; FLOAT_DMEM max_y = 0; //get amount of flow for each pixel for (int cidx = 0; cidx < flow_img.cols; cidx++){ for (int ridx = 0; ridx < flow_img.rows; ridx++){ cv::Point2f pixgrad = flow_img.at(ridx, cidx); //pixgrad.x -= mean_flow.at(0); //pixgrad.y -= mean_flow.at(1); flo_abs.at(ridx, cidx) = sqrt(pixgrad.x*pixgrad.x + pixgrad.y*pixgrad.y); max_x = std::max(max_x, std::abs(pixgrad.x)); max_y = std::max(max_y, std::abs(pixgrad.y)); } } //std::cout << "Maximum gradients " << max_x << ", " << max_y << "\n"; //TODO: Find absolute normalization scheme cv::Mat flo_nrm; cv::normalize(flo_abs, flo_nrm, 0, 255, cv::NORM_MINMAX, CV_8UC1); cv::Mat tmp_disp_img = flo_nrm.clone(); if(display) { cv::imshow("DenseOpticalFlow", tmp_disp_img); } //get optical flow amount histogram cv::calcHist(&flo_abs, 1, fhist_channels, cv::Mat(), flo_hist, 1, fhist_size, fhist_ranges, true); if(normalize == 1) { cv::normalize(flo_hist, flo_hist, 1, 0, cv::NORM_L1, -1, cv::Mat()); // L1-norm } //std::vector flo_zero_hist(par.flo_bins, 0); //flo_hist = cv::Mat(flo_zero_hist); } else { std::cout << "Skip optical flow analysis, no previous frame stored\n"; std::vector flo_zero_hist(params.flo_bins, 0); flo_hist = cv::Mat(flo_zero_hist); } ft_vec.push_back(mean_flow[0]); ft_vec.push_back(mean_flow[1]); ft_vec.push_back(stddev_flow[0]); ft_vec.push_back(stddev_flow[1]); for (int i = 0; i < params.flo_bins; i++){ ft_vec.push_back(flo_hist.at(i)); } return ft_vec; } } // End namespace OpticalFlow #endif // HAVE_OPENCV #endif /* OPENCV_OPTICALFLOW_HPP_ */ stoimenoff/OOP-Cpp #include #include "personalassistant.h" using namespace std; int main() { string name; cout << "Enter your name:" << endl; getline(cin, name); cout << "Hello, " << name << "!" << endl; //PersonalAssistant kiro(name); PersonalAssistant* assistant = PersonalAssistant::instance(name); string command; cout << ">>"; getline(cin, command); while(command != "exit") { //cout << kiro.processCommand(command) << endl; cout << assistant->processCommand(command) << endl; cout << ">>"; getline(cin, command); } //kiro.writeChanges(); assistant->writeChanges(); return 0; }// This is an open source non-commercial project. Dear PVS-Studio, please check it. // PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com #include "QtIrbis.h" //========================================================= QTextCodec* IrbisEncoding::_ansi = nullptr; QTextCodec* IrbisEncoding::_utf = nullptr; QTextCodec* IrbisEncoding::ansi() { if (!_ansi) { _ansi = QTextCodec::codecForName("windows-1251"); } return _ansi; } QString IrbisEncoding::fromAnsi(const QByteArray &bytes) { return ansi()->toUnicode(bytes); } QString IrbisEncoding::fromUtf(const QByteArray &bytes) { return utf()->toUnicode(bytes); } QByteArray IrbisEncoding::toAnsi(const QString &text) { return ansi()->fromUnicode(text); } QByteArray IrbisEncoding::toUtf(const QString &text) { return utf()->fromUnicode(text); } QTextCodec* IrbisEncoding::utf() { if (!_utf) { _utf = QTextCodec::codecForName("UTF-8"); } return _utf; } 0 #include "Sprite.h" #include "ResourceManager.h" Sprite::Sprite(SpriteType sprite) { m_texture = ResourceManager::getInstance().loadTexture(sprite.filename); m_columnCount = sprite.columnCount; m_rowCount = sprite.rowCount; m_animSpeed = sprite.animSpeed; m_sheetWidth = m_texture->as()->getWidth(); m_sheetHeight = m_texture->as()->getHeight(); m_spriteWidth = m_texture->as()->getWidth() / m_columnCount; m_spriteHeight = m_texture->as()->getHeight() / m_rowCount; } void Sprite::changeSprite(SpriteType sprite) { m_texture = ResourceManager::getInstance().loadTexture(sprite.filename); m_columnCount = sprite.columnCount; m_rowCount = sprite.rowCount; m_animSpeed = sprite.animSpeed; m_sheetWidth = m_texture->as()->getWidth(); m_sheetHeight = m_texture->as()->getHeight(); m_spriteWidth = m_texture->as()->getWidth() / m_columnCount; m_spriteHeight = m_texture->as()->getHeight() / m_rowCount; } void Sprite::updateUVRect(aie::Renderer2D* renderer) { //get size of single frame as percentage of total spritesheet float width = 1.0f / m_columnCount; float height = 1.0f / m_rowCount; //initialise renderer->setUVRect(width * m_currentCol, height * m_currentRow, width, height); //play animation if (m_timer > m_animSpeed) { ++m_currentCol; if (m_currentCol == m_columnCount) { ++m_currentRow; m_currentCol = 0; } if (m_currentRow == m_rowCount) m_currentRow = 0; renderer->setUVRect(width * m_currentCol, height * m_currentRow, width, height); m_timer = 0; } } void Sprite::draw(GameObject* gameObject, aie::Renderer2D* renderer) { updateUVRect(renderer); renderer->drawSpriteTransformed3x3(m_texture->as(), gameObject->getGlobalTransformFloat(), m_spriteWidth, m_spriteHeight); renderer->setUVRect(1, 1, 1, 1); //reset UV }/** * Copyright 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 "src/runtime/kernel/arm/base/argminmax_base.h" #include "schema/model_generated.h" #include "src/kernel_registry.h" using mindspore::kernel::KERNEL_ARCH::kCPU; using mindspore::lite::KernelRegistrar; using mindspore::lite::RET_ERROR; using mindspore::lite::RET_OK; using mindspore::schema::PrimitiveType_ArgMax; using mindspore::schema::PrimitiveType_ArgMin; namespace mindspore::kernel { int ArgMinMaxCPUKernel::Init() { arg_param_->data_type_ = kNumberTypeFloat32; if (!InferShapeDone()) { return RET_OK; } return ReSize(); } int ArgMinMaxCPUKernel::ReSize() { auto in_shape = in_tensors_.at(0)->shape(); auto dims_size = in_shape.size(); int axis = arg_param_->axis_ < 0 ? arg_param_->axis_ + dims_size : arg_param_->axis_; arg_param_->axis_ = axis; arg_param_->dims_size_ = dims_size; if (arg_param_->topk_ <= 0) { MS_LOG(ERROR) << "Invalid topk " << arg_param_->topk_; return RET_ERROR; } arg_param_->topk_ = MSMIN(arg_param_->topk_, in_shape.at(axis)); ComputeStrides(in_shape.data(), arg_param_->in_strides_, in_shape.size()); auto out_shape = out_tensors_.at(0)->shape(); ComputeStrides(out_shape.data(), arg_param_->out_strides_, out_shape.size()); return RET_OK; } int ArgMinMaxCPUKernel::Run() { auto input = in_tensors_.at(0); auto shape = input->shape(); auto input_data = input->data_c(); auto output_data = out_tensors_.at(0)->data_c(); void *output_value = nullptr; if (out_tensors_.size() == 2) { output_value = out_tensors_.at(1)->data_c(); } MS_ASSERT(context_->allocator != nullptr); if (arg_param_->topk_ > 1 || arg_param_->keep_dims_) { arg_param_->arg_elements_ = reinterpret_cast(context_->allocator->Malloc(sizeof(ArgElement) * shape[arg_param_->axis_])); if (arg_param_->arg_elements_ == nullptr) { MS_LOG(ERROR) << "malloc memory fail!"; return RET_ERROR; } } if (input->data_type() == kNumberTypeFloat32) { ArgMinMaxFp32(reinterpret_cast(input_data), reinterpret_cast(output_data), reinterpret_cast(output_value), shape.data(), arg_param_); #ifdef ENABLE_ARM64 } else if (input->data_type() == kNumberTypeFloat16) { ArgMinMaxFp16(reinterpret_cast(input_data), reinterpret_cast(output_data), reinterpret_cast(output_value), shape.data(), arg_param_); #endif } else { MS_LOG(ERROR) << "unsupported data type!"; } context_->allocator->Free(arg_param_->arg_elements_); arg_param_->arg_elements_ = nullptr; return RET_OK; } REG_KERNEL(kCPU, kNumberTypeFloat32, PrimitiveType_ArgMax, LiteKernelCreator) REG_KERNEL(kCPU, kNumberTypeFloat32, PrimitiveType_ArgMin, LiteKernelCreator) REG_KERNEL(kCPU, kNumberTypeFloat16, PrimitiveType_ArgMax, LiteKernelCreator) REG_KERNEL(kCPU, kNumberTypeFloat16, PrimitiveType_ArgMin, LiteKernelCreator) } // namespace mindspore::kernel Engine/src/renderer/fbopass.cpp #include "pch.h" #include "fbopass.h" #include "graphics/renderstate.h" namespace prev { static constexpr const char DEFAULT_FBO_VERTEX_SHADER[] = "res/shaders/fboDefaultVertex.hlsl"; static constexpr const char DEFAULT_FBO_PIXEL_SHADER[] = "res/shaders/fboDefaultPixel.hlsl"; FramebufferPass::FramebufferPass() { LoadShaders(); CreateVertexBuffer(); CreateVertexLayout(); } FramebufferPass::~FramebufferPass() { } void FramebufferPass::LoadShaders() { m_DefaultFBOVertexShader = ShaderManager::Ref().LoadVertexShaderFromFile("DEFAULT_FBO_VERTEX_SHADER", DEFAULT_FBO_VERTEX_SHADER); m_DefaultFBOPixelShader = ShaderManager::Ref().LoadPixelShaderFromFile("DEFAULT_FBO_PIXEL_SHADER", DEFAULT_FBO_PIXEL_SHADER); } void FramebufferPass::CreateVertexBuffer() { static const float vertices[] = { // Vertices TextureCoords -1.0f, 1.0f, 0.0f, 0.0f, //TopLeft 1.0f, -1.0f, 1.0f, 1.0f, //BottomRight -1.0f, -1.0f, 0.0f, 1.0f, //BottomLeft -1.0f, 1.0f, 0.0f, 0.0f, //TopLeft 1.0f, 1.0f, 1.0f, 0.0f, //TopRight 1.0f, -1.0f, 1.0f, 1.0f, //BottomRight }; m_VertexBuffer = VertexBuffer::CreateVertexBuffer(); m_VertexBuffer->Init((void *)vertices, 6, sizeof(float) * 4u, BUFFER_USAGE_STATIC); } void FramebufferPass::CreateVertexLayout() { m_VertexLayout = VertexLayout::CreateVertexLayout(); m_VertexLayout->BeginEntries(); m_VertexLayout->AddEntry(PV_DATA_TYPE_FLOAT_32, 2, 0, "POSITION", false); m_VertexLayout->AddEntry(PV_DATA_TYPE_FLOAT_32, 2, sizeof(float) * 2u, "TEXCOORDS", false); m_VertexLayout->EndEntries(m_DefaultFBOVertexShader); } void FramebufferPass::Pass(StrongHandle fbo, StrongHandle vShader, StrongHandle pShader) { if (fbo == nullptr) return; if (vShader == nullptr) vShader = m_DefaultFBOVertexShader; if (pShader == nullptr) pShader = m_DefaultFBOPixelShader; fbo->GetTexture()->SetTextureSlot(0); fbo->GetTexture()->Bind(); m_VertexLayout->Bind(); m_VertexBuffer->Bind(); vShader->Bind(); pShader->Bind(); BlendFunction bf = RenderState::Ref().GetBlendFunction(); BlendFunction nbf; nbf.DestBlend = PV_BLEND_ZERO; nbf.SrcBlend = PV_BLEND_ONE; nbf.Operation = PV_BLEND_OP_ADD; RenderState::Ref().SetBlendFunction(nbf); m_VertexBuffer->Draw(6, 0); RenderState::Ref().SetBlendFunction(bf); } void FramebufferPass::Pass(StrongHandle fbo, BlendFunction blendFunc, StrongHandle vShader, StrongHandle pShader) { if (fbo == nullptr) return; if (vShader == nullptr) vShader = m_DefaultFBOVertexShader; if (pShader == nullptr) pShader = m_DefaultFBOPixelShader; fbo->GetTexture()->SetTextureSlot(0); fbo->GetTexture()->Bind(); m_VertexLayout->Bind(); m_VertexBuffer->Bind(); vShader->Bind(); pShader->Bind(); BlendFunction bf = RenderState::Ref().GetBlendFunction(); RenderState::Ref().SetBlendFunction(blendFunc); m_VertexBuffer->Draw(6, 0); RenderState::Ref().SetBlendFunction(bf); } }#include "Auto.h" #include "Honda.h" #include int main() { using namespace std; using namespace cs52; cout << "------AUTO------" << endl; Auto a; a.insertKey(); a.turn(); a.drive(); cout << "------HONDA------" << endl; Honda h; h.insertKey(); h.turn(); h.drive(); cout << "doing the same thing with pointer variables..." << endl; Auto * ptrAuto = NULL; ptrAuto = &a; cout << "------PTRAUTO POINTING AT AN AUTO------" << endl; ptrAuto->insertKey(); ptrAuto->turn(); ptrAuto->drive(); ptrAuto = &h; cout << "------PTRAUTO POINTING AT AN HONDA------" << endl; // This is where the magic happens. // remember ptrAuto is a pointer to an Auto, not to a Honda // But since Auto has these marked as virtual functions, // the derived class's (Honda) functions are called! ptrAuto->insertKey(); ptrAuto->turn(); ptrAuto->drive(); return 0; } #include #include "xsrf_filter.h" #include "src/envoy/utils/session_manager.h" #include "common/protobuf/utility.h" #include "envoy/registry/registry.h" #include "envoy/server/filter_config.h" #include "src/envoy/utils/config.pb.validate.h" namespace Envoy { namespace Server { namespace Configuration { class XsrfFilterConfig : public NamedHttpFilterConfigFactory { private: HttpFilterFactoryCb createFilter(const Utils::Config::SessionManagerConfig& proto_config, FactoryContext& context) { Utils::SessionManager::SessionManagerPtr session_manager = std::make_shared(proto_config); Upstream::ClusterManager& cm = context.clusterManager(); return [&cm, session_manager](Http::FilterChainFactoryCallbacks& callbacks) -> void { callbacks.addStreamDecoderFilter( std::make_shared(cm, session_manager)); }; } public: HttpFilterFactoryCb createFilterFactory(const Json::Object &config, const std::string&, FactoryContext &context) override { Utils::Config::SessionManagerConfig proto_config; MessageUtil::loadFromJson(config.asJsonString(), proto_config); return createFilter(proto_config, context); } HttpFilterFactoryCb createFilterFactoryFromProto(const Protobuf::Message &proto_config, const std::string&, FactoryContext &context) override { return createFilter( MessageUtil::downcastAndValidate(proto_config), context); } ProtobufTypes::MessagePtr createEmptyConfigProto() override { return ProtobufTypes::MessagePtr{new Envoy::ProtobufWkt::Empty()}; } std::string name() override { return "xsrf"; } }; static Registry::RegisterFactory register_; } // Configuration } // Server } // Envoy project1/oppg_d.cc /** * Copyright (c) 2016 * This code is license under MIT license (see LICENSE for details) */ #include #include #include "tridiagonal.hh" typedef double number; /** Function [$f(x)$] */ number F(number x) { return 100 * exp(-10 * x); } /** Closed-form solution */ number G(number x) { return 1 - (1 - exp(-10)) * x - exp(-10 * x); } int main() { // list of N values to test const size_t Nlist[] = { 10, 100, 1000, 10000, 100000, 1000000, 10000000 }; const size_t Nlen = sizeof(Nlist) / sizeof(*Nlist); size_t N; // allocate dynamic memory in heap // (since 80MB is too much memory for stack) number *x = new number[10000001]; number *a = new number[10000001]; number *b = new number[10000001]; number *c = new number[10000001]; number *f = new number[10000001]; // open file to write to FILE *fp = fopen("d.dat", "w"); fprintf(fp, "log h\teps\n"); // generate and solve problem for 10x10, 100x100 and 1000x1000 for(size_t i = 0, N = Nlist[0]; i < Nlen; N = Nlist[++i]) { number h = 1.0 / (N + 1); // generate matrix [$A$] and vector [$\V{b}$] for(size_t i = 0; i <= N; i++) { x[i] = i * h; a[i] = -1; b[i] = 2; c[i] = -1; f[i] = h * h * F(x[i]); } // solve solve_tridiagonal(N + 1, a, b, c, f); // now f contains the solution, [$\V{v}$] // rename for convinience number *v = f; // write maximum relative erro number maxeps = 0; for(size_t i = 1; i <= N; i++) { number u = G(x[i]); number eps = log10(fabs((u - v[i]) / u)); if(eps > maxeps) maxeps = eps; } fprintf(fp, "%.0lf\t%.5E\n", log10(h), maxeps); } fclose(fp); // deallocate memory // (strictly speaking not necessary but let's be nice to the OS) delete[] x; delete[] a; delete[] b; delete[] c; delete[] f; } 1-10 //////////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2020 NovAtel 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. // //////////////////////////////////////////////////////////////////////////////// /*! \file timefilter.hpp * \brief * * Time filter will work based on the start and end time pairs configured in the filter configuration structure. * Each time pair has GPS Time in milliseconds and GPS Week where GPS Week is optional parameter. This filter allows * messages which have a time stamp within the range of start and end time. All remaining messages will be discarded. * */ //---------------------------------------------------------------------- // Recursive Inclusion //---------------------------------------------------------------------- #ifndef TIMEFILTER_HPP #define TIMEFILTER_HPP //---------------------------------------------------------------------- // Includes //---------------------------------------------------------------------- #include "messagedatafilter.hpp" /*! \class TimeFilter * \brief Provides API's to configure filter with message start and end time pairs. * * Derived from MessageDataFilter. */ class TimeFilter : public MessageDataFilter { public: /*! A Constructor * \brief Initialize filter count(Number of time filters) to 0. * Disable Negative time filtering. * Clears vector of start time pair and end time pair. * Here pair means((GPS time in milliseconds and GPS week) */ TimeFilter(); /*! A virtual destructor * \brief Clears vector of start time pair and end time pair. * Here pair means((GPS time in milliseconds and GPS week) */ virtual ~TimeFilter(); /*! \fn BOOL Filter(BaseMessageData& pclBaseMessageData) * \brief Gets the message Week and time in milli seconds and compare with configured pairs to filter. * \param [in] pclBaseMessageData BaseMessageData object * \return TRUE or FALSE. * \remark By default, messages with unknown and sattime statuses will always be passed. * If negative filter is enabled, the messages whitch are not in between start and end pair will be filtered. */ BOOL Filter(BaseMessageData& pclBaseMessageData); /*! \fn void ConfigureFilter(FilterConfig& stFilterConfig) * \brief Sets Start and End time pairs from given configuration. * Enable/Disable negative time filtering. * \param [in] stFilterConfig FilterConfig structure variable */ void ConfigureFilter(FilterConfig& stFilterConfig); /*! \fn DOUBLE GetFilterCount() * \return Number of time filters. */ DOUBLE GetFilterCount(); /*! \fn void Reset() * \brief Set time filter count to 0. */ void Reset(); friend class TimeFilterTest; private: DOUBLE dFilterCount; /**< Filter count(Number of time filters) variable */ /*! \fn void SetFilterCount() * \brief Increment filter count(Number of time filters) by 1. */ void SetFilterCount(); /**< Vector of Start time pair with message GNSS Week and time in milliseconds as key-value pair. */ std::vector < std::pair > ulMyStartPair; /**< Vector of End time pair with message GNSS Week and time in milliseconds as key-value pair. */ std::vector < std::pair > ulMyEndPair; /**< Enable or Disable negative time filtering. */ BOOL bMyIsNegativeTimeFilter; }; #endif // // BidirTOH.cpp // hog2 glut // // Created by on 2/14/17. // Copyright © 2017 University of Denver. All rights reserved. // #include "BidirTOH.h" #include "TOH.h" #include "TemplateAStar.h" #include "NBS.h" #include "MM.h" #include "BSStar.h" #include "WeightedVertexGraph.h" //// Builds two PDBs according to the sizes, plus 2 smaller pdbs that also cover the state space //template //Heuristic> *BuildPDB(const TOHState &goal) //{ // TOH toh; // TOH absToh1; // TOH absToh2; // TOH absToh3; // TOH absToh4; // TOHState absTohState1; // TOHState absTohState2; // // // TOHPDB *pdb1 = new TOHPDB(&absToh1, goal); // top disks // TOHPDB *pdb2 = new TOHPDB(&absToh2, goal); // bottom disks // TOHPDB *pdb3 = new TOHPDB(&absToh3, goal); // top disks // TOHPDB *pdb4 = new TOHPDB(&absToh4, goal); // top disks // pdb1->BuildPDB(goal, std::thread::hardware_concurrency()); // pdb2->BuildPDB(goal, std::thread::hardware_concurrency()); // pdb3->BuildPDB(goal, std::thread::hardware_concurrency()); // pdb4->BuildPDB(goal, std::thread::hardware_concurrency()); // // Heuristic> *h = new Heuristic>; // // h->lookups.resize(0); // // h->lookups.push_back({kMaxNode, 1, 2}); // h->lookups.push_back({kAddNode, 3, 2}); // h->lookups.push_back({kAddNode, 5, 2}); // h->lookups.push_back({kLeafNode, 0, 0}); // h->lookups.push_back({kLeafNode, 1, 1}); // h->lookups.push_back({kLeafNode, 2, 2}); // h->lookups.push_back({kLeafNode, 3, 3}); // h->heuristics.resize(0); // h->heuristics.push_back(pdb1); // h->heuristics.push_back(pdb2); // h->heuristics.push_back(pdb3); // h->heuristics.push_back(pdb4); // // return h; //} //// Builds two PDBs that are symmetric for the standard goal - but not necessarily for random goals //template //Heuristic> *BuildPDB(const TOHState &goal) //{ // TOH toh; // TOH absToh1; // TOH absToh2; // TOHState absTohState1; // TOHState absTohState2; // // // TOHPDB *pdb1 = new TOHPDB(&absToh1, goal); // top disks // TOHPDB *pdb2 = new TOHPDB(&absToh2, goal); // bottom disks // TOHPDB *pdb3 = new TOHPDB(&absToh2, goal); // top disks // TOHPDB *pdb4 = new TOHPDB(&absToh1, goal); // bottom disks // pdb1->BuildPDB(goal, std::thread::hardware_concurrency()); // pdb2->BuildPDB(goal, std::thread::hardware_concurrency()); // pdb3->BuildPDB(goal, std::thread::hardware_concurrency()); // pdb4->BuildPDB(goal, std::thread::hardware_concurrency()); // // Heuristic> *h = new Heuristic>; // // h->lookups.resize(0); // // h->lookups.push_back({kMaxNode, 1, 2}); // h->lookups.push_back({kAddNode, 3, 2}); // h->lookups.push_back({kAddNode, 5, 2}); // h->lookups.push_back({kLeafNode, 0, 0}); // h->lookups.push_back({kLeafNode, 1, 1}); // h->lookups.push_back({kLeafNode, 2, 2}); // h->lookups.push_back({kLeafNode, 3, 3}); // h->heuristics.resize(0); // h->heuristics.push_back(pdb1); // h->heuristics.push_back(pdb2); // h->heuristics.push_back(pdb3); // h->heuristics.push_back(pdb4); // // return h; //} // Builds two PDBs that are symmetric for the standard goal - but not necessarily for random goals template Heuristic> *BuildPDB(const TOHState &goal) { TOH toh; TOH absToh1; TOH absToh2; TOHState absTohState1; TOHState absTohState2; TOHPDB *pdb1 = new TOHPDB(&absToh1, goal); // top disks TOHPDB *pdb2 = new TOHPDB(&absToh2, goal); // bottom disks pdb1->BuildPDB(goal, std::thread::hardware_concurrency()); pdb2->BuildPDB(goal, std::thread::hardware_concurrency()); Heuristic> *h = new Heuristic>; h->lookups.resize(0); h->lookups.push_back({kAddNode, 1, 2}); h->lookups.push_back({kLeafNode, 0, 0}); h->lookups.push_back({kLeafNode, 1, 1}); h->heuristics.resize(0); h->heuristics.push_back(pdb1); h->heuristics.push_back(pdb2); return h; } template void TestTOH(int first, int last) { TemplateAStar, TOHMove, TOH> astar; NBS, TOHMove, TOH, NBSQueue, 0>> nbse0; NBS, TOHMove, TOH, NBSQueue, 1>> nbse1; MM, TOHMove, TOH> mm; BSStar, TOHMove, TOH> bs; TOH toh; TOHState s; TOHState g; std::vector> thePath; std::vector actionPath; Heuristic> *f; Heuristic> *b; ZeroHeuristic> z; // g.Reset(); // f = BuildPDB(g); int table[] = {52058078,116173544,208694125,131936966,141559500,133800745,194246206,50028346,167007978,207116816,163867037,119897198,201847476,210859515,117688410,121633885}; int table2[] = {145008714,165971878,154717942,218927374,182772845,5808407,19155194,137438954,13143598,124513215,132635260,39667704,2462244,41006424,214146208,54305743}; for (int count = first; count < last; count++) { printf("Seed: %d\n", table[count&0xF]^table2[(count>>4)&0xF]); srandom(table[count&0xF]^table2[(count>>4)&0xF]); s.counts[0] = s.counts[1] = s.counts[2] = s.counts[3] = 0; for (int x = N; x > 0; x--) { int whichPeg = random()%4; s.disks[whichPeg][s.counts[whichPeg]] = x; s.counts[whichPeg]++; } // b = BuildPDB(s); g.counts[0] = g.counts[1] = g.counts[2] = g.counts[3] = 0; for (int x = N; x > 0; x--) { int whichPeg = random()%4; g.disks[whichPeg][g.counts[whichPeg]] = x; g.counts[whichPeg]++; } // Using canonical goal currently - comment to use random goal //g.Reset(); // f = BuildPDB(g); Timer timer; // printf("Starting heuristics: %f %f\n", f->HCost(s, g), b->HCost(g, s)); std::cout << s << "\n"; std::cout << g << "\n"; if (0) { printf("-=-=-NBSe0-=-=-\n"); timer.StartTimer(); nbse0.GetPath(&toh, s, g, f, b, thePath); timer.EndTimer(); printf("I%d-%d-%d\t%d\t", N, pdb1Disks, count, (int)toh.GetPathLength(thePath)); printf("%llu nodes\t%llu necessary\t", nbse0.GetNodesExpanded(), nbse0.GetNecessaryExpansions()); printf("%1.2fs elapsed\n", timer.GetElapsedTime()); } if (0) { printf("-=-=-NBSe1-=-=-\n"); timer.StartTimer(); nbse1.GetPath(&toh, s, g, f, b, thePath); timer.EndTimer(); printf("I%d-%d-%d\t%d\t", N, pdb1Disks, count, (int)toh.GetPathLength(thePath)); printf("%llu nodes\t%llu necessary\t", nbse1.GetNodesExpanded(), nbse1.GetNecessaryExpansions()); printf("%1.2fs elapsed\n", timer.GetElapsedTime()); } if (1) { printf("-=-=-NBS0e1-=-=-\n"); timer.StartTimer(); nbse1.GetPath(&toh, s, g, &z, &z, thePath); timer.EndTimer(); printf("I%d-%d-%d\t%d\t", N, pdb1Disks, count, (int)toh.GetPathLength(thePath)); printf("%llu nodes\t%llu necessary\t", nbse1.GetNodesExpanded(), nbse1.GetNecessaryExpansions()); printf("%1.2fs elapsed\n", timer.GetElapsedTime()); } if (0) { BidirectionalProblemAnalyzer, TOHMove, TOH>::GetWeightedVertexGraph(s, g, &toh, f, b); } // if (1) // { // printf("-=-=-BS-=-=-\n"); // timer.StartTimer(); // bs.GetPath(&toh, s, g, f, b, thePath); // timer.EndTimer(); // printf("I%d-%d-%d\t%d\t", N, pdb1Disks, count, (int)toh.GetPathLength(thePath)); // printf("%llu nodes\t%llu necessary\t", bs.GetNodesExpanded(), bs.GetNecessaryExpansions()); // printf("%1.2fs elapsed\n", timer.GetElapsedTime()); // } // if (1) // { // printf("-=-=-MM-=-=-\n"); // timer.StartTimer(); // mm.GetPath(&toh, s, g, f, b, thePath); // timer.EndTimer(); // printf("I%d-%d-%d\t%d\t", N, pdb1Disks, count, (int)toh.GetPathLength(thePath)); // printf("%llu nodes\t%llu necessary\t", mm.GetNodesExpanded(), mm.GetNecessaryExpansions()); // printf("%1.2fs elapsed\n", timer.GetElapsedTime()); // } // if (1) // { // printf("-=-=-A*-=-=-\n"); // astar.SetHeuristic(f); // timer.StartTimer(); // astar.GetPath(&toh, s, g, thePath); // timer.EndTimer(); // printf("I%d-%d-%d\t%d\t", N, pdb1Disks, count, (int)toh.GetPathLength(thePath)); // printf("%llu nodes\t%llu necessary\t", astar.GetNodesExpanded(), astar.GetNecessaryExpansions()); // printf("%1.2fs elapsed\n", timer.GetElapsedTime()); // } // while (b->heuristics.size() > 0) // { // delete b->heuristics.back(); // b->heuristics.pop_back(); // } // delete b; // while (f->heuristics.size() > 0) // { // delete f->heuristics.back(); // f->heuristics.pop_back(); // } // delete f; } } void TOHTest() { // TestTOH<14, 2>(0, 50); TestTOH<14, 4>(0, 50); // TestTOH<14, 5>(0, 50); // TestTOH<14, 6>(0, 50); // TestTOH<14, 7>(0, 50); // TestTOH<14, 8>(0, 50); // TestTOH<14, 9>(0, 50); // TestTOH<14, 10>(0, 50); // const int numDisks = 16; // [disks - 2] (4^14 - 256 million) // const int pdb1Disks = 10; // const int pdb2Disks = 6; // TOH toh; // TOHState s, g; // // TOHState goal; // TOH absToh1; // TOH absToh2; // TOHState absTohState1; // TOHState absTohState2; // // TOHPDB pdb1(&absToh1); // top disks // TOHPDB pdb2(&absToh2); // bottom disks // // ZeroHeuristic> z; // // goal.Reset(); // pdb1.BuildPDB(goal, std::thread::hardware_concurrency()); // pdb2.BuildPDB(goal, std::thread::hardware_concurrency()); // //// s.Reset(); //// goal.Reset(); //// for (int x = 0; x < 100; x++) //// { //// std::vector actionPath; //// for (int x = 0; x < 20000; x++) //// { //// toh.GetActions(s, actionPath); //// toh.ApplyAction(s, actionPath[random()%actionPath.size()]); //// } //// std::cout << s << "\n"; //// std::cout << "H1: " << pdb1.HCost(s, goal) << "\n"; //// std::cout << "H2: " << pdb2.HCost(s, goal) << "\n"; //// } //// exit(0); // goal.Reset(); // Heuristic> h; // // h.lookups.resize(0); // h.lookups.push_back({kAddNode, 1, 2}); // h.lookups.push_back({kLeafNode, 0, 0}); // h.lookups.push_back({kLeafNode, 1, 1}); // h.heuristics.resize(0); // h.heuristics.push_back(&pdb1); // h.heuristics.push_back(&pdb2); // printf("-=-=-=-==-=-=-=-=-\n"); // printf("With %d and %d\n", pdb1Disks, pdb2Disks); // TestTOH(&h, 0, 10); // // printf("-=-=-=-==-=-=-=-=-\n"); // h.heuristics[1] = &z; // printf("With just %d\n", pdb1Disks); // TestTOH(&h, 0, 10); exit(0); } 10-100 /*========================================================================= Program: GDCM (Grassroots DICOM). A DICOM library Copyright (c) 2006-2011 All rights reserved. See Copyright.txt or http://gdcm.sourceforge.net/Copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "gdcmReader.h" #include /* openssl smime -encrypt -binary -aes256 -in outputfile.dcm -inform DER -out outputfile.der -outform DER ../trunk/Testing/Source/Data/certificate.pem openssl smime -decrypt -binary -in out.der -inform DER -out outputfile.dcm -outform DER -inkey ../trunk/Testing/Source/Data/privatekey.pem ../trunk/Testing/Source/Data/certificate.pem */ int main(int argc, char *argv[]) { if( argc < 3 ) { std::cerr << argv[0] << " input.dcm output.der" << std::endl; return 1; } const char *filename = argv[1]; const char *outfilename = argv[2]; gdcm::Reader reader; reader.SetFileName( filename ); if( !reader.Read() ) { return 1; } gdcm::File &file = reader.GetFile(); gdcm::DataSet &ds = file.GetDataSet(); const gdcm::DataElement &EncryptedAttributesSequence = ds.GetDataElement( gdcm::Tag( 0x0400,0x0500 ) ); gdcm::SequenceOfItems *sqi = EncryptedAttributesSequence.GetValueAsSQ(); if ( !sqi || sqi->GetNumberOfItems() != 1 ) return 1; gdcm::Item &item = sqi->GetItem(1); gdcm::DataSet &nestedds = item.GetNestedDataSet(); if( ! nestedds.FindDataElement( gdcm::Tag( 0x0400,0x0520) ) ) return 1; const gdcm::DataElement &EncryptedContent = nestedds.GetDataElement( gdcm::Tag( 0x0400,0x0520) ); const gdcm::ByteValue *bv = EncryptedContent.GetByteValue(); std::ofstream of( outfilename, std::ios::binary ); of.write( bv->GetPointer(), bv->GetLength() ); of.close(); return 0; } //#include "../core/core_headers.h" #include "../core/cistem_constants.h" #include "../core/gui_core_headers.h" // extern MyMovieAssetPanel *movie_asset_panel; extern MyImageAssetPanel* image_asset_panel; extern MyVolumeAssetPanel* volume_asset_panel; extern MyRunProfilesPanel* run_profiles_panel; extern MyMainFrame* main_frame; extern MatchTemplateResultsPanel* match_template_results_panel; RefineTemplateDevPanel::RefineTemplateDevPanel(wxWindow* parent) : RefineTemplateDevPanelParent(parent) { // Set variables my_job_id = -1; running_job = false; group_combo_is_dirty = false; run_profiles_are_dirty = false; all_input_images_have_match_template_result = false; SetInfo( ); FillGroupComboBox( ); FillRunProfileComboBox( ); wxSize input_size = InputSizer->GetMinSize( ); input_size.x += wxSystemSettings::GetMetric(wxSYS_VSCROLL_X); input_size.y = -1; ExpertPanel->SetMinSize(input_size); ExpertPanel->SetSize(input_size); ResetDefaults( ); // EnableMovieProcessingIfAppropriate(); result_bitmap.Create(1, 1, 24); time_of_last_result_update = time(NULL); DefocusSearchRangeNumericCtrl->SetMinMaxValue(0.0f, FLT_MAX); DefocusSearchStepNumericCtrl->SetMinMaxValue(1.0f, FLT_MAX); PixelSizeSearchRangeNumericCtrl->SetMinMaxValue(0.0f, FLT_MAX); HighResolutionLimitNumericCtrl->SetMinMaxValue(0.0f, FLT_MAX); GroupComboBox->AssetComboBox->Bind(wxEVT_COMMAND_COMBOBOX_SELECTED, &RefineTemplateDevPanel::OnGroupComboBox, this); } bool RefineTemplateDevPanel::CheckGroupHasTemplateMatchRunDone( ) { wxArrayLong images_with_template_match_result = main_frame->current_project.database.ReturnLongArrayFromSelectCommand("SELECT DISTINCT IMAGE_ASSET_ID FROM TEMPLATE_MATCH_LIST"); long current_image_id; int images_with_template_match_counter; bool image_was_found; for ( int image_in_group_counter = 0; image_in_group_counter < image_asset_panel->ReturnGroupSize(GroupComboBox->GetSelection( )); image_in_group_counter++ ) { current_image_id = image_asset_panel->all_assets_list->ReturnAssetPointer(image_asset_panel->ReturnGroupMember(GroupComboBox->GetSelection( ), image_in_group_counter))->asset_id; image_was_found = false; for ( images_with_template_match_counter = 0; images_with_template_match_counter < images_with_template_match_result.GetCount( ); images_with_template_match_counter++ ) { if ( images_with_template_match_result[images_with_template_match_counter] == current_image_id ) { image_was_found = true; break; } } if ( image_was_found == false ) return false; } return true; } void RefineTemplateDevPanel::ResetAllDefaultsClick(wxCommandEvent& event) { ResetDefaults( ); } void RefineTemplateDevPanel::OnInfoURL(wxTextUrlEvent& event) { const wxMouseEvent& ev = event.GetMouseEvent( ); // filter out mouse moves, too many of them if ( ev.Moving( ) ) return; long start = event.GetURLStart( ); wxTextAttr my_style; InfoText->GetStyle(start, my_style); // Launch the URL wxLaunchDefaultBrowser(my_style.GetURL( )); } void RefineTemplateDevPanel::Reset( ) { ProgressBar->SetValue(0); TimeRemainingText->SetLabel("Time Remaining : ???h:??m:??s"); CancelAlignmentButton->Show(true); FinishButton->Show(false); ProgressPanel->Show(false); StartPanel->Show(true); OutputTextPanel->Show(false); output_textctrl->Clear( ); ResultsPanel->Show(false); InputPanel->Show(true); //graph_is_hidden = true; InfoPanel->Show(true); ResultsPanel->Clear(true); if ( running_job == true ) { main_frame->job_controller.KillJob(my_job_id); cached_results.Clear( ); running_job = false; } ResetDefaults( ); Layout( ); } void RefineTemplateDevPanel::ResetDefaults( ) { MinPeakRadiusNumericCtrl->ChangeValueFloat(10.0f); RemoveShiftedPeaksNoRadio->SetValue(true); PeakChangeThresholdNumericTextCtrl->ChangeValueFloat(10.0f); // TODO: set clever defaults active_group.CopyFrom(&image_asset_panel->all_groups_list->groups[GroupComboBox->GetSelection( )]); if ( active_group.number_of_members > 0 ) { ImageAsset* current_image; current_image = image_asset_panel->all_assets_list->ReturnImageAssetPointer(image_asset_panel->ReturnGroupMember(GroupComboBox->GetSelection( ), 0)); // first image in group HighResolutionLimitNumericCtrl->ChangeValueFloat(2.0f * current_image->pixel_size); int job_id = main_frame->current_project.database.ReturnSingleLongFromSelectCommand(wxString::Format("SELECT TEMPLATE_MATCH_ID FROM TEMPLATE_MATCH_LIST WHERE IMAGE_ASSET_ID=%i AND IS_ACTIVE=1", current_image->asset_id)); TemplateMatchJobResults result_for_first_image; result_for_first_image = main_frame->current_project.database.GetTemplateMatchingResultByID(job_id); PeakSelectionThresholdNumericCtrl->ChangeValueFloat(result_for_first_image.used_threshold * 0.94f); PeakPlottingThresholdNumericCtrl->ChangeValueFloat(result_for_first_image.used_threshold); MaskRadiusNumericTextCtrl->ChangeValueFloat(result_for_first_image.reference_box_size_in_angstroms / 2.0f); } else { HighResolutionLimitNumericCtrl->ChangeValueFloat(2.0f); PeakSelectionThresholdNumericCtrl->ChangeValueFloat(7.5f); PeakPlottingThresholdNumericCtrl->ChangeValueFloat(8.0f); MaskRadiusNumericTextCtrl->ChangeValueFloat(200.0f); } OutofPlaneStepNumericCtrl->ChangeValueFloat(0.2); InPlaneStepNumericCtrl->ChangeValueFloat(0.1); DefocusSearchYesRadio->SetValue(true); DefocusSearchRangeNumericCtrl->ChangeValueFloat(200.0f); DefocusSearchStepNumericCtrl->ChangeValueFloat(10.0f); // AssetGroup active_group; } void RefineTemplateDevPanel::OnGroupComboBox(wxCommandEvent& event) { // ResetDefaults(); // AssetGroup active_group; active_group.CopyFrom(&image_asset_panel->all_groups_list->groups[GroupComboBox->GetSelection( )]); if ( active_group.number_of_members > 0 ) { ImageAsset* current_image; current_image = image_asset_panel->all_assets_list->ReturnImageAssetPointer(image_asset_panel->ReturnGroupMember(GroupComboBox->GetSelection( ), 0)); // first image in group HighResolutionLimitNumericCtrl->ChangeValueFloat(2.0f * current_image->pixel_size); int job_id = main_frame->current_project.database.ReturnSingleLongFromSelectCommand(wxString::Format("SELECT TEMPLATE_MATCH_ID FROM TEMPLATE_MATCH_LIST WHERE IMAGE_ASSET_ID=%i AND IS_ACTIVE=1", current_image->asset_id)); if ( job_id > 0 ) { TemplateMatchJobResults result_for_first_image; result_for_first_image = main_frame->current_project.database.GetTemplateMatchingResultByID(job_id); PeakSelectionThresholdNumericCtrl->ChangeValueFloat(result_for_first_image.used_threshold * 0.94f); PeakPlottingThresholdNumericCtrl->ChangeValueFloat(result_for_first_image.used_threshold); MaskRadiusNumericTextCtrl->ChangeValueFloat(result_for_first_image.reference_box_size_in_angstroms / 2.0f); } else { HighResolutionLimitNumericCtrl->ChangeValueFloat(2.0f); PeakSelectionThresholdNumericCtrl->ChangeValueFloat(7.5f); PeakPlottingThresholdNumericCtrl->ChangeValueFloat(8.0f); MaskRadiusNumericTextCtrl->ChangeValueFloat(200.0f); } } else { HighResolutionLimitNumericCtrl->ChangeValueFloat(2.0f); PeakSelectionThresholdNumericCtrl->ChangeValueFloat(7.5f); PeakPlottingThresholdNumericCtrl->ChangeValueFloat(8.0f); MaskRadiusNumericTextCtrl->ChangeValueFloat(200.0f); } if ( GroupComboBox->GetCount( ) > 0 && main_frame->current_project.is_open == true ) all_input_images_have_match_template_result = CheckGroupHasTemplateMatchRunDone( ); if ( all_input_images_have_match_template_result == true && InputErrorText->IsShown( ) == true ) { InputErrorText->Show(false); Layout( ); } else if ( all_input_images_have_match_template_result == false && InputErrorText->IsShown( ) == false ) { InputErrorText->Show(true); Layout( ); } } void RefineTemplateDevPanel::SetInfo( ) { /* #include "icons/ctffind_definitions.cpp" #include "icons/ctffind_diagnostic_image.cpp" #include "icons/ctffind_example_1dfit.cpp" wxLogNull *suppress_png_warnings = new wxLogNull; wxBitmap definitions_bmp = wxBITMAP_PNG_FROM_DATA(ctffind_definitions); wxBitmap diagnostic_image_bmp = wxBITMAP_PNG_FROM_DATA(ctffind_diagnostic_image); wxBitmap example_1dfit_bmp = wxBITMAP_PNG_FROM_DATA(ctffind_example_1dfit); delete suppress_png_warnings;*/ InfoText->GetCaret( )->Hide( ); InfoText->BeginSuppressUndo( ); InfoText->BeginAlignment(wxTEXT_ALIGNMENT_CENTRE); InfoText->BeginBold( ); InfoText->BeginUnderline( ); InfoText->BeginFontSize(14); InfoText->WriteText(wxT("Refine Templates")); InfoText->EndFontSize( ); InfoText->EndBold( ); InfoText->EndUnderline( ); InfoText->Newline( ); InfoText->Newline( ); InfoText->EndAlignment( ); InfoText->BeginAlignment(wxTEXT_ALIGNMENT_LEFT); InfoText->WriteText(wxT("Refine results from a template matching run.")); InfoText->Newline( ); InfoText->Newline( ); InfoText->EndAlignment( ); InfoText->BeginAlignment(wxTEXT_ALIGNMENT_CENTRE); InfoText->BeginBold( ); InfoText->BeginUnderline( ); InfoText->WriteText(wxT("Program Options")); InfoText->EndBold( ); InfoText->EndUnderline( ); InfoText->Newline( ); InfoText->Newline( ); InfoText->EndAlignment( ); InfoText->BeginAlignment(wxTEXT_ALIGNMENT_LEFT); InfoText->BeginBold( ); InfoText->WriteText(wxT("Input Group : ")); InfoText->EndBold( ); InfoText->WriteText(wxT("The group of image assets to look for templates in")); InfoText->Newline( ); InfoText->BeginBold( ); InfoText->WriteText(wxT("Reference Volume : ")); InfoText->EndBold( ); InfoText->WriteText(wxT("The volume that will used for the template search.")); InfoText->Newline( ); InfoText->BeginBold( ); InfoText->WriteText(wxT("Run Profile : ")); InfoText->EndBold( ); InfoText->WriteText(wxT("The selected run profile will be used to run the job. The run profile describes how the job should be run (e.g. how many processors should be used, and on which different computers). Run profiles are set in the Run Profile panel, located under settings.")); InfoText->Newline( ); InfoText->Newline( ); InfoText->EndAlignment( ); InfoText->BeginAlignment(wxTEXT_ALIGNMENT_CENTRE); InfoText->BeginBold( ); InfoText->BeginUnderline( ); InfoText->WriteText(wxT("Expert Options")); InfoText->EndBold( ); InfoText->EndUnderline( ); InfoText->Newline( ); InfoText->Newline( ); InfoText->EndAlignment( ); InfoText->BeginAlignment(wxTEXT_ALIGNMENT_LEFT); InfoText->BeginBold( ); InfoText->WriteText(wxT("Out of Plane Angular Step : ")); InfoText->EndBold( ); InfoText->WriteText(wxT("The angular step that should be used for the out of plane search. Smaller values may increase accuracy, but will significantly increase the required processing time.")); InfoText->Newline( ); InfoText->BeginBold( ); InfoText->WriteText(wxT("In Plane Angular Step : ")); InfoText->EndBold( ); InfoText->WriteText(wxT("The angular step that should be used for the in plane search. As with the out of plane angle, smaller values may increase accuracy, but will significantly increase the required processing time.")); InfoText->Newline( ); InfoText->Newline( ); InfoText->EndAlignment( ); InfoText->BeginAlignment(wxTEXT_ALIGNMENT_CENTRE); InfoText->BeginBold( ); InfoText->BeginUnderline( ); InfoText->WriteText(wxT("References")); InfoText->EndBold( ); InfoText->EndUnderline( ); InfoText->Newline( ); InfoText->Newline( ); InfoText->EndAlignment( ); InfoText->BeginAlignment(wxTEXT_ALIGNMENT_LEFT); InfoText->BeginBold( ); InfoText->WriteText(wxT("., ., .")); InfoText->EndBold( ); InfoText->WriteText(wxT(" 2017. Single-protein detection in crowded molecular environments in cryo-EM images. Elife 6, e25648.. ")); InfoText->BeginURL("http://doi.org/10.7554/eLife.25648"); InfoText->BeginUnderline( ); InfoText->BeginTextColour(*wxBLUE); InfoText->WriteText(wxT("doi:10.7554/eLife.25648")); InfoText->EndURL( ); InfoText->EndTextColour( ); InfoText->EndUnderline( ); InfoText->Newline( ); InfoText->Newline( ); InfoText->EndSuppressUndo( ); } void RefineTemplateDevPanel::FillGroupComboBox( ) { GroupComboBox->FillComboBox(true); if ( GroupComboBox->GetCount( ) > 0 && main_frame->current_project.is_open == true ) all_input_images_have_match_template_result = CheckGroupHasTemplateMatchRunDone( ); if ( all_input_images_have_match_template_result == true && InputErrorText->IsShown( ) == true ) { InputErrorText->Show(false); Layout( ); } else if ( all_input_images_have_match_template_result == false && InputErrorText->IsShown( ) == false ) { InputErrorText->Show(true); Layout( ); } } void RefineTemplateDevPanel::FillRunProfileComboBox( ) { RunProfileComboBox->FillWithRunProfiles( ); } void RefineTemplateDevPanel::OnUpdateUI(wxUpdateUIEvent& event) { // are there enough members in the selected group. if ( main_frame->current_project.is_open == false ) { RunProfileComboBox->Enable(false); GroupComboBox->Enable(false); StartEstimationButton->Enable(false); ReferenceSelectPanel->Enable(false); } else { //Enable(true); if ( running_job == false ) { RunProfileComboBox->Enable(true); GroupComboBox->Enable(true); ReferenceSelectPanel->Enable(true); if ( RunProfileComboBox->GetCount( ) > 0 ) { if ( image_asset_panel->ReturnGroupSize(GroupComboBox->GetSelection( )) > 0 && run_profiles_panel->run_profile_manager.ReturnTotalJobs(RunProfileComboBox->GetSelection( )) > 0 && all_input_images_have_match_template_result == true ) { StartEstimationButton->Enable(true); } else StartEstimationButton->Enable(false); } else { StartEstimationButton->Enable(false); } if ( DefocusSearchYesRadio->GetValue( ) == true ) { DefocusRangeStaticText->Enable(true); DefocusSearchRangeNumericCtrl->Enable(true); DefocusStepStaticText->Enable(true); DefocusSearchStepNumericCtrl->Enable(true); } else { DefocusRangeStaticText->Enable(false); DefocusSearchRangeNumericCtrl->Enable(false); DefocusStepStaticText->Enable(false); DefocusSearchStepNumericCtrl->Enable(false); } if ( RemoveShiftedPeaksYesRadio->GetValue( ) == true ) { ShiftThresholdStaticText->Enable(true); PeakChangeThresholdNumericTextCtrl->Enable(true); } else { ShiftThresholdStaticText->Enable(false); PeakChangeThresholdNumericTextCtrl->Enable(false); } } else { GroupComboBox->Enable(false); ReferenceSelectPanel->Enable(false); RunProfileComboBox->Enable(false); //StartAlignmentButton->SetLabel("Stop Job"); //StartAlignmentButton->Enable(true); } if ( group_combo_is_dirty == true ) { FillGroupComboBox( ); group_combo_is_dirty = false; } if ( run_profiles_are_dirty == true ) { FillRunProfileComboBox( ); run_profiles_are_dirty = false; } if ( volumes_are_dirty == true ) { ReferenceSelectPanel->FillComboBox( ); volumes_are_dirty = false; } } } void RefineTemplateDevPanel::StartEstimationClick(wxCommandEvent& event) { active_group.CopyFrom(&image_asset_panel->all_groups_list->groups[GroupComboBox->GetSelection( )]); int job_counter; int number_of_defocus_positions; int image_number_for_gui; int number_of_jobs_per_image_in_gui; double voltage_kV; double spherical_aberration_mm; double amplitude_contrast; double defocus1; double defocus2; double defocus_angle; double phase_shift; double iciness; int best_parameters_to_keep = 1; float padding = 1; float mask_radius_search = MaskRadiusNumericTextCtrl->ReturnValue( ); float min_peak_radius = MinPeakRadiusNumericCtrl->ReturnValue( ); float shift_threshold = PeakChangeThresholdNumericTextCtrl->ReturnValue( ); bool exclude_based_on_shift = RemoveShiftedPeaksYesRadio->GetValue( ); float wanted_threshold = PeakSelectionThresholdNumericCtrl->ReturnValue( ); float result_threshold = PeakPlottingThresholdNumericCtrl->ReturnValue( ); input_image_filenames.Clear( ); cached_results.Clear( ); ResultsPanel->Clear(true); // Package the job details.. ImageAsset* current_image; VolumeAsset* current_volume; current_volume = volume_asset_panel->ReturnAssetPointer(ReferenceSelectPanel->GetSelection( )); ref_box_size_in_pixels = current_volume->x_size / current_volume->pixel_size; float wanted_out_of_plane_angular_step = OutofPlaneStepNumericCtrl->ReturnValue( ); float wanted_in_plane_angular_step = InPlaneStepNumericCtrl->ReturnValue( ); float defocus_search_range; float defocus_step; float pixel_size_search_range; float pixel_size_step; if ( DefocusSearchYesRadio->GetValue( ) == true ) { defocus_search_range = DefocusSearchRangeNumericCtrl->ReturnValue( ); defocus_step = DefocusSearchStepNumericCtrl->ReturnValue( ); } else { defocus_search_range = 0.0f; defocus_step = 0.0f; } RunProfile active_refinement_run_profile = run_profiles_panel->run_profile_manager.run_profiles[RunProfileComboBox->GetSelection( )]; int number_of_processes = active_refinement_run_profile.ReturnTotalJobs( ) - 1; // how many jobs are there going to be.. // get first image to make decisions about how many jobs.. .we assume this is representative. current_image = image_asset_panel->ReturnAssetPointer(active_group.members[0]); #ifdef USEGPU number_of_jobs_per_image_in_gui = 1; int number_of_jobs = number_of_processes; #else int number_of_jobs = active_group.number_of_members; #endif // Some settings for testing // float defocus_search_range = 1200.0f; // float defocus_step = 200.0f; // number of rotations current_job_package.Reset(active_refinement_run_profile, "refine_template", number_of_jobs); expected_number_of_results = active_group.number_of_members; number_of_received_results = 0; // loop over all images.. OneSecondProgressDialog* my_progress_dialog = new OneSecondProgressDialog("Preparing Job", "Preparing Job...", active_group.number_of_members, this, wxPD_REMAINING_TIME | wxPD_AUTO_HIDE | wxPD_APP_MODAL); TemplateMatchJobResults input_result; TemplateMatchJobResults temp_result; temp_result.job_type = cistem::job_type::template_match_refinement; // float high_resolution_limit = resolution_limit; for ( int image_counter = 0; image_counter < active_group.number_of_members; image_counter++ ) { image_number_for_gui = image_counter + 1; // current image asset current_image = image_asset_panel->ReturnAssetPointer(active_group.members[image_counter]); // get the input result... long current_match_template_result_id = main_frame->current_project.database.ReturnSingleLongFromSelectCommand(wxString::Format("SELECT TEMPLATE_MATCH_ID FROM TEMPLATE_MATCH_LIST WHERE IMAGE_ASSET_ID=%i AND IS_ACTIVE=1", current_image->asset_id)); input_result = main_frame->current_project.database.GetTemplateMatchingResultByID(current_match_template_result_id); temp_result.input_job_id = current_match_template_result_id; int number_of_previous_template_matches = main_frame->current_project.database.ReturnNumberOfPreviousTemplateMatchesByAssetID(current_image->asset_id); main_frame->current_project.database.GetCTFParameters(current_image->ctf_estimation_id, voltage_kV, spherical_aberration_mm, amplitude_contrast, defocus1, defocus2, defocus_angle, phase_shift, iciness); wxString mip_output_file = main_frame->current_project.template_matching_asset_directory.GetFullPath( ); mip_output_file += wxString::Format("/%s_refined_mip_%i_%i.mrc", current_image->filename.GetName( ), current_image->asset_id, number_of_previous_template_matches); wxString best_psi_output_file = main_frame->current_project.template_matching_asset_directory.GetFullPath( ); best_psi_output_file += wxString::Format("/%s_refined_psi_%i_%i.mrc", current_image->filename.GetName( ), current_image->asset_id, number_of_previous_template_matches); wxString best_theta_output_file = main_frame->current_project.template_matching_asset_directory.GetFullPath( ); best_theta_output_file += wxString::Format("/%s_refined_theta_%i_%i.mrc", current_image->filename.GetName( ), current_image->asset_id, number_of_previous_template_matches); wxString best_phi_output_file = main_frame->current_project.template_matching_asset_directory.GetFullPath( ); best_phi_output_file += wxString::Format("/%s_refined_phi_%i_%i.mrc", current_image->filename.GetName( ), current_image->asset_id, number_of_previous_template_matches); wxString best_defocus_output_file = main_frame->current_project.template_matching_asset_directory.GetFullPath( ); best_defocus_output_file += wxString::Format("/%s_refined_defocus_%i_%i.mrc", current_image->filename.GetName( ), current_image->asset_id, number_of_previous_template_matches); wxString best_pixel_size_output_file = main_frame->current_project.template_matching_asset_directory.GetFullPath( ); best_pixel_size_output_file += wxString::Format("/%s_refined_pixel_size_%i_%i.mrc", current_image->filename.GetName( ), current_image->asset_id, number_of_previous_template_matches); wxString scaled_mip_output_file = main_frame->current_project.template_matching_asset_directory.GetFullPath( ); scaled_mip_output_file += wxString::Format("/%s_refined_scaled_mip_%i_%i.mrc", current_image->filename.GetName( ), current_image->asset_id, number_of_previous_template_matches); wxString output_histogram_file = ""; wxString output_result_file = main_frame->current_project.template_matching_asset_directory.GetFullPath( ); output_result_file += wxString::Format("/%s_refined_plotted_result_%i_%i.mrc", current_image->filename.GetName( ), current_image->asset_id, number_of_previous_template_matches); wxString correlation_variance_output_file = "/dev/null"; wxString input_search_image = current_image->filename.GetFullPath( ); wxString input_reconstruction = current_volume->filename.GetFullPath( ); float pixel_size = current_image->pixel_size; input_image_filenames.Add(input_search_image); float low_resolution_limit = 300.0f; temp_result.image_asset_id = current_image->asset_id; temp_result.job_name = wxString::Format("Refinement with %s", current_volume->filename.GetName( )); temp_result.ref_volume_asset_id = current_volume->asset_id; wxDateTime now = wxDateTime::Now( ); temp_result.datetime_of_run = (long int)now.GetAsDOS( ); temp_result.pixel_size = pixel_size; temp_result.voltage = voltage_kV; temp_result.spherical_aberration = spherical_aberration_mm; temp_result.amplitude_contrast = amplitude_contrast; temp_result.defocus1 = defocus1; temp_result.defocus2 = defocus2; temp_result.defocus_angle = defocus_angle; temp_result.phase_shift = phase_shift; temp_result.low_res_limit = low_resolution_limit; temp_result.high_res_limit = 2.f; //FIXME temp_result.out_of_plane_step = wanted_out_of_plane_angular_step; temp_result.in_plane_step = wanted_in_plane_angular_step; temp_result.defocus_search_range = defocus_search_range; temp_result.defocus_step = defocus_step; temp_result.reference_box_size_in_angstroms = ref_box_size_in_pixels * pixel_size; temp_result.mip_filename = mip_output_file; temp_result.scaled_mip_filename = scaled_mip_output_file; temp_result.psi_filename = best_psi_output_file; temp_result.theta_filename = best_theta_output_file; temp_result.phi_filename = best_phi_output_file; temp_result.defocus_filename = best_defocus_output_file; temp_result.pixel_size_filename = best_pixel_size_output_file; temp_result.histogram_filename = output_histogram_file; temp_result.projection_result_filename = output_result_file; temp_result.mask_radius = mask_radius_search; temp_result.min_peak_radius = min_peak_radius; temp_result.exclude_above_xy_threshold = exclude_based_on_shift; temp_result.xy_change_threshold = shift_threshold; temp_result.refinement_threshold = wanted_threshold; cached_results.Add(temp_result); float angular_range = 2.0f; // this doesn't seem to be used. bool ctf_refinement = false; // also not used. int max_threads = 1; // this will be overwritten when run in the gui based on the run profile int first_search_position = -1; // not used int last_search_position = -1; // not used int number_of_jobs_per_image_in_gui = 0; // not used wxString directory_for_results = main_frame->current_project.image_asset_directory.GetFullPath( ); // not used int result_number = 1; // should be no image stacks through the gui. current_job_package.AddJob("ttfffffffffffifffffbffttttttttttttttfffbtfiiiiiitft", input_search_image.ToUTF8( ).data( ), input_reconstruction.ToUTF8( ).data( ), pixel_size, voltage_kV, spherical_aberration_mm, amplitude_contrast, defocus1, defocus2, defocus_angle, low_resolution_limit, 2.f, //FIXME angular_range, wanted_out_of_plane_angular_step, best_parameters_to_keep, defocus_search_range, defocus_step, // defocus_refine_step, 0.0f, //FIXME 0.01f, // FIXME // pixel_size_refine_step, padding, ctf_refinement, mask_radius_search, phase_shift, input_result.mip_filename.ToUTF8( ).data( ), input_result.scaled_mip_filename.ToUTF8( ).data( ), input_result.psi_filename.ToUTF8( ).data( ), input_result.theta_filename.ToUTF8( ).data( ), input_result.phi_filename.ToUTF8( ).data( ), input_result.defocus_filename.ToUTF8( ).data( ), input_result.pixel_size_filename.ToUTF8( ).data( ), best_psi_output_file.ToUTF8( ).data( ), best_theta_output_file.ToUTF8( ).data( ), best_phi_output_file.ToUTF8( ).data( ), best_defocus_output_file.ToUTF8( ).data( ), best_pixel_size_output_file.ToUTF8( ).data( ), mip_output_file.ToUTF8( ).data( ), scaled_mip_output_file.ToUTF8( ).data( ), wanted_threshold, min_peak_radius, shift_threshold, exclude_based_on_shift, "C1", // FIXME wanted_in_plane_angular_step, first_search_position, last_search_position, image_number_for_gui, number_of_jobs_per_image_in_gui, result_number, max_threads, directory_for_results.ToUTF8( ).data( ), result_threshold, output_result_file.ToUTF8( ).data( )); my_progress_dialog->Update(image_counter + 1); } my_progress_dialog->Destroy( ); // launch a controller my_job_id = main_frame->job_controller.AddJob(this, run_profiles_panel->run_profile_manager.run_profiles[RunProfileComboBox->GetSelection( )].manager_command, run_profiles_panel->run_profile_manager.run_profiles[RunProfileComboBox->GetSelection( )].gui_address); if ( my_job_id != -1 ) { SetNumberConnectedTextToZeroAndStartTracking( ); StartPanel->Show(false); ProgressPanel->Show(true); InputPanel->Show(false); ExpertPanel->Show(false); InfoPanel->Show(false); OutputTextPanel->Show(true); ResultsPanel->Show(true); GroupComboBox->Enable(false); Layout( ); } ProgressBar->Pulse( ); } static int wxCMPFUNC_CONV SortByPeakHeight(TemplateMatchFoundPeakInfo** a, TemplateMatchFoundPeakInfo** b) { if ( (*a)->peak_height > (*b)->peak_height ) return -1; else if ( (*a)->peak_height < (*b)->peak_height ) return 1; else return 0; }; static int wxCMPFUNC_CONV SortByNewPeakNumber(TemplateMatchFoundPeakInfo** a, TemplateMatchFoundPeakInfo** b) { if ( (*a)->new_peak_number == -1 && (*b)->new_peak_number == -1 ) return 0; if ( (*a)->new_peak_number == -1 ) return 1; if ( (*b)->new_peak_number == -1 ) return -1; if ( (*a)->new_peak_number > (*b)->new_peak_number ) return 1; else if ( (*a)->new_peak_number < (*b)->new_peak_number ) return -1; else return 0; }; void RefineTemplateDevPanel::HandleSocketTemplateMatchResultReady(wxSocketBase* connected_socket, int& image_number, float& threshold_used, ArrayOfTemplateMatchFoundPeakInfos& peak_infos, ArrayOfTemplateMatchFoundPeakInfos& peak_changes) { // result is available for an image.. cached_results[image_number - 1].found_peaks.Clear( ); cached_results[image_number - 1].found_peaks = peak_infos; cached_results[image_number - 1].used_threshold = threshold_used; cached_results[image_number - 1].peak_changes.Clear( ); cached_results[image_number - 1].peak_changes = peak_changes; // sort the change peaks by peak height change and match them up to the input.. TemplateMatchJobResults current_input; int change_peak_counter; int result_peak_counter; int leftover_counter; float original_x; float original_y; // match the peaks up with the input peaks.. current_input = main_frame->current_project.database.GetTemplateMatchingResultByID(cached_results[image_number - 1].input_job_id); for ( change_peak_counter = 0; change_peak_counter < cached_results[image_number - 1].peak_changes.GetCount( ); change_peak_counter++ ) { original_x = cached_results[image_number - 1].found_peaks[change_peak_counter].x_pos - cached_results[image_number - 1].peak_changes[change_peak_counter].x_pos; original_y = cached_results[image_number - 1].found_peaks[change_peak_counter].y_pos - cached_results[image_number - 1].peak_changes[change_peak_counter].y_pos; cached_results[image_number - 1].peak_changes[change_peak_counter].original_peak_number = -1; for ( result_peak_counter = 0; result_peak_counter < current_input.found_peaks.GetCount( ); result_peak_counter++ ) { if ( fabsf(current_input.found_peaks[result_peak_counter].x_pos - original_x) < current_input.pixel_size && fabsf(current_input.found_peaks[result_peak_counter].y_pos - original_y) < current_input.pixel_size ) { cached_results[image_number - 1].peak_changes[change_peak_counter].original_peak_number = result_peak_counter + 1; break; } } } // remove peaks below threshold or moved too much, and match peaks up to their changes for ( change_peak_counter = cached_results[image_number - 1].peak_changes.GetCount( ) - 1; change_peak_counter >= 0; change_peak_counter-- ) { if ( cached_results[image_number - 1].found_peaks[change_peak_counter].peak_height < cached_results[image_number - 1].used_threshold || (sqrtf(powf(cached_results[image_number - 1].peak_changes[change_peak_counter].x_pos, 2) + powf(cached_results[image_number - 1].peak_changes[change_peak_counter].y_pos, 2)) > PeakChangeThresholdNumericTextCtrl->ReturnValue( ) && RemoveShiftedPeaksYesRadio->GetValue( ) == true) ) { cached_results[image_number - 1].found_peaks.RemoveAt(change_peak_counter); cached_results[image_number - 1].peak_changes[change_peak_counter].new_peak_number = -1; // shift everything down one.. for ( leftover_counter = change_peak_counter; leftover_counter < cached_results[image_number - 1].peak_changes.GetCount( ); leftover_counter++ ) { if ( cached_results[image_number - 1].peak_changes[leftover_counter].new_peak_number != -1 ) cached_results[image_number - 1].peak_changes[leftover_counter].new_peak_number--; } } else cached_results[image_number - 1].peak_changes[change_peak_counter].new_peak_number = change_peak_counter + 1; } // set peak number, then sort the result peaks, and carry over the number to the changes.. for ( result_peak_counter = 0; result_peak_counter < cached_results[image_number - 1].found_peaks.GetCount( ); result_peak_counter++ ) { cached_results[image_number - 1].found_peaks[result_peak_counter].peak_number = result_peak_counter + 1; } cached_results[image_number - 1].found_peaks.Sort(SortByPeakHeight); for ( change_peak_counter = 0; change_peak_counter < cached_results[image_number - 1].peak_changes.GetCount( ); change_peak_counter++ ) { for ( result_peak_counter = 0; result_peak_counter < cached_results[image_number - 1].found_peaks.GetCount( ); result_peak_counter++ ) { if ( cached_results[image_number - 1].peak_changes[change_peak_counter].new_peak_number == cached_results[image_number - 1].found_peaks[result_peak_counter].peak_number ) { cached_results[image_number - 1].peak_changes[change_peak_counter].new_peak_number = result_peak_counter + 1; break; } } } cached_results[image_number - 1].peak_changes.Sort(SortByNewPeakNumber); ResultsPanel->SetActiveResult(cached_results[image_number - 1]); } void RefineTemplateDevPanel::FinishButtonClick(wxCommandEvent& event) { ProgressBar->SetValue(0); TimeRemainingText->SetLabel("Time Remaining : ???h:??m:??s"); CancelAlignmentButton->Show(true); FinishButton->Show(false); ProgressPanel->Show(false); StartPanel->Show(true); OutputTextPanel->Show(false); output_textctrl->Clear( ); ResultsPanel->Show(false); //graph_is_hidden = true; InfoPanel->Show(true); InputPanel->Show(true); ExpertPanel->Show(true); running_job = false; Layout( ); } void RefineTemplateDevPanel::TerminateButtonClick(wxCommandEvent& event) { // kill the job, this will kill the socket to terminate downstream processes // - this will have to be improved when clever network failure is incorporated main_frame->job_controller.KillJob(my_job_id); WriteInfoText("Terminated Job"); TimeRemainingText->SetLabel("Time Remaining : Terminated"); CancelAlignmentButton->Show(false); FinishButton->Show(true); ProgressPanel->Layout( ); cached_results.Clear( ); //running_job = false; } void RefineTemplateDevPanel::WriteInfoText(wxString text_to_write) { output_textctrl->SetDefaultStyle(wxTextAttr(*wxBLACK)); output_textctrl->AppendText(text_to_write); if ( text_to_write.EndsWith("\n") == false ) output_textctrl->AppendText("\n"); } void RefineTemplateDevPanel::WriteErrorText(wxString text_to_write) { output_textctrl->SetDefaultStyle(wxTextAttr(*wxRED)); output_textctrl->AppendText(text_to_write); if ( text_to_write.EndsWith("\n") == false ) output_textctrl->AppendText("\n"); } void RefineTemplateDevPanel::OnSocketJobResultMsg(JobResult& received_result) { if ( received_result.result_size > 0 ) { ProcessResult(&received_result); } } void RefineTemplateDevPanel::OnSocketJobResultQueueMsg(ArrayofJobResults& received_queue) { for ( int counter = 0; counter < received_queue.GetCount( ); counter++ ) { ProcessResult(&received_queue.Item(counter)); } } void RefineTemplateDevPanel::SetNumberConnectedText(wxString wanted_text) { NumberConnectedText->SetLabel(wanted_text); } void RefineTemplateDevPanel::SetTimeRemainingText(wxString wanted_text) { TimeRemainingText->SetLabel(wanted_text); } void RefineTemplateDevPanel::OnSocketAllJobsFinished( ) { ProcessAllJobsFinished( ); } void RefineTemplateDevPanel::ProcessResult(JobResult* result_to_process) // this will have to be overidden in the parent clas when i make it. { long current_time = time(NULL); wxString bitmap_string; wxString plot_string; number_of_received_results++; if ( number_of_received_results == 1 ) { current_job_starttime = current_time; time_of_last_update = 0; } else if ( current_time != time_of_last_update ) { int current_percentage; current_percentage = myroundint(float(number_of_received_results) / float(expected_number_of_results) * 100.0f); time_of_last_update = current_time; if ( current_percentage > 100 ) current_percentage = 100; ProgressBar->SetValue(current_percentage); long job_time = current_time - current_job_starttime; float seconds_per_job = float(job_time) / float(number_of_received_results - 1); long seconds_remaining; seconds_remaining = float(expected_number_of_results - number_of_received_results) * seconds_per_job; wxTimeSpan time_remaining = wxTimeSpan(0, 0, seconds_remaining); TimeRemainingText->SetLabel(time_remaining.Format("Time Remaining : %Hh:%Mm:%Ss")); } // results should be .. // Defocus 1 (Angstroms) // Defocus 2 (Angstroms) // Astigmatism Angle (degrees) // Additional phase shift (e.g. from phase plate) radians // Score // Resolution (Angstroms) to which Thon rings are well fit by the CTF // Reolution (Angstroms) at which aliasing was detected /* if (current_time - time_of_last_result_update > 5) { // we need the filename of the image.. wxString image_filename = image_asset_panel->ReturnAssetPointer(active_group.members[result_to_process->job_number])->filename.GetFullPath(); ResultsPanel->Draw(my_job_package.jobs[result_to_process->job_number].arguments[3].ReturnStringArgument(), my_job_package.jobs[result_to_process->job_number].arguments[16].ReturnBoolArgument(), result_to_process->result_data[0], result_to_process->result_data[1], result_to_process->result_data[2], result_to_process->result_data[3], result_to_process->result_data[4], result_to_process->result_data[5], result_to_process->result_data[6], image_filename); time_of_last_result_update = time(NULL); } */ // my_job_tracker.MarkJobFinished(); // if (my_job_tracker.ShouldUpdate() == true) UpdateProgressBar(); // store the results.. //buffered_results[result_to_process->job_number] = result_to_process; } void RefineTemplateDevPanel::ProcessAllJobsFinished( ) { MyDebugAssertTrue(my_job_tracker.total_number_of_finished_jobs == my_job_tracker.total_number_of_jobs, "In ProcessAllJobsFinished, but total_number_of_finished_jobs != total_number_of_jobs. Oops."); // Update the GUI with project timings extern MyOverviewPanel* overview_panel; overview_panel->SetProjectInfo( ); WriteResultToDataBase( ); match_template_results_panel->is_dirty = true; cached_results.Clear( ); // Kill the job (in case it isn't already dead) main_frame->job_controller.KillJob(my_job_id); WriteInfoText("All Jobs have finished."); ProgressBar->SetValue(100); TimeRemainingText->SetLabel("Time Remaining : All Done!"); CancelAlignmentButton->Show(false); FinishButton->Show(true); ProgressPanel->Layout( ); } void RefineTemplateDevPanel::WriteResultToDataBase( ) { // find the current highest template match numbers in the database, then increment by one int template_match_id = main_frame->current_project.database.ReturnHighestTemplateMatchID( ) + 1; int template_match_job_id = main_frame->current_project.database.ReturnHighestTemplateMatchJobID( ) + 1; main_frame->current_project.database.Begin( ); for ( int counter = 0; counter < cached_results.GetCount( ); counter++ ) { cached_results[counter].job_id = template_match_job_id; main_frame->current_project.database.AddTemplateMatchingResult(template_match_id, cached_results[counter]); template_match_id++; } for ( int counter = 0; counter < cached_results.GetCount( ); counter++ ) { main_frame->current_project.database.SetActiveTemplateMatchJobForGivenImageAssetID(cached_results[counter].image_asset_id, template_match_job_id); } main_frame->current_project.database.Commit( ); // match_template_results_panel->is_dirty = true; } void RefineTemplateDevPanel::UpdateProgressBar( ) { ProgressBar->SetValue(my_job_tracker.ReturnPercentCompleted( )); TimeRemainingText->SetLabel(my_job_tracker.ReturnRemainingTime( ).Format("Time Remaining : %Hh:%Mm:%Ss")); } #pragma once #include "std/cstdint.hpp" class FilesContainerR; class ReaderSrc; class Writer; class ModelReaderPtr; namespace version { enum Format { unknownFormat = -1, v1 = 0, // April 2011 v2, // November 2011 (store type index, instead of raw type in mwm) v3, // March 2013 (store type index, instead of raw type in search data) v4, // April 2015 (distinguish и and й in search index) v5, // July 2015 (feature id is the index in vector now). v6, // October 2015 (offsets vector is in mwm now). lastFormat = v6 }; struct MwmVersion { MwmVersion(); Format format; uint32_t timestamp; }; /// Writes latest format and current timestamp to the writer. void WriteVersion(Writer & w, uint32_t versionDate); /// Reads mwm version from src. void ReadVersion(ReaderSrc & src, MwmVersion & version); /// \return True when version was successfully parsed from container, /// otherwise returns false. In the latter case version is /// unchanged. bool ReadVersion(FilesContainerR const & container, MwmVersion & version); /// Helper function that is used in FindAllLocalMaps. uint32_t ReadVersionTimestamp(ModelReaderPtr const & reader); } // namespace version class Solution { public: int maxArea(vector& nums) { int i = 0; int j = nums.size()-1; int ans = 0; while(i <= j){ ans = max(ans,(j-i)*min(nums[i],nums[j])); if(nums[i] < nums[j]){ i++; } else{ j--; } } return ans; } };Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupoREDSI_1160929_1161573/boost_1_67_0/libs/icl/test/test_interval_map_cases.hpp /*-----------------------------------------------------------------------------+ Copyright (c) 2008-2009: +------------------------------------------------------------------------------+ Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENCE.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +-----------------------------------------------------------------------------*/ #ifndef BOOST_ICL_TEST_INTERVAL_MAP_CASES_HPP_JOFA_090701 #define BOOST_ICL_TEST_INTERVAL_MAP_CASES_HPP_JOFA_090701 BOOST_AUTO_TEST_CASE_TEMPLATE (test_icl_interval_map_fundamentals_4_ordered_types, T, ordered_types) { interval_map_fundamentals_4_ordered_types();} BOOST_AUTO_TEST_CASE_TEMPLATE (test_icl_interval_map_ctor_4_bicremental_types, T, bicremental_types) { interval_map_ctor_4_bicremental_types();} BOOST_AUTO_TEST_CASE_TEMPLATE (test_icl_interval_map_add_sub_4_bicremental_types, T, bicremental_types) { interval_map_add_sub_4_bicremental_types();} BOOST_AUTO_TEST_CASE_TEMPLATE (test_icl_interval_map_distinct_4_bicremental_types, T, bicremental_types) { interval_map_distinct_4_bicremental_types();} BOOST_AUTO_TEST_CASE_TEMPLATE (test_icl_interval_map_distinct_4_bicremental_continuous_types, T, bicremental_continuous_types) { interval_map_distinct_4_bicremental_continuous_types();} BOOST_AUTO_TEST_CASE_TEMPLATE (test_icl_interval_map_isolate_4_bicremental_continuous_types, T, bicremental_continuous_types) { interval_map_isolate_4_bicremental_continuous_types();} BOOST_AUTO_TEST_CASE_TEMPLATE (test_icl_interval_map_contains_4_bicremental_types, T, bicremental_types) { interval_map_contains_4_bicremental_types();} BOOST_AUTO_TEST_CASE_TEMPLATE (test_icl_interval_map_contains_key_objects_4_bicremental_types, T, bicremental_types) { interval_map_contains_key_objects_4_bicremental_types();} BOOST_AUTO_TEST_CASE_TEMPLATE (test_icl_interval_map_operators_4_bicremental_types, T, bicremental_types) { interval_map_operators_4_bicremental_types();} BOOST_AUTO_TEST_CASE_TEMPLATE (test_icl_interval_map_base_intersect_4_bicremental_types, T, bicremental_types) { interval_map_base_intersect_4_bicremental_types();} BOOST_AUTO_TEST_CASE_TEMPLATE (test_icl_interval_map_base_erase_4_bicremental_types, T, bicremental_types) { interval_map_base_erase_4_bicremental_types();} BOOST_AUTO_TEST_CASE_TEMPLATE (test_icl_interval_map_base_is_disjoint_4_bicremental_types, T, bicremental_types) { interval_map_base_is_disjoint_4_bicremental_types();} BOOST_AUTO_TEST_CASE_TEMPLATE (test_icl_interval_map_flip_4_bicremental_types, T, bicremental_types) { interval_map_flip_4_bicremental_types();} BOOST_AUTO_TEST_CASE_TEMPLATE (test_icl_interval_map_find_4_bicremental_types, T, bicremental_types) { interval_map_find_4_bicremental_types();} BOOST_AUTO_TEST_CASE_TEMPLATE (test_icl_interval_map_find_4_numeric_continuous_types, T, numeric_continuous_types) { interval_map_find_4_numeric_continuous_types();} BOOST_AUTO_TEST_CASE_TEMPLATE (test_icl_interval_map_range_4_bicremental_types, T, bicremental_types) { interval_map_range_4_bicremental_types();} BOOST_AUTO_TEST_CASE_TEMPLATE (test_icl_interval_map_set_4_bicremental_types, T, bicremental_types) { interval_map_set_4_bicremental_types();} BOOST_AUTO_TEST_CASE_TEMPLATE (test_icl_interval_map_inclusion_compare_4_bicremental_types, T, bicremental_types) { interval_map_inclusion_compare_4_bicremental_types();} BOOST_AUTO_TEST_CASE_TEMPLATE (test_icl_interval_map_std_copy_via_inserter_4_bicremental_types, T, bicremental_types) { interval_map_std_copy_via_inserter_4_bicremental_types();} BOOST_AUTO_TEST_CASE_TEMPLATE (test_icl_interval_map_element_iter_4_discrete_types, T, discrete_types) { interval_map_element_iter_4_discrete_types();} #endif // BOOST_ICL_TEST_INTERVAL_MAP_CASES_HPP_JOFA_090701 dujianxin/Windows-universal-samples1000+ //********************************************************* // // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the MIT License (MIT). // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // //********************************************************* #include "pch.h" #include "Scenario2_DetectInWebcam.h" #include "Scenario2_DetectInWebcam.g.cpp" #include "SampleConfiguration.h" using namespace winrt; using namespace winrt::Windows::ApplicationModel; using namespace winrt::Windows::Foundation; using namespace winrt::Windows::Foundation::Collections; using namespace winrt::Windows::Graphics::Imaging; using namespace winrt::Windows::Media; using namespace winrt::Windows::Media::Capture; using namespace winrt::Windows::Media::FaceAnalysis; using namespace winrt::Windows::Media::MediaProperties; using namespace winrt::Windows::UI::Xaml; using namespace winrt::Windows::UI::Xaml::Media; using namespace winrt::Windows::UI::Xaml::Media::Imaging; using namespace winrt::Windows::UI::Xaml::Navigation; namespace winrt::SDKTemplate::implementation { Scenario2_DetectInWebcam::Scenario2_DetectInWebcam() { InitializeComponent(); } void Scenario2_DetectInWebcam::OnNavigatedTo(NavigationEventArgs const&) { suspendingEventToken = Application::Current().Suspending({ get_weak(), &Scenario2_DetectInWebcam::OnSuspending }); } void Scenario2_DetectInWebcam::OnNavigatedFrom(NavigationEventArgs const&) { Application::Current().Suspending(suspendingEventToken); } // Responds to App Suspend event to stop/release MediaCapture object if it's running and return to Idle state. fire_and_forget Scenario2_DetectInWebcam::OnSuspending(IInspectable const&, SuspendingEventArgs const& e) { auto lifetime = get_strong(); if (currentState == ScenarioState::Streaming) { auto deferral = e.SuspendingOperation().GetDeferral(); co_await ChangeScenarioStateAsync(ScenarioState::Idle); deferral.Complete(); } } // Creates the FaceDetector object which we will use for face detection. // Initializes a new MediaCapture instance and starts the Preview streaming to the CamPreview UI element. // Completes with true if initialization and streaming were successful and false if an exception occurred. IAsyncOperation Scenario2_DetectInWebcam::StartWebcamStreamingAsync() { auto lifetime = get_strong(); bool successful; faceDetector = co_await FaceDetector::CreateAsync(); try { MediaCapture mediaCapture; agileMediaCapture = mediaCapture; MediaCaptureInitializationSettings settings; // For this scenario, we only need Video (not microphone) so specify this in the initializer. // NOTE: the appxmanifest only declares "webcam" under capabilities and if this is changed to include // microphone (default constructor) you must add "microphone" to the manifest or initialization will fail. settings.StreamingCaptureMode(StreamingCaptureMode::Video); co_await mediaCapture.InitializeAsync(settings); mediaCapture.CameraStreamStateChanged({ get_weak(), &Scenario2_DetectInWebcam::MediaCapture_CameraStreamStateChanged }); // Cache the media properties as we'll need them later. auto deviceController = mediaCapture.VideoDeviceController(); videoProperties = deviceController.GetMediaStreamProperties(MediaStreamType::VideoPreview).as(); // Immediately start streaming to our CaptureElement UI. // NOTE: CaptureElement's Source must be set before streaming is started. CamPreview().Source(mediaCapture); co_await mediaCapture.StartPreviewAsync(); successful = true; } catch (hresult_access_denied const&) { // If the user has disabled their webcam this exception is thrown; provide a descriptive message to inform the user of this fact. rootPage.NotifyUser(L"Webcam is disabled or access to the webcam is disabled for this app.\nEnsure Privacy Settings allow webcam usage.", NotifyType::ErrorMessage); successful = false; } catch (hresult_error const& ex) { rootPage.NotifyUser(ex.message(), NotifyType::ErrorMessage); successful = false; } co_return successful; } // Safely stops webcam streaming (if running) and releases MediaCapture object. IAsyncAction Scenario2_DetectInWebcam::ShutdownWebcamAsync() { auto lifetime = get_strong(); if (agileMediaCapture) { auto mediaCapture = agileMediaCapture.get(); if (mediaCapture.CameraStreamState() == Windows::Media::Devices::CameraStreamState::Streaming) { try { co_await mediaCapture.StopPreviewAsync(); } catch (hresult_error const&) { // Since we're going to destroy the MediaCapture object there's nothing to do here } } mediaCapture.Close(); } CamPreview().Source(nullptr); agileMediaCapture = nullptr; } // Captures a single frame from the running webcam stream and executes the FaceDetector on the image. If successful calls SetupVisualization to display the results. IAsyncOperation Scenario2_DetectInWebcam::TakeSnapshotAndFindFacesAsync() { auto lifetime = get_strong(); if (currentState != ScenarioState::Streaming) { co_return false; } bool successful = false; try { // Create a VideoFrame object specifying the pixel format we want our capture image to be (NV12 bitmap in this case). // GetPreviewFrame will convert the native webcam frame into this format. static constexpr BitmapPixelFormat InputPixelFormat = BitmapPixelFormat::Nv12; VideoFrame previewFrame(InputPixelFormat, (int)videoProperties.Width(), (int)videoProperties.Height()); co_await agileMediaCapture.get().GetPreviewFrameAsync(previewFrame); // The returned VideoFrame should be in the supported NV12 format but we need to verify if (FaceDetector::IsBitmapPixelFormatSupported(previewFrame.SoftwareBitmap().BitmapPixelFormat())) { IVector faces = co_await faceDetector.DetectFacesAsync(previewFrame.SoftwareBitmap()); // Create a WritableBitmap for our visualization display; copy the original bitmap pixels to wb's buffer. // Note that WriteableBitmap doesn't support NV12 and we have to convert it to 32-bit BGRA. SoftwareBitmap convertedSource = SoftwareBitmap::Convert(previewFrame.SoftwareBitmap(), BitmapPixelFormat::Bgra8); WriteableBitmap displaySource(convertedSource.PixelWidth(), convertedSource.PixelHeight()); convertedSource.CopyToBuffer(displaySource.PixelBuffer()); // Create our display using the available image and face results. SetupVisualization(displaySource, faces); successful = true; } else { rootPage.NotifyUser(L"PixelFormat 'NV12' is not supported by FaceDetector", NotifyType::ErrorMessage); } } catch (hresult_error const& ex) { rootPage.NotifyUser(ex.message(), NotifyType::ErrorMessage); } co_return successful; } // Takes the webcam image and FaceTracker results and assembles the visualization onto the Canvas. void Scenario2_DetectInWebcam::SetupVisualization(WriteableBitmap const& displaySource, IVector const& foundFaces) { ImageBrush brush; brush.ImageSource(displaySource); brush.Stretch(Stretch::Fill); SnapshotCanvas().Background(brush); SampleHelpers::HighlightFaces(displaySource, foundFaces, SnapshotCanvas(), HighlightedFaceBox()); } // Manages the scenario's internal state. Invokes the internal methods and updates the UI according to the // passed in state value. Handles failures and resets the state if necessary. IAsyncAction Scenario2_DetectInWebcam::ChangeScenarioStateAsync(ScenarioState newState) { auto lifetime = get_strong(); switch (newState) { case ScenarioState::Idle: CameraSnapshotButton().IsEnabled(false); currentState = newState; co_await ShutdownWebcamAsync(); SnapshotCanvas().Background(nullptr); SnapshotCanvas().Children().Clear(); CameraStreamingButton().Content(box_value(L"Start Streaming")); CameraSnapshotButton().Content(box_value(L"Take Snapshot")); break; case ScenarioState::Streaming: if (!co_await StartWebcamStreamingAsync()) { co_await ChangeScenarioStateAsync(ScenarioState::Idle); break; } SnapshotCanvas().Background(nullptr); SnapshotCanvas().Children().Clear(); CameraSnapshotButton().IsEnabled(true); CameraStreamingButton().Content(box_value(L"Stop Streaming")); CameraSnapshotButton().Content(box_value(L"Take Snapshot")); currentState = newState; break; case ScenarioState::Snapshot: if (!co_await TakeSnapshotAndFindFacesAsync()) { co_await ChangeScenarioStateAsync(ScenarioState::Idle); break; } co_await ShutdownWebcamAsync(); CameraSnapshotButton().IsEnabled(true); CameraStreamingButton().Content(box_value(L"Start Streaming")); CameraSnapshotButton().Content(box_value(L"Clear Display")); currentState = newState; break; } } // Handles MediaCapture changes by shutting down streaming and returning to Idle state. fire_and_forget Scenario2_DetectInWebcam::MediaCapture_CameraStreamStateChanged(MediaCapture const&, IInspectable const& args) { auto lifetime = get_strong(); // MediaCapture is not Agile and so we cannot invoke it's methods on this caller's thread // and instead need to schedule the state change on the UI thread. co_await resume_foreground(Dispatcher()); co_await ChangeScenarioStateAsync(ScenarioState::Idle); } // Handles "streaming" button clicks to start/stop webcam streaming. fire_and_forget Scenario2_DetectInWebcam::CameraStreamingButton_Click(IInspectable const&, RoutedEventArgs const&) { auto lifetime = get_strong(); rootPage.NotifyUser(L"", NotifyType::StatusMessage); if (currentState == ScenarioState::Streaming) { co_await ChangeScenarioStateAsync(ScenarioState::Idle); } else { co_await ChangeScenarioStateAsync(ScenarioState::Streaming); } } // Handles "snapshot" button clicks to take a snapshot or clear the current display. fire_and_forget Scenario2_DetectInWebcam::CameraSnapshotButton_Click(IInspectable const&, RoutedEventArgs const&) { auto lifetime = get_strong(); rootPage.NotifyUser(L"", NotifyType::StatusMessage); if (currentState == ScenarioState::Streaming) { co_await ChangeScenarioStateAsync(ScenarioState::Snapshot); } else { co_await ChangeScenarioStateAsync(ScenarioState::Idle); } } // Updates any existing face bounding boxes in response to changes in the size of the Canvas. void Scenario2_DetectInWebcam::SnapshotCanvas_SizeChanged(IInspectable const&, SizeChangedEventArgs const&) { // If the Canvas is resized we must recompute a new scaling factor and // apply it to each face box. ImageBrush brush = SnapshotCanvas().Background().try_as(); if (brush != nullptr) { WriteableBitmap displaySource = brush.ImageSource().as(); SampleHelpers::RepositionFaces(displaySource, SnapshotCanvas()); } } } /* * Copyright (c) [2019] Huawei Technologies Co.,Ltd.All rights reserved. * * OpenArkCompiler is licensed under the Mulan PSL v1. * You can use this software according to the terms and conditions of the Mulan PSL v1. * You may obtain a copy of Mulan PSL v1 at: * * http://license.coscl.org.cn/MulanPSL * * 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 PSL v1 for more details. */ #include "irmap.h" #include #include "ssa_mir_nodes.h" #include "ssa.h" #include "mir_builder.h" #include "factory.h" namespace maple { using MeStmtFactory = FunctionFactory; // recursively invoke itself in a pre-order traversal of the dominator tree of // the CFG to build the HSSA representation for the code in each BB void IRMap::BuildBB(BB &bb, std::vector &bbIRMapProcessed) { BBId bbid = bb.GetBBId(); if (bbIRMapProcessed[bbid]) { return; } bbIRMapProcessed[bbid] = true; curBB = &bb; SetCurFunction(bb); // iterate phi list to update the definition by phi BuildPhiMeNode(bb); if (!bb.IsEmpty()) { for (auto &stmt : bb.GetStmtNodes()) { MeStmt *meStmt = BuildMeStmt(stmt); bb.AddMeStmtLast(meStmt); } } // travesal bb's dominated tree ASSERT(bbid < dom.GetDomChildrenSize(), " index out of range in IRMap::BuildBB"); const MapleSet &domChildren = dom.GetDomChildren(bbid); for (auto bbit = domChildren.begin(); bbit != domChildren.end(); ++bbit) { BBId childbbid = *bbit; BuildBB(*GetBB(childbbid), bbIRMapProcessed); } } void IRMap::BuildPhiMeNode(BB &bb) { for (auto &phi : bb.GetPhiList()) { const OriginalSt *origst = phi.first; VersionSt *verSt = phi.second.GetResult(); if (origst->IsPregOst()) { MeRegPhiNode *phiMeNode = NewInPool(); RegMeExpr *medef = GetOrCreateRegFromVerSt(*verSt); phiMeNode->UpdateLHS(*medef); phiMeNode->SetDefBB(&bb); // build phi operands for (VersionSt *opnd : phi.second.GetPhiOpnds()) { phiMeNode->GetOpnds().push_back(GetOrCreateRegFromVerSt(*opnd)); } bb.GetMeregphiList().insert(std::make_pair(medef->GetOstIdx(), phiMeNode)); } else { MeVarPhiNode *phimenode = NewInPool(); VarMeExpr *medef = GetOrCreateVarFromVerSt(*verSt); phimenode->UpdateLHS(*medef); phimenode->SetDefBB(&bb); // build phi operands for (VersionSt *opnd : phi.second.GetPhiOpnds()) { phimenode->GetOpnds().push_back(GetOrCreateVarFromVerSt(*opnd)); } bb.GetMevarPhiList().insert(std::make_pair(medef->GetOStIdx(), phimenode)); } } } VarMeExpr *IRMap::CreateVarMeExprVersion(const VarMeExpr &origExpr) { VarMeExpr *varmeexpr = New(&irMapAlloc, exprID++, origExpr.GetOStIdx(), verst2MeExprTable.size()); verst2MeExprTable.push_back(varmeexpr); varmeexpr->InitBase(origExpr.GetOp(), origExpr.GetPrimType(), origExpr.GetNumOpnds()); varmeexpr->SetFieldID(origExpr.GetFieldID()); return varmeexpr; } MeExpr *IRMap::CreateAddrofMeExpr(MeExpr &expr) { if (expr.GetMeOp() == kMeOpVar) { VarMeExpr &varmeexpr = static_cast(expr); AddrofMeExpr addrofme(kInvalidExprID, varmeexpr.GetOStIdx()); addrofme.SetOp(OP_addrof); addrofme.SetPtyp(PTY_ptr); return HashMeExpr(addrofme); } else { ASSERT(expr.GetMeOp() == kMeOpIvar, "expecting IVarMeExpr"); IvarMeExpr &ivarexpr = static_cast(expr); OpMeExpr opmeexpr(kInvalidExprID); opmeexpr.SetFieldID(ivarexpr.GetFieldID()); opmeexpr.SetTyIdx(ivarexpr.GetTyIdx()); opmeexpr.SetOpnd(0, ivarexpr.GetBase()); opmeexpr.SetOp(OP_iaddrof); opmeexpr.SetPtyp(PTY_ptr); opmeexpr.SetNumOpnds(1); return HashMeExpr(opmeexpr); } } VarMeExpr *IRMap::CreateNewVarMeExpr(OStIdx oStIdx, PrimType pType, FieldID fieldID) { VarMeExpr *varMeExpr = meBuilder.BuildVarMeExpr(exprID++, oStIdx, verst2MeExprTable.size(), pType, fieldID); PushBackVerst2MeExprTable(varMeExpr); return varMeExpr; } VarMeExpr *IRMap::CreateNewVarMeExpr(OriginalSt &oSt, PrimType pType, FieldID fieldID) { VarMeExpr *varMeExpr = CreateNewVarMeExpr(oSt.GetIndex(), pType, fieldID); oSt.PushbackVersionIndex(varMeExpr->GetVstIdx()); return varMeExpr; } VarMeExpr *IRMap::CreateNewGlobalTmp(GStrIdx strIdx, PrimType ptyp) { MIRSymbol *st = mirModule.GetMIRBuilder()->CreateSymbol((TyIdx)ptyp, strIdx, kStVar, kScGlobal, nullptr, kScopeGlobal); st->SetIsTmp(true); OriginalSt *oSt = ssaTab.CreateSymbolOriginalSt(*st, 0, 0); VarMeExpr *varx = New(&irMapAlloc, exprID++, oSt->GetIndex(), oSt->GetZeroVersionIndex()); varx->InitBase(OP_dread, ptyp, 0); return varx; } VarMeExpr *IRMap::CreateNewLocalRefVarTmp(GStrIdx strIdx, TyIdx tIdx) { MIRSymbol *st = mirModule.GetMIRBuilder()->CreateSymbol(tIdx, strIdx, kStVar, kScAuto, mirModule.CurFunction(), kScopeLocal); st->SetInstrumented(); OriginalSt *oSt = ssaTab.CreateSymbolOriginalSt(*st, mirModule.CurFunction()->GetPuidx(), 0); oSt->SetZeroVersionIndex(verst2MeExprTable.size()); verst2MeExprTable.push_back(nullptr); oSt->PushbackVersionIndex(oSt->GetZeroVersionIndex()); VarMeExpr *newlocalrefvar = New(&irMapAlloc, exprID++, oSt->GetIndex(), verst2MeExprTable.size()); verst2MeExprTable.push_back(newlocalrefvar); newlocalrefvar->InitBase(OP_dread, PTY_ref, 0); return newlocalrefvar; } RegMeExpr *IRMap::CreateRegMeExprVersion(const OriginalSt &pregOrgst) { RegMeExpr *regreadexpr = NewInPool(exprID++, pregOrgst.GetPregIdx(), pregOrgst.GetPuIdx(), pregOrgst.GetIndex(), 0); regreadexpr->InitBase(OP_regread, pregOrgst.GetMIRPreg()->GetPrimType(), 0); regMeExprTable.push_back(regreadexpr); return regreadexpr; } RegMeExpr *IRMap::CreateRegMeExprVersion(const RegMeExpr &origExpr) { RegMeExpr *regreadexpr = NewInPool(exprID++, origExpr.GetRegIdx(), origExpr.GetPuIdx(), origExpr.GetOstIdx(), 0); regreadexpr->InitBase(origExpr.GetOp(), origExpr.GetPrimType(), origExpr.GetNumOpnds()); regMeExprTable.push_back(regreadexpr); return regreadexpr; } RegMeExpr *IRMap::CreateRefRegMeExpr(const MIRSymbol &mirSt) { MIRFunction *mirfunc = mirModule.CurFunction(); MIRType *sttype = mirSt.GetType(); PrimType ptyp = sttype->GetPrimType(); ASSERT(ptyp == PTY_ref, "only PTY_ref needed"); PregIdx regidx = mirfunc->GetPregTab()->CreateRefPreg(*sttype); ASSERT(regidx <= 0xffff, "register oversized"); MIRPreg *preg = mirfunc->GetPregTab()->PregFromPregIdx(regidx); if (!mirSt.IgnoreRC()) { preg->SetNeedRC(); } OriginalSt *oSt = ssaTab.GetOriginalStTable().CreatePregOriginalSt(regidx, mirfunc->GetPuidx()); RegMeExpr *regreadexpr = NewInPool(exprID++, regidx, mirfunc->GetPuidx(), oSt->GetIndex(), 0); regreadexpr->InitBase(OP_regread, ptyp, 0); regMeExprTable.push_back(regreadexpr); return regreadexpr; } RegMeExpr *IRMap::CreateRegMeExpr(PrimType ptyp) { MIRFunction *mirfunc = mirModule.CurFunction(); PregIdx regidx = mirfunc->GetPregTab()->CreatePreg(ptyp); ASSERT(regidx <= 0xffff, "register oversized"); OriginalSt *oSt = ssaTab.GetOriginalStTable().CreatePregOriginalSt(regidx, mirfunc->GetPuidx()); RegMeExpr *regreadexpr = NewInPool(exprID++, regidx, mirfunc->GetPuidx(), oSt->GetIndex(), 0); regreadexpr->InitBase(OP_regread, ptyp, 0); regMeExprTable.push_back(regreadexpr); return regreadexpr; } RegMeExpr *IRMap::CreateRegRefMeExpr(MIRType &mirType) { MIRFunction *mirfunc = mirModule.CurFunction(); PregIdx regidx = mirfunc->GetPregTab()->CreateRefPreg(mirType); ASSERT(regidx <= 0xffff, "register oversized"); OriginalSt *oSt = ssaTab.GetOriginalStTable().CreatePregOriginalSt(regidx, mirfunc->GetPuidx()); RegMeExpr *regreadexpr = NewInPool(exprID++, regidx, mirfunc->GetPuidx(), oSt->GetIndex(), 0); regreadexpr->InitBase(OP_regread, mirType.GetPrimType(), 0); regMeExprTable.push_back(regreadexpr); return regreadexpr; } RegMeExpr *IRMap::CreateRegRefMeExpr(MeExpr &meExpr) { MIRType *mirType = nullptr; switch (meExpr.GetMeOp()) { case kMeOpVar: { VarMeExpr &varmeexpr = static_cast(meExpr); const OriginalSt *oSt = ssaTab.GetOriginalStFromID(varmeexpr.GetOStIdx()); ASSERT(oSt->GetTyIdx() != 0, "expect oSt->tyIdx to be initialized"); mirType = GlobalTables::GetTypeTable().GetTypeFromTyIdx(oSt->GetTyIdx()); break; } case kMeOpIvar: { IvarMeExpr &ivarmeexpr = static_cast(meExpr); MIRType *ptrmirtype = GlobalTables::GetTypeTable().GetTypeFromTyIdx(ivarmeexpr.GetTyIdx()); ASSERT(ptrmirtype->GetKind() == kTypePointer, "must be point type for ivar"); MIRPtrType *realmirtype = static_cast(ptrmirtype); FieldID fieldID = ivarmeexpr.GetFieldID(); if (fieldID > 0) { mirType = GlobalTables::GetTypeTable().GetTypeFromTyIdx(realmirtype->GetPointedTyIdxWithFieldID(fieldID)); } else { mirType = realmirtype->GetPointedType(); } ASSERT(mirType->GetPrimType() == meExpr.GetPrimType() || !(IsAddress(mirType->GetPrimType()) && IsAddress(meExpr.GetPrimType())), "inconsistent type"); ASSERT(mirType->GetPrimType() == PTY_ref, "CreateRegRefMeExpr: only ref type expected"); break; } case kMeOpOp: if (meExpr.GetOp() == OP_retype) { OpMeExpr &opmeexpr = static_cast(meExpr); ASSERT(opmeexpr.GetTyIdx() != 0, "expect opmeexpr.tyIdx to be initialized"); mirType = GlobalTables::GetTypeTable().GetTypeFromTyIdx(opmeexpr.GetTyIdx()); break; } // fall thru default: return CreateRegMeExpr(PTY_ptr); } return CreateRegRefMeExpr(*mirType); } VarMeExpr *IRMap::GetOrCreateVarFromVerSt(const VersionSt &verSt) { size_t vindex = verSt.GetIndex(); ASSERT(vindex < verst2MeExprTable.size(), "GetOrCreateVarFromVerSt: index %d is out of range", vindex); MeExpr *meExpr = verst2MeExprTable.at(vindex); if (meExpr != nullptr) { return static_cast(meExpr); } const OriginalSt *oSt = verSt.GetOrigSt(); ASSERT(oSt->IsSymbolOst(), "GetOrCreateVarFromVerSt: wrong ost_type"); VarMeExpr *varx = New(&irMapAlloc, exprID++, oSt->GetIndex(), vindex); ASSERT(!GlobalTables::GetTypeTable().GetTypeTable().empty(), "container check"); varx->InitBase(OP_dread, GlobalTables::GetTypeTable().GetTypeFromTyIdx(oSt->GetTyIdx())->GetPrimType(), 0); varx->SetFieldID(oSt->GetFieldID()); verst2MeExprTable[vindex] = varx; return varx; } VarMeExpr *IRMap::GetOrCreateZeroVersionVarMeExpr(const OriginalSt &oSt) { ASSERT(oSt.GetZeroVersionIndex() < verst2MeExprTable.size(), "GetOrCreateZeroVersionVarMeExpr: version index of osym's kInitVersion out of range"); if (oSt.GetZeroVersionIndex() == 0) { ssaTab.SetZeroVersionIndex(oSt.GetIndex(), verst2MeExprTable.size()); verst2MeExprTable.push_back(nullptr); } if (verst2MeExprTable[oSt.GetZeroVersionIndex()] == nullptr) { VarMeExpr *varmeexpr = New(&irMapAlloc, exprID++, oSt.GetIndex(), oSt.GetZeroVersionIndex()); varmeexpr->SetFieldID(oSt.GetFieldID()); varmeexpr->SetOp(OP_dread); ASSERT(!GlobalTables::GetTypeTable().GetTypeTable().empty(), "container check"); varmeexpr->SetPtyp(GlobalTables::GetTypeTable().GetTypeFromTyIdx(oSt.GetTyIdx())->GetPrimType()); varmeexpr->SetNumOpnds(0); verst2MeExprTable[oSt.GetZeroVersionIndex()] = varmeexpr; return varmeexpr; } return static_cast(verst2MeExprTable[oSt.GetZeroVersionIndex()]); } RegMeExpr *IRMap::GetOrCreateRegFromVerSt(const VersionSt &verSt) { size_t vindex = verSt.GetIndex(); ASSERT(vindex < verst2MeExprTable.size(), " GetOrCreateRegFromVerSt: index %d is out of range", vindex); MeExpr *meExpr = verst2MeExprTable[vindex]; if (meExpr != nullptr) { return static_cast(meExpr); } const OriginalSt *oSt = verSt.GetOrigSt(); ASSERT(oSt->IsPregOst(), "GetOrCreateRegFromVerSt: PregOST expected"); RegMeExpr *regx = NewInPool(exprID++, oSt->GetPregIdx(), mirModule.CurFunction()->GetPuidx(), oSt->GetIndex(), vindex); regx->InitBase(OP_regread, oSt->GetMIRPreg()->GetPrimType(), 0); regMeExprTable.push_back(regx); verst2MeExprTable[vindex] = regx; return regx; } MeExpr *IRMap::BuildLHSVar(const VersionSt &verSt, DassignMeStmt &defMeStmt) { VarMeExpr *medef = GetOrCreateVarFromVerSt(verSt); medef->SetDefStmt(&defMeStmt); medef->SetDefBy(kDefByStmt); verst2MeExprTable.at(verSt.GetIndex()) = medef; return medef; } MeExpr *IRMap::BuildLHSReg(const VersionSt &verSt, RegassignMeStmt &defMeStmt, const RegassignNode ®assign) { RegMeExpr *medef = GetOrCreateRegFromVerSt(verSt); medef->SetPtyp(regassign.GetPrimType()); medef->SetDefStmt(&defMeStmt); medef->SetDefBy(kDefByStmt); verst2MeExprTable.at(verSt.GetIndex()) = medef; return medef; } IvarMeExpr *IRMap::BuildLHSIvar(MeExpr &baseAddr, IassignMeStmt &iassignMeStmt, FieldID fieldID) { IvarMeExpr *medef = New(exprID++); medef->SetFieldID(fieldID); medef->SetTyIdx(iassignMeStmt.GetTyIdx()); medef->SetBase(&baseAddr); medef->SetDefStmt(&iassignMeStmt); medef->SetOp(OP_iread); medef->SetPtyp(iassignMeStmt.GetRHS()->GetPrimType()); PutToBucket(medef->GetHashIndex() % mapHashLength, *medef); return medef; } IvarMeExpr *IRMap::BuildLHSIvarFromIassMeStmt(IassignMeStmt &iassignMeStmt) { return BuildLHSIvar(*iassignMeStmt.GetLHSVal()->GetBase(), iassignMeStmt, iassignMeStmt.GetLHSVal()->GetFieldID()); } // build Me chilist from MayDefNode list void IRMap::BuildChiList(MeStmt &meStmt, MapleMap &mayDefNodes, MapleMap &outList) { for (auto it = mayDefNodes.begin(); it != mayDefNodes.end(); ++it) { MayDefNode &maydefNode = it->second; VersionSt *opndst = maydefNode.GetOpnd(); VersionSt *resst = maydefNode.GetResult(); ChiMeNode *chimestmt = New(&meStmt); chimestmt->SetRHS(GetOrCreateVarFromVerSt(*opndst)); VarMeExpr *lhs = GetOrCreateVarFromVerSt(*resst); lhs->SetDefBy(kDefByChi); lhs->SetDefChi(*chimestmt); chimestmt->SetLHS(lhs); outList.insert(std::make_pair(lhs->GetOStIdx(), chimestmt)); } } void IRMap::BuildMustDefList(MeStmt &meStmt, MapleVector &mustdeflist, MapleVector &mustdefList) { for (auto it = mustdeflist.begin(); it != mustdeflist.end(); ++it) { MustDefNode &mustdefnode = *it; VersionSt *verSt = mustdefnode.GetResult(); VarMeExpr *lhs = GetOrCreateVarFromVerSt(*verSt); ASSERT(lhs->GetMeOp() == kMeOpReg || lhs->GetMeOp() == kMeOpVar, "unexpected opcode"); mustdefList.push_back(MustDefMeNode(lhs, &meStmt)); } } MeStmt *IRMap::BuildMeStmtWithNoSSAPart(StmtNode &stmt) { Opcode op = stmt.GetOpCode(); switch (op) { case OP_jscatch: case OP_finally: case OP_endtry: case OP_cleanuptry: case OP_membaracquire: case OP_membarrelease: case OP_membarstorestore: case OP_membarstoreload: return New(&stmt); case OP_goto: return New(&stmt); case OP_comment: return NewInPool(&stmt); case OP_jstry: return New(&stmt); case OP_catch: return NewInPool(&stmt); case OP_brfalse: case OP_brtrue: { CondGotoNode &condGotoNode = static_cast(stmt); CondGotoMeStmt *condGotoMeStmt = New(&stmt); condGotoMeStmt->SetOpnd(0, BuildExpr(*condGotoNode.Opnd(0))); return condGotoMeStmt; } case OP_try: { TryNode &tryNode = static_cast(stmt); TryMeStmt *tryMeStmt = NewInPool(&stmt); for (size_t i = 0; i < tryNode.GetOffsetsCount(); ++i) { tryMeStmt->OffsetsPushBack(tryNode.GetOffset(i)); } return tryMeStmt; } case OP_assertnonnull: case OP_eval: case OP_free: case OP_switch: { UnaryStmtNode &unaryStmt = static_cast(stmt); UnaryMeStmt *unMeStmt = static_cast((op == OP_switch) ? NewInPool(&stmt) : New(&stmt)); unMeStmt->SetOpnd(0, BuildExpr(*unaryStmt.Opnd(0))); return unMeStmt; } default: CHECK_FATAL(false, "NYI"); } } MeStmt *IRMap::BuildDassignMeStmt(StmtNode &stmt, AccessSSANodes &ssaPart) { DassignMeStmt *meStmt = NewInPool(&stmt); DassignNode &dassiNode = static_cast(stmt); meStmt->SetRHS(BuildExpr(*dassiNode.GetRHS())); VarMeExpr *varlhs = static_cast(BuildLHSVar(*ssaPart.GetSSAVar(), *meStmt)); meStmt->SetLHS(varlhs); BuildChiList(*meStmt, ssaPart.GetMayDefNodes(), *meStmt->GetChiList()); return meStmt; } MeStmt *IRMap::BuildRegassignMeStmt(StmtNode &stmt, AccessSSANodes &ssaPart) { RegassignMeStmt *meStmt = New(&stmt); RegassignNode ®Node = static_cast(stmt); meStmt->SetRHS(BuildExpr(*regNode.Opnd(0))); RegMeExpr *regLHS = static_cast(BuildLHSReg(*ssaPart.GetSSAVar(), *meStmt, regNode)); meStmt->SetLHS(regLHS); return meStmt; } MeStmt *IRMap::BuildIassignMeStmt(StmtNode &stmt, AccessSSANodes &ssaPart) { IassignNode &iasNode = static_cast(stmt); IassignMeStmt *meStmt = NewInPool(&stmt); meStmt->SetTyIdx(iasNode.GetTyIdx()); meStmt->SetRHS(BuildExpr(*iasNode.GetRHS())); meStmt->SetLHSVal(BuildLHSIvar(*BuildExpr(*iasNode.Opnd(0)), *meStmt, iasNode.GetFieldID())); BuildChiList(*meStmt, ssaPart.GetMayDefNodes(), *(meStmt->GetChiList())); return meStmt; } MeStmt *IRMap::BuildMaydassignMeStmt(StmtNode &stmt, AccessSSANodes &ssaPart) { MaydassignMeStmt *meStmt = NewInPool(&stmt); DassignNode &dassiNode = static_cast(stmt); meStmt->SetRHS(BuildExpr(*dassiNode.GetRHS())); meStmt->SetMayDassignSym(ssaPart.GetSSAVar()->GetOrigSt()); meStmt->SetFieldID(dassiNode.GetFieldID()); BuildChiList(*meStmt, ssaPart.GetMayDefNodes(), *(meStmt->GetChiList())); return meStmt; } MeStmt *IRMap::BuildCallMeStmt(StmtNode &stmt, AccessSSANodes &ssaPart) { CallMeStmt *callMeStmt = NewInPool(&stmt); CallNode &intrinNode = static_cast(stmt); callMeStmt->SetPUIdx(intrinNode.GetPUIdx()); for (size_t i = 0; i < intrinNode.NumOpnds(); ++i) { callMeStmt->GetOpnds().push_back(BuildExpr(*intrinNode.Opnd(i))); } BuildMuList(ssaPart.GetMayUseNodes(), *(callMeStmt->GetMuList())); if (kOpcodeInfo.IsCallAssigned(stmt.GetOpCode())) { BuildMustDefList(*callMeStmt, ssaPart.GetMustDefNodes(), *(callMeStmt->GetMustDefList())); } BuildChiList(*callMeStmt, ssaPart.GetMayDefNodes(), *(callMeStmt->GetChiList())); return callMeStmt; } MeStmt *IRMap::BuildNaryMeStmt(StmtNode &stmt, AccessSSANodes &ssaPart) { Opcode op = stmt.GetOpCode(); NaryMeStmt *naryMeStmt = (op == OP_icall || op == OP_icallassigned) ? static_cast(NewInPool(&stmt)) : static_cast(NewInPool(&stmt)); NaryStmtNode &naryStmtNode = static_cast(stmt); for (size_t i = 0; i < naryStmtNode.NumOpnds(); ++i) { naryMeStmt->GetOpnds().push_back(BuildExpr(*naryStmtNode.Opnd(i))); } BuildMuList(ssaPart.GetMayUseNodes(), *(naryMeStmt->GetMuList())); if (kOpcodeInfo.IsCallAssigned(op)) { BuildMustDefList(*naryMeStmt, ssaPart.GetMustDefNodes(), *(naryMeStmt->GetMustDefList())); } BuildChiList(*naryMeStmt, ssaPart.GetMayDefNodes(), *(naryMeStmt->GetChiList())); return naryMeStmt; } MeStmt *IRMap::BuildRetMeStmt(StmtNode &stmt, AccessSSANodes &ssaPart) { NaryStmtNode &retStmt = static_cast(stmt); RetMeStmt *meStmt = NewInPool(&stmt); for (size_t i = 0; i < retStmt.NumOpnds(); ++i) { meStmt->GetOpnds().push_back(BuildExpr(*retStmt.Opnd(i))); } BuildMuList(ssaPart.GetMayUseNodes(), *(meStmt->GetMuList())); return meStmt; } MeStmt *IRMap::BuildWithMuMeStmt(StmtNode &stmt, AccessSSANodes &ssaPart) { WithMuMeStmt *retSub = NewInPool(&stmt); BuildMuList(ssaPart.GetMayUseNodes(), *(retSub->GetMuList())); return retSub; } MeStmt *IRMap::BuildGosubMeStmt(StmtNode &stmt, AccessSSANodes &ssaPart) { GosubMeStmt *goSub = NewInPool(&stmt); BuildMuList(ssaPart.GetMayUseNodes(), *(goSub->GetMuList())); return goSub; } MeStmt *IRMap::BuildThrowMeStmt(StmtNode &stmt, AccessSSANodes &ssaPart) { UnaryStmtNode &unaryNode = static_cast(stmt); ThrowMeStmt *tmeStmt = NewInPool(&stmt); tmeStmt->SetMeStmtOpndValue(BuildExpr(*unaryNode.Opnd(0))); BuildMuList(ssaPart.GetMayUseNodes(), *(tmeStmt->GetMuList())); return tmeStmt; } MeStmt *IRMap::BuildSyncMeStmt(StmtNode &stmt, AccessSSANodes &ssaPart) { NaryStmtNode &naryNode = static_cast(stmt); SyncMeStmt *naryStmt = NewInPool(&stmt); for (size_t i = 0; i < naryNode.NumOpnds(); ++i) { naryStmt->GetOpnds().push_back(BuildExpr(*naryNode.Opnd(i))); } BuildMuList(ssaPart.GetMayUseNodes(), *(naryStmt->GetMuList())); BuildChiList(*naryStmt, ssaPart.GetMayDefNodes(), *(naryStmt->GetChiList())); return naryStmt; } MeStmt *IRMap::BuildMeStmt(StmtNode &stmt) { AccessSSANodes *ssaPart = ssaTab.GetStmtsSSAPart().SSAPartOf(stmt); if (ssaPart == nullptr) { return BuildMeStmtWithNoSSAPart(stmt); } auto func = CreateProductFunction(stmt.GetOpCode()); ASSERT(func != nullptr, "NYI"); return func != nullptr ? func(this, stmt, *ssaPart) : nullptr; } void IRMap::BuildMuList(MapleMap &mayuseList, MapleMap &mulist) { for (std::pair mapitem : mayuseList) { MayUseNode &mayusenode = mapitem.second; VersionSt *verSt = mayusenode.GetOpnd(); VarMeExpr *varmeexpr = GetOrCreateVarFromVerSt(*verSt); mulist.insert(std::make_pair(varmeexpr->GetOStIdx(), varmeexpr)); } } MeExpr *IRMap::BuildExpr(BaseNode &mirNode) { Opcode op = mirNode.GetOpCode(); if (op == OP_dread) { AddrofSSANode &addrofnode = static_cast(mirNode); VersionSt *verSt = addrofnode.GetSSAVar(); VarMeExpr *varmeexpr = GetOrCreateVarFromVerSt(*verSt); varmeexpr->InitBase(mirNode.GetOpCode(), mirNode.GetPrimType(), mirNode.GetNumOpnds()); if (verSt->GetOrigSt()->IsRealSymbol()) { ASSERT(!verSt->GetOrigSt()->IsPregOst(), "not expect preg symbol here"); varmeexpr->SetPtyp(GlobalTables::GetTypeTable().GetTypeFromTyIdx(verSt->GetOrigSt()->GetTyIdx())->GetPrimType()); varmeexpr->SetFieldID(addrofnode.GetFieldID()); } return varmeexpr; } if (op == OP_regread) { RegreadSSANode ®node = static_cast(mirNode); VersionSt *verSt = regnode.GetSSAVar(); RegMeExpr *regmeexpr = GetOrCreateRegFromVerSt(*verSt); regmeexpr->InitBase(mirNode.GetOpCode(), mirNode.GetPrimType(), mirNode.GetNumOpnds()); return regmeexpr; } MeExpr *meExpr = meBuilder.BuildMeExpr(mirNode); SetMeExprOpnds(*meExpr, mirNode); if (op == OP_iread) { IvarMeExpr *ivarMeExpr = static_cast(meExpr); IreadSSANode &ireadSSANode = static_cast(mirNode); ivarMeExpr->SetBase(BuildExpr(*ireadSSANode.Opnd(0))); VersionSt *verSt = ireadSSANode.GetSSAVar(); if (verSt != nullptr) { VarMeExpr *varMeExpr = GetOrCreateVarFromVerSt(*verSt); ivarMeExpr->SetMuVal(varMeExpr); } } MeExpr *retMeExpr = HashMeExpr(*meExpr); if (op == OP_iread) { ASSERT(static_cast(retMeExpr)->GetMu() != nullptr, "BuildExpr: ivar node cannot have mu == nullptr"); } return retMeExpr; } void IRMap::SetMeExprOpnds(MeExpr &meExpr, BaseNode &mirNode) { OpMeExpr &opMeExpr = static_cast(meExpr); if (mirNode.IsUnaryNode()) { if (mirNode.GetOpCode() != OP_iread) { opMeExpr.SetOpnd(0, BuildExpr(*static_cast(mirNode).Opnd(0))); } } else if (mirNode.IsBinaryNode()) { BinaryNode &binaryNode = static_cast(mirNode); opMeExpr.SetOpnd(0, BuildExpr(*binaryNode.Opnd(0))); opMeExpr.SetOpnd(1, BuildExpr(*binaryNode.Opnd(1))); } else if (mirNode.IsTernaryNode()) { TernaryNode &ternaryNode = static_cast(mirNode); opMeExpr.SetOpnd(0, BuildExpr(*ternaryNode.Opnd(0))); opMeExpr.SetOpnd(1, BuildExpr(*ternaryNode.Opnd(1))); opMeExpr.SetOpnd(2, BuildExpr(*ternaryNode.Opnd(2))); } else if (mirNode.IsNaryNode()) { NaryMeExpr &naryMeExpr = static_cast(meExpr); NaryNode &naryNode = static_cast(mirNode); for (size_t i = 0; i < naryNode.NumOpnds(); ++i) { naryMeExpr.GetOpnds().push_back(BuildExpr(*naryNode.Opnd(i))); } } else { // No need to do anything } } void IRMap::PutToBucket(uint32 hashidx, MeExpr &meExpr) { MeExpr *headexpr = hashTable[hashidx]; if (headexpr != nullptr) { meExpr.SetNext(headexpr); } hashTable[hashidx] = &meExpr; } MeExpr *IRMap::HashMeExpr(MeExpr &meExpr) { MeExpr *resultExpr = nullptr; uint32 hidx = meExpr.GetHashIndex() % mapHashLength; MeExpr *hashedExpr = hashTable[hidx]; if (hashedExpr != nullptr && meExpr.GetMeOp() != kMeOpGcmalloc) { resultExpr = meExpr.GetIdenticalExpr(*hashedExpr); } if (resultExpr == nullptr) { resultExpr = meBuilder.CreateMeExpr(exprID++, meExpr); if (resultExpr != nullptr) { PutToBucket(hidx, *resultExpr); } } return resultExpr; } MeExpr *IRMap::ReplaceMeExprExpr(MeExpr &origExpr, MeExpr &newExpr, size_t opndsSize, MeExpr &meExpr, MeExpr &repExpr) { bool needRehash = false; for (size_t i = 0; i < opndsSize; ++i) { MeExpr *origOpnd = origExpr.GetOpnd(i); if (origOpnd == nullptr) { continue; } if (origOpnd == &meExpr) { needRehash = true; newExpr.SetOpnd(i, &repExpr); } else if (!origOpnd->IsLeaf()) { newExpr.SetOpnd(i, ReplaceMeExprExpr(*newExpr.GetOpnd(i), meExpr, repExpr)); if (newExpr.GetOpnd(i) != origOpnd) { needRehash = true; } } } return needRehash ? HashMeExpr(newExpr) : &origExpr; } // replace meExpr with repexpr. meExpr must be a kid of origexpr // return repexpr's parent if replaced, otherwise return nullptr MeExpr *IRMap::ReplaceMeExprExpr(MeExpr &origExpr, MeExpr &meExpr, MeExpr &repExpr) { if (origExpr.IsLeaf()) { return &origExpr; } switch (origExpr.GetMeOp()) { case kMeOpOp: { OpMeExpr &opMeExpr = static_cast(origExpr); OpMeExpr newMeExpr(opMeExpr, kInvalidExprID); return ReplaceMeExprExpr(opMeExpr, newMeExpr, kOperandNumTernary, meExpr, repExpr); } case kMeOpNary: { NaryMeExpr &narymeexpr = static_cast(origExpr); NaryMeExpr newmeexpr(&irMapAlloc, kInvalidExprID, narymeexpr); return ReplaceMeExprExpr(narymeexpr, newmeexpr, narymeexpr.GetOpnds().size(), meExpr, repExpr); } case kMeOpIvar: { IvarMeExpr &ivarexpr = static_cast(origExpr); IvarMeExpr newmeexpr(kInvalidExprID, ivarexpr); bool needRehash = false; if (ivarexpr.GetBase() == &meExpr) { newmeexpr.SetBase(&repExpr); needRehash = true; } else if (!ivarexpr.GetBase()->IsLeaf()) { newmeexpr.SetBase(ReplaceMeExprExpr(*newmeexpr.GetBase(), meExpr, repExpr)); if (newmeexpr.GetBase() != ivarexpr.GetBase()) { needRehash = true; } } return needRehash ? HashMeExpr(newmeexpr) : &origExpr; } default: ASSERT(false, "NYI"); return nullptr; } } bool IRMap::ReplaceMeExprStmtOpnd(uint32 opndID, MeStmt &meStmt, MeExpr &meExpr, MeExpr &repExpr) { MeExpr *opnd = meStmt.GetOpnd(opndID); if (opnd == &meExpr) { meStmt.SetOpnd(opndID, &repExpr); return true; } else if (!opnd->IsLeaf()) { meStmt.SetOpnd(opndID, ReplaceMeExprExpr(*opnd, meExpr, repExpr)); return meStmt.GetOpnd(opndID) != opnd; } return false; } // replace meExpr in meStmt with repexpr bool IRMap::ReplaceMeExprStmt(MeStmt &meStmt, MeExpr &meExpr, MeExpr &repexpr) { bool isReplaced = false; Opcode op = meStmt.GetOp(); for (size_t i = 0; i < meStmt.NumMeStmtOpnds(); ++i) { if (op == OP_intrinsiccall || op == OP_xintrinsiccall || op == OP_intrinsiccallwithtype || op == OP_intrinsiccallassigned || op == OP_xintrinsiccallassigned || op == OP_intrinsiccallwithtypeassigned) { MeExpr *opnd = meStmt.GetOpnd(i); if (opnd->IsLeaf() && opnd->GetMeOp() == kMeOpVar) { VarMeExpr *varmeexpr = static_cast(opnd); const OriginalSt *orgsym = ssaTab.GetOriginalStFromID(varmeexpr->GetOStIdx()); if (orgsym->IsSymbolOst() && orgsym->GetMIRSymbol()->GetAttr(ATTR_static)) { // its address may be taken continue; } } } bool curOpndReplaced = ReplaceMeExprStmtOpnd(i, meStmt, meExpr, repexpr); isReplaced = isReplaced || curOpndReplaced; if (i == 0 && curOpndReplaced && op == OP_iassign) { IassignMeStmt &ivarstmt = static_cast(meStmt); ivarstmt.SetLHSVal(BuildLHSIvar(*ivarstmt.GetOpnd(0), ivarstmt, ivarstmt.GetLHSVal()->GetFieldID())); } } return isReplaced; } MeRegPhiNode *IRMap::CreateMeRegPhi(RegMeExpr &mevar) { MeRegPhiNode *phimereg = NewInPool(); phimereg->UpdateLHS(mevar); return phimereg; } MeVarPhiNode *IRMap::CreateMeVarPhi(VarMeExpr &mevar) { MeVarPhiNode *phimevar = NewInPool(); phimevar->UpdateLHS(mevar); return phimevar; } DassignMeStmt *IRMap::CreateDassignMeStmt(MeExpr &lhs, MeExpr &rhs, BB &curbb) { DassignMeStmt *meStmt = NewInPool(); meStmt->SetRHS(&rhs); VarMeExpr &var = static_cast(lhs); meStmt->SetLHS(&var); var.SetDefBy(kDefByStmt); var.SetDefStmt(meStmt); meStmt->SetBB(&curbb); return meStmt; } RegassignMeStmt *IRMap::CreateRegassignMeStmt(MeExpr &lhs, MeExpr &rhs, BB &curbb) { RegassignMeStmt *meStmt = New(); ASSERT(lhs.GetMeOp() == kMeOpReg, "Create regassign without lhs == regread"); meStmt->SetRHS(&rhs); RegMeExpr ® = static_cast(lhs); meStmt->SetLHS(®); reg.SetDefBy(kDefByStmt); reg.SetDefStmt(meStmt); meStmt->SetBB(&curbb); return meStmt; } // get the false goto bb, if condgoto is brtrue, take the other bb of brture @lable // otherwise, take the bb of @lable BB *IRMap::GetFalseBrBB(CondGotoMeStmt &condgoto) { LabelIdx lblidx = (LabelIdx)condgoto.GetOffset(); BB *gotobb = GetBBForLabIdx(lblidx); BB *bb = condgoto.GetBB(); ASSERT(bb->GetSucc().size() == kBBVectorInitialSize, "array size error"); if (condgoto.GetOp() == OP_brfalse) { return gotobb; } else { return gotobb == bb->GetSucc(0) ? bb->GetSucc(1) : bb->GetSucc(0); } } MeExpr *IRMap::CreateConstMeExpr(PrimType ptyp, MIRConst &mirConst) { ConstMeExpr constMeExpr(kInvalidExprID, &mirConst); constMeExpr.SetOp(OP_constval); constMeExpr.SetPtyp(ptyp); return HashMeExpr(constMeExpr); } MeExpr *IRMap::CreateIntConstMeExpr(int64 value, PrimType ptyp) { MIRIntConst *intConst = mirModule.GetMemPool()->New(value, *GlobalTables::GetTypeTable().GetPrimType(ptyp)); return CreateConstMeExpr(ptyp, *intConst); } MeExpr *IRMap::CreateMeExprBinary(Opcode op, PrimType ptyp, MeExpr &expr0, MeExpr &expr1) { OpMeExpr opmeexpr(kInvalidExprID); opmeexpr.SetOpnd(0, &expr0); opmeexpr.SetOpnd(1, &expr1); opmeexpr.InitBase(op, ptyp, kOperandNumBinary); return HashMeExpr(opmeexpr); } MeExpr *IRMap::CreateMeExprSelect(PrimType ptyp, MeExpr &expr0, MeExpr &expr1, MeExpr &expr2) { OpMeExpr opmeexpr(kInvalidExprID); opmeexpr.SetOpnd(0, &expr0); opmeexpr.SetOpnd(1, &expr1); opmeexpr.SetOpnd(2, &expr2); opmeexpr.InitBase(OP_select, ptyp, kOperandNumTernary); return HashMeExpr(opmeexpr); } MeExpr *IRMap::CreateMeExprCompare(Opcode op, PrimType resptyp, PrimType opndptyp, MeExpr &opnd0, MeExpr &opnd1) { OpMeExpr opmeexpr(kInvalidExprID); opmeexpr.SetOpnd(0, &opnd0); opmeexpr.SetOpnd(1, &opnd1); opmeexpr.InitBase(op, resptyp, kOperandNumBinary); opmeexpr.SetOpndType(opndptyp); MeExpr *retmeexpr = HashMeExpr(opmeexpr); static_cast(retmeexpr)->SetOpndType(opndptyp); return retmeexpr; } MeExpr *IRMap::CreateMeExprTypeCvt(PrimType ptyp, PrimType opndptyp, MeExpr &opnd0) { OpMeExpr opmeexpr(kInvalidExprID); opmeexpr.SetOpnd(0, &opnd0); opmeexpr.InitBase(OP_cvt, ptyp, kOperandNumUnary); opmeexpr.SetOpndType(opndptyp); return HashMeExpr(opmeexpr); } IntrinsiccallMeStmt *IRMap::CreateIntrinsicCallMeStmt(MIRIntrinsicID idx, std::vector &opnds, TyIdx tyidx) { IntrinsiccallMeStmt *meStmt = NewInPool(tyidx == 0 ? OP_intrinsiccall : OP_intrinsiccallwithtype, idx, tyidx); for (MeExpr *opnd : opnds) { meStmt->GetOpnds().push_back(opnd); } return meStmt; } IntrinsiccallMeStmt *IRMap::CreateIntrinsicCallAssignedMeStmt(MIRIntrinsicID idx, std::vector &opnds, MeExpr *ret, TyIdx tyidx) { IntrinsiccallMeStmt *meStmt = NewInPool( tyidx == 0 ? OP_intrinsiccallassigned : OP_intrinsiccallwithtypeassigned, idx, tyidx); for (MeExpr *opnd : opnds) { meStmt->GetOpnds().push_back(opnd); } if (ret != nullptr) { ASSERT(ret->GetMeOp() == kMeOpReg || ret->GetMeOp() == kMeOpVar, "unexpected opcode"); MustDefMeNode *mustdef = New(ret, meStmt); meStmt->GetMustDefList()->push_back(*mustdef); } return meStmt; } MeExpr *IRMap::CreateAddrofMeExprFromNewSymbol(MIRSymbol &st, PUIdx puidx) { OriginalSt *baseOst = ssaTab.CreateSymbolOriginalSt(st, puidx, 0); AddrofMeExpr addrofme(kInvalidExprID, baseOst->GetIndex()); addrofme.SetOp(OP_addrof); addrofme.SetPtyp(PTY_ptr); return HashMeExpr(addrofme); } void IRMap::InitMeStmtFactory() const { RegisterFactoryFunction(OP_dassign, &IRMap::BuildDassignMeStmt); RegisterFactoryFunction(OP_regassign, &IRMap::BuildRegassignMeStmt); RegisterFactoryFunction(OP_iassign, &IRMap::BuildIassignMeStmt); RegisterFactoryFunction(OP_maydassign, &IRMap::BuildMaydassignMeStmt); RegisterFactoryFunction(OP_call, &IRMap::BuildCallMeStmt); RegisterFactoryFunction(OP_virtualcall, &IRMap::BuildCallMeStmt); RegisterFactoryFunction(OP_virtualicall, &IRMap::BuildCallMeStmt); RegisterFactoryFunction(OP_superclasscall, &IRMap::BuildCallMeStmt); RegisterFactoryFunction(OP_interfacecall, &IRMap::BuildCallMeStmt); RegisterFactoryFunction(OP_interfaceicall, &IRMap::BuildCallMeStmt); RegisterFactoryFunction(OP_customcall, &IRMap::BuildCallMeStmt); RegisterFactoryFunction(OP_polymorphiccall, &IRMap::BuildCallMeStmt); RegisterFactoryFunction(OP_callassigned, &IRMap::BuildCallMeStmt); RegisterFactoryFunction(OP_virtualcallassigned, &IRMap::BuildCallMeStmt); RegisterFactoryFunction(OP_virtualicallassigned, &IRMap::BuildCallMeStmt); RegisterFactoryFunction(OP_superclasscallassigned, &IRMap::BuildCallMeStmt); RegisterFactoryFunction(OP_interfacecallassigned, &IRMap::BuildCallMeStmt); RegisterFactoryFunction(OP_interfaceicallassigned, &IRMap::BuildCallMeStmt); RegisterFactoryFunction(OP_customcallassigned, &IRMap::BuildCallMeStmt); RegisterFactoryFunction(OP_polymorphiccallassigned, &IRMap::BuildCallMeStmt); RegisterFactoryFunction(OP_icall, &IRMap::BuildNaryMeStmt); RegisterFactoryFunction(OP_icallassigned, &IRMap::BuildNaryMeStmt); RegisterFactoryFunction(OP_intrinsiccall, &IRMap::BuildNaryMeStmt); RegisterFactoryFunction(OP_xintrinsiccall, &IRMap::BuildNaryMeStmt); RegisterFactoryFunction(OP_intrinsiccallwithtype, &IRMap::BuildNaryMeStmt); RegisterFactoryFunction(OP_intrinsiccallassigned, &IRMap::BuildNaryMeStmt); RegisterFactoryFunction(OP_intrinsiccallwithtypeassigned, &IRMap::BuildNaryMeStmt); RegisterFactoryFunction(OP_return, &IRMap::BuildRetMeStmt); RegisterFactoryFunction(OP_retsub, &IRMap::BuildWithMuMeStmt); RegisterFactoryFunction(OP_gosub, &IRMap::BuildGosubMeStmt); RegisterFactoryFunction(OP_throw, &IRMap::BuildThrowMeStmt); RegisterFactoryFunction(OP_syncenter, &IRMap::BuildSyncMeStmt); RegisterFactoryFunction(OP_syncexit, &IRMap::BuildSyncMeStmt); } } // namespace maple BIMDataHub/OpenStudio-1openstudiocore/src/model/WaterToAirComponent.hpp1-10 /********************************************************************** * Copyright (c) 2008-2015, Alliance for Sustainable Energy. * All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * 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 **********************************************************************/ #ifndef MODEL_WATERTOAIRCOMPONENT_HPP #define MODEL_WATERTOAIRCOMPONENT_HPP #include "ModelAPI.hpp" #include "HVACComponent.hpp" namespace openstudio { namespace model { namespace detail{ class WaterToAirComponent_Impl; } class AirLoopHVAC; class PlantLoop; /** WaterToAirComponent is the base class for model objects which interact with * an air stream and a water stream. * * These objects are typically water coils such as the EnergyPlus IDD objects * named Coil:Heating:Water and Coil:Cooling:Water. */ class MODEL_API WaterToAirComponent : public HVACComponent { public: virtual ~WaterToAirComponent() {} /** Returns the air inlet port. **/ virtual unsigned airInletPort(); /** Returns the air outlet port. **/ virtual unsigned airOutletPort(); /** Returns the optional ModelObject connected to the air inlet port. **/ virtual boost::optional airInletModelObject(); /** Returns the optional ModelObject connected to the air outlet port. **/ virtual boost::optional airOutletModelObject(); /** Returns the water inlet port. **/ virtual unsigned waterInletPort(); /** Returns the water outlet port. **/ virtual unsigned waterOutletPort(); /** Returns the optional ModelObject connected to the water inlet port. **/ virtual boost::optional waterInletModelObject(); /** Returns the optional ModelObject connected to the water outlet port. **/ virtual boost::optional waterOutletModelObject(); virtual boost::optional airLoopHVAC() const; virtual boost::optional plantLoop() const; virtual bool addToNode(Node & node); virtual bool addToSplitter(Splitter & splitter); virtual std::vector remove(); virtual ModelObject clone(Model model) const; void disconnectWaterSide(); void disconnectAirSide(); /** Removes the component from the airLoopHVAC if one is attached. * Repairs the airLoopHVAC connections preserving the integrity of the loop. * Does not remove the component from the model */ bool removeFromAirLoopHVAC(); /** Removes the component from the plantLoop if one is attached. * Repairs the plantLoop connections preserving the integrity of the loop. * Does not remove the component from the model */ bool removeFromPlantLoop(); protected: friend class Model; friend class openstudio::IdfObject; /// @cond typedef detail::WaterToAirComponent_Impl ImplType; explicit WaterToAirComponent(std::shared_ptr impl); WaterToAirComponent(IddObjectType type,const Model& model); private: REGISTER_LOGGER("openstudio.model.WaterToAirComponent"); /// @endcond }; typedef boost::optional OptionalWaterToAirComponent; } // model } // openstudio #endif // MODEL_WATERTOAIRCOMPONENT_HPP #include #include #include extern "C" JNIEXPORT jstring JNICALL Java_com_xinghai_multi_JniUtil_stringFromOne(JNIEnv *env, jclass type) { std::string tag = "one ndk"; char* msg = "日志打印"; __android_log_print(ANDROID_LOG_DEBUG, tag.c_str(), "%s\n", msg); std::string hello = "ndk one"; return env->NewStringUTF(hello.c_str()); }#pragma once #include "../aabb2d.hpp" #include "frea/src/serialization/vector.hpp" namespace beat { namespace g2 { template void serialize(Ar& ar, AABB& ab) { ar( cereal::make_nvp("min", ab.min), cereal::make_nvp("max", ab.max) ); } } } net/disk_cache/entry_unittest.cc // Copyright (c) 2006-2008 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 "base/platform_thread.h" #include "base/timer.h" #include "base/string_util.h" #include "net/base/net_errors.h" #include "net/disk_cache/disk_cache_test_base.h" #include "net/disk_cache/disk_cache_test_util.h" #include "net/disk_cache/entry_impl.h" #include "testing/gtest/include/gtest/gtest.h" extern int g_cache_tests_max_id; extern volatile int g_cache_tests_received; extern volatile bool g_cache_tests_error; // Tests that can run with different types of caches. class DiskCacheEntryTest : public DiskCacheTestWithCache { protected: void InternalSyncIO(); void InternalAsyncIO(); void ExternalSyncIO(); void ExternalAsyncIO(); void GetKey(); void GrowData(); void TruncateData(); void ReuseEntry(int size); void InvalidData(); void DoomEntry(); void DoomedEntry(); }; void DiskCacheEntryTest::InternalSyncIO() { disk_cache::Entry *entry1 = NULL; ASSERT_TRUE(cache_->CreateEntry("the first key", &entry1)); ASSERT_TRUE(NULL != entry1); char buffer1[10]; CacheTestFillBuffer(buffer1, sizeof(buffer1), false); EXPECT_EQ(0, entry1->ReadData(0, 0, buffer1, sizeof(buffer1), NULL)); base::strlcpy(buffer1, "the data", sizeof(buffer1)); EXPECT_EQ(10, entry1->WriteData(0, 0, buffer1, sizeof(buffer1), NULL, false)); memset(buffer1, 0, sizeof(buffer1)); EXPECT_EQ(10, entry1->ReadData(0, 0, buffer1, sizeof(buffer1), NULL)); EXPECT_STREQ("the data", buffer1); char buffer2[5000]; char buffer3[10000] = {0}; CacheTestFillBuffer(buffer2, sizeof(buffer2), false); base::strlcpy(buffer2, "The really big data goes here", sizeof(buffer2)); EXPECT_EQ(5000, entry1->WriteData(1, 1500, buffer2, sizeof(buffer2), NULL, false)); memset(buffer2, 0, sizeof(buffer2)); EXPECT_EQ(4989, entry1->ReadData(1, 1511, buffer2, sizeof(buffer2), NULL)); EXPECT_STREQ("big data goes here", buffer2); EXPECT_EQ(5000, entry1->ReadData(1, 0, buffer2, sizeof(buffer2), NULL)); EXPECT_EQ(0, memcmp(buffer2, buffer3, 1500)); EXPECT_EQ(1500, entry1->ReadData(1, 5000, buffer2, sizeof(buffer2), NULL)); EXPECT_EQ(0, entry1->ReadData(1, 6500, buffer2, sizeof(buffer2), NULL)); EXPECT_EQ(6500, entry1->ReadData(1, 0, buffer3, sizeof(buffer3), NULL)); EXPECT_EQ(8192, entry1->WriteData(1, 0, buffer3, 8192, NULL, false)); EXPECT_EQ(8192, entry1->ReadData(1, 0, buffer3, sizeof(buffer3), NULL)); EXPECT_EQ(8192, entry1->GetDataSize(1)); entry1->Doom(); entry1->Close(); EXPECT_EQ(0, cache_->GetEntryCount()); } TEST_F(DiskCacheEntryTest, InternalSyncIO) { InitCache(); InternalSyncIO(); } TEST_F(DiskCacheEntryTest, MemoryOnlyInternalSyncIO) { SetMemoryOnlyMode(); InitCache(); InternalSyncIO(); } void DiskCacheEntryTest::InternalAsyncIO() { disk_cache::Entry *entry1 = NULL; ASSERT_TRUE(cache_->CreateEntry("the first key", &entry1)); ASSERT_TRUE(NULL != entry1); // Let's verify that each IO goes to the right callback object. CallbackTest callback1(1, false); CallbackTest callback2(2, false); CallbackTest callback3(3, false); CallbackTest callback4(4, false); CallbackTest callback5(5, false); CallbackTest callback6(6, false); CallbackTest callback7(7, false); CallbackTest callback8(8, false); CallbackTest callback9(9, false); CallbackTest callback10(10, false); CallbackTest callback11(11, false); CallbackTest callback12(12, false); CallbackTest callback13(13, false); g_cache_tests_error = false; g_cache_tests_max_id = 0; g_cache_tests_received = 0; MessageLoopHelper helper; char buffer1[10]; char buffer2[5000]; char buffer3[10000]; CacheTestFillBuffer(buffer1, sizeof(buffer1), false); CacheTestFillBuffer(buffer2, sizeof(buffer2), false); CacheTestFillBuffer(buffer3, sizeof(buffer3), false); EXPECT_EQ(0, entry1->ReadData(0, 0, buffer1, sizeof(buffer1), &callback1)); base::strlcpy(buffer1, "the data", sizeof(buffer1)); int expected = 0; int ret = entry1->WriteData(0, 0, buffer1, sizeof(buffer1), &callback2, false); EXPECT_TRUE(10 == ret || net::ERR_IO_PENDING == ret); if (net::ERR_IO_PENDING == ret) expected++; memset(buffer2, 0, sizeof(buffer1)); ret = entry1->ReadData(0, 0, buffer2, sizeof(buffer1), &callback3); EXPECT_TRUE(10 == ret || net::ERR_IO_PENDING == ret); if (net::ERR_IO_PENDING == ret) expected++; g_cache_tests_max_id = 3; EXPECT_TRUE(helper.WaitUntilCacheIoFinished(expected)); EXPECT_STREQ("the data", buffer2); base::strlcpy(buffer2, "The really big data goes here", sizeof(buffer2)); ret = entry1->WriteData(1, 1500, buffer2, sizeof(buffer2), &callback4, false); EXPECT_TRUE(5000 == ret || net::ERR_IO_PENDING == ret); if (net::ERR_IO_PENDING == ret) expected++; memset(buffer3, 0, sizeof(buffer2)); ret = entry1->ReadData(1, 1511, buffer3, sizeof(buffer2), &callback5); EXPECT_TRUE(4989 == ret || net::ERR_IO_PENDING == ret); if (net::ERR_IO_PENDING == ret) expected++; g_cache_tests_max_id = 5; EXPECT_TRUE(helper.WaitUntilCacheIoFinished(expected)); EXPECT_STREQ("big data goes here", buffer3); ret = entry1->ReadData(1, 0, buffer2, sizeof(buffer2), &callback6); EXPECT_TRUE(5000 == ret || net::ERR_IO_PENDING == ret); if (net::ERR_IO_PENDING == ret) expected++; memset(buffer3, 0, sizeof(buffer3)); g_cache_tests_max_id = 6; EXPECT_TRUE(helper.WaitUntilCacheIoFinished(expected)); EXPECT_EQ(0, memcmp(buffer2, buffer3, 1500)); ret = entry1->ReadData(1, 5000, buffer2, sizeof(buffer2), &callback7); EXPECT_TRUE(1500 == ret || net::ERR_IO_PENDING == ret); if (net::ERR_IO_PENDING == ret) expected++; EXPECT_EQ(0, entry1->ReadData(1, 6500, buffer2, sizeof(buffer2), &callback8)); ret = entry1->ReadData(1, 0, buffer3, sizeof(buffer3), &callback9); EXPECT_TRUE(6500 == ret || net::ERR_IO_PENDING == ret); if (net::ERR_IO_PENDING == ret) expected++; ret = entry1->WriteData(1, 0, buffer3, 8192, &callback10, false); EXPECT_TRUE(8192 == ret || net::ERR_IO_PENDING == ret); if (net::ERR_IO_PENDING == ret) expected++; ret = entry1->ReadData(1, 0, buffer3, sizeof(buffer3), &callback11); EXPECT_TRUE(8192 == ret || net::ERR_IO_PENDING == ret); if (net::ERR_IO_PENDING == ret) expected++; EXPECT_EQ(8192, entry1->GetDataSize(1)); ret = entry1->ReadData(0, 0, buffer1, sizeof(buffer1), &callback12); EXPECT_TRUE(10 == ret || net::ERR_IO_PENDING == ret); if (net::ERR_IO_PENDING == ret) expected++; ret = entry1->ReadData(1, 0, buffer2, sizeof(buffer2), &callback13); EXPECT_TRUE(5000 == ret || net::ERR_IO_PENDING == ret); if (net::ERR_IO_PENDING == ret) expected++; g_cache_tests_max_id = 13; EXPECT_TRUE(helper.WaitUntilCacheIoFinished(expected)); EXPECT_FALSE(g_cache_tests_error); EXPECT_EQ(expected, g_cache_tests_received); entry1->Doom(); entry1->Close(); EXPECT_EQ(0, cache_->GetEntryCount()); } TEST_F(DiskCacheEntryTest, InternalAsyncIO) { InitCache(); InternalAsyncIO(); } TEST_F(DiskCacheEntryTest, MemoryOnlyInternalAsyncIO) { SetMemoryOnlyMode(); InitCache(); InternalAsyncIO(); } void DiskCacheEntryTest::ExternalSyncIO() { disk_cache::Entry *entry1; ASSERT_TRUE(cache_->CreateEntry("the first key", &entry1)); char buffer1[17000], buffer2[25000]; CacheTestFillBuffer(buffer1, sizeof(buffer1), false); CacheTestFillBuffer(buffer2, sizeof(buffer2), false); base::strlcpy(buffer1, "the data", sizeof(buffer1)); EXPECT_EQ(17000, entry1->WriteData(0, 0, buffer1, sizeof(buffer1), NULL, false)); memset(buffer1, 0, sizeof(buffer1)); EXPECT_EQ(17000, entry1->ReadData(0, 0, buffer1, sizeof(buffer1), NULL)); EXPECT_STREQ("the data", buffer1); base::strlcpy(buffer2, "The really big data goes here", sizeof(buffer2)); EXPECT_EQ(25000, entry1->WriteData(1, 10000, buffer2, sizeof(buffer2), NULL, false)); memset(buffer2, 0, sizeof(buffer2)); EXPECT_EQ(24989, entry1->ReadData(1, 10011, buffer2, sizeof(buffer2), NULL)); EXPECT_STREQ("big data goes here", buffer2); EXPECT_EQ(25000, entry1->ReadData(1, 0, buffer2, sizeof(buffer2), NULL)); EXPECT_EQ(0, memcmp(buffer2, buffer2, 10000)); EXPECT_EQ(5000, entry1->ReadData(1, 30000, buffer2, sizeof(buffer2), NULL)); EXPECT_EQ(0, entry1->ReadData(1, 35000, buffer2, sizeof(buffer2), NULL)); EXPECT_EQ(17000, entry1->ReadData(1, 0, buffer1, sizeof(buffer1), NULL)); EXPECT_EQ(17000, entry1->WriteData(1, 20000, buffer1, sizeof(buffer1), NULL, false)); EXPECT_EQ(37000, entry1->GetDataSize(1)); entry1->Doom(); entry1->Close(); EXPECT_EQ(0, cache_->GetEntryCount()); } TEST_F(DiskCacheEntryTest, ExternalSyncIO) { InitCache(); ExternalSyncIO(); } TEST_F(DiskCacheEntryTest, MemoryOnlyExternalSyncIO) { SetMemoryOnlyMode(); InitCache(); ExternalSyncIO(); } void DiskCacheEntryTest::ExternalAsyncIO() { disk_cache::Entry *entry1; ASSERT_TRUE(cache_->CreateEntry("the first key", &entry1)); // Let's verify that each IO goes to the right callback object. CallbackTest callback1(1, false); CallbackTest callback2(2, false); CallbackTest callback3(3, false); CallbackTest callback4(4, false); CallbackTest callback5(5, false); CallbackTest callback6(6, false); CallbackTest callback7(7, false); CallbackTest callback8(8, false); CallbackTest callback9(9, false); g_cache_tests_error = false; g_cache_tests_max_id = 0; g_cache_tests_received = 0; int expected = 0; MessageLoopHelper helper; char buffer1[17000], buffer2[25000], buffer3[25000]; CacheTestFillBuffer(buffer1, sizeof(buffer1), false); CacheTestFillBuffer(buffer2, sizeof(buffer2), false); CacheTestFillBuffer(buffer3, sizeof(buffer3), false); base::strlcpy(buffer1, "the data", sizeof(buffer1)); int ret = entry1->WriteData(0, 0, buffer1, sizeof(buffer1), &callback1, false); EXPECT_TRUE(17000 == ret || net::ERR_IO_PENDING == ret); if (net::ERR_IO_PENDING == ret) expected++; g_cache_tests_max_id = 1; EXPECT_TRUE(helper.WaitUntilCacheIoFinished(expected)); memset(buffer2, 0, sizeof(buffer1)); ret = entry1->ReadData(0, 0, buffer2, sizeof(buffer1), &callback2); EXPECT_TRUE(17000 == ret || net::ERR_IO_PENDING == ret); if (net::ERR_IO_PENDING == ret) expected++; g_cache_tests_max_id = 2; EXPECT_TRUE(helper.WaitUntilCacheIoFinished(expected)); EXPECT_STREQ("the data", buffer1); base::strlcpy(buffer2, "The really big data goes here", sizeof(buffer2)); ret = entry1->WriteData(1, 10000, buffer2, sizeof(buffer2), &callback3, false); EXPECT_TRUE(25000 == ret || net::ERR_IO_PENDING == ret); if (net::ERR_IO_PENDING == ret) expected++; g_cache_tests_max_id = 3; EXPECT_TRUE(helper.WaitUntilCacheIoFinished(expected)); memset(buffer3, 0, sizeof(buffer3)); ret = entry1->ReadData(1, 10011, buffer3, sizeof(buffer3), &callback4); EXPECT_TRUE(24989 == ret || net::ERR_IO_PENDING == ret); if (net::ERR_IO_PENDING == ret) expected++; g_cache_tests_max_id = 4; EXPECT_TRUE(helper.WaitUntilCacheIoFinished(expected)); EXPECT_STREQ("big data goes here", buffer3); ret = entry1->ReadData(1, 0, buffer2, sizeof(buffer2), &callback5); EXPECT_TRUE(25000 == ret || net::ERR_IO_PENDING == ret); if (net::ERR_IO_PENDING == ret) expected++; g_cache_tests_max_id = 5; EXPECT_TRUE(helper.WaitUntilCacheIoFinished(expected)); EXPECT_EQ(0, memcmp(buffer2, buffer2, 10000)); ret = entry1->ReadData(1, 30000, buffer2, sizeof(buffer2), &callback6); EXPECT_TRUE(5000 == ret || net::ERR_IO_PENDING == ret); if (net::ERR_IO_PENDING == ret) expected++; EXPECT_EQ(0, entry1->ReadData(1, 35000, buffer2, sizeof(buffer2), &callback7)); ret = entry1->ReadData(1, 0, buffer1, sizeof(buffer1), &callback8); EXPECT_TRUE(17000 == ret || net::ERR_IO_PENDING == ret); if (net::ERR_IO_PENDING == ret) expected++; ret = entry1->WriteData(1, 20000, buffer1, sizeof(buffer1), &callback9, false); EXPECT_TRUE(17000 == ret || net::ERR_IO_PENDING == ret); if (net::ERR_IO_PENDING == ret) expected++; EXPECT_EQ(37000, entry1->GetDataSize(1)); g_cache_tests_max_id = 9; EXPECT_TRUE(helper.WaitUntilCacheIoFinished(expected)); EXPECT_FALSE(g_cache_tests_error); EXPECT_EQ(expected, g_cache_tests_received); entry1->Doom(); entry1->Close(); EXPECT_EQ(0, cache_->GetEntryCount()); } TEST_F(DiskCacheEntryTest, ExternalAsyncIO) { InitCache(); ExternalAsyncIO(); } TEST_F(DiskCacheEntryTest, MemoryOnlyExternalAsyncIO) { SetMemoryOnlyMode(); InitCache(); ExternalAsyncIO(); } void DiskCacheEntryTest::GetKey() { std::string key1("the first key"); disk_cache::Entry *entry1; ASSERT_TRUE(cache_->CreateEntry(key1, &entry1)); EXPECT_EQ(key1, entry1->GetKey()) << "short key"; entry1->Close(); int seed = static_cast(Time::Now().ToInternalValue()); srand(seed); char key_buffer[20000]; CacheTestFillBuffer(key_buffer, 3000, true); key_buffer[1000] = '\0'; key1 = key_buffer; ASSERT_TRUE(cache_->CreateEntry(key1, &entry1)); EXPECT_TRUE(key1 == entry1->GetKey()) << "1000 bytes key"; entry1->Close(); key_buffer[1000] = 'p'; key_buffer[3000] = '\0'; key1 = key_buffer; ASSERT_TRUE(cache_->CreateEntry(key1, &entry1)); EXPECT_TRUE(key1 == entry1->GetKey()) << "medium size key"; entry1->Close(); CacheTestFillBuffer(key_buffer, sizeof(key_buffer), true); key_buffer[19999] = '\0'; key1 = key_buffer; ASSERT_TRUE(cache_->CreateEntry(key1, &entry1)); EXPECT_TRUE(key1 == entry1->GetKey()) << "long key"; entry1->Close(); } TEST_F(DiskCacheEntryTest, GetKey) { InitCache(); GetKey(); } TEST_F(DiskCacheEntryTest, MemoryOnlyGetKey) { SetMemoryOnlyMode(); InitCache(); GetKey(); } void DiskCacheEntryTest::GrowData() { std::string key1("the first key"); disk_cache::Entry *entry1, *entry2; ASSERT_TRUE(cache_->CreateEntry(key1, &entry1)); char buffer1[20000]; char buffer2[20000]; CacheTestFillBuffer(buffer1, sizeof(buffer1), false); memset(buffer2, 0, sizeof(buffer2)); base::strlcpy(buffer1, "the data", sizeof(buffer1)); EXPECT_EQ(10, entry1->WriteData(0, 0, buffer1, 10, NULL, false)); EXPECT_EQ(10, entry1->ReadData(0, 0, buffer2, 10, NULL)); EXPECT_STREQ("the data", buffer2); EXPECT_EQ(10, entry1->GetDataSize(0)); EXPECT_EQ(2000, entry1->WriteData(0, 0, buffer1, 2000, NULL, false)); EXPECT_EQ(2000, entry1->GetDataSize(0)); EXPECT_EQ(2000, entry1->ReadData(0, 0, buffer2, 2000, NULL)); EXPECT_TRUE(!memcmp(buffer1, buffer2, 2000)); EXPECT_EQ(20000, entry1->WriteData(0, 0, buffer1, sizeof(buffer1), NULL, false)); EXPECT_EQ(20000, entry1->GetDataSize(0)); EXPECT_EQ(20000, entry1->ReadData(0, 0, buffer2, sizeof(buffer2), NULL)); EXPECT_TRUE(!memcmp(buffer1, buffer2, sizeof(buffer1))); entry1->Close(); memset(buffer2, 0, sizeof(buffer2)); ASSERT_TRUE(cache_->CreateEntry("Second key", &entry2)); EXPECT_EQ(10, entry2->WriteData(0, 0, buffer1, 10, NULL, false)); EXPECT_EQ(10, entry2->GetDataSize(0)); entry2->Close(); // Go from an internal address to a bigger block size. ASSERT_TRUE(cache_->OpenEntry("Second key", &entry2)); EXPECT_EQ(2000, entry2->WriteData(0, 0, buffer1, 2000, NULL, false)); EXPECT_EQ(2000, entry2->GetDataSize(0)); EXPECT_EQ(2000, entry2->ReadData(0, 0, buffer2, 2000, NULL)); EXPECT_TRUE(!memcmp(buffer1, buffer2, 2000)); entry2->Close(); memset(buffer2, 0, sizeof(buffer2)); // Go from an internal address to an external one. ASSERT_TRUE(cache_->OpenEntry("Second key", &entry2)); EXPECT_EQ(20000, entry2->WriteData(0, 0, buffer1, sizeof(buffer1), NULL, false)); EXPECT_EQ(20000, entry2->GetDataSize(0)); EXPECT_EQ(20000, entry2->ReadData(0, 0, buffer2, sizeof(buffer2), NULL)); EXPECT_TRUE(!memcmp(buffer1, buffer2, sizeof(buffer1))); entry2->Close(); } TEST_F(DiskCacheEntryTest, GrowData) { InitCache(); GrowData(); } TEST_F(DiskCacheEntryTest, MemoryOnlyGrowData) { SetMemoryOnlyMode(); InitCache(); GrowData(); } void DiskCacheEntryTest::TruncateData() { std::string key1("the first key"); disk_cache::Entry *entry1; ASSERT_TRUE(cache_->CreateEntry(key1, &entry1)); char buffer1[20000]; char buffer2[20000]; CacheTestFillBuffer(buffer1, sizeof(buffer1), false); memset(buffer2, 0, sizeof(buffer2)); // Simple truncation: EXPECT_EQ(200, entry1->WriteData(0, 0, buffer1, 200, NULL, false)); EXPECT_EQ(200, entry1->GetDataSize(0)); EXPECT_EQ(100, entry1->WriteData(0, 0, buffer1, 100, NULL, false)); EXPECT_EQ(200, entry1->GetDataSize(0)); EXPECT_EQ(100, entry1->WriteData(0, 0, buffer1, 100, NULL, true)); EXPECT_EQ(100, entry1->GetDataSize(0)); EXPECT_EQ(0, entry1->WriteData(0, 50, buffer1, 0, NULL, true)); EXPECT_EQ(50, entry1->GetDataSize(0)); EXPECT_EQ(0, entry1->WriteData(0, 0, buffer1, 0, NULL, true)); EXPECT_EQ(0, entry1->GetDataSize(0)); entry1->Close(); ASSERT_TRUE(cache_->OpenEntry(key1, &entry1)); // Go to an external file. EXPECT_EQ(20000, entry1->WriteData(0, 0, buffer1, 20000, NULL, true)); EXPECT_EQ(20000, entry1->GetDataSize(0)); EXPECT_EQ(20000, entry1->ReadData(0, 0, buffer2, 20000, NULL)); EXPECT_TRUE(!memcmp(buffer1, buffer2, 20000)); memset(buffer2, 0, sizeof(buffer2)); // External file truncation EXPECT_EQ(18000, entry1->WriteData(0, 0, buffer1, 18000, NULL, false)); EXPECT_EQ(20000, entry1->GetDataSize(0)); EXPECT_EQ(18000, entry1->WriteData(0, 0, buffer1, 18000, NULL, true)); EXPECT_EQ(18000, entry1->GetDataSize(0)); EXPECT_EQ(0, entry1->WriteData(0, 17500, buffer1, 0, NULL, true)); EXPECT_EQ(17500, entry1->GetDataSize(0)); // And back to an internal block. EXPECT_EQ(600, entry1->WriteData(0, 1000, buffer1, 600, NULL, true)); EXPECT_EQ(1600, entry1->GetDataSize(0)); EXPECT_EQ(600, entry1->ReadData(0, 1000, buffer2, 600, NULL)); EXPECT_TRUE(!memcmp(buffer1, buffer2, 600)); EXPECT_EQ(1000, entry1->ReadData(0, 0, buffer2, 1000, NULL)); EXPECT_TRUE(!memcmp(buffer1, buffer2, 1000)) << "Preserves previous data"; // Go from external file to zero length. EXPECT_EQ(20000, entry1->WriteData(0, 0, buffer1, 20000, NULL, true)); EXPECT_EQ(20000, entry1->GetDataSize(0)); EXPECT_EQ(0, entry1->WriteData(0, 0, buffer1, 0, NULL, true)); EXPECT_EQ(0, entry1->GetDataSize(0)); entry1->Close(); } TEST_F(DiskCacheEntryTest, TruncateData) { InitCache(); TruncateData(); // We generate asynchronous IO that is not really tracked until completion // so we just wait here before running the next test. MessageLoopHelper helper; helper.WaitUntilCacheIoFinished(1); } TEST_F(DiskCacheEntryTest, MemoryOnlyTruncateData) { SetMemoryOnlyMode(); InitCache(); TruncateData(); } // Write more than the total cache capacity but to a single entry. |size| is the // amount of bytes to write each time. void DiskCacheEntryTest::ReuseEntry(int size) { std::string key1("the first key"); disk_cache::Entry *entry; ASSERT_TRUE(cache_->CreateEntry(key1, &entry)); entry->Close(); std::string key2("the second key"); ASSERT_TRUE(cache_->CreateEntry(key2, &entry)); scoped_array buffer(new char[size]); CacheTestFillBuffer(buffer.get(), size, false); for (int i = 0; i < 15; i++) { EXPECT_EQ(0, entry->WriteData(0, 0, buffer.get(), 0, NULL, true)); EXPECT_EQ(size, entry->WriteData(0, 0, buffer.get(), size, NULL, false)); entry->Close(); ASSERT_TRUE(cache_->OpenEntry(key2, &entry)); } entry->Close(); ASSERT_TRUE(cache_->OpenEntry(key1, &entry)) << "have not evicted this entry"; entry->Close(); } TEST_F(DiskCacheEntryTest, ReuseExternalEntry) { SetDirectMode(); SetMaxSize(200 * 1024); InitCache(); ReuseEntry(20 * 1024); } TEST_F(DiskCacheEntryTest, MemoryOnlyReuseExternalEntry) { SetDirectMode(); SetMemoryOnlyMode(); SetMaxSize(200 * 1024); InitCache(); ReuseEntry(20 * 1024); } TEST_F(DiskCacheEntryTest, ReuseInternalEntry) { SetDirectMode(); SetMaxSize(100 * 1024); InitCache(); ReuseEntry(10 * 1024); } TEST_F(DiskCacheEntryTest, MemoryOnlyReuseInternalEntry) { SetDirectMode(); SetMemoryOnlyMode(); SetMaxSize(100 * 1024); InitCache(); ReuseEntry(10 * 1024); } // Reading somewhere that was not written should return zeros. void DiskCacheEntryTest::InvalidData() { std::string key1("the first key"); disk_cache::Entry *entry1; ASSERT_TRUE(cache_->CreateEntry(key1, &entry1)); char buffer1[20000]; char buffer2[20000]; char buffer3[20000]; CacheTestFillBuffer(buffer1, sizeof(buffer1), false); memset(buffer2, 0, sizeof(buffer2)); // Simple data grow: EXPECT_EQ(200, entry1->WriteData(0, 400, buffer1, 200, NULL, false)); EXPECT_EQ(600, entry1->GetDataSize(0)); EXPECT_EQ(100, entry1->ReadData(0, 300, buffer3, 100, NULL)); EXPECT_TRUE(!memcmp(buffer3, buffer2, 100)); entry1->Close(); ASSERT_TRUE(cache_->OpenEntry(key1, &entry1)); // The entry is now on disk. Load it and extend it. EXPECT_EQ(200, entry1->WriteData(0, 800, buffer1, 200, NULL, false)); EXPECT_EQ(1000, entry1->GetDataSize(0)); EXPECT_EQ(100, entry1->ReadData(0, 700, buffer3, 100, NULL)); EXPECT_TRUE(!memcmp(buffer3, buffer2, 100)); entry1->Close(); ASSERT_TRUE(cache_->OpenEntry(key1, &entry1)); // This time using truncate. EXPECT_EQ(200, entry1->WriteData(0, 1800, buffer1, 200, NULL, true)); EXPECT_EQ(2000, entry1->GetDataSize(0)); EXPECT_EQ(100, entry1->ReadData(0, 1500, buffer3, 100, NULL)); EXPECT_TRUE(!memcmp(buffer3, buffer2, 100)); // Go to an external file. EXPECT_EQ(200, entry1->WriteData(0, 19800, buffer1, 200, NULL, false)); EXPECT_EQ(20000, entry1->GetDataSize(0)); EXPECT_EQ(4000, entry1->ReadData(0, 14000, buffer3, 4000, NULL)); EXPECT_TRUE(!memcmp(buffer3, buffer2, 4000)); // And back to an internal block. EXPECT_EQ(600, entry1->WriteData(0, 1000, buffer1, 600, NULL, true)); EXPECT_EQ(1600, entry1->GetDataSize(0)); EXPECT_EQ(600, entry1->ReadData(0, 1000, buffer3, 600, NULL)); EXPECT_TRUE(!memcmp(buffer3, buffer1, 600)); // Extend it again. EXPECT_EQ(600, entry1->WriteData(0, 2000, buffer1, 600, NULL, false)); EXPECT_EQ(2600, entry1->GetDataSize(0)); EXPECT_EQ(200, entry1->ReadData(0, 1800, buffer3, 200, NULL)); EXPECT_TRUE(!memcmp(buffer3, buffer2, 200)); // And again (with truncation flag). EXPECT_EQ(600, entry1->WriteData(0, 3000, buffer1, 600, NULL, true)); EXPECT_EQ(3600, entry1->GetDataSize(0)); EXPECT_EQ(200, entry1->ReadData(0, 2800, buffer3, 200, NULL)); EXPECT_TRUE(!memcmp(buffer3, buffer2, 200)); entry1->Close(); } TEST_F(DiskCacheEntryTest, InvalidData) { InitCache(); InvalidData(); } TEST_F(DiskCacheEntryTest, MemoryOnlyInvalidData) { SetMemoryOnlyMode(); InitCache(); InvalidData(); } void DiskCacheEntryTest::DoomEntry() { std::string key1("the first key"); disk_cache::Entry *entry1; ASSERT_TRUE(cache_->CreateEntry(key1, &entry1)); entry1->Doom(); entry1->Close(); char key_buffer[20000]; CacheTestFillBuffer(key_buffer, sizeof(key_buffer), true); key_buffer[19999] = '\0'; key1 = key_buffer; ASSERT_TRUE(cache_->CreateEntry(key1, &entry1)); EXPECT_EQ(20000, entry1->WriteData(0, 0, key_buffer, 20000, NULL, false)); EXPECT_EQ(20000, entry1->WriteData(1, 0, key_buffer, 20000, NULL, false)); entry1->Doom(); entry1->Close(); EXPECT_EQ(0, cache_->GetEntryCount()); } TEST_F(DiskCacheEntryTest, DoomEntry) { InitCache(); DoomEntry(); } TEST_F(DiskCacheEntryTest, MemoryOnlyDoomEntry) { SetMemoryOnlyMode(); InitCache(); DoomEntry(); } // Verify that basic operations work as expected with doomed entries. void DiskCacheEntryTest::DoomedEntry() { std::string key("the first key"); disk_cache::Entry *entry; ASSERT_TRUE(cache_->CreateEntry(key, &entry)); entry->Doom(); EXPECT_EQ(0, cache_->GetEntryCount()); Time initial = Time::Now(); PlatformThread::Sleep(20); char buffer1[2000]; char buffer2[2000]; CacheTestFillBuffer(buffer1, sizeof(buffer1), false); memset(buffer2, 0, sizeof(buffer2)); EXPECT_EQ(2000, entry->WriteData(0, 0, buffer1, 2000, NULL, false)); EXPECT_EQ(2000, entry->ReadData(0, 0, buffer2, 2000, NULL)); EXPECT_EQ(0, memcmp(buffer1, buffer2, sizeof(buffer1))); EXPECT_TRUE(initial < entry->GetLastModified()); EXPECT_TRUE(initial < entry->GetLastUsed()); entry->Close(); } TEST_F(DiskCacheEntryTest, DoomedEntry) { InitCache(); DoomEntry(); } TEST_F(DiskCacheEntryTest, MemoryOnlyDoomedEntry) { SetMemoryOnlyMode(); InitCache(); DoomEntry(); } LimitlessWill/SoloLearn #include using namespace std; int main() { int yards; cin >> yards; if(yards > 10) cout<< "High Five"; else if(yards < 1) cout<< "shh"; else { for(int x=0;x10-100 // license:BSD-3-Clause // copyright-holders: /********************************************************************** RCA CDP1861 Video Display Controller emulation Timing: The 1861 interrupts the CPU to signal that DMA will be starting in exactly 29 cycles. The CPU must set R0 as the pointer to the first of 8 sequential bytes to be transferred. After the DMA, exactly 6 cycles will elapse before the next DMA. This process continues until the 1861 is within 4 lines of the end of the visible area, when it will assert EFx. When the CPU sees this, it can finish up the interrupt routine. The 1861 will clear EFx at the last visible line. The original IRQ request is cleared 28 cycles after it was asserted. EFx is also asserted 4 lines before the first visible scanline and ends 4 lines later, but this is usually ignored. Timing as it applies to the Studio II: - The usage of EFx before the visible area is not used. - R1 is preset with the value 001C, the interrupt vector. - When the interrupt from the 1861 occurs, R1 becomes the P register, so causing a jump to 001C. - This is followed by 13 2-cycle instructions and one 3-cycle instruction, giving us the required 29 cycles. - The first DMA therefore will occur just after the PLO at 002D. - This is followed by 3 2-cycle instructions, giving the required 6 cycles. - The 1861 will draw 128 scanlines, but due to memory constraints, the Studio II can only do 32 lines, and so each group of 4 scanlines is DMA'd from the same part of memory. - Each DMA will automatically add 8 to R0, and so this needs to be reset for each of the 4 lines. After this, the new R0 value can be used for the next group of 4 scanlines. - After the 4 scanlines are done, EF1 is checked to see if the bottom of the display is being reached. If not, more lines can be processed. - At the end, the random number seed (not part of video drawing) gets updated and the interrupt routine ends. **********************************************************************/ #include "emu.h" #include "cdp1861.h" #include "screen.h" //************************************************************************** // MACROS / CONSTANTS //************************************************************************** #define CDP1861_CYCLES_DMA_START (2*8) #define CDP1861_CYCLES_DMA_ACTIVE (8*8) #define CDP1861_CYCLES_DMA_WAIT (6*8) //************************************************************************** // DEVICE DEFINITIONS //************************************************************************** // device type definition DEFINE_DEVICE_TYPE(CDP1861, cdp1861_device, "cdp1861", "RCA CDP1861") //************************************************************************** // LIVE DEVICE //************************************************************************** //------------------------------------------------- // cdp1861_device - constructor //------------------------------------------------- cdp1861_device::cdp1861_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock) : device_t(mconfig, CDP1861, tag, owner, clock) , device_video_interface(mconfig, *this) , m_write_int(*this) , m_write_dma_out(*this) , m_write_efx(*this) , m_disp(0) , m_dispon(0), m_dispoff(0) , m_dmaout(CLEAR_LINE) , m_int_timer(nullptr), m_efx_timer(nullptr), m_dma_timer(nullptr) { } //------------------------------------------------- // device_config_complete - perform any // operations now that the configuration is // complete //------------------------------------------------- void cdp1861_device::device_config_complete() { if (!has_screen()) return; if (!screen().refresh_attoseconds()) screen().set_raw(clock(), SCREEN_WIDTH, HBLANK_END, HBLANK_START, TOTAL_SCANLINES, SCANLINE_VBLANK_END, SCANLINE_VBLANK_START); if (!screen().has_screen_update()) screen().set_screen_update(*this, FUNC(cdp1861_device::screen_update)); } //------------------------------------------------- // device_start - device-specific startup //------------------------------------------------- void cdp1861_device::device_start() { // resolve callbacks m_write_int.resolve_safe(); m_write_dma_out.resolve_safe(); m_write_efx.resolve_safe(); // allocate timers m_int_timer = timer_alloc(TIMER_INT); m_efx_timer = timer_alloc(TIMER_EFX); m_dma_timer = timer_alloc(TIMER_DMA); // find devices screen().register_screen_bitmap(m_bitmap); // register for state saving save_item(NAME(m_disp)); save_item(NAME(m_dispon)); save_item(NAME(m_dispoff)); save_item(NAME(m_dmaout)); } //------------------------------------------------- // device_reset - device-specific reset //------------------------------------------------- void cdp1861_device::device_reset() { m_int_timer->adjust(screen().time_until_pos(SCANLINE_INT_START, 0)); m_efx_timer->adjust(screen().time_until_pos(SCANLINE_EFX_TOP_START, 0)); m_dma_timer->adjust(clocks_to_attotime(CDP1861_CYCLES_DMA_START)); m_disp = 0; m_dmaout = 0; m_dispon = 0; m_write_int(CLEAR_LINE); m_write_dma_out(CLEAR_LINE); m_write_efx(CLEAR_LINE); } //------------------------------------------------- // device_timer - handle timer events //------------------------------------------------- void cdp1861_device::device_timer(emu_timer &timer, device_timer_id id, int param, void *ptr) { int scanline = screen().vpos(); switch (id) { case TIMER_INT: if (scanline == SCANLINE_INT_START) { if (m_disp) { m_write_int(ASSERT_LINE); } m_int_timer->adjust(screen().time_until_pos( SCANLINE_INT_END, 0)); } else { if (m_disp) { m_write_int(CLEAR_LINE); } m_int_timer->adjust(screen().time_until_pos(SCANLINE_INT_START, 0)); } break; case TIMER_EFX: switch (scanline) { case SCANLINE_EFX_TOP_START: m_write_efx(ASSERT_LINE); m_efx_timer->adjust(screen().time_until_pos(SCANLINE_EFX_TOP_END, 0)); break; case SCANLINE_EFX_TOP_END: m_write_efx(CLEAR_LINE); m_efx_timer->adjust(screen().time_until_pos(SCANLINE_EFX_BOTTOM_START, 0)); break; case SCANLINE_EFX_BOTTOM_START: m_write_efx(ASSERT_LINE); m_efx_timer->adjust(screen().time_until_pos(SCANLINE_EFX_BOTTOM_END, 0)); break; case SCANLINE_EFX_BOTTOM_END: m_write_efx(CLEAR_LINE); m_efx_timer->adjust(screen().time_until_pos(SCANLINE_EFX_TOP_START, 0)); break; } break; case TIMER_DMA: if (m_dmaout) { if (m_disp) { if (scanline >= SCANLINE_DISPLAY_START && scanline < SCANLINE_DISPLAY_END) { m_write_dma_out(CLEAR_LINE); } } m_dma_timer->adjust(clocks_to_attotime(CDP1861_CYCLES_DMA_WAIT)); m_dmaout = CLEAR_LINE; } else { if (m_disp) { if (scanline >= SCANLINE_DISPLAY_START && scanline < SCANLINE_DISPLAY_END) { m_write_dma_out(ASSERT_LINE); } } m_dma_timer->adjust(clocks_to_attotime(CDP1861_CYCLES_DMA_ACTIVE)); m_dmaout = ASSERT_LINE; } break; } } //------------------------------------------------- // dma_w - //------------------------------------------------- void cdp1861_device::dma_w(uint8_t data) { int sx = screen().hpos() + 4; int y = screen().vpos(); for (int x = 0; x < 8; x++) { pen_t color = BIT(data, 7) ? rgb_t::white() : rgb_t::black(); m_bitmap.pix(y, sx + x) = color; data <<= 1; } } //------------------------------------------------- // disp_on_w - //------------------------------------------------- void cdp1861_device::disp_on_w(int state) { if (!m_dispon && state) m_disp = 1; m_dispon = state; } //------------------------------------------------- // disp_off_w - //------------------------------------------------- void cdp1861_device::disp_off_w(int state) { if (!m_dispon && !m_dispoff && state) m_disp = 0; m_dispoff = state; m_write_int(CLEAR_LINE); m_write_dma_out(CLEAR_LINE); } //------------------------------------------------- // screen_update - //------------------------------------------------- uint32_t cdp1861_device::screen_update(screen_device &screen, bitmap_rgb32 &bitmap, const rectangle &cliprect) { if (m_disp) { copybitmap(bitmap, m_bitmap, 0, 0, 0, 0, cliprect); } else { bitmap.fill(rgb_t::black(), cliprect); } return 0; } ch10/ex10-22.cc /* * Exercise 10.22: Rewrite the program to count words of size 6 or less * using functions in place of the lambdas. */ #include #include #include #include #include bool is_less_than_6(const std::string& s, std::string::size_type sz) { return s.size() <= sz; } int main() { std::vector words{"library", "define", "name", "like", "if"}; std::cout << std::count_if(words.begin(), words.end(), std::bind(is_less_than_6, std::placeholders::_1, 6)) << std::endl; return 0; } #ifndef VECTORANDCIRCULARMATH_HPP_ #define VECTORANDCIRCULARMATH_HPP_ #include #include #include #include #include #include #include #include #include inline bool operator==(const cv::Vec4i& lhs, const cv::Vec4i& rhs) { return ((lhs[0] == rhs[0]) && (lhs[1] == rhs[1]) && (lhs[2] == rhs[2]) && (lhs[3] == rhs[3])); }; inline bool operator<(const cv::Vec4i& lhs, const cv::Vec4i& rhs) { if (lhs[0] < rhs[0]) return true; else if (lhs[0] > rhs[0]) return false; if (lhs[1] < rhs[1]) return true; else if (lhs[1] > rhs[1]) return false; if (lhs[2] < rhs[2]) return true; else if (lhs[2] > rhs[2]) return false; if (lhs[3] < rhs[3]) return true; return false; }; inline bool lessThanVec4i(const cv::Vec4i& lhs, const cv::Vec4i& rhs) { return (lhs < rhs); }; inline bool lessThanArray5i(const std::array& lhs, const std::array& rhs) { return (lhs < rhs); }; namespace vc_math { #if BOOST_VERSION/100 < 1050 constexpr double pi = 3.1415926535897932384626433832795; constexpr double two_pi = pi*2; constexpr double inv_sqrt_2pi = 0.3989422804014327; constexpr double degree = pi/180.0; constexpr double radian = 180.0/pi; constexpr double half_pi = pi/2.0; #else constexpr double pi = boost::math::constants::pi(); constexpr double two_pi = boost::math::constants::two_pi(); constexpr double inv_sqrt_2pi = 1.0/boost::math::constants::root_two_pi(); constexpr double degree = boost::math::constants::degree(); constexpr double radian = boost::math::constants::radian(); constexpr double half_pi = boost::math::constants::half_pi(); #endif constexpr double INVALID_ANGLE = 361.0; inline double normal_pdf(double x, double m, double s) { double a = (x - m) / s; return (inv_sqrt_2pi / s) * exp(-0.5 * a * a); }; inline double log_normal_pdf(double x, double m, double s) { double a = (x - m) / s; return log(inv_sqrt_2pi) - log(s) -0.5 * a * a; }; /** * Generates a pair of random samples from the unit Normal distribution, * using the Box-Mueller method. */ inline std::pair randn() { double U = double(rand())/RAND_MAX; double V = double(rand())/RAND_MAX; double sqrtMinusTwolnU = sqrt(-2*log(U)); double TwoPiV = two_pi * V; return std::pair(sqrtMinusTwolnU * cos(TwoPiV), sqrtMinusTwolnU * sin(TwoPiV)); }; /** * Computes angular (and general modulo-'range') magnitude, signed */ inline double angularMag( double a, double b, double range = 360.0) { double d = b - a + range/2; d = (d > 0) ? d - floor(d/range)*range - range/2 : d - (floor(d/range) + 1)*range + range/2; return d; }; /** * Computes angular (and general modulo-'range') distance */ inline double angularDist(double a, double b, double range = 360.0) { return fabs(angularMag(a, b, range)); }; /** * Computes Eulidean distance between 2 2-D points */ inline double dist(double x1, double y1, double x2, double y2) { return sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2)); }; inline double dist(const cv::Point2d& xy1, const cv::Point2d& xy2) { return sqrt((xy1.x-xy2.x)*(xy1.x-xy2.x)+(xy1.y-xy2.y)*(xy1.y-xy2.y)); }; inline double dist(const cv::Point2f& xy1, const cv::Point2f& xy2) { return sqrt((xy1.x-xy2.x)*(xy1.x-xy2.x)+(xy1.y-xy2.y)*(xy1.y-xy2.y)); }; inline double dist(const cv::Point2i& xy1, const cv::Point2i& xy2) { return sqrt((xy1.x-xy2.x)*(xy1.x-xy2.x)+(xy1.y-xy2.y)*(xy1.y-xy2.y)); }; inline double dist(const cv::Vec4i& xy12) { return sqrt((xy12[0]-xy12[2])*(xy12[0]-xy12[2])+(xy12[1]-xy12[3])*(xy12[1]-xy12[3])); }; inline double distSqrd(double x1, double y1, double x2, double y2) { return (x1-x2)*(x1-x2)+(y1-y2)*(y1-y2); }; inline double distSqrd(const cv::Point2d& xy1, const cv::Point2d& xy2) { return (xy1.x-xy2.x)*(xy1.x-xy2.x)+(xy1.y-xy2.y)*(xy1.y-xy2.y); }; inline double distSqrd(const cv::Point2f& xy1, const cv::Point2f& xy2) { return (xy1.x-xy2.x)*(xy1.x-xy2.x)+(xy1.y-xy2.y)*(xy1.y-xy2.y); }; inline double distSqrd(const cv::Point2i& xy1, const cv::Point2i& xy2) { return (xy1.x-xy2.x)*(xy1.x-xy2.x)+(xy1.y-xy2.y)*(xy1.y-xy2.y); }; inline double distSqrd(const cv::Vec4i& xy12) { return (xy12[0]-xy12[2])*(xy12[0]-xy12[2])+(xy12[1]-xy12[3])*(xy12[1]-xy12[3]); }; /** * Wraps angle in degrees to [0, maxAngle) range */ inline constexpr double wrapAngle(double angleDeg, double maxAngle = 360.0) { return (angleDeg - floor(angleDeg/maxAngle)*maxAngle); }; /** * Count number of entries in matrix that are not equal * * NOTE: if Mat represents a colored image, then it will count different * color channels separately. */ inline unsigned long long countNotEqual(const cv::Mat& a, const cv::Mat& b) { if (a.size != b.size || a.channels() != b.channels()) { return std::max(a.rows * a.cols * a.channels(), b.rows * b.cols * b.channels()); } cv::Mat not_equal; cv::compare(a, b, not_equal, cv::CMP_NE); cv::Scalar sum_not_equal = sum(sum(not_equal) / 255); return sum_not_equal[0] + sum_not_equal[1] + sum_not_equal[2] + sum_not_equal[3]; }; inline unsigned long long countNotEqual(const std::vector& a, const std::vector& b) { unsigned long long count = abs(a.size() - b.size()); size_t minSize = std::min(a.size(), b.size()); std::vector::const_iterator itA = a.begin(); std::vector::const_iterator itB = b.begin(); for (unsigned int i = 0; i < minSize; i++, itA++, itB++) { if (*itA != *itB) { count += 1; } } return count; }; /** * Computes the Euclidean distance between a 2-D point and a 2-D line */ inline double distPointLine( const cv::Point& point, const cv::Vec4f& currFit) { // http://local.wasp.uwa.edu.au/~pbourke/geometry/pointline/ double vx = currFit[0], vy = currFit[1], x1 = currFit[2], y1 = currFit[3]; if (vx == 0 && vy == 0) { return 0; // P1 = P2! } double x3 = point.x, y3 = point.y; double u = ((x3-x1)*vx + (y3-y1)*vy)/(vx*vx+vy*vy); double dx = x1 + u*vx - x3, dy = y1 + u*vy - y3; return sqrt(dx*dx + dy*dy); }; /** * Finds closest point to given line in given set of points. */ inline cv::Point findClosestPointToLine( const std::vector& points, const cv::Vec4f& line) { // Identify the 8-connected set of edgels closest to the previous line fit std::vector::const_iterator itPoints = points.begin(); std::vector::const_iterator itPointsEnd = points.end(); double closestDist = distPointLine(*itPoints, line); cv::Point closestPoint = *itPoints; double currDist; for (itPoints++; itPoints != itPointsEnd; itPoints++) { currDist = distPointLine(*itPoints, line); if (currDist < closestDist) { closestDist = currDist; closestPoint = *itPoints; } } return closestPoint; }; /** * Computes 3D point on plane closest to specified 3D point * * Justification: * The equation of a plane is: n * v = d, where n is the normal vector, * v is an arbitrary 3D point, and d is a constant offset. * * Given query point v', then the closest point on the above plane is: * v* = v' + a * n, for some unknown factor a * * Also, we know that n * v* = d, by definition of the plane. * * Thus, n * (v' + a * n) = d, * i.e. a = ( d - n * v' ) / ( n * n ), * which allows us to then solve for v* by substituting in a * * (side-note: n * n is guaranteed to be always non-zero for plane to exist) */ inline cv::Vec3d findClosestPointOnPlane(const cv::Vec3d& vp, const cv::Vec3d& n, double d) { double a = (d - n.dot(vp)) / n.dot(n); cv::Vec3d vs = vp + a*n; return vs; }; /** * Computes 2D point on line closest to specified 2D point * * Justification: * The equation of a line is: vla + a * vd, * where vd = vlb - vla, for some constant a * * Let vdd be orthogonal to vd. The resulting point vr satisfied both: * vr = vla + a * vd, for some constant a * vr = vp - d * vdd, for some constant d * * Hence, vd * a + vdd * b = vp - vla. We can now solve a and d using the normal equation. */ inline cv::Vec2d findClosestPointOnLine2(const cv::Vec2d& vp, const cv::Vec2d& vla, const cv::Vec2d& vlb) { if (vla == vlb) { return vp; } cv::Vec2d vd = vlb - vla; double det = vd[0]*vd[0] + vd[1]*vd[1]; double a = (vd[0] * (vp[0] - vla[0]) + vd[1] * (vp[1] - vla[1])) / det; //double d = (vd[1] * (vp[0] - vla[0]) - vd[0] * (vp[1] - vla[1])) / det; cv::Vec2d result = vla + a * vd; return result; }; /** * same as above, but takes in normal form of line: (n1, n2) * (x, y) = nd */ inline cv::Vec2d findClosestPointOnLine2(const cv::Vec2d& vp, double n1, double n2, double nd) { // Make sure normal vector of line has non-zero norm double det = n1*n1 + n2*n2; if (det == 0) { return vp; } // Compute point on line double vlx = 0, vly = 0; if (n1 == 0) { vly = nd/n2; } else { vlx = nd/n1; } // Compute vr = vl + a * vd, where vd is orthogonal to n double a = (n2 * (vp[0] - vlx) - n1 * (vp[1] - vly)) / det; return cv::Vec2d(vlx + a*n2, vly - a*n1); }; /** * Computes 3D point on line closest to specified 3D point * * Justification: * The equation of a line is: vla + a * vld, * where vld = vlb - vla, for some constant a * * Denote the resulting point on the line as vr, then the vector vn = (vr->vp) is * orthogonal to vld, as well as to a 3rd orthogonal vector vo. * vo can be computed as vld x vnp, where vnp = (vl->vp) for any point vl on the line. * * Then, we can link the 2 points vla and vp together, as: * vnp = vp - vla = a * vld + d * vn * * There are 2 unknowns and 3 equations here, so we can solve this using the * normal equation. */ inline cv::Vec3d findClosestPointOnLine3(const cv::Vec3d& vp, const cv::Vec3d& vla, const cv::Vec3d& vlb) { cv::Vec3d result; if (vla == vlb) { return vp; } cv::Vec3d vld = vlb - vla; cv::Vec3d vnp = vp - vla; if (vp == vla) { vnp = vp - vlb; } cv::Vec3d vo = vld.cross(vnp); cv::Vec3d vn = vld.cross(vo); cv::Mat A(3, 2, CV_64FC1); cv::Mat b(3, 1, CV_64FC1); for (unsigned int i = 0; i < 3; i++) { A.at(i, 0) = vld[i]; A.at(i, 1) = vn[i]; b.at(i, 0) = vnp[i]; } cv::Mat sln = (A.t()*A).inv()*(A.t()*b); //double a = sln.at(0, 0); double d = sln.at(1, 0); result = vp - d*vn; return result; }; /** * Find the closest point to a number of planes, where each plane is represented * by their normal vector n, and constant offset d, which are stored into * matrices A = [n1; n2; ...], and b = [d1; d2; ...]. * * The query point vp is only used in degenerate cases; see below. * * For 1 single plane, this function returns the closest point on plane to * the query point vp. * * Otherwise, we check if (A'*A) is invertible, and if it is, then we can use * the normal equation to solve for the closest point. * * If (A'*A) is not invertible, then we choose the first 2 planes that have * different normals, and find their intersecting line. We then compute * the closest point on line to the query point. */ cv::Vec3d findClosestPointToPlanes3(const cv::Vec3d& vp, const cv::Mat& A, const cv::Mat& b); /** * Find the closest point to a number of lines, where each line is represented * by their normal vector n, and constant offset d, which are stored into * matrices A = [n1; n2; ...], and b = [d1; d2; ...]. * * The query point vp is only used in degenerate cases; see below. * * For 1 single line, this function returns the closest point on line to * the query point vp. * * Otherwise, we check if the lines are parallel via det(A) != 0. If they * intersect, then we can use the normal equation to solve for the closest point. * * If all lines are parallel, then we average over the offsets b, to get an * average line. We then return the closest point on this average line to the * query point. */ cv::Vec2d findClosestPointToLines2(const cv::Vec2d& vp, const cv::Mat& A, const cv::Mat& b); /** * Check if the line segments (a<->b) and (c<->d) intersect with each other * * From: http://gamedev.stackexchange.com/questions/26004/how-to-detect-2d-line-on-line-collision * * WARNING: algorithm returns true for special case where the line segments * are co-linear and do not overlap */ inline bool isIntersecting(const cv::Point2f& a, const cv::Point2f& b, const cv::Point2f& c, const cv::Point2f& d) { float denominator = ((b.x - a.x) * (d.y - c.y)) - ((b.y - a.y) * (d.x - c.x)); float numerator1 = ((a.y - c.y) * (d.x - c.x)) - ((a.x - c.x) * (d.y - c.y)); float numerator2 = ((a.y - c.y) * (b.x - a.x)) - ((a.x - c.x) * (b.y - a.y)); if (denominator == 0) return numerator1 == 0 && numerator2 == 0; float r = numerator1 / denominator; float s = numerator2 / denominator; return (r >= 0 && r <= 1) && (s >= 0 && s <= 1); }; /** * Computes x intercept (in pixels, intersection with bottom of image) and * slope (in degrees, 0' = top of image) given line in image * * \param line: straight line; format: [dx, dy, x0, y0] * \param imWidth: image width, in pixels * \param imHeight: image height, in pixels */ std::pair computeXInterceptAndSlopeFromLine( cv::Vec4f line, unsigned int imWidth, unsigned int imHeight); /** * Computes heading angle (in degrees) given line in overhead image, and * given preferred heading directionality. * * \param line: straight line; format: [dx, dy, x0, y0] * \param imWidth: image width, in pixels * \param imHeight: image height, in pixels * \param preferredDirDeg: preferred direction of heading, in degrees (0 = top of image, 90 = right of image) */ double computeHeadingFromOverheadLine( cv::Vec4f line, unsigned int imWidth, unsigned int imHeight, double preferredDirDeg); /** * Computes point closest to border in the direction of heading, * centered at image's center. * * \param heading: desired heading, in degrees; 0 = North/top of image; 90 = East/right of image * \param imWidth: image width * \param imHeight: image height * \param marginWidth: width of margin around image borders to avoid when computing intersection */ cv::Point computeHeadingBorderIntersection( double heading, unsigned int imWidth, unsigned int imHeight, unsigned int marginWidth); /** * Computes and returns closest point within set of points */ inline cv::Point findClosestPoint( const std::vector& points, const cv::Point targetPoint) { std::vector::const_iterator itPoints = points.begin(); std::vector::const_iterator itPointsEnd = points.end(); cv::Point result = *itPoints; double bestDistSqrd = (itPoints->x - targetPoint.x)*(itPoints->x - targetPoint.x) + (itPoints->y - targetPoint.y)*(itPoints->y - targetPoint.y); double currDistSqrd; for (itPoints++; itPoints != itPointsEnd; itPoints++) { currDistSqrd = (itPoints->x - targetPoint.x)*(itPoints->x - targetPoint.x) + (itPoints->y - targetPoint.y)*(itPoints->y - targetPoint.y); if (currDistSqrd < bestDistSqrd) { result = *itPoints; bestDistSqrd = currDistSqrd; } } return result; }; /** * Computes (minimum) scale factor between 2 sizes (i.e. prefer letterbox over * cropping) */ inline double computeScaleFactor(const cv::Size& from, const cv::Size& to) { if (from == cv::Size() || to == cv::Size()) { return 1.0; } else { return std::min(double(to.width) / double(from.width), double(to.height) / double(from.height)); } }; /** * Computes orientation of line segment (of the form [x1, y1, x2, y2]), in * radians. */ inline double orientation(const cv::Vec4i& seg) { return std::atan2(seg[3] - seg[1], seg[2] - seg[0]); }; inline double orientation(const cv::Point2i& ptA, const cv::Point2i& ptB) { return std::atan2(ptB.y - ptA.y, ptB.x - ptA.x); }; inline double orientation(const cv::Point2d& ptA, const cv::Point2d& ptB) { return std::atan2(ptB.y - ptA.y, ptB.x - ptA.x); }; /** * Sort values in increasing order * NOTE: faster than recursive implementations and specifically * cv::sort(vec4iA, vec4iB, CV_SORT_EVERY_COLUMN | CV_SORT_ASCENDING) */ inline cv::Vec4i sort(cv::Vec4i v) { cv::Vec4i s(v); if (v[0] > v[1]) { s[0] = v[1]; s[1] = v[0]; } if (v[2] > v[3]) { s[2] = v[3]; s[3] = v[2]; } if (s[0] > s[2]) { v[0] = s[2]; if (s[3] > s[1]) { v[1] = s[0]; v[2] = s[1]; v[3] = s[3]; } else if (s[3] > s[0]) { v[1] = s[0]; v[2] = s[3]; v[3] = s[1]; } else { v[1] = s[3]; v[2] = s[0]; v[3] = s[1]; } } else { v[0] = s[0]; if (s[1] > s[3]) { v[1] = s[2]; v[2] = s[3]; v[3] = s[1]; } else if (s[1] > s[2]) { v[1] = s[2]; v[2] = s[1]; v[3] = s[3]; } else { v[1] = s[1]; v[2] = s[2]; v[3] = s[3]; } } return v; }; /** * Cycles vector such that smallest value is listed first, but the (cyclic) * ordering of values are preserved */ inline cv::Vec4i minCyclicOrder(cv::Vec4i v) { if ((v[0] <= v[1]) && (v[0] <= v[2]) && (v[0] <= v[3])) { return v; } else if ((v[1] <= v[0]) && (v[1] <= v[2]) && (v[1] <= v[3])) { return cv::Vec4i(v[1], v[2], v[3], v[0]); } else if ((v[2] <= v[0]) && (v[2] <= v[1]) && (v[2] <= v[3])) { return cv::Vec4i(v[2], v[3], v[0], v[1]); } else { // if ((v[3] <= v[0]) && (v[3] <= v[1]) && (v[3] <= v[2])) { return cv::Vec4i(v[3], v[0], v[1], v[2]); } }; /** * Sorts and removes duplicate entries in-place */ inline void unique(std::vector& v) { std::sort(v.begin(), v.end(), lessThanVec4i); std::vector u; for (const cv::Vec4i& d: v) { if (u.empty()) { u.push_back(d); } else if (u.back() < d) { u.push_back(d); } } v.swap(u); }; inline void unique(std::vector< std::array >& v) { std::sort(v.begin(), v.end(), lessThanArray5i); std::vector< std::array > u; for (const std::array& d: v) { if (u.empty()) { u.push_back(d); } else if (u.back() < d) { u.push_back(d); } } v.swap(u); }; /** * Returns dot product of 2 line segments (of the form [x1, y1, x2, y2]) */ inline double dot(const cv::Vec4i& A, const cv::Vec4i& B) { return (A[2]-A[0])*(B[2]-B[0]) + (A[3]-A[1])*(B[3]-B[1]); }; /** * Returns dot product of 2 line segments */ inline double dot(const cv::Point2f& endA1, const cv::Point2f& endA2, const cv::Point2f& endB1, const cv::Point2f& endB2) { return (endA2.x-endA1.x)*(endB2.x-endB1.x) + (endA2.y-endA1.y)*(endB2.y-endB1.y); }; /** * Converts a rotation matrix into a quaternion * * From: http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/ */ inline void rotMat2quat(const cv::Mat rotMat, double& w, double& x, double& y, double& z) { assert(rotMat.rows == 3 && rotMat.cols == 3 && rotMat.isContinuous() && rotMat.elemSize() == sizeof(double)); double tr = rotMat.at(0, 0) + rotMat.at(1, 1) + rotMat.at(2, 2); double s; if (tr > 0) { s = 0.5/sqrt(tr + 1.0); w = 0.25/s; x = (rotMat.at(2, 1) - rotMat.at(1, 2))*s; y = (rotMat.at(0, 2) - rotMat.at(2, 0))*s; z = (rotMat.at(1, 0) - rotMat.at(0, 1))*s; } else if (rotMat.at(0, 0) > rotMat.at(1, 1) && rotMat.at(0, 0) > rotMat.at(2, 2)) { s = 2.0*sqrt(1.0 + 2*rotMat.at(0, 0) - tr); w = (rotMat.at(2, 1) - rotMat.at(1, 2))/s; x = 0.25*s; y = (rotMat.at(0, 1) + rotMat.at(1, 0))/s; z = (rotMat.at(0, 2) + rotMat.at(2, 0))/s; } else if (rotMat.at(1, 1) > rotMat.at(2, 2)) { s = 2.0*sqrt(1.0 + 2*rotMat.at(1, 1) - tr); w = (rotMat.at(0, 2) - rotMat.at(2, 0))/s; x = (rotMat.at(0, 1) + rotMat.at(1, 0))/s; y = 0.25*s; z = (rotMat.at(1, 2) + rotMat.at(2, 1))/s; } else { s = 2.0*sqrt(1.0 + 2*rotMat.at(2, 2) - tr); w = (rotMat.at(1, 0) - rotMat.at(0, 1))/s; x = (rotMat.at(0, 2) + rotMat.at(2, 0))/s; y = (rotMat.at(1, 2) + rotMat.at(2, 1))/s; z = 0.25*s; } }; inline cv::Mat quat2RotMat(double w, double x, double y, double z) { double distSqrd = x*x+y*y+z*z+w*w; if (distSqrd < 1e-15) { return cv::Mat::zeros(3, 3, CV_64FC1); } double s = 2.0/distSqrd; double xs = x * s, ys = y * s, zs = z * s; double wx = w * xs, wy = w * ys, wz = w * zs; double xx = x * xs, xy = x * ys, xz = x * zs; double yy = y * ys, yz = y * zs, zz = z * zs; cv::Mat result(3, 3, CV_64FC1); double* data = (double*) result.data; *data = 1.0 - (yy + zz); data++; *data = xy - wz; data++; *data = xz + wy; data++; *data = xy + wz; data++; *data = 1.0 - (xx + zz); data++; *data = yz - wx; data++; *data = xz - wy; data++; *data = yz + wx; data++; *data = 1.0 - (xx + yy); return result; }; /** * Converts a quaternion to Euler angles * Assume right-hand coordinate frame, and static-x-y-z (sxyz) rotation ordering */ inline std::array quat2euler(double w, double x, double y, double z) { double distSqrd = x*x+y*y+z*z+w*w; if (distSqrd < 1e-15) { std::array{ {0, 0, 0} }; } w /= distSqrd; x /= distSqrd; y /= distSqrd; z /= distSqrd; return std::array{ { atan2(2*(x*w + z*y), (w*w - x*x - y*y + z*z)), asin(2*(y*w - x*z)), atan2(2*(x*y + z*w), (w*w + x*x - y*y - z*z))} }; }; inline std::array quat2euler(std::array wxyz) { return quat2euler(wxyz[0], wxyz[1], wxyz[2], wxyz[3]); }; /** * Computes (normalized) inverse of a given quaternion */ inline std::array quatInv(double w, double x, double y, double z) { double distSqrd = x*x+y*y+z*z+w*w; if (distSqrd < 1e-15) { std::array{ {0, 0, 0, 0} }; } return std::array{ {w/distSqrd, -x/distSqrd, -y/distSqrd, -z/distSqrd} }; }; inline cv::Mat str2mat(const std::string& s, int rows, int type = CV_64F, int channels = 1) { std::string input = s; auto it = std::remove_if(std::begin(input), std::end(input), [](char c) { return (c == ',' || c == ';' || c == ':'); }); input.erase(it, std::end(input)); cv::Mat mat(0, 0, type); std::istringstream iss(input); double currNum; while (!iss.eof()) { iss >> currNum; mat.push_back(currNum); } return mat.reshape(channels, rows); }; inline std::vector str2doublesVec(const std::string& doublesStr) { std::list tokens; boost::split(tokens, doublesStr, boost::is_any_of(", "), boost::token_compress_on); std::vector doublesVec; for (const std::string& t: tokens) { doublesVec.push_back(boost::lexical_cast(t)); } return doublesVec; }; /** * Check if 2 (convex) polygons overlap, using the dividing axis algorithm: * - if 2 convex polygons do not intersect, then there exists a line that passes between them * - such a line only exists if formed by one of the polygons' sides * * Note that two polygons sharing an edge, or whose one's endpoint intersects * the other's edge, are considered to be overlapping. */ inline bool checkPolygonOverlap(const std::vector& cornersA, const std::vector& cornersB) { // Compute angles perpendicular to each of the polygons' sides std::vector projectionAngles; unsigned int i, j; cv::Point2f vec; for (i = 0; i < cornersA.size(); i++) { j = (i == 0) ? cornersA.size() - 1 : i - 1; vec = cornersA[i] - cornersA[j]; if (vec.x == 0 && vec.y == 0) continue; projectionAngles.push_back(atan2(vec.x, vec.y)); // NOTE: (x, y) arguments swapped to compute perpendicular angle } for (i = 0; i < cornersB.size(); i++) { j = (i == 0) ? cornersB.size() - 1 : i - 1; vec = cornersB[i] - cornersB[j]; if (vec.x == 0 && vec.y == 0) continue; projectionAngles.push_back(atan2(vec.x, vec.y)); } // Scan for dividing axis line bool overlap = true; for (const double& angle: projectionAngles) { double projAMin = std::numeric_limits::infinity(); double projAMax = -std::numeric_limits::infinity(); double projBMin = std::numeric_limits::infinity(); double projBMax = -std::numeric_limits::infinity(); double cosAngle = cos(angle); double sinAngle = sin(angle); for (const cv::Point2f& pt: cornersA) { double proj = cosAngle * pt.x - sinAngle * pt.y; if (proj < projAMin) projAMin = proj; if (proj > projAMax) projAMax = proj; } for (const cv::Point2f& pt: cornersB) { double proj = cosAngle * pt.x - sinAngle * pt.y; if (proj < projBMin) projBMin = proj; if (proj > projBMax) projBMax = proj; } if ((projAMax < projBMin) || (projAMin > projBMax)) { overlap = false; break; } } return overlap; }; }; #endif /* VECTORANDCIRCULARMATH_HPP_ */ ArcadiusGFN/SourceEngine2007 // OpenArchive.cpp #include "StdAfx.h" // #define SHOW_DEBUG_INFO #ifdef SHOW_DEBUG_INFO #include #endif #include "../../../../C/CpuArch.h" #include "../../../Common/ComTry.h" #include "../../../Common/IntToString.h" #include "../../../Common/StringConvert.h" #include "../../../Common/StringToInt.h" #include "../../../Common/Wildcard.h" #include "../../../Windows/FileDir.h" #include "../../Common/FileStreams.h" #include "../../Common/LimitedStreams.h" #include "../../Common/ProgressUtils.h" #include "../../Common/StreamUtils.h" #include "../../Compress/CopyCoder.h" #include "DefaultName.h" #include "OpenArchive.h" #ifndef _SFX #include "SetProperties.h" #endif #ifdef SHOW_DEBUG_INFO #define PRF(x) x #else #define PRF(x) #endif // increase it, if you need to support larger SFX stubs static const UInt64 kMaxCheckStartPosition = 1 << 23; /* Open: - formatIndex >= 0 (exact Format) 1) Open with main type. Archive handler is allowed to use archive start finder. Warning, if there is tail. - formatIndex = -1 (Parser:0) (default) - same as #1 but doesn't return Parser - formatIndex = -2 (#1) - file has supported extension (like a.7z) Open with that main type (only starting from start of file). - open OK: - if there is no tail - return OK - if there is tail: - archive is not "Self Exe" - return OK with Warning, that there is tail - archive is "Self Exe" ignore "Self Exe" stub, and tries to open tail - tail can be open as archive - shows that archive and stub size property. - tail can't be open as archive - shows Parser ??? - open FAIL: Try to open with all other types from offset 0 only. If some open type is OK and physical archive size is uequal or larger than file size, then return that archive with warning that can not be open as [extension type]. If extension was EXE, it will try to open as unknown_extension case - file has unknown extension (like a.hhh) It tries to open via parser code. - if there is full archive or tail archive and unknown block or "Self Exe" at front, it shows tail archive and stub size property. - in another cases, if there is some archive inside file, it returns parser/ - in another cases, it retuens S_FALSE - formatIndex = -3 (#2) - same as #1, but - stub (EXE) + archive is open in Parser - formatIndex = -4 (#3) - returns only Parser. skip full file archive. And show other sub-archives - formatIndex = -5 (#4) - returns only Parser. skip full file archive. And show other sub-archives for each byte pos */ using namespace NWindows; /* #ifdef _SFX #define OPEN_PROPS_PARAM #else #define OPEN_PROPS_PARAM , props #endif */ /* CArc::~CArc() { GetRawProps.Release(); Archive.Release(); printf("\nCArc::~CArc()\n"); } */ #ifndef _SFX namespace NArchive { namespace NParser { struct CParseItem { UInt64 Offset; UInt64 Size; // UInt64 OkSize; UString Name; UString Extension; FILETIME FileTime; UString Comment; UString ArcType; bool FileTime_Defined; bool UnpackSize_Defined; bool NumSubDirs_Defined; bool NumSubFiles_Defined; bool IsSelfExe; bool IsNotArcType; UInt64 UnpackSize; UInt64 NumSubDirs; UInt64 NumSubFiles; int FormatIndex; bool LenIsUnknown; CParseItem(): LenIsUnknown(false), FileTime_Defined(false), UnpackSize_Defined(false), NumSubFiles_Defined(false), NumSubDirs_Defined(false), IsSelfExe(false), IsNotArcType(false) // OkSize(0) {} /* bool IsEqualTo(const CParseItem &item) const { return Offset == item.Offset && Size == item.Size; } */ void NormalizeOffset() { if ((Int64)Offset < 0) { Size += Offset; // OkSize += Offset; Offset = 0; } } }; class CHandler: public IInArchive, public IInArchiveGetStream, public CMyUnknownImp { public: CObjectVector _items; UInt64 _maxEndOffset; CMyComPtr _stream; MY_UNKNOWN_IMP2( IInArchive, IInArchiveGetStream) INTERFACE_IInArchive(;) STDMETHOD(GetStream)(UInt32 index, ISequentialInStream **stream); UInt64 GetLastEnd() const { if (_items.IsEmpty()) return 0; const CParseItem &back = _items.Back(); return back.Offset + back.Size; } void AddUnknownItem(UInt64 next); int FindInsertPos(const CParseItem &item) const; void AddItem(const CParseItem &item); CHandler(): _maxEndOffset(0) {} }; int CHandler::FindInsertPos(const CParseItem &item) const { unsigned left = 0, right = _items.Size(); while (left != right) { unsigned mid = (left + right) / 2; const CParseItem & midItem = _items[mid]; if (item.Offset < midItem.Offset) right = mid; else if (item.Offset > midItem.Offset) left = mid + 1; else if (item.Size < midItem.Size) right = mid; else if (item.Size > midItem.Size) left = mid + 1; else { left = mid + 1; // return -1; } } return left; } void CHandler::AddUnknownItem(UInt64 next) { /* UInt64 prevEnd = 0; if (!_items.IsEmpty()) { const CParseItem &back = _items.Back(); prevEnd = back.Offset + back.Size; } */ if (_maxEndOffset < next) { CParseItem item2; item2.Offset = _maxEndOffset; item2.Size = next - _maxEndOffset; _maxEndOffset = next; _items.Add(item2); } else if (_maxEndOffset > next && !_items.IsEmpty()) { CParseItem &back = _items.Back(); if (back.LenIsUnknown) { back.Size = next - back.Offset; _maxEndOffset = next; } } } void CHandler::AddItem(const CParseItem &item) { AddUnknownItem(item.Offset); int pos = FindInsertPos(item); if (pos >= 0) { _items.Insert(pos, item); UInt64 next = item.Offset + item.Size; if (_maxEndOffset < next) _maxEndOffset = next; } } /* static const CStatProp kProps[] = { { NULL, kpidPath, VT_BSTR}, { NULL, kpidSize, VT_UI8}, { NULL, kpidMTime, VT_FILETIME}, { NULL, kpidType, VT_BSTR}, { NULL, kpidComment, VT_BSTR}, { NULL, kpidOffset, VT_UI8}, { NULL, kpidUnpackSize, VT_UI8}, // { NULL, kpidNumSubDirs, VT_UI8}, }; */ static const Byte kProps[] = { kpidPath, kpidSize, kpidMTime, kpidType, kpidComment, kpidOffset, kpidUnpackSize }; IMP_IInArchive_Props IMP_IInArchive_ArcProps_NO STDMETHODIMP CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallback * /* openArchiveCallback */) { COM_TRY_BEGIN { Close(); _stream = stream; } return S_OK; COM_TRY_END } STDMETHODIMP CHandler::Close() { _items.Clear(); _stream.Release(); return S_OK; } STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems) { *numItems = _items.Size(); return S_OK; } STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value) { COM_TRY_BEGIN NCOM::CPropVariant prop; const CParseItem &item = _items[index]; switch (propID) { case kpidPath: { char sz[32]; ConvertUInt32ToString(index + 1, sz); UString s(sz); if (!item.Name.IsEmpty()) { s += '.'; s += item.Name; } if (!item.Extension.IsEmpty()) { s += '.'; s += item.Extension; } prop = s; break; } case kpidSize: case kpidPackSize: prop = item.Size; break; case kpidOffset: prop = item.Offset; break; case kpidUnpackSize: if (item.UnpackSize_Defined) prop = item.UnpackSize; break; case kpidNumSubFiles: if (item.NumSubFiles_Defined) prop = item.NumSubFiles; break; case kpidNumSubDirs: if (item.NumSubDirs_Defined) prop = item.NumSubDirs; break; case kpidMTime: if (item.FileTime_Defined) prop = item.FileTime; break; case kpidComment: if (!item.Comment.IsEmpty()) prop = item.Comment; break; case kpidType: if (!item.ArcType.IsEmpty()) prop = item.ArcType; break; } prop.Detach(value); return S_OK; COM_TRY_END } HRESULT CHandler::Extract(const UInt32 *indices, UInt32 numItems, Int32 testMode, IArchiveExtractCallback *extractCallback) { COM_TRY_BEGIN bool allFilesMode = (numItems == (UInt32)(Int32)-1); if (allFilesMode) numItems = _items.Size(); if (_stream && numItems == 0) return S_OK; UInt64 totalSize = 0; UInt32 i; for (i = 0; i < numItems; i++) totalSize += _items[allFilesMode ? i : indices[i]].Size; extractCallback->SetTotal(totalSize); totalSize = 0; CLocalProgress *lps = new CLocalProgress; CMyComPtr progress = lps; lps->Init(extractCallback, false); CLimitedSequentialInStream *streamSpec = new CLimitedSequentialInStream; CMyComPtr inStream(streamSpec); streamSpec->SetStream(_stream); CLimitedSequentialOutStream *outStreamSpec = new CLimitedSequentialOutStream; CMyComPtr outStream(outStreamSpec); NCompress::CCopyCoder *copyCoderSpec = new NCompress::CCopyCoder(); CMyComPtr copyCoder = copyCoderSpec; for (i = 0; i < numItems; i++) { lps->InSize = totalSize; lps->OutSize = totalSize; RINOK(lps->SetCur()); CMyComPtr realOutStream; Int32 askMode = testMode ? NExtract::NAskMode::kTest : NExtract::NAskMode::kExtract; Int32 index = allFilesMode ? i : indices[i]; const CParseItem &item = _items[index]; RINOK(extractCallback->GetStream(index, &realOutStream, askMode)); UInt64 unpackSize = item.Size; totalSize += unpackSize; bool skipMode = false; if (!testMode && !realOutStream) continue; RINOK(extractCallback->PrepareOperation(askMode)); outStreamSpec->SetStream(realOutStream); realOutStream.Release(); outStreamSpec->Init(skipMode ? 0 : unpackSize, true); Int32 opRes = NExtract::NOperationResult::kOK; RINOK(_stream->Seek(item.Offset, STREAM_SEEK_SET, NULL)); streamSpec->Init(unpackSize); RINOK(copyCoder->Code(inStream, outStream, NULL, NULL, progress)); if (outStreamSpec->GetRem() != 0) opRes = NExtract::NOperationResult::kDataError; outStreamSpec->ReleaseStream(); RINOK(extractCallback->SetOperationResult(opRes)); } return S_OK; COM_TRY_END } STDMETHODIMP CHandler::GetStream(UInt32 index, ISequentialInStream **stream) { COM_TRY_BEGIN const CParseItem &item = _items[index]; return CreateLimitedInStream(_stream, item.Offset, item.Size, stream); COM_TRY_END } }} #endif HRESULT Archive_GetItemBoolProp(IInArchive *arc, UInt32 index, PROPID propID, bool &result) throw() { NCOM::CPropVariant prop; result = false; RINOK(arc->GetProperty(index, propID, &prop)); if (prop.vt == VT_BOOL) result = VARIANT_BOOLToBool(prop.boolVal); else if (prop.vt != VT_EMPTY) return E_FAIL; return S_OK; } HRESULT Archive_IsItem_Dir(IInArchive *arc, UInt32 index, bool &result) throw() { return Archive_GetItemBoolProp(arc, index, kpidIsDir, result); } HRESULT Archive_IsItem_Aux(IInArchive *arc, UInt32 index, bool &result) throw() { return Archive_GetItemBoolProp(arc, index, kpidIsAux, result); } HRESULT Archive_IsItem_AltStream(IInArchive *arc, UInt32 index, bool &result) throw() { return Archive_GetItemBoolProp(arc, index, kpidIsAltStream, result); } HRESULT Archive_IsItem_Deleted(IInArchive *arc, UInt32 index, bool &result) throw() { return Archive_GetItemBoolProp(arc, index, kpidIsDeleted, result); } static HRESULT Archive_GetArcBoolProp(IInArchive *arc, PROPID propid, bool &result) throw() { NCOM::CPropVariant prop; result = false; RINOK(arc->GetArchiveProperty(propid, &prop)); if (prop.vt == VT_BOOL) result = VARIANT_BOOLToBool(prop.boolVal); else if (prop.vt != VT_EMPTY) return E_FAIL; return S_OK; } static HRESULT Archive_GetArcProp_UInt(IInArchive *arc, PROPID propid, UInt64 &result, bool &defined) { defined = false; NCOM::CPropVariant prop; RINOK(arc->GetArchiveProperty(propid, &prop)); switch (prop.vt) { case VT_UI4: result = prop.ulVal; defined = true; break; case VT_I4: result = (Int64)prop.lVal; defined = true; break; case VT_UI8: result = (UInt64)prop.uhVal.QuadPart; defined = true; break; case VT_I8: result = (UInt64)prop.hVal.QuadPart; defined = true; break; case VT_EMPTY: break; default: return E_FAIL; } return S_OK; } static HRESULT Archive_GetArcProp_Int(IInArchive *arc, PROPID propid, Int64 &result, bool &defined) { defined = false; NCOM::CPropVariant prop; RINOK(arc->GetArchiveProperty(propid, &prop)); switch (prop.vt) { case VT_UI4: result = prop.ulVal; defined = true; break; case VT_I4: result = prop.lVal; defined = true; break; case VT_UI8: result = (Int64)prop.uhVal.QuadPart; defined = true; break; case VT_I8: result = (Int64)prop.hVal.QuadPart; defined = true; break; case VT_EMPTY: break; default: return E_FAIL; } return S_OK; } #ifndef _SFX HRESULT CArc::GetItemPathToParent(UInt32 index, UInt32 parent, UStringVector &parts) const { if (!GetRawProps) return E_FAIL; if (index == parent) return S_OK; UInt32 curIndex = index; UString s; bool prevWasAltStream = false; for (;;) { #ifdef MY_CPU_LE const void *p; UInt32 size; UInt32 propType; RINOK(GetRawProps->GetRawProp(curIndex, kpidName, &p, &size, &propType)); if (p && propType == PROP_DATA_TYPE_wchar_t_PTR_Z_LE) s = (const wchar_t *)p; else #endif { NCOM::CPropVariant prop; RINOK(Archive->GetProperty(curIndex, kpidName, &prop)); if (prop.vt == VT_BSTR && prop.bstrVal) s.SetFromBstr(prop.bstrVal); else if (prop.vt == VT_EMPTY) s.Empty(); else return E_FAIL; } UInt32 curParent = (UInt32)(Int32)-1; UInt32 parentType = 0; RINOK(GetRawProps->GetParent(curIndex, &curParent, &parentType)); if (parentType != NParentType::kAltStream) { for (;;) { int pos = s.ReverseFind_PathSepar(); if (pos < 0) { break; } parts.Insert(0, s.Ptr(pos + 1)); s.DeleteFrom(pos); } } parts.Insert(0, s); if (prevWasAltStream) { { UString &s2 = parts[parts.Size() - 2]; s2 += ':'; s2 += parts.Back(); } parts.DeleteBack(); } if (parent == curParent) return S_OK; prevWasAltStream = false; if (parentType == NParentType::kAltStream) prevWasAltStream = true; if (curParent == (UInt32)(Int32)-1) return E_FAIL; curIndex = curParent; } } #endif HRESULT CArc::GetItemPath(UInt32 index, UString &result) const { #ifdef MY_CPU_LE if (GetRawProps) { const void *p; UInt32 size; UInt32 propType; if (!IsTree) { if (GetRawProps->GetRawProp(index, kpidPath, &p, &size, &propType) == S_OK && propType == NPropDataType::kUtf16z) { unsigned len = size / 2 - 1; wchar_t *s = result.GetBuf(len); for (unsigned i = 0; i < len; i++) { wchar_t c = GetUi16(p); p = (const void *)((const Byte *)p + 2); #if WCHAR_PATH_SEPARATOR != L'/' if (c == L'/') c = WCHAR_PATH_SEPARATOR; #endif *s++ = c; } *s = 0; result.ReleaseBuf_SetLen(len); if (len != 0) return S_OK; } } /* else if (GetRawProps->GetRawProp(index, kpidName, &p, &size, &propType) == S_OK && p && propType == NPropDataType::kUtf16z) { size -= 2; UInt32 totalSize = size; bool isOK = false; { UInt32 index2 = index; for (;;) { UInt32 parent = (UInt32)(Int32)-1; UInt32 parentType = 0; if (GetRawProps->GetParent(index2, &parent, &parentType) != S_OK) break; if (parent == (UInt32)(Int32)-1) { if (parentType != 0) totalSize += 2; isOK = true; break; } index2 = parent; UInt32 size2; const void *p2; if (GetRawProps->GetRawProp(index2, kpidName, &p2, &size2, &propType) != S_OK && p2 && propType == NPropDataType::kUtf16z) break; totalSize += size2; } } if (isOK) { wchar_t *sz = result.GetBuf_SetEnd(totalSize / 2); UInt32 pos = totalSize - size; memcpy((Byte *)sz + pos, p, size); UInt32 index2 = index; for (;;) { UInt32 parent = (UInt32)(Int32)-1; UInt32 parentType = 0; if (GetRawProps->GetParent(index2, &parent, &parentType) != S_OK) break; if (parent == (UInt32)(Int32)-1) { if (parentType != 0) sz[pos / 2 - 1] = L':'; break; } index2 = parent; UInt32 size2; const void *p2; if (GetRawProps->GetRawProp(index2, kpidName, &p2, &size2, &propType) != S_OK) break; pos -= size2; memcpy((Byte *)sz + pos, p2, size2); sz[(pos + size2 - 2) / 2] = (parentType == 0) ? WCHAR_PATH_SEPARATOR : L':'; } #ifdef _WIN32 // result.Replace(L'/', WCHAR_PATH_SEPARATOR); #endif return S_OK; } } */ } #endif { NCOM::CPropVariant prop; RINOK(Archive->GetProperty(index, kpidPath, &prop)); if (prop.vt == VT_BSTR && prop.bstrVal) result.SetFromBstr(prop.bstrVal); else if (prop.vt == VT_EMPTY) result.Empty(); else return E_FAIL; } if (result.IsEmpty()) return GetDefaultItemPath(index, result); return S_OK; } HRESULT CArc::GetDefaultItemPath(UInt32 index, UString &result) const { result.Empty(); bool isDir; RINOK(Archive_IsItem_Dir(Archive, index, isDir)); if (!isDir) { result = DefaultName; NCOM::CPropVariant prop; RINOK(Archive->GetProperty(index, kpidExtension, &prop)); if (prop.vt == VT_BSTR) { result += '.'; result += prop.bstrVal; } else if (prop.vt != VT_EMPTY) return E_FAIL; } return S_OK; } HRESULT CArc::GetItemPath2(UInt32 index, UString &result) const { RINOK(GetItemPath(index, result)); if (Ask_Deleted) { bool isDeleted = false; RINOK(Archive_IsItem_Deleted(Archive, index, isDeleted)); if (isDeleted) result.Insert(0, L"[DELETED]" WSTRING_PATH_SEPARATOR); } return S_OK; } #ifdef SUPPORT_ALT_STREAMS int FindAltStreamColon_in_Path(const wchar_t *path) { unsigned i = 0; int colonPos = -1; for (;; i++) { wchar_t c = path[i]; if (c == 0) return colonPos; if (c == ':') { if (colonPos < 0) colonPos = i; continue; } if (c == WCHAR_PATH_SEPARATOR) colonPos = -1; } } #endif HRESULT CArc::GetItem(UInt32 index, CReadArcItem &item) const { #ifdef SUPPORT_ALT_STREAMS item.IsAltStream = false; item.AltStreamName.Empty(); item.MainPath.Empty(); #endif item.IsDir = false; item.Path.Empty(); item.ParentIndex = (UInt32)(Int32)-1; item.PathParts.Clear(); RINOK(Archive_IsItem_Dir(Archive, index, item.IsDir)); item.MainIsDir = item.IsDir; RINOK(GetItemPath2(index, item.Path)); #ifndef _SFX UInt32 mainIndex = index; #endif #ifdef SUPPORT_ALT_STREAMS item.MainPath = item.Path; if (Ask_AltStream) { RINOK(Archive_IsItem_AltStream(Archive, index, item.IsAltStream)); } bool needFindAltStream = false; if (item.IsAltStream) { needFindAltStream = true; if (GetRawProps) { UInt32 parentType = 0; UInt32 parentIndex; RINOK(GetRawProps->GetParent(index, &parentIndex, &parentType)); if (parentType == NParentType::kAltStream) { NCOM::CPropVariant prop; RINOK(Archive->GetProperty(index, kpidName, &prop)); if (prop.vt == VT_BSTR && prop.bstrVal) item.AltStreamName.SetFromBstr(prop.bstrVal); else if (prop.vt != VT_EMPTY) return E_FAIL; else { // item.IsAltStream = false; } /* if (item.AltStreamName.IsEmpty()) item.IsAltStream = false; */ needFindAltStream = false; item.ParentIndex = parentIndex; mainIndex = parentIndex; if (parentIndex == (UInt32)(Int32)-1) { item.MainPath.Empty(); item.MainIsDir = true; } else { RINOK(GetItemPath2(parentIndex, item.MainPath)); RINOK(Archive_IsItem_Dir(Archive, parentIndex, item.MainIsDir)); } } } } if (item.WriteToAltStreamIfColon || needFindAltStream) { /* Good handler must support GetRawProps::GetParent for alt streams. So the following code currently is not used */ int colon = FindAltStreamColon_in_Path(item.Path); if (colon >= 0) { item.MainPath.DeleteFrom(colon); item.AltStreamName = item.Path.Ptr(colon + 1); item.MainIsDir = (colon == 0 || IsPathSepar(item.Path[(unsigned)colon - 1])); item.IsAltStream = true; } } #endif #ifndef _SFX if (item._use_baseParentFolder_mode) { RINOK(GetItemPathToParent(mainIndex, item._baseParentFolder, item.PathParts)); #ifdef SUPPORT_ALT_STREAMS if ((item.WriteToAltStreamIfColon || needFindAltStream) && !item.PathParts.IsEmpty()) { int colon; { UString &s = item.PathParts.Back(); colon = FindAltStreamColon_in_Path(s); if (colon >= 0) { item.AltStreamName = s.Ptr(colon + 1); item.MainIsDir = (colon == 0 || IsPathSepar(s[(unsigned)colon - 1])); item.IsAltStream = true; s.DeleteFrom(colon); } } if (colon == 0) item.PathParts.DeleteBack(); } #endif } else #endif SplitPathToParts( #ifdef SUPPORT_ALT_STREAMS item.MainPath #else item.Path #endif , item.PathParts); return S_OK; } #ifndef _SFX static HRESULT Archive_GetItem_Size(IInArchive *archive, UInt32 index, UInt64 &size, bool &defined) { NCOM::CPropVariant prop; defined = false; size = 0; RINOK(archive->GetProperty(index, kpidSize, &prop)); switch (prop.vt) { case VT_UI1: size = prop.bVal; break; case VT_UI2: size = prop.uiVal; break; case VT_UI4: size = prop.ulVal; break; case VT_UI8: size = (UInt64)prop.uhVal.QuadPart; break; case VT_EMPTY: return S_OK; default: return E_FAIL; } defined = true; return S_OK; } #endif HRESULT CArc::GetItemSize(UInt32 index, UInt64 &size, bool &defined) const { NCOM::CPropVariant prop; defined = false; size = 0; RINOK(Archive->GetProperty(index, kpidSize, &prop)); switch (prop.vt) { case VT_UI1: size = prop.bVal; break; case VT_UI2: size = prop.uiVal; break; case VT_UI4: size = prop.ulVal; break; case VT_UI8: size = (UInt64)prop.uhVal.QuadPart; break; case VT_EMPTY: return S_OK; default: return E_FAIL; } defined = true; return S_OK; } HRESULT CArc::GetItemMTime(UInt32 index, FILETIME &ft, bool &defined) const { NCOM::CPropVariant prop; defined = false; ft.dwHighDateTime = ft.dwLowDateTime = 0; RINOK(Archive->GetProperty(index, kpidMTime, &prop)); if (prop.vt == VT_FILETIME) { ft = prop.filetime; defined = true; } else if (prop.vt != VT_EMPTY) return E_FAIL; else if (MTimeDefined) { ft = MTime; defined = true; } return S_OK; } #ifndef _SFX static inline bool TestSignature(const Byte *p1, const Byte *p2, size_t size) { for (size_t i = 0; i < size; i++) if (p1[i] != p2[i]) return false; return true; } static void MakeCheckOrder(CCodecs *codecs, CIntVector &orderIndices, unsigned numTypes, CIntVector &orderIndices2, const Byte *data, size_t dataSize) { for (unsigned i = 0; i < numTypes; i++) { int index = orderIndices[i]; if (index < 0) continue; const CArcInfoEx &ai = codecs->Formats[(unsigned)index]; if (ai.SignatureOffset != 0) { orderIndices2.Add(index); orderIndices[i] = -1; continue; } const CObjectVector &sigs = ai.Signatures; FOR_VECTOR (k, sigs) { const CByteBuffer &sig = sigs[k]; if (sig.Size() == 0 && dataSize == 0 || sig.Size() != 0 && sig.Size() <= dataSize && TestSignature(data, sig, sig.Size())) { orderIndices2.Add(index); orderIndices[i] = -1; break; } } } } #endif #ifdef UNDER_CE static const unsigned kNumHashBytes = 1; #define HASH_VAL(buf) ((buf)[0]) #else static const unsigned kNumHashBytes = 2; // #define HASH_VAL(buf) ((buf)[0] | ((UInt32)(buf)[1] << 8)) #define HASH_VAL(buf) GetUi16(buf) #endif #ifndef _SFX static bool IsExeExt(const UString &ext) { return ext.IsEqualTo_Ascii_NoCase("exe"); } static const char * const k_PreArcFormats[] = { "pe" , "elf" , "macho" , "mub" , "te" }; static bool IsNameFromList(const UString &s, const char * const names[], size_t num) { for (unsigned i = 0; i < num; i++) if (StringsAreEqualNoCase_Ascii(s, names[i])) return true; return false; } static bool IsPreArcFormat(const CArcInfoEx &ai) { if (ai.Flags_PreArc()) return true; return IsNameFromList(ai.Name, k_PreArcFormats, ARRAY_SIZE(k_PreArcFormats)); } static const char * const k_Formats_with_simple_signuature[] = { "7z" , "xz" , "rar" , "bzip2" , "gzip" , "cab" , "wim" , "rpm" , "vhd" , "xar" }; static bool IsNewStyleSignature(const CArcInfoEx &ai) { // if (ai.Version >= 0x91F) if (ai.NewInterface) return true; return IsNameFromList(ai.Name, k_Formats_with_simple_signuature, ARRAY_SIZE(k_Formats_with_simple_signuature)); } class CArchiveOpenCallback_Offset: public IArchiveOpenCallback, public IArchiveOpenVolumeCallback, #ifndef _NO_CRYPTO public ICryptoGetTextPassword, #endif public CMyUnknownImp { public: CMyComPtr Callback; CMyComPtr OpenVolumeCallback; UInt64 Files; UInt64 Offset; #ifndef _NO_CRYPTO CMyComPtr GetTextPassword; #endif MY_QUERYINTERFACE_BEGIN2(IArchiveOpenCallback) MY_QUERYINTERFACE_ENTRY(IArchiveOpenVolumeCallback) #ifndef _NO_CRYPTO MY_QUERYINTERFACE_ENTRY(ICryptoGetTextPassword) #endif MY_QUERYINTERFACE_END MY_ADDREF_RELEASE INTERFACE_IArchiveOpenCallback(;) INTERFACE_IArchiveOpenVolumeCallback(;) #ifndef _NO_CRYPTO STDMETHOD(CryptoGetTextPassword)(BSTR *password); #endif }; #ifndef _NO_CRYPTO STDMETHODIMP CArchiveOpenCallback_Offset::CryptoGetTextPassword(BSTR *password) { COM_TRY_BEGIN if (GetTextPassword) return GetTextPassword->CryptoGetTextPassword(password); return E_NOTIMPL; COM_TRY_END } #endif STDMETHODIMP CArchiveOpenCallback_Offset::SetTotal(const UInt64 *, const UInt64 *) { return S_OK; } STDMETHODIMP CArchiveOpenCallback_Offset::SetCompleted(const UInt64 *, const UInt64 *bytes) { if (!Callback) return S_OK; UInt64 value = Offset; if (bytes) value += *bytes; return Callback->SetCompleted(&Files, &value); } STDMETHODIMP CArchiveOpenCallback_Offset::GetProperty(PROPID propID, PROPVARIANT *value) { if (OpenVolumeCallback) return OpenVolumeCallback->GetProperty(propID, value); NCOM::PropVariant_Clear(value); return S_OK; // return E_NOTIMPL; } STDMETHODIMP CArchiveOpenCallback_Offset::GetStream(const wchar_t *name, IInStream **inStream) { if (OpenVolumeCallback) return OpenVolumeCallback->GetStream(name, inStream); return S_FALSE; } #endif UInt32 GetOpenArcErrorFlags(const NCOM::CPropVariant &prop, bool *isDefinedProp) { if (isDefinedProp != NULL) *isDefinedProp = false; switch (prop.vt) { case VT_UI8: if (isDefinedProp) *isDefinedProp = true; return (UInt32)prop.uhVal.QuadPart; case VT_UI4: if (isDefinedProp) *isDefinedProp = true; return prop.ulVal; case VT_EMPTY: return 0; default: throw 151199; } } void CArcErrorInfo::ClearErrors() { // ErrorFormatIndex = -1; // we don't need to clear ErrorFormatIndex here !!! ThereIsTail = false; UnexpecedEnd = false; IgnoreTail = false; // NonZerosTail = false; ErrorFlags_Defined = false; ErrorFlags = 0; WarningFlags = 0; TailSize = 0; ErrorMessage.Empty(); WarningMessage.Empty(); } HRESULT CArc::ReadBasicProps(IInArchive *archive, UInt64 startPos, HRESULT openRes) { // OkPhySize_Defined = false; PhySizeDefined = false; PhySize = 0; Offset = 0; AvailPhySize = FileSize - startPos; ErrorInfo.ClearErrors(); { NCOM::CPropVariant prop; RINOK(archive->GetArchiveProperty(kpidErrorFlags, &prop)); ErrorInfo.ErrorFlags = GetOpenArcErrorFlags(prop, &ErrorInfo.ErrorFlags_Defined); } { NCOM::CPropVariant prop; RINOK(archive->GetArchiveProperty(kpidWarningFlags, &prop)); ErrorInfo.WarningFlags = GetOpenArcErrorFlags(prop); } { NCOM::CPropVariant prop; RINOK(archive->GetArchiveProperty(kpidError, &prop)); if (prop.vt != VT_EMPTY) ErrorInfo.ErrorMessage = (prop.vt == VT_BSTR ? prop.bstrVal : L"Unknown error"); } { NCOM::CPropVariant prop; RINOK(archive->GetArchiveProperty(kpidWarning, &prop)); if (prop.vt != VT_EMPTY) ErrorInfo.WarningMessage = (prop.vt == VT_BSTR ? prop.bstrVal : L"Unknown warning"); } if (openRes == S_OK || ErrorInfo.IsArc_After_NonOpen()) { RINOK(Archive_GetArcProp_UInt(archive, kpidPhySize, PhySize, PhySizeDefined)); /* RINOK(Archive_GetArcProp_UInt(archive, kpidOkPhySize, OkPhySize, OkPhySize_Defined)); if (!OkPhySize_Defined) { OkPhySize_Defined = PhySizeDefined; OkPhySize = PhySize; } */ bool offsetDefined; RINOK(Archive_GetArcProp_Int(archive, kpidOffset, Offset, offsetDefined)); Int64 globalOffset = startPos + Offset; AvailPhySize = FileSize - globalOffset; if (PhySizeDefined) { UInt64 endPos = globalOffset + PhySize; if (endPos < FileSize) { AvailPhySize = PhySize; ErrorInfo.ThereIsTail = true; ErrorInfo.TailSize = FileSize - endPos; } else if (endPos > FileSize) ErrorInfo.UnexpecedEnd = true; } } return S_OK; } /* static PrintNumber(const char *s, int n) { char temp[100]; sprintf(temp, "%s %d", s, n); OutputDebugStringA(temp); } */ HRESULT CArc::PrepareToOpen(const COpenOptions &op, unsigned formatIndex, CMyComPtr &archive) { // OutputDebugStringA("a1"); // PrintNumber("formatIndex", formatIndex); RINOK(op.codecs->CreateInArchive(formatIndex, archive)); // OutputDebugStringA("a2"); if (!archive) return S_OK; #ifdef EXTERNAL_CODECS if (op.codecs->NeedSetLibCodecs) { const CArcInfoEx &ai = op.codecs->Formats[formatIndex]; if (ai.LibIndex >= 0 ? !op.codecs->Libs[ai.LibIndex].SetCodecs : !op.codecs->Libs.IsEmpty()) { CMyComPtr setCompressCodecsInfo; archive.QueryInterface(IID_ISetCompressCodecsInfo, (void **)&setCompressCodecsInfo); if (setCompressCodecsInfo) { RINOK(setCompressCodecsInfo->SetCompressCodecsInfo(op.codecs)); } } } #endif #ifndef _SFX const CArcInfoEx &ai = op.codecs->Formats[formatIndex]; // OutputDebugStringW(ai.Name); // OutputDebugStringA("a3"); if (ai.Flags_PreArc()) { /* we notify parsers that extract executables, that they don't need to open archive, if there is tail after executable (for SFX cases) */ CMyComPtr allowTail; archive.QueryInterface(IID_IArchiveAllowTail, (void **)&allowTail); if (allowTail) allowTail->AllowTail(BoolToInt(true)); } if (op.props) { /* FOR_VECTOR (y, op.props) { const COptionalOpenProperties &optProps = (*op.props)[y]; if (optProps.FormatName.IsEmpty() || optProps.FormatName.CompareNoCase(ai.Name) == 0) { RINOK(SetProperties(archive, optProps.Props)); break; } } */ RINOK(SetProperties(archive, *op.props)); } #endif return S_OK; } #ifndef _SFX static HRESULT ReadParseItemProps(IInArchive *archive, const CArcInfoEx &ai, NArchive::NParser::CParseItem &pi) { pi.Extension = ai.GetMainExt(); pi.FileTime_Defined = false; pi.ArcType = ai.Name; RINOK(Archive_GetArcBoolProp(archive, kpidIsNotArcType, pi.IsNotArcType)); // RINOK(Archive_GetArcBoolProp(archive, kpidIsSelfExe, pi.IsSelfExe)); pi.IsSelfExe = ai.Flags_PreArc(); { NCOM::CPropVariant prop; RINOK(archive->GetArchiveProperty(kpidMTime, &prop)); if (prop.vt == VT_FILETIME) { pi.FileTime_Defined = true; pi.FileTime = prop.filetime; } } if (!pi.FileTime_Defined) { NCOM::CPropVariant prop; RINOK(archive->GetArchiveProperty(kpidCTime, &prop)); if (prop.vt == VT_FILETIME) { pi.FileTime_Defined = true; pi.FileTime = prop.filetime; } } { NCOM::CPropVariant prop; RINOK(archive->GetArchiveProperty(kpidName, &prop)); if (prop.vt == VT_BSTR) { pi.Name.SetFromBstr(prop.bstrVal); pi.Extension.Empty(); } else { RINOK(archive->GetArchiveProperty(kpidExtension, &prop)); if (prop.vt == VT_BSTR) pi.Extension.SetFromBstr(prop.bstrVal); } } { NCOM::CPropVariant prop; RINOK(archive->GetArchiveProperty(kpidShortComment, &prop)); if (prop.vt == VT_BSTR) pi.Comment.SetFromBstr(prop.bstrVal); } UInt32 numItems; RINOK(archive->GetNumberOfItems(&numItems)); // pi.NumSubFiles = numItems; // RINOK(Archive_GetArcProp_UInt(archive, kpidUnpackSize, pi.UnpackSize, pi.UnpackSize_Defined)); // if (!pi.UnpackSize_Defined) { pi.NumSubFiles = 0; pi.NumSubDirs = 0; pi.UnpackSize = 0; for (UInt32 i = 0; i < numItems; i++) { UInt64 size = 0; bool defined = false; Archive_GetItem_Size(archive, i, size, defined); if (defined) { pi.UnpackSize_Defined = true; pi.UnpackSize += size; } bool isDir = false; Archive_IsItem_Dir(archive, i, isDir); if (isDir) pi.NumSubDirs++; else pi.NumSubFiles++; } if (pi.NumSubDirs != 0) pi.NumSubDirs_Defined = true; pi.NumSubFiles_Defined = true; } return S_OK; } #endif HRESULT CArc::CheckZerosTail(const COpenOptions &op, UInt64 offset) { if (!op.stream) return S_OK; RINOK(op.stream->Seek(offset, STREAM_SEEK_SET, NULL)); const UInt32 kBufSize = 1 << 11; Byte buf[kBufSize]; for (;;) { UInt32 processed = 0; RINOK(op.stream->Read(buf, kBufSize, &processed)); if (processed == 0) { // ErrorInfo.NonZerosTail = false; ErrorInfo.IgnoreTail = true; return S_OK; } for (size_t i = 0; i < processed; i++) { if (buf[i] != 0) { // ErrorInfo.IgnoreTail = false; // ErrorInfo.NonZerosTail = true; return S_OK; } } } } #ifndef _SFX class CExtractCallback_To_OpenCallback: public IArchiveExtractCallback, public ICompressProgressInfo, public CMyUnknownImp { public: CMyComPtr Callback; UInt64 Files; UInt64 Offset; MY_UNKNOWN_IMP2(IArchiveExtractCallback, ICompressProgressInfo) INTERFACE_IArchiveExtractCallback(;) STDMETHOD(SetRatioInfo)(const UInt64 *inSize, const UInt64 *outSize); void Init(IArchiveOpenCallback *callback) { Callback = callback; Files = 0; Offset = 0; } }; STDMETHODIMP CExtractCallback_To_OpenCallback::SetTotal(UInt64 /* size */) { return S_OK; } STDMETHODIMP CExtractCallback_To_OpenCallback::SetCompleted(const UInt64 * /* completeValue */) { return S_OK; } STDMETHODIMP CExtractCallback_To_OpenCallback::SetRatioInfo(const UInt64 *inSize, const UInt64 * /* outSize */) { if (Callback) { UInt64 value = Offset; if (inSize) value += *inSize; return Callback->SetCompleted(&Files, &value); } return S_OK; } STDMETHODIMP CExtractCallback_To_OpenCallback::GetStream(UInt32 /* index */, ISequentialOutStream **outStream, Int32 /* askExtractMode */) { *outStream = 0; return S_OK; } STDMETHODIMP CExtractCallback_To_OpenCallback::PrepareOperation(Int32 /* askExtractMode */) { return S_OK; } STDMETHODIMP CExtractCallback_To_OpenCallback::SetOperationResult(Int32 /* operationResult */) { return S_OK; } static HRESULT OpenArchiveSpec(IInArchive *archive, bool needPhySize, IInStream *stream, const UInt64 *maxCheckStartPosition, IArchiveOpenCallback *openCallback, IArchiveExtractCallback *extractCallback) { /* if (needPhySize) { CMyComPtr open2; archive->QueryInterface(IID_IArchiveOpen2, (void **)&open2); if (open2) return open2->ArcOpen2(stream, kOpenFlags_RealPhySize, openCallback); } */ RINOK(archive->Open(stream, maxCheckStartPosition, openCallback)); if (needPhySize) { bool phySize_Defined = false; UInt64 phySize = 0; RINOK(Archive_GetArcProp_UInt(archive, kpidPhySize, phySize, phySize_Defined)); if (phySize_Defined) return S_OK; bool phySizeCantBeDetected = false;; RINOK(Archive_GetArcBoolProp(archive, kpidPhySizeCantBeDetected, phySizeCantBeDetected)); if (!phySizeCantBeDetected) { RINOK(archive->Extract(0, (UInt32)(Int32)-1, BoolToInt(true), extractCallback)); } } return S_OK; } static int FindFormatForArchiveType(CCodecs *codecs, CIntVector orderIndices, const char *name) { FOR_VECTOR (i, orderIndices) if (StringsAreEqualNoCase_Ascii(codecs->Formats[orderIndices[i]].Name, name)) return i; return -1; } #endif HRESULT CArc::OpenStream2(const COpenOptions &op) { // fprintf(stdout, "\nOpen: %S", Path); fflush(stdout); Archive.Release(); GetRawProps.Release(); GetRootProps.Release(); ErrorInfo.ClearErrors(); ErrorInfo.ErrorFormatIndex = -1; IsParseArc = false; ArcStreamOffset = 0; // OutputDebugStringA("1"); // OutputDebugStringW(Path); const UString fileName = ExtractFileNameFromPath(Path); UString extension; { int dotPos = fileName.ReverseFind_Dot(); if (dotPos >= 0) extension = fileName.Ptr(dotPos + 1); } CIntVector orderIndices; bool searchMarkerInHandler = false; #ifdef _SFX searchMarkerInHandler = true; #endif CBoolArr isMainFormatArr(op.codecs->Formats.Size()); { FOR_VECTOR(i, op.codecs->Formats) isMainFormatArr[i] = false; } UInt64 maxStartOffset = op.openType.MaxStartOffset_Defined ? op.openType.MaxStartOffset : kMaxCheckStartPosition; #ifndef _SFX bool isUnknownExt = false; #endif bool isForced = false; unsigned numMainTypes = 0; int formatIndex = op.openType.FormatIndex; if (formatIndex >= 0) { isForced = true; orderIndices.Add(formatIndex); numMainTypes = 1; isMainFormatArr[(unsigned)formatIndex] = true; searchMarkerInHandler = true; } else { unsigned numFinded = 0; #ifndef _SFX bool isPrearcExt = false; #endif { #ifndef _SFX bool isZip = false; bool isRar = false; const wchar_t c = extension[0]; if (c == 'z' || c == 'Z' || c == 'r' || c == 'R') { bool isNumber = false; for (unsigned k = 1;; k++) { const wchar_t d = extension[k]; if (d == 0) break; if (d < '0' || d > '9') { isNumber = false; break; } isNumber = true; } if (isNumber) if (c == 'z' || c == 'Z') isZip = true; else isRar = true; } #endif FOR_VECTOR (i, op.codecs->Formats) { const CArcInfoEx &ai = op.codecs->Formats[i]; if (IgnoreSplit || !op.openType.CanReturnArc) if (ai.IsSplit()) continue; if (op.excludedFormats->FindInSorted(i) >= 0) continue; #ifndef _SFX if (IsPreArcFormat(ai)) isPrearcExt = true; #endif if (ai.FindExtension(extension) >= 0 #ifndef _SFX || isZip && StringsAreEqualNoCase_Ascii(ai.Name, "zip") || isRar && StringsAreEqualNoCase_Ascii(ai.Name, "rar") #endif ) { // PrintNumber("orderIndices.Insert", i); orderIndices.Insert(numFinded++, i); isMainFormatArr[i] = true; } else orderIndices.Add(i); } } if (!op.stream) { if (numFinded != 1) return E_NOTIMPL; orderIndices.DeleteFrom(1); } // PrintNumber("numFinded", numFinded ); /* if (op.openOnlySpecifiedByExtension) { if (numFinded != 0 && !IsExeExt(extension)) orderIndices.DeleteFrom(numFinded); } */ #ifndef _SFX if (op.stream && orderIndices.Size() >= 2) { RINOK(op.stream->Seek(0, STREAM_SEEK_SET, NULL)); CByteBuffer byteBuffer; CIntVector orderIndices2; if (numFinded == 0 || IsExeExt(extension)) { // signature search was here } else if (extension.IsEqualTo("000") || extension.IsEqualTo("001")) { int i = FindFormatForArchiveType(op.codecs, orderIndices, "rar"); if (i >= 0) { const size_t kBufSize = (1 << 10); byteBuffer.Alloc(kBufSize); size_t processedSize = kBufSize; RINOK(ReadStream(op.stream, byteBuffer, &processedSize)); if (processedSize >= 16) { const Byte *buf = byteBuffer; const Byte kRarHeader[] = { 0x52 , 0x61, 0x72, 0x21, 0x1a, 0x07, 0x00 }; if (TestSignature(buf, kRarHeader, 7) && buf[9] == 0x73 && (buf[10] & 1) != 0) { orderIndices2.Add(orderIndices[i]); orderIndices[i] = -1; if (i >= (int)numFinded) numFinded++; } } } } else { const size_t kBufSize = (1 << 10); byteBuffer.Alloc(kBufSize); size_t processedSize = kBufSize; RINOK(ReadStream(op.stream, byteBuffer, &processedSize)); if (processedSize == 0) return S_FALSE; /* check type order: 1) matched extension, no signuature 2) matched extension, matched signuature // 3) no signuature // 4) matched signuature */ MakeCheckOrder(op.codecs, orderIndices, numFinded, orderIndices2, NULL, 0); MakeCheckOrder(op.codecs, orderIndices, numFinded, orderIndices2, byteBuffer, processedSize); // MakeCheckOrder(op.codecs, orderIndices, orderIndices.Size(), orderIndices2, NULL, 0); // MakeCheckOrder(op.codecs, orderIndices, orderIndices.Size(), orderIndices2, byteBuffer, processedSize); } FOR_VECTOR (i, orderIndices) { int val = orderIndices[i]; if (val != -1) orderIndices2.Add(val); } orderIndices = orderIndices2; } if (orderIndices.Size() >= 2) { int iIso = FindFormatForArchiveType(op.codecs, orderIndices, "iso"); int iUdf = FindFormatForArchiveType(op.codecs, orderIndices, "udf"); if (iUdf > iIso && iIso >= 0) { int isoIndex = orderIndices[iIso]; int udfIndex = orderIndices[iUdf]; orderIndices[iUdf] = isoIndex; orderIndices[iIso] = udfIndex; } } numMainTypes = numFinded; isUnknownExt = (numMainTypes == 0) || isPrearcExt; #else // _SFX numMainTypes = orderIndices.Size(); // we need correct numMainTypes for mutlivolume SFX (if some volume is missing) if (numFinded != 0) numMainTypes = numFinded; #endif } UInt64 fileSize = 0; if (op.stream) { RINOK(op.stream->Seek(0, STREAM_SEEK_END, &fileSize)); RINOK(op.stream->Seek(0, STREAM_SEEK_SET, NULL)); } FileSize = fileSize; #ifndef _SFX CBoolArr skipFrontalFormat(op.codecs->Formats.Size()); { FOR_VECTOR(i, op.codecs->Formats) skipFrontalFormat[i] = false; } #endif const COpenType &mode = op.openType; if (mode.CanReturnArc) { // ---------- OPEN main type by extenssion ---------- unsigned numCheckTypes = orderIndices.Size(); if (formatIndex >= 0) numCheckTypes = numMainTypes; for (unsigned i = 0; i < numCheckTypes; i++) { FormatIndex = orderIndices[i]; bool exactOnly = false; #ifndef _SFX const CArcInfoEx &ai = op.codecs->Formats[FormatIndex]; // OutputDebugStringW(ai.Name); if (i >= numMainTypes) { if (!ai.Flags_BackwardOpen() // && !ai.Flags_PureStartOpen() ) continue; exactOnly = true; } #endif // Some handlers do not set total bytes. So we set it here if (op.callback) RINOK(op.callback->SetTotal(NULL, &fileSize)); if (op.stream) { RINOK(op.stream->Seek(0, STREAM_SEEK_SET, NULL)); } CMyComPtr archive; RINOK(PrepareToOpen(op, FormatIndex, archive)); if (!archive) continue; HRESULT result; if (op.stream) { UInt64 searchLimit = (!exactOnly && searchMarkerInHandler) ? maxStartOffset: 0; result = archive->Open(op.stream, &searchLimit, op.callback); } else { CMyComPtr openSeq; archive.QueryInterface(IID_IArchiveOpenSeq, (void **)&openSeq); if (!openSeq) return E_NOTIMPL; result = openSeq->OpenSeq(op.seqStream); } RINOK(ReadBasicProps(archive, 0, result)); if (result == S_FALSE) { bool isArc = ErrorInfo.IsArc_After_NonOpen(); #ifndef _SFX // if it's archive, we allow another open attempt for parser if (!mode.CanReturnParser || !isArc) skipFrontalFormat[(unsigned)FormatIndex] = true; #endif if (exactOnly) continue; if (i == 0 && numMainTypes == 1) { // we set NonOpenErrorInfo, only if there is only one main format (defined by extension). ErrorInfo.ErrorFormatIndex = FormatIndex; NonOpen_ErrorInfo = ErrorInfo; if (!mode.CanReturnParser && isArc) { // if (formatIndex < 0 && !searchMarkerInHandler) { // if bad archive was detected, we don't need additional open attempts #ifndef _SFX if (!IsPreArcFormat(ai) /* || !mode.SkipSfxStub */) #endif return S_FALSE; } } } /* #ifndef _SFX if (IsExeExt(extension) || ai.Flags_PreArc()) { // openOnlyFullArc = false; // canReturnTailArc = true; // limitSignatureSearch = true; } #endif */ continue; } RINOK(result); #ifndef _SFX bool isMainFormat = isMainFormatArr[(unsigned)FormatIndex]; const COpenSpecFlags &specFlags = mode.GetSpec(isForced, isMainFormat, isUnknownExt); bool thereIsTail = ErrorInfo.ThereIsTail; if (thereIsTail && mode.ZerosTailIsAllowed) { RINOK(CheckZerosTail(op, Offset + PhySize)); if (ErrorInfo.IgnoreTail) thereIsTail = false; } if (Offset > 0) { if (exactOnly || !searchMarkerInHandler || !specFlags.CanReturn_NonStart() || (mode.MaxStartOffset_Defined && (UInt64)Offset > mode.MaxStartOffset)) continue; } if (thereIsTail) { if (Offset > 0) { if (!specFlags.CanReturnMid) continue; } else if (!specFlags.CanReturnFrontal) continue; } if (Offset > 0 || thereIsTail) { if (formatIndex < 0) { if (IsPreArcFormat(ai)) { // openOnlyFullArc = false; // canReturnTailArc = true; /* if (mode.SkipSfxStub) limitSignatureSearch = true; */ // if (mode.SkipSfxStub) { // skipFrontalFormat[FormatIndex] = true; continue; } } } } #endif Archive = archive; return S_OK; } } #ifndef _SFX if (!op.stream) return S_FALSE; if (formatIndex >= 0 && !mode.CanReturnParser) { if (mode.MaxStartOffset_Defined) { if (mode.MaxStartOffset == 0) return S_FALSE; } else { const CArcInfoEx &ai = op.codecs->Formats[formatIndex]; if (ai.FindExtension(extension) >= 0) { if (ai.Flags_FindSignature() && searchMarkerInHandler) return S_FALSE; } } } NArchive::NParser::CHandler *handlerSpec = new NArchive::NParser::CHandler; CMyComPtr handler = handlerSpec; CExtractCallback_To_OpenCallback *extractCallback_To_OpenCallback_Spec = new CExtractCallback_To_OpenCallback; CMyComPtr extractCallback_To_OpenCallback = extractCallback_To_OpenCallback_Spec; extractCallback_To_OpenCallback_Spec->Init(op.callback); { // ---------- Check all possible START archives ---------- // this code is better for full file archives than Parser's code. CByteBuffer byteBuffer; bool endOfFile = false; size_t processedSize; { size_t bufSize = 1 << 20; // it must be larger than max signature offset or IsArcFunc offset ((1 << 19) + x for UDF) if (bufSize > fileSize) { bufSize = (size_t)fileSize; endOfFile = true; } byteBuffer.Alloc(bufSize); RINOK(op.stream->Seek(0, STREAM_SEEK_SET, NULL)); processedSize = bufSize; RINOK(ReadStream(op.stream, byteBuffer, &processedSize)); if (processedSize == 0) return S_FALSE; if (processedSize < bufSize) endOfFile = true; } CUIntVector sortedFormats; unsigned i; int splitIndex = -1; for (i = 0; i < orderIndices.Size(); i++) { unsigned form = orderIndices[i]; if (skipFrontalFormat[form]) continue; const CArcInfoEx &ai = op.codecs->Formats[form]; if (ai.IsSplit()) { splitIndex = form; continue; } if (ai.IsArcFunc) { UInt32 isArcRes = ai.IsArcFunc(byteBuffer, processedSize); if (isArcRes == k_IsArc_Res_NO) continue; if (isArcRes == k_IsArc_Res_NEED_MORE && endOfFile) continue; // if (isArcRes == k_IsArc_Res_YES_LOW_PROB) continue; sortedFormats.Insert(0, form); continue; } bool isNewStyleSignature = IsNewStyleSignature(ai); bool needCheck = !isNewStyleSignature || ai.Signatures.IsEmpty() || ai.Flags_PureStartOpen() || ai.Flags_StartOpen() || ai.Flags_BackwardOpen(); if (isNewStyleSignature && !ai.Signatures.IsEmpty()) { unsigned k; for (k = 0; k < ai.Signatures.Size(); k++) { const CByteBuffer &sig = ai.Signatures[k]; UInt32 signatureEnd = ai.SignatureOffset + (UInt32)sig.Size(); if (processedSize < signatureEnd) { if (!endOfFile) needCheck = true; } else if (memcmp(sig, byteBuffer + ai.SignatureOffset, sig.Size()) == 0) break; } if (k != ai.Signatures.Size()) { sortedFormats.Insert(0, form); continue; } } if (needCheck) sortedFormats.Add(form); } if (splitIndex >= 0) sortedFormats.Insert(0, splitIndex); for (i = 0; i < sortedFormats.Size(); i++) { FormatIndex = sortedFormats[i]; const CArcInfoEx &ai = op.codecs->Formats[FormatIndex]; if (op.callback) RINOK(op.callback->SetTotal(NULL, &fileSize)); RINOK(op.stream->Seek(0, STREAM_SEEK_SET, NULL)); CMyComPtr archive; RINOK(PrepareToOpen(op, FormatIndex, archive)); if (!archive) continue; PRF(printf("\nSorted Open %S", (const wchar_t *)ai.Name)); HRESULT result; { UInt64 searchLimit = 0; /* if (mode.CanReturnArc) result = archive->Open(op.stream, &searchLimit, op.callback); else */ result = OpenArchiveSpec(archive, !mode.CanReturnArc, op.stream, &searchLimit, op.callback, extractCallback_To_OpenCallback); } if (result == S_FALSE) { skipFrontalFormat[(unsigned)FormatIndex] = true; // FIXME: maybe we must use LenIsUnknown. // printf(" OpenForSize Error"); continue; } RINOK(result); RINOK(ReadBasicProps(archive, 0, result)); if (Offset > 0) { continue; // good handler doesn't return such Offset > 0 // but there are some cases like false prefixed PK00 archive, when // we can support it? } NArchive::NParser::CParseItem pi; pi.Offset = Offset; pi.Size = AvailPhySize; // bool needScan = false; if (!PhySizeDefined) { // it's for Z format pi.LenIsUnknown = true; // needScan = true; // phySize = arcRem; // nextNeedCheckStartOpen = false; } /* if (OkPhySize_Defined) pi.OkSize = pi.OkPhySize; else pi.OkSize = pi.Size; */ pi.NormalizeOffset(); // printf(" phySize = %8d", (unsigned)phySize); if (mode.CanReturnArc) { bool isMainFormat = isMainFormatArr[(unsigned)FormatIndex]; const COpenSpecFlags &specFlags = mode.GetSpec(isForced, isMainFormat, isUnknownExt); bool openCur = false; if (!ErrorInfo.ThereIsTail) openCur = true; else { if (mode.ZerosTailIsAllowed) { RINOK(CheckZerosTail(op, Offset + PhySize)); if (ErrorInfo.IgnoreTail) openCur = true; } if (!openCur) { openCur = specFlags.CanReturnFrontal; if (formatIndex < 0) // format is not forced { if (IsPreArcFormat(ai)) { // if (mode.SkipSfxStub) { openCur = false; } } } } } if (openCur) { InStream = op.stream; Archive = archive; return S_OK; } } skipFrontalFormat[(unsigned)FormatIndex] = true; // if (!mode.CanReturnArc) /* if (!ErrorInfo.ThereIsTail) continue; */ if (pi.Offset == 0 && !pi.LenIsUnknown && pi.Size >= FileSize) continue; // printf("\nAdd offset = %d", (int)pi.Offset); RINOK(ReadParseItemProps(archive, ai, pi)); handlerSpec->AddItem(pi); } } // ---------- PARSER ---------- CUIntVector arc2sig; // formatIndex to signatureIndex CUIntVector sig2arc; // signatureIndex to formatIndex; { unsigned sum = 0; FOR_VECTOR (i, op.codecs->Formats) { arc2sig.Add(sum); const CObjectVector &sigs = op.codecs->Formats[i].Signatures; sum += sigs.Size(); FOR_VECTOR (k, sigs) sig2arc.Add(i); } } { const size_t kBeforeSize = 1 << 16; const size_t kAfterSize = 1 << 20; const size_t kBufSize = 1 << 22; // it must be more than kBeforeSize + kAfterSize const UInt32 kNumVals = (UInt32)1 << (kNumHashBytes * 8); CByteArr hashBuffer(kNumVals); Byte *hash = hashBuffer; memset(hash, 0xFF, kNumVals); Byte prevs[256]; memset(prevs, 0xFF, sizeof(prevs)); if (sig2arc.Size() >= 0xFF) return S_FALSE; CUIntVector difficultFormats; CBoolArr difficultBools(256); { for (unsigned i = 0; i < 256; i++) difficultBools[i] = false; } bool thereAreHandlersForSearch = false; // UInt32 maxSignatureEnd = 0; FOR_VECTOR (i, orderIndices) { int index = orderIndices[i]; if (index < 0) continue; const CArcInfoEx &ai = op.codecs->Formats[(unsigned)index]; bool isDifficult = false; // if (ai.Version < 0x91F) // we don't use parser with old DLL (before 9.31) if (!ai.NewInterface) isDifficult = true; else { if (ai.Flags_StartOpen()) isDifficult = true; FOR_VECTOR (k, ai.Signatures) { const CByteBuffer &sig = ai.Signatures[k]; /* UInt32 signatureEnd = ai.SignatureOffset + (UInt32)sig.Size(); if (maxSignatureEnd < signatureEnd) maxSignatureEnd = signatureEnd; */ if (sig.Size() < kNumHashBytes) { isDifficult = true; continue; } thereAreHandlersForSearch = true; UInt32 v = HASH_VAL(sig); unsigned sigIndex = arc2sig[(unsigned)index] + k; prevs[sigIndex] = hash[v]; hash[v] = (Byte)sigIndex; } } if (isDifficult) { difficultFormats.Add(index); difficultBools[(unsigned)index] = true; } } if (!thereAreHandlersForSearch) { // openOnlyFullArc = true; // canReturnTailArc = true; } RINOK(op.stream->Seek(0, STREAM_SEEK_SET, NULL)); CLimitedCachedInStream *limitedStreamSpec = new CLimitedCachedInStream; CMyComPtr limitedStream = limitedStreamSpec; limitedStreamSpec->SetStream(op.stream); CArchiveOpenCallback_Offset *openCallback_Offset_Spec = NULL; CMyComPtr openCallback_Offset; if (op.callback) { openCallback_Offset_Spec = new CArchiveOpenCallback_Offset; openCallback_Offset = openCallback_Offset_Spec; openCallback_Offset_Spec->Callback = op.callback; openCallback_Offset_Spec->Callback.QueryInterface(IID_IArchiveOpenVolumeCallback, &openCallback_Offset_Spec->OpenVolumeCallback); #ifndef _NO_CRYPTO openCallback_Offset_Spec->Callback.QueryInterface(IID_ICryptoGetTextPassword, &openCallback_Offset_Spec->GetTextPassword); #endif } if (op.callback) RINOK(op.callback->SetTotal(NULL, &fileSize)); CByteBuffer &byteBuffer = limitedStreamSpec->Buffer; byteBuffer.Alloc(kBufSize); UInt64 callbackPrev = 0; bool needCheckStartOpen = true; // = true, if we need to test all archives types for current pos. bool endOfFile = false; UInt64 bufPhyPos = 0; size_t bytesInBuf = 0; // UInt64 prevPos = 0; // ---------- Main Scan Loop ---------- UInt64 pos = 0; if (!mode.EachPos && handlerSpec->_items.Size() == 1) { NArchive::NParser::CParseItem &pi = handlerSpec->_items[0]; if (!pi.LenIsUnknown && pi.Offset == 0) pos = pi.Size; } for (;;) { // printf("\nPos = %d", (int)pos); UInt64 posInBuf = pos - bufPhyPos; // if (pos > ((UInt64)1 << 35)) break; if (!endOfFile) { if (bytesInBuf < kBufSize) { size_t processedSize = kBufSize - bytesInBuf; // printf("\nRead ask = %d", (unsigned)processedSize); UInt64 seekPos = bufPhyPos + bytesInBuf; RINOK(op.stream->Seek(bufPhyPos + bytesInBuf, STREAM_SEEK_SET, NULL)); RINOK(ReadStream(op.stream, byteBuffer + bytesInBuf, &processedSize)); // printf(" processed = %d", (unsigned)processedSize); if (processedSize == 0) { fileSize = seekPos; endOfFile = true; } else { bytesInBuf += processedSize; limitedStreamSpec->SetCache(processedSize, (size_t)bufPhyPos); } continue; } if (bytesInBuf < posInBuf) { UInt64 skipSize = posInBuf - bytesInBuf; if (skipSize <= kBeforeSize) { size_t keepSize = (size_t)(kBeforeSize - skipSize); // printf("\nmemmove skip = %d", (int)keepSize); memmove(byteBuffer, byteBuffer + bytesInBuf - keepSize, keepSize); bytesInBuf = keepSize; bufPhyPos = pos - keepSize; continue; } // printf("\nSkip %d", (int)(skipSize - kBeforeSize)); // RINOK(op.stream->Seek(skipSize - kBeforeSize, STREAM_SEEK_CUR, NULL)); bytesInBuf = 0; bufPhyPos = pos - kBeforeSize; continue; } if (bytesInBuf - posInBuf < kAfterSize) { size_t beg = (size_t)posInBuf - kBeforeSize; // printf("\nmemmove for after beg = %d", (int)beg); memmove(byteBuffer, byteBuffer + beg, bytesInBuf - beg); bufPhyPos += beg; bytesInBuf -= beg; continue; } } if (bytesInBuf <= (size_t)posInBuf) break; bool useOffsetCallback = false; if (openCallback_Offset) { openCallback_Offset_Spec->Files = handlerSpec->_items.Size(); openCallback_Offset_Spec->Offset = pos; useOffsetCallback = (!op.openType.CanReturnArc || handlerSpec->_items.Size() > 1); if (pos >= callbackPrev + (1 << 23)) { RINOK(openCallback_Offset_Spec->SetCompleted(NULL, NULL)); callbackPrev = pos; } } { UInt64 endPos = bufPhyPos + bytesInBuf; if (fileSize < endPos) { FileSize = fileSize; // why ???? fileSize = endPos; } } size_t availSize = bytesInBuf - (size_t)posInBuf; if (availSize < kNumHashBytes) break; size_t scanSize = availSize - ((availSize >= kAfterSize) ? kAfterSize : kNumHashBytes); { /* UInt64 scanLimit = openOnlyFullArc ? maxSignatureEnd : op.openType.ScanSize + maxSignatureEnd; */ if (!mode.CanReturnParser) { if (pos > maxStartOffset) break; UInt64 remScan = maxStartOffset - pos; if (scanSize > remScan) scanSize = (size_t)remScan; } } scanSize++; const Byte *buf = byteBuffer + (size_t)posInBuf; const Byte *bufLimit = buf + scanSize; size_t ppp = 0; if (!needCheckStartOpen) { for (; buf < bufLimit && hash[HASH_VAL(buf)] == 0xFF; buf++); ppp = buf - (byteBuffer + (size_t)posInBuf); pos += ppp; if (buf == bufLimit) continue; } UInt32 v = HASH_VAL(buf); bool nextNeedCheckStartOpen = true; unsigned i = hash[v]; unsigned indexOfDifficult = 0; // ---------- Open Loop for Current Pos ---------- bool wasOpen = false; for (;;) { unsigned index; bool isDifficult; if (needCheckStartOpen && indexOfDifficult < difficultFormats.Size()) { index = difficultFormats[indexOfDifficult++]; isDifficult = true; } else { if (i == 0xFF) break; index = sig2arc[i]; unsigned sigIndex = i - arc2sig[index]; i = prevs[i]; if (needCheckStartOpen && difficultBools[index]) continue; const CArcInfoEx &ai = op.codecs->Formats[index]; if (pos < ai.SignatureOffset) continue; /* if (openOnlyFullArc) if (pos != ai.SignatureOffset) continue; */ const CByteBuffer &sig = ai.Signatures[sigIndex]; if (ppp + sig.Size() > availSize || !TestSignature(buf, sig, sig.Size())) continue; // printf("\nSignature OK: %10S %8x %5d", (const wchar_t *)ai.Name, (int)pos, (int)(pos - prevPos)); // prevPos = pos; isDifficult = false; } const CArcInfoEx &ai = op.codecs->Formats[index]; if ((isDifficult && pos == 0) || ai.SignatureOffset == pos) { // we don't check same archive second time */ if (skipFrontalFormat[index]) continue; } UInt64 startArcPos = pos; if (!isDifficult) { if (pos < ai.SignatureOffset) continue; startArcPos = pos - ai.SignatureOffset; /* // we don't need the check for Z files if (startArcPos < handlerSpec->GetLastEnd()) continue; */ } if (ai.IsArcFunc && startArcPos >= bufPhyPos) { size_t offsetInBuf = (size_t)(startArcPos - bufPhyPos); if (offsetInBuf < bytesInBuf) { UInt32 isArcRes = ai.IsArcFunc(byteBuffer + offsetInBuf, bytesInBuf - offsetInBuf); if (isArcRes == k_IsArc_Res_NO) continue; if (isArcRes == k_IsArc_Res_NEED_MORE && endOfFile) continue; /* if (isArcRes == k_IsArc_Res_YES_LOW_PROB) { // if (pos != ai.SignatureOffset) continue; } */ } // printf("\nIsArc OK: %S", (const wchar_t *)ai.Name); } /* if (pos == 67109888) pos = pos; */ PRF(printf("\npos = %9I64d : %S", pos, (const wchar_t *)ai.Name)); bool isMainFormat = isMainFormatArr[index]; const COpenSpecFlags &specFlags = mode.GetSpec(isForced, isMainFormat, isUnknownExt); CMyComPtr archive; RINOK(PrepareToOpen(op, index, archive)); if (!archive) return E_FAIL; // OutputDebugStringW(ai.Name); UInt64 rem = fileSize - startArcPos; UInt64 arcStreamOffset = 0; if (ai.Flags_UseGlobalOffset()) { limitedStreamSpec->InitAndSeek(0, fileSize); limitedStream->Seek(startArcPos, STREAM_SEEK_SET, NULL); } else { limitedStreamSpec->InitAndSeek(startArcPos, rem); arcStreamOffset = startArcPos; } UInt64 maxCheckStartPosition = 0; if (openCallback_Offset) { openCallback_Offset_Spec->Files = handlerSpec->_items.Size(); openCallback_Offset_Spec->Offset = startArcPos; } // HRESULT result = archive->Open(limitedStream, &maxCheckStartPosition, openCallback_Offset); extractCallback_To_OpenCallback_Spec->Files = 0; extractCallback_To_OpenCallback_Spec->Offset = startArcPos; HRESULT result = OpenArchiveSpec(archive, true, limitedStream, &maxCheckStartPosition, useOffsetCallback ? (IArchiveOpenCallback *)openCallback_Offset : (IArchiveOpenCallback *)op.callback, extractCallback_To_OpenCallback); RINOK(ReadBasicProps(archive, ai.Flags_UseGlobalOffset() ? 0 : startArcPos, result)); bool isOpen = false; if (result == S_FALSE) { if (!mode.CanReturnParser) { if (formatIndex < 0 && ErrorInfo.IsArc_After_NonOpen()) { ErrorInfo.ErrorFormatIndex = index; NonOpen_ErrorInfo = ErrorInfo; // if archive was detected, we don't need additional open attempts return S_FALSE; } continue; } if (!ErrorInfo.IsArc_After_NonOpen() || !PhySizeDefined || PhySize == 0) continue; } else { isOpen = true; RINOK(result); PRF(printf(" OK ")); } // fprintf(stderr, "\n %8X %S", startArcPos, Path); // printf("\nOpen OK: %S", ai.Name); NArchive::NParser::CParseItem pi; pi.Offset = startArcPos; if (ai.Flags_UseGlobalOffset()) pi.Offset = Offset; else if (Offset != 0) return E_FAIL; UInt64 arcRem = FileSize - pi.Offset; UInt64 phySize = arcRem; bool phySizeDefined = PhySizeDefined; if (phySizeDefined) { if (pi.Offset + PhySize > FileSize) { // ErrorInfo.ThereIsTail = true; PhySize = FileSize - pi.Offset; } phySize = PhySize; } if (phySize == 0 || (UInt64)phySize > ((UInt64)1 << 63)) return E_FAIL; /* if (!ai.UseGlobalOffset) { if (phySize > arcRem) { ThereIsTail = true; phySize = arcRem; } } */ bool needScan = false; if (isOpen && !phySizeDefined) { // it's for Z format pi.LenIsUnknown = true; needScan = true; phySize = arcRem; nextNeedCheckStartOpen = false; } pi.Size = phySize; /* if (OkPhySize_Defined) pi.OkSize = OkPhySize; */ pi.NormalizeOffset(); // printf(" phySize = %8d", (unsigned)phySize); /* if (needSkipFullArc) if (pi.Offset == 0 && phySizeDefined && pi.Size >= fileSize) continue; */ if (pi.Offset == 0 && !pi.LenIsUnknown && pi.Size >= FileSize) { // it's possible for dmg archives if (!mode.CanReturnArc) continue; } if (mode.EachPos) pos++; else if (needScan) { pos++; /* if (!OkPhySize_Defined) pos++; else pos = pi.Offset + pi.OkSize; */ } else pos = pi.Offset + pi.Size; RINOK(ReadParseItemProps(archive, ai, pi)); if (pi.Offset < startArcPos && !mode.EachPos /* && phySizeDefined */) { /* It's for DMG format. This code deletes all previous items that are included to current item */ while (!handlerSpec->_items.IsEmpty()) { { const NArchive::NParser::CParseItem &back = handlerSpec->_items.Back(); if (back.Offset < pi.Offset) break; if (back.Offset + back.Size > pi.Offset + pi.Size) break; } handlerSpec->_items.DeleteBack(); } } if (isOpen && mode.CanReturnArc && phySizeDefined) { // if (pi.Offset + pi.Size >= fileSize) bool openCur = false; bool thereIsTail = ErrorInfo.ThereIsTail; if (thereIsTail && mode.ZerosTailIsAllowed) { RINOK(CheckZerosTail(op, arcStreamOffset + Offset + PhySize)); if (ErrorInfo.IgnoreTail) thereIsTail = false; } if (pi.Offset != 0) { if (!pi.IsNotArcType) if (thereIsTail) openCur = specFlags.CanReturnMid; else openCur = specFlags.CanReturnTail; } else { if (!thereIsTail) openCur = true; else openCur = specFlags.CanReturnFrontal; if (formatIndex >= -2) openCur = true; } if (formatIndex < 0 && pi.IsSelfExe /* && mode.SkipSfxStub */) openCur = false; // We open file as SFX, if there is front archive or first archive is "Self Executable" if (!openCur && !pi.IsSelfExe && !thereIsTail && (!pi.IsNotArcType || pi.Offset == 0)) { if (handlerSpec->_items.IsEmpty()) { if (specFlags.CanReturnTail) openCur = true; } else if (handlerSpec->_items.Size() == 1) { if (handlerSpec->_items[0].IsSelfExe) { if (mode.SpecUnknownExt.CanReturnTail) openCur = true; } } } if (openCur) { InStream = op.stream; Archive = archive; FormatIndex = index; ArcStreamOffset = arcStreamOffset; return S_OK; } } /* if (openOnlyFullArc) { ErrorInfo.ClearErrors(); return S_FALSE; } */ pi.FormatIndex = index; // printf("\nAdd offset = %d", (int)pi.Offset); handlerSpec->AddItem(pi); wasOpen = true; break; } // ---------- End of Open Loop for Current Pos ---------- if (!wasOpen) pos++; needCheckStartOpen = (nextNeedCheckStartOpen && wasOpen); } // ---------- End of Main Scan Loop ---------- /* if (handlerSpec->_items.Size() == 1) { const NArchive::NParser::CParseItem &pi = handlerSpec->_items[0]; if (pi.Size == fileSize && pi.Offset == 0) { Archive = archive; FormatIndex2 = pi.FormatIndex; return S_OK; } } */ if (mode.CanReturnParser) { bool returnParser = (handlerSpec->_items.Size() == 1); // it's possible if fileSize was not correct at start of parsing handlerSpec->AddUnknownItem(fileSize); if (handlerSpec->_items.Size() == 0) return S_FALSE; if (returnParser || handlerSpec->_items.Size() != 1) { // return S_FALSE; handlerSpec->_stream = op.stream; Archive = handler; ErrorInfo.ClearErrors(); IsParseArc = true; FormatIndex = -1; // It's parser Offset = 0; return S_OK; } } } #endif if (!Archive) return S_FALSE; return S_OK; } HRESULT CArc::OpenStream(const COpenOptions &op) { RINOK(OpenStream2(op)); // PrintNumber("op.formatIndex 3", op.formatIndex); if (Archive) { GetRawProps.Release(); GetRootProps.Release(); Archive->QueryInterface(IID_IArchiveGetRawProps, (void **)&GetRawProps); Archive->QueryInterface(IID_IArchiveGetRootProps, (void **)&GetRootProps); RINOK(Archive_GetArcBoolProp(Archive, kpidIsTree, IsTree)); RINOK(Archive_GetArcBoolProp(Archive, kpidIsDeleted, Ask_Deleted)); RINOK(Archive_GetArcBoolProp(Archive, kpidIsAltStream, Ask_AltStream)); RINOK(Archive_GetArcBoolProp(Archive, kpidIsAux, Ask_Aux)); RINOK(Archive_GetArcBoolProp(Archive, kpidINode, Ask_INode)); RINOK(Archive_GetArcBoolProp(Archive, kpidReadOnly, IsReadOnly)); const UString fileName = ExtractFileNameFromPath(Path); UString extension; { int dotPos = fileName.ReverseFind_Dot(); if (dotPos >= 0) extension = fileName.Ptr(dotPos + 1); } DefaultName.Empty(); if (FormatIndex >= 0) { const CArcInfoEx &ai = op.codecs->Formats[FormatIndex]; if (ai.Exts.Size() == 0) DefaultName = GetDefaultName2(fileName, UString(), UString()); else { int subExtIndex = ai.FindExtension(extension); if (subExtIndex < 0) subExtIndex = 0; const CArcExtInfo &extInfo = ai.Exts[subExtIndex]; DefaultName = GetDefaultName2(fileName, extInfo.Ext, extInfo.AddExt); } } } return S_OK; } #ifdef _SFX #ifdef _WIN32 #define k_ExeExt ".exe" static const unsigned k_ExeExt_Len = 4; #else #define k_ExeExt "" static const unsigned k_ExeExt_Len = 0; #endif #endif HRESULT CArc::OpenStreamOrFile(COpenOptions &op) { CMyComPtr fileStream; CMyComPtr seqStream; CInFileStream *fileStreamSpec = NULL; if (op.stdInMode) { seqStream = new CStdInFileStream; op.seqStream = seqStream; } else if (!op.stream) { fileStreamSpec = new CInFileStream; fileStream = fileStreamSpec; Path = filePath; if (!fileStreamSpec->Open(us2fs(Path))) { return GetLastError(); } op.stream = fileStream; #ifdef _SFX IgnoreSplit = true; #endif } /* if (callback) { UInt64 fileSize; RINOK(op.stream->Seek(0, STREAM_SEEK_END, &fileSize)); RINOK(op.callback->SetTotal(NULL, &fileSize)) } */ HRESULT res = OpenStream(op); IgnoreSplit = false; #ifdef _SFX if (res != S_FALSE || !fileStreamSpec || !op.callbackSpec || NonOpen_ErrorInfo.IsArc_After_NonOpen()) return res; { if (filePath.Len() > k_ExeExt_Len && StringsAreEqualNoCase_Ascii(filePath.RightPtr(k_ExeExt_Len), k_ExeExt)) { const UString path2 = filePath.Left(filePath.Len() - k_ExeExt_Len); FOR_VECTOR (i, op.codecs->Formats) { const CArcInfoEx &ai = op.codecs->Formats[i]; if (ai.IsSplit()) continue; UString path3 = path2; path3 += '.'; path3 += ai.GetMainExt(); // "7z" for SFX. Path = path3; Path += ".001"; bool isOk = op.callbackSpec->SetSecondFileInfo(us2fs(Path)); if (!isOk) { Path = path3; isOk = op.callbackSpec->SetSecondFileInfo(us2fs(Path)); } if (isOk) { if (fileStreamSpec->Open(us2fs(Path))) { op.stream = fileStream; NonOpen_ErrorInfo.ClearErrors_Full(); if (OpenStream(op) == S_OK) return S_OK; } } } } } #endif return res; } void CArchiveLink::KeepModeForNextOpen() { for (unsigned i = Arcs.Size(); i != 0;) { i--; CMyComPtr keep; Arcs[i].Archive->QueryInterface(IID_IArchiveKeepModeForNextOpen, (void **)&keep); if (keep) keep->KeepModeForNextOpen(); } } HRESULT CArchiveLink::Close() { for (unsigned i = Arcs.Size(); i != 0;) { i--; RINOK(Arcs[i].Close()); } IsOpen = false; // ErrorsText.Empty(); return S_OK; } void CArchiveLink::Release() { // NonOpenErrorFormatIndex = -1; NonOpen_ErrorInfo.ClearErrors(); NonOpen_ArcPath.Empty(); while (!Arcs.IsEmpty()) Arcs.DeleteBack(); } /* void CArchiveLink::Set_ErrorsText() { FOR_VECTOR(i, Arcs) { const CArc &arc = Arcs[i]; if (!arc.ErrorFlagsText.IsEmpty()) { if (!ErrorsText.IsEmpty()) ErrorsText.Add_LF(); ErrorsText += GetUnicodeString(arc.ErrorFlagsText); } if (!arc.ErrorMessage.IsEmpty()) { if (!ErrorsText.IsEmpty()) ErrorsText.Add_LF(); ErrorsText += arc.ErrorMessage; } if (!arc.WarningMessage.IsEmpty()) { if (!ErrorsText.IsEmpty()) ErrorsText.Add_LF(); ErrorsText += arc.WarningMessage; } } } */ HRESULT CArchiveLink::Open(COpenOptions &op) { Release(); if (op.types->Size() >= 32) return E_NOTIMPL; HRESULT resSpec; for (;;) { resSpec = S_OK; op.openType = COpenType(); if (op.types->Size() >= 1) { COpenType latest; if (Arcs.Size() < op.types->Size()) latest = (*op.types)[op.types->Size() - Arcs.Size() - 1]; else { latest = (*op.types)[0]; if (!latest.Recursive) break; } op.openType = latest; } else if (Arcs.Size() >= 32) break; /* op.formatIndex = -1; if (op.types->Size() >= 1) { int latest; if (Arcs.Size() < op.types->Size()) latest = (*op.types)[op.types->Size() - Arcs.Size() - 1]; else { latest = (*op.types)[0]; if (latest != -2 && latest != -3) break; } if (latest >= 0) op.formatIndex = latest; else if (latest == -1 || latest == -2) { // default } else if (latest == -3) op.formatIndex = -2; else op.formatIndex = latest + 2; } else if (Arcs.Size() >= 32) break; */ if (Arcs.IsEmpty()) { CArc arc; arc.filePath = op.filePath; arc.Path = op.filePath; arc.SubfileIndex = (UInt32)(Int32)-1; HRESULT result = arc.OpenStreamOrFile(op); if (result != S_OK) { if (result == S_FALSE) { NonOpen_ErrorInfo = arc.NonOpen_ErrorInfo; // NonOpenErrorFormatIndex = arc.ErrorFormatIndex; NonOpen_ArcPath = arc.Path; } return result; } Arcs.Add(arc); continue; } // PrintNumber("op.formatIndex 11", op.formatIndex); const CArc &arc = Arcs.Back(); if (op.types->Size() > Arcs.Size()) resSpec = E_NOTIMPL; UInt32 mainSubfile; { NCOM::CPropVariant prop; RINOK(arc.Archive->GetArchiveProperty(kpidMainSubfile, &prop)); if (prop.vt == VT_UI4) mainSubfile = prop.ulVal; else break; UInt32 numItems; RINOK(arc.Archive->GetNumberOfItems(&numItems)); if (mainSubfile >= numItems) break; } CMyComPtr getStream; if (arc.Archive->QueryInterface(IID_IInArchiveGetStream, (void **)&getStream) != S_OK || !getStream) break; CMyComPtr subSeqStream; if (getStream->GetStream(mainSubfile, &subSeqStream) != S_OK || !subSeqStream) break; CMyComPtr subStream; if (subSeqStream.QueryInterface(IID_IInStream, &subStream) != S_OK || !subStream) break; CArc arc2; RINOK(arc.GetItemPath(mainSubfile, arc2.Path)); bool zerosTailIsAllowed; RINOK(Archive_GetItemBoolProp(arc.Archive, mainSubfile, kpidZerosTailIsAllowed, zerosTailIsAllowed)); if (op.callback) { CMyComPtr setSubArchiveName; op.callback->QueryInterface(IID_IArchiveOpenSetSubArchiveName, (void **)&setSubArchiveName); if (setSubArchiveName) setSubArchiveName->SetSubArchiveName(arc2.Path); } arc2.SubfileIndex = mainSubfile; // CIntVector incl; CIntVector excl; COpenOptions op2; #ifndef _SFX op2.props = op.props; #endif op2.codecs = op.codecs; // op2.types = &incl; op2.openType = op.openType; op2.openType.ZerosTailIsAllowed = zerosTailIsAllowed; op2.excludedFormats = ! op2.stdInMode = false; op2.stream = subStream; op2.filePath = arc2.Path; op2.callback = op.callback; op2.callbackSpec = op.callbackSpec; HRESULT result = arc2.OpenStream(op2); resSpec = (op.types->Size() == 0 ? S_OK : S_FALSE); if (result == S_FALSE) { NonOpen_ErrorInfo = arc2.ErrorInfo; NonOpen_ArcPath = arc2.Path; break; } RINOK(result); RINOK(arc.GetItemMTime(mainSubfile, arc2.MTime, arc2.MTimeDefined)); Arcs.Add(arc2); } IsOpen = !Arcs.IsEmpty(); return resSpec; } HRESULT CArchiveLink::Open2(COpenOptions &op, IOpenCallbackUI *callbackUI) { VolumesSize = 0; COpenCallbackImp *openCallbackSpec = new COpenCallbackImp; CMyComPtr callback = openCallbackSpec; openCallbackSpec->Callback = callbackUI; FString prefix, name; if (!op.stream && !op.stdInMode) { NFile::NDir::GetFullPathAndSplit(us2fs(op.filePath), prefix, name); openCallbackSpec->Init(prefix, name); } else { openCallbackSpec->SetSubArchiveName(op.filePath); } op.callback = callback; op.callbackSpec = openCallbackSpec; HRESULT res = Open(op); PasswordWasAsked = openCallbackSpec->PasswordWasAsked; // Password = openCallbackSpec->Password; RINOK(res); // VolumePaths.Add(fs2us(prefix + name)); FOR_VECTOR (i, openCallbackSpec->FileNames_WasUsed) { if (openCallbackSpec->FileNames_WasUsed[i]) { VolumePaths.Add(fs2us(prefix) + openCallbackSpec->FileNames[i]); VolumesSize += openCallbackSpec->FileSizes[i]; } } // VolumesSize = openCallbackSpec->TotalSize; return S_OK; } HRESULT CArc::ReOpen(const COpenOptions &op) { ErrorInfo.ClearErrors(); ErrorInfo.ErrorFormatIndex = -1; UInt64 fileSize = 0; if (op.stream) { RINOK(op.stream->Seek(0, STREAM_SEEK_END, &fileSize)); RINOK(op.stream->Seek(0, STREAM_SEEK_SET, NULL)); } FileSize = fileSize; CMyComPtr stream2; Int64 globalOffset = GetGlobalOffset(); if (globalOffset <= 0) stream2 = op.stream; else { CTailInStream *tailStreamSpec = new CTailInStream; stream2 = tailStreamSpec; tailStreamSpec->Stream = op.stream; tailStreamSpec->Offset = globalOffset; tailStreamSpec->Init(); RINOK(tailStreamSpec->SeekToStart()); } // There are archives with embedded STUBs (like ZIP), so we must support signature scanning // But for another archives we can use 0 here. So the code can be fixed !!! UInt64 maxStartPosition = kMaxCheckStartPosition; HRESULT res = Archive->Open(stream2, &maxStartPosition, op.callback); if (res == S_OK) { RINOK(ReadBasicProps(Archive, globalOffset, res)); ArcStreamOffset = globalOffset; if (ArcStreamOffset != 0) InStream = op.stream; } return res; } HRESULT CArchiveLink::Open3(COpenOptions &op, IOpenCallbackUI *callbackUI) { HRESULT res = Open2(op, callbackUI); if (callbackUI) { RINOK(callbackUI->Open_Finished()); } return res; } HRESULT CArchiveLink::ReOpen(COpenOptions &op) { if (Arcs.Size() > 1) return E_NOTIMPL; CObjectVector inc; CIntVector excl; op.types = &inc; op.excludedFormats = ! op.stdInMode = false; op.stream = NULL; if (Arcs.Size() == 0) // ??? return Open2(op, NULL); COpenCallbackImp *openCallbackSpec = new COpenCallbackImp; CMyComPtr openCallbackNew = openCallbackSpec; openCallbackSpec->Callback = NULL; openCallbackSpec->ReOpenCallback = op.callback; { FString dirPrefix, fileName; NFile::NDir::GetFullPathAndSplit(us2fs(op.filePath), dirPrefix, fileName); openCallbackSpec->Init(dirPrefix, fileName); } CInFileStream *fileStreamSpec = new CInFileStream; CMyComPtr stream(fileStreamSpec); if (!fileStreamSpec->Open(us2fs(op.filePath))) return GetLastError(); op.stream = stream; CArc &arc = Arcs[0]; HRESULT res = arc.ReOpen(op); PasswordWasAsked = openCallbackSpec->PasswordWasAsked; // Password = ; IsOpen = (res == S_OK); return res; } #ifndef _SFX bool ParseComplexSize(const wchar_t *s, UInt64 &result) { result = 0; const wchar_t *end; UInt64 number = ConvertStringToUInt64(s, &end); if (end == s) return false; if (*end == 0) { result = number; return true; } if (end[1] != 0) return false; unsigned numBits; switch (MyCharLower_Ascii(*end)) { case 'b': result = number; return true; case 'k': numBits = 10; break; case 'm': numBits = 20; break; case 'g': numBits = 30; break; case 't': numBits = 40; break; default: return false; } if (number >= ((UInt64)1 << (64 - numBits))) return false; result = number << numBits; return true; } static bool ParseTypeParams(const UString &s, COpenType &type) { if (s[0] == 0) return true; if (s[1] == 0) { switch ((unsigned)(Byte)s[0]) { case 'e': type.EachPos = true; return true; case 'a': type.CanReturnArc = true; return true; case 'r': type.Recursive = true; return true; } return false; } if (s[0] == 's') { UInt64 result; if (!ParseComplexSize(s.Ptr(1), result)) return false; type.MaxStartOffset = result; type.MaxStartOffset_Defined = true; return true; } return false; } bool ParseType(CCodecs &codecs, const UString &s, COpenType &type) { int pos2 = s.Find(L':'); { UString name; if (pos2 < 0) { name = s; pos2 = s.Len(); } else { name = s.Left(pos2); pos2++; } int index = codecs.FindFormatForArchiveType(name); type.Recursive = false; if (index < 0) { if (name[0] == '*') { if (name[1] != 0) return false; } else if (name[0] == '#') { if (name[1] != 0) return false; type.CanReturnArc = false; type.CanReturnParser = true; } else return false; } type.FormatIndex = index; } for (unsigned i = pos2; i < s.Len();) { int next = s.Find(L':', i); if (next < 0) next = s.Len(); const UString name = s.Mid(i, next - i); if (name.IsEmpty()) return false; if (!ParseTypeParams(name, type)) return false; i = next + 1; } return true; } bool ParseOpenTypes(CCodecs &codecs, const UString &s, CObjectVector &types) { types.Clear(); for (unsigned pos = 0; pos < s.Len();) { int pos2 = s.Find(L'.', pos); if (pos2 < 0) pos2 = s.Len(); UString name = s.Mid(pos, pos2 - pos); if (name.IsEmpty()) return false; COpenType type; if (!ParseType(codecs, name, type)) return false; types.Add(type); pos = pos2 + 1; } return true; } #endif /** * \file dnn/src/common/conv_bias.cpp * MegEngine is Licensed under the Apache License, Version 2.0 (the "License") * * Copyright (c) 2014-2020 Megvii Inc. All rights reserved. * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. */ #include "src/common/conv_bias.h" #include "megdnn/oprs/nn.h" #include "src/common/utils.h" #include "src/common/opr_delegate.h" namespace megdnn { void ConvBiasForward::deduce_dtype(DType src, DType filter, DType /* bias */, DType /* z */, DType& dst) { check_or_deduce_dtype_fwd(src, filter, dst); } void ConvBiasForward::deduce_layout(const TensorLayout& src, const TensorLayout& filter, const TensorLayout& /* bias */, const TensorLayout& /* z */, TensorLayout& dst) { deduce_layout_fwd(src, filter, dst); } ConvBiasForward::CanonizedFilterMeta ConvBiasForward::check_exec( const TensorLayout& src, const TensorLayout& filter, const TensorLayout& bias, const TensorLayout& z, const TensorLayout& dst, size_t workspace_in_bytes, const PreprocessedFilter* preprocessed_filter) { if ((param().format == param::ConvBias::Format::NCHW_WINOGRAD || param().format == param::ConvBias::Format::NCHW88_WINOGRAD || param().format == param::ConvBias::Format::NCHW44_WINOGRAD) && src.dtype.category() == DTypeCategory::QUANTIZED) { megdnn_assert(filter.dtype.enumv() == DTypeEnum::QuantizedS16 || //!int8 winogradf23_44 using float,QuantizedS32 take the scale filter.dtype.enumv() == DTypeEnum::QuantizedS32); megdnn_assert(src.dtype.enumv() == DTypeEnum::QuantizedS8 || src.dtype.enumv() == DTypeEnum::Quantized8Asymm); } else { megdnn_assert(src.dtype.enumv() == filter.dtype.enumv()); } if (src.dtype.enumv() == DTypeEnum::QuantizedS8) { float scale_src = src.dtype.param().scale; float scale_filter = 0.f; if (param().format == param::ConvBias::Format::NCHW_WINOGRAD || param().format == param::ConvBias::Format::NCHW88_WINOGRAD || param().format == param::ConvBias::Format::NCHW44_WINOGRAD) { if (filter.dtype.enumv() == DTypeEnum::QuantizedS32) { //!int8 winogradf23_44 using float,QuantizedS32 take the scale scale_filter = filter.dtype.param().scale; } else { scale_filter = filter.dtype.param().scale; } } else { scale_filter = filter.dtype.param().scale; } float scale_bias = bias.dtype.param().scale; megdnn_assert(std::abs(scale_src * scale_filter - scale_bias) < 1e-6, "scale_src: %f scale_filter: %f scale_bias: %f", scale_src, scale_filter, scale_bias); } else if (src.dtype.enumv() == DTypeEnum::Quantized8Asymm) { float scale_src = src.dtype.param().scale; float scale_filter = 0.f; if (param().format == param::ConvBias::Format::NCHW_WINOGRAD || param().format == param::ConvBias::Format::NCHW88_WINOGRAD || param().format == param::ConvBias::Format::NCHW44_WINOGRAD) { scale_filter = filter.dtype.param().scale; } else { scale_filter = filter.dtype.param().scale; } float scale_bias = bias.dtype.param().scale; megdnn_assert(std::abs(scale_src * scale_filter - scale_bias) < 1e-6, "scale_src: %f scale_filter: %f scale_bias: %f", scale_src, scale_filter, scale_bias); } auto ret = check_layout_fwd(src, filter, dst); megdnn_assert_contiguous(bias); auto required_workspace_in_bytes = get_workspace_in_bytes( src, filter, bias, z, dst, preprocessed_filter); megdnn_assert(workspace_in_bytes >= required_workspace_in_bytes, "worksapce have size of %zu, but need %zu", workspace_in_bytes, required_workspace_in_bytes); if (bias.ndim != 0) { //! bias.layout == dst.layout failed, no assert information auto check_eq = [](const TensorLayout& bias, const TensorLayout& dst) { if (dst.dtype.category() == DTypeCategory::QUANTIZED) { return bias.eq_shape(dst); } else { return bias.eq_layout(dst); } }; if (check_eq(bias, dst)) return ret; if (param().format == param::ConvBias::Format::NCHW || param().format == param::ConvBias::Format::NCHW_WINOGRAD) { megdnn_assert(bias.shape[0] == 1); megdnn_assert(bias.shape[1] == dst.shape[1], "bias:%s, dst:%s", bias.to_string().c_str(), dst.to_string().c_str()); megdnn_assert(bias.shape[2] == 1); megdnn_assert(bias.shape[3] == 1); } else if (param().format == param::ConvBias::Format::NHWC) { megdnn_assert(bias.shape[0] == 1); megdnn_assert(bias.shape[1] == 1); megdnn_assert(bias.shape[2] == 1); megdnn_assert(bias.shape[3] == dst.shape[3], "bias:%s, dst:%s", bias.to_string().c_str(), dst.to_string().c_str()); } else if (param().format == param::ConvBias::Format::NCHW4 || param().format == param::ConvBias::Format::NCHW44 || param().format == param::ConvBias::Format::NCHW44_DOT || param().format == param::ConvBias::Format::NCHW44_WINOGRAD) { megdnn_assert(bias.shape[0] == 1); megdnn_assert(bias.shape[1] == dst.shape[1], "bias:%s, dst:%s", bias.to_string().c_str(), dst.to_string().c_str()); megdnn_assert(bias.shape[2] == 1); megdnn_assert(bias.shape[3] == 1); megdnn_assert(bias.shape[4] == 4); } else if (param().format == param::ConvBias::Format::NCHW8 || param().format == param::ConvBias::Format::NCHW88 || param().format == param::ConvBias::Format::NCHW88_WINOGRAD) { megdnn_assert(bias.shape[0] == 1); megdnn_assert(bias.shape[1] == dst.shape[1], "bias:%s, dst:%s", bias.to_string().c_str(), dst.to_string().c_str()); megdnn_assert(bias.shape[2] == 1); megdnn_assert(bias.shape[3] == 1); megdnn_assert(bias.shape[4] == 8); } else if (param().format == param::ConvBias::Format::NCHW32) { megdnn_assert(bias.shape[0] == 1); megdnn_assert(bias.shape[1] == dst.shape[1], "bias:%s, dst:%s", bias.to_string().c_str(), dst.to_string().c_str()); megdnn_assert(bias.shape[2] == 1); megdnn_assert(bias.shape[3] == 1); megdnn_assert(bias.shape[4] == 32); } else if (param().format == param::ConvBias::Format::CHWN4) { megdnn_assert(bias.shape[0] == dst.shape[0], "bias:%s, dst:%s", bias.to_string().c_str(), dst.to_string().c_str()); megdnn_assert(bias.shape[1] == 1); megdnn_assert(bias.shape[2] == 1); megdnn_assert(bias.shape[3] == 1); megdnn_assert(bias.shape[4] == 4); } else { megdnn_assert(param().format == param::ConvBias::Format::NHWCD4); megdnn_assert(bias.shape[0] == 1); megdnn_assert(bias.shape[1] == 1); megdnn_assert(bias.shape[2] == dst.shape[2], "bias:%s, dst:%s", bias.to_string().c_str(), dst.to_string().c_str()); megdnn_assert(bias.shape[3] == 1); megdnn_assert(bias.shape[4] == 4); } } if (z.ndim != 0) { megdnn_assert(param().format != param::ConvBias::Format::NCHW_WINOGRAD); megdnn_assert(param().format != param::ConvBias::Format::NCHW88_WINOGRAD); megdnn_assert(param().format != param::ConvBias::Format::NCHW44_WINOGRAD); megdnn_assert(z.dtype.enumv() == dst.dtype.enumv()); megdnn_assert(z.eq_shape(dst)); } return ret; } /*! * \brief deduce the origin filter layout and param after winograd transformed */ void ConvBiasForward::deduce_winograd_origin_layout_and_param( const Param::Format format, const size_t output_block_size, const TensorLayout& src_layout, const TensorLayout& winograd_filter_layout, TensorLayout& origin_layout, Param& origin_param) { if (format == megdnn::param::ConvBias::Format::NCHW88_WINOGRAD || format == megdnn::param::ConvBias::Format::NCHW44_WINOGRAD || format == megdnn::param::ConvBias::Format::NCHW_WINOGRAD) { //! change NCHWxx_WINOGRAD to NCHWxx size_t OC = 0; size_t IC = 0; size_t GROUP = 1; size_t FH = winograd_filter_layout[1] - output_block_size + 1; //! {alpha, alpha, IC, OC} if (winograd_filter_layout.ndim == 4) { OC = winograd_filter_layout[3]; IC = winograd_filter_layout[2]; } //! {group, alpha, alpha, IC, OC} else if (winograd_filter_layout.ndim == 5) { OC = winograd_filter_layout[4]; IC = winograd_filter_layout[3]; GROUP = winograd_filter_layout[0]; } //! {alpha, alpha, OC/f, IC/f, f, f} else if (winograd_filter_layout.ndim == 6) { OC = winograd_filter_layout[2] * winograd_filter_layout[5]; IC = winograd_filter_layout[3] * winograd_filter_layout[4]; } //! {group, alpha, alpha, OC/f, IC/f, f, f} else if (winograd_filter_layout.ndim == 7) { OC = winograd_filter_layout[3] * winograd_filter_layout[6]; IC = winograd_filter_layout[4] * winograd_filter_layout[5]; GROUP = winograd_filter_layout[0]; } auto origin_data_type = winograd_filter_layout.dtype; if (src_layout.dtype.enumv() == DTypeEnum::QuantizedS8) { if (origin_data_type.enumv() == DTypeEnum::QuantizedS16) { float scale = origin_data_type.param().scale; origin_data_type = megdnn::dtype::QuantizedS8(scale); } else { //! In order to braing the sacle of filter, the transformed //! qint8 winograd filter computing with float dtype is Qint32 megdnn_assert(origin_data_type.enumv() == DTypeEnum::QuantizedS32); float scale = origin_data_type.param().scale; origin_data_type = megdnn::dtype::QuantizedS8(scale); } } if (GROUP == 1) { if (format == megdnn::param::ConvBias::Format::NCHW_WINOGRAD) { origin_layout = TensorLayout({OC, IC, FH, FH}, origin_data_type); } else if (format == megdnn::param::ConvBias::Format::NCHW44_WINOGRAD) { origin_layout = TensorLayout({OC / 4, IC / 4, FH, FH, 4, 4}, origin_data_type); } else { megdnn_assert(format == megdnn::param::ConvBias::Format::NCHW88_WINOGRAD); origin_layout = TensorLayout({OC / 8, IC / 8, FH, FH, 8, 8}, origin_data_type); } } else { if (format == megdnn::param::ConvBias::Format::NCHW_WINOGRAD) { origin_layout = TensorLayout({GROUP, OC, IC, FH, FH}, origin_data_type); } else if (format == megdnn::param::ConvBias::Format::NCHW44_WINOGRAD) { origin_layout = TensorLayout({GROUP, OC / 4, IC / 4, FH, FH, 4, 4}, origin_data_type); } else { megdnn_assert(format == megdnn::param::ConvBias::Format::NCHW88_WINOGRAD); origin_layout = TensorLayout({GROUP, OC / 8, IC / 8, FH, FH, 8, 8}, origin_data_type); } } origin_param.output_block_size = 0; if (format == megdnn::param::ConvBias::Format::NCHW_WINOGRAD) { origin_param.format = megdnn::param::ConvBias::Format::NCHW; } else if (format == megdnn::param::ConvBias::Format::NCHW44_WINOGRAD) { origin_param.format = megdnn::param::ConvBias::Format::NCHW44; } else { megdnn_assert(format == megdnn::param::ConvBias::Format::NCHW88_WINOGRAD); origin_param.format = megdnn::param::ConvBias::Format::NCHW88; } } } template struct NCHWParamTrait; template struct NCHW44ParamTrait; std::string ConvBias::WinogradParam::to_string() const { return ssprintf("%u:%u:%u", channel_block_size, output_block_size, tile_size); } template std::string ConvBias::algo_name(const std::string& base, const T& p, param::ConvBias::Format format) { if (format == param::ConvBias::Format::NCHW) { return ssprintf("%s:%s:%s", NCHWParamTrait::category.c_str(), base.c_str(), p.to_string().c_str()); } else if (format == param::ConvBias::Format::NCHW44) { return ssprintf("%s:%s:%s", NCHW44ParamTrait::category.c_str(), base.c_str(), p.to_string().c_str()); } megdnn_throw("Invalid format"); return ""; } #define FOREACH_CONV_BIAS_PARAM(cb) \ cb(WinogradParam) cb(DirectParam) cb(MatmulParam) cb(DefaultParam) #define cb(pt) \ template <> \ struct NCHWParamTrait { \ static const std::string category; \ }; \ template <> \ struct NCHW44ParamTrait { \ static const std::string category; \ }; FOREACH_CONV_BIAS_PARAM(cb) #undef cb #define cb(pt, ct) \ const std::string NCHWParamTrait::category = ct; \ const std::string NCHW44ParamTrait::category = ct cb(DirectParam, "DIRECT"); cb(MatmulParam, "MATMUL"); cb(DefaultParam, "DEFAULT"); #undef cb const std::string NCHWParamTrait::category = "WINOGRAD"; const std::string NCHW44ParamTrait::category = "WINOGRAD_NCHW44"; #define cb(t) \ template std::string ConvBias::algo_name( \ const std::string& base, const ConvBias::t& p, \ param::ConvBias::Format format); FOREACH_CONV_BIAS_PARAM(cb) #undef cb ConvBias::WinogradParam ConvBias::parse_winograd_name( const std::string& algo_name) { ConvBias::WinogradParam ret = INVALID_WINOGRAD_PARAM; char base[128]; char name[128]; auto parse = [&](const std::string& algo_name, const std::string& pre) -> auto { memset(name, 0, 128); sscanf(algo_name.c_str(), "%[^:]:%[^:]:%u:%u:%u", name, base, &(ret.channel_block_size), &(ret.output_block_size), &(ret.tile_size)); if (strcmp(name, pre.c_str())) { ret = INVALID_WINOGRAD_PARAM; return false; } if (ret.tile_size == 0 || ret.output_block_size == 0 || ret.channel_block_size == 0) { ret = INVALID_WINOGRAD_PARAM; return false; } return true; }; if (parse(algo_name, "WINOGRAD_NCHW44")) { return ret; } else { parse(algo_name, "WINOGRAD"); return ret; } } constexpr ConvBias::WinogradParam ConvBias::INVALID_WINOGRAD_PARAM; void handle_bias_and_nonlinear(Handle* handle, param::ConvBias args, const TensorND* conv_dst_tensor, const TensorND* dst_tensor, const TensorND* bias_tensor) { using NonlineMode = param::ConvBias::NonlineMode; switch (args.nonlineMode) { #define cb(_mode) \ case NonlineMode::_mode: { \ if (conv_dst_tensor->layout.dtype.category() != \ DTypeCategory::QUANTIZED) { \ auto nonlinear = handle->create_operator(); \ if (bias_tensor->layout.ndim > 0) { \ nonlinear->param().mode = \ Elemwise::Param::Mode::FUSE_ADD_##_mode; \ nonlinear->exec({*conv_dst_tensor, *bias_tensor}, \ *dst_tensor); \ } else { \ nonlinear->param().mode = Elemwise::Param::Mode::_mode; \ nonlinear->exec({*conv_dst_tensor}, *dst_tensor); \ } \ } else { \ auto nonlinear = handle->create_operator(); \ if (bias_tensor->layout.ndim > 0) { \ nonlinear->param().mode = \ ElemwiseMultiType::Param::Mode::QFUSE_ADD_##_mode; \ nonlinear->exec({*conv_dst_tensor, *bias_tensor}, \ *dst_tensor); \ } else { \ nonlinear->param().mode = \ ElemwiseMultiType::Param::Mode::Q##_mode; \ nonlinear->exec({*conv_dst_tensor}, *dst_tensor); \ } \ } \ break; \ } cb(RELU); cb(H_SWISH); #undef cb case NonlineMode::SIGMOID: { megdnn_assert(conv_dst_tensor->layout.dtype.category() != DTypeCategory::QUANTIZED); auto nonlinear = handle->create_operator(); if (bias_tensor->layout.ndim > 0) { nonlinear->param().mode = Elemwise::Param::Mode::FUSE_ADD_SIGMOID; nonlinear->exec({*conv_dst_tensor, *bias_tensor}, *conv_dst_tensor); } else { nonlinear->param().mode = Elemwise::Param::Mode::SIGMOID; nonlinear->exec({*conv_dst_tensor}, *conv_dst_tensor); } break; } case NonlineMode::IDENTITY: { if (bias_tensor->layout.ndim > 0) { if (dst_tensor->layout.dtype.category() == DTypeCategory::QUANTIZED) { auto nonlinear = handle->create_operator(); nonlinear->param().mode = ElemwiseMultiType::Param::Mode::QADD; nonlinear->exec({*conv_dst_tensor, *bias_tensor}, *dst_tensor); } else { auto nonlinear = handle->create_operator(); nonlinear->param().mode = Elemwise::Param::Mode::ADD; nonlinear->exec({*conv_dst_tensor, *bias_tensor}, *dst_tensor); } } else { if (conv_dst_tensor->layout.dtype != dst_tensor->layout.dtype) { handle->create_operator()->exec({*conv_dst_tensor}, *dst_tensor); } } break; } default: megdnn_assert(false); } } } // namespace megdnn // vim: syntax=cpp.doxygen vives-projectweek-2022/Lannooleaf #pragma once #include #include namespace Lannooleaf::baseclasses { class AddressedCommunicator { public: AddressedCommunicator () {}; ~AddressedCommunicator() {}; public: virtual void send_data(uint8_t slave_address, const uint8_t* src, size_t len) = 0; virtual void receive_data(uint8_t slave_address, uint8_t* dest, size_t len) = 0; }; } 0 /*! * \autor captainpeng * \date 2019-1-13 * \update 2019-1-13 * \version 1.0 * \copyright */ #ifndef myStd_hpp #define myStd_hpp #include #include #include #include #include #include #include"nil.hpp" #include"typeLib.hpp" #include"digitLib.hpp" #include"intLib.hpp" #include"charLib.hpp" #include"memory.hpp" #endif // Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/browsing_data/chrome_browsing_data_remover_delegate.h" #include #include #include #include #include #include "base/barrier_closure.h" #include "base/bind.h" #include "base/callback.h" #include "base/callback_helpers.h" #include "base/feature_list.h" #include "base/metrics/histogram_functions.h" #include "base/metrics/histogram_macros.h" #include "base/metrics/user_metrics.h" #include "base/task/thread_pool.h" #include "base/trace_event/trace_event.h" #include "build/build_config.h" #include "build/chromeos_buildflags.h" #include "chrome/browser/autofill/personal_data_manager_factory.h" #include "chrome/browser/autofill/strike_database_factory.h" #include "chrome/browser/availability/availability_prober.h" #include "chrome/browser/bookmarks/bookmark_model_factory.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/browsing_data/chrome_browsing_data_remover_constants.h" #include "chrome/browser/browsing_data/navigation_entry_remover.h" #include "chrome/browser/chrome_notification_types.h" #include "chrome/browser/content_settings/host_content_settings_map_factory.h" #include "chrome/browser/crash_upload_list/crash_upload_list.h" #include "chrome/browser/custom_handlers/protocol_handler_registry.h" #include "chrome/browser/custom_handlers/protocol_handler_registry_factory.h" #include "chrome/browser/data_reduction_proxy/data_reduction_proxy_chrome_settings.h" #include "chrome/browser/data_reduction_proxy/data_reduction_proxy_chrome_settings_factory.h" #include "chrome/browser/domain_reliability/service_factory.h" #include "chrome/browser/downgrade/user_data_downgrade.h" #include "chrome/browser/download/download_prefs.h" #include "chrome/browser/external_protocol/external_protocol_handler.h" #include "chrome/browser/heavy_ad_intervention/heavy_ad_blocklist.h" #include "chrome/browser/heavy_ad_intervention/heavy_ad_service.h" #include "chrome/browser/heavy_ad_intervention/heavy_ad_service_factory.h" #include "chrome/browser/history/history_service_factory.h" #include "chrome/browser/history/web_history_service_factory.h" #include "chrome/browser/language/url_language_histogram_factory.h" #include "chrome/browser/lite_video/lite_video_keyed_service.h" #include "chrome/browser/lite_video/lite_video_keyed_service_factory.h" #include "chrome/browser/login_detection/login_detection_prefs.h" #include "chrome/browser/media/history/media_history_keyed_service.h" #include "chrome/browser/media/history/media_history_keyed_service_factory.h" #include "chrome/browser/media/media_device_id_salt.h" #include "chrome/browser/media/media_engagement_service.h" #include "chrome/browser/media/webrtc/webrtc_event_log_manager.h" #include "chrome/browser/optimization_guide/optimization_guide_keyed_service.h" #include "chrome/browser/optimization_guide/optimization_guide_keyed_service_factory.h" #include "chrome/browser/password_manager/account_password_store_factory.h" #include "chrome/browser/password_manager/password_store_factory.h" #include "chrome/browser/permissions/permission_actions_history.h" #include "chrome/browser/permissions/permission_decision_auto_blocker_factory.h" #include "chrome/browser/prefetch/no_state_prefetch/no_state_prefetch_manager_factory.h" #include "chrome/browser/prefetch/prefetch_proxy/prefetch_proxy_origin_decider.h" #include "chrome/browser/prefetch/prefetch_proxy/prefetch_proxy_service.h" #include "chrome/browser/prefetch/prefetch_proxy/prefetch_proxy_service_factory.h" #include "chrome/browser/prefetch/search_prefetch/search_prefetch_service.h" #include "chrome/browser/prefetch/search_prefetch/search_prefetch_service_factory.h" #include "chrome/browser/privacy_sandbox/privacy_sandbox_settings.h" #include "chrome/browser/privacy_sandbox/privacy_sandbox_settings_factory.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/safe_browsing/safe_browsing_service.h" #include "chrome/browser/search_engines/template_url_service_factory.h" #include "chrome/browser/spellchecker/spellcheck_factory.h" #include "chrome/browser/spellchecker/spellcheck_service.h" #include "chrome/browser/translate/chrome_translate_client.h" #include "chrome/browser/ui/find_bar/find_bar_state.h" #include "chrome/browser/ui/find_bar/find_bar_state_factory.h" #include "chrome/browser/web_data_service_factory.h" #include "chrome/browser/webauthn/chrome_authenticator_request_delegate.h" #include "chrome/common/buildflags.h" #include "chrome/common/pref_names.h" #include "chrome/common/url_constants.h" #include "components/autofill/core/browser/payments/strike_database.h" #include "components/autofill/core/browser/personal_data_manager.h" #include "components/autofill/core/browser/webdata/autofill_webdata_service.h" #include "components/autofill/core/common/autofill_features.h" #include "components/autofill/core/common/autofill_payments_features.h" #include "components/bookmarks/browser/bookmark_model.h" #include "components/browsing_data/content/browsing_data_helper.h" #include "components/content_settings/core/browser/content_settings_registry.h" #include "components/content_settings/core/browser/host_content_settings_map.h" #include "components/content_settings/core/common/content_settings.h" #include "components/content_settings/core/common/content_settings_pattern.h" #include "components/crash/core/app/crashpad.h" #include "components/data_reduction_proxy/core/browser/data_reduction_proxy_compression_stats.h" #include "components/data_reduction_proxy/core/browser/data_reduction_proxy_service.h" #include "components/data_reduction_proxy/core/browser/data_reduction_proxy_settings.h" #include "components/device_event_log/device_event_log.h" #include "components/history/core/browser/history_service.h" #include "components/keyed_service/core/service_access_type.h" #include "components/language/core/browser/url_language_histogram.h" #include "components/nacl/browser/nacl_browser.h" #include "components/nacl/browser/pnacl_host.h" #include "components/no_state_prefetch/browser/no_state_prefetch_manager.h" #include "components/omnibox/browser/omnibox_prefs.h" #include "components/open_from_clipboard/clipboard_recent_content.h" #include "components/password_manager/core/browser/password_manager_features_util.h" #include "components/password_manager/core/browser/password_store.h" #include "components/password_manager/core/common/password_manager_features.h" #include "components/permissions/permission_decision_auto_blocker.h" #include "components/prefs/pref_service.h" #include "components/search_engines/template_url_service.h" #include "components/web_cache/browser/web_cache_manager.h" #include "components/webrtc_logging/browser/log_cleanup.h" #include "components/webrtc_logging/browser/text_log_list.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/browsing_data_filter_builder.h" #include "content/public/browser/host_zoom_map.h" #include "content/public/browser/plugin_data_remover.h" #include "content/public/browser/ssl_host_state_delegate.h" #include "content/public/browser/storage_partition.h" #include "google_apis/gaia/gaia_urls.h" #include "media/base/media_switches.h" #include "media/mojo/services/video_decode_perf_history.h" #include "mojo/public/cpp/bindings/callback_helpers.h" #include "mojo/public/cpp/bindings/remote.h" #include "net/base/registry_controlled_domains/registry_controlled_domain.h" #include "net/http/http_transaction_factory.h" #include "net/net_buildflags.h" #if defined(OS_ANDROID) #include "chrome/browser/android/customtabs/origin_verifier.h" #include "chrome/browser/android/explore_sites/explore_sites_service_factory.h" #include "chrome/browser/android/feed/v2/feed_service_factory.h" #include "chrome/browser/android/oom_intervention/oom_intervention_decider.h" #include "chrome/browser/android/search_permissions/search_permissions_service.h" #include "chrome/browser/android/webapps/webapp_registry.h" #include "chrome/browser/offline_pages/offline_page_model_factory.h" #include "chrome/browser/profiles/profile_android.h" #include "components/cdm/browser/media_drm_storage_impl.h" // nogncheck crbug.com/1125897 #include "components/feed/buildflags.h" #include "components/feed/core/v2/public/feed_service.h" #include "components/feed/feed_feature_list.h" #include "components/installedapp/android/jni_headers/PackageHash_jni.h" #include "components/offline_pages/core/offline_page_feature.h" #include "components/offline_pages/core/offline_page_model.h" #include "sql/database.h" #endif // defined(OS_ANDROID) #if BUILDFLAG(ENABLE_EXTENSIONS) #include "chrome/browser/extensions/activity_log/activity_log.h" #include "extensions/browser/extension_prefs.h" #include "extensions/common/constants.h" #endif // BUILDFLAG(ENABLE_EXTENSIONS) #if BUILDFLAG(IS_CHROMEOS_ASH) #include "chrome/browser/ash/profiles/profile_helper.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/browser_process_platform_part.h" #include "chrome/browser/chromeos/policy/browser_policy_connector_chromeos.h" #include "chrome/browser/chromeos/policy/system_proxy_manager.h" #include "chromeos/cryptohome/cryptohome_parameters.h" #include "chromeos/dbus/attestation/attestation_client.h" #include "chromeos/dbus/attestation/interface.pb.h" #include "chromeos/dbus/constants/attestation_constants.h" #include "chromeos/dbus/dbus_thread_manager.h" #include "components/user_manager/user.h" #endif // BUILDFLAG(IS_CHROMEOS_ASH) #if defined(OS_MAC) #include "device/fido/mac/credential_store.h" #endif // defined(OS_MAC) using base::UserMetricsAction; using content::BrowserContext; using content::BrowserThread; using content::BrowsingDataFilterBuilder; namespace constants = chrome_browsing_data_remover; namespace { // Timeout after which the histogram for slow tasks is recorded. const base::TimeDelta kSlowTaskTimeout = base::TimeDelta::FromSeconds(180); // Generic functions but currently only used when ENABLE_NACL. #if BUILDFLAG(ENABLE_NACL) void UIThreadTrampolineHelper(base::OnceClosure callback) { content::GetUIThreadTaskRunner({})->PostTask(FROM_HERE, std::move(callback)); } // Convenience method to create a callback that can be run on any thread and // will post the given |callback| back to the UI thread. base::OnceClosure UIThreadTrampoline(base::OnceClosure callback) { // We could directly bind &base::PostTask, but that would require // evaluating FROM_HERE when this method is called, as opposed to when the // task is actually posted. return base::BindOnce(&UIThreadTrampolineHelper, std::move(callback)); } #endif // BUILDFLAG(ENABLE_NACL) template void IgnoreArgumentHelper(base::OnceClosure callback, T unused_argument) { std::move(callback).Run(); } // Another convenience method to turn a callback without arguments into one that // accepts (and ignores) a single argument. template base::OnceCallback IgnoreArgument(base::OnceClosure callback) { return base::BindOnce(&IgnoreArgumentHelper, std::move(callback)); } #if BUILDFLAG(ENABLE_NACL) void ClearNaClCacheOnIOThread(base::OnceClosure callback) { DCHECK_CURRENTLY_ON(BrowserThread::IO); nacl::NaClBrowser::GetInstance()->ClearValidationCache(std::move(callback)); } void ClearPnaclCacheOnIOThread(base::Time begin, base::Time end, base::OnceClosure callback) { DCHECK_CURRENTLY_ON(BrowserThread::IO); pnacl::PnaclHost::GetInstance()->ClearTranslationCacheEntriesBetween( begin, end, std::move(callback)); } #endif #if defined(OS_ANDROID) void ClearPrecacheInBackground(content::BrowserContext* browser_context) { // Precache code was removed in M61 but the sqlite database file could be // still here. base::FilePath db_path(browser_context->GetPath().Append( base::FilePath(FILE_PATH_LITERAL("PrecacheDatabase")))); sql::Database::Delete(db_path); } #endif // Returned by ChromeBrowsingDataRemoverDelegate::GetOriginTypeMatcher(). bool DoesOriginMatchEmbedderMask(uint64_t origin_type_mask, const url::Origin& origin, storage::SpecialStoragePolicy* policy) { DCHECK_EQ(0ULL, origin_type_mask & (constants::ORIGIN_TYPE_EMBEDDER_BEGIN - 1)) << "|origin_type_mask| can only contain origin types defined in " << "the embedder."; #if BUILDFLAG(ENABLE_EXTENSIONS) // Packaged apps and extensions match iff EXTENSION. if ((origin.scheme() == extensions::kExtensionScheme) && (origin_type_mask & constants::ORIGIN_TYPE_EXTENSION)) { return true; } origin_type_mask &= ~constants::ORIGIN_TYPE_EXTENSION; #endif DCHECK(!origin_type_mask) << "DoesOriginMatchEmbedderMask must handle all origin types."; return false; } } // namespace ChromeBrowsingDataRemoverDelegate::ChromeBrowsingDataRemoverDelegate( BrowserContext* browser_context) : profile_(Profile::FromBrowserContext(browser_context)) #if defined(OS_ANDROID) , webapp_registry_(new WebappRegistry()) #endif { domain_reliability_clearer_ = base::BindRepeating( [](BrowserContext* browser_context, content::BrowsingDataFilterBuilder* filter_builder, network::mojom::NetworkContext_DomainReliabilityClearMode mode, network::mojom::NetworkContext::ClearDomainReliabilityCallback callback) { network::mojom::NetworkContext* network_context = BrowserContext::GetDefaultStoragePartition(browser_context) ->GetNetworkContext(); network_context->ClearDomainReliability( filter_builder->BuildNetworkServiceFilter(), mode, std::move(callback)); }, browser_context); } ChromeBrowsingDataRemoverDelegate::~ChromeBrowsingDataRemoverDelegate() = default; void ChromeBrowsingDataRemoverDelegate::Shutdown() { history_task_tracker_.TryCancelAll(); } content::BrowsingDataRemoverDelegate::EmbedderOriginTypeMatcher ChromeBrowsingDataRemoverDelegate::GetOriginTypeMatcher() { return base::BindRepeating(&DoesOriginMatchEmbedderMask); } bool ChromeBrowsingDataRemoverDelegate::MayRemoveDownloadHistory() { return profile_->GetPrefs()->GetBoolean(prefs::kAllowDeletingBrowserHistory); } std::vector ChromeBrowsingDataRemoverDelegate::GetDomainsForDeferredCookieDeletion( uint64_t remove_mask) { if (!base::FeatureList::IsEnabled( password_manager::features::kEnablePasswordsAccountStorage)) { return {}; } if ((remove_mask & constants::DEFERRED_COOKIE_DELETION_DATA_TYPES) == 0) { return {}; } // Return Google and Gaia domains, so Google signout is deferred until // account-scoped data is deleted. auto urls = {GaiaUrls::GetInstance()->google_url(), GaiaUrls::GetInstance()->gaia_url()}; std::set domains; for (const GURL& url : urls) { std::string domain = GetDomainAndRegistry( url, net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES); if (domain.empty()) domain = url.host(); domains.insert(domain); } return {domains.begin(), domains.end()}; } void ChromeBrowsingDataRemoverDelegate::RemoveEmbedderData( const base::Time& delete_begin, const base::Time& delete_end, uint64_t remove_mask, BrowsingDataFilterBuilder* filter_builder, uint64_t origin_type_mask, base::OnceCallback callback) { DCHECK(((remove_mask & ~content::BrowsingDataRemover::DATA_TYPE_AVOID_CLOSING_CONNECTIONS & ~constants::FILTERABLE_DATA_TYPES) == 0) || filter_builder->MatchesAllOriginsAndDomains()); DCHECK(!should_clear_password_account_storage_settings_); TRACE_EVENT0("browsing_data", "ChromeBrowsingDataRemoverDelegate::RemoveEmbedderData"); // To detect tasks that are causing slow deletions, record running sub tasks // after a delay. slow_pending_tasks_closure_.Reset(base::BindOnce( &ChromeBrowsingDataRemoverDelegate::RecordUnfinishedSubTasks, weak_ptr_factory_.GetWeakPtr())); content::GetUIThreadTaskRunner({})->PostDelayedTask( FROM_HERE, slow_pending_tasks_closure_.callback(), kSlowTaskTimeout); // Embedder-defined DOM-accessible storage currently contains only // one datatype, which is the durable storage permission. if (remove_mask & content::BrowsingDataRemover::DATA_TYPE_EMBEDDER_DOM_STORAGE) { remove_mask |= constants::DATA_TYPE_DURABLE_PERMISSION; } if (origin_type_mask & content::BrowsingDataRemover::ORIGIN_TYPE_UNPROTECTED_WEB) { base::RecordAction( UserMetricsAction("ClearBrowsingData_MaskContainsUnprotectedWeb")); } if (origin_type_mask & content::BrowsingDataRemover::ORIGIN_TYPE_PROTECTED_WEB) { base::RecordAction( UserMetricsAction("ClearBrowsingData_MaskContainsProtectedWeb")); } #if BUILDFLAG(ENABLE_EXTENSIONS) if (origin_type_mask & constants::ORIGIN_TYPE_EXTENSION) { base::RecordAction( UserMetricsAction("ClearBrowsingData_MaskContainsExtension")); } #endif // If this fires, we added a new BrowsingDataHelper::OriginTypeMask without // updating the user metrics above. static_assert( constants::ALL_ORIGIN_TYPES == (content::BrowsingDataRemover::ORIGIN_TYPE_UNPROTECTED_WEB | #if BUILDFLAG(ENABLE_EXTENSIONS) constants::ORIGIN_TYPE_EXTENSION | #endif content::BrowsingDataRemover::ORIGIN_TYPE_PROTECTED_WEB), "OriginTypeMask has been updated without updating user metrics"); ////////////////////////////////////////////////////////////////////////////// // INITIALIZATION base::ScopedClosureRunner synchronous_clear_operations( CreateTaskCompletionClosure(TracingDataType::kSynchronous)); callback_ = std::move(callback); delete_begin_ = delete_begin; delete_end_ = delete_end; failed_data_types_ = 0; base::RepeatingCallback filter = filter_builder->BuildUrlFilter(); // Some backends support a filter that |is_null()| to make complete deletion // more efficient. base::RepeatingCallback nullable_filter = filter_builder->MatchesAllOriginsAndDomains() ? base::RepeatingCallback() : filter; HostContentSettingsMap::PatternSourcePredicate website_settings_filter = browsing_data::CreateWebsiteSettingsFilter(filter_builder); // Managed devices and supervised users can have restrictions on history // deletion. PrefService* prefs = profile_->GetPrefs(); bool may_delete_history = prefs->GetBoolean(prefs::kAllowDeletingBrowserHistory); // All the UI entry points into the BrowsingDataRemoverImpl should be // disabled, but this will fire if something was missed or added. DCHECK(may_delete_history || (remove_mask & content::BrowsingDataRemover::DATA_TYPE_NO_CHECKS) || (!(remove_mask & constants::DATA_TYPE_HISTORY) && !(remove_mask & content::BrowsingDataRemover::DATA_TYPE_DOWNLOADS))); HostContentSettingsMap* host_content_settings_map_ = HostContentSettingsMapFactory::GetForProfile(profile_); ////////////////////////////////////////////////////////////////////////////// // DATA_TYPE_HISTORY if ((remove_mask & constants::DATA_TYPE_HISTORY) && may_delete_history) { history::HistoryService* history_service = HistoryServiceFactory::GetForProfile( profile_, ServiceAccessType::EXPLICIT_ACCESS); if (history_service) { // TODO(dmurph): Support all backends with filter (crbug.com/113621). base::RecordAction(UserMetricsAction("ClearBrowsingData_History")); history_service->DeleteLocalAndRemoteHistoryBetween( WebHistoryServiceFactory::GetForProfile(profile_), delete_begin_, delete_end_, base::AdaptCallbackForRepeating( CreateTaskCompletionClosure(TracingDataType::kHistory)), &history_task_tracker_); } if (ClipboardRecentContent::GetInstance()) ClipboardRecentContent::GetInstance()->SuppressClipboardContent(); language::UrlLanguageHistogram* language_histogram = UrlLanguageHistogramFactory::GetForBrowserContext(profile_); if (language_histogram) { language_histogram->ClearHistory(delete_begin_, delete_end_); } #if BUILDFLAG(ENABLE_EXTENSIONS) // The extension activity log contains details of which websites extensions // were active on. It therefore indirectly stores details of websites a // user has visited so best clean from here as well. // TODO(msramek): Support all backends with filter (crbug.com/589586). extensions::ActivityLog::GetInstance(profile_)->RemoveURLs( std::set()); // Clear launch times as they are a form of history. // BrowsingDataFilterBuilder currently doesn't support extension origins. // Therefore, clearing history for a small set of origins (deletelist) // should never delete any extension launch times, while clearing for almost // all origins (preservelist) should always delete all of extension launch // times. if (filter_builder->MatchesAllOriginsAndDomains()) { extensions::ExtensionPrefs* extension_prefs = extensions::ExtensionPrefs::Get(profile_); extension_prefs->ClearLastLaunchTimes(); } #endif // Need to clear the host cache and accumulated speculative data, as it also // reveals some history. We have no mechanism to track when these items were // created, so we'll not honor the time range. BrowserContext::GetDefaultStoragePartition(profile_) ->GetNetworkContext() ->ClearHostCache( filter_builder->BuildNetworkServiceFilter(), CreateTaskCompletionClosureForMojo(TracingDataType::kHostCache)); // The NoStatePrefetchManager keeps history of pages scanned for prefetch, // so clear that. It also may have a scanned page. If so, the page could be // considered to have a small amount of historical information, so delete // it, too. prerender::NoStatePrefetchManager* no_state_prefetch_manager = prerender::NoStatePrefetchManagerFactory::GetForBrowserContext( profile_); if (no_state_prefetch_manager) { // TODO(dmurph): Support all backends with filter (crbug.com/113621). no_state_prefetch_manager->ClearData( prerender::NoStatePrefetchManager::CLEAR_PRERENDER_CONTENTS | prerender::NoStatePrefetchManager::CLEAR_PRERENDER_HISTORY); } // The saved Autofill profiles and credit cards can include the origin from // which these profiles and credit cards were learned. These are a form of // history, so clear them as well. // TODO(dmurph): Support all backends with filter (crbug.com/113621). scoped_refptr web_data_service = WebDataServiceFactory::GetAutofillWebDataForProfile( profile_, ServiceAccessType::EXPLICIT_ACCESS); if (web_data_service.get()) { web_data_service->RemoveOriginURLsModifiedBetween(delete_begin_, delete_end_); // Ask for a call back when the above call is finished. web_data_service->GetDBTaskRunner()->PostTaskAndReply( FROM_HERE, base::DoNothing(), CreateTaskCompletionClosure(TracingDataType::kAutofillOrigins)); autofill::PersonalDataManager* data_manager = autofill::PersonalDataManagerFactory::GetForProfile(profile_); if (data_manager) data_manager->Refresh(); } base::ThreadPool::PostTaskAndReply( FROM_HERE, {base::TaskPriority::USER_VISIBLE, base::MayBlock()}, base::BindOnce( &webrtc_logging::DeleteOldAndRecentWebRtcLogFiles, webrtc_logging::TextLogList:: GetWebRtcLogDirectoryForBrowserContextPath(profile_->GetPath()), delete_begin_), CreateTaskCompletionClosure(TracingDataType::kWebrtcLogs)); #if defined(OS_ANDROID) base::ThreadPool::PostTaskAndReply( FROM_HERE, {base::TaskPriority::USER_VISIBLE, base::MayBlock()}, base::BindOnce(&ClearPrecacheInBackground, profile_), CreateTaskCompletionClosure(TracingDataType::kPrecache)); // Clear the history information (last launch time and origin URL) of any // registered webapps. webapp_registry_->ClearWebappHistoryForUrls(filter); // The OriginVerifier caches origins for Trusted Web Activities that have // been verified and stores them in Android Preferences. customtabs::OriginVerifier::ClearBrowsingData(); #endif data_reduction_proxy::DataReductionProxySettings* data_reduction_proxy_settings = DataReductionProxyChromeSettingsFactory::GetForBrowserContext( profile_); // |data_reduction_proxy_settings| is null if |profile_| is off the record. if (data_reduction_proxy_settings) { data_reduction_proxy::DataReductionProxyService* data_reduction_proxy_service = data_reduction_proxy_settings->data_reduction_proxy_service(); if (data_reduction_proxy_service) { data_reduction_proxy_service->compression_stats() ->DeleteBrowsingHistory(delete_begin_, delete_end_); } } HeavyAdService* heavy_ad_service = HeavyAdServiceFactory::GetForBrowserContext(profile_); if (heavy_ad_service && heavy_ad_service->heavy_ad_blocklist()) { heavy_ad_service->heavy_ad_blocklist()->ClearBlockList(delete_begin_, delete_end_); } OptimizationGuideKeyedService* optimization_guide_keyed_service = OptimizationGuideKeyedServiceFactory::GetForProfile(profile_); if (optimization_guide_keyed_service) optimization_guide_keyed_service->ClearData(); AvailabilityProber::ClearData(prefs); LiteVideoKeyedService* lite_video_keyed_service = LiteVideoKeyedServiceFactory::GetForProfile(profile_); if (lite_video_keyed_service) lite_video_keyed_service->ClearData(delete_begin_, delete_end_); PrefetchProxyService* prefetch_proxy_service = PrefetchProxyServiceFactory::GetForProfile(profile_); if (prefetch_proxy_service) { prefetch_proxy_service->origin_decider()->OnBrowsingDataCleared(); } #if defined(OS_ANDROID) OomInterventionDecider* oom_intervention_decider = OomInterventionDecider::GetForBrowserContext(profile_); if (oom_intervention_decider) oom_intervention_decider->ClearData(); #endif // The SSL Host State that tracks SSL interstitial "proceed" decisions may // include origins that the user has visited, so it must be cleared. // TODO(msramek): We can reuse the plugin filter here, since both plugins // and SSL host state are scoped to hosts and represent them as std::string. // Rename the method to indicate its more general usage. if (profile_->GetSSLHostStateDelegate()) { profile_->GetSSLHostStateDelegate()->Clear( filter_builder->MatchesAllOriginsAndDomains() ? base::RepeatingCallback() : filter_builder->BuildPluginFilter()); } // Clear VideoDecodePerfHistory only if asked to clear from the beginning of // time. The perf history is a simple summing of decode statistics with no // record of when the stats were written nor what site the video was played // on. if (IsForAllTime()) { // TODO(chcunningham): Add UMA to track how often this gets deleted. media::VideoDecodePerfHistory* video_decode_perf_history = profile_->GetVideoDecodePerfHistory(); if (video_decode_perf_history) { video_decode_perf_history->ClearHistory( CreateTaskCompletionClosure(TracingDataType::kVideoDecodeHistory)); } } device_event_log::Clear(delete_begin_, delete_end_); #if defined(OS_ANDROID) explore_sites::ExploreSitesService* explore_sites_service = explore_sites::ExploreSitesServiceFactory::GetForBrowserContext( profile_); if (explore_sites_service) { explore_sites_service->ClearActivities( delete_begin_, delete_end_, CreateTaskCompletionClosure(TracingDataType::kExploreSites)); } #endif CreateCrashUploadList()->Clear(delete_begin_, delete_end_); FindBarStateFactory::GetForBrowserContext(profile_)->SetLastSearchText( base::string16()); } ////////////////////////////////////////////////////////////////////////////// // DATA_TYPE_DOWNLOADS if ((remove_mask & content::BrowsingDataRemover::DATA_TYPE_DOWNLOADS) && may_delete_history) { DownloadPrefs* download_prefs = DownloadPrefs::FromDownloadManager( BrowserContext::GetDownloadManager(profile_)); download_prefs->SetSaveFilePath(download_prefs->DownloadPath()); } ////////////////////////////////////////////////////////////////////////////// // DATA_TYPE_COOKIES // We ignore the DATA_TYPE_COOKIES request if UNPROTECTED_WEB is not set, // so that callers who request DATA_TYPE_SITE_DATA with PROTECTED_WEB // don't accidentally remove the cookies that are associated with the // UNPROTECTED_WEB origin. This is necessary because cookies are not separated // between UNPROTECTED_WEB and PROTECTED_WEB. if ((remove_mask & content::BrowsingDataRemover::DATA_TYPE_COOKIES) && (origin_type_mask & content::BrowsingDataRemover::ORIGIN_TYPE_UNPROTECTED_WEB)) { base::RecordAction(UserMetricsAction("ClearBrowsingData_Cookies")); network::mojom::NetworkContext* safe_browsing_context = nullptr; safe_browsing::SafeBrowsingService* sb_service = g_browser_process->safe_browsing_service(); if (sb_service) safe_browsing_context = sb_service->GetNetworkContext(profile_); browsing_data::RemoveEmbedderCookieData( delete_begin, delete_end, filter_builder, host_content_settings_map_, safe_browsing_context, base::BindOnce( &ChromeBrowsingDataRemoverDelegate::CreateTaskCompletionClosure, base::Unretained(this), TracingDataType::kCookies)); if (filter_builder->GetMode() == BrowsingDataFilterBuilder::Mode::kPreserve) { PrivacySandboxSettings* privacy_sandbox_settings = PrivacySandboxSettingsFactory::GetForProfile(profile_); if (privacy_sandbox_settings) privacy_sandbox_settings->OnCookiesCleared(); MediaDeviceIDSalt::Reset(profile_->GetPrefs()); #if defined(OS_ANDROID) Java_PackageHash_onCookiesDeleted( base::android::AttachCurrentThread(), ProfileAndroid::FromProfile(profile_)->GetJavaObject()); #endif } if (nullable_filter.is_null() || nullable_filter.Run(GaiaUrls::GetInstance()->google_url())) { // Set a flag to clear account storage settings later instead of clearing // it now as we can not reset this setting before passwords are deleted. should_clear_password_account_storage_settings_ = true; } } ////////////////////////////////////////////////////////////////////////////// // DATA_TYPE_CONTENT_SETTINGS if (remove_mask & constants::DATA_TYPE_CONTENT_SETTINGS) { base::RecordAction(UserMetricsAction("ClearBrowsingData_ContentSettings")); browsing_data::RemoveSiteSettingsData(delete_begin, delete_end, host_content_settings_map_); auto* handler_registry = ProtocolHandlerRegistryFactory::GetForBrowserContext(profile_); if (handler_registry) handler_registry->ClearUserDefinedHandlers(delete_begin_, delete_end_); ChromeTranslateClient::CreateTranslatePrefs(prefs) ->DeleteNeverPromptSitesBetween(delete_begin_, delete_end_); host_content_settings_map_->ClearSettingsForOneTypeWithPredicate( ContentSettingsType::PERMISSION_AUTOREVOCATION_DATA, delete_begin, delete_end, website_settings_filter); #if !defined(OS_ANDROID) content::HostZoomMap* zoom_map = content::HostZoomMap::GetDefaultForBrowserContext(profile_); zoom_map->ClearZoomLevels(delete_begin, delete_end_); #else // Reset the Default Search Engine permissions to their default. SearchPermissionsService* search_permissions_service = SearchPermissionsService::Factory::GetForBrowserContext(profile_); search_permissions_service->ResetDSEPermissions(); #endif } ////////////////////////////////////////////////////////////////////////////// // DATA_TYPE_BOOKMARKS if (remove_mask & constants::DATA_TYPE_BOOKMARKS) { auto* bookmark_model = BookmarkModelFactory::GetForBrowserContext(profile_); if (bookmark_model) { if (delete_begin_.is_null() && (delete_end_.is_null() || delete_end_.is_max())) { bookmark_model->RemoveAllUserBookmarks(); } else { // Bookmark deletion is only implemented to remove all data after a // profile deletion. A full implementation would need to traverse the // whole tree and check timestamps against delete_begin and delete_end. NOTIMPLEMENTED(); } } } ////////////////////////////////////////////////////////////////////////////// // DATA_TYPE_LOCAL_CUSTOM_DICTIONARY if (remove_mask & constants::DATA_TYPE_LOCAL_CUSTOM_DICTIONARY) { auto* spellcheck = SpellcheckServiceFactory::GetForContext(profile_); if (spellcheck) { auto* dict = spellcheck->GetCustomDictionary(); if (dict) dict->Clear(); } } ////////////////////////////////////////////////////////////////////////////// // DATA_TYPE_DURABLE_PERMISSION if (remove_mask & constants::DATA_TYPE_DURABLE_PERMISSION) { host_content_settings_map_->ClearSettingsForOneTypeWithPredicate( ContentSettingsType::DURABLE_STORAGE, base::Time(), base::Time::Max(), website_settings_filter); } ////////////////////////////////////////////////////////////////////////////// // DATA_TYPE_SITE_USAGE_DATA if (remove_mask & constants::DATA_TYPE_SITE_USAGE_DATA) { base::RecordAction(UserMetricsAction("ClearBrowsingData_SiteUsageData")); host_content_settings_map_->ClearSettingsForOneTypeWithPredicate( ContentSettingsType::SITE_ENGAGEMENT, base::Time(), base::Time::Max(), website_settings_filter); if (MediaEngagementService::IsEnabled()) { MediaEngagementService::Get(profile_)->ClearDataBetweenTime(delete_begin_, delete_end_); } PermissionActionsHistory::GetForProfile(profile_)->ClearHistory( delete_begin_, delete_end_); } if ((remove_mask & constants::DATA_TYPE_SITE_USAGE_DATA) || (remove_mask & constants::DATA_TYPE_HISTORY)) { host_content_settings_map_->ClearSettingsForOneTypeWithPredicate( ContentSettingsType::APP_BANNER, base::Time(), base::Time::Max(), website_settings_filter); #if !defined(OS_ANDROID) host_content_settings_map_->ClearSettingsForOneTypeWithPredicate( ContentSettingsType::INSTALLED_WEB_APP_METADATA, delete_begin_, delete_end_, website_settings_filter); host_content_settings_map_->ClearSettingsForOneTypeWithPredicate( ContentSettingsType::INTENT_PICKER_DISPLAY, delete_begin_, delete_end_, website_settings_filter); host_content_settings_map_->ClearSettingsForOneTypeWithPredicate( ContentSettingsType::FILE_SYSTEM_LAST_PICKED_DIRECTORY, delete_begin, delete_end, website_settings_filter); #endif PermissionDecisionAutoBlockerFactory::GetForProfile(profile_) ->RemoveEmbargoAndResetCounts(filter); } ////////////////////////////////////////////////////////////////////////////// // Password manager if (remove_mask & constants::DATA_TYPE_PASSWORDS) { base::RecordAction(UserMetricsAction("ClearBrowsingData_Passwords")); auto password_store = PasswordStoreFactory::GetForProfile( profile_, ServiceAccessType::EXPLICIT_ACCESS); if (password_store) { // TODO:(crbug.com/1167715) - Test that associated compromised credentials // are removed. password_store->RemoveLoginsByURLAndTime( filter, delete_begin_, delete_end_, CreateTaskCompletionClosure(TracingDataType::kPasswords)); } BrowserContext::GetDefaultStoragePartition(profile_) ->GetNetworkContext() ->ClearHttpAuthCache( delete_begin_.is_null() ? base::Time::Min() : delete_begin_, delete_end_.is_null() ? base::Time::Max() : delete_end_, CreateTaskCompletionClosureForMojo( TracingDataType::kHttpAuthCache)); #if BUILDFLAG(IS_CHROMEOS_ASH) policy::SystemProxyManager* system_proxy_manager = g_browser_process->platform_part() ->browser_policy_connector_chromeos() ->GetSystemProxyManager(); if (system_proxy_manager) { // Sends a request to the System-proxy daemon to clear the proxy user // credentials. System-proxy retrieves proxy username and password from // the NetworkService, but not the creation time of the credentials. The // |ClearUserCredentials| request will remove all the cached proxy // credentials. If credentials prior to |delete_begin_| are removed from // System-proxy, the daemon will send a D-Bus request to Chrome to fetch // them from the NetworkService when needed. system_proxy_manager->ClearUserCredentials(); } #endif // BUILDFLAG(IS_CHROMEOS_ASH) #if defined(OS_MAC) device::fido::mac::TouchIdCredentialStore( ChromeAuthenticatorRequestDelegate:: TouchIdAuthenticatorConfigForProfile(profile_)) .DeleteCredentials(delete_begin_, delete_end_); #endif // defined(OS_MAC) } if (remove_mask & constants::DATA_TYPE_ACCOUNT_PASSWORDS) { auto account_store = AccountPasswordStoreFactory::GetForProfile( profile_, ServiceAccessType::EXPLICIT_ACCESS); if (account_store) { // TODO:(crbug.com/1167715) - Test that associated compromised credentials // are removed. account_store->RemoveLoginsByURLAndTime( filter, delete_begin_, delete_end_, CreateTaskCompletionClosure(TracingDataType::kAccountPasswords), CreateTaskCompletionCallback(TracingDataType::kAccountPasswordsSynced, constants::DATA_TYPE_ACCOUNT_PASSWORDS)); } } if (remove_mask & content::BrowsingDataRemover::DATA_TYPE_COOKIES) { password_manager::PasswordStore* password_store = PasswordStoreFactory::GetForProfile(profile_, ServiceAccessType::EXPLICIT_ACCESS) .get(); if (password_store) { password_store->DisableAutoSignInForOrigins( filter, base::AdaptCallbackForRepeating(CreateTaskCompletionClosure( TracingDataType::kDisableAutoSignin))); } } if (remove_mask & constants::DATA_TYPE_HISTORY) { password_manager::PasswordStore* password_store = PasswordStoreFactory::GetForProfile(profile_, ServiceAccessType::EXPLICIT_ACCESS) .get(); if (password_store) { password_store->RemoveStatisticsByOriginAndTime( nullable_filter, delete_begin_, delete_end_, base::AdaptCallbackForRepeating(CreateTaskCompletionClosure( TracingDataType::kPasswordsStatistics))); password_store->RemoveFieldInfoByTime( delete_begin_, delete_end_, CreateTaskCompletionClosure(TracingDataType::kFieldInfo)); } } ////////////////////////////////////////////////////////////////////////////// // DATA_TYPE_FORM_DATA // TODO(dmurph): Support all backends with filter (crbug.com/113621). if (remove_mask & constants::DATA_TYPE_FORM_DATA) { base::RecordAction(UserMetricsAction("ClearBrowsingData_Autofill")); scoped_refptr web_data_service = WebDataServiceFactory::GetAutofillWebDataForProfile( profile_, ServiceAccessType::EXPLICIT_ACCESS); if (web_data_service.get()) { web_data_service->RemoveFormElementsAddedBetween(delete_begin_, delete_end_); web_data_service->RemoveAutofillDataModifiedBetween(delete_begin_, delete_end_); // Clear out the Autofill StrikeDatabase in its entirety. // TODO(crbug.com/884817): Respect |delete_begin_| and |delete_end_| and // only clear out entries whose last strikes were created in that // timeframe. autofill::StrikeDatabase* strike_database = autofill::StrikeDatabaseFactory::GetForProfile(profile_); if (strike_database) strike_database->ClearAllStrikes(); // Ask for a call back when the above calls are finished. web_data_service->GetDBTaskRunner()->PostTaskAndReply( FROM_HERE, base::DoNothing(), CreateTaskCompletionClosure(TracingDataType::kAutofillData)); autofill::PersonalDataManager* data_manager = autofill::PersonalDataManagerFactory::GetForProfile(profile_); if (data_manager) data_manager->Refresh(); } } ////////////////////////////////////////////////////////////////////////////// // DATA_TYPE_CACHE if (remove_mask & content::BrowsingDataRemover::DATA_TYPE_CACHE) { // Tell the renderers associated with |profile_| to clear their cache. // TODO(crbug.com/668114): Renderer cache is a platform concept, and should // live in BrowsingDataRemoverImpl. However, WebCacheManager itself is // a component with dependency on content/browser. Untangle these // dependencies or reimplement the relevant part of WebCacheManager // in content/browser. // TODO(crbug.com/1022757): add a test for this. for (content::RenderProcessHost::iterator iter = content::RenderProcessHost::AllHostsIterator(); !iter.IsAtEnd(); iter.Advance()) { content::RenderProcessHost* render_process_host = iter.GetCurrentValue(); if (render_process_host->GetBrowserContext() == profile_ && render_process_host->IsInitializedAndNotDead()) { web_cache::WebCacheManager::GetInstance()->ClearCacheForProcess( render_process_host->GetID()); } } #if BUILDFLAG(ENABLE_NACL) content::GetIOThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce(&ClearNaClCacheOnIOThread, UIThreadTrampoline(CreateTaskCompletionClosure( TracingDataType::kNaclCache)))); content::GetIOThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce(&ClearPnaclCacheOnIOThread, delete_begin_, delete_end_, UIThreadTrampoline(CreateTaskCompletionClosure( TracingDataType::kPnaclCache)))); #endif browsing_data::RemovePrerenderCacheData( prerender::NoStatePrefetchManagerFactory::GetForBrowserContext( profile_)); if (base::FeatureList::IsEnabled(media::kUseMediaHistoryStore)) { media_history::MediaHistoryKeyedService* media_history_service = media_history::MediaHistoryKeyedServiceFactory::GetForProfile( profile_); if (media_history_service) { media_history_service->ResetMediaFeedDueToCacheClearing( delete_begin_, delete_end_, nullable_filter, CreateTaskCompletionClosure(TracingDataType::kMediaFeeds)); } } #if defined(OS_ANDROID) #if BUILDFLAG(ENABLE_FEED_V2) // Don't bridge through if the service isn't present, which means we're // probably running in a native unit test. feed::FeedService* service = feed::FeedServiceFactory::GetForBrowserContext(profile_); if (service) { service->ClearCachedData(); } #endif // BUILDFLAG(ENABLE_FEED_V2) #endif // defined(OS_ANDROID) #if defined(OS_ANDROID) // For now we're considering offline pages as cache, so if we're removing // cache we should remove offline pages as well. if (remove_mask & content::BrowsingDataRemover::DATA_TYPE_CACHE) { auto* offline_page_model = offline_pages::OfflinePageModelFactory::GetForBrowserContext( profile_); if (offline_page_model) offline_page_model->DeleteCachedPagesByURLPredicate( filter, base::AdaptCallbackForRepeating( IgnoreArgument< offline_pages::OfflinePageModel::DeletePageResult>( CreateTaskCompletionClosure( TracingDataType::kOfflinePages)))); } #endif // TODO(crbug.com/829321): Remove null-check. auto* webrtc_event_log_manager = WebRtcEventLogManager::GetInstance(); if (webrtc_event_log_manager) { webrtc_event_log_manager->ClearCacheForBrowserContext( profile_, delete_begin_, delete_end_, CreateTaskCompletionClosure(TracingDataType::kWebrtcEventLogs)); } else { LOG(ERROR) << "WebRtcEventLogManager not instantiated."; } } #if BUILDFLAG(ENABLE_PLUGINS) // Plugin is data not separated for protected and unprotected web origins. We // check the origin_type_mask_ to prevent unintended deletion. if ((remove_mask & constants::DATA_TYPE_PLUGIN_DATA) && (origin_type_mask & content::BrowsingDataRemover::ORIGIN_TYPE_UNPROTECTED_WEB)) { base::RecordAction(UserMetricsAction("ClearBrowsingData_LSOData")); if (filter_builder->MatchesAllOriginsAndDomains()) { // TODO(bbudge) Figure out how to delete Flash plugin data without a // Flash plugin. } } #endif ////////////////////////////////////////////////////////////////////////////// // DATA_TYPE_MEDIA_LICENSES if (remove_mask & content::BrowsingDataRemover::DATA_TYPE_MEDIA_LICENSES) { // TODO(jrummell): This UMA should be renamed to indicate it is for Media // Licenses. base::RecordAction(UserMetricsAction("ClearBrowsingData_ContentLicenses")); #if BUILDFLAG(IS_CHROMEOS_ASH) // On Chrome OS, delete any content protection platform keys. // Platform keys do not support filtering by domain, so skip this if // clearing only a specified set of sites. if (filter_builder->GetMode() != BrowsingDataFilterBuilder::Mode::kDelete) { const user_manager::User* user = chromeos::ProfileHelper::Get()->GetUserByProfile(profile_); if (!user) { LOG(WARNING) << "Failed to find user for current profile."; } else { ::attestation::DeleteKeysRequest request; request.set_username(cryptohome::CreateAccountIdentifierFromAccountId( user->GetAccountId()) .account_id()); request.set_key_label_match( chromeos::attestation::kContentProtectionKeyPrefix); request.set_match_behavior( ::attestation::DeleteKeysRequest::MATCH_BEHAVIOR_PREFIX); auto callback = base::BindOnce( &ChromeBrowsingDataRemoverDelegate::OnClearPlatformKeys, weak_ptr_factory_.GetWeakPtr(), CreateTaskCompletionClosure(TracingDataType::kTpmAttestationKeys)); chromeos::AttestationClient::Get()->DeleteKeys( request, base::BindOnce( [](decltype(callback) cb, const ::attestation::DeleteKeysReply& reply) { std::move(cb).Run(reply.status() == ::attestation::STATUS_SUCCESS); }, std::move(callback))); } } #endif // BUILDFLAG(IS_CHROMEOS_ASH) #if defined(OS_ANDROID) cdm::MediaDrmStorageImpl::ClearMatchingLicenses( prefs, delete_begin_, delete_end, nullable_filter, CreateTaskCompletionClosure(TracingDataType::kDrmLicenses)); #endif // defined(OS_ANDROID); } ////////////////////////////////////////////////////////////////////////////// // Zero suggest, Search prefetch, and search session token. // Remove omnibox zero-suggest cache results and Search Prefetch cached // results only when their respective URLs are in the filter. if ((remove_mask & (content::BrowsingDataRemover::DATA_TYPE_CACHE | content::BrowsingDataRemover::DATA_TYPE_COOKIES))) { // If there is no template service or DSE, clear the caches. bool should_clear_zero_suggest_and_session_token = true; bool should_clear_search_prefetch = true; auto* template_url_service = TemplateURLServiceFactory::GetForProfile(profile_); // If there is no default search engine, clearing the cache is fine. if (template_url_service && template_url_service->GetDefaultSearchProvider()) { // The suggest URL is used for zero suggest. GURL suggest_url( template_url_service->GetDefaultSearchProvider()->suggestions_url()); should_clear_zero_suggest_and_session_token = nullable_filter.is_null() || nullable_filter.Run(suggest_url); // The search URL is used for search prefetch. GURL search_url(template_url_service->GetDefaultSearchProvider()->url()); should_clear_search_prefetch = nullable_filter.is_null() || nullable_filter.Run(search_url); } if (should_clear_zero_suggest_and_session_token) prefs->SetString(omnibox::kZeroSuggestCachedResults, std::string()); // |search_prefetch_service| is null if |profile_| is off the record. auto* search_prefetch_service = SearchPrefetchServiceFactory::GetForProfile(profile_); if (should_clear_search_prefetch && search_prefetch_service) search_prefetch_service->ClearPrefetches(); if (should_clear_zero_suggest_and_session_token && template_url_service) template_url_service->ClearSessionToken(); } ////////////////////////////////////////////////////////////////////////////// // Domain reliability. if (remove_mask & (content::BrowsingDataRemover::DATA_TYPE_COOKIES | constants::DATA_TYPE_HISTORY)) { network::mojom::NetworkContext_DomainReliabilityClearMode mode; if (remove_mask & content::BrowsingDataRemover::DATA_TYPE_COOKIES) mode = network::mojom::NetworkContext::DomainReliabilityClearMode:: CLEAR_CONTEXTS; else mode = network::mojom::NetworkContext::DomainReliabilityClearMode:: CLEAR_BEACONS; domain_reliability_clearer_.Run(filter_builder, mode, CreateTaskCompletionClosureForMojo( TracingDataType::kDomainReliability)); } ////////////////////////////////////////////////////////////////////////////// // Persisted isolated origins. // Clear persisted isolated origins when cookies and other site data are // cleared (DATA_TYPE_ISOLATED_ORIGINS is part of DATA_TYPE_SITE_DATA), or // when history is cleared. This is because (1) clearing cookies implies // forgetting that the user has logged into sites, which also implies // forgetting that a user has typed a password on them, and (2) saved // isolated origins are a form of history, since the user has visited them in // the past and triggered isolation via heuristics like typing a password on // them. Note that the Clear-Site-Data header should not clear isolated // origins: they should only be cleared by user-driven actions. // // TODO(alexmos): Support finer-grained filtering based on time ranges and // |filter|. For now, conservatively delete all saved isolated origins. if (remove_mask & (constants::DATA_TYPE_ISOLATED_ORIGINS | constants::DATA_TYPE_HISTORY)) browsing_data::RemoveSiteIsolationData(prefs); #if BUILDFLAG(ENABLE_REPORTING) if (remove_mask & constants::DATA_TYPE_HISTORY) { network::mojom::NetworkContext* network_context = BrowserContext::GetDefaultStoragePartition(profile_) ->GetNetworkContext(); network_context->ClearReportingCacheReports( filter_builder->BuildNetworkServiceFilter(), CreateTaskCompletionClosureForMojo(TracingDataType::kReportingCache)); network_context->ClearNetworkErrorLogging( filter_builder->BuildNetworkServiceFilter(), CreateTaskCompletionClosureForMojo( TracingDataType::kNetworkErrorLogging)); } #endif // BUILDFLAG(ENABLE_REPORTING) ////////////////////////////////////////////////////////////////////////////// // DATA_TYPE_WEB_APP_DATA #if defined(OS_ANDROID) // Clear all data associated with registered webapps. if (remove_mask & constants::DATA_TYPE_WEB_APP_DATA) webapp_registry_->UnregisterWebappsForUrls(filter); #endif ////////////////////////////////////////////////////////////////////////////// // Remove external protocol data. if (remove_mask & constants::DATA_TYPE_EXTERNAL_PROTOCOL_DATA) ExternalProtocolHandler::ClearData(profile_); #if BUILDFLAG(ENABLE_DOWNGRADE_PROCESSING) ////////////////////////////////////////////////////////////////////////////// // Remove data for this profile contained in any snapshots. if (remove_mask && filter_builder->GetMode() == BrowsingDataFilterBuilder::Mode::kPreserve) { base::ThreadPool::PostTaskAndReply( FROM_HERE, {base::TaskPriority::USER_VISIBLE, base::MayBlock()}, base::BindOnce(&downgrade::RemoveDataForProfile, delete_begin_, profile_->GetPath(), remove_mask), CreateTaskCompletionClosure(TracingDataType::kUserDataSnapshot)); } #endif // BUILDFLAG(ENABLE_DOWNGRADE_PROCESSING) ////////////////////////////////////////////////////////////////////////////// // Login detection data: // Clear the origins where login has been detected, when cookies and other // site data are cleared, or when history is cleared. This is because clearing // cookies or history implies forgetting that the user has logged into sites. if (remove_mask & (constants::DATA_TYPE_SITE_DATA | constants::DATA_TYPE_HISTORY)) { login_detection::prefs::RemoveLoginDetectionData(prefs); } } void ChromeBrowsingDataRemoverDelegate::OnTaskStarted( TracingDataType data_type) { DCHECK_CURRENTLY_ON(BrowserThread::UI); auto result = pending_sub_tasks_.insert(data_type); DCHECK(result.second) << "Task already started: " << static_cast(data_type); TRACE_EVENT_NESTABLE_ASYNC_BEGIN1( "browsing_data", "ChromeBrowsingDataRemoverDelegate", TRACE_ID_WITH_SCOPE("ChromeBrowsingDataRemoverDelegate", static_cast(data_type)), "data_type", static_cast(data_type)); } void ChromeBrowsingDataRemoverDelegate::OnTaskComplete( TracingDataType data_type, uint64_t data_type_mask, bool success) { DCHECK_CURRENTLY_ON(BrowserThread::UI); size_t num_erased = pending_sub_tasks_.erase(data_type); DCHECK_EQ(num_erased, 1U); TRACE_EVENT_NESTABLE_ASYNC_END1( "browsing_data", "ChromeBrowsingDataRemoverDelegate", TRACE_ID_WITH_SCOPE("ChromeBrowsingDataRemoverDelegate", static_cast(data_type)), "data_type", static_cast(data_type)); if (!success) { base::UmaHistogramEnumeration("History.ClearBrowsingData.FailedTasksChrome", data_type); failed_data_types_ |= data_type_mask; } if (!pending_sub_tasks_.empty()) return; // Explicitly clear any opt-ins to the account-scoped password storage // when cookies are being cleared. This needs to happen after passwords // have been deleted, so it is performed when all other tasks are completed. // TODO(crbug.com/1052005, crbug.com/1078762): These *should* get cleared // automatically when the Google cookies are deleted, but currently this // doesn't always work reliably. When these bugs get resolved, the // following line and associated code can be removed. if (should_clear_password_account_storage_settings_) { should_clear_password_account_storage_settings_ = false; password_manager::features_util::ClearAccountStorageSettingsForAllUsers( profile_->GetPrefs()); } slow_pending_tasks_closure_.Cancel(); DCHECK(!callback_.is_null()); std::move(callback_).Run(failed_data_types_); } base::OnceClosure ChromeBrowsingDataRemoverDelegate::CreateTaskCompletionClosure( TracingDataType data_type) { return base::BindOnce( CreateTaskCompletionCallback(data_type, /*data_type_mask=*/0), /*success=*/true); } base::OnceCallback ChromeBrowsingDataRemoverDelegate::CreateTaskCompletionCallback( TracingDataType data_type, uint64_t data_type_mask) { OnTaskStarted(data_type); return base::BindOnce(&ChromeBrowsingDataRemoverDelegate::OnTaskComplete, weak_ptr_factory_.GetWeakPtr(), data_type, data_type_mask); } base::OnceClosure ChromeBrowsingDataRemoverDelegate::CreateTaskCompletionClosureForMojo( TracingDataType data_type) { DCHECK_CURRENTLY_ON(BrowserThread::UI); // Note num_pending_tasks++ unnecessary here because it's done by the call to // CreateTaskCompletionClosure(). return mojo::WrapCallbackWithDropHandler( CreateTaskCompletionClosure(data_type), base::BindOnce(&ChromeBrowsingDataRemoverDelegate::OnTaskComplete, weak_ptr_factory_.GetWeakPtr(), data_type, /*data_type_mask=*/0, /*success=*/true)); } void ChromeBrowsingDataRemoverDelegate::RecordUnfinishedSubTasks() { DCHECK(!pending_sub_tasks_.empty()); for (TracingDataType task : pending_sub_tasks_) { UMA_HISTOGRAM_ENUMERATION( "History.ClearBrowsingData.Duration.SlowTasks180sChrome", task); } } #if defined(OS_ANDROID) void ChromeBrowsingDataRemoverDelegate::OverrideWebappRegistryForTesting( std::unique_ptr webapp_registry) { webapp_registry_ = std::move(webapp_registry); } #endif void ChromeBrowsingDataRemoverDelegate:: OverrideDomainReliabilityClearerForTesting( DomainReliabilityClearer clearer) { domain_reliability_clearer_ = std::move(clearer); } bool ChromeBrowsingDataRemoverDelegate::IsForAllTime() const { return delete_begin_ == base::Time() && delete_end_ == base::Time::Max(); } #if BUILDFLAG(IS_CHROMEOS_ASH) void ChromeBrowsingDataRemoverDelegate::OnClearPlatformKeys( base::OnceClosure done, bool result) { LOG_IF(ERROR, !result) << "Failed to clear platform keys."; std::move(done).Run(); } #endif /* * Project: FullereneViewer * Version: 1.0 * Copyright: (C) 2011-15 Dr.Sc.KAWAMOTO,Takuji (Ext) */ #include #include #include "Random.h" void Random::initialize() { srand((unsigned int)time(NULL)); } double Random::minus1to1() { return minus_width_to_width(1.0); } double Random::minus_width_to_width(double width) { double result = (double)rand() / (double)RAND_MAX; return (result * 2.0 - 1.0) * width; } /* Local Variables: */ /* mode: c++ */ /* End: */ /**************************************************************************\ * Copyright (c) & Gas Technologies AS * 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 * 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. \**************************************************************************/ /* Collects functionality for glyph-handling common for 2D and 3D glyphs. */ /* ********************************************************************** */ #include "glyph.h" #include #include #include "fontlib_wrapper.h" #include "coindefs.h" #ifndef COIN_WORKAROUND_NO_USING_STD_FUNCS using namespace std; #endif // !COIN_WORKAROUND_NO_USING_STD_FUNCS /* ********************************************************************** */ void cc_glyph_unref(cc_dict * dict, cc_glyph * glyph, cc_glyph_finalize * f) { cc_list * glyphlist; int ret; void * tmp; int i; glyph->refcount--; assert(glyph->refcount >= 0); if (glyph->refcount > 0) { return; } /* external finalizing: */ if (f) { (*f)(glyph); } /* handling of common data: */ ret = cc_dict_get(dict, (uintptr_t)glyph->character, &tmp); assert(ret); glyphlist = (cc_list *)tmp; for (i = 0; i < cc_list_get_length(glyphlist); i++) { if (glyph == (cc_glyph *)cc_list_get(glyphlist, i)) break; } assert(i < cc_list_get_length(glyphlist)); cc_list_remove_fast(glyphlist, i); if (cc_list_get_length(glyphlist) == 0) { (void)cc_dict_remove(dict, (uintptr_t)glyph->character); cc_list_destruct(glyphlist); } cc_fontspec_clean(glyph->fontspec); free(glyph->fontspec); cc_flw_done_glyph(glyph->fontidx, glyph->glyphidx); cc_flw_unref_font(glyph->fontidx); free(glyph); } /* ********************************************************************** */ 0 #include using namespace std; typedef struct node { int data; node* next; node* prev; }*list; list head; list tail; int batas; void initData() { head = NULL; tail = NULL; } int cekHead() { return (head == NULL) ? 1 : 0; } void tampilList() { list bantu; if (cekHead() == 1) { cout << "Data Masih Kosong"; } else { bantu = head; for (int x = 1; x <= batas; x++) { cout << "Data Ke-" << x << " : " << bantu->data << endl; bantu = bantu->next; } } } void hapusDepan(); void hapusBelakang(); void hapusData(int nomor) { list bantu; if (cekHead() == 1) { system("cls"); cout << "Data Masih Kosong\n\n"; system("pause"); system("cls"); } else { if (nomor == 1) { hapusDepan(); } else if (nomor == batas) { hapusBelakang(); } else if ((nomor > batas) || (nomor < 0)) { system("cls"); cout << "No Urutan Tidak Ditemukan\n\n"; system("pause"); system("cls"); } else { bantu = head; for (int x = 1; x < nomor; x++) { bantu = bantu->next; } bantu->prev->next = bantu->next; bantu->next->prev = bantu->prev; delete bantu; batas--; system("cls"); cout << "Data Ke-" << nomor << " Telah Dihapus\n\n"; system("pause"); system("cls"); } } } void hapusDepan() { list bantu; if (cekHead() == 1) { system("cls"); cout << "Data Masih Kosong\n\n"; system("pause"); system("cls"); } else { bantu = head; head = head->next; head->prev = NULL; delete bantu; batas--; system("cls"); cout << "Data Depan Telah Dihapus\n\n"; system("pause"); system("cls"); } } void hapusBelakang() { list bantu; if (cekHead() == 1) { system("cls"); cout << "Data Masih Kosong\n\n"; system("pause"); system("cls"); } else { bantu = tail; tail = tail->prev; tail->next = NULL; delete bantu; batas--; system("cls"); cout << "Data Belakang Telah Dihapus\n\n"; system("pause"); system("cls"); } } void hapusSebelumNode(int nomor) { list bantu; if (cekHead() == 1) { system("cls"); cout << "Data Masih Kosong\n\n"; system("pause"); system("cls"); } else { if (nomor == 1) { system("cls"); cout << "Tidak Ada Data Sebelum Data Tersebut\n\n"; system("pause"); system("cls"); } else if (nomor == 2) { hapusDepan(); } else if ((nomor > batas) || (nomor < 0)) { system("cls"); cout << "No Urutan Tidak Ditemukan\n\n"; system("pause"); system("cls"); } else { bantu = head; for (int x = 1; x < nomor - 1; x++) { bantu = bantu->next; } bantu->prev->next = bantu->next; bantu->next->prev = bantu->prev; delete bantu; batas--; system("cls"); cout << "Data Sebelum Ke-" << nomor << " Telah Dihapus\n\n"; system("pause"); system("cls"); } } } void hapusSetelahNode(int nomor) { list bantu; if (cekHead() == 1) { system("cls"); cout << "Data Masih Kosong\n\n"; system("pause"); system("cls"); } else { if (nomor == batas) { system("cls"); cout << "Tidak Ada Data Setelah Data Tersebut\n\n"; system("pause"); system("cls"); } else if ((nomor > batas) || (nomor < 0)) { system("cls"); cout << "No Urutan Tidak Ditemukan\n\n"; system("pause"); system("cls"); } else { bantu = head; for (int x = 1; x <= nomor; x++) { bantu = bantu->next; } bantu->prev->next = bantu->next; bantu->next->prev = bantu->prev; delete bantu; system("cls"); cout << "Data Setelah Ke-" << nomor << " Telah Dihapus\n\n"; system("pause"); system("cls"); batas--; } } } void hapusSemua() { list bantu; list hapus; if (cekHead() == 1) { system("cls"); cout << "Data Masih Kosong\n\n"; system("pause"); system("cls"); } else { bantu = head; while (bantu != NULL) { hapus = bantu; bantu = bantu->next; delete hapus; } head = NULL; tail = NULL; system("cls"); cout << "Semua Data Telah Terhapus\n\n"; system("pause"); system("cls"); batas = 0; } } void dataDepan(list insert); void gantiData(list insert, int nomor) { list bantu; bantu = new node; if (cekHead() == 1) { dataDepan(insert); } else { if (nomor == 1) { bantu = head; insert->next = bantu->next; bantu->next->prev = insert; insert->prev = NULL; head = insert; delete bantu; system("cls"); cout << "Data Ke-" << nomor << " Telah Diganti\n\n"; system("pause"); system("cls"); } else if (nomor == batas) { bantu = tail; bantu->prev->next = insert; insert->prev = bantu->prev; insert->next = NULL; tail = insert; delete bantu; system("cls"); cout << "Data Ke-" << nomor << " Telah Diganti\n\n"; system("pause"); system("cls"); } else if ((nomor > batas) || (nomor < 0)) { system("cls"); cout << "No Urutan Tidak Ditemukan\n\n"; system("pause"); system("cls"); } else { bantu = head; for (int x = 1; x < nomor; x++) { bantu = bantu->next; } bantu->prev->next = insert; insert->prev = bantu->prev; insert->next = bantu->next; bantu->next->prev = insert; delete bantu; system("cls"); cout << "Data Ke-" << nomor << " Telah Diganti\n\n"; system("pause"); system("cls"); } } } void dataDepan(list insert) { if (cekHead() == 1) { head = insert; head->next = NULL; head->prev = NULL; } else { insert->next = head; head->prev = insert; head = insert; head->prev = NULL; } batas++; system("cls"); cout << "Data Telah Ditambahkan Di Depan\n\n"; system("pause"); system("cls"); } void dataBelakang(list insert) { if (cekHead() == 1) { dataDepan(insert); } else { tail->next = insert; insert->prev = tail; tail = insert; tail->next = NULL; } batas++; system("cls"); cout << "Data Telah Ditambahkan Di Belakang\n\n"; system("pause"); system("cls"); } void DataSebelumNode(list insert, int nomor) { list bantu; if (cekHead() == 1) { dataDepan(insert); } else { if (nomor == 1) { dataDepan(insert); } else if ((nomor > batas) || (nomor < 0)) { system("cls"); cout << "No Urutan Tidak Ditemukan\n\n"; system("pause"); system("cls"); } else { bantu = head; for (int x = 1; x < nomor; x++) { bantu = bantu->next; } bantu->prev->next = insert; insert->prev = bantu->prev; insert->next = bantu; bantu->prev = insert; batas++; system("cls"); cout << "Data Telah Ditambahkan Sebelum Data Ke-" << nomor << "\n\n"; system("pause"); system("cls"); } } } void DataSetelahNode(list insert, int nomor) { list bantu; if (cekHead() == 1) { dataDepan(insert); } else { if (nomor == batas) { dataBelakang(insert); } else if ((nomor > batas) || (nomor < 0)) { system("cls"); cout << "No Urutan Tidak Ditemukan\n\n"; system("pause"); system("cls"); } else { bantu = head; for (int x = 1; x <= nomor; x++) { bantu = bantu->next; } bantu->prev->next = insert; insert->prev = bantu->prev; insert->next = bantu; bantu->prev = insert; batas++; system("cls"); cout << "Data Telah Ditambahkan Setelah Data Ke-" << nomor << "\n\n"; system("pause"); system("cls"); } } } void SalahMemasukkan() { system("cls"); cout << "Anda Salah Memasukkan Input\n\n"; system("pause"); } void KeluarProgram() { system("cls"); cout << "Anda Keluar Program \n\n"; system("pause"); } int main() { initData(); list n, bantu; bantu = new node; do { unsigned short int pilihan, urutan; int data; system("cls"); cout << "Program Double Linked List Not Circular\n\n"; system("pause"); system("cls"); cout << "Apakah anda ingin melanjutkan ? \n1. Iya\n2. Tidak\n\nPilihan: "; cin >> pilihan; switch (pilihan) { case 1: system("cls"); cout << "Masukkan Jumlah Data: "; cin >> batas; system("cls"); for (int x = 1; x <= batas; x++) { if (x == 1) { cout << "Data Ke-" << x << "\n\n"; cout << "Masukkan Data: "; cin >> data; n = new node; n->data = data; n->prev = NULL; head = bantu = n; cout << "\n\nData Telah Masuk Ke Data Store\n\n"; system("pause"); system("cls"); } else if (x == batas) { cout << "Data Ke-" << x << "\n\n"; cout << "Masukkan Data: "; cin >> data; n = new node; n->data = data; bantu->next = n; n->prev = bantu; n->next = NULL; tail = n; bantu = head; cout << "\n\nData Telah Masuk Ke Data Store\n\n"; system("pause"); system("cls"); } else { cout << "Data Ke-" << x << "\n\n"; cout << "Masukkan Data: "; cin >> data; n = new node; n->data = data; bantu->next = n; n->prev = bantu; bantu = bantu->next; cout << "\n\nData Telah Masuk Ke Data Store\n\n"; system("pause"); system("cls"); } } do { cout << "Pengoperasian Data \n\n1. Tampilkan Data\n2. Hapus Data Menurut Urutan\n3. Hapus Data Depan \n4. Hapus Data Belakang\n5. Hapus Data Sebelum Urutan\n6. Hapus Data Setelah Urutan\n7. Hapus Semua Data\n8. Ganti Data\n9. Input Data Depan\n10. Input Data Belakang\n11. Input Data Sebelum Urutan\n12. Input Data Setelah Urutan\n13. Keluar Program\n\nPilihan: "; cin >> pilihan; switch (pilihan) { case 1: system("cls"); tampilList(); cout << endl << endl; system("pause"); system("cls"); break; case 2: system("cls"); tampilList(); cout << endl << endl; cout << "Masukkan Nomor Urutan: "; cin >> urutan; hapusData(urutan); break; case 3: system("cls"); hapusDepan(); break; case 4: system("cls"); hapusBelakang(); break; case 5: system("cls"); tampilList(); cout << endl << endl; cout << "Masukkan Nomor Urutan: "; cin >> urutan; hapusSebelumNode(urutan); break; case 6: system("cls"); tampilList(); cout << endl << endl; cout << "Masukkan Nomor Urutan: "; cin >> urutan; hapusSetelahNode(urutan); break; case 7: system("cls"); hapusSemua(); break; case 8: system("cls"); tampilList(); cout << endl << endl; cout << "Masukkan Nomor Urutan: "; cin >> urutan; cout << "Masukkan Data Baru: "; cin >> data; n = new node; n->data = data; gantiData(n, urutan); break; case 9: system("cls"); cout << "Masukkan Data: "; cin >> data; n = new node; n->data = data; dataDepan(n); break; case 10: system("cls"); system("cls"); cout << "Masukkan Data: "; cin >> data; n = new node; n->data = data; dataBelakang(n); break; case 11: system("cls"); system("cls"); tampilList(); cout << endl << endl; cout << "Masukkan Nomor Urutan: "; cin >> urutan; cout << "Masukkan Data: "; cin >> data; n = new node; n->data = data; DataSebelumNode(n, urutan); break; case 12: system("cls"); system("cls"); tampilList(); cout << endl << endl; cout << "Masukkan Nomor Urutan: "; cin >> urutan; cout << "Masukkan Data: "; cin >> data; n = new node; n->data = data; DataSetelahNode(n, urutan); break; case 13: KeluarProgram(); return 0; break; default: SalahMemasukkan(); return 0; break; } } while (true); case 2: KeluarProgram(); return 0; default: SalahMemasukkan(); return 0; } } while (true); } 0 // 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 #include "SurfaceQueue.inl" // // Notes about the synchronization: It's important for this library // to be reasonably parallel; it should be possible to have simultaneously // enqueues/dequeues. It is undesirable for a thread to grab the queue // lock while it calls into a blocking or very time consuming DirectX API. // // The single threaded flag will disable the synchronization constructs. // // There are 4 synchronization primitives used in this library. // 1) Critical Section in CSurfaceProducer/CSurfaceConsumer that protects // simultaneous access to their apis (Enqueue&Flush/Dequeue). The public // functions from those objects are not designed to be multithreaded. It // is not designed to support, for example, simultaneous Enqueues to the same // queue. This lock guarantees that the Queue can not have simultaneous Enqueues // and Flushes. There are a few CSurfaceQueue member variables that are shared // ONLY between Enqueue and Flush and do not need to be protected in CSurfaceQueue. // 2) A Semaphore to control waiting when the Queue is empty. The semaphore is // released on Enqueue/Flush and is waited on in Dequeue. // 3) A SlimReaderWriter lock protecting the CSurfaceQueue object. All of the // high frequency calls grab shared locks (Enqueue/Flush/Dequeue) to allow // parallel access to the queue. The low frequency state changes // (i.e. OpenProducer) will grab an exclusive lock. // 4) A critical section protecting the underlying circular queue. Both Enqueue // and dequeue will contend for this lock but the duration the lock is held // is kept to a minimum. // //----------------------------------------------------------------------------- // Helper Functions //----------------------------------------------------------------------------- HRESULT CreateDeviceWrapper(IUnknown* pUnknown, ISurfaceQueueDevice** ppDevice) { IDirect3DDevice9Ex* pD3D9Device = nullptr; ID3D10Device* pD3D10Device = nullptr; ID3D11Device* pD3D11Device = nullptr; HRESULT hr = S_OK; *ppDevice = NULL; if (SUCCEEDED(pUnknown->QueryInterface(__uuidof(IDirect3DDevice9Ex), (void**)&pD3D9Device))) { pD3D9Device->Release(); *ppDevice = new QUEUE_NOTHROW_SPECIFIER CSurfaceQueueDeviceD3D9(pD3D9Device); } else if (SUCCEEDED(pUnknown->QueryInterface(__uuidof(ID3D10Device), (void**)&pD3D10Device))) { pD3D10Device->Release(); *ppDevice = new QUEUE_NOTHROW_SPECIFIER CSurfaceQueueDeviceD3D10(pD3D10Device); } else if (SUCCEEDED(pUnknown->QueryInterface(__uuidof(ID3D11Device), (void**)&pD3D11Device))) { pD3D11Device->Release(); *ppDevice = new QUEUE_NOTHROW_SPECIFIER CSurfaceQueueDeviceD3D11(pD3D11Device); } else { hr = E_INVALIDARG; } if (SUCCEEDED(hr) && *ppDevice == NULL) { hr = E_OUTOFMEMORY; } return hr; }; //----------------------------------------------------------------------------- // SharedSurfaceObject Implementation //----------------------------------------------------------------------------- SharedSurfaceObject::SharedSurfaceObject(UINT Width, UINT Height, DXGI_FORMAT Format) { hSharedHandle = NULL; state = SHARED_SURFACE_STATE_UNINITIALIZED; queue = NULL; width = Width; height = Height; format = Format; pSurface = NULL; } SharedSurfaceObject::~SharedSurfaceObject() { // Release the reference to the created surface if (pSurface) { pSurface->Release(); } } //----------------------------------------------------------------------------- // CreateSurfaceQueue //----------------------------------------------------------------------------- HRESULT WINAPI CreateSurfaceQueue( SURFACE_QUEUE_DESC* pDesc, IUnknown* pDevice, ISurfaceQueue** ppQueue) { HRESULT hr = E_FAIL; if (ppQueue == NULL) { return E_INVALIDARG; } *ppQueue = NULL; if (pDesc == NULL) { return E_INVALIDARG; } if (pDevice == NULL) { return E_INVALIDARG; } if (pDesc->NumSurfaces == 0) { return E_INVALIDARG; } if (pDesc->Width == 0 || pDesc->Height == 0) { return E_INVALIDARG; } if (pDesc->Flags != 0 && pDesc->Flags != SURFACE_QUEUE_FLAG_SINGLE_THREADED) { return E_INVALIDARG; } CSurfaceQueue* pSurfaceQueue = new QUEUE_NOTHROW_SPECIFIER CSurfaceQueue(); if (!pSurfaceQueue) { hr = E_OUTOFMEMORY; goto end; } hr = pSurfaceQueue->Initialize(pDesc, pDevice, pSurfaceQueue); if (FAILED(hr)) { goto end; } hr = pSurfaceQueue->QueryInterface(__uuidof(ISurfaceQueue), (void**)ppQueue); end: if (FAILED(hr)) { if (pSurfaceQueue) { delete pSurfaceQueue; } *ppQueue = NULL; } return hr; } //----------------------------------------------------------------------------- // CSurfaceConsumer implementation //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- CSurfaceConsumer:: CSurfaceConsumer(BOOL IsMultithreaded) : m_RefCount(0), m_IsMultithreaded(IsMultithreaded), m_pQueue(NULL), m_pDevice(NULL) { if (m_IsMultithreaded) { InitializeCriticalSection(&m_lock); } } //----------------------------------------------------------------------------- CSurfaceConsumer::~CSurfaceConsumer() { if (m_pQueue) { m_pQueue->RemoveConsumer(); m_pQueue->Release(); } if (m_pDevice) { delete m_pDevice; } if (m_IsMultithreaded) { DeleteCriticalSection(&m_lock); } } //----------------------------------------------------------------------------- HRESULT CSurfaceConsumer::Initialize(IUnknown* pDevice) { ASSERT(pDevice); ASSERT(m_pDevice == NULL); HRESULT hr; hr = CreateDeviceWrapper(pDevice, &m_pDevice); if (FAILED(hr)) { if (m_pDevice) { delete m_pDevice; m_pDevice = NULL; } } return hr; } //----------------------------------------------------------------------------- void CSurfaceConsumer::SetQueue(CSurfaceQueue* queue) { ASSERT(!m_pQueue && queue); if (NULL != m_pQueue || NULL == queue) { return; } m_pQueue = queue; m_pQueue->AddRef(); } //----------------------------------------------------------------------------- HRESULT CSurfaceConsumer::Dequeue( REFIID id, IUnknown** ppSurface, void* pBuffer, UINT* BufferSize, DWORD dwTimeout) { ASSERT(m_pQueue); if (NULL == m_pQueue) { return E_FAIL; } HRESULT hr = S_OK; if (m_IsMultithreaded) { EnterCriticalSection(&m_lock); } // Validate that REFIID is correct for a surface from this device if (!m_pDevice->ValidateREFIID(id)) { hr = E_INVALIDARG; goto end; } if (ppSurface == NULL) { hr = E_INVALIDARG; goto end; } *ppSurface = NULL; // Forward to queue hr = m_pQueue->Dequeue(ppSurface, pBuffer, BufferSize, dwTimeout); end: if (m_IsMultithreaded) { LeaveCriticalSection(&m_lock); } return hr; } //----------------------------------------------------------------------------- // CSurfaceProducer implementation //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- CSurfaceProducer:: CSurfaceProducer(BOOL IsMultithreaded) : m_RefCount(0), m_IsMultithreaded(IsMultithreaded), m_pQueue(NULL), m_pDevice(NULL), m_nStagingResources(0), m_pStagingResources(NULL), m_uiStagingResourceHeight(0), m_uiStagingResourceWidth(0), m_iCurrentResource(0) { if (m_IsMultithreaded) { InitializeCriticalSection(&m_lock); } } //----------------------------------------------------------------------------- CSurfaceProducer::~CSurfaceProducer() { if (m_pQueue) { m_pQueue->RemoveProducer(); m_pQueue->Release(); } if (m_pStagingResources) { for (UINT i = 0; i < m_nStagingResources; i++) { if (m_pStagingResources[i]) { m_pStagingResources[i]->Release(); } } delete[] m_pStagingResources; } if (m_pDevice) { delete m_pDevice; } if (m_IsMultithreaded) { DeleteCriticalSection(&m_lock); } } //----------------------------------------------------------------------------- void CSurfaceProducer::SetQueue(CSurfaceQueue* queue) { ASSERT(!m_pQueue && queue); if (NULL != m_pQueue || NULL == queue) { return; } m_pQueue = queue; m_pQueue->AddRef(); } //----------------------------------------------------------------------------- HRESULT CSurfaceProducer::Initialize(IUnknown* pDevice, UINT uNumSurfaces, SURFACE_QUEUE_DESC* queueDesc) { ASSERT(pDevice); ASSERT(!m_pStagingResources && m_nStagingResources == 0) HRESULT hr = S_OK; hr = CreateDeviceWrapper(pDevice, &m_pDevice); if (FAILED(hr)) { goto end; } m_pStagingResources = new QUEUE_NOTHROW_SPECIFIER IUnknown*[uNumSurfaces]; if (!m_pStagingResources) { hr = E_OUTOFMEMORY; goto end; } ZeroMemory(m_pStagingResources, sizeof(IUnknown*) * uNumSurfaces); m_nStagingResources = uNumSurfaces; // Determine the size of the staging resource in case the queue surface is less than SHARED_SURFACE_COPY_SIZE m_uiStagingResourceWidth = min(queueDesc->Width, SHARED_SURFACE_COPY_SIZE); m_uiStagingResourceHeight = min(queueDesc->Height, SHARED_SURFACE_COPY_SIZE); // Create the staging resources for (UINT i = 0; i < m_nStagingResources; i++) { if (FAILED(hr = m_pDevice->CreateCopyResource(queueDesc->Format, m_uiStagingResourceWidth, m_uiStagingResourceHeight, &(m_pStagingResources[i])))) { goto end; } } end: if (FAILED(hr)) { if (m_pStagingResources) { for (UINT i = 0; i < m_nStagingResources; i++) { if (m_pStagingResources[i]) { m_pStagingResources[i]->Release(); } } delete[] m_pStagingResources; m_pStagingResources = NULL; m_nStagingResources = 0; } if (m_pDevice) { delete m_pDevice; m_pDevice = NULL; } } return hr; } //----------------------------------------------------------------------------- HRESULT CSurfaceProducer::Enqueue( IUnknown* pSurface, void* pBuffer, UINT BufferSize, DWORD Flags ) { // // This function essentially does simple error checking and then // forwards the call to the queue object. The SurfaceProducer // maintains a circular buffer of staging resources to use and will // pass the next availible one to the queue. // ASSERT(m_pQueue); if (NULL == m_pQueue) { return E_FAIL; } if (m_IsMultithreaded) { EnterCriticalSection(&m_lock); } HRESULT hr; if (m_pDevice == NULL) { hr = E_INVALIDARG; goto end; } if (!pSurface) { hr = E_INVALIDARG; goto end; } if (Flags && Flags != SURFACE_QUEUE_FLAG_DO_NOT_WAIT) { hr = E_INVALIDARG; goto end; } // Forward call to queue hr = m_pQueue->Enqueue( pSurface, pBuffer, BufferSize, Flags, m_pStagingResources[m_iCurrentResource], m_uiStagingResourceWidth, m_uiStagingResourceHeight ); if (hr == DXGI_ERROR_WAS_STILL_DRAWING) { // // Increment the staging resource only if the current one is still // being used. This only happens if the function returns with // DXGI_ERROR_WAS_STILL_DRAWING indicating that a future flush // will still need the resource // // We do not need to worry about wrapping around and reusing staging // surfaces that are currently in use. The design of the queue makes // it invalid to enqueue when the queue is already full. If the user // does that, the queue will fail the call with E_INVALIDARG. m_iCurrentResource = (m_iCurrentResource + 1) % m_nStagingResources; } end: if (m_IsMultithreaded) { LeaveCriticalSection(&m_lock); } return hr; } //----------------------------------------------------------------------------- HRESULT CSurfaceProducer::Flush( DWORD Flags, UINT* NumSurfaces ) { ASSERT(m_pQueue); if (NULL == m_pQueue) { return E_FAIL; } if (m_IsMultithreaded) { EnterCriticalSection(&m_lock); } HRESULT hr; if (m_pDevice == NULL) { hr = E_INVALIDARG; goto end; } if (Flags && Flags != SURFACE_QUEUE_FLAG_DO_NOT_WAIT) { hr = E_INVALIDARG; goto end; } // Forward call to queue hr = m_pQueue->Flush(Flags, NumSurfaces); end: if (m_IsMultithreaded) { LeaveCriticalSection(&m_lock); } return hr; } //----------------------------------------------------------------------------- // CSurfaceQueue implementation //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- CSurfaceQueue:: CSurfaceQueue() : m_RefCount(0), m_IsMultithreaded(TRUE), m_hSemaphore(NULL), m_pRootQueue(NULL), m_NumQueuesInNetwork(0), m_pConsumer(NULL), m_pProducer(NULL), m_pCreator(NULL), m_SurfaceQueue(NULL), m_QueueHead(0), m_QueueSize(0), m_ConsumerSurfaces(NULL), m_CreatedSurfaces(NULL), m_iEnqueuedHead(0), m_nEnqueuedSurfaces(0) { } //----------------------------------------------------------------------------- CSurfaceQueue::~CSurfaceQueue() { Destroy(); } //----------------------------------------------------------------------------- void CSurfaceQueue::Destroy() { RemoveQueueFromNetwork(); // The ref counting should guarantee that the root queue object // is the last to be deleted if (m_pRootQueue != this) { m_pRootQueue->Release(); } else { ASSERT(m_NumQueuesInNetwork == 0); } // The root queue will destroy the creating device if (m_pCreator) { delete m_pCreator; m_pCreator = NULL; } // Release all opened surfaces if (m_ConsumerSurfaces) { for (UINT i = 0; i < m_Desc.NumSurfaces; i++) { if (m_ConsumerSurfaces[i].pSurface) { m_ConsumerSurfaces[i].pSurface->Release(); } } delete[] m_ConsumerSurfaces; m_ConsumerSurfaces = NULL; } // Clean up the allocated meta data buffers if (m_SurfaceQueue) { for (UINT i = 0; i < m_Desc.NumSurfaces; i++) { if (m_SurfaceQueue[i].pMetaData) { delete[] m_SurfaceQueue[i].pMetaData; } } delete[] m_SurfaceQueue; m_SurfaceQueue = NULL; } // The root queue object created the surfaces. All other queue // objects only have a reference. if (m_CreatedSurfaces) { for (UINT i = 0; i < m_Desc.NumSurfaces; i++) { if (m_pRootQueue == this && m_CreatedSurfaces[i]) { delete m_CreatedSurfaces[i]; } m_CreatedSurfaces[i] = NULL; } delete[] m_CreatedSurfaces; m_CreatedSurfaces = NULL; } m_pConsumer = NULL; m_pProducer = NULL; if (m_IsMultithreaded) { if (m_hSemaphore) { CloseHandle(m_hSemaphore); m_hSemaphore = NULL; } DeleteCriticalSection(&m_QueueLock); } else { m_nFlushedSurfaces = 0; } } //----------------------------------------------------------------------------- ISurfaceQueueDevice* CSurfaceQueue::GetCreatorDevice() { return m_pRootQueue->m_pCreator; } //----------------------------------------------------------------------------- UINT CSurfaceQueue::GetNumQueuesInNetwork() { return m_pRootQueue->m_NumQueuesInNetwork; } //----------------------------------------------------------------------------- UINT CSurfaceQueue::AddQueueToNetwork() { if (m_pRootQueue == this) { return InterlockedIncrement(&m_NumQueuesInNetwork); } else { return m_pRootQueue->AddQueueToNetwork(); } } //----------------------------------------------------------------------------- UINT CSurfaceQueue::RemoveQueueFromNetwork() { ASSERT(GetNumQueuesInNetwork() > 0); if (m_pRootQueue == this) { return InterlockedDecrement(&m_NumQueuesInNetwork); } else { return m_pRootQueue->RemoveQueueFromNetwork(); } } //----------------------------------------------------------------------------- SharedSurfaceObject* CSurfaceQueue::GetSurfaceObjectFromHandle(HANDLE handle) { // // This does a linear search through the created surfaces for the specific // handle. When the user enqueues, we get the shared handle from surface // and then use the handle to get to the SharedSurfaceObject. This essentially // converts from a "generic d3d surface" to a "surface queue surface". // // This search is linear with the number of surfaces created. We expect that // number to be small. // ASSERT(handle); ASSERT(m_CreatedSurfaces); if (NULL == handle || NULL == m_CreatedSurfaces) { return NULL; } for (UINT i = 0; i < m_Desc.NumSurfaces; i++) { if (m_CreatedSurfaces[i]->hSharedHandle == handle) { return m_CreatedSurfaces[i]; } } // The user tried to enqueue an shared surface that was not part of the queue. return NULL; } //----------------------------------------------------------------------------- IUnknown* CSurfaceQueue::GetOpenedSurface(const SharedSurfaceObject* pObject) const { // // On OpenConsumer, all of the shared surfaces will be opened by the consuming // device and cached. On dequeue, we simply look in the cache and return the // appropriate surface, getting a significant perf bonus over opening/closing // the surface on every dequeue/enqueue. // // This method is also linear with respect to the number of surfaces and a more // scalable data structure can be used if the number of surfaces is used. // ASSERT(pObject); ASSERT(m_ConsumerSurfaces); if (NULL == pObject || NULL == m_ConsumerSurfaces) { return NULL; } for (UINT i = 0; i < m_Desc.NumSurfaces; i++) { if (m_ConsumerSurfaces[i].pObject == pObject) { return m_ConsumerSurfaces[i].pSurface; } } return NULL; } //----------------------------------------------------------------------------- HRESULT CSurfaceQueue::AllocateMetaDataBuffers() { // This function allocates the meta data buffers during creation time. if (m_Desc.MetaDataSize != 0) { for (UINT i = 0; i < m_Desc.NumSurfaces; i++) { m_SurfaceQueue[i].pMetaData = new QUEUE_NOTHROW_SPECIFIER BYTE[m_Desc.MetaDataSize]; if (m_SurfaceQueue[i].pMetaData == NULL) { return E_OUTOFMEMORY; } } } return S_OK; } //----------------------------------------------------------------------------- HRESULT CSurfaceQueue::CreateSurfaces() { // // This function is only called by the root queue to create the surfaces. // The queue has the property that the root queue starts off full (all the // surfaces on it are ready for dequeue. This function will use the creating // device to create the shared surfaces and initialize them for dequeue. // HRESULT hr = S_OK; ASSERT(m_pRootQueue == this); for (UINT i = 0; i < m_Desc.NumSurfaces; i++) { SharedSurfaceObject* pSurfaceObject = new QUEUE_NOTHROW_SPECIFIER SharedSurfaceObject(m_Desc.Width, m_Desc.Height, m_Desc.Format); if (!pSurfaceObject) { return E_OUTOFMEMORY; } m_CreatedSurfaces[i] = pSurfaceObject; if (FAILED(hr = m_pCreator->CreateSharedSurface( m_Desc.Width, m_Desc.Height, m_Desc.Format, &(pSurfaceObject->pSurface), &(pSurfaceObject->hSharedHandle) ))) { return hr; } // Important to note that created surfaces start in the flushed state. This // lets the system start in a state that makes it ready to go. m_SurfaceQueue[i].surface = m_CreatedSurfaces[i]; m_SurfaceQueue[i].surface->state = SHARED_SURFACE_STATE_FLUSHED; m_SurfaceQueue[i].surface->queue = this; } return S_OK; } //----------------------------------------------------------------------------- void CSurfaceQueue::CopySurfaceReferences(CSurfaceQueue* pRootQueue) { // This is called by cloned devices. They simply take a reference // to the shared created surfaces. ASSERT(m_pRootQueue != this); for (UINT i = 0; i < m_Desc.NumSurfaces; i++) { m_CreatedSurfaces[i] = pRootQueue->m_CreatedSurfaces[i]; } } //----------------------------------------------------------------------------- HRESULT CSurfaceQueue::Initialize(SURFACE_QUEUE_DESC* pDesc, IUnknown* pDevice, CSurfaceQueue* pRootQueue) { ASSERT(pDesc); ASSERT(pRootQueue); if (NULL == pDesc || NULL == pRootQueue) { return E_FAIL; } HRESULT hr = S_OK; m_Desc = *pDesc; m_pRootQueue = pRootQueue; m_IsMultithreaded = !(m_Desc.Flags & SURFACE_QUEUE_FLAG_SINGLE_THREADED); AddQueueToNetwork(); if (m_IsMultithreaded) { InitializeCriticalSection(&m_QueueLock); } // Allocate Queue ASSERT(!m_SurfaceQueue); m_SurfaceQueue = new QUEUE_NOTHROW_SPECIFIER SharedSurfaceQueueEntry[pDesc->NumSurfaces]; if (!m_SurfaceQueue) { hr = E_OUTOFMEMORY; goto cleanup; } ZeroMemory(m_SurfaceQueue, sizeof(SharedSurfaceQueueEntry) * pDesc->NumSurfaces); // Allocate array to keep track of opened surfaces ASSERT(!m_ConsumerSurfaces); m_ConsumerSurfaces = new QUEUE_NOTHROW_SPECIFIER SharedSurfaceOpenedMapping[pDesc->NumSurfaces]; if (!m_ConsumerSurfaces) { hr = E_OUTOFMEMORY; goto cleanup; } ZeroMemory(m_ConsumerSurfaces, sizeof(SharedSurfaceOpenedMapping) * pDesc->NumSurfaces); // Allocate created surface tracking list ASSERT(!m_CreatedSurfaces); m_CreatedSurfaces = new QUEUE_NOTHROW_SPECIFIER SharedSurfaceObject*[pDesc->NumSurfaces]; if (!m_CreatedSurfaces) { hr = E_OUTOFMEMORY; goto cleanup; } ZeroMemory(m_CreatedSurfaces, sizeof(SharedSurfaceObject*) * pDesc->NumSurfaces); // If this is the root queue, create the surfaces if (m_pRootQueue == this) { ASSERT(pDevice); hr = CreateDeviceWrapper(pDevice, &m_pCreator); if (FAILED(hr)) { ASSERT(m_pCreator == NULL); goto cleanup; } hr = CreateSurfaces(); if (FAILED(hr)) { goto cleanup; } m_QueueSize = pDesc->NumSurfaces; } else { // Increment the reference count on the src queue m_pRootQueue->AddRef(); CopySurfaceReferences(pRootQueue); m_QueueSize = 0; } if (m_Desc.MetaDataSize) { if (FAILED(hr = AllocateMetaDataBuffers())) { goto cleanup; } } ASSERT(m_pRootQueue); if (m_IsMultithreaded) { // Create Semaphore for queue synchronization m_hSemaphore = CreateSemaphore(NULL, m_pRootQueue == this ? pDesc->NumSurfaces : 0, pDesc->NumSurfaces, NULL); if (m_hSemaphore == NULL) { hr = HRESULT_FROM_WIN32(GetLastError()); goto cleanup; } // Initialize the slim reader/writer lock InitializeSRWLock(&m_lock); } else { m_nFlushedSurfaces = m_pRootQueue == this ? pDesc->NumSurfaces : 0; } cleanup: // The object will get destroyed if initialize fails. Cleanup // will happen then. return hr; } //----------------------------------------------------------------------------- HRESULT CSurfaceQueue::OpenConsumer( IUnknown* pDevice, ISurfaceConsumer** ppConsumer) { if (pDevice == NULL) { return E_INVALIDARG; } if (ppConsumer == NULL) { return E_INVALIDARG; } *ppConsumer = NULL; HRESULT hr = E_FAIL; if (m_IsMultithreaded) { AcquireSRWLockExclusive(&m_lock); } // // If a consumer exists, we need to bail early. The normal error // path will deallocate the current consumer. Instead this will // be a no-op for the queue and E_INVALIDARG will be returned. // if (m_pConsumer) { if (m_IsMultithreaded) { ReleaseSRWLockExclusive(&m_lock); } return E_INVALIDARG; } m_pConsumer = new QUEUE_NOTHROW_SPECIFIER CSurfaceConsumer(m_IsMultithreaded); if (m_pConsumer == NULL) { hr = E_OUTOFMEMORY; goto end; } hr = m_pConsumer->Initialize(pDevice); if (FAILED(hr)) { goto end; } // // For all the surfaces in the queue, we want to open it with the producing device. // This guarantees that surfaces are only open at creation time. // for (UINT i = 0; i < m_Desc.NumSurfaces; i++) { ASSERT(m_CreatedSurfaces[i]); ASSERT(m_ConsumerSurfaces); if (NULL == m_CreatedSurfaces[i] || NULL == m_ConsumerSurfaces) { return E_FAIL; } IUnknown* pSurface = NULL; hr = m_pConsumer->GetDevice()->OpenSurface( m_CreatedSurfaces[i]->hSharedHandle, (void**)&pSurface, m_Desc.Width, m_Desc.Height, m_Desc.Format); if (FAILED(hr)) { goto end; } ASSERT(pSurface); m_ConsumerSurfaces[i].pObject = m_CreatedSurfaces[i]; m_ConsumerSurfaces[i].pSurface = pSurface; } hr = m_pConsumer->QueryInterface(__uuidof(ISurfaceConsumer), (void**) ppConsumer); if (FAILED(hr)) { goto end; } m_pConsumer->SetQueue(this); end: if (FAILED(hr)) { *ppConsumer = NULL; if (m_pConsumer) { if (m_pConsumer->GetDevice()) { for (UINT i = 0; i < m_Desc.NumSurfaces; i++) { if (m_ConsumerSurfaces[i].pSurface) { m_ConsumerSurfaces[i].pSurface->Release(); } } } ZeroMemory(m_ConsumerSurfaces, sizeof(SharedSurfaceOpenedMapping) * m_Desc.NumSurfaces); delete m_pConsumer; m_pConsumer = NULL; } } if (m_IsMultithreaded) { ReleaseSRWLockExclusive(&m_lock); } return hr; } //----------------------------------------------------------------------------- HRESULT CSurfaceQueue::OpenProducer( IUnknown* pDevice, ISurfaceProducer** ppProducer) { if (pDevice == NULL) { return E_INVALIDARG; } if (ppProducer == NULL) { return E_INVALIDARG; } *ppProducer = NULL; HRESULT hr = E_FAIL; if (m_IsMultithreaded) { AcquireSRWLockExclusive(&m_lock); } if (m_pProducer) { if (m_IsMultithreaded) { ReleaseSRWLockExclusive(&m_lock); } return E_INVALIDARG; } m_pProducer = new QUEUE_NOTHROW_SPECIFIER CSurfaceProducer(m_IsMultithreaded); if (m_pProducer == NULL) { hr = E_OUTOFMEMORY; goto end; } hr = m_pProducer->Initialize(pDevice, m_Desc.NumSurfaces, &m_Desc); if (FAILED(hr)) { goto end; } hr = m_pProducer->QueryInterface(__uuidof(ISurfaceProducer), (void**)ppProducer); if (FAILED (hr)) { goto end; } m_pProducer->SetQueue(this); end: if (FAILED(hr)) { *ppProducer = NULL; if (m_pProducer) { delete m_pProducer; m_pProducer = NULL; *ppProducer = NULL; } } if (m_IsMultithreaded) { ReleaseSRWLockExclusive(&m_lock); } return hr; } //----------------------------------------------------------------------------- void CSurfaceQueue::RemoveProducer() { if (m_IsMultithreaded) { AcquireSRWLockExclusive(&m_lock); } ASSERT(m_pProducer); m_pProducer = NULL; if (m_IsMultithreaded) { ReleaseSRWLockExclusive(&m_lock); } } //----------------------------------------------------------------------------- void CSurfaceQueue::RemoveConsumer() { if (m_IsMultithreaded) { AcquireSRWLockExclusive(&m_lock); } ASSERT(m_pConsumer && m_pConsumer->GetDevice()); for (UINT i = 0; i < m_Desc.NumSurfaces; i++) { if (m_ConsumerSurfaces[i].pSurface) { m_ConsumerSurfaces[i].pSurface->Release(); } } ZeroMemory(m_ConsumerSurfaces, sizeof(SharedSurfaceOpenedMapping) * m_Desc.NumSurfaces); m_pConsumer = NULL; if (m_IsMultithreaded) { ReleaseSRWLockExclusive(&m_lock); } } //----------------------------------------------------------------------------- HRESULT CSurfaceQueue::Clone( SURFACE_QUEUE_CLONE_DESC* pDesc, ISurfaceQueue** ppQueue) { // Have all the clones originate from the root queue. This makes tracking // referenes easier. if (m_pRootQueue != this) { return m_pRootQueue->Clone(pDesc, ppQueue); } if (!pDesc) { return E_INVALIDARG; } if (!ppQueue) { return E_INVALIDARG; } if (pDesc->Flags != 0 && pDesc->Flags != SURFACE_QUEUE_FLAG_SINGLE_THREADED) { return E_INVALIDARG; } *ppQueue = NULL; HRESULT hr = E_FAIL; if (m_IsMultithreaded) { AcquireSRWLockExclusive(&m_lock); } SURFACE_QUEUE_DESC createDesc = m_Desc; createDesc.MetaDataSize = pDesc->MetaDataSize; createDesc.Flags = pDesc->Flags; CSurfaceQueue* pQueue = new QUEUE_NOTHROW_SPECIFIER CSurfaceQueue(); if (!pQueue) { hr = E_OUTOFMEMORY; goto end; } hr = pQueue->Initialize(&createDesc, NULL, this); if (FAILED(hr)) { goto end; } hr = pQueue->QueryInterface(__uuidof(ISurfaceQueue), (void**)ppQueue); end: if (FAILED(hr)) { if (pQueue) { delete pQueue; } *ppQueue = NULL; } if (m_IsMultithreaded) { ReleaseSRWLockExclusive(&m_lock); } return hr; } //----------------------------------------------------------------------------- HRESULT CSurfaceQueue::Enqueue( IUnknown* pSurface, void* pBuffer, UINT BufferSize, DWORD Flags, IUnknown* pStagingResource, UINT width, UINT height ) { ASSERT( pSurface ); if (pBuffer && !BufferSize) { return E_INVALIDARG; } if (!pBuffer && BufferSize) { return E_INVALIDARG; } if (BufferSize > m_Desc.MetaDataSize) { return E_INVALIDARG; } HRESULT hr = E_FAIL; if (m_IsMultithreaded) { AcquireSRWLockShared(&m_lock); } ASSERT( m_pProducer ); SharedSurfaceQueueEntry QueueEntry; HANDLE hSharedHandle; SharedSurfaceObject* pSurfaceObject; // Require both the producer and consumer to be initialized. // This avoids a potential race condition if (!m_pProducer || !m_pConsumer) { hr = E_INVALIDARG; goto end; } // Check that the queue is not full. Enqueuing onto a full queue is // not a scenario that makes sense if (m_QueueSize == m_Desc.NumSurfaces) { hr = E_INVALIDARG; goto end; } // Get the SharedSurfaceObject from the surface hr = m_pProducer->GetDevice()->GetSharedHandle(pSurface, &hSharedHandle); if (FAILED(hr)) { goto end; } pSurfaceObject = GetSurfaceObjectFromHandle(hSharedHandle); // Validate that this surface is one that can be part of this queue if (pSurfaceObject == NULL) { hr = E_INVALIDARG; goto end; } if (pSurfaceObject->state != SHARED_SURFACE_STATE_DEQUEUED) { hr = E_INVALIDARG; goto end; } QueueEntry.surface = pSurfaceObject; QueueEntry.pMetaData = (BYTE*)pBuffer; QueueEntry.bMetaDataSize = BufferSize; QueueEntry.pStagingResource = NULL; // Copy a small portion of the surface onto the staging surface hr = m_pProducer->GetDevice()->CopySurface(pStagingResource, pSurface, width, height); if (FAILED(hr)) { goto end; } pSurfaceObject->state = SHARED_SURFACE_STATE_ENQUEUED; pSurfaceObject->queue = this; // // At this point we have succesfully issued the copy to the staging resource. // The surface will now must be added to the fifo queue either in the ENQUEUED // or FLUSHED state. // // // Do not attempt to flush the surfaces if the DO_NOT_WAIT flag was used. // In these cases, simply add the surface to the FIFO queue as an ENQUEUED surface. // // // Note: m_nEnqueuedSurfaces and m_iEnqueuedHead are protected by the lock in the // SurfaceProducer. This value is not shared between the Consumer and Producer and // therefore does not need any sychronization in the queue object. // if (Flags & SURFACE_QUEUE_FLAG_DO_NOT_WAIT) { // // The surface should go into the ENQUEUED but not FLUSHED state. // // // Queue the entry into the fifo queue along with the staging resource for it // QueueEntry.pStagingResource = pStagingResource; Enqueue(QueueEntry); m_nEnqueuedSurfaces++; // // Since the surface did not flush, set the return to DXGI_ERROR_WAS_STILL_DRAWING // and return. // hr = DXGI_ERROR_WAS_STILL_DRAWING; goto end; } else if (m_nEnqueuedSurfaces) { // // Enqueued was called without the DO_NOT_WAIT flag but there are enqueued surfaces // currently not flushed. First flush the existing surfaces and then perform the // current Enqueue. // hr = Flush(0, NULL); ASSERT(SUCCEEDED(hr)); } // // Force rendering to complete by locking the staging resource. // if (FAILED(hr = m_pProducer->GetDevice()->LockSurface(pStagingResource, Flags))) { goto end; } if (FAILED(hr = m_pProducer->GetDevice()->UnlockSurface(pStagingResource))) { goto end; } ASSERT(QueueEntry.pStagingResource == NULL); // // The call to lock the surface completed succesfully meaning the surface if flushed // and ready for dequeue. Mark the surface as such and add it to the fifo queue. // pSurfaceObject->state = SHARED_SURFACE_STATE_FLUSHED; m_iEnqueuedHead = (m_iEnqueuedHead + 1) % m_Desc.NumSurfaces; Enqueue(QueueEntry); if (m_IsMultithreaded) { // Increment the semaphore ReleaseSemaphore(m_hSemaphore, 1, NULL); } else { m_nFlushedSurfaces++; } end: if (m_IsMultithreaded) { ReleaseSRWLockShared(&m_lock); } return hr; } //----------------------------------------------------------------------------- HRESULT CSurfaceQueue::Dequeue( IUnknown** ppSurface, void* pBuffer, UINT* BufferSize, DWORD dwTimeout ) { if (!pBuffer && BufferSize) { return E_INVALIDARG; } if (pBuffer) { if (!BufferSize || *BufferSize == 0) { return E_INVALIDARG; } if (*BufferSize > m_Desc.MetaDataSize) { return E_INVALIDARG; } } if (m_IsMultithreaded) { AcquireSRWLockShared(&m_lock); } SharedSurfaceQueueEntry QueueElement; IUnknown* pSurface = NULL; HRESULT hr = E_FAIL; // Require both the producer and consumer to be initialized. // This avoids a potential race condition if (!m_pProducer || !m_pConsumer) { hr = E_INVALIDARG; goto end; } if (m_IsMultithreaded) { // Wait on the semaphore until the queue is not empty DWORD dwWait = WaitForSingleObject(m_hSemaphore, dwTimeout); switch (dwWait) { case WAIT_ABANDONED: hr = E_FAIL; break; case WAIT_OBJECT_0: hr = S_OK; break; case WAIT_TIMEOUT: hr = HRESULT_FROM_WIN32(WAIT_TIMEOUT); break; case WAIT_FAILED: hr = HRESULT_FROM_WIN32(GetLastError()); break; default: hr = E_FAIL; break; } } else { // In the single threaded case, dequeuing on an empty // will return immediately. The error returned is not // *exactly* right but it parallels the multithreaded // case. if (m_nFlushedSurfaces == 0) { hr = HRESULT_FROM_WIN32(WAIT_TIMEOUT); } else { m_nFlushedSurfaces--; hr = S_OK; } } // Early return because of timeout or wait error if (FAILED(hr)) { goto end; } // // At this point, there must be a surface in the queue ready to be // dequeued. Get a reference to the first surface make sure // it is valid. We don't want the situation where the surface is // removed but then fails. // // At this point there must be an surface in the queue ready to go // Dequeue it Front(QueueElement); ASSERT (QueueElement.surface->state == SHARED_SURFACE_STATE_FLUSHED); ASSERT (QueueElement.surface->queue == this); // // Update the state of the surface to dequeued // QueueElement.surface->state = SHARED_SURFACE_STATE_DEQUEUED; QueueElement.surface->device = m_pConsumer->GetDevice(); // // Get the surface for the consuming device from the surface object // pSurface = GetOpenedSurface(QueueElement.surface); ASSERT(pSurface); pSurface->AddRef(); *ppSurface = pSurface; // // There should be no more failures after here // if (pBuffer && QueueElement.bMetaDataSize) { memcpy(pBuffer, QueueElement.pMetaData, sizeof(BYTE) * QueueElement.bMetaDataSize); } // // Store the actual number of bytes copied as meta data. // if (BufferSize) { *BufferSize = QueueElement.bMetaDataSize; } // // Remove the element from the queue. We do it at the very end in case there are // errors. // Dequeue(QueueElement); end: if (m_IsMultithreaded) { ReleaseSRWLockShared(&m_lock); } return hr; } //----------------------------------------------------------------------------- HRESULT CSurfaceQueue::Flush( DWORD Flags, UINT* pRemainingSurfaces ) { if (m_IsMultithreaded) { AcquireSRWLockShared(&m_lock); } HRESULT hr = S_OK; UINT uiFlushedSurfaces = 0; UINT index, i; // Store this locally for the loop counter. The loop will change the // value of m_nEnqueuedSurfaces. UINT uiEnqueuedSize = m_nEnqueuedSurfaces; // Require both the producer and consumer to be initialized. // This avoids a potential race condition if (!m_pProducer || !m_pConsumer) { hr = E_INVALIDARG; goto end; } // Iterate over all queue entries starting at the head. for (index = m_iEnqueuedHead, i = 0; i < uiEnqueuedSize; i++, index++) { index = index % m_Desc.NumSurfaces; SharedSurfaceQueueEntry& queueEntry = m_SurfaceQueue[index]; ASSERT(queueEntry.surface->state == SHARED_SURFACE_STATE_ENQUEUED); ASSERT(queueEntry.surface->queue == this); ASSERT(queueEntry.pStagingResource); IUnknown* pStagingResource = queueEntry.pStagingResource; // // Attempt to lock the staging surface to see if the rendering // is complete. // hr = m_pProducer->GetDevice()->LockSurface(pStagingResource, Flags); if (FAILED(hr)) { // // As soon as the first surface is not flushed, skip the remaining // goto end; } hr = m_pProducer->GetDevice()->UnlockSurface(pStagingResource); ASSERT(SUCCEEDED(hr)); // When the lock is complete, rendering is complete and the the surface is // ready for dequeue queueEntry.surface->state = SHARED_SURFACE_STATE_FLUSHED; queueEntry.pStagingResource = NULL; uiFlushedSurfaces++; // This is protected by the SurfaceProducer lock. m_nEnqueuedSurfaces--; m_iEnqueuedHead = (m_iEnqueuedHead + 1) % m_Desc.NumSurfaces; if (m_IsMultithreaded) { // Increment the semaphore count ReleaseSemaphore(m_hSemaphore, 1, NULL); } else { m_nFlushedSurfaces++; } } end: if (pRemainingSurfaces) { *pRemainingSurfaces = m_nEnqueuedSurfaces; } if (m_IsMultithreaded) { ReleaseSRWLockShared(&m_lock); } return hr; } //----------------------------------------------------------------------------- void CSurfaceQueue::Front(SharedSurfaceQueueEntry& entry) { entry = m_SurfaceQueue[m_QueueHead]; } //----------------------------------------------------------------------------- void CSurfaceQueue::Dequeue(SharedSurfaceQueueEntry& entry) { // The semaphore protecting access to the queue guarantees that the queue // can not be empty. if (m_IsMultithreaded) { EnterCriticalSection(&m_QueueLock); } entry = m_SurfaceQueue[m_QueueHead]; m_QueueHead = (m_QueueHead + 1) % m_Desc.NumSurfaces; m_QueueSize--; if (m_IsMultithreaded) { LeaveCriticalSection(&m_QueueLock); } } //----------------------------------------------------------------------------- void CSurfaceQueue::Enqueue(SharedSurfaceQueueEntry& entry) { // // The validation in the queue should guarantee that the queue is not full // if (m_IsMultithreaded) { EnterCriticalSection(&m_QueueLock); } UINT end = (m_QueueHead + m_QueueSize) % m_Desc.NumSurfaces; m_QueueSize++; if (m_IsMultithreaded) { LeaveCriticalSection(&m_QueueLock); } m_SurfaceQueue[end].surface = entry.surface; m_SurfaceQueue[end].bMetaDataSize = entry.bMetaDataSize; m_SurfaceQueue[end].pStagingResource = entry.pStagingResource; if (entry.bMetaDataSize) { memcpy(m_SurfaceQueue[end].pMetaData, entry.pMetaData, sizeof(BYTE) * entry.bMetaDataSize); } } 1-10 // // Created by alexey on 26/05/2020. // #include #include "If.h" #include "../../../../memory/builtins/primitive/PyBool.h" #include "../../../../memory/builtins/PyCodeblock.h" #include "../../../../memory/builtins/primitive/PyInteger.h" #include "../../OptionalCodeblock.h" Operator *If::reduceWithFullContext(std::shared_ptr& right, std::shared_ptr& afterRight) { if (right->bt != BT_ROUND) { throw std::runtime_error("If expected round bracket expression"); } PyClass* afterRightClass = afterRight->getAsClass(); if (afterRightClass == nullptr || afterRightClass->type != pyCODE_BLOCK) { throw std::runtime_error("If expected code block"); } return new OptionalCodeblock((PyCodeblock*)afterRightClass, nullptr, std::static_pointer_cast(right)); } If::If() { precedence = 16; } Operator *If::reduce(PyClass *right, PyClass *afterRight) { return nullptr; } #include using namespace std; int main() { float C, K, R, F; cout<<"Masukkan suhu celcius : "; cin>>C; cout< using namespace std; int bananas; int apples; void eat_a(int num) { apples = apples - num; cout << num << " apples were eaten! Now you have " << apples << " apples." << endl; } void keep_a(int num) { apples = apples + num; cout << num << " apples have been kept! Now you have " << apples << " apples." << endl; } void askeat_a() { int eatnum; cout << "How many apples do you want to eat?" << endl; cin >> eatnum; eat_a(eatnum); } void askkeep_a() { int keepnum; cout << "How many apples do you want to keep?" << endl; cin >> keepnum; keep_a(keepnum); } void eat_b(int num) { bananas = bananas - num; cout << num << " bananas were eaten! Now you have " << bananas << " bananas." << endl; } void keep_b(int num) { bananas = bananas + num; cout << num << " bananas have been kept! Now you have " << bananas << " bananas." << endl; } void askeat_b() { int eatnum; cout << "How many banana's do you want to eat?" << endl; cin >> eatnum; eat_b(eatnum); } void askkeep_b() { int keepnum; cout << "How many banana's do you want to keep?" << endl; cin >> keepnum; keep_b(keepnum); } int main() { apples = 9; bananas = 10; while(1) { int a_or_b; cout << "Apples or bananas? (1 or 2)" << endl; cin >> a_or_b; if(a_or_b == 1) { int e_or_k_a; cout << "Eat or keep? (1 or 2)" << endl; cin >> e_or_k_a; if(e_or_k_a == 1) { askeat_a(); } else { askkeep_a(); } } else { int e_or_k_b; cout << "Eat or keep? (1 or 2)" << endl; cin >> e_or_k_b; if(e_or_k_b == 1) { askeat_b(); } else { askkeep_b(); } } } return 0; }#include "Utilities.hxx" #include "IfaceTeLICeMS.hxx" #include "TeLICeMService.hpp" #include "IfaceCellML_APISPEC.hxx" #include "CellMLBootstrap.hpp" #include #include #include #ifndef WIN32 #include #endif #include #include int main(int argc, char** argv) { if (argc < 2) { puts("Usage: TestTeLICeMParser uri\n"); return 1; } RETURN_INTO_OBJREF(ts, iface::cellml_services::TeLICeMService, CreateTeLICeMService()); struct stat statbuf; FILE* f = fopen(argv[1], "r"); if (f == NULL) { #ifdef WIN32 printf("Error opening file.\n"); #else printf("Error opening file: %s\n", strerror(errno)); #endif return 2; } fstat(fileno(f), &statbuf); char* buf = new char[statbuf.st_size + 1]; fread(buf, statbuf.st_size, 1, f); fclose(f); buf[statbuf.st_size] = 0; wchar_t* wcb = new wchar_t[statbuf.st_size + 1]; mbstowcs(wcb, buf, statbuf.st_size + 1); delete [] buf; RETURN_INTO_OBJREF(res, iface::cellml_services::TeLICeMModelResult, ts->parseModel(wcb)); delete [] wcb; RETURN_INTO_WSTRING(errmsg, res->errorMessage()); if (errmsg != L"") { fprintf(stderr, "TeLICeMS error message: %S\n", errmsg.c_str()); return 1; } RETURN_INTO_OBJREF(mod, iface::cellml_api::Model, res->modelResult()); RETURN_INTO_WSTRING(t, mod->serialisedText()); printf("%S\n", t.c_str()); return 0; } bfridkis/Fantasy-Creature-Battle-Game-CPP /********************************************************** ** Program name: Creature.cpp ** Author: ** Date: 5/16/2017 ** Description: Creature class implementation file. This is the abstract base class for various derived classes which will server as the basis for characters in fantasy battle game. The attributes common to all characters include armor and strength points, which are established here in the base class. ***********************************************************/ #include "Creature.hpp" /*************************************** getArmor Function to get member variable armor. ***************************************/ int Creature::getArmor() const { return armor; } /*********************************************** getStrengthPoints Function to get member variable strengthPoints. ************************************************/ int Creature::getStrengthPoints() const { return strengthPoints; } /************************************** getName Function to get member variable name. ****************************************/ string Creature::getName() const { return name; } /******************************************* getSName Function to get member variable sName. ("sName" denotes specific name, the user assigned name given during tournament play for project 4.) ********************************************/ string Creature::getSName() const { return sName; } /************************************** setArmor Function to set armor member variable. ***************************************/ void Creature::setArmor(int armor) { this->armor = armor; } /************************************************** setStartingStrPoints Function to set startingStrPoints member variable. ***************************************************/ void Creature::setStartingStrPoints (int startingStrPoints) { this->startingStrPoints = startingStrPoints; } /****************************************** setStrengthPoints Function to set armor member variable. *******************************************/ void Creature::setStrengthPoints (int strengthPoints) { this->strengthPoints = strengthPoints; } /************************************** setName Function to set member variable name. ***************************************/ void Creature::setName(string name) { this->name = name; } /*************************************** setSName Function to set member variable sName. ****************************************/ void Creature::setSName(string sName) { this->sName = sName; } /********************************************** restoreStrength Function to restore strength value after a victor is returned to the CreatureQueue (tournament play - project 4). There is a 1 in 5 chance the strength value is restored 0%, 1 in 5 chance the strength value is restored 25%, 1 in 5 chance the strength value is restored 50%, 1 in 5 chance the strength value is restored 75%, and a 1 in 5 chance the strength value is restored to 100% ***********************************************/ void Creature::restoreStrength() { int random = rand() % 5 + 1; //The restore value is calculated by //determining the deficit from the starting //strength points, multiplying it by the //appropriate percentage based on the random //integer generator, and adding to the //current strength points (the decimal value //of the multiplication result is truncated //before the result is added to the strength //points). (If the random int generator outputs //a 1, no restoration occurs. If the random int //generator outputs a 5, full restoration to //starting strength points occurs. if (random == 1) { cout << "Restore Value (% Deficit to Full Strength - " << "Decimal Value Truncated): 0%\n" << "Strength Points After Restoration: " << getStrengthPoints() << endl << endl; } else if (random == 2) { setStrengthPoints(((startingStrPoints - strengthPoints) * 0.25) + strengthPoints); cout << "Restore Value (% Deficit to Full Strength - " << "Decimal Value Truncated): 25%\n" << "Strength Points After Restoration: " << getStrengthPoints() << endl << endl; } else if (random == 3) { setStrengthPoints(((startingStrPoints - strengthPoints) * 0.50) + strengthPoints); cout << "Restore Value (% Deficit to Full Strength - " << "Decimal Value Truncated): 50%\n" << "Strength Points After Restoration: " << getStrengthPoints() << endl << endl; } else if (random == 4) { setStrengthPoints(((startingStrPoints - strengthPoints) * 0.75) + strengthPoints); cout << "Restore Value (% Deficit to Full Strength - " << "Decimal Value Truncated): 75%\n" << "Strength Points After Restoration: " << getStrengthPoints() << endl << endl; } else { setStrengthPoints(startingStrPoints); cout << "Restore Value (% Deficit to Full Strength - " << "Decimal Value Truncated): 100%\n" << "Strength Points After Restoration: " << getStrengthPoints() << endl << endl; } }1-10 // 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 "sync/engine/model_type_sync_worker_impl.h" #include "base/strings/stringprintf.h" #include "sync/engine/commit_contribution.h" #include "sync/engine/model_type_sync_proxy.h" #include "sync/internal_api/public/base/model_type.h" #include "sync/internal_api/public/non_blocking_sync_common.h" #include "sync/protocol/sync.pb.h" #include "sync/sessions/status_controller.h" #include "sync/syncable/syncable_util.h" #include "sync/test/engine/mock_model_type_sync_proxy.h" #include "sync/test/engine/mock_nudge_handler.h" #include "sync/test/engine/single_type_mock_server.h" #include "sync/test/fake_encryptor.h" #include "testing/gtest/include/gtest/gtest.h" static const std::string kTypeParentId = "PrefsRootNodeID"; static const syncer::ModelType kModelType = syncer::PREFERENCES; // Special constant value taken from cryptographer.cc. const char kNigoriKeyName[] = "nigori-key"; namespace syncer { // Tests the ModelTypeSyncWorkerImpl. // // This class passes messages between the model thread and sync server. // As such, its code is subject to lots of different race conditions. This // test harness lets us exhaustively test all possible races. We try to // focus on just a few interesting cases. // // Inputs: // - Initial data type state from the model thread. // - Commit requests from the model thread. // - Update responses from the server. // - Commit responses from the server. // - The cryptographer, if encryption is enabled. // // Outputs: // - Commit requests to the server. // - Commit responses to the model thread. // - Update responses to the model thread. // - Nudges to the sync scheduler. // // We use the MockModelTypeSyncProxy to stub out all communication // with the model thread. That interface is synchronous, which makes it // much easier to test races. // // The interface with the server is built around "pulling" data from this // class, so we don't have to mock out any of it. We wrap it with some // convenience functions to we can emulate server behavior. class ModelTypeSyncWorkerImplTest : public ::testing::Test { public: ModelTypeSyncWorkerImplTest(); ~ModelTypeSyncWorkerImplTest() override; // One of these Initialize functions should be called at the beginning of // each test. // Initializes with no data type state. We will be unable to perform any // significant server action until we receive an update response that // contains the type root node for this type. void FirstInitialize(); // Initializes with some existing data type state. Allows us to start // committing items right away. void NormalInitialize(); // Initialize with some saved pending updates from the model thread. void InitializeWithPendingUpdates( const UpdateResponseDataList& initial_pending_updates); // Initialize with a custom initial DataTypeState and pending updates. void InitializeWithState(const DataTypeState& state, const UpdateResponseDataList& pending_updates); // Introduce a new key that the local cryptographer can't decrypt. void NewForeignEncryptionKey(); // Update the local cryptographer with all relevant keys. void UpdateLocalCryptographer(); // Use the Nth nigori instance to encrypt incoming updates. // The default value, zero, indicates no encryption. void SetUpdateEncryptionFilter(int n); // Modifications on the model thread that get sent to the worker under test. void CommitRequest(const std::string& tag, const std::string& value); void DeleteRequest(const std::string& tag); // Pretends to receive update messages from the server. void TriggerTypeRootUpdateFromServer(); void TriggerUpdateFromServer(int64 version_offset, const std::string& tag, const std::string& value); void TriggerTombstoneFromServer(int64 version_offset, const std::string& tag); // Delivers specified protos as updates. // // Does not update mock server state. Should be used as a last resort when // writing test cases that require entities that don't fit the normal sync // protocol. Try to use the other, higher level methods if possible. void DeliverRawUpdates(const SyncEntityList& update_list); // By default, this harness behaves as if all tasks posted to the model // thread are executed immediately. However, this is not necessarily true. // The model's TaskRunner has a queue, and the tasks we post to it could // linger there for a while. In the meantime, the model thread could // continue posting tasks to the worker based on its stale state. // // If you want to test those race cases, then these functions are for you. void SetModelThreadIsSynchronous(bool is_synchronous); void PumpModelThread(); // Returns true if the |worker_| is ready to commit something. bool WillCommit(); // Pretend to successfully commit all outstanding unsynced items. // It is safe to call this only if WillCommit() returns true. void DoSuccessfulCommit(); // Read commit messages the worker_ sent to the emulated server. size_t GetNumCommitMessagesOnServer() const; sync_pb::ClientToServerMessage GetNthCommitMessageOnServer(size_t n) const; // Read the latest version of sync entities committed to the emulated server. bool HasCommitEntityOnServer(const std::string& tag) const; sync_pb::SyncEntity GetLatestCommitEntityOnServer( const std::string& tag) const; // Read the latest update messages received on the model thread. // Note that if the model thread is in non-blocking mode, this data will not // be updated until the response is actually processed by the model thread. size_t GetNumModelThreadUpdateResponses() const; UpdateResponseDataList GetNthModelThreadUpdateResponse(size_t n) const; UpdateResponseDataList GetNthModelThreadPendingUpdates(size_t n) const; DataTypeState GetNthModelThreadUpdateState(size_t n) const; // Reads the latest update response datas on the model thread. // Note that if the model thread is in non-blocking mode, this data will not // be updated until the response is actually processed by the model thread. bool HasUpdateResponseOnModelThread(const std::string& tag) const; UpdateResponseData GetUpdateResponseOnModelThread( const std::string& tag) const; // Read the latest commit messages received on the model thread. // Note that if the model thread is in non-blocking mode, this data will not // be updated until the response is actually processed by the model thread. size_t GetNumModelThreadCommitResponses() const; CommitResponseDataList GetNthModelThreadCommitResponse(size_t n) const; DataTypeState GetNthModelThreadCommitState(size_t n) const; // Reads the latest commit response datas on the model thread. // Note that if the model thread is in non-blocking mode, this data will not // be updated until the response is actually processed by the model thread. bool HasCommitResponseOnModelThread(const std::string& tag) const; CommitResponseData GetCommitResponseOnModelThread( const std::string& tag) const; // Returns the number of commit nudges sent to the mock nudge handler. int GetNumCommitNudges() const; // Returns the number of initial sync nudges sent to the mock nudge handler. int GetNumInitialDownloadNudges() const; // Returns the name of the encryption key in the cryptographer last passed to // the ModelTypeSyncWorker. Returns an empty string if no crypgorapher is // in use. See also: UpdateLocalCryptographer(). std::string GetLocalCryptographerKeyName() const; // Helpers for building various messages and structures. static std::string GenerateTagHash(const std::string& tag); static sync_pb::EntitySpecifics GenerateSpecifics(const std::string& tag, const std::string& value); // Returns a set of KeyParams for the cryptographer. Each input 'n' value // results in a different set of parameters. static KeyParams GetNthKeyParams(int n); // Returns the name for the given Nigori. // // Uses some 'white-box' knowledge to mimic the names that a real sync client // would generate. It's probably not necessary to do so, but it can't hurt. static std::string GetNigoriName(const Nigori& nigori); // Modifies the input/output parameter |specifics| by encrypting it with // a Nigori intialized with the specified KeyParams. static void EncryptUpdate(const KeyParams& params, sync_pb::EntitySpecifics* specifics); private: // An encryptor for our cryptographer. FakeEncryptor fake_encryptor_; // The cryptographer itself. NULL if we're not encrypting the type. scoped_ptr cryptographer_; // The number of the most recent foreign encryption key known to our // cryptographer. Note that not all of these will be decryptable. int foreign_encryption_key_index_; // The number of the encryption key used to encrypt incoming updates. A zero // value implies no encryption. int update_encryption_filter_index_; // The ModelTypeSyncWorkerImpl being tested. scoped_ptr worker_; // Non-owned, possibly NULL pointer. This object belongs to the // ModelTypeSyncWorkerImpl under test. MockModelTypeSyncProxy* mock_type_sync_proxy_; // A mock that emulates enough of the sync server that it can be used // a single UpdateHandler and CommitContributor pair. In this test // harness, the |worker_| is both of them. SingleTypeMockServer mock_server_; // A mock to track the number of times the ModelTypeSyncWorker requests to // sync. MockNudgeHandler mock_nudge_handler_; }; ModelTypeSyncWorkerImplTest::ModelTypeSyncWorkerImplTest() : foreign_encryption_key_index_(0), update_encryption_filter_index_(0), mock_type_sync_proxy_(NULL), mock_server_(kModelType) { } ModelTypeSyncWorkerImplTest::~ModelTypeSyncWorkerImplTest() { } void ModelTypeSyncWorkerImplTest::FirstInitialize() { DataTypeState initial_state; initial_state.progress_marker.set_data_type_id( GetSpecificsFieldNumberFromModelType(kModelType)); initial_state.next_client_id = 0; InitializeWithState(initial_state, UpdateResponseDataList()); } void ModelTypeSyncWorkerImplTest::NormalInitialize() { InitializeWithPendingUpdates(UpdateResponseDataList()); } void ModelTypeSyncWorkerImplTest::InitializeWithPendingUpdates( const UpdateResponseDataList& initial_pending_updates) { DataTypeState initial_state; initial_state.progress_marker.set_data_type_id( GetSpecificsFieldNumberFromModelType(kModelType)); initial_state.progress_marker.set_token(""); initial_state.next_client_id = 10; initial_state.type_root_id = kTypeParentId; initial_state.initial_sync_done = true; InitializeWithState(initial_state, initial_pending_updates); mock_nudge_handler_.ClearCounters(); } void ModelTypeSyncWorkerImplTest::InitializeWithState( const DataTypeState& state, const UpdateResponseDataList& initial_pending_updates) { DCHECK(!worker_); // We don't get to own this object. The |worker_| keeps a scoped_ptr to it. mock_type_sync_proxy_ = new MockModelTypeSyncProxy(); scoped_ptr proxy(mock_type_sync_proxy_); scoped_ptr cryptographer_copy; if (cryptographer_) { cryptographer_copy.reset(new Cryptographer(*cryptographer_)); } worker_.reset(new ModelTypeSyncWorkerImpl(kModelType, state, initial_pending_updates, cryptographer_copy.Pass(), &mock_nudge_handler_, proxy.Pass())); } void ModelTypeSyncWorkerImplTest::NewForeignEncryptionKey() { if (!cryptographer_) { cryptographer_.reset(new Cryptographer(&fake_encryptor_)); } foreign_encryption_key_index_++; sync_pb::NigoriKeyBag bag; for (int i = 0; i <= foreign_encryption_key_index_; ++i) { Nigori nigori; KeyParams params = GetNthKeyParams(i); nigori.InitByDerivation(params.hostname, params.username, params.password); sync_pb::NigoriKey* key = bag.add_key(); key->set_name(GetNigoriName(nigori)); nigori.ExportKeys(key->mutable_user_key(), key->mutable_encryption_key(), key->mutable_mac_key()); } // Re-create the last nigori from that loop. Nigori last_nigori; KeyParams params = GetNthKeyParams(foreign_encryption_key_index_); last_nigori.InitByDerivation( params.hostname, params.username, params.password); // Serialize and encrypt the bag with the last nigori. std::string serialized_bag; bag.SerializeToString(&serialized_bag); sync_pb::EncryptedData encrypted; encrypted.set_key_name(GetNigoriName(last_nigori)); last_nigori.Encrypt(serialized_bag, encrypted.mutable_blob()); // Update the cryptographer with new pending keys. cryptographer_->SetPendingKeys(encrypted); // Update the worker with the latest cryptographer. if (worker_) { worker_->UpdateCryptographer( make_scoped_ptr(new Cryptographer(*cryptographer_))); } } void ModelTypeSyncWorkerImplTest::UpdateLocalCryptographer() { if (!cryptographer_) { cryptographer_.reset(new Cryptographer(&fake_encryptor_)); } KeyParams params = GetNthKeyParams(foreign_encryption_key_index_); bool success = cryptographer_->DecryptPendingKeys(params); DCHECK(success); // Update the worker with the latest cryptographer. if (worker_) { worker_->UpdateCryptographer( make_scoped_ptr(new Cryptographer(*cryptographer_))); } } void ModelTypeSyncWorkerImplTest::SetUpdateEncryptionFilter(int n) { update_encryption_filter_index_ = n; } void ModelTypeSyncWorkerImplTest::CommitRequest(const std::string& name, const std::string& value) { const std::string tag_hash = GenerateTagHash(name); CommitRequestData data = mock_type_sync_proxy_->CommitRequest( tag_hash, GenerateSpecifics(name, value)); CommitRequestDataList list; list.push_back(data); worker_->EnqueueForCommit(list); } void ModelTypeSyncWorkerImplTest::DeleteRequest(const std::string& tag) { const std::string tag_hash = GenerateTagHash(tag); CommitRequestData data = mock_type_sync_proxy_->DeleteRequest(tag_hash); CommitRequestDataList list; list.push_back(data); worker_->EnqueueForCommit(list); } void ModelTypeSyncWorkerImplTest::TriggerTypeRootUpdateFromServer() { sync_pb::SyncEntity entity = mock_server_.TypeRootUpdate(); SyncEntityList entity_list; entity_list.push_back(&entity); sessions::StatusController dummy_status; worker_->ProcessGetUpdatesResponse(mock_server_.GetProgress(), mock_server_.GetContext(), entity_list, &dummy_status); worker_->ApplyUpdates(&dummy_status); } void ModelTypeSyncWorkerImplTest::TriggerUpdateFromServer( int64 version_offset, const std::string& tag, const std::string& value) { sync_pb::SyncEntity entity = mock_server_.UpdateFromServer( version_offset, GenerateTagHash(tag), GenerateSpecifics(tag, value)); if (update_encryption_filter_index_ != 0) { EncryptUpdate(GetNthKeyParams(update_encryption_filter_index_), entity.mutable_specifics()); } SyncEntityList entity_list; entity_list.push_back(&entity); sessions::StatusController dummy_status; worker_->ProcessGetUpdatesResponse(mock_server_.GetProgress(), mock_server_.GetContext(), entity_list, &dummy_status); worker_->ApplyUpdates(&dummy_status); } void ModelTypeSyncWorkerImplTest::DeliverRawUpdates( const SyncEntityList& list) { sessions::StatusController dummy_status; worker_->ProcessGetUpdatesResponse(mock_server_.GetProgress(), mock_server_.GetContext(), list, &dummy_status); worker_->ApplyUpdates(&dummy_status); } void ModelTypeSyncWorkerImplTest::TriggerTombstoneFromServer( int64 version_offset, const std::string& tag) { sync_pb::SyncEntity entity = mock_server_.TombstoneFromServer(version_offset, GenerateTagHash(tag)); if (update_encryption_filter_index_ != 0) { EncryptUpdate(GetNthKeyParams(update_encryption_filter_index_), entity.mutable_specifics()); } SyncEntityList entity_list; entity_list.push_back(&entity); sessions::StatusController dummy_status; worker_->ProcessGetUpdatesResponse(mock_server_.GetProgress(), mock_server_.GetContext(), entity_list, &dummy_status); worker_->ApplyUpdates(&dummy_status); } void ModelTypeSyncWorkerImplTest::SetModelThreadIsSynchronous( bool is_synchronous) { mock_type_sync_proxy_->SetSynchronousExecution(is_synchronous); } void ModelTypeSyncWorkerImplTest::PumpModelThread() { mock_type_sync_proxy_->RunQueuedTasks(); } bool ModelTypeSyncWorkerImplTest::WillCommit() { scoped_ptr contribution( worker_->GetContribution(INT_MAX)); if (contribution) { contribution->CleanUp(); // Gracefully abort the commit. return true; } else { return false; } } // Conveniently, this is all one big synchronous operation. The sync thread // remains blocked while the commit is in progress, so we don't need to worry // about other tasks being run between the time when the commit request is // issued and the time when the commit response is received. void ModelTypeSyncWorkerImplTest::DoSuccessfulCommit() { DCHECK(WillCommit()); scoped_ptr contribution( worker_->GetContribution(INT_MAX)); sync_pb::ClientToServerMessage message; contribution->AddToCommitMessage(&message); sync_pb::ClientToServerResponse response = mock_server_.DoSuccessfulCommit(message); sessions::StatusController dummy_status; contribution->ProcessCommitResponse(response, &dummy_status); contribution->CleanUp(); } size_t ModelTypeSyncWorkerImplTest::GetNumCommitMessagesOnServer() const { return mock_server_.GetNumCommitMessages(); } sync_pb::ClientToServerMessage ModelTypeSyncWorkerImplTest::GetNthCommitMessageOnServer(size_t n) const { DCHECK_LT(n, GetNumCommitMessagesOnServer()); return mock_server_.GetNthCommitMessage(n); } bool ModelTypeSyncWorkerImplTest::HasCommitEntityOnServer( const std::string& tag) const { const std::string tag_hash = GenerateTagHash(tag); return mock_server_.HasCommitEntity(tag_hash); } sync_pb::SyncEntity ModelTypeSyncWorkerImplTest::GetLatestCommitEntityOnServer( const std::string& tag) const { DCHECK(HasCommitEntityOnServer(tag)); const std::string tag_hash = GenerateTagHash(tag); return mock_server_.GetLastCommittedEntity(tag_hash); } size_t ModelTypeSyncWorkerImplTest::GetNumModelThreadUpdateResponses() const { return mock_type_sync_proxy_->GetNumUpdateResponses(); } UpdateResponseDataList ModelTypeSyncWorkerImplTest::GetNthModelThreadUpdateResponse(size_t n) const { DCHECK_LT(n, GetNumModelThreadUpdateResponses()); return mock_type_sync_proxy_->GetNthUpdateResponse(n); } UpdateResponseDataList ModelTypeSyncWorkerImplTest::GetNthModelThreadPendingUpdates(size_t n) const { DCHECK_LT(n, GetNumModelThreadUpdateResponses()); return mock_type_sync_proxy_->GetNthPendingUpdates(n); } DataTypeState ModelTypeSyncWorkerImplTest::GetNthModelThreadUpdateState( size_t n) const { DCHECK_LT(n, GetNumModelThreadUpdateResponses()); return mock_type_sync_proxy_->GetNthTypeStateReceivedInUpdateResponse(n); } bool ModelTypeSyncWorkerImplTest::HasUpdateResponseOnModelThread( const std::string& tag) const { const std::string tag_hash = GenerateTagHash(tag); return mock_type_sync_proxy_->HasUpdateResponse(tag_hash); } UpdateResponseData ModelTypeSyncWorkerImplTest::GetUpdateResponseOnModelThread( const std::string& tag) const { const std::string tag_hash = GenerateTagHash(tag); return mock_type_sync_proxy_->GetUpdateResponse(tag_hash); } size_t ModelTypeSyncWorkerImplTest::GetNumModelThreadCommitResponses() const { return mock_type_sync_proxy_->GetNumCommitResponses(); } CommitResponseDataList ModelTypeSyncWorkerImplTest::GetNthModelThreadCommitResponse(size_t n) const { DCHECK_LT(n, GetNumModelThreadCommitResponses()); return mock_type_sync_proxy_->GetNthCommitResponse(n); } DataTypeState ModelTypeSyncWorkerImplTest::GetNthModelThreadCommitState( size_t n) const { DCHECK_LT(n, GetNumModelThreadCommitResponses()); return mock_type_sync_proxy_->GetNthTypeStateReceivedInCommitResponse(n); } bool ModelTypeSyncWorkerImplTest::HasCommitResponseOnModelThread( const std::string& tag) const { const std::string tag_hash = GenerateTagHash(tag); return mock_type_sync_proxy_->HasCommitResponse(tag_hash); } CommitResponseData ModelTypeSyncWorkerImplTest::GetCommitResponseOnModelThread( const std::string& tag) const { DCHECK(HasCommitResponseOnModelThread(tag)); const std::string tag_hash = GenerateTagHash(tag); return mock_type_sync_proxy_->GetCommitResponse(tag_hash); } int ModelTypeSyncWorkerImplTest::GetNumCommitNudges() const { return mock_nudge_handler_.GetNumCommitNudges(); } int ModelTypeSyncWorkerImplTest::GetNumInitialDownloadNudges() const { return mock_nudge_handler_.GetNumInitialDownloadNudges(); } std::string ModelTypeSyncWorkerImplTest::GetLocalCryptographerKeyName() const { if (!cryptographer_) { return std::string(); } return cryptographer_->GetDefaultNigoriKeyName(); } // static. std::string ModelTypeSyncWorkerImplTest::GenerateTagHash( const std::string& tag) { const std::string& client_tag_hash = syncable::GenerateSyncableHash(kModelType, tag); return client_tag_hash; } // static. sync_pb::EntitySpecifics ModelTypeSyncWorkerImplTest::GenerateSpecifics( const std::string& tag, const std::string& value) { sync_pb::EntitySpecifics specifics; specifics.mutable_preference()->set_name(tag); specifics.mutable_preference()->set_value(value); return specifics; } // static. std::string ModelTypeSyncWorkerImplTest::GetNigoriName(const Nigori& nigori) { std::string name; if (!nigori.Permute(Nigori::Password, kNigoriKeyName, &name)) { NOTREACHED(); return std::string(); } return name; } // static. KeyParams ModelTypeSyncWorkerImplTest::GetNthKeyParams(int n) { KeyParams params; params.hostname = std::string("localhost"); params.username = std::string("userX"); params.password = base::StringPrintf("", n); return params; } // static. void ModelTypeSyncWorkerImplTest::EncryptUpdate( const KeyParams& params, sync_pb::EntitySpecifics* specifics) { Nigori nigori; nigori.InitByDerivation(params.hostname, params.username, params.password); sync_pb::EntitySpecifics original_specifics = *specifics; std::string plaintext; original_specifics.SerializeToString(&plaintext); std::string encrypted; nigori.Encrypt(plaintext, &encrypted); specifics->Clear(); AddDefaultFieldValue(kModelType, specifics); specifics->mutable_encrypted()->set_key_name(GetNigoriName(nigori)); specifics->mutable_encrypted()->set_blob(encrypted); } // Requests a commit and verifies the messages sent to the client and server as // a result. // // This test performs sanity checks on most of the fields in these messages. // For the most part this is checking that the test code behaves as expected // and the |worker_| doesn't mess up its simple task of moving around these // values. It makes sense to have one or two tests that are this thorough, but // we shouldn't be this verbose in all tests. TEST_F(ModelTypeSyncWorkerImplTest, SimpleCommit) { NormalInitialize(); EXPECT_FALSE(WillCommit()); EXPECT_EQ(0U, GetNumCommitMessagesOnServer()); EXPECT_EQ(0U, GetNumModelThreadCommitResponses()); CommitRequest("tag1", "value1"); EXPECT_EQ(1, GetNumCommitNudges()); ASSERT_TRUE(WillCommit()); DoSuccessfulCommit(); const std::string& client_tag_hash = GenerateTagHash("tag1"); // Exhaustively verify the SyncEntity sent in the commit message. ASSERT_EQ(1U, GetNumCommitMessagesOnServer()); EXPECT_EQ(1, GetNthCommitMessageOnServer(0).commit().entries_size()); ASSERT_TRUE(HasCommitEntityOnServer("tag1")); const sync_pb::SyncEntity& entity = GetLatestCommitEntityOnServer("tag1"); EXPECT_FALSE(entity.id_string().empty()); EXPECT_EQ(kTypeParentId, entity.parent_id_string()); EXPECT_EQ(kUncommittedVersion, entity.version()); EXPECT_NE(0, entity.mtime()); EXPECT_NE(0, entity.ctime()); EXPECT_FALSE(entity.name().empty()); EXPECT_EQ(client_tag_hash, entity.client_defined_unique_tag()); EXPECT_EQ("tag1", entity.specifics().preference().name()); EXPECT_FALSE(entity.deleted()); EXPECT_EQ("value1", entity.specifics().preference().value()); // Exhaustively verify the commit response returned to the model thread. ASSERT_EQ(1U, GetNumModelThreadCommitResponses()); EXPECT_EQ(1U, GetNthModelThreadCommitResponse(0).size()); ASSERT_TRUE(HasCommitResponseOnModelThread("tag1")); const CommitResponseData& commit_response = GetCommitResponseOnModelThread("tag1"); // The ID changes in a commit response to initial commit. EXPECT_FALSE(commit_response.id.empty()); EXPECT_NE(entity.id_string(), commit_response.id); EXPECT_EQ(client_tag_hash, commit_response.client_tag_hash); EXPECT_LT(0, commit_response.response_version); } TEST_F(ModelTypeSyncWorkerImplTest, SimpleDelete) { NormalInitialize(); // We can't delete an entity that was never committed. // Step 1 is to create and commit a new entity. CommitRequest("tag1", "value1"); EXPECT_EQ(1, GetNumCommitNudges()); ASSERT_TRUE(WillCommit()); DoSuccessfulCommit(); ASSERT_TRUE(HasCommitResponseOnModelThread("tag1")); const CommitResponseData& initial_commit_response = GetCommitResponseOnModelThread("tag1"); int64 base_version = initial_commit_response.response_version; // Now that we have an entity, we can delete it. DeleteRequest("tag1"); ASSERT_TRUE(WillCommit()); DoSuccessfulCommit(); // Verify the SyncEntity sent in the commit message. ASSERT_EQ(2U, GetNumCommitMessagesOnServer()); EXPECT_EQ(1, GetNthCommitMessageOnServer(1).commit().entries_size()); ASSERT_TRUE(HasCommitEntityOnServer("tag1")); const sync_pb::SyncEntity& entity = GetLatestCommitEntityOnServer("tag1"); EXPECT_FALSE(entity.id_string().empty()); EXPECT_EQ(GenerateTagHash("tag1"), entity.client_defined_unique_tag()); EXPECT_EQ(base_version, entity.version()); EXPECT_TRUE(entity.deleted()); // Deletions should contain enough specifics to identify the type. EXPECT_TRUE(entity.has_specifics()); EXPECT_EQ(kModelType, GetModelTypeFromSpecifics(entity.specifics())); // Verify the commit response returned to the model thread. ASSERT_EQ(2U, GetNumModelThreadCommitResponses()); EXPECT_EQ(1U, GetNthModelThreadCommitResponse(1).size()); ASSERT_TRUE(HasCommitResponseOnModelThread("tag1")); const CommitResponseData& commit_response = GetCommitResponseOnModelThread("tag1"); EXPECT_EQ(entity.id_string(), commit_response.id); EXPECT_EQ(entity.client_defined_unique_tag(), commit_response.client_tag_hash); EXPECT_EQ(entity.version(), commit_response.response_version); } // The server doesn't like it when we try to delete an entity it's never heard // of before. This test helps ensure we avoid that scenario. TEST_F(ModelTypeSyncWorkerImplTest, NoDeleteUncommitted) { NormalInitialize(); // Request the commit of a new, never-before-seen item. CommitRequest("tag1", "value1"); EXPECT_TRUE(WillCommit()); EXPECT_EQ(1, GetNumCommitNudges()); // Request a deletion of that item before we've had a chance to commit it. DeleteRequest("tag1"); EXPECT_FALSE(WillCommit()); EXPECT_EQ(2, GetNumCommitNudges()); } // Verifies the sending of an "initial sync done" signal. TEST_F(ModelTypeSyncWorkerImplTest, SendInitialSyncDone) { FirstInitialize(); // Initialize with no saved sync state. EXPECT_EQ(0U, GetNumModelThreadUpdateResponses()); EXPECT_EQ(1, GetNumInitialDownloadNudges()); // Receive an update response that contains only the type root node. TriggerTypeRootUpdateFromServer(); // Two updates: // - One triggered by process updates to forward the type root ID. // - One triggered by apply updates, which the worker interprets to mean // "initial sync done". This triggers a model thread update, too. EXPECT_EQ(2U, GetNumModelThreadUpdateResponses()); // The type root and initial sync done updates both contain no entities. EXPECT_EQ(0U, GetNthModelThreadUpdateResponse(0).size()); EXPECT_EQ(0U, GetNthModelThreadUpdateResponse(1).size()); const DataTypeState& state = GetNthModelThreadUpdateState(1); EXPECT_FALSE(state.progress_marker.token().empty()); EXPECT_FALSE(state.type_root_id.empty()); EXPECT_TRUE(state.initial_sync_done); } // Commit two new entities in two separate commit messages. TEST_F(ModelTypeSyncWorkerImplTest, TwoNewItemsCommittedSeparately) { NormalInitialize(); // Commit the first of two entities. CommitRequest("tag1", "value1"); EXPECT_EQ(1, GetNumCommitNudges()); ASSERT_TRUE(WillCommit()); DoSuccessfulCommit(); ASSERT_EQ(1U, GetNumCommitMessagesOnServer()); EXPECT_EQ(1, GetNthCommitMessageOnServer(0).commit().entries_size()); ASSERT_TRUE(HasCommitEntityOnServer("tag1")); const sync_pb::SyncEntity& tag1_entity = GetLatestCommitEntityOnServer("tag1"); // Commit the second of two entities. CommitRequest("tag2", "value2"); EXPECT_EQ(2, GetNumCommitNudges()); ASSERT_TRUE(WillCommit()); DoSuccessfulCommit(); ASSERT_EQ(2U, GetNumCommitMessagesOnServer()); EXPECT_EQ(1, GetNthCommitMessageOnServer(1).commit().entries_size()); ASSERT_TRUE(HasCommitEntityOnServer("tag2")); const sync_pb::SyncEntity& tag2_entity = GetLatestCommitEntityOnServer("tag2"); EXPECT_FALSE(WillCommit()); // The IDs assigned by the |worker_| should be unique. EXPECT_NE(tag1_entity.id_string(), tag2_entity.id_string()); // Check that the committed specifics values are sane. EXPECT_EQ(tag1_entity.specifics().preference().value(), "value1"); EXPECT_EQ(tag2_entity.specifics().preference().value(), "value2"); // There should have been two separate commit responses sent to the model // thread. They should be uninteresting, so we don't bother inspecting them. EXPECT_EQ(2U, GetNumModelThreadCommitResponses()); } // Test normal update receipt code path. TEST_F(ModelTypeSyncWorkerImplTest, ReceiveUpdates) { NormalInitialize(); const std::string& tag_hash = GenerateTagHash("tag1"); TriggerUpdateFromServer(10, "tag1", "value1"); ASSERT_EQ(1U, GetNumModelThreadUpdateResponses()); UpdateResponseDataList updates_list = GetNthModelThreadUpdateResponse(0); ASSERT_EQ(1U, updates_list.size()); ASSERT_TRUE(HasUpdateResponseOnModelThread("tag1")); UpdateResponseData update = GetUpdateResponseOnModelThread("tag1"); EXPECT_FALSE(update.id.empty()); EXPECT_EQ(tag_hash, update.client_tag_hash); EXPECT_LT(0, update.response_version); EXPECT_FALSE(update.ctime.is_null()); EXPECT_FALSE(update.mtime.is_null()); EXPECT_FALSE(update.non_unique_name.empty()); EXPECT_FALSE(update.deleted); EXPECT_EQ("tag1", update.specifics.preference().name()); EXPECT_EQ("value1", update.specifics.preference().value()); } // Test commit of encrypted updates. TEST_F(ModelTypeSyncWorkerImplTest, EncryptedCommit) { NormalInitialize(); ASSERT_EQ(0U, GetNumModelThreadUpdateResponses()); NewForeignEncryptionKey(); UpdateLocalCryptographer(); ASSERT_EQ(1U, GetNumModelThreadUpdateResponses()); EXPECT_EQ(GetLocalCryptographerKeyName(), GetNthModelThreadUpdateState(0).encryption_key_name); // Normal commit request stuff. CommitRequest("tag1", "value1"); DoSuccessfulCommit(); ASSERT_EQ(1U, GetNumCommitMessagesOnServer()); EXPECT_EQ(1, GetNthCommitMessageOnServer(0).commit().entries_size()); ASSERT_TRUE(HasCommitEntityOnServer("tag1")); const sync_pb::SyncEntity& tag1_entity = GetLatestCommitEntityOnServer("tag1"); EXPECT_TRUE(tag1_entity.specifics().has_encrypted()); // The title should be overwritten. EXPECT_EQ(tag1_entity.name(), "encrypted"); // The type should be set, but there should be no non-encrypted contents. EXPECT_TRUE(tag1_entity.specifics().has_preference()); EXPECT_FALSE(tag1_entity.specifics().preference().has_name()); EXPECT_FALSE(tag1_entity.specifics().preference().has_value()); } // Test items are not committed when encryption is required but unavailable. TEST_F(ModelTypeSyncWorkerImplTest, EncryptionBlocksCommits) { NormalInitialize(); CommitRequest("tag1", "value1"); EXPECT_TRUE(WillCommit()); // We know encryption is in use on this account, but don't have the necessary // encryption keys. The worker should refuse to commit. NewForeignEncryptionKey(); EXPECT_FALSE(WillCommit()); // Once the cryptographer is returned to a normal state, we should be able to // commit again. EXPECT_EQ(1, GetNumCommitNudges()); UpdateLocalCryptographer(); EXPECT_EQ(2, GetNumCommitNudges()); EXPECT_TRUE(WillCommit()); // Verify the committed entity was properly encrypted. DoSuccessfulCommit(); ASSERT_EQ(1U, GetNumCommitMessagesOnServer()); EXPECT_EQ(1, GetNthCommitMessageOnServer(0).commit().entries_size()); ASSERT_TRUE(HasCommitEntityOnServer("tag1")); const sync_pb::SyncEntity& tag1_entity = GetLatestCommitEntityOnServer("tag1"); EXPECT_TRUE(tag1_entity.specifics().has_encrypted()); EXPECT_EQ(tag1_entity.name(), "encrypted"); EXPECT_TRUE(tag1_entity.specifics().has_preference()); EXPECT_FALSE(tag1_entity.specifics().preference().has_name()); EXPECT_FALSE(tag1_entity.specifics().preference().has_value()); } // Test the receipt of decryptable entities. TEST_F(ModelTypeSyncWorkerImplTest, ReceiveDecryptableEntities) { NormalInitialize(); // Create a new Nigori and allow the cryptographer to decrypt it. NewForeignEncryptionKey(); UpdateLocalCryptographer(); // First, receive an unencrypted entry. TriggerUpdateFromServer(10, "tag1", "value1"); // Test some basic properties regarding the update. ASSERT_TRUE(HasUpdateResponseOnModelThread("tag1")); UpdateResponseData update1 = GetUpdateResponseOnModelThread("tag1"); EXPECT_EQ("tag1", update1.specifics.preference().name()); EXPECT_EQ("value1", update1.specifics.preference().value()); EXPECT_TRUE(update1.encryption_key_name.empty()); // Set received updates to be encrypted using the new nigori. SetUpdateEncryptionFilter(1); // This next update will be encrypted. TriggerUpdateFromServer(10, "tag2", "value2"); // Test its basic features and the value of encryption_key_name. ASSERT_TRUE(HasUpdateResponseOnModelThread("tag2")); UpdateResponseData update2 = GetUpdateResponseOnModelThread("tag2"); EXPECT_EQ("tag2", update2.specifics.preference().name()); EXPECT_EQ("value2", update2.specifics.preference().value()); EXPECT_FALSE(update2.encryption_key_name.empty()); } // Test initializing a ModelTypeSyncWorker with a cryptographer at startup. TEST_F(ModelTypeSyncWorkerImplTest, InitializeWithCryptographer) { // Set up some encryption state. NewForeignEncryptionKey(); UpdateLocalCryptographer(); // Then initialize. NormalInitialize(); // The worker should tell the model thread about encryption as soon as // possible, so that it will have the chance to re-encrypt local data if // necessary. ASSERT_EQ(1U, GetNumModelThreadUpdateResponses()); EXPECT_EQ(GetLocalCryptographerKeyName(), GetNthModelThreadUpdateState(0).encryption_key_name); } // Receive updates that are initially undecryptable, then ensure they get // delivered to the model thread when decryption becomes possible. TEST_F(ModelTypeSyncWorkerImplTest, ReceiveUndecryptableEntries) { NormalInitialize(); // Receive a new foreign encryption key that we can't decrypt. NewForeignEncryptionKey(); // Receive an encrypted with that new key, which we can't access. SetUpdateEncryptionFilter(1); TriggerUpdateFromServer(10, "tag1", "value1"); // At this point, the cryptographer does not have access to the key, so the // updates will be undecryptable. They'll be transfered to the model thread // for safe-keeping as pending updates. ASSERT_EQ(1U, GetNumModelThreadUpdateResponses()); UpdateResponseDataList updates_list = GetNthModelThreadUpdateResponse(0); EXPECT_EQ(0U, updates_list.size()); UpdateResponseDataList pending_updates = GetNthModelThreadPendingUpdates(0); EXPECT_EQ(1U, pending_updates.size()); // The update will be delivered as soon as decryption becomes possible. UpdateLocalCryptographer(); ASSERT_TRUE(HasUpdateResponseOnModelThread("tag1")); UpdateResponseData update = GetUpdateResponseOnModelThread("tag1"); EXPECT_EQ("tag1", update.specifics.preference().name()); EXPECT_EQ("value1", update.specifics.preference().value()); EXPECT_FALSE(update.encryption_key_name.empty()); } // Ensure that even encrypted updates can cause conflicts. TEST_F(ModelTypeSyncWorkerImplTest, EncryptedUpdateOverridesPendingCommit) { NormalInitialize(); // Prepeare to commit an item. CommitRequest("tag1", "value1"); EXPECT_TRUE(WillCommit()); // Receive an encrypted update for that item. SetUpdateEncryptionFilter(1); TriggerUpdateFromServer(10, "tag1", "value1"); // The pending commit state should be cleared. EXPECT_FALSE(WillCommit()); // The encrypted update will be delivered to the model thread. ASSERT_EQ(1U, GetNumModelThreadUpdateResponses()); UpdateResponseDataList updates_list = GetNthModelThreadUpdateResponse(0); EXPECT_EQ(0U, updates_list.size()); UpdateResponseDataList pending_updates = GetNthModelThreadPendingUpdates(0); EXPECT_EQ(1U, pending_updates.size()); } // Test decryption of pending updates saved across a restart. TEST_F(ModelTypeSyncWorkerImplTest, RestorePendingEntries) { // Create a fake pending update. UpdateResponseData update; update.client_tag_hash = GenerateTagHash("tag1"); update.id = "SomeID"; update.response_version = 100; update.ctime = base::Time::UnixEpoch() + base::TimeDelta::FromSeconds(10); update.mtime = base::Time::UnixEpoch() + base::TimeDelta::FromSeconds(11); update.non_unique_name = "encrypted"; update.deleted = false; update.specifics = GenerateSpecifics("tag1", "value1"); EncryptUpdate(GetNthKeyParams(1), &(update.specifics)); // Inject the update during ModelTypeSyncWorker initialization. UpdateResponseDataList saved_pending_updates; saved_pending_updates.push_back(update); InitializeWithPendingUpdates(saved_pending_updates); // Update will be undecryptable at first. EXPECT_EQ(0U, GetNumModelThreadUpdateResponses()); ASSERT_FALSE(HasUpdateResponseOnModelThread("tag1")); // Update the cryptographer so it can decrypt that update. NewForeignEncryptionKey(); UpdateLocalCryptographer(); // Verify the item gets decrypted and sent back to the model thread. ASSERT_TRUE(HasUpdateResponseOnModelThread("tag1")); } // Test decryption of pending updates saved across a restart. This test // differs from the previous one in that the restored updates can be decrypted // immediately after the ModelTypeSyncWorker is constructed. TEST_F(ModelTypeSyncWorkerImplTest, RestoreApplicableEntries) { // Update the cryptographer so it can decrypt that update. NewForeignEncryptionKey(); UpdateLocalCryptographer(); // Create a fake pending update. UpdateResponseData update; update.client_tag_hash = GenerateTagHash("tag1"); update.id = "SomeID"; update.response_version = 100; update.ctime = base::Time::UnixEpoch() + base::TimeDelta::FromSeconds(10); update.mtime = base::Time::UnixEpoch() + base::TimeDelta::FromSeconds(11); update.non_unique_name = "encrypted"; update.deleted = false; update.specifics = GenerateSpecifics("tag1", "value1"); EncryptUpdate(GetNthKeyParams(1), &(update.specifics)); // Inject the update during ModelTypeSyncWorker initialization. UpdateResponseDataList saved_pending_updates; saved_pending_updates.push_back(update); InitializeWithPendingUpdates(saved_pending_updates); // Verify the item gets decrypted and sent back to the model thread. ASSERT_TRUE(HasUpdateResponseOnModelThread("tag1")); } // Test that undecryptable updates provide sufficient reason to not commit. // // This should be rare in practice. Usually the cryptographer will be in an // unusable state when we receive undecryptable updates, and that alone will be // enough to prevent all commits. TEST_F(ModelTypeSyncWorkerImplTest, CommitBlockedByPending) { NormalInitialize(); // Prepeare to commit an item. CommitRequest("tag1", "value1"); EXPECT_TRUE(WillCommit()); // Receive an encrypted update for that item. SetUpdateEncryptionFilter(1); TriggerUpdateFromServer(10, "tag1", "value1"); // The pending commit state should be cleared. EXPECT_FALSE(WillCommit()); // The pending update will be delivered to the model thread. HasUpdateResponseOnModelThread("tag1"); // Pretend the update arrived too late to prevent another commit request. CommitRequest("tag1", "value2"); EXPECT_FALSE(WillCommit()); } // Verify that corrupted encrypted updates don't cause crashes. TEST_F(ModelTypeSyncWorkerImplTest, ReceiveCorruptEncryption) { // Initialize the worker with basic encryption state. NormalInitialize(); NewForeignEncryptionKey(); UpdateLocalCryptographer(); // Manually create an update. sync_pb::SyncEntity entity; entity.set_client_defined_unique_tag(GenerateTagHash("tag1")); entity.set_id_string("SomeID"); entity.set_version(1); entity.set_ctime(1000); entity.set_mtime(1001); entity.set_name("encrypted"); entity.set_deleted(false); // Encrypt it. entity.mutable_specifics()->CopyFrom(GenerateSpecifics("tag1", "value1")); EncryptUpdate(GetNthKeyParams(1), entity.mutable_specifics()); // Replace a few bytes to corrupt it. entity.mutable_specifics()->mutable_encrypted()->mutable_blob()->replace( 0, 4, "xyz!"); SyncEntityList entity_list; entity_list.push_back(&entity); // If a corrupt update could trigger a crash, this is where it would happen. DeliverRawUpdates(entity_list); EXPECT_FALSE(HasUpdateResponseOnModelThread("tag1")); // Deliver a non-corrupt update to see if the everything still works. SetUpdateEncryptionFilter(1); TriggerUpdateFromServer(10, "tag1", "value1"); EXPECT_TRUE(HasUpdateResponseOnModelThread("tag1")); } } // namespace syncer ouonline/ppl.cv // 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. #include #include "ppl/cv/x86/perspectivetransform.h" #include "ppl/cv/debug.h" namespace { template class PerspectiveTransformBenchmark { public: int32_t height; int32_t width; T *inData; T *outData; int32_t mHeight; int32_t mWidth; double* mData; PerspectiveTransformBenchmark(int32_t height, int32_t width) : height(height) , width(width) , mHeight(ncDst + 1) , mWidth(ncSrc + 1) { inData = NULL; outData = NULL; inData = (T*)malloc(height * width * ncSrc * sizeof(T)); outData = (T*)malloc(height * width * ncDst * sizeof(T)); mData = (double*)malloc(mHeight * mWidth * sizeof(double)); ppl::cv::debug::randomFill(mData, mHeight * mWidth, 0, 255); } void apply() { //pplcv int32_t iStride = width * ncSrc; int32_t oStride = width * ncDst; ppl::cv::x86::PerspectiveTransform(height, width, iStride, inData, oStride, outData, (float*)mData); } void apply_opencv() { cv::Mat iMat(height, width, CV_MAKETYPE(cv::DataType::depth, ncSrc), inData); cv::Mat oMat(height, width, CV_MAKETYPE(cv::DataType::depth, ncDst), outData); cv::Mat mMat(mHeight, mWidth, CV_MAKETYPE(cv::DataType::depth, 1), mData); cv::perspectiveTransform(iMat, oMat, mMat); } ~PerspectiveTransformBenchmark() { free(inData); free(outData); free(mData); } }; } using namespace ppl::cv::debug; template static void BM_PerspectiveTransform_ppl_x86(benchmark::State &state) { PerspectiveTransformBenchmark bm(state.range(1), state.range(0)); for (auto _: state) { bm.apply(); } state.SetItemsProcessed(state.iterations()); } template static void BM_PerspectiveTransform_opencv_x86(benchmark::State &state) { PerspectiveTransformBenchmark bm(state.range(1), state.range(0)); for (auto _: state) { bm.apply_opencv(); } state.SetItemsProcessed(state.iterations()); } //pplcv BENCHMARK_TEMPLATE(BM_PerspectiveTransform_ppl_x86, float, c2, c2)->Args({320, 240})->Args({640, 480}); BENCHMARK_TEMPLATE(BM_PerspectiveTransform_ppl_x86, float, c2, c3)->Args({320, 240})->Args({640, 480}); BENCHMARK_TEMPLATE(BM_PerspectiveTransform_ppl_x86, float, c3, c2)->Args({320, 240})->Args({640, 480}); BENCHMARK_TEMPLATE(BM_PerspectiveTransform_ppl_x86, float, c3, c3)->Args({320, 240})->Args({640, 480}); //opencv BENCHMARK_TEMPLATE(BM_PerspectiveTransform_opencv_x86, float, c2, c2)->Args({320, 240})->Args({640, 480}); BENCHMARK_TEMPLATE(BM_PerspectiveTransform_opencv_x86, float, c2, c3)->Args({320, 240})->Args({640, 480}); BENCHMARK_TEMPLATE(BM_PerspectiveTransform_opencv_x86, float, c3, c2)->Args({320, 240})->Args({640, 480}); BENCHMARK_TEMPLATE(BM_PerspectiveTransform_opencv_x86, float, c3, c3)->Args({320, 240})->Args({640, 480}); // This file is part of RAVL, Recognition And Vision Library // Copyright (C) 2001, University of Surrey // This code may be redistributed under the terms of the GNU Lesser // General Public License (LGPL). See the lgpl.licence file for details or // see http://www.gnu.org/copyleft/lesser.html // file-header-ends-here //////////////////////////////////////////////////// //! author="" //! rcsid="$Id: exFailOver.cc 558 2001-11-02 17:15:03Z craftit $" //! lib=RavlDPMT #include "Ravl/Option.hh" #include "Ravl/DP/RunningAve.hh" #include "Ravl/DP/FileIO.hh" #include "Ravl/DP/Compose.hh" #include "Ravl/DP/IFailOver.hh" #include "Ravl/DP/TaskList.hh" #include "Ravl/DP/IOConnect.hh" int main(int argc,char **argv) { using namespace DPComposeST; // Using single threaded namespace. OptionC option(argc,argv,true); FilenameC infile = option.CharArr("i","in.dat","Input filename"); FilenameC outfile = option.CharArr("o","out.dat","Output filename"); option.Check(); DPIFailOverC failOver; DPIFileC(infile) >> failOver >> DPRunningAverage(1.0,5) >>= DPOFileC(outfile); DPIFileC(infile) >> failOver; // Second input. //calc.Out1() >> xx >> xxx.Input2(); cout << "Running.\n"; DPTaskListC::GlobalTaskRun(); cout << "Done.\n"; return 1; } # ifndef CPPAD_LOCAL_GRAPH_JSON_LEXER_HPP # define CPPAD_LOCAL_GRAPH_JSON_LEXER_HPP /* -------------------------------------------------------------------------- CppAD: C++ Algorithmic Differentiation: Copyright (C) 2003-19 CppAD is distributed under the terms of the Eclipse Public License Version 2.0. This Source Code may also be made available under the following Secondary License when the conditions for such availability set forth in the Eclipse Public License, Version 2.0 are satisfied: GNU General Public License, Version 2.0 or later. -------------------------------------------------------------------------- */ # include # include // BEGIN_NAMESPACE_CPPAD_LOCAL_GRAPH namespace CppAD { namespace local { namespace graph { // =========================================================================== class json_lexer { // =========================================================================== /* ------------------------------------------------------------------------------- $begin json_lexer_member_data$$ $spell json lexer $$ $section json lexer: Private Data$$ $head graph_$$ The $cref json_ad_graph$$. $head index_$$ is the index in the graph for the current character. If a token is returned, this corresponds to the last character it the token. $head line_number_$$ line number in the graph for the current character $head char_number_$$ character number in the graph for the current character $head token_$$ used to return tokens. $head function_name_$$ is the function name for this graph. This is initialized as empty, should be set as soon as it is parsed, and is used for error reporting. $head token$$ returns current value of $code token_$$. $head line_number$$ returns current value of $code line_number_$$ (which corresponds to last character in the token). $head char_number$$ returns current value of $code char_number_$$. (which corresponds to last character in the token). $head set_function_name$$ sets the value of $code function_name_$$. $head Source Code$$ $srccode%hpp% */ private: const std::string& json_; size_t index_; size_t line_number_; size_t char_number_; std::string token_; std::string function_name_; public: const std::string& token(void) const; size_t line_number(void) const; size_t char_number(void) const; void set_function_name(const std::string& function_name); /* %$$ $end ------------------------------------------------------------------------------- $begin json_lexer_report_error$$ $spell json lexer CppAD $$ $section json lexer: Report an Error$$ $head Syntax$$ $codei% %json_lexer%.report_error(%expected%, %found%) %$$ $head json_lexer$$ is a $code local::graph::json_lexer$$ object. $head expected$$ is the token that is expected. $head found$$ is the token or text that was found. $head Report$$ The current CppAD $cref ErrorHandler$$ is used to report an error parsing this Json AD graph. $head Prototype$$ $srccode%hpp% */ public: void report_error(const std::string& expected, const std::string& found); /* %$$ $end ------------------------------------------------------------------------------- $begin json_lexer_next_index$$ $spell json lexer $$ $section json lexer: Advance Index by One$$ $head Syntax$$ $codei% %json_lexer%.next_index() %$$ $head json_lexer$$ is a $code local::graph::json_lexer$$ object. $head index_$$ The input value of $code index_$$ is increased by one. It is an error to call this routine when the input value of $code index_$$ is greater than or equal $code json_.size()$$. $head line_number_$$ If the previous character, before the call, was a new line, $code line_number_$$ is increased by one. $head char_number_$$ If the previous character, before the call, was a new line, $code char_number$$ is set to one. Otherwise, $code char_number_$$ is increased by one. $head Prototype$$ $srccode%hpp% */ private: void next_index(void); /* %$$ $end ------------------------------------------------------------------------------- $begin json_lexer_skip_white_space$$ $spell json lexer $$ $section json lexer: Skip White Space That Separates Tokens$$ $head Syntax$$ $codei% %json_lexer%.skip_white_space() %$$ $head json_lexer$$ is a json lexer object. $head Discussion$$ This member functions is used to increase $code index_$$ until either a non-white space character is found or $code index_$$ is equal to $code json_.size()$$. $head Prototype$$ $srccode%hpp% */ private: void skip_white_space(void); /* %$$ $end ------------------------------------------------------------------------------- $begin json_lexer_constructor$$ $spell json lexer enum op arg $$ $section json lexer: Constructor$$ $head Syntax$$ $codei% local::graph::lexer %json_lexer%(%json%) %$$ $head json$$ The argument $icode json$$ is an $cref json_ad_graph$$ and it is assumed that $icode json$$ does not change for as long as $icode json_lexer$$ exists. $head Initialization$$ The current token, index, line number, and character number are set to the first non white space character in $code json_$$. If this is not a left brace character $code '{'$$, the error is reported and the constructor does not return. $head Side Effect$$ If $code local::graph::op_name2enum.size() == 0$$, the routine $cref/set_operator_info/cpp_graph_op/set_operator_info/$$ is called to initialize $code op_enum2fixed_n_arg$$, $code op_enum2name$$, and $code op_name2enum$$. This initialization cannot be done in $cref/parallel mode/ta_in_parallel/$$. $head Prototype$$ $srccode%hpp% */ public: json_lexer(const std::string& json); /* %$$ $end ------------------------------------------------------------------------------- $begin json_lexer_check_next_char$$ $spell json lexer ch $$ $section Get and Check Next Single Character Token$$ $head Syntax$$ $codei% %json_lexer%.check_next_char(%ch%) %$$ $head index_$$ The search for the character starts at one greater than the input value for $code index_$$ and skips white space. $head ch$$ Is a non white space single character token that is expected. If this character is not found, the error is reported and this function does not return. In the special case where $icode ch$$ is $code '\0'$$, any non-white space character will be accepted (but there must be such a character). $head token_$$ If this routine returns, $code token_$$ has size one and contains the character that is found. $head Prototype$$ $srccode%hpp% */ public: void check_next_char(char ch); /* %$$ $end ------------------------------------------------------------------------------- $begin json_lexer_check_next_string$$ $spell json lexer $$ $section Get and Check Next Single Character Token$$ $head Syntax$$ $codei% %json_lexer%.check_next_string(%expected%) %$$ $head index_$$ The search for the string starts at one greater than the input value for $code index_$$ and skips white space. $head expected$$ Is the value (not including double quotes) for the string that is expected. If this string is not found, the error is reported and this function does not return. In the special case where $icode expected$$ is empty, any string will be accepted. $head token_$$ If this routine returns, $icode token_$$ is the string that was found. $head Prototype$$ $srccode%hpp% */ public: void check_next_string(const std::string& expected); /* %$$ $end ------------------------------------------------------------------------------- $begin json_lexer_next_non_neg_int$$ $spell json lexer neg $$ $section Get Next Non-Negative Integer$$ $head Syntax$$ $codei% %json_lexer%.next_non_neg_int() %value% = %json_lexer%.token2size_t() %$$ $head index_$$ The search for the non-negative integer starts at one greater than the input value for $code index_$$ and skips white space. $head token_$$ is set to the non-negative integer. If the next token is not a non-negative integer, the error is reported and this function does not return. $head value$$ If the current token is a non-negative integer, $icode value$$ is the corresponding value. $head Prototype$$ $srccode%hpp% */ public: void next_non_neg_int(void); size_t token2size_t(void) const; /* %$$ $end ------------------------------------------------------------------------------- $begin json_lexer_next_float$$ $spell json lexer $$ $section Get Next Floating Point Number$$ $head Syntax$$ $codei% %ok% = %json_lexer%.next_float() %value% = %json_lexer%.token2double() %$$ $head index_$$ The search for the floating point number starts at one greater than the input value for $code index_$$ and skips white space. $head token_$$ is set to the floating point number. If the next token is not a floating point number, the error is reported and this function does not return. $head value$$ If the current token is a floating point number, $icode value$$ is the corresponding value. $head Prototype$$ $srccode%hpp% */ public: void next_float(void); double token2double(void) const; /* %$$ $end */ // ========================================================================== }; // end class lexer // ========================================================================== } } } // END_NAMESPACE_CPPAD_LOCAL_GRAPH # endif fardragon/AdventOfCode2021day18/main.cpp #include "shared.hpp" #include #include #include #include #include "Node.hpp" std::vector> ParseInput(const std::vector &lines); std::uint64_t SolvePart1(const std::vector> &nodes); std::uint64_t SolvePart2(const std::vector> &nodes); int main(int argc, char **argv) { if (argc < 2) { throw std::runtime_error("Not enough input arguments"); } const auto begin = std::chrono::steady_clock::now(); const auto lines = LoadLines(argv[1]); auto input = ParseInput(lines); const auto beginSolving = std::chrono::steady_clock::now(); const auto part1Result = SolvePart1(input); const auto part2Result = SolvePart2(input); const auto end = std::chrono::steady_clock::now(); const auto elapsed = std::chrono::duration_cast(end - begin).count(); const auto elapsedSolving = std::chrono::duration_cast(end - beginSolving).count(); std::cout << "Part 1 result: " << part1Result << "\r\n"; std::cout << "Part 2 result: " << part2Result << "\r\n"; std::cout << "Time: " << elapsed << "us \r\n"; std::cout << "Time (without reading and parsing): " << elapsedSolving << "us \r\n"; return 0; } std::vector> ParseInput(const std::vector &lines) { std::vector> result {}; result.reserve(lines.size()); NodeParser parser {}; for (const auto &line: lines) { result.push_back(parser.Parse(line)); } return result; } std::uint64_t SolvePart1(const std::vector> &nodes) { auto node = nodes.front()->Copy(); for (auto it = std::next(nodes.cbegin(), 1); it != nodes.cend(); std::advance(it, 1)) { auto newNode = std::make_unique(NodeOrientation::Top, std::make_pair(nullptr, nullptr)); node->SetParent(newNode.get()); node->SetOrientation(NodeOrientation::Left); auto addNode = (*it)->Copy(); addNode->SetParent(newNode.get()); addNode->SetOrientation(NodeOrientation::Right); newNode->SetNested(std::make_pair(std::move(node), std::move(addNode))); node = std::move(newNode); node->Reduce(); } return node->GetMagnitude(); } std::uint64_t SolvePart2(const std::vector> &nodes) { std::set results; for (auto it1 = nodes.cbegin(); it1 != nodes.cend(); std::advance(it1, 1)) { for (auto it2 = nodes.cbegin(); it2 != nodes.cend(); std::advance(it2, 1)) { if (it1 != it2) { auto newNode = std::make_unique(NodeOrientation::Top, std::make_pair(nullptr, nullptr)); auto lNode = (*it1)->Copy(); lNode->SetParent(newNode.get()); lNode->SetOrientation(NodeOrientation::Left); auto rNode = (*it2)->Copy(); rNode->SetParent(newNode.get()); rNode->SetOrientation(NodeOrientation::Right); newNode->SetNested(std::make_pair(std::move(lNode), std::move(rNode))); newNode->Reduce(); results.emplace(newNode->GetMagnitude()); } } } return *results.rbegin(); }ut/source/test_ck_sha_256.cpp #include "test_ck_sha_256.h" #include "cppkit/ck_sha_256.h" using namespace std; using namespace cppkit; REGISTER_TEST_FIXTURE(test_ck_sha_256); void test_ck_sha_256::setup() { } void test_ck_sha_256::teardown() { } void test_ck_sha_256::test_hash_basic() { ck_sha_256 sha256; string msg = "Beneath this mask there is an idea, Mr. Creedy, and ideas are bulletproof."; sha256.update((uint8_t*)msg.c_str(), msg.length()); sha256.finalize(); auto output = sha256.get_as_string(); RTF_ASSERT( output == "ddeb9f4cbc687d0a49d0ae60a683e0b62d3e4e27d91404690d37690e890f1d5c" ); } //===--- SILGenBuilder.cpp ------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #include "SILGenBuilder.h" #include "SILGenFunction.h" using namespace swift; using namespace Lowering; //===----------------------------------------------------------------------===// // Utility Methods //===----------------------------------------------------------------------===// SILGenModule &SILGenBuilder::getSILGenModule() const { return gen.SGM; } //===----------------------------------------------------------------------===// // Constructors //===----------------------------------------------------------------------===// SILGenBuilder::SILGenBuilder(SILGenFunction &gen) : SILBuilder(gen.F), gen(gen) {} SILGenBuilder::SILGenBuilder(SILGenFunction &gen, SILBasicBlock *insertBB) : SILBuilder(insertBB), gen(gen) {} SILGenBuilder::SILGenBuilder(SILGenFunction &gen, SILBasicBlock *insertBB, SmallVectorImpl *insertedInsts) : SILBuilder(insertBB, insertedInsts), gen(gen) {} SILGenBuilder::SILGenBuilder(SILGenFunction &gen, SILBasicBlock *insertBB, SILBasicBlock::iterator insertInst) : SILBuilder(insertBB, insertInst), gen(gen) {} //===----------------------------------------------------------------------===// // Instruction Emission //===----------------------------------------------------------------------===// MetatypeInst *SILGenBuilder::createMetatype(SILLocation loc, SILType metatype) { auto theMetatype = metatype.castTo(); // Getting a nontrivial metatype requires forcing any conformances necessary // to instantiate the type. switch (theMetatype->getRepresentation()) { case MetatypeRepresentation::Thin: break; case MetatypeRepresentation::Thick: case MetatypeRepresentation::ObjC: { // Walk the type recursively to look for substitutions we may need. theMetatype.getInstanceType().findIf([&](Type t) -> bool { if (!t->getAnyNominal()) return false; auto subs = t->gatherAllSubstitutions(getSILGenModule().SwiftModule, nullptr); getSILGenModule().useConformancesFromSubstitutions(subs); return false; }); break; } } return SILBuilder::createMetatype(loc, metatype); } ApplyInst *SILGenBuilder::createApply(SILLocation Loc, SILValue Fn, SILType SubstFnTy, SILType Result, SubstitutionList Subs, ArrayRef Args) { getSILGenModule().useConformancesFromSubstitutions(Subs); return SILBuilder::createApply(Loc, Fn, SubstFnTy, Result, Subs, Args, false); } TryApplyInst *SILGenBuilder::createTryApply(SILLocation loc, SILValue Fn, SILType substFnTy, SubstitutionList subs, ArrayRef args, SILBasicBlock *normalBB, SILBasicBlock *errorBB) { getSILGenModule().useConformancesFromSubstitutions(subs); return SILBuilder::createTryApply(loc, Fn, substFnTy, subs, args, normalBB, errorBB); } PartialApplyInst *SILGenBuilder::createPartialApply( SILLocation Loc, SILValue Fn, SILType SubstFnTy, SubstitutionList Subs, ArrayRef Args, SILType ClosureTy) { getSILGenModule().useConformancesFromSubstitutions(Subs); return SILBuilder::createPartialApply(Loc, Fn, SubstFnTy, Subs, Args, ClosureTy); } BuiltinInst *SILGenBuilder::createBuiltin(SILLocation Loc, Identifier Name, SILType ResultTy, SubstitutionList Subs, ArrayRef Args) { getSILGenModule().useConformancesFromSubstitutions(Subs); return SILBuilder::createBuiltin(Loc, Name, ResultTy, Subs, Args); } InitExistentialAddrInst *SILGenBuilder::createInitExistentialAddr( SILLocation Loc, SILValue Existential, CanType FormalConcreteType, SILType LoweredConcreteType, ArrayRef Conformances) { for (auto conformance : Conformances) getSILGenModule().useConformance(conformance); return SILBuilder::createInitExistentialAddr( Loc, Existential, FormalConcreteType, LoweredConcreteType, Conformances); } InitExistentialMetatypeInst *SILGenBuilder::createInitExistentialMetatype( SILLocation loc, SILValue metatype, SILType existentialType, ArrayRef conformances) { for (auto conformance : conformances) getSILGenModule().useConformance(conformance); return SILBuilder::createInitExistentialMetatype( loc, metatype, existentialType, conformances); } InitExistentialRefInst *SILGenBuilder::createInitExistentialRef( SILLocation Loc, SILType ExistentialType, CanType FormalConcreteType, SILValue Concrete, ArrayRef Conformances) { for (auto conformance : Conformances) getSILGenModule().useConformance(conformance); return SILBuilder::createInitExistentialRef( Loc, ExistentialType, FormalConcreteType, Concrete, Conformances); } AllocExistentialBoxInst *SILGenBuilder::createAllocExistentialBox( SILLocation Loc, SILType ExistentialType, CanType ConcreteType, ArrayRef Conformances) { for (auto conformance : Conformances) getSILGenModule().useConformance(conformance); return SILBuilder::createAllocExistentialBox(Loc, ExistentialType, ConcreteType, Conformances); } ManagedValue SILGenBuilder::createStructExtract(SILLocation Loc, ManagedValue Base, VarDecl *Decl) { ManagedValue BorrowedBase = gen.emitManagedBeginBorrow(Loc, Base.getValue()); SILValue StructExtract = SILBuilder::createStructExtract(Loc, BorrowedBase.getValue(), Decl); return ManagedValue::forUnmanaged(StructExtract); } ManagedValue SILGenBuilder::createCopyValue(SILLocation Loc, ManagedValue OriginalValue) { SILValue Result = SILBuilder::createCopyValue(Loc, OriginalValue.getValue()); return gen.emitManagedRValueWithCleanup(Result); } ManagedValue SILGenBuilder::createCopyUnownedValue(SILLocation Loc, ManagedValue OriginalValue) { auto UnownedType = OriginalValue.getType().castTo(); assert(UnownedType->isLoadable(ResilienceExpansion::Maximal)); (void)UnownedType; SILValue Result = SILBuilder::createCopyUnownedValue(Loc, OriginalValue.getValue()); return gen.emitManagedRValueWithCleanup(Result); } ManagedValue SILGenBuilder::createUnsafeCopyUnownedValue(SILLocation Loc, ManagedValue OriginalValue) { auto UnmanagedType = OriginalValue.getType().getAs(); SILValue Result = SILBuilder::createUnmanagedToRef( Loc, OriginalValue.getValue(), SILType::getPrimitiveObjectType(UnmanagedType.getReferentType())); SILBuilder::createUnmanagedRetainValue(Loc, Result); return gen.emitManagedRValueWithCleanup(Result); } ManagedValue SILGenBuilder::createOwnedPHIArgument(SILType Type) { SILPHIArgument *Arg = getInsertionBB()->createPHIArgument(Type, ValueOwnershipKind::Owned); return gen.emitManagedRValueWithCleanup(Arg); } #include "sfge/behaviours/render_sprite_behaviour.hpp" #include "sfge/graphics/graphic_system.hpp" #include "sfge/infrastructure/attribute.hpp" #include "sfge/infrastructure/builtin_attributes.hpp" #include "sfge/infrastructure/builtin_messages.hpp" #include "sfge/infrastructure/game_object.hpp" #include "sfge/infrastructure/game.hpp" #include "sfge/infrastructure/message_manager.hpp" #include "sfge/utilities/ptree_parse_helpers_sfml.hpp" #include using namespace boost; using namespace sf; namespace sfge { RenderSpriteBehaviour::RenderSpriteBehaviour(GameObjectWeakPtr owner) : Behaviour(owner) { RegisterAttribute(AK_Color, &Color::White); RegisterAttribute(AK_Origin); RegisterAttribute(AK_SpriteRegion, IntRect(-1, -1, -1, -1)); MessageKey msgKey; msgKey.mID = MID_AttributeChanged; msgKey.mSource = mOwner; MessageReceiver slot = MessageReceiver::from_method(this); MessageManager::getSingleton().SubscribeTo(msgKey, slot); } void RenderSpriteBehaviour::OnParamsReceived(const Parameters ¶ms) { // Empty Parameters used as default return value const Parameters defParams; // Read source filename const std::string &src = params.get("source", ""); assert(!src.empty()); Image img; img.loadFromFile(mOwner.lock()->GetGame()->GetImagesFolder() + "/" + src); // Apply keycolor const Parameters &keyColorParams = params.get_child("keyColor", defParams); if (keyColorParams.size() > 0) { Color keyColor; parseTo(keyColorParams, keyColor); Uint8 kcoa = params.get("keyColorOutA", 0); img.createMaskFromColor(keyColor, kcoa); } mTexture = TexturePtr(new Texture()); mTexture->loadFromImage(img); mSprite = SpritePtr(new Sprite(*mTexture)); // Apply origin if found const Parameters &origin = params.get_child("origin", defParams); if (origin.size() > 0) parseTo(origin, *GetAttribute(AK_Origin)); // Apply smoothing optional smooth = params.get_optional("smooth"); if (smooth) mTexture->setSmooth(*smooth); // Apply anything we're interested in due to unknown initialization order if (mSprite) { ApplyTransform(); ApplyRender(); } } void RenderSpriteBehaviour::OnUpdate(float /*dt*/) { if (!mSprite) return; const Attribute layer = GetAttribute(AK_LayerIndex); GraphicSystem::getSingleton().AddDrawableToLayer(layer, mSprite); } void RenderSpriteBehaviour::OnAttributeChanged(const Message &msg) { if (!mSprite) return; assert(msg.mSource.lock().get() == mOwner.lock().get()); switch (msg.mData.GetValue()) { case AK_Position: case AK_Scale: ApplyTransform(); break; case AK_Color: case AK_Origin: ApplyRender(); break; } } void RenderSpriteBehaviour::ApplyTransform() { const Attribute pos = GetAttribute(AK_Position); assert(pos.IsValid()); mSprite->setPosition(pos); const Attribute scale = GetAttribute(AK_Scale); assert(scale.IsValid()); mSprite->setScale(scale); } void RenderSpriteBehaviour::ApplyRender() { const Attribute col = GetAttribute(AK_Color); assert(col.IsValid()); mSprite->setColor(col); const Attribute origin = GetAttribute(AK_Origin); assert(origin.IsValid()); mSprite->setOrigin(origin); const Attribute region = GetAttribute(AK_SpriteRegion); assert(region.IsValid()); if (region->top != -1 && region->left != -1 && region->width != -1 && region->height != -1) mSprite->setTextureRect(region); else mSprite->setTextureRect(IntRect(0, 0, mTexture->getSize().x, mTexture->getSize().y)); } } // Copyright (C) 2011-2020 Roki. Distributed under the MIT License #ifndef INCLUDED_SROOK_MATH_CONSTANTS_ALGORITHM_ABS_HPP #define INCLUDED_SROOK_MATH_CONSTANTS_ALGORITHM_ABS_HPP #include #include #include #include #include //#if !SROOK_USE_BUILTIN_CMATH_FUNCTION or !SROOK_BUILTIN_CMATH_FUNCTION_IS_DEFINED_CONSTEXPR #include //#endif namespace srook { namespace math { inline namespace v1 { template ::value)> #if SROOK_USE_BUILTIN_CMATH_FUNCTION && SROOK_BUILTIN_CMATH_FUNCTION_IS_DEFINED_CONSTEXPR SROOK_FORCE_INLINE #else inline #endif constexpr ArithmeticType abs(ArithmeticType x) #if SROOK_USE_BUILTIN_CMATH_FUNCTION && SROOK_BUILTIN_CMATH_FUNCTION_IS_DEFINED_CONSTEXPR SROOK_NOEXCEPT(__builtin_abs(x)) #else SROOK_NOEXCEPT(math::fabs(x)) #endif { return #if SROOK_USE_BUILTIN_CMATH_FUNCTION && SROOK_BUILTIN_CMATH_FUNCTION_IS_DEFINED_CONSTEXPR __builtin_abs(x) #else static_cast(math::fabs(x)) #endif ; } } // namespace v1 } // namespace math using math::abs; } // namespace srook #endif boot/log/Log.cpp1-10 // Devon #include #include #include #include #include #include #include // STL #include #include namespace Devon { // ************************************************************************************************* // Globals LogCategory LogCategoryDefault("Default"); LogCategory LogCategoryAssertion("Assertions"); LogCategory LogCategoryException("Exceptions"); LogCategory LogCategoryLifetime("Lifetimes"); LogPop LogEnd; LogPop LogEndCommand; LogLock LockLog; // ************************************************************************************************* // Local Constants static const char* kBeginMessage = "\x001"; static const char* kEndMessage = "\x002"; static StringLog* kDeadCollector = reinterpret_cast(0xFFFFFFFF); #ifdef WIN32 static const char* kLogFilePath = "c:/temp/DevonLog.txt"; static const char* kDisabledLogsFilePath = "c:/temp/DevonDisabledLogs.txt"; #else static const char* kLogFilePath = "/tmp/DevonLog.txt"; static const char* kDisabledLogsFilePath = "/tmp/DevonDisabledLogs.txt"; #endif // ************************************************************************************************* // Local Helpers inline bool isNumber(char s) { return s >= '0' && s <= '9'; } inline bool isNotNumber(char s) { return !(s >= '0' && s <= '9'); } static std::vector& GetDisabledCategories() { static std::vector disabledCategories; return disabledCategories; } static bool IsCategoryDisabled(const std::string& name) { static std::vector& disabledCategories = GetDisabledCategories(); return std::find(disabledCategories.begin(), disabledCategories.end(), name) != disabledCategories.end(); } // ************************************************************************************************* // Global Helpers std::string CleanTypeIdName(const std::string& typeName) { // C++ doesn't specify the format of a typeid name. MSVC formats its typeids as "class ", // with no angle brackets. GCC has its own weird format, which looks something like // "N6Devon4DomainE". I don't know what the N or E mean, perhaps "namespace" and "end"? Anyway, // the numbers refer to the length of each segment of the string. This little bit here just // parses the string and turns it into something like "Devon::Domain". // (XXXblake This will fail for identifiers that contain numbers.) #ifdef WIN32 // Just strip out the "class" prefix return typeName.substr(6); #endif std::string cleanName = ""; std::string::const_iterator iter = typeName.begin(); std::string::const_iterator iterEnd = typeName.end(); while (iter != iterEnd) { std::string::const_iterator firstNum = std::find_if(iter, iterEnd, isNumber); if (firstNum == iterEnd) break; std::string::const_iterator firstNonNum = std::find_if(firstNum, iterEnd, isNotNumber); if (firstNonNum == iterEnd) break; std::string charCountStr = std::string(firstNum, firstNonNum); unsigned int charCount = atoi(charCountStr.c_str()); iter = firstNonNum+charCount; if (!cleanName.empty()) cleanName += "::"; cleanName += std::string(firstNonNum, iter); } return cleanName; } // ************************************************************************************************* // Log class public Log::Log(std::ostream& stream, const std::string& name) : mStream(stream), mName(name), mCollector(NULL), mWriteLockCount(0), mIsOwned(false) { static std::vector& disabledCategories = GetDisabledCategories(); char categoryName[1024]; static std::ifstream GetDisabledLogsStream(kDisabledLogsFilePath); while (GetDisabledLogsStream.good()) { GetDisabledLogsStream.getline(categoryName, 1024); if (::strlen(categoryName) > 0) disabledCategories.push_back(categoryName); } } Log& Log::GetRootLog() { // Purposely leak the log because we need it to remain alive up until the very last // nanosecond, even after the main function, because there may be other global or // static variables that wish to use the log in their destructors, and there is no // way to predict which order these are destroyed static std::ofstream* logStream = new std::ofstream(kLogFilePath, std::ios::app); static Log* log = new Log(*logStream, "Default Log"); return *log; } Log& Log::GetStringLog() { static StringLog stringLog; return stringLog; } const std::string& Log::GetName() const { return mName; } bool Log::GetDisabled() const { AutoDevonMutex autoMutex(const_cast(&mContainerMutex)); if (mCollector == kDeadCollector) return true; else if (mCategoryStack.empty()) return false; else { const LogCategory* category = mCategoryStack.back(); return category->GetDisabled(); } } unsigned int Log::GetCategoryCount() const { return mCategories.size(); } LogCategory* Log::GetCategory(unsigned int index) const { return mCategories[index]; } void Log::AddCategory(LogCategory& category) { if (IsCategoryDisabled(category.GetName())) category.SetDisabled(true); else category.SetDisabled(false); AutoDevonMutex autoMutex(mContainerMutex); mCategories.push_back(&category); } void Log::RemoveCategory(LogCategory& category) { AutoDevonMutex autoMutex(mContainerMutex); mCategories.erase(std::remove(mCategories.begin(), mCategories.end(), &category)); } Log& Log::operator<<(long text) { if (GetDisabled()) return *this; // Not sure why the explicit cast is required on msvc. --Blake std::ostream& stream = mCollector ? (std::ostream&)mCollector->GetStream() : mStream; stream << text; return *this; } Log& Log::operator<<(unsigned long text) { if (GetDisabled()) return *this; std::ostream& stream = mCollector ? (std::ostream&)mCollector->GetStream() : mStream; stream << text; return *this; } Log& Log::operator<<(long long text) { if (GetDisabled()) return *this; std::ostream& stream = mCollector ? (std::ostream&)mCollector->GetStream() : mStream; stream << text; return *this; } Log& Log::operator<<(unsigned long long text) { if (GetDisabled()) return *this; std::ostream& stream = mCollector ? (std::ostream&)mCollector->GetStream() : mStream; stream << text; return *this; } Log& Log::operator<<(bool text) { if (GetDisabled()) return *this; std::ostream& stream = mCollector ? (std::ostream&)mCollector->GetStream() : mStream; stream << text; return *this; } Log& Log::operator<<(short text) { if (GetDisabled()) return *this; std::ostream& stream = mCollector ? (std::ostream&)mCollector->GetStream() : mStream; stream << text; return *this; } Log& Log::operator<<(unsigned short text) { if (GetDisabled()) return *this; std::ostream& stream = mCollector ? (std::ostream&)mCollector->GetStream() : mStream; stream << text; return *this; } Log& Log::operator<<(int text) { if (GetDisabled()) return *this; std::ostream& stream = mCollector ? (std::ostream&)mCollector->GetStream() : mStream; stream << text; return *this; } Log& Log::operator<<(unsigned int text) { if (GetDisabled()) return *this; std::ostream& stream = mCollector ? (std::ostream&)mCollector->GetStream() : mStream; stream << text; return *this; } Log& Log::operator<<(float text) { if (GetDisabled()) return *this; std::ostream& stream = mCollector ? (std::ostream&)mCollector->GetStream() : mStream; stream << text; return *this; } Log& Log::operator<<(double text) { if (GetDisabled()) return *this; std::ostream& stream = mCollector ? (std::ostream&)mCollector->GetStream() : mStream; stream << text; return *this; } Log& Log::operator<<(const char text) { if (GetDisabled()) return *this; std::ostream& stream = mCollector ? (std::ostream&)mCollector->GetStream() : mStream; stream << text; return *this; } Log& Log::operator<<(char* text) { return operator<<(const_cast(text)); } Log& Log::operator<<(const char* text) { if (GetDisabled()) return *this; if (text) WriteEscapedString(text, strlen(text)); else *this << "(NULL)"; return *this; } Log& Log::operator<<(wchar_t* text) { // This function is necessary because msvc defers to the generic operator<< // when you use a non-const wchar_t*. -Blake return operator<<(const_cast(text)); } Log& Log::operator<<(const wchar_t* text) { if (GetDisabled()) return *this; size_t len = wcslen(text); char* buf = new char[len + 1]; wcstombs(buf, text, len + 1); if (text) WriteEscapedString(buf, len); else *this << "(NULL)"; delete[] buf; return *this; } Log& Log::operator<<(const void* text) { if (GetDisabled()) return *this; std::ostream& stream = mCollector ? (std::ostream&)mCollector->GetStream() : mStream; stream << text; return *this; } Log& Log::operator<<(void* text) { // This function is necessary because msvc defers to the generic operator<< // when you use a non-const void* (which is what win32 HANDLEs are.) -Blake return operator<<(const_cast(text)); } Log& Log::operator<<(const std::string& text) { if (GetDisabled()) return *this; WriteEscapedString(text.c_str(), text.size()); return *this; } Log& Log::operator<<(const std::wstring& text) { return *this << text.c_str(); } Log& Log::operator<<(Log::EscapeMode escapeMode) { AutoDevonMutex autoMutex(mContainerMutex); if (escapeMode == EscapeNone) mEscapeStack.pop_back(); else mEscapeStack.push_back(escapeMode); return *this; } Log& Log::operator<<(Log& log) { return log; } Log& Log::operator<<(const LogCategory& category) { AutoDevonMutex autoMutex(mContainerMutex); // if (&category == &LogCategoryEnd) // mCategoryStack.pop_back(); // else mCategoryStack.push_back(&category); return *this; } Log& Log::operator<<(const LogCommand& command) { if (GetDisabled()) return *this; mStream.seekp(0, std::ios_base::end); mStream << kBeginMessage << "<" << command.GetName(); return *this; } Log& Log::operator<<(const LogEvent& event) { if (GetDisabled()) return *this; AutoDevonMutex autoMutex(mContainerMutex); const std::string eventName = event.GetName(); CollectorMap::const_iterator iter = mCollectors.find(eventName); if (iter != mCollectors.end()) mCollector = iter->second; else mCollector = kDeadCollector; return *this; } Log& Log::operator<<(const LogPop& pop) { std::ostream& stream = mCollector ? (std::ostream&)mCollector->GetStream() : mStream; if (&pop == &LogEndCommand) *this << "/>" << kEndMessage; else if (&pop == &LogEnd) { AutoDevonMutex autoMutex(mContainerMutex); mCategoryStack.clear(); mCollector = NULL; if (mIsOwned && pthread_equal(pthread_self(), mOwnerThread) && --mWriteLockCount == 0) { mIsOwned = false; mWriteMutex.Unlock(); } } stream.flush(); return *this; } Log& Log::operator<<(const LogLock& lock) { pthread_t id = pthread_self(); if (!mIsOwned || !pthread_equal(id, mOwnerThread)) { mWriteMutex.Lock(); mOwnerThread = id; mIsOwned = true; } ++mWriteLockCount; return *this; } void Log::Subscribe(const std::string& name) { StringLog* log = new StringLog(); AutoDevonMutex autoMutex(mContainerMutex); mCollectors[name] = log; } std::string Log::Unsubscribe(const std::string& name) { AutoDevonMutex autoMutex(mContainerMutex); CollectorMap::const_iterator iter = mCollectors.find(name); if (iter != mCollectors.end()) { std::string value = iter->second->GetString(); delete iter->second; mCollectors[name] = NULL; return value; } else return ""; } // ************************************************************************************************* // Log class protected void Log::WriteEscapedString(const char* text, unsigned int textSize) { AutoDevonMutex autoMutex(mContainerMutex); std::ostream& stream = mCollector ? (std::ostream&)mCollector->GetStream() : mStream; if (!mEscapeStack.empty()) { if (mEscapeStack.back() == EscapeXML) { const char* c = text; const char* lastWrite = c; const char* maxBytes = c + textSize; for (c; *c != 0 && c < maxBytes; ++c) { if (*c == '"') { stream.write(lastWrite, c-lastWrite); stream << """; lastWrite = c+1; } else if (*c == '&') { stream.write(lastWrite, c-lastWrite); stream << "&"; lastWrite = c+1; } else if (*c == '<') { stream.write(lastWrite, c-lastWrite); stream << "<"; lastWrite = c+1; } else if (*c == '>') { stream.write(lastWrite, c-lastWrite); stream << ">"; lastWrite = c+1; } else if (*c == '\n') { stream.write(lastWrite, c-lastWrite); stream << "\\n"; lastWrite = c+1; } else if (*c == '\r') { stream.write(lastWrite, c-lastWrite); stream << "\\r"; lastWrite = c+1; } } stream.write(lastWrite, c-lastWrite); } } else stream << text; } // ************************************************************************************************* } // namespace Devon /* * Copyright 2012 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "include/core/SkBlendMode.h" #include "include/core/SkCanvas.h" #include "include/core/SkColor.h" #include "include/core/SkFont.h" #include "include/core/SkImageInfo.h" #include "include/core/SkMatrix.h" #include "include/core/SkPaint.h" #include "include/core/SkPath.h" #include "include/core/SkPathMeasure.h" #include "include/core/SkPoint.h" #include "include/core/SkRRect.h" #include "include/core/SkRect.h" #include "include/core/SkRefCnt.h" #include "include/core/SkScalar.h" #include "include/core/SkShader.h" #include "include/core/SkString.h" #include "include/core/SkSurface.h" #include "include/core/SkTypes.h" #include "include/private/SkTArray.h" #include "include/private/SkTemplates.h" #include "include/utils/SkTextUtils.h" #include "samplecode/Sample.h" #include "src/core/SkGeometry.h" #include "src/core/SkPointPriv.h" #include "src/core/SkStroke.h" #include "tools/ToolUtils.h" #include class SkEvent; static bool hittest(const SkPoint& target, SkScalar x, SkScalar y) { const SkScalar TOL = 7; return SkPoint::Distance(target, SkPoint::Make(x, y)) <= TOL; } static int getOnCurvePoints(const SkPath& path, SkPoint storage[]) { SkPath::RawIter iter(path); SkPoint pts[4]; SkPath::Verb verb; int count = 0; while ((verb = iter.next(pts)) != SkPath::kDone_Verb) { switch (verb) { case SkPath::kMove_Verb: case SkPath::kLine_Verb: case SkPath::kQuad_Verb: case SkPath::kConic_Verb: case SkPath::kCubic_Verb: storage[count++] = pts[0]; break; default: break; } } return count; } static void getContourCounts(const SkPath& path, SkTArray* contourCounts) { SkPath::RawIter iter(path); SkPoint pts[4]; SkPath::Verb verb; int count = 0; while ((verb = iter.next(pts)) != SkPath::kDone_Verb) { switch (verb) { case SkPath::kMove_Verb: case SkPath::kLine_Verb: count += 1; break; case SkPath::kQuad_Verb: case SkPath::kConic_Verb: count += 2; break; case SkPath::kCubic_Verb: count += 3; break; case SkPath::kClose_Verb: contourCounts->push_back(count); count = 0; break; default: break; } } if (count > 0) { contourCounts->push_back(count); } } static void erase(const sk_sp& surface) { SkCanvas* canvas = surface->getCanvas(); if (canvas) { canvas->clear(SK_ColorTRANSPARENT); } } struct StrokeTypeButton { SkRect fBounds; char fLabel; bool fEnabled; }; struct CircleTypeButton : public StrokeTypeButton { bool fFill; }; class QuadStrokerView : public Sample { enum { SKELETON_COLOR = 0xFF0000FF, WIREFRAME_COLOR = 0x80FF0000 }; enum { kCount = 18 }; SkPoint fPts[kCount]; SkRect fWeightControl; SkRect fRadiusControl; SkRect fErrorControl; SkRect fWidthControl; SkRect fBounds; SkMatrix fMatrix, fInverse; sk_sp fShader; sk_sp fMinSurface; sk_sp fMaxSurface; StrokeTypeButton fCubicButton; StrokeTypeButton fConicButton; StrokeTypeButton fQuadButton; StrokeTypeButton fArcButton; StrokeTypeButton fRRectButton; CircleTypeButton fCircleButton; StrokeTypeButton fTextButton; SkString fText; SkScalar fTextSize; SkScalar fWeight; SkScalar fRadius; SkScalar fWidth, fDWidth; SkScalar fWidthScale; int fW, fH, fZoom; bool fAnimate; bool fDrawRibs; bool fDrawTangents; bool fDrawTDivs; #ifdef SK_DEBUG #define kStrokerErrorMin 0.001f #define kStrokerErrorMax 5 #endif #define kWidthMin 1 #define kWidthMax 100 public: QuadStrokerView() { this->setBGColor(SK_ColorLTGRAY); fPts[0].set(50, 200); // cubic fPts[1].set(50, 100); fPts[2].set(150, 50); fPts[3].set(300, 50); fPts[4].set(350, 200); // conic fPts[5].set(350, 100); fPts[6].set(450, 50); fPts[7].set(150, 300); // quad fPts[8].set(150, 200); fPts[9].set(250, 150); fPts[10].set(250, 200); // arc fPts[11].set(250, 300); fPts[12].set(150, 350); fPts[13].set(200, 200); // rrect fPts[14].set(400, 400); fPts[15].set(250, 250); // oval fPts[16].set(450, 450); fText = "a"; fTextSize = 12; fWidth = 50; fDWidth = 0.25f; fWeight = 1; fRadius = 150; fCubicButton.fLabel = 'C'; fCubicButton.fEnabled = false; fConicButton.fLabel = 'K'; fConicButton.fEnabled = false; fQuadButton.fLabel = 'Q'; fQuadButton.fEnabled = false; fArcButton.fLabel = 'A'; fArcButton.fEnabled = true; fRRectButton.fLabel = 'R'; fRRectButton.fEnabled = false; fCircleButton.fLabel = 'O'; fCircleButton.fEnabled = true; fCircleButton.fFill = true; fTextButton.fLabel = 'T'; fTextButton.fEnabled = false; fAnimate = false; setAsNeeded(); } protected: SkString name() override { return SkString("QuadStroker"); } bool onChar(SkUnichar uni) override { if (fTextButton.fEnabled) { switch (uni) { case ' ': fText = ""; break; case '-': fTextSize = std::max(1.0f, fTextSize - 1); break; case '+': case '=': fTextSize += 1; break; default: fText.appendUnichar(uni); } return true; } return false; } void onSizeChange() override { fRadiusControl.setXYWH(this->width() - 200, 30, 30, 400); fWeightControl.setXYWH(this->width() - 150, 30, 30, 400); fErrorControl.setXYWH(this->width() - 100, 30, 30, 400); fWidthControl.setXYWH(this->width() - 50, 30, 30, 400); int buttonOffset = 450; fCubicButton.fBounds.setXYWH(this->width() - 50, SkIntToScalar(buttonOffset), 30, 30); buttonOffset += 50; fConicButton.fBounds.setXYWH(this->width() - 50, SkIntToScalar(buttonOffset), 30, 30); buttonOffset += 50; fQuadButton.fBounds.setXYWH(this->width() - 50, SkIntToScalar(buttonOffset), 30, 30); buttonOffset += 50; fArcButton.fBounds.setXYWH(this->width() - 50, SkIntToScalar(buttonOffset), 30, 30); buttonOffset += 50; fRRectButton.fBounds.setXYWH(this->width() - 50, SkIntToScalar(buttonOffset), 30, 30); buttonOffset += 50; fCircleButton.fBounds.setXYWH(this->width() - 50, SkIntToScalar(buttonOffset), 30, 30); buttonOffset += 50; fTextButton.fBounds.setXYWH(this->width() - 50, SkIntToScalar(buttonOffset), 30, 30); this->INHERITED::onSizeChange(); } void copyMinToMax() { erase(fMaxSurface); SkCanvas* canvas = fMaxSurface->getCanvas(); canvas->save(); canvas->concat(fMatrix); fMinSurface->draw(canvas, 0, 0, nullptr); canvas->restore(); SkPaint paint; paint.setBlendMode(SkBlendMode::kClear); for (int iy = 1; iy < fH; ++iy) { SkScalar y = SkIntToScalar(iy * fZoom); canvas->drawLine(0, y - SK_ScalarHalf, 999, y - SK_ScalarHalf, paint); } for (int ix = 1; ix < fW; ++ix) { SkScalar x = SkIntToScalar(ix * fZoom); canvas->drawLine(x - SK_ScalarHalf, 0, x - SK_ScalarHalf, 999, paint); } } void setWHZ(int width, int height, int zoom) { fZoom = zoom; fBounds.setIWH(width * zoom, height * zoom); fMatrix.setScale(SkIntToScalar(zoom), SkIntToScalar(zoom)); fInverse.setScale(SK_Scalar1 / zoom, SK_Scalar1 / zoom); fShader = ToolUtils::create_checkerboard_shader(0xFFCCCCCC, 0xFFFFFFFF, zoom); SkImageInfo info = SkImageInfo::MakeN32Premul(width, height); fMinSurface = SkSurface::MakeRaster(info); info = info.makeWH(width * zoom, height * zoom); fMaxSurface = SkSurface::MakeRaster(info); } void draw_points(SkCanvas* canvas, const SkPath& path, SkColor color, bool show_lines) { SkPaint paint; paint.setColor(color); paint.setAlpha(0x80); paint.setAntiAlias(true); int n = path.countPoints(); SkAutoSTArray<32, SkPoint> pts(n); if (show_lines && fDrawTangents) { SkTArray contourCounts; getContourCounts(path, &contourCounts); SkPoint* ptPtr = pts.get(); for (int i = 0; i < contourCounts.count(); ++i) { int count = contourCounts[i]; path.getPoints(ptPtr, count); canvas->drawPoints(SkCanvas::kPolygon_PointMode, count, ptPtr, paint); ptPtr += count; } } else { n = getOnCurvePoints(path, pts.get()); } paint.setStrokeWidth(5); canvas->drawPoints(SkCanvas::kPoints_PointMode, n, pts.get(), paint); } void draw_ribs(SkCanvas* canvas, const SkPath& path, SkScalar width, SkColor color) { const SkScalar radius = width / 2; SkPathMeasure meas(path, false); SkScalar total = meas.getLength(); SkScalar delta = 8; SkPaint paint, labelP; paint.setColor(color); labelP.setColor(color & 0xff5f9f5f); SkFont font; SkPoint pos, tan; int index = 0; for (SkScalar dist = 0; dist <= total; dist += delta) { if (meas.getPosTan(dist, &pos, &tan)) { tan.scale(radius); SkPointPriv::RotateCCW(&tan); canvas->drawLine(pos.x() + tan.x(), pos.y() + tan.y(), pos.x() - tan.x(), pos.y() - tan.y(), paint); if (0 == index % 10) { SkString label; label.appendS32(index); SkRect dot = SkRect::MakeXYWH(pos.x() - 2, pos.y() - 2, 4, 4); canvas->drawRect(dot, labelP); canvas->drawString(label, pos.x() - tan.x() * 1.25f, pos.y() - tan.y() * 1.25f, font, labelP); } } ++index; } } void draw_t_divs(SkCanvas* canvas, const SkPath& path, SkScalar width, SkColor color) { const SkScalar radius = width / 2; SkPaint paint; paint.setColor(color); SkPathMeasure meas(path, false); SkScalar total = meas.getLength(); SkScalar delta = 8; int ribs = 0; for (SkScalar dist = 0; dist <= total; dist += delta) { ++ribs; } SkPath::RawIter iter(path); SkPoint pts[4]; if (SkPath::kMove_Verb != iter.next(pts)) { SkASSERT(0); return; } SkPath::Verb verb = iter.next(pts); SkASSERT(SkPath::kLine_Verb <= verb && verb <= SkPath::kCubic_Verb); SkPoint pos, tan; for (int index = 0; index < ribs; ++index) { SkScalar t = (SkScalar) index / ribs; switch (verb) { case SkPath::kLine_Verb: tan = pts[1] - pts[0]; pos = pts[0]; pos.fX += tan.fX * t; pos.fY += tan.fY * t; break; case SkPath::kQuad_Verb: pos = SkEvalQuadAt(pts, t); tan = SkEvalQuadTangentAt(pts, t); break; case SkPath::kConic_Verb: { SkConic conic(pts, iter.conicWeight()); pos = conic.evalAt(t); tan = conic.evalTangentAt(t); } break; case SkPath::kCubic_Verb: SkEvalCubicAt(pts, t, &pos, &tan, nullptr); break; default: SkASSERT(0); return; } tan.setLength(radius); SkPointPriv::RotateCCW(&tan); canvas->drawLine(pos.x() + tan.x(), pos.y() + tan.y(), pos.x() - tan.x(), pos.y() - tan.y(), paint); if (0 == index % 10) { SkString label; label.appendS32(index); canvas->drawString(label, pos.x() + tan.x() * 1.25f, pos.y() + tan.y() * 1.25f, SkFont(), paint); } } } void draw_stroke(SkCanvas* canvas, const SkPath& path, SkScalar width, SkScalar scale, bool drawText) { if (path.isEmpty()) { return; } SkRect bounds = path.getBounds(); this->setWHZ(SkScalarCeilToInt(bounds.right()), drawText ? SkScalarRoundToInt(scale * 3 / 2) : SkScalarRoundToInt(scale), SkScalarRoundToInt(950.0f / scale)); erase(fMinSurface); SkPaint paint; paint.setColor(0x1f1f0f0f); paint.setStyle(SkPaint::kStroke_Style); paint.setStrokeWidth(width * scale * scale); paint.setColor(0x3f0f1f3f); if (drawText) { fMinSurface->getCanvas()->drawPath(path, paint); this->copyMinToMax(); fMaxSurface->draw(canvas, 0, 0, nullptr); } paint.setAntiAlias(true); paint.setStyle(SkPaint::kStroke_Style); paint.setStrokeWidth(1); paint.setColor(SKELETON_COLOR); SkPath scaled; SkMatrix matrix; matrix.reset(); matrix.setScale(950 / scale, 950 / scale); if (drawText) { path.transform(matrix, &scaled); } else { scaled = path; } canvas->drawPath(scaled, paint); draw_points(canvas, scaled, SKELETON_COLOR, true); if (fDrawRibs) { draw_ribs(canvas, scaled, width, 0xFF00FF00); } if (fDrawTDivs) { draw_t_divs(canvas, scaled, width, 0xFF3F3F00); } SkPath fill; SkPaint p; p.setStyle(SkPaint::kStroke_Style); if (drawText) { p.setStrokeWidth(width * scale * scale); } else { p.setStrokeWidth(width); } p.getFillPath(path, &fill); SkPath scaledFill; if (drawText) { fill.transform(matrix, &scaledFill); } else { scaledFill = fill; } paint.setColor(WIREFRAME_COLOR); canvas->drawPath(scaledFill, paint); draw_points(canvas, scaledFill, WIREFRAME_COLOR, false); } void draw_fill(SkCanvas* canvas, const SkRect& rect, SkScalar width) { if (rect.isEmpty()) { return; } SkPaint paint; paint.setColor(0x1f1f0f0f); paint.setStyle(SkPaint::kStroke_Style); paint.setStrokeWidth(width); SkPath path; SkScalar maxSide = std::max(rect.width(), rect.height()) / 2; SkPoint center = { rect.fLeft + maxSide, rect.fTop + maxSide }; path.addCircle(center.fX, center.fY, maxSide); canvas->drawPath(path, paint); paint.setStyle(SkPaint::kFill_Style); path.reset(); path.addCircle(center.fX, center.fY, maxSide - width / 2); paint.setColor(0x3f0f1f3f); canvas->drawPath(path, paint); path.reset(); path.setFillType(SkPathFillType::kEvenOdd); path.addCircle(center.fX, center.fY, maxSide + width / 2); SkRect outside = SkRect::MakeXYWH(center.fX - maxSide - width, center.fY - maxSide - width, (maxSide + width) * 2, (maxSide + width) * 2); path.addRect(outside); canvas->drawPath(path, paint); } void draw_button(SkCanvas* canvas, const StrokeTypeButton& button) { SkPaint paint; paint.setAntiAlias(true); paint.setStyle(SkPaint::kStroke_Style); paint.setColor(button.fEnabled ? 0xFF3F0000 : 0x6F3F0000); canvas->drawRect(button.fBounds, paint); paint.setColor(button.fEnabled ? 0xFF3F0000 : 0x6F3F0000); paint.setStyle(SkPaint::kFill_Style); SkFont font; font.setSize(25.0f); SkTextUtils::Draw(canvas, &button.fLabel, 1, SkTextEncoding::kUTF8, button.fBounds.centerX(), button.fBounds.fBottom - 5, font, paint, SkTextUtils::kCenter_Align); } void draw_control(SkCanvas* canvas, const SkRect& bounds, SkScalar value, SkScalar min, SkScalar max, const char* name) { SkPaint paint; paint.setAntiAlias(true); paint.setStyle(SkPaint::kStroke_Style); canvas->drawRect(bounds, paint); SkScalar scale = max - min; SkScalar yPos = bounds.fTop + (value - min) * bounds.height() / scale; paint.setColor(0xFFFF0000); canvas->drawLine(bounds.fLeft - 5, yPos, bounds.fRight + 5, yPos, paint); SkString label; label.printf("%0.3g", value); paint.setColor(0xFF000000); paint.setStyle(SkPaint::kFill_Style); SkFont font(nullptr, 11.0f); canvas->drawString(label, bounds.fLeft + 5, yPos - 5, font, paint); font.setSize(13.0f); canvas->drawString(name, bounds.fLeft, bounds.bottom() + 11, font, paint); } void setForGeometry() { fDrawRibs = true; fDrawTangents = true; fDrawTDivs = false; fWidthScale = 1; } void setForText() { fDrawRibs = fDrawTangents = fDrawTDivs = false; fWidthScale = 0.002f; } void setForSingles() { setForGeometry(); fDrawTDivs = true; } void setAsNeeded() { if (fConicButton.fEnabled || fCubicButton.fEnabled || fQuadButton.fEnabled) { setForSingles(); } else if (fRRectButton.fEnabled || fCircleButton.fEnabled || fArcButton.fEnabled) { setForGeometry(); } else { setForText(); } } bool arcCenter(SkPoint* center) { SkPath path; path.moveTo(fPts[10]); path.arcTo(fPts[11], fPts[12], fRadius); SkPath::Iter iter(path, false); SkPoint pts[4]; iter.next(pts); if (SkPath::kLine_Verb == iter.next(pts)) { iter.next(pts); } SkVector before = pts[0] - pts[1]; SkVector after = pts[1] - pts[2]; before.setLength(fRadius); after.setLength(fRadius); SkVector beforeCCW, afterCCW; SkPointPriv::RotateCCW(before, &beforeCCW); SkPointPriv::RotateCCW(after, &afterCCW); beforeCCW += pts[0]; afterCCW += pts[2]; *center = beforeCCW; if (SkScalarNearlyEqual(beforeCCW.fX, afterCCW.fX) && SkScalarNearlyEqual(beforeCCW.fY, afterCCW.fY)) { return true; } SkVector beforeCW, afterCW; SkPointPriv::RotateCW(before, &beforeCW); SkPointPriv::RotateCW(after, &afterCW); beforeCW += pts[0]; afterCW += pts[2]; *center = beforeCW; return SkScalarNearlyEqual(beforeCW.fX, afterCW.fX) && SkScalarNearlyEqual(beforeCCW.fY, afterCW.fY); } void onDrawContent(SkCanvas* canvas) override { SkPath path; SkScalar width = fWidth; if (fCubicButton.fEnabled) { path.moveTo(fPts[0]); path.cubicTo(fPts[1], fPts[2], fPts[3]); setForSingles(); draw_stroke(canvas, path, width, 950, false); } if (fConicButton.fEnabled) { path.reset(); path.moveTo(fPts[4]); path.conicTo(fPts[5], fPts[6], fWeight); setForSingles(); draw_stroke(canvas, path, width, 950, false); } if (fQuadButton.fEnabled) { path.reset(); path.moveTo(fPts[7]); path.quadTo(fPts[8], fPts[9]); setForSingles(); draw_stroke(canvas, path, width, 950, false); } if (fArcButton.fEnabled) { path.reset(); path.moveTo(fPts[10]); path.arcTo(fPts[11], fPts[12], fRadius); setForGeometry(); draw_stroke(canvas, path, width, 950, false); SkPath pathPts; pathPts.moveTo(fPts[10]); pathPts.lineTo(fPts[11]); pathPts.lineTo(fPts[12]); draw_points(canvas, pathPts, SK_ColorDKGRAY, true); } if (fRRectButton.fEnabled) { SkScalar rad = 32; SkRect r; r.setBounds(&fPts[13], 2); path.reset(); SkRRect rr; rr.setRectXY(r, rad, rad); path.addRRect(rr); setForGeometry(); draw_stroke(canvas, path, width, 950, false); path.reset(); SkRRect rr2; rr.inset(width/2, width/2, &rr2); path.addRRect(rr2, SkPathDirection::kCCW); rr.inset(-width/2, -width/2, &rr2); path.addRRect(rr2, SkPathDirection::kCW); SkPaint paint; paint.setAntiAlias(true); paint.setColor(0x40FF8844); canvas->drawPath(path, paint); } if (fCircleButton.fEnabled) { path.reset(); SkRect r; r.setBounds(&fPts[15], 2); path.addOval(r); setForGeometry(); if (fCircleButton.fFill) { if (fArcButton.fEnabled) { SkPoint center; if (arcCenter(¢er)) { r.setLTRB(center.fX - fRadius, center.fY - fRadius, center.fX + fRadius, center.fY + fRadius); } } draw_fill(canvas, r, width); } else { draw_stroke(canvas, path, width, 950, false); } } if (fTextButton.fEnabled) { path.reset(); SkFont font; font.setSize(fTextSize); SkTextUtils::GetPath(fText.c_str(), fText.size(), SkTextEncoding::kUTF8, 0, fTextSize, font, &path); setForText(); draw_stroke(canvas, path, width * fWidthScale / fTextSize, fTextSize, true); } if (fAnimate) { fWidth += fDWidth; if (fDWidth > 0 && fWidth > kWidthMax) { fDWidth = -fDWidth; } else if (fDWidth < 0 && fWidth < kWidthMin) { fDWidth = -fDWidth; } } setAsNeeded(); if (fConicButton.fEnabled) { draw_control(canvas, fWeightControl, fWeight, 0, 5, "weight"); } if (fArcButton.fEnabled) { draw_control(canvas, fRadiusControl, fRadius, 0, 500, "radius"); } #ifdef SK_DEBUG draw_control(canvas, fErrorControl, gDebugStrokerError, kStrokerErrorMin, kStrokerErrorMax, "error"); #endif draw_control(canvas, fWidthControl, fWidth * fWidthScale, kWidthMin * fWidthScale, kWidthMax * fWidthScale, "width"); draw_button(canvas, fQuadButton); draw_button(canvas, fCubicButton); draw_button(canvas, fConicButton); draw_button(canvas, fArcButton); draw_button(canvas, fRRectButton); draw_button(canvas, fCircleButton); draw_button(canvas, fTextButton); } class MyClick : public Click { public: int fIndex; MyClick(int index) : fIndex(index) {} }; virtual Sample::Click* onFindClickHandler(SkScalar x, SkScalar y, skui::ModifierKey modi) override { for (size_t i = 0; i < SK_ARRAY_COUNT(fPts); ++i) { if (hittest(fPts[i], x, y)) { return new MyClick((int)i); } } const SkRect& rectPt = SkRect::MakeXYWH(x, y, 1, 1); if (fWeightControl.contains(rectPt)) { return new MyClick((int) SK_ARRAY_COUNT(fPts) + 1); } if (fRadiusControl.contains(rectPt)) { return new MyClick((int) SK_ARRAY_COUNT(fPts) + 2); } #ifdef SK_DEBUG if (fErrorControl.contains(rectPt)) { return new MyClick((int) SK_ARRAY_COUNT(fPts) + 3); } #endif if (fWidthControl.contains(rectPt)) { return new MyClick((int) SK_ARRAY_COUNT(fPts) + 4); } if (fCubicButton.fBounds.contains(rectPt)) { fCubicButton.fEnabled ^= true; return new MyClick((int) SK_ARRAY_COUNT(fPts) + 5); } if (fConicButton.fBounds.contains(rectPt)) { fConicButton.fEnabled ^= true; return new MyClick((int) SK_ARRAY_COUNT(fPts) + 6); } if (fQuadButton.fBounds.contains(rectPt)) { fQuadButton.fEnabled ^= true; return new MyClick((int) SK_ARRAY_COUNT(fPts) + 7); } if (fArcButton.fBounds.contains(rectPt)) { fArcButton.fEnabled ^= true; return new MyClick((int) SK_ARRAY_COUNT(fPts) + 8); } if (fRRectButton.fBounds.contains(rectPt)) { fRRectButton.fEnabled ^= true; return new MyClick((int) SK_ARRAY_COUNT(fPts) + 9); } if (fCircleButton.fBounds.contains(rectPt)) { bool wasEnabled = fCircleButton.fEnabled; fCircleButton.fEnabled = !fCircleButton.fFill; fCircleButton.fFill = wasEnabled && !fCircleButton.fFill; return new MyClick((int) SK_ARRAY_COUNT(fPts) + 10); } if (fTextButton.fBounds.contains(rectPt)) { fTextButton.fEnabled ^= true; return new MyClick((int) SK_ARRAY_COUNT(fPts) + 11); } return nullptr; } static SkScalar MapScreenYtoValue(SkScalar y, const SkRect& control, SkScalar min, SkScalar max) { return (y - control.fTop) / control.height() * (max - min) + min; } bool onClick(Click* click) override { int index = ((MyClick*)click)->fIndex; if (index < (int) SK_ARRAY_COUNT(fPts)) { fPts[index].offset(click->fCurr.fX - click->fPrev.fX, click->fCurr.fY - click->fPrev.fY); } else if (index == (int) SK_ARRAY_COUNT(fPts) + 1) { fWeight = MapScreenYtoValue(click->fCurr.fY, fWeightControl, 0, 5); } else if (index == (int) SK_ARRAY_COUNT(fPts) + 2) { fRadius = MapScreenYtoValue(click->fCurr.fY, fRadiusControl, 0, 500); } #ifdef SK_DEBUG else if (index == (int) SK_ARRAY_COUNT(fPts) + 3) { gDebugStrokerError = std::max(FLT_EPSILON, MapScreenYtoValue(click->fCurr.fY, fErrorControl, kStrokerErrorMin, kStrokerErrorMax)); gDebugStrokerErrorSet = true; } #endif else if (index == (int) SK_ARRAY_COUNT(fPts) + 4) { fWidth = std::max(FLT_EPSILON, MapScreenYtoValue(click->fCurr.fY, fWidthControl, kWidthMin, kWidthMax)); fAnimate = fWidth <= kWidthMin; } return true; } private: typedef Sample INHERITED; }; /////////////////////////////////////////////////////////////////////////////// DEF_SAMPLE( return new QuadStrokerView(); ) 0 #include #include #include #include int main(int argc, char** argv) { auto logger = faabric::util::getLogger(); auto& scheduler = faabric::scheduler::getScheduler(); auto& conf = faabric::util::getSystemConfig(); bool __isRoot; int __worldSize; if (argc < 2) { logger->debug("Non-root process started"); __isRoot = false; } else if (argc < 3) { logger->error("Root process started without specifying world size!"); return 1; } else { logger->debug("Root process started"); __worldSize = std::stoi(argv[2]); __isRoot = true; logger->debug("MPI World Size: {}", __worldSize); } // Pre-load message to bootstrap execution if (__isRoot) { faabric::Message msg = faabric::util::messageFactory("mpi", "exec"); msg.set_mpiworldsize(__worldSize); scheduler.callFunction(msg); } { faabric::executor::SingletonPool p; p.startPool(); } return 0; } int faabric::executor::mpiFunc() { MPI_Init(NULL, NULL); int rank; int worldSize; MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_Comm_size(MPI_COMM_WORLD, &worldSize); if (worldSize < 4) { printf("Need world size of 3 or more\n"); return 1; } if (rank == 0) { // Send messages out int out[3] = { 111, 222, 333 }; MPI_Send(&out[0], 1, MPI_INT, 1, 0, MPI_COMM_WORLD); MPI_Send(&out[1], 1, MPI_INT, 2, 0, MPI_COMM_WORLD); MPI_Send(&out[2], 1, MPI_INT, 3, 0, MPI_COMM_WORLD); // Get responses out of order int in[3] = { 0, 0, 0 }; MPI_Recv(&in[2], 1, MPI_INT, 3, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); MPI_Recv(&in[0], 1, MPI_INT, 1, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); MPI_Recv(&in[1], 1, MPI_INT, 2, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); // Check values if (out[0] != in[0] || out[1] != in[1] || out[2] != in[2]) { printf("Responses not as expected (got [%i, %i, %i], expected [%i, " "%i, %i]\n", in[0], in[1], in[2], out[0], out[1], out[2]); return 1; } else { printf("MPI order check successful\n"); } } else if (rank > 0 && rank <= 3) { // Echo message back to master int receivedNumber = 0; MPI_Recv( &receivedNumber, 1, MPI_INT, 0, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); MPI_Send(&receivedNumber, 1, MPI_INT, 0, 0, MPI_COMM_WORLD); } MPI_Finalize(); return 0; } goksanisil23/lazyECS0 #include "Minimal3D.h" #include "Spawner.hpp" extern json launch_obj; Minimal3D::Minimal3D(bool isFullscreen, int windowWidth, int windowHeight) : prevAppTime_{std::chrono::high_resolution_clock::now()}, deltaTime_(0.0), timeAccumulator_(0.0) { // --------------- lAZYECS -------------- // gOrchestrator.Init(); // initializes the ECS managers // Register the components gOrchestrator.RegisterComponentType(); gOrchestrator.RegisterComponentType(); gOrchestrator.RegisterComponentType(); gOrchestrator.RegisterComponentType(); // Register the systems (calls Constructors during registration) physicsSys = gOrchestrator.RegisterSystem(); renderSys = gOrchestrator.RegisterSystem(isFullscreen, windowWidth, windowHeight, "Minimal 3D"); // entities below will be matched with systems so signature of the system is set renderSys->SetupSignature(); physicsSys->SetupSignature(); // Create the entities and assign components json entities_json = launch_obj.at("entities"); lazyECS::Spawner::CreatePhysicsEntities(entities_json); lazyECS::Spawner::CreateTerrainEntity(entities_json); lazyECS::Spawner::CreateRenderOnlyEntities(entities_json); // Init requires the entities to be initialized and entities requires system's signature to be set renderSys->Init(); physicsSys->Init(); } void Minimal3D::main_loop() { auto main_loop_step = [this]() { auto current_app_time = std::chrono::high_resolution_clock::now(); this->deltaTime_ = std::chrono::duration(current_app_time-prevAppTime_).count(); this->prevAppTime_ = current_app_time; // update previous time this->timeAccumulator_ += deltaTime_; while(this->timeAccumulator_ >= APP_STEP_TIME ) { this->timeAccumulator_ -= APP_STEP_TIME; // ------------- 1) Apply ego control, NPC AI, kinematic control, etc. ------------- // for(auto& entity : this->physicsSys->m_entities) { auto& rigidBody = gOrchestrator.GetComponent(entity); if(rigidBody.rp3d_bodyType == rp3d::BodyType::DYNAMIC) // set force for the dynamic bodies rigidBody.rp3d_rigidBody->applyForceToCenterOfMass(rp3d::Vector3(0.4,0,0.0)); else if (rigidBody.rp3d_bodyType == rp3d::BodyType::KINEMATIC) // set velocity for the kinematic body rigidBody.rp3d_rigidBody->setLinearVelocity(rp3d::Vector3(0.2,0.0,0.0)); } // Update render only entities for(auto& entity : this->renderSys->m_entities) { if (!gOrchestrator.CheckComponentExistsInEntity(entity)) { // if render only entity auto & trans = gOrchestrator.GetComponent(entity); trans.rp3d_transform.setPosition(trans.rp3d_transform.getPosition() + rp3d::Vector3(0,0,0.02)); } } // ------------- 2) Update physics ------------- // // (needs to happen right after Actor applies force/teleports on rigid body) this->physicsSys->Update(); } // ------------- 3) Update graphics ------------- // this->renderSys->Update(); }; // start the render timer thread to trigger render pipeline periodically std::thread render_timer_thread(&lazyECS::RenderingSystem::TimerThreadFunc, this->renderSys); try { while(true) { main_loop_step(); } } catch (const std::exception& e) { std::cerr << "Caught exception in lazyECS main loop: " << e.what() << std::endl; } render_timer_thread.join(); }10-100 #pragma once #include "pool.hpp" #include "utility/range.hpp" #include "abstract_component_pool.hpp" #include #include namespace gorc { template class component_pool : public abstract_component_pool { private: using PoolT = pool; using IndexT = std::unordered_multimap; public: using iterator = typename IndexT::iterator; using const_iterator = typename IndexT::const_iterator; private: PoolT components; IndexT index; std::unordered_map erase_queue; public: auto begin() { return index.begin(); } auto end() { return index.end(); } template CompT& emplace(IdT parent, ArgT &&...args) { auto &em = components.emplace(std::forward(args)...); index.emplace(parent, &em); return em; } auto erase(const_iterator it) { erase_queue.emplace(it->second, it); return ++it; } auto erase(const_iterator begin, const_iterator end) { for(auto it = begin; it != end; ++it) { erase_queue.emplace(it->second, it); } return end; } auto erase(range const &rng) { erase(rng.begin(), rng.end()); return rng.end(); } auto erase(range const &rng) { erase(rng.begin(), rng.end()); return rng.end(); } range equal_range(IdT id) { return make_range(index.equal_range(id)); } range equal_range(IdT id) const { return make_range(index.equal_range(id)); } virtual void erase_equal_range(IdT id) override { erase(equal_range(id)); } template void erase_if(PredT pred) { for(const_iterator it = index.begin(); it != index.end(); ) { bool should_delete = pred(it->first, *it->second); if(should_delete) { it = erase(it); } else { ++it; } } return; } virtual void flush_erase_queue() override { for(auto const &em : erase_queue) { LOG_DEBUG(format("erasing component %s for entity %d") % typeid(CompT).name() % static_cast(em.second->first)); components.erase(*em.second->second); index.erase(em.second); } erase_queue.clear(); } }; } // // Created by on 15/08/20. // #include "SortingLevelCombinationFinder.h" #include #include #include #include static bool comparePlayerInfoAsc(const PlayerInfo &lhs, const PlayerInfo &rhs) { return lhs.level < rhs.level; } static bool comparePlayerInfoDesc(const PlayerInfo &lhs, const PlayerInfo &rhs) { return rhs.level < lhs.level; } QVector SortingLevelCombinationFinder::doFind(const QVector &players, unsigned int numCourtAvailable) const { if (players.isEmpty() || numCourtAvailable == 0 || numPlayersPerCourt_ == 0) { return {}; } using namespace ranges; auto comparator = (sorting_ == Sorting::ASC) ? &comparePlayerInfoAsc : &comparePlayerInfoDesc; unsigned numOnCourt = std::min(numCourtAvailable, players.size() / numPlayersPerCourt_) * numPlayersPerCourt_; auto topPlayers = players | to>() | actions::shuffle(std::default_random_engine(randomSeed_)) | actions::stable_sort(comparator) | actions::take(numOnCourt); return topPlayers | views::chunk(numPlayersPerCourt_) | views::transform( [](auto players) { return CourtAllocation{players | to>(), 100}; }) | to>(); } /** @file @warning Automatically Generated */ /** @warning AUTOMATICALLY GENERATED */ #ifndef _RYSQ_KERNEL_QUADRATURE2_IMPL_HPP_ #define _RYSQ_KERNEL_QUADRATURE2_IMPL_HPP_ #include "rysq/config.hpp" #include "kernel/eri.hpp" #include "meta.hpp" #include "vector.hpp" BEGIN_NAMESPACE(rysq, kernel, quadrature) namespace recurrence { static inline double coefficient(double A1, double B, double t2) { return 0.5*A1*(1.0 - B*t2); } template static inline double coefficient(const Vector<3> &rAi, double B, const Vector<3> &rAB, double t2) { return rAi[q] - B*rAB[q]*t2; } template static inline Vector coefficient(const Vector<3> &rAi, double B, const Vector<3> &rAB, double (&t2)[N]) { Vector C; for (int a = 0; a < N; ++a) { C[a] = coefficient(rAi, B, rAB, t2[a]); } } } namespace mpl = boost::mpl; template<> struct impl > { typedef void enable; static const bool value = true; static inline void eval(double A, double B, const Vector<3> &rAi, const Vector<3> &rBk, const Vector<3> &rAB, const Vector<3> &rij, const Vector<3> &rkl, const Vector<2> &t2, const Vector<2> &W, const double (&C)[1], double (&I)[27]) { #define pow(x,y) util::pow<(y)>::eval((x)) const int N = 2; double xij = rij[0]; double yij = rij[1]; double zij = rij[2]; // // double vB00[N] __attribute__ ((aligned(16))); // // // double vB10[N] __attribute__ ((aligned(16))); // // // // double vCx[N] __attribute__ ((aligned(16))); // double vCy[N] __attribute__ ((aligned(16))); // double vCz[N] __attribute__ ((aligned(16))); // // // double vDx[N] __attribute__ ((aligned(16))); // double vDy[N] __attribute__ ((aligned(16))); // double vDz[N] __attribute__ ((aligned(16))); // // for (int a = 0; a < N; ++a) { // // vB00[a] = 0.5*t2[a]; // // // vB10[a] = recurrence::coefficient(1.0/A, B, t2[a]); // // // // vCx[a] = recurrence::coefficient<0>(rAi, B, rAB, t2[a]); // vCy[a] = recurrence::coefficient<1>(rAi, B, rAB, t2[a]); // vCz[a] = recurrence::coefficient<2>(rAi, B, rAB, t2[a]); // // // vDx[a] = recurrence::coefficient<0>(rBk, -A, rAB, t2[a]); // vDy[a] = recurrence::coefficient<1>(rBk, -A, rAB, t2[a]); // vDz[a] = recurrence::coefficient<2>(rBk, -A, rAB, t2[a]); // // } // #define B00 vB00[a] // #define B10 vB10[a] // #define B01 vB01[a] // #define Cx vCx[a] // #define Cy vCy[a] // #define Cz vCz[a] // #define Dx vDx[a] // #define Dy vDy[a] // #define Dz vDz[a] #if defined (__INTEL_COMPILER) #pragma ivdep #pragma vector aligned #endif for (int a = 0; a < N; ++a) { double B00 = 0.5*t2[a]; double B10 = recurrence::coefficient(1.0/A, B, t2[a]); double Cx = recurrence::coefficient<0>(rAi, B, rAB, t2[a]); double Cy = recurrence::coefficient<1>(rAi, B, rAB, t2[a]); double Cz = recurrence::coefficient<2>(rAi, B, rAB, t2[a]); double Dx = recurrence::coefficient<0>(rBk, -A, rAB, t2[a]); double Dy = recurrence::coefficient<1>(rBk, -A, rAB, t2[a]); double Dz = recurrence::coefficient<2>(rBk, -A, rAB, t2[a]); double Ix = (Cx + xij); double Iy = (Cy + yij); double Iz = (Cz + zij); double Qx = (Cx*Dx + B00); double Qy = (Cy*Dy + B00); double Qz = (Cz*Dz + B00); double f1 = (B00 + Dz*Iz); double f11 = (B10 + Cz*Iz); double f3 = (Cy*Iy + B10); double f7 = (Cx*Ix + B10); I[0] += C[0]*W[a]*((Dz*(B10 + Cz*Iz) + B00*(2*Cz + zij))); I[1] += C[0]*W[a]*(Cy*(Dx*xij + Qx)); I[2] += C[0]*W[a]*(Cz*(Dx*xij + Qx)); I[3] += C[0]*W[a]*((Dx*(Cx*Ix + B10) + B00*(xij + 2*Cx))); I[4] += C[0]*W[a]*((B00*(yij + 2*Cy) + Dy*(Cy*Iy + B10))); I[5] += C[0]*W[a]*(Cx*(Dy*yij + Qy)); I[6] += C[0]*W[a]*(Cz*(Dy*yij + Qy)); I[7] += C[0]*W[a]*(Cz*Dy*Ix); I[8] += C[0]*W[a]*(Cx*Dy*Iz); I[9] += C[0]*W[a]*(Cy*Dx*Iz); I[10] += C[0]*W[a]*(Cy*Dz*Ix); I[11] += C[0]*W[a]*(Cx*Dz*Iy); I[12] += C[0]*W[a]*(Cz*Dx*Iy); I[13] += C[0]*W[a]*(Dx*f3); I[14] += C[0]*W[a]*(Dx*f11); I[15] += C[0]*W[a]*(Dy*f11); I[16] += C[0]*W[a]*(Dy*f7); I[17] += C[0]*W[a]*(Dz*f7); I[18] += C[0]*W[a]*(Dz*f3); I[19] += C[0]*W[a]*(Ix*Qz); I[20] += C[0]*W[a]*(Ix*Qy); I[21] += C[0]*W[a]*(Iz*Qy); I[22] += C[0]*W[a]*(Iz*Qx); I[23] += C[0]*W[a]*(Iy*Qx); I[24] += C[0]*W[a]*(Iy*Qz); I[25] += C[0]*W[a]*(Cx*f1); I[26] += C[0]*W[a]*(Cy*f1); } #undef B00 #undef B10 #undef B01 #undef Cx #undef Cy #undef Cz #undef Dx #undef Dy #undef Dz #undef pow } static inline void reorder(double (&I)[27]) { double T[27]; for (int i = 0; i < 27; ++i) { T[i] = I[i]; } I[26] = T[0]; I[1] = T[1]; I[2] = T[2]; I[0] = T[3]; I[13] = T[4]; I[12] = T[5]; I[14] = T[6]; I[11] = T[7]; I[15] = T[8]; I[7] = T[9]; I[19] = T[10]; I[21] = T[11]; I[5] = T[12]; I[4] = T[13]; I[8] = T[14]; I[17] = T[15]; I[9] = T[16]; I[18] = T[17]; I[22] = T[18]; I[20] = T[19]; I[10] = T[20]; I[16] = T[21]; I[6] = T[22]; I[3] = T[23]; I[23] = T[24]; I[24] = T[25]; I[25] = T[26]; } }; template<> struct impl > { typedef void enable; static const bool value = true; static inline void eval(double A, double B, const Vector<3> &rAi, const Vector<3> &rBk, const Vector<3> &rAB, const Vector<3> &rij, const Vector<3> &rkl, const Vector<3> &t2, const Vector<3> &W, const double (&C)[1], double (&I)[30]) { #define pow(x,y) util::pow<(y)>::eval((x)) const int N = 3; double xij = rij[0]; double yij = rij[1]; double zij = rij[2]; // // // double vB10[N] __attribute__ ((aligned(16))); // // // // double vCx[N] __attribute__ ((aligned(16))); // double vCy[N] __attribute__ ((aligned(16))); // double vCz[N] __attribute__ ((aligned(16))); // // // for (int a = 0; a < N; ++a) { // // // vB10[a] = recurrence::coefficient(1.0/A, B, t2[a]); // // // // vCx[a] = recurrence::coefficient<0>(rAi, B, rAB, t2[a]); // vCy[a] = recurrence::coefficient<1>(rAi, B, rAB, t2[a]); // vCz[a] = recurrence::coefficient<2>(rAi, B, rAB, t2[a]); // // // } // #define B00 vB00[a] // #define B10 vB10[a] // #define B01 vB01[a] // #define Cx vCx[a] // #define Cy vCy[a] // #define Cz vCz[a] // #define Dx vDx[a] // #define Dy vDy[a] // #define Dz vDz[a] #if defined (__INTEL_COMPILER) #pragma ivdep #pragma vector aligned #endif for (int a = 0; a < N; ++a) { double B10 = recurrence::coefficient(1.0/A, B, t2[a]); double Cx = recurrence::coefficient<0>(rAi, B, rAB, t2[a]); double Cy = recurrence::coefficient<1>(rAi, B, rAB, t2[a]); double Cz = recurrence::coefficient<2>(rAi, B, rAB, t2[a]); double Ix = (Cx + xij); double Iy = (Cy + yij); double Iz = (Cz + zij); double Px = (B10 + pow(Cx,2)); double Py = (B10 + pow(Cy,2)); double Pz = (B10 + pow(Cz,2)); double f0 = (3*B10 + pow(Cx,2)); double f11 = (3*B10 + pow(Cz,2)); double f12 = (3*B10 + pow(Cy,2)); double f13 = (Iz*pow(Cz,2) + B10*(3*Cz + zij)); double f2 = (B10*(3*Cy + yij) + Iy*pow(Cy,2)); double f5 = (Cy*Iy + B10); double f6 = (B10*(3*Cx + xij) + Ix*pow(Cx,2)); double f8 = 3*pow(B10,2); I[0] += C[0]*W[a]*(Cx*Cy*(Cz*zij + Pz)); I[1] += C[0]*W[a]*(Cy*Cz*(Px + Cx*xij)); I[2] += C[0]*W[a]*((3*B10*Cx*(xij + 2*Cx) + Ix*pow(Cx,3) + f8)); I[3] += C[0]*W[a]*((Iy*pow(Cy,3) + f8 + 3*B10*Cy*(yij + 2*Cy))); I[4] += C[0]*W[a]*((3*B10*Cz*(2*Cz + zij) + f8 + Iz*pow(Cz,3))); I[5] += C[0]*W[a]*(Px*(Cz*zij + Pz)); I[6] += C[0]*W[a]*(Py*(Cz*zij + Pz)); I[7] += C[0]*W[a]*(Cx*Cz*f5); I[8] += C[0]*W[a]*(Cy*Ix*Pz); I[9] += C[0]*W[a]*(Cy*Ix*f12); I[10] += C[0]*W[a]*(Cy*Iz*f12); I[11] += C[0]*W[a]*(Cy*Iz*Px); I[12] += C[0]*W[a]*(Py*(Px + Cx*xij)); I[13] += C[0]*W[a]*(Pz*(Px + Cx*xij)); I[14] += C[0]*W[a]*(Cx*Iy*Pz); I[15] += C[0]*W[a]*(Cx*Iy*f0); I[16] += C[0]*W[a]*(Cx*Iz*f0); I[17] += C[0]*W[a]*(Cx*Iz*Py); I[18] += C[0]*W[a]*(Cz*Ix*Py); I[19] += C[0]*W[a]*(Cz*Ix*f11); I[20] += C[0]*W[a]*(Cz*Iy*f11); I[21] += C[0]*W[a]*(Cz*Iy*Px); I[22] += C[0]*W[a]*(Px*f5); I[23] += C[0]*W[a]*(Pz*f5); I[24] += C[0]*W[a]*(Cy*f6); I[25] += C[0]*W[a]*(Cz*f6); I[26] += C[0]*W[a]*(Cz*f2); I[27] += C[0]*W[a]*(Cx*f2); I[28] += C[0]*W[a]*(Cx*f13); I[29] += C[0]*W[a]*(Cy*f13); } #undef B00 #undef B10 #undef B01 #undef Cx #undef Cy #undef Cz #undef Dx #undef Dy #undef Dz #undef pow } static inline void reorder(double (&I)[30]) { double T[30]; for (int i = 0; i < 30; ++i) { T[i] = I[i]; } I[29] = T[0]; I[9] = T[1]; I[0] = T[2]; I[11] = T[3]; I[22] = T[4]; I[24] = T[5]; I[26] = T[6]; I[19] = T[7]; I[8] = T[8]; I[1] = T[9]; I[21] = T[10]; I[23] = T[11]; I[5] = T[12]; I[7] = T[13]; I[17] = T[14]; I[10] = T[15]; I[20] = T[16]; I[25] = T[17]; I[6] = T[18]; I[2] = T[19]; I[12] = T[20]; I[14] = T[21]; I[13] = T[22]; I[18] = T[23]; I[3] = T[24]; I[4] = T[25]; I[16] = T[26]; I[15] = T[27]; I[27] = T[28]; I[28] = T[29]; } }; template<> struct impl > { typedef void enable; static const bool value = true; static inline void eval(double A, double B, const Vector<3> &rAi, const Vector<3> &rBk, const Vector<3> &rAB, const Vector<3> &rij, const Vector<3> &rkl, const Vector<2> &t2, const Vector<2> &W, const double (&C)[1], double (&I)[10]) { #define pow(x,y) util::pow<(y)>::eval((x)) const int N = 2; // // // double vB10[N] __attribute__ ((aligned(16))); // // // // double vCx[N] __attribute__ ((aligned(16))); // double vCy[N] __attribute__ ((aligned(16))); // double vCz[N] __attribute__ ((aligned(16))); // // // for (int a = 0; a < N; ++a) { // // // vB10[a] = recurrence::coefficient(1.0/A, B, t2[a]); // // // // vCx[a] = recurrence::coefficient<0>(rAi, B, rAB, t2[a]); // vCy[a] = recurrence::coefficient<1>(rAi, B, rAB, t2[a]); // vCz[a] = recurrence::coefficient<2>(rAi, B, rAB, t2[a]); // // // } // #define B00 vB00[a] // #define B10 vB10[a] // #define B01 vB01[a] // #define Cx vCx[a] // #define Cy vCy[a] // #define Cz vCz[a] // #define Dx vDx[a] // #define Dy vDy[a] // #define Dz vDz[a] #if defined (__INTEL_COMPILER) #pragma ivdep #pragma vector aligned #endif for (int a = 0; a < N; ++a) { double B10 = recurrence::coefficient(1.0/A, B, t2[a]); double Cx = recurrence::coefficient<0>(rAi, B, rAB, t2[a]); double Cy = recurrence::coefficient<1>(rAi, B, rAB, t2[a]); double Cz = recurrence::coefficient<2>(rAi, B, rAB, t2[a]); double Px = (B10 + pow(Cx,2)); double Py = (B10 + pow(Cy,2)); double Pz = (B10 + pow(Cz,2)); I[0] += C[0]*W[a]*(Cx*Cy*Cz); I[1] += C[0]*W[a]*(Cy*Px); I[2] += C[0]*W[a]*(Cz*Px); I[3] += C[0]*W[a]*(Cx*Py); I[4] += C[0]*W[a]*(Cz*Py); I[5] += C[0]*W[a]*((3*B10*Cz + pow(Cz,3))); I[6] += C[0]*W[a]*((3*B10*Cy + pow(Cy,3))); I[7] += C[0]*W[a]*((3*B10*Cx + pow(Cx,3))); I[8] += C[0]*W[a]*(Cx*Pz); I[9] += C[0]*W[a]*(Cy*Pz); } #undef B00 #undef B10 #undef B01 #undef Cx #undef Cy #undef Cz #undef Dx #undef Dy #undef Dz #undef pow } static inline void reorder(double (&I)[10]) { double T[10]; for (int i = 0; i < 10; ++i) { T[i] = I[i]; } I[9] = T[0]; I[3] = T[1]; I[4] = T[2]; I[5] = T[3]; I[6] = T[4]; I[2] = T[5]; I[1] = T[6]; I[0] = T[7]; I[7] = T[8]; I[8] = T[9]; } }; template<> struct impl > { typedef void enable; static const bool value = true; static inline void eval(double A, double B, const Vector<3> &rAi, const Vector<3> &rBk, const Vector<3> &rAB, const Vector<3> &rij, const Vector<3> &rkl, const Vector<3> &t2, const Vector<3> &W, const double (&C)[1], double (&I)[54]) { #define pow(x,y) util::pow<(y)>::eval((x)) const int N = 3; double xij = rij[0]; double yij = rij[1]; double zij = rij[2]; // // double vB00[N] __attribute__ ((aligned(16))); // // // double vB10[N] __attribute__ ((aligned(16))); // // // // double vCx[N] __attribute__ ((aligned(16))); // double vCy[N] __attribute__ ((aligned(16))); // double vCz[N] __attribute__ ((aligned(16))); // // // double vDx[N] __attribute__ ((aligned(16))); // double vDy[N] __attribute__ ((aligned(16))); // double vDz[N] __attribute__ ((aligned(16))); // // for (int a = 0; a < N; ++a) { // // vB00[a] = 0.5*t2[a]; // // // vB10[a] = recurrence::coefficient(1.0/A, B, t2[a]); // // // // vCx[a] = recurrence::coefficient<0>(rAi, B, rAB, t2[a]); // vCy[a] = recurrence::coefficient<1>(rAi, B, rAB, t2[a]); // vCz[a] = recurrence::coefficient<2>(rAi, B, rAB, t2[a]); // // // vDx[a] = recurrence::coefficient<0>(rBk, -A, rAB, t2[a]); // vDy[a] = recurrence::coefficient<1>(rBk, -A, rAB, t2[a]); // vDz[a] = recurrence::coefficient<2>(rBk, -A, rAB, t2[a]); // // } // #define B00 vB00[a] // #define B10 vB10[a] // #define B01 vB01[a] // #define Cx vCx[a] // #define Cy vCy[a] // #define Cz vCz[a] // #define Dx vDx[a] // #define Dy vDy[a] // #define Dz vDz[a] #if defined (__INTEL_COMPILER) #pragma ivdep #pragma vector aligned #endif for (int a = 0; a < N; ++a) { double B00 = 0.5*t2[a]; double B10 = recurrence::coefficient(1.0/A, B, t2[a]); double Cx = recurrence::coefficient<0>(rAi, B, rAB, t2[a]); double Cy = recurrence::coefficient<1>(rAi, B, rAB, t2[a]); double Cz = recurrence::coefficient<2>(rAi, B, rAB, t2[a]); double Dx = recurrence::coefficient<0>(rBk, -A, rAB, t2[a]); double Dy = recurrence::coefficient<1>(rBk, -A, rAB, t2[a]); double Dz = recurrence::coefficient<2>(rBk, -A, rAB, t2[a]); double Ix = (Cx + xij); double Iy = (Cy + yij); double Iz = (Cz + zij); double Px = (B10 + pow(Cx,2)); double Py = (B10 + pow(Cy,2)); double Pz = (B10 + pow(Cz,2)); double Qx = (Cx*Dx + B00); double Qy = (Cy*Dy + B00); double Qz = (Cz*Dz + B00); double f1 = (B00*(yij + 2*Cy) + Dy*(Cy*Iy + B10)); double f10 = (Dy*Iy + B00); double f11 = (Cy*Iy + B10); double f12 = (B10*(3*Cx + xij) + Ix*pow(Cx,2)); double f14 = (Dx*Px + 2*B00*Cx); double f15 = (Dx*Ix + B00); double f22 = (Iz*pow(Cz,2) + B10*(3*Cz + zij)); double f3 = 3*B00*B10; double f4 = (Dy*Py + 2*B00*Cy); double f5 = (B10*(3*Cy + yij) + Iy*pow(Cy,2)); double f6 = (Dz*Pz + 2*B00*Cz); double f8 = (Dx*(Cx*Ix + B10) + B00*(xij + 2*Cx)); I[0] += C[0]*W[a]*((Dy*Iy*pow(Cy,2) + f3 + B00*Cy*(3*Cy + 2*yij) + B10*Dy*(3*Cy + yij))); I[1] += C[0]*W[a]*(Cx*Cy*(Dz*zij + Qz)); I[2] += C[0]*W[a]*(Cy*Dz*(Px + Cx*xij)); I[3] += C[0]*W[a]*(Cz*Dy*(Px + Cx*xij)); I[4] += C[0]*W[a]*(Qy*(Px + Cx*xij)); I[5] += C[0]*W[a]*(Qz*(Px + Cx*xij)); I[6] += C[0]*W[a]*((Dx*Ix*pow(Cx,2) + B00*Cx*(3*Cx + 2*xij) + B10*Dx*(3*Cx + xij) + f3)); I[7] += C[0]*W[a]*((B00*Cz*(3*Cz + 2*zij) + Dz*Iz*pow(Cz,2) + B10*Dz*(3*Cz + zij) + f3)); I[8] += C[0]*W[a]*(Cx*(f6 + Qz*zij)); I[9] += C[0]*W[a]*(Cy*(f6 + Qz*zij)); I[10] += C[0]*W[a]*(Cy*Dx*(Cz*zij + Pz)); I[11] += C[0]*W[a]*(Qy*(Cz*zij + Pz)); I[12] += C[0]*W[a]*(Qx*(Cz*zij + Pz)); I[13] += C[0]*W[a]*(Cx*Dy*(Cz*zij + Pz)); I[14] += C[0]*W[a]*(Dy*Ix*Pz); I[15] += C[0]*W[a]*(Cz*Ix*Qy); I[16] += C[0]*W[a]*(Cx*Cz*f10); I[17] += C[0]*W[a]*(Cz*Dx*f11); I[18] += C[0]*W[a]*(Dx*Iy*Pz); I[19] += C[0]*W[a]*(Dx*Iz*Py); I[20] += C[0]*W[a]*(Dy*Iz*Px); I[21] += C[0]*W[a]*(Cx*Iz*Qy); I[22] += C[0]*W[a]*(Cy*Iz*Qx); I[23] += C[0]*W[a]*(Cy*Ix*Qz); I[24] += C[0]*W[a]*(Dz*Ix*Py); I[25] += C[0]*W[a]*(Py*(Dz*zij + Qz)); I[26] += C[0]*W[a]*(Px*(Dz*zij + Qz)); I[27] += C[0]*W[a]*(Dz*Iy*Px); I[28] += C[0]*W[a]*(Cx*Dz*f11); I[29] += C[0]*W[a]*(Cx*Iy*Qz); I[30] += C[0]*W[a]*(Cz*Iy*Qx); I[31] += C[0]*W[a]*(Cy*Cz*f15); I[32] += C[0]*W[a]*(Py*f15); I[33] += C[0]*W[a]*(Pz*f15); I[34] += C[0]*W[a]*(Cy*f8); I[35] += C[0]*W[a]*(Cz*f8); I[36] += C[0]*W[a]*(Px*f10); I[37] += C[0]*W[a]*(Pz*f10); I[38] += C[0]*W[a]*(Cx*f1); I[39] += C[0]*W[a]*(Cz*f1); I[40] += C[0]*W[a]*(Dx*f5); I[41] += C[0]*W[a]*(Dx*f22); I[42] += C[0]*W[a]*(Dy*f22); I[43] += C[0]*W[a]*(Dy*f12); I[44] += C[0]*W[a]*(Dz*f12); I[45] += C[0]*W[a]*(Dz*f5); I[46] += C[0]*W[a]*(Ix*f6); I[47] += C[0]*W[a]*(Ix*f4); I[48] += C[0]*W[a]*(Iz*f4); I[49] += C[0]*W[a]*(Iz*f14); I[50] += C[0]*W[a]*(Iy*f14); I[51] += C[0]*W[a]*(Iy*f6); I[52] += C[0]*W[a]*(Qx*f11); I[53] += C[0]*W[a]*(Qz*f11); } #undef B00 #undef B10 #undef B01 #undef Cx #undef Cy #undef Cz #undef Dx #undef Dy #undef Dz #undef pow } static inline void reorder(double (&I)[54]) { double T[54]; for (int i = 0; i < 54; ++i) { T[i] = I[i]; } I[25] = T[0]; I[51] = T[1]; I[39] = T[2]; I[22] = T[3]; I[21] = T[4]; I[40] = T[5]; I[0] = T[6]; I[50] = T[7]; I[52] = T[8]; I[53] = T[9]; I[17] = T[10]; I[35] = T[11]; I[16] = T[12]; I[34] = T[13]; I[20] = T[14]; I[23] = T[15]; I[28] = T[16]; I[11] = T[17]; I[8] = T[18]; I[13] = T[19]; I[30] = T[20]; I[33] = T[21]; I[15] = T[22]; I[41] = T[23]; I[37] = T[24]; I[49] = T[25]; I[48] = T[26]; I[42] = T[27]; I[45] = T[28]; I[46] = T[29]; I[10] = T[30]; I[5] = T[31]; I[1] = T[32]; I[2] = T[33]; I[3] = T[34]; I[4] = T[35]; I[24] = T[36]; I[26] = T[37]; I[27] = T[38]; I[29] = T[39]; I[7] = T[40]; I[14] = T[41]; I[32] = T[42]; I[18] = T[43]; I[36] = T[44]; I[43] = T[45]; I[38] = T[46]; I[19] = T[47]; I[31] = T[48]; I[12] = T[49]; I[6] = T[50]; I[44] = T[51]; I[9] = T[52]; I[47] = T[53]; } }; template<> struct impl > { typedef void enable; static const bool value = true; static inline void eval(double A, double B, const Vector<3> &rAi, const Vector<3> &rBk, const Vector<3> &rAB, const Vector<3> &rij, const Vector<3> &rkl, const Vector<3> &t2, const Vector<3> &W, const double (&C)[1], double (&I)[60]) { #define pow(x,y) util::pow<(y)>::eval((x)) const int N = 3; // // double vB00[N] __attribute__ ((aligned(16))); // // // double vB10[N] __attribute__ ((aligned(16))); // // // double vB01[N] __attribute__ ((aligned(16))); // // // double vCx[N] __attribute__ ((aligned(16))); // double vCy[N] __attribute__ ((aligned(16))); // double vCz[N] __attribute__ ((aligned(16))); // // // double vDx[N] __attribute__ ((aligned(16))); // double vDy[N] __attribute__ ((aligned(16))); // double vDz[N] __attribute__ ((aligned(16))); // // for (int a = 0; a < N; ++a) { // // vB00[a] = 0.5*t2[a]; // // // vB10[a] = recurrence::coefficient(1.0/A, B, t2[a]); // // // vB01[a] = recurrence::coefficient(1.0/B, A, t2[a]); // // // vCx[a] = recurrence::coefficient<0>(rAi, B, rAB, t2[a]); // vCy[a] = recurrence::coefficient<1>(rAi, B, rAB, t2[a]); // vCz[a] = recurrence::coefficient<2>(rAi, B, rAB, t2[a]); // // // vDx[a] = recurrence::coefficient<0>(rBk, -A, rAB, t2[a]); // vDy[a] = recurrence::coefficient<1>(rBk, -A, rAB, t2[a]); // vDz[a] = recurrence::coefficient<2>(rBk, -A, rAB, t2[a]); // // } // #define B00 vB00[a] // #define B10 vB10[a] // #define B01 vB01[a] // #define Cx vCx[a] // #define Cy vCy[a] // #define Cz vCz[a] // #define Dx vDx[a] // #define Dy vDy[a] // #define Dz vDz[a] #if defined (__INTEL_COMPILER) #pragma ivdep #pragma vector aligned #endif for (int a = 0; a < N; ++a) { double B00 = 0.5*t2[a]; double B10 = recurrence::coefficient(1.0/A, B, t2[a]); double B01 = recurrence::coefficient(1.0/B, A, t2[a]); double Cx = recurrence::coefficient<0>(rAi, B, rAB, t2[a]); double Cy = recurrence::coefficient<1>(rAi, B, rAB, t2[a]); double Cz = recurrence::coefficient<2>(rAi, B, rAB, t2[a]); double Dx = recurrence::coefficient<0>(rBk, -A, rAB, t2[a]); double Dy = recurrence::coefficient<1>(rBk, -A, rAB, t2[a]); double Dz = recurrence::coefficient<2>(rBk, -A, rAB, t2[a]); double Px = (B10 + pow(Cx,2)); double Py = (B10 + pow(Cy,2)); double Pz = (B10 + pow(Cz,2)); double Qx = (Cx*Dx + B00); double Qy = (Cy*Dy + B00); double Qz = (Cz*Dz + B00); double Rx = (B01 + pow(Dx,2)); double Ry = (B01 + pow(Dy,2)); double Rz = (pow(Dz,2) + B01); double f0 = (3*B10 + pow(Cx,2)); double f1 = (Dy*Py + 2*B00*Cy); double f11 = (2*B00*Dx + Cx*Rx); double f12 = (Dx*Px + 2*B00*Cx); double f14 = (Px*Rx + 2*pow(B00,2) + 4*B00*Cx*Dx); double f17 = (Cx*Dx*(3*B10 + pow(Cx,2)) + 3*B00*Px); double f19 = (3*B10 + pow(Cz,2)); double f2 = (Dz*Pz + 2*B00*Cz); double f20 = (3*B10 + pow(Cy,2)); double f21 = (2*pow(B00,2) + Pz*Rz + 4*B00*Cz*Dz); double f22 = (2*B00*Dy + Cy*Ry); double f3 = (4*B00*Cy*Dy + Py*Ry + 2*pow(B00,2)); double f4 = (Cy*Dy*(3*B10 + pow(Cy,2)) + 3*B00*Py); double f7 = (2*B00*Dz + Cz*Rz); double f8 = (3*B00*Pz + Cz*Dz*(3*B10 + pow(Cz,2))); I[0] += C[0]*W[a]*((6*Cx*pow(B00,2) + Cx*Rx*f0 + 6*B00*Dx*Px)); I[1] += C[0]*W[a]*((6*Cy*pow(B00,2) + Cy*Ry*f20 + 6*B00*Dy*Py)); I[2] += C[0]*W[a]*((6*B00*Dz*Pz + 6*Cz*pow(B00,2) + Cz*Rz*f19)); I[3] += C[0]*W[a]*(Cz*Dx*Dy*f19); I[4] += C[0]*W[a]*(Cz*Dx*f1); I[5] += C[0]*W[a]*(Cz*Dy*f12); I[6] += C[0]*W[a]*(Dy*Pz*Qx); I[7] += C[0]*W[a]*(Dx*Pz*Qy); I[8] += C[0]*W[a]*(Cz*Qx*Qy); I[9] += C[0]*W[a]*(Cx*Cz*f22); I[10] += C[0]*W[a]*(Cx*Cy*f7); I[11] += C[0]*W[a]*(Cy*Dx*Dz*f20); I[12] += C[0]*W[a]*(Cy*Dz*f12); I[13] += C[0]*W[a]*(Dz*Py*Qx); I[14] += C[0]*W[a]*(Dx*Py*Qz); I[15] += C[0]*W[a]*(Cy*Dx*f2); I[16] += C[0]*W[a]*(Cy*Qx*Qz); I[17] += C[0]*W[a]*(Cy*Rz*f20); I[18] += C[0]*W[a]*(Cy*Px*Rz); I[19] += C[0]*W[a]*(Dz*Px*Qy); I[20] += C[0]*W[a]*(Dy*Px*Qz); I[21] += C[0]*W[a]*(Cx*Dy*Dz*f0); I[22] += C[0]*W[a]*(Cx*Dz*f1); I[23] += C[0]*W[a]*(Cx*Dy*f2); I[24] += C[0]*W[a]*(Cx*Qy*Qz); I[25] += C[0]*W[a]*(Cx*Py*Rz); I[26] += C[0]*W[a]*(Cx*Rz*f0); I[27] += C[0]*W[a]*(Cx*Ry*f0); I[28] += C[0]*W[a]*(Cx*Pz*Ry); I[29] += C[0]*W[a]*(Cy*Pz*Rx); I[30] += C[0]*W[a]*(Cy*Rx*f20); I[31] += C[0]*W[a]*(Cy*Cz*f11); I[32] += C[0]*W[a]*(Cz*Px*Ry); I[33] += C[0]*W[a]*(Cz*Ry*f19); I[34] += C[0]*W[a]*(Cz*Rx*f19); I[35] += C[0]*W[a]*(Cz*Py*Rx); I[36] += C[0]*W[a]*(Py*f11); I[37] += C[0]*W[a]*(Pz*f11); I[38] += C[0]*W[a]*(Pz*f22); I[39] += C[0]*W[a]*(Px*f22); I[40] += C[0]*W[a]*(Px*f7); I[41] += C[0]*W[a]*(Py*f7); I[42] += C[0]*W[a]*(Cy*f14); I[43] += C[0]*W[a]*(Cz*f14); I[44] += C[0]*W[a]*(Cz*f3); I[45] += C[0]*W[a]*(Cx*f3); I[46] += C[0]*W[a]*(Cx*f21); I[47] += C[0]*W[a]*(Cy*f21); I[48] += C[0]*W[a]*(Dx*f8); I[49] += C[0]*W[a]*(Dx*f4); I[50] += C[0]*W[a]*(Dz*f4); I[51] += C[0]*W[a]*(Dz*f17); I[52] += C[0]*W[a]*(Dy*f17); I[53] += C[0]*W[a]*(Dy*f8); I[54] += C[0]*W[a]*(Qx*f2); I[55] += C[0]*W[a]*(Qx*f1); I[56] += C[0]*W[a]*(Qz*f1); I[57] += C[0]*W[a]*(Qz*f12); I[58] += C[0]*W[a]*(Qy*f12); I[59] += C[0]*W[a]*(Qy*f2); } #undef B00 #undef B10 #undef B01 #undef Cx #undef Cy #undef Cz #undef Dx #undef Dy #undef Dz #undef pow } static inline void reorder(double (&I)[60]) { double T[60]; for (int i = 0; i < 60; ++i) { T[i] = I[i]; } I[0] = T[0]; I[11] = T[1]; I[22] = T[2]; I[32] = T[3]; I[36] = T[4]; I[34] = T[5]; I[37] = T[6]; I[38] = T[7]; I[39] = T[8]; I[19] = T[9]; I[29] = T[10]; I[41] = T[11]; I[43] = T[12]; I[45] = T[13]; I[46] = T[14]; I[48] = T[15]; I[49] = T[16]; I[21] = T[17]; I[23] = T[18]; I[53] = T[19]; I[54] = T[20]; I[50] = T[21]; I[55] = T[22]; I[57] = T[23]; I[59] = T[24]; I[25] = T[25]; I[20] = T[26]; I[10] = T[27]; I[17] = T[28]; I[8] = T[29]; I[1] = T[30]; I[9] = T[31]; I[14] = T[32]; I[12] = T[33]; I[2] = T[34]; I[6] = T[35]; I[5] = T[36]; I[7] = T[37]; I[18] = T[38]; I[13] = T[39]; I[24] = T[40]; I[26] = T[41]; I[3] = T[42]; I[4] = T[43]; I[16] = T[44]; I[15] = T[45]; I[27] = T[46]; I[28] = T[47]; I[42] = T[48]; I[31] = T[49]; I[51] = T[50]; I[40] = T[51]; I[30] = T[52]; I[52] = T[53]; I[47] = T[54]; I[35] = T[55]; I[56] = T[56]; I[44] = T[57]; I[33] = T[58]; I[58] = T[59]; } }; template<> struct impl > { typedef void enable; static const bool value = true; static inline void eval(double A, double B, const Vector<3> &rAi, const Vector<3> &rBk, const Vector<3> &rAB, const Vector<3> &rij, const Vector<3> &rkl, const Vector<3> &t2, const Vector<3> &W, const double (&C)[16], double (&I)[256]) { #define pow(x,y) util::pow<(y)>::eval((x)) const int N = 3; double xij = rij[0]; double yij = rij[1]; double zij = rij[2]; double xkl = rkl[0]; double ykl = rkl[1]; double zkl = rkl[2]; // // double vB00[N] __attribute__ ((aligned(16))); // // // double vB10[N] __attribute__ ((aligned(16))); // // // double vB01[N] __attribute__ ((aligned(16))); // // // double vCx[N] __attribute__ ((aligned(16))); // double vCy[N] __attribute__ ((aligned(16))); // double vCz[N] __attribute__ ((aligned(16))); // // // double vDx[N] __attribute__ ((aligned(16))); // double vDy[N] __attribute__ ((aligned(16))); // double vDz[N] __attribute__ ((aligned(16))); // // for (int a = 0; a < N; ++a) { // // vB00[a] = 0.5*t2[a]; // // // vB10[a] = recurrence::coefficient(1.0/A, B, t2[a]); // // // vB01[a] = recurrence::coefficient(1.0/B, A, t2[a]); // // // vCx[a] = recurrence::coefficient<0>(rAi, B, rAB, t2[a]); // vCy[a] = recurrence::coefficient<1>(rAi, B, rAB, t2[a]); // vCz[a] = recurrence::coefficient<2>(rAi, B, rAB, t2[a]); // // // vDx[a] = recurrence::coefficient<0>(rBk, -A, rAB, t2[a]); // vDy[a] = recurrence::coefficient<1>(rBk, -A, rAB, t2[a]); // vDz[a] = recurrence::coefficient<2>(rBk, -A, rAB, t2[a]); // // } // #define B00 vB00[a] // #define B10 vB10[a] // #define B01 vB01[a] // #define Cx vCx[a] // #define Cy vCy[a] // #define Cz vCz[a] // #define Dx vDx[a] // #define Dy vDy[a] // #define Dz vDz[a] #if defined (__INTEL_COMPILER) #pragma ivdep #pragma vector aligned #endif for (int a = 0; a < N; ++a) { double B00 = 0.5*t2[a]; double B10 = recurrence::coefficient(1.0/A, B, t2[a]); double B01 = recurrence::coefficient(1.0/B, A, t2[a]); double Cx = recurrence::coefficient<0>(rAi, B, rAB, t2[a]); double Cy = recurrence::coefficient<1>(rAi, B, rAB, t2[a]); double Cz = recurrence::coefficient<2>(rAi, B, rAB, t2[a]); double Dx = recurrence::coefficient<0>(rBk, -A, rAB, t2[a]); double Dy = recurrence::coefficient<1>(rBk, -A, rAB, t2[a]); double Dz = recurrence::coefficient<2>(rBk, -A, rAB, t2[a]); double Ix = (Cx + xij); double Iy = (Cy + yij); double Iz = (Cz + zij); double Kx = (xkl + Dx); double Ky = (ykl + Dy); double Kz = (Dz + zkl); double Px = (B10 + pow(Cx,2)); double Qy = (Cy*Dy + B00); double Ry = (B01 + pow(Dy,2)); double f1 = Cx*Dx*xij; double f10 = Cz*Dz*zij; double f11 = B00*ykl; double f12 = Cy*Dy; double f13 = (Dz*Kz + B01); double f17 = 2*B00*Dx; double f2 = B00*xij; double f20 = Cz*Dz; double f21 = Cz*pow(Dz,2); double f26 = Cz*zkl; double f3 = B00*zkl; double f33 = Dy*yij; double f34 = B10*Dx; double f35 = B01*Cy; double f38 = Cx*xkl; double f4 = Cx*Dx; double f41 = 2*B00*Cy; double f44 = 2*B00*Dy; double f45 = B10*Dy; double f46 = Dz*pow(Cz,2); double f48 = (B01 + Dx*Kx); double f49 = Dz*zij; double f5 = B01*B10; double f51 = Cy*ykl; double f54 = 2*B00*Dz; double f55 = B10*Dz; double f56 = (B01 + Dy*Ky); double f58 = B01*Cx; double f59 = Dy*pow(Cy,2); double f6 = 2*B00*Cz; double f63 = Cx*pow(Dx,2); double f64 = B00*zij; double f67 = 2*B00*Cx; double f68 = Cy*pow(Dy,2); double f7 = Dx*pow(Cx,2); double f76 = Dx*xij; double f77 = B01*Cz; I[0] += C[15]*W[a]*((f58*(Cx + xij) + f1*xkl + f5 + f63*xij + Dx*(2*f2 + Dx*Px) + xkl*(f34 + f2 + f7) + 2*B00*(f38 + B00 + 2*f4))); I[1] += C[15]*W[a]*(Cy*(xij*pow(Dx,2) + f17 + f63 + B01*Ix + xkl*(f76 + B00 + f4))); I[2] += C[15]*W[a]*(Cz*(xij*pow(Dx,2) + f17 + f63 + B01*Ix + xkl*(f76 + B00 + f4))); I[3] += C[14]*W[a]*((xij*pow(Dx,2) + f17 + f63 + B01*Ix + xkl*(f76 + B00 + f4))); I[4] += C[15]*W[a]*(Iy*(f17 + f63 + f58 + xkl*(B00 + f4))); I[5] += C[15]*W[a]*(Iz*(f17 + f63 + f58 + xkl*(B00 + f4))); I[6] += C[13]*W[a]*((f17 + f63 + f58 + xkl*(B00 + f4))); I[7] += C[15]*W[a]*((Cy*(f68 + 2*f11) + 2*B00*(f33 + B00 + 2*f12) + yij*(f11 + f68 + f35) + B01*pow(Cy,2) + f12*yij*ykl + f59*ykl + f5 + f45*(ykl + Dy))); I[8] += C[15]*W[a]*(Cz*(f11 + f68 + f44 + f35 + Ry*yij + ykl*(f12 + f33))); I[9] += C[15]*W[a]*(Cx*(f11 + f68 + f44 + f35 + Ry*yij + ykl*(f12 + f33))); I[10] += C[14]*W[a]*((f11 + f68 + f44 + f35 + Ry*yij + ykl*(f12 + f33))); I[11] += C[15]*W[a]*(Iz*(f11 + f68 + f44 + f35 + f12*ykl)); I[12] += C[15]*W[a]*(Ix*(f11 + f68 + f44 + f35 + f12*ykl)); I[13] += C[13]*W[a]*((f11 + f68 + f44 + f35 + f12*ykl)); I[14] += C[15]*W[a]*(Dz*(f59 + B00*(yij + 2*Cy) + B10*Ky + yij*(f12 + f51) + ykl*pow(Cy,2))); I[15] += C[15]*W[a]*(Dx*(f59 + B00*(yij + 2*Cy) + B10*Ky + yij*(f12 + f51) + ykl*pow(Cy,2))); I[16] += C[11]*W[a]*((f59 + B00*(yij + 2*Cy) + B10*Ky + yij*(f12 + f51) + ykl*pow(Cy,2))); I[17] += C[15]*W[a]*(Kz*(f41 + f45 + f59 + yij*(f12 + B00))); I[18] += C[15]*W[a]*(Kx*(f41 + f45 + f59 + yij*(f12 + B00))); I[19] += C[7]*W[a]*((f41 + f45 + f59 + yij*(f12 + B00))); I[20] += C[15]*W[a]*((2*B00*(f49 + B00) + zkl*(f10 + f46) + f3*zij + f21*zij + f5 + 2*Cz*f3 + pow(Cz,2)*pow(Dz,2) + 2*Dz*f6 + f77*(Cz + zij) + f55*(Dz + zkl))); I[21] += C[15]*W[a]*(Cy*(f54 + f21 + zij*pow(Dz,2) + f3 + zkl*(f49 + f20) + B01*Iz)); I[22] += C[15]*W[a]*(Cx*(f54 + f21 + zij*pow(Dz,2) + f3 + zkl*(f49 + f20) + B01*Iz)); I[23] += C[14]*W[a]*((f54 + f21 + zij*pow(Dz,2) + f3 + zkl*(f49 + f20) + B01*Iz)); I[24] += C[15]*W[a]*(Iy*(f77 + f54 + f21 + f3 + f20*zkl)); I[25] += C[15]*W[a]*(Ix*(f77 + f54 + f21 + f3 + f20*zkl)); I[26] += C[13]*W[a]*((f77 + f54 + f21 + f3 + f20*zkl)); I[27] += C[15]*W[a]*(Dy*(zkl*pow(Cz,2) + f10 + f46 + zij*(f26 + B00) + B10*Kz + f6)); I[28] += C[15]*W[a]*(Dx*(zkl*pow(Cz,2) + f10 + f46 + zij*(f26 + B00) + B10*Kz + f6)); I[29] += C[11]*W[a]*((zkl*pow(Cz,2) + f10 + f46 + zij*(f26 + B00) + B10*Kz + f6)); I[30] += C[15]*W[a]*(Ky*(f10 + f64 + f46 + f55 + f6)); I[31] += C[15]*W[a]*(Kx*(f10 + f64 + f46 + f55 + f6)); I[32] += C[7]*W[a]*((f10 + f64 + f46 + f55 + f6)); I[33] += C[15]*W[a]*(Dz*(f67 + f34 + Px*xkl + f1 + f2 + f7 + f38*xij)); I[34] += C[15]*W[a]*(Dy*(f67 + f34 + Px*xkl + f1 + f2 + f7 + f38*xij)); I[35] += C[11]*W[a]*((f67 + f34 + Px*xkl + f1 + f2 + f7 + f38*xij)); I[36] += C[15]*W[a]*(Ky*(f67 + f34 + f1 + f2 + f7)); I[37] += C[15]*W[a]*(Kz*(f67 + f34 + f1 + f2 + f7)); I[38] += C[7]*W[a]*((f67 + f34 + f1 + f2 + f7)); I[39] += C[15]*W[a]*(Qy*(f49 + f20 + f26 + zij*zkl + B00)); I[40] += C[15]*W[a]*((B00 + f4)*(f49 + f20 + f26 + zij*zkl + B00)); I[41] += C[14]*W[a]*(Dx*(f49 + f20 + f26 + zij*zkl + B00)); I[42] += C[15]*W[a]*(Cy*Dx*(f49 + f20 + f26 + zij*zkl + B00)); I[43] += C[11]*W[a]*(Cy*(f49 + f20 + f26 + zij*zkl + B00)); I[44] += C[14]*W[a]*(Dy*(f49 + f20 + f26 + zij*zkl + B00)); I[45] += C[15]*W[a]*(Cx*Dy*(f49 + f20 + f26 + zij*zkl + B00)); I[46] += C[11]*W[a]*(Cx*(f49 + f20 + f26 + zij*zkl + B00)); I[47] += C[10]*W[a]*((f49 + f20 + f26 + zij*zkl + B00)); I[48] += C[15]*W[a]*((f20 + B00)*(f76 + f38 + xij*xkl + B00 + f4)); I[49] += C[15]*W[a]*(Qy*(f76 + f38 + xij*xkl + B00 + f4)); I[50] += C[14]*W[a]*(Dy*(f76 + f38 + xij*xkl + B00 + f4)); I[51] += C[15]*W[a]*(Cz*Dy*(f76 + f38 + xij*xkl + B00 + f4)); I[52] += C[11]*W[a]*(Cz*(f76 + f38 + xij*xkl + B00 + f4)); I[53] += C[15]*W[a]*(Cy*Dz*(f76 + f38 + xij*xkl + B00 + f4)); I[54] += C[11]*W[a]*(Cy*(f76 + f38 + xij*xkl + B00 + f4)); I[55] += C[10]*W[a]*((f76 + f38 + xij*xkl + B00 + f4)); I[56] += C[14]*W[a]*(Dz*(f76 + f38 + xij*xkl + B00 + f4)); I[57] += C[15]*W[a]*(Dz*Iy*(f38 + B00 + f4)); I[58] += C[15]*W[a]*((f20 + B00)*(f51 + f33 + yij*ykl + Qy)); I[59] += C[15]*W[a]*((B00 + f4)*(f51 + f33 + yij*ykl + Qy)); I[60] += C[14]*W[a]*(Dx*(f51 + f33 + yij*ykl + Qy)); I[61] += C[15]*W[a]*(Cz*Dx*(f51 + f33 + yij*ykl + Qy)); I[62] += C[11]*W[a]*(Cz*(f51 + f33 + yij*ykl + Qy)); I[63] += C[14]*W[a]*(Dz*(f51 + f33 + yij*ykl + Qy)); I[64] += C[15]*W[a]*(Cx*Dz*(f51 + f33 + yij*ykl + Qy)); I[65] += C[11]*W[a]*(Cx*(f51 + f33 + yij*ykl + Qy)); I[66] += C[10]*W[a]*((f51 + f33 + yij*ykl + Qy)); I[67] += C[15]*W[a]*((f51 + Qy)*(f49 + f20 + B00)); I[68] += C[15]*W[a]*((f38 + B00 + f4)*(f49 + f20 + B00)); I[69] += C[15]*W[a]*((f20 + f26 + B00)*(f76 + B00 + f4)); I[70] += C[15]*W[a]*((f33 + Qy)*(f20 + f26 + B00)); I[71] += C[15]*W[a]*((f33 + Qy)*(f38 + B00 + f4)); I[72] += C[15]*W[a]*(Dy*Iz*(f38 + B00 + f4)); I[73] += C[13]*W[a]*(Dy*(f38 + B00 + f4)); I[74] += C[13]*W[a]*(Dz*(f38 + B00 + f4)); I[75] += C[15]*W[a]*(Cz*Ix*f56); I[76] += C[13]*W[a]*(Cy*Dz*Kx); I[77] += C[14]*W[a]*(Dz*Iy*Kx); I[78] += C[15]*W[a]*(Iy*Kx*(f20 + B00)); I[79] += C[13]*W[a]*(Kx*(f20 + B00)); I[80] += C[14]*W[a]*(Kx*(f49 + f20 + B00)); I[81] += C[15]*W[a]*(Cy*Kx*(f49 + f20 + B00)); I[82] += C[7]*W[a]*(Cy*(f49 + f20 + B00)); I[83] += C[14]*W[a]*(Ky*(f49 + f20 + B00)); I[84] += C[15]*W[a]*(Cx*Ky*(f49 + f20 + B00)); I[85] += C[7]*W[a]*(Cx*(f49 + f20 + B00)); I[86] += C[6]*W[a]*((f49 + f20 + B00)); I[87] += C[13]*W[a]*(Dx*(f20 + f26 + B00)); I[88] += C[15]*W[a]*(Dx*Iy*(f20 + f26 + B00)); I[89] += C[11]*W[a]*(Iy*(f20 + f26 + B00)); I[90] += C[13]*W[a]*(Dy*(f20 + f26 + B00)); I[91] += C[15]*W[a]*(Dy*Ix*(f20 + f26 + B00)); I[92] += C[11]*W[a]*(Ix*(f20 + f26 + B00)); I[93] += C[7]*W[a]*(Ix*(f20 + B00)); I[94] += C[15]*W[a]*(Ix*Ky*(f20 + B00)); I[95] += C[13]*W[a]*(Ky*(f20 + B00)); I[96] += C[9]*W[a]*((f20 + f26 + B00)); I[97] += C[7]*W[a]*(Iy*(f20 + B00)); I[98] += C[15]*W[a]*(Cz*Iy*f48); I[99] += C[15]*W[a]*(f48*(B10 + Cz*Iz)); I[100] += C[11]*W[a]*(Kx*(B10 + Cz*Iz)); I[101] += C[15]*W[a]*(Dy*Kx*(B10 + Cz*Iz)); I[102] += C[7]*W[a]*(Dy*(B10 + Cz*Iz)); I[103] += C[11]*W[a]*(Ky*(B10 + Cz*Iz)); I[104] += C[15]*W[a]*(Dx*Ky*(B10 + Cz*Iz)); I[105] += C[7]*W[a]*(Dx*(B10 + Cz*Iz)); I[106] += C[3]*W[a]*((B10 + Cz*Iz)); I[107] += C[15]*W[a]*(f56*(B10 + Cz*Iz)); I[108] += C[15]*W[a]*(f56*(Cx*Ix + B10)); I[109] += C[11]*W[a]*(Ky*(Cx*Ix + B10)); I[110] += C[15]*W[a]*(Dz*Ky*(Cx*Ix + B10)); I[111] += C[7]*W[a]*(Dz*(Cx*Ix + B10)); I[112] += C[11]*W[a]*(Kz*(Cx*Ix + B10)); I[113] += C[15]*W[a]*(Dy*Kz*(Cx*Ix + B10)); I[114] += C[7]*W[a]*(Dy*(Cx*Ix + B10)); I[115] += C[3]*W[a]*((Cx*Ix + B10)); I[116] += C[15]*W[a]*(f13*(Cx*Ix + B10)); I[117] += C[15]*W[a]*(f13*(Cy*Iy + B10)); I[118] += C[11]*W[a]*(Kz*(Cy*Iy + B10)); I[119] += C[15]*W[a]*(f48*(Cy*Iy + B10)); I[120] += C[11]*W[a]*(Kx*(Cy*Iy + B10)); I[121] += C[15]*W[a]*(Dz*Kx*(Cy*Iy + B10)); I[122] += C[7]*W[a]*(Dz*(Cy*Iy + B10)); I[123] += C[3]*W[a]*((Cy*Iy + B10)); I[124] += C[7]*W[a]*(Dx*(Cy*Iy + B10)); I[125] += C[15]*W[a]*(Dx*Kz*(Cy*Iy + B10)); I[126] += C[13]*W[a]*(Cy*Dx*Kz); I[127] += C[15]*W[a]*(Cy*Ix*f13); I[128] += C[15]*W[a]*(Dz*Ix*(f51 + Qy)); I[129] += C[13]*W[a]*(Dz*(f51 + Qy)); I[130] += C[15]*W[a]*(Dx*Iz*(f51 + Qy)); I[131] += C[13]*W[a]*(Dx*(f51 + Qy)); I[132] += C[15]*W[a]*((f51 + Qy)*(f76 + B00 + f4)); I[133] += C[7]*W[a]*(Cz*(f76 + B00 + f4)); I[134] += C[15]*W[a]*(Cz*Ky*(f76 + B00 + f4)); I[135] += C[14]*W[a]*(Ky*(f76 + B00 + f4)); I[136] += C[13]*W[a]*(Ky*(B00 + f4)); I[137] += C[15]*W[a]*(Iz*Ky*(B00 + f4)); I[138] += C[7]*W[a]*(Iz*(B00 + f4)); I[139] += C[11]*W[a]*(Iz*(f38 + B00 + f4)); I[140] += C[9]*W[a]*((f38 + B00 + f4)); I[141] += C[11]*W[a]*(Iy*(f38 + B00 + f4)); I[142] += C[7]*W[a]*(Iy*(B00 + f4)); I[143] += C[15]*W[a]*(Iy*Kz*(B00 + f4)); I[144] += C[13]*W[a]*(Kz*(B00 + f4)); I[145] += C[14]*W[a]*(Kz*(f76 + B00 + f4)); I[146] += C[15]*W[a]*(Cy*Kz*(f76 + B00 + f4)); I[147] += C[7]*W[a]*(Cy*(f76 + B00 + f4)); I[148] += C[6]*W[a]*((f76 + B00 + f4)); I[149] += C[5]*W[a]*((B00 + f4)); I[150] += C[5]*W[a]*((f20 + B00)); I[151] += C[15]*W[a]*(Cz*Kx*(f33 + Qy)); I[152] += C[7]*W[a]*(Cz*(f33 + Qy)); I[153] += C[14]*W[a]*(Kz*(f33 + Qy)); I[154] += C[15]*W[a]*(Cx*Kz*(f33 + Qy)); I[155] += C[7]*W[a]*(Cx*(f33 + Qy)); I[156] += C[6]*W[a]*((f33 + Qy)); I[157] += C[14]*W[a]*(Kx*(f33 + Qy)); I[158] += C[15]*W[a]*(Iz*Kx*Qy); I[159] += C[11]*W[a]*(Cy*Iz*Kx); I[160] += C[9]*W[a]*(Cy*Kx); I[161] += C[10]*W[a]*(Iy*Kx); I[162] += C[10]*W[a]*(Iz*Kx); I[163] += C[15]*W[a]*(Cy*Iz*f48); I[164] += C[13]*W[a]*(Cy*f48); I[165] += C[13]*W[a]*(Cz*f48); I[166] += C[14]*W[a]*(Iy*f48); I[167] += C[14]*W[a]*(Iz*f48); I[168] += C[6]*W[a]*(Dy*Iz); I[169] += C[14]*W[a]*(Dy*Iz*Kx); I[170] += C[12]*W[a]*(Dy*Kx); I[171] += C[13]*W[a]*(Kx*Qy); I[172] += C[12]*W[a]*(Dz*Kx); I[173] += C[6]*W[a]*(Dz*Iy); I[174] += C[11]*W[a]*(Cx*Iy*Kz); I[175] += C[14]*W[a]*(Dx*Iy*Kz); I[176] += C[6]*W[a]*(Dx*Iy); I[177] += C[6]*W[a]*(Dx*Iz); I[178] += C[14]*W[a]*(Dx*Iz*Ky); I[179] += C[10]*W[a]*(Iz*Ky); I[180] += C[12]*W[a]*(Dx*Ky); I[181] += C[5]*W[a]*(Cy*Dx); I[182] += C[7]*W[a]*(Cy*Dx*Iz); I[183] += C[3]*W[a]*(Cy*Iz); I[184] += C[15]*W[a]*(Cx*Iz*f56); I[185] += C[13]*W[a]*(Cx*f56); I[186] += C[13]*W[a]*(Cz*f56); I[187] += C[14]*W[a]*(Ix*f56); I[188] += C[14]*W[a]*(Iz*f56); I[189] += C[7]*W[a]*(Iz*Qy); I[190] += C[11]*W[a]*(Iz*(f51 + Qy)); I[191] += C[9]*W[a]*((f51 + Qy)); I[192] += C[11]*W[a]*(Ix*(f51 + Qy)); I[193] += C[7]*W[a]*(Ix*Qy); I[194] += C[15]*W[a]*(Ix*Kz*Qy); I[195] += C[14]*W[a]*(Dy*Ix*Kz); I[196] += C[6]*W[a]*(Dy*Ix); I[197] += C[10]*W[a]*(Ix*Ky); I[198] += C[11]*W[a]*(Cz*Ix*Ky); I[199] += C[9]*W[a]*(Cz*Ky); I[200] += C[13]*W[a]*(Cz*Dx*Ky); I[201] += C[5]*W[a]*(Cz*Dx); I[202] += C[7]*W[a]*(Cz*Dx*Iy); I[203] += C[3]*W[a]*(Cz*Iy); I[204] += C[11]*W[a]*(Cz*Iy*Kx); I[205] += C[9]*W[a]*(Cz*Kx); I[206] += C[13]*W[a]*(Cz*Dy*Kx); I[207] += C[5]*W[a]*(Cz*Dy); I[208] += C[7]*W[a]*(Cz*Dy*Ix); I[209] += C[3]*W[a]*(Cz*Ix); I[210] += C[6]*W[a]*(Dz*Ix); I[211] += C[14]*W[a]*(Dz*Ix*Ky); I[212] += C[12]*W[a]*(Dz*Ky); I[213] += C[5]*W[a]*(Cy*Dz); I[214] += C[7]*W[a]*(Cy*Dz*Ix); I[215] += C[3]*W[a]*(Cy*Ix); I[216] += C[11]*W[a]*(Cy*Ix*Kz); I[217] += C[9]*W[a]*(Cy*Kz); I[218] += C[10]*W[a]*(Ix*Kz); I[219] += C[10]*W[a]*(Iy*Kz); I[220] += C[12]*W[a]*(Dx*Kz); I[221] += C[12]*W[a]*(Dy*Kz); I[222] += C[13]*W[a]*(Kz*Qy); I[223] += C[9]*W[a]*(Cx*Kz); I[224] += C[13]*W[a]*(Cx*Dy*Kz); I[225] += C[5]*W[a]*(Cx*Dy); I[226] += C[7]*W[a]*(Cx*Dy*Iz); I[227] += C[3]*W[a]*(Cx*Iz); I[228] += C[11]*W[a]*(Cx*Iz*Ky); I[229] += C[9]*W[a]*(Cx*Ky); I[230] += C[13]*W[a]*(Cx*Dz*Ky); I[231] += C[5]*W[a]*(Cx*Dz); I[232] += C[7]*W[a]*(Cx*Dz*Iy); I[233] += C[15]*W[a]*(Cx*Iy*f13); I[234] += C[13]*W[a]*(Cx*f13); I[235] += C[13]*W[a]*(Cy*f13); I[236] += C[14]*W[a]*(Ix*f13); I[237] += C[14]*W[a]*(Iy*f13); I[238] += C[3]*W[a]*(Cx*Iy); I[239] += C[1]*W[a]*(Cx); I[240] += C[1]*W[a]*(Cy); I[241] += C[1]*W[a]*(Cz); I[242] += C[2]*W[a]*(Ix); I[243] += C[2]*W[a]*(Iy); I[244] += C[2]*W[a]*(Iz); I[245] += C[4]*W[a]*(Dx); I[246] += C[4]*W[a]*(Dy); I[247] += C[5]*W[a]*(Qy); I[248] += C[4]*W[a]*(Dz); I[249] += C[8]*W[a]*(Kx); I[250] += C[12]*W[a]*(f48); I[251] += C[8]*W[a]*(Ky); I[252] += C[12]*W[a]*(f56); I[253] += C[8]*W[a]*(Kz); I[254] += C[12]*W[a]*(f13); I[255] += C[0]*W[a]*(1); } #undef B00 #undef B10 #undef B01 #undef Cx #undef Cy #undef Cz #undef Dx #undef Dy #undef Dz #undef pow } static inline void reorder(double (&I)[256]) { double T[256]; for (int i = 0; i < 256; ++i) { T[i] = I[i]; } I[85] = T[0]; I[86] = T[1]; I[87] = T[2]; I[84] = T[3]; I[89] = T[4]; I[93] = T[5]; I[81] = T[6]; I[170] = T[7]; I[171] = T[8]; I[169] = T[9]; I[168] = T[10]; I[174] = T[11]; I[166] = T[12]; I[162] = T[13]; I[186] = T[14]; I[154] = T[15]; I[138] = T[16]; I[234] = T[17]; I[106] = T[18]; I[42] = T[19]; I[255] = T[20]; I[254] = T[21]; I[253] = T[22]; I[252] = T[23]; I[251] = T[24]; I[247] = T[25]; I[243] = T[26]; I[239] = T[27]; I[223] = T[28]; I[207] = T[29]; I[191] = T[30]; I[127] = T[31]; I[63] = T[32]; I[117] = T[33]; I[101] = T[34]; I[69] = T[35]; I[149] = T[36]; I[213] = T[37]; I[21] = T[38]; I[238] = T[39]; I[221] = T[40]; I[220] = T[41]; I[222] = T[42]; I[206] = T[43]; I[236] = T[44]; I[237] = T[45]; I[205] = T[46]; I[204] = T[47]; I[119] = T[48]; I[102] = T[49]; I[100] = T[50]; I[103] = T[51]; I[71] = T[52]; I[118] = T[53]; I[70] = T[54]; I[68] = T[55]; I[116] = T[56]; I[121] = T[57]; I[187] = T[58]; I[153] = T[59]; I[152] = T[60]; I[155] = T[61]; I[139] = T[62]; I[184] = T[63]; I[185] = T[64]; I[137] = T[65]; I[136] = T[66]; I[190] = T[67]; I[125] = T[68]; I[215] = T[69]; I[235] = T[70]; I[105] = T[71]; I[109] = T[72]; I[97] = T[73]; I[113] = T[74]; I[167] = T[75]; I[114] = T[76]; I[120] = T[77]; I[123] = T[78]; I[115] = T[79]; I[124] = T[80]; I[126] = T[81]; I[62] = T[82]; I[188] = T[83]; I[189] = T[84]; I[61] = T[85]; I[60] = T[86]; I[211] = T[87]; I[219] = T[88]; I[203] = T[89]; I[227] = T[90]; I[231] = T[91]; I[199] = T[92]; I[55] = T[93]; I[183] = T[94]; I[179] = T[95]; I[195] = T[96]; I[59] = T[97]; I[91] = T[98]; I[95] = T[99]; I[79] = T[100]; I[111] = T[101]; I[47] = T[102]; I[143] = T[103]; I[159] = T[104]; I[31] = T[105]; I[15] = T[106]; I[175] = T[107]; I[165] = T[108]; I[133] = T[109]; I[181] = T[110]; I[53] = T[111]; I[197] = T[112]; I[229] = T[113]; I[37] = T[114]; I[5] = T[115]; I[245] = T[116]; I[250] = T[117]; I[202] = T[118]; I[90] = T[119]; I[74] = T[120]; I[122] = T[121]; I[58] = T[122]; I[10] = T[123]; I[26] = T[124]; I[218] = T[125]; I[210] = T[126]; I[246] = T[127]; I[182] = T[128]; I[178] = T[129]; I[158] = T[130]; I[146] = T[131]; I[150] = T[132]; I[23] = T[133]; I[151] = T[134]; I[148] = T[135]; I[145] = T[136]; I[157] = T[137]; I[29] = T[138]; I[77] = T[139]; I[65] = T[140]; I[73] = T[141]; I[25] = T[142]; I[217] = T[143]; I[209] = T[144]; I[212] = T[145]; I[214] = T[146]; I[22] = T[147]; I[20] = T[148]; I[17] = T[149]; I[51] = T[150]; I[107] = T[151]; I[43] = T[152]; I[232] = T[153]; I[233] = T[154]; I[41] = T[155]; I[40] = T[156]; I[104] = T[157]; I[110] = T[158]; I[78] = T[159]; I[66] = T[160]; I[72] = T[161]; I[76] = T[162]; I[94] = T[163]; I[82] = T[164]; I[83] = T[165]; I[88] = T[166]; I[92] = T[167]; I[44] = T[168]; I[108] = T[169]; I[96] = T[170]; I[98] = T[171]; I[112] = T[172]; I[56] = T[173]; I[201] = T[174]; I[216] = T[175]; I[24] = T[176]; I[28] = T[177]; I[156] = T[178]; I[140] = T[179]; I[144] = T[180]; I[18] = T[181]; I[30] = T[182]; I[14] = T[183]; I[173] = T[184]; I[161] = T[185]; I[163] = T[186]; I[164] = T[187]; I[172] = T[188]; I[46] = T[189]; I[142] = T[190]; I[130] = T[191]; I[134] = T[192]; I[38] = T[193]; I[230] = T[194]; I[228] = T[195]; I[36] = T[196]; I[132] = T[197]; I[135] = T[198]; I[131] = T[199]; I[147] = T[200]; I[19] = T[201]; I[27] = T[202]; I[11] = T[203]; I[75] = T[204]; I[67] = T[205]; I[99] = T[206]; I[35] = T[207]; I[39] = T[208]; I[7] = T[209]; I[52] = T[210]; I[180] = T[211]; I[176] = T[212]; I[50] = T[213]; I[54] = T[214]; I[6] = T[215]; I[198] = T[216]; I[194] = T[217]; I[196] = T[218]; I[200] = T[219]; I[208] = T[220]; I[224] = T[221]; I[226] = T[222]; I[193] = T[223]; I[225] = T[224]; I[33] = T[225]; I[45] = T[226]; I[13] = T[227]; I[141] = T[228]; I[129] = T[229]; I[177] = T[230]; I[49] = T[231]; I[57] = T[232]; I[249] = T[233]; I[241] = T[234]; I[242] = T[235]; I[244] = T[236]; I[248] = T[237]; I[9] = T[238]; I[1] = T[239]; I[2] = T[240]; I[3] = T[241]; I[4] = T[242]; I[8] = T[243]; I[12] = T[244]; I[16] = T[245]; I[32] = T[246]; I[34] = T[247]; I[48] = T[248]; I[64] = T[249]; I[80] = T[250]; I[128] = T[251]; I[160] = T[252]; I[192] = T[253]; I[240] = T[254]; I[0] = T[255]; } }; template<> struct impl > { typedef void enable; static const bool value = true; static inline void eval(double A, double B, const Vector<3> &rAi, const Vector<3> &rBk, const Vector<3> &rAB, const Vector<3> &rij, const Vector<3> &rkl, const Vector<2> &t2, const Vector<2> &W, const double (&C)[4], double (&I)[48]) { #define pow(x,y) util::pow<(y)>::eval((x)) const int N = 2; double xij = rij[0]; double yij = rij[1]; double zij = rij[2]; // // double vB00[N] __attribute__ ((aligned(16))); // // // double vB10[N] __attribute__ ((aligned(16))); // // // // double vCx[N] __attribute__ ((aligned(16))); // double vCy[N] __attribute__ ((aligned(16))); // double vCz[N] __attribute__ ((aligned(16))); // // // double vDx[N] __attribute__ ((aligned(16))); // double vDy[N] __attribute__ ((aligned(16))); // double vDz[N] __attribute__ ((aligned(16))); // // for (int a = 0; a < N; ++a) { // // vB00[a] = 0.5*t2[a]; // // // vB10[a] = recurrence::coefficient(1.0/A, B, t2[a]); // // // // vCx[a] = recurrence::coefficient<0>(rAi, B, rAB, t2[a]); // vCy[a] = recurrence::coefficient<1>(rAi, B, rAB, t2[a]); // vCz[a] = recurrence::coefficient<2>(rAi, B, rAB, t2[a]); // // // vDx[a] = recurrence::coefficient<0>(rBk, -A, rAB, t2[a]); // vDy[a] = recurrence::coefficient<1>(rBk, -A, rAB, t2[a]); // vDz[a] = recurrence::coefficient<2>(rBk, -A, rAB, t2[a]); // // } // #define B00 vB00[a] // #define B10 vB10[a] // #define B01 vB01[a] // #define Cx vCx[a] // #define Cy vCy[a] // #define Cz vCz[a] // #define Dx vDx[a] // #define Dy vDy[a] // #define Dz vDz[a] #if defined (__INTEL_COMPILER) #pragma ivdep #pragma vector aligned #endif for (int a = 0; a < N; ++a) { double B00 = 0.5*t2[a]; double B10 = recurrence::coefficient(1.0/A, B, t2[a]); double Cx = recurrence::coefficient<0>(rAi, B, rAB, t2[a]); double Cy = recurrence::coefficient<1>(rAi, B, rAB, t2[a]); double Cz = recurrence::coefficient<2>(rAi, B, rAB, t2[a]); double Dx = recurrence::coefficient<0>(rBk, -A, rAB, t2[a]); double Dy = recurrence::coefficient<1>(rBk, -A, rAB, t2[a]); double Dz = recurrence::coefficient<2>(rBk, -A, rAB, t2[a]); double Ix = (Cx + xij); double Iy = (Cy + yij); double Iz = (Cz + zij); double Qx = (Cx*Dx + B00); double Qy = (Cy*Dy + B00); double Qz = (Cz*Dz + B00); I[0] += C[3]*W[a]*((B00*(yij + 2*Cy) + Dy*(Cy*Iy + B10))); I[1] += C[3]*W[a]*((Dz*(B10 + Cz*Iz) + B00*(2*Cz + zij))); I[2] += C[3]*W[a]*((Dx*(Cx*Ix + B10) + B00*(xij + 2*Cx))); I[3] += C[3]*W[a]*(Dy*(Cx*Ix + B10)); I[4] += C[3]*W[a]*(Dz*(Cx*Ix + B10)); I[5] += C[1]*W[a]*((Cx*Ix + B10)); I[6] += C[3]*W[a]*(Cz*(Dx*xij + Qx)); I[7] += C[3]*W[a]*(Cy*(Dx*xij + Qx)); I[8] += C[2]*W[a]*((Dx*xij + Qx)); I[9] += C[3]*W[a]*(Dx*(B10 + Cz*Iz)); I[10] += C[1]*W[a]*((B10 + Cz*Iz)); I[11] += C[3]*W[a]*(Dy*(B10 + Cz*Iz)); I[12] += C[3]*W[a]*(Cz*(Dy*yij + Qy)); I[13] += C[3]*W[a]*(Cx*(Dy*yij + Qy)); I[14] += C[2]*W[a]*((Dy*yij + Qy)); I[15] += C[3]*W[a]*(Dx*(Cy*Iy + B10)); I[16] += C[1]*W[a]*((Cy*Iy + B10)); I[17] += C[3]*W[a]*(Dz*(Cy*Iy + B10)); I[18] += C[3]*W[a]*(Cy*(Dz*zij + Qz)); I[19] += C[3]*W[a]*(Cx*(Dz*zij + Qz)); I[20] += C[2]*W[a]*((Dz*zij + Qz)); I[21] += C[3]*W[a]*(Ix*Qz); I[22] += C[3]*W[a]*(Iz*Qx); I[23] += C[3]*W[a]*(Iy*Qx); I[24] += C[3]*W[a]*(Cz*Dx*Iy); I[25] += C[1]*W[a]*(Cz*Iy); I[26] += C[1]*W[a]*(Cx*Iy); I[27] += C[3]*W[a]*(Cx*Dz*Iy); I[28] += C[2]*W[a]*(Dz*Iy); I[29] += C[3]*W[a]*(Iy*Qz); I[30] += C[2]*W[a]*(Dx*Iy); I[31] += C[2]*W[a]*(Dx*Iz); I[32] += C[3]*W[a]*(Cy*Dx*Iz); I[33] += C[1]*W[a]*(Cy*Iz); I[34] += C[2]*W[a]*(Dy*Iz); I[35] += C[3]*W[a]*(Cx*Dy*Iz); I[36] += C[1]*W[a]*(Cx*Iz); I[37] += C[3]*W[a]*(Iz*Qy); I[38] += C[3]*W[a]*(Ix*Qy); I[39] += C[2]*W[a]*(Dy*Ix); I[40] += C[3]*W[a]*(Cz*Dy*Ix); I[41] += C[1]*W[a]*(Cz*Ix); I[42] += C[2]*W[a]*(Dz*Ix); I[43] += C[3]*W[a]*(Cy*Dz*Ix); I[44] += C[1]*W[a]*(Cy*Ix); I[45] += C[0]*W[a]*(Ix); I[46] += C[0]*W[a]*(Iy); I[47] += C[0]*W[a]*(Iz); } #undef B00 #undef B10 #undef B01 #undef Cx #undef Cy #undef Cz #undef Dx #undef Dy #undef Dz #undef pow } static inline void reorder(double (&I)[48]) { double T[48]; for (int i = 0; i < 48; ++i) { T[i] = I[i]; } I[30] = T[0]; I[47] = T[1]; I[13] = T[2]; I[25] = T[3]; I[37] = T[4]; I[1] = T[5]; I[15] = T[6]; I[14] = T[7]; I[12] = T[8]; I[23] = T[9]; I[11] = T[10]; I[35] = T[11]; I[31] = T[12]; I[29] = T[13]; I[28] = T[14]; I[18] = T[15]; I[6] = T[16]; I[42] = T[17]; I[46] = T[18]; I[45] = T[19]; I[44] = T[20]; I[39] = T[21]; I[21] = T[22]; I[17] = T[23]; I[19] = T[24]; I[7] = T[25]; I[5] = T[26]; I[41] = T[27]; I[40] = T[28]; I[43] = T[29]; I[16] = T[30]; I[20] = T[31]; I[22] = T[32]; I[10] = T[33]; I[32] = T[34]; I[33] = T[35]; I[9] = T[36]; I[34] = T[37]; I[26] = T[38]; I[24] = T[39]; I[27] = T[40]; I[3] = T[41]; I[36] = T[42]; I[38] = T[43]; I[2] = T[44]; I[0] = T[45]; I[4] = T[46]; I[8] = T[47]; } }; template<> struct impl > { typedef void enable; static const bool value = true; static inline void eval(double A, double B, const Vector<3> &rAi, const Vector<3> &rBk, const Vector<3> &rAB, const Vector<3> &rij, const Vector<3> &rkl, const Vector<4> &t2, const Vector<4> &W, const double (&C)[1], double (&I)[100]) { #define pow(x,y) util::pow<(y)>::eval((x)) const int N = 4; double xij = rij[0]; double yij = rij[1]; double zij = rij[2]; // // // double vB10[N] __attribute__ ((aligned(16))); // // // // double vCx[N] __attribute__ ((aligned(16))); // double vCy[N] __attribute__ ((aligned(16))); // double vCz[N] __attribute__ ((aligned(16))); // // // for (int a = 0; a < N; ++a) { // // // vB10[a] = recurrence::coefficient(1.0/A, B, t2[a]); // // // // vCx[a] = recurrence::coefficient<0>(rAi, B, rAB, t2[a]); // vCy[a] = recurrence::coefficient<1>(rAi, B, rAB, t2[a]); // vCz[a] = recurrence::coefficient<2>(rAi, B, rAB, t2[a]); // // // } // #define B00 vB00[a] // #define B10 vB10[a] // #define B01 vB01[a] // #define Cx vCx[a] // #define Cy vCy[a] // #define Cz vCz[a] // #define Dx vDx[a] // #define Dy vDy[a] // #define Dz vDz[a] #if defined (__INTEL_COMPILER) #pragma ivdep #pragma vector aligned #endif for (int a = 0; a < N; ++a) { double B10 = recurrence::coefficient(1.0/A, B, t2[a]); double Cx = recurrence::coefficient<0>(rAi, B, rAB, t2[a]); double Cy = recurrence::coefficient<1>(rAi, B, rAB, t2[a]); double Cz = recurrence::coefficient<2>(rAi, B, rAB, t2[a]); double Ix = (Cx + xij); double Iy = (Cy + yij); double Iz = (Cz + zij); double Px = (B10 + pow(Cx,2)); double Py = (B10 + pow(Cy,2)); double Pz = (B10 + pow(Cz,2)); double f0 = (3*B10 + pow(Cx,2)); double f10 = (3*pow(B10,2) + B10*(6*Cx*xij + pow(xij,2) + 6*pow(Cx,2)) + pow(Cx,2)*pow(Ix,2)); double f12 = (3*B10 + pow(Iy,2)); double f13 = (B10*(3*Cz + 2*zij) + Cz*pow(Iz,2)); double f14 = (3*pow(B10,2) + B10*(6*Cy*yij + pow(yij,2) + 6*pow(Cy,2)) + pow(Cy,2)*pow(Iy,2)); double f15 = (Cy*Iy + B10); double f18 = (B10*(3*Cx + 2*xij) + Cx*pow(Ix,2)); double f19 = (Cy*pow(Iy,2) + B10*(3*Cy + 2*yij)); double f2 = (3*pow(B10,2)*(5*Cz + 2*zij) + B10*Cz*(3*pow(zij,2) + 10*pow(Cz,2) + 12*Cz*zij) + pow(Cz,3)*pow(Iz,2)); double f20 = (B10 + pow(Iy,2)); double f21 = (pow(Cy,2)*pow(Iy,3) + B10*Iy*(8*Cy*yij + 10*pow(Cy,2) + pow(yij,2)) + 3*pow(B10,2)*(5*Cy + 3*yij)); double f22 = (3*pow(B10,2)*(3*zij + 5*Cz) + B10*Iz*(8*Cz*zij + 10*pow(Cz,2) + pow(zij,2)) + pow(Cz,2)*pow(Iz,3)); double f23 = (3*pow(B10,2) + Cy*pow(Iy,3) + 3*B10*Iy*(yij + 2*Cy)); double f25 = (pow(Cx,2)*pow(Ix,3) + B10*Ix*(8*Cx*xij + pow(xij,2) + 10*pow(Cx,2)) + 3*pow(B10,2)*(5*Cx + 3*xij)); double f27 = (3*pow(B10,2) + 3*B10*Cz*(2*Cz + zij) + Iz*pow(Cz,3)); double f28 = (B10 + pow(Iz,2)); double f29 = (3*B10 + pow(Iz,2)); double f3 = (B10*Cx*(12*Cx*xij + 10*pow(Cx,2) + 3*pow(xij,2)) + 3*pow(B10,2)*(5*Cx + 2*xij) + pow(Cx,3)*pow(Ix,2)); double f30 = (3*pow(B10,2) + 3*B10*Ix*(xij + 2*Cx) + Cx*pow(Ix,3)); double f31 = (3*pow(B10,2) + Cz*pow(Iz,3) + 3*B10*Iz*(2*Cz + zij)); double f32 = (3*B10 + pow(Cz,2)); double f33 = (3*B10 + pow(Cy,2)); double f34 = (B10*(3*Cx + xij) + Ix*pow(Cx,2)); double f35 = (Iz*pow(Cz,2) + B10*(3*Cz + zij)); double f36 = 15*pow(B10,3); double f39 = (3*pow(B10,2) + Iy*pow(Cy,3) + 3*B10*Cy*(yij + 2*Cy)); double f6 = (3*pow(B10,2) + pow(Cz,2)*pow(Iz,2) + B10*(6*Cz*zij + pow(zij,2) + 6*pow(Cz,2))); double f7 = (B10*(3*Cy + yij) + Iy*pow(Cy,2)); double f8 = (3*pow(B10,2) + 3*B10*Cx*(xij + 2*Cx) + Ix*pow(Cx,3)); double f9 = (3*pow(B10,2)*(5*Cy + 2*yij) + B10*Cy*(12*Cy*yij + 3*pow(yij,2) + 10*pow(Cy,2)) + pow(Cy,3)*pow(Iy,2)); I[0] += C[0]*W[a]*(Py*(Cz*zij + Pz)*(xij*(xij + 2*Cx) + Px)); I[1] += C[0]*W[a]*(f15*(Px + Cx*xij)*(Cz*zij + Pz)); I[2] += C[0]*W[a]*(Cy*f18*(Cz*zij + Pz)); I[3] += C[0]*W[a]*(Cx*f19*(Cz*zij + Pz)); I[4] += C[0]*W[a]*(Iy*f34*(Cz*zij + Pz)); I[5] += C[0]*W[a]*(Ix*f7*(Cz*zij + Pz)); I[6] += C[0]*W[a]*(Cz*Ix*Py*(xij*(xij + 2*Cx) + f0)); I[7] += C[0]*W[a]*(Cz*Ix*f32*(xij*(xij + 2*Cx) + f0)); I[8] += C[0]*W[a]*(Cy*Ix*Pz*(xij*(xij + 2*Cx) + f0)); I[9] += C[0]*W[a]*(Cy*Ix*f33*(xij*(xij + 2*Cx) + f0)); I[10] += C[0]*W[a]*((3*B10*Cx*Ix*(5*Cx*xij + 5*pow(Cx,2) + pow(xij,2)) + f36 + 9*pow(B10,2)*(5*Cx*xij + 5*pow(Cx,2) + pow(xij,2)) + pow(Cx,3)*pow(Ix,3))); I[11] += C[0]*W[a]*((9*pow(B10,2)*(5*Cy*yij + 5*pow(Cy,2) + pow(yij,2)) + f36 + pow(Cy,3)*pow(Iy,3) + 3*B10*Cy*Iy*(5*Cy*yij + 5*pow(Cy,2) + pow(yij,2)))); I[12] += C[0]*W[a]*((f36 + 3*B10*Cz*Iz*(5*pow(Cz,2) + 5*Cz*zij + pow(zij,2)) + pow(Cz,3)*pow(Iz,3) + 9*pow(B10,2)*(5*pow(Cz,2) + 5*Cz*zij + pow(zij,2)))); I[13] += C[0]*W[a]*(f10*(Cz*zij + Pz)); I[14] += C[0]*W[a]*(f14*(Cz*zij + Pz)); I[15] += C[0]*W[a]*(Px*f20*(Cz*zij + Pz)); I[16] += C[0]*W[a]*(Pz*f20*(Px + Cx*xij)); I[17] += C[0]*W[a]*(Pz*f15*(xij*(xij + 2*Cx) + Px)); I[18] += C[0]*W[a]*(Iz*f7*(Px + Cx*xij)); I[19] += C[0]*W[a]*(Cy*Iz*f33*(xij*(xij + 2*Cx) + Px)); I[20] += C[0]*W[a]*(Cy*f13*(Px + Cx*xij)); I[21] += C[0]*W[a]*(Cy*f35*(xij*(xij + 2*Cx) + Px)); I[22] += C[0]*W[a]*(Iy*f35*(Px + Cx*xij)); I[23] += C[0]*W[a]*(Cz*Iy*f32*(xij*(xij + 2*Cx) + Px)); I[24] += C[0]*W[a]*(Cz*f19*(Px + Cx*xij)); I[25] += C[0]*W[a]*(Cz*f7*(xij*(xij + 2*Cx) + Px)); I[26] += C[0]*W[a]*(Py*f28*(Px + Cx*xij)); I[27] += C[0]*W[a]*(Cx*Iy*f0*f28); I[28] += C[0]*W[a]*(Cx*f20*f35); I[29] += C[0]*W[a]*(Ix*Pz*f19); I[30] += C[0]*W[a]*(Cy*Ix*f28*f33); I[31] += C[0]*W[a]*(Cy*Ix*f6); I[32] += C[0]*W[a]*(Cy*f28*f34); I[33] += C[0]*W[a]*(Px*f15*f28); I[34] += C[0]*W[a]*(Cx*f28*f7); I[35] += C[0]*W[a]*(Cx*f13*f15); I[36] += C[0]*W[a]*(Iy*Iz*f8); I[37] += C[0]*W[a]*(Ix*Iz*f39); I[38] += C[0]*W[a]*(Ix*Iy*f27); I[39] += C[0]*W[a]*(Cz*Ix*f14); I[40] += C[0]*W[a]*(Cz*Ix*f20*f32); I[41] += C[0]*W[a]*(Cz*f20*f34); I[42] += C[0]*W[a]*(Cz*f15*f18); I[43] += C[0]*W[a]*(Iz*f15*f34); I[44] += C[0]*W[a]*(Ix*f15*f35); I[45] += C[0]*W[a]*(Ix*Py*f13); I[46] += C[0]*W[a]*(Iy*Px*f13); I[47] += C[0]*W[a]*(Cz*Iy*Px*f12); I[48] += C[0]*W[a]*(Cz*Iy*f12*f32); I[49] += C[0]*W[a]*(Cz*Iy*f10); I[50] += C[0]*W[a]*(Iy*Pz*f18); I[51] += C[0]*W[a]*(Cx*Iy*Pz*f12); I[52] += C[0]*W[a]*(Cx*Iy*f0*f12); I[53] += C[0]*W[a]*(Cx*Iy*f6); I[54] += C[0]*W[a]*(f6*(Px + Cx*xij)); I[55] += C[0]*W[a]*(f27*(xij*(xij + 2*Cx) + Px)); I[56] += C[0]*W[a]*(f39*(xij*(xij + 2*Cx) + Px)); I[57] += C[0]*W[a]*(f14*(Px + Cx*xij)); I[58] += C[0]*W[a]*(Cx*Iz*f14); I[59] += C[0]*W[a]*(Cx*Iz*f0*f20); I[60] += C[0]*W[a]*(Cx*Iz*f0*f29); I[61] += C[0]*W[a]*(Cx*Iz*Py*f29); I[62] += C[0]*W[a]*(Iz*Py*f18); I[63] += C[0]*W[a]*(Iz*Px*f19); I[64] += C[0]*W[a]*(Cy*Iz*Px*f29); I[65] += C[0]*W[a]*(Cy*Iz*f29*f33); I[66] += C[0]*W[a]*(Cy*Iz*f10); I[67] += C[0]*W[a]*(Cx*Cy*f31); I[68] += C[0]*W[a]*(Cx*Cz*f23); I[69] += C[0]*W[a]*(Cy*Cz*f30); I[70] += C[0]*W[a]*(Py*f30); I[71] += C[0]*W[a]*(Pz*f30); I[72] += C[0]*W[a]*(Pz*f23); I[73] += C[0]*W[a]*(Px*f23); I[74] += C[0]*W[a]*(Px*f31); I[75] += C[0]*W[a]*(Py*f31); I[76] += C[0]*W[a]*(Cy*f25); I[77] += C[0]*W[a]*(Cz*f25); I[78] += C[0]*W[a]*(Cz*f21); I[79] += C[0]*W[a]*(Cx*f21); I[80] += C[0]*W[a]*(Cx*f22); I[81] += C[0]*W[a]*(Cy*f22); I[82] += C[0]*W[a]*(f20*f27); I[83] += C[0]*W[a]*(f20*f8); I[84] += C[0]*W[a]*(f28*f8); I[85] += C[0]*W[a]*(f28*f39); I[86] += C[0]*W[a]*(Ix*f2); I[87] += C[0]*W[a]*(Ix*f9); I[88] += C[0]*W[a]*(Iz*f9); I[89] += C[0]*W[a]*(Iz*f3); I[90] += C[0]*W[a]*(Iy*f3); I[91] += C[0]*W[a]*(Iy*f2); I[92] += C[0]*W[a]*(f13*f34); I[93] += C[0]*W[a]*(f19*f34); I[94] += C[0]*W[a]*(f19*f35); I[95] += C[0]*W[a]*(f18*f35); I[96] += C[0]*W[a]*(f18*f7); I[97] += C[0]*W[a]*(f13*f7); I[98] += C[0]*W[a]*(f10*f15); I[99] += C[0]*W[a]*(f15*f6); } #undef B00 #undef B10 #undef B01 #undef Cx #undef Cy #undef Cz #undef Dx #undef Dy #undef Dz #undef pow } static inline void reorder(double (&I)[100]) { double T[100]; for (int i = 0; i < 100; ++i) { T[i] = I[i]; } I[46] = T[0]; I[99] = T[1]; I[49] = T[2]; I[69] = T[3]; I[94] = T[4]; I[96] = T[5]; I[6] = T[6]; I[2] = T[7]; I[8] = T[8]; I[1] = T[9]; I[0] = T[10]; I[11] = T[11]; I[22] = T[12]; I[44] = T[13]; I[66] = T[14]; I[64] = T[15]; I[57] = T[16]; I[38] = T[17]; I[95] = T[18]; I[41] = T[19]; I[79] = T[20]; I[48] = T[21]; I[97] = T[22]; I[32] = T[23]; I[59] = T[24]; I[36] = T[25]; I[75] = T[26]; I[80] = T[27]; I[67] = T[28]; I[58] = T[29]; I[71] = T[30]; I[78] = T[31]; I[73] = T[32]; I[83] = T[33]; I[85] = T[34]; I[89] = T[35]; I[90] = T[36]; I[91] = T[37]; I[92] = T[38]; I[56] = T[39]; I[52] = T[40]; I[54] = T[41]; I[39] = T[42]; I[93] = T[43]; I[98] = T[44]; I[76] = T[45]; I[84] = T[46]; I[14] = T[47]; I[12] = T[48]; I[34] = T[49]; I[37] = T[50]; I[17] = T[51]; I[10] = T[52]; I[87] = T[53]; I[77] = T[54]; I[42] = T[55]; I[31] = T[56]; I[55] = T[57]; I[65] = T[58]; I[60] = T[59]; I[20] = T[60]; I[25] = T[61]; I[45] = T[62]; I[63] = T[63]; I[23] = T[64]; I[21] = T[65]; I[43] = T[66]; I[29] = T[67]; I[19] = T[68]; I[9] = T[69]; I[5] = T[70]; I[7] = T[71]; I[18] = T[72]; I[13] = T[73]; I[24] = T[74]; I[26] = T[75]; I[3] = T[76]; I[4] = T[77]; I[16] = T[78]; I[15] = T[79]; I[27] = T[80]; I[28] = T[81]; I[62] = T[82]; I[50] = T[83]; I[70] = T[84]; I[81] = T[85]; I[72] = T[86]; I[51] = T[87]; I[61] = T[88]; I[40] = T[89]; I[30] = T[90]; I[82] = T[91]; I[74] = T[92]; I[53] = T[93]; I[68] = T[94]; I[47] = T[95]; I[35] = T[96]; I[86] = T[97]; I[33] = T[98]; I[88] = T[99]; } }; template<> struct impl > { typedef void enable; static const bool value = true; static inline void eval(double A, double B, const Vector<3> &rAi, const Vector<3> &rBk, const Vector<3> &rAB, const Vector<3> &rij, const Vector<3> &rkl, const Vector<3> &t2, const Vector<3> &W, const double (&C)[1], double (&I)[108]) { #define pow(x,y) util::pow<(y)>::eval((x)) const int N = 3; double xij = rij[0]; double yij = rij[1]; double zij = rij[2]; // // double vB00[N] __attribute__ ((aligned(16))); // // // double vB10[N] __attribute__ ((aligned(16))); // // // // double vCx[N] __attribute__ ((aligned(16))); // double vCy[N] __attribute__ ((aligned(16))); // double vCz[N] __attribute__ ((aligned(16))); // // // double vDx[N] __attribute__ ((aligned(16))); // double vDy[N] __attribute__ ((aligned(16))); // double vDz[N] __attribute__ ((aligned(16))); // // for (int a = 0; a < N; ++a) { // // vB00[a] = 0.5*t2[a]; // // // vB10[a] = recurrence::coefficient(1.0/A, B, t2[a]); // // // // vCx[a] = recurrence::coefficient<0>(rAi, B, rAB, t2[a]); // vCy[a] = recurrence::coefficient<1>(rAi, B, rAB, t2[a]); // vCz[a] = recurrence::coefficient<2>(rAi, B, rAB, t2[a]); // // // vDx[a] = recurrence::coefficient<0>(rBk, -A, rAB, t2[a]); // vDy[a] = recurrence::coefficient<1>(rBk, -A, rAB, t2[a]); // vDz[a] = recurrence::coefficient<2>(rBk, -A, rAB, t2[a]); // // } // #define B00 vB00[a] // #define B10 vB10[a] // #define B01 vB01[a] // #define Cx vCx[a] // #define Cy vCy[a] // #define Cz vCz[a] // #define Dx vDx[a] // #define Dy vDy[a] // #define Dz vDz[a] #if defined (__INTEL_COMPILER) #pragma ivdep #pragma vector aligned #endif for (int a = 0; a < N; ++a) { double B00 = 0.5*t2[a]; double B10 = recurrence::coefficient(1.0/A, B, t2[a]); double Cx = recurrence::coefficient<0>(rAi, B, rAB, t2[a]); double Cy = recurrence::coefficient<1>(rAi, B, rAB, t2[a]); double Cz = recurrence::coefficient<2>(rAi, B, rAB, t2[a]); double Dx = recurrence::coefficient<0>(rBk, -A, rAB, t2[a]); double Dy = recurrence::coefficient<1>(rBk, -A, rAB, t2[a]); double Dz = recurrence::coefficient<2>(rBk, -A, rAB, t2[a]); double Ix = (Cx + xij); double Iy = (Cy + yij); double Iz = (Cz + zij); double Px = (B10 + pow(Cx,2)); double Py = (B10 + pow(Cy,2)); double Pz = (B10 + pow(Cz,2)); double Qx = (Cx*Dx + B00); double Qy = (Cy*Dy + B00); double Qz = (Cz*Dz + B00); double f1 = (Dz*Pz + 2*B00*Cz); double f10 = (3*pow(B10,2) + pow(Cz,2)*pow(Iz,2) + B10*(6*Cz*zij + pow(zij,2) + 6*pow(Cz,2))); double f11 = (B00*(Iz*(3*Cz + zij) + 3*B10) + Dz*(B10*(3*Cz + 2*zij) + Cz*pow(Iz,2))); double f12 = (B10*(3*Cy + yij) + Iy*pow(Cy,2)); double f13 = (3*pow(B10,2) + B10*(6*Cx*xij + pow(xij,2) + 6*pow(Cx,2)) + pow(Cx,2)*pow(Ix,2)); double f14 = (Dy*(Cy*pow(Iy,2) + B10*(3*Cy + 2*yij)) + B00*(3*B10 + Iy*(3*Cy + yij))); double f2 = (Dz*(Iz*pow(Cz,2) + B10*(3*Cz + zij)) + 3*B00*Pz + 2*B00*Cz*zij); double f20 = (B10*(3*Cz + 2*zij) + Cz*pow(Iz,2)); double f21 = (3*pow(B10,2) + B10*(6*Cy*yij + pow(yij,2) + 6*pow(Cy,2)) + pow(Cy,2)*pow(Iy,2)); double f22 = (Cy*Iy + B10); double f23 = (Cy*pow(Iy,2) + B10*(3*Cy + 2*yij)); double f24 = (B10*(3*Cx + xij) + Ix*pow(Cx,2)); double f25 = (B00*(3*B10 + Ix*(3*Cx + xij)) + Dx*(B10*(3*Cx + 2*xij) + Cx*pow(Ix,2))); double f28 = (B10 + pow(Iy,2)); double f29 = (B10 + pow(Iz,2)); double f37 = (2*B00*Cy*yij + 3*B00*Py + Dy*(B10*(3*Cy + yij) + Iy*pow(Cy,2))); double f38 = (Iz*pow(Cz,2) + B10*(3*Cz + zij)); double f39 = (Dx*(B10*(3*Cx + xij) + Ix*pow(Cx,2)) + 2*B00*Cx*xij + 3*B00*Px); double f4 = (B10*(3*Cx + 2*xij) + Cx*pow(Ix,2)); double f5 = (B00*(yij + 2*Cy) + Dy*(Cy*Iy + B10)); double f6 = (Dx*Px + 2*B00*Cx); double f9 = (Dy*Py + 2*B00*Cy); I[0] += C[0]*W[a]*(Cy*Iz*(Qx*xij + f6)); I[1] += C[0]*W[a]*(Cy*(Cz*zij + Pz)*(Dx*xij + Qx)); I[2] += C[0]*W[a]*(Dy*(Px + Cx*xij)*(Cz*zij + Pz)); I[3] += C[0]*W[a]*(Cx*Iy*(f1 + Qz*zij)); I[4] += C[0]*W[a]*((Px + Cx*xij)*(f1 + Qz*zij)); I[5] += C[0]*W[a]*(Cy*(Px + Cx*xij)*(Dz*zij + Qz)); I[6] += C[0]*W[a]*(Cy*Qz*(xij*(xij + 2*Cx) + Px)); I[7] += C[0]*W[a]*(Iy*Qz*(Px + Cx*xij)); I[8] += C[0]*W[a]*(Dz*f22*(Px + Cx*xij)); I[9] += C[0]*W[a]*(Dz*Py*(xij*(xij + 2*Cx) + Px)); I[10] += C[0]*W[a]*(Ix*Py*(Dz*zij + Qz)); I[11] += C[0]*W[a]*(Iy*Px*(Dz*zij + Qz)); I[12] += C[0]*W[a]*(Cx*f22*(Dz*zij + Qz)); I[13] += C[0]*W[a]*((Dz*(3*pow(B10,2) + pow(Cz,2)*pow(Iz,2) + B10*(6*Cz*zij + pow(zij,2) + 6*pow(Cz,2))) + 2*B00*(2*Cz + zij)*(3*B10 + Cz*Iz))); I[14] += C[0]*W[a]*(f22*(f1 + Qz*zij)); I[15] += C[0]*W[a]*(Py*(zij*(2*B00 + Dz*(2*Cz + zij)) + f1)); I[16] += C[0]*W[a]*(Px*(zij*(2*B00 + Dz*(2*Cz + zij)) + f1)); I[17] += C[0]*W[a]*(Cy*Ix*(f1 + Qz*zij)); I[18] += C[0]*W[a]*(Cx*Cy*(zij*(2*B00 + Dz*(2*Cz + zij)) + f1)); I[19] += C[0]*W[a]*(Cx*Cz*(yij*(2*B00 + Dy*(yij + 2*Cy)) + f9)); I[20] += C[0]*W[a]*((2*B00*(yij + 2*Cy)*(3*B10 + Cy*Iy) + Dy*(3*pow(B10,2) + B10*(6*Cy*yij + pow(yij,2) + 6*pow(Cy,2)) + pow(Cy,2)*pow(Iy,2)))); I[21] += C[0]*W[a]*(Pz*(yij*(2*B00 + Dy*(yij + 2*Cy)) + f9)); I[22] += C[0]*W[a]*(Px*(yij*(2*B00 + Dy*(yij + 2*Cy)) + f9)); I[23] += C[0]*W[a]*(Iz*Px*(Dy*yij + Qy)); I[24] += C[0]*W[a]*(Iz*Qy*(Px + Cx*xij)); I[25] += C[0]*W[a]*(Cz*Qy*(xij*(xij + 2*Cx) + Px)); I[26] += C[0]*W[a]*(Cz*(Px + Cx*xij)*(Dy*yij + Qy)); I[27] += C[0]*W[a]*(Cx*(Cz*zij + Pz)*(Dy*yij + Qy)); I[28] += C[0]*W[a]*(Ix*Qy*(Cz*zij + Pz)); I[29] += C[0]*W[a]*(Dx*f22*(Cz*zij + Pz)); I[30] += C[0]*W[a]*((Cz*zij + Pz)*(Qx*xij + f6)); I[31] += C[0]*W[a]*(Cz*Iy*(Qx*xij + f6)); I[32] += C[0]*W[a]*(Cy*Cz*(xij*(2*B00 + Dx*(xij + 2*Cx)) + f6)); I[33] += C[0]*W[a]*((2*B00*(xij + 2*Cx)*(Cx*Ix + 3*B10) + Dx*(3*pow(B10,2) + B10*(6*Cx*xij + pow(xij,2) + 6*pow(Cx,2)) + pow(Cx,2)*pow(Ix,2)))); I[34] += C[0]*W[a]*(f22*(Qx*xij + f6)); I[35] += C[0]*W[a]*(Pz*(xij*(2*B00 + Dx*(xij + 2*Cx)) + f6)); I[36] += C[0]*W[a]*(Py*(xij*(2*B00 + Dx*(xij + 2*Cx)) + f6)); I[37] += C[0]*W[a]*(Iz*Py*(Dx*xij + Qx)); I[38] += C[0]*W[a]*(Cz*f22*(Dx*xij + Qx)); I[39] += C[0]*W[a]*(Iy*Pz*(Dx*xij + Qx)); I[40] += C[0]*W[a]*(Iy*Qx*(Cz*zij + Pz)); I[41] += C[0]*W[a]*(f5*(Cz*zij + Pz)); I[42] += C[0]*W[a]*(Cz*Ix*f5); I[43] += C[0]*W[a]*(Ix*Pz*(Dy*yij + Qy)); I[44] += C[0]*W[a]*(f38*(Dy*yij + Qy)); I[45] += C[0]*W[a]*(f24*(Dy*yij + Qy)); I[46] += C[0]*W[a]*(Dy*Iz*f24); I[47] += C[0]*W[a]*(Ix*Iz*f9); I[48] += C[0]*W[a]*(Dy*Ix*f38); I[49] += C[0]*W[a]*(Cx*Dy*f20); I[50] += C[0]*W[a]*(Dy*Pz*(xij*(xij + 2*Cx) + Px)); I[51] += C[0]*W[a]*(f1*(xij*(xij + 2*Cx) + Px)); I[52] += C[0]*W[a]*(f9*(xij*(xij + 2*Cx) + Px)); I[53] += C[0]*W[a]*(f5*(Px + Cx*xij)); I[54] += C[0]*W[a]*(Cx*Iz*f5); I[55] += C[0]*W[a]*(Cx*Qy*f29); I[56] += C[0]*W[a]*(Dy*Px*f29); I[57] += C[0]*W[a]*(Cz*Dy*f4); I[58] += C[0]*W[a]*(Cy*Dz*f4); I[59] += C[0]*W[a]*(Dz*Px*f28); I[60] += C[0]*W[a]*(Cx*Dz*f23); I[61] += C[0]*W[a]*(Cx*Qz*f28); I[62] += C[0]*W[a]*(f12*(Dz*zij + Qz)); I[63] += C[0]*W[a]*(f24*(Dz*zij + Qz)); I[64] += C[0]*W[a]*(Dz*Iy*f24); I[65] += C[0]*W[a]*(Dz*Ix*f12); I[66] += C[0]*W[a]*(Ix*Iy*f1); I[67] += C[0]*W[a]*(Ix*Qz*f22); I[68] += C[0]*W[a]*(Iz*Qx*f22); I[69] += C[0]*W[a]*(Iy*Iz*f6); I[70] += C[0]*W[a]*(Dx*Iy*f38); I[71] += C[0]*W[a]*(f38*(Dx*xij + Qx)); I[72] += C[0]*W[a]*(f12*(Dx*xij + Qx)); I[73] += C[0]*W[a]*(Dx*Iz*f12); I[74] += C[0]*W[a]*(Cy*Dx*f20); I[75] += C[0]*W[a]*(Cy*Qx*f29); I[76] += C[0]*W[a]*(Dx*Py*f29); I[77] += C[0]*W[a]*(Cz*Dx*f23); I[78] += C[0]*W[a]*(Cz*Qx*f28); I[79] += C[0]*W[a]*(Dx*Pz*f28); I[80] += C[0]*W[a]*(Dx*f21); I[81] += C[0]*W[a]*(Dx*f10); I[82] += C[0]*W[a]*(Dy*f10); I[83] += C[0]*W[a]*(Dy*f13); I[84] += C[0]*W[a]*(Dz*f13); I[85] += C[0]*W[a]*(Dz*f21); I[86] += C[0]*W[a]*(f29*f9); I[87] += C[0]*W[a]*(f29*f6); I[88] += C[0]*W[a]*(f28*f6); I[89] += C[0]*W[a]*(f1*f28); I[90] += C[0]*W[a]*(Qz*f4); I[91] += C[0]*W[a]*(Qy*f4); I[92] += C[0]*W[a]*(Qy*f20); I[93] += C[0]*W[a]*(Qx*f20); I[94] += C[0]*W[a]*(Qx*f23); I[95] += C[0]*W[a]*(Qz*f23); I[96] += C[0]*W[a]*(Cy*f25); I[97] += C[0]*W[a]*(Cz*f25); I[98] += C[0]*W[a]*(Cz*f14); I[99] += C[0]*W[a]*(Cx*f14); I[100] += C[0]*W[a]*(Cx*f11); I[101] += C[0]*W[a]*(Cy*f11); I[102] += C[0]*W[a]*(Iy*f39); I[103] += C[0]*W[a]*(Iz*f39); I[104] += C[0]*W[a]*(Iz*f37); I[105] += C[0]*W[a]*(Ix*f37); I[106] += C[0]*W[a]*(Ix*f2); I[107] += C[0]*W[a]*(Iy*f2); } #undef B00 #undef B10 #undef B01 #undef Cx #undef Cy #undef Cz #undef Dx #undef Dy #undef Dz #undef pow } static inline void reorder(double (&I)[108]) { double T[108]; for (int i = 0; i < 108; ++i) { T[i] = I[i]; } I[27] = T[0]; I[29] = T[1]; I[64] = T[2]; I[106] = T[3]; I[100] = T[4]; I[99] = T[5]; I[77] = T[6]; I[94] = T[7]; I[93] = T[8]; I[73] = T[9]; I[97] = T[10]; I[102] = T[11]; I[105] = T[12]; I[86] = T[13]; I[107] = T[14]; I[85] = T[15]; I[84] = T[16]; I[101] = T[17]; I[87] = T[18]; I[46] = T[19]; I[43] = T[20]; I[44] = T[21]; I[42] = T[22]; I[66] = T[23]; I[63] = T[24]; I[41] = T[25]; I[58] = T[26]; I[70] = T[27]; I[65] = T[28]; I[35] = T[29]; I[28] = T[30]; I[22] = T[31]; I[5] = T[32]; I[0] = T[33]; I[21] = T[34]; I[2] = T[35]; I[1] = T[36]; I[25] = T[37]; I[23] = T[38]; I[20] = T[39]; I[34] = T[40]; I[71] = T[41]; I[59] = T[42]; I[56] = T[43]; I[68] = T[44]; I[54] = T[45]; I[60] = T[46]; I[61] = T[47]; I[62] = T[48]; I[52] = T[49]; I[38] = T[50]; I[74] = T[51]; I[37] = T[52]; I[57] = T[53]; I[69] = T[54]; I[51] = T[55]; I[48] = T[56]; I[40] = T[57]; I[75] = T[58]; I[78] = T[59]; I[81] = T[60]; I[82] = T[61]; I[103] = T[62]; I[96] = T[63]; I[90] = T[64]; I[91] = T[65]; I[92] = T[66]; I[95] = T[67]; I[33] = T[68]; I[30] = T[69]; I[32] = T[70]; I[26] = T[71]; I[19] = T[72]; I[31] = T[73]; I[17] = T[74]; I[15] = T[75]; I[13] = T[76]; I[11] = T[77]; I[10] = T[78]; I[8] = T[79]; I[7] = T[80]; I[14] = T[81]; I[50] = T[82]; I[36] = T[83]; I[72] = T[84]; I[79] = T[85]; I[49] = T[86]; I[12] = T[87]; I[6] = T[88]; I[80] = T[89]; I[76] = T[90]; I[39] = T[91]; I[53] = T[92]; I[16] = T[93]; I[9] = T[94]; I[83] = T[95]; I[3] = T[96]; I[4] = T[97]; I[47] = T[98]; I[45] = T[99]; I[88] = T[100]; I[89] = T[101]; I[18] = T[102]; I[24] = T[103]; I[67] = T[104]; I[55] = T[105]; I[98] = T[106]; I[104] = T[107]; } }; template<> struct impl > { typedef void enable; static const bool value = true; static inline void eval(double A, double B, const Vector<3> &rAi, const Vector<3> &rBk, const Vector<3> &rAB, const Vector<3> &rij, const Vector<3> &rkl, const Vector<3> &t2, const Vector<3> &W, const double (&C)[4], double (&I)[96]) { #define pow(x,y) util::pow<(y)>::eval((x)) const int N = 3; double xkl = rkl[0]; double ykl = rkl[1]; double zkl = rkl[2]; // // double vB00[N] __attribute__ ((aligned(16))); // // // double vB10[N] __attribute__ ((aligned(16))); // // // double vB01[N] __attribute__ ((aligned(16))); // // // double vCx[N] __attribute__ ((aligned(16))); // double vCy[N] __attribute__ ((aligned(16))); // double vCz[N] __attribute__ ((aligned(16))); // // // double vDx[N] __attribute__ ((aligned(16))); // double vDy[N] __attribute__ ((aligned(16))); // double vDz[N] __attribute__ ((aligned(16))); // // for (int a = 0; a < N; ++a) { // // vB00[a] = 0.5*t2[a]; // // // vB10[a] = recurrence::coefficient(1.0/A, B, t2[a]); // // // vB01[a] = recurrence::coefficient(1.0/B, A, t2[a]); // // // vCx[a] = recurrence::coefficient<0>(rAi, B, rAB, t2[a]); // vCy[a] = recurrence::coefficient<1>(rAi, B, rAB, t2[a]); // vCz[a] = recurrence::coefficient<2>(rAi, B, rAB, t2[a]); // // // vDx[a] = recurrence::coefficient<0>(rBk, -A, rAB, t2[a]); // vDy[a] = recurrence::coefficient<1>(rBk, -A, rAB, t2[a]); // vDz[a] = recurrence::coefficient<2>(rBk, -A, rAB, t2[a]); // // } // #define B00 vB00[a] // #define B10 vB10[a] // #define B01 vB01[a] // #define Cx vCx[a] // #define Cy vCy[a] // #define Cz vCz[a] // #define Dx vDx[a] // #define Dy vDy[a] // #define Dz vDz[a] #if defined (__INTEL_COMPILER) #pragma ivdep #pragma vector aligned #endif for (int a = 0; a < N; ++a) { double B00 = 0.5*t2[a]; double B10 = recurrence::coefficient(1.0/A, B, t2[a]); double B01 = recurrence::coefficient(1.0/B, A, t2[a]); double Cx = recurrence::coefficient<0>(rAi, B, rAB, t2[a]); double Cy = recurrence::coefficient<1>(rAi, B, rAB, t2[a]); double Cz = recurrence::coefficient<2>(rAi, B, rAB, t2[a]); double Dx = recurrence::coefficient<0>(rBk, -A, rAB, t2[a]); double Dy = recurrence::coefficient<1>(rBk, -A, rAB, t2[a]); double Dz = recurrence::coefficient<2>(rBk, -A, rAB, t2[a]); double Kx = (xkl + Dx); double Ky = (ykl + Dy); double Kz = (Dz + zkl); double Px = (B10 + pow(Cx,2)); double Py = (B10 + pow(Cy,2)); double Pz = (B10 + pow(Cz,2)); double Qx = (Cx*Dx + B00); double Qy = (Cy*Dy + B00); double Qz = (Cz*Dz + B00); double f10 = 2*B00*Cx; double f11 = (B01 + Dx*Kx); double f19 = 2*B00*Cz; double f2 = (Cy*Dy*Ky + B01*Cy + B00*(ykl + 2*Dy)); double f20 = (Dz*Kz + B01); double f21 = Dx*pow(Cx,2); double f22 = (B00 + Cx*Kx); double f23 = (B00 + Cy*Ky); double f25 = B10*Dz; double f27 = 2*pow(B00,2); double f29 = (B01 + Dy*Ky); double f31 = B10*Dx; double f33 = Dy*pow(Cy,2); double f35 = (B01*Cz + B00*(2*Dz + zkl) + Cz*Dz*Kz); double f4 = (B01*Cx + Cx*Dx*Kx + B00*(xkl + 2*Dx)); double f5 = 2*B00*Cy; double f7 = B10*Dy; double f8 = Dz*pow(Cz,2); I[0] += C[3]*W[a]*((f27 + xkl*(f10 + f21 + f31) + B01*Px + Dx*(2*f10 + Dx*Px))); I[1] += C[3]*W[a]*((f27 + Dz*(Dz*Pz + 2*f19) + B01*Pz + zkl*(f19 + f25 + f8))); I[2] += C[3]*W[a]*((f27 + B01*Py + Dy*(2*f5 + Dy*Py) + ykl*(f33 + f5 + f7))); I[3] += C[3]*W[a]*(Dx*(f33 + B10*Ky + ykl*pow(Cy,2) + f5)); I[4] += C[3]*W[a]*(Dz*(f33 + B10*Ky + ykl*pow(Cy,2) + f5)); I[5] += C[2]*W[a]*((f33 + B10*Ky + ykl*pow(Cy,2) + f5)); I[6] += C[3]*W[a]*(Kx*(f33 + f5 + f7)); I[7] += C[3]*W[a]*(Kz*(f33 + f5 + f7)); I[8] += C[1]*W[a]*((f33 + f5 + f7)); I[9] += C[3]*W[a]*(Dy*(zkl*pow(Cz,2) + f19 + B10*Kz + f8)); I[10] += C[3]*W[a]*(Dx*(zkl*pow(Cz,2) + f19 + B10*Kz + f8)); I[11] += C[2]*W[a]*((zkl*pow(Cz,2) + f19 + B10*Kz + f8)); I[12] += C[3]*W[a]*(Ky*(f19 + f25 + f8)); I[13] += C[3]*W[a]*(Kx*(f19 + f25 + f8)); I[14] += C[1]*W[a]*((f19 + f25 + f8)); I[15] += C[3]*W[a]*(Dz*(f10 + f21 + B10*Kx + xkl*pow(Cx,2))); I[16] += C[3]*W[a]*(Dy*(f10 + f21 + B10*Kx + xkl*pow(Cx,2))); I[17] += C[2]*W[a]*((f10 + f21 + B10*Kx + xkl*pow(Cx,2))); I[18] += C[3]*W[a]*(Kz*(f10 + f21 + f31)); I[19] += C[3]*W[a]*(Ky*(f10 + f21 + f31)); I[20] += C[1]*W[a]*((f10 + f21 + f31)); I[21] += C[3]*W[a]*(Cy*Dx*(Cz*zkl + Qz)); I[22] += C[3]*W[a]*(Cx*Dy*(Cz*zkl + Qz)); I[23] += C[2]*W[a]*(Cx*(Cz*zkl + Qz)); I[24] += C[3]*W[a]*(Qx*(Cz*zkl + Qz)); I[25] += C[3]*W[a]*(Qy*(Cz*zkl + Qz)); I[26] += C[2]*W[a]*(Cy*(Cz*zkl + Qz)); I[27] += C[3]*W[a]*(Cy*Kx*Qz); I[28] += C[3]*W[a]*(Px*f20); I[29] += C[3]*W[a]*(Py*f20); I[30] += C[3]*W[a]*(Cx*Cy*f20); I[31] += C[3]*W[a]*(Cx*Dz*f23); I[32] += C[3]*W[a]*(Cz*Dx*f23); I[33] += C[2]*W[a]*(Cz*f23); I[34] += C[3]*W[a]*(Qx*f23); I[35] += C[2]*W[a]*(Cx*f23); I[36] += C[3]*W[a]*(Cx*f2); I[37] += C[3]*W[a]*(Cz*f2); I[38] += C[3]*W[a]*(Qy*f22); I[39] += C[3]*W[a]*(Qz*f22); I[40] += C[3]*W[a]*(Cx*Ky*Qz); I[41] += C[1]*W[a]*(Cx*Qz); I[42] += C[3]*W[a]*(Qz*f23); I[43] += C[1]*W[a]*(Cy*Qz); I[44] += C[3]*W[a]*(Cy*f4); I[45] += C[3]*W[a]*(Cz*f4); I[46] += C[3]*W[a]*(Cz*Dy*f22); I[47] += C[2]*W[a]*(Cz*f22); I[48] += C[3]*W[a]*(Cz*Kx*Qy); I[49] += C[1]*W[a]*(Cz*Qy); I[50] += C[1]*W[a]*(Cx*Qy); I[51] += C[3]*W[a]*(Cx*Kz*Qy); I[52] += C[2]*W[a]*(Cx*Cy*Kz); I[53] += C[3]*W[a]*(Dx*Kz*Py); I[54] += C[2]*W[a]*(Kz*Py); I[55] += C[3]*W[a]*(Cy*Kz*Qx); I[56] += C[1]*W[a]*(Cy*Qx); I[57] += C[2]*W[a]*(Cy*f22); I[58] += C[3]*W[a]*(Cy*Dz*f22); I[59] += C[1]*W[a]*(Cx*Cy*Dz); I[60] += C[0]*W[a]*(Cx*Cy); I[61] += C[3]*W[a]*(Cx*Cz*f29); I[62] += C[3]*W[a]*(Px*f29); I[63] += C[3]*W[a]*(Pz*f29); I[64] += C[3]*W[a]*(Pz*f11); I[65] += C[3]*W[a]*(Py*f11); I[66] += C[3]*W[a]*(Cy*Cz*f11); I[67] += C[2]*W[a]*(Cy*Cz*Kx); I[68] += C[1]*W[a]*(Cy*Cz*Dx); I[69] += C[0]*W[a]*(Cy*Cz); I[70] += C[1]*W[a]*(Cz*Qx); I[71] += C[3]*W[a]*(Cz*Ky*Qx); I[72] += C[2]*W[a]*(Cx*Cz*Ky); I[73] += C[0]*W[a]*(Cx*Cz); I[74] += C[1]*W[a]*(Cx*Cz*Dy); I[75] += C[1]*W[a]*(Dy*Pz); I[76] += C[3]*W[a]*(Dy*Kx*Pz); I[77] += C[2]*W[a]*(Kx*Pz); I[78] += C[2]*W[a]*(Kx*Py); I[79] += C[3]*W[a]*(Dz*Kx*Py); I[80] += C[1]*W[a]*(Dz*Py); I[81] += C[0]*W[a]*(Py); I[82] += C[1]*W[a]*(Dx*Py); I[83] += C[3]*W[a]*(Dx*Ky*Pz); I[84] += C[1]*W[a]*(Dx*Pz); I[85] += C[0]*W[a]*(Pz); I[86] += C[2]*W[a]*(Ky*Pz); I[87] += C[2]*W[a]*(Ky*Px); I[88] += C[3]*W[a]*(Dz*Ky*Px); I[89] += C[1]*W[a]*(Dz*Px); I[90] += C[2]*W[a]*(Kz*Px); I[91] += C[3]*W[a]*(Dy*Kz*Px); I[92] += C[1]*W[a]*(Dy*Px); I[93] += C[0]*W[a]*(Px); I[94] += C[3]*W[a]*(Cx*f35); I[95] += C[3]*W[a]*(Cy*f35); } #undef B00 #undef B10 #undef B01 #undef Cx #undef Cy #undef Cz #undef Dx #undef Dy #undef Dz #undef pow } static inline void reorder(double (&I)[96]) { double T[96]; for (int i = 0; i < 96; ++i) { T[i] = I[i]; } I[30] = T[0]; I[92] = T[1]; I[61] = T[2]; I[55] = T[3]; I[67] = T[4]; I[49] = T[5]; I[37] = T[6]; I[85] = T[7]; I[13] = T[8]; I[86] = T[9]; I[80] = T[10]; I[74] = T[11]; I[68] = T[12]; I[44] = T[13]; I[20] = T[14]; I[42] = T[15]; I[36] = T[16]; I[24] = T[17]; I[78] = T[18]; I[54] = T[19]; I[6] = T[20]; I[83] = T[21]; I[88] = T[22]; I[76] = T[23]; I[82] = T[24]; I[89] = T[25]; I[77] = T[26]; I[47] = T[27]; I[90] = T[28]; I[91] = T[29]; I[93] = T[30]; I[69] = T[31]; I[59] = T[32]; I[53] = T[33]; I[57] = T[34]; I[51] = T[35]; I[63] = T[36]; I[65] = T[37]; I[39] = T[38]; I[46] = T[39]; I[70] = T[40]; I[22] = T[41]; I[71] = T[42]; I[23] = T[43]; I[33] = T[44]; I[34] = T[45]; I[40] = T[46]; I[28] = T[47]; I[41] = T[48]; I[17] = T[49]; I[15] = T[50]; I[87] = T[51]; I[75] = T[52]; I[79] = T[53]; I[73] = T[54]; I[81] = T[55]; I[9] = T[56]; I[27] = T[57]; I[45] = T[58]; I[21] = T[59]; I[3] = T[60]; I[64] = T[61]; I[60] = T[62]; I[62] = T[63]; I[32] = T[64]; I[31] = T[65]; I[35] = T[66]; I[29] = T[67]; I[11] = T[68]; I[5] = T[69]; I[10] = T[70]; I[58] = T[71]; I[52] = T[72]; I[4] = T[73]; I[16] = T[74]; I[14] = T[75]; I[38] = T[76]; I[26] = T[77]; I[25] = T[78]; I[43] = T[79]; I[19] = T[80]; I[1] = T[81]; I[7] = T[82]; I[56] = T[83]; I[8] = T[84]; I[2] = T[85]; I[50] = T[86]; I[48] = T[87]; I[66] = T[88]; I[18] = T[89]; I[72] = T[90]; I[84] = T[91]; I[12] = T[92]; I[0] = T[93]; I[94] = T[94]; I[95] = T[95]; } }; template<> struct impl > { typedef void enable; static const bool value = true; static inline void eval(double A, double B, const Vector<3> &rAi, const Vector<3> &rBk, const Vector<3> &rAB, const Vector<3> &rij, const Vector<3> &rkl, const Vector<2> &t2, const Vector<2> &W, const double (&C)[2], double (&I)[24]) { #define pow(x,y) util::pow<(y)>::eval((x)) const int N = 2; // // double vB00[N] __attribute__ ((aligned(16))); // // // double vB10[N] __attribute__ ((aligned(16))); // // // // double vCx[N] __attribute__ ((aligned(16))); // double vCy[N] __attribute__ ((aligned(16))); // double vCz[N] __attribute__ ((aligned(16))); // // // double vDx[N] __attribute__ ((aligned(16))); // double vDy[N] __attribute__ ((aligned(16))); // double vDz[N] __attribute__ ((aligned(16))); // // for (int a = 0; a < N; ++a) { // // vB00[a] = 0.5*t2[a]; // // // vB10[a] = recurrence::coefficient(1.0/A, B, t2[a]); // // // // vCx[a] = recurrence::coefficient<0>(rAi, B, rAB, t2[a]); // vCy[a] = recurrence::coefficient<1>(rAi, B, rAB, t2[a]); // vCz[a] = recurrence::coefficient<2>(rAi, B, rAB, t2[a]); // // // vDx[a] = recurrence::coefficient<0>(rBk, -A, rAB, t2[a]); // vDy[a] = recurrence::coefficient<1>(rBk, -A, rAB, t2[a]); // vDz[a] = recurrence::coefficient<2>(rBk, -A, rAB, t2[a]); // // } // #define B00 vB00[a] // #define B10 vB10[a] // #define B01 vB01[a] // #define Cx vCx[a] // #define Cy vCy[a] // #define Cz vCz[a] // #define Dx vDx[a] // #define Dy vDy[a] // #define Dz vDz[a] #if defined (__INTEL_COMPILER) #pragma ivdep #pragma vector aligned #endif for (int a = 0; a < N; ++a) { double B00 = 0.5*t2[a]; double B10 = recurrence::coefficient(1.0/A, B, t2[a]); double Cx = recurrence::coefficient<0>(rAi, B, rAB, t2[a]); double Cy = recurrence::coefficient<1>(rAi, B, rAB, t2[a]); double Cz = recurrence::coefficient<2>(rAi, B, rAB, t2[a]); double Dx = recurrence::coefficient<0>(rBk, -A, rAB, t2[a]); double Dy = recurrence::coefficient<1>(rBk, -A, rAB, t2[a]); double Dz = recurrence::coefficient<2>(rBk, -A, rAB, t2[a]); double Px = (B10 + pow(Cx,2)); double Py = (B10 + pow(Cy,2)); double Pz = (B10 + pow(Cz,2)); double Qx = (Cx*Dx + B00); double Qy = (Cy*Dy + B00); double Qz = (Cz*Dz + B00); I[0] += C[1]*W[a]*((Dx*Px + 2*B00*Cx)); I[1] += C[1]*W[a]*((Dy*Py + 2*B00*Cy)); I[2] += C[1]*W[a]*((Dz*Pz + 2*B00*Cz)); I[3] += C[1]*W[a]*(Cy*Cz*Dx); I[4] += C[1]*W[a]*(Cx*Cz*Dy); I[5] += C[0]*W[a]*(Cx*Cz); I[6] += C[0]*W[a]*(Cy*Cz); I[7] += C[1]*W[a]*(Cy*Qx); I[8] += C[1]*W[a]*(Cz*Qx); I[9] += C[1]*W[a]*(Dx*Pz); I[10] += C[1]*W[a]*(Dx*Py); I[11] += C[0]*W[a]*(Py); I[12] += C[1]*W[a]*(Dz*Py); I[13] += C[1]*W[a]*(Dz*Px); I[14] += C[1]*W[a]*(Cx*Cy*Dz); I[15] += C[0]*W[a]*(Cx*Cy); I[16] += C[1]*W[a]*(Cx*Qy); I[17] += C[1]*W[a]*(Cz*Qy); I[18] += C[0]*W[a]*(Pz); I[19] += C[1]*W[a]*(Dy*Pz); I[20] += C[1]*W[a]*(Dy*Px); I[21] += C[0]*W[a]*(Px); I[22] += C[1]*W[a]*(Cx*Qz); I[23] += C[1]*W[a]*(Cy*Qz); } #undef B00 #undef B10 #undef B01 #undef Cx #undef Cy #undef Cz #undef Dx #undef Dy #undef Dz #undef pow } static inline void reorder(double (&I)[24]) { double T[24]; for (int i = 0; i < 24; ++i) { T[i] = I[i]; } I[6] = T[0]; I[13] = T[1]; I[20] = T[2]; I[11] = T[3]; I[16] = T[4]; I[4] = T[5]; I[5] = T[6]; I[9] = T[7]; I[10] = T[8]; I[8] = T[9]; I[7] = T[10]; I[1] = T[11]; I[19] = T[12]; I[18] = T[13]; I[21] = T[14]; I[3] = T[15]; I[15] = T[16]; I[17] = T[17]; I[2] = T[18]; I[14] = T[19]; I[12] = T[20]; I[0] = T[21]; I[22] = T[22]; I[23] = T[23]; } }; template<> struct impl > { typedef void enable; static const bool value = true; static inline void eval(double A, double B, const Vector<3> &rAi, const Vector<3> &rBk, const Vector<3> &rAB, const Vector<3> &rij, const Vector<3> &rkl, const Vector<3> &t2, const Vector<3> &W, const double (&C)[2], double (&I)[72]) { #define pow(x,y) util::pow<(y)>::eval((x)) const int N = 3; double xij = rij[0]; double yij = rij[1]; double zij = rij[2]; // // double vB00[N] __attribute__ ((aligned(16))); // // // double vB10[N] __attribute__ ((aligned(16))); // // // // double vCx[N] __attribute__ ((aligned(16))); // double vCy[N] __attribute__ ((aligned(16))); // double vCz[N] __attribute__ ((aligned(16))); // // // double vDx[N] __attribute__ ((aligned(16))); // double vDy[N] __attribute__ ((aligned(16))); // double vDz[N] __attribute__ ((aligned(16))); // // for (int a = 0; a < N; ++a) { // // vB00[a] = 0.5*t2[a]; // // // vB10[a] = recurrence::coefficient(1.0/A, B, t2[a]); // // // // vCx[a] = recurrence::coefficient<0>(rAi, B, rAB, t2[a]); // vCy[a] = recurrence::coefficient<1>(rAi, B, rAB, t2[a]); // vCz[a] = recurrence::coefficient<2>(rAi, B, rAB, t2[a]); // // // vDx[a] = recurrence::coefficient<0>(rBk, -A, rAB, t2[a]); // vDy[a] = recurrence::coefficient<1>(rBk, -A, rAB, t2[a]); // vDz[a] = recurrence::coefficient<2>(rBk, -A, rAB, t2[a]); // // } // #define B00 vB00[a] // #define B10 vB10[a] // #define B01 vB01[a] // #define Cx vCx[a] // #define Cy vCy[a] // #define Cz vCz[a] // #define Dx vDx[a] // #define Dy vDy[a] // #define Dz vDz[a] #if defined (__INTEL_COMPILER) #pragma ivdep #pragma vector aligned #endif for (int a = 0; a < N; ++a) { double B00 = 0.5*t2[a]; double B10 = recurrence::coefficient(1.0/A, B, t2[a]); double Cx = recurrence::coefficient<0>(rAi, B, rAB, t2[a]); double Cy = recurrence::coefficient<1>(rAi, B, rAB, t2[a]); double Cz = recurrence::coefficient<2>(rAi, B, rAB, t2[a]); double Dx = recurrence::coefficient<0>(rBk, -A, rAB, t2[a]); double Dy = recurrence::coefficient<1>(rBk, -A, rAB, t2[a]); double Dz = recurrence::coefficient<2>(rBk, -A, rAB, t2[a]); double Ix = (Cx + xij); double Iy = (Cy + yij); double Iz = (Cz + zij); double Px = (B10 + pow(Cx,2)); double Py = (B10 + pow(Cy,2)); double Pz = (B10 + pow(Cz,2)); double Qx = (Cx*Dx + B00); double Qy = (Cy*Dy + B00); double Qz = (Cz*Dz + B00); double f1 = (B00*(yij + 2*Cy) + Dy*(Cy*Iy + B10)); double f10 = (Dy*Iy + B00); double f11 = (Cy*Iy + B10); double f12 = (B10*(3*Cx + xij) + Ix*pow(Cx,2)); double f14 = (Dx*Px + 2*B00*Cx); double f15 = (Dx*Ix + B00); double f22 = (Iz*pow(Cz,2) + B10*(3*Cz + zij)); double f3 = 3*B00*B10; double f4 = (Dy*Py + 2*B00*Cy); double f5 = (B10*(3*Cy + yij) + Iy*pow(Cy,2)); double f6 = (Dz*Pz + 2*B00*Cz); double f8 = (Dx*(Cx*Ix + B10) + B00*(xij + 2*Cx)); I[0] += C[1]*W[a]*((Dx*Ix*pow(Cx,2) + B00*Cx*(3*Cx + 2*xij) + B10*Dx*(3*Cx + xij) + f3)); I[1] += C[1]*W[a]*((Dy*Iy*pow(Cy,2) + f3 + B00*Cy*(3*Cy + 2*yij) + B10*Dy*(3*Cy + yij))); I[2] += C[1]*W[a]*((B00*Cz*(3*Cz + 2*zij) + Dz*Iz*pow(Cz,2) + B10*Dz*(3*Cz + zij) + f3)); I[3] += C[1]*W[a]*(Cx*(f6 + Qz*zij)); I[4] += C[1]*W[a]*(Cy*(f6 + Qz*zij)); I[5] += C[1]*W[a]*(Cx*Cy*(Dz*zij + Qz)); I[6] += C[1]*W[a]*(Cy*Dz*(Px + Cx*xij)); I[7] += C[1]*W[a]*(Qy*(Px + Cx*xij)); I[8] += C[1]*W[a]*(Qz*(Px + Cx*xij)); I[9] += C[1]*W[a]*(Cz*Dy*(Px + Cx*xij)); I[10] += C[1]*W[a]*(Cx*Dy*(Cz*zij + Pz)); I[11] += C[1]*W[a]*(Qy*(Cz*zij + Pz)); I[12] += C[1]*W[a]*(Qx*(Cz*zij + Pz)); I[13] += C[1]*W[a]*(Cy*Dx*(Cz*zij + Pz)); I[14] += C[1]*W[a]*(Dx*Iy*Pz); I[15] += C[1]*W[a]*(Cx*Cz*f10); I[16] += C[0]*W[a]*(Cx*Cz*Dy); I[17] += C[1]*W[a]*(Dy*Iz*Px); I[18] += C[1]*W[a]*(Px*(Dz*zij + Qz)); I[19] += C[1]*W[a]*(Py*(Dz*zij + Qz)); I[20] += C[1]*W[a]*(Dz*Ix*Py); I[21] += C[0]*W[a]*(Cx*Cy*Dz); I[22] += C[1]*W[a]*(Cx*Dz*f11); I[23] += C[1]*W[a]*(Cz*Dx*f11); I[24] += C[1]*W[a]*(Cy*Cz*f15); I[25] += C[0]*W[a]*(Cy*Cz*Dx); I[26] += C[1]*W[a]*(Dx*f5); I[27] += C[1]*W[a]*(Py*f15); I[28] += C[1]*W[a]*(Pz*f15); I[29] += C[1]*W[a]*(Dy*Ix*Pz); I[30] += C[0]*W[a]*(Dy*Pz); I[31] += C[1]*W[a]*(Dy*f12); I[32] += C[1]*W[a]*(Px*f10); I[33] += C[1]*W[a]*(Pz*f10); I[34] += C[0]*W[a]*(Dx*Pz); I[35] += C[1]*W[a]*(Dx*Iz*Py); I[36] += C[0]*W[a]*(Dx*Py); I[37] += C[1]*W[a]*(Dx*f22); I[38] += C[1]*W[a]*(Dy*f22); I[39] += C[0]*W[a]*(Dy*Px); I[40] += C[1]*W[a]*(Dz*Iy*Px); I[41] += C[0]*W[a]*(Dz*Px); I[42] += C[0]*W[a]*(Dz*Py); I[43] += C[1]*W[a]*(Dz*f12); I[44] += C[1]*W[a]*(Dz*f5); I[45] += C[1]*W[a]*(Cx*f1); I[46] += C[1]*W[a]*(Cz*f1); I[47] += C[1]*W[a]*(Cz*Ix*Qy); I[48] += C[0]*W[a]*(Cz*Qy); I[49] += C[1]*W[a]*(Cx*Iz*Qy); I[50] += C[0]*W[a]*(Cx*Qy); I[51] += C[1]*W[a]*(Cx*Iy*Qz); I[52] += C[0]*W[a]*(Cx*Qz); I[53] += C[1]*W[a]*(Cy*Ix*Qz); I[54] += C[0]*W[a]*(Cy*Qz); I[55] += C[1]*W[a]*(Cy*f8); I[56] += C[1]*W[a]*(Cz*f8); I[57] += C[1]*W[a]*(Cz*Iy*Qx); I[58] += C[0]*W[a]*(Cz*Qx); I[59] += C[1]*W[a]*(Cy*Iz*Qx); I[60] += C[0]*W[a]*(Cy*Qx); I[61] += C[1]*W[a]*(Qx*f11); I[62] += C[1]*W[a]*(Qz*f11); I[63] += C[1]*W[a]*(Iy*f6); I[64] += C[1]*W[a]*(Ix*f6); I[65] += C[1]*W[a]*(Ix*f4); I[66] += C[1]*W[a]*(Iz*f4); I[67] += C[1]*W[a]*(Iz*f14); I[68] += C[1]*W[a]*(Iy*f14); I[69] += C[0]*W[a]*(f14); I[70] += C[0]*W[a]*(f4); I[71] += C[0]*W[a]*(f6); } #undef B00 #undef B10 #undef B01 #undef Cx #undef Cy #undef Cz #undef Dx #undef Dy #undef Dz #undef pow } static inline void reorder(double (&I)[72]) { double T[72]; for (int i = 0; i < 72; ++i) { T[i] = I[i]; } I[6] = T[0]; I[37] = T[1]; I[68] = T[2]; I[70] = T[3]; I[71] = T[4]; I[69] = T[5]; I[57] = T[6]; I[33] = T[7]; I[58] = T[8]; I[34] = T[9]; I[46] = T[10]; I[47] = T[11]; I[22] = T[12]; I[23] = T[13]; I[14] = T[14]; I[40] = T[15]; I[28] = T[16]; I[42] = T[17]; I[66] = T[18]; I[67] = T[19]; I[55] = T[20]; I[51] = T[21]; I[63] = T[22]; I[17] = T[23]; I[11] = T[24]; I[5] = T[25]; I[13] = T[26]; I[7] = T[27]; I[8] = T[28]; I[32] = T[29]; I[26] = T[30]; I[30] = T[31]; I[36] = T[32]; I[38] = T[33]; I[2] = T[34]; I[19] = T[35]; I[1] = T[36]; I[20] = T[37]; I[44] = T[38]; I[24] = T[39]; I[60] = T[40]; I[48] = T[41]; I[49] = T[42]; I[54] = T[43]; I[61] = T[44]; I[39] = T[45]; I[41] = T[46]; I[35] = T[47]; I[29] = T[48]; I[45] = T[49]; I[27] = T[50]; I[64] = T[51]; I[52] = T[52]; I[59] = T[53]; I[53] = T[54]; I[9] = T[55]; I[10] = T[56]; I[16] = T[57]; I[4] = T[58]; I[21] = T[59]; I[3] = T[60]; I[15] = T[61]; I[65] = T[62]; I[62] = T[63]; I[56] = T[64]; I[31] = T[65]; I[43] = T[66]; I[18] = T[67]; I[12] = T[68]; I[0] = T[69]; I[25] = T[70]; I[50] = T[71]; } }; template<> struct impl > { typedef void enable; static const bool value = true; static inline void eval(double A, double B, const Vector<3> &rAi, const Vector<3> &rBk, const Vector<3> &rAB, const Vector<3> &rij, const Vector<3> &rkl, const Vector<3> &t2, const Vector<3> &W, const double (&C)[1], double (&I)[36]) { #define pow(x,y) util::pow<(y)>::eval((x)) const int N = 3; // // double vB00[N] __attribute__ ((aligned(16))); // // // double vB10[N] __attribute__ ((aligned(16))); // // // double vB01[N] __attribute__ ((aligned(16))); // // // double vCx[N] __attribute__ ((aligned(16))); // double vCy[N] __attribute__ ((aligned(16))); // double vCz[N] __attribute__ ((aligned(16))); // // // double vDx[N] __attribute__ ((aligned(16))); // double vDy[N] __attribute__ ((aligned(16))); // double vDz[N] __attribute__ ((aligned(16))); // // for (int a = 0; a < N; ++a) { // // vB00[a] = 0.5*t2[a]; // // // vB10[a] = recurrence::coefficient(1.0/A, B, t2[a]); // // // vB01[a] = recurrence::coefficient(1.0/B, A, t2[a]); // // // vCx[a] = recurrence::coefficient<0>(rAi, B, rAB, t2[a]); // vCy[a] = recurrence::coefficient<1>(rAi, B, rAB, t2[a]); // vCz[a] = recurrence::coefficient<2>(rAi, B, rAB, t2[a]); // // // vDx[a] = recurrence::coefficient<0>(rBk, -A, rAB, t2[a]); // vDy[a] = recurrence::coefficient<1>(rBk, -A, rAB, t2[a]); // vDz[a] = recurrence::coefficient<2>(rBk, -A, rAB, t2[a]); // // } // #define B00 vB00[a] // #define B10 vB10[a] // #define B01 vB01[a] // #define Cx vCx[a] // #define Cy vCy[a] // #define Cz vCz[a] // #define Dx vDx[a] // #define Dy vDy[a] // #define Dz vDz[a] #if defined (__INTEL_COMPILER) #pragma ivdep #pragma vector aligned #endif for (int a = 0; a < N; ++a) { double B00 = 0.5*t2[a]; double B10 = recurrence::coefficient(1.0/A, B, t2[a]); double B01 = recurrence::coefficient(1.0/B, A, t2[a]); double Cx = recurrence::coefficient<0>(rAi, B, rAB, t2[a]); double Cy = recurrence::coefficient<1>(rAi, B, rAB, t2[a]); double Cz = recurrence::coefficient<2>(rAi, B, rAB, t2[a]); double Dx = recurrence::coefficient<0>(rBk, -A, rAB, t2[a]); double Dy = recurrence::coefficient<1>(rBk, -A, rAB, t2[a]); double Dz = recurrence::coefficient<2>(rBk, -A, rAB, t2[a]); double Px = (B10 + pow(Cx,2)); double Py = (B10 + pow(Cy,2)); double Pz = (B10 + pow(Cz,2)); double Qx = (Cx*Dx + B00); double Qy = (Cy*Dy + B00); double Qz = (Cz*Dz + B00); double Rx = (B01 + pow(Dx,2)); double Ry = (B01 + pow(Dy,2)); double Rz = (pow(Dz,2) + B01); double f0 = (Dz*Pz + 2*B00*Cz); double f1 = (Dy*Py + 2*B00*Cy); double f13 = 2*pow(B00,2); double f15 = (2*B00*Dy + Cy*Ry); double f3 = (2*B00*Dz + Cz*Rz); double f7 = B01*B10; double f8 = (2*B00*Dx + Cx*Rx); double f9 = (Dx*Px + 2*B00*Cx); I[0] += C[0]*W[a]*((4*B00*Cy*Dy + f13 + B01*pow(Cy,2) + f7 + Py*pow(Dy,2))); I[1] += C[0]*W[a]*((f13 + B01*pow(Cz,2) + Pz*pow(Dz,2) + f7 + 4*B00*Cz*Dz)); I[2] += C[0]*W[a]*((B01*pow(Cx,2) + f13 + Px*pow(Dx,2) + 4*B00*Cx*Dx + f7)); I[3] += C[0]*W[a]*(Cx*Cy*Rz); I[4] += C[0]*W[a]*(Cz*Dy*Qx); I[5] += C[0]*W[a]*(Cz*Dx*Qy); I[6] += C[0]*W[a]*(Dx*Dz*Py); I[7] += C[0]*W[a]*(Cy*Dz*Qx); I[8] += C[0]*W[a]*(Cy*Dx*Qz); I[9] += C[0]*W[a]*(Dx*Dy*Pz); I[10] += C[0]*W[a]*(Dy*Dz*Px); I[11] += C[0]*W[a]*(Cx*Dz*Qy); I[12] += C[0]*W[a]*(Cx*Dy*Qz); I[13] += C[0]*W[a]*(Cx*Cz*Ry); I[14] += C[0]*W[a]*(Cy*Cz*Rx); I[15] += C[0]*W[a]*(Py*Rx); I[16] += C[0]*W[a]*(Pz*Rx); I[17] += C[0]*W[a]*(Pz*Ry); I[18] += C[0]*W[a]*(Px*Ry); I[19] += C[0]*W[a]*(Px*Rz); I[20] += C[0]*W[a]*(Py*Rz); I[21] += C[0]*W[a]*(Cy*f8); I[22] += C[0]*W[a]*(Cz*f8); I[23] += C[0]*W[a]*(Cz*f15); I[24] += C[0]*W[a]*(Cx*f15); I[25] += C[0]*W[a]*(Cx*f3); I[26] += C[0]*W[a]*(Cy*f3); I[27] += C[0]*W[a]*(Dx*f0); I[28] += C[0]*W[a]*(Dx*f1); I[29] += C[0]*W[a]*(Dz*f1); I[30] += C[0]*W[a]*(Dz*f9); I[31] += C[0]*W[a]*(Dy*f9); I[32] += C[0]*W[a]*(Dy*f0); I[33] += C[0]*W[a]*(Qx*Qz); I[34] += C[0]*W[a]*(Qx*Qy); I[35] += C[0]*W[a]*(Qy*Qz); } #undef B00 #undef B10 #undef B01 #undef Cx #undef Cy #undef Cz #undef Dx #undef Dy #undef Dz #undef pow } static inline void reorder(double (&I)[36]) { double T[36]; for (int i = 0; i < 36; ++i) { T[i] = I[i]; } I[7] = T[0]; I[14] = T[1]; I[0] = T[2]; I[15] = T[3]; I[22] = T[4]; I[23] = T[5]; I[25] = T[6]; I[27] = T[7]; I[29] = T[8]; I[20] = T[9]; I[30] = T[10]; I[33] = T[11]; I[34] = T[12]; I[10] = T[13]; I[5] = T[14]; I[1] = T[15]; I[2] = T[16]; I[8] = T[17]; I[6] = T[18]; I[12] = T[19]; I[13] = T[20]; I[3] = T[21]; I[4] = T[22]; I[11] = T[23]; I[9] = T[24]; I[16] = T[25]; I[17] = T[26]; I[26] = T[27]; I[19] = T[28]; I[31] = T[29]; I[24] = T[30]; I[18] = T[31]; I[32] = T[32]; I[28] = T[33]; I[21] = T[34]; I[35] = T[35]; } }; template<> struct impl > { typedef void enable; static const bool value = true; static inline void eval(double A, double B, const Vector<3> &rAi, const Vector<3> &rBk, const Vector<3> &rAB, const Vector<3> &rij, const Vector<3> &rkl, const Vector<2> &t2, const Vector<2> &W, const double (&C)[2], double (&I)[12]) { #define pow(x,y) util::pow<(y)>::eval((x)) const int N = 2; double xij = rij[0]; double yij = rij[1]; double zij = rij[2]; // // // double vB10[N] __attribute__ ((aligned(16))); // // // // double vCx[N] __attribute__ ((aligned(16))); // double vCy[N] __attribute__ ((aligned(16))); // double vCz[N] __attribute__ ((aligned(16))); // // // for (int a = 0; a < N; ++a) { // // // vB10[a] = recurrence::coefficient(1.0/A, B, t2[a]); // // // // vCx[a] = recurrence::coefficient<0>(rAi, B, rAB, t2[a]); // vCy[a] = recurrence::coefficient<1>(rAi, B, rAB, t2[a]); // vCz[a] = recurrence::coefficient<2>(rAi, B, rAB, t2[a]); // // // } // #define B00 vB00[a] // #define B10 vB10[a] // #define B01 vB01[a] // #define Cx vCx[a] // #define Cy vCy[a] // #define Cz vCz[a] // #define Dx vDx[a] // #define Dy vDy[a] // #define Dz vDz[a] #if defined (__INTEL_COMPILER) #pragma ivdep #pragma vector aligned #endif for (int a = 0; a < N; ++a) { double B10 = recurrence::coefficient(1.0/A, B, t2[a]); double Cx = recurrence::coefficient<0>(rAi, B, rAB, t2[a]); double Cy = recurrence::coefficient<1>(rAi, B, rAB, t2[a]); double Cz = recurrence::coefficient<2>(rAi, B, rAB, t2[a]); double Ix = (Cx + xij); double Iy = (Cy + yij); double Iz = (Cz + zij); I[0] += C[1]*W[a]*((Cx*Ix + B10)); I[1] += C[1]*W[a]*((Cy*Iy + B10)); I[2] += C[1]*W[a]*((B10 + Cz*Iz)); I[3] += C[1]*W[a]*(Cz*Ix); I[4] += C[1]*W[a]*(Cz*Iy); I[5] += C[1]*W[a]*(Cx*Iy); I[6] += C[1]*W[a]*(Cx*Iz); I[7] += C[1]*W[a]*(Cy*Iz); I[8] += C[1]*W[a]*(Cy*Ix); I[9] += C[0]*W[a]*(Ix); I[10] += C[0]*W[a]*(Iy); I[11] += C[0]*W[a]*(Iz); } #undef B00 #undef B10 #undef B01 #undef Cx #undef Cy #undef Cz #undef Dx #undef Dy #undef Dz #undef pow } static inline void reorder(double (&I)[12]) { double T[12]; for (int i = 0; i < 12; ++i) { T[i] = I[i]; } I[1] = T[0]; I[6] = T[1]; I[11] = T[2]; I[3] = T[3]; I[7] = T[4]; I[5] = T[5]; I[9] = T[6]; I[10] = T[7]; I[2] = T[8]; I[0] = T[9]; I[4] = T[10]; I[8] = T[11]; } }; template<> struct impl > { typedef void enable; static const bool value = true; static inline void eval(double A, double B, const Vector<3> &rAi, const Vector<3> &rBk, const Vector<3> &rAB, const Vector<3> &rij, const Vector<3> &rkl, const Vector<3> &t2, const Vector<3> &W, const double (&C)[2], double (&I)[144]) { #define pow(x,y) util::pow<(y)>::eval((x)) const int N = 3; double xij = rij[0]; double yij = rij[1]; double zij = rij[2]; // // double vB00[N] __attribute__ ((aligned(16))); // // // double vB10[N] __attribute__ ((aligned(16))); // // // double vB01[N] __attribute__ ((aligned(16))); // // // double vCx[N] __attribute__ ((aligned(16))); // double vCy[N] __attribute__ ((aligned(16))); // double vCz[N] __attribute__ ((aligned(16))); // // // double vDx[N] __attribute__ ((aligned(16))); // double vDy[N] __attribute__ ((aligned(16))); // double vDz[N] __attribute__ ((aligned(16))); // // for (int a = 0; a < N; ++a) { // // vB00[a] = 0.5*t2[a]; // // // vB10[a] = recurrence::coefficient(1.0/A, B, t2[a]); // // // vB01[a] = recurrence::coefficient(1.0/B, A, t2[a]); // // // vCx[a] = recurrence::coefficient<0>(rAi, B, rAB, t2[a]); // vCy[a] = recurrence::coefficient<1>(rAi, B, rAB, t2[a]); // vCz[a] = recurrence::coefficient<2>(rAi, B, rAB, t2[a]); // // // vDx[a] = recurrence::coefficient<0>(rBk, -A, rAB, t2[a]); // vDy[a] = recurrence::coefficient<1>(rBk, -A, rAB, t2[a]); // vDz[a] = recurrence::coefficient<2>(rBk, -A, rAB, t2[a]); // // } // #define B00 vB00[a] // #define B10 vB10[a] // #define B01 vB01[a] // #define Cx vCx[a] // #define Cy vCy[a] // #define Cz vCz[a] // #define Dx vDx[a] // #define Dy vDy[a] // #define Dz vDz[a] #if defined (__INTEL_COMPILER) #pragma ivdep #pragma vector aligned #endif for (int a = 0; a < N; ++a) { double B00 = 0.5*t2[a]; double B10 = recurrence::coefficient(1.0/A, B, t2[a]); double B01 = recurrence::coefficient(1.0/B, A, t2[a]); double Cx = recurrence::coefficient<0>(rAi, B, rAB, t2[a]); double Cy = recurrence::coefficient<1>(rAi, B, rAB, t2[a]); double Cz = recurrence::coefficient<2>(rAi, B, rAB, t2[a]); double Dx = recurrence::coefficient<0>(rBk, -A, rAB, t2[a]); double Dy = recurrence::coefficient<1>(rBk, -A, rAB, t2[a]); double Dz = recurrence::coefficient<2>(rBk, -A, rAB, t2[a]); double Ix = (Cx + xij); double Iy = (Cy + yij); double Iz = (Cz + zij); double Px = (B10 + pow(Cx,2)); double Py = (B10 + pow(Cy,2)); double Pz = (B10 + pow(Cz,2)); double Qx = (Cx*Dx + B00); double Qy = (Cy*Dy + B00); double Qz = (Cz*Dz + B00); double Rx = (B01 + pow(Dx,2)); double Ry = (B01 + pow(Dy,2)); double Rz = (pow(Dz,2) + B01); double f1 = (Dz*Pz + 2*B00*Cz); double f14 = (2*B00*Dx + Ix*Rx); double f16 = (2*B00*Cy*yij + 3*B00*Py + Dy*(B10*(3*Cy + yij) + Iy*pow(Cy,2))); double f2 = (4*B00*Cy*Dy + Py*Ry + 2*pow(B00,2)); double f21 = (Cy*Iy + B10); double f22 = (B10*(3*Cx + xij) + Ix*pow(Cx,2)); double f23 = (2*B00*Dx + Cx*Rx); double f24 = (B00*(yij + 2*Cy) + Dy*(Cy*Iy + B10)); double f28 = (2*B00*Dy + Iy*Ry); double f29 = (Dx*(B10*(3*Cx + xij) + Ix*pow(Cx,2)) + 2*B00*Cx*xij + 3*B00*Px); double f3 = B01*B10; double f30 = (Iz*Rz + 2*B00*Dz); double f31 = (B10*(3*Cy + yij) + Iy*pow(Cy,2)); double f32 = (Dy*Py + 2*B00*Cy); double f33 = (2*B00*Dz + Cz*Rz); double f36 = 2*pow(B00,2); double f4 = (Dx*Px + 2*B00*Cx); double f40 = (Iz*pow(Cz,2) + B10*(3*Cz + zij)); double f42 = (2*B00*Dy + Cy*Ry); double f7 = (Dz*(Iz*pow(Cz,2) + B10*(3*Cz + zij)) + 3*B00*Pz + 2*B00*Cz*zij); double f8 = (B00 + Dz*Iz); I[0] += C[1]*W[a]*(Cz*(f36 + 2*B00*Dx*(xij + 2*Cx) + B01*Cx*Ix + pow(Dx,2)*(Cx*Ix + B10) + f3)); I[1] += C[1]*W[a]*(Cx*(yij*(2*B00*Dy + Cy*Ry) + f2)); I[2] += C[1]*W[a]*(Cz*(yij*(2*B00*Dy + Cy*Ry) + f2)); I[3] += C[1]*W[a]*((B01*Iy*pow(Cy,2) + 4*B00*Cy*Dy*yij + 6*B00*Dy*Py + yij*(f36 + f3 + Py*pow(Dy,2)) + Cy*(3*f36 + 3*f3 + pow(Dy,2)*(3*B10 + pow(Cy,2))))); I[4] += C[1]*W[a]*(Cy*(f36 + pow(Dz,2)*(B10 + Cz*Iz) + 2*B00*Dz*(2*Cz + zij) + f3 + B01*Cz*Iz)); I[5] += C[1]*W[a]*(Cx*(f36 + pow(Dz,2)*(B10 + Cz*Iz) + 2*B00*Dz*(2*Cz + zij) + f3 + B01*Cz*Iz)); I[6] += C[1]*W[a]*((6*B00*Dz*Pz + B01*Iz*pow(Cz,2) + Cz*(3*f36 + 3*f3 + pow(Dz,2)*(3*B10 + pow(Cz,2))) + zij*(f36 + Pz*pow(Dz,2) + f3) + 4*B00*Cz*Dz*zij)); I[7] += C[1]*W[a]*(Iy*(f36 + B01*pow(Cz,2) + Pz*pow(Dz,2) + f3 + 4*B00*Cz*Dz)); I[8] += C[1]*W[a]*(Ix*(f36 + B01*pow(Cz,2) + Pz*pow(Dz,2) + f3 + 4*B00*Cz*Dz)); I[9] += C[0]*W[a]*((f36 + B01*pow(Cz,2) + Pz*pow(Dz,2) + f3 + 4*B00*Cz*Dz)); I[10] += C[1]*W[a]*(Iz*(B01*pow(Cx,2) + f36 + Px*pow(Dx,2) + 4*B00*Cx*Dx + f3)); I[11] += C[1]*W[a]*(Iy*(B01*pow(Cx,2) + f36 + Px*pow(Dx,2) + 4*B00*Cx*Dx + f3)); I[12] += C[0]*W[a]*((B01*pow(Cx,2) + f36 + Px*pow(Dx,2) + 4*B00*Cx*Dx + f3)); I[13] += C[1]*W[a]*((B01*Ix*pow(Cx,2) + 6*B00*Dx*Px + Cx*(3*f36 + 3*f3 + pow(Dx,2)*(3*B10 + pow(Cx,2))) + 4*B00*Cx*Dx*xij + xij*(f36 + Px*pow(Dx,2) + f3))); I[14] += C[1]*W[a]*(Cy*(f36 + 2*B00*Dx*(xij + 2*Cx) + B01*Cx*Ix + pow(Dx,2)*(Cx*Ix + B10) + f3)); I[15] += C[1]*W[a]*(Cy*Dz*(Qx*xij + f4)); I[16] += C[1]*W[a]*(Qy*(Qx*xij + f4)); I[17] += C[1]*W[a]*(Qz*(Qx*xij + f4)); I[18] += C[1]*W[a]*(Cz*Dy*(Qx*xij + f4)); I[19] += C[1]*W[a]*(Cx*Dy*(f1 + Qz*zij)); I[20] += C[1]*W[a]*(Cy*Dx*(f1 + Qz*zij)); I[21] += C[1]*W[a]*(Qx*(f1 + Qz*zij)); I[22] += C[1]*W[a]*(Qy*(f1 + Qz*zij)); I[23] += C[1]*W[a]*(Cz*Qx*(Dy*yij + Qy)); I[24] += C[1]*W[a]*(Dx*Qy*(Cz*zij + Pz)); I[25] += C[1]*W[a]*(Dz*Py*(Dx*xij + Qx)); I[26] += C[1]*W[a]*(Cy*Qz*(Dx*xij + Qx)); I[27] += C[1]*W[a]*(Cy*Rz*(Px + Cx*xij)); I[28] += C[1]*W[a]*(Dz*Qy*(Px + Cx*xij)); I[29] += C[1]*W[a]*(Dz*Px*(Dy*yij + Qy)); I[30] += C[1]*W[a]*(Cx*Qz*(Dy*yij + Qy)); I[31] += C[1]*W[a]*(f4*(Dy*yij + Qy)); I[32] += C[1]*W[a]*(f1*(Dy*yij + Qy)); I[33] += C[1]*W[a]*(Dx*Pz*(Dy*yij + Qy)); I[34] += C[1]*W[a]*(Dy*Pz*(Dx*xij + Qx)); I[35] += C[1]*W[a]*(f1*(Dx*xij + Qx)); I[36] += C[1]*W[a]*(f32*(Dx*xij + Qx)); I[37] += C[1]*W[a]*(Cz*Qy*(Dx*xij + Qx)); I[38] += C[0]*W[a]*(Cz*Dx*Qy); I[39] += C[1]*W[a]*(Cz*Dx*f24); I[40] += C[0]*W[a]*(Dx*Dy*Pz); I[41] += C[1]*W[a]*(Dx*Dy*f40); I[42] += C[1]*W[a]*(Dx*Dz*f31); I[43] += C[0]*W[a]*(Dx*Dz*Py); I[44] += C[1]*W[a]*(Dx*Py*f8); I[45] += C[1]*W[a]*(Dx*Qz*f21); I[46] += C[0]*W[a]*(Cy*Dx*Qz); I[47] += C[1]*W[a]*(Cy*Ix*f33); I[48] += C[1]*W[a]*(Cx*Cy*f30); I[49] += C[0]*W[a]*(Cx*Cy*Rz); I[50] += C[1]*W[a]*(Cx*Rz*f21); I[51] += C[1]*W[a]*(Dz*Qx*f21); I[52] += C[0]*W[a]*(Cy*Dz*Qx); I[53] += C[1]*W[a]*(Cy*Qx*f8); I[54] += C[0]*W[a]*(Cz*Dy*Qx); I[55] += C[1]*W[a]*(Dy*Qx*(Cz*zij + Pz)); I[56] += C[1]*W[a]*(Cx*Ry*(Cz*zij + Pz)); I[57] += C[1]*W[a]*(Cz*Ry*(Px + Cx*xij)); I[58] += C[1]*W[a]*(Dy*Qz*(Px + Cx*xij)); I[59] += C[0]*W[a]*(Cx*Dy*Qz); I[60] += C[1]*W[a]*(Dy*Dz*f22); I[61] += C[0]*W[a]*(Dy*Dz*Px); I[62] += C[1]*W[a]*(Dy*Px*f8); I[63] += C[1]*W[a]*(f33*(Px + Cx*xij)); I[64] += C[1]*W[a]*(f42*(Px + Cx*xij)); I[65] += C[1]*W[a]*(Cx*Iz*f42); I[66] += C[1]*W[a]*(Cx*Dz*f24); I[67] += C[0]*W[a]*(Cx*Dz*Qy); I[68] += C[1]*W[a]*(Cx*Qy*f8); I[69] += C[1]*W[a]*(Cx*Cz*f28); I[70] += C[0]*W[a]*(Cx*Cz*Ry); I[71] += C[1]*W[a]*(Cz*Rx*f21); I[72] += C[1]*W[a]*(Cy*Rx*(Cz*zij + Pz)); I[73] += C[1]*W[a]*(f42*(Cz*zij + Pz)); I[74] += C[1]*W[a]*(f23*(Cz*zij + Pz)); I[75] += C[1]*W[a]*(Cz*Iy*f23); I[76] += C[1]*W[a]*(Cy*Cz*f14); I[77] += C[0]*W[a]*(Cy*Cz*Rx); I[78] += C[1]*W[a]*(Cy*Iz*f23); I[79] += C[0]*W[a]*(Cy*f23); I[80] += C[1]*W[a]*(f21*f23); I[81] += C[0]*W[a]*(Cz*f23); I[82] += C[1]*W[a]*(Cz*Ix*f42); I[83] += C[0]*W[a]*(Cz*f42); I[84] += C[0]*W[a]*(Cx*f42); I[85] += C[1]*W[a]*(Cx*Iy*f33); I[86] += C[0]*W[a]*(Cx*f33); I[87] += C[0]*W[a]*(Cy*f33); I[88] += C[1]*W[a]*(f21*f33); I[89] += C[1]*W[a]*(Rz*f31); I[90] += C[1]*W[a]*(Rx*f31); I[91] += C[1]*W[a]*(Rx*f40); I[92] += C[1]*W[a]*(Ry*f40); I[93] += C[1]*W[a]*(Ry*f22); I[94] += C[1]*W[a]*(Rz*f22); I[95] += C[1]*W[a]*(Ix*Py*Rz); I[96] += C[0]*W[a]*(Py*Rz); I[97] += C[1]*W[a]*(Iy*Px*Rz); I[98] += C[0]*W[a]*(Px*Rz); I[99] += C[1]*W[a]*(Px*f28); I[100] += C[1]*W[a]*(Pz*f28); I[101] += C[1]*W[a]*(Pz*f14); I[102] += C[1]*W[a]*(Py*f14); I[103] += C[1]*W[a]*(Iz*Py*Rx); I[104] += C[0]*W[a]*(Py*Rx); I[105] += C[1]*W[a]*(Iy*Pz*Rx); I[106] += C[0]*W[a]*(Pz*Rx); I[107] += C[1]*W[a]*(Ix*Pz*Ry); I[108] += C[0]*W[a]*(Pz*Ry); I[109] += C[1]*W[a]*(Iz*Px*Ry); I[110] += C[0]*W[a]*(Px*Ry); I[111] += C[1]*W[a]*(Px*f30); I[112] += C[1]*W[a]*(Py*f30); I[113] += C[1]*W[a]*(Dy*Ix*f1); I[114] += C[0]*W[a]*(Dy*f1); I[115] += C[1]*W[a]*(Dz*Ix*f32); I[116] += C[0]*W[a]*(Dz*f32); I[117] += C[1]*W[a]*(Dz*f16); I[118] += C[1]*W[a]*(Ix*Qy*Qz); I[119] += C[0]*W[a]*(Qy*Qz); I[120] += C[1]*W[a]*(Iy*Qx*Qz); I[121] += C[0]*W[a]*(Qx*Qz); I[122] += C[1]*W[a]*(Iz*Qx*Qy); I[123] += C[0]*W[a]*(Qx*Qy); I[124] += C[1]*W[a]*(Qx*f24); I[125] += C[1]*W[a]*(Qz*f24); I[126] += C[1]*W[a]*(Dx*f7); I[127] += C[1]*W[a]*(Dx*Iy*f1); I[128] += C[0]*W[a]*(Dx*f1); I[129] += C[1]*W[a]*(Dx*f16); I[130] += C[1]*W[a]*(Dx*Iz*f32); I[131] += C[0]*W[a]*(Dx*f32); I[132] += C[1]*W[a]*(f32*f8); I[133] += C[1]*W[a]*(f4*f8); I[134] += C[1]*W[a]*(Dz*Iy*f4); I[135] += C[0]*W[a]*(Dz*f4); I[136] += C[1]*W[a]*(Dz*f29); I[137] += C[1]*W[a]*(Dy*f29); I[138] += C[1]*W[a]*(Dy*Iz*f4); I[139] += C[0]*W[a]*(Dy*f4); I[140] += C[1]*W[a]*(Dy*f7); I[141] += C[1]*W[a]*(Iz*f2); I[142] += C[1]*W[a]*(Ix*f2); I[143] += C[0]*W[a]*(f2); } #undef B00 #undef B10 #undef B01 #undef Cx #undef Cy #undef Cz #undef Dx #undef Dy #undef Dz #undef pow } static inline void reorder(double (&I)[144]) { double T[144]; for (int i = 0; i < 144; ++i) { T[i] = I[i]; } I[10] = T[0]; I[39] = T[1]; I[41] = T[2]; I[37] = T[3]; I[71] = T[4]; I[70] = T[5]; I[68] = T[6]; I[62] = T[7]; I[56] = T[8]; I[50] = T[9]; I[18] = T[10]; I[12] = T[11]; I[0] = T[12]; I[6] = T[13]; I[9] = T[14]; I[105] = T[15]; I[81] = T[16]; I[106] = T[17]; I[82] = T[18]; I[142] = T[19]; I[119] = T[20]; I[118] = T[21]; I[143] = T[22]; I[88] = T[23]; I[95] = T[24]; I[103] = T[25]; I[107] = T[26]; I[57] = T[27]; I[129] = T[28]; I[132] = T[29]; I[136] = T[30]; I[84] = T[31]; I[134] = T[32]; I[86] = T[33]; I[80] = T[34]; I[104] = T[35]; I[79] = T[36]; I[83] = T[37]; I[77] = T[38]; I[89] = T[39]; I[74] = T[40]; I[92] = T[41]; I[109] = T[42]; I[97] = T[43]; I[115] = T[44]; I[113] = T[45]; I[101] = T[46]; I[59] = T[47]; I[69] = T[48]; I[51] = T[49]; I[63] = T[50]; I[111] = T[51]; I[99] = T[52]; I[117] = T[53]; I[76] = T[54]; I[94] = T[55]; I[46] = T[56]; I[34] = T[57]; I[130] = T[58]; I[124] = T[59]; I[126] = T[60]; I[120] = T[61]; I[138] = T[62]; I[58] = T[63]; I[33] = T[64]; I[45] = T[65]; I[135] = T[66]; I[123] = T[67]; I[141] = T[68]; I[40] = T[69]; I[28] = T[70]; I[17] = T[71]; I[23] = T[72]; I[47] = T[73]; I[22] = T[74]; I[16] = T[75]; I[11] = T[76]; I[5] = T[77]; I[21] = T[78]; I[3] = T[79]; I[15] = T[80]; I[4] = T[81]; I[35] = T[82]; I[29] = T[83]; I[27] = T[84]; I[64] = T[85]; I[52] = T[86]; I[53] = T[87]; I[65] = T[88]; I[61] = T[89]; I[13] = T[90]; I[20] = T[91]; I[44] = T[92]; I[30] = T[93]; I[54] = T[94]; I[55] = T[95]; I[49] = T[96]; I[60] = T[97]; I[48] = T[98]; I[36] = T[99]; I[38] = T[100]; I[8] = T[101]; I[7] = T[102]; I[19] = T[103]; I[1] = T[104]; I[14] = T[105]; I[2] = T[106]; I[32] = T[107]; I[26] = T[108]; I[42] = T[109]; I[24] = T[110]; I[66] = T[111]; I[67] = T[112]; I[128] = T[113]; I[122] = T[114]; I[127] = T[115]; I[121] = T[116]; I[133] = T[117]; I[131] = T[118]; I[125] = T[119]; I[112] = T[120]; I[100] = T[121]; I[93] = T[122]; I[75] = T[123]; I[87] = T[124]; I[137] = T[125]; I[116] = T[126]; I[110] = T[127]; I[98] = T[128]; I[85] = T[129]; I[91] = T[130]; I[73] = T[131]; I[139] = T[132]; I[114] = T[133]; I[108] = T[134]; I[96] = T[135]; I[102] = T[136]; I[78] = T[137]; I[90] = T[138]; I[72] = T[139]; I[140] = T[140]; I[43] = T[141]; I[31] = T[142]; I[25] = T[143]; } }; template<> struct impl > { typedef void enable; static const bool value = true; static inline void eval(double A, double B, const Vector<3> &rAi, const Vector<3> &rBk, const Vector<3> &rAB, const Vector<3> &rij, const Vector<3> &rkl, const Vector<2> &t2, const Vector<2> &W, const double (&C)[1], double (&I)[9]) { #define pow(x,y) util::pow<(y)>::eval((x)) const int N = 2; double xij = rij[0]; double yij = rij[1]; double zij = rij[2]; // // // double vB10[N] __attribute__ ((aligned(16))); // // // // double vCx[N] __attribute__ ((aligned(16))); // double vCy[N] __attribute__ ((aligned(16))); // double vCz[N] __attribute__ ((aligned(16))); // // // for (int a = 0; a < N; ++a) { // // // vB10[a] = recurrence::coefficient(1.0/A, B, t2[a]); // // // // vCx[a] = recurrence::coefficient<0>(rAi, B, rAB, t2[a]); // vCy[a] = recurrence::coefficient<1>(rAi, B, rAB, t2[a]); // vCz[a] = recurrence::coefficient<2>(rAi, B, rAB, t2[a]); // // // } // #define B00 vB00[a] // #define B10 vB10[a] // #define B01 vB01[a] // #define Cx vCx[a] // #define Cy vCy[a] // #define Cz vCz[a] // #define Dx vDx[a] // #define Dy vDy[a] // #define Dz vDz[a] #if defined (__INTEL_COMPILER) #pragma ivdep #pragma vector aligned #endif for (int a = 0; a < N; ++a) { double B10 = recurrence::coefficient(1.0/A, B, t2[a]); double Cx = recurrence::coefficient<0>(rAi, B, rAB, t2[a]); double Cy = recurrence::coefficient<1>(rAi, B, rAB, t2[a]); double Cz = recurrence::coefficient<2>(rAi, B, rAB, t2[a]); double Ix = (Cx + xij); double Iy = (Cy + yij); double Iz = (Cz + zij); I[0] += C[0]*W[a]*((Cx*Ix + B10)); I[1] += C[0]*W[a]*((B10 + Cz*Iz)); I[2] += C[0]*W[a]*((Cy*Iy + B10)); I[3] += C[0]*W[a]*(Cy*Ix); I[4] += C[0]*W[a]*(Cz*Ix); I[5] += C[0]*W[a]*(Cz*Iy); I[6] += C[0]*W[a]*(Cx*Iy); I[7] += C[0]*W[a]*(Cx*Iz); I[8] += C[0]*W[a]*(Cy*Iz); } #undef B00 #undef B10 #undef B01 #undef Cx #undef Cy #undef Cz #undef Dx #undef Dy #undef Dz #undef pow } static inline void reorder(double (&I)[9]) { double T[9]; for (int i = 0; i < 9; ++i) { T[i] = I[i]; } I[0] = T[0]; I[8] = T[1]; I[4] = T[2]; I[1] = T[3]; I[2] = T[4]; I[5] = T[5]; I[3] = T[6]; I[6] = T[7]; I[7] = T[8]; } }; template<> struct impl > { typedef void enable; static const bool value = true; static inline void eval(double A, double B, const Vector<3> &rAi, const Vector<3> &rBk, const Vector<3> &rAB, const Vector<3> &rij, const Vector<3> &rkl, const Vector<1> &t2, const Vector<1> &W, const double (&C)[2], double (&I)[4]) { #define pow(x,y) util::pow<(y)>::eval((x)) const int N = 1; // // // // // double vCx[N] __attribute__ ((aligned(16))); // double vCy[N] __attribute__ ((aligned(16))); // double vCz[N] __attribute__ ((aligned(16))); // // // for (int a = 0; a < N; ++a) { // // // // // vCx[a] = recurrence::coefficient<0>(rAi, B, rAB, t2[a]); // vCy[a] = recurrence::coefficient<1>(rAi, B, rAB, t2[a]); // vCz[a] = recurrence::coefficient<2>(rAi, B, rAB, t2[a]); // // // } // #define B00 vB00[a] // #define B10 vB10[a] // #define B01 vB01[a] // #define Cx vCx[a] // #define Cy vCy[a] // #define Cz vCz[a] // #define Dx vDx[a] // #define Dy vDy[a] // #define Dz vDz[a] #if defined (__INTEL_COMPILER) #pragma ivdep #pragma vector aligned #endif for (int a = 0; a < N; ++a) { double Cx = recurrence::coefficient<0>(rAi, B, rAB, t2[a]); double Cy = recurrence::coefficient<1>(rAi, B, rAB, t2[a]); double Cz = recurrence::coefficient<2>(rAi, B, rAB, t2[a]); I[0] += C[1]*W[a]*(Cx); I[1] += C[1]*W[a]*(Cy); I[2] += C[1]*W[a]*(Cz); I[3] += C[0]*W[a]*(1); } #undef B00 #undef B10 #undef B01 #undef Cx #undef Cy #undef Cz #undef Dx #undef Dy #undef Dz #undef pow } static inline void reorder(double (&I)[4]) { double T[4]; for (int i = 0; i < 4; ++i) { T[i] = I[i]; } I[1] = T[0]; I[2] = T[1]; I[3] = T[2]; I[0] = T[3]; } }; template<> struct impl > { typedef void enable; static const bool value = true; static inline void eval(double A, double B, const Vector<3> &rAi, const Vector<3> &rBk, const Vector<3> &rAB, const Vector<3> &rij, const Vector<3> &rkl, const Vector<3> &t2, const Vector<3> &W, const double (&C)[4], double (&I)[160]) { #define pow(x,y) util::pow<(y)>::eval((x)) const int N = 3; double xkl = rkl[0]; double ykl = rkl[1]; double zkl = rkl[2]; // // double vB00[N] __attribute__ ((aligned(16))); // // // double vB10[N] __attribute__ ((aligned(16))); // // // double vB01[N] __attribute__ ((aligned(16))); // // // double vCx[N] __attribute__ ((aligned(16))); // double vCy[N] __attribute__ ((aligned(16))); // double vCz[N] __attribute__ ((aligned(16))); // // // double vDx[N] __attribute__ ((aligned(16))); // double vDy[N] __attribute__ ((aligned(16))); // double vDz[N] __attribute__ ((aligned(16))); // // for (int a = 0; a < N; ++a) { // // vB00[a] = 0.5*t2[a]; // // // vB10[a] = recurrence::coefficient(1.0/A, B, t2[a]); // // // vB01[a] = recurrence::coefficient(1.0/B, A, t2[a]); // // // vCx[a] = recurrence::coefficient<0>(rAi, B, rAB, t2[a]); // vCy[a] = recurrence::coefficient<1>(rAi, B, rAB, t2[a]); // vCz[a] = recurrence::coefficient<2>(rAi, B, rAB, t2[a]); // // // vDx[a] = recurrence::coefficient<0>(rBk, -A, rAB, t2[a]); // vDy[a] = recurrence::coefficient<1>(rBk, -A, rAB, t2[a]); // vDz[a] = recurrence::coefficient<2>(rBk, -A, rAB, t2[a]); // // } // #define B00 vB00[a] // #define B10 vB10[a] // #define B01 vB01[a] // #define Cx vCx[a] // #define Cy vCy[a] // #define Cz vCz[a] // #define Dx vDx[a] // #define Dy vDy[a] // #define Dz vDz[a] #if defined (__INTEL_COMPILER) #pragma ivdep #pragma vector aligned #endif for (int a = 0; a < N; ++a) { double B00 = 0.5*t2[a]; double B10 = recurrence::coefficient(1.0/A, B, t2[a]); double B01 = recurrence::coefficient(1.0/B, A, t2[a]); double Cx = recurrence::coefficient<0>(rAi, B, rAB, t2[a]); double Cy = recurrence::coefficient<1>(rAi, B, rAB, t2[a]); double Cz = recurrence::coefficient<2>(rAi, B, rAB, t2[a]); double Dx = recurrence::coefficient<0>(rBk, -A, rAB, t2[a]); double Dy = recurrence::coefficient<1>(rBk, -A, rAB, t2[a]); double Dz = recurrence::coefficient<2>(rBk, -A, rAB, t2[a]); double Kx = (xkl + Dx); double Ky = (ykl + Dy); double Kz = (Dz + zkl); double Px = (B10 + pow(Cx,2)); double Py = (B10 + pow(Cy,2)); double Pz = (B10 + pow(Cz,2)); double Qx = (Cx*Dx + B00); double Qy = (Cy*Dy + B00); double Qz = (Cz*Dz + B00); double f0 = (3*B10 + pow(Cx,2)); double f1 = 3*B00*pow(Cy,2); double f11 = 3*B00*B10; double f12 = (Dy*Py + 2*B00*Cy); double f14 = (2*B00*Cx*(xkl + 2*Dx) + 2*pow(B00,2) + Px*(B01 + Dx*Kx)); double f15 = 3*B10*Cy*Dy; double f16 = (B01 + Dx*Kx); double f19 = (Kx*Px + 2*B00*Cx); double f2 = (B01*Cx + Cx*Dx*Kx + B00*(xkl + 2*Dx)); double f20 = 3*B00*pow(Cz,2); double f21 = (2*pow(B00,2) + Pz*(Dz*Kz + B01) + 2*B00*Cz*(2*Dz + zkl)); double f22 = 3*B00*pow(Cx,2); double f25 = (Dx*Px + 2*B00*Cx); double f26 = 3*B10*Cx*Dx; double f27 = (Dz*Kz + B01); double f28 = (B01 + Dy*Ky); double f29 = (B00 + Cx*Kx); double f3 = (Dz*Pz + 2*B00*Cz); double f36 = Dx*pow(Cx,3); double f37 = (3*B10 + pow(Cz,2)); double f38 = (3*B10 + pow(Cy,2)); double f4 = 3*B10*Cz*Dz; double f42 = Dy*pow(Cy,3); double f45 = (B01*Cz + B00*(2*Dz + zkl) + Cz*Dz*Kz); double f5 = (Py*(B01 + Dy*Ky) + 2*pow(B00,2) + 2*B00*Cy*(ykl + 2*Dy)); double f6 = (Cy*Dy*Ky + B01*Cy + B00*(ykl + 2*Dy)); double f7 = Dz*pow(Cz,3); I[0] += C[3]*W[a]*((6*Cy*pow(B00,2) + B01*(3*B10*Cy + pow(Cy,3)) + Dy*(2*f11 + Cy*Dy*f38 + 2*f1) + ykl*(f11 + f15 + f42 + f1))); I[1] += C[3]*W[a]*(Dx*(f11 + f15 + f42 + ykl*pow(Cy,3) + f1 + 3*B10*Cy*ykl)); I[2] += C[3]*W[a]*(Dz*(f11 + f15 + f42 + ykl*pow(Cy,3) + f1 + 3*B10*Cy*ykl)); I[3] += C[2]*W[a]*((f11 + f15 + f42 + ykl*pow(Cy,3) + f1 + 3*B10*Cy*ykl)); I[4] += C[3]*W[a]*((Dz*(2*f20 + Cz*Dz*f37 + 2*f11) + zkl*(f11 + f20 + f4 + f7) + B01*(3*B10*Cz + pow(Cz,3)) + 6*Cz*pow(B00,2))); I[5] += C[3]*W[a]*(Dy*(f11 + f20 + 3*B10*Cz*zkl + f4 + f7 + zkl*pow(Cz,3))); I[6] += C[3]*W[a]*(Dx*(f11 + f20 + 3*B10*Cz*zkl + f4 + f7 + zkl*pow(Cz,3))); I[7] += C[2]*W[a]*((f11 + f20 + 3*B10*Cz*zkl + f4 + f7 + zkl*pow(Cz,3))); I[8] += C[3]*W[a]*((6*Cx*pow(B00,2) + B01*(3*B10*Cx + pow(Cx,3)) + xkl*(f11 + f22 + f26 + f36) + Dx*(Cx*Dx*f0 + 2*f22 + 2*f11))); I[9] += C[3]*W[a]*(Dz*(f11 + f22 + f26 + f36 + 3*B10*Cx*xkl + xkl*pow(Cx,3))); I[10] += C[3]*W[a]*(Dy*(f11 + f22 + f26 + f36 + 3*B10*Cx*xkl + xkl*pow(Cx,3))); I[11] += C[2]*W[a]*((f11 + f22 + f26 + f36 + 3*B10*Cx*xkl + xkl*pow(Cx,3))); I[12] += C[3]*W[a]*(Ky*(f11 + f22 + f26 + f36)); I[13] += C[3]*W[a]*(Kz*(f11 + f22 + f26 + f36)); I[14] += C[1]*W[a]*((f11 + f22 + f26 + f36)); I[15] += C[3]*W[a]*(Kz*(f11 + f15 + f42 + f1)); I[16] += C[3]*W[a]*(Kx*(f11 + f15 + f42 + f1)); I[17] += C[1]*W[a]*((f11 + f15 + f42 + f1)); I[18] += C[3]*W[a]*(Ky*(f11 + f20 + f4 + f7)); I[19] += C[3]*W[a]*(Kx*(f11 + f20 + f4 + f7)); I[20] += C[1]*W[a]*((f11 + f20 + f4 + f7)); I[21] += C[3]*W[a]*(Dx*Py*(Cz*zkl + Qz)); I[22] += C[3]*W[a]*(Cx*Qy*(Cz*zkl + Qz)); I[23] += C[3]*W[a]*(Qy*(Pz*zkl + f3)); I[24] += C[3]*W[a]*(Qx*(Pz*zkl + f3)); I[25] += C[3]*W[a]*(Cx*Dy*(Pz*zkl + f3)); I[26] += C[2]*W[a]*(Cx*(Pz*zkl + f3)); I[27] += C[3]*W[a]*(Cy*Dx*(Pz*zkl + f3)); I[28] += C[2]*W[a]*(Cy*(Pz*zkl + f3)); I[29] += C[3]*W[a]*(Cy*Qx*(Cz*zkl + Qz)); I[30] += C[2]*W[a]*(Cx*Cy*(Cz*zkl + Qz)); I[31] += C[3]*W[a]*(Dy*Px*(Cz*zkl + Qz)); I[32] += C[2]*W[a]*(Px*(Cz*zkl + Qz)); I[33] += C[2]*W[a]*(Py*(Cz*zkl + Qz)); I[34] += C[3]*W[a]*(f25*(Cz*zkl + Qz)); I[35] += C[3]*W[a]*(f12*(Cz*zkl + Qz)); I[36] += C[3]*W[a]*(Cy*f27*f38); I[37] += C[3]*W[a]*(Cy*Px*f27); I[38] += C[3]*W[a]*(Cx*Cz*f6); I[39] += C[3]*W[a]*(Cx*Pz*f28); I[40] += C[3]*W[a]*(Cx*f0*f28); I[41] += C[3]*W[a]*(Cx*f0*f27); I[42] += C[3]*W[a]*(Cx*Py*f27); I[43] += C[3]*W[a]*(Cx*Qz*(Cy*ykl + Qy)); I[44] += C[3]*W[a]*(Qz*(f12 + Py*ykl)); I[45] += C[3]*W[a]*(Qx*(f12 + Py*ykl)); I[46] += C[3]*W[a]*(Cx*Dz*(f12 + Py*ykl)); I[47] += C[2]*W[a]*(Cx*(f12 + Py*ykl)); I[48] += C[3]*W[a]*(Cz*Dx*(f12 + Py*ykl)); I[49] += C[2]*W[a]*(Cz*(f12 + Py*ykl)); I[50] += C[3]*W[a]*(Cz*Qx*(Cy*ykl + Qy)); I[51] += C[2]*W[a]*(Cx*Cz*(Cy*ykl + Qy)); I[52] += C[3]*W[a]*(f3*(Cy*ykl + Qy)); I[53] += C[3]*W[a]*(f25*(Cy*ykl + Qy)); I[54] += C[3]*W[a]*(Dz*Px*(Cy*ykl + Qy)); I[55] += C[2]*W[a]*(Px*(Cy*ykl + Qy)); I[56] += C[3]*W[a]*(Dx*Pz*(Cy*ykl + Qy)); I[57] += C[2]*W[a]*(Pz*(Cy*ykl + Qy)); I[58] += C[3]*W[a]*(Kx*Pz*Qy); I[59] += C[3]*W[a]*(Cz*Qy*f29); I[60] += C[3]*W[a]*(Cy*Cz*f2); I[61] += C[1]*W[a]*(Cy*Cz*Qx); I[62] += C[2]*W[a]*(Cy*Cz*f29); I[63] += C[3]*W[a]*(Cy*Qz*f29); I[64] += C[1]*W[a]*(Cx*Cy*Qz); I[65] += C[3]*W[a]*(Cx*Cy*f45); I[66] += C[0]*W[a]*(Cx*Cy*Cz); I[67] += C[1]*W[a]*(Cx*Cz*Qy); I[68] += C[3]*W[a]*(Qy*f19); I[69] += C[3]*W[a]*(Qz*f19); I[70] += C[3]*W[a]*(Px*f6); I[71] += C[3]*W[a]*(f12*f29); I[72] += C[3]*W[a]*(f29*f3); I[73] += C[3]*W[a]*(Cx*Ky*f3); I[74] += C[1]*W[a]*(Cx*f3); I[75] += C[3]*W[a]*(Cy*Kx*f3); I[76] += C[1]*W[a]*(Cy*f3); I[77] += C[3]*W[a]*(Cy*f14); I[78] += C[3]*W[a]*(Cz*f14); I[79] += C[3]*W[a]*(Cz*Dy*f19); I[80] += C[2]*W[a]*(Cz*f19); I[81] += C[3]*W[a]*(Cz*Kx*f12); I[82] += C[1]*W[a]*(Cz*f12); I[83] += C[3]*W[a]*(Cx*Kz*f12); I[84] += C[1]*W[a]*(Cx*f12); I[85] += C[3]*W[a]*(Cx*f5); I[86] += C[3]*W[a]*(Cz*f5); I[87] += C[3]*W[a]*(Pz*f2); I[88] += C[3]*W[a]*(Py*f2); I[89] += C[3]*W[a]*(Kx*Py*Qz); I[90] += C[1]*W[a]*(Py*Qz); I[91] += C[2]*W[a]*(Py*f29); I[92] += C[3]*W[a]*(Dz*Py*f29); I[93] += C[1]*W[a]*(Cx*Dz*Py); I[94] += C[0]*W[a]*(Cx*Py); I[95] += C[2]*W[a]*(Cx*Kz*Py); I[96] += C[3]*W[a]*(Kz*Py*Qx); I[97] += C[1]*W[a]*(Py*Qx); I[98] += C[3]*W[a]*(Ky*Pz*Qx); I[99] += C[1]*W[a]*(Pz*Qx); I[100] += C[3]*W[a]*(Pz*f6); I[101] += C[1]*W[a]*(Pz*Qy); I[102] += C[3]*W[a]*(Kz*Px*Qy); I[103] += C[1]*W[a]*(Px*Qy); I[104] += C[1]*W[a]*(Px*Qz); I[105] += C[3]*W[a]*(Ky*Px*Qz); I[106] += C[2]*W[a]*(Cz*Ky*Px); I[107] += C[3]*W[a]*(Cz*Px*f28); I[108] += C[3]*W[a]*(Cz*f28*f37); I[109] += C[3]*W[a]*(Cz*f16*f37); I[110] += C[3]*W[a]*(Cz*Py*f16); I[111] += C[2]*W[a]*(Cz*Kx*Py); I[112] += C[2]*W[a]*(Cz*Kx*f37); I[113] += C[3]*W[a]*(Cz*Dy*Kx*f37); I[114] += C[1]*W[a]*(Cz*Dy*f37); I[115] += C[1]*W[a]*(Cz*Dy*Px); I[116] += C[0]*W[a]*(Cz*Px); I[117] += C[3]*W[a]*(Px*f45); I[118] += C[3]*W[a]*(Py*f45); I[119] += C[0]*W[a]*(Cz*Py); I[120] += C[1]*W[a]*(Cz*Dx*Py); I[121] += C[3]*W[a]*(Cz*Dx*Ky*f37); I[122] += C[1]*W[a]*(Cz*Dx*f37); I[123] += C[0]*W[a]*(Cz*f37); I[124] += C[2]*W[a]*(Cz*Ky*f37); I[125] += C[3]*W[a]*(Cz*Ky*f25); I[126] += C[1]*W[a]*(Cz*f25); I[127] += C[3]*W[a]*(Cy*Kz*f25); I[128] += C[1]*W[a]*(Cy*f25); I[129] += C[2]*W[a]*(Cy*f19); I[130] += C[3]*W[a]*(Cy*Dz*f19); I[131] += C[1]*W[a]*(Cy*Dz*Px); I[132] += C[0]*W[a]*(Cy*Px); I[133] += C[2]*W[a]*(Cy*Kz*Px); I[134] += C[3]*W[a]*(Cy*Dx*Kz*f38); I[135] += C[2]*W[a]*(Cy*Kz*f38); I[136] += C[3]*W[a]*(Cy*f16*f38); I[137] += C[3]*W[a]*(Cy*Pz*f16); I[138] += C[2]*W[a]*(Cy*Kx*Pz); I[139] += C[2]*W[a]*(Cy*Kx*f38); I[140] += C[3]*W[a]*(Cy*Dz*Kx*f38); I[141] += C[1]*W[a]*(Cy*Dz*f38); I[142] += C[0]*W[a]*(Cy*f38); I[143] += C[1]*W[a]*(Cy*Dx*f38); I[144] += C[1]*W[a]*(Cy*Dx*Pz); I[145] += C[0]*W[a]*(Cy*Pz); I[146] += C[2]*W[a]*(Pz*f29); I[147] += C[3]*W[a]*(Dy*Pz*f29); I[148] += C[1]*W[a]*(Cx*Dy*Pz); I[149] += C[0]*W[a]*(Cx*Pz); I[150] += C[2]*W[a]*(Cx*Ky*Pz); I[151] += C[2]*W[a]*(Cx*Ky*f0); I[152] += C[3]*W[a]*(Cx*Dz*Ky*f0); I[153] += C[1]*W[a]*(Cx*Dz*f0); I[154] += C[2]*W[a]*(Cx*Kz*f0); I[155] += C[3]*W[a]*(Cx*Dy*Kz*f0); I[156] += C[1]*W[a]*(Cx*Dy*f0); I[157] += C[0]*W[a]*(Cx*f0); I[158] += C[3]*W[a]*(Cx*f21); I[159] += C[3]*W[a]*(Cy*f21); } #undef B00 #undef B10 #undef B01 #undef Cx #undef Cy #undef Cz #undef Dx #undef Dy #undef Dz #undef pow } static inline void reorder(double (&I)[160]) { double T[160]; for (int i = 0; i < 160; ++i) { T[i] = I[i]; } I[101] = T[0]; I[91] = T[1]; I[111] = T[2]; I[81] = T[3]; I[152] = T[4]; I[142] = T[5]; I[132] = T[6]; I[122] = T[7]; I[50] = T[8]; I[70] = T[9]; I[60] = T[10]; I[40] = T[11]; I[90] = T[12]; I[130] = T[13]; I[10] = T[14]; I[141] = T[15]; I[61] = T[16]; I[21] = T[17]; I[112] = T[18]; I[72] = T[19]; I[32] = T[20]; I[136] = T[21]; I[149] = T[22]; I[148] = T[23]; I[137] = T[24]; I[147] = T[25]; I[127] = T[26]; I[138] = T[27]; I[128] = T[28]; I[139] = T[29]; I[129] = T[30]; I[144] = T[31]; I[124] = T[32]; I[126] = T[33]; I[134] = T[34]; I[146] = T[35]; I[151] = T[36]; I[153] = T[37]; I[109] = T[38]; I[107] = T[39]; I[100] = T[40]; I[150] = T[41]; I[155] = T[42]; I[119] = T[43]; I[116] = T[44]; I[95] = T[45]; I[115] = T[46]; I[85] = T[47]; I[96] = T[48]; I[86] = T[49]; I[99] = T[50]; I[89] = T[51]; I[118] = T[52]; I[93] = T[53]; I[113] = T[54]; I[83] = T[55]; I[98] = T[56]; I[88] = T[57]; I[68] = T[58]; I[69] = T[59]; I[59] = T[60]; I[19] = T[61]; I[49] = T[62]; I[79] = T[63]; I[39] = T[64]; I[159] = T[65]; I[9] = T[66]; I[29] = T[67]; I[63] = T[68]; I[74] = T[69]; I[103] = T[70]; I[65] = T[71]; I[77] = T[72]; I[117] = T[73]; I[37] = T[74]; I[78] = T[75]; I[38] = T[76]; I[53] = T[77]; I[54] = T[78]; I[64] = T[79]; I[44] = T[80]; I[66] = T[81]; I[26] = T[82]; I[145] = T[83]; I[25] = T[84]; I[105] = T[85]; I[106] = T[86]; I[57] = T[87]; I[55] = T[88]; I[76] = T[89]; I[36] = T[90]; I[45] = T[91]; I[75] = T[92]; I[35] = T[93]; I[5] = T[94]; I[125] = T[95]; I[135] = T[96]; I[15] = T[97]; I[97] = T[98]; I[17] = T[99]; I[108] = T[100]; I[28] = T[101]; I[143] = T[102]; I[23] = T[103]; I[34] = T[104]; I[114] = T[105]; I[84] = T[106]; I[104] = T[107]; I[102] = T[108]; I[52] = T[109]; I[56] = T[110]; I[46] = T[111]; I[42] = T[112]; I[62] = T[113]; I[22] = T[114]; I[24] = T[115]; I[4] = T[116]; I[154] = T[117]; I[156] = T[118]; I[6] = T[119]; I[16] = T[120]; I[92] = T[121]; I[12] = T[122]; I[2] = T[123]; I[82] = T[124]; I[94] = T[125]; I[14] = T[126]; I[133] = T[127]; I[13] = T[128]; I[43] = T[129]; I[73] = T[130]; I[33] = T[131]; I[3] = T[132]; I[123] = T[133]; I[131] = T[134]; I[121] = T[135]; I[51] = T[136]; I[58] = T[137]; I[48] = T[138]; I[41] = T[139]; I[71] = T[140]; I[31] = T[141]; I[1] = T[142]; I[11] = T[143]; I[18] = T[144]; I[8] = T[145]; I[47] = T[146]; I[67] = T[147]; I[27] = T[148]; I[7] = T[149]; I[87] = T[150]; I[80] = T[151]; I[110] = T[152]; I[30] = T[153]; I[120] = T[154]; I[140] = T[155]; I[20] = T[156]; I[0] = T[157]; I[157] = T[158]; I[158] = T[159]; } }; template<> struct impl > { typedef void enable; static const bool value = true; static inline void eval(double A, double B, const Vector<3> &rAi, const Vector<3> &rBk, const Vector<3> &rAB, const Vector<3> &rij, const Vector<3> &rkl, const Vector<3> &t2, const Vector<3> &W, const double (&C)[2], double (&I)[40]) { #define pow(x,y) util::pow<(y)>::eval((x)) const int N = 3; // // double vB00[N] __attribute__ ((aligned(16))); // // // double vB10[N] __attribute__ ((aligned(16))); // // // // double vCx[N] __attribute__ ((aligned(16))); // double vCy[N] __attribute__ ((aligned(16))); // double vCz[N] __attribute__ ((aligned(16))); // // // double vDx[N] __attribute__ ((aligned(16))); // double vDy[N] __attribute__ ((aligned(16))); // double vDz[N] __attribute__ ((aligned(16))); // // for (int a = 0; a < N; ++a) { // // vB00[a] = 0.5*t2[a]; // // // vB10[a] = recurrence::coefficient(1.0/A, B, t2[a]); // // // // vCx[a] = recurrence::coefficient<0>(rAi, B, rAB, t2[a]); // vCy[a] = recurrence::coefficient<1>(rAi, B, rAB, t2[a]); // vCz[a] = recurrence::coefficient<2>(rAi, B, rAB, t2[a]); // // // vDx[a] = recurrence::coefficient<0>(rBk, -A, rAB, t2[a]); // vDy[a] = recurrence::coefficient<1>(rBk, -A, rAB, t2[a]); // vDz[a] = recurrence::coefficient<2>(rBk, -A, rAB, t2[a]); // // } // #define B00 vB00[a] // #define B10 vB10[a] // #define B01 vB01[a] // #define Cx vCx[a] // #define Cy vCy[a] // #define Cz vCz[a] // #define Dx vDx[a] // #define Dy vDy[a] // #define Dz vDz[a] #if defined (__INTEL_COMPILER) #pragma ivdep #pragma vector aligned #endif for (int a = 0; a < N; ++a) { double B00 = 0.5*t2[a]; double B10 = recurrence::coefficient(1.0/A, B, t2[a]); double Cx = recurrence::coefficient<0>(rAi, B, rAB, t2[a]); double Cy = recurrence::coefficient<1>(rAi, B, rAB, t2[a]); double Cz = recurrence::coefficient<2>(rAi, B, rAB, t2[a]); double Dx = recurrence::coefficient<0>(rBk, -A, rAB, t2[a]); double Dy = recurrence::coefficient<1>(rBk, -A, rAB, t2[a]); double Dz = recurrence::coefficient<2>(rBk, -A, rAB, t2[a]); double Px = (B10 + pow(Cx,2)); double Py = (B10 + pow(Cy,2)); double Pz = (B10 + pow(Cz,2)); double Qx = (Cx*Dx + B00); double Qy = (Cy*Dy + B00); double Qz = (Cz*Dz + B00); double f0 = (3*B10 + pow(Cx,2)); double f1 = (Dz*Pz + 2*B00*Cz); double f10 = (3*B10 + pow(Cz,2)); double f11 = (3*B10 + pow(Cy,2)); double f3 = 3*B00*B10; double f4 = (Dy*Py + 2*B00*Cy); double f6 = (Dx*Px + 2*B00*Cx); I[0] += C[1]*W[a]*((Dx*pow(Cx,3) + 3*B00*pow(Cx,2) + 3*B10*Cx*Dx + f3)); I[1] += C[1]*W[a]*((3*B00*pow(Cy,2) + f3 + Dy*pow(Cy,3) + 3*B10*Cy*Dy)); I[2] += C[1]*W[a]*((3*B10*Cz*Dz + f3 + 3*B00*pow(Cz,2) + Dz*pow(Cz,3))); I[3] += C[1]*W[a]*(Cy*Cz*Qx); I[4] += C[1]*W[a]*(Cz*Dy*f10); I[5] += C[1]*W[a]*(Cz*Dy*Px); I[6] += C[1]*W[a]*(Cx*Cz*Qy); I[7] += C[1]*W[a]*(Cx*Dz*f0); I[8] += C[1]*W[a]*(Cx*Dz*Py); I[9] += C[1]*W[a]*(Cx*Cy*Qz); I[10] += C[0]*W[a]*(Cx*Cy*Cz); I[11] += C[1]*W[a]*(Cz*Dx*Py); I[12] += C[1]*W[a]*(Cz*Dx*f10); I[13] += C[0]*W[a]*(Cz*f10); I[14] += C[1]*W[a]*(Cy*f6); I[15] += C[1]*W[a]*(Cz*f6); I[16] += C[0]*W[a]*(Cz*Px); I[17] += C[1]*W[a]*(Px*Qy); I[18] += C[1]*W[a]*(Cx*f4); I[19] += C[1]*W[a]*(Cz*f4); I[20] += C[0]*W[a]*(Cz*Py); I[21] += C[1]*W[a]*(Py*Qx); I[22] += C[1]*W[a]*(Pz*Qx); I[23] += C[1]*W[a]*(Pz*Qy); I[24] += C[0]*W[a]*(Cy*Pz); I[25] += C[1]*W[a]*(Cy*Dx*Pz); I[26] += C[1]*W[a]*(Cy*Dx*f11); I[27] += C[0]*W[a]*(Cy*f11); I[28] += C[1]*W[a]*(Cy*Dz*f11); I[29] += C[1]*W[a]*(Cy*Dz*Px); I[30] += C[0]*W[a]*(Cy*Px); I[31] += C[1]*W[a]*(Px*Qz); I[32] += C[1]*W[a]*(Py*Qz); I[33] += C[0]*W[a]*(Cx*Py); I[34] += C[0]*W[a]*(Cx*Pz); I[35] += C[1]*W[a]*(Cx*Dy*Pz); I[36] += C[1]*W[a]*(Cx*Dy*f0); I[37] += C[0]*W[a]*(Cx*f0); I[38] += C[1]*W[a]*(Cx*f1); I[39] += C[1]*W[a]*(Cy*f1); } #undef B00 #undef B10 #undef B01 #undef Cx #undef Cy #undef Cz #undef Dx #undef Dy #undef Dz #undef pow } static inline void reorder(double (&I)[40]) { double T[40]; for (int i = 0; i < 40; ++i) { T[i] = I[i]; } I[10] = T[0]; I[21] = T[1]; I[32] = T[2]; I[19] = T[3]; I[22] = T[4]; I[24] = T[5]; I[29] = T[6]; I[30] = T[7]; I[35] = T[8]; I[39] = T[9]; I[9] = T[10]; I[16] = T[11]; I[12] = T[12]; I[2] = T[13]; I[13] = T[14]; I[14] = T[15]; I[4] = T[16]; I[23] = T[17]; I[25] = T[18]; I[26] = T[19]; I[6] = T[20]; I[15] = T[21]; I[17] = T[22]; I[28] = T[23]; I[8] = T[24]; I[18] = T[25]; I[11] = T[26]; I[1] = T[27]; I[31] = T[28]; I[33] = T[29]; I[3] = T[30]; I[34] = T[31]; I[36] = T[32]; I[5] = T[33]; I[7] = T[34]; I[27] = T[35]; I[20] = T[36]; I[0] = T[37]; I[37] = T[38]; I[38] = T[39]; } }; template<> struct impl > { typedef void enable; static const bool value = true; static inline void eval(double A, double B, const Vector<3> &rAi, const Vector<3> &rBk, const Vector<3> &rAB, const Vector<3> &rij, const Vector<3> &rkl, const Vector<3> &t2, const Vector<3> &W, const double (&C)[1], double (&I)[30]) { #define pow(x,y) util::pow<(y)>::eval((x)) const int N = 3; // // double vB00[N] __attribute__ ((aligned(16))); // // // double vB10[N] __attribute__ ((aligned(16))); // // // // double vCx[N] __attribute__ ((aligned(16))); // double vCy[N] __attribute__ ((aligned(16))); // double vCz[N] __attribute__ ((aligned(16))); // // // double vDx[N] __attribute__ ((aligned(16))); // double vDy[N] __attribute__ ((aligned(16))); // double vDz[N] __attribute__ ((aligned(16))); // // for (int a = 0; a < N; ++a) { // // vB00[a] = 0.5*t2[a]; // // // vB10[a] = recurrence::coefficient(1.0/A, B, t2[a]); // // // // vCx[a] = recurrence::coefficient<0>(rAi, B, rAB, t2[a]); // vCy[a] = recurrence::coefficient<1>(rAi, B, rAB, t2[a]); // vCz[a] = recurrence::coefficient<2>(rAi, B, rAB, t2[a]); // // // vDx[a] = recurrence::coefficient<0>(rBk, -A, rAB, t2[a]); // vDy[a] = recurrence::coefficient<1>(rBk, -A, rAB, t2[a]); // vDz[a] = recurrence::coefficient<2>(rBk, -A, rAB, t2[a]); // // } // #define B00 vB00[a] // #define B10 vB10[a] // #define B01 vB01[a] // #define Cx vCx[a] // #define Cy vCy[a] // #define Cz vCz[a] // #define Dx vDx[a] // #define Dy vDy[a] // #define Dz vDz[a] #if defined (__INTEL_COMPILER) #pragma ivdep #pragma vector aligned #endif for (int a = 0; a < N; ++a) { double B00 = 0.5*t2[a]; double B10 = recurrence::coefficient(1.0/A, B, t2[a]); double Cx = recurrence::coefficient<0>(rAi, B, rAB, t2[a]); double Cy = recurrence::coefficient<1>(rAi, B, rAB, t2[a]); double Cz = recurrence::coefficient<2>(rAi, B, rAB, t2[a]); double Dx = recurrence::coefficient<0>(rBk, -A, rAB, t2[a]); double Dy = recurrence::coefficient<1>(rBk, -A, rAB, t2[a]); double Dz = recurrence::coefficient<2>(rBk, -A, rAB, t2[a]); double Px = (B10 + pow(Cx,2)); double Py = (B10 + pow(Cy,2)); double Pz = (B10 + pow(Cz,2)); double Qx = (Cx*Dx + B00); double Qy = (Cy*Dy + B00); double Qz = (Cz*Dz + B00); double f0 = (3*B10 + pow(Cx,2)); double f1 = (Dz*Pz + 2*B00*Cz); double f10 = (3*B10 + pow(Cz,2)); double f11 = (3*B10 + pow(Cy,2)); double f3 = 3*B00*B10; double f4 = (Dy*Py + 2*B00*Cy); double f6 = (Dx*Px + 2*B00*Cx); I[0] += C[0]*W[a]*((Dx*pow(Cx,3) + 3*B00*pow(Cx,2) + 3*B10*Cx*Dx + f3)); I[1] += C[0]*W[a]*((3*B00*pow(Cy,2) + f3 + Dy*pow(Cy,3) + 3*B10*Cy*Dy)); I[2] += C[0]*W[a]*((3*B10*Cz*Dz + f3 + 3*B00*pow(Cz,2) + Dz*pow(Cz,3))); I[3] += C[0]*W[a]*(Cx*Cz*Qy); I[4] += C[0]*W[a]*(Cy*Dz*Px); I[5] += C[0]*W[a]*(Cy*Dz*f11); I[6] += C[0]*W[a]*(Cy*Dx*f11); I[7] += C[0]*W[a]*(Cy*Dx*Pz); I[8] += C[0]*W[a]*(Cx*Dy*Pz); I[9] += C[0]*W[a]*(Cx*Dy*f0); I[10] += C[0]*W[a]*(Cx*Dz*f0); I[11] += C[0]*W[a]*(Cx*Dz*Py); I[12] += C[0]*W[a]*(Cx*Cy*Qz); I[13] += C[0]*W[a]*(Cy*Cz*Qx); I[14] += C[0]*W[a]*(Cz*Dy*Px); I[15] += C[0]*W[a]*(Cz*Dy*f10); I[16] += C[0]*W[a]*(Cz*Dx*f10); I[17] += C[0]*W[a]*(Cz*Dx*Py); I[18] += C[0]*W[a]*(Py*Qx); I[19] += C[0]*W[a]*(Pz*Qx); I[20] += C[0]*W[a]*(Pz*Qy); I[21] += C[0]*W[a]*(Px*Qy); I[22] += C[0]*W[a]*(Px*Qz); I[23] += C[0]*W[a]*(Py*Qz); I[24] += C[0]*W[a]*(Cy*f6); I[25] += C[0]*W[a]*(Cz*f6); I[26] += C[0]*W[a]*(Cz*f4); I[27] += C[0]*W[a]*(Cx*f4); I[28] += C[0]*W[a]*(Cx*f1); I[29] += C[0]*W[a]*(Cy*f1); } #undef B00 #undef B10 #undef B01 #undef Cx #undef Cy #undef Cz #undef Dx #undef Dy #undef Dz #undef pow } static inline void reorder(double (&I)[30]) { double T[30]; for (int i = 0; i < 30; ++i) { T[i] = I[i]; } I[0] = T[0]; I[11] = T[1]; I[22] = T[2]; I[19] = T[3]; I[23] = T[4]; I[21] = T[5]; I[1] = T[6]; I[8] = T[7]; I[17] = T[8]; I[10] = T[9]; I[20] = T[10]; I[25] = T[11]; I[29] = T[12]; I[9] = T[13]; I[14] = T[14]; I[12] = T[15]; I[2] = T[16]; I[6] = T[17]; I[5] = T[18]; I[7] = T[19]; I[18] = T[20]; I[13] = T[21]; I[24] = T[22]; I[26] = T[23]; I[3] = T[24]; I[4] = T[25]; I[16] = T[26]; I[15] = T[27]; I[27] = T[28]; I[28] = T[29]; } }; template<> struct impl > { typedef void enable; static const bool value = true; static inline void eval(double A, double B, const Vector<3> &rAi, const Vector<3> &rBk, const Vector<3> &rAB, const Vector<3> &rij, const Vector<3> &rkl, const Vector<3> &t2, const Vector<3> &W, const double (&C)[4], double (&I)[160]) { #define pow(x,y) util::pow<(y)>::eval((x)) const int N = 3; double xij = rij[0]; double yij = rij[1]; double zij = rij[2]; // // double vB00[N] __attribute__ ((aligned(16))); // // // double vB10[N] __attribute__ ((aligned(16))); // // // // double vCx[N] __attribute__ ((aligned(16))); // double vCy[N] __attribute__ ((aligned(16))); // double vCz[N] __attribute__ ((aligned(16))); // // // double vDx[N] __attribute__ ((aligned(16))); // double vDy[N] __attribute__ ((aligned(16))); // double vDz[N] __attribute__ ((aligned(16))); // // for (int a = 0; a < N; ++a) { // // vB00[a] = 0.5*t2[a]; // // // vB10[a] = recurrence::coefficient(1.0/A, B, t2[a]); // // // // vCx[a] = recurrence::coefficient<0>(rAi, B, rAB, t2[a]); // vCy[a] = recurrence::coefficient<1>(rAi, B, rAB, t2[a]); // vCz[a] = recurrence::coefficient<2>(rAi, B, rAB, t2[a]); // // // vDx[a] = recurrence::coefficient<0>(rBk, -A, rAB, t2[a]); // vDy[a] = recurrence::coefficient<1>(rBk, -A, rAB, t2[a]); // vDz[a] = recurrence::coefficient<2>(rBk, -A, rAB, t2[a]); // // } // #define B00 vB00[a] // #define B10 vB10[a] // #define B01 vB01[a] // #define Cx vCx[a] // #define Cy vCy[a] // #define Cz vCz[a] // #define Dx vDx[a] // #define Dy vDy[a] // #define Dz vDz[a] #if defined (__INTEL_COMPILER) #pragma ivdep #pragma vector aligned #endif for (int a = 0; a < N; ++a) { double B00 = 0.5*t2[a]; double B10 = recurrence::coefficient(1.0/A, B, t2[a]); double Cx = recurrence::coefficient<0>(rAi, B, rAB, t2[a]); double Cy = recurrence::coefficient<1>(rAi, B, rAB, t2[a]); double Cz = recurrence::coefficient<2>(rAi, B, rAB, t2[a]); double Dx = recurrence::coefficient<0>(rBk, -A, rAB, t2[a]); double Dy = recurrence::coefficient<1>(rBk, -A, rAB, t2[a]); double Dz = recurrence::coefficient<2>(rBk, -A, rAB, t2[a]); double Ix = (Cx + xij); double Iy = (Cy + yij); double Iz = (Cz + zij); double Px = (B10 + pow(Cx,2)); double Py = (B10 + pow(Cy,2)); double Pz = (B10 + pow(Cz,2)); double Qx = (Cx*Dx + B00); double Qy = (Cy*Dy + B00); double Qz = (Cz*Dz + B00); double f0 = (3*B10 + pow(Cx,2)); double f12 = (B00 + Dz*Iz); double f2 = (Dz*Pz + 2*B00*Cz); double f20 = (3*B10 + pow(Cz,2)); double f21 = (3*pow(B10,2) + Iy*pow(Cy,3) + 3*B10*Cy*(yij + 2*Cy)); double f23 = (Cy*Iy + B10); double f24 = (B10*(3*Cx + xij) + Ix*pow(Cx,2)); double f25 = (B00*(yij + 2*Cy) + Dy*(Cy*Iy + B10)); double f28 = (2*B00*Cy*yij + 3*B00*Py + Dy*(B10*(3*Cy + yij) + Iy*pow(Cy,2))); double f29 = (B10*(3*Cy + yij) + Iy*pow(Cy,2)); double f3 = (3*B00*Pz + Cz*Dz*(3*B10 + pow(Cz,2))); double f30 = (Cy*Dy*(3*B10 + pow(Cy,2)) + 3*B00*Py); double f31 = 3*B00*B10; double f32 = (Dy*Py + 2*B00*Cy); double f33 = 3*pow(B10,2); double f36 = (Iz*pow(Cz,2) + B10*(3*Cz + zij)); double f4 = (3*pow(B10,2) + 3*B10*Cx*(xij + 2*Cx) + Ix*pow(Cx,3)); double f5 = (Dx*Px + 2*B00*Cx); double f7 = (3*pow(B10,2) + 3*B10*Cz*(2*Cz + zij) + Iz*pow(Cz,3)); double f8 = (Cx*Dx*(3*B10 + pow(Cx,2)) + 3*B00*Px); double f9 = (3*B10 + pow(Cy,2)); I[0] += C[3]*W[a]*((B00*pow(Cy,2)*(4*Cy + 3*yij) + f31*yij + Dy*f33 + Dy*pow(Cy,4) + Dy*yij*pow(Cy,3) + 4*Cy*f31 + 3*B10*Cy*Dy*(yij + 2*Cy))); I[1] += C[3]*W[a]*(Cz*(xij*(Dx*Px + 2*B00*Cx) + f8)); I[2] += C[3]*W[a]*(Cy*(xij*(Dx*Px + 2*B00*Cx) + f8)); I[3] += C[3]*W[a]*(Cy*Cz*(Qx*xij + f5)); I[4] += C[3]*W[a]*(Py*(Qx*xij + f5)); I[5] += C[3]*W[a]*(Pz*(Qx*xij + f5)); I[6] += C[3]*W[a]*((Dx*f33 + Dx*xij*pow(Cx,3) + f31*xij + Dx*pow(Cx,4) + 4*Cx*f31 + B00*pow(Cx,2)*(4*Cx + 3*xij) + 3*B10*Cx*Dx*(xij + 2*Cx))); I[7] += C[3]*W[a]*((Dz*f33 + B00*pow(Cz,2)*(4*Cz + 3*zij) + Dz*pow(Cz,4) + 3*B10*Cz*Dz*(2*Cz + zij) + 4*Cz*f31 + Dz*zij*pow(Cz,3) + f31*zij)); I[8] += C[3]*W[a]*(Cy*(f3 + zij*(Dz*Pz + 2*B00*Cz))); I[9] += C[3]*W[a]*(Cx*(f3 + zij*(Dz*Pz + 2*B00*Cz))); I[10] += C[3]*W[a]*(Cx*Cy*(f2 + Qz*zij)); I[11] += C[3]*W[a]*(Px*(f2 + Qz*zij)); I[12] += C[3]*W[a]*(Py*(f2 + Qz*zij)); I[13] += C[3]*W[a]*(Cz*f20*(Dy*yij + Qy)); I[14] += C[3]*W[a]*(Cz*Px*(Dy*yij + Qy)); I[15] += C[3]*W[a]*(Cx*f0*(Dy*yij + Qy)); I[16] += C[3]*W[a]*(Cx*Pz*(Dy*yij + Qy)); I[17] += C[3]*W[a]*(Cy*Qz*(Px + Cx*xij)); I[18] += C[1]*W[a]*(Cy*Cz*(Px + Cx*xij)); I[19] += C[3]*W[a]*(Cz*Qy*(Px + Cx*xij)); I[20] += C[3]*W[a]*(Cx*Qy*(Cz*zij + Pz)); I[21] += C[3]*W[a]*(Dx*Py*(Cz*zij + Pz)); I[22] += C[3]*W[a]*(Cz*Py*(Dx*xij + Qx)); I[23] += C[3]*W[a]*(Cz*f20*(Dx*xij + Qx)); I[24] += C[3]*W[a]*(Cy*f9*(Dx*xij + Qx)); I[25] += C[3]*W[a]*(Cy*Pz*(Dx*xij + Qx)); I[26] += C[3]*W[a]*(Cy*Qx*(Cz*zij + Pz)); I[27] += C[1]*W[a]*(Cx*Cy*(Cz*zij + Pz)); I[28] += C[3]*W[a]*(Dy*Px*(Cz*zij + Pz)); I[29] += C[1]*W[a]*(Px*(Cz*zij + Pz)); I[30] += C[1]*W[a]*(Py*(Cz*zij + Pz)); I[31] += C[3]*W[a]*(f5*(Cz*zij + Pz)); I[32] += C[3]*W[a]*(f32*(Cz*zij + Pz)); I[33] += C[3]*W[a]*(Cy*Dz*f24); I[34] += C[3]*W[a]*(Ix*Py*Qz); I[35] += C[3]*W[a]*(Cy*Ix*f2); I[36] += C[2]*W[a]*(Cx*Cy*Qz); I[37] += C[3]*W[a]*(Cx*Cz*f25); I[38] += C[2]*W[a]*(Cx*Cz*Qy); I[39] += C[3]*W[a]*(Cz*Qx*f23); I[40] += C[2]*W[a]*(Cy*Cz*Qx); I[41] += C[0]*W[a]*(Cx*Cy*Cz); I[42] += C[1]*W[a]*(Cx*Cz*f23); I[43] += C[3]*W[a]*(Cx*Qz*f23); I[44] += C[3]*W[a]*(Cx*f0*f12); I[45] += C[3]*W[a]*(Cy*f12*f9); I[46] += C[3]*W[a]*(Cy*Px*f12); I[47] += C[3]*W[a]*(f2*(Px + Cx*xij)); I[48] += C[3]*W[a]*(f32*(Px + Cx*xij)); I[49] += C[3]*W[a]*(Dy*Pz*(Px + Cx*xij)); I[50] += C[1]*W[a]*(Pz*(Px + Cx*xij)); I[51] += C[1]*W[a]*(Py*(Px + Cx*xij)); I[52] += C[3]*W[a]*(Dz*Py*(Px + Cx*xij)); I[53] += C[2]*W[a]*(Cx*Dz*Py); I[54] += C[3]*W[a]*(Cx*Py*f12); I[55] += C[3]*W[a]*(Cx*f28); I[56] += C[3]*W[a]*(Cz*f28); I[57] += C[3]*W[a]*(Pz*f25); I[58] += C[3]*W[a]*(Px*f25); I[59] += C[3]*W[a]*(Iy*Px*Qz); I[60] += C[2]*W[a]*(Px*Qz); I[61] += C[2]*W[a]*(Py*Qz); I[62] += C[3]*W[a]*(Qx*f36); I[63] += C[3]*W[a]*(Qx*f29); I[64] += C[3]*W[a]*(Iy*Pz*Qx); I[65] += C[2]*W[a]*(Pz*Qx); I[66] += C[3]*W[a]*(Dx*Pz*f23); I[67] += C[1]*W[a]*(Pz*f23); I[68] += C[3]*W[a]*(f23*f5); I[69] += C[3]*W[a]*(Cy*Iz*f5); I[70] += C[2]*W[a]*(Cy*f5); I[71] += C[3]*W[a]*(Cy*Dx*f36); I[72] += C[1]*W[a]*(Cy*f36); I[73] += C[3]*W[a]*(Qy*f36); I[74] += C[3]*W[a]*(Qy*f24); I[75] += C[3]*W[a]*(Iz*Px*Qy); I[76] += C[2]*W[a]*(Px*Qy); I[77] += C[2]*W[a]*(Cz*Dy*Px); I[78] += C[3]*W[a]*(Cz*Dy*Ix*f20); I[79] += C[2]*W[a]*(Cz*Dy*f20); I[80] += C[3]*W[a]*(Cz*Dy*f24); I[81] += C[1]*W[a]*(Cz*f24); I[82] += C[2]*W[a]*(Cz*f5); I[83] += C[3]*W[a]*(Cz*Iy*f5); I[84] += C[1]*W[a]*(Cz*Iy*Px); I[85] += C[0]*W[a]*(Cz*Px); I[86] += C[3]*W[a]*(Cz*Ix*f32); I[87] += C[2]*W[a]*(Cz*f32); I[88] += C[3]*W[a]*(Cx*Iz*f32); I[89] += C[2]*W[a]*(Cx*f32); I[90] += C[3]*W[a]*(Cx*Iy*f2); I[91] += C[2]*W[a]*(Cx*f2); I[92] += C[2]*W[a]*(Cy*f2); I[93] += C[1]*W[a]*(Cy*f24); I[94] += C[3]*W[a]*(Qz*f24); I[95] += C[3]*W[a]*(Ix*f3); I[96] += C[3]*W[a]*(Ix*f30); I[97] += C[3]*W[a]*(Iz*f30); I[98] += C[3]*W[a]*(Iz*f8); I[99] += C[3]*W[a]*(Iy*f8); I[100] += C[3]*W[a]*(Iy*f3); I[101] += C[3]*W[a]*(Cx*Dz*Iy*f0); I[102] += C[2]*W[a]*(Cx*Dz*f0); I[103] += C[3]*W[a]*(Cx*Dz*f29); I[104] += C[1]*W[a]*(Cx*f29); I[105] += C[3]*W[a]*(Qz*f29); I[106] += C[1]*W[a]*(Cz*f29); I[107] += C[3]*W[a]*(Cz*Dx*f29); I[108] += C[2]*W[a]*(Cz*Dx*Py); I[109] += C[2]*W[a]*(Cz*Dx*f20); I[110] += C[3]*W[a]*(Cz*Dx*Iy*f20); I[111] += C[1]*W[a]*(Cz*Iy*f20); I[112] += C[0]*W[a]*(Cz*f20); I[113] += C[1]*W[a]*(Cz*Ix*f20); I[114] += C[1]*W[a]*(Cz*Ix*Py); I[115] += C[0]*W[a]*(Cz*Py); I[116] += C[2]*W[a]*(Py*Qx); I[117] += C[3]*W[a]*(Iz*Py*Qx); I[118] += C[1]*W[a]*(Cx*Iz*Py); I[119] += C[0]*W[a]*(Cx*Py); I[120] += C[1]*W[a]*(Cx*f36); I[121] += C[3]*W[a]*(Cx*Dy*f36); I[122] += C[2]*W[a]*(Cx*Dy*Pz); I[123] += C[2]*W[a]*(Cx*Dy*f0); I[124] += C[3]*W[a]*(Cx*Dy*Iz*f0); I[125] += C[1]*W[a]*(Cx*Iz*f0); I[126] += C[0]*W[a]*(Cx*f0); I[127] += C[1]*W[a]*(Cx*Iy*f0); I[128] += C[1]*W[a]*(Cx*Iy*Pz); I[129] += C[0]*W[a]*(Cx*Pz); I[130] += C[2]*W[a]*(Pz*Qy); I[131] += C[3]*W[a]*(Ix*Pz*Qy); I[132] += C[1]*W[a]*(Cy*Ix*Pz); I[133] += C[0]*W[a]*(Cy*Pz); I[134] += C[2]*W[a]*(Cy*Dx*Pz); I[135] += C[3]*W[a]*(Cy*Dx*Iz*f9); I[136] += C[2]*W[a]*(Cy*Dx*f9); I[137] += C[2]*W[a]*(Cy*Dz*f9); I[138] += C[3]*W[a]*(Cy*Dz*Ix*f9); I[139] += C[1]*W[a]*(Cy*Ix*f9); I[140] += C[0]*W[a]*(Cy*f9); I[141] += C[1]*W[a]*(Cy*Iz*f9); I[142] += C[1]*W[a]*(Cy*Iz*Px); I[143] += C[0]*W[a]*(Cy*Px); I[144] += C[2]*W[a]*(Cy*Dz*Px); I[145] += C[3]*W[a]*(Dz*Px*f23); I[146] += C[1]*W[a]*(Px*f23); I[147] += C[3]*W[a]*(f2*f23); I[148] += C[3]*W[a]*(Dz*f4); I[149] += C[3]*W[a]*(Dz*f21); I[150] += C[3]*W[a]*(Dx*f21); I[151] += C[3]*W[a]*(Dx*f7); I[152] += C[3]*W[a]*(Dy*f7); I[153] += C[3]*W[a]*(Dy*f4); I[154] += C[1]*W[a]*(f4); I[155] += C[1]*W[a]*(f21); I[156] += C[1]*W[a]*(f7); I[157] += C[2]*W[a]*(f8); I[158] += C[2]*W[a]*(f30); I[159] += C[2]*W[a]*(f3); } #undef B00 #undef B10 #undef B01 #undef Cx #undef Cy #undef Cz #undef Dx #undef Dy #undef Dz #undef pow } static inline void reorder(double (&I)[160]) { double T[160]; for (int i = 0; i < 160; ++i) { T[i] = I[i]; } I[101] = T[0]; I[54] = T[1]; I[53] = T[2]; I[59] = T[3]; I[55] = T[4]; I[57] = T[5]; I[50] = T[6]; I[152] = T[7]; I[158] = T[8]; I[157] = T[9]; I[159] = T[10]; I[154] = T[11]; I[156] = T[12]; I[102] = T[13]; I[104] = T[14]; I[100] = T[15]; I[107] = T[16]; I[139] = T[17]; I[19] = T[18]; I[99] = T[19]; I[119] = T[20]; I[76] = T[21]; I[56] = T[22]; I[52] = T[23]; I[51] = T[24]; I[58] = T[25]; I[79] = T[26]; I[39] = T[27]; I[114] = T[28]; I[34] = T[29]; I[36] = T[30]; I[74] = T[31]; I[116] = T[32]; I[133] = T[33]; I[136] = T[34]; I[138] = T[35]; I[129] = T[36]; I[109] = T[37]; I[89] = T[38]; I[69] = T[39]; I[49] = T[40]; I[9] = T[41]; I[29] = T[42]; I[149] = T[43]; I[150] = T[44]; I[151] = T[45]; I[153] = T[46]; I[137] = T[47]; I[95] = T[48]; I[97] = T[49]; I[17] = T[50]; I[15] = T[51]; I[135] = T[52]; I[125] = T[53]; I[155] = T[54]; I[105] = T[55]; I[106] = T[56]; I[108] = T[57]; I[103] = T[58]; I[144] = T[59]; I[124] = T[60]; I[126] = T[61]; I[77] = T[62]; I[65] = T[63]; I[67] = T[64]; I[47] = T[65]; I[68] = T[66]; I[28] = T[67]; I[63] = T[68]; I[73] = T[69]; I[43] = T[70]; I[78] = T[71]; I[38] = T[72]; I[118] = T[73]; I[93] = T[74]; I[113] = T[75]; I[83] = T[76]; I[84] = T[77]; I[92] = T[78]; I[82] = T[79]; I[94] = T[80]; I[14] = T[81]; I[44] = T[82]; I[64] = T[83]; I[24] = T[84]; I[4] = T[85]; I[96] = T[86]; I[86] = T[87]; I[115] = T[88]; I[85] = T[89]; I[147] = T[90]; I[127] = T[91]; I[128] = T[92]; I[13] = T[93]; I[134] = T[94]; I[132] = T[95]; I[91] = T[96]; I[111] = T[97]; I[70] = T[98]; I[60] = T[99]; I[142] = T[100]; I[140] = T[101]; I[120] = T[102]; I[145] = T[103]; I[25] = T[104]; I[146] = T[105]; I[26] = T[106]; I[66] = T[107]; I[46] = T[108]; I[42] = T[109]; I[62] = T[110]; I[22] = T[111]; I[2] = T[112]; I[12] = T[113]; I[16] = T[114]; I[6] = T[115]; I[45] = T[116]; I[75] = T[117]; I[35] = T[118]; I[5] = T[119]; I[37] = T[120]; I[117] = T[121]; I[87] = T[122]; I[80] = T[123]; I[110] = T[124]; I[30] = T[125]; I[0] = T[126]; I[20] = T[127]; I[27] = T[128]; I[7] = T[129]; I[88] = T[130]; I[98] = T[131]; I[18] = T[132]; I[8] = T[133]; I[48] = T[134]; I[71] = T[135]; I[41] = T[136]; I[121] = T[137]; I[131] = T[138]; I[11] = T[139]; I[1] = T[140]; I[31] = T[141]; I[33] = T[142]; I[3] = T[143]; I[123] = T[144]; I[143] = T[145]; I[23] = T[146]; I[148] = T[147]; I[130] = T[148]; I[141] = T[149]; I[61] = T[150]; I[72] = T[151]; I[112] = T[152]; I[90] = T[153]; I[10] = T[154]; I[21] = T[155]; I[32] = T[156]; I[40] = T[157]; I[81] = T[158]; I[122] = T[159]; } }; template<> struct impl > { typedef void enable; static const bool value = true; static inline void eval(double A, double B, const Vector<3> &rAi, const Vector<3> &rBk, const Vector<3> &rAB, const Vector<3> &rij, const Vector<3> &rkl, const Vector<3> &t2, const Vector<3> &W, const double (&C)[2], double (&I)[72]) { #define pow(x,y) util::pow<(y)>::eval((x)) const int N = 3; double xkl = rkl[0]; double ykl = rkl[1]; double zkl = rkl[2]; // // double vB00[N] __attribute__ ((aligned(16))); // // // double vB10[N] __attribute__ ((aligned(16))); // // // double vB01[N] __attribute__ ((aligned(16))); // // // double vCx[N] __attribute__ ((aligned(16))); // double vCy[N] __attribute__ ((aligned(16))); // double vCz[N] __attribute__ ((aligned(16))); // // // double vDx[N] __attribute__ ((aligned(16))); // double vDy[N] __attribute__ ((aligned(16))); // double vDz[N] __attribute__ ((aligned(16))); // // for (int a = 0; a < N; ++a) { // // vB00[a] = 0.5*t2[a]; // // // vB10[a] = recurrence::coefficient(1.0/A, B, t2[a]); // // // vB01[a] = recurrence::coefficient(1.0/B, A, t2[a]); // // // vCx[a] = recurrence::coefficient<0>(rAi, B, rAB, t2[a]); // vCy[a] = recurrence::coefficient<1>(rAi, B, rAB, t2[a]); // vCz[a] = recurrence::coefficient<2>(rAi, B, rAB, t2[a]); // // // vDx[a] = recurrence::coefficient<0>(rBk, -A, rAB, t2[a]); // vDy[a] = recurrence::coefficient<1>(rBk, -A, rAB, t2[a]); // vDz[a] = recurrence::coefficient<2>(rBk, -A, rAB, t2[a]); // // } // #define B00 vB00[a] // #define B10 vB10[a] // #define B01 vB01[a] // #define Cx vCx[a] // #define Cy vCy[a] // #define Cz vCz[a] // #define Dx vDx[a] // #define Dy vDy[a] // #define Dz vDz[a] #if defined (__INTEL_COMPILER) #pragma ivdep #pragma vector aligned #endif for (int a = 0; a < N; ++a) { double B00 = 0.5*t2[a]; double B10 = recurrence::coefficient(1.0/A, B, t2[a]); double B01 = recurrence::coefficient(1.0/B, A, t2[a]); double Cx = recurrence::coefficient<0>(rAi, B, rAB, t2[a]); double Cy = recurrence::coefficient<1>(rAi, B, rAB, t2[a]); double Cz = recurrence::coefficient<2>(rAi, B, rAB, t2[a]); double Dx = recurrence::coefficient<0>(rBk, -A, rAB, t2[a]); double Dy = recurrence::coefficient<1>(rBk, -A, rAB, t2[a]); double Dz = recurrence::coefficient<2>(rBk, -A, rAB, t2[a]); double Kx = (xkl + Dx); double Ky = (ykl + Dy); double Kz = (Dz + zkl); double Px = (B10 + pow(Cx,2)); double Py = (B10 + pow(Cy,2)); double Pz = (B10 + pow(Cz,2)); double Qx = (Cx*Dx + B00); double Qy = (Cy*Dy + B00); double Qz = (Cz*Dz + B00); double f0 = (Dy*Py + 2*B00*Cy); double f1 = (Dz*Pz + 2*B00*Cz); double f10 = B01*B10; double f13 = (Dx*Px + 2*B00*Cx); double f15 = (Dz*Kz + B01); double f16 = (B00 + Cx*Kx); double f17 = (B00 + Cy*Ky); double f19 = 2*pow(B00,2); double f2 = (Cy*Dy*Ky + B01*Cy + B00*(ykl + 2*Dy)); double f21 = (B01 + Dy*Ky); double f4 = (B01*Cx + Cx*Dx*Kx + B00*(xkl + 2*Dx)); double f6 = (B01*Cz + B00*(2*Dz + zkl) + Cz*Dz*Kz); double f7 = (B01 + Dx*Kx); double f9 = (Kx*Px + 2*B00*Cx); I[0] += C[1]*W[a]*((B01*pow(Cx,2) + f10 + f19 + 2*B00*Cx*(xkl + 2*Dx) + Dx*Kx*Px)); I[1] += C[1]*W[a]*((f10 + f19 + B01*pow(Cz,2) + Dz*Kz*Pz + 2*B00*Cz*(2*Dz + zkl))); I[2] += C[1]*W[a]*((f10 + f19 + Dy*Ky*Py + B01*pow(Cy,2) + 2*B00*Cy*(ykl + 2*Dy))); I[3] += C[1]*W[a]*(Dx*(f0 + Py*ykl)); I[4] += C[1]*W[a]*(Dz*(f0 + Py*ykl)); I[5] += C[0]*W[a]*((f0 + Py*ykl)); I[6] += C[1]*W[a]*(Dy*(Pz*zkl + f1)); I[7] += C[1]*W[a]*(Dx*(Pz*zkl + f1)); I[8] += C[0]*W[a]*((Pz*zkl + f1)); I[9] += C[1]*W[a]*(Cx*Cz*f21); I[10] += C[1]*W[a]*(Cx*Ky*Qz); I[11] += C[1]*W[a]*(Cy*Kx*Qz); I[12] += C[1]*W[a]*(Cy*Kz*Qx); I[13] += C[1]*W[a]*(Dy*Kz*Px); I[14] += C[1]*W[a]*(Cx*Kz*Qy); I[15] += C[0]*W[a]*(Cx*Cy*Kz); I[16] += C[1]*W[a]*(Cx*Cy*f15); I[17] += C[1]*W[a]*(Cy*Cz*f7); I[18] += C[0]*W[a]*(Cy*Cz*Kx); I[19] += C[1]*W[a]*(Cz*Kx*Qy); I[20] += C[1]*W[a]*(Qy*(Cz*zkl + Qz)); I[21] += C[1]*W[a]*(Cy*Dx*(Cz*zkl + Qz)); I[22] += C[0]*W[a]*(Cy*(Cz*zkl + Qz)); I[23] += C[1]*W[a]*(Cx*Dy*(Cz*zkl + Qz)); I[24] += C[0]*W[a]*(Cx*(Cz*zkl + Qz)); I[25] += C[1]*W[a]*(Qx*(Cz*zkl + Qz)); I[26] += C[1]*W[a]*(Cz*Ky*Qx); I[27] += C[0]*W[a]*(Cx*Cz*Ky); I[28] += C[1]*W[a]*(Ky*f13); I[29] += C[1]*W[a]*(Qx*f17); I[30] += C[1]*W[a]*(Kx*f0); I[31] += C[1]*W[a]*(Kx*f1); I[32] += C[1]*W[a]*(Ky*f1); I[33] += C[1]*W[a]*(Qy*f16); I[34] += C[1]*W[a]*(Qz*f16); I[35] += C[1]*W[a]*(Qz*f17); I[36] += C[1]*W[a]*(Dx*Kz*Py); I[37] += C[0]*W[a]*(Kz*Py); I[38] += C[1]*W[a]*(Kz*f13); I[39] += C[1]*W[a]*(Kz*f0); I[40] += C[0]*W[a]*(Kz*Px); I[41] += C[1]*W[a]*(Px*f21); I[42] += C[1]*W[a]*(Pz*f21); I[43] += C[1]*W[a]*(Pz*f7); I[44] += C[1]*W[a]*(Py*f7); I[45] += C[1]*W[a]*(Dz*Kx*Py); I[46] += C[0]*W[a]*(Kx*Py); I[47] += C[1]*W[a]*(Dy*Kx*Pz); I[48] += C[0]*W[a]*(Kx*Pz); I[49] += C[1]*W[a]*(Dx*Ky*Pz); I[50] += C[0]*W[a]*(Ky*Pz); I[51] += C[1]*W[a]*(Dz*Ky*Px); I[52] += C[0]*W[a]*(Ky*Px); I[53] += C[1]*W[a]*(Px*f15); I[54] += C[1]*W[a]*(Py*f15); I[55] += C[1]*W[a]*(Cx*f2); I[56] += C[1]*W[a]*(Cz*f2); I[57] += C[1]*W[a]*(Cz*f4); I[58] += C[1]*W[a]*(Cy*f4); I[59] += C[1]*W[a]*(Cy*Dz*f16); I[60] += C[0]*W[a]*(Cy*f16); I[61] += C[1]*W[a]*(Cz*Dy*f16); I[62] += C[0]*W[a]*(Cz*f16); I[63] += C[1]*W[a]*(Cz*Dx*f17); I[64] += C[0]*W[a]*(Cz*f17); I[65] += C[1]*W[a]*(Cx*Dz*f17); I[66] += C[0]*W[a]*(Cx*f17); I[67] += C[1]*W[a]*(Cx*f6); I[68] += C[1]*W[a]*(Cy*f6); I[69] += C[1]*W[a]*(Dz*f9); I[70] += C[1]*W[a]*(Dy*f9); I[71] += C[0]*W[a]*(f9); } #undef B00 #undef B10 #undef B01 #undef Cx #undef Cy #undef Cz #undef Dx #undef Dy #undef Dz #undef pow } static inline void reorder(double (&I)[72]) { double T[72]; for (int i = 0; i < 72; ++i) { T[i] = I[i]; } I[6] = T[0]; I[68] = T[1]; I[37] = T[2]; I[31] = T[3]; I[43] = T[4]; I[25] = T[5]; I[62] = T[6]; I[56] = T[7]; I[50] = T[8]; I[40] = T[9]; I[46] = T[10]; I[23] = T[11]; I[57] = T[12]; I[60] = T[13]; I[63] = T[14]; I[51] = T[15]; I[69] = T[16]; I[11] = T[17]; I[5] = T[18]; I[17] = T[19]; I[65] = T[20]; I[59] = T[21]; I[53] = T[22]; I[64] = T[23]; I[52] = T[24]; I[58] = T[25]; I[34] = T[26]; I[28] = T[27]; I[30] = T[28]; I[33] = T[29]; I[13] = T[30]; I[20] = T[31]; I[44] = T[32]; I[15] = T[33]; I[22] = T[34]; I[47] = T[35]; I[55] = T[36]; I[49] = T[37]; I[54] = T[38]; I[61] = T[39]; I[48] = T[40]; I[36] = T[41]; I[38] = T[42]; I[8] = T[43]; I[7] = T[44]; I[19] = T[45]; I[1] = T[46]; I[14] = T[47]; I[2] = T[48]; I[32] = T[49]; I[26] = T[50]; I[42] = T[51]; I[24] = T[52]; I[66] = T[53]; I[67] = T[54]; I[39] = T[55]; I[41] = T[56]; I[10] = T[57]; I[9] = T[58]; I[21] = T[59]; I[3] = T[60]; I[16] = T[61]; I[4] = T[62]; I[35] = T[63]; I[29] = T[64]; I[45] = T[65]; I[27] = T[66]; I[70] = T[67]; I[71] = T[68]; I[18] = T[69]; I[12] = T[70]; I[0] = T[71]; } }; template<> struct impl > { typedef void enable; static const bool value = true; static inline void eval(double A, double B, const Vector<3> &rAi, const Vector<3> &rBk, const Vector<3> &rAB, const Vector<3> &rij, const Vector<3> &rkl, const Vector<2> &t2, const Vector<2> &W, const double (&C)[1], double (&I)[6]) { #define pow(x,y) util::pow<(y)>::eval((x)) const int N = 2; // // // double vB10[N] __attribute__ ((aligned(16))); // // // // double vCx[N] __attribute__ ((aligned(16))); // double vCy[N] __attribute__ ((aligned(16))); // double vCz[N] __attribute__ ((aligned(16))); // // // for (int a = 0; a < N; ++a) { // // // vB10[a] = recurrence::coefficient(1.0/A, B, t2[a]); // // // // vCx[a] = recurrence::coefficient<0>(rAi, B, rAB, t2[a]); // vCy[a] = recurrence::coefficient<1>(rAi, B, rAB, t2[a]); // vCz[a] = recurrence::coefficient<2>(rAi, B, rAB, t2[a]); // // // } // #define B00 vB00[a] // #define B10 vB10[a] // #define B01 vB01[a] // #define Cx vCx[a] // #define Cy vCy[a] // #define Cz vCz[a] // #define Dx vDx[a] // #define Dy vDy[a] // #define Dz vDz[a] #if defined (__INTEL_COMPILER) #pragma ivdep #pragma vector aligned #endif for (int a = 0; a < N; ++a) { double B10 = recurrence::coefficient(1.0/A, B, t2[a]); double Cx = recurrence::coefficient<0>(rAi, B, rAB, t2[a]); double Cy = recurrence::coefficient<1>(rAi, B, rAB, t2[a]); double Cz = recurrence::coefficient<2>(rAi, B, rAB, t2[a]); double Px = (B10 + pow(Cx,2)); double Py = (B10 + pow(Cy,2)); double Pz = (B10 + pow(Cz,2)); I[0] += C[0]*W[a]*(Py); I[1] += C[0]*W[a]*(Pz); I[2] += C[0]*W[a]*(Px); I[3] += C[0]*W[a]*(Cx*Cy); I[4] += C[0]*W[a]*(Cx*Cz); I[5] += C[0]*W[a]*(Cy*Cz); } #undef B00 #undef B10 #undef B01 #undef Cx #undef Cy #undef Cz #undef Dx #undef Dy #undef Dz #undef pow } static inline void reorder(double (&I)[6]) { double T[6]; for (int i = 0; i < 6; ++i) { T[i] = I[i]; } I[1] = T[0]; I[2] = T[1]; I[0] = T[2]; I[3] = T[3]; I[4] = T[4]; I[5] = T[5]; } }; template<> struct impl > { typedef void enable; static const bool value = true; static inline void eval(double A, double B, const Vector<3> &rAi, const Vector<3> &rBk, const Vector<3> &rAB, const Vector<3> &rij, const Vector<3> &rkl, const Vector<0> &t2, const Vector<1> &W, const double (&C)[1], double (&I)[1]) { #define pow(x,y) util::pow<(y)>::eval((x)) const int N = 1; // // // // // // for (int a = 0; a < N; ++a) { // // // // // // } // #define B00 vB00[a] // #define B10 vB10[a] // #define B01 vB01[a] // #define Cx vCx[a] // #define Cy vCy[a] // #define Cz vCz[a] // #define Dx vDx[a] // #define Dy vDy[a] // #define Dz vDz[a] #if defined (__INTEL_COMPILER) #pragma ivdep #pragma vector aligned #endif for (int a = 0; a < N; ++a) { I[0] += C[0]*W[a]*(1); } #undef B00 #undef B10 #undef B01 #undef Cx #undef Cy #undef Cz #undef Dx #undef Dy #undef Dz #undef pow } static inline void reorder(double (&I)[1]) { double T[1]; for (int i = 0; i < 1; ++i) { T[i] = I[i]; } I[0] = T[0]; } }; template<> struct impl > { typedef void enable; static const bool value = true; static inline void eval(double A, double B, const Vector<3> &rAi, const Vector<3> &rBk, const Vector<3> &rAB, const Vector<3> &rij, const Vector<3> &rkl, const Vector<3> &t2, const Vector<3> &W, const double (&C)[1], double (&I)[90]) { #define pow(x,y) util::pow<(y)>::eval((x)) const int N = 3; double xkl = rkl[0]; double ykl = rkl[1]; double zkl = rkl[2]; // // double vB00[N] __attribute__ ((aligned(16))); // // // double vB10[N] __attribute__ ((aligned(16))); // // // double vB01[N] __attribute__ ((aligned(16))); // // // double vCx[N] __attribute__ ((aligned(16))); // double vCy[N] __attribute__ ((aligned(16))); // double vCz[N] __attribute__ ((aligned(16))); // // // double vDx[N] __attribute__ ((aligned(16))); // double vDy[N] __attribute__ ((aligned(16))); // double vDz[N] __attribute__ ((aligned(16))); // // for (int a = 0; a < N; ++a) { // // vB00[a] = 0.5*t2[a]; // // // vB10[a] = recurrence::coefficient(1.0/A, B, t2[a]); // // // vB01[a] = recurrence::coefficient(1.0/B, A, t2[a]); // // // vCx[a] = recurrence::coefficient<0>(rAi, B, rAB, t2[a]); // vCy[a] = recurrence::coefficient<1>(rAi, B, rAB, t2[a]); // vCz[a] = recurrence::coefficient<2>(rAi, B, rAB, t2[a]); // // // vDx[a] = recurrence::coefficient<0>(rBk, -A, rAB, t2[a]); // vDy[a] = recurrence::coefficient<1>(rBk, -A, rAB, t2[a]); // vDz[a] = recurrence::coefficient<2>(rBk, -A, rAB, t2[a]); // // } // #define B00 vB00[a] // #define B10 vB10[a] // #define B01 vB01[a] // #define Cx vCx[a] // #define Cy vCy[a] // #define Cz vCz[a] // #define Dx vDx[a] // #define Dy vDy[a] // #define Dz vDz[a] #if defined (__INTEL_COMPILER) #pragma ivdep #pragma vector aligned #endif for (int a = 0; a < N; ++a) { double B00 = 0.5*t2[a]; double B10 = recurrence::coefficient(1.0/A, B, t2[a]); double B01 = recurrence::coefficient(1.0/B, A, t2[a]); double Cx = recurrence::coefficient<0>(rAi, B, rAB, t2[a]); double Cy = recurrence::coefficient<1>(rAi, B, rAB, t2[a]); double Cz = recurrence::coefficient<2>(rAi, B, rAB, t2[a]); double Dx = recurrence::coefficient<0>(rBk, -A, rAB, t2[a]); double Dy = recurrence::coefficient<1>(rBk, -A, rAB, t2[a]); double Dz = recurrence::coefficient<2>(rBk, -A, rAB, t2[a]); double Kx = (xkl + Dx); double Ky = (ykl + Dy); double Kz = (Dz + zkl); double Px = (B10 + pow(Cx,2)); double Py = (B10 + pow(Cy,2)); double Pz = (B10 + pow(Cz,2)); double Qx = (Cx*Dx + B00); double Qy = (Cy*Dy + B00); double Qz = (Cz*Dz + B00); double f0 = (3*B10 + pow(Cx,2)); double f1 = (Cx*Kx*(3*B10 + pow(Cx,2)) + 3*B00*Px); double f10 = (Cz*Kz*(3*B10 + pow(Cz,2)) + 3*B00*Pz); double f11 = (B01*Cz + B00*(2*Dz + zkl) + Cz*Dz*Kz); double f12 = (B01 + Dx*Kx); double f14 = (3*B00*Pz + Cz*Dz*(3*B10 + pow(Cz,2))); double f15 = (Kx*Px + 2*B00*Cx); double f16 = (Dy*Py + 2*B00*Cy); double f17 = (2*pow(B00,2) + Pz*(Dz*Kz + B01) + 2*B00*Cz*(2*Dz + zkl)); double f2 = (Dz*Pz + 2*B00*Cz); double f20 = (Dx*Px + 2*B00*Cx); double f22 = (Dz*Kz + B01); double f23 = (B00 + Cx*Kx); double f29 = (Cx*Dx*(3*B10 + pow(Cx,2)) + 3*B00*Px); double f3 = (Py*(B01 + Dy*Ky) + 2*pow(B00,2) + 2*B00*Cy*(ykl + 2*Dy)); double f30 = (B01 + Dy*Ky); double f31 = (3*B10 + pow(Cz,2)); double f32 = (3*B10 + pow(Cy,2)); double f4 = (Cy*Dy*Ky + B01*Cy + B00*(ykl + 2*Dy)); double f5 = (3*B00*Py + Cy*Ky*(3*B10 + pow(Cy,2))); double f6 = (Cy*Dy*(3*B10 + pow(Cy,2)) + 3*B00*Py); double f7 = (B01*Cx + Cx*Dx*Kx + B00*(xkl + 2*Dx)); double f9 = (2*B00*Cx*(xkl + 2*Dx) + 2*pow(B00,2) + Px*(B01 + Dx*Kx)); I[0] += C[0]*W[a]*((3*B00*Px*(xkl + 2*Dx) + Cx*f0*(B01 + Dx*Kx) + 6*Cx*pow(B00,2))); I[1] += C[0]*W[a]*((6*Cy*pow(B00,2) + 3*B00*Py*(ykl + 2*Dy) + Cy*f32*(B01 + Dy*Ky))); I[2] += C[0]*W[a]*((Cz*f31*(Dz*Kz + B01) + 3*B00*Pz*(2*Dz + zkl) + 6*Cz*pow(B00,2))); I[3] += C[0]*W[a]*(Dx*Py*(Cz*zkl + Qz)); I[4] += C[0]*W[a]*(Cy*Qx*(Cz*zkl + Qz)); I[5] += C[0]*W[a]*(Dy*Px*(Cz*zkl + Qz)); I[6] += C[0]*W[a]*(Cx*Dy*(Pz*zkl + f2)); I[7] += C[0]*W[a]*(Cy*Dx*(Pz*zkl + f2)); I[8] += C[0]*W[a]*(Qx*(Pz*zkl + f2)); I[9] += C[0]*W[a]*(Qy*(Pz*zkl + f2)); I[10] += C[0]*W[a]*(Cx*Qy*(Cz*zkl + Qz)); I[11] += C[0]*W[a]*(Cx*Qz*(Cy*ykl + Qy)); I[12] += C[0]*W[a]*(Dz*Px*(Cy*ykl + Qy)); I[13] += C[0]*W[a]*(Cx*Dz*(f16 + Py*ykl)); I[14] += C[0]*W[a]*(Cz*Dx*(f16 + Py*ykl)); I[15] += C[0]*W[a]*(Qz*(f16 + Py*ykl)); I[16] += C[0]*W[a]*(Qx*(f16 + Py*ykl)); I[17] += C[0]*W[a]*(Cz*Qx*(Cy*ykl + Qy)); I[18] += C[0]*W[a]*(Dx*Pz*(Cy*ykl + Qy)); I[19] += C[0]*W[a]*(Cy*Dx*Kz*f32); I[20] += C[0]*W[a]*(Cx*Dz*Ky*f0); I[21] += C[0]*W[a]*(Cx*Dy*Kz*f0); I[22] += C[0]*W[a]*(Cx*Cz*f4); I[23] += C[0]*W[a]*(Cy*Qz*f23); I[24] += C[0]*W[a]*(Ky*Px*Qz); I[25] += C[0]*W[a]*(Cx*Ky*f2); I[26] += C[0]*W[a]*(Ky*Pz*Qx); I[27] += C[0]*W[a]*(Kz*Py*Qx); I[28] += C[0]*W[a]*(Kz*Px*Qy); I[29] += C[0]*W[a]*(Cx*Kz*f16); I[30] += C[0]*W[a]*(Cy*Kz*f20); I[31] += C[0]*W[a]*(f20*(Cy*ykl + Qy)); I[32] += C[0]*W[a]*(f2*(Cy*ykl + Qy)); I[33] += C[0]*W[a]*(Cy*Kx*f2); I[34] += C[0]*W[a]*(Kx*Py*Qz); I[35] += C[0]*W[a]*(Dz*Py*f23); I[36] += C[0]*W[a]*(Cz*Qy*f23); I[37] += C[0]*W[a]*(Cy*Cz*f7); I[38] += C[0]*W[a]*(Cy*Dz*f15); I[39] += C[0]*W[a]*(Cy*Dz*Kx*f32); I[40] += C[0]*W[a]*(Cy*f22*f32); I[41] += C[0]*W[a]*(Cy*Px*f22); I[42] += C[0]*W[a]*(Cz*Px*f30); I[43] += C[0]*W[a]*(Cz*f30*f31); I[44] += C[0]*W[a]*(Cz*Dx*Ky*f31); I[45] += C[0]*W[a]*(Cz*Ky*f20); I[46] += C[0]*W[a]*(f20*(Cz*zkl + Qz)); I[47] += C[0]*W[a]*(f16*(Cz*zkl + Qz)); I[48] += C[0]*W[a]*(Cz*Kx*f16); I[49] += C[0]*W[a]*(Kx*Pz*Qy); I[50] += C[0]*W[a]*(Dy*Pz*f23); I[51] += C[0]*W[a]*(Cx*Pz*f30); I[52] += C[0]*W[a]*(Cx*f0*f30); I[53] += C[0]*W[a]*(Cx*f0*f22); I[54] += C[0]*W[a]*(Cx*Py*f22); I[55] += C[0]*W[a]*(Cx*Cy*f11); I[56] += C[0]*W[a]*(Cy*Pz*f12); I[57] += C[0]*W[a]*(Cy*f12*f32); I[58] += C[0]*W[a]*(Cz*Py*f12); I[59] += C[0]*W[a]*(Cz*f12*f31); I[60] += C[0]*W[a]*(Cz*Dy*Kx*f31); I[61] += C[0]*W[a]*(Cz*Dy*f15); I[62] += C[0]*W[a]*(Qy*f15); I[63] += C[0]*W[a]*(Qz*f15); I[64] += C[0]*W[a]*(f16*f23); I[65] += C[0]*W[a]*(f2*f23); I[66] += C[0]*W[a]*(Kx*f6); I[67] += C[0]*W[a]*(Kx*f14); I[68] += C[0]*W[a]*(Ky*f14); I[69] += C[0]*W[a]*(Ky*f29); I[70] += C[0]*W[a]*(Kz*f29); I[71] += C[0]*W[a]*(Kz*f6); I[72] += C[0]*W[a]*(Dx*f10); I[73] += C[0]*W[a]*(Dx*f5); I[74] += C[0]*W[a]*(Dz*f5); I[75] += C[0]*W[a]*(Dz*f1); I[76] += C[0]*W[a]*(Dy*f1); I[77] += C[0]*W[a]*(Dy*f10); I[78] += C[0]*W[a]*(Py*f7); I[79] += C[0]*W[a]*(Pz*f7); I[80] += C[0]*W[a]*(Pz*f4); I[81] += C[0]*W[a]*(Px*f4); I[82] += C[0]*W[a]*(Px*f11); I[83] += C[0]*W[a]*(Py*f11); I[84] += C[0]*W[a]*(Cy*f9); I[85] += C[0]*W[a]*(Cz*f9); I[86] += C[0]*W[a]*(Cz*f3); I[87] += C[0]*W[a]*(Cx*f3); I[88] += C[0]*W[a]*(Cx*f17); I[89] += C[0]*W[a]*(Cy*f17); } #undef B00 #undef B10 #undef B01 #undef Cx #undef Cy #undef Cz #undef Dx #undef Dy #undef Dz #undef pow } static inline void reorder(double (&I)[90]) { double T[90]; for (int i = 0; i < 90; ++i) { T[i] = I[i]; } I[0] = T[0]; I[41] = T[1]; I[82] = T[2]; I[66] = T[3]; I[69] = T[4]; I[74] = T[5]; I[77] = T[6]; I[68] = T[7]; I[67] = T[8]; I[78] = T[9]; I[79] = T[10]; I[59] = T[11]; I[53] = T[12]; I[55] = T[13]; I[36] = T[14]; I[56] = T[15]; I[35] = T[16]; I[39] = T[17]; I[38] = T[18]; I[61] = T[19]; I[50] = T[20]; I[70] = T[21]; I[49] = T[22]; I[29] = T[23]; I[54] = T[24]; I[57] = T[25]; I[37] = T[26]; I[65] = T[27]; I[73] = T[28]; I[75] = T[29]; I[63] = T[30]; I[33] = T[31]; I[58] = T[32]; I[28] = T[33]; I[26] = T[34]; I[25] = T[35]; I[19] = T[36]; I[9] = T[37]; I[23] = T[38]; I[21] = T[39]; I[81] = T[40]; I[83] = T[41]; I[44] = T[42]; I[42] = T[43]; I[32] = T[44]; I[34] = T[45]; I[64] = T[46]; I[76] = T[47]; I[16] = T[48]; I[18] = T[49]; I[17] = T[50]; I[47] = T[51]; I[40] = T[52]; I[80] = T[53]; I[85] = T[54]; I[89] = T[55]; I[8] = T[56]; I[1] = T[57]; I[6] = T[58]; I[2] = T[59]; I[12] = T[60]; I[14] = T[61]; I[13] = T[62]; I[24] = T[63]; I[15] = T[64]; I[27] = T[65]; I[11] = T[66]; I[22] = T[67]; I[52] = T[68]; I[30] = T[69]; I[60] = T[70]; I[71] = T[71]; I[62] = T[72]; I[31] = T[73]; I[51] = T[74]; I[20] = T[75]; I[10] = T[76]; I[72] = T[77]; I[5] = T[78]; I[7] = T[79]; I[48] = T[80]; I[43] = T[81]; I[84] = T[82]; I[86] = T[83]; I[3] = T[84]; I[4] = T[85]; I[46] = T[86]; I[45] = T[87]; I[87] = T[88]; I[88] = T[89]; } }; template<> struct impl > { typedef void enable; static const bool value = true; static inline void eval(double A, double B, const Vector<3> &rAi, const Vector<3> &rBk, const Vector<3> &rAB, const Vector<3> &rij, const Vector<3> &rkl, const Vector<2> &t2, const Vector<2> &W, const double (&C)[1], double (&I)[18]) { #define pow(x,y) util::pow<(y)>::eval((x)) const int N = 2; // // double vB00[N] __attribute__ ((aligned(16))); // // // double vB10[N] __attribute__ ((aligned(16))); // // // // double vCx[N] __attribute__ ((aligned(16))); // double vCy[N] __attribute__ ((aligned(16))); // double vCz[N] __attribute__ ((aligned(16))); // // // double vDx[N] __attribute__ ((aligned(16))); // double vDy[N] __attribute__ ((aligned(16))); // double vDz[N] __attribute__ ((aligned(16))); // // for (int a = 0; a < N; ++a) { // // vB00[a] = 0.5*t2[a]; // // // vB10[a] = recurrence::coefficient(1.0/A, B, t2[a]); // // // // vCx[a] = recurrence::coefficient<0>(rAi, B, rAB, t2[a]); // vCy[a] = recurrence::coefficient<1>(rAi, B, rAB, t2[a]); // vCz[a] = recurrence::coefficient<2>(rAi, B, rAB, t2[a]); // // // vDx[a] = recurrence::coefficient<0>(rBk, -A, rAB, t2[a]); // vDy[a] = recurrence::coefficient<1>(rBk, -A, rAB, t2[a]); // vDz[a] = recurrence::coefficient<2>(rBk, -A, rAB, t2[a]); // // } // #define B00 vB00[a] // #define B10 vB10[a] // #define B01 vB01[a] // #define Cx vCx[a] // #define Cy vCy[a] // #define Cz vCz[a] // #define Dx vDx[a] // #define Dy vDy[a] // #define Dz vDz[a] #if defined (__INTEL_COMPILER) #pragma ivdep #pragma vector aligned #endif for (int a = 0; a < N; ++a) { double B00 = 0.5*t2[a]; double B10 = recurrence::coefficient(1.0/A, B, t2[a]); double Cx = recurrence::coefficient<0>(rAi, B, rAB, t2[a]); double Cy = recurrence::coefficient<1>(rAi, B, rAB, t2[a]); double Cz = recurrence::coefficient<2>(rAi, B, rAB, t2[a]); double Dx = recurrence::coefficient<0>(rBk, -A, rAB, t2[a]); double Dy = recurrence::coefficient<1>(rBk, -A, rAB, t2[a]); double Dz = recurrence::coefficient<2>(rBk, -A, rAB, t2[a]); double Px = (B10 + pow(Cx,2)); double Py = (B10 + pow(Cy,2)); double Pz = (B10 + pow(Cz,2)); double Qx = (Cx*Dx + B00); double Qy = (Cy*Dy + B00); double Qz = (Cz*Dz + B00); I[0] += C[0]*W[a]*((Dx*Px + 2*B00*Cx)); I[1] += C[0]*W[a]*((Dy*Py + 2*B00*Cy)); I[2] += C[0]*W[a]*((Dz*Pz + 2*B00*Cz)); I[3] += C[0]*W[a]*(Cx*Cz*Dy); I[4] += C[0]*W[a]*(Cx*Cy*Dz); I[5] += C[0]*W[a]*(Cy*Cz*Dx); I[6] += C[0]*W[a]*(Dx*Py); I[7] += C[0]*W[a]*(Dx*Pz); I[8] += C[0]*W[a]*(Dy*Pz); I[9] += C[0]*W[a]*(Dy*Px); I[10] += C[0]*W[a]*(Dz*Px); I[11] += C[0]*W[a]*(Dz*Py); I[12] += C[0]*W[a]*(Cy*Qx); I[13] += C[0]*W[a]*(Cz*Qx); I[14] += C[0]*W[a]*(Cz*Qy); I[15] += C[0]*W[a]*(Cx*Qy); I[16] += C[0]*W[a]*(Cx*Qz); I[17] += C[0]*W[a]*(Cy*Qz); } #undef B00 #undef B10 #undef B01 #undef Cx #undef Cy #undef Cz #undef Dx #undef Dy #undef Dz #undef pow } static inline void reorder(double (&I)[18]) { double T[18]; for (int i = 0; i < 18; ++i) { T[i] = I[i]; } I[0] = T[0]; I[7] = T[1]; I[14] = T[2]; I[10] = T[3]; I[15] = T[4]; I[5] = T[5]; I[1] = T[6]; I[2] = T[7]; I[8] = T[8]; I[6] = T[9]; I[12] = T[10]; I[13] = T[11]; I[3] = T[12]; I[4] = T[13]; I[11] = T[14]; I[9] = T[15]; I[16] = T[16]; I[17] = T[17]; } }; template<> struct impl > { typedef void enable; static const bool value = true; static inline void eval(double A, double B, const Vector<3> &rAi, const Vector<3> &rBk, const Vector<3> &rAB, const Vector<3> &rij, const Vector<3> &rkl, const Vector<1> &t2, const Vector<1> &W, const double (&C)[1], double (&I)[3]) { #define pow(x,y) util::pow<(y)>::eval((x)) const int N = 1; // // // // // double vCx[N] __attribute__ ((aligned(16))); // double vCy[N] __attribute__ ((aligned(16))); // double vCz[N] __attribute__ ((aligned(16))); // // // for (int a = 0; a < N; ++a) { // // // // // vCx[a] = recurrence::coefficient<0>(rAi, B, rAB, t2[a]); // vCy[a] = recurrence::coefficient<1>(rAi, B, rAB, t2[a]); // vCz[a] = recurrence::coefficient<2>(rAi, B, rAB, t2[a]); // // // } // #define B00 vB00[a] // #define B10 vB10[a] // #define B01 vB01[a] // #define Cx vCx[a] // #define Cy vCy[a] // #define Cz vCz[a] // #define Dx vDx[a] // #define Dy vDy[a] // #define Dz vDz[a] #if defined (__INTEL_COMPILER) #pragma ivdep #pragma vector aligned #endif for (int a = 0; a < N; ++a) { double Cx = recurrence::coefficient<0>(rAi, B, rAB, t2[a]); double Cy = recurrence::coefficient<1>(rAi, B, rAB, t2[a]); double Cz = recurrence::coefficient<2>(rAi, B, rAB, t2[a]); I[0] += C[0]*W[a]*(Cx); I[1] += C[0]*W[a]*(Cy); I[2] += C[0]*W[a]*(Cz); } #undef B00 #undef B10 #undef B01 #undef Cx #undef Cy #undef Cz #undef Dx #undef Dy #undef Dz #undef pow } static inline void reorder(double (&I)[3]) { double T[3]; for (int i = 0; i < 3; ++i) { T[i] = I[i]; } I[0] = T[0]; I[1] = T[1]; I[2] = T[2]; } }; template<> struct impl > { typedef void enable; static const bool value = true; static inline void eval(double A, double B, const Vector<3> &rAi, const Vector<3> &rBk, const Vector<3> &rAB, const Vector<3> &rij, const Vector<3> &rkl, const Vector<2> &t2, const Vector<2> &W, const double (&C)[2], double (&I)[24]) { #define pow(x,y) util::pow<(y)>::eval((x)) const int N = 2; double xij = rij[0]; double yij = rij[1]; double zij = rij[2]; // // // double vB10[N] __attribute__ ((aligned(16))); // // // // double vCx[N] __attribute__ ((aligned(16))); // double vCy[N] __attribute__ ((aligned(16))); // double vCz[N] __attribute__ ((aligned(16))); // // // for (int a = 0; a < N; ++a) { // // // vB10[a] = recurrence::coefficient(1.0/A, B, t2[a]); // // // // vCx[a] = recurrence::coefficient<0>(rAi, B, rAB, t2[a]); // vCy[a] = recurrence::coefficient<1>(rAi, B, rAB, t2[a]); // vCz[a] = recurrence::coefficient<2>(rAi, B, rAB, t2[a]); // // // } // #define B00 vB00[a] // #define B10 vB10[a] // #define B01 vB01[a] // #define Cx vCx[a] // #define Cy vCy[a] // #define Cz vCz[a] // #define Dx vDx[a] // #define Dy vDy[a] // #define Dz vDz[a] #if defined (__INTEL_COMPILER) #pragma ivdep #pragma vector aligned #endif for (int a = 0; a < N; ++a) { double B10 = recurrence::coefficient(1.0/A, B, t2[a]); double Cx = recurrence::coefficient<0>(rAi, B, rAB, t2[a]); double Cy = recurrence::coefficient<1>(rAi, B, rAB, t2[a]); double Cz = recurrence::coefficient<2>(rAi, B, rAB, t2[a]); double Ix = (Cx + xij); double Iy = (Cy + yij); double Iz = (Cz + zij); double Px = (B10 + pow(Cx,2)); double Py = (B10 + pow(Cy,2)); double Pz = (B10 + pow(Cz,2)); I[0] += C[1]*W[a]*(Iy*Px); I[1] += C[1]*W[a]*(Iy*Pz); I[2] += C[1]*W[a]*(Cx*Cz*Iy); I[3] += C[1]*W[a]*(Cy*Cz*Ix); I[4] += C[1]*W[a]*(Cy*(B10 + Cz*Iz)); I[5] += C[1]*W[a]*(Cz*(Cy*Iy + B10)); I[6] += C[1]*W[a]*(Cx*(Cy*Iy + B10)); I[7] += C[1]*W[a]*((B10*(3*Cy + yij) + Iy*pow(Cy,2))); I[8] += C[1]*W[a]*(Iz*Py); I[9] += C[1]*W[a]*(Cy*(Cx*Ix + B10)); I[10] += C[1]*W[a]*((B10*(3*Cx + xij) + Ix*pow(Cx,2))); I[11] += C[1]*W[a]*(Cz*(Cx*Ix + B10)); I[12] += C[1]*W[a]*(Cx*(B10 + Cz*Iz)); I[13] += C[1]*W[a]*((Iz*pow(Cz,2) + B10*(3*Cz + zij))); I[14] += C[1]*W[a]*(Ix*Pz); I[15] += C[1]*W[a]*(Ix*Py); I[16] += C[0]*W[a]*(Py); I[17] += C[0]*W[a]*(Pz); I[18] += C[0]*W[a]*(Px); I[19] += C[1]*W[a]*(Iz*Px); I[20] += C[1]*W[a]*(Cx*Cy*Iz); I[21] += C[0]*W[a]*(Cx*Cy); I[22] += C[0]*W[a]*(Cx*Cz); I[23] += C[0]*W[a]*(Cy*Cz); } #undef B00 #undef B10 #undef B01 #undef Cx #undef Cy #undef Cz #undef Dx #undef Dy #undef Dz #undef pow } static inline void reorder(double (&I)[24]) { double T[24]; for (int i = 0; i < 24; ++i) { T[i] = I[i]; } I[12] = T[0]; I[14] = T[1]; I[16] = T[2]; I[11] = T[3]; I[23] = T[4]; I[17] = T[5]; I[15] = T[6]; I[13] = T[7]; I[19] = T[8]; I[9] = T[9]; I[6] = T[10]; I[10] = T[11]; I[22] = T[12]; I[20] = T[13]; I[8] = T[14]; I[7] = T[15]; I[1] = T[16]; I[2] = T[17]; I[0] = T[18]; I[18] = T[19]; I[21] = T[20]; I[3] = T[21]; I[4] = T[22]; I[5] = T[23]; } }; template<> struct impl > { typedef void enable; static const bool value = true; static inline void eval(double A, double B, const Vector<3> &rAi, const Vector<3> &rBk, const Vector<3> &rAB, const Vector<3> &rij, const Vector<3> &rkl, const Vector<2> &t2, const Vector<2> &W, const double (&C)[4], double (&I)[16]) { #define pow(x,y) util::pow<(y)>::eval((x)) const int N = 2; // // double vB00[N] __attribute__ ((aligned(16))); // // // // // double vCx[N] __attribute__ ((aligned(16))); // double vCy[N] __attribute__ ((aligned(16))); // double vCz[N] __attribute__ ((aligned(16))); // // // double vDx[N] __attribute__ ((aligned(16))); // double vDy[N] __attribute__ ((aligned(16))); // double vDz[N] __attribute__ ((aligned(16))); // // for (int a = 0; a < N; ++a) { // // vB00[a] = 0.5*t2[a]; // // // // // vCx[a] = recurrence::coefficient<0>(rAi, B, rAB, t2[a]); // vCy[a] = recurrence::coefficient<1>(rAi, B, rAB, t2[a]); // vCz[a] = recurrence::coefficient<2>(rAi, B, rAB, t2[a]); // // // vDx[a] = recurrence::coefficient<0>(rBk, -A, rAB, t2[a]); // vDy[a] = recurrence::coefficient<1>(rBk, -A, rAB, t2[a]); // vDz[a] = recurrence::coefficient<2>(rBk, -A, rAB, t2[a]); // // } // #define B00 vB00[a] // #define B10 vB10[a] // #define B01 vB01[a] // #define Cx vCx[a] // #define Cy vCy[a] // #define Cz vCz[a] // #define Dx vDx[a] // #define Dy vDy[a] // #define Dz vDz[a] #if defined (__INTEL_COMPILER) #pragma ivdep #pragma vector aligned #endif for (int a = 0; a < N; ++a) { double B00 = 0.5*t2[a]; double Cx = recurrence::coefficient<0>(rAi, B, rAB, t2[a]); double Cy = recurrence::coefficient<1>(rAi, B, rAB, t2[a]); double Cz = recurrence::coefficient<2>(rAi, B, rAB, t2[a]); double Dx = recurrence::coefficient<0>(rBk, -A, rAB, t2[a]); double Dy = recurrence::coefficient<1>(rBk, -A, rAB, t2[a]); double Dz = recurrence::coefficient<2>(rBk, -A, rAB, t2[a]); double Qx = (Cx*Dx + B00); double Qy = (Cy*Dy + B00); double Qz = (Cz*Dz + B00); I[0] += C[3]*W[a]*(Qx); I[1] += C[3]*W[a]*(Qy); I[2] += C[3]*W[a]*(Qz); I[3] += C[3]*W[a]*(Cx*Dz); I[4] += C[3]*W[a]*(Cy*Dz); I[5] += C[3]*W[a]*(Cy*Dx); I[6] += C[3]*W[a]*(Cz*Dx); I[7] += C[3]*W[a]*(Cz*Dy); I[8] += C[3]*W[a]*(Cx*Dy); I[9] += C[1]*W[a]*(Cx); I[10] += C[1]*W[a]*(Cy); I[11] += C[1]*W[a]*(Cz); I[12] += C[2]*W[a]*(Dx); I[13] += C[2]*W[a]*(Dy); I[14] += C[2]*W[a]*(Dz); I[15] += C[0]*W[a]*(1); } #undef B00 #undef B10 #undef B01 #undef Cx #undef Cy #undef Cz #undef Dx #undef Dy #undef Dz #undef pow } static inline void reorder(double (&I)[16]) { double T[16]; for (int i = 0; i < 16; ++i) { T[i] = I[i]; } I[5] = T[0]; I[10] = T[1]; I[15] = T[2]; I[13] = T[3]; I[14] = T[4]; I[6] = T[5]; I[7] = T[6]; I[11] = T[7]; I[9] = T[8]; I[1] = T[9]; I[2] = T[10]; I[3] = T[11]; I[4] = T[12]; I[8] = T[13]; I[12] = T[14]; I[0] = T[15]; } }; template<> struct impl > { typedef void enable; static const bool value = true; static inline void eval(double A, double B, const Vector<3> &rAi, const Vector<3> &rBk, const Vector<3> &rAB, const Vector<3> &rij, const Vector<3> &rkl, const Vector<3> &t2, const Vector<3> &W, const double (&C)[2], double (&I)[120]) { #define pow(x,y) util::pow<(y)>::eval((x)) const int N = 3; double xij = rij[0]; double yij = rij[1]; double zij = rij[2]; // // double vB00[N] __attribute__ ((aligned(16))); // // // double vB10[N] __attribute__ ((aligned(16))); // // // // double vCx[N] __attribute__ ((aligned(16))); // double vCy[N] __attribute__ ((aligned(16))); // double vCz[N] __attribute__ ((aligned(16))); // // // double vDx[N] __attribute__ ((aligned(16))); // double vDy[N] __attribute__ ((aligned(16))); // double vDz[N] __attribute__ ((aligned(16))); // // for (int a = 0; a < N; ++a) { // // vB00[a] = 0.5*t2[a]; // // // vB10[a] = recurrence::coefficient(1.0/A, B, t2[a]); // // // // vCx[a] = recurrence::coefficient<0>(rAi, B, rAB, t2[a]); // vCy[a] = recurrence::coefficient<1>(rAi, B, rAB, t2[a]); // vCz[a] = recurrence::coefficient<2>(rAi, B, rAB, t2[a]); // // // vDx[a] = recurrence::coefficient<0>(rBk, -A, rAB, t2[a]); // vDy[a] = recurrence::coefficient<1>(rBk, -A, rAB, t2[a]); // vDz[a] = recurrence::coefficient<2>(rBk, -A, rAB, t2[a]); // // } // #define B00 vB00[a] // #define B10 vB10[a] // #define B01 vB01[a] // #define Cx vCx[a] // #define Cy vCy[a] // #define Cz vCz[a] // #define Dx vDx[a] // #define Dy vDy[a] // #define Dz vDz[a] #if defined (__INTEL_COMPILER) #pragma ivdep #pragma vector aligned #endif for (int a = 0; a < N; ++a) { double B00 = 0.5*t2[a]; double B10 = recurrence::coefficient(1.0/A, B, t2[a]); double Cx = recurrence::coefficient<0>(rAi, B, rAB, t2[a]); double Cy = recurrence::coefficient<1>(rAi, B, rAB, t2[a]); double Cz = recurrence::coefficient<2>(rAi, B, rAB, t2[a]); double Dx = recurrence::coefficient<0>(rBk, -A, rAB, t2[a]); double Dy = recurrence::coefficient<1>(rBk, -A, rAB, t2[a]); double Dz = recurrence::coefficient<2>(rBk, -A, rAB, t2[a]); double Ix = (Cx + xij); double Iy = (Cy + yij); double Iz = (Cz + zij); double Px = (B10 + pow(Cx,2)); double Py = (B10 + pow(Cy,2)); double Pz = (B10 + pow(Cz,2)); double Qx = (Cx*Dx + B00); double Qy = (Cy*Dy + B00); double Qz = (Cz*Dz + B00); double f0 = (3*B10 + pow(Cx,2)); double f10 = (B10*(3*Cy + yij) + Iy*pow(Cy,2)); double f12 = (3*pow(B10,2) + 3*B10*Cz*(2*Cz + zij) + Iz*pow(Cz,3)); double f15 = (Dx*(Cx*Ix + B10) + B00*(xij + 2*Cx)); double f17 = (Dy*Iy + B00); double f18 = (Cy*Iy + B10); double f19 = (3*pow(B10,2) + Iy*pow(Cy,3) + 3*B10*Cy*(yij + 2*Cy)); double f2 = (Dz*Pz + 2*B00*Cz); double f20 = (3*pow(B10,2) + 3*B10*Cx*(xij + 2*Cx) + Ix*pow(Cx,3)); double f22 = (Dx*Px + 2*B00*Cx); double f23 = (Dx*Ix + B00); double f24 = (B10*(3*Cx + xij) + Ix*pow(Cx,2)); double f3 = (Iz*pow(Cz,2) + B10*(3*Cz + zij)); double f33 = (3*B10 + pow(Cz,2)); double f34 = (3*B10 + pow(Cy,2)); double f4 = (B00*(yij + 2*Cy) + Dy*(Cy*Iy + B10)); double f5 = (Dx*(B10*(3*Cx + xij) + Ix*pow(Cx,2)) + 2*B00*Cx*xij + 3*B00*Px); double f6 = (Cy*Dy*(3*B10 + pow(Cy,2)) + 3*B00*Py); double f8 = 3*B00*B10; double f9 = (Dy*Py + 2*B00*Cy); I[0] += C[1]*W[a]*(Cx*(f6 + yij*(Dy*Py + 2*B00*Cy))); I[1] += C[1]*W[a]*(Cz*(f6 + yij*(Dy*Py + 2*B00*Cy))); I[2] += C[1]*W[a]*((B00*pow(Cy,2)*(4*Cy + 3*yij) + 3*Dy*pow(B10,2) + 4*Cy*f8 + Dy*pow(Cy,4) + Dy*yij*pow(Cy,3) + f8*yij + 3*B10*Cy*Dy*(yij + 2*Cy))); I[3] += C[1]*W[a]*(Cx*Cy*(f2 + Qz*zij)); I[4] += C[1]*W[a]*(Px*(f2 + Qz*zij)); I[5] += C[1]*W[a]*(Py*(f2 + Qz*zij)); I[6] += C[1]*W[a]*(Cy*(B00*Cz*(3*Cz + 2*zij) + Dz*Iz*pow(Cz,2) + B10*Dz*(3*Cz + zij) + f8)); I[7] += C[1]*W[a]*(Cx*(B00*Cz*(3*Cz + 2*zij) + Dz*Iz*pow(Cz,2) + B10*Dz*(3*Cz + zij) + f8)); I[8] += C[1]*W[a]*((f8*zij + 3*Dz*pow(B10,2) + B00*pow(Cz,2)*(4*Cz + 3*zij) + Dz*pow(Cz,4) + 3*B10*Cz*Dz*(2*Cz + zij) + 4*Cz*f8 + Dz*zij*pow(Cz,3))); I[9] += C[1]*W[a]*(Iy*(3*B10*Cz*Dz + f8 + 3*B00*pow(Cz,2) + Dz*pow(Cz,3))); I[10] += C[1]*W[a]*(Ix*(3*B10*Cz*Dz + f8 + 3*B00*pow(Cz,2) + Dz*pow(Cz,3))); I[11] += C[0]*W[a]*((3*B10*Cz*Dz + f8 + 3*B00*pow(Cz,2) + Dz*pow(Cz,3))); I[12] += C[1]*W[a]*(Iz*(Dx*pow(Cx,3) + 3*B00*pow(Cx,2) + 3*B10*Cx*Dx + f8)); I[13] += C[1]*W[a]*(Iy*(Dx*pow(Cx,3) + 3*B00*pow(Cx,2) + 3*B10*Cx*Dx + f8)); I[14] += C[0]*W[a]*((Dx*pow(Cx,3) + 3*B00*pow(Cx,2) + 3*B10*Cx*Dx + f8)); I[15] += C[1]*W[a]*((Dx*xij*pow(Cx,3) + f8*xij + 3*Dx*pow(B10,2) + Dx*pow(Cx,4) + 4*Cx*f8 + B00*pow(Cx,2)*(4*Cx + 3*xij) + 3*B10*Cx*Dx*(xij + 2*Cx))); I[16] += C[1]*W[a]*(Cy*Qz*(Px + Cx*xij)); I[17] += C[1]*W[a]*(Cy*f34*(Dz*zij + Qz)); I[18] += C[1]*W[a]*(Cy*Px*(Dz*zij + Qz)); I[19] += C[1]*W[a]*(Cx*f0*(Dz*zij + Qz)); I[20] += C[1]*W[a]*(Cx*Py*(Dz*zij + Qz)); I[21] += C[1]*W[a]*(Dz*Py*(Px + Cx*xij)); I[22] += C[1]*W[a]*(Dy*Pz*(Px + Cx*xij)); I[23] += C[1]*W[a]*(f9*(Px + Cx*xij)); I[24] += C[1]*W[a]*(f2*(Px + Cx*xij)); I[25] += C[1]*W[a]*(Cz*Qy*(Px + Cx*xij)); I[26] += C[1]*W[a]*(Cx*Qy*(Cz*zij + Pz)); I[27] += C[1]*W[a]*(Cy*Qx*(Cz*zij + Pz)); I[28] += C[1]*W[a]*(Dx*Py*(Cz*zij + Pz)); I[29] += C[1]*W[a]*(f9*(Cz*zij + Pz)); I[30] += C[1]*W[a]*(f22*(Cz*zij + Pz)); I[31] += C[1]*W[a]*(Dy*Px*(Cz*zij + Pz)); I[32] += C[1]*W[a]*(Cz*Dy*f24); I[33] += C[1]*W[a]*(Cx*Dy*f3); I[34] += C[0]*W[a]*(Cx*Dz*Py); I[35] += C[1]*W[a]*(Dz*Px*f18); I[36] += C[1]*W[a]*(Cz*Qx*f18); I[37] += C[1]*W[a]*(Cx*Cz*f4); I[38] += C[0]*W[a]*(Cx*Cz*Qy); I[39] += C[1]*W[a]*(Cx*f0*f17); I[40] += C[1]*W[a]*(Cx*Pz*f17); I[41] += C[0]*W[a]*(Cx*Dy*Pz); I[42] += C[1]*W[a]*(Cx*Dy*Iz*f0); I[43] += C[0]*W[a]*(Cx*Dy*f0); I[44] += C[1]*W[a]*(Cx*Dz*Iy*f0); I[45] += C[0]*W[a]*(Cx*Dz*f0); I[46] += C[1]*W[a]*(Cx*Dz*f10); I[47] += C[0]*W[a]*(Cx*Cy*Qz); I[48] += C[1]*W[a]*(Cx*Qz*f18); I[49] += C[1]*W[a]*(Dx*Pz*f18); I[50] += C[1]*W[a]*(Cz*Dx*f10); I[51] += C[1]*W[a]*(Cy*Dx*f3); I[52] += C[1]*W[a]*(Cy*Dz*f24); I[53] += C[0]*W[a]*(Cy*Dz*Px); I[54] += C[1]*W[a]*(Cy*Dz*Ix*f34); I[55] += C[0]*W[a]*(Cy*Dz*f34); I[56] += C[1]*W[a]*(Cy*f23*f34); I[57] += C[1]*W[a]*(Cy*Pz*f23); I[58] += C[0]*W[a]*(Cy*Dx*Pz); I[59] += C[1]*W[a]*(Cy*Dx*Iz*f34); I[60] += C[0]*W[a]*(Cy*Dx*f34); I[61] += C[1]*W[a]*(Cy*Cz*f15); I[62] += C[0]*W[a]*(Cy*Cz*Qx); I[63] += C[1]*W[a]*(Cz*Px*f17); I[64] += C[1]*W[a]*(Cz*f17*f33); I[65] += C[1]*W[a]*(Cz*f23*f33); I[66] += C[1]*W[a]*(Cz*Py*f23); I[67] += C[0]*W[a]*(Cz*Dx*Py); I[68] += C[1]*W[a]*(Cz*Dx*Iy*f33); I[69] += C[0]*W[a]*(Cz*Dx*f33); I[70] += C[1]*W[a]*(Cz*Dy*Ix*f33); I[71] += C[0]*W[a]*(Cz*Dy*f33); I[72] += C[0]*W[a]*(Cz*Dy*Px); I[73] += C[1]*W[a]*(Px*f4); I[74] += C[1]*W[a]*(Pz*f4); I[75] += C[1]*W[a]*(Qz*f24); I[76] += C[1]*W[a]*(Dz*f20); I[77] += C[1]*W[a]*(Dy*f20); I[78] += C[1]*W[a]*(Dy*f12); I[79] += C[1]*W[a]*(Dx*f12); I[80] += C[1]*W[a]*(Dx*f19); I[81] += C[1]*W[a]*(Dz*f19); I[82] += C[1]*W[a]*(Qx*f3); I[83] += C[1]*W[a]*(Qy*f3); I[84] += C[1]*W[a]*(Qy*f24); I[85] += C[1]*W[a]*(Ix*Pz*Qy); I[86] += C[0]*W[a]*(Pz*Qy); I[87] += C[1]*W[a]*(Iz*Px*Qy); I[88] += C[0]*W[a]*(Px*Qy); I[89] += C[1]*W[a]*(Iy*Px*Qz); I[90] += C[0]*W[a]*(Px*Qz); I[91] += C[1]*W[a]*(Ix*Py*Qz); I[92] += C[0]*W[a]*(Py*Qz); I[93] += C[1]*W[a]*(Py*f15); I[94] += C[1]*W[a]*(Pz*f15); I[95] += C[1]*W[a]*(Iy*Pz*Qx); I[96] += C[0]*W[a]*(Pz*Qx); I[97] += C[1]*W[a]*(Iz*Py*Qx); I[98] += C[0]*W[a]*(Py*Qx); I[99] += C[1]*W[a]*(Qx*f10); I[100] += C[1]*W[a]*(Qz*f10); I[101] += C[1]*W[a]*(Cz*Ix*f9); I[102] += C[0]*W[a]*(Cz*f9); I[103] += C[1]*W[a]*(Cx*Iz*f9); I[104] += C[0]*W[a]*(Cx*f9); I[105] += C[1]*W[a]*(Cx*Iy*f2); I[106] += C[0]*W[a]*(Cx*f2); I[107] += C[1]*W[a]*(Cy*Ix*f2); I[108] += C[0]*W[a]*(Cy*f2); I[109] += C[1]*W[a]*(Cy*f5); I[110] += C[1]*W[a]*(Cz*f5); I[111] += C[1]*W[a]*(Cz*Iy*f22); I[112] += C[0]*W[a]*(Cz*f22); I[113] += C[1]*W[a]*(Cy*Iz*f22); I[114] += C[0]*W[a]*(Cy*f22); I[115] += C[1]*W[a]*(f18*f22); I[116] += C[1]*W[a]*(f18*f2); I[117] += C[1]*W[a]*(Iz*f6); I[118] += C[1]*W[a]*(Ix*f6); I[119] += C[0]*W[a]*(f6); } #undef B00 #undef B10 #undef B01 #undef Cx #undef Cy #undef Cz #undef Dx #undef Dy #undef Dz #undef pow } static inline void reorder(double (&I)[120]) { double T[120]; for (int i = 0; i < 120; ++i) { T[i] = I[i]; } I[65] = T[0]; I[66] = T[1]; I[61] = T[2]; I[119] = T[3]; I[114] = T[4]; I[116] = T[5]; I[118] = T[6]; I[117] = T[7]; I[112] = T[8]; I[102] = T[9]; I[92] = T[10]; I[82] = T[11]; I[30] = T[12]; I[20] = T[13]; I[0] = T[14]; I[10] = T[15]; I[99] = T[16]; I[111] = T[17]; I[113] = T[18]; I[110] = T[19]; I[115] = T[20]; I[95] = T[21]; I[57] = T[22]; I[55] = T[23]; I[97] = T[24]; I[59] = T[25]; I[79] = T[26]; I[39] = T[27]; I[36] = T[28]; I[76] = T[29]; I[34] = T[30]; I[74] = T[31]; I[54] = T[32]; I[77] = T[33]; I[85] = T[34]; I[103] = T[35]; I[29] = T[36]; I[69] = T[37]; I[49] = T[38]; I[60] = T[39]; I[67] = T[40]; I[47] = T[41]; I[70] = T[42]; I[40] = T[43]; I[100] = T[44]; I[80] = T[45]; I[105] = T[46]; I[89] = T[47]; I[109] = T[48]; I[28] = T[49]; I[26] = T[50]; I[38] = T[51]; I[93] = T[52]; I[83] = T[53]; I[91] = T[54]; I[81] = T[55]; I[11] = T[56]; I[18] = T[57]; I[8] = T[58]; I[31] = T[59]; I[1] = T[60]; I[19] = T[61]; I[9] = T[62]; I[64] = T[63]; I[62] = T[64]; I[12] = T[65]; I[16] = T[66]; I[6] = T[67]; I[22] = T[68]; I[2] = T[69]; I[52] = T[70]; I[42] = T[71]; I[44] = T[72]; I[63] = T[73]; I[68] = T[74]; I[94] = T[75]; I[90] = T[76]; I[50] = T[77]; I[72] = T[78]; I[32] = T[79]; I[21] = T[80]; I[101] = T[81]; I[37] = T[82]; I[78] = T[83]; I[53] = T[84]; I[58] = T[85]; I[48] = T[86]; I[73] = T[87]; I[43] = T[88]; I[104] = T[89]; I[84] = T[90]; I[96] = T[91]; I[86] = T[92]; I[15] = T[93]; I[17] = T[94]; I[27] = T[95]; I[7] = T[96]; I[35] = T[97]; I[5] = T[98]; I[25] = T[99]; I[106] = T[100]; I[56] = T[101]; I[46] = T[102]; I[75] = T[103]; I[45] = T[104]; I[107] = T[105]; I[87] = T[106]; I[98] = T[107]; I[88] = T[108]; I[13] = T[109]; I[14] = T[110]; I[24] = T[111]; I[4] = T[112]; I[33] = T[113]; I[3] = T[114]; I[23] = T[115]; I[108] = T[116]; I[71] = T[117]; I[51] = T[118]; I[41] = T[119]; } }; template<> struct impl > { typedef void enable; static const bool value = true; static inline void eval(double A, double B, const Vector<3> &rAi, const Vector<3> &rBk, const Vector<3> &rAB, const Vector<3> &rij, const Vector<3> &rkl, const Vector<2> &t2, const Vector<2> &W, const double (&C)[2], double (&I)[12]) { #define pow(x,y) util::pow<(y)>::eval((x)) const int N = 2; // // double vB00[N] __attribute__ ((aligned(16))); // // // // // double vCx[N] __attribute__ ((aligned(16))); // double vCy[N] __attribute__ ((aligned(16))); // double vCz[N] __attribute__ ((aligned(16))); // // // double vDx[N] __attribute__ ((aligned(16))); // double vDy[N] __attribute__ ((aligned(16))); // double vDz[N] __attribute__ ((aligned(16))); // // for (int a = 0; a < N; ++a) { // // vB00[a] = 0.5*t2[a]; // // // // // vCx[a] = recurrence::coefficient<0>(rAi, B, rAB, t2[a]); // vCy[a] = recurrence::coefficient<1>(rAi, B, rAB, t2[a]); // vCz[a] = recurrence::coefficient<2>(rAi, B, rAB, t2[a]); // // // vDx[a] = recurrence::coefficient<0>(rBk, -A, rAB, t2[a]); // vDy[a] = recurrence::coefficient<1>(rBk, -A, rAB, t2[a]); // vDz[a] = recurrence::coefficient<2>(rBk, -A, rAB, t2[a]); // // } // #define B00 vB00[a] // #define B10 vB10[a] // #define B01 vB01[a] // #define Cx vCx[a] // #define Cy vCy[a] // #define Cz vCz[a] // #define Dx vDx[a] // #define Dy vDy[a] // #define Dz vDz[a] #if defined (__INTEL_COMPILER) #pragma ivdep #pragma vector aligned #endif for (int a = 0; a < N; ++a) { double B00 = 0.5*t2[a]; double Cx = recurrence::coefficient<0>(rAi, B, rAB, t2[a]); double Cy = recurrence::coefficient<1>(rAi, B, rAB, t2[a]); double Cz = recurrence::coefficient<2>(rAi, B, rAB, t2[a]); double Dx = recurrence::coefficient<0>(rBk, -A, rAB, t2[a]); double Dy = recurrence::coefficient<1>(rBk, -A, rAB, t2[a]); double Dz = recurrence::coefficient<2>(rBk, -A, rAB, t2[a]); double Qx = (Cx*Dx + B00); double Qy = (Cy*Dy + B00); double Qz = (Cz*Dz + B00); I[0] += C[1]*W[a]*(Qx); I[1] += C[1]*W[a]*(Qy); I[2] += C[1]*W[a]*(Qz); I[3] += C[1]*W[a]*(Cz*Dx); I[4] += C[1]*W[a]*(Cz*Dy); I[5] += C[1]*W[a]*(Cx*Dy); I[6] += C[1]*W[a]*(Cx*Dz); I[7] += C[1]*W[a]*(Cy*Dz); I[8] += C[1]*W[a]*(Cy*Dx); I[9] += C[0]*W[a]*(Dx); I[10] += C[0]*W[a]*(Dy); I[11] += C[0]*W[a]*(Dz); } #undef B00 #undef B10 #undef B01 #undef Cx #undef Cy #undef Cz #undef Dx #undef Dy #undef Dz #undef pow } static inline void reorder(double (&I)[12]) { double T[12]; for (int i = 0; i < 12; ++i) { T[i] = I[i]; } I[1] = T[0]; I[6] = T[1]; I[11] = T[2]; I[3] = T[3]; I[7] = T[4]; I[5] = T[5]; I[9] = T[6]; I[10] = T[7]; I[2] = T[8]; I[0] = T[9]; I[4] = T[10]; I[8] = T[11]; } }; template<> struct impl > { typedef void enable; static const bool value = true; static inline void eval(double A, double B, const Vector<3> &rAi, const Vector<3> &rBk, const Vector<3> &rAB, const Vector<3> &rij, const Vector<3> &rkl, const Vector<2> &t2, const Vector<2> &W, const double (&C)[8], double (&I)[64]) { #define pow(x,y) util::pow<(y)>::eval((x)) const int N = 2; double xij = rij[0]; double yij = rij[1]; double zij = rij[2]; // // double vB00[N] __attribute__ ((aligned(16))); // // // double vB10[N] __attribute__ ((aligned(16))); // // // // double vCx[N] __attribute__ ((aligned(16))); // double vCy[N] __attribute__ ((aligned(16))); // double vCz[N] __attribute__ ((aligned(16))); // // // double vDx[N] __attribute__ ((aligned(16))); // double vDy[N] __attribute__ ((aligned(16))); // double vDz[N] __attribute__ ((aligned(16))); // // for (int a = 0; a < N; ++a) { // // vB00[a] = 0.5*t2[a]; // // // vB10[a] = recurrence::coefficient(1.0/A, B, t2[a]); // // // // vCx[a] = recurrence::coefficient<0>(rAi, B, rAB, t2[a]); // vCy[a] = recurrence::coefficient<1>(rAi, B, rAB, t2[a]); // vCz[a] = recurrence::coefficient<2>(rAi, B, rAB, t2[a]); // // // vDx[a] = recurrence::coefficient<0>(rBk, -A, rAB, t2[a]); // vDy[a] = recurrence::coefficient<1>(rBk, -A, rAB, t2[a]); // vDz[a] = recurrence::coefficient<2>(rBk, -A, rAB, t2[a]); // // } // #define B00 vB00[a] // #define B10 vB10[a] // #define B01 vB01[a] // #define Cx vCx[a] // #define Cy vCy[a] // #define Cz vCz[a] // #define Dx vDx[a] // #define Dy vDy[a] // #define Dz vDz[a] #if defined (__INTEL_COMPILER) #pragma ivdep #pragma vector aligned #endif for (int a = 0; a < N; ++a) { double B00 = 0.5*t2[a]; double B10 = recurrence::coefficient(1.0/A, B, t2[a]); double Cx = recurrence::coefficient<0>(rAi, B, rAB, t2[a]); double Cy = recurrence::coefficient<1>(rAi, B, rAB, t2[a]); double Cz = recurrence::coefficient<2>(rAi, B, rAB, t2[a]); double Dx = recurrence::coefficient<0>(rBk, -A, rAB, t2[a]); double Dy = recurrence::coefficient<1>(rBk, -A, rAB, t2[a]); double Dz = recurrence::coefficient<2>(rBk, -A, rAB, t2[a]); double Ix = (Cx + xij); double Iy = (Cy + yij); double Iz = (Cz + zij); double Px = (B10 + pow(Cx,2)); double Py = (B10 + pow(Cy,2)); double Pz = (B10 + pow(Cz,2)); double Qy = (Cy*Dy + B00); double f2 = Cz*Dz; double f4 = Cx*Dx; double f8 = Cy*Dy; I[0] += C[7]*W[a]*((B00*(yij + 2*Cy) + f8*yij + Dy*Py)); I[1] += C[7]*W[a]*((f4*xij + Dx*Px + B00*(xij + 2*Cx))); I[2] += C[7]*W[a]*(Cy*(B00 + f4 + Dx*xij)); I[3] += C[7]*W[a]*(Cz*(B00 + f4 + Dx*xij)); I[4] += C[6]*W[a]*((B00 + f4 + Dx*xij)); I[5] += C[7]*W[a]*((Dz*Pz + B00*(2*Cz + zij) + f2*zij)); I[6] += C[7]*W[a]*(Cy*(B00 + Dz*zij + f2)); I[7] += C[7]*W[a]*(Cx*(B00 + Dz*zij + f2)); I[8] += C[6]*W[a]*((B00 + Dz*zij + f2)); I[9] += C[7]*W[a]*(Dz*(Cy*Iy + B10)); I[10] += C[7]*W[a]*(Dx*(Cy*Iy + B10)); I[11] += C[3]*W[a]*((Cy*Iy + B10)); I[12] += C[7]*W[a]*(Dy*(B10 + Cz*Iz)); I[13] += C[7]*W[a]*(Dx*(B10 + Cz*Iz)); I[14] += C[3]*W[a]*((B10 + Cz*Iz)); I[15] += C[7]*W[a]*(Cz*(Dy*yij + Qy)); I[16] += C[7]*W[a]*(Cx*(Dy*yij + Qy)); I[17] += C[6]*W[a]*((Dy*yij + Qy)); I[18] += C[7]*W[a]*(Dy*(Cx*Ix + B10)); I[19] += C[3]*W[a]*((Cx*Ix + B10)); I[20] += C[7]*W[a]*(Dz*(Cx*Ix + B10)); I[21] += C[7]*W[a]*(Cx*Dz*Iy); I[22] += C[5]*W[a]*(Cx*Dz); I[23] += C[5]*W[a]*(Cy*Dz); I[24] += C[6]*W[a]*(Dy*Iz); I[25] += C[7]*W[a]*(Iz*(B00 + f4)); I[26] += C[5]*W[a]*((B00 + f4)); I[27] += C[7]*W[a]*(Iy*(B00 + f4)); I[28] += C[7]*W[a]*(Iy*(B00 + f2)); I[29] += C[7]*W[a]*(Ix*(B00 + f2)); I[30] += C[5]*W[a]*((B00 + f2)); I[31] += C[6]*W[a]*(Dx*Iy); I[32] += C[6]*W[a]*(Dx*Iz); I[33] += C[7]*W[a]*(Iz*Qy); I[34] += C[7]*W[a]*(Ix*Qy); I[35] += C[6]*W[a]*(Dy*Ix); I[36] += C[5]*W[a]*(Cx*Dy); I[37] += C[7]*W[a]*(Cx*Dy*Iz); I[38] += C[3]*W[a]*(Cx*Iz); I[39] += C[3]*W[a]*(Cy*Iz); I[40] += C[7]*W[a]*(Cy*Dx*Iz); I[41] += C[5]*W[a]*(Cy*Dx); I[42] += C[5]*W[a]*(Cz*Dx); I[43] += C[7]*W[a]*(Cz*Dx*Iy); I[44] += C[3]*W[a]*(Cz*Iy); I[45] += C[5]*W[a]*(Cz*Dy); I[46] += C[7]*W[a]*(Cz*Dy*Ix); I[47] += C[3]*W[a]*(Cz*Ix); I[48] += C[3]*W[a]*(Cy*Ix); I[49] += C[7]*W[a]*(Cy*Dz*Ix); I[50] += C[6]*W[a]*(Dz*Ix); I[51] += C[6]*W[a]*(Dz*Iy); I[52] += C[3]*W[a]*(Cx*Iy); I[53] += C[1]*W[a]*(Cx); I[54] += C[1]*W[a]*(Cy); I[55] += C[1]*W[a]*(Cz); I[56] += C[2]*W[a]*(Ix); I[57] += C[2]*W[a]*(Iy); I[58] += C[2]*W[a]*(Iz); I[59] += C[4]*W[a]*(Dx); I[60] += C[4]*W[a]*(Dy); I[61] += C[5]*W[a]*(Qy); I[62] += C[4]*W[a]*(Dz); I[63] += C[0]*W[a]*(1); } #undef B00 #undef B10 #undef B01 #undef Cx #undef Cy #undef Cz #undef Dx #undef Dy #undef Dz #undef pow } static inline void reorder(double (&I)[64]) { double T[64]; for (int i = 0; i < 64; ++i) { T[i] = I[i]; } I[42] = T[0]; I[21] = T[1]; I[22] = T[2]; I[23] = T[3]; I[20] = T[4]; I[63] = T[5]; I[62] = T[6]; I[61] = T[7]; I[60] = T[8]; I[58] = T[9]; I[26] = T[10]; I[10] = T[11]; I[47] = T[12]; I[31] = T[13]; I[15] = T[14]; I[43] = T[15]; I[41] = T[16]; I[40] = T[17]; I[37] = T[18]; I[5] = T[19]; I[53] = T[20]; I[57] = T[21]; I[49] = T[22]; I[50] = T[23]; I[44] = T[24]; I[29] = T[25]; I[17] = T[26]; I[25] = T[27]; I[59] = T[28]; I[55] = T[29]; I[51] = T[30]; I[24] = T[31]; I[28] = T[32]; I[46] = T[33]; I[38] = T[34]; I[36] = T[35]; I[33] = T[36]; I[45] = T[37]; I[13] = T[38]; I[14] = T[39]; I[30] = T[40]; I[18] = T[41]; I[19] = T[42]; I[27] = T[43]; I[11] = T[44]; I[35] = T[45]; I[39] = T[46]; I[7] = T[47]; I[6] = T[48]; I[54] = T[49]; I[52] = T[50]; I[56] = T[51]; I[9] = T[52]; I[1] = T[53]; I[2] = T[54]; I[3] = T[55]; I[4] = T[56]; I[8] = T[57]; I[12] = T[58]; I[16] = T[59]; I[32] = T[60]; I[34] = T[61]; I[48] = T[62]; I[0] = T[63]; } }; template<> struct impl > { typedef void enable; static const bool value = true; static inline void eval(double A, double B, const Vector<3> &rAi, const Vector<3> &rBk, const Vector<3> &rAB, const Vector<3> &rij, const Vector<3> &rkl, const Vector<2> &t2, const Vector<2> &W, const double (&C)[2], double (&I)[36]) { #define pow(x,y) util::pow<(y)>::eval((x)) const int N = 2; double xkl = rkl[0]; double ykl = rkl[1]; double zkl = rkl[2]; // // double vB00[N] __attribute__ ((aligned(16))); // // // // double vB01[N] __attribute__ ((aligned(16))); // // // double vCx[N] __attribute__ ((aligned(16))); // double vCy[N] __attribute__ ((aligned(16))); // double vCz[N] __attribute__ ((aligned(16))); // // // double vDx[N] __attribute__ ((aligned(16))); // double vDy[N] __attribute__ ((aligned(16))); // double vDz[N] __attribute__ ((aligned(16))); // // for (int a = 0; a < N; ++a) { // // vB00[a] = 0.5*t2[a]; // // // // vB01[a] = recurrence::coefficient(1.0/B, A, t2[a]); // // // vCx[a] = recurrence::coefficient<0>(rAi, B, rAB, t2[a]); // vCy[a] = recurrence::coefficient<1>(rAi, B, rAB, t2[a]); // vCz[a] = recurrence::coefficient<2>(rAi, B, rAB, t2[a]); // // // vDx[a] = recurrence::coefficient<0>(rBk, -A, rAB, t2[a]); // vDy[a] = recurrence::coefficient<1>(rBk, -A, rAB, t2[a]); // vDz[a] = recurrence::coefficient<2>(rBk, -A, rAB, t2[a]); // // } // #define B00 vB00[a] // #define B10 vB10[a] // #define B01 vB01[a] // #define Cx vCx[a] // #define Cy vCy[a] // #define Cz vCz[a] // #define Dx vDx[a] // #define Dy vDy[a] // #define Dz vDz[a] #if defined (__INTEL_COMPILER) #pragma ivdep #pragma vector aligned #endif for (int a = 0; a < N; ++a) { double B00 = 0.5*t2[a]; double B01 = recurrence::coefficient(1.0/B, A, t2[a]); double Cx = recurrence::coefficient<0>(rAi, B, rAB, t2[a]); double Cy = recurrence::coefficient<1>(rAi, B, rAB, t2[a]); double Cz = recurrence::coefficient<2>(rAi, B, rAB, t2[a]); double Dx = recurrence::coefficient<0>(rBk, -A, rAB, t2[a]); double Dy = recurrence::coefficient<1>(rBk, -A, rAB, t2[a]); double Dz = recurrence::coefficient<2>(rBk, -A, rAB, t2[a]); double Kx = (xkl + Dx); double Ky = (ykl + Dy); double Kz = (Dz + zkl); double Qx = (Cx*Dx + B00); double Qy = (Cy*Dy + B00); double Qz = (Cz*Dz + B00); double f7 = (B00 + Cy*Ky); double f9 = (B00 + Cx*Kx); I[0] += C[1]*W[a]*((Cy*Dy*Ky + B01*Cy + B00*(ykl + 2*Dy))); I[1] += C[1]*W[a]*((B01*Cx + Cx*Dx*Kx + B00*(xkl + 2*Dx))); I[2] += C[1]*W[a]*(Dx*(Cz*zkl + Qz)); I[3] += C[1]*W[a]*(Dy*(Cz*zkl + Qz)); I[4] += C[1]*W[a]*(Cx*Dy*Kz); I[5] += C[1]*W[a]*(Cx*(B01 + Dy*Ky)); I[6] += C[0]*W[a]*((B01 + Dy*Ky)); I[7] += C[1]*W[a]*(Cz*(B01 + Dy*Ky)); I[8] += C[1]*W[a]*((B01*Cz + B00*(2*Dz + zkl) + Cz*Dz*Kz)); I[9] += C[1]*W[a]*(Cy*(Dz*Kz + B01)); I[10] += C[1]*W[a]*(Cx*(Dz*Kz + B01)); I[11] += C[0]*W[a]*((Dz*Kz + B01)); I[12] += C[1]*W[a]*(Cy*(B01 + Dx*Kx)); I[13] += C[0]*W[a]*((B01 + Dx*Kx)); I[14] += C[1]*W[a]*(Cz*(B01 + Dx*Kx)); I[15] += C[1]*W[a]*(Cz*Dx*Ky); I[16] += C[1]*W[a]*(Ky*Qx); I[17] += C[1]*W[a]*(Dx*f7); I[18] += C[1]*W[a]*(Kx*Qy); I[19] += C[1]*W[a]*(Cy*Dz*Kx); I[20] += C[0]*W[a]*(Dz*Kx); I[21] += C[1]*W[a]*(Cx*Dz*Ky); I[22] += C[0]*W[a]*(Dz*Ky); I[23] += C[1]*W[a]*(Dz*f7); I[24] += C[1]*W[a]*(Dz*f9); I[25] += C[1]*W[a]*(Dy*f9); I[26] += C[1]*W[a]*(Cz*Dy*Kx); I[27] += C[0]*W[a]*(Dy*Kx); I[28] += C[1]*W[a]*(Kx*Qz); I[29] += C[1]*W[a]*(Ky*Qz); I[30] += C[0]*W[a]*(Dx*Ky); I[31] += C[1]*W[a]*(Cy*Dx*Kz); I[32] += C[0]*W[a]*(Dx*Kz); I[33] += C[1]*W[a]*(Kz*Qx); I[34] += C[0]*W[a]*(Dy*Kz); I[35] += C[1]*W[a]*(Kz*Qy); } #undef B00 #undef B10 #undef B01 #undef Cx #undef Cy #undef Cz #undef Dx #undef Dy #undef Dz #undef pow } static inline void reorder(double (&I)[36]) { double T[36]; for (int i = 0; i < 36; ++i) { T[i] = I[i]; } I[18] = T[0]; I[1] = T[1]; I[27] = T[2]; I[31] = T[3]; I[29] = T[4]; I[17] = T[5]; I[16] = T[6]; I[19] = T[7]; I[35] = T[8]; I[34] = T[9]; I[33] = T[10]; I[32] = T[11]; I[2] = T[12]; I[0] = T[13]; I[3] = T[14]; I[15] = T[15]; I[13] = T[16]; I[14] = T[17]; I[6] = T[18]; I[10] = T[19]; I[8] = T[20]; I[21] = T[21]; I[20] = T[22]; I[22] = T[23]; I[9] = T[24]; I[5] = T[25]; I[7] = T[26]; I[4] = T[27]; I[11] = T[28]; I[23] = T[29]; I[12] = T[30]; I[26] = T[31]; I[24] = T[32]; I[25] = T[33]; I[28] = T[34]; I[30] = T[35]; } }; template<> struct impl > { typedef void enable; static const bool value = true; static inline void eval(double A, double B, const Vector<3> &rAi, const Vector<3> &rBk, const Vector<3> &rAB, const Vector<3> &rij, const Vector<3> &rkl, const Vector<2> &t2, const Vector<2> &W, const double (&C)[1], double (&I)[9]) { #define pow(x,y) util::pow<(y)>::eval((x)) const int N = 2; // // double vB00[N] __attribute__ ((aligned(16))); // // // // // double vCx[N] __attribute__ ((aligned(16))); // double vCy[N] __attribute__ ((aligned(16))); // double vCz[N] __attribute__ ((aligned(16))); // // // double vDx[N] __attribute__ ((aligned(16))); // double vDy[N] __attribute__ ((aligned(16))); // double vDz[N] __attribute__ ((aligned(16))); // // for (int a = 0; a < N; ++a) { // // vB00[a] = 0.5*t2[a]; // // // // // vCx[a] = recurrence::coefficient<0>(rAi, B, rAB, t2[a]); // vCy[a] = recurrence::coefficient<1>(rAi, B, rAB, t2[a]); // vCz[a] = recurrence::coefficient<2>(rAi, B, rAB, t2[a]); // // // vDx[a] = recurrence::coefficient<0>(rBk, -A, rAB, t2[a]); // vDy[a] = recurrence::coefficient<1>(rBk, -A, rAB, t2[a]); // vDz[a] = recurrence::coefficient<2>(rBk, -A, rAB, t2[a]); // // } // #define B00 vB00[a] // #define B10 vB10[a] // #define B01 vB01[a] // #define Cx vCx[a] // #define Cy vCy[a] // #define Cz vCz[a] // #define Dx vDx[a] // #define Dy vDy[a] // #define Dz vDz[a] #if defined (__INTEL_COMPILER) #pragma ivdep #pragma vector aligned #endif for (int a = 0; a < N; ++a) { double B00 = 0.5*t2[a]; double Cx = recurrence::coefficient<0>(rAi, B, rAB, t2[a]); double Cy = recurrence::coefficient<1>(rAi, B, rAB, t2[a]); double Cz = recurrence::coefficient<2>(rAi, B, rAB, t2[a]); double Dx = recurrence::coefficient<0>(rBk, -A, rAB, t2[a]); double Dy = recurrence::coefficient<1>(rBk, -A, rAB, t2[a]); double Dz = recurrence::coefficient<2>(rBk, -A, rAB, t2[a]); double Qx = (Cx*Dx + B00); double Qy = (Cy*Dy + B00); double Qz = (Cz*Dz + B00); I[0] += C[0]*W[a]*(Qy); I[1] += C[0]*W[a]*(Qz); I[2] += C[0]*W[a]*(Qx); I[3] += C[0]*W[a]*(Cy*Dx); I[4] += C[0]*W[a]*(Cz*Dx); I[5] += C[0]*W[a]*(Cz*Dy); I[6] += C[0]*W[a]*(Cx*Dy); I[7] += C[0]*W[a]*(Cx*Dz); I[8] += C[0]*W[a]*(Cy*Dz); } #undef B00 #undef B10 #undef B01 #undef Cx #undef Cy #undef Cz #undef Dx #undef Dy #undef Dz #undef pow } static inline void reorder(double (&I)[9]) { double T[9]; for (int i = 0; i < 9; ++i) { T[i] = I[i]; } I[4] = T[0]; I[8] = T[1]; I[0] = T[2]; I[1] = T[3]; I[2] = T[4]; I[5] = T[5]; I[3] = T[6]; I[6] = T[7]; I[7] = T[8]; } }; template<> struct impl > { typedef void enable; static const bool value = true; static inline void eval(double A, double B, const Vector<3> &rAi, const Vector<3> &rBk, const Vector<3> &rAB, const Vector<3> &rij, const Vector<3> &rkl, const Vector<3> &t2, const Vector<3> &W, const double (&C)[2], double (&I)[40]) { #define pow(x,y) util::pow<(y)>::eval((x)) const int N = 3; double xij = rij[0]; double yij = rij[1]; double zij = rij[2]; // // // double vB10[N] __attribute__ ((aligned(16))); // // // // double vCx[N] __attribute__ ((aligned(16))); // double vCy[N] __attribute__ ((aligned(16))); // double vCz[N] __attribute__ ((aligned(16))); // // // for (int a = 0; a < N; ++a) { // // // vB10[a] = recurrence::coefficient(1.0/A, B, t2[a]); // // // // vCx[a] = recurrence::coefficient<0>(rAi, B, rAB, t2[a]); // vCy[a] = recurrence::coefficient<1>(rAi, B, rAB, t2[a]); // vCz[a] = recurrence::coefficient<2>(rAi, B, rAB, t2[a]); // // // } // #define B00 vB00[a] // #define B10 vB10[a] // #define B01 vB01[a] // #define Cx vCx[a] // #define Cy vCy[a] // #define Cz vCz[a] // #define Dx vDx[a] // #define Dy vDy[a] // #define Dz vDz[a] #if defined (__INTEL_COMPILER) #pragma ivdep #pragma vector aligned #endif for (int a = 0; a < N; ++a) { double B10 = recurrence::coefficient(1.0/A, B, t2[a]); double Cx = recurrence::coefficient<0>(rAi, B, rAB, t2[a]); double Cy = recurrence::coefficient<1>(rAi, B, rAB, t2[a]); double Cz = recurrence::coefficient<2>(rAi, B, rAB, t2[a]); double Ix = (Cx + xij); double Iy = (Cy + yij); double Iz = (Cz + zij); double Px = (B10 + pow(Cx,2)); double Py = (B10 + pow(Cy,2)); double Pz = (B10 + pow(Cz,2)); double f0 = (3*B10 + pow(Cx,2)); double f11 = (3*B10 + pow(Cz,2)); double f12 = (3*B10 + pow(Cy,2)); double f13 = (Iz*pow(Cz,2) + B10*(3*Cz + zij)); double f2 = (B10*(3*Cy + yij) + Iy*pow(Cy,2)); double f5 = (Cy*Iy + B10); double f6 = (B10*(3*Cx + xij) + Ix*pow(Cx,2)); double f8 = 3*pow(B10,2); I[0] += C[1]*W[a]*(Cx*Cy*(Cz*zij + Pz)); I[1] += C[1]*W[a]*(Cy*Cz*(Px + Cx*xij)); I[2] += C[1]*W[a]*(Py*(Px + Cx*xij)); I[3] += C[1]*W[a]*(Pz*(Px + Cx*xij)); I[4] += C[1]*W[a]*((3*B10*Cx*(xij + 2*Cx) + Ix*pow(Cx,3) + f8)); I[5] += C[1]*W[a]*((Iy*pow(Cy,3) + f8 + 3*B10*Cy*(yij + 2*Cy))); I[6] += C[1]*W[a]*((3*B10*Cz*(2*Cz + zij) + f8 + Iz*pow(Cz,3))); I[7] += C[1]*W[a]*(Px*(Cz*zij + Pz)); I[8] += C[1]*W[a]*(Py*(Cz*zij + Pz)); I[9] += C[1]*W[a]*(Cz*Iy*f11); I[10] += C[1]*W[a]*(Cz*Iy*Px); I[11] += C[0]*W[a]*(Cx*Cy*Cz); I[12] += C[1]*W[a]*(Cx*Cz*f5); I[13] += C[1]*W[a]*(Cz*Ix*Py); I[14] += C[1]*W[a]*(Cz*Ix*f11); I[15] += C[0]*W[a]*(Cz*f11); I[16] += C[0]*W[a]*(Cz*Py); I[17] += C[1]*W[a]*(Cy*f6); I[18] += C[1]*W[a]*(Cz*f6); I[19] += C[1]*W[a]*(Px*f5); I[20] += C[1]*W[a]*(Cx*Iz*f0); I[21] += C[1]*W[a]*(Cx*Iz*Py); I[22] += C[0]*W[a]*(Cx*Py); I[23] += C[1]*W[a]*(Cx*f2); I[24] += C[1]*W[a]*(Cz*f2); I[25] += C[0]*W[a]*(Cz*Px); I[26] += C[0]*W[a]*(Cy*Px); I[27] += C[1]*W[a]*(Cy*Iz*Px); I[28] += C[1]*W[a]*(Cy*Iz*f12); I[29] += C[0]*W[a]*(Cy*f12); I[30] += C[1]*W[a]*(Cy*Ix*f12); I[31] += C[1]*W[a]*(Cy*Ix*Pz); I[32] += C[0]*W[a]*(Cy*Pz); I[33] += C[1]*W[a]*(Pz*f5); I[34] += C[0]*W[a]*(Cx*Pz); I[35] += C[1]*W[a]*(Cx*Iy*Pz); I[36] += C[1]*W[a]*(Cx*Iy*f0); I[37] += C[0]*W[a]*(Cx*f0); I[38] += C[1]*W[a]*(Cx*f13); I[39] += C[1]*W[a]*(Cy*f13); } #undef B00 #undef B10 #undef B01 #undef Cx #undef Cy #undef Cz #undef Dx #undef Dy #undef Dz #undef pow } static inline void reorder(double (&I)[40]) { double T[40]; for (int i = 0; i < 40; ++i) { T[i] = I[i]; } I[39] = T[0]; I[19] = T[1]; I[15] = T[2]; I[17] = T[3]; I[10] = T[4]; I[21] = T[5]; I[32] = T[6]; I[34] = T[7]; I[36] = T[8]; I[22] = T[9]; I[24] = T[10]; I[9] = T[11]; I[29] = T[12]; I[16] = T[13]; I[12] = T[14]; I[2] = T[15]; I[6] = T[16]; I[13] = T[17]; I[14] = T[18]; I[23] = T[19]; I[30] = T[20]; I[35] = T[21]; I[5] = T[22]; I[25] = T[23]; I[26] = T[24]; I[4] = T[25]; I[3] = T[26]; I[33] = T[27]; I[31] = T[28]; I[1] = T[29]; I[11] = T[30]; I[18] = T[31]; I[8] = T[32]; I[28] = T[33]; I[7] = T[34]; I[27] = T[35]; I[20] = T[36]; I[0] = T[37]; I[37] = T[38]; I[38] = T[39]; } }; template<> struct impl > { typedef void enable; static const bool value = true; static inline void eval(double A, double B, const Vector<3> &rAi, const Vector<3> &rBk, const Vector<3> &rAB, const Vector<3> &rij, const Vector<3> &rkl, const Vector<3> &t2, const Vector<3> &W, const double (&C)[4], double (&I)[96]) { #define pow(x,y) util::pow<(y)>::eval((x)) const int N = 3; double xij = rij[0]; double yij = rij[1]; double zij = rij[2]; // // double vB00[N] __attribute__ ((aligned(16))); // // // double vB10[N] __attribute__ ((aligned(16))); // // // // double vCx[N] __attribute__ ((aligned(16))); // double vCy[N] __attribute__ ((aligned(16))); // double vCz[N] __attribute__ ((aligned(16))); // // // double vDx[N] __attribute__ ((aligned(16))); // double vDy[N] __attribute__ ((aligned(16))); // double vDz[N] __attribute__ ((aligned(16))); // // for (int a = 0; a < N; ++a) { // // vB00[a] = 0.5*t2[a]; // // // vB10[a] = recurrence::coefficient(1.0/A, B, t2[a]); // // // // vCx[a] = recurrence::coefficient<0>(rAi, B, rAB, t2[a]); // vCy[a] = recurrence::coefficient<1>(rAi, B, rAB, t2[a]); // vCz[a] = recurrence::coefficient<2>(rAi, B, rAB, t2[a]); // // // vDx[a] = recurrence::coefficient<0>(rBk, -A, rAB, t2[a]); // vDy[a] = recurrence::coefficient<1>(rBk, -A, rAB, t2[a]); // vDz[a] = recurrence::coefficient<2>(rBk, -A, rAB, t2[a]); // // } // #define B00 vB00[a] // #define B10 vB10[a] // #define B01 vB01[a] // #define Cx vCx[a] // #define Cy vCy[a] // #define Cz vCz[a] // #define Dx vDx[a] // #define Dy vDy[a] // #define Dz vDz[a] #if defined (__INTEL_COMPILER) #pragma ivdep #pragma vector aligned #endif for (int a = 0; a < N; ++a) { double B00 = 0.5*t2[a]; double B10 = recurrence::coefficient(1.0/A, B, t2[a]); double Cx = recurrence::coefficient<0>(rAi, B, rAB, t2[a]); double Cy = recurrence::coefficient<1>(rAi, B, rAB, t2[a]); double Cz = recurrence::coefficient<2>(rAi, B, rAB, t2[a]); double Dx = recurrence::coefficient<0>(rBk, -A, rAB, t2[a]); double Dy = recurrence::coefficient<1>(rBk, -A, rAB, t2[a]); double Dz = recurrence::coefficient<2>(rBk, -A, rAB, t2[a]); double Ix = (Cx + xij); double Iy = (Cy + yij); double Iz = (Cz + zij); double Px = (B10 + pow(Cx,2)); double Py = (B10 + pow(Cy,2)); double Pz = (B10 + pow(Cz,2)); double Qx = (Cx*Dx + B00); double Qy = (Cy*Dy + B00); double Qz = (Cz*Dz + B00); double f10 = (Dy*Iy + B00); double f15 = (Dx*Ix + B00); I[0] += C[3]*W[a]*(Py*(Dz*zij + Qz)); I[1] += C[3]*W[a]*(Cx*Cy*(Dz*zij + Qz)); I[2] += C[3]*W[a]*(Qy*(Cx*Ix + B10)); I[3] += C[3]*W[a]*(Qz*(Cx*Ix + B10)); I[4] += C[3]*W[a]*(Px*(Dz*zij + Qz)); I[5] += C[3]*W[a]*(Cx*(Dz*(B10 + Cz*Iz) + B00*(2*Cz + zij))); I[6] += C[3]*W[a]*(Cy*(Dz*(B10 + Cz*Iz) + B00*(2*Cz + zij))); I[7] += C[3]*W[a]*(Cz*(B00*(yij + 2*Cy) + Dy*(Cy*Iy + B10))); I[8] += C[3]*W[a]*(Cx*(B00*(yij + 2*Cy) + Dy*(Cy*Iy + B10))); I[9] += C[3]*W[a]*(Iz*(Dy*Py + 2*B00*Cy)); I[10] += C[3]*W[a]*(Ix*(Dy*Py + 2*B00*Cy)); I[11] += C[2]*W[a]*((Dy*Py + 2*B00*Cy)); I[12] += C[3]*W[a]*((2*B00*Cy*yij + 3*B00*Py + Dy*(B10*(3*Cy + yij) + Iy*pow(Cy,2)))); I[13] += C[3]*W[a]*(Qx*(Cy*Iy + B10)); I[14] += C[3]*W[a]*(Qz*(Cy*Iy + B10)); I[15] += C[2]*W[a]*(Cy*Cz*Dx); I[16] += C[3]*W[a]*(Cy*Cz*f15); I[17] += C[3]*W[a]*(Cy*Iz*Qx); I[18] += C[3]*W[a]*(Iz*(Dx*Px + 2*B00*Cx)); I[19] += C[3]*W[a]*(Iy*(Dx*Px + 2*B00*Cx)); I[20] += C[3]*W[a]*(Dz*Iy*Px); I[21] += C[3]*W[a]*(Iy*(Dz*Pz + 2*B00*Cz)); I[22] += C[3]*W[a]*(Ix*(Dz*Pz + 2*B00*Cz)); I[23] += C[2]*W[a]*((Dz*Pz + 2*B00*Cz)); I[24] += C[3]*W[a]*((Dz*(Iz*pow(Cz,2) + B10*(3*Cz + zij)) + 3*B00*Pz + 2*B00*Cz*zij)); I[25] += C[3]*W[a]*(Qy*(B10 + Cz*Iz)); I[26] += C[3]*W[a]*(Qx*(B10 + Cz*Iz)); I[27] += C[3]*W[a]*(Dx*(Iz*pow(Cz,2) + B10*(3*Cz + zij))); I[28] += C[3]*W[a]*(Cy*Dx*(B10 + Cz*Iz)); I[29] += C[1]*W[a]*(Cy*(B10 + Cz*Iz)); I[30] += C[3]*W[a]*(Cx*Dy*(B10 + Cz*Iz)); I[31] += C[2]*W[a]*(Cx*Cz*Dy); I[32] += C[3]*W[a]*(Cz*Ix*Qy); I[33] += C[3]*W[a]*(Cz*Iy*Qx); I[34] += C[1]*W[a]*(Cx*Cz*Iy); I[35] += C[1]*W[a]*(Iy*Pz); I[36] += C[3]*W[a]*(Dx*Iy*Pz); I[37] += C[2]*W[a]*(Dx*Pz); I[38] += C[3]*W[a]*(Cz*(Dx*(Cx*Ix + B10) + B00*(xij + 2*Cx))); I[39] += C[3]*W[a]*(Cy*(Dx*(Cx*Ix + B10) + B00*(xij + 2*Cx))); I[40] += C[3]*W[a]*((Dx*(B10*(3*Cx + xij) + Ix*pow(Cx,2)) + 2*B00*Cx*xij + 3*B00*Px)); I[41] += C[2]*W[a]*((Dx*Px + 2*B00*Cx)); I[42] += C[3]*W[a]*(Px*f10); I[43] += C[3]*W[a]*(Pz*f10); I[44] += C[3]*W[a]*(Cx*Cz*f10); I[45] += C[1]*W[a]*(Cx*(B10 + Cz*Iz)); I[46] += C[1]*W[a]*((Iz*pow(Cz,2) + B10*(3*Cz + zij))); I[47] += C[3]*W[a]*(Dy*(Iz*pow(Cz,2) + B10*(3*Cz + zij))); I[48] += C[2]*W[a]*(Dy*Pz); I[49] += C[3]*W[a]*(Dy*Ix*Pz); I[50] += C[1]*W[a]*(Ix*Pz); I[51] += C[3]*W[a]*(Pz*f15); I[52] += C[3]*W[a]*(Py*f15); I[53] += C[1]*W[a]*(Iz*Py); I[54] += C[3]*W[a]*(Dx*Iz*Py); I[55] += C[2]*W[a]*(Dx*Py); I[56] += C[3]*W[a]*(Dx*(B10*(3*Cy + yij) + Iy*pow(Cy,2))); I[57] += C[3]*W[a]*(Cz*Dx*(Cy*Iy + B10)); I[58] += C[1]*W[a]*(Cz*(Cy*Iy + B10)); I[59] += C[3]*W[a]*(Cx*Dz*(Cy*Iy + B10)); I[60] += C[3]*W[a]*(Cy*Dz*(Cx*Ix + B10)); I[61] += C[3]*W[a]*(Dz*(B10*(3*Cx + xij) + Ix*pow(Cx,2))); I[62] += C[2]*W[a]*(Dz*Px); I[63] += C[2]*W[a]*(Cx*Cy*Dz); I[64] += C[3]*W[a]*(Cy*Ix*Qz); I[65] += C[1]*W[a]*(Cy*Cz*Ix); I[66] += C[0]*W[a]*(Cy*Cz); I[67] += C[2]*W[a]*(Cy*Qx); I[68] += C[2]*W[a]*(Cz*Qx); I[69] += C[0]*W[a]*(Cx*Cz); I[70] += C[3]*W[a]*(Cx*Iz*Qy); I[71] += C[2]*W[a]*(Cx*Qy); I[72] += C[2]*W[a]*(Cz*Qy); I[73] += C[0]*W[a]*(Pz); I[74] += C[1]*W[a]*(Cz*(Cx*Ix + B10)); I[75] += C[3]*W[a]*(Cz*Dy*(Cx*Ix + B10)); I[76] += C[3]*W[a]*(Dy*(B10*(3*Cx + xij) + Ix*pow(Cx,2))); I[77] += C[2]*W[a]*(Dy*Px); I[78] += C[3]*W[a]*(Dy*Iz*Px); I[79] += C[1]*W[a]*(Iz*Px); I[80] += C[1]*W[a]*(Cx*Cy*Iz); I[81] += C[0]*W[a]*(Cx*Cy); I[82] += C[1]*W[a]*(Cx*(Cy*Iy + B10)); I[83] += C[1]*W[a]*((B10*(3*Cy + yij) + Iy*pow(Cy,2))); I[84] += C[3]*W[a]*(Dz*(B10*(3*Cy + yij) + Iy*pow(Cy,2))); I[85] += C[2]*W[a]*(Dz*Py); I[86] += C[3]*W[a]*(Dz*Ix*Py); I[87] += C[1]*W[a]*(Ix*Py); I[88] += C[0]*W[a]*(Py); I[89] += C[1]*W[a]*(Cy*(Cx*Ix + B10)); I[90] += C[1]*W[a]*((B10*(3*Cx + xij) + Ix*pow(Cx,2))); I[91] += C[0]*W[a]*(Px); I[92] += C[1]*W[a]*(Iy*Px); I[93] += C[3]*W[a]*(Cx*Iy*Qz); I[94] += C[2]*W[a]*(Cx*Qz); I[95] += C[2]*W[a]*(Cy*Qz); } #undef B00 #undef B10 #undef B01 #undef Cx #undef Cy #undef Cz #undef Dx #undef Dy #undef Dz #undef pow } static inline void reorder(double (&I)[96]) { double T[96]; for (int i = 0; i < 96; ++i) { T[i] = I[i]; } I[91] = T[0]; I[93] = T[1]; I[57] = T[2]; I[82] = T[3]; I[90] = T[4]; I[94] = T[5]; I[95] = T[6]; I[65] = T[7]; I[63] = T[8]; I[67] = T[9]; I[55] = T[10]; I[49] = T[11]; I[61] = T[12]; I[39] = T[13]; I[89] = T[14]; I[29] = T[15]; I[35] = T[16]; I[45] = T[17]; I[42] = T[18]; I[36] = T[19]; I[84] = T[20]; I[86] = T[21]; I[80] = T[22]; I[74] = T[23]; I[92] = T[24]; I[71] = T[25]; I[46] = T[26]; I[44] = T[27]; I[47] = T[28]; I[23] = T[29]; I[70] = T[30]; I[52] = T[31]; I[59] = T[32]; I[40] = T[33]; I[16] = T[34]; I[14] = T[35]; I[38] = T[36]; I[26] = T[37]; I[34] = T[38]; I[33] = T[39]; I[30] = T[40]; I[24] = T[41]; I[60] = T[42]; I[62] = T[43]; I[64] = T[44]; I[22] = T[45]; I[20] = T[46]; I[68] = T[47]; I[50] = T[48]; I[56] = T[49]; I[8] = T[50]; I[32] = T[51]; I[31] = T[52]; I[19] = T[53]; I[43] = T[54]; I[25] = T[55]; I[37] = T[56]; I[41] = T[57]; I[17] = T[58]; I[87] = T[59]; I[81] = T[60]; I[78] = T[61]; I[72] = T[62]; I[75] = T[63]; I[83] = T[64]; I[11] = T[65]; I[5] = T[66]; I[27] = T[67]; I[28] = T[68]; I[4] = T[69]; I[69] = T[70]; I[51] = T[71]; I[53] = T[72]; I[2] = T[73]; I[10] = T[74]; I[58] = T[75]; I[54] = T[76]; I[48] = T[77]; I[66] = T[78]; I[18] = T[79]; I[21] = T[80]; I[3] = T[81]; I[15] = T[82]; I[13] = T[83]; I[85] = T[84]; I[73] = T[85]; I[79] = T[86]; I[7] = T[87]; I[1] = T[88]; I[9] = T[89]; I[6] = T[90]; I[0] = T[91]; I[12] = T[92]; I[88] = T[93]; I[76] = T[94]; I[77] = T[95]; } }; template<> struct impl > { typedef void enable; static const bool value = true; static inline void eval(double A, double B, const Vector<3> &rAi, const Vector<3> &rBk, const Vector<3> &rAB, const Vector<3> &rij, const Vector<3> &rkl, const Vector<3> &t2, const Vector<3> &W, const double (&C)[8], double (&I)[192]) { #define pow(x,y) util::pow<(y)>::eval((x)) const int N = 3; double xij = rij[0]; double yij = rij[1]; double zij = rij[2]; double xkl = rkl[0]; double ykl = rkl[1]; double zkl = rkl[2]; // // double vB00[N] __attribute__ ((aligned(16))); // // // double vB10[N] __attribute__ ((aligned(16))); // // // double vB01[N] __attribute__ ((aligned(16))); // // // double vCx[N] __attribute__ ((aligned(16))); // double vCy[N] __attribute__ ((aligned(16))); // double vCz[N] __attribute__ ((aligned(16))); // // // double vDx[N] __attribute__ ((aligned(16))); // double vDy[N] __attribute__ ((aligned(16))); // double vDz[N] __attribute__ ((aligned(16))); // // for (int a = 0; a < N; ++a) { // // vB00[a] = 0.5*t2[a]; // // // vB10[a] = recurrence::coefficient(1.0/A, B, t2[a]); // // // vB01[a] = recurrence::coefficient(1.0/B, A, t2[a]); // // // vCx[a] = recurrence::coefficient<0>(rAi, B, rAB, t2[a]); // vCy[a] = recurrence::coefficient<1>(rAi, B, rAB, t2[a]); // vCz[a] = recurrence::coefficient<2>(rAi, B, rAB, t2[a]); // // // vDx[a] = recurrence::coefficient<0>(rBk, -A, rAB, t2[a]); // vDy[a] = recurrence::coefficient<1>(rBk, -A, rAB, t2[a]); // vDz[a] = recurrence::coefficient<2>(rBk, -A, rAB, t2[a]); // // } // #define B00 vB00[a] // #define B10 vB10[a] // #define B01 vB01[a] // #define Cx vCx[a] // #define Cy vCy[a] // #define Cz vCz[a] // #define Dx vDx[a] // #define Dy vDy[a] // #define Dz vDz[a] #if defined (__INTEL_COMPILER) #pragma ivdep #pragma vector aligned #endif for (int a = 0; a < N; ++a) { double B00 = 0.5*t2[a]; double B10 = recurrence::coefficient(1.0/A, B, t2[a]); double B01 = recurrence::coefficient(1.0/B, A, t2[a]); double Cx = recurrence::coefficient<0>(rAi, B, rAB, t2[a]); double Cy = recurrence::coefficient<1>(rAi, B, rAB, t2[a]); double Cz = recurrence::coefficient<2>(rAi, B, rAB, t2[a]); double Dx = recurrence::coefficient<0>(rBk, -A, rAB, t2[a]); double Dy = recurrence::coefficient<1>(rBk, -A, rAB, t2[a]); double Dz = recurrence::coefficient<2>(rBk, -A, rAB, t2[a]); double Ix = (Cx + xij); double Iy = (Cy + yij); double Iz = (Cz + zij); double Kx = (xkl + Dx); double Ky = (ykl + Dy); double Kz = (Dz + zkl); double Px = (B10 + pow(Cx,2)); double Py = (B10 + pow(Cy,2)); double Pz = (B10 + pow(Cz,2)); double Qy = (Cy*Dy + B00); double f1 = B00*zkl; double f11 = 2*B00*Dx; double f14 = Cz*pow(Dz,2); double f19 = Cz*zkl; double f2 = Cx*Dx; double f25 = B01*Cy; double f27 = Cx*xkl; double f3 = B01*B10; double f31 = (Cx*Ix + B10); double f32 = 2*B00*Dy; double f35 = (B01 + Dx*Kx); double f36 = (Cy*Iy + B10); double f38 = Cy*ykl; double f41 = 2*B00*Dz; double f42 = (B01 + Dy*Ky); double f44 = B01*Cx; double f47 = Cx*pow(Dx,2); double f49 = Cz*Dz; double f52 = Cy*pow(Dy,2); double f53 = 2*pow(B00,2); double f58 = B01*Cz; double f59 = (B10 + Cz*Iz); double f6 = B00*ykl; double f7 = Cy*Dy; I[0] += C[7]*W[a]*((f53 + Px*pow(Dx,2) + f44*(Cx + xij) + f3 + Dx*Px*xkl + B00*(2*f27 + 4*f2 + xij*(xkl + 2*Dx)) + xij*(f47 + f2*xkl))); I[1] += C[7]*W[a]*(Cy*(xkl*(B00 + f2) + f11 + f47 + B01*Ix + Dx*Kx*xij)); I[2] += C[7]*W[a]*(Cz*(xkl*(B00 + f2) + f11 + f47 + B01*Ix + Dx*Kx*xij)); I[3] += C[6]*W[a]*((xkl*(B00 + f2) + f11 + f47 + B01*Ix + Dx*Kx*xij)); I[4] += C[7]*W[a]*(Iy*(xkl*(B00 + f2) + f11 + f44 + f47)); I[5] += C[7]*W[a]*(Iz*(xkl*(B00 + f2) + f11 + f44 + f47)); I[6] += C[5]*W[a]*((xkl*(B00 + f2) + f11 + f44 + f47)); I[7] += C[7]*W[a]*(Dz*(xij*(f27 + f2) + Kx*Px + B00*(xij + 2*Cx))); I[8] += C[7]*W[a]*(Dy*(xij*(f27 + f2) + Kx*Px + B00*(xij + 2*Cx))); I[9] += C[3]*W[a]*((xij*(f27 + f2) + Kx*Px + B00*(xij + 2*Cx))); I[10] += C[7]*W[a]*(Ky*(Dx*Px + B00*(xij + 2*Cx) + f2*xij)); I[11] += C[7]*W[a]*(Kz*(Dx*Px + B00*(xij + 2*Cx) + f2*xij)); I[12] += C[7]*W[a]*((yij*(f52 + f25 + f7*ykl + f6) + f53 + Dy*Py*ykl + B01*pow(Cy,2) + f3 + Py*pow(Dy,2) + 2*Cy*f6 + 2*B00*(Dy*yij + 2*f7))); I[13] += C[7]*W[a]*(Cz*(f52 + f25 + f32 + f7*ykl + yij*(B01 + Dy*Ky) + f6)); I[14] += C[7]*W[a]*(Cx*(f52 + f25 + f32 + f7*ykl + yij*(B01 + Dy*Ky) + f6)); I[15] += C[6]*W[a]*((f52 + f25 + f32 + f7*ykl + yij*(B01 + Dy*Ky) + f6)); I[16] += C[7]*W[a]*(Iz*(f52 + f25 + f32 + f7*ykl + f6)); I[17] += C[7]*W[a]*(Ix*(f52 + f25 + f32 + f7*ykl + f6)); I[18] += C[5]*W[a]*((f52 + f25 + f32 + f7*ykl + f6)); I[19] += C[7]*W[a]*(Dz*(B00*(yij + 2*Cy) + yij*(f38 + f7) + Ky*Py)); I[20] += C[7]*W[a]*(Dx*(B00*(yij + 2*Cy) + yij*(f38 + f7) + Ky*Py)); I[21] += C[3]*W[a]*((B00*(yij + 2*Cy) + yij*(f38 + f7) + Ky*Py)); I[22] += C[7]*W[a]*(Kx*(f7*yij + B00*(yij + 2*Cy) + Dy*Py)); I[23] += C[7]*W[a]*(Kz*(f7*yij + B00*(yij + 2*Cy) + Dy*Py)); I[24] += C[7]*W[a]*((f53 + Pz*pow(Dz,2) + Dz*Pz*zkl + f58*(Cz + zij) + zij*(f14 + f1 + Dz*f19) + f3 + 2*Cz*f1 + 2*B00*(2*f49 + Dz*zij))); I[25] += C[7]*W[a]*(Cy*(f14 + Dz*(f19 + 2*B00 + Kz*zij) + f1 + B01*Iz)); I[26] += C[7]*W[a]*(Cx*(f14 + Dz*(f19 + 2*B00 + Kz*zij) + f1 + B01*Iz)); I[27] += C[6]*W[a]*((f14 + Dz*(f19 + 2*B00 + Kz*zij) + f1 + B01*Iz)); I[28] += C[7]*W[a]*(Iy*(f14 + f41 + f58 + f1 + Dz*f19)); I[29] += C[7]*W[a]*(Ix*(f14 + f41 + f58 + f1 + Dz*f19)); I[30] += C[5]*W[a]*((f14 + f41 + f58 + f1 + Dz*f19)); I[31] += C[7]*W[a]*(Dy*(Kz*Pz + zij*(f19 + f49) + B00*(2*Cz + zij))); I[32] += C[7]*W[a]*(Dx*(Kz*Pz + zij*(f19 + f49) + B00*(2*Cz + zij))); I[33] += C[3]*W[a]*((Kz*Pz + zij*(f19 + f49) + B00*(2*Cz + zij))); I[34] += C[7]*W[a]*(Ky*(f49*zij + Dz*Pz + B00*(2*Cz + zij))); I[35] += C[7]*W[a]*(Kx*(f49*zij + Dz*Pz + B00*(2*Cz + zij))); I[36] += C[7]*W[a]*((f38 + Qy)*(f49 + B00 + Dz*zij)); I[37] += C[7]*W[a]*(Qy*(f19 + f49 + B00 + Kz*zij)); I[38] += C[7]*W[a]*((B00 + f2)*(f19 + f49 + B00 + Kz*zij)); I[39] += C[6]*W[a]*(Dx*(f19 + f49 + B00 + Kz*zij)); I[40] += C[7]*W[a]*(Cy*Dx*(f19 + f49 + B00 + Kz*zij)); I[41] += C[3]*W[a]*(Cy*(f19 + f49 + B00 + Kz*zij)); I[42] += C[6]*W[a]*(Dy*(f19 + f49 + B00 + Kz*zij)); I[43] += C[7]*W[a]*(Cx*Dy*(f19 + f49 + B00 + Kz*zij)); I[44] += C[3]*W[a]*(Cx*(f19 + f49 + B00 + Kz*zij)); I[45] += C[2]*W[a]*((f19 + f49 + B00 + Kz*zij)); I[46] += C[7]*W[a]*((f27 + B00 + f2)*(f49 + B00 + Dz*zij)); I[47] += C[7]*W[a]*((Dy*yij + Qy)*(f27 + B00 + f2)); I[48] += C[7]*W[a]*((Dy*yij + Qy)*(f19 + f49 + B00)); I[49] += C[7]*W[a]*((f49 + B00)*(f38 + Ky*yij + Qy)); I[50] += C[7]*W[a]*((B00 + f2)*(f38 + Ky*yij + Qy)); I[51] += C[6]*W[a]*(Dx*(f38 + Ky*yij + Qy)); I[52] += C[7]*W[a]*(Cz*Dx*(f38 + Ky*yij + Qy)); I[53] += C[3]*W[a]*(Cz*(f38 + Ky*yij + Qy)); I[54] += C[6]*W[a]*(Dz*(f38 + Ky*yij + Qy)); I[55] += C[7]*W[a]*(Cx*Dz*(f38 + Ky*yij + Qy)); I[56] += C[3]*W[a]*(Cx*(f38 + Ky*yij + Qy)); I[57] += C[2]*W[a]*((f38 + Ky*yij + Qy)); I[58] += C[7]*W[a]*(Cx*Kz*(Dy*yij + Qy)); I[59] += C[7]*W[a]*(Cz*Kx*(Dy*yij + Qy)); I[60] += C[6]*W[a]*(Kx*(Dy*yij + Qy)); I[61] += C[6]*W[a]*(Kz*(Dy*yij + Qy)); I[62] += C[7]*W[a]*((f38 + Qy)*(B00 + f2 + Dx*xij)); I[63] += C[7]*W[a]*((B00 + f2 + Dx*xij)*(f19 + f49 + B00)); I[64] += C[7]*W[a]*((f49 + B00)*(f27 + Kx*xij + B00 + f2)); I[65] += C[7]*W[a]*(Cy*Dz*(f27 + Kx*xij + B00 + f2)); I[66] += C[6]*W[a]*(Dz*(f27 + Kx*xij + B00 + f2)); I[67] += C[7]*W[a]*(Qy*(f27 + Kx*xij + B00 + f2)); I[68] += C[6]*W[a]*(Dy*(f27 + Kx*xij + B00 + f2)); I[69] += C[7]*W[a]*(Cz*Dy*(f27 + Kx*xij + B00 + f2)); I[70] += C[3]*W[a]*(Cz*(f27 + Kx*xij + B00 + f2)); I[71] += C[2]*W[a]*((f27 + Kx*xij + B00 + f2)); I[72] += C[3]*W[a]*(Cy*(f27 + Kx*xij + B00 + f2)); I[73] += C[7]*W[a]*(Cy*Kz*(B00 + f2 + Dx*xij)); I[74] += C[6]*W[a]*(Kz*(B00 + f2 + Dx*xij)); I[75] += C[7]*W[a]*(Cz*Ky*(B00 + f2 + Dx*xij)); I[76] += C[6]*W[a]*(Ky*(B00 + f2 + Dx*xij)); I[77] += C[7]*W[a]*(Dx*Ky*f59); I[78] += C[7]*W[a]*(Cz*Ix*f42); I[79] += C[7]*W[a]*(Ix*Ky*(f49 + B00)); I[80] += C[7]*W[a]*(Cx*Ky*(f49 + B00 + Dz*zij)); I[81] += C[6]*W[a]*(Ky*(f49 + B00 + Dz*zij)); I[82] += C[7]*W[a]*(Cy*Kx*(f49 + B00 + Dz*zij)); I[83] += C[6]*W[a]*(Kx*(f49 + B00 + Dz*zij)); I[84] += C[7]*W[a]*(Iy*Kx*(f49 + B00)); I[85] += C[5]*W[a]*(Kx*(f49 + B00)); I[86] += C[5]*W[a]*(Dx*(f19 + f49 + B00)); I[87] += C[7]*W[a]*(Dx*Iy*(f19 + f49 + B00)); I[88] += C[3]*W[a]*(Iy*(f19 + f49 + B00)); I[89] += C[5]*W[a]*(Dy*(f19 + f49 + B00)); I[90] += C[7]*W[a]*(Dy*Ix*(f19 + f49 + B00)); I[91] += C[3]*W[a]*(Ix*(f19 + f49 + B00)); I[92] += C[1]*W[a]*((f19 + f49 + B00)); I[93] += C[5]*W[a]*(Ky*(f49 + B00)); I[94] += C[7]*W[a]*(Iz*Ky*(B00 + f2)); I[95] += C[5]*W[a]*(Ky*(B00 + f2)); I[96] += C[7]*W[a]*(Dz*Iy*(f27 + B00 + f2)); I[97] += C[5]*W[a]*(Dz*(f27 + B00 + f2)); I[98] += C[5]*W[a]*(Dy*(f27 + B00 + f2)); I[99] += C[7]*W[a]*(Dy*Iz*(f27 + B00 + f2)); I[100] += C[3]*W[a]*(Iz*(f27 + B00 + f2)); I[101] += C[1]*W[a]*((f27 + B00 + f2)); I[102] += C[3]*W[a]*(Iy*(f27 + B00 + f2)); I[103] += C[7]*W[a]*(Iy*Kz*(B00 + f2)); I[104] += C[5]*W[a]*(Kz*(B00 + f2)); I[105] += C[7]*W[a]*(Ix*Kz*Qy); I[106] += C[7]*W[a]*(Dx*Kz*f36); I[107] += C[7]*W[a]*(f36*(Dz*Kz + B01)); I[108] += C[7]*W[a]*(f31*(Dz*Kz + B01)); I[109] += C[6]*W[a]*(Ix*(Dz*Kz + B01)); I[110] += C[7]*W[a]*(Cy*Ix*(Dz*Kz + B01)); I[111] += C[5]*W[a]*(Cy*(Dz*Kz + B01)); I[112] += C[6]*W[a]*(Iy*(Dz*Kz + B01)); I[113] += C[7]*W[a]*(Cx*Iy*(Dz*Kz + B01)); I[114] += C[5]*W[a]*(Cx*(Dz*Kz + B01)); I[115] += C[4]*W[a]*((Dz*Kz + B01)); I[116] += C[5]*W[a]*(Dz*(f38 + Qy)); I[117] += C[7]*W[a]*(Dz*Ix*(f38 + Qy)); I[118] += C[3]*W[a]*(Ix*(f38 + Qy)); I[119] += C[5]*W[a]*(Dx*(f38 + Qy)); I[120] += C[7]*W[a]*(Dx*Iz*(f38 + Qy)); I[121] += C[3]*W[a]*(Iz*(f38 + Qy)); I[122] += C[7]*W[a]*(Iz*Kx*Qy); I[123] += C[5]*W[a]*(Kx*Qy); I[124] += C[1]*W[a]*((f38 + Qy)); I[125] += C[7]*W[a]*(Cx*Iz*f42); I[126] += C[5]*W[a]*(Cx*f42); I[127] += C[5]*W[a]*(Cz*f42); I[128] += C[6]*W[a]*(Ix*f42); I[129] += C[7]*W[a]*(f31*f42); I[130] += C[6]*W[a]*(Iz*f42); I[131] += C[7]*W[a]*(f42*f59); I[132] += C[3]*W[a]*(Ky*f59); I[133] += C[7]*W[a]*(Dz*Ky*f31); I[134] += C[6]*W[a]*(Dz*Ix*Ky); I[135] += C[2]*W[a]*(Ix*Ky); I[136] += C[3]*W[a]*(Cz*Ix*Ky); I[137] += C[1]*W[a]*(Cz*Ky); I[138] += C[5]*W[a]*(Cz*Dx*Ky); I[139] += C[4]*W[a]*(Dx*Ky); I[140] += C[6]*W[a]*(Dx*Iz*Ky); I[141] += C[2]*W[a]*(Iz*Ky); I[142] += C[3]*W[a]*(Cx*Iz*Ky); I[143] += C[1]*W[a]*(Cx*Ky); I[144] += C[5]*W[a]*(Cx*Dz*Ky); I[145] += C[4]*W[a]*(Dz*Ky); I[146] += C[3]*W[a]*(Ky*f31); I[147] += C[7]*W[a]*(Dy*Kz*f31); I[148] += C[5]*W[a]*(Cx*Dy*Kz); I[149] += C[6]*W[a]*(Dy*Ix*Kz); I[150] += C[3]*W[a]*(Cy*Ix*Kz); I[151] += C[5]*W[a]*(Cy*Dx*Kz); I[152] += C[6]*W[a]*(Dx*Iy*Kz); I[153] += C[3]*W[a]*(Cx*Iy*Kz); I[154] += C[1]*W[a]*(Cx*Kz); I[155] += C[1]*W[a]*(Cy*Kz); I[156] += C[2]*W[a]*(Ix*Kz); I[157] += C[3]*W[a]*(Kz*f31); I[158] += C[2]*W[a]*(Iy*Kz); I[159] += C[4]*W[a]*(Dx*Kz); I[160] += C[4]*W[a]*(Dy*Kz); I[161] += C[5]*W[a]*(Kz*Qy); I[162] += C[3]*W[a]*(Kz*f36); I[163] += C[7]*W[a]*(f35*f36); I[164] += C[6]*W[a]*(Iy*f35); I[165] += C[7]*W[a]*(Cz*Iy*f35); I[166] += C[5]*W[a]*(Cz*f35); I[167] += C[6]*W[a]*(Iz*f35); I[168] += C[7]*W[a]*(Cy*Iz*f35); I[169] += C[5]*W[a]*(Cy*f35); I[170] += C[7]*W[a]*(f35*f59); I[171] += C[7]*W[a]*(Dy*Kx*f59); I[172] += C[3]*W[a]*(Kx*f59); I[173] += C[3]*W[a]*(Kx*f36); I[174] += C[7]*W[a]*(Dz*Kx*f36); I[175] += C[5]*W[a]*(Cy*Dz*Kx); I[176] += C[4]*W[a]*(Dz*Kx); I[177] += C[6]*W[a]*(Dz*Iy*Kx); I[178] += C[2]*W[a]*(Iy*Kx); I[179] += C[3]*W[a]*(Cz*Iy*Kx); I[180] += C[1]*W[a]*(Cz*Kx); I[181] += C[5]*W[a]*(Cz*Dy*Kx); I[182] += C[4]*W[a]*(Dy*Kx); I[183] += C[6]*W[a]*(Dy*Iz*Kx); I[184] += C[2]*W[a]*(Iz*Kx); I[185] += C[3]*W[a]*(Cy*Iz*Kx); I[186] += C[1]*W[a]*(Cy*Kx); I[187] += C[0]*W[a]*(Kx); I[188] += C[4]*W[a]*(f35); I[189] += C[0]*W[a]*(Ky); I[190] += C[4]*W[a]*(f42); I[191] += C[0]*W[a]*(Kz); } #undef B00 #undef B10 #undef B01 #undef Cx #undef Cy #undef Cz #undef Dx #undef Dy #undef Dz #undef pow } static inline void reorder(double (&I)[192]) { double T[192]; for (int i = 0; i < 192; ++i) { T[i] = I[i]; } I[21] = T[0]; I[22] = T[1]; I[23] = T[2]; I[20] = T[3]; I[25] = T[4]; I[29] = T[5]; I[17] = T[6]; I[53] = T[7]; I[37] = T[8]; I[5] = T[9]; I[85] = T[10]; I[149] = T[11]; I[106] = T[12]; I[107] = T[13]; I[105] = T[14]; I[104] = T[15]; I[110] = T[16]; I[102] = T[17]; I[98] = T[18]; I[122] = T[19]; I[90] = T[20]; I[74] = T[21]; I[42] = T[22]; I[170] = T[23]; I[191] = T[24]; I[190] = T[25]; I[189] = T[26]; I[188] = T[27]; I[187] = T[28]; I[183] = T[29]; I[179] = T[30]; I[175] = T[31]; I[159] = T[32]; I[143] = T[33]; I[127] = T[34]; I[63] = T[35]; I[126] = T[36]; I[174] = T[37]; I[157] = T[38]; I[156] = T[39]; I[158] = T[40]; I[142] = T[41]; I[172] = T[42]; I[173] = T[43]; I[141] = T[44]; I[140] = T[45]; I[61] = T[46]; I[41] = T[47]; I[171] = T[48]; I[123] = T[49]; I[89] = T[50]; I[88] = T[51]; I[91] = T[52]; I[75] = T[53]; I[120] = T[54]; I[121] = T[55]; I[73] = T[56]; I[72] = T[57]; I[169] = T[58]; I[43] = T[59]; I[40] = T[60]; I[168] = T[61]; I[86] = T[62]; I[151] = T[63]; I[55] = T[64]; I[54] = T[65]; I[52] = T[66]; I[38] = T[67]; I[36] = T[68]; I[39] = T[69]; I[7] = T[70]; I[4] = T[71]; I[6] = T[72]; I[150] = T[73]; I[148] = T[74]; I[87] = T[75]; I[84] = T[76]; I[95] = T[77]; I[103] = T[78]; I[119] = T[79]; I[125] = T[80]; I[124] = T[81]; I[62] = T[82]; I[60] = T[83]; I[59] = T[84]; I[51] = T[85]; I[147] = T[86]; I[155] = T[87]; I[139] = T[88]; I[163] = T[89]; I[167] = T[90]; I[135] = T[91]; I[131] = T[92]; I[115] = T[93]; I[93] = T[94]; I[81] = T[95]; I[57] = T[96]; I[49] = T[97]; I[33] = T[98]; I[45] = T[99]; I[13] = T[100]; I[1] = T[101]; I[9] = T[102]; I[153] = T[103]; I[145] = T[104]; I[166] = T[105]; I[154] = T[106]; I[186] = T[107]; I[181] = T[108]; I[180] = T[109]; I[182] = T[110]; I[178] = T[111]; I[184] = T[112]; I[185] = T[113]; I[177] = T[114]; I[176] = T[115]; I[114] = T[116]; I[118] = T[117]; I[70] = T[118]; I[82] = T[119]; I[94] = T[120]; I[78] = T[121]; I[46] = T[122]; I[34] = T[123]; I[66] = T[124]; I[109] = T[125]; I[97] = T[126]; I[99] = T[127]; I[100] = T[128]; I[101] = T[129]; I[108] = T[130]; I[111] = T[131]; I[79] = T[132]; I[117] = T[133]; I[116] = T[134]; I[68] = T[135]; I[71] = T[136]; I[67] = T[137]; I[83] = T[138]; I[80] = T[139]; I[92] = T[140]; I[76] = T[141]; I[77] = T[142]; I[65] = T[143]; I[113] = T[144]; I[112] = T[145]; I[69] = T[146]; I[165] = T[147]; I[161] = T[148]; I[164] = T[149]; I[134] = T[150]; I[146] = T[151]; I[152] = T[152]; I[137] = T[153]; I[129] = T[154]; I[130] = T[155]; I[132] = T[156]; I[133] = T[157]; I[136] = T[158]; I[144] = T[159]; I[160] = T[160]; I[162] = T[161]; I[138] = T[162]; I[26] = T[163]; I[24] = T[164]; I[27] = T[165]; I[19] = T[166]; I[28] = T[167]; I[30] = T[168]; I[18] = T[169]; I[31] = T[170]; I[47] = T[171]; I[15] = T[172]; I[10] = T[173]; I[58] = T[174]; I[50] = T[175]; I[48] = T[176]; I[56] = T[177]; I[8] = T[178]; I[11] = T[179]; I[3] = T[180]; I[35] = T[181]; I[32] = T[182]; I[44] = T[183]; I[12] = T[184]; I[14] = T[185]; I[2] = T[186]; I[0] = T[187]; I[16] = T[188]; I[64] = T[189]; I[96] = T[190]; I[128] = T[191]; } }; template<> struct impl > { typedef void enable; static const bool value = true; static inline void eval(double A, double B, const Vector<3> &rAi, const Vector<3> &rBk, const Vector<3> &rAB, const Vector<3> &rij, const Vector<3> &rkl, const Vector<3> &t2, const Vector<3> &W, const double (&C)[2], double (&I)[120]) { #define pow(x,y) util::pow<(y)>::eval((x)) const int N = 3; double xkl = rkl[0]; double ykl = rkl[1]; double zkl = rkl[2]; // // double vB00[N] __attribute__ ((aligned(16))); // // // double vB10[N] __attribute__ ((aligned(16))); // // // double vB01[N] __attribute__ ((aligned(16))); // // // double vCx[N] __attribute__ ((aligned(16))); // double vCy[N] __attribute__ ((aligned(16))); // double vCz[N] __attribute__ ((aligned(16))); // // // double vDx[N] __attribute__ ((aligned(16))); // double vDy[N] __attribute__ ((aligned(16))); // double vDz[N] __attribute__ ((aligned(16))); // // for (int a = 0; a < N; ++a) { // // vB00[a] = 0.5*t2[a]; // // // vB10[a] = recurrence::coefficient(1.0/A, B, t2[a]); // // // vB01[a] = recurrence::coefficient(1.0/B, A, t2[a]); // // // vCx[a] = recurrence::coefficient<0>(rAi, B, rAB, t2[a]); // vCy[a] = recurrence::coefficient<1>(rAi, B, rAB, t2[a]); // vCz[a] = recurrence::coefficient<2>(rAi, B, rAB, t2[a]); // // // vDx[a] = recurrence::coefficient<0>(rBk, -A, rAB, t2[a]); // vDy[a] = recurrence::coefficient<1>(rBk, -A, rAB, t2[a]); // vDz[a] = recurrence::coefficient<2>(rBk, -A, rAB, t2[a]); // // } // #define B00 vB00[a] // #define B10 vB10[a] // #define B01 vB01[a] // #define Cx vCx[a] // #define Cy vCy[a] // #define Cz vCz[a] // #define Dx vDx[a] // #define Dy vDy[a] // #define Dz vDz[a] #if defined (__INTEL_COMPILER) #pragma ivdep #pragma vector aligned #endif for (int a = 0; a < N; ++a) { double B00 = 0.5*t2[a]; double B10 = recurrence::coefficient(1.0/A, B, t2[a]); double B01 = recurrence::coefficient(1.0/B, A, t2[a]); double Cx = recurrence::coefficient<0>(rAi, B, rAB, t2[a]); double Cy = recurrence::coefficient<1>(rAi, B, rAB, t2[a]); double Cz = recurrence::coefficient<2>(rAi, B, rAB, t2[a]); double Dx = recurrence::coefficient<0>(rBk, -A, rAB, t2[a]); double Dy = recurrence::coefficient<1>(rBk, -A, rAB, t2[a]); double Dz = recurrence::coefficient<2>(rBk, -A, rAB, t2[a]); double Kx = (xkl + Dx); double Ky = (ykl + Dy); double Kz = (Dz + zkl); double Px = (B10 + pow(Cx,2)); double Py = (B10 + pow(Cy,2)); double Pz = (B10 + pow(Cz,2)); double Qx = (Cx*Dx + B00); double Qy = (Cy*Dy + B00); double Qz = (Cz*Dz + B00); double f0 = (3*B10 + pow(Cx,2)); double f1 = (Cx*Kx*(3*B10 + pow(Cx,2)) + 3*B00*Px); double f10 = (2*B00*Cx*(xkl + 2*Dx) + 2*pow(B00,2) + Px*(B01 + Dx*Kx)); double f11 = (B01 + Dx*Kx); double f14 = (Kx*Px + 2*B00*Cx); double f16 = (Dy*Py + 2*B00*Cy); double f17 = (2*pow(B00,2) + Pz*(Dz*Kz + B01) + 2*B00*Cz*(2*Dz + zkl)); double f2 = (Dz*Pz + 2*B00*Cz); double f21 = (Dx*Px + 2*B00*Cx); double f22 = (Dz*Kz + B01); double f23 = (B01 + Dy*Ky); double f25 = (B00 + Cx*Kx); double f3 = (Py*(B01 + Dy*Ky) + 2*pow(B00,2) + 2*B00*Cy*(ykl + 2*Dy)); double f31 = (3*B10 + pow(Cz,2)); double f32 = (3*B10 + pow(Cy,2)); double f36 = (B01*Cz + B00*(2*Dz + zkl) + Cz*Dz*Kz); double f4 = (Cy*Dy*Ky + B01*Cy + B00*(ykl + 2*Dy)); double f5 = (3*B00*Py + Cy*Ky*(3*B10 + pow(Cy,2))); double f6 = (Cy*Dy*(3*B10 + pow(Cy,2)) + 3*B00*Py); double f7 = 3*B00*B10; double f8 = (B01*Cx + Cx*Dx*Kx + B00*(xkl + 2*Dx)); I[0] += C[1]*W[a]*((Dy*(2*f7 + Dy*pow(Cy,3) + 3*B10*Cy*Dy) + 6*Cy*pow(B00,2) + ykl*(f7 + Dy*pow(Cy,3) + 3*B10*Cy*Dy) + B01*(3*B10*Cy + pow(Cy,3)) + 3*B00*pow(Cy,2)*(ykl + 2*Dy))); I[1] += C[1]*W[a]*((xkl*(Dx*pow(Cx,3) + 3*B10*Cx*Dx + f7) + Dx*(Dx*pow(Cx,3) + 3*B10*Cx*Dx + 2*f7) + 3*B00*pow(Cx,2)*(xkl + 2*Dx) + 6*Cx*pow(B00,2) + B01*(3*B10*Cx + pow(Cx,3)))); I[2] += C[1]*W[a]*(Kz*(Dx*pow(Cx,3) + 3*B00*pow(Cx,2) + 3*B10*Cx*Dx + f7)); I[3] += C[1]*W[a]*(Ky*(Dx*pow(Cx,3) + 3*B00*pow(Cx,2) + 3*B10*Cx*Dx + f7)); I[4] += C[1]*W[a]*(Ky*(3*B10*Cz*Dz + f7 + 3*B00*pow(Cz,2) + Dz*pow(Cz,3))); I[5] += C[1]*W[a]*(Kx*(3*B10*Cz*Dz + f7 + 3*B00*pow(Cz,2) + Dz*pow(Cz,3))); I[6] += C[1]*W[a]*((Dz*(3*B10*Cz*Dz + 2*f7 + Dz*pow(Cz,3)) + 3*B00*pow(Cz,2)*(2*Dz + zkl) + zkl*(3*B10*Cz*Dz + f7 + Dz*pow(Cz,3)) + B01*(3*B10*Cz + pow(Cz,3)) + 6*Cz*pow(B00,2))); I[7] += C[1]*W[a]*(Dy*(Cz*Kz*f31 + f7 + 3*B00*pow(Cz,2))); I[8] += C[0]*W[a]*((Cz*Kz*f31 + f7 + 3*B00*pow(Cz,2))); I[9] += C[1]*W[a]*(Dx*(Cz*Kz*f31 + f7 + 3*B00*pow(Cz,2))); I[10] += C[1]*W[a]*(Cy*Dx*(Pz*zkl + f2)); I[11] += C[1]*W[a]*(Cx*Dy*(Pz*zkl + f2)); I[12] += C[0]*W[a]*(Cx*(Pz*zkl + f2)); I[13] += C[1]*W[a]*(Qx*(Pz*zkl + f2)); I[14] += C[1]*W[a]*(Qy*(Pz*zkl + f2)); I[15] += C[0]*W[a]*(Cy*(Pz*zkl + f2)); I[16] += C[1]*W[a]*(Qz*(f16 + Py*ykl)); I[17] += C[1]*W[a]*(Qx*(f16 + Py*ykl)); I[18] += C[1]*W[a]*(Cz*Dx*(f16 + Py*ykl)); I[19] += C[0]*W[a]*(Cz*(f16 + Py*ykl)); I[20] += C[1]*W[a]*(Cx*Dz*(f16 + Py*ykl)); I[21] += C[0]*W[a]*(Cx*(f16 + Py*ykl)); I[22] += C[1]*W[a]*(Cx*Qz*(Cy*ykl + Qy)); I[23] += C[0]*W[a]*(Cx*Cz*(Cy*ykl + Qy)); I[24] += C[1]*W[a]*(Cz*Qx*(Cy*ykl + Qy)); I[25] += C[1]*W[a]*(Cy*Qx*(Cz*zkl + Qz)); I[26] += C[0]*W[a]*(Cx*Cy*(Cz*zkl + Qz)); I[27] += C[1]*W[a]*(Cx*Qy*(Cz*zkl + Qz)); I[28] += C[1]*W[a]*(Ky*Px*Qz); I[29] += C[1]*W[a]*(Cx*Ky*f2); I[30] += C[1]*W[a]*(Kz*Py*Qx); I[31] += C[1]*W[a]*(Kz*Px*Qy); I[32] += C[1]*W[a]*(Cx*Kz*f16); I[33] += C[1]*W[a]*(Cx*Pz*f23); I[34] += C[1]*W[a]*(Cx*f0*f23); I[35] += C[1]*W[a]*(Cx*f0*f22); I[36] += C[1]*W[a]*(Cx*Cz*f4); I[37] += C[1]*W[a]*(Cz*Qy*f25); I[38] += C[1]*W[a]*(Cy*Qz*f25); I[39] += C[1]*W[a]*(Kx*Py*Qz); I[40] += C[1]*W[a]*(Cy*Kx*f2); I[41] += C[1]*W[a]*(f2*(Cy*ykl + Qy)); I[42] += C[1]*W[a]*(Dx*Pz*(Cy*ykl + Qy)); I[43] += C[0]*W[a]*(Pz*(Cy*ykl + Qy)); I[44] += C[1]*W[a]*(Dz*Px*(Cy*ykl + Qy)); I[45] += C[0]*W[a]*(Px*(Cy*ykl + Qy)); I[46] += C[1]*W[a]*(f21*(Cy*ykl + Qy)); I[47] += C[1]*W[a]*(Cy*Kz*f21); I[48] += C[0]*W[a]*(Cy*Kz*Px); I[49] += C[1]*W[a]*(Cy*Dx*Kz*f32); I[50] += C[0]*W[a]*(Cy*Kz*f32); I[51] += C[1]*W[a]*(Cy*f22*f32); I[52] += C[1]*W[a]*(Cy*Px*f22); I[53] += C[1]*W[a]*(Cy*Cz*f8); I[54] += C[0]*W[a]*(Cy*Cz*f25); I[55] += C[1]*W[a]*(Cz*Kx*f16); I[56] += C[1]*W[a]*(f16*(Cz*zkl + Qz)); I[57] += C[1]*W[a]*(Dx*Py*(Cz*zkl + Qz)); I[58] += C[0]*W[a]*(Py*(Cz*zkl + Qz)); I[59] += C[1]*W[a]*(Dy*Px*(Cz*zkl + Qz)); I[60] += C[0]*W[a]*(Px*(Cz*zkl + Qz)); I[61] += C[1]*W[a]*(f21*(Cz*zkl + Qz)); I[62] += C[1]*W[a]*(Cz*Ky*f21); I[63] += C[0]*W[a]*(Cz*Ky*Px); I[64] += C[1]*W[a]*(Cz*Px*f23); I[65] += C[1]*W[a]*(Cz*f23*f31); I[66] += C[1]*W[a]*(Cz*f11*f31); I[67] += C[1]*W[a]*(Cz*Py*f11); I[68] += C[0]*W[a]*(Cz*Kx*Py); I[69] += C[1]*W[a]*(Cz*Dy*Kx*f31); I[70] += C[0]*W[a]*(Cz*Kx*f31); I[71] += C[1]*W[a]*(Cz*Dx*Ky*f31); I[72] += C[0]*W[a]*(Cz*Ky*f31); I[73] += C[1]*W[a]*(Ky*Pz*Qx); I[74] += C[0]*W[a]*(Cx*Ky*Pz); I[75] += C[1]*W[a]*(Cx*Dz*Ky*f0); I[76] += C[0]*W[a]*(Cx*Ky*f0); I[77] += C[1]*W[a]*(Cx*Dy*Kz*f0); I[78] += C[0]*W[a]*(Cx*Kz*f0); I[79] += C[0]*W[a]*(Cx*Kz*Py); I[80] += C[1]*W[a]*(Cx*Py*f22); I[81] += C[1]*W[a]*(Cx*Cy*f36); I[82] += C[1]*W[a]*(Cy*Pz*f11); I[83] += C[1]*W[a]*(Cy*f11*f32); I[84] += C[1]*W[a]*(Cy*Dz*Kx*f32); I[85] += C[0]*W[a]*(Cy*Kx*f32); I[86] += C[0]*W[a]*(Cy*Kx*Pz); I[87] += C[1]*W[a]*(Kx*Pz*Qy); I[88] += C[1]*W[a]*(Qy*f14); I[89] += C[1]*W[a]*(Qz*f14); I[90] += C[1]*W[a]*(f16*f25); I[91] += C[1]*W[a]*(f2*f25); I[92] += C[1]*W[a]*(Kx*f6); I[93] += C[1]*W[a]*(Kz*f6); I[94] += C[1]*W[a]*(Pz*f8); I[95] += C[1]*W[a]*(Py*f8); I[96] += C[1]*W[a]*(Dz*Py*f25); I[97] += C[0]*W[a]*(Py*f25); I[98] += C[1]*W[a]*(Dy*Pz*f25); I[99] += C[0]*W[a]*(Pz*f25); I[100] += C[1]*W[a]*(Pz*f4); I[101] += C[1]*W[a]*(Px*f4); I[102] += C[1]*W[a]*(Px*f36); I[103] += C[1]*W[a]*(Py*f36); I[104] += C[1]*W[a]*(Cz*f10); I[105] += C[1]*W[a]*(Cy*f10); I[106] += C[1]*W[a]*(Cy*Dz*f14); I[107] += C[0]*W[a]*(Cy*f14); I[108] += C[1]*W[a]*(Cz*Dy*f14); I[109] += C[0]*W[a]*(Cz*f14); I[110] += C[1]*W[a]*(Cz*f3); I[111] += C[1]*W[a]*(Cx*f3); I[112] += C[1]*W[a]*(Cx*f17); I[113] += C[1]*W[a]*(Cy*f17); I[114] += C[1]*W[a]*(Dx*f5); I[115] += C[1]*W[a]*(Dz*f5); I[116] += C[1]*W[a]*(Dz*f1); I[117] += C[1]*W[a]*(Dy*f1); I[118] += C[0]*W[a]*(f1); I[119] += C[0]*W[a]*(f5); } #undef B00 #undef B10 #undef B01 #undef Cx #undef Cy #undef Cz #undef Dx #undef Dy #undef Dz #undef pow } static inline void reorder(double (&I)[120]) { double T[120]; for (int i = 0; i < 120; ++i) { T[i] = I[i]; } I[61] = T[0]; I[10] = T[1]; I[90] = T[2]; I[50] = T[3]; I[72] = T[4]; I[32] = T[5]; I[112] = T[6]; I[102] = T[7]; I[82] = T[8]; I[92] = T[9]; I[98] = T[10]; I[107] = T[11]; I[87] = T[12]; I[97] = T[13]; I[108] = T[14]; I[88] = T[15]; I[76] = T[16]; I[55] = T[17]; I[56] = T[18]; I[46] = T[19]; I[75] = T[20]; I[45] = T[21]; I[79] = T[22]; I[49] = T[23]; I[59] = T[24]; I[99] = T[25]; I[89] = T[26]; I[109] = T[27]; I[74] = T[28]; I[77] = T[29]; I[95] = T[30]; I[103] = T[31]; I[105] = T[32]; I[67] = T[33]; I[60] = T[34]; I[110] = T[35]; I[69] = T[36]; I[29] = T[37]; I[39] = T[38]; I[36] = T[39]; I[38] = T[40]; I[78] = T[41]; I[58] = T[42]; I[48] = T[43]; I[73] = T[44]; I[43] = T[45]; I[53] = T[46]; I[93] = T[47]; I[83] = T[48]; I[91] = T[49]; I[81] = T[50]; I[111] = T[51]; I[113] = T[52]; I[19] = T[53]; I[9] = T[54]; I[26] = T[55]; I[106] = T[56]; I[96] = T[57]; I[86] = T[58]; I[104] = T[59]; I[84] = T[60]; I[94] = T[61]; I[54] = T[62]; I[44] = T[63]; I[64] = T[64]; I[62] = T[65]; I[12] = T[66]; I[16] = T[67]; I[6] = T[68]; I[22] = T[69]; I[2] = T[70]; I[52] = T[71]; I[42] = T[72]; I[57] = T[73]; I[47] = T[74]; I[70] = T[75]; I[40] = T[76]; I[100] = T[77]; I[80] = T[78]; I[85] = T[79]; I[115] = T[80]; I[119] = T[81]; I[18] = T[82]; I[11] = T[83]; I[31] = T[84]; I[1] = T[85]; I[8] = T[86]; I[28] = T[87]; I[23] = T[88]; I[34] = T[89]; I[25] = T[90]; I[37] = T[91]; I[21] = T[92]; I[101] = T[93]; I[17] = T[94]; I[15] = T[95]; I[35] = T[96]; I[5] = T[97]; I[27] = T[98]; I[7] = T[99]; I[68] = T[100]; I[63] = T[101]; I[114] = T[102]; I[116] = T[103]; I[14] = T[104]; I[13] = T[105]; I[33] = T[106]; I[3] = T[107]; I[24] = T[108]; I[4] = T[109]; I[66] = T[110]; I[65] = T[111]; I[117] = T[112]; I[118] = T[113]; I[51] = T[114]; I[71] = T[115]; I[30] = T[116]; I[20] = T[117]; I[0] = T[118]; I[41] = T[119]; } }; template<> struct impl > { typedef void enable; static const bool value = true; static inline void eval(double A, double B, const Vector<3> &rAi, const Vector<3> &rBk, const Vector<3> &rAB, const Vector<3> &rij, const Vector<3> &rkl, const Vector<2> &t2, const Vector<2> &W, const double (&C)[4], double (&I)[48]) { #define pow(x,y) util::pow<(y)>::eval((x)) const int N = 2; double xij = rij[0]; double yij = rij[1]; double zij = rij[2]; // // double vB00[N] __attribute__ ((aligned(16))); // // // double vB10[N] __attribute__ ((aligned(16))); // // // // double vCx[N] __attribute__ ((aligned(16))); // double vCy[N] __attribute__ ((aligned(16))); // double vCz[N] __attribute__ ((aligned(16))); // // // double vDx[N] __attribute__ ((aligned(16))); // double vDy[N] __attribute__ ((aligned(16))); // double vDz[N] __attribute__ ((aligned(16))); // // for (int a = 0; a < N; ++a) { // // vB00[a] = 0.5*t2[a]; // // // vB10[a] = recurrence::coefficient(1.0/A, B, t2[a]); // // // // vCx[a] = recurrence::coefficient<0>(rAi, B, rAB, t2[a]); // vCy[a] = recurrence::coefficient<1>(rAi, B, rAB, t2[a]); // vCz[a] = recurrence::coefficient<2>(rAi, B, rAB, t2[a]); // // // vDx[a] = recurrence::coefficient<0>(rBk, -A, rAB, t2[a]); // vDy[a] = recurrence::coefficient<1>(rBk, -A, rAB, t2[a]); // vDz[a] = recurrence::coefficient<2>(rBk, -A, rAB, t2[a]); // // } // #define B00 vB00[a] // #define B10 vB10[a] // #define B01 vB01[a] // #define Cx vCx[a] // #define Cy vCy[a] // #define Cz vCz[a] // #define Dx vDx[a] // #define Dy vDy[a] // #define Dz vDz[a] #if defined (__INTEL_COMPILER) #pragma ivdep #pragma vector aligned #endif for (int a = 0; a < N; ++a) { double B00 = 0.5*t2[a]; double B10 = recurrence::coefficient(1.0/A, B, t2[a]); double Cx = recurrence::coefficient<0>(rAi, B, rAB, t2[a]); double Cy = recurrence::coefficient<1>(rAi, B, rAB, t2[a]); double Cz = recurrence::coefficient<2>(rAi, B, rAB, t2[a]); double Dx = recurrence::coefficient<0>(rBk, -A, rAB, t2[a]); double Dy = recurrence::coefficient<1>(rBk, -A, rAB, t2[a]); double Dz = recurrence::coefficient<2>(rBk, -A, rAB, t2[a]); double Ix = (Cx + xij); double Iy = (Cy + yij); double Iz = (Cz + zij); double Px = (B10 + pow(Cx,2)); double Py = (B10 + pow(Cy,2)); double Pz = (B10 + pow(Cz,2)); double Qy = (Cy*Dy + B00); double f1 = Cz*Dz; double f14 = (B10 + Cz*Iz); double f15 = (Cy*Iy + B10); double f4 = Cx*Dx; double f8 = Cy*Dy; double f9 = (Cx*Ix + B10); I[0] += C[3]*W[a]*((B00*(yij + 2*Cy) + f8*yij + Dy*Py)); I[1] += C[3]*W[a]*((f4*xij + Dx*Px + B00*(xij + 2*Cx))); I[2] += C[3]*W[a]*(Cy*(B00 + f4 + Dx*xij)); I[3] += C[3]*W[a]*(Cz*(B00 + f4 + Dx*xij)); I[4] += C[2]*W[a]*((B00 + f4 + Dx*xij)); I[5] += C[3]*W[a]*((Dz*Pz + B00*(2*Cz + zij) + f1*zij)); I[6] += C[3]*W[a]*(Cy*(B00 + Dz*zij + f1)); I[7] += C[3]*W[a]*(Cx*(B00 + Dz*zij + f1)); I[8] += C[2]*W[a]*((B00 + Dz*zij + f1)); I[9] += C[3]*W[a]*(Cz*(Dy*yij + Qy)); I[10] += C[3]*W[a]*(Cx*(Dy*yij + Qy)); I[11] += C[2]*W[a]*((Dy*yij + Qy)); I[12] += C[3]*W[a]*(Ix*Qy); I[13] += C[3]*W[a]*(Iz*Qy); I[14] += C[3]*W[a]*(Iz*(B00 + f4)); I[15] += C[1]*W[a]*((B00 + f4)); I[16] += C[3]*W[a]*(Iy*(B00 + f4)); I[17] += C[3]*W[a]*(Iy*(B00 + f1)); I[18] += C[3]*W[a]*(Ix*(B00 + f1)); I[19] += C[1]*W[a]*((B00 + f1)); I[20] += C[3]*W[a]*(Dx*f14); I[21] += C[3]*W[a]*(Dy*f14); I[22] += C[3]*W[a]*(Dy*f9); I[23] += C[2]*W[a]*(Dy*Ix); I[24] += C[3]*W[a]*(Cz*Dy*Ix); I[25] += C[1]*W[a]*(Cz*Dy); I[26] += C[2]*W[a]*(Dy*Iz); I[27] += C[3]*W[a]*(Cx*Dy*Iz); I[28] += C[1]*W[a]*(Cx*Dy); I[29] += C[3]*W[a]*(Cx*Dz*Iy); I[30] += C[1]*W[a]*(Cx*Dz); I[31] += C[1]*W[a]*(Cy*Dz); I[32] += C[3]*W[a]*(Cy*Dz*Ix); I[33] += C[2]*W[a]*(Dz*Ix); I[34] += C[3]*W[a]*(Dz*f9); I[35] += C[2]*W[a]*(Dz*Iy); I[36] += C[3]*W[a]*(Dz*f15); I[37] += C[3]*W[a]*(Dx*f15); I[38] += C[2]*W[a]*(Dx*Iy); I[39] += C[3]*W[a]*(Cz*Dx*Iy); I[40] += C[1]*W[a]*(Cz*Dx); I[41] += C[2]*W[a]*(Dx*Iz); I[42] += C[3]*W[a]*(Cy*Dx*Iz); I[43] += C[1]*W[a]*(Cy*Dx); I[44] += C[0]*W[a]*(Dx); I[45] += C[0]*W[a]*(Dy); I[46] += C[1]*W[a]*(Qy); I[47] += C[0]*W[a]*(Dz); } #undef B00 #undef B10 #undef B01 #undef Cx #undef Cy #undef Cz #undef Dx #undef Dy #undef Dz #undef pow } static inline void reorder(double (&I)[48]) { double T[48]; for (int i = 0; i < 48; ++i) { T[i] = I[i]; } I[26] = T[0]; I[5] = T[1]; I[6] = T[2]; I[7] = T[3]; I[4] = T[4]; I[47] = T[5]; I[46] = T[6]; I[45] = T[7]; I[44] = T[8]; I[27] = T[9]; I[25] = T[10]; I[24] = T[11]; I[22] = T[12]; I[30] = T[13]; I[13] = T[14]; I[1] = T[15]; I[9] = T[16]; I[43] = T[17]; I[39] = T[18]; I[35] = T[19]; I[15] = T[20]; I[31] = T[21]; I[21] = T[22]; I[20] = T[23]; I[23] = T[24]; I[19] = T[25]; I[28] = T[26]; I[29] = T[27]; I[17] = T[28]; I[41] = T[29]; I[33] = T[30]; I[34] = T[31]; I[38] = T[32]; I[36] = T[33]; I[37] = T[34]; I[40] = T[35]; I[42] = T[36]; I[10] = T[37]; I[8] = T[38]; I[11] = T[39]; I[3] = T[40]; I[12] = T[41]; I[14] = T[42]; I[2] = T[43]; I[0] = T[44]; I[16] = T[45]; I[18] = T[46]; I[32] = T[47]; } }; template<> struct impl > { typedef void enable; static const bool value = true; static inline void eval(double A, double B, const Vector<3> &rAi, const Vector<3> &rBk, const Vector<3> &rAB, const Vector<3> &rij, const Vector<3> &rkl, const Vector<3> &t2, const Vector<3> &W, const double (&C)[2], double (&I)[72]) { #define pow(x,y) util::pow<(y)>::eval((x)) const int N = 3; double xij = rij[0]; double yij = rij[1]; double zij = rij[2]; // // double vB00[N] __attribute__ ((aligned(16))); // // // double vB10[N] __attribute__ ((aligned(16))); // // // // double vCx[N] __attribute__ ((aligned(16))); // double vCy[N] __attribute__ ((aligned(16))); // double vCz[N] __attribute__ ((aligned(16))); // // // double vDx[N] __attribute__ ((aligned(16))); // double vDy[N] __attribute__ ((aligned(16))); // double vDz[N] __attribute__ ((aligned(16))); // // for (int a = 0; a < N; ++a) { // // vB00[a] = 0.5*t2[a]; // // // vB10[a] = recurrence::coefficient(1.0/A, B, t2[a]); // // // // vCx[a] = recurrence::coefficient<0>(rAi, B, rAB, t2[a]); // vCy[a] = recurrence::coefficient<1>(rAi, B, rAB, t2[a]); // vCz[a] = recurrence::coefficient<2>(rAi, B, rAB, t2[a]); // // // vDx[a] = recurrence::coefficient<0>(rBk, -A, rAB, t2[a]); // vDy[a] = recurrence::coefficient<1>(rBk, -A, rAB, t2[a]); // vDz[a] = recurrence::coefficient<2>(rBk, -A, rAB, t2[a]); // // } // #define B00 vB00[a] // #define B10 vB10[a] // #define B01 vB01[a] // #define Cx vCx[a] // #define Cy vCy[a] // #define Cz vCz[a] // #define Dx vDx[a] // #define Dy vDy[a] // #define Dz vDz[a] #if defined (__INTEL_COMPILER) #pragma ivdep #pragma vector aligned #endif for (int a = 0; a < N; ++a) { double B00 = 0.5*t2[a]; double B10 = recurrence::coefficient(1.0/A, B, t2[a]); double Cx = recurrence::coefficient<0>(rAi, B, rAB, t2[a]); double Cy = recurrence::coefficient<1>(rAi, B, rAB, t2[a]); double Cz = recurrence::coefficient<2>(rAi, B, rAB, t2[a]); double Dx = recurrence::coefficient<0>(rBk, -A, rAB, t2[a]); double Dy = recurrence::coefficient<1>(rBk, -A, rAB, t2[a]); double Dz = recurrence::coefficient<2>(rBk, -A, rAB, t2[a]); double Ix = (Cx + xij); double Iy = (Cy + yij); double Iz = (Cz + zij); double Px = (B10 + pow(Cx,2)); double Py = (B10 + pow(Cy,2)); double Pz = (B10 + pow(Cz,2)); double Qx = (Cx*Dx + B00); double Qy = (Cy*Dy + B00); double Qz = (Cz*Dz + B00); double f1 = (B00*(yij + 2*Cy) + Dy*(Cy*Iy + B10)); double f10 = (Cy*Iy + B10); double f11 = (B10*(3*Cx + xij) + Ix*pow(Cx,2)); double f13 = (Dx*Px + 2*B00*Cx); double f14 = (Dx*Ix + B00); double f21 = (Iz*pow(Cz,2) + B10*(3*Cz + zij)); double f24 = (B10*(3*Cy + yij) + Iy*pow(Cy,2)); double f3 = 3*B00*B10; double f4 = (Dy*Py + 2*B00*Cy); double f5 = (Dz*Pz + 2*B00*Cz); double f7 = (Dx*(Cx*Ix + B10) + B00*(xij + 2*Cx)); double f9 = (Dy*Iy + B00); I[0] += C[1]*W[a]*((Dx*Ix*pow(Cx,2) + B00*Cx*(3*Cx + 2*xij) + B10*Dx*(3*Cx + xij) + f3)); I[1] += C[1]*W[a]*((Dy*Iy*pow(Cy,2) + f3 + B00*Cy*(3*Cy + 2*yij) + B10*Dy*(3*Cy + yij))); I[2] += C[1]*W[a]*((B00*Cz*(3*Cz + 2*zij) + Dz*Iz*pow(Cz,2) + B10*Dz*(3*Cz + zij) + f3)); I[3] += C[1]*W[a]*(Cx*(f5 + Qz*zij)); I[4] += C[1]*W[a]*(Cy*(f5 + Qz*zij)); I[5] += C[1]*W[a]*(Cx*Cy*(Dz*zij + Qz)); I[6] += C[1]*W[a]*(Py*(Dz*zij + Qz)); I[7] += C[1]*W[a]*(Px*(Dz*zij + Qz)); I[8] += C[1]*W[a]*(Qz*(Px + Cx*xij)); I[9] += C[1]*W[a]*(Qy*(Px + Cx*xij)); I[10] += C[1]*W[a]*(Cy*Dz*(Px + Cx*xij)); I[11] += C[0]*W[a]*(Cy*(Px + Cx*xij)); I[12] += C[1]*W[a]*(Cz*Dy*(Px + Cx*xij)); I[13] += C[0]*W[a]*(Cz*(Px + Cx*xij)); I[14] += C[1]*W[a]*(Cx*Cz*f9); I[15] += C[1]*W[a]*(Dy*Iz*Px); I[16] += C[1]*W[a]*(Cy*Iz*Qx); I[17] += C[0]*W[a]*(Cx*Cy*Iz); I[18] += C[1]*W[a]*(Cx*Iz*Qy); I[19] += C[1]*W[a]*(Cz*Ix*Qy); I[20] += C[1]*W[a]*(Qy*(Cz*zij + Pz)); I[21] += C[1]*W[a]*(Qx*(Cz*zij + Pz)); I[22] += C[1]*W[a]*(Cx*Dy*(Cz*zij + Pz)); I[23] += C[0]*W[a]*(Cx*(Cz*zij + Pz)); I[24] += C[1]*W[a]*(Cy*Dx*(Cz*zij + Pz)); I[25] += C[0]*W[a]*(Cy*(Cz*zij + Pz)); I[26] += C[1]*W[a]*(Cy*Cz*f14); I[27] += C[0]*W[a]*(Cy*Cz*Ix); I[28] += C[1]*W[a]*(Cy*Ix*Qz); I[29] += C[1]*W[a]*(Cx*Iy*Qz); I[30] += C[0]*W[a]*(Cx*Cz*Iy); I[31] += C[1]*W[a]*(Cz*Iy*Qx); I[32] += C[1]*W[a]*(Qx*f10); I[33] += C[1]*W[a]*(Iy*f13); I[34] += C[1]*W[a]*(Iz*f13); I[35] += C[1]*W[a]*(Ix*f4); I[36] += C[1]*W[a]*(Cx*f1); I[37] += C[1]*W[a]*(Cz*f1); I[38] += C[1]*W[a]*(Px*f9); I[39] += C[1]*W[a]*(Pz*f9); I[40] += C[1]*W[a]*(Pz*f14); I[41] += C[1]*W[a]*(Py*f14); I[42] += C[1]*W[a]*(Dx*Iz*Py); I[43] += C[0]*W[a]*(Iz*Py); I[44] += C[1]*W[a]*(Iz*f4); I[45] += C[0]*W[a]*(Iz*Px); I[46] += C[1]*W[a]*(Dz*Iy*Px); I[47] += C[0]*W[a]*(Iy*Px); I[48] += C[1]*W[a]*(Dx*Iy*Pz); I[49] += C[0]*W[a]*(Iy*Pz); I[50] += C[1]*W[a]*(Dy*Ix*Pz); I[51] += C[0]*W[a]*(Ix*Pz); I[52] += C[1]*W[a]*(Dz*Ix*Py); I[53] += C[0]*W[a]*(Ix*Py); I[54] += C[1]*W[a]*(Ix*f5); I[55] += C[1]*W[a]*(Iy*f5); I[56] += C[1]*W[a]*(Cy*f7); I[57] += C[1]*W[a]*(Cz*f7); I[58] += C[1]*W[a]*(Cz*Dx*f10); I[59] += C[0]*W[a]*(Cz*f10); I[60] += C[1]*W[a]*(Cx*Dz*f10); I[61] += C[0]*W[a]*(Cx*f10); I[62] += C[1]*W[a]*(Qz*f10); I[63] += C[1]*W[a]*(Dz*f11); I[64] += C[1]*W[a]*(Dz*f24); I[65] += C[1]*W[a]*(Dx*f24); I[66] += C[1]*W[a]*(Dx*f21); I[67] += C[1]*W[a]*(Dy*f21); I[68] += C[1]*W[a]*(Dy*f11); I[69] += C[0]*W[a]*(f11); I[70] += C[0]*W[a]*(f24); I[71] += C[0]*W[a]*(f21); } #undef B00 #undef B10 #undef B01 #undef Cx #undef Cy #undef Cz #undef Dx #undef Dy #undef Dz #undef pow } static inline void reorder(double (&I)[72]) { double T[72]; for (int i = 0; i < 72; ++i) { T[i] = I[i]; } I[18] = T[0]; I[43] = T[1]; I[68] = T[2]; I[70] = T[3]; I[71] = T[4]; I[69] = T[5]; I[67] = T[6]; I[66] = T[7]; I[58] = T[8]; I[39] = T[9]; I[57] = T[10]; I[3] = T[11]; I[40] = T[12]; I[4] = T[13]; I[46] = T[14]; I[48] = T[15]; I[33] = T[16]; I[15] = T[17]; I[51] = T[18]; I[41] = T[19]; I[53] = T[20]; I[34] = T[21]; I[52] = T[22]; I[16] = T[23]; I[35] = T[24]; I[17] = T[25]; I[23] = T[26]; I[5] = T[27]; I[59] = T[28]; I[64] = T[29]; I[10] = T[30]; I[28] = T[31]; I[27] = T[32]; I[24] = T[33]; I[30] = T[34]; I[37] = T[35]; I[45] = T[36]; I[47] = T[37]; I[42] = T[38]; I[44] = T[39]; I[20] = T[40]; I[19] = T[41]; I[31] = T[42]; I[13] = T[43]; I[49] = T[44]; I[12] = T[45]; I[60] = T[46]; I[6] = T[47]; I[26] = T[48]; I[8] = T[49]; I[38] = T[50]; I[2] = T[51]; I[55] = T[52]; I[1] = T[53]; I[56] = T[54]; I[62] = T[55]; I[21] = T[56]; I[22] = T[57]; I[29] = T[58]; I[11] = T[59]; I[63] = T[60]; I[9] = T[61]; I[65] = T[62]; I[54] = T[63]; I[61] = T[64]; I[25] = T[65]; I[32] = T[66]; I[50] = T[67]; I[36] = T[68]; I[0] = T[69]; I[7] = T[70]; I[14] = T[71]; } }; template<> struct impl > { typedef void enable; static const bool value = true; static inline void eval(double A, double B, const Vector<3> &rAi, const Vector<3> &rBk, const Vector<3> &rAB, const Vector<3> &rij, const Vector<3> &rkl, const Vector<2> &t2, const Vector<2> &W, const double (&C)[4], double (&I)[16]) { #define pow(x,y) util::pow<(y)>::eval((x)) const int N = 2; double xij = rij[0]; double yij = rij[1]; double zij = rij[2]; // // // double vB10[N] __attribute__ ((aligned(16))); // // // // double vCx[N] __attribute__ ((aligned(16))); // double vCy[N] __attribute__ ((aligned(16))); // double vCz[N] __attribute__ ((aligned(16))); // // // for (int a = 0; a < N; ++a) { // // // vB10[a] = recurrence::coefficient(1.0/A, B, t2[a]); // // // // vCx[a] = recurrence::coefficient<0>(rAi, B, rAB, t2[a]); // vCy[a] = recurrence::coefficient<1>(rAi, B, rAB, t2[a]); // vCz[a] = recurrence::coefficient<2>(rAi, B, rAB, t2[a]); // // // } // #define B00 vB00[a] // #define B10 vB10[a] // #define B01 vB01[a] // #define Cx vCx[a] // #define Cy vCy[a] // #define Cz vCz[a] // #define Dx vDx[a] // #define Dy vDy[a] // #define Dz vDz[a] #if defined (__INTEL_COMPILER) #pragma ivdep #pragma vector aligned #endif for (int a = 0; a < N; ++a) { double B10 = recurrence::coefficient(1.0/A, B, t2[a]); double Cx = recurrence::coefficient<0>(rAi, B, rAB, t2[a]); double Cy = recurrence::coefficient<1>(rAi, B, rAB, t2[a]); double Cz = recurrence::coefficient<2>(rAi, B, rAB, t2[a]); double Ix = (Cx + xij); double Iy = (Cy + yij); double Iz = (Cz + zij); I[0] += C[3]*W[a]*((Cy*Iy + B10)); I[1] += C[3]*W[a]*((B10 + Cz*Iz)); I[2] += C[3]*W[a]*((Cx*Ix + B10)); I[3] += C[3]*W[a]*(Cx*Iz); I[4] += C[3]*W[a]*(Cy*Iz); I[5] += C[3]*W[a]*(Cy*Ix); I[6] += C[3]*W[a]*(Cz*Ix); I[7] += C[3]*W[a]*(Cz*Iy); I[8] += C[3]*W[a]*(Cx*Iy); I[9] += C[1]*W[a]*(Cx); I[10] += C[1]*W[a]*(Cy); I[11] += C[1]*W[a]*(Cz); I[12] += C[2]*W[a]*(Ix); I[13] += C[2]*W[a]*(Iy); I[14] += C[2]*W[a]*(Iz); I[15] += C[0]*W[a]*(1); } #undef B00 #undef B10 #undef B01 #undef Cx #undef Cy #undef Cz #undef Dx #undef Dy #undef Dz #undef pow } static inline void reorder(double (&I)[16]) { double T[16]; for (int i = 0; i < 16; ++i) { T[i] = I[i]; } I[10] = T[0]; I[15] = T[1]; I[5] = T[2]; I[13] = T[3]; I[14] = T[4]; I[6] = T[5]; I[7] = T[6]; I[11] = T[7]; I[9] = T[8]; I[1] = T[9]; I[2] = T[10]; I[3] = T[11]; I[4] = T[12]; I[8] = T[13]; I[12] = T[14]; I[0] = T[15]; } }; template<> struct impl > { typedef void enable; static const bool value = true; static inline void eval(double A, double B, const Vector<3> &rAi, const Vector<3> &rBk, const Vector<3> &rAB, const Vector<3> &rij, const Vector<3> &rkl, const Vector<3> &t2, const Vector<3> &W, const double (&C)[2], double (&I)[144]) { #define pow(x,y) util::pow<(y)>::eval((x)) const int N = 3; double xij = rij[0]; double yij = rij[1]; double zij = rij[2]; // // double vB00[N] __attribute__ ((aligned(16))); // // // double vB10[N] __attribute__ ((aligned(16))); // // // // double vCx[N] __attribute__ ((aligned(16))); // double vCy[N] __attribute__ ((aligned(16))); // double vCz[N] __attribute__ ((aligned(16))); // // // double vDx[N] __attribute__ ((aligned(16))); // double vDy[N] __attribute__ ((aligned(16))); // double vDz[N] __attribute__ ((aligned(16))); // // for (int a = 0; a < N; ++a) { // // vB00[a] = 0.5*t2[a]; // // // vB10[a] = recurrence::coefficient(1.0/A, B, t2[a]); // // // // vCx[a] = recurrence::coefficient<0>(rAi, B, rAB, t2[a]); // vCy[a] = recurrence::coefficient<1>(rAi, B, rAB, t2[a]); // vCz[a] = recurrence::coefficient<2>(rAi, B, rAB, t2[a]); // // // vDx[a] = recurrence::coefficient<0>(rBk, -A, rAB, t2[a]); // vDy[a] = recurrence::coefficient<1>(rBk, -A, rAB, t2[a]); // vDz[a] = recurrence::coefficient<2>(rBk, -A, rAB, t2[a]); // // } // #define B00 vB00[a] // #define B10 vB10[a] // #define B01 vB01[a] // #define Cx vCx[a] // #define Cy vCy[a] // #define Cz vCz[a] // #define Dx vDx[a] // #define Dy vDy[a] // #define Dz vDz[a] #if defined (__INTEL_COMPILER) #pragma ivdep #pragma vector aligned #endif for (int a = 0; a < N; ++a) { double B00 = 0.5*t2[a]; double B10 = recurrence::coefficient(1.0/A, B, t2[a]); double Cx = recurrence::coefficient<0>(rAi, B, rAB, t2[a]); double Cy = recurrence::coefficient<1>(rAi, B, rAB, t2[a]); double Cz = recurrence::coefficient<2>(rAi, B, rAB, t2[a]); double Dx = recurrence::coefficient<0>(rBk, -A, rAB, t2[a]); double Dy = recurrence::coefficient<1>(rBk, -A, rAB, t2[a]); double Dz = recurrence::coefficient<2>(rBk, -A, rAB, t2[a]); double Ix = (Cx + xij); double Iy = (Cy + yij); double Iz = (Cz + zij); double Px = (B10 + pow(Cx,2)); double Py = (B10 + pow(Cy,2)); double Pz = (B10 + pow(Cz,2)); double Qx = (Cx*Dx + B00); double Qy = (Cy*Dy + B00); double Qz = (Cz*Dz + B00); double f1 = (Dz*Pz + 2*B00*Cz); double f11 = (Dz*(Iz*pow(Cz,2) + B10*(3*Cz + zij)) + 3*B00*Pz + 2*B00*Cz*zij); double f12 = (B00 + Dz*Iz); double f15 = (B00*(3*B10 + Ix*(3*Cx + xij)) + Dx*(B10*(3*Cx + 2*xij) + Cx*pow(Ix,2))); double f17 = (Dx*(B10*(3*Cx + xij) + Ix*pow(Cx,2)) + 2*B00*Cx*xij + 3*B00*Px); double f18 = (B10 + pow(Iy,2)); double f2 = (B10*(3*Cx + 2*xij) + Cx*pow(Ix,2)); double f22 = (2*B00*Cy*yij + 3*B00*Py + Dy*(B10*(3*Cy + yij) + Iy*pow(Cy,2))); double f25 = (B00*(Iz*(3*Cz + zij) + 3*B10) + Dz*(B10*(3*Cz + 2*zij) + Cz*pow(Iz,2))); double f27 = (B10*(3*Cz + 2*zij) + Cz*pow(Iz,2)); double f28 = (Cy*Iy + B10); double f29 = (B10*(3*Cx + xij) + Ix*pow(Cx,2)); double f3 = (3*pow(B10,2) + pow(Cz,2)*pow(Iz,2) + B10*(6*Cz*zij + pow(zij,2) + 6*pow(Cz,2))); double f30 = (B00*(yij + 2*Cy) + Dy*(Cy*Iy + B10)); double f35 = (B10*(3*Cy + yij) + Iy*pow(Cy,2)); double f36 = (Dy*Py + 2*B00*Cy); double f37 = (Dy*(Cy*pow(Iy,2) + B10*(3*Cy + 2*yij)) + B00*(3*B10 + Iy*(3*Cy + yij))); double f38 = 3*pow(B10,2); double f4 = (3*pow(B10,2) + B10*(6*Cx*xij + pow(xij,2) + 6*pow(Cx,2)) + pow(Cx,2)*pow(Ix,2)); double f41 = (Iz*pow(Cz,2) + B10*(3*Cz + zij)); double f5 = (3*pow(B10,2) + B10*(6*Cy*yij + pow(yij,2) + 6*pow(Cy,2)) + pow(Cy,2)*pow(Iy,2)); double f6 = (2*B00*Iy + Dy*(B10 + pow(Iy,2))); double f7 = (Dx*Px + 2*B00*Cx); double f8 = (Cy*pow(Iy,2) + B10*(3*Cy + 2*yij)); I[0] += C[1]*W[a]*((Px + Cx*xij)*(f1 + Qz*zij)); I[1] += C[1]*W[a]*(Cy*Ix*(f1 + Qz*zij)); I[2] += C[1]*W[a]*(Cx*Cy*(zij*(2*B00 + Dz*(2*Cz + zij)) + f1)); I[3] += C[1]*W[a]*(Cx*Iy*(f1 + Qz*zij)); I[4] += C[1]*W[a]*((2*B00*(xij + 2*Cx)*(Cx*Ix + 3*B10) + Dx*(f38 + B10*(6*Cx*xij + pow(xij,2) + 6*pow(Cx,2)) + pow(Cx,2)*pow(Ix,2)))); I[5] += C[1]*W[a]*((2*B00*(yij + 2*Cy)*(3*B10 + Cy*Iy) + Dy*(B10*(6*Cy*yij + pow(yij,2) + 6*pow(Cy,2)) + f38 + pow(Cy,2)*pow(Iy,2)))); I[6] += C[1]*W[a]*((2*B00*(2*Cz + zij)*(3*B10 + Cz*Iz) + Dz*(f38 + pow(Cz,2)*pow(Iz,2) + B10*(6*Cz*zij + pow(zij,2) + 6*pow(Cz,2))))); I[7] += C[1]*W[a]*(Py*(zij*(2*B00 + Dz*(2*Cz + zij)) + f1)); I[8] += C[1]*W[a]*(Px*(zij*(2*B00 + Dz*(2*Cz + zij)) + f1)); I[9] += C[1]*W[a]*(f28*(f1 + Qz*zij)); I[10] += C[1]*W[a]*(Cy*(Cz*zij + Pz)*(Dx*xij + Qx)); I[11] += C[1]*W[a]*(Iz*Py*(Dx*xij + Qx)); I[12] += C[1]*W[a]*(Cy*Iz*(Qx*xij + f7)); I[13] += C[1]*W[a]*(Cz*Iy*(Qx*xij + f7)); I[14] += C[1]*W[a]*(Cy*Cz*(xij*(2*B00 + Dx*(xij + 2*Cx)) + f7)); I[15] += C[1]*W[a]*(f28*(Qx*xij + f7)); I[16] += C[1]*W[a]*(Py*(xij*(2*B00 + Dx*(xij + 2*Cx)) + f7)); I[17] += C[1]*W[a]*(Pz*(xij*(2*B00 + Dx*(xij + 2*Cx)) + f7)); I[18] += C[1]*W[a]*((Cz*zij + Pz)*(Qx*xij + f7)); I[19] += C[1]*W[a]*(Cx*(Cz*zij + Pz)*(Dy*yij + Qy)); I[20] += C[1]*W[a]*(Ix*Pz*(Dy*yij + Qy)); I[21] += C[1]*W[a]*(Iz*Px*(Dy*yij + Qy)); I[22] += C[1]*W[a]*(f29*(Dy*yij + Qy)); I[23] += C[1]*W[a]*(f41*(Dy*yij + Qy)); I[24] += C[1]*W[a]*(Cz*(Px + Cx*xij)*(Dy*yij + Qy)); I[25] += C[1]*W[a]*(Dy*(Px + Cx*xij)*(Cz*zij + Pz)); I[26] += C[0]*W[a]*((Px + Cx*xij)*(Cz*zij + Pz)); I[27] += C[1]*W[a]*(Cy*f12*(Px + Cx*xij)); I[28] += C[1]*W[a]*(Iy*Qz*(Px + Cx*xij)); I[29] += C[1]*W[a]*(Cy*Qz*(xij*(xij + 2*Cx) + Px)); I[30] += C[0]*W[a]*(Cy*Iz*(Px + Cx*xij)); I[31] += C[1]*W[a]*(Iz*Qy*(Px + Cx*xij)); I[32] += C[1]*W[a]*(Cz*Qy*(xij*(xij + 2*Cx) + Px)); I[33] += C[0]*W[a]*(Cz*Iy*(Px + Cx*xij)); I[34] += C[0]*W[a]*(Cy*Cz*(xij*(xij + 2*Cx) + Px)); I[35] += C[1]*W[a]*(f30*(Px + Cx*xij)); I[36] += C[1]*W[a]*(f36*(xij*(xij + 2*Cx) + Px)); I[37] += C[1]*W[a]*(Dy*Pz*(xij*(xij + 2*Cx) + Px)); I[38] += C[0]*W[a]*(Pz*(xij*(xij + 2*Cx) + Px)); I[39] += C[0]*W[a]*(f28*(Px + Cx*xij)); I[40] += C[1]*W[a]*(Dz*f28*(Px + Cx*xij)); I[41] += C[1]*W[a]*(Dz*Py*(xij*(xij + 2*Cx) + Px)); I[42] += C[0]*W[a]*(Py*(xij*(xij + 2*Cx) + Px)); I[43] += C[1]*W[a]*(f1*(xij*(xij + 2*Cx) + Px)); I[44] += C[1]*W[a]*(Cx*Cz*f6); I[45] += C[1]*W[a]*(Ix*Iz*f36); I[46] += C[1]*W[a]*(Cx*Iz*f30); I[47] += C[1]*W[a]*(Cx*Dz*f8); I[48] += C[1]*W[a]*(Cx*Qz*f18); I[49] += C[0]*W[a]*(Cx*Cz*f18); I[50] += C[1]*W[a]*(Cz*Qx*f18); I[51] += C[1]*W[a]*(Cz*f28*(Dx*xij + Qx)); I[52] += C[1]*W[a]*(Iy*Pz*(Dx*xij + Qx)); I[53] += C[1]*W[a]*(f41*(Dx*xij + Qx)); I[54] += C[1]*W[a]*(f35*(Dx*xij + Qx)); I[55] += C[1]*W[a]*(Dx*Iz*f35); I[56] += C[1]*W[a]*(Dz*Ix*f35); I[57] += C[1]*W[a]*(Ix*Qz*f28); I[58] += C[1]*W[a]*(Ix*Py*f12); I[59] += C[0]*W[a]*(Ix*Iz*Py); I[60] += C[1]*W[a]*(Iy*Iz*f7); I[61] += C[0]*W[a]*(Iy*Iz*Px); I[62] += C[1]*W[a]*(Iy*Px*f12); I[63] += C[1]*W[a]*(Ix*Iy*f1); I[64] += C[0]*W[a]*(Ix*Iy*Pz); I[65] += C[1]*W[a]*(Ix*Qy*(Cz*zij + Pz)); I[66] += C[1]*W[a]*(Cx*Qy*(zij*(2*Cz + zij) + Pz)); I[67] += C[0]*W[a]*(Cx*Iy*(Cz*zij + Pz)); I[68] += C[1]*W[a]*(Iy*Qx*(Cz*zij + Pz)); I[69] += C[1]*W[a]*(Cy*Qx*(zij*(2*Cz + zij) + Pz)); I[70] += C[0]*W[a]*(Cy*Ix*(Cz*zij + Pz)); I[71] += C[0]*W[a]*(Cx*Cy*(zij*(2*Cz + zij) + Pz)); I[72] += C[1]*W[a]*(f36*(zij*(2*Cz + zij) + Pz)); I[73] += C[1]*W[a]*(f7*(zij*(2*Cz + zij) + Pz)); I[74] += C[0]*W[a]*(f28*(Cz*zij + Pz)); I[75] += C[1]*W[a]*(Dx*f28*(Cz*zij + Pz)); I[76] += C[1]*W[a]*(Dx*Py*(zij*(2*Cz + zij) + Pz)); I[77] += C[0]*W[a]*(Py*(zij*(2*Cz + zij) + Pz)); I[78] += C[1]*W[a]*(Dy*Px*(zij*(2*Cz + zij) + Pz)); I[79] += C[0]*W[a]*(Px*(zij*(2*Cz + zij) + Pz)); I[80] += C[1]*W[a]*(f30*(Cz*zij + Pz)); I[81] += C[1]*W[a]*(Cz*Ix*f30); I[82] += C[0]*W[a]*(Cz*Ix*f28); I[83] += C[1]*W[a]*(Iz*Qx*f28); I[84] += C[0]*W[a]*(Cx*Iz*f28); I[85] += C[1]*W[a]*(Cx*f12*f28); I[86] += C[1]*W[a]*(Cy*f15); I[87] += C[1]*W[a]*(Cz*f15); I[88] += C[1]*W[a]*(Px*f6); I[89] += C[1]*W[a]*(Pz*f6); I[90] += C[1]*W[a]*(Cx*f37); I[91] += C[1]*W[a]*(Cz*f37); I[92] += C[1]*W[a]*(Qy*f27); I[93] += C[1]*W[a]*(Qy*f2); I[94] += C[1]*W[a]*(Qz*f2); I[95] += C[1]*W[a]*(f18*f7); I[96] += C[1]*W[a]*(Dx*Pz*f18); I[97] += C[0]*W[a]*(Pz*f18); I[98] += C[1]*W[a]*(Dz*Px*f18); I[99] += C[0]*W[a]*(Px*f18); I[100] += C[1]*W[a]*(f1*f18); I[101] += C[1]*W[a]*(Qx*f8); I[102] += C[1]*W[a]*(Qx*f27); I[103] += C[1]*W[a]*(Cx*Dy*f27); I[104] += C[0]*W[a]*(Cx*f27); I[105] += C[1]*W[a]*(Cy*Dx*f27); I[106] += C[0]*W[a]*(Cy*f27); I[107] += C[1]*W[a]*(Cy*Dz*f2); I[108] += C[0]*W[a]*(Cy*f2); I[109] += C[1]*W[a]*(Cz*Dy*f2); I[110] += C[0]*W[a]*(Cz*f2); I[111] += C[1]*W[a]*(Cz*Dx*f8); I[112] += C[0]*W[a]*(Cz*f8); I[113] += C[1]*W[a]*(Qz*f8); I[114] += C[0]*W[a]*(Cx*f8); I[115] += C[1]*W[a]*(Cx*f25); I[116] += C[1]*W[a]*(Cy*f25); I[117] += C[1]*W[a]*(f12*f29); I[118] += C[1]*W[a]*(Ix*f22); I[119] += C[1]*W[a]*(Iz*f22); I[120] += C[1]*W[a]*(Iz*f17); I[121] += C[1]*W[a]*(Iy*f17); I[122] += C[1]*W[a]*(Dx*Iy*f41); I[123] += C[0]*W[a]*(Iy*f41); I[124] += C[1]*W[a]*(Dy*Ix*f41); I[125] += C[0]*W[a]*(Ix*f41); I[126] += C[1]*W[a]*(Ix*f11); I[127] += C[0]*W[a]*(Ix*f35); I[128] += C[1]*W[a]*(f12*f35); I[129] += C[0]*W[a]*(Iz*f35); I[130] += C[1]*W[a]*(Dy*Iz*f29); I[131] += C[0]*W[a]*(Iz*f29); I[132] += C[1]*W[a]*(Dz*Iy*f29); I[133] += C[0]*W[a]*(Iy*f29); I[134] += C[1]*W[a]*(Iy*f11); I[135] += C[1]*W[a]*(Dz*f4); I[136] += C[1]*W[a]*(Dz*f5); I[137] += C[1]*W[a]*(Dx*f5); I[138] += C[1]*W[a]*(Dx*f3); I[139] += C[1]*W[a]*(Dy*f3); I[140] += C[1]*W[a]*(Dy*f4); I[141] += C[0]*W[a]*(f4); I[142] += C[0]*W[a]*(f5); I[143] += C[0]*W[a]*(f3); } #undef B00 #undef B10 #undef B01 #undef Cx #undef Cy #undef Cz #undef Dx #undef Dy #undef Dz #undef pow } static inline void reorder(double (&I)[144]) { double T[144]; for (int i = 0; i < 144; ++i) { T[i] = I[i]; } I[136] = T[0]; I[137] = T[1]; I[123] = T[2]; I[142] = T[3]; I[36] = T[4]; I[79] = T[5]; I[122] = T[6]; I[121] = T[7]; I[120] = T[8]; I[143] = T[9]; I[65] = T[10]; I[61] = T[11]; I[63] = T[12]; I[58] = T[13]; I[41] = T[14]; I[57] = T[15]; I[37] = T[16]; I[38] = T[17]; I[64] = T[18]; I[106] = T[19]; I[92] = T[20]; I[102] = T[21]; I[90] = T[22]; I[104] = T[23]; I[94] = T[24]; I[100] = T[25]; I[28] = T[26]; I[135] = T[27]; I[130] = T[28]; I[113] = T[29]; I[27] = T[30]; I[99] = T[31]; I[77] = T[32]; I[22] = T[33]; I[5] = T[34]; I[93] = T[35]; I[73] = T[36]; I[74] = T[37]; I[2] = T[38]; I[21] = T[39]; I[129] = T[40]; I[109] = T[41]; I[1] = T[42]; I[110] = T[43]; I[82] = T[44]; I[97] = T[45]; I[105] = T[46]; I[117] = T[47]; I[118] = T[48]; I[10] = T[49]; I[46] = T[50]; I[59] = T[51]; I[56] = T[52]; I[62] = T[53]; I[55] = T[54]; I[67] = T[55]; I[127] = T[56]; I[131] = T[57]; I[133] = T[58]; I[25] = T[59]; I[66] = T[60]; I[30] = T[61]; I[138] = T[62]; I[128] = T[63]; I[20] = T[64]; I[101] = T[65]; I[87] = T[66]; I[34] = T[67]; I[70] = T[68]; I[51] = T[69]; I[29] = T[70]; I[15] = T[71]; I[85] = T[72]; I[48] = T[73]; I[35] = T[74]; I[71] = T[75]; I[49] = T[76]; I[13] = T[77]; I[84] = T[78]; I[12] = T[79]; I[107] = T[80]; I[95] = T[81]; I[23] = T[82]; I[69] = T[83]; I[33] = T[84]; I[141] = T[85]; I[39] = T[86]; I[40] = T[87]; I[78] = T[88]; I[80] = T[89]; I[81] = T[90]; I[83] = T[91]; I[89] = T[92]; I[75] = T[93]; I[112] = T[94]; I[42] = T[95]; I[44] = T[96]; I[8] = T[97]; I[114] = T[98]; I[6] = T[99]; I[116] = T[100]; I[45] = T[101]; I[52] = T[102]; I[88] = T[103]; I[16] = T[104]; I[53] = T[105]; I[17] = T[106]; I[111] = T[107]; I[3] = T[108]; I[76] = T[109]; I[4] = T[110]; I[47] = T[111]; I[11] = T[112]; I[119] = T[113]; I[9] = T[114]; I[124] = T[115]; I[125] = T[116]; I[132] = T[117]; I[91] = T[118]; I[103] = T[119]; I[60] = T[120]; I[54] = T[121]; I[68] = T[122]; I[32] = T[123]; I[98] = T[124]; I[26] = T[125]; I[134] = T[126]; I[19] = T[127]; I[139] = T[128]; I[31] = T[129]; I[96] = T[130]; I[24] = T[131]; I[126] = T[132]; I[18] = T[133]; I[140] = T[134]; I[108] = T[135]; I[115] = T[136]; I[43] = T[137]; I[50] = T[138]; I[86] = T[139]; I[72] = T[140]; I[0] = T[141]; I[7] = T[142]; I[14] = T[143]; } }; template<> struct impl > { typedef void enable; static const bool value = true; static inline void eval(double A, double B, const Vector<3> &rAi, const Vector<3> &rBk, const Vector<3> &rAB, const Vector<3> &rij, const Vector<3> &rkl, const Vector<3> &t2, const Vector<3> &W, const double (&C)[1], double (&I)[54]) { #define pow(x,y) util::pow<(y)>::eval((x)) const int N = 3; double xkl = rkl[0]; double ykl = rkl[1]; double zkl = rkl[2]; // // double vB00[N] __attribute__ ((aligned(16))); // // // double vB10[N] __attribute__ ((aligned(16))); // // // double vB01[N] __attribute__ ((aligned(16))); // // // double vCx[N] __attribute__ ((aligned(16))); // double vCy[N] __attribute__ ((aligned(16))); // double vCz[N] __attribute__ ((aligned(16))); // // // double vDx[N] __attribute__ ((aligned(16))); // double vDy[N] __attribute__ ((aligned(16))); // double vDz[N] __attribute__ ((aligned(16))); // // for (int a = 0; a < N; ++a) { // // vB00[a] = 0.5*t2[a]; // // // vB10[a] = recurrence::coefficient(1.0/A, B, t2[a]); // // // vB01[a] = recurrence::coefficient(1.0/B, A, t2[a]); // // // vCx[a] = recurrence::coefficient<0>(rAi, B, rAB, t2[a]); // vCy[a] = recurrence::coefficient<1>(rAi, B, rAB, t2[a]); // vCz[a] = recurrence::coefficient<2>(rAi, B, rAB, t2[a]); // // // vDx[a] = recurrence::coefficient<0>(rBk, -A, rAB, t2[a]); // vDy[a] = recurrence::coefficient<1>(rBk, -A, rAB, t2[a]); // vDz[a] = recurrence::coefficient<2>(rBk, -A, rAB, t2[a]); // // } // #define B00 vB00[a] // #define B10 vB10[a] // #define B01 vB01[a] // #define Cx vCx[a] // #define Cy vCy[a] // #define Cz vCz[a] // #define Dx vDx[a] // #define Dy vDy[a] // #define Dz vDz[a] #if defined (__INTEL_COMPILER) #pragma ivdep #pragma vector aligned #endif for (int a = 0; a < N; ++a) { double B00 = 0.5*t2[a]; double B10 = recurrence::coefficient(1.0/A, B, t2[a]); double B01 = recurrence::coefficient(1.0/B, A, t2[a]); double Cx = recurrence::coefficient<0>(rAi, B, rAB, t2[a]); double Cy = recurrence::coefficient<1>(rAi, B, rAB, t2[a]); double Cz = recurrence::coefficient<2>(rAi, B, rAB, t2[a]); double Dx = recurrence::coefficient<0>(rBk, -A, rAB, t2[a]); double Dy = recurrence::coefficient<1>(rBk, -A, rAB, t2[a]); double Dz = recurrence::coefficient<2>(rBk, -A, rAB, t2[a]); double Kx = (xkl + Dx); double Ky = (ykl + Dy); double Kz = (Dz + zkl); double Px = (B10 + pow(Cx,2)); double Py = (B10 + pow(Cy,2)); double Pz = (B10 + pow(Cz,2)); double Qx = (Cx*Dx + B00); double Qy = (Cy*Dy + B00); double Qz = (Cz*Dz + B00); double f0 = (Dy*Py + 2*B00*Cy); double f1 = (Dz*Pz + 2*B00*Cz); double f10 = B01*B10; double f13 = (Dx*Px + 2*B00*Cx); double f15 = (Dz*Kz + B01); double f16 = (B00 + Cx*Kx); double f17 = (B00 + Cy*Ky); double f2 = (Cy*Dy*Ky + B01*Cy + B00*(ykl + 2*Dy)); double f20 = 2*pow(B00,2); double f22 = (B01 + Dy*Ky); double f4 = (B01*Cx + Cx*Dx*Kx + B00*(xkl + 2*Dx)); double f6 = (B01*Cz + B00*(2*Dz + zkl) + Cz*Dz*Kz); double f7 = (B01 + Dx*Kx); double f9 = (Kx*Px + 2*B00*Cx); I[0] += C[0]*W[a]*((B01*pow(Cx,2) + f10 + f20 + 2*B00*Cx*(xkl + 2*Dx) + Dx*Kx*Px)); I[1] += C[0]*W[a]*((f10 + f20 + Dy*Ky*Py + B01*pow(Cy,2) + 2*B00*Cy*(ykl + 2*Dy))); I[2] += C[0]*W[a]*((f10 + f20 + B01*pow(Cz,2) + Dz*Kz*Pz + 2*B00*Cz*(2*Dz + zkl))); I[3] += C[0]*W[a]*(Cy*Dx*(Cz*zkl + Qz)); I[4] += C[0]*W[a]*(Cx*Dy*(Cz*zkl + Qz)); I[5] += C[0]*W[a]*(Dy*(Pz*zkl + f1)); I[6] += C[0]*W[a]*(Dx*(Pz*zkl + f1)); I[7] += C[0]*W[a]*(Dz*(f0 + Py*ykl)); I[8] += C[0]*W[a]*(Dx*(f0 + Py*ykl)); I[9] += C[0]*W[a]*(Dx*Ky*Pz); I[10] += C[0]*W[a]*(Cz*Dx*f17); I[11] += C[0]*W[a]*(Cx*Cz*f22); I[12] += C[0]*W[a]*(Cy*Kx*Qz); I[13] += C[0]*W[a]*(Cy*Dz*f16); I[14] += C[0]*W[a]*(Dz*Ky*Px); I[15] += C[0]*W[a]*(Cx*Dz*f17); I[16] += C[0]*W[a]*(Cx*Ky*Qz); I[17] += C[0]*W[a]*(Cz*Ky*Qx); I[18] += C[0]*W[a]*(Qx*(Cz*zkl + Qz)); I[19] += C[0]*W[a]*(Qy*(Cz*zkl + Qz)); I[20] += C[0]*W[a]*(Cz*Kx*Qy); I[21] += C[0]*W[a]*(Dz*Kx*Py); I[22] += C[0]*W[a]*(Dx*Kz*Py); I[23] += C[0]*W[a]*(Cy*Kz*Qx); I[24] += C[0]*W[a]*(Dy*Kz*Px); I[25] += C[0]*W[a]*(Cx*Kz*Qy); I[26] += C[0]*W[a]*(Cx*Cy*f15); I[27] += C[0]*W[a]*(Cy*Cz*f7); I[28] += C[0]*W[a]*(Cz*Dy*f16); I[29] += C[0]*W[a]*(Dy*Kx*Pz); I[30] += C[0]*W[a]*(Dy*f9); I[31] += C[0]*W[a]*(Dz*f9); I[32] += C[0]*W[a]*(Qy*f16); I[33] += C[0]*W[a]*(Qz*f16); I[34] += C[0]*W[a]*(Qx*f17); I[35] += C[0]*W[a]*(Qz*f17); I[36] += C[0]*W[a]*(Kx*f0); I[37] += C[0]*W[a]*(Kx*f1); I[38] += C[0]*W[a]*(Ky*f1); I[39] += C[0]*W[a]*(Ky*f13); I[40] += C[0]*W[a]*(Kz*f13); I[41] += C[0]*W[a]*(Kz*f0); I[42] += C[0]*W[a]*(Py*f7); I[43] += C[0]*W[a]*(Pz*f7); I[44] += C[0]*W[a]*(Pz*f22); I[45] += C[0]*W[a]*(Px*f22); I[46] += C[0]*W[a]*(Px*f15); I[47] += C[0]*W[a]*(Py*f15); I[48] += C[0]*W[a]*(Cy*f4); I[49] += C[0]*W[a]*(Cz*f4); I[50] += C[0]*W[a]*(Cz*f2); I[51] += C[0]*W[a]*(Cx*f2); I[52] += C[0]*W[a]*(Cx*f6); I[53] += C[0]*W[a]*(Cy*f6); } #undef B00 #undef B10 #undef B01 #undef Cx #undef Cy #undef Cz #undef Dx #undef Dy #undef Dz #undef pow } static inline void reorder(double (&I)[54]) { double T[54]; for (int i = 0; i < 54; ++i) { T[i] = I[i]; } I[0] = T[0]; I[25] = T[1]; I[50] = T[2]; I[41] = T[3]; I[46] = T[4]; I[44] = T[5]; I[38] = T[6]; I[31] = T[7]; I[19] = T[8]; I[20] = T[9]; I[23] = T[10]; I[28] = T[11]; I[17] = T[12]; I[15] = T[13]; I[30] = T[14]; I[33] = T[15]; I[34] = T[16]; I[22] = T[17]; I[40] = T[18]; I[47] = T[19]; I[11] = T[20]; I[13] = T[21]; I[37] = T[22]; I[39] = T[23]; I[42] = T[24]; I[45] = T[25]; I[51] = T[26]; I[5] = T[27]; I[10] = T[28]; I[8] = T[29]; I[6] = T[30]; I[12] = T[31]; I[9] = T[32]; I[16] = T[33]; I[21] = T[34]; I[35] = T[35]; I[7] = T[36]; I[14] = T[37]; I[32] = T[38]; I[18] = T[39]; I[36] = T[40]; I[43] = T[41]; I[1] = T[42]; I[2] = T[43]; I[26] = T[44]; I[24] = T[45]; I[48] = T[46]; I[49] = T[47]; I[3] = T[48]; I[4] = T[49]; I[29] = T[50]; I[27] = T[51]; I[52] = T[52]; I[53] = T[53]; } }; template<> struct impl > { typedef void enable; static const bool value = true; static inline void eval(double A, double B, const Vector<3> &rAi, const Vector<3> &rBk, const Vector<3> &rAB, const Vector<3> &rij, const Vector<3> &rkl, const Vector<3> &t2, const Vector<3> &W, const double (&C)[4], double (&I)[144]) { #define pow(x,y) util::pow<(y)>::eval((x)) const int N = 3; double xij = rij[0]; double yij = rij[1]; double zij = rij[2]; double xkl = rkl[0]; double ykl = rkl[1]; double zkl = rkl[2]; // // double vB00[N] __attribute__ ((aligned(16))); // // // double vB10[N] __attribute__ ((aligned(16))); // // // double vB01[N] __attribute__ ((aligned(16))); // // // double vCx[N] __attribute__ ((aligned(16))); // double vCy[N] __attribute__ ((aligned(16))); // double vCz[N] __attribute__ ((aligned(16))); // // // double vDx[N] __attribute__ ((aligned(16))); // double vDy[N] __attribute__ ((aligned(16))); // double vDz[N] __attribute__ ((aligned(16))); // // for (int a = 0; a < N; ++a) { // // vB00[a] = 0.5*t2[a]; // // // vB10[a] = recurrence::coefficient(1.0/A, B, t2[a]); // // // vB01[a] = recurrence::coefficient(1.0/B, A, t2[a]); // // // vCx[a] = recurrence::coefficient<0>(rAi, B, rAB, t2[a]); // vCy[a] = recurrence::coefficient<1>(rAi, B, rAB, t2[a]); // vCz[a] = recurrence::coefficient<2>(rAi, B, rAB, t2[a]); // // // vDx[a] = recurrence::coefficient<0>(rBk, -A, rAB, t2[a]); // vDy[a] = recurrence::coefficient<1>(rBk, -A, rAB, t2[a]); // vDz[a] = recurrence::coefficient<2>(rBk, -A, rAB, t2[a]); // // } // #define B00 vB00[a] // #define B10 vB10[a] // #define B01 vB01[a] // #define Cx vCx[a] // #define Cy vCy[a] // #define Cz vCz[a] // #define Dx vDx[a] // #define Dy vDy[a] // #define Dz vDz[a] #if defined (__INTEL_COMPILER) #pragma ivdep #pragma vector aligned #endif for (int a = 0; a < N; ++a) { double B00 = 0.5*t2[a]; double B10 = recurrence::coefficient(1.0/A, B, t2[a]); double B01 = recurrence::coefficient(1.0/B, A, t2[a]); double Cx = recurrence::coefficient<0>(rAi, B, rAB, t2[a]); double Cy = recurrence::coefficient<1>(rAi, B, rAB, t2[a]); double Cz = recurrence::coefficient<2>(rAi, B, rAB, t2[a]); double Dx = recurrence::coefficient<0>(rBk, -A, rAB, t2[a]); double Dy = recurrence::coefficient<1>(rBk, -A, rAB, t2[a]); double Dz = recurrence::coefficient<2>(rBk, -A, rAB, t2[a]); double Ix = (Cx + xij); double Iy = (Cy + yij); double Iz = (Cz + zij); double Kx = (xkl + Dx); double Ky = (ykl + Dy); double Kz = (Dz + zkl); double Qx = (Cx*Dx + B00); double Qy = (Cy*Dy + B00); double Qz = (Cz*Dz + B00); double f1 = B00*zkl; double f10 = B00*xkl; double f13 = Cz*pow(Dz,2); double f14 = (B00 + Dz*Iz); double f18 = (B00 + Iy*Ky); double f19 = (B00 + Cy*Ky); double f2 = B01*B10; double f20 = (Dy*Iy + B00); double f21 = Cz*Dz*zkl; double f22 = (Dz*(B10 + Cz*Iz) + B00*(2*Cz + zij)); double f23 = B01*Cy; double f24 = (Cx*Ix + B10); double f27 = (Kx*(Cx*Ix + B10) + B00*(xij + 2*Cx)); double f28 = 2*B00*Dy; double f3 = (Dz*Kz + B01); double f30 = (Dx*(Cx*Ix + B10) + B00*(xij + 2*Cx)); double f31 = (B01 + Dx*Kx); double f32 = (Cy*Iy + B10); double f33 = (B00*(yij + 2*Cy) + Ky*(Cy*Iy + B10)); double f34 = (B00*(yij + 2*Cy) + Dy*(Cy*Iy + B10)); double f36 = 2*B00*Dz; double f37 = (B01 + Dy*Ky); double f39 = B01*Cx; double f4 = (B00 + Cx*Kx); double f42 = Cx*pow(Dx,2); double f45 = Cy*pow(Dy,2); double f46 = 2*pow(B00,2); double f5 = (B00*(ykl + 2*Dy) + Iy*(B01 + Dy*Ky)); double f51 = B01*Cz; double f52 = (B10 + Cz*Iz); double f6 = B00*ykl; double f7 = Cy*Dy*ykl; double f8 = Cx*Dx*xkl; double f9 = 2*B00*Dx; I[0] += C[3]*W[a]*((f46 + f23*yij + 2*Cy*(f28 + f6) + B01*pow(Cy,2) + Dy*Ky*pow(Cy,2) + f2 + B10*pow(Dy,2) + B10*Dy*ykl + yij*(f45 + f28 + f7 + f6))); I[1] += C[3]*W[a]*((f46 + 2*Cx*(f10 + f9) + B10*Dx*xkl + f39*(Cx + xij) + B10*pow(Dx,2) + f2 + xij*(f10 + f42 + f9 + f8) + Dx*Kx*pow(Cx,2))); I[2] += C[3]*W[a]*(Cy*(f10 + f42 + f9 + f8 + B01*Ix + Dx*Kx*xij)); I[3] += C[3]*W[a]*(Cz*(f10 + f42 + f9 + f8 + B01*Ix + Dx*Kx*xij)); I[4] += C[2]*W[a]*((f10 + f42 + f9 + f8 + B01*Ix + Dx*Kx*xij)); I[5] += C[3]*W[a]*(Iy*(f10 + f42 + f39 + f9 + f8)); I[6] += C[3]*W[a]*(Iz*(f10 + f42 + f39 + f9 + f8)); I[7] += C[1]*W[a]*((f10 + f42 + f39 + f9 + f8)); I[8] += C[3]*W[a]*((Dz*Kz*pow(Cz,2) + f46 + zij*(f13 + f21 + f36 + f1) + B10*Dz*zkl + B10*pow(Dz,2) + 2*Cz*(f36 + f1) + f2 + f51*(Cz + zij))); I[9] += C[3]*W[a]*(Cy*(f13 + f21 + f36 + Dz*Kz*zij + f1 + B01*Iz)); I[10] += C[3]*W[a]*(Cx*(f13 + f21 + f36 + Dz*Kz*zij + f1 + B01*Iz)); I[11] += C[2]*W[a]*((f13 + f21 + f36 + Dz*Kz*zij + f1 + B01*Iz)); I[12] += C[3]*W[a]*(Iy*(f13 + f51 + f21 + f36 + f1)); I[13] += C[3]*W[a]*(Ix*(f13 + f51 + f21 + f36 + f1)); I[14] += C[1]*W[a]*((f13 + f51 + f21 + f36 + f1)); I[15] += C[3]*W[a]*(Iz*(f45 + f28 + f23 + f7 + f6)); I[16] += C[3]*W[a]*(Ix*(f45 + f28 + f23 + f7 + f6)); I[17] += C[1]*W[a]*((f45 + f28 + f23 + f7 + f6)); I[18] += C[3]*W[a]*(Dx*(f22 + zkl*(B10 + Cz*Iz))); I[19] += C[3]*W[a]*(Dy*(f22 + zkl*(B10 + Cz*Iz))); I[20] += C[3]*W[a]*(Dy*Ix*(Cz*zkl + Qz)); I[21] += C[3]*W[a]*(Qx*(f14 + Iz*zkl)); I[22] += C[3]*W[a]*(Cx*Dy*(f14 + Iz*zkl)); I[23] += C[2]*W[a]*(Dy*(f14 + Iz*zkl)); I[24] += C[3]*W[a]*(Qy*(f14 + Iz*zkl)); I[25] += C[2]*W[a]*(Dx*(f14 + Iz*zkl)); I[26] += C[3]*W[a]*(Cy*Dx*(f14 + Iz*zkl)); I[27] += C[3]*W[a]*(Cy*Dz*(Kx*xij + f4)); I[28] += C[2]*W[a]*(Dz*(Kx*xij + f4)); I[29] += C[3]*W[a]*(Qy*(Kx*xij + f4)); I[30] += C[3]*W[a]*(Cz*Dy*(Kx*xij + f4)); I[31] += C[2]*W[a]*(Dy*(Kx*xij + f4)); I[32] += C[3]*W[a]*(Qz*(Kx*xij + f4)); I[33] += C[3]*W[a]*((Cz*zkl + Qz)*(Dx*xij + Qx)); I[34] += C[3]*W[a]*(Dx*Iy*(Cz*zkl + Qz)); I[35] += C[1]*W[a]*(Dx*(Cz*zkl + Qz)); I[36] += C[1]*W[a]*(Dy*(Cz*zkl + Qz)); I[37] += C[3]*W[a]*(f20*(Cz*zkl + Qz)); I[38] += C[3]*W[a]*(Cx*Kz*f20); I[39] += C[3]*W[a]*(Cy*Ix*f3); I[40] += C[3]*W[a]*(Ix*Kz*Qy); I[41] += C[3]*W[a]*(Dy*Kz*f24); I[42] += C[2]*W[a]*(Dy*Ix*Kz); I[43] += C[1]*W[a]*(Cx*Dy*Kz); I[44] += C[3]*W[a]*(Dy*Kx*f52); I[45] += C[3]*W[a]*(Dz*Kx*f32); I[46] += C[3]*W[a]*(Dx*Kz*f32); I[47] += C[3]*W[a]*(Cy*Kz*(Dx*xij + Qx)); I[48] += C[2]*W[a]*(Kz*(Dx*xij + Qx)); I[49] += C[3]*W[a]*(f19*(Dx*xij + Qx)); I[50] += C[3]*W[a]*(Cz*Ky*(Dx*xij + Qx)); I[51] += C[2]*W[a]*(Ky*(Dx*xij + Qx)); I[52] += C[3]*W[a]*(Dx*Ky*f52); I[53] += C[3]*W[a]*(Dx*f33); I[54] += C[3]*W[a]*(Cx*f5); I[55] += C[3]*W[a]*(Cz*f5); I[56] += C[3]*W[a]*(Iz*Ky*Qx); I[57] += C[2]*W[a]*(Dx*Iz*Ky); I[58] += C[3]*W[a]*(Dx*Iz*f19); I[59] += C[1]*W[a]*(Dx*f19); I[60] += C[3]*W[a]*(Dz*Ix*f19); I[61] += C[1]*W[a]*(Dz*f19); I[62] += C[3]*W[a]*(Ky*f30); I[63] += C[3]*W[a]*(Ix*Ky*Qz); I[64] += C[1]*W[a]*(Ky*Qz); I[65] += C[3]*W[a]*(Qx*f18); I[66] += C[3]*W[a]*(Cx*Dz*f18); I[67] += C[2]*W[a]*(Dz*f18); I[68] += C[3]*W[a]*(Dz*f33); I[69] += C[3]*W[a]*(Cy*Kx*f14); I[70] += C[2]*W[a]*(Kx*f14); I[71] += C[3]*W[a]*(Kx*f34); I[72] += C[3]*W[a]*(Iy*Kx*Qz); I[73] += C[1]*W[a]*(Kx*Qz); I[74] += C[3]*W[a]*(Qz*f18); I[75] += C[2]*W[a]*(Dx*f18); I[76] += C[3]*W[a]*(Cz*Dx*f18); I[77] += C[1]*W[a]*(Cz*Dx*Ky); I[78] += C[0]*W[a]*(Dx*Ky); I[79] += C[3]*W[a]*(Dz*Ky*f24); I[80] += C[2]*W[a]*(Dz*Ix*Ky); I[81] += C[0]*W[a]*(Dz*Ky); I[82] += C[1]*W[a]*(Cx*Dz*Ky); I[83] += C[3]*W[a]*(Cx*Ky*f14); I[84] += C[2]*W[a]*(Ky*f14); I[85] += C[3]*W[a]*(f14*f19); I[86] += C[3]*W[a]*(f14*f4); I[87] += C[3]*W[a]*(f20*f4); I[88] += C[1]*W[a]*(Dz*f4); I[89] += C[3]*W[a]*(Dz*Iy*f4); I[90] += C[2]*W[a]*(Dz*Iy*Kx); I[91] += C[1]*W[a]*(Cy*Dz*Kx); I[92] += C[0]*W[a]*(Dz*Kx); I[93] += C[3]*W[a]*(Dz*f27); I[94] += C[3]*W[a]*(Dy*f27); I[95] += C[1]*W[a]*(Dy*f4); I[96] += C[3]*W[a]*(Dy*Iz*f4); I[97] += C[2]*W[a]*(Dy*Iz*Kx); I[98] += C[3]*W[a]*(Iz*Kx*Qy); I[99] += C[1]*W[a]*(Kx*Qy); I[100] += C[2]*W[a]*(Kx*f20); I[101] += C[3]*W[a]*(Cz*Kx*f20); I[102] += C[1]*W[a]*(Cz*Dy*Kx); I[103] += C[0]*W[a]*(Dy*Kx); I[104] += C[3]*W[a]*(Kx*f22); I[105] += C[3]*W[a]*(Ky*f22); I[106] += C[1]*W[a]*(Ky*Qx); I[107] += C[3]*W[a]*(Iy*Kz*Qx); I[108] += C[2]*W[a]*(Dx*Iy*Kz); I[109] += C[1]*W[a]*(Cy*Dx*Kz); I[110] += C[0]*W[a]*(Dx*Kz); I[111] += C[1]*W[a]*(Kz*Qx); I[112] += C[3]*W[a]*(Kz*f30); I[113] += C[0]*W[a]*(Dy*Kz); I[114] += C[1]*W[a]*(Kz*Qy); I[115] += C[2]*W[a]*(Kz*f20); I[116] += C[3]*W[a]*(Kz*f34); I[117] += C[3]*W[a]*(f31*f52); I[118] += C[3]*W[a]*(f37*f52); I[119] += C[3]*W[a]*(f24*f37); I[120] += C[2]*W[a]*(Ix*f37); I[121] += C[3]*W[a]*(Cz*Ix*f37); I[122] += C[1]*W[a]*(Cz*f37); I[123] += C[2]*W[a]*(Iz*f37); I[124] += C[3]*W[a]*(Cx*Iz*f37); I[125] += C[1]*W[a]*(Cx*f37); I[126] += C[3]*W[a]*(Cx*Iy*f3); I[127] += C[1]*W[a]*(Cx*f3); I[128] += C[1]*W[a]*(Cy*f3); I[129] += C[2]*W[a]*(Ix*f3); I[130] += C[3]*W[a]*(f24*f3); I[131] += C[2]*W[a]*(Iy*f3); I[132] += C[3]*W[a]*(f3*f32); I[133] += C[3]*W[a]*(f31*f32); I[134] += C[2]*W[a]*(Iy*f31); I[135] += C[3]*W[a]*(Cz*Iy*f31); I[136] += C[1]*W[a]*(Cz*f31); I[137] += C[2]*W[a]*(Iz*f31); I[138] += C[3]*W[a]*(Cy*Iz*f31); I[139] += C[1]*W[a]*(Cy*f31); I[140] += C[0]*W[a]*(f31); I[141] += C[0]*W[a]*(f37); I[142] += C[2]*W[a]*(f5); I[143] += C[0]*W[a]*(f3); } #undef B00 #undef B10 #undef B01 #undef Cx #undef Cy #undef Cz #undef Dx #undef Dy #undef Dz #undef pow } static inline void reorder(double (&I)[144]) { double T[144]; for (int i = 0; i < 144; ++i) { T[i] = I[i]; } I[74] = T[0]; I[5] = T[1]; I[6] = T[2]; I[7] = T[3]; I[4] = T[4]; I[9] = T[5]; I[13] = T[6]; I[1] = T[7]; I[143] = T[8]; I[142] = T[9]; I[141] = T[10]; I[140] = T[11]; I[139] = T[12]; I[135] = T[13]; I[131] = T[14]; I[78] = T[15]; I[70] = T[16]; I[66] = T[17]; I[111] = T[18]; I[127] = T[19]; I[119] = T[20]; I[109] = T[21]; I[125] = T[22]; I[124] = T[23]; I[126] = T[24]; I[108] = T[25]; I[110] = T[26]; I[38] = T[27]; I[36] = T[28]; I[22] = T[29]; I[23] = T[30]; I[20] = T[31]; I[39] = T[32]; I[103] = T[33]; I[107] = T[34]; I[99] = T[35]; I[115] = T[36]; I[123] = T[37]; I[121] = T[38]; I[134] = T[39]; I[118] = T[40]; I[117] = T[41]; I[116] = T[42]; I[113] = T[43]; I[31] = T[44]; I[42] = T[45]; I[106] = T[46]; I[102] = T[47]; I[100] = T[48]; I[54] = T[49]; I[55] = T[50]; I[52] = T[51]; I[63] = T[52]; I[58] = T[53]; I[73] = T[54]; I[75] = T[55]; I[61] = T[56]; I[60] = T[57]; I[62] = T[58]; I[50] = T[59]; I[86] = T[60]; I[82] = T[61]; I[53] = T[62]; I[87] = T[63]; I[83] = T[64]; I[57] = T[65]; I[89] = T[66]; I[88] = T[67]; I[90] = T[68]; I[46] = T[69]; I[44] = T[70]; I[26] = T[71]; I[43] = T[72]; I[35] = T[73]; I[91] = T[74]; I[56] = T[75]; I[59] = T[76]; I[51] = T[77]; I[48] = T[78]; I[85] = T[79]; I[84] = T[80]; I[80] = T[81]; I[81] = T[82]; I[93] = T[83]; I[92] = T[84]; I[94] = T[85]; I[45] = T[86]; I[25] = T[87]; I[33] = T[88]; I[41] = T[89]; I[40] = T[90]; I[34] = T[91]; I[32] = T[92]; I[37] = T[93]; I[21] = T[94]; I[17] = T[95]; I[29] = T[96]; I[28] = T[97]; I[30] = T[98]; I[18] = T[99]; I[24] = T[100]; I[27] = T[101]; I[19] = T[102]; I[16] = T[103]; I[47] = T[104]; I[95] = T[105]; I[49] = T[106]; I[105] = T[107]; I[104] = T[108]; I[98] = T[109]; I[96] = T[110]; I[97] = T[111]; I[101] = T[112]; I[112] = T[113]; I[114] = T[114]; I[120] = T[115]; I[122] = T[116]; I[15] = T[117]; I[79] = T[118]; I[69] = T[119]; I[68] = T[120]; I[71] = T[121]; I[67] = T[122]; I[76] = T[123]; I[77] = T[124]; I[65] = T[125]; I[137] = T[126]; I[129] = T[127]; I[130] = T[128]; I[132] = T[129]; I[133] = T[130]; I[136] = T[131]; I[138] = T[132]; I[10] = T[133]; I[8] = T[134]; I[11] = T[135]; I[3] = T[136]; I[12] = T[137]; I[14] = T[138]; I[2] = T[139]; I[0] = T[140]; I[64] = T[141]; I[72] = T[142]; I[128] = T[143]; } }; template<> struct impl > { typedef void enable; static const bool value = true; static inline void eval(double A, double B, const Vector<3> &rAi, const Vector<3> &rBk, const Vector<3> &rAB, const Vector<3> &rij, const Vector<3> &rkl, const Vector<3> &t2, const Vector<3> &W, const double (&C)[4], double (&I)[144]) { #define pow(x,y) util::pow<(y)>::eval((x)) const int N = 3; double xij = rij[0]; double yij = rij[1]; double zij = rij[2]; double xkl = rkl[0]; double ykl = rkl[1]; double zkl = rkl[2]; // // double vB00[N] __attribute__ ((aligned(16))); // // // double vB10[N] __attribute__ ((aligned(16))); // // // double vB01[N] __attribute__ ((aligned(16))); // // // double vCx[N] __attribute__ ((aligned(16))); // double vCy[N] __attribute__ ((aligned(16))); // double vCz[N] __attribute__ ((aligned(16))); // // // double vDx[N] __attribute__ ((aligned(16))); // double vDy[N] __attribute__ ((aligned(16))); // double vDz[N] __attribute__ ((aligned(16))); // // for (int a = 0; a < N; ++a) { // // vB00[a] = 0.5*t2[a]; // // // vB10[a] = recurrence::coefficient(1.0/A, B, t2[a]); // // // vB01[a] = recurrence::coefficient(1.0/B, A, t2[a]); // // // vCx[a] = recurrence::coefficient<0>(rAi, B, rAB, t2[a]); // vCy[a] = recurrence::coefficient<1>(rAi, B, rAB, t2[a]); // vCz[a] = recurrence::coefficient<2>(rAi, B, rAB, t2[a]); // // // vDx[a] = recurrence::coefficient<0>(rBk, -A, rAB, t2[a]); // vDy[a] = recurrence::coefficient<1>(rBk, -A, rAB, t2[a]); // vDz[a] = recurrence::coefficient<2>(rBk, -A, rAB, t2[a]); // // } // #define B00 vB00[a] // #define B10 vB10[a] // #define B01 vB01[a] // #define Cx vCx[a] // #define Cy vCy[a] // #define Cz vCz[a] // #define Dx vDx[a] // #define Dy vDy[a] // #define Dz vDz[a] #if defined (__INTEL_COMPILER) #pragma ivdep #pragma vector aligned #endif for (int a = 0; a < N; ++a) { double B00 = 0.5*t2[a]; double B10 = recurrence::coefficient(1.0/A, B, t2[a]); double B01 = recurrence::coefficient(1.0/B, A, t2[a]); double Cx = recurrence::coefficient<0>(rAi, B, rAB, t2[a]); double Cy = recurrence::coefficient<1>(rAi, B, rAB, t2[a]); double Cz = recurrence::coefficient<2>(rAi, B, rAB, t2[a]); double Dx = recurrence::coefficient<0>(rBk, -A, rAB, t2[a]); double Dy = recurrence::coefficient<1>(rBk, -A, rAB, t2[a]); double Dz = recurrence::coefficient<2>(rBk, -A, rAB, t2[a]); double Ix = (Cx + xij); double Iy = (Cy + yij); double Iz = (Cz + zij); double Kx = (xkl + Dx); double Ky = (ykl + Dy); double Kz = (Dz + zkl); double Qx = (Cx*Dx + B00); double Qy = (Cy*Dy + B00); double Qz = (Cz*Dz + B00); double f1 = B01*B10; double f14 = (Cx*Ix + B10); double f2 = (B00 + Cx*Kx); double f21 = (B01 + Dx*Kx); double f22 = (Cy*Iy + B10); double f26 = (B01 + Dy*Ky); double f3 = (B00*(ykl + 2*Dy) + Iy*(B01 + Dy*Ky)); double f30 = (Dz*Kz + B01); double f32 = 2*pow(B00,2); double f37 = (B10 + Cz*Iz); I[0] += C[3]*W[a]*((f32 + Dy*Ky*(Cy*Iy + B10) + B01*Cy*Iy + B00*(yij + 2*Cy)*(ykl + 2*Dy) + f1)); I[1] += C[3]*W[a]*((B00 + Cz*Kz)*(Dx*Ix + B00)); I[2] += C[3]*W[a]*((B00 + Cy*Ky)*(Dx*Ix + B00)); I[3] += C[3]*W[a]*(Cz*Dx*(B00 + Iy*Ky)); I[4] += C[3]*W[a]*((B00 + Cz*Kz)*(Dy*Iy + B00)); I[5] += C[3]*W[a]*((Dz*Kz*(B10 + Cz*Iz) + f32 + B00*(2*Cz + zij)*(2*Dz + zkl) + f1 + B01*Cz*Iz)); I[6] += C[3]*W[a]*(Cx*(B00*(2*Dz + zkl) + Iz*(Dz*Kz + B01))); I[7] += C[3]*W[a]*(Cy*(B00*(2*Dz + zkl) + Iz*(Dz*Kz + B01))); I[8] += C[2]*W[a]*((B00*(2*Dz + zkl) + Iz*(Dz*Kz + B01))); I[9] += C[3]*W[a]*(Dx*Iy*(B00 + Cz*Kz)); I[10] += C[3]*W[a]*(Iy*Kx*Qz); I[11] += C[3]*W[a]*(Iy*(B01*Cz + B00*(2*Dz + zkl) + Cz*Dz*Kz)); I[12] += C[3]*W[a]*(Ix*(B01*Cz + B00*(2*Dz + zkl) + Cz*Dz*Kz)); I[13] += C[3]*W[a]*(Dy*Ix*(B00 + Cz*Kz)); I[14] += C[1]*W[a]*(Ix*(B00 + Cz*Kz)); I[15] += C[1]*W[a]*(Iy*(B00 + Cz*Kz)); I[16] += C[3]*W[a]*(f2*(B00 + Dz*Iz)); I[17] += C[3]*W[a]*(Qz*(Kx*xij + f2)); I[18] += C[3]*W[a]*(Dz*(Kx*(Cx*Ix + B10) + B00*(xij + 2*Cx))); I[19] += C[3]*W[a]*(Dy*(Kx*(Cx*Ix + B10) + B00*(xij + 2*Cx))); I[20] += C[3]*W[a]*((B00*(xij + 2*Cx)*(xkl + 2*Dx) + f32 + B01*Cx*Ix + f1 + Dx*Kx*(Cx*Ix + B10))); I[21] += C[3]*W[a]*(Iz*(B01*Cx + Cx*Dx*Kx + B00*(xkl + 2*Dx))); I[22] += C[3]*W[a]*(Iz*Ky*Qx); I[23] += C[3]*W[a]*(Cz*Ky*(Dx*Ix + B00)); I[24] += C[3]*W[a]*(Ky*(Dx*(Cx*Ix + B10) + B00*(xij + 2*Cx))); I[25] += C[2]*W[a]*(Ky*(Dx*Ix + B00)); I[26] += C[3]*W[a]*(Iy*Kz*Qx); I[27] += C[3]*W[a]*(Iy*(B01*Cx + Cx*Dx*Kx + B00*(xkl + 2*Dx))); I[28] += C[3]*W[a]*(Cz*(Ix*(B01 + Dx*Kx) + B00*(xkl + 2*Dx))); I[29] += C[2]*W[a]*((Ix*(B01 + Dx*Kx) + B00*(xkl + 2*Dx))); I[30] += C[3]*W[a]*(Cy*(Ix*(B01 + Dx*Kx) + B00*(xkl + 2*Dx))); I[31] += C[3]*W[a]*(Qy*(Kx*xij + f2)); I[32] += C[2]*W[a]*(Dy*(Kx*xij + f2)); I[33] += C[3]*W[a]*(Cz*Dy*(Kx*xij + f2)); I[34] += C[1]*W[a]*(Cz*(Kx*xij + f2)); I[35] += C[2]*W[a]*(Dz*(Kx*xij + f2)); I[36] += C[3]*W[a]*(Cy*Dz*(Kx*xij + f2)); I[37] += C[1]*W[a]*(Cy*(Kx*xij + f2)); I[38] += C[0]*W[a]*((Kx*xij + f2)); I[39] += C[1]*W[a]*((Kx*(Cx*Ix + B10) + B00*(xij + 2*Cx))); I[40] += C[3]*W[a]*(Kz*(Dx*(Cx*Ix + B10) + B00*(xij + 2*Cx))); I[41] += C[2]*W[a]*(Kz*(Dx*Ix + B00)); I[42] += C[3]*W[a]*(Cy*Kz*(Dx*Ix + B00)); I[43] += C[3]*W[a]*(Ix*Kz*Qy); I[44] += C[3]*W[a]*(Kz*(B00*(yij + 2*Cy) + Dy*(Cy*Iy + B10))); I[45] += C[3]*W[a]*(Cx*Kz*(Dy*Iy + B00)); I[46] += C[2]*W[a]*(Kz*(Dy*Iy + B00)); I[47] += C[3]*W[a]*(f2*(Dy*Iy + B00)); I[48] += C[3]*W[a]*(Cz*Kx*(Dy*Iy + B00)); I[49] += C[3]*W[a]*(Kx*(B00*(yij + 2*Cy) + Dy*(Cy*Iy + B10))); I[50] += C[2]*W[a]*(Kx*(Dy*Iy + B00)); I[51] += C[3]*W[a]*(Iz*Kx*Qy); I[52] += C[3]*W[a]*(Dx*Iz*(B00 + Cy*Ky)); I[53] += C[1]*W[a]*(Iz*(B00 + Cy*Ky)); I[54] += C[3]*W[a]*(Iz*(Cy*Dy*Ky + B01*Cy + B00*(ykl + 2*Dy))); I[55] += C[3]*W[a]*(Ix*(Cy*Dy*Ky + B01*Cy + B00*(ykl + 2*Dy))); I[56] += C[1]*W[a]*(Ix*(B00 + Cy*Ky)); I[57] += C[3]*W[a]*(Dz*Ix*(B00 + Cy*Ky)); I[58] += C[3]*W[a]*(Cx*Dz*(B00 + Iy*Ky)); I[59] += C[2]*W[a]*(Dz*(B00 + Iy*Ky)); I[60] += C[3]*W[a]*(Dz*(B00*(yij + 2*Cy) + Ky*(Cy*Iy + B10))); I[61] += C[1]*W[a]*((B00*(yij + 2*Cy) + Ky*(Cy*Iy + B10))); I[62] += C[3]*W[a]*(Dx*(B00*(yij + 2*Cy) + Ky*(Cy*Iy + B10))); I[63] += C[2]*W[a]*(Dx*(B00 + Iy*Ky)); I[64] += C[3]*W[a]*(Qx*(B00 + Iy*Ky)); I[65] += C[1]*W[a]*(Cx*(B00 + Iy*Ky)); I[66] += C[0]*W[a]*((B00 + Iy*Ky)); I[67] += C[1]*W[a]*(Cz*(B00 + Iy*Ky)); I[68] += C[3]*W[a]*(Qz*(B00 + Iy*Ky)); I[69] += C[3]*W[a]*((B00 + Cy*Ky)*(B00 + Dz*Iz)); I[70] += C[3]*W[a]*(Qy*(Iz*Kz + B00)); I[71] += C[3]*W[a]*(Cx*Dy*(Iz*Kz + B00)); I[72] += C[2]*W[a]*(Dy*(Iz*Kz + B00)); I[73] += C[3]*W[a]*(Dy*(Kz*(B10 + Cz*Iz) + B00*(2*Cz + zij))); I[74] += C[1]*W[a]*((Kz*(B10 + Cz*Iz) + B00*(2*Cz + zij))); I[75] += C[3]*W[a]*(Dx*(Kz*(B10 + Cz*Iz) + B00*(2*Cz + zij))); I[76] += C[3]*W[a]*(Cy*Dx*(Iz*Kz + B00)); I[77] += C[2]*W[a]*(Dx*(Iz*Kz + B00)); I[78] += C[3]*W[a]*(Qx*(Iz*Kz + B00)); I[79] += C[1]*W[a]*(Cx*(Iz*Kz + B00)); I[80] += C[0]*W[a]*((Iz*Kz + B00)); I[81] += C[1]*W[a]*(Cy*(Iz*Kz + B00)); I[82] += C[3]*W[a]*(Cy*Kx*(B00 + Dz*Iz)); I[83] += C[2]*W[a]*(Kx*(B00 + Dz*Iz)); I[84] += C[3]*W[a]*(Kx*(Dz*(B10 + Cz*Iz) + B00*(2*Cz + zij))); I[85] += C[3]*W[a]*(Ky*(Dz*(B10 + Cz*Iz) + B00*(2*Cz + zij))); I[86] += C[3]*W[a]*(Cx*Ky*(B00 + Dz*Iz)); I[87] += C[2]*W[a]*(Ky*(B00 + Dz*Iz)); I[88] += C[3]*W[a]*(Ix*Ky*Qz); I[89] += C[2]*W[a]*(Dz*Ix*Ky); I[90] += C[3]*W[a]*(Dz*Ky*f14); I[91] += C[3]*W[a]*(Dx*Kz*f22); I[92] += C[2]*W[a]*(Dx*Iy*Kz); I[93] += C[1]*W[a]*(Cx*Iy*Kz); I[94] += C[3]*W[a]*(Cx*Iy*f30); I[95] += C[3]*W[a]*(Cx*Iz*f26); I[96] += C[3]*W[a]*(Cy*Iz*f21); I[97] += C[1]*W[a]*(Cy*Iz*Kx); I[98] += C[3]*W[a]*(Dz*Kx*f22); I[99] += C[1]*W[a]*(Kx*f22); I[100] += C[2]*W[a]*(Dz*Iy*Kx); I[101] += C[3]*W[a]*(Dz*Iy*f2); I[102] += C[1]*W[a]*(Iy*f2); I[103] += C[3]*W[a]*(Dy*Iz*f2); I[104] += C[1]*W[a]*(Iz*f2); I[105] += C[0]*W[a]*(Iz*Kx); I[106] += C[2]*W[a]*(Dy*Iz*Kx); I[107] += C[3]*W[a]*(Dy*Kx*f37); I[108] += C[1]*W[a]*(Kx*f37); I[109] += C[0]*W[a]*(Iy*Kx); I[110] += C[1]*W[a]*(Cz*Iy*Kx); I[111] += C[3]*W[a]*(Cz*Iy*f21); I[112] += C[2]*W[a]*(Iy*f21); I[113] += C[3]*W[a]*(f21*f22); I[114] += C[2]*W[a]*(Iz*f21); I[115] += C[3]*W[a]*(f21*f37); I[116] += C[3]*W[a]*(Dx*Ky*f37); I[117] += C[2]*W[a]*(Dx*Iz*Ky); I[118] += C[1]*W[a]*(Cx*Iz*Ky); I[119] += C[0]*W[a]*(Iz*Ky); I[120] += C[1]*W[a]*(Ky*f37); I[121] += C[1]*W[a]*(Ky*f14); I[122] += C[3]*W[a]*(f14*f26); I[123] += C[2]*W[a]*(Iz*f26); I[124] += C[3]*W[a]*(f26*f37); I[125] += C[2]*W[a]*(Ix*f26); I[126] += C[3]*W[a]*(Cz*Ix*f26); I[127] += C[1]*W[a]*(Cz*Ix*Ky); I[128] += C[0]*W[a]*(Ix*Ky); I[129] += C[2]*W[a]*(Dy*Ix*Kz); I[130] += C[3]*W[a]*(Dy*Kz*f14); I[131] += C[1]*W[a]*(Kz*f14); I[132] += C[0]*W[a]*(Iy*Kz); I[133] += C[1]*W[a]*(Kz*f22); I[134] += C[0]*W[a]*(Ix*Kz); I[135] += C[1]*W[a]*(Cy*Ix*Kz); I[136] += C[3]*W[a]*(Cy*Ix*f30); I[137] += C[2]*W[a]*(Ix*f30); I[138] += C[3]*W[a]*(f14*f30); I[139] += C[2]*W[a]*(Iy*f30); I[140] += C[3]*W[a]*(f22*f30); I[141] += C[3]*W[a]*(Cz*f3); I[142] += C[3]*W[a]*(Cx*f3); I[143] += C[2]*W[a]*(f3); } #undef B00 #undef B10 #undef B01 #undef Cx #undef Cy #undef Cz #undef Dx #undef Dy #undef Dz #undef pow } static inline void reorder(double (&I)[144]) { double T[144]; for (int i = 0; i < 144; ++i) { T[i] = I[i]; } I[78] = T[0]; I[111] = T[1]; I[62] = T[2]; I[67] = T[3]; I[127] = T[4]; I[143] = T[5]; I[141] = T[6]; I[142] = T[7]; I[140] = T[8]; I[115] = T[9]; I[43] = T[10]; I[139] = T[11]; I[135] = T[12]; I[123] = T[13]; I[99] = T[14]; I[103] = T[15]; I[45] = T[16]; I[39] = T[17]; I[37] = T[18]; I[25] = T[19]; I[13] = T[20]; I[21] = T[21]; I[69] = T[22]; I[63] = T[23]; I[61] = T[24]; I[60] = T[25]; I[113] = T[26]; I[17] = T[27]; I[15] = T[28]; I[12] = T[29]; I[14] = T[30]; I[26] = T[31]; I[24] = T[32]; I[27] = T[33]; I[3] = T[34]; I[36] = T[35]; I[38] = T[36]; I[2] = T[37]; I[0] = T[38]; I[1] = T[39]; I[109] = T[40]; I[108] = T[41]; I[110] = T[42]; I[122] = T[43]; I[126] = T[44]; I[125] = T[45]; I[124] = T[46]; I[29] = T[47]; I[31] = T[48]; I[30] = T[49]; I[28] = T[50]; I[34] = T[51]; I[70] = T[52]; I[58] = T[53]; I[82] = T[54]; I[74] = T[55]; I[50] = T[56]; I[86] = T[57]; I[89] = T[58]; I[88] = T[59]; I[90] = T[60]; I[54] = T[61]; I[66] = T[62]; I[64] = T[63]; I[65] = T[64]; I[53] = T[65]; I[52] = T[66]; I[55] = T[67]; I[91] = T[68]; I[94] = T[69]; I[130] = T[70]; I[129] = T[71]; I[128] = T[72]; I[131] = T[73]; I[107] = T[74]; I[119] = T[75]; I[118] = T[76]; I[116] = T[77]; I[117] = T[78]; I[105] = T[79]; I[104] = T[80]; I[106] = T[81]; I[46] = T[82]; I[44] = T[83]; I[47] = T[84]; I[95] = T[85]; I[93] = T[86]; I[92] = T[87]; I[87] = T[88]; I[84] = T[89]; I[85] = T[90]; I[114] = T[91]; I[112] = T[92]; I[101] = T[93]; I[137] = T[94]; I[81] = T[95]; I[22] = T[96]; I[10] = T[97]; I[42] = T[98]; I[6] = T[99]; I[40] = T[100]; I[41] = T[101]; I[5] = T[102]; I[33] = T[103]; I[9] = T[104]; I[8] = T[105]; I[32] = T[106]; I[35] = T[107]; I[11] = T[108]; I[4] = T[109]; I[7] = T[110]; I[19] = T[111]; I[16] = T[112]; I[18] = T[113]; I[20] = T[114]; I[23] = T[115]; I[71] = T[116]; I[68] = T[117]; I[57] = T[118]; I[56] = T[119]; I[59] = T[120]; I[49] = T[121]; I[73] = T[122]; I[80] = T[123]; I[83] = T[124]; I[72] = T[125]; I[75] = T[126]; I[51] = T[127]; I[48] = T[128]; I[120] = T[129]; I[121] = T[130]; I[97] = T[131]; I[100] = T[132]; I[102] = T[133]; I[96] = T[134]; I[98] = T[135]; I[134] = T[136]; I[132] = T[137]; I[133] = T[138]; I[136] = T[139]; I[138] = T[140]; I[79] = T[141]; I[77] = T[142]; I[76] = T[143]; } }; template<> struct impl > { typedef void enable; static const bool value = true; static inline void eval(double A, double B, const Vector<3> &rAi, const Vector<3> &rBk, const Vector<3> &rAB, const Vector<3> &rij, const Vector<3> &rkl, const Vector<3> &t2, const Vector<3> &W, const double (&C)[1], double (&I)[90]) { #define pow(x,y) util::pow<(y)>::eval((x)) const int N = 3; double xij = rij[0]; double yij = rij[1]; double zij = rij[2]; // // double vB00[N] __attribute__ ((aligned(16))); // // // double vB10[N] __attribute__ ((aligned(16))); // // // // double vCx[N] __attribute__ ((aligned(16))); // double vCy[N] __attribute__ ((aligned(16))); // double vCz[N] __attribute__ ((aligned(16))); // // // double vDx[N] __attribute__ ((aligned(16))); // double vDy[N] __attribute__ ((aligned(16))); // double vDz[N] __attribute__ ((aligned(16))); // // for (int a = 0; a < N; ++a) { // // vB00[a] = 0.5*t2[a]; // // // vB10[a] = recurrence::coefficient(1.0/A, B, t2[a]); // // // // vCx[a] = recurrence::coefficient<0>(rAi, B, rAB, t2[a]); // vCy[a] = recurrence::coefficient<1>(rAi, B, rAB, t2[a]); // vCz[a] = recurrence::coefficient<2>(rAi, B, rAB, t2[a]); // // // vDx[a] = recurrence::coefficient<0>(rBk, -A, rAB, t2[a]); // vDy[a] = recurrence::coefficient<1>(rBk, -A, rAB, t2[a]); // vDz[a] = recurrence::coefficient<2>(rBk, -A, rAB, t2[a]); // // } // #define B00 vB00[a] // #define B10 vB10[a] // #define B01 vB01[a] // #define Cx vCx[a] // #define Cy vCy[a] // #define Cz vCz[a] // #define Dx vDx[a] // #define Dy vDy[a] // #define Dz vDz[a] #if defined (__INTEL_COMPILER) #pragma ivdep #pragma vector aligned #endif for (int a = 0; a < N; ++a) { double B00 = 0.5*t2[a]; double B10 = recurrence::coefficient(1.0/A, B, t2[a]); double Cx = recurrence::coefficient<0>(rAi, B, rAB, t2[a]); double Cy = recurrence::coefficient<1>(rAi, B, rAB, t2[a]); double Cz = recurrence::coefficient<2>(rAi, B, rAB, t2[a]); double Dx = recurrence::coefficient<0>(rBk, -A, rAB, t2[a]); double Dy = recurrence::coefficient<1>(rBk, -A, rAB, t2[a]); double Dz = recurrence::coefficient<2>(rBk, -A, rAB, t2[a]); double Ix = (Cx + xij); double Iy = (Cy + yij); double Iz = (Cz + zij); double Px = (B10 + pow(Cx,2)); double Py = (B10 + pow(Cy,2)); double Pz = (B10 + pow(Cz,2)); double Qx = (Cx*Dx + B00); double Qy = (Cy*Dy + B00); double Qz = (Cz*Dz + B00); double f0 = (3*B10 + pow(Cx,2)); double f10 = (3*B00*Pz + Cz*Dz*(3*B10 + pow(Cz,2))); double f11 = (3*pow(B10,2) + 3*B10*Cz*(2*Cz + zij) + Iz*pow(Cz,3)); double f12 = (B00 + Dz*Iz); double f14 = (Dx*(Cx*Ix + B10) + B00*(xij + 2*Cx)); double f16 = (Dy*Iy + B00); double f17 = (Cy*Iy + B10); double f18 = (3*pow(B10,2) + 3*B10*Cx*(xij + 2*Cx) + Ix*pow(Cx,3)); double f2 = (Dz*Pz + 2*B00*Cz); double f20 = (Dx*Px + 2*B00*Cx); double f22 = (B10*(3*Cx + xij) + Ix*pow(Cx,2)); double f28 = (Cx*Dx*(3*B10 + pow(Cx,2)) + 3*B00*Px); double f3 = (Iz*pow(Cz,2) + B10*(3*Cz + zij)); double f31 = (3*B10 + pow(Cz,2)); double f32 = (3*B10 + pow(Cy,2)); double f35 = (3*pow(B10,2) + Iy*pow(Cy,3) + 3*B10*Cy*(yij + 2*Cy)); double f4 = (Dz*(Iz*pow(Cz,2) + B10*(3*Cz + zij)) + 3*B00*Pz + 2*B00*Cz*zij); double f5 = (B00*(yij + 2*Cy) + Dy*(Cy*Iy + B10)); double f6 = (Dx*(B10*(3*Cx + xij) + Ix*pow(Cx,2)) + 2*B00*Cx*xij + 3*B00*Px); double f7 = (Cy*Dy*(3*B10 + pow(Cy,2)) + 3*B00*Py); double f8 = (Dy*Py + 2*B00*Cy); double f9 = (B10*(3*Cy + yij) + Iy*pow(Cy,2)); I[0] += C[0]*W[a]*(Cx*(f7 + yij*(Dy*Py + 2*B00*Cy))); I[1] += C[0]*W[a]*(Cz*(f7 + yij*(Dy*Py + 2*B00*Cy))); I[2] += C[0]*W[a]*((3*B00*Py*yij + Dy*(3*pow(B10,2) + Iy*pow(Cy,3) + 3*B10*Cy*(yij + 2*Cy)) + 4*B00*Cy*f32)); I[3] += C[0]*W[a]*(Dz*Py*(Px + Cx*xij)); I[4] += C[0]*W[a]*(Cy*Qz*(Px + Cx*xij)); I[5] += C[0]*W[a]*(Cz*Qy*(Px + Cx*xij)); I[6] += C[0]*W[a]*(Cx*Qy*(Cz*zij + Pz)); I[7] += C[0]*W[a]*(Cx*Cy*(f2 + Qz*zij)); I[8] += C[0]*W[a]*(Py*(f2 + Qz*zij)); I[9] += C[0]*W[a]*(Px*(f2 + Qz*zij)); I[10] += C[0]*W[a]*((3*B00*Pz*zij + Dz*(3*pow(B10,2) + 3*B10*Cz*(2*Cz + zij) + Iz*pow(Cz,3)) + 4*B00*Cz*f31)); I[11] += C[0]*W[a]*((3*B00*Px*xij + 4*B00*Cx*f0 + Dx*(3*pow(B10,2) + 3*B10*Cx*(xij + 2*Cx) + Ix*pow(Cx,3)))); I[12] += C[0]*W[a]*(Cx*Dy*Iz*f0); I[13] += C[0]*W[a]*(Dy*Pz*(Px + Cx*xij)); I[14] += C[0]*W[a]*(Dy*Px*(Cz*zij + Pz)); I[15] += C[0]*W[a]*(Cy*Qx*(Cz*zij + Pz)); I[16] += C[0]*W[a]*(Cy*Pz*(Dx*xij + Qx)); I[17] += C[0]*W[a]*(Cy*f32*(Dx*xij + Qx)); I[18] += C[0]*W[a]*(Cz*f31*(Dx*xij + Qx)); I[19] += C[0]*W[a]*(Cz*Py*(Dx*xij + Qx)); I[20] += C[0]*W[a]*(Dx*Py*(Cz*zij + Pz)); I[21] += C[0]*W[a]*(f20*(Cz*zij + Pz)); I[22] += C[0]*W[a]*(f8*(Cz*zij + Pz)); I[23] += C[0]*W[a]*(Cx*Cz*f5); I[24] += C[0]*W[a]*(Cy*Dz*Ix*f32); I[25] += C[0]*W[a]*(Cy*Dz*f22); I[26] += C[0]*W[a]*(Ix*Py*Qz); I[27] += C[0]*W[a]*(Cy*Ix*f2); I[28] += C[0]*W[a]*(f2*(Px + Cx*xij)); I[29] += C[0]*W[a]*(f8*(Px + Cx*xij)); I[30] += C[0]*W[a]*(Cx*Iz*f8); I[31] += C[0]*W[a]*(Iz*Px*Qy); I[32] += C[0]*W[a]*(Dz*Px*f17); I[33] += C[0]*W[a]*(Iy*Px*Qz); I[34] += C[0]*W[a]*(Cx*Dz*Iy*f0); I[35] += C[0]*W[a]*(Cx*Dz*f9); I[36] += C[0]*W[a]*(Cx*Iy*f2); I[37] += C[0]*W[a]*(Cx*Qz*f17); I[38] += C[0]*W[a]*(Cx*Dy*f3); I[39] += C[0]*W[a]*(Cy*Dx*f3); I[40] += C[0]*W[a]*(Cy*Iz*f20); I[41] += C[0]*W[a]*(Cy*Dx*Iz*f32); I[42] += C[0]*W[a]*(Cy*f12*f32); I[43] += C[0]*W[a]*(Cy*Px*f12); I[44] += C[0]*W[a]*(Cz*Px*f16); I[45] += C[0]*W[a]*(Cz*f16*f31); I[46] += C[0]*W[a]*(Cz*Dy*f22); I[47] += C[0]*W[a]*(Cz*Dy*Ix*f31); I[48] += C[0]*W[a]*(Cz*Ix*f8); I[49] += C[0]*W[a]*(Ix*Pz*Qy); I[50] += C[0]*W[a]*(Cx*Pz*f16); I[51] += C[0]*W[a]*(Cx*f0*f16); I[52] += C[0]*W[a]*(Cx*f0*f12); I[53] += C[0]*W[a]*(Cx*Py*f12); I[54] += C[0]*W[a]*(Iz*Py*Qx); I[55] += C[0]*W[a]*(Cz*Qx*f17); I[56] += C[0]*W[a]*(Iy*Pz*Qx); I[57] += C[0]*W[a]*(Dx*Pz*f17); I[58] += C[0]*W[a]*(Cz*Dx*f9); I[59] += C[0]*W[a]*(Cz*Dx*Iy*f31); I[60] += C[0]*W[a]*(Cz*Iy*f20); I[61] += C[0]*W[a]*(Cy*Cz*f14); I[62] += C[0]*W[a]*(Cy*f6); I[63] += C[0]*W[a]*(Cz*f6); I[64] += C[0]*W[a]*(Py*f14); I[65] += C[0]*W[a]*(Pz*f14); I[66] += C[0]*W[a]*(Px*f5); I[67] += C[0]*W[a]*(Pz*f5); I[68] += C[0]*W[a]*(Dx*f35); I[69] += C[0]*W[a]*(Dx*f11); I[70] += C[0]*W[a]*(Dy*f11); I[71] += C[0]*W[a]*(Dy*f18); I[72] += C[0]*W[a]*(Dz*f18); I[73] += C[0]*W[a]*(Dz*f35); I[74] += C[0]*W[a]*(Ix*f10); I[75] += C[0]*W[a]*(Ix*f7); I[76] += C[0]*W[a]*(Iz*f7); I[77] += C[0]*W[a]*(Iz*f28); I[78] += C[0]*W[a]*(Iy*f28); I[79] += C[0]*W[a]*(Iy*f10); I[80] += C[0]*W[a]*(Qz*f22); I[81] += C[0]*W[a]*(Qy*f22); I[82] += C[0]*W[a]*(Qy*f3); I[83] += C[0]*W[a]*(Qx*f3); I[84] += C[0]*W[a]*(Qx*f9); I[85] += C[0]*W[a]*(Qz*f9); I[86] += C[0]*W[a]*(f17*f20); I[87] += C[0]*W[a]*(f17*f2); I[88] += C[0]*W[a]*(Cx*f4); I[89] += C[0]*W[a]*(Cy*f4); } #undef B00 #undef B10 #undef B01 #undef Cx #undef Cy #undef Cz #undef Dx #undef Dy #undef Dz #undef pow } static inline void reorder(double (&I)[90]) { double T[90]; for (int i = 0; i < 90; ++i) { T[i] = I[i]; } I[45] = T[0]; I[46] = T[1]; I[41] = T[2]; I[65] = T[3]; I[69] = T[4]; I[39] = T[5]; I[59] = T[6]; I[89] = T[7]; I[86] = T[8]; I[84] = T[9]; I[82] = T[10]; I[0] = T[11]; I[50] = T[12]; I[37] = T[13]; I[54] = T[14]; I[29] = T[15]; I[8] = T[16]; I[1] = T[17]; I[2] = T[18]; I[6] = T[19]; I[26] = T[20]; I[24] = T[21]; I[56] = T[22]; I[49] = T[23]; I[61] = T[24]; I[63] = T[25]; I[66] = T[26]; I[68] = T[27]; I[67] = T[28]; I[35] = T[29]; I[55] = T[30]; I[53] = T[31]; I[73] = T[32]; I[74] = T[33]; I[70] = T[34]; I[75] = T[35]; I[77] = T[36]; I[79] = T[37]; I[57] = T[38]; I[28] = T[39]; I[23] = T[40]; I[21] = T[41]; I[81] = T[42]; I[83] = T[43]; I[44] = T[44]; I[42] = T[45]; I[34] = T[46]; I[32] = T[47]; I[36] = T[48]; I[38] = T[49]; I[47] = T[50]; I[40] = T[51]; I[80] = T[52]; I[85] = T[53]; I[25] = T[54]; I[19] = T[55]; I[17] = T[56]; I[18] = T[57]; I[16] = T[58]; I[12] = T[59]; I[14] = T[60]; I[9] = T[61]; I[3] = T[62]; I[4] = T[63]; I[5] = T[64]; I[7] = T[65]; I[43] = T[66]; I[48] = T[67]; I[11] = T[68]; I[22] = T[69]; I[52] = T[70]; I[30] = T[71]; I[60] = T[72]; I[71] = T[73]; I[62] = T[74]; I[31] = T[75]; I[51] = T[76]; I[20] = T[77]; I[10] = T[78]; I[72] = T[79]; I[64] = T[80]; I[33] = T[81]; I[58] = T[82]; I[27] = T[83]; I[15] = T[84]; I[76] = T[85]; I[13] = T[86]; I[78] = T[87]; I[87] = T[88]; I[88] = T[89]; } }; template<> struct impl > { typedef void enable; static const bool value = true; static inline void eval(double A, double B, const Vector<3> &rAi, const Vector<3> &rBk, const Vector<3> &rAB, const Vector<3> &rij, const Vector<3> &rkl, const Vector<3> &t2, const Vector<3> &W, const double (&C)[1], double (&I)[60]) { #define pow(x,y) util::pow<(y)>::eval((x)) const int N = 3; double xij = rij[0]; double yij = rij[1]; double zij = rij[2]; // // // double vB10[N] __attribute__ ((aligned(16))); // // // // double vCx[N] __attribute__ ((aligned(16))); // double vCy[N] __attribute__ ((aligned(16))); // double vCz[N] __attribute__ ((aligned(16))); // // // for (int a = 0; a < N; ++a) { // // // vB10[a] = recurrence::coefficient(1.0/A, B, t2[a]); // // // // vCx[a] = recurrence::coefficient<0>(rAi, B, rAB, t2[a]); // vCy[a] = recurrence::coefficient<1>(rAi, B, rAB, t2[a]); // vCz[a] = recurrence::coefficient<2>(rAi, B, rAB, t2[a]); // // // } // #define B00 vB00[a] // #define B10 vB10[a] // #define B01 vB01[a] // #define Cx vCx[a] // #define Cy vCy[a] // #define Cz vCz[a] // #define Dx vDx[a] // #define Dy vDy[a] // #define Dz vDz[a] #if defined (__INTEL_COMPILER) #pragma ivdep #pragma vector aligned #endif for (int a = 0; a < N; ++a) { double B10 = recurrence::coefficient(1.0/A, B, t2[a]); double Cx = recurrence::coefficient<0>(rAi, B, rAB, t2[a]); double Cy = recurrence::coefficient<1>(rAi, B, rAB, t2[a]); double Cz = recurrence::coefficient<2>(rAi, B, rAB, t2[a]); double Ix = (Cx + xij); double Iy = (Cy + yij); double Iz = (Cz + zij); double Px = (B10 + pow(Cx,2)); double Py = (B10 + pow(Cy,2)); double Pz = (B10 + pow(Cz,2)); double f0 = (3*B10 + pow(Cx,2)); double f10 = (Cy*Iy + B10); double f11 = (Cy*pow(Iy,2) + B10*(3*Cy + 2*yij)); double f12 = (B10*(3*Cx + xij) + Ix*pow(Cx,2)); double f13 = (B10 + Cz*Iz); double f14 = (3*pow(B10,2) + 3*B10*Cx*(xij + 2*Cx) + Ix*pow(Cx,3)); double f15 = (B10 + pow(Iy,2)); double f16 = (B10 + pow(Iz,2)); double f19 = (3*pow(B10,2) + 3*B10*Cz*(2*Cz + zij) + Iz*pow(Cz,3)); double f2 = (B10*(3*Cx + 2*xij) + Cx*pow(Ix,2)); double f21 = (3*B10 + pow(Cz,2)); double f22 = (3*B10 + pow(Cy,2)); double f23 = (Iz*pow(Cz,2) + B10*(3*Cz + zij)); double f26 = (3*pow(B10,2) + Iy*pow(Cy,3) + 3*B10*Cy*(yij + 2*Cy)); double f3 = (3*pow(B10,2) + pow(Cz,2)*pow(Iz,2) + B10*(6*Cz*zij + pow(zij,2) + 6*pow(Cz,2))); double f4 = (B10*(3*Cy + yij) + Iy*pow(Cy,2)); double f5 = (3*pow(B10,2) + B10*(6*Cx*xij + pow(xij,2) + 6*pow(Cx,2)) + pow(Cx,2)*pow(Ix,2)); double f7 = (B10*(3*Cz + 2*zij) + Cz*pow(Iz,2)); double f9 = (3*pow(B10,2) + B10*(6*Cy*yij + pow(yij,2) + 6*pow(Cy,2)) + pow(Cy,2)*pow(Iy,2)); I[0] += C[0]*W[a]*(Cz*f21*(xij*(xij + 2*Cx) + Px)); I[1] += C[0]*W[a]*(Cz*f10*(Px + Cx*xij)); I[2] += C[0]*W[a]*(Cz*Py*(xij*(xij + 2*Cx) + Px)); I[3] += C[0]*W[a]*(Iz*Py*(Px + Cx*xij)); I[4] += C[0]*W[a]*(Cy*f22*(xij*(xij + 2*Cx) + Px)); I[5] += C[0]*W[a]*(Cy*f13*(Px + Cx*xij)); I[6] += C[0]*W[a]*(Cy*Pz*(xij*(xij + 2*Cx) + Px)); I[7] += C[0]*W[a]*(Iy*Pz*(Px + Cx*xij)); I[8] += C[0]*W[a]*(Cx*Iy*Iz*f0); I[9] += C[0]*W[a]*(Cx*Cy*f7); I[10] += C[0]*W[a]*(Ix*Pz*f10); I[11] += C[0]*W[a]*(Cy*Ix*Iz*f22); I[12] += C[0]*W[a]*(Cy*Iz*f12); I[13] += C[0]*W[a]*((3*pow(B10,2)*(5*Cz + 2*zij) + B10*Cz*(3*pow(zij,2) + 10*pow(Cz,2) + 12*Cz*zij) + pow(Cz,3)*pow(Iz,2))); I[14] += C[0]*W[a]*(Cz*Ix*f4); I[15] += C[0]*W[a]*(Ix*Py*f13); I[16] += C[0]*W[a]*(Cy*Ix*f23); I[17] += C[0]*W[a]*(Cy*Px*f16); I[18] += C[0]*W[a]*(Cy*f16*f22); I[19] += C[0]*W[a]*(Cx*Py*f16); I[20] += C[0]*W[a]*(Cx*f0*f16); I[21] += C[0]*W[a]*(Cx*Pz*f15); I[22] += C[0]*W[a]*(Cx*f0*f15); I[23] += C[0]*W[a]*(Cx*Cz*f11); I[24] += C[0]*W[a]*(Cz*Iy*f12); I[25] += C[0]*W[a]*(Cz*Ix*Iy*f21); I[26] += C[0]*W[a]*(Cz*f15*f21); I[27] += C[0]*W[a]*(Cz*Px*f15); I[28] += C[0]*W[a]*(Iz*Px*f10); I[29] += C[0]*W[a]*(Iy*Px*f13); I[30] += C[0]*W[a]*(f23*(Px + Cx*xij)); I[31] += C[0]*W[a]*(f4*(Px + Cx*xij)); I[32] += C[0]*W[a]*(Cx*Iz*f4); I[33] += C[0]*W[a]*(Cx*Iy*f23); I[34] += C[0]*W[a]*(Cx*f10*f13); I[35] += C[0]*W[a]*((B10*Cx*(12*Cx*xij + 10*pow(Cx,2) + 3*pow(xij,2)) + 3*pow(B10,2)*(5*Cx + 2*xij) + pow(Cx,3)*pow(Ix,2))); I[36] += C[0]*W[a]*((3*pow(B10,2)*(5*Cy + 2*yij) + B10*Cy*(12*Cy*yij + 3*pow(yij,2) + 10*pow(Cy,2)) + pow(Cy,3)*pow(Iy,2))); I[37] += C[0]*W[a]*(Cy*Cz*f2); I[38] += C[0]*W[a]*(Py*f2); I[39] += C[0]*W[a]*(Pz*f2); I[40] += C[0]*W[a]*(Pz*f11); I[41] += C[0]*W[a]*(Px*f11); I[42] += C[0]*W[a]*(Px*f7); I[43] += C[0]*W[a]*(Py*f7); I[44] += C[0]*W[a]*(Cy*f5); I[45] += C[0]*W[a]*(Cz*f5); I[46] += C[0]*W[a]*(Cz*f9); I[47] += C[0]*W[a]*(Cx*f9); I[48] += C[0]*W[a]*(Cx*f3); I[49] += C[0]*W[a]*(Cy*f3); I[50] += C[0]*W[a]*(Ix*f19); I[51] += C[0]*W[a]*(Ix*f26); I[52] += C[0]*W[a]*(Iz*f26); I[53] += C[0]*W[a]*(Iz*f14); I[54] += C[0]*W[a]*(Iy*f14); I[55] += C[0]*W[a]*(Iy*f19); I[56] += C[0]*W[a]*(f13*f4); I[57] += C[0]*W[a]*(f12*f13); I[58] += C[0]*W[a]*(f10*f12); I[59] += C[0]*W[a]*(f10*f23); } #undef B00 #undef B10 #undef B01 #undef Cx #undef Cy #undef Cz #undef Dx #undef Dy #undef Dz #undef pow } static inline void reorder(double (&I)[60]) { double T[60]; for (int i = 0; i < 60; ++i) { T[i] = I[i]; } I[2] = T[0]; I[39] = T[1]; I[6] = T[2]; I[45] = T[3]; I[1] = T[4]; I[49] = T[5]; I[8] = T[6]; I[37] = T[7]; I[50] = T[8]; I[29] = T[9]; I[38] = T[10]; I[41] = T[11]; I[43] = T[12]; I[22] = T[13]; I[36] = T[14]; I[46] = T[15]; I[48] = T[16]; I[23] = T[17]; I[21] = T[18]; I[25] = T[19]; I[20] = T[20]; I[17] = T[21]; I[10] = T[22]; I[19] = T[23]; I[34] = T[24]; I[32] = T[25]; I[12] = T[26]; I[14] = T[27]; I[53] = T[28]; I[54] = T[29]; I[47] = T[30]; I[35] = T[31]; I[55] = T[32]; I[57] = T[33]; I[59] = T[34]; I[0] = T[35]; I[11] = T[36]; I[9] = T[37]; I[5] = T[38]; I[7] = T[39]; I[18] = T[40]; I[13] = T[41]; I[24] = T[42]; I[26] = T[43]; I[3] = T[44]; I[4] = T[45]; I[16] = T[46]; I[15] = T[47]; I[27] = T[48]; I[28] = T[49]; I[42] = T[50]; I[31] = T[51]; I[51] = T[52]; I[40] = T[53]; I[30] = T[54]; I[52] = T[55]; I[56] = T[56]; I[44] = T[57]; I[33] = T[58]; I[58] = T[59]; } }; template<> struct impl > { typedef void enable; static const bool value = true; static inline void eval(double A, double B, const Vector<3> &rAi, const Vector<3> &rBk, const Vector<3> &rAB, const Vector<3> &rij, const Vector<3> &rkl, const Vector<3> &t2, const Vector<3> &W, const double (&C)[1], double (&I)[81]) { #define pow(x,y) util::pow<(y)>::eval((x)) const int N = 3; double xij = rij[0]; double yij = rij[1]; double zij = rij[2]; double xkl = rkl[0]; double ykl = rkl[1]; double zkl = rkl[2]; // // double vB00[N] __attribute__ ((aligned(16))); // // // double vB10[N] __attribute__ ((aligned(16))); // // // double vB01[N] __attribute__ ((aligned(16))); // // // double vCx[N] __attribute__ ((aligned(16))); // double vCy[N] __attribute__ ((aligned(16))); // double vCz[N] __attribute__ ((aligned(16))); // // // double vDx[N] __attribute__ ((aligned(16))); // double vDy[N] __attribute__ ((aligned(16))); // double vDz[N] __attribute__ ((aligned(16))); // // for (int a = 0; a < N; ++a) { // // vB00[a] = 0.5*t2[a]; // // // vB10[a] = recurrence::coefficient(1.0/A, B, t2[a]); // // // vB01[a] = recurrence::coefficient(1.0/B, A, t2[a]); // // // vCx[a] = recurrence::coefficient<0>(rAi, B, rAB, t2[a]); // vCy[a] = recurrence::coefficient<1>(rAi, B, rAB, t2[a]); // vCz[a] = recurrence::coefficient<2>(rAi, B, rAB, t2[a]); // // // vDx[a] = recurrence::coefficient<0>(rBk, -A, rAB, t2[a]); // vDy[a] = recurrence::coefficient<1>(rBk, -A, rAB, t2[a]); // vDz[a] = recurrence::coefficient<2>(rBk, -A, rAB, t2[a]); // // } // #define B00 vB00[a] // #define B10 vB10[a] // #define B01 vB01[a] // #define Cx vCx[a] // #define Cy vCy[a] // #define Cz vCz[a] // #define Dx vDx[a] // #define Dy vDy[a] // #define Dz vDz[a] #if defined (__INTEL_COMPILER) #pragma ivdep #pragma vector aligned #endif for (int a = 0; a < N; ++a) { double B00 = 0.5*t2[a]; double B10 = recurrence::coefficient(1.0/A, B, t2[a]); double B01 = recurrence::coefficient(1.0/B, A, t2[a]); double Cx = recurrence::coefficient<0>(rAi, B, rAB, t2[a]); double Cy = recurrence::coefficient<1>(rAi, B, rAB, t2[a]); double Cz = recurrence::coefficient<2>(rAi, B, rAB, t2[a]); double Dx = recurrence::coefficient<0>(rBk, -A, rAB, t2[a]); double Dy = recurrence::coefficient<1>(rBk, -A, rAB, t2[a]); double Dz = recurrence::coefficient<2>(rBk, -A, rAB, t2[a]); double Ix = (Cx + xij); double Iy = (Cy + yij); double Iz = (Cz + zij); double Kx = (xkl + Dx); double Ky = (ykl + Dy); double Kz = (Dz + zkl); double Qx = (Cx*Dx + B00); double Qy = (Cy*Dy + B00); double Qz = (Cz*Dz + B00); double f1 = (B00*(ykl + 2*Dy) + Iy*(B01 + Dy*Ky)); double f10 = (B00 + Dz*Iz); double f12 = (Dx*(Cx*Ix + B10) + B00*(xij + 2*Cx)); double f13 = (B01 + Dx*Kx); double f14 = (Cy*Iy + B10); double f15 = B01*B10; double f16 = (B00*(yij + 2*Cy) + Ky*(Cy*Iy + B10)); double f18 = (B01*Cz + B00*(2*Dz + zkl) + Cz*Dz*Kz); double f19 = (B00 + Iy*Ky); double f2 = (Cy*Dy*Ky + B01*Cy + B00*(ykl + 2*Dy)); double f21 = (B00*(yij + 2*Cy) + Dy*(Cy*Iy + B10)); double f23 = (Dz*Kz + B01); double f24 = (B01 + Dy*Ky); double f26 = (B00 + Cy*Ky); double f27 = 2*pow(B00,2); double f28 = (Cx*Ix + B10); double f29 = (Dy*Iy + B00); double f31 = (Dz*(B10 + Cz*Iz) + B00*(2*Cz + zij)); double f34 = (B10 + Cz*Iz); double f4 = (B01*Cx + Cx*Dx*Kx + B00*(xkl + 2*Dx)); double f5 = (Kx*(Cx*Ix + B10) + B00*(xij + 2*Cx)); double f7 = (B00 + Ix*Kx); double f9 = (Iz*Kz + B00); I[0] += C[0]*W[a]*((B00*(xij + 2*Cx)*(xkl + 2*Dx) + f15 + f27 + B01*Cx*Ix + Dx*Kx*(Cx*Ix + B10))); I[1] += C[0]*W[a]*((f15 + f27 + Dy*Ky*(Cy*Iy + B10) + B01*Cy*Iy + B00*(yij + 2*Cy)*(ykl + 2*Dy))); I[2] += C[0]*W[a]*((Dz*Kz*(B10 + Cz*Iz) + f15 + f27 + B00*(2*Cz + zij)*(2*Dz + zkl) + B01*Cz*Iz)); I[3] += C[0]*W[a]*(Cx*(zij*(Dz*Kz + B01) + f18)); I[4] += C[0]*W[a]*(Cy*(zij*(Dz*Kz + B01) + f18)); I[5] += C[0]*W[a]*(Dy*(f31 + zkl*(B10 + Cz*Iz))); I[6] += C[0]*W[a]*(Dx*(f31 + zkl*(B10 + Cz*Iz))); I[7] += C[0]*W[a]*(Cz*(f4 + xij*(B01 + Dx*Kx))); I[8] += C[0]*W[a]*(Cy*(f4 + xij*(B01 + Dx*Kx))); I[9] += C[0]*W[a]*(Dy*Iz*(Cx*xkl + Qx)); I[10] += C[0]*W[a]*(Dz*Iy*(Cx*xkl + Qx)); I[11] += C[0]*W[a]*(f29*(Cx*xkl + Qx)); I[12] += C[0]*W[a]*(f10*(Cx*xkl + Qx)); I[13] += C[0]*W[a]*(Cy*Kz*(Dx*xij + Qx)); I[14] += C[0]*W[a]*(Cz*Ky*(Dx*xij + Qx)); I[15] += C[0]*W[a]*(f26*(Dx*xij + Qx)); I[16] += C[0]*W[a]*((Cz*zkl + Qz)*(Dx*xij + Qx)); I[17] += C[0]*W[a]*(Dy*Ix*(Cz*zkl + Qz)); I[18] += C[0]*W[a]*(Cz*Ix*f24); I[19] += C[0]*W[a]*(Cx*Iz*f24); I[20] += C[0]*W[a]*(Dx*Iz*f26); I[21] += C[0]*W[a]*(Dx*Ky*f34); I[22] += C[0]*W[a]*(Dz*Ky*f28); I[23] += C[0]*W[a]*(Dz*Ix*f26); I[24] += C[0]*W[a]*(Ix*Ky*Qz); I[25] += C[0]*W[a]*(Cy*Kx*f10); I[26] += C[0]*W[a]*(Dz*Kx*f14); I[27] += C[0]*W[a]*(Cx*Dz*f19); I[28] += C[0]*W[a]*(Cx*Ky*f10); I[29] += C[0]*W[a]*(Iz*Ky*Qx); I[30] += C[0]*W[a]*(Iy*Kz*Qx); I[31] += C[0]*W[a]*(Dx*Kz*f14); I[32] += C[0]*W[a]*(Cy*Dx*f9); I[33] += C[0]*W[a]*(Cy*Dz*f7); I[34] += C[0]*W[a]*(Cz*Dy*f7); I[35] += C[0]*W[a]*(Dy*Kz*f28); I[36] += C[0]*W[a]*(Ix*Kz*Qy); I[37] += C[0]*W[a]*(Cx*Kz*f29); I[38] += C[0]*W[a]*(Cx*Dy*f9); I[39] += C[0]*W[a]*(Dy*Kx*f34); I[40] += C[0]*W[a]*(Iy*Kx*Qz); I[41] += C[0]*W[a]*(Dx*Iy*(Cz*zkl + Qz)); I[42] += C[0]*W[a]*(f29*(Cz*zkl + Qz)); I[43] += C[0]*W[a]*(Cz*Kx*f29); I[44] += C[0]*W[a]*(Iz*Kx*Qy); I[45] += C[0]*W[a]*(Cy*Iz*f13); I[46] += C[0]*W[a]*(Cy*Ix*f23); I[47] += C[0]*W[a]*(Cx*Iy*f23); I[48] += C[0]*W[a]*(Cz*Iy*f13); I[49] += C[0]*W[a]*(Cz*Dx*f19); I[50] += C[0]*W[a]*(Dx*f16); I[51] += C[0]*W[a]*(Cx*f1); I[52] += C[0]*W[a]*(Cz*f1); I[53] += C[0]*W[a]*(Dy*f5); I[54] += C[0]*W[a]*(Dz*f5); I[55] += C[0]*W[a]*(Dz*f16); I[56] += C[0]*W[a]*(f10*f26); I[57] += C[0]*W[a]*(Kx*f21); I[58] += C[0]*W[a]*(Kx*f31); I[59] += C[0]*W[a]*(Ky*f31); I[60] += C[0]*W[a]*(Ky*f12); I[61] += C[0]*W[a]*(Kz*f12); I[62] += C[0]*W[a]*(Kz*f21); I[63] += C[0]*W[a]*(Qx*f9); I[64] += C[0]*W[a]*(Qx*f19); I[65] += C[0]*W[a]*(Qz*f19); I[66] += C[0]*W[a]*(Qz*f7); I[67] += C[0]*W[a]*(Qy*f7); I[68] += C[0]*W[a]*(Qy*f9); I[69] += C[0]*W[a]*(f13*f14); I[70] += C[0]*W[a]*(f13*f34); I[71] += C[0]*W[a]*(f24*f34); I[72] += C[0]*W[a]*(f24*f28); I[73] += C[0]*W[a]*(f23*f28); I[74] += C[0]*W[a]*(f14*f23); I[75] += C[0]*W[a]*(Ix*f18); I[76] += C[0]*W[a]*(Ix*f2); I[77] += C[0]*W[a]*(Iz*f2); I[78] += C[0]*W[a]*(Iz*f4); I[79] += C[0]*W[a]*(Iy*f4); I[80] += C[0]*W[a]*(Iy*f18); } #undef B00 #undef B10 #undef B01 #undef Cx #undef Cy #undef Cz #undef Dx #undef Dy #undef Dz #undef pow } static inline void reorder(double (&I)[81]) { double T[81]; for (int i = 0; i < 81; ++i) { T[i] = I[i]; } I[0] = T[0]; I[40] = T[1]; I[80] = T[2]; I[78] = T[3]; I[79] = T[4]; I[71] = T[5]; I[62] = T[6]; I[2] = T[7]; I[1] = T[8]; I[15] = T[9]; I[21] = T[10]; I[12] = T[11]; I[24] = T[12]; I[55] = T[13]; I[29] = T[14]; I[28] = T[15]; I[56] = T[16]; I[65] = T[17]; I[38] = T[18]; I[42] = T[19]; I[34] = T[20]; I[35] = T[21]; I[45] = T[22]; I[46] = T[23]; I[47] = T[24]; I[25] = T[25]; I[22] = T[26]; I[48] = T[27]; I[51] = T[28]; I[33] = T[29]; I[57] = T[30]; I[58] = T[31]; I[61] = T[32]; I[19] = T[33]; I[11] = T[34]; I[63] = T[35]; I[64] = T[36]; I[66] = T[37]; I[69] = T[38]; I[17] = T[39]; I[23] = T[40]; I[59] = T[41]; I[68] = T[42]; I[14] = T[43]; I[16] = T[44]; I[7] = T[45]; I[73] = T[46]; I[75] = T[47]; I[5] = T[48]; I[32] = T[49]; I[31] = T[50]; I[39] = T[51]; I[41] = T[52]; I[9] = T[53]; I[18] = T[54]; I[49] = T[55]; I[52] = T[56]; I[13] = T[57]; I[26] = T[58]; I[53] = T[59]; I[27] = T[60]; I[54] = T[61]; I[67] = T[62]; I[60] = T[63]; I[30] = T[64]; I[50] = T[65]; I[20] = T[66]; I[10] = T[67]; I[70] = T[68]; I[4] = T[69]; I[8] = T[70]; I[44] = T[71]; I[36] = T[72]; I[72] = T[73]; I[76] = T[74]; I[74] = T[75]; I[37] = T[76]; I[43] = T[77]; I[6] = T[78]; I[3] = T[79]; I[77] = T[80]; } }; template<> struct impl > { typedef void enable; static const bool value = true; static inline void eval(double A, double B, const Vector<3> &rAi, const Vector<3> &rBk, const Vector<3> &rAB, const Vector<3> &rij, const Vector<3> &rkl, const Vector<3> &t2, const Vector<3> &W, const double (&C)[1], double (&I)[108]) { #define pow(x,y) util::pow<(y)>::eval((x)) const int N = 3; double xij = rij[0]; double yij = rij[1]; double zij = rij[2]; // // double vB00[N] __attribute__ ((aligned(16))); // // // double vB10[N] __attribute__ ((aligned(16))); // // // double vB01[N] __attribute__ ((aligned(16))); // // // double vCx[N] __attribute__ ((aligned(16))); // double vCy[N] __attribute__ ((aligned(16))); // double vCz[N] __attribute__ ((aligned(16))); // // // double vDx[N] __attribute__ ((aligned(16))); // double vDy[N] __attribute__ ((aligned(16))); // double vDz[N] __attribute__ ((aligned(16))); // // for (int a = 0; a < N; ++a) { // // vB00[a] = 0.5*t2[a]; // // // vB10[a] = recurrence::coefficient(1.0/A, B, t2[a]); // // // vB01[a] = recurrence::coefficient(1.0/B, A, t2[a]); // // // vCx[a] = recurrence::coefficient<0>(rAi, B, rAB, t2[a]); // vCy[a] = recurrence::coefficient<1>(rAi, B, rAB, t2[a]); // vCz[a] = recurrence::coefficient<2>(rAi, B, rAB, t2[a]); // // // vDx[a] = recurrence::coefficient<0>(rBk, -A, rAB, t2[a]); // vDy[a] = recurrence::coefficient<1>(rBk, -A, rAB, t2[a]); // vDz[a] = recurrence::coefficient<2>(rBk, -A, rAB, t2[a]); // // } // #define B00 vB00[a] // #define B10 vB10[a] // #define B01 vB01[a] // #define Cx vCx[a] // #define Cy vCy[a] // #define Cz vCz[a] // #define Dx vDx[a] // #define Dy vDy[a] // #define Dz vDz[a] #if defined (__INTEL_COMPILER) #pragma ivdep #pragma vector aligned #endif for (int a = 0; a < N; ++a) { double B00 = 0.5*t2[a]; double B10 = recurrence::coefficient(1.0/A, B, t2[a]); double B01 = recurrence::coefficient(1.0/B, A, t2[a]); double Cx = recurrence::coefficient<0>(rAi, B, rAB, t2[a]); double Cy = recurrence::coefficient<1>(rAi, B, rAB, t2[a]); double Cz = recurrence::coefficient<2>(rAi, B, rAB, t2[a]); double Dx = recurrence::coefficient<0>(rBk, -A, rAB, t2[a]); double Dy = recurrence::coefficient<1>(rBk, -A, rAB, t2[a]); double Dz = recurrence::coefficient<2>(rBk, -A, rAB, t2[a]); double Ix = (Cx + xij); double Iy = (Cy + yij); double Iz = (Cz + zij); double Px = (B10 + pow(Cx,2)); double Py = (B10 + pow(Cy,2)); double Pz = (B10 + pow(Cz,2)); double Qx = (Cx*Dx + B00); double Qy = (Cy*Dy + B00); double Qz = (Cz*Dz + B00); double Rx = (B01 + pow(Dx,2)); double Ry = (B01 + pow(Dy,2)); double Rz = (pow(Dz,2) + B01); double f0 = (Iz*Rz + 2*B00*Dz); double f1 = (Dz*(Iz*pow(Cz,2) + B10*(3*Cz + zij)) + 3*B00*Pz + 2*B00*Cz*zij); double f12 = (Dx*(Cx*Ix + B10) + B00*(xij + 2*Cx)); double f15 = (Cy*Iy + B10); double f16 = (B10*(3*Cx + xij) + Ix*pow(Cx,2)); double f17 = (2*B00*Dx + Cx*Rx); double f2 = (4*B00*Cy*Dy + Py*Ry + 2*pow(B00,2)); double f20 = (2*B00*Dx*(xij + 2*Cx) + Rx*(Cx*Ix + B10) + 2*pow(B00,2)); double f22 = (Px*Rx + 2*pow(B00,2) + 4*B00*Cx*Dx); double f24 = (2*B00*Cy*yij + 3*B00*Py + Dy*(B10*(3*Cy + yij) + Iy*pow(Cy,2))); double f26 = (Dy*Iy + B00); double f29 = (Dx*Px + 2*B00*Cx); double f3 = (Dy*Py + 2*B00*Cy); double f30 = (2*B00*Dy + Iy*Ry); double f31 = (Iz*pow(Cz,2) + B10*(3*Cz + zij)); double f32 = (Dx*(B10*(3*Cx + xij) + Ix*pow(Cx,2)) + 2*B00*Cx*xij + 3*B00*Px); double f33 = (2*B00*Dy + Cy*Ry); double f39 = (Rz*(B10 + Cz*Iz) + 2*B00*Dz*(2*Cz + zij) + 2*pow(B00,2)); double f40 = (2*pow(B00,2) + Pz*Rz + 4*B00*Cz*Dz); double f5 = (2*B00*Dz + Cz*Rz); double f6 = (B10*(3*Cy + yij) + Iy*pow(Cy,2)); double f9 = (Dz*Pz + 2*B00*Cz); I[0] += C[0]*W[a]*(Cy*Dx*(f9 + Qz*zij)); I[1] += C[0]*W[a]*((6*B00*Dz*Pz + 2*pow(B00,2)*(3*Cz + zij) + 4*B00*Cz*Dz*zij + Rz*(Iz*pow(Cz,2) + B10*(3*Cz + zij)))); I[2] += C[0]*W[a]*(Qx*(f9 + Qz*zij)); I[3] += C[0]*W[a]*(Qy*(f9 + Qz*zij)); I[4] += C[0]*W[a]*(Cx*Dy*(f9 + Qz*zij)); I[5] += C[0]*W[a]*(Cx*Dz*(Qy*yij + f3)); I[6] += C[0]*W[a]*(Qz*(Qy*yij + f3)); I[7] += C[0]*W[a]*(Qx*(Qy*yij + f3)); I[8] += C[0]*W[a]*(Cz*Dx*(Qy*yij + f3)); I[9] += C[0]*W[a]*(Cz*(yij*(2*B00*Dy + Cy*Ry) + f2)); I[10] += C[0]*W[a]*(Cx*(yij*(2*B00*Dy + Cy*Ry) + f2)); I[11] += C[0]*W[a]*((4*B00*Cy*Dy*yij + 2*pow(B00,2)*(3*Cy + yij) + Ry*(B10*(3*Cy + yij) + Iy*pow(Cy,2)) + 6*B00*Dy*Py)); I[12] += C[0]*W[a]*((6*B00*Dx*Px + Rx*(B10*(3*Cx + xij) + Ix*pow(Cx,2)) + 4*B00*Cx*Dx*xij + 2*pow(B00,2)*(3*Cx + xij))); I[13] += C[0]*W[a]*(Dy*Pz*(Dx*xij + Qx)); I[14] += C[0]*W[a]*(Dx*Qy*(Cz*zij + Pz)); I[15] += C[0]*W[a]*(Cz*Qy*(Dx*xij + Qx)); I[16] += C[0]*W[a]*(Cy*Cz*(f17 + Rx*xij)); I[17] += C[0]*W[a]*(Pz*(f17 + Rx*xij)); I[18] += C[0]*W[a]*(Py*(f17 + Rx*xij)); I[19] += C[0]*W[a]*(Dz*Py*(Dx*xij + Qx)); I[20] += C[0]*W[a]*(Dx*Py*(Dz*zij + Qz)); I[21] += C[0]*W[a]*(Cy*Qx*(Dz*zij + Qz)); I[22] += C[0]*W[a]*(Cy*Qz*(Dx*xij + Qx)); I[23] += C[0]*W[a]*(Cy*Rz*(Px + Cx*xij)); I[24] += C[0]*W[a]*(Dz*Qy*(Px + Cx*xij)); I[25] += C[0]*W[a]*(Dy*Qz*(Px + Cx*xij)); I[26] += C[0]*W[a]*(Dy*Px*(Dz*zij + Qz)); I[27] += C[0]*W[a]*(Cx*Qy*(Dz*zij + Qz)); I[28] += C[0]*W[a]*(f3*(Dz*zij + Qz)); I[29] += C[0]*W[a]*(f29*(Dz*zij + Qz)); I[30] += C[0]*W[a]*(Dz*Iy*f29); I[31] += C[0]*W[a]*(Dx*Dz*f6); I[32] += C[0]*W[a]*(Dz*Qx*f15); I[33] += C[0]*W[a]*(Iy*Qx*Qz); I[34] += C[0]*W[a]*(Dx*Qz*f15); I[35] += C[0]*W[a]*(Cx*Cy*f0); I[36] += C[0]*W[a]*(Cy*Dz*f12); I[37] += C[0]*W[a]*(Dy*Dz*f16); I[38] += C[0]*W[a]*(Dz*Ix*f3); I[39] += C[0]*W[a]*(Dy*Ix*f9); I[40] += C[0]*W[a]*(Ix*Qy*Qz); I[41] += C[0]*W[a]*(Iz*Qx*Qy); I[42] += C[0]*W[a]*(Dy*Iz*f29); I[43] += C[0]*W[a]*(Dx*Dy*f31); I[44] += C[0]*W[a]*(Dx*Iy*f9); I[45] += C[0]*W[a]*(f9*(Dx*xij + Qx)); I[46] += C[0]*W[a]*(f3*(Dx*xij + Qx)); I[47] += C[0]*W[a]*(Dx*Iz*f3); I[48] += C[0]*W[a]*(Dx*Pz*f26); I[49] += C[0]*W[a]*(Cz*Qx*f26); I[50] += C[0]*W[a]*(Cz*Dy*f12); I[51] += C[0]*W[a]*(Dy*Qx*(Cz*zij + Pz)); I[52] += C[0]*W[a]*(Cy*Rx*(Cz*zij + Pz)); I[53] += C[0]*W[a]*(Cx*Ry*(Cz*zij + Pz)); I[54] += C[0]*W[a]*(Cz*Ry*(Px + Cx*xij)); I[55] += C[0]*W[a]*(f5*(Px + Cx*xij)); I[56] += C[0]*W[a]*(f33*(Px + Cx*xij)); I[57] += C[0]*W[a]*(Cx*Iz*f33); I[58] += C[0]*W[a]*(Cx*Cz*f30); I[59] += C[0]*W[a]*(Cx*Rz*f15); I[60] += C[0]*W[a]*(Iy*Px*Rz); I[61] += C[0]*W[a]*(Dz*Px*f26); I[62] += C[0]*W[a]*(Cx*Qz*f26); I[63] += C[0]*W[a]*(Cx*Iy*f5); I[64] += C[0]*W[a]*(Cy*Ix*f5); I[65] += C[0]*W[a]*(Ix*Py*Rz); I[66] += C[0]*W[a]*(Ix*Pz*Ry); I[67] += C[0]*W[a]*(Iz*Px*Ry); I[68] += C[0]*W[a]*(Iz*Py*Rx); I[69] += C[0]*W[a]*(Iy*Pz*Rx); I[70] += C[0]*W[a]*(Cz*Rx*f15); I[71] += C[0]*W[a]*(Cz*Ix*f33); I[72] += C[0]*W[a]*(f33*(Cz*zij + Pz)); I[73] += C[0]*W[a]*(f17*(Cz*zij + Pz)); I[74] += C[0]*W[a]*(Cz*Iy*f17); I[75] += C[0]*W[a]*(Cy*Iz*f17); I[76] += C[0]*W[a]*(Cy*f20); I[77] += C[0]*W[a]*(Cz*f20); I[78] += C[0]*W[a]*(Rx*f6); I[79] += C[0]*W[a]*(Rx*f31); I[80] += C[0]*W[a]*(Ry*f31); I[81] += C[0]*W[a]*(Ry*f16); I[82] += C[0]*W[a]*(Rz*f16); I[83] += C[0]*W[a]*(Rz*f6); I[84] += C[0]*W[a]*(Ix*f40); I[85] += C[0]*W[a]*(Ix*f2); I[86] += C[0]*W[a]*(Iz*f2); I[87] += C[0]*W[a]*(Iz*f22); I[88] += C[0]*W[a]*(Iy*f22); I[89] += C[0]*W[a]*(Iy*f40); I[90] += C[0]*W[a]*(f15*f17); I[91] += C[0]*W[a]*(f15*f5); I[92] += C[0]*W[a]*(Pz*f30); I[93] += C[0]*W[a]*(Px*f30); I[94] += C[0]*W[a]*(Px*f0); I[95] += C[0]*W[a]*(Py*f0); I[96] += C[0]*W[a]*(Cx*f39); I[97] += C[0]*W[a]*(Cy*f39); I[98] += C[0]*W[a]*(Qy*f12); I[99] += C[0]*W[a]*(Qz*f12); I[100] += C[0]*W[a]*(f26*f29); I[101] += C[0]*W[a]*(f26*f9); I[102] += C[0]*W[a]*(Dx*f1); I[103] += C[0]*W[a]*(Dx*f24); I[104] += C[0]*W[a]*(Dz*f24); I[105] += C[0]*W[a]*(Dz*f32); I[106] += C[0]*W[a]*(Dy*f32); I[107] += C[0]*W[a]*(Dy*f1); } #undef B00 #undef B10 #undef B01 #undef Cx #undef Cy #undef Cz #undef Dx #undef Dy #undef Dz #undef pow } static inline void reorder(double (&I)[108]) { double T[108]; for (int i = 0; i < 108; ++i) { T[i] = I[i]; } I[89] = T[0]; I[50] = T[1]; I[88] = T[2]; I[107] = T[3]; I[106] = T[4]; I[99] = T[5]; I[101] = T[6]; I[63] = T[7]; I[65] = T[8]; I[29] = T[9]; I[27] = T[10]; I[25] = T[11]; I[0] = T[12]; I[56] = T[13]; I[71] = T[14]; I[59] = T[15]; I[5] = T[16]; I[2] = T[17]; I[1] = T[18]; I[73] = T[19]; I[85] = T[20]; I[87] = T[21]; I[77] = T[22]; I[39] = T[23]; I[93] = T[24]; I[94] = T[25]; I[102] = T[26]; I[105] = T[27]; I[103] = T[28]; I[84] = T[29]; I[78] = T[30]; I[79] = T[31]; I[81] = T[32]; I[82] = T[33]; I[83] = T[34]; I[51] = T[35]; I[75] = T[36]; I[90] = T[37]; I[91] = T[38]; I[92] = T[39]; I[95] = T[40]; I[69] = T[41]; I[66] = T[42]; I[68] = T[43]; I[80] = T[44]; I[74] = T[45]; I[55] = T[46]; I[67] = T[47]; I[62] = T[48]; I[64] = T[49]; I[58] = T[50]; I[70] = T[51]; I[17] = T[52]; I[34] = T[53]; I[22] = T[54]; I[40] = T[55]; I[21] = T[56]; I[33] = T[57]; I[28] = T[58]; I[45] = T[59]; I[42] = T[60]; I[96] = T[61]; I[100] = T[62]; I[46] = T[63]; I[41] = T[64]; I[37] = T[65]; I[20] = T[66]; I[30] = T[67]; I[13] = T[68]; I[8] = T[69]; I[11] = T[70]; I[23] = T[71]; I[35] = T[72]; I[16] = T[73]; I[10] = T[74]; I[15] = T[75]; I[3] = T[76]; I[4] = T[77]; I[7] = T[78]; I[14] = T[79]; I[32] = T[80]; I[18] = T[81]; I[36] = T[82]; I[43] = T[83]; I[38] = T[84]; I[19] = T[85]; I[31] = T[86]; I[12] = T[87]; I[6] = T[88]; I[44] = T[89]; I[9] = T[90]; I[47] = T[91]; I[26] = T[92]; I[24] = T[93]; I[48] = T[94]; I[49] = T[95]; I[52] = T[96]; I[53] = T[97]; I[57] = T[98]; I[76] = T[99]; I[60] = T[100]; I[98] = T[101]; I[86] = T[102]; I[61] = T[103]; I[97] = T[104]; I[72] = T[105]; I[54] = T[106]; I[104] = T[107]; } }; template<> struct impl > { typedef void enable; static const bool value = true; static inline void eval(double A, double B, const Vector<3> &rAi, const Vector<3> &rBk, const Vector<3> &rAB, const Vector<3> &rij, const Vector<3> &rkl, const Vector<4> &t2, const Vector<4> &W, const double (&C)[1], double (&I)[100]) { #define pow(x,y) util::pow<(y)>::eval((x)) const int N = 4; // // double vB00[N] __attribute__ ((aligned(16))); // // // double vB10[N] __attribute__ ((aligned(16))); // // // double vB01[N] __attribute__ ((aligned(16))); // // // double vCx[N] __attribute__ ((aligned(16))); // double vCy[N] __attribute__ ((aligned(16))); // double vCz[N] __attribute__ ((aligned(16))); // // // double vDx[N] __attribute__ ((aligned(16))); // double vDy[N] __attribute__ ((aligned(16))); // double vDz[N] __attribute__ ((aligned(16))); // // for (int a = 0; a < N; ++a) { // // vB00[a] = 0.5*t2[a]; // // // vB10[a] = recurrence::coefficient(1.0/A, B, t2[a]); // // // vB01[a] = recurrence::coefficient(1.0/B, A, t2[a]); // // // vCx[a] = recurrence::coefficient<0>(rAi, B, rAB, t2[a]); // vCy[a] = recurrence::coefficient<1>(rAi, B, rAB, t2[a]); // vCz[a] = recurrence::coefficient<2>(rAi, B, rAB, t2[a]); // // // vDx[a] = recurrence::coefficient<0>(rBk, -A, rAB, t2[a]); // vDy[a] = recurrence::coefficient<1>(rBk, -A, rAB, t2[a]); // vDz[a] = recurrence::coefficient<2>(rBk, -A, rAB, t2[a]); // // } // #define B00 vB00[a] // #define B10 vB10[a] // #define B01 vB01[a] // #define Cx vCx[a] // #define Cy vCy[a] // #define Cz vCz[a] // #define Dx vDx[a] // #define Dy vDy[a] // #define Dz vDz[a] #if defined (__INTEL_COMPILER) #pragma ivdep #pragma vector aligned #endif for (int a = 0; a < N; ++a) { double B00 = 0.5*t2[a]; double B10 = recurrence::coefficient(1.0/A, B, t2[a]); double B01 = recurrence::coefficient(1.0/B, A, t2[a]); double Cx = recurrence::coefficient<0>(rAi, B, rAB, t2[a]); double Cy = recurrence::coefficient<1>(rAi, B, rAB, t2[a]); double Cz = recurrence::coefficient<2>(rAi, B, rAB, t2[a]); double Dx = recurrence::coefficient<0>(rBk, -A, rAB, t2[a]); double Dy = recurrence::coefficient<1>(rBk, -A, rAB, t2[a]); double Dz = recurrence::coefficient<2>(rBk, -A, rAB, t2[a]); double Px = (B10 + pow(Cx,2)); double Py = (B10 + pow(Cy,2)); double Pz = (B10 + pow(Cz,2)); double Qx = (Cx*Dx + B00); double Qy = (Cy*Dy + B00); double Qz = (Cz*Dz + B00); double Rx = (B01 + pow(Dx,2)); double Ry = (B01 + pow(Dy,2)); double Rz = (pow(Dz,2) + B01); double f0 = (4*B00*Cy*Dy + Py*Ry + 2*pow(B00,2)); double f1 = (3*B10 + pow(Cx,2)); double f11 = (2*B00*Dz + Cz*Rz); double f12 = (pow(Dz,2) + 3*B01); double f13 = (6*Cy*pow(B00,2) + Cy*Ry*(3*B10 + pow(Cy,2)) + 6*B00*Dy*Py); double f15 = (3*B01 + pow(Dy,2)); double f16 = 9*B00*B01*B10; double f19 = 6*pow(B00,3); double f2 = (6*Dz*pow(B00,2) + Dz*Pz*(pow(Dz,2) + 3*B01) + 6*B00*Cz*Rz); double f21 = (3*B01 + pow(Dx,2)); double f22 = (3*B00*Pz + Cz*Dz*(3*B10 + pow(Cz,2))); double f23 = (Dy*Py + 2*B00*Cy); double f25 = (2*B00*Dx + Cx*Rx); double f26 = (3*B00*Rx + Cx*Dx*(3*B01 + pow(Dx,2))); double f27 = (Dx*Px + 2*B00*Cx); double f28 = (Cy*Dy*(3*B01 + pow(Dy,2)) + 3*B00*Ry); double f29 = (6*Cx*pow(B00,2) + Cx*Rx*(3*B10 + pow(Cx,2)) + 6*B00*Dx*Px); double f3 = (Dz*Pz + 2*B00*Cz); double f32 = (Cx*Dx*(3*B10 + pow(Cx,2)) + 3*B00*Px); double f33 = (3*B10 + pow(Cz,2)); double f34 = (3*B10 + pow(Cy,2)); double f35 = (2*pow(B00,2) + Pz*Rz + 4*B00*Cz*Dz); double f36 = (6*B00*Dz*Pz + Cz*Rz*(3*B10 + pow(Cz,2)) + 6*Cz*pow(B00,2)); double f4 = (2*B00*Dy + Cy*Ry); double f5 = (Dx*Px*(3*B01 + pow(Dx,2)) + 6*Dx*pow(B00,2) + 6*B00*Cx*Rx); double f6 = (Px*Rx + 2*pow(B00,2) + 4*B00*Cx*Dx); double f7 = (6*B00*Cy*Ry + 6*Dy*pow(B00,2) + Dy*Py*(3*B01 + pow(Dy,2))); double f8 = (Cy*Dy*(3*B10 + pow(Cy,2)) + 3*B00*Py); double f9 = (Cz*Dz*(pow(Dz,2) + 3*B01) + 3*B00*Rz); I[0] += C[0]*W[a]*((f16 + f19 + Cy*Dy*f15*f34 + 9*B00*(B01*pow(Cy,2) + Py*pow(Dy,2)) + 18*Cy*Dy*pow(B00,2))); I[1] += C[0]*W[a]*((Cz*Dz*f12*f33 + f16 + f19 + 9*B00*(B01*pow(Cz,2) + Pz*pow(Dz,2)) + 18*Cz*Dz*pow(B00,2))); I[2] += C[0]*W[a]*((18*Cx*Dx*pow(B00,2) + f16 + f19 + Cx*Dx*f1*f21 + 9*B00*(B01*pow(Cx,2) + Px*pow(Dx,2)))); I[3] += C[0]*W[a]*(Cx*Ry*f3); I[4] += C[0]*W[a]*(Cx*Qz*f4); I[5] += C[0]*W[a]*(Cz*Qx*f4); I[6] += C[0]*W[a]*(Py*Qx*Rz); I[7] += C[0]*W[a]*(Cy*Rz*f27); I[8] += C[0]*W[a]*(Cy*Dx*Rz*f34); I[9] += C[0]*W[a]*(Cy*Dx*f35); I[10] += C[0]*W[a]*(Cy*Qx*f11); I[11] += C[0]*W[a]*(Pz*Qx*Ry); I[12] += C[0]*W[a]*(Cz*Dx*Ry*f33); I[13] += C[0]*W[a]*(Cz*Ry*f27); I[14] += C[0]*W[a]*(Px*Qz*Ry); I[15] += C[0]*W[a]*(Px*Qy*Rz); I[16] += C[0]*W[a]*(Cx*Qy*f11); I[17] += C[0]*W[a]*(Cx*Dy*f35); I[18] += C[0]*W[a]*(Dy*Dz*f32); I[19] += C[0]*W[a]*(Dx*Dz*f8); I[20] += C[0]*W[a]*(Dx*Dy*f22); I[21] += C[0]*W[a]*(Dx*Pz*f4); I[22] += C[0]*W[a]*(Cy*Dx*Pz*f21); I[23] += C[0]*W[a]*(Cy*Dx*f21*f34); I[24] += C[0]*W[a]*(Cy*Dz*Rx*f34); I[25] += C[0]*W[a]*(Cy*Rx*f3); I[26] += C[0]*W[a]*(Cy*Qz*f25); I[27] += C[0]*W[a]*(Cz*Qy*f25); I[28] += C[0]*W[a]*(Pz*Qy*Rx); I[29] += C[0]*W[a]*(Dz*Qy*f27); I[30] += C[0]*W[a]*(Dy*Qz*f27); I[31] += C[0]*W[a]*(Cz*Dy*Rx*f33); I[32] += C[0]*W[a]*(Cz*Rx*f23); I[33] += C[0]*W[a]*(Dz*Qx*f23); I[34] += C[0]*W[a]*(Dx*Qz*f23); I[35] += C[0]*W[a]*(Cx*Rz*f23); I[36] += C[0]*W[a]*(Cx*Dy*Rz*f1); I[37] += C[0]*W[a]*(Cx*Dy*f1*f15); I[38] += C[0]*W[a]*(Cx*Dy*Pz*f15); I[39] += C[0]*W[a]*(Dy*Pz*f25); I[40] += C[0]*W[a]*(Dy*Px*f11); I[41] += C[0]*W[a]*(Cz*Dy*Px*f15); I[42] += C[0]*W[a]*(Cz*Dy*f15*f33); I[43] += C[0]*W[a]*(Cz*Dy*f6); I[44] += C[0]*W[a]*(Dy*Qx*f3); I[45] += C[0]*W[a]*(Dx*Qy*f3); I[46] += C[0]*W[a]*(Qx*Qy*Qz); I[47] += C[0]*W[a]*(Py*Qz*Rx); I[48] += C[0]*W[a]*(Dx*Py*f11); I[49] += C[0]*W[a]*(Cz*Dx*Py*f21); I[50] += C[0]*W[a]*(Cz*Dx*f21*f33); I[51] += C[0]*W[a]*(Cz*Dx*f0); I[52] += C[0]*W[a]*(Cx*Dz*f0); I[53] += C[0]*W[a]*(Cx*Dz*Ry*f1); I[54] += C[0]*W[a]*(Cx*Dz*f1*f12); I[55] += C[0]*W[a]*(Cx*Dz*Py*f12); I[56] += C[0]*W[a]*(Dz*Py*f25); I[57] += C[0]*W[a]*(Dz*Px*f4); I[58] += C[0]*W[a]*(Cy*Dz*Px*f12); I[59] += C[0]*W[a]*(Cy*Dz*f12*f34); I[60] += C[0]*W[a]*(Cy*Dz*f6); I[61] += C[0]*W[a]*(Cx*Cy*f9); I[62] += C[0]*W[a]*(Cx*Cz*f28); I[63] += C[0]*W[a]*(Cy*Cz*f26); I[64] += C[0]*W[a]*(Py*f26); I[65] += C[0]*W[a]*(Pz*f26); I[66] += C[0]*W[a]*(Pz*f28); I[67] += C[0]*W[a]*(Px*f28); I[68] += C[0]*W[a]*(Px*f9); I[69] += C[0]*W[a]*(Py*f9); I[70] += C[0]*W[a]*(Cy*f5); I[71] += C[0]*W[a]*(Cz*f5); I[72] += C[0]*W[a]*(Cz*f7); I[73] += C[0]*W[a]*(Cx*f7); I[74] += C[0]*W[a]*(Cx*f2); I[75] += C[0]*W[a]*(Cy*f2); I[76] += C[0]*W[a]*(Rx*f8); I[77] += C[0]*W[a]*(Rx*f22); I[78] += C[0]*W[a]*(Ry*f22); I[79] += C[0]*W[a]*(Ry*f32); I[80] += C[0]*W[a]*(Rz*f32); I[81] += C[0]*W[a]*(Rz*f8); I[82] += C[0]*W[a]*(Dx*f36); I[83] += C[0]*W[a]*(Dx*f13); I[84] += C[0]*W[a]*(Dz*f13); I[85] += C[0]*W[a]*(Dz*f29); I[86] += C[0]*W[a]*(Dy*f29); I[87] += C[0]*W[a]*(Dy*f36); I[88] += C[0]*W[a]*(f11*f27); I[89] += C[0]*W[a]*(f27*f4); I[90] += C[0]*W[a]*(f3*f4); I[91] += C[0]*W[a]*(f25*f3); I[92] += C[0]*W[a]*(f23*f25); I[93] += C[0]*W[a]*(f11*f23); I[94] += C[0]*W[a]*(Qx*f35); I[95] += C[0]*W[a]*(Qx*f0); I[96] += C[0]*W[a]*(Qz*f0); I[97] += C[0]*W[a]*(Qz*f6); I[98] += C[0]*W[a]*(Qy*f6); I[99] += C[0]*W[a]*(Qy*f35); } #undef B00 #undef B10 #undef B01 #undef Cx #undef Cy #undef Cz #undef Dx #undef Dy #undef Dz #undef pow } static inline void reorder(double (&I)[100]) { double T[100]; for (int i = 0; i < 100; ++i) { T[i] = I[i]; } I[11] = T[0]; I[22] = T[1]; I[0] = T[2]; I[67] = T[3]; I[69] = T[4]; I[59] = T[5]; I[75] = T[6]; I[73] = T[7]; I[71] = T[8]; I[78] = T[9]; I[79] = T[10]; I[57] = T[11]; I[52] = T[12]; I[54] = T[13]; I[64] = T[14]; I[83] = T[15]; I[89] = T[16]; I[87] = T[17]; I[90] = T[18]; I[91] = T[19]; I[92] = T[20]; I[58] = T[21]; I[8] = T[22]; I[1] = T[23]; I[41] = T[24]; I[48] = T[25]; I[49] = T[26]; I[39] = T[27]; I[38] = T[28]; I[93] = T[29]; I[94] = T[30]; I[32] = T[31]; I[36] = T[32]; I[95] = T[33]; I[96] = T[34]; I[85] = T[35]; I[80] = T[36]; I[10] = T[37]; I[17] = T[38]; I[37] = T[39]; I[84] = T[40]; I[14] = T[41]; I[12] = T[42]; I[34] = T[43]; I[97] = T[44]; I[98] = T[45]; I[99] = T[46]; I[46] = T[47]; I[76] = T[48]; I[6] = T[49]; I[2] = T[50]; I[56] = T[51]; I[65] = T[52]; I[60] = T[53]; I[20] = T[54]; I[25] = T[55]; I[45] = T[56]; I[63] = T[57]; I[23] = T[58]; I[21] = T[59]; I[43] = T[60]; I[29] = T[61]; I[19] = T[62]; I[9] = T[63]; I[5] = T[64]; I[7] = T[65]; I[18] = T[66]; I[13] = T[67]; I[24] = T[68]; I[26] = T[69]; I[3] = T[70]; I[4] = T[71]; I[16] = T[72]; I[15] = T[73]; I[27] = T[74]; I[28] = T[75]; I[31] = T[76]; I[42] = T[77]; I[62] = T[78]; I[50] = T[79]; I[70] = T[80]; I[81] = T[81]; I[72] = T[82]; I[51] = T[83]; I[61] = T[84]; I[40] = T[85]; I[30] = T[86]; I[82] = T[87]; I[74] = T[88]; I[53] = T[89]; I[68] = T[90]; I[47] = T[91]; I[35] = T[92]; I[86] = T[93]; I[77] = T[94]; I[55] = T[95]; I[66] = T[96]; I[44] = T[97]; I[33] = T[98]; I[88] = T[99]; } }; template<> struct impl > { typedef void enable; static const bool value = true; static inline void eval(double A, double B, const Vector<3> &rAi, const Vector<3> &rBk, const Vector<3> &rAB, const Vector<3> &rij, const Vector<3> &rkl, const Vector<3> &t2, const Vector<3> &W, const double (&C)[2], double (&I)[108]) { #define pow(x,y) util::pow<(y)>::eval((x)) const int N = 3; double xij = rij[0]; double yij = rij[1]; double zij = rij[2]; double xkl = rkl[0]; double ykl = rkl[1]; double zkl = rkl[2]; // // double vB00[N] __attribute__ ((aligned(16))); // // // double vB10[N] __attribute__ ((aligned(16))); // // // double vB01[N] __attribute__ ((aligned(16))); // // // double vCx[N] __attribute__ ((aligned(16))); // double vCy[N] __attribute__ ((aligned(16))); // double vCz[N] __attribute__ ((aligned(16))); // // // double vDx[N] __attribute__ ((aligned(16))); // double vDy[N] __attribute__ ((aligned(16))); // double vDz[N] __attribute__ ((aligned(16))); // // for (int a = 0; a < N; ++a) { // // vB00[a] = 0.5*t2[a]; // // // vB10[a] = recurrence::coefficient(1.0/A, B, t2[a]); // // // vB01[a] = recurrence::coefficient(1.0/B, A, t2[a]); // // // vCx[a] = recurrence::coefficient<0>(rAi, B, rAB, t2[a]); // vCy[a] = recurrence::coefficient<1>(rAi, B, rAB, t2[a]); // vCz[a] = recurrence::coefficient<2>(rAi, B, rAB, t2[a]); // // // vDx[a] = recurrence::coefficient<0>(rBk, -A, rAB, t2[a]); // vDy[a] = recurrence::coefficient<1>(rBk, -A, rAB, t2[a]); // vDz[a] = recurrence::coefficient<2>(rBk, -A, rAB, t2[a]); // // } // #define B00 vB00[a] // #define B10 vB10[a] // #define B01 vB01[a] // #define Cx vCx[a] // #define Cy vCy[a] // #define Cz vCz[a] // #define Dx vDx[a] // #define Dy vDy[a] // #define Dz vDz[a] #if defined (__INTEL_COMPILER) #pragma ivdep #pragma vector aligned #endif for (int a = 0; a < N; ++a) { double B00 = 0.5*t2[a]; double B10 = recurrence::coefficient(1.0/A, B, t2[a]); double B01 = recurrence::coefficient(1.0/B, A, t2[a]); double Cx = recurrence::coefficient<0>(rAi, B, rAB, t2[a]); double Cy = recurrence::coefficient<1>(rAi, B, rAB, t2[a]); double Cz = recurrence::coefficient<2>(rAi, B, rAB, t2[a]); double Dx = recurrence::coefficient<0>(rBk, -A, rAB, t2[a]); double Dy = recurrence::coefficient<1>(rBk, -A, rAB, t2[a]); double Dz = recurrence::coefficient<2>(rBk, -A, rAB, t2[a]); double Ix = (Cx + xij); double Iy = (Cy + yij); double Iz = (Cz + zij); double Kx = (xkl + Dx); double Ky = (ykl + Dy); double Kz = (Dz + zkl); double Qx = (Cx*Dx + B00); double Qy = (Cy*Dy + B00); double Qz = (Cz*Dz + B00); double f1 = B01*B10; double f11 = (B00 + Iy*Ky); double f12 = (B00 + Cy*Ky); double f13 = (Dy*Iy + B00); double f14 = (Dz*(B10 + Cz*Iz) + B00*(2*Cz + zij)); double f15 = (Cx*Ix + B10); double f16 = (B00*(2*Dz + zkl) + Iz*(Dz*Kz + B01)); double f18 = (Kx*(Cx*Ix + B10) + B00*(xij + 2*Cx)); double f2 = (Dz*Kz + B01); double f20 = (Dx*(Cx*Ix + B10) + B00*(xij + 2*Cx)); double f21 = (B01 + Dx*Kx); double f22 = (Cy*Iy + B10); double f23 = (B00*(yij + 2*Cy) + Ky*(Cy*Iy + B10)); double f24 = (B00*(yij + 2*Cy) + Dy*(Cy*Iy + B10)); double f26 = (B01 + Dy*Ky); double f28 = (Cy*Dy*Ky + B01*Cy + B00*(ykl + 2*Dy)); double f29 = (B01*Cx + Cx*Dx*Kx + B00*(xkl + 2*Dx)); double f3 = (B00 + Cx*Kx); double f30 = (B01*Cz + B00*(2*Dz + zkl) + Cz*Dz*Kz); double f31 = 2*pow(B00,2); double f36 = (B10 + Cz*Iz); double f4 = (B00*(ykl + 2*Dy) + Iy*(B01 + Dy*Ky)); double f7 = (B00 + Dz*Iz); I[0] += C[1]*W[a]*((B00*(xij + 2*Cx)*(xkl + 2*Dx) + f31 + B01*Cx*Ix + f1 + Dx*Kx*(Cx*Ix + B10))); I[1] += C[1]*W[a]*((f31 + Dy*Ky*(Cy*Iy + B10) + B01*Cy*Iy + B00*(yij + 2*Cy)*(ykl + 2*Dy) + f1)); I[2] += C[1]*W[a]*((Dz*Kz*(B10 + Cz*Iz) + f31 + B00*(2*Cz + zij)*(2*Dz + zkl) + f1 + B01*Cz*Iz)); I[3] += C[1]*W[a]*(Dy*Ix*(Cz*zkl + Qz)); I[4] += C[1]*W[a]*(Dy*(f14 + zkl*(B10 + Cz*Iz))); I[5] += C[1]*W[a]*(Dx*(f14 + zkl*(B10 + Cz*Iz))); I[6] += C[1]*W[a]*(Cy*Dx*(Iz*zkl + f7)); I[7] += C[1]*W[a]*(Qx*(Iz*zkl + f7)); I[8] += C[1]*W[a]*(Cx*Dy*(Iz*zkl + f7)); I[9] += C[0]*W[a]*(Dy*(Iz*zkl + f7)); I[10] += C[1]*W[a]*(Qy*(Iz*zkl + f7)); I[11] += C[0]*W[a]*(Dx*(Iz*zkl + f7)); I[12] += C[1]*W[a]*(Cz*(f29 + xij*(B01 + Dx*Kx))); I[13] += C[0]*W[a]*((f29 + xij*(B01 + Dx*Kx))); I[14] += C[1]*W[a]*(Cy*(f29 + xij*(B01 + Dx*Kx))); I[15] += C[1]*W[a]*(Cy*Dz*(Kx*xij + f3)); I[16] += C[0]*W[a]*(Dz*(Kx*xij + f3)); I[17] += C[1]*W[a]*(Qy*(Kx*xij + f3)); I[18] += C[1]*W[a]*(Cz*Dy*(Kx*xij + f3)); I[19] += C[0]*W[a]*(Dy*(Kx*xij + f3)); I[20] += C[1]*W[a]*(Qz*(Kx*xij + f3)); I[21] += C[1]*W[a]*((Cz*zkl + Qz)*(Dx*xij + Qx)); I[22] += C[1]*W[a]*(Dx*Iy*(Cz*zkl + Qz)); I[23] += C[1]*W[a]*(f13*(Cz*zkl + Qz)); I[24] += C[1]*W[a]*(Cx*Dz*f11); I[25] += C[1]*W[a]*(Dx*Kz*f22); I[26] += C[1]*W[a]*(Ix*Kz*Qy); I[27] += C[1]*W[a]*(Cx*Kz*f13); I[28] += C[1]*W[a]*(Dy*Kz*f15); I[29] += C[0]*W[a]*(Dy*Ix*Kz); I[30] += C[1]*W[a]*(Cy*Ix*f2); I[31] += C[1]*W[a]*(Dz*Ix*f12); I[32] += C[1]*W[a]*(Dx*Iz*f12); I[33] += C[1]*W[a]*(Dx*Ky*f36); I[34] += C[1]*W[a]*(Dz*Ky*f15); I[35] += C[0]*W[a]*(Dz*Ix*Ky); I[36] += C[1]*W[a]*(Ix*Ky*Qz); I[37] += C[1]*W[a]*(Iy*Kx*Qz); I[38] += C[1]*W[a]*(Dz*Kx*f22); I[39] += C[1]*W[a]*(Dy*Kx*f36); I[40] += C[1]*W[a]*(Iz*Kx*Qy); I[41] += C[0]*W[a]*(Dy*Iz*Kx); I[42] += C[1]*W[a]*(Dy*Iz*f3); I[43] += C[1]*W[a]*(Dz*Iy*f3); I[44] += C[0]*W[a]*(Dz*Iy*Kx); I[45] += C[1]*W[a]*(Iy*Kz*Qx); I[46] += C[0]*W[a]*(Dx*Iy*Kz); I[47] += C[1]*W[a]*(Cy*Kz*(Dx*xij + Qx)); I[48] += C[0]*W[a]*(Kz*(Dx*xij + Qx)); I[49] += C[1]*W[a]*(f12*(Dx*xij + Qx)); I[50] += C[1]*W[a]*(Cz*Ky*(Dx*xij + Qx)); I[51] += C[0]*W[a]*(Ky*(Dx*xij + Qx)); I[52] += C[1]*W[a]*(Iz*Ky*Qx); I[53] += C[0]*W[a]*(Dx*Iz*Ky); I[54] += C[1]*W[a]*(Dx*f23); I[55] += C[1]*W[a]*(Ix*f28); I[56] += C[1]*W[a]*(Cx*Iz*f26); I[57] += C[0]*W[a]*(Iz*f26); I[58] += C[1]*W[a]*(Iz*f28); I[59] += C[1]*W[a]*(f21*f36); I[60] += C[1]*W[a]*(f26*f36); I[61] += C[1]*W[a]*(Dy*f18); I[62] += C[1]*W[a]*(Dz*f18); I[63] += C[1]*W[a]*(Dz*f23); I[64] += C[0]*W[a]*(Dz*f11); I[65] += C[1]*W[a]*(Qx*f11); I[66] += C[1]*W[a]*(Cz*Dx*f11); I[67] += C[0]*W[a]*(Dx*f11); I[68] += C[1]*W[a]*(Qz*f11); I[69] += C[1]*W[a]*(Kx*f24); I[70] += C[1]*W[a]*(Cy*Kx*f7); I[71] += C[0]*W[a]*(Kx*f7); I[72] += C[1]*W[a]*(Cx*Ky*f7); I[73] += C[0]*W[a]*(Ky*f7); I[74] += C[1]*W[a]*(f12*f7); I[75] += C[1]*W[a]*(f3*f7); I[76] += C[1]*W[a]*(f13*f3); I[77] += C[1]*W[a]*(Cz*Kx*f13); I[78] += C[0]*W[a]*(Kx*f13); I[79] += C[1]*W[a]*(Kx*f14); I[80] += C[1]*W[a]*(Ky*f14); I[81] += C[1]*W[a]*(Ky*f20); I[82] += C[1]*W[a]*(Kz*f20); I[83] += C[0]*W[a]*(Kz*f13); I[84] += C[1]*W[a]*(Kz*f24); I[85] += C[1]*W[a]*(f15*f2); I[86] += C[1]*W[a]*(f15*f26); I[87] += C[1]*W[a]*(Cz*Ix*f26); I[88] += C[0]*W[a]*(Ix*f26); I[89] += C[1]*W[a]*(Ix*f30); I[90] += C[0]*W[a]*(Ix*f2); I[91] += C[1]*W[a]*(Cx*Iy*f2); I[92] += C[0]*W[a]*(Iy*f2); I[93] += C[1]*W[a]*(f2*f22); I[94] += C[1]*W[a]*(f21*f22); I[95] += C[1]*W[a]*(Cy*Iz*f21); I[96] += C[0]*W[a]*(Iz*f21); I[97] += C[1]*W[a]*(Iz*f29); I[98] += C[1]*W[a]*(Iy*f29); I[99] += C[1]*W[a]*(Cz*Iy*f21); I[100] += C[0]*W[a]*(Iy*f21); I[101] += C[1]*W[a]*(Iy*f30); I[102] += C[1]*W[a]*(Cx*f16); I[103] += C[1]*W[a]*(Cy*f16); I[104] += C[1]*W[a]*(Cz*f4); I[105] += C[1]*W[a]*(Cx*f4); I[106] += C[0]*W[a]*(f4); I[107] += C[0]*W[a]*(f16); } #undef B00 #undef B10 #undef B01 #undef Cx #undef Cy #undef Cz #undef Dx #undef Dy #undef Dz #undef pow } static inline void reorder(double (&I)[108]) { double T[108]; for (int i = 0; i < 108; ++i) { T[i] = I[i]; } I[1] = T[0]; I[54] = T[1]; I[107] = T[2]; I[87] = T[3]; I[95] = T[4]; I[83] = T[5]; I[82] = T[6]; I[81] = T[7]; I[93] = T[8]; I[92] = T[9]; I[94] = T[10]; I[80] = T[11]; I[3] = T[12]; I[0] = T[13]; I[2] = T[14]; I[26] = T[15]; I[24] = T[16]; I[14] = T[17]; I[15] = T[18]; I[12] = T[19]; I[27] = T[20]; I[75] = T[21]; I[79] = T[22]; I[91] = T[23]; I[65] = T[24]; I[78] = T[25]; I[86] = T[26]; I[89] = T[27]; I[85] = T[28]; I[84] = T[29]; I[98] = T[30]; I[62] = T[31]; I[46] = T[32]; I[47] = T[33]; I[61] = T[34]; I[60] = T[35]; I[63] = T[36]; I[31] = T[37]; I[30] = T[38]; I[23] = T[39]; I[22] = T[40]; I[20] = T[41]; I[21] = T[42]; I[29] = T[43]; I[28] = T[44]; I[77] = T[45]; I[76] = T[46]; I[74] = T[47]; I[72] = T[48]; I[38] = T[49]; I[39] = T[50]; I[36] = T[51]; I[45] = T[52]; I[44] = T[53]; I[42] = T[54]; I[50] = T[55]; I[57] = T[56]; I[56] = T[57]; I[58] = T[58]; I[11] = T[59]; I[59] = T[60]; I[13] = T[61]; I[25] = T[62]; I[66] = T[63]; I[64] = T[64]; I[41] = T[65]; I[43] = T[66]; I[40] = T[67]; I[67] = T[68]; I[18] = T[69]; I[34] = T[70]; I[32] = T[71]; I[69] = T[72]; I[68] = T[73]; I[70] = T[74]; I[33] = T[75]; I[17] = T[76]; I[19] = T[77]; I[16] = T[78]; I[35] = T[79]; I[71] = T[80]; I[37] = T[81]; I[73] = T[82]; I[88] = T[83]; I[90] = T[84]; I[97] = T[85]; I[49] = T[86]; I[51] = T[87]; I[48] = T[88]; I[99] = T[89]; I[96] = T[90]; I[101] = T[91]; I[100] = T[92]; I[102] = T[93]; I[6] = T[94]; I[10] = T[95]; I[8] = T[96]; I[9] = T[97]; I[5] = T[98]; I[7] = T[99]; I[4] = T[100]; I[103] = T[101]; I[105] = T[102]; I[106] = T[103]; I[55] = T[104]; I[53] = T[105]; I[52] = T[106]; I[104] = T[107]; } }; template<> struct impl > { typedef void enable; static const bool value = true; static inline void eval(double A, double B, const Vector<3> &rAi, const Vector<3> &rBk, const Vector<3> &rAB, const Vector<3> &rij, const Vector<3> &rkl, const Vector<3> &t2, const Vector<3> &W, const double (&C)[1], double (&I)[36]) { #define pow(x,y) util::pow<(y)>::eval((x)) const int N = 3; double xij = rij[0]; double yij = rij[1]; double zij = rij[2]; // // // double vB10[N] __attribute__ ((aligned(16))); // // // // double vCx[N] __attribute__ ((aligned(16))); // double vCy[N] __attribute__ ((aligned(16))); // double vCz[N] __attribute__ ((aligned(16))); // // // for (int a = 0; a < N; ++a) { // // // vB10[a] = recurrence::coefficient(1.0/A, B, t2[a]); // // // // vCx[a] = recurrence::coefficient<0>(rAi, B, rAB, t2[a]); // vCy[a] = recurrence::coefficient<1>(rAi, B, rAB, t2[a]); // vCz[a] = recurrence::coefficient<2>(rAi, B, rAB, t2[a]); // // // } // #define B00 vB00[a] // #define B10 vB10[a] // #define B01 vB01[a] // #define Cx vCx[a] // #define Cy vCy[a] // #define Cz vCz[a] // #define Dx vDx[a] // #define Dy vDy[a] // #define Dz vDz[a] #if defined (__INTEL_COMPILER) #pragma ivdep #pragma vector aligned #endif for (int a = 0; a < N; ++a) { double B10 = recurrence::coefficient(1.0/A, B, t2[a]); double Cx = recurrence::coefficient<0>(rAi, B, rAB, t2[a]); double Cy = recurrence::coefficient<1>(rAi, B, rAB, t2[a]); double Cz = recurrence::coefficient<2>(rAi, B, rAB, t2[a]); double Ix = (Cx + xij); double Iy = (Cy + yij); double Iz = (Cz + zij); double Px = (B10 + pow(Cx,2)); double Py = (B10 + pow(Cy,2)); double Pz = (B10 + pow(Cz,2)); double f1 = (B10*(3*Cx + 2*xij) + Cx*pow(Ix,2)); double f10 = (B10 + pow(Iz,2)); double f11 = 3*pow(B10,2); double f15 = (Iz*pow(Cz,2) + B10*(3*Cz + zij)); double f3 = (B10*(3*Cy + yij) + Iy*pow(Cy,2)); double f6 = (B10*(3*Cz + 2*zij) + Cz*pow(Iz,2)); double f7 = (Cy*pow(Iy,2) + B10*(3*Cy + 2*yij)); double f8 = (B10*(3*Cx + xij) + Ix*pow(Cx,2)); double f9 = (B10 + pow(Iy,2)); I[0] += C[0]*W[a]*((Py + Cy*yij)*(Cz*zij + Pz)); I[1] += C[0]*W[a]*(Cz*Ix*(Py + Cy*yij)); I[2] += C[0]*W[a]*(Cx*Iz*(Py + Cy*yij)); I[3] += C[0]*W[a]*(Cy*Iz*(Px + Cx*xij)); I[4] += C[0]*W[a]*((Px + Cx*xij)*(Cz*zij + Pz)); I[5] += C[0]*W[a]*(Cx*Iy*(Cz*zij + Pz)); I[6] += C[0]*W[a]*(Cz*Iy*(Px + Cx*xij)); I[7] += C[0]*W[a]*(Cy*Cz*(xij*(xij + 2*Cx) + Px)); I[8] += C[0]*W[a]*((Px + Cx*xij)*(Py + Cy*yij)); I[9] += C[0]*W[a]*(Py*(xij*(xij + 2*Cx) + Px)); I[10] += C[0]*W[a]*(Pz*(xij*(xij + 2*Cx) + Px)); I[11] += C[0]*W[a]*((f11 + B10*(6*Cx*xij + pow(xij,2) + 6*pow(Cx,2)) + pow(Cx,2)*pow(Ix,2))); I[12] += C[0]*W[a]*((B10*(6*Cy*yij + pow(yij,2) + 6*pow(Cy,2)) + f11 + pow(Cy,2)*pow(Iy,2))); I[13] += C[0]*W[a]*((f11 + pow(Cz,2)*pow(Iz,2) + B10*(6*Cz*zij + pow(zij,2) + 6*pow(Cz,2)))); I[14] += C[0]*W[a]*(Cy*Ix*(Cz*zij + Pz)); I[15] += C[0]*W[a]*(Ix*Iy*Pz); I[16] += C[0]*W[a]*(Ix*Iz*Py); I[17] += C[0]*W[a]*(Iy*Iz*Px); I[18] += C[0]*W[a]*(Cx*Cy*f10); I[19] += C[0]*W[a]*(Cx*Cz*f9); I[20] += C[0]*W[a]*(Pz*f9); I[21] += C[0]*W[a]*(Px*f9); I[22] += C[0]*W[a]*(Px*f10); I[23] += C[0]*W[a]*(Py*f10); I[24] += C[0]*W[a]*(Cy*f1); I[25] += C[0]*W[a]*(Cz*f1); I[26] += C[0]*W[a]*(Cz*f7); I[27] += C[0]*W[a]*(Cx*f7); I[28] += C[0]*W[a]*(Cx*f6); I[29] += C[0]*W[a]*(Cy*f6); I[30] += C[0]*W[a]*(Ix*f15); I[31] += C[0]*W[a]*(Ix*f3); I[32] += C[0]*W[a]*(Iz*f3); I[33] += C[0]*W[a]*(Iz*f8); I[34] += C[0]*W[a]*(Iy*f8); I[35] += C[0]*W[a]*(Iy*f15); } #undef B00 #undef B10 #undef B01 #undef Cx #undef Cy #undef Cz #undef Dx #undef Dy #undef Dz #undef pow } static inline void reorder(double (&I)[36]) { double T[36]; for (int i = 0; i < 36; ++i) { T[i] = I[i]; } I[35] = T[0]; I[23] = T[1]; I[33] = T[2]; I[27] = T[3]; I[28] = T[4]; I[34] = T[5]; I[22] = T[6]; I[5] = T[7]; I[21] = T[8]; I[1] = T[9]; I[2] = T[10]; I[0] = T[11]; I[7] = T[12]; I[14] = T[13]; I[29] = T[14]; I[20] = T[15]; I[25] = T[16]; I[30] = T[17]; I[15] = T[18]; I[10] = T[19]; I[8] = T[20]; I[6] = T[21]; I[12] = T[22]; I[13] = T[23]; I[3] = T[24]; I[4] = T[25]; I[11] = T[26]; I[9] = T[27]; I[16] = T[28]; I[17] = T[29]; I[26] = T[30]; I[19] = T[31]; I[31] = T[32]; I[24] = T[33]; I[18] = T[34]; I[32] = T[35]; } }; template<> struct impl > { typedef void enable; static const bool value = true; static inline void eval(double A, double B, const Vector<3> &rAi, const Vector<3> &rBk, const Vector<3> &rAB, const Vector<3> &rij, const Vector<3> &rkl, const Vector<3> &t2, const Vector<3> &W, const double (&C)[2], double (&I)[120]) { #define pow(x,y) util::pow<(y)>::eval((x)) const int N = 3; double xij = rij[0]; double yij = rij[1]; double zij = rij[2]; // // double vB00[N] __attribute__ ((aligned(16))); // // // double vB10[N] __attribute__ ((aligned(16))); // // // // double vCx[N] __attribute__ ((aligned(16))); // double vCy[N] __attribute__ ((aligned(16))); // double vCz[N] __attribute__ ((aligned(16))); // // // double vDx[N] __attribute__ ((aligned(16))); // double vDy[N] __attribute__ ((aligned(16))); // double vDz[N] __attribute__ ((aligned(16))); // // for (int a = 0; a < N; ++a) { // // vB00[a] = 0.5*t2[a]; // // // vB10[a] = recurrence::coefficient(1.0/A, B, t2[a]); // // // // vCx[a] = recurrence::coefficient<0>(rAi, B, rAB, t2[a]); // vCy[a] = recurrence::coefficient<1>(rAi, B, rAB, t2[a]); // vCz[a] = recurrence::coefficient<2>(rAi, B, rAB, t2[a]); // // // vDx[a] = recurrence::coefficient<0>(rBk, -A, rAB, t2[a]); // vDy[a] = recurrence::coefficient<1>(rBk, -A, rAB, t2[a]); // vDz[a] = recurrence::coefficient<2>(rBk, -A, rAB, t2[a]); // // } // #define B00 vB00[a] // #define B10 vB10[a] // #define B01 vB01[a] // #define Cx vCx[a] // #define Cy vCy[a] // #define Cz vCz[a] // #define Dx vDx[a] // #define Dy vDy[a] // #define Dz vDz[a] #if defined (__INTEL_COMPILER) #pragma ivdep #pragma vector aligned #endif for (int a = 0; a < N; ++a) { double B00 = 0.5*t2[a]; double B10 = recurrence::coefficient(1.0/A, B, t2[a]); double Cx = recurrence::coefficient<0>(rAi, B, rAB, t2[a]); double Cy = recurrence::coefficient<1>(rAi, B, rAB, t2[a]); double Cz = recurrence::coefficient<2>(rAi, B, rAB, t2[a]); double Dx = recurrence::coefficient<0>(rBk, -A, rAB, t2[a]); double Dy = recurrence::coefficient<1>(rBk, -A, rAB, t2[a]); double Dz = recurrence::coefficient<2>(rBk, -A, rAB, t2[a]); double Ix = (Cx + xij); double Iy = (Cy + yij); double Iz = (Cz + zij); double Px = (B10 + pow(Cx,2)); double Py = (B10 + pow(Cy,2)); double Pz = (B10 + pow(Cz,2)); double Qx = (Cx*Dx + B00); double Qy = (Cy*Dy + B00); double Qz = (Cz*Dz + B00); double f0 = (3*B10 + pow(Cx,2)); double f10 = (3*B00*Pz + Cz*Dz*(3*B10 + pow(Cz,2))); double f15 = (Dy*Iy + B00); double f16 = (3*pow(B10,2) + 3*B10*Cz*(2*Cz + zij) + Iz*pow(Cz,3)); double f17 = (Cy*Iy + B10); double f18 = (3*pow(B10,2) + Iy*pow(Cy,3) + 3*B10*Cy*(yij + 2*Cy)); double f19 = (B10*(3*Cx + xij) + Ix*pow(Cx,2)); double f2 = (Dz*Pz + 2*B00*Cz); double f21 = (Dx*(B10*(3*Cx + xij) + Ix*pow(Cx,2)) + 2*B00*Cx*xij + 3*B00*Px); double f24 = 3*pow(B10,2); double f28 = (Cx*Dx*(3*B10 + pow(Cx,2)) + 3*B00*Px); double f3 = (Dz*(Iz*pow(Cz,2) + B10*(3*Cz + zij)) + 3*B00*Pz + 2*B00*Cz*zij); double f32 = (3*B10 + pow(Cz,2)); double f33 = (3*B10 + pow(Cy,2)); double f34 = (Iz*pow(Cz,2) + B10*(3*Cz + zij)); double f4 = (B00*(yij + 2*Cy) + Dy*(Cy*Iy + B10)); double f5 = (Dx*Px + 2*B00*Cx); double f6 = (B00 + Dz*Iz); double f7 = (Cy*Dy*(3*B10 + pow(Cy,2)) + 3*B00*Py); double f8 = (Dy*Py + 2*B00*Cy); double f9 = (B10*(3*Cy + yij) + Iy*pow(Cy,2)); I[0] += C[1]*W[a]*(Cx*Cy*(f2 + Qz*zij)); I[1] += C[1]*W[a]*(Cz*(f7 + yij*(Dy*Py + 2*B00*Cy))); I[2] += C[1]*W[a]*(Cx*(f7 + yij*(Dy*Py + 2*B00*Cy))); I[3] += C[1]*W[a]*((Dy*(f24 + Iy*pow(Cy,3) + 3*B10*Cy*(yij + 2*Cy)) + 3*B00*Py*yij + 4*B00*Cy*f33)); I[4] += C[1]*W[a]*((Dz*(f24 + 3*B10*Cz*(2*Cz + zij) + Iz*pow(Cz,3)) + 3*B00*Pz*zij + 4*B00*Cz*f32)); I[5] += C[1]*W[a]*(Px*(f2 + Qz*zij)); I[6] += C[1]*W[a]*(Py*(f2 + Qz*zij)); I[7] += C[1]*W[a]*(Cz*f32*(Dx*xij + Qx)); I[8] += C[1]*W[a]*(Cz*Py*(Dx*xij + Qx)); I[9] += C[1]*W[a]*(Cy*f33*(Dx*xij + Qx)); I[10] += C[1]*W[a]*(Cy*Pz*(Dx*xij + Qx)); I[11] += C[1]*W[a]*(Cy*Qx*(Cz*zij + Pz)); I[12] += C[0]*W[a]*(Cx*Cy*(Cz*zij + Pz)); I[13] += C[1]*W[a]*(Cx*Qy*(Cz*zij + Pz)); I[14] += C[1]*W[a]*(Cz*Qy*(Px + Cx*xij)); I[15] += C[1]*W[a]*(Cy*Qz*(Px + Cx*xij)); I[16] += C[0]*W[a]*(Cy*Cz*(Px + Cx*xij)); I[17] += C[1]*W[a]*(Cy*Cz*(Qx*xij + f5)); I[18] += C[1]*W[a]*(Pz*(Qx*xij + f5)); I[19] += C[1]*W[a]*(Py*(Qx*xij + f5)); I[20] += C[1]*W[a]*((Dx*(f24 + 3*B10*Cx*(xij + 2*Cx) + Ix*pow(Cx,3)) + 3*B00*Px*xij + 4*B00*Cx*f0)); I[21] += C[1]*W[a]*(Dz*(f24 + 3*B10*Cx*(xij + 2*Cx) + Ix*pow(Cx,3))); I[22] += C[1]*W[a]*(Dy*(f24 + 3*B10*Cx*(xij + 2*Cx) + Ix*pow(Cx,3))); I[23] += C[0]*W[a]*((f24 + 3*B10*Cx*(xij + 2*Cx) + Ix*pow(Cx,3))); I[24] += C[1]*W[a]*(Cy*Ix*f2); I[25] += C[1]*W[a]*(Ix*Py*Qz); I[26] += C[1]*W[a]*(Cx*Qz*f17); I[27] += C[1]*W[a]*(Iy*Px*Qz); I[28] += C[1]*W[a]*(Iz*Px*Qy); I[29] += C[1]*W[a]*(Iz*Py*Qx); I[30] += C[1]*W[a]*(Cy*Iz*f5); I[31] += C[1]*W[a]*(Cy*f33*f6); I[32] += C[1]*W[a]*(Cy*Px*f6); I[33] += C[0]*W[a]*(Cy*Iz*Px); I[34] += C[1]*W[a]*(Cy*Dx*Iz*f33); I[35] += C[0]*W[a]*(Cy*Iz*f33); I[36] += C[1]*W[a]*(Cx*Iz*f8); I[37] += C[1]*W[a]*(Cx*Cz*f4); I[38] += C[1]*W[a]*(Cx*Iy*f2); I[39] += C[1]*W[a]*(f2*(Px + Cx*xij)); I[40] += C[1]*W[a]*(f8*(Px + Cx*xij)); I[41] += C[1]*W[a]*(Dz*Py*(Px + Cx*xij)); I[42] += C[0]*W[a]*(Py*(Px + Cx*xij)); I[43] += C[1]*W[a]*(Dy*Pz*(Px + Cx*xij)); I[44] += C[0]*W[a]*(Pz*(Px + Cx*xij)); I[45] += C[1]*W[a]*(Cx*Pz*f15); I[46] += C[1]*W[a]*(Cx*f0*f15); I[47] += C[1]*W[a]*(Cx*f0*f6); I[48] += C[1]*W[a]*(Cx*Py*f6); I[49] += C[0]*W[a]*(Cx*Iz*Py); I[50] += C[1]*W[a]*(Cx*Dy*Iz*f0); I[51] += C[0]*W[a]*(Cx*Iz*f0); I[52] += C[1]*W[a]*(Cx*Dz*Iy*f0); I[53] += C[0]*W[a]*(Cx*Iy*f0); I[54] += C[0]*W[a]*(Cx*Iy*Pz); I[55] += C[1]*W[a]*(Iy*Pz*Qx); I[56] += C[1]*W[a]*(Cz*Qx*f17); I[57] += C[0]*W[a]*(Cx*Cz*f17); I[58] += C[1]*W[a]*(Cz*f15*f32); I[59] += C[1]*W[a]*(Cz*Px*f15); I[60] += C[0]*W[a]*(Cz*Iy*Px); I[61] += C[1]*W[a]*(Cz*Dx*Iy*f32); I[62] += C[0]*W[a]*(Cz*Iy*f32); I[63] += C[1]*W[a]*(Cz*Iy*f5); I[64] += C[1]*W[a]*(f5*(Cz*zij + Pz)); I[65] += C[1]*W[a]*(Dx*Py*(Cz*zij + Pz)); I[66] += C[0]*W[a]*(Py*(Cz*zij + Pz)); I[67] += C[1]*W[a]*(Dy*Px*(Cz*zij + Pz)); I[68] += C[0]*W[a]*(Px*(Cz*zij + Pz)); I[69] += C[1]*W[a]*(f8*(Cz*zij + Pz)); I[70] += C[1]*W[a]*(Cz*Ix*f8); I[71] += C[0]*W[a]*(Cz*Ix*Py); I[72] += C[1]*W[a]*(Cz*Dy*Ix*f32); I[73] += C[0]*W[a]*(Cz*Ix*f32); I[74] += C[1]*W[a]*(Ix*Pz*Qy); I[75] += C[0]*W[a]*(Cy*Ix*Pz); I[76] += C[1]*W[a]*(Cy*Dz*Ix*f33); I[77] += C[0]*W[a]*(Cy*Ix*f33); I[78] += C[1]*W[a]*(Cy*f21); I[79] += C[1]*W[a]*(Cz*f21); I[80] += C[1]*W[a]*(Px*f4); I[81] += C[1]*W[a]*(Pz*f4); I[82] += C[1]*W[a]*(Dz*f18); I[83] += C[1]*W[a]*(Ix*f10); I[84] += C[1]*W[a]*(Ix*f7); I[85] += C[1]*W[a]*(Iz*f7); I[86] += C[1]*W[a]*(Iz*f28); I[87] += C[1]*W[a]*(Iy*f28); I[88] += C[1]*W[a]*(Iy*f10); I[89] += C[1]*W[a]*(f17*f5); I[90] += C[1]*W[a]*(Dx*Pz*f17); I[91] += C[0]*W[a]*(Pz*f17); I[92] += C[1]*W[a]*(Dz*Px*f17); I[93] += C[0]*W[a]*(Px*f17); I[94] += C[1]*W[a]*(f17*f2); I[95] += C[1]*W[a]*(Qy*f34); I[96] += C[1]*W[a]*(Qy*f19); I[97] += C[1]*W[a]*(Qz*f19); I[98] += C[1]*W[a]*(Qz*f9); I[99] += C[1]*W[a]*(Qx*f9); I[100] += C[1]*W[a]*(Qx*f34); I[101] += C[1]*W[a]*(Cx*Dy*f34); I[102] += C[0]*W[a]*(Cx*f34); I[103] += C[1]*W[a]*(Cy*Dx*f34); I[104] += C[0]*W[a]*(Cy*f34); I[105] += C[1]*W[a]*(Cy*Dz*f19); I[106] += C[0]*W[a]*(Cy*f19); I[107] += C[1]*W[a]*(Cz*Dy*f19); I[108] += C[0]*W[a]*(Cz*f19); I[109] += C[1]*W[a]*(Cz*Dx*f9); I[110] += C[0]*W[a]*(Cz*f9); I[111] += C[1]*W[a]*(Cx*Dz*f9); I[112] += C[0]*W[a]*(Cx*f9); I[113] += C[1]*W[a]*(Cx*f3); I[114] += C[1]*W[a]*(Cy*f3); I[115] += C[1]*W[a]*(Dy*f16); I[116] += C[1]*W[a]*(Dx*f16); I[117] += C[1]*W[a]*(Dx*f18); I[118] += C[0]*W[a]*(f18); I[119] += C[0]*W[a]*(f16); } #undef B00 #undef B10 #undef B01 #undef Cx #undef Cy #undef Cz #undef Dx #undef Dy #undef Dz #undef pow } static inline void reorder(double (&I)[120]) { double T[120]; for (int i = 0; i < 120; ++i) { T[i] = I[i]; } I[119] = T[0]; I[76] = T[1]; I[75] = T[2]; I[71] = T[3]; I[112] = T[4]; I[114] = T[5]; I[116] = T[6]; I[32] = T[7]; I[36] = T[8]; I[31] = T[9]; I[38] = T[10]; I[59] = T[11]; I[29] = T[12]; I[89] = T[13]; I[69] = T[14]; I[99] = T[15]; I[9] = T[16]; I[39] = T[17]; I[37] = T[18]; I[35] = T[19]; I[30] = T[20]; I[90] = T[21]; I[60] = T[22]; I[0] = T[23]; I[98] = T[24]; I[96] = T[25]; I[109] = T[26]; I[104] = T[27]; I[83] = T[28]; I[55] = T[29]; I[53] = T[30]; I[111] = T[31]; I[113] = T[32]; I[23] = T[33]; I[51] = T[34]; I[21] = T[35]; I[85] = T[36]; I[79] = T[37]; I[107] = T[38]; I[97] = T[39]; I[65] = T[40]; I[95] = T[41]; I[5] = T[42]; I[67] = T[43]; I[7] = T[44]; I[77] = T[45]; I[70] = T[46]; I[110] = T[47]; I[115] = T[48]; I[25] = T[49]; I[80] = T[50]; I[20] = T[51]; I[100] = T[52]; I[10] = T[53]; I[17] = T[54]; I[47] = T[55]; I[49] = T[56]; I[19] = T[57]; I[72] = T[58]; I[74] = T[59]; I[14] = T[60]; I[42] = T[61]; I[12] = T[62]; I[44] = T[63]; I[54] = T[64]; I[56] = T[65]; I[26] = T[66]; I[84] = T[67]; I[24] = T[68]; I[86] = T[69]; I[66] = T[70]; I[6] = T[71]; I[62] = T[72]; I[2] = T[73]; I[68] = T[74]; I[8] = T[75]; I[91] = T[76]; I[1] = T[77]; I[33] = T[78]; I[34] = T[79]; I[73] = T[80]; I[78] = T[81]; I[101] = T[82]; I[92] = T[83]; I[61] = T[84]; I[81] = T[85]; I[50] = T[86]; I[40] = T[87]; I[102] = T[88]; I[43] = T[89]; I[48] = T[90]; I[18] = T[91]; I[103] = T[92]; I[13] = T[93]; I[108] = T[94]; I[88] = T[95]; I[63] = T[96]; I[94] = T[97]; I[106] = T[98]; I[45] = T[99]; I[57] = T[100]; I[87] = T[101]; I[27] = T[102]; I[58] = T[103]; I[28] = T[104]; I[93] = T[105]; I[3] = T[106]; I[64] = T[107]; I[4] = T[108]; I[46] = T[109]; I[16] = T[110]; I[105] = T[111]; I[15] = T[112]; I[117] = T[113]; I[118] = T[114]; I[82] = T[115]; I[52] = T[116]; I[41] = T[117]; I[11] = T[118]; I[22] = T[119]; } }; template<> struct impl > { typedef void enable; static const bool value = true; static inline void eval(double A, double B, const Vector<3> &rAi, const Vector<3> &rBk, const Vector<3> &rAB, const Vector<3> &rij, const Vector<3> &rkl, const Vector<2> &t2, const Vector<2> &W, const double (&C)[2], double (&I)[36]) { #define pow(x,y) util::pow<(y)>::eval((x)) const int N = 2; double xij = rij[0]; double yij = rij[1]; double zij = rij[2]; // // double vB00[N] __attribute__ ((aligned(16))); // // // double vB10[N] __attribute__ ((aligned(16))); // // // // double vCx[N] __attribute__ ((aligned(16))); // double vCy[N] __attribute__ ((aligned(16))); // double vCz[N] __attribute__ ((aligned(16))); // // // double vDx[N] __attribute__ ((aligned(16))); // double vDy[N] __attribute__ ((aligned(16))); // double vDz[N] __attribute__ ((aligned(16))); // // for (int a = 0; a < N; ++a) { // // vB00[a] = 0.5*t2[a]; // // // vB10[a] = recurrence::coefficient(1.0/A, B, t2[a]); // // // // vCx[a] = recurrence::coefficient<0>(rAi, B, rAB, t2[a]); // vCy[a] = recurrence::coefficient<1>(rAi, B, rAB, t2[a]); // vCz[a] = recurrence::coefficient<2>(rAi, B, rAB, t2[a]); // // // vDx[a] = recurrence::coefficient<0>(rBk, -A, rAB, t2[a]); // vDy[a] = recurrence::coefficient<1>(rBk, -A, rAB, t2[a]); // vDz[a] = recurrence::coefficient<2>(rBk, -A, rAB, t2[a]); // // } // #define B00 vB00[a] // #define B10 vB10[a] // #define B01 vB01[a] // #define Cx vCx[a] // #define Cy vCy[a] // #define Cz vCz[a] // #define Dx vDx[a] // #define Dy vDy[a] // #define Dz vDz[a] #if defined (__INTEL_COMPILER) #pragma ivdep #pragma vector aligned #endif for (int a = 0; a < N; ++a) { double B00 = 0.5*t2[a]; double B10 = recurrence::coefficient(1.0/A, B, t2[a]); double Cx = recurrence::coefficient<0>(rAi, B, rAB, t2[a]); double Cy = recurrence::coefficient<1>(rAi, B, rAB, t2[a]); double Cz = recurrence::coefficient<2>(rAi, B, rAB, t2[a]); double Dx = recurrence::coefficient<0>(rBk, -A, rAB, t2[a]); double Dy = recurrence::coefficient<1>(rBk, -A, rAB, t2[a]); double Dz = recurrence::coefficient<2>(rBk, -A, rAB, t2[a]); double Ix = (Cx + xij); double Iy = (Cy + yij); double Iz = (Cz + zij); double Qx = (Cx*Dx + B00); double Qy = (Cy*Dy + B00); double Qz = (Cz*Dz + B00); double f1 = (B00 + Dz*Iz); double f11 = (B10 + Cz*Iz); double f12 = (Cy*Iy + B10); double f6 = (Cx*Ix + B10); I[0] += C[1]*W[a]*((B00*(yij + 2*Cy) + Dy*(Cy*Iy + B10))); I[1] += C[1]*W[a]*((Dz*(B10 + Cz*Iz) + B00*(2*Cz + zij))); I[2] += C[1]*W[a]*((Dx*(Cx*Ix + B10) + B00*(xij + 2*Cx))); I[3] += C[1]*W[a]*(Cy*(Dx*xij + Qx)); I[4] += C[1]*W[a]*(Cz*(Dx*xij + Qx)); I[5] += C[0]*W[a]*((Dx*xij + Qx)); I[6] += C[1]*W[a]*(Cz*(Dy*yij + Qy)); I[7] += C[1]*W[a]*(Cx*(Dy*yij + Qy)); I[8] += C[0]*W[a]*((Dy*yij + Qy)); I[9] += C[1]*W[a]*(Cy*Dz*Ix); I[10] += C[1]*W[a]*(Ix*Qy); I[11] += C[1]*W[a]*(Cx*Dy*Iz); I[12] += C[0]*W[a]*(Dy*Iz); I[13] += C[1]*W[a]*(Iz*Qy); I[14] += C[1]*W[a]*(Dx*f11); I[15] += C[1]*W[a]*(Dy*f11); I[16] += C[1]*W[a]*(Dz*f6); I[17] += C[1]*W[a]*(Dy*f6); I[18] += C[1]*W[a]*(Cz*Dy*Ix); I[19] += C[0]*W[a]*(Dy*Ix); I[20] += C[1]*W[a]*(Ix*Qz); I[21] += C[0]*W[a]*(Dz*Ix); I[22] += C[1]*W[a]*(Cx*Dz*Iy); I[23] += C[0]*W[a]*(Dz*Iy); I[24] += C[1]*W[a]*(Dz*f12); I[25] += C[1]*W[a]*(Dx*f12); I[26] += C[1]*W[a]*(Cy*Dx*Iz); I[27] += C[0]*W[a]*(Dx*Iz); I[28] += C[1]*W[a]*(Iz*Qx); I[29] += C[1]*W[a]*(Iy*Qx); I[30] += C[1]*W[a]*(Cz*Dx*Iy); I[31] += C[0]*W[a]*(Dx*Iy); I[32] += C[1]*W[a]*(Iy*Qz); I[33] += C[1]*W[a]*(Cx*f1); I[34] += C[1]*W[a]*(Cy*f1); I[35] += C[0]*W[a]*(f1); } #undef B00 #undef B10 #undef B01 #undef Cx #undef Cy #undef Cz #undef Dx #undef Dy #undef Dz #undef pow } static inline void reorder(double (&I)[36]) { double T[36]; for (int i = 0; i < 36; ++i) { T[i] = I[i]; } I[18] = T[0]; I[35] = T[1]; I[1] = T[2]; I[2] = T[3]; I[3] = T[4]; I[0] = T[5]; I[19] = T[6]; I[17] = T[7]; I[16] = T[8]; I[26] = T[9]; I[14] = T[10]; I[21] = T[11]; I[20] = T[12]; I[22] = T[13]; I[11] = T[14]; I[23] = T[15]; I[25] = T[16]; I[13] = T[17]; I[15] = T[18]; I[12] = T[19]; I[27] = T[20]; I[24] = T[21]; I[29] = T[22]; I[28] = T[23]; I[30] = T[24]; I[6] = T[25]; I[10] = T[26]; I[8] = T[27]; I[9] = T[28]; I[5] = T[29]; I[7] = T[30]; I[4] = T[31]; I[31] = T[32]; I[33] = T[33]; I[34] = T[34]; I[32] = T[35]; } }; template<> struct impl > { typedef void enable; static const bool value = true; static inline void eval(double A, double B, const Vector<3> &rAi, const Vector<3> &rBk, const Vector<3> &rAB, const Vector<3> &rij, const Vector<3> &rkl, const Vector<2> &t2, const Vector<2> &W, const double (&C)[1], double (&I)[18]) { #define pow(x,y) util::pow<(y)>::eval((x)) const int N = 2; double xij = rij[0]; double yij = rij[1]; double zij = rij[2]; // // // double vB10[N] __attribute__ ((aligned(16))); // // // // double vCx[N] __attribute__ ((aligned(16))); // double vCy[N] __attribute__ ((aligned(16))); // double vCz[N] __attribute__ ((aligned(16))); // // // for (int a = 0; a < N; ++a) { // // // vB10[a] = recurrence::coefficient(1.0/A, B, t2[a]); // // // // vCx[a] = recurrence::coefficient<0>(rAi, B, rAB, t2[a]); // vCy[a] = recurrence::coefficient<1>(rAi, B, rAB, t2[a]); // vCz[a] = recurrence::coefficient<2>(rAi, B, rAB, t2[a]); // // // } // #define B00 vB00[a] // #define B10 vB10[a] // #define B01 vB01[a] // #define Cx vCx[a] // #define Cy vCy[a] // #define Cz vCz[a] // #define Dx vDx[a] // #define Dy vDy[a] // #define Dz vDz[a] #if defined (__INTEL_COMPILER) #pragma ivdep #pragma vector aligned #endif for (int a = 0; a < N; ++a) { double B10 = recurrence::coefficient(1.0/A, B, t2[a]); double Cx = recurrence::coefficient<0>(rAi, B, rAB, t2[a]); double Cy = recurrence::coefficient<1>(rAi, B, rAB, t2[a]); double Cz = recurrence::coefficient<2>(rAi, B, rAB, t2[a]); double Ix = (Cx + xij); double Iy = (Cy + yij); double Iz = (Cz + zij); double Px = (B10 + pow(Cx,2)); double Py = (B10 + pow(Cy,2)); double Pz = (B10 + pow(Cz,2)); double f2 = (B10 + Cz*Iz); I[0] += C[0]*W[a]*(Cx*(Py + Cy*yij)); I[1] += C[0]*W[a]*(Cz*(Py + Cy*yij)); I[2] += C[0]*W[a]*((B10*(3*Cy + yij) + Iy*pow(Cy,2))); I[3] += C[0]*W[a]*(Cx*Cz*Iy); I[4] += C[0]*W[a]*((Iz*pow(Cz,2) + B10*(3*Cz + zij))); I[5] += C[0]*W[a]*((B10*(3*Cx + xij) + Ix*pow(Cx,2))); I[6] += C[0]*W[a]*(Cz*(Px + Cx*xij)); I[7] += C[0]*W[a]*(Cy*(Px + Cx*xij)); I[8] += C[0]*W[a]*(Cx*Cy*Iz); I[9] += C[0]*W[a]*(Cy*Cz*Ix); I[10] += C[0]*W[a]*(Ix*Py); I[11] += C[0]*W[a]*(Ix*Pz); I[12] += C[0]*W[a]*(Iy*Pz); I[13] += C[0]*W[a]*(Iy*Px); I[14] += C[0]*W[a]*(Iz*Px); I[15] += C[0]*W[a]*(Iz*Py); I[16] += C[0]*W[a]*(Cx*f2); I[17] += C[0]*W[a]*(Cy*f2); } #undef B00 #undef B10 #undef B01 #undef Cx #undef Cy #undef Cz #undef Dx #undef Dy #undef Dz #undef pow } static inline void reorder(double (&I)[18]) { double T[18]; for (int i = 0; i < 18; ++i) { T[i] = I[i]; } I[9] = T[0]; I[11] = T[1]; I[7] = T[2]; I[10] = T[3]; I[14] = T[4]; I[0] = T[5]; I[4] = T[6]; I[3] = T[7]; I[15] = T[8]; I[5] = T[9]; I[1] = T[10]; I[2] = T[11]; I[8] = T[12]; I[6] = T[13]; I[12] = T[14]; I[13] = T[15]; I[16] = T[16]; I[17] = T[17]; } }; END_NAMESPACE(rysq, kernel, quadrature) #endif /* _RYSQ_KERNEL_QUADRATURE2_IMPL_HPP_ */ marcomanno/ploygon_triangulation #pragma once #include "subtype.hh" #include "Geo/entity.hh" #include "Geo/range.hh" #include #include namespace Topo { MAKE_ENUM(Type, VERTEX, EDGE, COEDGE, LOOP, FACE, SHELL, BODY) MAKE_ENUM(Direction, Up, Down ) typedef unsigned __int64 Identifier; struct Object { template friend class Wrap; void add_ref() const { ++ref_; } void release_ref() const { auto refs = --ref_; if (refs == 0) delete this; } virtual Type type() const = 0; virtual SubType sub_type() const = 0; virtual bool operator<(const Object& _oth) const; virtual bool operator==(const Object& _oth) const; virtual Identifier id() const { return id_; } protected: Object(); virtual ~Object(); private: static void* operator new(std::size_t sz) { return ::operator new(sz); } static void* operator new[](std::size_t sz) { return ::operator new(sz); } private: mutable size_t ref_; Identifier id_; }; class WrapObject { Object* ptr_ = nullptr; public: WrapObject() { } WrapObject(Object* _ptr) { reset(_ptr); } WrapObject(const WrapObject& _oth) { reset(_oth.ptr_); } ~WrapObject() { if (ptr_) ptr_->release_ref(); } WrapObject& operator=(const WrapObject& _oth) { reset(_oth.ptr_); return *this; } Object* operator->() { return get(); } const Object* operator->() const { return get(); } Object* get() { return ptr_; } const Object* get() const { return ptr_; } explicit operator bool() const { return ptr_ != nullptr; } void reset(Object* _ptr) { if (ptr_ != _ptr) { if (ptr_ != nullptr) ptr_->release_ref(); ptr_ = _ptr; if (ptr_ != nullptr) ptr_->add_ref(); } } bool operator<(const WrapObject& _oth) const { if (ptr_ == _oth.ptr_) return false; if (ptr_ != nullptr && _oth.ptr_ != nullptr) return *ptr_ < *_oth.ptr_; return ptr_ == nullptr; } bool operator==(const WrapObject& _oth) const { if (ptr_ == _oth.ptr_) return true; if (ptr_ != nullptr && _oth.ptr_ != nullptr) return *ptr_ == *_oth.ptr_; return false; } bool operator!=(const WrapObject& _oth) const { return !(*this == _oth); } }; struct IBase : public Object { template friend struct UpEntity; virtual bool replace(IBase*) { return false; } virtual bool remove() { return false; } virtual bool reverse() { return false; } virtual size_t size(Direction) const { return SIZE_MAX; } virtual IBase* get(Direction, size_t) const { return nullptr; } virtual size_t find_parent(const IBase*) const { return SIZE_MAX; } virtual size_t find_child(const IBase*, size_t _end = SIZE_MAX) const { _end; return SIZE_MAX; } virtual bool insert_child(IBase*, size_t _pos = SIZE_MAX) { _pos; return false; } virtual bool remove_child(size_t) { return false; } virtual bool remove_child(IBase*) { return false; } virtual bool replace_child(IBase* /*_elem*/, IBase* /*_new_elem*/) { return false; } virtual Geo::Point internal_point() const { return Geo::uniform_vector<3>(std::numeric_limits::max()); } virtual Geo::Range<3> box() const { return Geo::Range<3>(); } virtual double tolerance() const { return 0; } protected: virtual bool remove_parent(IBase* /*_prnt*/) { return false; } virtual bool add_parent(IBase* /*_prnt*/) { return false; } }; template struct EBase : public IBase { virtual Type type() const { return typeT; } }; template struct E : public EBase {}; template <> struct E : public EBase { virtual bool geom(Geo::Point&) const = 0; virtual bool set_geom(const Geo::Point&) = 0; virtual double tolerance() const = 0; virtual bool set_tolerance(const double _tol) = 0; }; template <> struct E : public EBase { virtual bool geom(Geo::Segment&) const = 0; virtual bool set_geom(const Geo::Segment&) = 0; virtual double tolerance() const = 0; virtual bool set_tolerance(const double _tol) = 0; }; template <> struct E : public EBase { virtual void optimize() {} virtual bool remove_children( std::vector&) { return false; } }; template <> struct E : public EBase { virtual bool geom(Geo::Segment&) const = 0; virtual bool set_geom(const Geo::Segment&) = 0; virtual double tolerance() const = 0; virtual bool set_tolerance(const double _tol) = 0; }; template class WrapIbase { public: WrapIbase() : ptr_(nullptr) { } WrapIbase(IBaseT* _ptr) : ptr_(nullptr) { reset(_ptr); } WrapIbase(const WrapIbase& _ew) : ptr_(_ew.ptr_) { if (ptr_ != nullptr) ptr_->add_ref(); } ~WrapIbase() { if (ptr_) ptr_->release_ref(); } WrapIbase& operator=(const WrapIbase& _oth) { reset(_oth.ptr_); return *this; } IBaseT* operator->() { return get(); } const IBaseT* operator->() const { return get(); } IBaseT* get() const { return ptr_; } explicit operator bool() const { return ptr_ != nullptr; } void reset(IBaseT* _ptr) { if (ptr_ != _ptr) { if (ptr_ != nullptr) ptr_->release_ref(); ptr_ = _ptr; if (ptr_ != nullptr) ptr_->add_ref(); } } bool operator<(const WrapIbase& _oth) const { if (ptr_ == _oth.ptr_) return false; if (ptr_ != nullptr && _oth.ptr_ != nullptr) return *ptr_ < *_oth.ptr_; return ptr_ == nullptr; } bool operator==(const WrapIbase& _oth) const { if (ptr_ == _oth.ptr_) return true; if (ptr_ != nullptr && _oth.ptr_ != nullptr) return *ptr_ == *_oth.ptr_; return false; } bool operator!=(const WrapIbase& _oth) const { return !(*this == _oth); } private: IBaseT* ptr_; }; template class Wrap : public WrapIbase> { public: using WrapIbase>::WrapIbase; template TopoTypeT* make() { auto ptr = new TopoTypeT; reset(ptr); return ptr; } }; typedef std::vector> VertexChain; typedef std::vector VertexChains; }//namespace Topo dariusarnold/xunit-plugin #include using namespace boost::unit_test; int add(int i, int j) { return i+j; } static void test1() { BOOST_CHECK_EQUAL(add(2, 2), 4); } static void test2() { BOOST_CHECK_EQUAL(add(2, 3), 4); } static void test3() { BOOST_FAIL("un test failed"); } static void test4() { BOOST_CHECK_EQUAL(add(2, 2), 4); } static void test5() { BOOST_CHECK_EQUAL(add(2, 3), 4); } static void test6() { BOOST_FAIL("un test failed"); } struct returnFalse{ assertion_result operator()(test_unit_id) { return assertion_result(false); } }; test_suite * init_unit_test_suite(int, char ** const) { test_suite* ts_root = BOOST_TEST_SUITE("root"); test_suite* ts1 = BOOST_TEST_SUITE("ts1"); ts1->add_precondition(returnFalse()); ts1->add(BOOST_TEST_CASE(&test1)); ts1->add(BOOST_TEST_CASE(&test2)); ts1->add(BOOST_TEST_CASE(&test3)); //framework::master_test_suite().add(ts); ts_root->add(ts1); test_suite* ts2 = BOOST_TEST_SUITE("ts2"); auto tc1 = BOOST_TEST_CASE(&test4); tc1->add_precondition(returnFalse()); ts2->add(tc1); auto tc2 = BOOST_TEST_CASE(&test5); tc2->add_precondition(returnFalse()); ts2->add(tc2); auto tc3 = BOOST_TEST_CASE(&test6); tc3->add_precondition(returnFalse()); ts2->add(tc3); //framework::master_test_suite().add(ts); ts_root->add(ts2); return ts_root; } zyiacas/boost-doc-zh // Boost.Range library // // Copyright 2010. Use, modification and // distribution is subject to the Boost Software License, Version // 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // // For more information, see http://www.boost.org/libs/range/ // #include #include #include #include #include #include #include #include namespace { template< class Container > void test_insert_impl( int n ) { Container test; boost::insert( test, test.end(), boost::irange(0, n) ); Container reference; for (int i = 0; i < n; ++i) reference.push_back(i); BOOST_CHECK_EQUAL_COLLECTIONS( reference.begin(), reference.end(), test.begin(), test.end() ); // Do it again so that we are inserting into a non-empty target boost::insert( test, test.end(), boost::irange(0, n) ); for (int j = 0; j < n; ++j) reference.push_back(j); BOOST_CHECK_EQUAL_COLLECTIONS( reference.begin(), reference.end(), test.begin(), test.end() ); } template< class Container > void test_insert_impl() { test_insert_impl< Container >(0); test_insert_impl< Container >(1); test_insert_impl< Container >(2); test_insert_impl< Container >(100); } void test_insert() { test_insert_impl< std::vector >(); test_insert_impl< std::list >(); } } boost::unit_test::test_suite* init_unit_test_suite(int argc, char* argv[]) { boost::unit_test::test_suite* test = BOOST_TEST_SUITE( "RangeTestSuite.algorithm_ext.insert" ); test->add( BOOST_TEST_CASE( &test_insert ) ); return test; } #include "../includes.h" Capturer::Capturer(void) {} Capturer::~Capturer(void) {} UI/io_editor.cpp0 #include "io_editor.h" #include "face_defaults.h" #include "face_util.h" #include "face_window.h" Io_Editor::Io_Editor(Face_Window *win, int x, int y, int w, int h) : Fl_Text_Editor(x, y, w, h), messages_window(win->get_messages_window()), state(IDLE) { buffer(buff); buff.append("Ввод/вывод\n"); insert_position(buff.length()); buff.add_modify_callback(modify_cb, this); } void Io_Editor::set_active() { io_block = 0; State_Holder sh(state); state = MODIFYING; activate(); show_cursor(); take_focus(); } void Io_Editor::bind_stream(FILE *new_stream) { stream = new_stream; } void Io_Editor::unbind_stream() { stream = NULL; io_block = buff.length(); } void Io_Editor::write(const std::string &str) { State_Holder sh(state); state = MODIFYING; buff.append(str.c_str()); insert_position(buff.length()); io_block = buff.length(); scroll(buff.count_lines(0, buff.length()), 0); Fl::check(); } void Io_Editor::write(char ch) { State_Holder sh(state); state = MODIFYING; const char str[] = {ch, '\0'}; buff.append(str); io_block = buff.length(); scroll(buff.count_lines(0, buff.length()), 0); Fl::check(); } void Io_Editor::write_file(const std::string &fname) { State_Holder sh(state); state = MODIFYING; if (buff.appendfile(fname.c_str())) { messages_window->put_message("running file err: "); messages_window->put_message(strerror(1)); messages_window->put_message("\n"); } insert_position(buff.length()); io_block = buff.length(); Fl::check(); } void Io_Editor::clear() { State_Holder sh(state); state = MODIFYING; buff.remove(0, std::string(buff.text()).size()); Fl::check(); } void Io_Editor::modify_cb(int pos, int nins, int ndel, int nrestyled, const char *c_del, void *io_editor_voided) { Io_Editor *io_editor = reinterpret_cast(io_editor_voided); // printf("mod nins = %i ndel = %i nres = %i state = %s\n", nins, ndel, // nrestyled, // io_editor->state == Io_Editor::MODIFYING ? "mod" : "norm"); if (io_editor->state == Io_Editor::MODIFYING) return; State_Holder sh(io_editor->state); io_editor->state = MODIFYING; /*char msg[256]; sprintf(msg, "io changed pos=%i nins=%i ndel=%i nres=%i\n", pos, nins, ndel, nrestyled); mess(msg); */ /*if (!running) { if (nins > 0) { from_modyfy_cb = true; buff.remove(pos, pos + nins); insert_position(pos); } if (ndel > 0) { from_modyfy_cb = true; buff.insert(pos, c_del); insert_position(pos + 2 * ndel); } return; }*/ if (nins > 0) { if (!io_editor->stream) { // printf("I should have removed that!\n"); io_editor->buff.remove(pos, pos + nins); return; } if (nins > 2) { io_editor->messages_window->put_message( "Копирование в окно ввода/вывода пока не поддерживается\n"); io_editor->buff.remove(pos, pos + nins); io_editor->insert_position(pos); return; } if ((pos < io_editor->io_block)) { io_editor->buff.remove(pos, pos + nins); io_editor->insert_position(pos); return; } char ch = io_editor->buff.char_at(pos); if (ch == '\n') { std::string added = io_editor->buff.text_range(io_editor->io_block, pos + 1); if (io_editor->stream) { fprintf(io_editor->stream, "%s\n", added.c_str()); fflush(io_editor->stream); } io_editor->io_block = pos + 1; } return; } if (nrestyled > 0) return; // This last part executes only if characters were deleted int last_endl_pos = 0; if (pos < io_editor->io_block) { if (pos != io_editor->buff.length()) { io_editor->insert_position(pos + ndel); io_editor->buff.insert(pos, c_del); } else { io_editor->buff.insert(pos, c_del); io_editor->insert_position(io_editor->buff.length()); } return; } int pos_endl = 0; std::string del(c_del); pos_endl = del.find_last_of('\n'); if (pos_endl != -1) io_editor->buff.insert(pos, del.substr(0, pos_endl + 1).c_str()); } /** * @file * @copyright defined in eos/LICENSE.txt */ void unpack_provided_keys( flat_set& keys, const char* pubkeys_data, size_t pubkeys_size ) { keys.clear(); if( pubkeys_size == 0 ) return; keys = fc::raw::unpack>( pubkeys_data, pubkeys_size ); } void unpack_provided_permissions( flat_set& permissions, const char* perms_data, size_t perms_size ) { permissions.clear(); if( perms_size == 0 ) return; permissions = fc::raw::unpack>( perms_data, perms_size ); } int32_t check_transaction_authorization( const char* trx_data, uint32_t trx_size, const char* pubkeys_data, uint32_t pubkeys_size, const char* perms_data, uint32_t perms_size ) { return false; } int32_t check_permission_authorization( uint64_t account, uint64_t permission, const char* pubkeys_data, uint32_t pubkeys_size, const char* perms_data, uint32_t perms_size, uint64_t delay_us ) { return false; } int64_t get_permission_last_used( uint64_t account, uint64_t permission ) { return 0; } int64_t get_account_creation_time( uint64_t account ) { return 0; } #include "PgSqlDatabase.h" #include #include #include #include "SqlBuilder/SqlBuilder.h" #include #include namespace PgSqlDatabase_Deleter { template > struct DisarmedDelete : private Deleter { void operator()(T *ptr) { if (_armed) Deleter::operator()(ptr); } bool _armed = false; }; } PgSqlDatabase::PgSqlDatabase(const std::string &connectionInfo, size_t connectionPoolSize) { // _connection = PQconnectdb(connectionInfo.c_str()); for (size_t i = 0; i < connectionPoolSize; ++i) { PGconn *new_connection = PQconnectdb(connectionInfo.c_str()); if (PQstatus(new_connection) != CONNECTION_OK) { LOG_ERROR << "Failed to connect to: " << connectionInfo; LOG_ERROR << "Error Message: " << PQerrorMessage(new_connection); } connections.add(std::make_shared(new_connection)); } this->self = std::shared_ptr(this, PgSqlDatabase_Deleter::DisarmedDelete()); _isConnected = true; } PgSqlDatabase::~PgSqlDatabase() { // if(this->self) { // auto deleter = get_deleter>(this->self); // } auto items = connections.releaseAll(); for (auto &item: items) { PQfinish(item->connection); } if (_isConnected) // PQfinish(_connection); _isConnected = false; } RsData PgSqlDatabase::query(const std::string &sql) { LOG_DEBUG << "Query: " << sql; // std::lock_guard query_lock(_queryMutex); auto connection = connections.get(); PGresult *res = PQexec(connection->object->connection, sql.c_str()); RsData data; if (isError(res, connection->object->connection)) return data; fillDataWithRes(data, res); PQclear(res); return data; } RsData PgSqlDatabase::query(const std::string &sql, const std::vector ¶ms) { // std::lock_guard query_lock(_queryMutex); LOG_DEBUG << "Query: " << sql; RsData data; const size_t paramsSize = params.size(); // const char *paramChars[paramsSize]; // int paramLengths[paramsSize]; // int paramFormats[paramsSize]; std::vector paramChars; std::vector paramLengths; std::vector paramFormats; for (size_t i = 0; i < paramsSize; ++i) { LOG_TRACE << "Parameter " << i << ": " << params.at(i); paramChars.push_back(params.at(i).c_str()); paramLengths.push_back(static_cast(params.at(i).size())); paramFormats.push_back(0); // Insert Text } auto connection = connections.get(); PGresult *res = PQexecParams(connection->object->connection, sql.c_str(), static_cast(paramsSize), NULL, /* let the backend deduce param type */ paramChars.data(), paramLengths.data(), paramFormats.data(), 0); /* ask for text results */ if (isError(res, connection->object.get()->connection)) return data; fillDataWithRes(data, res); PQclear(res); return data; } std::string PgSqlDatabase::ffQuery(const std::string &sql) { LOG_DEBUG << "Query: " << sql; auto connection = connections.get(); PGresult *res = PQexec(connection->object->connection, sql.c_str()); std::string rtn; if (isError(res, connection->object.get()->connection)) return rtn; if (PQresultStatus(res) == PGRES_TUPLES_OK) { rtn = std::string(PQgetvalue(res, 0, 0), PQgetlength(res, 0, 0)); } PQclear(res); return rtn; } std::string PgSqlDatabase::ffQuery(const std::string &sql, const std::vector ¶ms) { LOG_DEBUG << "Query: " << sql; const size_t paramsSize = params.size(); std::vector paramChars; std::vector paramLengths; std::vector paramFormats; for (size_t i = 0; i < paramsSize; ++i) { LOG_TRACE << "Parameter " << i << ": " << params.at(i); paramChars.push_back(params.at(i).c_str()); paramLengths.push_back(static_cast(params.at(i).size())); paramFormats.push_back(0); // Insert Text } auto connection = connections.get(); PGresult *res = PQexecParams(connection->object->connection, sql.c_str(), static_cast(paramsSize), NULL, /* let the backend deduce param type */ paramChars.data(), paramLengths.data(), paramFormats.data(), 0); /* ask for text results */ std::string rtn; if (isError(res, connection->object.get()->connection)) return rtn; if (PQresultStatus(res) == PGRES_TUPLES_OK) { rtn = std::string(PQgetvalue(res, 0, 0), PQgetlength(res, 0, 0)); } PQclear(res); return rtn; } bool PgSqlDatabase::isError(PGresult *res, PGconn *connection) { ExecStatusType result = PQresultStatus(res); if (result == PGRES_BAD_RESPONSE || result == PGRES_FATAL_ERROR) { LOG_ERROR << "Error Message: " << PQerrorMessage(connection); PQclear(res); return true; } return false; } void PgSqlDatabase::fillDataWithRes(RsData &data, PGresult *res) { if (PQresultStatus(res) == PGRES_TUPLES_OK) { int fieldsCount = PQnfields(res); int resultCount = PQntuples(res); for (int row = 0; row < resultCount; ++row) { for (int col = 0; col < fieldsCount; ++col) { std::string columnName(PQfname(res, col)); auto itr = data.find(columnName); if (itr == data.end()) { itr = data.insert(make_pair(columnName, std::vector())).first; } itr->second.emplace_back(PQgetvalue(res, row, col), PQgetlength(res, row, col)); } } } } PgTable PgSqlDatabase::getTable(const std::string &tableName) { return PgTable(this->self, "public", tableName); } PgTable PgSqlDatabase::getTable(const std::string &schema, const std::string &tableName) { return PgTable(this->self, schema, tableName); } bool PgSqlDatabase::execute(const std::string &sql, const std::vector ¶ms) { LOG_DEBUG << "Execute: " << sql; const size_t paramsSize = params.size(); std::vector paramChars; std::vector paramLengths; std::vector paramFormats; for (size_t i = 0; i < paramsSize; ++i) { LOG_TRACE << "Parameter " << i << ": " << params.at(i); paramChars.push_back(params.at(i).c_str()); paramLengths.push_back(static_cast(params.at(i).size())); paramFormats.push_back(0); // Insert Text } auto connection = connections.get(); PGresult *res = PQexecParams(connection->object->connection, sql.c_str(), static_cast(paramsSize), NULL, /* let the backend deduce param type */ paramChars.data(), paramLengths.data(), paramFormats.data(), 0); /* ask for text results */ if (PQresultStatus(res) != PGRES_COMMAND_OK && PQresultStatus(res) != PGRES_TUPLES_OK) { LOG_ERROR << PQerrorMessage(connection->object->connection); PQclear(res); return false; } PQclear(res); return true; } bool PgSqlDatabase::execute(const std::string &sql) { LOG_DEBUG << sql; auto connection = connections.get(); PGresult *res = PQexec(connection->object->connection, sql.c_str()); if (PQresultStatus(res) != PGRES_COMMAND_OK && PQresultStatus(res) != PGRES_TUPLES_OK) { LOG_ERROR << PQerrorMessage(connection->object->connection); PQclear(res); return false; } PQclear(res); return true; } std::vector PgSqlDatabase::find(const PgEntity &entity, const std::string &sql, const std::vector ¶ms) { LOG_DEBUG << "Query: " << sql; std::vector data; const size_t paramsSize = params.size(); std::vector paramChars; std::vector paramLengths; std::vector paramFormats; for (size_t i = 0; i < paramsSize; ++i) { LOG_TRACE << "Parameter " << i << ": " << params.at(i); paramChars.push_back(params.at(i).c_str()); paramLengths.push_back(static_cast(params.at(i).size())); paramFormats.push_back(0); // Insert Text } auto connection = connections.get(); PGresult *res = PQexecParams(connection->object->connection, sql.c_str(), static_cast(paramsSize), NULL, /* let the backend deduce param type */ paramChars.data(), paramLengths.data(), paramFormats.data(), 0); /* ask for text results */ if (isError(res, connection->object.get()->connection)) return data; fillPgEntity(entity, data, res); PQclear(res); return data; } std::vector> PgSqlDatabase::findBy(const PgEntity &entity, const std::string &sql, const std::vector ¶ms) { LOG_DEBUG << "Query: " << sql; std::vector> data; const size_t paramsSize = params.size(); std::vector paramChars; std::vector paramLengths; std::vector paramFormats; for (size_t i = 0; i < paramsSize; ++i) { LOG_TRACE << "Parameter " << i << ": " << params.at(i); paramChars.push_back(params.at(i).c_str()); paramLengths.push_back(static_cast(params.at(i).size())); paramFormats.push_back(0); // Insert Text } auto connection = connections.get(); PGresult *res = PQexecParams(connection->object->connection, sql.c_str(), static_cast(paramsSize), NULL, /* let the backend deduce param type */ paramChars.data(), paramLengths.data(), paramFormats.data(), 0); /* ask for text results */ if (isError(res, connection->object.get()->connection)) return data; fillPgEntity(entity, data, res); PQclear(res); return data; } void PgSqlDatabase::fillPgEntity(const PgEntity &entity, std::vector &rtn, PGresult *res) { if (PQresultStatus(res) == PGRES_TUPLES_OK) { int fieldsCount = PQnfields(res); int resultCount = PQntuples(res); for (size_t row = 0; row < resultCount; ++row) { PgEntity new_entity = entity.New(); for (int col = 0; col < fieldsCount; ++col) { new_entity.at(col)->Get().Set(PQgetvalue(res, row, col), PQgetlength(res, row, col)); new_entity.at(col)->Get().Dirty = false; } rtn.emplace_back(std::move(new_entity)); } } } void PgSqlDatabase::fillPgEntity(const PgEntity &entity, std::vector> &rtn, PGresult *res) { if (PQresultStatus(res) == PGRES_TUPLES_OK) { int fieldsCount = PQnfields(res); int resultCount = PQntuples(res); for (size_t row = 0; row < resultCount; ++row) { std::shared_ptr new_entity(entity.NewPtr()); for (int col = 0; col < fieldsCount; ++col) { new_entity->at(col)->Get().Set(PQgetvalue(res, row, col), PQgetlength(res, row, col)); new_entity->at(col)->Get().Dirty = false; } rtn.emplace_back(new_entity); } } } std::vector PgSqlDatabase::findAll(const PgEntity &entity) { std::vector data; SqlBuilder::SqlBuilder builder; builder.table = entity.GetSchemaTable(); builder.columns = entity.GetColumnNames(); const auto sql = builder.build(); LOG_DEBUG << sql; auto connection = connections.get(); PGresult *res = PQexec(connection->object->connection, sql.c_str()); if (isError(res, connection->object.get()->connection)) return data; fillPgEntity(entity, data, res); return data; } bool PgSqlDatabase::insert(const PgEntity &entity) { SqlBuilder::SqlBuilder builder; builder.type = SqlBuilder::INSERT; builder.table = entity.GetSchemaTable(); builder.values = entity.GetPairs(); std::vector parameters; const auto sql = builder.build(parameters); LOG_DEBUG << sql; return execute(sql, parameters); } void PgSqlDatabase::copyCSV(const std::string &table, const std::string &file, std::function callback, const std::string &delimiter) { StringFileHandler sfh(file); if (!sfh.HasNext()) { LOG_ERROR << "Empty file"; } const auto header = sfh.GetLine(); const auto columns = FlowString::splitNotEmpty(header, delimiter); std::ostringstream sql; sql << "COPY " << table << "("; for (size_t i = 0; i < columns.size(); ++i) { sql << columns.at(i); if (i != (columns.size() - 1)) { sql << ", "; } } sql << ") FROM STDIN CSV DELIMITER '" << delimiter << "';"; auto connection = connections.get(); const auto res = PQexec(connection->object->connection, sql.str().c_str()); if (isError(res, connection->object->connection) || PQresultStatus(res) != PGRES_COPY_IN) { return; } int a = 1; while (sfh.HasNext() && a == 1) { auto buffer = sfh.GetLine() + '\n'; callback(buffer); if (buffer.size() > 1) { a = PQputCopyData(connection->object->connection, buffer.c_str(), buffer.size()); } } const char *errmsg = nullptr; PQputCopyEnd(connection->object->connection, errmsg); const auto res_cp = PQgetResult(connection->object->connection); if (isError(res_cp, connection->object->connection)) { return; } PQclear(res); PQclear(res_cp); LOG_INFO << "Finished: " << sql.str(); } void PgSqlDatabase::copyCSV(const std::string &table, const std::string &file, const std::string &delimiter) { StringFileHandler sfh(file); if (!sfh.HasNext()) { LOG_ERROR << "Empty file"; } const auto header = sfh.GetLine(); const auto columns = FlowString::splitNotEmpty(header, delimiter); std::ostringstream sql; sql << "COPY " << table << "("; for (size_t i = 0; i < columns.size(); ++i) { sql << columns.at(i); if (i != (columns.size() - 1)) { sql << ", "; } } sql << ") FROM STDIN CSV DELIMITER '" << delimiter << "';"; auto connection = connections.get(); // << HERE const auto res = PQexec(connection->object->connection, sql.str().c_str()); if (isError(res, connection->object->connection) || PQresultStatus(res) != PGRES_COPY_IN) { return; } int a = 1; while (sfh.HasNext() && a == 1) { const auto buffer = sfh.GetLine() + '\n'; if (buffer.size() > 1) { a = PQputCopyData(connection->object->connection, buffer.c_str(), buffer.size()); } } const char *errmsg = nullptr; PQputCopyEnd(connection->object->connection, errmsg); const auto res_cp = PQgetResult(connection->object->connection); if (isError(res_cp, connection->object->connection)) { return; } PQclear(res); PQclear(res_cp); LOG_INFO << "Finished: " << sql.str(); } wliotproxy-src-server/wliotproxyd/TcpControlSocket.cpp /******************************************* Copyright 2017 OOO "LMS" 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 "TcpControlSocket.h" #include "wliot/WLIOTProtocolDefs.h" #include "wliot/WLIOTServerProtocolDefs.h" #include "ServerLogs.h" #include #include #include using namespace WLIOT; TcpControlSocket::TcpControlSocket(QObject *parent) :QObject(parent) { connect(&sslServer,&SslServer::newConnection,this,&TcpControlSocket::onNewLocalConnection); } TcpControlSocket::~TcpControlSocket() { for(auto &set:QList(clients)) { set.sock->disconnect(this); if(set.proc) set.proc->scheduleDelete(); else set.sock->deleteLater(); // set->sock()->disconnect(this); // set->quit(); // set->wait(2000); // set->terminate(); // //TODO gracefull stop // delete set; } clients.clear(); } void TcpControlSocket::start(const QList &crt,const QSslKey &key) { if(sslServer.isListening())return; sslServer.setSslOptions(crt,key); sslServer.listen(QHostAddress::AnyIPv4,WLIOTServerProtocolDefs::controlSslPort); } void TcpControlSocket::stop() { sslServer.close(); } void TcpControlSocket::onNewLocalConnection() { QSslSocket *sock=(QSslSocket*)sslServer.nextPendingConnection(); while(sock!=0) { //TODO multithread ??? "QSocketNotifier: Socket notifiers cannot be enabled or disabled from another thread" ServerLogs::logClients(QtInfoMsg,"Client connected"); connect(sock,&QSslSocket::disconnected,this,&TcpControlSocket::onSocketDisconnected, Qt::QueuedConnection); connect(sock,&QSslSocket::encrypted,this,&TcpControlSocket::onSocketEncrypted,Qt::QueuedConnection); connect(sock,static_cast&)>(&QSslSocket::sslErrors),this, &TcpControlSocket::onSslErrors,Qt::QueuedConnection); connect(sock,static_cast(&QSslSocket::error),this, &TcpControlSocket::onSocketError,Qt::QueuedConnection); ClientSet set; set.sock=sock; clients.append(set); // ClientThread *thr=new ClientThread(sock,this); // thr->setup(); // clients.append(thr); sock=(QSslSocket*)sslServer.nextPendingConnection(); } } void TcpControlSocket::onSocketDisconnected() { closeClient((QSslSocket*)sender()); // ClientThread *thr=clients[index]; // thr->quit(); // thr->wait(2000); // thr->terminate(); // delete thr; // clients.removeAt(index);ARpcConfig // qDebug()<<"Client disconnected"; } void TcpControlSocket::onSocketEncrypted() { QSslSocket *sock=(QSslSocket*)sender(); int index=findClient(sock); if(index==-1) return; ClientSet &set=clients[index]; CommandProcessor *cProc=new CommandProcessor(sock); set.proc=cProc; } void TcpControlSocket::onSocketError(QAbstractSocket::SocketError) { QSslSocket *s=(QSslSocket*)sender(); if(s->error()!=QSslSocket::RemoteHostClosedError) qWarning()<<"tcp control socket error: "<errorString(); s->disconnectFromHost(); } void TcpControlSocket::onSslErrors(const QList &errs) { for(const auto &e:errs) qWarning()<<"tcp control socket ssl error: "<scheduleDelete(); else set.sock->deleteLater(); clients.removeAt(index); ServerLogs::logClients(QtInfoMsg,"Client disconnected"); } clang-tools-extra/clangd/FindSymbols.cpp //===--- FindSymbols.cpp ------------------------------------*- C++-*------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "FindSymbols.h" #include "AST.h" #include "ClangdUnit.h" #include "FuzzyMatch.h" #include "Logger.h" #include "Quality.h" #include "SourceCode.h" #include "index/Index.h" #include "clang/Index/IndexDataConsumer.h" #include "clang/Index/IndexSymbol.h" #include "clang/Index/IndexingAction.h" #include "llvm/Support/FormatVariadic.h" #include "llvm/Support/Path.h" #define DEBUG_TYPE "FindSymbols" namespace clang { namespace clangd { namespace { // Convert a index::SymbolKind to clangd::SymbolKind (LSP) // Note, some are not perfect matches and should be improved when this LSP // issue is addressed: // https://github.com/Microsoft/language-server-protocol/issues/344 SymbolKind indexSymbolKindToSymbolKind(index::SymbolKind Kind) { switch (Kind) { case index::SymbolKind::Unknown: return SymbolKind::Variable; case index::SymbolKind::Module: return SymbolKind::Module; case index::SymbolKind::Namespace: return SymbolKind::Namespace; case index::SymbolKind::NamespaceAlias: return SymbolKind::Namespace; case index::SymbolKind::Macro: return SymbolKind::String; case index::SymbolKind::Enum: return SymbolKind::Enum; case index::SymbolKind::Struct: return SymbolKind::Struct; case index::SymbolKind::Class: return SymbolKind::Class; case index::SymbolKind::Protocol: return SymbolKind::Interface; case index::SymbolKind::Extension: return SymbolKind::Interface; case index::SymbolKind::Union: return SymbolKind::Class; case index::SymbolKind::TypeAlias: return SymbolKind::Class; case index::SymbolKind::Function: return SymbolKind::Function; case index::SymbolKind::Variable: return SymbolKind::Variable; case index::SymbolKind::Field: return SymbolKind::Field; case index::SymbolKind::EnumConstant: return SymbolKind::EnumMember; case index::SymbolKind::InstanceMethod: case index::SymbolKind::ClassMethod: case index::SymbolKind::StaticMethod: return SymbolKind::Method; case index::SymbolKind::InstanceProperty: case index::SymbolKind::ClassProperty: case index::SymbolKind::StaticProperty: return SymbolKind::Property; case index::SymbolKind::Constructor: case index::SymbolKind::Destructor: return SymbolKind::Method; case index::SymbolKind::ConversionFunction: return SymbolKind::Function; case index::SymbolKind::Parameter: return SymbolKind::Variable; case index::SymbolKind::Using: return SymbolKind::Namespace; } llvm_unreachable("invalid symbol kind"); } using ScoredSymbolInfo = std::pair; struct ScoredSymbolGreater { bool operator()(const ScoredSymbolInfo &L, const ScoredSymbolInfo &R) { if (L.first != R.first) return L.first > R.first; return L.second.name < R.second.name; // Earlier name is better. } }; } // namespace llvm::Expected> getWorkspaceSymbols(StringRef Query, int Limit, const SymbolIndex *const Index, StringRef HintPath) { std::vector Result; if (Query.empty() || !Index) return Result; auto Names = splitQualifiedName(Query); FuzzyFindRequest Req; Req.Query = Names.second; // FuzzyFind doesn't want leading :: qualifier bool IsGlobalQuery = Names.first.consume_front("::"); // Restrict results to the scope in the query string if present (global or // not). if (IsGlobalQuery || !Names.first.empty()) Req.Scopes = {Names.first}; if (Limit) Req.MaxCandidateCount = Limit; TopN Top(Req.MaxCandidateCount); FuzzyMatcher Filter(Req.Query); Index->fuzzyFind(Req, [HintPath, &Top, &Filter](const Symbol &Sym) { // Prefer the definition over e.g. a function declaration in a header auto &CD = Sym.Definition ? Sym.Definition : Sym.CanonicalDeclaration; auto Uri = URI::parse(CD.FileURI); if (!Uri) { log("Workspace symbol: Could not parse URI '{0}' for symbol '{1}'.", CD.FileURI, Sym.Name); return; } auto Path = URI::resolve(*Uri, HintPath); if (!Path) { log("Workspace symbol: Could not resolve path for URI '{0}' for symbol " "'{1}'.", Uri->toString(), Sym.Name); return; } Location L; L.uri = URIForFile((*Path)); Position Start, End; Start.line = CD.Start.Line; Start.character = CD.Start.Column; End.line = CD.End.Line; End.character = CD.End.Column; L.range = {Start, End}; SymbolKind SK = indexSymbolKindToSymbolKind(Sym.SymInfo.Kind); std::string Scope = Sym.Scope; StringRef ScopeRef = Scope; ScopeRef.consume_back("::"); SymbolInformation Info = {Sym.Name, SK, L, ScopeRef}; SymbolQualitySignals Quality; Quality.merge(Sym); SymbolRelevanceSignals Relevance; Relevance.Query = SymbolRelevanceSignals::Generic; if (auto NameMatch = Filter.match(Sym.Name)) Relevance.NameMatch = *NameMatch; else { log("Workspace symbol: {0} didn't match query {1}", Sym.Name, Filter.pattern()); return; } Relevance.merge(Sym); auto Score = evaluateSymbolAndRelevance(Quality.evaluate(), Relevance.evaluate()); dlog("FindSymbols: {0}{1} = {2}\n{3}{4}\n", Sym.Scope, Sym.Name, Score, Quality, Relevance); Top.push({Score, std::move(Info)}); }); for (auto &R : std::move(Top).items()) Result.push_back(std::move(R.second)); return Result; } namespace { /// Finds document symbols in the main file of the AST. class DocumentSymbolsConsumer : public index::IndexDataConsumer { ASTContext &AST; std::vector Symbols; // We are always list document for the same file, so cache the value. llvm::Optional MainFileUri; public: DocumentSymbolsConsumer(ASTContext &AST) : AST(AST) {} std::vector takeSymbols() { return std::move(Symbols); } void initialize(ASTContext &Ctx) override { // Compute the absolute path of the main file which we will use for all // results. const SourceManager &SM = AST.getSourceManager(); const FileEntry *F = SM.getFileEntryForID(SM.getMainFileID()); if (!F) return; auto FilePath = getRealPath(F, SM); if (FilePath) MainFileUri = URIForFile(*FilePath); } bool shouldIncludeSymbol(const NamedDecl *ND) { if (!ND || ND->isImplicit()) return false; // Skip anonymous declarations, e.g (anonymous enum/class/struct). if (ND->getDeclName().isEmpty()) return false; return true; } bool handleDeclOccurence(const Decl *, index::SymbolRoleSet Roles, ArrayRef Relations, SourceLocation Loc, index::IndexDataConsumer::ASTNodeInfo ASTNode) override { assert(ASTNode.OrigD); // No point in continuing the index consumer if we could not get the // absolute path of the main file. if (!MainFileUri) return false; // We only want declarations and definitions, i.e. no references. if (!(Roles & static_cast(index::SymbolRole::Declaration) || Roles & static_cast(index::SymbolRole::Definition))) return true; SourceLocation NameLoc = findNameLoc(ASTNode.OrigD); const SourceManager &SourceMgr = AST.getSourceManager(); // We should be only be looking at "local" decls in the main file. if (!SourceMgr.isWrittenInMainFile(NameLoc)) { // Even thought we are visiting only local (non-preamble) decls, // we can get here when in the presence of "extern" decls. return true; } const NamedDecl *ND = llvm::dyn_cast(ASTNode.OrigD); if (!shouldIncludeSymbol(ND)) return true; SourceLocation EndLoc = Lexer::getLocForEndOfToken(NameLoc, 0, SourceMgr, AST.getLangOpts()); Position Begin = sourceLocToPosition(SourceMgr, NameLoc); Position End = sourceLocToPosition(SourceMgr, EndLoc); Range R = {Begin, End}; Location L; L.uri = *MainFileUri; L.range = R; std::string QName = printQualifiedName(*ND); StringRef Scope, Name; std::tie(Scope, Name) = splitQualifiedName(QName); Scope.consume_back("::"); index::SymbolInfo SymInfo = index::getSymbolInfo(ND); SymbolKind SK = indexSymbolKindToSymbolKind(SymInfo.Kind); SymbolInformation SI; SI.name = Name; SI.kind = SK; SI.location = L; SI.containerName = Scope; Symbols.push_back(std::move(SI)); return true; } }; } // namespace llvm::Expected> getDocumentSymbols(ParsedAST &AST) { DocumentSymbolsConsumer DocumentSymbolsCons(AST.getASTContext()); index::IndexingOptions IndexOpts; IndexOpts.SystemSymbolFilter = index::IndexingOptions::SystemSymbolFilterKind::DeclarationsOnly; IndexOpts.IndexFunctionLocals = false; indexTopLevelDecls(AST.getASTContext(), AST.getLocalTopLevelDecls(), DocumentSymbolsCons, IndexOpts); return DocumentSymbolsCons.takeSymbols(); } } // namespace clangd } // namespace clang BakaErii/ACM_CollectionCodeForces/920A/12889381_AC_15ms_1852kB.cpp0 /** * @author Moe_Sakiya * @date 2018-02-02 22:40:07 * */ #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; int arr[200]; int main(void) { int t, n, k, d, ans; int i; cin >> t; while (t--) { d = 0; cin >> n >> k; for (i = 0; i < k; i++) cin >> arr[i]; sort(arr, arr + k); for (i = 1; i < k; i++) d = max(arr[i] - arr[i - 1] + 1, d); if (d % 2 == 0) ans = d / 2; else ans = d / 2 + 1; ans = max(arr[0], ans); ans = max(n - arr[k - 1] + 1, ans); cout << ans << endl; } return 0; }///////////////////////////////////////////////////////////////////////// /// /// /// YARP - Yet Another Robotic Platform (c) 2001-2004 /// /// /// /// #Add our name(s) here# /// /// /// /// "Licensed under the Academic Free License Version 1.0" /// /// /// /// The complete license description is contained in the /// /// licence.template file included in this distribution in /// /// $YARP_ROOT/conf. Please refer to this file for complete /// /// information about the licensing of YARP /// /// /// /// DISCLAIMERS: LICENSOR WARRANTS THAT THE COPYRIGHT IN AND TO THE /// /// SOFTWARE IS OWNED BY THE LICENSOR OR THAT THE SOFTWARE IS /// /// DISTRIBUTED BY LICENSOR UNDER A VALID CURRENT LICENSE. EXCEPT AS /// /// EXPRESSLY STATED IN THE IMMEDIATELY PRECEDING SENTENCE, THE /// /// SOFTWARE IS PROVIDED BY THE LICENSOR, CONTRIBUTORS AND COPYRIGHT /// /// OWNERS "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 NON-INFRINGEMENT. IN NO /// /// EVENT SHALL THE LICENSOR, CONTRIBUTORS OR COPYRIGHT OWNERS 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. /// /// /// ///////////////////////////////////////////////////////////////////////// /// /// /// YARP - Yet Another Robotic Platform (c) 2001-2003 /// /// #emmebi# /// /// "Licensed under the Academic Free License Version 1.0" /// /// /// $Id: YARPDragonflyDeviceDriver.cpp,v 1.2 2005-04-21 12:44:54 emmebi75 Exp $ /// /// #include "YARPDragonflyDeviceDriver.h" #include //============================================================================= // FlyCam Includes //============================================================================= #include "../dd_orig/include/pgrflycapture.h" /// double GetTimeAs_mSeconds(void) { ACE_Time_Value timev = ACE_OS::gettimeofday (); return double(timev.sec()*1e3) + timev.usec() * 1e-3; } // class DragonflyResources { public: DragonflyResources (void) : _newFrameMutex(0)/* CONV_MUTEX*/, _convImgMutex(1) { // Variables initialization sizeX = 0; sizeY = 0; maxCams = 0; bufIndex = 0; _canPost = false; imageConverted.pData = NULL; _acqStarted = false; _validContext = false; _pSubsampled_data = NULL; _raw_sizeX = 640; _raw_sizeY = 480; } ~DragonflyResources () { _uninitialize (); // To be sure - must protected against double calling } // Hardware-dependant variables enum { _num_buffers = 3 }; int sizeX; int sizeY; int maxCams; int bufIndex; bool _canPost; bool _acqStarted; bool _validContext; int _raw_sizeX; int _raw_sizeY; unsigned char *_pSubsampled_data; FlyCaptureContext context; FlyCaptureImage imageBuffer[_num_buffers]; FlyCaptureImage imageConverted; YARPSemaphore mutexArray[_num_buffers]; YARPSemaphore _newFrameMutex; /* CONV_MUTEX*/ YARPSemaphore _convImgMutex; inline int _initialize (const DragonflyOpenParameters& params); inline int _uninitialize (void); inline void _cleanBuffers (void); inline bool _setBrightness (int value, bool bDefault=false); inline bool _setExposure (int value, bool bDefault=false); inline bool _setWhiteBalance (int redValue, int blueValue, bool bDefault=false); inline bool _setShutter (int value, bool bDefault=false); inline bool _setGain (int value, bool bDefault=false); inline void _subSampling(void); protected: inline void _prepareBuffers (void); inline void _destroyBuffers (void); }; /// /// /// full initialize and startup of the grabber. inline int DragonflyResources::_initialize (const DragonflyOpenParameters& params) { FlyCaptureError error = FLYCAPTURE_OK; // LATER: add a camera_init function sizeX = params._size_x; sizeY = params._size_y; // Create the context. if (!_validContext) { error = flycaptureCreateContext( &context ); if (error != FLYCAPTURE_OK) return YARP_FAIL; _validContext = true; // Initialize the camera. error = flycaptureInitialize( context, params._unit_number ); if (error != FLYCAPTURE_OK) return YARP_FAIL; } // Setup Camera Parameters, Magic Numbers :-) _setBrightness(0); _setExposure(300); _setWhiteBalance(20, 50); _setShutter(320); // x * 0.0625 = 20 mSec = 50 Hz _setGain(700); // x * -0.0224 = -11.2dB // Set color reconstruction method error = flycaptureSetColorProcessingMethod(context, FLYCAPTURE_NEAREST_NEIGHBOR_FAST); // Should be an Option if (error != FLYCAPTURE_OK) return YARP_FAIL; // Set Acquisition Timeout error = flycaptureSetGrabTimeoutEx(context, 200); if (error != FLYCAPTURE_OK) return YARP_FAIL; // Buffers _prepareBuffers (); // Start Acquisition if (!_acqStarted) { error = flycaptureStart( context, FLYCAPTURE_VIDEOMODE_640x480Y8, FLYCAPTURE_FRAMERATE_30 ); if (error != FLYCAPTURE_OK) return YARP_FAIL; _acqStarted = true; } return YARP_OK; } inline int DragonflyResources::_uninitialize (void) { int i; FlyCaptureError error = FLYCAPTURE_OK; for (i=0; i< _num_buffers; i++) mutexArray[i].Wait(); // Stop Acquisition if (_acqStarted) { error = flycaptureStop(context); if (error != FLYCAPTURE_OK) return YARP_FAIL; _acqStarted = false; } // Destroy the context. if (_validContext) { error = flycaptureDestroyContext( context ); if (error != FLYCAPTURE_OK) return YARP_FAIL; _validContext = false; } // Deallocate buffers _destroyBuffers(); for (i=0; i< _num_buffers; i++) mutexArray[i].Post(); return YARP_OK; } /// /// inline void DragonflyResources::_prepareBuffers(void) { if (imageConverted.pData == NULL) imageConverted.pData = new unsigned char[ _raw_sizeX * _raw_sizeY * 3 ]; imageConverted.pixelFormat = FLYCAPTURE_BGR; if (_pSubsampled_data == NULL) _pSubsampled_data = new unsigned char[ sizeX * sizeY * 3 ]; _cleanBuffers(); } inline void DragonflyResources::_cleanBuffers(void) { for (int i=0; i< _num_buffers; i++) memset( &imageBuffer[i], 0x0, sizeof( FlyCaptureImage ) ); memset(_pSubsampled_data, 0x0, (sizeX * sizeY * 3)); } inline void DragonflyResources::_destroyBuffers(void) { if (imageConverted.pData != NULL) delete [] imageConverted.pData; imageConverted.pData = NULL; if (_pSubsampled_data != NULL) delete [] _pSubsampled_data; _pSubsampled_data = NULL; } inline bool DragonflyResources::_setBrightness (int value, bool bAuto) { FlyCaptureError error = FLYCAPTURE_OK; error = flycaptureSetCameraProperty(context, FLYCAPTURE_BRIGHTNESS, value, 0, bAuto); if (error == FLYCAPTURE_OK) return true; else return false; } inline bool DragonflyResources::_setExposure (int value, bool bAuto) { FlyCaptureError error = FLYCAPTURE_OK; error = flycaptureSetCameraProperty(context, FLYCAPTURE_AUTO_EXPOSURE, value, 0, bAuto); if (error == FLYCAPTURE_OK) return true; else return false; } inline bool DragonflyResources::_setWhiteBalance (int redValue, int blueValue, bool bAuto) { FlyCaptureError error = FLYCAPTURE_OK; error = flycaptureSetCameraProperty(context, FLYCAPTURE_WHITE_BALANCE, redValue, blueValue, bAuto); if (error == FLYCAPTURE_OK) return true; else return false; } inline bool DragonflyResources::_setShutter (int value, bool bAuto) { FlyCaptureError error = FLYCAPTURE_OK; error = flycaptureSetCameraProperty(context, FLYCAPTURE_SHUTTER,value, 0, bAuto); if (error == FLYCAPTURE_OK) return true; else return false; } inline bool DragonflyResources::_setGain (int value, bool bAuto) { FlyCaptureError error = FLYCAPTURE_OK; error = flycaptureSetCameraProperty(context, FLYCAPTURE_GAIN, value, 0, bAuto); if (error == FLYCAPTURE_OK) return true; else return false; } inline void DragonflyResources::_subSampling(void) { int srcX, srcY; float xRatio, yRatio; int srcOffset; int srcSizeY = _raw_sizeY, srcSizeX = _raw_sizeX; int dstSizeY = sizeY, dstSizeX = sizeX; int bytePerPixel = 3; xRatio = ((float)srcSizeX)/dstSizeX; yRatio = ((float)srcSizeY)/dstSizeY; unsigned char *pSrcImg = imageConverted.pData; unsigned char *pDstImg = _pSubsampled_data; unsigned char *pSrc = pSrcImg; unsigned char *pDst = pDstImg; for (int j=0; j(FCMDNCmds) { system_resources = (void *) new DragonflyResources; ACE_ASSERT (system_resources != NULL); /// for the IOCtl call. m_cmds[FCMDAcquireBuffer] = &YARPDragonflyDeviceDriver::acquireBuffer; m_cmds[FCMDReleaseBuffer] = &YARPDragonflyDeviceDriver::releaseBuffer; m_cmds[FCMDWaitNewFrame] = &YARPDragonflyDeviceDriver::waitOnNewFrame; m_cmds[FCMDGetSizeX] = &YARPDragonflyDeviceDriver::getWidth; m_cmds[FCMDGetSizeY] = &YARPDragonflyDeviceDriver::getHeight; m_cmds[FCMDSetBright] = &YARPDragonflyDeviceDriver::setBrightness; m_cmds[FCMDSetHue] = &YARPDragonflyDeviceDriver::setHue; m_cmds[FCMDSetContrast] = &YARPDragonflyDeviceDriver::setContrast; m_cmds[FCMDSetSatU] = &YARPDragonflyDeviceDriver::setSatU; m_cmds[FCMDSetSatV] = &YARPDragonflyDeviceDriver::setSatV; m_cmds[FCMDSetLNotch] = &YARPDragonflyDeviceDriver::setLNotch; m_cmds[FCMDSetLDec] = &YARPDragonflyDeviceDriver::setLDec; m_cmds[FCMDSetCrush] = &YARPDragonflyDeviceDriver::setCrush; } YARPDragonflyDeviceDriver::~YARPDragonflyDeviceDriver() { if (system_resources != NULL) delete (DragonflyResources *)system_resources; system_resources = NULL; } /// /// int YARPDragonflyDeviceDriver::open (void *res) { DragonflyResources& d = RES(system_resources); int ret = d._initialize (*(DragonflyOpenParameters *)res); YARPScheduler::setHighResScheduling (); Begin (); return ret; } int YARPDragonflyDeviceDriver::close (void) { DragonflyResources& d = RES(system_resources); End (); /// stops the thread first (joins too). int ret = d._uninitialize (); return ret; } /// /// /// acquisition thread for real! void YARPDragonflyDeviceDriver::Body (void) { DragonflyResources& d = RES(system_resources); FlyCaptureError error = FLYCAPTURE_OK; d._cleanBuffers(); d.bufIndex = 0; d._canPost = true; int nImages = 0; double startTime; startTime = GetTimeAs_mSeconds(); int lostFrames = 0; ACE_DEBUG ((LM_DEBUG, "\n[DragonFly Driver] Acquisition thread starting... ")); while (!IsTerminated()) { d.bufIndex++; if (d.bufIndex == d._num_buffers) d.bufIndex = 0; if ((d.mutexArray[d.bufIndex]).PollingWait() == 1) { error = flycaptureGrabImage2( d.context, &(d.imageBuffer[d.bufIndex]) ); if (d._canPost) { d._canPost = false; d._newFrameMutex.Post(); } (d.mutexArray[d.bufIndex]).Post(); if (error != FLYCAPTURE_OK) { ACE_DEBUG ((LM_DEBUG, "\n[DragonFly Driver] ERROR: It's likely that the acquisition failed, returning. ")); AskForEnd(); } nImages++; } else { ACE_DEBUG ((LM_DEBUG, "\n[DragonFly Driver] WARNING: Frame lost. ")); lostFrames++; } } double stopTime; stopTime = GetTimeAs_mSeconds(); unsigned int delay = int(stopTime - startTime); unsigned int avTime = delay / nImages; double fps = 1000 * (1/double(avTime)); char str[256]; sprintf(str,"\n[DragonFly Driver] Acquired %u frames(s) in %ums (average time %ums per image, %.2ffps). ", nImages, delay, avTime, fps); ACE_DEBUG ((LM_DEBUG, str)); sprintf(str,"\n[DragonFly Driver] %u lost Frame(s). "); ACE_DEBUG ((LM_DEBUG, "\n[DragonFly Driver] Acquisition thread returning... ")); } int YARPDragonflyDeviceDriver::acquireBuffer (void *buffer) { DragonflyResources& d = RES(system_resources); FlyCaptureError error = FLYCAPTURE_OK; int reqBuffer = d.bufIndex - 1; if (reqBuffer < 0) reqBuffer = d._num_buffers - 1; (d.mutexArray[reqBuffer]).Wait (); /* CONV_MUTEX*/ d._convImgMutex.Wait(); FlyCaptureImage *pSrc; FlyCaptureImage *pDst; pDst = &(d.imageConverted); pSrc = &(d.imageBuffer[reqBuffer]); error = flycaptureConvertImage( d.context, pSrc, pDst ); (d.mutexArray[reqBuffer]).Post (); /* if (error != FLYCAPTURE_OK) return YARP_FAIL; */ //unsigned char * pData = (*(unsigned char **)buffer); // Copy or just reference?? //memcpy (pData, d.imageConverted.pData, (d.sizeX * d.sizeY * 3) ); if ((d.sizeX == d._raw_sizeX) && (d.sizeY == d._raw_sizeY) ) (*(unsigned char **)buffer)= d.imageConverted.pData; else { d._subSampling(); (*(unsigned char **)buffer)= d._pSubsampled_data; } return YARP_OK; } int YARPDragonflyDeviceDriver::releaseBuffer (void *cmd) { DragonflyResources& d = RES(system_resources); d._canPost = true; /* CONV_MUTEX*/ d._convImgMutex.Post(); return YARP_OK; } int YARPDragonflyDeviceDriver::waitOnNewFrame (void *cmd) { DragonflyResources& d = RES(system_resources); d._newFrameMutex.Wait (); return YARP_OK; } int YARPDragonflyDeviceDriver::getWidth (void *cmd) { *(int *)cmd = RES(system_resources).sizeX; return YARP_OK; } int YARPDragonflyDeviceDriver::getHeight (void *cmd) { *(int *)cmd = RES(system_resources).sizeY; return YARP_OK; } int YARPDragonflyDeviceDriver::setBrightness (void *cmd) { /// RES(system_resources)._setBrightness(*cmd); return YARP_OK; } int YARPDragonflyDeviceDriver::setHue (void *cmd) { /// RES(system_resources)._setHue(*cmd); return YARP_OK; } int YARPDragonflyDeviceDriver::setContrast (void *cmd) { /// RES(system_resources)._setContrast(*cmd); return YARP_OK; } int YARPDragonflyDeviceDriver::setSatU (void *cmd) { /// RES(system_resources)._setSatU(*cmd); return YARP_OK; } int YARPDragonflyDeviceDriver::setSatV (void *cmd) { /// RES(system_resources)._setSatV(*cmd); return YARP_OK; } int YARPDragonflyDeviceDriver::setLNotch (void *cmd) { /// RES(system_resources)._setLNotch(*cmd); return YARP_OK; } int YARPDragonflyDeviceDriver::setLDec (void *cmd) { /// RES(system_resources)._setLDec(*cmd); return YARP_OK; } int YARPDragonflyDeviceDriver::setCrush (void *cmd) { /// RES(system_resources)._setCrush(*cmd); return YARP_OK; } /**************************************************************************** Copyright (c) 2011-2013,WebJet Business Division,CYOU http://www.genesis-3d.com.cn 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 "stdneb.h" #include "particles/particletarget.h" namespace Particles { using namespace Serialization; const char* s_TargetName = "TargetName"; const char* s_TargetTexRowSize = "TargetTexRowSize"; const char* s_TargetTexColumnSize = "TargetTexColumnSize"; const char* s_OrientType = "OrientType"; const char* s_StretchScale = "StretchScale"; class ParticleTargetSerialization { public: //------------------------------------------------------------------------ void Load( ParticleTarget* obj, SVersion ver, SerializeReader* pReader ) { if ( 1 == ver ) { Load_1(obj, pReader); return; } if( 2== ver) { Load_2(obj, pReader); return; } if( 3== ver) { Load_3(obj, pReader); return; } n_error(" %s Load unknown version.\n", obj->GetClassName().AsCharPtr() ); } //-------------------------------------------------------------------------------- void Load_3(ParticleTarget* obj, SerializeReader* pReader) { Load_2(obj, pReader); float stretch; pReader->SerializeFloat(s_StretchScale, stretch ); obj->SetStretchScale(stretch ); } //-------------------------------------------------------------------------------- void Load_2(ParticleTarget* obj, SerializeReader* pReader) { Load_1(obj, pReader); int orienttype; pReader->SerializeInt(s_OrientType, orienttype ); obj->SetOrientType( (ParticleTarget::OrientType)orienttype ); } //------------------------------------------------------------------------ void Load_1(ParticleTarget* obj, SerializeReader* pReader) { Util::String name; pReader->SerializeString(s_TargetName, name ); obj->SetName( name ); SizeT texRowSize, texColumnSize; pReader->SerializeInt(s_TargetTexRowSize, texRowSize ); pReader->SerializeInt(s_TargetTexColumnSize, texColumnSize ); obj->SetTexCoordSize(texRowSize, texColumnSize); } //------------------------------------------------------------------------ void Save( const ParticleTarget* obj, SerializeWriter* pWriter ) { pWriter->SerializeString(s_TargetName, obj->GetName() ); pWriter->SerializeInt(s_TargetTexRowSize, obj->GetTexCoordRowSize() ); pWriter->SerializeInt(s_TargetTexColumnSize, obj->GetTexCoordColumnSize() ); pWriter->SerializeInt(s_OrientType, (int)obj->GetOrientType() ); pWriter->SerializeFloat(s_StretchScale, obj->GetStretchScale() ); } }; //------------------------------------------------------------------------ // @ISerialization::GetVersion. when change storage, must add SerializeVersion count SVersion ParticleTarget::GetVersion() const { return 3; } //------------------------------------------------------------------------ // @ISerialization::Load void ParticleTarget::Load( SVersion ver, SerializeReader* pReader, const Serialization::SerializationArgs* args ) { ParticleTargetSerialization Serialize; Serialize.Load( this, ver, pReader ); } //------------------------------------------------------------------------ // @ISerialization::Save void ParticleTarget::Save( SerializeWriter* pWriter ) const { ParticleTargetSerialization Serialize; Serialize.Save( this, pWriter ); } //------------------------------------------------------------------------ void ParticleTarget::CopyFrom( const ParticleTargetPtr& obj ) { SetName( obj->GetName() ); SetTexCoordSize( obj->GetTexCoordRowSize(), obj->GetTexCoordColumnSize() ); SetOrientType( obj->GetOrientType() ); SetStretchScale(obj->GetStretchScale()); } }CodeRancher/offcenter_commonlib/framework/src/AdminControlMessage.cpp /** * Copyright 2021 * * 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 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 AdminControlMessage.cpp * @author * @date 05-04-2021 */ #include #include "easylogging++.h" #include "offcenter/common/framework/admin/AdminControlMessage.hpp" #include "offcenter/common/Utility.hpp" #include "offcenter/common/RuntimeException.hpp" namespace offcenter { namespace common { namespace framework { namespace admin { void to_string(const AdminControlState &state, std::string &value) { switch(state) { case AdminControlState::Start: value = "Start"; break; case AdminControlState::Stop: value = "Stop"; break; case AdminControlState::Pause: value = "Pause"; break; case AdminControlState::Resume: value = "Resume"; break; case AdminControlState::Unknown: value = "Unknown"; break; } } void from_string(AdminControlState &state, const std::string &value) { static std::map lookup = { {"start", AdminControlState::Start}, {"stop", AdminControlState::Stop}, {"pause", AdminControlState::Pause}, {"resume", AdminControlState::Resume}, {"unknown", AdminControlState::Unknown} }; try { state = lookup.at(offcenter::common::toLower(value)); } catch(std::out_of_range& e) { std::string msg("Unknown AdminControlState string ("); msg += value; msg += ")"; LOG(ERROR) << msg; state = AdminControlState::Unknown; } } AdminControlMessage::AdminControlMessage(): m_appID(""), m_AdminControlState(AdminControlState::Unknown) { } AdminControlMessage::AdminControlMessage(const std::string& appID): m_appID(appID), m_AdminControlState(AdminControlState::Unknown) { // TODO Auto-generated constructor stub } AdminControlMessage::~AdminControlMessage() { // TODO Auto-generated destructor stub } void AdminControlMessage::setAppID(const std::string &appID) { m_appID = appID; } void AdminControlMessage::set(const AdminControlState AdminControlState) { m_AdminControlState = AdminControlState; } void to_cmsMessage(AdminControlMessage::MessageType* j, const AdminControlMessage &p) { j->setString("app_id", p.m_appID); std::string AdminControlState; to_string(p.m_AdminControlState, AdminControlState); j->setString("admin_status_state", AdminControlState); } void from_cmsMessage(const AdminControlMessage::MessageType* j, AdminControlMessage &p) { p.setAppID(j->getString("app_id")); AdminControlState AdminControlState; std::string tmp = j->getString("admin_status_state"); from_string(AdminControlState, tmp); p.set( AdminControlState ); } } /* namespace admin */ } /* namespace framework */ } /* namespace common */ } /* namespace offcenter */ /* * fixedgrid.hpp * * Created by on 4/8/08. * Copyright 2008 Transatlantic Giraffe. All rights reserved. * */ #ifndef __FIXEDGRID_HPP__ #define __FIXEDGRID_HPP__ #include #include #include #include "timer.hpp" namespace fixedgrid { /* Floating point value type */ typedef float real_t; /* Model state variables */ template < size_t NROWS, size_t NCOLS > class Model { public: typedef real_t (*matrix_t)[NCOLS]; typedef real_t (*transposed_t)[NROWS]; Model(int _run_id, size_t _dx, size_t _dy, size_t _dz, real_t conc_init, real_t wind_u_init, real_t wind_v_init, real_t diff_init) : write_each_iter(false), row_discret(true), col_discret(true), run_id(_run_id), dx(_dx), dy(_dy), dz(_dz), step(0), time(0), conc((matrix_t)alloc()), wind_u((matrix_t)alloc()), wind_v((transposed_t)alloc()), diff((matrix_t)alloc()) { conc[0:NROWS][:] = conc_init; wind_u[0:NROWS][:] = wind_u_init; wind_v[0:NCOLS][:] = wind_v_init; diff[0:NROWS][:] = diff_init; } ~Model() { } /* Add emission plume (mol/m^3) */ void AddPlume(real_t plume, size_t row, size_t col) { conc[row][col] += plume / (dx * dy * dz); } bool AreRowsDiscretized() const { return row_discret; } bool AreColsDiscretized() const { return col_discret; } real_t GetTime() const { return time; } void Step(real_t tstart, real_t tend, real_t dt); void WriteConcFile(void); private: void * alloc() { void * memptr; switch (posix_memalign(&memptr, 64, NROWS*NCOLS*sizeof(real_t))) { case EINVAL: std::cerr << "ERROR: Invalid argument to posix_memalign" << std::endl; memptr = NULL; break; case ENOMEM: std::cerr << "ERROR: Insufficient memory for allocation" << std::endl; memptr = NULL; break; } return memptr; } int WriteGnuplotBinaryMatrixFile(matrix_t mat, char const * fname); /* Write output each iteration? */ bool write_each_iter; /* Discretize rows each iteration? */ bool row_discret; /* Discretize columns each iteration? */ bool col_discret; /* Run identifier */ int run_id; /* Cell dimensions */ real_t dx, dy, dz; /* Model step */ size_t step; /* Current model time */ real_t time; /* Concentration field [NROWS][NCOLS] */ matrix_t conc; /* Wind field [NROWS][NCOLS] */ matrix_t wind_u; transposed_t wind_v; /* Diffusion tensor field [NROWS][NCOLS] */ matrix_t diff; }; /* * Upwinded advection/diffusion stencil. * c = conc, w = wind, d = diff * x2l is the 2-left neighbor of x, etc. * x2r is the 2-right neighbor of x, etc. */ static inline real_t advec_diff( real_t const cell_size, real_t const c2l, real_t const w2l, real_t const d2l, real_t const c1l, real_t const w1l, real_t const d1l, real_t const c, real_t const w, real_t const d, real_t const c1r, real_t const w1r, real_t const d1r, real_t const c2r, real_t const w2r, real_t const d2r) { real_t windL = (w1l + w) / 2.0; real_t advec_termL; if (windL >= 0.0) { advec_termL = (1.0 / 6.0) * (-c2l + 5.0 * c1l + 2.0 * c); } else { advec_termL = (1.0 / 6.0) * (2.0 * c1l + 5.0 * c - c1r); } advec_termL *= windL; real_t windR = (w1r + w) / 2.0; real_t advec_termR; if (windR >= 0.0) { advec_termR = (1.0 / 6.0) * (-c1l + 5.0 * c + 2.0 * c1r); } else { advec_termR = (1.0 / 6.0) * (2.0 * c + 5.0 * c1r - c2r); } advec_termR *= windR; real_t advec_term = (advec_termL - advec_termR) / cell_size; real_t diff_term = (((d1l + d) / 2) * (c1l - c) - ((d + d1r) / 2) * (c - c1r)) / (cell_size * cell_size); return advec_term + diff_term; } /* * Applies advection / diffusion stencil */ template < size_t N > static inline void space_advec_diff( real_t const cell_size, real_t const cb0, real_t const wb0, real_t const db0, real_t const cb1, real_t const wb1, real_t const db1, real_t const cb2, real_t const wb2, real_t const db2, real_t const cb3, real_t const wb3, real_t const db3, real_t const c[N], real_t const w[N], real_t const d[N], real_t dcdx[N]) { /* Do boundary cell c[0] explicitly */ dcdx[0] = advec_diff(cell_size, cb0, wb0, db0, /* 2-left neighbors */ cb1, wb1, db1, /* 1-left neighbors */ c[0], w[0], d[0], /* Values */ c[1], w[1], d[1], /* 1-right neighbors */ c[2], w[2], d[2]); /* 2-right neighbors */ /* Do boundary cell c[1] explicitly */ dcdx[1] = advec_diff(cell_size, cb1, wb1, db1, /* 2-left neighbors */ cb2, wb2, db2, /* 1-left neighbors */ c[1], w[1], d[1], /* Values */ c[2], w[2], d[2], /* 1-right neighbors */ c[3], w[3], d[3]); /* 2-right neighbors */ for(int i=2; i static inline void discretize( real_t const cell_size, real_t const dt, real_t const cb0, real_t const wb0, real_t const db0, real_t const cb1, real_t const wb1, real_t const db1, real_t const cb2, real_t const wb2, real_t const db2, real_t const cb3, real_t const wb3, real_t const db3, real_t const conc_in[N], real_t const wind[N], real_t const diff[N], real_t conc_out[N]) { real_t c[N]; real_t dcdx[N]; conc_out[:] = conc_in[:]; c[:] = conc_in[:]; space_advec_diff( cell_size, cb0, wb0, db0, cb1, wb1, db1, cb2, wb2, db2, cb3, wb3, db3, conc_in, wind, diff, dcdx); c[:] += dt * dcdx[:]; space_advec_diff( cell_size, cb0, wb0, db0, cb1, wb1, db1, cb2, wb2, db2, cb3, wb3, db3, c, wind, diff, dcdx); c[:] += dt * dcdx[:]; conc_out[:] = 0.5 * (conc_out[:] + c[:]); } template < size_t NROWS, size_t NCOLS > void discretize(real_t const dx, real_t const dt, real_t (*conc)[NCOLS], real_t (*wind)[NCOLS], real_t (*diff)[NCOLS]) { TIMER_START("Discret"); #pragma omp parallel { /* Buffers */ real_t buff[NCOLS]; #pragma omp for for (int i = 0; i < NROWS; i++) { real_t cb0 = conc[i][NCOLS - 2]; real_t cb1 = conc[i][NCOLS - 1]; real_t cb2 = conc[i][0]; real_t cb3 = conc[i][1]; real_t wb0 = wind[i][NCOLS - 2]; real_t wb1 = wind[i][NCOLS - 1]; real_t wb2 = wind[i][0]; real_t wb3 = wind[i][1]; real_t db0 = diff[i][NCOLS - 2]; real_t db1 = diff[i][NCOLS - 1]; real_t db2 = diff[i][0]; real_t db3 = diff[i][1]; discretize(dx, dt, cb0, wb0, db0, cb1, wb1, db1, cb2, wb2, db2, cb3, wb3, db3, conc[i], wind[i], diff[i], buff); conc[i][:] = buff[:]; } } // pragma omp parallel TIMER_STOP("Discret"); } /* * From gnuplot/doc/html/gnuplot.html: * For binary input data, the first element of the first row must contain * the number of data columns. (This number is ignored for ascii input). * Both the coordinates and the data values in a binary input are treated * as single precision floats. Example commands for plotting non-uniform matrix data: * * splot 'file' nonuniform matrix using 1:2:3 # ascii input * splot 'file' binary matrix using 1:2:3 # binary input * * Thus the data organization for non-uniform matrix input is * * ... * ... * ... * : : : : ... : * * which is then converted into triplets: * * * * * : : : * * * * : : : * * These triplets are then converted into gnuplot iso-curves and then gnuplot * proceeds in the usual manner to do the rest of the plotting. */ template < size_t NROWS, size_t NCOLS > int Model::WriteGnuplotBinaryMatrixFile(matrix_t mat, char const * fname) { using namespace std; // Open file for writing FILE * fout = fopen(fname, "wb"); if (!fout) { int err = errno; fprintf(stderr, "ERROR: Can't open '%s' for writing\n", fname); return err; } size_t nmemb = NCOLS + 1; float buffer[nmemb]; // Write ncols and column indices as float values buffer[0] = (float)NCOLS; for (int j=0; j void Model::WriteConcFile(void) { TIMER_START("File I/O"); // Build filename char fname[512]; sprintf(fname, "fixedgrid_%03d_%05ld.dat", run_id, step); if (WriteGnuplotBinaryMatrixFile(conc, fname)) { std::cerr << "ERROR: Failed to write '" << fname << "'" << std::endl; } else { std::cout << "Wrote '" << fname << "'" << std::endl; } TIMER_STOP("File I/O"); } template < size_t NROWS, size_t NCOLS > void Model::Step(real_t tstart, real_t tend, real_t dt) { TIMER_START("Step"); for(time=tstart; time < tend; time += dt) { //cout << " Step " << step << ": Time = " << time << endl; if (row_discret) { discretize(dx, 0.5*dt, conc, wind_u, diff); } if (col_discret) { // Transpose TIMER_START("Transpose"); mkl_simatcopy('R', 'T', NROWS, NCOLS, 1, conc[0], NCOLS, NROWS); mkl_simatcopy('R', 'T', NROWS, NCOLS, 1, diff[0], NCOLS, NROWS); TIMER_STOP("Transpose"); discretize(dy, dt, (transposed_t)conc, wind_v, (transposed_t)diff); // Transpose TIMER_START("Transpose"); mkl_simatcopy('R', 'T', NCOLS, NROWS, 1, conc[0], NROWS, NCOLS); mkl_simatcopy('R', 'T', NCOLS, NROWS, 1, diff[0], NROWS, NCOLS); TIMER_STOP("Transpose"); } if (row_discret) { discretize(dx, 0.5*dt, conc, wind_u, diff); } ++step; /* * Could update wind field here... */ /* * Could update diffusion tensor here... */ /* * Could update environment here... */ /* Store concentration */ if (write_each_iter) { WriteConcFile(); } } TIMER_STOP("Step"); } } // namespace fixedgrid #endif 0 #include #include #include TEST (peer_container, empty_peers) { badem::system system (24000, 1); badem::network & network (system.nodes[0]->network); system.nodes[0]->network.cleanup (std::chrono::steady_clock::now ()); ASSERT_EQ (0, network.size ()); } TEST (peer_container, no_recontact) { badem::system system (24000, 1); badem::network & network (system.nodes[0]->network); auto observed_peer (0); auto observed_disconnect (false); badem::endpoint endpoint1 (boost::asio::ip::address_v6::loopback (), 10000); ASSERT_EQ (0, network.size ()); network.channel_observer = [&observed_peer](std::shared_ptr) { ++observed_peer; }; system.nodes[0]->network.disconnect_observer = [&observed_disconnect]() { observed_disconnect = true; }; auto channel (network.udp_channels.insert (endpoint1, system.nodes[0]->network_params.protocol.protocol_version)); ASSERT_EQ (1, network.size ()); ASSERT_EQ (channel, network.udp_channels.insert (endpoint1, system.nodes[0]->network_params.protocol.protocol_version)); system.nodes[0]->network.cleanup (std::chrono::steady_clock::now () + std::chrono::seconds (5)); ASSERT_TRUE (network.empty ()); ASSERT_EQ (1, observed_peer); ASSERT_TRUE (observed_disconnect); } TEST (peer_container, no_self_incoming) { badem::system system (24000, 1); ASSERT_EQ (nullptr, system.nodes[0]->network.udp_channels.insert (system.nodes[0]->network.endpoint (), 0)); ASSERT_TRUE (system.nodes[0]->network.empty ()); } TEST (peer_container, reserved_peers_no_contact) { badem::system system (24000, 1); auto & channels (system.nodes[0]->network.udp_channels); ASSERT_EQ (nullptr, channels.insert (badem::endpoint (boost::asio::ip::address_v6::v4_mapped (boost::asio::ip::address_v4 (0x00000001)), 10000), 0)); ASSERT_EQ (nullptr, channels.insert (badem::endpoint (boost::asio::ip::address_v6::v4_mapped (boost::asio::ip::address_v4 (0xc0000201)), 10000), 0)); ASSERT_EQ (nullptr, channels.insert (badem::endpoint (boost::asio::ip::address_v6::v4_mapped (boost::asio::ip::address_v4 (0xc6336401)), 10000), 0)); ASSERT_EQ (nullptr, channels.insert (badem::endpoint (boost::asio::ip::address_v6::v4_mapped (boost::asio::ip::address_v4 (0xcb007101)), 10000), 0)); ASSERT_EQ (nullptr, channels.insert (badem::endpoint (boost::asio::ip::address_v6::v4_mapped (boost::asio::ip::address_v4 (0xe9fc0001)), 10000), 0)); ASSERT_EQ (nullptr, channels.insert (badem::endpoint (boost::asio::ip::address_v6::v4_mapped (boost::asio::ip::address_v4 (0xf0000001)), 10000), 0)); ASSERT_EQ (nullptr, channels.insert (badem::endpoint (boost::asio::ip::address_v6::v4_mapped (boost::asio::ip::address_v4 (0xffffffff)), 10000), 0)); ASSERT_EQ (0, system.nodes[0]->network.size ()); } TEST (peer_container, split) { badem::system system (24000, 1); auto now (std::chrono::steady_clock::now ()); badem::endpoint endpoint1 (boost::asio::ip::address_v6::loopback (), 100); badem::endpoint endpoint2 (boost::asio::ip::address_v6::loopback (), 101); auto channel1 (system.nodes[0]->network.udp_channels.insert (endpoint1, 0)); ASSERT_NE (nullptr, channel1); system.nodes[0]->network.udp_channels.modify (channel1, [&now](auto channel) { channel->set_last_packet_received (now - std::chrono::seconds (1)); }); auto channel2 (system.nodes[0]->network.udp_channels.insert (endpoint2, 0)); ASSERT_NE (nullptr, channel2); system.nodes[0]->network.udp_channels.modify (channel2, [&now](auto channel) { channel->set_last_packet_received (now + std::chrono::seconds (1)); }); ASSERT_EQ (2, system.nodes[0]->network.size ()); ASSERT_EQ (2, system.nodes[0]->network.udp_channels.size ()); system.nodes[0]->network.cleanup (now); ASSERT_EQ (1, system.nodes[0]->network.size ()); ASSERT_EQ (1, system.nodes[0]->network.udp_channels.size ()); auto list (system.nodes[0]->network.list (1)); ASSERT_EQ (endpoint2, list[0]->get_endpoint ()); } TEST (channels, fill_random_clear) { badem::system system (24000, 1); std::array target; std::fill (target.begin (), target.end (), badem::endpoint (boost::asio::ip::address_v6::loopback (), 10000)); system.nodes[0]->network.random_fill (target); ASSERT_TRUE (std::all_of (target.begin (), target.end (), [](badem::endpoint const & endpoint_a) { return endpoint_a == badem::endpoint (boost::asio::ip::address_v6::any (), 0); })); } TEST (channels, fill_random_full) { badem::system system (24000, 1); for (uint16_t i (0u); i < 100u; ++i) { system.nodes[0]->network.udp_channels.insert (badem::endpoint (boost::asio::ip::address_v6::loopback (), i), 0); } std::array target; std::fill (target.begin (), target.end (), badem::endpoint (boost::asio::ip::address_v6::loopback (), 10000)); system.nodes[0]->network.random_fill (target); ASSERT_TRUE (std::none_of (target.begin (), target.end (), [](badem::endpoint const & endpoint_a) { return endpoint_a == badem::endpoint (boost::asio::ip::address_v6::loopback (), 10000); })); } TEST (channels, fill_random_part) { badem::system system (24000, 1); std::array target; auto half (target.size () / 2); for (auto i (0); i < half; ++i) { system.nodes[0]->network.udp_channels.insert (badem::endpoint (boost::asio::ip::address_v6::loopback (), i + 1), 0); } std::fill (target.begin (), target.end (), badem::endpoint (boost::asio::ip::address_v6::loopback (), 10000)); system.nodes[0]->network.random_fill (target); ASSERT_TRUE (std::none_of (target.begin (), target.begin () + half, [](badem::endpoint const & endpoint_a) { return endpoint_a == badem::endpoint (boost::asio::ip::address_v6::loopback (), 10000); })); ASSERT_TRUE (std::none_of (target.begin (), target.begin () + half, [](badem::endpoint const & endpoint_a) { return endpoint_a == badem::endpoint (boost::asio::ip::address_v6::loopback (), 0); })); ASSERT_TRUE (std::all_of (target.begin () + half, target.end (), [](badem::endpoint const & endpoint_a) { return endpoint_a == badem::endpoint (boost::asio::ip::address_v6::any (), 0); })); } TEST (peer_container, list_fanout) { badem::system system (24000, 1); auto list1 (system.nodes[0]->network.list_fanout ()); ASSERT_TRUE (list1.empty ()); for (auto i (0); i < 1000; ++i) { ASSERT_NE (nullptr, system.nodes[0]->network.udp_channels.insert (badem::endpoint (boost::asio::ip::address_v6::loopback (), 10000 + i), system.nodes[0]->network_params.protocol.protocol_version)); } auto list2 (system.nodes[0]->network.list_fanout ()); ASSERT_EQ (32, list2.size ()); } // Test to make sure we don't repeatedly send keepalive messages to nodes that aren't responding TEST (peer_container, reachout) { badem::system system (24000, 1); badem::endpoint endpoint0 (boost::asio::ip::address_v6::loopback (), 24000); // Make sure having been contacted by them already indicates we shouldn't reach out system.nodes[0]->network.udp_channels.insert (endpoint0, system.nodes[0]->network_params.protocol.protocol_version); ASSERT_TRUE (system.nodes[0]->network.reachout (endpoint0)); badem::endpoint endpoint1 (boost::asio::ip::address_v6::loopback (), 24001); ASSERT_FALSE (system.nodes[0]->network.reachout (endpoint1)); // Reaching out to them once should signal we shouldn't reach out again. ASSERT_TRUE (system.nodes[0]->network.reachout (endpoint1)); // Make sure we don't purge new items system.nodes[0]->network.cleanup (std::chrono::steady_clock::now () - std::chrono::seconds (10)); ASSERT_TRUE (system.nodes[0]->network.reachout (endpoint1)); // Make sure we purge old items system.nodes[0]->network.cleanup (std::chrono::steady_clock::now () + std::chrono::seconds (10)); ASSERT_FALSE (system.nodes[0]->network.reachout (endpoint1)); } TEST (peer_container, depeer) { badem::system system (24000, 1); badem::endpoint endpoint0 (boost::asio::ip::address_v6::loopback (), 24001); badem::keepalive message; message.header.version_using = 1; auto bytes (message.to_bytes ()); badem::message_buffer buffer = { bytes->data (), bytes->size (), endpoint0 }; system.nodes[0]->network.udp_channels.receive_action (&buffer); ASSERT_EQ (1, system.nodes[0]->stats.count (badem::stat::type::udp, badem::stat::detail::outdated_version)); } /** \file * \author <> * \section LICENSE * Copyright (c) 2014, . * All rights reserved. * This file is licensed under the "BSD 3-Clause License". * Full license text is under the file "LICENSE" provided with this code. */ #ifndef _CONNECTION_HPP_ #define _CONNECTION_HPP_ namespace SphereSim { /** \brief Connection details for client and server. */ namespace Connection { /** \brief The address the server listens to. */ extern const char* listeningAddress; /** \brief The address the client connects to. */ extern const char* address; /** \brief The port that the client listens to. */ extern unsigned short serverSendPort; /** \brief The port that the server listens to. */ extern unsigned short serverRecvPort; } } #endif /*_CONNECTION_HPP_*/ /*@@@ File: df.cxx Version: 1.00 Description: Class DF - Data Field Author: , @@@*/ #include "df.hxx" DF::DF() { } DF& DF::operator=(const DF& OtherDf) { FieldName = OtherDf.FieldName; Fct = OtherDf.Fct; return *this; } void DF::SetFieldName(const STRING& NewFieldName) { FieldName = NewFieldName; FieldName.UpperCase(); } void DF::GetFieldName(PSTRING StringBuffer) const { *StringBuffer = FieldName; } void DF::SetFct(const FCT& NewFct) { Fct = NewFct; } void DF::GetFct(PFCT FctBuffer) const { *FctBuffer = Fct; } void DF::Write(PFILE fp) const { FieldName.Print(fp); fprintf(fp, "\n"); Fct.Write(fp); } void DF::Read(PFILE fp) { FieldName.FGet(fp, 256); Fct.Read(fp); } DF::~DF() { } #include "stdafx.h" #include "IGameBase.h" jwarrencode/USD // // Copyright 2021 Pixar // // Licensed under the Apache License, Version 2.0 (the "Apache License") // with the following modification; you may not use this file except in // compliance with the Apache License and the following modification to it: // Section 6. Trademarks. is deleted and replaced with: // // 6. Trademarks. This License does not grant permission to use the trade // names, trademarks, service marks, or product names of the Licensor // and its affiliates, except as required to comply with Section 4(c) of // the License and to reproduce the content of the NOTICE file. // // You may obtain a copy of the Apache License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the Apache License with the above modification is // distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the Apache License for the specific // language governing permissions and limitations under the Apache License. // #include "pxr/imaging/hd/dataSourceMaterialNetworkInterface.h" #include "pxr/imaging/hd/materialConnectionSchema.h" #include "pxr/imaging/hd/materialNetworkSchema.h" #include "pxr/imaging/hd/materialNodeSchema.h" #include "pxr/imaging/hd/retainedDataSource.h" PXR_NAMESPACE_OPEN_SCOPE HdContainerDataSourceHandle HdDataSourceMaterialNetworkInterface::_GetNode( const TfToken &nodeName) const { if (_deletedNodes.find(nodeName) != _deletedNodes.end()) { return nullptr; } if (nodeName == _lastAccessedNodeName) { return _lastAccessedNode; } if (!_nodesContainer) { _nodesContainer = HdMaterialNetworkSchema(_networkContainer).GetNodes(); } _lastAccessedNodeName = nodeName; _lastAccessedNode = nullptr; _lastAccessedNodeParameters = nullptr; _lastAccessedNodeConnections = nullptr; if (!_nodesContainer) { return nullptr; } _lastAccessedNode = HdContainerDataSource::Cast(_nodesContainer->Get(nodeName)); return _lastAccessedNode; } HdContainerDataSourceHandle HdDataSourceMaterialNetworkInterface::_GetNodeParameters( const TfToken &nodeName) const { if (HdContainerDataSourceHandle node = _GetNode(nodeName)) { if (_lastAccessedNodeParameters) { return _lastAccessedNodeParameters; } _lastAccessedNodeParameters = HdMaterialNodeSchema(node).GetParameters(); return _lastAccessedNodeParameters; } return nullptr; } HdContainerDataSourceHandle HdDataSourceMaterialNetworkInterface::_GetNodeConnections( const TfToken &nodeName) const { if (HdContainerDataSourceHandle node = _GetNode(nodeName)) { if (_lastAccessedNodeConnections) { return _lastAccessedNodeConnections; } _lastAccessedNodeConnections = HdMaterialNodeSchema(node).GetInputConnections(); return _lastAccessedNodeConnections; } return nullptr; } void HdDataSourceMaterialNetworkInterface::_SetOverride( const HdDataSourceLocator &loc, const HdDataSourceBaseHandle &ds) { _containerEditor.Set(loc, ds); _existingOverrides[loc] = ds; static const HdDataSourceLocator nodesLocator( HdMaterialNetworkSchemaTokens->nodes); static const HdDataSourceLocator terminalsLocator( HdMaterialNetworkSchemaTokens->terminals); if (loc.Intersects(nodesLocator) && loc.GetElementCount() > 1) { _overriddenNodes.insert(loc.GetElement(1)); _deletedNodes.erase(loc.GetElement(1)); } else if(loc.Intersects(terminalsLocator)) { _terminalsOverridden = true; } } TfTokenVector HdDataSourceMaterialNetworkInterface::GetNodeNames() const { if (!_nodesContainer) { _nodesContainer = HdMaterialNetworkSchema(_networkContainer).GetNodes(); } if (!_nodesContainer) { return {}; } TfTokenVector result = _nodesContainer->GetNames(); if (!_deletedNodes.empty()) { std::unordered_set nameSet; nameSet.insert(result.begin(), result.end()); for (const TfToken &deletedName : _deletedNodes) { nameSet.erase(deletedName); } result.clear(); result.insert(result.end(), nameSet.begin(), nameSet.end()); } return result; } TfToken HdDataSourceMaterialNetworkInterface::GetNodeType( const TfToken &nodeName) const { HdDataSourceLocator locator( HdMaterialNetworkSchemaTokens->nodes, nodeName, HdMaterialNodeSchemaTokens->nodeIdentifier); const auto it = _existingOverrides.find(locator); if (it != _existingOverrides.end()) { if (HdTypedSampledDataSource::Handle ds = HdTypedSampledDataSource::Cast(it->second)) { return ds->GetTypedValue(0.0f); } else { // if not a token, it's deleterd. return TfToken(); } } HdMaterialNodeSchema node(_GetNode(nodeName)); if (node) { if (HdTokenDataSourceHandle idDs = node.GetNodeIdentifier()) { return idDs->GetTypedValue(0.0f); } } return TfToken(); } TfTokenVector HdDataSourceMaterialNetworkInterface::GetAuthoredNodeParameterNames( const TfToken &nodeName) const { TfTokenVector result; if (HdContainerDataSourceHandle params = _GetNodeParameters(nodeName)) { result = params->GetNames(); } if (_overriddenNodes.find(nodeName) != _overriddenNodes.end()) { HdDataSourceLocator paramsLocator( HdMaterialNetworkSchemaTokens->nodes, nodeName, HdMaterialNodeSchemaTokens->parameters); std::unordered_set nameSet; nameSet.insert(result.begin(), result.end()); for (const auto &locDsPair : _existingOverrides) { // anything with this prefix will have at least 4 elements if (locDsPair.first.HasPrefix(paramsLocator)) { if (locDsPair.second) { nameSet.insert(locDsPair.first.GetElement(3)); } else { nameSet.erase(locDsPair.first.GetElement(3)); } } } result.clear(); result.insert(result.end(), nameSet.begin(), nameSet.end()); } return result; } VtValue HdDataSourceMaterialNetworkInterface::GetNodeParameterValue( const TfToken &nodeName, const TfToken ¶mName) const { // check overrides for existing value HdDataSourceLocator locator( HdMaterialNetworkSchemaTokens->nodes, nodeName, HdMaterialNodeSchemaTokens->parameters, paramName); const auto it = _existingOverrides.find(locator); if (it != _existingOverrides.end()) { if (HdSampledDataSourceHandle sds = HdSampledDataSource::Cast(it->second)) { return sds->GetValue(0.0f); } else { // overriden with nullptr data source means deletion return VtValue(); } } if (HdContainerDataSourceHandle params = _GetNodeParameters(nodeName)) { if (HdSampledDataSourceHandle param = HdSampledDataSource::Cast(params->Get(paramName))) { return param->GetValue(0.0f); } } return VtValue(); } TfTokenVector HdDataSourceMaterialNetworkInterface::GetNodeInputConnectionNames( const TfToken &nodeName) const { TfTokenVector result; if (HdContainerDataSourceHandle inputs = _GetNodeConnections(nodeName)) { result = inputs->GetNames(); } if (_overriddenNodes.find(nodeName) != _overriddenNodes.end()) { HdDataSourceLocator inputsLocator( HdMaterialNetworkSchemaTokens->nodes, nodeName, HdMaterialNodeSchemaTokens->inputConnections); std::unordered_set nameSet; nameSet.insert(result.begin(), result.end()); for (const auto &locDsPair : _existingOverrides) { // anything with this prefix will have at least 4 elements if (locDsPair.first.HasPrefix(inputsLocator)) { if (locDsPair.second) { nameSet.insert(locDsPair.first.GetElement(3)); } else { nameSet.erase(locDsPair.first.GetElement(3)); } } } result.clear(); result.insert(result.end(), nameSet.begin(), nameSet.end()); } return result; } HdMaterialNetworkInterface::InputConnectionVector HdDataSourceMaterialNetworkInterface::GetNodeInputConnection( const TfToken &nodeName, const TfToken &inputName) const { // check overrides for existing value HdDataSourceLocator locator( HdMaterialNetworkSchemaTokens->nodes, nodeName, HdMaterialNodeSchemaTokens->inputConnections, inputName); HdVectorDataSourceHandle connectionVectorDs; const auto it = _existingOverrides.find(locator); if (it != _existingOverrides.end()) { if (HdVectorDataSourceHandle vds = HdVectorDataSource::Cast(it->second)) { connectionVectorDs = vds; } else { // overridden with nullptr means deletion return {}; } } if (!connectionVectorDs) { if (HdContainerDataSourceHandle inputs = _GetNodeConnections(nodeName)) { connectionVectorDs = HdVectorDataSource::Cast(inputs->Get(inputName)); } } if (!connectionVectorDs) { return {}; } size_t e = connectionVectorDs->GetNumElements(); InputConnectionVector result; result.reserve(e); for (size_t i = 0; i < e; ++i) { HdMaterialConnectionSchema c(HdContainerDataSource::Cast( connectionVectorDs->GetElement(i))); if (c) { HdTokenDataSourceHandle nodeNameDs = c.GetUpstreamNodePath(); HdTokenDataSourceHandle outputNameDs = c.GetUpstreamNodeOutputName(); if (nodeNameDs && outputNameDs) { result.push_back({ nodeNameDs->GetTypedValue(0.0f), outputNameDs->GetTypedValue(0.0f)}); } } } return result; } void HdDataSourceMaterialNetworkInterface::DeleteNode(const TfToken &nodeName) { HdDataSourceLocator locator( HdMaterialNetworkSchemaTokens->nodes, nodeName); _containerEditor.Set(locator, nullptr); _deletedNodes.insert(nodeName); } void HdDataSourceMaterialNetworkInterface::SetNodeType( const TfToken &nodeName, const TfToken &nodeType) { HdDataSourceLocator locator( HdMaterialNetworkSchemaTokens->nodes, nodeName, HdMaterialNodeSchemaTokens->nodeIdentifier); HdDataSourceBaseHandle ds = HdRetainedTypedSampledDataSource::New(nodeType); _SetOverride(locator, ds); } void HdDataSourceMaterialNetworkInterface::SetNodeParameterValue( const TfToken &nodeName, const TfToken ¶mName, const VtValue &value) { HdDataSourceLocator locator( HdMaterialNetworkSchemaTokens->nodes, nodeName, HdMaterialNodeSchemaTokens->parameters, paramName); HdDataSourceBaseHandle ds = HdRetainedSampledDataSource::New(value); _SetOverride(locator, ds); } void HdDataSourceMaterialNetworkInterface::DeleteNodeParameter( const TfToken &nodeName, const TfToken ¶mName) { HdDataSourceLocator locator( HdMaterialNetworkSchemaTokens->nodes, nodeName, HdMaterialNodeSchemaTokens->parameters, paramName); _SetOverride(locator, nullptr); } void HdDataSourceMaterialNetworkInterface::SetNodeInputConnection( const TfToken &nodeName, const TfToken &inputName, const InputConnectionVector &connections) { HdDataSourceLocator locator( HdMaterialNetworkSchemaTokens->nodes, nodeName, HdMaterialNodeSchemaTokens->inputConnections, inputName); std::vector groups; groups.reserve(connections.size()); using TDS = HdRetainedTypedSampledDataSource; for (const InputConnection &c : connections) { groups.push_back(HdMaterialConnectionSchema::Builder() .SetUpstreamNodePath(TDS::New(c.upstreamNodeName)) .SetUpstreamNodeOutputName(TDS::New(c.upstreamOutputName)) .Build()); } HdDataSourceBaseHandle ds = HdRetainedSmallVectorDataSource::New(groups.size(), groups.data()); _SetOverride(locator, ds); } void HdDataSourceMaterialNetworkInterface::DeleteNodeInputConnection( const TfToken &nodeName, const TfToken &inputName) { HdDataSourceLocator locator( HdMaterialNetworkSchemaTokens->nodes, nodeName, HdMaterialNodeSchemaTokens->inputConnections, inputName); _SetOverride(locator, nullptr); } TfTokenVector HdDataSourceMaterialNetworkInterface::GetTerminalNames() const { TfTokenVector result; HdContainerDataSourceHandle terminals = HdMaterialNetworkSchema(_networkContainer).GetTerminals(); if (terminals) { result = terminals->GetNames(); } if (_terminalsOverridden) { static const HdDataSourceLocator terminalsLocator( HdMaterialNetworkSchemaTokens->terminals); std::unordered_set nameSet; nameSet.insert(result.begin(), result.end()); for (const auto &locDsPair : _existingOverrides) { // anything with this prefix will have at least 2 elements if (locDsPair.first.HasPrefix(terminalsLocator)) { if (locDsPair.second) { nameSet.insert(locDsPair.first.GetElement(1)); } else { nameSet.erase(locDsPair.first.GetElement(1)); } } } result.clear(); result.insert(result.end(), nameSet.begin(), nameSet.end()); } return result; } HdMaterialNetworkInterface::InputConnectionResult HdDataSourceMaterialNetworkInterface::GetTerminalConnection( const TfToken &terminalName) const { HdDataSourceLocator locator( HdMaterialNetworkSchemaTokens->terminals, terminalName); HdContainerDataSourceHandle container = nullptr; const auto it = _existingOverrides.find(locator); if (it != _existingOverrides.end()) { container = HdContainerDataSource::Cast(it->second); // If it's set but still isn't a container then it's been deleted if (!container) { return {false, {TfToken(), TfToken()}}; } } if (!container) { HdContainerDataSourceHandle terminals = HdMaterialNetworkSchema(_networkContainer).GetTerminals(); if (terminals) { container = HdContainerDataSource::Cast(terminals->Get(terminalName)); } } HdMaterialConnectionSchema connectionSchema(container); if (connectionSchema) { InputConnectionResult result = {true, {TfToken(), TfToken()}}; if (HdTypedSampledDataSource::Handle ds = connectionSchema.GetUpstreamNodePath()) { result.second.upstreamNodeName = ds->GetTypedValue(0.0f); } else { result.first = false; } // output name is optional for a terminal if (HdTypedSampledDataSource::Handle ds = connectionSchema.GetUpstreamNodeOutputName()) { result.second.upstreamOutputName = ds->GetTypedValue(0.0f); } return result; } return {false, {TfToken(), TfToken()}}; } void HdDataSourceMaterialNetworkInterface::DeleteTerminal( const TfToken &terminalName) { HdDataSourceLocator locator( HdMaterialNetworkSchemaTokens->terminals, terminalName); _SetOverride(locator, nullptr); } void HdDataSourceMaterialNetworkInterface::SetTerminalConnection( const TfToken &terminalName, const InputConnection &connection) { HdDataSourceLocator locator( HdMaterialNetworkSchemaTokens->terminals, terminalName); HdContainerDataSourceHandle ds = HdMaterialConnectionSchema::Builder() .SetUpstreamNodePath( HdRetainedTypedSampledDataSource::New( connection.upstreamNodeName)) .SetUpstreamNodeOutputName( HdRetainedTypedSampledDataSource::New( connection.upstreamOutputName)) .Build(); _SetOverride(locator, ds); } HdContainerDataSourceHandle HdDataSourceMaterialNetworkInterface::Finish() { if (_existingOverrides.empty()) { return _networkContainer; } return _containerEditor.Finish(); } PXR_NAMESPACE_CLOSE_SCOPE 0 /* 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. */ #include "stdafx.h" #include "FastHeaps.h" #include Boolean DeAlloc(Pointer Ptr) { Ptr = *(PPointer)((NativeUInt)Ptr - sizeof(TBlockHeader)); (*((PNativeUInt)Ptr))--; if (*(PNativeUInt)Ptr > 0) return false; free(Ptr); return true; } /* TFastHeap */ Pointer AllocBlockInPage(Pointer APage, NativeUInt AOffset) { Pointer Result = (Pointer)((NativeUInt)APage + AOffset); ((PBlock)Result)->Header.PagePointer = (PPage)APage; ((PPage)APage)->Header.RefCount++; return &((PBlock)Result)->Data; } TFastHeap::~TFastHeap() { if (FStartBlockArray != nullptr) { ((PPage)FStartBlockArray)->Header.RefCount--; if (((PPage)FStartBlockArray)->Header.RefCount <= 0) DeallocateMemory(FStartBlockArray); } } void TFastHeap::AllocNewBlockArray() { if (FStartBlockArray != nullptr && ((PPage)FStartBlockArray)->Header.RefCount == 1) FNextOffset = sizeof(TPageHeader); else { if (FStartBlockArray != nullptr) ((PPage)FStartBlockArray)->Header.RefCount--; AllocateMemory(FStartBlockArray, FPageSize); ((PPage)FStartBlockArray)->Header.RefCount = 1; FNextOffset = sizeof(TPageHeader); } } void TFastHeap::DeAlloc(Pointer Ptr) { ::DeAlloc(Ptr); } void TFastHeap::AllocateMemory(Pointer &APtr, NativeUInt ASize) { APtr = malloc(ASize); } void TFastHeap::DeallocateMemory(Pointer APtr) { free(APtr); } Integer TFastHeap::GetCurrentBlockRefCount() { return ((PPage)FStartBlockArray)->Header.RefCount; } /* TFixedBlockHeap */ TFixedBlockHeap::TFixedBlockHeap(NativeUInt ABlockSize, NativeUInt ABlockCount) { FOriginalBlockSize = ABlockSize; FBlockSize = (ABlockSize + sizeof(TBlockHeader) + Aligner) & (~Aligner); FTotalUsableSize = FBlockSize * ABlockCount; FPageSize = FTotalUsableSize + sizeof(TPageHeader); FNextOffset = FPageSize; } Pointer TFixedBlockHeap::Alloc() { if (FNextOffset >= FPageSize) AllocNewBlockArray(); Pointer Result = AllocBlockInPage(FStartBlockArray, FNextOffset); FNextOffset += FBlockSize; return Result; } /* TVariableBlockHeap */ TVariableBlockHeap::TVariableBlockHeap(NativeUInt APoolSize) { FTotalUsableSize = (APoolSize + Aligner) & (~Aligner); FPageSize = FTotalUsableSize + sizeof(TPageHeader); FNextOffset = FPageSize; } Pointer TVariableBlockHeap::Alloc(NativeUInt ASize) { Pointer Result; ASize = (ASize + sizeof(TBlockHeader) + Aligner) & (~Aligner); // Align size to native word size bits if (ASize <= FTotalUsableSize) { if (FNextOffset + ASize >= FPageSize) AllocNewBlockArray(); Result = AllocBlockInPage(FStartBlockArray, FNextOffset); FNextOffset += ASize; } else { AllocateMemory(Result, sizeof(TPageHeader) + ASize); ((PPage)Result)->Header.RefCount = 0; Result = AllocBlockInPage(PPage(Result), sizeof(TPageHeader)); } return Result; }#ifndef PASTEL_UTILITY_TUPLE_META_TRANSFORM_HPP # define PASTEL_UTILITY_TUPLE_META_TRANSFORM_HPP # include # include namespace pastel { namespace utility { namespace tuple { namespace meta { namespace transform_detail { template typename Operation, typename... Args> struct transform; template typename Operation, typename Type, typename... Args> struct transform, Operation, Type, Args...> : ::pastel::utility::tuple::meta::transform_detail::transform< std::tuple::type>, Operation, Args...> { }; template typename Operation> struct transform { using type = Result; }; template typename Operation> struct transform2; template typename Operation> struct transform2, std::tuple, std::tuple, Operation> : ::pastel::utility::tuple::meta::transform_detail::transform2< std::tuple::type>, std::tuple, std::tuple, Operation> { }; template typename Operation> struct transform2, std::tuple, Operation> { using type = Result; }; template typename Operation> struct transform2, std::tuple<>, Operation> { using type = Result; }; template typename Operation> struct transform2, std::tuple<>, Operation> { using type = Result; }; } // namespace transform_detail template typename Operation> struct transform; template typename Operation> struct transform, Operation> : ::pastel::utility::tuple::meta::transform_detail::transform, Operation, Args...> { }; template typename Operation> struct transform2; template typename Operation> struct transform2, std::tuple, Operation> : ::pastel::utility::tuple::meta::transform_detail::transform2, std::tuple, std::tuple, Operation> { }; } // namespace meta } // namespace tuple } // namespace utility } // namespace pastel #endif // PASTEL_UTILITY_TUPLE_META_TRANSFORM_HPP #pragma once #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 #include #include "AudioDevice.h" #include #include #include #include static RingBufferT buffer(BUFFER_LENGTH); static int rt_callback(void * output_buffer, void * input_buffer, unsigned int num_bufferframes, double stream_time, RtAudioStreamStatus status, void * user_data) { if (status) std::cerr << "[rtaudio] Buffer over or underflow" << std::endl; if (buffer.getAvailableRead()) { buffer.read((float*) output_buffer, BUFFER_LENGTH); } else { memset(output_buffer, 0, BUFFER_LENGTH * sizeof(float)); } return 0; } AudioDevice::AudioDevice(int numChannels, int sampleRate, int deviceId) { rtaudio = std::unique_ptr(new RtAudio); info.id = deviceId != -1 ? deviceId : rtaudio->getDefaultOutputDevice(); info.numChannels = numChannels; info.sampleRate = sampleRate; info.frameSize = FRAME_SIZE; } AudioDevice::~AudioDevice() { if (rtaudio) { rtaudio->stopStream(); if (rtaudio->isStreamOpen()) rtaudio->closeStream(); } } bool AudioDevice::Open(const int deviceId) { if (!rtaudio) throw std::runtime_error("rtaudio not created yet"); RtAudio::StreamParameters parameters; parameters.deviceId = info.id; parameters.nChannels = info.numChannels; parameters.firstChannel = 0; rtaudio->openStream(¶meters, NULL, RTAUDIO_FLOAT32, info.sampleRate, &info.frameSize, &rt_callback, (void*) & buffer); if (rtaudio->isStreamOpen()) { rtaudio->startStream(); return true; } return false; } void AudioDevice::ListAudioDevices() { std::unique_ptr tempDevice(new RtAudio); RtAudio::DeviceInfo info; unsigned int devices = tempDevice->getDeviceCount(); std::cout << "[rtaudio] Found: " << devices << " device(s)\n"; for (unsigned int i = 0; i < devices; ++i) { info = tempDevice->getDeviceInfo(i); std::cout << "\tDevice: " << i << " - " << info.name << std::endl; } std::cout << std::endl; } bool AudioDevice::Play(const std::vector & data) { if (!rtaudio->isStreamOpen()) return false; // Each frame is the (size/2) cause interleaved channels! int sizeInFrames = ((int) data.size()) / (BUFFER_LENGTH); int writeCount = 0; while(writeCount < sizeInFrames) { bool status = buffer.write((data.data() + (writeCount * BUFFER_LENGTH)), BUFFER_LENGTH); if (status) writeCount++; } return true; }// Copyright (c) 2014 // Copyright (c) 2014 // Copyright (c) 2018 // // 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) // This is the fourth in a series of examples demonstrating the development of // a fully distributed solver for a simple 1D heat distribution problem. // // This example builds on example three. It futurizes the code from that // example. Compared to example two this code runs much more efficiently. It // allows for changing the amount of work executed in one HPX thread which // enables tuning the performance for the optimal grain size of the // computation. This example is still fully local but demonstrates nice // scalability on SMP machines. // // In this variation of stencil we use the save_checkpoint and // revive_checkpint functions to back up the state of the application // every n time steps. // #include #include #include #include #include #include #include #include #include #include #include #include #include #include "print_time_results.hpp" /////////////////////////////////////////////////////////////////////////////// // Command-line variables bool header = true; // print csv heading double k = 0.5; // heat transfer coefficient double dt = 1.; // time step double dx = 1.; // grid spacing inline std::size_t idx(std::size_t i, int dir, std::size_t size) { if (i == 0 && dir == -1) return size - 1; if (i == size - 1 && dir == +1) return 0; HPX_ASSERT((i + dir) < size); return i + dir; } /////////////////////////////////////////////////////////////////////////////// // Our partition data type struct partition_data { private: typedef hpx::serialization::serialize_buffer buffer_type; public: partition_data() : data_() , size_(0) { } partition_data(std::size_t size) : data_(std::allocator().allocate(size), size, buffer_type::take) , size_(size) { } partition_data(std::size_t size, double initial_value) : data_(std::allocator().allocate(size), size, buffer_type::take) , size_(size) { double base_value = double(initial_value * size); for (std::size_t i = 0; i != size; ++i) data_[i] = base_value + double(i); } partition_data(const partition_data& old_part) : data_(std::allocator().allocate(old_part.size()), old_part.size(), buffer_type::take) , size_(old_part.size()) { for (std::size_t i = 0; i < old_part.size(); i++) { data_[i] = old_part[i]; } } double& operator[](std::size_t idx) { return data_[idx]; } double operator[](std::size_t idx) const { return data_[idx]; } std::size_t size() const { return size_; } private: buffer_type data_; std::size_t size_; // Serialization Definitions friend class hpx::serialization::access; template void serialize(Volume& vol, const unsigned int version) { vol& data_& size_; } }; std::ostream& operator<<(std::ostream& os, partition_data const& c) { os << "{"; for (std::size_t i = 0; i != c.size(); ++i) { if (i != 0) os << ", "; os << c[i]; } os << "}"; return os; } /////////////////////////////////////////////////////////////////////////////// // Checkpoint Function struct backup { std::vector bin; std::string file_name_; backup(std::string const& file_name, std::size_t np) : bin(np) , file_name_(file_name) { } backup(backup&& old) : bin(std::move(old.bin)) , file_name_(std::move(old.file_name_)) { } ~backup() {} void save(partition_data const& status, std::size_t index) { bin[index] = hpx::util::save_checkpoint(hpx::launch::sync, status); } void write() { hpx::util::checkpoint archive_data = hpx::util::save_checkpoint(hpx::launch::sync, bin); // Make sure file stream is bianary for Windows/Mac machines std::ofstream file_archive( file_name_, std::ios::binary | std::ios::out); if (file_archive.is_open()) { file_archive << archive_data; } else { std::cout << "Error opening file!" << std::endl; } file_archive.close(); } void revive(std::vector>>& U, std::size_t nx) { hpx::util::checkpoint temp_archive; // Make sure file stream is bianary for Windows/Mac machines std::ifstream ist(file_name_, std::ios::binary | std::ios::in); ist >> temp_archive; hpx::util::restore_checkpoint(temp_archive, bin); for (std::size_t i = 0; i < U[0].size(); i++) { partition_data temp(nx, double(i)); hpx::util::restore_checkpoint(bin[i], temp); //Check for (std::size_t e = 0; e < temp.size(); e++) { std::cout << temp[e] << ", "; } std::cout << std::endl; U[0][i] = hpx::make_ready_future(temp); } } }; void print(std::vector>> U) { for (std::size_t out = 0; out < U[0].size(); out++) { partition_data print_buff(U[0][out].get()); for (std::size_t inner = 0; inner < print_buff.size(); inner++) { std::cout << print_buff[inner] << ", "; if (inner % 9 == 0 && inner != 0) std::cout << std::endl; } } std::cout << std::endl; } void print_space(std::vector> next) { for (std::size_t out = 0; out < next.size(); out++) { partition_data print_buff(next[out].get()); for (std::size_t inner = 0; inner < print_buff.size(); inner++) { std::cout << print_buff[inner] << ", "; if (inner % 9 == 0 && inner != 0) std::cout << std::endl; } } std::cout << std::endl; } /////////////////////////////////////////////////////////////////////////////// struct stepper { // Our data for one time step typedef hpx::shared_future partition; typedef std::vector space; // Our operator static double heat(double left, double middle, double right) { return middle + (k * dt / (dx * dx)) * (left - 2 * middle + right); } // The partitioned operator, it invokes the heat operator above on all // elements of a partition. static partition_data heat_part(partition_data const& left, partition_data const& middle, partition_data const& right) { std::size_t size = middle.size(); partition_data next(size); next[0] = heat(left[size - 1], middle[0], middle[1]); for (std::size_t i = 1; i != size - 1; ++i) { next[i] = heat(middle[i - 1], middle[i], middle[i + 1]); } next[size - 1] = heat(middle[size - 2], middle[size - 1], right[0]); return next; } // do all the work on 'np' partitions, 'nx' data points each, for 'nt' // time steps, limit depth of dependency tree to 'nd' hpx::future do_work(std::size_t np, std::size_t nx, std::size_t nt, std::uint64_t nd, std::uint64_t cp, std::string rsf, std::string fn) { using hpx::dataflow; using hpx::util::unwrapping; // Set up Check-pointing std::size_t num_c = nt / cp; // Number of checkpoints to be made std::cout << "Number of checkpoints to be made: " << num_c << std::endl; std::vector v_file_names(num_c, fn); std::vector container; // Initialize checkpoint file names for (std::size_t i = 0; i < num_c; i++) { v_file_names[i] = v_file_names[i] + "_" + std::to_string((i + 1) * cp); container.push_back(backup(v_file_names[i], np)); } // Container to wait on all held futures std::vector> backup_complete; // U[t][i] is the state of position i at time t. std::vector U(2); for (space& s : U) s.resize(np); // Initial conditions: f(0, i) = i std::size_t b = 0; auto range = boost::irange(b, np); using hpx::parallel::execution::par; hpx::ranges::for_each(par, range, [&U, nx](std::size_t i) { U[0][i] = hpx::make_ready_future(partition_data(nx, double(i))); }); //Initialize from backup if (rsf != "") { backup restart(rsf, np); restart.revive(U, nx); } //Check std::cout << "Initialization Check" << std::endl; print(U); // limit depth of dependency tree hpx::lcos::local::sliding_semaphore sem(nd); auto Op = unwrapping(&stepper::heat_part); // Actual time step loop for (std::size_t t = 0; t != nt; ++t) { space const& current = U[t % 2]; space& next = U[(t + 1) % 2]; for (std::size_t i = 0; i != np; ++i) { next[i] = dataflow(hpx::launch::async, Op, current[idx(i, -1, np)], current[i], current[idx(i, +1, np)]); //Checkpoint if (t % cp == 0 && t != 0) { next[i] = next[i].then([&container, i, t, cp](partition&& p) { partition_data value(p.get()); container[(t / cp) - 1].save(value, i); partition f_value = hpx::make_ready_future(value); return f_value; }); } } //Print Checkpoint to file if (t % cp == 0 && t != 0) { hpx::future f_print = hpx::when_all(next).then( [&container, t, cp](hpx::future&& f_s) { container[(t / cp) - 1].write(); }); backup_complete.push_back(std::move(f_print)); } //Check if (t % cp == 0 && t != 0) { std::cout << "Checkpoint Check:" << std::endl; print_space(next); } // every nd time steps, attach additional continuation which will // trigger the semaphore once computation has reached this point if ((t % nd) == 0) { next[0].then([&sem, t](partition&&) { // inform semaphore about new lower limit sem.signal(t); }); } // suspend if the tree has become too deep, the continuation above // will resume this thread once the computation has caught up sem.wait(t); } // Wait on Checkpoint Printing hpx::wait_all(backup_complete); //Begin Test //Create a new test vector and resize it std::vector Z(2); for (space& y : Z) { y.resize(np); } backup test(v_file_names[0], np); std::cout << std::endl; std::cout << "Revive Check:" << std::endl; test.revive(Z, nx); std::cout << std::endl; //End Test // Return the solution at time-step 'nt'. return hpx::when_all(U[nt % 2]); } }; /////////////////////////////////////////////////////////////////////////////// int hpx_main(hpx::program_options::variables_map& vm) { std::uint64_t np = vm["np"].as(); // Number of partitions. std::uint64_t nx = vm["nx"].as(); // Number of grid points. std::uint64_t nt = vm["nt"].as(); // Number of steps. std::uint64_t nd = vm["nd"].as(); // Max depth of dep tree. std::uint64_t cp = vm["cp"].as(); // Num. steps to checkpoint std::string rsf = vm["restart-file"].as(); std::string fn = vm["output-file"].as(); if (vm.count("no-header")) header = false; // Create the stepper object stepper step; // Measure execution time. std::uint64_t t = hpx::util::high_resolution_clock::now(); // Execute nt time steps on nx grid points and print the final solution. hpx::future result = step.do_work(np, nx, nt, nd, cp, rsf, fn); stepper::space solution = result.get(); hpx::wait_all(solution); std::uint64_t elapsed = hpx::util::high_resolution_clock::now() - t; // Print the final solution if (vm.count("results")) { for (std::size_t i = 0; i != np; ++i) std::cout << "U[" << i << "] = " << solution[i].get() << std::endl; } std::uint64_t const os_thread_count = hpx::get_os_thread_count(); print_time_results(os_thread_count, elapsed, nx, np, nt, header); return hpx::finalize(); } int main(int argc, char* argv[]) { using namespace hpx::program_options; // Configure application-specific options. options_description desc_commandline; desc_commandline.add_options()( "results", "print generated results (default: false)")("nx", value()->default_value(10), "Local x dimension (of each partition)")("nt", value()->default_value(45), "Number of time steps")("nd", value()->default_value(10), "Number of time steps to allow the dependency tree to grow to")("np", value()->default_value(10), "Number of partitions")("k", value(&k)->default_value(0.5), "Heat transfer coefficient (default: 0.5)")("dt", value(&dt)->default_value(1.0), "Timestep unit (default: 1.0[s])")( "dx", value(&dx)->default_value(1.0), "Local x dimension")("cp", value()->default_value(44), "Number of steps to checkpoint")( "no-header", "do not print out the csv header row")("restart-file", value()->default_value(""), "Start application from restart file")("output-file", value()->default_value("1d.archive"), "Base name of archive file"); // Initialize and run HPX return hpx::init(desc_commandline, argc, argv); } /*========================================================================= Program: Visualization Toolkit Module: TestLinePlot.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 "vtkRenderer.h" #include "vtkRenderWindow.h" #include "vtkSmartPointer.h" #include "vtkChartXY.h" #include "vtkAxis.h" #include "vtkPlot.h" #include "vtkTable.h" #include "vtkFloatArray.h" #include "vtkContextView.h" #include "vtkContextScene.h" #include "vtkInteractorEventRecorder.h" #include "vtkRenderWindowInteractor.h" #include "vtkNew.h" #include "vtkCompositeControlPointsItem.h" #include "vtkPiecewiseFunction.h" #include "vtkColorTransferFunction.h" #include "vtkCompositeTransferFunctionItem.h" char TestControlPointsHandleItemLog[] = "# StreamVersion 1\n" "RenderEvent 0 0 0 0 0 0 0\n" "TimerEvent 0 0 0 0 0 0 0\n" "EnterEvent 249 3 0 0 0 0 0\n" "MouseMoveEvent 193 128 0 0 0 0 0\n" "MouseMoveEvent 193 129 0 0 0 0 0\n" "MouseMoveEvent 193 130 0 0 0 0 0\n" "MouseMoveEvent 193 132 0 0 0 0 0\n" "MouseMoveEvent 193 134 0 0 0 0 0\n" "MouseMoveEvent 194 134 0 0 0 0 0\n" "MouseMoveEvent 194 136 0 0 0 0 0\n" "MouseMoveEvent 194 137 0 0 0 0 0\n" "MouseMoveEvent 195 138 0 0 0 0 0\n" "MouseMoveEvent 195 139 0 0 0 0 0\n" "MouseMoveEvent 195 140 0 0 0 0 0\n" "MouseMoveEvent 196 140 0 0 0 0 0\n" "MouseMoveEvent 196 142 0 0 0 0 0\n" "MouseMoveEvent 196 143 0 0 0 0 0\n" "MouseMoveEvent 196 144 0 0 0 0 0\n" "MouseMoveEvent 196 145 0 0 0 0 0\n" "MouseMoveEvent 197 146 0 0 0 0 0\n" "MouseMoveEvent 197 147 0 0 0 0 0\n" "MouseMoveEvent 198 148 0 0 0 0 0\n" "MouseMoveEvent 198 149 0 0 0 0 0\n" "MouseMoveEvent 199 150 0 0 0 0 0\n" "MouseMoveEvent 199 151 0 0 0 0 0\n" "MouseMoveEvent 199 151 0 0 0 0 0\n" "LeftButtonPressEvent 199 151 0 0 0 0 0\n" "TimerEvent 199 151 0 0 0 0 0\n" "LeftButtonReleaseEvent 199 151 0 0 0 0 0\n" "MouseMoveEvent 199 151 0 0 0 0 0\n" "LeftButtonPressEvent 199 151 0 0 0 0 0\n" "LeftButtonReleaseEvent 199 151 0 0 0 0 0\n" "LeftButtonPressEvent 199 151 0 0 0 1 0\n" "LeftButtonReleaseEvent 199 151 0 0 0 0 0\n" "MouseMoveEvent 199 151 0 0 0 0 0\n" "MouseMoveEvent 199 151 0 0 0 0 0\n" "MouseMoveEvent 200 151 0 0 0 0 0\n" "MouseMoveEvent 202 152 0 0 0 0 0\n" "MouseMoveEvent 202 154 0 0 0 0 0\n" "MouseMoveEvent 204 156 0 0 0 0 0\n" "MouseMoveEvent 206 159 0 0 0 0 0\n" "MouseMoveEvent 212 163 0 0 0 0 0\n" "MouseMoveEvent 222 167 0 0 0 0 0\n" "MouseMoveEvent 231 174 0 0 0 0 0\n" "MouseMoveEvent 243 182 0 0 0 0 0\n" "MouseMoveEvent 253 190 0 0 0 0 0\n" "MouseMoveEvent 263 197 0 0 0 0 0\n" "MouseMoveEvent 274 206 0 0 0 0 0\n" "MouseMoveEvent 284 215 0 0 0 0 0\n" "MouseMoveEvent 289 224 0 0 0 0 0\n" "MouseMoveEvent 297 233 0 0 0 0 0\n" "MouseMoveEvent 304 240 0 0 0 0 0\n" "MouseMoveEvent 308 246 0 0 0 0 0\n" "MouseMoveEvent 313 255 0 0 0 0 0\n" "MouseMoveEvent 319 263 0 0 0 0 0\n" "MouseMoveEvent 323 270 0 0 0 0 0\n" "MouseMoveEvent 326 276 0 0 0 0 0\n" "MouseMoveEvent 331 282 0 0 0 0 0\n" "MouseMoveEvent 334 287 0 0 0 0 0\n" "MouseMoveEvent 337 292 0 0 0 0 0\n" "MouseMoveEvent 341 297 0 0 0 0 0\n" "RenderEvent 341 297 0 0 0 0 0 \n" "TimerEvent 341 297 0 0 0 0 0 \n" "TimerEvent 341 297 0 0 0 0 0 \n" "TimerEvent 341 297 0 0 0 0 0 \n" "EnterEvent 206 0 0 0 0 0 0 \n" "MouseMoveEvent 206 0 0 0 0 0 0 \n" "MouseMoveEvent 205 9 0 0 0 0 0 \n" "MouseMoveEvent 205 18 0 0 0 0 0 \n" "MouseMoveEvent 204 27 0 0 0 0 0 \n" "MouseMoveEvent 203 36 0 0 0 0 0 \n" "MouseMoveEvent 203 42 0 0 0 0 0 \n" "MouseMoveEvent 203 51 0 0 0 0 0 \n" "MouseMoveEvent 203 55 0 0 0 0 0 \n" "MouseMoveEvent 203 62 0 0 0 0 0 \n" "MouseMoveEvent 203 65 0 0 0 0 0 \n" "MouseMoveEvent 203 72 0 0 0 0 0 \n" "MouseMoveEvent 204 76 0 0 0 0 0 \n" "MouseMoveEvent 205 81 0 0 0 0 0 \n" "MouseMoveEvent 206 85 0 0 0 0 0 \n" "MouseMoveEvent 207 9 0 0 0 0 0 0 \n" "MouseMoveEvent 208 93 0 0 0 0 0 \n" "MouseMoveEvent 208 96 0 0 0 0 0 \n" "MouseMoveEvent 208 98 0 0 0 0 0 \n" "MouseMoveEvent 209 10 0 0 0 0 0 0 \n" "MouseMoveEvent 209 102 0 0 0 0 0 \n" "MouseMoveEvent 209 103 0 0 0 0 0 \n" "MouseMoveEvent 209 105 0 0 0 0 0 \n" "MouseMoveEvent 210 108 0 0 0 0 0 \n" "MouseMoveEvent 210 108 0 0 0 0 0 \n" "MouseMoveEvent 210 111 0 0 0 0 0 \n" "MouseMoveEvent 211 114 0 0 0 0 0 \n" "MouseMoveEvent 211 115 0 0 0 0 0 \n" "MouseMoveEvent 211 118 0 0 0 0 0 \n" "MouseMoveEvent 211 121 0 0 0 0 0 \n" "MouseMoveEvent 210 124 0 0 0 0 0 \n" "MouseMoveEvent 210 125 0 0 0 0 0 \n" "MouseMoveEvent 209 126 0 0 0 0 0 \n" "MouseMoveEvent 209 127 0 0 0 0 0 \n" "MouseMoveEvent 209 128 0 0 0 0 0 \n" "MouseMoveEvent 208 128 0 0 0 0 0 \n" "MouseMoveEvent 207 129 0 0 0 0 0 \n" "MouseMoveEvent 207 13 0 0 0 0 0 0 \n" "MouseMoveEvent 206 13 0 0 0 0 0 0 \n" "MouseMoveEvent 206 131 0 0 0 0 0 \n" "MouseMoveEvent 206 132 0 0 0 0 0 \n" "MouseMoveEvent 205 133 0 0 0 0 0 \n" "MouseMoveEvent 204 134 0 0 0 0 0 \n" "MouseMoveEvent 203 135 0 0 0 0 0 \n" "MouseMoveEvent 203 136 0 0 0 0 0 \n" "MouseMoveEvent 202 136 0 0 0 0 0 \n" "MouseMoveEvent 201 137 0 0 0 0 0 \n" "MouseMoveEvent 201 138 0 0 0 0 0 \n" "TimerEvent 201 138 0 0 0 0 0 \n" "MouseMoveEvent 200 138 0 0 0 0 0 \n" "MouseMoveEvent 199 138 0 0 0 0 0 \n" "MouseMoveEvent 198 138 0 0 0 0 0 \n" "MouseMoveEvent 198 139 0 0 0 0 0 \n" "MouseMoveEvent 199 139 0 0 0 0 0 \n" "LeftButtonPressEvent 199 139 0 0 0 0 0 \n" "MouseMoveEvent 199 139 0 0 0 0 0 \n" "TimerEvent 199 139 0 0 0 0 0 \n" "MouseMoveEvent 199 138 0 0 0 0 0 \n" "MouseMoveEvent 199 137 0 0 0 0 0 \n" "MouseMoveEvent 199 136 0 0 0 0 0 \n" "TimerEvent 199 136 0 0 0 0 0 \n" "MouseMoveEvent 199 135 0 0 0 0 0 \n" "TimerEvent 199 135 0 0 0 0 0 \n" "MouseMoveEvent 199 134 0 0 0 0 0 \n" "TimerEvent 199 134 0 0 0 0 0 \n" "MouseMoveEvent 199 133 0 0 0 0 0 \n" "MouseMoveEvent 198 133 0 0 0 0 0 \n" "TimerEvent 198 133 0 0 0 0 0 \n" "MouseMoveEvent 198 132 0 0 0 0 0 \n" "MouseMoveEvent 198 131 0 0 0 0 0 \n" "TimerEvent 198 131 0 0 0 0 0 \n" "MouseMoveEvent 198 13 0 0 0 0 0 0 \n" "TimerEvent 198 13 0 0 0 0 0 0 \n" "MouseMoveEvent 198 13 0 0 0 0 0 0 \n" "TimerEvent 198 13 0 0 0 0 0 0 \n" "LeftButtonReleaseEvent 198 13 0 0 0 0 0 0 \n" "MouseMoveEvent 198 13 0 0 0 0 0 0 \n" "MouseMoveEvent 197 13 0 0 0 0 0 0 \n" "MouseMoveEvent 196 13 0 0 0 0 0 0 \n" "MouseMoveEvent 195 129 0 0 0 0 0 \n" "TimerEvent 195 129 0 0 0 0 0 \n" "MouseMoveEvent 194 129 0 0 0 0 0 \n" "MouseMoveEvent 193 129 0 0 0 0 0 \n" "MouseMoveEvent 193 128 0 0 0 0 0 \n" "MouseMoveEvent 192 128 0 0 0 0 0 \n" "MouseMoveEvent 193 128 0 0 0 0 0 \n" "MouseMoveEvent 193 129 0 0 0 0 0 \n" "MouseMoveEvent 193 13 0 0 0 0 0 0 \n" "MouseMoveEvent 194 13 0 0 0 0 0 0 \n" "MouseMoveEvent 194 131 0 0 0 0 0 \n" "MouseMoveEvent 194 132 0 0 0 0 0 \n" "MouseMoveEvent 194 133 0 0 0 0 0 \n" "MouseMoveEvent 194 134 0 0 0 0 0 \n" "MouseMoveEvent 194 135 0 0 0 0 0 \n" "MouseMoveEvent 194 135 0 0 0 0 0 \n" "MouseMoveEvent 194 136 0 0 0 0 0 \n" "MouseMoveEvent 194 138 0 0 0 0 0 \n" "MouseMoveEvent 194 139 0 0 0 0 0 \n" "MouseMoveEvent 194 14 0 0 0 0 0 0 \n" "MouseMoveEvent 194 141 0 0 0 0 0 \n" "MouseMoveEvent 194 142 0 0 0 0 0 \n" "MouseMoveEvent 194 143 0 0 0 0 0 \n" "MouseMoveEvent 194 145 0 0 0 0 0 \n" "MouseMoveEvent 194 146 0 0 0 0 0 \n" "MouseMoveEvent 194 147 0 0 0 0 0 \n" "MouseMoveEvent 194 148 0 0 0 0 0 \n" "MouseMoveEvent 194 149 0 0 0 0 0 \n" "MouseMoveEvent 194 15 0 0 0 0 0 0 \n" "MouseMoveEvent 194 151 0 0 0 0 0 \n" "MouseMoveEvent 194 152 0 0 0 0 0 \n" "MouseMoveEvent 194 153 0 0 0 0 0 \n" "MouseMoveEvent 194 154 0 0 0 0 0 \n" "MouseMoveEvent 194 155 0 0 0 0 0 \n" "MouseMoveEvent 194 156 0 0 0 0 0 \n" "MouseMoveEvent 194 158 0 0 0 0 0 \n" "MouseMoveEvent 194 159 0 0 0 0 0 \n" "MouseMoveEvent 194 16 0 0 0 0 0 0 \n" "MouseMoveEvent 195 161 0 0 0 0 0 \n" "MouseMoveEvent 196 161 0 0 0 0 0 \n" "TimerEvent 196 161 0 0 0 0 0 \n" "MouseMoveEvent 196 162 0 0 0 0 0 \n" "TimerEvent 196 162 0 0 0 0 0 \n" "MouseMoveEvent 197 162 0 0 0 0 0 \n" "TimerEvent 197 162 0 0 0 0 0 \n" "MouseMoveEvent 198 162 0 0 0 0 0 \n" "MouseMoveEvent 198 162 0 0 0 0 0 \n" "MouseMoveEvent 199 162 0 0 0 0 0 \n" "MouseMoveEvent 199 161 0 0 0 0 0 \n" "MouseMoveEvent 199 16 0 0 0 0 0 0 \n" "MouseMoveEvent 199 159 0 0 0 0 0 \n" "LeftButtonPressEvent 199 159 0 0 0 0 0 \n" "MouseMoveEvent 199 159 0 0 0 0 0 \n" "MouseMoveEvent 199 16 0 0 0 0 0 0 \n" "MouseMoveEvent 199 161 0 0 0 0 0 \n" "MouseMoveEvent 199 162 0 0 0 0 0 \n" "MouseMoveEvent 199 163 0 0 0 0 0 \n" "TimerEvent 199 163 0 0 0 0 0 \n" "MouseMoveEvent 200 163 0 0 0 0 0 \n" "MouseMoveEvent 200 164 0 0 0 0 0 \n" "MouseMoveEvent 200 165 0 0 0 0 0 \n" "MouseMoveEvent 200 166 0 0 0 0 0 \n" "TimerEvent 200 166 0 0 0 0 0 \n" "MouseMoveEvent 200 167 0 0 0 0 0 \n" "MouseMoveEvent 201 167 0 0 0 0 0 \n" "MouseMoveEvent 201 168 0 0 0 0 0 \n" "TimerEvent 201 168 0 0 0 0 0 \n" "MouseMoveEvent 201 169 0 0 0 0 0 \n" "TimerEvent 201 169 0 0 0 0 0 \n" "MouseMoveEvent 201 17 0 0 0 0 0 0 \n" "TimerEvent 201 17 0 0 0 0 0 0 \n" "MouseMoveEvent 201 171 0 0 0 0 0 \n" "TimerEvent 201 171 0 0 0 0 0 \n" "MouseMoveEvent 201 171 0 0 0 0 0 \n" "TimerEvent 201 171 0 0 0 0 0 \n" "LeftButtonReleaseEvent 201 171 0 0 0 0 0 \n" "MouseMoveEvent 201 171 0 0 0 0 0 \n" "MouseMoveEvent 201 172 0 0 0 0 0 \n" "TimerEvent 201 172 0 0 0 0 0 \n" "MouseMoveEvent 200 172 0 0 0 0 0 \n" "MouseMoveEvent 200 171 0 0 0 0 0 \n" "MouseMoveEvent 200 17 0 0 0 0 0 0 \n" "MouseMoveEvent 200 169 0 0 0 0 0 \n" "MouseMoveEvent 199 169 0 0 0 0 0 \n" "MouseMoveEvent 199 168 0 0 0 0 0 \n" "MouseMoveEvent 199 167 0 0 0 0 0 \n" "MouseMoveEvent 199 166 0 0 0 0 0 \n" "TimerEvent 199 166 0 0 0 0 0 \n" "MouseMoveEvent 200 168 0 0 0 0 0 \n" "MouseMoveEvent 201 169 0 0 0 0 0 \n" "MouseMoveEvent 204 171 0 0 0 0 0 \n" "MouseMoveEvent 205 172 0 0 0 0 0 \n" "MouseMoveEvent 206 172 0 0 0 0 0 \n" "MouseMoveEvent 207 172 0 0 0 0 0 \n" "TimerEvent 207 172 0 0 0 0 0 \n" "MouseMoveEvent 207 173 0 0 0 0 0 \n" "MouseMoveEvent 208 173 0 0 0 0 0 \n" "MouseMoveEvent 209 173 0 0 0 0 0 \n" "MouseMoveEvent 210 173 0 0 0 0 0 \n" "MouseMoveEvent 211 175 0 0 0 0 0 \n" "MouseMoveEvent 212 175 0 0 0 0 0 \n" "MouseMoveEvent 213 176 0 0 0 0 0 \n" "MouseMoveEvent 213 177 0 0 0 0 0 \n" "MouseMoveEvent 213 179 0 0 0 0 0 \n" "MouseMoveEvent 213 18 0 0 0 0 0 0 \n" "MouseMoveEvent 213 181 0 0 0 0 0 \n" "MouseMoveEvent 213 182 0 0 0 0 0 \n" "MouseMoveEvent 213 185 0 0 0 0 0 \n" "MouseMoveEvent 214 187 0 0 0 0 0 \n" "MouseMoveEvent 215 189 0 0 0 0 0 \n" "MouseMoveEvent 215 191 0 0 0 0 0 \n" "MouseMoveEvent 216 194 0 0 0 0 0 \n" "MouseMoveEvent 216 195 0 0 0 0 0 \n" "MouseMoveEvent 216 199 0 0 0 0 0 \n" "MouseMoveEvent 217 203 0 0 0 0 0 \n" "MouseMoveEvent 218 208 0 0 0 0 0 \n" "MouseMoveEvent 218 211 0 0 0 0 0 \n" "MouseMoveEvent 219 215 0 0 0 0 0 \n" "MouseMoveEvent 221 221 0 0 0 0 0 \n" "MouseMoveEvent 222 224 0 0 0 0 0 \n" "MouseMoveEvent 222 227 0 0 0 0 0 \n" "MouseMoveEvent 223 23 0 0 0 0 0 0 \n" "MouseMoveEvent 223 232 0 0 0 0 0 \n" "MouseMoveEvent 223 234 0 0 0 0 0 \n" "MouseMoveEvent 224 236 0 0 0 0 0 \n" "MouseMoveEvent 225 238 0 0 0 0 0 \n" "MouseMoveEvent 226 24 0 0 0 0 0 0 \n" "MouseMoveEvent 226 242 0 0 0 0 0 \n" "MouseMoveEvent 227 244 0 0 0 0 0 \n" "MouseMoveEvent 228 246 0 0 0 0 0 \n" "MouseMoveEvent 228 247 0 0 0 0 0 \n" "MouseMoveEvent 228 248 0 0 0 0 0 \n" "MouseMoveEvent 229 25 0 0 0 0 0 0 \n" "MouseMoveEvent 230 251 0 0 0 0 0 \n" "MouseMoveEvent 230 252 0 0 0 0 0 \n" "MouseMoveEvent 230 254 0 0 0 0 0 \n" "MouseMoveEvent 231 255 0 0 0 0 0 \n" "MouseMoveEvent 231 255 0 0 0 0 0 \n" "MouseMoveEvent 232 256 0 0 0 0 0 \n" "MouseMoveEvent 232 257 0 0 0 0 0 \n" "MouseMoveEvent 234 257 0 0 0 0 0 \n" "MouseMoveEvent 235 258 0 0 0 0 0 \n" "MouseMoveEvent 236 258 0 0 0 0 0 \n" "MouseMoveEvent 237 258 0 0 0 0 0 \n" "MouseMoveEvent 238 258 0 0 0 0 0 \n" "MouseMoveEvent 239 259 0 0 0 0 0 \n" "MouseMoveEvent 240 259 0 0 0 0 0 \n" "MouseMoveEvent 241 259 0 0 0 0 0 \n" "MouseMoveEvent 241 26 0 0 0 0 0 0 \n" "MouseMoveEvent 242 261 0 0 0 0 0 \n" "MouseMoveEvent 243 262 0 0 0 0 0 \n" "MouseMoveEvent 244 262 0 0 0 0 0 \n" "MouseMoveEvent 244 263 0 0 0 0 0 \n" "MouseMoveEvent 245 264 0 0 0 0 0 \n" "MouseMoveEvent 244 264 0 0 0 0 0 \n" "MouseMoveEvent 244 264 0 0 0 0 0 \n" "MouseMoveEvent 244 263 0 0 0 0 0 \n" "MouseMoveEvent 243 263 0 0 0 0 0 \n" "MouseMoveEvent 242 263 0 0 0 0 0 \n" "MouseMoveEvent 241 263 0 0 0 0 0 \n" "MouseMoveEvent 240 263 0 0 0 0 0 \n" "MouseMoveEvent 240 262 0 0 0 0 0 \n" "MouseMoveEvent 239 262 0 0 0 0 0 \n" "MouseMoveEvent 238 261 0 0 0 0 0 \n" "MouseMoveEvent 237 26 0 0 0 0 0 0 \n" "MouseMoveEvent 237 259 0 0 0 0 0 \n" "MouseMoveEvent 237 259 0 0 0 0 0 \n" "MouseMoveEvent 238 259 0 0 0 0 0 \n" "MouseMoveEvent 239 259 0 0 0 0 0 \n" "MouseMoveEvent 240 26 0 0 0 0 0 0 \n" "MouseMoveEvent 241 26 0 0 0 0 0 0 \n" "MouseMoveEvent 241 261 0 0 0 0 0 \n" "MouseMoveEvent 242 261 0 0 0 0 0 \n" "MouseMoveEvent 243 261 0 0 0 0 0 \n" "MouseMoveEvent 243 262 0 0 0 0 0 \n" "MouseMoveEvent 244 262 0 0 0 0 0 \n" "MouseMoveEvent 245 262 0 0 0 0 0 \n" "MouseMoveEvent 246 263 0 0 0 0 0 \n" "MouseMoveEvent 246 261 0 0 0 0 0 \n" "MouseMoveEvent 246 259 0 0 0 0 0 \n" "MouseMoveEvent 246 258 0 0 0 0 0 \n" "MouseMoveEvent 246 256 0 0 0 0 0 \n" "MouseMoveEvent 246 254 0 0 0 0 0 \n" "MouseMoveEvent 246 253 0 0 0 0 0 \n" "MouseMoveEvent 246 252 0 0 0 0 0 \n" "MouseMoveEvent 246 251 0 0 0 0 0 \n" "MouseMoveEvent 246 25 0 0 0 0 0 0 \n" "MouseMoveEvent 246 249 0 0 0 0 0 \n" "MouseMoveEvent 246 248 0 0 0 0 0 \n" "MouseMoveEvent 246 247 0 0 0 0 0 \n" "MouseMoveEvent 246 246 0 0 0 0 0 \n" "MouseMoveEvent 246 245 0 0 0 0 0 \n" "MouseMoveEvent 246 243 0 0 0 0 0 \n" "MouseMoveEvent 246 242 0 0 0 0 0 \n" "MouseMoveEvent 245 241 0 0 0 0 0 \n" "MouseMoveEvent 245 24 0 0 0 0 0 0 \n" "MouseMoveEvent 245 238 0 0 0 0 0 \n" "MouseMoveEvent 244 235 0 0 0 0 0 \n" "MouseMoveEvent 243 233 0 0 0 0 0 \n" "MouseMoveEvent 242 229 0 0 0 0 0 \n" "MouseMoveEvent 240 225 0 0 0 0 0 \n" "MouseMoveEvent 240 221 0 0 0 0 0 \n" "MouseMoveEvent 238 215 0 0 0 0 0 \n" "MouseMoveEvent 236 21 0 0 0 0 0 0 \n" "MouseMoveEvent 235 205 0 0 0 0 0 \n" "MouseMoveEvent 233 199 0 0 0 0 0 \n" "MouseMoveEvent 232 194 0 0 0 0 0 \n" "MouseMoveEvent 230 19 0 0 0 0 0 0 \n" "MouseMoveEvent 228 185 0 0 0 0 0 \n" "MouseMoveEvent 227 181 0 0 0 0 0 \n" "MouseMoveEvent 227 178 0 0 0 0 0 \n" "MouseMoveEvent 227 174 0 0 0 0 0 \n" "MouseMoveEvent 227 171 0 0 0 0 0 \n" "MouseMoveEvent 227 169 0 0 0 0 0 \n" "MouseMoveEvent 227 168 0 0 0 0 0 \n" "MouseMoveEvent 227 167 0 0 0 0 0 \n" "MouseMoveEvent 228 165 0 0 0 0 0 \n" "MouseMoveEvent 229 163 0 0 0 0 0 \n" "MouseMoveEvent 229 162 0 0 0 0 0 \n" "MouseMoveEvent 229 161 0 0 0 0 0 \n" "MouseMoveEvent 229 159 0 0 0 0 0 \n" "MouseMoveEvent 229 158 0 0 0 0 0 \n" "MouseMoveEvent 229 157 0 0 0 0 0 \n" "MouseMoveEvent 230 156 0 0 0 0 0 \n" "MouseMoveEvent 230 155 0 0 0 0 0 \n" "MouseMoveEvent 230 154 0 0 0 0 0 \n" "MouseMoveEvent 230 153 0 0 0 0 0 \n" "MouseMoveEvent 231 152 0 0 0 0 0 \n" "MouseMoveEvent 231 15 0 0 0 0 0 0 \n" "MouseMoveEvent 232 148 0 0 0 0 0 \n" "MouseMoveEvent 232 147 0 0 0 0 0 \n" "MouseMoveEvent 233 145 0 0 0 0 0 \n" "TimerEvent 233 145 0 0 0 0 0 \n" "MouseMoveEvent 233 143 0 0 0 0 0 \n" "MouseMoveEvent 233 142 0 0 0 0 0 \n" "MouseMoveEvent 233 142 0 0 0 0 0 \n" "MouseMoveEvent 233 141 0 0 0 0 0 \n" "MouseMoveEvent 233 14 0 0 0 0 0 0 \n" "MouseMoveEvent 233 139 0 0 0 0 0 \n" "MouseMoveEvent 233 138 0 0 0 0 0 \n" "MouseMoveEvent 234 138 0 0 0 0 0 \n" "MouseMoveEvent 234 139 0 0 0 0 0 \n" "MouseMoveEvent 234 14 0 0 0 0 0 0 \n" "MouseMoveEvent 235 141 0 0 0 0 0 \n" "MouseMoveEvent 235 142 0 0 0 0 0 \n" "MouseMoveEvent 235 143 0 0 0 0 0 \n" "MouseMoveEvent 235 144 0 0 0 0 0 \n" "MouseMoveEvent 235 145 0 0 0 0 0 \n" "MouseMoveEvent 235 146 0 0 0 0 0 \n" "MouseMoveEvent 235 147 0 0 0 0 0 \n" "MouseMoveEvent 235 148 0 0 0 0 0 \n" "TimerEvent 235 148 0 0 0 0 0 \n" "MouseMoveEvent 235 15 0 0 0 0 0 0 \n" "MouseMoveEvent 235 151 0 0 0 0 0 \n" "MouseMoveEvent 235 152 0 0 0 0 0 \n" "MouseMoveEvent 234 152 0 0 0 0 0 \n" "MouseMoveEvent 233 152 0 0 0 0 0 \n" "MouseMoveEvent 232 152 0 0 0 0 0 \n" "MouseMoveEvent 231 152 0 0 0 0 0 \n" "MouseMoveEvent 231 151 0 0 0 0 0 \n" "MouseMoveEvent 231 15 0 0 0 0 0 0 \n" "MouseMoveEvent 231 15 0 0 0 0 0 0 \n" "LeftButtonPressEvent 231 15 0 0 0 0 0 0 \n" "MouseMoveEvent 231 149 0 0 0 0 0 \n" "MouseMoveEvent 230 149 0 0 0 0 0 \n" "TimerEvent 230 149 0 0 0 0 0 \n" "MouseMoveEvent 229 148 0 0 0 0 0 \n" "MouseMoveEvent 228 148 0 0 0 0 0 \n" "TimerEvent 228 148 0 0 0 0 0 \n" "MouseMoveEvent 227 148 0 0 0 0 0 \n" "MouseMoveEvent 227 148 0 0 0 0 0 \n" "MouseMoveEvent 226 147 0 0 0 0 0 \n" "TimerEvent 226 147 0 0 0 0 0 \n" "MouseMoveEvent 225 147 0 0 0 0 0 \n" "TimerEvent 225 147 0 0 0 0 0 \n" "MouseMoveEvent 224 147 0 0 0 0 0 \n" "MouseMoveEvent 224 146 0 0 0 0 0 \n" "LeftButtonReleaseEvent 224 146 0 0 0 0 0 \n" "MouseMoveEvent 224 146 0 0 0 0 0 \n" "TimerEvent 224 146 0 0 0 0 0 \n" "MouseMoveEvent 223 146 0 0 0 0 0 \n" "MouseMoveEvent 223 145 0 0 0 0 0 \n" "MouseMoveEvent 222 145 0 0 0 0 0 \n" "MouseMoveEvent 221 144 0 0 0 0 0 \n" "TimerEvent 221 144 0 0 0 0 0 \n" "MouseMoveEvent 220 144 0 0 0 0 0 \n" "MouseMoveEvent 220 142 0 0 0 0 0 \n" "MouseMoveEvent 219 142 0 0 0 0 0 \n" "MouseMoveEvent 219 14 0 0 0 0 0 0 \n" "MouseMoveEvent 217 14 0 0 0 0 0 0 \n" "MouseMoveEvent 216 138 0 0 0 0 0 \n" "MouseMoveEvent 215 138 0 0 0 0 0 \n" "MouseMoveEvent 214 137 0 0 0 0 0 \n" "MouseMoveEvent 212 136 0 0 0 0 0 \n" "MouseMoveEvent 211 136 0 0 0 0 0 \n" "MouseMoveEvent 209 135 0 0 0 0 0 \n" "MouseMoveEvent 207 134 0 0 0 0 0 \n" "MouseMoveEvent 204 134 0 0 0 0 0 \n" "MouseMoveEvent 202 133 0 0 0 0 0 \n" "MouseMoveEvent 199 133 0 0 0 0 0 \n" "MouseMoveEvent 198 133 0 0 0 0 0 \n" "MouseMoveEvent 197 133 0 0 0 0 0 \n" "MouseMoveEvent 196 133 0 0 0 0 0 \n" "MouseMoveEvent 195 133 0 0 0 0 0 \n" "TimerEvent 195 133 0 0 0 0 0 \n" "MouseMoveEvent 194 133 0 0 0 0 0 \n" "MouseMoveEvent 193 133 0 0 0 0 0 \n" "MouseMoveEvent 192 133 0 0 0 0 0 \n" "MouseMoveEvent 191 133 0 0 0 0 0 \n" "MouseMoveEvent 190 133 0 0 0 0 0 \n" "MouseMoveEvent 189 133 0 0 0 0 0 \n" "MouseMoveEvent 187 133 0 0 0 0 0 \n" "MouseMoveEvent 187 134 0 0 0 0 0 \n" "MouseMoveEvent 186 134 0 0 0 0 0 \n" "MouseMoveEvent 185 134 0 0 0 0 0 \n" "MouseMoveEvent 184 134 0 0 0 0 0 \n" "MouseMoveEvent 184 135 0 0 0 0 0 \n" "MouseMoveEvent 183 135 0 0 0 0 0 \n" "MouseMoveEvent 182 135 0 0 0 0 0 \n" "MouseMoveEvent 181 136 0 0 0 0 0 \n" "MouseMoveEvent 180 136 0 0 0 0 0 \n" "MouseMoveEvent 179 137 0 0 0 0 0 \n" "MouseMoveEvent 178 137 0 0 0 0 0 \n" "MouseMoveEvent 177 137 0 0 0 0 0 \n" "MouseMoveEvent 176 137 0 0 0 0 0 \n" "MouseMoveEvent 175 137 0 0 0 0 0 \n" "MouseMoveEvent 175 138 0 0 0 0 0 \n" "MouseMoveEvent 173 138 0 0 0 0 0 \n" "MouseMoveEvent 170 139 0 0 0 0 0 \n" "MouseMoveEvent 169 139 0 0 0 0 0 \n" "MouseMoveEvent 168 139 0 0 0 0 0 \n" "MouseMoveEvent 167 14 0 0 0 0 0 0 \n" "MouseMoveEvent 167 14 0 0 0 0 0 0 \n" "MouseMoveEvent 165 142 0 0 0 0 0 \n" "MouseMoveEvent 165 143 0 0 0 0 0 \n" "MouseMoveEvent 164 144 0 0 0 0 0 \n" "MouseMoveEvent 164 145 0 0 0 0 0 \n" "MouseMoveEvent 163 145 0 0 0 0 0 \n" "MouseMoveEvent 163 146 0 0 0 0 0 \n" "MouseMoveEvent 163 147 0 0 0 0 0 \n" "MouseMoveEvent 163 148 0 0 0 0 0 \n" "TimerEvent 163 148 0 0 0 0 0 \n" "MouseMoveEvent 164 148 0 0 0 0 0 \n" "MouseMoveEvent 165 148 0 0 0 0 0 \n" "MouseMoveEvent 166 148 0 0 0 0 0 \n" "MouseMoveEvent 166 149 0 0 0 0 0 \n" "MouseMoveEvent 167 149 0 0 0 0 0 \n" "LeftButtonPressEvent 167 149 0 0 0 0 0 \n" "MouseMoveEvent 167 149 0 0 0 0 0 \n" "TimerEvent 167 149 0 0 0 0 0 \n" "MouseMoveEvent 168 149 0 0 0 0 0 \n" "TimerEvent 168 149 0 0 0 0 0 \n" "MouseMoveEvent 169 149 0 0 0 0 0 \n" "MouseMoveEvent 170 149 0 0 0 0 0 \n" "MouseMoveEvent 171 149 0 0 0 0 0 \n" "TimerEvent 171 149 0 0 0 0 0 \n" "MouseMoveEvent 172 149 0 0 0 0 0 \n" "MouseMoveEvent 172 149 0 0 0 0 0 \n" "MouseMoveEvent 173 149 0 0 0 0 0 \n" "TimerEvent 173 149 0 0 0 0 0 \n" "MouseMoveEvent 174 149 0 0 0 0 0 \n" "MouseMoveEvent 174 148 0 0 0 0 0 \n" "TimerEvent 174 148 0 0 0 0 0 \n" "MouseMoveEvent 175 148 0 0 0 0 0 \n" "TimerEvent 175 148 0 0 0 0 0 \n" "MouseMoveEvent 176 148 0 0 0 0 0 \n" "TimerEvent 176 148 0 0 0 0 0 \n" "MouseMoveEvent 177 148 0 0 0 0 0 \n" "TimerEvent 177 148 0 0 0 0 0 \n" "LeftButtonReleaseEvent 177 148 0 0 0 0 0 \n" "MouseMoveEvent 177 148 0 0 0 0 0 \n" "TimerEvent 177 148 0 0 0 0 0 \n" "MouseMoveEvent 177 147 0 0 0 0 0 \n" "MouseMoveEvent 176 147 0 0 0 0 0 \n" "MouseMoveEvent 176 146 0 0 0 0 0 \n" "MouseMoveEvent 175 146 0 0 0 0 0 \n" "MouseMoveEvent 176 146 0 0 0 0 0 \n" "MouseMoveEvent 177 146 0 0 0 0 0 \n" "MouseMoveEvent 178 147 0 0 0 0 0 \n" "MouseMoveEvent 180 147 0 0 0 0 0 \n" "MouseMoveEvent 182 148 0 0 0 0 0 \n" "MouseMoveEvent 185 15 0 0 0 0 0 0 \n" "MouseMoveEvent 185 15 0 0 0 0 0 0 \n" "MouseMoveEvent 187 151 0 0 0 0 0 \n" "MouseMoveEvent 189 153 0 0 0 0 0 \n" "MouseMoveEvent 193 155 0 0 0 0 0 \n" "TimerEvent 193 155 0 0 0 0 0 \n" "MouseMoveEvent 198 159 0 0 0 0 0 \n" "MouseMoveEvent 202 162 0 0 0 0 0 \n" "MouseMoveEvent 206 164 0 0 0 0 0 \n" "MouseMoveEvent 212 168 0 0 0 0 0 \n" "MouseMoveEvent 217 17 0 0 0 0 0 0 \n" "MouseMoveEvent 222 172 0 0 0 0 0 \n" "MouseMoveEvent 230 175 0 0 0 0 0 \n" "MouseMoveEvent 240 178 0 0 0 0 0 \n" "MouseMoveEvent 247 179 0 0 0 0 0 \n" "MouseMoveEvent 254 183 0 0 0 0 0 \n" "MouseMoveEvent 263 184 0 0 0 0 0 \n" "MouseMoveEvent 268 186 0 0 0 0 0 \n" "MouseMoveEvent 273 188 0 0 0 0 0 \n" "MouseMoveEvent 278 19 0 0 0 0 0 0 \n" "MouseMoveEvent 281 192 0 0 0 0 0 \n" "MouseMoveEvent 283 192 0 0 0 0 0 \n" "MouseMoveEvent 287 194 0 0 0 0 0 \n" "MouseMoveEvent 290 196 0 0 0 0 0 \n" "MouseMoveEvent 292 197 0 0 0 0 0 \n" "MouseMoveEvent 296 199 0 0 0 0 0 \n" "MouseMoveEvent 298 201 0 0 0 0 0 \n" "MouseMoveEvent 301 202 0 0 0 0 0 \n" "MouseMoveEvent 303 204 0 0 0 0 0 \n" "MouseMoveEvent 306 205 0 0 0 0 0 \n" "MouseMoveEvent 308 208 0 0 0 0 0 \n" "MouseMoveEvent 310 208 0 0 0 0 0 \n" "MouseMoveEvent 313 21 0 0 0 0 0 0 \n" "MouseMoveEvent 314 211 0 0 0 0 0 \n" "MouseMoveEvent 316 213 0 0 0 0 0 \n" "MouseMoveEvent 318 214 0 0 0 0 0 \n" "MouseMoveEvent 319 216 0 0 0 0 0 \n" "MouseMoveEvent 320 216 0 0 0 0 0 \n" "MouseMoveEvent 320 218 0 0 0 0 0 \n" "MouseMoveEvent 322 22 0 0 0 0 0 0 \n" "MouseMoveEvent 323 222 0 0 0 0 0 \n" "MouseMoveEvent 324 225 0 0 0 0 0 \n" "MouseMoveEvent 325 227 0 0 0 0 0 \n" "MouseMoveEvent 326 228 0 0 0 0 0 \n" "MouseMoveEvent 327 23 0 0 0 0 0 0 \n" "MouseMoveEvent 327 232 0 0 0 0 0 \n" "MouseMoveEvent 328 234 0 0 0 0 0 \n" "MouseMoveEvent 329 236 0 0 0 0 0 \n" "MouseMoveEvent 330 239 0 0 0 0 0 \n" "MouseMoveEvent 331 24 0 0 0 0 0 0 \n" "MouseMoveEvent 332 243 0 0 0 0 0 \n" "MouseMoveEvent 333 246 0 0 0 0 0 \n" "MouseMoveEvent 334 248 0 0 0 0 0 \n" "MouseMoveEvent 335 25 0 0 0 0 0 0 \n" "MouseMoveEvent 336 252 0 0 0 0 0 \n" "MouseMoveEvent 337 254 0 0 0 0 0 \n" "MouseMoveEvent 337 256 0 0 0 0 0 \n" "MouseMoveEvent 339 258 0 0 0 0 0 \n" "MouseMoveEvent 340 261 0 0 0 0 0 \n" "MouseMoveEvent 341 263 0 0 0 0 0 \n" "MouseMoveEvent 343 265 0 0 0 0 0 \n" "MouseMoveEvent 344 267 0 0 0 0 0 \n" "MouseMoveEvent 344 269 0 0 0 0 0 \n" "MouseMoveEvent 346 272 0 0 0 0 0 \n" "MouseMoveEvent 347 273 0 0 0 0 0 \n" "MouseMoveEvent 348 276 0 0 0 0 0 \n" "MouseMoveEvent 349 278 0 0 0 0 0 \n" "MouseMoveEvent 350 28 0 0 0 0 0 0 \n" "MouseMoveEvent 352 282 0 0 0 0 0 \n" "MouseMoveEvent 353 285 0 0 0 0 0 \n" "MouseMoveEvent 353 286 0 0 0 0 0 \n" "MouseMoveEvent 355 288 0 0 0 0 0 \n" "MouseMoveEvent 356 288 0 0 0 0 0 \n" "MouseMoveEvent 357 29 0 0 0 0 0 0 \n" "MouseMoveEvent 358 291 0 0 0 0 0 \n" "MouseMoveEvent 360 293 0 0 0 0 0 \n" "MouseMoveEvent 362 295 0 0 0 0 0 \n" "MouseMoveEvent 363 298 0 0 0 0 0 \n" "LeaveEvent 341 297 0 0 0 0 0\n" "ExitEvent 341 297 0 0 0 0 0\n" ; //---------------------------------------------------------------------------- int TestControlPointsHandleItem(int, char * []) { // Set up a 2D scene, add an XY chart to it vtkNew view; view->GetRenderer()->SetBackground(1.0, 1.0, 1.0); view->GetRenderWindow()->SetSize(400, 300); vtkNew chart; chart->ForceAxesToBoundsOn(); chart->SetAutoSize(true); chart->SetAutoAxes(false); chart->SetHiddenAxisBorder(0); // chart->SetActionToButton(vtkChart::PAN, vtkContextMouseEvent::MIDDLE_BUTTON); // chart->SetActionToButton(vtkChart::SELECT, vtkContextMouseEvent::RIGHT_BUTTON); for (int i = 0; i < 4; ++i) { chart->GetAxis(i)->SetVisible(true); chart->GetAxis(i)->SetNumberOfTicks(0); chart->GetAxis(i)->SetBehavior(2); chart->GetAxis(i)->SetLabelsVisible(false); chart->GetAxis(i)->SetMargins(1,1); chart->GetAxis(i)->SetTitle(""); } view->GetScene()->AddItem(chart.GetPointer()); // Create transfer mapping scalar value to opacity. vtkNew opacityFunction; opacityFunction->AddPoint(0.0, 0.1); opacityFunction->AddPoint(0.5,0.5); opacityFunction->AddPoint(1.,1.); // Create transfer mapping scalar value to color. vtkNew colorTransferFunction; colorTransferFunction->SetColorSpaceToHSV(); colorTransferFunction->HSVWrapOn(); colorTransferFunction->AddHSVSegment(0.,0.,1.,1.,0.3333,0.3333,1.,1.); colorTransferFunction->AddHSVSegment(0.3333,0.3333,1.,1.,0.6666,0.6666,1.,1.); colorTransferFunction->AddHSVSegment(0.6666,0.6666,1.,1.,1.,0.,1.,1.); colorTransferFunction->Build(); vtkNew item; item->SetColorTransferFunction(colorTransferFunction.GetPointer()); item->SetOpacityFunction(opacityFunction.GetPointer()); item->SetMaskAboveCurve(true); chart->AddPlot(item.GetPointer()); vtkNew controlPoints; controlPoints->SetColorTransferFunction(colorTransferFunction.GetPointer()); controlPoints->SetOpacityFunction(opacityFunction.GetPointer()); controlPoints->SetEndPointsXMovable(false); controlPoints->SetUseOpacityPointHandles(true); controlPoints->SetEndPointsRemovable(false); chart->AddPlot(controlPoints.GetPointer()); //Finally render the scene and compare the image to a reference image view->GetRenderWindow()->SetMultiSamples(0); // recorder to play back previously events vtkSmartPointer recorder = vtkSmartPointer::New(); recorder->SetInteractor(view->GetInteractor()); // recorder->SetKeyPressActivationValue('b'); recorder->ReadFromInputStringOn(); recorder->SetInputString(TestControlPointsHandleItemLog); view->GetInteractor()->Initialize(); view->Render(); recorder->Play(); // Remove the observers so we can go interactive. Without this the "-I" // testing option fails. recorder->Off(); //recorder->SetFileName("record.log"); //recorder->On(); //recorder->Record(); view->GetInteractor()->Initialize(); view->GetInteractor()->Start(); return EXIT_SUCCESS; } // Euchre.cpp : This file contains the 'main' function. Program execution begins and ends there. // #include "pch.h" #include #include "Game.h" //heaps: cards,deck,& hand container of cards int main() { //Dealer card; Game game; game.Play(); std::cout << "Card instances: "<"; std::string sign4 = ""; std::string s = link_title_str; strReplace(s, "\n", " "); FetchedInfoScholarship fis; fis.m_URL = getStringInBetween(s, sign1, sign2); fis.m_Title = getStringInBetween(s, sign3, sign4); DatePtr deadline = DateConverter::instance()->convert(deadline_str); if (deadline.get()) { fis.m_Deadline = boost::gregorian::to_iso_string(*deadline); writeInputToManager(file_output, fis, now, count); count++; } } void FetcherScholarshipPositions::fetch() { const std::string now = "spgmail" + currentDateTime(); std::size_t count = 0; std::ifstream file_input(m_FilenameHtmlScholarshipPositionsGmail.c_str()); std::ofstream file_output(m_FilenameInputScholarshipPositionsGmail.c_str()); if (!file_input.is_open()) { std::cerr << "Cannot open file \"" << m_FilenameHtmlScholarshipPositionsGmail << "\" for reading!" << std::endl; return; } if (!file_output.is_open()) { std::cerr << "Cannot open file \"" << m_FilenameInputScholarshipPositionsGmail << "\" for writing!" << std::endl; return; } std::string content_gmail((std::istreambuf_iterator(file_input)), std::istreambuf_iterator()); HTML::ParserDom parser; tree dom = parser.parseTree(content_gmail); tree::iterator beg = dom.begin(); tree::iterator end = dom.end(); std::string ct = ""; std::string link_title_str = ""; std::string deadline_str = ""; tree::iterator previous_bold_it = NULL; for (tree::iterator it = beg; it != end; ++it) { if (it->tagName() == "strong" || it->tagName() == "b") { ct = it->content(content_gmail); // 20150908: // The link to the scholarship can be in the text content of this node or the previous node with tag . // if (ct == "Provided by:") { link_title_str = it->content(content_gmail); if (link_title_str.find("href=\"") == std::string::npos) link_title_str = previous_bold_it->content(content_gmail); assert(link_title_str.find("href=\"") != std::string::npos); } if (ct.find("Application Deadline") != std::string::npos) { tree::iterator jt = it; // To deal with the following form: // Application Deadline //  22 September 2014
++jt; ++jt; ++jt; deadline_str = jt->content(content_gmail); // // To deal with the following form: // Application Deadline 31 October 2014
// if (deadline_str == "") { for (jt = it; jt != end; ++jt) { if (jt->tagName() == "br") { jt--; deadline_str = jt->text(); break; } } } fetchOneScholarshipPosition(file_output, now, count, link_title_str, deadline_str); } previous_bold_it = it; } } DBGINFO("Fetched " << count << " scholarship items from ScholarshipPositions-Gmail!") } } // namespace findscholarships #include int main() { int sum = 0, tmp = 0; while (std::cin >> tmp) sum += tmp; std::cout <<"The sum is: " <1-10 /*! @file XTcpMessageReceiverThread.cpp @author This file is part of the Xylasoft Lightrail product. Copyright (c) 2011 , Xylasoft, All Rights Reserved http://www.xylasoft.com Licensed for use under the MIT License See accompanying LICENSE file for more information */ #include "XTcpMessageReceiverThread.h" using namespace Xylasoft; XTcpMessageReceiverThread::XTcpMessageReceiverThread(SOCKET socket, XSingleEventCallback& callback) : m_callback(callback) { this->m_socket = socket; this->m_completed = false; this->m_wasKilled = false; } XTcpMessageReceiverThread::~XTcpMessageReceiverThread() { } SOCKET XTcpMessageReceiverThread::SocketHandle() { return this->m_socket; } bool XTcpMessageReceiverThread::CompletedExecution() { return this->m_completed; } void XTcpMessageReceiverThread::KillConnection() { this->CloseSocket(this->m_socket); this->m_wasKilled = true; } void XTcpMessageReceiverThread::Execution() { char msgBuffer[STREAM_BUFFER_SIZE]; XByteArray message; long msgSize = -1; try { // continue while the message size has not yet been set or the amount of data received is // less than the specified message size while (msgSize == -1 || message.Size() < msgSize) { int packetSize = this->Receive(this->m_socket, msgBuffer, STREAM_BUFFER_SIZE); if (msgSize < 0) { if (packetSize < sizeof(u_long)) { throw CommunicationException(L"Packet size was too small to understand."); } u_long* netlong = (u_long*)msgBuffer; // parse the total message size msgSize = ntohl(*netlong); // copy the rest of the packet message.Append(msgBuffer + sizeof(u_long), packetSize - sizeof(u_long)); } else { message.Append(msgBuffer, packetSize); } } // send acknowledgement this->SendAck(this->m_socket); try { this->m_callback.Execute(message); } // if the event receiver throws an exception, we don't care, except for debugging #ifdef _DEBUG catch (std::exception& ex) { std::cout << "TCP Receiver event failed: " << ex.what() << std::endl; assert(false); } catch (...) { assert(false); } #else catch (...) { } #endif } // if there was an error in receiving, then close the socket and move on catch (...) { } // mark that this thread has executed this->m_completed = true; // if this thread was not explicitly killed, then close the socket if (!this->m_wasKilled) { this->CloseSocket(this->m_socket); } } //============================================================================== // Copyright (c) 2018 , all rights reserved. //============================================================================== #include "hw/hx711.h" #include "global/logging.h" #include "catch.hpp" #include "wiringPiMock.hpp" /** * How to write tests with Catch: * https://github.com/catchorg/Catch2/blob/master/docs/tutorial.md#bdd-style */ using namespace beewatch; using io::GPIO; using hw::HX711; //============================================================================== SCENARIO("Application can communicate with a mocked HX711 sensor", "[hx711][hw]") { // Disable logger g_logger.setVerbosity(Logger::Level::Unattainable); } cf/ Educational Codeforces Round 40 (Rated for Div. 2) /d.cpp #include using namespace std; const int N=2000; int a[N*2][2],g[N],dis[2][N],d[N]; bool link[N][N]; int n,m,s,t; void ins(int x,int y){ static int sum=0; a[++sum][0]=y,a[sum][1]=g[x],g[x]=sum; } void spfa(int*dis,int s){ int l=0,r=0; d[++r]=s; dis[s]=1; while (l!=r){ for (int i=g[d[++l]];i;i=a[i][1]) if (!dis[a[i][0]]){ dis[d[++r]=a[i][0]]=dis[d[l]]+1; } } } int main(){ ios::sync_with_stdio(false); cin>>n>>m>>s>>t; for (int i=1;i<=m;i++){ int x,y; cin>>x>>y; ins(x,y),ins(y,x); link[x][y]=link[y][x]=1; } spfa(dis[0],s); spfa(dis[1],t); int sum=0; for (int i=1;i<=n;i++) for (int j=i+1;j<=n;j++) if (!link[i][j]&&min(dis[0][i]+dis[1][j]-2+1,dis[0][j]+dis[1][i]-2+1)>=dis[0][t]-1)sum++; cout< #include "include/graph/op/all_ops.h" #include "src/delegate/npu/npu_converter_utils.h" namespace mindspore { int ReshapeNPUOp::IsSupport(const schema::Primitive *primitive, const std::vector &in_tensors, const std::vector &out_tensors) { if (in_tensors.size() != 2) { MS_LOG(WARNING) << "Npu op should have w2 input tensors."; return RET_NOT_SUPPORT; } auto shape_tensor = in_tensors.at(1); if (shape_tensor->data() == nullptr) { MS_LOG(WARNING) << "Npu reshape op only supports const shape."; return RET_NOT_SUPPORT; } return RET_OK; } int ReshapeNPUOp::Init(const schema::Primitive *primitive, const std::vector &in_tensors, const std::vector &out_tensors) { reshape_ = new (std::nothrow) hiai::op::Reshape(name_); if (reshape_ == nullptr) { MS_LOG(ERROR) << name_ << " op is nullptr"; return RET_ERROR; } return RET_OK; } int ReshapeNPUOp::SetNPUInputs(const std::vector &in_tensors, const std::vector &out_tensors, const std::vector &npu_inputs) { reshape_->set_input_x(*npu_inputs[0]); reshape_->set_input_shape(*npu_inputs[1]); return RET_OK; } ge::Operator *ReshapeNPUOp::GetNPUOp() { return this->reshape_; } ReshapeNPUOp::~ReshapeNPUOp() { if (reshape_ != nullptr) { delete reshape_; reshape_ = nullptr; } } } // namespace mindspore // student.cpp (implementation) #include "student.h" #include #include #include #include using namespace std; Student::Student(){ // new allows us to store on the heap using the type specifier like an object // Here the pointers declared in the interfaced are assigned to 50 // element arrays stored on the heap Surname = new string[50]; GivenName = new string[50]; address = new Address[50]; dob = new Date[50]; graduation = new Date[50]; gpa = new double[50]; creditHours = new int[50]; // the arrays however have no intialization, they could contain anything // the process below assigns sensible default values for each element fill_n(Surname, 50, "anonymous"); fill_n(GivenName, 50, "anonymous"); fill_n(address, 50, Address()); fill_n(dob, 50, Date()); fill_n(graduation, 50, Date()); fill_n(gpa, 50, 0); fill_n(creditHours, 50, 0); } // end null parameter constructor Student::~Student(){ // The destructor is necessary for removing things off the heap // this is similar to deleting nodes in linked list // where its important manage the data creation/destruction properly // to avoid memory leaks // objects responsible for allocating memory should be responsible for // destroying it. Your calls to new should be equal to the calls to delete. delete[] Surname; delete[] GivenName; delete[] address; delete[] dob; delete[] graduation; delete[] gpa; delete[] creditHours; } void Student::printName(){ stringstream ss; int i; for( i = 0; i < 50 ; i++){ cout << "Full Name: " << GivenName[i] << " " << Surname[i] << endl; address[i].printFullAddress(); dob[i].printDate(); graduation[i].printDate(); cout.precision(4); cout << "GPA: " << gpa[i] << endl; cout << "Credit Hours Complete: " << creditHours[i] << endl; cout << endl; } } void Student::loadData(){ // Parsing and File I/O declarations // instantiate ifstream(input stream class) object // instantiate ofstream(output stream class) object ifstream inFile; ofstream outFile; string currentLine; string subLine; stringstream current; stringstream converter; int i; int int_num; double double_num; inFile.open("students.dat"); if (inFile.is_open()){ // Read student.dat file and assign data to heap variables i = 0; // loads currentLine(string) till delimiter character \n is found getline(inFile,currentLine); while(getline(inFile,currentLine)){ // set no errors and clear stringstreams current.clear(); current.str(""); // load contents of currentLine(string) into current(stringstream) current.str(currentLine); // separate data from commas and assign to heap variables rinse and repeat getline(current,subLine,','); Surname[i] = subLine; getline(current,subLine,','); GivenName[i] = subLine; getline(current,subLine,','); address[i].setAddress1(subLine); getline(current,subLine,','); address[i].setAddress2(subLine); getline(current,subLine,','); address[i].setCity(subLine); getline(current,subLine,','); address[i].setState(subLine); getline(current,subLine,','); // this method is passes the string data to a stringstream // then passes the stringstream data to int variable converter << subLine; converter >> int_num; address[i].setZip(int_num); getline(current,subLine,','); dob[i].setDate(subLine); getline(current,subLine,','); graduation[i].setDate(subLine); // clean out converter converter.clear(); converter.str(""); getline(current,subLine,','); // convert string to double for assignment to gpa converter << subLine; converter >> double_num; gpa[i] = double_num; converter.clear(); converter.str(""); getline(current,subLine); converter << subLine; converter >> int_num; creditHours[i] = int_num; i += 1; } // end read student.dat inFile.close(); cout << "student.dat loaded and stored on heap" << endl; } // end if inFile is open else{ cout << "Could not open student.dat" << endl; } } // end loadData method void Student::write_fullReport(){ int i; // I/O Declartions ofstream outFile; outFile.open("fullReport.txt"); if(outFile.is_open()){ // write to fullReport.txt for( i = 0; i < 50 ; i++){ outFile << "Full Name: " << GivenName[i] << " " << Surname[i] << endl; outFile << "StreetAddress: " << address[i].getAddress1() << endl; outFile << "Address2: " << address[i].getAddress2() << endl; outFile << "City: " << address[i].getCity() << endl; outFile << "State: " << address[i].getState() << endl; outFile << "ZipCode: " << address[i].getZipCode() << endl; outFile << "Date Of Birth: " << dob[i].getMonth() << "/" << dob[i].getDay() << "/" << dob[i].getYear() << endl; outFile << "Date Of Graduation: " << graduation[i].getMonth() << "/" << graduation[i].getDay() << "/" << graduation[i].getYear() << endl; outFile << "GPA: " << gpa[i] << endl; outFile << "Credit Hours Complete: " << creditHours[i] << endl; outFile << endl; } // end write to fullReport.txt outFile.close(); cout << "fullReport.txt created" << endl; } // end if outFile is open else{ cout << "Could not open fullReport.txt" << endl; } } // end write_fullReport() method void Student::write_shortReport(){ int i; // I/O Declartions ofstream outFile; outFile.open("shortReport.txt"); if(outFile.is_open()){ // write to shortReport.txt for( i = 0; i < 50 ; i++){ outFile << "Full Name: " << GivenName[i] << " "; outFile << Surname[i] << endl; outFile << endl; } // end write to shortReport.txt outFile.close(); cout << "shortReport.txt created" << endl; } // end if outFile is open else{ cout << "Could not open shortReport.txt" << endl; } } // end write_shortReprot() method void Student::write_alphaReport(){ int i, j; int MAX = 50; // I/O Declartions ofstream outFile; outFile.open("alphaReport.txt"); if(outFile.is_open()){ // alphabetically sort heap of students (bubble sort) for (i = 0; i < MAX-1; i++){ for (j = 0; j < MAX-1-i; j++){ if((Surname[j].compare(Surname[j+1])) > 0){ swap(j+1,j); } } } // end alphabetically sort heap of students // write to alphaReport.txt for( i = 0; i < 50 ; i++){ outFile << "Full Name: " << GivenName[i] << " "; outFile << Surname[i] << endl; outFile << endl; } // end write to alphaReport.txt outFile.close(); cout << "alphaReport.txt created" << endl; } // end if outFile is open else{ cout << "Could not open alphaReport.txt" << endl; } } // end write_alphaReport() method void Student::swap(int a, int b){ // swap student data string tempName1, tempName2; Address tempAddress; Date tempDOB, tempGrad; double tempGPA; int tempCredits; tempName1 = Surname[a]; tempName2 = GivenName[a]; tempAddress = address[a]; tempDOB = dob[a]; tempGrad = graduation[a]; tempGPA = gpa[a]; tempCredits = creditHours[a]; Surname[a] = Surname[b]; GivenName[a] = GivenName[b]; address[a] = address[b]; dob[a] = dob[b]; graduation[a] = graduation[b]; gpa[a] = gpa[b]; creditHours[a] = creditHours[b]; Surname[b] = tempName1; GivenName[b] = tempName2; address[b] = tempAddress; dob[b] = tempDOB; graduation[b] = tempGrad; gpa[b] = tempGPA; creditHours[b] = tempCredits; } // end swap() method // // Created by Khyber on 7/18/2019. // #include "src/share/llvm/operandBundles.h" namespace llvm { ArrayRef getOperandBundles(const CallBase& inst) noexcept { return {reinterpret_cast(inst.bundle_op_info_begin()), inst.getNumOperandBundles()}; } } #include "stdafx.h" #include "Event.h" Event::Event(BOOL bInitiallyOwn, BOOL bManualReset, LPCTSTR pstrName, LPSECURITY_ATTRIBUTES lpsaAttribute) { m_hObject = ::CreateEvent(lpsaAttribute, bManualReset, bInitiallyOwn, pstrName); } Event::~Event() { if (NULL != m_hObject) { ::CloseHandle(m_hObject); m_hObject = NULL; } } BOOL Event::SetEvent() { return ::SetEvent(m_hObject); } BOOL Event::PulseEvent() { return ::PulseEvent(m_hObject); } BOOL Event::ResetEvent() { return ::ResetEvent(m_hObject); } /* * Copyright (c) 2015-2020, Onbings. All rights reserved. * * 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. * * This module defines the bofobserver/bofobservable design pattern * * Name: bofobserver.h * Author: : * Web: onbings.dscloud.me * Revision: 1.0 * * Rem: http://come-david.developpez.com/tutoriels/dps/?page=BofObserver * * History: * * V 1.00 Dec 26 2013 BHA : Initial release */ #include #include #include #include #include "bofstd/bofobserver.h" BofObserver::~BofObserver() { // For each observed object, we ask him to remove its current observer ConstObservableIterator ItEnd_O = mListOfObservable_O.end(); for (ObservableIterator It_O = mListOfObservable_O.begin(); It_O != ItEnd_O; ++It_O) { (*It_O)->UnregisterObserver(this); } } void BofObserver::V_ObservableNotify(BofObservable * /*_pObservable_O*/, uint64_t /*_User_U64*/, void * /*_pUser*/) {} void BofObserver::RegisterObservable(BofObservable *_pBofObservable_O) { std::lock_guard Lock_O(mCsObserver_O); mListOfObservable_O.push_back(_pBofObservable_O); } void BofObserver::UnregisterObservable(BofObservable *_pBofObservable_O) { // Remove observed object. if (mListOfObservable_O.size()) { ObservableIterator It_O = std::find(mListOfObservable_O.begin(), mListOfObservable_O.end(), _pBofObservable_O); if (It_O != mListOfObservable_O.end()) { std::lock_guard Lock_O(mCsObserver_O); mListOfObservable_O.erase(It_O); } } } void BofObserver::ObserverNotifyAll(uint64_t _User_U64, void *_pUser) { // Notify each observer that the value has changed ObservableIterator It_O = mListOfObservable_O.begin(); ConstObservableIterator ItEnd_O = mListOfObservable_O.end(); for (; It_O != ItEnd_O; ++It_O) { (*It_O)->V_ObserverNotifyAll(this, _User_U64, _pUser); } } BofObservable::BofObservable() {} BofObservable::~BofObservable() { // Idem BofObserver::~BofObserver ObserverIterator It_O = mListOfObserver_O.begin(); ConstObserverIterator ItEnd_O = mListOfObserver_O.end(); for (; It_O != ItEnd_O; ++It_O) { (*It_O)->UnregisterObservable(this); } } void BofObservable::RegisterObserver(BofObserver *_pBofObserver_O) { // Add observer to list { std::lock_guard Lock_O(mCsObservable_O); mListOfObserver_O.push_back(_pBofObserver_O); } // And we give him a new observed object. _pBofObserver_O->RegisterObservable(this); } void BofObservable::UnregisterObserver(BofObserver *_pBofObserver_O) { // Idem BofObserver::RegisterObserver if (mListOfObserver_O.size()) { ObserverIterator It_O = std::find(mListOfObserver_O.begin(), mListOfObserver_O.end(), _pBofObserver_O); if (It_O != mListOfObserver_O.end()) { std::lock_guard Lock_O(mCsObservable_O); mListOfObserver_O.erase(It_O); } } } void BofObservable::V_ObserverNotifyAll(BofObserver * /*_pObserver_O*/, uint64_t /*_User_U64*/, void * /*_pUser*/) {} void BofObservable::ObservableNotify(uint64_t _User_U64, void *_pUser) { // Notify each observer that the value has changed ObserverIterator It_O = mListOfObserver_O.begin(); ConstObserverIterator ItEnd_O = mListOfObserver_O.end(); for (; It_O != ItEnd_O; ++It_O) { (*It_O)->V_ObservableNotify(this, _User_U64, _pUser); } } #if 0 // Example void Barometre::Change(int _Valeur_i) { pression = _Valeur_i; Notify(); } int Barometre::Status() const { return pression; } void Thermometre::Change(int _Valeur_i) { temperature = _Valeur_i; Notify(); } Info Thermometre::Status() const { return temperature; } #endif #if 0 // App Barometre barometre; Thermometre thermometre; // un faux bloc pour limiter la port�e de la station { MeteoFrance station; thermometre.RegisterObserver(&station); barometre.RegisterObserver(&station); thermometre.Change(31); barometre.Change(975); } thermometre.Change(45); #endif6lackmag3/Play- #include "GSH_Null.h" CGSH_Null::CGSH_Null() { } CGSH_Null::~CGSH_Null() { } void CGSH_Null::InitializeImpl() { } void CGSH_Null::ReleaseImpl() { } void CGSH_Null::ProcessHostToLocalTransfer() { } void CGSH_Null::ProcessLocalToHostTransfer() { } void CGSH_Null::ProcessLocalToLocalTransfer() { } void CGSH_Null::ProcessClutTransfer(uint32, uint32) { } void CGSH_Null::ReadFramebuffer(uint32, uint32, void*) { } CGSHandler::FactoryFunction CGSH_Null::GetFactoryFunction() { return std::bind(&CGSH_Null::GSHandlerFactory); } CGSHandler* CGSH_Null::GSHandlerFactory() { return new CGSH_Null(); } /* PICCANTE The hottest HDR imaging library! http://vcg.isti.cnr.it/piccante Copyright (C) 2014 Visual Computing Laboratory - ISTI CNR http://vcg.isti.cnr.it First author: 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/. */ #ifndef PIC_FILTERING_FILTER_DRAGO_TMO_HPP #define PIC_FILTERING_FILTER_DRAGO_TMO_HPP #include "../util/array.hpp" #include "../filtering/filter.hpp" #include "../filtering/filter_luminance.hpp" namespace pic { /** * @brief The FilterDragoTMO class */ class FilterDragoTMO: public Filter { protected: float constant1, constant2, Lw_Max_scaled, Lw_a_scaled; float b, Ld_Max, Lw_Max, Lw_a; /** * @brief ProcessBBox * @param dst * @param src * @param box */ void ProcessBBox(Image *dst, ImageVec src, BBox *box); public: /** * @brief FilterDragoTMO */ FilterDragoTMO(); /** * @brief FilterDragoTMO * @param Ld_Max * @param b * @param Lw_Max * @param Lwa */ FilterDragoTMO(float Ld_Max, float b, float Lw_Max, float Lwa); /** * @brief update * @param Ld_Max * @param b * @param Lw_Max * @param Lwa */ void update(float Ld_Max, float b, float Lw_Max, float Lwa); }; PIC_INLINE FilterDragoTMO::FilterDragoTMO() : Filter() { update(100.0f, 0.95f, 1e6f, 0.5f); } PIC_INLINE FilterDragoTMO::FilterDragoTMO(float Ld_Max, float b, float Lw_Max, float Lw_a) : Filter() { update(Ld_Max, b, Lw_Max, Lw_a); } PIC_INLINE void FilterDragoTMO::update(float Ld_Max, float b, float Lw_Max, float Lw_a) { //protected values are assigned/computed this->Ld_Max = (Ld_Max > 0.0f) ? Ld_Max : 100.0f; this->b = (b > 0.0f) ? b : 0.95f; this->Lw_Max = (Lw_Max > 0.0f) ? Lw_Max : 1e6f; this->Lw_a = (Lw_a > 0.0f) ? Lw_a : 0.5f; //constants Lw_a_scaled = this->Lw_a / powf(1.0f + b - 0.85f, 5.0f); Lw_Max_scaled = this->Lw_Max / Lw_a_scaled; constant1 = logf(b) / logf(0.5f); constant2 = (Ld_Max / 100.0f) / (log10f(1.0f + Lw_Max_scaled)); } PIC_INLINE void FilterDragoTMO::ProcessBBox(Image *dst, ImageVec src, BBox *box) { int channels = src[0]->channels; for(int j = box->y0; j < box->y1; j++) { for(int i = box->x0; i < box->x1; i++) { float *dataIn = (*src[0])(i, j); float *dataLum = (*src[1])(i, j); float *dataOut = (*dst )(i, j); if(dataLum[0] > 0.0f) { float L_scaled = dataLum[0] / Lw_a_scaled; float tmp = powf((L_scaled / Lw_Max_scaled), constant1); float Ld = constant2 * logf(1.0f + L_scaled) / logf(2.0f + 8.0f * tmp); for(int k = 0; k < channels; k++) { dataOut[k] = (dataIn[k] * Ld) / dataLum[0]; } } else { Array::assign(0.0f, dataOut, src[0]->channels); } } } } } // end namespace pic #endif /* PIC_FILTERING_FILTER_DRAGO_TMO_HPP */ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkSceneIOTestScenarioProvider.h" #include "mitkPointSet.h" #include "mitkImage.h" #include "mitkImageGenerator.h" #include "mitkSurface.h" #include "mitkGeometryData.h" #include "mitkProperties.h" #include #include #include namespace { std::string VeryLongText = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.Donec a diam lectus.Sed sit amet ipsum mauris.Maecenas congue ligula ac quam viverra nec consectetur ante hendrerit.Donec et mollis dolor.Praesent et diam eget libero egestas mattis sit amet vitae augue.Nam tincidunt congue enim, ut porta lorem lacinia consectetur.Donec ut libero sed arcu vehicula ultricies a non tortor.Lorem ipsum dolor sit amet, consectetur adipiscing elit.Aenean ut gravida lorem.Ut turpis felis, pulvinar a semper sed, adipiscing id dolor.Pellentesque auctor nisi id magna consequat sagittis.Curabitur dapibus enim sit amet elit pharetra tincidunt feugiat nisl imperdiet.Ut convallis libero in urna ultrices accumsan.Donec sed odio eros.Donec viverra mi quis quam pulvinar at malesuada arcu rhoncus.Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.In rutrum accumsan ultricies.Mauris vitae nisi at sem facilisis semper ac in est.\n" "Vivamus fermentum semper porta.Nunc diam velit, adipiscing ut tristique vitae, sagittis vel odio.Maecenas convallis ullamcorper ultricies.Curabitur ornare, ligula semper consectetur sagittis, nisi diam iaculis velit, id fringilla sem nunc vel mi.Nam dictum, odio nec pretium volutpat, arcu ante placerat erat, non tristique elit urna et turpis.Quisque mi metus, ornare sit amet fermentum et, tincidunt et orci.Fusce eget orci a orci congue vestibulum.Ut dolor diam, elementum et vestibulum eu, porttitor vel elit.Curabitur venenatis pulvinar tellus gravida ornare.Sed et erat faucibus nunc euismod ultricies ut id justo.Nullam cursus suscipit nisi, et ultrices justo sodales nec.Fusce venenatis facilisis lectus ac semper.Aliquam at massa ipsum.Quisque bibendum purus convallis nulla ultrices ultricies.Nullam aliquam, mi eu aliquam tincidunt, purus velit laoreet tortor, viverra pretium nisi quam vitae mi.Fusce vel volutpat elit.Nam sagittis nisi dui.\r\n" "Suspendisse lectus leo, consectetur in tempor sit amet, placerat quis neque.Etiam luctus porttitor lorem, sed suscipit est rutrum non.Curabitur lobortis nisl a enim congue semper.Aenean commodo ultrices imperdiet.Vestibulum ut justo vel sapien venenatis tincidunt.Phasellus eget dolor sit amet ipsum dapibus condimentum vitae quis lectus.Aliquam ut massa in turpis dapibus convallis.Praesent elit lacus, vestibulum at malesuada et, ornare et est.Ut augue nunc, sodales ut euismod non, adipiscing vitae orci.Mauris ut placerat justo.Mauris in ultricies enim.Quisque nec est eleifend nulla ultrices egestas quis ut quam.Donec sollicitudin lectus a mauris pulvinar id aliquam urna cursus.Cras quis ligula sem, vel elementum mi.Phasellus non ullamcorper urna.\t\n" "Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos.In euismod ultrices facilisis.Vestibulum porta sapien adipiscing augue congue id pretium lectus molestie.Proin quis dictum nisl.Morbi id quam sapien, sed vestibulum sem.Duis elementum rutrum mauris sed convallis.Proin vestibulum magna mi.Aenean tristique hendrerit magna, ac facilisis nulla hendrerit ut.Sed non tortor sodales quam auctor elementum.Donec hendrerit nunc eget elit pharetra pulvinar.Suspendisse id tempus tortor.Aenean luctus, elit commodo laoreet commodo, justo nisi consequat massa, sed vulputate quam urna quis eros.Donec vel." ; } // --------------- SceneIOTestScenarioProvider::Scenario --------------- mitk::DataStorage::Pointer mitk::SceneIOTestScenarioProvider::Scenario::BuildDataStorage() const { return (*m_ScenarioProvider.*m_ProviderMethod)(); // calls function } mitk::SceneIOTestScenarioProvider::Scenario::Scenario(const std::string& _key, const SceneIOTestScenarioProvider* _scenarioProvider, SceneIOTestScenarioProvider::BuilderMethodPointer _providerMethod, bool _isSerializable, const std::string& _referenceArchiveFilename, bool _isReferenceLoadable, double _comparisonPrecision) : key(_key) , serializable(_isSerializable) , referenceArchiveFilename(_referenceArchiveFilename) , referenceArchiveLoadable(_isReferenceLoadable) , comparisonPrecision(_comparisonPrecision) , m_ScenarioProvider(_scenarioProvider) , m_ProviderMethod(_providerMethod) { } // --------------- SceneIOTestScenarioProvider --------------- mitk::SceneIOTestScenarioProvider::ScenarioList mitk::SceneIOTestScenarioProvider::GetAllScenarios() const { return m_Scenarios; } void mitk::SceneIOTestScenarioProvider::AddScenario(const std::string& key, BuilderMethodPointer creator, bool isSerializable, const std::string& referenceArchiveFilename, bool isReferenceLoadable, double comparisonPrecision) { Scenario newScenario(key, this, creator, isSerializable, referenceArchiveFilename, isReferenceLoadable, comparisonPrecision); m_Scenarios.push_back(newScenario); } mitk::DataStorage::Pointer mitk::SceneIOTestScenarioProvider::EmptyStorage() const { mitk::DataStorage::Pointer storage = StandaloneDataStorage::New().GetPointer(); return storage; } mitk::DataStorage::Pointer mitk::SceneIOTestScenarioProvider::OneEmptyNode() const { mitk::DataStorage::Pointer storage = StandaloneDataStorage::New().GetPointer(); mitk::DataNode::Pointer node = DataNode::New(); storage->Add(node); return storage; } mitk::DataStorage::Pointer mitk::SceneIOTestScenarioProvider::OneEmptyNamedNode() const { mitk::DataStorage::Pointer storage = StandaloneDataStorage::New().GetPointer(); mitk::DataNode::Pointer node = DataNode::New(); node->SetName("Urmel"); storage->Add(node); return storage; } mitk::DataStorage::Pointer mitk::SceneIOTestScenarioProvider::ManyTopLevelNodes() const { mitk::DataStorage::Pointer storage = StandaloneDataStorage::New().GetPointer(); for ( auto i = 0; i < m_HowMuchIsMany; ++i ) { mitk::DataNode::Pointer node = DataNode::New(); std::stringstream s; s << "Node #" << i; node->SetName(s.str()); storage->Add(node); } return storage; } mitk::DataStorage::Pointer mitk::SceneIOTestScenarioProvider::LineOfManyOnlyChildren() const { mitk::DataStorage::Pointer storage = StandaloneDataStorage::New().GetPointer(); mitk::DataNode::Pointer parent; for ( auto i = 0; i < m_HowMuchIsMany; ++i ) { mitk::DataNode::Pointer node = DataNode::New(); std::stringstream s; s << "Node #" << i; node->SetName(s.str()); storage->Add(node, parent); parent = node; } return storage; } #define AddNode(name) \ storage->Add(name); #define DefineNode(name) \ mitk::DataNode::Pointer name = mitk::DataNode::New(); \ name->SetName( #name ); #define DefNode0(name) \ DefineNode(name) \ AddNode(name) #define DefNode1(source, name) \ DefineNode(name) \ storage->Add(name, source); #define DefNode2(source1, source2, name) \ DefineNode(name) \ { mitk::DataStorage::SetOfObjects::Pointer sources = mitk::DataStorage::SetOfObjects::New(); \ sources->push_back(source1); \ sources->push_back(source2); \ storage->Add(name, sources); } #define DefNode3(source1, source2, source3, name) \ DefineNode(name) \ { mitk::DataStorage::SetOfObjects::Pointer sources = mitk::DataStorage::SetOfObjects::New(); \ sources->push_back(source1); \ sources->push_back(source2); \ sources->push_back(source3); \ storage->Add(name, sources); } mitk::DataStorage::Pointer mitk::SceneIOTestScenarioProvider::ComplicatedFamilySituation() const { mitk::DataStorage::Pointer storage = StandaloneDataStorage::New().GetPointer(); // constructing a hierarchy with multiple levels // and a couple of multiple parent relations. // Anybody, feel free to make this something // meaningful and/or visualize it :-) DefNode0(Color) DefNode0(White) DefNode1(Color, Green) DefNode1(Color, Election) DefNode1(Color, Red) DefNode1(Green, Yellow) DefNode1(Election, Looser) DefNode1(Election, FreeBeer) DefNode1(Election, Winner) DefNode1(Looser, Tears) DefNode1(Looser, Anger) DefNode1(FreeBeer, OpenSource); DefNode1(White, Sweet) DefNode2(White, Sweet, Sugar) DefNode2(Red, Sweet, Tomatoe) DefNode2(Tomatoe, Sugar, Ketchup) DefNode1(Ketchup, BBQSauce) DefNode1(Tomatoe, ATLAS) DefNode0(Fish) DefNode0(OperatingSystem) DefNode1(Fish, Bird) DefNode1(Bird, Penguin) DefNode3(Penguin, OperatingSystem, OpenSource, Linux) return storage; } mitk::DataStorage::Pointer mitk::SceneIOTestScenarioProvider::Image() const { mitk::DataStorage::Pointer storage = StandaloneDataStorage::New().GetPointer(); { // Image of ints mitk::Image::Pointer image3Dints = mitk::ImageGenerator::GenerateRandomImage(10, 5, 7, // dim 1, 0.5, 0.5,// spacing 1, // time steps 3000, -1000); // random max / min mitk::DataNode::Pointer node = DataNode::New(); node->SetName("Image-Int"); node->SetData(image3Dints); storage->Add(node); } { // Image of doubles mitk::Image::Pointer image3Ddouble = mitk::ImageGenerator::GenerateRandomImage(5, 10, 8, // dim 1, 0.5, 0.5,// spacing 2, // time steps 3000, -1000); // random max / min mitk::DataNode::Pointer node = DataNode::New(); node->SetName("Image-Double"); node->SetData(image3Ddouble); storage->Add(node); } return storage; } mitk::DataStorage::Pointer mitk::SceneIOTestScenarioProvider::Surface() const { mitk::DataStorage::Pointer storage = StandaloneDataStorage::New().GetPointer(); { // Surface vtkSmartPointer points1 = vtkSmartPointer::New(); points1->InsertNextPoint(0.0, 0.0, 0.0); points1->InsertNextPoint(1.0, 0.0, 0.0); points1->InsertNextPoint(0.0, 1.0, 0.0); points1->InsertNextPoint(1.0, 1.0, 0.0); vtkSmartPointer polygon1 = vtkSmartPointer::New(); polygon1->GetPointIds()->SetNumberOfIds(4); polygon1->GetPointIds()->SetId(0, 0); polygon1->GetPointIds()->SetId(1, 1); polygon1->GetPointIds()->SetId(2, 2); polygon1->GetPointIds()->SetId(3, 3); vtkSmartPointer polygon2 = vtkSmartPointer::New(); polygon2->GetPointIds()->SetNumberOfIds(4); polygon2->GetPointIds()->SetId(0, 3); polygon2->GetPointIds()->SetId(1, 2); polygon2->GetPointIds()->SetId(2, 0); polygon2->GetPointIds()->SetId(3, 1); //generate polydatas vtkSmartPointer polygonArray1 = vtkSmartPointer::New(); polygonArray1->InsertNextCell(polygon1); vtkSmartPointer polydata1 = vtkSmartPointer::New(); polydata1->SetPoints(points1); polydata1->SetPolys(polygonArray1); vtkSmartPointer polygonArray2 = vtkSmartPointer::New(); polygonArray2->InsertNextCell(polygon2); vtkSmartPointer polyDataTwo = vtkSmartPointer::New(); polyDataTwo->SetPoints(points1); polyDataTwo->SetPolys(polygonArray2); //generate surfaces mitk::Surface::Pointer surface = mitk::Surface::New(); surface->SetVtkPolyData(polydata1); mitk::DataNode::Pointer node = DataNode::New(); node->SetName("Surface"); node->SetData(surface); storage->Add(node); } return storage; } mitk::DataStorage::Pointer mitk::SceneIOTestScenarioProvider::PointSet() const { mitk::DataStorage::Pointer storage = StandaloneDataStorage::New().GetPointer(); { // PointSet mitk::PointSet::Pointer ps = mitk::PointSet::New(); mitk::PointSet::PointType p; mitk::FillVector3D(p, 1.0, -2.0, 33.0); ps->SetPoint(0, p); mitk::FillVector3D(p, 100.0, -200.0, 3300.0); ps->SetPoint(1, p); mitk::FillVector3D(p, 2.0, -3.0, 22.0); ps->SetPoint(2, p, mitk::PTCORNER); // add point spec mitk::DataNode::Pointer node = DataNode::New(); node->SetName("PointSet"); node->SetData(ps); storage->Add(node); } return storage; } mitk::DataStorage::Pointer mitk::SceneIOTestScenarioProvider::GeometryData() const { mitk::DataStorage::Pointer storage = StandaloneDataStorage::New().GetPointer(); { // GeometryData mitk::GeometryData::Pointer gdata = mitk::GeometryData::New(); // define Geometry3D parameters mitk::AffineTransform3D::MatrixType matrix; matrix[0][0] = 1.1; matrix[1][1] = 2.2; matrix[2][2] = 3.3; mitk::AffineTransform3D::OffsetType offset; mitk::FillVector3D(offset, 0.1, 0.2, 0.3); bool isImageGeometry(false); unsigned int frameOfReferenceID(47); mitk::BaseGeometry::BoundsArrayType bounds; bounds[0] = std::numeric_limits::min(); bounds[1] = -52.723; bounds[2] = -0.002; bounds[3] = 918273645.18293746; bounds[4] = -0.002; bounds[5] = +52.723; mitk::Point3D origin; mitk::FillVector3D(origin, 5.1, 5.2, 5.3); mitk::Vector3D spacing; mitk::FillVector3D(spacing, 2.1, 2.2, 2.3); // build GeometryData from matrix/offset/etc. mitk::AffineTransform3D::Pointer newTransform = mitk::AffineTransform3D::New(); newTransform->SetMatrix(matrix); newTransform->SetOffset(offset); mitk::Geometry3D::Pointer newGeometry = mitk::Geometry3D::New(); newGeometry->SetFrameOfReferenceID(frameOfReferenceID); newGeometry->SetImageGeometry(isImageGeometry); newGeometry->SetIndexToWorldTransform(newTransform); newGeometry->SetBounds(bounds); newGeometry->SetOrigin(origin); newGeometry->SetSpacing(spacing); mitk::GeometryData::Pointer geometryData = mitk::GeometryData::New(); geometryData->SetGeometry(newGeometry); mitk::DataNode::Pointer node = DataNode::New(); node->SetName("GeometryData"); node->SetData(geometryData); storage->Add(node); } return storage; } mitk::DataStorage::Pointer mitk::SceneIOTestScenarioProvider::SpecialProperties() const { mitk::DataStorage::Pointer storage = StandaloneDataStorage::New().GetPointer(); mitk::DataNode::Pointer node = DataNode::New(); node->SetName("Camion"); node->SetProperty("", StringProperty::New("Colis")); // no name! node->SetProperty("Livre", StringProperty::New( VeryLongText ) ); // defined at the top of this file node->SetProperty(VeryLongText.c_str(), StringProperty::New( "Shorty" ) ); node->GetPropertyList("Chapitre1")->SetProperty("Page 1", StringProperty::New( VeryLongText )); node->GetPropertyList("Chapitre1")->SetProperty("Page 2", StringProperty::New( VeryLongText )); node->GetPropertyList("Chapitre 2")->SetProperty("Page", StringProperty::New( VeryLongText )); node->GetPropertyList("Chapitre 3")->SetProperty("Page", StringProperty::New( VeryLongText )); node->GetPropertyList(VeryLongText)->SetProperty("Page", StringProperty::New( VeryLongText )); // not working (NaN etc.) //node->SetProperty("NotAFloat", FloatProperty::New( sqrt(-1.0) ) ); node->SetProperty("sqrt(2)", FloatProperty::New( -sqrt(2.0) ) ); node->SetProperty("sqrt(3)", FloatProperty::New( sqrt(3.0) ) ); // most values work fine, just min/max double produces serialization precision errors node->SetProperty("sqrt(4)", DoubleProperty::New( -sqrt(4.0) ) ); node->SetProperty("sqrt(5)", DoubleProperty::New( sqrt(5.0) ) ); //node->SetProperty("maxd", DoubleProperty::New( std::numeric_limits::max() ) ); node->SetProperty("zero", DoubleProperty::New( 0.0 ) ); node->SetProperty("minzero", DoubleProperty::New( -0.0 ) ); //node->SetProperty("mind", DoubleProperty::New( std::numeric_limits::min() ) ); storage->Add(node); return storage; } // 2DSoundRender.cpp: implementation of the C2DSoundRender class. // ////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "2DSoundRender.h" #include "2DSound.h" #include "device.h" #include "xr_sndman.h" #include "xr_ini.h" ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// C2DSoundRender::C2DSoundRender() { } C2DSoundRender::~C2DSoundRender() { } void C2DSoundRender::OnMove() { for (u32 i=0; iOnMove(); } } } int C2DSoundRender::FindByName(LPCSTR name) { for (u32 i=0; ifName,name)==0) return i; } } return -1; } int C2DSoundRender::FindEmptySlot() { for (u32 i=0; i pv; sounds.push_back( pv ); refcounts.push_back(1); int i = sounds.size()-1; sounds[i].push_back(p); return i; } int C2DSoundRender::CreateSound(CInifile *pIni, LPCSTR section) { int fnd; FILE_NAME fn; strcpy (fn,pIni->ReadSTRING(section, "fname")); if ((fnd=FindByName(fn))>=0) { refcounts[fnd]+=1; return fnd; } // sound not found - create new C2DSound *pSnd = new C2DSound; pSnd->Load(pIni, section); // search for empty slot if ((fnd=FindEmptySlot())>=0) { // empty slot sounds[fnd].push_back(pSnd); refcounts[fnd]+=1; return fnd; } return Append(pSnd); } int C2DSoundRender::CreateSound(LPCSTR name) { int fnd; if ((fnd=FindByName(name))>=0) { refcounts[fnd]+=1; return fnd; } // sound not found - create new C2DSound *pSnd = new C2DSound; pSnd->Load(name); // search for empty slot if ((fnd=FindEmptySlot())>=0) { // empty slot sounds[fnd].push_back(pSnd); refcounts[fnd]+=1; return fnd; } return Append(pSnd); } void C2DSoundRender::DeleteSound(int& hSound) { VERIFY(hSound>=0); VERIFY(hSound0); refcounts[hSound]-=1; if (refcounts[hSound]==0) { // all references destroyed - destroy sound as itself for (u32 i=0; i=0); VERIFY(hSoundisPlaying()) return sounds[hSound][i]; } // xr_free sound not found - create duplicate C2DSound *pSnd = new C2DSound; pSnd->Load(sounds[hSound][0]); sounds[hSound].push_back(pSnd); return pSnd; } C2DSound* C2DSoundRender::Play(int hSound, BOOL bLoop, int iLoopCnt) { C2DSound *pSnd = GetFreeSound(hSound); pSnd->Play(bLoop, iLoopCnt); return pSnd; } void C2DSoundRender::Reload() { for (u32 i=0; iStop(); _RELEASE(sounds[i][0]->pBuffer); sounds[i][0]->Load((LPCSTR)0); sounds[i][0]->bNeedUpdate = true; if (sounds[i][0]->isPlaying()) { sounds[i][0]->Play(sounds[i][0]->bMustLoop, sounds[i][0]->iLoopCountRested); } // Clones for (u32 j=1; jStop(); _RELEASE(sounds[i][j]->pBuffer); pSounds->pDevice->DuplicateSoundBuffer(sounds[i][0]->pBuffer,&sounds[i][j]->pBuffer); VERIFY (sounds[i][j]->pBuffer); sounds[i][j]->bNeedUpdate = true; if (sounds[i][j]->isPlaying()) { sounds[i][j]->Play(sounds[i][j]->bMustLoop, sounds[i][j]->iLoopCountRested); } } } } } #include "MainForm.h" using namespace System; using namespace System::Windows::Forms; [System::STAThread] int main(array ^args) { Application::EnableVisualStyles(); Application::SetCompatibleTextRenderingDefault(false); DiplomaUI::MainForm myForm; Application::Run(%myForm); return 0; }#include #include #include #include using namespace std; void clean_breaklines(string file_name){ // String para armazenar cada linha string s; // Cria vetor para armanzenar cada linha válida no arquivo .txt vector content_file; // Cria arquivo para leitura ifstream file; // Abre arquivo file_name = "doc/" + file_name; file.open(file_name.c_str()); // Variável para informar em qual linha existe um '\n' int numero_linha = 1; // Looping para percorrer todo o arquivo capturando apenas as quebras de linha while(getline(file, s)){ // Se a linha tiver um '\n' if(s.size() == 0){ cout << "Tem espaço aqui na linha " << numero_linha << "!" << endl; }else{ // Coloca a linha válida no vetor content_file.push_back(s); } numero_linha++; } // Fecha arquivo file.close(); // Remove arquivo para criar um novo com o mesmo nome // Descomente a linha abaixo para fazer a substituição do novo arquivo // remove(file_name.c_str()); // Abre arquivo para escrita ofstream new_file; // Opcional: coloquei um outro nome para melhor visualização file_name = "new_" + file_name; // Abre novo arquivo para escrita new_file.open(file_name.c_str()); // Insere no arquivo cada linha armazenada no vetor for(int i = 0; i < content_file.size(); i++){ new_file << content_file[i] << endl; } // Fecha o novo arquivo new_file.close(); } int main(){ string file_name; cout << "Insira o nome do arquivo a ser executado: " << endl; cin >> file_name; clean_breaklines(file_name); return 0; } 10-100 ////////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2000-2001 Microsoft Corporation // // Module Name: // CClusCfgIPAddressInfo.cpp // // Description: // This file contains the definition of the CClusCfgIPAddressInfo // class. // // The class CClusCfgIPAddressInfo represents a cluster manageable // network. It implements the IClusCfgIPAddressInfo interface. // // Maintained By: // (GalenB) 23-MAR-2000 // ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// // Include Files ////////////////////////////////////////////////////////////////////////////// #include "Pch.h" #include "CClusCfgIPAddressInfo.h" #include ////////////////////////////////////////////////////////////////////////////// // Constant Definitions ////////////////////////////////////////////////////////////////////////////// DEFINE_THISCLASS( "CClusCfgIPAddressInfo" ); //*************************************************************************// ///////////////////////////////////////////////////////////////////////////// // CClusCfgIPAddressInfo class ///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// //++ // // CClusCfgIPAddressInfo::S_HrCreateInstance // // Description: // Create a CClusCfgIPAddressInfo instance. // // Arguments: // None. // // Return Values: // Pointer to CClusCfgIPAddressInfo instance. // //-- ////////////////////////////////////////////////////////////////////////////// HRESULT CClusCfgIPAddressInfo::S_HrCreateInstance( IUnknown ** ppunkOut ) { TraceFunc( "" ); Assert( ppunkOut != NULL ); HRESULT hr = S_OK; CClusCfgIPAddressInfo * pccipai = NULL; if ( ppunkOut == NULL ) { hr = THR( E_POINTER ); goto Cleanup; } // if: pccipai = new CClusCfgIPAddressInfo(); if ( pccipai == NULL ) { hr = THR( E_OUTOFMEMORY ); goto Cleanup; } // if: error allocating object hr = THR( pccipai->HrInit() ); if ( FAILED( hr ) ) { goto Cleanup; } // if: HrInit() failed hr = THR( pccipai->TypeSafeQI( IUnknown, ppunkOut ) ); if ( FAILED( hr ) ) { goto Cleanup; } // if: QI failed Cleanup: if ( FAILED( hr ) ) { LogMsg( L"[SRV] CClusCfgIPAddressInfo::S_HrCreateInstance() failed. (hr = %#08x)", hr ); } // if: if ( pccipai != NULL ) { pccipai->Release(); } // if: HRETURN( hr ); } //*** CClusCfgIPAddressInfo::S_HrCreateInstance ////////////////////////////////////////////////////////////////////////////// //++ // // CClusCfgIPAddressInfo::S_HrCreateInstance // // Description: // Create a CClusCfgIPAddressInfo instance. // // Arguments: // None. // // Return Values: // Pointer to CClusCfgIPAddressInfo instance. // //-- ////////////////////////////////////////////////////////////////////////////// HRESULT CClusCfgIPAddressInfo::S_HrCreateInstance( ULONG ulIPAddressIn , ULONG ulIPSubnetIn , IUnknown ** ppunkOut ) { TraceFunc( "" ); Assert( ppunkOut != NULL ); Assert( ulIPAddressIn != 0 ); Assert( ulIPSubnetIn != 0 ); HRESULT hr = S_OK; CClusCfgIPAddressInfo * pccipai = NULL; if ( ppunkOut == NULL ) { hr = THR( E_POINTER ); goto Cleanup; } // if: pccipai = new CClusCfgIPAddressInfo(); if ( pccipai == NULL ) { hr = THR( E_OUTOFMEMORY ); goto Cleanup; } // if: error allocating object hr = THR( pccipai->HrInit( ulIPAddressIn, ulIPSubnetIn ) ); if ( FAILED( hr ) ) { goto Cleanup; } // if: HrInit() failed hr = THR( pccipai->TypeSafeQI( IUnknown, ppunkOut ) ); Cleanup: if ( FAILED( hr ) ) { LogMsg( L"[SRV] CClusCfgIPAddressInfo::S_HrCreateInstance( ULONG, ULONG ) failed. (hr = %#08x)", hr ); } // if: if ( pccipai != NULL ) { pccipai->Release(); } // if: HRETURN( hr ); } //*** CClusCfgIPAddressInfo::S_HrCreateInstance ////////////////////////////////////////////////////////////////////////////// //++ // // CClusCfgIPAddressInfo::CClusCfgIPAddressInfo // // Description: // Constructor of the CClusCfgIPAddressInfo class. This initializes // the m_cRef variable to 1 instead of 0 to account of possible // QueryInterface failure in DllGetClassObject. // // Arguments: // None. // // Return Value: // None. // // Remarks: // None. // //-- ////////////////////////////////////////////////////////////////////////////// CClusCfgIPAddressInfo::CClusCfgIPAddressInfo( void ) : m_cRef( 1 ) { TraceFunc( "" ); // Increment the count of components in memory so the DLL hosting this // object cannot be unloaded. InterlockedIncrement( &g_cObjects ); Assert( m_ulIPAddress == 0 ); Assert( m_ulIPSubnet == 0 ); Assert( m_pIWbemServices == NULL ); Assert( m_picccCallback == NULL ); TraceFuncExit(); } //*** CClusCfgIPAddressInfo::CClusCfgIPAddressInfo ////////////////////////////////////////////////////////////////////////////// //++ // // CClusCfgIPAddressInfo::~CClusCfgIPAddressInfo // // Description: // Desstructor of the CClusCfgIPAddressInfo class. // // Arguments: // None. // // Return Value: // None. // // Remarks: // None. // //-- ////////////////////////////////////////////////////////////////////////////// CClusCfgIPAddressInfo::~CClusCfgIPAddressInfo( void ) { TraceFunc( "" ); if ( m_pIWbemServices != NULL ) { m_pIWbemServices->Release(); } // if: if ( m_picccCallback != NULL ) { m_picccCallback->Release(); } // if: // There's going to be one less component in memory. Decrement component count. InterlockedDecrement( &g_cObjects ); TraceFuncExit(); } //*** CClusCfgIPAddressInfo::~CClusCfgIPAddressInfo //*************************************************************************// ///////////////////////////////////////////////////////////////////////////// // CClusCfgIPAddressInfo -- IUknkown interface. ///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// //++ // // CClusCfgIPAddressInfo::AddRef // // Description: // Increment the reference count of this object by one. // // Arguments: // None. // // Return Value: // The new reference count. // // Remarks: // None. // //-- ////////////////////////////////////////////////////////////////////////////// STDMETHODIMP_( ULONG ) CClusCfgIPAddressInfo::AddRef( void ) { TraceFunc( "[IUnknown]" ); InterlockedIncrement( & m_cRef ); CRETURN( m_cRef ); } //*** CClusCfgIPAddressInfo::AddRef ////////////////////////////////////////////////////////////////////////////// //++ // // CClusCfgIPAddressInfo::Release // // Description: // Decrement the reference count of this object by one. // // Arguments: // None. // // Return Value: // The new reference count. // // Remarks: // None. // //-- ////////////////////////////////////////////////////////////////////////////// STDMETHODIMP_( ULONG ) CClusCfgIPAddressInfo::Release( void ) { TraceFunc( "[IUnknown]" ); LONG cRef; cRef = InterlockedDecrement( &m_cRef ); if ( cRef == 0 ) { TraceDo( delete this ); } // if: reference count equal to zero CRETURN( cRef ); } //*** CClusCfgIPAddressInfo::Release ////////////////////////////////////////////////////////////////////////////// //++ // // CClusCfgIPAddressInfo::QueryInterface // // Description: // Query this object for the passed in interface. // // Arguments: // riidIn // Id of interface requested. // // ppvOut // Pointer to the requested interface. // // Return Value: // S_OK // If the interface is available on this object. // // E_NOINTERFACE // If the interface is not available. // // E_POINTER // ppvOut was NULL. // // Remarks: // None. // //-- ////////////////////////////////////////////////////////////////////////////// STDMETHODIMP CClusCfgIPAddressInfo::QueryInterface( REFIID riidIn , void ** ppvOut ) { TraceQIFunc( riidIn, ppvOut ); HRESULT hr = S_OK; // // Validate arguments. // Assert( ppvOut != NULL ); if ( ppvOut == NULL ) { hr = THR( E_POINTER ); goto Cleanup; } // // Handle known interfaces. // if ( IsEqualIID( riidIn, IID_IUnknown ) ) { *ppvOut = static_cast< IClusCfgIPAddressInfo * >( this ); } // if: IUnknown else if ( IsEqualIID( riidIn, IID_IClusCfgIPAddressInfo ) ) { *ppvOut = TraceInterface( __THISCLASS__, IClusCfgIPAddressInfo, this, 0 ); } // else if: IClusCfgIPAddressInfo else if ( IsEqualIID( riidIn, IID_IClusCfgWbemServices ) ) { *ppvOut = TraceInterface( __THISCLASS__, IClusCfgWbemServices, this, 0 ); } // else if: IClusCfgWbemServices else if ( IsEqualIID( riidIn, IID_IClusCfgInitialize ) ) { *ppvOut = TraceInterface( __THISCLASS__, IClusCfgInitialize, this, 0 ); } // else if: IClusCfgInitialize else { *ppvOut = NULL; hr = E_NOINTERFACE; } // // Add a reference to the interface if successful. // if ( SUCCEEDED( hr ) ) { ((IUnknown *) *ppvOut)->AddRef(); } // if: success Cleanup: QIRETURN_IGNORESTDMARSHALLING( hr, riidIn ); } //*** CClusCfgIPAddressInfo::QueryInterface //*************************************************************************// ///////////////////////////////////////////////////////////////////////////// // CClusCfgIPAddressInfo -- IClusCfgInitialize interface. ///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// //++ // // CClusCfgIPAddressInfo::Initialize // // Description: // Initialize this component. // // Arguments: // IN IUknown * punkCallbackIn // // IN LCID lcidIn // // Return Value: // S_OK // Success // // Remarks: // None. // //-- ////////////////////////////////////////////////////////////////////////////// STDMETHODIMP CClusCfgIPAddressInfo::Initialize( IUnknown * punkCallbackIn, LCID lcidIn ) { TraceFunc( "[IClusCfgInitialize]" ); Assert( m_picccCallback == NULL ); HRESULT hr = S_OK; m_lcid = lcidIn; if ( punkCallbackIn == NULL ) { hr = THR( E_POINTER ); goto Cleanup; } // if: hr = THR( punkCallbackIn->TypeSafeQI( IClusCfgCallback, &m_picccCallback ) ); Cleanup: HRETURN( hr ); } //*** CClusCfgIPAddressInfo::Initialize //*************************************************************************// ///////////////////////////////////////////////////////////////////////////// // CClusCfgIPAddressInfo -- IClusCfgWbemServices interface. ///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// //++ // // CClusCfgIPAddressInfo::SetWbemServices // // Description: // Set the WBEM services provider. // // Arguments: // IN IWbemServices pIWbemServicesIn // // Return Value: // S_OK // Success // // E_POINTER // The pIWbemServicesIn param is NULL. // // Remarks: // None. // //-- ////////////////////////////////////////////////////////////////////////////// STDMETHODIMP CClusCfgIPAddressInfo::SetWbemServices( IWbemServices * pIWbemServicesIn ) { TraceFunc( "[IClusCfgWbemServices]" ); HRESULT hr = S_OK; if ( pIWbemServicesIn == NULL ) { hr = THR( E_POINTER ); STATUS_REPORT_REF( TASKID_Major_Find_Devices, TASKID_Minor_SetWbemServices_IPAddress, IDS_ERROR_NULL_POINTER, IDS_ERROR_NULL_POINTER_REF, hr ); goto Cleanup; } // if: m_pIWbemServices = pIWbemServicesIn; m_pIWbemServices->AddRef(); Cleanup: HRETURN( hr ); } //*** CClusCfgIPAddressInfo::SetWbemServices //*************************************************************************// ///////////////////////////////////////////////////////////////////////////// // CClusCfgIPAddressInfo class -- IClusCfgIPAddressInfo interface ///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// //++ // // CClusCfgIPAddressInfo::GetUID // // Description: // // Arguments: // None. // // Return Value: // // // Remarks: // None. // //-- ////////////////////////////////////////////////////////////////////////////// STDMETHODIMP CClusCfgIPAddressInfo::GetUID( BSTR * pbstrUIDOut ) { TraceFunc( "[IClusCfgIPAddressInfo]" ); Assert( m_ulIPAddress != 0 ); Assert( m_ulIPSubnet != 0 ); HRESULT hr = S_OK; ULONG ulNetwork = ( m_ulIPAddress & m_ulIPSubnet ); LPWSTR psz = NULL; DWORD sc; if ( pbstrUIDOut == NULL ) { hr = THR( E_POINTER ); STATUS_REPORT_REF( TASKID_Major_Find_Devices, TASKID_Minor_IPAddressInfo_GetUID_Pointer, IDS_ERROR_NULL_POINTER, IDS_ERROR_NULL_POINTER_REF, hr ); goto Cleanup; } // if: sc = ClRtlTcpipAddressToString( ulNetwork, &psz ); // KB: Allocates to psz using LocalAlloc(). if ( sc != ERROR_SUCCESS ) { hr = THR( HRESULT_FROM_WIN32( sc ) ); LOG_STATUS_REPORT( L"CClusCfgIPAddressInfo::GetUID() ClRtlTcpipAddressToString() failed.", hr ); goto Cleanup; } // if: *pbstrUIDOut = SysAllocString( psz ); if ( *pbstrUIDOut == NULL ) { hr = THR( E_OUTOFMEMORY ); STATUS_REPORT_REF( TASKID_Major_Find_Devices, TASKID_Minor_IPAddressInfo_GetUID_Memory, IDS_ERROR_OUTOFMEMORY, IDS_ERROR_OUTOFMEMORY_REF, hr ); goto Cleanup; } // if: Cleanup: if ( psz != NULL ) { LocalFree( psz ); // KB: Don't use TraceFree() here! } // if: HRETURN( hr ); } //*** CClusCfgIPAddressInfo::GetUID ////////////////////////////////////////////////////////////////////////////// //++ // // CClusCfgIPAddressInfo::GetIPAddress // // Description: // // Arguments: // None. // // Return Value: // // // Remarks: // None. // //-- ////////////////////////////////////////////////////////////////////////////// STDMETHODIMP CClusCfgIPAddressInfo::GetIPAddress( ULONG * pulDottedQuadOut ) { TraceFunc( "[IClusCfgIPAddressInfo]" ); HRESULT hr = S_OK; if ( pulDottedQuadOut == NULL ) { hr = THR( E_POINTER ); STATUS_REPORT_REF( TASKID_Major_Find_Devices, TASKID_Minor_GetNetworkGetIPAddress, IDS_ERROR_NULL_POINTER, IDS_ERROR_NULL_POINTER_REF, hr ); goto Cleanup; } // if: *pulDottedQuadOut = m_ulIPAddress; Cleanup: HRETURN( hr ); } //*** CClusCfgIPAddressInfo::GetIPAddress ////////////////////////////////////////////////////////////////////////////// //++ // // CClusCfgIPAddressInfo::SetIPAddress // // Description: // // Arguments: // None. // // Return Value: // // // Remarks: // None. // //-- ////////////////////////////////////////////////////////////////////////////// STDMETHODIMP CClusCfgIPAddressInfo::SetIPAddress( ULONG ulDottedQuadIn ) { TraceFunc( "[IClusCfgIPAddressInfo]" ); HRESULT hr = S_OK; if ( ulDottedQuadIn == 0 ) { hr = THR( E_INVALIDARG ); goto Cleanup; } // if: m_ulIPAddress = ulDottedQuadIn; Cleanup: HRETURN( hr ); } //*** CClusCfgIPAddressInfo::SetIPAddress ////////////////////////////////////////////////////////////////////////////// //++ // // CClusCfgIPAddressInfo::GetSubnetMask // // Description: // // Arguments: // None. // // Return Value: // // // Remarks: // None. // //-- ////////////////////////////////////////////////////////////////////////////// STDMETHODIMP CClusCfgIPAddressInfo::GetSubnetMask( ULONG * pulDottedQuadOut ) { TraceFunc( "[IClusCfgIPAddressInfo]" ); HRESULT hr = S_OK; if ( pulDottedQuadOut == NULL ) { hr = THR( E_POINTER ); STATUS_REPORT_REF( TASKID_Major_Find_Devices, TASKID_Minor_GetSubnetMask, IDS_ERROR_NULL_POINTER, IDS_ERROR_NULL_POINTER_REF, hr ); goto Cleanup; } // if: *pulDottedQuadOut = m_ulIPSubnet; Cleanup: HRETURN( hr ); } //*** CClusCfgIPAddressInfo::GetSubnetMask ////////////////////////////////////////////////////////////////////////////// //++ // // CClusCfgIPAddressInfo::SetSubnetMask // // Description: // // Arguments: // None. // // Return Value: // // // Remarks: // None. // //-- ////////////////////////////////////////////////////////////////////////////// STDMETHODIMP CClusCfgIPAddressInfo::SetSubnetMask( ULONG ulDottedQuadIn ) { TraceFunc( "[IClusCfgIPAddressInfo]" ); HRESULT hr = S_OK; if ( ulDottedQuadIn == 0 ) { hr = THR( E_INVALIDARG ); goto Cleanup; } // if: m_ulIPSubnet = ulDottedQuadIn; Cleanup: HRETURN( hr ); } //*** CClusCfgIPAddressInfo::SetSubnetMask //*************************************************************************// ///////////////////////////////////////////////////////////////////////////// // CClusCfgIPAddressInfo class -- Private Methods. ///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// //++ // // CClusCfgIPAddressInfo::HrInit // // Description: // Initialize this component. // // Arguments: // None. // // Return Value: // // // Remarks: // None. // //-- ////////////////////////////////////////////////////////////////////////////// HRESULT CClusCfgIPAddressInfo::HrInit( void ) { TraceFunc( "" ); HRESULT hr = S_OK; // IUnknown Assert( m_cRef == 1 ); HRETURN( hr ); } //*** CClusCfgIPAddressInfo::HrInit ////////////////////////////////////////////////////////////////////////////// //++ // // CClusCfgIPAddressInfo::HrInit // // Description: // Initialize this component. // // Arguments: // ulIPAddressIn // ulIPSubnetIn // // Return Value: // // // Remarks: // None. // //-- ////////////////////////////////////////////////////////////////////////////// HRESULT CClusCfgIPAddressInfo::HrInit( ULONG ulIPAddressIn, ULONG ulIPSubnetIn ) { TraceFunc( "" ); HRESULT hr = S_OK; // IUnknown Assert( m_cRef == 1 ); m_ulIPAddress = ulIPAddressIn; m_ulIPSubnet = ulIPSubnetIn; HRETURN( hr ); } //*** CClusCfgIPAddressInfo::HrInit( ulIPAddressIn, ulIPSubnetIn ) #include #include #include #include using namespace cv; using namespace std; Mat input_image, input_image_gray; Mat output_image; const char *window_name = "Triangulate Tool (c) "; vector point_set; int opacity = 75; Subdiv2D subdiv; void run_filter(int, void*) { output_image = input_image.clone(); vector triangle_list; subdiv.getTriangleList(triangle_list); for ( int i = 0 ; i < triangle_list.size() ; i++ ) { Vec6f &t = triangle_list[i]; Point pt[3]; pt[0] = Point(cvRound(t[0]), cvRound(t[1])); pt[1] = Point(cvRound(t[2]), cvRound(t[3])); pt[2] = Point(cvRound(t[4]), cvRound(t[5])); const Point* pts[1] = {pt}; int npts[1] = {3}; Mat mask(input_image.size(), CV_8UC1); mask = Scalar::all(0); fillPoly(mask, pts, npts, 1, Scalar(255)); Scalar colour = mean(input_image, mask); fillPoly(output_image, pts, npts, 1, colour); } Mat display_image; addWeighted(input_image, (100-opacity)/100.0, output_image, opacity/100.0, 0, display_image); imshow(window_name, display_image); } void show_help(const char *progname) { cerr <<"Usage: " << progname << " input_image output_image" << endl; } void on_mouse(int event, int x, int y, int, void*) { if( event != EVENT_LBUTTONDOWN ) return; point_set.push_back(Point(x, y)); subdiv.insert(Point(x, y)); run_filter(0, 0); } int main( int argc, char** argv ) { if( argc < 3 ) { show_help(argv[0]); return -1; } input_image = imread(argv[1], CV_LOAD_IMAGE_COLOR); if ( ! input_image.data ) { show_help(argv[0]); cerr << "ERROR: Could not open or find the image " << argv[1] << endl; return -1; } cvtColor(input_image, input_image_gray, CV_BGR2GRAY); subdiv.initDelaunay(Rect(0, 0, input_image.cols, input_image.rows)); namedWindow(window_name, CV_WINDOW_AUTOSIZE); createTrackbar("Opacity of triangles: ", window_name, &opacity, 100, run_filter); setMouseCallback(window_name, on_mouse); output_image = input_image.clone(); imshow(window_name, output_image); run_filter(0, NULL); bool saved_once_atleast = false; while (true) { char input = waitKey(0); if ( input == 's' ) { imwrite(argv[2],output_image); saved_once_atleast = true; } else if ( input == 'q' ) { break; } } if ( ! saved_once_atleast ) { imwrite(argv[2],output_image); } return 0; } Modules/RigidRegistrationUI/RigidRegistrationOptimizer/QmitkVersorRigid3DTransformOptimizerView.cpp /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "QmitkVersorRigid3DTransformOptimizerView.h" #include "mitkImageAccessByItk.h" #include QmitkVersorRigid3DTransformOptimizerView::QmitkVersorRigid3DTransformOptimizerView(QWidget* parent, Qt::WindowFlags f ) : QmitkRigidRegistrationOptimizerGUIBase (parent, f), m_NumberTransformParameters(16) { } QmitkVersorRigid3DTransformOptimizerView::~QmitkVersorRigid3DTransformOptimizerView() { } mitk::OptimizerParameters::OptimizerType QmitkVersorRigid3DTransformOptimizerView::GetOptimizerType() { return mitk::OptimizerParameters::VERSORRIGID3DTRANSFORMOPTIMIZER; } itk::Object::Pointer QmitkVersorRigid3DTransformOptimizerView::GetOptimizer() { itk::VersorRigid3DTransformOptimizer::Pointer OptimizerPointer = itk::VersorRigid3DTransformOptimizer::New(); OptimizerPointer->SetMaximize( m_Controls.m_Maximize->isChecked() ); OptimizerPointer->SetGradientMagnitudeTolerance( m_Controls.m_GradientMagnitudeToleranceVersorRigid3DTransform->text().toFloat() ); OptimizerPointer->SetMinimumStepLength( m_Controls.m_MinimumStepLengthVersorRigid3DTransform->text().toFloat() ); OptimizerPointer->SetMaximumStepLength( m_Controls.m_MaximumStepLengthVersorRigid3DTransform->text().toFloat() ); OptimizerPointer->SetNumberOfIterations( m_Controls.m_IterationsVersorRigid3DTransform->text().toInt() ); return OptimizerPointer.GetPointer(); } itk::Array QmitkVersorRigid3DTransformOptimizerView::GetOptimizerParameters() { itk::Array optimizerValues; optimizerValues.SetSize(5); optimizerValues.fill(0); optimizerValues[0] = m_Controls.m_Maximize->isChecked(); optimizerValues[1] = m_Controls.m_GradientMagnitudeToleranceVersorRigid3DTransform->text().toFloat(); optimizerValues[2] = m_Controls.m_MinimumStepLengthVersorRigid3DTransform->text().toFloat(); optimizerValues[3] = m_Controls.m_MaximumStepLengthVersorRigid3DTransform->text().toFloat(); optimizerValues[4] = m_Controls.m_IterationsVersorRigid3DTransform->text().toInt(); return optimizerValues; } void QmitkVersorRigid3DTransformOptimizerView::SetOptimizerParameters(itk::Array optimizerValues) { m_Controls.m_Maximize->setChecked(optimizerValues[0]); m_Controls.m_GradientMagnitudeToleranceVersorRigid3DTransform->setText(QString::number(optimizerValues[1])); m_Controls.m_MinimumStepLengthVersorRigid3DTransform->setText(QString::number(optimizerValues[2])); m_Controls.m_MaximumStepLengthVersorRigid3DTransform->setText(QString::number(optimizerValues[3])); m_Controls.m_IterationsVersorRigid3DTransform->setText(QString::number(optimizerValues[4])); } void QmitkVersorRigid3DTransformOptimizerView::SetNumberOfTransformParameters(int transformParameters) { m_NumberTransformParameters = transformParameters; } QString QmitkVersorRigid3DTransformOptimizerView::GetName() { return "VersorRigid3DTransform"; } void QmitkVersorRigid3DTransformOptimizerView::SetupUI(QWidget* parent) { m_Controls.setupUi(parent); QValidator* validatorLineEditInput = new QIntValidator(0, 20000000, this); m_Controls.m_IterationsVersorRigid3DTransform->setValidator(validatorLineEditInput); QValidator* validatorLineEditInputFloat = new QDoubleValidator(0, 20000000, 8, this); m_Controls.m_GradientMagnitudeToleranceVersorRigid3DTransform->setValidator(validatorLineEditInputFloat); m_Controls.m_MinimumStepLengthVersorRigid3DTransform->setValidator(validatorLineEditInputFloat); m_Controls.m_MaximumStepLengthVersorRigid3DTransform->setValidator(validatorLineEditInputFloat); } SuiMachine/khg-d3d10drv /*============================================================================= Launch.cpp: Game launcher. Copyright 1997-1999 Epic Games, Inc. All Rights Reserved. Revision history: * Created by . =============================================================================*/ #include "LaunchPrivate.h" #include "UnEngineWin.h" /*----------------------------------------------------------------------------- Global variables. -----------------------------------------------------------------------------*/ // General. extern "C" {HINSTANCE hInstance;} extern "C" {TCHAR GPackage[64]=TEXT("Launch");} // Log file. #include "FOutputDeviceFile.h" FOutputDeviceFile Log; // Error handler. #include "FOutputDeviceWindowsError.h" FOutputDeviceWindowsError Error; // Feedback. //#include "FFeedbackContextWindows.h" //FFeedbackContextWindows Warn; #if 0 // File manager. #include "FFileManagerWindows.h" FFileManagerWindows FileManager; #endif // Config. #include "FConfigCacheIni.h" /*----------------------------------------------------------------------------- WinMain. -----------------------------------------------------------------------------*/ // // Main entry point. // This is an example of how to initialize and launch the engine. // INT WINAPI WinMain( HINSTANCE hInInstance, HINSTANCE hPrevInstance, char*, INT nCmdShow ) { // Remember instance. INT ErrorLevel = 0; GIsStarted = 1; hInstance = hInInstance; const TCHAR* CmdLine = GetCommandLine(); appStrcpy( GPackage, appPackage() ); // See if this should be passed to another instances. if( !appStrfind(CmdLine,TEXT("Server")) && !appStrfind(CmdLine,TEXT("NewWindow")) && !appStrfind(CmdLine,TEXT("changevideo")) && !appStrfind(CmdLine,TEXT("TestRenDev")) ) { TCHAR ClassName[256]; MakeWindowClassName(ClassName,TEXT("WLog")); for( HWND hWnd=NULL; ; ) { hWnd = TCHAR_CALL_OS(FindWindowExW(hWnd,NULL,ClassName,NULL),FindWindowExA(hWnd,NULL,TCHAR_TO_ANSI(ClassName),NULL)); if( !hWnd ) break; if( GetPropX(hWnd,TEXT("IsBrowser")) ) { while( *CmdLine && *CmdLine!=' ' ) CmdLine++; if( *CmdLine==' ' ) CmdLine++; COPYDATASTRUCT CD; DWORD Result; CD.dwData = WindowMessageOpen; CD.cbData = (appStrlen(CmdLine)+1)*sizeof(TCHAR*); CD.lpData = const_cast( CmdLine ); SendMessageTimeout( hWnd, WM_COPYDATA, (WPARAM)NULL, (LPARAM)&CD, SMTO_ABORTIFHUNG|SMTO_BLOCK, 30000, &Result ); GIsStarted = 0; return 0; } } } // Begin guarded code. #ifndef _DEBUG try { #endif // Init core. GIsClient = GIsGuarded = 1; //appInit( GPackage, CmdLine, &Malloc, &Log, &Error, &Warn, &FileManager, FConfigCacheIni::Factory, 1 ); appInit(); //if( ParseParam(appCmdLine(),TEXT("MAKE")) )//oldver //appErrorf( TEXT("'Unreal -make' is obsolete, use 'ucc make' now") ); // Init mode. GIsServer = 1; GIsClient = !ParseParam(appCmdLine(),TEXT("SERVER")) && !ParseParam(appCmdLine(),TEXT("MAKE")); GIsEditor = ParseParam(appCmdLine(),TEXT("EDITOR")) || ParseParam(appCmdLine(),TEXT("MAKE")); GLazyLoad = GIsEditor || !GIsClient || ParseParam(appCmdLine(),TEXT("LAZY")); // Figure out whether to show log or splash screen. UBOOL ShowLog = ParseParam(CmdLine,TEXT("LOG")); // Note: Splash Screen is loaded out of Resource file in Khg 1.1 FString Filename = FString( TEXT("..\\Help\\") ) + GPackage + TEXT("Logo.bmp"); if( appFSize(*Filename)<0 ) Filename = TEXT("..\\Help\\Logo.bmp"); appStrcpy( GPackage, appPackage() ); //InitSplash( hInstance, !ShowLog && !ParseParam(CmdLine,TEXT("server")), *Filename ); if ( !ShowLog && !ParseParam(CmdLine,TEXT("server")) && !appStrfind(CmdLine,TEXT("TestRenDev")) ) InitSplash( *Filename ); // Init windowing. InitWindowing(); // Create log window, but only show it if ShowLog. if ( ShowLog ) { GLog = new WLog( TEXT("GameLog") ); GLog->OpenWindow( ShowLog, 0 ); GLog->Log( NAME_Title, LocalizeGeneral("Start") ); if( GIsClient ) SetPropX( *GLog, TEXT("IsBrowser"), (HANDLE)1 ); } else { GLog = NULL; } // Init engine. UEngine* Engine = InitEngine(); if ( Engine ) { if ( GLog ) GLog->Log( NAME_Title, LocalizeGeneral("Run") ); // Hide splash screen. ExitSplash(); // Optionally Exec an exec file TCHAR Temp[4096] = TEXT("exec "); //!! if( Parse(CmdLine, TEXT("EXEC="), Temp + appStrlen(Temp), 4096 ) ) { if( Engine->Client && Engine->Client->Viewports.Num() && Engine->Client->Viewports(0) ) Engine->Client->Viewports(0)->Exec( Temp, *GLog ); } // Start main engine loop, including the Windows message pump. if( !GIsRequestingExit ) MainLoop( Engine ); } // Delete is-running semaphore file. appUnlink( TEXT("Running.ini") ); // Clean shutdown. if ( GLog ) { RemovePropX( *GLog, TEXT("IsBrowser") ); GLog->Log( NAME_Title, LocalizeGeneral("Exit") ); delete GLog; } appPreExit(); GIsGuarded = 0; #ifndef _DEBUG } catch( ... ) { // Crashed. ErrorLevel = 1; appHandleError(); } #endif // Final shut down. appExit(); GIsStarted = 0; return ErrorLevel; } /*----------------------------------------------------------------------------- The End. -----------------------------------------------------------------------------*/ #include "ExpModule.h" #include "../stringFunctions.h" ExpModule::ExpModule(shared_ptr expChart): expChart(expChart), expGainMeter(levelUpChecker) { levelUpChecker.setExpChart(expChart); //expGainMeter.setObserver(valueGainObserver); /* DECLARE_MESSAGE_RULE(STR_GET_EXP_VITAL_MAKEUP_BONUS); DECLARE_MESSAGE_RULE(STR_GET_EXP_VITAL_BONUS); DECLARE_MESSAGE_RULE(STR_GET_EXP_MAKEUP_BONUS); */ DECLARE_MESSAGE_RULE(STR_GET_EXP); /* DECLARE_MESSAGE_RULE(STR_GET_EXP2_VITAL_MAKEUP_BONUS); DECLARE_MESSAGE_RULE(STR_GET_EXP2_VITAL_BONUS); DECLARE_MESSAGE_RULE(STR_GET_EXP2_MAKEUP_BONUS); */ DECLARE_MESSAGE_RULE(STR_GET_EXP2); /* DECLARE_MESSAGE_RULE(STR_MSG_F2P_GET_EXP_BOOST_VITAL_MAKEUP_BONUS); DECLARE_MESSAGE_RULE(STR_MSG_F2P_GET_EXP_BOOST_VITAL_BONUS); DECLARE_MESSAGE_RULE(STR_MSG_F2P_GET_EXP2_BOOST_VITAL_MAKEUP_BONUS); DECLARE_MESSAGE_RULE(STR_MSG_F2P_GET_EXP2_BOOST_VITAL_BONUS); DECLARE_MESSAGE_RULE(STR_GET_EXP_PCBANG_VITAL_MAKEUP_BONUS); DECLARE_MESSAGE_RULE(STR_GET_EXP_PCBANG_VITAL_BONUS); DECLARE_MESSAGE_RULE(STR_GET_EXP2_PCBANG_VITAL_MAKEUP_BONUS); DECLARE_MESSAGE_RULE(STR_GET_EXP2_PCBANG_VITAL_BONUS); */ DECLARE_MESSAGE_RULE(STR_CANNOT_GET_PVP_EXP_TARGET_LIMIT); DECLARE_MESSAGE_RULE(STR_CANNOT_GET_PVP_EXP_TIMEBASE_LIMIT); //DECLARE_MESSAGE_RULE(STR_MSG_ADDEXP_POINT_USE); DECLARE_MESSAGE_RULE(STR_MSG_EXP_EXTRACTION_USE); DECLARE_MESSAGE_RULE(STR_LEVEL_LIMIT_QUEST_NOT_FINISHED1); DECLARE_MESSAGE_RULE(STR_LEVEL_LIMIT_QUEST_NOT_FINISHED2); DECLARE_MESSAGE_RULE(STR_MSG_CANT_NOVICE_SERVER_ALREADY_MAX_LEVEL); DECLARE_MESSAGE_RULE(STR_SKILL_LEARNED_NEW_SKILL); DECLARE_MESSAGE_RULE(STR_MSG_GET_CP); //timer.start(); } void ExpModule::executeChatLogCommand(ChatLogCommand& command){ map& params = command.getParams(); switch(command.getMessageRuleCode()){ // EXP from a monster/player/NPC /* case STR_GET_EXP_VITAL_MAKEUP_BONUS: case STR_MSG_F2P_GET_EXP_BOOST_VITAL_MAKEUP_BONUS: expGainMeter.gain(stringToInt(params["%num1"])); expGainMeter.useRepose(stringToInt(params["%num2"])); expGainMeter.useSalvation(stringToInt(params["%num3"])); break; case STR_GET_EXP_VITAL_BONUS: case STR_MSG_F2P_GET_EXP_BOOST_VITAL_BONUS: expGainMeter.gain(stringToInt(params["%num1"])); expGainMeter.useRepose(stringToInt(params["%num2"])); break; case STR_GET_EXP_MAKEUP_BONUS: expGainMeter.gain(stringToInt(params["%num1"])); expGainMeter.useSalvation(stringToInt(params["%num2"])); break; */ case STR_GET_EXP: expGainMeter.gain(stringToInt(params["%num1"])); break; /* // EXP from no target (gathering/crafting) case STR_GET_EXP2_VITAL_MAKEUP_BONUS: case STR_MSG_F2P_GET_EXP2_BOOST_VITAL_MAKEUP_BONUS: expGainMeter.gain(stringToInt(params["%num0"])); expGainMeter.useRepose(stringToInt(params["%num1"])); expGainMeter.useSalvation(stringToInt(params["%num2"])); break; case STR_GET_EXP2_VITAL_BONUS: case STR_MSG_F2P_GET_EXP2_BOOST_VITAL_BONUS: expGainMeter.gain(stringToInt(params["%num0"])); expGainMeter.useRepose(stringToInt(params["%num1"])); break; case STR_GET_EXP2_MAKEUP_BONUS: expGainMeter.gain(stringToInt(params["%num0"])); expGainMeter.useSalvation(stringToInt(params["%num1"])); break; */ case STR_GET_EXP2: expGainMeter.gain(stringToInt(params["%num0"])); break; /* // PC Cafe - from a target case STR_GET_EXP_PCBANG_VITAL_MAKEUP_BONUS: expGainMeter.gain(stringToInt(params["%num1"])); expGainMeter.useRepose(stringToInt(params["%num2"])); expGainMeter.useSalvation(stringToInt(params["%num3"])); break; case STR_GET_EXP_PCBANG_VITAL_BONUS: expGainMeter.gain(stringToInt(params["%num1"])); expGainMeter.useRepose(stringToInt(params["%num2"])); break; // PC Cafe - gathering/crafting case STR_GET_EXP2_PCBANG_VITAL_BONUS: expGainMeter.gain(stringToInt(params["%num0"])); expGainMeter.useRepose(stringToInt(params["%num1"])); break; case STR_GET_EXP2_PCBANG_VITAL_MAKEUP_BONUS: expGainMeter.gain(stringToInt(params["%num0"])); expGainMeter.useRepose(stringToInt(params["%num1"])); expGainMeter.useSalvation(stringToInt(params["%num2"])); break; */ // PvP XP Cap case STR_CANNOT_GET_PVP_EXP_TARGET_LIMIT: case STR_CANNOT_GET_PVP_EXP_TIMEBASE_LIMIT: expGainMeter.gain(0); // Item Exp case STR_MSG_EXP_EXTRACTION_USE: expGainMeter.spend(stringToInt(params["%num1"])); break; // Level capped case STR_LEVEL_LIMIT_QUEST_NOT_FINISHED1: case STR_LEVEL_LIMIT_QUEST_NOT_FINISHED2: case STR_MSG_CANT_NOVICE_SERVER_ALREADY_MAX_LEVEL: levelUpChecker.prohibitLevelUp(); break; // Level up automatic skill learn /*case STR_SKILL_LEARNED_NEW_SKILL: levelUpChecker.levelUpLearnSkill(); break; */ case STR_MSG_GET_CP: levelUpChecker.gainEssence(); break; } } void ExpModule::endOfTickAction(){ expGainMeter.applyFromBuffer(); } double ExpModule::getWeightedLevelUpsPerHour(){ if (!levelUpChecker.isInitialized()) return 0; double hours = (double)timer.getElapsedTime() / 3600; double levelsGainedWeight = 1; if (hours >= 1) return timer.calculatePerHourRate(levelUpChecker.getNumLevelsGained()); levelsGainedWeight = hours; double expPerHour = timer.calculatePerHourRate(expGainMeter.getNetGained()); double projectedDecimalLevelAfterOneHour = levelUpChecker.getProjectedDecimalLevel(expPerHour); /* double weightedLevelsGainedPerHour = timer.calculatePerHourRate( levelUpChecker.getNumLevelsGained() * levelsGainedWeight); */ double weightedLevelUpProjectionPerHour = (projectedDecimalLevelAfterOneHour - levelUpChecker.getCurrentDecimalLevel()) * (1 - levelsGainedWeight); return levelUpChecker.getNumLevelsGained() + weightedLevelUpProjectionPerHour; } viewdy/phantomjs /* Copyright (C) 2009-2010 ProFUSION embedded systems Copyright (C) 2009-2011 Samsung Electronics This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "config.h" #include "ewk_main.h" #include "FileSystem.h" #include "InitializeLogging.h" #include "PageCache.h" #include "PageGroup.h" #include "PlatformStrategiesEfl.h" #include "ResourceHandle.h" #include "ScriptController.h" #include "Settings.h" #include "StorageTracker.h" #include "StorageTrackerClientEfl.h" #include "ewk_auth_soup_private.h" #include "ewk_network.h" #include "ewk_private.h" #include "ewk_settings.h" #include "ewk_settings_private.h" #include "runtime/InitializeThreading.h" #include "runtime/Operations.h" #include #include #include #include #include #include #include #include #include #include #include #include #ifdef HAVE_ECORE_X #include #endif static int _ewkInitCount = 0; /** * \var _ewk_log_dom * @brief the log domain identifier that is used with EINA's macros */ int _ewk_log_dom = -1; static Eina_Bool _ewk_init_body(void); int ewk_init(void) { if (_ewkInitCount) return ++_ewkInitCount; if (!eina_init()) goto error_eina; _ewk_log_dom = eina_log_domain_register("ewebkit", EINA_COLOR_ORANGE); if (_ewk_log_dom < 0) { EINA_LOG_CRIT("could not register log domain 'ewebkit'"); goto error_log_domain; } if (!evas_init()) { CRITICAL("could not init evas."); goto error_evas; } if (!ecore_init()) { CRITICAL("could not init ecore."); goto error_ecore; } if (!ecore_evas_init()) { CRITICAL("could not init ecore_evas."); goto error_ecore_evas; } if (!edje_init()) { CRITICAL("could not init edje."); goto error_edje; } #ifdef HAVE_ECORE_X if (!ecore_x_init(0)) { CRITICAL("could not init ecore_x."); goto error_ecore_x; } #endif if (!_ewk_init_body()) { CRITICAL("could not init body"); goto error_edje; } return ++_ewkInitCount; #ifdef HAVE_ECORE_X error_ecore_x: edje_shutdown(); #endif error_edje: ecore_evas_shutdown(); error_ecore_evas: ecore_shutdown(); error_ecore: evas_shutdown(); error_evas: eina_log_domain_unregister(_ewk_log_dom); _ewk_log_dom = -1; error_log_domain: eina_shutdown(); error_eina: return 0; } int ewk_shutdown(void) { _ewkInitCount--; if (_ewkInitCount) return _ewkInitCount; #ifdef HAVE_ECORE_X ecore_x_shutdown(); #endif edje_shutdown(); ecore_evas_shutdown(); ecore_shutdown(); evas_shutdown(); eina_log_domain_unregister(_ewk_log_dom); _ewk_log_dom = -1; eina_shutdown(); return 0; } static WebCore::StorageTrackerClientEfl* trackerClient() { DEFINE_STATIC_LOCAL(WebCore::StorageTrackerClientEfl, trackerClient, ()); return &trackerClient; } Eina_Bool _ewk_init_body(void) { #if !GLIB_CHECK_VERSION(2, 35, 0) g_type_init(); #endif if (!ecore_main_loop_glib_integrate()) WARN("Ecore was not compiled with GLib support, some plugins will not " "work (ie: Adobe Flash)"); WebCore::ScriptController::initializeThreading(); #if !LOG_DISABLED WebCore::initializeLoggingChannelsIfNecessary(); #endif // !LOG_DISABLED WebCore::Settings::setDefaultMinDOMTimerInterval(0.004); PlatformStrategiesEfl::initialize(); // Page cache capacity (in pages). Comment from Mac port: // (Research indicates that value / page drops substantially after 3 pages.) // FIXME: Calculate based on available resources ewk_settings_page_cache_capacity_set(3); WebCore::PageGroup::setShouldTrackVisitedLinks(true); String localStorageDirectory = String::fromUTF8(efreet_data_home_get()) + "/WebKitEfl/LocalStorage"; String webDatabaseDirectory = String::fromUTF8(efreet_cache_home_get()) + "/WebKitEfl/Databases"; String applicationCacheDirectory = String::fromUTF8(efreet_cache_home_get()) + "/WebKitEfl/Applications"; String fileSystemDirectory = String::fromUTF8(efreet_data_home_get()) + "/WebKitEfl/FileSystem"; ewk_settings_local_storage_path_set(localStorageDirectory.utf8().data()); ewk_settings_web_database_path_set(webDatabaseDirectory.utf8().data()); ewk_settings_application_cache_path_set(applicationCacheDirectory.utf8().data()); ewk_settings_file_system_path_set(fileSystemDirectory.utf8().data()); ewk_network_tls_certificate_check_set(false); WebCore::StorageTracker::initializeTracker(localStorageDirectory.utf8().data(), trackerClient()); SoupSession* session = WebCore::ResourceHandle::defaultSession(); SoupSessionFeature* auth_dialog = static_cast(g_object_new(EWK_TYPE_SOUP_AUTH_DIALOG, 0)); soup_session_add_feature(session, auth_dialog); WebCore::ResourceHandle::setIgnoreSSLErrors(true); return true; } src/Engine/DebugGraphic.hpp #pragma once #include #include #include /// \brief Fast Debug Line class DebugGraphic : public ALifeTimeObject { friend class ADebugObject; public: DebugGraphic(); ~DebugGraphic() override; void render() override; void addDebugObject(ADebugObject &debugObject); void removeDebugObject(ADebugObject &debugObject); private: unsigned int VAO; unsigned int VBO; unsigned int const debugVertexBufferMarge_ = 1000; unsigned int debugVertexBufferActualSize_; unsigned int totalLine_; DebugVertex *debugBuffer_; std::vector< ADebugObject * > bufferObject_; void updateInfo_(); void updateDebugObject_(ADebugObject &object); void updateDebugBuffer_(); void buildBuffers_(unsigned int newSize); static bool debug_; };mikelange49/pedalevitesrc/fstb/txt/unicode/PredLt.hpp /***************************************************************************** PredLt.hpp Author: , 2008 --- Legal stuff --- This program is free software. It comes without any warranty, to the extent permitted by applicable law. You can redistribute it and/or modify it under the terms of the Do What The Fuck You Want To Public License, Version 2, as published by Sam Hocevar. See http://sam.zoy.org/wtfpl/COPYING for more details. *Tab=3***********************************************************************/ #if defined (fstb_txt_unicode_PredLt_CURRENT_CODEHEADER) #error Recursive inclusion of PredLt code header. #endif #define fstb_txt_unicode_PredLt_CURRENT_CODEHEADER #if ! defined (fstb_txt_unicode_PredLt_CODEHEADER_INCLUDED) #define fstb_txt_unicode_PredLt_CODEHEADER_INCLUDED /*\\\ INCLUDE FILES \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ namespace fstb { namespace txt { namespace unicode { /*\\\ PUBLIC \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ template bool PredLt ::operator () (char32_t lhs, char32_t rhs) const { lhs = C::convert (lhs); rhs = C::convert (rhs); return (lhs < rhs); } /*\\\ PROTECTED \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ /*\\\ PRIVATE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ } // namespace unicode } // namespace txt } // namespace fstb #endif // fstb_txt_unicode_PredLt_CODEHEADER_INCLUDED #undef fstb_txt_unicode_PredLt_CURRENT_CODEHEADER /*\\\ EOF \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ mclow/bde // ball_fileobserver2.t.cpp -*-C++-*- #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 #include #include #include #include #include #include #include #include #include #ifdef BSLS_PLATFORM_OS_UNIX #include #include #include //unsetenv #include #include #include #endif #ifdef BSLS_PLATFORM_OS_WINDOWS #include #endif // Note: on Windows -> WinGDI.h:#define ERROR 0 #if defined(BSLS_PLATFORM_CMP_MSVC) && defined(ERROR) #undef ERROR #endif using namespace BloombergLP; using bsl::cout; using bsl::cerr; using bsl::endl; using bsl::flush; // ============================================================================ // TEST PLAN // ---------------------------------------------------------------------------- // Overview // -------- // The component under test defines an observer ('ball::FileObserver2') that // writes log records to a file. // ---------------------------------------------------------------------------- // CREATORS // [ 1] FileObserver2(bslma::Allocator *); // [ 1] ~FileObserver2(); // // MANIPULATORS // [ 1] void disableFileLogging(); // [ 2] void disableLifetimeRotation(); // [ 1] void disablePublishInLocalTime(); // [ 2] void disableSizeRotation(); // [ 8] void disableTimeIntervalRotation(); // [ 1] int enableFileLogging(const char *fileName); // [ 1] int enableFileLogging(const char *fileName, bool timestampFlag); // [ 1] void enablePublishInLocalTime(); // [ 1] void publish(const Record& record, const Context& context); // [ 1] void publish(const shared_ptr&, const Context&); // [ 2] void forceRotation(); // [ 2] void rotateOnSize(int size); // [ 2] void rotateOnLifetime(DatetimeInterval& interval); // [ 8] void rotateOnTimeInterval(const DatetimeInterval& interval); // [ 9] void rotateOnTimeInterval(const DtInterval& i, const Datetime& s); // [ 1] void setLogFileFunctor(const logRecordFunctor& logFileFunctor); // [ 5] void setOnFileRotationCallback(const OnFileRotationCallback&); // // ACCESSORS // [ 1] bool isFileLoggingEnabled() const; // [ 1] bool isFileLoggingEnabled(bsl::string *result) const; // [ 1] bool isPublishInLocalTimeEnabled() const; // [ 2] DatetimeInterval rotationLifetime() const; // [ 2] int rotationSize() const; // ---------------------------------------------------------------------------- // [13] USAGE EXAMPLE // [12] CONCERN: CURRENT LOCAL-TIME OFFSET IN TIMESTAMP // [11] CONCERN: TIME CALLBACKS ARE CALLED // [10] CONCERN: ROTATION CAN BE ENABLED AFTER FILE LOGGING // [ 7] CONCERN: ROTATION CALLBACK TRIGGERS CORRECTLY FOR EXISTING FILE // [ 6] CONCERN: ROTATION ON SIZE WORKS FOR EXISTING FILES // [ 4] CONCERN: ROTATED LOG FILENAMES ARE AS EXPECTED // [ 3] CONCERN: LOGGING TO A FAILING STREAM // ============================================================================ // STANDARD BDE ASSERT TEST FUNCTION // ---------------------------------------------------------------------------- namespace { int testStatus = 0; void aSsErT(bool condition, const char *message, int line) { if (condition) { cout << "Error " __FILE__ "(" << line << "): " << message << " (failed)" << endl; if (0 <= testStatus && testStatus <= 100) { ++testStatus; } } } } // close unnamed namespace namespace { void aSsErT2(bool condition, const char *message, int line) { if (condition) { cerr << "Error " __FILE__ "(" << line << "): " << message << " (failed)" << endl; if (0 <= testStatus && testStatus <= 100) { ++testStatus; } } } } // close unnamed namespace #define ASSERT2(X) { aSsErT2(!(X), #X, __LINE__); } // ============================================================================ // STANDARD BDE TEST DRIVER MACRO ABBREVIATIONS // ---------------------------------------------------------------------------- #define ASSERT BSLIM_TESTUTIL_ASSERT #define ASSERTV BSLIM_TESTUTIL_ASSERTV #define LOOP_ASSERT BSLIM_TESTUTIL_LOOP_ASSERT #define LOOP0_ASSERT BSLIM_TESTUTIL_LOOP0_ASSERT #define LOOP1_ASSERT BSLIM_TESTUTIL_LOOP1_ASSERT #define LOOP2_ASSERT BSLIM_TESTUTIL_LOOP2_ASSERT #define LOOP3_ASSERT BSLIM_TESTUTIL_LOOP3_ASSERT #define LOOP4_ASSERT BSLIM_TESTUTIL_LOOP4_ASSERT #define LOOP5_ASSERT BSLIM_TESTUTIL_LOOP5_ASSERT #define LOOP6_ASSERT BSLIM_TESTUTIL_LOOP6_ASSERT #define Q BSLIM_TESTUTIL_Q // Quote identifier literally. #define P BSLIM_TESTUTIL_P // Print identifier and value. #define P_ BSLIM_TESTUTIL_P_ // P(X) without '\n'. #define T_ BSLIM_TESTUTIL_T_ // Print a tab (w/o newline). #define L_ BSLIM_TESTUTIL_L_ // current Line number // ============================================================================ // GLOBAL TYPEDEFS/CONSTANTS FOR TESTING // ---------------------------------------------------------------------------- static bool verbose; static bool veryVerbose; static bool veryVeryVerbose; static bool veryVeryVeryVerbose; typedef ball::FileObserver2 Obj; typedef bdls::FilesystemUtil FsUtil; typedef bsls::Types::Int64 Int64; //============================================================================= // GLOBAL HELPER FUNCTIONS FOR TESTING //----------------------------------------------------------------------------- namespace { class TempDirectoryGuard { // This class implements a scoped temporary directory guard. The guard // tries to create a temporary directory in the system-wide temp directory // and falls back to the current directory. // DATA bsl::string d_dirName; // path to the created directory bslma::Allocator *d_allocator_p; // memory allocator (held, not owned) private: // NOT IMPLEMENTED TempDirectoryGuard(const TempDirectoryGuard&); TempDirectoryGuard& operator=(const TempDirectoryGuard&); public: // TRAITS BSLMF_NESTED_TRAIT_DECLARATION(TempDirectoryGuard, bslma::UsesBslmaAllocator); // CREATORS explicit TempDirectoryGuard(bslma::Allocator *basicAllocator = 0) // Create temporary directory in the system-wide temp or current // directory. Optionally specify a 'basicAllocator' used to supply // memory. If 'basicAllocator' is 0, the currently installed default // allocator is used. : d_dirName(bslma::Default::allocator(basicAllocator)) , d_allocator_p(bslma::Default::allocator(basicAllocator)) { bsl::string tmpPath(d_allocator_p); #ifdef BSLS_PLATFORM_OS_WINDOWS char tmpPathBuf[MAX_PATH]; GetTempPath(MAX_PATH, tmpPathBuf); tmpPath.assign(tmpPathBuf); #else const char *envTmpPath = bsl::getenv("TMPDIR"); if (envTmpPath) { tmpPath.assign(envTmpPath); } #endif int res = bdls::PathUtil::appendIfValid(&tmpPath, "ball_"); ASSERTV(tmpPath, 0 == res); res = bdls::FilesystemUtil::createTemporaryDirectory(&d_dirName, tmpPath); ASSERTV(tmpPath, 0 == res); } ~TempDirectoryGuard() // Destroy this object and remove the temporary directory (recursively) // created at construction. { bdls::FilesystemUtil::remove(d_dirName, true); } // ACCESSORS const bsl::string& getTempDirName() const // Return a 'const' reference to the name of the created temporary // directory. { return d_dirName; } }; void enableFileLogging( bsl::shared_ptr& observer, const bsl::string& fileName, const bool addTimestamp = false) // Enable file logging for the specified 'observer' to the specified // 'fileName'. Optionally specify 'addTimestamp' to append timestamp to // the filename. { ASSERT(false == observer->isFileLoggingEnabled()); if (!addTimestamp) { ASSERT(0 == observer->enableFileLogging(fileName.c_str())); ASSERT(true == observer->isFileLoggingEnabled()); ASSERT(1 == observer->enableFileLogging(fileName.c_str())); } else { ASSERT(0 == observer->enableFileLogging(fileName.c_str(), addTimestamp)); ASSERT(true == observer->isFileLoggingEnabled()); ASSERT(1 == observer->enableFileLogging(fileName.c_str(), addTimestamp)); } } bsl::string::size_type replaceSecondSpace(bsl::string *s, char value) // Replace the second space character (' ') in the specified string 's' // with the specified 'value'. Return the index position of the character // that was replaced on success, and 'bsl::string::npos' otherwise. { bsl::string::size_type index = s->find(' '); if (bsl::string::npos != index) { index = s->find(' ', index + 1); if (bsl::string::npos != index) { (*s)[index] = value; } } return index; } bdlt::Datetime getCurrentLocalTime() // Return current local time as a 'bdlt::Datetime' value. { time_t currentTime = time(0); struct tm localtm; #ifdef BSLS_PLATFORM_OS_WINDOWS localtm = *localtime(¤tTime); #else localtime_r(¤tTime, &localtm); #endif bdlt::Datetime stamp; bdlt::DatetimeUtil::convertFromTm(&stamp, localtm); return stamp; } void logRecord1(bsl::ostream& stream, const ball::Record& record) // Output the specified 'record' into the specified 'stream'. { ball::Severity::Level severityLevel = (ball::Severity::Level) record.fixedFields().severity(); stream << '\n'; const int k_SIZE = 64; char buffer[k_SIZE]; const int fractionalSecondPrecision = 3; const int numBytesWritten = record.fixedFields().timestamp().printToBuffer( buffer, k_SIZE, fractionalSecondPrecision); stream.write(buffer, numBytesWritten); stream << " "; stream << record.fixedFields().processID() << ":"; stream << record.fixedFields().threadID() << " "; stream << ball::Severity::toAscii(severityLevel) << " "; stream << record.fixedFields().fileName() << ":"; stream << record.fixedFields().lineNumber() << " "; stream << record.fixedFields().category() << " "; stream << record.fixedFields().message () << " "; const ball::UserFields& customFields = record.customFields(); for (int i = 0; i < customFields.length(); ++i) { stream << customFields[i] << "*"; } stream << '\n' << bsl::flush; } void logRecord2(bsl::ostream& stream, const ball::Record& record) // Output the specified 'record' into the specified 'stream'. { ball::Severity::Level severityLevel = (ball::Severity::Level) record.fixedFields().severity(); stream << '\n'; stream << record.fixedFields().message () << " "; stream << record.fixedFields().category() << " "; stream << record.fixedFields().fileName() << ":"; stream << ball::Severity::toAscii(severityLevel) << " "; stream << record.fixedFields().threadID() << " "; stream << record.fixedFields().processID() << ":"; const ball::UserFields& customFields = record.customFields(); for (int i = 0; i < customFields.length(); ++i) { stream << customFields[i] << "*"; } stream << '\n' << bsl::flush; } int readFileIntoString(int lineNum, const bsl::string& fileName, bsl::string& fileContent) // Read the content of the specified 'fileName' file into the specified // 'fileContent' string. Return the number of lines read from the file. { bsl::ifstream fs; #ifdef BSLS_PLATFORM_OS_UNIX glob_t globbuf; ASSERTV(lineNum, 0 == glob((fileName + "*").c_str(), 0, 0, &globbuf)); ASSERTV(lineNum, 1 == globbuf.gl_pathc); fs.open(globbuf.gl_pathv[0], bsl::ifstream::in); globfree(&globbuf); #else fs.open(fileName.c_str(), bsl::ifstream::in); #endif ASSERTV(lineNum, fs.is_open()); fileContent = ""; bsl::string lineContent; int lines = 0; while (getline(fs, lineContent)) { fileContent += lineContent; fileContent += '\n'; lines++; } fs.close(); return lines; } class LogRotationCallbackTester { // This class can be used as a functor matching the signature of // 'ball::FileObserver2::OnFileRotationCallback'. This class records every // invocation of the function-call operator, and is intended to test // whether 'ball::FileObserver2' calls the log-rotation callback // appropriately. // PRIVATE TYPES struct Rep { private: // NOT IMPLEMENTED Rep(const Rep&); Rep& operator=(const Rep&); public: // DATA int d_invocations; int d_status; bsl::string d_rotatedFileName; // TRAITS BSLMF_NESTED_TRAIT_DECLARATION(Rep, bslma::UsesBslmaAllocator); // CREATORS explicit Rep(bslma::Allocator *basicAllocator) // Create an object with default attribute values. Use the // specified 'basicAllocator' to supply memory. : d_invocations(0) , d_status(0) , d_rotatedFileName(basicAllocator) { } }; enum { k_UNINITIALIZED = INT_MIN }; // DATA bsl::shared_ptr d_rep; public: // CREATORS explicit LogRotationCallbackTester(bslma::Allocator *basicAllocator) // Create a callback tester object with default attribute values. Use // the specified 'basicAllocator' to supply memory. { d_rep.createInplace(basicAllocator, basicAllocator); reset(); } // MANIPULATORS void operator()(int status, const bsl::string& rotatedFileName) // Set the value at the status address supplied at construction to the // specified 'status', and set the value at the log file name address // supplied at construction to the specified 'rotatedFileName'. { ++d_rep->d_invocations; d_rep->d_status = status; d_rep->d_rotatedFileName = rotatedFileName; } void reset() // Reset the attributes of this object to their default values. { d_rep->d_invocations = 0; d_rep->d_status = k_UNINITIALIZED; d_rep->d_rotatedFileName.clear(); } // ACCESSORS int numInvocations() const { return d_rep->d_invocations; } // Return the number of times that the function-call operator has been // invoked since the most recent call to 'reset', or if 'reset' has // not been called, since this objects construction. int status() const { return d_rep->d_status; } // Return the status passed to the most recent invocation of the // function-call operation, or 'k_UNINITIALIZED' if 'numInvocations' is // 0. const bsl::string& rotatedFileName() const // Return a 'const' reference to the file name supplied to the most // recent invocation of the function-call operator, or the empty string // if 'numInvocations' is 0. { return d_rep->d_rotatedFileName; } }; typedef LogRotationCallbackTester RotCb; class ReentrantRotationCallback { // This class can be used as a functor matching the signature of // 'ball::FileObserver2::OnFileRotationCallback'. This class implements // the function-call operator, that will call 'disableFileLogging' on the // file observer supplied at construction. Note that this type is intended // to test whether the rotation callback is called in a way that allows the // supplied file observer to be modified on the callback. Obj *d_observer_p; public: explicit ReentrantRotationCallback(Obj *observer) // Create a rotation callback for the specified 'observer'. : d_observer_p(observer) { } void operator()(int, const bsl::string&); // Disables file logging for the observer supplied at construction. }; void ReentrantRotationCallback::operator()(int, const bsl::string& ) { d_observer_p->disableFileLogging(); } void publishRecord(Obj *observer, const char *message) // Publish the specified 'message' to the specified 'observer' object. { ball::RecordAttributes attr(bdlt::CurrentTime::utc(), 1, 2, "FILENAME", 3, "CATEGORY", 32, message); ball::Record record(attr, ball::UserFields()); ball::Context context(ball::Transmission::e_PASSTHROUGH, 0, 1); observer->publish(record, context); } int getNumLines(const char *fileName) // Return the number of lines in the file with the specified 'fileName'. { bsl::ifstream fs; fs.open(fileName, bsl::ifstream::in); fs.clear(); ASSERT(fs.is_open()); int numLines = 0; bsl::string line; while (getline(fs, line)) { ++numLines; } fs.close(); return numLines; } struct TestCurrentTimeCallback { private: // DATA static bsls::TimeInterval s_utcTime; public: // CLASS METHODS static bsls::TimeInterval load(); // Return the value corresponding to the most recent call to the // 'setTimeToReport' method. The behavior is undefined unless // 'setUtcTime' has been called. static void setUtcDatetime(const bdlt::Datetime& utcTime); // Set the specified 'utcTime' as the value obtained (after conversion // to 'bdlt::IntervalConversionUtil') from calls to the 'load' method. // The behavior is undefined unless // 'bdlt::EpochUtil::epoch() <= utcTime'. }; bsls::TimeInterval TestCurrentTimeCallback::s_utcTime; bsls::TimeInterval TestCurrentTimeCallback::load() { return s_utcTime; } void TestCurrentTimeCallback::setUtcDatetime(const bdlt::Datetime &utcTime) { ASSERT(bdlt::EpochUtil::epoch() <= utcTime); int rc = bdlt::EpochUtil::convertToTimeInterval(&s_utcTime, utcTime); ASSERT(0 == rc); } struct TestLocalTimeOffsetCallback { private: // DATA static bsls::Types::Int64 s_localTimeOffsetInSeconds; static int s_loadCount; public: // CLASS METHODS static bsls::TimeInterval loadLocalTimeOffset(const bdlt::Datetime&); // Return the local time offset that was set by the previous call to // the 'setLocalTimeOffset' method. If the 'setLocalTimeOffset' method // has not been called, load 0. static void setLocalTimeOffset( bsls::Types::Int64 localTimeOffsetInSeconds); // Set the specified 'localTimeOffsetInSeconds' as the value loaded by // calls to the loadLocalTimeOffset' method. static int loadCount(); // Return the number of times the 'loadLocalTimeOffset' method has been // called since the start of process. }; bsls::Types::Int64 TestLocalTimeOffsetCallback::s_localTimeOffsetInSeconds = 0; int TestLocalTimeOffsetCallback::s_loadCount = 0; bsls::TimeInterval TestLocalTimeOffsetCallback::loadLocalTimeOffset( const bdlt::Datetime&) { ++s_loadCount; return bsls::TimeInterval(s_localTimeOffsetInSeconds, 0); } void TestLocalTimeOffsetCallback::setLocalTimeOffset( bsls::Types::Int64 localTimeOffsetInSeconds) { s_localTimeOffsetInSeconds = localTimeOffsetInSeconds; } int TestLocalTimeOffsetCallback::loadCount() { return s_loadCount; } void splitStringIntoLines(bsl::vector *result, const char *ascii) { ASSERT(result); ASSERT(ascii); for (bdlb::Tokenizer itr(bslstl::StringRef(ascii), bslstl::StringRef(""), bslstl::StringRef("\n")); itr.isValid(); ++itr) { if (itr.token().length() > 0) { result->push_back(itr.token()); } } } void getDatetimeField(bsl::string *result, const bsl::string& fileName, int recordNumber) { ASSERT(1 <= recordNumber); bsl::string fileContent; int lineCount = readFileIntoString(__LINE__, fileName, fileContent); ASSERT(recordNumber * 2 <= lineCount); bsl::vector lines; splitStringIntoLines(&lines, fileContent.c_str()); int recordIndex = recordNumber - 1; ASSERT(0 <= recordIndex); ASSERT(static_cast(lines.size()) > recordIndex); const bsl::string& s = lines[recordIndex]; *result = s.substr(0, s.find_first_of(' ')); } } // close unnamed namespace //============================================================================= // MAIN PROGRAM //----------------------------------------------------------------------------- int main(int argc, char *argv[]) { int test = argc > 1 ? bsl::atoi(argv[1]) : 0; verbose = argc > 2; veryVerbose = argc > 3; veryVeryVerbose = argc > 4; veryVeryVeryVerbose = argc > 5; cout << "TEST " << __FILE__ << " CASE " << test << endl; bslma::TestAllocator defaultAllocator("default", veryVeryVeryVerbose); ASSERT(0 == bslma::Default::setDefaultAllocator(&defaultAllocator)); switch (test) { case 0: case 14: { // -------------------------------------------------------------------- // USAGE EXAMPLE // // Concerns: //: 1 The usage example provided in the component header file compiles, //: links, and runs as shown. // // Plan: //: 1 Incorporate usage example from header into test driver, remove //: leading comment characters, and replace 'assert' with 'ASSERT'. //: (C-1) // // Testing: // USAGE EXAMPLE // -------------------------------------------------------------------- if (verbose) cout << "\nUSAGE EXAMPLE" << "\n=============" << endl; // This is standard preamble to create the directory and filename for // the test. TempDirectoryGuard tempDirGuard; bsl::string fileName(tempDirGuard.getTempDirName()); bdls::PathUtil::appendRaw(&fileName, "test.log"); ///Example: Basic Usage /// - - - - - - - - - - // First, we create a 'ball::LoggerManagerConfiguration' object, 'lmConfig', // and set the logging "pass-through" level -- the level at which log records // are published to registered observers -- to 'DEBUG': //.. ball::LoggerManagerConfiguration lmConfig; lmConfig.setDefaultThresholdLevelsIfValid(ball::Severity::e_DEBUG); //.. // Next, create a 'ball::LoggerManagerScopedGuard' object whose constructor // takes the configuration object just created. The guard will initialize the // logger manager singleton on creation and destroy the singleton upon // destruction. This guarantees that any resources used by the logger manager // will be properly released when they are not needed: //.. ball::LoggerManagerScopedGuard guard(lmConfig); ball::LoggerManager& manager = ball::LoggerManager::singleton(); //.. // Next, we create a 'ball::FileObserver2' object and register it with the // 'ball' logging system; //.. bsl::shared_ptr observer = bsl::make_shared(); //.. // Next, we configure the log file rotation rules: //.. // Rotate the file when its size becomes greater than or equal to 128 // megabytes. observer->rotateOnSize(1024 * 128); // Rotate the file every 24 hours. observer->rotateOnTimeInterval(bdlt::DatetimeInterval(1)); //.. // Note that in this configuration the user may end up with multiple log files // for a specific day (because of the rotation-on-size rule). // // Then, we enable logging to a file: //.. // Create and log records to a file named "/var/log/task/task.log". observer->enableFileLogging("/var/log/task/task.log"); //.. // Finally, we register the file observer with the logger manager. Upon // successful registration, the observer will start to receive log records via // the 'publish' method: //.. int rc = manager.registerObserver(observer, "default"); ASSERT(0 == rc); //.. } break; case 13: { // -------------------------------------------------------------------- // REPRODUCE BUG FROM DRQS 123123158 // // Concerns: //: 1 On Solaris, logging "" wound up calling 'fstream::write(0, 0)' //: which Solaris did not deal with properly, and resulted in the //: fail bit of the stream being set and a (confusing) error message //: being written to the console by the file observer. // // Plan: //: 1 Log "" and assert that the file logging is still enabled //: afterward. If the bug manifests itself, and error will be //: written to the console and the assert will fail. // -------------------------------------------------------------------- if (verbose) cout << "REPRODUCE BUG FROM DRQS 123123158\n" "=================================\n"; int rot_size = 1024 * 1024; TempDirectoryGuard tempDirGuard; bsl::string baseName(tempDirGuard.getTempDirName()); bdls::PathUtil::appendRaw(&baseName, "testLog"); if (veryVeryVerbose) { T_; T_; P(baseName); } ball::LoggerManagerConfiguration configuration; configuration.setDefaultThresholdLevelsIfValid( ball::Severity::e_TRACE, ball::Severity::e_TRACE, ball::Severity::e_WARN, ball::Severity::e_FATAL); // Instantiate the logger manager singleton. ball::LoggerManagerScopedGuard scopedGuard(configuration); bsl::shared_ptr observer = bsl::make_shared(); observer->enableFileLogging(baseName.c_str(), false); observer->rotateOnSize(rot_size); ASSERT(0 == ball::LoggerManager::singleton().registerObserver( observer, "testObserver")); // Set a category -- an arbitrary name. BALL_LOG_SET_CATEGORY("main category"); BALL_LOG_INFO << "LOG"; BALL_LOG_TRACE << ""; ASSERT(observer->isFileLoggingEnabled()); if (verbose) { bsl::string out; (void) readFileIntoString(__LINE__, baseName, out); bsl::cout << out; } } break; case 12: { // -------------------------------------------------------------------- // TESTING CURRENT LOCAL-TIME OFFSET IN TIMESTAMP // Per DRQS 13681097, log records observe DST time transitions when // the default logging functor is used and the 'publishInLocalTime' // attribute is 'true'. // // Concern: //: 1 Log records show the current local time offset (possibly //: different from the local time offset in effect on construction), //: when 'true == isPublishInLocalTimeEnabled()'. //: //: 2 Log records show UTC when //: 'false == isPublishInLocalTimeEnabled()'. //: //: 3 QoI: The local-time offset is obtained not more than once per log //: record. //: //: 4 The helper class 'TestCurrentTimeCallback' has a method, 'load', //: that loads the user-specified UTC time, and that method can be //: installed as the system-time callback of 'bdlt::CurrentTime'. //: //: 5 The helper class 'TestLocalTimeOffsetCallback' has a method, //: 'loadLocalTimeOffset', that loads the user-specified local-time //: offset value, and that method can be installed as the local-time //: callback of 'bdlt::CurrentTime', and that the value loaded is not //: influenced by the user-specified 'utcDatetime'. //: //: 6 The helper class method 'TestLocalTimeOffsetCallback::loadCount' //: provides an accurate count of the calls to the //: 'TestLocalTimeOffsetCallback::loadLocalTimeOffset' method. // // Plan: //: 1 Test the helper 'TestCurrentTimeCallback' class (C-4): //: //: 1 Using the array-driven technique, confirm that the 'load' //: method obtains the value last set by the 'setUtcDatetime' //: method. Use UTC values that do not coincide with the actual //: UTC datetime. //: //: 2 Install the 'TestCurrentTimeCallback::load' method as the //: system-time callback of system-time offset callback of //: 'bdlt::CurrentTime', and run through the same values as used in //: P-1.1. Confirm that values returned from 'bdlt::CurrentTime' //: match the user-specified values. //: //: 2 Test the helper 'TestLocalTimeOffsetCallback' class (C-5): //: //: 1 Using the array-driven technique, confirm that the //: 'loadLocalTimeOffset' method obtains the value last set by the //: 'setLocalTimeOffset' method. At least one value should differ //: from the current, actual local-time offset. //: //: 2 Install the 'TestLocalTimeOffsetCallback::loadLocalTimeOffset' //: method as the local-time offset callback of //: 'bdlt::CurrentTime', and run through the same same //: user-specified local time offsets as used in P-2.1. Confirm //: that values returned from 'bdlt::CurrentTime' match the //: user-specified values. Repeat the request for (widely) //: different UTC datetime values to confirm that the local time //: offset value remains that defined by the callback. //: //: 3 Confirm that the value returned by the 'loadCount' method //: increases by exactly 1 each time a local-time offset is //: obtained via 'bdlt::CurrentTime'. (C-6) //: //: 3 Using an ad-hoc approach, confirm that the datetime field of a //: published log record is the expected (arbitrary) UTC datetime //: value when publishing in local-time is disabled. Enable //: publishing in local-time and confirm that the published datetime //: field matches that of the (arbitrary) user-defined local-time //: offsets. Disable publishing in local time, and confirm that log //: records are again published with the UTC datetime. (C-1, C-2) //: //: 4 When publishing in local time is enabled, confirm that there //: exactly 1 request for local time offset for each published //: record. (C-3) // // Testing: // CONCERN: CURRENT LOCAL-TIME OFFSET IN TIMESTAMP // -------------------------------------------------------------------- if (verbose) cout << "\nTESTING CURRENT LOCAL-TIME OFFSET IN TIMESTAMP" << "\n==============================================" << endl; const bdlt::Datetime UTC_ARRAY[] = { bdlt::EpochUtil::epoch(), bdlt::Datetime(2017, 1, 1, 12, 46, 30, 0), bdlt::Datetime(9999, 12, 31, 23, 59, 59, 999) }; enum { NUM_UTC_ARRAY = sizeof UTC_ARRAY / sizeof *UTC_ARRAY }; if (verbose) cout << "\nTest TestCurrentTimeCallback: Direct" << endl; { for (int i = 0; i < NUM_UTC_ARRAY; ++i) { bdlt::Datetime utcDatetime = UTC_ARRAY[i]; if (veryVerbose) { T_ P_(i) P(utcDatetime) } TestCurrentTimeCallback::setUtcDatetime(utcDatetime); bsls::TimeInterval result = TestCurrentTimeCallback::load(); bdlt::Datetime resultAsDatetime = bdlt::EpochUtil::convertFromTimeInterval(result); ASSERTV(i, utcDatetime == resultAsDatetime); } } if (verbose) cout << "\nTest TestCurrentTimeCallback: Installed" << endl; { // Install callback from 'TestCurrentTimeCallback'. bdlt::CurrentTime::CurrentTimeCallback originalCurrentTimeCallback = bdlt::CurrentTime::setCurrentTimeCallback( &TestCurrentTimeCallback::load); for (int i = 0; i < NUM_UTC_ARRAY; ++i) { bdlt::Datetime utcDatetime = UTC_ARRAY[i]; if (veryVerbose) { T_ P_(i) P(utcDatetime) } TestCurrentTimeCallback::setUtcDatetime(utcDatetime); bdlt::Datetime result1 = bdlt::CurrentTime::utc(); bslmt::ThreadUtil::microSleep(0, 2); // two seconds bdlt::Datetime result2 = bdlt::CurrentTime::utc(); ASSERTV(i, utcDatetime == result1); ASSERTV(i, result2 == result1); } // Restore original system-time callback. bdlt::CurrentTime::setCurrentTimeCallback( originalCurrentTimeCallback); } const Int64 LTO_ARRAY[] = { -86399, -1, 0, 1, 86399 }; enum { NUM_LTO_ARRAY = sizeof LTO_ARRAY / sizeof *LTO_ARRAY }; int loadCount = TestLocalTimeOffsetCallback::loadCount(); ASSERT(0 == loadCount); if (verbose) cout << "\nTest TestLocalTimeOffsetCallback: Direct" << endl; { for (int i = 0; i < NUM_LTO_ARRAY; ++i) { Int64 localTimeOffset = LTO_ARRAY[i]; if (veryVerbose) { T_ P_(i) P(localTimeOffset) } TestLocalTimeOffsetCallback::setLocalTimeOffset( localTimeOffset); for (int j = 0; j < NUM_UTC_ARRAY; ++j) { bdlt::Datetime utcDatetime = UTC_ARRAY[j]; if (veryVerbose) { T_ T_ P_(j) P(utcDatetime) } Int64 result = TestLocalTimeOffsetCallback::loadLocalTimeOffset( utcDatetime) .totalSeconds(); ++loadCount; ASSERTV(i, j, localTimeOffset == result); ASSERTV(i, j, loadCount == TestLocalTimeOffsetCallback::loadCount()); } } } if (verbose) cout << "\nTest TestLocalTimeOffsetCallback: Installed" << endl; { bdlt::LocalTimeOffset::LocalTimeOffsetCallback originalLocalTimeOffsetCallback = bdlt::LocalTimeOffset::setLocalTimeOffsetCallback( &TestLocalTimeOffsetCallback::loadLocalTimeOffset); for (int i = 0; i < NUM_LTO_ARRAY; ++i) { Int64 localTimeOffset = LTO_ARRAY[i]; if (veryVerbose) { T_ P_(i) P(localTimeOffset) } TestLocalTimeOffsetCallback::setLocalTimeOffset( localTimeOffset); for (int j = 0; j < NUM_UTC_ARRAY; ++j) { bdlt::Datetime utcDatetime = UTC_ARRAY[j]; if (veryVerbose) { T_ T_ P_(j) P(utcDatetime) } Int64 result = bdlt::LocalTimeOffset::localTimeOffset(utcDatetime) .totalSeconds(); ++loadCount; ASSERTV(i, j, localTimeOffset == result); ASSERTV(i, j, loadCount == TestLocalTimeOffsetCallback::loadCount()); } } bdlt::LocalTimeOffset::setLocalTimeOffsetCallback( originalLocalTimeOffsetCallback); } } break; case 11: { // -------------------------------------------------------------------- // TESTING TIME CALLBACKS // // Concern: //: 1 Time converting callbacks are invoked when log string is //: generated. // // Plan: //: 1 Call logging and verify that the installed test time callbacks //: are invoked as expected. // // Testing: // CONCERN: TIME CALLBACKS ARE CALLED // -------------------------------------------------------------------- if (verbose) cout << "\nTESTING TIME CALLBACKS" << "\n======================" << endl; const bdlt::Datetime UTC_ARRAY[] = { bdlt::EpochUtil::epoch(), bdlt::Datetime(2017, 1, 1, 12, 46, 30, 0), bdlt::Datetime(9999, 12, 31, 23, 59, 59, 999) }; enum { NUM_UTC_ARRAY = sizeof UTC_ARRAY / sizeof *UTC_ARRAY }; // This configuration guarantees that the logger manager will publish // all messages regardless of their severity and the observer will see // each message only once. ball::LoggerManagerConfiguration configuration; ASSERT(0 == configuration.setDefaultThresholdLevelsIfValid( ball::Severity::e_OFF, ball::Severity::e_TRACE, ball::Severity::e_OFF, ball::Severity::e_OFF)); ball::LoggerManagerScopedGuard guard(configuration); ball::LoggerManager& manager = ball::LoggerManager::singleton(); { bslma::TestAllocator da("da", veryVeryVeryVerbose); bslma::TestAllocator ta("ta", veryVeryVeryVerbose); bslma::DefaultAllocatorGuard dag(&da); TempDirectoryGuard tempDirGuard; bsl::shared_ptr mX(new (ta) Obj(&ta), &ta); bsl::shared_ptr X = mX; ASSERT(0 == manager.registerObserver(mX, "testObserver")); bsl::string baseName(tempDirGuard.getTempDirName()); bdls::PathUtil::appendRaw(&baseName, "testLog"); if (veryVeryVerbose) { T_; T_; P(baseName); } enableFileLogging(mX, baseName, true); // Fetch the actual file name with timestamp appended. bsl::string fileName; ASSERT(true == X->isFileLoggingEnabled(&fileName)); if (veryVeryVerbose) { T_; T_; P(fileName); } BALL_LOG_SET_CATEGORY("TestCategory"); int logRecordCount = 0; int testLocalTimeOffsetInSeconds; bsl::string datetimeField; bsl::ostringstream expectedDatetimeField; const bdlt::Datetime testUtcDatetime = UTC_ARRAY[1]; bdlt::CurrentTime::CurrentTimeCallback originalCurrentTimeCallback = bdlt::CurrentTime::setCurrentTimeCallback( &TestCurrentTimeCallback::load); TestCurrentTimeCallback::setUtcDatetime(testUtcDatetime); bdlt::LocalTimeOffset::LocalTimeOffsetCallback originalLocalTimeOffsetCallback = bdlt::LocalTimeOffset::setLocalTimeOffsetCallback( &TestLocalTimeOffsetCallback::loadLocalTimeOffset); int expectedLoadCount = TestLocalTimeOffsetCallback::loadCount(); if (veryVerbose) cout << "\tLog with Publish In Local Time Disabled" << endl; ASSERT(false == X->isPublishInLocalTimeEnabled()); BALL_LOG_TRACE << "log 1"; ++logRecordCount; getDatetimeField(&datetimeField, fileName, logRecordCount); const int SIZE = 32; char buffer[SIZE]; bsl::memset(buffer, 'X', SIZE); testUtcDatetime.printToBuffer(buffer, SIZE, 3); bsl::string EXP(buffer); if (veryVerbose) { T_ P_(EXP) P(datetimeField) } ASSERT(EXP == datetimeField); ASSERT(expectedLoadCount == TestLocalTimeOffsetCallback::loadCount()); BALL_LOG_TRACE << "log 2"; ++logRecordCount; getDatetimeField(&datetimeField, fileName, logRecordCount); bsl::memset(buffer, 'X', SIZE); testUtcDatetime.printToBuffer(buffer, SIZE, 3); EXP.assign(buffer); if (veryVerbose) { T_ P_(EXP) P(datetimeField) } ASSERT(EXP == datetimeField); ASSERT(expectedLoadCount == TestLocalTimeOffsetCallback::loadCount()); if (veryVerbose) cout << "\tLog with Publish In Local Time Enabled" << endl; mX->enablePublishInLocalTime(); ASSERT(X->isPublishInLocalTimeEnabled()); testLocalTimeOffsetInSeconds = -1 * 60 * 60; TestLocalTimeOffsetCallback::setLocalTimeOffset( testLocalTimeOffsetInSeconds); if (veryVerbose) { T_ P(testLocalTimeOffsetInSeconds); } BALL_LOG_TRACE << "log 3"; ++logRecordCount; ++expectedLoadCount; getDatetimeField(&datetimeField, fileName, logRecordCount); bsl::memset(buffer, 'X', SIZE); bdlt::Datetime DT = testUtcDatetime + bdlt::DatetimeInterval(0, 0, 0, testLocalTimeOffsetInSeconds, 0); DT.printToBuffer(buffer, SIZE, 3); EXP.assign(buffer); if (veryVerbose) { T_ P_(EXP) P(datetimeField) } ASSERT(EXP == datetimeField); ASSERT(expectedLoadCount == TestLocalTimeOffsetCallback::loadCount()); testLocalTimeOffsetInSeconds = -2 * 60 * 60; TestLocalTimeOffsetCallback::setLocalTimeOffset( testLocalTimeOffsetInSeconds); if (veryVerbose) { T_ P(testLocalTimeOffsetInSeconds); } BALL_LOG_TRACE << "log 4"; ++logRecordCount; ++expectedLoadCount; getDatetimeField(&datetimeField, fileName, logRecordCount); bsl::memset(buffer, 'X', SIZE); DT = testUtcDatetime + bdlt::DatetimeInterval(0, 0, 0, testLocalTimeOffsetInSeconds, 0); DT.printToBuffer(buffer, SIZE, 3); EXP.assign(buffer); if (veryVerbose) { T_ P_(EXP) P(datetimeField) } ASSERT(EXP == datetimeField); ASSERT(expectedLoadCount == TestLocalTimeOffsetCallback::loadCount()); mX->disablePublishInLocalTime(); ASSERT(false == X->isPublishInLocalTimeEnabled()); BALL_LOG_TRACE << "log 5"; ++logRecordCount; getDatetimeField(&datetimeField, fileName, logRecordCount); bsl::memset(buffer, 'X', SIZE); testUtcDatetime.printToBuffer(buffer, SIZE, 3); EXP.assign(buffer); if (veryVerbose) { T_ P_(EXP) P(datetimeField) } ASSERT(EXP == datetimeField); ASSERT(expectedLoadCount == TestLocalTimeOffsetCallback::loadCount()); if (veryVerbose) cout << "\tLog with Publish In Local Time Disabled Again" << endl; if (veryVerbose) cout << "\tCleanup" << endl; bdlt::CurrentTime::setCurrentTimeCallback( originalCurrentTimeCallback); bdlt::LocalTimeOffset::setLocalTimeOffsetCallback( originalLocalTimeOffsetCallback); mX->disableFileLogging(); // Deregister here as we used local allocator for the observer. ASSERT(0 == manager.deregisterObserver("testObserver")); } } break; case 10: { // -------------------------------------------------------------------- // TESTING 'rotateOnTimeInterval' AFTER 'enableFileLogging' // // Concern: //: 1 'rotateOnTimeInterval' does not cause rotation immediately if //: invoked after 'enableFileLogging'. // // Plan: //: 1 Invoke 'enableFileLogging' before 'rotateOnTimeInterval' and //: verify rotation does not occur. // // Testing: // CONCERN: ROTATION CAN BE ENABLED AFTER FILE LOGGING // -------------------------------------------------------------------- if (verbose) cout << "\nTESTING 'rotateOnTimeInterval' AFTER 'enableFileLogging'" << "\n========================================================" << endl; // This configuration guarantees that the logger manager will publish // all messages regardless of their severity and the observer will see // each message only once. ball::LoggerManagerConfiguration configuration; ASSERT(0 == configuration.setDefaultThresholdLevelsIfValid( ball::Severity::e_OFF, ball::Severity::e_TRACE, ball::Severity::e_OFF, ball::Severity::e_OFF)); ball::LoggerManagerScopedGuard guard(configuration); ball::LoggerManager& manager = ball::LoggerManager::singleton(); { bslma::TestAllocator da("da", veryVeryVeryVerbose); bslma::TestAllocator ta("ta", veryVeryVeryVerbose); bslma::DefaultAllocatorGuard dag(&da); TempDirectoryGuard tempDirGuard; bsl::string fileName(tempDirGuard.getTempDirName()); bdls::PathUtil::appendRaw(&fileName, "testLog"); bsl::shared_ptr mX(new (ta) Obj(&ta), &ta); bsl::shared_ptr X = mX; ASSERT(0 == manager.registerObserver(mX, "testObserver")); // Set callback to monitor rotation. RotCb cb(&ta); mX->setOnFileRotationCallback(cb); enableFileLogging(mX, fileName); ASSERT(0 == cb.numInvocations()); BALL_LOG_SET_CATEGORY("TestCategory"); mX->rotateOnTimeInterval(bdlt::DatetimeInterval(1)); BALL_LOG_TRACE << "log"; ASSERT(0 == cb.numInvocations()); mX->disableFileLogging(); ASSERT(0 == manager.deregisterObserver("testObserver")); } } break; case 9: { // -------------------------------------------------------------------- // TESTING TIME-BASED ROTATION // // Concern: //: 1 'rotateOnTimeInterval' accepts any valid datetime value as the //: reference time. //: //: 2 Reference time is a local time. // // Plan: //: 1 Setup test infrastructure. //: //: 2 Call 'rotateOnTimeInterval' with boundary values on the reference //: start time, and verify that rotation occurs on schedule. (C-1) //: //: 3 Call 'rotateOnTimeInterval' with a large interval and a reference //: time such that the next rotation will occur soon. Verify that //: rotation occurs on the scheduled time. (C-2) // // Testing: // void rotateOnTimeInterval(const DtInterval& i, const Datetime& s); // -------------------------------------------------------------------- if (verbose) cout << "\nTESTING TIME-BASED ROTATION" << "\n===========================" << endl; // This configuration guarantees that the logger manager will publish // all messages regardless of their severity and the observer will see // each message only once. ball::LoggerManagerConfiguration configuration; ASSERT(0 == configuration.setDefaultThresholdLevelsIfValid( ball::Severity::e_OFF, ball::Severity::e_TRACE, ball::Severity::e_OFF, ball::Severity::e_OFF)); ball::LoggerManagerScopedGuard guard(configuration); ball::LoggerManager& manager = ball::LoggerManager::singleton(); { bslma::TestAllocator da("da", veryVeryVeryVerbose); bslma::TestAllocator ta("ta", veryVeryVeryVerbose); bslma::DefaultAllocatorGuard dag(&da); bsl::shared_ptr mX(new (ta) Obj(&ta), &ta); bsl::shared_ptr X = mX; ASSERT(0 == manager.registerObserver(mX, "testObserver")); RotCb cb(&ta); mX->setOnFileRotationCallback(cb); mX->enablePublishInLocalTime(); { TempDirectoryGuard tempDirGuard; bsl::string fileName(tempDirGuard.getTempDirName()); bdls::PathUtil::appendRaw(&fileName, "testLog"); // Set callback to monitor rotation. enableFileLogging(mX, fileName); ASSERTV(cb.numInvocations(), 0 == cb.numInvocations()); mX->disableFileLogging(); } if (veryVerbose) cout << "Test lower bound of absolute time reference." << endl; { BALL_LOG_SET_CATEGORY("TestCategory"); TempDirectoryGuard tempDirGuard; bsl::string fileName(tempDirGuard.getTempDirName()); bdls::PathUtil::appendRaw(&fileName, "testLog"); mX->rotateOnTimeInterval(bdlt::DatetimeInterval(0, 0, 0, 2), bdlt::Datetime(1, 1, 1)); enableFileLogging(mX, fileName); bslmt::ThreadUtil::microSleep(0, 2); ASSERTV(cb.numInvocations(), 0 == cb.numInvocations()); BALL_LOG_TRACE << "log"; ASSERTV(cb.numInvocations(), 1 == cb.numInvocations()); ASSERT(1 == FsUtil::exists(cb.rotatedFileName().c_str())); mX->disableFileLogging(); cb.reset(); } if (veryVerbose) cout << "Test upper bound of absolute time reference." << endl; { BALL_LOG_SET_CATEGORY("TestCategory"); TempDirectoryGuard tempDirGuard; bsl::string fileName(tempDirGuard.getTempDirName()); bdls::PathUtil::appendRaw(&fileName, "testLog"); mX->rotateOnTimeInterval( bdlt::DatetimeInterval(0, 0, 0, 2), bdlt::Datetime(9999, 12, 31, 23, 59, 59)); enableFileLogging(mX, fileName); bslmt::ThreadUtil::microSleep(0, 2); ASSERTV(cb.numInvocations(), 0 == cb.numInvocations()); BALL_LOG_TRACE << "log"; ASSERTV(cb.numInvocations(), 1 == cb.numInvocations()); ASSERT(1 == FsUtil::exists(cb.rotatedFileName().c_str())); mX->disableFileLogging(); cb.reset(); } if (veryVerbose) cout << "Test absolute time reference." << endl; { BALL_LOG_SET_CATEGORY("TestCategory"); TempDirectoryGuard tempDirGuard; bsl::string fileName(tempDirGuard.getTempDirName()); bdls::PathUtil::appendRaw(&fileName, "testLog"); bdlt::Datetime startTime = bdlt::CurrentTime::local(); startTime += bdlt::DatetimeInterval(-1, 0, 0, 3); mX->rotateOnTimeInterval(bdlt::DatetimeInterval(1), startTime); enableFileLogging(mX, fileName); BALL_LOG_TRACE << "log"; bslmt::ThreadUtil::microSleep(0, 2); // 2s ASSERTV(cb.numInvocations(), 0 == cb.numInvocations()); bslmt::ThreadUtil::microSleep(250000, 1); // 3.25s BALL_LOG_TRACE << "log"; ASSERTV(cb.numInvocations(), 1 == cb.numInvocations()); ASSERT(1 == FsUtil::exists(cb.rotatedFileName().c_str())); mX->disableFileLogging(); cb.reset(); } ASSERT(0 == manager.deregisterObserver("testObserver")); } } break; case 8: { // -------------------------------------------------------------------- // TESTING TIME-BASED ROTATION // // Concern: //: 1 Time-based rotation occurs as scheduled //: //: 2 Rotation schedule is not affected if the previous rotation was //: delayed because not record was published at the scheduled time //: of rotation. //: //: 3 A rotation that occurred between two scheduled rotations does //: not affect the schedule. //: //: 4 Disabling file logging does not affect rotation schedule. //: //: 5 'disableLifetimeRotation' prevents further time-base rotation. //: //: 6 A delay between 'enableFileLogging' and 'rotateOnTimeInterval', //: when 'rotateOnItemInterval' uses the current time as its //: reference start time, does not incur an erroneous rotation //: (DRQS 87930585). // // Plan: //: 1 Configure rotation for 1 second. Log a record before 1 second, //: and ensure that no rotation occurs. Then log a record after the //: 1 second and verify a rotation occurs. (C-1) //: //: 2 Delay logging such that the rotation is delayed. Then verify the //: schedule for the next rotation is not affected. (C-2) //: //: 3 Cause a rotation to occur between scheduled rotations and verify //: that the rotation schedule is not affected. (C-3) //: //: 4 Disable and then re-enable file logging and verify rotation //: schedule is not affect. (C-4) //: //: 5 Call 'disableTimeIntervalRotation' and verify that time-based //: rotation is disabled. (C-5) //: //: 6 Insert a delay between 'enableFileLogging' and //: 'rotateOnTimeInterval' and verify the log file is not //: immediately rotated. (C-6) //: // Testing: // void rotateOnTimeInterval(const DatetimeInterval& interval); // void disableTimeIntervalRotation(); // -------------------------------------------------------------------- if (verbose) cout << "\nTESTING TIME-BASED ROTATION" << "\n===========================" << endl; if (veryVerbose) cout << "Test normal rotation" << endl; { bslma::TestAllocator ta("test", veryVeryVeryVerbose); TempDirectoryGuard tempDirGuard; bsl::string fileName(tempDirGuard.getTempDirName()); bdls::PathUtil::appendRaw(&fileName, "testLog"); Obj mX(&ta); RotCb cb(&ta); mX.setOnFileRotationCallback(cb); mX.rotateOnTimeInterval(bdlt::DatetimeInterval(0, 0, 0, 1)); ASSERT(0 == mX.enableFileLogging(fileName.c_str())); bslmt::ThreadUtil::microSleep(250000, 0); publishRecord(&mX, "test message 1"); ASSERTV(cb.numInvocations(), 0 == cb.numInvocations()); bslmt::ThreadUtil::microSleep(0, 1); publishRecord(&mX, "test message 2"); ASSERTV(cb.numInvocations(), 1 == cb.numInvocations()); mX.disableFileLogging(); } if (veryVerbose) cout << "Test delayed logging" << endl; { bslma::TestAllocator ta("test", veryVeryVeryVerbose); TempDirectoryGuard tempDirGuard; bsl::string fileName(tempDirGuard.getTempDirName()); bdls::PathUtil::appendRaw(&fileName, "testLog"); // Rotate every 1s. Obj mX(&ta); RotCb cb(&ta); mX.setOnFileRotationCallback(cb); mX.rotateOnTimeInterval(bdlt::DatetimeInterval(0, 0, 0, 1)); ASSERT(0 == mX.enableFileLogging(fileName.c_str())); bslmt::ThreadUtil::microSleep(100000, 1); // 1.1 s publishRecord(&mX, "test message 1"); ASSERTV(cb.numInvocations(), 1 == cb.numInvocations()); // Delay the next message so that it is in the middle of an // scheduled rotation. bslmt::ThreadUtil::microSleep(750000, 1); // 1.75s publishRecord(&mX, "test message 2"); ASSERTV(cb.numInvocations(), 2 == cb.numInvocations()); // Verify we are back on schedule. bslmt::ThreadUtil::microSleep(250000, 0); // .25s publishRecord(&mX, "test message 3"); ASSERTV(cb.numInvocations(), 3 == cb.numInvocations()); mX.disableFileLogging(); } if (veryVerbose) cout << "Test rotation between scheduled rotations" << endl; { bslma::TestAllocator ta("test", veryVeryVeryVerbose); TempDirectoryGuard tempDirGuard; bsl::string fileName(tempDirGuard.getTempDirName()); bdls::PathUtil::appendRaw(&fileName, "testLog"); Obj mX(&ta); RotCb cb(&ta); mX.setOnFileRotationCallback(cb); mX.rotateOnTimeInterval(bdlt::DatetimeInterval(0, 0, 0, 1)); ASSERT(0 == mX.enableFileLogging(fileName.c_str())); bslmt::ThreadUtil::microSleep(500000, 0); // .5s mX.forceRotation(); ASSERTV(cb.numInvocations(), 1 == cb.numInvocations()); bslmt::ThreadUtil::microSleep(600000, 0); // .6s publishRecord(&mX, "test message 1"); ASSERTV(cb.numInvocations(), 2 == cb.numInvocations()); mX.disableFileLogging(); } if (veryVerbose) cout << "Test disabling file logging between rotations" << endl; { bslma::TestAllocator ta("test", veryVeryVeryVerbose); TempDirectoryGuard tempDirGuard; bsl::string fileName(tempDirGuard.getTempDirName()); bdls::PathUtil::appendRaw(&fileName, "testLog"); Obj mX(&ta); RotCb cb(&ta); mX.setOnFileRotationCallback(cb); mX.rotateOnTimeInterval(bdlt::DatetimeInterval(0, 0, 0, 1)); ASSERT(0 == mX.enableFileLogging(fileName.c_str())); bslmt::ThreadUtil::microSleep(0, 2); ASSERTV(cb.numInvocations(), 0 == cb.numInvocations()); mX.disableFileLogging(); ASSERT(0 == mX.enableFileLogging(fileName.c_str())); // This rotation should happen immediately. publishRecord(&mX, "test message 1"); ASSERTV(cb.numInvocations(), 1 == cb.numInvocations()); mX.disableFileLogging(); } if (veryVerbose) cout << "Test 'disableTimeIntervalRotation" << endl; { bslma::TestAllocator ta("test", veryVeryVeryVerbose); TempDirectoryGuard tempDirGuard; bsl::string fileName(tempDirGuard.getTempDirName()); bdls::PathUtil::appendRaw(&fileName, "testLog"); Obj mX(&ta); RotCb cb(&ta); mX.setOnFileRotationCallback(cb); mX.rotateOnTimeInterval(bdlt::DatetimeInterval(0, 0, 0, 0, 500)); ASSERT(0 == mX.enableFileLogging(fileName.c_str())); bslmt::ThreadUtil::microSleep(0, 1); mX.disableTimeIntervalRotation(); publishRecord(&mX, "test message 1"); ASSERTV(cb.numInvocations(), 0 == cb.numInvocations()); mX.disableFileLogging(); } if (veryVerbose) cout << "\tTest a delayed rotateOnTimeInterval" << "(DRQS 87930585)" << bsl::endl; { // Test if there is a delay between 'enableFileLogging' and // 'rotateOnTimeInterval'. bslma::TestAllocator ta("test", veryVeryVeryVerbose); TempDirectoryGuard tempDirGuard; bsl::string fileName(tempDirGuard.getTempDirName()); bdls::PathUtil::appendRaw(&fileName, "testLog"); Obj mX(&ta); RotCb cb(&ta); mX.setOnFileRotationCallback(cb); mX.enablePublishInLocalTime(); ASSERT(0 == mX.enableFileLogging(fileName.c_str())); // Delay, so that the time stamps for the file log and reference // start time (which is supplied by a default parameter value on // 'rotateOnTimeInterval') differ by a small amount. bslmt::ThreadUtil::microSleep(0, 1); mX.rotateOnTimeInterval(bdlt::DatetimeInterval(0, 1)); // 1 hour ASSERT(0 == cb.numInvocations()); publishRecord(&mX, "test message 1"); bslmt::ThreadUtil::microSleep(0, 1); publishRecord(&mX, "test message 2"); // Verify the callback has not been invoked. ASSERT(0 == cb.numInvocations()); mX.disableFileLogging(); } } break; case 7: { // -------------------------------------------------------------------- // TESTING ROTATION CALLBACK WITH EXISTING FILE // // Concerns: //: 1 'rotateOnSize' triggers a rotation as expected even if the log //: file already exist. // // Plan: //: 1 Set 'rotateOnSize' to 1k, create a file with approximately 0.5k. //: //: 2 Write another 0.5k to the file and verify that the file is //: rotated. (C-1) // // Testing: // CONCERN: ROTATION CALLBACK TRIGGERS CORRECTLY FOR EXISTING FILE // -------------------------------------------------------------------- if (verbose) cout << "\nTESTING ROTATION CALLBACK WITH EXISTING FILE" << "\n============================================" << endl; // This configuration guarantees that the logger manager will publish // all messages regardless of their severity and the observer will see // each message only once. ball::LoggerManagerConfiguration configuration; ASSERT(0 == configuration.setDefaultThresholdLevelsIfValid( ball::Severity::e_OFF, ball::Severity::e_TRACE, ball::Severity::e_OFF, ball::Severity::e_OFF)); ball::LoggerManagerScopedGuard guard(configuration); ball::LoggerManager& manager = ball::LoggerManager::singleton(); BALL_LOG_SET_CATEGORY("TestCategory"); bslma::TestAllocator ta("ta", veryVeryVeryVerbose); bsl::shared_ptr mX(new (ta) Obj(&ta), &ta); ASSERT(0 == manager.registerObserver(mX, "testObserver")); RotCb cb(&ta); mX->setOnFileRotationCallback(cb); if (verbose) cout << "Test-case infrastructure setup." << endl; { TempDirectoryGuard tempDirGuard; bsl::string fileName(tempDirGuard.getTempDirName()); bdls::PathUtil::appendRaw(&fileName, "testLog"); if (verbose) cout << "Testing setup." << endl; { enableFileLogging(mX, fileName); mX->rotateOnSize(1); BALL_LOG_TRACE << "log 1"; ASSERT(1 == FsUtil::exists(fileName.c_str())); ASSERT(2 == getNumLines(fileName.c_str())); ASSERT(0 == cb.numInvocations()); } if (verbose) cout << "Testing file observer with existing file." << endl; { char buffer[512]; memset(buffer, 'x', sizeof buffer); buffer[sizeof buffer - 1] = '\0'; BALL_LOG_TRACE << buffer; mX->disableFileLogging(); enableFileLogging(mX, fileName); BALL_LOG_TRACE << 'x'; ASSERT(0 == cb.numInvocations()); BALL_LOG_TRACE << buffer; BALL_LOG_TRACE << 'x'; ASSERT(1 == FsUtil::exists(fileName.c_str())); ASSERT(1 == cb.numInvocations()); ASSERT(1 == FsUtil::exists(cb.rotatedFileName().c_str())); } mX->disableFileLogging(); } // Deregister here as we used local allocator for the observer. ASSERT(0 == manager.deregisterObserver("testObserver")); } break; case 6: { // -------------------------------------------------------------------- // TESTING ROTATE ON SIZE ON EXISTING FILE // // Concerns: //: 1 Rotate on size is based on file size and not the number of bytes //: written to the file. // // Plan: //: 1 Disable any rotation and create a file over 1 KB and then disable //: file logging. Enable 'rotateOnSize', start logging again and //: verify that the file is rotated on first log. (C-1) // // Testing: // CONCERN: ROTATION ON SIZE WORKS FOR EXISTING FILES // -------------------------------------------------------------------- if (verbose) cout << "\nTESTING ROTATE ON SIZE ON EXISTING FILE" << "\n=======================================" << endl; // This configuration guarantees that the logger manager will publish // all messages regardless of their severity and the observer will see // each message only once. ball::LoggerManagerConfiguration configuration; ASSERT(0 == configuration.setDefaultThresholdLevelsIfValid( ball::Severity::e_OFF, ball::Severity::e_TRACE, ball::Severity::e_OFF, ball::Severity::e_OFF)); ball::LoggerManagerScopedGuard guard(configuration); ball::LoggerManager& manager = ball::LoggerManager::singleton(); BALL_LOG_SET_CATEGORY("TestCategory"); bslma::TestAllocator ta("ta", veryVeryVeryVerbose); bsl::shared_ptr mX(new (ta) Obj(&ta), &ta); bsl::shared_ptr X = mX; ASSERT(0 == manager.registerObserver(mX, "testObserver")); RotCb cb(&ta); mX->setOnFileRotationCallback(cb); { TempDirectoryGuard tempDirGuard; bsl::string fileName(tempDirGuard.getTempDirName()); bdls::PathUtil::appendRaw(&fileName, "testLog"); enableFileLogging(mX, fileName); char buffer[1024]; memset(buffer, 'x', sizeof buffer); buffer[sizeof buffer - 1] = '\0'; BALL_LOG_TRACE << buffer; mX->disableFileLogging(); ASSERT(false == X->isFileLoggingEnabled()); ASSERT(1024 < FsUtil::getFileSize(fileName.c_str())); ASSERT(0 == X->rotationSize()); mX->rotateOnSize(1); ASSERT(1 == X->rotationSize()); enableFileLogging(mX, fileName); BALL_LOG_TRACE << "x"; ASSERTV(cb.numInvocations(), 1 == cb.numInvocations()); ASSERTV(cb.status(), 0 == cb.status()); ASSERT(1 == FsUtil::exists(cb.rotatedFileName())); mX->disableFileLogging(); } // Deregister here as we used local allocator for the observer. ASSERT(0 == manager.deregisterObserver("testObserver")); } break; case 5: { // -------------------------------------------------------------------- // TESTING LOG FILE ROTATION CALLBACK // // Concerns: //: 1 Rotation callback is invoked when a rotation occurs, regardless //: of the event that causes the rotation. //: //: 2 Setting a callback is not necessary for file rotation whether the //: rotation succeed or not. //: //: 3 Rotation callback is *not* invoked if a rotation did not occur. //: //: 4 Rotation callback supply the name of the rotated log file. //: //: 5 Rotation callback is invoked in such a way that the file observer //: is not locked during the callback. // // Plan: //: 1 Call 'forceRotation' without setting the callback. (C-2) //: //: 2 Call 'forceRotation' when logging is not enable and verify that //: the callback is not invoked. (C-3) //: //: 3 Setup the test callback function. Call 'enableFileLogging' with //: a pattern that produces unique log names. Call 'forceRotation' //: and verify that the callback is invoked and the rotated log name //: is as expected. //: //: 4 Setup the test callback function. Call 'enableFileLogging' with //: a pattern that produces logs with the same names. Call //: 'forceRotation' and verify that the callback is invoked and the //: rotated log name is changed. //: //: 5 Setup the test callback function. Cause a rotation-on-size and //: rotation-on-time-interval, and verify that the callback is //: invoked. //: //: 6 Set file rotation callback with a function that will call //: 'disableFileLogging'. Call 'forceRotation' and verify it does //: not result in a deadlock. // // Testing: // void setOnFileRotationCallback(const OnFileRotationCallback&); // -------------------------------------------------------------------- if (verbose) cout << "\nTESTING LOG FILE ROTATION CALLBACK" << "\n==================================" << endl; if (veryVerbose) cout << "\tTest a rotation that will fail without a callback." << endl; { bslma::TestAllocator da("default", veryVeryVeryVerbose); bslma::TestAllocator ta("test", veryVeryVeryVerbose); bslma::DefaultAllocatorGuard dag(&da); Obj mX(&ta); mX.forceRotation(); ASSERT(0 == da.numBytesInUse()); } if (veryVerbose) cout << "\tTest a rotation that fails with a callback." << endl; { bslma::TestAllocator da("default", veryVeryVeryVerbose); bslma::TestAllocator ta("test", veryVeryVeryVerbose); bslma::DefaultAllocatorGuard dag(&da); Obj mX(&ta); RotCb cb(&ta); mX.setOnFileRotationCallback(cb); ASSERT(0 == cb.numInvocations()); mX.forceRotation(); ASSERT(0 == cb.numInvocations()); ASSERT(0 != cb.status()); ASSERT(0 == da.numBytesInUse()); } if (veryVerbose) cout << "\tTest a rotation that renames old log files." << endl; { bslma::TestAllocator ta("test", veryVeryVeryVerbose); TempDirectoryGuard tempDirGuard; bsl::string fileName(tempDirGuard.getTempDirName()); bdls::PathUtil::appendRaw(&fileName, "testLog"); Obj mX; const Obj& X = mX; RotCb cb(&ta); mX.setOnFileRotationCallback(cb); ASSERT(0 == cb.numInvocations()); ASSERT(0 == mX.enableFileLogging(fileName.c_str())); bsl::string logName; ASSERT(true == X.isFileLoggingEnabled(&logName)); for (int i = 0; i < 3; ++i) { // A sleep is required because timestamp resolution is 1 second bslmt::ThreadUtil::microSleep(0, 1); ASSERTV(i, cb.numInvocations(), 0 == cb.numInvocations()); mX.forceRotation(); ASSERTV(i, cb.numInvocations(), 1 == cb.numInvocations()); ASSERTV(i, cb.status(), 0 == cb.status()); ASSERTV(i, logName, cb.rotatedFileName(), logName != cb.rotatedFileName()); if (veryVeryVerbose) { P(cb.rotatedFileName()); } cb.reset(); } } if (veryVerbose) cout << "\tTest a rotation that succeeds with a callback." << endl; { bslma::TestAllocator ta("test", veryVeryVeryVerbose); TempDirectoryGuard tempDirGuard; bsl::string fileName(tempDirGuard.getTempDirName()); bdls::PathUtil::appendRaw(&fileName, "testLog.%T"); Obj mX; const Obj& X = mX; RotCb cb(&ta); mX.setOnFileRotationCallback(cb); ASSERT(0 == cb.numInvocations()); ASSERT(0 == mX.enableFileLogging(fileName.c_str())); for (int i = 0; i < 3; ++i) { // A sleep is required because timestamp resolution is 1 second bslmt::ThreadUtil::microSleep(0, 1); bsl::string logName; ASSERT(true == X.isFileLoggingEnabled(&logName)); ASSERTV(i, cb.numInvocations(), 0 == cb.numInvocations()); mX.forceRotation(); ASSERTV(i, cb.numInvocations(), 1 == cb.numInvocations()); ASSERTV(i, cb.status(), 0 == cb.status()); ASSERTV(i, logName, cb.rotatedFileName(), logName == cb.rotatedFileName()); if (veryVeryVerbose) { P(cb.rotatedFileName()); } cb.reset(); } } if (veryVerbose) cout << "\tTest a with publication rotation" << endl; { bslma::TestAllocator ta("test", veryVeryVeryVerbose); TempDirectoryGuard tempDirGuard; bsl::string fileName(tempDirGuard.getTempDirName()); bdls::PathUtil::appendRaw(&fileName, "testLog"); Obj mX; const Obj& X = mX; RotCb cb(&ta); mX.setOnFileRotationCallback(cb); ASSERT(0 == cb.numInvocations()); ASSERT(0 == mX.enableFileLogging(fileName.c_str(), true)); mX.rotateOnSize(1); ASSERT(true == X.isFileLoggingEnabled()); char buffer[1025]; // rotateOnSize is specified in multiples of 1K bsl::memset(buffer, 'x', sizeof(buffer)); buffer[sizeof(buffer) - 1] = 0; publishRecord(&mX, buffer); for (int i = 0; i < 3; ++i) { // A sleep is required because timestamp resolution is 1 second bslmt::ThreadUtil::microSleep(0, 1); // 1s publishRecord(&mX, buffer); ASSERTV(i, cb.numInvocations(), 1 == cb.numInvocations()); ASSERTV(i, cb.numInvocations(), 0 == cb.status()); if (veryVeryVerbose) { P(cb.rotatedFileName()); } cb.reset(); } mX.disableSizeRotation(); // Set to rotate every second mX.rotateOnTimeInterval(bdlt::DatetimeInterval(0, 0, 0, 1)); buffer[1] = 0; // Don't need to write much for time-based rotation for (int i = 0; i < 3; ++i) { bslmt::ThreadUtil::microSleep(250000, 1); // 1.25s publishRecord(&mX, buffer); ASSERTV(i, cb.numInvocations(), 1 == cb.numInvocations()); ASSERTV(i, cb.numInvocations(), 0 == cb.status()); if (veryVeryVerbose) { P(cb.rotatedFileName()); } cb.reset(); } } if (veryVerbose) cout << "\tTest a re-entrant rotation" << endl; { bslma::TestAllocator ta("test", veryVeryVeryVerbose); Obj mX(&ta); ReentrantRotationCallback cb(&mX); mX.setOnFileRotationCallback(cb); mX.forceRotation(); // The test is whether this call will lock // the task. } } break; case 4: { // -------------------------------------------------------------------- // TESTING ROTATED FILENAME // // Concerns: //: 1 A timestamp is appended to the filename if the rotated file has //: the same name as the current log file. //: //: 2 The callback function is correctly supplied with the name of the //: rotated file. //: //: 3 The user specified '%p'-escape sequence expands to the to the //: process id (in decimal format) in the rotated file name. //: //: 4 The user specified escape sequences for time stamp (%Y, %M, %D, //: %h, %m, s, %T) are expanded to their corresponding time element //: (year, month, day, hour, minute, second, complete-timestamp, //: respectively) //: //: 5 That the time stamp elements of the file name are appended in //: localtime if 'isPublishInLocalTime' is 'true' and in UTC //: otherwise. //: // Plans: //: 1 Setup the test infrastructure, including a callback. //: //: 2 Create a table of patterns and the expected names. //: //: 3 For each row in the table: //: 1 Enable file logging and ensure the time before and after call //: to 'enableFileLogging' is within the same second. If not, //: disable and re-enable file logging again until we can get the //: log file timestamp with certainty. //: //: 2 Verify the correct log is created //: //: 3 Perform a force rotation and verify the rotated log has the //: correct filename. //: //: 4 Use 'enablePublishInLocalTime' and 'disablePublishInLocalTime' //: to configure the time stamp on the generated log file. Enable //: file logging and verify the generated file name has a time stamp //: in local-time or UTC, respectively. // // Testing: // CONCERN: ROTATED LOG FILENAMES ARE AS EXPECTED // -------------------------------------------------------------------- if (verbose) cout << "\nTESTING ROTATED FILENAME" << "\n========================" << endl; if (veryVerbose) cout << "Test infrastructure setup." << endl; const int processId = bdls::ProcessUtil::getProcessId(); if (veryVeryVerbose) { P(processId) } // This configuration guarantees that the logger manager will publish // all messages regardless of their severity and the observer will see // each message only once. ball::LoggerManagerConfiguration configuration; ASSERT(0 == configuration.setDefaultThresholdLevelsIfValid( ball::Severity::e_OFF, ball::Severity::e_TRACE, ball::Severity::e_OFF, ball::Severity::e_OFF)); ball::LoggerManagerScopedGuard guard(configuration); ball::LoggerManager& manager = ball::LoggerManager::singleton(); BALL_LOG_SET_CATEGORY("TestCategory"); bslma::TestAllocator ta("ta", veryVeryVeryVerbose); bsl::shared_ptr mX(new (ta) Obj(&ta), &ta); bsl::shared_ptr X = mX; ASSERT(0 == manager.registerObserver(mX, "testObserver")); RotCb cb(&ta); mX->setOnFileRotationCallback(cb); mX->enablePublishInLocalTime(); if (verbose) cout << "Test table of file names" << endl; { static const struct { int d_line; const char *d_suffix; const char *d_expectedPattern; bool d_uniqueNameFlag; } DATA[] = { //LINE SUFFIX PATTERN UNIQUE //---- ----------------- ------------- ------ { L_, "", "", false }, { L_, "%Y", "Y", false }, { L_, "%Y%M%D", "YMD", false }, { L_, "%p-%Y", "p-Y", false }, { L_, "%p%Y%p%M%p%D%p", "pYpMpDp", false }, { L_, ".%p.%T.%p", ".p.YMD_hms.p", true }, { L_, ".%T", ".YMD_hms", true }, }; enum { NUM_DATA = sizeof DATA / sizeof *DATA }; for (int ti = 0; ti < NUM_DATA; ++ti) { const int LINE = DATA[ti].d_line; const char *SUF = DATA[ti].d_suffix; const char *PAT = DATA[ti].d_expectedPattern; const bool UNI = DATA[ti].d_uniqueNameFlag; if (veryVeryVerbose) { P_(LINE) P_(SUF) P_(PAT) P(UNI) } TempDirectoryGuard tempDirGuard; bsl::string fileName(tempDirGuard.getTempDirName()); bdls::PathUtil::appendRaw(&fileName, "testLog"); bdlt::Datetime startDatetime, endDatetime; // loop until startDatetime is equal to endDatetime do { startDatetime = getCurrentLocalTime(); enableFileLogging(mX, fileName + SUF); endDatetime = getCurrentLocalTime(); if (startDatetime.date() != endDatetime.date() || startDatetime.hour() != endDatetime.hour() || startDatetime.minute() != endDatetime.minute() || startDatetime.second() != endDatetime.second()) { // not sure the exact time when the log file was // opened because startDatetime and endDatetime are // different; will try it again bsl::string fn; ASSERT(true == mX->isFileLoggingEnabled(&fn)); mX->disableFileLogging(); ASSERT(0 == FsUtil::remove(fn.c_str())); } } while (!X->isFileLoggingEnabled()); ASSERTV(LINE, startDatetime.year() == endDatetime.year()); ASSERTV(LINE, startDatetime.month() == endDatetime.month()); ASSERTV(LINE, startDatetime.day() == endDatetime.day()); ASSERTV(LINE, startDatetime.hour() == endDatetime.hour()); ASSERTV(LINE, startDatetime.minute() == endDatetime.minute()); ASSERTV(LINE, startDatetime.second() == endDatetime.second()); BALL_LOG_INFO << "log"; // now construct the name of the log file from startDatetime bsl::ostringstream oss; oss << fileName; for (const char *c = PAT; *c != '\0'; ++c) { switch (*c) { case 'Y': { oss << bsl::setw(4) << bsl::setfill('0') << startDatetime.year(); } break; case 'M': { oss << bsl::setw(2) << bsl::setfill('0') << startDatetime.month(); } break; case 'D': { oss << bsl::setw(2) << bsl::setfill('0') << startDatetime.day(); } break; case 'h': { oss << bsl::setw(2) << bsl::setfill('0') << startDatetime.hour(); } break; case 'm': { oss << bsl::setw(2) << bsl::setfill('0') << startDatetime.minute(); } break; case 's': { oss << bsl::setw(2) << bsl::setfill('0') << startDatetime.second(); } break; case 'p': { oss << processId; } break; default: { oss << *c; } break; } } const bsl::string actualFileName(oss.str()); if (veryVeryVerbose) { P(actualFileName) } ASSERTV(LINE, actualFileName, 1 == FsUtil::exists(actualFileName)); bslmt::ThreadUtil::microSleep(0, 1); mX->forceRotation(); mX->disableFileLogging(); ASSERTV(LINE, actualFileName, 1 == FsUtil::exists(actualFileName)); bsl::string rotatedFileName(actualFileName); if (!UNI) { oss << '.'; oss << bsl::setw(4) << bsl::setfill('0') << startDatetime.year(); oss << bsl::setw(2) << bsl::setfill('0') << startDatetime.month(); oss << bsl::setw(2) << bsl::setfill('0') << startDatetime.day(); oss << '_'; oss << bsl::setw(2) << bsl::setfill('0') << startDatetime.hour(); oss << bsl::setw(2) << bsl::setfill('0') << startDatetime.minute(); oss << bsl::setw(2) << bsl::setfill('0') << startDatetime.second(); rotatedFileName = oss.str(); if (veryVeryVerbose) { P(rotatedFileName) } ASSERTV(LINE, rotatedFileName, 1 == FsUtil::exists(rotatedFileName)); ASSERTV(LINE, 2 == getNumLines(rotatedFileName.c_str())); } if (veryVeryVerbose) { P(rotatedFileName) } ASSERTV(ti, cb.numInvocations(), 1 == cb.numInvocations()); ASSERTV(ti, cb.status(), 0 == cb.status()); ASSERTV(ti, cb.rotatedFileName(), rotatedFileName == cb.rotatedFileName()); cb.reset(); } } if (verbose) cout << "Testing filename time-stamp uses " << "'isPublishInLocalTimeEnabled'" << endl; { TempDirectoryGuard tempDirGuard; if (veryVerbose) cout << "\tTesting utc pattern in filename." << endl; { // Testing UTC timestamp in filename. bsl::string fileName(tempDirGuard.getTempDirName()); bdls::PathUtil::appendRaw(&fileName, "utc_%T"); bdlt::Datetime start = bdlt::CurrentTime::utc(); mX->disablePublishInLocalTime(); enableFileLogging(mX, fileName); BALL_LOG_INFO << "log"; bdlt::Datetime end = bdlt::CurrentTime::utc(); bsl::string actualFileName; ASSERT(true == X->isFileLoggingEnabled(&actualFileName)); mX->disableFileLogging(); // Actual file name suffix should follow the pattern // YYYYMMDD_hhmmss and should be UTC time. size_t pos = actualFileName.find("utc_") + 4; bsl::string year(actualFileName.substr( pos + 0, 4)); bsl::string month(actualFileName.substr( pos + 4, 2)); bsl::string day(actualFileName.substr( pos + 6, 2)); bsl::string hour(actualFileName.substr( pos + 9, 2)); bsl::string minute(actualFileName.substr(pos + 11, 2)); bsl::string second(actualFileName.substr(pos + 13, 2)); bdlt::Datetime timestamp(bsl::atoi(year.c_str()), bsl::atoi(month.c_str()), bsl::atoi(day.c_str()), bsl::atoi(hour.c_str()), bsl::atoi(minute.c_str()), bsl::atoi(second.c_str())); if (veryVerbose) { P(actualFileName); P_(year); P_(month); P_(day); P_(hour); P_(minute); P(second); } start.setMillisecond(0); start.setMicrosecond(0); ASSERTV(timestamp, start, end, start <= timestamp && timestamp <= end); } { // Testing local timestamp in filename. bsl::string fileName(tempDirGuard.getTempDirName()); bdls::PathUtil::appendRaw(&fileName, "local_%T"); bdlt::Datetime start = bdlt::CurrentTime::local(); mX->enablePublishInLocalTime(); enableFileLogging(mX, fileName); BALL_LOG_INFO << "log"; bdlt::Datetime end = bdlt::CurrentTime::local(); bsl::string actualFileName; ASSERT(true == X->isFileLoggingEnabled(&actualFileName)); mX->disableFileLogging(); // Verify the time stamp in the filename. size_t pos = actualFileName.find("local_") + 6; bsl::string year(actualFileName.substr( pos + 0, 4)); bsl::string month(actualFileName.substr( pos + 4, 2)); bsl::string day(actualFileName.substr( pos + 6, 2)); bsl::string hour(actualFileName.substr( pos + 9, 2)); bsl::string minute(actualFileName.substr(pos + 11, 2)); bsl::string second(actualFileName.substr(pos + 13, 2)); bdlt::Datetime timestamp(bsl::atoi(year.c_str()), bsl::atoi(month.c_str()), bsl::atoi(day.c_str()), bsl::atoi(hour.c_str()), bsl::atoi(minute.c_str()), bsl::atoi(second.c_str())); if (veryVerbose) { P(actualFileName); P_(year); P_(month); P_(day); P_(hour); P_(minute); P(second); } start.setMillisecond(0); start.setMicrosecond(0); ASSERTV(timestamp, start, end, start <= timestamp && timestamp <= end); } // Deregister here as we used local allocator for the observer. ASSERT(0 == manager.deregisterObserver("testObserver")); } } break; case 3: { // -------------------------------------------------------------------- // TESTING LOGGING TO A FAILING STREAM // // Concerns: //: 1 An error message is written to stderr when the stream fails. // // Plan: //: 1 Set the OS to limit the total size of any file we write to a //: fairly small amount, then use BALL to write more than that. //: While doing this, capture the stderr output and verify a message //: has been written. // // Testing: // CONCERN: LOGGING TO A FAILING STREAM // -------------------------------------------------------------------- if (verbose) cerr << "\nTESTING LOGGING TO A FAILING STREAM." << "\n====================================" << endl; #if defined(BSLS_PLATFORM_OS_UNIX) && !defined(BSLS_PLATFORM_OS_CYGWIN) // 'setrlimit' is not implemented on Cygwin. // Publish synchronously all messages regardless of their severity. // This configuration also guarantees that the observer will only see // each message only once. ball::LoggerManagerConfiguration configuration; ASSERT(0 == configuration.setDefaultThresholdLevelsIfValid( ball::Severity::e_OFF, ball::Severity::e_TRACE, ball::Severity::e_OFF, ball::Severity::e_OFF)); ball::LoggerManagerScopedGuard guard(configuration); ball::LoggerManager& manager = ball::LoggerManager::singleton(); BALL_LOG_SET_CATEGORY("TestCategory"); if (verbose) cout << "Testing output when the stream fails" << " (UNIX only)." << endl; { bslma::TestAllocator ta("ta", veryVeryVeryVerbose); TempDirectoryGuard tempDirGuard; bsl::string fileName(tempDirGuard.getTempDirName()); bdls::PathUtil::appendRaw(&fileName, "testLog"); // Set the limit of the file size we can produce to 2048 bytes. struct rlimit rlim; ASSERT(0 == getrlimit(RLIMIT_FSIZE, &rlim)); rlim.rlim_cur = 2048; ASSERT(0 == setrlimit(RLIMIT_FSIZE, &rlim)); // I think this sets it so we won't trap when we get the file size // limit exception. struct sigaction act,oact; act.sa_handler = SIG_IGN; sigemptyset(&act.sa_mask); act.sa_flags = 0; ASSERT(0 == sigaction(SIGXFSZ, &act, &oact)); bsl::shared_ptr mX(new (ta) Obj(&ta), &ta); bsl::shared_ptr X = mX; ASSERT(0 == manager.registerObserver(mX, "testObserver")); bsl::stringstream os; // we want to capture the error message that will be written to // stderr (not cerr). Redirect stderr to a file. We can't // redirect it back; we'll have to use 'ASSERT2' (which outputs to // cout, not cerr) from now on and report a summary to cout at the // end of this case. bsl::string stderrFileName(tempDirGuard.getTempDirName()); bdls::PathUtil::appendRaw(&stderrFileName, "stderrLog"); ASSERT(stderr == freopen(stderrFileName.c_str(), "w", stderr)); enableFileLogging(mX, fileName, true); for (int i = 0; i < 40; ++i) { BALL_LOG_TRACE << "log"; } fflush(stderr); bsl::fstream stderrFs; stderrFs.open(stderrFileName.c_str(), bsl::ios_base::in); bsl::string line; ASSERT2(getline(stderrFs, line)); // caught an error message const bool fail = (bsl::string::npos == line.find("Error on file stream")); ASSERT(!fail); if (fail) cout << "line: " << line << endl; #ifndef BSLS_PLATFORM_CMP_IBM // On native IBM, after the error, even when the stream fails, // logging will be attempted over and over again, which results in // more than one error messages. ASSERT2(!getline(stderrFs, line)); // and only one message #endif mX->disableFileLogging(); // Deregister here as we used local allocator for the observer. ASSERT(0 == manager.deregisterObserver("testObserver")); } #else if (verbose) { cout << "Skipping case 4 on Windows and Cygwin..." << endl; } #endif } break; case 2: { // -------------------------------------------------------------------- // TESTING ROTATION METHODS // // Concerns: //: 1 'rotateOnSize' triggers a rotation when expected. //: //: 2 'disableSizeRotation' disables rotation on size. //: //: 3 'forceRotation' triggers a rotation. //: //: 4 'rotateOnLifetime' triggers a rotation when expected. //: //: 5 'disableLifetimeRotation' disables rotation on lifetime. // // Plan: //: 1 We will exercise both rotation rules to verify that they work //: properly using glob to count the files and proper timing. We //: will also verify that the size rule is followed by checking the //: size of log files. // // Testing: // void disableLifetimeRotation(); // void disableSizeRotation(); // void forceRotation(); // void rotateOnSize(int size); // void rotateOnLifetime(DatetimeInterval& interval); // DatetimeInterval rotationLifetime() const; // int rotationSize() const; // -------------------------------------------------------------------- if (verbose) cout << "\nTESTING ROTATION METHODS" << "\n========================" << endl; // This configuration guarantees that the logger manager will publish // all messages regardless of their severity and the observer will see // each message only once. ball::LoggerManagerConfiguration configuration; ASSERT(0 == configuration.setDefaultThresholdLevelsIfValid( ball::Severity::e_OFF, ball::Severity::e_TRACE, ball::Severity::e_OFF, ball::Severity::e_OFF)); ball::LoggerManagerScopedGuard guard(configuration); ball::LoggerManager& manager = ball::LoggerManager::singleton(); BALL_LOG_SET_CATEGORY("TestCategory"); #ifdef BSLS_PLATFORM_OS_UNIX bslma::TestAllocator ta("ta", veryVeryVeryVerbose); if (verbose) cout << "Test-case infrastructure setup." << endl; { TempDirectoryGuard tempDirGuard; bsl::string fileName(tempDirGuard.getTempDirName()); bdls::PathUtil::appendRaw(&fileName, "testLog"); bsl::shared_ptr mX(new (ta) Obj(&ta), &ta); bsl::shared_ptr X = mX; ASSERT(0 == manager.registerObserver(mX, "testObserver")); if (verbose) cout << "Testing setup." << endl; { enableFileLogging(mX, fileName, true); BALL_LOG_TRACE << "log 1"; glob_t globbuf; ASSERT(0 == glob((fileName + ".2*").c_str(), 0, 0, &globbuf)); ASSERT(1 == globbuf.gl_pathc); bsl::ifstream fs; fs.open(globbuf.gl_pathv[0], bsl::ifstream::in); globfree(&globbuf); ASSERT(fs.is_open()); int linesNum = 0; bsl::string line; while (getline(fs, line)) { ++linesNum; } fs.close(); ASSERT(2 == linesNum); ASSERT(true == X->isFileLoggingEnabled()); } if (verbose) cout << "Testing lifetime-constrained rotation." << endl; { ASSERT(bdlt::DatetimeInterval(0) == X->rotationLifetime()); mX->rotateOnLifetime(bdlt::DatetimeInterval(0,0,0,3)); ASSERT(bdlt::DatetimeInterval(0,0,0,3) == X->rotationLifetime()); bslmt::ThreadUtil::microSleep(0, 4); BALL_LOG_TRACE << "log 1"; BALL_LOG_DEBUG << "log 2"; // Check that a rotation occurred. glob_t globbuf; ASSERT(0 == glob((fileName + ".2*").c_str(), 0, 0, &globbuf)); ASSERT(2 == globbuf.gl_pathc); // Check the number of lines in the file. bsl::ifstream fs; fs.open(globbuf.gl_pathv[1], bsl::ifstream::in); fs.clear(); globfree(&globbuf); ASSERT(fs.is_open()); int linesNum = 0; bsl::string line(&ta); while (getline(fs, line)) { ++linesNum; } fs.close(); ASSERT(4 == linesNum); mX->disableLifetimeRotation(); bslmt::ThreadUtil::microSleep(0, 4); BALL_LOG_FATAL << "log 3"; // Check that no rotation occurred. ASSERT(0 == glob((fileName + ".2*").c_str(), 0, 0, &globbuf)); ASSERT(2 == globbuf.gl_pathc); fs.open(globbuf.gl_pathv[1], bsl::ifstream::in); fs.clear(); globfree(&globbuf); ASSERT(fs.is_open()); linesNum = 0; while (getline(fs, line)) { ++linesNum; } fs.close(); ASSERT(6 == linesNum); } if (verbose) cout << "Testing forced rotation." << endl; { bslmt::ThreadUtil::microSleep(0, 2); mX->forceRotation(); BALL_LOG_TRACE << "log 1"; BALL_LOG_DEBUG << "log 2"; BALL_LOG_INFO << "log 3"; BALL_LOG_WARN << "log 4"; // Check that the rotation occurred. glob_t globbuf; ASSERT(0 == glob((fileName + ".2*").c_str(), 0, 0, &globbuf)); ASSERT(3 == globbuf.gl_pathc); bsl::ifstream fs; fs.open(globbuf.gl_pathv[2], bsl::ifstream::in); fs.clear(); globfree(&globbuf); ASSERT(fs.is_open()); int linesNum = 0; bsl::string line(&ta); while (getline(fs, line)) { ++linesNum; } fs.close(); ASSERT(8 == linesNum); } if (verbose) cout << "Testing size-constrained rotation." << endl; { bslmt::ThreadUtil::microSleep(0, 2); ASSERT(0 == X->rotationSize()); mX->rotateOnSize(1); ASSERT(1 == X->rotationSize()); for (int i = 0; i < 15; ++i) { BALL_LOG_TRACE << "log"; // We sleep because otherwise, the loop is too fast to make // the timestamp change so we cannot observe the rotation. bslmt::ThreadUtil::microSleep(200 * 1000); } glob_t globbuf; ASSERT(0 == glob((fileName + ".2*").c_str(), 0, 0, &globbuf)); ASSERT(4 <= globbuf.gl_pathc); // We are not checking the last one since we do not have any // information on its size. for (int i = 0; i < (int)globbuf.gl_pathc - 3; ++i) { ASSERT(1024 < FsUtil::getFileSize(globbuf.gl_pathv[i + 2])); } size_t oldNumFiles = globbuf.gl_pathc; globfree(&globbuf); ASSERT(1 == X->rotationSize()); mX->disableSizeRotation(); ASSERT(0 == X->rotationSize()); for (int i = 0; i < 15; ++i) { BALL_LOG_TRACE << "log"; bslmt::ThreadUtil::microSleep(50 * 1000); } // Verify that no rotation occurred. ASSERT(0 == glob((fileName + ".2*").c_str(), 0, 0, &globbuf)); ASSERT(oldNumFiles == globbuf.gl_pathc); globfree(&globbuf); } mX->disableFileLogging(); // Deregister here as we used local allocator for the observer. ASSERT(0 == manager.deregisterObserver("testObserver")); } // Test with no timestamp. if (verbose) cout << "Test-case infrastructure setup." << endl; { // Create a temporary directory for log files. TempDirectoryGuard tempDirGuard; bsl::string fileName(tempDirGuard.getTempDirName()); bdls::PathUtil::appendRaw(&fileName, "testLog"); bsl::shared_ptr mX(new (ta) Obj(&ta), &ta); bsl::shared_ptr X = mX; ASSERT(0 == manager.registerObserver(mX, "testObserver")); if (verbose) cout << "Testing setup." << endl; { enableFileLogging(mX, fileName); BALL_LOG_TRACE << "log 1"; glob_t globbuf; ASSERT(0 == glob((fileName + "*").c_str(), 0, 0, &globbuf)); ASSERT(1 == globbuf.gl_pathc); bsl::ifstream fs; fs.open(globbuf.gl_pathv[0], bsl::ifstream::in); globfree(&globbuf); ASSERT(fs.is_open()); int linesNum = 0; bsl::string line; while (getline(fs, line)) { ++linesNum; } fs.close(); ASSERT(2 == linesNum); ASSERT(true == X->isFileLoggingEnabled()); } if (verbose) cout << "Testing lifetime-constrained rotation." << endl; { ASSERT(bdlt::DatetimeInterval(0) == X->rotationLifetime()); mX->rotateOnLifetime(bdlt::DatetimeInterval(0,0,0,3)); ASSERT(bdlt::DatetimeInterval(0,0,0,3) == X->rotationLifetime()); bslmt::ThreadUtil::microSleep(0, 4); BALL_LOG_TRACE << "log 1"; BALL_LOG_DEBUG << "log 2"; // Check that a rotation occurred. glob_t globbuf; ASSERT(0 == glob((fileName + "*").c_str(), 0, 0, &globbuf)); ASSERT(2 == globbuf.gl_pathc); // Check the number of lines in the file. bsl::ifstream fs; fs.open(globbuf.gl_pathv[0], bsl::ifstream::in); fs.clear(); globfree(&globbuf); ASSERT(fs.is_open()); int linesNum = 0; bsl::string line(&ta); while (getline(fs, line)) { ++linesNum; } fs.close(); ASSERT(4 == linesNum); mX->disableLifetimeRotation(); bslmt::ThreadUtil::microSleep(0, 4); BALL_LOG_FATAL << "log 3"; // Check that no rotation occurred. ASSERT(0 == glob((fileName + "*").c_str(), 0, 0, &globbuf)); ASSERT(2 == globbuf.gl_pathc); fs.open(globbuf.gl_pathv[0], bsl::ifstream::in); fs.clear(); globfree(&globbuf); ASSERT(fs.is_open()); linesNum = 0; while (getline(fs, line)) { ++linesNum; } fs.close(); ASSERT(6 == linesNum); } mX->disableFileLogging(); // Deregister here as we used local allocator for the observer. ASSERT(0 == manager.deregisterObserver("testObserver")); } #endif } break; case 1: { // -------------------------------------------------------------------- // TESTING THRESHOLDS AND OUTPUT FORMATS // // Concerns: //: 1 'publish' logs in the default format. //: //: 2 'publish' publishes all messages to a file if file logging is //: enabled. //: //: 3 The name of the log file should be in accordance with what is //: defined by the pattern if file logging is enabled by a pattern. //: //: 4 'setLogFileFunctor' can change the format effectively. // // Plan: //: 1 We will set up the observer and check if logged messages are in //: the expected format and contain the expected data by comparing //: the output of this observer with 'ball::StreamObserver', that we //: slightly modify. Then, we will use different manipulators and //: functors to affect output format and verify that it has changed //: where expected. // // Testing: // FileObserver(ball::Severity::Level, bslma::Allocator); // ~FileObserver(); // void disableFileLogging(); // int enableFileLogging(const char *fileName); // int enableFileLogging(const char *fileName, bool timestampFlag); // void publish(const Record& record, const Context& context); // void publish(const shared_ptr&, const Context&); // void disablePublishInLocalTime(); // void enablePublishInLocalTime(); // void setLogFileFunctor(const logRecordFunctor& logFileFunctor); // DatetimeInterval localTimeOffset(); // bool isFileLoggingEnabled() const; // bool isFileLoggingEnabled(bsl::string *result) const; // bool isPublishInLocalTimeEnabled() const; // -------------------------------------------------------------------- if (verbose) cout << "\nTESTING THRESHOLDS AND OUTPUT FORMATS" "\n=====================================" << endl; // This configuration guarantees that the logger manager will publish // all messages regardless of their severity and the observer will see // each message only once. ball::LoggerManagerConfiguration configuration; ASSERT(0 == configuration.setDefaultThresholdLevelsIfValid( ball::Severity::e_OFF, ball::Severity::e_TRACE, ball::Severity::e_OFF, ball::Severity::e_OFF)); ball::LoggerManagerScopedGuard guard(configuration); ball::LoggerManager& manager = ball::LoggerManager::singleton(); BALL_LOG_SET_CATEGORY("TestCategory"); // TBD fix this for Windows !!! #ifndef BSLS_PLATFORM_OS_WINDOWS #if (!defined(BSLS_PLATFORM_OS_SOLARIS) || BSLS_PLATFORM_OS_VER_MAJOR >= 10)\ && !defined(BSLS_PLATFORM_OS_AIX) // For the localtime to be picked to avoid the all.pl env to pollute // us. unsetenv("TZ"); #endif bslma::TestAllocator ta("ta", veryVeryVeryVerbose); { if (verbose) cout << "Testing default output format." << endl; { TempDirectoryGuard tempDirGuard; bsl::string fileName(tempDirGuard.getTempDirName()); bdls::PathUtil::appendRaw(&fileName, "testLog"); bsl::shared_ptr mX(new (ta) Obj(&ta), &ta); bsl::shared_ptr X = mX; bsl::ostringstream dos; time_t currentTime = time(0); struct tm localtm, gmtm; #ifdef BSLS_PLATFORM_OS_WINDOWS localtm = *localtime(¤tTime); gmtm = *gmtime(¤tTime); #else localtime_r(¤tTime, &localtm); gmtime_r(¤tTime, &gmtm); #endif bdlt::Datetime currentLocalTime, currentUTCTime; bdlt::DatetimeUtil::convertFromTm(¤tLocalTime, localtm); bdlt::DatetimeUtil::convertFromTm(¤tUTCTime, gmtm); ASSERT(currentLocalTime - currentUTCTime == X->localTimeOffset()); bsl::shared_ptr refX(new (ta) ball::StreamObserver(&dos), &ta); ASSERT(0 == manager.registerObserver(mX, "testObserver")); ASSERT(0 == manager.registerObserver(refX, "refObserver")); enableFileLogging(mX, fileName, true); BALL_LOG_WARN << "log WARN"; bsl::string os; ASSERT(2 == readFileIntoString(__LINE__, fileName, os)); // Replace the spaces after pid, __FILE__ { bsl::string temp = dos.str(); temp[temp.find(__FILE__) + sizeof(__FILE__) - 1] = ':'; replaceSecondSpace(&temp, ':'); dos.str(temp); } ASSERT(dos.str() == os); mX->disableFileLogging(); // Deregister here as we used local allocator for the observer. ASSERT(0 == manager.deregisterObserver("testObserver")); ASSERT(0 == manager.deregisterObserver("refObserver")); } if (verbose) cout << "Testing format with local time offset." << endl; { TempDirectoryGuard tempDirGuard; bsl::string fileName(tempDirGuard.getTempDirName()); bdls::PathUtil::appendRaw(&fileName, "testLog"); bsl::shared_ptr mX(new (ta) Obj(&ta), &ta); bsl::shared_ptr X = mX; ASSERT(false == X->isPublishInLocalTimeEnabled()); mX->enablePublishInLocalTime(); ASSERT(true == X->isPublishInLocalTimeEnabled()); mX->disablePublishInLocalTime(); ASSERT(false == X->isPublishInLocalTimeEnabled()); mX->enablePublishInLocalTime(); ASSERT(true == X->isPublishInLocalTimeEnabled()); bsl::ostringstream testOs, dos; bsl::shared_ptr refX(new (ta) ball::StreamObserver(&dos), &ta); ASSERT(0 == manager.registerObserver(mX, "testObserver")); ASSERT(0 == manager.registerObserver(refX, "refObserver")); enableFileLogging(mX, fileName, true); BALL_LOG_FATAL << "log FATAL"; bsl::string os; ASSERT(2 == readFileIntoString(__LINE__, fileName, os)); testOs << "\nFATAL " << __FILE__ << ":" << __LINE__ - 1 << " ball::FileObserverTest log FATAL " << "\n"; // Replace the spaces after pid, __FILE__ { bsl::string temp = dos.str(); temp[temp.find(__FILE__) + sizeof(__FILE__) - 1] = ':'; replaceSecondSpace(&temp, ':'); dos.str(temp); } ASSERTV(dos.str(), os, dos.str() != os); ASSERT(testOs.str() != os); // Now let's verify the actual difference. int defaultObsHour = 0; if (dos.str().length() >= 11) { bsl::istringstream is(dos.str().substr(11, 2)); ASSERT(is >> defaultObsHour); } else { ASSERT(0 && "can't substr(11,2), string too short"); } int fileObsHour = 0; if (dos.str().length() >= 11) { bsl::istringstream is(os.substr(11, 2)); ASSERT(is >> fileObsHour); } else { ASSERT(0 && "can't substr(11,2), string too short"); } #ifdef BSLS_PLATFORM_OS_UNIX tzset(); time_t currentTime; struct tm *ts; ::time(¤tTime); ts = ::localtime(¤tTime); #ifdef BSLS_PLATFORM_OS_FREEBSD // This is the BSD way. I am not sure of this accounts for DST // or not. The following if might need to be moved into the // #else long difference = -ts->tm_gmtoff / 3600; #else long difference = timezone / 3600; #endif if (ts->tm_isdst > 0) { --difference; } #else _tzset(); long difference = _timezone / 3600; #endif ASSERTV((fileObsHour + difference + 24) % 24, defaultObsHour, (fileObsHour + difference + 24) % 24 == defaultObsHour); { bsl::string temp = dos.str(); temp[11] = os[11]; temp[12] = os[12]; dos.str(temp); } if (defaultObsHour - difference >= 0 && defaultObsHour - difference < 24) { // UTC and local time are on the same day ASSERT(dos.str() == os); } else if (dos.str().length() >= 10 && os.length() >= 10) { // UTC and local time are on different days. Ignore date. ASSERT(dos.str().substr(10) == os.substr(10)); } else { ASSERT(0 && "can't substr(10), string too short"); } mX->disableFileLogging(); // Deregister here as we used local allocator for the observer. ASSERT(0 == manager.deregisterObserver("testObserver")); ASSERT(0 == manager.deregisterObserver("refObserver")); } if (verbose) cout << "Testing file logging." << endl; { TempDirectoryGuard tempDirGuard; bsl::string fileName(tempDirGuard.getTempDirName()); bdls::PathUtil::appendRaw(&fileName, "testLog"); bsl::shared_ptr mX(new (ta) Obj(&ta), &ta); bsl::shared_ptr X = mX; ASSERT(-1 == mX->enableFileLogging("/bogus/path/foo")); ASSERT(0 == manager.registerObserver(mX, "testObserver")); enableFileLogging(mX, fileName); BALL_LOG_TRACE << "log 1"; BALL_LOG_DEBUG << "log 2"; BALL_LOG_INFO << "log 3"; BALL_LOG_WARN << "log 4"; BALL_LOG_ERROR << "log 5"; BALL_LOG_FATAL << "log 6"; bsl::string os; ASSERT(12 == readFileIntoString(__LINE__, fileName, os)); ASSERT(true == X->isFileLoggingEnabled()); mX->disableFileLogging(); ASSERT(false == X->isFileLoggingEnabled()); BALL_LOG_TRACE << "log 1"; BALL_LOG_DEBUG << "log 2"; BALL_LOG_INFO << "log 3"; BALL_LOG_WARN << "log 4"; BALL_LOG_ERROR << "log 5"; BALL_LOG_FATAL << "log 6"; ASSERT(12 == readFileIntoString(__LINE__, fileName, os)); enableFileLogging(mX, fileName); BALL_LOG_TRACE << "log 7"; BALL_LOG_DEBUG << "log 8"; BALL_LOG_INFO << "log 9"; BALL_LOG_WARN << "log 1"; BALL_LOG_ERROR << "log 2"; BALL_LOG_FATAL << "log 3"; ASSERT(24 == readFileIntoString(__LINE__, fileName, os)); mX->disableFileLogging(); // Deregister here as we used local allocator for the observer. ASSERT(0 == manager.deregisterObserver("testObserver")); } #ifdef BSLS_PLATFORM_OS_UNIX if (verbose) cout << "Testing file logging with timestamp." << endl; { TempDirectoryGuard tempDirGuard; bsl::string fileName(tempDirGuard.getTempDirName()); bdls::PathUtil::appendRaw(&fileName, "testLog"); bsl::shared_ptr mX(new (ta) Obj(&ta), &ta); bsl::shared_ptr X = mX; ASSERT(0 == manager.registerObserver(mX, "testObserver")); enableFileLogging(mX, fileName, true); BALL_LOG_TRACE << "log 1"; BALL_LOG_DEBUG << "log 2"; BALL_LOG_INFO << "log 3"; BALL_LOG_WARN << "log 4"; BALL_LOG_ERROR << "log 5"; BALL_LOG_FATAL << "log 6"; bsl::string os; ASSERT(12 == readFileIntoString(__LINE__, fileName, os)); mX->disableFileLogging(); // Deregister here as we used local allocator for the observer. ASSERT(0 == manager.deregisterObserver("testObserver")); } if (verbose) cout << "Testing '%%' in file name pattern." << endl; { static const struct { int d_lineNum; // source line number const char *d_patternSuffix_p; // pattern suffix const char *d_fileNameSuffix_p; // filename suffix } DATA[] = { //line pattern suffix filename suffix //---- -------------- --------------- { L_, "foo", "foo" }, { L_, "foo%", "foo%" }, { L_, "foo%bar", "foo%bar" }, { L_, "foo%%", "foo" }, { L_, "foo%%bar", "foobar" }, { L_, "foo%%%", "foo%" }, { L_, "foo%%%bar", "foo%bar" }, }; const int NUM_DATA = sizeof DATA / sizeof *DATA; for (int ti = 0; ti < NUM_DATA; ++ti) { const int LINE = DATA[ti].d_lineNum; const char *PATTERN = DATA[ti].d_patternSuffix_p; const char *FILENAME = DATA[ti].d_fileNameSuffix_p; TempDirectoryGuard tempDirGuard; bsl::string baseName(tempDirGuard.getTempDirName()); bdls::PathUtil::appendRaw(&baseName, "testLog"); bsl::string pattern(baseName + PATTERN); bsl::string expected(baseName + FILENAME); Obj mX(&ta); const Obj& X = mX; ASSERT(0 == mX.enableFileLogging(pattern.c_str())); bsl::string actual; ASSERTV(LINE, true == X.isFileLoggingEnabled(&actual)); if (veryVeryVerbose) { P_(PATTERN); P_(expected); P(actual); } ASSERTV(LINE, expected == actual); mX.disableFileLogging(); // look for the file with the expected name glob_t globbuf; ASSERTV(LINE, 0 == glob(expected.c_str(), 0, 0, &globbuf)); ASSERTV(LINE, 1 == globbuf.gl_pathc); globfree(&globbuf); } } if (verbose) cout << "Testing functors with the same format." << endl; { TempDirectoryGuard tempDirGuard; bsl::string baseName(tempDirGuard.getTempDirName()); bdls::PathUtil::appendRaw(&baseName, "testLog"); // Create observers. bsl::shared_ptr mX1(new (ta) Obj(&ta), &ta); bsl::shared_ptr X1 = mX1; bsl::shared_ptr mX2(new (ta) Obj(&ta), &ta); bsl::shared_ptr X2 = mX2; bsl::shared_ptr mX3(new (ta) Obj(&ta), &ta); bsl::shared_ptr X3 = mX3; // Register with logger manager. ASSERT(0 == manager.registerObserver(mX1, "testObserver1")); ASSERT(0 == manager.registerObserver(mX2, "testObserver2")); ASSERT(0 == manager.registerObserver(mX3, "testObserver3")); bsl::string fileName1 = baseName + "1"; bsl::string fileName2 = baseName + "2"; bsl::string fileName3 = baseName + "3"; // Enable file logging and set the formatting functor. enableFileLogging(mX1, fileName1); enableFileLogging(mX2, fileName2); mX2->setLogFileFunctor(ball::RecordStringFormatter()); enableFileLogging(mX3, fileName3); mX3->setLogFileFunctor(&logRecord1); BALL_LOG_WARN << "log"; bsl::string file1, file2, file3; ASSERT(2 == readFileIntoString(__LINE__, fileName1, file1)); ASSERT(2 == readFileIntoString(__LINE__, fileName2, file2)); ASSERT(2 == readFileIntoString(__LINE__, fileName3, file3)); if (veryVeryVerbose) { P_(file1); P_(file2); P(file3); } ASSERT(file1 == file2); ASSERT(file1 == file3); ASSERT(file2 == file3); mX1->disableFileLogging(); mX2->disableFileLogging(); mX3->disableFileLogging(); // Deregister here as we used local allocator for the observer. ASSERT(0 == manager.deregisterObserver("testObserver1")); ASSERT(0 == manager.deregisterObserver("testObserver2")); ASSERT(0 == manager.deregisterObserver("testObserver3")); } if (verbose) cout << "Testing functors with different formats." << endl; { TempDirectoryGuard tempDirGuard; bsl::string baseName(tempDirGuard.getTempDirName()); bdls::PathUtil::appendRaw(&baseName, "testLog"); // Create observers. bsl::shared_ptr mX1(new (ta) Obj(&ta), &ta); bsl::shared_ptr X1 = mX1; bsl::shared_ptr mX2(new (ta) Obj(&ta), &ta); bsl::shared_ptr X2 = mX2; bsl::shared_ptr mX3(new (ta) Obj(&ta), &ta); bsl::shared_ptr X3 = mX3; // Register with logger manager. ASSERT(0 == manager.registerObserver(mX1, "testObserver1")); ASSERT(0 == manager.registerObserver(mX2, "testObserver2")); ASSERT(0 == manager.registerObserver(mX3, "testObserver3")); bsl::string fileName1 = baseName + "1"; bsl::string fileName2 = baseName + "2"; bsl::string fileName3 = baseName + "3"; // Enable file logging and set the formatting functor. enableFileLogging(mX1, fileName1); enableFileLogging(mX2, fileName2); mX2->setLogFileFunctor(ball::RecordStringFormatter( "\n%p %t %s %f %c %m %u\n")); enableFileLogging(mX3, fileName3); mX3->setLogFileFunctor(&logRecord2); BALL_LOG_WARN << "log"; bsl::string file1, file2, file3; ASSERT(2 == readFileIntoString(__LINE__, fileName1, file1)); ASSERT(2 == readFileIntoString(__LINE__, fileName2, file2)); ASSERT(2 == readFileIntoString(__LINE__, fileName3, file3)); ASSERT(file1 != file2); ASSERT(file1 != file3); ASSERT(file2 != file3); // At this point we have three different logs produced by these // three file observers configured with different formats; now // we are going to reuse one of these fileobserver and change // its functors to see if the resulting log should be identical // to one of those known logs in file1, file2, and file3 bsl::string fileName1a = baseName + "1a"; bsl::string fileContent; mX1->disableFileLogging(); enableFileLogging(mX1, fileName1a); mX1->setLogFileFunctor(ball::RecordStringFormatter( "\n%p %t %s %f %c %m %u\n")); BALL_LOG_WARN << "log"; ASSERT(2 == readFileIntoString(__LINE__, fileName1a, fileContent)); ASSERT(file2 == fileContent); bsl::string fileName1b = baseName + "1b"; mX1->disableFileLogging(); enableFileLogging(mX1, fileName1b); mX1->setLogFileFunctor(&logRecord2); BALL_LOG_WARN << "log"; ASSERT(2 == readFileIntoString(__LINE__, fileName1b, fileContent)); ASSERT(file3 == fileContent); bsl::string fileName1c = baseName + "1c"; mX1->disableFileLogging(); enableFileLogging(mX1, fileName1c); mX1->setLogFileFunctor(ball::RecordStringFormatter( "\n%p %t %s %f %c %m %u\n")); BALL_LOG_WARN << "log"; ASSERT(2 == readFileIntoString(__LINE__, fileName1c, fileContent)); ASSERT(file2 == fileContent); mX1->disableFileLogging(); mX2->disableFileLogging(); mX3->disableFileLogging(); // Deregister here as we used local allocator for the observer. ASSERT(0 == manager.deregisterObserver("testObserver1")); ASSERT(0 == manager.deregisterObserver("testObserver2")); ASSERT(0 == manager.deregisterObserver("testObserver3")); } #endif } #endif } break; case -1: { // -------------------------------------------------------------------- // LARGE FILE TEST // // Concern: //: 1 'ball::FileObserver2' is able to write to a file over 2 GB. // // Plan: //: 1 Keep logging to a file until it is over 5 GB. Manually verify //: the file created is as expected. // // Testing: // CONCERN: 'ball::FileObserver2' is able to write to a file over 2GB // -------------------------------------------------------------------- // This configuration guarantees that the logger manager will publish // all messages regardless of their severity and the observer will see // each message only once. ball::LoggerManagerConfiguration configuration; ASSERT(0 == configuration.setDefaultThresholdLevelsIfValid( ball::Severity::e_OFF, ball::Severity::e_TRACE, ball::Severity::e_OFF, ball::Severity::e_OFF)); ball::LoggerManagerScopedGuard guard(configuration); ball::LoggerManager& manager = ball::LoggerManager::singleton(); BALL_LOG_SET_CATEGORY("TestCategory"); bslma::TestAllocator ta("ta", veryVeryVeryVerbose); TempDirectoryGuard tempDirGuard; bsl::string fileName(tempDirGuard.getTempDirName()); bdls::PathUtil::appendRaw(&fileName, "testLog"); bsl::shared_ptr mX(new (ta) Obj(&ta), &ta); bsl::shared_ptr X = mX; ASSERT(0 == manager.registerObserver(mX, "testObserver")); enableFileLogging(mX, fileName); if (veryVerbose) { P(fileName); } char buffer[1026]; memset(buffer, 'x', sizeof buffer); buffer[sizeof buffer - 1] = '\0'; // Write over 5 GB for (int i = 0; i < 5000000; ++i) { BALL_LOG_WARN << buffer; } mX->disableFileLogging(); // Deregister here as we used local allocator for the observer. ASSERT(0 == manager.deregisterObserver("testObserver")); } 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 2015 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 ---------------------------------- Source/Ocean.Core/OceanRenderer.cpp // Ocean - Copyright © 2020 // This file is subject to the terms and conditions defined in the // file 'LICENSE.md', which is a part of this source code package. #include "BufferedOceanRenderer.h" #include "Ocean.h" #include "OceanRenderer.h" OceanRenderer::OceanRenderer(Ocean *ocean) { m_ocean = ocean; } Ocean *OceanRenderer::GetOcean() const { return m_ocean; } void *__cdecl AllocateOceanRenderer(void *oceanPtr, void *bufferPtr) { return new BufferedOceanRenderer((Ocean *)oceanPtr, (char *)bufferPtr); } void __cdecl DrawOcean(void *oceanRendererPtr, void *bufferPtr) { BufferedOceanRenderer *bufferedOceanRenderer = (BufferedOceanRenderer *)oceanRendererPtr; if (bufferedOceanRenderer->GetBuffer() != bufferPtr) bufferedOceanRenderer->SetBuffer((char *)bufferPtr); bufferedOceanRenderer->Draw(); } void __cdecl FreeOceanRenderer(void *oceanRendererPtr) { delete (BufferedOceanRenderer *)oceanRendererPtr; } // // Copyright (c) 2015 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. // // DisplayWGL.h: WGL implementation of egl::Display #include "libANGLE/renderer/gl/wgl/DisplayWGL.h" #include "common/debug.h" #include "libANGLE/Config.h" #include "libANGLE/Display.h" #include "libANGLE/Surface.h" #include "libANGLE/renderer/gl/RendererGL.h" #include "libANGLE/renderer/gl/renderergl_utils.h" #include "libANGLE/renderer/gl/wgl/D3DTextureSurfaceWGL.h" #include "libANGLE/renderer/gl/wgl/DXGISwapChainWindowSurfaceWGL.h" #include "libANGLE/renderer/gl/wgl/FunctionsWGL.h" #include "libANGLE/renderer/gl/wgl/PbufferSurfaceWGL.h" #include "libANGLE/renderer/gl/wgl/WindowSurfaceWGL.h" #include "libANGLE/renderer/gl/wgl/wgl_utils.h" #include "platform/Platform.h" #include #include #include namespace rx { class FunctionsGLWindows : public FunctionsGL { public: FunctionsGLWindows(HMODULE openGLModule, PFNWGLGETPROCADDRESSPROC getProcAddressWGL) : mOpenGLModule(openGLModule), mGetProcAddressWGL(getProcAddressWGL) { ASSERT(mOpenGLModule); ASSERT(mGetProcAddressWGL); } ~FunctionsGLWindows() override {} private: void *loadProcAddress(const std::string &function) override { void *proc = reinterpret_cast(mGetProcAddressWGL(function.c_str())); if (!proc) { proc = reinterpret_cast(GetProcAddress(mOpenGLModule, function.c_str())); } return proc; } HMODULE mOpenGLModule; PFNWGLGETPROCADDRESSPROC mGetProcAddressWGL; }; DisplayWGL::DisplayWGL(const egl::DisplayState &state) : DisplayGL(state), mOpenGLModule(nullptr), mFunctionsWGL(nullptr), mFunctionsGL(nullptr), mHasRobustness(false), mWindowClass(0), mWindow(nullptr), mDeviceContext(nullptr), mPixelFormat(0), mWGLContext(nullptr), mUseDXGISwapChains(false), mDxgiModule(nullptr), mD3d11Module(nullptr), mD3D11DeviceHandle(nullptr), mD3D11Device(nullptr), mDisplay(nullptr) { } DisplayWGL::~DisplayWGL() { } egl::Error DisplayWGL::initialize(egl::Display *display) { mDisplay = display; mOpenGLModule = LoadLibraryA("opengl32.dll"); if (!mOpenGLModule) { return egl::Error(EGL_NOT_INITIALIZED, "Failed to load OpenGL library."); } mFunctionsWGL = new FunctionsWGL(); mFunctionsWGL->initialize(mOpenGLModule, nullptr); // WGL can't grab extensions until it creates a context because it needs to load the driver's DLLs first. // Create a dummy context to load the driver and determine which GL versions are available. // Work around compile error from not defining "UNICODE" while Chromium does const LPSTR idcArrow = MAKEINTRESOURCEA(32512); std::string className = FormatString("ANGLE DisplayWGL 0x%0.8p Intermediate Window Class", mDisplay); WNDCLASSA intermediateClassDesc = { 0 }; intermediateClassDesc.style = CS_OWNDC; intermediateClassDesc.lpfnWndProc = DefWindowProc; intermediateClassDesc.cbClsExtra = 0; intermediateClassDesc.cbWndExtra = 0; intermediateClassDesc.hInstance = GetModuleHandle(nullptr); intermediateClassDesc.hIcon = nullptr; intermediateClassDesc.hCursor = LoadCursorA(nullptr, idcArrow); intermediateClassDesc.hbrBackground = 0; intermediateClassDesc.lpszMenuName = nullptr; intermediateClassDesc.lpszClassName = className.c_str(); mWindowClass = RegisterClassA(&intermediateClassDesc); if (!mWindowClass) { return egl::Error(EGL_NOT_INITIALIZED, "Failed to register intermediate OpenGL window class."); } HWND dummyWindow = CreateWindowExA(0, reinterpret_cast(mWindowClass), "ANGLE Dummy Window", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, nullptr, nullptr, nullptr, nullptr); if (!dummyWindow) { return egl::Error(EGL_NOT_INITIALIZED, "Failed to create dummy OpenGL window."); } HDC dummyDeviceContext = GetDC(dummyWindow); if (!dummyDeviceContext) { return egl::Error(EGL_NOT_INITIALIZED, "Failed to get the device context of the dummy OpenGL window."); } const PIXELFORMATDESCRIPTOR pixelFormatDescriptor = wgl::GetDefaultPixelFormatDescriptor(); int dummyPixelFormat = ChoosePixelFormat(dummyDeviceContext, &pixelFormatDescriptor); if (dummyPixelFormat == 0) { return egl::Error(EGL_NOT_INITIALIZED, "Could not find a compatible pixel format for the dummy OpenGL window."); } if (!SetPixelFormat(dummyDeviceContext, dummyPixelFormat, &pixelFormatDescriptor)) { return egl::Error(EGL_NOT_INITIALIZED, "Failed to set the pixel format on the intermediate OpenGL window."); } HGLRC dummyWGLContext = mFunctionsWGL->createContext(dummyDeviceContext); if (!dummyDeviceContext) { return egl::Error(EGL_NOT_INITIALIZED, "Failed to create a WGL context for the dummy OpenGL window."); } if (!mFunctionsWGL->makeCurrent(dummyDeviceContext, dummyWGLContext)) { return egl::Error(EGL_NOT_INITIALIZED, "Failed to make the dummy WGL context current."); } // Grab the GL version from this context and use it as the maximum version available. typedef const GLubyte* (GL_APIENTRYP PFNGLGETSTRINGPROC) (GLenum name); PFNGLGETSTRINGPROC getString = reinterpret_cast(GetProcAddress(mOpenGLModule, "glGetString")); if (!getString) { return egl::Error(EGL_NOT_INITIALIZED, "Failed to get glGetString pointer."); } // Reinitialize the wgl functions to grab the extensions mFunctionsWGL->initialize(mOpenGLModule, dummyDeviceContext); bool hasWGLCreateContextRobustness = mFunctionsWGL->hasExtension("WGL_ARB_create_context_robustness"); // Destroy the dummy window and context mFunctionsWGL->makeCurrent(dummyDeviceContext, nullptr); mFunctionsWGL->deleteContext(dummyWGLContext); ReleaseDC(dummyWindow, dummyDeviceContext); DestroyWindow(dummyWindow); const egl::AttributeMap &displayAttributes = display->getAttributeMap(); EGLint requestedDisplayType = static_cast(displayAttributes.get( EGL_PLATFORM_ANGLE_TYPE_ANGLE, EGL_PLATFORM_ANGLE_TYPE_DEFAULT_ANGLE)); if (requestedDisplayType == EGL_PLATFORM_ANGLE_TYPE_OPENGLES_ANGLE && !mFunctionsWGL->hasExtension("WGL_EXT_create_context_es2_profile") && !mFunctionsWGL->hasExtension("WGL_EXT_create_context_es_profile")) { return egl::Error(EGL_NOT_INITIALIZED, "Cannot create an OpenGL ES platform on Windows without " "the WGL_EXT_create_context_es(2)_profile extension."); } // Create the real intermediate context and windows mWindow = CreateWindowExA(0, reinterpret_cast(mWindowClass), "ANGLE Intermediate Window", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, nullptr, nullptr, nullptr, nullptr); if (!mWindow) { return egl::Error(EGL_NOT_INITIALIZED, "Failed to create intermediate OpenGL window."); } mDeviceContext = GetDC(mWindow); if (!mDeviceContext) { return egl::Error(EGL_NOT_INITIALIZED, "Failed to get the device context of the intermediate OpenGL window."); } if (mFunctionsWGL->choosePixelFormatARB) { std::vector attribs = wgl::GetDefaultPixelFormatAttributes(false); UINT matchingFormats = 0; mFunctionsWGL->choosePixelFormatARB(mDeviceContext, &attribs[0], nullptr, 1u, &mPixelFormat, &matchingFormats); } if (mPixelFormat == 0) { mPixelFormat = ChoosePixelFormat(mDeviceContext, &pixelFormatDescriptor); } if (mPixelFormat == 0) { return egl::Error(EGL_NOT_INITIALIZED, "Could not find a compatible pixel format for the intermediate OpenGL window."); } if (!SetPixelFormat(mDeviceContext, mPixelFormat, &pixelFormatDescriptor)) { return egl::Error(EGL_NOT_INITIALIZED, "Failed to set the pixel format on the intermediate OpenGL window."); } if (mFunctionsWGL->createContextAttribsARB) { int flags = 0; // TODO: allow debug contexts // TODO: handle robustness int mask = 0; if (requestedDisplayType == EGL_PLATFORM_ANGLE_TYPE_OPENGLES_ANGLE) { mask |= WGL_CONTEXT_ES_PROFILE_BIT_EXT; } else { // Request core profile mask |= WGL_CONTEXT_CORE_PROFILE_BIT_ARB; } std::vector contextCreationAttributes; if (hasWGLCreateContextRobustness) { contextCreationAttributes.push_back(WGL_CONTEXT_RESET_NOTIFICATION_STRATEGY_ARB); contextCreationAttributes.push_back(WGL_LOSE_CONTEXT_ON_RESET_ARB); } // Don't request a specific version unless the user wants one. WGL will return the highest version // that the driver supports if no version is requested. EGLint requestedMajorVersion = static_cast( displayAttributes.get(EGL_PLATFORM_ANGLE_MAX_VERSION_MAJOR_ANGLE, EGL_DONT_CARE)); EGLint requestedMinorVersion = static_cast( displayAttributes.get(EGL_PLATFORM_ANGLE_MAX_VERSION_MINOR_ANGLE, EGL_DONT_CARE)); if (requestedMajorVersion != EGL_DONT_CARE && requestedMinorVersion != EGL_DONT_CARE) { contextCreationAttributes.push_back(WGL_CONTEXT_MAJOR_VERSION_ARB); contextCreationAttributes.push_back(requestedMajorVersion); contextCreationAttributes.push_back(WGL_CONTEXT_MINOR_VERSION_ARB); contextCreationAttributes.push_back(requestedMinorVersion); } else { // the ES profile will give us ES version 1.1 unless a higher version is requested. // Requesting version 2.0 will give us the highest compatible version available (2.0, // 3.0, 3.1, etc). if (requestedDisplayType == EGL_PLATFORM_ANGLE_TYPE_OPENGLES_ANGLE) { contextCreationAttributes.push_back(WGL_CONTEXT_MAJOR_VERSION_ARB); contextCreationAttributes.push_back(2); contextCreationAttributes.push_back(WGL_CONTEXT_MINOR_VERSION_ARB); contextCreationAttributes.push_back(0); } } // Set the flag attributes if (flags != 0) { contextCreationAttributes.push_back(WGL_CONTEXT_FLAGS_ARB); contextCreationAttributes.push_back(flags); } // Set the mask attribute if (mask != 0) { contextCreationAttributes.push_back(WGL_CONTEXT_PROFILE_MASK_ARB); contextCreationAttributes.push_back(mask); } // Signal the end of the attributes contextCreationAttributes.push_back(0); contextCreationAttributes.push_back(0); mWGLContext = mFunctionsWGL->createContextAttribsARB(mDeviceContext, NULL, &contextCreationAttributes[0]); } // If wglCreateContextAttribsARB is unavailable or failed, try the standard wglCreateContext if (!mWGLContext) { // Don't have control over GL versions mWGLContext = mFunctionsWGL->createContext(mDeviceContext); } if (!mWGLContext) { return egl::Error(EGL_NOT_INITIALIZED, "Failed to create a WGL context for the intermediate OpenGL window."); } if (!mFunctionsWGL->makeCurrent(mDeviceContext, mWGLContext)) { return egl::Error(EGL_NOT_INITIALIZED, "Failed to make the intermediate WGL context current."); } mFunctionsGL = new FunctionsGLWindows(mOpenGLModule, mFunctionsWGL->getProcAddress); mFunctionsGL->initialize(); mHasRobustness = mFunctionsGL->getGraphicsResetStatus != nullptr; if (hasWGLCreateContextRobustness != mHasRobustness) { ANGLEPlatformCurrent()->logWarning( "WGL_ARB_create_context_robustness exists but unable to OpenGL context with " "robustness."); } // Intel OpenGL ES drivers are not currently supported due to bugs in the driver and ANGLE VendorID vendor = GetVendorID(mFunctionsGL); if (requestedDisplayType == EGL_PLATFORM_ANGLE_TYPE_OPENGLES_ANGLE && IsIntel(vendor)) { return egl::Error(EGL_NOT_INITIALIZED, "Intel OpenGL ES drivers are not supported."); } // Create DXGI swap chains for windows that come from other processes. Windows is unable to // SetPixelFormat on windows from other processes when a sandbox is enabled. HDC nativeDisplay = display->getNativeDisplayId(); HWND nativeWindow = WindowFromDC(nativeDisplay); if (nativeWindow != nullptr) { DWORD currentProcessId = GetCurrentProcessId(); DWORD windowProcessId; GetWindowThreadProcessId(nativeWindow, &windowProcessId); // AMD drivers advertise the WGL_NV_DX_interop and WGL_NV_DX_interop2 extensions but fail mUseDXGISwapChains = !IsAMD(vendor) && (currentProcessId != windowProcessId); } else { mUseDXGISwapChains = false; } if (mUseDXGISwapChains) { egl::Error error = initializeD3DDevice(); if (error.isError()) { return error; } } return DisplayGL::initialize(display); } void DisplayWGL::terminate() { DisplayGL::terminate(); releaseD3DDevice(mD3D11DeviceHandle); mFunctionsWGL->makeCurrent(mDeviceContext, NULL); mFunctionsWGL->deleteContext(mWGLContext); mWGLContext = NULL; ReleaseDC(mWindow, mDeviceContext); mDeviceContext = NULL; DestroyWindow(mWindow); mWindow = NULL; UnregisterClassA(reinterpret_cast(mWindowClass), NULL); mWindowClass = NULL; SafeDelete(mFunctionsWGL); SafeDelete(mFunctionsGL); FreeLibrary(mOpenGLModule); mOpenGLModule = nullptr; SafeRelease(mD3D11Device); if (mDxgiModule) { FreeLibrary(mDxgiModule); mDxgiModule = nullptr; } if (mD3d11Module) { FreeLibrary(mD3d11Module); mD3d11Module = nullptr; } ASSERT(mRegisteredD3DDevices.empty()); } SurfaceImpl *DisplayWGL::createWindowSurface(const egl::SurfaceState &state, EGLNativeWindowType window, const egl::AttributeMap &attribs) { EGLint orientation = static_cast(attribs.get(EGL_SURFACE_ORIENTATION_ANGLE, 0)); if (mUseDXGISwapChains) { return new DXGISwapChainWindowSurfaceWGL(state, getRenderer(), window, mD3D11Device, mD3D11DeviceHandle, mWGLContext, mDeviceContext, mFunctionsGL, mFunctionsWGL, orientation); } else { return new WindowSurfaceWGL(state, getRenderer(), window, mPixelFormat, mWGLContext, mFunctionsWGL, orientation); } } SurfaceImpl *DisplayWGL::createPbufferSurface(const egl::SurfaceState &state, const egl::AttributeMap &attribs) { EGLint width = static_cast(attribs.get(EGL_WIDTH, 0)); EGLint height = static_cast(attribs.get(EGL_HEIGHT, 0)); bool largest = (attribs.get(EGL_LARGEST_PBUFFER, EGL_FALSE) == EGL_TRUE); EGLenum textureFormat = static_cast(attribs.get(EGL_TEXTURE_FORMAT, EGL_NO_TEXTURE)); EGLenum textureTarget = static_cast(attribs.get(EGL_TEXTURE_TARGET, EGL_NO_TEXTURE)); return new PbufferSurfaceWGL(state, getRenderer(), width, height, textureFormat, textureTarget, largest, mPixelFormat, mDeviceContext, mWGLContext, mFunctionsWGL); } SurfaceImpl *DisplayWGL::createPbufferFromClientBuffer(const egl::SurfaceState &state, EGLenum buftype, EGLClientBuffer clientBuffer, const egl::AttributeMap &attribs) { ASSERT(buftype == EGL_D3D_TEXTURE_ANGLE); return new D3DTextureSurfaceWGL(state, getRenderer(), clientBuffer, this, mWGLContext, mDeviceContext, mFunctionsGL, mFunctionsWGL); } SurfaceImpl *DisplayWGL::createPixmapSurface(const egl::SurfaceState &state, NativePixmapType nativePixmap, const egl::AttributeMap &attribs) { UNIMPLEMENTED(); return nullptr; } egl::Error DisplayWGL::getDevice(DeviceImpl **device) { UNIMPLEMENTED(); return egl::Error(EGL_BAD_DISPLAY); } egl::ConfigSet DisplayWGL::generateConfigs() { egl::ConfigSet configs; int minSwapInterval = 1; int maxSwapInterval = 1; if (mFunctionsWGL->swapIntervalEXT) { // No defined maximum swap interval in WGL_EXT_swap_control, use a reasonable number minSwapInterval = 0; maxSwapInterval = 8; } const gl::Version &maxVersion = getMaxSupportedESVersion(); ASSERT(maxVersion >= gl::Version(2, 0)); bool supportsES3 = maxVersion >= gl::Version(3, 0); PIXELFORMATDESCRIPTOR pixelFormatDescriptor; DescribePixelFormat(mDeviceContext, mPixelFormat, sizeof(pixelFormatDescriptor), &pixelFormatDescriptor); auto getAttrib = [this](int attrib) { return wgl::QueryWGLFormatAttrib(mDeviceContext, mPixelFormat, attrib, mFunctionsWGL); }; const EGLint optimalSurfaceOrientation = mUseDXGISwapChains ? EGL_SURFACE_ORIENTATION_INVERT_Y_ANGLE : 0; egl::Config config; config.renderTargetFormat = GL_RGBA8; // TODO: use the bit counts to determine the format config.depthStencilFormat = GL_DEPTH24_STENCIL8; // TODO: use the bit counts to determine the format config.bufferSize = pixelFormatDescriptor.cColorBits; config.redSize = pixelFormatDescriptor.cRedBits; config.greenSize = pixelFormatDescriptor.cGreenBits; config.blueSize = pixelFormatDescriptor.cBlueBits; config.luminanceSize = 0; config.alphaSize = pixelFormatDescriptor.cAlphaBits; config.alphaMaskSize = 0; config.bindToTextureRGB = (getAttrib(WGL_BIND_TO_TEXTURE_RGB_ARB) == TRUE); config.bindToTextureRGBA = (getAttrib(WGL_BIND_TO_TEXTURE_RGBA_ARB) == TRUE); config.colorBufferType = EGL_RGB_BUFFER; config.configCaveat = EGL_NONE; config.conformant = EGL_OPENGL_ES2_BIT | (supportsES3 ? EGL_OPENGL_ES3_BIT_KHR : 0); config.depthSize = pixelFormatDescriptor.cDepthBits; config.level = 0; config.matchNativePixmap = EGL_NONE; config.maxPBufferWidth = getAttrib(WGL_MAX_PBUFFER_WIDTH_ARB); config.maxPBufferHeight = getAttrib(WGL_MAX_PBUFFER_HEIGHT_ARB); config.maxPBufferPixels = getAttrib(WGL_MAX_PBUFFER_PIXELS_ARB); config.maxSwapInterval = maxSwapInterval; config.minSwapInterval = minSwapInterval; config.nativeRenderable = EGL_TRUE; // Direct rendering config.nativeVisualID = 0; config.nativeVisualType = EGL_NONE; config.renderableType = EGL_OPENGL_ES2_BIT | (supportsES3 ? EGL_OPENGL_ES3_BIT_KHR : 0); config.sampleBuffers = 0; // FIXME: enumerate multi-sampling config.samples = 0; config.stencilSize = pixelFormatDescriptor.cStencilBits; config.surfaceType = ((pixelFormatDescriptor.dwFlags & PFD_DRAW_TO_WINDOW) ? EGL_WINDOW_BIT : 0) | ((getAttrib(WGL_DRAW_TO_PBUFFER_ARB) == TRUE) ? EGL_PBUFFER_BIT : 0) | ((getAttrib(WGL_SWAP_METHOD_ARB) == WGL_SWAP_COPY_ARB) ? EGL_SWAP_BEHAVIOR_PRESERVED_BIT : 0); config.optimalOrientation = optimalSurfaceOrientation; config.transparentType = EGL_NONE; config.transparentRedValue = 0; config.transparentGreenValue = 0; config.transparentBlueValue = 0; configs.add(config); return configs; } bool DisplayWGL::testDeviceLost() { if (mHasRobustness) { return getRenderer()->getResetStatus() != GL_NO_ERROR; } return false; } egl::Error DisplayWGL::restoreLostDevice() { return egl::Error(EGL_BAD_DISPLAY); } bool DisplayWGL::isValidNativeWindow(EGLNativeWindowType window) const { return (IsWindow(window) == TRUE); } egl::Error DisplayWGL::validateClientBuffer(const egl::Config *configuration, EGLenum buftype, EGLClientBuffer clientBuffer, const egl::AttributeMap &attribs) const { switch (buftype) { case EGL_D3D_TEXTURE_ANGLE: return D3DTextureSurfaceWGL::ValidateD3DTextureClientBuffer(clientBuffer); default: return DisplayGL::validateClientBuffer(configuration, buftype, clientBuffer, attribs); } } std::string DisplayWGL::getVendorString() const { //UNIMPLEMENTED(); return ""; } const FunctionsGL *DisplayWGL::getFunctionsGL() const { return mFunctionsGL; } egl::Error DisplayWGL::initializeD3DDevice() { if (mD3D11Device != nullptr) { return egl::Error(EGL_SUCCESS); } mDxgiModule = LoadLibrary(TEXT("dxgi.dll")); if (!mDxgiModule) { return egl::Error(EGL_NOT_INITIALIZED, "Failed to load DXGI library."); } mD3d11Module = LoadLibrary(TEXT("d3d11.dll")); if (!mD3d11Module) { return egl::Error(EGL_NOT_INITIALIZED, "Failed to load d3d11 library."); } PFN_D3D11_CREATE_DEVICE d3d11CreateDevice = nullptr; d3d11CreateDevice = reinterpret_cast( GetProcAddress(mD3d11Module, "D3D11CreateDevice")); if (d3d11CreateDevice == nullptr) { return egl::Error(EGL_NOT_INITIALIZED, "Could not retrieve D3D11CreateDevice address."); } HRESULT result = d3d11CreateDevice(nullptr, D3D_DRIVER_TYPE_HARDWARE, nullptr, 0, nullptr, 0, D3D11_SDK_VERSION, &mD3D11Device, nullptr, nullptr); if (FAILED(result)) { return egl::Error(EGL_NOT_INITIALIZED, "Could not create D3D11 device, error: 0x%X", result); } egl::Error error = registerD3DDevice(mD3D11Device, &mD3D11DeviceHandle); if (error.isError()) { return error; } return egl::Error(EGL_SUCCESS); } void DisplayWGL::generateExtensions(egl::DisplayExtensions *outExtensions) const { // Only enable the surface orientation and post sub buffer for DXGI swap chain surfaces, they // prefer to swap with inverted Y. outExtensions->postSubBuffer = mUseDXGISwapChains; outExtensions->surfaceOrientation = mUseDXGISwapChains; outExtensions->createContextRobustness = mHasRobustness; outExtensions->d3dTextureClientBuffer = mFunctionsWGL->hasExtension("WGL_NV_DX_interop2"); } void DisplayWGL::generateCaps(egl::Caps *outCaps) const { outCaps->textureNPOT = true; } egl::Error DisplayWGL::waitClient() const { // Unimplemented as this is not needed for WGL return egl::Error(EGL_SUCCESS); } egl::Error DisplayWGL::waitNative(EGLint engine, egl::Surface *drawSurface, egl::Surface *readSurface) const { // Unimplemented as this is not needed for WGL return egl::Error(EGL_SUCCESS); } egl::Error DisplayWGL::getDriverVersion(std::string *version) const { *version = ""; return egl::Error(EGL_SUCCESS); } egl::Error DisplayWGL::registerD3DDevice(IUnknown *device, HANDLE *outHandle) { ASSERT(device != nullptr); ASSERT(outHandle != nullptr); auto iter = mRegisteredD3DDevices.find(device); if (iter != mRegisteredD3DDevices.end()) { iter->second.refCount++; *outHandle = iter->second.handle; return egl::Error(EGL_SUCCESS); } HANDLE handle = mFunctionsWGL->dxOpenDeviceNV(device); if (!handle) { return egl::Error(EGL_BAD_PARAMETER, "Failed to open D3D device."); } device->AddRef(); D3DObjectHandle newDeviceInfo; newDeviceInfo.handle = handle; newDeviceInfo.refCount = 1; mRegisteredD3DDevices[device] = newDeviceInfo; *outHandle = handle; return egl::Error(EGL_SUCCESS); } void DisplayWGL::releaseD3DDevice(HANDLE deviceHandle) { for (auto iter = mRegisteredD3DDevices.begin(); iter != mRegisteredD3DDevices.end(); iter++) { if (iter->second.handle == deviceHandle) { iter->second.refCount--; if (iter->second.refCount == 0) { mFunctionsWGL->dxCloseDeviceNV(iter->second.handle); iter->first->Release(); mRegisteredD3DDevices.erase(iter); break; } } } } } 0 #pragma once #include "ReadWriteService.cpp" #include "DumpService.cpp" #include "ActionResult.cpp" #include "InterfaceFileSystem.cpp" #include "InterfaceCluster.cpp" #include "ActionResult.cpp" using namespace std; class FileSystemService { private: InterfaceFileSystem *interfaceFileSystem; InterfaceCluster *interfaceCluster; ReadWriteService *readWriteService; DumpService *dumpService; public: void setInterfaceFileSystem(InterfaceFileSystem *interfaceFileSystem) { this->interfaceFileSystem = interfaceFileSystem; } void setInterfaceCluster(InterfaceCluster *interfaceCluster) { this->interfaceCluster = interfaceCluster; } void setReadWriteService(ReadWriteService *readWriteService) { this->readWriteService = readWriteService; } void setDumpService(DumpService *dumpService) { this->dumpService = dumpService; } ActionResult *createFile(const string &path) { try { interfaceFileSystem->save(path, new CustomFile(path)); return new ActionResult("File is created", true); } catch (exception &e) { return new ActionResult(e.what(), false); } } ActionResult *deleteFile(const string &path) { try { CustomFile *deletedFile = interfaceFileSystem->deleteFile(path); interfaceCluster->deleteAllClusters(deletedFile->getAddresses()); delete deletedFile; return new ActionResult("File is deleted", true); } catch (exception &e) { return new ActionResult(e.what(), false); } } ActionResult *copyFile(const string &path, const string ©Path) { try { CustomFile *file = interfaceFileSystem->findByName(path); CustomFile *copy = interfaceFileSystem->save(copyPath, new CustomFile(copyPath)); readWriteService->fillFile(copy, readWriteService->readClusters(file)); return new ActionResult("File is copied", true); } catch (exception &e) { return new ActionResult(e.what(), false); } } ActionResult *moveFile(const string &path, const string &movePath) { return copyFile(path, movePath); } ActionResult *readFile(const string &path) { try { CustomFile *file = interfaceFileSystem->findByName(path); vector *clusters = readWriteService->readClusters(file); readWriteService->printClusters(clusters); delete clusters; return new ActionResult("\nFile is read", true); } catch (exception &e) { return new ActionResult(e.what(), false); } } ActionResult *writeFile(const string &path, char *data, int size) { try { CustomFile *file = interfaceFileSystem->findByName(path); vector *clusters = readWriteService->readClusters(file); readWriteService->writeClusters(file, data, size, clusters); interfaceFileSystem->updateFile(path, file); delete clusters; return new ActionResult("File is written", true); } catch (exception &e) { return new ActionResult(e.what(), false); } } ActionResult *rewriteFile(const string &path, char *data, int size) { try { deleteFile(path); auto *file = new CustomFile(path); auto *clusters = new vector(); readWriteService->writeClusters(file, data, size, clusters); interfaceFileSystem->save(path, file); delete clusters; return new ActionResult("File is rewritten", true); } catch (exception &e) { return new ActionResult(e.what(), false); } } ActionResult *dump() { try { dumpService->dump(); return new ActionResult("Dump is printed", true); } catch (exception &e) { return new ActionResult(e.what(), false); } } ActionResult *listFiles() { try { vector *files = interfaceFileSystem->findAll(); for (auto &file : *files) { cout << file->getName() << endl; } return new ActionResult("Files is printed", true); } catch (exception &e) { return new ActionResult(e.what(), false); } } };#include TESSERACT_COMMON_IGNORE_WARNINGS_PUSH #include #include TESSERACT_COMMON_IGNORE_WARNINGS_POP #include #include "tesseract_urdf_common_unit.h" TEST(TesseractURDFUnit, parse_cone) // NOLINT { { std::string str = R"()"; tesseract_geometry::Cone::Ptr geom; auto status = runTest(geom, str, "cone", 2); EXPECT_TRUE(*status); EXPECT_EQ(status->category()->name(), "ConeStatusCategory"); EXPECT_FALSE(status->category()->message(999).empty()); // Test invalid error code EXPECT_FALSE(status->message().empty()); EXPECT_NEAR(geom->getRadius(), 1, 1e-8); EXPECT_NEAR(geom->getLength(), 2, 1e-8); } { std::string str = R"()"; tesseract_geometry::Cone::Ptr geom; auto status = runTest(geom, str, "cone", 2); EXPECT_FALSE(*status); EXPECT_FALSE(status->message().empty()); } { std::string str = R"()"; tesseract_geometry::Cone::Ptr geom; auto status = runTest(geom, str, "cone", 2); EXPECT_FALSE(*status); EXPECT_FALSE(status->message().empty()); } { std::string str = R"()"; tesseract_geometry::Cone::Ptr geom; auto status = runTest(geom, str, "cone", 2); EXPECT_FALSE(*status); EXPECT_FALSE(status->message().empty()); } { std::string str = R"()"; tesseract_geometry::Cone::Ptr geom; auto status = runTest(geom, str, "cone", 2); EXPECT_FALSE(*status); EXPECT_FALSE(status->message().empty()); } // TODO: I would expect this to fail but tinyxml2 still parses it so need to create an issue. // { // std::string str = R"()"; // tesseract_geometry::Cone::Ptr geom; // auto status = runTest(geom, str, "cone"); // EXPECT_FALSE(*status); // EXPECT_FALSE(status->message().empty()); // } { std::string str = R"()"; tesseract_geometry::Cone::Ptr geom; auto status = runTest(geom, str, "cone", 2); EXPECT_FALSE(*status); EXPECT_FALSE(status->message().empty()); } { std::string str = R"()"; tesseract_geometry::Cone::Ptr geom; auto status = runTest(geom, str, "cone", 2); EXPECT_FALSE(*status); EXPECT_FALSE(status->message().empty()); } { std::string str = ""; tesseract_geometry::Cone::Ptr geom; auto status = runTest(geom, str, "cone", 2); EXPECT_FALSE(*status); EXPECT_FALSE(status->message().empty()); } } #include "Box.hpp" // following code is NOT compilable, it's just for examples!!! //======================================================== template class VectorWithBoxes { Box* boxes; }; //======================================================== template class Vector { T* elements; }; //======================================================== template class VectorWithPointers { T** elements; }; //======================================================== template class InsertItem { protected: int counter; T destination; public: virtual void operator()(std::string item) { destination->Insert(item.c_str(), counter++); } public: InsertItem(T argDestination) { counter = 0; destination = argDestination; } }; template class InsertItem2 : InsertItem { public: virtual void operator()(std::string item) { destination ->Insert2(item.c_str(), counter++, 0); } }; //======================================================== template class Area { T area; }; class Rectangle : public Area { // ... }; class Triangle : public Area, public Area { // ... }; template class Square : public Area { // ... }; //========================================================== class Rectangle // not inheriting from any Area type { // Area independent interface }; template class SpecificRectangle : public Rectangle, public Area { // Area dependent stuff }; void foo(Rectangle&); // A function which works with generic rectangles int main() { SpecificRectangle intrect; foo(intrect); SpecificRectangle charrect; foo(charrect); } //========================================================== // diamond problem class Area { // generic Area interface }; template class Rectangle : public virtual Area // virtual because of "diamond inheritance" { // generic rectangle interface }; template class SpecificArea : public virtual Area { // specific implementation of Area for type T }; template class SpecificRectangle : public Rectangle, // maybe this should be virtual as well, in case the hierarchy is extended later public SpecificArea // no virtual inheritance needed here { // specific implementation of Rectangle for type T }; // ====================================================================== // default type for templates template class Foo { }; template class A; template // we can not do that class B; template class C { public: T x; U y; }; int main() { Foo f; // for C++17 and above Foo<> f; // for every standard of C++ return 0; } mwoehlke-kitware/kwiver // This file is part of KWIVER, and is distributed under the // OSI-approved BSD 3-Clause License. See top-level LICENSE file or // https://github.com/Kitware/kwiver/blob/master/LICENSE for details. /** * \file * \brief vital::image C interface implementation */ #include "image.h" #include #include #include #include /// Create a new, empty image vital_image_t* vital_image_new() { STANDARD_CATCH( "C::image:new", 0, return reinterpret_cast( new kwiver::vital::image() ); ); return 0; } /// Create a new image with dimensions, allocating memory vital_image_t* vital_image_new_with_dim( size_t width, size_t height, size_t depth, bool interleave, vital_image_pixel_type_t pixel_type, size_t pixel_num_bytes) { STANDARD_CATCH( "C::image:new_with_dim", 0, typedef kwiver::vital::image_pixel_traits pixel_traits; pixel_traits pt(static_cast(pixel_type), pixel_num_bytes); return reinterpret_cast( new kwiver::vital::image( width, height, depth, interleave, pt ) ); ); return 0; } /// Create a new image wrapping existing data vital_image_t* vital_image_new_from_data( void const* first_pixel, size_t width, size_t height, size_t depth, int32_t w_step, int32_t h_step, int32_t d_step, vital_image_pixel_type_t pixel_type, size_t pixel_num_bytes) { STANDARD_CATCH( "C::image:new_from_data", 0, typedef kwiver::vital::image_pixel_traits pixel_traits; pixel_traits pt(static_cast(pixel_type), pixel_num_bytes); return reinterpret_cast( new kwiver::vital::image( first_pixel, width, height, depth, w_step, h_step, d_step, pt ) ); ); return 0; } /// Create a new image from an existing image vital_image_t* vital_image_new_from_image( vital_image_t *other_image ) { STANDARD_CATCH( "C::image::new_from_image", 0, return reinterpret_cast( new kwiver::vital::image( *reinterpret_cast(other_image) ) ); ); return 0; } /// Destroy an image instance void vital_image_destroy( vital_image_t *image ) { STANDARD_CATCH( "C::image::destroy", 0, delete reinterpret_cast( image ); ); }; /// Copy the data from \p image_src into \p image_dest void vital_image_copy_from_image(vital_image_t *image_dest, vital_image_t *image_src ) { STANDARD_CATCH( "C::image::copy_from", 0, reinterpret_cast( image_dest )->copy_from( *reinterpret_cast( image_src )); ); } /// Return true if two images have equal content (deep equality) VITAL_C_EXPORT bool vital_image_equal_content( vital_image_t* image1, vital_image_t* image2 ) { STANDARD_CATCH( "C::image::equal_content", 0, return kwiver::vital::equal_content(*reinterpret_cast( image1 ), *reinterpret_cast( image2 )); ); return false; } // // A little shortcut for defining pixel accessors // #define GET_PIXEL( TYPE, NAME ) \ TYPE vital_image_get_pixel2_ ## NAME( vital_image_t *image, \ unsigned i, unsigned j ) \ { \ STANDARD_CATCH( \ "C::image::get_pixel2_" # NAME, 0, \ return reinterpret_cast(image)->at(i,j); \ ); \ return static_cast(0); \ } \ TYPE vital_image_get_pixel3_ ## NAME( vital_image_t *image, \ unsigned i, unsigned j, \ VITAL_UNUSED unsigned k ) \ { \ STANDARD_CATCH( \ "C::image::get_pixel2_" # NAME, 0, \ return reinterpret_cast(image)->at(i,j); \ ); \ return static_cast(0); \ } GET_PIXEL( uint8_t, uint8 ) GET_PIXEL( int8_t, int8 ) GET_PIXEL( uint16_t, uint16 ) GET_PIXEL( int16_t, int16 ) GET_PIXEL( uint32_t, uint32 ) GET_PIXEL( int32_t, int32 ) GET_PIXEL( uint64_t, uint64 ) GET_PIXEL( int64_t, int64 ) GET_PIXEL( float, float ) GET_PIXEL( double, double ) GET_PIXEL( bool, bool ) // // A little shortcut for defining accessors // #define ACCESSOR( TYPE, NAME ) \ TYPE vital_image_ ## NAME( vital_image_t *image ) \ { \ STANDARD_CATCH( \ "C::image::" # NAME, 0, \ return reinterpret_cast(image)->NAME(); \ ); \ return 0; \ } ACCESSOR( size_t, size ) ACCESSOR( void*, first_pixel ) ACCESSOR( size_t, width ) ACCESSOR( size_t, height ) ACCESSOR( size_t, depth ) ACCESSOR( size_t, w_step ) ACCESSOR( size_t, h_step ) ACCESSOR( size_t, d_step ) ACCESSOR( bool, is_contiguous ) #undef ACCESSOR // // A little shortcut for defining pixel traits accessors // #define PT_ACCESSOR( TYPE, NAME ) \ TYPE vital_image_pixel_ ## NAME( vital_image_t *image ) \ { \ STANDARD_CATCH( \ "C::image::pixel_format::" # NAME, 0, \ return static_cast( \ reinterpret_cast(image) \ ->pixel_traits().NAME); \ ); \ return static_cast(0); \ } PT_ACCESSOR( size_t, num_bytes ) PT_ACCESSOR( vital_image_pixel_type_t, type ) #undef PT_ACCESSOR WindJSTeam/mapbox-font-toolconvert-font/fonts/node_modules/mapnik-vector-tile/src/vector_tile_geometry_decoder.cpp #include "vector_tile_geometry_decoder.hpp" #include "vector_tile_geometry_decoder.ipp" namespace mapnik { namespace vector_tile_impl { // decode geometry template mapnik::geometry::geometry decode_geometry(GeometryPBF & paths, int32_t geom_type, unsigned version, double tile_x, double tile_y, double scale_x, double scale_y); template mapnik::geometry::geometry decode_geometry(GeometryPBF & paths, int32_t geom_type, unsigned version, std::int64_t tile_x, std::int64_t tile_y, double scale_x, double scale_y); template mapnik::geometry::geometry decode_geometry(GeometryPBF & paths, int32_t geom_type, unsigned version, double tile_x, double tile_y, double scale_x, double scale_y, mapnik::box2d const& bbox); template mapnik::geometry::geometry decode_geometry(GeometryPBF & paths, int32_t geom_type, unsigned version, std::int64_t tile_x, std::int64_t tile_y, double scale_x, double scale_y, mapnik::box2d const& bbox); } // end ns vector_tile_impl } // end ns mapnik #include int main() { while (1) { char S[81] = { 0, }; gets(S); if (S[0] == 'E' && S[1] == 'O' && S[2] == 'I') break; for (int i = 0; S[i]; i++) if (S[i] >= 'A' && S[i] <= 'Z') S[i] = 'a' + (S[i] - 'A'); printf("%s\n", S); bool isFind = false; int isn = 0, ise = 0, ism = 0, iso = 0; for (int i = 0; S[i]; i++) { if (S[i] != 'n' && S[i] != 'e' && S[i] != 'm' && S[i] != 'o') { isn = ise = ism = iso = 0; continue; } if (isn + ise + ism + iso == 0 && S[i] == 'n') isn = 1; if (isn == 1 && ise + ism + iso == 0 && S[i] == 'e') ise = 1; if (isn + ise == 2 && ism + iso == 0 && S[i] == 'm') ism = 1; if (isn + ise + ism == 3 && iso == 0 && S[i] == 'o') { iso = 1; isFind = true; break; } } printf("%s\n", (isFind == true? "Found": "Missing")); } return 0; } /**************************************************************************** * * (c) 2009-2016 QGROUNDCONTROL PROJECT * * QGroundControl is licensed according to the terms in the file * COPYING.md in the root of the source code directory. * ****************************************************************************/ #include "TransectStyleComplexItem.h" #include "JsonHelper.h" #include "MissionController.h" #include "QGCGeo.h" #include "QGroundControlQmlGlobal.h" #include "QGCQGeoCoordinate.h" #include "SettingsManager.h" #include "AppSettings.h" #include "QGCQGeoCoordinate.h" #include QGC_LOGGING_CATEGORY(TransectStyleComplexItemLog, "TransectStyleComplexItemLog") const char* TransectStyleComplexItem::turnAroundDistanceName = "TurnAroundDistance"; const char* TransectStyleComplexItem::turnAroundDistanceMultiRotorName = "TurnAroundDistanceMultiRotor"; const char* TransectStyleComplexItem::cameraTriggerInTurnAroundName = "CameraTriggerInTurnAround"; const char* TransectStyleComplexItem::hoverAndCaptureName = "HoverAndCapture"; const char* TransectStyleComplexItem::refly90DegreesName = "Refly90Degrees"; const char* TransectStyleComplexItem::_jsonCameraCalcKey = "CameraCalc"; TransectStyleComplexItem::TransectStyleComplexItem(Vehicle* vehicle, QString settingsGroup, QObject* parent) : ComplexMissionItem (vehicle, parent) , _settingsGroup (settingsGroup) , _sequenceNumber (0) , _dirty (false) , _ignoreRecalc (false) , _complexDistance (0) , _cameraShots (0) , _cameraMinTriggerInterval (0) , _cameraCalc (vehicle) , _metaDataMap (FactMetaData::createMapFromJsonFile(QStringLiteral(":/json/TransectStyle.SettingsGroup.json"), this)) , _turnAroundDistanceFact (_settingsGroup, _metaDataMap[_vehicle->multiRotor() ? turnAroundDistanceMultiRotorName : turnAroundDistanceName]) , _cameraTriggerInTurnAroundFact(_settingsGroup, _metaDataMap[cameraTriggerInTurnAroundName]) , _hoverAndCaptureFact (_settingsGroup, _metaDataMap[hoverAndCaptureName]) , _refly90DegreesFact (_settingsGroup, _metaDataMap[refly90DegreesName]) { connect(&_turnAroundDistanceFact, &Fact::valueChanged, this, &TransectStyleComplexItem::_rebuildTransects); connect(&_hoverAndCaptureFact, &Fact::valueChanged, this, &TransectStyleComplexItem::_rebuildTransects); connect(&_refly90DegreesFact, &Fact::valueChanged, this, &TransectStyleComplexItem::_rebuildTransects); connect(&_surveyAreaPolygon, &QGCMapPolygon::pathChanged, this, &TransectStyleComplexItem::_rebuildTransects); connect(&_cameraTriggerInTurnAroundFact, &Fact::valueChanged, this, &TransectStyleComplexItem::_rebuildTransects); connect(_cameraCalc.adjustedFootprintSide(), &Fact::valueChanged, this, &TransectStyleComplexItem::_rebuildTransects); connect(_cameraCalc.adjustedFootprintFrontal(), &Fact::valueChanged, this, &TransectStyleComplexItem::_rebuildTransects); connect(&_turnAroundDistanceFact, &Fact::valueChanged, this, &TransectStyleComplexItem::_signalLastSequenceNumberChanged); connect(&_hoverAndCaptureFact, &Fact::valueChanged, this, &TransectStyleComplexItem::_signalLastSequenceNumberChanged); connect(&_refly90DegreesFact, &Fact::valueChanged, this, &TransectStyleComplexItem::_signalLastSequenceNumberChanged); connect(&_surveyAreaPolygon, &QGCMapPolygon::pathChanged, this, &TransectStyleComplexItem::_signalLastSequenceNumberChanged); connect(&_cameraTriggerInTurnAroundFact, &Fact::valueChanged, this, &TransectStyleComplexItem::_signalLastSequenceNumberChanged); connect(_cameraCalc.adjustedFootprintSide(), &Fact::valueChanged, this, &TransectStyleComplexItem::_signalLastSequenceNumberChanged); connect(_cameraCalc.adjustedFootprintFrontal(), &Fact::valueChanged, this, &TransectStyleComplexItem::_signalLastSequenceNumberChanged); connect(&_turnAroundDistanceFact, &Fact::valueChanged, this, &TransectStyleComplexItem::complexDistanceChanged); connect(&_hoverAndCaptureFact, &Fact::valueChanged, this, &TransectStyleComplexItem::complexDistanceChanged); connect(&_refly90DegreesFact, &Fact::valueChanged, this, &TransectStyleComplexItem::complexDistanceChanged); connect(&_surveyAreaPolygon, &QGCMapPolygon::pathChanged, this, &TransectStyleComplexItem::complexDistanceChanged); connect(&_turnAroundDistanceFact, &Fact::valueChanged, this, &TransectStyleComplexItem::greatestDistanceToChanged); connect(&_hoverAndCaptureFact, &Fact::valueChanged, this, &TransectStyleComplexItem::greatestDistanceToChanged); connect(&_refly90DegreesFact, &Fact::valueChanged, this, &TransectStyleComplexItem::greatestDistanceToChanged); connect(&_surveyAreaPolygon, &QGCMapPolygon::pathChanged, this, &TransectStyleComplexItem::greatestDistanceToChanged); connect(&_turnAroundDistanceFact, &Fact::valueChanged, this, &TransectStyleComplexItem::_setDirty); connect(&_cameraTriggerInTurnAroundFact, &Fact::valueChanged, this, &TransectStyleComplexItem::_setDirty); connect(&_hoverAndCaptureFact, &Fact::valueChanged, this, &TransectStyleComplexItem::_setDirty); connect(&_refly90DegreesFact, &Fact::valueChanged, this, &TransectStyleComplexItem::_setDirty); connect(&_surveyAreaPolygon, &QGCMapPolygon::pathChanged, this, &TransectStyleComplexItem::_setDirty); connect(&_surveyAreaPolygon, &QGCMapPolygon::dirtyChanged, this, &TransectStyleComplexItem::_setIfDirty); connect(&_cameraCalc, &CameraCalc::dirtyChanged, this, &TransectStyleComplexItem::_setIfDirty); connect(&_surveyAreaPolygon, &QGCMapPolygon::pathChanged, this, &TransectStyleComplexItem::coveredAreaChanged); connect(this, &TransectStyleComplexItem::transectPointsChanged, this, &TransectStyleComplexItem::complexDistanceChanged); connect(this, &TransectStyleComplexItem::transectPointsChanged, this, &TransectStyleComplexItem::greatestDistanceToChanged); } void TransectStyleComplexItem::_setCameraShots(int cameraShots) { if (_cameraShots != cameraShots) { _cameraShots = cameraShots; emit cameraShotsChanged(); } } void TransectStyleComplexItem::setDirty(bool dirty) { if (!dirty) { _surveyAreaPolygon.setDirty(false); _cameraCalc.setDirty(false); } if (_dirty != dirty) { _dirty = dirty; emit dirtyChanged(_dirty); } } void TransectStyleComplexItem::_save(QJsonObject& complexObject) { complexObject[turnAroundDistanceName] = _turnAroundDistanceFact.rawValue().toDouble(); complexObject[cameraTriggerInTurnAroundName] = _cameraTriggerInTurnAroundFact.rawValue().toBool(); complexObject[hoverAndCaptureName] = _hoverAndCaptureFact.rawValue().toBool(); complexObject[refly90DegreesName] = _refly90DegreesFact.rawValue().toBool(); QJsonObject cameraCalcObject; _cameraCalc.save(cameraCalcObject); complexObject[_jsonCameraCalcKey] = cameraCalcObject; } void TransectStyleComplexItem::setSequenceNumber(int sequenceNumber) { if (_sequenceNumber != sequenceNumber) { _sequenceNumber = sequenceNumber; emit sequenceNumberChanged(sequenceNumber); emit lastSequenceNumberChanged(lastSequenceNumber()); } } bool TransectStyleComplexItem::_load(const QJsonObject& complexObject, QString& errorString) { QList keyInfoList = { { turnAroundDistanceName, QJsonValue::Double, true }, { cameraTriggerInTurnAroundName, QJsonValue::Bool, true }, { hoverAndCaptureName, QJsonValue::Bool, true }, { refly90DegreesName, QJsonValue::Bool, true }, { _jsonCameraCalcKey, QJsonValue::Object, true }, }; if (!JsonHelper::validateKeys(complexObject, keyInfoList, errorString)) { return false; } if (!_cameraCalc.load(complexObject[_jsonCameraCalcKey].toObject(), errorString)) { return false; } _turnAroundDistanceFact.setRawValue (complexObject[turnAroundDistanceName].toDouble()); _cameraTriggerInTurnAroundFact.setRawValue (complexObject[cameraTriggerInTurnAroundName].toBool()); _hoverAndCaptureFact.setRawValue (complexObject[hoverAndCaptureName].toBool()); _hoverAndCaptureFact.setRawValue (complexObject[refly90DegreesName].toBool()); return true; } double TransectStyleComplexItem::greatestDistanceTo(const QGeoCoordinate &other) const { double greatestDistance = 0.0; for (int i=0; i<_transectPoints.count(); i++) { QGeoCoordinate vertex = _transectPoints[i].value(); double distance = vertex.distanceTo(other); if (distance > greatestDistance) { greatestDistance = distance; } } return greatestDistance; } void TransectStyleComplexItem::setMissionFlightStatus(MissionController::MissionFlightStatus_t& missionFlightStatus) { ComplexMissionItem::setMissionFlightStatus(missionFlightStatus); if (!qFuzzyCompare(_cruiseSpeed, missionFlightStatus.vehicleSpeed)) { _cruiseSpeed = missionFlightStatus.vehicleSpeed; emit timeBetweenShotsChanged(); } } void TransectStyleComplexItem::_setDirty(void) { setDirty(true); } void TransectStyleComplexItem::_setIfDirty(bool dirty) { if (dirty) { setDirty(true); } } void TransectStyleComplexItem::applyNewAltitude(double newAltitude) { Q_UNUSED(newAltitude); // FIXME: NYI //_altitudeFact.setRawValue(newAltitude); } double TransectStyleComplexItem::timeBetweenShots(void) { return _cruiseSpeed == 0 ? 0 : _cameraCalc.adjustedFootprintSide()->rawValue().toDouble() / _cruiseSpeed; } void TransectStyleComplexItem::_updateCoordinateAltitudes(void) { emit coordinateChanged(coordinate()); emit exitCoordinateChanged(exitCoordinate()); } void TransectStyleComplexItem::_signalLastSequenceNumberChanged(void) { emit lastSequenceNumberChanged(lastSequenceNumber()); } double TransectStyleComplexItem::coveredArea(void) const { return _surveyAreaPolygon.area(); } bool TransectStyleComplexItem::_hasTurnaround(void) const { return _turnaroundDistance() > 0; } double TransectStyleComplexItem::_turnaroundDistance(void) const { return _turnAroundDistanceFact.rawValue().toDouble(); } bool TransectStyleComplexItem::hoverAndCaptureAllowed(void) const { return _vehicle->multiRotor() || _vehicle->vtol(); } source/layout/Box.cpp /* * Copyright (c) 2009-2016, * 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 software author 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 "Box.h" #include #include #include #include using namespace std; using namespace math; namespace layout{ void Box::SetStyle(Style *_style){ if (style){ unref(style); style=0; } if (_style){ style = static_cast(_style->ref()); } } void Box::Draw(Context *context, const Rect2& parent_rect ){ DrawChildren(context, parent_rect); } void Box::DrawChildren(Context *context, const math::Rect2& parent_rect ){ Rect2 child_rect = rect.impose( parent_rect ); for (list::iterator i = child.begin(); i != child.end(); i++){ (*i)->Draw(context, child_rect); } } void Box::AddChild(Box* box){ child.push_back(box); } Box::Box(const char* _name, float x, float y, float width, float height){ style = 0; name = _name; rect = Rect2(x, y, x+width, y+height); helper_only = false; locked = false; } Box::~Box(){ SetStyle(0); for (list::iterator i = child.begin(); i != child.end(); i++){ unref(*i); } } Box* Box::GetNamedBox(const char *name_){ if (name.compare(name_) == 0){ return this; } Box* r; for (list::iterator i = child.begin(); i != child.end(); i++){ if ((r = (*i)->GetNamedBox(name_))){ if (!r->helper_only) return r; } } return 0; } Box* Box::GetBoxAt(const Vec2& point){ if (rect.isInside(point.x, point.y)){ Vec2 transformed_point = Vec2((point.x-rect.getX()) / rect.getWidth(), (point.y-rect.getY()) / rect.getHeight()); Box* r; for (list::iterator i = child.begin(); i != child.end(); i++){ if ((r = (*i)->GetBoxAt(transformed_point))){ if (!r->helper_only) return r; } } if (typeid(*this) == typeid(Box)) //do not match Box, because it is invisible return 0; else return this; }else{ return 0; } } void Text::Draw(Context *context, const Rect2& parent_rect ){ Rect2 draw_rect = rect.impose( parent_rect ); cairo_t *cr = context->getCairo(); if (text != ""){ if (helper_only){ cairo_select_font_face(cr, "sans-serif", CAIRO_FONT_SLANT_ITALIC, CAIRO_FONT_WEIGHT_NORMAL); }else{ cairo_select_font_face(cr, "sans-serif", CAIRO_FONT_SLANT_NORMAL, CAIRO_FONT_WEIGHT_NORMAL); } if (style){ cairo_set_font_size(cr, style->font_size * draw_rect.getHeight()); Color color; if (context->getTransformationChain()){ context->getTransformationChain()->apply(&style->color, &color); }else{ color_copy(&style->color, &color); } cairo_set_source_rgb(cr, boost::math::round(color.rgb.red * 255.0) / 255.0, boost::math::round(color.rgb.green * 255.0) / 255.0, boost::math::round(color.rgb.blue * 255.0) / 255.0); }else{ cairo_set_font_size(cr, draw_rect.getHeight()); cairo_set_source_rgb(cr, 0, 0, 0); } cairo_text_extents_t extents; cairo_text_extents(cr, text.c_str(), &extents); cairo_move_to(cr, draw_rect.getX() + draw_rect.getWidth()/2 - (extents.width/2 + extents.x_bearing), draw_rect.getY() + draw_rect.getHeight()/2 - (extents.height/2 + extents.y_bearing)); cairo_show_text(cr, text.c_str()); if (style && style->GetBox() == this){ cairo_rectangle(cr, draw_rect.getX()+1, draw_rect.getY()+1, draw_rect.getWidth()-2, draw_rect.getHeight()-2); cairo_set_source_rgb(cr, 1, 1, 1); cairo_set_line_width(cr, 2); cairo_stroke(cr); } } DrawChildren(context, parent_rect); } void Fill::Draw(Context *context, const Rect2& parent_rect ){ Rect2 draw_rect = rect.impose( parent_rect ); cairo_t *cr = context->getCairo(); Color color; if (context->getTransformationChain()){ context->getTransformationChain()->apply(&style->color, &color); }else{ color_copy(&style->color, &color); } cairo_set_source_rgb(cr, boost::math::round(color.rgb.red * 255.0) / 255.0, boost::math::round(color.rgb.green * 255.0) / 255.0, boost::math::round(color.rgb.blue * 255.0) / 255.0); cairo_rectangle(cr, draw_rect.getX(), draw_rect.getY(), draw_rect.getWidth(), draw_rect.getHeight()); cairo_fill(cr); if (style->GetBox() == this){ cairo_rectangle(cr, draw_rect.getX()+1, draw_rect.getY()+1, draw_rect.getWidth()-2, draw_rect.getHeight()-2); cairo_set_source_rgb(cr, 1, 1, 1); cairo_set_line_width(cr, 2); cairo_stroke(cr); } DrawChildren(context, parent_rect); } } /****************************************************************************/ /** * @file ImageFileDirectory.cpp * @author */ /*---------------------------------------------------------------------------- * * Copyright (c) Visualization Laboratory, Kyoto University. * All rights reserved. * See http://www.viz.media.kyoto-u.ac.jp/kvs/copyright/ for details. * * $Id: ImageFileDirectory.cpp 1312 2012-09-18 15:33:43Z $ */ /****************************************************************************/ #include "ImageFileDirectory.h" namespace kvs { namespace tiff { ImageFileDirectory::ImageFileDirectory(): m_offset( 0 ) { } ImageFileDirectory::ImageFileDirectory( std::ifstream& ifs ) { this->read( ifs ); } const std::list& ImageFileDirectory::entryList() const { return m_entry_list; } kvs::UInt32 ImageFileDirectory::offset() const { return m_offset; } void ImageFileDirectory::print( std::ostream& os, const kvs::Indent& indent ) const { kvs::tiff::ImageFileDirectory::EntryList::const_iterator entry = m_entry_list.begin(); kvs::tiff::ImageFileDirectory::EntryList::const_iterator last = m_entry_list.end(); while ( entry != last ) { entry->print( os, indent ); ++entry; } } bool ImageFileDirectory::read( std::ifstream& ifs ) { kvs::UInt16 nentries = 0; ifs.read( reinterpret_cast( &nentries ), 2 ); if ( ifs.gcount() != 2 ) return false; for( size_t i = 0; i < nentries; i++ ) { m_entry_list.push_back( kvs::tiff::Entry( ifs ) ); } ifs.read( reinterpret_cast( &m_offset ), 4 ); if ( ifs.gcount() != 4 ) return false; if ( m_offset > 0 ) { ifs.seekg( m_offset, std::ios::beg ); } return true; } } // end of namesapce tiff } // end of namespace kvs pierrelouys/PSP-MAME4ALL1-10 #include "driver.h" #include "vidhrdw/generic.h" static int gfxbank; void sichuan2_bankswitch_w(int offset,int data) { int bankaddress; unsigned char *RAM = Machine->memory_region[Machine->drv->cpu[0].memory_region]; /* bits 0-2 select ROM bank */ bankaddress = 0x10000 + (data & 0x07) * 0x4000; cpu_setbank(1,&RAM[bankaddress]); /* bits 3-5 select gfx bank */ if (gfxbank != ((data & 0x38) >> 3)) { gfxbank = (data & 0x38) >> 3; fast_memset(dirtybuffer,1,videoram_size); } /* bits 6-7 unknown */ } void sichuan2_paletteram_w(int offset,int data) { int r,g,b; paletteram[offset] = data; offset &= 0xff; r = paletteram[offset+0x000] & 0x1f; g = paletteram[offset+0x100] & 0x1f; b = paletteram[offset+0x200] & 0x1f; r = (r << 3) | (r >> 2); g = (g << 3) | (g >> 2); b = (b << 3) | (b >> 2); palette_change_color(offset,r,g,b); } void sichuan2_vh_screenrefresh(struct osd_bitmap *bitmap,int full_refresh) { int offs; if (palette_recalc()) fast_memset(dirtybuffer,1,videoram_size); /* for every character in the Video RAM, check if it has been modified */ /* since last time and update it accordingly. */ for (offs = videoram_size-2;offs >= 0;offs -= 2) { if (dirtybuffer[offs] || dirtybuffer[offs+1]) { int sx,sy; dirtybuffer[offs] = dirtybuffer[offs+1] = 0; sx = (offs/2) % 64; sy = (offs/2) / 64; drawgfx(tmpbitmap,Machine->gfx[gfxbank], videoram[offs] + ((videoram[offs+1] & 0x0f) << 8), (videoram[offs+1] & 0xf0) >> 4, 0,0, 8*sx,8*sy, &Machine->drv->visible_area,TRANSPARENCY_NONE,0); } } /* copy the character mapped graphics */ copybitmap(bitmap,tmpbitmap,0,0,0,0,&Machine->drv->visible_area,TRANSPARENCY_NONE,0); } // Copyright snsinfu 2018. // 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 "catch.hpp" #include "../include/point.hpp" TEST_CASE("point - is default constructible as the origin") { cxx::point pt; CHECK(pt.x == 0); CHECK(pt.y == 0); CHECK(pt.z == 0); } TEST_CASE("point - is constructible from coordinate values") { cxx::point pt = {1, 2, 3}; CHECK(pt.x == 1); CHECK(pt.y == 2); CHECK(pt.z == 3); } TEST_CASE("point - provides mutable element references") { cxx::point pt = {1, 2, 3}; CHECK(&pt[0] == &pt.x); CHECK(&pt[1] == &pt.y); CHECK(&pt[2] == &pt.z); } TEST_CASE("point - provides const element references") { cxx::point const pt = {1, 2, 3}; CHECK(&pt[0] == &pt.x); CHECK(&pt[1] == &pt.y); CHECK(&pt[2] == &pt.z); } TEST_CASE("point::vector - returns coordinate vector") { cxx::point const pt = {1, 2, 3}; cxx::vector const vec = pt.vector(); CHECK(vec.x == pt.x); CHECK(vec.y == pt.y); CHECK(vec.z == pt.z); } TEST_CASE("point - may be translated by a vector") { cxx::point pt = {2, 4, 6}; pt += cxx::vector {5, 1, 3}; CHECK(pt.x == 7); CHECK(pt.y == 5); CHECK(pt.z == 9); } TEST_CASE("point - may be translated by a negated vector") { cxx::point pt = {2, 4, 6}; pt -= cxx::vector {3, 1, 5}; CHECK(pt.x == -1); CHECK(pt.y == 3); CHECK(pt.z == 1); } TEST_CASE("point - supports translation by vector addition") { cxx::point const pt = {2, 4, 6}; cxx::vector const vec = {5, 1, 3}; cxx::point const dest = pt + vec; CHECK(dest.x == 7); CHECK(dest.y == 5); CHECK(dest.z == 9); } TEST_CASE("point - supports translation by vector subtraction") { cxx::point const pt = {2, 4, 6}; cxx::vector const vec = {3, 1, 5}; cxx::point const dest = pt - vec; CHECK(dest.x == -1); CHECK(dest.y == 3); CHECK(dest.z == 1); } TEST_CASE("point - difference gives translation vector") { cxx::point const pa = {2, 4, 6}; cxx::point const pb = {7, 5, 3}; cxx::vector const vec = pa - pb; CHECK(vec.x == -5); CHECK(vec.y == -1); CHECK(vec.z == 3); } TEST_CASE("point::squared_distance - returns squared Euclidean distance") { cxx::point const pa = {2, 4, 6}; cxx::point const pb = {7, 5, 3}; CHECK(pa.squared_distance(pb) == 35); } TEST_CASE("point::distance - returns Euclidean distance") { cxx::point const pa = {2, 4, 6}; cxx::point const pb = {7, 5, 3}; CHECK(pa.distance(pb) == Approx(5.916079783)); } TEST_CASE("squared_distance - returns squared Euclidean distance between points") { cxx::point const pa = {2, 4, 6}; cxx::point const pb = {7, 5, 3}; CHECK(cxx::squared_distance(pa, pb) == 35); } TEST_CASE("distance - returns Euclidean distance between points") { cxx::point const pa = {2, 4, 6}; cxx::point const pb = {7, 5, 3}; CHECK(cxx::distance(pa, pb) == Approx(5.916079783)); } TEST_CASE("point - is formattable") { cxx::point const pt {1.2, 3.4, 5.6}; std::ostringstream str; str << '(' << pt << ')'; CHECK(str.str() == "(1.2 3.4 5.6)"); } TEST_CASE("point - is parsable") { cxx::point pt; std::istringstream str{"1.2 3.4 5.6"}; str >> pt; CHECK(pt.x == Approx(1.2)); CHECK(pt.y == Approx(3.4)); CHECK(pt.z == Approx(5.6)); } Hamdor/actor-frameworklibcaf_core/caf/byte_span.hpp1000+ // This file is part of CAF, the C++ Actor Framework. See the file LICENSE in // the main distribution directory for license terms and copyright or visit // https://github.com/actor-framework/actor-framework/blob/master/LICENSE. #pragma once #include "caf/byte.hpp" #include "caf/span.hpp" namespace caf { /// Convenience alias for referring to a writable sequence of bytes. using byte_span = span; /// Convenience alias for referring to a read-only sequence of bytes. using const_byte_span = span; } // namespace caf 10-100 #include "PeripheralBase.h" #include #include #include "Bluez.h" using namespace SimpleBLE; using namespace std::chrono_literals; PeripheralBase::PeripheralBase(std::shared_ptr device) : device_(device) {} PeripheralBase::~PeripheralBase() { // TODO: A more extensive cleanup process is probably needed. device_->clear_on_disconnected(); device_->clear_on_services_resolved(); } std::string PeripheralBase::identifier() { return device_->name(); } BluetoothAddress PeripheralBase::address() { return device_->address(); } void PeripheralBase::connect() { // Set the OnDisconnected callback device_->set_on_disconnected([this]() { this->disconnection_cv_.notify_all(); if (this->callback_on_disconnected_) { this->callback_on_disconnected_(); } }); // Set the OnServicesResolved callback device_->set_on_services_resolved([this]() { this->connection_cv_.notify_all(); }); // Attempt to connect to the device. for (size_t i = 0; i < 5; i++) { if (_attempt_connect()) { break; } } if (!is_connected()) { throw Exception::OperationFailed(); } } void PeripheralBase::disconnect() { // Attempt to connect to the device. for (size_t i = 0; i < 5; i++) { if (_attempt_disconnect()) { break; } } if (is_connected()) { throw Exception::OperationFailed(); } } bool PeripheralBase::is_connected() { // NOTE: For Bluez, a device being connected means that it's both // connected and services have been resolved. return device_->connected() && device_->services_resolved(); } bool PeripheralBase::is_connectable() { return device_->name() != ""; } std::vector PeripheralBase::services() { std::vector service_list; for (auto bluez_service : device_->services()) { BluetoothService service; service.uuid = bluez_service->uuid(); for (auto bluez_characteristic : bluez_service->characteristics()) { service.characteristics.push_back(bluez_characteristic->uuid()); } service_list.push_back(service); } return service_list; } std::map PeripheralBase::manufacturer_data() { std::map manufacturer_data; for (auto& [manufacturer_id, value_array] : device_->manufacturer_data()) { manufacturer_data[manufacturer_id] = ByteArray((const char*)value_array.data(), value_array.size()); } return manufacturer_data; } ByteArray PeripheralBase::read(BluetoothUUID service, BluetoothUUID characteristic) { // TODO: Check if the characteristic is readable. return _get_characteristic(service, characteristic)->value(); } void PeripheralBase::write_request(BluetoothUUID service, BluetoothUUID characteristic, ByteArray data) { // TODO: Check if the characteristic is writable. _get_characteristic(service, characteristic)->write_request(data); } void PeripheralBase::write_command(BluetoothUUID service, BluetoothUUID characteristic, ByteArray data) { // TODO: Check if the characteristic is writable. _get_characteristic(service, characteristic)->write_command(data); } void PeripheralBase::notify(BluetoothUUID service, BluetoothUUID characteristic, std::function callback) { // TODO: What to do if the characteristic is already being notified? // TODO: Check if the property can be notified. auto characteristic_object = _get_characteristic(service, characteristic); characteristic_object->set_on_value_changed([callback](SimpleBluez::ByteArray new_value) { callback(new_value); }); characteristic_object->start_notify(); } void PeripheralBase::indicate(BluetoothUUID service, BluetoothUUID characteristic, std::function callback) { notify(service, characteristic, callback); } void PeripheralBase::unsubscribe(BluetoothUUID service, BluetoothUUID characteristic) { // TODO: What to do if the characteristic is not being notified? auto characteristic_object = _get_characteristic(service, characteristic); characteristic_object->stop_notify(); // Wait for the characteristic to stop notifying. // TODO: Upgrade SimpleDBus to provide a way to wait for this signal. auto timeout = std::chrono::system_clock::now() + 5s; while (characteristic_object->notifying() && std::chrono::system_clock::now() < timeout) { std::this_thread::sleep_for(50ms); } } void PeripheralBase::set_callback_on_connected(std::function on_connected) { callback_on_connected_ = on_connected; } void PeripheralBase::set_callback_on_disconnected(std::function on_disconnected) { callback_on_disconnected_ = on_disconnected; } // Private methods bool PeripheralBase::_attempt_connect() { try { device_->connect(); } catch (SimpleDBus::Exception::SendFailed& e) { return false; } // Wait for the connection to be confirmed. // The condition variable will return false if the connection was not established. std::unique_lock lock(connection_mutex_); return connection_cv_.wait_for(lock, 2s, [this]() { return is_connected(); }); } bool PeripheralBase::_attempt_disconnect() { device_->disconnect(); // Wait for the disconnection to be confirmed. // The condition variable will return false if the connection is still active. std::unique_lock lock(disconnection_mutex_); return disconnection_cv_.wait_for(lock, 1s, [this]() { return !is_connected(); }); } std::shared_ptr PeripheralBase::_get_characteristic(BluetoothUUID service_uuid, BluetoothUUID characteristic_uuid) { try { return device_->get_characteristic(service_uuid, characteristic_uuid); } catch (SimpleBluez::Exception::ServiceNotFoundException& e) { throw Exception::ServiceNotFound(service_uuid); } catch (SimpleBluez::Exception::CharacteristicNotFoundException& e) { throw Exception::CharacteristicNotFound(characteristic_uuid); } } libskiwi/reg_alloc.cpp #include "reg_alloc.h" #include SKIWI_BEGIN reg_alloc::reg_alloc(const std::vector& usable_registers, uint32_t number_of_locals) : available_registers(usable_registers), nr_locals(number_of_locals) { make_all_available(); } reg_alloc::~reg_alloc() { } bool reg_alloc::free_register_available() const { return !free_registers.empty(); } bool reg_alloc::free_local_available() const { return !free_locals.empty(); } ASM::asmcode::operand reg_alloc::get_next_available_register() { if (!free_register_available()) throw std::runtime_error("no register available"); assert(!free_registers.empty()); auto it = (--free_registers.end()); uint8_t reg_value = *it; free_registers.erase(it); return available_registers[reg_value]; } void reg_alloc::make_register_available(ASM::asmcode::operand reg) { assert(free_registers.find(register_to_index[reg]) == free_registers.end()); assert(register_to_index.find(reg) != register_to_index.end()); free_registers.insert(register_to_index.at(reg)); } uint32_t reg_alloc::get_next_available_local() { if (!free_local_available()) throw std::runtime_error("no local available"); assert(!free_locals.empty()); auto it = (--free_locals.end()); uint32_t local_value = *it; free_locals.erase(it); return local_value; } void reg_alloc::make_local_available(uint32_t val) { assert(free_locals.find(val) == free_locals.end()); free_locals.insert(val); } uint8_t reg_alloc::number_of_registers() { return (uint8_t)available_registers.size(); } uint32_t reg_alloc::number_of_locals() { return nr_locals; } uint8_t reg_alloc::number_of_available_registers() { return (uint8_t)free_registers.size(); } uint32_t reg_alloc::number_of_available_locals() { return (uint32_t)free_locals.size(); } bool reg_alloc::is_free_register(ASM::asmcode::operand reg) { auto it = register_to_index.find(reg); if (it == register_to_index.end()) return true; return (free_registers.find(it->second) != free_registers.end()); } bool reg_alloc::is_free_local(uint32_t local_id) { return (free_locals.find(local_id) != free_locals.end()); } void reg_alloc::make_all_available() { for (uint8_t i = 0; i < (uint8_t)available_registers.size(); ++i) { register_to_index[available_registers[i]] = i; free_registers.insert(i); } for (uint32_t i = 0; i < nr_locals; ++i) free_locals.insert(i); } void reg_alloc::make_register_unavailable(ASM::asmcode::operand reg) { free_registers.erase(register_to_index[reg]); } void reg_alloc::make_local_unavailable(uint32_t val) { free_locals.erase(val); } SKIWI_END wedataintelligence/vivaldi-source // Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/site_details.h" #include #include #include #include "base/bind_helpers.h" #include "base/files/file_path.h" #include "base/macros.h" #include "base/message_loop/message_loop.h" #include "base/path_service.h" #include "base/strings/stringprintf.h" #include "base/test/histogram_tester.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/extensions/extension_browsertest.h" #include "chrome/browser/extensions/test_extension_dir.h" #include "chrome/browser/metrics/metrics_memory_details.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/common/extensions/extension_process_policy.h" #include "chrome/common/url_constants.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/ui_test_utils.h" #include "components/metrics/metrics_service.h" #include "components/variations/metrics_util.h" #include "content/public/browser/notification_service.h" #include "content/public/browser/render_process_host.h" #include "content/public/common/content_switches.h" #include "content/public/test/browser_test_utils.h" #include "content/public/test/test_utils.h" #include "extensions/common/switches.h" #include "extensions/common/value_builder.h" #include "net/dns/mock_host_resolver.h" #include "net/test/embedded_test_server/embedded_test_server.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" using base::Bucket; using content::WebContents; using extensions::DictionaryBuilder; using extensions::Extension; using extensions::ListBuilder; using extensions::TestExtensionDir; using testing::ContainerEq; using testing::ElementsAre; namespace { class TestMemoryDetails : public MetricsMemoryDetails { public: TestMemoryDetails() : MetricsMemoryDetails(base::Bind(&base::DoNothing), nullptr) {} void StartFetchAndWait() { uma_.reset(new base::HistogramTester()); StartFetch(FROM_CHROME_ONLY); content::RunMessageLoop(); } // Returns a HistogramTester which observed the most recent call to // StartFetchAndWait(). base::HistogramTester* uma() { return uma_.get(); } int GetOutOfProcessIframeCount() { std::vector buckets = uma_->GetAllSamples("SiteIsolation.OutOfProcessIframes"); CHECK_EQ(1U, buckets.size()); return buckets[0].min; } size_t CountPageTitles() { size_t count = 0; for (const ProcessMemoryInformation& process : ChromeBrowser()->processes) { if (process.process_type == content::PROCESS_TYPE_RENDERER) { count += process.titles.size(); } } return count; } private: ~TestMemoryDetails() override {} void OnDetailsAvailable() override { MetricsMemoryDetails::OnDetailsAvailable(); // Exit the loop initiated by StartFetchAndWait(). base::MessageLoop::current()->QuitWhenIdle(); } scoped_ptr uma_; DISALLOW_COPY_AND_ASSIGN(TestMemoryDetails); }; } // namespace class SiteDetailsBrowserTest : public ExtensionBrowserTest { public: SiteDetailsBrowserTest() {} ~SiteDetailsBrowserTest() override {} void SetUpOnMainThread() override { host_resolver()->AddRule("*", "127.0.0.1"); // Add content/test/data so we can use cross_site_iframe_factory.html base::FilePath test_data_dir; ASSERT_TRUE(PathService::Get(base::DIR_SOURCE_ROOT, &test_data_dir)); embedded_test_server()->ServeFilesFromDirectory( test_data_dir.AppendASCII("content/test/data/")); ASSERT_TRUE(embedded_test_server()->Start()); } // Create and install an extension that has a couple of web-accessible // resources and, optionally, a background process. const Extension* CreateExtension(const std::string& name, bool has_background_process) { scoped_ptr dir(new TestExtensionDir); DictionaryBuilder manifest; manifest.Set("name", name) .Set("version", "1.0") .Set("manifest_version", 2) .Set("web_accessible_resources", std::move(ListBuilder() .Append("blank_iframe.html") .Append("http_iframe.html") .Append("two_http_iframes.html"))); if (has_background_process) { manifest.Set( "background", std::move(DictionaryBuilder().Set( "scripts", std::move(ListBuilder().Append("script.js"))))); dir->WriteFile(FILE_PATH_LITERAL("script.js"), "console.log('" + name + " running');"); } dir->WriteFile(FILE_PATH_LITERAL("blank_iframe.html"), base::StringPrintf("%s, blank iframe:" " " " ", name.c_str())); std::string iframe_url = embedded_test_server() ->GetURL("w.com", "/cross_site_iframe_factory.html?w") .spec(); std::string iframe_url2 = embedded_test_server() ->GetURL("x.com", "/cross_site_iframe_factory.html?x") .spec(); dir->WriteFile( FILE_PATH_LITERAL("http_iframe.html"), base::StringPrintf("%s, http:// iframe:" " " "", name.c_str(), iframe_url.c_str())); dir->WriteFile(FILE_PATH_LITERAL("two_http_iframes.html"), base::StringPrintf( "%s, two http:// iframes:" " " " " "", name.c_str(), iframe_url.c_str(), iframe_url2.c_str())); dir->WriteManifest(manifest.ToJSON()); const Extension* extension = LoadExtension(dir->unpacked_path()); EXPECT_TRUE(extension); temp_dirs_.push_back(dir.release()); return extension; } const Extension* CreateHostedApp(const std::string& name, const GURL& app_url) { scoped_ptr dir(new TestExtensionDir); DictionaryBuilder manifest; manifest.Set("name", name) .Set("version", "1.0") .Set("manifest_version", 2) .Set("app", std::move(DictionaryBuilder() .Set("urls", std::move(ListBuilder().Append(app_url.spec()))) .Set("launch", std::move(DictionaryBuilder().Set( "web_url", app_url.spec()))))); dir->WriteManifest(manifest.ToJSON()); const Extension* extension = LoadExtension(dir->unpacked_path()); EXPECT_TRUE(extension); temp_dirs_.push_back(dir.release()); return extension; } int GetRenderProcessCount() { int count = 0; for (content::RenderProcessHost::iterator it( content::RenderProcessHost::AllHostsIterator()); !it.IsAtEnd(); it.Advance()) { count++; } return count; } // Checks whether the test run is part of a field trial with |trial_name|. bool IsInTrial(const std::string& trial_name) { uint32_t trial = metrics::HashName(trial_name); std::vector synthetic_trials; g_browser_process->metrics_service() ->GetCurrentSyntheticFieldTrialsForTesting(&synthetic_trials); for (const auto& entry : synthetic_trials) { if (trial == entry.name) return true; } return false; } // Similar to IsInTrial but checks that the correct group is present as well. bool IsInTrialGroup(const std::string& trial_name, const std::string& group_name) { uint32_t trial = metrics::HashName(trial_name); uint32_t group = metrics::HashName(group_name); std::vector synthetic_trials; g_browser_process->metrics_service() ->GetCurrentSyntheticFieldTrialsForTesting(&synthetic_trials); for (const auto& entry : synthetic_trials) { if (trial == entry.name && group == entry.group) return true; } return false; } private: ScopedVector temp_dirs_; DISALLOW_COPY_AND_ASSIGN(SiteDetailsBrowserTest); }; MATCHER_P(EqualsIfExtensionsIsolated, expected, "") { if (content::AreAllSitesIsolatedForTesting()) return arg >= expected; if (extensions::IsIsolateExtensionsEnabled()) return arg == expected; return true; } MATCHER_P(EqualsIfSitePerProcess, expected, "") { return !content::AreAllSitesIsolatedForTesting() || expected == arg; } // Test the accuracy of SiteDetails process estimation, in the presence of // multiple iframes, navigation, multiple BrowsingInstances, and multiple tabs // in the same BrowsingInstance. IN_PROC_BROWSER_TEST_F(SiteDetailsBrowserTest, ManyIframes) { // Page with 14 nested oopifs across 9 sites (a.com through i.com). // None of these are https. GURL abcdefghi_url = embedded_test_server()->GetURL( "a.com", "/cross_site_iframe_factory.html?a(b(a(b,c,d,e,f,g,h)),c,d,e,i(f))"); ui_test_utils::NavigateToURL(browser(), abcdefghi_url); // Get the metrics. scoped_refptr details = new TestMemoryDetails(); details->StartFetchAndWait(); EXPECT_EQ(1U, details->CountPageTitles()); EXPECT_THAT( details->uma()->GetAllSamples("SiteIsolation.BrowsingInstanceCount"), ElementsAre(Bucket(1, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.CurrentRendererProcessCount"), ElementsAre(Bucket(GetRenderProcessCount(), 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateNothingProcessCountEstimate"), ElementsAre(Bucket(1, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateAllSitesProcessCountEstimate"), ElementsAre(Bucket(9, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateAllSitesProcessCountLowerBound"), ElementsAre(Bucket(9, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateAllSitesProcessCountNoLimit"), ElementsAre(Bucket(9, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateHttpsSitesProcessCountEstimate"), ElementsAre(Bucket(1, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateHttpsSitesProcessCountLowerBound"), ElementsAre(Bucket(1, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateHttpsSitesProcessCountNoLimit"), ElementsAre(Bucket(1, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateExtensionsProcessCountEstimate"), ElementsAre(Bucket(1, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateExtensionsProcessCountLowerBound"), ElementsAre(Bucket(1, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateExtensionsProcessCountNoLimit"), ElementsAre(Bucket(1, 1))); EXPECT_THAT(GetRenderProcessCount(), EqualsIfExtensionsIsolated(1)); EXPECT_THAT(GetRenderProcessCount(), EqualsIfSitePerProcess(9)); EXPECT_THAT(details->GetOutOfProcessIframeCount(), EqualsIfExtensionsIsolated(0)); EXPECT_THAT(details->GetOutOfProcessIframeCount(), EqualsIfSitePerProcess(14)); // Navigate to a different, disjoint set of 7 sites. GURL pqrstuv_url = embedded_test_server()->GetURL( "p.com", "/cross_site_iframe_factory.html?p(q(r),r(s),s(t),t(q),u(u),v(p))"); ui_test_utils::NavigateToURL(browser(), pqrstuv_url); details = new TestMemoryDetails(); details->StartFetchAndWait(); EXPECT_EQ(1U, details->CountPageTitles()); EXPECT_THAT( details->uma()->GetAllSamples("SiteIsolation.BrowsingInstanceCount"), ElementsAre(Bucket(1, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.CurrentRendererProcessCount"), ElementsAre(Bucket(GetRenderProcessCount(), 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateNothingProcessCountEstimate"), ElementsAre(Bucket(1, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateAllSitesProcessCountEstimate"), ElementsAre(Bucket(7, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateAllSitesProcessCountLowerBound"), ElementsAre(Bucket(7, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateAllSitesProcessCountNoLimit"), ElementsAre(Bucket(7, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateHttpsSitesProcessCountEstimate"), ElementsAre(Bucket(1, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateHttpsSitesProcessCountLowerBound"), ElementsAre(Bucket(1, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateHttpsSitesProcessCountNoLimit"), ElementsAre(Bucket(1, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateExtensionsProcessCountEstimate"), ElementsAre(Bucket(1, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateExtensionsProcessCountLowerBound"), ElementsAre(Bucket(1, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateExtensionsProcessCountNoLimit"), ElementsAre(Bucket(1, 1))); EXPECT_THAT(GetRenderProcessCount(), EqualsIfExtensionsIsolated(1)); EXPECT_THAT(GetRenderProcessCount(), EqualsIfSitePerProcess(7)); EXPECT_THAT(details->GetOutOfProcessIframeCount(), EqualsIfExtensionsIsolated(0)); EXPECT_THAT(details->GetOutOfProcessIframeCount(), EqualsIfSitePerProcess(11)); // Open a second tab (different BrowsingInstance) with 4 sites (a through d). GURL abcd_url = embedded_test_server()->GetURL( "a.com", "/cross_site_iframe_factory.html?a(b(c(d())))"); AddTabAtIndex(1, abcd_url, ui::PAGE_TRANSITION_TYPED); details = new TestMemoryDetails(); details->StartFetchAndWait(); EXPECT_EQ(2U, details->CountPageTitles()); EXPECT_THAT( details->uma()->GetAllSamples("SiteIsolation.BrowsingInstanceCount"), ElementsAre(Bucket(2, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.CurrentRendererProcessCount"), ElementsAre(Bucket(GetRenderProcessCount(), 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateNothingProcessCountEstimate"), ElementsAre(Bucket(2, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateAllSitesProcessCountEstimate"), ElementsAre(Bucket(11, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateAllSitesProcessCountLowerBound"), ElementsAre(Bucket(11, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateAllSitesProcessCountNoLimit"), ElementsAre(Bucket(11, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateHttpsSitesProcessCountEstimate"), ElementsAre(Bucket(2, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateHttpsSitesProcessCountLowerBound"), ElementsAre(Bucket(1, 1))); // TODO(nick): This should be 2. EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateHttpsSitesProcessCountNoLimit"), ElementsAre(Bucket(2, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateExtensionsProcessCountEstimate"), ElementsAre(Bucket(2, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateExtensionsProcessCountLowerBound"), ElementsAre(Bucket(1, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateExtensionsProcessCountNoLimit"), ElementsAre(Bucket(2, 1))); EXPECT_THAT(GetRenderProcessCount(), EqualsIfExtensionsIsolated(2)); EXPECT_THAT(GetRenderProcessCount(), EqualsIfSitePerProcess(11)); EXPECT_THAT(details->GetOutOfProcessIframeCount(), EqualsIfExtensionsIsolated(0)); EXPECT_THAT(details->GetOutOfProcessIframeCount(), EqualsIfSitePerProcess(14)); // Open a third tab (different BrowsingInstance) with the same 4 sites. AddTabAtIndex(2, abcd_url, ui::PAGE_TRANSITION_TYPED); details = new TestMemoryDetails(); details->StartFetchAndWait(); EXPECT_THAT( details->uma()->GetAllSamples("SiteIsolation.BrowsingInstanceCount"), ElementsAre(Bucket(3, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.CurrentRendererProcessCount"), ElementsAre(Bucket(GetRenderProcessCount(), 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateNothingProcessCountEstimate"), ElementsAre(Bucket(3, 1))); // Could be 11 if subframe processes were reused across BrowsingInstances. EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateAllSitesProcessCountEstimate"), ElementsAre(Bucket(15, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateAllSitesProcessCountLowerBound"), ElementsAre(Bucket(11, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateAllSitesProcessCountNoLimit"), ElementsAre(Bucket(15, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateHttpsSitesProcessCountEstimate"), ElementsAre(Bucket(3, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateHttpsSitesProcessCountLowerBound"), ElementsAre(Bucket(1, 1))); // TODO(nick): This should be 3. EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateHttpsSitesProcessCountNoLimit"), ElementsAre(Bucket(3, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateExtensionsProcessCountEstimate"), ElementsAre(Bucket(3, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateExtensionsProcessCountLowerBound"), ElementsAre(Bucket(1, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateExtensionsProcessCountNoLimit"), ElementsAre(Bucket(3, 1))); EXPECT_THAT(GetRenderProcessCount(), EqualsIfExtensionsIsolated(3)); EXPECT_THAT(GetRenderProcessCount(), EqualsIfSitePerProcess(15)); EXPECT_THAT(details->GetOutOfProcessIframeCount(), EqualsIfExtensionsIsolated(0)); EXPECT_THAT(details->GetOutOfProcessIframeCount(), EqualsIfSitePerProcess(17)); // From the third tab, window.open() a fourth tab in the same // BrowsingInstance, to a page using the same four sites "a-d" as third tab, // plus an additional site "e". The estimated process counts should increase // by one (not five) from the previous scenario, as the new tab can reuse the // four processes already in the BrowsingInstance. GURL dcbae_url = embedded_test_server()->GetURL( "a.com", "/cross_site_iframe_factory.html?d(c(b(a(e))))"); ui_test_utils::UrlLoadObserver load_complete( dcbae_url, content::NotificationService::AllSources()); ASSERT_EQ(3, browser()->tab_strip_model()->count()); ASSERT_TRUE(content::ExecuteScript( browser()->tab_strip_model()->GetActiveWebContents(), "window.open('" + dcbae_url.spec() + "');")); ASSERT_EQ(4, browser()->tab_strip_model()->count()); load_complete.Wait(); details = new TestMemoryDetails(); details->StartFetchAndWait(); EXPECT_THAT( details->uma()->GetAllSamples("SiteIsolation.BrowsingInstanceCount"), ElementsAre(Bucket(3, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.CurrentRendererProcessCount"), ElementsAre(Bucket(GetRenderProcessCount(), 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateNothingProcessCountEstimate"), ElementsAre(Bucket(3, 1))); // Could be 11 if subframe processes were reused across BrowsingInstances. EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateAllSitesProcessCountEstimate"), ElementsAre(Bucket(16, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateAllSitesProcessCountLowerBound"), ElementsAre(Bucket(12, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateAllSitesProcessCountNoLimit"), ElementsAre(Bucket(16, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateHttpsSitesProcessCountEstimate"), ElementsAre(Bucket(3, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateHttpsSitesProcessCountLowerBound"), ElementsAre(Bucket(1, 1))); // TODO(nick): This should be 3. EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateHttpsSitesProcessCountNoLimit"), ElementsAre(Bucket(3, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateExtensionsProcessCountEstimate"), ElementsAre(Bucket(3, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateExtensionsProcessCountLowerBound"), ElementsAre(Bucket(1, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateExtensionsProcessCountNoLimit"), ElementsAre(Bucket(3, 1))); EXPECT_THAT(GetRenderProcessCount(), EqualsIfExtensionsIsolated(3)); EXPECT_THAT(GetRenderProcessCount(), EqualsIfSitePerProcess(16)); EXPECT_THAT(details->GetOutOfProcessIframeCount(), EqualsIfExtensionsIsolated(0)); EXPECT_THAT(details->GetOutOfProcessIframeCount(), EqualsIfSitePerProcess(21)); // This test doesn't navigate to any extensions URLs, so it should not be // in any of the field trial groups. EXPECT_FALSE(IsInTrial("SiteIsolationExtensionsActive")); } IN_PROC_BROWSER_TEST_F(SiteDetailsBrowserTest, IsolateExtensions) { // We start on "about:blank", which should be credited with a process in this // case. scoped_refptr details = new TestMemoryDetails(); details->StartFetchAndWait(); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.CurrentRendererProcessCount"), ElementsAre(Bucket(GetRenderProcessCount(), 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateNothingProcessCountEstimate"), ElementsAre(Bucket(1, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateExtensionsProcessCountEstimate"), ElementsAre(Bucket(1, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateExtensionsProcessCountLowerBound"), ElementsAre(Bucket(1, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateExtensionsProcessCountNoLimit"), ElementsAre(Bucket(1, 1))); EXPECT_THAT(GetRenderProcessCount(), 1); EXPECT_EQ(0, details->GetOutOfProcessIframeCount()); // Install one script-injecting extension with background page, and an // extension with web accessible resources. const Extension* extension1 = CreateExtension("Extension One", true); const Extension* extension2 = CreateExtension("Extension Two", false); // Open two a.com tabs (with cross site http iframes). IsolateExtensions mode // should have no effect so far, since there are no frames straddling the // extension/web boundary. GURL tab1_url = embedded_test_server()->GetURL( "a.com", "/cross_site_iframe_factory.html?a(b,c)"); ui_test_utils::NavigateToURL(browser(), tab1_url); WebContents* tab1 = browser()->tab_strip_model()->GetWebContentsAt(0); GURL tab2_url = embedded_test_server()->GetURL( "a.com", "/cross_site_iframe_factory.html?a(d,e)"); AddTabAtIndex(1, tab2_url, ui::PAGE_TRANSITION_TYPED); WebContents* tab2 = browser()->tab_strip_model()->GetWebContentsAt(1); details = new TestMemoryDetails(); details->StartFetchAndWait(); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.CurrentRendererProcessCount"), ElementsAre(Bucket(GetRenderProcessCount(), 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateNothingProcessCountEstimate"), ElementsAre(Bucket(3, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateExtensionsProcessCountEstimate"), ElementsAre(Bucket(3, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateExtensionsProcessCountLowerBound"), ElementsAre(Bucket(2, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateExtensionsProcessCountNoLimit"), ElementsAre(Bucket(3, 1))); EXPECT_THAT(GetRenderProcessCount(), EqualsIfExtensionsIsolated(3)); EXPECT_THAT(details->GetOutOfProcessIframeCount(), EqualsIfExtensionsIsolated(0)); EXPECT_THAT(details->GetOutOfProcessIframeCount(), EqualsIfSitePerProcess(4)); // Test that "one process per extension" applies even when web content has an // extension iframe. // Tab1 navigates its first iframe to a resource of extension1. This shouldn't // result in a new extension process (it should share with extension1's // background page). content::NavigateIframeToURL( tab1, "child-0", extension1->GetResourceURL("/blank_iframe.html")); details = new TestMemoryDetails(); details->StartFetchAndWait(); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.CurrentRendererProcessCount"), ElementsAre(Bucket(GetRenderProcessCount(), 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateNothingProcessCountEstimate"), ElementsAre(Bucket(3, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateExtensionsProcessCountEstimate"), ElementsAre(Bucket(3, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateExtensionsProcessCountLowerBound"), ElementsAre(Bucket(2, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateExtensionsProcessCountNoLimit"), ElementsAre(Bucket(3, 1))); EXPECT_THAT(GetRenderProcessCount(), EqualsIfExtensionsIsolated(3)); EXPECT_THAT(details->GetOutOfProcessIframeCount(), EqualsIfExtensionsIsolated(1)); EXPECT_THAT(details->GetOutOfProcessIframeCount(), EqualsIfSitePerProcess(4)); // Tab2 navigates its first iframe to a resource of extension1. This also // shouldn't result in a new extension process (it should share with the // background page and the other iframe). content::NavigateIframeToURL( tab2, "child-0", extension1->GetResourceURL("/blank_iframe.html")); details = new TestMemoryDetails(); details->StartFetchAndWait(); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.CurrentRendererProcessCount"), ElementsAre(Bucket(GetRenderProcessCount(), 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateNothingProcessCountEstimate"), ElementsAre(Bucket(3, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateExtensionsProcessCountEstimate"), ElementsAre(Bucket(3, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateExtensionsProcessCountLowerBound"), ElementsAre(Bucket(2, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateExtensionsProcessCountNoLimit"), ElementsAre(Bucket(3, 1))); EXPECT_THAT(GetRenderProcessCount(), EqualsIfExtensionsIsolated(3)); EXPECT_THAT(details->GetOutOfProcessIframeCount(), EqualsIfExtensionsIsolated(2)); EXPECT_THAT(details->GetOutOfProcessIframeCount(), EqualsIfSitePerProcess(4)); // Tab1 navigates its second iframe to a resource of extension2. This SHOULD // result in a new process since extension2 had no existing process. content::NavigateIframeToURL( tab1, "child-1", extension2->GetResourceURL("/blank_iframe.html")); details = new TestMemoryDetails(); details->StartFetchAndWait(); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.CurrentRendererProcessCount"), ElementsAre(Bucket(GetRenderProcessCount(), 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateNothingProcessCountEstimate"), ElementsAre(Bucket(3, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateExtensionsProcessCountEstimate"), ElementsAre(Bucket(4, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateExtensionsProcessCountLowerBound"), ElementsAre(Bucket(3, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateExtensionsProcessCountNoLimit"), ElementsAre(Bucket(4, 1))); EXPECT_THAT(GetRenderProcessCount(), EqualsIfExtensionsIsolated(4)); EXPECT_THAT(details->GetOutOfProcessIframeCount(), EqualsIfExtensionsIsolated(3)); EXPECT_THAT(details->GetOutOfProcessIframeCount(), EqualsIfSitePerProcess(4)); // Tab2 navigates its second iframe to a resource of extension2. This should // share the existing extension2 process. content::NavigateIframeToURL( tab2, "child-1", extension2->GetResourceURL("/blank_iframe.html")); details = new TestMemoryDetails(); details->StartFetchAndWait(); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.CurrentRendererProcessCount"), ElementsAre(Bucket(GetRenderProcessCount(), 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateNothingProcessCountEstimate"), ElementsAre(Bucket(3, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateExtensionsProcessCountEstimate"), ElementsAre(Bucket(4, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateExtensionsProcessCountLowerBound"), ElementsAre(Bucket(3, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateExtensionsProcessCountNoLimit"), ElementsAre(Bucket(4, 1))); EXPECT_THAT(GetRenderProcessCount(), EqualsIfExtensionsIsolated(4)); EXPECT_THAT(details->GetOutOfProcessIframeCount(), EqualsIfExtensionsIsolated(4)); EXPECT_THAT(details->GetOutOfProcessIframeCount(), EqualsIfSitePerProcess(4)); // Install extension3 (identical config to extension2) const Extension* extension3 = CreateExtension("Extension Three", false); // Navigate Tab2 to a top-level page from extension3. There are four processes // now: one for tab1's main frame, and one for each of the extensions: // extension1 has a process because it has a background page; extension2 is // used as an iframe in tab1, and extension3 is the top-level frame in tab2. ui_test_utils::NavigateToURL(browser(), extension3->GetResourceURL("blank_iframe.html")); details = new TestMemoryDetails(); details->StartFetchAndWait(); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.CurrentRendererProcessCount"), ElementsAre(Bucket(GetRenderProcessCount(), 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateNothingProcessCountEstimate"), ElementsAre(Bucket(3, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateExtensionsProcessCountEstimate"), ElementsAre(Bucket(4, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateExtensionsProcessCountLowerBound"), ElementsAre(Bucket(4, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateExtensionsProcessCountNoLimit"), ElementsAre(Bucket(4, 1))); EXPECT_THAT(GetRenderProcessCount(), EqualsIfExtensionsIsolated(4)); EXPECT_THAT(details->GetOutOfProcessIframeCount(), EqualsIfExtensionsIsolated(2)); EXPECT_THAT(details->GetOutOfProcessIframeCount(), EqualsIfSitePerProcess(2)); // Navigate tab2 to a different extension3 page containing a web iframe. The // iframe should get its own process. The lower bound number indicates that, // in theory, the iframe could share a process with tab1's main frame. ui_test_utils::NavigateToURL(browser(), extension3->GetResourceURL("http_iframe.html")); details = new TestMemoryDetails(); details->StartFetchAndWait(); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.CurrentRendererProcessCount"), ElementsAre(Bucket(GetRenderProcessCount(), 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateNothingProcessCountEstimate"), ElementsAre(Bucket(3, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateExtensionsProcessCountEstimate"), ElementsAre(Bucket(5, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateExtensionsProcessCountLowerBound"), ElementsAre(Bucket(4, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateExtensionsProcessCountNoLimit"), ElementsAre(Bucket(5, 1))); EXPECT_THAT(GetRenderProcessCount(), EqualsIfExtensionsIsolated(5)); EXPECT_THAT(details->GetOutOfProcessIframeCount(), EqualsIfExtensionsIsolated(3)); EXPECT_THAT(details->GetOutOfProcessIframeCount(), EqualsIfSitePerProcess(3)); // Navigate tab1 to an extension3 page with an extension3 iframe. There should // be three processes estimated by IsolateExtensions: one for extension3, one // for extension1's background page, and one for the web iframe in tab2. browser()->tab_strip_model()->ActivateTabAt(0, true); ui_test_utils::NavigateToURL(browser(), extension3->GetResourceURL("blank_iframe.html")); details = new TestMemoryDetails(); details->StartFetchAndWait(); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.CurrentRendererProcessCount"), ElementsAre(Bucket(GetRenderProcessCount(), 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateNothingProcessCountEstimate"), ElementsAre(Bucket(2, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateExtensionsProcessCountEstimate"), ElementsAre(Bucket(3, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateExtensionsProcessCountLowerBound"), ElementsAre(Bucket(3, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateExtensionsProcessCountNoLimit"), ElementsAre(Bucket(3, 1))); EXPECT_THAT(GetRenderProcessCount(), EqualsIfExtensionsIsolated(3)); EXPECT_THAT(details->GetOutOfProcessIframeCount(), EqualsIfExtensionsIsolated(1)); EXPECT_THAT(details->GetOutOfProcessIframeCount(), EqualsIfSitePerProcess(1)); // Now navigate tab1 to an extension3 page with a web iframe. This could share // a process with tab2's iframe (the LowerBound number), or it could get its // own process (the Estimate number). ui_test_utils::NavigateToURL(browser(), extension3->GetResourceURL("http_iframe.html")); details = new TestMemoryDetails(); details->StartFetchAndWait(); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.CurrentRendererProcessCount"), ElementsAre(Bucket(GetRenderProcessCount(), 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateNothingProcessCountEstimate"), ElementsAre(Bucket(2, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateExtensionsProcessCountEstimate"), ElementsAre(Bucket(4, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateExtensionsProcessCountLowerBound"), ElementsAre(Bucket(3, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateExtensionsProcessCountNoLimit"), ElementsAre(Bucket(4, 1))); EXPECT_THAT(GetRenderProcessCount(), EqualsIfExtensionsIsolated(4)); EXPECT_THAT(details->GetOutOfProcessIframeCount(), EqualsIfExtensionsIsolated(2)); EXPECT_THAT(details->GetOutOfProcessIframeCount(), EqualsIfSitePerProcess(2)); EXPECT_TRUE(IsInTrial("SiteIsolationExtensionsActive")); } // Exercises accounting in the case where an extension has two different-site // web iframes. IN_PROC_BROWSER_TEST_F(SiteDetailsBrowserTest, ExtensionWithTwoWebIframes) { scoped_refptr details = new TestMemoryDetails(); details->StartFetchAndWait(); // Install one script-injecting extension with background page, and an // extension with web accessible resources. const Extension* extension = CreateExtension("Test Extension", false); ui_test_utils::NavigateToURL( browser(), extension->GetResourceURL("/two_http_iframes.html")); details = new TestMemoryDetails(); details->StartFetchAndWait(); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.CurrentRendererProcessCount"), ElementsAre(Bucket(GetRenderProcessCount(), 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateNothingProcessCountEstimate"), ElementsAre(Bucket(1, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateExtensionsProcessCountEstimate"), ElementsAre(Bucket(2, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateExtensionsProcessCountLowerBound"), ElementsAre(Bucket(2, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateExtensionsProcessCountNoLimit"), ElementsAre(Bucket(2, 1))); // TODO(nick): https://crbug.com/512560 Make the number below agree with the // estimates above, which assume consolidation of subframe processes. EXPECT_THAT(GetRenderProcessCount(), EqualsIfExtensionsIsolated(3)); EXPECT_THAT(details->GetOutOfProcessIframeCount(), EqualsIfExtensionsIsolated(2)); EXPECT_THAT(details->GetOutOfProcessIframeCount(), EqualsIfSitePerProcess(2)); EXPECT_TRUE(IsInTrial("SiteIsolationExtensionsActive")); } // Verifies that --isolate-extensions doesn't isolate hosted apps. IN_PROC_BROWSER_TEST_F(SiteDetailsBrowserTest, IsolateExtensionsHostedApps) { GURL app_with_web_iframe_url = embedded_test_server()->GetURL( "app.org", "/cross_site_iframe_factory.html?app.org(b.com)"); GURL app_in_web_iframe_url = embedded_test_server()->GetURL( "b.com", "/cross_site_iframe_factory.html?b.com(app.org)"); // No hosted app is installed: app.org just behaves like a normal domain. ui_test_utils::NavigateToURL(browser(), app_with_web_iframe_url); scoped_refptr details = new TestMemoryDetails(); details->StartFetchAndWait(); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.CurrentRendererProcessCount"), ElementsAre(Bucket(GetRenderProcessCount(), 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateNothingProcessCountEstimate"), ElementsAre(Bucket(1, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateExtensionsProcessCountEstimate"), ElementsAre(Bucket(1, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateExtensionsProcessCountLowerBound"), ElementsAre(Bucket(1, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateExtensionsProcessCountNoLimit"), ElementsAre(Bucket(1, 1))); EXPECT_THAT(GetRenderProcessCount(), EqualsIfExtensionsIsolated(1)); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateAllSitesProcessCountEstimate"), ElementsAre(Bucket(2, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateAllSitesProcessCountLowerBound"), ElementsAre(Bucket(2, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateAllSitesProcessCountNoLimit"), ElementsAre(Bucket(2, 1))); EXPECT_THAT(GetRenderProcessCount(), EqualsIfSitePerProcess(2)); EXPECT_THAT(details->GetOutOfProcessIframeCount(), EqualsIfExtensionsIsolated(0)); EXPECT_THAT(details->GetOutOfProcessIframeCount(), EqualsIfSitePerProcess(1)); ui_test_utils::NavigateToURL(browser(), app_in_web_iframe_url); details = new TestMemoryDetails(); details->StartFetchAndWait(); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.CurrentRendererProcessCount"), ElementsAre(Bucket(GetRenderProcessCount(), 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateNothingProcessCountEstimate"), ElementsAre(Bucket(1, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateExtensionsProcessCountEstimate"), ElementsAre(Bucket(1, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateExtensionsProcessCountLowerBound"), ElementsAre(Bucket(1, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateExtensionsProcessCountNoLimit"), ElementsAre(Bucket(1, 1))); EXPECT_THAT(GetRenderProcessCount(), EqualsIfExtensionsIsolated(1)); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateAllSitesProcessCountEstimate"), ElementsAre(Bucket(2, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateAllSitesProcessCountLowerBound"), ElementsAre(Bucket(2, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateAllSitesProcessCountNoLimit"), ElementsAre(Bucket(2, 1))); EXPECT_THAT(GetRenderProcessCount(), EqualsIfSitePerProcess(2)); EXPECT_THAT(details->GetOutOfProcessIframeCount(), EqualsIfExtensionsIsolated(0)); EXPECT_THAT(details->GetOutOfProcessIframeCount(), EqualsIfSitePerProcess(1)); // Now install app.org as a hosted app. CreateHostedApp("App", GURL("http://app.org")); // Reload the same two pages, and verify that the hosted app still is not // isolated by --isolate-extensions, but is isolated by --site-per-process. ui_test_utils::NavigateToURL(browser(), app_with_web_iframe_url); details = new TestMemoryDetails(); details->StartFetchAndWait(); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.CurrentRendererProcessCount"), ElementsAre(Bucket(GetRenderProcessCount(), 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateNothingProcessCountEstimate"), ElementsAre(Bucket(1, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateExtensionsProcessCountEstimate"), ElementsAre(Bucket(1, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateExtensionsProcessCountLowerBound"), ElementsAre(Bucket(1, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateExtensionsProcessCountNoLimit"), ElementsAre(Bucket(1, 1))); EXPECT_THAT(GetRenderProcessCount(), EqualsIfExtensionsIsolated(1)); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateAllSitesProcessCountEstimate"), ElementsAre(Bucket(2, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateAllSitesProcessCountLowerBound"), ElementsAre(Bucket(2, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateAllSitesProcessCountNoLimit"), ElementsAre(Bucket(2, 1))); EXPECT_THAT(GetRenderProcessCount(), EqualsIfSitePerProcess(2)); EXPECT_THAT(details->GetOutOfProcessIframeCount(), EqualsIfExtensionsIsolated(0)); EXPECT_THAT(details->GetOutOfProcessIframeCount(), EqualsIfSitePerProcess(1)); ui_test_utils::NavigateToURL(browser(), app_in_web_iframe_url); details = new TestMemoryDetails(); details->StartFetchAndWait(); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.CurrentRendererProcessCount"), ElementsAre(Bucket(GetRenderProcessCount(), 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateNothingProcessCountEstimate"), ElementsAre(Bucket(1, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateExtensionsProcessCountEstimate"), ElementsAre(Bucket(1, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateExtensionsProcessCountLowerBound"), ElementsAre(Bucket(1, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateExtensionsProcessCountNoLimit"), ElementsAre(Bucket(1, 1))); EXPECT_THAT(GetRenderProcessCount(), EqualsIfExtensionsIsolated(1)); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateAllSitesProcessCountEstimate"), ElementsAre(Bucket(2, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateAllSitesProcessCountLowerBound"), ElementsAre(Bucket(2, 1))); EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.IsolateAllSitesProcessCountNoLimit"), ElementsAre(Bucket(2, 1))); EXPECT_THAT(GetRenderProcessCount(), EqualsIfSitePerProcess(2)); EXPECT_THAT(details->GetOutOfProcessIframeCount(), EqualsIfExtensionsIsolated(0)); EXPECT_THAT(details->GetOutOfProcessIframeCount(), EqualsIfSitePerProcess(1)); // Since hosted apps are excluded from isolation, this test should not be // in any of the field trial groups. EXPECT_FALSE(IsInTrial("SiteIsolationExtensionsActive")); } // Verifies that the client is put in the appropriate field trial group. IN_PROC_BROWSER_TEST_F(SiteDetailsBrowserTest, VerifyFieldTrialGroup) { const Extension* extension = CreateExtension("Extension", false); GURL tab1_url = embedded_test_server()->GetURL( "a.com", "/cross_site_iframe_factory.html?a(b,c)"); ui_test_utils::NavigateToURL(browser(), tab1_url); WebContents* tab = browser()->tab_strip_model()->GetWebContentsAt(0); // Tab navigates its second iframe to a page of the extension. content::NavigateIframeToURL(tab, "child-1", extension->GetResourceURL("/blank_iframe.html")); std::string group; if (base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kSitePerProcess)) { group = "SitePerProcessFlag"; } else if (extensions::IsIsolateExtensionsEnabled()) { if (base::CommandLine::ForCurrentProcess()->HasSwitch( extensions::switches::kIsolateExtensions)) { group = "IsolateExtensionsFlag"; } else { group = "FieldTrial"; } } else { group = "Default"; } EXPECT_TRUE(IsInTrialGroup("SiteIsolationExtensionsActive", group)); } // Verifies that the UMA counter for SiteInstances in a BrowsingInstance is // correct when using tabs with web pages. IN_PROC_BROWSER_TEST_F(SiteDetailsBrowserTest, VerifySiteInstanceCountInBrowsingInstance) { // Page with 14 nested oopifs across 9 sites (a.com through i.com). GURL abcdefghi_url = embedded_test_server()->GetURL( "a.com", "/cross_site_iframe_factory.html?a(b(a(b,c,d,e,f,g,h)),c,d,e,i(f))"); ui_test_utils::NavigateToURL(browser(), abcdefghi_url); // Get the metrics. scoped_refptr details = new TestMemoryDetails(); details->StartFetchAndWait(); if (content::AreAllSitesIsolatedForTesting()) { EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.SiteInstancesPerBrowsingInstance"), ElementsAre(Bucket(9, 1))); } else { // Since there are no extensions involved, the results in the default case // and extensions::IsIsolateExtensionsEnabled() are the same. EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.SiteInstancesPerBrowsingInstance"), ElementsAre(Bucket(1, 1))); } // Open another tab through window.open(), which will be in the same // BrowsingInstance. GURL dcbae_url = embedded_test_server()->GetURL( "a.com", "/cross_site_iframe_factory.html?d(c(b(j(k))))"); ui_test_utils::UrlLoadObserver load_complete( dcbae_url, content::NotificationService::AllSources()); ASSERT_EQ(1, browser()->tab_strip_model()->count()); ASSERT_TRUE(content::ExecuteScript( browser()->tab_strip_model()->GetActiveWebContents(), "window.open('" + dcbae_url.spec() + "');")); ASSERT_EQ(2, browser()->tab_strip_model()->count()); load_complete.Wait(); details = new TestMemoryDetails(); details->StartFetchAndWait(); if (content::AreAllSitesIsolatedForTesting()) { EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.SiteInstancesPerBrowsingInstance"), ElementsAre(Bucket(11, 1))); } else { EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.SiteInstancesPerBrowsingInstance"), ElementsAre(Bucket(1, 1))); } // Open a tab, which will be in a different BrowsingInstance. GURL abcd_url = embedded_test_server()->GetURL( "a.com", "/cross_site_iframe_factory.html?a(b(c(d())))"); AddTabAtIndex(1, abcd_url, ui::PAGE_TRANSITION_TYPED); details = new TestMemoryDetails(); details->StartFetchAndWait(); if (content::AreAllSitesIsolatedForTesting()) { EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.SiteInstancesPerBrowsingInstance"), ElementsAre(Bucket(4, 1), Bucket(11, 1))); } else { EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.SiteInstancesPerBrowsingInstance"), ElementsAre(Bucket(1, 2))); } } // Verifies that the UMA counter for SiteInstances in a BrowsingInstance is // correct when extensions and web pages are mixed together. IN_PROC_BROWSER_TEST_F( SiteDetailsBrowserTest, VerifySiteInstanceCountInBrowsingInstanceWithExtensions) { // Open two a.com tabs (with cross site http iframes). IsolateExtensions mode // should have no effect so far, since there are no frames straddling the // extension/web boundary. GURL tab_url = embedded_test_server()->GetURL( "a.com", "/cross_site_iframe_factory.html?a(b,c,d(e))"); ui_test_utils::NavigateToURL(browser(), tab_url); WebContents* tab = browser()->tab_strip_model()->GetWebContentsAt(0); scoped_refptr details = new TestMemoryDetails(); details->StartFetchAndWait(); if (content::AreAllSitesIsolatedForTesting()) { EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.SiteInstancesPerBrowsingInstance"), ElementsAre(Bucket(5, 1))); } else { // Since there are no extensions loaded yet, the results in the default case // and extensions::IsIsolateExtensionsEnabled() are the same. EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.SiteInstancesPerBrowsingInstance"), ElementsAre(Bucket(1, 1))); } // Load an extension without a background page, which will avoid creating a // BrowsingInstance for it. const Extension* extension1 = CreateExtension("Extension One", false); // Navigate the tab's first iframe to a resource of the extension. The // extension iframe will be put in the same BrowsingInstance as it is part // of the frame tree. content::NavigateIframeToURL( tab, "child-0", extension1->GetResourceURL("/blank_iframe.html")); details = new TestMemoryDetails(); details->StartFetchAndWait(); if (content::AreAllSitesIsolatedForTesting()) { EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.SiteInstancesPerBrowsingInstance"), ElementsAre(Bucket(5, 1))); } else if (extensions::IsIsolateExtensionsEnabled()) { EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.SiteInstancesPerBrowsingInstance"), ElementsAre(Bucket(2, 1))); } else { EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.SiteInstancesPerBrowsingInstance"), ElementsAre(Bucket(1, 1))); } // Now load an extension with a background page. This will result in a // BrowsingInstance for the background page. const Extension* extension2 = CreateExtension("Extension One", true); details = new TestMemoryDetails(); details->StartFetchAndWait(); if (content::AreAllSitesIsolatedForTesting()) { EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.SiteInstancesPerBrowsingInstance"), ElementsAre(Bucket(1, 1), Bucket(5, 1))); } else if (extensions::IsIsolateExtensionsEnabled()) { EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.SiteInstancesPerBrowsingInstance"), ElementsAre(Bucket(1, 1), Bucket(2, 1))); } else { EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.SiteInstancesPerBrowsingInstance"), ElementsAre(Bucket(1, 2))); } // Navigate the second iframe of the tab to the second extension. It should // stay in the same BrowsingInstance as the page. content::NavigateIframeToURL( tab, "child-1", extension2->GetResourceURL("/blank_iframe.html")); details = new TestMemoryDetails(); details->StartFetchAndWait(); if (content::AreAllSitesIsolatedForTesting()) { EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.SiteInstancesPerBrowsingInstance"), ElementsAre(Bucket(1, 1), Bucket(5, 1))); } else if (extensions::IsIsolateExtensionsEnabled()) { EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.SiteInstancesPerBrowsingInstance"), ElementsAre(Bucket(1, 1), Bucket(3, 1))); } else { EXPECT_THAT(details->uma()->GetAllSamples( "SiteIsolation.SiteInstancesPerBrowsingInstance"), ElementsAre(Bucket(1, 2))); } } // // Created by on 8/9/15. // #include "JsonValue.h" namespace CLDEParser { namespace Parsing { namespace Json { std::string JsonValue::CopyToString() const { switch ((JsonValueType) id) { case JsonValueType::Null: return "null"; case JsonValueType::String: return strValue; case JsonValueType::Integer: return std::to_string(intValue); case JsonValueType::Real: return std::to_string(doubleValue); case JsonValueType::Boolean: return std::to_string(boolValue); case JsonValueType::Entity: return sptrJsonEntity->CopyToString(); } } } } } #include "createPensum.h" #include "createTreePensum.h" #include #include using namespace std; CreatePensum::CreatePensum(void){} void CreatePensum::addCareer() { metaData objM; cout << "Ingrese codigo del plan: "; cin >> objM.codigoPlan; cout << "Ingrese nombre del plan: "; cin >> objM.nombrePlan; cout << "Ingrese cantidad total de clases: "; cin >> objM.totalClases; //cout << "Ingrese cantidad de bloques de conocimiento: "; objM.cantBloques = 0; string codex = objM.codigoPlan; fstream file(codex + "_plan.dat", ios::out | ios::app | ios::binary); file.write(reinterpret_cast(&objM), sizeof(metaData)); materia obj; string padrex; createTreePensum obj2; file.seekg(0); file.seekg(sizeof(metaData)); obj2.cantBloques = objM.cantBloques; for (int n = 0; n < objM.totalClases; n++) { cout << "Input class code: "; cin >> obj.codigo; cout << "Input name of class: "; cin >> obj.nombre; cout << "Input class UVs: "; cin >> obj.UVs; cout << "Input year of period: "; cin >> obj.anoP; cout << "Input Period: "; cin >> obj.periodo; cout << "Input amount of parent classes: "; int x = 0; cin >> x; for (int i = 0; i < x; i++) { cout << "Input required class: "; cin >> padrex; for (int n = 0; n < padrex.size(); n++) { obj.padres[i][n] = padrex.at(n); } } file.write(reinterpret_cast(&obj), sizeof(materia)); } file.close(); printPensum(codex + "_plan.dat"); readPensum(codex + "_plan.dat"); //printPensum(codex + "_plan.dat"); //addHijos(codex + "_plan.dat", obj.padres, nameData); //obj2.addClass(codeData, nameData, UVsData, periodYearData, periodData, obj.padres, obj.hijos, obj.nota, obj.UVsRequisito); } void CreatePensum::extractTextFile(string name) { ifstream file; file.open(name); string line; materia obj; if (file.fail()) { cout << "Could not open text file."; return; } while (!file.eof()) { getline(file, line); string delimiter("Codigo:"); size_t pos = 0; int x = 0; string word = ""; string save = ""; bool check = false; //cout << line << endl; for (int i = 0; i < line.size(); i++) { save = ""; word += line.at(i); if (word == "Codigo:") { for (int j = i; j < line.length(); j++) { save += line.at(j); } cout << save << endl; } else if (word == "Materia:") { for (int j = i; j < line.length(); j++) { save += line.at(j); } cout << save << endl; } else if (word == "UVs:") { for (int j = line.length() - i; j < line.length(); j++) { save += line.at(j); } cout << save << endl; } else if (word == "Ano Plan:") { for (int j = line.length() - i; j < line.length(); j++) { save += line.at(j); } cout << save << endl; } else if (word == "Periodo:") { for (int j = line.length() - i; j < line.length(); j++) { save += line.at(j); } cout << save << endl; } else if (word == "Padre:") { for (int j = line.length() - i; j < line.length(); j++) { save += line.at(j); } cout << save << endl; } //cout << '\n'; } } } void CreatePensum::readPensum(string name) { fstream file; file.open(name, ios::in | ios::binary); if (file.fail()) { cout << "Unable to open file, check file\'s path."; return; } materia actual; createTreePensum obj; file.seekg(sizeof(metaData)); file.read(reinterpret_cast(&actual), sizeof(actual)); materiaMemo* nuevo = new materiaMemo(); nuevo = obj.convert(actual); //obj.addClass(nuevo); while (!file.eof()) { file.read(reinterpret_cast(&actual), sizeof(actual)); nuevo = obj.convert(actual); } file.close(); } void CreatePensum::readRegister(string name, estudianteMemo* estu) { fstream file; file.open(name, ios::in | ios::binary); if (file.fail()) { cout << "Unable to open file, check file\'s path."; return; } materia actual; createTreePensum obj; file.seekg(sizeof(metaData)); file.read(reinterpret_cast(&actual), sizeof(actual)); materiaMemo* nuevo = new materiaMemo(); nuevo = obj.convert2(actual, estu); //obj.addClass(nuevo); while (!file.eof()) { file.read(reinterpret_cast(&actual), sizeof(actual)); nuevo = obj.convert2(actual,estu); } file.close(); } void CreatePensum::printPensum(string name) { fstream file; file.open(name, ios::in | ios::binary); if (file.fail()) { cout << "Unable to open file, check file\'s path."; return; } materia actual; createTreePensum obj; file.seekg(sizeof(metaData)); //file.seekg(0); file.read(reinterpret_cast(&actual), sizeof(actual)); while (!file.eof()) { cout << "\nNombre: " << actual.nombre; cout << "\nCodigo: " << actual.codigo; cout << "\nUVs: " << actual.UVs; cout << "\nAno Periodo: " << actual.anoP; cout << "\nPeriodo: " << actual.periodo; cout << "\nPadres: "; for (int i = 0; i < 4; i++) { string af = actual.padres[i]; for (int j = 0; j < af.size(); j++) { cout << actual.padres[i][j]; } cout << ", "; } cout << "\nNota: " << actual.nota; cout << "\nUVs necesarias: " << actual.UVsRequisito; cout << '\n'; file.read(reinterpret_cast(&actual), sizeof(actual)); } file.close(); } jane8384/seven-monkeys // // Rand.hpp // SevenMonkeys // #ifndef Rand_hpp #define Rand_hpp #include "SevenMonkeys.hpp" NS_SM_BEGIN class Rand { public: // Rand(); // ~Rand() = default; static bool randBool(); static int32_t randInt(); static int32_t randInt(int32_t v); static int32_t randInt(int32_t a, int32_t b); static float randFloat(); static void shuffle(std::vector& v); private: static std::mt19937 svRnd; static std::uniform_int_distribution svIntDist; static std::uniform_real_distribution svRealDist; }; // Rand shortcuts inline bool randBool() { return Rand::randBool(); } inline int32_t randInt() { return Rand::randInt(); } inline int32_t randInt(int32_t v) { return Rand::randInt(v); } inline int32_t randInt(int32_t a, int32_t b) { return Rand::randInt(a, b); } inline float randFloat() { return Rand::randFloat(); } NS_SM_END #endif /* Rand_hpp */ // 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 // The example companies, organizations, products, domain names, // e-mail addresses, logos, people, places, and events depicted herein are fictitious. // No association with any real company, organization, product, domain name, // email address, logo, person, places, or events is intended or should be inferred. #define _WIN32_DCOM #include #include #include #include // Include the task header file. #include "taskschd.h" # pragma comment(lib, "taskschd.lib") # pragma comment(lib, "comsupp.lib") # pragma comment(lib, "credui.lib") /******************************************************************** This sample schedules a task to start notepad.exe 30 seconds after the system is booted. ********************************************************************/ int __cdecl wmain() { // ------------------------------------------------------ // Initialize COM. HRESULT hr = CoInitializeEx(NULL, COINIT_MULTITHREADED); if( FAILED(hr) ) { printf("\nCoInitializeEx failed: %x", hr ); return 1; } // Set general COM security levels. hr = CoInitializeSecurity( NULL, -1, NULL, NULL, RPC_C_AUTHN_LEVEL_PKT_PRIVACY, RPC_C_IMP_LEVEL_IMPERSONATE, NULL, 0, NULL); if( FAILED(hr) ) { printf("\nCoInitializeSecurity failed: %x", hr ); CoUninitialize(); return 1; } // ------------------------------------------------------ // Create a name for the task. LPCWSTR wszTaskName = L"Event Trigger Test Task"; // ------------------------------------------------------ // Create an instance of the Task Service. ITaskService *pService = NULL; hr = CoCreateInstance( CLSID_TaskScheduler, NULL, CLSCTX_INPROC_SERVER, IID_ITaskService, (void**)&pService ); if (FAILED(hr)) { printf("\nFailed to CoCreate an instance of the TaskService class: %x", hr); CoUninitialize(); return 1; } // Connect to the task service. hr = pService->Connect(_variant_t(), _variant_t(), _variant_t(), _variant_t()); if( FAILED(hr) ) { printf("\nITaskService::Connect failed: %x", hr ); pService->Release(); CoUninitialize(); return 1; } // ------------------------------------------------------ // Get the pointer to the root task folder. This folder will hold the // new task that is registered. ITaskFolder *pRootFolder = NULL; hr = pService->GetFolder( _bstr_t( L"\\") , &pRootFolder ); if( FAILED(hr) ) { printf("\nCannot get Root Folder pointer: %x", hr ); pService->Release(); CoUninitialize(); return 1; } // If the same task exists, remove it. pRootFolder->DeleteTask( _bstr_t( wszTaskName), 0 ); // Create the task builder object to create the task. ITaskDefinition *pTask = NULL; hr = pService->NewTask( 0, &pTask ); pService->Release(); // COM clean up. Pointer is no longer used. if (FAILED(hr)) { printf("\nFailed to create an instance of the task: %x", hr); pRootFolder->Release(); CoUninitialize(); return 1; } // ------------------------------------------------------ // Get the registration info for setting the identification. IRegistrationInfo *pRegInfo= NULL; hr = pTask->get_RegistrationInfo( &pRegInfo ); if( FAILED(hr) ) { printf("\nCannot get identification pointer: %x", hr ); pRootFolder->Release(); pTask->Release(); CoUninitialize(); return 1; } hr = pRegInfo->put_Author( L"Author Name" ); pRegInfo->Release(); // COM clean up. Pointer is no longer used. if( FAILED(hr) ) { printf("\nCannot put identification info: %x", hr ); pRootFolder->Release(); pTask->Release(); CoUninitialize(); return 1; } // ------------------------------------------------------ // Create the settings for the task ITaskSettings *pSettings = NULL; hr = pTask->get_Settings( &pSettings ); if( FAILED(hr) ) { printf("\nCannot get settings pointer: %x", hr ); pRootFolder->Release(); pTask->Release(); CoUninitialize(); return 1; } // Set setting values for the task. hr = pSettings->put_StartWhenAvailable(VARIANT_BOOL(true)); pSettings->Release(); // COM clean up. Pointer is no longer used. if( FAILED(hr) ) { printf("\nCannot put setting info: %x", hr ); pRootFolder->Release(); pTask->Release(); CoUninitialize(); return 1; } // ------------------------------------------------------ // Get the trigger collection to insert the event trigger. ITriggerCollection *pTriggerCollection = NULL; hr = pTask->get_Triggers( &pTriggerCollection ); if( FAILED(hr) ) { printf("\nCannot get trigger collection: %x", hr ); pRootFolder->Release(); pTask->Release(); CoUninitialize(); return 1; } // Create the event trigger for the task. ITrigger *pTrigger = NULL; hr = pTriggerCollection->Create( TASK_TRIGGER_EVENT, &pTrigger ); pTriggerCollection->Release(); if( FAILED(hr) ) { printf("\nCannot create the trigger: %x", hr ); pRootFolder->Release(); pTask->Release(); CoUninitialize(); return 1; } IEventTrigger *pEventTrigger = NULL; hr = pTrigger->QueryInterface( IID_IEventTrigger, (void**) &pEventTrigger ); pTrigger->Release(); if( FAILED(hr) ) { printf("\nQueryInterface call on IEventTrigger failed: %x", hr ); pRootFolder->Release(); pTask->Release(); CoUninitialize(); return 1; } hr = pEventTrigger->put_Id( _bstr_t( L"Trigger1" ) ); if( FAILED(hr) ) printf("\nCannot put the trigger ID: %x", hr); // Set the task to start at a certain time. The time // format should be YYYY-MM-DDTHH:MM:SS(+-)(timezone). // For example, the start boundary below // is January 1st 2005 at 12:05 hr = pEventTrigger->put_StartBoundary( _bstr_t(L"2005-01-01T12:05:00") ); if( FAILED(hr) ) printf("\nCannot put the trigger start boundary: %x", hr); hr = pEventTrigger->put_EndBoundary( _bstr_t(L"2015-05-02T08:00:00") ); if( FAILED(hr) ) printf("\nCannot put the trigger end boundary: %x", hr); // Define the delay for the event trigger (30 seconds). hr = pEventTrigger->put_Delay( L"PT30S" ); if( FAILED(hr) ) printf("\nCannot put the trigger delay: %x", hr); // Define the event query for the event trigger. // The following query string defines a subscription to all // level 2 events in the System channel. hr = pEventTrigger->put_Subscription( L" " ); pEventTrigger->Release(); if( FAILED(hr) ) { printf("\nCannot put the event query: %x", hr); pRootFolder->Release(); pTask->Release(); CoUninitialize(); return 1; } // ------------------------------------------------------ // Add an action to the task. This task will send an e-mail. IActionCollection *pActionCollection = NULL; // Get the task action collection pointer. hr = pTask->get_Actions( &pActionCollection ); if( FAILED(hr) ) { printf("\nCannot get action collection pointer: %x", hr ); pRootFolder->Release(); pTask->Release(); CoUninitialize(); return 1; } // Create the action, specifying that it will send an e-mail. IAction *pAction = NULL; hr = pActionCollection->Create( TASK_ACTION_SEND_EMAIL, &pAction ); pActionCollection->Release(); if( FAILED(hr) ) { printf("\nCannot create an e-mail action: %x", hr ); pRootFolder->Release(); pTask->Release(); CoUninitialize(); return 1; } IEmailAction *pEmailAction = NULL; // QI for the e-mail task pointer. hr = pAction->QueryInterface(IID_IEmailAction, (void**) &pEmailAction ); pAction->Release(); if( FAILED(hr) ) { printf("\nQueryInterface call failed for IEmailAction: %x", hr ); pRootFolder->Release(); pTask->Release(); CoUninitialize(); return 1; } // Set the properties of the e-mail action. hr = pEmailAction->put_From(L""); if( FAILED(hr) ) { printf("\nCannot put From information: %x", hr ); pRootFolder->Release(); pEmailAction->Release(); pTask->Release(); CoUninitialize(); return 1; } hr = pEmailAction->put_To(L""); if( FAILED(hr) ) { printf("\nCannot put To information: %x", hr ); pRootFolder->Release(); pEmailAction->Release(); pTask->Release(); CoUninitialize(); return 1; } hr = pEmailAction->put_Server(L"smtp.tschd.microsoft.com"); if( FAILED(hr) ) { printf("\nCannot put SMTP server information: %x", hr ); pRootFolder->Release(); pEmailAction->Release(); pTask->Release(); CoUninitialize(); return 1; } hr = pEmailAction->put_Subject(L"An event has occurred"); if( FAILED(hr) ) printf("\nCannot put the subject information: %x", hr); hr = pEmailAction->put_Body(L"A level 2 event occurred in the system channel."); if( FAILED(hr) ) printf("\nCannot put the e-mail body information: %x", hr); pEmailAction->Release(); // ------------------------------------------------------ // Securely get the user name and password. The task will // be created to run with the credentials from the supplied // user name and password. CREDUI_INFO cui; TCHAR pszName[CREDUI_MAX_USERNAME_LENGTH] = TEXT(""); TCHAR pszPwd[CREDUI_MAX_PASSWORD_LENGTH] = TEXT(""); BOOL fSave; DWORD dwErr; cui.cbSize = sizeof(CREDUI_INFO); cui.hwndParent = NULL; // Ensure that MessageText and CaptionText identify // what credentials to use and which application requires them. cui.pszMessageText = TEXT("Account information for task registration:"); cui.pszCaptionText = TEXT("Enter Account Information for Task Registration"); cui.hbmBanner = NULL; fSave = FALSE; // Create the UI asking for the credentials. dwErr = CredUIPromptForCredentials( &cui, // CREDUI_INFO structure TEXT(""), // Target for credentials NULL, // Reserved 0, // Reason pszName, // User name CREDUI_MAX_USERNAME_LENGTH, // Max number for user name pszPwd, // Password CREDUI_MAX_PASSWORD_LENGTH, // Max number for password &fSave, // State of save check box CREDUI_FLAGS_GENERIC_CREDENTIALS | // Flags CREDUI_FLAGS_ALWAYS_SHOW_UI | CREDUI_FLAGS_DO_NOT_PERSIST); if(dwErr) { printf("\nDid not get credentials."); pRootFolder->Release(); pTask->Release(); CoUninitialize(); return 1; } // ------------------------------------------------------ // Save the task in the root folder. IRegisteredTask *pRegisteredTask = NULL; hr = pRootFolder->RegisterTaskDefinition( _bstr_t( wszTaskName ), pTask, TASK_CREATE_OR_UPDATE, _variant_t(_bstr_t(pszName)), _variant_t(_bstr_t(pszPwd)), TASK_LOGON_PASSWORD, _variant_t(L""), &pRegisteredTask); if( FAILED(hr) ) { printf("\nError saving the Task : %x", hr ); pRootFolder->Release(); pTask->Release(); CoUninitialize(); SecureZeroMemory(pszName, sizeof(pszName)); SecureZeroMemory(pszPwd, sizeof(pszPwd)); return 1; } printf("\n Success! Task successfully registered. " ); // Clean up. pRootFolder->Release(); pTask->Release(); pRegisteredTask->Release(); CoUninitialize(); // When you have finished using the credentials, // erase them from memory. SecureZeroMemory(pszName, sizeof(pszName)); SecureZeroMemory(pszPwd, sizeof(pszPwd)); return 0; } Pysis868/Plutonium #include namespace pu::ui::elm { TextBlock::TextBlock(i32 X, i32 Y, String Text) : Element::Element() { this->x = X; this->y = Y; this->text = Text; this->fnt_name = "DefaultFont@25"; this->ntex = render::RenderText(this->fnt_name, Text, this->clr); } TextBlock::~TextBlock() { if(this->ntex != nullptr) { render::DeleteTexture(this->ntex); this->ntex = nullptr; } } i32 TextBlock::GetX() { return this->x; } void TextBlock::SetX(i32 X) { this->x = X; } i32 TextBlock::GetY() { return this->y; } void TextBlock::SetY(i32 Y) { this->y = Y; } i32 TextBlock::GetWidth() { return this->GetTextWidth(); } i32 TextBlock::GetHeight() { return this->GetTextHeight(); } i32 TextBlock::GetTextWidth() { return render::GetTextWidth(this->fnt_name, this->text); } i32 TextBlock::GetTextHeight() { return render::GetTextHeight(this->fnt_name, this->text); } String TextBlock::GetText() { return this->text; } void TextBlock::SetText(String Text) { this->text = Text; render::DeleteTexture(this->ntex); this->ntex = render::RenderText(this->fnt_name, Text, this->clr); } void TextBlock::SetFont(String font_name) { this->fnt_name = font_name; render::DeleteTexture(this->ntex); this->ntex = render::RenderText(this->fnt_name, this->text, this->clr); } Color TextBlock::GetColor() { return this->clr; } void TextBlock::SetColor(Color Color) { this->clr = Color; render::DeleteTexture(this->ntex); this->ntex = render::RenderText(this->fnt_name, this->text, Color); } void TextBlock::OnRender(render::Renderer::Ref &Drawer, i32 X, i32 Y) { i32 rdx = X; i32 rdy = Y; Drawer->RenderTexture(this->ntex, rdx, rdy); } void TextBlock::OnInput(u64 Down, u64 Up, u64 Held, Touch Pos) { } }tests/simulator/gencode/test_add_cout_16.cpp0 #include "add_cout_16.h" #include #include using namespace std; int main() { circuit_state state; state.self_cout = 0; state.self_in[0] = (1 << 15) | 1; state.self_in[1] = (1 << 15) | (1 << 14); simulate(&state); cout << "self_cout = " << bitset<16>(state.self_cout) << endl; cout << "self_out = " << bitset<16>(state.self_out) << endl; if (state.self_out != ((1 << 14) | 1)) { return 1; } if (state.self_cout != 1) { return 1; } return 0; } 0 /* * Copyright (c) 2020, NVIDIA 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. */ #pragma once #include #include #include #include #include #include #include #include #include #include #include #include #include #include "HugeCTR/include/common.hpp" #include "HugeCTR/include/data_parser.hpp" namespace HugeCTR { /** * CPU Timer. */ class Timer { public: void start() { m_StartTime_ = std::chrono::steady_clock::now(); m_bRunning_ = true; } void stop() { m_EndTime_ = std::chrono::steady_clock::now(); m_bRunning_ = false; } double elapsedMilliseconds() { return elapsed().count() / 1000.0; } double elapsedMicroseconds() { return elapsed().count(); } double elapsedSeconds() { return elapsed().count() / 1000000.0; } private: std::chrono::microseconds elapsed() { std::chrono::time_point endTime; if (m_bRunning_) { endTime = std::chrono::steady_clock::now(); } else { endTime = m_EndTime_; } return std::chrono::duration_cast(endTime - m_StartTime_); } std::chrono::time_point m_StartTime_{}; std::chrono::time_point m_EndTime_{}; bool m_bRunning_ = false; }; /** * Helper class for switching device */ class CudaDeviceContext { int original_device; /** * Pop current cuda device and set new device. * @param i_device device ID to set * @param o_device device ID to pop, if o_device is NULL just set device to i_device. * @return the same as cudaError_t */ static inline cudaError_t get_set_device(int i_device, int* o_device = nullptr) { int current_device = 0; cudaError_t err = cudaSuccess; err = cudaGetDevice(¤t_device); if (err != cudaSuccess) return err; if (current_device != i_device) { err = cudaSetDevice(i_device); if (err != cudaSuccess) return err; } if (o_device) { *o_device = current_device; } return cudaSuccess; } public: CudaDeviceContext(int device) { CK_CUDA_THROW_(get_set_device(device, &original_device)); } ~CudaDeviceContext() noexcept(false) { CK_CUDA_THROW_(get_set_device(original_device)); } void set_device(int device) const { CK_CUDA_THROW_(get_set_device(device)); } }; /** * Get total product from dims. */ inline size_t get_size_from_dims(const std::vector& dims) { size_t matrix_size = 1; for (auto iter = dims.begin(); iter != dims.end(); iter++) { matrix_size = matrix_size * iter[0]; } return matrix_size; } /** * Check if file exist. */ inline bool file_exist(const std::string& name) { if (FILE* file = fopen(name.c_str(), "r")) { fclose(file); return true; } else { return false; } } /** * Check if file path exist if not create it. */ inline void check_make_dir(const std::string& finalpath) { if (mkdir(finalpath.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) == -1) { if (errno == EEXIST) { std::cout << (finalpath + " exist") << std::endl; } else { // something else std::cerr << ("cannot create" + finalpath + ": unexpected error") << std::endl; } } } /** * Generate random dataset for HugeCTR test. */ template class Checker_Traits; template <> class Checker_Traits { public: static char zero() { return 0; } static char accum(char pre, char x) { return pre + x; } static void write(int N, char* array, char chk_bits, std::ofstream& stream) { stream.write(reinterpret_cast(&N), sizeof(int)); stream.write(reinterpret_cast(array), N); stream.write(reinterpret_cast(&chk_bits), sizeof(char)); } static long long ID() { return 1; } }; template <> class Checker_Traits { public: static char zero() { return 0; } static char accum(char pre, char x) { return 0; } static void write(int N, char* array, char chk_bits, std::ofstream& stream) { stream.write(reinterpret_cast(array), N); } static long long ID() { return 0; } }; template class DataWriter { std::vector array_; std::ofstream& stream_; char check_char_{0}; public: DataWriter(std::ofstream& stream) : stream_(stream) { check_char_ = Checker_Traits::zero(); } void append(char* array, int N) { for (int i = 0; i < N; i++) { array_.push_back(array[i]); check_char_ = Checker_Traits::accum(check_char_, array[i]); } } void write() { // if(array_.size() == 0){ // std::cout << "array_.size() == 0" << std::endl;; // } Checker_Traits::write(static_cast(array_.size()), array_.data(), check_char_, stream_); check_char_ = Checker_Traits::zero(); array_.clear(); } }; template void data_generation_for_test(std::string file_list_name, std::string data_prefix, int num_files, int num_records_per_file, int slot_num, int vocabulary_size, int label_dim, int dense_dim, int max_nnz) { if (file_exist(file_list_name)) { std::cout << "File (" + file_list_name + ") exist. To generate new dataset plesae remove this file." << std::endl; return; } std::string directory; const size_t last_slash_idx = data_prefix.rfind('/'); if (std::string::npos != last_slash_idx) { directory = data_prefix.substr(0, last_slash_idx); } check_make_dir(directory); std::ofstream file_list_stream(file_list_name, std::ofstream::out); file_list_stream << (std::to_string(num_files) + "\n"); for (int k = 0; k < num_files; k++) { std::string tmp_file_name(data_prefix + std::to_string(k) + ".data"); file_list_stream << (tmp_file_name + "\n"); std::cout << tmp_file_name << std::endl; // data generation; std::ofstream out_stream(tmp_file_name, std::ofstream::binary); DataWriter data_writer(out_stream); DataSetHeader header = { Checker_Traits::ID(), num_records_per_file, label_dim, dense_dim, slot_num, 0, 0, 0}; data_writer.append(reinterpret_cast(&header), sizeof(DataSetHeader)); data_writer.write(); for (int i = 0; i < num_records_per_file; i++) { UnifiedDataSimulator idata_sim(1, max_nnz); // for nnz UnifiedDataSimulator fdata_sim(0, 1); // for lable and dense UnifiedDataSimulator ldata_sim(0, vocabulary_size - 1); // for key for (int j = 0; j < label_dim + dense_dim; j++) { float label_dense = fdata_sim.get_num(); data_writer.append(reinterpret_cast(&label_dense), sizeof(float)); } for (int k = 0; k < slot_num; k++) { int nnz = idata_sim.get_num(); data_writer.append(reinterpret_cast(&nnz), sizeof(int)); for (int j = 0; j < nnz; j++) { T key = ldata_sim.get_num(); while ((key % static_cast(slot_num)) != static_cast(k)) { // guarantee the key belongs to the current slot_id(=k) key = ldata_sim.get_num(); } data_writer.append(reinterpret_cast(&key), sizeof(T)); } } data_writer.write(); } out_stream.close(); } file_list_stream.close(); std::cout << file_list_name << " done!" << std::endl; return; } // Add a new data_generation function for LocalizedSparseEmbedding testing // In this function, the relationship between key and slot_id is: key's slot_id=(key%slot_num) // Add a new data_generation function for LocalizedSparseEmbedding testing // In this function, the relationship between key and slot_id is: key's slot_id=(key%slot_num) template void data_generation_for_localized_test(std::string file_list_name, std::string data_prefix, int num_files, int num_records_per_file, int slot_num, int vocabulary_size, int label_dim, int dense_dim, int max_nnz) { if (file_exist(file_list_name)) { return; } std::string directory; const size_t last_slash_idx = data_prefix.rfind('/'); if (std::string::npos != last_slash_idx) { directory = data_prefix.substr(0, last_slash_idx); } check_make_dir(directory); std::ofstream file_list_stream(file_list_name, std::ofstream::out); file_list_stream << (std::to_string(num_files) + "\n"); for (int k = 0; k < num_files; k++) { std::string tmp_file_name(data_prefix + std::to_string(k) + ".data"); file_list_stream << (tmp_file_name + "\n"); // data generation; std::ofstream out_stream(tmp_file_name, std::ofstream::binary); DataWriter data_writer(out_stream); DataSetHeader header = {1, num_records_per_file, label_dim, dense_dim, slot_num, 0, 0, 0}; data_writer.append(reinterpret_cast(&header), sizeof(DataSetHeader)); data_writer.write(); for (int i = 0; i < num_records_per_file; i++) { UnifiedDataSimulator idata_sim(1, max_nnz); // for nnz UnifiedDataSimulator fdata_sim(0, 1); // for lable and dense UnifiedDataSimulator ldata_sim(0, vocabulary_size - 1); // for key for (int j = 0; j < label_dim + dense_dim; j++) { float label_dense = fdata_sim.get_num(); data_writer.append(reinterpret_cast(&label_dense), sizeof(float)); } for (int k = 0; k < slot_num; k++) { int nnz = idata_sim.get_num(); data_writer.append(reinterpret_cast(&nnz), sizeof(int)); for (int j = 0; j < nnz; j++) { T key = ldata_sim.get_num(); while ((key % slot_num) != k) { // guarantee the key belongs to the current slot_id(=k) key = ldata_sim.get_num(); } data_writer.append(reinterpret_cast(&key), sizeof(T)); } } data_writer.write(); } out_stream.close(); } file_list_stream.close(); return; } template void data_generation_for_localized_test(std::string file_list_name, std::string data_prefix, int num_files, int num_records_per_file, int slot_num, int vocabulary_size, int label_dim, int dense_dim, int max_nnz, const std::vector slot_sizes) { if (file_exist(file_list_name)) { return; } std::string directory; const size_t last_slash_idx = data_prefix.rfind('/'); if (std::string::npos != last_slash_idx) { directory = data_prefix.substr(0, last_slash_idx); } check_make_dir(directory); std::ofstream file_list_stream(file_list_name, std::ofstream::out); file_list_stream << (std::to_string(num_files) + "\n"); for (int k = 0; k < num_files; k++) { std::string tmp_file_name(data_prefix + std::to_string(k) + ".data"); file_list_stream << (tmp_file_name + "\n"); // data generation; std::ofstream out_stream(tmp_file_name, std::ofstream::binary); DataWriter data_writer(out_stream); DataSetHeader header = {1, num_records_per_file, label_dim, dense_dim, slot_num, 0, 0, 0}; data_writer.append(reinterpret_cast(&header), sizeof(DataSetHeader)); data_writer.write(); for (int i = 0; i < num_records_per_file; i++) { UnifiedDataSimulator idata_sim(1, max_nnz); // for nnz per slot UnifiedDataSimulator fdata_sim(0, 1); // for lable and dense for (int j = 0; j < label_dim + dense_dim; j++) { float label_dense = fdata_sim.get_num(); data_writer.append(reinterpret_cast(&label_dense), sizeof(float)); } size_t offset = 0; for (int k = 0; k < slot_num; k++) { // int nnz = idata_sim.get_num(); int nnz = max_nnz; // for test data_writer.append(reinterpret_cast(&nnz), sizeof(int)); size_t slot_size = slot_sizes[k]; UnifiedDataSimulator ldata_sim(0, slot_size - 1); // for key for (int j = 0; j < nnz; j++) { T key = ldata_sim.get_num() + offset; data_writer.append(reinterpret_cast(&key), sizeof(T)); } offset += slot_size; } data_writer.write(); } out_stream.close(); } file_list_stream.close(); return; } inline void data_generation_for_raw( std::string file_name, long long num_samples, int label_dim = 1, int dense_dim = 13, int sparse_dim = 26, const std::vector slot_size = std::vector()) { std::ofstream out_stream(file_name, std::ofstream::binary); for (long long i = 0; i < num_samples; i++) { for (int j = 0; j < label_dim; j++) { int label = i % 2; out_stream.write(reinterpret_cast(&label), sizeof(int)); } for (int j = 0; j < dense_dim; j++) { int dense = j; out_stream.write(reinterpret_cast(&dense), sizeof(int)); } for (int j = 0; j < sparse_dim; j++) { int sparse = 0; if (slot_size.size() != 0) { UnifiedDataSimulator temp_sim( 0, (slot_size[j] - 1) < 0 ? 0 : (slot_size[j] - 1)); // range = [0, slot_size[j]) long long num_ = temp_sim.get_num(); sparse = num_ > std::numeric_limits::max() ? std::numeric_limits::max() : num_; } else { sparse = j; } out_stream.write(reinterpret_cast(&sparse), sizeof(int)); } } out_stream.close(); return; } /** * Find the item from a map according to str and pass by opt. * @return true: found / false: not found **/ template bool find_item_in_map(ITEM_TYPE& item, const std::string& str, const std::map& item_map) { typename std::map::const_iterator it = item_map.find(str); if (it == item_map.end()) { return false; } else { item = it->second; return true; } } template void print_cuda_buff(T* buf, int start, int end) { T h_buf[end - start]; cudaMemcpy(h_buf, buf, (end - start) * sizeof(T), cudaMemcpyDeviceToHost); std::cout << "Cuda Buff Print " << start << "-" << end << ": " << std::endl; for (int i = 0; i < (end - start); i++) { std::cout << h_buf[i] << ","; } std::cout << std::endl; } template void print_cuda_buff_sum(T* buf, int num) { T sum; T h_buf[num]; cudaMemcpy(h_buf, buf, (num) * sizeof(T), cudaMemcpyDeviceToHost); for (int i = 0; i < num; i++) { sum += h_buf[i]; } std::cout << "Cuda Buff Sum: " << sum << " size:" << num << std::endl; } template std::vector> sp_vec_dynamic_cast(std::vector>& vin) { std::vector> vout; for (auto& i : vin) { vout.emplace_back(std::dynamic_pointer_cast(i)); } return vout; } inline void set_affinity(std::thread& t, int core) { cpu_set_t cpuset; CPU_ZERO(&cpuset); CPU_SET(core, &cpuset); int rc = pthread_setaffinity_np(t.native_handle(), sizeof(cpu_set_t), &cpuset); if (rc != 0) { CK_THROW_(Error_t::WrongInput, "Error calling pthread_setaffinity_np: " + std::to_string(rc)); } return; } inline void set_affinity(std::thread& t, std::set set, bool excluded) { if (set.empty()) { auto get_core_id = [](int i) { return (i % 8) * 16 + (i / 8) % 2 + (i / 16) * 128; }; for (int i = 0; i < 31; i++) { int core = get_core_id(i); set.insert(core); } } cpu_set_t cpuset; CPU_ZERO(&cpuset); for (int core = 0; core < 256; core++) { if (excluded) { if (set.find(core) == set.end()) { CPU_SET(core, &cpuset); } } else { if (set.find(core) != set.end()) { CPU_SET(core, &cpuset); } } } int rc = pthread_setaffinity_np(t.native_handle(), sizeof(cpu_set_t), &cpuset); if (rc != 0) { CK_THROW_(Error_t::WrongInput, "Error calling pthread_setaffinity_np: " + std::to_string(rc)); } return; } template struct TypeConvert { static __host__ T convert(const float val) { return (T)val; } }; template <> struct TypeConvert<__half> { static __host__ __half convert(const float val) { return __float2half(val); } }; } // namespace HugeCTR huaweiatlasTest/samples /** * ============================================================================ * * Copyright (C) 2019, Huawei Technologies Co., Ltd. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 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 names of the copyright holders 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 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 "DeviceEngine.h" #include "hiaiengine/log.h" #include "hiaiengine/data_type_reg.h" #include #include HIAI_REGISTER_DATA_TYPE("input_data_st", input_data_st); HIAI_REGISTER_DATA_TYPE("result_output_st", result_output_st); HIAI_StatusT DeviceEngine::Init(const AIConfig &config, const std::vector &model_desc) { return HIAI_OK; } DeviceEngine::~DeviceEngine(){} HIAI_IMPL_ENGINE_PROCESS("DeviceEngine", DeviceEngine, DEVICE_ENGINE_INPUT_SIZE) { std::shared_ptr input_arg = std::static_pointer_cast(arg0); int hiai_ret; HIAI_ENGINE_LOG(MY_DEVICE_ERROR, "This is a Device ERROR Description."); // This is a Sample of how to print user defined log, this log can be found in dlog. HIAI_ENGINE_LOG(MY_DEVICE_WARNING, "This is a Device WARNING Description."); string str = "This message is from LogSample\n"; std::shared_ptr out = std::make_shared(); out->result_data.size = str.length() + 1; out->result_data.data = std::shared_ptr(reinterpret_cast(new char[str.length() + 1])); for (int i = 0; i < str.length(); i++) { out->result_data.data.get()[i] = str[i]; } out->result_data.data.get()[str.length()] = '\0'; hiai_ret = SendData(0, "result_output_st", std::static_pointer_cast(out)); if (HIAI_OK != hiai_ret) { HIAI_ENGINE_LOG(HIAI_IDE_ERROR, "send_data failed!hiai_ret = %d", hiai_ret); return hiai_ret; } return HIAI_OK; } src/gui/formabout.cpp10-100 /* Copyright (c) 2012, BuildmLearn Contributors listed at http://buildmlearn.org/people/ 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 BuildmLearn 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 "gui/formabout.h" #include "miscellaneous/iconfactory.h" #include "miscellaneous/textfactory.h" #include #include FormAbout::FormAbout(QWidget *parent) : QDialog(parent), m_ui(new Ui::FormAbout) { m_ui->setupUi(this); // Set flags and attributes. setWindowFlags(Qt::MSWindowsFixedSizeDialogHint | Qt::Dialog | Qt::WindowSystemMenuHint | Qt::WindowTitleHint); setWindowIcon(IconFactory::instance()->fromTheme("application-about")); //: About toolkit dialog title. setWindowTitle(tr("About %1").arg(APP_NAME)); m_ui->m_lblIcon->setPixmap(QPixmap(APP_ICON_PATH)); // Load information from embedded text files. QTextStream text_stream; QFile file; text_stream.setDevice(&file); file.setFileName(APP_INFO_PATH + "/CHANGELOG"); if (file.open(QIODevice::ReadOnly | QIODevice::Text)) { m_ui->m_txtChangelog->setText(text_stream.readAll()); file.close(); } else { m_ui->m_txtChangelog->setText(tr("Changelog not found.")); } file.setFileName(APP_INFO_PATH + "/LICENSE"); if (file.open(QIODevice::ReadOnly | QIODevice::Text)) { m_ui->m_txtLicense->setText(text_stream.readAll()); file.close(); } else { m_ui->m_txtLicense->setText(tr("License not found.")); } // Set other informative texts. m_ui->m_lblDesc->setText(tr("%8
" "Version: %1 (build on %2 with CMake %3)
" "Revision: %4
" "Build date: %5
" "Qt: %6 (compiled against %7)
").arg(qApp->applicationVersion(), CMAKE_SYSTEM, CMAKE_VERSION, APP_REVISION, TextFactory::parseDateTime(QString("%1 %2").arg(__DATE__, __TIME__)).toString(Qt::DefaultLocaleShortDate), qVersion(), QT_VERSION_STR, APP_NAME)); m_ui->m_txtInfo->setText(tr("%4 is an easy-to-use program that helps users make mobile apps without any knowledge of application development." "

Visit us at %2." "

Any feedback or suggestions related to %4 are always welcome. Please write to us at %1." "

Copyright (C) 2012 %3").arg(APP_EMAIL, APP_URL, APP_AUTHOR, APP_NAME)); } FormAbout::~FormAbout() { qDebug("Destroying FormAbout instance."); delete m_ui; } stephenzhj/NIM_PC_Demo #pragma once #include "pch.h" #include "avchat_business_wrapper.h" #include "g2_kit/component/avchat_component.h" #include "g2_kit/component/avchat_component_def.h" #include "shared/business_action_gateway/business_manager/business_manager.h" namespace nim_comp { AvChatComponent AvChatBusinessWrapper::component; std::shared_ptr AvChatBusinessWrapper::eventHandler_; void AvChatComponentEventHandler::onInvited(const std::string& invitor, std::vector userIDs, bool isFromGroup, int type) { QLOG_APP(L"AvChatComponentEventHandler onInvited, invitor: {0}") << invitor; nbase::BatpPack bp; bp.head_.action_name_ = kAvChatOnInvite; AvChatParams params; params.invitorAccid = invitor; params.members = userIDs; params.isFromGroup = isFromGroup; params.callType = type; bp.body_.param_ = params; nbase::BusinessManager::GetInstance()->Notify(bp); } void AvChatComponentEventHandler::onUserAccept(const std::string& userId) { QLOG_APP(L"AvChatComponentEventHandler onUserAccept, userId: {0}") << userId; nbase::BatpPack bp; bp.head_.action_name_ = kAvChatOnUserAccept; AvChatParams params; params.userId = userId; bp.body_.param_ = params; nbase::BusinessManager::GetInstance()->Notify(bp); } void AvChatComponentEventHandler::onUserReject(const std::string& userId) { QLOG_APP(L"AvChatComponentEventHandler onUserReject, userId: {0}") << userId; nbase::BatpPack bp; bp.head_.action_name_ = kAvChatOnUserReject; AvChatParams params; params.userId = userId; bp.body_.param_ = params; nbase::BusinessManager::GetInstance()->Notify(bp); } void AvChatComponentEventHandler::onUserEnter(const std::string& userId) { QLOG_APP(L"AvChatComponentEventHandler onUserEnter, userId: {0}") << userId; nbase::BatpPack bp; bp.head_.action_name_ = kAvChatOnUserEnter; AvChatParams params; params.userId = userId; bp.body_.param_ = params; nbase::BusinessManager::GetInstance()->Notify(bp); } void AvChatComponentEventHandler::onUserLeave(const std::string& userId) { QLOG_APP(L"AvChatComponentEventHandler onUserLeave, userId: {0}") << userId; nbase::BatpPack bp; bp.head_.action_name_ = kAvChatOnUserLeave; AvChatParams params; params.userId = userId; bp.body_.param_ = params; nbase::BusinessManager::GetInstance()->Notify(bp); } void AvChatComponentEventHandler::onUserDisconnect(const std::string& userId) { QLOG_APP(L"AvChatComponentEventHandler onUserDisconnect, userId: {0}") << userId; nbase::BatpPack bp; bp.head_.action_name_ = kAvChatOnUserDisconnect; AvChatParams params; params.userId = userId; bp.body_.param_ = params; nbase::BusinessManager::GetInstance()->Notify(bp); } void AvChatComponentEventHandler::onUserBusy(const std::string& userId) { QLOG_APP(L"AvChatComponentEventHandler onUserBusy, userId: {0}") << userId; nbase::BatpPack bp; bp.head_.action_name_ = kAvChatOnUserBusy; AvChatParams params; params.userId = userId; bp.body_.param_ = params; nbase::BusinessManager::GetInstance()->Notify(bp); } void AvChatComponentEventHandler::onUserCancel(const std::string& userId) { QLOG_APP(L"AvChatComponentEventHandler onUserCanale, userId: {0}") << userId; nbase::BatpPack bp; bp.head_.action_name_ = kAvChatOnUserCancel; AvChatParams params; params.userId = userId; bp.body_.param_ = params; nbase::BusinessManager::GetInstance()->Notify(bp); } void AvChatComponentEventHandler::onCallingTimeOut() { QLOG_APP(L"AvChatComponentEventHandler onCallingTimeOut"); nbase::BatpPack bp; bp.head_.action_name_ = kAvChatOnCallingTimeOut; nbase::BusinessManager::GetInstance()->Notify(bp); } void AvChatComponentEventHandler::onDisconnect(int reason) { QLOG_APP(L"AvChatComponentEventHandler onDisconnect"); nbase::BatpPack bp; bp.head_.action_name_ = kAvChatOnDisconnect; AvChatParams params; params.reason = reason; bp.body_.param_ = params; nbase::BusinessManager::GetInstance()->Notify(bp); } void AvChatComponentEventHandler::OnVideoToAudio() { QLOG_APP(L"AvChatComponentEventHandler OnVideoToAudio"); nbase::BatpPack bp; bp.head_.action_name_ = kAvChatOnVideoToAudio; nbase::BusinessManager::GetInstance()->Notify(bp); } void AvChatComponentEventHandler::onCallEnd() { QLOG_APP(L"AvChatComponentEventHandler onCallEnd"); nbase::BatpPack bp; bp.head_.action_name_ = kAvChatOnCallEnd; nbase::BusinessManager::GetInstance()->Notify(bp); } void AvChatComponentEventHandler::onError(int errCode) { QLOG_APP(L"AvChatComponentEventHandler onError: {0}")<Notify(bp); } void AvChatComponentEventHandler::onOtherClientAccept() { QLOG_APP(L"AvChatComponentEventHandler onOtherClientAccept: "); nbase::BatpPack bp; bp.head_.action_name_ = kAvChatOnOtherClientAccept; nbase::BusinessManager::GetInstance()->Notify(bp); } void AvChatComponentEventHandler::onOtherClientReject() { QLOG_APP(L"AvChatComponentEventHandler onOtherClientReject: "); nbase::BatpPack bp; bp.head_.action_name_ = kAvChatOnOtherClientReject; nbase::BusinessManager::GetInstance()->Notify(bp); } void AvChatComponentEventHandler::onUserNetworkQuality(std::map network_quality) { QLOG_APP(L"AvChatComponentEventHandler onUserNetworkQuality: "); nbase::BatpPack bp; bp.head_.action_name_ = kAvChatOnUserNetworkQuality; AvChatParams params; params.network_quality = network_quality; bp.body_.param_ = params; nbase::BusinessManager::GetInstance()->Notify(bp); } void AvChatComponentEventHandler::onCameraAvailable(const std::string& userId, bool available) { QLOG_APP(L"AvChatComponentEventHandler onCameraAvailable, userId: {0}, available: {1}") << userId << available; nbase::BatpPack bp; bp.head_.action_name_ = kAvChatOnCameraAvailable; AvChatParams params; params.userId = userId; params.cameraAvailable = available; bp.body_.param_ = params; nbase::BusinessManager::GetInstance()->Notify(bp); } void AvChatComponentEventHandler::onAudioAvailable(const std::string& userId, bool available) { QLOG_APP(L"AvChatComponentEventHandler onAudioAvailable, userId: {0}, available: {1}") << userId << available; nbase::BatpPack bp; bp.head_.action_name_ = kAvChatOnAudioAvailable; AvChatParams params; params.userId = userId; params.audioAvailable = available; bp.body_.param_ = params; nbase::BusinessManager::GetInstance()->Notify(bp); } void AvChatComponentEventHandler::onLocalCameraStateChanged(bool available) { nbase::BatpPack bp; bp.head_.action_name_ = kAvChatOnLocalCameraStateChanged; AvChatParams params; params.cameraAvailable = available; bp.body_.param_ = params; nbase::BusinessManager::GetInstance()->Notify(bp); } void AvChatComponentEventHandler::onAudioVolumeChanged(unsigned char value, bool isRecord) { nbase::BatpPack bp; bp.head_.action_name_ = kAvChatOnAudioVolumChanged; AvChatParams params; params.volume = value; params.isRecordDevice = isRecord; bp.body_.param_ = params; nbase::BusinessManager::GetInstance()->Notify(bp); } void AvChatBusinessWrapper::release(const nbase::BatpPack& request) { QLOG_APP(L"Release component resource"); component.release(); nbase::BusinessManager::GetInstance()->Response(request); } void AvChatBusinessWrapper::setupAppKey(const nbase::BatpPack& request) { AvChatParams params = nbase::BatpParamCast(request.body_.param_); std::string key = params.appKey; bool bUseRtcSafeMode = params.useRtcSafeMode; component.setupAppKey(key, bUseRtcSafeMode); eventHandler_.reset(); eventHandler_ = std::make_shared(); component.regEventHandler(eventHandler_); } //avchat 组件并未定义onCalling事件,为了通知界面更新状态,在AvChatBusinessWrapper::call中发一个onCalling事件 void AvChatBusinessWrapper::call(const nbase::BatpPack& request) { AvChatParams params = nbase::BatpParamCast(request.body_.param_); std::string userId = params.userId; AVCHAT_CALL_TYPE callType = AVCHAT_CALL_TYPE(params.callType); component.call(userId, callType, params.optCb); nbase::BatpPack bp; bp.head_.action_name_ = kAvChatOnCalling; bp.body_.param_ = params; nbase::BusinessManager::GetInstance()->Notify(bp); } void AvChatBusinessWrapper::login(const nbase::BatpPack& request) { assert(false); } void AvChatBusinessWrapper::logout(const nbase::BatpPack& request) { assert(false); } void AvChatBusinessWrapper::accept(const nbase::BatpPack& request) { AvChatParams params = nbase::BatpParamCast(request.body_.param_); component.accept(params.optCb); } void AvChatBusinessWrapper::reject(const nbase::BatpPack& request) { AvChatParams params = nbase::BatpParamCast(request.body_.param_); component.reject(params.optCb); } void AvChatBusinessWrapper::hangup(const nbase::BatpPack& request) { AvChatParams params = nbase::BatpParamCast(request.body_.param_); component.hangup(params.optCb); } void AvChatBusinessWrapper::switchCallType(const nbase::BatpPack& request) { AvChatParams params = nbase::BatpParamCast(request.body_.param_); component.switchCallType(params.sessionId, params.callType); } void AvChatBusinessWrapper::setAudioMute(const nbase::BatpPack& request) { AvChatParams params = nbase::BatpParamCast(request.body_.param_); component.setAudioMute(params.sessionId, params.muteAudio); } void AvChatBusinessWrapper::cancel(const nbase::BatpPack& request) { AvChatParams params = nbase::BatpParamCast(request.body_.param_); component.cancel(params.optCb); } void AvChatBusinessWrapper::leave(const nbase::BatpPack& request) { AvChatParams params = nbase::BatpParamCast(request.body_.param_); component.leave(params.optCb); } void AvChatBusinessWrapper::setupLocalView(const nbase::BatpPack& request) { AvChatParams params = nbase::BatpParamCast(request.body_.param_); nertc::NERtcVideoCanvas canvas; canvas.window = params.window; canvas.cb = params.dataCb; canvas.user_data = nullptr; canvas.scaling_mode = nertc::kNERtcVideoScaleFit; component.setupLocalView(&canvas); nbase::BatpPackResponse response(request.head_, BatpTrailInfoFromHere); nbase::BusinessManager::GetInstance()->Response(response); } void AvChatBusinessWrapper::setupRemoteView(const nbase::BatpPack& request) { AvChatParams params = nbase::BatpParamCast(request.body_.param_); nertc::NERtcVideoCanvas canvas; canvas.window = params.window; canvas.cb = params.dataCb; canvas.user_data = nullptr; canvas.scaling_mode = nertc::kNERtcVideoScaleFit; component.setupRemoteView(&canvas, params.userId); } void AvChatBusinessWrapper::switchCamera(const nbase::BatpPack& request) { component.switchCamera(); } void AvChatBusinessWrapper::getLocalDeviceList( std::vector* recordDevicesNames, std::vector* recordDevicesIds, std::vector* playoutDevicesNames, std::vector* playoutDevicesIds, std::vector* videoDeviceNames, std::vector* videoDeviceIds) { component.getLocalDeviceList( recordDevicesNames, recordDevicesIds, playoutDevicesNames, playoutDevicesIds, videoDeviceNames, videoDeviceIds); } unsigned char AvChatBusinessWrapper::getAudioVolumn(bool isRecord) { auto value = component.getAudioVolumn(isRecord); return value <= 255 ? value : value % 255; } std::wstring AvChatBusinessWrapper::getVideoDevice() { return component.getVideoDevice(); } std::wstring AvChatBusinessWrapper::getAudioDevice(bool isRecord) { return component.getAudioDevice(isRecord); } // bool AvChatBusinessWrapper::isAudioEnable(bool isRecord) // { // return component.isAudioEnable(isRecord); // } // bool AvChatBusinessWrapper::isVideoEnable() // { // return component.isVideoEnable(); // } void AvChatBusinessWrapper::setRecordDeviceVolume(const nbase::BatpPack& request) { AvChatParams params = nbase::BatpParamCast(request.body_.param_); component.setRecordDeviceVolume(params.volume); } void AvChatBusinessWrapper::setPlayoutDeviceVolume(const nbase::BatpPack& request) { AvChatParams params = nbase::BatpParamCast(request.body_.param_); component.setPlayoutDeviceVolume(params.volume); } void AvChatBusinessWrapper::setVideoDevice(const nbase::BatpPack& request) { AvChatParams params = nbase::BatpParamCast(request.body_.param_); component.setVideoDevice(params.deviceId); } void AvChatBusinessWrapper::setAudioDevice(const nbase::BatpPack& request) { AvChatParams params = nbase::BatpParamCast(request.body_.param_); component.setAudioDevice(params.deviceId, params.isRecordDevice); } void AvChatBusinessWrapper::enableLocalVideo(const nbase::BatpPack& request) { AvChatParams params = nbase::BatpParamCast(request.body_.param_); component.enableLocalVideo(params.cameraAvailable); } void AvChatBusinessWrapper::muteLocalAudio(const nbase::BatpPack& request) { AvChatParams params = nbase::BatpParamCast(request.body_.param_); component.muteLocalAudio(params.muteAudio); } void AvChatBusinessWrapper::enableAudioPlayout(const nbase::BatpPack& request) { AvChatParams params = nbase::BatpParamCast(request.body_.param_); component.enableAudioPlayout(params.audioAvailable); } void AvChatBusinessWrapper::startVideoPreview(const nbase::BatpPack& request) { AvChatParams params = nbase::BatpParamCast(request.body_.param_); component.startVideoPreview(params.startPreview); } void AvChatBusinessWrapper::startAudioDeviceLoopbackTest(const nbase::BatpPack& request) { AvChatParams params = nbase::BatpParamCast(request.body_.param_); component.startAudioDeviceLoopbackTest(params.interval); } void AvChatBusinessWrapper::stopAudioDeviceLoopbackTest(const nbase::BatpPack& request) { component.stopAudioDeviceLoopbackTest(); } void AvChatBusinessWrapper::setVideoQuality(const nbase::BatpPack& request) { AvChatParams params = nbase::BatpParamCast(request.body_.param_); component.setVideoQuality((nertc::NERtcVideoProfileType)params.videoQuality); } void AvChatBusinessWrapper::getTokenService(const nbase::BatpPack& request) { AvChatParams params = nbase::BatpParamCast(request.body_.param_); component.setTokenService((GetTokenServiceFunc)params.tockenServiceFunc); } std::string AvChatBusinessWrapper::getChannelId() { auto info = component.getCreatedChannelInfo(); return info.channel_info_.channel_id_; } }uppsrc/MSSQL/MSSQL.cpp #include "MSSQL.h" namespace Upp { String MsSqlTextType(int width) { if(width <= 4000) return NFormat("varchar(%d)", width); return "text"; } void IdentityInsert(Sql& sql, const SqlInsert& ins) { sql.Execute("SET IDENTITY_INSERT " + ins.GetTable().ToString() + " ON;" + ((SqlStatement)ins).Get(MSSQL)); } void IdentityInsert(const SqlInsert& ins) { IdentityInsert(SQL, ins); } }; src/runner/job.hh /* * Copyright (C) 2011-2012, . * * This software is provided "as is" without warranty of any kind, * either expressed or implied, including but not limited to the * implied warranties of fitness for a particular purpose. * * See the LICENSE file for more information. */ /** ** \file runner/job.hh ** \brief Definition of runner::Job. */ #include #ifndef RUNNER_JOB_HH # define RUNNER_JOB_HH // declare sched::Job # include // declare runner::State # include // declare object::* # include # include // declare evalution interface eval::Action # include // Avoid post-declaration of runner::Job # include // Register events used to watch for future changes of the evaluation // result. \a Name corresponds to an attribute which of the object // accessible through an accessor Name_get(). #define URBI_AT_HOOK(Name) \ URBI_AT_HOOK_(Name##_get) #define URBI_AT_HOOK_(accessor) \ do \ { \ if (runner::Job* r = \ ::kernel::urbiserver->getCurrentRunnerOpt()) \ if (r->dependencies_log_get()) \ { \ try \ { \ r->dependencies_log_set(false); \ GD_CATEGORY(Urbi.At); \ GD_FPUSH_TRACE("Register %s for at monitoring on %s", #accessor, \ this); \ rEvent e = accessor()->as(); \ r->dependencies_log_set(true); \ r->dependency_add(e); \ } \ catch (...) \ { \ r->dependencies_log_set(true); \ throw; \ } \ } \ } \ while (false) // Deactivate dependency tracking for the current scope #define URBI_SCOPE_DISABLE_DEPENDENCY_TRACKER \ runner::Job* usddt_j = ::kernel::urbiserver->getCurrentRunnerOpt(); \ bool usddt_d = false; \ if (usddt_j) \ { \ usddt_d = usddt_j->dependencies_log_get(); \ usddt_j->dependencies_log_set(false); \ } \ FINALLY(((runner::Job*, usddt_j))((bool, usddt_d)), \ if (usddt_j) \ usddt_j->dependencies_log_set(usddt_d)) namespace runner { using urbi::object::Profile; using urbi::object::FunctionProfile; /// Job is holding a common stack representation for all method of /// evaluations. Method of evaluation could be Text evaluation, AST /// evaluation, or Byte code evaluation. class Job : public sched::Job { public: typedef sched::Job super_type; typedef object::Object Object; typedef object::rObject rObject; typedef object::rLobby rLobby; /// Create a job from another one. /// /// \param model The parent job. The scheduler and tags will be inherited // from it. Job(const Job& model, size_t stack_size = 0); /// Create a new job. /// /// \param lobby The lobby attached to the current job. /// If null, used the main Lobby. /// /// \param scheduler The scheduler to which this job will be attached. Job(rLobby lobby, sched::Scheduler& scheduler); /// Destroy a job and the action bound to it. virtual ~Job(); public: /// urbiscript evaluation /// \{ /// Urbiscript is evaluated in this function, whatever the /// representation used to store urbiscript sources. virtual void work(); /// Return the result of the latest evaluation. /// FIXME: is that used ?! virtual rObject result_get(); /// Get the current runner as an Urbi Job or nil if the job is /// terminated. object::rJob as_job(); /// Signal a scheduling error exception. /// Implementation for abstract class sched::Job. /// /// \param msg The explanation of the scheduling error. virtual void scheduling_error(const std::string& msg); // Avoid cycle dependencies with cached objects. virtual void terminate_cleanup(); /// \} /// Job status defined by Tags /// \{ /// Inherited from sched::job. /// Bounce on the state to know if one tag is frozen. virtual bool frozen() const; /// Freeze the current job, without using any tag. void frozen_set(bool); bool frozen_get(); /// Inherited from sched::job. /// Bounce on the state to know if the job has a specific tag. virtual size_t has_tag(const sched::Tag& tag, size_t max_depth = (size_t)-1) const; bool has_tag(const object::rTag& tag) const; /// Inherited from sched::job. /// Bounce on the state to know the higest tag priority. virtual sched::prio_type prio_get() const; /// \} Job* name_set(const std::string& name); const std::string name_get() const; /// Job processing /// \{ /// Create a new Job that inherits the current lobby and clone /// necessary stacks parts. Define an action which would be /// executed by the child, and if a collector is specified, then /// the child is registered in the collector. /// /// This command return a child job which has to be started with /// 'start_job()' to execute the action asynchronously. Job* spawn_child(eval::Action action, Job::Collector& collector, size_t stack_size = 0); Job* spawn_child(eval::Action action, size_t stack_size = 0); void set_action(eval::Action action); /// \} /// \name Profiling /// \{ /// Start profiling into \a profile. /// profile_start should be used with profile_stop. void profile_start(Profile* profile, libport::Symbol name, Object* current, bool count = false); /// Stop profiling. /// profile_stop should be used with profile_start. void profile_stop(); /// Fork the profiling content of the parent /// profile_fork should be used with profile_join. void profile_fork(Job& parent); /// Append profiling content of a child. /// profile_join should be used with profile_fork. void profile_join(Job& child); /// Object* profile_enter(Object* function, libport::Symbol msg); /// void profile_leave(Object* idx); /// Wheter there is a profiling in run. bool is_profiling() const; /// The current profile to fill - if any. ATTRIBUTE_R(Profile*, profile); private: mutable Profile::Info profile_info_; protected: virtual void hook_preempted() const; virtual void hook_resumed() const; /// \} /// \name Dependencies tarcker /// \{ public: typedef boost::unordered_set dependencies_type; dependencies_type& dependencies(); bool dependencies_log_get() const; void dependencies_log_set(bool val); void dependency_add(object::rEvent evt); void dependency_add(object::rObject evt); void dependencies_clear(); protected: bool dependencies_log_; dependencies_type dependencies_; /// \} /// \name sched::Job accessors /// \{ public: // FIXME: should ensure that one job release the non-interruptible flag. bool non_interruptible_get() const; void non_interruptible_set(bool); /// \} public: State state; private: eval::Action worker_; rObject result_cache_; object::rJob job_cache_; }; } // namespace runner # if defined LIBPORT_COMPILATION_MODE_SPEED # include # endif #endif // ! RUNNER_JOB_HH 0 #include "abcg.hpp" #include "openglwindow.hpp" int main(int argc, char **argv) { // Create application instance abcg::Application app(argc, argv); // Create OpenGL window auto window{std::make_unique()}; window->setWindowSettings({.title = "First App"}); // Run application app.run(std::move(window)); return 0; } JujuDel/MNN // // DepthToSpaceTest.cpp // MNNTests // // Created by MNN on 2019/12/24. // Copyright © 2018, Alibaba Group Holding Limited // #include #include #include "MNNTestSuite.h" #include "TestUtils.h" using namespace MNN::Express; class DepthToSpaceTest : public MNNTestCase { public: virtual ~DepthToSpaceTest() = default; virtual bool run(int precision) { auto input = _Input({1, 8, 2, 3}, NCHW); input->setName("input"); // set input data const float input_data[] = { 0., 1., 2., 3., 4., 5., 9., 10., 11., 12., 13., 14., 18., 19., 20., 21., 22., 23., 27., 28., 29., 30., 31., 32., 36., 37., 38., 39., 40., 41., 45., 46., 47., 48., 49., 50., 54., 55., 56., 57., 58., 59., 63., 64., 65., 66., 67., 68. }; auto inputPtr = input->writeMap(); memcpy(inputPtr, input_data, 48 * sizeof(float)); input->unMap(); std::unique_ptr depthToSpaceOp(new MNN::OpT); depthToSpaceOp->type = MNN::OpType_DepthToSpace; auto depthtospaceParam = new MNN::DepthSpaceParamT; depthtospaceParam->blockSize = 2; depthToSpaceOp->main.type = MNN::OpParameter_DepthSpaceParam; depthToSpaceOp->main.value = depthtospaceParam; depthtospaceParam->mode = MNN::DepthToSpaceMode_DCR; auto outputDCR = Variable::create(Expr::create(depthToSpaceOp.get(), {input})); const std::vector expectedOutputDCR = { 0., 18., 1., 19., 2., 20., 36., 54., 37., 55., 38., 56., 3., 21., 4., 22., 5., 23., 39., 57., 40., 58., 41., 59., 9., 27., 10., 28., 11., 29., 45., 63., 46., 64., 47., 65., 12., 30., 13., 31., 14., 32., 48., 66., 49., 67., 50., 68. }; depthtospaceParam->mode = MNN::DepthToSpaceMode_CRD; auto outputCRD = Variable::create(Expr::create(depthToSpaceOp.get(), {input})); const std::vector expectedOutputCRD = { 0., 9., 1., 10., 2., 11., 18., 27., 19., 28., 20., 29., 3., 12., 4., 13., 5., 14., 21., 30., 22., 31., 23., 32., 36., 45., 37., 46., 38., 47., 54., 63., 55., 64., 56., 65., 39., 48., 40., 49., 41., 50., 57., 66., 58., 67., 59., 68. }; auto check = [](VARP output, const std::vector& expectedOutput) { const std::vector expectedDim = {1, 2, 4, 6}; auto gotOutput = output->readMap(); auto gotDim = output->getInfo()->dim; if (!checkVector(gotOutput, expectedOutput.data(), 48, 0)) { MNN_ERROR("DepthToSpaceTest test failed!\n"); return false; } if (!checkVector(gotDim.data(), expectedDim.data(), 4, 0)) { MNN_ERROR("DepthToSpaceTest test failed!\n"); return false; } return true; }; if (!check(outputDCR, expectedOutputDCR)) { MNN_ERROR("DCR mode failed!\n"); return false; } if (!check(outputCRD, expectedOutputCRD)) { MNN_ERROR("CRD mode failed!\n"); return false; } return true; } }; MNNTestSuiteRegister(DepthToSpaceTest, "op/depthtospace"); #pragma once #include #include #include #include #include namespace mstch { namespace internal { template class object_t { public: const N& at(const std::string& name) const { cache[name] = (methods.at(name))(); return cache[name]; } bool has(const std::string name) const { return methods.count(name) != 0; } protected: template void register_methods(S* s, std::map methods) { for(auto& item: methods) this->methods.insert({item.first, std::bind(item.second, s)}); } private: std::map> methods; mutable std::map cache; }; template class is_fun { private: using not_fun = char; using fun_without_args = char[2]; using fun_with_args = char[3]; template struct really_has; template static fun_without_args& test( really_has*); template static fun_with_args& test( really_has*); template static not_fun& test(...); public: static bool const no_args = sizeof(test(0)) == sizeof(fun_without_args); static bool const has_args = sizeof(test(0)) == sizeof(fun_with_args); }; template using node_renderer = std::function; template class lambda_t { public: lambda_t() { } template lambda_t(F f, typename std::enable_if::no_args>::type* = 0): fun([f](node_renderer renderer, const std::string&) { return renderer(f()); }) { } template lambda_t(F f, typename std::enable_if::has_args>::type* = 0): fun([f](node_renderer renderer, const std::string& text) { return renderer(f(text)); }) { } std::string operator()(node_renderer renderer, const std::string& text = "") const { return fun(renderer, text); } private: std::function renderer, const std::string&)> fun; }; } // original variant //using node = boost::make_recursive_variant< // std::nullptr_t, // std::string, // int, // double, // bool, // internal::lambda_t, // std::shared_ptr>, // std::map, // std::vector // >::type; enum class node_type { NULL_T, STRING, INT, DOUBLE, BOOL, LAMBDA, OBJECT, MAP, ARRAY }; // mstch requires 'node' to be copyable - using shared_ptrs for safety // tagged union is possible here, but tricky as // unfortunately VS2013 doesn't support unrestricted unions // see example: https://github.com/staticlibs/staticlib_serialization/blob/770a4c751558837af19ad852f8b32c0e97de1ebb/include/staticlib/serialization/JsonValue.hpp#L76 // storing map and array together to avoid additional shared_ptr class node { private: using map_or_array_type = std::pair, std::vector>; node_type type; std::nullptr_t null_value; std::string string_value; int int_value; double double_value; bool bool_value; internal::lambda_t lambda_value; std::shared_ptr> object_value; std::shared_ptr map_or_array_value; public: node() : type(node_type::NULL_T) { } // don't know whether to create map or array, from initializer_list // let's create neither node(const std::initializer_list&) : type(node_type::NULL_T) { } node(std::nullptr_t) : type(node_type::NULL_T) { } node(std::string string_value) : type(node_type::STRING), string_value(std::move(string_value)) { } node(int int_value) : type(node_type::INT), int_value(int_value) { } node(double double_value) : type(node_type::DOUBLE), double_value(double_value) { } node(bool bool_value) : type(node_type::BOOL), bool_value(bool_value) { } node(const internal::lambda_t& lambda_value) : type(node_type::LAMBDA), lambda_value(lambda_value) { } template node(std::shared_ptr object_value) : type(node_type::OBJECT), object_value(std::move(object_value)) { } node(const std::map& map_value) : type(node_type::MAP), map_or_array_value(std::make_shared()) { std::map tmp = map_value; this->map_or_array_value->first = std::move(tmp); } node(std::map&& map_value) : type(node_type::MAP), map_or_array_value(std::make_shared()) { this->map_or_array_value->first = std::move(map_value); } node(const std::vector& array) : type(node_type::ARRAY), map_or_array_value(std::make_shared()) { std::vector tmp = array; this->map_or_array_value->second = std::move(tmp); } node(std::vector&& array) : type(node_type::ARRAY), map_or_array_value(std::make_shared()) { this->map_or_array_value->second = std::move(array); } template typename Visitor::result_type apply_visitor(const Visitor& visitor) const { switch (type) { case node_type::NULL_T: return visitor(null_value); case node_type::STRING: return visitor(string_value); case node_type::INT: return visitor(int_value); case node_type::DOUBLE: return visitor(double_value); case node_type::BOOL: return visitor(bool_value); case node_type::LAMBDA: return visitor(lambda_value); case node_type::OBJECT: return visitor(object_value); case node_type::MAP: return visitor(map_or_array_value->first); case node_type::ARRAY: return visitor(map_or_array_value->second); default: return visitor(null_value); } } std::string& get_string() { if (node_type::STRING == this->type) { return string_value; } else { return empty_string(); } } int get_int() { if (node_type::INT == this->type) { return int_value; } else { return 0; } } double get_double() { if (node_type::DOUBLE == this->type) { return double_value; } else { return 0; } } double get_bool() { if (node_type::BOOL == this->type) { return bool_value; } else { return false; } } internal::lambda_t& get_lambda() { if (node_type::LAMBDA == this->type) { return lambda_value; } else { return empty_lambda(); } } std::shared_ptr>& get_object() { if (node_type::OBJECT == this->type) { return object_value; } else { return empty_object(); } } std::map& get_map() { if (node_type::MAP == this->type) { return map_or_array_value->first; } else { return empty_map(); } } std::vector& get_array() { if (node_type::ARRAY == this->type) { return map_or_array_value->second; } else { return empty_array(); } } private: std::string& empty_string() { static std::string empty{""}; return empty; } internal::lambda_t& empty_lambda() { static internal::lambda_t empty{}; return empty; } std::shared_ptr>& empty_object() { static std::shared_ptr> empty{}; return empty; } std::map& empty_map() { static std::map empty{}; return empty; } std::vector& empty_array() { static std::vector empty{0}; return empty; } }; } #pragma once /**************************************************************************** Copyright (c) 2019 ZhuLei Email: 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 "scriptcommon.h" #include "ScriptCodeStyle.h" #include "ScriptExecBlock.h" #include "ScriptRunState.h" #include "ScriptClassMgr.h" namespace zlscript { int CAddExeCode::Run(CScriptExecBlock* pBlock, CBaseExeCode **pNextPoint) { StackVarInfo& resultVar = pBlock->m_register[cResultRegister]; StackVarInfo& leftVar = pBlock->m_register[R_A]; //pBlock->GetVal(rightVar, cType, dwPos); switch (leftVar.cType) { case EScriptVal_Int: { __int64 nVal2 = 0; pBlock->GetVal(nVal2, cType, dwPos); //resultVar = leftVar.Int64 + nVal2; SCRIPTVAR_SET_INT(resultVar, leftVar.Int64 + nVal2); } break; case EScriptVal_Double: { double dVal2 = 0; pBlock->GetVal(dVal2, cType, dwPos); SCRIPTVAR_SET_FLOAT(resultVar , leftVar.Double + dVal2); } break; case EScriptVal_String: { std::string strVal1; SCRIPTVAR_GET_STRING(leftVar, strVal1); std::string strVal2; pBlock->GetVal(strVal2, cType, dwPos); strVal1 = strVal1 + strVal2; SCRIPTVAR_SET_STRING(resultVar, strVal1); } break; default: return CScriptExecBlock::ERESULT_ERROR; } if (pNextPoint) { *pNextPoint = this->m_pNext; } return CScriptExecBlock::ERESULT_CONTINUE; } std::string CAddExeCode::GetCodeString() { char strbuff[128] = { 0 }; sprintf(strbuff, "ADD\tRegisterIndex:%d\tVarType:%d\tpos:%d", (int)cResultRegister, (int)cType, (int)dwPos); return strbuff; } int CSumExeCode::Run(CScriptExecBlock* pBlock, CBaseExeCode **pNextPoint) { StackVarInfo& resultVar = pBlock->m_register[cResultRegister]; StackVarInfo& leftVar = pBlock->m_register[R_A]; if (leftVar.cType == EScriptVal_Int) { __int64 nVal2 = 0; pBlock->GetVal(nVal2, cType, dwPos); SCRIPTVAR_SET_INT(resultVar,leftVar.Int64-nVal2); } else if (leftVar.cType == EScriptVal_Double) { double dVal2 = 0; pBlock->GetVal(dVal2, cType, dwPos); SCRIPTVAR_SET_FLOAT(resultVar, leftVar.Double - dVal2); } else { return CScriptExecBlock::ERESULT_ERROR; } if (pNextPoint) { *pNextPoint = this->m_pNext; } return CScriptExecBlock::ERESULT_CONTINUE; } std::string CSumExeCode::GetCodeString() { char strbuff[128] = { 0 }; sprintf(strbuff, "Sum\tRegisterIndex:%d\tVarType:%d\tpos:%d", (int)cResultRegister, (int)cType, (int)dwPos); return strbuff; } int CMulExeCode::Run(CScriptExecBlock* pBlock, CBaseExeCode **pNextPoint) { StackVarInfo& resultVar = pBlock->m_register[cResultRegister]; StackVarInfo& leftVar = pBlock->m_register[R_A]; if (leftVar.cType == EScriptVal_Int) { __int64 nVal2 = 0; pBlock->GetVal(nVal2, cType, dwPos); SCRIPTVAR_SET_INT(resultVar, leftVar.Int64 * nVal2); } else if (leftVar.cType == EScriptVal_Double) { double dVal2 = 0; pBlock->GetVal(dVal2, cType, dwPos); SCRIPTVAR_SET_FLOAT(resultVar ,leftVar.Double * dVal2); } else{ return CScriptExecBlock::ERESULT_ERROR; } if (pNextPoint) { *pNextPoint = this->m_pNext; } return CScriptExecBlock::ERESULT_CONTINUE; } std::string CMulExeCode::GetCodeString() { char strbuff[128] = { 0 }; sprintf(strbuff, "Mul\tResultRegister:%d\tVarType:%d\tpos:%d", (int)cResultRegister, (int)cType, (int)dwPos); return strbuff; } int CDivExeCode::Run(CScriptExecBlock* pBlock, CBaseExeCode **pNextPoint) { StackVarInfo& resultVar = pBlock->m_register[cResultRegister]; StackVarInfo& leftVar = pBlock->m_register[R_A]; if (leftVar.cType == EScriptVal_Int) { __int64 nVal2 = 0; GetInt_StackVar(&pBlock->m_register[R_D]); pBlock->GetVal(nVal2, cType, dwPos); if (nVal2 == 0) { SCRIPTVAR_SET_INT(resultVar, (__int64)0xffffffffffffffff); } else { SCRIPTVAR_SET_INT(resultVar, leftVar.Int64 / nVal2); } } else if (leftVar.cType == EScriptVal_Double) { double dVal2 = 0; pBlock->GetVal(dVal2, cType, dwPos); if (dVal2 <= 0.00000001f && dVal2 >= -0.00000001f) { SCRIPTVAR_SET_FLOAT(resultVar, (double)1.7976931348623158e+308); } else { SCRIPTVAR_SET_FLOAT(resultVar, leftVar.Double / dVal2); } } else{ return CScriptExecBlock::ERESULT_ERROR; } if (pNextPoint) { *pNextPoint = this->m_pNext; } return CScriptExecBlock::ERESULT_CONTINUE; } std::string CDivExeCode::GetCodeString() { char strbuff[128] = { 0 }; sprintf(strbuff, "Div\tRegisterIndex:%d\tVarType:%d\tpos:%d", (int)cResultRegister, (int)cType, (int)dwPos); return strbuff; } int CModExeCode::Run(CScriptExecBlock* pBlock, CBaseExeCode **pNextPoint) { StackVarInfo& resultVar = pBlock->m_register[cResultRegister]; StackVarInfo& leftVar = pBlock->m_register[R_A]; __int64 nVal1 = 0; SCRIPTVAR_GET_INT(leftVar,nVal1); __int64 nVal2 = 0; pBlock->GetVal(nVal2, cType, dwPos); if (nVal2 == 0) { resultVar = (__int64)0; } else { resultVar = nVal1 % nVal2; } if (pNextPoint) { *pNextPoint = this->m_pNext; } return CScriptExecBlock::ERESULT_CONTINUE; } std::string CModExeCode::GetCodeString() { char strbuff[128] = { 0 }; sprintf(strbuff, "Mod\tRegisterIndex:%d\tVarType:%d\tpos:%d", (int)cResultRegister, (int)cType, (int)dwPos); return strbuff; } int CMinusExeCode::Run(CScriptExecBlock* pBlock, CBaseExeCode **pNextPoint) { StackVarInfo& resultVar = pBlock->m_register[cResultRegister]; StackVarInfo& leftVar = pBlock->m_register[R_A]; if (leftVar.cType == EScriptVal_Int) { SCRIPTVAR_SET_INT(resultVar, -leftVar.Int64); } if (leftVar.cType == EScriptVal_Double) { SCRIPTVAR_SET_FLOAT(resultVar, -leftVar.Double); } else{ return CScriptExecBlock::ERESULT_ERROR; } if (pNextPoint) { *pNextPoint = this->m_pNext; } return CScriptExecBlock::ERESULT_CONTINUE; } std::string CMinusExeCode::GetCodeString() { char strbuff[128] = { 0 }; sprintf(strbuff, "Minus\tRegisterIndex(extend):%d", (int)cResultRegister); return strbuff; } int CCmpEqualExeCode::Run(CScriptExecBlock* pBlock, CBaseExeCode **pNextPoint) { StackVarInfo& resultVar = pBlock->m_register[cResultRegister]; StackVarInfo& leftVar = pBlock->m_register[R_A]; switch (leftVar.cType) { case EScriptVal_Int: { __int64 nVal2 = 0; pBlock->GetVal(nVal2, cType, dwPos); SCRIPTVAR_SET_INT(resultVar, (__int64)(leftVar.Int64 == nVal2 ? 1 : 0)); } break; case EScriptVal_Double: { double dVal2 = 0; pBlock->GetVal(dVal2, cType, dwPos); SCRIPTVAR_SET_INT(resultVar, (__int64)(leftVar.Double == dVal2 ? 1 : 0)); } break; case EScriptVal_String: { std::string strVal1; SCRIPTVAR_GET_STRING(leftVar, strVal1); std::string strVal2; pBlock->GetVal(strVal2, cType, dwPos); SCRIPTVAR_SET_INT(resultVar, (__int64)(strVal1 == strVal2 ? 1 : 0)); } break; case EScriptVal_ClassPoint: { StackVarInfo rightVar; pBlock->GetVal(rightVar, cType, dwPos); if (leftVar.pPoint == nullptr && (rightVar.cType == EScriptVal_None || rightVar.cType == EScriptVal_Void)) { SCRIPTVAR_SET_INT(resultVar, (__int64)(1)); } else if (rightVar.cType == EScriptVal_ClassPoint && leftVar.pPoint == rightVar.pPoint) { SCRIPTVAR_SET_INT(resultVar, (__int64)(1)); } else { SCRIPTVAR_SET_INT(resultVar, (__int64)(0)); } } break; default: return CScriptExecBlock::ERESULT_ERROR; } if (pNextPoint) { *pNextPoint = this->m_pNext; } return CScriptExecBlock::ERESULT_CONTINUE; } std::string CCmpEqualExeCode::GetCodeString() { char strbuff[128] = { 0 }; sprintf(strbuff, "CMP_EQUAL\tRegisterIndex:%d\tVarType:%d\tpos:%d", (int)cResultRegister, (int)cType, (int)dwPos); return strbuff; } int CCmpNotEqualExeCode::Run(CScriptExecBlock* pBlock, CBaseExeCode **pNextPoint) { StackVarInfo& resultVar = pBlock->m_register[cResultRegister]; StackVarInfo& leftVar = pBlock->m_register[R_A]; switch (leftVar.cType) { case EScriptVal_Int: { __int64 nVal2 = 0; pBlock->GetVal(nVal2, cType, dwPos); SCRIPTVAR_SET_INT(resultVar, (__int64)(leftVar.Int64 != nVal2 ? 1 : 0)); } break; case EScriptVal_Double: { double dVal2 = 0; pBlock->GetVal(dVal2, cType, dwPos); SCRIPTVAR_SET_INT(resultVar, (__int64)(leftVar.Double != dVal2 ? 1 : 0)); } break; case EScriptVal_String: { std::string strVal1; SCRIPTVAR_GET_STRING(leftVar, strVal1); std::string strVal2; pBlock->GetVal(strVal2, cType, dwPos); SCRIPTVAR_SET_INT(resultVar, (__int64)(strVal1 != strVal2 ? 1 : 0)); } break; case EScriptVal_ClassPoint: { StackVarInfo rightVar; pBlock->GetVal(rightVar, cType, dwPos); if (leftVar.pPoint == nullptr && (rightVar.cType == EScriptVal_None || rightVar.cType == EScriptVal_Void)) { SCRIPTVAR_SET_INT(resultVar, (__int64)(0)); } else if (rightVar.cType == EScriptVal_ClassPoint && leftVar.pPoint == rightVar.pPoint) { SCRIPTVAR_SET_INT(resultVar, (__int64)(0)); } else { SCRIPTVAR_SET_INT(resultVar, (__int64)(1)); } } break; default: return CScriptExecBlock::ERESULT_ERROR; } if (pNextPoint) { *pNextPoint = this->m_pNext; } return CScriptExecBlock::ERESULT_CONTINUE; } std::string CCmpNotEqualExeCode::GetCodeString() { char strbuff[128] = { 0 }; sprintf(strbuff, "CMP_NOT_EQUAL\tRegisterIndex:%d\tVarType:%d\tpos:%d", (int)cResultRegister, (int)cType, (int)dwPos); return strbuff; } int CCmpBigExeCode::Run(CScriptExecBlock* pBlock, CBaseExeCode **pNextPoint) { StackVarInfo& resultVar = pBlock->m_register[cResultRegister]; StackVarInfo& leftVar = pBlock->m_register[R_A]; if (leftVar.cType==EScriptVal_Int) { __int64 nVal2 = 0; pBlock->GetVal(nVal2, cType, dwPos); SCRIPTVAR_SET_INT(resultVar, (__int64)(leftVar.Int64 > nVal2 ? 1 : 0)); } else if (leftVar.cType == EScriptVal_Double) { double dVal2 = 0; pBlock->GetVal(dVal2, cType, dwPos); SCRIPTVAR_SET_INT(resultVar, (__int64)(leftVar.Double > dVal2 ? 1 : 0)); } else{ return CScriptExecBlock::ERESULT_ERROR; } if (pNextPoint) { *pNextPoint = this->m_pNext; } return CScriptExecBlock::ERESULT_CONTINUE; } std::string CCmpBigExeCode::GetCodeString() { char strbuff[128] = { 0 }; sprintf(strbuff, "CMP_BIG\tRegisterIndex:%d\tVarType:%d\tpos:%d", (int)cResultRegister, (int)cType, (int)dwPos); return strbuff; } int CCmpBigAndEqualExeCode::Run(CScriptExecBlock* pBlock, CBaseExeCode **pNextPoint) { StackVarInfo& resultVar = pBlock->m_register[cResultRegister]; StackVarInfo& leftVar = pBlock->m_register[R_A]; if (leftVar.cType == EScriptVal_Int) { __int64 nVal2 = 0; pBlock->GetVal(nVal2, cType, dwPos); SCRIPTVAR_SET_INT(resultVar, (__int64)(leftVar.Int64 >= nVal2 ? 1 : 0)); } else if (leftVar.cType == EScriptVal_Double) { double dVal2 = 0; pBlock->GetVal(dVal2, cType, dwPos); SCRIPTVAR_SET_INT(resultVar, (__int64)(leftVar.Double >= dVal2 ? 1 : 0)); } else { return CScriptExecBlock::ERESULT_ERROR; } if (pNextPoint) { *pNextPoint = this->m_pNext; } return CScriptExecBlock::ERESULT_CONTINUE; } std::string CCmpBigAndEqualExeCode::GetCodeString() { char strbuff[128] = { 0 }; sprintf(strbuff, "CMP_BIG_EQUAL\tRegisterIndex:%d\tVarType:%d\tpos:%d", (int)cResultRegister, (int)cType, (int)dwPos); return strbuff; } int CCmpLessExeCode::Run(CScriptExecBlock* pBlock, CBaseExeCode **pNextPoint) { StackVarInfo& resultVar = pBlock->m_register[cResultRegister]; StackVarInfo& leftVar = pBlock->m_register[R_A]; if (leftVar.cType == EScriptVal_Int) { __int64 nVal2 = 0; pBlock->GetVal(nVal2, cType, dwPos); SCRIPTVAR_SET_INT(resultVar, (__int64)(leftVar.Int64 < nVal2 ? 1 : 0)); } else if (leftVar.cType == EScriptVal_Double) { double dVal2 = 0; pBlock->GetVal(dVal2, cType, dwPos); SCRIPTVAR_SET_INT(resultVar, (__int64)(leftVar.Double < dVal2 ? 1 : 0)); } else { return CScriptExecBlock::ERESULT_ERROR; } if (pNextPoint) { *pNextPoint = this->m_pNext; } return CScriptExecBlock::ERESULT_CONTINUE; } std::string CCmpLessExeCode::GetCodeString() { char strbuff[128] = { 0 }; sprintf(strbuff, "CMP_LESS\tRegisterIndex:%d\tVarType:%d\tpos:%d", (int)cResultRegister, (int)cType, (int)dwPos); return strbuff; } int CCmpLessAndEqualExeCode::Run(CScriptExecBlock* pBlock, CBaseExeCode **pNextPoint) { StackVarInfo& resultVar = pBlock->m_register[cResultRegister]; StackVarInfo& leftVar = pBlock->m_register[R_A]; if (leftVar.cType == EScriptVal_Int) { __int64 nVal2 = 0; pBlock->GetVal(nVal2, cType, dwPos); SCRIPTVAR_SET_INT(resultVar, (__int64)(leftVar.Int64 <= nVal2 ? 1 : 0)); } else if (leftVar.cType == EScriptVal_Double) { double dVal2 = 0; pBlock->GetVal(dVal2, cType, dwPos); SCRIPTVAR_SET_INT(resultVar, (__int64)(leftVar.Double <= dVal2 ? 1 : 0)); } else { return CScriptExecBlock::ERESULT_ERROR; } if (pNextPoint) { *pNextPoint = this->m_pNext; } return CScriptExecBlock::ERESULT_CONTINUE; } std::string CCmpLessAndEqualExeCode::GetCodeString() { char strbuff[128] = { 0 }; sprintf(strbuff, "CMP_LESS_EQUAL\tRegisterIndex:%d\tVarType:%d\tpos:%d", (int)cResultRegister, (int)cType, (int)dwPos); return strbuff; } int CBitAndExeCode::Run(CScriptExecBlock* pBlock, CBaseExeCode **pNextPoint) { StackVarInfo& resultVar = pBlock->m_register[cResultRegister]; StackVarInfo& leftVar = pBlock->m_register[R_A]; if (leftVar.cType == EScriptVal_Int) { __int64 nVal2 = 0; pBlock->GetVal(nVal2, cType, dwPos); SCRIPTVAR_SET_INT(resultVar, leftVar.Int64 & nVal2); } else{ return CScriptExecBlock::ERESULT_ERROR; } if (pNextPoint) { *pNextPoint = this->m_pNext; } return CScriptExecBlock::ERESULT_CONTINUE; } std::string CBitAndExeCode::GetCodeString() { char strbuff[128] = { 0 }; sprintf(strbuff, "BIT_AND\tRegisterIndex:%d\tVarType:%d\tpos:%d", (int)cResultRegister, (int)cType, (int)dwPos); return strbuff; } int CBitOrExeCode::Run(CScriptExecBlock* pBlock, CBaseExeCode **pNextPoint) { StackVarInfo& resultVar = pBlock->m_register[cResultRegister]; StackVarInfo& leftVar = pBlock->m_register[R_A]; if (leftVar.cType == EScriptVal_Int) { __int64 nVal2 = 0; pBlock->GetVal(nVal2, cType, dwPos); SCRIPTVAR_SET_INT(resultVar, leftVar.Int64 | nVal2); } else { return CScriptExecBlock::ERESULT_ERROR; } if (pNextPoint) { *pNextPoint = this->m_pNext; } return CScriptExecBlock::ERESULT_CONTINUE; } std::string CBitOrExeCode::GetCodeString() { char strbuff[128] = { 0 }; sprintf(strbuff, "BIT_OR\tRegisterIndex:%d\tVarType:%d\tpos:%d", (int)cResultRegister, (int)cType, (int)dwPos); return strbuff; } int CBitXorExeCode::Run(CScriptExecBlock* pBlock, CBaseExeCode **pNextPoint) { StackVarInfo& resultVar = pBlock->m_register[cResultRegister]; StackVarInfo& leftVar = pBlock->m_register[R_A]; if (leftVar.cType == EScriptVal_Int) { __int64 nVal2 = 0; pBlock->GetVal(nVal2, cType, dwPos); SCRIPTVAR_SET_INT(resultVar, leftVar.Int64 ^ nVal2); } else { return CScriptExecBlock::ERESULT_ERROR; } if (pNextPoint) { *pNextPoint = this->m_pNext; } return CScriptExecBlock::ERESULT_CONTINUE; } std::string CBitXorExeCode::GetCodeString() { char strbuff[128] = { 0 }; sprintf(strbuff, "BIT_XOR\tRegisterIndex:%d\tVarType:%d\tpos:%d", (int)cResultRegister, (int)cType, (int)dwPos); return strbuff; } int CPushExeCode::Run(CScriptExecBlock* pBlock, CBaseExeCode **pNextPoint) { StackVarInfo& var = pBlock->m_register[R_D]; pBlock->GetVal(var, cType, dwPos); STACK_PUSH(pBlock->m_stackRegister, var); if (pNextPoint) { *pNextPoint = this->m_pNext; } return CScriptExecBlock::ERESULT_CONTINUE; } std::string CPushExeCode::GetCodeString() { char strbuff[128] = { 0 }; sprintf(strbuff, "PUSH\tVarType:%d\tpos:%d", (int)cType, (int)dwPos); return strbuff; } int CPopExeCode::Run(CScriptExecBlock* pBlock, CBaseExeCode **pNextPoint) { StackVarInfo& var = pBlock->m_register[R_D]; STACK_GET(pBlock->m_stackRegister, var); STACK_POP(pBlock->m_stackRegister); if (pBlock->SetVal(cType, dwPos, var) == false) { return CScriptExecBlock::ERESULT_ERROR; } if (pNextPoint) { *pNextPoint = this->m_pNext; } return CScriptExecBlock::ERESULT_CONTINUE; } std::string CPopExeCode::GetCodeString() { char strbuff[128] = { 0 }; sprintf(strbuff, "POP\tVarType:%d\tpos:%d", (int)cType, (int)dwPos); return strbuff; } int CLoadExeCode::Run(CScriptExecBlock* pBlock, CBaseExeCode **pNextPoint) { pBlock->GetVal(pBlock->m_register[cResultRegister],cType, dwPos); if (pNextPoint) { *pNextPoint = this->m_pNext; } return CScriptExecBlock::ERESULT_CONTINUE; } std::string CLoadExeCode::GetCodeString() { char strbuff[128] = { 0 }; sprintf(strbuff, "LOAD\tRegisterIndex:%d\tVarType:%d\tpos:%d", (int)cResultRegister, (int)cType, (int)dwPos); return strbuff; } int CMoveExeCode::Run(CScriptExecBlock* pBlock, CBaseExeCode **pNextPoint) { if (pBlock->SetVal(cType, dwPos, pBlock->m_register[cVarRegister]) == false) { return CScriptExecBlock::ERESULT_ERROR; } if (pNextPoint) { *pNextPoint = this->m_pNext; } return CScriptExecBlock::ERESULT_CONTINUE; } std::string CMoveExeCode::GetCodeString() { char strbuff[128] = { 0 }; sprintf(strbuff, "MOVE\tRegisterIndex:%d\tVarType:%d\tpos:%d", (int)cVarRegister, (int)cType, (int)dwPos); return strbuff; } int CGetClassParamExeCode::Run(CScriptExecBlock* pBlock, CBaseExeCode **pNextPoint) { int nResult = CScriptExecBlock::ERESULT_CONTINUE; StackVarInfo& pointVar = pBlock->m_register[cClassRegIndex]; StackVarInfo& var = pBlock->m_register[cResultRegister]; if (pointVar.cType == EScriptVal_ClassPoint) { //PointVarInfo pointVal = GetPointIndex_StackVar(&m_register[code.cSign]); CScriptBasePointer* pPoint = pointVar.pPoint; if (pPoint) { pPoint->Lock(); auto pAttribute = pPoint->GetAttribute(dwPos); if (pAttribute) { var = pAttribute->ToScriptVal(); } else { //TODO 报错 nResult = CScriptExecBlock::ERESULT_ERROR; } pPoint->Unlock(); } } else { //TODO 报错 nResult = CScriptExecBlock::ERESULT_ERROR; } if (pNextPoint) { *pNextPoint = this->m_pNext; } return nResult; } std::string CGetClassParamExeCode::GetCodeString() { char strbuff[128] = { 0 }; sprintf(strbuff, "GetClassParam\tRegisterIndex:%d\tClassReg:%d\tpos:%d", (int)cResultRegister, (int)cClassRegIndex, (int)dwPos); return strbuff; } int CSetClassParamExeCode::Run(CScriptExecBlock* pBlock, CBaseExeCode **pNextPoint) { int nResult = CScriptExecBlock::ERESULT_CONTINUE; StackVarInfo& pointVar = pBlock->m_register[cClassRegIndex]; StackVarInfo& var = pBlock->m_register[cVarRegister]; if (pointVar.cType == EScriptVal_ClassPoint) { //PointVarInfo pointVal = GetPointIndex_StackVar(&m_register[code.cSign]); CScriptBasePointer* pPoint = pointVar.pPoint; if (pPoint) { pPoint->Lock(); auto pAttribute = pPoint->GetAttribute(dwPos); if (pAttribute) { pAttribute->SetVal(var); } else { //TODO 报错 nResult = CScriptExecBlock::ERESULT_ERROR; } pPoint->Unlock(); } } else { //TODO 报错 nResult = CScriptExecBlock::ERESULT_ERROR; } if (pNextPoint) { *pNextPoint = this->m_pNext; } return nResult; } std::string CSetClassParamExeCode::GetCodeString() { char strbuff[128] = { 0 }; sprintf(strbuff, "SetClassParam\tVarRegister:%d\tClassReg:%d\tpos:%d", (int)cVarRegister, (int)cClassRegIndex, (int)dwPos); return strbuff; } int CCallBackExeCode::Run(CScriptExecBlock* pBlock, CBaseExeCode **pNextPoint) { int nResult = CScriptExecBlock::ERESULT_CONTINUE; if (pBlock->m_stackRegister.nIndex >= cParmSize) { CACHE_NEW(CScriptCallState, pCallState, pBlock->m_pMaster); if (pCallState) { //设置参数 unsigned nBegin = pBlock->m_stackRegister.nIndex - (unsigned int)cParmSize; STACK_MOVE_ALL_BACK(pCallState->m_stackRegister, pBlock->m_stackRegister, nBegin); //for (unsigned int i = pBlock->m_stackRegister.nIndex - cParmSize; i < pBlock->m_stackRegister.nIndex; i++) //{ // StackVarInfo var; // STACK_GET_INDEX(pBlock->m_stackRegister, var,i); // STACK_PUSH(pCallState->m_stackRegister, var); //} //for (unsigned char i = 0; i < cParmSize; i++) //{ // STACK_POP(pBlock->m_stackRegister); //} //运行回调函数 switch (pBlock->m_pMaster->CallFun_CallBack(pBlock->m_pMaster->m_pMachine, unFunIndex, pCallState)) { case ECALLBACK_ERROR: nResult = CScriptExecBlock::ERESULT_ERROR; break; case ECALLBACK_WAITING: pBlock->m_cReturnRegisterIndex = cResultRegister; nResult = CScriptExecBlock::ERESULT_WAITING; break; case ECALLBACK_CALLSCRIPTFUN: nResult = CScriptExecBlock::ERESULT_CALLSCRIPTFUN; break; case ECALLBACK_NEXTCONTINUE: nResult = CScriptExecBlock::ERESULT_NEXTCONTINUE; break; case ECALLBACK_FINISH: pBlock->m_register[cResultRegister] = pCallState->GetResult(); break; } //执行完将结果放入寄存器 //pBlock->m_register[cResultRegister] = pCallState->GetResult(); } CACHE_DELETE(pCallState); } else { //TODO 报错 nResult = CScriptExecBlock::ERESULT_ERROR; } if (pNextPoint) { *pNextPoint = this->m_pNext; } return nResult; } std::string CCallBackExeCode::GetCodeString() { char strbuff[128] = { 0 }; sprintf(strbuff, "CallBack\tResultRegister:%d\tFunIndex:%d\tParmSize:%d", (int)cResultRegister, (int)unFunIndex, (int)cParmSize); return strbuff; } int CCallScriptExeCode::Run(CScriptExecBlock* pBlock, CBaseExeCode **pNextPoint) { int nResult = CScriptExecBlock::ERESULT_CONTINUE; if (pBlock->m_stackRegister.nIndex >= cParmSize) { //运行回调函数 switch (pBlock->m_pMaster->CallFun_Script(pBlock->m_pMaster->m_pMachine, unFunIndex, pBlock->m_stackRegister, cParmSize, cResultRegister)) { case ECALLBACK_ERROR: nResult = CScriptExecBlock::ERESULT_ERROR; break; case ECALLBACK_WAITING: nResult = CScriptExecBlock::ERESULT_WAITING; break; case ECALLBACK_CALLSCRIPTFUN: nResult = CScriptExecBlock::ERESULT_CALLSCRIPTFUN; break; case ECALLBACK_NEXTCONTINUE: nResult = CScriptExecBlock::ERESULT_NEXTCONTINUE; break; } for (unsigned char i = 0; i < cParmSize; i++) { STACK_POP(pBlock->m_stackRegister); } } else { nResult = CScriptExecBlock::ERESULT_ERROR; } if (pNextPoint) { *pNextPoint = this->m_pNext; } return nResult; } std::string CCallScriptExeCode::GetCodeString() { char strbuff[128] = { 0 }; sprintf(strbuff, "CallScript\tResultRegister:%d\tFunIndex:%d\tParmSize:%d", (int)cResultRegister, (int)unFunIndex, (int)cParmSize); return strbuff; } int CJumpExeCode::Run(CScriptExecBlock* pBlock, CBaseExeCode **pNextPoint) { if (pNextPoint) { if (this->pJumpCode) *pNextPoint = this->pJumpCode; else *pNextPoint = m_pNext; } return CScriptExecBlock::ERESULT_CONTINUE; } std::string CJumpExeCode::GetCodeString() { char strbuff[128] = { 0 }; sprintf(strbuff, "JUMP\tIndex:%d", (int)pJumpCode? pJumpCode->nCodeIndex:0); return strbuff; } int CJumpTrueExeCode::Run(CScriptExecBlock* pBlock, CBaseExeCode** pNextPoint) { if (pBlock->CheckRegisterTrue(cVarRegister)) { if (pNextPoint) { *pNextPoint = this->pJumpCode; } } else { if (pNextPoint) { *pNextPoint = this->m_pNext; } } return CScriptExecBlock::ERESULT_CONTINUE; } std::string CJumpTrueExeCode::GetCodeString() { char strbuff[128] = { 0 }; sprintf(strbuff, "JUMP_TRUE\tVarRegister:%d\tIndex:%d", (int)cVarRegister,(int)pJumpCode ? pJumpCode->nCodeIndex : 0); return strbuff; } int CJumpFalseExeCode::Run(CScriptExecBlock* pBlock, CBaseExeCode** pNextPoint) { if (!pBlock->CheckRegisterTrue(cVarRegister)) { if (pNextPoint) { *pNextPoint = this->pJumpCode; } } else { if (pNextPoint) { *pNextPoint = this->m_pNext; } } return CScriptExecBlock::ERESULT_CONTINUE; } std::string CJumpFalseExeCode::GetCodeString() { char strbuff[128] = { 0 }; sprintf(strbuff, "JUMP_FALSE\tVarRegister:%d\tIndex:%d", (int)cVarRegister, (int)pJumpCode ? pJumpCode->nCodeIndex : 0); return strbuff; } int CReturnExeCode::Run(CScriptExecBlock* pBlock, CBaseExeCode** pNextPoint) { if (pNextPoint) { *pNextPoint = nullptr; } pBlock->m_varReturnVar = pBlock->m_register[cVarRegister]; return CScriptExecBlock::ERESULT_CONTINUE; } std::string CReturnExeCode::GetCodeString() { char strbuff[128] = { 0 }; sprintf(strbuff, "RETURN\tVarRegister:%d", (int)cVarRegister); return strbuff; } int CCallClassFunExeCode::Run(CScriptExecBlock* pBlock, CBaseExeCode** pNextPoint) { int nResult = CScriptExecBlock::ERESULT_CONTINUE; PointVarInfo pointVal = GetPoint_StackVar(&pBlock->m_register[cClassRegIndex]); if (pBlock->m_stackRegister.nIndex >= cParmSize) { CACHE_NEW(CScriptCallState, pCallState, pBlock->m_pMaster); if (pCallState) { //设置参数 unsigned nBegin = pBlock->m_stackRegister.nIndex - (unsigned int)cParmSize; STACK_MOVE_ALL_BACK(pCallState->m_stackRegister, pBlock->m_stackRegister, nBegin); CScriptBasePointer* pPoint = pointVal.pPoint; if (pPoint) { switch (pPoint->RunFun(dwPos, pCallState)) { case ECALLBACK_ERROR: nResult = CScriptExecBlock::ERESULT_ERROR; break; case ECALLBACK_WAITING: pBlock->m_cReturnRegisterIndex = cResultRegister; nResult = CScriptExecBlock::ERESULT_WAITING; break; case ECALLBACK_CALLSCRIPTFUN: nResult = CScriptExecBlock::ERESULT_CALLSCRIPTFUN; break; case ECALLBACK_NEXTCONTINUE: nResult = CScriptExecBlock::ERESULT_NEXTCONTINUE; break; case ECALLBACK_FINISH: //执行完将结果放入寄存器 pBlock->m_register[cResultRegister] = pCallState->GetResult(); break; } if (pNextPoint) { *pNextPoint = m_pNext; } ////执行完将结果放入寄存器 //pBlock->m_register[cResultRegister] = pCallState->GetResult(); //pBlock->m_cReturnRegisterIndex = cResultRegister; } else { nResult = CScriptExecBlock::ERESULT_ERROR; } } CACHE_DELETE(pCallState); } else { nResult = CScriptExecBlock::ERESULT_ERROR; } return nResult; } std::string CCallClassFunExeCode::GetCodeString() { char strbuff[128] = { 0 }; sprintf(strbuff, "CALL_CLASS_FUN\tResultRegister:%d\tClassReg:%d\tFunIndex:%d\tParmSize:%d", (int)cResultRegister,(int)cClassRegIndex,(int)dwPos,(int)cParmSize); return strbuff; } int CNewClassExeCode::Run(CScriptExecBlock* pBlock, CBaseExeCode** pNextPoint) { CBaseScriptClassMgr* pMgr = CScriptSuperPointerMgr::GetInstance()->GetClassMgr(dwClassIndex); if (pMgr) { auto pNewPoint = pMgr->New(SCRIPT_NO_USED_AUTO_RELEASE); pBlock->m_register[cResultRegister] = pNewPoint; } else { pBlock->m_register[cResultRegister] = (CScriptPointInterface*)nullptr; } if (pNextPoint) { *pNextPoint = m_pNext; } return CScriptExecBlock::ERESULT_CONTINUE; } std::string CNewClassExeCode::GetCodeString() { char strbuff[128] = { 0 }; sprintf(strbuff, "NEW_CLASS\tResultRegister:%d\tClassIndex:%d", (int)cResultRegister, (int)dwClassIndex); return strbuff; } int CReleaseClassExeCode::Run(CScriptExecBlock* pBlock, CBaseExeCode** pNextPoint) { PointVarInfo pointVal = GetPoint_StackVar(&pBlock->m_register[cVarRegister]); CScriptBasePointer* pPoint = pointVal.pPoint; if (pPoint) { CBaseScriptClassMgr* pMgr = CScriptSuperPointerMgr::GetInstance()->GetClassMgr(pPoint->GetType()); if (pMgr) { pMgr->Release(pPoint); } } if (pNextPoint) { *pNextPoint = m_pNext; } return CScriptExecBlock::ERESULT_CONTINUE; } std::string CReleaseClassExeCode::GetCodeString() { char strbuff[128] = { 0 }; sprintf(strbuff, "RELEASE_CLASS\tVarRegister:%d", (int)cVarRegister); return strbuff; } int CBreakExeCode::Run(CScriptExecBlock* pBlock, CBaseExeCode** pNextPoint) { if (pNextPoint) { if (this->pJumpCode) *pNextPoint = this->pJumpCode; else *pNextPoint = m_pNext; } return CScriptExecBlock::ERESULT_CONTINUE; } std::string CBreakExeCode::GetCodeString() { char strbuff[128] = { 0 }; sprintf(strbuff, "BREAK\tIndex:%d", (int)pJumpCode ? pJumpCode->nCodeIndex : 0); return strbuff; } int CContinueExeCode::Run(CScriptExecBlock* pBlock, CBaseExeCode** pNextPoint) { if (pNextPoint) { if (this->pJumpCode) *pNextPoint = this->pJumpCode; else *pNextPoint = m_pNext; } return CScriptExecBlock::ERESULT_CONTINUE; } std::string CContinueExeCode::GetCodeString() { char strbuff[128] = { 0 }; sprintf(strbuff, "CONTINUE\tIndex:%d", (int)pJumpCode ? pJumpCode->nCodeIndex : 0); return strbuff; } int CSignExeCode::Run(CScriptExecBlock* pBlock, CBaseExeCode** pNextPoint) { if (pNextPoint) { *pNextPoint = m_pNext; } return CScriptExecBlock::ERESULT_CONTINUE; } std::string CSignExeCode::GetCodeString() { char strbuff[128] = { 0 }; sprintf(strbuff, "SIGN"); return strbuff; } CExeCodeMgr CExeCodeMgr::s_Instance; CExeCodeMgr::CExeCodeMgr() { } CExeCodeMgr::~CExeCodeMgr() { } void CExeCodeMgr::Clear() { for (auto it = m_listExeCode.begin(); it != m_listExeCode.end(); it++) { CBaseExeCode* pCode = *it; if (pCode) { delete pCode; } } m_listExeCode.clear(); } }Programming Principles and Practice Using C Plus Plus Bjarne Stroustrup/Chapter 8/Drill/Two/swap.cpp #include "swap.h" void swap_v(int a, int b){ int temp; temp = a; a=b; b = temp; } void swap_r(int& a, int& b) { int temp; temp = a; a=b; b = temp; } // NOTE: swap_cr(const int& a, const int& b) will not compile because a and b are read only references. // void swap_cr(const int& a, const int& b) // { // int temp; // temp = a; // a=b; // b = temp; // } otb/cplusplus/fileloader.cpp /** * The Forgotten Server - a free and open-source MMORPG server emulator * Copyright (C) 2019 <> * * 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 "otpch.h" #include #include "fileloader.h" namespace OTB { constexpr Identifier wildcard = {{'\0', '\0', '\0', '\0'}}; Loader::Loader(const std::string& fileName, const Identifier& acceptedIdentifier): fileContents(fileName) { constexpr auto minimalSize = sizeof(Identifier) + sizeof(Node::START) + sizeof(Node::type) + sizeof(Node::END); if (fileContents.size() <= minimalSize) { throw InvalidOTBFormat{}; } Identifier fileIdentifier; std::copy(fileContents.begin(), fileContents.begin() + fileIdentifier.size(), fileIdentifier.begin()); if (fileIdentifier != acceptedIdentifier && fileIdentifier != wildcard) { throw InvalidOTBFormat{}; } } using NodeStack = std::stack>; static Node& getCurrentNode(const NodeStack& nodeStack) { if (nodeStack.empty()) { throw InvalidOTBFormat{}; } return *nodeStack.top(); } const Node& Loader::parseTree() { auto it = fileContents.begin() + sizeof(Identifier); if (static_cast(*it) != Node::START) { throw InvalidOTBFormat{}; } root.type = *(++it); root.propsBegin = ++it; NodeStack parseStack; parseStack.push(&root); for (; it != fileContents.end(); ++it) { switch(static_cast(*it)) { case Node::START: { auto& currentNode = getCurrentNode(parseStack); if (currentNode.children.empty()) { currentNode.propsEnd = it; } currentNode.children.emplace_back(); auto& child = currentNode.children.back(); if (++it == fileContents.end()) { throw InvalidOTBFormat{}; } child.type = *it; child.propsBegin = it + sizeof(Node::type); parseStack.push(&child); break; } case Node::END: { auto& currentNode = getCurrentNode(parseStack); if (currentNode.children.empty()) { currentNode.propsEnd = it; } parseStack.pop(); break; } case Node::ESCAPE: { if (++it == fileContents.end()) { throw InvalidOTBFormat{}; } break; } default: { break; } } } if (!parseStack.empty()) { throw InvalidOTBFormat{}; } return root; } bool Loader::getProps(const Node& node, PropStream& props) { auto size = std::distance(node.propsBegin, node.propsEnd); if (size == 0) { return false; } propBuffer.resize(size); bool lastEscaped = false; auto escapedPropEnd = std::copy_if(node.propsBegin, node.propsEnd, propBuffer.begin(), [&lastEscaped](const char& byte) { lastEscaped = byte == static_cast(Node::ESCAPE) && !lastEscaped; return !lastEscaped; }); props.init(&propBuffer[0], std::distance(propBuffer.begin(), escapedPropEnd)); return true; } } //namespace OTB #include "integer.hpp" class Integer : public node::ObjectWrap { public: static void Init(v8::Local exports, v8::Local module) { v8::Isolate* isolate = v8::Isolate::GetCurrent(); v8::HandleScope scope(isolate); v8::Local t = v8::FunctionTemplate::New(isolate, New); t->InstanceTemplate()->SetInternalFieldCount(1); t->PrototypeTemplate()->SetInternalFieldCount(1); t->SetClassName(StringFromLatin1(isolate, "Integer")); NODE_SET_PROTOTYPE_GETTER(t, "low", Low); NODE_SET_PROTOTYPE_GETTER(t, "high", High); NODE_SET_PROTOTYPE_METHOD(t, "add", Add); NODE_SET_PROTOTYPE_METHOD(t, "subtract", Subtract); NODE_SET_PROTOTYPE_METHOD(t, "multiply", Multiply); NODE_SET_PROTOTYPE_METHOD(t, "divide", Divide); NODE_SET_PROTOTYPE_METHOD(t, "modulo", Modulo); NODE_SET_PROTOTYPE_METHOD(t, "negate", Negate); NODE_SET_PROTOTYPE_METHOD(t, "abs", Abs); NODE_SET_PROTOTYPE_METHOD(t, "and", And); NODE_SET_PROTOTYPE_METHOD(t, "or", Or); NODE_SET_PROTOTYPE_METHOD(t, "xor", Xor); NODE_SET_PROTOTYPE_METHOD(t, "not", Not); NODE_SET_PROTOTYPE_METHOD(t, "shiftLeft", ShiftLeft); NODE_SET_PROTOTYPE_METHOD(t, "shiftRight", ShiftRight); NODE_SET_PROTOTYPE_METHOD(t, "equals", Equals); NODE_SET_PROTOTYPE_METHOD(t, "notEquals", NotEquals); NODE_SET_PROTOTYPE_METHOD(t, "greaterThan", GreaterThan); NODE_SET_PROTOTYPE_METHOD(t, "greaterThanOrEquals", GreaterThanOrEquals); NODE_SET_PROTOTYPE_METHOD(t, "lessThan", LessThan); NODE_SET_PROTOTYPE_METHOD(t, "lessThanOrEquals", LessThanOrEquals); NODE_SET_PROTOTYPE_METHOD(t, "compare", Compare); NODE_SET_PROTOTYPE_METHOD(t, "bitSizeAbs", BitSizeAbs); NODE_SET_PROTOTYPE_METHOD(t, "isEven", IsEven); NODE_SET_PROTOTYPE_METHOD(t, "isOdd", IsOdd); NODE_SET_PROTOTYPE_METHOD(t, "isPositive", IsPositive); NODE_SET_PROTOTYPE_METHOD(t, "isNegative", IsNegative); NODE_SET_PROTOTYPE_METHOD(t, "isZero", IsZero); NODE_SET_PROTOTYPE_METHOD(t, "isNonZero", IsNonZero); NODE_SET_PROTOTYPE_METHOD(t, "isSafe", IsSafe); NODE_SET_PROTOTYPE_METHOD(t, "isUnsafe", IsUnsafe); NODE_SET_PROTOTYPE_METHOD(t, "toNumberUnsafe", ToNumberUnsafe); NODE_SET_PROTOTYPE_METHOD(t, "toString", ToString); NODE_SET_PROTOTYPE_METHOD(t, "valueOf", ValueOf); v8::Local c = t->GetFunction(isolate->GetCurrentContext()).ToLocalChecked(); v8::Local::Cast(c->Get(isolate->GetCurrentContext(), StringFromLatin1(isolate, "prototype")).ToLocalChecked())->SetAlignedPointerInInternalField(0, &controller); exports->Set(isolate->GetCurrentContext(), StringFromLatin1(isolate, "Integer"), c).FromJust(); NODE_SET_METHOD(v8::Local::Cast(c), "fromString", FromString); NODE_SET_METHOD(v8::Local::Cast(c), "fromNumber", FromNumber); NODE_SET_METHOD(v8::Local::Cast(c), "fromBits", FromBits); NODE_SET_METHOD(v8::Local::Cast(c), "isInstance", IsInstance); constructor.Reset(isolate, c); constructorTemplate.Reset(isolate, t); controller.privileges = false; controller.value = 0; } private: explicit Integer(int64_t _value) : node::ObjectWrap(), value(_value) {} NODE_METHOD(New) { if (info.IsConstructCall()) { if (!controller.privileges) { return ThrowTypeError(info, "Disabled constructor (use fromString, fromNumber, or fromBits)"); } controller.privileges = false; (new Integer(controller.value))->Wrap(info.This()); return info.GetReturnValue().Set(info.This()); } if (info.Length() == 0) return ReturnNew(info, 0); Result cast = Cast(info, info[0]); // TODO: ideally if info[0] is an Integer, that same object is returned. cast.error ? ThrowException(info, *cast.error) : ReturnNew(info, cast.Checked()); } NODE_METHOD(FromBits) { int32_t low; int32_t high = 0; REQUIRE_ARGUMENT_INT32(first, low); if (info.Length() > 1) { REQUIRE_ARGUMENT_INT32(second, high); } ReturnNew(info, (int64_t)((((uint64_t)((uint32_t)high)) << 32) | (uint32_t)low)); } NODE_METHOD(FromNumber) { REQUIRE_ARGUMENT_NUMBER(first, v8::Local number); Result cast = Cast(number); if (!cast.error) return ReturnNew(info, cast.Checked()); if (info.Length() == 1) return ThrowException(info, *cast.error); v8::Local defValue = info[1]; if (HasInstance(info, defValue)) return info.GetReturnValue().Set(defValue); if (!defValue->IsNumber()) return ThrowTypeError(info, "Expected the default value to be a number or Integer"); Result def = Cast(v8::Local::Cast(defValue)); if (!def.error) return ReturnNew(info, def.Checked()); ThrowTypeError(info, "The default value could not be converted to an Integer"); } NODE_METHOD(FromString) { REQUIRE_ARGUMENT_STRING(first, v8::Local string); uint32_t radix = 10; if (info.Length() > 1) { REQUIRE_ARGUMENT_UINT32(second, radix); if (radix < 2 || radix > 36) return ThrowRangeError(info, "Radix argument must be within 2 - 36"); } Result cast = Cast(string, (uint8_t)radix); if (!cast.error) return ReturnNew(info, cast.Checked()); if (info.Length() < 3) return ThrowException(info, *cast.error); v8::Local defValue = info[2]; if (HasInstance(info, defValue)) return info.GetReturnValue().Set(defValue); if (!defValue->IsString()) return ThrowTypeError(info, "Expected the default value to be a string or Integer"); Result def = Cast(v8::Local::Cast(defValue), (uint8_t)radix); if (!def.error) return ReturnNew(info, def.Checked()); ThrowTypeError(info, "The default value could not be converted to an Integer"); } NODE_METHOD(IsInstance) { Return(info, info.Length() != 0 && HasInstance(info, info[0])); } NODE_GETTER(Low) { UseValue; Return(info, (int32_t)((uint32_t)(((uint64_t)value) & U32_in_U64))); } NODE_GETTER(High) { UseValue; Return(info, (int32_t)((uint32_t)(((uint64_t)value) >> 32))); } NODE_METHOD(Add) { UseValue; UseArgument; if ((arg > 0 && value > MAX_VALUE - arg) || (arg < 0 && value < MIN_VALUE - arg)) return ThrowRangeError(info, "Integer overflow"); ReturnNew(info, value + arg); } NODE_METHOD(Subtract) { UseValue; UseArgument; if ((arg < 0 && value > MAX_VALUE + arg) || (arg > 0 && value < MIN_VALUE + arg)) return ThrowRangeError(info, "Integer overflow"); ReturnNew(info, value - arg); } NODE_METHOD(Multiply) { UseValue; UseArgument; if (value > 0 ? (arg > 0 ? value > MAX_VALUE / arg : arg < MIN_VALUE / value) : (arg > 0 ? value < MIN_VALUE / arg : (value != 0 && arg < MAX_VALUE / value))) return ThrowRangeError(info, "Integer overflow"); ReturnNew(info, value * arg); } NODE_METHOD(Divide) { UseValue; UseArgument; if (arg == 0) return ThrowRangeError(info, "Divide by zero"); if (arg == -1 && value == MIN_VALUE) return ThrowRangeError(info, "Integer overflow"); ReturnNew(info, value / arg); } NODE_METHOD(Modulo) { UseValue; UseArgument; if (arg == 0) return ThrowRangeError(info, "Divide by zero"); ReturnNew(info, arg == -1 ? 0 : value % arg); } NODE_METHOD(Negate) { UseValue; if (value == MIN_VALUE) return ThrowRangeError(info, "Integer overflow"); ReturnNew(info, -value); } NODE_METHOD(Abs) { UseValue; if (value == MIN_VALUE) return ThrowRangeError(info, "Integer overflow"); ReturnNew(info, value >= 0 ? value : -value); } NODE_METHOD(And) { UseValue; UseArgument; ReturnNew(info, value & arg); } NODE_METHOD(Or) { UseValue; UseArgument; ReturnNew(info, value | arg); } NODE_METHOD(Xor) { UseValue; UseArgument; ReturnNew(info, value ^ arg); } NODE_METHOD(Not) { UseValue; ReturnNew(info, ~value); } NODE_METHOD(ShiftLeft) { UseValue; REQUIRE_ARGUMENT_UINT32(first, uint32_t shift); ReturnNew(info, (int64_t)((uint64_t)value << (shift & 63))); } NODE_METHOD(ShiftRight) { UseValue; REQUIRE_ARGUMENT_UINT32(first, uint32_t shift); ReturnNew(info, value >> (shift & 63)); } NODE_METHOD(Equals) { UseValue; UseArgument; Return(info, value == arg); } NODE_METHOD(NotEquals) { UseValue; UseArgument; Return(info, value != arg); } NODE_METHOD(GreaterThan) { UseValue; UseArgument; Return(info, value > arg); } NODE_METHOD(GreaterThanOrEquals) { UseValue; UseArgument; Return(info, value >= arg); } NODE_METHOD(LessThan) { UseValue; UseArgument; Return(info, value < arg); } NODE_METHOD(LessThanOrEquals) { UseValue; UseArgument; Return(info, value <= arg); } NODE_METHOD(Compare) { UseValue; UseArgument; Return(info, value < arg ? -1 : value > arg ? 1 : 0); } NODE_METHOD(BitSizeAbs) { UseValue; if (value < 0) { if (value == MIN_VALUE) return Return(info, (uint32_t)64); value = -value; } uint64_t uvalue = (uint64_t)value; uint32_t bits = 1; while (uvalue >>= 1) { ++bits; } Return(info, bits); } NODE_METHOD(IsEven) { UseValue; Return(info, (value & 1) == 0); } NODE_METHOD(IsOdd) { UseValue; Return(info, (value & 1) != 0); } NODE_METHOD(IsPositive) { UseValue; Return(info, value >= 0); } NODE_METHOD(IsNegative) { UseValue; Return(info, value < 0); } NODE_METHOD(IsZero) { UseValue; Return(info, value == 0); } NODE_METHOD(IsNonZero) { UseValue; Return(info, value != 0); } NODE_METHOD(IsSafe) { UseValue; Return(info, value <= MAX_SAFE && value >= MIN_SAFE); } NODE_METHOD(IsUnsafe) { UseValue; Return(info, value > MAX_SAFE || value < MIN_SAFE); } NODE_METHOD(ToNumberUnsafe) { UseValue; Return(info, (double)value); } NODE_METHOD(ToString) { UseValue; uint32_t radix = 10; if (info.Length()) { REQUIRE_ARGUMENT_UINT32(first, radix); if (radix < 2 || radix > 36) return ThrowRangeError(info, "Radix argument must be within 2 - 36"); } char buffer[STRING_BUFFER_LENGTH]; info.GetReturnValue().Set(StringFromLatin1(info.GetIsolate(), WriteString(buffer, value, (uint8_t)radix))); } NODE_METHOD(ValueOf) { UseValue; if (value <= MAX_SAFE && value >= MIN_SAFE) return Return(info, (double)value); char buffer[STRING_BUFFER_LENGTH]; std::string message = "Cannot losslessly convert "; message += WriteString(buffer, value, 10); message += " to a number"; ThrowRangeError(info, message.c_str()); } static inline bool HasInstance(NODE_ARGUMENTS info, v8::Local value) { return v8::Local::New(info.GetIsolate(), constructorTemplate)->HasInstance(value); } static inline void Return(NODE_GETTER_ARGUMENTS info, int32_t value) { info.GetReturnValue().Set(value); } static inline void Return(NODE_ARGUMENTS info, int32_t value) { info.GetReturnValue().Set(value); } static inline void Return(NODE_ARGUMENTS info, uint32_t value) { info.GetReturnValue().Set(value); } static inline void Return(NODE_ARGUMENTS info, double value) { info.GetReturnValue().Set(value); } static inline void Return(NODE_ARGUMENTS info, bool value) { info.GetReturnValue().Set(value); } static inline void ReturnNew(NODE_ARGUMENTS info, int64_t value) { v8::Isolate* isolate = info.GetIsolate(); controller.privileges = true; controller.value = value; info.GetReturnValue().Set(v8::Local::New(isolate, constructor)->NewInstance(isolate->GetCurrentContext()).ToLocalChecked()); } static Result Cast(NODE_ARGUMENTS info, v8::Local value) { if (value->IsNumber()) return Cast(v8::Local::Cast(value)); if (value->IsString()) return Cast(v8::Local::Cast(value), 10); if (HasInstance(info, value)) return Result(node::ObjectWrap::Unwrap(v8::Local::Cast(value))->value); return Result("Expected a number, string, or Integer"); } static Result Cast(v8::Local number) { double value = number->Value(); if (!std::isfinite(value) || std::floor(value) != value) return Result("The given number is not an integer"); if (value > MAX_SAFE_DOUBLE || value < MIN_SAFE_DOUBLE) return Result("The precision of the given number cannot be guaranteed", true); return Result((int64_t)value); } static Result Cast(v8::Local string, uint8_t radix) { auto IsWhitespace = [](uint16_t c) { return c == ' ' || (c <= '\r' && c >= '\t'); }; v8::String::Value utf16(string); const uint16_t* str = *utf16; int len = utf16.length(); int i = 0; // Skip leading whitespace. while (i 10 ? '9' : (radix - 1 + '0'); uint8_t max_alpha = radix > 10 ? (radix - 11 + 'a') : 0; uint8_t min_alpha = radix > 10 ? 'a' : 255; bool is_negative = (i + 1 < len) && (str[i] == '-') && !IsWhitespace(str[i + 1]); for (i+=is_negative; i max_digit) { if (c <= 'Z') c += 32; if (c < min_alpha || c > max_alpha) { if (c == 78 && ((i + 1 < len && !IsWhitespace(str[i + 1])) || (i != 0 && !IsWhitespace(str[i - 1]) && str[i - 1] != '-'))) { // Skip zeros after a decimal point. do { ++i; } while (i (value = value * radix + (c - '0'))) return Result("The given string represents a number that is too large", true); } // Skip trailing whitespace. while (i I64_in_U64 + is_negative) return Result("The given string represents a number that is too large", true); return Result((is_negative && value) ? -((int64_t)(value - 1)) - 1 : (int64_t)value); } static char* WriteString(char* buffer, int64_t value, uint8_t radix) { bool is_negative = value < 0; uint64_t x = (uint64_t)(value ^ -is_negative) + is_negative; unsigned char* slot = reinterpret_cast(buffer + STRING_BUFFER_LENGTH - 1); *slot = '\0'; do { uint64_t digit = x % radix; *(--slot) = digit + '0' + (digit > 9) * 39; } while (x /= radix); *(slot - 1) = '-'; return reinterpret_cast(slot - is_negative); } struct ConstructorController { bool privileges; int64_t value; }; static const int64_t MAX_VALUE = 0x7fffffffffffffffLL; static const int64_t MIN_VALUE = -0x8000000000000000LL; static const int64_t MAX_SAFE = 9007199254740991LL; static const int64_t MIN_SAFE = -9007199254740991LL; static constexpr double MAX_SAFE_DOUBLE = (double)MAX_SAFE; static constexpr double MIN_SAFE_DOUBLE = (double)MIN_SAFE; static constexpr uint64_t I64_in_U64 = (uint64_t)MAX_VALUE; static constexpr uint64_t U32_in_U64 = (uint64_t)0xffffffffLU; static const size_t STRING_BUFFER_LENGTH = 72; static v8::Persistent constructor; static v8::Persistent constructorTemplate; static ConstructorController controller; const int64_t value; }; v8::Persistent Integer::constructor; v8::Persistent Integer::constructorTemplate; Integer::ConstructorController Integer::controller; NODE_MODULE(integer, Integer::Init); #include "checking.h" #include Checking::Checking(const std::string &name, float balance, float minbalance): m_MinimumBalance(minbalance), Account(name, balance) { } Checking::~Checking() { std::cout << "~Checking()" << std::endl; } void Checking::Withdraw(float amount) { if ((m_Balance - amount) > m_MinimumBalance) { // Scope is important, otherwise becomes recursive Account::Withdraw(amount); //public from base } else { std::cout << "Invalid amount" << std::endl; } } float Checking::GetMinimumBalance() const { return m_MinimumBalance; } MatmanBJ/etu_2022_6_kg_lab #include #include #include #include "./include/Point.h" Point::Point() : _x(0.0), _y(0.0), _z(0.0){} Point::Point(double X, double Y, double Z) : _x(X), _y(Y), _z(Z){} Point::Point(const Point& toCopied) : _x(toCopied.getX()), _y(toCopied.getY()), _z(toCopied.getZ()){} double Point::getX() const { return _x; } double Point::getY() const { return _y; } double Point::getZ() const { return _z; } void Point::setX(double new_x) { _x = new_x; } void Point::setY(double new_y) { _y = new_y; } void Point::setZ(double new_z) { _z = new_z; } double Point::x() const {return getX();} double Point::y() const {return getY();} double Point::z() const {return getZ();} void Point::add(const Point& other) { _x += other._x; _y += other._y; _z += other._z; } void Point::sub(const Point& other) { _x -= other._x; _y -= other._y; _z -= other._z; } void Point::mul(double x) { _x *= x; _y *= x; _z *= x; } std::string Point::print(std::string prefix) const { std::string res = prefix + "(" + std::to_string(_x) + ", " + std::to_string(_y) + ", " + std::to_string(_z) + ")"; return res; } double Point::vector_len() const { return sqrt(_x*_x + _y*_y + _z*_z); } Point& Point::operator=(const Point& other) { if (this == &other) return *this; this->_x = other._x; this->_y = other._y; this->_z = other._z; return *this; }Hyp-ed/hyped-2022 #pragma once #include #include #include #include #include namespace hyped { namespace navigation { class KalmanFilter { public: KalmanFilter(uint32_t n = 3, uint32_t m = 1, uint32_t k = 0); void setup(); void updateStateTransitionMatrix(data::nav_t dt); void updateMeasurementCovarianceMatrix(const data::nav_t var); data::nav_t filter(data::nav_t z); // transfer estimate to NavigationVector data::nav_t getEstimate(); // transfer estimate variances to NavigationVector const data::nav_t getEstimateVariance(); private: // state dimensionality uint32_t n_; // measurement dimensionality uint32_t m_; // control dimensionality default = 0 uint32_t k_; utils::math::KalmanMultivariate kalmanFilter_; // covariance matrix variances static constexpr float kInitialErrorVariance = 0.5; static constexpr float kStateTransitionVariance = 0.02; static constexpr float kTrackMeasurementVariance = 0.001; static constexpr float kElevatorMeasurementVariance = 0.12; static constexpr float kStationaryMeasurementVariance = 0.04; // create initial error covariance matrix P const Eigen::MatrixXf createInitialErrorCovarianceMatrix() const; // create state transition matrix A Eigen::MatrixXf createStateTransitionMatrix(data::nav_t dt) const; // create measurement matrix H Eigen::MatrixXf createMeasurementMatrix() const; // create state transition coveriance matrix Q const Eigen::MatrixXf createStateTransitionCovarianceMatrix() const; // create measurement covariance matrices R const Eigen::MatrixXf createTrackMeasurementCovarianceMatrix() const; const Eigen::MatrixXf createElevatorMeasurementCovarianceMatrix() const; const Eigen::MatrixXf createStationaryMeasurementCovarianceMatrix() const; }; } // namespace navigation } // namespace hypednaos/includes/kernel/ucontext.hpp #pragma once #include "arch/idt.hpp" #include "lock.hpp" #include "preempt.hpp" #include namespace uctx { struct UninterruptibleController { private: bool IF; public: void begin() { IF = arch::idt::save_and_disable(); } void end() { if (IF) arch::idt::enable(); else arch::idt::disable(); } }; template struct BaseUninterruptibleController { UninterruptibleController ctl; Controller ctl2; template BaseUninterruptibleController(T &&... args) : ctl2(std::forward(args)...) { } void begin() { ctl.begin(); ctl2.begin(); } void end() { ctl2.end(); ctl.end(); } }; struct RawSpinLockController { private: lock::spinlock_t &sl; public: RawSpinLockController(lock::spinlock_t &sl) : sl(sl) { } void begin() { sl.lock(); } void end() { sl.unlock(); } }; using RawSpinLockUninterruptibleController = BaseUninterruptibleController; struct RawReadLockController { private: lock::rw_lock_t &lock; public: RawReadLockController(lock::rw_lock_t &lock) : lock(lock) { } void begin() { lock.lock_read(); } void end() { lock.unlock_read(); } }; using RawReadLockUninterruptibleController = BaseUninterruptibleController; struct RawWriteLockController { private: lock::rw_lock_t &lock; public: RawWriteLockController(lock::rw_lock_t &lock) : lock(lock) { } void begin() { lock.lock_write(); } void end() { lock.unlock_write(); } }; using RawWriteLockUninterruptibleController = BaseUninterruptibleController; template struct Guard_t { Controller ctrl; template Guard_t(T &&... arg) : ctrl(std::forward(arg)...) { ctrl.begin(); } ~Guard_t() { ctrl.end(); } }; template struct LockGuard_t { Lock &ctrl; explicit LockGuard_t(Lock &l) : ctrl(l) { ctrl.lock(); } ~LockGuard_t() { ctrl.unlock(); } }; /// define guards using RawSpinLockContext = Guard_t; using SpinLockContext = Guard_t; using UninterruptibleContext = Guard_t; using SpinLockUninterruptibleContext = Guard_t; using RawSpinLockUninterruptibleContext = Guard_t; using RawReadLockContext = Guard_t; using RawWriteLockContext = Guard_t; using RawReadLockUninterruptibleContext = Guard_t; using RawWriteLockUninterruptibleContext = Guard_t; } // namespace uctx #pragma once #include "DistrhoPluginInfo.h" __attribute__((unused)) static constexpr int NOISE_MAX_BURSTS = 8; __attribute__((unused)) static constexpr int NOISE_MAX_DURATION = 1000; __attribute__((unused)) static constexpr int NOISE_MAX_PITCH = 32000.0f; __attribute__((unused)) static constexpr int SYNTH_NOTES = 12; __attribute__((unused)) static constexpr int SYNTH_CHANNELS = 8; #define OVERSAMPLING 8 __attribute__((unused)) static constexpr unsigned MAX_NAME_LEN = 32; __attribute__((unused)) static const char *const NoteNames[12] = { "C (Kick)", "C# (Crash)", "D (Snare)", "D# (Ride)", "E (Clap)", "F (Cowbell)", "F# (Closed hat)", "G (Low tom)", "G# (Medium hat)", "A (Mid tom)", "A# (Open hat)", "B (Hi tom)" }; inline int ParameterNoteNumber(int p) { int first = pIdNoteLevelFirstGroup; int end = first + (pIdDrumVolume2 - pIdDrumVolume1) * SYNTH_NOTES; if (p < first || p >= end) return -1; return (p - first) / (pIdDrumVolume2 - pIdDrumVolume1); } inline int ParameterFirstOfNoteGroup(int p) { int n = ParameterNoteNumber(p); return (n == -1) ? p : (p - n * (pIdDrumVolume2 - pIdDrumVolume1)); } inline int ParameterBurstNumber(int p) { p = ParameterFirstOfNoteGroup(p); if (p == -1 || p < pIdBurstLevelFirstGroup) return -1; int n = (p - pIdBurst1Duration1) / (pIdBurst2Duration1 - pIdBurst1Duration1); return (n < NOISE_MAX_BURSTS) ? n : -1; } inline int ParameterFirstOfBurstGroup(int p) { int n = ParameterBurstNumber(p); return (n == -1) ? p : (p - n * (pIdBurst2Duration1 - pIdBurst1Duration1)); } inline int ParameterFirstOfGroup(int p) { p = ParameterFirstOfNoteGroup(p); p = ParameterFirstOfBurstGroup(p); return p; } /* Copyright 2019 Ultralight, Inc. Copyright 2012 Google Inc. Portions below are under the following license: 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 "FontLoaderWin.h" #include #include #include #include #include #include #include #include #include #include #include #include static const wchar_t kFontLinkKey[] = L"Software\\Microsoft\\Windows NT\\CurrentVersion\\FontLink\\SystemLink"; struct MatchImprovingProcData { MatchImprovingProcData(LONG desiredWeight, bool desiredItalic) : m_desiredWeight(desiredWeight) , m_desiredItalic(desiredItalic) , m_hasMatched(false) { } LONG m_desiredWeight; bool m_desiredItalic; bool m_hasMatched; LOGFONT m_chosen; }; static int CALLBACK matchImprovingEnumProc(CONST LOGFONT* candidate, CONST TEXTMETRIC* metrics, DWORD fontType, LPARAM lParam) { MatchImprovingProcData* matchData = reinterpret_cast(lParam); if (!matchData->m_hasMatched) { matchData->m_hasMatched = true; matchData->m_chosen = *candidate; return 1; } if (!candidate->lfItalic != !matchData->m_chosen.lfItalic) { if (!candidate->lfItalic == !matchData->m_desiredItalic) matchData->m_chosen = *candidate; return 1; } unsigned chosenWeightDeltaMagnitude = abs(matchData->m_chosen.lfWeight - matchData->m_desiredWeight); unsigned candidateWeightDeltaMagnitude = abs(candidate->lfWeight - matchData->m_desiredWeight); // If both are the same distance from the desired weight, prefer the candidate if it is further from regular. if (chosenWeightDeltaMagnitude == candidateWeightDeltaMagnitude && abs(candidate->lfWeight - FW_NORMAL) > abs(matchData->m_chosen.lfWeight - FW_NORMAL)) { matchData->m_chosen = *candidate; return 1; } // Otherwise, prefer the one closer to the desired weight. if (candidateWeightDeltaMagnitude < chosenWeightDeltaMagnitude) matchData->m_chosen = *candidate; return 1; } static USHORT ReadUShort(BYTE* p) { return ((USHORT)p[0] << 8) + ((USHORT)p[1]); } static DWORD ReadDWord(BYTE* p) { return ((LONG)p[0] << 24) + ((LONG)p[1] << 16) + ((LONG)p[2] << 8) + ((LONG)p[3]); } static DWORD ReadTag(BYTE* p) { return ((LONG)p[3] << 24) + ((LONG)p[2] << 16) + ((LONG)p[1] << 8) + ((LONG)p[0]); } static void WriteDWord(BYTE* p, DWORD dw) { p[0] = (BYTE)((dw >> 24) & 0xFF); p[1] = (BYTE)((dw >> 16) & 0xFF); p[2] = (BYTE)((dw >> 8) & 0xFF); p[3] = (BYTE)((dw) & 0xFF); } static DWORD RoundUpToDWord(DWORD val) { return (val + 3) & ~3; } #define TTC_FILE 0x66637474 const DWORD sizeOfFixedHeader = 12; const DWORD offsetOfTableCount = 4; const DWORD sizeOfTableEntry = 16; const DWORD offsetOfTableTag = 0; const DWORD offsetOfTableChecksum = 4; const DWORD offsetOfTableOffset = 8; const DWORD offsetOfTableLength = 12; static bool ExtractFontData(HDC hdc, DWORD& fontDataSize, BYTE*& fontData) { bool ok = false; fontData = NULL; fontDataSize = 0; // Check if font is in TrueType collection if (GetFontData(hdc, TTC_FILE, 0, NULL, 0) != GDI_ERROR) { // Extract font data from TTC (TrueType Collection) // 1. Read number of tables in the font (ushort value at offset 2) USHORT nTables; BYTE uShortBuf[2]; if (GetFontData(hdc, 0, 4, uShortBuf, 2) == GDI_ERROR) { return false; } nTables = ReadUShort(uShortBuf); // 2. Calculate memory needed for the whole font header and read it into buffer DWORD headerSize = sizeOfFixedHeader + nTables * sizeOfTableEntry; BYTE* fontHeader = new BYTE[headerSize]; if (!fontHeader) { return false; } if (GetFontData(hdc, 0, 0, fontHeader, headerSize) == GDI_ERROR) { delete[] fontHeader; return false; } // 3. Calculate total font size. // Tables are padded to 4-byte boundaries, so length should be rounded up to dword. DWORD bufferSize = headerSize; USHORT i; for (i = 0; i < nTables; i++) { DWORD tableLength = ReadDWord(fontHeader + sizeOfFixedHeader + i * sizeOfTableEntry + offsetOfTableLength); if (i < nTables - 1) { bufferSize += RoundUpToDWord(tableLength); } else { bufferSize += tableLength; } } // 4. Copying header into target buffer. // Patch offsets with correct values while copying data. BYTE* buffer = new BYTE[bufferSize]; if (buffer == NULL) { delete[] fontHeader; return false; } memcpy(buffer, fontHeader, headerSize); // 5. Get table data from GDI, write it into known place // inside target buffer and fix offset value. DWORD runningOffset = headerSize; for (i = 0; i < nTables; i++) { BYTE* entryData = fontHeader + sizeOfFixedHeader + i * sizeOfTableEntry; DWORD tableTag = ReadTag(entryData + offsetOfTableTag); DWORD tableLength = ReadDWord(entryData + offsetOfTableLength); // Write new offset for this table. WriteDWord(buffer + sizeOfFixedHeader + i * sizeOfTableEntry + offsetOfTableOffset, runningOffset); //Get font data from GDI and place it into target buffer if (GetFontData(hdc, tableTag, 0, buffer + runningOffset, tableLength) == GDI_ERROR) { delete[] buffer; delete[] fontHeader; return false; } runningOffset += tableLength; // Pad tables (except last) with zero's if (i < nTables - 1) { while (runningOffset % 4 != 0) { buffer[runningOffset] = 0; ++runningOffset; } } } delete[] fontHeader; fontDataSize = bufferSize; fontData = buffer; } else { // Check if font is TrueType DWORD bufferSize = GetFontData(hdc, 0, 0, NULL, 0); if (bufferSize != GDI_ERROR) { BYTE* buffer = new BYTE[bufferSize]; if (buffer != NULL) { ok = (GetFontData(hdc, 0, 0, buffer, bufferSize) != GDI_ERROR); if (ok) { fontDataSize = bufferSize; fontData = buffer; } else { delete[] buffer; } } } } return ok; } ultralight::Ref GetFontData(const HFONT fontHandle) { HDC hdc = ::CreateCompatibleDC(NULL); if (hdc != NULL && fontHandle != NULL) { ::SelectObject(hdc, fontHandle); DWORD fontDataSize; BYTE* fontData; bool ok = ExtractFontData(hdc, fontDataSize, fontData); auto result = ultralight::Buffer::Create(fontData, fontDataSize); delete[] fontData; ::DeleteDC(hdc); return result; } return ultralight::Buffer::Create(nullptr, 0); } static LONG toGDIFontWeight(LONG fontWeight) { if (fontWeight < LONG(150)) return FW_THIN; if (fontWeight < LONG(250)) return FW_EXTRALIGHT; if (fontWeight < LONG(350)) return FW_LIGHT; if (fontWeight < LONG(450)) return FW_NORMAL; if (fontWeight < LONG(550)) return FW_MEDIUM; if (fontWeight < LONG(650)) return FW_SEMIBOLD; if (fontWeight < LONG(750)) return FW_BOLD; if (fontWeight < LONG(850)) return FW_EXTRABOLD; return FW_HEAVY; } uint32_t murmur3_32(const uint8_t* key, size_t len, uint32_t seed); static HFONT createGDIFont(const std::wstring& family, LONG desiredWeight, bool desiredItalic, int size, bool synthesizeItalic, uint32_t& logfont_hash) { HDC hdc = GetDC(0); LOGFONT logFont; memset(&logFont, 0, sizeof(LOGFONT)); logFont.lfCharSet = DEFAULT_CHARSET; #ifdef UNICODE std::wstring truncatedFamily = family.substr(0, static_cast(LF_FACESIZE - 1)); memcpy(logFont.lfFaceName, truncatedFamily.data(), truncatedFamily.length() * sizeof(wchar_t)); #else std::vector family_utf8; int sz = WideCharToMultiByte(CP_UTF8, 0, family.c_str(), -1, NULL, 0, NULL, NULL); if (sz <= 0) return nullptr; family_utf8.resize(sz); WideCharToMultiByte(CP_UTF8, 0, family.c_str(), -1, &family_utf8[0], (int)family_utf8.size(), NULL, NULL); std::string family_utf8Str = std::string(&family_utf8[0]); std::string truncatedFamily = family_utf8Str.substr(0, static_cast(LF_FACESIZE - 1)); memcpy(logFont.lfFaceName, truncatedFamily.data(), truncatedFamily.length() * sizeof(char)); #endif logFont.lfFaceName[truncatedFamily.length()] = 0; logFont.lfPitchAndFamily = 0; MatchImprovingProcData matchData(toGDIFontWeight(desiredWeight), desiredItalic); EnumFontFamiliesEx(hdc, &logFont, matchImprovingEnumProc, reinterpret_cast(&matchData), 0); if (!matchData.m_hasMatched) return nullptr; matchData.m_chosen.lfHeight = -size; matchData.m_chosen.lfWidth = 0; matchData.m_chosen.lfEscapement = 0; matchData.m_chosen.lfOrientation = 0; matchData.m_chosen.lfUnderline = false; matchData.m_chosen.lfStrikeOut = false; matchData.m_chosen.lfCharSet = DEFAULT_CHARSET; matchData.m_chosen.lfOutPrecision = OUT_TT_ONLY_PRECIS; matchData.m_chosen.lfQuality = DEFAULT_QUALITY; matchData.m_chosen.lfPitchAndFamily = DEFAULT_PITCH | FF_DONTCARE; if (desiredItalic && !matchData.m_chosen.lfItalic && synthesizeItalic) matchData.m_chosen.lfItalic = 1; auto chosenFont = ::CreateFontIndirect(&matchData.m_chosen); if (!chosenFont) return nullptr; SaveDC(hdc); SelectObject(hdc, chosenFont); struct FontDescription { TCHAR actualName[LF_FACESIZE]; BYTE italic; LONG weight; } fontDescription; fontDescription.italic = matchData.m_chosen.lfItalic; fontDescription.weight = matchData.m_chosen.lfWeight; GetTextFace(hdc, LF_FACESIZE, fontDescription.actualName); RestoreDC(hdc, -1); if (_tcsicmp(matchData.m_chosen.lfFaceName, fontDescription.actualName)) { DeleteObject(chosenFont); return nullptr; } logfont_hash = murmur3_32((const uint8_t*)&(fontDescription), sizeof(FontDescription), 0xBEEF); return chosenFont; } static bool CurrentFontContainsCharacter(HDC hdc, wchar_t character) { std::unique_ptr buffer(new char[::GetFontUnicodeRanges(hdc, 0)]); GLYPHSET* glyphset = reinterpret_cast(buffer.get()); ::GetFontUnicodeRanges(hdc, glyphset); for (unsigned i = 0; i < glyphset->cRanges; ++i) { if (glyphset->ranges[i].wcLow <= character && glyphset->ranges[i].wcLow + glyphset->ranges[i].cGlyphs > character) { return true; } } return false; } static IMLangFontLink2* GetFontLinkInterface() { static IMultiLanguage* multi_language = NULL; if (!multi_language) { if (::CoCreateInstance(CLSID_CMultiLanguage, 0, CLSCTX_ALL, IID_IMultiLanguage, reinterpret_cast(&multi_language)) != S_OK) return 0; } static IMLangFontLink2* font_link = NULL; if (!font_link) { if (multi_language->QueryInterface(&font_link) != S_OK) return 0; } return font_link; } static int CALLBACK MetaFileEnumProc( HDC hdc, HANDLETABLE* table, CONST ENHMETARECORD* record, int table_entries, LPARAM log_font) { // Enumerate the MetaFile operations and find the last CreateFontIndirect call // to determined what font uniscribe used in the metafile. if (record->iType == EMR_EXTCREATEFONTINDIRECTW) { const EMREXTCREATEFONTINDIRECTW* create_font_record = reinterpret_cast(record); *reinterpret_cast(log_font) = create_font_record->elfw.elfLogFont; } return true; } static LOGFONT CreateMLangFont(IMLangFontLink2* font_link, HDC hdc, DWORD code_pages, wchar_t character) { HFONT mlang_font = NULL; LOGFONT lf = { 0 }; if (SUCCEEDED(font_link->MapFont(hdc, code_pages, character, &mlang_font)) && mlang_font) { ::GetObject(mlang_font, sizeof(LOGFONT), &lf); font_link->ReleaseFont(mlang_font); } return lf; } static bool FontContainsCharacter(const LOGFONT& logfont, HDC dc, wchar_t character) { HFONT font = ::CreateFontIndirect(&logfont); bool contains = font; if (contains) { HGDIOBJ old_font = ::SelectObject(dc, font); contains = CurrentFontContainsCharacter(dc, character); ::SelectObject(dc, old_font); } ::DeleteObject(font); return contains; } static const std::vector* GetLinkedFonts(const std::wstring& family) { typedef std::unordered_map > FontLinkMap; static FontLinkMap system_link_map; FontLinkMap::iterator it = system_link_map.find(family); if (it != system_link_map.end()) { return &it->second; } HKEY key = NULL; if (FAILED(::RegOpenKeyEx(HKEY_LOCAL_MACHINE, kFontLinkKey, 0, KEY_READ, &key))) { return NULL; } DWORD size = 0; RegQueryValueEx(key, family.c_str(), 0, NULL, NULL, &size); std::unique_ptr buffer(new BYTE[size]); if (SUCCEEDED(RegQueryValueEx(key, family.c_str(), 0, NULL, buffer.get(), &size))) { // The value in the registry is a MULTI_SZ like: // ,\0 // for example: // MSMINCHO.TTC,MS Mincho\0 // MINGLIU.TTC,MingLiU\0 // SIMSUN.TTC,SimSun\0 // And we need to find all the font families. std::vector& linked_fonts = system_link_map[family]; unsigned i = 0; unsigned length = size / sizeof(wchar_t); wchar_t* string_value = reinterpret_cast(buffer.get()); while (i < length) { while (i < length && string_value[i] != ',') i++; i++; unsigned j = i; while (j < length && string_value[j]) j++; linked_fonts.push_back(std::wstring(string_value + i, j - i)); i = j + 1; } return &linked_fonts; } return NULL; } // Fallback font is determined by following steps: // 1. Use MLang to map current font. // 2. Try drawing with the mapped font and find which font uniscribe used. // 3. if the font in 2 does not contain the character, try its linked fonts. LOGFONT GetFallbackFont(HDC dc, wchar_t character) { LOGFONT fallback_font = { 0 }; ::GetObject(::GetCurrentObject(dc, OBJ_FONT), sizeof(fallback_font), &fallback_font); if (IMLangFontLink2* font_link = GetFontLinkInterface()) { DWORD char_code_pages = 0; font_link->GetCharCodePages(character, &char_code_pages); fallback_font = CreateMLangFont(font_link, dc, char_code_pages, character); } // To find out what font Uniscribe would use, we make it draw into a // metafile and intercept calls to CreateFontIndirect(). HDC meta_file_dc = ::CreateEnhMetaFile(dc, NULL, NULL, NULL); ::SelectObject(meta_file_dc, ::GetCurrentObject(dc, OBJ_FONT)); bool success = false; SCRIPT_STRING_ANALYSIS ssa; if (SUCCEEDED(::ScriptStringAnalyse( meta_file_dc, &character, 1, 0, -1, SSA_METAFILE | SSA_FALLBACK | SSA_GLYPHS | SSA_LINK, 0, NULL, NULL, NULL, NULL, NULL, &ssa))) { success = SUCCEEDED(::ScriptStringOut(ssa, 0, 0, 0, NULL, 0, 0, FALSE)); ::ScriptStringFree(&ssa); } HENHMETAFILE meta_file = ::CloseEnhMetaFile(meta_file_dc); if (success) ::EnumEnhMetaFile(0, meta_file, MetaFileEnumProc, &fallback_font, NULL); ::DeleteEnhMetaFile(meta_file); if (FontContainsCharacter(fallback_font, dc, character)) return fallback_font; const std::vector* linked_fonts = GetLinkedFonts( fallback_font.lfFaceName); if (!linked_fonts) return fallback_font; for (size_t i = 0; i < linked_fonts->size(); ++i) { LOGFONT logfont = { 0 }; logfont.lfCharSet = DEFAULT_CHARSET; ::wcscpy_s(logfont.lfFaceName, LF_FACESIZE, linked_fonts->at(i).c_str()); if (FontContainsCharacter(logfont, dc, character)) return logfont; } return fallback_font; } uint32_t murmur3_32(const uint8_t* key, size_t len, uint32_t seed) { uint32_t h = seed; if (len > 3) { const uint32_t* key_x4 = (const uint32_t*)key; size_t i = len >> 2; do { uint32_t k = *key_x4++; k *= 0xcc9e2d51; k = (k << 15) | (k >> 17); k *= 0x1b873593; h ^= k; h = (h << 13) | (h >> 19); h = (h * 5) + 0xe6546b64; } while (--i); key = (const uint8_t*)key_x4; } if (len & 3) { size_t i = len & 3; uint32_t k = 0; key = &key[i - 1]; do { k <<= 8; k |= *key--; } while (--i); k *= 0xcc9e2d51; k = (k << 15) | (k >> 17); k *= 0x1b873593; h ^= k; } h ^= len; h ^= h >> 16; h *= 0x85ebca6b; h ^= h >> 13; h *= 0xc2b2ae35; h ^= h >> 16; return h; } namespace ultralight { String16 FontLoaderWin::fallback_font() const { return "Times New Roman"; } static int CALLBACK metaFileEnumProc(HDC hdc, HANDLETABLE* table, CONST ENHMETARECORD* record, int tableEntries, LPARAM logFont) { if (record->iType == EMR_EXTCREATEFONTINDIRECTW) { const EMREXTCREATEFONTINDIRECTW* createFontRecord = reinterpret_cast(record); *reinterpret_cast(logFont) = createFontRecord->elfw.elfLogFont; } return true; } IMLangFontLink2* getFontLinkInterface() { static IMultiLanguage *multiLanguage; if (!multiLanguage) { if (CoCreateInstance(CLSID_CMultiLanguage, 0, CLSCTX_ALL, IID_IMultiLanguage, (void**)&multiLanguage) != S_OK) return 0; } static IMLangFontLink2* langFontLink; if (!langFontLink) { if (multiLanguage->QueryInterface(&langFontLink) != S_OK) return 0; } return langFontLink; } String16 FontLoaderWin::fallback_font_for_characters(const String16& characters, int weight, bool italic, float size) const { String16 result = fallback_font(); LOGFONT logFont = GetFallbackFont(GetDC(0), characters[0]); if (logFont.lfFaceName[0]) result = String16(logFont.lfFaceName, lstrlenW(logFont.lfFaceName)); return result; } Ref FontLoaderWin::Load(const String16& family, int weight, bool italic, float size) { uint32_t hash = 0; HFONT font = createGDIFont(family.data(), weight, italic, (int)size, false, hash); if (!font) return ultralight::Buffer::Create(nullptr, 0); auto i = fonts_.find(hash); if (i == fonts_.end()) { ultralight::Ref data = GetFontData(font); DeleteObject(font); fonts_.insert({ hash, data }); return data; } else { DeleteObject(font); return *i->second.get(); } } } // namespace ultralight namespace framework { ultralight::FontLoader* CreatePlatformFontLoader() { return new ultralight::FontLoaderWin(); } } // namespace framework #include "Listener.h" void setup_ruby_class_listener(mrb_state* mrb, RClass* ruby_module) { MrbWrap::wrap_class_under(mrb, "Listener", ruby_module); auto ruby_listener_class = MrbWrap::define_data_class_under(mrb, "Listener", ruby_module); MrbWrap::wrap_constructor(mrb); MrbWrap::define_member_function(mrb, ruby_listener_class, "listen", MRUBY_FUNC { mrb_int port; mrb_value address; mrb_get_args(mrb, "i|o", &port, &address); sf::IpAddress address_to_listen_on = sf::IpAddress::Any; if (mrb_string_p(address)) address_to_listen_on = sf::IpAddress(mrb_str_to_cstr(mrb, address)); //! TODO: Error message if wrong argument type is used auto listener = MrbWrap::convert_from_object(mrb, self); auto status_code = listener->listen(static_cast(port), address_to_listen_on); return mrb_fixnum_value(status_code); }, MRB_ARGS_ARG(1, 1)); MrbWrap::define_member_function(mrb, ruby_listener_class, "accept", MRUBY_FUNC { mrb_value ruby_socket; mrb_get_args(mrb, "o", &ruby_socket); auto listener = MrbWrap::convert_from_object(mrb, self); auto socket = MrbWrap::convert_from_object(mrb, ruby_socket); auto status_code = listener->accept(*socket); return mrb_fixnum_value(status_code); }, MRB_ARGS_REQ(1)); }// SPDX-License-Identifier: BSD-2-Clause // This code is part of the sfizz library and is licensed under a BSD 2-clause // license. You should have receive a LICENSE.md file along with the code. // If not, contact the sfizz maintainers at https://github.com/sfztools/sfizz /** * @brief This file holds some of the specific MidiState tests. Some tests on the * effects of the midi state are also available in e.g. RegionValueComputationT.cpp * and SynthT.cpp. */ #include "sfizz/MidiState.h" #include "sfizz/Synth.h" #include "sfizz/SfzHelpers.h" #include "catch2/catch.hpp" #include "absl/strings/string_view.h" #include "TestHelpers.h" using namespace Catch::literals; using namespace sfz::literals; TEST_CASE("[MidiState] Initial values") { sfz::MidiState state; for (unsigned cc = 0; cc < sfz::config::numCCs; cc++) REQUIRE(state.getCCValue(cc) == 0_norm); REQUIRE( state.getPitchBend() == 0 ); } TEST_CASE("[MidiState] Set and get CCs") { sfz::MidiState state; state.ccEvent(0, 24, 23_norm); state.ccEvent(0, 123, 124_norm); REQUIRE(state.getCCValue(24) == 23_norm); REQUIRE(state.getCCValue(123) == 124_norm); } TEST_CASE("[MidiState] Set and get pitch bends") { sfz::MidiState state; state.pitchBendEvent(0, 0.5f); REQUIRE(state.getPitchBend() == 0.5f); state.pitchBendEvent(0, 0.0f); REQUIRE(state.getPitchBend() == 0.0f); } TEST_CASE("[MidiState] Resetting things") { sfz::MidiState state; state.pitchBendEvent(0, 0.7f); state.noteOnEvent(0, 64, 24_norm); state.ccEvent(0, 123, 124_norm); state.channelAftertouchEvent(0, 56_norm); state.polyAftertouchEvent(0, 64, 43_norm); state.advanceTime(1024); // Only reset note stuff state.resetNoteStates(); REQUIRE(state.getNoteVelocity(64) == 0_norm); REQUIRE(state.getNoteDuration(64) == 0_norm); REQUIRE(state.getActiveNotes() == 0); // Extended CCs too REQUIRE(state.getCCValue(131) == 0.0f); REQUIRE(state.getCCValue(132) == 0.0f); REQUIRE(state.getCCValue(133) == 0.0f); REQUIRE(state.getCCValue(134) == 0.0f); REQUIRE(state.getCCValue(135) == 0.0f); REQUIRE(state.getCCValue(136) == 0.0f); REQUIRE(state.getCCValue(137) == 0.0f); // State isn't reset REQUIRE(state.getPitchBend() != 0.0f); REQUIRE(state.getCCValue(123) != 0_norm); REQUIRE(state.getChannelAftertouch() != 0_norm); REQUIRE(state.getPolyAftertouch(64) != 0_norm); state.resetEventStates(); // But now it is REQUIRE(state.getPitchBend() == 0.0f); REQUIRE(state.getCCValue(123) == 0_norm); REQUIRE(state.getChannelAftertouch() == 0_norm); REQUIRE(state.getPolyAftertouch(64) == 0_norm); } TEST_CASE("[MidiState] Flushing state") { sfz::MidiState state; state.pitchBendEvent(40, 0.7f); state.ccEvent(100, 123, 124_norm); state.channelAftertouchEvent(20, 56_norm); state.polyAftertouchEvent(80, 64, 43_norm); REQUIRE(state.getCCEvents(123).size() > 1); REQUIRE(state.getChannelAftertouchEvents().size() > 1); REQUIRE(state.getPolyAftertouchEvents(64).size() > 1); REQUIRE(state.getPitchEvents().size() > 1); state.flushEvents(); REQUIRE(state.getCCEvents(123).size() == 1); REQUIRE(state.getChannelAftertouchEvents().size() == 1); REQUIRE(state.getPolyAftertouchEvents(64).size() == 1); REQUIRE(state.getPitchEvents().size() == 1); REQUIRE(state.getCCValue(123) == 124_norm); REQUIRE(state.getChannelAftertouch() == 56_norm); REQUIRE(state.getPolyAftertouch(64) == 43_norm); REQUIRE(state.getPitchBend() == 0.7f); } TEST_CASE("[MidiState] Set and get note velocities") { sfz::MidiState state; state.noteOnEvent(0, 64, 24_norm); REQUIRE(+state.getNoteVelocity(64) == 24_norm); state.noteOnEvent(0, 64, 123_norm); REQUIRE(+state.getNoteVelocity(64) == 123_norm); } TEST_CASE("[MidiState] Extended CCs") { sfz::MidiState state; state.ccEvent(0, 142, 64_norm); // should not trap } TEST_CASE("[MidiState] Last note velocity") { sfz::MidiState state; state.noteOnEvent(0, 62, 64_norm); state.noteOnEvent(0, 60, 10_norm); REQUIRE(state.getVelocityOverride() == 64_norm); } TEST_CASE("[CC] Extended CCs on offset and delay") { sfz::Synth synth; std::vector messageList; sfz::Client client(&messageList); client.setReceiveCallback(&simpleMessageReceiver); sfz::AudioBuffer buffer { 2, static_cast(synth.getSamplesPerBlock()) }; synth.setSampleRate(48000); SECTION("CC131 - Note on velocity") { synth.loadSfzString(fs::current_path() / "tests/TestFiles/extended_ccs.sfz", R"( key=60 delay_cc131=1 sample=kick.wav key=61 offset_cc131=100 sample=snare.wav )"); synth.hdNoteOn(0, 60, 0.0f); synth.hdNoteOn(0, 60, 0.5f); synth.hdNoteOn(0, 61, 0.0f); synth.hdNoteOn(0, 61, 0.5f); synth.dispatchMessage(client, 0, "/voice0/remaining_delay", "", nullptr); synth.dispatchMessage(client, 0, "/voice1/remaining_delay", "", nullptr); synth.dispatchMessage(client, 0, "/voice2/source_position", "", nullptr); synth.dispatchMessage(client, 0, "/voice3/source_position", "", nullptr); std::vector expected { "/voice0/remaining_delay,i : { 0 }", "/voice1/remaining_delay,i : { 24000 }", "/voice2/source_position,i : { 0 }", "/voice3/source_position,i : { 50 }", }; REQUIRE(messageList == expected); } SECTION("CC132 - Note off velocity") { synth.loadSfzString(fs::current_path() / "tests/TestFiles/extended_ccs.sfz", R"( key=60 sample=*silence key=60 delay_cc132=1 sample=kick.wav trigger=release key=61 sample=snare.wav key=61 offset_cc132=100 sample=snare.wav trigger=release )"); synth.hdNoteOn(0, 60, 1.0f); synth.hdNoteOff(1, 60, 0.0f); synth.hdNoteOn(2, 60, 1.0f); synth.hdNoteOff(3, 60, 0.5f); synth.hdNoteOn(4, 61, 1.0f); synth.hdNoteOff(5, 61, 0.0f); synth.hdNoteOn(6, 61, 1.0f); synth.hdNoteOff(7, 61, 0.5f); synth.dispatchMessage(client, 10, "/voice1/remaining_delay", "", nullptr); synth.dispatchMessage(client, 10, "/voice3/remaining_delay", "", nullptr); synth.dispatchMessage(client, 10, "/voice5/source_position", "", nullptr); synth.dispatchMessage(client, 10, "/voice7/source_position", "", nullptr); std::vector expected { "/voice1/remaining_delay,i : { 1 }", // 1 is the note off event delay "/voice3/remaining_delay,i : { 24003 }", // 3 is the note off event delay "/voice5/source_position,i : { 0 }", "/voice7/source_position,i : { 50 }", }; REQUIRE(messageList == expected); } SECTION("CC133 - Note number") { synth.loadSfzString(fs::current_path() / "tests/TestFiles/extended_ccs.sfz", R"( delay_cc133=1 offset_cc133=100 sample=kick.wav )"); synth.hdNoteOn(0, 0, 1.0f); synth.hdNoteOn(0, 127, 1.0f); synth.dispatchMessage(client, 0, "/voice0/remaining_delay", "", nullptr); synth.dispatchMessage(client, 0, "/voice1/remaining_delay", "", nullptr); synth.dispatchMessage(client, 0, "/voice0/source_position", "", nullptr); synth.dispatchMessage(client, 0, "/voice1/source_position", "", nullptr); std::vector expected { "/voice0/remaining_delay,i : { 0 }", "/voice1/remaining_delay,i : { 48000 }", "/voice0/source_position,i : { 0 }", "/voice1/source_position,i : { 100 }", }; REQUIRE(messageList == expected); } SECTION("CC134 - Note gate") { synth.loadSfzString(fs::current_path() / "tests/TestFiles/extended_ccs.sfz", R"( delay_cc134=1 offset_cc134=100 sample=kick.wav )"); synth.hdNoteOn(0, 60, 1.0f); synth.hdNoteOn(0, 127, 1.0f); synth.hdNoteOff(1, 60, 1.0f); synth.hdNoteOff(1, 127, 1.0f); synth.hdNoteOn(2, 60, 1.0f); synth.hdNoteOn(2, 127, 1.0f); synth.dispatchMessage(client, 0, "/voice0/remaining_delay", "", nullptr); synth.dispatchMessage(client, 0, "/voice1/remaining_delay", "", nullptr); synth.dispatchMessage(client, 0, "/voice2/remaining_delay", "", nullptr); synth.dispatchMessage(client, 0, "/voice3/remaining_delay", "", nullptr); synth.dispatchMessage(client, 0, "/voice0/source_position", "", nullptr); synth.dispatchMessage(client, 0, "/voice1/source_position", "", nullptr); synth.dispatchMessage(client, 0, "/voice2/source_position", "", nullptr); synth.dispatchMessage(client, 0, "/voice3/source_position", "", nullptr); std::vector expected { "/voice0/remaining_delay,i : { 0 }", "/voice1/remaining_delay,i : { 48000 }", "/voice2/remaining_delay,i : { 2 }", // 2 is the event delay "/voice3/remaining_delay,i : { 48002 }", // 2 is the event delay "/voice0/source_position,i : { 0 }", "/voice1/source_position,i : { 100 }", "/voice2/source_position,i : { 0 }", "/voice3/source_position,i : { 100 }", }; REQUIRE(messageList == expected); } SECTION("CC137 - Alternate") { synth.loadSfzString(fs::current_path() / "tests/TestFiles/extended_ccs.sfz", R"( delay_cc137=1 offset_cc137=100 sample=kick.wav )"); synth.hdNoteOn(0, 60, 1.0f); synth.hdNoteOn(0, 127, 1.0f); synth.hdNoteOn(0, 54, 1.0f); synth.hdNoteOn(0, 12, 1.0f); synth.dispatchMessage(client, 0, "/voice0/remaining_delay", "", nullptr); synth.dispatchMessage(client, 0, "/voice1/remaining_delay", "", nullptr); synth.dispatchMessage(client, 0, "/voice2/remaining_delay", "", nullptr); synth.dispatchMessage(client, 0, "/voice3/remaining_delay", "", nullptr); synth.dispatchMessage(client, 0, "/voice0/source_position", "", nullptr); synth.dispatchMessage(client, 0, "/voice1/source_position", "", nullptr); synth.dispatchMessage(client, 0, "/voice2/source_position", "", nullptr); synth.dispatchMessage(client, 0, "/voice3/source_position", "", nullptr); std::vector expected { "/voice0/remaining_delay,i : { 0 }", "/voice1/remaining_delay,i : { 48000 }", "/voice2/remaining_delay,i : { 0 }", "/voice3/remaining_delay,i : { 48000 }", "/voice0/source_position,i : { 0 }", "/voice1/source_position,i : { 100 }", "/voice2/source_position,i : { 0 }", "/voice3/source_position,i : { 100 }", }; REQUIRE(messageList == expected); } SECTION("CC140 - Keydelta") { synth.loadSfzString(fs::current_path() / "tests/TestFiles/extended_ccs.sfz", R"( delay=2 offset=200 delay_cc140=1 offset_cc140=100 sample=kick.wav )"); synth.hdNoteOn(0, 60, 1.0f); synth.hdNoteOn(0, 61, 1.0f); synth.hdNoteOn(0, 59, 1.0f); synth.dispatchMessage(client, 0, "/voice0/remaining_delay", "", nullptr); synth.dispatchMessage(client, 0, "/voice1/remaining_delay", "", nullptr); synth.dispatchMessage(client, 0, "/voice2/remaining_delay", "", nullptr); synth.dispatchMessage(client, 0, "/voice0/source_position", "", nullptr); synth.dispatchMessage(client, 0, "/voice1/source_position", "", nullptr); synth.dispatchMessage(client, 0, "/voice2/source_position", "", nullptr); std::vector expected { "/voice0/remaining_delay,i : { 96000 }", "/voice1/remaining_delay,i : { 144000 }", "/voice2/remaining_delay,i : { 0 }", "/voice0/source_position,i : { 200 }", "/voice1/source_position,i : { 300 }", "/voice2/source_position,i : { 0 }", }; REQUIRE(messageList == expected); } SECTION("CC141 - Absolute Keydelta") { synth.loadSfzString(fs::current_path() / "tests/TestFiles/extended_ccs.sfz", R"( delay=2 offset=200 delay_cc141=1 offset_cc141=100 sample=kick.wav )"); synth.hdNoteOn(0, 60, 1.0f); synth.hdNoteOn(0, 61, 1.0f); synth.hdNoteOn(0, 59, 1.0f); synth.dispatchMessage(client, 0, "/voice0/remaining_delay", "", nullptr); synth.dispatchMessage(client, 0, "/voice1/remaining_delay", "", nullptr); synth.dispatchMessage(client, 0, "/voice2/remaining_delay", "", nullptr); synth.dispatchMessage(client, 0, "/voice0/source_position", "", nullptr); synth.dispatchMessage(client, 0, "/voice1/source_position", "", nullptr); synth.dispatchMessage(client, 0, "/voice2/source_position", "", nullptr); std::vector expected { "/voice0/remaining_delay,i : { 96000 }", "/voice1/remaining_delay,i : { 144000 }", "/voice2/remaining_delay,i : { 192000 }", "/voice0/source_position,i : { 200 }", "/voice1/source_position,i : { 300 }", "/voice2/source_position,i : { 400 }", }; REQUIRE(messageList == expected); } } #include using namespace std; typedef long long int ll; typedef pair P; typedef pair Pll; typedef vector Vi; typedef tuple T; #define FOR(i,s,x) for(ll i=s;i<(ll)(x);i++) #define REP(i,x) FOR(i,0,x) #define ALL(c) c.begin(), c.end() #define DUMP( x ) cerr << #x << " = " << ( x ) << endl int main() { ll N; cin >> N; if (N == 1) { cout << N << endl; return 0; } ll ans = 1; FOR(i, 2, sqrt(N)+1) { int cnt = 0; while (N % i == 0) { cnt++; N /= i; } if (cnt > 0) ans *= i; } if (N > 1) ans *= N; cout << ans << endl; return 0; } Alexey-N-Chernyshov/cpp-libp2ptest/libp2p/muxer/yamux/yamux_frame_test.cpp /** * Copyright Soramitsu Co., Ltd. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 */ #include "libp2p/muxer/yamux/yamux_frame.hpp" #include #include using namespace libp2p::connection; using namespace libp2p::common; class YamuxFrameTest : public ::testing::Test { public: ~YamuxFrameTest() override = default; static constexpr size_t data_length = 6; static constexpr YamuxedConnection::StreamId default_stream_id = 1; static constexpr uint32_t default_ping_value = 337; ByteArray data{"1234456789AB"_unhex}; /** * Check that all frame's fields are as expected */ void checkFrame(boost::optional frame_opt, uint8_t version, YamuxFrame::FrameType type, YamuxFrame::Flag flag, YamuxedConnection::StreamId stream_id, uint32_t length, const ByteArray &frame_data) { ASSERT_TRUE(frame_opt); auto frame = *frame_opt; ASSERT_EQ(frame.version, version); ASSERT_EQ(frame.type, type); ASSERT_EQ(frame.flags, static_cast(flag)); ASSERT_EQ(frame.stream_id, stream_id); ASSERT_EQ(frame.length, length); ASSERT_EQ(frame.data, frame_data); } }; /** * @given data message frame * @when parsed by YamuxFrame * @then the frame is parsed successfully */ TEST_F(YamuxFrameTest, ParseFrameSuccess) { ByteArray data_frame_bytes = dataMsg(default_stream_id, data); auto frame_opt = parseFrame(data_frame_bytes); SCOPED_TRACE("ParseFrameSuccess"); checkFrame(frame_opt, YamuxFrame::kDefaultVersion, YamuxFrame::FrameType::DATA, YamuxFrame::Flag::NONE, default_stream_id, data_length, data); } /** * @given invalid frame * @when parsed by YamuxFrame * @then the frame is not parsed */ TEST_F(YamuxFrameTest, ParseFrameFailure) { auto frame_opt = parseFrame(data); ASSERT_FALSE(frame_opt); } /** * @given new stream frame * @when parsed by YamuxFrame * @then the frame is parsed successfully */ TEST_F(YamuxFrameTest, NewStreamMsg) { auto frame_bytes = newStreamMsg(default_stream_id); auto frame_opt = parseFrame(frame_bytes); SCOPED_TRACE("NewStreamMsg"); checkFrame(frame_opt, YamuxFrame::kDefaultVersion, YamuxFrame::FrameType::DATA, YamuxFrame::Flag::SYN, default_stream_id, 0, ByteArray{}); } /** * @given ack stream frame * @when parsed by YamuxFrame * @then the frame is parsed successfully */ TEST_F(YamuxFrameTest, AckStreamMsg) { auto frame_bytes = ackStreamMsg(default_stream_id); auto frame_opt = parseFrame(frame_bytes); SCOPED_TRACE("AckStreamMsg"); checkFrame(frame_opt, YamuxFrame::kDefaultVersion, YamuxFrame::FrameType::DATA, YamuxFrame::Flag::ACK, default_stream_id, 0, ByteArray{}); } /** * @given close stream frame * @when parsed by YamuxFrame * @then the frame is parsed successfully */ TEST_F(YamuxFrameTest, CloseStreamMsg) { auto frame_bytes = closeStreamMsg(default_stream_id); auto frame_opt = parseFrame(frame_bytes); SCOPED_TRACE("CloseStreamMsg"); checkFrame(frame_opt, YamuxFrame::kDefaultVersion, YamuxFrame::FrameType::DATA, YamuxFrame::Flag::FIN, default_stream_id, 0, ByteArray{}); } /** * @given reset frame * @when parsed by YamuxFrame * @then the frame is parsed successfully */ TEST_F(YamuxFrameTest, ResetStreamMsg) { auto frame_bytes = resetStreamMsg(default_stream_id); auto frame_opt = parseFrame(frame_bytes); SCOPED_TRACE("ResetStreamMsg"); checkFrame(frame_opt, YamuxFrame::kDefaultVersion, YamuxFrame::FrameType::DATA, YamuxFrame::Flag::RST, default_stream_id, 0, ByteArray{}); } /** * @given ping out frame * @when parsed by YamuxFrame * @then the frame is parsed successfully */ TEST_F(YamuxFrameTest, PingOutMsg) { auto frame_bytes = pingOutMsg(default_ping_value); auto frame_opt = parseFrame(frame_bytes); SCOPED_TRACE("PingOutMsg"); checkFrame(frame_opt, YamuxFrame::kDefaultVersion, YamuxFrame::FrameType::PING, YamuxFrame::Flag::SYN, 0, default_ping_value, ByteArray{}); } /** * @given ping response frame * @when parsed by YamuxFrame * @then the frame is parsed successfully */ TEST_F(YamuxFrameTest, PingResponseMsg) { auto frame_bytes = pingResponseMsg(default_ping_value); auto frame_opt = parseFrame(frame_bytes); SCOPED_TRACE("PingResponseMsg"); checkFrame(frame_opt, YamuxFrame::kDefaultVersion, YamuxFrame::FrameType::PING, YamuxFrame::Flag::ACK, 0, default_ping_value, ByteArray{}); } /** * @given go away frame * @when parsed by YamuxFrame * @then the frame is parsed successfully */ TEST_F(YamuxFrameTest, GoAwayMsg) { auto frame_bytes = goAwayMsg(YamuxFrame::GoAwayError::PROTOCOL_ERROR); auto frame_opt = parseFrame(frame_bytes); SCOPED_TRACE("GoAwayMsg"); checkFrame(frame_opt, YamuxFrame::kDefaultVersion, YamuxFrame::FrameType::GO_AWAY, YamuxFrame::Flag::NONE, 0, static_cast(YamuxFrame::GoAwayError::PROTOCOL_ERROR), ByteArray{}); } gameArena.cpp #include "gameArena.h" #include "starmanMove.h" #include #include using namespace std; /* Function Name: gameArena (Constructor) * * Function Description: * Declares all the variables and intitializes all of them. * * Parameters: * No parameters needed. * * return value: * A constructor does not require a return statement. */ gameArena::gameArena(){ gePointer = ≥ boardP = &board; ge.musk.encounters = 0; ge.yugo.encounters = 0; ge.pinto.encounters = 0; ge.roadster.encounters = 0; } /* Function Name: rulesDisplay * * Function Description: * Displays the story and rules of the Game at the start. * * Parameters: * No parameters needed * * return value: * There is no return statement. */ void gameArena::rulesDisplay(){ cout << "We have created a simple version of a classic game TESLA in C++." << endl; cout << endl; cout << "The player starts in a random position on a checkered floor of a room in SpaceX." << endl; cout << endl; cout << "Goal: In this game, you will have to save Elon Musk\'s prized Tesla Roadster from being sent" << endl; cout << "into space before becoming the STARMAN." << endl; cout << endl; cout << "Story: You find your way to SpaceX the night before the Roadster is mounted atop the rocket" << endl; cout << "which is to send it into space. The building is dark and the Roadster is hidden somewhere in" << endl; cout << "a large open dark room. In addition to the Roadster, two other cars (a Yugo and a Pinto) are" << endl; cout << "being stored in the same facility as well. ELON MUSK is sleeping somewhere in the same room" << endl; cout << "and you have to avoid waking him to find your way to the Roadster. Once awoken he will randomnly" << endl; cout << "move through the building looking for you. If he lands next to you, you can get away from him only" << endl; cout << "once. The second time you will be the STARMAN and blasted into the space with his Roadster. Once" << endl; cout << "he is awake your only chance to avoid being STARMAN is to make your escape in his roadster. If you" << endl; cout << "get into either of the two cars you will be caught and become the STARMAN." << endl; cout << endl; cout << "This article states the rules of the TESLA game:" << endl; cout << "1) The player will be starting in a random unoccupied location in SpaceX." << endl; cout << "2) The player will be indicated as \"UU\"." << endl; cout << "3) The player will have to enter w (forward/north), a (left/west), s (backward/south), d(right/east)" << endl; cout << "for movement directions." << endl; cout << "4) The player will be guided to the proper location of the Roadster by issuing a hint which will" << endl; cout << "state if the user is GETTING FAR or GETTING CLOSER to the Roadster. You will not be told to go in" << endl; cout << "a specific direction." << endl; cout << "5) Intitially, is sleeping in the same room of SpaceX. You will know the postion of ELON MUSK while he is sleeping" << endl; cout << "It will be indicated on the screen as \"EE\". There are 50 MINES that will be detonated when the player steps on them." << endl; cout << "No sooner the first MINE is triggered, ELON MUSK WAKES UP and he will start chasing you. BEWARE: ELON MUSK MOVES FASTER THAN YOU." << endl; cout << "6) Once the game is over you will be asked to play again and if chose to do so, you will be placed in the room again at a different location." << endl; cout << "7) The player will be able to quit the game anytime. The player must hit Q to quit the game. Once you choose to quit the game," << endl; cout << "your statistics will be displayed about the number of turns it took the player to" << endl; cout << "find the roadster, the number of times the roadster was found, and the number of times the player became STARMAN." << endl; cout << endl; cout << endl; cout << endl; } /* Function Name: boardDisplay * * Function Description: * This function displays the board (SpaceX Room). * * Parameters: * No parameters needed * * return value: * True is returned as it is a "bool" function. */ bool gameArena::boardDisplay(){ for(unsigned int i = 0; i < ROWS; i++){ for(unsigned int l = 0; l < BLOCK_LENGTH; l++){ for(unsigned int j = 0; j < COLUMNS; j++){ for(unsigned int k = 0; k < BLOCK_WIDTH; k++){ cout << board[i][j]; } } cout << endl; } } return true; } /* Function Name: boardGenerate * * Function Description: * This function generates a board (SpaceX Room) for the game. * * Parameters: * No parameteres needed. * * return value: * True is returned as it is a "bool" function. */ bool gameArena::boardGenerate(){ for(unsigned int i = 0; i < ROWS; i++){ for(unsigned int j = 0; j < COLUMNS; j++){ if((i + j) % 2 == 0){ board[i][j] = static_cast(WHITE); } else{ board[i][j] = static_cast(BLACK); } } } return true; } /* Function Name: posAlloc * * Function Description: * This function generates random numbers (which will be used as coordinates) for allocating positions to the elements of the game on the board. * * Parameters: * No parameters needed. * * return value: * True is returned as it is a "bool" function. */ bool gameArena::posAlloc(){ srand(time(0)); for (int i = 0; i<50; i++){ ge.mines[i].row = (rand()%14) + 1; ge.mines[i].column = (rand()%14) + 1; } ge.musk.row = (rand()%14) + 1; ge.musk.column = (rand()%14) + 1; ge.roadster.row = (rand()%14) + 1; ge.roadster.column = (rand()%14) + 1; ge.yugo.row = (rand()%14) + 1; ge.yugo.column = (rand()%14) + 1; ge.pinto.row = (rand()%14) + 1; ge.pinto.column = (rand()%14) + 1; ge.user.row = (rand()%14) + 1; ge.user.column = (rand()%14) + 1; board[ge.user.row][ge.user.column] = 'U'; return true; } /* Function Name: setBoardElement * * Function Description: * This function is a "set" function and it actually prints the game elements on the Board. * * Parameters: * The "row" parameter has the row-number (ordinate) of a particular position on the board. * The "col" parameter has the column-number (co-ordinate) of a particular position on the board. * The "c" parameter is the character which is to be printed on the board to represent a game element. * * return value: * There is no return statement. */ void gameArena::setBoardElement(int row, int col, char c){ board[row][col] = c; } /* Function Name: getGE * * Function Description: * This function is a "get" function that gets the pointer to the structure of "gameElements". * * Parameters: * No parameters needed. * * return value: * A pointer to the struct of gameElemts is returned. */ gameElement* gameArena::getGE(){ return gePointer; } #include "StreamReader.h" /** * Reads a specified number of bytes into a buffer. * * \note The buffer provided must remain valid throughout the operation. */ int StreamReader::read(void* buffer, size_t size) { unsigned char* buf = (unsigned char*)(buffer); for (size_t i = 0; i < size; ++i) { buf[i] = mStream[i + mPosition]; } mPosition += size; return size; } /** * Moved read position to \c pos. */ void StreamReader::seek(int pos) { mPosition += pos; } nliao6622/QuantaDB-1 /* Copyright 2021 Futurewei Technologies, 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 "TestUtil.h" #include "TestLog.h" #include "WorkerPool.h" using namespace QDB; using namespace RAMCloud; class WorkerPoolTest : public ::testing::Test { public: TestLog::Enable logEnabler; mutable std::mutex mutex; typedef std::unique_lock Lock; WorkerPool* wp; std::atomic counter; void Increment(std::atomic* c) { Cycles::sleep(taskExecTimeUs); (*c)++; } explicit WorkerPoolTest() { wp = new WorkerPool(numWorkers, minWorkers, highWatermark, lowWatermark); counter = 0; } const uint64_t numWorkers = 16; const uint64_t minWorkers = 2; const uint64_t highWatermark = 10; const uint64_t lowWatermark = 2; const uint64_t taskExecTimeUs = 100; DISALLOW_COPY_AND_ASSIGN(WorkerPoolTest); }; TEST_F(WorkerPoolTest, basic) { Task* task = wp->allocTask(); task->callback = std::bind(&WorkerPoolTest::Increment, this,&counter); wp->enqueue(task); while(!wp->isTaskQueuesEmpty()); EXPECT_EQ(counter, 1); } TEST_F(WorkerPoolTest, multitasks) { uint64_t numIncrTasks = highWatermark; for (uint64_t i = 0; i < numIncrTasks; i++) { Task* task = wp->allocTask(); task->callback = std::bind(&WorkerPoolTest::Increment, this,&counter); wp->enqueue(task); } EXPECT_EQ(wp->getNumActiveWorkers(), 1); while(!wp->isTaskQueuesEmpty()); EXPECT_EQ(counter, numIncrTasks); } TEST_F(WorkerPoolTest, spinup) { uint64_t numIncrTasks = 20; for (uint64_t i = 0; i < numIncrTasks; i++) { Task* task = wp->allocTask(); task->callback = std::bind(&WorkerPoolTest::Increment, this,&counter); wp->enqueue(task); Cycles::sleep(5); } EXPECT_TRUE(wp->getNumActiveWorkers()>= 2); EXPECT_TRUE(wp->getNumIdleWorkers() <= (numWorkers-2)); while(!wp->isTaskQueuesEmpty()); EXPECT_EQ(counter, 20); } TEST_F(WorkerPoolTest, spindown) { uint64_t numIncrTasks = highWatermark+2; for (uint64_t i = 0; i < numIncrTasks; i++) { Task* task = wp->allocTask(); task->callback = std::bind(&WorkerPoolTest::Increment, this,&counter); wp->enqueue(task); Cycles::sleep(5); } while(!wp->isTaskQueuesEmpty()); for (uint64_t i = 0; i < 1; i++) { Task* task = wp->allocTask(); task->callback = std::bind(&WorkerPoolTest::Increment, this,&counter); wp->enqueue(task); Cycles::sleep(5); } EXPECT_TRUE(wp->getNumActiveWorkers() <= minWorkers); EXPECT_TRUE(wp->getNumIdleWorkers()>= (numWorkers-minWorkers)); while(!wp->isTaskQueuesEmpty()); EXPECT_EQ(counter, 13); } TEST_F(WorkerPoolTest, execlatency) { uint64_t numIncrTasks = 1000; uint64_t start = Cycles::rdtsc(); for (uint64_t i = 0; i < numIncrTasks; i++) { Task* task = wp->allocTask(); task->callback = std::bind(&WorkerPoolTest::Increment, this,&counter); wp->enqueue(task); Cycles::sleep(10); } EXPECT_TRUE(wp->getNumActiveWorkers() >= 3); EXPECT_TRUE(wp->getNumIdleWorkers() <= (numWorkers-3)); while(!wp->isTaskQueuesEmpty()); uint64_t end = Cycles::rdtsc(); EXPECT_EQ(counter, numIncrTasks); EXPECT_TRUE(Cycles::toMicroseconds(end-start) < (((taskExecTimeUs+10)*numIncrTasks)>>1)); printf("execution time: %lu vs %lu\n", Cycles::toMicroseconds(end-start), ((taskExecTimeUs+10)*numIncrTasks)>>1); printf("spinup latency avg/max(us): %lu/%lu\n", wp->getAvgSpinupLatencyUs(), wp->getMaxSpinupLatencyUs()); } #include #include using namespace std; void printVector(const std::vector &n) { for (int j = 0; j < n.size(); j++) { cout << "n[" << j << "] = " << n[j] << endl; } } int main() { vector n = {1,2,3,4,5}; printVector(n); return 0; }manasij7479/cbmc #include #include #include #include #include #include #include size_t default_constant_strategy(invariant_programt &program, const size_t max_length) { const typet type(cegis_default_integer_type()); const bv_spect spec(type); add_danger_constant(program, from_integer(spec.max_value().to_ulong(), type)); add_danger_constant(program, from_integer(0u, type)); return std::max(size_t(1u), literals_constant_strategy(program, max_length)); //return 2u + literals_constant_strategy(program, max_length); /*for (size_t i=0; i < max_length; ++i) { const side_effect_expr_nondett value(type); std::string name(NONDET_PREFIX); add_danger_constant(program, name+=integer2string(i), value); } return 2u + max_length + literals_constant_strategy(program, max_length);*/ } /******************************************************************************** * Copyright 2009 The Robotics Group, The Maersk Mc-Kinney Moller Institute, * Faculty of Engineering, University of Southern Denmark * * 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 "DOMTrajectorySaver.hpp" #include #include #include #include #include #include #include #include #include #include #include using namespace rw::core; using namespace rw::math; using namespace rw::loaders; using namespace rw::trajectory; DOMTrajectorySaver::Initializer::Initializer () { static bool done = false; if (!done) { DOMBasisTypes::Initializer init1; DOMTrajectoryLoader::Initializer init2; done = true; } } const DOMTrajectorySaver::Initializer DOMTrajectorySaver::initializer; namespace { template< class T > class ElementCreator { public: static DOMElem::Ptr createElement (const T& element, DOMElem::Ptr parent); }; template<> DOMElem::Ptr ElementCreator< Q >::createElement (const Q& element, DOMElem::Ptr parent) { return DOMBasisTypes::createQ (element, parent); } template<> DOMElem::Ptr ElementCreator< Vector3D<> >::createElement (const Vector3D<>& element, DOMElem::Ptr parent) { return DOMBasisTypes::createVector3D (element, parent); } template<> DOMElem::Ptr ElementCreator< Rotation3D<> >::createElement (const Rotation3D<>& element, DOMElem::Ptr parent) { return DOMBasisTypes::createRotation3D (element, parent); } template<> DOMElem::Ptr ElementCreator< Transform3D<> >::createElement (const Transform3D<>& element, DOMElem::Ptr parent) { return DOMBasisTypes::createTransform3D (element, parent); } template< class T > class Identifiers { public: static const std::string& linearInterpolatorId (); static const std::string& cubicSplineInterpolatorId (); static const std::string& circularInterpolatorId (); }; template<> const std::string& Identifiers< Q >::linearInterpolatorId () { return DOMTrajectoryLoader::idQLinearInterpolator (); } /* template<> const std::string& Identifiers::cubicSplineInterpolatorId() { return DOMTrajectoryLoader::idQCubicSplineInterpolator(); } */ template<> const std::string& Identifiers< Q >::circularInterpolatorId () { const static std::string str = ""; return str; } template<> const std::string& Identifiers< Vector3D<> >::linearInterpolatorId () { return DOMTrajectoryLoader::idV3DLinearInterpolator (); } /* template<> const std::string& Identifiers >::cubicSplineInterpolatorId() { return DOMTrajectoryLoader::idV3DCubicSplineInterpolator(); } */ template<> const std::string& Identifiers< Vector3D<> >::circularInterpolatorId () { return DOMTrajectoryLoader::idV3DCircularInterpolator (); } template<> const std::string& Identifiers< Rotation3D<> >::linearInterpolatorId () { return DOMTrajectoryLoader::idR3DLinearInterpolator (); } /* template<> const std::string& Identifiers >::cubicSplineInterpolatorId() { return DOMTrajectoryLoader::idR3DCubicSplineInterpolator(); } */ template<> const std::string& Identifiers< Rotation3D<> >::circularInterpolatorId () { const static std::string str = ""; return str; } template<> const std::string& Identifiers< Transform3D<> >::linearInterpolatorId () { return DOMTrajectoryLoader::idT3DLinearInterpolator (); } /* template<> const std::string& Identifiers >::cubicSplineInterpolatorId() { return DOMTrajectoryLoader::idT3DCubicSplineInterpolator(); } */ template<> const std::string& Identifiers< Transform3D<> >::circularInterpolatorId () { const static std::string str = ""; return str; } template< class T > DOMElem::Ptr writeInterpolator (const Ptr< Interpolator< T > > interpolator, DOMElem::Ptr parent) { LinearInterpolator< T >* linear = dynamic_cast< LinearInterpolator< T >* > (interpolator.get ()); if (linear != NULL) { T start = linear->getStart (); T end = linear->getEnd (); double duration = linear->duration (); DOMElem::Ptr element = parent->addChild (Identifiers< T >::linearInterpolatorId ()); element->addAttribute (DOMTrajectoryLoader::idDurationAttribute ())->setValue (duration); ElementCreator< T >::createElement (start, element); ElementCreator< T >::createElement (end, element); return element; } CubicSplineInterpolator< T >* cspline = dynamic_cast< CubicSplineInterpolator< T >* > (interpolator.get ()); if (cspline != NULL) { // TODO Once implemented RW_THROW ("Interpolator not supported by DOMTrajectorySaver"); } CircularInterpolator< T >* circular = dynamic_cast< CircularInterpolator< T >* > (interpolator.get ()); if (circular != NULL) { T p1 = circular->getP1 (); T p2 = circular->getP2 (); T p3 = circular->getP3 (); double duration = circular->duration (); DOMElem::Ptr element = parent->addChild (Identifiers< T >::circularInterpolatorId ()); element->addAttribute (DOMTrajectoryLoader::idDurationAttribute ())->setValue (duration); ElementCreator< T >::createElement (p1, parent); ElementCreator< T >::createElement (p2, parent); ElementCreator< T >::createElement (p3, parent); return element; } RW_THROW ("The Trajectory contains an interpolator not supported by DOMTrajectorySaver"); } template< class T > DOMElem::Ptr writeBlend (const Ptr< Blend< T > >& blend, DOMElem::Ptr parent) { const ParabolicBlend< T >* parabolic = dynamic_cast< const ParabolicBlend< T >* > (blend.get ()); if (parabolic != NULL) { double tau = parabolic->tau1 (); DOMElem::Ptr element = parent->addChild (DOMTrajectoryLoader::idParabolicBlend ()); element->addAttribute (DOMTrajectoryLoader::idTauAttribute ())->setValue (tau); return element; } const LloydHaywardBlend< T >* lloydHayward = dynamic_cast< const LloydHaywardBlend< T >* > (blend.get ()); if (lloydHayward != NULL) { double tau = lloydHayward->tau1 (); double kappa = lloydHayward->kappa (); DOMElem::Ptr element = parent->addChild (DOMTrajectoryLoader::idLloydHaywardBlend ()); element->addAttribute (DOMTrajectoryLoader::idTauAttribute ())->setValue (tau); element->addAttribute (DOMTrajectoryLoader::idKappaAttribute ())->setValue (kappa); return element; } RW_THROW ("The Trajectory contains a blend not supported by DOMTrajectorySaver"); } template< class T, class TRAJ > DOMElem::Ptr createDOMDocument (TRAJ& trajectory, const std::string& trajectoryId, DOMParser::Ptr parser) { DOMElem::Ptr doc = parser->getRootElement (); try { DOMElem::Ptr root = doc->addChild (trajectoryId); typedef const InterpolatorTrajectory< T > Traj; Traj* traj = dynamic_cast< Traj* > (&trajectory); if (traj == NULL) { RW_THROW ("Unable to save trajectory which is not a InterpolatorTrajectory"); } for (size_t i = 0; i < traj->getSegmentsCount (); i++) { typedef std::pair< const Ptr< Blend< T > >, const Ptr< Interpolator< T > > > Segment; Segment segment = traj->getSegment (i); if (segment.first != NULL) { writeBlend (segment.first, root); } writeInterpolator (segment.second, root); } } catch (const rw::core::Exception& exp) { throw exp; } catch (...) { RW_THROW ("DOMTrajectoryWriter: Unknown Exception while creating saving path"); } return doc; } template< class T, class TRAJ > bool saveTrajectoryImpl (TRAJ& trajectory, const std::string& trajectoryId, const std::string& filename) { DOMParser::Ptr parser = DOMParser::make (); createDOMDocument< T, TRAJ > (trajectory, trajectoryId, parser); parser->save (filename); return true; } template< class T, class TRAJ > bool saveTrajectoryImpl (TRAJ& trajectory, const std::string& trajectoryId, std::ostream& outstream) { DOMParser::Ptr parser = DOMParser::make (); createDOMDocument< T, TRAJ > (trajectory, trajectoryId, parser); parser->save (outstream); return true; } } // namespace bool DOMTrajectorySaver::save (const rw::trajectory::QTrajectory& trajectory, const std::string& filename) { return saveTrajectoryImpl< Q, const QTrajectory > ( trajectory, DOMTrajectoryLoader::idQTrajectory (), filename); } bool DOMTrajectorySaver::save (const rw::trajectory::Vector3DTrajectory& trajectory, const std::string& filename) { return saveTrajectoryImpl< Vector3D<>, const Vector3DTrajectory > ( trajectory, DOMTrajectoryLoader::idV3DTrajectory (), filename); } bool DOMTrajectorySaver::save (const rw::trajectory::Rotation3DTrajectory& trajectory, const std::string& filename) { return saveTrajectoryImpl< Rotation3D<>, const Rotation3DTrajectory > ( trajectory, DOMTrajectoryLoader::idR3DTrajectory (), filename); } bool DOMTrajectorySaver::save (const rw::trajectory::Transform3DTrajectory& trajectory, const std::string& filename) { return saveTrajectoryImpl< Transform3D<>, const Transform3DTrajectory > ( trajectory, DOMTrajectoryLoader::idT3DTrajectory (), filename); } bool DOMTrajectorySaver::write (const rw::trajectory::QTrajectory& trajectory, std::ostream& outstream) { return saveTrajectoryImpl< Q, const QTrajectory > ( trajectory, DOMTrajectoryLoader::idQTrajectory (), outstream); } bool DOMTrajectorySaver::write (const rw::trajectory::Vector3DTrajectory& trajectory, std::ostream& outstream) { return saveTrajectoryImpl< Vector3D<>, const Vector3DTrajectory > ( trajectory, DOMTrajectoryLoader::idV3DTrajectory (), outstream); } bool DOMTrajectorySaver::write (const rw::trajectory::Rotation3DTrajectory& trajectory, std::ostream& outstream) { return saveTrajectoryImpl< Rotation3D<>, const Rotation3DTrajectory > ( trajectory, DOMTrajectoryLoader::idR3DTrajectory (), outstream); } bool DOMTrajectorySaver::write (const rw::trajectory::Transform3DTrajectory& trajectory, std::ostream& outstream) { return saveTrajectoryImpl< Transform3D<>, const Transform3DTrajectory > ( trajectory, DOMTrajectoryLoader::idT3DTrajectory (), outstream); } #include "stdafx.h" #include "ChimeraVideoWindow.h" ChimeraVideoWindow::ChimeraVideoWindow(): m_bMsgHandled{0} { CoInitialize(nullptr); } ChimeraVideoWindow::~ChimeraVideoWindow() { CoUninitialize(); } BOOL ChimeraVideoWindow::PreTranslateMessage(MSG* pMsg) { return FALSE; } BOOL ChimeraVideoWindow::OnIdle() { return FALSE; } void ChimeraVideoWindow::OnFinalMessage(HWND) { } void ChimeraVideoWindow::onChar(UINT nChar, UINT nRepCnt, UINT nFlags) { } void ChimeraVideoWindow::onPaint(CDCHandle dc) { } void ChimeraVideoWindow::onSize(UINT nType, CSize size) { } void ChimeraVideoWindow::onLButtonDown(UINT nFlags, CPoint point) { } void ChimeraVideoWindow::onLButtonDblClk(UINT nFlags, CPoint point) { } void ChimeraVideoWindow::onDestroy() { PostQuitMessage(0); } int ChimeraVideoWindow::onCreate(LPCREATESTRUCT lpCreateStruct) { auto pLoop = _Module.GetMessageLoop(); pLoop->AddMessageFilter(this); pLoop->AddIdleHandler(this); return 0; } void ChimeraVideoWindow::onMouseMove(UINT nFlags, CPoint point) { } void ChimeraVideoWindow::fullScreen() { // ウィンドウスタイル変更(メニューバーなし、最前面) SetWindowLongPtr(GWL_STYLE, WS_POPUP); SetWindowLongPtr(GWL_EXSTYLE, WS_EX_TOPMOST); // 最大化する ShowWindow(SW_MAXIMIZE); } auto ChimeraVideoWindow::ready() noexcept(false) -> void { this->readyVideo(); } auto ChimeraVideoWindow::ready(const wchar_t* path) noexcept(false) -> void { this->setVideoPath(path); this->ready(); } auto ChimeraVideoWindow::play() const noexcept(false) -> void { this->setVideoWindow(); ChimeraPlayer::play(); } auto ChimeraVideoWindow::setVideoWindow() const noexcept(false) -> void { check(this->video_window_->put_Owner(reinterpret_cast(this->m_hWnd))); check(this->video_window_->put_WindowStyle(WS_CHILD | WS_CLIPSIBLINGS)); check(this->video_window_->put_MessageDrain(reinterpret_cast(this->m_hWnd))); check(this->video_window_->SetWindowForeground(OATRUE)); check(this->video_window_->put_Visible(OATRUE)); } //------------------------------------------------------------------------------------- // xmcolor.cpp - DirectXMath Test Suite // // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkID=615560 //------------------------------------------------------------------------------------- #include "math3.h" using namespace DirectX; HRESULT Test049(LogProxy* pLog) { //XMColorAdjustContrast HRESULT ret = S_OK; COMPARISON c; XMVECTORF32 check={}; XMVECTORF32 v={}; float f; for(int k = 0; k < 15; k++) { f = GetRandomFloat(3.0f) - 1; for(int i = 0; i < 4; i++) { v.v = XMVectorSetByIndex(v,GetRandomFloat(3.0f) - 1,i); check.v = XMVectorSetByIndex(check,((XMVectorGetByIndex(v,i) - .5f) * f) + .5f,i); } check.v = XMVectorSetW(check,XMVectorGetW(v)); XMVECTOR r = XMColorAdjustContrast(v, f); c = CompareXMVECTOR(r,check,4); if(c > WITHIN100EPSILON) { printe ("%s: %f %f %f %f, %f = %f %f %f %f ... %f %f %f %f (%d)\n", TestName, XMVectorGetX(v),XMVectorGetY(v),XMVectorGetZ(v),XMVectorGetW(v), f, XMVectorGetX(r),XMVectorGetY(r),XMVectorGetZ(r),XMVectorGetW(r), XMVectorGetX(check),XMVectorGetY(check),XMVectorGetZ(check),XMVectorGetW(check), c); ret = MATH_FAIL; } else { printi ("%s: %d\n", TestName, c); } } return ret; } HRESULT Test050(LogProxy* pLog) { //XMColorAdjustSaturation HRESULT ret = S_OK; COMPARISON c; XMVECTORF32 check={}; XMVECTORF32 v={}; float f; for(int k = 0; k < 15; k++) { f = GetRandomFloat(3.0f) - 1; int i; for(i = 0; i < 4; i++) { v.v = XMVectorSetByIndex(v,GetRandomFloat(3.0f) - 1,i); } float lum = 0.2125f * XMVectorGetX(v) + 0.7154f * XMVectorGetY(v) + 0.0721f * XMVectorGetZ(v); for(i = 0; i < 3; i++) { check.v = XMVectorSetByIndex(check,((XMVectorGetByIndex(v,i) - lum) * f) + lum,i); } check.v = XMVectorSetW(check,XMVectorGetW(v)); XMVECTOR r = XMColorAdjustSaturation(v, f); c = CompareXMVECTOR(r,check,4); if(c > WITHIN100EPSILON) { printe ("%s: %f %f %f %f, %f = %f %f %f %f ... %f %f %f %f (%d)\n", TestName, XMVectorGetX(v),XMVectorGetY(v),XMVectorGetZ(v),XMVectorGetW(v), f, XMVectorGetX(r),XMVectorGetY(r),XMVectorGetZ(r),XMVectorGetW(r), XMVectorGetX(check),XMVectorGetY(check),XMVectorGetZ(check),XMVectorGetW(check), c); ret = MATH_FAIL; } else { printi ("%s: %d\n", TestName, c); } } return ret; } HRESULT Test051(LogProxy* pLog) { //XMColorEqual XMVECTORF32 v1={}, v2={}; BOOL r, check; int i,j; HRESULT ret = S_OK; for(j = 0; j < 16; j++) { for(i = 0; i < 4; i++) { float ftemp = (float)rand(); v1.v = XMVectorSetByIndex(v1,ftemp,i); v2.v = XMVectorSetByIndex(v2,ftemp,i); } check = TRUE; if(j & 8) { v1.v = XMVectorSetX(v1,XMVectorGetX(v2)+.01f); check = FALSE; } else {} if(j & 4) { v1.v = XMVectorSetY(v1,XMVectorGetY(v2)+.01f); check = FALSE; } else {} if(j & 2) { v1.v = XMVectorSetZ(v1,XMVectorGetZ(v2)+.01f); check = FALSE; } else {} if(j & 1) { v1.v = XMVectorSetW(v1,XMVectorGetW(v2)+.01f); check = FALSE; } else {} r = XMColorEqual(v1,v2); if(r != check) { printe("%s: j(%d) i(%d): %x ... %x\n",TestName,j,i,r,check); ret = MATH_FAIL; } check = TRUE; for(i = 0; i < 4; i++) { float ftemp = (float)rand(); v1.v = XMVectorSetByIndex(v1,ftemp,i); v2.v = XMVectorSetByIndex(v2,ftemp,i); } if(j & 8) { v1.v = XMVectorSetX(v1,XMVectorGetX(v2)-.01f); check = FALSE; } else {} if(j & 4) { v1.v = XMVectorSetY(v1,XMVectorGetY(v2)-.01f); check = FALSE; } else {} if(j & 2) { v1.v = XMVectorSetZ(v1,XMVectorGetZ(v2)-.01f); check = FALSE; } else {} if(j & 1) { v1.v = XMVectorSetW(v1,XMVectorGetW(v2)-.01f); check = FALSE; } else {} r = XMColorEqual(v1,v2); if(r != check) { printe("%s: j(%d) i(%d): %x ... %x\n",TestName,j,i,r,check); ret = MATH_FAIL; } } return ret; } HRESULT Test052(LogProxy* pLog) { //XMColorGreater XMVECTORF32 v1={}, v2={}; BOOL r, check; int i,j; HRESULT ret = S_OK; for(j = 0; j < 16; j++) { for(i = 0; i < 4; i++) { float ftemp = (float)rand(); v1.v = XMVectorSetByIndex(v1,ftemp,i); v2.v = XMVectorSetByIndex(v2,ftemp,i); } if(j & 8) { v1.v = XMVectorSetX(v1,XMVectorGetX(v2)+.01f); } else {} if(j & 4) { v1.v = XMVectorSetY(v1,XMVectorGetY(v2)+.01f); } else {} if(j & 2) { v1.v = XMVectorSetZ(v1,XMVectorGetZ(v2)+.01f); } else {} if(j & 1) { v1.v = XMVectorSetW(v1,XMVectorGetW(v2)+.01f); } else {} r = XMColorGreater(v1,v2); check = (j == 15) ? TRUE : FALSE; if(r != check) { printe("%s: j(%d) i(%d): %x ... %x\n",TestName,j,i,r,check); ret = MATH_FAIL; } check = FALSE; for(i = 0; i < 4; i++) { float ftemp = (float)rand(); v1.v = XMVectorSetByIndex(v1,ftemp,i); v2.v = XMVectorSetByIndex(v2,ftemp,i); } if(j & 8) { v1.v = XMVectorSetX(v1,XMVectorGetX(v2)-.01f); } else {} if(j & 4) { v1.v = XMVectorSetY(v1,XMVectorGetY(v2)-.01f); } else {} if(j & 2) { v1.v = XMVectorSetZ(v1,XMVectorGetZ(v2)-.01f); } else {} if(j & 1) { v1.v = XMVectorSetW(v1,XMVectorGetW(v2)-.01f); } else {} r = XMColorGreater(v1,v2); if(r != check) { printe("%s: j(%d) i(%d): %x ... %x\n",TestName,j,i,r,check); ret = MATH_FAIL; } } return ret; } HRESULT Test053(LogProxy* pLog) { //XMColorGreaterOrEqual XMVECTORF32 v1={}, v2={}; BOOL r, check; int i,j; HRESULT ret = S_OK; for(j = 0; j < 16; j++) { for(i = 0; i < 4; i++) { float ftemp = (float)rand(); v1.v = XMVectorSetByIndex(v1,ftemp,i); v2.v = XMVectorSetByIndex(v2,ftemp,i); } if(j & 8) { v1.v = XMVectorSetX(v1,XMVectorGetX(v2)+.01f); } else {} if(j & 4) { v1.v = XMVectorSetY(v1,XMVectorGetY(v2)+.01f); } else {} if(j & 2) { v1.v = XMVectorSetZ(v1,XMVectorGetZ(v2)+.01f); } else {} if(j & 1) { v1.v = XMVectorSetW(v1,XMVectorGetW(v2)+.01f); } else {} r = XMColorGreaterOrEqual(v1,v2); check = TRUE; if(r != check) { printe("%s: j(%d) i(%d): %x ... %x\n",TestName,j,i,r,check); ret = MATH_FAIL; } for(i = 0; i < 4; i++) { float ftemp = (float)rand(); v1.v = XMVectorSetByIndex(v1,ftemp,i); v2.v = XMVectorSetByIndex(v2,ftemp,i); } if(j & 8) { v1.v = XMVectorSetX(v1,XMVectorGetX(v2)-.01f); } else {} if(j & 4) { v1.v = XMVectorSetY(v1,XMVectorGetY(v2)-.01f); } else {} if(j & 2) { v1.v = XMVectorSetZ(v1,XMVectorGetZ(v2)-.01f); } else {} if(j & 1) { v1.v = XMVectorSetW(v1,XMVectorGetW(v2)-.01f); } else {} check = (j) ? FALSE : TRUE; r = XMColorGreaterOrEqual(v1,v2); if(r != check) { printe("%s: j(%d) i(%d): %x ... %x\n",TestName,j,i,r,check); ret = MATH_FAIL; } } return ret; } HRESULT Test054(LogProxy* pLog) { //XMColorIsInfinite HRESULT ret = S_OK; static const float f[] = {_INF, -_INF, _Q_NAN, 1,-1}; int r,g,b,a; XMVECTOR col; BOOL res, check; for(r = 0; r < countof(f); r++) { for(g = 0; g < countof(f); g++) { printi("\n%s: ", TestName); for(b = 0; b < countof(f); b++) { for(a = 0; a < countof(f); a++) { col = XMVectorSet(f[r],f[g],f[b],f[a]); check = (r < 2 || g < 2 || b < 2 || a < 2) ? TRUE : FALSE; res = XMColorIsInfinite(col); if(res != check) { printe("\n%s: %f %f %f %f = %d ... %d\n", TestName, XMVectorGetX(col),XMVectorGetY(col),XMVectorGetZ(col),XMVectorGetW(col), res, check); ret = MATH_FAIL; } else { //printi("%d ", res); } } } } } printi("\n"); return ret; } ISNAN_TEST_BEGIN HRESULT Test055(LogProxy* pLog) { //XMColorIsNaN HRESULT ret = S_OK; static const float f[] = {_Q_NAN, _NAN, _INF, 1,-1,605,1.0f-(1.0f/(65536.0f*32768.0f))}; int r,g,b,a; XMVECTOR col; BOOL res, check; for(r = 0; r < countof(f); r++) { for(g = 0; g < countof(f); g++) { printi("\n%s: ", TestName); for(b = 0; b < countof(f); b++) { for(a = 0; a < countof(f); a++) { col = XMVectorSet(f[r],f[g],f[b],f[a]); check = (r < 2 || g < 2 || b < 2 || a < 2) ? TRUE : FALSE; res = XMColorIsNaN(col); if(res != check) { printe("\n%s: %f %f %f %f = %d ... %d\n", TestName,XMVectorGetX(col),XMVectorGetY(col),XMVectorGetZ(col),XMVectorGetW(col), res, check); ret = MATH_FAIL; } else { //printi("%d ", res); } } } } } printi("\n"); return ret; } ISNAN_TEST_END HRESULT Test056(LogProxy* pLog) { //XMColorLess XMVECTORF32 v1={}, v2={}; BOOL r, check; int i,j; HRESULT ret = S_OK; for(j = 0; j < 16; j++) { for(i = 0; i < 4; i++) { float ftemp = (float)rand(); v1.v = XMVectorSetByIndex(v1,ftemp,i); v2.v = XMVectorSetByIndex(v2,ftemp,i); } if(j & 8) { v1.v = XMVectorSetX(v1,XMVectorGetX(v2)+.01f); } else {} if(j & 4) { v1.v = XMVectorSetY(v1,XMVectorGetY(v2)+.01f); } else {} if(j & 2) { v1.v = XMVectorSetZ(v1,XMVectorGetZ(v2)+.01f); } else {} if(j & 1) { v1.v = XMVectorSetW(v1,XMVectorGetW(v2)+.01f); } else {} r = XMColorLess(v1,v2); check = FALSE; if(r != check) { printe("%s: j(%d) i(%d): %x ... %x\n",TestName,j,i,r,check); ret = MATH_FAIL; } for(i = 0; i < 4; i++) { float ftemp = (float)rand(); v1.v = XMVectorSetByIndex(v1,ftemp,i); v2.v = XMVectorSetByIndex(v2,ftemp,i); } if(j & 8) { v1.v = XMVectorSetX(v1,XMVectorGetX(v2)-.01f); } else {} if(j & 4) { v1.v = XMVectorSetY(v1,XMVectorGetY(v2)-.01f); } else {} if(j & 2) { v1.v = XMVectorSetZ(v1,XMVectorGetZ(v2)-.01f); } else {} if(j & 1) { v1.v = XMVectorSetW(v1,XMVectorGetW(v2)-.01f); } else {} check = (j == 15) ? TRUE : FALSE; r = XMColorLess(v1,v2); if(r != check) { printe("%s: j(%d) i(%d): %x ... %x\n",TestName,j,i,r,check); ret = MATH_FAIL; } } return ret; } HRESULT Test057(LogProxy* pLog) { //XMColorLessOrEqual XMVECTORF32 v1={}, v2={}; BOOL r, check; int i,j; HRESULT ret = S_OK; for(j = 0; j < 16; j++) { for(i = 0; i < 4; i++) { float ftemp = (float)rand(); v1.v = XMVectorSetByIndex(v1,ftemp,i); v2.v = XMVectorSetByIndex(v2,ftemp,i); } if(j & 8) { v1.v = XMVectorSetX(v1,XMVectorGetX(v2)+.01f); } else {} if(j & 4) { v1.v = XMVectorSetY(v1,XMVectorGetY(v2)+.01f); } else {} if(j & 2) { v1.v = XMVectorSetZ(v1,XMVectorGetZ(v2)+.01f); } else {} if(j & 1) { v1.v = XMVectorSetW(v1,XMVectorGetW(v2)+.01f); } else {} r = XMColorLessOrEqual(v1,v2); check = (j) ? FALSE: TRUE; if(r != check) { printe("%s: j(%d) i(%d): %x ... %x\n",TestName,j,i,r,check); ret = MATH_FAIL; } for(i = 0; i < 4; i++) { float ftemp = (float)rand(); v1.v = XMVectorSetByIndex(v1,ftemp,i); v2.v = XMVectorSetByIndex(v2,ftemp,i); } if(j & 8) { v1.v = XMVectorSetX(v1,XMVectorGetX(v2)-.01f); } else {} if(j & 4) { v1.v = XMVectorSetY(v1,XMVectorGetY(v2)-.01f); } else {} if(j & 2) { v1.v = XMVectorSetZ(v1,XMVectorGetZ(v2)-.01f); } else {} if(j & 1) { v1.v = XMVectorSetW(v1,XMVectorGetW(v2)-.01f); } else {} check = TRUE; r = XMColorLessOrEqual(v1,v2); if(r != check) { printe("%s: j(%d) i(%d): %x ... %x\n",TestName,j,i,r,check); ret = MATH_FAIL; } } return ret; } HRESULT Test058(LogProxy* pLog) { //XMColorModulate HRESULT ret = S_OK; COMPARISON c; XMVECTORF32 check={}; XMVECTORF32 v1={}, v2={}; for(int i = 0; i < 10; i++) { for(int j = 0; j < 4; j++) { v1.v = XMVectorSetByIndex(v1,(float)rand() / 100.f,j); v2.v = XMVectorSetByIndex(v2,(float)rand() / 100.f,j); check.v = XMVectorSetByIndex(check,XMVectorGetByIndex(v1,j) * XMVectorGetByIndex(v2,j),j); } XMVECTOR r = XMColorModulate(v1, v2); c = CompareXMVECTOR(r,check,4); if(c > WITHIN2EPSILON) { printe ("%s: %f %f %f %f, %f %f %f %f = %f %f %f %f ... %f %f %f %f (%d)\n", TestName, XMVectorGetX(v1),XMVectorGetY(v1),XMVectorGetZ(v1),XMVectorGetW(v1), XMVectorGetX(v2),XMVectorGetY(v2),XMVectorGetZ(v2),XMVectorGetW(v2), XMVectorGetX(r),XMVectorGetY(r),XMVectorGetZ(r),XMVectorGetW(r), XMVectorGetX(check),XMVectorGetY(check),XMVectorGetZ(check),XMVectorGetW(check), c); ret = MATH_FAIL; } else { printi ("%s: %d\n", TestName, c); } } return ret; } HRESULT Test059(LogProxy* pLog) { //XMColorNegative const XMVECTORF32 v[] = { {{1,.5,0,.004f}}, {{0,.5,1,.004f}}, {{.3125,.75,100,.8f}},{{.6875,.25,-99,.8f}}, {{.9f,.1f,.25,.12f}},{{.1f,.9f,.75,.12f}} }; HRESULT ret = S_OK; XMVECTOR r; for(int i =0 ; i < sizeof(v) / sizeof(v[0]); i += 2) { COMPARISON c = CompareXMVECTOR(r = XMColorNegative(v[i]),v[i+1],4); if(c > WITHIN2EPSILON) { printe("%s: %f %f %f %f: %f %f %f %f ... %f %f %f %f (%d)\n", TestName, XMVectorGetX(v[i]),XMVectorGetY(v[i]),XMVectorGetZ(v[i]),XMVectorGetW(v[i]), XMVectorGetX(r),XMVectorGetY(r),XMVectorGetZ(r),XMVectorGetW(r), XMVectorGetX(v[i+1]),XMVectorGetY(v[i+1]),XMVectorGetZ(v[i+1]),XMVectorGetW(v[i+1]),c); ret = MATH_FAIL; } } return ret; } HRESULT Test060(LogProxy* pLog) { //XMColorNotEqual XMVECTORF32 v1={}, v2={}; BOOL r, check; int i,j; HRESULT ret = S_OK; for(j = 0; j < 16; j++) { for(i = 0; i < 4; i++) { float ftemp = (float)rand(); v1.v = XMVectorSetByIndex(v1,ftemp,i); v2.v = XMVectorSetByIndex(v2,ftemp,i); } if(j & 8) { v1.v = XMVectorSetX(v1,XMVectorGetX(v2)+.01f); } else {} if(j & 4) { v1.v = XMVectorSetY(v1,XMVectorGetY(v2)+.01f); } else {} if(j & 2) { v1.v = XMVectorSetZ(v1,XMVectorGetZ(v2)+.01f); } else {} if(j & 1) { v1.v = XMVectorSetW(v1,XMVectorGetW(v2)+.01f); } else {} r = XMColorNotEqual(v1,v2); check = (j) ? TRUE : FALSE; if(r != check) { printe("%s: j(%d) i(%d): %x ... %x\n",TestName,j,i,r,check); ret = MATH_FAIL; } for(i = 0; i < 4; i++) { float ftemp = (float)rand(); v1.v = XMVectorSetByIndex(v1,ftemp,i); v2.v = XMVectorSetByIndex(v2,ftemp,i); } if(j & 8) { v1.v = XMVectorSetX(v1,XMVectorGetX(v2)-.01f); } else {} if(j & 4) { v1.v = XMVectorSetY(v1,XMVectorGetY(v2)-.01f); } else {} if(j & 2) { v1.v = XMVectorSetZ(v1,XMVectorGetZ(v2)-.01f); } else {} if(j & 1) { v1.v = XMVectorSetW(v1,XMVectorGetW(v2)-.01f); } else {} check = (j) ? TRUE : FALSE; r = XMColorNotEqual(v1,v2); if(r != check) { printe("%s: j(%d) i(%d): %x ... %x\n",TestName,j,i,r,check); ret = MATH_FAIL; } } return ret; } static void rgb2hsl( float r, float g, float b, float &h, float &s, float &l ) { float rgb_min = std::min( r, std::min(g, b) ); float rgb_max = std::max( r, std::max(g, b) ); l = (rgb_min + rgb_max) / 2.0f; float d = rgb_max - rgb_min; if ( fabs(d) < TESTEPSILON ) { h = s = 0; } else { s = ( l < 0.5f ) ? (d/(rgb_min+rgb_max)) : (d/(2.f - rgb_min - rgb_max)); if ( r == rgb_max ) h = (g - b) / d; else if ( g == rgb_max ) h = 2.0f + (b-r) / d; else h = 4.0f + (r-g) / d; h /= 6.f; if ( h < 0 ) h += 1.f; } } HRESULT Test603(LogProxy* pLog) { // XMColorRGBToHSL/XMColorHSLToRGB HRESULT ret = S_OK; XMVECTOR colors[11]; colors[0] = Colors::Violet; colors[1] = Colors::Plum; colors[2] = Colors::Silver; colors[3] = Colors::Black; colors[4] = Colors::White; colors[5] = Colors::Red; colors[6] = Colors::Green; colors[7] = Colors::Blue; colors[8] = Colors::Magenta; colors[9] = Colors::Cyan; colors[10] = Colors::Yellow; for(uint32_t i=0; i < sizeof(colors)/sizeof(XMVECTOR); ++i) { XMVECTOR color = colors[i]; XMVECTOR hsl = XMColorRGBToHSL( color ); float h, s, l; rgb2hsl( XMVectorGetX(color), XMVectorGetY(color), XMVectorGetZ(color), h, s, l ); XMVECTOR chk = XMVectorSet( h, s, l, 1.0f ); COMPARISON c = CompareXMVECTOR( hsl, chk, 4 ); if(c > WITHIN10EPSILON) { printe("%s: failed RGB to HSL for %d - %f %f %f %f: %f %f %f %f ... %f %f %f %f (%d)\n",TestName,i, XMVectorGetX(color),XMVectorGetY(color),XMVectorGetZ(color),XMVectorGetW(color), XMVectorGetX(hsl),XMVectorGetY(hsl),XMVectorGetZ(hsl),XMVectorGetW(hsl), XMVectorGetX(chk),XMVectorGetY(chk),XMVectorGetZ(chk),XMVectorGetW(chk), c); ret = MATH_FAIL; } XMVECTOR rgb = XMColorHSLToRGB( hsl ); c = CompareXMVECTOR( rgb, color, 4 ); if(c > WITHIN10EPSILON) { printe("%s: failed HSL to RGB %d - %f %f %f %f: %f %f %f %f ... %f %f %f %f (%d)\n",TestName,i, XMVectorGetX(hsl),XMVectorGetY(hsl),XMVectorGetZ(hsl),XMVectorGetW(hsl), XMVectorGetX(rgb),XMVectorGetY(rgb),XMVectorGetZ(rgb),XMVectorGetW(rgb), XMVectorGetX(color),XMVectorGetY(color),XMVectorGetZ(color),XMVectorGetW(color), c); ret = MATH_FAIL; } XMVECTOR rgbo = XMVectorSetW( color, 0.5f ); hsl = XMColorRGBToHSL( rgbo ); chk = XMVectorSetW( chk, 0.5f ); c = CompareXMVECTOR( hsl, chk, 4 ); if(c > WITHIN10EPSILON) { printe("%s: failed RGB to HSL A 0.5 for %d - %f %f %f %f: %f %f %f %f ... %f %f %f %f (%d)\n",TestName,i, XMVectorGetX(rgbo),XMVectorGetY(rgbo),XMVectorGetZ(rgbo),XMVectorGetW(rgbo), XMVectorGetX(hsl),XMVectorGetY(hsl),XMVectorGetZ(hsl),XMVectorGetW(hsl), XMVectorGetX(chk),XMVectorGetY(chk),XMVectorGetZ(chk),XMVectorGetW(chk), c); ret = MATH_FAIL; } rgb = XMColorHSLToRGB( hsl ); c = CompareXMVECTOR( rgb, rgbo, 4 ); if(c > WITHIN10EPSILON) { printe("%s: failed HSL to RGB A 0.5 %d - %f %f %f %f: %f %f %f %f ... %f %f %f %f (%d)\n",TestName,i, XMVectorGetX(hsl),XMVectorGetY(hsl),XMVectorGetZ(hsl),XMVectorGetW(hsl), XMVectorGetX(rgb),XMVectorGetY(rgb),XMVectorGetZ(rgb),XMVectorGetW(rgb), XMVectorGetX(rgbo),XMVectorGetY(rgbo),XMVectorGetZ(rgbo),XMVectorGetW(rgbo), c); ret = MATH_FAIL; } } return ret; } void rgb2hsv( float r, float g, float b, float &h, float &s, float &v ) { float rgb_min = std::min( r, std::min(g, b) ); float rgb_max = std::max( r, std::max(g, b) ); v = rgb_max; if ( fabs(v) < TESTEPSILON ) { h = s = 0; } else { r /= v; g /= v; b /= v; rgb_min = std::min( r, std::min(g, b) ); rgb_max = std::max( r, std::max(g, b) ); s = rgb_max - rgb_min; if( fabs(s) < TESTEPSILON ) { h = 0; } else { r = (r - rgb_min) / (rgb_max - rgb_min); g = (g - rgb_min) / (rgb_max - rgb_min); b = (b - rgb_min) / (rgb_max - rgb_min); rgb_min = std::min( r, std::min(g, b) ); rgb_max = std::max( r, std::max(g, b) ); if ( fabs( rgb_max - r ) < TESTEPSILON ) { h = 60.f*(g - b); if ( h < 0 ) h += 360.0f; } else if ( fabs( rgb_max - g ) < TESTEPSILON ) { h = 120.f + 60.f*(b - r); } else { h = 240.f + 60.f*(r - g); } h /= 360.f; } } } HRESULT Test604(LogProxy* pLog) { // XMColorRGBToHSV/XMColorHSVToRGB HRESULT ret = S_OK; XMVECTOR colors[11]; colors[0] = Colors::DodgerBlue; colors[1] = Colors::Indigo; colors[2] = Colors::Silver; colors[3] = Colors::Black; colors[4] = Colors::White; colors[5] = Colors::Red; colors[6] = Colors::Green; colors[7] = Colors::Blue; colors[8] = Colors::Magenta; colors[9] = Colors::Cyan; colors[10] = Colors::Yellow; for(uint32_t i=0; i < sizeof(colors)/sizeof(XMVECTOR); ++i) { XMVECTOR color = colors[i]; XMVECTOR hsv = XMColorRGBToHSV( color ); float h, s, v; rgb2hsv( XMVectorGetX(color), XMVectorGetY(color), XMVectorGetZ(color), h, s, v ); XMVECTOR chk = XMVectorSet( h, s, v, 1.0f ); COMPARISON c = CompareXMVECTOR( hsv, chk, 4 ); if(c > WITHIN10EPSILON) { printe("%s: failed RGB to HSV for %d - %f %f %f %f: %f %f %f %f ... %f %f %f %f (%d)\n",TestName,i, XMVectorGetX(color),XMVectorGetY(color),XMVectorGetZ(color),XMVectorGetW(color), XMVectorGetX(hsv),XMVectorGetY(hsv),XMVectorGetZ(hsv),XMVectorGetW(hsv), XMVectorGetX(chk),XMVectorGetY(chk),XMVectorGetZ(chk),XMVectorGetW(chk), c); ret = MATH_FAIL; } XMVECTOR rgb = XMColorHSVToRGB( hsv ); c = CompareXMVECTOR( rgb, color, 4 ); if(c > WITHIN10EPSILON) { printe("%s: failed HSV to RGB for %d - %f %f %f %f: %f %f %f %f ... %f %f %f %f (%d)\n",TestName,i, XMVectorGetX(hsv),XMVectorGetY(hsv),XMVectorGetZ(hsv),XMVectorGetW(hsv), XMVectorGetX(rgb),XMVectorGetY(rgb),XMVectorGetZ(rgb),XMVectorGetW(rgb), XMVectorGetX(color),XMVectorGetY(color),XMVectorGetZ(color),XMVectorGetW(color), c); ret = MATH_FAIL; } XMVECTOR rgbo = XMVectorSetW( color, 0.5f ); hsv = XMColorRGBToHSV( rgbo ); chk = XMVectorSetW( chk, 0.5f ); c = CompareXMVECTOR( hsv, chk, 4 ); if(c > WITHIN10EPSILON) { printe("%s: failed RGB to HSV A 0.5 for %d - %f %f %f %f: %f %f %f %f ... %f %f %f %f (%d)\n",TestName,i, XMVectorGetX(rgbo),XMVectorGetY(rgbo),XMVectorGetZ(rgbo),XMVectorGetW(rgbo), XMVectorGetX(hsv),XMVectorGetY(hsv),XMVectorGetZ(hsv),XMVectorGetW(hsv), XMVectorGetX(chk),XMVectorGetY(chk),XMVectorGetZ(chk),XMVectorGetW(chk), c); ret = MATH_FAIL; } rgb = XMColorHSVToRGB( hsv ); c = CompareXMVECTOR( rgb, rgbo, 4 ); if(c > WITHIN10EPSILON) { printe("%s: failed HSV to RGB A 0.5 for %d - %f %f %f %f: %f %f %f %f ... %f %f %f %f (%d)\n",TestName,i, XMVectorGetX(hsv),XMVectorGetY(hsv),XMVectorGetZ(hsv),XMVectorGetW(hsv), XMVectorGetX(rgb),XMVectorGetY(rgb),XMVectorGetZ(rgb),XMVectorGetW(rgb), XMVectorGetX(rgbo),XMVectorGetY(rgbo),XMVectorGetZ(rgbo),XMVectorGetW(rgbo), c); ret = MATH_FAIL; } } return ret; } void rgb2yuv( float r, float g, float b, float &y, float &u, float &v ) { y = 0.299f*r + 0.587f*g + 0.114f*b; u = 0.436f*b - 0.14713f*r - 0.28886f*g; v = 0.615f*r - 0.51499f*g - 0.10001f*b; } HRESULT Test605(LogProxy* pLog) { // XMColorRGBToYUV/XMColorYUVToRGB HRESULT ret = S_OK; XMVECTOR colors[11]; colors[0] = Colors::PaleGreen; colors[1] = Colors::RoyalBlue; colors[2] = Colors::Silver; colors[3] = Colors::Black; colors[4] = Colors::White; colors[5] = Colors::Red; colors[6] = Colors::Green; colors[7] = Colors::Blue; colors[8] = Colors::Magenta; colors[9] = Colors::Cyan; colors[10] = Colors::Yellow; for(uint32_t i=0; i < sizeof(colors)/sizeof(XMVECTOR); ++i) { XMVECTOR color = colors[i]; XMVECTOR yuv = XMColorRGBToYUV( color ); float y, u, v; rgb2yuv( XMVectorGetX(color), XMVectorGetY(color), XMVectorGetZ(color), y, u, v ); XMVECTOR chk = XMVectorSet( y, u, v, 1.0f ); COMPARISON c = CompareXMVECTOR( yuv, chk, 4 ); if(c > WITHINBIGEPSILON) { printe("%s: failed RGB to YUV for %d - %f %f %f %f: %f %f %f %f ... %f %f %f %f (%d)\n",TestName,i, XMVectorGetX(color),XMVectorGetY(color),XMVectorGetZ(color),XMVectorGetW(color), XMVectorGetX(yuv),XMVectorGetY(yuv),XMVectorGetZ(yuv),XMVectorGetW(yuv), XMVectorGetX(chk),XMVectorGetY(chk),XMVectorGetZ(chk),XMVectorGetW(chk), c); ret = MATH_FAIL; } XMVECTOR rgb = XMColorYUVToRGB( yuv ); c = CompareXMVECTOR( rgb, color, 4 ); if(c > WITHINBIGEPSILON) { printe("%s: failed YUV to RGB for %d - %f %f %f %f: %f %f %f %f ... %f %f %f %f (%d)\n",TestName,i, XMVectorGetX(yuv),XMVectorGetY(yuv),XMVectorGetZ(yuv),XMVectorGetW(yuv), XMVectorGetX(rgb),XMVectorGetY(rgb),XMVectorGetZ(rgb),XMVectorGetW(rgb), XMVectorGetX(color),XMVectorGetY(color),XMVectorGetZ(color),XMVectorGetW(color), c); ret = MATH_FAIL; } XMVECTOR rgbo = XMVectorSetW( color, 0.5f ); yuv = XMColorRGBToYUV( rgbo ); chk = XMVectorSetW( chk, 0.5f ); c = CompareXMVECTOR( yuv, chk, 4 ); if(c > WITHINBIGEPSILON) { printe("%s: failed RGB to YUV A 0.5 for %d - %f %f %f %f: %f %f %f %f ... %f %f %f %f (%d)\n",TestName,i, XMVectorGetX(rgbo),XMVectorGetY(rgbo),XMVectorGetZ(rgbo),XMVectorGetW(rgbo), XMVectorGetX(yuv),XMVectorGetY(yuv),XMVectorGetZ(yuv),XMVectorGetW(yuv), XMVectorGetX(chk),XMVectorGetY(chk),XMVectorGetZ(chk),XMVectorGetW(chk), c); ret = MATH_FAIL; } rgb = XMColorYUVToRGB( yuv ); c = CompareXMVECTOR( rgb, rgbo, 4 ); if(c > WITHINBIGEPSILON) { printe("%s: failed YUV to RGB A 0.5 for %d - %f %f %f %f: %f %f %f %f ... %f %f %f %f (%d)\n",TestName,i, XMVectorGetX(yuv),XMVectorGetY(yuv),XMVectorGetZ(yuv),XMVectorGetW(yuv), XMVectorGetX(rgb),XMVectorGetY(rgb),XMVectorGetZ(rgb),XMVectorGetW(rgb), XMVectorGetX(rgbo),XMVectorGetY(rgbo),XMVectorGetZ(rgbo),XMVectorGetW(rgbo), c); ret = MATH_FAIL; } } return ret; } void rgb2yuv709( float r, float g, float b, float &y, float &u, float &v ) { y = 0.2126f*r + 0.7152f*g + 0.0722f*b; u = 0.4351f*b - 0.0997f*r - 0.3354f*g; v = 0.6150f*r - 0.5586f*g - 0.0564f*b; } HRESULT Test606(LogProxy* pLog) { // XMColorRGBToYUV_HD/XMColorYUVToRGB_HD HRESULT ret = S_OK; XMVECTOR colors[11]; colors[0] = Colors::PaleGreen; colors[1] = Colors::RoyalBlue; colors[2] = Colors::Silver; colors[3] = Colors::Black; colors[4] = Colors::White; colors[5] = Colors::Red; colors[6] = Colors::Green; colors[7] = Colors::Blue; colors[8] = Colors::Magenta; colors[9] = Colors::Cyan; colors[10] = Colors::Yellow; for(uint32_t i=0; i < sizeof(colors)/sizeof(XMVECTOR); ++i) { XMVECTOR color = colors[i]; XMVECTOR yuv = XMColorRGBToYUV_HD( color ); float y, u, v; rgb2yuv709( XMVectorGetX(color), XMVectorGetY(color), XMVectorGetZ(color), y, u, v ); XMVECTOR chk = XMVectorSet( y, u, v, 1.0f ); COMPARISON c = CompareXMVECTOR( yuv, chk, 4 ); if(c > WITHINBIGEPSILON) { printe("%s: failed RGB to YUV709 for %d - %f %f %f %f: %f %f %f %f ... %f %f %f %f (%d)\n",TestName,i, XMVectorGetX(color),XMVectorGetY(color),XMVectorGetZ(color),XMVectorGetW(color), XMVectorGetX(yuv),XMVectorGetY(yuv),XMVectorGetZ(yuv),XMVectorGetW(yuv), XMVectorGetX(chk),XMVectorGetY(chk),XMVectorGetZ(chk),XMVectorGetW(chk), c); ret = MATH_FAIL; } XMVECTOR rgb = XMColorYUVToRGB_HD( yuv ); c = CompareXMVECTOR( rgb, color, 4 ); if(c > WITHINBIGEPSILON) { printe("%s: failed YUV709 to RGB for %d - %f %f %f %f: %f %f %f %f ... %f %f %f %f (%d)\n",TestName,i, XMVectorGetX(yuv),XMVectorGetY(yuv),XMVectorGetZ(yuv),XMVectorGetW(yuv), XMVectorGetX(rgb),XMVectorGetY(rgb),XMVectorGetZ(rgb),XMVectorGetW(rgb), XMVectorGetX(color),XMVectorGetY(color),XMVectorGetZ(color),XMVectorGetW(color), c); ret = MATH_FAIL; } XMVECTOR rgbo = XMVectorSetW( color, 0.5f ); yuv = XMColorRGBToYUV_HD( rgbo ); chk = XMVectorSetW( chk, 0.5f ); c = CompareXMVECTOR( yuv, chk, 4 ); if(c > WITHINBIGEPSILON) { printe("%s: failed RGB to YUV709 A 0.5 for %d - %f %f %f %f: %f %f %f %f ... %f %f %f %f (%d)\n",TestName,i, XMVectorGetX(rgbo),XMVectorGetY(rgbo),XMVectorGetZ(rgbo),XMVectorGetW(rgbo), XMVectorGetX(yuv),XMVectorGetY(yuv),XMVectorGetZ(yuv),XMVectorGetW(yuv), XMVectorGetX(chk),XMVectorGetY(chk),XMVectorGetZ(chk),XMVectorGetW(chk), c); ret = MATH_FAIL; } rgb = XMColorYUVToRGB_HD( yuv ); c = CompareXMVECTOR( rgb, rgbo, 4 ); if(c > WITHINBIGEPSILON) { printe("%s: failed YUV709 to RGB A 0.5 for %d - %f %f %f %f: %f %f %f %f ... %f %f %f %f (%d)\n",TestName,i, XMVectorGetX(yuv),XMVectorGetY(yuv),XMVectorGetZ(yuv),XMVectorGetW(yuv), XMVectorGetX(rgb),XMVectorGetY(rgb),XMVectorGetZ(rgb),XMVectorGetW(rgb), XMVectorGetX(rgbo),XMVectorGetY(rgbo),XMVectorGetZ(rgbo),XMVectorGetW(rgbo), c); ret = MATH_FAIL; } } return ret; } void rgb2xyz( float r, float g, float b, float& x, float& y, float& z ) { x = (0.4887180f*r + 0.3106803f*g + 0.2006017f*b) / 0.17697f; y = (0.1762044f*r + 0.8129847f*g + 0.0108109f*b) / 0.17697f; z = (0.0102048f*g + 0.9897952f*b) / 0.17697f; } HRESULT Test607(LogProxy* pLog) { // XMColorRGBToXYZ/XMColorXYZToRGB HRESULT ret = S_OK; XMVECTOR colors[11]; colors[0] = Colors::DarkSalmon; colors[1] = Colors::DodgerBlue; colors[2] = Colors::Silver; colors[3] = Colors::Black; colors[4] = Colors::White; colors[5] = Colors::Red; colors[6] = Colors::Green; colors[7] = Colors::Blue; colors[8] = Colors::Magenta; colors[9] = Colors::Cyan; colors[10] = Colors::Yellow; for(uint32_t i=0; i < sizeof(colors)/sizeof(XMVECTOR); ++i) { XMVECTOR color = colors[i]; XMVECTOR xyz = XMColorRGBToXYZ( color ); float x, y, z; rgb2xyz( XMVectorGetX(color), XMVectorGetY(color), XMVectorGetZ(color), x, y, z ); XMVECTOR chk = XMVectorSet( x, y, z, 1.0f ); COMPARISON c = CompareXMVECTOR( xyz, chk, 4 ); if(c > WITHIN10EPSILON) { printe("%s: failed RGB to XYZ for %d - %f %f %f %f: %f %f %f %f ... %f %f %f %f (%d)\n",TestName,i, XMVectorGetX(color),XMVectorGetY(color),XMVectorGetZ(color),XMVectorGetW(color), XMVectorGetX(xyz),XMVectorGetY(xyz),XMVectorGetZ(xyz),XMVectorGetW(xyz), XMVectorGetX(chk),XMVectorGetY(chk),XMVectorGetZ(chk),XMVectorGetW(chk), c); ret = MATH_FAIL; } XMVECTOR rgb = XMColorXYZToRGB( xyz ); c = CompareXMVECTOR( rgb, color, 4 ); if(c > WITHIN10EPSILON) { printe("%s: failed XYZ to RGB for %d - %f %f %f %f: %f %f %f %f ... %f %f %f %f (%d)\n",TestName,i, XMVectorGetX(xyz),XMVectorGetY(xyz),XMVectorGetZ(xyz),XMVectorGetW(xyz), XMVectorGetX(rgb),XMVectorGetY(rgb),XMVectorGetZ(rgb),XMVectorGetW(rgb), XMVectorGetX(color),XMVectorGetY(color),XMVectorGetZ(color),XMVectorGetW(color), c); ret = MATH_FAIL; } XMVECTOR rgbo = XMVectorSetW( color, 0.5f ); xyz = XMColorRGBToXYZ( rgbo ); chk = XMVectorSetW( chk, 0.5f ); c = CompareXMVECTOR( xyz, chk, 4 ); if(c > WITHIN10EPSILON) { printe("%s: failed RGB to XYZ A 0.5 for %d - %f %f %f %f: %f %f %f %f ... %f %f %f %f (%d)\n",TestName,i, XMVectorGetX(rgbo),XMVectorGetY(rgbo),XMVectorGetZ(rgbo),XMVectorGetW(rgbo), XMVectorGetX(xyz),XMVectorGetY(xyz),XMVectorGetZ(xyz),XMVectorGetW(xyz), XMVectorGetX(chk),XMVectorGetY(chk),XMVectorGetZ(chk),XMVectorGetW(chk), c); ret = MATH_FAIL; } rgb = XMColorXYZToRGB( xyz ); c = CompareXMVECTOR( rgb, rgbo, 4 ); if(c > WITHIN10EPSILON) { printe("%s: failed XYZ to RGB A 0.5 for %d - %f %f %f %f: %f %f %f %f ... %f %f %f %f (%d)\n",TestName,i, XMVectorGetX(xyz),XMVectorGetY(xyz),XMVectorGetZ(xyz),XMVectorGetW(xyz), XMVectorGetX(rgb),XMVectorGetY(rgb),XMVectorGetZ(rgb),XMVectorGetW(rgb), XMVectorGetX(rgbo),XMVectorGetY(rgbo),XMVectorGetZ(rgbo),XMVectorGetW(rgbo), c); ret = MATH_FAIL; } } return ret; } void srgb2xyz( float r, float g, float b, float& x, float& y, float& z ) { float rl = (r <= 0.04045f) ? (r / 12.92f) : powf( (r + 0.055f) / (1.055f), 2.4f ); float gl = (g <= 0.04045f) ? (g / 12.92f) : powf( (g + 0.055f) / (1.055f), 2.4f ); float bl = (b <= 0.04045f) ? (b / 12.92f) : powf( (b + 0.055f) / (1.055f), 2.4f ); x = 0.4124f*rl + 0.3576f*gl + 0.1805f*bl; y = 0.2126f*rl + 0.7152f*gl + 0.0722f*bl; z = 0.0193f*rl + 0.1192f*gl + 0.9505f*bl; } HRESULT Test608(LogProxy* pLog) { // XMColorXYZToSRGB/XMColorSRGBToXYZ HRESULT ret = S_OK; XMVECTOR colors[11]; colors[0] = Colors::DarkSalmon; colors[1] = Colors::DodgerBlue; colors[2] = Colors::Silver; colors[3] = Colors::Black; colors[4] = Colors::White; colors[5] = Colors::Red; colors[6] = Colors::Green; colors[7] = Colors::Blue; colors[8] = Colors::Magenta; colors[9] = Colors::Cyan; colors[10] = Colors::Yellow; for(uint32_t i=0; i < sizeof(colors)/sizeof(XMVECTOR); ++i) { XMVECTOR color = colors[i]; XMVECTOR xyz = XMColorSRGBToXYZ( color ); float x, y, z; srgb2xyz( XMVectorGetX(color), XMVectorGetY(color), XMVectorGetZ(color), x, y, z ); XMVECTOR chk = XMVectorSet( x, y, z, 1.0f ); COMPARISON c = CompareXMVECTOR( xyz, chk, 4 ); if(c > WITHINBIGEPSILON) { printe("%s: failed sRGB to XYZ for %d - %f %f %f %f: %f %f %f %f ... %f %f %f %f (%d)\n",TestName,i, XMVectorGetX(color),XMVectorGetY(color),XMVectorGetZ(color),XMVectorGetW(color), XMVectorGetX(xyz),XMVectorGetY(xyz),XMVectorGetZ(xyz),XMVectorGetW(xyz), XMVectorGetX(chk),XMVectorGetY(chk),XMVectorGetZ(chk),XMVectorGetW(chk), c); ret = MATH_FAIL; } XMVECTOR rgb = XMColorXYZToSRGB( xyz ); c = CompareXMVECTOR( rgb, color, 4 ); if(c > WITHINBIGEPSILON) { printe("%s: failed XYZ to sRGB for %d - %f %f %f %f: %f %f %f %f ... %f %f %f %f (%d)\n",TestName,i, XMVectorGetX(xyz),XMVectorGetY(xyz),XMVectorGetZ(xyz),XMVectorGetW(xyz), XMVectorGetX(rgb),XMVectorGetY(rgb),XMVectorGetZ(rgb),XMVectorGetW(rgb), XMVectorGetX(color),XMVectorGetY(color),XMVectorGetZ(color),XMVectorGetW(color), c); ret = MATH_FAIL; } XMVECTOR rgbo = XMVectorSetW( color, 0.5f ); xyz = XMColorSRGBToXYZ( rgbo ); chk = XMVectorSetW( chk, 0.5f ); c = CompareXMVECTOR( xyz, chk, 4 ); if(c > WITHINBIGEPSILON) { printe("%s: failed sRGB to XYZ A 0.5 for %d - %f %f %f %f: %f %f %f %f ... %f %f %f %f (%d)\n",TestName,i, XMVectorGetX(rgbo),XMVectorGetY(rgbo),XMVectorGetZ(rgbo),XMVectorGetW(rgbo), XMVectorGetX(xyz),XMVectorGetY(xyz),XMVectorGetZ(xyz),XMVectorGetW(xyz), XMVectorGetX(chk),XMVectorGetY(chk),XMVectorGetZ(chk),XMVectorGetW(chk), c); ret = MATH_FAIL; } rgb = XMColorXYZToSRGB( xyz ); c = CompareXMVECTOR( rgb, rgbo, 4 ); if(c > WITHINBIGEPSILON) { printe("%s: failed XYZ to sRGB A 0.5 for %d - %f %f %f %f: %f %f %f %f ... %f %f %f %f (%d)\n",TestName,i, XMVectorGetX(xyz),XMVectorGetY(xyz),XMVectorGetZ(xyz),XMVectorGetW(xyz), XMVectorGetX(rgb),XMVectorGetY(rgb),XMVectorGetZ(rgb),XMVectorGetW(rgb), XMVectorGetX(rgbo),XMVectorGetY(rgbo),XMVectorGetZ(rgbo),XMVectorGetW(rgbo), c); ret = MATH_FAIL; } } return ret; } static inline float EncodeSRGB( float f ) { if (f <= 0.0f) return 0.0f; else if (f >= 1.0f) return 1.0f; else if (f < 0.0031308f) return 12.92f * f; else return 1.055f * powf(f, 1.0f/2.4f) - 0.055f; } static inline float DecodeSRGB( float f ) { if (f <= 0.0f) return 0.0f; else if (f >= 1.0f) return 1.0f; else if (f <= 0.04045f) return f / 12.92f; else return powf((f + 0.055f) / 1.055f, 2.4f); } HRESULT Test610(LogProxy* pLog) { // XMColorRGBToSRGB/XMColorSRGBToRGB HRESULT ret = S_OK; XMVECTOR colors[11]; colors[0] = Colors::DarkSalmon; colors[1] = Colors::DodgerBlue; colors[2] = Colors::Silver; colors[3] = Colors::Black; colors[4] = Colors::White; colors[5] = Colors::Red; colors[6] = Colors::Green; colors[7] = Colors::Blue; colors[8] = Colors::Magenta; colors[9] = Colors::Cyan; colors[10] = Colors::Yellow; for(uint32_t i=0; i < sizeof(colors)/sizeof(XMVECTOR); ++i) { XMVECTOR color = colors[i]; XMVECTOR srgb = XMColorRGBToSRGB( color ); float r = EncodeSRGB( XMVectorGetX(color) ); float g = EncodeSRGB( XMVectorGetY(color) ); float b = EncodeSRGB( XMVectorGetZ(color) ); XMVECTOR chk = XMVectorSet( r, g, b, 1.0f ); COMPARISON c = CompareXMVECTOR( srgb, chk, 4 ); if(c > WITHINBIGEPSILON) { printe("%s: failed RGB to sRGB for %d - %f %f %f %f: %f %f %f %f ... %f %f %f %f (%d)\n",TestName,i, XMVectorGetX(color),XMVectorGetY(color),XMVectorGetZ(color),XMVectorGetW(color), XMVectorGetX(srgb),XMVectorGetY(srgb),XMVectorGetZ(srgb),XMVectorGetW(srgb), XMVectorGetX(chk),XMVectorGetY(chk),XMVectorGetZ(chk),XMVectorGetW(chk), c); ret = MATH_FAIL; } r = DecodeSRGB( XMVectorGetX( srgb ) ); g = DecodeSRGB( XMVectorGetY( srgb ) ); b = DecodeSRGB( XMVectorGetZ( srgb ) ); XMVECTOR chk2 = XMVectorSet(r,g,b,1.f); c = CompareXMVECTOR( color, chk2, 4 ); if(c > WITHINBIGEPSILON) { printe("%s (2): failed RGB to sRGB for %d - %f %f %f %f: %f %f %f %f ... %f %f %f %f (%d)\n",TestName,i, XMVectorGetX(srgb),XMVectorGetY(srgb),XMVectorGetZ(srgb),XMVectorGetW(srgb), XMVectorGetX(color),XMVectorGetY(color),XMVectorGetZ(color),XMVectorGetW(color), XMVectorGetX(chk2),XMVectorGetY(chk2),XMVectorGetZ(chk2),XMVectorGetW(chk2), c); ret = MATH_FAIL; } XMVECTOR rgb = XMColorSRGBToRGB( srgb ); c = CompareXMVECTOR( rgb, color, 4 ); if(c > WITHINBIGEPSILON) { printe("%s: failed sRGB to RGB for %d - %f %f %f %f: %f %f %f %f ... %f %f %f %f (%d)\n",TestName,i, XMVectorGetX(srgb),XMVectorGetY(srgb),XMVectorGetZ(srgb),XMVectorGetW(srgb), XMVectorGetX(rgb),XMVectorGetY(rgb),XMVectorGetZ(rgb),XMVectorGetW(rgb), XMVectorGetX(color),XMVectorGetY(color),XMVectorGetZ(color),XMVectorGetW(color), c); ret = MATH_FAIL; } XMVECTOR rgbo = XMVectorSetW( color, 0.5f ); srgb = XMColorRGBToSRGB( rgbo ); chk = XMVectorSetW( chk, 0.5f ); c = CompareXMVECTOR( srgb, chk, 4 ); if(c > WITHINBIGEPSILON) { printe("%s: failed RGB to sRGB A 0.5 for %d - %f %f %f %f: %f %f %f %f ... %f %f %f %f (%d)\n",TestName,i, XMVectorGetX(rgbo),XMVectorGetY(rgbo),XMVectorGetZ(rgbo),XMVectorGetW(rgbo), XMVectorGetX(srgb),XMVectorGetY(srgb),XMVectorGetZ(srgb),XMVectorGetW(srgb), XMVectorGetX(chk),XMVectorGetY(chk),XMVectorGetZ(chk),XMVectorGetW(chk), c); ret = MATH_FAIL; } rgb = XMColorSRGBToRGB( srgb ); c = CompareXMVECTOR( rgb, rgbo, 4 ); if(c > WITHINBIGEPSILON) { printe("%s: failed sRGB to RGB A 0.5 for %d - %f %f %f %f: %f %f %f %f ... %f %f %f %f (%d)\n",TestName,i, XMVectorGetX(srgb),XMVectorGetY(srgb),XMVectorGetZ(srgb),XMVectorGetW(srgb), XMVectorGetX(rgb),XMVectorGetY(rgb),XMVectorGetZ(rgb),XMVectorGetW(rgb), XMVectorGetX(rgbo),XMVectorGetY(rgbo),XMVectorGetZ(rgbo),XMVectorGetW(rgbo), c); ret = MATH_FAIL; } } return ret; } gavinp/chromium // Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/bind.h" #include "base/bind_helpers.h" #include "media/audio/test_audio_input_controller_factory.h" #include "media/audio/audio_io.h" namespace media { TestAudioInputController::TestAudioInputController( TestAudioInputControllerFactory* factory, AudioManager* audio_manager, EventHandler* event_handler, SyncWriter* sync_writer) : AudioInputController(event_handler, sync_writer), factory_(factory), event_handler_(event_handler) { message_loop_ = audio_manager->GetMessageLoop(); } TestAudioInputController::~TestAudioInputController() { // Inform the factory so that it allows creating new instances in future. factory_->OnTestAudioInputControllerDestroyed(this); } void TestAudioInputController::Close(const base::Closure& closed_task) { message_loop_->PostTaskAndReply(FROM_HERE, base::Bind(&base::DoNothing), closed_task); } TestAudioInputControllerFactory::TestAudioInputControllerFactory() : controller_(NULL) { } AudioInputController* TestAudioInputControllerFactory::Create( AudioManager* audio_manager, AudioInputController::EventHandler* event_handler, AudioParameters params) { DCHECK(!controller_); // Only one test instance managed at a time. controller_ = new TestAudioInputController(this, audio_manager, event_handler, NULL); return controller_; } void TestAudioInputControllerFactory::OnTestAudioInputControllerDestroyed( TestAudioInputController* controller) { DCHECK_EQ(controller_, controller); controller_ = NULL; } } // namespace media maemo5/android-source-browsing.platform--external--collada0 /* * Copyright 2006 Sony Computer Entertainment Inc. * * Licensed under the MIT Open Source License, for details please see license.txt or the website * http://www.opensource.org/licenses/mit-license.php * */ #include #include #include #include #include #include #include #include #include daeElementRef domCamera::create(DAE& dae) { domCameraRef ref = new domCamera(dae); return ref; } daeMetaElement * domCamera::registerElement(DAE& dae) { daeMetaElement* meta = dae.getMeta(ID()); if ( meta != NULL ) return meta; meta = new daeMetaElement(dae); dae.setMeta(ID(), *meta); meta->setName( "camera" ); meta->registerClass(domCamera::create); daeMetaCMPolicy *cm = NULL; daeMetaElementAttribute *mea = NULL; cm = new daeMetaSequence( meta, cm, 0, 1, 1 ); mea = new daeMetaElementAttribute( meta, cm, 0, 0, 1 ); mea->setName( "asset" ); mea->setOffset( daeOffsetOf(domCamera,elemAsset) ); mea->setElementType( domAsset::registerElement(dae) ); cm->appendChild( mea ); mea = new daeMetaElementAttribute( meta, cm, 1, 1, 1 ); mea->setName( "optics" ); mea->setOffset( daeOffsetOf(domCamera,elemOptics) ); mea->setElementType( domCamera::domOptics::registerElement(dae) ); cm->appendChild( mea ); mea = new daeMetaElementAttribute( meta, cm, 2, 0, 1 ); mea->setName( "imager" ); mea->setOffset( daeOffsetOf(domCamera,elemImager) ); mea->setElementType( domCamera::domImager::registerElement(dae) ); cm->appendChild( mea ); mea = new daeMetaElementArrayAttribute( meta, cm, 3, 0, -1 ); mea->setName( "extra" ); mea->setOffset( daeOffsetOf(domCamera,elemExtra_array) ); mea->setElementType( domExtra::registerElement(dae) ); cm->appendChild( mea ); cm->setMaxOrdinal( 3 ); meta->setCMRoot( cm ); // Add attribute: id { daeMetaAttribute *ma = new daeMetaAttribute; ma->setName( "id" ); ma->setType( dae.getAtomicTypes().get("xsID")); ma->setOffset( daeOffsetOf( domCamera , attrId )); ma->setContainer( meta ); meta->appendAttribute(ma); } // Add attribute: name { daeMetaAttribute *ma = new daeMetaAttribute; ma->setName( "name" ); ma->setType( dae.getAtomicTypes().get("xsNCName")); ma->setOffset( daeOffsetOf( domCamera , attrName )); ma->setContainer( meta ); meta->appendAttribute(ma); } meta->setElementSize(sizeof(domCamera)); meta->validate(); return meta; } daeElementRef domCamera::domOptics::create(DAE& dae) { domCamera::domOpticsRef ref = new domCamera::domOptics(dae); return ref; } daeMetaElement * domCamera::domOptics::registerElement(DAE& dae) { daeMetaElement* meta = dae.getMeta(ID()); if ( meta != NULL ) return meta; meta = new daeMetaElement(dae); dae.setMeta(ID(), *meta); meta->setName( "optics" ); meta->registerClass(domCamera::domOptics::create); meta->setIsInnerClass( true ); daeMetaCMPolicy *cm = NULL; daeMetaElementAttribute *mea = NULL; cm = new daeMetaSequence( meta, cm, 0, 1, 1 ); mea = new daeMetaElementAttribute( meta, cm, 0, 1, 1 ); mea->setName( "technique_common" ); mea->setOffset( daeOffsetOf(domCamera::domOptics,elemTechnique_common) ); mea->setElementType( domCamera::domOptics::domTechnique_common::registerElement(dae) ); cm->appendChild( mea ); mea = new daeMetaElementArrayAttribute( meta, cm, 1, 0, -1 ); mea->setName( "technique" ); mea->setOffset( daeOffsetOf(domCamera::domOptics,elemTechnique_array) ); mea->setElementType( domTechnique::registerElement(dae) ); cm->appendChild( mea ); mea = new daeMetaElementArrayAttribute( meta, cm, 2, 0, -1 ); mea->setName( "extra" ); mea->setOffset( daeOffsetOf(domCamera::domOptics,elemExtra_array) ); mea->setElementType( domExtra::registerElement(dae) ); cm->appendChild( mea ); cm->setMaxOrdinal( 2 ); meta->setCMRoot( cm ); meta->setElementSize(sizeof(domCamera::domOptics)); meta->validate(); return meta; } daeElementRef domCamera::domOptics::domTechnique_common::create(DAE& dae) { domCamera::domOptics::domTechnique_commonRef ref = new domCamera::domOptics::domTechnique_common(dae); return ref; } daeMetaElement * domCamera::domOptics::domTechnique_common::registerElement(DAE& dae) { daeMetaElement* meta = dae.getMeta(ID()); if ( meta != NULL ) return meta; meta = new daeMetaElement(dae); dae.setMeta(ID(), *meta); meta->setName( "technique_common" ); meta->registerClass(domCamera::domOptics::domTechnique_common::create); meta->setIsInnerClass( true ); daeMetaCMPolicy *cm = NULL; daeMetaElementAttribute *mea = NULL; cm = new daeMetaChoice( meta, cm, 0, 0, 1, 1 ); mea = new daeMetaElementAttribute( meta, cm, 0, 1, 1 ); mea->setName( "orthographic" ); mea->setOffset( daeOffsetOf(domCamera::domOptics::domTechnique_common,elemOrthographic) ); mea->setElementType( domCamera::domOptics::domTechnique_common::domOrthographic::registerElement(dae) ); cm->appendChild( mea ); mea = new daeMetaElementAttribute( meta, cm, 0, 1, 1 ); mea->setName( "perspective" ); mea->setOffset( daeOffsetOf(domCamera::domOptics::domTechnique_common,elemPerspective) ); mea->setElementType( domCamera::domOptics::domTechnique_common::domPerspective::registerElement(dae) ); cm->appendChild( mea ); cm->setMaxOrdinal( 0 ); meta->setCMRoot( cm ); // Ordered list of sub-elements meta->addContents(daeOffsetOf(domCamera::domOptics::domTechnique_common,_contents)); meta->addContentsOrder(daeOffsetOf(domCamera::domOptics::domTechnique_common,_contentsOrder)); meta->addCMDataArray(daeOffsetOf(domCamera::domOptics::domTechnique_common,_CMData), 1); meta->setElementSize(sizeof(domCamera::domOptics::domTechnique_common)); meta->validate(); return meta; } daeElementRef domCamera::domOptics::domTechnique_common::domOrthographic::create(DAE& dae) { domCamera::domOptics::domTechnique_common::domOrthographicRef ref = new domCamera::domOptics::domTechnique_common::domOrthographic(dae); return ref; } daeMetaElement * domCamera::domOptics::domTechnique_common::domOrthographic::registerElement(DAE& dae) { daeMetaElement* meta = dae.getMeta(ID()); if ( meta != NULL ) return meta; meta = new daeMetaElement(dae); dae.setMeta(ID(), *meta); meta->setName( "orthographic" ); meta->registerClass(domCamera::domOptics::domTechnique_common::domOrthographic::create); meta->setIsInnerClass( true ); daeMetaCMPolicy *cm = NULL; daeMetaElementAttribute *mea = NULL; cm = new daeMetaSequence( meta, cm, 0, 1, 1 ); cm = new daeMetaChoice( meta, cm, 0, 0, 1, 1 ); cm = new daeMetaSequence( meta, cm, 0, 1, 1 ); mea = new daeMetaElementAttribute( meta, cm, 0, 1, 1 ); mea->setName( "xmag" ); mea->setOffset( daeOffsetOf(domCamera::domOptics::domTechnique_common::domOrthographic,elemXmag) ); mea->setElementType( domTargetableFloat::registerElement(dae) ); cm->appendChild( mea ); cm = new daeMetaChoice( meta, cm, 1, 1, 0, 1 ); mea = new daeMetaElementAttribute( meta, cm, 0, 1, 1 ); mea->setName( "ymag" ); mea->setOffset( daeOffsetOf(domCamera::domOptics::domTechnique_common::domOrthographic,elemYmag) ); mea->setElementType( domTargetableFloat::registerElement(dae) ); cm->appendChild( mea ); mea = new daeMetaElementAttribute( meta, cm, 0, 1, 1 ); mea->setName( "aspect_ratio" ); mea->setOffset( daeOffsetOf(domCamera::domOptics::domTechnique_common::domOrthographic,elemAspect_ratio) ); mea->setElementType( domTargetableFloat::registerElement(dae) ); cm->appendChild( mea ); cm->setMaxOrdinal( 0 ); cm->getParent()->appendChild( cm ); cm = cm->getParent(); cm->setMaxOrdinal( 1 ); cm->getParent()->appendChild( cm ); cm = cm->getParent(); cm = new daeMetaSequence( meta, cm, 2, 1, 1 ); mea = new daeMetaElementAttribute( meta, cm, 0, 1, 1 ); mea->setName( "ymag" ); mea->setOffset( daeOffsetOf(domCamera::domOptics::domTechnique_common::domOrthographic,elemYmag) ); mea->setElementType( domTargetableFloat::registerElement(dae) ); cm->appendChild( mea ); mea = new daeMetaElementAttribute( meta, cm, 1, 0, 1 ); mea->setName( "aspect_ratio" ); mea->setOffset( daeOffsetOf(domCamera::domOptics::domTechnique_common::domOrthographic,elemAspect_ratio) ); mea->setElementType( domTargetableFloat::registerElement(dae) ); cm->appendChild( mea ); cm->setMaxOrdinal( 1 ); cm->getParent()->appendChild( cm ); cm = cm->getParent(); cm->setMaxOrdinal( 3 ); cm->getParent()->appendChild( cm ); cm = cm->getParent(); mea = new daeMetaElementAttribute( meta, cm, 1, 1, 1 ); mea->setName( "znear" ); mea->setOffset( daeOffsetOf(domCamera::domOptics::domTechnique_common::domOrthographic,elemZnear) ); mea->setElementType( domTargetableFloat::registerElement(dae) ); cm->appendChild( mea ); mea = new daeMetaElementAttribute( meta, cm, 2, 1, 1 ); mea->setName( "zfar" ); mea->setOffset( daeOffsetOf(domCamera::domOptics::domTechnique_common::domOrthographic,elemZfar) ); mea->setElementType( domTargetableFloat::registerElement(dae) ); cm->appendChild( mea ); cm->setMaxOrdinal( 2 ); meta->setCMRoot( cm ); // Ordered list of sub-elements meta->addContents(daeOffsetOf(domCamera::domOptics::domTechnique_common::domOrthographic,_contents)); meta->addContentsOrder(daeOffsetOf(domCamera::domOptics::domTechnique_common::domOrthographic,_contentsOrder)); meta->addCMDataArray(daeOffsetOf(domCamera::domOptics::domTechnique_common::domOrthographic,_CMData), 2); meta->setElementSize(sizeof(domCamera::domOptics::domTechnique_common::domOrthographic)); meta->validate(); return meta; } daeElementRef domCamera::domOptics::domTechnique_common::domPerspective::create(DAE& dae) { domCamera::domOptics::domTechnique_common::domPerspectiveRef ref = new domCamera::domOptics::domTechnique_common::domPerspective(dae); return ref; } daeMetaElement * domCamera::domOptics::domTechnique_common::domPerspective::registerElement(DAE& dae) { daeMetaElement* meta = dae.getMeta(ID()); if ( meta != NULL ) return meta; meta = new daeMetaElement(dae); dae.setMeta(ID(), *meta); meta->setName( "perspective" ); meta->registerClass(domCamera::domOptics::domTechnique_common::domPerspective::create); meta->setIsInnerClass( true ); daeMetaCMPolicy *cm = NULL; daeMetaElementAttribute *mea = NULL; cm = new daeMetaSequence( meta, cm, 0, 1, 1 ); cm = new daeMetaChoice( meta, cm, 0, 0, 1, 1 ); cm = new daeMetaSequence( meta, cm, 0, 1, 1 ); mea = new daeMetaElementAttribute( meta, cm, 0, 1, 1 ); mea->setName( "xfov" ); mea->setOffset( daeOffsetOf(domCamera::domOptics::domTechnique_common::domPerspective,elemXfov) ); mea->setElementType( domTargetableFloat::registerElement(dae) ); cm->appendChild( mea ); cm = new daeMetaChoice( meta, cm, 1, 1, 0, 1 ); mea = new daeMetaElementAttribute( meta, cm, 0, 1, 1 ); mea->setName( "yfov" ); mea->setOffset( daeOffsetOf(domCamera::domOptics::domTechnique_common::domPerspective,elemYfov) ); mea->setElementType( domTargetableFloat::registerElement(dae) ); cm->appendChild( mea ); mea = new daeMetaElementAttribute( meta, cm, 0, 1, 1 ); mea->setName( "aspect_ratio" ); mea->setOffset( daeOffsetOf(domCamera::domOptics::domTechnique_common::domPerspective,elemAspect_ratio) ); mea->setElementType( domTargetableFloat::registerElement(dae) ); cm->appendChild( mea ); cm->setMaxOrdinal( 0 ); cm->getParent()->appendChild( cm ); cm = cm->getParent(); cm->setMaxOrdinal( 1 ); cm->getParent()->appendChild( cm ); cm = cm->getParent(); cm = new daeMetaSequence( meta, cm, 0, 1, 1 ); mea = new daeMetaElementAttribute( meta, cm, 0, 1, 1 ); mea->setName( "yfov" ); mea->setOffset( daeOffsetOf(domCamera::domOptics::domTechnique_common::domPerspective,elemYfov) ); mea->setElementType( domTargetableFloat::registerElement(dae) ); cm->appendChild( mea ); mea = new daeMetaElementAttribute( meta, cm, 1, 0, 1 ); mea->setName( "aspect_ratio" ); mea->setOffset( daeOffsetOf(domCamera::domOptics::domTechnique_common::domPerspective,elemAspect_ratio) ); mea->setElementType( domTargetableFloat::registerElement(dae) ); cm->appendChild( mea ); cm->setMaxOrdinal( 1 ); cm->getParent()->appendChild( cm ); cm = cm->getParent(); cm->setMaxOrdinal( 3 ); cm->getParent()->appendChild( cm ); cm = cm->getParent(); mea = new daeMetaElementAttribute( meta, cm, 1, 1, 1 ); mea->setName( "znear" ); mea->setOffset( daeOffsetOf(domCamera::domOptics::domTechnique_common::domPerspective,elemZnear) ); mea->setElementType( domTargetableFloat::registerElement(dae) ); cm->appendChild( mea ); mea = new daeMetaElementAttribute( meta, cm, 2, 1, 1 ); mea->setName( "zfar" ); mea->setOffset( daeOffsetOf(domCamera::domOptics::domTechnique_common::domPerspective,elemZfar) ); mea->setElementType( domTargetableFloat::registerElement(dae) ); cm->appendChild( mea ); cm->setMaxOrdinal( 2 ); meta->setCMRoot( cm ); // Ordered list of sub-elements meta->addContents(daeOffsetOf(domCamera::domOptics::domTechnique_common::domPerspective,_contents)); meta->addContentsOrder(daeOffsetOf(domCamera::domOptics::domTechnique_common::domPerspective,_contentsOrder)); meta->addCMDataArray(daeOffsetOf(domCamera::domOptics::domTechnique_common::domPerspective,_CMData), 2); meta->setElementSize(sizeof(domCamera::domOptics::domTechnique_common::domPerspective)); meta->validate(); return meta; } daeElementRef domCamera::domImager::create(DAE& dae) { domCamera::domImagerRef ref = new domCamera::domImager(dae); return ref; } daeMetaElement * domCamera::domImager::registerElement(DAE& dae) { daeMetaElement* meta = dae.getMeta(ID()); if ( meta != NULL ) return meta; meta = new daeMetaElement(dae); dae.setMeta(ID(), *meta); meta->setName( "imager" ); meta->registerClass(domCamera::domImager::create); meta->setIsInnerClass( true ); daeMetaCMPolicy *cm = NULL; daeMetaElementAttribute *mea = NULL; cm = new daeMetaSequence( meta, cm, 0, 1, 1 ); mea = new daeMetaElementArrayAttribute( meta, cm, 0, 1, -1 ); mea->setName( "technique" ); mea->setOffset( daeOffsetOf(domCamera::domImager,elemTechnique_array) ); mea->setElementType( domTechnique::registerElement(dae) ); cm->appendChild( mea ); mea = new daeMetaElementArrayAttribute( meta, cm, 1, 0, -1 ); mea->setName( "extra" ); mea->setOffset( daeOffsetOf(domCamera::domImager,elemExtra_array) ); mea->setElementType( domExtra::registerElement(dae) ); cm->appendChild( mea ); cm->setMaxOrdinal( 1 ); meta->setCMRoot( cm ); meta->setElementSize(sizeof(domCamera::domImager)); meta->validate(); return meta; } // 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 #include #include "gtest/gtest.h" #include "mojo/public/cpp/bindings/lib/fixed_buffer.h" #include "mojo/public/cpp/bindings/lib/validation_errors.h" #include "mojo/public/cpp/system/message_pipe.h" #include "mojo/public/interfaces/bindings/tests/test_structs.mojom.h" namespace mojo { namespace test { namespace { static_assert(std::is_same::type, int32_t>::value, "The underlying type of mojom generated enums must be int32_t."); RectPtr MakeRect(int32_t factor = 1) { RectPtr rect(Rect::New()); rect->x = 1 * factor; rect->y = 2 * factor; rect->width = 10 * factor; rect->height = 20 * factor; return rect; } void CheckRect(const Rect& rect, int32_t factor = 1) { EXPECT_EQ(1 * factor, rect.x); EXPECT_EQ(2 * factor, rect.y); EXPECT_EQ(10 * factor, rect.width); EXPECT_EQ(20 * factor, rect.height); } MultiVersionStructPtr MakeMultiVersionStruct() { MultiVersionStructPtr output(MultiVersionStruct::New()); output->f_int32 = 123; output->f_rect = MakeRect(5); output->f_string = "hello"; output->f_array = Array::New(3); output->f_array[0] = 10; output->f_array[1] = 9; output->f_array[2] = 8; MessagePipe pipe; output->f_message_pipe = pipe.handle0.Pass(); output->f_int16 = 42; return output; } template U SerializeAndDeserialize(T input) { typedef typename mojo::internal::WrapperTraits::DataType InputDataType; typedef typename mojo::internal::WrapperTraits::DataType OutputDataType; size_t size = GetSerializedSize_(*input); mojo::internal::FixedBufferForTesting buf(size + 32); InputDataType data; EXPECT_EQ(mojo::internal::ValidationError::NONE, Serialize_(input.get(), &buf, &data)); std::vector handles; data->EncodePointersAndHandles(&handles); // Set the subsequent area to a special value, so that we can find out if we // mistakenly access the area. void* subsequent_area = buf.Allocate(32); memset(subsequent_area, 0xAA, 32); OutputDataType output_data = reinterpret_cast(data); output_data->DecodePointersAndHandles(&handles); using RawUType = typename mojo::internal::RemoveStructPtr::type; U output(RawUType::New()); Deserialize_(output_data, output.get()); return output; } } // namespace TEST(StructTest, Rect) { RectPtr rect; EXPECT_FALSE(rect); EXPECT_TRUE(rect.is_null()); EXPECT_TRUE(!rect); EXPECT_FALSE(rect); rect = nullptr; EXPECT_FALSE(rect); EXPECT_TRUE(rect.is_null()); EXPECT_TRUE(!rect); EXPECT_FALSE(rect); rect = MakeRect(); EXPECT_TRUE(rect); EXPECT_FALSE(rect.is_null()); EXPECT_FALSE(!rect); EXPECT_TRUE(rect); RectPtr null_rect = nullptr; EXPECT_FALSE(null_rect); EXPECT_TRUE(null_rect.is_null()); EXPECT_TRUE(!null_rect); EXPECT_FALSE(null_rect); CheckRect(*rect); } TEST(StructTest, Clone) { NamedRegionPtr region; NamedRegionPtr clone_region = region.Clone(); EXPECT_TRUE(clone_region.is_null()); region = NamedRegion::New(); clone_region = region.Clone(); EXPECT_TRUE(clone_region->name.is_null()); EXPECT_TRUE(clone_region->rects.is_null()); region->name = ""; clone_region = region.Clone(); EXPECT_EQ(region->name, clone_region->name); region->rects = Array::New(2); region->rects[1] = MakeRect(); clone_region = region.Clone(); EXPECT_EQ(2u, clone_region->rects.size()); EXPECT_TRUE(clone_region->rects[0].is_null()); CheckRect(*clone_region->rects[1]); // NoDefaultFieldValues contains handles, so Clone() is not available, but // NoDefaultFieldValuesPtr should still compile. NoDefaultFieldValuesPtr no_default_field_values(NoDefaultFieldValues::New()); EXPECT_FALSE(no_default_field_values->f13.is_valid()); } // Serialization test of a struct with no pointer or handle members. TEST(StructTest, Serialization_Basic) { RectPtr rect(MakeRect()); size_t size = GetSerializedSize_(*rect); EXPECT_EQ(8U + 16U, size); mojo::internal::FixedBufferForTesting buf(size); internal::Rect_Data* data; EXPECT_EQ(mojo::internal::ValidationError::NONE, Serialize_(rect.get(), &buf, &data)); RectPtr rect2(Rect::New()); Deserialize_(data, rect2.get()); CheckRect(*rect2); } // Construction of a struct with struct pointers from null. TEST(StructTest, Construction_StructPointers) { RectPairPtr pair; EXPECT_TRUE(pair.is_null()); pair = RectPair::New(); EXPECT_FALSE(pair.is_null()); EXPECT_TRUE(pair->first.is_null()); EXPECT_TRUE(pair->first.is_null()); pair = nullptr; EXPECT_TRUE(pair.is_null()); } // Serialization test of a struct with struct pointers. TEST(StructTest, Serialization_StructPointers) { RectPairPtr pair(RectPair::New()); pair->first = MakeRect(); pair->second = MakeRect(); size_t size = GetSerializedSize_(*pair); EXPECT_EQ(8U + 16U + 2 * (8U + 16U), size); mojo::internal::FixedBufferForTesting buf(size); internal::RectPair_Data* data; EXPECT_EQ(mojo::internal::ValidationError::NONE, Serialize_(pair.get(), &buf, &data)); RectPairPtr pair2(RectPair::New()); Deserialize_(data, pair2.get()); CheckRect(*pair2->first); CheckRect(*pair2->second); } // Serialization test of a struct with an array member. TEST(StructTest, Serialization_ArrayPointers) { NamedRegionPtr region(NamedRegion::New()); region->name = "region"; region->rects = Array::New(4); for (size_t i = 0; i < region->rects.size(); ++i) region->rects[i] = MakeRect(static_cast(i) + 1); size_t size = GetSerializedSize_(*region); EXPECT_EQ(8U + // header 8U + // name pointer 8U + // rects pointer 8U + // name header 8U + // name payload (rounded up) 8U + // rects header 4 * 8U + // rects payload (four pointers) 4 * (8U + // rect header 16U), // rect payload (four ints) size); mojo::internal::FixedBufferForTesting buf(size); internal::NamedRegion_Data* data; EXPECT_EQ(mojo::internal::ValidationError::NONE, Serialize_(region.get(), &buf, &data)); NamedRegionPtr region2(NamedRegion::New()); Deserialize_(data, region2.get()); EXPECT_EQ(String("region"), region2->name); EXPECT_EQ(4U, region2->rects.size()); for (size_t i = 0; i < region2->rects.size(); ++i) CheckRect(*region2->rects[i], static_cast(i) + 1); } // Serialization test of a struct with null array pointers. TEST(StructTest, Serialization_NullArrayPointers) { NamedRegionPtr region(NamedRegion::New()); EXPECT_TRUE(region->name.is_null()); EXPECT_TRUE(region->rects.is_null()); size_t size = GetSerializedSize_(*region); EXPECT_EQ(8U + // header 8U + // name pointer 8U, // rects pointer size); mojo::internal::FixedBufferForTesting buf(size); internal::NamedRegion_Data* data; EXPECT_EQ(mojo::internal::ValidationError::NONE, Serialize_(region.get(), &buf, &data)); NamedRegionPtr region2(NamedRegion::New()); Deserialize_(data, region2.get()); EXPECT_TRUE(region2->name.is_null()); EXPECT_TRUE(region2->rects.is_null()); } TEST(StructTest, Serialization_InterfaceRequest) { ContainsInterfaceRequest iface_req_struct; auto size = GetSerializedSize_(iface_req_struct); EXPECT_EQ(8U // struct header + 4U // interface request handle + 4U, // interface request nullable handle size); mojo::internal::FixedBufferForTesting buf(size * 2); ContainsInterfaceRequest::Data_* data; // Test failure when non-nullable interface request is null. EXPECT_EQ(mojo::internal::ValidationError::UNEXPECTED_INVALID_HANDLE, Serialize_(&iface_req_struct, &buf, &data)); SomeInterfacePtr i_ptr; iface_req_struct.req = GetProxy(&i_ptr); EXPECT_TRUE(iface_req_struct.req.is_pending()); EXPECT_EQ(mojo::internal::ValidationError::NONE, Serialize_(&iface_req_struct, &buf, &data)); EXPECT_FALSE(iface_req_struct.req.is_pending()); Deserialize_(data, &iface_req_struct); EXPECT_TRUE(iface_req_struct.req.is_pending()); } // Tests deserializing structs as a newer version. TEST(StructTest, Versioning_OldToNew) { { MultiVersionStructV0Ptr input(MultiVersionStructV0::New()); input->f_int32 = 123; MultiVersionStructPtr expected_output(MultiVersionStruct::New()); expected_output->f_int32 = 123; MultiVersionStructPtr output = SerializeAndDeserialize(input.Pass()); EXPECT_TRUE(output); EXPECT_TRUE(output->Equals(*expected_output)); } { MultiVersionStructV1Ptr input(MultiVersionStructV1::New()); input->f_int32 = 123; input->f_rect = MakeRect(5); MultiVersionStructPtr expected_output(MultiVersionStruct::New()); expected_output->f_int32 = 123; expected_output->f_rect = MakeRect(5); MultiVersionStructPtr output = SerializeAndDeserialize(input.Pass()); EXPECT_TRUE(output); EXPECT_TRUE(output->Equals(*expected_output)); } { MultiVersionStructV3Ptr input(MultiVersionStructV3::New()); input->f_int32 = 123; input->f_rect = MakeRect(5); input->f_string = "hello"; MultiVersionStructPtr expected_output(MultiVersionStruct::New()); expected_output->f_int32 = 123; expected_output->f_rect = MakeRect(5); expected_output->f_string = "hello"; MultiVersionStructPtr output = SerializeAndDeserialize(input.Pass()); EXPECT_TRUE(output); EXPECT_TRUE(output->Equals(*expected_output)); } { MultiVersionStructV5Ptr input(MultiVersionStructV5::New()); input->f_int32 = 123; input->f_rect = MakeRect(5); input->f_string = "hello"; input->f_array = Array::New(3); input->f_array[0] = 10; input->f_array[1] = 9; input->f_array[2] = 8; MultiVersionStructPtr expected_output(MultiVersionStruct::New()); expected_output->f_int32 = 123; expected_output->f_rect = MakeRect(5); expected_output->f_string = "hello"; expected_output->f_array = Array::New(3); expected_output->f_array[0] = 10; expected_output->f_array[1] = 9; expected_output->f_array[2] = 8; MultiVersionStructPtr output = SerializeAndDeserialize(input.Pass()); EXPECT_TRUE(output); EXPECT_TRUE(output->Equals(*expected_output)); } { MultiVersionStructV7Ptr input(MultiVersionStructV7::New()); input->f_int32 = 123; input->f_rect = MakeRect(5); input->f_string = "hello"; input->f_array = Array::New(3); input->f_array[0] = 10; input->f_array[1] = 9; input->f_array[2] = 8; MessagePipe pipe; input->f_message_pipe = pipe.handle0.Pass(); MultiVersionStructPtr expected_output(MultiVersionStruct::New()); expected_output->f_int32 = 123; expected_output->f_rect = MakeRect(5); expected_output->f_string = "hello"; expected_output->f_array = Array::New(3); expected_output->f_array[0] = 10; expected_output->f_array[1] = 9; expected_output->f_array[2] = 8; // Save the raw handle value separately so that we can compare later. MojoHandle expected_handle = input->f_message_pipe.get().value(); MultiVersionStructPtr output = SerializeAndDeserialize(input.Pass()); EXPECT_TRUE(output); EXPECT_EQ(expected_handle, output->f_message_pipe.get().value()); output->f_message_pipe.reset(); EXPECT_TRUE(output->Equals(*expected_output)); } } // Tests deserializing structs as an older version. TEST(StructTest, Versioning_NewToOld) { { MultiVersionStructPtr input = MakeMultiVersionStruct(); MultiVersionStructV7Ptr expected_output(MultiVersionStructV7::New()); expected_output->f_int32 = 123; expected_output->f_rect = MakeRect(5); expected_output->f_string = "hello"; expected_output->f_array = Array::New(3); expected_output->f_array[0] = 10; expected_output->f_array[1] = 9; expected_output->f_array[2] = 8; // Save the raw handle value separately so that we can compare later. MojoHandle expected_handle = input->f_message_pipe.get().value(); MultiVersionStructV7Ptr output = SerializeAndDeserialize(input.Pass()); EXPECT_TRUE(output); EXPECT_EQ(expected_handle, output->f_message_pipe.get().value()); output->f_message_pipe.reset(); EXPECT_TRUE(output->Equals(*expected_output)); } { MultiVersionStructPtr input = MakeMultiVersionStruct(); MultiVersionStructV5Ptr expected_output(MultiVersionStructV5::New()); expected_output->f_int32 = 123; expected_output->f_rect = MakeRect(5); expected_output->f_string = "hello"; expected_output->f_array = Array::New(3); expected_output->f_array[0] = 10; expected_output->f_array[1] = 9; expected_output->f_array[2] = 8; MultiVersionStructV5Ptr output = SerializeAndDeserialize(input.Pass()); EXPECT_TRUE(output); EXPECT_TRUE(output->Equals(*expected_output)); } { MultiVersionStructPtr input = MakeMultiVersionStruct(); MultiVersionStructV3Ptr expected_output(MultiVersionStructV3::New()); expected_output->f_int32 = 123; expected_output->f_rect = MakeRect(5); expected_output->f_string = "hello"; MultiVersionStructV3Ptr output = SerializeAndDeserialize(input.Pass()); EXPECT_TRUE(output); EXPECT_TRUE(output->Equals(*expected_output)); } { MultiVersionStructPtr input = MakeMultiVersionStruct(); MultiVersionStructV1Ptr expected_output(MultiVersionStructV1::New()); expected_output->f_int32 = 123; expected_output->f_rect = MakeRect(5); MultiVersionStructV1Ptr output = SerializeAndDeserialize(input.Pass()); EXPECT_TRUE(output); EXPECT_TRUE(output->Equals(*expected_output)); } { MultiVersionStructPtr input = MakeMultiVersionStruct(); MultiVersionStructV0Ptr expected_output(MultiVersionStructV0::New()); expected_output->f_int32 = 123; MultiVersionStructV0Ptr output = SerializeAndDeserialize(input.Pass()); EXPECT_TRUE(output); EXPECT_TRUE(output->Equals(*expected_output)); } } } // namespace test } // namespace mojo Sources/Overload/OvMaths/src/OvMaths/FMatrix4.cpp /** * @project: Overload * @author: . * @licence: MIT */ #include #include #include #include #include "OvMaths/FMatrix4.h" #include "OvMaths/FVector3.h" #include "OvMaths/FQuaternion.h" const OvMaths::FMatrix4 OvMaths::FMatrix4::Identity = FMatrix4(1.f, 0.f, 0.f, 0.f, 0.f, 1.f, 0.f, 0.f, 0.f, 0.f, 1.f, 0.f, 0.f, 0.f, 0.f, 1.f); OvMaths::FMatrix4::FMatrix4() { memcpy(this->data, Identity.data, 16 * sizeof(float)); } OvMaths::FMatrix4::FMatrix4(float p_element1, float p_element2, float p_element3, float p_element4, float p_element5, float p_element6, float p_element7, float p_element8, float p_element9, float p_element10, float p_element11, float p_element12, float p_element13, float p_element14, float p_element15, float p_element16) { data[0] = p_element1; data[1] = p_element2; data[2] = p_element3; data[3] = p_element4; data[4] = p_element5; data[5] = p_element6; data[6] = p_element7; data[7] = p_element8; data[8] = p_element9; data[9] = p_element10; data[10] = p_element11; data[11] = p_element12; data[12] = p_element13; data[13] = p_element14; data[14] = p_element15; data[15] = p_element16; } OvMaths::FMatrix4::FMatrix4(const FMatrix4& p_other) { *this = p_other; } OvMaths::FMatrix4& OvMaths::FMatrix4::operator=(const FMatrix4& p_other) { memcpy(this->data, p_other.data, 16 * sizeof(float)); return *this; } bool OvMaths::FMatrix4::operator==(const FMatrix4& p_other) { return AreEquals(*this, p_other); } OvMaths::FMatrix4 OvMaths::FMatrix4::operator+(const FMatrix4& p_other) const { return Add(*this, p_other); } OvMaths::FMatrix4& OvMaths::FMatrix4::operator+=(const FMatrix4& p_other) { *this = Add(*this, p_other); return *this; } OvMaths::FMatrix4 OvMaths::FMatrix4::operator-(float p_scalar) const { return Subtract(*this, p_scalar); } OvMaths::FMatrix4 OvMaths::FMatrix4::operator-(const FMatrix4& p_other) const { return Subtract(*this, p_other); } OvMaths::FMatrix4& OvMaths::FMatrix4::operator-=(const FMatrix4& p_other) { *this = Subtract(*this, p_other); return *this; } OvMaths::FMatrix4 OvMaths::FMatrix4::operator*(float p_scalar) const { return Multiply(*this, p_scalar); } OvMaths::FMatrix4& OvMaths::FMatrix4::operator*=(float p_scalar) { *this = Multiply(*this, p_scalar); return *this; } OvMaths::FVector4 OvMaths::FMatrix4::operator*(const FVector4& p_vector) const { return Multiply(*this, p_vector); } OvMaths::FMatrix4 OvMaths::FMatrix4::operator*(const FMatrix4& p_other) const { return Multiply(*this, p_other); } OvMaths::FMatrix4& OvMaths::FMatrix4::operator*=(const FMatrix4& p_other) { *this = Multiply(*this, p_other); return *this; } OvMaths::FMatrix4 OvMaths::FMatrix4::operator/(float p_scalar) const { return Divide(*this, p_scalar); } OvMaths::FMatrix4& OvMaths::FMatrix4::operator/=(float p_scalar) { *this = Divide(*this, p_scalar); return *this; } OvMaths::FMatrix4 OvMaths::FMatrix4::operator/(const FMatrix4& p_other) const { return Divide(*this, p_other); } OvMaths::FMatrix4& OvMaths::FMatrix4::operator/=(const FMatrix4& p_other) { *this = Divide(*this, p_other); return *this; } float& OvMaths::FMatrix4::operator()(uint8_t p_row, uint8_t p_column) { if (p_row >= 4 || p_column >= 4) throw std::out_of_range( "Invalid index : " + std::to_string(p_row) + "," + std::to_string(p_column) + " is out of range"); return data[4 * p_row + p_column]; } bool OvMaths::FMatrix4::AreEquals(const FMatrix4& p_left, const FMatrix4& p_right) { return memcmp(&p_left, &p_right, 16 * sizeof(float)) == 0; } OvMaths::FMatrix4 OvMaths::FMatrix4::Add(const FMatrix4& p_left, float p_scalar) { FMatrix4 result(p_left); for (int8_t i = 0; i < 16; i++) result.data[i] += p_scalar; return result; } OvMaths::FMatrix4 OvMaths::FMatrix4::Add(const FMatrix4& p_left, const FMatrix4& p_right) { FMatrix4 result(p_left); for (int8_t i = 0; i < 16; i++) result.data[i] += p_right.data[i]; return result; } OvMaths::FMatrix4 OvMaths::FMatrix4::Subtract(const FMatrix4& p_left, float p_scalar) { FMatrix4 result(p_left); for (int8_t i = 0; i < 16; ++i) result.data[i] -= p_scalar; return result; } OvMaths::FMatrix4 OvMaths::FMatrix4::Subtract(const FMatrix4& p_left, const FMatrix4& p_right) { FMatrix4 result(p_left); for (int8_t i = 0; i < 16; ++i) result.data[i] -= p_right.data[i]; return result; } OvMaths::FMatrix4 OvMaths::FMatrix4::Multiply(const FMatrix4& p_left, float p_scalar) { FMatrix4 result(p_left); for (int8_t i = 0; i < 16; ++i) result.data[i] *= p_scalar; return result; } OvMaths::FVector4 OvMaths::FMatrix4::Multiply(const FMatrix4& p_matrix, const FVector4& p_vector) { FVector4 multiply; multiply.x = ((p_matrix.data[0] * p_vector.x) + (p_matrix.data[1] * p_vector.y) + (p_matrix.data[2] * p_vector.z) + (p_matrix.data[3] * p_vector.w)); multiply.y = ((p_matrix.data[4] * p_vector.x) + (p_matrix.data[5] * p_vector.y) + (p_matrix.data[6] * p_vector.z) + (p_matrix.data[7] * p_vector.w)); multiply.z = ((p_matrix.data[8] * p_vector.x) + (p_matrix.data[9] * p_vector.y) + (p_matrix.data[10] * p_vector.z) + (p_matrix.data[11] * p_vector.w)); multiply.w = ((p_matrix.data[12] * p_vector.x) + (p_matrix.data[13] * p_vector.y) + (p_matrix.data[ 14] * p_vector.z) + (p_matrix.data[15] * p_vector.w)); return multiply; } OvMaths::FMatrix4 OvMaths::FMatrix4::Multiply(const FMatrix4& p_left, const FMatrix4& p_right) { return FMatrix4( ((p_left.data[0] * p_right.data[0]) + (p_left.data[1] * p_right.data[4]) + (p_left.data[ 2] * p_right.data[8]) + (p_left.data[3] * p_right.data[12])), ((p_left.data[0] * p_right.data[1]) + (p_left.data[1] * p_right.data[5]) + (p_left.data[ 2] * p_right.data[9]) + (p_left.data[3] * p_right.data[13])), ((p_left.data[0] * p_right.data[2]) + (p_left.data[1] * p_right.data[6]) + (p_left.data[ 2] * p_right.data[10]) + (p_left.data[3] * p_right.data[14])), ((p_left.data[0] * p_right.data[3]) + (p_left.data[1] * p_right.data[7]) + (p_left.data[ 2] * p_right.data[11]) + (p_left.data[3] * p_right.data[15])), ((p_left.data[4] * p_right.data[0]) + (p_left.data[5] * p_right.data[4]) + (p_left.data[ 6] * p_right.data[8]) + (p_left.data[7] * p_right.data[12])), ((p_left.data[4] * p_right.data[1]) + (p_left.data[5] * p_right.data[5]) + (p_left.data[ 6] * p_right.data[9]) + (p_left.data[7] * p_right.data[13])), ((p_left.data[4] * p_right.data[2]) + (p_left.data[5] * p_right.data[6]) + (p_left.data[ 6] * p_right.data[10]) + (p_left.data[7] * p_right.data[14])), ((p_left.data[4] * p_right.data[3]) + (p_left.data[5] * p_right.data[7]) + (p_left.data[ 6] * p_right.data[11]) + (p_left.data[7] * p_right.data[15])), ((p_left.data[8] * p_right.data[0]) + (p_left.data[9] * p_right.data[4]) + (p_left.data[ 10] * p_right.data[8]) + (p_left.data[11] * p_right.data[12])), ((p_left.data[8] * p_right.data[1]) + (p_left.data[9] * p_right.data[5]) + (p_left.data[ 10] * p_right.data[9]) + (p_left.data[11] * p_right.data[13])), ((p_left.data[8] * p_right.data[2]) + (p_left.data[9] * p_right.data[6]) + (p_left.data[ 10] * p_right.data[10]) + (p_left.data[11] * p_right.data[14])), ((p_left.data[8] * p_right.data[3]) + (p_left.data[9] * p_right.data[7]) + (p_left.data[ 10] * p_right.data[11]) + (p_left.data[11] * p_right.data[15])), ((p_left.data[12] * p_right.data[0]) + (p_left.data[13] * p_right.data[4]) + (p_left. data[14] * p_right.data[8]) + (p_left.data[15] * p_right.data[12])), ((p_left.data[12] * p_right.data[1]) + (p_left.data[13] * p_right.data[5]) + (p_left. data[14] * p_right.data[9]) + (p_left.data[15] * p_right.data[13])), ((p_left.data[12] * p_right.data[2]) + (p_left.data[13] * p_right.data[6]) + (p_left. data[14] * p_right.data[10]) + (p_left.data[15] * p_right.data[14])), ((p_left.data[12] * p_right.data[3]) + (p_left.data[13] * p_right.data[7]) + (p_left. data[14] * p_right.data[11]) + (p_left.data[15] * p_right.data[15]))); } OvMaths::FMatrix4 OvMaths::FMatrix4::Divide(const FMatrix4& p_left, float p_scalar) { FMatrix4 result(p_left); for (float& element : result.data) element /= p_scalar; return result; } OvMaths::FMatrix4 OvMaths::FMatrix4::Divide(const FMatrix4& p_left, const FMatrix4& p_right) { FMatrix4 leftCopy(p_left); return leftCopy * Inverse(p_right); } bool OvMaths::FMatrix4::IsIdentity(const FMatrix4& p_matrix) { return memcmp(Identity.data, p_matrix.data, 16 * sizeof(float)) == 0; } float OvMaths::FMatrix4::GetMinor(float p_minor0, float p_minor1, float p_minor2, float p_minor3, float p_minor4, float p_minor5, float p_minor6, float p_minor7, float p_minor8) { return p_minor0 * (p_minor4 * p_minor8 - p_minor5 * p_minor7) - p_minor1 * (p_minor3 * p_minor8 - p_minor5 * p_minor6) + p_minor2 * (p_minor3 * p_minor7 - p_minor4 * p_minor6); } float OvMaths::FMatrix4::Determinant(const FMatrix4& p_matrix) { return p_matrix.data[0] * GetMinor(p_matrix.data[5], p_matrix.data[9], p_matrix.data[13], p_matrix.data[6], p_matrix.data[10], p_matrix.data[14], p_matrix.data[7], p_matrix.data[11], p_matrix.data[15]) - p_matrix.data[4] * GetMinor(p_matrix.data[1], p_matrix.data[9], p_matrix.data[13], p_matrix.data[2], p_matrix.data[10], p_matrix.data[14], p_matrix.data[3], p_matrix.data[11], p_matrix.data[15]) + p_matrix.data[8] * GetMinor(p_matrix.data[1], p_matrix.data[5], p_matrix.data[13], p_matrix.data[2], p_matrix.data[6], p_matrix.data[14], p_matrix.data[3], p_matrix.data[7], p_matrix.data[15]) - p_matrix.data[12] * GetMinor(p_matrix.data[1], p_matrix.data[5], p_matrix.data[9], p_matrix.data[2], p_matrix.data[6], p_matrix.data[10], p_matrix.data[3], p_matrix.data[7], p_matrix.data[11]); } OvMaths::FMatrix4 OvMaths::FMatrix4::Transpose(const FMatrix4& p_matrix) { FMatrix4 TransposedMatrix(p_matrix); for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { TransposedMatrix.data[4 * j + i] = p_matrix.data[4 * i + j]; } } return TransposedMatrix; } OvMaths::FMatrix4 OvMaths::FMatrix4::Inverse(const FMatrix4& p_matrix) { const float determinant = Determinant(p_matrix); if (determinant == 0) throw std::logic_error("Division by 0"); const float cof0 = GetMinor(p_matrix.data[5], p_matrix.data[9], p_matrix.data[13], p_matrix.data[6], p_matrix.data[10], p_matrix.data[14], p_matrix.data[7], p_matrix.data[11], p_matrix.data[15]); const float cof1 = GetMinor(p_matrix.data[1], p_matrix.data[9], p_matrix.data[13], p_matrix.data[2], p_matrix.data[10], p_matrix.data[14], p_matrix.data[3], p_matrix.data[11], p_matrix.data[15]); const float cof2 = GetMinor(p_matrix.data[1], p_matrix.data[5], p_matrix.data[13], p_matrix.data[2], p_matrix.data[6], p_matrix.data[14], p_matrix.data[3], p_matrix.data[7], p_matrix.data[15]); const float cof3 = GetMinor(p_matrix.data[1], p_matrix.data[5], p_matrix.data[9], p_matrix.data[2], p_matrix.data[6], p_matrix.data[10], p_matrix.data[3], p_matrix.data[7], p_matrix.data[11]); const float det = p_matrix.data[0] * cof0 - p_matrix.data[4] * cof1 + p_matrix.data[8] * cof2 - p_matrix.data[12] * cof3; if (fabs(det) <= EPSILON) return Identity; const float cof4 = GetMinor(p_matrix.data[4], p_matrix.data[8], p_matrix.data[12], p_matrix.data[6], p_matrix.data[10], p_matrix.data[14], p_matrix.data[7], p_matrix.data[11], p_matrix.data[15]); const float cof5 = GetMinor(p_matrix.data[0], p_matrix.data[8], p_matrix.data[12], p_matrix.data[2], p_matrix.data[10], p_matrix.data[14], p_matrix.data[3], p_matrix.data[11], p_matrix.data[15]); const float cof6 = GetMinor(p_matrix.data[0], p_matrix.data[4], p_matrix.data[12], p_matrix.data[2], p_matrix.data[6], p_matrix.data[14], p_matrix.data[3], p_matrix.data[7], p_matrix.data[15]); const float cof7 = GetMinor(p_matrix.data[0], p_matrix.data[4], p_matrix.data[8], p_matrix.data[2], p_matrix.data[6], p_matrix.data[10], p_matrix.data[3], p_matrix.data[7], p_matrix.data[11]); const float cof8 = GetMinor(p_matrix.data[4], p_matrix.data[8], p_matrix.data[12], p_matrix.data[5], p_matrix.data[9], p_matrix.data[13], p_matrix.data[7], p_matrix.data[11], p_matrix.data[15]); const float cof9 = GetMinor(p_matrix.data[0], p_matrix.data[8], p_matrix.data[12], p_matrix.data[1], p_matrix.data[9], p_matrix.data[13], p_matrix.data[3], p_matrix.data[11], p_matrix.data[15]); const float cof10 = GetMinor(p_matrix.data[0], p_matrix.data[4], p_matrix.data[12], p_matrix.data[1], p_matrix.data[5], p_matrix.data[13], p_matrix.data[3], p_matrix.data[7], p_matrix.data[15]); const float cof11 = GetMinor(p_matrix.data[0], p_matrix.data[4], p_matrix.data[8], p_matrix.data[1], p_matrix.data[5], p_matrix.data[9], p_matrix.data[3], p_matrix.data[7], p_matrix.data[11]); const float cof12 = GetMinor(p_matrix.data[4], p_matrix.data[8], p_matrix.data[12], p_matrix.data[5], p_matrix.data[9], p_matrix.data[13], p_matrix.data[6], p_matrix.data[10], p_matrix.data[14]); const float cof13 = GetMinor(p_matrix.data[0], p_matrix.data[8], p_matrix.data[12], p_matrix.data[1], p_matrix.data[9], p_matrix.data[13], p_matrix.data[2], p_matrix.data[10], p_matrix.data[14]); const float cof14 = GetMinor(p_matrix.data[0], p_matrix.data[4], p_matrix.data[12], p_matrix.data[1], p_matrix.data[5], p_matrix.data[13], p_matrix.data[2], p_matrix.data[6], p_matrix.data[14]); const float cof15 = GetMinor(p_matrix.data[0], p_matrix.data[4], p_matrix.data[8], p_matrix.data[1], p_matrix.data[5], p_matrix.data[9], p_matrix.data[2], p_matrix.data[6], p_matrix.data[10]); const float detInv = 1.0f / det; FMatrix4 inverse; inverse.data[0] = detInv * cof0; inverse.data[4] = -detInv * cof4; inverse.data[8] = detInv * cof8; inverse.data[12] = -detInv * cof12; inverse.data[1] = -detInv * cof1; inverse.data[5] = detInv * cof5; inverse.data[9] = -detInv * cof9; inverse.data[13] = detInv * cof13; inverse.data[2] = detInv * cof2; inverse.data[6] = -detInv * cof6; inverse.data[10] = detInv * cof10; inverse.data[14] = -detInv * cof14; inverse.data[3] = -detInv * cof3; inverse.data[7] = detInv * cof7; inverse.data[11] = -detInv * cof11; inverse.data[15] = detInv * cof15; return inverse; } OvMaths::FMatrix4 OvMaths::FMatrix4::Translation(const FVector3& p_translation) { return FMatrix4(1, 0, 0, p_translation.x, 0, 1, 0, p_translation.y, 0, 0, 1, p_translation.z, 0, 0, 0, 1); } OvMaths::FMatrix4 OvMaths::FMatrix4::Translate(const FMatrix4& p_matrix, const FVector3& p_translation) { return p_matrix * Translation(p_translation); } OvMaths::FMatrix4 OvMaths::FMatrix4::RotationOnAxisX(float p_rotation) { return FMatrix4(1, 0, 0, 0, 0, std::cos(p_rotation), -std::sin(p_rotation), 0, 0, std::sin(p_rotation), std::cos(p_rotation), 0, 0, 0, 0, 1); } OvMaths::FMatrix4 OvMaths::FMatrix4::RotateOnAxisX(const FMatrix4& p_matrix, float p_rotation) { return p_matrix * RotationOnAxisX(p_rotation); } OvMaths::FMatrix4 OvMaths::FMatrix4::RotationOnAxisY(float p_rotation) { return FMatrix4(std::cos(p_rotation), 0, -std::sin(p_rotation), 0, 0, 1, 0, 0, std::sin(p_rotation), 0, std::cos(p_rotation), 0, 0, 0, 0, 1); } OvMaths::FMatrix4 OvMaths::FMatrix4::RotateOnAxisY(const FMatrix4& p_matrix, float p_rotation) { return p_matrix * RotationOnAxisY(p_rotation); } OvMaths::FMatrix4 OvMaths::FMatrix4::RotationOnAxisZ(float p_rotation) { return FMatrix4(std::cos(p_rotation), -std::sin(p_rotation), 0, 0, std::sin(p_rotation), std::cos(p_rotation), 0, 0, 0, 0, 1, 0, 0, 0, 0, 1); } OvMaths::FMatrix4 OvMaths::FMatrix4::RotateOnAxisZ(const FMatrix4& p_matrix, float p_rotation) { return p_matrix * RotationOnAxisZ(p_rotation); } OvMaths::FMatrix4 OvMaths::FMatrix4::RotationYXZ(float p_rotation) { FMatrix4 Xrot = RotationOnAxisX(p_rotation); FMatrix4 Yrot = RotationOnAxisY(p_rotation); FMatrix4 Zrot = RotationOnAxisZ(p_rotation); return Yrot * Xrot * Zrot; } OvMaths::FMatrix4 OvMaths::FMatrix4::RotateYXZ(const FMatrix4& p_matrix, float p_rotation) { return p_matrix * RotationYXZ(p_rotation); } OvMaths::FMatrix4 OvMaths::FMatrix4::Scaling(const FVector3& p_scale) { return FMatrix4(p_scale.x, 0, 0, 0, 0, p_scale.y, 0, 0, 0, 0, p_scale.z, 0, 0, 0, 0, 1); } OvMaths::FMatrix4 OvMaths::FMatrix4::Scale(const FMatrix4& p_matrix, const FVector3& p_scale) { return p_matrix * Scaling(p_scale); } OvMaths::FMatrix4 OvMaths::FMatrix4::Rotation(const FQuaternion& p_quaternion) { return OvMaths::FQuaternion::ToMatrix4(p_quaternion); } OvMaths::FMatrix4 OvMaths::FMatrix4::Rotate(const FMatrix4& p_matrix, const FQuaternion& p_quaternion) { return p_matrix * Rotation(p_quaternion); } OvMaths::FMatrix4 OvMaths::FMatrix4::CreatePerspective(const float p_fov, const float p_aspectRatio, const float p_zNear, const float p_zFar) { const float tangent = tanf(p_fov / 2.0f * PI / 180.0f); const float height = p_zNear * tangent; const float width = height * p_aspectRatio; return CreateFrustum(-width, width, -height, height, p_zNear, p_zFar); } OvMaths::FMatrix4 OvMaths::FMatrix4::CreateOrthographic(const float p_size, const float p_aspectRatio, const float p_zNear, const float p_zFar) { auto ortho = OvMaths::FMatrix4::Identity; const auto right = p_size * p_aspectRatio; const auto left = -right; const auto top = p_size; const auto bottom = -top; ortho(0, 0) = 2.0f / (right - left); ortho(1, 1) = 2.0f / (top - bottom); ortho(2, 2) = -2.0f / (p_zFar - p_zNear); ortho(0, 3) = -(right + left) / (right - left); ortho(1, 3) = -(top + bottom) / (top - bottom); ortho(2, 3) = -(p_zFar + p_zNear) / (p_zFar - p_zNear); ortho(3, 3) = 1.0f; return ortho; } OvMaths::FMatrix4 OvMaths::FMatrix4::CreateView(const float p_eyeX, const float p_eyeY, const float p_eyeZ, const float p_lookX, const float p_lookY, const float p_lookZ, const float p_upX, const float p_upY, const float p_upZ) { const OvMaths::FVector3 eye(p_eyeX, p_eyeY, p_eyeZ); const OvMaths::FVector3 look(p_lookX, p_lookY, p_lookZ); const OvMaths::FVector3 up(p_upX, p_upY, p_upZ); const OvMaths::FVector3 forward(eye - look); FVector3::Normalize(forward); const OvMaths::FVector3 upXForward(OvMaths::FVector3::Cross(up, forward)); FVector3::Normalize(upXForward); const OvMaths::FVector3 v(OvMaths::FVector3::Cross(forward, upXForward)); OvMaths::FMatrix4 View; View.data[0] = upXForward.x; View.data[1] = upXForward.y; View.data[2] = upXForward.z; View.data[3] = -OvMaths::FVector3::Dot(eye, upXForward); View.data[4] = v.x; View.data[5] = v.y; View.data[6] = v.z; View.data[7] = -OvMaths::FVector3::Dot(eye, v); View.data[8] = forward.x; View.data[9] = forward.y; View.data[10] = forward.z; View.data[11] = -OvMaths::FVector3::Dot(eye, forward); return View; } OvMaths::FMatrix4 OvMaths::FMatrix4::CreateFrustum(const float p_left, const float p_right, const float p_bottom, const float p_top, const float p_zNear, const float p_zFar) { const float maxView = 2.0f * p_zNear; const float width = p_right - p_left; const float height = p_top - p_bottom; const float zRange = p_zFar - p_zNear; FMatrix4 Frustum; Frustum.data[0] = maxView / width; Frustum.data[5] = maxView / height; Frustum.data[2] = (p_right + p_left) / width; Frustum.data[6] = (p_top + p_bottom) / height; Frustum.data[10] = (-p_zFar - p_zNear) / zRange; Frustum.data[14] = -1.0f; Frustum.data[11] = (-maxView * p_zFar) / zRange; Frustum.data[15] = 0.0f; return Frustum; } OvMaths::FVector4 OvMaths::FMatrix4::GetRow(const FMatrix4& p_matrix, uint8_t p_row) { if (p_row >= 4) throw std::out_of_range("Invalid index : " + std::to_string(p_row) + " is out of range"); return FVector4(p_matrix.data[p_row * 4], p_matrix.data[p_row * 4 + 1], p_matrix.data[p_row * 4 + 2], p_matrix.data[p_row * 4 + 3]); } OvMaths::FVector4 OvMaths::FMatrix4::GetColumn(const FMatrix4& p_matrix, uint8_t p_column) { if (p_column >= 4) throw std::out_of_range("Invalid index : " + std::to_string(p_column) + " is out of range"); return FVector4(p_matrix.data[p_column], p_matrix.data[p_column + 4], p_matrix.data[p_column + 8], p_matrix.data[p_column + 12]); } pnorbert/ADIOS2source/engine/adios1/ADIOS1Writer.cpp /* * Distributed under the OSI-approved Apache License, Version 2.0. See * accompanying file Copyright.txt for details. * * ADIOS1Writer.cpp * Class to write files using old adios 1.x library. * It requires adios 1.x installed * * Created on: Mar 27, 2017 * Author: pnb */ #include "engine/adios1/ADIOS1Writer.h" #include "ADIOS.h" extern int adios_verbose_level; extern int adios_errno; namespace adios { ADIOS1Writer::ADIOS1Writer(ADIOS &adios, const std::string name, const std::string accessMode, MPI_Comm mpiComm, const Method &method, const IOMode iomode, const float timeout_sec, const bool debugMode, const unsigned int nthreads) : Engine(adios, "ADIOS1Writer", name, accessMode, mpiComm, method, debugMode, nthreads, " ADIOS1Writer constructor (or call to ADIOS Open).\n"), m_groupname{method.m_Name.c_str()}, m_filename{name.c_str()}, m_comm{mpiComm} { Init(); adios_open(&m_adios_file, m_groupname, m_filename, accessMode.c_str(), m_comm); if (adios_errno == err_no_error) { m_IsFileOpen = true; } } ADIOS1Writer::~ADIOS1Writer() { if (m_IsFileOpen) { adios_close(m_adios_file); m_IsFileOpen = false; } } void ADIOS1Writer::Init() { if (!m_initialized) { adios_init_noxml(m_comm); m_initialized = true; } adios_declare_group(&m_adios_group, m_groupname, "", adios_stat_default); InitParameters(); InitTransports(); } bool ADIOS1Writer::ReOpenAsNeeded() { if (!m_IsFileOpen) { adios_open(&m_adios_file, m_groupname, m_filename, "a", m_comm); if (adios_errno == err_no_error) { m_IsFileOpen = true; adios_delete_vardefs(m_adios_group); } } return m_IsFileOpen; } void ADIOS1Writer::DefineVariable(std::string name, bool isScalar, enum ADIOS_DATATYPES vartype, std::string ldims, std::string gdims, std::string offs) { if (isScalar) { adios_define_var(m_adios_group, name.c_str(), "", vartype, "", "", ""); } else { adios_define_var(m_adios_group, name.c_str(), "", vartype, ldims.c_str(), gdims.c_str(), offs.c_str()); } } void ADIOS1Writer::WriteVariable(std::string name, bool isScalar, enum ADIOS_DATATYPES vartype, std::string ldims, std::string gdims, std::string offs, const void *values) { if (ReOpenAsNeeded()) { DefineVariable(name, isScalar, vartype, ldims, gdims, offs); adios_write(m_adios_file, name.c_str(), values); } } void ADIOS1Writer::Write(Variable &variable, const char *values) { WriteVariable(variable.m_Name, variable.m_IsScalar, adios_byte, variable.GetDimensionAsString(), variable.GetGlobalDimensionAsString(), variable.GetOffsetsAsString(), values); } void ADIOS1Writer::Write(Variable &variable, const unsigned char *values) { WriteVariable(variable.m_Name, variable.m_IsScalar, adios_unsigned_byte, variable.GetDimensionAsString(), variable.GetGlobalDimensionAsString(), variable.GetOffsetsAsString(), values); } void ADIOS1Writer::Write(Variable &variable, const short *values) { WriteVariable(variable.m_Name, variable.m_IsScalar, adios_short, variable.GetDimensionAsString(), variable.GetGlobalDimensionAsString(), variable.GetOffsetsAsString(), values); } void ADIOS1Writer::Write(Variable &variable, const unsigned short *values) { WriteVariable(variable.m_Name, variable.m_IsScalar, adios_unsigned_short, variable.GetDimensionAsString(), variable.GetGlobalDimensionAsString(), variable.GetOffsetsAsString(), values); } void ADIOS1Writer::Write(Variable &variable, const int *values) { WriteVariable(variable.m_Name, variable.m_IsScalar, adios_integer, variable.GetDimensionAsString(), variable.GetGlobalDimensionAsString(), variable.GetOffsetsAsString(), values); } void ADIOS1Writer::Write(Variable &variable, const unsigned int *values) { WriteVariable(variable.m_Name, variable.m_IsScalar, adios_unsigned_integer, variable.GetDimensionAsString(), variable.GetGlobalDimensionAsString(), variable.GetOffsetsAsString(), values); } void ADIOS1Writer::Write(Variable &variable, const long int *values) { enum ADIOS_DATATYPES type = adios_integer; // long int is usually 4 bytes which is adios_integer if (sizeof(long int) == 8) { type = adios_long; } WriteVariable(variable.m_Name, variable.m_IsScalar, type, variable.GetDimensionAsString(), variable.GetGlobalDimensionAsString(), variable.GetOffsetsAsString(), values); } void ADIOS1Writer::Write(Variable &variable, const unsigned long int *values) { enum ADIOS_DATATYPES type = adios_unsigned_integer; // long int is usually 4 bytes if (sizeof(long int) == 8) { type = adios_unsigned_long; } WriteVariable(variable.m_Name, variable.m_IsScalar, type, variable.GetDimensionAsString(), variable.GetGlobalDimensionAsString(), variable.GetOffsetsAsString(), values); } void ADIOS1Writer::Write(Variable &variable, const long long int *values) { WriteVariable(variable.m_Name, variable.m_IsScalar, adios_long, variable.GetDimensionAsString(), variable.GetGlobalDimensionAsString(), variable.GetOffsetsAsString(), values); } void ADIOS1Writer::Write(Variable &variable, const unsigned long long int *values) { WriteVariable(variable.m_Name, variable.m_IsScalar, adios_unsigned_long, variable.GetDimensionAsString(), variable.GetGlobalDimensionAsString(), variable.GetOffsetsAsString(), values); } void ADIOS1Writer::Write(Variable &variable, const float *values) { WriteVariable(variable.m_Name, variable.m_IsScalar, adios_real, variable.GetDimensionAsString(), variable.GetGlobalDimensionAsString(), variable.GetOffsetsAsString(), values); } void ADIOS1Writer::Write(Variable &variable, const double *values) { WriteVariable(variable.m_Name, variable.m_IsScalar, adios_double, variable.GetDimensionAsString(), variable.GetGlobalDimensionAsString(), variable.GetOffsetsAsString(), values); } void ADIOS1Writer::Write(Variable &variable, const long double *values) { /* TODO: This is faulty: adios_long_double expects 16 bytes per elements, * but * long double is compiler dependent */ WriteVariable(variable.m_Name, variable.m_IsScalar, adios_long_double, variable.GetDimensionAsString(), variable.GetGlobalDimensionAsString(), variable.GetOffsetsAsString(), values); } void ADIOS1Writer::Write(Variable> &variable, const std::complex *values) { WriteVariable(variable.m_Name, variable.m_IsScalar, adios_complex, variable.GetDimensionAsString(), variable.GetGlobalDimensionAsString(), variable.GetOffsetsAsString(), values); } void ADIOS1Writer::Write(Variable> &variable, const std::complex *values) { WriteVariable(variable.m_Name, variable.m_IsScalar, adios_double_complex, variable.GetDimensionAsString(), variable.GetGlobalDimensionAsString(), variable.GetOffsetsAsString(), values); } void ADIOS1Writer::Write(Variable> &variable, const std::complex *values) { throw std::invalid_argument( "ERROR: Adios 1.x does not support complex type, so it cannot write variable " + variable.m_Name + "\n"); } void ADIOS1Writer::Write(VariableCompound &variable, const void *values) { throw std::invalid_argument("ERROR: Adios 1.x does not support compound " "types, so it cannot write variable " + variable.m_Name + "\n"); } // String version void ADIOS1Writer::Write(const std::string variableName, const char *values) { Write(m_ADIOS.GetVariable(variableName), values); } void ADIOS1Writer::Write(const std::string variableName, const unsigned char *values) { Write(m_ADIOS.GetVariable(variableName), values); } void ADIOS1Writer::Write(const std::string variableName, const short *values) { Write(m_ADIOS.GetVariable(variableName), values); } void ADIOS1Writer::Write(const std::string variableName, const unsigned short *values) { Write(m_ADIOS.GetVariable(variableName), values); } void ADIOS1Writer::Write(const std::string variableName, const int *values) { Write(m_ADIOS.GetVariable(variableName), values); } void ADIOS1Writer::Write(const std::string variableName, const unsigned int *values) { Write(m_ADIOS.GetVariable(variableName), values); } void ADIOS1Writer::Write(const std::string variableName, const long int *values) { Write(m_ADIOS.GetVariable(variableName), values); } void ADIOS1Writer::Write(const std::string variableName, const unsigned long int *values) { Write(m_ADIOS.GetVariable(variableName), values); } void ADIOS1Writer::Write(const std::string variableName, const long long int *values) { Write(m_ADIOS.GetVariable(variableName), values); } void ADIOS1Writer::Write(const std::string variableName, const unsigned long long int *values) { Write(m_ADIOS.GetVariable(variableName), values); } void ADIOS1Writer::Write(const std::string variableName, const float *values) { Write(m_ADIOS.GetVariable(variableName), values); } void ADIOS1Writer::Write(const std::string variableName, const double *values) { Write(m_ADIOS.GetVariable(variableName), values); } void ADIOS1Writer::Write(const std::string variableName, const long double *values) { Write(m_ADIOS.GetVariable(variableName), values); } void ADIOS1Writer::Write(const std::string variableName, const std::complex *values) { Write(m_ADIOS.GetVariable>(variableName), values); } void ADIOS1Writer::Write(const std::string variableName, const std::complex *values) { Write(m_ADIOS.GetVariable>(variableName), values); } void ADIOS1Writer::Write(const std::string variableName, const std::complex *values) { Write(m_ADIOS.GetVariable>(variableName), values); } void ADIOS1Writer::Write(const std::string variableName, const void *values) // Compound type { throw std::invalid_argument("ERROR: Adios 1.x does not support compound " "types, so it cannot write variable " + variableName + "\n"); } void ADIOS1Writer::Advance() { if (m_IsFileOpen) { adios_close(m_adios_file); m_IsFileOpen = false; } } void ADIOS1Writer::Close(const int transportIndex) { if (m_IsFileOpen) { adios_close(m_adios_file); m_IsFileOpen = false; } } // PRIVATE FUNCTIONS void ADIOS1Writer::InitParameters() { auto itMaxBufferSize = m_Method.m_Parameters.find("max_size_MB"); if (itMaxBufferSize != m_Method.m_Parameters.end()) { adios_set_max_buffer_size(std::stoul(itMaxBufferSize->second)); } auto itVerbosity = m_Method.m_Parameters.find("verbose"); if (itVerbosity != m_Method.m_Parameters.end()) { int verbosity = std::stoi(itVerbosity->second); if (m_DebugMode == true) { if (verbosity < 0 || verbosity > 5) throw std::invalid_argument( "ERROR: Method verbose argument must be an " "integer in the range [0,5], in call to " "Open or Engine constructor\n"); } adios_verbose_level = verbosity; } } void ADIOS1Writer::InitTransports() { if (m_DebugMode == true) { if (TransportNamesUniqueness() == false) { throw std::invalid_argument( "ERROR: two transports of the same kind (e.g file IO) " "can't have the same name, modify with name= in Method " "AddTransport\n"); } } for (const auto ¶meters : m_Method.m_TransportParameters) { auto itTransport = parameters.find("transport"); if (itTransport->second == "file" || itTransport->second == "File") { auto itLibrary = parameters.find("library"); if (itLibrary == parameters.end() || itLibrary->second == "POSIX") // use default POSIX { adios_select_method(m_adios_group, "POSIX", "", ""); } else if (itLibrary->second == "MPI_File" || itLibrary->second == "MPI-IO") { adios_select_method(m_adios_group, "MPI", "", ""); } else { if (m_DebugMode == true) throw std::invalid_argument( "ERROR: file transport library " + itLibrary->second + " not supported, in " + m_Name + m_EndMessage); } } else { if (m_DebugMode == true) throw std::invalid_argument( "ERROR: transport " + itTransport->second + " (you mean File?) not supported, in " + m_Name + m_EndMessage); } } } } // end namespace adios // Copyright (C) 2017 // This file is part of the "Nazara Engine - Graphics module" // For conditions of distribution and use, see copyright notice in Config.hpp #include #include #include namespace Nz { /*! * \brief Constructs a Billboard object by default */ inline Billboard::Billboard() { ResetMaterials(1); SetColor(Color::White); SetDefaultMaterial(); SetRotation(0.f); SetSize(64.f, 64.f); } /*! * \brief Constructs a Billboard object with a reference to a material * * \param material Reference to a material */ inline Billboard::Billboard(MaterialRef material) { ResetMaterials(1); SetColor(Color::White); SetMaterial(std::move(material), true); SetRotation(0.f); SetSize(64.f, 64.f); } /*! * \brief Constructs a Billboard object with a pointer to a texture * * \param texture Pointer to a texture */ inline Billboard::Billboard(Texture* texture) { ResetMaterials(1); SetColor(Color::White); SetRotation(0.f); SetSize(64.f, 64.f); SetTexture(texture, true); } /*! * \brief Constructs a Billboard object by assignation * * \param billboard Billboard to copy into this */ inline Billboard::Billboard(const Billboard& billboard) : InstancedRenderable(billboard), m_color(billboard.m_color), m_sinCos(billboard.m_sinCos), m_size(billboard.m_size), m_rotation(billboard.m_rotation) { } /*! * \brief Gets the color of the billboard * \return Current color */ inline const Color& Billboard::GetColor() const { return m_color; } /*! * \brief Gets the rotation of the billboard * \return Current rotation */ inline const RadianAnglef& Billboard::GetRotation() const { return m_rotation; } /*! * \brief Gets the size of the billboard * \return Current size */ inline const Vector2f& Billboard::GetSize() const { return m_size; } /*! * \brief Sets the color of the billboard * * \param color Color for the billboard */ inline void Billboard::SetColor(const Color& color) { m_color = color; } /*! * \brief Sets the default material of the billboard (just default material) */ inline void Billboard::SetDefaultMaterial() { MaterialRef material = Material::New(); material->EnableFaceCulling(true); SetMaterial(std::move(material)); } /*! * \brief Sets the material of the billboard * * \param material Material for the billboard * \param resizeBillboard Should billboard be resized to the material size (diffuse map) */ inline void Billboard::SetMaterial(MaterialRef material, bool resizeBillboard) { SetMaterial(GetSkin(), std::move(material), resizeBillboard); } /*! * \brief Sets the material of the billboard * * \param skinIndex Skin index to change * \param material Material for the billboard * \param resizeBillboard Should billboard be resized to the material size (diffuse map) */ inline void Billboard::SetMaterial(std::size_t skinIndex, MaterialRef material, bool resizeBillboard) { InstancedRenderable::SetMaterial(skinIndex, 0, std::move(material)); if (resizeBillboard) { if (const MaterialRef& newMat = GetMaterial()) { const TextureRef& diffuseMap = newMat->GetDiffuseMap(); if (diffuseMap && diffuseMap->IsValid()) SetSize(Vector2f(Vector2ui(diffuseMap->GetSize()))); } } } /*! * \brief Sets the rotation of the billboard * * \param rotation Rotation for the billboard */ inline void Billboard::SetRotation(const RadianAnglef& rotation) { m_rotation = rotation; auto sincos = rotation.GetSinCos(); m_sinCos.Set(sincos.first, sincos.second); } /*! * \brief Sets the size of the billboard * * \param size Size for the billboard */ inline void Billboard::SetSize(const Vector2f& size) { m_size = size; // We invalidate the bounding volume InvalidateBoundingVolume(); } /*! * \brief Sets the size of the billboard * * \param sizeX Size in X for the billboard * \param sizeY Size in Y for the billboard */ inline void Billboard::SetSize(float sizeX, float sizeY) { SetSize(Vector2f(sizeX, sizeY)); } /*! * \brief Sets the texture of the billboard * * \param texture Texture for the billboard * \param resizeBillboard Should billboard be resized to the texture size */ inline void Billboard::SetTexture(TextureRef texture, bool resizeBillboard) { SetTexture(GetSkin(), std::move(texture), resizeBillboard); } /*! * \brief Sets the texture of the billboard for a specific index * * This function changes the diffuse map of the material associated with the specified skin index * * \param skinIndex Skin index to change * \param texture Texture for the billboard * \param resizeBillboard Should billboard be resized to the texture size */ inline void Billboard::SetTexture(std::size_t skinIndex, TextureRef texture, bool resizeBillboard) { if (resizeBillboard && texture && texture->IsValid()) SetSize(Vector2f(Vector2ui(texture->GetSize()))); const MaterialRef& material = GetMaterial(skinIndex); if (material->GetReferenceCount() > 1) { MaterialRef newMat = Material::New(*material); // Copy newMat->SetDiffuseMap(std::move(texture)); SetMaterial(skinIndex, std::move(newMat)); } else material->SetDiffuseMap(std::move(texture)); } /*! * \brief Sets the current billboard with the content of the other one * \return A reference to this * * \param billboard The other Billboard */ inline Billboard& Billboard::operator=(const Billboard& billboard) { InstancedRenderable::operator=(billboard); m_color = billboard.m_color; m_size = billboard.m_size; InvalidateBoundingVolume(); return *this; } /*! * \brief Creates a new billboard from the arguments * \return A reference to the newly created billboard * * \param args Arguments for the billboard */ template BillboardRef Billboard::New(Args&&... args) { std::unique_ptr object(new Billboard(std::forward(args)...)); object->SetPersistent(false); return object.release(); } } #include SM-125F/chromeos_smart_card_connectorcommon/cpp/src/google_smart_card_common/requesting/remote_call_arguments_conversion.cc // Copyright 2020 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 #include #include #include #include #include namespace google_smart_card { namespace internal { // Definitions of the constants declared in the header file: const char kRemoteCallArgumentConversionError[] = "Failed to convert argument #%d for %s(): %s"; } // namespace internal RemoteCallArgumentsExtractor::RemoteCallArgumentsExtractor( std::string title, std::vector argument_values) : title_(std::move(title)), argument_values_(std::move(argument_values)) {} RemoteCallArgumentsExtractor::RemoteCallArgumentsExtractor( std::string title, Value arguments_as_value) : title_(std::move(title)) { if (!ConvertFromValue(std::move(arguments_as_value), &argument_values_, &error_message_)) { success_ = false; error_message_ = FormatPrintfTemplate("Failed to convert arguments for %s(): %s", title_.c_str(), error_message_.c_str()); } } RemoteCallArgumentsExtractor::~RemoteCallArgumentsExtractor() = default; void RemoteCallArgumentsExtractor::Extract() {} bool RemoteCallArgumentsExtractor::Finish() { VerifyNothingLeft(); return success_; } void RemoteCallArgumentsExtractor::VerifySufficientCount( int arguments_to_convert) { if (!success_) return; const size_t min_size = current_argument_index_ + arguments_to_convert; if (min_size <= argument_values_.size()) return; success_ = false; error_message_ = FormatPrintfTemplate( "Failed to convert arguments for %s(): expected at least %d argument(s), " "received only %d", title_.c_str(), static_cast(min_size), static_cast(argument_values_.size())); } void RemoteCallArgumentsExtractor::VerifyNothingLeft() { if (!success_ || current_argument_index_ == argument_values_.size()) return; success_ = false; error_message_ = FormatPrintfTemplate( "Failed to convert arguments for %s(): expected exactly %d arguments, " "received %d; first extra argument: %s", title_.c_str(), static_cast(current_argument_index_), static_cast(argument_values_.size()), DebugDumpValueSanitized(argument_values_[current_argument_index_]) .c_str()); } } // namespace google_smart_card // // context.hpp // ~~~~~~~~~~ // // Copyright (c) 2016 (business at didenko dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #pragma once #include namespace asion { class connection; using connection_ptr = std::shared_ptr; using connected = std::function; using disconnected = std::function; using shutdown = std::function; using admitter = std::function)>; using reader = std::function; using writer = std::function(connection_ptr)>; struct Context { public: Context( connected c, disconnected d, shutdown s, admitter a, reader r, writer w ); const connected on_connect; const disconnected on_disconnect; const shutdown on_shutdown; const admitter admit_read; const reader on_read; const writer on_write; }; using context_ptr = std::shared_ptr; } // namespace ses GameEngine/iScene.cpp0 #include "iScene.h" iScene::iScene(const std::string & pFileName) : fileName(pFileName) { } iScene::~iScene() { } /* * Copyright 2006 The Android Open Source Project * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkSVGClipPath.h" #include "SkSVGParser.h" #include "SkSVGUse.h" DEFINE_SVG_NO_INFO(ClipPath) bool SkSVGClipPath::isDef() { return true; } bool SkSVGClipPath::isNotDef() { return false; } void SkSVGClipPath::translate(SkSVGParser& parser, bool defState) { parser._startElement("clip"); INHERITED::translate(parser, defState); SkASSERT(fChildren.count() == 1); SkSVGElement* child = *fChildren.begin(); SkASSERT(child->getType() == SkSVGType_Use); SkSVGUse* use = (SkSVGUse*) child; SkSVGElement* ref = nullptr; const char* refStr = &use->f_xlink_href.c_str()[1]; SkASSERT(parser.getIDs().find(refStr, &ref)); SkASSERT(ref); if (ref->getType() == SkSVGType_Rect) parser._addAttribute("rectangle", refStr); else parser._addAttribute("path", refStr); parser._endElement(); } #include int main() { int A,B; float C; scanf("%d %d %f",&A,&B,&C); printf("NUMBER = %d\nSALARY = U$ %.2f\n",A,(B*C)); return 0; } rghvdberg/ninjas10-100 // system includes #include #include #include "sndfile.hh" #include // local includes #include "Sample.h" #include #include "Slice.h" #include "Voice.h" #include "ADSR.h" #include "Mixer.h" #include "globals.h" #include "Stack.h" using namespace std; // maybe move this to it's own class int main() { //init //create sample object, pass filepath to it right away Sample SampleObject("/home/rob/build/ninjas/sample.ogg"); // get the vector holding the sample vector mySample = SampleObject.getSampleVector(); /*vector mySample; fill vector with test data for (int i =0; i < 256; i++) { int j = i /16; float h = (float) j *100; float k = (float) (i % 16); float var = (h + k) / 10000.0; mySample.push_back(var); mySample.push_back(-var); }*/ /*cout << mySample.size() << endl; get sample size (length) */ int mySize = SampleObject.getSampleSize(); /*int mySize = mySample.size(); for (int i = 0; i <512;i++) { cout << mySample[i] << " , "; } cout << endl; */ cout << "Sample size :" << mySize << endl; // make slices vector v_slices ; int slices {1}; int sliceSize { mySize / slices }; cout << "sliceSize :" << sliceSize << endl; for (int i=0, j=0 ; i < mySize; i+=sliceSize ) { v_slices.push_back( Slice() ); // create slice // set start and end v_slices[j].setSliceStart( i ); v_slices[j].setSliceEnd(i+sliceSize-1); // cout << j << " : " << i << " -> " << i+sliceSize-1 << endl; // cout << "Slice :" << j << " : " << v_slices[j].getSliceStart() << "->" << v_slices[j].getSliceEnd() << endl; ++j; } // output array // prototyping run() process /*float outL[BUFFERSIZE] { }; float outR[BUFFERSIZE] { }; */ uint32_t framesDone = 0; /* uint32_t curEventIndex = 0; */ /* create Mixer objects One for each audio channel after each iteration mix is put in audiobuffer */ Mixer mixL { }; Mixer mixR { }; /*Voice stack here we keep track of voices playing TODO timing stuff .. kinda important */ Stack stack { }; /*by example of the cars plugin create array of voices tried to create them 'on the fly' but that won't work. */ Voice voices[128] { }; /*Status lsb msb * 1110nnnn 0lllllll 0mmmmmmm * Pitch Bend Change. This message is sent to indicate a change in the pitch bender (wheel or lever, typically). * The pitch bender is measured by a fourteen bit value. Center (no pitch change) is 2000H. * Sensitivity is a function of the receiver, but may be set using RPN 0. (lllllll) * are the least significant 7 bits. (mmmmmmm) are the most significant 7 bits. */ int pitchbend { 8192 }; float gain { 1.0f }; int voice_index { 0 }; /* becomese the main loop * */ // first check for new midi events // get midi events .. suppose we receive note 60 on channel 1, velocity 64 int status { 0x90 }; //cout << "Input midi status (0x90) :"; //cin >> hex >> status; //int status { 0x92 }; int note { 60}; int velocity { 127 }; int channel { status & 0x0F }; // get midi channel int message { status & 0xF0 }; // get midi message // check if note message while (framesDone < (uint32_t) mySize) { if (message == 0x80 || (message == 0x90)) { switch (message) { case (0x80): { // check if note is playing bool voice_playing = stack.check_Voice_Playing(channel, note); if (voice_playing == false) break; // note wasn't playing anyway .. ignore if (voice_playing) { // get the (pointer to) voice Voice* vp = stack.get_Voice(channel, note); if (!vp->active) stack.remove_Voice(channel,note); else vp->adsr.ADSRstage=ADSR::RELEASE; /* TODO .. think about how this works for pitchbend*/ } break; } case (0x90): { // new note, // find empty "slot" int i { 0 }; while ( (voices[i].active) && i <= 127 ) { //cout << i << " , " << voices[i].active << endl; i++; } /* voices[i] should be free but lets check it * also if no unactive voices are found it means that 128 voices are playing * unlikely .. but * TODO needs fixing, create proper cue (fifo) */ if (i>127) { cout << "index out of range" << endl; return -1; } else { //set properties of voice and add to stack voices[i].active = true; voices[i].index= voice_index; voices[i].channel = channel; voices[i].notenumber = note; voices[i].velocity = velocity; voices[i].pitchbend = pitchbend; voices[i].gain = (float) velocity / 127.0f; voices[i].slice = &v_slices[channel]; voices[i].adsr.initADSR(); voices[i].adsr.setADSR(0.1f, 0.1f ,0.75f ,0.1f); voices[i].position = 0; // all set . add to stack stack.add_Voice(&voices[i]); // voice_index++; voice_index=voice_index%128; } // else } // case 0x90 break; } // switch } // if note message // get all voices playing int max = stack.get_Stack_Size(); // loop through active voices for (int i = 0; i < max ; ++i) { // get the raw samples from the voice // TODOD mono/stereo handling .. // float* pointer will allow any amount of samples to be pulled in int pos_debug = stack.get_Position(i); /*int start_debug = stack.get_Slice_Start(i); int end_debug = stack.get_Slice_End(i); */// cout << pos_debug << " | " << start_debug + pos_debug << " - " << end_debug << endl; float* sample = stack.get_Sample(i, &mySample); // cout << *sample << " - " << *(sample+1) << endl; float sampleL { *sample }; float sampleR { *(sample + 1) }; // get gain factor // process adsr to get the gain back float adsr_gain = stack.runADSR(i); gain = stack.get_Gain(i) * adsr_gain; cout << "Pos :"<< pos_debug << " Gain :" << gain << endl; sampleL = sampleL * gain; sampleR = sampleR * gain; // put samples in mixer mixL.add_Sample(sampleL); mixR.add_Sample(sampleR); // increase the sample position int channels = SampleObject.getSampleChannels(); // cout << "sample channels :#" << channels << endl; stack.inc_Position(i, channels); } // end for loop through active voices message = 0x00; ++framesDone; } return 0; } // main /****************************************************************************** * ____ _ _____ * * / ___| / \ | ___| C++ * * | | / _ \ | |_ Actor * * | |___ / ___ \| _| Framework * * \____/_/ \_|_| * * * * Copyright (C) 2011 - 2016 * * <.charousset (at) haw-hamburg.de> * * * * Distributed under the terms and conditions of the BSD 3-Clause License or * * (at your option) under the terms and conditions of the Boost Software * * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. * * * * If you did not receive a copy of the license files, see * * http://opensource.org/licenses/BSD-3-Clause and * * http://www.boost.org/LICENSE_1_0.txt. * ******************************************************************************/ #ifndef CAF_TYPE_NR_HPP #define CAF_TYPE_NR_HPP #include #include #include #include #include #include "caf/fwd.hpp" #include "caf/atom.hpp" #include "caf/timestamp.hpp" #include "caf/detail/type_list.hpp" #include "caf/detail/squashed_int.hpp" namespace caf { /// Compile-time list of all built-in types. /// @warning Types are sorted by uniform name. using sorted_builtin_types = detail::type_list< actor, // @actor std::vector, // @actorvec actor_addr, // @addr std::vector, // @addrvec atom_value, // @atom std::vector, // @charbuf down_msg, // @down duration, // @duration timestamp, // @timestamp error, // @error exit_msg, // @exit group, // @group group_down_msg, // @group_down int16_t, // @i16 int32_t, // @i32 int64_t, // @i64 int8_t, // @i8 long double, // @ldouble message, // @message message_id, // @message_id node_id, // @node std::string, // @str std::map, // @strmap strong_actor_ptr, // @strong_actor_ptr std::set, // @strset std::vector, // @strvec timeout_msg, // @timeout uint16_t, // @u16 std::u16string, // @u16_str uint32_t, // @u32 std::u32string, // @u32_str uint64_t, // @u64 uint8_t, // @u8 unit_t, // @unit weak_actor_ptr, // @weak_actor_ptr bool, // bool double, // double float // float >; /// Computes the type number for `T`. template ::value> struct type_nr { static constexpr uint16_t value = static_cast( detail::tl_index_of::value + 1); }; template struct type_nr { using type = detail::squashed_int_t; static constexpr uint16_t value = static_cast( detail::tl_index_of::value + 1); }; template <> struct type_nr { static constexpr uint16_t value = static_cast( detail::tl_index_of::value + 1); }; template struct type_nr, false> { static constexpr uint16_t value = type_nr::value; }; /// The number of built-in types. static constexpr size_t type_nrs = detail::tl_size::value + 1; /// List of all type names, indexed via `type_nr`. extern const char* numbered_type_names[]; template struct type_token_helper; template struct type_token_helper : std::integral_constant { // nop }; template struct type_token_helper : type_token_helper<(R << 6) | I, Is...> { // nop }; template constexpr uint32_t make_type_token() { return type_token_helper<0xFFFFFFFF, type_nr::value...>::value; } constexpr uint32_t add_to_type_token(uint32_t token, uint16_t tnr) { return (token << 6) | tnr; } template struct make_type_token_from_list_helper; template struct make_type_token_from_list_helper> : type_token_helper<0xFFFFFFFF, type_nr::value...> { // nop }; template constexpr uint32_t make_type_token_from_list() { return make_type_token_from_list_helper::value; } } // namespace caf #endif // CAF_TYPE_NR_HPP #ifndef __HWMODEL_SREM_HH__ #define __HWMODEL_SREM_HH__ // GENERATED FILE - DO NOT MODIFY #include "params/Srem.hh" #include "sim/sim_object.hh" #include "base.hh" using namespace gem5; class Srem: public SimObject, public InstConfigBase { private: protected: public: Srem(); Srem(const SremParams ¶ms); }; #endif // __HWMODEL_SREM_HH__initialz/tensorflow-yolo-face-ios version https://git-lfs.github.com/spec/v1 oid sha256:86d07f00e2e0dbef3bb7a55606c7c4a9ccb7c1001a750a85c4704fea5228ea49 size 757 #include "pytypes.h" #include "pyhelpers.h" #include "pybuiltins.h" #include "pyint.h" #include "pybool.h" #include "pybaseobject.h" #include "pylist.h" #include "pydict.h" #include "pytuple.h" #include "pynotimplemented.h" #include "pystring.h" #include "pygarbagecollector.h" #include "pyglobalinstances.h" #include "pytraceback.h" using namespace cppy; using namespace cppy::globals; #include std::shared_ptr BuiltinTypes::instance = nullptr; BuiltinTypes::BuiltinTypes() { // types["object"] = std::make_shared( "object", PyBaseObject::construct, helpers::new_tuple() ); // types["type"] = std::make_shared( "type", PyType::construct, helpers::new_tuple(std::vector({std::weak_ptr(types["object"])})) ); // types["function"] = std::make_shared( "function", PyFunction::construct, helpers::new_tuple(std::vector({std::weak_ptr(types["object"])})) ); // types["none"] = std::make_shared( "NoneType", PyNone::construct, helpers::new_tuple(std::vector({std::weak_ptr(types["object"])})) ); // types["notimpl"] = std::make_shared( "NotImplemented", PyNotImplemented::construct, helpers::new_tuple(std::vector({std::weak_ptr(types["object"])})) ); // types["str"] = std::make_shared( "str", PyString::construct, helpers::new_tuple(std::vector({std::weak_ptr(types["object"])})) ); // types["int"] = std::make_shared( "int", PyInt::construct, helpers::new_tuple(std::vector({std::weak_ptr(types["object"])})) ); // types["bool"] = std::make_shared( "bool", PyBool::construct, helpers::new_tuple(std::vector({std::weak_ptr(types["object"]), std::weak_ptr(types["int"])})) ); // types["list"] = std::make_shared( "list", PyList::construct, helpers::new_tuple(std::vector({std::weak_ptr(types["object"])})) ); // types["tuple"] = std::make_shared( "tuple", PyTuple::construct, helpers::new_tuple(std::vector({std::weak_ptr(types["object"])})) ); // types["dict"] = std::make_shared( "dict", PyDict::construct, helpers::new_tuple(std::vector({std::weak_ptr(types["object"])})) ); init_builtin_types(); } BuiltinTypes &BuiltinTypes::the() { if (instance == nullptr) { instance = std::shared_ptr(new BuiltinTypes()); } return *instance; } PyObjectPtr BuiltinTypes::get_type_named(const std::string& name) const { return types.at(name); } bool BuiltinTypes::is_builtin_type(PyObjectPtr t) const { for (const auto &pair: types) { if (pair.second == t) return true; } return false; } void BuiltinTypes::init_builtin_types() { // Hardcode MROs for the builtin types for (auto &pair : types) { if (pair.first != "object" && pair.first != "bool") pair.second->setattr("__mro__", helpers::new_tuple(std::vector({std::weak_ptr(pair.second), std::weak_ptr(types["object"])}))); else if (pair.first == "object") pair.second->setattr("__mro__", helpers::new_tuple(std::vector({std::weak_ptr(pair.second)}))); else pair.second->setattr("__mro__", helpers::new_tuple(std::vector({std::weak_ptr(pair.second), std::weak_ptr(types["int"]), std::weak_ptr(types["object"])}))); } } topillar/PuTTY-ng #include "window_interface.h" #include "../vendor/framework-nd/WinProcessor.h" #include "putty_callback.h" void WindowInterface::at_exit() { g_bg_processor->stop(); process_fini(); std::map < void*, std::function> temp_map; { AutoLock lock(at_exit_map_mutex_); temp_map = at_exit_map_; at_exit_map_.clear(); } std::map < void*, std::function>::iterator it = temp_map.begin(); for (; it != temp_map.end(); it++) { std::function cb = it->second; cb(); } }/* Copyright 2020 Neijwiert 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 "stdafx.h" #include "MPhysicsSceneClass.h" #include "Mphyscoltest.h" #include "obboxclass.h" #include "MVisTableClass.h" #include "MVisTableMgrClass.h" #include "MRenderObjClassRefMultiListClass.h" #include "MTexProjectClassMultiListClass.h" #include "MTexProjectClassTypedAABTreeCullSystemClass.h" #include "MTexProjectClassTypedGridCullSystemClass.h" #include "MPhysClassRefMultiListClass.h" #include "MPhysClassMultiListClass.h" #include "Imports.h" #include "UnmanagedContainer.h" namespace RenSharp { PhysicsSceneClass::StatsStruct::StatsStruct(IntPtr pointer) : AbstractUnmanagedObject(pointer) { } bool PhysicsSceneClass::StatsStruct::Equals(Object^ other) { if (AbstractUnmanagedObject::Equals(other)) { return true; } PhysicsSceneClass::IStatsStruct^ otherThis = dynamic_cast(other); if (otherThis == nullptr) { return nullptr; } return StatsStructPointer.Equals(otherThis->StatsStructPointer); } IntPtr PhysicsSceneClass::StatsStruct::StatsStructPointer::get() { return IntPtr(InternalStatsStructPointer); } int PhysicsSceneClass::StatsStruct::FrameCount::get() { return InternalStatsStructPointer->FrameCount; } void PhysicsSceneClass::StatsStruct::FrameCount::set(int value) { InternalStatsStructPointer->FrameCount = value; } int PhysicsSceneClass::StatsStruct::CullNodeCount::get() { return InternalStatsStructPointer->CullNodeCount; } void PhysicsSceneClass::StatsStruct::CullNodeCount::set(int value) { InternalStatsStructPointer->CullNodeCount = value; } int PhysicsSceneClass::StatsStruct::CullNodesAccepted::get() { return InternalStatsStructPointer->CullNodesAccepted; } void PhysicsSceneClass::StatsStruct::CullNodesAccepted::set(int value) { InternalStatsStructPointer->CullNodesAccepted = value; } int PhysicsSceneClass::StatsStruct::CullNodesTriviallyAccepted::get() { return InternalStatsStructPointer->CullNodesTriviallyAccepted; } void PhysicsSceneClass::StatsStruct::CullNodesTriviallyAccepted::set(int value) { InternalStatsStructPointer->CullNodesTriviallyAccepted = value; } int PhysicsSceneClass::StatsStruct::CullNodesRejected::get() { return InternalStatsStructPointer->CullNodesRejected; } void PhysicsSceneClass::StatsStruct::CullNodesRejected::set(int value) { InternalStatsStructPointer->CullNodesRejected = value; } bool PhysicsSceneClass::StatsStruct::InternalDestroyPointer() { Imports::DestroyPhysicsSceneClassStatsStruct(InternalStatsStructPointer); Pointer = IntPtr::Zero; return true; } ::PhysicsSceneClass::StatsStruct* PhysicsSceneClass::StatsStruct::InternalStatsStructPointer::get() { return reinterpret_cast<::PhysicsSceneClass::StatsStruct*>(Pointer.ToPointer()); } PhysicsSceneClass::PhysicsSceneClass(IntPtr pointer) : SceneClass(pointer) { } bool PhysicsSceneClass::CastRay(IPhysRayCollisionTestClass^ raytest, bool useCollisionRegion) { if (raytest == nullptr || raytest->PhysRayCollisionTestClassPointer.ToPointer() == nullptr) { throw gcnew ArgumentNullException("raytest"); } return InternalPhysicsSceneClassPointer->Cast_Ray( *reinterpret_cast<::PhysRayCollisionTestClass*>(raytest->PhysRayCollisionTestClassPointer.ToPointer()), useCollisionRegion); } bool PhysicsSceneClass::CastRay(IPhysRayCollisionTestClass^ raytest) { if (raytest == nullptr || raytest->PhysRayCollisionTestClassPointer.ToPointer() == nullptr) { throw gcnew ArgumentNullException("raytest"); } return InternalPhysicsSceneClassPointer->Cast_Ray( *reinterpret_cast<::PhysRayCollisionTestClass*>(raytest->PhysRayCollisionTestClassPointer.ToPointer())); } bool PhysicsSceneClass::CastRay(PhysRayCollisionTestClass^ raytest, bool useCollisionRegion) { if (raytest == nullptr) { throw gcnew ArgumentNullException("raytest"); } auto unmanagedRayTest = RenSharpPhysRayCollisionTestClass::CreateRenSharpPhysRayCollisionTestClass(raytest); try { bool result = InternalPhysicsSceneClassPointer->Cast_Ray( *reinterpret_cast<::PhysRayCollisionTestClass*>(unmanagedRayTest->UnmanagedObject->PhysRayCollisionTestClassPointer.ToPointer()), useCollisionRegion); raytest->CopyFrom(unmanagedRayTest->UnmanagedObject); return result; } finally { #pragma push_macro("delete") #undef delete delete unmanagedRayTest; unmanagedRayTest = nullptr; #pragma pop_macro("delete") } } bool PhysicsSceneClass::CastRay(PhysRayCollisionTestClass^ raytest) { if (raytest == nullptr) { throw gcnew ArgumentNullException("raytest"); } auto unmanagedRayTest = RenSharpPhysRayCollisionTestClass::CreateRenSharpPhysRayCollisionTestClass(raytest); try { bool result = InternalPhysicsSceneClassPointer->Cast_Ray( *reinterpret_cast<::PhysRayCollisionTestClass*>(unmanagedRayTest->UnmanagedObject->PhysRayCollisionTestClassPointer.ToPointer())); raytest->CopyFrom(unmanagedRayTest->UnmanagedObject); return result; } finally { #pragma push_macro("delete") #undef delete delete unmanagedRayTest; unmanagedRayTest = nullptr; #pragma pop_macro("delete") } } bool PhysicsSceneClass::CastAABox(IPhysAABoxCollisionTestClass^ boxtest, bool useCollisionRegion) { if (boxtest == nullptr || boxtest->PhysAABoxCollisionTestClassPointer.ToPointer() == nullptr) { throw gcnew ArgumentNullException("boxtest"); } return InternalPhysicsSceneClassPointer->Cast_AABox( *reinterpret_cast<::PhysAABoxCollisionTestClass*>(boxtest->PhysAABoxCollisionTestClassPointer.ToPointer()), useCollisionRegion); } bool PhysicsSceneClass::CastAABox(IPhysAABoxCollisionTestClass^ boxtest) { if (boxtest == nullptr || boxtest->PhysAABoxCollisionTestClassPointer.ToPointer() == nullptr) { throw gcnew ArgumentNullException("boxtest"); } return InternalPhysicsSceneClassPointer->Cast_AABox( *reinterpret_cast<::PhysAABoxCollisionTestClass*>(boxtest->PhysAABoxCollisionTestClassPointer.ToPointer())); } bool PhysicsSceneClass::CastAABox(PhysAABoxCollisionTestClass^ boxtest, bool useCollisionRegion) { if (boxtest == nullptr) { throw gcnew ArgumentNullException("boxtest"); } auto unmanagedBoxTest = RenSharpPhysAABoxCollisionTestClass::CreateRenSharpPhysAABoxCollisionTestClass(boxtest); try { bool result = InternalPhysicsSceneClassPointer->Cast_AABox( *reinterpret_cast<::PhysAABoxCollisionTestClass*>(unmanagedBoxTest->UnmanagedObject->PhysAABoxCollisionTestClassPointer.ToPointer()), useCollisionRegion); boxtest->CopyFrom(unmanagedBoxTest->UnmanagedObject); return result; } finally { #pragma push_macro("delete") #undef delete delete unmanagedBoxTest; unmanagedBoxTest = nullptr; #pragma pop_macro("delete") } } bool PhysicsSceneClass::CastAABox(PhysAABoxCollisionTestClass^ boxtest) { if (boxtest == nullptr) { throw gcnew ArgumentNullException("boxtest"); } auto unmanagedBoxTest = RenSharpPhysAABoxCollisionTestClass::CreateRenSharpPhysAABoxCollisionTestClass(boxtest); try { bool result = InternalPhysicsSceneClassPointer->Cast_AABox( *reinterpret_cast<::PhysAABoxCollisionTestClass*>(unmanagedBoxTest->UnmanagedObject->PhysAABoxCollisionTestClassPointer.ToPointer())); boxtest->CopyFrom(unmanagedBoxTest->UnmanagedObject); return result; } finally { #pragma push_macro("delete") #undef delete delete unmanagedBoxTest; unmanagedBoxTest = nullptr; #pragma pop_macro("delete") } } bool PhysicsSceneClass::CastOBBox(IPhysOBBoxCollisionTestClass^ boxtest, bool useCollisionRegion) { if (boxtest == nullptr || boxtest->PhysOBBoxCollisionTestClassPointer.ToPointer() == nullptr) { throw gcnew ArgumentNullException("boxtest"); } return InternalPhysicsSceneClassPointer->Cast_OBBox( *reinterpret_cast<::PhysOBBoxCollisionTestClass*>(boxtest->PhysOBBoxCollisionTestClassPointer.ToPointer()), useCollisionRegion); } bool PhysicsSceneClass::CastOBBox(IPhysOBBoxCollisionTestClass^ boxtest) { if (boxtest == nullptr || boxtest->PhysOBBoxCollisionTestClassPointer.ToPointer() == nullptr) { throw gcnew ArgumentNullException("boxtest"); } return InternalPhysicsSceneClassPointer->Cast_OBBox( *reinterpret_cast<::PhysOBBoxCollisionTestClass*>(boxtest->PhysOBBoxCollisionTestClassPointer.ToPointer())); } bool PhysicsSceneClass::CastOBBox(PhysOBBoxCollisionTestClass^ boxtest, bool useCollisionRegion) { if (boxtest == nullptr) { throw gcnew ArgumentNullException("boxtest"); } auto unmanagedBoxTest = RenSharpPhysOBBoxCollisionTestClass::CreateRenSharpPhysOBBoxCollisionTestClass(boxtest); try { bool result = InternalPhysicsSceneClassPointer->Cast_OBBox( *reinterpret_cast<::PhysOBBoxCollisionTestClass*>(unmanagedBoxTest->UnmanagedObject->PhysOBBoxCollisionTestClassPointer.ToPointer()), useCollisionRegion); boxtest->CopyFrom(unmanagedBoxTest->UnmanagedObject); return result; } finally { #pragma push_macro("delete") #undef delete delete unmanagedBoxTest; unmanagedBoxTest = nullptr; #pragma pop_macro("delete") } } bool PhysicsSceneClass::CastOBBox(PhysOBBoxCollisionTestClass^ boxtest) { if (boxtest == nullptr) { throw gcnew ArgumentNullException("boxtest"); } auto unmanagedBoxTest = RenSharpPhysOBBoxCollisionTestClass::CreateRenSharpPhysOBBoxCollisionTestClass(boxtest); try { bool result = InternalPhysicsSceneClassPointer->Cast_OBBox( *reinterpret_cast<::PhysOBBoxCollisionTestClass*>(unmanagedBoxTest->UnmanagedObject->PhysOBBoxCollisionTestClassPointer.ToPointer())); boxtest->CopyFrom(unmanagedBoxTest->UnmanagedObject); return result; } finally { #pragma push_macro("delete") #undef delete delete unmanagedBoxTest; unmanagedBoxTest = nullptr; #pragma pop_macro("delete") } } IUnmanagedContainer^>^ PhysicsSceneClass::CollectObjects(OBBoxClass box, bool staticObjs, bool dynamicObjs) { ::OBBoxClass tmp; OBBoxClass::ManagedToUnmanagedOBBoxClass(box, tmp); auto result = PhysClassMultiListClass::CreatePhysClassMultiListClass(); try { InternalPhysicsSceneClassPointer->Collect_Objects( tmp, staticObjs, dynamicObjs, reinterpret_cast<::MultiListClass<::PhysClass>*>(result->UnmanagedObject->Pointer.ToPointer())); return result; } catch (Exception^) { #pragma push_macro("delete") #undef delete delete result; result = nullptr; #pragma pop_macro("delete") throw; } } void PhysicsSceneClass::OnVisOccludersRendered(IntPtr context, IntPtr sample) { if (context.ToPointer() == nullptr) { throw gcnew ArgumentNullException("context"); } else if (sample.ToPointer() == nullptr) { throw gcnew ArgumentNullException("sample"); } InternalPhysicsSceneClassPointer->On_Vis_Occluders_Rendered( *reinterpret_cast<::VisRenderContextClass*>(context.ToPointer()), *reinterpret_cast<::VisSampleClass*>(sample.ToPointer())); } void PhysicsSceneClass::ResetVis(bool doItNow) { InternalPhysicsSceneClassPointer->Reset_Vis(doItNow); } void PhysicsSceneClass::ResetVis() { InternalPhysicsSceneClassPointer->Reset_Vis(); } void PhysicsSceneClass::GetLevelExtents([Out] Vector3% min, [Out] Vector3% max) { ::Vector3 minVec; ::Vector3 maxVec; InternalPhysicsSceneClassPointer->Get_Level_Extents(minVec, maxVec); Vector3::UnmanagedToManagedVector3(minVec, min); Vector3::UnmanagedToManagedVector3(maxVec, max); } IPhysicsSceneClass^ PhysicsSceneClass::Instance::get() { auto result = ::PhysicsSceneClass::Get_Instance(); if (result == nullptr) { return nullptr; } else { return gcnew PhysicsSceneClass(IntPtr(result)); } } IntPtr PhysicsSceneClass::PhysicsSceneClassPointer::get() { return IntPtr(InternalPhysicsSceneClassPointer); } IntPtr PhysicsSceneClass::WidgetUserClassPointer::get() { return IntPtr(InternalWidgetUserClassPointer); } int PhysicsSceneClass::LightingMode::get() { return InternalPhysicsSceneClassPointer->Get_Lighting_Mode(); } void PhysicsSceneClass::LightingMode::set(int value) { InternalPhysicsSceneClassPointer->Set_Lighting_Mode(value); } bool PhysicsSceneClass::VisResetNeeded::get() { return InternalPhysicsSceneClassPointer->Is_Vis_Reset_Needed(); } void PhysicsSceneClass::VisResetNeeded::set(bool value) { InternalPhysicsSceneClassPointer->Vis_Reset_Needed(value); } bool PhysicsSceneClass::UpdateOnlyVisibleObjects::get() { return InternalPhysicsSceneClassPointer->Get_Update_Only_Visible_Objects(); } void PhysicsSceneClass::UpdateOnlyVisibleObjects::set(bool value) { InternalPhysicsSceneClassPointer->Set_Update_Only_Visible_Objects(value); } bool PhysicsSceneClass::DebugDisplayEnabled::get() { return InternalPhysicsSceneClassPointer->Is_Debug_Display_Enabled(); } void PhysicsSceneClass::DebugDisplayEnabled::set(bool value) { InternalPhysicsSceneClassPointer->Enable_Debug_Display(value); } bool PhysicsSceneClass::ProjectorDebugDisplayEnabled::get() { return InternalPhysicsSceneClassPointer->Is_Projector_Debug_Display_Enabled(); } void PhysicsSceneClass::ProjectorDebugDisplayEnabled::set(bool value) { InternalPhysicsSceneClassPointer->Enable_Projector_Debug_Display(value); } bool PhysicsSceneClass::DirtyCullDebugDisplayEnabled::get() { return InternalPhysicsSceneClassPointer->Is_Dirty_Cull_Debug_Display_Enabled(); } void PhysicsSceneClass::DirtyCullDebugDisplayEnabled::set(bool value) { InternalPhysicsSceneClassPointer->Enable_Dirty_Cull_Debug_Display(value); } bool PhysicsSceneClass::LightingDebugDisplayEnabled::get() { return InternalPhysicsSceneClassPointer->Is_Lighting_Debug_Display_Enabled(); } void PhysicsSceneClass::LightingDebugDisplayEnabled::set(bool value) { InternalPhysicsSceneClassPointer->Enable_Lighting_Debug_Display(value); } Vector3 PhysicsSceneClass::LastCameraPosition::get() { Vector3 result; Vector3::UnmanagedToManagedVector3(InternalPhysicsSceneClassPointer->Get_Last_Camera_Position(), result); return result; } void PhysicsSceneClass::LastCameraPosition::set(Vector3 value) { auto helper = reinterpret_cast(InternalPhysicsSceneClassPointer); auto& lastCameraPosition = helper->GetLastCameraPosition(); Vector3::ManagedToUnmanagedVector3(value, lastCameraPosition); } unsigned int PhysicsSceneClass::CurrentFrameNumber::get() { return InternalPhysicsSceneClassPointer->CurrentFrameNumber; } void PhysicsSceneClass::CurrentFrameNumber::set(unsigned int value) { InternalPhysicsSceneClassPointer->CurrentFrameNumber = value; } Collections::Generic::IEnumerable^ PhysicsSceneClass::DynamicObjects::get() { return ObjList; } Collections::Generic::IEnumerable^ PhysicsSceneClass::StaticObjects::get() { return StaticObjList; } Collections::Generic::IEnumerable^ PhysicsSceneClass::LightObjects::get() { return StaticLightList; } void PhysicsSceneClass::InternalVisReset() { auto helper = reinterpret_cast(InternalPhysicsSceneClassPointer); helper->InternalVisReset(); } ::SceneClass* PhysicsSceneClass::InternalSceneClassPointer::get() { return InternalPhysicsSceneClassPointer; } ::WidgetUserClass* PhysicsSceneClass::InternalWidgetUserClassPointer::get() { return InternalPhysicsSceneClassPointer; } ::PhysicsSceneClass* PhysicsSceneClass::InternalPhysicsSceneClassPointer::get() { return reinterpret_cast<::PhysicsSceneClass*>(Pointer.ToPointer()); } IRefMultiListClass^ PhysicsSceneClass::VisibleStaticObjectList::get() { auto helper = reinterpret_cast(InternalPhysicsSceneClassPointer); auto& visibileStaticObjectList = helper->GetVisibleStaticObjectList(); return gcnew PhysClassRefMultiListClass(IntPtr(&visibileStaticObjectList)); } IRefMultiListClass^ PhysicsSceneClass::VisibleWSMeshList::get() { auto helper = reinterpret_cast(InternalPhysicsSceneClassPointer); auto& visibleWSMeshList = helper->GetVisibleWSMeshList(); return gcnew PhysClassRefMultiListClass(IntPtr(&visibleWSMeshList)); } IRefMultiListClass^ PhysicsSceneClass::VisibleDynamicObjectList::get() { auto helper = reinterpret_cast(InternalPhysicsSceneClassPointer); auto& visibleDynamicObjectList = helper->GetVisibleDynamicObjectList(); return gcnew PhysClassRefMultiListClass(IntPtr(&visibleDynamicObjectList)); } IMultiListClass^ PhysicsSceneClass::ActiveTextureProjectors::get() { auto helper = reinterpret_cast(InternalPhysicsSceneClassPointer); auto& activeTextureProjectors = helper->GetActiveTextureProjectors(); return gcnew TexProjectClassMultiListClass(IntPtr(&activeTextureProjectors)); } int PhysicsSceneClass::FrameNum::get() { auto helper = reinterpret_cast(InternalPhysicsSceneClassPointer); auto& frameNum = helper->GetFrameNum(); return frameNum; } void PhysicsSceneClass::FrameNum::set(int value) { auto helper = reinterpret_cast(InternalPhysicsSceneClassPointer); auto& frameNum = helper->GetFrameNum(); frameNum = value; } int PhysicsSceneClass::LastValidVisId::get() { auto helper = reinterpret_cast(InternalPhysicsSceneClassPointer); auto& lastValidVisId = helper->GetLastValidVisId(); return lastValidVisId; } void PhysicsSceneClass::LastValidVisId::set(int value) { auto helper = reinterpret_cast(InternalPhysicsSceneClassPointer); auto& lastValidVisId = helper->GetLastValidVisId(); lastValidVisId = value; } PhysicsSceneClass::IStatsStruct^ PhysicsSceneClass::LastValidStats::get() { auto helper = reinterpret_cast(InternalPhysicsSceneClassPointer); auto& lastValidStats = helper->GetLastValidStats(); return gcnew StatsStruct(IntPtr(&lastValidStats)); } void PhysicsSceneClass::LastValidStats::set(PhysicsSceneClass::IStatsStruct^ value) { auto helper = reinterpret_cast(InternalPhysicsSceneClassPointer); auto& lastValidStats = helper->GetLastValidStats(); lastValidStats = *reinterpret_cast<::PhysicsSceneClass::StatsStruct*>(value->StatsStructPointer.ToPointer()); } PhysicsSceneClass::IStatsStruct^ PhysicsSceneClass::CurrentStats::get() { auto helper = reinterpret_cast(InternalPhysicsSceneClassPointer); auto& currentStats = helper->GetCurrentStats(); return gcnew StatsStruct(IntPtr(¤tStats)); } void PhysicsSceneClass::CurrentStats::set(PhysicsSceneClass::IStatsStruct^ value) { auto helper = reinterpret_cast(InternalPhysicsSceneClassPointer); auto& currentStats = helper->GetCurrentStats(); currentStats = *reinterpret_cast<::PhysicsSceneClass::StatsStruct*>(value->StatsStructPointer.ToPointer()); } bool PhysicsSceneClass::StaticProjectorsDirty::get() { auto helper = reinterpret_cast(InternalPhysicsSceneClassPointer); auto& staticProjectorsDirty = helper->GetStaticProjectorsDirty(); return staticProjectorsDirty; } void PhysicsSceneClass::StaticProjectorsDirty::set(bool value) { auto helper = reinterpret_cast(InternalPhysicsSceneClassPointer); auto& staticProjectorsDirty = helper->GetStaticProjectorsDirty(); staticProjectorsDirty = value; } bool PhysicsSceneClass::VisEnabled::get() { auto helper = reinterpret_cast(InternalPhysicsSceneClassPointer); auto& visEnabled = helper->GetVisEnabled(); return visEnabled; } void PhysicsSceneClass::VisEnabled::set(bool value) { auto helper = reinterpret_cast(InternalPhysicsSceneClassPointer); auto& visEnabled = helper->GetVisEnabled(); visEnabled = value; } bool PhysicsSceneClass::VisInverted::get() { auto helper = reinterpret_cast(InternalPhysicsSceneClassPointer); auto& visInverted = helper->GetVisInverted(); return visInverted; } void PhysicsSceneClass::VisInverted::set(bool value) { auto helper = reinterpret_cast(InternalPhysicsSceneClassPointer); auto& visInverted = helper->GetVisInverted(); visInverted = value; } bool PhysicsSceneClass::VisQuickAndDirty::get() { auto helper = reinterpret_cast(InternalPhysicsSceneClassPointer); auto& visQuickAndDirty = helper->GetVisQuickAndDirty(); return visQuickAndDirty; } void PhysicsSceneClass::VisQuickAndDirty::set(bool value) { auto helper = reinterpret_cast(InternalPhysicsSceneClassPointer); auto& visQuickAndDirty = helper->GetVisQuickAndDirty(); visQuickAndDirty = value; } bool PhysicsSceneClass::VisSectorDisplayEnabled::get() { auto helper = reinterpret_cast(InternalPhysicsSceneClassPointer); auto& visSectorDisplayEnabled = helper->GetVisSectorDisplayEnabled(); return visSectorDisplayEnabled; } void PhysicsSceneClass::VisSectorDisplayEnabled::set(bool value) { auto helper = reinterpret_cast(InternalPhysicsSceneClassPointer); auto& visSectorDisplayEnabled = helper->GetVisSectorDisplayEnabled(); visSectorDisplayEnabled = value; } bool PhysicsSceneClass::VisSectorHistoryEnabled::get() { auto helper = reinterpret_cast(InternalPhysicsSceneClassPointer); auto& visSectorHistoryEnabled = helper->GetVisSectorHistoryEnabled(); return visSectorHistoryEnabled; } void PhysicsSceneClass::VisSectorHistoryEnabled::set(bool value) { auto helper = reinterpret_cast(InternalPhysicsSceneClassPointer); auto& visSectorHistoryEnabled = helper->GetVisSectorHistoryEnabled(); visSectorHistoryEnabled = value; } int PhysicsSceneClass::VisGridDisplayMode::get() { auto helper = reinterpret_cast(InternalPhysicsSceneClassPointer); auto& visGridDisplayMode = helper->GetVisGridDisplayMode(); return visGridDisplayMode; } void PhysicsSceneClass::VisGridDisplayMode::set(int value) { auto helper = reinterpret_cast(InternalPhysicsSceneClassPointer); auto& visGridDisplayMode = helper->GetVisGridDisplayMode(); visGridDisplayMode = value; } bool PhysicsSceneClass::VisSectorMissing::get() { auto helper = reinterpret_cast(InternalPhysicsSceneClassPointer); auto& visSectorMissing = helper->GetVisSectorMissing(); return visSectorMissing; } void PhysicsSceneClass::VisSectorMissing::set(bool value) { auto helper = reinterpret_cast(InternalPhysicsSceneClassPointer); auto& visSectorMissing = helper->GetVisSectorMissing(); visSectorMissing = value; } bool PhysicsSceneClass::VisSectorFallbackEnabled::get() { auto helper = reinterpret_cast(InternalPhysicsSceneClassPointer); auto& visSectorFallbackEnabled = helper->GetVisSectorFallbackEnabled(); return visSectorFallbackEnabled; } void PhysicsSceneClass::VisSectorFallbackEnabled::set(bool value) { auto helper = reinterpret_cast(InternalPhysicsSceneClassPointer); auto& visSectorFallbackEnabled = helper->GetVisSectorFallbackEnabled(); visSectorFallbackEnabled = value; } bool PhysicsSceneClass::BackfaceDebugEnabled::get() { auto helper = reinterpret_cast(InternalPhysicsSceneClassPointer); auto& backfaceDebugEnabled = helper->GetBackfaceDebugEnabled(); return backfaceDebugEnabled; } void PhysicsSceneClass::BackfaceDebugEnabled::set(bool value) { auto helper = reinterpret_cast(InternalPhysicsSceneClassPointer); auto& backfaceDebugEnabled = helper->GetBackfaceDebugEnabled(); backfaceDebugEnabled = value; } bool PhysicsSceneClass::VisSamplePointLocked::get() { auto helper = reinterpret_cast(InternalPhysicsSceneClassPointer); auto& visSamplePointLocked = helper->GetVisSamplePointLocked(); return visSamplePointLocked; } void PhysicsSceneClass::VisSamplePointLocked::set(bool value) { auto helper = reinterpret_cast(InternalPhysicsSceneClassPointer); auto& visSamplePointLocked = helper->GetVisSamplePointLocked(); visSamplePointLocked = value; } Vector3 PhysicsSceneClass::LockedVisSamplePoint::get() { auto helper = reinterpret_cast(InternalPhysicsSceneClassPointer); auto& lockedVisSamplePoint = helper->GetLockedVisSamplePoint(); Vector3 result; Vector3::UnmanagedToManagedVector3(lockedVisSamplePoint, result); return result; } void PhysicsSceneClass::LockedVisSamplePoint::set(Vector3 value) { auto helper = reinterpret_cast(InternalPhysicsSceneClassPointer); auto& lockedVisSamplePoint = helper->GetLockedVisSamplePoint(); Vector3::ManagedToUnmanagedVector3(value, lockedVisSamplePoint); } IntPtr PhysicsSceneClass::VisCamera::get() { auto helper = reinterpret_cast(InternalPhysicsSceneClassPointer); auto& visCamera = helper->GetVisCamera(); return IntPtr(visCamera); } void PhysicsSceneClass::VisCamera::set(IntPtr value) { auto helper = reinterpret_cast(InternalPhysicsSceneClassPointer); auto& visCamera = helper->GetVisCamera(); visCamera = reinterpret_cast<::CameraClass*>(value.ToPointer()); } IVisTableClass^ PhysicsSceneClass::CurrentVisTable::get() { auto helper = reinterpret_cast(InternalPhysicsSceneClassPointer); auto& currentVisTable = helper->GetCurrentVisTable(); if (currentVisTable == nullptr) { return nullptr; } else { return gcnew VisTableClass(IntPtr(currentVisTable)); } } void PhysicsSceneClass::CurrentVisTable::set(IVisTableClass^ value) { auto helper = reinterpret_cast(InternalPhysicsSceneClassPointer); auto& currentVisTable = helper->GetCurrentVisTable(); if (value == nullptr || value->VisTableClassPointer.ToPointer() == nullptr) { currentVisTable = nullptr; } else { currentVisTable = reinterpret_cast<::VisTableClass*>(value->VisTableClassPointer.ToPointer()); } } bool PhysicsSceneClass::StaticProjectorsEnabled::get() { auto helper = reinterpret_cast(InternalPhysicsSceneClassPointer); auto& staticProjectorsEnabled = helper->GetStaticProjectorsEnabled(); return staticProjectorsEnabled; } void PhysicsSceneClass::StaticProjectorsEnabled::set(bool value) { auto helper = reinterpret_cast(InternalPhysicsSceneClassPointer); auto& staticProjectorsEnabled = helper->GetStaticProjectorsEnabled(); staticProjectorsEnabled = value; } bool PhysicsSceneClass::DynamicProjectorsEnabled::get() { auto helper = reinterpret_cast(InternalPhysicsSceneClassPointer); auto& dynamicProjectorsEnabled = helper->GetDynamicProjectorsEnabled(); return dynamicProjectorsEnabled; } void PhysicsSceneClass::DynamicProjectorsEnabled::set(bool value) { auto helper = reinterpret_cast(InternalPhysicsSceneClassPointer); auto& dynamicProjectorsEnabled = helper->GetDynamicProjectorsEnabled(); dynamicProjectorsEnabled = value; } IPhysicsSceneClass::ShadowEnum PhysicsSceneClass::ShadowMode::get() { auto helper = reinterpret_cast(InternalPhysicsSceneClassPointer); auto& shadowMode = helper->GetShadowMode(); return static_cast(shadowMode); } void PhysicsSceneClass::ShadowMode::set(IPhysicsSceneClass::ShadowEnum value) { auto helper = reinterpret_cast(InternalPhysicsSceneClassPointer); auto& shadowMode = helper->GetShadowMode(); shadowMode = static_cast<::PhysicsSceneClass::ShadowEnum>(value); } float PhysicsSceneClass::ShadowAttenStart::get() { auto helper = reinterpret_cast(InternalPhysicsSceneClassPointer); auto& shadowAttenStart = helper->GetShadowAttenStart(); return shadowAttenStart; } void PhysicsSceneClass::ShadowAttenStart::set(float value) { auto helper = reinterpret_cast(InternalPhysicsSceneClassPointer); auto& shadowAttenStart = helper->GetShadowAttenStart(); shadowAttenStart = value; } float PhysicsSceneClass::ShadowAttenEnd::get() { auto helper = reinterpret_cast(InternalPhysicsSceneClassPointer); auto& shadowAttenEnd = helper->GetShadowAttenEnd(); return shadowAttenEnd; } void PhysicsSceneClass::ShadowAttenEnd::set(float value) { auto helper = reinterpret_cast(InternalPhysicsSceneClassPointer); auto& shadowAttenEnd = helper->GetShadowAttenEnd(); shadowAttenEnd = value; } float PhysicsSceneClass::ShadowNormalIntensity::get() { auto helper = reinterpret_cast(InternalPhysicsSceneClassPointer); auto& shadowNormalIntensity = helper->GetShadowNormalIntensity(); return shadowNormalIntensity; } void PhysicsSceneClass::ShadowNormalIntensity::set(float value) { auto helper = reinterpret_cast(InternalPhysicsSceneClassPointer); auto& shadowNormalIntensity = helper->GetShadowNormalIntensity(); shadowNormalIntensity = value; } IntPtr PhysicsSceneClass::ShadowBlobTexture::get() { auto helper = reinterpret_cast(InternalPhysicsSceneClassPointer); auto& shadowBlobTexture = helper->GetShadowBlobTexture(); return IntPtr(shadowBlobTexture); } void PhysicsSceneClass::ShadowBlobTexture::set(IntPtr value) { auto helper = reinterpret_cast(InternalPhysicsSceneClassPointer); auto& shadowBlobTexture = helper->GetShadowBlobTexture(); shadowBlobTexture = reinterpret_cast<::TextureClass*>(value.ToPointer()); } IntPtr PhysicsSceneClass::ShadowRenderContext::get() { auto helper = reinterpret_cast(InternalPhysicsSceneClassPointer); auto& shadowRenderContext = helper->GetShadowRenderContext(); return IntPtr(shadowRenderContext); } void PhysicsSceneClass::ShadowRenderContext::set(IntPtr value) { auto helper = reinterpret_cast(InternalPhysicsSceneClassPointer); auto& shadowRenderContext = helper->GetShadowRenderContext(); shadowRenderContext = reinterpret_cast<::SpecialRenderInfoClass*>(value.ToPointer()); } IntPtr PhysicsSceneClass::ShadowCamera::get() { auto helper = reinterpret_cast(InternalPhysicsSceneClassPointer); auto& shadowCamera = helper->GetShadowCamera(); return IntPtr(shadowCamera); } void PhysicsSceneClass::ShadowCamera::set(IntPtr value) { auto helper = reinterpret_cast(InternalPhysicsSceneClassPointer); auto& shadowCamera = helper->GetShadowCamera(); shadowCamera = reinterpret_cast<::CameraClass*>(value.ToPointer()); } IntPtr PhysicsSceneClass::ShadowMaterialPass::get() { auto helper = reinterpret_cast(InternalPhysicsSceneClassPointer); auto& shadowMaterialPass = helper->GetShadowMaterialPass(); return IntPtr(shadowMaterialPass); } void PhysicsSceneClass::ShadowMaterialPass::set(IntPtr value) { auto helper = reinterpret_cast(InternalPhysicsSceneClassPointer); auto& shadowMaterialPass = helper->GetShadowMaterialPass(); shadowMaterialPass = reinterpret_cast<::MaterialPassClass*>(value.ToPointer()); } int PhysicsSceneClass::ShadowResWidth::get() { auto helper = reinterpret_cast(InternalPhysicsSceneClassPointer); auto& shadowResWidth = helper->GetShadowResWidth(); return shadowResWidth; } void PhysicsSceneClass::ShadowResWidth::set(int value) { auto helper = reinterpret_cast(InternalPhysicsSceneClassPointer); auto& shadowResWidth = helper->GetShadowResWidth(); shadowResWidth = value; } int PhysicsSceneClass::ShadowResHeight::get() { auto helper = reinterpret_cast(InternalPhysicsSceneClassPointer); auto& shadowResHeight = helper->GetShadowResHeight(); return shadowResHeight; } void PhysicsSceneClass::ShadowResHeight::set(int value) { auto helper = reinterpret_cast(InternalPhysicsSceneClassPointer); auto& shadowResHeight = helper->GetShadowResHeight(); shadowResHeight = value; } IntPtr PhysicsSceneClass::DecalSystem::get() { auto helper = reinterpret_cast(InternalPhysicsSceneClassPointer); auto& decalSystem = helper->GetDecalSystem(); return IntPtr(decalSystem); } void PhysicsSceneClass::DecalSystem::set(IntPtr value) { auto helper = reinterpret_cast(InternalPhysicsSceneClassPointer); auto& decalSystem = helper->GetDecalSystem(); decalSystem = reinterpret_cast<::PhysDecalSysClass*>(value.ToPointer()); } IntPtr PhysicsSceneClass::Pathfinder::get() { auto helper = reinterpret_cast(InternalPhysicsSceneClassPointer); auto& pathfinder = helper->GetPathfinder(); return IntPtr(pathfinder); } void PhysicsSceneClass::Pathfinder::set(IntPtr value) { auto helper = reinterpret_cast(InternalPhysicsSceneClassPointer); auto& pathfinder = helper->GetPathfinder(); pathfinder = reinterpret_cast<::PathfindClass*>(value.ToPointer()); } IntPtr PhysicsSceneClass::CameraShakeSystem::get() { auto helper = reinterpret_cast(InternalPhysicsSceneClassPointer); auto& cameraShakeSystem = helper->GetCameraShakeSystem(); return IntPtr(cameraShakeSystem); } void PhysicsSceneClass::CameraShakeSystem::set(IntPtr value) { auto helper = reinterpret_cast(InternalPhysicsSceneClassPointer); auto& cameraShakeSystem = helper->GetCameraShakeSystem(); cameraShakeSystem = reinterpret_cast<::CameraShakeSystemClass*>(value.ToPointer()); } IRefMultiListClass^ PhysicsSceneClass::UpdateList::get() { auto helper = reinterpret_cast(InternalPhysicsSceneClassPointer); auto& updateList = helper->GetUpdateList(); return gcnew RenderObjClassRefMultiListClass(IntPtr(&updateList)); } IRefMultiListClass^ PhysicsSceneClass::VertexProcList::get() { auto helper = reinterpret_cast(InternalPhysicsSceneClassPointer); auto& vertexProcList = helper->GetVertexProcList(); return gcnew RenderObjClassRefMultiListClass(IntPtr(&vertexProcList)); } IRefMultiListClass^ PhysicsSceneClass::ReleaseList::get() { auto helper = reinterpret_cast(InternalPhysicsSceneClassPointer); auto& releaseList = helper->GetReleaseList(); return gcnew PhysClassRefMultiListClass(IntPtr(&releaseList)); } IntPtr PhysicsSceneClass::HighlightMaterialPass::get() { auto helper = reinterpret_cast(InternalPhysicsSceneClassPointer); auto& highlightMaterialPass = helper->GetHighlightMaterialPass(); return IntPtr(highlightMaterialPass); } void PhysicsSceneClass::HighlightMaterialPass::set(IntPtr value) { auto helper = reinterpret_cast(InternalPhysicsSceneClassPointer); auto& highlightMaterialPass = helper->GetHighlightMaterialPass(); highlightMaterialPass = reinterpret_cast<::MaterialPassClass*>(value.ToPointer()); } IntPtr PhysicsSceneClass::StaticCullingSystem::get() { auto helper = reinterpret_cast(InternalPhysicsSceneClassPointer); auto& staticCullingSystem = helper->GetStaticCullingSystem(); return IntPtr(staticCullingSystem); } void PhysicsSceneClass::StaticCullingSystem::set(IntPtr value) { auto helper = reinterpret_cast(InternalPhysicsSceneClassPointer); auto& staticCullingSystem = helper->GetStaticCullingSystem(); staticCullingSystem = reinterpret_cast<::StaticAABTreeCullClass*>(value.ToPointer()); } IntPtr PhysicsSceneClass::StaticLightingSystem::get() { auto helper = reinterpret_cast(InternalPhysicsSceneClassPointer); auto& staticLightingSystem = helper->GetStaticLightingSystem(); return IntPtr(staticLightingSystem); } void PhysicsSceneClass::StaticLightingSystem::set(IntPtr value) { auto helper = reinterpret_cast(InternalPhysicsSceneClassPointer); auto& staticLightingSystem = helper->GetStaticLightingSystem(); staticLightingSystem = reinterpret_cast<::StaticLightCullClass*>(value.ToPointer()); } IntPtr PhysicsSceneClass::DynamicCullingSystem::get() { auto helper = reinterpret_cast(InternalPhysicsSceneClassPointer); auto& dynamicCullingSystem = helper->GetDynamicCullingSystem(); return IntPtr(dynamicCullingSystem); } void PhysicsSceneClass::DynamicCullingSystem::set(IntPtr value) { auto helper = reinterpret_cast(InternalPhysicsSceneClassPointer); auto& dynamicCullingSystem = helper->GetDynamicCullingSystem(); dynamicCullingSystem = reinterpret_cast<::PhysGridCullClass*>(value.ToPointer()); } IntPtr PhysicsSceneClass::DynamicObjVisSystem::get() { auto helper = reinterpret_cast(InternalPhysicsSceneClassPointer); auto& dynamicObjVisSystem = helper->GetDynamicObjVisSystem(); return IntPtr(dynamicObjVisSystem); } void PhysicsSceneClass::DynamicObjVisSystem::set(IntPtr value) { auto helper = reinterpret_cast(InternalPhysicsSceneClassPointer); auto& dynamicObjVisSystem = helper->GetDynamicObjVisSystem(); dynamicObjVisSystem = reinterpret_cast<::DynamicAABTreeCullClass*>(value.ToPointer()); } ITypedAABTreeCullSystemClass^ PhysicsSceneClass::StaticProjectorCullingSystem::get() { auto helper = reinterpret_cast(InternalPhysicsSceneClassPointer); auto& staticProjectorCullingSystem = helper->GetStaticProjectorCullingSystem(); if (staticProjectorCullingSystem == nullptr) { return nullptr; } else { return gcnew TexProjectClassTypedAABTreeCullSystemClass(IntPtr(staticProjectorCullingSystem)); } } void PhysicsSceneClass::StaticProjectorCullingSystem::set(ITypedAABTreeCullSystemClass^ value) { auto helper = reinterpret_cast(InternalPhysicsSceneClassPointer); auto& staticProjectorCullingSystem = helper->GetStaticProjectorCullingSystem(); if (value == nullptr || value->Pointer.ToPointer() == nullptr) { staticProjectorCullingSystem = nullptr; } else { staticProjectorCullingSystem = reinterpret_cast<::TypedAABTreeCullSystemClass<::TexProjectClass>*>(value->Pointer.ToPointer()); } } ITypedGridCullSystemClass^ PhysicsSceneClass::DynamicProjectorCullingSystem::get() { auto helper = reinterpret_cast(InternalPhysicsSceneClassPointer); auto& dynamicProjectorCullingSystem = helper->GetDynamicProjectorCullingSystem(); if (dynamicProjectorCullingSystem == nullptr) { return nullptr; } else { return gcnew TexProjectClassTypedGridCullSystemClass(IntPtr(dynamicProjectorCullingSystem)); } } void PhysicsSceneClass::DynamicProjectorCullingSystem::set(ITypedGridCullSystemClass^ value) { auto helper = reinterpret_cast(InternalPhysicsSceneClassPointer); auto& dynamicProjectorCullingSystem = helper->GetDynamicProjectorCullingSystem(); if (value == nullptr || value->Pointer.ToPointer() == nullptr) { dynamicProjectorCullingSystem = nullptr; } else { dynamicProjectorCullingSystem = reinterpret_cast<::TypedGridCullSystemClass<::TexProjectClass>*>(value->Pointer.ToPointer()); } } IVisTableMgrClass^ PhysicsSceneClass::VisTableManager::get() { auto helper = reinterpret_cast(InternalPhysicsSceneClassPointer); auto& visTableManager = helper->GetVisTableManager(); return gcnew VisTableMgrClass(IntPtr(&visTableManager)); } void PhysicsSceneClass::VisTableManager::set(IVisTableMgrClass^ value) { auto helper = reinterpret_cast(InternalPhysicsSceneClassPointer); auto& visTableManager = helper->GetVisTableManager(); visTableManager = *reinterpret_cast<::VisTableMgrClass*>(value->VisTableMgrClassPointer.ToPointer()); } Vector3 PhysicsSceneClass::SceneAmbientLight::get() { auto helper = reinterpret_cast(InternalPhysicsSceneClassPointer); auto& sceneAmbientLight = helper->GetSceneAmbientLight(); Vector3 result; Vector3::UnmanagedToManagedVector3(sceneAmbientLight, result); return result; } void PhysicsSceneClass::SceneAmbientLight::set(Vector3 value) { auto helper = reinterpret_cast(InternalPhysicsSceneClassPointer); auto& sceneAmbientLight = helper->GetSceneAmbientLight(); Vector3::ManagedToUnmanagedVector3(value, sceneAmbientLight); } bool PhysicsSceneClass::UseSun::get() { auto helper = reinterpret_cast(InternalPhysicsSceneClassPointer); auto& useSun = helper->GetUseSun(); return useSun; } void PhysicsSceneClass::UseSun::set(bool value) { auto helper = reinterpret_cast(InternalPhysicsSceneClassPointer); auto& useSun = helper->GetUseSun(); useSun = value; } float PhysicsSceneClass::SunPitch::get() { auto helper = reinterpret_cast(InternalPhysicsSceneClassPointer); auto& sunPitch = helper->GetSunPitch(); return sunPitch; } void PhysicsSceneClass::SunPitch::set(float value) { auto helper = reinterpret_cast(InternalPhysicsSceneClassPointer); auto& sunPitch = helper->GetSunPitch(); sunPitch = value; } float PhysicsSceneClass::SunYaw::get() { auto helper = reinterpret_cast(InternalPhysicsSceneClassPointer); auto& sunYaw = helper->GetSunYaw(); return sunYaw; } void PhysicsSceneClass::SunYaw::set(float value) { auto helper = reinterpret_cast(InternalPhysicsSceneClassPointer); auto& sunYaw = helper->GetSunYaw(); sunYaw = value; } IntPtr PhysicsSceneClass::SunLight::get() { auto helper = reinterpret_cast(InternalPhysicsSceneClassPointer); auto& sunLight = helper->GetSunLight(); return IntPtr(sunLight); } void PhysicsSceneClass::SunLight::set(IntPtr value) { auto helper = reinterpret_cast(InternalPhysicsSceneClassPointer); auto& sunLight = helper->GetSunLight(); sunLight = reinterpret_cast<::LightClass*>(value.ToPointer()); } int PhysicsSceneClass::DynamicPolyBudget::get() { auto helper = reinterpret_cast(InternalPhysicsSceneClassPointer); auto& dynamicPolyBudget = helper->GetDynamicPolyBudget(); return dynamicPolyBudget; } void PhysicsSceneClass::DynamicPolyBudget::set(int value) { auto helper = reinterpret_cast(InternalPhysicsSceneClassPointer); auto& dynamicPolyBudget = helper->GetDynamicPolyBudget(); dynamicPolyBudget = value; } int PhysicsSceneClass::StaticPolyBudget::get() { auto helper = reinterpret_cast(InternalPhysicsSceneClassPointer); auto& staticPolyBudget = helper->GetStaticPolyBudget(); return staticPolyBudget; } void PhysicsSceneClass::StaticPolyBudget::set(int value) { auto helper = reinterpret_cast(InternalPhysicsSceneClassPointer); auto& staticPolyBudget = helper->GetStaticPolyBudget(); staticPolyBudget = value; } IRefMultiListClass^ PhysicsSceneClass::ObjList::get() { auto helper = reinterpret_cast(InternalPhysicsSceneClassPointer); auto& objList = helper->GetObjList(); return gcnew PhysClassRefMultiListClass(IntPtr(&objList)); } IRefMultiListClass^ PhysicsSceneClass::StaticObjList::get() { auto helper = reinterpret_cast(InternalPhysicsSceneClassPointer); auto& staticObjList = helper->GetStaticObjList(); return gcnew PhysClassRefMultiListClass(IntPtr(&staticObjList)); } IRefMultiListClass^ PhysicsSceneClass::StaticLightList::get() { auto helper = reinterpret_cast(InternalPhysicsSceneClassPointer); auto& staticLightList = helper->GetStaticLightList(); return gcnew PhysClassRefMultiListClass(IntPtr(&staticLightList)); } IMultiListClass^ PhysicsSceneClass::StaticProjectorList::get() { auto helper = reinterpret_cast(InternalPhysicsSceneClassPointer); auto& staticProjectorList = helper->GetStaticProjectorList(); return gcnew TexProjectClassMultiListClass(IntPtr(&staticProjectorList)); } IMultiListClass^ PhysicsSceneClass::DynamicProjectorList::get() { auto helper = reinterpret_cast(InternalPhysicsSceneClassPointer); auto& dynamicProjectorList = helper->GetDynamicProjectorList(); return gcnew TexProjectClassMultiListClass(IntPtr(&dynamicProjectorList)); } IRefMultiListClass^ PhysicsSceneClass::DirtyCullList::get() { auto helper = reinterpret_cast(InternalPhysicsSceneClassPointer); auto& dirtyCullList = helper->GetDirtyCullList(); return gcnew PhysClassRefMultiListClass(IntPtr(&dirtyCullList)); } IRefMultiListClass^ PhysicsSceneClass::TimestepList::get() { auto helper = reinterpret_cast(InternalPhysicsSceneClassPointer); auto& timestepList = helper->GetTimestepList(); return gcnew PhysClassRefMultiListClass(IntPtr(×tepList)); } IRefMultiListClass^ PhysicsSceneClass::StaticAnimList::get() { auto helper = reinterpret_cast(InternalPhysicsSceneClassPointer); auto& staticAnimList = helper->GetStaticAnimList(); return gcnew PhysClassRefMultiListClass(IntPtr(&staticAnimList)); } IMultiListClass^ PhysicsSceneClass::CollisionRegionList::get() { auto helper = reinterpret_cast(InternalPhysicsSceneClassPointer); auto& collisionRegionList = helper->GetCollisionRegionList(); return gcnew PhysClassMultiListClass(IntPtr(&collisionRegionList)); } }ryanliaoyz/not-tetris // // Created by ryan on 4/22/20. // #include "Block.h" #include b2Vec2 gravity(0.0f, -1.0f); b2World world(gravity); b2Body* body; std::vector bodies; b2Vec2 position; float32 angle; int current_ = 0; void Block::setup() { //groundbox b2BodyDef groundBodyDef; groundBodyDef.position.Set(0.0f, -10.0f); b2Body* groundBody = world.CreateBody(&groundBodyDef); b2PolygonShape groundBoxbot; groundBoxbot.SetAsBox(1000.0f, 10.1f); groundBody->CreateFixture(&groundBoxbot, 0.0f); b2BodyDef groundBodyDefleft; groundBodyDefleft.position.Set(0.0f, 0.0f); b2Body* groundBodyleft = world.CreateBody(&groundBodyDefleft); b2PolygonShape groundBoxleft; groundBoxleft.SetAsBox(.1f, 10.1f); groundBodyleft->CreateFixture(&groundBoxleft, 0.0f); b2BodyDef groundBodyDefright; groundBodyDefright.position.Set(4.0f, 0.0f); b2Body* groundBodyright = world.CreateBody(&groundBodyDefright); b2PolygonShape groundBoxright; groundBoxright.SetAsBox(.1f, 10.1f); groundBodyright->CreateFixture(&groundBoxright, 0.0f); // generateBox(); } void Block::generateBox() { // b2BodyDef bodyDef; // bodyDef.type = b2_dynamicBody; // bodyDef.position.Set(2.0f, 4.0f); // body = world.CreateBody(&bodyDef); // // b2PolygonShape dynamicBox; // // dynamicBox.SetAsBox(0.1f, 0.1f); // // b2FixtureDef fixtureDef; // fixtureDef.shape = &dynamicBox; // fixtureDef.density = 1.0f; // fixtureDef.friction = 0.3f; // // body->CreateFixture(&fixtureDef); body = generateRandomBlock(); bodies.push_back(body); } b2Body* Block::generateRandomBlock() { b2Body* temp_body; b2BodyDef bodyDef; bodyDef.type = b2_dynamicBody; bodyDef.position.Set(2.0f, 4.0f); temp_body = world.CreateBody(&bodyDef); //left Z shape b2PolygonShape dynamicBox1; b2PolygonShape dynamicBox2; b2PolygonShape dynamicBox3; b2PolygonShape dynamicBox4; b2Vec2 offset1; b2Vec2 offset2; b2Vec2 offset3; b2Vec2 offset4; srand(time(0)); // Initialize random number generator. int id = rand() % 7 + 1; switch (id) { case 1: //left Z shape offset1.x = 0.0f; offset1.y = 0.0f; offset2.x = 0.2f; offset2.y = 0.0f; offset3.x = 0.2f; offset3.y = -0.2f; offset4.x = 0.4; offset4.y = -0.2f; break; case 2: //right Z shape offset1.x = 0.0f; offset1.y = 0.0f; offset2.x = 0.2f; offset2.y = 0.0f; offset3.x = 0.2f; offset3.y = 0.2f; offset4.x = 0.4; offset4.y = 0.2f; break; case 3: //T shape offset1.x = 0.0f; offset1.y = 0.0f; offset2.x = 0.2f; offset2.y = 0.0f; offset3.x = 0.2f; offset3.y = 0.2f; offset4.x = 0.4; offset4.y = 0.0f; break; case 4: //left L shape offset1.x = 0.0f; offset1.y = 0.0f; offset2.x = 0.0f; offset2.y = -0.2f; offset3.x = 0.2f; offset3.y = -0.2f; offset4.x = 0.4; offset4.y = -0.2f; break; case 5: //right L shape offset1.x = 0.0f; offset1.y = 0.0f; offset2.x = 0.2f; offset2.y = 0.0f; offset3.x = 0.4f; offset3.y = 0.0f; offset4.x = 0.4; offset4.y = 0.2f; break; case 6: //I shape offset1.x = 0.0f; offset1.y = 0.0f; offset2.x = 0.2f; offset2.y = 0.0f; offset3.x = 0.2f; offset3.y = 0.0f; offset4.x = 0.4; offset4.y = 0.0f; break; default: // O shape offset1.x = 0.0f; offset1.y = 0.0f; offset2.x = 0.2f; offset2.y = 0.0f; offset3.x = 0.2f; offset3.y = -0.2f; offset4.x = 0.0; offset4.y = -0.2f; } dynamicBox1.SetAsBox(0.1f, 0.1f, offset1, .0f); dynamicBox2.SetAsBox(0.1f, 0.1f, offset2, .0f); dynamicBox3.SetAsBox(0.1f, 0.1f, offset3, .0f); dynamicBox4.SetAsBox(0.1f, 0.1f, offset4, .0f); b2FixtureDef fixtureDef1; b2FixtureDef fixtureDef2; b2FixtureDef fixtureDef3; b2FixtureDef fixtureDef4; fixtureDef1.shape = &dynamicBox1; fixtureDef2.shape = &dynamicBox2; fixtureDef3.shape = &dynamicBox3; fixtureDef4.shape = &dynamicBox4; fixtureDef1.density = 1.0f; fixtureDef1.friction = 0.3f; fixtureDef2.density = 1.0f; fixtureDef2.friction = 0.3f; fixtureDef3.density = 1.0f; fixtureDef3.friction = 0.3f; fixtureDef4.density = 1.0f; fixtureDef4.friction = 0.3f; temp_body->CreateFixture(&fixtureDef1); temp_body->CreateFixture(&fixtureDef2); temp_body->CreateFixture(&fixtureDef3); temp_body->CreateFixture(&fixtureDef4); return temp_body; bodies.push_back(body); } void Block::move(float32 val) { float32 x = body->GetPosition().x + val; b2Vec2 newVec; newVec.x = x; newVec.y = body->GetPosition().y; body->SetTransform(newVec, body->GetAngle()); } void Block::rotate() { body->SetTransform(body->GetPosition(), body->GetAngle() + 0.1f); } void Block::step(float32 f, int32 s, int32 t) { world.Step(f, s, t); position = bodies[current_]->GetPosition(); angle = bodies[current_]->GetAngle(); // printf("%4.2f %4.2f %4.2f\n", position.x, position.y, angle); } b2Vec2 Block::getPosition() { return position; } float32 Block::getAngle() { return angle; } int Block::getcurrent() { return current_; } void Block::setcurrent(int i) { current_ = i; } std::vector Block::getBodies() { return bodies; } b2Body *Block::getCurrentBody() { return body; } void Block::deleteBody(int line) { int upperbound = line * 40 + 20; int lowerbound = upperbound - 40; for (b2Body* b = world.GetBodyList(); b; b = b->GetNext()) { for (b2Fixture* f = b->GetFixtureList(); f; f = f->GetNext()) { b2PolygonShape* s = reinterpret_cast(f->GetShape()); b2Body* temp = f->GetBody(); int size = s->GetVertexCount(); std::vector intersects(size); std::vector vx(size); std::vector vy(size); for (int i = 0; i < size; i++) { vx[i] = temp->GetWorldPoint(s->GetVertex(i)).x * 200; vy[i] = temp->GetWorldPoint(s->GetVertex(i)).y * 200; } for (int i = 0; i < size; i++) { int loc; if (i < size - 1) { loc = i + 1; } else { loc = 0; } float32 x1 = vx[i]; float32 y1 = vy[i]; float32 x2 = vx[loc]; float32 y2 = vy[loc]; float32 intersect = findIntersect(x1, x2, y1, y2, upperbound); if (intersect <= 0 || intersect > 800) { break; } else { intersects.push_back(intersect); } } break; } } } float32 Block::findIntersect(float32 x1, float32 x2, float32 y1, float32 y2, float32 height) { float32 intersection; float32 m1, c1, m2, c2; float32 dx, dy; m1 = 0; c1 = height; dx = x2 - x1; dy = y2 - y1; m2 = dy / dx; c2 = y2 - m2 * x2; if (m1 - m2 == 0) { return 0; } return (c2 - c1) / (m1 - m2); } void Block::reset() { for (b2Body* b = world.GetBodyList(); b; b = b->GetNext()) { world.DestroyBody(b); } bodies.clear(); // generateBox(); } MandelbrotSet/src/Main.cpp #include #include #include #include #include "include/Core.h" #include "include/Application.h" #include "vendor/vulkan/include/vulkan.h" #undef APIENTRY INT WINAPI wWinMain( HINSTANCE hInstance, HINSTANCE hPreviousInstance, PWSTR pCmdLine, INT cmdShow) { VulkanApp* application = new VulkanApp(VulkanApp::ERenderMethod::Graphics, hInstance, cmdShow); if (application->Initialize()) { if (application->Run()) { } else { printf("Failed to run application properly\n"); delete application; return EXIT_FAILURE; } if (application->Shutdown()) { /* Everything went well up to this point.. weird.. */ } else { printf("Failed to shutdown application properly\n"); delete application; return EXIT_FAILURE; } } else { printf("Failed to initialize application\n"); delete application; return EXIT_FAILURE; } /* Application Initialize */ printf("Shutting down. . .\n"); delete application; return EXIT_SUCCESS; } // Copyright 2016 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 #include #include #include #include #include #include #include #include //--needed for tf2::Matrix3x3 #include "competition.h" #include "utils.h" #include "gantry_control.h" #include "agv_control.h" #include "camera_listener.h" #include "rwa_implementation.h" #include #include #include #define GET_VARIABLE_NAME(Variable) (#Variable) template // we can make this generic for any container [1] struct container_hash { std::size_t operator()(Container const& c) const { return boost::hash_range(c.begin(), c.end()); } }; int main(int argc, char ** argv) { ros::init(argc, argv, "rwa3_node"); ros::NodeHandle node; ros::AsyncSpinner spinner(8); spinner.start(); Competition comp(node); comp.init(); std::string c_state = comp.getCompetitionState(); comp.getClock(); GantryControl gantry(node); gantry.init(); gantry.goToPresetLocation(gantry.start_); CameraListener cam_listener(node); AGVControl agv_control(node); RWAImplementation rwa(node, cam_listener, gantry, comp, agv_control); bool gaps_found = false; if (!gaps_found) // this if block needs to be before rwa.InitRegionDictionaryDependingOnSituation() call { gaps_found = rwa.detectGaps(); } while(ros::ok()) { ROS_INFO_STREAM("Starting while loop..."); rwa.processOrder(); ros::Duration(1.0).sleep(); // added for RWA5, try to deal with incosistency conveyor==1 when not and also bouncing to agv1 and start rwa.InitRegionDictionaryDependingOnSituation(); // Initialize region (shelf + upper or lower) dictionary depending on situation. if (rwa.checkConveyor()) continue; if (rwa.buildKit()) continue; rwa.checkAgvErrors(); ros::Duration(0.5).sleep(); if (rwa.competition_over()) break; // auto dirs = rwa.lane_handler.queryLanes(); // ROS_INFO_STREAM("--------------"); // for (int i{AllLanesHandler::LEFT}; i <= AllLanesHandler::RIGHT; i++) { // std::string prompt{""}; // if (dirs[i] == 0) prompt = "Traveling away from conveyor"; // else if (dirs[i] == 1) prompt = "Traveling towards conveyor"; // else prompt = "Direction unknown. Likely no obstacle in lane"; // ROS_INFO_STREAM("Lane " << i << ", Dir " << dirs[i] << ", " << prompt); // } // ROS_INFO_STREAM("--------------"); // ros::Duration(1).sleep(); } comp.endCompetition(); spinner.stop(); ros::shutdown(); return 0; } // // This simple program is used to generate the constants // for the cppints program // all of constants are defined as macro // fenglai liu // #include #include #include #include #include "boost/lexical_cast.hpp" using boost::lexical_cast; using namespace std; int main() { cout << "/*******************************************************" << endl; cout << " *THIS FILE PROVIDES CONSTANTS FOR THE CPPINTS PROGRAM *" << endl; cout << " *ALL CONSTANTS HAVE 18 DECIMALS ACCURACY *" << endl; cout << " *******************************************************/" << endl; cout << endl << endl << endl; // generate the number of 2m+1 cout << "/*******************************************************" << endl; cout << " * CONSTANTS 1/(2M+1) M FROM 0 TO 200 *" << endl; cout << " *******************************************************/" << endl; string mainpart = "ONEOVER"; for(int i=0; i<=200; i++) { long double r = i; long double result = 1.0E0/(2.0E0*r+1.0E0); string n = lexical_cast(2*i+1); string name = mainpart + n; printf("#define %-20s %-20.18Lf\n", name.c_str(), result); } cout << endl << endl << endl; // generate other constants cout << "/*******************************************************" << endl; cout << " * OTHER CONSTANTS *" << endl; cout << " *******************************************************/" << endl; long double c = 1.0; long double pi = 4.0*atan(c); printf("#ifndef PI\n"); printf("#define %-20s %-20.18Lf\n", "PI", pi); printf("#endif\n"); long double result = 2.0E0/(sqrt(pi)); printf("#define %-20s %-20.18Lf\n", "TWOOVERSQRTPI", result); return 0; } SpartanJ/eepp #include #include #include #include #include #include #include #include #include #include #include #include #include namespace EE { namespace UI { UITextView* UITextView::New() { return eeNew( UITextView, () ); } UITextView* UITextView::NewWithTag( const std::string& tag ) { return eeNew( UITextView, ( tag ) ); } UITextView::UITextView( const std::string& tag ) : UIWidget( tag ), mRealAlignOffset( 0.f, 0.f ), mSelCurInit( 0 ), mSelCurEnd( 0 ), mLastSelCurInit( 0 ), mLastSelCurEnd( 0 ), mFontLineCenter( 0 ), mSelecting( false ) { mTextCache = Text::New(); UITheme* theme = getUISceneNode()->getUIThemeManager()->getDefaultTheme(); if ( NULL != theme && NULL != theme->getDefaultFont() ) { setFont( theme->getDefaultFont() ); } if ( NULL == getFont() ) { if ( NULL != getUISceneNode()->getUIThemeManager()->getDefaultFont() ) { setFont( getUISceneNode()->getUIThemeManager()->getDefaultFont() ); } else { Log::error( "UITextView::UITextView : Created a without a defined font." ); } } if ( NULL != theme ) { setFontSize( theme->getDefaultFontSize() ); } else { setFontSize( getUISceneNode()->getUIThemeManager()->getDefaultFontSize() ); } applyDefaultTheme(); } UITextView::UITextView() : UITextView( "textview" ) {} UITextView::~UITextView() { eeSAFE_DELETE( mTextCache ); } Uint32 UITextView::getType() const { return UI_TYPE_TEXTVIEW; } bool UITextView::isType( const Uint32& type ) const { return UITextView::getType() == type ? true : UIWidget::isType( type ); } void UITextView::draw() { if ( mVisible && 0.f != mAlpha ) { UINode::draw(); if ( mTextCache->getTextWidth() ) { drawSelection( mTextCache ); if ( isClipped() ) { clipSmartEnable( mScreenPos.x + mPaddingPx.Left, mScreenPos.y + mPaddingPx.Top, mSize.getWidth() - mPaddingPx.Left - mPaddingPx.Right, mSize.getHeight() - mPaddingPx.Top - mPaddingPx.Bottom ); } mTextCache->setAlign( getFlags() ); mTextCache->draw( (Float)mScreenPosi.x + (int)mRealAlignOffset.x + (int)mPaddingPx.Left, mFontLineCenter + (Float)mScreenPosi.y + (int)mRealAlignOffset.y + (int)mPaddingPx.Top, Vector2f::One, 0.f, getBlendMode() ); if ( isClipped() ) { clipSmartDisable(); } } } } Graphics::Font* UITextView::getFont() const { return mTextCache->getFont(); } UITextView* UITextView::setFont( Graphics::Font* font ) { if ( NULL != font && mTextCache->getFont() != font ) { mTextCache->setFont( font ); mFontStyleConfig.Font = font; recalculate(); onFontChanged(); notifyLayoutAttrChange(); invalidateDraw(); } return this; } Uint32 UITextView::getFontSize() const { return mTextCache->getCharacterSize(); } Uint32 UITextView::getPixelsFontSize() const { return mTextCache->getCharacterSizePx(); } UITextView* UITextView::setFontSize( const Uint32& characterSize ) { if ( mTextCache->getCharacterSize() != characterSize ) { mFontStyleConfig.CharacterSize = characterSize; mTextCache->setFontSize( characterSize ); recalculate(); onFontStyleChanged(); notifyLayoutAttrChange(); invalidateDraw(); } return this; } const Uint32& UITextView::getFontStyle() const { return mFontStyleConfig.Style; } const Float& UITextView::getOutlineThickness() const { return mFontStyleConfig.OutlineThickness; } UITextView* UITextView::setOutlineThickness( const Float& outlineThickness ) { if ( mFontStyleConfig.OutlineThickness != outlineThickness ) { mTextCache->setOutlineThickness( outlineThickness ); mFontStyleConfig.OutlineThickness = outlineThickness; recalculate(); onFontStyleChanged(); notifyLayoutAttrChange(); invalidateDraw(); } return this; } const Color& UITextView::getOutlineColor() const { return mFontStyleConfig.OutlineColor; } UITextView* UITextView::setOutlineColor( const Color& outlineColor ) { if ( mFontStyleConfig.OutlineColor != outlineColor ) { mFontStyleConfig.OutlineColor = outlineColor; Color newColor( outlineColor.r, outlineColor.g, outlineColor.b, outlineColor.a * mAlpha / 255.f ); mTextCache->setOutlineColor( newColor ); onFontStyleChanged(); invalidateDraw(); } return this; } UITextView* UITextView::setFontStyle( const Uint32& fontStyle ) { if ( mFontStyleConfig.Style != fontStyle ) { mTextCache->setStyle( fontStyle ); mFontStyleConfig.Style = fontStyle; recalculate(); onFontStyleChanged(); notifyLayoutAttrChange(); invalidateDraw(); } return this; } const String& UITextView::getText() { if ( mFlags & UI_WORD_WRAP ) return mString; return mTextCache->getString(); } UITextView* UITextView::setText( const String& text ) { if ( mString != text ) { mString = text; mTextCache->setString( mString ); recalculate(); onTextChanged(); notifyLayoutAttrChange(); } return this; } const Color& UITextView::getFontColor() const { return mFontStyleConfig.FontColor; } UITextView* UITextView::setFontColor( const Color& color ) { if ( mFontStyleConfig.FontColor != color ) { mFontStyleConfig.FontColor = color; Color newColor( color.r, color.g, color.b, color.a * mAlpha / 255.f ); mTextCache->setFillColor( newColor ); invalidateDraw(); } return this; } UITextView* UITextView::setFontFillColor( const Color& color, Uint32 from, Uint32 to ) { Color newColor( color.r, color.g, color.b, color.a * mAlpha / 255.f ); mTextCache->setFillColor( newColor, from, to ); invalidateDraw(); return this; } const Text* UITextView::getTextCache() const { return mTextCache; } const Vector2f& UITextView::getRealAlignOffset() const { return mRealAlignOffset; } const Color& UITextView::getFontShadowColor() const { return mFontStyleConfig.ShadowColor; } UITextView* UITextView::setFontShadowColor( const Color& color ) { if ( mFontStyleConfig.ShadowColor != color ) { mFontStyleConfig.ShadowColor = color; Color newColor( color.r, color.g, color.b, color.a * mAlpha / 255.f ); mTextCache->setShadowColor( newColor ); onFontStyleChanged(); invalidateDraw(); } return this; } const Color& UITextView::getSelectionBackColor() const { return mFontStyleConfig.FontSelectionBackColor; } UITextView* UITextView::setSelectionBackColor( const Color& color ) { if ( mFontStyleConfig.FontSelectionBackColor != color ) { mFontStyleConfig.FontSelectionBackColor = color; onFontStyleChanged(); invalidateDraw(); } return this; } void UITextView::autoShrink() { if ( mFlags & UI_WORD_WRAP ) { shrinkText( mSize.getWidth() ); } } void UITextView::shrinkText( const Uint32& maxWidth ) { if ( mFlags & UI_WORD_WRAP ) { mTextCache->setString( mString ); } mTextCache->shrinkText( maxWidth ); invalidateDraw(); } void UITextView::onAutoSize() { if ( ( mFlags & UI_AUTO_SIZE && 0 == getSize().getWidth() ) ) { setInternalPixelsSize( Sizef( mTextCache->getTextWidth(), mTextCache->getTextHeight() ) ); } if ( mWidthPolicy == SizePolicy::WrapContent ) { setInternalPixelsWidth( (int)mTextCache->getTextWidth() + mPaddingPx.Left + mPaddingPx.Right ); } if ( mHeightPolicy == SizePolicy::WrapContent ) { setInternalPixelsHeight( (int)mTextCache->getTextHeight() + mPaddingPx.Top + mPaddingPx.Bottom ); } } void UITextView::alignFix() { switch ( Font::getHorizontalAlign( getFlags() ) ) { case UI_HALIGN_CENTER: mRealAlignOffset.x = ( Float )( ( Int32 )( ( mSize.x - mPaddingPx.Left - mPaddingPx.Right ) / 2 - mTextCache->getTextWidth() / 2 ) ); break; case UI_HALIGN_RIGHT: mRealAlignOffset.x = ( (Float)mSize.x - mPaddingPx.Left - mPaddingPx.Right - (Float)mTextCache->getTextWidth() ); break; case UI_HALIGN_LEFT: mRealAlignOffset.x = 0; break; } switch ( Font::getVerticalAlign( getFlags() ) ) { case UI_VALIGN_CENTER: mRealAlignOffset.y = ( Float )( ( Int32 )( ( mSize.y - mPaddingPx.Top - mPaddingPx.Bottom ) / 2 - mTextCache->getTextHeight() / 2 ) ) - 1; break; case UI_VALIGN_BOTTOM: mRealAlignOffset.y = ( (Float)mSize.y - mPaddingPx.Top - mPaddingPx.Bottom - (Float)mTextCache->getTextHeight() ); break; case UI_VALIGN_TOP: mRealAlignOffset.y = 0; break; } } Uint32 UITextView::onFocusLoss() { UIWidget::onFocusLoss(); selCurEnd( selCurInit() ); onSelectionChange(); return 1; } void UITextView::onSizeChange() { recalculate(); UINode::onSizeChange(); } void UITextView::onTextChanged() { sendCommonEvent( Event::OnTextChanged ); invalidateDraw(); } void UITextView::onFontChanged() { sendCommonEvent( Event::OnFontChanged ); invalidateDraw(); } void UITextView::onFontStyleChanged() { sendCommonEvent( Event::OnFontStyleChanged ); invalidateDraw(); } void UITextView::onAlphaChange() { Color color( getFontColor() ); Color newColor( color.r, color.g, color.b, color.a * mAlpha / 255.f ); mTextCache->setFillColor( newColor ); color = getFontShadowColor(); newColor = Color( color.r, color.g, color.b, color.a * mAlpha / 255.f ); mTextCache->setShadowColor( newColor ); color = getOutlineColor(); newColor = Color( color.r, color.g, color.b, color.a * mAlpha / 255.f ); mTextCache->setOutlineColor( newColor ); invalidateDraw(); } void UITextView::setTheme( UITheme* Theme ) { UIWidget::setTheme( Theme ); onThemeLoaded(); } Float UITextView::getTextWidth() { return mTextCache->getTextWidth(); } Float UITextView::getTextHeight() { return mTextCache->getTextHeight(); } const int& UITextView::getNumLines() const { return mTextCache->getNumLines(); } Vector2f UITextView::getAlignOffset() const { return PixelDensity::pxToDp( mRealAlignOffset ); } Uint32 UITextView::onMouseDoubleClick( const Vector2i& Pos, const Uint32& Flags ) { if ( isTextSelectionEnabled() && ( Flags & EE_BUTTON_LMASK ) ) { Vector2f nodePos( Vector2f( Pos.x, Pos.y ) ); worldToNode( nodePos ); nodePos = PixelDensity::dpToPx( nodePos ) - mRealAlignOffset - Vector2f( mPaddingPx.Left, mPaddingPx.Top ); nodePos.x = eemax( 0.f, nodePos.x ); nodePos.y = eemax( 0.f, nodePos.y ); Int32 curPos = mTextCache->findCharacterFromPos( nodePos.asInt() ); if ( -1 != curPos ) { Int32 tSelCurInit, tSelCurEnd; mTextCache->findWordFromCharacterIndex( curPos, tSelCurInit, tSelCurEnd ); selCurInit( tSelCurEnd ); selCurEnd( tSelCurInit ); onSelectionChange(); mSelecting = false; } } return UIWidget::onMouseDoubleClick( Pos, Flags ); } Uint32 UITextView::onMouseClick( const Vector2i& Pos, const Uint32& Flags ) { if ( isTextSelectionEnabled() && ( Flags & EE_BUTTON_LMASK ) ) { mSelecting = false; } return UIWidget::onMouseClick( Pos, Flags ); } Uint32 UITextView::onMouseDown( const Vector2i& Pos, const Uint32& Flags ) { if ( NULL != getEventDispatcher() && isTextSelectionEnabled() && ( Flags & EE_BUTTON_LMASK ) && getEventDispatcher()->getMouseDownNode() == this ) { Vector2f nodePos( Vector2f( Pos.x, Pos.y ) ); worldToNode( nodePos ); nodePos = PixelDensity::dpToPx( nodePos ) - mRealAlignOffset - Vector2f( mPaddingPx.Left, mPaddingPx.Top ); nodePos.x = eemax( 0.f, nodePos.x ); nodePos.y = eemax( 0.f, nodePos.y ); Int32 curPos = mTextCache->findCharacterFromPos( nodePos.asInt() ); if ( -1 != curPos ) { if ( !mSelecting ) { selCurInit( curPos ); selCurEnd( curPos ); } else { selCurInit( curPos ); } onSelectionChange(); } mSelecting = true; } return UIWidget::onMouseDown( Pos, Flags ); } void UITextView::drawSelection( Text* textCache ) { if ( selCurInit() != selCurEnd() ) { Int32 init = eemin( selCurInit(), selCurEnd() ); Int32 end = eemax( selCurInit(), selCurEnd() ); if ( init < 0 && end > (Int32)textCache->getString().size() ) { return; } Int32 lastEnd; Vector2f initPos, endPos; if ( mLastSelCurInit != selCurInit() || mLastSelCurEnd != selCurEnd() ) { mSelPosCache.clear(); mLastSelCurInit = selCurInit(); mLastSelCurEnd = selCurEnd(); do { initPos = textCache->findCharacterPos( init ); lastEnd = textCache->getString().find_first_of( '\n', init ); if ( lastEnd < end && -1 != lastEnd ) { endPos = textCache->findCharacterPos( lastEnd ); init = lastEnd + 1; } else { endPos = textCache->findCharacterPos( end ); lastEnd = end; } mSelPosCache.push_back( SelPosCache( initPos, endPos ) ); } while ( end != lastEnd ); } if ( !mSelPosCache.empty() ) { Primitives P; P.setColor( mFontStyleConfig.FontSelectionBackColor ); Float vspace = textCache->getFont()->getFontHeight( textCache->getCharacterSizePx() ); for ( size_t i = 0; i < mSelPosCache.size(); i++ ) { initPos = mSelPosCache[i].initPos; endPos = mSelPosCache[i].endPos; P.drawRectangle( Rectf( mScreenPos.x + initPos.x + mRealAlignOffset.x + mPaddingPx.Left, mScreenPos.y + initPos.y + mRealAlignOffset.y + mPaddingPx.Top, mScreenPos.x + endPos.x + mRealAlignOffset.x + mPaddingPx.Left, mScreenPos.y + endPos.y + vspace + mRealAlignOffset.y + mPaddingPx.Top ) ); } } } } bool UITextView::isTextSelectionEnabled() const { return 0 != ( mFlags & UI_TEXT_SELECTION_ENABLED ); } void UITextView::setTextSelection( const bool& active ) { if ( active ) { mFlags |= UI_TEXT_SELECTION_ENABLED; } else { mFlags &= ~UI_TEXT_SELECTION_ENABLED; } } const UIFontStyleConfig& UITextView::getFontStyleConfig() const { return mFontStyleConfig; } void UITextView::setFontStyleConfig( const UIFontStyleConfig& fontStyleConfig ) { mFontStyleConfig = fontStyleConfig; setFont( fontStyleConfig.getFont() ); setFontSize( fontStyleConfig.getFontCharacterSize() ); setFontColor( fontStyleConfig.getFontColor() ); setFontShadowColor( fontStyleConfig.getFontShadowColor() ); setOutlineThickness( fontStyleConfig.getOutlineThickness() ); setOutlineColor( fontStyleConfig.getOutlineColor() ); setFontStyle( fontStyleConfig.getFontStyle() ); onFontStyleChanged(); } void UITextView::selCurInit( const Int32& init ) { if ( mSelCurInit != init ) { mSelCurInit = init; invalidateDraw(); } } void UITextView::selCurEnd( const Int32& end ) { if ( mSelCurEnd != end ) { mSelCurEnd = end; invalidateDraw(); } } Int32 UITextView::selCurInit() { return mSelCurInit; } Int32 UITextView::selCurEnd() { return mSelCurEnd; } void UITextView::onAlignChange() { UIWidget::onAlignChange(); alignFix(); } void UITextView::onSelectionChange() { mTextCache->invalidateColors(); if ( selCurInit() != selCurEnd() ) { Color color( mFontStyleConfig.getFontSelectedColor() ); color.a = mFontStyleConfig.getFontSelectedColor().a * mAlpha / 255.f; mTextCache->setFillColor( color, eemin( selCurInit(), selCurEnd() ), eemax( selCurInit(), selCurEnd() ) - 1 ); } else { Color color( mFontStyleConfig.getFontColor() ); color.a = mFontStyleConfig.getFontColor().a * mAlpha / 255.f; mTextCache->setFillColor( color ); } invalidateDraw(); } const Int32& UITextView::getFontLineCenter() { return mFontLineCenter; } void UITextView::recalculate() { int fontHeight = mTextCache->getCharacterSizePx(); mFontLineCenter = eefloor( ( Float )( ( mTextCache->getFont()->getLineSpacing( fontHeight ) - fontHeight ) / 2 ) ); autoShrink(); onAutoSize(); alignFix(); resetSelCache(); } void UITextView::resetSelCache() { mLastSelCurInit = mLastSelCurEnd = 0; onSelectionChange(); } bool UITextView::applyProperty( const StyleSheetProperty& attribute ) { if ( !checkPropertyDefinition( attribute ) ) return false; switch ( attribute.getPropertyDefinition()->getPropertyId() ) { case PropertyId::Text: if ( NULL != mUISceneNode ) setText( mUISceneNode->getTranslatorString( attribute.asString() ) ); break; case PropertyId::Color: setFontColor( attribute.asColor() ); break; case PropertyId::ShadowColor: setFontShadowColor( attribute.asColor() ); break; case PropertyId::SelectionColor: mFontStyleConfig.FontSelectedColor = attribute.asColor(); break; case PropertyId::SelectionBackColor: setSelectionBackColor( attribute.asColor() ); break; case PropertyId::FontFamily: { Font* font = FontManager::instance()->getByName( attribute.asString() ); if ( NULL != font && font->loaded() ) { setFont( font ); } break; } case PropertyId::FontSize: setFontSize( lengthFromValueAsDp( attribute ) ); break; case PropertyId::FontStyle: { Uint32 flags = attribute.asFontStyle(); if ( flags & UI_WORD_WRAP ) { mFlags |= UI_WORD_WRAP; flags &= ~UI_WORD_WRAP; autoShrink(); } setFontStyle( flags ); break; } case PropertyId::Wordwrap: if ( attribute.asBool() ) mFlags |= UI_WORD_WRAP; else mFlags &= ~UI_WORD_WRAP; autoShrink(); break; case PropertyId::TextStrokeWidth: setOutlineThickness( lengthFromValue( attribute ) ); break; case PropertyId::TextStrokeColor: setOutlineColor( attribute.asColor() ); break; case PropertyId::TextSelection: setTextSelection( attribute.asBool() ); break; case PropertyId::TextAlign: { std::string align = String::toLower( attribute.value() ); if ( align == "center" ) setTextAlign( UI_HALIGN_CENTER ); else if ( align == "left" ) setTextAlign( UI_HALIGN_LEFT ); else if ( align == "right" ) setTextAlign( UI_HALIGN_RIGHT ); break; } default: return UIWidget::applyProperty( attribute ); } return true; } std::string UITextView::getPropertyString( const PropertyDefinition* propertyDef, const Uint32& propertyIndex ) { if ( NULL == propertyDef ) return ""; switch ( propertyDef->getPropertyId() ) { case PropertyId::Text: return getText().toUtf8(); case PropertyId::Color: return getFontColor().toHexString(); case PropertyId::ShadowColor: return getFontShadowColor().toHexString(); case PropertyId::SelectionColor: return mFontStyleConfig.FontSelectedColor.toHexString(); case PropertyId::SelectionBackColor: return getSelectionBackColor().toHexString(); case PropertyId::FontFamily: return NULL != getFont() ? getFont()->getName() : ""; case PropertyId::FontSize: return String::format( "%ddp", getFontSize() ); case PropertyId::FontStyle: return Text::styleFlagToString( getFontStyle() ); case PropertyId::TextStrokeWidth: return String::toString( PixelDensity::dpToPx( getOutlineThickness() ) ); case PropertyId::TextStrokeColor: return getOutlineColor().toHexString(); case PropertyId::Wordwrap: return mFlags & UI_WORD_WRAP ? "true" : "false"; case PropertyId::TextSelection: return isTextSelectionEnabled() ? "true" : "false"; case PropertyId::TextAlign: return Font::getHorizontalAlign( getFlags() ) == UI_HALIGN_CENTER ? "center" : ( Font::getHorizontalAlign( getFlags() ) == UI_HALIGN_RIGHT ? "right" : "left" ); default: return UIWidget::getPropertyString( propertyDef, propertyIndex ); } } void UITextView::setTextAlign( const Uint32& align ) { mFlags &= ~( UI_HALIGN_CENTER | UI_HALIGN_RIGHT ); mFlags |= align; onAlignChange(); } }} // namespace EE::UI #include "sha3_384.hpp" #include // This example attempts to show how to use 2-to-1 SHA3-384 hash function ! int main(int argc, char** argv) { // $ python3 // >>> a = [0xff] * 48 // // first input digest constexpr sycl::uchar digest_0[48] = { 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 }; // >>> b = [0x0f] * 48 // // second input digest constexpr sycl::uchar digest_1[48] = { 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15 }; // >>> c = a + b // >>> import hashlib // >>> list(hashlib.sha3_384(bytes(c)).digest()) // // final output digest after merging two input digests constexpr sycl::uchar digest_2[48] = { 25, 254, 93, 230, 2, 191, 78, 51, 238, 228, 239, 160, 231, 101, 38, 216, 38, 8, 135, 59, 34, 169, 154, 20, 221, 245, 50, 59, 27, 9, 21, 234, 249, 223, 45, 73, 214, 0, 146, 51, 25, 83, 0, 0, 111, 210, 47, 206 }; sycl::default_selector s{}; sycl::device d{ s }; sycl::context c{ d }; sycl::queue q{ c, d }; // so that input digests can be transferred from host to device ( by runtime ) sycl::uchar* in = static_cast( sycl::malloc_shared(sizeof(digest_0) + sizeof(digest_1), q)); // so that output digest can be transferred from device to host ( by runtime ) sycl::uchar* out = static_cast(sycl::malloc_shared(sizeof(digest_2), q)); // copy both input digests to device memory q.memcpy(in + 0, digest_0, sizeof(digest_0)).wait(); q.memcpy(in + sizeof(digest_0), digest_1, sizeof(digest_1)).wait(); // compute 2-to-1 hash q.single_task( [=]() { sha3_384::hash(in, out); }); q.wait(); // finally assert ! for (size_t i = 0; i < sizeof(digest_2); i++) { assert(*(out + i) == digest_2[i]); } // deallocate resources ! sycl::free(in, q); sycl::free(out, q); return EXIT_SUCCESS; } Gabs48/tigrillo2 #ifndef SHAPE_SHIFTER_FACTORY_HPP #define SHAPE_SHIFTER_FACTORY_HPP #include #include "PlotJuggler/any.hpp" class RosIntrospectionFactory{ public: static RosIntrospectionFactory &get(); static void registerMessage(const std::string& topic_name, const std::string &md5sum, const std::string& datatype, const std::string& definition ); static const RosIntrospection::ShapeShifter* getShapeShifter(const std::string& topic_name); static const std::set &getTopicList(); static RosIntrospection::Parser& parser() { return get()._parser; } static bool isRegistered(const std::string& topic_name) { return get()._topics.count(topic_name) != 0; } private: RosIntrospectionFactory() = default; std::map _ss_map; std::set _topics; RosIntrospection::Parser _parser; }; //--------------------------------------------- inline RosIntrospectionFactory& RosIntrospectionFactory::get() { static RosIntrospectionFactory instance; return instance; } // return true if added inline void RosIntrospectionFactory::registerMessage(const std::string &topic_name, const std::string &md5sum, const std::string &datatype, const std::string &definition) { auto& instance = get(); if( instance._ss_map.find(topic_name) == instance._ss_map.end() ) { RosIntrospection::ShapeShifter msg; msg.morph(md5sum, datatype,definition); instance._ss_map.insert( std::make_pair(topic_name, std::move(msg) )); instance._topics.insert( topic_name ); parser().registerMessageDefinition( topic_name, RosIntrospection::ROSType(datatype), definition); } } inline const RosIntrospection::ShapeShifter* RosIntrospectionFactory::getShapeShifter(const std::string &topic_name) { auto& instance = get(); auto it = instance._ss_map.find( topic_name ); return ( it == instance._ss_map.end()) ? nullptr : &(it->second); } inline const std::set &RosIntrospectionFactory::getTopicList() { return get()._topics; } #endif // SHAPE_SHIFTER_FACTORY_HPP test/disabled_tests.cpp //====================================================================== //----------------------------------------------------------------------- /** * @file disabled_tests.cpp * @brief also_run_disabled_tests option test * * @author t.shirayanagi * @par copyright * Copyright (C) 2012-2021, \n * This software is released under the new BSD License, * see LICENSE */ //----------------------------------------------------------------------- //====================================================================== //====================================================================== // include #include "iutest.hpp" #include "disabled_tests_decl.cpp" #ifdef UNICODE int wmain(int argc, wchar_t* argv[]) #else int main(int argc, char* argv[]) #endif { IUTEST_INIT(&argc, argv); const int ret = IUTEST_RUN_ALL_TESTS(); IUTEST_TERMINATE_ON_FAILURE( ::iutest::UnitTest::GetInstance()->disabled_test_count() == expected_disable_test_count ); #if !defined(IUTEST_USE_GTEST) || (defined(GTEST_MINOR) && GTEST_MINOR >= 0x07) IUTEST_TERMINATE_ON_FAILURE( ::iutest::UnitTest::GetInstance()->reportable_disabled_test_count() == expected_disable_test_count ); #endif #if !defined(IUTEST_USE_GTEST) IUTEST_TERMINATE_ON_FAILURE( ::iutest::UnitTest::GetInstance()->skip_test_count() == expected_disable_test_count ); #endif return ret; } #if defined(_WIN32) #define UNICODE #include #include #include #include "WindowProcedureApiWin32.hpp" using namespace System; using namespace System::Windows::Forms; core_export_ extern HINSTANCE __instance; intptr Native::CheckBoxApi::Create(const System::Windows::Forms::CheckBox& checkBox) { HWND handle = CreateWindowEx(0, WC_BUTTON, checkBox.Text().w_str().c_str(), WS_CHILD | BS_3STATE, checkBox.Left, checkBox.Top, checkBox.Width, checkBox.Height, (HWND)checkBox.Parent()().Handle(), (HMENU)0, __instance, (LPVOID)NULL); WindowProcedure::SetWindowTheme(handle); WindowProcedure::DefWindowProcs[(intptr)handle] = (WNDPROC)SetWindowLongPtr(handle, GWLP_WNDPROC, (LONG_PTR)WindowProcedure::WndProc); /// @todo to remove after create SetFont method... PostMessage(handle, WM_SETFONT, WPARAM((HFONT)GetStockObject(DEFAULT_GUI_FONT)), TRUE); return (intptr)handle; } void Native::CheckBoxApi::SetAutoCheck(const System::Windows::Forms::CheckBox& checkBox) { } void Native::CheckBoxApi::SetChecked(const System::Windows::Forms::CheckBox& checkBox) { SendMessage((HWND)checkBox.Handle(), BM_SETCHECK, (int32)checkBox.CheckState(), 0); } #endif 3rdparty/stout-borrowed-ptr #include #include #include #include #include "gtest/gtest.h" #include "gmock/gmock.h" #include "stout/borrowable.h" using std::atomic; using std::function; using std::string; using std::thread; using std::unique_ptr; using std::vector; using stout::Borrowable; using stout::borrowed_ptr; using testing::_; using testing::MockFunction; TEST(BorrowTest, Borrow) { Borrowable s("hello world"); MockFunction mock; EXPECT_CALL(mock, Call()) .Times(1); borrowed_ptr borrowed = s.Borrow(); s.Watch(mock.AsStdFunction()); } TEST(BorrowTest, ConstBorrow) { Borrowable s("hello world"); MockFunction mock; EXPECT_CALL(mock, Call()) .Times(1); borrowed_ptr borrowed = s.Borrow(); s.Watch(mock.AsStdFunction()); } TEST(BorrowTest, Reborrow) { Borrowable s("hello world"); MockFunction mock; EXPECT_CALL(mock, Call()) .Times(1); borrowed_ptr borrowed = s.Borrow(); s.Watch(mock.AsStdFunction()); borrowed_ptr reborrow = borrowed.reborrow(); EXPECT_TRUE(reborrow); } TEST(BorrowTest, Emplace) { struct S { S(borrowed_ptr i) : i_(std::move(i)) {} borrowed_ptr i_; }; Borrowable i(42); MockFunction mock; EXPECT_CALL(mock, Call()) .Times(1); vector> vector; vector.emplace_back(i.Borrow()); i.Watch(mock.AsStdFunction()); } TEST(BorrowTest, MultipleBorrows) { Borrowable s("hello world"); MockFunction mock; EXPECT_CALL(mock, Call()) .Times(0); vector> borrows; borrows.push_back(s.Borrow()); borrows.push_back(s.Borrow()); borrows.push_back(s.Borrow()); borrows.push_back(s.Borrow()); s.Watch(mock.AsStdFunction()); vector threads; atomic wait(true); while (!borrows.empty()) { threads.push_back(thread([&wait, borrowed = std::move(borrows.back())]() { while (wait.load()) {} // ... destructor will invoke borrowed.relinquish(). })); borrows.pop_back(); } EXPECT_CALL(mock, Call()) .Times(1); wait.store(false); for (auto&& thread : threads) { thread.join(); } } TEST(BorrowTest, MultipleConstBorrows) { Borrowable s("hello world"); MockFunction mock; EXPECT_CALL(mock, Call()) .Times(0); vector> borrows; borrows.push_back(s.Borrow()); borrows.push_back(s.Borrow()); borrows.push_back(s.Borrow()); borrows.push_back(s.Borrow()); s.Watch(mock.AsStdFunction()); vector threads; atomic wait(true); while (!borrows.empty()) { threads.push_back(thread([&wait, borrowed = std::move(borrows.back())]() { while (wait.load()) {} // ... destructor will invoke borrowed.relinquish(). })); borrows.pop_back(); } EXPECT_CALL(mock, Call()) .Times(1); wait.store(false); for (auto&& thread : threads) { thread.join(); } } #include "Request.h" Request::Request(String method, String path, std::map headers, String body) { this->method = method; this->path = path; this->headers = headers; this->body = body; } String Request::getMethod() { return this->method; } String Request::getPath() { return this->path; } std::map Request::getHeaders() { return this->headers; } String Request::getBody() { return this->body; } source/dummy-includes/gui/windowing-support/message-dispatching.include.cpp #include Zehvogel/julea-adios2 /* * Distributed under the OSI-approved Apache License, Version 2.0. See * accompanying file Copyright.txt for details. * * JULEA engine using the JULEA storage framework to handle lower I/O. * * Created on: Jul 26, 2019 * Author: */ #ifndef ADIOS2_ENGINE_JULEADBREADER_TCC_ #define ADIOS2_ENGINE_JULEADBREADER_TCC_ #include "JuleaDBReader.h" #include // #include // #include namespace adios2 { namespace core { namespace engine { // TODO: check whether this is sufficient for strings! // is separate data stored which needs to be read or just metadata? template <> void JuleaDBReader::GetSyncCommon(Variable &variable, std::string *data) { if (m_Verbosity == 5) { std::cout << "\n______________GetSync String_____________________" << std::endl; std::cout << "Julea DB Reader " << m_ReaderRank << " Namespace: " << m_Name << " Variable name: " << variable.m_Name << std::endl; } for (typename Variable::Info &blockInfo : variable.m_BlocksInfo) { long unsigned int dataSize = 0; guint32 buffer_len = 0; std::string nameSpace = m_Name; std::string stepBlockID; gpointer md_buffer = nullptr; if (m_UseKeysForBPLS) { stepBlockID = g_strdup_printf("%lu_%lu", variable.m_StepsStart, variable.m_BlockID); // std::cout << "variable.m... stepBlockID: " << stepBlockID << // std::endl; } else { stepBlockID = g_strdup_printf("%lu_%lu", m_CurrentStep, m_CurrentBlockID); // std::cout << "m_Current... stepBlockID: " << stepBlockID << // std::endl; } // std::cout << "blocksInfos.size: " << variable.m_BlocksInfo.size() // << std::endl; // GetBlockMetadataFromJulea(nameSpace, variable.m_Name, &md_buffer, // &buffer_len, stepBlockID); // DeserializeBlockMetadata(variable, md_buffer, variable.m_BlockID, // blockInfo); if (variable.m_SingleValue) { std::cout << "Single value" << std::endl; return; } m_CurrentBlockID++; } } template void JuleaDBReader::GetSyncCommon(Variable &variable, T *data) { if (m_Verbosity == 5) { std::cout << "\n______________GetSync T_____________________" << std::endl; std::cout << "Julea DB Reader " << m_ReaderRank << " Reached Get Sync Common (T, T)" << std::endl; std::cout << "Julea Reader " << m_ReaderRank << " Namespace: " << m_Name << std::endl; std::cout << "Julea Reader " << m_ReaderRank << " Variable name: " << variable.m_Name << std::endl; } if (variable.m_SingleValue) { std::cout << "FIXME: read single value" << std::endl; // FIXME: just read metadata from DB. value is stored in there. // m_BP3Deserializer.GetValueFromMetadata(variable, data); // return; } typename Variable::Info &blockInfo = InitVariableBlockInfo(variable, data); SetVariableBlockInfo(variable, blockInfo); if (variable.m_ShapeID == ShapeID::LocalArray) { ReadBlock(variable, data, variable.m_BlockID); } else if (variable.m_ShapeID == ShapeID::GlobalArray) { ReadVariableBlocks(variable); } variable.m_BlocksInfo.pop_back(); } template void JuleaDBReader::GetDeferredCommon(Variable &variable, T *data) { if (m_Verbosity == 5) { std::cout << "Julea DB Reader " << m_ReaderRank << " GetDeferred(" << variable.m_Name << ")\n"; } // store data pointer in related blockinfo to be called in perform gets // InitVariableBlockInfo(variable, data); typename Variable::Info &blockInfo = InitVariableBlockInfo(variable, data); SetVariableBlockInfo(variable, blockInfo); size_t size = variable.m_BlocksInfo.size(); // FIXME: if (variable.m_ShapeID == ShapeID::LocalArray) { variable.m_BlocksInfo[size - 1].BlockID = variable.m_BlockID; } else if (variable.m_ShapeID == ShapeID::GlobalArray) { // variable.m_BlocksInfo[size-1].BlockID = // blockInfo.StepBlockSubStreamsInfo[m_CurrentStep].SubStreamID; // variable.m_BlocksInfo[size - 1].BlockID = // blockInfo.StepBlockSubStreamsInfo[m_CurrentStep][m_ReaderRank] // .SubStreamID; } m_DeferredVariables.insert(variable.m_Name); } template void JuleaDBReader::ReadBlock(Variable &variable, T *data, size_t blockID) { if (m_Verbosity == 5) { std::cout << "\n ReadBlock" << std::endl; std::cout << "Julea Reader " << m_ReaderRank << " Namespace: " << m_Name << " Variable name: " << variable.m_Name << std::endl; } size_t step = 0; std::string stepBlockID; Dims count; std::string nameSpace = m_Name; long unsigned int dataSize = 0; guint32 buffer_len = 0; gpointer md_buffer = nullptr; // std::cout << "unique entry ID: " << // variable.m_AvailableStepBlockIndexOffsets[m_CurrentStep] << std::endl; if (m_UseKeysForBPLS) { stepBlockID = g_strdup_printf("%lu_%lu", variable.m_StepsStart, blockID); step = variable.m_StepsStart; // std::cout << "variable.m... stepBlockID: " << stepBlockID << // std::endl; } else { stepBlockID = g_strdup_printf("%lu_%lu", m_CurrentStep, blockID); step = m_CurrentStep; // std::cout << "variable.m... stepBlockID: " << stepBlockID << // std::endl; } /** only retrieve Count. Everything is only needed for bp3 and bp4 to * determine block position in buffer and for AllStepsBlockInfo for bpls */ auto entryID = variable.m_AvailableStepBlockIndexOffsets[step + 1][blockID]; GetCountFromBlockMetadata(nameSpace, variable.m_Name, step, blockID, &count, entryID, variable.m_SingleValue, data); if (variable.m_SingleValue) { // FIXME: get Value from DB std::cout << "Single value" << std::endl; return; } size_t numberElements = helper::GetTotalSize(count); dataSize = numberElements * variable.m_ElementSize; size_t offset = 0; // FIXME: // DBGetVariableDataFromJulea(variable, data, nameSpace, offset, dataSize, // stepBlockID); } template void JuleaDBReader::ReadBlockMD(typename core::Variable::Info &blockInfo, size_t blockID) { // if (m_Verbosity == 5) // { // std::cout << "\n ReadBlock" << std::endl; // std::cout << "Julea Reader " << m_ReaderRank << " Namespace: " << // m_Name // << " Variable name: " << variable.m_Name << std::endl; // } // size_t step = 0; // std::string stepBlockID; // Dims count; // std::string nameSpace = m_Name; // long unsigned int dataSize = 0; // guint32 buffer_len = 0; // gpointer md_buffer = nullptr; // //TODO: needed here? // if (m_UseKeysForBPLS) // { // // stepBlockID = // // g_strdup_printf("%lu_%lu", variable.m_StepsStart, blockID); // // step = variable.m_StepsStart; // // std::cout << "variable.m... stepBlockID: " << stepBlockID << // // std::endl; // } // else // { // // stepBlockID = g_strdup_printf("%lu_%lu", m_CurrentStep, blockID); // // step = m_CurrentStep; // // std::cout << "variable.m... stepBlockID: " << stepBlockID << // // std::endl; // } // /** only retrieve Count. Everything is only needed for bp3 and bp4 to // * determine block position in buffer and for AllStepsBlockInfo for bpls // */ // auto entryID = variable.m_AvailableStepBlockIndexOffsets[m_CurrentStep + // 1][blockID]; GetCountFromBlockMetadata(nameSpace, variable.m_Name, // m_CurrentStep, blockID, &count, // entryID, variable.m_SingleValue, data); } template void JuleaDBReader::ReadVariableBlocks(Variable &variable) { if (m_Verbosity == 5) { std::cout << "\n__________ReadVariableBlocks_____________" << std::endl; std::cout << "Julea DB Reader " << m_ReaderRank << " Namespace: " << m_Name << " Variable name: " << variable.m_Name << std::endl; } for (typename Variable::Info &blockInfo : variable.m_BlocksInfo) { // std::cout << "blocksInfos.size: " << variable.m_BlocksInfo.size() // << std::endl; // long unsigned int dataSize = 0; // guint32 buffer_len = 0; // std::string nameSpace = m_Name; // std::string stepBlockID; // gpointer md_buffer = nullptr; // size_t block = 0; // size_t step = 0; // if (m_UseKeysForBPLS) // { // stepBlockID = g_strdup_printf("%lu_%lu", variable.m_StepsStart, // variable.m_BlockID); // step = variable.m_StepsStart; // block = variable.m_BlockID; // std::cout << "variable.m... stepBlockID: " << stepBlockID << // std::endl; // } // else // { // stepBlockID = // g_strdup_printf("%lu_%lu", m_CurrentStep, m_CurrentBlockID); // step = m_CurrentStep; // block = m_CurrentBlockID; // std::cout << "m_Current... stepBlockID: " << stepBlockID << // std::endl; // } // // GetBlockMetadataFromJulea(nameSpace, variable.m_Name, &md_buffer, // // &buffer_len, stepBlockID); // // DeserializeBlockMetadata(variable, md_buffer, variable.m_BlockID, // // blockInfo); // DBGetBlockMetadata(variable,nameSpace,step, block, blockInfo); // // variable.m_BlocksInfo.push_back(blockInfo); // variable.m_BlocksInfo[block] = blockInfo; // // variable.m_BlocksInfo[0] = blockInfo; // if (variable.m_SingleValue) // { // std::cout << "Single value" << std::endl; // return; // } // size_t numberElements = helper::GetTotalSize(blockInfo.Count); // dataSize = numberElements * variable.m_ElementSize; // T *data = blockInfo.Data; // if (m_UseKeysForBPLS) // { // DBGetVariableDataFromJulea(variable, data, nameSpace, dataSize, // variable.m_StepsStart, variable.m_BlockID); // } // else // { // DBGetVariableDataFromJulea(variable, data, nameSpace, dataSize, // m_CurrentStep, m_CurrentBlockID); // } // m_CurrentBlockID++; for (typename Variable::Info &blockInfo : variable.m_BlocksInfo) { T *originalBlockData = blockInfo.Data; for (const auto &stepPair : blockInfo.StepBlockSubStreamsInfo) { for (const helper::SubStreamBoxInfo &subStreamBoxInfo : stepPair.second) { if (subStreamBoxInfo.ZeroBlock) { continue; } // char *buffer = nullptr; std::string stepBlockID; std::string nameSpace = m_Name; long unsigned int dataSize = 0; // TODO: -1 because BP stuff starts at 1 size_t offset = subStreamBoxInfo.Seeks.first; size_t step = stepPair.first - 1; // std::cout << "stepPair.first: " << stepPair.first // << std::endl; // std::cout // << "unique entry ID: " << subStreamBoxInfo.SubStreamID // << std::endl; // std::string entryID = subStreamBoxInfo.SubStreamID; // FIXME: implement // stepBlockID = g_strdup_printf("%lu_%lu", step, // subStreamBoxInfo.SubStreamID); // std::cout << "stepBlockID: " << stepBlockID << std::endl; // variable.m_AvailableStepBlockIndexOffsets if (m_UseKeysForBPLS) { // DBGetVariableDataFromJulea( // variable, data, nameSpace, dataSize, // variable.m_StepsStart, variable.m_BlockID); } else { // size_t numberElements = helper::GetTotalSize(count); // dataSize = numberElements * variable.m_ElementSize; dataSize = subStreamBoxInfo.Seeks.second - subStreamBoxInfo.Seeks.first; // std::cout << "dataSize: " << dataSize << std::endl; // T data[dataSize]; std::vector data = std::vector(dataSize); DBGetVariableDataFromJulea( variable, data.data(), nameSpace, offset, dataSize, subStreamBoxInfo.SubStreamID); const Dims blockInfoStart = (variable.m_ShapeID == ShapeID::LocalArray && blockInfo.Start.empty()) ? Dims(blockInfo.Count.size(), 0) : blockInfo.Start; helper::ClipContiguousMemory( blockInfo.Data, blockInfoStart, blockInfo.Count, (char *)data.data(), subStreamBoxInfo.BlockBox, subStreamBoxInfo.IntersectionBox, true, false, false); // helper::ClipVector(m_ThreadBuffers[threadID][0], // subStreamBoxInfo.Seeks.first, // subStreamBoxInfo.Seeks.second); } m_CurrentBlockID++; } // substreams loop // advance pointer to next step blockInfo.Data += helper::GetTotalSize(blockInfo.Count); } // steps loop blockInfo.Data = originalBlockData; } // deferred blocks loop } } template std::map::Info>> JuleaDBReader::AllStepsBlocksInfo(const core::Variable &variable) const { std::map::Info>> allStepsBlocksInfo; // Explanation for this ugly assumption is in the header file. This assumes // that only bpls calls AllStepsBlocksInfo. for now that should be ok now // = 21.04.2020 m_UseKeysForBPLS = true; // SetUseKeysForBPLS(true); for (const auto &pair : variable.m_AvailableStepBlockIndexOffsets) { const size_t step = pair.first; const std::vector &blockPositions = pair.second; if (m_Verbosity == 5) { std::cout << "\n__________AllStepsBlocksInfo_____________" << std::endl; std::cout << "Julea DB Reader " << m_ReaderRank << " Namespace: " << m_Name << " Variable name: " << variable.m_Name << std::endl; std::cout << "--- step: " << step << " blockPositions: " << blockPositions.data()[0] << std::endl; } // bp3 index starts at 1 allStepsBlocksInfo[step - 1] = BlocksInfoCommon(variable, blockPositions, step - 1); } return allStepsBlocksInfo; } template std::vector::Info> JuleaDBReader::BlocksInfoCommon(const core::Variable &variable, const std::vector &blocksIndexOffsets, size_t step) const { if (m_Verbosity == 5) { std::cout << "\n__________BlocksInfoCommon_____________" << std::endl; std::cout << "Julea DB Reader " << m_ReaderRank << " Namespace: " << m_Name << " Variable name: " << variable.m_Name << std::endl; std::cout << "--- step: " << step << std::endl; std::cout << "blocksIndexOffsets.size(): " << blocksIndexOffsets.size() << std::endl; } std::vector::Info> blocksInfo; blocksInfo.reserve(blocksIndexOffsets.size()); typename core::Variable::Info blockInfo; for (size_t i = 0; i < blocksIndexOffsets.size(); i++) { guint32 buffer_len = 0; gpointer md_buffer = nullptr; auto nameSpace = m_Name; long unsigned int dataSize = 0; auto stepBlockID = g_strdup_printf("%lu_%lu", step, i); auto entryID = blocksIndexOffsets[i]; typename core::Variable::Info info = // *DBGetBlockMetadata(variable, nameSpace, step, i, entryID); *DBGetBlockMetadata(variable, entryID); info.IsReverseDims = false; info.Step = step; blocksInfo.push_back(info); } return blocksInfo; } // FIXME: not yet tested! template std::vector::Info>> JuleaDBReader::AllRelativeStepsBlocksInfo( const core::Variable &variable) const { if (m_Verbosity == 5) { std::cout << "\n__________AllRelativeStepsBlocksInfo_____________" << std::endl; std::cout << "Julea DB Reader " << m_ReaderRank << " Namespace: " << m_Name << " Variable name: " << variable.m_Name << std::endl; } std::vector::Info>> allRelativeStepsBlocksInfo( variable.m_AvailableStepBlockIndexOffsets.size()); size_t relativeStep = 0; for (const auto &pair : variable.m_AvailableStepBlockIndexOffsets) { const std::vector &blockPositions = pair.second; allRelativeStepsBlocksInfo[relativeStep] = BlocksInfoCommon(variable, blockPositions, relativeStep); ++relativeStep; } return allRelativeStepsBlocksInfo; } template std::vector::Info> JuleaDBReader::BlocksInfo(const core::Variable &variable, const size_t step) const { if (m_Verbosity == 5) { std::cout << "\n__________BlocksInfo_____________" << std::endl; std::cout << "Julea DB Reader " << m_ReaderRank << " Namespace: " << m_Name << " Variable name: " << variable.m_Name << std::endl; } // bp4 format starts at 1 auto itStep = variable.m_AvailableStepBlockIndexOffsets.find(step + 1); if (itStep == variable.m_AvailableStepBlockIndexOffsets.end()) { return std::vector::Info>(); std::cout << " --- step not found in m_AvailableStepBlockIndexOffsets " << std::endl; } return BlocksInfoCommon(variable, itStep->second, step); } template typename core::Variable::Info & JuleaDBReader::InitVariableBlockInfo(core::Variable &variable, T *data) { if (m_Verbosity == 5) { std::cout << "\n__________InitVariableBlockInfo_____________" << std::endl; std::cout << "Julea DB Reader " << m_ReaderRank << " Namespace: " << m_Name << " Variable name: " << variable.m_Name << std::endl; } const size_t stepsStart = variable.m_StepsStart; const size_t stepsCount = variable.m_StepsCount; // std::cout << "stepsStart: " << stepsStart << std::endl; // std::cout << "stepsCount: " << stepsCount << std::endl; // if (m_DebugMode) if (m_Verbosity == 5) { const auto &indices = variable.m_AvailableStepBlockIndexOffsets; const size_t maxStep = indices.rbegin()->first; if (stepsStart + 1 > maxStep) { throw std::invalid_argument( "ERROR: steps start " + std::to_string(stepsStart) + " from SetStepsSelection or BeginStep is larger than " "the maximum available step " + std::to_string(maxStep - 1) + " for variable " + variable.m_Name + ", in call to Get\n"); } auto itStep = std::next(indices.begin(), stepsStart); for (size_t i = 0; i < stepsCount; ++i) { if (itStep == indices.end()) { throw std::invalid_argument( "ERROR: offset " + std::to_string(i) + " from steps start " + std::to_string(stepsStart) + " in variable " + variable.m_Name + " is beyond the largest available step = " + std::to_string(maxStep - 1) + ", check Variable SetStepSelection argument stepsCount " "(random access), or " "number of BeginStep calls (streaming), in call to Get"); } ++itStep; } } if (variable.m_SelectionType == SelectionType::WriteBlock) { const std::vector::Info> blocksInfo = JuleaDBReader::BlocksInfo(variable, stepsStart); if (variable.m_BlockID >= blocksInfo.size()) { throw std::invalid_argument( "ERROR: invalid blockID " + std::to_string(variable.m_BlockID) + " from steps start " + std::to_string(stepsStart) + " in variable " + variable.m_Name + ", check argument to Variable::SetBlockID, in call " "to Get\n"); } // switch to bounding box for global array if (variable.m_ShapeID == ShapeID::GlobalArray) { const Dims &start = blocksInfo[variable.m_BlockID].Start; const Dims &count = blocksInfo[variable.m_BlockID].Count; variable.SetSelection({start, count}); } else if (variable.m_ShapeID == ShapeID::LocalArray) { // TODO from Adios people! "keep Count for block updated" variable.m_Count = blocksInfo[variable.m_BlockID].Count; } } return variable.SetBlockInfo(data, stepsStart, stepsCount); } template void JuleaDBReader::SetVariableBlockInfo( core::Variable &variable, typename core::Variable::Info &blockInfo) const { if (m_Verbosity == 5) { std::cout << "\n______________SetVariableBlockInfo_____________________" << std::endl; std::cout << "Julea DB Reader " << m_ReaderRank << " Reached SetVariableBlockInfo" << std::endl; std::cout << "Julea Reader " << m_ReaderRank << " Namespace: " << m_Name << std::endl; std::cout << "Julea Reader " << m_ReaderRank << " Variable name: " << variable.m_Name << std::endl; } // auto lf_SetSubStreamInfoLocalArray = // [&](const std::string &variableName, const Box &selectionBox, // typename core::Variable::Info &blockInfo, const size_t step, // const size_t blockIndexOffset, const BufferSTL &bufferSTL, // const bool isRowMajor) // { // const std::vector &buffer = bufferSTL.m_Buffer; // size_t position = blockIndexOffset; // const Characteristics blockCharacteristics = // ReadElementIndexCharacteristics(buffer, position, // TypeTraits::type_enum, // false, // m_Minifooter.IsLittleEndian); // // check if they intersect // helper::SubStreamBoxInfo subStreamInfo; // if (helper::GetTotalSize(blockCharacteristics.Count) == 0) // { // subStreamInfo.ZeroBlock = true; // } // // if selection box start is not empty = local selection // subStreamInfo.BlockBox = // helper::StartEndBox(Dims(blockCharacteristics.Count.size(), 0), // blockCharacteristics.Count); // if (!selectionBox.first.empty()) // selection start count was defined // { // subStreamInfo.IntersectionBox = // helper::IntersectionBox(selectionBox, // subStreamInfo.BlockBox); // } // else // read the entire block // { // subStreamInfo.IntersectionBox = subStreamInfo.BlockBox; // } // if (subStreamInfo.IntersectionBox.first.empty() || // subStreamInfo.IntersectionBox.second.empty()) // { // return; // } // const size_t dimensions = blockCharacteristics.Count.size(); // if (dimensions != blockInfo.Count.size()) // { // throw std::invalid_argument( // "ERROR: block Count (available) and " // "selection Count (requested) number of dimensions, do not " // "match " // "when reading local array variable " + // variableName + ", in call to Get"); // } // const Dims readInCount = m_ReverseDimensions // ? // Dims(blockCharacteristics.Count.rbegin(), // blockCharacteristics.Count.rend()) // : blockCharacteristics.Count; // const Dims blockInfoStart = blockInfo.Start.empty() // ? Dims(blockInfo.Count.size(), 0) // : blockInfo.Start; // for (size_t i = 0; i < dimensions; ++i) // { // if (blockInfoStart[i] + blockInfo.Count[i] > readInCount[i]) // { // throw std::invalid_argument( // "ERROR: selection Start " + // helper::DimsToString(blockInfoStart) + " and Count " + // helper::DimsToString(blockInfo.Count) + // " (requested) is out of bounds of (available) local" // " Count " + // helper::DimsToString(readInCount) + // " , when reading local array variable " + variableName + // ", in call to Get"); // } // } // subStreamInfo.Seeks.first = // sizeof(T) * helper::LinearIndex(subStreamInfo.BlockBox, // subStreamInfo.IntersectionBox.first, // isRowMajor); // subStreamInfo.Seeks.second = // sizeof(T) * (helper::LinearIndex( // subStreamInfo.BlockBox, // subStreamInfo.IntersectionBox.second, // isRowMajor) + // 1); // const size_t payloadOffset = // blockCharacteristics.Statistics.PayloadOffset; // const BPOpInfo &bpOp = blockCharacteristics.Statistics.Op; // // if they intersect get info Seeks (first: start, second: // // count) depending on operation info // if (bpOp.IsActive) // { // lf_SetSubStreamInfoOperations(bpOp, payloadOffset, subStreamInfo, // m_IsRowMajor); // } // else // { // // make it absolute if no operations // subStreamInfo.Seeks.first += payloadOffset; // subStreamInfo.Seeks.second += payloadOffset; // } // subStreamInfo.SubStreamID = // static_cast(blockCharacteristics.Statistics.FileIndex); // blockInfo.StepBlockSubStreamsInfo[step].push_back( // std::move(subStreamInfo)); // }; auto lf_SetSubStreamInfoGlobalArray = [&](const std::string &variableName, const Box &selectionBox, typename core::Variable::Info &blockInfo, const size_t step, const size_t blockIndexOffset, const bool isRowMajor) { // const std::vector &buffer = bufferSTL.m_Buffer; size_t position = blockIndexOffset; // info = blockCharacteristics in BP3 typename core::Variable::Info info = *DBGetBlockMetadata(variable, blockIndexOffset); // check if they intersect helper::SubStreamBoxInfo subStreamInfo; if (helper::GetTotalSize(info.Count) == 0) { subStreamInfo.ZeroBlock = true; } subStreamInfo.BlockBox = helper::StartEndBox(info.Start, info.Count); // std::cout << "BlockBox: ([" // << helper::VectorToCSV(subStreamInfo.BlockBox.first) << "], // [" // << helper::VectorToCSV(subStreamInfo.BlockBox.second) << // "])" // << std::endl; // std::cout << "selectionBox: ([" // << helper::VectorToCSV(selectionBox.first) << "], [" // << helper::VectorToCSV(selectionBox.second) << "])" // << std::endl; subStreamInfo.IntersectionBox = helper::IntersectionBox(selectionBox, subStreamInfo.BlockBox); if (subStreamInfo.IntersectionBox.first.empty() || subStreamInfo.IntersectionBox.second.empty()) { return; } const size_t dimensions = info.Shape.size(); if (dimensions != blockInfo.Shape.size()) { throw std::invalid_argument( "ERROR: block Shape (available) and " "selection Shape (requested) number of dimensions, do not " "match " "when reading global array variable " + variableName + ", in call to Get"); } Dims readInShape = info.Shape; // if (m_ReverseDimensions) // { // std::reverse(readInShape.begin(), readInShape.end()); // } for (size_t i = 0; i < dimensions; ++i) { if (blockInfo.Start[i] + blockInfo.Count[i] > readInShape[i]) { throw std::invalid_argument( "ERROR: selection Start " + helper::DimsToString(blockInfo.Start) + " and Count " + helper::DimsToString(blockInfo.Count) + " (requested) is out of bounds of (available) " "Shape " + helper::DimsToString(readInShape) + " , when reading global array variable " + variableName + ", in call to Get"); } } // relative position subStreamInfo.Seeks.first = sizeof(T) * helper::LinearIndex(subStreamInfo.BlockBox, subStreamInfo.IntersectionBox.first, isRowMajor); // std::cout << "Seeks.first: " << subStreamInfo.Seeks.first << // std::endl; subStreamInfo.Seeks.second = sizeof(T) * (helper::LinearIndex( subStreamInfo.BlockBox, subStreamInfo.IntersectionBox.second, isRowMajor) + 1); // std::cout << "Seeks.second: " << subStreamInfo.Seeks.second // << std::endl; // const size_t payloadOffset = // blockCharacteristics.Statistics.PayloadOffset; // const auto &bp3Op = blockCharacteristics.Statistics.Op; // // if they intersect get info Seeks (first: start, second: // // count) depending on operation info // if (bp3Op.IsActive) // { // lf_SetSubStreamInfoOperations(bp3Op, payloadOffset, // subStreamInfo, // m_IsRowMajor); // } // else // { // // make it absolute if no operations // subStreamInfo.Seeks.first += payloadOffset; // subStreamInfo.Seeks.second += payloadOffset; // } // subStreamInfo.SubStreamID = // static_cast(blockCharacteristics.Statistics.FileIndex); // blockInfo.StepBlockSubStreamsInfo[step].push_back( // std::move(subStreamInfo)); // make it absolute if no operations // subStreamInfo.Seeks.first += 42; // subStreamInfo.Seeks.second += 42; subStreamInfo.SubStreamID = static_cast(blockIndexOffset); // subStreamInfo.SubStreamID = static_cast(info.BlockID); // static_cast(blockCharacteristics.Statistics.FileIndex); blockInfo.StepBlockSubStreamsInfo[step].push_back( std::move(subStreamInfo)); }; // BODY OF FUNCTIONS STARTS HERE const std::map> &indices = variable.m_AvailableStepBlockIndexOffsets; // last param is m_reverseDims const Box selectionBox = helper::StartEndBox(blockInfo.Start, blockInfo.Count, false); auto itStep = std::next(indices.begin(), blockInfo.StepsStart); for (size_t i = 0; i < blockInfo.StepsCount; ++i) { const size_t step = itStep->first; const std::vector &blockOffsets = itStep->second; if (variable.m_ShapeID == ShapeID::GlobalArray) { for (const size_t blockOffset : blockOffsets) { // std::cout << "blockOffset: " << blockOffset << std::endl; lf_SetSubStreamInfoGlobalArray(variable.m_Name, selectionBox, blockInfo, step, blockOffset, true); } } else if (variable.m_ShapeID == ShapeID::LocalArray) { // lf_SetSubStreamInfoLocalArray( // variable.m_Name, selectionBox, blockInfo, step, // blockOffsets[blockInfo.BlockID], m_Metadata, m_IsRowMajor); } ++itStep; } } } // end namespace engine } // end namespace core } // end namespace adios2 #endif // ADIOS2_ENGINE_JULEADBREADER_TCC_ // 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 "tink/jwt/jwt_validator.h" #include "tink/jwt/raw_jwt.h" #include "gtest/gtest.h" #include "absl/strings/escaping.h" #include "tink/util/test_matchers.h" #include "tink/util/test_util.h" using ::crypto::tink::test::IsOk; namespace crypto { namespace tink { TEST(JwtValidator, ExpiredTokenNotOK) { absl::Time now = absl::Now(); util::StatusOr jwt_or = RawJwtBuilder().SetExpiration(now - absl::Seconds(100)).Build(); ASSERT_THAT(jwt_or.status(), IsOk()); RawJwt jwt = jwt_or.ValueOrDie(); JwtValidator validator = JwtValidatorBuilder().Build(); EXPECT_FALSE(validator.Validate(jwt).ok()); } TEST(JwtValidator, NotExpiredTokenOK) { absl::Time now = absl::Now(); util::StatusOr jwt_or = RawJwtBuilder().SetExpiration(now + absl::Seconds(100)).Build(); ASSERT_THAT(jwt_or.status(), IsOk()); RawJwt jwt = jwt_or.ValueOrDie(); JwtValidator validator = JwtValidatorBuilder().Build(); EXPECT_THAT(validator.Validate(jwt), IsOk()); } TEST(JwtValidator, ClockSkewIsToLarge) { JwtValidatorBuilder builder = JwtValidatorBuilder(); EXPECT_FALSE(builder.SetClockSkew(absl::Minutes(11)).ok()); } TEST(JwtValidator, RecentlyExpiredTokenWithClockSkewOK) { absl::Time now = absl::Now(); util::StatusOr jwt_or = RawJwtBuilder().SetExpiration(now - absl::Seconds(100)).Build(); ASSERT_THAT(jwt_or.status(), IsOk()); RawJwt jwt = jwt_or.ValueOrDie(); JwtValidatorBuilder builder = JwtValidatorBuilder(); ASSERT_THAT(builder.SetClockSkew(absl::Seconds(200)), IsOk()); JwtValidator validator = builder.Build(); EXPECT_THAT(validator.Validate(jwt), IsOk()); } TEST(JwtValidator, NotBeforeInTheFutureNotOK) { absl::Time now = absl::Now(); util::StatusOr jwt_or = RawJwtBuilder().SetNotBefore(now + absl::Seconds(100)).Build(); ASSERT_THAT(jwt_or.status(), IsOk()); RawJwt jwt = jwt_or.ValueOrDie(); JwtValidator validator = JwtValidatorBuilder().Build(); EXPECT_FALSE(validator.Validate(jwt).ok()); } TEST(JwtValidator, NotBeforeInThePastOK) { absl::Time now = absl::Now(); util::StatusOr jwt_or = RawJwtBuilder().SetNotBefore(now - absl::Seconds(100)).Build(); ASSERT_THAT(jwt_or.status(), IsOk()); RawJwt jwt = jwt_or.ValueOrDie(); JwtValidator validator = JwtValidatorBuilder().Build(); EXPECT_THAT(validator.Validate(jwt), IsOk()); } TEST(JwtValidator, NotBeforeInTheNearFutureWithClockSkewOK) { absl::Time now = absl::Now(); util::StatusOr jwt_or = RawJwtBuilder().SetNotBefore(now + absl::Seconds(100)).Build(); ASSERT_THAT(jwt_or.status(), IsOk()); RawJwt jwt = jwt_or.ValueOrDie(); JwtValidatorBuilder builder = JwtValidatorBuilder(); ASSERT_THAT(builder.SetClockSkew(absl::Seconds(200)), IsOk()); JwtValidator validator = builder.Build(); EXPECT_THAT(validator.Validate(jwt), IsOk()); } TEST(JwtValidator, RequiresIssuerButNotIssuerNotOK) { util::StatusOr jwt_or = RawJwtBuilder().Build(); ASSERT_THAT(jwt_or.status(), IsOk()); RawJwt jwt = jwt_or.ValueOrDie(); JwtValidator validator = JwtValidatorBuilder().SetIssuer("issuer").Build(); EXPECT_FALSE(validator.Validate(jwt).ok()); } TEST(JwtValidator, InvalidIssuerNotOK) { util::StatusOr jwt_or = RawJwtBuilder().SetIssuer("unknown").Build(); ASSERT_THAT(jwt_or.status(), IsOk()); RawJwt jwt = jwt_or.ValueOrDie(); JwtValidator validator = JwtValidatorBuilder().SetIssuer("issuer").Build(); EXPECT_FALSE(validator.Validate(jwt).ok()); } TEST(JwtValidator, CorrectIssuerOK) { util::StatusOr jwt_or = RawJwtBuilder().SetIssuer("issuer").Build(); ASSERT_THAT(jwt_or.status(), IsOk()); RawJwt jwt = jwt_or.ValueOrDie(); JwtValidator validator = JwtValidatorBuilder().SetIssuer("issuer").Build(); EXPECT_THAT(validator.Validate(jwt), IsOk()); } TEST(JwtValidator, DontCheckIssuerOK) { util::StatusOr jwt_or = RawJwtBuilder().SetIssuer("issuer").Build(); ASSERT_THAT(jwt_or.status(), IsOk()); RawJwt jwt = jwt_or.ValueOrDie(); JwtValidator validator = JwtValidatorBuilder().Build(); EXPECT_THAT(validator.Validate(jwt), IsOk()); } TEST(JwtValidator, RequiresSubjectButNotSubjectNotOK) { util::StatusOr jwt_or = RawJwtBuilder().Build(); ASSERT_THAT(jwt_or.status(), IsOk()); RawJwt jwt = jwt_or.ValueOrDie(); JwtValidator validator = JwtValidatorBuilder().SetSubject("subject").Build(); EXPECT_FALSE(validator.Validate(jwt).ok()); } TEST(JwtValidator, InvalidSubjectNotOK) { util::StatusOr jwt_or = RawJwtBuilder().SetSubject("unknown").Build(); ASSERT_THAT(jwt_or.status(), IsOk()); RawJwt jwt = jwt_or.ValueOrDie(); JwtValidator validator = JwtValidatorBuilder().SetSubject("subject").Build(); EXPECT_FALSE(validator.Validate(jwt).ok()); } TEST(JwtValidator, CorrectSubjectOK) { util::StatusOr jwt_or = RawJwtBuilder().SetSubject("subject").Build(); ASSERT_THAT(jwt_or.status(), IsOk()); RawJwt jwt = jwt_or.ValueOrDie(); JwtValidator validator = JwtValidatorBuilder().SetSubject("subject").Build(); EXPECT_THAT(validator.Validate(jwt), IsOk()); } TEST(JwtValidator, DontCheckSubjectOK) { util::StatusOr jwt_or = RawJwtBuilder().SetSubject("subject").Build(); ASSERT_THAT(jwt_or.status(), IsOk()); RawJwt jwt = jwt_or.ValueOrDie(); JwtValidator validator = JwtValidatorBuilder().Build(); EXPECT_THAT(validator.Validate(jwt), IsOk()); } TEST(JwtValidator, RequiresAudienceButNotAudienceNotOK) { util::StatusOr jwt_or = RawJwtBuilder().Build(); ASSERT_THAT(jwt_or.status(), IsOk()); RawJwt jwt = jwt_or.ValueOrDie(); JwtValidator validator = JwtValidatorBuilder().SetSubject("subject").Build(); EXPECT_FALSE(validator.Validate(jwt).ok()); } TEST(JwtValidator, InvalidAudienceNotOK) { util::StatusOr jwt_or = RawJwtBuilder().SetSubject("unknown").Build(); ASSERT_THAT(jwt_or.status(), IsOk()); RawJwt jwt = jwt_or.ValueOrDie(); JwtValidator validator = JwtValidatorBuilder().SetAudience("audience").Build(); EXPECT_FALSE(validator.Validate(jwt).ok()); } TEST(JwtValidator, CorrectAudienceOK) { util::StatusOr jwt_or = RawJwtBuilder() .AddAudience("otherAudience") .AddAudience("audience") .Build(); ASSERT_THAT(jwt_or.status(), IsOk()); RawJwt jwt = jwt_or.ValueOrDie(); JwtValidator validator = JwtValidatorBuilder().SetAudience("audience").Build(); EXPECT_THAT(validator.Validate(jwt), IsOk()); } TEST(JwtValidator, AudienceInTokenButNotInValiatorNotOK) { util::StatusOr jwt_or = RawJwtBuilder().AddAudience("audience").Build(); ASSERT_THAT(jwt_or.status(), IsOk()); RawJwt jwt = jwt_or.ValueOrDie(); JwtValidator validator = JwtValidatorBuilder().Build(); EXPECT_FALSE(validator.Validate(jwt).ok()); } TEST(JwtValidator, NoAudienceOK) { util::StatusOr jwt_or = RawJwtBuilder().Build(); ASSERT_THAT(jwt_or.status(), IsOk()); RawJwt jwt = jwt_or.ValueOrDie(); JwtValidator validator = JwtValidatorBuilder().Build(); EXPECT_THAT(validator.Validate(jwt), IsOk()); } TEST(JwtValidator, FixedNowExpiredNotOk) { absl::Time now = absl::Now(); util::StatusOr jwt_or = RawJwtBuilder().SetExpiration(now + absl::Seconds(100)).Build(); ASSERT_THAT(jwt_or.status(), IsOk()); RawJwt jwt = jwt_or.ValueOrDie(); JwtValidator validator = JwtValidatorBuilder().SetFixedNow(now + absl::Seconds(200)).Build(); EXPECT_FALSE(validator.Validate(jwt).ok()); } TEST(JwtValidator, FixedNowNotYetValidNotOk) { absl::Time now = absl::Now(); util::StatusOr jwt_or = RawJwtBuilder().SetNotBefore(now - absl::Seconds(100)).Build(); ASSERT_THAT(jwt_or.status(), IsOk()); RawJwt jwt = jwt_or.ValueOrDie(); JwtValidator validator = JwtValidatorBuilder().SetFixedNow(now - absl::Seconds(200)).Build(); EXPECT_FALSE(validator.Validate(jwt).ok()); } TEST(JwtValidator, FixedNowValidOk) { absl::Time now = absl::FromUnixSeconds(12345); util::StatusOr jwt_or = RawJwtBuilder() .SetExpiration(now + absl::Seconds(100)) .SetNotBefore(now - absl::Seconds(100)) .Build(); ASSERT_THAT(jwt_or.status(), IsOk()); RawJwt jwt = jwt_or.ValueOrDie(); JwtValidator validator = JwtValidatorBuilder().SetFixedNow(now).Build(); EXPECT_THAT(validator.Validate(jwt), IsOk()); } TEST(JwtValidator, CallBuildTwiceOk) { JwtValidatorBuilder builder = JwtValidatorBuilder(); builder.SetIssuer("issuer1"); JwtValidator validator1 = builder.Build(); builder.SetIssuer("issuer2"); JwtValidator validator2 = builder.Build(); util::StatusOr jwt1_or = RawJwtBuilder() .SetIssuer("issuer1") .Build(); ASSERT_THAT(jwt1_or.status(), IsOk()); RawJwt jwt1 = jwt1_or.ValueOrDie(); util::StatusOr jwt2_or = RawJwtBuilder() .SetIssuer("issuer2") .Build(); ASSERT_THAT(jwt2_or.status(), IsOk()); RawJwt jwt2 = jwt2_or.ValueOrDie(); EXPECT_THAT(validator1.Validate(jwt1), IsOk()); EXPECT_FALSE(validator1.Validate(jwt2).ok()); EXPECT_THAT(validator2.Validate(jwt2), IsOk()); EXPECT_FALSE(validator2.Validate(jwt1).ok()); } } // namespace tink } // namespace crypto libui/tableui.cpp /** Copyright 2019 Fornux 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 "tableui.h" #include #include #include #include //Added by qt3to4: #include #include TableItemUI::TableItemUI(QTreeWidget * parent, QTreeWidgetItem * after, QString s1, QString s2) : QTreeWidgetItem(parent, after) { setText(0, s1); setText(1, s2); } void TableItemUI::paintCell(QPainter * painter, const QPalette & colorgroup, int column, int width, int align) { // if (TableUI * const p = static_cast(treeWidget())) // { // int const x = column ? p->columnWidth(column - 1) : 0; // if (p->eRowHeader == TableUI::eReadOnly) // { // QTreeWidgetItem::paintCell(painter, colorgroup, column, width, align); // painter->setPen(Qt::lightGray); // painter->drawLine(width - 1, 0, width - 1, height() - 1); // painter->drawLine(0, height() - 1, width - 1, height() - 1); // if (isSelected() && isVisible() && column != 0) // { // p->pLineEdit->hide(); // p->pLineEdit->setText(text(column)); // p->pLineEdit->selectAll(); // p->pLineEdit->move(x, p->itemRect(this).y()); // p->pLineEdit->resize(width, height()); // p->pLineEdit->show(); // } // } // else if (p->eRowHeader == TableUI::eHeader) // { // QColorGroup headercg = QColorGroup(colorgroup); // headercg.setColor(QColorGroup::Base, colorgroup.background()); // QTreeWidgetItem::paintCell(painter, headercg, column, width, align); // qDrawWinPanel(painter, x, 0, width, height(), headercg, false, 0); // } // } } TableUI::TableUI(QWidget * p, const char * n) : QTreeWidget(p), eRowHeader(eHeader) { pLineEdit = new QLineEdit(viewport()); pLineEdit->hide(); pLineEdit->setReadOnly(true); pLineEdit->setFocusProxy(this); // pLineEdit->setLineWidth(1); // pLineEdit->setFrameShape(QLineEdit::Box); // pLineEdit->setFrameShadow(QLineEdit::Plain); // setSorting(-1); // header()->setResizeEnabled(false); // header()->setMovingEnabled(false); // setSelectionMode(QTreeWidget::Single); setAllColumnsShowFocus(true); // setHScrollBarMode(Q3ScrollView::AlwaysOff); } void TableUI::resizeEvent(QResizeEvent * p) { QTreeWidget::resizeEvent(p); if (eRowHeader == eReadOnly && columnCount()) { // setColumnWidth(columns() - 1, visibleWidth() - (header()->headerWidth() - columnWidth(columns() - 1))); pLineEdit->resize(columnWidth(columnCount() - 1), pLineEdit->height()); } } /* -*- mode: c++; c-basic-offset: 4; indent-tabs-mode: nil -*- this file is part of rcssserver3D Fri May 9 2003 Copyright (C) 2002,2003 Koblenz University Copyright (C) 2003 RoboCup Soccer Server 3D Maintenance Group $Id$ 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., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include "driveaction.h" #include "driveeffector.h" #include #include #include #include #include using namespace boost; using namespace oxygen; using namespace salt; DriveEffector::DriveEffector() : oxygen::Effector(), mForceFactor(60.0), mMaxPower(100.0), mConsumption(1.0/18000.0) { } DriveEffector::~DriveEffector() { } bool DriveEffector::Realize(boost::shared_ptr action) { if (mBody.get() == 0) { return false; } boost::shared_ptr parent = dynamic_pointer_cast(GetParent().lock()); if (parent.get() == 0) { GetLog()->Error() << "ERROR: (DriveEffector) parent node is not derived from BaseNode\n"; return false; } boost::shared_ptr driveAction = dynamic_pointer_cast(action); if (driveAction.get() == 0) { GetLog()->Error() << "ERROR: (DriveEffector) cannot realize an unknown ActionObject\n"; return false; } mForce = driveAction->GetForce(); // cut down the drive power vector to maximum length if (mForce.SquareLength() > mMaxPower * mMaxPower) { mForce.Normalize(); mForce *= mMaxPower; } if (mForceErrorRNG.get() != 0) { mForce[0] = mForce[0] * (*(mForceErrorRNG.get()))() * mForceFactor; mForce[1] = mForce[1] * (*(mForceErrorRNG.get()))() * mForceFactor; mForce[2] = mForce[2] * (*(mForceErrorRNG.get()))() * mForceFactor; } else { mForce = mForce * mForceFactor; } return true; } boost::shared_ptr DriveEffector::GetActionObject(const Predicate& predicate) { if (predicate.name != GetPredicate()) { GetLog()->Error() << "ERROR: (DriveEffector) invalid predicate" << predicate.name << "\n"; return boost::shared_ptr(); } Vector3f force; if (! predicate.GetValue(predicate.begin(), force)) { GetLog()->Error() << "ERROR: (DriveEffector) Vector3f parameter expected\n"; return boost::shared_ptr(new ActionObject(GetPredicate())); } return boost::shared_ptr(new DriveAction(GetPredicate(),force)); } void DriveEffector::OnLink() { SoccerBase::GetTransformParent(*this,mTransformParent); SoccerBase::GetBody(*this,mBody); SoccerBase::GetAgentState(*this,mAgentState); boost::shared_ptr geom = dynamic_pointer_cast(mTransformParent->GetChild("geometry")); mMaxDistance = 0.001; if (geom.get() == 0) { GetLog()->Error() << "ERROR: (DriveEffector) parent node has " << "no 'geometry' sphere child\n"; } else { mMaxDistance += geom->GetRadius(); } } void DriveEffector::OnUnlink() { mForceErrorRNG.reset(); mTransformParent.reset(); mBody.reset(); } void DriveEffector::SetForceFactor(float force_factor) { mForceFactor = salt::gAbs(force_factor); } void DriveEffector::SetSigma(float sigma) { NormalRngPtr rng(new salt::NormalRNG<>(1.0,sigma)); mForceErrorRNG = rng; } void DriveEffector::SetMaxPower(float max_power) { mMaxPower = max_power; } void DriveEffector::PrePhysicsUpdateInternal(float deltaTime) { Effector::PrePhysicsUpdateInternal(deltaTime); if (mBody.get() == 0 || mForce.Length() <= std::numeric_limits::epsilon()) { return; } Vector3f vec = mTransformParent->GetWorldTransform().Pos(); if (vec.z() > mMaxDistance) return; if (mAgentState->ReduceBattery(mForce.Length() * mConsumption)) { mBody->AddForce(SoccerBase::FlipView(mForce,mAgentState->GetTeamIndex())); } } void DriveEffector::SetConsumption(float consume_time) { mConsumption = 1.0 / consume_time; } MJLaukala/UE4FastNoisePlugin // Copyright 1998-2018 Epic Games, Inc. All Rights Reserved. #include "FastNoisePluginEditor.h" #include "ThumbnailRendering/ThumbnailManager.h" #include "FastNoise.h" #include "FastNoiseThumbnailRenderer.h" #include "AssetTypeActions_FastNoise.h" #include "FastNoiseEditor.h" #include "ISettingsModule.h" #define LOCTEXT_NAMESPACE "FFastNoisePluginEditorModule" void FFastNoisePluginEditorModule::StartupModule() { // This code will execute after your module is loaded into memory; the exact timing is specified in the .uplugin file per-module MenuExtensibilityManager = MakeShareable(new FExtensibilityManager); ToolBarExtensibilityManager = MakeShareable(new FExtensibilityManager); IAssetTools& AssetTools = FModuleManager::LoadModuleChecked("AssetTools").Get(); FastNoiseAssetCategoryBit = AssetTools.RegisterAdvancedAssetCategory(FName(TEXT("Fast Noise")), LOCTEXT("FastNoiseAssetCategory", "Fast Noise")); RegisterAssetTypeAction(AssetTools, MakeShareable(new FAssetTypeActions_FastNoise(FastNoiseAssetCategoryBit))); // register settings ISettingsModule* SettingsModule = FModuleManager::GetModulePtr("Settings"); if (SettingsModule != nullptr) { SettingsModule->RegisterSettings("Editor", "ContentEditors", "FastNoisePluginEditor", LOCTEXT("FastNoiseEditorSettingsName", "FastNoise Editor"), LOCTEXT("FastNoiseEditorSettingsDescription", "Configure the look and feel of the Texture Editor."), GetMutableDefault() ); } UThumbnailManager::Get().RegisterCustomRenderer(UFastNoise::StaticClass(), UFastNoiseThumbnailRenderer::StaticClass()); } void FFastNoisePluginEditorModule::ShutdownModule() { // This function may be called during shutdown to clean up your module. For modules that support dynamic reloading, // we call this function before unloading the module. // unregister settings ISettingsModule* SettingsModule = FModuleManager::GetModulePtr("Settings"); if (SettingsModule != nullptr) { SettingsModule->UnregisterSettings("Editor", "ContentEditors", "FastNoisePluginEditor"); } if (UObjectInitialized()) { UThumbnailManager::Get().UnregisterCustomRenderer(UFastNoise::StaticClass()); } // Unregister all the asset types that we registered if (FModuleManager::Get().IsModuleLoaded("AssetTools")) { IAssetTools& AssetTools = FModuleManager::GetModuleChecked("AssetTools").Get(); for (int32 Index = 0; Index < CreatedAssetTypeActions.Num(); ++Index) { AssetTools.UnregisterAssetTypeActions(CreatedAssetTypeActions[Index].ToSharedRef()); } } CreatedAssetTypeActions.Empty(); MenuExtensibilityManager.Reset(); ToolBarExtensibilityManager.Reset(); } TSharedRef FFastNoisePluginEditorModule::CreateFastNoiseEditor(const EToolkitMode::Type Mode, const TSharedPtr& InitToolkitHost, UFastNoise* FastNoise) { TSharedRef NewFastNoiseEditor(new FFastNoiseEditor()); NewFastNoiseEditor->InitFastNoiseEditor(Mode, InitToolkitHost, FastNoise); return NewFastNoiseEditor; } void FFastNoisePluginEditorModule::RegisterAssetTypeAction(IAssetTools& AssetTools, TSharedRef Action) { AssetTools.RegisterAssetTypeActions(Action); CreatedAssetTypeActions.Add(Action); } #undef LOCTEXT_NAMESPACE IMPLEMENT_MODULE(FFastNoisePluginEditorModule, FastNoisePluginEditor)src/cfg_loader.cpp #include #include #include #include "cfg_loader.h" using std::string; using std::vector; using libconfig::Setting; using libconfig::SettingNotFoundException; game::Cfg &game::Cfg::instance() { static Cfg s; return s; } game::Cfg::Cfg(string config_path) { vector actors = {"Mainchar", "Guard", "Teacher", "Fireball", "Stone"}; cfg_.readFile(config_path.c_str()); Setting& root = cfg_.getRoot(); for (const auto& actor_cfg_name : actors) { const auto& curr_root = root[actor_cfg_name]; double speed; char icon; int max_hp; int attack_damage; short color_pair; int max_mana; try { speed = curr_root.lookup("speed"); } catch(const SettingNotFoundException &e) { speed = 0.0; } try { icon = curr_root.lookup("icon").c_str()[0]; } catch(const SettingNotFoundException &e) { icon = '-'; } try { max_hp = curr_root.lookup("hp"); } catch(const SettingNotFoundException &e) { max_hp = 1; } try { attack_damage= curr_root.lookup("attack"); } catch(const SettingNotFoundException &e) { attack_damage = 1; } try { color_pair = static_cast(static_cast(curr_root.lookup("color"))); } catch(const SettingNotFoundException &e) { color_pair = 0; } try { max_mana = curr_root.lookup("mana"); } catch(const SettingNotFoundException &e) { max_mana = 1; } actor_settings_.emplace_back(speed, icon, max_hp, attack_damage, color_pair, max_mana); } vector potions = {"HealPotion", "ManaPotion"}; for (const auto& potion_cfg_name : potions) { const auto &curr_root = root[potion_cfg_name]; char icon; short color; int restore; try { icon = curr_root.lookup("icon").c_str()[0]; } catch (const SettingNotFoundException &e) { icon = 'P'; } try { color = static_cast(static_cast(curr_root.lookup("color"))); } catch (const SettingNotFoundException &e) { color = 0; } try { restore = curr_root.lookup("restore"); } catch (const SettingNotFoundException &e) { restore = 0; } potion_settings_.emplace_back(icon, color, restore); } } // //struct ActorSettings //{ // double speed; // char icon; // int max_hp; // int attack_damage; // short color_pair; // int max_mana; //}; 0 /* ------------------------------------------------------- XP-DOS Version indev-4 Written in C++ by Copyright JMCOG 2020 Contact at: ------------------------------------------------------- */ #include #include #include using namespace std; bool isRunning = true; string userCommand; string version = "indev-4"; void CodeEdit() { isRunning = false; bool isEditor = true; std::cout << "Welcome to XP-DOS Code!" << endl; std::cout << "Type 'help' for help." << endl; string commands[6]; string debugCommands[8]; string emptyLine; string separator = " "; string newLine = "\n"; string file[100]; string userDebugCommand; int currentLines = 0; commands[0] = "print"; commands[1] = "end"; commands[2] = "goxpdos"; commands[3] = "cls"; commands[4] = "pause"; commands[5] = "input"; debugCommands[0] = "run"; debugCommands[1] = "stop"; debugCommands[2] = "newfile"; debugCommands[3] = "writefile"; debugCommands[4] = "list"; debugCommands[5] = "chkfile"; debugCommands[6] = "goxpdos"; debugCommands[7] = "help"; emptyLine = ""; for (int i = 0; i < 101; i++) { file[i] = ""; } while (isEditor) { std::cin >> userDebugCommand; if (userDebugCommand == debugCommands[0]) { string code[100]; int currentExecutedLine = 0; for (int i = 0; i < 101; i++) { code[i] = file[i]; } for (int i = 0; i < 101; i++) { if (code[i] == commands[0]) { string userInput; std::cout << "Request user input..." << endl; std::cin >> userInput; std::cout << userInput << endl; } else if (code[i] == commands[1]) { break; } else if (code[i] == commands[2]) { std::cout << "Booting to XP-DOS..." << endl; isRunning = true; isEditor = false; break; } else if (code[i] == commands[3]) { system("cls"); } else if (code[i] == commands[4]) { system("PAUSE"); } else if (code[i] == commands[5]) { string usrInp; std::cin >> usrInp; std::cout << "User Input: " << usrInp << endl; // Sample result, Change to fit you style } else if (code[i] == emptyLine || code[i] == separator) { std::cout << " " << endl; } else { std::cout << "?Syntax error in: " << i << endl; break; } currentExecutedLine += 1; } } else if (userDebugCommand == debugCommands[1]) { //TODO: Stop program } else if (userDebugCommand == debugCommands[2]) { for (int i = 0; i < 101; i++) { file[i] = ""; } } else if (userDebugCommand == debugCommands[3]) { string tempCode; std::cin >> tempCode; if (currentLines == 0) { if (file[0] == "") { file[0] = tempCode; currentLines += 1; } } else { currentLines += 1; file[currentLines] = tempCode; } } else if (userDebugCommand == debugCommands[4]) { for (int i = 0; i < 101; i++) { if (file[i] == "" && i != 1) { break; } else { std::cout << file[i] << endl; } } } else if (userDebugCommand == debugCommands[5]) { for (int i = 0; i < 101; i++) { if (file[i] == commands[0]) { std::cout << "Line " << i << " OK!" << endl; } else if (file[i] == commands[1]) { std::cout << "Line " << i << " OK!" << endl; } else if (file[i] == commands[2]) { std::cout << "Line " << i << " OK!" << endl; } else if (file[i] == commands[3]) { std::cout << "Line " << i << " OK!" << endl; } else if (file[i] == commands[4]) { std::cout << "Line " << i << " OK!" << endl; } else if (file[i] == emptyLine || file[i] == separator) { std::cout << "Line " << i << " OK!" << endl; } else { std::cout << "?Syntax error in line " << i << "!" << endl; } } } else if (userDebugCommand == debugCommands[6]) { std::cout << "Booting to XP-DOS..." << endl; isRunning = true; isEditor = false; system("cls"); break; } else if (userDebugCommand == debugCommands[7]) { std::cout << "XPDPS Help:" << endl; std::cout << "Command reference:" << endl; std::cout << "cls - clears the screen" << endl; std::cout << "end - breaks the program" << endl; std::cout << "goxpdos - Boot's XP-DOS and exits XPDPS mode" << endl; std::cout << "pause - pauses the system" << endl; std::cout << "print - get the user to input a string and print's it back" << endl; std::cout << "input - get user input over string variable 'usrInp'" << endl; std::cout << "Debug Command reference:" << endl; std::cout << "chkfile - check the script for syxtax errors" << endl; std::cout << "help - shows the help page ()" << endl; std::cout << "list - lists your program" << endl; //std::cout << "stop" << endl; std::cout << "newfile - makes a new script" << endl; std::cout << "writefile - enables you to write one line of script (one line per command)" << endl; std::cout << "goxpdos - Boot's XP-DOS and exits XPDPS mode" << endl; std::cout << "run - runs your program" << endl; } else { std::cout << "Unknown debug command." << endl; } system("PAUSE"); } } void Print() { string userInput; std::cout << "Request user input..." << endl; std::cin >> userInput; std::cout << userInput << endl; } void Quit() { std::cout << "Quitting XP-DOS..." << endl; isRunning = false; // Sets isRunning to false which breaks the loop } void ClearScreen() { system("cls"); } void PauseSystem() { system("PAUSE"); } void DisplayAbout() { std::cout << "About:" << endl; std::cout << "XP-DOS: version " << version << endl; std::cout << "Home user operation system for PC's" << endl; std::cout << "Written in C++ by " << endl; std::cout << "Copyright 2020 by JMCOG" << endl; std::cout << "Type 'help' for user help" << endl; } void DisplayHelp() { std::cout << "User help" << endl; std::cout << "IMPORTANT!!! THIS VERSION IS NOT FINAL! REPORT BUGS AT " << endl; std::cout << "Command reference:" << endl; std::cout << "about: Displays about page" << endl; std::cout << "cls: Clears the screen" << endl; std::cout << "code: Program in XPDPS" << endl; std::cout << "help: Display help page ()" << endl; std::cout << "pause: Pauses the system" << endl; std::cout << "calc: Runs Calculator" << endl; } void Calculator() { std::cout << "Calculator started!" << endl; char op; float num1, num2; bool isCalculator = true; string endAskAgain; while (isCalculator) { std::cout << "Enter operation here (+, -, *, or /): "; std::cin >> op; std::cout << endl; std::cout << "Enter two operands: "; std::cin >> num1 >> num2; std::cout << endl; switch (op) { case '+': std::cout << num1 + num2 << endl; break; case '-': std::cout << num1 - num2 << endl; break; case '*': std::cout << num1 * num2 << endl; break; case '/': std::cout << num1 / num2 << endl; break; default: std::cout << "Error during calculation - Type of error: Invalid operation" << endl; break; } std::cout << "Do Another calculation? (Y or N) "; std::cin >> endAskAgain; if (endAskAgain == "Y" || endAskAgain == "y") { isCalculator = true; } else if (endAskAgain == "N" || endAskAgain == "n") { std::cout << "Quitting to XP-DOS..." << endl; ClearScreen(); isCalculator = false; break; } else { std::cout << "Invalid answer! Quitting to XP-DOS..." << endl; ClearScreen(); isCalculator = false; break; } } } int main() { std::cout << "XP-DOS version " << version << endl; std::cout << "Type 'help' for user help" << endl; while (isRunning) { std::cout << "Enter command:" << endl; std::cin >> userCommand; if (userCommand == "print") { Print(); } else if (userCommand == "quit") { Quit(); } else if (userCommand == "cls") { ClearScreen(); } else if (userCommand == "pause") { PauseSystem(); } else if (userCommand == "about") { DisplayAbout(); } else if (userCommand == "help") { DisplayHelp(); } else if (userCommand == "code") { ClearScreen(); std::cout << "Quitting XP-DOS and starting code editor..." << endl; CodeEdit(); } else if (userCommand == "calc") { std::cout << "Quitting to Calculator..." << endl; ClearScreen(); Calculator(); } else { std::cout << "Unknown command/Illegal action" << endl; } } return 0; } // 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/cloud/accessapproval/v1/accessapproval.proto #include "google/cloud/accessapproval/internal/access_approval_auth_decorator.h" #include #include namespace google { namespace cloud { namespace accessapproval_internal { GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN AccessApprovalAuth::AccessApprovalAuth( std::shared_ptr auth, std::shared_ptr child) : auth_(std::move(auth)), child_(std::move(child)) {} StatusOr AccessApprovalAuth::ListApprovalRequests( grpc::ClientContext& context, google::cloud::accessapproval::v1::ListApprovalRequestsMessage const& request) { auto status = auth_->ConfigureContext(context); if (!status.ok()) return status; return child_->ListApprovalRequests(context, request); } StatusOr AccessApprovalAuth::GetApprovalRequest( grpc::ClientContext& context, google::cloud::accessapproval::v1::GetApprovalRequestMessage const& request) { auto status = auth_->ConfigureContext(context); if (!status.ok()) return status; return child_->GetApprovalRequest(context, request); } StatusOr AccessApprovalAuth::ApproveApprovalRequest( grpc::ClientContext& context, google::cloud::accessapproval::v1::ApproveApprovalRequestMessage const& request) { auto status = auth_->ConfigureContext(context); if (!status.ok()) return status; return child_->ApproveApprovalRequest(context, request); } StatusOr AccessApprovalAuth::DismissApprovalRequest( grpc::ClientContext& context, google::cloud::accessapproval::v1::DismissApprovalRequestMessage const& request) { auto status = auth_->ConfigureContext(context); if (!status.ok()) return status; return child_->DismissApprovalRequest(context, request); } StatusOr AccessApprovalAuth::GetAccessApprovalSettings( grpc::ClientContext& context, google::cloud::accessapproval::v1::GetAccessApprovalSettingsMessage const& request) { auto status = auth_->ConfigureContext(context); if (!status.ok()) return status; return child_->GetAccessApprovalSettings(context, request); } StatusOr AccessApprovalAuth::UpdateAccessApprovalSettings( grpc::ClientContext& context, google::cloud::accessapproval::v1:: UpdateAccessApprovalSettingsMessage const& request) { auto status = auth_->ConfigureContext(context); if (!status.ok()) return status; return child_->UpdateAccessApprovalSettings(context, request); } Status AccessApprovalAuth::DeleteAccessApprovalSettings( grpc::ClientContext& context, google::cloud::accessapproval::v1:: DeleteAccessApprovalSettingsMessage const& request) { auto status = auth_->ConfigureContext(context); if (!status.ok()) return status; return child_->DeleteAccessApprovalSettings(context, request); } GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END } // namespace accessapproval_internal } // namespace cloud } // namespace google test/module/irohad/validation/stateless/transaction_validator_test.cpp0 /** * Copyright Soramitsu Co., Ltd. 2017 All Rights Reserved. * http://soramitsu.co.jp * * 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 iroha::model::Transaction sign(iroha::model::Transaction &tx, const iroha::privkey_t &privkey, const iroha::pubkey_t &pubkey) { auto tx_hash = iroha::hash(tx).to_string(); auto sign = iroha::sign(tx_hash, pubkey, privkey); iroha::model::Signature signature{}; signature.signature = sign; signature.pubkey = pubkey; tx.signatures.push_back(signature); return tx; } iroha::model::Transaction create_transaction() { iroha::model::Transaction tx{}; tx.creator_account_id = "test"; tx.tx_counter = 0; std::chrono::milliseconds now = std::chrono::duration_cast( std::chrono::system_clock::now().time_since_epoch()); tx.created_ts = (iroha::ts64_t)now.count(); return tx; } TEST(stateless_validation, stateless_validation_when_valid) { auto keypair = iroha::create_keypair(); auto crypto_provider = std::make_shared(); iroha::validation::StatelessValidatorImpl transaction_validator( crypto_provider); auto tx = create_transaction(); sign(tx, keypair.privkey, keypair.pubkey); ASSERT_TRUE(transaction_validator.validate(tx)); } TEST(stateless_validation, stateless_validation_when_invalid_wrong_signature) { auto keypair = iroha::create_keypair(); auto crypto_provider = std::make_shared(); iroha::validation::StatelessValidatorImpl transaction_validator( crypto_provider); auto tx = create_transaction(); sign(tx, keypair.privkey, keypair.pubkey); tx.creator_account_id = "test1"; ASSERT_FALSE(transaction_validator.validate(tx)); } TEST(stateless_validation, stateless_validation_when_invalid_due_to_big_time_delay) { auto keypair = iroha::create_keypair(); auto crypto_provider = std::make_shared(); iroha::validation::StatelessValidatorImpl transaction_validator( crypto_provider); auto tx = create_transaction(); std::chrono::milliseconds now = std::chrono::duration_cast( std::chrono::system_clock::now().time_since_epoch()); tx.created_ts = (iroha::ts64_t)(now.count() - 1000 * 3600 * 25); // tx created 25 hours ago sign(tx, keypair.privkey, keypair.pubkey); ASSERT_FALSE(transaction_validator.validate(tx)); } TEST(stateless_validation, stateless_validation_when_invalid_due_to_tx_from_future) { auto keypair = iroha::create_keypair(); auto crypto_provider = std::make_shared(); iroha::validation::StatelessValidatorImpl transaction_validator( crypto_provider); auto tx = create_transaction(); std::chrono::milliseconds now = std::chrono::duration_cast( std::chrono::system_clock::now().time_since_epoch()); tx.created_ts = (iroha::ts64_t)(now.count() + 1000 * 3600); // tx created 1 hour later sign(tx, keypair.privkey, keypair.pubkey); ASSERT_FALSE(transaction_validator.validate(tx)); } 1-10 /* -*- Mode: c++; -*- */ // copyright (c) 2010 by <> /*************************************************************************** * * * 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"MultivariateGaussianClassifier.h" /// Construct the class MultivariateGaussianClassifier::MultivariateGaussianClassifier(int n_inputs_, int n_classes_) : n_inputs(n_inputs_), n_classes(n_classes_), class_distribution(n_classes), prior(n_classes, 0.5), output(n_classes) { Vector mu(n_inputs); real tau = 1.0; real alpha = (real) n_inputs; //1.0; Matrix T(Matrix::Unity(n_inputs, n_inputs)); for (int i=0; ilog_pdf(x); if (std::isnan(output(i))) { Serror("Output %d is nan", i); output.print(stdout); class_distribution[i]->Show(); } } output += log(prior.getMarginal()); real S = output.logSum(); output -= S; for (int i=0; iShow(); exit(-1); } } return output; } real MultivariateGaussianClassifier::Observe(const Vector& x, const int& label) { assert(label >= 0 && label < n_classes); real probability = Output(x)(label); class_distribution[label]->Observe(x); prior.Observe(label); return probability; } Vector MultivariateGaussianClassifier::getClassMean(const int label) const { return class_distribution[label]->getMean(); } // Copyright (C) 2004-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 // . // 27.6.1.2.3 character extractors #include #include #include void test02() { std::wstring str_01; const std::wstring str_02(L"or coltrane playing tunji with jimmy garrison"); const std::wstring str_03(L"coltrane"); std::wstringbuf isbuf_01(std::ios_base::in); std::wstringbuf isbuf_02(str_02, std::ios_base::in); std::wistream is_01(0); std::wistream is_02(&isbuf_02); std::ios_base::iostate state1, state2, statefail; statefail = std::ios_base::failbit; // template<_CharT, _Traits> // basic_istream& operator>>(istream&, _CharT&) wchar_t c1 = L'c', c2 = L'c'; state1 = is_01.rdstate(); is_01 >> c1; state2 = is_01.rdstate(); VERIFY( state1 != state2 ); VERIFY( c1 == c2 ); VERIFY( static_cast(state2 & statefail) ); state1 = is_02.rdstate(); is_02 >> c1; state2 = is_02.rdstate(); VERIFY( state1 == state2 ); VERIFY( c1 == L'o' ); is_02 >> c1; is_02 >> c1; VERIFY( c1 == L'c' ); VERIFY( !static_cast(state2 & statefail) ); } int main() { test02(); return 0; } 100-1000 #include #include #include #include #include using namespace std; namespace micro_profiler { namespace tests { namespace { class allocation_monitor : public allocator { public: std::function allocated; std::function freeing; private: virtual void *allocate(std::size_t length) override { auto memory = malloc(length); try { if (allocated) allocated(length, memory); } catch (...) { free(memory); throw; } return memory; } virtual void deallocate(void *memory) throw() override { if (freeing) freeing(memory); free(memory); } }; class ptr : noncopyable { public: ptr(allocator &a, size_t length) : _allocator(a), _ptr(a.allocate(length)), _allocated(true) { } ~ptr() { deallocate(); } char *get() const { return static_cast(_ptr); } void deallocate() { if (_allocated) { _allocator.deallocate(_ptr); _allocated = false; } } private: allocator &_allocator; void * const _ptr; bool _allocated; }; } begin_test_suite( PoolAllocatorTests ) allocation_monitor underlying; test( NoAllocationsAreMadeOnConstruction ) { // INIT auto ops = 0; underlying.allocated = [&] (size_t, void *) { ops++; }; underlying.freeing = [&] (void *) { ops++; }; // INIT / ACT { pool_allocator a(underlying); } // ASSERT assert_equal(0, ops); } test( AllocationsOfDifferentSizesInvokeUnderlying ) { // INIT const auto overhead = static_cast(pool_allocator::overhead); vector< pair > log; pool_allocator a(underlying); underlying.allocated = [&] (size_t n, void *p) { log.push_back(make_pair(n, static_cast(p))); }; // ACT ptr p1(a, 10); ptr p2(a, 15); ptr p3(a, 15000); // ASSERT pair reference1[] = { make_pair(10u + overhead, p1.get() - overhead), make_pair(15u + overhead, p2.get() - overhead), make_pair(15000u + overhead, p3.get() - overhead), }; assert_equal(reference1, log); // INIT log.clear(); // ACT ptr p4(a, 100); ptr p5(a, 115); // ASSERT pair reference2[] = { make_pair(100u + pool_allocator::overhead, p4.get() - overhead), make_pair(115u + overhead, p5.get() - overhead), }; assert_equal(reference2, log); } test( NewAllocationOfTheSameSizeRequestNewUnderlyingAllocations ) { // INIT const auto overhead = static_cast(pool_allocator::overhead); vector< pair > log; pool_allocator a(underlying); underlying.allocated = [&] (size_t n, void *p) { log.push_back(make_pair(n, static_cast(p))); }; // ACT ptr p1(a, 10); ptr p2(a, 10); ptr p3(a, 10); // ASSERT pair reference1[] = { make_pair(10u + overhead, p1.get() - overhead), make_pair(10u + overhead, p2.get() - overhead), make_pair(10u + overhead, p3.get() - overhead), }; assert_equal(reference1, log); // INIT log.clear(); // ACT ptr p4(a, 20); ptr p5(a, 20); // ASSERT pair reference2[] = { make_pair(20u + overhead, p4.get() - overhead), make_pair(20u + overhead, p5.get() - overhead), }; assert_equal(reference2, log); } test( DeallocatedBlocksAreReturnedBeforeNewUnderlyingAllocationsAreMade ) { // INIT const auto overhead = static_cast(pool_allocator::overhead); vector< pair > log; auto deallocations = 0; pool_allocator a(underlying); underlying.allocated = [&] (size_t n, void *p) { log.push_back(make_pair(n, static_cast(p))); }; underlying.freeing = [&] (void *) { deallocations++; }; ptr p1(a, 10); ptr p2(a, 10); ptr p3(a, 10); ptr p4(a, 25); ptr p5(a, 25); ptr p101(a, 10); ptr p102(a, 25); p1.deallocate(); p2.deallocate(); p3.deallocate(); p5.deallocate(); p4.deallocate(); log.clear(); // ACT ptr p11(a, 10); ptr p12(a, 10); ptr p13(a, 25); // ASSERT assert_equal(p3.get(), p11.get()); assert_equal(p2.get(), p12.get()); assert_equal(p4.get(), p13.get()); // ACT ptr p14(a, 10); ptr p15(a, 25); // ASSERT assert_equal(p1.get(), p14.get()); assert_equal(p5.get(), p15.get()); assert_is_empty(log); // ACT ptr p16(a, 10); ptr p17(a, 25); // ASSERT pair reference[] = { make_pair(10u + overhead, p16.get() - overhead), make_pair(25u + overhead, p17.get() - overhead), }; assert_equal(reference, log); } test( AllAllocatedBlocksAreReturnedOnDestruction ) { // INIT vector allocated, deallocated; underlying.allocated = [&] (size_t, void *p) { allocated.push_back(p); }; underlying.freeing = [&] (void *p) { deallocated.push_back(p); }; { pool_allocator a(underlying); ptr p1(a, 10); ptr p2(a, 10); ptr p3(a, 10); ptr p4(a, 25); ptr p5(a, 25); ptr p6(a, 10); ptr p7(a, 25); // ACT } // ASSERT assert_equivalent(allocated, deallocated); } end_test_suite } } #include "ComponentTransform.h" #include "GameObject.h" ComponentTransform::ComponentTransform(GameObject* ContainerGO) : Component(ContainerGO, Component::ComponentType::Transform) { } ComponentTransform::~ComponentTransform() { } float3 ComponentTransform::GetPosition() const { return position; } float3 ComponentTransform::GetScale() const { return scale; } float3 ComponentTransform::GetRotation() const { return rotation_euler; } float4x4 ComponentTransform::GetLocalTransform() const { return Local_transform; } float4x4 ComponentTransform::GetGlobalTransform() const { return Global_transform; } float3 ComponentTransform::GetGlobalPosition() const { float4x4 global_transform = GetGlobalTransform(); return global_transform.TranslatePart(); } void ComponentTransform::SetPosition(float x, float y, float z) { position = float3(x, y, z); UpdateLocalTransform(); } void ComponentTransform::SetRotation(float3 euler_angles) { float3 difference = (euler_angles - rotation_euler) * DEGTORAD; Quat quatrot = Quat::FromEulerXYZ(difference.x, difference.y, difference.z); rotation = rotation * quatrot; rotation_euler = euler_angles; UpdateLocalTransform(); } void ComponentTransform::Scale(float x, float y, float z) { if (x > 0.0f && y > 0.0f && z > 0.0f) { scale = float3(x, y, z); UpdateLocalTransform(); } } void ComponentTransform::SetGlobalTransform(float4x4 new_transform) { Local_transform = Local_transform = new_transform.Inverted() * Global_transform; Global_transform = new_transform; OnUpdateTransform(Global_transform); } void ComponentTransform::UpdateLocalTransform() { Local_transform = float4x4::FromTRS(position, rotation, scale); update_transform = true; } void ComponentTransform::OnUpdateTransform(const float4x4& ParentGlobal) { Global_transform = ParentGlobal * Local_transform; UpdateTRS(); update_transform = false; } void ComponentTransform::UpdateTRS() { Local_transform.Decompose(position, rotation, scale); rotation_euler = rotation.ToEulerXYZ() * RADTODEG; } /* 124. Binary Tree Maximum Path Sum https://leetcode.com/problems/binary-tree-maximum-path-sum/ We do postorder traversal and each time we return the max path in the subtree to the subtree root. At root we update the global max. Now the max path can be either left, right, left+curr+right, curr. */ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: int findMaxSum(TreeNode* root, long long& max_sum) { if(!root) return numeric_limits :: min(); long long left = findMaxSum(root->left, max_sum); long long right = findMaxSum(root->right, max_sum); // find the max amongst the left path, right path and curr node only long long left_curr_right_max = max({left + root->val, (long long)root->val, right + root->val}); // now find the max with the combined left + curr + right path sum max_sum = max({left_curr_right_max, left + root->val + right, max_sum}); return left_curr_right_max; } int maxPathSum(TreeNode* root) { long long max_sum = numeric_limits :: min(); findMaxSum(root, max_sum); return max_sum; } }; tapaswenipathak/CoreNeuron1-10 /* Copyright (c) 2016, Blue Brain Project 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. */ #define BOOST_TEST_MODULE PaddingCheck #define BOOST_TEST_MAIN #include #include #include #include #include #include "coreneuron/nrniv/memory.h" template struct data{ typedef T value_type; static const int chunk=n; }; typedef boost::mpl::list< data, data > chunk_default_data_type; typedef boost::mpl::list< data, data, data, data, data, data, data, data, data, data > chunk_data_type; BOOST_AUTO_TEST_CASE(padding_simd) { /** AOS test */ int pad = coreneuron::soa_padded_size<1>(11, 1); BOOST_CHECK_EQUAL(pad,11); /** SOA tests with 11 */ pad = coreneuron::soa_padded_size<1>(11, 0); BOOST_CHECK_EQUAL(pad,11); pad = coreneuron::soa_padded_size<2>(11, 0); BOOST_CHECK_EQUAL(pad,12); pad = coreneuron::soa_padded_size<4>(11, 0); BOOST_CHECK_EQUAL(pad,12); pad = coreneuron::soa_padded_size<8>(11, 0); BOOST_CHECK_EQUAL(pad,16); pad = coreneuron::soa_padded_size<16>(11, 0); BOOST_CHECK_EQUAL(pad,16); pad = coreneuron::soa_padded_size<32>(11, 0); BOOST_CHECK_EQUAL(pad,32); /** SOA tests with 32 */ pad = coreneuron::soa_padded_size<1>(32, 0); BOOST_CHECK_EQUAL(pad,32); pad = coreneuron::soa_padded_size<2>(32, 0); BOOST_CHECK_EQUAL(pad,32); pad = coreneuron::soa_padded_size<4>(32, 0); BOOST_CHECK_EQUAL(pad,32); pad = coreneuron::soa_padded_size<8>(32, 0); BOOST_CHECK_EQUAL(pad,32); pad = coreneuron::soa_padded_size<16>(32, 0); BOOST_CHECK_EQUAL(pad,32); pad = coreneuron::soa_padded_size<32>(32, 0); BOOST_CHECK_EQUAL(pad,32); /** SOA tests with 33 */ pad = coreneuron::soa_padded_size<1>(33, 0); BOOST_CHECK_EQUAL(pad,33); pad = coreneuron::soa_padded_size<2>(33, 0); BOOST_CHECK_EQUAL(pad,34); pad = coreneuron::soa_padded_size<4>(33, 0); BOOST_CHECK_EQUAL(pad,36); pad = coreneuron::soa_padded_size<8>(33, 0); BOOST_CHECK_EQUAL(pad,40); pad = coreneuron::soa_padded_size<16>(33, 0); BOOST_CHECK_EQUAL(pad,48); pad = coreneuron::soa_padded_size<32>(33, 0); BOOST_CHECK_EQUAL(pad,64); } /// Even number is randomly depends of the TYPE!!! and the number of elements. /// This test work for 64 bits type not for 32 bits. BOOST_AUTO_TEST_CASE_TEMPLATE(memory_alignment_simd_false, T, chunk_default_data_type){ const int c = T::chunk; int total_size_chunk = coreneuron::soa_padded_size(247, 0); int ne = 6*total_size_chunk; typename T::value_type* data = (typename T::value_type*)coreneuron::ecalloc_align(ne, 16, sizeof(typename T::value_type)); for(int i=1; i < 6; i+=2){ bool b = coreneuron::is_aligned((data+i*total_size_chunk),16); BOOST_CHECK_EQUAL(b,0); } for(int i=0; i < 6; i+=2){ bool b = coreneuron::is_aligned((data+i*total_size_chunk),16); BOOST_CHECK_EQUAL(b,1); } free(data); } BOOST_AUTO_TEST_CASE_TEMPLATE(memory_alignment_simd_true, T, chunk_data_type){ const int c = T::chunk; int total_size_chunk = coreneuron::soa_padded_size(247, 0); int ne = 6*total_size_chunk; typename T::value_type* data = (typename T::value_type*)coreneuron::ecalloc_align(ne, 16, sizeof(typename T::value_type)); for(int i=0; i < 6; ++i){ bool b = coreneuron::is_aligned((data+i*total_size_chunk),16); BOOST_CHECK_EQUAL(b,1); } free(data); } /** * particle_filter.cpp * * Created on: Dec 12, 2016 * Author: */ #include "particle_filter.h" #include #include #include #include #include #include #include #include #include "helper_functions.h" using std::string; using std::vector; void ParticleFilter::init(double x, double y, double theta, double std[]) { /** * TODO: Set the number of particles. Initialize all particles to * first position (based on estimates of x, y, theta and their uncertainties * from GPS) and all weights to 1. * TODO: Add random Gaussian noise to each particle. * NOTE: Consult particle_filter.h for more information about this method * (and others in this file). */ num_particles = 100; // TODO: Set the number of particles // This line creates a normal (Gaussian) distribution for x std::default_random_engine gen; std::normal_distribution dist_x(x, std[0]); std::normal_distribution dist_y(y, std[1]); std::normal_distribution dist_theta(theta, std[2]); double particle_x = dist_x(gen); double particle_y = dist_y(gen); double particle_theta = dist_theta(gen); for (unsigned int ii=0; iiparticles.push_back(p); this->weights.push_back(1.); } this->is_initialized = true; } void ParticleFilter::prediction(double delta_t, double std_pos[], double velocity, double yaw_rate) { /** * TODO: Add measurements to each particle and add random Gaussian noise. * NOTE: When adding noise you may find std::normal_distribution * and std::default_random_engine useful. * http://en.cppreference.com/w/cpp/numeric/random/normal_distribution * http://www.cplusplus.com/reference/random/default_random_engine/ */ std::default_random_engine gen; for (unsigned int ii=0; iiparticles[ii]; double particle_x=p.x, particle_y=p.y, particle_theta=p.theta; if (fabs(yaw_rate)<0.0000001) { particle_x += velocity*delta_t*cos(p.theta); particle_y += velocity*delta_t*sin(p.theta); } else { particle_x += velocity/yaw_rate*(sin(p.theta+yaw_rate*delta_t) - sin(p.theta)); particle_y += velocity/yaw_rate*(cos(p.theta) - cos(p.theta+yaw_rate*delta_t)); particle_theta += yaw_rate*delta_t; } std::normal_distribution dist_x(particle_x, std_pos[0]); std::normal_distribution dist_y(particle_y, std_pos[1]); std::normal_distribution dist_theta(particle_theta, std_pos[2]); this->particles[ii].x = dist_x(gen); this->particles[ii].y = dist_y(gen); this->particles[ii].theta = dist_theta(gen); } } void ParticleFilter::dataAssociation(vector predicted, vector& observations, Particle &particle) { /** * TODO: Find the predicted measurement that is closest to each * observed measurement and assign the observed measurement to this * particular landmark. * NOTE: this method will NOT be called by the grading code. But you will * probably find it useful to implement this method and use it as a helper * during the updateWeights phase. */ vector associations; for (std::size_t ii=0; ii::max(); for (std::size_t jj=0; jj &observations, const Map &map_landmarks) { /** * TODO: Update the weights of each particle using a multi-variate Gaussian * distribution. You can read more about this distribution here: * https://en.wikipedia.org/wiki/Multivariate_normal_distribution * NOTE: The observations are given in the VEHICLE'S coordinate system. * Your particles are located according to the MAP'S coordinate system. * You will need to transform between the two systems. Keep in mind that * this transformation requires both rotation AND translation (but no scaling). * The following is a good resource for the theory: * https://www.willamette.edu/~gorr/classes/GeneralGraphics/Transforms/transforms2d.htm * and the following is a good resource for the actual equation to implement * (look at equation 3.33) http://planning.cs.uiuc.edu/node99.html */ for(std::size_t ii=0; iiparticles.size(); ++ii) { // get predicted landmarks: only those within sensor_range vector predicted; for (std::size_t kk=0; kk temp_obs = observations; for (std::size_t jj=0; jjdataAssociation(predicted, temp_obs, particles[ii]); this->particles[ii].weight = 1.; for (std::size_t jj=0; jjparticles[ii].weight *= val; } this->weights[ii] = this->particles[ii].weight; } } void ParticleFilter::resample() { /** * TODO: Resample particles with replacement with probability proportional * to their weight. * NOTE: You may find std::discrete_distribution helpful here. * http://en.cppreference.com/w/cpp/numeric/random/discrete_distribution */ vector new_weights; std::default_random_engine generator; std::discrete_distribution<> distribution(this->weights.begin(), this->weights.end()); std::vector new_particles; for (size_t i=0; iparticles.size(); ++i) { new_particles.push_back(this->particles.at(distribution(generator))); } this->particles = new_particles; } void ParticleFilter::SetAssociations(Particle& particle, const vector& associations, const vector& sense_x, const vector& sense_y) { // particle: the particle to which assign each listed association, // and association's (x,y) world coordinates mapping // associations: The landmark id that goes along with each listed association // sense_x: the associations x mapping already converted to world coordinates // sense_y: the associations y mapping already converted to world coordinates particle.associations= associations; particle.sense_x = sense_x; particle.sense_y = sense_y; } string ParticleFilter::getAssociations(Particle best) { vector v = best.associations; std::stringstream ss; copy(v.begin(), v.end(), std::ostream_iterator(ss, " ")); string s = ss.str(); s = s.substr(0, s.length()-1); // get rid of the trailing space return s; } string ParticleFilter::getSenseCoord(Particle best, string coord) { vector v; if (coord == "X") { v = best.sense_x; } else { v = best.sense_y; } std::stringstream ss; copy(v.begin(), v.end(), std::ostream_iterator(ss, " ")); string s = ss.str(); s = s.substr(0, s.length()-1); // get rid of the trailing space return s; } 0 // This program uses a selection sort to arrange an array of integers in // descending order // : 101430670 // Headers #include using namespace std; // Function Prototypes void selectionSortArray(int [], int); void displayArray(int[], int); // Global Constants const int SIZE = 5; int main() { int values[SIZE] = {9,2,0,11,5}; cout << "\nThe values before the selection sort is performed are:" << endl; displayArray(values, SIZE); cout << "\n\nThe values during the selection sort's performance are:" << endl; selectionSortArray(values, SIZE); cout << "\n\nThe values after the selection sort is performed are:" << endl; displayArray(values, SIZE); return 0; } //****************************************************************** // displayArray // // task: to print the array // data in: the array to be printed, the array size // data out: none // //****************************************************************** void displayArray(int array[], int elems) { for(int count = 0; count < elems; count++) cout << array[count] << " "; cout << endl; } //****************************************************************** // selectionSortArray // // task: to sort values of an array in ascending order // data in: the array, the array size // data out: the sorted array // //****************************************************************** void selectionSortArray(int array[], int elems) { int seek; //array position currently being put in order int minCount; //location of smallest value found int minValue; //holds the smallest value found for(seek = 0; seek < (elems-1); seek++) { // outer loop performs the swap minCount = seek; // and then increments seek minValue = array[seek]; for(int index = seek + 1; index < elems; index++) { // inner loop searches through array // starting at array[seek] searching // for the smallest value. When the // value is found, the subscript is // stored in minCount. The value is // stored in minValue. if(array[index] > minValue) { minValue = array[index]; minCount = index; } } // the following two statements exchange the value of the // element currently needing the smallest value found in the // pass(indicated by seek) with the smallest value found // (located in minValue) array[minCount] = array[seek]; array[seek] = minValue; displayArray(array, SIZE); } } // After doing the selection sort by hand on a sheet of paper, the output is the same as // each step that was printed on the program screen. #include "common/csv_writer.h" #include namespace slog { CSVWriter::CSVWriter(const std::string& file_name, const std::vector& columns, char delimiter) { if (columns.empty()) { throw std::runtime_error("There must be at least one column"); } num_columns_ = columns.size(); line_items_ = 0; delim_ = delimiter; file_ = std::ofstream(file_name, std::ios::out); if (!file_) { throw std::runtime_error(std::string("Cannot open file: ") + file_name); } bool first = true; for (const auto& col : columns) { if (!first) { file_ << ","; } file_ << col; first = false; } file_ << "\n"; } void CSVWriter::AppendDelim() { if (line_items_ > 1) { file_ << delim_; } } void CSVWriter::IncrementLineItemsAndCheck() { line_items_++; if (line_items_ > num_columns_) { throw std::runtime_error("Number of items exceeds number of columns"); } } } // namespace slog#ifndef LLARP_QUEUE_HPP #define LLARP_QUEUE_HPP #include #include #include #if __cplusplus >= 201703L #include #else #include #endif #include namespace llarp { namespace thread { template < typename Type > class QueuePushGuard; template < typename Type > class QueuePopGuard; template < typename Type > class Queue { // This class provides a thread-safe, lock-free, fixed-size queue. public: static constexpr size_t Alignment = 64; private: Type *m_data; const char m_dataPadding[Alignment - sizeof(Type *)]; QueueManager m_manager; std::atomic< std::uint32_t > m_waitingPoppers; util::Semaphore m_popSemaphore; const char m_popSemaphorePadding[(2u * Alignment) - sizeof(util::Semaphore)]; std::atomic< std::uint32_t > m_waitingPushers; util::Semaphore m_pushSemaphore; const char m_pushSemaphorePadding[(2u * Alignment) - sizeof(util::Semaphore)]; friend QueuePopGuard< Type >; friend QueuePushGuard< Type >; public: explicit Queue(size_t capacity); ~Queue(); Queue(const Queue &) = delete; Queue & operator=(const Queue &) = delete; // Push back to the queue, blocking until space is available (if // required). Will fail if the queue is disabled (or becomes disabled // while waiting for space on the queue). QueueReturn pushBack(const Type &value); QueueReturn pushBack(Type &&value); // Try to push back to the queue. Return false if the queue is full or // disabled. QueueReturn tryPushBack(const Type &value); QueueReturn tryPushBack(Type &&value); // Remove an element from the queue. Block until an element is available Type popFront(); #if __cplusplus >= 201703L std::optional< Type > #else tl::optional< Type > #endif tryPopFront(); // Remove all elements from the queue. Note this is not atomic, and if // other threads `pushBack` onto the queue during this call, the `size` of // the queue is not guaranteed to be 0. void removeAll(); // Disable the queue. All push operations will fail "fast" (including // blocked operations). Calling this method on a disabled queue has no // effect. void disable(); // Enable the queue. Calling this method on a disabled queue has no // effect. void enable(); size_t capacity() const; size_t size() const; bool enabled() const; bool full() const; bool empty() const; }; // Provide a guard class to provide exception safety for pushing to a queue. // On destruction, unless the `release` method has been called, will remove // and destroy all elements from the queue, putting the queue into an empty // state. template < typename Type > class QueuePushGuard { private: Queue< Type > *m_queue; uint32_t m_generation; uint32_t m_index; public: QueuePushGuard(Queue< Type > &queue, uint32_t generation, uint32_t index) : m_queue(&queue), m_generation(generation), m_index(index) { } ~QueuePushGuard(); void release(); }; // Provide a guard class to provide exception safety for popping from a // queue. On destruction, this will pop the the given element from the // queue. template < typename Type > class QueuePopGuard { private: Queue< Type > &m_queue; uint32_t m_generation; uint32_t m_index; public: QueuePopGuard(Queue< Type > &queue, uint32_t generation, uint32_t index) : m_queue(queue), m_generation(generation), m_index(index) { } ~QueuePopGuard(); }; template < typename Type > Queue< Type >::Queue(size_t capacity) : m_data(nullptr) , m_dataPadding() , m_manager(capacity) , m_waitingPoppers(0) , m_popSemaphore(0) , m_popSemaphorePadding() , m_waitingPushers(0) , m_pushSemaphore(0) , m_pushSemaphorePadding() { m_data = static_cast< Type * >(::operator new(capacity * sizeof(Type))); } template < typename Type > Queue< Type >::~Queue() { removeAll(); // We have already deleted the queue members above, free as (void *) ::operator delete(static_cast< void * >(m_data)); } template < typename Type > QueueReturn Queue< Type >::tryPushBack(const Type &value) { uint32_t generation = 0; uint32_t index = 0; // Sync point A // // The next call writes with full sequential consistency to the push // index, which guarantees that the relaxed read to the waiting poppers // count sees any waiting poppers from Sync point B. QueueReturn retVal = m_manager.reservePushIndex(generation, index); if(retVal != QueueReturn::Success) { return retVal; } // Copy into the array. If the copy constructor throws, the pushGuard will // roll the reserve back. QueuePushGuard< Type > pushGuard(*this, generation, index); // Construct in place. ::new(&m_data[index]) Type(value); pushGuard.release(); m_manager.commitPushIndex(generation, index); if(m_waitingPoppers > 0) { m_popSemaphore.notify(); } return QueueReturn::Success; } template < typename Type > QueueReturn Queue< Type >::tryPushBack(Type &&value) { uint32_t generation = 0; uint32_t index = 0; // Sync point A // // The next call writes with full sequential consistency to the push // index, which guarantees that the relaxed read to the waiting poppers // count sees any waiting poppers from Sync point B. QueueReturn retVal = m_manager.reservePushIndex(generation, index); if(retVal != QueueReturn::Success) { return retVal; } // Copy into the array. If the copy constructor throws, the pushGuard will // roll the reserve back. QueuePushGuard< Type > pushGuard(*this, generation, index); Type &dummy = value; // Construct in place. ::new(&m_data[index]) Type(std::move(dummy)); pushGuard.release(); m_manager.commitPushIndex(generation, index); if(m_waitingPoppers > 0) { m_popSemaphore.notify(); } return QueueReturn::Success; } template < typename Type > #if __cplusplus >= 201703L std::optional< Type > #else tl::optional< Type > #endif Queue< Type >::tryPopFront() { uint32_t generation; uint32_t index; // Sync Point C. // // The call to reservePopIndex writes with full *sequential* consistency, // which guarantees the relaxed read to waiting poppers is synchronized // with Sync Point D. QueueReturn retVal = m_manager.reservePopIndex(generation, index); if(retVal != QueueReturn::Success) { return {}; } // Pop guard will (even if the move/copy constructor throws) // - destroy the original object // - update the queue // - notify any waiting pushers QueuePopGuard< Type > popGuard(*this, generation, index); #if __cplusplus >= 201703L return std::optional< Type >(std::move(m_data[index])); #else return tl::optional< Type >(std::move(m_data[index])); #endif } template < typename Type > QueueReturn Queue< Type >::pushBack(const Type &value) { for(;;) { QueueReturn retVal = tryPushBack(value); switch(retVal) { // Queue disabled. case QueueReturn::QueueDisabled: // We pushed the value back case QueueReturn::Success: return retVal; default: // continue on. break; } m_waitingPushers.fetch_add(1, std::memory_order_relaxed); // Sync Point B. // // The call to `full` below loads the push index with full *sequential* // consistency, which gives visibility of the change above to // waiting pushers in Synchronisation Point B. if(full() && enabled()) { m_pushSemaphore.wait(); } m_waitingPushers.fetch_add(-1, std::memory_order_relaxed); } } template < typename Type > QueueReturn Queue< Type >::pushBack(Type &&value) { for(;;) { QueueReturn retVal = tryPushBack(std::move(value)); switch(retVal) { // Queue disabled. case QueueReturn::QueueDisabled: // We pushed the value back case QueueReturn::Success: return retVal; default: // continue on. break; } m_waitingPushers.fetch_add(1, std::memory_order_relaxed); // Sync Point B. // // The call to `full` below loads the push index with full *sequential* // consistency, which gives visibility of the change above to // waiting pushers in Synchronisation Point C. if(full() && enabled()) { m_pushSemaphore.wait(); } m_waitingPushers.fetch_add(-1, std::memory_order_relaxed); } } template < typename Type > Type Queue< Type >::popFront() { uint32_t generation = 0; uint32_t index = 0; while(m_manager.reservePopIndex(generation, index) != QueueReturn::Success) { m_waitingPoppers.fetch_add(1, std::memory_order_relaxed); if(empty()) { m_popSemaphore.wait(); } m_waitingPoppers.fetch_sub(1, std::memory_order_relaxed); } QueuePopGuard< Type > popGuard(*this, generation, index); return Type(std::move(m_data[index])); } template < typename Type > void Queue< Type >::removeAll() { size_t elemCount = size(); uint32_t poppedItems = 0; while(poppedItems++ < elemCount) { uint32_t generation = 0; uint32_t index = 0; if(m_manager.reservePopIndex(generation, index) != QueueReturn::Success) { break; } m_data[index].~Type(); m_manager.commitPopIndex(generation, index); } size_t wakeups = std::min(poppedItems, m_waitingPushers.load()); while(wakeups--) { m_pushSemaphore.notify(); } } template < typename Type > void Queue< Type >::disable() { m_manager.disable(); uint32_t numWaiting = m_waitingPushers; while(numWaiting--) { m_pushSemaphore.notify(); } } template < typename Type > void Queue< Type >::enable() { m_manager.enable(); } template < typename Type > size_t Queue< Type >::capacity() const { return m_manager.capacity(); } template < typename Type > size_t Queue< Type >::size() const { return m_manager.size(); } template < typename Type > bool Queue< Type >::enabled() const { return m_manager.enabled(); } template < typename Type > bool Queue< Type >::full() const { return (capacity() <= size()); } template < typename Type > bool Queue< Type >::empty() const { return (0 >= size()); } template < typename Type > QueuePushGuard< Type >::~QueuePushGuard() { if(m_queue) { // Thread currently has the cell at index/generation. Dispose of it. uint32_t generation = 0; uint32_t index = 0; // We should always have at least one item to pop. size_t poppedItems = 1; while(m_queue->m_manager.reservePopForClear(generation, index, m_generation, m_index)) { m_queue->m_data[index].~Type(); poppedItems++; m_queue->m_manager.commitPopIndex(generation, index); } // And release m_queue->m_manager.abortPushIndexReservation(m_generation, m_index); while(poppedItems--) { m_queue->m_pushSemaphore.notify(); } } } template < typename Type > void QueuePushGuard< Type >::release() { m_queue = nullptr; } template < typename Type > QueuePopGuard< Type >::~QueuePopGuard() { m_queue.m_data[m_index].~Type(); m_queue.m_manager.commitPopIndex(m_generation, m_index); // Notify a pusher if(m_queue.m_waitingPushers > 0) { m_queue.m_pushSemaphore.notify(); } } } // namespace thread } // namespace llarp #endif // // Created by 方泓睿 on 2020/4/21. // #include #include #include #include #include #include namespace embryo::std_lib { api::FuncReg kTableLib{ // NOLINT(cert-err58-cpp) {"move", table::Move}, {"insert", table::Insert}, {"remove", table::Remove}, {"sort", table::Sort}, {"concat", table::Concat}, {"pack", table::Pack}, {"unpack", table::Unpack} }; int32_t OpenTableLib(const std::shared_ptr &state) { state->NewLib(kTableLib); return 1; } namespace table { namespace { bool CheckField(const std::shared_ptr &state, const std::string &key, int32_t &n) { state->PushString(key); ++n; return state->RawGet(-n) != api::LuaValueType::kNil; } void CheckTab(const std::shared_ptr &state, int32_t arg, TableOp what) { if (state->Type(arg) != api::LuaValueType::kTable) { int32_t n = 1; if (state->GetMetatable(arg) && ((static_cast(what) & static_cast(TableOp::kR)) != 0// NOLINT(hicpp-signed-bitwise) || CheckField(state, "__index", n)) && ((static_cast(what) & static_cast(TableOp::kW)) != 0 // NOLINT(hicpp-signed-bitwise) || CheckField(state, "__newindex", n)) && ((static_cast(what) & static_cast(TableOp::kL)) != 0 // NOLINT(hicpp-signed-bitwise) || CheckField(state, "__len", n))) state->Pop(n); else state->CheckType(arg, api::LuaValueType::kTable); } } int64_t AuxGetN(const std::shared_ptr &state, int32_t n, TableOp w) { CheckTab(state, n, static_cast(static_cast(w) // NOLINT(hicpp-signed-bitwise) | static_cast(TableOp::kL))); // NOLINT(hicpp-signed-bitwise) return state->Len2(n); } } int32_t Move(const std::shared_ptr &state) { auto f = state->CheckInteger(2); auto e = state->CheckInteger(3); auto t = state->CheckInteger(4); int32_t tt = 1; if (!state->IsNoneOrNil(5)) tt = 5; CheckTab(state, 1, TableOp::kR); CheckTab(state, tt, TableOp::kW); if (e >= f) { int64_t n{}, i{}; state->ArgCheck(f > 0 || e < math::kMaxInteger + f, 3, "too many elements to move"); n = e - f + 1; state->ArgCheck(t <= math::kMaxInteger - n + 1, 4, "destination wrap around"); if (t > e || t <= f || (tt != 1 && !state->Compare(1, tt, api::CompareOp::kEQ))) { for (i = 0; i < n; i++) { state->GetI(1, f + i); state->SetI(tt, t + i); } } else { for (i = n - 1; i >= 0; --i) { state->GetI(1, f + 1); state->SetI(tt, t + i); } } } state->PushValue(tt); return 1; } int32_t Insert(const std::shared_ptr &state) { auto e = AuxGetN(state, 1, TableOp::kRW) + 1; int64_t pos{}; switch (state->GetTop()) { case 2:pos = e; break; case 3:pos = state->CheckInteger(2); state->ArgCheck(1 <= pos && pos <= e, 2, "position out of bound"); for (auto i = e; i > pos; --i) { state->GetI(1, i - 1); state->SetI(1, i); } break; default:return state->Error2("wrong number of arguments to 'insert'"); } state->SetI(1, pos); return 0; } int32_t Remove(const std::shared_ptr &state) { auto size = AuxGetN(state, 1, TableOp::kRW); auto pos = state->OptInteger(2, size); if (pos != size) state->ArgCheck(1 <= pos && pos <= size + 1, 1, "position out of bounds"); state->GetI(1, pos); for (; pos < size; ++pos) { state->GetI(1, pos + 1); state->SetI(1, pos); } state->PushNil(); state->SetI(1, pos); return 1; } class TableSortWrapper : public utils::Sortable { private: const std::shared_ptr &state_; public: explicit TableSortWrapper(const std::shared_ptr &state) : state_(state) {} [[nodiscard]] size_t Len() const override { return state_->Len2(1); } [[nodiscard]] bool Less(size_t i, size_t j) const override { if (state_->IsFunction(2)) { state_->PushValue(2); state_->GetI(1, i + 1); state_->GetI(1, j + 1); state_->Call(2, 1); auto b = state_->ToBoolean(-1); state_->Pop(1); return b; } state_->GetI(1, i + 1); state_->GetI(1, j + 1); auto b = state_->Compare(-2, -1, api::CompareOp::kLT); state_->Pop(2); return b; } void Swap(size_t i, size_t j) override { state_->GetI(1, i + 1); state_->GetI(1, j + 1); state_->SetI(1, i + 1); state_->SetI(1, j + 1); } ~TableSortWrapper() override = default; }; int32_t Sort(const std::shared_ptr &state) { auto wrapper = std::make_shared(state); state->ArgCheck(wrapper->Len() < kMaxLen, 1, "array too big"); utils::Sort(wrapper); return 0; } int32_t Concat(const std::shared_ptr &state) { auto tab_len = AuxGetN(state, 1, TableOp::kR); auto sep = state->OptString(2, ""); auto i = state->OptInteger(3, 1); auto j = state->OptInteger(4, tab_len); if (i > j) { state->PushString(""); return 1; } std::vector buf(j - i + 1); for (auto k = i; k > 0 && k <= j; ++k) { state->GetI(1, k); if (!state->IsString(-1)) state->Error2(fmt::format("invalid value({}) at index {} in table for 'concat'", state->TypeName2(-1), i)); buf[k - i] = state->ToString(-1); state->Pop(1); } state->PushString(utils::Join(buf, sep)); return 1; } int32_t Pack(const std::shared_ptr &state) { int64_t n = state->GetTop(); state->CreateTable(n, 1); state->Insert(1); for (auto i = n; i >= 1; --i) state->SetI(1, i); state->PushInteger(n); state->SetField(1, "n"); return 1; } int32_t Unpack(const std::shared_ptr &state) { auto i = state->OptInteger(2, 1); auto e = state->OptInteger(3, state->Len2(1)); if (i > e) return 0; auto n = e - i + 1; if (n <= 0 || n >= kMaxLen || !state->CheckStack(n)) return state->Error2("too many results to unpack"); for (; i < e; ++i) state->GetI(1, i); state->GetI(1, e); return n; } } }/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- */ /* * Main authors: * <> * * Contributing authors: * <> * * Copyright: * , 2004 * , 2004 * * This file is part of Gecode, the generic constraint * development environment: * http://www.gecode.org * * 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. * */ namespace Gecode { namespace Int { /// VarArg type for integer views template<> class ViewToVarArg { public: typedef IntVarArgs argtype; }; /// VarArg type for minus views template<> class ViewToVarArg { public: typedef IntVarArgs argtype; }; /// VarArg type for Boolean views template<> class ViewToVarArg { public: typedef BoolVarArgs argtype; }; /// VarArg type for Boolean views template<> class ViewToVarArg { public: typedef BoolVarArgs argtype; }; template forceinline IdxView* IdxView::allocate(Space& home, int n) { return home.alloc >(n); } template forceinline IdxViewArray::IdxViewArray(void) : xs(NULL), n(0) {} template forceinline IdxViewArray::IdxViewArray(const IdxViewArray& a) { n = a.n; xs = a.xs; } template forceinline IdxViewArray::IdxViewArray(Space& home, const typename ViewToVarArg::argtype& xa) : xs(NULL) { n = xa.size(); if (n>0) { xs = IdxView::allocate(home, n); for (int i=0; i forceinline IdxViewArray::IdxViewArray(Space& home, int n0) : xs(NULL) { n = n0; if (n>0) { xs = IdxView::allocate(home, n); } } template forceinline int IdxViewArray::size(void) const { return n; } template forceinline void IdxViewArray::size(int n0) { n = n0; } template forceinline IdxView& IdxViewArray::operator [](int i) { assert((i >= 0) && (i < size())); return xs[i]; } template forceinline const IdxView& IdxViewArray::operator [](int i) const { assert((i >= 0) && (i < size())); return xs[i]; } template forceinline void IdxViewArray::subscribe(Space& home, Propagator& p, PropCond pc, bool process) { for (int i=0; i forceinline void IdxViewArray::cancel(Space& home, Propagator& p, PropCond pc) { for (int i=0; i forceinline void IdxViewArray::reschedule(Space& home, Propagator& p, PropCond pc) { for (int i=0; i forceinline void IdxViewArray::update(Space& home, IdxViewArray& a) { n = a.size(); if (n>0) { xs = IdxView::allocate(home,n); for (int i=0; i std::basic_ostream& operator <<(std::basic_ostream& os, const IdxViewArray& x) { std::basic_ostringstream s; s.copyfmt(os); s.width(0); s << '{'; if (x.size() > 0) { s << x[0].idx << ':' << x[0].view; for (int i=1; iresources/kate/flow/execs/Builder.hpp #pragma once #include "Compiler.hpp" namespace flow { struct Builder { Builder(QString prog, QString targ, QString flowdir) : compiler_ (prog, flowdir), runner_(prog, targ, flowdir) { } const Compiler& compiler() const { return compiler_; } const Runner& runner() const { return runner_; } QString invocation() const; QStringList args(const QString& opts) const; QStringList compilerOpts(const QString&) const; QStringList builderOpts(const QString&) const; private: Compiler compiler_; Runner runner_; }; } #include #include #include int main() { std::vector x(10), y(10); for (int i = 0; i < 10; ++i) x[i] = i + 1; // copy x to y, then y = [1, 2, ... 10] cblas_dcopy(10, x.data(), 1, y.data(), 1); for (int i = 0; i < 10; ++i) std::cout << y[i] << ' '; std::cout << '\n'; // axpy y = 2*x+y cblas_daxpy(10, 2.0, x.data(), 1, y.data(), 1); // nrm2 ||y||_2 = sqrt(sum(y_i^2)) double nrm2 = cblas_dnrm2(10, y.data(), 1); } ///////////////////////////////////////////////////////////// // // // Copyright (c) 2003-2017 by The University of Queensland // // Centre for Geoscience Computing // // http://earth.uq.edu.au/centre-geoscience-computing // // // // Primary Business: Brisbane, Queensland, Australia // // Licensed under the Open Software License version 3.0 // // http://www.apache.org/licenses/LICENSE-2.0 // // // ///////////////////////////////////////////////////////////// #include #include #include #include "Python/esys/lsm/ParticleIdPairVectorPy.h" namespace esys { namespace lsm { void exportParticleIdPairVector() { // Disable autogeneration of C++ signatures (Boost 1.34.0 and higher) // for Epydoc which stumbles over indentation in the automatically generated strings. boost::python::docstring_options no_autogen(true,false); ParticleIdPairVectorPy::exportVector( "ParticleIdPairVector", "Vector of particle ID pairs." ); } } } #include #include "BazaTestu.hh" using namespace std; /*int main(int argc, char **argv) { if (argc < 2) { cout << endl; cout << " Brak opcji okreslajacej rodzaj testu." << endl; cout << " Dopuszczalne nazwy to: latwy, trudny." << endl; cout << endl; return 1; } BazaTestu BazaT = { nullptr, 0, 0 }; if (InicjalizujTest(&BazaT,argv[1]) == false) { cerr << " Inicjalizacja testu nie powiodla sie." << endl; return 1; } cout << endl; cout << " Start testu arytmetyki zespolonej: " << argv[1] << endl; cout << endl; WyrazenieZesp WyrZ_PytanieTestowe; while (PobierzNastpnePytanie(&BazaT,&WyrZ_PytanieTestowe)) { cout << " Czesc rzeczywista pierwszego argumentu: "; cout << WyrZ_PytanieTestowe.Arg1.re << endl; } cout << endl; cout << " Koniec testu" << endl; cout << endl; }*/ int main(){ LZespolona L1, L2, Wynik; char znak; cout << "Podaj liczbe zespolona" << endl; Wczytaj(L1); // Wyswietl(L1); cin >> znak; Wczytaj(L2); // Wyswietl(L2); switch(znak){ case '+': Wynik=Dodaj(L1,L2); break; case '-': Wynik=Odejmij(L1,L2); break; case '*': Wynik=Pomnoz(L1,L2); break; /* case '/': Wynik=Podziel(L1,L2); break;*/ } cout << " = " << Wyswietl(Wynik); /* DodajIPodstaw(&Wynik, Z1); operator+= (&Wynik, Z1); &Wynik += Z1; */ } /*=========================================================================== _____ _____ _____ _____ ___| _|__ __|_ |__ __|__ |__ __| __ |__ ______ | \ / | || \ || | || |/ / ||___ | | \/ | || \ || \ || \ ||___ | |__/\__/|__|_||__|\__\ __||__|\__\ __||__|\__\ __||______| |_____| |_____| |_____| |_____| --[Mark3 Realtime Platform]-------------------------------------------------- Copyright (c) 2012-2016 Funkenstein Software Consulting, all rights reserved. See license.txt for more information ===========================================================================*/ /*! \file unit_test.cpp \brief Unit test class definition */ #include "kerneltypes.h" #include "unit_test.h" //--------------------------------------------------------------------------- UnitTest::UnitTest() { m_bIsActive = false; m_u16Iterations = 0; m_u16Passed = 0; m_bComplete = false; } //--------------------------------------------------------------------------- void UnitTest::Pass() { if (m_bComplete) { return; } if (m_bIsActive) { m_bIsActive = false; m_u16Iterations++; m_u16Passed++; m_bStatus = true; } } //--------------------------------------------------------------------------- void UnitTest::Fail() { if (m_bComplete) { return; } if (m_bIsActive) { m_bIsActive = false; m_u16Iterations++; m_bStatus = false; } } 0 #include "endgame.h" bool isKvKNB(Board* b) { return popCount(b->occupied) == 4 && ( (getPieces(b, Piece::B, WHITE) && getPieces(b, Piece::N, WHITE)) || (getPieces(b, Piece::b, BLACK) && getPieces(b, Piece::n, BLACK))); } bool isKQvKR(Board* b) { return popCount(b->occupied) == 4 && ( (getPieces(b, Piece::Q, WHITE) && getPieces(b, Piece::r, BLACK)) || (getPieces(b, Piece::q, BLACK) && getPieces(b, Piece::R, WHITE))); } bool isKvKX(Board* b) { return popCount(b->pieces[PAWN]) == 0 && ( popCount(b->color[WHITE]) == 1 || popCount(b->color[BLACK]) == 1); } bool isKQvKP(Board* b) { return popCount(b->occupied) == 4 && ( (getPieces(b, Piece::Q, WHITE) && getPieces(b, Piece::p, BLACK)) || (getPieces(b, Piece::q, BLACK) && getPieces(b, Piece::P, WHITE))); } bool isKQvKQ(Board* b) { return popCount(b->occupied) == 4 && popCount(getPieces(b, QUEEN, WHITE)) && popCount(getPieces(b, QUEEN, BLACK)); } Value evaluate_KvKNB(Board* b) { Value eval = pieceValues[BISHOP] + pieceValues[KNIGHT]; Color strongColor = (b->material > 0) ? WHITE : BLACK; Color bishopColor = (b->pieces[BISHOP] & SQUARES_WHITE) ? WHITE : BLACK; Assert(popCount(b->color[strongColor ]) == 3); Assert(popCount(b->color[strongColor^1]) == 1); // 1) Minimize distance between kings int strongKingSq = getKingSquare(b, strongColor ); int weakKingSq = getKingSquare(b, !strongColor); int kDistance = manhatten[weakKingSq][strongKingSq]; eval -= 28 - kDistance * 2; // 2) Drive weak king towards corner of bishopColor eval += cornerReward[bishopColor][weakKingSq] * 2; return (b->stm == strongColor) ? eval : -eval; } Value evaluate_KQvKR(Board* b) { Value eval = pieceValues[QUEEN] - pieceValues[ROOK]; Color strongColor = (b->material > 0) ? WHITE : BLACK; // 1) Minimize distance between kings int strongKingSq = getKingSquare(b, strongColor ); int weakKingSq = getKingSquare(b, !strongColor); int kDistance = manhatten[weakKingSq][strongKingSq]; eval -= 14 - kDistance; // 2) Drive weak king towards border eval += borderReward[weakKingSq] * 10; return (b->stm == strongColor) ? eval : -eval; } Value evaluate_KQvKQ(Board* b) { int kSq1 = getKingSquare(b, WHITE); int kSq2 = getKingSquare(b, BLACK); int kDistance = manhatten[kSq1][kSq2]; return kDistance; } Value evaluate_KQvKP(Board* b) { Value eval = 0; Color strongColor = (b->material > 0) ? WHITE : BLACK; Assert(b->material != 0); Assert(popCount(getPieces(b, PAWN, !strongColor)) == 1); Assert(popCount(getPieces(b, QUEEN, strongColor)) == 1); Assert(popCount(b->occupied) == 4); // 1) Minimize distance between kings int strongKingSq = getKingSquare(b, strongColor); int weakKingSq = getKingSquare(b, !strongColor); int kDistance = manhatten[weakKingSq][strongKingSq]; Assert(kDistance <= 14); eval -= 2 * (14 - kDistance); // 2) Bishop- or rook-pawns on seventh-rank supported // by king are theoretical draw due to stalemate issues Bitboard pawnBoard = getPieces(b, PAWN, !strongColor); Bitboard seventh = (strongColor == WHITE) ? RANK_2_HEX : RANK_7_HEX; Bitboard winningFiles = FILE_B_HEX | FILE_D_HEX | FILE_E_HEX | FILE_G_HEX; // Winning case if ( pawnBoard & winningFiles || pawnBoard & ~seventh || !(kingAtkMask[weakKingSq] & pawnBoard)) { eval += pieceValues[QUEEN] - pieceValues[PAWN]; } return (b->stm == strongColor) ? eval : -eval; } acidicMercury8/xray-1.0 // (C) Copyright 2000. Permission to copy, use, modify, sell and // distribute this software is granted provided this copyright notice appears // in all copies. This software is provided "as is" without express or implied // warranty, and with no claim as to its suitability for any purpose. #ifndef TT_TEST_HPP #define TT_TEST_HPP #include // // basic configuration: // #ifdef TEST_STD #define tt std #define TYPE_TRAITS(x) #define TYPE_COMPARE(x) #define TYPE_TRANSFORM(x) #else #define tt boost #define TYPE_TRAITS(x) BOOST_STRINGIZE(boost/type_traits/x.hpp) #define TYPE_COMPARE(x) BOOST_STRINGIZE(boost/type_traits/x.hpp) #define TYPE_TRANSFORM(x) BOOST_STRINGIZE(boost/type_traits/x.hpp) #endif // // global unit, this is not safe, but until the unit test framework uses // shared_ptr throughout this is about as good as it gets :-( // boost::unit_test_framework::test_suite* get_master_unit(const char* name = 0); // // initialisation class: // class unit_initialiser { public: unit_initialiser(void (*f)(), const char* name) { get_master_unit("Type Traits")->add( ::boost::unit_test_framework::create_test_case(f, name) ); } }; #define TT_TEST_BEGIN(trait_name)\ namespace{\ void trait_name();\ unit_initialiser init(trait_name, BOOST_STRINGIZE(trait_name));\ void trait_name(){ #define TT_TEST_END }} #define TRANSFORM_CHECK(name, from_suffix, to_suffix)\ BOOST_CHECK_TYPE(bool to_suffix, name::type);\ BOOST_CHECK_TYPE(char to_suffix, name::type);\ BOOST_CHECK_TYPE(wchar_t to_suffix, name::type);\ BOOST_CHECK_TYPE(signed char to_suffix, name::type);\ BOOST_CHECK_TYPE(unsigned char to_suffix, name::type);\ BOOST_CHECK_TYPE(short to_suffix, name::type);\ BOOST_CHECK_TYPE(unsigned short to_suffix, name::type);\ BOOST_CHECK_TYPE(int to_suffix, name::type);\ BOOST_CHECK_TYPE(unsigned int to_suffix, name::type);\ BOOST_CHECK_TYPE(long to_suffix, name::type);\ BOOST_CHECK_TYPE(unsigned long to_suffix, name::type);\ BOOST_CHECK_TYPE(float to_suffix, name::type);\ BOOST_CHECK_TYPE(long double to_suffix, name::type);\ BOOST_CHECK_TYPE(double to_suffix, name::type);\ BOOST_CHECK_TYPE(UDT to_suffix, name::type);\ BOOST_CHECK_TYPE(enum1 to_suffix, name::type); #define BOOST_DUMMY_MACRO_PARAM /**/ #define BOOST_DECL_TRANSFORM_TEST(name, type, from, to)\ void name(){ TRANSFORM_CHECK(type, from, to) } #define BOOST_DECL_TRANSFORM_TEST3(name, type, from)\ void name(){ TRANSFORM_CHECK(type, from, BOOST_DUMMY_MACRO_PARAM) } #define BOOST_DECL_TRANSFORM_TEST2(name, type, to)\ void name(){ TRANSFORM_CHECK(type, BOOST_DUMMY_MACRO_PARAM, to) } #define BOOST_DECL_TRANSFORM_TEST0(name, type)\ void name(){ TRANSFORM_CHECK(type, BOOST_DUMMY_MACRO_PARAM, BOOST_DUMMY_MACRO_PARAM) } // // VC++ emits an awful lot of warnings unless we define these: #ifdef BOOST_MSVC # pragma warning(disable:4800) #endif // // define some test types: // enum enum_UDT{ one, two, three }; struct UDT { UDT(){}; ~UDT(){}; UDT(const UDT&); UDT& operator=(const UDT&); int i; void f1(); int f2(); int f3(int); int f4(int, float); }; typedef void(*f1)(); typedef int(*f2)(int); typedef int(*f3)(int, bool); typedef void (UDT::*mf1)(); typedef int (UDT::*mf2)(); typedef int (UDT::*mf3)(int); typedef int (UDT::*mf4)(int, float); typedef int (UDT::*mp); typedef int (UDT::*cmf)(int) const; // cv-qualifiers applied to reference types should have no effect // declare these here for later use with is_reference and remove_reference: # ifdef BOOST_MSVC # pragma warning(push) # pragma warning(disable: 4181) # elif defined(__ICL) # pragma warning(push) # pragma warning(disable: 21) # endif // // This is intentional: // r_type and cr_type should be the same type // but some compilers wrongly apply cv-qualifiers // to reference types (this may generate a warning // on some compilers): // typedef int& r_type; typedef const r_type cr_type; # ifdef BOOST_MSVC # pragma warning(pop) # elif defined(__ICL) # pragma warning(pop) # pragma warning(disable: 985) // identifier truncated in debug information # endif struct POD_UDT { int x; }; struct empty_UDT { ~empty_UDT(){}; empty_UDT& operator=(const empty_UDT&){ return *this; } bool operator==(const empty_UDT&)const { return true; } }; struct empty_POD_UDT { empty_POD_UDT& operator=(const empty_POD_UDT&){ return *this; } bool operator==(const empty_POD_UDT&)const { return true; } }; union union_UDT { int x; double y; ~union_UDT(){} }; union POD_union_UDT { int x; double y; }; union empty_union_UDT { ~empty_union_UDT(){} }; union empty_POD_union_UDT{}; class Base { }; class Derived : public Base { }; class Derived2 : public Base { }; class MultiBase : public Derived, public Derived2 {}; class PrivateBase : private Base {}; class NonDerived { }; enum enum1 { one_,two_ }; enum enum2 { three_,four_ }; struct VB { virtual ~VB(){}; }; struct VD : VB { ~VD(){}; }; // // struct non_pointer: // used to verify that is_pointer does not return // true for class types that implement operator void*() // struct non_pointer { operator void*(){return this;} }; struct non_int_pointer { int i; operator int*(){return &i;} }; struct int_constructible { int_constructible(int); }; struct int_convertible { operator int(); }; // // struct non_empty: // used to verify that is_empty does not emit // spurious warnings or errors. // struct non_empty : private boost::noncopyable { int i; }; // // abstract base classes: struct test_abc1 { virtual void foo() = 0; virtual void foo2() = 0; }; struct test_abc2 { virtual void foo() = 0; virtual void foo2() = 0; }; struct test_abc3 : public test_abc1 { virtual void foo3() = 0; }; struct incomplete_type; typedef void foo0_t(); typedef void foo1_t(int); typedef void foo2_t(int&, double); typedef void foo3_t(int&, bool, int, int); typedef void foo4_t(int, bool, int*, int[], int, int, int, int, int); #endif src/ball_chaser/src/process_image.cpp #include "ros/ros.h" #include "ball_chaser/DriveToTarget.h" #include ros::ServiceClient client; void drive_robot(float lin_x, float ang_z) { ball_chaser::DriveToTarget srv; srv.request.linear_x = lin_x; srv.request.angular_z = ang_z; if(!client.call(srv)) { ROS_ERROR("Failed to call service"); } } void process_image_callback(const sensor_msgs::Image img) { const int SCAN_START = img.data.size() / 3; const int SCAN_END = img.data.size() * 2 / 3; const int WHITE_PIXEL = 255; const float TURN = 1.5; const float MOVE = 0.5; const float STOP = 0; int whiteCount = 0; int xSum = 0; for(int i = 0; i + 2 < img.data.size(); i+=3) { int redChannel = img.data[i]; int blueChannel = img.data[i+1]; int greenChannel = img.data[i+2]; if(redChannel == WHITE_PIXEL && blueChannel == WHITE_PIXEL && greenChannel == WHITE_PIXEL) { whiteCount++; xSum += (i % (img.width * 3)) / 3; } } if(whiteCount == 0) { drive_robot(STOP, STOP); } else { int xMean = xSum / whiteCount; if(xMean < img.width / 3) { drive_robot(MOVE, TURN); return; } else if(xMean > img.width * 2 / 3) { drive_robot(MOVE, -(TURN)); return; } else { drive_robot(MOVE, STOP); return; } } } int main(int argc, char** argv) { ros::init(argc, argv, "process_image"); ros::NodeHandle n; client = n.serviceClient("/ball_chaser/command_robot"); ros::Subscriber sub1 = n.subscribe("/camera/rgb/image_raw", 10, process_image_callback); ros::spin(); return 0; } #include "Fireworks.h" #include "Lua.h" #include "consts.h" #include "Resources.h" #include "Game.h" Fireworks::Fireworks() {} void Fireworks::create(std::string type, Direction direction) { FireworksResources fireworks_resources = Resources::get_fireworks(type); duration = fireworks_resources.duration; sound = fireworks_resources.sound; oriented = fireworks_resources.oriented; set_texture(Resources::get_texture(fireworks_resources.sprite_sheet)); float fps = fireworks_resources.fps; std::vector frames = fireworks_resources.frames; if (oriented) { for (auto &vertices : frames) { switch (direction) { case Direction::UP: offset_tex_pos(&vertices[0], 0.f, (float)-fireworks_resources.sprite_height); break; case Direction::DOWN: offset_tex_pos(&vertices[0], 0.f, (float)fireworks_resources.sprite_height); break; case Direction::LEFT: offset_tex_pos(&vertices[0], (float)-fireworks_resources.sprite_width, 0.f); break; case Direction::RIGHT: offset_tex_pos(&vertices[0], (float)fireworks_resources.sprite_width, 0.f); break; case Direction::UP_RIGHT: offset_tex_pos(&vertices[0], (float)fireworks_resources.sprite_width, (float)-fireworks_resources.sprite_height); break; case Direction::UP_LEFT: offset_tex_pos(&vertices[0], (float)-fireworks_resources.sprite_width, (float)-fireworks_resources.sprite_height); break; case Direction::DOWN_RIGHT: offset_tex_pos(&vertices[0], (float)fireworks_resources.sprite_width, (float)fireworks_resources.sprite_height); break; case Direction::DOWN_LEFT: offset_tex_pos(&vertices[0], (float)-fireworks_resources.sprite_width, (float)fireworks_resources.sprite_height); break; } } } AnimatedEntity::set_animation(frames, fps); set_dimensions(fireworks_resources.sprite_height, fireworks_resources.sprite_width); } UVa/AC/Shopaholic_Solution-11369.cpp //Shopaholic_Solution-11369.cpp #include #include #include using namespace std; int main() { int n,t,price[20001],i,j; long int discount; scanf("%d",&t); for(i=0;i=0;j=j-3) discount=discount+price[j]; printf("%ld\n",discount); } return 0; } #include void show_value(int a) { std::cout << a << std::endl; return; // ここに到達した時点で呼び出し元に処理が戻る // return文で処理が戻っているためこの処理は呼ばれない std::cout << "show value" << std::endl; } int add(int a, int b) { int c = a + b; return c; } int main() { int x = add(10, 20); show_value(x); } latte-dock/app/settings/views/layoutsheaderview.cpp /* * Copyright 2020 <> * * This file is part of Latte-Dock * * Latte-Dock 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. * * Latte-Dock 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 . */ #include "layoutsheaderview.h" // local #include "../models/layoutsmodel.h" // Qt #include #include namespace Latte { namespace Settings { namespace Layouts { HeaderView::HeaderView(Qt::Orientation orientation, QWidget *parent) : QHeaderView(orientation, parent) { setSectionsClickable(true); setSectionsMovable(true); setSortIndicatorShown(true); } void HeaderView::paintSection(QPainter *painter, const QRect &rect, int logicalIndex) const { painter->setRenderHint(QPainter::Antialiasing, true); if (logicalIndex == Model::Layouts::BACKGROUNDCOLUMN) { QString text = model()->headerData(Model::Layouts::BACKGROUNDCOLUMN, Qt::Horizontal, Qt::DisplayRole).toString(); QIcon icon = model()->headerData(Model::Layouts::BACKGROUNDCOLUMN, Qt::Horizontal, Qt::DecorationRole).value(); if (text.isEmpty() && !icon.isNull()) { //! draw centered icon QHeaderView::paintSection(painter, rect, Model::Layouts::HIDDENTEXTCOLUMN); int margin = 4; int thick = rect.height() - 2*margin; int iX = rect.x() + (rect.width()/2) - (thick/2); painter->drawPixmap(QRect(iX, rect.y() + margin, thick, thick), icon.pixmap(thick, thick, QIcon::Normal)); return; } } QHeaderView::paintSection(painter, rect, logicalIndex); } } } } middleware/xatmi/source/xatmi/server.cpp0 //! //! Copyright (c) 2015, The casual project //! //! This software is licensed under the MIT license, https://opensource.org/licenses/MIT //! #include "casual/xatmi/server.h" #include "casual/xatmi/internal/log.h" #include "casual/xatmi/internal/code.h" #include "casual/xatmi/internal/transform.h" #include "common/server/start.h" #include "common/code/raise.h" #include "common/code/xatmi.h" #include "common/functional.h" #include "common/process.h" #include "common/event/send.h" #include "common/signal.h" #include #include namespace casual { namespace xatmi { namespace server { namespace local { namespace { namespace transform { template< typename A> auto services( A& value) { std::vector< common::server::argument::xatmi::Service> result; auto service = value.services; for( ; service->function_pointer != nullptr; ++service) { result.emplace_back( service->name, service->function_pointer, common::service::transaction::mode( service->transaction), service->category); } return result; } } // transform template< typename A> int start( const A& argument) { return common::exception::main::log::guard( [&argument]() { casual::xatmi::Trace trace{ "casual::xatmi::server::local::start"}; auto done = common::execute::scope( [done = argument.server_done]() { if( done) common::invoke( done); }); // We block child so users can spawn stuff without actions/errors from casual common::signal::thread::scope::Block block( { common::code::signal::child}); common::server::start( transform::services( argument), xatmi::transform::resources( argument.xa_switches), [&]() { if( argument.server_init && common::invoke( argument.server_init, argument.argc, argument.argv) == -1) { // if init is not ok, then we don't call done, symmetry with ctor/dtor done.release(); common::event::error::raise( common::code::xatmi::argument, "server initialize failed - action: exit"); } }); }); } } // } // local } // server } // xatmi } // casual int casual_start_server( struct casual_server_argument* arguments) { return casual::xatmi::server::local::start( *arguments); } int casual_run_server( struct casual_server_arguments* arguments) { return casual::xatmi::server::local::start( *arguments); } // Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/crash_upload_list/crash_upload_list_android.h" #include #include "base/android/jni_android.h" #include "base/android/jni_string.h" #include "base/files/file.h" #include "base/files/file_enumerator.h" #include "base/files/file_util.h" #include "base/metrics/histogram_macros_local.h" #include "chrome/android/chrome_jni_headers/MinidumpUploadService_jni.h" #include "ui/base/text/bytes_formatting.h" namespace { enum class UnsuccessfulUploadListState { FORCED, PENDING, NOT_UPLOADED, OTHER_FILENAME_SUFFIX, FAILED_TO_LOAD_FILE_INFO, FAILED_TO_LOAD_FILE_SIZE, FAILED_TO_FIND_DASH, ADDING_AN_UPLOAD_ENTRY, COUNT }; // TODO(isherman): This is a temporary histogram for debugging // [ https://crbug.com/772159 ] and should be removed once that bug is closed. void RecordUnsuccessfulUploadListState(UnsuccessfulUploadListState state) { LOCAL_HISTOGRAM_ENUMERATION( "Debug.Crash.Android.LoadUnsuccessfulUploadListState", state, UnsuccessfulUploadListState::COUNT); } } // namespace CrashUploadListAndroid::CrashUploadListAndroid( const base::FilePath& upload_log_path) : TextLogUploadList(upload_log_path) {} CrashUploadListAndroid::~CrashUploadListAndroid() {} // static bool CrashUploadListAndroid::BrowserCrashMetricsInitialized() { JNIEnv* env = base::android::AttachCurrentThread(); return Java_MinidumpUploadService_browserCrashMetricsInitialized(env); } // static bool CrashUploadListAndroid::DidBrowserCrashRecently() { JNIEnv* env = base::android::AttachCurrentThread(); return Java_MinidumpUploadService_didBrowserCrashRecently(env); } std::vector CrashUploadListAndroid::LoadUploadList() { std::vector uploads; LoadUnsuccessfulUploadList(&uploads); std::vector complete_uploads = TextLogUploadList::LoadUploadList(); for (auto info : complete_uploads) { uploads.push_back(info); } return uploads; } void CrashUploadListAndroid::RequestSingleUpload(const std::string& local_id) { JNIEnv* env = base::android::AttachCurrentThread(); base::android::ScopedJavaLocalRef j_local_id = base::android::ConvertUTF8ToJavaString(env, local_id); Java_MinidumpUploadService_tryUploadCrashDumpWithLocalId(env, j_local_id); } void CrashUploadListAndroid::LoadUnsuccessfulUploadList( std::vector* uploads) { const char pending_uploads[] = ".dmp"; const char skipped_uploads[] = ".skipped"; const char manually_forced_uploads[] = ".forced"; base::FileEnumerator files(upload_log_path().DirName(), false, base::FileEnumerator::FILES); for (base::FilePath file = files.Next(); !file.empty(); file = files.Next()) { UploadList::UploadInfo::State upload_state; if (file.value().find(manually_forced_uploads) != std::string::npos) { RecordUnsuccessfulUploadListState(UnsuccessfulUploadListState::FORCED); upload_state = UploadList::UploadInfo::State::Pending_UserRequested; } else if (file.value().find(pending_uploads) != std::string::npos) { RecordUnsuccessfulUploadListState(UnsuccessfulUploadListState::PENDING); upload_state = UploadList::UploadInfo::State::Pending; } else if (file.value().find(skipped_uploads) != std::string::npos) { RecordUnsuccessfulUploadListState( UnsuccessfulUploadListState::NOT_UPLOADED); upload_state = UploadList::UploadInfo::State::NotUploaded; } else { // The |file| is something other than a minidump file, e.g. a logcat file. RecordUnsuccessfulUploadListState( UnsuccessfulUploadListState::OTHER_FILENAME_SUFFIX); continue; } base::File::Info info; if (!base::GetFileInfo(file, &info)) { RecordUnsuccessfulUploadListState( UnsuccessfulUploadListState::FAILED_TO_LOAD_FILE_INFO); continue; } int64_t file_size = 0; if (!base::GetFileSize(file, &file_size)) { RecordUnsuccessfulUploadListState( UnsuccessfulUploadListState::FAILED_TO_LOAD_FILE_SIZE); continue; } // Crash reports can have multiple extensions (e.g. foo.dmp, foo.dmp.try1, // foo.skipped.try0). file = file.BaseName(); while (file != file.RemoveExtension()) file = file.RemoveExtension(); // ID is the last part of the file name. e.g. // chromium-renderer-minidump-f297dbcba7a2d0bb. std::string id = file.value(); std::size_t pos = id.find_last_of("-"); if (pos == std::string::npos) { RecordUnsuccessfulUploadListState( UnsuccessfulUploadListState::FAILED_TO_FIND_DASH); continue; } RecordUnsuccessfulUploadListState( UnsuccessfulUploadListState::ADDING_AN_UPLOAD_ENTRY); id = id.substr(pos + 1); UploadList::UploadInfo upload(id, info.creation_time, upload_state, ui::FormatBytes(file_size)); uploads->push_back(upload); } } #ifndef RANDPP_UNIFORM #define RANDPP_UNIFORM #include "randompp/Random_base.hpp" namespace rpp { template class Uniform : public Random { public: Uniform(); Uniform(const Uniform& obj); Uniform(unsigned int seed); Uniform(T min, T max); ~Uniform(); const T getMin() const {return min;} const T getMax() const {return max;} T random(); T random(T min, T max); private: T min; T max; }; template Uniform::Uniform() : Random() { min = (T)0; max = (T)1; } template Uniform::Uniform(const Uniform& obj) : Random(obj) { min = obj.getMin(); max = obj.getMax(); } template Uniform::Uniform(unsigned int seed) : Random(seed) { min = (T)0; max = (T)1; } template Uniform::Uniform(T min, T max) : Random() { this->min = min; this->max = max; } template Uniform::~Uniform() { /* nop */ } template T Uniform::random() { return (T)Random::random() * (max - min) + min; } template T Uniform::random(T min, T max) { return (T)Random::random() * (max - min) + min; } } #endif // // Created by kira on 01.05.2020. // #include "config.h" #include namespace parser { uint8_t parser::Config::get_mode() const { return _mode; } const geometry::Point &Config::get_center() const { return _center; } const std::vector &Config::get_vertices() const { return _vertices; } std::vector Config::get_tr_matrix() const { float cos = std::cos(_radian); float sin = std::sin(_radian); std::vector tr_matrix{ {cos, sin}, {-sin, cos} }; return std::move(tr_matrix); } const std::chrono::milliseconds &Config::get_timeout() const { return _timeout; } size_t Config::get_width() const { return _width; } size_t Config::get_length() const { return _length; } size_t Config::get_2d_objs_amount() const { return _width + _length; } } // namespace parser Hello_Window/OpenglTriangle.cpp #include #include #include // Function prototypes /* Callback function to resize window when main changes */ void framebufferSizeCallback(GLFWwindow* window, int width, int height); /* Callback for processing user inputs*/ void processInput(GLFWwindow* window); // Settings const unsigned int SCREEN_WIDTH = 800; const unsigned int SCREEN_HEIGHT = 600; int main() { // Initialize glfw if (!glfwInit()) { return -1; } // Setup glfw glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); // Create a window for rendering GLFWwindow* window = glfwCreateWindow(SCREEN_WIDTH, SCREEN_HEIGHT, "LeanOpenGL", NULL, NULL); if (window == NULL) { std::cout << "Failed to create GLFW window" << std::endl; glfwTerminate(); return -1; } glfwMakeContextCurrent(window); glfwSetFramebufferSizeCallback(window, framebufferSizeCallback); // glad: load all OpenGL function pointers if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) { std::cout << "Failed to initialize GLAD" << std::endl; return -1; } // Setup the size of the window glViewport(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT); // Render to the window as long as the while (!glfwWindowShouldClose(window)) { // input processInput(window); // rendering glClearColor(0.2f, 0.3f, 0.3f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); // check and call events and swap the buffers glfwSwapBuffers(window); glfwPollEvents(); } // Delete all GLFW allocated resources when program is closed. glfwTerminate(); return 0; } void framebufferSizeCallback(GLFWwindow* window, int width, int height) { glViewport(0, 0, width, height); } void processInput(GLFWwindow* window) { if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS) { glfwSetWindowShouldClose(window, true); } }#include using namespace std; class student { public: string name; int age; int roll_no; student(string h, int a, int r) { name = h; age = a; roll_no = r; } void print_info() { cout << name << " " << age << " " << roll_no; } ~student() { printf("I am distructor"); } }; int main() { student a("harsh", 89, 90); a.print_info(); return 0; }0 #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #define ll long long #define mod 1000000000 using namespace std; vector< vector > matrixMultiply(vector< vector > a, vector< vector > b) { ll r1 = a.size(), c1 = b.size(), c2 = b[0].size(); vector< vector > ans(r1, vector(c2)); for(ll i = 0; i < r1; i++) { for(ll j = 0; j < c2; j++) { ll element = 0; for(ll k = 0; k < c1; k++) { element += (a[i][k] * b[k][j]) % mod; } ans[i][j] = element % mod; } } return ans; } vector< vector > matrixExp(vector< vector > a, ll p) { if (p == 1) { return a; } vector< vector > ans(a.size(), vector(a[0].size(), 0)); for(ll i = 0; i < a.size(); i++) { for(ll j = 0; j < a.size(); j++) { if (i == j) { ans[i][j] = 1; } } } while (p > 0) { if (p & 1 > 0) { ans = matrixMultiply(ans, a); } p = p >> 1; a = matrixMultiply(a, a); } return ans; } ll seq(vector a, vector c, ll n, ll k) { if (a.size() >= n) { return a[n - 1]; } vector< vector > tr(k, vector(k)); for (ll i = 0; i < k; i++) { for (ll j = 0; j < k; j++) { if (i + 1 == j) { tr[i][j] = 1; } else if (i == k - 1) { tr[i][j] = c[k - j - 1]; } } } vector< vector > co(k, vector(1)); for (ll i = 0; i < k; i++) { co[i][0] = a[i]; } vector< vector > ans = matrixMultiply(matrixExp(tr, n - k), co); return ans[k - 1][0]; } int main() { ll t; cin >> t; while (t--) { ll k; cin >> k; vector a(k); for (ll i = 0; i < k; i++) { cin >> a[i]; } vector c(k); for (ll i = 0; i < k; i++) { cin >> c[i]; } ll n; cin >> n; cout << seq(a, c, n, k) << '\n'; } return 0; }#ifndef __SLEEPM_HEADER_INCLUDE__ #define __SLEEPM_HEADER_INCLUDE__ #include #include "HAL.hpp" #include "SleepM.hpp" #include "SleepSubscriber.hpp" const uint8_t maxSubscribers = 5; class SleepM { HAL *hal; uint32_t wakeupTime = 0; uint32_t sleepTime = 5; static SleepM *instance; uint8_t numSubscriber = 0; SleepSubscriber *subscriber[maxSubscribers]; SleepM(HAL *halptr):hal(halptr){} public: SleepM() { wakeupTime = ClockM::getInstance().getCtr(); sleepTime = wakeupTime+5; }; void cyclic(); void subscribe(SleepSubscriber *ref) { if(numSubscriberprolong(t);} void prolong(uint8_t t); static SleepM *getInstance(){return instance;} }; #endif //__SLEEPM_HEADER_INCLUDE__ #include "game_play.hpp" GamePlay::GamePlay() {} GamePlay::GamePlay(bool load) { // For testing load a map and an example human this->map = new Map("flatland.map"); this->entityIndex = 0; // Adding entities for testing this->entities.push_back(new Human(0, 10, 10)); this->cameraX = 0; this->cameraY = 0; this->view.reset(sf::FloatRect(0, 0, CONFIG.WINDOW_WIDTH, CONFIG.WINDOW_HEIGHT)); } void GamePlay::display(sf::RenderWindow& window) { // Check for keypress if (sf::Keyboard::isKeyPressed(CONFIG.KEY_UP)) { this->cameraY -= this->map->tileset.tileHeight / 4; } if (sf::Keyboard::isKeyPressed(CONFIG.KEY_DOWN)) { this->cameraY += this->map->tileset.tileHeight / 4; } if (sf::Keyboard::isKeyPressed(CONFIG.KEY_LEFT)) { this->cameraX -= this->map->tileset.tileWidth / 4; } if (sf::Keyboard::isKeyPressed(CONFIG.KEY_RIGHT)) { this->cameraX += this->map->tileset.tileWidth / 4; } // Display the map this->map->display(window); // Display entities for (Entity* entity : this->entities) { entity->display(window); } this->view.setCenter(this->cameraX + CONFIG.WINDOW_WIDTH / 2, this->cameraY + CONFIG.WINDOW_HEIGHT / 2); window.setView(this->view); } 1-10 /** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 / * * 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 . * */ /** * Software SPI functions originally from Arduino Sd2Card Library * Copyright (c) 2009 by */ /** * For TARGET_LPC1768 */ /** * Hardware SPI and Software SPI implementations are included in this file. * The hardware SPI runs faster and has higher throughput but is not compatible * with some LCD interfaces/adapters. * * Control of the slave select pin(s) is handled by the calling routines. * * Some of the LCD interfaces/adapters result in the LCD SPI and the SD card * SPI sharing pins. The SCK, MOSI & MISO pins can NOT be set/cleared with * WRITE nor digitalWrite when the hardware SPI module within the LPC17xx is * active. If any of these pins are shared then the software SPI must be used. * * A more sophisticated hardware SPI can be found at the following link. This * implementation has not been fully debugged. * https://github.com/MarlinFirmware/Marlin/tree/071c7a78f27078fd4aee9a3ef365fcf5e143531e */ #ifdef TARGET_LPC1768 #include "../../inc/MarlinConfig.h" #include // Hardware SPI and SPIClass #include #include // ------------------------ // Public functions // ------------------------ #if ENABLED(LPC_SOFTWARE_SPI) #include // Software SPI static uint8_t SPI_speed = 0; static uint8_t spiTransfer(uint8_t b) { return swSpiTransfer(b, SPI_speed, SCK_PIN, MISO_PIN, MOSI_PIN); } void spiBegin() { swSpiBegin(SCK_PIN, MISO_PIN, MOSI_PIN); } void spiInit(uint8_t spiRate) { SPI_speed = swSpiInit(spiRate, SCK_PIN, MOSI_PIN); } uint8_t spiRec() { return spiTransfer(0xFF); } void spiRead(uint8_t*buf, uint16_t nbyte) { for (int i = 0; i < nbyte; i++) buf[i] = spiTransfer(0xFF); } void spiSend(uint8_t b) { (void)spiTransfer(b); } void spiSend(const uint8_t* buf, size_t nbyte) { for (uint16_t i = 0; i < nbyte; i++) (void)spiTransfer(buf[i]); } void spiSendBlock(uint8_t token, const uint8_t* buf) { (void)spiTransfer(token); for (uint16_t i = 0; i < 512; i++) (void)spiTransfer(buf[i]); } #else // decide which HW SPI device to use #ifndef LPC_HW_SPI_DEV #if (SCK_PIN == P0_07 && MISO_PIN == P0_08 && MOSI_PIN == P0_09) #define LPC_HW_SPI_DEV 1 #else #if (SCK_PIN == P0_15 && MISO_PIN == P0_17 && MOSI_PIN == P0_18) #define LPC_HW_SPI_DEV 0 #else #error "Invalid pins selected for hardware SPI" #endif #endif #endif #if LPC_HW_SPI_DEV == 0 #define LPC_SSPn LPC_SSP0 #else #define LPC_SSPn LPC_SSP1 #endif void spiBegin() { // setup SCK, MOSI & MISO pins for SSP0 PINSEL_CFG_Type PinCfg; // data structure to hold init values PinCfg.Funcnum = 2; PinCfg.OpenDrain = 0; PinCfg.Pinmode = 0; PinCfg.Pinnum = LPC176x::pin_bit(SCK_PIN); PinCfg.Portnum = LPC176x::pin_port(SCK_PIN); PINSEL_ConfigPin(&PinCfg); SET_OUTPUT(SCK_PIN); PinCfg.Pinnum = LPC176x::pin_bit(MISO_PIN); PinCfg.Portnum = LPC176x::pin_port(MISO_PIN); PINSEL_ConfigPin(&PinCfg); SET_INPUT(MISO_PIN); PinCfg.Pinnum = LPC176x::pin_bit(MOSI_PIN); PinCfg.Portnum = LPC176x::pin_port(MOSI_PIN); PINSEL_ConfigPin(&PinCfg); SET_OUTPUT(MOSI_PIN); // divide PCLK by 2 for SSP0 CLKPWR_SetPCLKDiv(LPC_HW_SPI_DEV == 0 ? CLKPWR_PCLKSEL_SSP0 : CLKPWR_PCLKSEL_SSP1, CLKPWR_PCLKSEL_CCLK_DIV_2); spiInit(0); SSP_Cmd(LPC_SSPn, ENABLE); // start SSP running } void spiInit(uint8_t spiRate) { // table to convert Marlin spiRates (0-5 plus default) into bit rates uint32_t Marlin_speed[7]; // CPSR is always 2 Marlin_speed[0] = 8333333; //(SCR: 2) desired: 8,000,000 actual: 8,333,333 +4.2% SPI_FULL_SPEED Marlin_speed[1] = 4166667; //(SCR: 5) desired: 4,000,000 actual: 4,166,667 +4.2% SPI_HALF_SPEED Marlin_speed[2] = 2083333; //(SCR: 11) desired: 2,000,000 actual: 2,083,333 +4.2% SPI_QUARTER_SPEED Marlin_speed[3] = 1000000; //(SCR: 24) desired: 1,000,000 actual: 1,000,000 SPI_EIGHTH_SPEED Marlin_speed[4] = 500000; //(SCR: 49) desired: 500,000 actual: 500,000 SPI_SPEED_5 Marlin_speed[5] = 250000; //(SCR: 99) desired: 250,000 actual: 250,000 SPI_SPEED_6 Marlin_speed[6] = 125000; //(SCR:199) desired: 125,000 actual: 125,000 Default from HAL.h // setup for SPI mode SSP_CFG_Type HW_SPI_init; // data structure to hold init values SSP_ConfigStructInit(&HW_SPI_init); // set values for SPI mode HW_SPI_init.ClockRate = Marlin_speed[_MIN(spiRate, 6)]; // put in the specified bit rate HW_SPI_init.Mode |= SSP_CR1_SSP_EN; SSP_Init(LPC_SSPn, &HW_SPI_init); // puts the values into the proper bits in the SSP0 registers } static uint8_t doio(uint8_t b) { /* send and receive a single byte */ SSP_SendData(LPC_SSPn, b & 0x00FF); while (SSP_GetStatus(LPC_SSPn, SSP_STAT_BUSY)); // wait for it to finish return SSP_ReceiveData(LPC_SSPn) & 0x00FF; } void spiSend(uint8_t b) { doio(b); } void spiSend(const uint8_t* buf, size_t nbyte) { for (uint16_t i = 0; i < nbyte; i++) doio(buf[i]); } void spiSend(uint32_t chan, byte b) { } void spiSend(uint32_t chan, const uint8_t* buf, size_t nbyte) { } // Read single byte from SPI uint8_t spiRec() { return doio(0xFF); } uint8_t spiRec(uint32_t chan) { return 0; } // Read from SPI into buffer void spiRead(uint8_t *buf, uint16_t nbyte) { for (uint16_t i = 0; i < nbyte; i++) buf[i] = doio(0xFF); } uint8_t spiTransfer(uint8_t b) { return doio(b); } // Write from buffer to SPI void spiSendBlock(uint8_t token, const uint8_t* buf) { (void)spiTransfer(token); for (uint16_t i = 0; i < 512; i++) (void)spiTransfer(buf[i]); } /** Begin SPI transaction, set clock, bit order, data mode */ void spiBeginTransaction(uint32_t spiClock, uint8_t bitOrder, uint8_t dataMode) { // TODO: to be implemented } #endif // LPC_SOFTWARE_SPI /** * @brief Wait until TXE (tx empty) flag is set and BSY (busy) flag unset. */ static inline void waitSpiTxEnd(LPC_SSP_TypeDef *spi_d) { while (SSP_GetStatus(spi_d, SSP_STAT_TXFIFO_EMPTY) == RESET) { /* nada */ } // wait until TXE=1 while (SSP_GetStatus(spi_d, SSP_STAT_BUSY) == SET) { /* nada */ } // wait until BSY=0 } SPIClass::SPIClass(uint8_t device) { // Init things specific to each SPI device // clock divider setup is a bit of hack, and needs to be improved at a later date. PINSEL_CFG_Type PinCfg; // data structure to hold init values #if BOARD_NR_SPI >= 1 _settings[0].spi_d = LPC_SSP0; // _settings[0].clockDivider = determine_baud_rate(_settings[0].spi_d, _settings[0].clock); PinCfg.Funcnum = 2; PinCfg.OpenDrain = 0; PinCfg.Pinmode = 0; PinCfg.Pinnum = LPC176x::pin_bit(BOARD_SPI1_SCK_PIN); PinCfg.Portnum = LPC176x::pin_port(BOARD_SPI1_SCK_PIN); PINSEL_ConfigPin(&PinCfg); SET_OUTPUT(BOARD_SPI1_SCK_PIN); PinCfg.Pinnum = LPC176x::pin_bit(BOARD_SPI1_MISO_PIN); PinCfg.Portnum = LPC176x::pin_port(BOARD_SPI1_MISO_PIN); PINSEL_ConfigPin(&PinCfg); SET_INPUT(BOARD_SPI1_MISO_PIN); PinCfg.Pinnum = LPC176x::pin_bit(BOARD_SPI1_MOSI_PIN); PinCfg.Portnum = LPC176x::pin_port(BOARD_SPI1_MOSI_PIN); PINSEL_ConfigPin(&PinCfg); SET_OUTPUT(BOARD_SPI1_MOSI_PIN); #endif #if BOARD_NR_SPI >= 2 _settings[1].spi_d = LPC_SSP1; // _settings[1].clockDivider = determine_baud_rate(_settings[1].spi_d, _settings[1].clock); PinCfg.Funcnum = 2; PinCfg.OpenDrain = 0; PinCfg.Pinmode = 0; PinCfg.Pinnum = LPC176x::pin_bit(BOARD_SPI2_SCK_PIN); PinCfg.Portnum = LPC176x::pin_port(BOARD_SPI2_SCK_PIN); PINSEL_ConfigPin(&PinCfg); SET_OUTPUT(BOARD_SPI2_SCK_PIN); PinCfg.Pinnum = LPC176x::pin_bit(BOARD_SPI2_MISO_PIN); PinCfg.Portnum = LPC176x::pin_port(BOARD_SPI2_MISO_PIN); PINSEL_ConfigPin(&PinCfg); SET_INPUT(BOARD_SPI2_MISO_PIN); PinCfg.Pinnum = LPC176x::pin_bit(BOARD_SPI2_MOSI_PIN); PinCfg.Portnum = LPC176x::pin_port(BOARD_SPI2_MOSI_PIN); PINSEL_ConfigPin(&PinCfg); SET_OUTPUT(BOARD_SPI2_MOSI_PIN); #endif setModule(device); /* Initialize GPDMA controller */ //TODO: call once in the constructor? or each time? GPDMA_Init(); } void SPIClass::begin() { updateSettings(); SSP_Cmd(_currentSetting->spi_d, ENABLE); // start SSP running } void SPIClass::beginTransaction(const SPISettings &cfg) { setBitOrder(cfg.bitOrder); setDataMode(cfg.dataMode); setDataSize(cfg.dataSize); //setClockDivider(determine_baud_rate(_currentSetting->spi_d, settings.clock)); begin(); } uint8_t SPIClass::transfer(const uint16_t b) { /* send and receive a single byte */ SSP_ReceiveData(_currentSetting->spi_d); // read any previous data SSP_SendData(_currentSetting->spi_d, b); waitSpiTxEnd(_currentSetting->spi_d); // wait for it to finish return SSP_ReceiveData(_currentSetting->spi_d); } uint16_t SPIClass::transfer16(const uint16_t data) { return (transfer((data >> 8) & 0xFF) << 8) | (transfer(data & 0xFF) & 0xFF); } void SPIClass::end() { // SSP_Cmd(_currentSetting->spi_d, DISABLE); // stop device or SSP_DeInit? SSP_DeInit(_currentSetting->spi_d); } void SPIClass::send(uint8_t data) { SSP_SendData(_currentSetting->spi_d, data); } void SPIClass::dmaSend(void *buf, uint16_t length, bool minc) { //TODO: LPC dma can only write 0xFFF bytes at once. GPDMA_Channel_CFG_Type GPDMACfg; /* Configure GPDMA channel 0 -------------------------------------------------------------*/ /* DMA Channel 0 */ GPDMACfg.ChannelNum = 0; // Source memory GPDMACfg.SrcMemAddr = (uint32_t)buf; // Destination memory - Not used GPDMACfg.DstMemAddr = 0; // Transfer size GPDMACfg.TransferSize = (minc ? length : 1); // Transfer width GPDMACfg.TransferWidth = (_currentSetting->dataSize == DATA_SIZE_16BIT) ? GPDMA_WIDTH_HALFWORD : GPDMA_WIDTH_BYTE; // Transfer type GPDMACfg.TransferType = GPDMA_TRANSFERTYPE_M2P; // Source connection - unused GPDMACfg.SrcConn = 0; // Destination connection GPDMACfg.DstConn = (_currentSetting->spi_d == LPC_SSP0) ? GPDMA_CONN_SSP0_Tx : GPDMA_CONN_SSP1_Tx; GPDMACfg.DMALLI = 0; // Enable dma on SPI SSP_DMACmd(_currentSetting->spi_d, SSP_DMA_TX, ENABLE); // if minc=false, I'm repeating the same byte 'length' times, as I could not find yet how do GPDMA without memory increment do { // Setup channel with given parameter GPDMA_Setup(&GPDMACfg); // enabled dma GPDMA_ChannelCmd(0, ENABLE); // wait data transfer while (!GPDMA_IntGetStatus(GPDMA_STAT_INTTC, 0) && !GPDMA_IntGetStatus(GPDMA_STAT_INTERR, 0)) { } // clear err and int GPDMA_ClearIntPending (GPDMA_STATCLR_INTTC, 0); GPDMA_ClearIntPending (GPDMA_STATCLR_INTERR, 0); // dma disable GPDMA_ChannelCmd(0, DISABLE); --length; } while (!minc && length > 0); waitSpiTxEnd(_currentSetting->spi_d); SSP_DMACmd(_currentSetting->spi_d, SSP_DMA_TX, DISABLE); } uint16_t SPIClass::read() { return SSP_ReceiveData(_currentSetting->spi_d); } void SPIClass::read(uint8_t *buf, uint32_t len) { for (uint16_t i = 0; i < len; i++) buf[i] = transfer(0xFF); } void SPIClass::setClock(uint32_t clock) { _currentSetting->clock = clock; } void SPIClass::setModule(uint8_t device) { _currentSetting = &_settings[device - 1];// SPI channels are called 1 2 and 3 but the array is zero indexed } void SPIClass::setBitOrder(uint8_t bitOrder) { _currentSetting->bitOrder = bitOrder; } void SPIClass::setDataMode(uint8_t dataMode) { _currentSetting->dataSize = dataMode; } void SPIClass::setDataSize(uint32_t ds) { _currentSetting->dataSize = ds; } /** * Set up/tear down */ void SPIClass::updateSettings() { //SSP_DeInit(_currentSetting->spi_d); //todo: need force de init?! // divide PCLK by 2 for SSP0 CLKPWR_SetPCLKDiv(_currentSetting->spi_d == LPC_SSP0 ? CLKPWR_PCLKSEL_SSP0 : CLKPWR_PCLKSEL_SSP1, CLKPWR_PCLKSEL_CCLK_DIV_2); SSP_CFG_Type HW_SPI_init; // data structure to hold init values SSP_ConfigStructInit(&HW_SPI_init); // set values for SPI mode HW_SPI_init.ClockRate = _currentSetting->clock; HW_SPI_init.Databit = _currentSetting->dataSize; /** * SPI Mode CPOL CPHA Shift SCK-edge Capture SCK-edge * 0 0 0 Falling Rising * 1 0 1 Rising Falling * 2 1 0 Rising Falling * 3 1 1 Falling Rising */ switch (_currentSetting->dataMode) { case SPI_MODE0: HW_SPI_init.CPHA = SSP_CPHA_FIRST; HW_SPI_init.CPOL = SSP_CPOL_HI; break; case SPI_MODE1: HW_SPI_init.CPHA = SSP_CPHA_SECOND; HW_SPI_init.CPOL = SSP_CPOL_HI; break; case SPI_MODE2: HW_SPI_init.CPHA = SSP_CPHA_FIRST; HW_SPI_init.CPOL = SSP_CPOL_LO; break; case SPI_MODE3: HW_SPI_init.CPHA = SSP_CPHA_SECOND; HW_SPI_init.CPOL = SSP_CPOL_LO; break; default: break; } // TODO: handle bitOrder SSP_Init(_currentSetting->spi_d, &HW_SPI_init); // puts the values into the proper bits in the SSP0 registers } #if MISO_PIN == BOARD_SPI1_MISO_PIN SPIClass SPI(1); #elif MISO_PIN == BOARD_SPI2_MISO_PIN SPIClass SPI(2); #endif #endif // TARGET_LPC1768 bHimes/cisTEMx //#include "../core/core_headers.h" #include "../core/cistem_constants.h" #include "../core/gui_core_headers.h" // extern MyMovieAssetPanel *movie_asset_panel; extern MyImageAssetPanel* image_asset_panel; extern MyVolumeAssetPanel* volume_asset_panel; extern MyRunProfilesPanel* run_profiles_panel; extern MyMainFrame* main_frame; extern MatchTemplateResultsPanel* match_template_results_panel; MatchTemplatePanel::MatchTemplatePanel(wxWindow* parent) : MatchTemplatePanelParent(parent) { // Set variables my_job_id = -1; running_job = false; group_combo_is_dirty = false; run_profiles_are_dirty = false; set_up_to_resume_job = false; #ifndef ENABLEGPU UseGpuCheckBox->Show(false); #endif SetInfo( ); FillGroupComboBox( ); FillRunProfileComboBox( ); wxSize input_size = InputSizer->GetMinSize( ); input_size.x += wxSystemSettings::GetMetric(wxSYS_VSCROLL_X); input_size.y = -1; ExpertPanel->SetMinSize(input_size); ExpertPanel->SetSize(input_size); ResetDefaults( ); // EnableMovieProcessingIfAppropriate(); result_bitmap.Create(1, 1, 24); time_of_last_result_update = time(NULL); DefocusSearchRangeNumericCtrl->SetMinMaxValue(0.0f, FLT_MAX); DefocusSearchStepNumericCtrl->SetMinMaxValue(1.0f, FLT_MAX); PixelSizeSearchRangeNumericCtrl->SetMinMaxValue(0.0f, FLT_MAX); PixelSizeSearchStepNumericCtrl->SetMinMaxValue(0.01f, FLT_MAX); HighResolutionLimitNumericCtrl->SetMinMaxValue(0.0f, FLT_MAX); SymmetryComboBox->Clear( ); SymmetryComboBox->Append("C1"); SymmetryComboBox->Append("C2"); SymmetryComboBox->Append("C3"); SymmetryComboBox->Append("C4"); SymmetryComboBox->Append("D2"); SymmetryComboBox->Append("D3"); SymmetryComboBox->Append("D4"); SymmetryComboBox->Append("I"); SymmetryComboBox->Append("I2"); SymmetryComboBox->Append("O"); SymmetryComboBox->Append("T"); SymmetryComboBox->Append("T2"); SymmetryComboBox->SetSelection(0); GroupComboBox->AssetComboBox->Bind(wxEVT_COMMAND_COMBOBOX_SELECTED, &MatchTemplatePanel::OnGroupComboBox, this); } /* void MatchTemplatePanel::EnableMovieProcessingIfAppropriate() { // Check whether all members of the group have movie parents. If not, make sure we only allow image processing MovieRadioButton->Enable(true); NoMovieFramesStaticText->Enable(true); NoFramesToAverageSpinCtrl->Enable(true); for (int counter = 0; counter < image_asset_panel->ReturnGroupSize(GroupComboBox->GetSelection()); counter ++ ) { if (image_asset_panel->all_assets_list->ReturnAssetPointer(image_asset_panel->ReturnGroupMember(GroupComboBox->GetSelection(),counter))->parent_id < 0) { MovieRadioButton->SetValue(false); MovieRadioButton->Enable(false); NoMovieFramesStaticText->Enable(false); NoFramesToAverageSpinCtrl->Enable(false); ImageRadioButton->SetValue(true); } } } */ void MatchTemplatePanel::ResetAllDefaultsClick(wxCommandEvent& event) { ResetDefaults( ); } void MatchTemplatePanel::OnInfoURL(wxTextUrlEvent& event) { const wxMouseEvent& ev = event.GetMouseEvent( ); // filter out mouse moves, too many of them if ( ev.Moving( ) ) return; long start = event.GetURLStart( ); wxTextAttr my_style; InfoText->GetStyle(start, my_style); // Launch the URL wxLaunchDefaultBrowser(my_style.GetURL( )); } void MatchTemplatePanel::Reset( ) { ProgressBar->SetValue(0); TimeRemainingText->SetLabel("Time Remaining : ???h:??m:??s"); CancelAlignmentButton->Show(true); FinishButton->Show(false); ProgressPanel->Show(false); StartPanel->Show(true); OutputTextPanel->Show(false); output_textctrl->Clear( ); ResultsPanel->Show(false); InputPanel->Show(true); //graph_is_hidden = true; InfoPanel->Show(true); ResultsPanel->Clear( ); if ( running_job == true ) { main_frame->job_controller.KillJob(my_job_id); cached_results.Clear( ); running_job = false; } ResetDefaults( ); Layout( ); } void MatchTemplatePanel::ResetDefaults( ) { OutofPlaneStepNumericCtrl->ChangeValueFloat(2.5); InPlaneStepNumericCtrl->ChangeValueFloat(1.5); MinPeakRadiusNumericCtrl->ChangeValueFloat(10.0f); DefocusSearchYesRadio->SetValue(true); PixelSizeSearchNoRadio->SetValue(true); set_up_to_resume_job = false; SymmetryComboBox->SetValue("C1"); if ( main_frame->current_project.is_open ) { ResumeRunCheckBox->SetValue(false); if ( main_frame->current_project.database.ReturnNumberOfTemplateMatchingJobs( ) == 0 ) ResumeRunCheckBox->Enable(false); else ResumeRunCheckBox->Enable(true); } else { ResumeRunCheckBox->Enable(false); } #ifdef ENABLEGPU UseGpuCheckBox->SetValue(true); #else UseGpuCheckBox->SetValue(false); // Already disabled, but also set to un-ticked for visual consistency. #endif DefocusSearchRangeNumericCtrl->ChangeValueFloat(1200.0f); DefocusSearchStepNumericCtrl->ChangeValueFloat(200.0f); PixelSizeSearchRangeNumericCtrl->ChangeValueFloat(0.05f); PixelSizeSearchStepNumericCtrl->ChangeValueFloat(0.01f); // AssetGroup active_group; active_group.CopyFrom(&image_asset_panel->all_groups_list->groups[GroupComboBox->GetSelection( )]); if ( active_group.number_of_members > 0 ) { ImageAsset* current_image; current_image = image_asset_panel->ReturnAssetPointer(GroupComboBox->GetSelection( )); HighResolutionLimitNumericCtrl->ChangeValueFloat(2.0f * current_image->pixel_size); } } void MatchTemplatePanel::OnGroupComboBox(wxCommandEvent& event) { // ResetDefaults(); // AssetGroup active_group; active_group.CopyFrom(&image_asset_panel->all_groups_list->groups[GroupComboBox->GetSelection( )]); if ( active_group.number_of_members > 0 ) { ImageAsset* current_image; current_image = image_asset_panel->ReturnAssetPointer(active_group.members[0]); HighResolutionLimitNumericCtrl->ChangeValueFloat(2.0f * current_image->pixel_size); } if ( GroupComboBox->GetCount( ) > 0 && main_frame->current_project.is_open == true ) all_images_have_defocus_values = CheckGroupHasDefocusValues( ); if ( all_images_have_defocus_values == true && PleaseEstimateCTFStaticText->IsShown( ) == true ) { PleaseEstimateCTFStaticText->Show(false); Layout( ); } else if ( all_images_have_defocus_values == false && PleaseEstimateCTFStaticText->IsShown( ) == false ) { PleaseEstimateCTFStaticText->Show(true); Layout( ); } } void MatchTemplatePanel::SetInfo( ) { /* #include "icons/ctffind_definitions.cpp" #include "icons/ctffind_diagnostic_image.cpp" #include "icons/ctffind_example_1dfit.cpp" wxLogNull *suppress_png_warnings = new wxLogNull; wxBitmap definitions_bmp = wxBITMAP_PNG_FROM_DATA(ctffind_definitions); wxBitmap diagnostic_image_bmp = wxBITMAP_PNG_FROM_DATA(ctffind_diagnostic_image); wxBitmap example_1dfit_bmp = wxBITMAP_PNG_FROM_DATA(ctffind_example_1dfit); delete suppress_png_warnings;*/ InfoText->GetCaret( )->Hide( ); InfoText->BeginSuppressUndo( ); InfoText->BeginAlignment(wxTEXT_ALIGNMENT_CENTRE); InfoText->BeginBold( ); InfoText->BeginUnderline( ); InfoText->BeginFontSize(14); InfoText->WriteText(wxT("Match Templates")); InfoText->EndFontSize( ); InfoText->EndBold( ); InfoText->EndUnderline( ); InfoText->Newline( ); InfoText->Newline( ); InfoText->EndAlignment( ); InfoText->BeginAlignment(wxTEXT_ALIGNMENT_LEFT); InfoText->WriteText(wxT("Blah Blah Blah - See (Rickgauer, 2017).")); InfoText->Newline( ); InfoText->Newline( ); InfoText->EndAlignment( ); InfoText->BeginAlignment(wxTEXT_ALIGNMENT_CENTRE); InfoText->BeginBold( ); InfoText->BeginUnderline( ); InfoText->WriteText(wxT("Program Options")); InfoText->EndBold( ); InfoText->EndUnderline( ); InfoText->Newline( ); InfoText->Newline( ); InfoText->EndAlignment( ); InfoText->BeginAlignment(wxTEXT_ALIGNMENT_LEFT); InfoText->BeginBold( ); InfoText->WriteText(wxT("Input Group : ")); InfoText->EndBold( ); InfoText->WriteText(wxT("The group of image assets to look for templates in")); InfoText->Newline( ); InfoText->BeginBold( ); InfoText->WriteText(wxT("Reference Volume : ")); InfoText->EndBold( ); InfoText->WriteText(wxT("The volume that will used for the template search.")); InfoText->Newline( ); InfoText->BeginBold( ); InfoText->WriteText(wxT("Run Profile : ")); InfoText->EndBold( ); InfoText->WriteText(wxT("The selected run profile will be used to run the job. The run profile describes how the job should be run (e.g. how many processors should be used, and on which different computers). Run profiles are set in the Run Profile panel, located under settings.")); InfoText->Newline( ); InfoText->Newline( ); InfoText->EndAlignment( ); InfoText->BeginAlignment(wxTEXT_ALIGNMENT_CENTRE); InfoText->BeginBold( ); InfoText->BeginUnderline( ); InfoText->WriteText(wxT("Expert Options")); InfoText->EndBold( ); InfoText->EndUnderline( ); InfoText->Newline( ); InfoText->Newline( ); InfoText->EndAlignment( ); InfoText->BeginAlignment(wxTEXT_ALIGNMENT_LEFT); InfoText->BeginBold( ); InfoText->WriteText(wxT("Out of Plane Angular Step : ")); InfoText->EndBold( ); InfoText->WriteText(wxT("The angular step that should be used for the out of plane search. Smaller values may increase accuracy, but will significantly increase the required processing time.")); InfoText->Newline( ); InfoText->BeginBold( ); InfoText->WriteText(wxT("In Plane Angular Step : ")); InfoText->EndBold( ); InfoText->WriteText(wxT("The angular step that should be used for the in plane search. As with the out of plane angle, smaller values may increase accuracy, but will significantly increase the required processing time.")); InfoText->Newline( ); InfoText->Newline( ); InfoText->EndAlignment( ); InfoText->BeginAlignment(wxTEXT_ALIGNMENT_CENTRE); InfoText->BeginBold( ); InfoText->BeginUnderline( ); InfoText->WriteText(wxT("References")); InfoText->EndBold( ); InfoText->EndUnderline( ); InfoText->Newline( ); InfoText->Newline( ); InfoText->EndAlignment( ); InfoText->BeginAlignment(wxTEXT_ALIGNMENT_LEFT); InfoText->BeginBold( ); InfoText->WriteText(wxT("., ., .")); InfoText->EndBold( ); InfoText->WriteText(wxT(" 2017. Single-protein detection in crowded molecular environments in cryo-EM images. Elife 6, e25648.. ")); InfoText->BeginURL("http://doi.org/10.7554/eLife.25648"); InfoText->BeginUnderline( ); InfoText->BeginTextColour(*wxBLUE); InfoText->WriteText(wxT("doi:10.7554/eLife.25648")); InfoText->EndURL( ); InfoText->EndTextColour( ); InfoText->EndUnderline( ); InfoText->Newline( ); InfoText->Newline( ); InfoText->EndSuppressUndo( ); } void MatchTemplatePanel::FillGroupComboBox( ) { GroupComboBox->FillComboBox(true); if ( GroupComboBox->GetCount( ) > 0 && main_frame->current_project.is_open == true ) all_images_have_defocus_values = CheckGroupHasDefocusValues( ); if ( all_images_have_defocus_values == true && PleaseEstimateCTFStaticText->IsShown( ) == true ) { PleaseEstimateCTFStaticText->Show(false); Layout( ); } else if ( all_images_have_defocus_values == false && PleaseEstimateCTFStaticText->IsShown( ) == false ) { PleaseEstimateCTFStaticText->Show(true); Layout( ); } } void MatchTemplatePanel::FillRunProfileComboBox( ) { RunProfileComboBox->FillWithRunProfiles( ); } bool MatchTemplatePanel::CheckGroupHasDefocusValues( ) { wxArrayLong images_with_defocus_values = main_frame->current_project.database.ReturnLongArrayFromSelectCommand("SELECT DISTINCT IMAGE_ASSET_ID FROM ESTIMATED_CTF_PARAMETERS"); long current_image_id; int images_with_defocus_counter; bool image_was_found; for ( int image_in_group_counter = 0; image_in_group_counter < image_asset_panel->ReturnGroupSize(GroupComboBox->GetSelection( )); image_in_group_counter++ ) { current_image_id = image_asset_panel->all_assets_list->ReturnAssetPointer(image_asset_panel->ReturnGroupMember(GroupComboBox->GetSelection( ), image_in_group_counter))->asset_id; image_was_found = false; for ( images_with_defocus_counter = 0; images_with_defocus_counter < images_with_defocus_values.GetCount( ); images_with_defocus_counter++ ) { if ( images_with_defocus_values[images_with_defocus_counter] == current_image_id ) { image_was_found = true; break; } } if ( image_was_found == false ) return false; } return true; } void MatchTemplatePanel::OnUpdateUI(wxUpdateUIEvent& event) { // We want things to be greyed out if the user is re-running the job. if ( set_up_to_resume_job ) { return; } // are there enough members in the selected group. if ( main_frame->current_project.is_open == false ) { RunProfileComboBox->Enable(false); GroupComboBox->Enable(false); StartEstimationButton->Enable(false); ReferenceSelectPanel->Enable(false); ResumeRunCheckBox->Enable(false); } else { if ( main_frame->current_project.database.ReturnNumberOfTemplateMatchingJobs( ) == 0 ) { ResumeRunCheckBox->Enable(false); } else { ResumeRunCheckBox->Enable(true); } if ( running_job == false ) { RunProfileComboBox->Enable(true); GroupComboBox->Enable(true); ReferenceSelectPanel->Enable(true); #ifdef ENABLEGPU UseGpuCheckBox->Enable(true); #endif if ( RunProfileComboBox->GetCount( ) > 0 ) { if ( image_asset_panel->ReturnGroupSize(GroupComboBox->GetSelection( )) > 0 && run_profiles_panel->run_profile_manager.ReturnTotalJobs(RunProfileComboBox->GetSelection( )) > 0 && all_images_have_defocus_values == true ) { StartEstimationButton->Enable(true); } else StartEstimationButton->Enable(false); } else { StartEstimationButton->Enable(false); } if ( DefocusSearchYesRadio->GetValue( ) == true ) { DefocusRangeStaticText->Enable(true); DefocusSearchRangeNumericCtrl->Enable(true); DefocusStepStaticText->Enable(true); DefocusSearchStepNumericCtrl->Enable(true); } else { DefocusRangeStaticText->Enable(false); DefocusSearchRangeNumericCtrl->Enable(false); DefocusStepStaticText->Enable(false); DefocusSearchStepNumericCtrl->Enable(false); } if ( PixelSizeSearchYesRadio->GetValue( ) == true ) { PixelSizeRangeStaticText->Enable(true); PixelSizeSearchRangeNumericCtrl->Enable(true); PixelSizeStepStaticText->Enable(true); PixelSizeSearchStepNumericCtrl->Enable(true); } else { PixelSizeRangeStaticText->Enable(false); PixelSizeSearchRangeNumericCtrl->Enable(false); PixelSizeStepStaticText->Enable(false); PixelSizeSearchStepNumericCtrl->Enable(false); } } else { GroupComboBox->Enable(false); ReferenceSelectPanel->Enable(false); RunProfileComboBox->Enable(false); UseGpuCheckBox->Enable(false); // Doesn't matter if ENABLEGPU //StartAlignmentButton->SetLabel("Stop Job"); //StartAlignmentButton->Enable(true); } if ( group_combo_is_dirty == true ) { FillGroupComboBox( ); group_combo_is_dirty = false; } if ( run_profiles_are_dirty == true ) { FillRunProfileComboBox( ); run_profiles_are_dirty = false; } if ( volumes_are_dirty == true ) { ReferenceSelectPanel->FillComboBox( ); volumes_are_dirty = false; } } } /** * Disables argument controls if set_up_to_resume_job is true. * In that case a TemplateMatchResult must be supplied to set * the arguments identical to the to be resumed job. */ void MatchTemplatePanel::SetInputsForPossibleReRun(bool set_up_to_resume_job, TemplateMatchJobResults* job_to_resume) { this->set_up_to_resume_job = set_up_to_resume_job; bool enable_value; if ( set_up_to_resume_job ) { // We want to disable user inputs so the job run matches the intial state. enable_value = false; ResumeRunCheckBox->Show(true); ResumeRunCheckBox->SetValue(true); ResumeRunCheckBox->Enable(true); ResetAllDefaultsButton->Enable(false); // We want to set the controls to the values of the job to be resumed. // SetSelection requires the array position in the volume asset panel, // which needs to be calculated from the volume asset id. ReferenceSelectPanel->SetSelection(volume_asset_panel->ReturnArrayPositionFromAssetID(job_to_resume->ref_volume_asset_id)); OutofPlaneStepNumericCtrl->SetValue(wxString::Format(wxT("%f"), job_to_resume->out_of_plane_step)); InPlaneStepNumericCtrl->SetValue(wxString::Format(wxT("%f"), job_to_resume->in_plane_step)); MinPeakRadiusNumericCtrl->SetValue(wxString::Format(wxT("%f"), job_to_resume->min_peak_radius)); HighResolutionLimitNumericCtrl->SetValue(wxString::Format(wxT("%f"), job_to_resume->high_res_limit)); SymmetryComboBox->SetValue(job_to_resume->symmetry); // If either range or step are 0 no search will be perfomed. DefocusSearchYesRadio->SetValue(job_to_resume->defocus_search_range != 0.0f && job_to_resume->defocus_step != 0.0f); DefocusSearchNoRadio->SetValue(job_to_resume->defocus_search_range == 0.0f || job_to_resume->defocus_step == 0.0f); PixelSizeSearchYesRadio->SetValue(job_to_resume->pixel_size_search_range != 0.0f && job_to_resume->pixel_size_step != 0.0f); PixelSizeSearchNoRadio->SetValue(job_to_resume->pixel_size_search_range == 0.0f || job_to_resume->pixel_size_step == 0.0f); DefocusSearchRangeNumericCtrl->SetValue(wxString::Format(wxT("%f"), job_to_resume->defocus_search_range)); DefocusSearchStepNumericCtrl->SetValue(wxString::Format(wxT("%f"), job_to_resume->defocus_step)); PixelSizeSearchRangeNumericCtrl->SetValue(wxString::Format(wxT("%f"), job_to_resume->pixel_size_search_range)); PixelSizeSearchStepNumericCtrl->SetValue(wxString::Format(wxT("%f"), job_to_resume->pixel_size_step)); } else { // We want to allow the user to not re-run the job if the disable the ReRun radio button. // The state remembered in "was_enabled..." is meaningless here. enable_value = true; ResetAllDefaultsButton->Enable(true); } //SetAndRememberEnableState(GroupComboBox, was_enabled_GroupComboBox, enable_value); SetAndRememberEnableState(ReferenceSelectPanel, was_enabled_ReferenceSelectPanel, enable_value); SetAndRememberEnableState(OutofPlaneStepNumericCtrl, was_enabled_OutofPlaneStepNumericCtrl, enable_value); SetAndRememberEnableState(InPlaneStepNumericCtrl, was_enabled_InPlaneStepNumericCtrl, enable_value); SetAndRememberEnableState(MinPeakRadiusNumericCtrl, was_enabled_MinPeakRadiusNumericCtrl, enable_value); SetAndRememberEnableState(DefocusSearchYesRadio, was_enabled_DefocusSearchYesRadio, enable_value); SetAndRememberEnableState(DefocusSearchNoRadio, was_enabled_DefocusSearchNoRadio, enable_value); SetAndRememberEnableState(PixelSizeSearchYesRadio, was_enabled_PixelSizeSearchYesRadio, enable_value); SetAndRememberEnableState(PixelSizeSearchNoRadio, was_enabled_PixelSizeSearchNoRadio, enable_value); SetAndRememberEnableState(SymmetryComboBox, was_enabled_SymmetryComboBox, enable_value); SetAndRememberEnableState(HighResolutionLimitNumericCtrl, was_enabled_HighResolutionLimitNumericCtrl, enable_value); SetAndRememberEnableState(DefocusSearchRangeNumericCtrl, was_enabled_DefocusSearchRangeNumericCtrl, enable_value); SetAndRememberEnableState(DefocusSearchStepNumericCtrl, was_enabled_DefocusSearchStepNumericCtrl, enable_value); // It is okay to change the run profile for a rerun if ( RunProfileComboBox->GetCount( ) > 0 ) { if ( image_asset_panel->ReturnGroupSize(GroupComboBox->GetSelection( )) > 0 && run_profiles_panel->run_profile_manager.ReturnTotalJobs(RunProfileComboBox->GetSelection( )) > 0 && all_images_have_defocus_values == true ) { StartEstimationButton->Enable(true); } else StartEstimationButton->Enable(false); } else { StartEstimationButton->Enable(false); } if ( group_combo_is_dirty == true ) { FillGroupComboBox( ); group_combo_is_dirty = false; } if ( run_profiles_are_dirty == true ) { FillRunProfileComboBox( ); run_profiles_are_dirty = false; } if ( volumes_are_dirty == true ) { ReferenceSelectPanel->FillComboBox( ); volumes_are_dirty = false; } } void MatchTemplatePanel::StartEstimationClick(wxCommandEvent& event) { active_group.CopyFrom(&image_asset_panel->all_groups_list->groups[GroupComboBox->GetSelection( )]); // Check if this is a resume job. If yes, get the job id and set the active // group to the remaining images bool resume = ResumeRunCheckBox->GetValue( ); int job_id_to_resume; wxArrayLong images_to_resume; if ( resume ) { images_to_resume = CheckForUnfinishedWork(true, true); job_id_to_resume = match_template_results_panel->ResultDataView->ReturnActiveJobID( ); active_group.RemoveAll( ); for ( long counter = 0; counter < images_to_resume.GetCount( ); counter++ ) { // The active group contains array positions in the image asset // panel, which need to be calculate from the image asset id. long image_index = image_asset_panel->ReturnArrayPositionFromAssetID(images_to_resume[counter]); active_group.AddMember(image_index); } } float resolution_limit; float orientations_per_process; float current_orientation_counter; int job_counter; int number_of_rotations = 0; int number_of_defocus_positions; int number_of_pixel_size_positions; bool use_gpu; int max_threads = 1; // Only used for the GPU code. For GUI this comes from the run profile -> command line override as in other programs. int image_number_for_gui; int number_of_jobs_per_image_in_gui; int number_of_jobs; double voltage_kV; double spherical_aberration_mm; double amplitude_contrast; double defocus1; double defocus2; double defocus_angle; double phase_shift; double iciness; input_image_filenames.Clear( ); cached_results.Clear( ); ResultsPanel->Clear( ); // Package the job details.. EulerSearch* current_image_euler_search; ImageAsset* current_image; VolumeAsset* current_volume; current_volume = volume_asset_panel->ReturnAssetPointer(ReferenceSelectPanel->GetSelection( )); ref_box_size_in_pixels = current_volume->x_size / current_volume->pixel_size; ParameterMap parameter_map; parameter_map.SetAllTrue( ); float wanted_out_of_plane_angular_step = OutofPlaneStepNumericCtrl->ReturnValue( ); float wanted_in_plane_angular_step = InPlaneStepNumericCtrl->ReturnValue( ); float defocus_search_range; float defocus_step; float pixel_size_search_range; float pixel_size_step; if ( DefocusSearchYesRadio->GetValue( ) == true ) { defocus_search_range = DefocusSearchRangeNumericCtrl->ReturnValue( ); defocus_step = DefocusSearchStepNumericCtrl->ReturnValue( ); } else { defocus_search_range = 0.0f; defocus_step = 0.0f; } if ( PixelSizeSearchYesRadio->GetValue( ) == true ) { pixel_size_search_range = PixelSizeSearchRangeNumericCtrl->ReturnValue( ); pixel_size_step = PixelSizeSearchStepNumericCtrl->ReturnValue( ); } else { pixel_size_search_range = 0.0f; pixel_size_step = 0.0f; } float min_peak_radius = MinPeakRadiusNumericCtrl->ReturnValue( ); if ( UseGpuCheckBox->GetValue( ) == true ) { use_gpu = true; } else { use_gpu = false; } wxString wanted_symmetry = SymmetryComboBox->GetValue( ); wanted_symmetry = SymmetryComboBox->GetValue( ).Upper( ); float high_resolution_limit = HighResolutionLimitNumericCtrl->ReturnValue( ); wxPrintf("\n\nWanted symmetry %s, Defocus Range %3.3f, Defocus Step %3.3f\n", wanted_symmetry, defocus_search_range, defocus_step); RunProfile active_refinement_run_profile = run_profiles_panel->run_profile_manager.run_profiles[RunProfileComboBox->GetSelection( )]; int number_of_processes = active_refinement_run_profile.ReturnTotalJobs( ); // how many jobs are there going to be.. // get first image to make decisions about how many jobs.. .we assume this is representative. current_image = image_asset_panel->ReturnAssetPointer(active_group.members[0]); current_image_euler_search = new EulerSearch; // WARNING: resolution_limit below is used before its value is set current_image_euler_search->InitGrid(wanted_symmetry, wanted_out_of_plane_angular_step, 0.0, 0.0, 360.0, wanted_in_plane_angular_step, 0.0, current_image->pixel_size / resolution_limit, parameter_map, 1); if ( wanted_symmetry.StartsWith("C") ) { if ( current_image_euler_search->test_mirror == true ) // otherwise the theta max is set to 90.0 and test_mirror is set to true. However, I don't want to have to test the mirrors. { current_image_euler_search->theta_max = 180.0f; } } current_image_euler_search->CalculateGridSearchPositions(false); if ( use_gpu ) { // number_of_jobs_per_image_in_gui = std::max((int)1,number_of_processes / 2); // Using two threads in each job number_of_jobs_per_image_in_gui = number_of_processes; // Using two threads in each job number_of_jobs = number_of_jobs_per_image_in_gui * active_group.number_of_members; wxPrintf("In USEGPU:\n There are %d search positions\nThere are %d jobs per image\n", current_image_euler_search->number_of_search_positions, number_of_jobs_per_image_in_gui); delete current_image_euler_search; } else { if ( active_group.number_of_members >= 5 || current_image_euler_search->number_of_search_positions < number_of_processes * 20 ) number_of_jobs_per_image_in_gui = number_of_processes; else if ( current_image_euler_search->number_of_search_positions > number_of_processes * 250 ) number_of_jobs_per_image_in_gui = number_of_processes * 10; else number_of_jobs_per_image_in_gui = number_of_processes * 5; number_of_jobs = number_of_jobs_per_image_in_gui * active_group.number_of_members; delete current_image_euler_search; } // Some settings for testing // float defocus_search_range = 1200.0f; // float defocus_step = 200.0f; // number of rotations for ( float current_psi = 0.0f; current_psi <= 360.0f; current_psi += wanted_in_plane_angular_step ) { number_of_rotations++; } current_job_package.Reset(active_refinement_run_profile, "match_template", number_of_jobs); expected_number_of_results = 0; number_of_received_results = 0; // loop over all images.. OneSecondProgressDialog* my_progress_dialog = new OneSecondProgressDialog("Preparing Job", "Preparing Job...", active_group.number_of_members, this, wxPD_REMAINING_TIME | wxPD_AUTO_HIDE | wxPD_APP_MODAL); TemplateMatchJobResults temp_result; temp_result.input_job_id = -1; temp_result.job_type = cistem::job_type::template_match_full_search; temp_result.mask_radius = 0.0f; temp_result.min_peak_radius = min_peak_radius; temp_result.exclude_above_xy_threshold = false; temp_result.xy_change_threshold = 0.0f; for ( int image_counter = 0; image_counter < active_group.number_of_members; image_counter++ ) { image_number_for_gui = image_counter + 1; // current image asset current_image = image_asset_panel->ReturnAssetPointer(active_group.members[image_counter]); // setup the euler search for this image.. // this needs to be changed when more parameters are added. // right now, the resolution is always Nyquist. resolution_limit = current_image->pixel_size * 2.0f; current_image_euler_search = new EulerSearch; current_image_euler_search->InitGrid(wanted_symmetry, wanted_out_of_plane_angular_step, 0.0, 0.0, 360.0, wanted_in_plane_angular_step, 0.0, current_image->pixel_size / resolution_limit, parameter_map, 1); if ( wanted_symmetry.StartsWith("C") ) { if ( current_image_euler_search->test_mirror == true ) // otherwise the theta max is set to 90.0 and test_mirror is set to true. However, I don't want to have to test the mirrors. { current_image_euler_search->theta_max = 180.0f; } } current_image_euler_search->CalculateGridSearchPositions(false); if ( DefocusSearchYesRadio->GetValue( ) == true ) number_of_defocus_positions = 2 * myround(float(defocus_search_range) / float(defocus_step)) + 1; else number_of_defocus_positions = 1; if ( PixelSizeSearchYesRadio->GetValue( ) == true ) number_of_pixel_size_positions = 2 * myround(float(pixel_size_search_range) / float(pixel_size_step)) + 1; else number_of_pixel_size_positions = 1; wxPrintf("For Image %li\nThere are %i search positions\nThere are %i jobs per image\n", active_group.members[image_counter], current_image_euler_search->number_of_search_positions, number_of_jobs_per_image_in_gui); wxPrintf("Calculating %i correlation maps\n", current_image_euler_search->number_of_search_positions * number_of_rotations * number_of_defocus_positions * number_of_pixel_size_positions); // how many orientations will each process do for this image.. expected_number_of_results += current_image_euler_search->number_of_search_positions * number_of_rotations * number_of_defocus_positions * number_of_pixel_size_positions; orientations_per_process = float(current_image_euler_search->number_of_search_positions) / float(number_of_jobs_per_image_in_gui); if ( orientations_per_process < 1 ) orientations_per_process = 1; int number_of_previous_template_matches = main_frame->current_project.database.ReturnNumberOfPreviousTemplateMatchesByAssetID(current_image->asset_id); main_frame->current_project.database.GetCTFParameters(current_image->ctf_estimation_id, voltage_kV, spherical_aberration_mm, amplitude_contrast, defocus1, defocus2, defocus_angle, phase_shift, iciness); wxString mip_output_file = main_frame->current_project.template_matching_asset_directory.GetFullPath( ); mip_output_file += wxString::Format("/%s_mip_%i_%i.mrc", current_image->filename.GetName( ), current_image->asset_id, number_of_previous_template_matches); wxString best_psi_output_file = main_frame->current_project.template_matching_asset_directory.GetFullPath( ); best_psi_output_file += wxString::Format("/%s_psi_%i_%i.mrc", current_image->filename.GetName( ), current_image->asset_id, number_of_previous_template_matches); wxString best_theta_output_file = main_frame->current_project.template_matching_asset_directory.GetFullPath( ); best_theta_output_file += wxString::Format("/%s_theta_%i_%i.mrc", current_image->filename.GetName( ), current_image->asset_id, number_of_previous_template_matches); wxString best_phi_output_file = main_frame->current_project.template_matching_asset_directory.GetFullPath( ); best_phi_output_file += wxString::Format("/%s_phi_%i_%i.mrc", current_image->filename.GetName( ), current_image->asset_id, number_of_previous_template_matches); wxString best_defocus_output_file = main_frame->current_project.template_matching_asset_directory.GetFullPath( ); best_defocus_output_file += wxString::Format("/%s_defocus_%i_%i.mrc", current_image->filename.GetName( ), current_image->asset_id, number_of_previous_template_matches); wxString best_pixel_size_output_file = main_frame->current_project.template_matching_asset_directory.GetFullPath( ); best_pixel_size_output_file += wxString::Format("/%s_pixel_size_%i_%i.mrc", current_image->filename.GetName( ), current_image->asset_id, number_of_previous_template_matches); wxString scaled_mip_output_file = main_frame->current_project.template_matching_asset_directory.GetFullPath( ); scaled_mip_output_file += wxString::Format("/%s_scaled_mip_%i_%i.mrc", current_image->filename.GetName( ), current_image->asset_id, number_of_previous_template_matches); wxString output_histogram_file = main_frame->current_project.template_matching_asset_directory.GetFullPath( ); output_histogram_file += wxString::Format("/%s_histogram_%i_%i.txt", current_image->filename.GetName( ), current_image->asset_id, number_of_previous_template_matches); wxString output_result_file = main_frame->current_project.template_matching_asset_directory.GetFullPath( ); output_result_file += wxString::Format("/%s_plotted_result_%i_%i.mrc", current_image->filename.GetName( ), current_image->asset_id, number_of_previous_template_matches); wxString correlation_avg_output_file = main_frame->current_project.template_matching_asset_directory.GetFullPath( ); correlation_avg_output_file += wxString::Format("/%s_avg_%i_%i.mrc", current_image->filename.GetName( ), current_image->asset_id, number_of_previous_template_matches); wxString correlation_std_output_file = main_frame->current_project.template_matching_asset_directory.GetFullPath( ); correlation_std_output_file += wxString::Format("/%s_std_%i_%i.mrc", current_image->filename.GetName( ), current_image->asset_id, number_of_previous_template_matches); // wxString correlation_std_output_file = "/dev/null"; current_orientation_counter = 0; wxString input_search_image = current_image->filename.GetFullPath( ); wxString input_reconstruction = current_volume->filename.GetFullPath( ); float pixel_size = current_image->pixel_size; input_image_filenames.Add(input_search_image); float low_resolution_limit = 300.0f; // FIXME set this somehwere that is not buried in the code! temp_result.image_asset_id = current_image->asset_id; temp_result.job_name = wxString::Format("Full search with %s", current_volume->filename.GetName( )); temp_result.ref_volume_asset_id = current_volume->asset_id; wxDateTime now = wxDateTime::Now( ); temp_result.datetime_of_run = (long int)now.GetAsDOS( ); temp_result.symmetry = wanted_symmetry; temp_result.pixel_size = pixel_size; temp_result.voltage = voltage_kV; temp_result.spherical_aberration = spherical_aberration_mm; temp_result.amplitude_contrast = amplitude_contrast; temp_result.defocus1 = defocus1; temp_result.defocus2 = defocus2; temp_result.defocus_angle = defocus_angle; temp_result.phase_shift = phase_shift; temp_result.low_res_limit = low_resolution_limit; temp_result.high_res_limit = high_resolution_limit; temp_result.out_of_plane_step = wanted_out_of_plane_angular_step; temp_result.in_plane_step = wanted_in_plane_angular_step; temp_result.defocus_search_range = defocus_search_range; temp_result.defocus_step = defocus_step; temp_result.pixel_size_search_range = pixel_size_search_range; temp_result.pixel_size_step = pixel_size_step; temp_result.reference_box_size_in_angstroms = ref_box_size_in_pixels * pixel_size; temp_result.mip_filename = mip_output_file; temp_result.scaled_mip_filename = scaled_mip_output_file; temp_result.psi_filename = best_psi_output_file; temp_result.theta_filename = best_theta_output_file; temp_result.phi_filename = best_phi_output_file; temp_result.defocus_filename = best_defocus_output_file; temp_result.pixel_size_filename = best_pixel_size_output_file; temp_result.histogram_filename = output_histogram_file; temp_result.projection_result_filename = output_result_file; temp_result.avg_filename = correlation_avg_output_file; temp_result.std_filename = correlation_std_output_file; cached_results.Add(temp_result); for ( job_counter = 0; job_counter < number_of_jobs_per_image_in_gui; job_counter++ ) { // float high_resolution_limit = resolution_limit; int best_parameters_to_keep = 1; // float defocus_search_range = 0.0f; // float defocus_step = 0.0f; float padding = 1; bool ctf_refinement = false; float mask_radius_search = 0.0f; //current_volume->x_size; // this is actually not really used... wxPrintf("\n\tFor image %i, current_orientation_counter is %f\n", image_number_for_gui, current_orientation_counter); if ( current_orientation_counter >= current_image_euler_search->number_of_search_positions ) current_orientation_counter = current_image_euler_search->number_of_search_positions - 1; int first_search_position = myroundint(current_orientation_counter); current_orientation_counter += orientations_per_process; if ( current_orientation_counter >= current_image_euler_search->number_of_search_positions || job_counter == number_of_jobs_per_image_in_gui - 1 ) current_orientation_counter = current_image_euler_search->number_of_search_positions - 1; int last_search_position = myroundint(current_orientation_counter); current_orientation_counter++; wxString directory_for_results = main_frame->current_project.image_asset_directory.GetFullPath( ); // wxString directory_for_results = main_frame->ReturnScratchDirectory(); //wxPrintf("%i = %i - %i\n", job_counter, first_search_position, last_search_position); current_job_package.AddJob("ttffffffffffifffffbfftttttttttftiiiitttfbi", input_search_image.ToUTF8( ).data( ), input_reconstruction.ToUTF8( ).data( ), pixel_size, voltage_kV, spherical_aberration_mm, amplitude_contrast, defocus1, defocus2, defocus_angle, low_resolution_limit, high_resolution_limit, wanted_out_of_plane_angular_step, best_parameters_to_keep, defocus_search_range, defocus_step, pixel_size_search_range, pixel_size_step, padding, ctf_refinement, mask_radius_search, phase_shift, mip_output_file.ToUTF8( ).data( ), best_psi_output_file.ToUTF8( ).data( ), best_theta_output_file.ToUTF8( ).data( ), best_phi_output_file.ToUTF8( ).data( ), best_defocus_output_file.ToUTF8( ).data( ), best_pixel_size_output_file.ToUTF8( ).data( ), scaled_mip_output_file.ToUTF8( ).data( ), correlation_avg_output_file.ToUTF8( ).data( ), wanted_symmetry.ToUTF8( ).data( ), wanted_in_plane_angular_step, output_histogram_file.ToUTF8( ).data( ), first_search_position, last_search_position, image_number_for_gui, number_of_jobs_per_image_in_gui, correlation_std_output_file.ToUTF8( ).data( ), directory_for_results.ToUTF8( ).data( ), output_result_file.ToUTF8( ).data( ), min_peak_radius, use_gpu, max_threads); } delete current_image_euler_search; my_progress_dialog->Update(image_counter + 1); } my_progress_dialog->Destroy( ); // Get ID's from database for writing results as they come in.. template_match_id = main_frame->current_project.database.ReturnHighestTemplateMatchID( ) + 1; // If we resume, reuse the job id of the job we want to resume if ( resume ) { template_match_job_id = job_id_to_resume; } else { template_match_job_id = main_frame->current_project.database.ReturnHighestTemplateMatchJobID( ) + 1; } // launch a controller my_job_id = main_frame->job_controller.AddJob(this, run_profiles_panel->run_profile_manager.run_profiles[RunProfileComboBox->GetSelection( )].manager_command, run_profiles_panel->run_profile_manager.run_profiles[RunProfileComboBox->GetSelection( )].gui_address); if ( my_job_id != -1 ) { SetNumberConnectedTextToZeroAndStartTracking( ); StartPanel->Show(false); ProgressPanel->Show(true); InputPanel->Show(false); ExpertPanel->Show(false); InfoPanel->Show(false); OutputTextPanel->Show(true); ResultsPanel->Show(true); GroupComboBox->Enable(false); Layout( ); } ProgressBar->Pulse( ); } void MatchTemplatePanel::HandleSocketTemplateMatchResultReady(wxSocketBase* connected_socket, int& image_number, float& threshold_used, ArrayOfTemplateMatchFoundPeakInfos& peak_infos, ArrayOfTemplateMatchFoundPeakInfos& peak_changes) { // result is available for an image.. cached_results[image_number - 1].found_peaks.Clear( ); cached_results[image_number - 1].found_peaks = peak_infos; cached_results[image_number - 1].used_threshold = threshold_used; ResultsPanel->SetActiveResult(cached_results[image_number - 1]); // write to database.. main_frame->current_project.database.Begin( ); cached_results[image_number - 1].job_id = template_match_job_id; main_frame->current_project.database.AddTemplateMatchingResult(template_match_id, cached_results[image_number - 1]); template_match_id++; main_frame->current_project.database.SetActiveTemplateMatchJobForGivenImageAssetID(cached_results[image_number - 1].image_asset_id, template_match_job_id); main_frame->current_project.database.Commit( ); match_template_results_panel->is_dirty = true; } void MatchTemplatePanel::FinishButtonClick(wxCommandEvent& event) { ProgressBar->SetValue(0); TimeRemainingText->SetLabel("Time Remaining : ???h:??m:??s"); CancelAlignmentButton->Show(true); FinishButton->Show(false); ProgressPanel->Show(false); StartPanel->Show(true); OutputTextPanel->Show(false); output_textctrl->Clear( ); ResultsPanel->Show(false); //graph_is_hidden = true; InfoPanel->Show(true); InputPanel->Show(true); ExpertPanel->Show(true); running_job = false; Layout( ); } void MatchTemplatePanel::TerminateButtonClick(wxCommandEvent& event) { // kill the job, this will kill the socket to terminate downstream processes // - this will have to be improved when clever network failure is incorporated main_frame->job_controller.KillJob(my_job_id); WriteInfoText("Terminated Job"); TimeRemainingText->SetLabel("Time Remaining : Terminated"); CancelAlignmentButton->Show(false); FinishButton->Show(true); ProgressPanel->Layout( ); cached_results.Clear( ); //running_job = false; } void MatchTemplatePanel::WriteInfoText(wxString text_to_write) { output_textctrl->SetDefaultStyle(wxTextAttr(*wxBLACK)); output_textctrl->AppendText(text_to_write); if ( text_to_write.EndsWith("\n") == false ) output_textctrl->AppendText("\n"); } void MatchTemplatePanel::WriteErrorText(wxString text_to_write) { output_textctrl->SetDefaultStyle(wxTextAttr(*wxRED)); output_textctrl->AppendText(text_to_write); if ( text_to_write.EndsWith("\n") == false ) output_textctrl->AppendText("\n"); } void MatchTemplatePanel::OnSocketJobResultMsg(JobResult& received_result) { if ( received_result.result_size > 0 ) { ProcessResult(&received_result); } } void MatchTemplatePanel::OnSocketJobResultQueueMsg(ArrayofJobResults& received_queue) { for ( int counter = 0; counter < received_queue.GetCount( ); counter++ ) { ProcessResult(&received_queue.Item(counter)); } } void MatchTemplatePanel::SetNumberConnectedText(wxString wanted_text) { NumberConnectedText->SetLabel(wanted_text); } void MatchTemplatePanel::SetTimeRemainingText(wxString wanted_text) { TimeRemainingText->SetLabel(wanted_text); } void MatchTemplatePanel::OnSocketAllJobsFinished( ) { ProcessAllJobsFinished( ); } void MatchTemplatePanel::ProcessResult(JobResult* result_to_process) // this will have to be overidden in the parent clas when i make it. { long current_time = time(NULL); wxString bitmap_string; wxString plot_string; number_of_received_results++; if ( number_of_received_results == 1 ) { current_job_starttime = current_time; time_of_last_update = 0; } else if ( current_time != time_of_last_update ) { int current_percentage; current_percentage = myroundint(float(number_of_received_results) / float(expected_number_of_results) * 100.0f); time_of_last_update = current_time; if ( current_percentage > 100 ) current_percentage = 100; ProgressBar->SetValue(current_percentage); long job_time = current_time - current_job_starttime; float seconds_per_job = float(job_time) / float(number_of_received_results - 1); long seconds_remaining; seconds_remaining = float(expected_number_of_results - number_of_received_results) * seconds_per_job; wxTimeSpan time_remaining = wxTimeSpan(0, 0, seconds_remaining); TimeRemainingText->SetLabel(time_remaining.Format("Time Remaining : %Hh:%Mm:%Ss")); } // results should be .. // Defocus 1 (Angstroms) // Defocus 2 (Angstroms) // Astigmatism Angle (degrees) // Additional phase shift (e.g. from phase plate) radians // Score // Resolution (Angstroms) to which Thon rings are well fit by the CTF // Reolution (Angstroms) at which aliasing was detected /* if (current_time - time_of_last_result_update > 5) { // we need the filename of the image.. wxString image_filename = image_asset_panel->ReturnAssetPointer(active_group.members[result_to_process->job_number])->filename.GetFullPath(); ResultsPanel->Draw(my_job_package.jobs[result_to_process->job_number].arguments[3].ReturnStringArgument(), my_job_package.jobs[result_to_process->job_number].arguments[16].ReturnBoolArgument(), result_to_process->result_data[0], result_to_process->result_data[1], result_to_process->result_data[2], result_to_process->result_data[3], result_to_process->result_data[4], result_to_process->result_data[5], result_to_process->result_data[6], image_filename); time_of_last_result_update = time(NULL); } */ // my_job_tracker.MarkJobFinished(); // if (my_job_tracker.ShouldUpdate() == true) UpdateProgressBar(); // store the results.. //buffered_results[result_to_process->job_number] = result_to_process; } void MatchTemplatePanel::ProcessAllJobsFinished( ) { MyDebugAssertTrue(my_job_tracker.total_number_of_finished_jobs == my_job_tracker.total_number_of_jobs, "In ProcessAllJobsFinished, but total_number_of_finished_jobs != total_number_of_jobs. Oops."); // Update the GUI with project timings extern MyOverviewPanel* overview_panel; overview_panel->SetProjectInfo( ); // WriteResultToDataBase( ); match_template_results_panel->is_dirty = true; // let the FindParticles panel check whether any of the groups are now ready to be picked //extern MyFindParticlesPanel *findparticles_panel; //findparticles_panel->CheckWhetherGroupsCanBePicked(); cached_results.Clear( ); // Kill the job (in case it isn't already dead) main_frame->job_controller.KillJob(my_job_id); WriteInfoText("All Jobs have finished."); ProgressBar->SetValue(100); TimeRemainingText->SetLabel("Time Remaining : All Done!"); CancelAlignmentButton->Show(false); FinishButton->Show(true); ProgressPanel->Layout( ); } void MatchTemplatePanel::WriteResultToDataBase( ) { // I have moved this to HandleSocketTemplateMatchResultReady so that things are done one result at at time. /* // find the current highest template match numbers in the database, then increment by one int template_match_id = main_frame->current_project.database.ReturnHighestTemplateMatchID() + 1; int template_match_job_id = main_frame->current_project.database.ReturnHighestTemplateMatchJobID() + 1; main_frame->current_project.database.Begin(); for (int counter = 0; counter < cached_results.GetCount(); counter++) { cached_results[counter].job_id = template_match_job_id; main_frame->current_project.database.AddTemplateMatchingResult(template_match_id, cached_results[counter]); template_match_id++; } for (int counter = 0; counter < cached_results.GetCount(); counter++) { main_frame->current_project.database.SetActiveTemplateMatchJobForGivenImageAssetID(cached_results[counter].image_asset_id, template_match_job_id); } main_frame->current_project.database.Commit(); match_template_results_panel->is_dirty = true; */ } void MatchTemplatePanel::UpdateProgressBar( ) { ProgressBar->SetValue(my_job_tracker.ReturnPercentCompleted( )); TimeRemainingText->SetLabel(my_job_tracker.ReturnRemainingTime( ).Format("Time Remaining : %Hh:%Mm:%Ss")); } void MatchTemplatePanel::ResumeRunCheckBoxOnCheckBox(wxCommandEvent& event) { if ( event.IsChecked( ) ) { CheckForUnfinishedWork(true, true); } else { CheckForUnfinishedWork(false, true); } } /** * This may be called when the user clicks the resume run checkbox. * OR * When the header in the results panel is changed. */ wxArrayLong MatchTemplatePanel::CheckForUnfinishedWork(bool is_checked, bool is_from_check_box) { wxArrayLong unfinished_match_template_ids; if ( is_checked ) { // active group might have been overriden when resuming a run active_group.CopyFrom(&image_asset_panel->all_groups_list->groups[GroupComboBox->GetSelection( )]); int active_job_id = match_template_results_panel->ResultDataView->ReturnActiveJobID( ); int images_total = active_group.number_of_members; int images_to_be_processed = 0; int images_successfully_processed = 0; // Get a list of unfinished images by performing a left join between all // image assets or the image assets in the desired group and the results // stored for this job. The image assets that don't match are what we // want. // All images if ( active_group.id == -1 ) { unfinished_match_template_ids = main_frame->current_project.database.ReturnLongArrayFromSelectCommand( wxString::Format("select IMAGE_ASSETS.IMAGE_ASSET_ID, COMP.IMAGE_ASSET_ID as CID FROM IMAGE_ASSETS " "LEFT JOIN (SELECT IMAGE_ASSET_ID FROM TEMPLATE_MATCH_LIST WHERE TEMPLATE_MATCH_JOB_ID = %i ) COMP " "ON IMAGE_ASSETS.IMAGE_ASSET_ID = COMP.IMAGE_ASSET_ID " "WHERE CID IS NULL", active_job_id)); } // An Image group else { unfinished_match_template_ids = main_frame->current_project.database.ReturnLongArrayFromSelectCommand( wxString::Format("select IMAGE_ASSETS.IMAGE_ASSET_ID, COMP.IMAGE_ASSET_ID as CID FROM IMAGE_GROUP_%i AS IMAGE_ASSETS " "LEFT JOIN (SELECT IMAGE_ASSET_ID FROM TEMPLATE_MATCH_LIST WHERE TEMPLATE_MATCH_JOB_ID = %i ) COMP " "ON IMAGE_ASSETS.IMAGE_ASSET_ID = COMP.IMAGE_ASSET_ID " "WHERE CID IS NULL", active_group.id, active_job_id)); } images_to_be_processed = unfinished_match_template_ids.GetCount( ); images_successfully_processed = images_total - images_to_be_processed; no_unfinished_jobs = (images_to_be_processed == 0); if ( no_unfinished_jobs ) { wxPrintf("No unfinished jobs.\n"); // Only create the dialog if triggered by the checkbox, not by the header change. if ( is_from_check_box ) { wxMessageDialog* check_dialog = new wxMessageDialog(this, wxString::Format("There is no unfinished work for job %d.\n\nYou may select another job by clicking the header in the TM results panel.", active_job_id, "Please Confirm", wxOK)); check_dialog->ShowModal( ); } ResumeRunCheckBox->SetValue(false); SetInputsForPossibleReRun(false); } else { wxPrintf("Checking for unfinished work for job %d\n", active_job_id); // Only create the dialog if triggered by the checkbox, not by the header change. if ( is_from_check_box ) { wxMessageDialog* check_dialog = new wxMessageDialog(this, wxString::Format("Resuming work for job %d, which has %d/%d images completed.\n", active_job_id, images_successfully_processed, images_total, "Please Confirm", wxOK)); check_dialog->ShowModal( ); } int job_id_to_resume = match_template_results_panel->ResultDataView->ReturnActiveJobID( ); // This returns just one of the finished jobs, so we can get the arguments from it. long template_match_id = main_frame->current_project.database.GetTemplateMatchIdForGivenJobId(job_id_to_resume); TemplateMatchJobResults job_results_to_resume = main_frame->current_project.database.GetTemplateMatchingResultByID(template_match_id); SetInputsForPossibleReRun(true, &job_results_to_resume); } } else { wxPrintf("ELSE\n"); SetInputsForPossibleReRun(false); } return unfinished_match_template_ids; } /* Copyright (c) 2007 . 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. */ // Source for CPrefsLetterGeneral class #include "CPrefsLetterGeneral.h" #include "CMailboxPopup.h" #include "CMulberryApp.h" #include "CPreferences.h" #include "CPrefsEditCaption.h" #include "CPrefsEditHeadFoot.h" #include "CTextField.h" #include #include #include #include "JXSecondaryRadioGroup.h" #include #include #include #include #include "CInputField.h" #include // C O N S T R U C T I O N / D E S T R U C T I O N M E T H O D S // O T H E R M E T H O D S ____________________________________________________________________________ // Get details of sub-panes void CPrefsLetterGeneral::OnCreate() { // begin JXLayout1 JXStaticText* obj1 = new JXStaticText("Default Domain for\nOutgoing Email:", this, JXWidget::kHElastic, JXWidget::kVElastic, 10,0, 115,35); assert( obj1 != NULL ); mMailDomain = new CTextInputField(this, JXWidget::kHElastic, JXWidget::kVElastic, 125,5, 210,20); assert( mMailDomain != NULL ); JXStaticText* obj2 = new JXStaticText("Tab Width:", this, JXWidget::kHElastic, JXWidget::kVElastic, 10,35, 70,20); assert( obj2 != NULL ); mSpacesPerTab = new CInputField(this, JXWidget::kHElastic, JXWidget::kVElastic, 125,33, 40,20); assert( mSpacesPerTab != NULL ); mTabSpace = new JXTextCheckbox("Use Spaces for Tabs", this, JXWidget::kHElastic, JXWidget::kVElastic, 175,35, 155,20); assert( mTabSpace != NULL ); JXStaticText* obj3 = new JXStaticText("Wrap Length:", this, JXWidget::kHElastic, JXWidget::kVElastic, 10,58, 85,20); assert( obj3 != NULL ); mWrapLength = new CInputField(this, JXWidget::kHElastic, JXWidget::kVElastic, 125,56, 40,20); assert( mWrapLength != NULL ); JXStaticText* obj4 = new JXStaticText("Reply Prefix:", this, JXWidget::kHElastic, JXWidget::kVElastic, 10,81, 95,20); assert( obj4 != NULL ); mReplyQuote = new CTextInputField(this, JXWidget::kHElastic, JXWidget::kVElastic, 125,79, 60,20); assert( mReplyQuote != NULL ); JXStaticText* obj5 = new JXStaticText("Caption:", this, JXWidget::kHElastic, JXWidget::kVElastic, 195,81, 55,20); assert( obj5 != NULL ); mReplySetBtn = new JXTextButton("Set...", this, JXWidget::kHElastic, JXWidget::kVElastic, 250,78, 50,20); assert( mReplySetBtn != NULL ); JXStaticText* obj6 = new JXStaticText("Forward Prefix:", this, JXWidget::kHElastic, JXWidget::kVElastic, 10,106, 95,20); assert( obj6 != NULL ); mForwardQuote = new CTextInputField(this, JXWidget::kHElastic, JXWidget::kVElastic, 125,104, 60,20); assert( mForwardQuote != NULL ); JXStaticText* obj7 = new JXStaticText("Caption:", this, JXWidget::kHElastic, JXWidget::kVElastic, 195,106, 55,20); assert( obj7 != NULL ); mForwardSetBtn = new JXTextButton("Set...", this, JXWidget::kHElastic, JXWidget::kVElastic, 250,103, 50,20); assert( mForwardSetBtn != NULL ); JXStaticText* obj8 = new JXStaticText("Forward Subject:", this, JXWidget::kHElastic, JXWidget::kVElastic, 10,129, 105,20); assert( obj8 != NULL ); mForwardSubject = new CTextInputField(this, JXWidget::kHElastic, JXWidget::kVElastic, 125,127, 210,20); assert( mForwardSubject != NULL ); JXStaticText* obj9 = new JXStaticText("Print Captions:", this, JXWidget::kHElastic, JXWidget::kVElastic, 160,152, 90,20); assert( obj9 != NULL ); mPrintSetBtn = new JXTextButton("Set...", this, JXWidget::kHElastic, JXWidget::kVElastic, 250,149, 50,20); assert( mPrintSetBtn != NULL ); mSeparateBCC = new JXTextCheckbox("Separate Bcc Message with Caption:", this, JXWidget::kHElastic, JXWidget::kVElastic, 15,175, 235,20); assert( mSeparateBCC != NULL ); mBCCCaption = new JXTextButton("Set...", this, JXWidget::kHElastic, JXWidget::kVElastic, 250,172, 50,20); assert( mBCCCaption != NULL ); mSaveGroup = new JXSecondaryRadioGroup(this, JXWidget::kHElastic, JXWidget::kVElastic, 10,215, 360,95); assert( mSaveGroup != NULL ); mSaveToFile = new JXTextRadioButton(0, "Always Save to Disk", mSaveGroup, JXWidget::kHElastic, JXWidget::kVElastic, 5,7, 150,20); assert( mSaveToFile != NULL ); mSaveToMailbox = new JXTextRadioButton(1, "Always Save to Mailbox", mSaveGroup, JXWidget::kHElastic, JXWidget::kVElastic, 5,27, 170,20); assert( mSaveToMailbox != NULL ); mSaveToMailboxName = new CTextInputField(mSaveGroup, JXWidget::kHElastic, JXWidget::kVElastic, 32,52, 260,20); assert( mSaveToMailboxName != NULL ); mSaveToMailboxPopup = new CMailboxPopupButton(false,mSaveGroup, JXWidget::kHElastic, JXWidget::kVElastic, 302,54, 30,16); assert( mSaveToMailboxPopup != NULL ); mSaveChoose = new JXTextRadioButton(2, "Allow Choice of where to Save", mSaveGroup, JXWidget::kHElastic, JXWidget::kVElastic, 5,72, 210,20); assert( mSaveChoose != NULL ); JXStaticText* obj10 = new JXStaticText("Save Draft", this, JXWidget::kHElastic, JXWidget::kVElastic, 15,205, 70,20); assert( obj10 != NULL ); mAutoSaveDrafts = new JXTextCheckbox("Save Draft for Recovery Every:", this, JXWidget::kHElastic, JXWidget::kVElastic, 15,320, 205,20); assert( mAutoSaveDrafts != NULL ); mAutoSaveDraftsInterval = new CInputField(this, JXWidget::kHElastic, JXWidget::kVElastic, 220,318, 40,20); assert( mAutoSaveDraftsInterval != NULL ); JXStaticText* obj11 = new JXStaticText("seconds", this, JXWidget::kHElastic, JXWidget::kVElastic, 265,320, 60,20); assert( obj11 != NULL ); // end JXLayout1 if (!CMulberryApp::sApp->LoadedPrefs()) mSaveToMailboxPopup->Deactivate(); // Start listening ListenTo(mReplySetBtn); ListenTo(mForwardSetBtn); ListenTo(mPrintSetBtn); ListenTo(mSeparateBCC); ListenTo(mBCCCaption); ListenTo(mSaveGroup); ListenTo(mSaveToMailboxPopup); ListenTo(mAutoSaveDrafts); } void CPrefsLetterGeneral::Receive(JBroadcaster* sender, const Message& message) { if (message.Is(JXButton::kPushed)) { if (sender == mReplySetBtn) { EditCaption(&mCopyPrefs->mReplyStart, NULL, &mCopyPrefs->mReplyEnd, NULL, &mCopyPrefs->mReplyCursorTop, NULL, NULL, NULL); return; } else if (sender == mForwardSetBtn) { EditCaption(&mCopyPrefs->mForwardStart, NULL, &mCopyPrefs->mForwardEnd, NULL, &mCopyPrefs->mForwardCursorTop, NULL, NULL, NULL); return; } else if (sender == mPrintSetBtn) { EditCaption(&mCopyPrefs->mHeaderCaption, &mCopyPrefs->mLtrHeaderCaption, &mCopyPrefs->mFooterCaption, &mCopyPrefs->mLtrFooterCaption, NULL, &mCopyPrefs->mHeaderBox, &mCopyPrefs->mFooterBox, &mCopyPrefs->mPrintSummary); return; } else if (sender == mBCCCaption) { EditBCCCaption(); return; } } else if (message.Is(JXCheckbox::kPushed)) { if (sender == mSeparateBCC) { mBCCCaption->SetActive(mSeparateBCC->IsChecked()); } else if (sender == mSeparateBCC) { mAutoSaveDraftsInterval->SetActive(mAutoSaveDrafts->IsChecked()); } } else if (message.Is(JXRadioGroup::kSelectionChanged)) { JIndex index = dynamic_cast(&message)->GetID(); if (sender == mSaveGroup) { if (mSaveGroup->GetSelectedItem() != eSaveDraftToMailbox) { mSaveToMailboxName->Deactivate(); mSaveToMailboxPopup->Deactivate(); } else { mSaveToMailboxName->Activate(); mSaveToMailboxPopup->Activate(); } return; } } else if(message.Is(JXMenu::kItemSelected)) { if (sender == mSaveToMailboxPopup) { const JXMenu::ItemSelected* is = dynamic_cast(&message); OnChangeSaveTo(is->GetIndex()); return; } } CTabPanel::Receive(sender, message); } // Set prefs void CPrefsLetterGeneral::SetData(void* data) { CPreferences* copyPrefs = (CPreferences*) data; // Save ref to prefs mCopyPrefs = copyPrefs; mMailDomain->SetText(copyPrefs->mMailDomain.GetValue()); // Copy text to edit fields mSpacesPerTab->SetValue(copyPrefs->spaces_per_tab.GetValue()); mTabSpace->SetState(JBoolean(copyPrefs->mTabSpace.GetValue())); mWrapLength->SetValue(copyPrefs->wrap_length.GetValue()); mReplyQuote->SetText(copyPrefs->mReplyQuote.GetValue()); mForwardQuote->SetText(copyPrefs->mForwardQuote.GetValue()); mForwardSubject->SetText(copyPrefs->mForwardSubject.GetValue()); mSeparateBCC->SetState(JBoolean(copyPrefs->mSeparateBCC.GetValue())); if (!mSeparateBCC->IsChecked()) mBCCCaption->Deactivate(); mSaveGroup->SelectItem(copyPrefs->mSaveOptions.GetValue().GetValue()); mSaveToMailboxName->SetText(copyPrefs->mSaveMailbox.GetValue()); if (!copyPrefs->mSaveOptions.GetValue().GetValue() != eSaveDraftToMailbox) { mSaveToMailboxName->Deactivate(); mSaveToMailboxPopup->Deactivate(); } mAutoSaveDrafts->SetState(copyPrefs->mAutoSaveDrafts.GetValue()); mAutoSaveDraftsInterval->SetValue(copyPrefs->mAutoSaveDraftsInterval.GetValue()); mAutoSaveDraftsInterval->SetActive(copyPrefs->mAutoSaveDrafts.GetValue()); } // Force update of prefs bool CPrefsLetterGeneral::UpdateData(void* data) { CPreferences* copyPrefs = (CPreferences*) data; copyPrefs->mMailDomain.SetValue(cdstring(mMailDomain->GetText())); // Copy info from panel into prefs JInteger value; mSpacesPerTab->GetValue(&value); copyPrefs->spaces_per_tab.SetValue(value); copyPrefs->mTabSpace.SetValue(mTabSpace->IsChecked()); mWrapLength->GetValue(&value); copyPrefs->wrap_length.SetValue(value); copyPrefs->mReplyQuote.SetValue(cdstring(mReplyQuote->GetText())); copyPrefs->mForwardQuote.SetValue(cdstring(mForwardQuote->GetText())); copyPrefs->mForwardSubject.SetValue(cdstring(mForwardSubject->GetText())); copyPrefs->mSeparateBCC.SetValue(mSeparateBCC->IsChecked()); copyPrefs->mSaveOptions.SetValue((ESaveOptions) mSaveGroup->GetSelectedItem()); copyPrefs->mSaveMailbox.SetValue(cdstring(mSaveToMailboxName->GetText())); copyPrefs->mAutoSaveDrafts.SetValue(mAutoSaveDrafts->IsChecked()); mAutoSaveDraftsInterval->GetValue(&value); copyPrefs->mAutoSaveDraftsInterval.SetValue(value); return true; } // Edit caption void CPrefsLetterGeneral::EditCaption(CPreferenceValueMap* text1, CPreferenceValueMap* text2, CPreferenceValueMap* text3, CPreferenceValueMap* text4, CPreferenceValueMap* cursor_top, CPreferenceValueMap* box1, CPreferenceValueMap* box2, CPreferenceValueMap* summary) { CPrefsEditCaption::PoseDialog(mCopyPrefs, text1, text2, text3, text4, cursor_top, box1, box2, summary); } // Edit bcc caption void CPrefsLetterGeneral::EditBCCCaption() { cdstring title = "Set BCC Caption"; CPrefsEditHeadFoot::PoseDialog(mCopyPrefs->mBCCCaption.Value(), title, mCopyPrefs, false); } // Change move to void CPrefsLetterGeneral::OnChangeSaveTo(JIndex nID) { cdstring mbox_name; if (mSaveToMailboxPopup->GetSelectedMboxName(mbox_name)) mSaveToMailboxName->SetText(mbox_name); } 10-100 /** * Copyright 2011-2015 Quickstep Technologies LLC. * Copyright 2015 Pivotal Software, 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. **/ #ifndef QUICKSTEP_QUERY_OPTIMIZER_LOGICAL_GENERATOR_HPP_ #define QUICKSTEP_QUERY_OPTIMIZER_LOGICAL_GENERATOR_HPP_ #include "query_optimizer/logical/Logical.hpp" #include "utility/Macros.hpp" namespace quickstep { class ParseStatement; namespace optimizer { class OptimizerContext; /** \addtogroup QueryOptimizer * @{ */ /** * @brief Generates a logical plan from a parse tree. */ class LogicalGenerator { public: /** * @brief Constructor. * * @param optimizer_context The optimizer context. */ explicit LogicalGenerator(OptimizerContext *optimizer_context); /** * @brief Destructor. */ ~LogicalGenerator(); /** * @return The current logical plan. */ const logical::LogicalPtr& logical_plan() const { return logical_plan_; } /** * @brief Converts the parse tree to a logical plan and optimizes the logical * plan by using rules. * * @param parse_statement The parse tree to be converted. * @return An optimized logical plan. */ logical::LogicalPtr generatePlan(const ParseStatement &parse_statement); private: /** * @brief Applies rules to the logical plan. */ void optimizePlan(); OptimizerContext *optimizer_context_; logical::LogicalPtr logical_plan_; DISALLOW_COPY_AND_ASSIGN(LogicalGenerator); }; /** @} */ } // namespace optimizer } // namespace quickstep #endif /* QUICKSTEP_QUERY_OPTIMIZER_LOGICAL_GENERATOR_HPP_ */ #include "Sales_item.h" int main(void) { cplusplus_primer::Sales_item trans1, trans2; trans1.display(); return 0; } #pragma once #include #include "JSON.hh" std::shared_ptr parse_pickle(const std::string& pickle_data); std::shared_ptr parse_pickle(const void* pickle_data); std::shared_ptr parse_pickle(const void* data, size_t size); std::string serialize_pickle(const JSONObject& o); freeswitch/src/mod/endpoints/mod_khomp/commons/base/configurator/restriction.hpp /* KHOMP generic endpoint/channel library. Copyright (C) 2007-2009 Khomp Ind. & Com. The contents of this file are subject to the Mozilla Public License Version 1.1 (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.mozilla.org/MPL/ Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. Alternatively, the contents of this file may be used under the terms of the "GNU Lesser General Public License 2.1" license (the “LGPL" License), in which case the provisions of "LGPL License" are applicable instead of those above. If you wish to allow use of your version of this file only under the terms of the LGPL License and not to allow others to use your version of this file under the MPL, indicate your decision by deleting the provisions above and replace them with the notice and other provisions required by the LGPL License. If you do not delete the provisions above, a recipient may use your version of this file under either the MPL or the LGPL License. The LGPL header follows below: This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. 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 #include #include #include #include #include #ifndef _CONFIG_RESTRICTION_HPP_ #define _CONFIG_RESTRICTION_HPP_ struct Restriction: public ConstThis < Restriction > { /* generic types */ // TODO: change this type name for something different // to avoid conflicting with "format.hpp". enum Format { F_USER, F_FILE }; enum Kind { K_STRING, K_NUMBER // = K_INTEGER // compatibility }; enum Bounds { B_FREE, B_RANGE, B_LIST, B_MAPS }; enum Numeral { N_UNIQUE, N_MULTIPLE }; typedef std::string Value; /* types used for data input */ struct Pair { const char *pretty; const char *value; }; typedef std::pair < Value, Value > PairMap; typedef std::list < PairMap > ListMap; /* types used internally */ typedef std::map < Value, Value > Map; typedef std::vector < Value > Vector; typedef std::list < Value > List; typedef std::pair < Value, Value > MapPair; struct Generic { Value _unique; List _multiple; }; Restriction(Kind kind, Numeral num) : _kind(kind), _bounds(B_FREE), _numeral(num), _unit(""), _init(-1), _fini(-1), _step(-1) { init_class(); } Restriction(Kind kind, Numeral num, double init, double fini, double step = 1) : _kind(kind), _bounds(B_RANGE), _numeral(num), _unit(""), _init(init), _fini(fini), _step(step) { init_class(); } Restriction(Kind kind, Numeral num, const char *unit, double init, double fini, double step = 1.0) : _kind(kind), _bounds(B_RANGE), _numeral(num), _unit(unit), _init(init), _fini(fini), _step(step) { init_class(); } Restriction(Kind kind, Numeral num, std::string unit, double init, double fini, double step = 1.0) : _kind(kind), _bounds(B_RANGE), _numeral(num), _unit(unit), _init(init), _fini(fini), _step(step) { init_class(); } Restriction(Kind kind, Numeral num, const char *first, ...) : _kind(kind), _bounds(B_LIST), _numeral(num), _unit(""), _init(-1), _fini(-1), _step(-1) { _list.push_back(std::string(first)); va_list ap; va_start(ap, first); while (true) { const char *arg = va_arg(ap, const char *); if (arg == NULL) break; _list.push_back(std::string(arg)); } init_class(); } Restriction(Kind kind, const char *unit, Numeral num, const char *first, ...) : _kind(kind), _bounds(B_LIST), _numeral(num), _unit(unit), _init(-1), _fini(-1), _step(-1) { _list.push_back(std::string(first)); va_list ap; va_start(ap, first); while (true) { const char *arg = va_arg(ap, const char *); if (arg == NULL) break; _list.push_back(std::string(arg)); } init_class(); } Restriction(Kind kind, Numeral num, const struct Pair first, ...) : _kind(kind), _bounds(B_MAPS), _numeral(num), _unit(""), _init(-1), _fini(-1), _step(-1) { _map_from_usr.insert(MapPair(Value(first.pretty), Value(first.value))); _map_from_cfg.insert(MapPair(Value(first.value), Value(first.pretty))); va_list ap; va_start(ap, first); while (true) { Pair arg = va_arg(ap, Pair); if (arg.pretty == NULL) break; _map_from_usr.insert(MapPair(Value(arg.pretty), Value(arg.value))); _map_from_cfg.insert(MapPair(Value(arg.value), Value(arg.pretty))); } init_class(); } Restriction(Kind kind, Numeral num, List list) : _kind(kind), _bounds(B_LIST), _numeral(num), _unit(""), _init(-1), _fini(-1), _step(-1), _list(list) { init_class(); } Restriction(Kind kind, Numeral num, ListMap map) : _kind(kind), _bounds(B_MAPS), _numeral(num), _unit(""), _init(-1), _fini(-1), _step(-1) { for (ListMap::iterator i = map.begin(); i != map.end(); i++) { _map_from_usr.insert(MapPair(Value((*i).first), Value((*i).second))); _map_from_cfg.insert(MapPair(Value((*i).second), Value((*i).first))); } init_class(); } const Kind kind() const { return _kind; }; const Bounds bounds() const { return _bounds; }; const Numeral numeral() const { return _numeral; }; const std::string & unit() const { return _unit; }; bool set(Format, const Vector &); bool set(Format, const Value &); bool get(Format, Vector &) const; bool get(Format, Value &) const; void allowed(Vector &) const; private: bool process(const Format, const Value &, Value &) const; bool unprocess(const Format, const Value &, Value &) const; void init_class(); static bool equalNumber(const double, const double); protected: const Kind _kind; const Bounds _bounds; const Numeral _numeral; Value _unit; const double _init, _fini, _step; Map _map_from_usr, _map_from_cfg; List _list; Generic _value; }; #endif /* _CONFIG_RESTRICTION_HPP_ */ // // ******************************************************************** // * License and Disclaimer * // * * // * The Geant4 software is copyright of the Copyright Holders of * // * the Geant4 Collaboration. It is provided under the terms and * // * conditions of the Geant4 Software License, included in the file * // * LICENSE and available at http://cern.ch/geant4/license . These * // * include a list of copyright holders. * // * * // * Neither the authors of this software system, nor their employing * // * institutes,nor the agencies providing financial support for this * // * work make any representation or warranty, express or implied, * // * regarding this software system or assume any liability for its * // * use. Please see the license in the file LICENSE and URL above * // * for the full disclaimer and the limitation of liability. * // * * // * This code implementation is the result of the scientific and * // * technical work of the GEANT4 collaboration. * // * By using, copying, modifying or distributing the software (or * // * any work based on the software) you agree to acknowledge its * // * use in resulting scientific publications, and indicate your * // * acceptance of all terms of the Geant4 Software license. * // ******************************************************************** // // /// \file field/field04/src/F04PhysicsList.cc /// \brief Implementation of the F04PhysicsList class // #include "PhysicsList.hh" #include "G4StepLimiterPhysics.hh" #include "G4OpticalPhysics.hh" #include "G4LossTableManager.hh" #include "G4ProcessManager.hh" #include "G4ParticleTypes.hh" #include "G4ParticleTable.hh" //#include "G4PhysListFactory.hh" #include "FTFP_BERT.hh" #include "G4Electron.hh" #include "G4Positron.hh" //#include "StepMax.hh" #include "G4ProcessTable.hh" #include "G4DecayTable.hh" #include "FiveBodyMuonDecayChannel.hh" #include "G4MuonMinusCapture.hh" #include "G4MuMinusCapturePrecompound.hh" #include "MuonDataController.hh" #include "G4SystemOfUnits.hh" #include "G4AutoDelete.hh" namespace MATHUSLA { namespace MU { //G4ThreadLocal StepMax* PhysicsList::fStepMaxProcess = 0; //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... PhysicsList::PhysicsList() : G4VModularPhysicsList(),fData() { SetVerboseLevel(1); // G4PhysListFactory factory; G4VModularPhysicsList* phys = NULL; phys = new FTFP_BERT; if (!phys) G4Exception("F04PhysicsList::F04PhysicsList","InvalidSetup", FatalException,"PhysicsList does not exist"); for (G4int i = 0; ; ++i) { G4VPhysicsConstructor* elem = const_cast (phys->GetPhysics(i)); if (elem == NULL) break; G4cout << "RegisterPhysics: " << elem->GetPhysicsName() << G4endl; RegisterPhysics(elem); } RegisterPhysics(new G4StepLimiterPhysics()); fData = MuonDataController::getMuonDataController(); } //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... PhysicsList::~PhysicsList() { } //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... void PhysicsList::ConstructParticle() { G4VModularPhysicsList::ConstructParticle(); G4GenericIon::GenericIonDefinition(); G4DecayTable* muonPlusDecayTable = new G4DecayTable(); muonPlusDecayTable -> Insert(new FiveBodyMuonDecayChannel("mu+",1.00,fData)); G4MuonPlus::MuonPlusDefinition() -> SetDecayTable(muonPlusDecayTable); G4DecayTable* muonMinusDecayTable = new G4DecayTable(); muonMinusDecayTable -> Insert(new FiveBodyMuonDecayChannel("mu-",1.00,fData)); G4MuonMinus::MuonMinusDefinition() -> SetDecayTable(muonMinusDecayTable); } //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... }} gameswf/gameswf/gameswf_function.cpp1-10 // gameswf_function.cpp -- <> 2003 // This source code has been donated to the Public Domain. Do // whatever you want with it. // ActionScript function. #include "gameswf_function.h" #include "gameswf_log.h" #include "gameswf_character.h" #include "gameswf_sprite.h" #include "as_array.h" namespace gameswf { // Invokes the function represented by a Function object. // public call(thisObject:Object, [parameter1:Object]) : Object void as_s_function_call(const fn_call& fn) { assert(fn.this_ptr); if (fn.nargs > 0) { as_object* properties = fn.this_ptr; if (properties->m_this_ptr != NULL) { as_object* func = properties->m_this_ptr.get_ptr(); if (func) { as_environment env(fn.get_player()); int nargs = 0; if (fn.nargs > 1) { nargs = 1; env.push(fn.arg(1)); } *fn.result = call_method(func, &env, fn.arg(0).to_object(), nargs, env.get_top_index()); } } } } as_s_function::as_s_function(player* player, const action_buffer* ab, int start, const gameswf::array& with_stack) : as_function(player), m_with_stack(with_stack), m_start_pc(start), m_length(0), m_is_function2(false), m_local_register_count(0), m_function2_flags(0) { // Flash stores a body(functions) of a class in _global, // action_buffer is in movie_def, therefore when we load another _root // action_buffer will be deleted and _global.MyClass will keep // the pointer to the removed object(action_buffer). // Therefore we have updated action_buffer* ==> action_buffer in as_s_function assert(ab); m_action_buffer = *ab; m_this_ptr = this; // any function MUST have prototype builtin_member("prototype", new as_object(player)); builtin_member("call", as_s_function_call); } as_s_function::~as_s_function() { } void as_s_function::operator()(const fn_call& fn) // Dispatch. { assert(fn.env); // Keep target alive during execution! gc_ptr target(m_target.get_ptr()); // try to use caller environment // if the caller object has own environment then we use its environment as_environment* env = fn.env; if (fn.this_ptr) { if (fn.this_ptr->get_environment()) { env = fn.this_ptr->get_environment(); } } // set 'this' as_object* this_ptr = env->get_target(); if (fn.this_ptr) { this_ptr = fn.this_ptr; if (this_ptr->m_this_ptr != NULL) { this_ptr = this_ptr->m_this_ptr.get_ptr(); } } // Function has been declared in moviclip ==> we should use its environment // At the same time 'this_ptr' may refers to another object // see testcase in .h file if (m_target != NULL) { character* ch = cast_to(m_target.get_ptr()); if (ch) { if (ch->is_alive()) { env = m_target->get_environment(); } } } // Set up local stack frame, for parameters and locals. int local_stack_top = env->get_local_frame_top(); env->add_frame_barrier(); if (m_is_function2 == false) { // Conventional function. // Push the arguments onto the local frame. int args_to_pass = imin(fn.nargs, m_args.size()); for (int i = 0; i < args_to_pass; i++) { assert(m_args[i].m_register == 0); env->add_local(m_args[i].m_name, fn.arg(i)); } env->set_local("this", this_ptr); // Put 'super' in a local var. if (fn.this_ptr) { env->add_local("super", fn.this_ptr->get_proto()); } } else { // function2: most args go in registers; any others get pushed. // Create local registers. env->add_local_registers(m_local_register_count); // Handle the explicit args. int args_to_pass = imin(fn.nargs, m_args.size()); for (int i = 0; i < args_to_pass; i++) { if (m_args[i].m_register == 0) { // Conventional arg passing: create a local var. env->add_local(m_args[i].m_name, fn.arg(i)); } else { // Pass argument into a register. int reg = m_args[i].m_register; env->set_register(reg, fn.arg(i)); } } // Handle the implicit args. int current_reg = 1; if (m_function2_flags & 0x01) { // preload 'this' into a register. IF_VERBOSE_ACTION(log_msg("-------------- preload this=%p to register %d\n", this_ptr, current_reg)); env->set_register(current_reg, this_ptr); current_reg++; } if (m_function2_flags & 0x02) { // Don't put 'this' into a local var. } else { // Put 'this' in a local var. env->add_local("this", as_value(this_ptr)); } // Init arguments array, if it's going to be needed. gc_ptr arg_array; if ((m_function2_flags & 0x04) || ! (m_function2_flags & 0x08)) { arg_array = new as_array(env->get_player()); as_value index_number; for (int i = 0; i < fn.nargs; i++) { index_number.set_int(i); arg_array->set_member(index_number.to_string(), fn.arg(i)); } } if (m_function2_flags & 0x04) { // preload 'arguments' into a register. env->set_register(current_reg, arg_array.get_ptr()); current_reg++; } if (m_function2_flags & 0x08) { // Don't put 'arguments' in a local var. } else { // Put 'arguments' in a local var. env->add_local("arguments", as_value(arg_array.get_ptr())); } if (m_function2_flags & 0x10) { // Put 'super' in a register. IF_VERBOSE_ACTION(log_msg("-------------- preload super=%p to register %d\n", fn.this_ptr->get_proto(), current_reg)); env->set_register(current_reg, fn.this_ptr->get_proto()); current_reg++; } if (m_function2_flags & 0x20) { // Don't put 'super' in a local var. } else { // Put 'super' in a local var. env->add_local("super", fn.this_ptr->get_proto()); } if (m_function2_flags & 0x40) { // Put '_root' in a register. env->set_register(current_reg, env->get_root()->get_root_movie()); current_reg++; } if (m_function2_flags & 0x80) { // Put '_parent' in a register. gameswf::array dummy; as_value parent = env->get_variable("_parent", dummy); IF_VERBOSE_ACTION(log_msg("-------------- preload _parent=%p to register %d\n", parent.to_object(), current_reg)); env->set_register(current_reg, parent); current_reg++; } if (m_function2_flags & 0x100) { // Put '_global' in a register. IF_VERBOSE_ACTION(log_msg("-------------- preload _global=%p to register %d\n", get_global(), current_reg)); env->set_register(current_reg, get_global()); current_reg++; } } // keep stack size int stack_size = env->get_stack_size(); // Execute the actions. m_action_buffer.execute(env, m_start_pc, m_length, fn.result, m_with_stack, m_is_function2); // restore stack size // it should not be but it happens if (stack_size != env->get_stack_size()) { // log_error("s_function: on entry stack size (%d) != on exit stack size (%d)\n", // stack_size, env->m_stack.size()); env->set_stack_size(stack_size); } // Clean up stack frame. env->set_local_frame_top(local_stack_top); if (m_is_function2) { // Clean up the local registers. env->drop_local_registers(m_local_register_count); } } as_c_function::as_c_function(player* player, as_c_function_ptr func) : as_function(player), m_func(func) { // any function MUST have prototype builtin_member("prototype", new as_object(player)); } void as_c_function::operator()(const fn_call& fn) { if (m_func) { (*m_func)(fn); } } } 100-1000 /* Copyright (C) 2017 Quaternion Risk Management Ltd All rights reserved. This file is part of ORE, a free-software/open-source library for transparent pricing and risk analysis - http://opensourcerisk.org ORE is free software: you can redistribute it and/or modify it under the terms of the Modified BSD License. You should have received a copy of the license along with this program. The license is also available online at This program is distributed on the basis that it will form a useful contribution to risk analytics and model standardisation, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the license for more details. */ #include #include #include #include #include #include #include using QuantLib::Null; namespace ore { namespace analytics { namespace { template T getData(const std::vector& data, const Size index) { QL_REQUIRE(index > 0, "index is still zero, need call to next()"); QL_REQUIRE(index <= data.size(), "index " << index << " is bigger than available data size (" << data.size() << ")"); return data.at(index - 1); } // getData } // namespace boost::shared_ptr parseRiskFactorKey(const std::string& str, std::vector& addTokens) { std::vector tokens; boost::split(tokens, str, boost::is_any_of("/"), boost::token_compress_off); QL_REQUIRE(tokens.size() >= 3, "parseRiskFactorKey: at least 3 tokens required, string is \"" << str << "\""); RiskFactorKey::KeyType type = parseRiskFactorKeyType(tokens[0]); boost::shared_ptr key = boost::make_shared(type, tokens[1], ore::data::parseInteger(tokens[2])); for (Size i = 3; i < tokens.size(); ++i) { addTokens.emplace_back(tokens[i]); } return key; } // parseRiskFactorKey void SensitivityDataInMemory::add(const std::string& tradeId, const std::string& factor, const std::string& factor2, const double value, const double value2) { std::vector addTokens1, addTokens2; boost::shared_ptr key1 = parseRiskFactorKey(factor, addTokens1); boost::shared_ptr key2 = factor2 == "" ? nullptr : parseRiskFactorKey(factor2, addTokens2); tradeId_.emplace_back(tradeId); addTokens1_.emplace_back(addTokens1); addTokens2_.emplace_back(addTokens2); keys1_.emplace_back(key1); keys2_.emplace_back(key2); value_.push_back(value); value2_.push_back(value2); }; bool SensitivityDataInMemory::next() { if (index_ < tradeId_.size()) { ++index_; return true; } return false; } void SensitivityDataInMemory::reset() { index_ = 0; } std::string SensitivityDataInMemory::tradeId() const { return getData(tradeId_, index_); } bool SensitivityDataInMemory::isCrossGamma() const { return getData(keys2_, index_) != nullptr; } boost::shared_ptr SensitivityDataInMemory::factor1() const { return getData(keys1_, index_); } boost::shared_ptr SensitivityDataInMemory::factor2() const { return getData(keys2_, index_); } std::vector SensitivityDataInMemory::additionalTokens1() const { return getData(addTokens1_, index_); } std::vector SensitivityDataInMemory::additionalTokens2() const { return getData(addTokens2_, index_); } double SensitivityDataInMemory::value() const { return getData(value_, index_); } double SensitivityDataInMemory::value2() const { return getData(value2_, index_); } bool SensitivityDataInMemory::hasFactor(const RiskFactorKey& key) const { for (auto const& k : keys1_) { if (k != nullptr && key == *k) return true; } for (auto const& k : keys2_) { if (k != nullptr && key == *k) return true; } return false; } void loadSensitivityDataFromCsv(SensitivityDataInMemory& data, const std::string& fileName, const char delim) { LOG("Load Sensitivity Data from file " << fileName); ore::data::CSVFileReader reader(fileName, true); bool delta = reader.hasField("#TradeId") && reader.hasField("Factor") && (reader.hasField("Delta") || reader.hasField("ParDelta")); bool gamma = reader.hasField("#TradeId") && reader.hasField("Factor 1") && reader.hasField("Factor 2") && (reader.hasField("CrossGamma") || reader.hasField("ParCrossGamma")); QL_REQUIRE(delta || gamma, "loadSensitivityDataFromCsv: file " << fileName << " not recognised as either delta or crossgamma file"); std::string valueField, valueField2; if (delta) { valueField = reader.hasField("ParDelta") ? "ParDelta" : "Delta"; valueField2 = reader.hasField("ParGamma") ? "ParGamma" : "Gamma"; } else valueField = reader.hasField("ParCrossGamma") ? "ParCrossGamma" : "CrossGamma"; Size errorLines = 0, validLines = 0; while (reader.next()) { try { if (delta) { data.add(reader.get("#TradeId"), reader.get("Factor"), "", ore::data::parseReal(reader.get(valueField)), ore::data::parseReal(reader.get(valueField2))); } else if (gamma) { data.add(reader.get("#TradeId"), reader.get("Factor 1"), reader.get("Factor 2"), ore::data::parseReal(reader.get(valueField)), Null()); } ++validLines; } catch (const std::exception& e) { ++errorLines; WLOG("skipping line " << reader.currentLine() << ": " << e.what()); } } LOG("Read " << validLines << " valid data lines, skipped " << errorLines << " invalid data lines in file " << fileName); } // loadSensitivityDataFromCsv void loadMappingTableFromCsv(std::map& data, const std::string& fileName, const char delim) { LOG("Load Mapping Data from file " << fileName); ore::data::CSVFileReader reader(fileName, false); Size count = 0; while (reader.next()) { data[reader.get(0)] = reader.get(1); ++count; } LOG("Read " << count << " valid data lines in file " << fileName); } // loadMappingTableFromCsv } // namespace analytics } // namespace ore /* During the break the schoolchildren, boys and girls, formed a queue of n people in the canteen. Initially the children stood in the order they entered the canteen. However, after a while the boys started feeling awkward for standing in front of the girls in the queue and they started letting the girls move forward each second. Let's describe the process more precisely. Let's say that the positions in the queue are sequentially numbered by integers from 1 to n, at that the person in the position number 1 is served first. Then, if at time x a boy stands on the i-th position and a girl stands on the (i?+?1)-th position, then at time x?+?1 the i-th position will have a girl and the (i?+?1)-th position will have a boy. The time is given in seconds. You've got the initial position of the children, at the initial moment of time. Determine the way the queue is going to look after t seconds. Input The first line contains two integers n and t (1?=?n,?t?=?50), which represent the number of children in the queue and the time after which the queue will transform into the arrangement you need to find. The next line contains string s, which represents the schoolchildren's initial arrangement. If the i-th position in the queue contains a boy, then the i-th character of string s equals "B", otherwise the i-th character equals "G". Output Print string a, which describes the arrangement after t seconds. If the i-th position has a boy after the needed time, then the i-th character a must equal "B", otherwise it must equal "G". Examples inputCopy 5 1 BGGBG outputCopy GBGGB inputCopy 5 2 BGGBG outputCopy GGBGB inputCopy 4 1 GGGB outputCopy GGGB */ #include using namespace std; int main(){ ios_base::sync_with_stdio(false); cin.tie(NULL); int n, t; cin >> n >> t; string s; cin >> s; while (t--) { bool isSwap = false; for(int i = 0; i < n - 1; i++){ if(s[i] == 'B' && s[i + 1] == 'G'){ swap(s[i], s[i + 1]); i++; isSwap = true; } } if(isSwap == false) break; } cout << s; return 0; } #include "ObfRoutingSectionInfo.h" #include "ObfRoutingSectionInfo_P.h" #include "Utilities.h" #include "Logging.h" OsmAnd::ObfRoutingSectionInfo::ObfRoutingSectionInfo(const std::shared_ptr& container) : ObfSectionInfo(container) , _p(new ObfRoutingSectionInfo_P(this)) { } OsmAnd::ObfRoutingSectionInfo::~ObfRoutingSectionInfo() { } std::shared_ptr OsmAnd::ObfRoutingSectionInfo::getAttributeMapping() const { return _p->getAttributeMapping(); } OsmAnd::ObfRoutingSectionLevel::ObfRoutingSectionLevel(const RoutingDataLevel dataLevel_) : _p(new ObfRoutingSectionLevel_P(this)) , dataLevel(dataLevel_) , rootNodes(_p->_rootNodes) { } OsmAnd::ObfRoutingSectionLevel::~ObfRoutingSectionLevel() { } OsmAnd::ObfRoutingSectionLevelTreeNode::ObfRoutingSectionLevelTreeNode() : length(0) , offset(0) , hasChildrenDataBoxes(false) , firstDataBoxInnerOffset(0) , dataOffset(0) { } OsmAnd::ObfRoutingSectionLevelTreeNode::~ObfRoutingSectionLevelTreeNode() { } OsmAnd::ObfRoutingSectionAttributeMapping::ObfRoutingSectionAttributeMapping() { decodeMap.reserve(4096); } OsmAnd::ObfRoutingSectionAttributeMapping::~ObfRoutingSectionAttributeMapping() { } void OsmAnd::ObfRoutingSectionAttributeMapping::registerMapping( const uint32_t id, const QString& tag, const QString& value) { MapObject::AttributeMapping::registerMapping(id, tag, value); // Create decode mapping auto pDecode = decodeMap.getRef(id); if (!pDecode) { LogPrintf(LogSeverityLevel::Error, "Decode attribute #%u is not defined. Capture of %s = %s ignored.", id, qPrintable(tag), qPrintable(value)); return; } const QStringRef tagRef(&pDecode->tag); const QStringRef valueRef(&pDecode->value); // Create decode mapping auto pRoutingDecode = routingDecodeMap.getRef(id); if (!pRoutingDecode) { RouteTypeRule rt(tag, value); pRoutingDecode = routingDecodeMap.insert(id, rt); } // Capture quick-access rules if (tag.startsWith(QLatin1String("ref:"))) { const auto languageIdRef = tagRef.mid(QLatin1String("ref:").size()); localizedRefAttributes.insert(languageIdRef, id); localizedRefAttributeIds.insert(id, languageIdRef); refAttributeIds.insert(id); } } OsmAnd::ObfRoutingSectionAttributeMapping::RouteTypeCondition::RouteTypeCondition() : condition(""), hours(nullptr), floatValue(0) { } OsmAnd::ObfRoutingSectionAttributeMapping::RouteTypeCondition::~RouteTypeCondition() { } OsmAnd::ObfRoutingSectionAttributeMapping::RouteTypeRule::RouteTypeRule() : intValue(0), floatValue(0), type(0), forward(0) { } OsmAnd::ObfRoutingSectionAttributeMapping::RouteTypeRule::RouteTypeRule(const QString& tag, const QString& value) : intValue(0), floatValue(0), type(0), forward(0) { t = tag; if (QLatin1String("true") == value) v = QLatin1String("yes"); else if (QLatin1String("false") == value) v = QLatin1String("no"); else v = value; analyze(); } OsmAnd::ObfRoutingSectionAttributeMapping::RouteTypeRule::~RouteTypeRule() { } int OsmAnd::ObfRoutingSectionAttributeMapping::RouteTypeRule::isForward() const { return forward; } QString OsmAnd::ObfRoutingSectionAttributeMapping::RouteTypeRule::getTag() const { return t; } QString OsmAnd::ObfRoutingSectionAttributeMapping::RouteTypeRule::getValue() const { return v; } bool OsmAnd::ObfRoutingSectionAttributeMapping::RouteTypeRule::roundabout() const { return type == RouteTypeRule::Roundabout; } int OsmAnd::ObfRoutingSectionAttributeMapping::RouteTypeRule::getType() const { return type; } bool OsmAnd::ObfRoutingSectionAttributeMapping::RouteTypeRule::conditional() const { return !conditions.empty(); } int OsmAnd::ObfRoutingSectionAttributeMapping::RouteTypeRule::onewayDirection() const { if (type == RouteTypeRule::OneWay) return intValue; return 0; } float OsmAnd::ObfRoutingSectionAttributeMapping::RouteTypeRule::maxSpeed() const { if (type == RouteTypeRule::MaxSpeed) { if (!conditions.empty()) { for (auto& c : conditions) { if (c->hours && c->hours->isOpened()) { return c->floatValue; } } } return floatValue; } return -1; } int OsmAnd::ObfRoutingSectionAttributeMapping::RouteTypeRule::lanes() const { if (type == RouteTypeRule::Lanes) return intValue; return -1; } QString OsmAnd::ObfRoutingSectionAttributeMapping::RouteTypeRule::highwayRoad() const { if (type == RouteTypeRule::HighwayType) return v; return QString(); } void OsmAnd::ObfRoutingSectionAttributeMapping::RouteTypeRule::analyze() { if (t.compare(QLatin1String("oneway"), Qt::CaseInsensitive) == 0) { type = RouteTypeRule::OneWay; if (QLatin1String("-1") == v || QLatin1String("reverse") == v) intValue = -1; else if(QLatin1String("1") == v || QLatin1String("yes") == v) intValue = 1; else intValue = 0; } else if (t.compare(QLatin1String("highway"), Qt::CaseInsensitive) == 0 && QLatin1String("traffic_signals") == v) { type = RouteTypeRule::TrafficSignals; } else if (t.compare(QLatin1String("railway"), Qt::CaseInsensitive) == 0 && (QLatin1String("crossing") == v || QLatin1String("level_crossing") == v)) { type = RouteTypeRule::RailwayCrossing; } else if(t.compare(QLatin1String("roundabout"), Qt::CaseInsensitive) == 0 && !v.isNull()) { type = RouteTypeRule::Roundabout; } else if (t.compare(QLatin1String("junction"), Qt::CaseInsensitive) == 0 && QString("roundabout").compare(v, Qt::CaseInsensitive) == 0) { type = RouteTypeRule::Roundabout; } else if (t.compare(QLatin1String("highway"), Qt::CaseInsensitive) == 0 && !v.isNull()) { type = RouteTypeRule::HighwayType; } else if (t.startsWith(QLatin1String("access")) && !v.isNull()) { type = RouteTypeRule::Access; } else if (t.compare(QLatin1String("maxspeed:conditional"), Qt::CaseInsensitive) == 0 && !v.isNull()) { QStringList cts = v.split(';'); for (const auto& c : cts) { int ch = c.indexOf('@'); if (ch > 0) { const auto cond = std::make_shared(); cond->floatValue = Utilities::parseSpeed(c.mid(0, ch), 0); cond->condition = c.mid(0, ch + 1).trimmed(); if (cond->condition.startsWith('(')) cond->condition = cond->condition.mid(1).trimmed(); if (cond->condition.endsWith(')')) cond->condition = cond->condition.mid(0, cond->condition.length() - 1).trimmed(); cond->hours = OpeningHoursParser::parseOpenedHours(cond->condition.toStdString()); conditions.push_back(cond); } } type = RouteTypeRule::MaxSpeed; } else if (t.compare(QLatin1String("maxspeed"), Qt::CaseInsensitive) == 0 && !v.isNull()) { type = RouteTypeRule::MaxSpeed; floatValue = Utilities::parseSpeed(v, 0); } else if (t.compare(QLatin1String("maxspeed:forward"), Qt::CaseInsensitive) == 0 && !v.isNull()) { type = RouteTypeRule::MaxSpeed; forward = 1; floatValue = Utilities::parseSpeed(v, 0); } else if(t.compare(QLatin1String("maxspeed:backward"), Qt::CaseInsensitive) == 0 && !v.isNull()) { type = RouteTypeRule::MaxSpeed; forward = -1; floatValue = Utilities::parseSpeed(v, 0); } else if (t.compare(QLatin1String("lanes"), Qt::CaseInsensitive) == 0 && !v.isNull()) { type = RouteTypeRule::Lanes; intValue = Utilities::parseArbitraryInt(v, -1); } } /*else { LogPrintf(LogSeverityLevel::Debug, "%s = %s", qPrintable(ruleTag), qPrintable(ruleValue)); }*/ //if (ruleTag.compare(QLatin1String("oneway"), Qt::CaseInsensitive) == 0) //{ // rule->type = RuleType::OneWay; // if (ruleValue == QLatin1String("-1") || ruleValue == QLatin1String("reverse")) // rule->parsedValue.asSignedInt = -1; // else if (ruleValue == QLatin1String("1") || ruleValue == QLatin1String("yes")) // rule->parsedValue.asSignedInt = 1; // else // rule->parsedValue.asSignedInt = 0; //} //else if (ruleTag.compare(QLatin1String("highway"), Qt::CaseInsensitive) == 0 && ruleValue == QLatin1String("traffic_signals")) //{ // rule->type = RuleType::TrafficSignals; //} //else if (ruleTag.compare(QLatin1String("railway"), Qt::CaseInsensitive) == 0 && (ruleValue == QLatin1String("crossing") || ruleValue == QLatin1String("level_crossing"))) //{ // rule->type = RuleType::RailwayCrossing; //} //else if (ruleTag.compare(QLatin1String("roundabout"), Qt::CaseInsensitive) == 0 && !ruleValue.isEmpty()) //{ // rule->type = RuleType::Roundabout; //} //else if (ruleTag.compare(QLatin1String("junction"), Qt::CaseInsensitive) == 0 && ruleValue.compare(QLatin1String("roundabout"), Qt::CaseInsensitive) == 0) //{ // rule->type = RuleType::Roundabout; //} //else if (ruleTag.compare(QLatin1String("highway"), Qt::CaseInsensitive) == 0 && !ruleValue.isEmpty()) //{ // rule->type = RuleType::Highway; //} //else if (ruleTag.startsWith(QLatin1String("access")) && !ruleValue.isEmpty()) //{ // rule->type = RuleType::Access; //} //else if (ruleTag.compare(QLatin1String("maxspeed"), Qt::CaseInsensitive) == 0 && !ruleValue.isEmpty()) //{ // rule->type = RuleType::Maxspeed; // rule->parsedValue.asFloat = Utilities::parseSpeed(ruleValue, -1.0); //} //else if (ruleTag.compare(QLatin1String("lanes"), Qt::CaseInsensitive) == 0 && !ruleValue.isEmpty()) //{ // rule->type = RuleType::Lanes; // rule->parsedValue.asSignedInt = Utilities::parseArbitraryInt(ruleValue, -1); //} //// Fill gaps in IDs //while (decodingRules.size() < rule->id) // decodingRules.push_back(nullptr); //decodingRules.push_back(rule); #ifndef ___TSP_PROBLEM_IMPLEMENTATION___ #define ___TSP_PROBLEM_IMPLEMENTATION___ #include #include #include #include #include #include #include /* zadanie do rozwiązania */ struct City { std::string name; // nazwa miasta std::array x; // wsp. miasta /** * Oblicza odleglosc do miasta * */ double dist(const City &c); }; /** * problem komiwojazera - zadanie * */ class Problem : public std::vector { }; /** * lista kolejnych indeksów miast do odwiedzenia. Punkt roboczy, albo potencjalne rozwiązanie. Jest * to zgodne z formatem wyjściowym rozwiązania. * */ class Solution : public std::vector { public: std::shared_ptr problem; Solution(); Solution(std::shared_ptr p); /** * odwołujemy się do miast z problemu do rozwiażania * */ /** * metoda pozwalająca na bezpieczne ustawienie problemu do rozwiązania. * Inicjuje ona listę indeksów miast na kolejne wartości, czyli kolejność * miast do odwiedzenia jest taka jak w podanym zadaniu. * */ void set_problem(std::shared_ptr p); /** * metoda licząca długość trasy odwiedzającej wszystkie miasta. * To też jest nasza minimalizowana funkcja celu!!! * */ double distance() const; /** * Oblicza kolejne możliwe rozwiązanie. Ta metoda ma taką cechę, że * pozwala na deterministyczne przejście po wszystkich permutacjach. * Nadaje się więc do rozwiązania siłowego. * */ Solution generate_next(std::function on_end = []() {}) const; /** * Generuje nam losowego sąsiada. * */ Solution generate_random_neighbour(std::mt19937 &mt) const; void randomize(std::mt19937 &mt); // dodaje 1 na zadanej wspolrzednej Solution inc_axis(int ax) const; // odejmuje 1 na zadanej wspolrzednej Solution dec_axis(int ax) const; }; /** * Wczytywanie problemu z strumienia wejściowego. Jeśli jako nazwę miasta poda się "-" to kończy wczytywać. * */ std::istream &operator>>(std::istream &is, Problem &p); /** * Wypisanie rozwiązania na standardowe wyjście * */ std::ostream &operator<<(std::ostream &o, Solution &s); bool operator==(const Solution &a, const Solution &b); #endif // // file : uninitialized.hpp // in : file:///home/tim/projects/nblockchain/nblockchain/persistence/persistence/tools/uninitialized.hpp // // created by : // date: Fri Jul 08 2016 23:31:39 GMT+0200 (CEST) // // // Copyright (c) 2016 // // 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 __N_177204756238143312_155459372_UNINITIALIZED_HPP__ #define __N_177204756238143312_155459372_UNINITIALIZED_HPP__ #include #include namespace neam { namespace cr { /// \brief Create an uninitialized storage that yields a given type. /// This allows to create uninitialized objects on the stack or as class/struct members /// \warning The default behavior is to not call the destructor at the end of the life of uninitialized<> template class uninitialized { private: static constexpr uint8_t is_constructed_bit = 1 << 0; static constexpr uint8_t destructor_call_bit = 1 << 1; static constexpr uint8_t is_constructed_mask = ~is_constructed_bit; static constexpr uint8_t destructor_call_mask = ~destructor_call_bit; public: ObjectType *operator ->() noexcept { return (ObjectType *)(storage); } const ObjectType *operator ->() const noexcept { return (ObjectType *)(storage); } ObjectType *operator &() { return (ObjectType *)(storage); } const ObjectType *operator &() const noexcept { return (ObjectType *)(storage); } operator ObjectType &() & noexcept { return *(ObjectType *)(storage); } operator ObjectType &&() && noexcept { return *(ObjectType *)(storage); } operator const ObjectType &() const & noexcept { return (ObjectType *)(storage); } operator const ObjectType &&() const && noexcept { return (ObjectType *)(storage); } ObjectType &get() & noexcept { return *(ObjectType *)(storage); } ObjectType &&get() && noexcept { return *(ObjectType *)(storage); } const ObjectType &get() const & noexcept { return *(ObjectType *)(storage); } const ObjectType &&get() const && noexcept { return *(ObjectType *)(storage); } /// \brief if call_it is true, it will call the destructor of the object /// when the life of the instance ends. The default is to NOT call the destructor void schedule_destructor_call(bool call_it = true) noexcept { storage[sizeof(ObjectType)] = (storage[sizeof(ObjectType)] & destructor_call_mask) | (call_it ? destructor_call_bit : 0); } /// \brief Return whether or not the object is constructed bool is_constructed() const noexcept { return storage[sizeof(ObjectType)] & is_constructed_bit; } /// \brief construct the object /// \warning Does not call the destructor if the object has previously been constructed template void construct(Args &&... args) noexcept(noexcept(ObjectType(std::forward(args)...))) { new (&this->get()) ObjectType(std::forward(args)...); storage[sizeof(ObjectType)] |= is_constructed_bit; } /// \brief Change the constructed flag of the object void mark_as_constructed(bool constructed) noexcept { if (constructed) storage[sizeof(ObjectType)] |= is_constructed_bit; else storage[sizeof(ObjectType)] &= is_constructed_mask; } /// \brief call the destructor /// \param force Force a call to the destructor, even if the object is marked as not-created void destruct(bool force = false) noexcept(noexcept(~ObjectType())) { if (force || is_constructed()) { this->get().~ObjectType(); storage[sizeof(ObjectType)] &= is_constructed_mask; } } ~uninitialized() noexcept(noexcept(~ObjectType())) { if ((storage[sizeof(ObjectType)] & (is_constructed_bit | destructor_call_bit)) == (is_constructed_bit | destructor_call_bit)) destruct(); } uninitialized() noexcept = default; uninitialized(ObjectType&& o) noexcept(noexcept(construct(std::move(o)))) { construct(std::move(o)); } uninitialized(const ObjectType& o) noexcept(noexcept(construct(o))) { construct(o); } template uninitialized& operator = (Arg&& a) noexcept(noexcept(get() = std::forward(a)) && noexcept(construct(std::forward(a)))) { if (is_constructed()) get() = std::forward(a); else construct(std::forward(a)); } using object_type = ObjectType; private: alignas(ObjectType) uint8_t storage[1 + sizeof(ObjectType)]; }; } // namespace cr } // namespace neam #endif // __N_177204756238143312_155459372_UNINITIALIZED_HPP__ 10-100 #include #include #include #include "core.h" #include "examples/single_cube.h" #include "examples/debug.h" #include "examples/cube_storm.h" #include "examples/seesaw.h" #include "examples/spring.h" #include "examples/brick_wall.h" #include "examples/mirror_cube.h" #include "examples/hinge_joints.h" #include "examples/arm.h" #include "examples/stack.h" #include "examples/rott_pendulum.h" #include "examples/triple_pendula.h" #include "render/menu.h" #include "vendor/imgui.h" #define MENU_TITLE "Examples" #define FPS_MAX 144 #define FPS_MIN 30 static Example_Scene example_scenes[END_EXAMPLE_SCENE]; static Example_Scene_Type selected_scene; // Used when fps is fixed static bool fix_fps = true; static int fps = 60; static int load_selected_scene() { return example_scenes[selected_scene].init(); } static void core_destroy_selected_scene() { example_scenes[selected_scene].destroy(); } int core_init() { example_scenes[DEBUG_EXAMPLE_SCENE] = debug_example_scene; example_scenes[SINGLE_CUBE_EXAMPLE_SCENE] = single_cube_example_scene; example_scenes[CUBE_STORM_EXAMPLE_SCENE] = cube_storm_example_scene; example_scenes[SEESAW_EXAMPLE_SCENE] = seesaw_example_scene; example_scenes[SPRING_EXAMPLE_SCENE] = spring_example_scene; example_scenes[BRICK_WALL_EXAMPLE_SCENE] = brick_wall_example_scene; example_scenes[MIRROR_CUBE_EXAMPLE_SCENE] = mirror_cube_example_scene; example_scenes[HINGE_JOINTS_EXAMPLE_SCENE] = hinge_joints_example_scene; example_scenes[ARM_EXAMPLE_SCENE] = arm_example_scene; example_scenes[STACK_EXAMPLE_SCENE] = stack_example_scene; example_scenes[ROTT_PENDULUM_EXAMPLE_SCENE] = rott_pendulum_example_scene; example_scenes[TRIPLE_PENDULA_EXAMPLE_SCENE] = triple_pendula_example_scene; selected_scene = EXAMPLE_SCENE_INITIAL; return load_selected_scene(); } void core_destroy() { core_destroy_selected_scene(); } void core_update(r64 delta_time) { if (fix_fps) { fps = CLAMP(fps, FPS_MIN, FPS_MAX); delta_time = 1.0 / fps; } example_scenes[selected_scene].update(delta_time); } void core_render() { example_scenes[selected_scene].render(); } void core_input_process(boolean* key_state, r64 delta_time) { if (key_state[GLFW_KEY_2]) { core_switch_scene(SINGLE_CUBE_EXAMPLE_SCENE); key_state[GLFW_KEY_2] = 0; } else { example_scenes[selected_scene].input_process(key_state, delta_time); } } void core_mouse_change_process(boolean reset, r64 x_pos, r64 y_pos) { example_scenes[selected_scene].mouse_change_process(reset, x_pos, y_pos); } void core_mouse_click_process(s32 button, s32 action, r64 x_pos, r64 y_pos) { example_scenes[selected_scene].mouse_click_process(button, action, x_pos, y_pos); } void core_scroll_change_process(r64 x_offset, r64 y_offset) { example_scenes[selected_scene].scroll_change_process(x_offset, y_offset); } void core_window_resize_process(s32 width, s32 height) { example_scenes[selected_scene].window_resize_process(width, height); } void core_menu_render() { if (ImGui::Begin(MENU_TITLE, NULL, 0)) { ImGui::Text("Press [ESC] to open/close the menu"); ImGui::Checkbox("Fix timestep for FPS", &fix_fps); if (fix_fps) { ImGui::DragInt("FPS", &fps, 0.1f, FPS_MIN, FPS_MAX); } else { ImGui::Text("Timestep will be calculated per frame"); ImGui::Text("Simulation might become a bit unstable."); } // left static Example_Scene_Type selected = EXAMPLE_SCENE_INITIAL; ImGui::BeginChild("left pane", ImVec2(150, 0), true); for (u32 i = 0; i < END_EXAMPLE_SCENE; ++i) { Example_Scene* example_scene = &example_scenes[i]; if (ImGui::Selectable(example_scene->name, selected == i)) { selected = static_cast(i); core_switch_scene(selected); } } ImGui::EndChild(); ImGui::SameLine(); // right ImGui::BeginGroup(); ImGui::BeginChild("item view", ImVec2(0, -ImGui::GetFrameHeightWithSpacing())); // Leave room for 1 line below us example_scenes[selected_scene].menu_properties_update(); ImGui::EndChild(); //if (ImGui::Button("Revert")) {} //ImGui::SameLine(); //if (ImGui::Button("Save")) {} ImGui::EndGroup(); } } void core_switch_scene(Example_Scene_Type scene) { core_destroy_selected_scene(); selected_scene = scene; load_selected_scene(); // Force scene's camera to reset extern GLFWwindow* main_window; double xpos, ypos; glfwGetCursorPos(main_window, &xpos, &ypos); core_mouse_change_process(true, xpos, ypos); }H0RIA/LiliDoctorat #include "TaxInfo.h" #include "Locality.h" #include "Language.h" #include "PriestInfo.h" #include "County.h" #include "Comune.h" #include "Deanery.h" #include "ImageInfo.h" #include "HousePositioning.h" #include "HouseFunction.h" #include "BuildingInfo.h" #include "House.h" #include "DBManager.h" using namespace DBWrapper; DBManager* DBManager::m_pInstance = nullptr; DBManager* DBManager::instance() { if(m_pInstance == nullptr){ m_pInstance = new DBManager(); } return m_pInstance; } DBManager::~DBManager() { // TODO } Language* DBManager::findLanguage(const QString& name) { Language* lang = nullptr; if(name.isEmpty() || m_Languages.isEmpty()) return lang; foreach (Language* currentLang, m_Languages) { if(currentLang != nullptr){ if(currentLang->Name() == name){ lang = currentLang; break; } } } return lang; } //const Language* //DBManager::findLanguage(const QString& name)const //{ // const Language* lang = nullptr; // if(name.isEmpty() || m_Languages.isEmpty()) // return lang; // foreach (const Language* currentLang, m_Languages) { // if(currentLang != nullptr){ // if(currentLang->Name() == name){ // lang = currentLang; // break; // } // } // } // return lang; //} QList DBManager::findTaxByName(const QString& name) { QList result; if(name.isEmpty()) return result; foreach(const TaxInfo& tax, m_Taxes){ if(tax.Name().contains(name)) result.append(tax); } return result; } QList DBManager::findTaxByDescr(const QString& descr) { QList result; if(descr.isEmpty()) return result; foreach(const TaxInfo& tax, m_Taxes){ if(tax.Description().contains(descr)) result.append(tax); } return result; } QList DBManager::findTaxByFormula(const QString& formula) { QList result; if(formula.isEmpty()) return result; foreach(const TaxInfo& tax, m_Taxes){ if(tax.Formula().contains(formula)) result.append(tax); } return result; } QList DBManager::findTax(const QString& data) { QList result; if(data.isEmpty()) return result; foreach(const TaxInfo& tax, m_Taxes){ if(tax.Name().contains(data) || tax.Description().contains(data) || tax.Formula().contains(data)) result.append(tax); } return result; } TaxInfo DBManager::findTax(const QUuid& id) { TaxInfo tax; if(id.isNull()) return tax; foreach(const TaxInfo& taxInfo, m_Taxes){ if(taxInfo.Id() == id) return taxInfo; } return tax; } void DBManager::clearData() { clearLanguages(); } void DBManager::loadData() { loadTaxes(); loadLanguages(); } void DBManager::saveData() { saveTaxes(); saveLanguages(); } void DBManager::loadLanguages() { if(m_pDatabase == nullptr) return; if(!m_pDatabase->isOpen() || m_pDatabase->isOpenError()) return; QSqlQuery query(*m_pDatabase); if(query.exec("Select * From Languages")){ } // TODO Language::LANGUAGE_ROMANIAN = QUuid::createUuid(); Language::LANGUAGE_GERMAN = QUuid::createUuid(); Language::LANGUAGE_SAXON = QUuid::createUuid(); Language::LANGUAGE_HUNGARIAN = QUuid::createUuid(); } void DBManager::saveLanguages() { // TODO } void DBManager::loadTaxes() { QString strQuery = "Select * From TaxInfo;"; QSqlQuery query(strQuery); while(query.next()){ TaxInfo tax; tax.setId(QUuid(query.value("Id").toString())); tax.setName(query.value("Name").toString()); tax.setDescription(query.value("Description").toString()); tax.setFormula(query.value("Formula").toString()); m_Taxes.append(tax); } } void DBManager::saveTaxes()const { foreach(const TaxInfo& tax, m_Taxes) tax.SaveToDB(); } QSqlDatabase* DBManager::getDatabase() { return m_pDatabase; } bool DBManager::createDatabase() { if(m_pDatabase != nullptr) return false; QStringList strPathToDB = QStandardPaths::standardLocations(QStandardPaths::AppDataLocation); if(strPathToDB.isEmpty()){ QMessageBox::critical(0, QObject::tr("Cannot create database"), QObject::tr("Unable to create a SQLite database file.\n"), QMessageBox::Cancel); qApp->exit(); } QString firstPath = strPathToDB.front(); m_pDatabase = new QSqlDatabase(); *m_pDatabase = QSqlDatabase::addDatabase("QSQLITE"); firstPath += QDir::separator(); QDir dir(firstPath); dir.mkpath(firstPath); firstPath += DEFAULT_SQLITE_NAME; m_pDatabase->setDatabaseName(firstPath); if(!m_pDatabase->open()){ QMessageBox::critical(0, QObject::tr("Cannot open database"), m_pDatabase->lastError().text(), QMessageBox::Cancel); qDebug() << m_pDatabase->lastError().text(); qApp->exit(); return false; } return true; } bool DBManager::createTables() { if(m_pDatabase == nullptr) return false; if(!m_pDatabase->isOpen()){ if(!m_pDatabase->open()) return false; } bool result = true; // First we enable foreign keys QString strQuery = "PRAGMA foreign_keys = ON;"; RunQuery(strQuery, result); // Create the language table if(!Language::TableExists()) result = !result ? false : Language::CreateTable(); // Create the Priest table if(!PriestInfo::TableExists()) result = !result ? false : PriestInfo::CreateTable(); // Create the County table if(!County::TableExists()) result = !result ? false : County::CreateTable(); // Create the Comune table if(!Comune::TableExists()) result = !result ? false : Comune::CreateTable(); // Create the Deanery table if(!Deanery::TableExists()) result = !result ? false : Deanery::CreateTable(); // Create the locality table if(!Locality::TableExists()) result = !result ? false : Locality::CreateTable(); // Create the TaxInfo table if(!TaxInfo::TableExists()) result = !result ? false : TaxInfo::CreateTable(); // Create the ImageInfo table if(!ImageInfo::TableExists()) result = !result ? false : ImageInfo::CreateTable(); // Create the HousePositioning table if(!HousePositioning::TableExists()) result = !result ? false : HousePositioning::CreateTable(); // Create the HouseFunction table if(!HouseFunction::TableExists()) result = !result ? false : HouseFunction::CreateTable(); // Create the BuildingInfo table if(!BuildingInfo::TableExists()) result = !result ? false : BuildingInfo::CreateTable(); // Create the House table if(!House::TableExists()) result = !result ? false : House::CreateTable(); // Create the HousePriests table if(!PriestTenure::TableExists()) result = !result ? false : PriestTenure::CreateTable(); // Create the HouseTaxes table if(! ::TableExists("HouseTaxes")){ strQuery = "Create table HouseTaxes (IdHouse varchar(50),IdTax varchar(50),FOREIGN KEY(IdHouse) REFERENCES House(Id),FOREIGN KEY(IdTax) REFERENCES TaxInfo(Id))"; RunQuery(strQuery, result); } // Create the HouseImages table if(! ::TableExists("HouseImages")){ strQuery = "Create table HouseImages (IdHouse varchar(50),IdImage varchar(50),FOREIGN KEY(IdHouse) REFERENCES House(Id),FOREIGN KEY(IdImage) REFERENCES ImageInfo(Id))"; RunQuery(strQuery, result); } return result; } DBManager::DBManager() : m_pDatabase(nullptr) { bool howAreWe = true; if(createDatabase()){ howAreWe = createTables(); }else howAreWe = false; if(!howAreWe){ QMessageBox::critical(0, QObject::tr("Cannot open database"), QObject::tr("Unable to establish a database connection.\n" "This example needs SQLite support. Please read " "the Qt SQL driver documentation for information how " "to build it."), QMessageBox::Cancel); return; } loadData(); } DBManager::DBManager(const DBManager& dbm) : m_pDatabase(nullptr) { Q_UNUSED(dbm); loadData(); } DBManager& DBManager::operator=(const DBManager& dbm) { Q_UNUSED(dbm); return *this; } #pragma once #include "Math.hpp" #include "Object.hpp" #include //----------------------------------------------------------------------------// // Defs //----------------------------------------------------------------------------// #define gDevice Device::Get() //----------------------------------------------------------------------------// // Time //----------------------------------------------------------------------------// inline double Time(void) // in seconds { LARGE_INTEGER _f, _c; QueryPerformanceFrequency(&_f); QueryPerformanceCounter(&_c); return (double)_c.QuadPart / (double)_f.QuadPart; } //----------------------------------------------------------------------------// // Keyboard //----------------------------------------------------------------------------// enum InputKey : uint { IK_Unknown = 0, }; //----------------------------------------------------------------------------// // Mouse //----------------------------------------------------------------------------// enum CursorMode : uint { CM_Default = 0x0, CM_Hidden = 0x1, CM_Camera = 0x2 | CM_Hidden, }; //----------------------------------------------------------------------------// // Device //----------------------------------------------------------------------------// class Device : public Singleton { public: Device(void); ~Device(void); HWND WindowHandle(void) { return m_handle; } uint WindowWidth(void) { return m_width; } uint WindowHeight(void) { return m_height; } const Vec2& WindowSize(void) { return m_size; } bool ShouldClose(void) { return m_shouldClose; } void PollEvents(void); void SetCursorMode(CursorMode _mode); const Vec2& GetCameraDelta(void) { return m_cameraDelta; } void SetTitle(const char* _title, ...) { char _buff[256]; va_list _args; va_start(_args, _title); vsprintf(_buff, _title, _args); va_end(_args); SetWindowText(WindowHandle(), _buff); } protected: void _CursorToCenter(void); LRESULT _HandleMsg(UINT _msg, WPARAM _wParam, LPARAM _lParam); static LRESULT CALLBACK _MsgCallback(HWND _wnd, UINT _msg, WPARAM _wParam, LPARAM _lParam); // window HWND m_handle; bool m_shouldClose; bool m_active; bool m_fullscreen; uint m_width; uint m_height; Vec2 m_size; // cursor CursorMode m_cursorMode; Vec2i m_cursorPos; Vec2i m_cursorPrevPos; //todo: remove it (?) Vec2 m_cameraDelta; Vec2 m_cameraSensitivity; bool m_resetCameraDelta; //todo: rename to m_resetCursor }; //----------------------------------------------------------------------------// // //----------------------------------------------------------------------------// /* * MixerLoops.cpp * -------------- * Purpose: Utility inner loops for mixer-related functionality. * Notes : This file contains performance-critical loops with variants * optimized for various instruction sets. * Authors: * OpenMPT Devs * The OpenMPT source code is released under the BSD license. Read LICENSE for more details. */ #include "stdafx.h" #include "MixerLoops.h" #include "Snd_defs.h" #include "ModChannel.h" #ifdef ENABLE_SSE2 #include #endif OPENMPT_NAMESPACE_BEGIN //////////////////////////////////////////////////////////////////////////////////// // 3DNow! optimizations #ifdef ENABLE_X86_AMD // Convert integer mix to floating-point static void AMD_StereoMixToFloat(const int32 *pSrc, float *pOut1, float *pOut2, uint32 nCount, const float _i2fc) { _asm { movd mm0, _i2fc mov edx, pSrc mov edi, pOut1 mov ebx, pOut2 mov ecx, nCount punpckldq mm0, mm0 inc ecx shr ecx, 1 mainloop: movq mm1, qword ptr [edx] movq mm2, qword ptr [edx+8] add edi, 8 pi2fd mm1, mm1 pi2fd mm2, mm2 add ebx, 8 pfmul mm1, mm0 pfmul mm2, mm0 add edx, 16 movq mm3, mm1 punpckldq mm3, mm2 punpckhdq mm1, mm2 dec ecx movq qword ptr [edi-8], mm3 movq qword ptr [ebx-8], mm1 jnz mainloop emms } } static void AMD_FloatToStereoMix(const float *pIn1, const float *pIn2, int32 *pOut, uint32 nCount, const float _f2ic) { _asm { movd mm0, _f2ic mov eax, pIn1 mov ebx, pIn2 mov edx, pOut mov ecx, nCount punpckldq mm0, mm0 inc ecx shr ecx, 1 sub edx, 16 mainloop: movq mm1, [eax] movq mm2, [ebx] add edx, 16 movq mm3, mm1 punpckldq mm1, mm2 punpckhdq mm3, mm2 add eax, 8 pfmul mm1, mm0 pfmul mm3, mm0 add ebx, 8 pf2id mm1, mm1 pf2id mm3, mm3 dec ecx movq qword ptr [edx], mm1 movq qword ptr [edx+8], mm3 jnz mainloop emms } } static void AMD_FloatToMonoMix(const float *pIn, int32 *pOut, uint32 nCount, const float _f2ic) { _asm { movd mm0, _f2ic mov eax, pIn mov edx, pOut mov ecx, nCount punpckldq mm0, mm0 add ecx, 3 shr ecx, 2 sub edx, 16 mainloop: movq mm1, [eax] movq mm2, [eax+8] add edx, 16 pfmul mm1, mm0 pfmul mm2, mm0 add eax, 16 pf2id mm1, mm1 pf2id mm2, mm2 dec ecx movq qword ptr [edx], mm1 movq qword ptr [edx+8], mm2 jnz mainloop emms } } static void AMD_MonoMixToFloat(const int32 *pSrc, float *pOut, uint32 nCount, const float _i2fc) { _asm { movd mm0, _i2fc mov eax, pSrc mov edx, pOut mov ecx, nCount punpckldq mm0, mm0 add ecx, 3 shr ecx, 2 sub edx, 16 mainloop: movq mm1, qword ptr [eax] movq mm2, qword ptr [eax+8] add edx, 16 pi2fd mm1, mm1 pi2fd mm2, mm2 add eax, 16 pfmul mm1, mm0 pfmul mm2, mm0 dec ecx movq qword ptr [edx], mm1 movq qword ptr [edx+8], mm2 jnz mainloop emms } } #endif // ENABLE_X86_AMD /////////////////////////////////////////////////////////////////////////////////////// // SSE Optimizations #ifdef ENABLE_SSE2 static void SSE2_StereoMixToFloat(const int32 *pSrc, float *pOut1, float *pOut2, uint32 nCount, const float _i2fc) { __m128 i2fc = _mm_load_ps1(&_i2fc); const __m128i *in = reinterpret_cast(pSrc); // We may read beyond the wanted length... this works because we know that we will always work on our buffers of size MIXBUFFERSIZE nCount = (nCount + 3) / 4; do { __m128i i1 = _mm_loadu_si128(in); // Load four integer values, LRLR __m128i i2 = _mm_loadu_si128(in + 1); // Load four integer values, LRLR in += 2; __m128 f1 = _mm_cvtepi32_ps(i1); // Convert to four floats, LRLR __m128 f2 = _mm_cvtepi32_ps(i2); // Convert to four floats, LRLR f1 = _mm_mul_ps(f1, i2fc); // Apply int->float factor f2 = _mm_mul_ps(f2, i2fc); // Apply int->float factor __m128 fl = _mm_shuffle_ps(f1, f2, _MM_SHUFFLE(2, 0, 2, 0)); // LRLR+LRLR => LLLL __m128 fr = _mm_shuffle_ps(f1, f2, _MM_SHUFFLE(3, 1, 3, 1)); // LRLR+LRLR => RRRR _mm_storeu_ps(pOut1, fl); // Store four float values, LLLL _mm_storeu_ps(pOut2, fr); // Store four float values, RRRR pOut1 += 4; pOut2 += 4; } while(--nCount); } static void SSE2_FloatToStereoMix(const float *pIn1, const float *pIn2, int32 *pOut, uint32 nCount, const float _f2ic) { __m128 f2ic = _mm_load_ps1(&_f2ic); __m128i *out = reinterpret_cast<__m128i *>(pOut); // We may read beyond the wanted length... this works because we know that we will always work on our buffers of size MIXBUFFERSIZE nCount = (nCount + 3) / 4; do { __m128 fl = _mm_loadu_ps(pIn1); // Load four float values, LLLL __m128 fr = _mm_loadu_ps(pIn2); // Load four float values, RRRR pIn1 += 4; pIn2 += 4; fl = _mm_mul_ps(fl, f2ic); // Apply int->float factor fr = _mm_mul_ps(fr, f2ic); // Apply int->float factor __m128 f1 = _mm_unpacklo_ps(fl, fr); // LL__+RR__ => LRLR __m128 f2 = _mm_unpackhi_ps(fl, fr); // __LL+__RR => LRLR __m128i i1 =_mm_cvtps_epi32(f1); // Convert to four ints __m128i i2 =_mm_cvtps_epi32(f2); // Convert to four ints _mm_storeu_si128(out, i1); // Store four int values, LRLR _mm_storeu_si128(out + 1, i2); // Store four int values, LRLR out += 2; } while(--nCount); } #endif // ENABLE_SSE2 #if defined(ENABLE_X86) && defined(ENABLE_SSE) static void SSE_StereoMixToFloat(const int32 *pSrc, float *pOut1, float *pOut2, uint32 nCount, const float _i2fc) { _asm { movss xmm0, _i2fc mov edx, pSrc mov eax, pOut1 mov ebx, pOut2 mov ecx, nCount shufps xmm0, xmm0, 0x00 xorps xmm1, xmm1 xorps xmm2, xmm2 inc ecx shr ecx, 1 mainloop: cvtpi2ps xmm1, [edx] cvtpi2ps xmm2, [edx+8] add eax, 8 add ebx, 8 movlhps xmm1, xmm2 mulps xmm1, xmm0 add edx, 16 shufps xmm1, xmm1, 0xD8 dec ecx movlps qword ptr [eax-8], xmm1 movhps qword ptr [ebx-8], xmm1 jnz mainloop } } static void SSE_MonoMixToFloat(const int32 *pSrc, float *pOut, uint32 nCount, const float _i2fc) { _asm { movss xmm0, _i2fc mov edx, pSrc mov eax, pOut mov ecx, nCount shufps xmm0, xmm0, 0x00 xorps xmm1, xmm1 xorps xmm2, xmm2 add ecx, 3 shr ecx, 2 mainloop: cvtpi2ps xmm1, [edx] cvtpi2ps xmm2, [edx+8] add eax, 16 movlhps xmm1, xmm2 mulps xmm1, xmm0 add edx, 16 dec ecx movups [eax-16], xmm1 jnz mainloop } } #endif // ENABLE_X86 && ENABLE_SSE #ifdef ENABLE_X86 // Convert floating-point mix to integer static void X86_FloatToStereoMix(const float *pIn1, const float *pIn2, int32 *pOut, uint32 nCount, const float _f2ic) { _asm { mov esi, pIn1 mov ebx, pIn2 mov edi, pOut mov ecx, nCount fld _f2ic mainloop: fld dword ptr [ebx] add edi, 8 fld dword ptr [esi] add ebx, 4 add esi, 4 fmul st(0), st(2) fistp dword ptr [edi-8] fmul st(0), st(1) fistp dword ptr [edi-4] dec ecx jnz mainloop fstp st(0) } } // Convert integer mix to floating-point static void X86_StereoMixToFloat(const int32 *pSrc, float *pOut1, float *pOut2, uint32 nCount, const float _i2fc) { _asm { mov esi, pSrc mov edi, pOut1 mov ebx, pOut2 mov ecx, nCount fld _i2fc mainloop: fild dword ptr [esi] fild dword ptr [esi+4] add ebx, 4 add edi, 4 fmul st(0), st(2) add esi, 8 fstp dword ptr [ebx-4] fmul st(0), st(1) fstp dword ptr [edi-4] dec ecx jnz mainloop fstp st(0) } } static void X86_FloatToMonoMix(const float *pIn, int32 *pOut, uint32 nCount, const float _f2ic) { _asm { mov edx, pIn mov eax, pOut mov ecx, nCount fld _f2ic sub eax, 4 R2I_Loop: fld DWORD PTR [edx] add eax, 4 fmul ST(0), ST(1) dec ecx lea edx, [edx+4] fistp DWORD PTR [eax] jnz R2I_Loop fstp st(0) } } static void X86_MonoMixToFloat(const int32 *pSrc, float *pOut, uint32 nCount, const float _i2fc) { _asm { mov edx, pOut mov eax, pSrc mov ecx, nCount fld _i2fc sub edx, 4 I2R_Loop: fild DWORD PTR [eax] add edx, 4 fmul ST(0), ST(1) dec ecx lea eax, [eax+4] fstp DWORD PTR [edx] jnz I2R_Loop fstp st(0) } } #endif // ENABLE_X86 static void C_FloatToStereoMix(const float *pIn1, const float *pIn2, int32 *pOut, uint32 nCount, const float _f2ic) { for(uint32 i=0; i=0; i--) { pFrontBuf[i*4+3] = pRearBuf[i*2+1]; pFrontBuf[i*4+2] = pRearBuf[i*2+0]; pFrontBuf[i*4+1] = pFrontBuf[i*2+1]; pFrontBuf[i*4+0] = pFrontBuf[i*2+0]; } } void InterleaveFrontRear(mixsample_t *pFrontBuf, mixsample_t *pRearBuf, uint32 nFrames) { #if defined(ENABLE_X86) && defined(MPT_INTMIXER) X86_InterleaveFrontRear(pFrontBuf, pRearBuf, nFrames); #else C_InterleaveFrontRear(pFrontBuf, pRearBuf, nFrames); #endif } #ifdef ENABLE_X86 static void X86_MonoFromStereo(int32 *pMixBuf, uint32 nSamples) { _asm { mov ecx, nSamples mov esi, pMixBuf mov edi, esi stloop: mov eax, dword ptr [esi] mov edx, dword ptr [esi+4] add edi, 4 add esi, 8 add eax, edx sar eax, 1 dec ecx mov dword ptr [edi-4], eax jnz stloop } } #endif static void C_MonoFromStereo(mixsample_t *pMixBuf, uint32 nSamples) { for(uint32 i=0; i(1.0 / (1 << 20)) // Decay threshold for floating point mixer #ifdef ENABLE_X86 static void X86_StereoFill(int32 *pBuffer, uint32 nSamples, int32 *lpROfs, int32 *lpLOfs) { _asm { mov edi, pBuffer mov ecx, nSamples mov eax, lpROfs mov edx, lpLOfs mov eax, [eax] mov edx, [edx] or ecx, ecx jz fill_loop mov ebx, eax or ebx, edx jz fill_loop ofsloop: mov ebx, eax mov esi, edx neg ebx neg esi sar ebx, 31 sar esi, 31 and ebx, OFSDECAYMASK and esi, OFSDECAYMASK add ebx, eax add esi, edx sar ebx, OFSDECAYSHIFT sar esi, OFSDECAYSHIFT sub eax, ebx sub edx, esi mov ebx, eax or ebx, edx jz fill_loop add edi, 8 dec ecx mov [edi-8], eax mov [edi-4], edx jnz ofsloop fill_loop: mov ebx, ecx and ebx, 3 jz fill4x fill1x: mov [edi], eax mov [edi+4], edx add edi, 8 dec ebx jnz fill1x fill4x: shr ecx, 2 or ecx, ecx jz done fill4xloop: mov [edi], eax mov [edi+4], edx mov [edi+8], eax mov [edi+12], edx add edi, 8*4 dec ecx mov [edi-16], eax mov [edi-12], edx mov [edi-8], eax mov [edi-4], edx jnz fill4xloop done: mov esi, lpROfs mov edi, lpLOfs mov [esi], eax mov [edi], edx } } #endif // c implementation taken from libmodplug static void C_StereoFill(mixsample_t *pBuffer, uint32 nSamples, mixsample_t &rofs, mixsample_t &lofs) { if ((!rofs) && (!lofs)) { InitMixBuffer(pBuffer, nSamples*2); return; } for (uint32 i=0; i 0 ? 255 : -255)) / 256; #if MPT_COMPILER_SHIFT_SIGNED const mixsample_t x_r = (rofs + (((-rofs) >> (sizeof(mixsample_t) * 8 - 1)) & OFSDECAYMASK)) >> OFSDECAYSHIFT; const mixsample_t x_l = (lofs + (((-lofs) >> (sizeof(mixsample_t) * 8 - 1)) & OFSDECAYMASK)) >> OFSDECAYSHIFT; #else const mixsample_t x_r = mpt::rshift_signed(rofs + (mpt::rshift_signed(-rofs, sizeof(int) * 8 - 1) & OFSDECAYMASK), OFSDECAYSHIFT); const mixsample_t x_l = mpt::rshift_signed(lofs + (mpt::rshift_signed(-lofs, sizeof(int) * 8 - 1) & OFSDECAYMASK), OFSDECAYSHIFT); #endif #else const mixsample_t x_r = rofs * (1.0f / (1 << OFSDECAYSHIFT)); const mixsample_t x_l = lofs * (1.0f / (1 << OFSDECAYSHIFT)); #endif rofs -= x_r; lofs -= x_l; pBuffer[i*2] = rofs; pBuffer[i*2+1] = lofs; } #ifndef MPT_INTMIXER if(fabs(rofs) < OFSTHRESHOLD) rofs = 0; if(fabs(lofs) < OFSTHRESHOLD) lofs = 0; #endif } void StereoFill(mixsample_t *pBuffer, uint32 nSamples, mixsample_t &rofs, mixsample_t &lofs) { #if defined(ENABLE_X86) && defined(MPT_INTMIXER) X86_StereoFill(pBuffer, nSamples, &rofs, &lofs); #else C_StereoFill(pBuffer, nSamples, rofs, lofs); #endif } #ifdef ENABLE_X86 typedef ModChannel ModChannel_; static void X86_EndChannelOfs(ModChannel *pChannel, int32 *pBuffer, uint32 nSamples) { _asm { mov esi, pChannel mov edi, pBuffer mov ecx, nSamples mov eax, dword ptr [esi+ModChannel_.nROfs] mov edx, dword ptr [esi+ModChannel_.nLOfs] or ecx, ecx jz brkloop ofsloop: mov ebx, eax mov esi, edx neg ebx neg esi sar ebx, 31 sar esi, 31 and ebx, OFSDECAYMASK and esi, OFSDECAYMASK add ebx, eax add esi, edx sar ebx, OFSDECAYSHIFT sar esi, OFSDECAYSHIFT sub eax, ebx sub edx, esi mov ebx, eax add dword ptr [edi], eax add dword ptr [edi+4], edx or ebx, edx jz brkloop add edi, 8 dec ecx jnz ofsloop brkloop: mov esi, pChannel mov dword ptr [esi+ModChannel_.nROfs], eax mov dword ptr [esi+ModChannel_.nLOfs], edx } } #endif // c implementation taken from libmodplug static void C_EndChannelOfs(ModChannel &chn, mixsample_t *pBuffer, uint32 nSamples) { mixsample_t rofs = chn.nROfs; mixsample_t lofs = chn.nLOfs; if ((!rofs) && (!lofs)) return; for (uint32 i=0; i> (sizeof(mixsample_t) * 8 - 1)) & OFSDECAYMASK)) >> OFSDECAYSHIFT; const mixsample_t x_l = (lofs + (((-lofs) >> (sizeof(mixsample_t) * 8 - 1)) & OFSDECAYMASK)) >> OFSDECAYSHIFT; #else const mixsample_t x_r = mpt::rshift_signed(rofs + (mpt::rshift_signed(-rofs, sizeof(int) * 8 - 1) & OFSDECAYMASK), OFSDECAYSHIFT); const mixsample_t x_l = mpt::rshift_signed(lofs + (mpt::rshift_signed(-lofs, sizeof(int) * 8 - 1) & OFSDECAYMASK), OFSDECAYSHIFT); #endif #else const mixsample_t x_r = rofs * (1.0f / (1 << OFSDECAYSHIFT)); const mixsample_t x_l = lofs * (1.0f / (1 << OFSDECAYSHIFT)); #endif rofs -= x_r; lofs -= x_l; pBuffer[i*2] += rofs; pBuffer[i*2+1] += lofs; } #ifndef MPT_INTMIXER if(mpt::abs(rofs) < OFSTHRESHOLD) rofs = 0; if(mpt::abs(lofs) < OFSTHRESHOLD) lofs = 0; #endif chn.nROfs = rofs; chn.nLOfs = lofs; } void EndChannelOfs(ModChannel &chn, mixsample_t *pBuffer, uint32 nSamples) { #if defined(ENABLE_X86) && defined(MPT_INTMIXER) X86_EndChannelOfs(&chn, pBuffer, nSamples); #else C_EndChannelOfs(chn, pBuffer, nSamples); #endif } void InterleaveStereo(const mixsample_t * MPT_RESTRICT inputL, const mixsample_t * MPT_RESTRICT inputR, mixsample_t * MPT_RESTRICT output, size_t numSamples) { while(numSamples--) { *(output++) = *(inputL++); *(output++) = *(inputR++); } } void DeinterleaveStereo(const mixsample_t * MPT_RESTRICT input, mixsample_t * MPT_RESTRICT outputL, mixsample_t * MPT_RESTRICT outputR, size_t numSamples) { while(numSamples--) { *(outputL++) = *(input++); *(outputR++) = *(input++); } } #ifndef MODPLUG_TRACKER void ApplyGain(int32 *soundBuffer, std::size_t channels, std::size_t countChunk, int32 gainFactor16_16) { if(gainFactor16_16 == (1<<16)) { // nothing to do, gain == +/- 0dB return; } // no clipping prevention is done here int32 * buf = soundBuffer; for(std::size_t i=0; ip11866.cpp #include #include using namespace std; int main() { queue q; int N; scanf("%d", &N); for (int i = 1; i <= N; i++) { q.push(i); } int M; scanf("%d", &M); int cnt = 1; printf("<"); while (true) { if (cnt < M) { int pass = q.front(); q.pop(); q.push(pass); cnt++; } else { printf("%d", q.front()); q.pop(); if (q.empty()) break; printf(", "); cnt = 1; } } printf(">\n"); }zhcet19/NeoAlgo-1C-Plus-Plus/math/krishnamurthy_number.cpp /* If the factorial of individual digits of a number when summed up yields the number itself then the number is called Krishnamurthy Number. Example : Consider the number 145 Summing of factorials of the individual digits we get = 1! + 4! + 5! = 1 + 24 + 120 =145. Hence 145 is not a Krishnamurthy number. */ //CPP Program to find whether a number is a Krishnamurthy number #include //Function to calculate the factorial of the individual digits int Factorial ( int n ) { if ( n == 1 || n == 0 ) { return 1; } return n * Factorial( n - 1 ); } int Krishnamurthy_No ( int num ) { int digit, sum = 0 ,copy = num; //Running a loop till we have extracted all the digits from the copy of the given number while ( copy > 0 ) { digit = copy % 10; sum = sum + Factorial ( digit ); copy = copy / 10; } return sum; } int main () { int number, digit, sum = 0; std::cout << "Enter a natural number " << std::endl; std::cin >> number; int answer = Krishnamurthy_No ( number ); //Comparing if calculated sum adds up to the number if ( answer == number) { std:: cout << number <<" is a krishnamurthy number. "; } else { std:: cout << number <<" is not a krishnamurthy number. "; } } /* Test Case 1 :- INPUT : 37 OUTPUT : 37 is not a krishnamurthy number. Test Case 2 :- INPUT : 145 OUTPUT: 145 is a krishnamurthy number. */ gemxd/gemfirexd-oss /* * Copyright (c) 2010-2015 Pivotal Software, 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. See accompanying * LICENSE file. */ #include "GemFireXDHelper.h" using namespace std; BEGIN_TEST(testSQLDriverConnect) { retcode = ::SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &henv); ASSERT(retcode == SQL_SUCCESS, "SQLAllocHandle call failed"); ASSERT(henv != NULL, "SQLAllocHandle failed to return valid env handle"); retcode = ::SQLAllocHandle(SQL_HANDLE_DBC, henv, &hdbc); ASSERT(retcode == SQL_SUCCESS, "SQLAllocHandle call failed"); ASSERT(hdbc != NULL, "SQLAllocHandle failed to return valid DBC handle"); retcode = ::SQLDriverConnect(NULL, NULL, NULL, 0, NULL, 0, NULL, 0); ASSERT(retcode == SQL_INVALID_HANDLE, "SQLDriverConnect should return invalid handle"); retcode = ::SQLDriverConnect(NULL, NULL, NULL, 0, NULL, 0, NULL, SQL_DRIVER_PROMPT); ASSERT(retcode == SQL_ERROR, "SQLDriverConnect should return sql error"); #if defined(WIN32) || defined(_WIN32) retcode = ::SQLDriverConnect(hdbc, NULL, (SQLCHAR*)"InvalidConnectionString", strlen("InvalidConnectionString"), NULL, 0, NULL, SQL_DRIVER_NOPROMPT ); ASSERT(retcode == SQL_ERROR, "SQLDriverConnect should return sql error"); retcode = ::SQLDriverConnect(hdbc, NULL, (SQLCHAR*)"InvalidKey=Value", strlen("InvalidKey=Value"), NULL, 0, NULL, SQL_DRIVER_NOPROMPT ); ASSERT(retcode == SQL_ERROR, "SQLDriverConnect should return sql error"); retcode = ::SQLDriverConnect(hdbc, NULL, (SQLCHAR*)"DSN=Invalid", strlen("DSN=Invalid"), NULL, 0, NULL, SQL_DRIVER_NOPROMPT ); ASSERT(retcode == SQL_ERROR, "SQLDriverConnect should return sql error"); retcode = ::SQLDriverConnect(hdbc, NULL, (SQLCHAR*)"DSN=", strlen("DSN="), NULL, 0, NULL, SQL_DRIVER_NOPROMPT ); ASSERT(retcode == SQL_ERROR, "SQLDriverConnect should return sql error"); retcode = ::SQLDriverConnect(hdbc, NULL, (SQLCHAR*)"DSN=DEFAULT", strlen("DSN=DEFAULT"), NULL, 0, NULL, SQL_DRIVER_NOPROMPT ); ASSERT(retcode == SQL_ERROR, "SQLDriverConnect should return sql error"); #endif SQLCHAR OutConnStr[255]; SQLSMALLINT OutConnStrLen =0; retcode = ::SQLDriverConnect(hdbc, NULL, (SQLCHAR*)GFXDCONNSTRING, SQL_NTS, OutConnStr, 255, &OutConnStrLen, SQL_DRIVER_NOPROMPT ); LOGF("\nout conn str is %s and length is %d", OutConnStr, OutConnStrLen); ASSERT(strlen((char*)OutConnStr) == OutConnStrLen, "OutConnStrLen and Actual length should match"); ASSERT(strcmp((char*)OutConnStr, "jdbc:gemfirexd://127.0.0.1:1999/") == 0, "Returned output connection string sould match"); retcode = ::SQLFreeHandle(SQL_HANDLE_DBC, hdbc); ASSERT(retcode == SQL_SUCCESS, "SQLFreeHandle call failed"); retcode = ::SQLFreeHandle(SQL_HANDLE_ENV, henv); ASSERT(retcode == SQL_SUCCESS, "SQLFreeHandle call failed"); } END_TEST(testSQLDriverConnect) src/apache/filter.hpp #pragma once /** * Actually does the work of the filter * * © Copyright 2014 . All Rights Reserved. * License: Apache License, Version 2.0 (See LICENSE.txt) **/ extern "C" { #include } namespace cdnalizer { namespace apache { /** This function is the apache output filter. * It filters a bucket brigade (usually 8k of html content, broken into chunks (buckets), then * passes that on to the next filter. * * @param filter The filter chain (holds a bunch of state stuff) * @param bb The bucket brigade we're working on * @returns an apache status code */ apr_status_t filter(ap_filter_t *filter, apr_bucket_brigade *bb); } } 1-10 /* * Portions Copyright (c) 2020 Huawei Technologies Co.,Ltd. * Portions Copyright (c) 1996-2015, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * * openGauss is licensed under Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * 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 PSL v2 for more details. * ------------------------------------------------------------------------- * * nbtxlog.cpp * parse btree xlog * * IDENTIFICATION * * src/gausskernel/storage/access/redo/nbtxlog.cpp * *------------------------------------------------------------------------- */ #include "postgres.h" #include "knl/knl_variable.h" #include "access/nbtree.h" #include "access/transam.h" #include "access/xlog.h" #include "access/xlogutils.h" #include "access/xlogproc.h" #include "pgxc/pgxc.h" #include "access/multi_redo_api.h" #include "miscadmin.h" #include "access/redo_common.h" #ifdef ENABLE_UT #define static #endif enum { BTREE_INSERT_ORIG_BLOCK_NUM = 0, BTREE_INSERT_CHILD_BLOCK_NUM, BTREE_INSERT_META_BLOCK_NUM }; enum { BTREE_SPLIT_LEFT_BLOCK_NUM = 0, BTREE_SPLIT_RIGHT_BLOCK_NUM, BTREE_SPLIT_RIGHTNEXT_BLOCK_NUM, BTREE_SPLIT_CHILD_BLOCK_NUM }; enum { BTREE_VACUUM_ORIG_BLOCK_NUM = 0, }; enum { BTREE_DELETE_ORIG_BLOCK_NUM = 0, }; enum { BTREE_DELETE_PAGE_TARGET_BLOCK_NUM = 0, BTREE_DELETE_PAGE_LEFT_BLOCK_NUM, BTREE_DELETE_PAGE_RIGHT_BLOCK_NUM, BTREE_DELETE_PAGE_PARENT_BLOCK_NUM, BTREE_DELETE_PAGE_META_BLOCK_NUM, }; enum { BTREE_NEWROOT_ORIG_BLOCK_NUM = 0, BTREE_NEWROOT_LEFT_BLOCK_NUM, BTREE_NEWROOT_META_BLOCK_NUM, }; /* * _bt_restore_page -- re-enter all the index tuples on a page * * The page is freshly init'd, and *from (length len) is a copy of what * had been its upper part (pd_upper to pd_special). We assume that the * tuples had been added to the page in item-number order, and therefore * the one with highest item number appears first (lowest on the page). * * NOTE: the way this routine is coded, the rebuilt page will have the items * in correct itemno sequence, but physically the opposite order from the * original, because we insert them in the opposite of itemno order. This * does not matter in any current btree code, but it's something to keep an * eye on. Is it worth changing just on general principles? See also the * notes in btree_xlog_split(). */ void _bt_restore_page(Page page, char* from, int len) { IndexTupleData itupdata; Size itemsz; char* end = from + len; for (; from < end;) { /* Need to copy tuple header due to alignment considerations */ errno_t rc = memcpy_s(&itupdata, sizeof(IndexTupleData), from, sizeof(IndexTupleData)); securec_check(rc, "\0", "\0"); itemsz = IndexTupleDSize(itupdata); itemsz = MAXALIGN(itemsz); if (PageAddItem(page, (Item)from, itemsz, FirstOffsetNumber, false, false) == InvalidOffsetNumber) ereport(PANIC, (errmsg("_bt_restore_page: cannot add item to page"))); from += itemsz; } } void DumpBtreeDeleteInfo(XLogRecPtr lsn, OffsetNumber offsetList[], uint64 offsetNum) { ereport(DEBUG4, (errmodule(MOD_REDO), errcode(ERRCODE_LOG), errmsg("DumpBtreeDeleteInfo: lsn:%X/%X, offsetnum %lu", (uint32)(lsn >> 32), (uint32)lsn, offsetNum))); for (uint64 i = 0; i < offsetNum; ++i) { ereport(DEBUG4, (errmodule(MOD_REDO), errcode(ERRCODE_LOG), errmsg("DumpBtreeDeleteInfo: %lu offset %u", i, offsetList[i]))); } } void btree_restore_meta_operator_page(RedoBufferInfo* metabuf, void* recorddata, Size datalen) { char* ptr = (char*)recorddata; Page metapg = metabuf->pageinfo.page; BTMetaPageData* md = NULL; BTPageOpaqueInternal pageop; xl_btree_metadata* xlrec = NULL; Assert(datalen == sizeof(xl_btree_metadata)); Assert(metabuf->blockinfo.blkno == BTREE_METAPAGE); xlrec = (xl_btree_metadata*)ptr; metapg = metabuf->pageinfo.page; _bt_pageinit(metapg, metabuf->pageinfo.pagesize); md = BTPageGetMeta(metapg); md->btm_magic = BTREE_MAGIC; md->btm_version = BTREE_VERSION; md->btm_root = xlrec->root; md->btm_level = xlrec->level; md->btm_fastroot = xlrec->fastroot; md->btm_fastlevel = xlrec->fastlevel; pageop = (BTPageOpaqueInternal)PageGetSpecialPointer(metapg); pageop->btpo_flags = BTP_META; /* * Set pd_lower just past the end of the metadata. This is not essential * but it makes the page look compressible to xlog.c. */ ((PageHeader)metapg)->pd_lower = ((char*)md + sizeof(BTMetaPageData)) - (char*)metapg; PageSetLSN(metapg, metabuf->lsn); } void btree_xlog_insert_operator_page(RedoBufferInfo* buffer, void* recorddata, void* data, Size datalen) { xl_btree_insert* xlrec = (xl_btree_insert*)recorddata; Page page = buffer->pageinfo.page; char* datapos = (char*)data; if (PageAddItem(page, (Item)datapos, datalen, xlrec->offnum, false, false) == InvalidOffsetNumber) ereport(PANIC, (errmsg("btree_insert_redo: failed to add item"))); PageSetLSN(page, buffer->lsn); } void btree_xlog_split_operator_rightpage( RedoBufferInfo* rbuf, void* recorddata, BlockNumber leftsib, BlockNumber rnext, void* blkdata, Size datalen) { xl_btree_split* xlrec = (xl_btree_split*)recorddata; bool isleaf = (xlrec->level == 0); Page rpage = rbuf->pageinfo.page; char* datapos = (char*)blkdata; BTPageOpaqueInternal ropaque; _bt_pageinit(rpage, rbuf->pageinfo.pagesize); ropaque = (BTPageOpaqueInternal)PageGetSpecialPointer(rpage); ropaque->btpo_prev = leftsib; ropaque->btpo_next = rnext; ropaque->btpo.level = xlrec->level; ropaque->btpo_flags = isleaf ? BTP_LEAF : 0; ropaque->btpo_cycleid = 0; _bt_restore_page(rpage, datapos, (int)datalen); PageSetLSN(rpage, rbuf->lsn); } void btree_xlog_split_operator_nextpage(RedoBufferInfo* buffer, BlockNumber rightsib) { Page page = buffer->pageinfo.page; BTPageOpaqueInternal pageop = (BTPageOpaqueInternal)PageGetSpecialPointer(page); pageop->btpo_prev = rightsib; PageSetLSN(page, buffer->lsn); } void btree_xlog_split_operator_leftpage(RedoBufferInfo* lbuf, void* recorddata, BlockNumber rightsib, bool onleft, void* blkdata, Size datalen, Item input_left_hikey, Size input_left_hikeysz) { xl_btree_split* xlrec = (xl_btree_split*)recorddata; bool isleaf = (xlrec->level == 0); Page lpage = lbuf->pageinfo.page; char* datapos = (char*)blkdata; Item left_hikey = input_left_hikey; Size left_hikeysz = input_left_hikeysz; /* * To retain the same physical order of the tuples that they had, we * initialize a temporary empty page for the left page and add all the * items to that in item number order. This mirrors how _bt_split() * works. It's not strictly required to retain the same physical * order, as long as the items are in the correct item number order, * but it helps debugging. See also _bt_restore_page(), which does * the same for the right page. */ BTPageOpaqueInternal lopaque = (BTPageOpaqueInternal)PageGetSpecialPointer(lpage); OffsetNumber off; Item newitem = NULL; Size newitemsz = 0; Page newlpage; OffsetNumber leftoff; if (onleft) { newitem = (Item)datapos; newitemsz = MAXALIGN(IndexTupleSize(newitem)); datapos += newitemsz; datalen -= newitemsz; } /* Extract left hikey and its size (assuming 16-bit alignment) */ left_hikey = (Item)datapos; left_hikeysz = MAXALIGN(IndexTupleSize(left_hikey)); datapos += left_hikeysz; datalen -= left_hikeysz; Assert(datalen == 0); /* assure that memory is properly allocated, prevent from core dump caused by buffer unpin */ START_CRIT_SECTION(); newlpage = PageGetTempPageCopySpecial(lpage, true); END_CRIT_SECTION(); /* Set high key */ leftoff = P_HIKEY; if (PageAddItem(newlpage, left_hikey, left_hikeysz, P_HIKEY, false, false) == InvalidOffsetNumber) ereport(PANIC, (errmsg("failed to add high key to left page after split"))); leftoff = OffsetNumberNext(leftoff); for (off = P_FIRSTDATAKEY(lopaque); off < xlrec->firstright; off++) { ItemId itemid; Size itemsz; Item item; /* add the new item if it was inserted on left page */ if (onleft && off == xlrec->newitemoff) { if (PageAddItem(newlpage, newitem, newitemsz, leftoff, false, false) == InvalidOffsetNumber) ereport(ERROR, (errcode(ERRCODE_INDEX_CORRUPTED), errmsg("failed to add new item to left page after split"))); leftoff = OffsetNumberNext(leftoff); } itemid = PageGetItemId(lpage, off); itemsz = ItemIdGetLength(itemid); item = PageGetItem(lpage, itemid); if (PageAddItem(newlpage, item, itemsz, leftoff, false, false) == InvalidOffsetNumber) ereport( ERROR, (errcode(ERRCODE_INDEX_CORRUPTED), errmsg("failed to add old item to left page after split"))); leftoff = OffsetNumberNext(leftoff); } /* cope with possibility that newitem goes at the end */ if (onleft && off == xlrec->newitemoff) { if (PageAddItem(newlpage, newitem, newitemsz, leftoff, false, false) == InvalidOffsetNumber) ereport( ERROR, (errcode(ERRCODE_INDEX_CORRUPTED), errmsg("failed to add new item to left page after split"))); leftoff = OffsetNumberNext(leftoff); } PageRestoreTempPage(newlpage, lpage); /* Fix opaque fields */ lopaque = (BTPageOpaqueInternal)PageGetSpecialPointer(lpage); lopaque->btpo_flags = BTP_INCOMPLETE_SPLIT; if (isleaf) { lopaque->btpo_flags |= BTP_LEAF; } lopaque->btpo_next = rightsib; lopaque->btpo_cycleid = 0; PageSetLSN(lpage, lbuf->lsn); } void btree_xlog_vacuum_operator_page(RedoBufferInfo* redobuffer, void* recorddata, void* blkdata, Size len) { Page page = redobuffer->pageinfo.page; char* ptr = (char*)blkdata; BTPageOpaqueInternal opaque; if (len > 0) { OffsetNumber* unused = NULL; OffsetNumber* unend = NULL; unused = (OffsetNumber*)ptr; unend = (OffsetNumber*)((char*)ptr + len); if (module_logging_is_on(MOD_REDO)) { DumpBtreeDeleteInfo(redobuffer->lsn, unused, unend - unused); DumpPageInfo(page, redobuffer->lsn); } if ((unend - unused) > 0) PageIndexMultiDelete(page, unused, unend - unused); } /* * Mark the page as not containing any LP_DEAD items --- see comments in * _bt_delitems_vacuum(). */ opaque = (BTPageOpaqueInternal)PageGetSpecialPointer(page); opaque->btpo_flags &= ~BTP_HAS_GARBAGE; PageSetLSN(page, redobuffer->lsn); if (module_logging_is_on(MOD_REDO)) { DumpPageInfo(page, redobuffer->lsn); } } void btree_xlog_delete_operator_page(RedoBufferInfo* buffer, void* recorddata, Size recorddatalen) { xl_btree_delete* xlrec = (xl_btree_delete*)recorddata; Page page = buffer->pageinfo.page; BTPageOpaqueInternal opaque; if (recorddatalen > SizeOfBtreeDelete) { OffsetNumber* unused = NULL; unused = (OffsetNumber*)((char*)xlrec + SizeOfBtreeDelete); if (module_logging_is_on(MOD_REDO)) { DumpPageInfo(page, buffer->lsn); DumpBtreeDeleteInfo(buffer->lsn, unused, xlrec->nitems); } PageIndexMultiDelete(page, unused, xlrec->nitems); } /* * Mark the page as not containing any LP_DEAD items --- see comments in * _bt_delitems_delete(). */ opaque = (BTPageOpaqueInternal)PageGetSpecialPointer(page); opaque->btpo_flags &= ~BTP_HAS_GARBAGE; PageSetLSN(page, buffer->lsn); if (module_logging_is_on(MOD_REDO)) { DumpPageInfo(page, buffer->lsn); } } void btree_xlog_delete_page_operator_parentpage(RedoBufferInfo* buffer, void* recorddata, uint8 info) { xl_btree_delete_page* xlrec = (xl_btree_delete_page*)recorddata; Page page = buffer->pageinfo.page; OffsetNumber poffset, maxoff; BTPageOpaqueInternal pageop; pageop = (BTPageOpaqueInternal)PageGetSpecialPointer(page); poffset = xlrec->poffset; maxoff = PageGetMaxOffsetNumber(page); if (poffset >= maxoff) { Assert(info == XLOG_BTREE_DELETE_PAGE_HALF); Assert(poffset == P_FIRSTDATAKEY(pageop)); PageIndexTupleDelete(page, poffset); pageop->btpo_flags |= BTP_HALF_DEAD; } else { ItemId itemid; IndexTuple itup; OffsetNumber nextoffset; Assert(info != XLOG_BTREE_DELETE_PAGE_HALF); itemid = PageGetItemId(page, poffset); itup = (IndexTuple)PageGetItem(page, itemid); ItemPointerSet(&(itup->t_tid), xlrec->rightblk, P_HIKEY); nextoffset = OffsetNumberNext(poffset); PageIndexTupleDelete(page, nextoffset); } PageSetLSN(page, buffer->lsn); } void btree_xlog_delete_page_operator_rightpage(RedoBufferInfo* buffer, void* recorddata) { xl_btree_delete_page* xlrec = (xl_btree_delete_page*)recorddata; Page page = buffer->pageinfo.page; BTPageOpaqueInternal pageop; pageop = (BTPageOpaqueInternal)PageGetSpecialPointer(page); pageop->btpo_prev = xlrec->leftblk; PageSetLSN(page, buffer->lsn); } void btree_xlog_delete_page_operator_leftpage(RedoBufferInfo* buffer, void* recorddata) { xl_btree_delete_page* xlrec = (xl_btree_delete_page*)recorddata; Page page = buffer->pageinfo.page; BTPageOpaqueInternal pageop; pageop = (BTPageOpaqueInternal)PageGetSpecialPointer(page); pageop->btpo_next = xlrec->rightblk; PageSetLSN(page, buffer->lsn); } void btree_xlog_delete_page_operator_currentpage(RedoBufferInfo* buffer, void* recorddata) { xl_btree_delete_page* xlrec = (xl_btree_delete_page*)recorddata; Page page = buffer->pageinfo.page; BTPageOpaqueInternal pageop; _bt_pageinit(page, buffer->pageinfo.pagesize); pageop = (BTPageOpaqueInternal)PageGetSpecialPointer(page); pageop->btpo_prev = xlrec->leftblk; pageop->btpo_next = xlrec->rightblk; pageop->btpo_flags = BTP_DELETED; pageop->btpo_cycleid = 0; ((BTPageOpaque)pageop)->xact = xlrec->btpo_xact; PageSetLSN(page, buffer->lsn); } void btree_xlog_newroot_operator_page( RedoBufferInfo* buffer, void* record, void* blkdata, Size len, BlockNumber* downlink) { xl_btree_newroot* xlrec = (xl_btree_newroot*)record; Page page = buffer->pageinfo.page; char* ptr = (char*)blkdata; BTPageOpaqueInternal pageop; _bt_pageinit(page, buffer->pageinfo.pagesize); pageop = (BTPageOpaqueInternal)PageGetSpecialPointer(page); pageop->btpo_flags = BTP_ROOT; pageop->btpo_prev = pageop->btpo_next = P_NONE; pageop->btpo.level = xlrec->level; if (xlrec->level == 0) { pageop->btpo_flags |= BTP_LEAF; } pageop->btpo_cycleid = 0; if (xlrec->level > 0) { _bt_restore_page(page, ptr, len); } PageSetLSN(page, buffer->lsn); } void btree_xlog_clear_incomplete_split(RedoBufferInfo* buffer) { Page page = buffer->pageinfo.page; BTPageOpaqueInternal pageop = (BTPageOpaqueInternal)PageGetSpecialPointer(page); Assert(P_INCOMPLETE_SPLIT(pageop)); pageop->btpo_flags &= ~BTP_INCOMPLETE_SPLIT; PageSetLSN(page, buffer->lsn); } XLogRecParseState* btree_xlog_insert_parse_block(XLogReaderState* record, uint32* blocknum) { uint8 info = XLogRecGetInfo(record) & ~XLR_INFO_MASK; XLogRecParseState* recordstatehead = NULL; XLogRecParseState* blockstate = NULL; *blocknum = 1; XLogParseBufferAllocListFunc(record, &recordstatehead, NULL); if (recordstatehead == NULL) { return NULL; } XLogRecSetBlockDataState(record, BTREE_INSERT_ORIG_BLOCK_NUM, recordstatehead); if (info != XLOG_BTREE_INSERT_LEAF) { (*blocknum)++; XLogParseBufferAllocListFunc(record, &blockstate, recordstatehead); if (blockstate == NULL) { return NULL; } XLogRecSetBlockDataState(record, BTREE_INSERT_CHILD_BLOCK_NUM, blockstate); } if (info == XLOG_BTREE_INSERT_META) { (*blocknum)++; XLogParseBufferAllocListFunc(record, &blockstate, recordstatehead); if (blockstate == NULL) { return NULL; } XLogRecSetBlockDataState(record, BTREE_INSERT_META_BLOCK_NUM, blockstate); } return recordstatehead; } static XLogRecParseState* btree_xlog_split_parse_block(XLogReaderState* record, uint32* blocknum) { xl_btree_split* xlrec = (xl_btree_split*)XLogRecGetData(record); bool isleaf = (xlrec->level == 0); BlockNumber leftsib; BlockNumber rightsib; BlockNumber rnext; XLogRecParseState* recordstatehead = NULL; XLogRecParseState* blockstate = NULL; XLogRecGetBlockTag(record, BTREE_SPLIT_LEFT_BLOCK_NUM, NULL, NULL, &leftsib); XLogRecGetBlockTag(record, BTREE_SPLIT_RIGHT_BLOCK_NUM, NULL, NULL, &rightsib); if (!XLogRecGetBlockTag(record, BTREE_SPLIT_RIGHTNEXT_BLOCK_NUM, NULL, NULL, &rnext)) rnext = P_NONE; *blocknum = 1; XLogParseBufferAllocListFunc(record, &recordstatehead, NULL); if (recordstatehead == NULL) { return NULL; } XLogRecSetBlockDataState(record, BTREE_SPLIT_LEFT_BLOCK_NUM, recordstatehead); XLogRecSetAuxiBlkNumState(&recordstatehead->blockparse.extra_rec.blockdatarec, rightsib, InvalidForkNumber); (*blocknum)++; XLogParseBufferAllocListFunc(record, &blockstate, recordstatehead); if (blockstate == NULL) { return NULL; } XLogRecSetBlockDataState(record, BTREE_SPLIT_RIGHT_BLOCK_NUM, blockstate); XLogRecSetAuxiBlkNumState(&blockstate->blockparse.extra_rec.blockdatarec, rnext, leftsib); if (rnext != P_NONE) { (*blocknum)++; XLogParseBufferAllocListFunc(record, &blockstate, recordstatehead); if (blockstate == NULL) { return NULL; } XLogRecSetBlockDataState(record, BTREE_SPLIT_RIGHTNEXT_BLOCK_NUM, blockstate); XLogRecSetAuxiBlkNumState(&blockstate->blockparse.extra_rec.blockdatarec, rightsib, InvalidForkNumber); } if (!isleaf) { (*blocknum)++; XLogParseBufferAllocListFunc(record, &blockstate, recordstatehead); if (blockstate == NULL) { return NULL; } XLogRecSetBlockDataState(record, BTREE_SPLIT_CHILD_BLOCK_NUM, blockstate); } return recordstatehead; } static XLogRecParseState* btree_xlog_vacuum_parse_block(XLogReaderState* record, uint32* blocknum) { XLogRecParseState* recordstatehead = NULL; XLogRecParseState* blockstate = NULL; *blocknum = 1; XLogParseBufferAllocListFunc(record, &recordstatehead, NULL); if (recordstatehead == NULL) { return NULL; } XLogRecSetBlockDataState(record, BTREE_VACUUM_ORIG_BLOCK_NUM, recordstatehead); if (SUPPORT_HOT_STANDBY) { BlockNumber thisblkno; RelFileNode thisrnode; xl_btree_vacuum* xlrec = (xl_btree_vacuum*)XLogRecGetData(record); XLogRecGetBlockTag(record, BTREE_VACUUM_ORIG_BLOCK_NUM, &thisrnode, NULL, &thisblkno); if ((xlrec->lastBlockVacuumed + 1) < thisblkno) { (*blocknum)++; XLogParseBufferAllocListFunc(record, &blockstate, recordstatehead); if (blockstate == NULL) { return NULL; } XLogRecSetBlockCommonState( record, BLOCK_DATA_VACUUM_PIN_TYPE, MAIN_FORKNUM, thisblkno, &thisrnode, blockstate); XLogRecSetPinVacuumState(&blockstate->blockparse.extra_rec.blockvacuumpin, xlrec->lastBlockVacuumed); } } return recordstatehead; } static XLogRecParseState* btree_xlog_delete_parse_block(XLogReaderState* record, uint32* blocknum) { XLogRecParseState* recordstatehead = NULL; *blocknum = 1; XLogParseBufferAllocListFunc(record, &recordstatehead, NULL); if (recordstatehead == NULL) { return NULL; } XLogRecSetBlockDataState(record, BTREE_DELETE_ORIG_BLOCK_NUM, recordstatehead); /* for hot standby, need to reslove the conflict */ { /* wait for syn with pg > 9.6 */ } return recordstatehead; } static XLogRecParseState* btree_xlog_delete_page_parse_block(XLogReaderState* record, uint32* blocknum) { uint8 info = XLogRecGetInfo(record) & ~XLR_INFO_MASK; xl_btree_delete_page* xlrec = (xl_btree_delete_page*)XLogRecGetData(record); XLogRecParseState* recordstatehead = NULL; XLogRecParseState* blockstate = NULL; *blocknum = 1; XLogParseBufferAllocListFunc(record, &recordstatehead, NULL); if (recordstatehead == NULL) { return NULL; } XLogRecSetBlockDataState(record, BTREE_DELETE_PAGE_TARGET_BLOCK_NUM, recordstatehead); (*blocknum)++; XLogParseBufferAllocListFunc(record, &blockstate, recordstatehead); if (blockstate == NULL) { return NULL; } XLogRecSetBlockDataState(record, BTREE_DELETE_PAGE_PARENT_BLOCK_NUM, blockstate); (*blocknum)++; XLogParseBufferAllocListFunc(record, &blockstate, recordstatehead); if (blockstate == NULL) { return NULL; } XLogRecSetBlockDataState(record, BTREE_DELETE_PAGE_RIGHT_BLOCK_NUM, blockstate); if (xlrec->leftblk != P_NONE) { (*blocknum)++; XLogParseBufferAllocListFunc(record, &blockstate, recordstatehead); if (blockstate == NULL) { return NULL; } XLogRecSetBlockDataState(record, BTREE_DELETE_PAGE_LEFT_BLOCK_NUM, blockstate); } /* Update metapage if needed */ if (info == XLOG_BTREE_DELETE_PAGE_META) { (*blocknum)++; XLogParseBufferAllocListFunc(record, &blockstate, recordstatehead); if (blockstate == NULL) { return NULL; } XLogRecSetBlockDataState(record, BTREE_DELETE_PAGE_META_BLOCK_NUM, blockstate); } /* forget incomplete action */ if (info == XLOG_BTREE_DELETE_PAGE_HALF) { /* log incomplete action */ } return recordstatehead; } static XLogRecParseState* btree_xlog_newroot_parse_block(XLogReaderState* record, uint32* blocknum) { xl_btree_newroot* xlrec = (xl_btree_newroot*)XLogRecGetData(record); XLogRecParseState* recordstatehead = NULL; XLogRecParseState* blockstate = NULL; *blocknum = 1; XLogParseBufferAllocListFunc(record, &recordstatehead, NULL); if (recordstatehead == NULL) { return NULL; } XLogRecSetBlockDataState(record, BTREE_NEWROOT_ORIG_BLOCK_NUM, recordstatehead); if (xlrec->level > 0) { (*blocknum)++; XLogParseBufferAllocListFunc(record, &blockstate, recordstatehead); if (blockstate == NULL) { return NULL; } XLogRecSetBlockDataState(record, BTREE_NEWROOT_LEFT_BLOCK_NUM, blockstate); } (*blocknum)++; XLogParseBufferAllocListFunc(record, &blockstate, recordstatehead); if (blockstate == NULL) { return NULL; } XLogRecSetBlockDataState(record, BTREE_NEWROOT_META_BLOCK_NUM, blockstate); return recordstatehead; } static XLogRecParseState* btree_xlog_reuse_page_parse_block(XLogReaderState* record, uint32* blocknum) { XLogRecParseState* recordstatehead = NULL; xl_btree_reuse_page* xlrec = (xl_btree_reuse_page*)XLogRecGetData(record); *blocknum = 0; if (SUPPORT_HOT_STANDBY) { (*blocknum)++; XLogParseBufferAllocListFunc(record, &recordstatehead, NULL); if (recordstatehead == NULL) { return NULL; } RelFileNode rnode; RelFileNodeCopy(rnode, xlrec->node, XLogRecGetBucketId(record)); XLogRecSetBlockCommonState( record, BLOCK_DATA_INVALIDMSG_TYPE, InvalidForkNumber, InvalidBlockNumber, &rnode, recordstatehead); XLogRecSetInvalidMsgState(&recordstatehead->blockparse.extra_rec.blockinvalidmsg, xlrec->latestRemovedXid); } return recordstatehead; } XLogRecParseState* btree_redo_parse_to_block(XLogReaderState* record, uint32* blocknum) { uint8 info = XLogRecGetInfo(record) & ~XLR_INFO_MASK; XLogRecParseState* recordblockstate = NULL; *blocknum = 0; switch (info) { case XLOG_BTREE_INSERT_LEAF: case XLOG_BTREE_INSERT_UPPER: case XLOG_BTREE_INSERT_META: recordblockstate = btree_xlog_insert_parse_block(record, blocknum); break; case XLOG_BTREE_SPLIT_L: case XLOG_BTREE_SPLIT_R: case XLOG_BTREE_SPLIT_L_ROOT: case XLOG_BTREE_SPLIT_R_ROOT: recordblockstate = btree_xlog_split_parse_block(record, blocknum); break; case XLOG_BTREE_VACUUM: recordblockstate = btree_xlog_vacuum_parse_block(record, blocknum); break; case XLOG_BTREE_DELETE: recordblockstate = btree_xlog_delete_parse_block(record, blocknum); break; case XLOG_BTREE_DELETE_PAGE: case XLOG_BTREE_DELETE_PAGE_META: case XLOG_BTREE_DELETE_PAGE_HALF: recordblockstate = btree_xlog_delete_page_parse_block(record, blocknum); break; case XLOG_BTREE_NEWROOT: recordblockstate = btree_xlog_newroot_parse_block(record, blocknum); break; case XLOG_BTREE_REUSE_PAGE: recordblockstate = btree_xlog_reuse_page_parse_block(record, blocknum); break; default: ereport(PANIC, (errmsg("btree_redo_parse_to_block: unknown op code %u", info))); } return recordblockstate; } static void btree_xlog_insert_block( XLogBlockHead* blockhead, XLogBlockDataParse* blockdatarec, RedoBufferInfo* bufferinfo) { XLogBlockDataParse* datadecode = blockdatarec; Size blkdatalen; char* blkdata = NULL; blkdata = XLogBlockDataGetBlockData(datadecode, &blkdatalen); if (XLogBlockDataGetBlockId(datadecode) == BTREE_INSERT_ORIG_BLOCK_NUM) { XLogRedoAction action; action = XLogCheckBlockDataRedoAction(datadecode, bufferinfo); if (action == BLK_NEEDS_REDO) { Assert(blkdata != NULL); char* maindata = XLogBlockDataGetMainData(datadecode, NULL); btree_xlog_insert_operator_page(bufferinfo, (void*)maindata, (void*)blkdata, blkdatalen); MakeRedoBufferDirty(bufferinfo); } } else if (XLogBlockDataGetBlockId(datadecode) == BTREE_INSERT_CHILD_BLOCK_NUM) { /* child */ XLogRedoAction action; action = XLogCheckBlockDataRedoAction(datadecode, bufferinfo); if (action == BLK_NEEDS_REDO) { btree_xlog_clear_incomplete_split(bufferinfo); MakeRedoBufferDirty(bufferinfo); } } else { /* meta */ btree_restore_meta_operator_page(bufferinfo, (void*)blkdata, blkdatalen); MakeRedoBufferDirty(bufferinfo); } } static void btree_xlog_split_block( XLogBlockHead* blockhead, XLogBlockDataParse* blockdatarec, RedoBufferInfo* bufferinfo) { uint8 info = XLogBlockHeadGetInfo(blockhead) & ~XLR_INFO_MASK; XLogBlockDataParse* datadecode = blockdatarec; if (XLogBlockDataGetBlockId(datadecode) == BTREE_SPLIT_RIGHT_BLOCK_NUM) { /* right page */ BlockNumber leftsib; BlockNumber rnext; Size blkdatalen; char* blkdata = NULL; char* maindata = XLogBlockDataGetMainData(datadecode, NULL); blkdata = XLogBlockDataGetBlockData(datadecode, &blkdatalen); rnext = XLogBlockDataGetAuxiBlock1(datadecode); leftsib = XLogBlockDataGetAuxiBlock2(datadecode); btree_xlog_split_operator_rightpage(bufferinfo, (void*)maindata, leftsib, rnext, (void*)blkdata, blkdatalen); MakeRedoBufferDirty(bufferinfo); } else { XLogRedoAction action; action = XLogCheckBlockDataRedoAction(datadecode, bufferinfo); if (action == BLK_NEEDS_REDO) { BlockNumber rightsib; rightsib = XLogBlockDataGetAuxiBlock1(datadecode); if (XLogBlockDataGetBlockId(datadecode) == BTREE_SPLIT_LEFT_BLOCK_NUM) { /* left page */ Size blkdatalen; char* blkdata = NULL; char* maindata = XLogBlockDataGetMainData(datadecode, NULL); bool onleft = ((info == XLOG_BTREE_SPLIT_L) || (info == XLOG_BTREE_SPLIT_L_ROOT)); blkdata = XLogBlockDataGetBlockData(datadecode, &blkdatalen); btree_xlog_split_operator_leftpage( bufferinfo, (void*)maindata, rightsib, onleft, (void*)blkdata, blkdatalen, NULL, 0); } else if (XLogBlockDataGetBlockId(datadecode) == BTREE_SPLIT_RIGHTNEXT_BLOCK_NUM) { /* right next */ btree_xlog_split_operator_nextpage(bufferinfo, rightsib); } else { /* child */ btree_xlog_clear_incomplete_split(bufferinfo); } MakeRedoBufferDirty(bufferinfo); } } } static void btree_xlog_vacuum_block( XLogBlockHead* blockhead, XLogBlockDataParse* blockdatarec, RedoBufferInfo* bufferinfo) { XLogBlockDataParse* datadecode = blockdatarec; XLogRedoAction action; action = XLogCheckBlockDataRedoAction(datadecode, bufferinfo); if (action == BLK_NEEDS_REDO) { char* maindata = XLogBlockDataGetMainData(datadecode, NULL); Size blkdatalen = 0; char* blkdata = NULL; blkdata = XLogBlockDataGetBlockData(datadecode, &blkdatalen); btree_xlog_vacuum_operator_page(bufferinfo, (void*)maindata, (void*)blkdata, blkdatalen); MakeRedoBufferDirty(bufferinfo); } } static void btree_xlog_delete_block( XLogBlockHead* blockhead, XLogBlockDataParse* blockdatarec, RedoBufferInfo* bufferinfo) { XLogBlockDataParse* datadecode = blockdatarec; XLogRedoAction action; action = XLogCheckBlockDataRedoAction(datadecode, bufferinfo); if (action == BLK_NEEDS_REDO) { Size maindatalen; char* maindata = XLogBlockDataGetMainData(datadecode, &maindatalen); btree_xlog_delete_operator_page(bufferinfo, (void*)maindata, maindatalen); MakeRedoBufferDirty(bufferinfo); } } static void btree_xlog_delete_page_block( XLogBlockHead* blockhead, XLogBlockDataParse* blockdatarec, RedoBufferInfo* bufferinfo) { uint8 info = XLogBlockHeadGetInfo(blockhead) & ~XLR_INFO_MASK; XLogBlockDataParse* datadecode = blockdatarec; uint8 block_id = XLogBlockDataGetBlockId(datadecode); char* maindata = XLogBlockDataGetMainData(datadecode, NULL); if (block_id == BTREE_DELETE_PAGE_TARGET_BLOCK_NUM) { btree_xlog_delete_page_operator_currentpage(bufferinfo, (void*)maindata); MakeRedoBufferDirty(bufferinfo); } else if (block_id == BTREE_DELETE_PAGE_META_BLOCK_NUM) { Size blkdatalen; char* blkdata = NULL; blkdata = XLogBlockDataGetBlockData(datadecode, &blkdatalen); btree_restore_meta_operator_page(bufferinfo, (void*)blkdata, blkdatalen); MakeRedoBufferDirty(bufferinfo); } else { XLogRedoAction action; action = XLogCheckBlockDataRedoAction(datadecode, bufferinfo); if (action == BLK_NEEDS_REDO) { if (block_id == BTREE_DELETE_PAGE_PARENT_BLOCK_NUM) { btree_xlog_delete_page_operator_parentpage(bufferinfo, (void*)maindata, info); } else if (block_id == BTREE_DELETE_PAGE_RIGHT_BLOCK_NUM) { btree_xlog_delete_page_operator_rightpage(bufferinfo, (void*)maindata); } else { btree_xlog_delete_page_operator_leftpage(bufferinfo, (void*)maindata); } MakeRedoBufferDirty(bufferinfo); } } } static void btree_xlog_newroot_block( XLogBlockHead* blockhead, XLogBlockDataParse* blockdatarec, RedoBufferInfo* bufferinfo) { XLogBlockDataParse* datadecode = blockdatarec; Size blkdatalen; char* blkdata = NULL; BlockNumber downlink = 0; blkdata = XLogBlockDataGetBlockData(datadecode, &blkdatalen); if (XLogBlockDataGetBlockId(datadecode) == BTREE_NEWROOT_ORIG_BLOCK_NUM) { char* maindata = XLogBlockDataGetMainData(datadecode, NULL); btree_xlog_newroot_operator_page(bufferinfo, (void*)maindata, (void*)blkdata, blkdatalen, &downlink); } else if (XLogBlockDataGetBlockId(datadecode) == BTREE_NEWROOT_LEFT_BLOCK_NUM) { XLogRedoAction action; action = XLogCheckBlockDataRedoAction(datadecode, bufferinfo); if (action == BLK_NEEDS_REDO) { btree_xlog_clear_incomplete_split(bufferinfo); } } else { btree_restore_meta_operator_page(bufferinfo, (void*)blkdata, blkdatalen); } MakeRedoBufferDirty(bufferinfo); } void btree_redo_data_block(XLogBlockHead* blockhead, XLogBlockDataParse* blockdatarec, RedoBufferInfo* bufferinfo) { uint8 info = XLogBlockHeadGetInfo(blockhead) & ~XLR_INFO_MASK; switch (info) { case XLOG_BTREE_INSERT_LEAF: case XLOG_BTREE_INSERT_UPPER: case XLOG_BTREE_INSERT_META: btree_xlog_insert_block(blockhead, blockdatarec, bufferinfo); break; case XLOG_BTREE_SPLIT_L: case XLOG_BTREE_SPLIT_R: case XLOG_BTREE_SPLIT_L_ROOT: case XLOG_BTREE_SPLIT_R_ROOT: btree_xlog_split_block(blockhead, blockdatarec, bufferinfo); break; case XLOG_BTREE_VACUUM: btree_xlog_vacuum_block(blockhead, blockdatarec, bufferinfo); break; case XLOG_BTREE_DELETE: btree_xlog_delete_block(blockhead, blockdatarec, bufferinfo); break; case XLOG_BTREE_DELETE_PAGE: case XLOG_BTREE_DELETE_PAGE_META: case XLOG_BTREE_DELETE_PAGE_HALF: btree_xlog_delete_page_block(blockhead, blockdatarec, bufferinfo); break; case XLOG_BTREE_NEWROOT: btree_xlog_newroot_block(blockhead, blockdatarec, bufferinfo); break; default: ereport(PANIC, (errmsg("btree_redo_block: unknown op code %u", info))); } } 10-100 /// See ../../License.txt for license info. #pragma once #include "../Core.hpp" namespace HANDYMATH_NS { class IProjection { public: virtual Matrix4 Matrix(float zNear, float zFar) const = 0; }; }dservin/brlcadsrc/other/ext/gdal/ogr/ogr_srs_panorama.cpp /****************************************************************************** * * Project: OpenGIS Simple Features Reference Implementation * Purpose: OGRSpatialReference translation to/from "Panorama" GIS * georeferencing information (also know as GIS "Integration"). * Author: , * ****************************************************************************** * Copyright (c) 2005, <> * Copyright (c) 2008-2012, * * 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 "ogr_spatialref.h" #include "cpl_conv.h" #include "cpl_csv.h" #include "ogr_p.h" CPL_CVSID("$Id$"); static const double TO_DEGREES = 57.2957795130823208766; static const double TO_RADIANS = 0.017453292519943295769; // XXX: this macro computes zone number from the central meridian parameter. // Note, that "Panorama" parameters are set in radians. // In degrees it means formula: // // zone = (central_meridian + 3) / 6 // static int TO_ZONE( double x ) { return static_cast((x + 0.05235987755982989) / 0.1047197551196597 + 0.5); } /************************************************************************/ /* "Panorama" projection codes. */ /************************************************************************/ static const long PAN_PROJ_NONE = -1L; static const long PAN_PROJ_TM = 1L; // Gauss-Kruger (Transverse Mercator) static const long PAN_PROJ_LCC = 2L; // Lambert Conformal Conic 2SP static const long PAN_PROJ_STEREO = 5L; // Stereographic static const long PAN_PROJ_AE = 6L; // Azimuthal Equidistant (Postel) static const long PAN_PROJ_MERCAT = 8L; // Mercator static const long PAN_PROJ_POLYC = 10L; // Polyconic static const long PAN_PROJ_PS = 13L; // Polar Stereographic static const long PAN_PROJ_GNOMON = 15L; // Gnomonic static const long PAN_PROJ_UTM = 17L; // Universal Transverse Mercator (UTM) static const long PAN_PROJ_WAG1 = 18L; // Wagner I (Kavraisky VI) static const long PAN_PROJ_MOLL = 19L; // Mollweide static const long PAN_PROJ_EC = 20L; // Equidistant Conic static const long PAN_PROJ_LAEA = 24L; // Lambert Azimuthal Equal Area static const long PAN_PROJ_EQC = 27L; // Equirectangular static const long PAN_PROJ_CEA = 28L; // Cylindrical Equal Area (Lambert) static const long PAN_PROJ_IMWP = 29L; // International Map of the World Polyconic static const long PAN_PROJ_MILLER = 34L; // Miller /************************************************************************/ /* "Panorama" datum codes. */ /************************************************************************/ static const long PAN_DATUM_NONE = -1L; static const long PAN_DATUM_PULKOVO42 = 1L; // Pulkovo 1942 static const long PAN_DATUM_WGS84 = 2L; // WGS84 /************************************************************************/ /* "Panorama" ellipsoid codes. */ /************************************************************************/ static const long PAN_ELLIPSOID_NONE = -1L; static const long PAN_ELLIPSOID_KRASSOVSKY = 1L; // Krassovsky, 1940 // static const long PAN_ELLIPSOID_WGS72 = 2L; // WGS, 1972 // static const long PAN_ELLIPSOID_INT1924 = 3L; // International, 1924 (Hayford, 1909) // static const long PAN_ELLIPSOID_CLARCKE1880 = 4L; // Clarke, 1880 // static const long PAN_ELLIPSOID_CLARCKE1866 = 5L; // Clarke, 1866 (NAD1927) // static const long PAN_ELLIPSOID_EVEREST1830 = 6L; // Everest, 1830 // static const long PAN_ELLIPSOID_BESSEL1841 = 7L; // Bessel, 1841 // static const long PAN_ELLIPSOID_AIRY1830 = 8L; // Airy, 1830 static const long PAN_ELLIPSOID_WGS84 = 9L; // WGS, 1984 (GPS) /************************************************************************/ /* Correspondence between "Panorama" and EPSG datum codes. */ /************************************************************************/ static const int aoDatums[] = { 0, 4284, // Pulkovo, 1942 4326, // WGS, 1984, 4277, // OSGB 1936 (British National Grid) 0, 0, 0, 0, 0, 4200 // Pulkovo, 1995 }; #define NUMBER_OF_DATUMS (long)(sizeof(aoDatums)/sizeof(aoDatums[0])) /************************************************************************/ /* Correspondence between "Panorama" and EPSG ellipsoid codes. */ /************************************************************************/ static const int aoEllips[] = { 0, 7024, // Krassovsky, 1940 7043, // WGS, 1972 7022, // International, 1924 (Hayford, 1909) 7034, // Clarke, 1880 7008, // Clarke, 1866 (NAD1927) 7015, // Everest, 1830 7004, // Bessel, 1841 7001, // Airy, 1830 7030, // WGS, 1984 (GPS) 0, // FIXME: PZ90.02 7019, // GRS, 1980 (NAD1983) 7022, // International, 1924 (Hayford, 1909) XXX? 7036, // South American, 1969 7021, // Indonesian, 1974 7020, // Helmert 1906 0, // FIXME: Fisher 1960 0, // FIXME: Fisher 1968 0, // FIXME: Haff 1960 7042, // Everest, 1830 7003 // Australian National, 1965 }; static const int NUMBER_OF_ELLIPSOIDS = static_cast(sizeof(aoEllips)/sizeof(aoEllips[0])); /************************************************************************/ /* OSRImportFromPanorama() */ /************************************************************************/ /** Import coordinate system from "Panorama" GIS projection definition. * * See OGRSpatialReference::importFromPanorama() */ OGRErr OSRImportFromPanorama( OGRSpatialReferenceH hSRS, long iProjSys, long iDatum, long iEllips, double *padfPrjParams ) { VALIDATE_POINTER1( hSRS, "OSRImportFromPanorama", OGRERR_FAILURE ); return reinterpret_cast(hSRS)-> importFromPanorama( iProjSys, iDatum, iEllips, padfPrjParams ); } /************************************************************************/ /* importFromPanorama() */ /************************************************************************/ /** * Import coordinate system from "Panorama" GIS projection definition. * * This method will import projection definition in style, used by * "Panorama" GIS. * * This function is the equivalent of the C function OSRImportFromPanorama(). * * @param iProjSys Input projection system code, used in GIS "Panorama". * *

Supported Projections

*
 *      1:  Gauss-Kruger (Transverse Mercator)
 *      2:  Lambert Conformal Conic 2SP
 *      5:  Stereographic
 *      6:  Azimuthal Equidistant (Postel)
 *      8:  Mercator
 *      10: Polyconic
 *      13: Polar Stereographic
 *      15: Gnomonic
 *      17: Universal Transverse Mercator (UTM)
 *      18: Wagner I (Kavraisky VI)
 *      19: Mollweide
 *      20: Equidistant Conic
 *      24: Lambert Azimuthal Equal Area
 *      27: Equirectangular
 *      28: Cylindrical Equal Area (Lambert)
 *      29: International Map of the World Polyconic
 * 
* * @param iDatum Input coordinate system. * *

Supported Datums

*
 *       1: Pulkovo, 1942
 *       2: WGS, 1984
 *       3: OSGB 1936 (British National Grid)
 *       9: Pulkovo, 1995
 * 
* * @param iEllips Input spheroid. * *

Supported Spheroids

*
 *       1: Krassovsky, 1940
 *       2: WGS, 1972
 *       3: International, 1924 (Hayford, 1909)
 *       4: Clarke, 1880
 *       5: Clarke, 1866 (NAD1927)
 *       6: Everest, 1830
 *       7: Bessel, 1841
 *       8: Airy, 1830
 *       9: WGS, 1984 (GPS)
 * 
* * @param padfPrjParams Array of 8 coordinate system parameters: * *
 *      [0]  Latitude of the first standard parallel (radians)
 *      [1]  Latitude of the second standard parallel (radians)
 *      [2]  Latitude of center of projection (radians)
 *      [3]  Longitude of center of projection (radians)
 *      [4]  Scaling factor
 *      [5]  False Easting
 *      [6]  False Northing
 *      [7]  Zone number
 * 
* * Particular projection uses different parameters, unused ones may be set to * zero. If NULL supplied instead of array pointer default values will be used * (i.e., zeroes). * * @return OGRERR_NONE on success or an error code in case of failure. */ OGRErr OGRSpatialReference::importFromPanorama( long iProjSys, long iDatum, long iEllips, double *padfPrjParams ) { Clear(); /* -------------------------------------------------------------------- */ /* Use safe defaults if projection parameters are not supplied. */ /* -------------------------------------------------------------------- */ bool bProjAllocated = false; if( padfPrjParams == NULL ) { padfPrjParams = static_cast(CPLMalloc(8 * sizeof(double))); if( !padfPrjParams ) return OGRERR_NOT_ENOUGH_MEMORY; for( int i = 0; i < 7; i++ ) padfPrjParams[i] = 0.0; bProjAllocated = true; } /* -------------------------------------------------------------------- */ /* Operate on the basis of the projection code. */ /* -------------------------------------------------------------------- */ switch( iProjSys ) { case PAN_PROJ_NONE: break; case PAN_PROJ_UTM: { const int nZone = padfPrjParams[7] == 0.0 ? TO_ZONE(padfPrjParams[3]) : static_cast(padfPrjParams[7]); // XXX: no way to determine south hemisphere. Always assume // northern hemisphere. SetUTM( nZone, TRUE ); } break; case PAN_PROJ_WAG1: SetWagner( 1, 0.0, padfPrjParams[5], padfPrjParams[6] ); break; case PAN_PROJ_MERCAT: SetMercator( TO_DEGREES * padfPrjParams[0], TO_DEGREES * padfPrjParams[3], padfPrjParams[4], padfPrjParams[5], padfPrjParams[6] ); break; case PAN_PROJ_PS: SetPS( TO_DEGREES * padfPrjParams[2], TO_DEGREES * padfPrjParams[3], padfPrjParams[4], padfPrjParams[5], padfPrjParams[6] ); break; case PAN_PROJ_POLYC: SetPolyconic( TO_DEGREES * padfPrjParams[2], TO_DEGREES * padfPrjParams[3], padfPrjParams[5], padfPrjParams[6] ); break; case PAN_PROJ_EC: SetEC( TO_DEGREES * padfPrjParams[0], TO_DEGREES * padfPrjParams[1], TO_DEGREES * padfPrjParams[2], TO_DEGREES * padfPrjParams[3], padfPrjParams[5], padfPrjParams[6] ); break; case PAN_PROJ_LCC: SetLCC( TO_DEGREES * padfPrjParams[0], TO_DEGREES * padfPrjParams[1], TO_DEGREES * padfPrjParams[2], TO_DEGREES * padfPrjParams[3], padfPrjParams[5], padfPrjParams[6] ); break; case PAN_PROJ_TM: { // XXX: we need zone number to compute false easting // parameter, because usually it is not contained in the // "Panorama" projection definition. // FIXME: what to do with negative values? int nZone = 0; double dfCenterLong = 0.0; if( padfPrjParams[7] == 0.0 ) { nZone = TO_ZONE(padfPrjParams[3]); dfCenterLong = TO_DEGREES * padfPrjParams[3]; } else { nZone = static_cast(padfPrjParams[7]); dfCenterLong = 6.0 * nZone - 3.0; } padfPrjParams[5] = nZone * 1000000.0 + 500000.0; padfPrjParams[4] = 1.0; SetTM( TO_DEGREES * padfPrjParams[2], dfCenterLong, padfPrjParams[4], padfPrjParams[5], padfPrjParams[6] ); } break; case PAN_PROJ_STEREO: SetStereographic( TO_DEGREES * padfPrjParams[2], TO_DEGREES * padfPrjParams[3], padfPrjParams[4], padfPrjParams[5], padfPrjParams[6] ); break; case PAN_PROJ_AE: SetAE( TO_DEGREES * padfPrjParams[0], TO_DEGREES * padfPrjParams[3], padfPrjParams[5], padfPrjParams[6] ); break; case PAN_PROJ_GNOMON: SetGnomonic( TO_DEGREES * padfPrjParams[2], TO_DEGREES * padfPrjParams[3], padfPrjParams[5], padfPrjParams[6] ); break; case PAN_PROJ_MOLL: SetMollweide( TO_DEGREES * padfPrjParams[3], padfPrjParams[5], padfPrjParams[6] ); break; case PAN_PROJ_LAEA: SetLAEA( TO_DEGREES * padfPrjParams[0], TO_DEGREES * padfPrjParams[3], padfPrjParams[5], padfPrjParams[6] ); break; case PAN_PROJ_EQC: SetEquirectangular( TO_DEGREES * padfPrjParams[0], TO_DEGREES * padfPrjParams[3], padfPrjParams[5], padfPrjParams[6] ); break; case PAN_PROJ_CEA: SetCEA( TO_DEGREES * padfPrjParams[0], TO_DEGREES * padfPrjParams[3], padfPrjParams[5], padfPrjParams[6] ); break; case PAN_PROJ_IMWP: SetIWMPolyconic( TO_DEGREES * padfPrjParams[0], TO_DEGREES * padfPrjParams[1], TO_DEGREES * padfPrjParams[3], padfPrjParams[5], padfPrjParams[6] ); break; case PAN_PROJ_MILLER: SetMC(TO_DEGREES * padfPrjParams[5], TO_DEGREES * padfPrjParams[4], padfPrjParams[6], padfPrjParams[7]); break; default: CPLDebug( "OSR_Panorama", "Unsupported projection: %ld", iProjSys ); SetLocalCS( CPLString().Printf("\"Panorama\" projection number %ld", iProjSys) ); break; } /* -------------------------------------------------------------------- */ /* Try to translate the datum/spheroid. */ /* -------------------------------------------------------------------- */ if( !IsLocal() ) { if( iDatum > 0 && iDatum < NUMBER_OF_DATUMS && aoDatums[iDatum] ) { OGRSpatialReference oGCS; oGCS.importFromEPSG( aoDatums[iDatum] ); CopyGeogCSFrom( &oGCS ); } else if( iEllips > 0 && iEllips < NUMBER_OF_ELLIPSOIDS && aoEllips[iEllips] ) { char *pszName = NULL; double dfSemiMajor = 0.0; double dfInvFlattening = 0.0; if( OSRGetEllipsoidInfo( aoEllips[iEllips], &pszName, &dfSemiMajor, &dfInvFlattening ) == OGRERR_NONE ) { SetGeogCS( CPLString().Printf( "Unknown datum based upon the %s ellipsoid", pszName ), CPLString().Printf( "Not specified (based on %s spheroid)", pszName ), pszName, dfSemiMajor, dfInvFlattening, NULL, 0.0, NULL, 0.0 ); SetAuthority( "SPHEROID", "EPSG", aoEllips[iEllips] ); } else { CPLError( CE_Warning, CPLE_AppDefined, "Failed to lookup ellipsoid code %ld, likely due to " "missing GDAL gcs.csv " "file. Falling back to use Pulkovo 42.", iEllips ); SetWellKnownGeogCS( "EPSG:4284" ); } CPLFree( pszName ); } else { CPLError( CE_Warning, CPLE_AppDefined, "Wrong datum code %ld. Supported datums are 1--%ld " "only. Falling back to use Pulkovo 42.", iDatum, NUMBER_OF_DATUMS - 1 ); SetWellKnownGeogCS( "EPSG:4284" ); } } /* -------------------------------------------------------------------- */ /* Grid units translation */ /* -------------------------------------------------------------------- */ if( IsLocal() || IsProjected() ) SetLinearUnits( SRS_UL_METER, 1.0 ); FixupOrdering(); if( bProjAllocated && padfPrjParams ) CPLFree( padfPrjParams ); return OGRERR_NONE; } /************************************************************************/ /* OSRExportToPanorama() */ /************************************************************************/ /** Export coordinate system in "Panorama" GIS projection definition. * * See OGRSpatialReference::exportToPanorama() */ OGRErr OSRExportToPanorama( OGRSpatialReferenceH hSRS, long *piProjSys, long *piDatum, long *piEllips, long *piZone, double *padfPrjParams ) { VALIDATE_POINTER1( hSRS, "OSRExportToPanorama", OGRERR_FAILURE ); VALIDATE_POINTER1( piProjSys, "OSRExportToPanorama", OGRERR_FAILURE ); VALIDATE_POINTER1( piDatum, "OSRExportToPanorama", OGRERR_FAILURE ); VALIDATE_POINTER1( piEllips, "OSRExportToPanorama", OGRERR_FAILURE ); VALIDATE_POINTER1( padfPrjParams, "OSRExportToPanorama", OGRERR_FAILURE ); return reinterpret_cast(hSRS)-> exportToPanorama( piProjSys, piDatum, piEllips, piZone, padfPrjParams ); } /************************************************************************/ /* exportToPanorama() */ /************************************************************************/ /** * Export coordinate system in "Panorama" GIS projection definition. * * This method is the equivalent of the C function OSRExportToPanorama(). * * @param piProjSys Pointer to variable, where the projection system code will * be returned. * * @param piDatum Pointer to variable, where the coordinate system code will * be returned. * * @param piEllips Pointer to variable, where the spheroid code will be * returned. * * @param piZone Pointer to variable, where the zone for UTM projection * system will be returned. * * @param padfPrjParams an existing 7 double buffer into which the * projection parameters will be placed. See importFromPanorama() * for the list of parameters. * * @return OGRERR_NONE on success or an error code on failure. */ OGRErr OGRSpatialReference::exportToPanorama( long *piProjSys, long *piDatum, long *piEllips, long *piZone, double *padfPrjParams ) const { CPLAssert( padfPrjParams ); const char *pszProjection = GetAttrValue("PROJECTION"); /* -------------------------------------------------------------------- */ /* Fill all projection parameters with zero. */ /* -------------------------------------------------------------------- */ *piDatum = 0L; *piEllips = 0L; *piZone = 0L; for( int i = 0; i < 7; i++ ) padfPrjParams[i] = 0.0; /* ==================================================================== */ /* Handle the projection definition. */ /* ==================================================================== */ if( IsLocal() ) { *piProjSys = PAN_PROJ_NONE; } else if( pszProjection == NULL ) { #ifdef DEBUG CPLDebug( "OSR_Panorama", "Empty projection definition, considered as Geographic" ); #endif *piProjSys = PAN_PROJ_NONE; } else if( EQUAL(pszProjection, SRS_PT_MERCATOR_1SP) ) { *piProjSys = PAN_PROJ_MERCAT; padfPrjParams[3] = TO_RADIANS * GetNormProjParm( SRS_PP_CENTRAL_MERIDIAN, 0.0 ); padfPrjParams[0] = TO_RADIANS * GetNormProjParm( SRS_PP_LATITUDE_OF_ORIGIN, 0.0 ); padfPrjParams[4] = GetNormProjParm( SRS_PP_SCALE_FACTOR, 1.0 ); padfPrjParams[5] = GetNormProjParm( SRS_PP_FALSE_EASTING, 0.0 ); padfPrjParams[6] = GetNormProjParm( SRS_PP_FALSE_NORTHING, 0.0 ); } else if( EQUAL(pszProjection, SRS_PT_POLAR_STEREOGRAPHIC) ) { *piProjSys = PAN_PROJ_PS; padfPrjParams[3] = TO_RADIANS * GetNormProjParm( SRS_PP_CENTRAL_MERIDIAN, 0.0 ); padfPrjParams[2] = TO_RADIANS * GetNormProjParm( SRS_PP_LATITUDE_OF_ORIGIN, 0.0 ); padfPrjParams[4] = GetNormProjParm( SRS_PP_SCALE_FACTOR, 1.0 ); padfPrjParams[5] = GetNormProjParm( SRS_PP_FALSE_EASTING, 0.0 ); padfPrjParams[6] = GetNormProjParm( SRS_PP_FALSE_NORTHING, 0.0 ); } else if( EQUAL(pszProjection, SRS_PT_POLYCONIC) ) { *piProjSys = PAN_PROJ_POLYC; padfPrjParams[3] = TO_RADIANS * GetNormProjParm( SRS_PP_CENTRAL_MERIDIAN, 0.0 ); padfPrjParams[2] = TO_RADIANS * GetNormProjParm( SRS_PP_LATITUDE_OF_ORIGIN, 0.0 ); padfPrjParams[5] = GetNormProjParm( SRS_PP_FALSE_EASTING, 0.0 ); padfPrjParams[6] = GetNormProjParm( SRS_PP_FALSE_NORTHING, 0.0 ); } else if( EQUAL(pszProjection, SRS_PT_EQUIDISTANT_CONIC) ) { *piProjSys = PAN_PROJ_EC; padfPrjParams[0] = TO_RADIANS * GetNormProjParm( SRS_PP_STANDARD_PARALLEL_1, 0.0 ); padfPrjParams[1] = TO_RADIANS * GetNormProjParm( SRS_PP_STANDARD_PARALLEL_2, 0.0 ); padfPrjParams[3] = TO_RADIANS * GetNormProjParm( SRS_PP_CENTRAL_MERIDIAN, 0.0 ); padfPrjParams[2] = TO_RADIANS * GetNormProjParm( SRS_PP_LATITUDE_OF_ORIGIN, 0.0 ); padfPrjParams[5] = GetNormProjParm( SRS_PP_FALSE_EASTING, 0.0 ); padfPrjParams[6] = GetNormProjParm( SRS_PP_FALSE_NORTHING, 0.0 ); } else if( EQUAL(pszProjection, SRS_PT_LAMBERT_CONFORMAL_CONIC_2SP) ) { *piProjSys = PAN_PROJ_LCC; padfPrjParams[0] = TO_RADIANS * GetNormProjParm( SRS_PP_STANDARD_PARALLEL_1, 0.0 ); padfPrjParams[1] = TO_RADIANS * GetNormProjParm( SRS_PP_STANDARD_PARALLEL_2, 0.0 ); padfPrjParams[3] = TO_RADIANS * GetNormProjParm( SRS_PP_CENTRAL_MERIDIAN, 0.0 ); padfPrjParams[2] = TO_RADIANS * GetNormProjParm( SRS_PP_LATITUDE_OF_ORIGIN, 0.0 ); padfPrjParams[5] = GetNormProjParm( SRS_PP_FALSE_EASTING, 0.0 ); padfPrjParams[6] = GetNormProjParm( SRS_PP_FALSE_NORTHING, 0.0 ); } else if( EQUAL(pszProjection, SRS_PT_TRANSVERSE_MERCATOR) ) { int bNorth = FALSE; *piZone = GetUTMZone( &bNorth ); if( *piZone != 0 ) { *piProjSys = PAN_PROJ_UTM; if( !bNorth ) *piZone = - *piZone; } else { *piProjSys = PAN_PROJ_TM; padfPrjParams[3] = TO_RADIANS * GetNormProjParm( SRS_PP_CENTRAL_MERIDIAN, 0.0 ); padfPrjParams[2] = TO_RADIANS * GetNormProjParm( SRS_PP_LATITUDE_OF_ORIGIN, 0.0 ); padfPrjParams[4] = GetNormProjParm( SRS_PP_SCALE_FACTOR, 1.0 ); padfPrjParams[5] = GetNormProjParm( SRS_PP_FALSE_EASTING, 0.0 ); padfPrjParams[6] = GetNormProjParm( SRS_PP_FALSE_NORTHING, 0.0 ); } } else if( EQUAL(pszProjection, SRS_PT_WAGNER_I) ) { *piProjSys = PAN_PROJ_WAG1; padfPrjParams[5] = GetNormProjParm( SRS_PP_FALSE_EASTING, 0.0 ); padfPrjParams[6] = GetNormProjParm( SRS_PP_FALSE_NORTHING, 0.0 ); } else if( EQUAL(pszProjection, SRS_PT_STEREOGRAPHIC) ) { *piProjSys = PAN_PROJ_STEREO; padfPrjParams[3] = TO_RADIANS * GetNormProjParm( SRS_PP_CENTRAL_MERIDIAN, 0.0 ); padfPrjParams[2] = TO_RADIANS * GetNormProjParm( SRS_PP_LATITUDE_OF_ORIGIN, 0.0 ); padfPrjParams[4] = GetNormProjParm( SRS_PP_SCALE_FACTOR, 1.0 ); padfPrjParams[5] = GetNormProjParm( SRS_PP_FALSE_EASTING, 0.0 ); padfPrjParams[6] = GetNormProjParm( SRS_PP_FALSE_NORTHING, 0.0 ); } else if( EQUAL(pszProjection, SRS_PT_AZIMUTHAL_EQUIDISTANT) ) { *piProjSys = PAN_PROJ_AE; padfPrjParams[3] = TO_RADIANS * GetNormProjParm( SRS_PP_LONGITUDE_OF_CENTER, 0.0 ); padfPrjParams[0] = TO_RADIANS * GetNormProjParm( SRS_PP_LATITUDE_OF_CENTER, 0.0 ); padfPrjParams[5] = GetNormProjParm( SRS_PP_FALSE_EASTING, 0.0 ); padfPrjParams[6] = GetNormProjParm( SRS_PP_FALSE_NORTHING, 0.0 ); } else if( EQUAL(pszProjection, SRS_PT_GNOMONIC) ) { *piProjSys = PAN_PROJ_GNOMON; padfPrjParams[3] = TO_RADIANS * GetNormProjParm( SRS_PP_CENTRAL_MERIDIAN, 0.0 ); padfPrjParams[2] = TO_RADIANS * GetNormProjParm( SRS_PP_LATITUDE_OF_ORIGIN, 0.0 ); padfPrjParams[5] = GetNormProjParm( SRS_PP_FALSE_EASTING, 0.0 ); padfPrjParams[6] = GetNormProjParm( SRS_PP_FALSE_NORTHING, 0.0 ); } else if( EQUAL(pszProjection, SRS_PT_MOLLWEIDE) ) { *piProjSys = PAN_PROJ_MOLL; padfPrjParams[3] = TO_RADIANS * GetNormProjParm( SRS_PP_CENTRAL_MERIDIAN, 0.0 ); padfPrjParams[5] = GetNormProjParm( SRS_PP_FALSE_EASTING, 0.0 ); padfPrjParams[6] = GetNormProjParm( SRS_PP_FALSE_NORTHING, 0.0 ); } else if( EQUAL(pszProjection, SRS_PT_LAMBERT_AZIMUTHAL_EQUAL_AREA) ) { *piProjSys = PAN_PROJ_LAEA; padfPrjParams[3] = TO_RADIANS * GetNormProjParm( SRS_PP_CENTRAL_MERIDIAN, 0.0 ); padfPrjParams[0] = TO_RADIANS * GetNormProjParm( SRS_PP_LATITUDE_OF_ORIGIN, 0.0 ); padfPrjParams[5] = GetNormProjParm( SRS_PP_FALSE_EASTING, 0.0 ); padfPrjParams[6] = GetNormProjParm( SRS_PP_FALSE_NORTHING, 0.0 ); } else if( EQUAL(pszProjection, SRS_PT_EQUIRECTANGULAR) ) { *piProjSys = PAN_PROJ_EQC; padfPrjParams[3] = TO_RADIANS * GetNormProjParm( SRS_PP_CENTRAL_MERIDIAN, 0.0 ); padfPrjParams[0] = TO_RADIANS * GetNormProjParm( SRS_PP_LATITUDE_OF_ORIGIN, 0.0 ); padfPrjParams[5] = GetNormProjParm( SRS_PP_FALSE_EASTING, 0.0 ); padfPrjParams[6] = GetNormProjParm( SRS_PP_FALSE_NORTHING, 0.0 ); } else if( EQUAL(pszProjection, SRS_PT_CYLINDRICAL_EQUAL_AREA) ) { *piProjSys = PAN_PROJ_CEA; padfPrjParams[3] = TO_RADIANS * GetNormProjParm( SRS_PP_CENTRAL_MERIDIAN, 0.0 ); padfPrjParams[2] = TO_RADIANS * GetNormProjParm( SRS_PP_STANDARD_PARALLEL_1, 0.0 ); padfPrjParams[5] = GetNormProjParm( SRS_PP_FALSE_EASTING, 0.0 ); padfPrjParams[6] = GetNormProjParm( SRS_PP_FALSE_NORTHING, 0.0 ); } else if( EQUAL(pszProjection, SRS_PT_IMW_POLYCONIC) ) { *piProjSys = PAN_PROJ_IMWP; padfPrjParams[3] = TO_RADIANS * GetNormProjParm( SRS_PP_CENTRAL_MERIDIAN, 0.0 ); padfPrjParams[0] = TO_RADIANS * GetNormProjParm( SRS_PP_LATITUDE_OF_1ST_POINT, 0.0 ); padfPrjParams[1] = TO_RADIANS * GetNormProjParm( SRS_PP_LATITUDE_OF_2ND_POINT, 0.0 ); padfPrjParams[5] = GetNormProjParm( SRS_PP_FALSE_EASTING, 0.0 ); padfPrjParams[6] = GetNormProjParm( SRS_PP_FALSE_NORTHING, 0.0 ); } // Projection unsupported by "Panorama" GIS else { CPLDebug( "OSR_Panorama", "Projection \"%s\" unsupported by \"Panorama\" GIS. " "Geographic system will be used.", pszProjection ); *piProjSys = PAN_PROJ_NONE; } /* -------------------------------------------------------------------- */ /* Translate the datum. */ /* -------------------------------------------------------------------- */ const char *pszDatum = GetAttrValue( "DATUM" ); if( pszDatum == NULL ) { *piDatum = PAN_DATUM_NONE; *piEllips = PAN_ELLIPSOID_NONE; } else if( EQUAL( pszDatum, "Pulkovo_1942" ) ) { *piDatum = PAN_DATUM_PULKOVO42; *piEllips = PAN_ELLIPSOID_KRASSOVSKY; } else if( EQUAL( pszDatum, SRS_DN_WGS84 ) ) { *piDatum = PAN_DATUM_WGS84; *piEllips = PAN_ELLIPSOID_WGS84; } // If not found well known datum, translate ellipsoid. else { const double dfSemiMajor = GetSemiMajor(); const double dfInvFlattening = GetInvFlattening(); #ifdef DEBUG CPLDebug( "OSR_Panorama", "Datum \"%s\" unsupported by \"Panorama\" GIS. " "Trying to translate an ellipsoid definition.", pszDatum ); #endif int i = 0; // Used after for. for( ; i < NUMBER_OF_ELLIPSOIDS; i++ ) { if( aoEllips[i] ) { double dfSM = 0.0; double dfIF = 1.0; if( OSRGetEllipsoidInfo( aoEllips[i], NULL, &dfSM, &dfIF ) == OGRERR_NONE && CPLIsEqual(dfSemiMajor, dfSM) && CPLIsEqual(dfInvFlattening, dfIF) ) { *piEllips = i; break; } } } if( i == NUMBER_OF_ELLIPSOIDS ) // Didn't found matches. { #ifdef DEBUG CPLDebug( "OSR_Panorama", "Ellipsoid \"%s\" unsupported by \"Panorama\" GIS.", pszDatum ); #endif *piDatum = PAN_DATUM_NONE; *piEllips = PAN_ELLIPSOID_NONE; } } return OGRERR_NONE; } tpeterka/decaf //--------------------------------------------------------------------------- // // 3-node linear coupling example // // node0 (4 procs) - node1 (2 procs) - node2 (1 proc) // node0[0,3] -> dflow[4,6] -> node1[7,8] -> dflow[9,10] -> node2[11] // // entire workflow takes 12 procs (3 dataflow procs between node0 and node1 and // 2 dataflow procs between node1 and node2) // // // Argonne National Laboratory // 9700 S. Cass Ave. // Argonne, IL 60439 // // //-------------------------------------------------------------------------- #include #include #include #include #include #include #include #include #include using namespace decaf; using namespace std; // producer void node0(Decaf* decaf) { // produce data for some number of timesteps for (int timestep = 0; timestep < 10; timestep++) { fprintf(stderr, "node0 timestep %d\n", timestep); // the data in this example is just the timestep; add it to a container SimpleFieldi data(timestep); pConstructData container; container->appendData("var", data, DECAF_NOFLAG, DECAF_PRIVATE, DECAF_SPLIT_KEEP_VALUE, DECAF_MERGE_ADD_VALUE); // send the data on all outbound dataflows // in this example there is only one outbound dataflow, but in general there could be more decaf->put(container, "out"); } // terminate the task (mandatory) by sending a quit message to the rest of the workflow fprintf(stderr, "node0 terminating\n"); decaf->terminate(); } // intermediate node is both a consumer and producer void node1(Decaf* decaf) { map in_data; while (decaf->get(in_data)) { int sum = 0; // get the values and add them for (size_t i = 0; i < in_data.size(); i++) { SimpleFieldi field = in_data.at("in")->getFieldData("var"); if(field) sum += field.getData(); else fprintf(stderr, "Error: null pointer in node1\n"); } fprintf(stderr, "node1: sum = %d\n", sum); // append the sum to a container SimpleFieldi data(sum); pConstructData container; container->appendData("var", data, DECAF_NOFLAG, DECAF_PRIVATE, DECAF_SPLIT_KEEP_VALUE, DECAF_MERGE_ADD_VALUE); // send the data on all outbound dataflows // in this example there is only one outbound dataflow, but in general there could be more decaf->put(container, "out"); } // terminate the task (mandatory) by sending a quit message to the rest of the workflow fprintf(stderr, "node1 terminating\n"); decaf->terminate(); } // consumer void node2(Decaf* decaf) { map in_data; while (decaf->get(in_data)) { int sum = 0; // get the values and add them for (size_t i = 0; i < in_data.size(); i++) { SimpleFieldi field = in_data.at("in")->getFieldData("var"); if(field) sum += field.getData(); else fprintf(stderr, "Error: null pointer in node2\n"); } fprintf(stderr, "node2 sum = %d\n", sum); } // terminate the task (mandatory) by sending a quit message to the rest of the workflow fprintf(stderr, "node2 terminating\n"); decaf->terminate(); } extern "C" { // dataflow just forwards everything that comes its way in this example void dflow(void* args, // arguments to the callback Dataflow* dataflow, // dataflow pConstructData in_data) // input data { dataflow->put(in_data, DECAF_LINK); } } // extern "C" void run(Workflow& workflow) // workflow { MPI_Init(NULL, NULL); #ifdef TRANSPORT_CCI uint32_t caps = 0; int ret = cci_init(CCI_ABI_VERSION, 0, &caps); if (ret) { fprintf(stderr, "cci_init() failed with %s\n", cci_strerror(NULL, (cci_status)ret)); exit(EXIT_FAILURE); } #endif // create decaf Decaf* decaf = new Decaf(MPI_COMM_WORLD, workflow); // run workflow node tasks // decaf simply tells the user whether this rank belongs to a workflow node // how the tasks are called is entirely up to the user // e.g., if they overlap in rank, it is up to the user to call them in an order that makes // sense (threaded, alternting, etc.) // also, the user can define any function signature she wants if (decaf->my_node("node0")) node0(decaf); if (decaf->my_node("node1")) node1(decaf); if (decaf->my_node("node2")) node2(decaf); // cleanup delete decaf; MPI_Finalize(); } // test driver for debugging purposes // this is hard-coding the no overlap case int main(int argc, char** argv) { Workflow workflow; Workflow::make_wflow_from_json(workflow, "linear3.json"); // run decaf run(workflow); return 0; } /* * Copyright (c) 2019 - 2021 Geode-solutions * * 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 namespace { static constexpr char EOL{ '\n' }; static constexpr char SPACE{ ' ' }; void write_node( const std::string& filename, const geode::TriangulatedSurface2D& mesh ) { std::ofstream node{ filename }; node << mesh.nb_vertices() << " 2 0 0" << EOL; for( const auto v : geode::Range{ mesh.nb_vertices() } ) { node << v << SPACE << mesh.point( v ).string() << EOL; } node << std::flush; } void write_ele( const std::string& filename, const geode::TriangulatedSurface2D& mesh ) { std::ofstream ele{ filename }; ele << mesh.nb_polygons() << " 3 0" << EOL; for( const auto p : geode::Range{ mesh.nb_polygons() } ) { ele << p; for( const auto v : geode::LRange{ 3 } ) { ele << SPACE << mesh.polygon_vertex( { p, v } ); } ele << EOL; } ele << std::flush; } void write_neigh( const std::string& filename, const geode::TriangulatedSurface2D& mesh ) { std::ofstream neigh{ filename }; neigh << mesh.nb_polygons() << " 3" << EOL; for( const auto p : geode::Range{ mesh.nb_polygons() } ) { neigh << p; for( const auto e : geode::LRange{ 3 } ) { neigh << SPACE; if( const auto adj = mesh.polygon_adjacent( { p, e } ) ) { neigh << adj.value(); } else { neigh << -1; } } neigh << EOL; } neigh << std::flush; } } // namespace namespace geode { namespace detail { void TriangleOutput::write() const { auto file = filename(); file.remove_suffix( TriangleOutput::extension().size() + 1 ); const auto& mesh = triangulated_surface(); write_node( absl::StrCat( file, ".node" ), mesh ); write_ele( absl::StrCat( file, ".ele" ), mesh ); write_neigh( absl::StrCat( file, ".neigh" ), mesh ); } } // namespace detail } // namespace geode /* Problem: P1530 Time: 2020/09/26 13:24:03 Author: Insouciant21 Status: Accepted */ #include using namespace std; int n, d; void work() { vector dec, rem; int p = 0x3f3f3f; while (true) { dec.push_back(n / d); int x = n % d; if (x == 0) break; p = distance(rem.begin(), find(rem.begin(), rem.end(), x)); if (p != rem.size()) break; p = 0x3f3f3f; rem.push_back(x); n = x * 10; } int cnt = 0; if (dec.size() == 1) cout << dec[0] << ".0" << endl; else { cout << dec[0] << "."; string x = to_string(dec[0]); cnt = x.length() + 1; for (unsigned i = 1; i < dec.size(); i++) { if (cnt % 76 == 0) cout << endl; if (p + 1 == i) { cout << "("; cnt++; } cout << dec[i]; cnt++; } if (p != 0x3f3f3f) cout << ")"; } return; } int main() { ios::sync_with_stdio(false); cin >> n >> d; work(); return 0; }src/run.cpp1-10 #include #include // [[Rcpp::export]] Rcpp::CharacterVector cpp_tumopp(const std::vector& args) { try { std::streambuf* obuf = tumopp::std_cout_rdbuf(Rcpp::Rcout.rdbuf()); std::streambuf* ebuf = tumopp::std_cerr_rdbuf(Rcpp::Rcerr.rdbuf()); tumopp::Simulation simulation(args); simulation.run(); tumopp::std_cout_rdbuf(obuf); tumopp::std_cout_rdbuf(ebuf); return Rcpp::CharacterVector::create( Rcpp::Named("config", simulation.config()), Rcpp::Named("population", simulation.history()), Rcpp::Named("snapshots", simulation.snapshots()), Rcpp::Named("drivers", simulation.drivers()), Rcpp::Named("benchmark", simulation.benchmark()) ); } catch (const std::runtime_error& e) { Rcpp::Rcerr << e.what() << "\n"; } return {}; } src/obj/BSPackedAdditionalGeometryData.cpp /* Copyright (c) 2006, NIF File Format Library and Tools All rights reserved. Please see niflib.h for license. */ //-----------------------------------NOTICE----------------------------------// // Some of this file is automatically filled in by a Python script. Only // // add custom code in the designated areas or it will be overwritten during // // the next update. // //-----------------------------------NOTICE----------------------------------// //--BEGIN FILE HEAD CUSTOM CODE--// //--END CUSTOM CODE--// #include "../../include/FixLink.h" #include "../../include/ObjectRegistry.h" #include "../../include/NIF_IO.h" #include "../../include/obj/BSPackedAdditionalGeometryData.h" #include "../../include/gen/AdditionalDataInfo.h" #include "../../include/gen/BSPackedAdditionalDataBlock.h" using namespace Niflib; //Definition of TYPE constant const Type BSPackedAdditionalGeometryData::TYPE("BSPackedAdditionalGeometryData", &AbstractAdditionalGeometryData::TYPE ); BSPackedAdditionalGeometryData::BSPackedAdditionalGeometryData() : numVertices((unsigned short)0), numBlockInfos((unsigned int)0), numBlocks((int)0) { //--BEGIN CONSTRUCTOR CUSTOM CODE--// //--END CUSTOM CODE--// } BSPackedAdditionalGeometryData::~BSPackedAdditionalGeometryData() { //--BEGIN DESTRUCTOR CUSTOM CODE--// //--END CUSTOM CODE--// } const Type & BSPackedAdditionalGeometryData::GetType() const { return TYPE; } NiObject * BSPackedAdditionalGeometryData::Create() { return new BSPackedAdditionalGeometryData; } void BSPackedAdditionalGeometryData::Read( istream& in, list & link_stack, const NifInfo & info ) { //--BEGIN PRE-READ CUSTOM CODE--// //--END CUSTOM CODE--// AbstractAdditionalGeometryData::Read( in, link_stack, info ); NifStream( numVertices, in, info ); NifStream( numBlockInfos, in, info ); blockInfos.resize(numBlockInfos); for (unsigned int i1 = 0; i1 < blockInfos.size(); i1++) { NifStream( blockInfos[i1].dataType, in, info ); NifStream( blockInfos[i1].numChannelBytesPerElement, in, info ); NifStream( blockInfos[i1].numChannelBytes, in, info ); NifStream( blockInfos[i1].numTotalBytesPerElement, in, info ); NifStream( blockInfos[i1].blockIndex, in, info ); NifStream( blockInfos[i1].channelOffset, in, info ); NifStream( blockInfos[i1].unknownByte1, in, info ); }; NifStream( numBlocks, in, info ); blocks.resize(numBlocks); for (unsigned int i1 = 0; i1 < blocks.size(); i1++) { NifStream( blocks[i1].hasData, in, info ); if ( blocks[i1].hasData ) { NifStream( blocks[i1].numTotalBytes, in, info ); NifStream( blocks[i1].numBlocks, in, info ); blocks[i1].blockOffsets.resize(blocks[i1].numBlocks); for (unsigned int i3 = 0; i3 < blocks[i1].blockOffsets.size(); i3++) { NifStream( blocks[i1].blockOffsets[i3], in, info ); }; NifStream( blocks[i1].numAtoms, in, info ); blocks[i1].atomSizes.resize(blocks[i1].numAtoms); for (unsigned int i3 = 0; i3 < blocks[i1].atomSizes.size(); i3++) { NifStream( blocks[i1].atomSizes[i3], in, info ); }; blocks[i1].data.resize(blocks[i1].numTotalBytes); for (unsigned int i3 = 0; i3 < blocks[i1].data.size(); i3++) { NifStream( blocks[i1].data[i3], in, info ); }; }; NifStream( blocks[i1].unknownInt1, in, info ); NifStream( blocks[i1].numTotalBytesPerElement, in, info ); }; //--BEGIN POST-READ CUSTOM CODE--// //--END CUSTOM CODE--// } void BSPackedAdditionalGeometryData::Write( ostream& out, const map & link_map, list & missing_link_stack, const NifInfo & info ) const { //--BEGIN PRE-WRITE CUSTOM CODE--// //--END CUSTOM CODE--// AbstractAdditionalGeometryData::Write( out, link_map, missing_link_stack, info ); numBlocks = (int)(blocks.size()); numBlockInfos = (unsigned int)(blockInfos.size()); NifStream( numVertices, out, info ); NifStream( numBlockInfos, out, info ); for (unsigned int i1 = 0; i1 < blockInfos.size(); i1++) { NifStream( blockInfos[i1].dataType, out, info ); NifStream( blockInfos[i1].numChannelBytesPerElement, out, info ); NifStream( blockInfos[i1].numChannelBytes, out, info ); NifStream( blockInfos[i1].numTotalBytesPerElement, out, info ); NifStream( blockInfos[i1].blockIndex, out, info ); NifStream( blockInfos[i1].channelOffset, out, info ); NifStream( blockInfos[i1].unknownByte1, out, info ); }; NifStream( numBlocks, out, info ); for (unsigned int i1 = 0; i1 < blocks.size(); i1++) { blocks[i1].numAtoms = (int)(blocks[i1].atomSizes.size()); blocks[i1].numBlocks = (int)(blocks[i1].blockOffsets.size()); blocks[i1].numTotalBytes = (int)(blocks[i1].data.size()); NifStream( blocks[i1].hasData, out, info ); if ( blocks[i1].hasData ) { NifStream( blocks[i1].numTotalBytes, out, info ); NifStream( blocks[i1].numBlocks, out, info ); for (unsigned int i3 = 0; i3 < blocks[i1].blockOffsets.size(); i3++) { NifStream( blocks[i1].blockOffsets[i3], out, info ); }; NifStream( blocks[i1].numAtoms, out, info ); for (unsigned int i3 = 0; i3 < blocks[i1].atomSizes.size(); i3++) { NifStream( blocks[i1].atomSizes[i3], out, info ); }; for (unsigned int i3 = 0; i3 < blocks[i1].data.size(); i3++) { NifStream( blocks[i1].data[i3], out, info ); }; }; NifStream( blocks[i1].unknownInt1, out, info ); NifStream( blocks[i1].numTotalBytesPerElement, out, info ); }; //--BEGIN POST-WRITE CUSTOM CODE--// //--END CUSTOM CODE--// } std::string BSPackedAdditionalGeometryData::asString( bool verbose ) const { //--BEGIN PRE-STRING CUSTOM CODE--// //--END CUSTOM CODE--// stringstream out; unsigned int array_output_count = 0; out << AbstractAdditionalGeometryData::asString(); numBlocks = (int)(blocks.size()); numBlockInfos = (unsigned int)(blockInfos.size()); out << " Num Vertices: " << numVertices << endl; out << " Num Block Infos: " << numBlockInfos << endl; array_output_count = 0; for (unsigned int i1 = 0; i1 < blockInfos.size(); i1++) { if ( !verbose && ( array_output_count > MAXARRAYDUMP ) ) { out << "" << endl; break; }; out << " Data Type: " << blockInfos[i1].dataType << endl; out << " Num Channel Bytes Per Element: " << blockInfos[i1].numChannelBytesPerElement << endl; out << " Num Channel Bytes: " << blockInfos[i1].numChannelBytes << endl; out << " Num Total Bytes Per Element: " << blockInfos[i1].numTotalBytesPerElement << endl; out << " Block Index: " << blockInfos[i1].blockIndex << endl; out << " Channel Offset: " << blockInfos[i1].channelOffset << endl; out << " Unknown Byte 1: " << blockInfos[i1].unknownByte1 << endl; }; out << " Num Blocks: " << numBlocks << endl; array_output_count = 0; for (unsigned int i1 = 0; i1 < blocks.size(); i1++) { if ( !verbose && ( array_output_count > MAXARRAYDUMP ) ) { out << "" << endl; break; }; blocks[i1].numAtoms = (int)(blocks[i1].atomSizes.size()); blocks[i1].numBlocks = (int)(blocks[i1].blockOffsets.size()); blocks[i1].numTotalBytes = (int)(blocks[i1].data.size()); out << " Has Data: " << blocks[i1].hasData << endl; if ( blocks[i1].hasData ) { out << " Num Total Bytes: " << blocks[i1].numTotalBytes << endl; out << " Num Blocks: " << blocks[i1].numBlocks << endl; array_output_count = 0; for (unsigned int i3 = 0; i3 < blocks[i1].blockOffsets.size(); i3++) { if ( !verbose && ( array_output_count > MAXARRAYDUMP ) ) { out << "" << endl; break; }; if ( !verbose && ( array_output_count > MAXARRAYDUMP ) ) { break; }; out << " Block Offsets[" << i3 << "]: " << blocks[i1].blockOffsets[i3] << endl; array_output_count++; }; out << " Num Atoms: " << blocks[i1].numAtoms << endl; array_output_count = 0; for (unsigned int i3 = 0; i3 < blocks[i1].atomSizes.size(); i3++) { if ( !verbose && ( array_output_count > MAXARRAYDUMP ) ) { out << "" << endl; break; }; if ( !verbose && ( array_output_count > MAXARRAYDUMP ) ) { break; }; out << " Atom Sizes[" << i3 << "]: " << blocks[i1].atomSizes[i3] << endl; array_output_count++; }; array_output_count = 0; for (unsigned int i3 = 0; i3 < blocks[i1].data.size(); i3++) { if ( !verbose && ( array_output_count > MAXARRAYDUMP ) ) { out << "" << endl; break; }; if ( !verbose && ( array_output_count > MAXARRAYDUMP ) ) { break; }; out << " Data[" << i3 << "]: " << blocks[i1].data[i3] << endl; array_output_count++; }; }; out << " Unknown Int 1: " << blocks[i1].unknownInt1 << endl; out << " Num Total Bytes Per Element: " << blocks[i1].numTotalBytesPerElement << endl; }; return out.str(); //--BEGIN POST-STRING CUSTOM CODE--// //--END CUSTOM CODE--// } void BSPackedAdditionalGeometryData::FixLinks( const map & objects, list & link_stack, list & missing_link_stack, const NifInfo & info ) { //--BEGIN PRE-FIXLINKS CUSTOM CODE--// //--END CUSTOM CODE--// AbstractAdditionalGeometryData::FixLinks( objects, link_stack, missing_link_stack, info ); //--BEGIN POST-FIXLINKS CUSTOM CODE--// //--END CUSTOM CODE--// } std::list BSPackedAdditionalGeometryData::GetRefs() const { list > refs; refs = AbstractAdditionalGeometryData::GetRefs(); return refs; } std::list BSPackedAdditionalGeometryData::GetPtrs() const { list ptrs; ptrs = AbstractAdditionalGeometryData::GetPtrs(); return ptrs; } //--BEGIN MISC CUSTOM CODE--// //--END CUSTOM CODE--// /* * Copyright (C) 2013 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 "suggest/policyimpl/dictionary/bigram/dynamic_bigram_list_policy.h" #include "suggest/core/policy/dictionary_shortcuts_structure_policy.h" #include "suggest/policyimpl/dictionary/dynamic_patricia_trie_node_reader.h" #include "suggest/policyimpl/dictionary/dynamic_patricia_trie_writing_helper.h" #include "suggest/policyimpl/dictionary/utils/buffer_with_extendable_buffer.h" #include "suggest/policyimpl/dictionary/utils/forgetting_curve_utils.h" namespace latinime { const int DynamicBigramListPolicy::CONTINUING_BIGRAM_LINK_COUNT_LIMIT = 10000; const int DynamicBigramListPolicy::BIGRAM_ENTRY_COUNT_IN_A_BIGRAM_LIST_LIMIT = 100000; void DynamicBigramListPolicy::getNextBigram(int *const outBigramPos, int *const outProbability, bool *const outHasNext, int *const bigramEntryPos) const { const bool usesAdditionalBuffer = mBuffer->isInAdditionalBuffer(*bigramEntryPos); const uint8_t *const buffer = mBuffer->getBuffer(usesAdditionalBuffer); if (usesAdditionalBuffer) { *bigramEntryPos -= mBuffer->getOriginalBufferSize(); } BigramListReadWriteUtils::BigramFlags bigramFlags; int originalBigramPos; BigramListReadWriteUtils::getBigramEntryPropertiesAndAdvancePosition(buffer, &bigramFlags, &originalBigramPos, bigramEntryPos); if (usesAdditionalBuffer && originalBigramPos != NOT_A_DICT_POS) { originalBigramPos += mBuffer->getOriginalBufferSize(); } *outProbability = BigramListReadWriteUtils::getProbabilityFromFlags(bigramFlags); *outHasNext = BigramListReadWriteUtils::hasNext(bigramFlags); if (mIsDecayingDict && !ForgettingCurveUtils::isValidEncodedProbability(*outProbability)) { // This bigram is too weak to output. *outBigramPos = NOT_A_DICT_POS; } else { *outBigramPos = followBigramLinkAndGetCurrentBigramPtNodePos(originalBigramPos); } if (usesAdditionalBuffer) { *bigramEntryPos += mBuffer->getOriginalBufferSize(); } } void DynamicBigramListPolicy::skipAllBigrams(int *const bigramListPos) const { const bool usesAdditionalBuffer = mBuffer->isInAdditionalBuffer(*bigramListPos); const uint8_t *const buffer = mBuffer->getBuffer(usesAdditionalBuffer); if (usesAdditionalBuffer) { *bigramListPos -= mBuffer->getOriginalBufferSize(); } BigramListReadWriteUtils::skipExistingBigrams(buffer, bigramListPos); if (usesAdditionalBuffer) { *bigramListPos += mBuffer->getOriginalBufferSize(); } } bool DynamicBigramListPolicy::copyAllBigrams(BufferWithExtendableBuffer *const bufferToWrite, int *const fromPos, int *const toPos, int *const outBigramsCount) const { const bool usesAdditionalBuffer = mBuffer->isInAdditionalBuffer(*fromPos); if (usesAdditionalBuffer) { *fromPos -= mBuffer->getOriginalBufferSize(); } *outBigramsCount = 0; BigramListReadWriteUtils::BigramFlags bigramFlags; int bigramEntryCount = 0; int lastWrittenEntryPos = NOT_A_DICT_POS; do { if (++bigramEntryCount > BIGRAM_ENTRY_COUNT_IN_A_BIGRAM_LIST_LIMIT) { AKLOGE("Too many bigram entries. Entry count: %d, Limit: %d", bigramEntryCount, BIGRAM_ENTRY_COUNT_IN_A_BIGRAM_LIST_LIMIT); ASSERT(false); return false; } // The buffer address can be changed after calling buffer writing methods. int originalBigramPos; BigramListReadWriteUtils::getBigramEntryPropertiesAndAdvancePosition( mBuffer->getBuffer(usesAdditionalBuffer), &bigramFlags, &originalBigramPos, fromPos); if (originalBigramPos == NOT_A_DICT_POS) { // skip invalid bigram entry. continue; } if (usesAdditionalBuffer) { originalBigramPos += mBuffer->getOriginalBufferSize(); } const int bigramPos = followBigramLinkAndGetCurrentBigramPtNodePos(originalBigramPos); if (bigramPos == NOT_A_DICT_POS) { // Target PtNode has been invalidated. continue; } lastWrittenEntryPos = *toPos; if (!BigramListReadWriteUtils::createAndWriteBigramEntry(bufferToWrite, bigramPos, BigramListReadWriteUtils::getProbabilityFromFlags(bigramFlags), BigramListReadWriteUtils::hasNext(bigramFlags), toPos)) { return false; } (*outBigramsCount)++; } while(BigramListReadWriteUtils::hasNext(bigramFlags)); // Makes the last entry the terminal of the list. Updates the flags. if (lastWrittenEntryPos != NOT_A_DICT_POS) { if (!BigramListReadWriteUtils::setHasNextFlag(bufferToWrite, false /* hasNext */, lastWrittenEntryPos)) { return false; } } if (usesAdditionalBuffer) { *fromPos += mBuffer->getOriginalBufferSize(); } return true; } // Finding useless bigram entries and remove them. Bigram entry is useless when the target PtNode // has been deleted or is not a valid terminal. bool DynamicBigramListPolicy::updateAllBigramEntriesAndDeleteUselessEntries( int *const bigramListPos, int *const outValidBigramEntryCount) { const bool usesAdditionalBuffer = mBuffer->isInAdditionalBuffer(*bigramListPos); if (usesAdditionalBuffer) { *bigramListPos -= mBuffer->getOriginalBufferSize(); } DynamicPatriciaTrieNodeReader nodeReader(mBuffer, this /* bigramsPolicy */, mShortcutPolicy); BigramListReadWriteUtils::BigramFlags bigramFlags; int bigramEntryCount = 0; do { if (++bigramEntryCount > BIGRAM_ENTRY_COUNT_IN_A_BIGRAM_LIST_LIMIT) { AKLOGE("Too many bigram entries. Entry count: %d, Limit: %d", bigramEntryCount, BIGRAM_ENTRY_COUNT_IN_A_BIGRAM_LIST_LIMIT); ASSERT(false); return false; } int bigramEntryPos = *bigramListPos; int originalBigramPos; // The buffer address can be changed after calling buffer writing methods. BigramListReadWriteUtils::getBigramEntryPropertiesAndAdvancePosition( mBuffer->getBuffer(usesAdditionalBuffer), &bigramFlags, &originalBigramPos, bigramListPos); if (usesAdditionalBuffer) { bigramEntryPos += mBuffer->getOriginalBufferSize(); } if (originalBigramPos == NOT_A_DICT_POS) { // This entry has already been removed. continue; } if (usesAdditionalBuffer) { originalBigramPos += mBuffer->getOriginalBufferSize(); } const int bigramTargetNodePos = followBigramLinkAndGetCurrentBigramPtNodePos(originalBigramPos); nodeReader.fetchNodeInfoInBufferFromPtNodePos(bigramTargetNodePos); if (nodeReader.isDeleted() || !nodeReader.isTerminal() || bigramTargetNodePos == NOT_A_DICT_POS) { // The target is no longer valid terminal. Invalidate the current bigram entry. if (!BigramListReadWriteUtils::writeBigramEntry(mBuffer, bigramFlags, NOT_A_DICT_POS /* targetPtNodePos */, &bigramEntryPos)) { return false; } continue; } bool isRemoved = false; if (!updateProbabilityForDecay(bigramFlags, bigramTargetNodePos, &bigramEntryPos, &isRemoved)) { return false; } if (!isRemoved) { (*outValidBigramEntryCount) += 1; } } while(BigramListReadWriteUtils::hasNext(bigramFlags)); return true; } // Updates bigram target PtNode positions in the list after the placing step in GC. bool DynamicBigramListPolicy::updateAllBigramTargetPtNodePositions(int *const bigramListPos, const DynamicPatriciaTrieWritingHelper::PtNodePositionRelocationMap *const ptNodePositionRelocationMap, int *const outBigramEntryCount) { const bool usesAdditionalBuffer = mBuffer->isInAdditionalBuffer(*bigramListPos); if (usesAdditionalBuffer) { *bigramListPos -= mBuffer->getOriginalBufferSize(); } BigramListReadWriteUtils::BigramFlags bigramFlags; int bigramEntryCount = 0; do { if (++bigramEntryCount > BIGRAM_ENTRY_COUNT_IN_A_BIGRAM_LIST_LIMIT) { AKLOGE("Too many bigram entries. Entry count: %d, Limit: %d", bigramEntryCount, BIGRAM_ENTRY_COUNT_IN_A_BIGRAM_LIST_LIMIT); ASSERT(false); return false; } int bigramEntryPos = *bigramListPos; if (usesAdditionalBuffer) { bigramEntryPos += mBuffer->getOriginalBufferSize(); } int bigramTargetPtNodePos; // The buffer address can be changed after calling buffer writing methods. BigramListReadWriteUtils::getBigramEntryPropertiesAndAdvancePosition( mBuffer->getBuffer(usesAdditionalBuffer), &bigramFlags, &bigramTargetPtNodePos, bigramListPos); if (bigramTargetPtNodePos == NOT_A_DICT_POS) { continue; } if (usesAdditionalBuffer) { bigramTargetPtNodePos += mBuffer->getOriginalBufferSize(); } DynamicPatriciaTrieWritingHelper::PtNodePositionRelocationMap::const_iterator it = ptNodePositionRelocationMap->find(bigramTargetPtNodePos); if (it != ptNodePositionRelocationMap->end()) { bigramTargetPtNodePos = it->second; } else { bigramTargetPtNodePos = NOT_A_DICT_POS; } if (!BigramListReadWriteUtils::writeBigramEntry(mBuffer, bigramFlags, bigramTargetPtNodePos, &bigramEntryPos)) { return false; } } while(BigramListReadWriteUtils::hasNext(bigramFlags)); (*outBigramEntryCount) = bigramEntryCount; return true; } bool DynamicBigramListPolicy::addNewBigramEntryToBigramList(const int bigramTargetPos, const int probability, int *const bigramListPos, bool *const outAddedNewBigram) { const bool usesAdditionalBuffer = mBuffer->isInAdditionalBuffer(*bigramListPos); if (usesAdditionalBuffer) { *bigramListPos -= mBuffer->getOriginalBufferSize(); } BigramListReadWriteUtils::BigramFlags bigramFlags; int bigramEntryCount = 0; do { if (++bigramEntryCount > BIGRAM_ENTRY_COUNT_IN_A_BIGRAM_LIST_LIMIT) { AKLOGE("Too many bigram entries. Entry count: %d, Limit: %d", bigramEntryCount, BIGRAM_ENTRY_COUNT_IN_A_BIGRAM_LIST_LIMIT); ASSERT(false); return false; } int entryPos = *bigramListPos; if (usesAdditionalBuffer) { entryPos += mBuffer->getOriginalBufferSize(); } int originalBigramPos; // The buffer address can be changed after calling buffer writing methods. BigramListReadWriteUtils::getBigramEntryPropertiesAndAdvancePosition( mBuffer->getBuffer(usesAdditionalBuffer), &bigramFlags, &originalBigramPos, bigramListPos); if (usesAdditionalBuffer && originalBigramPos != NOT_A_DICT_POS) { originalBigramPos += mBuffer->getOriginalBufferSize(); } if (followBigramLinkAndGetCurrentBigramPtNodePos(originalBigramPos) == bigramTargetPos) { // Update this bigram entry. *outAddedNewBigram = false; const int originalProbability = BigramListReadWriteUtils::getProbabilityFromFlags( bigramFlags); const int probabilityToWrite = mIsDecayingDict ? ForgettingCurveUtils::getUpdatedEncodedProbability(originalProbability, probability) : probability; const BigramListReadWriteUtils::BigramFlags updatedFlags = BigramListReadWriteUtils::setProbabilityInFlags(bigramFlags, probabilityToWrite); return BigramListReadWriteUtils::writeBigramEntry(mBuffer, updatedFlags, originalBigramPos, &entryPos); } if (BigramListReadWriteUtils::hasNext(bigramFlags)) { continue; } // The current last entry is found. // First, update the flags of the last entry. if (!BigramListReadWriteUtils::setHasNextFlag(mBuffer, true /* hasNext */, entryPos)) { *outAddedNewBigram = false; return false; } if (usesAdditionalBuffer) { *bigramListPos += mBuffer->getOriginalBufferSize(); } // Then, add a new entry after the last entry. *outAddedNewBigram = true; return writeNewBigramEntry(bigramTargetPos, probability, bigramListPos); } while(BigramListReadWriteUtils::hasNext(bigramFlags)); // We return directly from the while loop. ASSERT(false); return false; } bool DynamicBigramListPolicy::writeNewBigramEntry(const int bigramTargetPos, const int probability, int *const writingPos) { // hasNext is false because we are adding a new bigram entry at the end of the bigram list. const int probabilityToWrite = mIsDecayingDict ? ForgettingCurveUtils::getUpdatedEncodedProbability(NOT_A_PROBABILITY, probability) : probability; return BigramListReadWriteUtils::createAndWriteBigramEntry(mBuffer, bigramTargetPos, probabilityToWrite, false /* hasNext */, writingPos); } bool DynamicBigramListPolicy::removeBigram(const int bigramListPos, const int bigramTargetPos) { const bool usesAdditionalBuffer = mBuffer->isInAdditionalBuffer(bigramListPos); int pos = bigramListPos; if (usesAdditionalBuffer) { pos -= mBuffer->getOriginalBufferSize(); } BigramListReadWriteUtils::BigramFlags bigramFlags; int bigramEntryCount = 0; do { if (++bigramEntryCount > BIGRAM_ENTRY_COUNT_IN_A_BIGRAM_LIST_LIMIT) { AKLOGE("Too many bigram entries. Entry count: %d, Limit: %d", bigramEntryCount, BIGRAM_ENTRY_COUNT_IN_A_BIGRAM_LIST_LIMIT); ASSERT(false); return false; } int bigramEntryPos = pos; int originalBigramPos; // The buffer address can be changed after calling buffer writing methods. BigramListReadWriteUtils::getBigramEntryPropertiesAndAdvancePosition( mBuffer->getBuffer(usesAdditionalBuffer), &bigramFlags, &originalBigramPos, &pos); if (usesAdditionalBuffer) { bigramEntryPos += mBuffer->getOriginalBufferSize(); } if (usesAdditionalBuffer && originalBigramPos != NOT_A_DICT_POS) { originalBigramPos += mBuffer->getOriginalBufferSize(); } const int bigramPos = followBigramLinkAndGetCurrentBigramPtNodePos(originalBigramPos); if (bigramPos != bigramTargetPos) { continue; } // Target entry is found. Write an invalid target position to mark the bigram invalid. return BigramListReadWriteUtils::writeBigramEntry(mBuffer, bigramFlags, NOT_A_DICT_POS /* targetOffset */, &bigramEntryPos); } while(BigramListReadWriteUtils::hasNext(bigramFlags)); return false; } int DynamicBigramListPolicy::followBigramLinkAndGetCurrentBigramPtNodePos( const int originalBigramPos) const { if (originalBigramPos == NOT_A_DICT_POS) { return NOT_A_DICT_POS; } int currentPos = originalBigramPos; DynamicPatriciaTrieNodeReader nodeReader(mBuffer, this /* bigramsPolicy */, mShortcutPolicy); nodeReader.fetchNodeInfoInBufferFromPtNodePos(currentPos); int bigramLinkCount = 0; while (nodeReader.getBigramLinkedNodePos() != NOT_A_DICT_POS) { currentPos = nodeReader.getBigramLinkedNodePos(); nodeReader.fetchNodeInfoInBufferFromPtNodePos(currentPos); bigramLinkCount++; if (bigramLinkCount > CONTINUING_BIGRAM_LINK_COUNT_LIMIT) { AKLOGE("Bigram link is invalid. start position: %d", originalBigramPos); ASSERT(false); return NOT_A_DICT_POS; } } return currentPos; } bool DynamicBigramListPolicy::updateProbabilityForDecay( const BigramListReadWriteUtils::BigramFlags bigramFlags, const int targetPtNodePos, int *const bigramEntryPos, bool *const outRemoved) const { *outRemoved = false; if (mIsDecayingDict) { // Update bigram probability for decaying. const int newProbability = ForgettingCurveUtils::getEncodedProbabilityToSave( BigramListReadWriteUtils::getProbabilityFromFlags(bigramFlags), mHeaderPolicy); if (ForgettingCurveUtils::isValidEncodedProbability(newProbability)) { // Write new probability. const BigramListReadWriteUtils::BigramFlags updatedBigramFlags = BigramListReadWriteUtils::setProbabilityInFlags( bigramFlags, newProbability); if (!BigramListReadWriteUtils::writeBigramEntry(mBuffer, updatedBigramFlags, targetPtNodePos, bigramEntryPos)) { return false; } } else { // Remove current bigram entry. *outRemoved = true; if (!BigramListReadWriteUtils::writeBigramEntry(mBuffer, bigramFlags, NOT_A_DICT_POS /* targetPtNodePos */, bigramEntryPos)) { return false; } } } return true; } } // namespace latinime 0 //Problema 3.01 using namespace std; //librería #include //proceso int main() { int edad;//definiendo la variable cout<<"digite su edad:"<>edad; if(edad>=18){ cout<<"usted puede votar"<Leomotors/Factoring-Polynomial-Generator /** * * Safe Input Module * * Original Work: @Teproanyx * * Customed by: @Leomotors */ #ifndef TEPROANYX_SAFE_INPUT #define TEPROANYX_SAFE_INPUT #ifndef INITIAL_BUFFER #define INITIAL_BUFFER 8 #endif #include namespace tsi { long long getlong(const char *); int getInt(const char *); double getDouble(const char *); std::string getString(const char *); void memoryError(const void *); } #endif// // Serializable.hpp // Project Space // // Created by on 5/24/20. // Copyright © 2020 . All rights reserved. // #ifndef NP_ENGINE_SERIALIZABLE_HPP #define NP_ENGINE_SERIALIZABLE_HPP #include "NP-Engine/Primitive/Primitive.hpp" #include "NP-Engine/Filesystem/Filesystem.hpp" #include "NP-Engine/String/String.hpp" #include "NP-Engine/JSON/JSON.hpp" namespace np { namespace serialization { /** this class acts as the basis for all serializable objects the entry points still enable inherited behavior while the protected methods allow for serialization coordination throughout inheritance */ class Serializable { protected: /** protected template Save method so child classes can directly call the Save of their parents */ template bl SaveAs(str filepath, const T* object) const { bl saved = false; str parent_path = fs::get_parent_path(filepath); if (parent_path.size() > 0) { fs::create_directories(parent_path); } if ((parent_path.size() == 0 && filepath.size() > 0) || fs::exists(parent_path)) { ofstrm os; os.open(filepath); object->T::Insertion(os, filepath); os.close(); saved = true; } return saved; } /** protected template Load method so child classes can directly call the Load of their parents */ template bl LoadAs(str filepath, T* object) { bl loaded = false; if (fs::exists(filepath)) { ifstrm is; is.open(filepath); object->T::Extraction(is, filepath); is.close(); loaded = true; } return loaded; } public: /** save ourselves to the given json object */ virtual bl SaveToJson(nlohmann::json& json) const { return false; } /** load ourselves from the given json object */ virtual bl LoadFromJson(const nlohmann::json& json) { return false; } /** save oursellves as the given filepath return if the save was successful or not */ bl SaveAs(str filepath) const { bl saved = false; str parent_path = fs::get_parent_path(filepath); if (parent_path.size() > 0) { fs::create_directories(parent_path); } if ((parent_path.size() == 0 && filepath.size() > 0) || fs::exists(parent_path)) { ofstrm os; os.open(filepath); Insertion(os, filepath); os.close(); saved = true; } return saved; } /** load outselves as the given filepath return if the load was successful or not */ bl LoadAs(str filepath) { bl loaded = false; if (fs::exists(filepath)) { ifstrm is; is.open(filepath); Extraction(is, filepath); is.close(); loaded = true; } return loaded; } /** serialization method for us to write we require our objects to know which filepath they are a part of */ virtual ostrm& Insertion(ostrm& os, str filepath) const = 0; /** deserialization method for us to read we require our objects to know which filepath they are a part of */ virtual istrm& Extraction(istrm& is, str filepath) = 0; /** save oursellves inside the given dirpath return if the save was successful or not */ virtual bl SaveTo(str dirpath) const = 0; /** load outselves from the given dirpath return if the load was successful or not */ virtual bl LoadFrom(str dirpath) = 0; }; } // namespace serialization } // namespace np #endif /* NP_ENGINE_SERIALIZABLE_HPP */ // © 2016 and later: Unicode, Inc. and others. // License & terms of use: http://www.unicode.org/copyright.html /* ******************************************************************************* * Copyright (C) 2007-2014, International Business Machines Corporation and * others. All Rights Reserved. ******************************************************************************* */ #include "unicode/utypes.h" #if !UCONFIG_NO_FORMATTING #include "zonemeta.h" #include "unicode/timezone.h" #include "unicode/ustring.h" #include "unicode/putil.h" #include "unicode/simpletz.h" #include "unicode/strenum.h" #include "umutex.h" #include "uvector.h" #include "cmemory.h" #include "gregoimp.h" #include "cstring.h" #include "ucln_in.h" #include "uassert.h" #include "uresimp.h" #include "uhash.h" #include "olsontz.h" #include "uinvchar.h" static icu::UMutex *gZoneMetaLock() { static icu::UMutex m = U_MUTEX_INITIALIZER; return &m; } // CLDR Canonical ID mapping table static UHashtable *gCanonicalIDCache = NULL; static icu::UInitOnce gCanonicalIDCacheInitOnce = U_INITONCE_INITIALIZER; // Metazone mapping table static UHashtable *gOlsonToMeta = NULL; static icu::UInitOnce gOlsonToMetaInitOnce = U_INITONCE_INITIALIZER; // Available metazone IDs vector and table static icu::UVector *gMetaZoneIDs = NULL; static UHashtable *gMetaZoneIDTable = NULL; static icu::UInitOnce gMetaZoneIDsInitOnce = U_INITONCE_INITIALIZER; // Country info vectors static icu::UVector *gSingleZoneCountries = NULL; static icu::UVector *gMultiZonesCountries = NULL; static icu::UInitOnce gCountryInfoVectorsInitOnce = U_INITONCE_INITIALIZER; U_CDECL_BEGIN /** * Cleanup callback func */ static UBool U_CALLCONV zoneMeta_cleanup(void) { if (gCanonicalIDCache != NULL) { uhash_close(gCanonicalIDCache); gCanonicalIDCache = NULL; } gCanonicalIDCacheInitOnce.reset(); if (gOlsonToMeta != NULL) { uhash_close(gOlsonToMeta); gOlsonToMeta = NULL; } gOlsonToMetaInitOnce.reset(); if (gMetaZoneIDTable != NULL) { uhash_close(gMetaZoneIDTable); gMetaZoneIDTable = NULL; } // delete after closing gMetaZoneIDTable, because it holds // value objects held by the hashtable delete gMetaZoneIDs; gMetaZoneIDs = NULL; gMetaZoneIDsInitOnce.reset(); delete gSingleZoneCountries; gSingleZoneCountries = NULL; delete gMultiZonesCountries; gMultiZonesCountries = NULL; gCountryInfoVectorsInitOnce.reset(); return TRUE; } /** * Deleter for UChar* string */ static void U_CALLCONV deleteUCharString(void *obj) { UChar *entry = (UChar*)obj; uprv_free(entry); } /** * Deleter for UVector */ static void U_CALLCONV deleteUVector(void *obj) { delete (icu::UVector*) obj; } /** * Deleter for OlsonToMetaMappingEntry */ static void U_CALLCONV deleteOlsonToMetaMappingEntry(void *obj) { icu::OlsonToMetaMappingEntry *entry = (icu::OlsonToMetaMappingEntry*)obj; uprv_free(entry); } U_CDECL_END U_NAMESPACE_BEGIN #define ZID_KEY_MAX 128 static const char gMetaZones[] = "metaZones"; static const char gMetazoneInfo[] = "metazoneInfo"; static const char gMapTimezonesTag[] = "mapTimezones"; static const char gKeyTypeData[] = "keyTypeData"; static const char gTypeAliasTag[] = "typeAlias"; static const char gTypeMapTag[] = "typeMap"; static const char gTimezoneTag[] = "timezone"; static const char gPrimaryZonesTag[] = "primaryZones"; static const char gWorldTag[] = "001"; static const UChar gWorld[] = {0x30, 0x30, 0x31, 0x00}; // "001" static const UChar gDefaultFrom[] = {0x31, 0x39, 0x37, 0x30, 0x2D, 0x30, 0x31, 0x2D, 0x30, 0x31, 0x20, 0x30, 0x30, 0x3A, 0x30, 0x30, 0x00}; // "1970-01-01 00:00" static const UChar gDefaultTo[] = {0x39, 0x39, 0x39, 0x39, 0x2D, 0x31, 0x32, 0x2D, 0x33, 0x31, 0x20, 0x32, 0x33, 0x3A, 0x35, 0x39, 0x00}; // "9999-12-31 23:59" static const UChar gCustomTzPrefix[] = {0x47, 0x4D, 0x54, 0}; // "GMT" #define ASCII_DIGIT(c) (((c)>=0x30 && (c)<=0x39) ? (c)-0x30 : -1) /* * Convert a date string used by metazone mappings to UDate. * The format used by CLDR metazone mapping is "yyyy-MM-dd HH:mm". */ static UDate parseDate (const UChar *text, UErrorCode &status) { if (U_FAILURE(status)) { return 0; } int32_t len = u_strlen(text); if (len != 16 && len != 10) { // It must be yyyy-MM-dd HH:mm (length 16) or yyyy-MM-dd (length 10) status = U_INVALID_FORMAT_ERROR; return 0; } int32_t year = 0, month = 0, day = 0, hour = 0, min = 0, n; int32_t idx; // "yyyy" (0 - 3) for (idx = 0; idx <= 3 && U_SUCCESS(status); idx++) { n = ASCII_DIGIT((int32_t)text[idx]); if (n >= 0) { year = 10*year + n; } else { status = U_INVALID_FORMAT_ERROR; } } // "MM" (5 - 6) for (idx = 5; idx <= 6 && U_SUCCESS(status); idx++) { n = ASCII_DIGIT((int32_t)text[idx]); if (n >= 0) { month = 10*month + n; } else { status = U_INVALID_FORMAT_ERROR; } } // "dd" (8 - 9) for (idx = 8; idx <= 9 && U_SUCCESS(status); idx++) { n = ASCII_DIGIT((int32_t)text[idx]); if (n >= 0) { day = 10*day + n; } else { status = U_INVALID_FORMAT_ERROR; } } if (len == 16) { // "HH" (11 - 12) for (idx = 11; idx <= 12 && U_SUCCESS(status); idx++) { n = ASCII_DIGIT((int32_t)text[idx]); if (n >= 0) { hour = 10*hour + n; } else { status = U_INVALID_FORMAT_ERROR; } } // "mm" (14 - 15) for (idx = 14; idx <= 15 && U_SUCCESS(status); idx++) { n = ASCII_DIGIT((int32_t)text[idx]); if (n >= 0) { min = 10*min + n; } else { status = U_INVALID_FORMAT_ERROR; } } } if (U_SUCCESS(status)) { UDate date = Grego::fieldsToDay(year, month - 1, day) * U_MILLIS_PER_DAY + hour * U_MILLIS_PER_HOUR + min * U_MILLIS_PER_MINUTE; return date; } return 0; } static void U_CALLCONV initCanonicalIDCache(UErrorCode &status) { gCanonicalIDCache = uhash_open(uhash_hashUChars, uhash_compareUChars, NULL, &status); if (gCanonicalIDCache == NULL) { status = U_MEMORY_ALLOCATION_ERROR; } if (U_FAILURE(status)) { gCanonicalIDCache = NULL; } // No key/value deleters - keys/values are from a resource bundle ucln_i18n_registerCleanup(UCLN_I18N_ZONEMETA, zoneMeta_cleanup); } const UChar* U_EXPORT2 ZoneMeta::getCanonicalCLDRID(const UnicodeString &tzid, UErrorCode& status) { if (U_FAILURE(status)) { return NULL; } if (tzid.isBogus() || tzid.length() > ZID_KEY_MAX) { status = U_ILLEGAL_ARGUMENT_ERROR; return NULL; } // Checking the cached results umtx_initOnce(gCanonicalIDCacheInitOnce, &initCanonicalIDCache, status); if (U_FAILURE(status)) { return NULL; } const UChar *canonicalID = NULL; UErrorCode tmpStatus = U_ZERO_ERROR; UChar utzid[ZID_KEY_MAX + 1]; tzid.extract(utzid, ZID_KEY_MAX + 1, tmpStatus); U_ASSERT(tmpStatus == U_ZERO_ERROR); // we checked the length of tzid already if (!uprv_isInvariantUString(utzid, -1)) { // All of known tz IDs are only containing ASCII invariant characters. status = U_ILLEGAL_ARGUMENT_ERROR; return NULL; } // Check if it was already cached umtx_lock(gZoneMetaLock()); { canonicalID = (const UChar *)uhash_get(gCanonicalIDCache, utzid); } umtx_unlock(gZoneMetaLock()); if (canonicalID != NULL) { return canonicalID; } // If not, resolve CLDR canonical ID with resource data UBool isInputCanonical = FALSE; char id[ZID_KEY_MAX + 1]; tzid.extract(0, 0x7fffffff, id, UPRV_LENGTHOF(id), US_INV); // replace '/' with ':' char *p = id; while (*p++) { if (*p == '/') { *p = ':'; } } UResourceBundle *top = ures_openDirect(NULL, gKeyTypeData, &tmpStatus); UResourceBundle *rb = ures_getByKey(top, gTypeMapTag, NULL, &tmpStatus); ures_getByKey(rb, gTimezoneTag, rb, &tmpStatus); ures_getByKey(rb, id, rb, &tmpStatus); if (U_SUCCESS(tmpStatus)) { // type entry (canonical) found // the input is the canonical ID. resolve to const UChar* canonicalID = TimeZone::findID(tzid); isInputCanonical = TRUE; } if (canonicalID == NULL) { // If a map element not found, then look for an alias tmpStatus = U_ZERO_ERROR; ures_getByKey(top, gTypeAliasTag, rb, &tmpStatus); ures_getByKey(rb, gTimezoneTag, rb, &tmpStatus); const UChar *canonical = ures_getStringByKey(rb,id,NULL,&tmpStatus); if (U_SUCCESS(tmpStatus)) { // canonical map found canonicalID = canonical; } if (canonicalID == NULL) { // Dereference the input ID using the tz data const UChar *derefer = TimeZone::dereferOlsonLink(tzid); if (derefer == NULL) { status = U_ILLEGAL_ARGUMENT_ERROR; } else { int32_t len = u_strlen(derefer); u_UCharsToChars(derefer,id,len); id[len] = (char) 0; // Make sure it is null terminated. // replace '/' with ':' char *q = id; while (*q++) { if (*q == '/') { *q = ':'; } } // If a dereference turned something up then look for an alias. // rb still points to the alias table, so we don't have to go looking // for it. tmpStatus = U_ZERO_ERROR; canonical = ures_getStringByKey(rb,id,NULL,&tmpStatus); if (U_SUCCESS(tmpStatus)) { // canonical map for the dereferenced ID found canonicalID = canonical; } else { canonicalID = derefer; isInputCanonical = TRUE; } } } } ures_close(rb); ures_close(top); if (U_SUCCESS(status)) { U_ASSERT(canonicalID != NULL); // canocanilD must be non-NULL here // Put the resolved canonical ID to the cache umtx_lock(gZoneMetaLock()); { const UChar* idInCache = (const UChar *)uhash_get(gCanonicalIDCache, utzid); if (idInCache == NULL) { const UChar* key = ZoneMeta::findTimeZoneID(tzid); U_ASSERT(key != NULL); if (key != NULL) { idInCache = (const UChar *)uhash_put(gCanonicalIDCache, (void *)key, (void *)canonicalID, &status); U_ASSERT(idInCache == NULL); } } if (U_SUCCESS(status) && isInputCanonical) { // Also put canonical ID itself into the cache if not exist const UChar *canonicalInCache = (const UChar*)uhash_get(gCanonicalIDCache, canonicalID); if (canonicalInCache == NULL) { canonicalInCache = (const UChar *)uhash_put(gCanonicalIDCache, (void *)canonicalID, (void *)canonicalID, &status); U_ASSERT(canonicalInCache == NULL); } } } umtx_unlock(gZoneMetaLock()); } return canonicalID; } UnicodeString& U_EXPORT2 ZoneMeta::getCanonicalCLDRID(const UnicodeString &tzid, UnicodeString &systemID, UErrorCode& status) { const UChar *canonicalID = getCanonicalCLDRID(tzid, status); if (U_FAILURE(status) || canonicalID == NULL) { systemID.setToBogus(); return systemID; } systemID.setTo(TRUE, canonicalID, -1); return systemID; } const UChar* U_EXPORT2 ZoneMeta::getCanonicalCLDRID(const TimeZone& tz) { if (dynamic_cast(&tz) != NULL) { // short cut for OlsonTimeZone const OlsonTimeZone *otz = (const OlsonTimeZone*)&tz; return otz->getCanonicalID(); } UErrorCode status = U_ZERO_ERROR; UnicodeString tzID; return getCanonicalCLDRID(tz.getID(tzID), status); } static void U_CALLCONV countryInfoVectorsInit(UErrorCode &status) { // Create empty vectors // No deleters for these UVectors, it's a reference to a resource bundle string. gSingleZoneCountries = new UVector(NULL, uhash_compareUChars, status); if (gSingleZoneCountries == NULL) { status = U_MEMORY_ALLOCATION_ERROR; } gMultiZonesCountries = new UVector(NULL, uhash_compareUChars, status); if (gMultiZonesCountries == NULL) { status = U_MEMORY_ALLOCATION_ERROR; } if (U_FAILURE(status)) { delete gSingleZoneCountries; delete gMultiZonesCountries; gSingleZoneCountries = NULL; gMultiZonesCountries = NULL; } ucln_i18n_registerCleanup(UCLN_I18N_ZONEMETA, zoneMeta_cleanup); } UnicodeString& U_EXPORT2 ZoneMeta::getCanonicalCountry(const UnicodeString &tzid, UnicodeString &country, UBool *isPrimary /* = NULL */) { if (isPrimary != NULL) { *isPrimary = FALSE; } const UChar *region = TimeZone::getRegion(tzid); if (region != NULL && u_strcmp(gWorld, region) != 0) { country.setTo(region, -1); } else { country.setToBogus(); return country; } if (isPrimary != NULL) { char regionBuf[] = {0, 0, 0}; // Checking the cached results UErrorCode status = U_ZERO_ERROR; umtx_initOnce(gCountryInfoVectorsInitOnce, &countryInfoVectorsInit, status); if (U_FAILURE(status)) { return country; } // Check if it was already cached UBool cached = FALSE; UBool singleZone = FALSE; umtx_lock(gZoneMetaLock()); { singleZone = cached = gSingleZoneCountries->contains((void*)region); if (!cached) { cached = gMultiZonesCountries->contains((void*)region); } } umtx_unlock(gZoneMetaLock()); if (!cached) { // We need to go through all zones associated with the region. // This is relatively heavy operation. U_ASSERT(u_strlen(region) == 2); u_UCharsToChars(region, regionBuf, 2); StringEnumeration *ids = TimeZone::createTimeZoneIDEnumeration(UCAL_ZONE_TYPE_CANONICAL_LOCATION, regionBuf, NULL, status); int32_t idsLen = ids->count(status); if (U_SUCCESS(status) && idsLen == 1) { // only the single zone is available for the region singleZone = TRUE; } delete ids; // Cache the result umtx_lock(gZoneMetaLock()); { UErrorCode ec = U_ZERO_ERROR; if (singleZone) { if (!gSingleZoneCountries->contains((void*)region)) { gSingleZoneCountries->addElement((void*)region, ec); } } else { if (!gMultiZonesCountries->contains((void*)region)) { gMultiZonesCountries->addElement((void*)region, ec); } } } umtx_unlock(gZoneMetaLock()); } if (singleZone) { *isPrimary = TRUE; } else { // Note: We may cache the primary zone map in future. // Even a country has multiple zones, one of them might be // dominant and treated as a primary zone int32_t idLen = 0; if (regionBuf[0] == 0) { u_UCharsToChars(region, regionBuf, 2); } UResourceBundle *rb = ures_openDirect(NULL, gMetaZones, &status); ures_getByKey(rb, gPrimaryZonesTag, rb, &status); const UChar *primaryZone = ures_getStringByKey(rb, regionBuf, &idLen, &status); if (U_SUCCESS(status)) { if (tzid.compare(primaryZone, idLen) == 0) { *isPrimary = TRUE; } else { // The given ID might not be a canonical ID UnicodeString canonicalID; TimeZone::getCanonicalID(tzid, canonicalID, status); if (U_SUCCESS(status) && canonicalID.compare(primaryZone, idLen) == 0) { *isPrimary = TRUE; } } } ures_close(rb); } } return country; } UnicodeString& U_EXPORT2 ZoneMeta::getMetazoneID(const UnicodeString &tzid, UDate date, UnicodeString &result) { UBool isSet = FALSE; const UVector *mappings = getMetazoneMappings(tzid); if (mappings != NULL) { for (int32_t i = 0; i < mappings->size(); i++) { OlsonToMetaMappingEntry *mzm = (OlsonToMetaMappingEntry*)mappings->elementAt(i); if (mzm->from <= date && mzm->to > date) { result.setTo(mzm->mzid, -1); isSet = TRUE; break; } } } if (!isSet) { result.setToBogus(); } return result; } static void U_CALLCONV olsonToMetaInit(UErrorCode &status) { U_ASSERT(gOlsonToMeta == NULL); ucln_i18n_registerCleanup(UCLN_I18N_ZONEMETA, zoneMeta_cleanup); gOlsonToMeta = uhash_open(uhash_hashUChars, uhash_compareUChars, NULL, &status); if (U_FAILURE(status)) { gOlsonToMeta = NULL; } else { uhash_setKeyDeleter(gOlsonToMeta, deleteUCharString); uhash_setValueDeleter(gOlsonToMeta, deleteUVector); } } const UVector* U_EXPORT2 ZoneMeta::getMetazoneMappings(const UnicodeString &tzid) { UErrorCode status = U_ZERO_ERROR; UChar tzidUChars[ZID_KEY_MAX + 1]; tzid.extract(tzidUChars, ZID_KEY_MAX + 1, status); if (U_FAILURE(status) || status == U_STRING_NOT_TERMINATED_WARNING) { return NULL; } umtx_initOnce(gOlsonToMetaInitOnce, &olsonToMetaInit, status); if (U_FAILURE(status)) { return NULL; } // get the mapping from cache const UVector *result = NULL; umtx_lock(gZoneMetaLock()); { result = (UVector*) uhash_get(gOlsonToMeta, tzidUChars); } umtx_unlock(gZoneMetaLock()); if (result != NULL) { return result; } // miss the cache - create new one UVector *tmpResult = createMetazoneMappings(tzid); if (tmpResult == NULL) { // not available return NULL; } // put the new one into the cache umtx_lock(gZoneMetaLock()); { // make sure it's already created result = (UVector*) uhash_get(gOlsonToMeta, tzidUChars); if (result == NULL) { // add the one just created int32_t tzidLen = tzid.length() + 1; UChar *key = (UChar*)uprv_malloc(tzidLen * sizeof(UChar)); if (key == NULL) { // memory allocation error.. just return NULL result = NULL; delete tmpResult; } else { tzid.extract(key, tzidLen, status); uhash_put(gOlsonToMeta, key, tmpResult, &status); if (U_FAILURE(status)) { // delete the mapping result = NULL; delete tmpResult; } else { result = tmpResult; } } } else { // another thread already put the one delete tmpResult; } } umtx_unlock(gZoneMetaLock()); return result; } UVector* ZoneMeta::createMetazoneMappings(const UnicodeString &tzid) { UVector *mzMappings = NULL; UErrorCode status = U_ZERO_ERROR; UnicodeString canonicalID; UResourceBundle *rb = ures_openDirect(NULL, gMetaZones, &status); ures_getByKey(rb, gMetazoneInfo, rb, &status); getCanonicalCLDRID(tzid, canonicalID, status); if (U_SUCCESS(status)) { char tzKey[ZID_KEY_MAX + 1]; int32_t tzKeyLen = canonicalID.extract(0, canonicalID.length(), tzKey, sizeof(tzKey), US_INV); tzKey[tzKeyLen] = 0; // tzid keys are using ':' as separators char *p = tzKey; while (*p) { if (*p == '/') { *p = ':'; } p++; } ures_getByKey(rb, tzKey, rb, &status); if (U_SUCCESS(status)) { UResourceBundle *mz = NULL; while (ures_hasNext(rb)) { mz = ures_getNextResource(rb, mz, &status); const UChar *mz_name = ures_getStringByIndex(mz, 0, NULL, &status); const UChar *mz_from = gDefaultFrom; const UChar *mz_to = gDefaultTo; if (ures_getSize(mz) == 3) { mz_from = ures_getStringByIndex(mz, 1, NULL, &status); mz_to = ures_getStringByIndex(mz, 2, NULL, &status); } if(U_FAILURE(status)){ status = U_ZERO_ERROR; continue; } // We do not want to use SimpleDateformat to parse boundary dates, // because this code could be triggered by the initialization code // used by SimpleDateFormat. UDate from = parseDate(mz_from, status); UDate to = parseDate(mz_to, status); if (U_FAILURE(status)) { status = U_ZERO_ERROR; continue; } OlsonToMetaMappingEntry *entry = (OlsonToMetaMappingEntry*)uprv_malloc(sizeof(OlsonToMetaMappingEntry)); if (entry == NULL) { status = U_MEMORY_ALLOCATION_ERROR; break; } entry->mzid = mz_name; entry->from = from; entry->to = to; if (mzMappings == NULL) { mzMappings = new UVector(deleteOlsonToMetaMappingEntry, NULL, status); if (U_FAILURE(status)) { delete mzMappings; mzMappings = NULL; uprv_free(entry); break; } } mzMappings->addElement(entry, status); if (U_FAILURE(status)) { break; } } ures_close(mz); if (U_FAILURE(status)) { if (mzMappings != NULL) { delete mzMappings; mzMappings = NULL; } } } } ures_close(rb); return mzMappings; } UnicodeString& U_EXPORT2 ZoneMeta::getZoneIdByMetazone(const UnicodeString &mzid, const UnicodeString ®ion, UnicodeString &result) { UErrorCode status = U_ZERO_ERROR; const UChar *tzid = NULL; int32_t tzidLen = 0; char keyBuf[ZID_KEY_MAX + 1]; int32_t keyLen = 0; if (mzid.isBogus() || mzid.length() > ZID_KEY_MAX) { result.setToBogus(); return result; } keyLen = mzid.extract(0, mzid.length(), keyBuf, ZID_KEY_MAX + 1, US_INV); keyBuf[keyLen] = 0; UResourceBundle *rb = ures_openDirect(NULL, gMetaZones, &status); ures_getByKey(rb, gMapTimezonesTag, rb, &status); ures_getByKey(rb, keyBuf, rb, &status); if (U_SUCCESS(status)) { // check region mapping if (region.length() == 2 || region.length() == 3) { keyLen = region.extract(0, region.length(), keyBuf, ZID_KEY_MAX + 1, US_INV); keyBuf[keyLen] = 0; tzid = ures_getStringByKey(rb, keyBuf, &tzidLen, &status); if (status == U_MISSING_RESOURCE_ERROR) { status = U_ZERO_ERROR; } } if (U_SUCCESS(status) && tzid == NULL) { // try "001" tzid = ures_getStringByKey(rb, gWorldTag, &tzidLen, &status); } } ures_close(rb); if (tzid == NULL) { result.setToBogus(); } else { result.setTo(tzid, tzidLen); } return result; } static void U_CALLCONV initAvailableMetaZoneIDs () { U_ASSERT(gMetaZoneIDs == NULL); U_ASSERT(gMetaZoneIDTable == NULL); ucln_i18n_registerCleanup(UCLN_I18N_ZONEMETA, zoneMeta_cleanup); UErrorCode status = U_ZERO_ERROR; gMetaZoneIDTable = uhash_open(uhash_hashUnicodeString, uhash_compareUnicodeString, NULL, &status); if (U_FAILURE(status) || gMetaZoneIDTable == NULL) { gMetaZoneIDTable = NULL; return; } uhash_setKeyDeleter(gMetaZoneIDTable, uprv_deleteUObject); // No valueDeleter, because the vector maintain the value objects gMetaZoneIDs = new UVector(NULL, uhash_compareUChars, status); if (U_FAILURE(status) || gMetaZoneIDs == NULL) { gMetaZoneIDs = NULL; uhash_close(gMetaZoneIDTable); gMetaZoneIDTable = NULL; return; } gMetaZoneIDs->setDeleter(uprv_free); UResourceBundle *rb = ures_openDirect(NULL, gMetaZones, &status); UResourceBundle *bundle = ures_getByKey(rb, gMapTimezonesTag, NULL, &status); StackUResourceBundle res; while (U_SUCCESS(status) && ures_hasNext(bundle)) { ures_getNextResource(bundle, res.getAlias(), &status); if (U_FAILURE(status)) { break; } const char *mzID = ures_getKey(res.getAlias()); int32_t len = static_cast(uprv_strlen(mzID)); UChar *uMzID = (UChar*)uprv_malloc(sizeof(UChar) * (len + 1)); if (uMzID == NULL) { status = U_MEMORY_ALLOCATION_ERROR; break; } u_charsToUChars(mzID, uMzID, len); uMzID[len] = 0; UnicodeString *usMzID = new UnicodeString(uMzID); if (uhash_get(gMetaZoneIDTable, usMzID) == NULL) { gMetaZoneIDs->addElement((void *)uMzID, status); uhash_put(gMetaZoneIDTable, (void *)usMzID, (void *)uMzID, &status); } else { uprv_free(uMzID); delete usMzID; } } ures_close(bundle); ures_close(rb); if (U_FAILURE(status)) { uhash_close(gMetaZoneIDTable); delete gMetaZoneIDs; gMetaZoneIDTable = NULL; gMetaZoneIDs = NULL; } } const UVector* ZoneMeta::getAvailableMetazoneIDs() { umtx_initOnce(gMetaZoneIDsInitOnce, &initAvailableMetaZoneIDs); return gMetaZoneIDs; } const UChar* ZoneMeta::findMetaZoneID(const UnicodeString& mzid) { umtx_initOnce(gMetaZoneIDsInitOnce, &initAvailableMetaZoneIDs); if (gMetaZoneIDTable == NULL) { return NULL; } return (const UChar*)uhash_get(gMetaZoneIDTable, &mzid); } const UChar* ZoneMeta::findTimeZoneID(const UnicodeString& tzid) { return TimeZone::findID(tzid); } TimeZone* ZoneMeta::createCustomTimeZone(int32_t offset) { UBool negative = FALSE; int32_t tmp = offset; if (offset < 0) { negative = TRUE; tmp = -offset; } uint8_t hour, min, sec; tmp /= 1000; sec = static_cast(tmp % 60); tmp /= 60; min = static_cast(tmp % 60); hour = static_cast(tmp / 60); UnicodeString zid; formatCustomID(hour, min, sec, negative, zid); return new SimpleTimeZone(offset, zid); } UnicodeString& ZoneMeta::formatCustomID(uint8_t hour, uint8_t min, uint8_t sec, UBool negative, UnicodeString& id) { // Create normalized time zone ID - GMT[+|-]HH:mm[:ss] id.setTo(gCustomTzPrefix, -1); if (hour != 0 || min != 0) { if (negative) { id.append((UChar)0x2D); // '-' } else { id.append((UChar)0x2B); // '+' } // Always use US-ASCII digits id.append((UChar)(0x30 + (hour%100)/10)); id.append((UChar)(0x30 + (hour%10))); id.append((UChar)0x3A); // ':' id.append((UChar)(0x30 + (min%100)/10)); id.append((UChar)(0x30 + (min%10))); if (sec != 0) { id.append((UChar)0x3A); // ':' id.append((UChar)(0x30 + (sec%100)/10)); id.append((UChar)(0x30 + (sec%10))); } } return id; } const UChar* ZoneMeta::getShortID(const TimeZone& tz) { const UChar* canonicalID = NULL; if (dynamic_cast(&tz) != NULL) { // short cut for OlsonTimeZone const OlsonTimeZone *otz = (const OlsonTimeZone*)&tz; canonicalID = otz->getCanonicalID(); } if (canonicalID == NULL) { return NULL; } return getShortIDFromCanonical(canonicalID); } const UChar* ZoneMeta::getShortID(const UnicodeString& id) { UErrorCode status = U_ZERO_ERROR; const UChar* canonicalID = ZoneMeta::getCanonicalCLDRID(id, status); if (U_FAILURE(status) || canonicalID == NULL) { return NULL; } return ZoneMeta::getShortIDFromCanonical(canonicalID); } const UChar* ZoneMeta::getShortIDFromCanonical(const UChar* canonicalID) { const UChar* shortID = NULL; int32_t len = u_strlen(canonicalID); char tzidKey[ZID_KEY_MAX + 1]; u_UCharsToChars(canonicalID, tzidKey, len); tzidKey[len] = (char) 0; // Make sure it is null terminated. // replace '/' with ':' char *p = tzidKey; while (*p++) { if (*p == '/') { *p = ':'; } } UErrorCode status = U_ZERO_ERROR; UResourceBundle *rb = ures_openDirect(NULL, gKeyTypeData, &status); ures_getByKey(rb, gTypeMapTag, rb, &status); ures_getByKey(rb, gTimezoneTag, rb, &status); shortID = ures_getStringByKey(rb, tzidKey, NULL, &status); ures_close(rb); return shortID; } U_NAMESPACE_END #endif /* #if !UCONFIG_NO_FORMATTING */ #include "includes/Timer.h" namespace alib { Timer::Timer(size_t r_time):run_time(r_time){} /* Starts/resets the timer. */ void Timer::begin() { #ifdef __linux__ struct timeval now; gettimeofday(&now, NULL); start_time = SECONDS_TO_MILLIS(now.tv_sec) + MICROS_TO_MILLIS(now.tv_usec); #else start_time = millis(); #endif rang = false; } /* Checks to see if the timer has rung. */ bool Timer::check() { if(rang)return(rang); #ifdef __linux__ struct timeval now; gettimeofday(&now, NULL); unsigned long long curMillis = SECONDS_TO_MILLIS(now.tv_sec) + MICROS_TO_MILLIS(now.tv_usec); rang = (curMillis - start_time) >= run_time; #else rang = (millis() - start_time) >= run_time; #endif return(rang); } /* Setters */ /* Sets the run time (in milliseconds) for the timer. */ void Timer::setRunTime(size_t r_time){run_time = r_time;} /***********/ } SoniaZotz/IOsonata10-100 /*--------------------------------------------------------------------------- File : usb_hidhost.cpp Author : Jan. 16, 2009 Desc : Generic class of USB HID device access Copyright (c) 2009, I-SYST, all rights reserved Permission to use, copy, modify, and 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, and none of the names : I-SYST, TidalStream or 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 REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ---------------------------------------------------------------------------- Modified by Date Description Hoan juin 2009 Ekomini ----------------------------------------------------------------------------*/ #include "usb_hidhost_impl.h" UsbHidDevice *UsbHidDevice::Create() { //return new UsbHidDevice_Impl; return NULL; } #include #include #include #include "TextToSpeech/CTextToSpeech.hpp" #include "TextToSpeech/CTextToSpeechConfig.hpp" #include "logging/Log.hpp" namespace NTextToSpeach { CTextToSpeech&CTextToSpeech::getInstance(const CTextToSpeechConfig& config) { static CTextToSpeech instance(config); return instance; } CTextToSpeech::CTextToSpeech(const CTextToSpeechConfig& config) : mConfig(config) , mState(QTextToSpeech::Ready) { if (mConfig.mEngine.isEmpty()) { mSpeech.reset(new QTextToSpeech); } else { mSpeech.reset(new QTextToSpeech(mConfig.mEngine)); } connect(mSpeech.get(), &QTextToSpeech::stateChanged, this, &CTextToSpeech::stateChanged); { if (mConfig.mLocaleId >= 0) { QVector locales = mSpeech->availableLocales(); if (mConfig.mLocaleId < locales.size()) { mSpeech->setLocale(locales[mConfig.mLocaleId]); } } if (mConfig.mVoiceId >= 0) { QVector voices = mSpeech->availableVoices(); if (mConfig.mVoiceId < voices.size()) { mSpeech->setVoice(voices[mConfig.mVoiceId]); } } } } void CTextToSpeech::say(const QString& str) { if (mState != QTextToSpeech::Speaking) { mState = QTextToSpeech::Speaking; mSpeech->say(str); } } void CTextToSpeech::stateChanged(QTextToSpeech::State state) { mState = state; } } YangKian/LogDevice /** * Copyright (c) 2017-present, Facebook, Inc. and its affiliates. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. */ #include "logdevice/common/TLSCredMonitor.h" #include "logdevice/common/SSLFetcher.h" #include "logdevice/common/Worker.h" #include "logdevice/common/request_util.h" namespace facebook { namespace logdevice { void TLSCredMonitor::postToAllWorkers(std::function func) { processor_->applyToWorkers([&](Worker& worker) { auto f = func; auto req = FuncRequest::make(worker.idx_, worker.worker_type_, RequestType::TLS_CRED_MONITOR, std::move(f)); processor_->postImportant(req); }); } void TLSCredMonitor::onCertificatesUpdated() { postToAllWorkers([]() { Worker* w = Worker::onThisThread(); w->sslFetcher().reloadSSLContext(); }); } }} // namespace facebook::logdevice #include "bits/stdc++.h" using namespace std; int map[8][8]; int main(){ int n, m, t, input; cin >> n >> m >> vector> arr(n,vector(m)); for(int i=0;i> map[i][j]; if(map[i][j]=="s"){ sx = i; sy = j; }else if(map[i][j]=="p"){ px = i; py = j; } } } bool win = false; int step = 0; int posx, posy; } // Copyright (C) 2001-2003 // // // Permission to use, copy, modify, distribute and sell this software // and its documentation for any purpose is hereby granted without fee, // provided that the above copyright notice appear in all copies and // that both that copyright notice and this permission notice appear // in supporting documentation. makes no representations // about the suitability of this software for any purpose. // It is provided "as is" without express or implied warranty. #ifndef BOOST_THREAD_CONFIG_WEK01032003_HPP #define BOOST_THREAD_CONFIG_WEK01032003_HPP #include // insist on threading support being available: #include #if defined(BOOST_HAS_WINTHREADS) # if defined(BOOST_THREAD_BUILD_DLL) //Build dll # define BOOST_THREAD_DECL __declspec(dllexport) # elif defined(BOOST_THREAD_BUILD_LIB) //Build lib # define BOOST_THREAD_DECL # elif defined(BOOST_THREAD_USE_DLL) //Use dll # define BOOST_THREAD_DECL __declspec(dllimport) # define BOOST_DYN_LINK # elif defined(BOOST_THREAD_USE_LIB) //Use lib # define BOOST_THREAD_DECL # else //Use default # if defined(BOOST_MSVC) || defined(BOOST_INTEL_WIN) //For VC++, choose according to threading library setting # if defined(_DLL) //Threading library is dll: use Boost.Threads dll # define BOOST_THREAD_USE_DLL # define BOOST_THREAD_DECL __declspec(dllimport) # define BOOST_DYN_LINK # else //Threading library is lib: used Boost.Threads lib # define BOOST_THREAD_USE_LIB # define BOOST_THREAD_DECL # endif # else //For compilers not yet supporting auto-tss cleanup //with Boost.Threads lib, use Boost.Threads dll # define BOOST_THREAD_USE_DLL # define BOOST_THREAD_DECL __declspec(dllimport) # define BOOST_DYN_LINK # endif # endif #else # define BOOST_THREAD_DECL # if defined(BOOST_THREAD_USE_LIB) //Use dll # define BOOST_THREAD_USE_DLL # define BOOST_DYN_LINK # elif defined(BOOST_THREAD_USE_DLL) //Use lib # define BOOST_THREAD_USE_LIB # else //Use default # define BOOST_THREAD_USE_LIB # endif #endif // BOOST_HAS_WINTHREADS // // Automatically link to the correct build variant where possible. // #if !defined(BOOST_ALL_NO_LIB) && !defined(BOOST_THREAD_NO_LIB) && !defined(BOOST_THREAD_BUILD_DLL) && !defined(BOOST_THREAD_BUILD_LIB) // // Set the name of our library, this will get undef'ed by auto_link.hpp // once it's done with it: // #if defined(BOOST_THREAD_LIB_NAME) # define BOOST_LIB_NAME BOOST_THREAD_LIB_NAME #else # define BOOST_LIB_NAME boost_thread #endif // // If we're importing code from a dll, then tell auto_link.hpp about it: // // And include the header that does the work: // #include #endif // auto-linking disabled #endif // BOOST_THREAD_CONFIG_WEK1032003_HPP RaresAil/rpi-pico-esp-cpp0 #include unsigned char hexval(unsigned char c) { if ('0' <= c && c <= '9') { return c - '0'; } else if ('a' <= c && c <= 'f') { return c - 'a' + 10; } else if ('A' <= c && c <= 'F') { return c - 'A' + 10; } else { return '\0'; } } std::string hex2ascii(const std::string& in) { std::string output; output.reserve(in.length() / 2); for (std::string::const_iterator p = in.begin(); p != in.end(); p++) { unsigned char c = hexval(*p); p++; if (p == in.end()) { break; } c = (c << 4) + hexval(*p); output.push_back(c); } return output; } src/box2d/Box2DExample.cpp /* This file is part of Magnum. Original authors — credit is appreciated but not required: 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019 — <> 2018 — <> This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law. 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 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 #include namespace Magnum { namespace Examples { typedef SceneGraph::Object Object2D; typedef SceneGraph::Scene Scene2D; using namespace Math::Literals; class Box2DExample: public Platform::Application { public: explicit Box2DExample(const Arguments& arguments); private: void drawEvent() override; void mousePressEvent(MouseEvent& event) override; b2Body* createBody(Object2D& object, const Vector2& size, b2BodyType type, const DualComplex& transformation, Float density = 1.0f); GL::Mesh _mesh{NoCreate}; Shaders::Flat2D _shader{NoCreate}; Scene2D _scene; Object2D* _cameraObject; SceneGraph::Camera2D* _camera; SceneGraph::DrawableGroup2D _drawables; Containers::Optional _world; }; class BoxDrawable: public SceneGraph::Drawable2D { public: explicit BoxDrawable(Object2D& object, GL::Mesh& mesh, Shaders::Flat2D& shader, const Color4& color, SceneGraph::DrawableGroup2D& drawables): SceneGraph::Drawable2D{object, &drawables}, _mesh(mesh), _shader(shader), _color{color} {} private: void draw(const Matrix3& transformationMatrix, SceneGraph::Camera2D& camera) override { _shader .setTransformationProjectionMatrix(camera.projectionMatrix()*transformationMatrix) .setColor(_color); _mesh.draw(_shader); } GL::Mesh& _mesh; Shaders::Flat2D& _shader; Color4 _color; }; b2Body* Box2DExample::createBody(Object2D& object, const Vector2& halfSize, const b2BodyType type, const DualComplex& transformation, const Float density) { b2BodyDef bodyDefinition; bodyDefinition.position.Set(transformation.translation().x(), transformation.translation().y()); bodyDefinition.angle = Float(transformation.rotation().angle()); bodyDefinition.type = type; b2Body* body = _world->CreateBody(&bodyDefinition); b2PolygonShape shape; shape.SetAsBox(halfSize.x(), halfSize.y()); b2FixtureDef fixture; fixture.friction = 0.8f; fixture.density = density; fixture.shape = &shape; body->CreateFixture(&fixture); body->SetUserData(&object); object.setScaling(halfSize); return body; } Box2DExample::Box2DExample(const Arguments& arguments): Platform::Application{arguments, NoCreate} { /* Make it possible for the user to have some fun */ Utility::Arguments args; args.addOption("transformation", "1 0 0 0").setHelp("transformation", "initial pyramid transformation") .addSkippedPrefix("magnum", "engine-specific options") .parse(arguments.argc, arguments.argv); const DualComplex globalTransformation = args.value("transformation").normalized(); /* Try 8x MSAA, fall back to zero samples if not possible. Enable only 2x MSAA if we have enough DPI. */ { const Vector2 dpiScaling = this->dpiScaling({}); Configuration conf; conf.setTitle("Magnum Box2D Example") .setSize(conf.size(), dpiScaling); GLConfiguration glConf; glConf.setSampleCount(dpiScaling.max() < 2.0f ? 8 : 2); if(!tryCreate(conf, glConf)) create(conf, glConf.setSampleCount(0)); } /* Configure camera */ _cameraObject = new Object2D{&_scene}; _camera = new SceneGraph::Camera2D{*_cameraObject}; _camera->setAspectRatioPolicy(SceneGraph::AspectRatioPolicy::Extend) .setProjectionMatrix(Matrix3::projection({20.0f, 20.0f})) .setViewport(GL::defaultFramebuffer.viewport().size()); /* Create the Box2D world with the usual gravity vector */ _world.emplace(b2Vec2{0.0f, -9.81f}); /* Create the shader and the box mesh */ _shader = Shaders::Flat2D{}; _mesh = MeshTools::compile(Primitives::squareSolid()); /* Create the ground */ auto ground = new Object2D{&_scene}; createBody(*ground, {11.0f, 0.5f}, b2_staticBody, DualComplex::translation(Vector2::yAxis(-8.0f))); new BoxDrawable{*ground, _mesh, _shader, 0xa5c9ea_rgbf, _drawables}; /* Create a pyramid of boxes */ for(std::size_t row = 0; row != 15; ++row) { for(std::size_t item = 0; item != 15 - row; ++item) { auto box = new Object2D{&_scene}; const DualComplex transformation = globalTransformation*DualComplex::translation( {Float(row)*0.6f + Float(item)*1.2f - 8.5f, Float(row)*1.0f - 6.0f}); createBody(*box, {0.5f, 0.5f}, b2_dynamicBody, transformation); new BoxDrawable{*box, _mesh, _shader, 0x2f83cc_rgbf, _drawables}; } } setSwapInterval(1); #if !defined(CORRADE_TARGET_EMSCRIPTEN) && !defined(CORRADE_TARGET_ANDROID) setMinimalLoopPeriod(16); #endif } void Box2DExample::mousePressEvent(MouseEvent& event) { if(event.button() != MouseEvent::Button::Left) return; /* Calculate mouse position in the Box2D world. Make it relative to window, with origin at center and then scale to world size with Y inverted. */ const auto position = _camera->projectionSize()*Vector2::yScale(-1.0f)*(Vector2{event.position()}/Vector2{windowSize()} - Vector2{0.5f}); auto destroyer = new Object2D{&_scene}; createBody(*destroyer, {0.5f, 0.5f}, b2_dynamicBody, DualComplex::translation(position), 2.0f); new BoxDrawable{*destroyer, _mesh, _shader, 0xffff66_rgbf, _drawables}; } void Box2DExample::drawEvent() { GL::defaultFramebuffer.clear(GL::FramebufferClear::Color); /* Step the world and update all object positions */ _world->Step(1.0f/60.0f, 6, 2); for(b2Body* body = _world->GetBodyList(); body; body = body->GetNext()) (*static_cast(body->GetUserData())) .setTranslation({body->GetPosition().x, body->GetPosition().y}) .setRotation(Complex::rotation(Rad(body->GetAngle()))); _camera->draw(_drawables); swapBuffers(); redraw(); } }} MAGNUM_APPLICATION_MAIN(Magnum::Examples::Box2DExample) #include "Engine.h" #pragma comment(lib, "d3d11.lib") #pragma comment(lib, "DirectXTK.lib") int APIENTRY wWinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPWSTR lpCmdLine, _In_ int nCmdShow) { Engine engine; engine.Init(hInstance, "Title", "WNDClass", 800, 600); while (engine.ProcessEvents()) { engine.Update(); } return 0; }Nurzamal/rest_api_docker /* $Id: VBoxNetBaseService.cpp 69500 2017-10-28 15:14:05Z vboxsync $ */ /** @file * VBoxNetBaseService - common services for VBoxNetDHCP and VBoxNetNAT. */ /* * Copyright (C) 2009-2017 Oracle Corporation * * This file is part of VirtualBox Open Source Edition (OSE), as * available from http://www.virtualbox.org. This file is free software; * you can redistribute it and/or modify it under the terms of the GNU * General Public License (GPL) as published by the Free Software * Foundation, in version 2 as it comes in the "COPYING" file of the * VirtualBox OSE distribution. VirtualBox OSE is distributed in the * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind. */ /********************************************************************************************************************************* * Header Files * *********************************************************************************************************************************/ #define LOG_GROUP LOG_GROUP_NET_SERVICE #include #include #include #include #include #include #include #include #include #include #include #include #include /* must come before getopt.h. */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "VBoxNetLib.h" #include "VBoxNetBaseService.h" #ifdef RT_OS_WINDOWS /* WinMain */ # include # include #endif /********************************************************************************************************************************* * Structures and Typedefs * *********************************************************************************************************************************/ struct VBoxNetBaseService::Data { Data(const std::string& aServiceName, const std::string& aNetworkName): m_ServiceName(aServiceName), m_NetworkName(aNetworkName), m_enmTrunkType(kIntNetTrunkType_WhateverNone), m_pSession(NIL_RTR0PTR), m_cbSendBuf(128 * _1K), m_cbRecvBuf(256 * _1K), m_hIf(INTNET_HANDLE_INVALID), m_pIfBuf(NULL), m_cVerbosity(0), m_fNeedMain(false), m_EventQ(NULL), m_hThrRecv(NIL_RTTHREAD), fShutdown(false) { int rc = RTCritSectInit(&m_csThis); AssertRC(rc); }; std::string m_ServiceName; std::string m_NetworkName; std::string m_TrunkName; INTNETTRUNKTYPE m_enmTrunkType; RTMAC m_MacAddress; RTNETADDRIPV4 m_Ipv4Address; RTNETADDRIPV4 m_Ipv4Netmask; PSUPDRVSESSION m_pSession; uint32_t m_cbSendBuf; uint32_t m_cbRecvBuf; INTNETIFHANDLE m_hIf; /**< The handle to the network interface. */ PINTNETBUF m_pIfBuf; /**< Interface buffer. */ std::vector m_vecOptionDefs; int32_t m_cVerbosity; /* cs for syncing */ RTCRITSECT m_csThis; /* Controls whether service will connect SVC for runtime needs */ bool m_fNeedMain; /* Event Queue */ com::NativeEventQueue *m_EventQ; /** receiving thread, used only if main is used */ RTTHREAD m_hThrRecv; bool fShutdown; static DECLCALLBACK(int) recvLoop(RTTHREAD, void *); }; /********************************************************************************************************************************* * Global Variables * *********************************************************************************************************************************/ /* Commonly used options for network configuration */ static RTGETOPTDEF g_aGetOptDef[] = { { "--name", 'N', RTGETOPT_REQ_STRING }, { "--network", 'n', RTGETOPT_REQ_STRING }, { "--trunk-name", 't', RTGETOPT_REQ_STRING }, { "--trunk-type", 'T', RTGETOPT_REQ_STRING }, { "--mac-address", 'a', RTGETOPT_REQ_MACADDR }, { "--ip-address", 'i', RTGETOPT_REQ_IPV4ADDR }, { "--netmask", 'm', RTGETOPT_REQ_IPV4ADDR }, { "--verbose", 'v', RTGETOPT_REQ_NOTHING }, { "--need-main", 'M', RTGETOPT_REQ_BOOL }, }; DECLCALLBACK(int) VBoxNetBaseService::Data::recvLoop(RTTHREAD, void *pvUser) { VBoxNetBaseService *pThis = static_cast(pvUser); HRESULT hrc = com::Initialize(); AssertComRCReturn(hrc, VERR_INTERNAL_ERROR); pThis->doReceiveLoop(); return VINF_SUCCESS; } VBoxNetBaseService::VBoxNetBaseService(const std::string& aName, const std::string& aNetworkName):m(NULL) { m = new VBoxNetBaseService::Data(aName, aNetworkName); for(unsigned int i = 0; i < RT_ELEMENTS(g_aGetOptDef); ++i) m->m_vecOptionDefs.push_back(&g_aGetOptDef[i]); } VBoxNetBaseService::~VBoxNetBaseService() { /* * Close the interface connection. */ if (m) { shutdown(); if (m->m_hIf != INTNET_HANDLE_INVALID) { INTNETIFCLOSEREQ CloseReq; CloseReq.Hdr.u32Magic = SUPVMMR0REQHDR_MAGIC; CloseReq.Hdr.cbReq = sizeof(CloseReq); CloseReq.pSession = m->m_pSession; CloseReq.hIf = m->m_hIf; m->m_hIf = INTNET_HANDLE_INVALID; int rc = SUPR3CallVMMR0Ex(NIL_RTR0PTR, NIL_VMCPUID, VMMR0_DO_INTNET_IF_CLOSE, 0, &CloseReq.Hdr); AssertRC(rc); } if (m->m_pSession != NIL_RTR0PTR) { SUPR3Term(false /*fForced*/); m->m_pSession = NIL_RTR0PTR; } RTCritSectDelete(&m->m_csThis); delete m; m = NULL; } } int VBoxNetBaseService::init() { if (isMainNeeded()) { HRESULT hrc = com::Initialize(); AssertComRCReturn(hrc, VERR_INTERNAL_ERROR); hrc = virtualboxClient.createInprocObject(CLSID_VirtualBoxClient); AssertComRCReturn(hrc, VERR_INTERNAL_ERROR); hrc = virtualboxClient->COMGETTER(VirtualBox)(virtualbox.asOutParam()); AssertComRCReturn(hrc, VERR_INTERNAL_ERROR); } return VINF_SUCCESS; } bool VBoxNetBaseService::isMainNeeded() const { return m->m_fNeedMain; } int VBoxNetBaseService::run() { /** * If the child class needs Main we start the receving thread which calls * doReceiveLoop and enter to event polling loop. For other clients we do * receiving on the current (main) thread. */ if (isMainNeeded()) return startReceiveThreadAndEnterEventLoop(); doReceiveLoop(); return VINF_SUCCESS; } /** * Parse the arguments. * * @returns 0 on success, fully bitched exit code on failure. * * @param argc Argument count. * @param argv Argument vector. * * @todo r=bird: The --help and --version options shall not return a * non-zero exit code. So, this method need to grow some * complexity. I'm to blame for that blunder :/ */ int VBoxNetBaseService::parseArgs(int argc, char **argv) { RTGETOPTSTATE State; PRTGETOPTDEF paOptionArray = getOptionsPtr(); int rc = RTGetOptInit(&State, argc, argv, paOptionArray, m->m_vecOptionDefs.size(), 0, 0 /*fFlags*/); AssertRCReturn(rc, 49); #if 0 /* default initialization */ m_enmTrunkType = kIntNetTrunkType_WhateverNone; #endif Log2(("BaseService: parseArgs enter\n")); for (;;) { RTGETOPTUNION Val; rc = RTGetOpt(&State, &Val); if (!rc) break; switch (rc) { case 'N': // --name m->m_ServiceName = Val.psz; break; case 'n': // --network m->m_NetworkName = Val.psz; break; case 't': //--trunk-name m->m_TrunkName = Val.psz; break; case 'T': //--trunk-type if (!strcmp(Val.psz, "none")) m->m_enmTrunkType = kIntNetTrunkType_None; else if (!strcmp(Val.psz, "whatever")) m->m_enmTrunkType = kIntNetTrunkType_WhateverNone; else if (!strcmp(Val.psz, "netflt")) m->m_enmTrunkType = kIntNetTrunkType_NetFlt; else if (!strcmp(Val.psz, "netadp")) m->m_enmTrunkType = kIntNetTrunkType_NetAdp; else if (!strcmp(Val.psz, "srvnat")) m->m_enmTrunkType = kIntNetTrunkType_SrvNat; else { RTStrmPrintf(g_pStdErr, "Invalid trunk type '%s'\n", Val.psz); return RTEXITCODE_SYNTAX; } break; case 'a': // --mac-address m->m_MacAddress = Val.MacAddr; break; case 'i': // --ip-address m->m_Ipv4Address = Val.IPv4Addr; break; case 'm': // --netmask m->m_Ipv4Netmask = Val.IPv4Addr; break; case 'v': // --verbose m->m_cVerbosity++; break; case 'V': // --version (missed) RTPrintf("%sr%u\n", RTBldCfgVersion(), RTBldCfgRevision()); return 1; /** @todo this exit code is wrong, of course. :/ */ case 'M': // --need-main m->m_fNeedMain = true; break; case 'h': // --help (missed) RTPrintf("%s Version %sr%u\n" "(C) 2009-" VBOX_C_YEAR " " VBOX_VENDOR "\n" "All rights reserved.\n" "\n" "Usage: %s \n" "\n" "Options:\n", RTProcShortName(), RTBldCfgVersion(), RTBldCfgRevision(), RTProcShortName()); for (unsigned int i = 0; i < m->m_vecOptionDefs.size(); i++) RTPrintf(" -%c, %s\n", m->m_vecOptionDefs[i]->iShort, m->m_vecOptionDefs[i]->pszLong); usage(); /* to print Service Specific usage */ return 1; /** @todo this exit code is wrong, of course. :/ */ default: { int rc1 = parseOpt(rc, Val); if (RT_FAILURE(rc1)) { RTEXITCODE rcExit = RTGetOptPrintError(rc, &Val); RTPrintf("Use --help for more information.\n"); return rcExit; } break; } } } RTMemFree(paOptionArray); return RTEXITCODE_SUCCESS; } int VBoxNetBaseService::tryGoOnline(void) { /* * Open the session, load ring-0 and issue the request. */ int rc = SUPR3Init(&m->m_pSession); if (RT_FAILURE(rc)) { m->m_pSession = NIL_RTR0PTR; LogRel(("VBoxNetBaseService: SUPR3Init -> %Rrc\n", rc)); return rc; } char szPath[RTPATH_MAX]; rc = RTPathExecDir(szPath, sizeof(szPath) - sizeof("/VMMR0.r0")); if (RT_FAILURE(rc)) { LogRel(("VBoxNetBaseService: RTPathExecDir -> %Rrc\n", rc)); return rc; } rc = SUPR3LoadVMM(strcat(szPath, "/VMMR0.r0")); if (RT_FAILURE(rc)) { LogRel(("VBoxNetBaseService: SUPR3LoadVMM(\"%s\") -> %Rrc\n", szPath, rc)); return rc; } /* * Create the open request. */ PINTNETBUF pBuf; INTNETOPENREQ OpenReq; OpenReq.Hdr.u32Magic = SUPVMMR0REQHDR_MAGIC; OpenReq.Hdr.cbReq = sizeof(OpenReq); OpenReq.pSession = m->m_pSession; RTStrCopy(OpenReq.szNetwork, sizeof(OpenReq.szNetwork), m->m_NetworkName.c_str()); OpenReq.szNetwork[sizeof(OpenReq.szNetwork) - 1] = '\0'; RTStrCopy(OpenReq.szTrunk, sizeof(OpenReq.szTrunk), m->m_TrunkName.c_str()); OpenReq.szTrunk[sizeof(OpenReq.szTrunk) - 1] = '\0'; OpenReq.enmTrunkType = m->m_enmTrunkType; OpenReq.fFlags = 0; /** @todo check this */ OpenReq.cbSend = m->m_cbSendBuf; OpenReq.cbRecv = m->m_cbRecvBuf; OpenReq.hIf = INTNET_HANDLE_INVALID; /* * Issue the request. */ Log2(("attempting to open/create network \"%s\"...\n", OpenReq.szNetwork)); rc = SUPR3CallVMMR0Ex(NIL_RTR0PTR, NIL_VMCPUID, VMMR0_DO_INTNET_OPEN, 0, &OpenReq.Hdr); if (RT_FAILURE(rc)) { Log2(("VBoxNetBaseService: SUPR3CallVMMR0Ex(,VMMR0_DO_INTNET_OPEN,) failed, rc=%Rrc\n", rc)); return rc; } m->m_hIf = OpenReq.hIf; Log2(("successfully opened/created \"%s\" - hIf=%#x\n", OpenReq.szNetwork, m->m_hIf)); /* * Get the ring-3 address of the shared interface buffer. */ INTNETIFGETBUFFERPTRSREQ GetBufferPtrsReq; GetBufferPtrsReq.Hdr.u32Magic = SUPVMMR0REQHDR_MAGIC; GetBufferPtrsReq.Hdr.cbReq = sizeof(GetBufferPtrsReq); GetBufferPtrsReq.pSession = m->m_pSession; GetBufferPtrsReq.hIf = m->m_hIf; GetBufferPtrsReq.pRing3Buf = NULL; GetBufferPtrsReq.pRing0Buf = NIL_RTR0PTR; rc = SUPR3CallVMMR0Ex(NIL_RTR0PTR, NIL_VMCPUID, VMMR0_DO_INTNET_IF_GET_BUFFER_PTRS, 0, &GetBufferPtrsReq.Hdr); if (RT_FAILURE(rc)) { Log2(("VBoxNetBaseService: SUPR3CallVMMR0Ex(,VMMR0_DO_INTNET_IF_GET_BUFFER_PTRS,) failed, rc=%Rrc\n", rc)); return rc; } pBuf = GetBufferPtrsReq.pRing3Buf; Log2(("pBuf=%p cbBuf=%d cbSend=%d cbRecv=%d\n", pBuf, pBuf->cbBuf, pBuf->cbSend, pBuf->cbRecv)); m->m_pIfBuf = pBuf; /* * Activate the interface. */ INTNETIFSETACTIVEREQ ActiveReq; ActiveReq.Hdr.u32Magic = SUPVMMR0REQHDR_MAGIC; ActiveReq.Hdr.cbReq = sizeof(ActiveReq); ActiveReq.pSession = m->m_pSession; ActiveReq.hIf = m->m_hIf; ActiveReq.fActive = true; rc = SUPR3CallVMMR0Ex(NIL_RTR0PTR, NIL_VMCPUID, VMMR0_DO_INTNET_IF_SET_ACTIVE, 0, &ActiveReq.Hdr); if (RT_SUCCESS(rc)) return 0; /* bail out */ Log2(("VBoxNetBaseService: SUPR3CallVMMR0Ex(,VMMR0_DO_INTNET_IF_SET_PROMISCUOUS_MODE,) failed, rc=%Rrc\n", rc)); /* ignore this error */ return VINF_SUCCESS; } void VBoxNetBaseService::shutdown(void) { syncEnter(); if (!m->fShutdown) { m->fShutdown = true; if (m->m_hThrRecv != NIL_RTTHREAD) { int rc = abortWait(); AssertRC(rc == VINF_SUCCESS || rc == VERR_SEM_DESTROYED); rc = m->m_EventQ->interruptEventQueueProcessing(); if (RT_SUCCESS(rc)) { rc = RTThreadWait(m->m_hThrRecv, 60000, NULL); if (RT_FAILURE(rc)) Log1WarningFunc(("RTThreadWait(%RTthrd) -> %Rrc\n", m->m_hThrRecv, rc)); } else { AssertMsgFailed(("interruptEventQueueProcessing() failed\n")); RTThreadWait(m->m_hThrRecv , 0, NULL); } } } syncLeave(); } int VBoxNetBaseService::syncEnter() { return RTCritSectEnter(&m->m_csThis); } int VBoxNetBaseService::syncLeave() { return RTCritSectLeave(&m->m_csThis); } int VBoxNetBaseService::waitForIntNetEvent(int cMillis) { INTNETIFWAITREQ WaitReq; LogFlowFunc(("ENTER:cMillis: %d\n", cMillis)); WaitReq.Hdr.u32Magic = SUPVMMR0REQHDR_MAGIC; WaitReq.Hdr.cbReq = sizeof(WaitReq); WaitReq.pSession = m->m_pSession; WaitReq.hIf = m->m_hIf; WaitReq.cMillies = cMillis; int rc = SUPR3CallVMMR0Ex(NIL_RTR0PTR, NIL_VMCPUID, VMMR0_DO_INTNET_IF_WAIT, 0, &WaitReq.Hdr); LogFlowFuncLeaveRC(rc); return rc; } int VBoxNetBaseService::abortWait() { INTNETIFABORTWAITREQ AbortReq; LogFlowFunc(("ENTER:\n")); AbortReq.Hdr.u32Magic = SUPVMMR0REQHDR_MAGIC; AbortReq.Hdr.cbReq = sizeof(AbortReq); AbortReq.pSession = m->m_pSession; AbortReq.hIf = m->m_hIf; AbortReq.fNoMoreWaits = true; int rc = SUPR3CallVMMR0Ex(NIL_RTR0PTR, NIL_VMCPUID, VMMR0_DO_INTNET_IF_ABORT_WAIT, 0, &AbortReq.Hdr); LogFlowFuncLeaveRC(rc); return rc; } /* S/G API */ int VBoxNetBaseService::sendBufferOnWire(PCINTNETSEG paSegs, size_t cSegs, size_t cbFrame) { /* Allocate frame */ PINTNETHDR pHdr = NULL; uint8_t *pbFrame = NULL; int rc = IntNetRingAllocateFrame(&m->m_pIfBuf->Send, (uint32_t)cbFrame, &pHdr, (void **)&pbFrame); AssertRCReturn(rc, rc); /* Now we fill pvFrame with S/G above */ size_t offFrame = 0; for (size_t idxSeg = 0; idxSeg < cSegs; ++idxSeg) { memcpy(&pbFrame[offFrame], paSegs[idxSeg].pv, paSegs[idxSeg].cb); offFrame += paSegs[idxSeg].cb; } /* Commit */ IntNetRingCommitFrameEx(&m->m_pIfBuf->Send, pHdr, cbFrame); LogFlowFuncLeaveRC(rc); return rc; } /** * forcible ask for send packet on the "wire" */ void VBoxNetBaseService::flushWire() { INTNETIFSENDREQ SendReq; SendReq.Hdr.u32Magic = SUPVMMR0REQHDR_MAGIC; SendReq.Hdr.cbReq = sizeof(SendReq); SendReq.pSession = m->m_pSession; SendReq.hIf = m->m_hIf; int rc = SUPR3CallVMMR0Ex(NIL_RTR0PTR, NIL_VMCPUID, VMMR0_DO_INTNET_IF_SEND, 0, &SendReq.Hdr); AssertRCReturnVoid(rc); LogFlowFuncLeave(); } int VBoxNetBaseService::hlpUDPBroadcast(unsigned uSrcPort, unsigned uDstPort, void const *pvData, size_t cbData) const { return VBoxNetUDPBroadcast(m->m_pSession, m->m_hIf, m->m_pIfBuf, m->m_Ipv4Address, &m->m_MacAddress, uSrcPort, uDstPort, pvData, cbData); } const std::string VBoxNetBaseService::getServiceName() const { return m->m_ServiceName; } void VBoxNetBaseService::setServiceName(const std::string& aName) { m->m_ServiceName = aName; } const std::string VBoxNetBaseService::getNetworkName() const { return m->m_NetworkName; } void VBoxNetBaseService::setNetworkName(const std::string& aName) { m->m_NetworkName = aName; } const RTMAC VBoxNetBaseService::getMacAddress() const { return m->m_MacAddress; } void VBoxNetBaseService::setMacAddress(const RTMAC& aMac) { m->m_MacAddress = aMac; } const RTNETADDRIPV4 VBoxNetBaseService::getIpv4Address() const { return m->m_Ipv4Address; } void VBoxNetBaseService::setIpv4Address(const RTNETADDRIPV4& aAddress) { m->m_Ipv4Address = aAddress; } const RTNETADDRIPV4 VBoxNetBaseService::getIpv4Netmask() const { return m->m_Ipv4Netmask; } void VBoxNetBaseService::setIpv4Netmask(const RTNETADDRIPV4& aNetmask) { m->m_Ipv4Netmask = aNetmask; } uint32_t VBoxNetBaseService::getSendBufSize() const { return m->m_cbSendBuf; } void VBoxNetBaseService::setSendBufSize(uint32_t cbBuf) { m->m_cbSendBuf = cbBuf; } uint32_t VBoxNetBaseService::getRecvBufSize() const { return m->m_cbRecvBuf; } void VBoxNetBaseService::setRecvBufSize(uint32_t cbBuf) { m->m_cbRecvBuf = cbBuf; } int32_t VBoxNetBaseService::getVerbosityLevel() const { return m->m_cVerbosity; } void VBoxNetBaseService::setVerbosityLevel(int32_t aVerbosity) { m->m_cVerbosity = aVerbosity; } void VBoxNetBaseService::addCommandLineOption(const PRTGETOPTDEF optDef) { m->m_vecOptionDefs.push_back(optDef); } void VBoxNetBaseService::doReceiveLoop() { int rc; /* Well we're ready */ PINTNETRINGBUF pRingBuf = &m->m_pIfBuf->Recv; for (;;) { /* * Wait for a packet to become available. */ rc = waitForIntNetEvent(2000); if (rc == VERR_SEM_DESTROYED) break; if (RT_FAILURE(rc)) { if (rc == VERR_TIMEOUT || rc == VERR_INTERRUPTED) { /* do we want interrupt anyone ??? */ continue; } LogRel(("VBoxNetBaseService: waitForIntNetEvent returned %Rrc\n", rc)); AssertRCReturnVoid(rc); } /* * Process the receive buffer. */ PCINTNETHDR pHdr; while ((pHdr = IntNetRingGetNextFrameToRead(pRingBuf)) != NULL) { uint8_t const u8Type = pHdr->u8Type; size_t cbFrame = pHdr->cbFrame; switch (u8Type) { case INTNETHDR_TYPE_FRAME: { void *pvFrame = IntNetHdrGetFramePtr(pHdr, m->m_pIfBuf); rc = processFrame(pvFrame, cbFrame); if (RT_FAILURE(rc) && rc == VERR_IGNORED) { /* XXX: UDP + ARP for DHCP */ VBOXNETUDPHDRS Hdrs; size_t cb; void *pv = VBoxNetUDPMatch(m->m_pIfBuf, RTNETIPV4_PORT_BOOTPS, &m->m_MacAddress, VBOXNETUDP_MATCH_UNICAST | VBOXNETUDP_MATCH_BROADCAST | VBOXNETUDP_MATCH_CHECKSUM | (m->m_cVerbosity > 2 ? VBOXNETUDP_MATCH_PRINT_STDERR : 0), &Hdrs, &cb); if (pv && cb) processUDP(pv, cb); else VBoxNetArpHandleIt(m->m_pSession, m->m_hIf, m->m_pIfBuf, &m->m_MacAddress, m->m_Ipv4Address); } break; } case INTNETHDR_TYPE_GSO: { PCPDMNETWORKGSO pGso = IntNetHdrGetGsoContext(pHdr, m->m_pIfBuf); rc = processGSO(pGso, cbFrame); if (RT_FAILURE(rc) && rc == VERR_IGNORED) break; break; } case INTNETHDR_TYPE_PADDING: break; default: break; } IntNetRingSkipFrame(&m->m_pIfBuf->Recv); } /* loop */ } } int VBoxNetBaseService::startReceiveThreadAndEnterEventLoop() { AssertMsgReturn(isMainNeeded(), ("It's expected that we need Main"), VERR_INTERNAL_ERROR); /* start receiving thread */ int rc = RTThreadCreate(&m->m_hThrRecv, /* thread handle*/ &VBoxNetBaseService::Data::recvLoop, /* routine */ this, /* user data */ 128 * _1K, /* stack size */ RTTHREADTYPE_IO, /* type */ RTTHREADFLAGS_WAITABLE, /* flags */ "RECV"); AssertRCReturn(rc, rc); m->m_EventQ = com::NativeEventQueue::getMainEventQueue(); AssertPtrReturn(m->m_EventQ, VERR_INTERNAL_ERROR); while (!m->fShutdown) { rc = m->m_EventQ->processEventQueue(RT_INDEFINITE_WAIT); if (rc == VERR_INTERRUPTED) { LogFlow(("Event queue processing ended with rc=%Rrc\n", rc)); break; } } return VINF_SUCCESS; } void VBoxNetBaseService::debugPrint(int32_t iMinLevel, bool fMsg, const char *pszFmt, ...) const { if (iMinLevel <= m->m_cVerbosity) { va_list va; va_start(va, pszFmt); debugPrintV(iMinLevel, fMsg, pszFmt, va); va_end(va); } } /** * Print debug message depending on the m_cVerbosity level. * * @param iMinLevel The minimum m_cVerbosity level for this message. * @param fMsg Whether to dump parts for the current service message. * @param pszFmt The message format string. * @param va Optional arguments. */ void VBoxNetBaseService::debugPrintV(int iMinLevel, bool fMsg, const char *pszFmt, va_list va) const { RT_NOREF(fMsg); if (iMinLevel <= m->m_cVerbosity) { va_list vaCopy; /* This dude is *very* special, thus the copy. */ va_copy(vaCopy, va); RTStrmPrintf(g_pStdErr, "%s: %s: %N\n", RTProcShortName(), iMinLevel >= 2 ? "debug" : "info", pszFmt, &vaCopy); va_end(vaCopy); } } PRTGETOPTDEF VBoxNetBaseService::getOptionsPtr() { PRTGETOPTDEF pOptArray = NULL; pOptArray = (PRTGETOPTDEF)RTMemAlloc(sizeof(RTGETOPTDEF) * m->m_vecOptionDefs.size()); if (!pOptArray) return NULL; for (unsigned int i = 0; i < m->m_vecOptionDefs.size(); ++i) { PRTGETOPTDEF pOpt = m->m_vecOptionDefs[i]; memcpy(&pOptArray[i], pOpt, sizeof(*pOpt)); } return pOptArray; } #include "Object.hpp" namespace Screeps { Object::Object() : value_(JS::Value::null()) { } Object::Object(JS::Value value) : value_(std::move(value)) { } Object::~Object() = default; JS::Value& Object::value() { return value_; } const JS::Value& Object::value() const { return value_; } void Object::setValue(JS::Value value) { value_ = std::move(value); } Object::operator JS::Value&() { return value(); } Object::operator const JS::Value&() const { return value(); } } // namespace Screeps src/py/wrapper_f301756c73b6518392c0b1c3e424eedd.cpp #include "_clanglite.h" class ::clang::ObjCTypeParamDecl * (*method_pointer_5b1cc0324c2f5bbaa04eeeb201cce4b1)(class ::clang::ASTContext &, unsigned int )= ::clang::ObjCTypeParamDecl::CreateDeserialized; class ::clang::SourceLocation (::clang::ObjCTypeParamDecl::*method_pointer_9dd273670de055689b2fe680e4733e51)()const= &::clang::ObjCTypeParamDecl::getVarianceLoc; unsigned int (::clang::ObjCTypeParamDecl::*method_pointer_848098375ecf5191ab138f57d7f18be2)()const= &::clang::ObjCTypeParamDecl::getIndex; bool (::clang::ObjCTypeParamDecl::*method_pointer_87e9ae4db816519ba865286418a743a2)()const= &::clang::ObjCTypeParamDecl::hasExplicitBound; class ::clang::SourceLocation (::clang::ObjCTypeParamDecl::*method_pointer_5ee395c5915e5695bf25b182f385694a)()const= &::clang::ObjCTypeParamDecl::getColonLoc; bool (*method_pointer_52818fedab575813b31990c66a75b374)(class ::clang::Decl const *)= ::clang::ObjCTypeParamDecl::classof; bool (*method_pointer_dae714d729a45c8f943893482e2d68d1)(enum ::clang::Decl::Kind )= ::clang::ObjCTypeParamDecl::classofKind; namespace autowig { } void wrapper_f301756c73b6518392c0b1c3e424eedd(pybind11::module& module) { pybind11::class_::Type, class ::clang::TypedefNameDecl > class_f301756c73b6518392c0b1c3e424eedd(module, "ObjCTypeParamDecl", ""); class_f301756c73b6518392c0b1c3e424eedd.def_static("create_deserialized", method_pointer_5b1cc0324c2f5bbaa04eeeb201cce4b1, pybind11::return_value_policy::reference_internal, ""); class_f301756c73b6518392c0b1c3e424eedd.def("get_variance_loc", method_pointer_9dd273670de055689b2fe680e4733e51, ":Return Type:\n :cpp:class:`::clang::SourceLocation`\n\n"); class_f301756c73b6518392c0b1c3e424eedd.def("get_index", method_pointer_848098375ecf5191ab138f57d7f18be2, ":Return Type:\n :cpp:any:`unsigned` int\n\n"); class_f301756c73b6518392c0b1c3e424eedd.def("has_explicit_bound", method_pointer_87e9ae4db816519ba865286418a743a2, ":Return Type:\n :cpp:any:`bool`\n\n"); class_f301756c73b6518392c0b1c3e424eedd.def("get_colon_loc", method_pointer_5ee395c5915e5695bf25b182f385694a, ":Return Type:\n :cpp:class:`::clang::SourceLocation`\n\n"); class_f301756c73b6518392c0b1c3e424eedd.def_static("classof", method_pointer_52818fedab575813b31990c66a75b374, ""); class_f301756c73b6518392c0b1c3e424eedd.def_static("classof_kind", method_pointer_dae714d729a45c8f943893482e2d68d1, ""); }/* communityNet.cpp 2006 Jan 10 Author: To compile: g++ -O -Wall communityNet.cpp -o communityNet To run: ./communityNet [params] > net.edg 2> net.log Example: ./communityNet 1000 2349 2 0.95 1 3 0.25 0.5 0.75 1 0 1 10 random 2 > net.edg 2> net.log (params: N randseed Nrandmax [cumulative probabilities of Nrand] Nwalksmax [cumulative probabilities of Nwalks] delta w0 seedSize seedType optional:k_ave Note: distributions for number of initial and secondary connections are given in cumulative form: Nrandmax [cumulative probabilities of Nrand] Nwalksmax [cumulative probabilities of Nwalks]. Note that zero initial contacts are not allowed. Therefore, Nrandmax [cumulative probabilities of Nrand] 2 0.95 1 means p(nrand=1) = 0.95, p(nrand=2) = 0.05. For the number of secondary connections, zero is allowed. As an example, the discrete distribution U[0,3] is given as 3 0.25 0.5 0.75 1 */ //#define DEBUG // for debugging code to be run #define NDEBUG // to turn assertions off #include #include #include #include #include #include #include "../../Containers.H" #include "../../Nets.H" #include "../../Randgens.H" #include "../Distributions.H" // instead of the #includes below, you can alternatively use #include Models.H #include "../NetExtras.H" #include "../models/CommunityNet.H" typedef SymmNet /*, ValueTable, ExplSumTreeTable>*/ NetType; int main(int argc, char* argv[]) { struct CommNetArgs args; readCommNetArgs(args, argc, argv); outputCommNetArgs(args); // Prints parameters to std::cerr verbosely //outputCommNetArguments2(argc, argv); // Prints command line to std::cout RandNumGen<> generator(args.randseed); NetType net(args.netSize); communityNetCustomCdfsFaster(net, args, generator); outputEdgesAndWeights(net); } $NetBSD: patch-lib_usrp_dboard_db__xcvr2450.cpp,v 1.1 2020/05/14 19:21:04 joerg Exp $ --- lib/usrp/dboard/db_xcvr2450.cpp.orig 2020-05-09 15:31:27.549815118 +0000 +++ lib/usrp/dboard/db_xcvr2450.cpp @@ -227,18 +227,18 @@ xcvr2450::xcvr2450(ctor_args_t args) : x .set_publisher(boost::bind(&xcvr2450::get_rssi, this)); for(const std::string &name: xcvr_rx_gain_ranges.keys()){ this->get_rx_subtree()->create("gains/"+name+"/value") - .set_coercer(boost::bind(&xcvr2450::set_rx_gain, this, _1, name)) + .set_coercer(boost::bind(&xcvr2450::set_rx_gain, this, boost::placeholders::_1, name)) .set(xcvr_rx_gain_ranges[name].start()); this->get_rx_subtree()->create("gains/"+name+"/range") .set(xcvr_rx_gain_ranges[name]); } this->get_rx_subtree()->create("freq/value") - .set_coercer(boost::bind(&xcvr2450::set_lo_freq, this, _1)) + .set_coercer(boost::bind(&xcvr2450::set_lo_freq, this, boost::placeholders::_1)) .set(double(2.45e9)); this->get_rx_subtree()->create("freq/range") .set(xcvr_freq_range); this->get_rx_subtree()->create("antenna/value") - .add_coerced_subscriber(boost::bind(&xcvr2450::set_rx_ant, this, _1)) + .add_coerced_subscriber(boost::bind(&xcvr2450::set_rx_ant, this, boost::placeholders::_1)) .set(xcvr_antennas.at(0)); this->get_rx_subtree()->create >("antenna/options") .set(xcvr_antennas); @@ -249,7 +249,7 @@ xcvr2450::xcvr2450(ctor_args_t args) : x this->get_rx_subtree()->create("use_lo_offset") .set(false); this->get_rx_subtree()->create("bandwidth/value") - .set_coercer(boost::bind(&xcvr2450::set_rx_bandwidth, this, _1)) //complex bandpass bandwidth + .set_coercer(boost::bind(&xcvr2450::set_rx_bandwidth, this, boost::placeholders::_1)) //complex bandpass bandwidth .set(2.0*_rx_bandwidth); //_rx_bandwidth in lowpass, convert to complex bandpass this->get_rx_subtree()->create("bandwidth/range") .set(xcvr_rx_bandwidth_range); @@ -263,18 +263,18 @@ xcvr2450::xcvr2450(ctor_args_t args) : x .set_publisher(boost::bind(&xcvr2450::get_locked, this)); for(const std::string &name: xcvr_tx_gain_ranges.keys()){ this->get_tx_subtree()->create("gains/"+name+"/value") - .set_coercer(boost::bind(&xcvr2450::set_tx_gain, this, _1, name)) + .set_coercer(boost::bind(&xcvr2450::set_tx_gain, this, boost::placeholders::_1, name)) .set(xcvr_tx_gain_ranges[name].start()); this->get_tx_subtree()->create("gains/"+name+"/range") .set(xcvr_tx_gain_ranges[name]); } this->get_tx_subtree()->create("freq/value") - .set_coercer(boost::bind(&xcvr2450::set_lo_freq, this, _1)) + .set_coercer(boost::bind(&xcvr2450::set_lo_freq, this, boost::placeholders::_1)) .set(double(2.45e9)); this->get_tx_subtree()->create("freq/range") .set(xcvr_freq_range); this->get_tx_subtree()->create("antenna/value") - .add_coerced_subscriber(boost::bind(&xcvr2450::set_tx_ant, this, _1)) + .add_coerced_subscriber(boost::bind(&xcvr2450::set_tx_ant, this, boost::placeholders::_1)) .set(xcvr_antennas.at(1)); this->get_tx_subtree()->create >("antenna/options") .set(xcvr_antennas); @@ -285,7 +285,7 @@ xcvr2450::xcvr2450(ctor_args_t args) : x this->get_tx_subtree()->create("use_lo_offset") .set(false); this->get_tx_subtree()->create("bandwidth/value") - .set_coercer(boost::bind(&xcvr2450::set_tx_bandwidth, this, _1)) //complex bandpass bandwidth + .set_coercer(boost::bind(&xcvr2450::set_tx_bandwidth, this, boost::placeholders::_1)) //complex bandpass bandwidth .set(2.0*_tx_bandwidth); //_tx_bandwidth in lowpass, convert to complex bandpass this->get_tx_subtree()->create("bandwidth/range") .set(xcvr_tx_bandwidth_range); LazyMechanic/SubbotnikTime0 // Fill out your copyright notice in the Description page of Project Settings. #include "ChairControl.h" UChairControl* UChairControl::SerialPort(bool& connected, int32 ComPort, AActor* TargetActor) { UChairControl* value = NewObject(); value->Timer = TargetActor; connected = value->OpenPort(ComPort); return value; } void UChairControl::BeginDestroy() { Super::BeginDestroy(); ClosePort(); } bool UChairControl::isConnected() { return this->connected; } bool UChairControl::PortWrite(TArray bytes) { DWORD byteSend; if (!WriteFile(this->handler, (void*)bytes.GetData(), bytes.Num(), &byteSend, 0)) { return false; } else return true; } bool UChairControl::ClosePort() { CloseHandle(this->handler); UE_LOG(LogTemp, Log, TEXT("Close Port")); return true; } TArray UChairControl::FloatToBytes(float value) { TArray bytes; bytes.Append(reinterpret_cast(&value), 4); return bytes; } void UChairControl::StartSending(float frequency, bool log) { this->log = log; UE_LOG(LogTemp, Log, TEXT("StartPost")); Timer->GetWorldTimerManager().SetTimer(timer, this, &UChairControl::StartPost, frequency, true); } void UChairControl::StopSending() { StopPost(); } void UChairControl::Destroy(AActor * test) { ClosePort(); } void UChairControl::TimerSending(float time, float frequency, bool log) { this->log = log; UE_LOG(LogTemp, Log, TEXT("StartPost")); if (time > 0 || time >= frequency) { Timer->GetWorldTimerManager().SetTimer(timerStop, this, &UChairControl::StopPost, time, true); } else { UE_LOG(LogTemp, Warning, TEXT("The timer value is less than 0, so the chair will work for 1 second")); Timer->GetWorldTimerManager().SetTimer(timerStop, this, &UChairControl::StopPost, 1.0f, true); } Timer->GetWorldTimerManager().SetTimer(timer, this, &UChairControl::StartPost, frequency, true); } void UChairControl::Control(float roll, float pitch) { this->roll = roll; this->pitch = pitch; } uint16 UChairControl::CRC16(uint16 crc, uint8 b) { uint16 num1 = 255 & (crc >> 8 ^ b); uint16 num2 = num1 ^ num1 >> 4; return (crc ^ num2 << 4 ^ num2 >> 3) << 8 ^ (num2 ^ num2 << 5) & 255; } uint16 UChairControl::FullCRC(TArray p, int32 pSize) { uint16 crc = 58005; for (int32 i = 0; i <= pSize - 1; ++i) crc = CRC16(crc, p[i]); return crc; } TArray UChairControl::EncodePacket(TArray arrByte) { TArray appendArr; appendArr.Add(255); auto crc = UInt16ToBytes(FullCRC(arrByte, arrByte.Num())); arrByte.Append(crc); appendArr.Append(Clear(arrByte)); appendArr.Add(254); return appendArr; } TArray UChairControl::Clear(TArray value) { TArray arr; for (int32 i = 0; i < value.Num(); ++i) { if (value[i] >= 253) { arr.Add(253); arr.Add(value[i] - 253); } else arr.Add(value[i]); } return arr; } TArray UChairControl::UInt16ToBytes(uint16 value) { TArray arrAppend; arrAppend.Add(value & 255); arrAppend.Add(value >> 8); return arrAppend; } void UChairControl::StartPost() { TArray packet; packet.Add(33); packet.Add(12); packet.Add(3); packet.Append(FloatToBytes(pitch)); packet.Append(FloatToBytes(roll)); packet.Append(FloatToBytes(0)); packet = EncodePacket(packet); if (log) { FString logResult = "Byte: \n"; for (int i = 0; i < packet.Num(); ++i) { FString textLog = FString::FromInt(packet[i]) + ", "; logResult = logResult + textLog; } UE_LOG(LogTemp, Log, TEXT("%s"), *logResult); } PortWrite(packet); packet.Empty(); } void UChairControl::StopPost() { Timer->GetWorldTimerManager().ClearTimer(timer); Timer->GetWorldTimerManager().ClearTimer(timerStop); UE_LOG(LogTemp, Log, TEXT("StopPost")); } bool UChairControl::OpenPort(int32 ComPort) { this->connected = false; FString portName = "COM" + FString::FromInt(ComPort); char* COMPort = TCHAR_TO_ANSI(*portName); this->handler = CreateFileA(static_cast(COMPort), GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (this->handler == INVALID_HANDLE_VALUE) { if (GetLastError() == ERROR_FILE_NOT_FOUND) { UE_LOG(LogTemp, Error, TEXT("ERROR: Handle was not attached. Reason: %s not available!"), *portName); } else { UE_LOG(LogTemp, Error, TEXT("ERROR!!!")); } } else { DCB dcbSerialParameters = { 0 }; if (!GetCommState(this->handler, &dcbSerialParameters)) { UE_LOG(LogTemp, Error, TEXT("Failed to get current serial parameter")); } else { dcbSerialParameters.BaudRate = CBR_115200; dcbSerialParameters.ByteSize = 8; dcbSerialParameters.StopBits = ONESTOPBIT; dcbSerialParameters.Parity = NOPARITY; dcbSerialParameters.fDtrControl = DTR_CONTROL_ENABLE; if (!SetCommState(handler, &dcbSerialParameters)) { UE_LOG(LogTemp, Error, TEXT("ALERT: could not set Serial port parameters")); } else { this->connected = true; PurgeComm(this->handler, PURGE_RXCLEAR | PURGE_TXCLEAR); UE_LOG(LogTemp, Log, TEXT("Open Port!!!")); } } } Timer->OnDestroyed.AddDynamic(this, &UChairControl::Destroy); return this->connected; } 0 #include "GameState.h" #include "Board.h" #include "Move.h" #include "types.h" #if defined(FEATURE_INCREMENTAL_STATIC_EVALUATION) #include "StaticEvaluator.h" #endif #if defined(ANALYSIS_GAME_STATE) #include #endif using json = nlohmann::json; GameState::GameState(Board const & board, int cube, Color cubeOwner, Color diceOwner, Color whoseTurn, bool doubleOffered, Resignation resignationOffered, int die0, int die1, int moveNumber, Result result, bool crawford, int length) : board_(board) , cube_(cube) , cubeOwner_(cubeOwner) , diceOwner_(diceOwner) , whoseTurn_(whoseTurn) , doubleOffered_(doubleOffered) , resignationOffered_(resignationOffered) , die0_(die0) , die1_(die1) , moveNumber_(moveNumber) , result_(result) , crawford_(crawford) , length_(length) , fingerprint_(0) { } void GameState::initialize() { board_.initialize(); cube_ = 1; cubeOwner_ = Color::INVALID; diceOwner_ = Color::BLACK; whoseTurn_ = Color::BLACK; doubleOffered_ = false; resignationOffered_ = Resignation::NONE; die0_ = 0; die1_ = 0; moveNumber_ = 0; result_ = Result::NOT_STARTED; crawford_ = false; length_ = 0; fingerprint_ = 0; } bool GameState::initializeFromId(char const * matchId, char const * positionId) { return true; } void GameState::generateResponses(int depth, std::vector & responses) const { } void GameState::makeMove(Move const & move) { } std::string GameState::matchId() const { std::string result; return result; } uint64_t GameState::initialFingerprint() { return 0; } bool operator ==(GameState const & x, GameState const & y) { // Easy quick test if (x.fingerprint_ != y.fingerprint_) return false; // They might be the same. Eliminate false positives. return true; } #if defined(ANALYSIS_GAME_STATE) void GameState::AnalysisData::reset() { } nlohmann::json GameState::AnalysisData::toJson() const { return json(); } #endif // defined(ANALYSIS_GAME_STATE) 10-100 /* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. 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 using TencentCloud::CoreInternalOutcome; using namespace TencentCloud::Ecm::V20190719::Model; using namespace std; Instance::Instance() : m_instanceIdHasBeenSet(false), m_instanceNameHasBeenSet(false), m_instanceStateHasBeenSet(false), m_imageHasBeenSet(false), m_simpleModuleHasBeenSet(false), m_positionHasBeenSet(false), m_internetHasBeenSet(false), m_instanceTypeConfigHasBeenSet(false), m_createTimeHasBeenSet(false), m_tagSetHasBeenSet(false), m_latestOperationHasBeenSet(false), m_latestOperationStateHasBeenSet(false), m_restrictStateHasBeenSet(false), m_systemDiskSizeHasBeenSet(false), m_dataDiskSizeHasBeenSet(false), m_uUIDHasBeenSet(false), m_payModeHasBeenSet(false), m_expireTimeHasBeenSet(false), m_isolatedTimeHasBeenSet(false), m_renewFlagHasBeenSet(false), m_expireStateHasBeenSet(false), m_systemDiskHasBeenSet(false), m_dataDisksHasBeenSet(false), m_newFlagHasBeenSet(false), m_securityGroupIdsHasBeenSet(false), m_virtualPrivateCloudHasBeenSet(false), m_iSPHasBeenSet(false), m_physicalPositionHasBeenSet(false) { } CoreInternalOutcome Instance::Deserialize(const rapidjson::Value &value) { string requestId = ""; if (value.HasMember("InstanceId") && !value["InstanceId"].IsNull()) { if (!value["InstanceId"].IsString()) { return CoreInternalOutcome(Core::Error("response `Instance.InstanceId` IsString=false incorrectly").SetRequestId(requestId)); } m_instanceId = string(value["InstanceId"].GetString()); m_instanceIdHasBeenSet = true; } if (value.HasMember("InstanceName") && !value["InstanceName"].IsNull()) { if (!value["InstanceName"].IsString()) { return CoreInternalOutcome(Core::Error("response `Instance.InstanceName` IsString=false incorrectly").SetRequestId(requestId)); } m_instanceName = string(value["InstanceName"].GetString()); m_instanceNameHasBeenSet = true; } if (value.HasMember("InstanceState") && !value["InstanceState"].IsNull()) { if (!value["InstanceState"].IsString()) { return CoreInternalOutcome(Core::Error("response `Instance.InstanceState` IsString=false incorrectly").SetRequestId(requestId)); } m_instanceState = string(value["InstanceState"].GetString()); m_instanceStateHasBeenSet = true; } if (value.HasMember("Image") && !value["Image"].IsNull()) { if (!value["Image"].IsObject()) { return CoreInternalOutcome(Core::Error("response `Instance.Image` is not object type").SetRequestId(requestId)); } CoreInternalOutcome outcome = m_image.Deserialize(value["Image"]); if (!outcome.IsSuccess()) { outcome.GetError().SetRequestId(requestId); return outcome; } m_imageHasBeenSet = true; } if (value.HasMember("SimpleModule") && !value["SimpleModule"].IsNull()) { if (!value["SimpleModule"].IsObject()) { return CoreInternalOutcome(Core::Error("response `Instance.SimpleModule` is not object type").SetRequestId(requestId)); } CoreInternalOutcome outcome = m_simpleModule.Deserialize(value["SimpleModule"]); if (!outcome.IsSuccess()) { outcome.GetError().SetRequestId(requestId); return outcome; } m_simpleModuleHasBeenSet = true; } if (value.HasMember("Position") && !value["Position"].IsNull()) { if (!value["Position"].IsObject()) { return CoreInternalOutcome(Core::Error("response `Instance.Position` is not object type").SetRequestId(requestId)); } CoreInternalOutcome outcome = m_position.Deserialize(value["Position"]); if (!outcome.IsSuccess()) { outcome.GetError().SetRequestId(requestId); return outcome; } m_positionHasBeenSet = true; } if (value.HasMember("Internet") && !value["Internet"].IsNull()) { if (!value["Internet"].IsObject()) { return CoreInternalOutcome(Core::Error("response `Instance.Internet` is not object type").SetRequestId(requestId)); } CoreInternalOutcome outcome = m_internet.Deserialize(value["Internet"]); if (!outcome.IsSuccess()) { outcome.GetError().SetRequestId(requestId); return outcome; } m_internetHasBeenSet = true; } if (value.HasMember("InstanceTypeConfig") && !value["InstanceTypeConfig"].IsNull()) { if (!value["InstanceTypeConfig"].IsObject()) { return CoreInternalOutcome(Core::Error("response `Instance.InstanceTypeConfig` is not object type").SetRequestId(requestId)); } CoreInternalOutcome outcome = m_instanceTypeConfig.Deserialize(value["InstanceTypeConfig"]); if (!outcome.IsSuccess()) { outcome.GetError().SetRequestId(requestId); return outcome; } m_instanceTypeConfigHasBeenSet = true; } if (value.HasMember("CreateTime") && !value["CreateTime"].IsNull()) { if (!value["CreateTime"].IsString()) { return CoreInternalOutcome(Core::Error("response `Instance.CreateTime` IsString=false incorrectly").SetRequestId(requestId)); } m_createTime = string(value["CreateTime"].GetString()); m_createTimeHasBeenSet = true; } if (value.HasMember("TagSet") && !value["TagSet"].IsNull()) { if (!value["TagSet"].IsArray()) return CoreInternalOutcome(Core::Error("response `Instance.TagSet` is not array type")); const rapidjson::Value &tmpValue = value["TagSet"]; for (rapidjson::Value::ConstValueIterator itr = tmpValue.Begin(); itr != tmpValue.End(); ++itr) { Tag item; CoreInternalOutcome outcome = item.Deserialize(*itr); if (!outcome.IsSuccess()) { outcome.GetError().SetRequestId(requestId); return outcome; } m_tagSet.push_back(item); } m_tagSetHasBeenSet = true; } if (value.HasMember("LatestOperation") && !value["LatestOperation"].IsNull()) { if (!value["LatestOperation"].IsString()) { return CoreInternalOutcome(Core::Error("response `Instance.LatestOperation` IsString=false incorrectly").SetRequestId(requestId)); } m_latestOperation = string(value["LatestOperation"].GetString()); m_latestOperationHasBeenSet = true; } if (value.HasMember("LatestOperationState") && !value["LatestOperationState"].IsNull()) { if (!value["LatestOperationState"].IsString()) { return CoreInternalOutcome(Core::Error("response `Instance.LatestOperationState` IsString=false incorrectly").SetRequestId(requestId)); } m_latestOperationState = string(value["LatestOperationState"].GetString()); m_latestOperationStateHasBeenSet = true; } if (value.HasMember("RestrictState") && !value["RestrictState"].IsNull()) { if (!value["RestrictState"].IsString()) { return CoreInternalOutcome(Core::Error("response `Instance.RestrictState` IsString=false incorrectly").SetRequestId(requestId)); } m_restrictState = string(value["RestrictState"].GetString()); m_restrictStateHasBeenSet = true; } if (value.HasMember("SystemDiskSize") && !value["SystemDiskSize"].IsNull()) { if (!value["SystemDiskSize"].IsInt64()) { return CoreInternalOutcome(Core::Error("response `Instance.SystemDiskSize` IsInt64=false incorrectly").SetRequestId(requestId)); } m_systemDiskSize = value["SystemDiskSize"].GetInt64(); m_systemDiskSizeHasBeenSet = true; } if (value.HasMember("DataDiskSize") && !value["DataDiskSize"].IsNull()) { if (!value["DataDiskSize"].IsInt64()) { return CoreInternalOutcome(Core::Error("response `Instance.DataDiskSize` IsInt64=false incorrectly").SetRequestId(requestId)); } m_dataDiskSize = value["DataDiskSize"].GetInt64(); m_dataDiskSizeHasBeenSet = true; } if (value.HasMember("UUID") && !value["UUID"].IsNull()) { if (!value["UUID"].IsString()) { return CoreInternalOutcome(Core::Error("response `Instance.UUID` IsString=false incorrectly").SetRequestId(requestId)); } m_uUID = string(value["UUID"].GetString()); m_uUIDHasBeenSet = true; } if (value.HasMember("PayMode") && !value["PayMode"].IsNull()) { if (!value["PayMode"].IsInt64()) { return CoreInternalOutcome(Core::Error("response `Instance.PayMode` IsInt64=false incorrectly").SetRequestId(requestId)); } m_payMode = value["PayMode"].GetInt64(); m_payModeHasBeenSet = true; } if (value.HasMember("ExpireTime") && !value["ExpireTime"].IsNull()) { if (!value["ExpireTime"].IsString()) { return CoreInternalOutcome(Core::Error("response `Instance.ExpireTime` IsString=false incorrectly").SetRequestId(requestId)); } m_expireTime = string(value["ExpireTime"].GetString()); m_expireTimeHasBeenSet = true; } if (value.HasMember("IsolatedTime") && !value["IsolatedTime"].IsNull()) { if (!value["IsolatedTime"].IsString()) { return CoreInternalOutcome(Core::Error("response `Instance.IsolatedTime` IsString=false incorrectly").SetRequestId(requestId)); } m_isolatedTime = string(value["IsolatedTime"].GetString()); m_isolatedTimeHasBeenSet = true; } if (value.HasMember("RenewFlag") && !value["RenewFlag"].IsNull()) { if (!value["RenewFlag"].IsInt64()) { return CoreInternalOutcome(Core::Error("response `Instance.RenewFlag` IsInt64=false incorrectly").SetRequestId(requestId)); } m_renewFlag = value["RenewFlag"].GetInt64(); m_renewFlagHasBeenSet = true; } if (value.HasMember("ExpireState") && !value["ExpireState"].IsNull()) { if (!value["ExpireState"].IsString()) { return CoreInternalOutcome(Core::Error("response `Instance.ExpireState` IsString=false incorrectly").SetRequestId(requestId)); } m_expireState = string(value["ExpireState"].GetString()); m_expireStateHasBeenSet = true; } if (value.HasMember("SystemDisk") && !value["SystemDisk"].IsNull()) { if (!value["SystemDisk"].IsObject()) { return CoreInternalOutcome(Core::Error("response `Instance.SystemDisk` is not object type").SetRequestId(requestId)); } CoreInternalOutcome outcome = m_systemDisk.Deserialize(value["SystemDisk"]); if (!outcome.IsSuccess()) { outcome.GetError().SetRequestId(requestId); return outcome; } m_systemDiskHasBeenSet = true; } if (value.HasMember("DataDisks") && !value["DataDisks"].IsNull()) { if (!value["DataDisks"].IsArray()) return CoreInternalOutcome(Core::Error("response `Instance.DataDisks` is not array type")); const rapidjson::Value &tmpValue = value["DataDisks"]; for (rapidjson::Value::ConstValueIterator itr = tmpValue.Begin(); itr != tmpValue.End(); ++itr) { DiskInfo item; CoreInternalOutcome outcome = item.Deserialize(*itr); if (!outcome.IsSuccess()) { outcome.GetError().SetRequestId(requestId); return outcome; } m_dataDisks.push_back(item); } m_dataDisksHasBeenSet = true; } if (value.HasMember("NewFlag") && !value["NewFlag"].IsNull()) { if (!value["NewFlag"].IsInt64()) { return CoreInternalOutcome(Core::Error("response `Instance.NewFlag` IsInt64=false incorrectly").SetRequestId(requestId)); } m_newFlag = value["NewFlag"].GetInt64(); m_newFlagHasBeenSet = true; } if (value.HasMember("SecurityGroupIds") && !value["SecurityGroupIds"].IsNull()) { if (!value["SecurityGroupIds"].IsArray()) return CoreInternalOutcome(Core::Error("response `Instance.SecurityGroupIds` is not array type")); const rapidjson::Value &tmpValue = value["SecurityGroupIds"]; for (rapidjson::Value::ConstValueIterator itr = tmpValue.Begin(); itr != tmpValue.End(); ++itr) { m_securityGroupIds.push_back((*itr).GetString()); } m_securityGroupIdsHasBeenSet = true; } if (value.HasMember("VirtualPrivateCloud") && !value["VirtualPrivateCloud"].IsNull()) { if (!value["VirtualPrivateCloud"].IsObject()) { return CoreInternalOutcome(Core::Error("response `Instance.VirtualPrivateCloud` is not object type").SetRequestId(requestId)); } CoreInternalOutcome outcome = m_virtualPrivateCloud.Deserialize(value["VirtualPrivateCloud"]); if (!outcome.IsSuccess()) { outcome.GetError().SetRequestId(requestId); return outcome; } m_virtualPrivateCloudHasBeenSet = true; } if (value.HasMember("ISP") && !value["ISP"].IsNull()) { if (!value["ISP"].IsString()) { return CoreInternalOutcome(Core::Error("response `Instance.ISP` IsString=false incorrectly").SetRequestId(requestId)); } m_iSP = string(value["ISP"].GetString()); m_iSPHasBeenSet = true; } if (value.HasMember("PhysicalPosition") && !value["PhysicalPosition"].IsNull()) { if (!value["PhysicalPosition"].IsObject()) { return CoreInternalOutcome(Core::Error("response `Instance.PhysicalPosition` is not object type").SetRequestId(requestId)); } CoreInternalOutcome outcome = m_physicalPosition.Deserialize(value["PhysicalPosition"]); if (!outcome.IsSuccess()) { outcome.GetError().SetRequestId(requestId); return outcome; } m_physicalPositionHasBeenSet = true; } return CoreInternalOutcome(true); } void Instance::ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const { if (m_instanceIdHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "InstanceId"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_instanceId.c_str(), allocator).Move(), allocator); } if (m_instanceNameHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "InstanceName"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_instanceName.c_str(), allocator).Move(), allocator); } if (m_instanceStateHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "InstanceState"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_instanceState.c_str(), allocator).Move(), allocator); } if (m_imageHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Image"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(rapidjson::kObjectType).Move(), allocator); m_image.ToJsonObject(value[key.c_str()], allocator); } if (m_simpleModuleHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "SimpleModule"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(rapidjson::kObjectType).Move(), allocator); m_simpleModule.ToJsonObject(value[key.c_str()], allocator); } if (m_positionHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Position"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(rapidjson::kObjectType).Move(), allocator); m_position.ToJsonObject(value[key.c_str()], allocator); } if (m_internetHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Internet"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(rapidjson::kObjectType).Move(), allocator); m_internet.ToJsonObject(value[key.c_str()], allocator); } if (m_instanceTypeConfigHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "InstanceTypeConfig"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(rapidjson::kObjectType).Move(), allocator); m_instanceTypeConfig.ToJsonObject(value[key.c_str()], allocator); } if (m_createTimeHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "CreateTime"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_createTime.c_str(), allocator).Move(), allocator); } if (m_tagSetHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "TagSet"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(rapidjson::kArrayType).Move(), allocator); int i=0; for (auto itr = m_tagSet.begin(); itr != m_tagSet.end(); ++itr, ++i) { value[key.c_str()].PushBack(rapidjson::Value(rapidjson::kObjectType).Move(), allocator); (*itr).ToJsonObject(value[key.c_str()][i], allocator); } } if (m_latestOperationHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "LatestOperation"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_latestOperation.c_str(), allocator).Move(), allocator); } if (m_latestOperationStateHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "LatestOperationState"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_latestOperationState.c_str(), allocator).Move(), allocator); } if (m_restrictStateHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "RestrictState"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_restrictState.c_str(), allocator).Move(), allocator); } if (m_systemDiskSizeHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "SystemDiskSize"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_systemDiskSize, allocator); } if (m_dataDiskSizeHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "DataDiskSize"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_dataDiskSize, allocator); } if (m_uUIDHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "UUID"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_uUID.c_str(), allocator).Move(), allocator); } if (m_payModeHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "PayMode"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_payMode, allocator); } if (m_expireTimeHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "ExpireTime"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_expireTime.c_str(), allocator).Move(), allocator); } if (m_isolatedTimeHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "IsolatedTime"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_isolatedTime.c_str(), allocator).Move(), allocator); } if (m_renewFlagHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "RenewFlag"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_renewFlag, allocator); } if (m_expireStateHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "ExpireState"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_expireState.c_str(), allocator).Move(), allocator); } if (m_systemDiskHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "SystemDisk"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(rapidjson::kObjectType).Move(), allocator); m_systemDisk.ToJsonObject(value[key.c_str()], allocator); } if (m_dataDisksHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "DataDisks"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(rapidjson::kArrayType).Move(), allocator); int i=0; for (auto itr = m_dataDisks.begin(); itr != m_dataDisks.end(); ++itr, ++i) { value[key.c_str()].PushBack(rapidjson::Value(rapidjson::kObjectType).Move(), allocator); (*itr).ToJsonObject(value[key.c_str()][i], allocator); } } if (m_newFlagHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "NewFlag"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_newFlag, allocator); } if (m_securityGroupIdsHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "SecurityGroupIds"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(rapidjson::kArrayType).Move(), allocator); for (auto itr = m_securityGroupIds.begin(); itr != m_securityGroupIds.end(); ++itr) { value[key.c_str()].PushBack(rapidjson::Value().SetString((*itr).c_str(), allocator), allocator); } } if (m_virtualPrivateCloudHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "VirtualPrivateCloud"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(rapidjson::kObjectType).Move(), allocator); m_virtualPrivateCloud.ToJsonObject(value[key.c_str()], allocator); } if (m_iSPHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "ISP"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_iSP.c_str(), allocator).Move(), allocator); } if (m_physicalPositionHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "PhysicalPosition"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(rapidjson::kObjectType).Move(), allocator); m_physicalPosition.ToJsonObject(value[key.c_str()], allocator); } } string Instance::GetInstanceId() const { return m_instanceId; } void Instance::SetInstanceId(const string& _instanceId) { m_instanceId = _instanceId; m_instanceIdHasBeenSet = true; } bool Instance::InstanceIdHasBeenSet() const { return m_instanceIdHasBeenSet; } string Instance::GetInstanceName() const { return m_instanceName; } void Instance::SetInstanceName(const string& _instanceName) { m_instanceName = _instanceName; m_instanceNameHasBeenSet = true; } bool Instance::InstanceNameHasBeenSet() const { return m_instanceNameHasBeenSet; } string Instance::GetInstanceState() const { return m_instanceState; } void Instance::SetInstanceState(const string& _instanceState) { m_instanceState = _instanceState; m_instanceStateHasBeenSet = true; } bool Instance::InstanceStateHasBeenSet() const { return m_instanceStateHasBeenSet; } Image Instance::GetImage() const { return m_image; } void Instance::SetImage(const Image& _image) { m_image = _image; m_imageHasBeenSet = true; } bool Instance::ImageHasBeenSet() const { return m_imageHasBeenSet; } SimpleModule Instance::GetSimpleModule() const { return m_simpleModule; } void Instance::SetSimpleModule(const SimpleModule& _simpleModule) { m_simpleModule = _simpleModule; m_simpleModuleHasBeenSet = true; } bool Instance::SimpleModuleHasBeenSet() const { return m_simpleModuleHasBeenSet; } Position Instance::GetPosition() const { return m_position; } void Instance::SetPosition(const Position& _position) { m_position = _position; m_positionHasBeenSet = true; } bool Instance::PositionHasBeenSet() const { return m_positionHasBeenSet; } Internet Instance::GetInternet() const { return m_internet; } void Instance::SetInternet(const Internet& _internet) { m_internet = _internet; m_internetHasBeenSet = true; } bool Instance::InternetHasBeenSet() const { return m_internetHasBeenSet; } InstanceTypeConfig Instance::GetInstanceTypeConfig() const { return m_instanceTypeConfig; } void Instance::SetInstanceTypeConfig(const InstanceTypeConfig& _instanceTypeConfig) { m_instanceTypeConfig = _instanceTypeConfig; m_instanceTypeConfigHasBeenSet = true; } bool Instance::InstanceTypeConfigHasBeenSet() const { return m_instanceTypeConfigHasBeenSet; } string Instance::GetCreateTime() const { return m_createTime; } void Instance::SetCreateTime(const string& _createTime) { m_createTime = _createTime; m_createTimeHasBeenSet = true; } bool Instance::CreateTimeHasBeenSet() const { return m_createTimeHasBeenSet; } vector Instance::GetTagSet() const { return m_tagSet; } void Instance::SetTagSet(const vector& _tagSet) { m_tagSet = _tagSet; m_tagSetHasBeenSet = true; } bool Instance::TagSetHasBeenSet() const { return m_tagSetHasBeenSet; } string Instance::GetLatestOperation() const { return m_latestOperation; } void Instance::SetLatestOperation(const string& _latestOperation) { m_latestOperation = _latestOperation; m_latestOperationHasBeenSet = true; } bool Instance::LatestOperationHasBeenSet() const { return m_latestOperationHasBeenSet; } string Instance::GetLatestOperationState() const { return m_latestOperationState; } void Instance::SetLatestOperationState(const string& _latestOperationState) { m_latestOperationState = _latestOperationState; m_latestOperationStateHasBeenSet = true; } bool Instance::LatestOperationStateHasBeenSet() const { return m_latestOperationStateHasBeenSet; } string Instance::GetRestrictState() const { return m_restrictState; } void Instance::SetRestrictState(const string& _restrictState) { m_restrictState = _restrictState; m_restrictStateHasBeenSet = true; } bool Instance::RestrictStateHasBeenSet() const { return m_restrictStateHasBeenSet; } int64_t Instance::GetSystemDiskSize() const { return m_systemDiskSize; } void Instance::SetSystemDiskSize(const int64_t& _systemDiskSize) { m_systemDiskSize = _systemDiskSize; m_systemDiskSizeHasBeenSet = true; } bool Instance::SystemDiskSizeHasBeenSet() const { return m_systemDiskSizeHasBeenSet; } int64_t Instance::GetDataDiskSize() const { return m_dataDiskSize; } void Instance::SetDataDiskSize(const int64_t& _dataDiskSize) { m_dataDiskSize = _dataDiskSize; m_dataDiskSizeHasBeenSet = true; } bool Instance::DataDiskSizeHasBeenSet() const { return m_dataDiskSizeHasBeenSet; } string Instance::GetUUID() const { return m_uUID; } void Instance::SetUUID(const string& _uUID) { m_uUID = _uUID; m_uUIDHasBeenSet = true; } bool Instance::UUIDHasBeenSet() const { return m_uUIDHasBeenSet; } int64_t Instance::GetPayMode() const { return m_payMode; } void Instance::SetPayMode(const int64_t& _payMode) { m_payMode = _payMode; m_payModeHasBeenSet = true; } bool Instance::PayModeHasBeenSet() const { return m_payModeHasBeenSet; } string Instance::GetExpireTime() const { return m_expireTime; } void Instance::SetExpireTime(const string& _expireTime) { m_expireTime = _expireTime; m_expireTimeHasBeenSet = true; } bool Instance::ExpireTimeHasBeenSet() const { return m_expireTimeHasBeenSet; } string Instance::GetIsolatedTime() const { return m_isolatedTime; } void Instance::SetIsolatedTime(const string& _isolatedTime) { m_isolatedTime = _isolatedTime; m_isolatedTimeHasBeenSet = true; } bool Instance::IsolatedTimeHasBeenSet() const { return m_isolatedTimeHasBeenSet; } int64_t Instance::GetRenewFlag() const { return m_renewFlag; } void Instance::SetRenewFlag(const int64_t& _renewFlag) { m_renewFlag = _renewFlag; m_renewFlagHasBeenSet = true; } bool Instance::RenewFlagHasBeenSet() const { return m_renewFlagHasBeenSet; } string Instance::GetExpireState() const { return m_expireState; } void Instance::SetExpireState(const string& _expireState) { m_expireState = _expireState; m_expireStateHasBeenSet = true; } bool Instance::ExpireStateHasBeenSet() const { return m_expireStateHasBeenSet; } DiskInfo Instance::GetSystemDisk() const { return m_systemDisk; } void Instance::SetSystemDisk(const DiskInfo& _systemDisk) { m_systemDisk = _systemDisk; m_systemDiskHasBeenSet = true; } bool Instance::SystemDiskHasBeenSet() const { return m_systemDiskHasBeenSet; } vector Instance::GetDataDisks() const { return m_dataDisks; } void Instance::SetDataDisks(const vector& _dataDisks) { m_dataDisks = _dataDisks; m_dataDisksHasBeenSet = true; } bool Instance::DataDisksHasBeenSet() const { return m_dataDisksHasBeenSet; } int64_t Instance::GetNewFlag() const { return m_newFlag; } void Instance::SetNewFlag(const int64_t& _newFlag) { m_newFlag = _newFlag; m_newFlagHasBeenSet = true; } bool Instance::NewFlagHasBeenSet() const { return m_newFlagHasBeenSet; } vector Instance::GetSecurityGroupIds() const { return m_securityGroupIds; } void Instance::SetSecurityGroupIds(const vector& _securityGroupIds) { m_securityGroupIds = _securityGroupIds; m_securityGroupIdsHasBeenSet = true; } bool Instance::SecurityGroupIdsHasBeenSet() const { return m_securityGroupIdsHasBeenSet; } VirtualPrivateCloud Instance::GetVirtualPrivateCloud() const { return m_virtualPrivateCloud; } void Instance::SetVirtualPrivateCloud(const VirtualPrivateCloud& _virtualPrivateCloud) { m_virtualPrivateCloud = _virtualPrivateCloud; m_virtualPrivateCloudHasBeenSet = true; } bool Instance::VirtualPrivateCloudHasBeenSet() const { return m_virtualPrivateCloudHasBeenSet; } string Instance::GetISP() const { return m_iSP; } void Instance::SetISP(const string& _iSP) { m_iSP = _iSP; m_iSPHasBeenSet = true; } bool Instance::ISPHasBeenSet() const { return m_iSPHasBeenSet; } PhysicalPosition Instance::GetPhysicalPosition() const { return m_physicalPosition; } void Instance::SetPhysicalPosition(const PhysicalPosition& _physicalPosition) { m_physicalPosition = _physicalPosition; m_physicalPositionHasBeenSet = true; } bool Instance::PhysicalPositionHasBeenSet() const { return m_physicalPositionHasBeenSet; } #include "Player.h" Player::Player() { name = "unknown"; title = "unknown"; occupation = "unknown"; action = "unknown"; int health = 100; attack = "unknown"; defense = "unknown"; heal = "unknown"; random = "unknown"; } Player::Player(const std::string &_name, const std::string &_title, const std::string &occupation, const std::string &_action, int _health, const std::string &_attack, const std::string &_defense, const std::string &_heal, const std::string &_random) { name = _name; title = _title; action = _action; health = _health; attack = _attack; defense = _defense; heal = _heal; random = _random; } std::string Player::getName() const { return name; } void Player::setName(const std::string &_name) { name = _name; } std::string Player::getTitle() const { return title; } void Player::setTitle(const std::string &_title) { title = _title; } std::string Player::getOccupation() const { return occupation; } std::string Player::getAction() const { return action; } void Player::setAction(std::string _action){ } void Player::setOccupation(const std::string &_occupation) { occupation = _occupation; } int Player::getHealth() const { return health; } void Player::setHealth(int _health) { health = _health; } std::string Player::getSkill1() const { return attack; } std::string Player::getSkill2() const { return defense; } std::string Player::getSkill3() const { return heal; } std::string Player::getSkill4() const { return random; } //================================================================================================== /** Copyright 2016 NumScale SAS Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt) **/ //================================================================================================== #include #include #include #include namespace bs = boost::simd; namespace bd = boost::dispatch; STF_CASE_TPL("Check basic behavior of ifrexp", STF_IEEE_TYPES) { STF_EXPR_IS ( (bs::ifrexp(T(0))) , (std::pair>) ); auto p = bs::ifrexp(T(1)); STF_EQUAL(p.first , T(0.5)); STF_EQUAL(p.second , T(1)); } STF_CASE_TPL("Check behavior of ifrexp on Zero", STF_IEEE_TYPES) { auto r = bs::ifrexp(T(0)); STF_EQUAL (r.first , T(0)); STF_EQUAL (r.second, T(0)); STF_EQUAL (ldexp(r.first,r.second), T(0)); } STF_CASE_TPL("Check behavior of ifrexp on Valmax", STF_IEEE_TYPES) { auto r = bs::ifrexp(bs::Valmax()); STF_ULP_EQUAL (r.first , T(1)-bs::Halfeps(), 1); STF_EQUAL (r.second, bs::Limitexponent()); STF_EQUAL (ldexp(r.first,r.second),bs::Valmax()); } ver1/answers/lp-14-07.cpp // Exercise 14.7: Define an output operator for you String class you wrote for the exercises in § 13.5 (p. 531). #include "include\String.h" #include "source\String.cpp" #include using namespace std; int main() { cout << String("Hello, World!") << endl; return 0; } zrz1996/ACM-Template1-10 /* O(n^2logn), please remove coincided circles first. */ point_t center[maxn]; double radius[maxn], cntarea[maxn]; pair isCC(point_t c1, point_t c2, double r1, double r2) { double d = dist(c1, c2); double x1 = c1.x, x2 = c2.x, y1 = c1.y, y2 = c2.y; double mid = atan2(y2 - y1, x2 - x1); double a = r1, c = r2; double t = acos((a * a + d * d - c * c) / (2 * a * d)); return make_pair(mid - t, mid + t); } struct event_t { double theta; int delta; event_t(double t, int d) : theta(t), delta(d) { } bool operator<(const event_t &r) const { if (fabs(theta - r.theta) < eps) return delta > r.delta; return theta < r.theta; } }; vector e; void add(double begin, double end) { if (begin <= -pi) begin += 2 * pi, end += 2 * pi; if (end > pi) { e.push_back(event_t(begin, 1)); e.push_back(event_t(pi, -1)); e.push_back(event_t(-pi, 1)); e.push_back(event_t(end - 2 * pi, -1)); } else { e.push_back(event_t(begin, 1)); e.push_back(event_t(end, -1)); } } double calc(point_t c, double r, double a1, double a2) { double da = a2 - a1; double aa = r * r * (da - sin(da)) / 2; point_t p1 = point_t(cos(a1), sin(a1)) * r + c; point_t p2 = point_t(cos(a2), sin(a2)) * r + c; return cross(p1, p2) / 2 + aa; } void circle_union() { for (int c = 1; c <= n; ++c) { int cvrcnt = 0; e.clear(); for (int i = 1; i <= n; ++i) { if (i != c) { int r = testCC(center[c], center[i], radius[c], radius[i]); if (r == 2) ++cvrcnt; else if (r == 0) { pair paa = isCC(center[c], center[i], radius[c], radius[i]); add(paa.first, paa.second); } } } if (e.size() == 0) { double a = pi * radius[c] * radius[c]; cntarea[cvrcnt] -= a; cntarea[cvrcnt + 1] += a; } else { e.push_back(event_t(-pi, 1)); e.push_back(event_t(pi, -2)); sort(e.begin(), e.end()); for (int i = 0; i < int(e.size()) - 1; ++i) { cvrcnt += e[i].delta; double a = calc(center[c], radius[c], e[i].theta, e[i + 1].theta); cntarea[cvrcnt - 1] -= a; cntarea[cvrcnt] += a; } } } }#include #include #include #include #include #include #include using namespace mastercore; BOOST_FIXTURE_TEST_SUITE(tradelayer_uint256_extensions_tests, BasicTestingSetup) BOOST_AUTO_TEST_CASE(uint256_from_uint64_t) { uint64_t number = 103242; arith_uint256 a(number); BOOST_CHECK_EQUAL(number, a.GetLow64()); } BOOST_AUTO_TEST_CASE(uint256_add) { uint64_t number_a = 103242; uint64_t number_b = 234324; uint64_t number_c = number_a + number_b; arith_uint256 a(number_a); arith_uint256 b(number_b); arith_uint256 c = a + b; BOOST_CHECK_EQUAL(number_c, c.GetLow64()); } BOOST_AUTO_TEST_CASE(uint256_sub) { uint64_t number_a = 503242; uint64_t number_b = 234324; uint64_t number_c = number_a - number_b; arith_uint256 a(number_a); arith_uint256 b(number_b); arith_uint256 c = a - b; BOOST_CHECK_EQUAL(number_c, c.GetLow64()); } BOOST_AUTO_TEST_CASE(uint256_mul) { uint64_t number_a = 503242; uint64_t number_b = 234324; uint64_t number_c = number_a * number_b; arith_uint256 a(number_a); arith_uint256 b(number_b); arith_uint256 c = a * b; BOOST_CHECK_EQUAL(number_c, c.GetLow64()); } BOOST_AUTO_TEST_CASE(uint256_div) { uint64_t number_a = 9; uint64_t number_b = 4; uint64_t number_c = number_a / number_b; arith_uint256 a(number_a); arith_uint256 b(number_b); arith_uint256 c = a / b; BOOST_CHECK_EQUAL(number_c, c.GetLow64()); } BOOST_AUTO_TEST_CASE(uint256_conversion) { BOOST_CHECK_EQUAL(0, ConvertTo64(ConvertTo256(0))); BOOST_CHECK_EQUAL(1, ConvertTo64(ConvertTo256(1))); BOOST_CHECK_EQUAL(1000000000000000000LL, ConvertTo64(ConvertTo256(1000000000000000000LL))); BOOST_CHECK_EQUAL(9223372036854775807LL, ConvertTo64(ConvertTo256(9223372036854775807LL))); } BOOST_AUTO_TEST_CASE(uint256_modulo) { BOOST_CHECK_EQUAL(1, ConvertTo64(Modulo256(ConvertTo256(9), ConvertTo256(4)))); } BOOST_AUTO_TEST_CASE(uint256_modulo_auto_conversion) { BOOST_CHECK_EQUAL(2, ConvertTo64(Modulo256(17, 3))); } BOOST_AUTO_TEST_CASE(uint256_divide_and_round_up) { BOOST_CHECK_EQUAL(3, ConvertTo64(DivideAndRoundUp(ConvertTo256(5), ConvertTo256(2)))); } BOOST_AUTO_TEST_CASE(uint256_const) { BOOST_CHECK_EQUAL(1, ConvertTo64(mastercore::uint256_const::one)); BOOST_CHECK_EQUAL(std::numeric_limits::max(), ConvertTo64(mastercore::uint256_const::max_int64)); } arith_uint256 amountReserved(int64_t amount, uint64_t margin_requirement, uint64_t leverage, int64_t uPrice) { return (ConvertTo256(COIN) * ConvertTo256(amount) * ConvertTo256(margin_requirement)) / (ConvertTo256(leverage) * ConvertTo256(uPrice)); } BOOST_AUTO_TEST_CASE(contractdex_trade_amount) { int64_t uPrice = 1000000000 * COIN; // price = 1 billion of dUSD uint64_t leverage = 10 * COIN; // max leverage uint64_t marginRequirement = 42 * COIN; // 42 tokens per contract (almost the maximum) // 1 contract BOOST_CHECK_EQUAL(ConvertTo64(amountReserved(1 * COIN, marginRequirement, leverage, uPrice)), ConvertTo64(ConvertTo256(0))); // 0.42 (in practice it's 0) // 1000 contracts BOOST_CHECK_EQUAL(ConvertTo64(amountReserved(1000 * COIN, marginRequirement, leverage, uPrice)), ConvertTo64(ConvertTo256(420))); // 420 (in practice it's 0.0000042) // 1000 000 contracts BOOST_CHECK_EQUAL(ConvertTo64(amountReserved(1000000 * COIN, marginRequirement, leverage, uPrice)), ConvertTo64(ConvertTo256(420000))); // 420 000 (in practice it's 0.0042) // 1000 000 000 contracts BOOST_CHECK_EQUAL(ConvertTo64(amountReserved(1000000000 * COIN, marginRequirement, leverage, uPrice)), ConvertTo64(ConvertTo256(420000000))); // 420 000 000 (in practice it's 4.2) } BOOST_AUTO_TEST_CASE(contractdex_trade_leverage) { int64_t amount = 1000000000 * COIN; // price = 1 billion contracts int64_t uPrice = 1000000000 * COIN; // price = 1 billion of dUSD uint32_t marginRequirement = 42 * COIN; // 42 tokens per contract (almost the maximum) // leverage 1 BOOST_CHECK_EQUAL(ConvertTo64(amountReserved(amount, marginRequirement, 1 * COIN, uPrice)), ConvertTo64(ConvertTo256(4200000000))); // (in practice it's 4.2) // leverage 2 BOOST_CHECK_EQUAL(ConvertTo64(amountReserved(amount, marginRequirement, 2 * COIN, uPrice)), ConvertTo64(ConvertTo256(2100000000))); // (in practice it's 2.1) // leverage 10 BOOST_CHECK_EQUAL(ConvertTo64(amountReserved(amount, marginRequirement, 10 * COIN, uPrice)), ConvertTo64(ConvertTo256(420000000))); //(in practice it's 0.42) } int64_t checkReserve(int64_t nBalance, int64_t amount, uint64_t marginRequirement, uint64_t leverage, bool oracle) { int64_t uPrice = COIN; std::pair factor; // max = 2.5 basis point in oracles, max = 1.0 basis point in natives (oracle) ? (factor.first = 100025, factor.second = 100000) : (factor.first = 10001, factor.second = 10000); arith_uint256 amountTR = (ConvertTo256(factor.first) * ConvertTo256(COIN) * ConvertTo256(amount) * ConvertTo256(marginRequirement)) / (ConvertTo256(leverage) * ConvertTo256(uPrice) * ConvertTo256(factor.second)); return (ConvertTo64(amountTR)); } BOOST_AUTO_TEST_CASE(check_reserve) { int64_t nBalance = 1000000000000; int64_t amount = 1000; // contracts uint64_t marginRequirement = 10000000; // 0.1 uint64_t leverage = 1; bool oracle = true; BOOST_CHECK_EQUAL(checkReserve(nBalance, amount, marginRequirement, leverage, oracle), 10002500000); oracle = false; BOOST_CHECK_EQUAL(checkReserve(nBalance, amount, marginRequirement, leverage, oracle), 10001000000); } BOOST_AUTO_TEST_SUITE_END() #include "Condition.h" Condition::Condition(Column *col, Parameter *param) { this->col = col; this->col_r=nullptr; this->param = param; this->disabled = false; this->mode=SIMPLE; } Condition::Condition(Column *col, Column *col_r) { this->col = col; this->param=nullptr; this->col_r = col_r; this->disabled = false; this->mode=JOIN; } Condition::Mode Condition::get_mode() { return this->mode; } Column* Condition::get_column() { return this->col; } Column* Condition::get_column_right() { return this->col_r; } Parameter* Condition::get_parameter() { return this->param; } std::string Condition::print(){ if (this->mode == Mode::JOIN){ return this->col->get_name()+" = "+this->col_r->get_name(); } else { return this->col->get_name()+" = @"+this->param->get_name(); } } #include "stdafx.h" #pragma hdrstop #include "../../xrEngine/Render.h" #include "../xrRender/ResourceManager.h" #include "../xrRender/tss.h" #include "../xrRender/blenders/blender.h" #include "../xrRender/blenders/blender_recorder.h" // adopt_compiler don't have = operator And it can't have = operator #pragma warning( push ) #pragma warning( disable : 4512) #include "../../xrScripts/lua_studio/ai_script_space.h" #pragma warning( pop ) #include "../../xrScripts/lua_studio/ai_script_lua_extension.h" #include "luabind/return_reference_to_policy.hpp" #include "../xrRender/dxRenderDeviceRender.h" #include "../../xrScripts/lua_traceback.hpp" using namespace luabind; class adopt_dx10options { public: bool _dx10_msaa_alphatest_atoc() { return(RImplementation.o.dx10_msaa_alphatest == CRender::MSAA_ATEST_DX10_0_ATOC); } }; // wrapper class adopt_dx10sampler { CBlender_Compile* m_pC; u32 m_SI; // Sampler index public: adopt_dx10sampler (CBlender_Compile* C, u32 SamplerIndex) : m_pC(C), m_SI(SamplerIndex) { if (u32(-1)==m_SI) m_pC=0;} adopt_dx10sampler (const adopt_dx10sampler& _C) : m_pC(_C.m_pC), m_SI(_C.m_SI) { if (u32(-1)==m_SI) m_pC=0;} }; #pragma warning( push ) #pragma warning( disable : 4512) // wrapper class adopt_compiler { CBlender_Compile* C; bool &m_bFirstPass; void TryEndPass() { if (!m_bFirstPass) C->r_End(); m_bFirstPass = false;} public: adopt_compiler (CBlender_Compile* _C, bool& bFirstPass) : C(_C), m_bFirstPass(bFirstPass) { m_bFirstPass = true;} adopt_compiler (const adopt_compiler& _C) : C(_C.C), m_bFirstPass(_C.m_bFirstPass){ } adopt_compiler& _options (int P, bool S) { C->SetParams (P,S); return *this; } adopt_compiler& _o_emissive (bool E) { C->SH->flags.bEmissive=E; return *this; } adopt_compiler& _o_distort (bool E) { C->SH->flags.bDistort=E; return *this; } adopt_compiler& _o_wmark (bool E) { C->SH->flags.bWmark=E; return *this; } adopt_compiler& _pass (LPCSTR vs, LPCSTR ps) { TryEndPass(); C->r_Pass(vs,ps,true); return *this; } adopt_compiler& _passgs (LPCSTR vs, LPCSTR gs, LPCSTR ps){ TryEndPass(); C->r_Pass(vs,gs,ps,true); return *this; } adopt_compiler& _fog (bool _fog) { C->PassSET_LightFog (FALSE,_fog); return *this; } adopt_compiler& _ZB (bool _test, bool _write) { C->PassSET_ZB (_test,_write); return *this; } adopt_compiler& _blend (bool _blend, u32 abSRC, u32 abDST) { C->PassSET_ablend_mode(_blend,abSRC,abDST); return *this; } adopt_compiler& _aref (bool _aref, u32 aref) { C->PassSET_ablend_aref(_aref,aref); return *this; } adopt_compiler& _dx10texture (LPCSTR _resname, LPCSTR _texname) { C->r_dx10Texture(_resname, _texname); return *this; } adopt_dx10sampler _dx10sampler (LPCSTR _name) { u32 s = C->r_dx10Sampler(_name); return adopt_dx10sampler(C,s); } // DX10 specific adopt_compiler& _dx10color_write_enable (bool cR, bool cG, bool cB, bool cA) { C->r_ColorWriteEnable(cR, cG, cB, cA); return *this; } adopt_compiler& _dx10Stencil (bool Enable, u32 Func, u32 Mask, u32 WriteMask, u32 Fail, u32 Pass, u32 ZFail) {C->r_Stencil(Enable, Func, Mask, WriteMask, Fail, Pass, ZFail); return *this; } adopt_compiler& _dx10StencilRef (u32 Ref) {C->r_StencilRef(Ref); return *this; } adopt_compiler& _dx10ATOC (bool Enable) { C->RS.SetRS( XRDX10RS_ALPHATOCOVERAGE, Enable); return *this; } adopt_compiler& _dx10ZFunc (u32 Func) { C->RS.SetRS ( D3DRS_ZFUNC, Func); return *this; } adopt_dx10options _dx10Options () { return adopt_dx10options(); }; }; #pragma warning( pop ) class adopt_blend { public: }; class adopt_cmp_func { public: }; class adopt_stencil_op { public: }; void LuaLog(LPCSTR caMessage) { Lua::LuaOut (Lua::eLuaMessageTypeMessage,"%s",caMessage); } void LuaError(lua_State* L) { const char *error = lua_tostring(L, -1); Debug.fatal(DEBUG_INFO, "LUA error: %s", error ? error : get_traceback(L, 1)); } // export void CResourceManager::LS_Load () { LSVM = luaL_newstate(); R_ASSERT2(LSVM, "Cannot initialize script virtual machine!"); // initialize lua standard library functions luaopen_base (LSVM); luaopen_table (LSVM); luaopen_string (LSVM); luaopen_math (LSVM); luaopen_jit (LSVM); luabind::open (LSVM); //#TODO: Error handling for R3/R4 // #if !XRAY_EXCEPTIONS // if (!luabind::get_error_callback()) // luabind::set_error_callback(LuaError); // #endif function (LSVM, "log", LuaLog); module (LSVM) [ class_("_dx10options") .def("dx10_msaa_alphatest_atoc", &adopt_dx10options::_dx10_msaa_alphatest_atoc), class_("_dx10sampler"), class_("_compiler") .def( constructor()) .def("begin", &adopt_compiler::_pass ,return_reference_to<1>()) .def("begin", &adopt_compiler::_passgs ,return_reference_to<1>()) .def("sorting", &adopt_compiler::_options ,return_reference_to<1>()) .def("emissive", &adopt_compiler::_o_emissive ,return_reference_to<1>()) .def("distort", &adopt_compiler::_o_distort ,return_reference_to<1>()) .def("wmark", &adopt_compiler::_o_wmark ,return_reference_to<1>()) .def("fog", &adopt_compiler::_fog ,return_reference_to<1>()) .def("zb", &adopt_compiler::_ZB ,return_reference_to<1>()) .def("blend", &adopt_compiler::_blend ,return_reference_to<1>()) .def("aref", &adopt_compiler::_aref ,return_reference_to<1>()) // For compatibility only .def("dx10color_write_enable", &adopt_compiler::_dx10color_write_enable,return_reference_to<1>()) .def("color_write_enable", &adopt_compiler::_dx10color_write_enable,return_reference_to<1>()) .def("dx10texture", &adopt_compiler::_dx10texture ,return_reference_to<1>()) .def("dx10stencil", &adopt_compiler::_dx10Stencil ,return_reference_to<1>()) .def("dx10stencil_ref", &adopt_compiler::_dx10StencilRef,return_reference_to<1>()) .def("dx10atoc", &adopt_compiler::_dx10ATOC ,return_reference_to<1>()) .def("dx10zfunc", &adopt_compiler::_dx10ZFunc ,return_reference_to<1>()) .def("dx10sampler", &adopt_compiler::_dx10sampler ) // returns sampler-object .def("dx10Options", &adopt_compiler::_dx10Options ), // returns options-object class_("blend") .enum_("blend") [ value("zero", int(D3DBLEND_ZERO)), value("one", int(D3DBLEND_ONE)), value("srccolor", int(D3DBLEND_SRCCOLOR)), value("invsrccolor", int(D3DBLEND_INVSRCCOLOR)), value("srcalpha", int(D3DBLEND_SRCALPHA)), value("invsrcalpha", int(D3DBLEND_INVSRCALPHA)), value("destalpha", int(D3DBLEND_DESTALPHA)), value("invdestalpha", int(D3DBLEND_INVDESTALPHA)), value("destcolor", int(D3DBLEND_DESTCOLOR)), value("invdestcolor", int(D3DBLEND_INVDESTCOLOR)), value("srcalphasat", int(D3DBLEND_SRCALPHASAT)) ], class_("cmp_func") .enum_("cmp_func") [ value("never", int(D3DCMP_NEVER)), value("less", int(D3DCMP_LESS)), value("equal", int(D3DCMP_EQUAL)), value("lessequal", int(D3DCMP_LESSEQUAL)), value("greater", int(D3DCMP_GREATER)), value("notequal", int(D3DCMP_NOTEQUAL)), value("greaterequal", int(D3DCMP_GREATEREQUAL)), value("always", int(D3DCMP_ALWAYS)) ], class_("stencil_op") .enum_("stencil_op") [ value("keep", int(D3DSTENCILOP_KEEP)), value("zero", int(D3DSTENCILOP_ZERO)), value("replace", int(D3DSTENCILOP_REPLACE)), value("incrsat", int(D3DSTENCILOP_INCRSAT)), value("decrsat", int(D3DSTENCILOP_DECRSAT)), value("invert", int(D3DSTENCILOP_INVERT)), value("incr", int(D3DSTENCILOP_INCR)), value("decr", int(D3DSTENCILOP_DECR)) ] ]; // load shaders xr_vector* folder = FS.file_list_open("$game_shaders$",::Render->getShaderPath(),FS_ListFiles|FS_RootOnly); VERIFY(folder); for (u32 it=0; itsize(); it++) { string_path namesp, fn; xr_strcpy(namesp,(*folder)[it]); if(!strext(namesp) || xr_strcmp(strext(namesp),".s")) continue; *strext (namesp)=0; if(!namesp[0]) xr_strcpy(namesp,"_G"); strconcat(sizeof(fn),fn,::Render->getShaderPath(),(*folder)[it]); FS.update_path(fn,"$game_shaders$",fn); try { Script::bfLoadFileIntoNamespace(LSVM,fn,namesp,true); } catch (...) { Log(lua_tostring(LSVM,-1)); } } FS.file_list_close (folder); } void CResourceManager::LS_Unload () { lua_close (LSVM); LSVM = NULL; } BOOL CResourceManager::_lua_HasShader (LPCSTR s_shader) { string256 undercorated; for (int i=0, l=xr_strlen(s_shader)+1; im_textures_description.GetDetailTexture(C.L_textures[0],C.detail_texture,C.detail_scaler); if (C.bDetail) S.E[0] = C._lua_Compile(s_shader,"normal_hq"); else S.E[0] = C._lua_Compile(s_shader,"normal"); } else { if (Script::bfIsObjectPresent(LSVM,s_shader,"normal",LUA_TFUNCTION)) { C.iElement = 0; C.bDetail = dxRenderDeviceRender::Instance().Resources->m_textures_description.GetDetailTexture(C.L_textures[0],C.detail_texture,C.detail_scaler); S.E[0] = C._lua_Compile(s_shader,"normal"); } } // Compile element (LOD1) if (Script::bfIsObjectPresent(LSVM,s_shader,"normal",LUA_TFUNCTION)) { C.iElement = 1; C.bDetail = dxRenderDeviceRender::Instance().Resources->m_textures_description.GetDetailTexture(C.L_textures[0],C.detail_texture,C.detail_scaler); S.E[1] = C._lua_Compile(s_shader,"normal"); } // Compile element if (Script::bfIsObjectPresent(LSVM,s_shader,"l_point",LUA_TFUNCTION)) { C.iElement = 2; C.bDetail = FALSE; S.E[2] = C._lua_Compile(s_shader,"l_point");; } // Compile element if (Script::bfIsObjectPresent(LSVM,s_shader,"l_spot",LUA_TFUNCTION)) { C.iElement = 3; C.bDetail = FALSE; S.E[3] = C._lua_Compile(s_shader,"l_spot");; } // Compile element if (Script::bfIsObjectPresent(LSVM,s_shader,"l_special",LUA_TFUNCTION)) { C.iElement = 4; C.bDetail = FALSE; S.E[4] = C._lua_Compile(s_shader,"l_special"); } // Search equal in shaders array for (u32 it=0; it(S); N->dwFlags |= xr_resource_flagged::RF_REGISTERED; v_shaders.push_back (N); return N; } ShaderElement* CBlender_Compile::_lua_Compile (LPCSTR namesp, LPCSTR name) { ShaderElement E; SH = &E; RS.Invalidate (); // Compile LPCSTR t_0 = *L_textures[0] ? *L_textures[0] : "null"; LPCSTR t_1 = (L_textures.size() > 1) ? *L_textures[1] : "null"; LPCSTR t_d = detail_texture ? detail_texture : "null" ; lua_State* LSVM = dxRenderDeviceRender::Instance().Resources->LSVM; object shader = get_globals(LSVM)[namesp]; functor element = object_cast >(shader[name]); bool bFirstPass = false; adopt_compiler ac = adopt_compiler(this, bFirstPass); element (ac,t_0,t_1,t_d); r_End (); ShaderElement* _r = dxRenderDeviceRender::Instance().Resources->_CreateElement(E); return _r; } #include #include #include #include "bundle_info.hpp" #include "generated_entity_lookup.hpp" #include "Cisco_IOS_XR_sysadmin_led_mgr_ui.hpp" using namespace ydk; namespace cisco_ios_xr { namespace Cisco_IOS_XR_sysadmin_led_mgr_ui { Led::Led() : location(this, {"location"}) , trace(this, {"buffer"}) { yang_name = "led"; yang_parent_name = "Cisco-IOS-XR-sysadmin-led-mgr-ui"; is_top_level_class = true; has_list_ancestor = false; } Led::~Led() { } bool Led::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; indexhas_data()) return true; } for (std::size_t index=0; indexhas_data()) return true; } return false; } bool Led::has_operation() const { for (std::size_t index=0; indexhas_operation()) return true; } for (std::size_t index=0; indexhas_operation()) return true; } return is_set(yfilter); } std::string Led::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XR-sysadmin-led-mgr-ui:led"; return path_buffer.str(); } std::vector > Led::get_name_leaf_data() const { std::vector > leaf_name_data {}; return leaf_name_data; } std::shared_ptr Led::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "location") { auto ent_ = std::make_shared(); ent_->parent = this; location.append(ent_); return ent_; } if(child_yang_name == "trace") { auto ent_ = std::make_shared(); ent_->parent = this; trace.append(ent_); return ent_; } return nullptr; } std::map> Led::get_children() const { std::map> _children{}; char count_=0; count_ = 0; for (auto ent_ : location.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } count_ = 0; for (auto ent_ : trace.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void Led::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void Led::set_filter(const std::string & value_path, YFilter yfilter) { } std::shared_ptr Led::clone_ptr() const { return std::make_shared(); } std::string Led::get_bundle_yang_models_location() const { return ydk_cisco_ios_xr_models_path; } std::string Led::get_bundle_name() const { return "cisco_ios_xr"; } augment_capabilities_function Led::get_augment_capabilities_function() const { return cisco_ios_xr_augment_lookup_tables; } std::map, std::string> Led::get_namespace_identity_lookup() const { return cisco_ios_xr_namespace_identity_lookup; } bool Led::has_leaf_or_child_of_name(const std::string & name) const { if(name == "location" || name == "trace") return true; return false; } Led::Location::Location() : location{YType::str, "location"} , led_attributes(this, {"led_name"}) { yang_name = "location"; yang_parent_name = "led"; is_top_level_class = false; has_list_ancestor = false; } Led::Location::~Location() { } bool Led::Location::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; indexhas_data()) return true; } return location.is_set; } bool Led::Location::has_operation() const { for (std::size_t index=0; indexhas_operation()) return true; } return is_set(yfilter) || ydk::is_set(location.yfilter); } std::string Led::Location::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XR-sysadmin-led-mgr-ui:led/" << get_segment_path(); return path_buffer.str(); } std::string Led::Location::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "location"; ADD_KEY_TOKEN(location, "location"); return path_buffer.str(); } std::vector > Led::Location::get_name_leaf_data() const { std::vector > leaf_name_data {}; if (location.is_set || is_set(location.yfilter)) leaf_name_data.push_back(location.get_name_leafdata()); return leaf_name_data; } std::shared_ptr Led::Location::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "led_attributes") { auto ent_ = std::make_shared(); ent_->parent = this; led_attributes.append(ent_); return ent_; } return nullptr; } std::map> Led::Location::get_children() const { std::map> _children{}; char count_=0; count_ = 0; for (auto ent_ : led_attributes.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void Led::Location::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "location") { location = value; location.value_namespace = name_space; location.value_namespace_prefix = name_space_prefix; } } void Led::Location::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "location") { location.yfilter = yfilter; } } bool Led::Location::has_leaf_or_child_of_name(const std::string & name) const { if(name == "led_attributes" || name == "location") return true; return false; } Led::Location::LedAttributes::LedAttributes() : led_name{YType::str, "led_name"}, led_mode{YType::str, "led_mode"}, led_color{YType::str, "led_color"} { yang_name = "led_attributes"; yang_parent_name = "location"; is_top_level_class = false; has_list_ancestor = true; } Led::Location::LedAttributes::~LedAttributes() { } bool Led::Location::LedAttributes::has_data() const { if (is_presence_container) return true; return led_name.is_set || led_mode.is_set || led_color.is_set; } bool Led::Location::LedAttributes::has_operation() const { return is_set(yfilter) || ydk::is_set(led_name.yfilter) || ydk::is_set(led_mode.yfilter) || ydk::is_set(led_color.yfilter); } std::string Led::Location::LedAttributes::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "led_attributes"; ADD_KEY_TOKEN(led_name, "led_name"); return path_buffer.str(); } std::vector > Led::Location::LedAttributes::get_name_leaf_data() const { std::vector > leaf_name_data {}; if (led_name.is_set || is_set(led_name.yfilter)) leaf_name_data.push_back(led_name.get_name_leafdata()); if (led_mode.is_set || is_set(led_mode.yfilter)) leaf_name_data.push_back(led_mode.get_name_leafdata()); if (led_color.is_set || is_set(led_color.yfilter)) leaf_name_data.push_back(led_color.get_name_leafdata()); return leaf_name_data; } std::shared_ptr Led::Location::LedAttributes::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map> Led::Location::LedAttributes::get_children() const { std::map> _children{}; char count_=0; return _children; } void Led::Location::LedAttributes::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "led_name") { led_name = value; led_name.value_namespace = name_space; led_name.value_namespace_prefix = name_space_prefix; } if(value_path == "led_mode") { led_mode = value; led_mode.value_namespace = name_space; led_mode.value_namespace_prefix = name_space_prefix; } if(value_path == "led_color") { led_color = value; led_color.value_namespace = name_space; led_color.value_namespace_prefix = name_space_prefix; } } void Led::Location::LedAttributes::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "led_name") { led_name.yfilter = yfilter; } if(value_path == "led_mode") { led_mode.yfilter = yfilter; } if(value_path == "led_color") { led_color.yfilter = yfilter; } } bool Led::Location::LedAttributes::has_leaf_or_child_of_name(const std::string & name) const { if(name == "led_name" || name == "led_mode" || name == "led_color") return true; return false; } Led::Trace::Trace() : buffer{YType::str, "buffer"} , location(this, {"location_name"}) { yang_name = "trace"; yang_parent_name = "led"; is_top_level_class = false; has_list_ancestor = false; } Led::Trace::~Trace() { } bool Led::Trace::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; indexhas_data()) return true; } return buffer.is_set; } bool Led::Trace::has_operation() const { for (std::size_t index=0; indexhas_operation()) return true; } return is_set(yfilter) || ydk::is_set(buffer.yfilter); } std::string Led::Trace::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XR-sysadmin-led-mgr-ui:led/" << get_segment_path(); return path_buffer.str(); } std::string Led::Trace::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "trace"; ADD_KEY_TOKEN(buffer, "buffer"); return path_buffer.str(); } std::vector > Led::Trace::get_name_leaf_data() const { std::vector > leaf_name_data {}; if (buffer.is_set || is_set(buffer.yfilter)) leaf_name_data.push_back(buffer.get_name_leafdata()); return leaf_name_data; } std::shared_ptr Led::Trace::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "location") { auto ent_ = std::make_shared(); ent_->parent = this; location.append(ent_); return ent_; } return nullptr; } std::map> Led::Trace::get_children() const { std::map> _children{}; char count_=0; count_ = 0; for (auto ent_ : location.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void Led::Trace::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "buffer") { buffer = value; buffer.value_namespace = name_space; buffer.value_namespace_prefix = name_space_prefix; } } void Led::Trace::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "buffer") { buffer.yfilter = yfilter; } } bool Led::Trace::has_leaf_or_child_of_name(const std::string & name) const { if(name == "location" || name == "buffer") return true; return false; } Led::Trace::Location::Location() : location_name{YType::str, "location_name"} , all_options(this, {"option"}) { yang_name = "location"; yang_parent_name = "trace"; is_top_level_class = false; has_list_ancestor = true; } Led::Trace::Location::~Location() { } bool Led::Trace::Location::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; indexhas_data()) return true; } return location_name.is_set; } bool Led::Trace::Location::has_operation() const { for (std::size_t index=0; indexhas_operation()) return true; } return is_set(yfilter) || ydk::is_set(location_name.yfilter); } std::string Led::Trace::Location::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "location"; ADD_KEY_TOKEN(location_name, "location_name"); return path_buffer.str(); } std::vector > Led::Trace::Location::get_name_leaf_data() const { std::vector > leaf_name_data {}; if (location_name.is_set || is_set(location_name.yfilter)) leaf_name_data.push_back(location_name.get_name_leafdata()); return leaf_name_data; } std::shared_ptr Led::Trace::Location::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "all-options") { auto ent_ = std::make_shared(); ent_->parent = this; all_options.append(ent_); return ent_; } return nullptr; } std::map> Led::Trace::Location::get_children() const { std::map> _children{}; char count_=0; count_ = 0; for (auto ent_ : all_options.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void Led::Trace::Location::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "location_name") { location_name = value; location_name.value_namespace = name_space; location_name.value_namespace_prefix = name_space_prefix; } } void Led::Trace::Location::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "location_name") { location_name.yfilter = yfilter; } } bool Led::Trace::Location::has_leaf_or_child_of_name(const std::string & name) const { if(name == "all-options" || name == "location_name") return true; return false; } Led::Trace::Location::AllOptions::AllOptions() : option{YType::str, "option"} , trace_blocks(this, {}) { yang_name = "all-options"; yang_parent_name = "location"; is_top_level_class = false; has_list_ancestor = true; } Led::Trace::Location::AllOptions::~AllOptions() { } bool Led::Trace::Location::AllOptions::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; indexhas_data()) return true; } return option.is_set; } bool Led::Trace::Location::AllOptions::has_operation() const { for (std::size_t index=0; indexhas_operation()) return true; } return is_set(yfilter) || ydk::is_set(option.yfilter); } std::string Led::Trace::Location::AllOptions::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "all-options"; ADD_KEY_TOKEN(option, "option"); return path_buffer.str(); } std::vector > Led::Trace::Location::AllOptions::get_name_leaf_data() const { std::vector > leaf_name_data {}; if (option.is_set || is_set(option.yfilter)) leaf_name_data.push_back(option.get_name_leafdata()); return leaf_name_data; } std::shared_ptr Led::Trace::Location::AllOptions::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "trace-blocks") { auto ent_ = std::make_shared(); ent_->parent = this; trace_blocks.append(ent_); return ent_; } return nullptr; } std::map> Led::Trace::Location::AllOptions::get_children() const { std::map> _children{}; char count_=0; count_ = 0; for (auto ent_ : trace_blocks.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void Led::Trace::Location::AllOptions::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "option") { option = value; option.value_namespace = name_space; option.value_namespace_prefix = name_space_prefix; } } void Led::Trace::Location::AllOptions::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "option") { option.yfilter = yfilter; } } bool Led::Trace::Location::AllOptions::has_leaf_or_child_of_name(const std::string & name) const { if(name == "trace-blocks" || name == "option") return true; return false; } Led::Trace::Location::AllOptions::TraceBlocks::TraceBlocks() : data{YType::str, "data"} { yang_name = "trace-blocks"; yang_parent_name = "all-options"; is_top_level_class = false; has_list_ancestor = true; } Led::Trace::Location::AllOptions::TraceBlocks::~TraceBlocks() { } bool Led::Trace::Location::AllOptions::TraceBlocks::has_data() const { if (is_presence_container) return true; return data.is_set; } bool Led::Trace::Location::AllOptions::TraceBlocks::has_operation() const { return is_set(yfilter) || ydk::is_set(data.yfilter); } std::string Led::Trace::Location::AllOptions::TraceBlocks::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "trace-blocks"; path_buffer << "[" << get_ylist_key() << "]"; return path_buffer.str(); } std::vector > Led::Trace::Location::AllOptions::TraceBlocks::get_name_leaf_data() const { std::vector > leaf_name_data {}; if (data.is_set || is_set(data.yfilter)) leaf_name_data.push_back(data.get_name_leafdata()); return leaf_name_data; } std::shared_ptr Led::Trace::Location::AllOptions::TraceBlocks::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map> Led::Trace::Location::AllOptions::TraceBlocks::get_children() const { std::map> _children{}; char count_=0; return _children; } void Led::Trace::Location::AllOptions::TraceBlocks::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "data") { data = value; data.value_namespace = name_space; data.value_namespace_prefix = name_space_prefix; } } void Led::Trace::Location::AllOptions::TraceBlocks::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "data") { data.yfilter = yfilter; } } bool Led::Trace::Location::AllOptions::TraceBlocks::has_leaf_or_child_of_name(const std::string & name) const { if(name == "data") return true; return false; } } } //======================================================================================= // // // Copyright 2021 // // Distributed under the MIT licence // // 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 "GIO.h" #include "GVICII.h" GIO::GIO() { gpu = NULL; } GIO::~GIO() { //dtor } //======================================================================== // // get a byte from the attached chips // //======================================================================== const byte GIO::getByte(int offset) { switch(offset) { case 0x00: if(gpu) return gpu->getFlags(); case 0x01: if(gpu) return gpu->getMainColours(); case 0x02: if(gpu) return gpu->getCharSetPtrLo(); case 0x03: if(gpu) return gpu->getCharSetPtrHi(); case 0x04: if(gpu) return gpu->getCharDisplayPtrLo(); case 0x05: if(gpu) return gpu->getCharDisplayPtrHi(); } return 0xff; } //======================================================================== // // Return the byte buffer of RGB24s // //======================================================================== void GIO::setByte(int offset, byte value) { switch(offset) { case 0x00: if(gpu) { gpu->setFlags(value); } case 0x01: if(gpu) { gpu->setMainColours(value); } case 0x02: if(gpu) { gpu->setCharSetPtrLo(value); } case 0x03: if(gpu) { gpu->setCharSetPtrHi(value); } case 0x04: if(gpu) { gpu->setCharDisplayPtrLo(value); } case 0x05: if(gpu) { gpu->setCharDisplayPtrHi(value); } } } /********************************************************************************* * The MIT License (MIT) * * 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 NON-INFRINGEMENT. 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 GRBL_GMODAL_H #define GRBL_GMODAL_H namespace grblconnector { class GModal { public: enum DISTANCE { distance_none = -1, distance_absolute = 90, distance_incremental = 91 }; enum WCS { wcs_none = -1, mcs = 53, wcs_1 = 54, wcs_2 = 55, wcs_3 = 56, wcs_4 = 57, wcs_5 = 58, wcs_6 = 59 }; enum PLANE { plane_none = -1, plane_xy = 17, plane_zx = 18, plane_yz = 19 }; enum MOTION { motion_none = -1, motion_rapid = 0, motion_linear = 1, motion_arc_cw = 2, motion_arc_ccw = 3 }; enum SPINDLE { spindle_off = 5, spindle_cw = 3, spindle_ccw = 4 }; enum COOLANT { coolant_off = 9, coolant_mist = 7, coolant_flood = 8 }; enum UNIT { unit_none = -1, unit_inch = 20, unit_mm = 21 }; enum PROGRAM { program_none = -1, program_m0 = 0, program_m1 = 1, program_m2 = 2, program_m30 = 30 }; enum FEED { feed_none = -1, feed_inverse_time = 93, feed_units_per_minute = 94 }; GModal::MOTION motion{GModal::motion_none}; GModal::WCS wcs{GModal::wcs_none}; GModal::PLANE plane{GModal::plane_none}; GModal::UNIT unit{GModal::unit_none}; GModal::DISTANCE distance{GModal::distance_none}; GModal::FEED feed{GModal::feed_none}; GModal::PROGRAM program{GModal::program_none}; GModal::SPINDLE spindle{GModal::spindle_off}; GModal::COOLANT coolant{GModal::coolant_off}; int tool_number = 0; int spindle_speed = 0; int feed_rate = 0; }; } #endif //GRBL_GMODAL_H #include #include #include #include using namespace std; inline void use_io_optimizations() { ios_base::sync_with_stdio(false); cin.tie(nullptr); } void read_word(string& object, string& subject, string& verb) { char bracket; cin >> bracket; if (bracket == '{') { getline(cin, object, '}'); } else if (bracket == '(') { getline(cin, subject, ')'); } else if (bracket == '[') { getline(cin, verb, ']'); } } string sentence() { string object; string subject; string verb; read_word(object, subject, verb); read_word(object, subject, verb); read_word(object, subject, verb); return object + ' ' + subject + ' ' + verb; } string conjunction() { if (cin.peek() != ',') { return ""; } cin.ignore(); cin.ignore(); if (!isalpha(cin.peek())) { return ", "; } string word; cin >> word; return ", " + word + ' '; } int main() { use_io_optimizations(); auto first = sentence(); auto link = conjunction(); auto second = sentence(); transform(first.begin(), first.end(), first.begin(), ::tolower); transform(link.begin(), link.end(), link.begin(), ::tolower); transform(second.begin(), second.end(), second.begin(), ::tolower); first.front() = toupper(first.front()); cout << first + link + second << '\n'; return 0; } //cpp #include #include #include #include"tic_tac_toe.h" using std::string; using std::vector; using std::cout; bool TicTacToe::game_over() { bool game_is_over = false; // Add checks for all the win conditions if (TicTacToe::check_column_win()) { TicTacToe::set_winner(); game_is_over = true; } if (check_row_win()) { TicTacToe::set_winner(); game_is_over = true; } if (check_diagonal_win()) { TicTacToe::set_winner(); game_is_over = true; } if ( ( game_is_over == false ) && ( check_board_full() ) ) { TicTacToe::winner = "C"; game_is_over = true; } return game_is_over; } void TicTacToe::start_game(std::string first_player) { TicTacToe::player = first_player; clear_board(); } void TicTacToe::mark_board(int position) { pegs[position - 1] = TicTacToe::player; set_next_player(); } string TicTacToe::get_player() const { return TicTacToe::player; } void TicTacToe::display_board() const { cout << " " << pegs[0] << " | " << pegs[1] << " | " << pegs[2] << " \n"; cout << " --|---|--\n"; cout << " " << pegs[3] << " | " << pegs[4] << " | " << pegs[5] << " \n"; cout << " --|---|--\n"; cout << " " << pegs[6] << " | " << pegs[7] << " | " << pegs[8] << " \n"; } void TicTacToe::set_next_player() { TicTacToe::player = TicTacToe::player == "X" ? "O" : "X"; } bool TicTacToe::check_board_full() { bool result = true; for (unsigned int i = 0; i < pegs.size(); i++) { if (pegs[i] == " ") { result = false; } } return result; } void TicTacToe::clear_board() { for (unsigned int i = 0; i < pegs.size(); i++) { pegs[i] = " "; } } string TicTacToe::get_winner() { return winner; } bool TicTacToe::check_column_win() { string previous_player = player == "X" ? "O" : "X"; // <-- TODO: Try to find a better way of handling this, had to do it this way because we call set_next_player in mark_board // Check each columm if Player has marked all 3 board locations if ((pegs[0] == previous_player) && (pegs[3] == previous_player) && (pegs[6] == previous_player)) { TicTacToe::set_winner(); return true; } if ((pegs[1] == previous_player) && (pegs[4] == previous_player) && (pegs[7] == previous_player)) { TicTacToe::set_winner(); return true; } if ((pegs[2] == previous_player) && (pegs[5] == previous_player) && (pegs[8] == previous_player)) { TicTacToe::set_winner(); return true; } return false; } bool TicTacToe::check_row_win() { string previous_player = player == "X" ? "O" : "X"; // <-- TODO: Try to find a better way of handling this // Check each row if Player has marked all 3 board locations if ((pegs[0] == previous_player) && (pegs[1] == previous_player) && (pegs[2] == previous_player)) { TicTacToe::set_winner(); return true; } if ((pegs[3] == previous_player) && (pegs[4] == previous_player) && (pegs[5] == previous_player)) { TicTacToe::set_winner(); return true; } if ((pegs[6] == previous_player) && (pegs[7] == previous_player) && (pegs[8] == previous_player)) { TicTacToe::set_winner(); return true; } return false; } bool TicTacToe::check_diagonal_win() { string previous_player = player == "X" ? "O" : "X"; // <-- TODO: Try to find a better way of handling this // Check diagonal lines if Player has marked all 3 board locations if ((pegs[0] == previous_player) && (pegs[4] == previous_player) && (pegs[8] == previous_player)) { TicTacToe::set_winner(); return true; } if ((pegs[2] == previous_player) && (pegs[4] == previous_player) && (pegs[6] == previous_player)) { TicTacToe::set_winner(); return true; } return false; } void TicTacToe::set_winner() { string previous_player = player == "X" ? "O" : "X"; TicTacToe::winner = previous_player; } src/sst/elements/miranda/generators/randomgen.cc // Copyright 2009-2019 NTESS. Under the terms // of Contract DE-NA0003525 with NTESS, the U.S. // Government retains certain rights in this software. // // Copyright (c) 2009-2019, NTESS // All rights reserved. // // Portions are copyright of other developers: // See the file CONTRIBUTORS.TXT in the top level directory // the distribution for more information. // // This file is part of the SST software package. For license // information, see the LICENSE file in the top level directory of the // distribution. #include #include #include #include using namespace SST::Miranda; #ifndef SST_ENABLE_PREVIEW_BUILD // inserted by script RandomGenerator::RandomGenerator( Component* owner, Params& params ) : RequestGenerator(owner, params) { build(params); } #endif // inserted by script RandomGenerator::RandomGenerator( ComponentId_t id, Params& params ) : RequestGenerator(id, params) { build(params); } void RandomGenerator::build(Params& params) { const uint32_t verbose = params.find("verbose", 0); out = new Output("RandomGenerator[@p:@l]: ", verbose, 0, Output::STDOUT); issueCount = params.find("count", 1000); reqLength = params.find("length", 8); maxAddr = params.find("max_address", 524288); rng = new MarsagliaRNG(11, 31); out->verbose(CALL_INFO, 1, 0, "Will issue %" PRIu64 " operations\n", issueCount); out->verbose(CALL_INFO, 1, 0, "Request lengths: %" PRIu64 " bytes\n", reqLength); out->verbose(CALL_INFO, 1, 0, "Maximum address: %" PRIu64 "\n", maxAddr); issueOpFences = params.find("issue_op_fences", "yes") == "yes"; } RandomGenerator::~RandomGenerator() { delete out; delete rng; } void RandomGenerator::generate(MirandaRequestQueue* q) { out->verbose(CALL_INFO, 4, 0, "Generating next request number: %" PRIu64 "\n", issueCount); const uint64_t rand_addr = rng->generateNextUInt64(); // Ensure we have a reqLength aligned request const uint64_t addr_under_limit = (rand_addr % maxAddr); const uint64_t addr = (addr_under_limit < reqLength) ? addr_under_limit : (rand_addr % maxAddr) - (rand_addr % reqLength); const double op_decide = rng->nextUniform(); // Populate request q->push_back(new MemoryOpRequest(addr, reqLength, (op_decide < 0.5) ? READ : WRITE)); if (issueOpFences) { q->push_back(new FenceOpRequest()); } issueCount--; } bool RandomGenerator::isFinished() { return (issueCount == 0); } void RandomGenerator::completed() { } /* * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * See the NOTICE file distributed with this work for additional information * regarding copyright ownership. 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 "traffic/continuous/TornadoCTP.h" #include #include "bits/bits.h" #include "gtest/gtest.h" #include "nlohmann/json.hpp" #include "prim/prim.h" #include "test/TestSetup_TESTLIB.h" TEST(TornadoCTP, no_dimMask) { TestSetup test(1, 1, 1, 1, 0xBAADF00D); u32 src, dst, numTerminals; nlohmann::json settings; TornadoCTP* tp; std::map pairs; settings["dimensions"][0] = nlohmann::json(5); settings["dimensions"][1] = nlohmann::json(4); settings["concentration"] = nlohmann::json(4); settings["interface_ports"] = nlohmann::json(1); numTerminals = 4 * 4 * 5 * 1; pairs = {{0, 8}, {4, 12}, {8, 16}, {12, 0}, {16, 4}}; for (u32 off = 0; off < 4; ++off) { for (u32 iface = 0; iface < 4; ++iface) { for (const auto& p : pairs) { src = p.first + 4 * 5 * off + iface; dst = p.second + 4 * 5 * off + iface; tp = new TornadoCTP("TP", nullptr, numTerminals, src, settings); for (u32 idx = 0; idx < 100; ++idx) { u32 next = tp->nextDestination(); ASSERT_LT(next, numTerminals); ASSERT_EQ(next, dst); } delete tp; } } } } TEST(TornadoCTP, dimension_0) { TestSetup test(1, 1, 1, 1, 0xBAADF00D); u32 src, dst, numTerminals; nlohmann::json settings; TornadoCTP* tp; std::map pairs; settings["dimensions"][0] = nlohmann::json(5); settings["dimensions"][1] = nlohmann::json(4); settings["concentration"] = nlohmann::json(4); settings["interface_ports"] = nlohmann::json(1); settings["enabled_dimensions"][0] = true; settings["enabled_dimensions"][1] = false; numTerminals = 4 * 4 * 5 * 1; pairs = {{0, 8}, {4, 12}, {8, 16}, {12, 0}, {16, 4}}; for (u32 off = 0; off < 4; ++off) { for (u32 iface = 0; iface < 4; ++iface) { for (const auto& p : pairs) { src = p.first + 4 * 5 * off + iface; dst = p.second + 4 * 5 * off + iface; tp = new TornadoCTP("TP", nullptr, numTerminals, src, settings); for (u32 idx = 0; idx < 100; ++idx) { u32 next = tp->nextDestination(); ASSERT_LT(next, numTerminals); ASSERT_EQ(next, dst); } delete tp; } } } } TEST(TornadoCTP, dimension_1) { TestSetup test(1, 1, 1, 1, 0xBAADF00D); u32 src, dst, numTerminals; nlohmann::json settings; TornadoCTP* tp; std::map pairs; settings["dimensions"][0] = nlohmann::json(5); settings["dimensions"][1] = nlohmann::json(4); settings["concentration"] = nlohmann::json(4); settings["interface_ports"] = nlohmann::json(1); settings["enabled_dimensions"][0] = false; settings["enabled_dimensions"][1] = true; numTerminals = 4 * 4 * 5 * 1; pairs = {{0, 20}, {20, 40}, {40, 60}, {60, 0}}; for (u32 off = 0; off < 5; ++off) { for (u32 iface = 0; iface < 4; ++iface) { for (const auto& p : pairs) { src = p.first + 4 * off + iface; dst = p.second + 4 * off + iface; tp = new TornadoCTP("TP", nullptr, numTerminals, src, settings); for (u32 idx = 0; idx < 100; ++idx) { u32 next = tp->nextDestination(); ASSERT_LT(next, numTerminals); ASSERT_EQ(next, dst); } delete tp; } } } } TEST(TornadoCTP, dimension_1_3d) { TestSetup test(1, 1, 1, 1, 0xBAADF00D); u32 src, dst, numTerminals; nlohmann::json settings; TornadoCTP* tp; std::map pairs; settings["dimensions"][0] = nlohmann::json(5); settings["dimensions"][1] = nlohmann::json(4); settings["dimensions"][2] = nlohmann::json(3); settings["concentration"] = nlohmann::json(4); settings["interface_ports"] = nlohmann::json(1); settings["enabled_dimensions"][0] = false; settings["enabled_dimensions"][1] = true; settings["enabled_dimensions"][2] = false; numTerminals = 3 * 4 * 4 * 5 * 1; pairs = {{0, 20}, {20, 40}, {40, 60}, {60, 0}}; for (u32 off = 0; off < 5; ++off) { for (u32 iface = 0; iface < 4; ++iface) { for (const auto& p : pairs) { src = p.first + 4 * off + iface; dst = p.second + 4 * off + iface; tp = new TornadoCTP("TP", nullptr, numTerminals, src, settings); for (u32 idx = 0; idx < 100; ++idx) { u32 next = tp->nextDestination(); ASSERT_LT(next, numTerminals); ASSERT_EQ(next, dst); } delete tp; } } } } TEST(TornadoCTP, dimension_1_3d_1) { TestSetup test(1, 1, 1, 1, 0xBAADF00D); u32 src, dst, numTerminals; nlohmann::json settings; TornadoCTP* tp; std::map pairs; settings["dimensions"][0] = nlohmann::json(5); settings["dimensions"][1] = nlohmann::json(4); settings["dimensions"][2] = nlohmann::json(3); settings["concentration"] = nlohmann::json(4); settings["interface_ports"] = nlohmann::json(1); settings["enabled_dimensions"] = {false, true, false}; numTerminals = 3 * 4 * 4 * 5 * 1; pairs = {{0, 20}, {20, 40}, {40, 60}, {60, 0}}; for (u32 off = 0; off < 5; ++off) { for (u32 iface = 0; iface < 4; ++iface) { for (const auto& p : pairs) { src = p.first + 4 * off + iface + 4 * 4 * 5; dst = p.second + 4 * off + iface + 4 * 4 * 5; tp = new TornadoCTP("TP", nullptr, numTerminals, src, settings); for (u32 idx = 0; idx < 100; ++idx) { u32 next = tp->nextDestination(); ASSERT_LT(next, numTerminals); ASSERT_EQ(next, dst); } delete tp; } } } } TEST(TornadoCTP, 2d) { TestSetup test(1, 1, 1, 1, 0xBAADF00D); u32 src, dst, numTerminals; nlohmann::json settings; TornadoCTP* tp; std::map pairs; settings["dimensions"][0] = nlohmann::json(5); settings["dimensions"][1] = nlohmann::json(4); settings["concentration"] = nlohmann::json(4); settings["interface_ports"] = nlohmann::json(1); settings["enabled_dimensions"][0] = true; settings["enabled_dimensions"][1] = true; numTerminals = 4 * 4 * 5 * 1; pairs = {{0, 28}, {4, 32}, {8, 36}, {12, 20}, {16, 24}, {20, 48}, {24, 52}, {28, 56}, {32, 40}, {36, 44}, {40, 68}, {44, 72}, {48, 76}, {52, 60}, {56, 64}, {60, 8}, {64, 12}, {68, 16}, {72, 0}, {76, 4}}; for (u32 iface = 0; iface < 4; ++iface) { for (const auto& p : pairs) { src = p.first + iface; dst = p.second + iface; tp = new TornadoCTP("TP", nullptr, numTerminals, src, settings); for (u32 idx = 0; idx < 100; ++idx) { u32 next = tp->nextDestination(); ASSERT_LT(next, numTerminals); ASSERT_EQ(next, dst); } delete tp; } } } TEST(TornadoCTP, 3d) { TestSetup test(1, 1, 1, 1, 0xBAADF00D); u32 src, dst, numTerminals; nlohmann::json settings; TornadoCTP* tp; std::map pairs; settings["dimensions"][0] = nlohmann::json(5); settings["dimensions"][1] = nlohmann::json(4); settings["dimensions"][2] = nlohmann::json(3); settings["concentration"] = nlohmann::json(4); settings["interface_ports"] = nlohmann::json(1); settings["enabled_dimensions"][0] = true; settings["enabled_dimensions"][1] = true; settings["enabled_dimensions"][2] = true; numTerminals = 3 * 4 * 4 * 5 * 1; pairs = {{0, 28}, {4, 32}, {8, 36}, {12, 20}, {16, 24}, {20, 48}, {24, 52}, {28, 56}, {32, 40}, {36, 44}, {40, 68}, {44, 72}, {48, 76}, {52, 60}, {56, 64}, {60, 8}, {64, 12}, {68, 16}, {72, 0}, {76, 4}}; for (u32 iface = 0; iface < 4; ++iface) { for (const auto& p : pairs) { src = p.first + iface + 4 * 4 * 5; dst = p.second + iface + 2 * 4 * 4 * 5; tp = new TornadoCTP("TP", nullptr, numTerminals, src, settings); for (u32 idx = 0; idx < 100; ++idx) { u32 next = tp->nextDestination(); ASSERT_LT(next, numTerminals); ASSERT_EQ(next, dst); } delete tp; } } } // Copyright 2021 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/page_info/core/about_this_site_validation.h" #include "components/page_info/core/proto/about_this_site_metadata.pb.h" #include "url/gurl.h" namespace page_info { namespace about_this_site_validation { AboutThisSiteStatus ValidateSource(const proto::Hyperlink& source) { if (!source.has_label()) return AboutThisSiteStatus::kIncompleteSource; if (!source.has_url()) return AboutThisSiteStatus::kIncompleteSource; GURL url(source.url()); if (!url.is_valid() || !url.SchemeIsHTTPOrHTTPS()) { return AboutThisSiteStatus::kInvalidSource; } return AboutThisSiteStatus::kValid; } AboutThisSiteStatus ValidateDescription( const proto::SiteDescription& description) { if (!description.has_description()) return AboutThisSiteStatus::kMissingDescriptionDescription; if (!description.has_name()) return AboutThisSiteStatus::kMissingDescriptionName; if (!description.has_lang()) return AboutThisSiteStatus::kMissingDescriptionLang; if (!description.has_source()) return AboutThisSiteStatus::kMissingDescriptionSource; return ValidateSource(description.source()); } AboutThisSiteStatus ValidateFirstSeen(const proto::SiteFirstSeen& first_seen) { if (!first_seen.has_count()) return AboutThisSiteStatus::kIncompleteTimeStamp; if (!first_seen.has_unit()) return AboutThisSiteStatus::kIncompleteTimeStamp; if (!first_seen.has_precision()) return AboutThisSiteStatus::kIncompleteTimeStamp; if (first_seen.count() < 0) return AboutThisSiteStatus::kInvalidTimeStamp; if (first_seen.unit() == proto::UNIT_UNSPECIFIED) return AboutThisSiteStatus::kInvalidTimeStamp; if (first_seen.precision() == proto::PRECISION_UNSPECIFIED) return AboutThisSiteStatus::kInvalidTimeStamp; return AboutThisSiteStatus::kValid; } AboutThisSiteStatus ValidateSiteInfo(const proto::SiteInfo& site_info) { if (!site_info.has_description() && !site_info.has_first_seen()) return AboutThisSiteStatus::kEmptySiteInfo; AboutThisSiteStatus status = AboutThisSiteStatus::kValid; if (!site_info.has_description()) return AboutThisSiteStatus::kMissingDescription; status = ValidateDescription(site_info.description()); if (status != AboutThisSiteStatus::kValid) return status; if (site_info.has_first_seen()) status = ValidateFirstSeen(site_info.first_seen()); return status; } AboutThisSiteStatus ValidateMetadata( const absl::optional& metadata) { if (!metadata) return AboutThisSiteStatus::kNoResult; if (!metadata->has_site_info()) return AboutThisSiteStatus::kMissingSiteInfo; return ValidateSiteInfo(metadata->site_info()); } } // namespace about_this_site_validation } // namespace page_info 1-10 #pragma once #include "Defines.hpp" #include "Shape2D.hpp" namespace XGF { namespace Shape { class Circle : public Shape2D { public: //precision:count of triangle Circle(int precision); ~Circle(); void SetPositionAndRadius(float x, float y, float r); virtual bool IsInBoundBox(const Point & p, const SM::Matrix & matrix) override; virtual void SetPosition(const Point & p); //always return 2 int GetLayer(int layer[]); private: float mRadius; }; } } #define GetPrecision(radius,arclen) (static_cast(DirectX::XM_PI/arclen * radius)) ; Libraries/RobsJuceModules/rapt/Math/Functions/FunctionIterators.cpp template rsComplexExponentialIterator::rsComplexExponentialIterator(std::complex a, std::complex z) { this->w = a; this->z = z; } template void rsComplexExponentialIterator::resetValue(std::complex initialValue) { w = initialValue; } template void rsComplexExponentialIterator::setZ(std::complex newZ) { z = newZ; } //================================================================================================= /* template rsSineIterator::rsSineIterator() { a1 = 1.0806046117362795; s1 = -0.84147098480789650; s2 = -0.90929742682568171; // calling setup(1, 0, 1) would compute these values, but that would be more costly. } template rsSineIterator::rsSineIterator(T w, T p, T a) { setup(w, p, a); } */ template void rsSineIterator::setup(T w, T p, T a) { a1 = 2.0*cos(w); s1 = a*sin(p- w); s2 = a*sin(p-2.0*w); // Try to optimize computations of s1,s2 using addition theorems - i think, we may save one call // to sin - but maybe that should be done in a separate function "setupFast" } //================================================================================================= template void rsPolynomialIterator::setup(const T* aIn, T h, T x0) { using Poly = rsPolynomial; // Given the coefficients of a degree N polynomial in a(x) and a stepsize h, this function // computes the coefficients for the degree N-1 correction polynomial c(x) such that // a(x) + c(x) = a(x+h). It may be used in place, i.e. c may point to the same array as a. auto corrector = [](const T* a, T h, int N, T* c) { for(int i = 0; i <= N-1; i++) { T bi = 0; for(int j = i; j <= N; j++) bi += a[j] * rsPow(h, j-i) * T(rsBinomialCoefficient(j, j-i)); //bi += a[j] * pow(h, j-i) * T(rsBinomialCoefficient(j, j-i)); c[i] = bi - a[i]; } }; // maybe make this available as public static member function - oh, but maybe it should go into // class rsPolynomial so it doesn't get instantiated again and again for every N // maybe it should be called getDifferencePolynomial or finiteDifference, forwardDifference or // something ...well, there is already rsPolynomial::finiteDifference which actually already does // the same thing...but the implementation there sucks (allocates heap memory, etc.)...i think, // it should be replaced by (a better version of) the code above T a[N+1]; rsArrayTools::copy(aIn, a, N+1); for(int m = N; m >= 0; m--) { y[m] = Poly::evaluate(x0, a, m); corrector(a, h, m, a); } // ToDo: // -optimize the call to rsBinomialCoefficient and maybe also avoid pow...maybe provide a variant // of the function that lets the caller pass a table of binomial coefficients and keep this // function as convenience function for prototyping (maybe add a qualilfier "Slow") to make it // apparent at the call site // ...or can we compute them at compile time by template trickery? see // https://en.wikipedia.org/wiki/Compile-time_function_execution // -Maybe make a special implementation for cubic polynomials that hardcodes the required // binomial coeffs // -Maybe have two template parameters, one for the state y and one for the type used for a,h,x0 // here. The idea is to use double precision for a,h,x0 and single for y, such that the initial // state does not already have too much roundoff error. // (See Hamming: Numerical Methods..., 2nd ed., pg. 156) } //================================================================================================= template void rsSineSweepIterator::setup(const rsSweepParameters& p) { T coeffsPhs[4]; fitCubicWithDerivative(p.t0, p.t1, p.p0, p.p1, p.w0, p.w1, &coeffsPhs[3], &coeffsPhs[2], &coeffsPhs[1], &coeffsPhs[0]); // ToDo: this API sucks! change it, so we can just pass the pointer to coeffsPhs T coeffsLogAmp[4]; fitCubicWithDerivative(p.t0, p.t1, p.g0, p.g1, p.f0, p.f1, &coeffsLogAmp[3], &coeffsLogAmp[2], &coeffsLogAmp[1], &coeffsLogAmp[0]); rsComplex coeffs[4]; for(int i = 0; i < 4; i++) coeffs[i] = rsComplex(coeffsLogAmp[i], coeffsPhs[i]); core.setup(coeffs, T(1), p.t0); // Could it be numerically better, if we normalize the time interval to 0..1 before computing the // polynomial coeffs? -> experiments needed } /* ToDo: -For rsSineSweepIterator, use a self-written rsComplex class. std::complex doesn't seem to admit usage of simd vector types for T, or in fact, any type other than float, double, long double. See https://en.cppreference.com/w/cpp/numeric/complex "The specializations std::complex, std::complex, and std::complex are LiteralTypes for representing and manipulating complex numbers. The effect of instantiating the template complex for any other type is unspecified." Seems like std::complex is not as flexible i i'd like it to be. ...that applies also to rsComplexExponentialIterator -rsSineCosineIterator : public rsComplexExponentialIterator -rsExponentialIterator, rsLinearIterator, rsQuadraticIterator, rsCubicIterator, rsCubicExpIterator -for the polynomial iterators, see Salomon - Computer Graphics, page 275ff ("Fast Calculation of the Curve" and page 698 ("Forward Differences") -other functions: sinh, cosh, tanh, 1/cosh, 1/cosh^2 (gaussian-like?) Ideas: We can derive iterations for approximating certian functions y = f(x) by constructing an ODE for the function in question and then use a numeric ODE solver to obtain successive solution values. Maybe a multistep method such as the Adams-Bashforth methods could be used: https://en.wikipedia.org/wiki/Linear_multistep_method#Adams%E2%80%93Bashforth_methods https://www.sciencedirect.com/science/article/pii/S0898122110007777 where the initial few values are computed directly by f(x). For example, consider y = x^p Taking the derivative gives: y' = p*x^(p-1) = p*x^p / x = p*y/x so the ODE is y' = p*y/x. Or let's take y = 1/x = x^(-1) y' = -x^(-2) = - x^(-1) * x^(-1) = -y^2 so the ODE is: y' = -y^2. To actually compute y = x^p via an ODE solver, we could define z = 1/x, then use the z' = -z^2 equation to compute 1/x and then use that result in y' = p*y/x, so as to avoid to compute the division by x for each iterate (we use the iteratively computed approximation to 1/x instead of dividing by x. This is similar to what rsPowerIterator does. Notes: here's an interesting thread about a recursive sine oscillator: https://dsp.stackexchange.com/questions/124/how-to-implement-a-digital-oscillator especially the amplitude drift compensation approach with a taylor expansion of 1 / (sqrt(re^2 + im^2)) ~= (1/2) * (3 - (re^2 + im^2)) every 1000 (or something) samples Here also: https://www.vicanek.de/articles/QuadOsc.pdf ..Martin says that this recursion has better numeric stability */#include #include "caffe/layers/split_layer.hpp" #include "caffe/util/math_functions.hpp" namespace caffe { template void SplitLayer::Reshape(const vector*>& bottom, const vector*>& top) { count_ = bottom[0]->count(); for (int i = 0; i < top.size(); ++i) { // Do not allow in-place computation in the SplitLayer. Instead, share data // by reference in the forward pass, and keep separate diff allocations in // the backward pass. (Technically, it should be possible to share the diff // blob of the first split output with the input, but this seems to cause // some strange effects in practice...) CHECK_NE(top[i], bottom[0]) << this->type() << " Layer does not " "allow in-place computation."; top[i]->ReshapeLike(*bottom[0]); CHECK_EQ(count_, top[i]->count()); } } template void SplitLayer::Forward_cpu(const vector*>& bottom, const vector*>& top) { for (int i = 0; i < top.size(); ++i) { top[i]->ShareData(*bottom[0]); } } template void SplitLayer::Backward_cpu(const vector*>& top, const vector& propagate_down, const vector*>& bottom) { if (!propagate_down[0]) { return; } if (top.size() == 1) { caffe_copy(count_, top[0]->cpu_diff(), bottom[0]->mutable_cpu_diff()); return; } /* for(int i = 0; i < 10; i++) { std::cout << top[0]->cpu_diff()[i]; std::cout << "|" << top[1]->cpu_diff()[i]; std::cout << "\n"; } */ caffe_add(count_, top[0]->cpu_diff(), top[1]->cpu_diff(), bottom[0]->mutable_cpu_diff()); // Add remaining top blob diffs. for (int i = 2; i < top.size(); ++i) { const Dtype* top_diff = top[i]->cpu_diff(); Dtype* bottom_diff = bottom[0]->mutable_cpu_diff(); caffe_axpy(count_, Dtype(1.), top_diff, bottom_diff); } } template void SplitLayer::Backward_relevance(const vector*>& top, const vector& propagate_down, const vector*>& bottom) { /* float sum = 0; for (int i = 0; i < top[0]->count(); ++i) { sum += top[0]->cpu_diff()[i]; } std::cout << "SPLIT TOP SUM: " << sum << '\n'; */ //take average unsigned n = bottom[0]->count(); Dtype *bottom_diff = bottom[0]->mutable_cpu_diff(); caffe_copy(n, top[0]->cpu_diff(), bottom_diff); for(unsigned i = 1, ntop = top.size(); i < ntop; i++) { caffe_axpy(n, 1.0, top[i]->cpu_diff(), bottom_diff); } //in our network this is merging softmax and softmaxwithloss, only one of which is //set see wee take the sum instead of the average //average //caffe_scal(n, 1.0/top.size(), bottom_diff); /* sum = 0; for (int i = 0; i < bottom[0]->count(); ++i) { sum += bottom[0]->cpu_diff()[i]; } std::cout << "SPLIT BOTTOM SUM: " << sum << '\n'; */ } #ifdef CPU_ONLY STUB_GPU(SplitLayer); #endif INSTANTIATE_CLASS(SplitLayer); REGISTER_LAYER_CLASS(Split); } // namespace caffe test_orders/main.cpp #include #include #include #include "../rehuel.hpp" #include "../newton.hpp" #include "../test_equations.hpp" #include "clara.hpp" int main( int argc, char **argv ) { bool help = false; double w = 0.1; // test_equations::harmonic func( w ); test_equations::exponential func( -w ); double t1 = 20.0 / w; std::string method = "RADAU_IIA_32"; auto cli = clara::Help( help )["-h"]["--help"] ( "Prints help." ) | clara::Opt( t1, "t1" )["--final-time"] ( "The time to stop the integration." ) | clara::Opt( method, "method" )["-m"]["--method"] ( "The method to use." ); auto args = clara::Args( argc, argv ); auto result = cli.parse( args ); if( !result ){ std::cerr << "Error in command line: " << result.errorMessage() << "\n"; } if( help ){ std::cerr << cli << "\n"; return 0; } int m = irk::name_to_method( method ); std::vector dts = { 5e-3, 1e-2, 2e-2, 5e-2, 1e-1, 2e-1, 5e-1, 1, 1.5, 2, 2.5, 5, 10, 12, 15, 20, 25, 30, 40, 50 }; auto so = irk::default_solver_options(); auto sc = irk::get_coefficients( m ); newton::options no; no.maxit = 100000; so.adaptive_step_size = false; so.newton_opts = &no; so.out_interval = 1000000; std::string fname = "total_error_"; fname += method; fname += ".dat"; std::ofstream err_out( fname ); for( double dt : dts ){ arma::vec y0 = { 1.0 }; irk::rk_output sol = irk::odeint( func, 0, t1, y0, so, m, dt ); double max_rel_err = 0.0; double max_abs_err = 0.0; for( std::size_t i = 0; i < sol.t_vals.size(); ++i ){ double ti = sol.t_vals[i]; arma::vec yi = sol.y_vals[i]; double yreal = func.sol( ti )[0]; double ynumer = yi[0]; double abs_err = std::abs( yreal - ynumer ); double rel_err = abs_err / std::abs( yreal ); max_rel_err = std::max( rel_err, max_rel_err ); max_abs_err = std::max( abs_err, max_abs_err ); err_out << ti << " " << abs_err << " " << rel_err << "\n"; } std::cout << dt << " " << max_abs_err << " " << max_rel_err << "\n"; } return 0; } Lab07/qCPUinterface.cpp #include "qCPUinterface.h" /////////////////////////////////////////////////////////////////////////// void qInterface(const char* m_Method, const char* m_qName, int m_NqBit, int m_nExp) { using namespace std; if ( !strcmp(m_Method,"Add") ) PARAMETER = 1; if ( !strcmp(m_Method,"Redefine") ) PARAMETER = 2; switch (PARAMETER) { case 1: { if (MACHINE==0) { cout<<">>> qInterface:: adding first qCPU"<>> qInterface:: adding new qCPU"<>> qInterface:: redefining qCPU"<>> qInterface::Unknown method, use one of the following: \n> 'Add' add new CPU to the Machine \n> 'Redefine' redefine the existing CPU in the Machine"<>> qInterface::Machine state evaluation "<>> qInterface:: Printing the Machine state "<'Evaluate' evaluate the Machine state"<'Print' printing the Machine state"<'Release' destroy the Machine"< using namespace std; int main() { string s; string n; while(getline(cin,s)) { n = ""; for(int i = 0; i < (int)s.size(); i++) { if(isdigit(s[i]) || toupper(s[i]) == 'O' || s[i] == 'l') { if(s[i] == 'l') { n+='1'; } else if (tolower(s[i]) == 'o') { n+='0'; } else { n+=s[i]; } } else if (s[i] != ',' && s[i] != ' ' && s[i] != 'l' && tolower(s[i]) != 'o') { n = ""; break; } } if(n != "") { try { if(stoi(n) <= 2147483647) cout << stoi(n) << endl; else throw; } catch(...) { cout << "error" << endl; } } else { cout << "error\n"; } } return 0; } #include using namespace std; int main() { RJRobot robot(RobotType::REAL); // here are some useful functions: //robot.SetDriveMotors(127, 127); //robot.Wait(1000ms); //robot.StopMotors(); } ckamtsikis/cmssw #include #include "PhysicsTools/MXNet/interface/Predictor.h" #include "FWCore/ParameterSet/interface/FileInPath.h" using namespace mxnet::cpp; class testMXNetCppPredictor : public CppUnit::TestFixture { CPPUNIT_TEST_SUITE(testMXNetCppPredictor); CPPUNIT_TEST(checkAll); CPPUNIT_TEST_SUITE_END(); public: void checkAll(); }; CPPUNIT_TEST_SUITE_REGISTRATION(testMXNetCppPredictor); void testMXNetCppPredictor::checkAll() { std::string model_path = edm::FileInPath("PhysicsTools/MXNet/test/data/testmxnet-symbol.json").fullPath(); std::string param_path = edm::FileInPath("PhysicsTools/MXNet/test/data/testmxnet-0000.params").fullPath(); // load model and params Block *block = nullptr; CPPUNIT_ASSERT_NO_THROW(block = new Block(model_path, param_path)); CPPUNIT_ASSERT(block != nullptr); // create predictor Predictor predictor(*block); // set input shape std::vector input_names{"data"}; std::vector> input_shapes{{1, 3}}; CPPUNIT_ASSERT_NO_THROW(predictor.set_input_shapes(input_names, input_shapes)); // run predictor std::vector> data{{ 1, 2, 3, }}; std::vector outputs; CPPUNIT_ASSERT_NO_THROW(outputs = predictor.predict(data)); // check outputs CPPUNIT_ASSERT(outputs.size() == 3); CPPUNIT_ASSERT(outputs.at(0) == 42); CPPUNIT_ASSERT(outputs.at(1) == 42); CPPUNIT_ASSERT(outputs.at(2) == 42); delete block; } Sunqia/FastCAE #include "GeoCommandImport.h" #include "geometry/geometryReader.h" #include "mainWindow/mainWindow.h" #include "geometry/geometryData.h" namespace Command { GeoCommandImport::GeoCommandImport(GUI::MainWindow* m, MainWidget::PreWindow* p) : GeoCommandBase(m, p) { connect(this, SIGNAL(showMessage(ModuleBase::Message)), _mainWindow, SIGNAL(printMessageToMessageWindow(ModuleBase::Message))); } void GeoCommandImport::setFileName(QStringList name) { _fileNames = name; } bool GeoCommandImport::execute() { bool ok = false; for (int i = 0; i < _fileNames.size(); ++i) { ModuleBase::Message m; QString filename = _fileNames.at(i); Geometry::GeometryReader reader(filename); if (!reader.read()) { m.type = ModuleBase::Error_Message; m.message = QString("Failed import Geometry From \"%1\"").arg(filename); emit showMessage(m); continue; } ok = true; m.type = ModuleBase::Normal_Message; m.message = QString("Import Geometry From \"%1\"").arg(filename); emit showMessage(m); QList setList = reader.getResult(); for (auto set : setList) { _resSet.append(set); emit showSet(set); } } emit updateGeoTree(); return ok; } void GeoCommandImport::undo() { for (int i = 0; i < _resSet.size(); ++i) { auto s = _resSet.at(i); _geoData->removeTopGeometrySet(s); emit removeDisplayActor(s); } emit updateGeoTree(); } void GeoCommandImport::redo() { for (int i = 0; i < _resSet.size(); ++i) { auto s = _resSet.at(i); _geoData->appendGeometrySet(s); emit showSet(s); } emit updateGeoTree(); } void GeoCommandImport::releaseResult() { for (int i = 0; i < _resSet.size(); ++i) { auto s = _resSet.at(i); delete s; } _resSet.clear(); } }#include #include #include #include #include #include #include #ifdef HAVE_NCURSES #include // For COLORS #else #define COLORS 16 #endif #define CSI "\x1B[" using namespace detail; AnsiDisplayBase::AnsiDisplayBase() : lastAttr(SGRAttribs::defaultInit), sgrFlags(0) { if (TermIO::isLinuxConsole()) sgrFlags |= sgrBrightIsBlink | sgrNoItalic | sgrNoUnderline; if (COLORS < 16) sgrFlags |= sgrBrightIsBold; } AnsiDisplayBase::~AnsiDisplayBase() { clearAttributes(); lowlevelFlush(); } void AnsiDisplayBase::bufWrite(TStringView s) { buf.insert(buf.end(), s.data(), s.data()+s.size()); } void AnsiDisplayBase::bufWriteCSI1(uint a, char F) { // CSI a F char s[32] = CSI; char *p = s + sizeof(CSI) - 1; p += fast_utoa(a, p); *p++ = F; bufWrite({s, size_t(p - s)}); } void AnsiDisplayBase::bufWriteCSI2(uint a, uint b, char F) { // CSI a ; b F char s[32] = CSI; char *p = s + sizeof(CSI) - 1; p += fast_utoa(a, p); *p++ = ';'; p += fast_utoa(b, p); *p++ = F; bufWrite({s, size_t(p - s)}); } void AnsiDisplayBase::clearAttributes() { bufWrite(CSI "0m"); lastAttr = {}; } void AnsiDisplayBase::clearScreen() { bufWrite(CSI "2J"); } void AnsiDisplayBase::lowlevelWriteChars(TStringView chars, TCellAttribs attr) { writeAttributes(attr); bufWrite(chars); } void AnsiDisplayBase::lowlevelMoveCursorX(uint x, uint) { // Optimized case where the cursor only moves horizontally. bufWriteCSI1(x + 1, 'G'); } void AnsiDisplayBase::lowlevelMoveCursor(uint x, uint y) { // Make dumps readable. // bufWrite("\r"); bufWriteCSI2(y + 1, x + 1, 'H'); } void AnsiDisplayBase::lowlevelFlush() { TermIO::consoleWrite(buf.data(), buf.size()); buf.resize(0); } void AnsiDisplayBase::writeAttributes(TCellAttribs c) { SGRAttribs sgr {c, sgrFlags}; SGRAttribs last = lastAttr; if (sgr != lastAttr) { char s[64] = CSI; char *p = s + sizeof(CSI) - 1; if (sgr.fg != last.fg) { p += fast_utoa(sgr.fg, p); *p++ = ';'; } if (sgr.bg != last.bg) { p += fast_utoa(sgr.bg, p); *p++ = ';'; } if (sgr.bold != last.bold) { p += fast_utoa(sgr.bold, p); *p++ = ';'; } if (sgr.blink != last.blink) { p += fast_utoa(sgr.blink, p); *p++ = ';'; } if (sgr.italic != last.italic) { p += fast_utoa(sgr.italic, p); *p++ = ';'; } if (sgr.underline != last.underline) { p += fast_utoa(sgr.underline, p); *p++ = ';'; } if (sgr.reverse != last.reverse) { p += fast_utoa(sgr.reverse, p); *p++ = ';'; } *(p - 1) = 'm'; lastAttr = sgr; bufWrite({s, size_t(p - s)}); } } src/alloc.cpp #include #include #include #include #include #include #include #include #include #include #include #include namespace exprc { namespace { template class DevicePool { public: DevicePool(dev::Context& context) : m_context(context) , m_unallocated(m_list.begin()) { } auto& alloc() { if (m_unallocated == m_list.end()) { auto& dev = m_list.emplace_back(m_context.make()); m_unallocated = m_list.end(); return dev; } return *m_unallocated++; } void reset() { m_unallocated = m_list.begin(); } auto& list() const { return m_list; } private: dev::Context& m_context; std::list m_list; decltype(m_list.begin()) m_unallocated; }; template class IoPool { public: IoPool(dev::Context& context) : m_context(context) { } const auto& alloc(const std::string& name) { return m_list.emplace_back(m_context.make(name)); } auto& list() const { return m_list; } private: dev::Context& m_context; std::list m_list; }; class RegisterPool { public: RegisterPool(dev::Context& context) : m_context(context) { } auto alloc() { if (m_unallocated.empty()) { auto reg = m_context.make(); return m_regs.emplace(reg, reg).first->second.id; } auto reg = m_unallocated.front(); m_unallocated.pop(); return reg; } void put(dev::DeviceId reg) { m_unallocated.push(reg); } auto& regs() const { return m_regs; } auto& reg(dev::DeviceId id) { return m_regs.at(id); } private: dev::Context& m_context; std::queue m_unallocated; std::unordered_map m_regs; }; class DeviceAllocator { public: DeviceAllocator(dev::Context& context, const std::multimap>& schedule, const std::unordered_map& name_by_oper) : m_context(context) , m_inputs(context) , m_outputs(context) , m_adders(context) , m_multipliers(context) , m_regs(context) , m_schedule(schedule) , m_name_by_oper(name_by_oper) { } DataPath doIt() { allocateRegisters(); allocateDevices(); return DataPath{m_inputs.list(), m_outputs.list(), m_adders.list(), m_multipliers.list(), m_regs.regs(), m_driver_list}; } private: void allocateDevices(); void allocateRegisters(); template void mapIn(uint32_t, const Instruction&, const Device&); template void mapOut(uint32_t, const Instruction&, const Device&); template void mapIo(uint32_t, const Instruction&, const Device&); const std::string& inputName(const Instruction&); const std::string& outputName(const Instruction&); dev::Context& m_context; IoPool m_inputs; IoPool m_outputs; DevicePool m_adders; DevicePool m_multipliers; RegisterPool m_regs; std::unordered_map m_reg_mapping; std::unordered_map m_fed_by_reg; std::unordered_map m_fed_by_input; const std::multimap>& m_schedule; const std::unordered_map& m_name_by_oper; std::map, dev::OutPort::Id> m_driver_list; }; template void DeviceAllocator::mapIn(uint32_t step, const Instruction& instr, const Device& device) { assert(instr.src.size() == device.in.size()); for (size_t i = 0; i < instr.src.size(); ++i) { auto& op = instr.src[i]; auto& in = device.in[i]; // at first step in ports feed devices directly, later everything are fed by regs auto& m_fed_by = (step == 1) ? m_fed_by_input : m_fed_by_reg; m_driver_list.emplace(std::make_tuple(step, in), m_fed_by.at(op)); } } template <> void DeviceAllocator::mapOut(uint32_t step, const Instruction& instr, const dev::Output&) { } template void DeviceAllocator::mapOut(uint32_t step, const Instruction& instr, const Device& device) { if (!instr.dst) return; auto& dst = *instr.dst; auto it = m_reg_mapping.find(dst); if (it == m_reg_mapping.end()) { assert(instr.opcode == Opcode::INPUT && step == 0); m_fed_by_input.emplace(dst, device.out); } else { auto& reg = m_regs.reg(it->second); // zero step is not really exists, so assignment should be done in first one m_driver_list.emplace(std::make_tuple(std::max(step, 1u), reg.in[0]), device.out); m_fed_by_reg.emplace(dst, reg.out); } } template void DeviceAllocator::mapIo(uint32_t step, const Instruction& instr, const Device& device) { mapIn(step, instr, device); mapOut(step, instr, device); } const std::string& DeviceAllocator::inputName(const Instruction& input) { return m_name_by_oper.at(input.dst.value()); } const std::string& DeviceAllocator::outputName(const Instruction& output) { return m_name_by_oper.at(output.src.at(0)); } void DeviceAllocator::allocateDevices() { auto last_step = m_schedule.rbegin()->first; for (uint32_t step = 0; step <= last_step; ++step) { m_adders.reset(); m_multipliers.reset(); for (auto p : m_schedule.equal_range(step)) { const Instruction& instr = p.second; switch (instr.opcode) { case Opcode::ADD: mapIo(step, instr, m_adders.alloc()); break; case Opcode::MUL: mapIo(step, instr, m_multipliers.alloc()); break; case Opcode::INPUT: mapIo(step, instr, m_inputs.alloc(inputName(instr))); break; case Opcode::OUTPUT: mapIo(step, instr, m_outputs.alloc(outputName(instr))); } } } } void DeviceAllocator::allocateRegisters() { // zero step contains only INPUT instructions // first step instructions are fed by ports auto last_step = m_schedule.rbegin()->first; for (auto step = last_step; step > 1; --step) for (auto p : m_schedule.equal_range(step)) { const Instruction& instr = p.second; if (instr.dst) m_regs.put(m_reg_mapping.at(*instr.dst)); for (auto& src : instr.src) if (m_reg_mapping.find(src) == m_reg_mapping.end()) m_reg_mapping.emplace(src, m_regs.alloc()); } } } // namespace DataPath allocate(const std::multimap>& schedule, const std::unordered_map& name_by_oper) { exprc::dev::Context context; exprc::DeviceAllocator allocator(context, schedule, name_by_oper); return allocator.doIt(); } } // namespace exprc // 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 "chrome/browser/ui/android/infobars/data_reduction_proxy_infobar.h" #include "base/android/jni_android.h" #include "base/android/jni_string.h" #include "base/logging.h" #include "chrome/browser/android/resource_mapper.h" #include "chrome/browser/net/spdyproxy/data_reduction_proxy_infobar_delegate.h" #include "content/public/browser/web_contents.h" #include "jni/DataReductionProxyInfoBarDelegate_jni.h" // DataReductionProxyInfoBar: // static void DataReductionProxyInfoBar::Launch( JNIEnv* env, jclass, jobject jweb_contents, jstring jlink_url) { content::WebContents* web_contents = content::WebContents::FromJavaWebContents(jweb_contents); DCHECK(web_contents); DataReductionProxyInfoBarDelegate::Create( web_contents, base::android::ConvertJavaStringToUTF8(env, jlink_url)); } // static bool DataReductionProxyInfoBar::Register(JNIEnv* env) { return RegisterNativesImpl(env); } DataReductionProxyInfoBar::DataReductionProxyInfoBar( scoped_ptr delegate) : ConfirmInfoBar(delegate.Pass()), java_data_reduction_proxy_delegate_() { } DataReductionProxyInfoBar::~DataReductionProxyInfoBar() { } base::android::ScopedJavaLocalRef DataReductionProxyInfoBar::CreateRenderInfoBar(JNIEnv* env) { java_data_reduction_proxy_delegate_.Reset( Java_DataReductionProxyInfoBarDelegate_create(env)); return Java_DataReductionProxyInfoBarDelegate_showDataReductionProxyInfoBar( env, java_data_reduction_proxy_delegate_.obj(), reinterpret_cast(this), GetEnumeratedIconId()); } DataReductionProxyInfoBarDelegate* DataReductionProxyInfoBar::GetDelegate() { return static_cast(delegate()); } // DataReductionProxyInfoBarDelegate: // static scoped_ptr DataReductionProxyInfoBarDelegate::CreateInfoBar( scoped_ptr delegate) { return scoped_ptr( new DataReductionProxyInfoBar(delegate.Pass())); } // JNI for DataReductionProxyInfoBarDelegate. void Launch(JNIEnv* env, jclass clazz, jobject jweb_contents, jstring jlink_url) { DataReductionProxyInfoBar::Launch(env, clazz, jweb_contents, jlink_url); } 0 // Copyright 2015 National ICT Australia Limited (NICTA) // // 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 "PowerToolsSupport.h" #include "Network.h" #include "CommonBranch.h" #include "Stopwatch.h" #include #include #include namespace Sgt { std::unique_ptr sgt2PowerTools(const Sgt::Network& sgtNw) { std::unique_ptr net(new Net); net->bMVA = sgtNw.PBase(); for (auto& bus : sgtNw.buses()) { std::string busId = bus->id(); Complex PLoad = sgtNw.S2Pu(bus->SConst()(0)); Complex yShunt = sgtNw.Y2Pu(bus->YConst()(0), bus->VBase()); Complex V = sgtNw.V2Pu(bus->V()(0), bus->VBase()); double VMin = sgtNw.V2Pu(bus->VMagMin(), bus->VBase()); double VMax = sgtNw.V2Pu(bus->VMagMax(), bus->VBase()); double kVBase = bus->VBase(); Node* node = new Node(busId, PLoad.real(), PLoad.imag(), yShunt.real(), yShunt.imag(), VMin, VMax, kVBase, 1); node->vs = std::abs(V); net->add_node(node); for (const auto& gen : bus->gens()) { double PMin = sgtNw.S2Pu(gen->PMin()); double PMax = sgtNw.S2Pu(gen->PMax()); double QMin = sgtNw.S2Pu(gen->QMin()); double QMax = sgtNw.S2Pu(gen->QMax()); ::Gen* g = new ::Gen(node, gen->id(), PMin, PMax, QMin, QMax); g->_active = gen->isInService(); double c0 = gen->c0(); double c1 = gen->c1(); double c2 = gen->c2(); g->set_costs(c0, c1, c2); net->gens.push_back(g); node->_gen.push_back(g); } } for (const auto& branch : sgtNw.branches()) { auto cBranch = branch.raw(); auto bus0 = branch->bus0(); auto bus1 = branch->bus1(); std::string id = cBranch->id(); std::string bus0Id = bus0->id(); std::string bus1Id = bus1->id(); auto arc = new Arc(id); arc->src = net->get_node(bus0Id); arc->dest = net->get_node(bus1Id); arc->connect(); Complex YSeries = sgtNw.Y2Pu(cBranch->YSeries(), bus1->VBase()); Complex ZSeries = sgtNw.Z2Pu(1.0/cBranch->YSeries(), bus1->VBase()); Complex yShunt = sgtNw.Y2Pu(cBranch->YShunt(), bus1->VBase()); double lim = sgtNw.S2Pu(cBranch->rateA()); Complex tap = cBranch->tapRatio()*bus1->VBase()/bus0->VBase(); // Off nominal tap ratio. arc->g = YSeries.real(); arc->b = YSeries.imag(); arc->r = ZSeries.real(); arc->x = ZSeries.imag(); arc->tr = std::abs(tap); arc->as = std::arg(tap); assert(std::abs(yShunt.real()) < 1e-9); arc->ch = yShunt.imag(); arc->cc = arc->tr * cos(arc->as); arc->dd = arc->tr * sin(arc->as); arc->tbound.min = cBranch->angMin(); arc->tbound.max = cBranch->angMax(); arc->limit = lim; arc->status = branch->isInService() ? 1 : 0; net->add_arc(arc); } return net; } void powerTools2Sgt(const Net& ptNetw, Sgt::Network& sgtNw) { for (auto node: ptNetw.nodes) { auto sgtBus = sgtNw.buses()[node->_name]; if (!sgtBus->isInService()) continue; // If not in service, ignore what PowerTools says. assert(sgtBus->gens().size() == node->_gen.size()); Complex VSolPu(node->vr.get_value(), node->vi.get_value()); Complex VSol = sgtNw.pu2V(VSolPu, sgtBus->VBase()); sgtBus->setV({VSol}); Complex SLoadUnservedSolPu(-node->plv.get_value(), -node->qlv.get_value()); Complex SLoadUnservedSol = sgtNw.pu2S(SLoadUnservedSolPu); if (std::abs(SLoadUnservedSol) > 1e-3) { sgtLogWarning() << "Unserved load at bus " << sgtBus->id() << " is " << SLoadUnservedSol << std::endl; } sgtBus->setSZipUnserved({SLoadUnservedSol}); sgtBus->setSGenUnserved(arma::Col(sgtBus->phases().size(), arma::fill::zeros)); auto nGen = node->_gen.size(); auto nSgtGen = sgtBus->gens().size(); assert(nGen == nSgtGen); for (std::size_t i = 0; i < nGen; ++i) { // Order of gens should be same in Sgt and Pt. auto sgtGen = sgtBus->gens()[i].raw(); if (!sgtGen->isInService()) continue; // If not in service, ignore what PowerTools says. auto gen = node->_gen[i]; Complex SGenSolPu(gen->pg.get_value(), gen->qg.get_value()); Complex SGenSol = sgtNw.pu2S(SGenSolPu); sgtGen->setInServiceS({SGenSol}); } } } void printNetw(const Net& net) { sgtLogMessage() << "Nodes-----------------" << std::endl; for (const auto node : net.nodes) { node->print(); } sgtLogMessage() << "Arcs------------------" << std::endl; for (const auto arc : net.arcs) { arc->print(); } sgtLogMessage() << "Gens------------------" << std::endl; for (const auto gen : net.gens) { gen->print(); } sgtLogMessage() << "Done------------------" << std::endl; } void printModel(const Model& mod) { std::cout << "----vars----" << std::endl; for (auto v : mod._vars) { if (v->is_int()) { static_cast*>(v)->print(); } else if (v->is_binary()) { static_cast*>(v)->print(); } else if (v->is_real()) { static_cast*>(v)->print(); } else if (v->is_longreal()) { static_cast*>(v)->print(); } } std::cout << "------------" << std::endl; std::cout << "----constrs----" << std::endl; for (auto cons : mod.get_cons()) { cons->print(); } std::cout << "------------" << std::endl; std::cout << "----objective----" << std::endl; mod._obj->print(false); std::cout << std::endl; std::cout << "------------" << std::endl; } } #include #include #include #include #include #include #include #include #include #include NAMESPACE_BEGIN(kazen) void Renderer::renderSample(const Scene *scene, Sampler *sampler, ImageBlock &block, const Vector2f &pos, Mask active) { // TODO } void Renderer::renderBlock(const Scene *scene, Sampler *sampler, ImageBlock &block) { #include usleep(1000000); /* Clear the block contents */ block.clear(); } void Renderer::render(Scene *scene, const std::string &filename) { // FIXME ScalarVector2i outputSize(1000, 1000); /* Create a block generator (i.e. a work scheduler) */ BlockGenerator blockGenerator(outputSize, KAZEN_BLOCK_SIZE); /* Allocate memory for the entire output image and clear it */ PropertyList list; list.setInt("index", 4); ReconstructionFilter* filter = static_cast(ObjectFactory::createInstance("tent", list)); ImageBlock result(outputSize, filter); result.clear(); /* Do the following in parallel and asynchronously */ std::thread render_thread([&] { auto progress = Progress("Rendering..."); std::mutex mutex; // Total number of blocks to be handled, including multiple passes. size_t totalBlocks = blockGenerator.getBlockCount(); size_t blocksDone = 0; tbb::blocked_range range(0, blockGenerator.getBlockCount()); auto map = [&](const tbb::blocked_range &range) { /* Allocate memory for a small image block to be rendered by the current thread */ PropertyList list; list.setInt("index", 4); ReconstructionFilter* filter = static_cast(ObjectFactory::createInstance("tent", list)); ImageBlock block(ScalarVector2i(KAZEN_BLOCK_SIZE), filter); /* Create a clone of the sampler for the current thread */ // std::unique_ptr sampler(scene->getSampler()->clone()); for (int i=range.begin(); i lock(mutex); blocksDone++; progress.update(blocksDone / (ScalarFloat) totalBlocks); } } }; /// Default: parallel rendering tbb::parallel_for(range, map); }); /* Shut down the user interface */ render_thread.join(); } NAMESPACE_END(kazen) 1-10 #include "stocks.h" #include "helper.h" #include "math/stats.h" #include #include using namespace std; namespace cpp_project::invest { stocks& stocks::feed_history(const candle& price) { history.emplace_back(price); return *this; } stocks& stocks::feed_history(candle&& price) { history.emplace_back(move(price)); return *this; } float stocks::calculate_average_price() const { std::vector avg_price_points; avg_price_points.reserve(history.size()); std::transform(history.begin(), history.end(), std::back_inserter(avg_price_points), [](const auto& p) { return helper::calculate_average_price(p); }); return stats::average(avg_price_points); } } // namespace cpp_project::invest /* Copyright 2020 Esri 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. For additional information, contact: Environmental Systems Research Institute, Inc. Attn: Contracts Dept 380 New York Street Redlands, California, USA 92373 email: */ #include "pch.h" #include "utils/utl_mime.h" #include "utils/utl_i3s_assert.h" #include "utils/utl_bitstream.h" #include namespace i3slib { namespace utl { namespace { static_assert((Mime_type_set)Mime_type::_next_ == 256, "Please update constants 'string' below"); constexpr int c_type_ext_count = 7; const char* const c_type_ext[c_type_ext_count] { //MUST BE IN POWER OF 2 ORDER ( to_known_mime_type() expects this) "json", // = 2, "bin",// = 4, "jpg", //= 8, "png", // = 16, "dds",// = 32, "bin.dds",// = 64, "bin.ktx"// = 128, }; static_assert((Mime_encoding_set)Mime_encoding::_next_ == 32, "Please update constants 'string' below"); constexpr int c_encoding_ext_count = 4; const char* const c_encoding_ext[c_encoding_ext_count] { "gz", //= 2, "pccxyz", // = 4, "pccrgb",// = 8, "pccint"// = 16, }; } void add_slpk_extension_to_path(std::string* path, const Mime_type& type, const Mime_encoding& pack) { I3S_ASSERT((Mime_type_set)type && (Mime_encoding_set)pack); int bit = first_bit_set((Mime_type_set)type) - 2; if (bit >= 0 && bit < c_type_ext_count) { path->append(".").append(c_type_ext[bit]); } bit = first_bit_set((Mime_encoding_set)pack) - 2; if (bit >= 0 && bit < c_encoding_ext_count) path->append(".").append(c_encoding_ext[bit]); } //! returns Not_set if not known. This function is case-sensitive Mime_type to_known_mime_type(const char* str, int len) { for (int i = 0; i < c_type_ext_count; ++i) { int expected_len = (int)std::strlen(c_type_ext[i]); if (expected_len == len && std::memcmp(c_type_ext[i], str, expected_len) == 0) return (Mime_type)(1 << (i + 1)); } return Mime_type::Not_set; } } // namespace utl } // namespace i3slib /** * 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. */ /** * File: LevelGenerator.hpp * Creation: 2015-03-02 16:05 * <> */ #ifndef __LevelGenerator__ # define __LevelGenerator__ # include # include # include # include # include "Room.hpp" class LevelGenerator { public: LevelGenerator(int maxMapSize, int minPathLenght, int doorsPopRate); ~LevelGenerator(); void print(void); void execute(void); //execute generation process void createFirstRoom(void); void firstPass(int distance); //generate base rooms void generateRoomsBehindDoors(Room* room); Room* generateRoom(int x, int y, int distance, Room* prevRoom, int origin); bool testDoor(int x, int y); bool testRoom(int x, int y); void linkAdjacentRooms(Room *room); void shockwave(void); int getEntryId(void); int id(void); std::vector > getLevel(void); std::vector *_rooms; std::vector > roomMap; int getStartX(); int getStartY(); int getNbMaps(); std::string getSpecialRoom(int i, int j); private: int _id; int _height; int _width; int _nbMaps; int _minPathLenght; int _maxMapSize; int _doorsPopRate; int _startX; int _startY; }; #endif SummerSad/HCMUS-Lectures #include using namespace std; int main() { system("cls"); system("\"\"C:\\Users\\sv\\Documents\\Visual Studio 2013\\Projects\\1612180\\Debug\\SapXep.exe\" \"C:\\Users\\sv\\Documents\\Visual Studio 2013\\Projects\\1612180\\Debug\\in.txt\" \"C:\\Users\\sv\\Documents\\Visual Studio 2013\\Projects\\1612180\\Debug\\out.txt\" \"1\" \""); return 0; }1-10 /* * Copyright 2019 * * 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. * * this file was made by tianxiaochun. * if any question ,touch me by * 2019,03,06 */ #include "ktransfcoordinate.h" // 长半径:a=6378137±2(m); // 地球引力和地球质量的乘积:GM=3986005×108m3s-2±0.6×108m3s-2; // 正常化二阶带谐系数:C20=-484.16685×10-6±1.3×10-9; // 地球重力场二阶带球谐系数:J2=108263×10-8 // 地球自转角速度:ω=7292115×10-11rads-1±0.150×10-11rads-1 // 扁率f=0.003352810664 double a = 6378137.0; double f = 1.0 / 298.257; // double b = (1 - f)*a; // double e = sqrt(a*a - b * b) / a; double e2 = e * e; double mean_R=(a+b)/2.0; KTransfCoordinate::KTransfCoordinate() { } KTransfCoordinate::~KTransfCoordinate() { } void KTransfCoordinate::enu2llh(double enu[3], double orgllh[3], double llh[3]) { double neworgllh[3] = { 0,0,0 }; double xyz[3] = { 0,0,0 }; for(int index=0;index<2;index++) { neworgllh[index]=orgllh[index]*PI/180.0f; } enu2xyz(enu, neworgllh, xyz); xyz2llh(xyz, llh); for(int index=0;index<2;index++) { llh[index]=llh[index]*180.0f/PI; } } void KTransfCoordinate::enu2xyz(double enu[3], double orgllh[3], double xyz[3]) { double lat = orgllh[0], lon = orgllh[1], height = orgllh[2]; double slat = sin(lat), clat = cos(lat), slon = sin(lon), clon = cos(lon); double orgxyz[3], difxyz[3]; double R_1[3][3] = { -slon,-slat * clon,clat*clon,clon,-slat * slon,clat*slon,0,clat,slat }; llh2xyz(orgllh, orgxyz); int i, j; for (i = 0; i<3; i++) { difxyz[i] = 0; for (j = 0; j<3; j++) { difxyz[i] = difxyz[i] + R_1[i][j] * enu[j]; } xyz[i] = orgxyz[i] + difxyz[i]; } } void KTransfCoordinate::llh2enu(double llh[3], double orgllh[3], double enu[3]) { double newllh[3] = { 0,0,0 }; double neworgllh[3] = { 0,0,0 }; double xyz[3] = { 0,0,0 }; for(int index=0;index<2;index++) { newllh[index]=llh[index]*PI/180.0f; neworgllh[index]=orgllh[index]*PI/180.0f; } llh2xyz(newllh, xyz); xyz2enu(xyz, neworgllh, enu); } void KTransfCoordinate::llh2xyz(double llh[3], double xyz[3]) { double lat = llh[0], lon = llh[1], height = llh[2]; double slat = sin(lat), clat = cos(lat), slon = sin(lon), clon = cos(lon); double t2lat = (tan(lat))*(tan(lat)); double tmp = 1 - e * e; double tmpden = sqrt(1 + tmp * t2lat); double tmp2 = sqrt(1 - e * e*slat*slat); double x = (a*clon) / tmpden + height * clon*clat; double y = (a*slon) / tmpden + height * slon*slat; double z = (a*tmp*slat) / tmp2 + height * slat; xyz[0] = x; xyz[1] = y; xyz[2] = z; } void KTransfCoordinate::posupdate_LLH(double llh[3], double deltenu[3]) { for(int index=0;index<2;index++) { llh[index]=llh[index]*PI/180.0f; } double lat = llh[0], lon = llh[1], height = llh[2]; double DE = deltenu[0], DN = deltenu[1], DU = deltenu[2]; double slat = sin(lat), clat = cos(lat), tlat = slat / clat; double sq = 1 - e2 * slat*slat, sq2 = sqrt(sq); double RMh = a * (1 - e2) / sq / sq2 + height; // 子午圈曲率半径 double RNh = a / sq2 + height; //卯酉圈曲率半径 double clRNh = clat * RNh; lat += DN / RMh; lon += DE / clRNh; height += DU; llh[0] = lat; llh[1] = lon; llh[2] = height; for(int index=0;index<2;index++) { llh[index]=llh[index]*180.0f/PI; } } void KTransfCoordinate::xyz2enu(double xyz[3], double orgllh[3], double enu[3]) { double lat = orgllh[0], lon = orgllh[1], height = orgllh[2]; double slat = sin(lat), clat = cos(lat), slon = sin(lon), clon = cos(lon); double tmpxyz[3], orgxyz[3],tmporg[3], difxyz[3]; enu[0] = 0; enu[1] = 0; enu[2] = 0; llh2xyz(orgllh, orgxyz); int i; for (i = 0; i<3; i++) { tmpxyz[i] = xyz[i]; tmporg[i] = orgxyz[i]; difxyz[i] = tmpxyz[i] - tmporg[i]; } double R[3][3] = { { -slon,clon,0 },{ -slat * clon,-slat * slon,clat },{ clat*clon,clat*slon,slat } }; for (i = 0; i<3; i++) { enu[0] = enu[0] + R[0][i] * difxyz[i]; enu[1] = enu[1] + R[1][i] * difxyz[i]; enu[2] = enu[2] + R[2][i] * difxyz[i]; } } void KTransfCoordinate::xyz2llh(double xyz[3], double llh[3]) { double x = xyz[0], y = xyz[1], z = xyz[2]; double x2 = x * x, y2 = y * y, z2 = z * z; double b2 = b * b; double ep = e * (a / b); double r = sqrt(x2 + y2); double r2 = r * r; double E2 = a * a - b * b; double F = 54 * b2*z2; double G = r2 + (1 - e2)*z2 - e2 * E2; double c = (e2*e2*F*r2) / (G*G*G); double s = pow(double(1 + c + sqrt(c*c + 2 * c)), double(1.0 / 3.0)); double P = F / (3 * (s + 1 / s + 1)*(s + 1 / s + 1) * G*G); double Q = sqrt(1 + 2 * e2*e2*P); double ro = -(P*e2*r) / (1 + Q) + sqrt((a*a / 2)*(1 + 1 / Q) - (P*(1 - e2)*z2) / (Q*(1 + Q)) - P * r2 / 2); double tmp = (r - e2 * ro)*(r - e2 * ro); double U = sqrt(tmp + z2); double V = sqrt(tmp + (1 - e2)*z2); double zo = (b2*z) / (a*V); double height = U * (a*V - b2) / (a*V); double lat = atan((z + ep * ep*zo) / r); double longth; double temp = atan(y / x); if (x >= 0) { longth = temp; } else if ((x < 0) & (y >= 0)) { longth = PI + temp; } else { longth = temp - PI; } llh[0] = lat; llh[1] = longth; llh[2] = height; } double KTransfCoordinate::cal_distance_2llh(double llh_start[3], double llh_end[3]) { double newllh_start[3] = { 0,0,0 }; double newllh_end[3] = { 0,0,0 }; for(int index=0;index<2;index++) { newllh_start[index]=llh_start[index]*PI/180.0d; newllh_end[index]=llh_end[index]*PI/180.0d; } double vlat = fabs (newllh_start[0]-newllh_end[0]); double vlong = fabs(newllh_start[1]-newllh_end[1]); double vh = fabs(newllh_start[2]-newllh_end[2]); double distance = asin (sqrt(sin(vlat/2)*sin(vlat/2)+cos(newllh_start[0])*cos(newllh_end[0])*sin(vlong/2)*sin(vlong/2))); distance = 2.0*distance*mean_R; return distance; } 1-10 // Borland C++ Builder // Copyright (c) 1995, 1999 by Borland International // All rights reserved // (DO NOT EDIT: machine generated header) 'AviWriter.pas' rev: 5.00 #ifndef AviWriterHPP #define AviWriterHPP #pragma delphiheader begin #pragma option push -w- #pragma option push -Vx #include // Pascal unit #include // Pascal unit #include // Pascal unit #include // Pascal unit #include // Pascal unit #include // Pascal unit #include // Pascal unit #include // Pascal unit #include // Pascal unit #include // Pascal unit #include // Pascal unit #include // Pascal unit //-- user supplied ----------------------------------------------------------- namespace Aviwriter { //-- type declarations ------------------------------------------------------- //typedef int LONG; typedef void *PVOID; struct TAVIFileInfoW { unsigned dwMaxBytesPerSec; unsigned dwFlags; unsigned dwCaps; unsigned dwStreams; unsigned dwSuggestedBufferSize; unsigned dwWidth; unsigned dwHeight; unsigned dwScale; unsigned dwRate; unsigned dwLength; unsigned dwEditCount; wchar_t szFileType[64]; } ; typedef TAVIFileInfoW *PAVIFileInfoW; struct TAVIStreamInfoA { unsigned fccType; unsigned fccHandler; unsigned dwFlags; unsigned dwCaps; Word wPriority; Word wLanguage; unsigned dwScale; unsigned dwRate; unsigned dwStart; unsigned dwLength; unsigned dwInitialFrames; unsigned dwSuggestedBufferSize; unsigned dwQuality; unsigned dwSampleSize; Windows::TRect rcFrame; unsigned dwEditCount; unsigned dwFormatChangeCount; char szName[64]; } ; typedef TAVIStreamInfoA TAVIStreamInfo; typedef TAVIStreamInfoA *PAVIStreamInfo; struct TAVIStreamInfoW { unsigned fccType; unsigned fccHandler; unsigned dwFlags; unsigned dwCaps; Word wPriority; Word wLanguage; unsigned dwScale; unsigned dwRate; unsigned dwStart; unsigned dwLength; unsigned dwInitialFrames; unsigned dwSuggestedBufferSize; unsigned dwQuality; unsigned dwSampleSize; Windows::TRect rcFrame; unsigned dwEditCount; unsigned dwFormatChangeCount; wchar_t szName[64]; } ; typedef void *PAVIStream; typedef void *PAVIFile; typedef void *TAVIStreamList[1]; typedef void * *PAVIStreamList; typedef int __stdcall (*TAVISaveCallback)(int nPercent); #pragma pack(push, 1) struct TAVICompressOptions { unsigned fccType; unsigned fccHandler; unsigned dwKeyFrameEvery; unsigned dwQuality; unsigned dwBytesPerSecond; unsigned dwFlags; void *lpFormat; unsigned cbFormat; void *lpParms; unsigned cbParms; unsigned dwInterleaveEvery; } ; #pragma pack(pop) typedef TAVICompressOptions *PAVICompressOptions; #pragma pack(push, 1) struct TAVIPalChange { Byte bFirstEntry; Byte bNumEntries; Word wFlags; tagPALETTEENTRY peNew[256]; } ; #pragma pack(pop) typedef TAVIPalChange *PAVIPalChange; typedef void *APAVISTREAM[2]; typedef TAVICompressOptions *APAVICompressOptions[2]; #pragma option push -b- enum TPixelFormat { pfDevice, pf1bit, pf4bit, pf8bit, pf15bit, pf16bit, pf24bit, pf32bit, pfCustom } ; #pragma option pop class DELPHICLASS TAviWriter; class PASCALIMPLEMENTATION TAviWriter : public Classes::TComponent { typedef Classes::TComponent inherited; private: AnsiString TempFileName; void *pFile; int fHeight; int fWidth; bool fStretch; int fFrameTime; AnsiString fFileName; AnsiString fWavFileName; int FrameCount; void *VideoStream; void *AudioStream; void __fastcall AddVideo(void); void __fastcall AddAudio(void); void __fastcall InternalGetDIBSizes(HBITMAP Bitmap, int &InfoHeaderSize, int &ImageSize, TPixelFormat PixelFormat); bool __fastcall InternalGetDIB(HBITMAP Bitmap, HPALETTE Palette, void *BitmapInfo, void *Bits, TPixelFormat PixelFormat); void __fastcall InitializeBitmapInfoHeader(HBITMAP Bitmap, tagBITMAPINFOHEADER &Info, TPixelFormat PixelFormat); void __fastcall SetWavFileName(AnsiString value); public: Classes::TList* Bitmaps; __fastcall virtual TAviWriter(Classes::TComponent* AOwner); __fastcall virtual ~TAviWriter(void); void __fastcall Write(void); __published: __property int Height = {read=fHeight, write=fHeight, nodefault}; __property int Width = {read=fWidth, write=fWidth, nodefault}; __property int FrameTime = {read=fFrameTime, write=fFrameTime, nodefault}; __property bool Stretch = {read=fStretch, write=fStretch, nodefault}; __property AnsiString FileName = {read=fFileName, write=fFileName}; __property AnsiString WavFileName = {read=fWavFileName, write=SetWavFileName}; }; //-- var, const, procedure --------------------------------------------------- static const Shortint AVIF_HASINDEX = 0x10; static const Shortint AVIF_MUSTUSEINDEX = 0x20; static const Word AVIF_ISINTERLEAVED = 0x100; static const int AVIF_WASCAPTUREFILE = 0x10000; static const int AVIF_COPYRIGHTED = 0x20000; static const int AVIF_KNOWN_FLAGS = 0x30130; static const unsigned AVIERR_UNSUPPORTED = 0x80044065; static const unsigned AVIERR_BADFORMAT = 0x80044066; static const unsigned AVIERR_MEMORY = 0x80044067; static const unsigned AVIERR_INTERNAL = 0x80044068; static const unsigned AVIERR_BADFLAGS = 0x80044069; static const unsigned AVIERR_BADPARAM = 0x8004406a; static const unsigned AVIERR_BADSIZE = 0x8004406b; static const unsigned AVIERR_BADHANDLE = 0x8004406c; static const unsigned AVIERR_FILEREAD = 0x8004406d; static const unsigned AVIERR_FILEWRITE = 0x8004406e; static const unsigned AVIERR_FILEOPEN = 0x8004406f; static const unsigned AVIERR_COMPRESSOR = 0x80044070; static const unsigned AVIERR_NOCOMPRESSOR = 0x80044071; static const unsigned AVIERR_READONLY = 0x80044072; static const unsigned AVIERR_NODATA = 0x80044073; static const unsigned AVIERR_BUFFERTOOSMALL = 0x80044074; static const unsigned AVIERR_CANTCOMPRESS = 0x80044075; static const unsigned AVIERR_USERABORT = 0x800440c6; static const unsigned AVIERR_ERROR = 0x800440c7; static const Shortint AVISF_DISABLED = 0x1; static const int AVISF_VIDEO_PALCHANGES = 0x10000; static const int AVISF_KNOWN_FLAGS = 0x10001; extern PACKAGE unsigned RIFF_PaletteChange; static const Shortint AVIERR_OK = 0x0; static const Shortint AVIIF_LIST = 0x1; static const Shortint AVIIF_TWOCC = 0x2; static const Shortint AVIIF_KEYFRAME = 0x10; static const int streamtypeVIDEO = 0x73646976; static const int streamtypeAUDIO = 0x73647561; extern PACKAGE void __fastcall Register(void); extern "C" void __stdcall AVIFileInit(void); extern "C" void __stdcall AVIFileExit(void); extern "C" HRESULT __stdcall AVIFileOpen(void * &ppfile, char * szFile, unsigned uMode, void * lpHandler ); extern "C" HRESULT __stdcall AVIFileCreateStream(void * pfile, void * &ppavi, TAVIStreamInfoA &psi); extern "C" HRESULT __stdcall AVIStreamSetFormat(void * pavi, int lPos, void * lpFormat, int cbFormat ); extern "C" HRESULT __stdcall AVIStreamReadFormat(void * pavi, int lPos, void * lpFormat, int &cbFormat ); extern "C" HRESULT __stdcall AVIStreamWrite(void * pavi, int lStart, int lSamples, void * lpBuffer, int cbBuffer, unsigned dwFlags, int &plSampWritten, int &plBytesWritten); extern "C" unsigned __stdcall AVIStreamRelease(void * pavi); extern "C" unsigned __stdcall AVIFileRelease(void * pfile); extern "C" HRESULT __stdcall AVIFileGetStream(void * pfile, void * &ppavi, unsigned fccType, int lParam ); extern "C" HRESULT __stdcall CreateEditableStream(void * &ppsEditable, void * psSource); extern "C" HRESULT __stdcall AVISaveV(char * szFile, System::PGUID pclsidHandler, TAVISaveCallback lpfnCallback , int nStreams, const void * * pavi, const PAVICompressOptions * lpOptions); #pragma option push -w-inl inline HRESULT __stdcall AVIFileOpen(void * &ppfile, char * szFile, unsigned uMode, void * lpHandler ) { return AVIFileOpen(ppfile, szFile, uMode, lpHandler); } #pragma option pop #pragma option push -w-inl inline HRESULT __stdcall AVIFileCreateStream(void * pfile, void * &ppavi, TAVIStreamInfoA &psi) { return AVIFileCreateStream(pfile, ppavi, psi); } #pragma option pop } /* namespace Aviwriter */ #if !defined(NO_IMPLICIT_NAMESPACE_USE) using namespace Aviwriter; #endif #pragma option pop // -w- #pragma option pop // -Vx #pragma delphiheader end. //-- end unit ---------------------------------------------------------------- #endif // AviWriter hleclerc/Evel #include "Containers/TypeConfig.h" #include "System/SocketUtil.h" #include "Timer.h" #include #include #include #include #include #include //// nsmake lib_name rt namespace Evel { namespace { int make_timer_fd( double delay, double freq ) { timespec now; if ( clock_gettime( CLOCK_REALTIME, &now ) == -1 ) { perror( "clock_gettime" ); return -1; } // int fd = timerfd_create( CLOCK_REALTIME, 0 ); if ( fd == -1 ) { perror( "timerfd_create" ); return fd; } if ( set_non_block( fd ) == -1 ) { perror( "non blocking timer fd" ); ::close( fd ); return -1; } PI64 di = 1e9 * delay + now.tv_nsec; // PI64 would be to small for tv_sec, but for a delay, it's ok PI64 fi = 1e9 * freq; // PI64 would be to small for tv_sec, but for a freq, it's ok itimerspec new_value; new_value.it_value.tv_sec = now.tv_sec + di / 1000000000; new_value.it_value.tv_nsec = di % 1000000000; new_value.it_interval.tv_sec = fi / 1000000000; new_value.it_interval.tv_nsec = fi % 1000000000; if ( timerfd_settime( fd, TFD_TIMER_ABSTIME, &new_value, NULL ) == -1 ) { perror( "timerfd_settime" ); ::close( fd ); return -1; } return fd; } } // namespace Timer::Timer( double delay, double freq, bool need_wait ) : Event( make_timer_fd( delay, freq ? freq : delay ), need_wait ) { } Timer::Timer( double freq, bool need_wait ) : Timer( freq, freq, need_wait ) { } bool Timer::may_have_out() const { return false; } void Timer::on_inp() { uint64_t nb_expirations; ssize_t s = read( fd, &nb_expirations, sizeof( uint64_t ) ); timeout( s >= (ssize_t)sizeof( uint64_t ) ? nb_expirations : 1 ); } bool Timer::out_are_sent() const { return true; } } // namespace Evel Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo // boost class noncopyable test program ------------------------------------// // (C) Copyright 1999. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // See http://www.boost.org for most recent version including documentation. // Revision History // 9 Jun 99 Add unnamed namespace // 2 Jun 99 Initial Version #include #include // This program demonstrates compiler errors resulting from trying to copy // construct or copy assign a class object derived from class noncopyable. namespace { class DontTreadOnMe : private boost::noncopyable { public: DontTreadOnMe() { std::cout << "defanged!" << std::endl; } }; // DontTreadOnMe } // unnamed namespace int main() { DontTreadOnMe object1; DontTreadOnMe object2(object1); object1 = object2; return 0; } // main NorbertoBurciaga/behavior-driven-development-hello #include "Hello.h" string Hello::sayHello() { return "Hello BDD!"; } /* * Copyright (c) 2014-2022 The Voxie Authors * * 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 "Node.hpp" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace vx; // TODO: Remove compatibility stuff where this is used to issue a warning bool Node::showWarningOnOldObjectNames() { return true; } QString Node::stateToString(State state) { switch (state) { #define D(s) \ case State::s: \ return #s D(Initial); D(Setup); D(Normal); D(Teardown); D(Destroyed); #undef D default: return "Invalid " + QString::number((uint8_t)state); } } Node::~Node() { // qDebug() << "Node::~Node()"; // TODO: check whether this is also safe to do in the dtor. // removeChildNode() calls setNodeProperty() but should only call it for // non-custom properties, so that no virtual functions should be called. // Setting emitSignalsForThis / emitSignalsForObj to false should make sure no // handlers on this are being called. // Make a copy to make sure the list doesn't change while it's modified QList childs = childNodes(); for (const auto& node : childs) this->removeChildNode(node, false, true); // Make a copy to make sure the list doesn't change while it's modified QList parents = parentNodes(); for (const auto& node : parents) node->removeChildNode(this, true, false); if (referencingNodesAsInput.size()) qCritical() << "Node being deconstructed has non-empty referencingNodesAsInput"; if (referencingNodesAsOutput.size()) qCritical() << "Node being deconstructed has non-empty " "referencingNodesAsOutput"; } QVariant Node::getNodeProperty(const QSharedPointer& property) { return getNodeProperty(property->name()); } QVariant Node::getNodeProperty(const QString& key) { auto property = prototype()->getProperty(key, false); if (property->isCustomStorage()) { return getNodePropertyCustom(key); } else { if (!propertyValues_.contains(key)) propertyValues_[key] = property->defaultValue(); return propertyValues_[key]; } } void Node::setNodeProperty(const QSharedPointer& property, const QVariant& value) { setNodeProperty(property->name(), value); } void Node::setNodeProperty(const QString& key, const QVariant& value) { setNodeProperty(key, value, true); } void Node::setNodeProperty(const QSharedPointer& property, const QVariant& value, bool emitSignalsForThis) { setNodeProperty(property->name(), value, emitSignalsForThis); } void Node::setNodeProperty(NodeProperty* property, const QVariant& value, bool emitSignalsForThis) { setNodeProperty(property->name(), value, emitSignalsForThis); } void Node::setNodeProperty(const QString& key, const QVariant& valueOrig, bool emitSignalsForThis) { auto property = prototype()->getProperty(key, false); // TODO: Add option to disable canonicalization, use verify() + value in this // case auto value = property->type()->canonicalize(*property, valueOrig); if (property->isReference()) { if (property->type() == types::NodeReferenceType()) { auto newValue = parseVariantNode(value); Node* oldValue = nullptr; // TODO: Check for new values whether the node state is Setup or Normal if (propertyValues_.contains(key)) { oldValue = parseVariantNode(propertyValues_[key]); if (oldValue) oldValue->referencingNodesAsInput.removeOne(this); } propertyValues_[key] = value; if (newValue) newValue->referencingNodesAsInput << this; if (oldValue != newValue) { if (oldValue) { Q_EMIT oldValue->childChanged(this); if (emitSignalsForThis) Q_EMIT this->parentChanged(oldValue); } if (newValue) { Q_EMIT newValue->childChanged(this); if (emitSignalsForThis) Q_EMIT this->parentChanged(newValue); } } } else if (property->type() == types::NodeReferenceListType()) { auto newValue = parseVariantNodeList(value); QList oldValue; // TODO: Check for new values whether the node state is Setup or Normal if (propertyValues_.contains(key)) { oldValue = parseVariantNodeList(propertyValues_[key]); for (const auto& val : oldValue) if (val) val->referencingNodesAsInput.removeOne(this); } propertyValues_[key] = value; for (const auto& val : newValue) { if (val) val->referencingNodesAsInput << this; } QSet inOldValue; for (const auto& val : oldValue) if (val) inOldValue << val; QSet inNewValue; for (const auto& val : newValue) if (val) inNewValue << val; for (const auto& val : oldValue) { if (val && !inNewValue.contains(val)) { Q_EMIT val->childChanged(this); if (emitSignalsForThis) Q_EMIT this->parentChanged(val); } } for (const auto& val : newValue) { if (val && !inOldValue.contains(val)) { Q_EMIT val->childChanged(this); if (emitSignalsForThis) Q_EMIT this->parentChanged(val); } } } else if (property->type() == types::OutputNodeReferenceType()) { auto newValue = parseVariantNode(value); Node* oldValue = nullptr; // TODO: Check for new values whether the node state is Setup or Normal if (propertyValues_.contains(key)) { oldValue = parseVariantNode(propertyValues_[key]); if (oldValue) oldValue->referencingNodesAsOutput.removeOne(this); } propertyValues_[key] = value; if (newValue) newValue->referencingNodesAsOutput << this; if (oldValue != newValue) { if (oldValue) { if (emitSignalsForThis) Q_EMIT this->childChanged(oldValue); Q_EMIT oldValue->parentChanged(this); } if (newValue) { if (emitSignalsForThis) Q_EMIT this->childChanged(newValue); Q_EMIT newValue->parentChanged(this); } } } else { throw Exception("de.uni_stuttgart.Voxie.Error", "Unknown reference type: " + property->typeName()); } } else if (property->isCustomStorage()) { if (emitSignalsForThis) setNodePropertyCustom(key, value); else qCritical() << "Trying to call setNodePropertyCustom() with " "emitSignalsForThis = false"; } else { // TODO: check type propertyValues_[key] = value; } if (emitSignalsForThis) Q_EMIT this->propertyChanged(property, value); } QVariant Node::getNodePropertyCustom(QString key) { throw Exception("de.uni_stuttgart.Voxie.Error", "Custom property getter for '" + key + "' not found"); } void Node::setNodePropertyCustom(QString key, QVariant value) { Q_UNUSED(value); throw Exception("de.uni_stuttgart.Voxie.Error", "Custom property setter for '" + key + "' not found"); } void Node::emitCustomPropertyChanged( const QSharedPointer& property) { if (prototype()->getProperty(property->name(), false) != property) throw Exception("de.uni_stuttgart.Voxie.InternalError", "Property " + property->name() + " is for another prototype (not " + prototype()->name() + ")"); if (!property->isCustomStorage()) throw Exception( "de.uni_stuttgart.Voxie.InternalError", "Property " + property->name() + " does not have custom storage"); auto value = getNodePropertyCustom(property->name()); Q_EMIT this->propertyChanged(property, value); } void Node::setNodeProperties(const QMap& options) { QList> properties; for (const auto& key : options.keys()) properties << prototype()->getProperty(key, false); std::sort(properties.begin(), properties.end(), [](const QSharedPointer& p1, const QSharedPointer& p2) { if (p1->callSetOrder() < p2->callSetOrder()) return true; if (p1->callSetOrder() > p2->callSetOrder()) return false; return p1->name() < p2->name(); }); for (auto property : properties) { // qDebug() << "SOP" << property->name(); this->setNodeProperty(property, options[property->name()]); } } QSharedPointer Node::getPropertyUIData(QString propertyName) { Q_UNUSED(propertyName); return QSharedPointer(); } QString Node::displayName() const { return displayNameIsSetManually ? manualDisplayName_ : automaticDisplayName_; } void Node::destroy() { vx::checkOnMainThread("Node::destroy"); if (this->state_ == State::Destroyed) { qWarning() << "Node::destroy() called for destroyed node"; return; } if (this->state_ == State::Teardown) { qWarning() << "Node::destroy() called recursively"; return; } // If the state is still initial, the teardown step can be skipped because // there are no references to this node from other nodes. if (this->state_ != State::Initial) { this->state_ = State::Teardown; Q_EMIT this->stateChanged(State::Teardown); // TODO: Removing all references to this node from other nodes should be // done here. if (this->state_ != State::Teardown) { qWarning() << "Node::destroy(): Expected state Teardown, got" << stateToString(this->state_); return; } } this->state_ = State::Destroyed; Q_EMIT this->stateChanged(State::Destroyed); // stateChanged(State::Destroyed) will cause the Root class to drop this // node from the global list of nodes. After that the node should be // freed (possibly once all other holders of references destroy those). // Note: This can happen in some cases if some thread still has a strong // reference to the node if (thisSharedWeakBase()) qInfo() << "Node" << this->getPath().path() << "still has reference at end of destroy() method"; } void Node::setAutomaticDisplayName(const QString& name) { automaticDisplayName_ = name; if (!displayNameIsSetManually) { // qDebug() << "Node::displayNameChanged()" << displayName(); Q_EMIT displayNameChanged(displayName()); } } void Node::setManualDisplayName(const std::tuple& name) { if (!std::get<0>(name) && std::get<1>(name) != "") throw Exception( "de.uni_stuttgart.Voxie.InvalidArgument", "Calling setManualDisplayName() with false and a non-empty string"); displayNameIsSetManually = std::get<0>(name); manualDisplayName_ = std::get<1>(name); // qDebug() << "Node::displayNameChanged()" << displayName(); Q_EMIT displayNameChanged(displayName()); } QIcon Node::icon() { // TODO: interpret paths relative to JSON file? QString iconName = this->prototype()->icon(); if (iconName != "") return QIcon(iconName); else if (nodeKind() == NodeKind::Filter) return QIcon(":/icons/universal.png"); else if (nodeKind() == NodeKind::Property) return QIcon(":/icons/property.png"); else return QIcon(); } QList Node::parentNodes() { QList list; // Search through all input nodes for (const auto& property : prototype()->nodeProperties()) { if (!property->isReference() || property->isOutputReference()) continue; if (property->type() == types::NodeReferenceType()) { auto ptr = parseVariantNode(this->getNodeProperty(property)); if (ptr) list.append(ptr); } else if (property->type() == types::NodeReferenceListType()) { for (const auto& ptr : parseVariantNodeList(this->getNodeProperty(property))) if (ptr) list.append(ptr); } else { throw Exception("de.uni_stuttgart.Voxie.Error", "Unknown reference type: " + property->typeName()); } } // Search for nodes which reference this nodes as output for (const auto& ptr : referencingNodesAsOutput) if (ptr) list.append(ptr); return list; } QList Node::childNodes() { QList list; // Search through all output nodes for (const auto& property : prototype()->nodeProperties()) { if (!property->isReference() || !property->isOutputReference()) continue; if (property->type() == types::OutputNodeReferenceType()) { auto ptr = parseVariantNode(this->getNodeProperty(property)); if (ptr) list.append(ptr); } else { throw Exception("de.uni_stuttgart.Voxie.Error", "Unknown reference type: " + property->typeName()); } } // Search for nodes which reference this nodes as input for (const auto& ptr : referencingNodesAsInput) if (ptr) list.append(ptr); return list; } void Node::addChildNode(Node* obj, int slot) { voxieRoot().createNodeConnection(this, obj, slot); } void Node::removeChildNode(Node* obj, int index) { if (index != -1) removeChildNode(obj, index, true, true); else removeChildNode(obj, true, true); } void Node::removeChildNode(Node* obj, int index, bool emitSignalsForThis, bool emitSignalsForObj) { // Search for the output property of matching index this which has obj as // value int counter = 0; for (const auto& property : this->prototype()->nodeProperties()) { if (!property->isReference() || !property->isOutputReference()) continue; auto value = parseVariantNode(this->getNodeProperty(property)); if (index == counter && value == obj) { this->setNodeProperty(property, getVariant((Node*)nullptr), emitSignalsForThis); return; } counter++; } // Search for the input property of matching index this which has obj as value counter = 0; for (const auto& property : obj->prototype()->nodeProperties()) { if (!property->isReference() || property->isOutputReference()) continue; if (property->type() == types::NodeReferenceType()) { auto value = parseVariantNode(obj->getNodeProperty(property)); if (index == counter && value == this) { obj->setNodeProperty(property, getVariant((Node*)nullptr), emitSignalsForObj); return; } } else if (property->type() == types::NodeReferenceListType()) { QList list = parseVariantNodeList(obj->getNodeProperty(property)); if (index == counter && list.removeOne(this)) { obj->setNodeProperty(property, getVariant(list), emitSignalsForObj); return; } } else { throw Exception("de.uni_stuttgart.Voxie.Error", "Unknown reference type: " + property->typeName()); return; } counter++; } qWarning() << "Unable to remove" << prototype()->name() << obj << "as child of" << obj->prototype() << this; } void Node::removeChildNode(Node* obj, bool emitSignalsForThis, bool emitSignalsForObj) { // Search for first output property in this which has obj as value for (const auto& property : this->prototype()->nodeProperties()) { if (!property->isReference() || !property->isOutputReference()) continue; auto value = parseVariantNode(this->getNodeProperty(property)); if (value != obj) continue; this->setNodeProperty(property, getVariant((Node*)nullptr), emitSignalsForThis); return; } // Search for first input property in obj which has this as value for (const auto& property : obj->prototype()->nodeProperties()) { if (!property->isReference() || property->isOutputReference()) continue; if (property->type() == types::NodeReferenceType()) { auto value = parseVariantNode(obj->getNodeProperty(property)); if (value != this) continue; obj->setNodeProperty(property, getVariant((Node*)nullptr), emitSignalsForObj); } else if (property->type() == types::NodeReferenceListType()) { QList list = parseVariantNodeList(obj->getNodeProperty(property)); if (!list.removeOne(this)) continue; obj->setNodeProperty(property, getVariant(list), emitSignalsForObj); } else { throw Exception("de.uni_stuttgart.Voxie.Error", "Unknown reference type: " + property->typeName()); } return; } qWarning() << "Unable to remove" << prototype()->name() << obj << "as child of" << obj->prototype() << this; /* childNodes_.removeOne(obj); obj->parentNodes_.removeOne(this); Q_EMIT childChanged(obj); Q_EMIT obj->parentChanged(this); */ } QWidget* Node::getCustomPropertySectionContent(const QString& name) { throw Exception("de.uni_stuttgart.Voxie.Error", "Could not find custom property section content with name '" + name + "' in node with type " + this->prototype()->name()); } void Node::addPropertySection(QWidget* section) { connect(section, &QObject::destroyed, this, [this, section]() { propertySections_.removeOne(section); }); propertySections_ << section; connect(this, &QObject::destroyed, section, &QObject::deleteLater); Q_EMIT propertySectionAdded(section); } void Node::addContextMenuAction(QAction* action) { contextMenuActions_ << action; } bool Node::isCreatableChild(NodeKind node) { return isAllowedChild(node); } // TODO: Deal with cycles, be faster on DACs etc. bool Node::hasAncestor(Node* node) { for (const auto& obj : parentNodes()) { if (obj == node) return true; if (obj->hasAncestor(node)) return true; } return false; } bool Node::hasParent(Node* node) { for (const auto& obj : parentNodes()) if (obj == node) return true; return false; } bool Node::hasChild(Node* node) { for (const auto& obj : childNodes()) if (obj == node) return true; return false; } NodeKind Node::nodeKind() { return prototype()->nodeKind(); } namespace vx { namespace { class NodeAdaptorImpl : public NodeAdaptor, public ObjectAdaptor { Node* object; public: NodeAdaptorImpl(Node* object) : NodeAdaptor(object), ObjectAdaptor(object), object(object) {} virtual ~NodeAdaptorImpl() {} // Note: Returning errors from the getters / setters currently does not work QDBusObjectPath parentNodeGroup() const override { if (object->parentNodeGroup() == nullptr) { return QDBusObjectPath("/"); } else { return object->parentNodeGroup().data()->getPath(); } } void setParentNodeGroup(const QDBusObjectPath& value) override { object->setParentNodeGroup(NodeGroup::lookupOptional(value).data()); } QStringList exportedProperties() const override { QStringList result; for (auto property : object->exportedProperties()) { result.append(property->name()); } return result; } void setExportedProperties(const QStringList& value) override { QList> result; for (QString propertyString : value) { for (auto property : object->prototype()->nodeProperties()) { if (property->name() == propertyString) result.append(property); } } object->setExportedProperties(result); } QString displayName() const override { try { return object->displayName(); } catch (vx::Exception& e) { e.handle(object); qWarning() << "Got error during DBus property:" << e.what(); return ""; } } QString automaticDisplayName() const override { try { return object->automaticDisplayName(); } catch (vx::Exception& e) { e.handle(object); qWarning() << "Got error during DBus property:" << e.what(); return ""; } } std::tuple manualDisplayName() const override { try { return object->manualDisplayName(); } catch (vx::Exception& e) { e.handle(object); qWarning() << "Got error during DBus property:" << e.what(); return std::make_tuple(false, ""); } } void setManualDisplayName(std::tuple value) override { try { object->setManualDisplayName(value); } catch (vx::Exception& e) { e.handle(object); qWarning() << "Got error during DBus property:" << e.what(); return; } } vx::TupleVector graphPosition() const override { try { return toTupleVector(voxieRoot().getGraphPosition(object)); } catch (vx::Exception& e) { e.handle(object); qWarning() << "Got error during DBus property:" << e.what(); return vx::TupleVector(0, 0); } } void setGraphPosition(vx::TupleVector pos) override { try { voxieRoot().setGraphPosition(object, toQtVector(pos)); } catch (vx::Exception& e) { e.handle(object); qWarning() << "Got error during DBus property:" << e.what(); return; } } QDBusObjectPath prototype() const override { try { return ExportedObject::getPath(object->prototype()); } catch (vx::Exception& e) { e.handle(object); qWarning() << "Got error during DBus property:" << e.what(); return QDBusObjectPath("/"); } } QDBusVariant GetProperty( const QString& key, const QMap& options) override { try { ExportedObject::checkOptions(options, "AllowCompatibilityNames"); bool allowCompatibilityNames = ExportedObject::getOptionValueOrDefault( options, "AllowCompatibilityNames", true); auto property = this->object->prototype()->getProperty(key, allowCompatibilityNames); auto valueRaw = this->object->getNodeProperty(property); return property->type()->rawToDBus(valueRaw); } catch (vx::Exception& e) { e.handle(object); return QDBusVariant(); } } void SetProperty(const QString& key, const QDBusVariant& value, const QMap& options) override { try { ExportedObject::checkOptions(options, "AllowCompatibilityNames"); bool allowCompatibilityNames = ExportedObject::getOptionValueOrDefault( options, "AllowCompatibilityNames", true); auto prototype = this->object->prototype(); auto property = prototype->getProperty(key, allowCompatibilityNames); auto valueRaw = Node::propertyDBusToRaw(prototype.data(), property, value); this->object->setNodeProperty(property, valueRaw); } catch (vx::Exception& e) { e.handle(object); } } void SetProperties(const QMap& values, const QMap& options) override { try { ExportedObject::checkOptions(options, "AllowCompatibilityNames"); bool allowCompatibilityNames = ExportedObject::getOptionValueOrDefault( options, "AllowCompatibilityNames", true); QVariantMap properties; for (const auto& key : values.keys()) { auto prototype = this->object->prototype(); auto property = prototype->getProperty(key, allowCompatibilityNames); auto valueRaw = Node::propertyDBusToRaw(prototype.data(), property, QDBusVariant(values[key])); if (properties.contains(property->name())) // Can happen with compatibility names throw vx::Exception( "de.uni_stuttgart.Voxie.DuplicateProperty", "Property '" + property->name() + "' was given multiple time"); properties[property->name()] = valueRaw; } this->object->setNodeProperties(properties); } catch (vx::Exception& e) { e.handle(object); } } void Destroy(const QMap& options) override { try { ExportedObject::checkOptions(options); this->object->destroy(); } catch (vx::Exception& e) { e.handle(object); } } }; } // namespace } // namespace vx void Node::addNodePropertyUIToSection( Node* self, PropertySection* section, const QSharedPointer& property, const QJsonObject& json) { // TODO: Is this ok if the QPointer's dtor is called from another thread? QSharedPointer> ptrPtrUi = createQSharedPointer>(nullptr); auto generatePropertyLayout = [=]() { auto type = property->type(); *ptrPtrUi = type->createUI(property, self); (*ptrPtrUi)->setParent(self); (*ptrPtrUi)->init(); QString labelStyle = (*ptrPtrUi)->isMultiline() ? "ExtraLine" : "SameLine"; if (json.contains("LabelStyle")) labelStyle = json["LabelStyle"].toString(); if (labelStyle == "SameLine") { QHBoxLayout* layout = new QHBoxLayout(); QLabel* label = new QLabel(property->displayName() + ":"); auto widget = (*ptrPtrUi)->widget(); if (property->shortDescription() != "") { label->setToolTip(property->shortDescription()); // TODO: overwrite widget tooltip here? widget->setToolTip(property->shortDescription()); } layout->addWidget(label); layout->addWidget(widget); return layout; } else if (labelStyle == "ExtraLine") { QHBoxLayout* layout = new QHBoxLayout(); QVBoxLayout* layout2 = new QVBoxLayout(); QLabel* label = new QLabel(property->displayName() + ":"); auto widget = (*ptrPtrUi)->widget(); if (property->shortDescription() != "") { label->setToolTip(property->shortDescription()); // TODO: overwrite widget tooltip here? widget->setToolTip(property->shortDescription()); } // TODO: How should this look like? Where should the export button be? layout2->addWidget(label); layout2->addWidget(widget); layout->addLayout(layout2); return layout; } else if (labelStyle == "None") { auto widget = (*ptrPtrUi)->widget(); if (property->shortDescription() != "") { // TODO: overwrite widget tooltip here? widget->setToolTip(property->shortDescription()); } auto layout = new QHBoxLayout(); layout->addWidget(widget); return layout; } else { qWarning() << "Unknown label style:" << labelStyle; return (QHBoxLayout*)nullptr; } }; // the button that appears next to each property and can be used to export // that property if it is inside a node group QPushButton* btnExport = new QPushButton(); btnExport->setCheckable(true); btnExport->setToolTip("Export"); btnExport->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); // only enable export button if node is in a node group btnExport->setEnabled(parentNodeGroup_ != nullptr); // enable/disable button when parent node group of this node is changed connect(this, &Node::parentNodeGroupChanged, this, [btnExport](NodeGroup* newNodeGroup) { btnExport->setEnabled(newNodeGroup != nullptr); }); // on loading make the button checked if the loaded property is already in the // exportedProperties list if (self->exportedProperties().contains(property)) { btnExport->setIcon(QIcon(":/icons/bookmark--minus.png")); btnExport->setChecked(true); } else { btnExport->setIcon(QIcon(":/icons/bookmark--plus.png")); btnExport->setChecked(false); } // if the list of exported properties changes we also need to check if the // property of our button is in there so that we can update the button's // checked status QObject::connect( self, &Node::exportedPropertiesChanged, [btnExport, property]( const QList>& exportedProperties) { btnExport->setChecked(exportedProperties.contains(property)); }); QSharedPointer> propLayout = createQSharedPointer>(nullptr); // change icon to plus or minus bookmark depending on if // button is checked and add or remove the property from // the exportedProperties list QObject::connect(btnExport, &QPushButton::toggled, btnExport, [=]() { if (btnExport->isChecked()) { // each child node gets its own section in the parent node groups // properties ui. this->exportedPropertiesSection is a pointer to that // section. Create the section if it doesn't exist already. We'll need it // later. if (self->exportedPropertiesSection == nullptr) { self->exportedPropertiesSection = new PropertySection(self->displayName()); connect(self, &Node::displayNameChanged, self->exportedPropertiesSection, [=]() { self->exportedPropertiesSection->setWindowTitle( self->displayName()); }); if (self->parentNodeGroup()) { self->parentNodeGroup().data()->addPropertySection( self->exportedPropertiesSection); } } // add the property's widget to the parent node group's properties ui *propLayout = generatePropertyLayout(); self->exportedPropertiesSection->addHBoxLayout(*propLayout); // export button should now get a minus icon to signify that the property // was exported btnExport->setIcon(QIcon(":/icons/bookmark--minus.png")); // add the property to the list of exported properties if it's not already // in there QList> list = self->exportedProperties(); if (!list.contains(property)) { list.append(property); self->setExportedProperties(list); } } else { // user clicked the button to un-export the property // change the button icon back btnExport->setIcon(QIcon(":/icons/bookmark--plus.png")); // remove the property from the exported properties list QList> list = self->exportedProperties(); if (list.contains(property)) { list.removeAll(property); self->setExportedProperties(list); if (*propLayout != nullptr && self->parentNodeGroup()) { for (int i = 0; i < (*propLayout)->count(); ++i) { QWidget* widget = (*propLayout)->itemAt(i)->widget(); if (widget != nullptr) widget->deleteLater(); } (*propLayout)->deleteLater(); (*propLayout) = nullptr; (*ptrPtrUi)->deleteLater(); (*ptrPtrUi) = nullptr; // delete this node's properties section from the parent node groups // properties ui if that section is now empty if (list.isEmpty()) { self->exportedPropertiesSection->deleteLater(); self->exportedPropertiesSection = nullptr; } } } } }); auto propertyLayout = generatePropertyLayout(); QWidget* spacer = new QWidget(); spacer->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred); propertyLayout->addWidget(spacer); propertyLayout->addWidget(btnExport); section->addHBoxLayout(propertyLayout); } Node::Node(const QString& type, const QSharedPointer& prototype) : DynamicObject(type), prototype_(prototype) { auto adaptor = new NodeAdaptorImpl(this); QObject::connect(this, &Node::propertyChanged, this, [adaptor](const QSharedPointer& property, const QVariant& value) { try { NodeAdaptor* adaptor1 = adaptor; Q_EMIT adaptor1->PropertyChanged( property->name(), property->type()->rawToDBus(value), vx::emptyOptions()); ObjectAdaptor* adaptor2 = adaptor; Q_EMIT adaptor2->PropertyChanged( property->name(), property->type()->rawToDBus(value), vx::emptyOptions()); } catch (Exception& e) { qWarning() << "Exception while emitting PropertyChanged event:" << e.message(); } }); for (const auto& spSection_ : this->prototype() ->rawJson()["UI"] .toObject()["SidePanelSections"] .toArray()) { auto spSection = spSection_.toObject(); QString name = spSection["Name"].toString(); QString displayName = spSection["DisplayName"].toString(); // qDebug() << "Section:" << name << displayName; auto section = new PropertySection(displayName); this->addPropertySection(section); sections << section; } } // This will be executed after the node has been fully // constructed and all virtual methods are available void Node::initialize() { DynamicObject::initialize(); // TODO: With the SliceVisualizer there there is some flicker effect when // calling initializeReal() directly if (prototype()->name() == "de.uni_stuttgart.Voxie.FakeFilter") { initializeReal(); } else { enqueueOnThread(this, [this] { this->initializeReal(); }); } } void Node::initializeReal() { // qDebug() << "CREATE" << prototype()->_name; PropertySection* propSection = nullptr; QSet> handledProperties; int pos = 0; for (const auto& spSection_ : this->prototype() ->rawJson()["UI"] .toObject()["SidePanelSections"] .toArray()) { auto spSection = spSection_.toObject(); if (pos >= sections.size()) { qCritical() << "pos >= sections.size()"; return; } PropertySection* section = sections[pos]; if (!section) { qWarning() << "PropertySection has been destroyed"; continue; } for (const auto& entry_ : spSection["Entries"].toArray()) { auto entry = entry_.toObject(); auto type = entry["Type"].toString(); if (type == "Property") { auto propertyName = entry["Property"].toString(); auto property = this->prototype()->getProperty(propertyName, false); addNodePropertyUIToSection(this, section, property, entry); handledProperties.insert(property); } else if (type == "Custom") { auto name = entry["Name"].toString(); QWidget* widget; try { widget = this->getCustomPropertySectionContent(name); } catch (vx::Exception& e) { qWarning() << "Error while creating custom section entry with name" << name << "for node of type" << this->prototype()->name(); continue; } auto layout = new QHBoxLayout(); layout->addWidget(widget); section->addHBoxLayout(layout); } else { qWarning() << "Unknown section entry type:" << type; } } pos++; } QList> properties = this->prototype()->nodeProperties(); std::sort(properties.begin(), properties.end(), [](const QSharedPointer& p1, const QSharedPointer& p2) { if (p1->uiPosition() < p2->uiPosition()) return true; if (p1->uiPosition() > p2->uiPosition()) return false; return p1->name() < p2->name(); }); for (const auto& property : properties) { if (property->isCustomUI()) continue; if (handledProperties.contains(property)) continue; /* if (property->name() == "de.uni_stuttgart.Voxie.Input" || property->name() == "de.uni_stuttgart.Voxie.Output") continue; // TODO */ // qDebug() << property->name(); if (!propSection) { propSection = new PropertySection("Node Properties"); this->addPropertySection(propSection); } addNodePropertyUIToSection(this, propSection, property, QJsonObject()); } } Node* Node::parseVariantNode(const QVariant& variant) { auto value = parseVariant(variant); if (value.path() == "/") return nullptr; auto ptr = ExportedObject::lookupWeakObject(value); if (!ptr) { /* throw Exception("de.uni_stuttgart.Voxie.Error", "Failed to look up node " + value.path()); */ qWarning() << "Failed to look up node" << value.path(); return nullptr; } auto obj = dynamic_cast(ptr); if (!obj) { /* throw Exception("de.uni_stuttgart.Voxie.Error", "Path " + value.path() + " is not an vx::Node"); */ qWarning() << "Path" << value.path() << "is not an vx::Node"; return nullptr; } return obj; } QList Node::parseVariantNodeList(const QVariant& variant) { auto list = parseVariant>(variant); QList res; for (const auto& value : list) { if (value.path() == "/") { qWarning() << "Node list contains nullptr"; continue; } auto ptr = ExportedObject::lookupWeakObject(value); if (!ptr) { /* throw Exception("de.uni_stuttgart.Voxie.Error", "Failed to look up node " + value.path()); */ qWarning() << "Failed to look up node" << value.path() << "for list"; continue; } auto obj = dynamic_cast(ptr); if (!obj) { /* throw Exception( "de.uni_stuttgart.Voxie.Error", "Path " + value.path() + " is not an vx::Node"); */ qWarning() << "Path" << value.path() << "is not an vx::Node for node list"; continue; } res.append(obj); } return res; } void Node::setStateToSetup() { vx::checkOnMainThread("Node::setStateToSetup"); if (this->state_ == State::Initial) { vx::voxieRoot().registerNode(thisShared()); this->state_ = State::Setup; Q_EMIT this->stateChanged(State::Setup); } else { qWarning() << "Invalid state for node in Node::setStateToSetup:" << stateToString(this->state_); } } void Node::setStateToNormal() { vx::checkOnMainThread("Node::setStateToNormal"); if (this->state_ == State::Setup) { this->state_ = State::Normal; Q_EMIT this->stateChanged(State::Normal); this->setupFinished(); } else { qWarning() << "Invalid state for node in Node::setStateToNormal:" << stateToString(this->state_); } } void Node::setupFinished() {} QVariant Node::getVariant(Node* obj) { return QVariant::fromValue(obj ? obj->getPath() : QDBusObjectPath("/")); } QVariant Node::getVariant(const QList& objs) { QList ret; for (const auto& obj : objs) { if (obj) { ret.append(obj->getPath()); } else { qWarning() << "Node list contains nullptr"; } } return QVariant::fromValue(ret); } QMap Node::propertyValues() { QMap map; for (const auto& prop : prototype()->nodeProperties()) map[prop->name()] = getNodeProperty(prop->name()); return map; } QVariant Node::propertyDBusToRaw(NodePrototype* prototype, const QSharedPointer& property, const QDBusVariant& value) { // Support for loading old ValueColorMapping values (before // 19ad5739b10ba87d970663ad5c1e5902b01440ed) if (property->type() == vx::types::ValueColorMappingType() && vx::dbusGetVariantSignature(value) == QDBusSignature("a(d(dddd))")) { auto val = dbusGetVariantValue< QList>>>(value); QList, qint32>> val2; for (const auto& entry : val) val2.push_back( std::make_tuple(std::get<0>(entry), std::get<1>(entry), 0)); // return property->type()->dbusToRaw(dbusMakeVariant(val2)); QList entries; for (const auto& entry : val) entries << ColorizerEntry(std::get<0>(entry), std::get<1>(entry), ColorInterpolator::RGB); return QVariant::fromValue( vx::PropertyValueConvertRaw< vx::types::ValueColorMapping::RawType, vx::types::ValueColorMapping::QtType>::toRaw(entries)); } // Support for loading old CCL nodes (up until // f2ecd9434aaa0e65b4a0d2c3a228422e266c3bf6) if (prototype->name() == "de.uni_stuttgart.Voxie.CCL" && property->name() == "de.uni_stuttgart.Voxie.Input" && vx::dbusGetVariantSignature(value) == QDBusSignature("ao")) { auto val = dbusGetVariantValue>(value); QDBusObjectPath path("/"); if (val.size() == 1) { path = val[0]; } else if (val.size() != 0) { throw vx::Exception("de.uni_stuttgart.Voxie.Error", "Got more than one input for CCL"); } return QVariant::fromValue(path); } return property->type()->dbusToRaw(value); } QPointer Node::parentNodeGroup() const { return parentNodeGroup_; } void Node::setParentNodeGroup(const QPointer group) { if (parentNodeGroup() != nullptr) disconnect(parentNodeGroup_.data(), &Node::stateChanged, this, &Node::parentNodeGroupStateChanged); parentNodeGroup_ = group; if (group != nullptr) connect(group.data(), &Node::stateChanged, this, &Node::parentNodeGroupStateChanged); Q_EMIT parentNodeGroupChanged(group.data()); } QList> Node::exportedProperties() const { return exportedProperties_; } void Node::setExportedProperties( const QList>& properties) { exportedProperties_ = properties; exportedPropertiesChanged(properties); if (parentNodeGroup_) { parentNodeGroup_.data()->childrenExportedPropertiesChanged(); } } void Node::parentNodeGroupStateChanged(State state) { if (state == Node::State::Teardown) { this->deleteLater(); } } PropertiesEntryBase::PropertiesEntryBase(const QString& name, const QVariant& value) : name_(name), value_(value) {} PropertiesEntryBase::~PropertiesEntryBase() {} 1-10 /** \file \author - \copyright \parblock Copyright 2019-2021 . 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. \endparblock */ #include using ETL_NAMESPACE::Detail::AHashTable; using ETL_NAMESPACE::Detail::SingleChain; void AHashTable::insert(AHashTable::Node& item) { ETL_ASSERT(buckets.data() != nullptr); ETL_ASSERT(buckets.size() > 0U); uint32_t ix = bucketIxOfHash(item.hash); if (buckets[ix] == nullptr) { if (lastItem == &chain_.getFrontNode()) { ETL_ASSERT(size() == 0U); frontBucketIx = ix; } buckets[ix] = lastItem; chain_.insertAfter(buckets[ix], &item); lastItem = buckets[ix]->next; ETL_ASSERT(lastItem == &item); } else { std::pair res = getPreviousInBucket(item.hash, ix); chain_.insertAfter(res.first, &item); if (res.first == lastItem) { lastItem = res.first->next; } } ETL_ASSERT(lastItem->next == nullptr); ++size_; } std::pair AHashTable::getPreviousInBucket(HashType hash, size_type ix) { ETL_ASSERT(bucketIxOfHash(hash) == ix); ETL_ASSERT(buckets[ix] != nullptr); bool found = false; bool end = false; SingleChain::Node* prev = buckets[ix]; ETL_ASSERT(prev->next != nullptr); while ((!found) && (!end)) { auto next = static_cast(prev->next); if ((next == nullptr) || (bucketIxOfHash(next->hash) != ix)) { end = true; } else if (next->hash > hash) { end = true; } else if (next->hash == hash) { found = true; } else { prev = next; } } return std::pair(prev, found); } AHashTable::Node* AHashTable::remove(AHashTable::Node& item) { ETL_ASSERT(size() > 0U); auto* next = static_cast(item.next); std::pair prev = findPreviousOfNode(item); if (lastItem == &item) { lastItem = prev.first; } SingleChain::Node* removed = chain_.removeAfter(prev.first); std::uint32_t ix = prev.second; if (buckets[ix] == lastItem) { buckets[ix] = nullptr; } else { const Node& nextOfBucket = static_cast(*(buckets[ix]->next)); if (bucketIxOfHash(nextOfBucket.hash) != ix) { buckets[ix] = nullptr; } } if (next != nullptr) { auto nextIx = bucketIxOfHash(next->hash); if (nextIx != ix) { // The next element of removed belongs to another bucket, // this means the next bucket pointer has to be corrected. buckets[nextIx] = prev.first; if (prev.first == &chain_.getFrontNode()) { frontBucketIx = nextIx; } } } --size_; return static_cast(removed); } std::pair AHashTable::findPreviousOfNode(AHashTable::Node& item) const { auto ix = bucketIxOfHash(item.hash); ETL_ASSERT(buckets[ix] != nullptr); SingleChain::Node* prev = buckets[ix]; ETL_ASSERT(prev != nullptr); while (prev->next != &item) { prev = prev->next; ETL_ASSERT(prev != nullptr); ETL_ASSERT(bucketIxOfHash(static_cast(prev)->hash) == ix); } return std::pair(prev, ix); } const AHashTable::Node* AHashTable::findNode(HashType hash) const { const Node* res = nullptr; auto ix = bucketIxOfHash(hash); if (buckets[ix] != nullptr) { auto node = static_cast(buckets[ix]->next); ETL_ASSERT(node != nullptr); while ((node != nullptr) && (node->hash != hash) && (bucketIxOfHash(node->hash) == ix)) { node = static_cast(node->next); } if ((node != nullptr) && (node->hash == hash)) { res = node; } } return res; } std::pair AHashTable::equalHashRange(HashType hash) const { const Node* rangeEnd = nullptr; auto rangeStart = findNode(hash); if (rangeStart != nullptr) { rangeEnd = static_cast(rangeStart->next); while ((rangeEnd != nullptr) && (rangeEnd->hash == hash)) { rangeEnd = static_cast(rangeEnd->next); } } return std::pair(rangeStart, rangeEnd); } std::uint32_t AHashTable::count(HashType hash) const { std::uint32_t cnt = 0U; std::pair res = equalHashRange(hash); if (res.first != nullptr) { while (res.first != res.second) { ++cnt; res.first = static_cast(res.first->next); } } return cnt; } // Copyright (C) 2011-2020 Roki. Distributed under the MIT License #ifndef INCLUDED_SROOK_TYPE_TRAITS_TRUE_FALSE_TYPE_HPP #define INCLUDED_SROOK_TYPE_TRAITS_TRUE_FALSE_TYPE_HPP #if (__has_include() || (__cplusplus > 201103L)) # include # define SROOK_TRUE_TYPE std::true_type # define SROOK_FALSE_TYPE std::false_type #elif __has_include() # include # define SROOK_TRUE_TYPE boost::true_type # define SROOK_FALSE_TYPE boost::false_type #else namespace srook { struct true_type { enum { value = true }; }; struct false_type { enum { value = false }; }; } // namespace srook # define SROOK_TRUE_TYPE srook::true_type # define SROOK_FALSE_TYPE srook::false_type #endif #endif #include #include #include #include #include //#include #include int main(int argc, char **argv) { QApplication app(argc, argv); QDir* userFolder = new QDir(QStandardPaths::writableLocation(QStandardPaths::AppDataLocation)); userFolder->cd("../Axolot Games/Scrap Mechanic/User"); if(!userFolder->exists() || !userFolder->isReadable()) { qFatal("User folder not found or cannot be read. Program will terminate."); QApplication::exit(); } userFolder->setSorting(QDir::Time); userFolder->setFilter(QDir::Dirs | QDir::NoDotAndDotDot); userFolder->cd(userFolder->entryList().first()); userFolder->cd("Blueprints"); //Window window(userFolder); //window.show(); Form form(userFolder); form.show(); return app.exec(); } lib/Basic/JSONSerialization.cpp //===--- JSONSerialization.cpp - JSON serialization support ---------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #include "swift/Basic/JSONSerialization.h" #include "llvm/ADT/StringExtras.h" #include "llvm/Support/Format.h" using namespace swift::json; using namespace swift; unsigned Output::beginArray() { StateStack.push_back(ArrayFirstValue); Stream << '['; if (PrettyPrint) { Stream << '\n'; } return 0; } bool Output::preflightElement(unsigned, void *&) { if (StateStack.back() != ArrayFirstValue) { assert(StateStack.back() == ArrayOtherValue && "We must be in a sequence!"); Stream << ','; if (PrettyPrint) Stream << '\n'; } if (PrettyPrint) indent(); return true; } void Output::postflightElement(void*) { if (StateStack.back() == ArrayFirstValue) { StateStack.pop_back(); StateStack.push_back(ArrayOtherValue); } } void Output::endArray() { StateStack.pop_back(); if (PrettyPrint) { Stream << '\n'; indent(); } Stream << ']'; } bool Output::canElideEmptyArray() { if (StateStack.size() < 2) return true; if (StateStack.back() != ObjectFirstKey) return true; State checkedState = StateStack[StateStack.size() - 2]; return (checkedState != ArrayFirstValue && checkedState != ArrayOtherValue); } void Output::beginObject() { StateStack.push_back(ObjectFirstKey); Stream << "{"; if (PrettyPrint) Stream << '\n'; } void Output::endObject() { StateStack.pop_back(); if (PrettyPrint) { Stream << '\n'; indent(); } Stream << "}"; } bool Output::preflightKey(const char *Key, bool Required, bool SameAsDefault, bool &UseDefault, void *&) { UseDefault = false; if (Required || !SameAsDefault) { if (StateStack.back() != ObjectFirstKey) { assert(StateStack.back() == ObjectOtherKey && "We must be in an object!"); Stream << ','; if (PrettyPrint) Stream << '\n'; } if (PrettyPrint) indent(); Stream << '"' << Key << "\":"; if (PrettyPrint) Stream << ' '; return true; } return false; } void Output::postflightKey(void*) { if (StateStack.back() == ObjectFirstKey) { StateStack.pop_back(); StateStack.push_back(ObjectOtherKey); } } void Output::beginEnumScalar() { EnumerationMatchFound = false; } bool Output::matchEnumScalar(const char *Str, bool Match) { if (Match && !EnumerationMatchFound) { StringRef StrRef(Str); scalarString(StrRef, true); EnumerationMatchFound = true; } return false; } void Output::endEnumScalar() { if (!EnumerationMatchFound) llvm_unreachable("bad runtime enum value"); } bool Output::beginBitSetScalar(bool &DoClear) { Stream << '['; if (PrettyPrint) Stream << ' '; NeedBitValueComma = false; DoClear = false; return true; } bool Output::bitSetMatch(const char *Str, bool Matches) { if (Matches) { if (NeedBitValueComma) { Stream << ','; if (PrettyPrint) Stream << ' '; } StringRef StrRef(Str); scalarString(StrRef, true); } return false; } void Output::endBitSetScalar() { if (PrettyPrint) Stream << ' '; Stream << ']'; } void Output::scalarString(StringRef &S, bool MustQuote) { if (MustQuote) { Stream << '"'; for (unsigned char c : S) { // According to the JSON standard, the following characters must be // escaped: // - Quotation mark (U+0022) // - Reverse solidus (U+005C) // - Control characters (U+0000 to U+001F) // We need to check for these and escape them if present. // // Since these are represented by a single byte in UTF8 (and will not be // present in any multi-byte UTF8 representations), we can just switch on // the value of the current byte. // // Any other bytes present in the string should therefore be emitted // as-is, without any escaping. switch (c) { // First, check for characters for which JSON has custom escape sequences. case '"': Stream << '\\' << '"'; break; case '\\': Stream << '\\' << '\\'; break; case '/': Stream << '\\' << '/'; break; case '\b': Stream << '\\' << 'b'; break; case '\f': Stream << '\\' << 'f'; break; case '\n': Stream << '\\' << 'n'; break; case '\r': Stream << '\\' << 'r'; break; case '\t': Stream << '\\' << 't'; break; default: // Otherwise, check to see if the current byte is a control character. if (c <= '\x1F') { // Since we have a control character, we need to escape it using // JSON's only valid escape sequence: \uxxxx (where x is a hex digit). // The upper two digits for control characters are always 00. Stream << "\\u00"; // Convert the current character into hexadecimal digits. Stream << llvm::hexdigit((c >> 4) & 0xF); Stream << llvm::hexdigit((c >> 0) & 0xF); } else { // This isn't a control character, so we don't need to escape it. // As a result, emit it directly; if it's part of a multi-byte UTF8 // representation, all bytes will be emitted in this fashion. Stream << c; } break; } } Stream << '"'; } else Stream << S; } void Output::indent() { Stream.indent(StateStack.size() * 2); } //===----------------------------------------------------------------------===// // traits for built-in types //===----------------------------------------------------------------------===// void ScalarTraits::output(const bool &Val, raw_ostream &Out) { Out << (Val ? "true" : "false"); } void ScalarTraits::output(const StringRef &Val, raw_ostream &Out) { Out << Val; } void ScalarTraits::output(const std::string &Val, raw_ostream &Out) { Out << Val; } void ScalarTraits::output(const uint8_t &Val, raw_ostream &Out) { // use temp uin32_t because ostream thinks uint8_t is a character uint32_t Num = Val; Out << Num; } void ScalarTraits::output(const uint16_t &Val, raw_ostream &Out) { Out << Val; } void ScalarTraits::output(const uint32_t &Val, raw_ostream &Out) { Out << Val; } #if defined(_MSC_VER) void ScalarTraits::output(const unsigned long &Val, raw_ostream &Out) { Out << Val; } #endif void ScalarTraits::output(const uint64_t &Val, raw_ostream &Out) { Out << Val; } void ScalarTraits::output(const int8_t &Val, raw_ostream &Out) { // use temp in32_t because ostream thinks int8_t is a character int32_t Num = Val; Out << Num; } void ScalarTraits::output(const int16_t &Val, raw_ostream &Out) { Out << Val; } void ScalarTraits::output(const int32_t &Val, raw_ostream &Out) { Out << Val; } void ScalarTraits::output(const int64_t &Val, raw_ostream &Out) { Out << Val; } void ScalarTraits::output(const double &Val, raw_ostream &Out) { Out << llvm::format("%g", Val); } void ScalarTraits::output(const float &Val, raw_ostream &Out) { Out << llvm::format("%g", Val); } // Copyright(c) 2017 POLYGONTEK // // 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 "Precompiled.h" #include "Math/Math.h" BE_NAMESPACE_BEGIN const Mat3x4 Mat3x4::zero(Vec4(0, 0, 0, 0), Vec4(0, 0, 0, 0), Vec4(0, 0, 0, 0)); const Mat3x4 Mat3x4::identity(Vec4(1, 0, 0, 0), Vec4(0, 1, 0, 0), Vec4(0, 0, 1, 0)); //--------------------------------------------------- // // | 1 0 0 tx | | m00 m01 m02 m03 | // T M = | 0 1 0 ty | | m10 m11 m12 m13 | // | 0 0 1 tz | | m20 m21 m22 m23 | // //--------------------------------------------------- Mat3x4 &Mat3x4::Translate(float tx, float ty, float tz) { mat[0][3] += tx; mat[1][3] += ty; mat[2][3] += tz; return *this; } //--------------------------------------------------- // // | m00 m01 m02 m03 | | 1 0 0 tx | // M T = | m10 m11 m12 m13 | | 0 1 0 ty | // | m20 m21 m22 m23 | | 0 0 1 tz | // //--------------------------------------------------- Mat3x4 &Mat3x4::TranslateRight(float tx, float ty, float tz) { mat[0][3] += mat[0][0] * tx + mat[0][1] * ty + mat[0][2] * tz; mat[1][3] += mat[1][0] * tx + mat[1][1] * ty + mat[1][2] * tz; mat[2][3] += mat[2][0] * tx + mat[2][1] * ty + mat[2][2] * tz; return *this; } //--------------------------------------------------- // // | sx 0 0 | | m00 m01 m02 m03 | // S M = | 0 sy 0 | | m10 m11 m12 m13 | // | 0 0 sz | | m20 m21 m22 m23 | // //--------------------------------------------------- Mat3x4 &Mat3x4::Scale(float sx, float sy, float sz) { mat[0] *= sx; mat[1] *= sy; mat[2] *= sz; return *this; } Mat3x4 Mat3x4::operator*(const Mat3x4 &a) const { Mat3x4 dst; dst.mat[0][0] = mat[0][0] * a.mat[0][0] + mat[0][1] * a.mat[1][0] + mat[0][2] * a.mat[2][0]; dst.mat[0][1] = mat[0][0] * a.mat[0][1] + mat[0][1] * a.mat[1][1] + mat[0][2] * a.mat[2][1]; dst.mat[0][2] = mat[0][0] * a.mat[0][2] + mat[0][1] * a.mat[1][2] + mat[0][2] * a.mat[2][2]; dst.mat[0][3] = mat[0][0] * a.mat[0][3] + mat[0][1] * a.mat[1][3] + mat[0][2] * a.mat[2][3] + mat[0][3]; dst.mat[1][0] = mat[1][0] * a.mat[0][0] + mat[1][1] * a.mat[1][0] + mat[1][2] * a.mat[2][0]; dst.mat[1][1] = mat[1][0] * a.mat[0][1] + mat[1][1] * a.mat[1][1] + mat[1][2] * a.mat[2][1]; dst.mat[1][2] = mat[1][0] * a.mat[0][2] + mat[1][1] * a.mat[1][2] + mat[1][2] * a.mat[2][2]; dst.mat[1][3] = mat[1][0] * a.mat[0][3] + mat[1][1] * a.mat[1][3] + mat[1][2] * a.mat[2][3] + mat[1][3]; dst.mat[2][0] = mat[2][0] * a.mat[0][0] + mat[2][1] * a.mat[1][0] + mat[2][2] * a.mat[2][0]; dst.mat[2][1] = mat[2][0] * a.mat[0][1] + mat[2][1] * a.mat[1][1] + mat[2][2] * a.mat[2][1]; dst.mat[2][2] = mat[2][0] * a.mat[0][2] + mat[2][1] * a.mat[1][2] + mat[2][2] * a.mat[2][2]; dst.mat[2][3] = mat[2][0] * a.mat[0][3] + mat[2][1] * a.mat[1][3] + mat[2][2] * a.mat[2][3] + mat[2][3]; return dst; } void Mat3x4::SetTRS(const Vec3 &translation, const Mat3 &rotation, const Vec3 &scale) { // T * R * S mat[0][0] = rotation[0][0] * scale.x; mat[0][1] = rotation[1][0] * scale.y; mat[0][2] = rotation[2][0] * scale.z; mat[0][3] = translation.x; mat[1][0] = rotation[0][1] * scale.x; mat[1][1] = rotation[1][1] * scale.y; mat[1][2] = rotation[2][1] * scale.z; mat[1][3] = translation.y; mat[2][0] = rotation[0][2] * scale.x; mat[2][1] = rotation[1][2] * scale.y; mat[2][2] = rotation[2][2] * scale.z; mat[2][3] = translation.z; } void Mat3x4::SetTQS(const Vec3 &translation, const Quat &rotation, const Vec3 &scale) { SetTRS(translation, rotation.ToMat3(), scale); } void Mat3x4::GetTRS(Vec3 &translation, Mat3 &rotation, Vec3 &scale) const { translation.x = mat[0][3]; translation.y = mat[1][3]; translation.z = mat[2][3]; rotation = ToMat3(); scale.x = rotation[0].Length(); scale.y = rotation[1].Length(); scale.z = rotation[2].Length(); rotation[0] *= 1.f / scale.x; rotation[1] *= 1.f / scale.y; rotation[2] *= 1.f / scale.z; } void Mat3x4::GetTQS(Vec3 &translation, Quat &rotation, Vec3 &scale) const { Mat3 r; GetTRS(translation, r, scale); rotation = r.ToQuat(); } // Euclidean inverse (TRS)^{-1} = S^{-1} R^T (-T) void Mat3x4::InverseSelf() { #if 0 *this = Mat3x4(ToMat4().Inverse()); #else float tmp[3]; // get squared inverse scale factor float inv_sx2 = 1.0f / (mat[0][0] * mat[0][0] + mat[1][0] * mat[1][0] + mat[2][0] * mat[2][0]); float inv_sy2 = 1.0f / (mat[0][1] * mat[0][1] + mat[1][1] * mat[1][1] + mat[2][1] * mat[2][1]); float inv_sz2 = 1.0f / (mat[0][2] * mat[0][2] + mat[1][2] * mat[1][2] + mat[2][2] * mat[2][2]); // negate inverse rotated translation part tmp[0] = mat[0][0] * mat[0][3] + mat[1][0] * mat[1][3] + mat[2][0] * mat[2][3]; tmp[1] = mat[0][1] * mat[0][3] + mat[1][1] * mat[1][3] + mat[2][1] * mat[2][3]; tmp[2] = mat[0][2] * mat[0][3] + mat[1][2] * mat[1][3] + mat[2][2] * mat[2][3]; mat[0][3] = -tmp[0] * inv_sx2; mat[1][3] = -tmp[1] * inv_sy2; mat[2][3] = -tmp[2] * inv_sz2; // transpose rotation part mat[0][0] *= inv_sx2; tmp[0] = mat[0][1] * inv_sy2; mat[0][1] = mat[1][0] * inv_sx2; mat[1][0] = tmp[0]; mat[1][1] *= inv_sy2; tmp[1] = mat[0][2] * inv_sz2; mat[0][2] = mat[2][0] * inv_sx2; mat[2][0] = tmp[1]; tmp[2] = mat[1][2] * inv_sz2; mat[1][2] = mat[2][1] * inv_sy2; mat[2][1] = tmp[2]; mat[2][2] *= inv_sz2; #endif } Mat3x4 &Mat3x4::TransformSelf(const Mat3x4 &a) { float dst[3]; dst[0] = mat[0][0] * a.mat[0][0] + mat[1][0] * a.mat[0][1] + mat[2][0] * a.mat[0][2]; dst[1] = mat[0][0] * a.mat[1][0] + mat[1][0] * a.mat[1][1] + mat[2][0] * a.mat[1][2]; dst[2] = mat[0][0] * a.mat[2][0] + mat[1][0] * a.mat[2][1] + mat[2][0] * a.mat[2][2]; mat[0][0] = dst[0]; mat[1][0] = dst[1]; mat[2][0] = dst[2]; dst[0] = mat[0][1] * a.mat[0][0] + mat[1][1] * a.mat[0][1] + mat[2][1] * a.mat[0][2]; dst[1] = mat[0][1] * a.mat[1][0] + mat[1][1] * a.mat[1][1] + mat[2][1] * a.mat[1][2]; dst[2] = mat[0][1] * a.mat[2][0] + mat[1][1] * a.mat[2][1] + mat[2][1] * a.mat[2][2]; mat[0][1] = dst[0]; mat[1][1] = dst[1]; mat[2][1] = dst[2]; dst[0] = mat[0][2] * a.mat[0][0] + mat[1][2] * a.mat[0][1] + mat[2][2] * a.mat[0][2]; dst[1] = mat[0][2] * a.mat[1][0] + mat[1][2] * a.mat[1][1] + mat[2][2] * a.mat[1][2]; dst[2] = mat[0][2] * a.mat[2][0] + mat[1][2] * a.mat[2][1] + mat[2][2] * a.mat[2][2]; mat[0][2] = dst[0]; mat[1][2] = dst[1]; mat[2][2] = dst[2]; dst[0] = mat[0][3] * a.mat[0][0] + mat[1][3] * a.mat[0][1] + mat[2][3] * a.mat[0][2]; dst[1] = mat[0][3] * a.mat[1][0] + mat[1][3] * a.mat[1][1] + mat[2][3] * a.mat[1][2]; dst[2] = mat[0][3] * a.mat[2][0] + mat[1][3] * a.mat[2][1] + mat[2][3] * a.mat[2][2]; mat[0][3] = dst[0]; mat[1][3] = dst[1]; mat[2][3] = dst[2]; mat[0][3] += a.mat[0][3]; mat[1][3] += a.mat[1][3]; mat[2][3] += a.mat[2][3]; return *this; } Mat3x4 &Mat3x4::UntransformSelf(const Mat3x4 &a) { float dst[3]; mat[0][3] -= a.mat[0][3]; mat[1][3] -= a.mat[1][3]; mat[2][3] -= a.mat[2][3]; dst[0] = mat[0][0] * a.mat[0][0] + mat[1][0] * a.mat[1][0] + mat[2][0] * a.mat[2][0]; dst[1] = mat[0][0] * a.mat[0][1] + mat[1][0] * a.mat[1][1] + mat[2][0] * a.mat[2][1]; dst[2] = mat[0][0] * a.mat[0][2] + mat[1][0] * a.mat[1][2] + mat[2][0] * a.mat[2][2]; mat[0][0] = dst[0]; mat[1][0] = dst[1]; mat[2][0] = dst[2]; dst[0] = mat[0][1] * a.mat[0][0] + mat[1][1] * a.mat[1][0] + mat[2][1] * a.mat[2][0]; dst[1] = mat[0][1] * a.mat[0][1] + mat[1][1] * a.mat[1][1] + mat[2][1] * a.mat[2][1]; dst[2] = mat[0][1] * a.mat[0][2] + mat[1][1] * a.mat[1][2] + mat[2][1] * a.mat[2][2]; mat[0][1] = dst[0]; mat[1][1] = dst[1]; mat[2][1] = dst[2]; dst[0] = mat[0][2] * a.mat[0][0] + mat[1][2] * a.mat[1][0] + mat[2][2] * a.mat[2][0]; dst[1] = mat[0][2] * a.mat[0][1] + mat[1][2] * a.mat[1][1] + mat[2][2] * a.mat[2][1]; dst[2] = mat[0][2] * a.mat[0][2] + mat[1][2] * a.mat[1][2] + mat[2][2] * a.mat[2][2]; mat[0][2] = dst[0]; mat[1][2] = dst[1]; mat[2][2] = dst[2]; dst[0] = mat[0][3] * a.mat[0][0] + mat[1][3] * a.mat[1][0] + mat[2][3] * a.mat[2][0]; dst[1] = mat[0][3] * a.mat[0][1] + mat[1][3] * a.mat[1][1] + mat[2][3] * a.mat[2][1]; dst[2] = mat[0][3] * a.mat[0][2] + mat[1][3] * a.mat[1][2] + mat[2][3] * a.mat[2][2]; mat[0][3] = dst[0]; mat[1][3] = dst[1]; mat[2][3] = dst[2]; return *this; } Mat3x4 Mat3x4::FromString(const char *str) { Mat3x4 m; sscanf(str, "%f %f %f %f %f %f %f %f %f %f %f %f", &m[0].x, &m[0].y, &m[0].z, &m[0].w, &m[1].x, &m[1].y, &m[1].z, &m[1].w, &m[2].x, &m[2].y, &m[2].z, &m[2].w); return m; } BE_NAMESPACE_END mmore500/dishtiny #pragma once #ifndef DISH2_PERIPHERAL_READABLE_STATE_INTROSPECTIVE_STATE_INTROSPECTIVESTATE_HPP_INCLUDE #define DISH2_PERIPHERAL_READABLE_STATE_INTROSPECTIVE_STATE_INTROSPECTIVESTATE_HPP_INCLUDE #include "../../../../../third-party/conduit/include/uitsl/datastructs/PodInternalNode.hpp" #include "../../../../../third-party/conduit/include/uitsl/meta/TypeName.hpp" #include "../../../../../third-party/Empirical/include/emp/base/assert.hpp" #include "../../../../../third-party/signalgp-lite/include/sgpl/utility/ByteEnumeration.hpp" #include "interpreted_introspective_state/InterpretedIntrospectiveState.hpp" #include "raw_introspective_state/RawIntrospectiveState.hpp" namespace dish2 { namespace internal { template< typename Spec > using introspective_state_parent_t = uitsl::PodInternalNode< dish2::InterpretedIntrospectiveState, dish2::RawIntrospectiveState >; } // namespace internal /** * Introspective state refers to the collection of simulation-generated sensor * values that evolving programs running within each cardinal can access via * read-only operations. * * Each cardinal has an independent copy of each piece of introspective state * state. (However, some introspective states representing cell state are set * to identical values across cardinals within the same cell.) * * Each cardinal's introspective state regularly copied and dispatched to that * cardinal's neighbor cell, where it serves as read-only extrospective state. */ template struct IntrospectiveState : public internal::introspective_state_parent_t{ using parent_t = internal::introspective_state_parent_t; constexpr inline static size_t parent_size = parent_t::GetSize(); void Assign(const size_t idx, const IntrospectiveState& other) { #define DISH2_INTROSPECTIVE_STATE_ASSIGN_CASE_PAYLOAD(N) \ case N: \ if constexpr ( N < parent_size ) { \ this->parent_t::template GetByIndex() \ = static_cast(other).template GetByIndex(); \ } \ break; emp_assert( idx < parent_size ); static_assert( parent_size < 256 ); switch ( idx ) { EMP_WRAP_EACH( DISH2_INTROSPECTIVE_STATE_ASSIGN_CASE_PAYLOAD, SGPL_BYTE_ENUMERATION ) default: emp_assert( false, idx ); __builtin_unreachable(); } } void Swap(const size_t idx, IntrospectiveState& other) { #define DISH2_INTROSPECTIVE_STATE_SWAP_CASE_PAYLOAD(N) \ case N: \ if constexpr ( N < parent_size ) { \ std::swap( \ this->parent_t::template GetByIndex(), \ static_cast(other).template GetByIndex() \ ); \ } \ break; emp_assert( idx < parent_size ); static_assert( parent_size < 256 ); switch ( idx ) { EMP_WRAP_EACH( DISH2_INTROSPECTIVE_STATE_SWAP_CASE_PAYLOAD, SGPL_BYTE_ENUMERATION ) default: emp_assert( false, idx ); __builtin_unreachable(); } } static std::string GetLeafTypeName( const size_t idx ) { // can't use emp_assert due to obsucre macro error #define DISH2_INTROSPECTIVE_STATE_NAME_CASE_PAYLOAD(N) \ case N: \ if constexpr ( N < parent_t::GetSize() ) { \ return uitsl::TypeName< \ typename parent_t::template leaf_t \ >::Get(); \ } else { \ assert( false && N ); \ __builtin_unreachable(); \ } emp_assert( idx < parent_t::GetSize() ); static_assert( parent_t::GetSize() < 256 ); switch ( idx ) { EMP_WRAP_EACH( DISH2_INTROSPECTIVE_STATE_NAME_CASE_PAYLOAD, SGPL_BYTE_ENUMERATION ) default: emp_assert( false, idx ); __builtin_unreachable(); } emp_assert( false, idx ); __builtin_unreachable(); } }; } // namespace dish2 #endif // #ifndef DISH2_PERIPHERAL_READABLE_STATE_INTROSPECTIVE_STATE_INTROSPECTIVESTATE_HPP_INCLUDE /* * Author : OFShare * E-mail : * Created Time : 2020-07-13 23:12:50 PM * File Name : UVA-10617.cc */ #include #define ll long long void debug() { #ifdef Acui freopen("data.in", "r", stdin); freopen("data.out", "w", stdout); #endif } const int N = 60 + 5; int t; char str[N]; // dp[i][j]表示区间i~j里回文序列的个数 ll dp[N][N]; ll dfs(int i, int j) { // 递归的边界 if (i == j) return 1; if (i > j) return 0; // 记忆化 if (dp[i][j] != -1) return dp[i][j]; ll ret = 0; if (str[i] == str[j]) ret = dfs(i, j - 1) + dfs(i + 1, j) + 1; else ret = dfs(i, j - 1) + dfs(i + 1, j) - dfs(i + 1, j - 1); return dp[i][j] = ret; } int main() { scanf("%d", &t); while (t--) { scanf("%s", str + 1); std::memset(dp, -1, sizeof dp); printf("%lld\n", dfs(1, (int)std::strlen(str + 1))); } return 0; } #include "cmd_processor.h" RspParams RspParams::Empty() { RspParams result{}; result.rspLen=0; result.rspType=RSP_EMPTY; return result; } RspParams RspParams::Invalid() { RspParams result{}; result.rspLen=0; result.rspType=RSP_INVALID; return result; } RspParams RspParams::Error(const CMDRSP_BUFF_TYPE rspLen) { RspParams result{}; result.rspLen=rspLen; result.rspType=RSP_ERROR; return result; } CmdProcessor::CmdProcessor(ClockHelper &clockHelper, ProfileManager &profileManager, CodeGenAggregator &codeGenAggregator) : codeGenAggregator(codeGenAggregator), clockHelper(clockHelper), profileManager(profileManager) { } RspParams CmdProcessor::ProcessCommand(const uint8_t cmdType, const uint8_t* const cmdData, const CMDRSP_BUFF_TYPE cmdLen, uint8_t* const rspData) { switch (cmdType) { case CMD_SETTIME: return SetTime(cmdData,cmdLen); case CMD_GETPRCOUNT: return GetProfilesCount(cmdLen,rspData); case CMD_GETPROFILE: return GetProfile(cmdData,cmdLen,rspData); case CMD_STOREROFILE: return StoreProfile(cmdData,cmdLen); default: return RspParams::Invalid(); } } RspParams CmdProcessor::GetProfilesCount(const CMDRSP_BUFF_TYPE cmdLen, uint8_t * const rspData) { if(cmdLen!=0) return RspParams::Invalid(); uint16_t prCount=profileManager.GetProfilesCount(); *(rspData)=static_cast(prCount & 0xFF); *(rspData+1)=static_cast((prCount>>8) & 0xFF); auto result=RspParams(); result.rspLen=2; result.rspType=RSP_PRCOUNT; return result; } RspParams CmdProcessor::StoreProfile(const uint8_t* const cmdData, const CMDRSP_BUFF_TYPE cmdLen) { if(cmdLen<(3+PROFILE_NAME_LEN)) return RspParams::Invalid(); //2 bytes - profile index auto index=static_cast( static_cast(*cmdData) | static_cast(*(cmdData+1))<<8 ); //1 byte - profile type auto profileType=static_cast(*(cmdData+2)); //PROFILE_NAME_LEN - profile name bool nullByteFound=false; CMDRSP_BUFF_TYPE secretDataPos=PROFILE_NAME_LEN+3; for(uint8_t pos=3; posPROFILE_PAYLOAD_LEN) return RspParams::Invalid(); if(!cgManager->VerifySecretData(cmdData+secretDataPos,secretDataLen)) return RspParams::Invalid(); //save profile Profile profile{profileType,{0}}; memcpy(profile.name,cmdData+3,PROFILE_NAME_LEN); //create profile-payload uint8_t profilePayload[PROFILE_PAYLOAD_LEN]; memset(profilePayload,0,PROFILE_PAYLOAD_LEN); memcpy(profilePayload,cmdData+secretDataPos,secretDataLen); if(!profileManager.WriteProfile(index,profile,profilePayload)) return RspParams::Invalid(); return RspParams::Empty(); } RspParams CmdProcessor::GetProfile(const uint8_t* const cmdData, const CMDRSP_BUFF_TYPE cmdLen, uint8_t * const rspData) { if(cmdLen!=2) return RspParams::Invalid(); auto index=static_cast( static_cast(*cmdData) | static_cast(*(cmdData+1))<<8 ); auto profile=profileManager.ReadProfileHeader(index); uint8_t nameLen=0; //poor-man's strnlen, to save some tiny bit of progmem //this is not an equalent to strnlen, will set nameLen to 0 if null character not found for(uint8_t pos=0; pos(profile.type); memcpy(rspData+1,profile.name,nameLen); RspParams result{}; result.rspLen=nameLen+1; result.rspType=RSP_PROFILE; return result; } RspParams CmdProcessor::SetTime(const uint8_t* const cmdData, const CMDRSP_BUFF_TYPE cmdLen) { if(cmdLen!=10) return RspParams::Invalid(); CMDRSP_BUFF_TYPE pos=0; uint8_t sec=cmdData[pos++]; uint8_t min=cmdData[pos++]; uint8_t hour=cmdData[pos++]; uint8_t day=cmdData[pos]&0x1F; uint8_t dow=cmdData[pos++]>>5; uint8_t month=cmdData[pos++]; uint16_t year=cmdData[pos++]; year|=(static_cast(cmdData[pos++])<<8); int32_t utcOffset=cmdData[pos++]; utcOffset|=static_cast(cmdData[pos++])<<8; uint8_t sign=cmdData[pos]>>7; utcOffset|=static_cast(cmdData[pos++]&0x7F)<<16; if(sign>0) utcOffset=-utcOffset; if(!clockHelper.SetTime(sec,min,hour,day,dow,month,year,utcOffset)) return RspParams::Error(0); return RspParams::Empty(); } /*========================================================================= * * Copyright Insight Software Consortium * * 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.txt * * 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 "itkQuaternionRigidTransform.h" #include "itkMutualInformationImageToImageMetric.h" #include "itkQuaternionRigidTransformGradientDescentOptimizer.h" #include "itkTextOutput.h" #include "itkSimpleMultiResolutionImageRegistrationUI.h" namespace { double F( itk::Vector & v ); } /** * This program test one instantiation of the * itk::MultiResolutionImageRegistrationMethod class * * This file tests the combination of: * - MutualInformation * - QuaternionRigidTransform * - QuaternionRigidTransformGradientDescentOptimizer * - LinearInterpolateImageFunction * - RecursiveMultiResolutionPyramidImageFilter * * The test image pattern consists of a 3D gaussian in the middle * with some directional pattern on the outside. * One image is rotated and shifted relative to the other. * * Notes: * ===== * This example performs an rigid * registration between a 3D moving image and a 3D fixed image using * mutual information and a multi-resolution strategy. * * See notes for itkImageRegistrationMethodTest_14.cxx for more * detailed information on the algorithm. * * A simple user-interface, allows the user to define the number * of iteration and learning rate at each resolution level. * */ int itkMultiResolutionImageRegistrationMethodTest_2(int, char* [] ) { itk::OutputWindow::SetInstance(itk::TextOutput::New().GetPointer()); bool pass = true; const unsigned int dimension = 3; unsigned int j; typedef float PixelType; // Fixed Image Type typedef itk::Image FixedImageType; // Moving Image Type typedef itk::Image MovingImageType; // Transform Type typedef itk::QuaternionRigidTransform< double > TransformType; // Optimizer Type typedef itk::QuaternionRigidTransformGradientDescentOptimizer OptimizerType; // Metric Type typedef itk::MutualInformationImageToImageMetric< FixedImageType, MovingImageType > MetricType; // Interpolation technique typedef itk:: LinearInterpolateImageFunction< MovingImageType, double > InterpolatorType; // Fixed Image Pyramid Type typedef itk::RecursiveMultiResolutionPyramidImageFilter< FixedImageType, FixedImageType > FixedImagePyramidType; // Moving Image Pyramid Type typedef itk::RecursiveMultiResolutionPyramidImageFilter< MovingImageType, MovingImageType > MovingImagePyramidType; // Registration Method typedef itk::MultiResolutionImageRegistrationMethod< FixedImageType, MovingImageType > RegistrationType; MetricType::Pointer metric = MetricType::New(); TransformType::Pointer transform = TransformType::New(); OptimizerType::Pointer optimizer = OptimizerType::New(); FixedImageType::Pointer fixedImage = FixedImageType::New(); MovingImageType::Pointer movingImage = MovingImageType::New(); InterpolatorType::Pointer interpolator = InterpolatorType::New(); FixedImagePyramidType::Pointer fixedImagePyramid = FixedImagePyramidType::New(); MovingImagePyramidType::Pointer movingImagePyramid = MovingImagePyramidType::New(); RegistrationType::Pointer registration = RegistrationType::New(); /********************************************************* * Set up the two input images. * One image rotated (xy plane) and shifted with respect to the other. **********************************************************/ double displacement[dimension] = {7,3,2}; double angle = 10.0 / 180.0 * itk::Math::pi; FixedImageType::SizeType size = {{100,100,40}}; FixedImageType::IndexType index = {{0,0,0}}; FixedImageType::RegionType region; region.SetSize( size ); region.SetIndex( index ); fixedImage->SetLargestPossibleRegion( region ); fixedImage->SetBufferedRegion( region ); fixedImage->SetRequestedRegion( region ); fixedImage->Allocate(); movingImage->SetLargestPossibleRegion( region ); movingImage->SetBufferedRegion( region ); movingImage->SetRequestedRegion( region ); movingImage->Allocate(); typedef itk::ImageRegionIterator MovingImageIterator; typedef itk::ImageRegionIterator FixedImageIterator; itk::Point center; for ( j = 0; j < dimension; j++ ) { center[j] = 0.5 * (double)region.GetSize()[j]; } itk::Point p; itk::Vector d, d2; MovingImageIterator mIter( movingImage, region ); FixedImageIterator fIter( fixedImage, region ); while( !mIter.IsAtEnd() ) { for ( j = 0; j < dimension; j++ ) { p[j] = mIter.GetIndex()[j]; } d = p - center; fIter.Set( (PixelType) F(d) ); d2[0] = d[0] * std::cos(angle) + d[1] * std::sin(angle) + displacement[0]; d2[1] = -d[0] * std::sin(angle) + d[1] * std::cos(angle) + displacement[1]; d2[2] = d[2] + displacement[2]; mIter.Set( (PixelType) F(d2) ); ++fIter; ++mIter; } // set the image origin to be center of the image double transCenter[dimension]; for ( j = 0; j < dimension; j++ ) { transCenter[j] = -0.5 * double(size[j]); } movingImage->SetOrigin( transCenter ); fixedImage->SetOrigin( transCenter ); /****************************************************************** * Set up the optimizer. ******************************************************************/ // set the translation scale typedef OptimizerType::ScalesType ScalesType; ScalesType parametersScales( transform->GetNumberOfParameters() ); parametersScales.Fill( 1.0 ); for ( j = 4; j < 7; j++ ) { parametersScales[j] = 0.0001; } optimizer->SetScales( parametersScales ); // need to maximize for mutual information optimizer->MaximizeOn(); /****************************************************************** * Set up the optimizer observer ******************************************************************/ /* typedef itk::CommandIterationUpdate< OptimizerType > CommandIterationType; CommandIterationType::Pointer iterationCommand = CommandIterationType::New(); iterationCommand->SetOptimizer( optimizer ); */ /****************************************************************** * Set up the metric. ******************************************************************/ metric->SetMovingImageStandardDeviation( 5.0 ); metric->SetFixedImageStandardDeviation( 5.0 ); metric->SetNumberOfSpatialSamples( 50 ); metric->ReinitializeSeed( 121212 ); /****************************************************************** * Set up the registrator. ******************************************************************/ // connect up the components registration->SetMetric( metric ); registration->SetOptimizer( optimizer ); registration->SetTransform( transform ); registration->SetFixedImage( fixedImage ); registration->SetMovingImage( movingImage ); registration->SetInterpolator( interpolator ); registration->SetFixedImagePyramid( fixedImagePyramid ); registration->SetMovingImagePyramid( movingImagePyramid ); registration->SetFixedImageRegion( fixedImage->GetBufferedRegion() ); // set initial parameters to identity RegistrationType::ParametersType initialParameters( transform->GetNumberOfParameters() ); initialParameters.Fill( 0.0 ); initialParameters[3] = 1.0; /****************************************************************** * Attach registration to a simple UI and run registration ******************************************************************/ SimpleMultiResolutionImageRegistrationUI2 simpleUI( registration ); unsigned short numberOfLevels = 3; itk::Array niter( numberOfLevels ); itk::Array rates( numberOfLevels ); niter[0] = 300; niter[1] = 300; niter[2] = 350; rates[0] = 1e-3; rates[1] = 5e-4; rates[2] = 1e-4; simpleUI.SetNumberOfIterations( niter ); simpleUI.SetLearningRates( rates ); try { registration->SetNumberOfLevels( numberOfLevels ); registration->SetInitialTransformParameters( initialParameters ); registration->Update(); } catch( itk::ExceptionObject & e ) { std::cout << "Registration failed" << std::endl; std::cout << "Reason " << e.GetDescription() << std::endl; return EXIT_FAILURE; } /*********************************************************** * Check the results ************************************************************/ RegistrationType::ParametersType solution = registration->GetLastTransformParameters(); std::cout << "Solution is: " << solution << std::endl; RegistrationType::ParametersType trueParameters( transform->GetNumberOfParameters() ); trueParameters.Fill( 0.0 ); trueParameters[2] = std::sin( angle / 2.0 ); trueParameters[3] = std::cos( angle / 2.0 ); trueParameters[4] = -1.0 * ( displacement[0] * std::cos(angle) - displacement[1] * std::sin(angle) ); trueParameters[5] = -1.0 * ( displacement[0] * std::sin(angle) + displacement[1] * std::cos(angle) ); trueParameters[6] = -1.0 * displacement[2]; std::cout << "True solution is: " << trueParameters << std::endl; for( j = 0; j < 4; j++ ) { if( itk::Math::abs( solution[j] - trueParameters[j] ) > 0.025 ) { pass = false; } } for( j = 4; j < 7; j++ ) { if( itk::Math::abs( solution[j] - trueParameters[j] ) > 1.0 ) { pass = false; } } if( !pass ) { std::cout << "Test failed." << std::endl; return EXIT_FAILURE; } /************************************************* * Check for parzen window exception **************************************************/ double oldValue = metric->GetMovingImageStandardDeviation(); metric->SetMovingImageStandardDeviation( 0.005 ); try { pass = false; registration->Update(); } catch(itk::ExceptionObject& err) { std::cout << "Caught expected ExceptionObject" << std::endl; std::cout << err << std::endl; pass = true; } if( !pass ) { std::cout << "Should have caught an exception" << std::endl; std::cout << "Test failed." << std::endl; return EXIT_FAILURE; } metric->SetMovingImageStandardDeviation( oldValue ); /************************************************* * Check for mapped out of image error **************************************************/ solution[5] = 1000; registration->SetInitialTransformParameters( solution ); try { pass = false; registration->Update(); } catch(itk::ExceptionObject& err) { std::cout << "Caught expected ExceptionObject" << std::endl; std::cout << err << std::endl; pass = true; } if( !pass ) { std::cout << "Should have caught an exception" << std::endl; std::cout << "Test failed." << std::endl; return EXIT_FAILURE; } std::cout << "Test passed." << std::endl; return EXIT_SUCCESS; } namespace { /** * This function defines the test image pattern. * The pattern is a 3D gaussian in the middle * and some directional pattern on the outside. */ double F( itk::Vector & v ) { double x = v[0]; double y = v[1]; double z = v[2]; const double s = 50; double value = 200.0 * std::exp( - ( x*x + y*y + z*z )/(s*s) ); x -= 8; y += 3; z += 0; double r = std::sqrt( x*x + y*y + z*z ); if( r > 35 ) { value = 2 * ( itk::Math::abs( x ) + 0.8 * itk::Math::abs( y ) + 0.5 * itk::Math::abs( z ) ); } if( r < 4 ) { value = 400; } return value; } } #include #include #include #include #include namespace DB { namespace { void formatProfileNameOrID(const String & str, bool is_id, const IAST::FormatSettings & settings) { if (is_id) { settings.ostr << (settings.hilite ? IAST::hilite_keyword : "") << "ID" << (settings.hilite ? IAST::hilite_none : "") << "(" << quoteString(str) << ")"; } else { settings.ostr << backQuoteIfNeed(str); } } } void ASTSettingsProfileElement::formatImpl(const FormatSettings & settings, FormatState &, FormatStateStacked) const { if (!parent_profile.empty()) { settings.ostr << (settings.hilite ? IAST::hilite_keyword : "") << (use_inherit_keyword ? "INHERIT" : "PROFILE") << " " << (settings.hilite ? IAST::hilite_none : ""); formatProfileNameOrID(parent_profile, id_mode, settings); return; } formatSettingName(setting_name, settings.ostr); if (!value.isNull()) { settings.ostr << " = " << applyVisitor(FieldVisitorToString{}, value); } if (!min_value.isNull()) { settings.ostr << (settings.hilite ? IAST::hilite_keyword : "") << " MIN " << (settings.hilite ? IAST::hilite_none : "") << applyVisitor(FieldVisitorToString{}, min_value); } if (!max_value.isNull()) { settings.ostr << (settings.hilite ? IAST::hilite_keyword : "") << " MAX " << (settings.hilite ? IAST::hilite_none : "") << applyVisitor(FieldVisitorToString{}, max_value); } if (readonly) { settings.ostr << (settings.hilite ? IAST::hilite_keyword : "") << (*readonly ? " READONLY" : " WRITABLE") << (settings.hilite ? IAST::hilite_none : ""); } } bool ASTSettingsProfileElements::empty() const { for (const auto & element : elements) if (!element->empty()) return false; return true; } void ASTSettingsProfileElements::formatImpl(const FormatSettings & settings, FormatState &, FormatStateStacked) const { if (empty()) { settings.ostr << (settings.hilite ? IAST::hilite_keyword : "") << "NONE" << (settings.hilite ? IAST::hilite_none : ""); return; } bool need_comma = false; for (const auto & element : elements) { if (need_comma) settings.ostr << ", "; need_comma = true; element->format(settings); } } void ASTSettingsProfileElements::setUseInheritKeyword(bool use_inherit_keyword_) { for (auto & element : elements) element->use_inherit_keyword = use_inherit_keyword_; } } // // TMP102.hpp // pumphouse // // Created by on 9/10/21. // #ifndef TMP102_hpp #define TMP102_hpp #include #include "I2C.hpp" class TMP102 { public: TMP102(); ~TMP102(); // Address of Temperature sensor (0x48,0x49,0x4A,0x4B) bool begin(uint8_t deviceAddress = 0x48, int *error = NULL); void stop(); bool isOpen(); bool readTempC(float&); bool readTempF(float&); uint8_t getDevAddr(); private: I2C _i2cPort; bool _isSetup; }; #endif /* TMP102_hpp */ jebreimo/JEBLib /* JEBBase: generic algorithms and functions * Copyright 2014 * All rights reserved. * * This file is distributed under the BSD License. * License text is included with the source distribution. */ #ifndef JEBBASE_ALGORITHMS_SORT_HPP #define JEBBASE_ALGORITHMS_SORT_HPP #include #include "JEBBase/JEBBaseDefinitions.hpp" namespace JEBBase { namespace Algorithms { template void sort(T& a, T& b) { if (b < a) std::swap(a, b); } template void sort(T& a, T& b, T& c) { sort(a, b); sort(b, c); sort(a, b); } template void sort(T& a, T& b, T& c, T& d) { sort(a, b); sort(c, d); sort(a, c); sort(b, d); sort(b, c); } template void sort(T (&a)[2]) { sort(a[0], a[1]); } template void sort(T (&a)[3]) { sort(a[0], a[1], a[2]); } template void sort(T (&a)[4]) { sort(a[0], a[1], a[2], a[3]); } }} #endif #include #include #include namespace obe::System::Project::Prefixes::Bindings { void LoadGlobalObjects(sol::state_view state) { sol::table PrefixesNamespace = state["obe"]["System"]["Project"]["Prefixes"].get(); PrefixesNamespace["objects"] = obe::System::Project::Prefixes::objects; } void LoadGlobalScenes(sol::state_view state) { sol::table PrefixesNamespace = state["obe"]["System"]["Project"]["Prefixes"].get(); PrefixesNamespace["scenes"] = obe::System::Project::Prefixes::scenes; } }; //Toonz app #include "tapp.h" //Toonz stage structures #include "toonz/tscenehandle.h" #include "toonz/toonzscene.h" #include "toonz/txsheethandle.h" #include "toonz/txsheet.h" #include "toonz/tcamera.h" #include "toonz/tframehandle.h" //Scene viewer #include "sceneviewer.h" //Qt event-handling includes #include #include "subcameramanager.h" //******************************************************************************** // Local namespace stuff //******************************************************************************** namespace { inline bool bitwiseContains(UCHAR flag, UCHAR state) { return flag == (flag | state); } inline bool bitwiseExclude(UCHAR flag, UCHAR state) { return bitwiseContains(~state, flag); } } //******************************************************************************** // Classes implementation //******************************************************************************** //================================ // PreviewSubCameraManager //-------------------------------- PreviewSubCameraManager::PreviewSubCameraManager() : m_mousePressed(false), m_dragType(NODRAG), m_clickAndDrag(false) { } //---------------------------------------------------------------------- PreviewSubCameraManager::~PreviewSubCameraManager() { } //---------------------------------------------------------------------- PreviewSubCameraManager *PreviewSubCameraManager::instance() { static PreviewSubCameraManager theInstance; return &theInstance; } //----------------------------------------------------------------------------- TRect PreviewSubCameraManager::getEditingCameraInterestRect() const { if (m_mousePressed) return m_editingInterestRect; else { //Return the actual current camera's interest rect TCamera *currCamera = TApp::instance()->getCurrentScene()->getScene()->getCurrentCamera(); return currCamera->getInterestRect(); } } //----------------------------------------------------------------------------- TRectD PreviewSubCameraManager::getEditingCameraInterestStageRect() const { TCamera *currCamera = TApp::instance()->getCurrentScene()->getScene()->getCurrentCamera(); if (m_mousePressed) //Build the stage rect associated with m_editingInterestRect return currCamera->getCameraToStageRef() * TRectD( m_editingInterestRect.x0, m_editingInterestRect.y0, m_editingInterestRect.x1 + 1, m_editingInterestRect.y1 + 1); else //Return the actual current camera's stage interest rect return currCamera->getInterestStageRect(); } //----------------------------------------------------------------------------- TPointD PreviewSubCameraManager::winToCamera(SceneViewer *viewer, const QPoint &pos) const { TPointD worldPos(viewer->winToWorld(pos)); TApp *app = TApp::instance(); TAffine stageToWorldRef(app->getCurrentXsheet()->getXsheet()->getCameraAff(app->getCurrentFrame()->getFrame())); TCamera *currCamera = app->getCurrentScene()->getScene()->getCurrentCamera(); return currCamera->getStageToCameraRef() * stageToWorldRef.inv() * worldPos; } //----------------------------------------------------------------------------- TPoint PreviewSubCameraManager::cameraToWin(SceneViewer *viewer, const TPointD &cameraPos) const { TApp *app = TApp::instance(); TAffine stageToWorldRef(app->getCurrentXsheet()->getXsheet()->getCameraAff(app->getCurrentFrame()->getFrame())); TCamera *currCamera = app->getCurrentScene()->getScene()->getCurrentCamera(); TPointD worldPos(stageToWorldRef * currCamera->getCameraToStageRef() * cameraPos); return viewer->worldToPos(worldPos); } //---------------------------------------------------------------------- bool PreviewSubCameraManager::mousePressEvent(SceneViewer *viewer, QMouseEvent *event) { if (viewer->is3DView()) return true; m_mousePressed = true; m_mousePressPos = event->pos(); m_dragType = getSubCameraDragEnum(viewer, m_mousePressPos); if (bitwiseExclude(m_dragType, OUTER)) m_cameraMousePressPos = winToCamera(viewer, m_mousePressPos); return false; } //---------------------------------------------------------------------- bool PreviewSubCameraManager::mouseMoveEvent(SceneViewer *viewer, QMouseEvent *event) { if (viewer->is3DView()) return true; QPoint curPos(event->pos()); if (event->buttons() == Qt::LeftButton) { if (!bitwiseContains(m_dragType, INNER)) { if (abs(curPos.x() - m_mousePressPos.x()) > 10 || abs(curPos.y() - m_mousePressPos.y()) > 10) m_clickAndDrag = true; } if (m_clickAndDrag == true) { //Write the temporary preview subcamera to current camera TPointD worldMousePressPos(viewer->winToWorld(m_mousePressPos)); TPointD worldCurPos(viewer->winToWorld(curPos)); TApp *app = TApp::instance(); TAffine cameraAffInv(app->getCurrentXsheet()->getXsheet()->getCameraAff(app->getCurrentFrame()->getFrame()).inv()); worldMousePressPos = cameraAffInv * worldMousePressPos; worldCurPos = cameraAffInv * worldCurPos; TRectD worldPreviewSubCameraRect( tmin(worldMousePressPos.x, worldCurPos.x), tmin(worldMousePressPos.y, worldCurPos.y), tmax(worldMousePressPos.x, worldCurPos.x), tmax(worldMousePressPos.y, worldCurPos.y)); TCamera *camera = app->getCurrentScene()->getScene()->getCurrentCamera(); //camera->setInterestStageRect(worldPreviewSubCameraRect); TRectD previewSubCameraD(camera->getStageToCameraRef() * worldPreviewSubCameraRect); m_editingInterestRect = TRect( previewSubCameraD.x0, previewSubCameraD.y0, previewSubCameraD.x1 - 1, previewSubCameraD.y1 - 1) * TRect(camera->getRes()); viewer->update(); } else { TPoint dragDistance = getSubCameraDragDistance(viewer, curPos); //Adjust the camera subrect TCamera *camera = TApp::instance()->getCurrentScene()->getScene()->getCurrentCamera(); TRect subRect(camera->getInterestRect()); if (bitwiseExclude(m_dragType, OUTER)) subRect += dragDistance; else { if (bitwiseContains(m_dragType, DRAG_LEFT)) subRect.x0 = subRect.x0 + dragDistance.x; else if (bitwiseContains(m_dragType, DRAG_RIGHT)) subRect.x1 = subRect.x1 + dragDistance.x; if (bitwiseContains(m_dragType, DRAG_BOTTOM)) subRect.y0 = subRect.y0 + dragDistance.y; else if (bitwiseContains(m_dragType, DRAG_TOP)) subRect.y1 = subRect.y1 + dragDistance.y; } m_editingInterestRect = subRect * TRect(camera->getRes()); viewer->update(); } } else { UCHAR dragEnum = getSubCameraDragEnum(viewer, curPos); if (dragEnum == NODRAG) viewer->setCursor(Qt::ArrowCursor); else if (bitwiseExclude(dragEnum, OUTER)) viewer->setCursor(Qt::SizeAllCursor); else switch (dragEnum) { case DRAG_LEFT: case DRAG_RIGHT: viewer->setCursor(Qt::SizeHorCursor); CASE DRAG_TOP : case DRAG_BOTTOM : viewer->setCursor(Qt::SizeVerCursor); CASE DRAG_LEFT | DRAG_TOP : case DRAG_RIGHT | DRAG_BOTTOM : viewer->setCursor(Qt::SizeFDiagCursor); CASE DRAG_LEFT | DRAG_BOTTOM : case DRAG_RIGHT | DRAG_TOP : viewer->setCursor(Qt::SizeBDiagCursor); DEFAULT: viewer->setCursor(Qt::ArrowCursor); } } //In case, perform the pan return event->buttons() == Qt::MidButton; } //---------------------------------------------------------------------- bool PreviewSubCameraManager::mouseReleaseEvent(SceneViewer *viewer, QMouseEvent *event) { if (viewer->is3DView()) return true; m_mousePressed = false; m_dragType = NODRAG; m_clickAndDrag = false; TCamera *camera = TApp::instance()->getCurrentScene()->getScene()->getCurrentCamera(); camera->setInterestRect(m_editingInterestRect); //Request a previewer update. Observe that whereas this previewer may not be in preview mode, //another visible one may. Previewer::instance(true)->updateView(); //Refresh viewer viewer->update(); return false; } //----------------------------------------------------------------------------- //! Builds the drag enum and camera distance for subcamera refinement drags. UCHAR PreviewSubCameraManager::getSubCameraDragEnum(SceneViewer *viewer, const QPoint &mousePos) { TCamera *camera = TApp::instance()->getCurrentScene()->getScene()->getCurrentCamera(); TRect subCamera = camera->getInterestRect(); if (subCamera.getLx() <= 0 || subCamera.getLy() <= 0) return NODRAG; TPointD cameraPosL(winToCamera(viewer, mousePos - QPoint(10, 0))); TPointD cameraPosR(winToCamera(viewer, mousePos + QPoint(10, 0))); TPointD cameraPosT(winToCamera(viewer, mousePos - QPoint(0, 10))); TPointD cameraPosB(winToCamera(viewer, mousePos + QPoint(0, 10))); TRectD cameraPosBox( tmin(cameraPosL.x, cameraPosR.x, cameraPosT.x, cameraPosB.x), tmin(cameraPosL.y, cameraPosR.y, cameraPosT.y, cameraPosB.y), tmax(cameraPosL.x, cameraPosR.x, cameraPosT.x, cameraPosB.x), tmax(cameraPosL.y, cameraPosR.y, cameraPosT.y, cameraPosB.y)); TRectD subCameraD(subCamera.x0, subCamera.y0, subCamera.x1 + 1, subCamera.y1 + 1); //Now, find out the drag enums, in case the mouse pos is near a sensible part of the rect UCHAR dragType = NODRAG; if (cameraPosBox.y0 < subCameraD.y1) dragType |= INNER_TOP; if (cameraPosBox.y1 > subCameraD.y0) dragType |= INNER_BOTTOM; if (cameraPosBox.x0 < subCameraD.x1) dragType |= INNER_RIGHT; if (cameraPosBox.x1 > subCameraD.x0) dragType |= INNER_LEFT; if (cameraPosBox.y1 > subCameraD.y1) dragType |= OUTER_TOP; if (cameraPosBox.y0 < subCameraD.y0) dragType |= OUTER_BOTTOM; if (cameraPosBox.x1 > subCameraD.x1) dragType |= OUTER_RIGHT; if (cameraPosBox.x0 < subCameraD.x0) dragType |= OUTER_LEFT; return dragType; } //----------------------------------------------------------------------------- TPoint PreviewSubCameraManager::getSubCameraDragDistance(SceneViewer *viewer, const QPoint &mousePos) { //Build the camera drag distance if (m_clickAndDrag) return TPoint(); TPointD cameraMousePos(winToCamera(viewer, mousePos)); if (bitwiseExclude(m_dragType, OUTER)) { TPointD resultD(cameraMousePos - m_cameraMousePressPos); return TPoint(resultD.x, resultD.y); } TCamera *camera = TApp::instance()->getCurrentScene()->getScene()->getCurrentCamera(); TRect subCamera = camera->getInterestRect(); TRectD subCameraD(subCamera.x0, subCamera.y0, subCamera.x1 + 1, subCamera.y1 + 1); TPoint result; if (bitwiseContains(m_dragType, DRAG_LEFT)) result.x = cameraMousePos.x - subCameraD.x0; else if (bitwiseContains(m_dragType, DRAG_RIGHT)) result.x = cameraMousePos.x - subCameraD.x1; if (bitwiseContains(m_dragType, DRAG_BOTTOM)) result.y = cameraMousePos.y - subCameraD.y0; else if (bitwiseContains(m_dragType, DRAG_TOP)) result.y = cameraMousePos.y - subCameraD.y1; return result; } //----------------------------------------------------------------------------- /*! Delete sub camera frame. Executed from context menu of the viewer. */ void PreviewSubCameraManager::deleteSubCamera(SceneViewer *viewer) { TCamera *camera = TApp::instance()->getCurrentScene()->getScene()->getCurrentCamera(); camera->setInterestRect(TRect()); Previewer::instance(true)->updateView(); //Refresh viewer viewer->update(); } 0 #include #include #include #include using namespace std; typedef unsigned long ul; int main() { ul N; cin >> N; map> cards; cerr << N << endl; string answer; ul r1, r2; for (ul i = 0; i < 2*N; i+=2) { cout << i+1 << " " << i+2 << endl; cin >> answer; if (answer == "MATCH") { continue; } istringstream iss(answer); iss >> r1; cin >> r2; map>::iterator it1 = cards.find(r1); if(it1 == cards.end()) { cards[r1] = pair(i+1, 0); } else { it1->second.second = i+1; } map>::iterator it2 = cards.find(r2); if(it2 == cards.end()) { cards[r2] = pair(i+2, 0); } else { it2->second.second = i+2; } } string match; for (auto iter = cards.begin(); iter != cards.end(); iter++) { cout << iter->second.first << " " << iter->second.second << endl; cin >> match; } cout << "-1" << endl; return 0; }src/Core/Input/KeyBindingsConfigWindow.cpp0 // For conditions of distribution and use, see copyright notice in license.txt #include "DebugOperatorNew.h" #include "KeyBindingsConfigWindow.h" #include "InputAPI.h" #include "Framework.h" #include "Application.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "MemoryLeakCheck.h" KeyBindingsConfigWindow::KeyBindingsConfigWindow(Framework *fw) : framework(fw), configList(0) { QUiLoader loader; QFile file(Application::InstallationDirectory() + "data/ui/KeyBindingsConfig.ui"); file.open(QFile::ReadOnly); QWidget *contents_widget_ = loader.load(&file, this); assert(contents_widget_); file.close(); if (!contents_widget_) return; QVBoxLayout *layout = new QVBoxLayout; assert(layout); layout->addWidget(contents_widget_); layout->setContentsMargins(0,0,0,0); setLayout(layout); configList = findChild("configList"); configList->installEventFilter(this); QPushButton *apply = findChild("pushButtonApply"); connect(apply, SIGNAL(pressed()), this, SLOT(ApplyKeyConfig())); connect(configList, SIGNAL(itemClicked(QTreeWidgetItem*, int)), this, SLOT(ConfigListAdjustEditable(QTreeWidgetItem *, int))); connect(configList, SIGNAL(itemDoubleClicked(QTreeWidgetItem*, int)), this, SLOT(ConfigListAdjustEditable(QTreeWidgetItem *, int))); PopulateBindingsList(); setWindowTitle(tr("Key bindings")); setAttribute(Qt::WA_DeleteOnClose); } KeyBindingsConfigWindow::~KeyBindingsConfigWindow() { Clear(); } void KeyBindingsConfigWindow::ApplyKeyConfig() { ExtractBindingsList(); QStringList conflictingSequences; for(std::map::const_iterator it = editedActions.begin(); it != editedActions.end(); ++it) { std::map::const_iterator jt = it; ++jt; for(;jt != editedActions.end(); ++jt) if(it != jt && it->second == jt->second && it->second == jt->second && !conflictingSequences.contains(it->second.toString())) { conflictingSequences.append(it->second.toString()); break; } } if (conflictingSequences.size() > 0) { if(!QMessageBox::question(this, tr("Bindings Warning?"), tr("Same shortcut '%1' has been set on multiple actions! Do you wish to continue?").arg(conflictingSequences.join(",")), tr("&Yes"), tr("&No"), QString::null, 0, 1)) { framework->Input()->SetKeyBindings(editedActions); framework->Input()->SaveKeyBindingsToFile(); } } } /// Read more from http://www.qtcentre.org/threads/26689-QTableWidget-one-column-editable void KeyBindingsConfigWindow::ConfigListAdjustEditable(QTreeWidgetItem *item, int column) { if (column == 1) item->setFlags(Qt::ItemIsSelectable|Qt::ItemIsEnabled|Qt::ItemIsEditable); else item->setFlags(Qt::ItemIsSelectable|Qt::ItemIsEnabled); } void KeyBindingsConfigWindow::ExtractBindingsList() { for(int i = 0; i < configList->topLevelItemCount(); ++i) { QTreeWidgetItem *item = configList->topLevelItem(i); std::string actionName = item->text(0).toStdString(); QKeySequence shortcut = QKeySequence::fromString(item->text(1), QKeySequence::NativeText); editedActions[actionName] = shortcut; } } void KeyBindingsConfigWindow::Clear() { for(uint i = 0; i < (uint)configList->topLevelItemCount(); ++i) { QTreeWidgetItem *item = configList->topLevelItem(i); delete item; } configList->clear(); } void KeyBindingsConfigWindow::PopulateBindingsList() { assert(configList); if (!configList) return; Clear(); const InputAPI::KeyActionsMap &keyActions = framework->Input()->KeyBindings(); for(InputAPI::KeyActionsMap::const_iterator iter = keyActions.begin(); iter != keyActions.end(); ++iter) { QTreeWidgetItem *item = new QTreeWidgetItem((QTreeWidget*)0, QStringList(QString(iter->first.c_str()))); item->setText(1, iter->second.toString(QKeySequence::NativeText)); item->setFlags(Qt::ItemIsSelectable|Qt::ItemIsEnabled|Qt::ItemIsEditable); configList->addTopLevelItem(item); } configList->resizeColumnToContents(0); } void KeyBindingsConfigWindow::ButtonOK() { ApplyKeyConfig(); } void KeyBindingsConfigWindow::ButtonCancel() { framework->Input()->LoadKeyBindingsFromFile(); } bool KeyBindingsConfigWindow::eventFilter(QObject *obj, QEvent *event) { QTreeWidgetItem *current_item = configList->currentItem(); if (event->type() == QEvent::KeyPress) { QKeyEvent *key_event = dynamic_cast(event); if (key_event && current_item) { if (key_event->isAutoRepeat()) return true; if (key_event->key() == Qt::Key_Backspace || key_event->key() == Qt::Key_Return || key_event->key() == Qt::Key_Enter ) return QWidget::eventFilter(obj, event); if (key_event->modifiers() != Qt::NoModifier && !key_event->isAutoRepeat()) { QKeySequence key_text(key_event->modifiers()); QString text = key_text.toString(); QString insert_text = text.remove(text.count() - 1, 1); current_item->setText(1, insert_text); key_event->accept(); return true; } else { if(key_event->key() == Qt::Key_Up || key_event->key() == Qt::Key_Down || key_event->key() == Qt::Key_Tab || key_event->key() == Qt::Key_PageUp || key_event->key() == Qt::Key_PageDown) { key_event->accept(); return true; } } } } else { if (event->type() == QEvent::KeyRelease) { QKeyEvent *key_event = dynamic_cast(event); if (key_event && current_item) { if (key_event->isAutoRepeat()) return true; if (key_event->key() == Qt::Key_Backspace || key_event->key() == Qt::Key_Return || key_event->key() == Qt::Key_Enter || SpecialKeyPressChecker(key_event->key())) return QWidget::eventFilter(obj, event); if (key_event->modifiers() == Qt::NoModifier || key_event->key() != Qt::Key_unknown) { QString item_text = current_item->text(1); if(item_text.length() < 2) { current_item->setText(1, ""); current_item->setText(1, QKeySequence(key_event->key()).toString()); key_event->accept(); return true; } else { QStringList items = item_text.split("+"); if(!items.isEmpty()) { if(items.last().length() < 2) { current_item->setText(1, QKeySequence(key_event->key()).toString()); key_event->accept(); return true; } else { int already_there = 0; for(int i = 0; i < items.length(); i++) { if(items.value(i) == QKeySequence(key_event->key()).toString()) { already_there = 1; break; } } if(already_there) { current_item->setText(1, QKeySequence(key_event->key()).toString()); key_event->accept(); return true; } else { current_item->setText(1, item_text + "+" + QKeySequence(key_event->key()).toString()); key_event->accept(); return true; } } } } } } } } return QWidget::eventFilter(obj, event); } bool KeyBindingsConfigWindow::SpecialKeyPressChecker(int pressed_key) { bool result = false; switch(pressed_key) { case Qt::Key_Control: case Qt::Key_Alt: case Qt::Key_Shift: case Qt::Key_Meta: case Qt::Key_AltGr: result = true; break; } return result; }terark-tools/fast-test/test.hpp #pragma warning(disable:4996) #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
#include
#include
#include #include #include #include #include #include #include #include #include #include #include #include #include typedef int8_t I1; typedef int16_t I2; typedef int32_t I4; typedef int64_t I8; typedef uint8_t U1; typedef uint16_t U2; typedef uint32_t U4; typedef uint64_t U8; typedef std::string t_str; t_str get_key(U8 u8_num) { char buffer[32]; snprintf(buffer, sizeof(buffer), "%012zd", u8_num); return buffer; } t_str get_val(U8 i) { static std::string str = [] { std::string s = "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890"; s += s; s += s; s += s; s += s; s += s; s += s; s += s; s += s; s += s; s += s; std::shuffle(s.begin(), s.end(), std::mt19937_64()); return s; }(); size_t pos = (i * 11) % str.size(); size_t size = std::min(str.size() - pos, (i * 13) % 64); std::string value = get_key(i); value.append("#"); value.append(str.data() + pos, str.data() + pos + size); value.append("#"); return value; }Source/Common/twModelReader.cpp #include #include "twModelReader.h" #include "twMaterialInstance.h" #include "twConsoleLog.h" namespace TwinkleGraphics { ModelReader::ModelReader() { } ModelReader::~ModelReader() { } /** * */ template <> ReadResult ModelReader::Read(const char *filename, ReaderOption *option) { // https://learnopengl.com/ Assimp::Importer importer; const aiScene* scene = importer.ReadFile(filename, aiProcess_Triangulate | aiProcess_FlipUVs | aiProcess_CalcTangentSpace); // check for errors if(!scene || scene->mFlags & AI_SCENE_FLAGS_INCOMPLETE || !scene->mRootNode) // if is Not Zero { Console::LogError("ERROR::ASSIMP:: ", importer.GetErrorString(), "\n"); return ReadResult(ReadResult::Status::FAILED); } Model::Ptr model = std::make_shared(); std::string path(filename); // retrieve the directory path of the filepath std::string directory = path.substr(0, path.find_last_of('\\')); Material::Ptr vectorMaterials[scene->mNumMaterials] = {nullptr}; // process ASSIMP's root node recursively Geometry::Ptr rootGeom = ProcessNode(scene->mRootNode, scene, directory, model, vectorMaterials); model->SetRootGeometry(rootGeom); return ReadResult(model, ReadResult::Status::SUCCESS); } /** * https://learnopengl.com/ * processes a node in a recursive fashion. Processes each individual mesh located at the node and repeats this process on its children nodes (if any). */ Geometry::Ptr ModelReader::ProcessNode(aiNode *node, const aiScene *scene, std::string dir, Model::Ptr model, Material::Ptr vecMats[]) { int32 verticeNum = 0; int32 meshFlag = (int32)(MeshDataFlag::DEFAULT); // process each mesh located at the current node for (unsigned int i = 0; i < node->mNumMeshes; i++) { // the node object only contains indices to index the actual objects in the scene. // the scene contains all the data, node is just to keep stuff organized (like relations between nodes). aiMesh *mesh = scene->mMeshes[node->mMeshes[i]]; verticeNum += mesh->mNumVertices; if(mesh->mColors[0] != nullptr) { meshFlag |= MeshDataFlag::HAS_COLOR; } if(mesh->mNormals != nullptr) { meshFlag |= MeshDataFlag::HAS_NORMAL; } if(mesh->mTangents != nullptr) { meshFlag |= MeshDataFlag::HAS_BINORMAL; } MeshDataFlag texcoordFlags[AI_MAX_NUMBER_OF_TEXTURECOORDS] = { MeshDataFlag::HAS_UV, MeshDataFlag::HAS_UV1, MeshDataFlag::HAS_UV2, MeshDataFlag::HAS_UV3, MeshDataFlag::HAS_UV4, MeshDataFlag::HAS_UV5, MeshDataFlag::HAS_UV6, MeshDataFlag::HAS_UV7 }; for(unsigned int k = 0; k < AI_MAX_NUMBER_OF_TEXTURECOORDS; k++) { if(mesh->mTextureCoords[k] != nullptr) { meshFlag |= texcoordFlags[k]; } } } Geometry::Ptr geom = std::make_shared(); Transform::Ptr parentTransform = geom->GetTransform(); model->AddGeometry(geom); if (verticeNum > 0) { MeshRenderer::Ptr renderer = std::make_shared(); geom->SetMeshRenderer(renderer); Mesh::Ptr tMesh = std::make_shared(); tMesh->Initialize(verticeNum, MeshDataFlag(meshFlag)); verticeNum = 0; for (unsigned int i = 0; i < node->mNumMeshes; i++) { // the node object only contains indices to index the actual objects in the scene. // the scene contains all the data, node is just to keep stuff organized (like relations between nodes). aiMesh *mesh = scene->mMeshes[node->mMeshes[i]]; SubMesh::Ptr subMesh = ProcessMesh(mesh, tMesh, verticeNum, scene); tMesh->AddSubMesh(subMesh); if(vecMats[mesh->mMaterialIndex] != nullptr) { int32 matIndex = renderer->GetMaterialIndex(vecMats[mesh->mMaterialIndex]); if(matIndex == -1) { subMesh->SetMaterialIndex(renderer->GetMaterialCount()); renderer->AddMaterial(vecMats[mesh->mMaterialIndex]); } else { subMesh->SetMaterialIndex(renderer->GetMaterialIndex(vecMats[mesh->mMaterialIndex])); } } else { Material::Ptr material = ProcessMaterial(mesh, scene, scene->mMaterials[mesh->mMaterialIndex], dir, (VertexLayoutFlag)meshFlag); subMesh->SetMaterialIndex(renderer->GetMaterialCount()); renderer->AddMaterial(material); vecMats[mesh->mMaterialIndex] = material; } verticeNum += mesh->mNumVertices; } geom->SetMeshExternal(tMesh); renderer->SetMesh(tMesh, true); } // after we've processed all of the meshes (if any) we then recursively process each of the children nodes for (unsigned int i = 0; i < node->mNumChildren; i++) { Geometry::Ptr childGeom = ProcessNode(node->mChildren[i], scene, dir, model, vecMats); Transform::Ptr childTransform = childGeom->GetTransform(); childTransform->SetParent(parentTransform); } return geom; } /** * https://learnopengl.com/ */ SubMesh::Ptr ModelReader::ProcessMesh(aiMesh *mesh, Mesh::Ptr tMesh, int32 offset, const aiScene *scene) { SubMesh::Ptr subMesh = std::make_shared(); int32 indiceNum = 0; // now wak through each of the mesh's faces (a face is a mesh its triangle) and retrieve the corresponding vertex indices. for(unsigned int i = 0; i < mesh->mNumFaces; i++) { aiFace face = mesh->mFaces[i]; indiceNum += face.mNumIndices; } subMesh->Initialize(indiceNum); uint32* indices = subMesh->GetIndice(); int indiceIndex = 0; for(unsigned int i = 0; i < mesh->mNumFaces; i++) { aiFace face = mesh->mFaces[i]; // retrieve all indices of the face and store them in the indices vector for(unsigned int j = 0; j < face.mNumIndices; j++) { indices[indiceIndex++] = face.mIndices[j] + offset; } } glm::vec3* verticePos = tMesh->GetVerticePos(); glm::vec3* verticeNormal = tMesh->GetVerticeNormal(); glm::vec3* verticeBinormal = tMesh->GetVerticeBiNormal(); glm::vec4* verticeColor = tMesh->GetVerticeColor(); glm::vec4* verticeUV = tMesh->GetVerticeUV(); glm::vec4* verticeUV1 = tMesh->GetVerticeUV1(); glm::vec4* verticeUV2 = tMesh->GetVerticeUV2(); glm::vec4* verticeUV3 = tMesh->GetVerticeUV3(); glm::vec4* verticeUV4 = tMesh->GetVerticeUV4(); glm::vec4* verticeUV5 = tMesh->GetVerticeUV5(); glm::vec4* verticeUV6 = tMesh->GetVerticeUV6(); glm::vec4* verticeUV7 = tMesh->GetVerticeUV7(); verticePos += offset; if(verticeNormal != nullptr) { verticeNormal += offset; } if(verticeBinormal != nullptr) { verticeBinormal += offset; } if(verticeColor != nullptr) { verticeColor += offset; } // texture coordinates glm::vec4 *uvs[AI_MAX_NUMBER_OF_TEXTURECOORDS] = { verticeUV, verticeUV1, verticeUV2, verticeUV3, verticeUV4, verticeUV5, verticeUV6, verticeUV7 }; for(int32 s = 0; s < AI_MAX_NUMBER_OF_TEXTURECOORDS; s++) { if (uvs[s] != nullptr) { uvs[s] += offset; } } // walk through each of the mesh's vertices for(unsigned int i = 0; i < mesh->mNumVertices; i++) { glm::vec3 vector; // we declare a placeholder vector since assimp uses its own vector class that doesn't directly convert to glm's vec3 class so we transfer the data to this placeholder glm::vec3 first. // positions vector.x = mesh->mVertices[i].x; vector.y = mesh->mVertices[i].y; vector.z = mesh->mVertices[i].z; verticePos[i] = vector; // normals if(mesh->mNormals != nullptr) { vector.x = mesh->mNormals[i].x; vector.y = mesh->mNormals[i].y; vector.z = mesh->mNormals[i].z; verticeNormal[i] = vector; } for(unsigned int j = 0; j < AI_MAX_NUMBER_OF_TEXTURECOORDS; j++) { if(uvs[j] != nullptr) { if(mesh->mTextureCoords[j]) { glm::vec4 vec; // a vertex can contain up to 8 different texture coordinates. We thus make the assumption that we won't // use models where a vertex can have multiple texture coordinates so we always take the first set (0). vec.x = mesh->mTextureCoords[j][i].x; vec.y = 1.0f - mesh->mTextureCoords[j][i].y; uvs[j][i] = vec; } else { uvs[j][i] = glm::vec4(0.0f, 0.0f, 0.0f, 0.0f); } } } // AI_MAX_NUMBER_OF_COLOR_SETS if(mesh->mColors[0] != nullptr) { glm::vec4 vecColor; vecColor.r = mesh->mColors[0][i].r; vecColor.g = mesh->mColors[0][i].g; vecColor.b = mesh->mColors[0][i].b; vecColor.a = mesh->mColors[0][i].a; verticeColor[i] = vecColor; } // tangent if(mesh->mTangents != nullptr) { vector.x = mesh->mTangents[i].x; vector.y = mesh->mTangents[i].y; vector.z = mesh->mTangents[i].z; verticeBinormal[i] = vector; } } verticePos = nullptr; verticeNormal = nullptr; verticeBinormal = nullptr; verticeColor = nullptr; verticeUV = nullptr; verticeUV1 = nullptr; verticeUV2 = nullptr; verticeUV3 = nullptr; verticeUV4 = nullptr; verticeUV5 = nullptr; verticeUV6 = nullptr; verticeUV7 = nullptr; return subMesh; } /** * https://learnopengl.com/ */ Material::Ptr ModelReader::ProcessMaterial(aiMesh *mesh, const aiScene *scene, aiMaterial *mat, std::string dir, VertexLayoutFlag layoutFlag) { std::string vertLayoutMacros(""); int32 operand = 1; int32 index = 0; int32 numVerteLayoutMacros = 0; while (index <= 10) { /* code */ int32 logicAnd = operand & (int32)layoutFlag; if(logicAnd > 0) { vertLayoutMacros += VertexLayoutDefines[index]; numVerteLayoutMacros++; } operand <<= 1; index++; } char* vertMarco = const_cast(vertLayoutMacros.c_str()); Console::LogInfo("ModelReader: Process material vertex shader macros\n", vertMarco, "\n"); char* vertMacros[] = { vertMarco }; ShaderReadInfo shaderReadInfos[] = { {std::string("Assets/Shaders/standard.vert"), ShaderType::VERTEX_SHADER, 1, vertMacros, true}, {std::string("Assets/Shaders/standard.frag"), ShaderType::FRAGMENT_SHADER, 1, vertMacros, true} }; StandardMaterial::Ptr material = std::make_shared(shaderReadInfos, 2); // process materials aiMaterial* aiMat = scene->mMaterials[mesh->mMaterialIndex]; // we assume a convention for sampler names in the shaders. Each diffuse texture should be named // as 'texture_diffuseN' where N is a sequential number ranging from 1 to MAX_SAMPLER_NUMBER. // Same applies to other texture as the following list summarizes: // diffuse: texture_diffuseN // specular: texture_specularN // normal: texture_normalN // 1. diffuse maps std::vector diffuseMaps = LoadTextures(aiMat, aiTextureType_DIFFUSE, dir); SetMaterialTextures(diffuseMaps, material, "diffuseTex"); // 2. specular maps std::vector specularMaps = LoadTextures(aiMat, aiTextureType_SPECULAR, dir); SetMaterialTextures(specularMaps, material, "specularTex"); // 3. normal maps std::vector normalMaps = LoadTextures(aiMat, aiTextureType_NORMALS, dir); SetMaterialTextures(normalMaps, material, "normalTex"); // 4. height maps std::vector heightMaps = LoadTextures(aiMat, aiTextureType_HEIGHT, dir); SetMaterialTextures(heightMaps, material, "heightTex"); // 5. amibient maps std::vector ambientMaps = LoadTextures(aiMat, aiTextureType_AMBIENT, dir); SetMaterialTextures(ambientMaps, material, "ambientTex"); // 6. emissive maps std::vector emissiveMaps = LoadTextures(aiMat, aiTextureType_EMISSIVE, dir); SetMaterialTextures(emissiveMaps, material, "emissiveTex"); // 7. shininess maps std::vector shininessMaps = LoadTextures(aiMat, aiTextureType_SHININESS, dir); SetMaterialTextures(shininessMaps, material, "shininessTex"); // 8. opacity maps std::vector opacityMaps = LoadTextures(aiMat, aiTextureType_OPACITY, dir); SetMaterialTextures(opacityMaps, material, "opacityTex"); // 9. displacement maps std::vector displacementMaps = LoadTextures(aiMat, aiTextureType_DISPLACEMENT, dir); SetMaterialTextures(displacementMaps, material, "displacementTex"); // 10. lightmap maps std::vector lightmapMaps = LoadTextures(aiMat, aiTextureType_LIGHTMAP, dir); SetMaterialTextures(lightmapMaps, material, "lightmapTex"); // 11. reflection maps std::vector reflectionMaps = LoadTextures(aiMat, aiTextureType_REFLECTION, dir); SetMaterialTextures(reflectionMaps, material, "reflectionTex"); return material; } void ModelReader::SetMaterialTextures(std::vector& textures, Material::Ptr material, std::string texNamePrefix) { int32 number = 0; for(auto texture : textures) { std::string texVarName = texNamePrefix + std::to_string(number++); material->SetTexture(texVarName.c_str(), texture); } } // checks all material textures of a given type and loads the textures if they're not loaded yet. // the required info is returned as a Texture struct. std::vector ModelReader::LoadTextures(aiMaterial *mat, aiTextureType type, std::string dir) { std::vector textures; for(unsigned int i = 0; i < mat->GetTextureCount(type); i++) { aiString str; mat->GetTexture(type, i, &str); // int32 a = 5; // if(std::string(str.C_Str()).find("sponza_arch_diff") && type == aiTextureType_DIFFUSE) // { // assert(a != 5); // std::cout << str.C_Str() << std::endl; // } ImageManagerInst imageMgr; ImageReadInfo images_info = {dir + "/" + std::string(str.C_Str())}; Image::Ptr image = imageMgr->ReadImage(images_info); if(image == nullptr) { continue; } ImageData* imageData = image->GetImageSourcePtr(); float fwh = imageData->mip[0].width > imageData->mip[0].height ? imageData->mip[0].height : imageData->mip[0].width; int32 level = 0; while(fwh >= 1.0f) { fwh /= 2.0f; level++; } if(level > 10) { level = 10; } imageData->mipLevels = level; Texture2D::Ptr texture = nullptr; if (image != nullptr) { texture = std::make_shared(true, true); texture->CreateFromImage(image); texture->SetWrap(WrapMode::REPEAT); texture->SetWrap(WrapMode::REPEAT); texture->SetFilter(FilterMode::LINEAR_MIPMAP_LINEAR); texture->SetFilter(FilterMode::LINEAR); texture->SetMipMapBaseLevel(MipMapBaseLevelParam::BESE_LEVEL, 0); texture->SetMipMapMaxLevel(MipMapMaxLevelParam::MAX_LEVEL, level - 1); textures.push_back(texture); } } return textures; } Model::Ptr ModelManager::ReadModel(const char* filename) { ResourceManagerInst resMgr; ReadResult result = resMgr->Read(filename, nullptr); Model::Ptr model = result.GetSharedObject(); return model; } } // namespace TwinkleGraphics NOAA-EMC/ioda /* * (C) Copyright 2020-2021 UCAR * * This software is licensed under the terms of the Apache Licence Version 2.0 * which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. */ /*! \addtogroup ioda_internals_engines_obsstore * * @{ * \file VarAttrStore.cpp * \brief Functions for ObsStore variable and attribute data storage */ #include "./VarAttrStore.hpp" #include #include "./Type.hpp" #include "ioda/Exception.h" namespace ioda { namespace ObsStore { //------------------------------------------------------------------------------ VarAttrStore_Base *createVarAttrStore(const std::shared_ptr & dtype) { VarAttrStore_Base *newStore = nullptr; // Get the fundamental (base) type marker. In the case of an arrayed type, // the fundamental type mark is in the base type data member of dtype. ObsTypes topLevelType = dtype->getType(); ObsTypes baseType; if (topLevelType == ObsTypes::ARRAY) { baseType = dtype->getBaseType()->getType(); } else { baseType = topLevelType; } // Record the number of elements in the type. For fundamental types this would be 1, // and for arrayed types this would be determined according to the dimension sizes. std::size_t numElements = dtype->getNumElements(); // Use the baseType value to determine which templated version of the data store // to instantiate. if (baseType == ObsTypes::FLOAT) { newStore = new VarAttrStore(numElements); } else if (baseType == ObsTypes::DOUBLE) { newStore = new VarAttrStore(numElements); } else if (baseType == ObsTypes::LDOUBLE) { newStore = new VarAttrStore(numElements); } else if (baseType == ObsTypes::SCHAR) { newStore = new VarAttrStore(numElements); } else if (baseType == ObsTypes::SHORT) { newStore = new VarAttrStore(numElements); } else if (baseType == ObsTypes::INT) { newStore = new VarAttrStore(numElements); } else if (baseType == ObsTypes::LONG) { newStore = new VarAttrStore(numElements); } else if (baseType == ObsTypes::LLONG) { newStore = new VarAttrStore(numElements); } else if (baseType == ObsTypes::UCHAR) { newStore = new VarAttrStore(numElements); } else if (baseType == ObsTypes::USHORT) { newStore = new VarAttrStore(numElements); } else if (baseType == ObsTypes::UINT) { newStore = new VarAttrStore(numElements); } else if (baseType == ObsTypes::ULONG) { newStore = new VarAttrStore(numElements); } else if (baseType == ObsTypes::ULLONG) { newStore = new VarAttrStore(numElements); } else if (baseType == ObsTypes::CHAR) { newStore = new VarAttrStore(numElements); } else if (baseType == ObsTypes::WCHAR) { newStore = new VarAttrStore(numElements); } else if (baseType == ObsTypes::CHAR16) { newStore = new VarAttrStore(numElements); } else if (baseType == ObsTypes::CHAR32) { newStore = new VarAttrStore(numElements); } else if (baseType == ObsTypes::STRING) { newStore = new VarAttrStore(numElements); } else throw Exception("Unrecognized data type encountered during " "Attribute object construnction", ioda_Here()); return newStore; } } // namespace ObsStore } // namespace ioda /// @} #define _USE_MATH_DEFINES #include "floodFill.h" #include "Utils.h" bool less_by_x(const cv::Point& lhs, const cv::Point& rhs) { return lhs.x < rhs.x; } bool less_by_y(const cv::Point& lhs, const cv::Point& rhs) { return lhs.y < rhs.y; } void floodFillStep(vector> &grid, Point startPoint, int stepFromStartPoint); void makeGridDoubleBoundary(vector> &grid, const vector &contour); void changeCellValue(vector>& grid, Point &cell, int cellValue); int getCellValue(const vector>& grid, const Point &cell); bool cellFitInGrid(const vector>& grid, const Point &cell); int enclosedPixels(const vector & contourVec, vector & regionPixels) { std::copy(contourVec.begin(), contourVec.end(), back_inserter(regionPixels)); //calculate min and max, x and y values auto mmx = std::minmax_element(contourVec.begin(), contourVec.end(), less_by_x); auto mmy = std::minmax_element(contourVec.begin(), contourVec.end(), less_by_y); const int width = mmx.second->x - mmx.first->x + 1; const int height = mmy.second->y - mmy.first->y + 1; Point translationVector(mmx.first->x, mmy.first->y); //make boundary box grid vector> grid(height); for (auto &columns : grid) { columns = vector(width); } for (auto &columns : grid) { for (auto &cell : columns) { cell = -1; } } vector boundaryBoxContour; //make contour points 100; for (auto const &contour : contourVec) { int x = contour.x - translationVector.x; int y = contour.y - translationVector.y; /*if (x < 0 || x >= grid[y].size() || y < 0 || y >= grid.size()) { cout << "X,Y outside of the grid" << x << ", " << y << endl; } */ boundaryBoxContour.push_back(Point(x, y)); //cout << "Last placed y and x: " << y << ", " << x << endl; grid[y][x] = 100; } //make the contour water proof. makeGridDoubleBoundary(grid, boundaryBoxContour); Point startPoint(3, 3); //define a startpoint bool loop = true; bool pointInC = false; bool pointInBoundary = true; while (loop) { startPoint.x = rand() % (mmx.second->x - mmx.first->x) + mmx.first->x; startPoint.y = rand() % (mmy.second->y - mmy.first->y) + mmy.first->y; pointInC = pixelInContour(boundaryBoxContour, startPoint); pointInBoundary = elementInVector(boundaryBoxContour, startPoint); cout << "point In Boundary" << endl; loop = !(pointInC && !pointInBoundary); } cout << "start point found: " << startPoint << endl; grid[startPoint.y][startPoint.x] = 0; floodFillStep(grid, startPoint, 1); for (int r = 0; r < grid.size(); r++) { for (int c = 0; c < grid[r].size(); c++) { auto cell = grid[r][c]; if (0 <= cell && cell < 100) { regionPixels.push_back(Point(c, r) + translationVector); } } } return regionPixels.size(); } vector directions = { {-1, 0}, {-1, -1}, {0,-1}, {1,-1}, {1,0}, {1,1}, {0,1}, {-1,1} }; /* grid, with the contour of values 100 startPoints lies i the contour. */ void floodFillStep(vector> &grid, Point startPoint, int stepFromStartPoint) { vector foundPoints = { startPoint }, nextStepPoints; do { std::copy(foundPoints.begin(), foundPoints.end(), back_inserter(nextStepPoints)); foundPoints.clear(); for (auto const &point : nextStepPoints) { for (auto const &dir : directions) { auto nextStep = point + dir; if (!cellFitInGrid(grid, nextStep)) continue; auto cellValue = getCellValue(grid, nextStep); if (cellValue == -1) { foundPoints.push_back(nextStep); changeCellValue(grid, nextStep, stepFromStartPoint); } } } cout << foundPoints.size() << endl; nextStepPoints.clear(); } while (foundPoints.size() > 0); } float angle = 90 / 180.0 * M_PI; void changeCellValue(vector>& grid, Point &cell, int cellValue) { if (!cellFitInGrid(grid, cell)) return; grid[cell.y][cell.x] = cellValue; } int getCellValue(const vector>& grid, const Point & cell) { if (!cellFitInGrid(grid, cell)) throw out_of_range("Cell out of range"); return grid[cell.y][cell.x]; } bool cellFitInGrid(const vector>& grid, const Point & cell) { if (cell.y < 0 || cell.y >= grid.size()) return false; if (cell.x < 0 || cell.x >= grid[cell.y].size()) return false; return true; } void makeGridDoubleBoundary(vector>& grid, const vector& contour) { Point translation, newBoundaryTranslation, newBoundary1, newBoundary2; int j; int x = 0, y = 0; for (int i = 0; i < contour.size(); i++) { j = (i + 1) % contour.size(); //substract next and current point to get the translation vector from the current to the next point. translation = contour[j] - contour[i]; //rotate the translation vector newBoundaryTranslation.x = translation.x * cos(angle) - translation.y * sin(angle); newBoundaryTranslation.y = translation.x * sin(angle) + translation.y * cos(angle); newBoundary1 = contour[i] + newBoundaryTranslation; newBoundary2 = contour[j] + newBoundaryTranslation; changeCellValue(grid, newBoundary1, 100); changeCellValue(grid, newBoundary2, 100); } } #include using namespace std; int main(){ int delta = 32; char in; char out; cin>>in; out = in+delta; cout< (sekiguchi at acm dot org) // // 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 . // ============================================================================== /*! \file tbc/ConsoleLog.hpp \author \version 3.0.1 \date 2014/01/10 \brief Header file for tbc library types This file defines types for tbc library */ #ifndef TBC_CONSOLE_LOG_HPP #define TBC_CONSOLE_LOG_HPP // Includes -------------------------------------------------------------------- #include #include "tbc/log/Log.hpp" #include "tbc/Mutex.hpp" // Namespace ------------------------------------------------------------------- namespace tbc { // ------------------------------------------------------------------------- // Exception class // ------------------------------------------------------------------------- class ConsoleLog : public virtual LogBase { public: // Constructors and Destructor ----------------------------------------- ConsoleLog() {} ~ConsoleLog() {} // Member Functions ---------------------------------------------------- virtual void write(unsigned int inType, unsigned char inLenvel, const char *inMessage) { if (!isLogOutMessage(inType, inLevel)) return; try { mMutex.lock(); } catch (Exception &ex) { std::cerr << "Can't lock mutex" << std::endl; ex.dump(); } const size_t bufSize = 80; char buf[bufSize]; makeTimeStampStr(buf, bufSize); std::cout << buf; makeTypeStr(inType, buf, bufSize); std::cout << buf; makeLevelStr(inLevel, buf, bufSize); std::cout << buf; std::cout << inMessage << std::endl; try { mMutex.unlock(); } catch (MyException &ex) { std::cerr << "Can't unlock mutex" << std::endl; ex.dump(); } } virtual void binayDump(int inDumpType, const char *inDumpName, const unsigned char *inData, int inDataLen) { } private: // Member Variables ---------------------------------------------------- Mutex mMutex; } #endif // TBC_CONSOLE_LOG_HPP // // Solution to https://dmoj.ca/problem/dmopc14c2p4 #include int dp[1000010],n,q; int main(){ scanf("%d",&n); for(int i=1;i<=n;i++){ scanf("%d",&dp[i]); dp[i] += dp[i-1]; } scanf("%d",&q); while(q--){ int a,b; scanf("%d %d",&a,&b); a++; b++; printf("%d\n",dp[b] - dp[a-1]); } return 0; }/**************************************************************************************** * @author: kzvd4729 created: Mar/28/2021 19:24 * solution_verdict: Accepted language: GNU C++14 * run_time: 62 ms memory_used: 33100 KB * problem: https://codeforces.com/contest/1475/problem/F ****************************************************************************************/ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); const int N=2e5,inf=1e9,mod=998244353; string a[N+2],b[N+2];int cl[N+2]; vector >ad[N+2]; bool dfs(int nd,int c) { if(cl[nd]!=-1) { if(cl[nd]!=c)return false; return true; } cl[nd]=c;bool ret=1; for(auto x:ad[nd])ret&=dfs(x.first,c^x.second); return ret; } int main() { ios_base::sync_with_stdio(0);cin.tie(0); int t;cin>>t; while(t--) { int n;cin>>n; for(int i=1;i<=n;i++)cin>>a[i],a[i]="#"+a[i]; for(int i=1;i<=n;i++)cin>>b[i],b[i]="#"+b[i]; for(int i=1;i<=n+n;i++)ad[i].clear(); for(int i=1;i<=n;i++) { for(int j=1;j<=n;j++) { int cl=1; if(a[i][j]==b[i][j])cl=0; ad[i].push_back({n+j,cl}); ad[n+j].push_back({i,cl}); } } for(int i=1;i<=n+n;i++)cl[i]=-1; if(dfs(1,0))cout<<"YES"< #include "solution.cc" void test() { Solution s; vector v{1, 2, 3, 4, 5, 6, 7}; s.rotate(v, 3); for (auto&& val : v) { std::cout << val << " "; } std::cout << std::endl; } int main() { test(); return 0; }// $Id: Foo_ClientEngine.cpp 76626 2007-01-26 13:50:03Z elliott_c $ #include "Foo_ClientEngine.h" #include "Foo_Statistics.h" #include "TestInf/TestAppExceptionC.h" #include "TestInf/AppHelper.h" #include "ace/Log_Msg.h" Foo_ClientEngine::Foo_ClientEngine(Foo_ptr obj, unsigned client_id) : obj_(Foo::_duplicate(obj)), client_id_(client_id) { } Foo_ClientEngine::~Foo_ClientEngine() { } bool Foo_ClientEngine::execute(unsigned num_loops) { // Make sure the connection is established before making // remote invocations. if (AppHelper::validate_connection(this->obj_.in()) == false) { ACE_ERROR((LM_ERROR, "(%P|%t)Foo_ClientEngine::execute - " "client %d connect failed.\n", this->client_id_)); return false; } // Verify the return values and return the results. bool success = true; for (unsigned loop = 0; loop < num_loops; loop++) { CORBA::Long i = this->client_id_; this->obj_->op1(); this->obj_->op2(i); CORBA::Long value = this->obj_->op3(i); success = (value != i) ? false : success; for (CORBA::Long j = 1; j <= 5; j++) { this->obj_->op4(495 + (i * 5) + j); } bool caught_exception = false; try { this->obj_->op5(); } catch (const FooException&) { // Expected caught_exception = true; } success = (!caught_exception) ? false : success; } this->obj_->done(); return success; } void Foo_ClientEngine::expected_results(Foo_Statistics& stats) { stats.expected(1, 1); stats.expected(2, 1); stats.expected(3, 1); stats.expected(4, 0); stats.expected(4, 5); stats.expected(5, 1); } // Copyright 2020 #include #include #include std::string getFullPath(const std::string& name) { std::string s(__FILE__); for (size_t i = 0; i < 8; ++i) { s.pop_back(); } return s + name; } TEST(Parser, Empty_path) { ASSERT_THROW(Parser(""), std::invalid_argument); } TEST(Parser, Opening_file) { ASSERT_THROW(Parser("my_jso.json"), std::runtime_error); } TEST(Parser, Empty_json) { ASSERT_THROW(Parser(R"({})"), std::invalid_argument); } TEST(Parser, Empty_file) { Parser pars(getFullPath("example_json.json")); std::stringstream str; str << pars; std::string str_example(R"(| name | group | avg | debt | |-----------------|--------|------|--------------| | | IU8-33 | null | C++ | |-----------------|--------|------|--------------| )"); std::vector column_width{19, 9, 7, 15}; std::vector column_name{"name", "group", "avg", "debt"}; ASSERT_EQ(str.str(), str_example); } TEST(Parser, Correct_array) { ASSERT_THROW(Parser(R"({"items": 0})"), std::invalid_argument); } TEST(Parser, Count_items) { ASSERT_THROW(Parser(R"({ "items": [ { "name": "", "group": "1", "avg": "4.25", "debt": null }, { "name": "", "group": 31, "avg": 4, "debt": "C++" } ], "_meta": { "count": 3 } })"), std::out_of_range); } TEST(Parser, correct_output) { Parser pars(getFullPath("my_json.json")); std::stringstream str; str << pars; std::string str_example(R"(| name | group | avg | debt | |---------------|--------|------|--------------| | | 1 | 4.25 | null | |---------------|--------|------|--------------| | | 31 | 4 | C++ | |---------------|--------|------|--------------| | | IU8-31 | 3.33 | 3 items | |---------------|--------|------|--------------| )"); ASSERT_EQ(str.str(), str_example); } TEST(Student, Empty_student) { ASSERT_THROW(Student(json::parse(R"({})")), std::invalid_argument); } TEST(Student, correct_out_name) { ASSERT_THROW(Student(json::parse(R"({ "name": [], "group": "1", "avg": "4.25", "debt": null })")), std::invalid_argument); } TEST(Student, correct_out_group) { ASSERT_THROW(Student(json::parse(R"({ "name": "", "group": [], "avg": 4, "debt": "C++" })")), std::invalid_argument); } TEST(Student, correct_out_avg) { ASSERT_THROW(Student st(json::parse(R"({ "name": "", "group": "IU8-31", "avg": [], "debt": [ "C++", "Linux", "Network" ] })")), std::invalid_argument); } TEST(Student, correct_out_debt) { ASSERT_THROW(Student st(json::parse(R"({ "name": "", "group": 33, "avg": null, "debt": 0 })")), std::invalid_argument); }/** * @file SMALModule.cpp * * @author * @author * @author * Implementation of SMALModule */ #include "SMALModule.h" #include "Tools/NaoTime.h" #include #include using namespace naoth; using namespace std; using namespace AL; // some low level debugging stuff #ifdef DEBUG_SMAL #define LNT current_line=__LINE__ int current_line = 0; #else #define LNT (void)0 #endif // this stuff is necessary to register at the DCM static SMALModule* theModule = NULL; static void motion_wrapper_pre() { assert(theModule != NULL); theModule->motionCallbackPre(); } static void motion_wrapper_post() { assert(theModule != NULL); theModule->motionCallbackPost(); } void* slowDCMCycle(void* ref) { while(true) { SMALModule* smalModule = (SMALModule*)ref; smalModule->slowDcmUpdate(); pthread_yield(); usleep(1000); } return NULL; } SMALModule::SMALModule(boost::shared_ptr pBroker, const std::string& pName ) : ALModule(pBroker, pName), pBroker(pBroker), state(DISCONNECTED), dcmTime(0), timeOffset(0), sem(SEM_FAILED), slowDCM(0), slowDCMupdateCanRun(false), command_data_available(false), sensor_data_available(false), shutdown_requested(false), initialMotion(NULL) { // there should be only one instance of SMALModule assert(theModule == NULL); theModule = this; // setModuleDescription( "Nao Shared Memory Abstraction Layer (NaoSMAL)" "provides access to the HAL functionality of naoqi through shared memory" ); } SMALModule::~SMALModule() { if(shutdownCallbackThread.joinable()) { shutdownCallbackThread.join(); } } std::string SMALModule::version() { return std::string(SMAL_VERSION); } void SMALModule::init() { std::cout << "Init DCMHandler" << endl; std::cout << "resetting working directory to /home/nao/" << std::endl; int retChDir = chdir("/home/nao"); if(retChDir != 0) { std::cerr << "Could not change working directory" << std::endl; } theDCMHandler.init(pBroker); // calculate the difference between the NaoTime and the DcmTime unsigned int delta = 0; dcmTime = theDCMHandler.getTime(delta); timeOffset = dcmTime - NaoTime::getNaoTimeInMilliSeconds(); // save the body ID string theBodyID = theDCMHandler.getBodyID(); std::cout << "bodyID: "<< theBodyID << endl; // save the nick name string theBodyNickName = theDCMHandler.getBodyNickName(); std::cout << "nickName: "<< theBodyNickName << endl; // save the value to file // FIXME: fixed path "Config/nao.info" { string staticMemberPath("Config/nao.info"); ofstream os(staticMemberPath.c_str()); ASSERT(os.good()); os<getProxy("DCM")->getModule()->atPreProcess(motion_wrapper_pre); fDCMPostProcessConnection = getParentBroker()->getProxy("DCM")->getModule()->atPostProcess(motion_wrapper_post); cout << "SMALModule:init finished!" << endl; pthread_create(&slowDCM, 0, slowDCMCycle, (void*)this); }//end init void SMALModule::shutdownCallback() { // play a sound that the user knows we recognized his shutdown request system("/usr/bin/paplay /usr/share/naoqi/wav/bip_gentle.wav"); // stop the user program std::cout << "stopping naoth" << std::endl; system("naoth stop"); sleep(5); // we are the child process, do a blocking call to shutdown system("/sbin/shutdown -h now"); std::cout << "System shutdown requested" << std::endl; // await termination while(true) { sleep(100); } }//end shutdownCallback void SMALModule::slowDcmUpdate() { if(!slowDCMupdateCanRun) { return; } int dcmTime = theDCMHandler.getTime(0); if(naoCommandLEDData.swapReading()) { const Accessor* commandData = naoCommandLEDData.reading(); //theDCMHandler.setSingleLED(commandData->get(), dcmTime); theDCMHandler.setLED(commandData->get(), dcmTime); } // get the UltraSoundSendData from the shared memory and put them to the DCM if (naoCommandUltraSoundSendData.swapReading() ) { const Accessor* commandData = naoCommandUltraSoundSendData.reading(); theDCMHandler.setUltraSoundSend(commandData->get(), dcmTime); } slowDCMupdateCanRun = false; } // we are at the moment shortly before the DCM commands are send to the // USB bus, so put the motion execute stuff here void SMALModule::motionCallbackPre() { #ifdef DEBUG_SMAL long long start = NaoTime::getSystemTimeInMicroSeconds(); counterPre++; if(counterPre == 100) { long long currentPreTime = NaoTime::getSystemTimeInMicroSeconds(); long long delta_cycle = (currentPreTime - lastPreTime)/counterPre; long long delta_execTime = time_motionCallbackPreSum/counterPre; std::cout << "[pre]\t" << delta_cycle <<"\t"<< delta_execTime <* commandData = naoCommandMotorJointData.reading(); theDCMHandler.setAllPositionData(commandData->get(), dcmTime); //stiffness_set = theDCMHandler.setAllHardnessDataSmart(commandData->get(), dcmTime); drop_count = 0; command_data_available = true; } else { if(drop_count == 0) { fprintf(stderr, "libnaoth: dropped comand data.\n"); } // don't count more than 11 drop_count += (drop_count < 11); }//end else // NOTE: the LEDs are only set if stiffness was not set in this cycle // get the LEDData from the shared memory and put them to the DCM // !stiffness_set && /* if(naoCommandLEDData.swapReading()) { const Accessor* commandData = naoCommandLEDData.reading(); //theDCMHandler.setSingleLED(commandData->get(), dcmTime); //theDCMHandler.setLED(commandData->get(), dcmTime); theDCMHandler.lastLEDData = commandData->get(); } theDCMHandler.setLED(theDCMHandler.lastLEDData, dcmTime); // get the UltraSoundSendData from the shared memory and put them to the DCM if (naoCommandUltraSoundSendData.swapReading() ) { const Accessor* commandData = naoCommandUltraSoundSendData.reading(); theDCMHandler.setUltraSoundSend(commandData->get(), dcmTime); } */ #ifdef DEBUG_SMAL long long stop = NaoTime::getSystemTimeInMicroSeconds(); time_motionCallbackPreSum += (int)(stop - start); #endif }//end motionCallbackPre void SMALModule::motionCallbackPost() { #ifdef DEBUG_SMAL long long start = NaoTime::getSystemTimeInMicroSeconds(); counterPost++; if(counterPost == 100) { long long currentPostTime = NaoTime::getSystemTimeInMicroSeconds(); long long delta_cycle = (currentPostTime - lastPostTime)/counterPost; long long delta_execTime = time_motionCallbackPostSum/counterPost; std::cout << "[post]\t" << delta_cycle <<"\t"<< delta_execTime <timeStamp = NaoTime::getSystemTimeInMilliSeconds(); // read the sensory data from DCM to the shared memory theDCMHandler.readSensorData(sensorData->sensorsValue); // check if chest button was pressed as a request to shutdown // each cycle needs 10ms so if the button was pressed for 30 seconds // these are 300 frames sensorData->get(theButtonData); if(!shutdown_requested && theButtonData.numOfFramesPressed[ButtonData::Chest] > 300) { shutdown_requested = true; shutdownCallbackThread = std::thread([this]{this->shutdownCallback();}); } // save the data for the emergency case if(state == DISCONNECTED) { sensorData->get(theInertialSensorData); sensor_data_available = true; } else { sensor_data_available = false; } // push the data to shared memory naoSensorData.swapWriting(); // allow the slow thread to run after all sensor data has been fetched slowDCMupdateCanRun = true; // raise the semaphore: triggers core if(sem != SEM_FAILED) { int sval; if(sem_getvalue(sem, &sval) == 0) { if(sval < 1) { sem_post(sem); if(state == DISCONNECTED) { fprintf(stderr, "libnaoth: I think the core is alive.\n"); } drop_count = 0; state = CONNECTED; } else { if(drop_count == 0) { fprintf(stderr, "libnaoth: dropped sensor data.\n"); } else if(drop_count == 10) { fprintf(stderr, "libnaoth: I think the core is dead.\n"); state = DISCONNECTED; } // don't count more than 11 drop_count += (drop_count < 11); }//end else } else { fprintf(stderr, "libnaoth: I couldn't get value by sem_getvalue.\n"); } }//end if SEM_FAILED #ifdef DEBUG_SMAL long long stop = NaoTime::getSystemTimeInMicroSeconds(); time_motionCallbackPostSum += (int)(stop - start); #endif }//end motionCallbackPost void SMALModule::exit() { cout << "NaoTH is exiting ..." << endl; // close semaphore if(sem != SEM_FAILED) { sem_close(sem); sem = SEM_FAILED; } // close the shared memory naoSensorData.close(); naoCommandMotorJointData.close(); naoCommandUltraSoundSendData.close(); naoCommandLEDData.close(); // set all stiffness to 0 theDCMHandler.setAllHardnessData(0.0, dcmTime); // Remove the call back connection fDCMPreProcessConnection.disconnect(); fDCMPostProcessConnection.disconnect(); cout << "NaoTH exit is finished" << endl; }//end exit void SMALModule::setWarningLED(bool red) { static naoth::LEDData theLEDData; static int count = 0; int begin = ((++count)/10)%10; theLEDData.theMonoLED[LEDData::EarRight0 + begin] = 0; theLEDData.theMonoLED[LEDData::EarLeft0 + begin] = 0; int end = (begin+2)%10; theLEDData.theMonoLED[LEDData::EarRight0 + end] = 1; theLEDData.theMonoLED[LEDData::EarLeft0 + end] = 1; for(int i=0; i* commandData = naoCommandMotorJointData.reading(); initialMotion = new BasicMotion(theMotorJointData, commandData->get(), theInertialSensorData); } setWarningLED(shutdown_requested); }//end if // after reconnect: wait until the init motion is finished if(initialMotion != NULL) { LNT; if(state == CONNECTED && initialMotion->isFinish()) { delete initialMotion; initialMotion = NULL; } else { initialMotion->execute(); theDCMHandler.setAllPositionData(theMotorJointData, dcmTime); theDCMHandler.setAllHardnessDataSmart(theMotorJointData, dcmTime); } }//end if return initialMotion != NULL; }//end runningEmergencyMotion // Copyright 2014 Intel Corporation. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ozone/ui/events/remote_state_change_handler.h" #include "ipc/ipc_sender.h" #include "ozone/ui/public/messages.h" namespace ui { RemoteStateChangeHandler::RemoteStateChangeHandler() : sender_(NULL) { WindowStateChangeHandler::SetInstance(this); IMEStateChangeHandler::SetInstance(this); } RemoteStateChangeHandler::~RemoteStateChangeHandler() { while (!deferred_messages_.empty()) deferred_messages_.pop(); } void RemoteStateChangeHandler::ChannelEstablished(IPC::Sender* sender) { sender_ = sender; while (!deferred_messages_.empty()) { sender_->Send(deferred_messages_.front()); deferred_messages_.pop(); } } void RemoteStateChangeHandler::ChannelDestroyed() { sender_ = NULL; } void RemoteStateChangeHandler::SetWidgetState(unsigned w, ui::WidgetState state, unsigned width, unsigned height) { Send(new WaylandWindow_State(w, state, width, height)); } void RemoteStateChangeHandler::SetWidgetTitle(unsigned w, const base::string16& title) { Send(new WaylandWindow_Title(w, title)); } void RemoteStateChangeHandler::SetWidgetCursor(int cursor_type) { Send(new WaylandWindow_Cursor(cursor_type)); } void RemoteStateChangeHandler::SetWidgetAttributes(unsigned widget, unsigned parent, unsigned x, unsigned y, ui::WidgetType type) { Send(new WaylandWindow_Attributes(widget, parent, x, y, type)); } void RemoteStateChangeHandler::ResetIme() { Send(new WaylandWindow_ImeReset()); } void RemoteStateChangeHandler::ImeCaretBoundsChanged(gfx::Rect rect) { Send(new WaylandWindow_ImeCaretBoundsChanged(rect)); } void RemoteStateChangeHandler::HideInputPanel() { Send(new WaylandWindow_HideInputPanel()); } void RemoteStateChangeHandler::ShowInputPanel() { Send(new WaylandWindow_ShowInputPanel()); } void RemoteStateChangeHandler::Send(IPC::Message* message) { // The GPU process never sends synchronous IPC, so clear the unblock flag. // This ensures the message is treated as a synchronous one and helps preserve // order. Check set_unblock in ipc_messages.h for explanation. message->set_unblock(true); if (!sender_) deferred_messages_.push(message); else sender_->Send(message); } } // namespace ui // -*- C++ -*- // Copyright (C) // For conditions of distribution and use, see files LICENSE.txt or pgfe.hpp #include "pgfe-unit.hpp" #include #include #include #include #include int main(int, char* argv[]) { namespace pgfe = dmitigr::pgfe; using namespace dmitigr::test; using pgfe::to; try { const auto conn = pgfe::test::make_connection(); conn->connect(); conn->set_result_format(pgfe::Data_format::binary); ASSERT(conn->is_connected()); // character { conn->execute("SELECT 'Dima', 'i', $1::character, $2::character", 'm', "a"); auto* r = conn->row(); ASSERT(r); for (std::size_t i = 0; i < r->field_count(); ++i) ASSERT(r->data(i) && r->data(i)->format() == pgfe::Data_format::binary); ASSERT('D' == r->data(0)->bytes()[0]); ASSERT('i' == r->data(1)->bytes()[0]); ASSERT('m' == r->data(2)->bytes()[0]); ASSERT('a' == r->data(3)->bytes()[0]); conn->dismiss_response(); conn->wait_response(); } // smallint { // Caution: note parentheses on expression to type cast! conn->execute("SELECT ($1 - 1)::smallint, $1::smallint", 16384); auto* const r = conn->row(); ASSERT(r); ASSERT(to(r->data(0)) == 16384 - 1); ASSERT(to(r->data(1)) == 16384); conn->dismiss_response(); conn->wait_response(); } // integer { // Caution: note parentheses on expression to type cast.! conn->execute("SELECT (2^31 - 1)::integer, $1::integer", 65536); auto* const r = conn->row(); ASSERT(r); ASSERT(to(r->data(0)) == 2147483647); ASSERT(to(r->data(1)) == 65536); conn->dismiss_response(); conn->wait_response(); } // bigint { constexpr long long n{1000000000000000000}; conn->execute("SELECT (2^60)::bigint, $1::bigint", n); auto* const r = conn->row(); ASSERT(r); ASSERT(to(r->data(0)) == 1152921504606846976); ASSERT(to(r->data(1)) == 1000000000000000000); conn->dismiss_response(); conn->wait_response(); } // float { conn->execute("SELECT 98.765::real, $1::real", float(4.321)); auto* const r = conn->row(); ASSERT(r); const auto float1 = to(r->data(0)); const auto float2 = to(r->data(1)); ASSERT(98 <= float1 && float1 <= 99); ASSERT( 4 <= float2 && float2 <= 5); conn->dismiss_response(); conn->wait_response(); } // double { conn->execute("SELECT 12.345::double precision, $1::double precision", double(67.89)); auto* const r = conn->row(); ASSERT(r); const auto double1 = to(r->data(0)); const auto double2 = to(r->data(1)); ASSERT(12 <= double1 && double1 <= 13); ASSERT(67 <= double2 && double2 <= 68); conn->dismiss_response(); conn->wait_response(); } // text { static const auto st = pgfe::Sql_string::make("SELECT 'dima'::text, :nm1::varchar, :nm2::text"); auto* ps = conn->prepare_statement(st.get()); ps->set_parameter("nm1", "olga"); ps->set_parameter("nm2", "vika"); ps->execute(); auto* const r = conn->row(); ASSERT(r); ASSERT(to(r->data(0)) == "dima"); ASSERT(to(r->data(1)) == "olga"); ASSERT(to(r->data(2)) == "vika"); conn->dismiss_response(); conn->wait_response(); } // boolean { conn->execute("SELECT true, $1::boolean", false); auto* const r = conn->row(); ASSERT(r); ASSERT(to(r->data(0)) == true); ASSERT(to(r->data(1)) == false); conn->dismiss_response(); conn->wait_response(); } } catch (const std::exception& e) { report_failure(argv[0], e); return 1; } catch (...) { report_failure(argv[0]); return 1; } return 0; } /** * @file blend_operation_inl.hpp * * @brief BlendOperation クラスの実装 * * @author myoukaku */ #ifndef BKSGE_CORE_RENDER_D3D11_DETAIL_INL_BLEND_OPERATION_INL_HPP #define BKSGE_CORE_RENDER_D3D11_DETAIL_INL_BLEND_OPERATION_INL_HPP #include #if BKSGE_CORE_RENDER_HAS_D3D11_RENDERER #include #include #include namespace bksge { namespace render { namespace d3d11 { namespace detail { inline ::D3D11_BLEND_OP ToD3D11BlendOperation(bksge::BlendOperation blend_operation) { switch (blend_operation) { case bksge::BlendOperation::kAdd: return D3D11_BLEND_OP_ADD; case bksge::BlendOperation::kSubtract: return D3D11_BLEND_OP_SUBTRACT; case bksge::BlendOperation::kReverseSubtract: return D3D11_BLEND_OP_REV_SUBTRACT; case bksge::BlendOperation::kMin: return D3D11_BLEND_OP_MIN; case bksge::BlendOperation::kMax: return D3D11_BLEND_OP_MAX; } return D3D11_BLEND_OP_ADD; } } // namespace detail BKSGE_INLINE BlendOperation::BlendOperation(bksge::BlendOperation blend_operation) : m_blend_operation(detail::ToD3D11BlendOperation(blend_operation)) {} BKSGE_INLINE BlendOperation::operator ::D3D11_BLEND_OP() const { return m_blend_operation; } } // namespace d3d11 } // namespace render } // namespace bksge #endif // BKSGE_CORE_RENDER_HAS_D3D11_RENDERER #endif // BKSGE_CORE_RENDER_D3D11_DETAIL_INL_BLEND_OPERATION_INL_HPP #include #include "ioproto/istream.hpp" #include "mocktails/metadata.hpp" #include "spdlog/spdlog.h" #include "spdlog/sinks/stdout_sinks.h" #include "argagg.hpp" static constexpr std::uint32_t GEM5_MAGIC_NUMBER = 0x356d6567; argagg::parser create_command_line_interface() { return {{{"help", {"-h", "--help"}, "Display help information.", 0}, {"input", {"-i", "--input"}, "gem5 packet trace.", 1}, {"output", {"-o", "--output"}, "Output file.", 1}}}; } void print_usage(std::ostream &stream, argagg::parser const &arguments) { argagg::fmt_ostream help(stream); help << "Dump an Mocktails model to a csv file.\n\n"; help << "dump-mocktails-profile [options] ARG [ARG...]\n\n"; help << arguments; } void validate(argagg::parser_results const &options) { if(options["input"].count() == 0) { throw std::runtime_error("Missing path to gem5 packet trace."); } if(options["output"].count() == 0) { throw std::runtime_error("Missing path to output file."); } } void dump_to_csv(std::string const &input_filename, std::string const &output_filename) { spdlog::get("log")->info("Loading statistical profile from: {}.", input_filename); std::ifstream file_stream(input_filename); ioproto::istream input(file_stream, GEM5_MAGIC_NUMBER); auto profile = mocktails::read(input); if(profile->type != mocktails::model_type::mocktails) { throw std::runtime_error("model-dumper only works with simple leaves."); } std::ofstream output(output_filename); output << "profile.id,node.id,total,min.address,max.address,start.address,size.states,time." "states,stride.states,op.states\n"; std::size_t profile_id = 0; while(profile != nullptr) { spdlog::get("log")->info( "Successfully loaded statistical profile ({} nodes).", profile->simple_leaves.size()); for(auto const &pair : profile->simple_leaves) { auto const &model = pair.second; output << profile_id << ","; output << pair.first << ","; output << model.request_count << ","; output << model.underlying_model->footprint.start << ","; output << model.underlying_model->footprint.end << ","; output << model.underlying_model->start_address << ","; output << model.size_model.transitions.size() << ","; output << model.time_model.transitions.size() << ","; output << model.underlying_model->stride_model.transitions.size() << ","; output << model.underlying_model->operation_model.transitions.size() << std::endl; } profile_id++; profile = mocktails::read(input); } } int main(int argc, char **argv) { try { // Create the logger. spdlog::stdout_logger_st("log"); // Parse the command line. auto interface = create_command_line_interface(); auto const arguments = interface.parse(argc, argv); // Check if help was requested. if(arguments["help"]) { print_usage(std::cout, interface); return EXIT_SUCCESS; } // Make sure we have the required arguments. validate(arguments); auto const input_filename = arguments["input"].as(); auto const output_filename = arguments["output"].as(); dump_to_csv(input_filename, output_filename); } catch(std::exception const &e) { spdlog::get("log")->error("{}", e.what()); return EXIT_FAILURE; } return EXIT_SUCCESS; } /* Copyright 2001, 2019 IBM Corporation * * 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. * * 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. */ #define charge14scale 0.833333333333333 #define ChargeConversion SciConst::AmberChargeConversion #define TimeConversionFactor SciConst::AmberTimeConversion struct LennardJonesForce_Params { double epsilon; double sigma; }; struct StdHarmonicBondForce_Params { double k; double r0; }; struct StdHarmonicAngleForce_Params { double k; double th0; }; struct OPLSTorsionForce_Params { double cosDelta; double k; double sinDelta; int n; }; class MDProblemSpec { public: static const UdfInvocation UdfInvocationTable[]; static const int UdfInvocationTableSize; static const int SizeOfParams[]; static const SiteInfo SiteInformation[]; static const int SiteInformationSize; static const int SiteIDtoSiteTypeMap[]; static const int SiteIDtoSiteTypeMapSize; static const int SiteIDtoFragmentIDMap[]; static const int SiteIDtoFragmentIDMapSize; static const LennardJonesForce_Params LJPairs[]; static const int LJPairsSize; static const LennardJonesForce_Params LJ14Pairs[]; static const int LJ14PairsSize; static const ExcludedPair14 Pair14List[]; static const int Pair14ListSize; static const ExcludedPair14 ExcludedList[]; static const int ExcludedListSize; static const IrreduciblePartition IrreduciblePartitionList[]; static const int IrreduciblePartitionListSize; static const int IrreduciblePartitionCount; static int StdHarmonicBondForce_sites[]; static StdHarmonicBondForce_Params StdHarmonicBondForceParamTupleTable[]; static int StdHarmonicAngleForce_sites[]; static StdHarmonicAngleForce_Params StdHarmonicAngleForceParamTupleTable[]; static int OPLSTorsionForce_sites[]; static OPLSTorsionForce_Params OPLSTorsionForceParamTupleTable[]; }; /* The parameters are in the order of the structs above. */ StdHarmonicBondForce_Params MDProblemSpec::StdHarmonicBondForceParamTupleTable[] = { { 3.40000000E+02 , 1.09000000E+00} , { 3.40000000E+02 , 1.09000000E+00} , { 3.40000000E+02 , 1.09000000E+00} , { 3.40000000E+02 , 1.09000000E+00} , { 3.40000000E+02 , 1.09000000E+00} , { 3.40000000E+02 , 1.09000000E+00} , { 3.40000000E+02 , 1.09000000E+00} , { 4.34000000E+02 , 1.01000000E+00} , { 3.40000000E+02 , 1.09000000E+00} , { 3.40000000E+02 , 1.09000000E+00} , { 3.40000000E+02 , 1.09000000E+00} , { 4.34000000E+02 , 1.01000000E+00} , { 5.70000000E+02 , 1.22900000E+00} , { 4.90000000E+02 , 1.33500000E+00} , { 3.17000000E+02 , 1.52200000E+00} , { 5.70000000E+02 , 1.22900000E+00} , { 4.90000000E+02 , 1.33500000E+00} , { 3.10000000E+02 , 1.52600000E+00} , { 3.17000000E+02 , 1.52200000E+00} , { 3.37000000E+02 , 1.44900000E+00} , { 3.37000000E+02 , 1.44900000E+00} }; /* These are the sites. */ int MDProblemSpec::StdHarmonicBondForce_sites[] = { 1,2 , 1,3 , 0,1 , 10,11 , 10,12 , 10,13 , 8,9 , 6,7 , 18,19 , 18,20 , 18,21 , 16,17 , 4,5 , 4,6 , 1,4 , 14,15 , 14,16 , 8,10 , 8,14 , 6,8 , 16,18}; /* The parameters are in the order of the structs above. */ StdHarmonicAngleForce_Params MDProblemSpec::StdHarmonicAngleForceParamTupleTable[] = { { 3.00000000E+01 , (120*Math::Deg2Rad)} , { 5.00000000E+01 , (109.5*Math::Deg2Rad)} , { 3.50000000E+01 , (109.5*Math::Deg2Rad)} , { 5.00000000E+01 , (109.5*Math::Deg2Rad)} , { 3.50000000E+01 , (109.5*Math::Deg2Rad)} , { 3.50000000E+01 , (109.5*Math::Deg2Rad)} , { 5.00000000E+01 , (109.5*Math::Deg2Rad)} , { 3.00000000E+01 , (120*Math::Deg2Rad)} , { 3.50000000E+01 , (109.5*Math::Deg2Rad)} , { 3.50000000E+01 , (109.5*Math::Deg2Rad)} , { 3.50000000E+01 , (109.5*Math::Deg2Rad)} , { 5.00000000E+01 , (109.5*Math::Deg2Rad)} , { 5.00000000E+01 , (109.5*Math::Deg2Rad)} , { 5.00000000E+01 , (109.5*Math::Deg2Rad)} , { 5.00000000E+01 , (109.5*Math::Deg2Rad)} , { 5.00000000E+01 , (109.5*Math::Deg2Rad)} , { 3.00000000E+01 , (118.039999885408*Math::Deg2Rad)} , { 5.00000000E+01 , (109.5*Math::Deg2Rad)} , { 3.50000000E+01 , (109.5*Math::Deg2Rad)} , { 3.50000000E+01 , (109.5*Math::Deg2Rad)} , { 3.50000000E+01 , (109.5*Math::Deg2Rad)} , { 3.00000000E+01 , (118.039999885408*Math::Deg2Rad)} , { 5.00000000E+01 , (109.5*Math::Deg2Rad)} , { 5.00000000E+01 , (109.5*Math::Deg2Rad)} , { 5.00000000E+01 , (109.5*Math::Deg2Rad)} , { 8.00000000E+01 , (122.9*Math::Deg2Rad)} , { 5.00000000E+01 , (121.9*Math::Deg2Rad)} , { 8.00000000E+01 , (120.4*Math::Deg2Rad)} , { 7.00000000E+01 , (116.6*Math::Deg2Rad)} , { 8.00000000E+01 , (122.9*Math::Deg2Rad)} , { 5.00000000E+01 , (121.9*Math::Deg2Rad)} , { 6.30000000E+01 , (111.1*Math::Deg2Rad)} , { 8.00000000E+01 , (120.4*Math::Deg2Rad)} , { 7.00000000E+01 , (116.6*Math::Deg2Rad)} , { 8.00000000E+01 , (109.7*Math::Deg2Rad)} , { 6.30000000E+01 , (110.1*Math::Deg2Rad)} }; /* These are the sites. */ int MDProblemSpec::StdHarmonicAngleForce_sites[] = { 4,6,7 , 3,1,4 , 2,1,3 , 2,1,4 , 0,1,2 , 0,1,3 , 0,1,4 , 14,16,17 , 12,10,13 , 11,10,12 , 11,10,13 , 9,8,10 , 9,8,14 , 8,10,11 , 8,10,12 , 8,10,13 , 7,6,8 , 6,8,9 , 20,18,21 , 19,18,20 , 19,18,21 , 17,16,18 , 16,18,19 , 16,18,20 , 16,18,21 , 5,4,6 , 4,6,8 , 1,4,5 , 1,4,6 , 15,14,16 , 14,16,18 , 10,8,14 , 8,14,15 , 8,14,16 , 6,8,10 , 6,8,14}; /* The parameters are in the order of the structs above. */ OPLSTorsionForce_Params MDProblemSpec::OPLSTorsionForceParamTupleTable[] = { { cos(0*Math::Deg2Rad) , 2.00000000E+00 , sin(0*Math::Deg2Rad) , 1.00000000E+00} , { cos(180*Math::Deg2Rad) , 2.50000000E+00 , sin(180*Math::Deg2Rad) , 2.00000000E+00} , { cos(180*Math::Deg2Rad) , 2.50000000E+00 , sin(180*Math::Deg2Rad) , 2.00000000E+00} , { cos(0*Math::Deg2Rad) , 2.00000000E+00 , sin(0*Math::Deg2Rad) , 1.00000000E+00} , { cos(180*Math::Deg2Rad) , 2.50000000E+00 , sin(180*Math::Deg2Rad) , 2.00000000E+00} , { cos(0*Math::Deg2Rad) , 1.55555556E-01 , sin(0*Math::Deg2Rad) , 3.00000000E+00} , { cos(0*Math::Deg2Rad) , 1.55555556E-01 , sin(0*Math::Deg2Rad) , 3.00000000E+00} , { cos(0*Math::Deg2Rad) , 1.55555556E-01 , sin(0*Math::Deg2Rad) , 3.00000000E+00} , { cos(0*Math::Deg2Rad) , 1.55555556E-01 , sin(0*Math::Deg2Rad) , 3.00000000E+00} , { cos(0*Math::Deg2Rad) , 1.55555556E-01 , sin(0*Math::Deg2Rad) , 3.00000000E+00} , { cos(0*Math::Deg2Rad) , 1.55555556E-01 , sin(0*Math::Deg2Rad) , 3.00000000E+00} , { cos(180*Math::Deg2Rad) , 2.50000000E+00 , sin(180*Math::Deg2Rad) , 2.00000000E+00} , { cos(0*Math::Deg2Rad) , 1.55555556E-01 , sin(0*Math::Deg2Rad) , 3.00000000E+00} , { cos(0*Math::Deg2Rad) , 1.55555556E-01 , sin(0*Math::Deg2Rad) , 3.00000000E+00} , { cos(0*Math::Deg2Rad) , 1.55555556E-01 , sin(0*Math::Deg2Rad) , 3.00000000E+00} , { cos(180*Math::Deg2Rad) , 2.50000000E+00 , sin(180*Math::Deg2Rad) , 2.00000000E+00} , { cos(0*Math::Deg2Rad) , 5.30000000E-01 , sin(0*Math::Deg2Rad) , 1.00000000E+00} , { cos(180*Math::Deg2Rad) , 1.50000000E-01 , sin(180*Math::Deg2Rad) , 3.00000000E+00} , { cos(180*Math::Deg2Rad) , 5.00000000E-01 , sin(180*Math::Deg2Rad) , 4.00000000E+00} , { cos(180*Math::Deg2Rad) , 2.00000000E-01 , sin(180*Math::Deg2Rad) , 2.00000000E+00} , { cos(180*Math::Deg2Rad) , 2.50000000E+00 , sin(180*Math::Deg2Rad) , 2.00000000E+00} , { cos(180*Math::Deg2Rad) , 2.50000000E+00 , sin(180*Math::Deg2Rad) , 2.00000000E+00} , { cos(0*Math::Deg2Rad) , 7.00000000E-02 , sin(0*Math::Deg2Rad) , 2.00000000E+00} , { cos(0*Math::Deg2Rad) , 1.00000000E-01 , sin(0*Math::Deg2Rad) , 4.00000000E+00} , { cos(180*Math::Deg2Rad) , 2.50000000E+00 , sin(180*Math::Deg2Rad) , 2.00000000E+00} , { cos(180*Math::Deg2Rad) , 7.50000000E-01 , sin(180*Math::Deg2Rad) , 1.00000000E+00} , { cos(180*Math::Deg2Rad) , 1.35000000E+00 , sin(180*Math::Deg2Rad) , 2.00000000E+00} , { cos(180*Math::Deg2Rad) , 4.00000000E-01 , sin(180*Math::Deg2Rad) , 4.00000000E+00} , { cos(180*Math::Deg2Rad) , 1.00000000E+00 , sin(180*Math::Deg2Rad) , 2.00000000E+00} , { cos(180*Math::Deg2Rad) , 1.00000000E+00 , sin(180*Math::Deg2Rad) , 2.00000000E+00} , { cos(180*Math::Deg2Rad) , 1.05000000E+01 , sin(180*Math::Deg2Rad) , 2.00000000E+00} , { cos(180*Math::Deg2Rad) , 1.05000000E+01 , sin(180*Math::Deg2Rad) , 2.00000000E+00} }; /* These are the sites. */ int MDProblemSpec::OPLSTorsionForce_sites[] = { 5,4,6,7 , 5,4,6,7 , 1,4,6,7 , 15,14,16,17 , 15,14,16,17 , 13,10,8,14 , 12,10,8,14 , 11,10,8,14 , 9,8,10,11 , 9,8,10,12 , 9,8,10,13 , 8,14,16,17 , 6,8,10,11 , 6,8,10,12 , 6,8,10,13 , 5,4,6,8 , 4,6,8,10 , 4,6,8,10 , 4,6,8,10 , 4,6,8,14 , 1,4,6,8 , 15,14,16,18 , 10,8,14,16 , 10,8,14,16 , 8,14,16,18 , 6,8,14,16 , 6,8,14,16 , 6,8,14,16 , 4,8,6,7 , 14,18,16,17 , 1,6,4,5 , 8,16,14,15}; /* UdfCode, size of tupleList, siteTupleListPtr, paramTupleListPtr */ const UdfInvocation MDProblemSpec::UdfInvocationTable[] = { { 1 , 21 , (int*) StdHarmonicBondForce_sites , (void*)StdHarmonicBondForceParamTupleTable }, { 2 , 36 , (int*) StdHarmonicAngleForce_sites , (void*)StdHarmonicAngleForceParamTupleTable }, { 5 , 32 , (int*) OPLSTorsionForce_sites , (void*)OPLSTorsionForceParamTupleTable } }; const int MDProblemSpec::UdfInvocationTableSize = 3; const int MDProblemSpec::SizeOfParams[] = { sizeof( StdHarmonicBondForce_Params ), sizeof( StdHarmonicAngleForce_Params ), sizeof( OPLSTorsionForce_Params )}; /* Indexed by site type = { mass, halfInverseMass, charge, lj_type, lj_14_type }; */ const SiteInfo MDProblemSpec::SiteInformation[] = { { 1.008 , 1.0/(2.0 * 1.008) , ( 0.0603*ChargeConversion) , 0 , 0 }, { 1.008 , 1.0/(2.0 * 1.008) , ( 0.0823*ChargeConversion) , 6 , 6 }, { 1.008 , 1.0/(2.0 * 1.008) , ( 0.0976*ChargeConversion) , 6 , 6 }, { 1.008 , 1.0/(2.0 * 1.008) , ( 0.1123*ChargeConversion) , 0 , 0 }, { 1.008 , 1.0/(2.0 * 1.008) , ( 0.2719*ChargeConversion) , 5 , 5 }, { 12.01 , 1.0/(2.0 * 12.01) , ( 0.0337*ChargeConversion) , 1 , 1 }, { 12.01 , 1.0/(2.0 * 12.01) , ( 0.5972*ChargeConversion) , 2 , 2 }, { 12.01 , 1.0/(2.0 * 12.01) , ( 0.5973*ChargeConversion) , 2 , 2 }, { 12.01 , 1.0/(2.0 * 12.01) , ( -0.1490*ChargeConversion) , 1 , 1 }, { 12.01 , 1.0/(2.0 * 12.01) , ( -0.1825*ChargeConversion) , 1 , 1 }, { 12.01 , 1.0/(2.0 * 12.01) , ( -0.3662*ChargeConversion) , 1 , 1 }, { 14.01 , 1.0/(2.0 * 14.01) , ( -0.4157*ChargeConversion) , 4 , 4 }, { 16 , 1.0/(2.0 * 16) , ( -0.5679*ChargeConversion) , 3 , 3 } }; const int MDProblemSpec::SiteInformationSize = 13; /* Mapping from SiteId to site type. */ const int MDProblemSpec::SiteIDtoSiteTypeMap[] = { 3, 10, 3, 3, 6, 12, 11, 4, 5, 1, 9, 0, 0, 0, 7, 12, 11, 4, 8, 2, 2, 2}; const int MDProblemSpec::SiteIDtoSiteTypeMapSize = 22; /* Every site is in its own fragment */ const int MDProblemSpec::SiteIDtoFragmentIDMap[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21}; const int MDProblemSpec::SiteIDtoFragmentIDMapSize = 22; /* An array of LJ Pairs */ const LennardJonesForce_Params MDProblemSpec::LJPairs[] = { {0.0157000000262363 , 2.64953278726022}, {0.0414436968131308 , 3.02460114765057}, {0.109399999915728 , 3.39966950845074}, {0.0367450679577815 , 3.02460114621455}, {0.0969969070897875 , 3.39966950874072}, {0.0860000001283588 , 3.39966950794483}, {0.0574195093096127 , 2.80472734282863}, {0.151571765093351 , 3.17979570475948}, {0.134387499166528 , 3.17979570537529}, {0.209999999841822 , 2.95992190164469}, {0.0516623653716887 , 2.94976565593296}, {0.136374484426501 , 3.32483401597941}, {0.120913192035741 , 3.32483401597788}, {0.188944436449698 , 3.1049602120171}, {0.169999999917667 , 3.24999852403104}, {0.0156999999538954 , 1.85930562583042}, {0.0414436967992371 , 2.23437398498119}, {0.0367450677667984 , 2.23437398514522}, {0.0574195087769978 , 2.01450018167939}, {0.0516623656705171 , 2.15953849182152}, {0.0157000000042192 , 1.06907846172052}, {0.0156999999806046 , 2.56044291633196}, {0.041443696532826 , 2.93551127765429}, {0.0367450677213321 , 2.93551127615256}, {0.0574195088474234 , 2.71563747302357}, {0.0516623650350694 , 2.86067578549896}, {0.0156999999963813 , 1.77021575302184}, {0.0157000000984614 , 2.47135304264217} }; const int MDProblemSpec::LJPairsSize = 28; /* An array of LJ 1-4 Pairs */ const LennardJonesForce_Params MDProblemSpec::LJ14Pairs[] = { {0.00785000001311814 , 2.64953278726022}, {0.0207218484065654 , 3.02460114765057}, {0.0546999999578639 , 3.39966950845074}, {0.0183725339788908 , 3.02460114621455}, {0.0484984535448938 , 3.39966950874072}, {0.0430000000641794 , 3.39966950794483}, {0.0287097546548063 , 2.80472734282863}, {0.0757858825466753 , 3.17979570475948}, {0.067193749583264 , 3.17979570537529}, {0.104999999920911 , 2.95992190164469}, {0.0258311826858444 , 2.94976565593296}, {0.0681872422132505 , 3.32483401597941}, {0.0604565960178706 , 3.32483401597788}, {0.0944722182248489 , 3.1049602120171}, {0.0849999999588335 , 3.24999852403104}, {0.00784999997694769 , 1.85930562583042}, {0.0207218483996185 , 2.23437398498119}, {0.0183725338833992 , 2.23437398514522}, {0.0287097543884989 , 2.01450018167939}, {0.0258311828352586 , 2.15953849182152}, {0.00785000000210962 , 1.06907846172052}, {0.00784999999030228 , 2.56044291633196}, {0.020721848266413 , 2.93551127765429}, {0.0183725338606661 , 2.93551127615256}, {0.0287097544237117 , 2.71563747302357}, {0.0258311825175347 , 2.86067578549896}, {0.00784999999819067 , 1.77021575302184}, {0.00785000004923071 , 2.47135304264217} }; const int MDProblemSpec::LJ14PairsSize = 28; const ExcludedPair14 MDProblemSpec::Pair14List[] = { { 0 , 5 }, { 0 , 6 }, { 1 , 7 }, { 1 , 8 }, { 2 , 5 }, { 2 , 6 }, { 3 , 5 }, { 3 , 6 }, { 4 , 9 }, { 4 , 10 }, { 4 , 14 }, { 5 , 7 }, { 5 , 8 }, { 6 , 11 }, { 6 , 12 }, { 6 , 13 }, { 6 , 15 }, { 6 , 16 }, { 7 , 9 }, { 7 , 10 }, { 7 , 14 }, { 8 , 17 }, { 8 , 18 }, { 9 , 11 }, { 9 , 12 }, { 9 , 13 }, { 9 , 15 }, { 9 , 16 }, { 10 , 15 }, { 10 , 16 }, { 11 , 14 }, { 12 , 14 }, { 13 , 14 }, { 14 , 19 }, { 14 , 20 }, { 14 , 21 }, { 15 , 17 }, { 15 , 18 }, { 17 , 19 }, { 17 , 20 }, { 17 , 21 } }; const int MDProblemSpec::Pair14ListSize = 41; const ExcludedPair14 MDProblemSpec::ExcludedList[] = { { 0 , 1 }, { 0 , 2 }, { 0 , 3 }, { 0 , 4 }, { 1 , 2 }, { 1 , 3 }, { 1 , 4 }, { 1 , 5 }, { 1 , 6 }, { 2 , 3 }, { 2 , 4 }, { 3 , 4 }, { 4 , 5 }, { 4 , 6 }, { 4 , 7 }, { 4 , 8 }, { 5 , 6 }, { 6 , 7 }, { 6 , 8 }, { 6 , 9 }, { 6 , 10 }, { 6 , 14 }, { 7 , 8 }, { 8 , 9 }, { 8 , 10 }, { 8 , 11 }, { 8 , 12 }, { 8 , 13 }, { 8 , 14 }, { 8 , 15 }, { 8 , 16 }, { 9 , 10 }, { 9 , 14 }, { 10 , 11 }, { 10 , 12 }, { 10 , 13 }, { 10 , 14 }, { 11 , 12 }, { 11 , 13 }, { 12 , 13 }, { 14 , 15 }, { 14 , 16 }, { 14 , 17 }, { 14 , 18 }, { 15 , 16 }, { 16 , 17 }, { 16 , 18 }, { 16 , 19 }, { 16 , 20 }, { 16 , 21 }, { 17 , 18 }, { 18 , 19 }, { 18 , 20 }, { 18 , 21 }, { 19 , 20 }, { 19 , 21 }, { 20 , 21 } }; const int MDProblemSpec::ExcludedListSize = 57; // All sites/molecules in one fragment const IrreduciblePartition MDProblemSpec::IrreduciblePartitionList[] = { { 0 , 0 , 22} }; const int MDProblemSpec::IrreduciblePartitionListSize = 1; const int MDProblemSpec::IrreduciblePartitionCount = 1; #define COMPONENT ace_viv #define COMPONENT_BEAUTIFIED ACE_VIV #include "\z\vtx\addons\main\script_mod.hpp" // #define DEBUG_MODE_FULL // #define DISABLE_COMPILE_CACHE // #define CBA_DEBUG_SYNCHRONOUS // #define ENABLE_PERFORMANCE_COUNTERS #ifdef DEBUG_ENABLED_ACE_VIV #define DEBUG_MODE_FULL #endif #ifdef DEBUG_SETTINGS_ACE_VIV #define DEBUG_SETTINGS DEBUG_SETTINGS_ACE_VIV #endif #include "\z\vtx\addons\main\script_macros.hpp" fangguanya/newton-dynamics /* Copyright (c) <2003-2016> * * 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 */ #include "toolbox_stdafx.h" #include "SkyBox.h" #include "DemoMesh.h" #include "DemoCamera.h" #include "PhysicsUtils.h" #include "TargaToOpenGl.h" #include "DemoEntityManager.h" #include "DebugDisplay.h" #include "HeightFieldPrimitive.h" enum dRigType { m_root, m_bone, }; struct dSkeletonRigDefinition { const char* m_name; dRigType m_type; }; static dSkeletonRigDefinition inverseKinematicsRidParts[] = { { "mixamorig:Hips", m_root}, { "mixamorig:RightUpLeg", m_bone}, { "mixamorig:LeftUpLeg", m_bone}, // { "mixamorig:RightLeg" }, // { "mixamorig:RightFoot" }, // { "mixamorig:RightToeBase" }, // { "mixamorig:RightToe_End" }, // { "mixamorig:LeftLeg" }, // { "mixamorig:LeftFoot" }, // { "mixamorig:LeftToeBase" }, // { "mixamorig:LeftToe_End" }, // { "mixamorig:Spine" }, // { "mixamorig:Spine1" }, // { "mixamorig:Spine2" }, // { "mixamorig:RightShoulder" }, // { "mixamorig:RightArm" }, // { "mixamorig:RightForeArm" }, // { "mixamorig:RightHand" }, // { "mixamorig:LeftShoulder" }, // { "mixamorig:LeftArm" }, // { "mixamorig:LeftForeArm" }, // { "mixamorig:LeftHand" }, // { "mixamorig:Neck" }, // { "mixamorig:Head" }, // { "mixamorig:HeadTop_End" }, }; #if 0 class InverseKinematicAnimationManager: public dAnimIKManager { public: /* class dAnimCharacterUserData: public DemoEntity::UserData { public: dAnimCharacterUserData(dAnimIKController* const controller) :DemoEntity::UserData() ,m_controller(controller) // ,m_walk(walk) // ,m_posture(posture) // ,m_hipHigh(0.0f) // ,m_walkSpeed(0.0f) { } void OnRender(dFloat timestep) const { } dAnimIKController* m_controller; //dAnimIKController* m_rig; //dAnimationEffectorBlendTwoWay* m_walk; //dAnimationBipeHipController* m_posture; //dFloat m_hipHigh; //dFloat m_walkSpeed; }; */ InverseKinematicAnimationManager(DemoEntityManager* const scene) :dAnimIKManager(scene->GetNewton()) ,m_currentRig(NULL) { scene->Set2DDisplayRenderFunction(RenderHelpMenu, NULL, this); } ~InverseKinematicAnimationManager() { while (m_animCache) { dAnimTakeData* const data = m_animCache.GetRoot()->GetInfo(); data->Release(); m_animCache.Remove(m_animCache.GetRoot()); } } static void RenderHelpMenu(DemoEntityManager* const scene, void* const context) { /* InverseKinematicAnimationManager* const me = (InverseKinematicAnimationManager*)context; if (me->m_currentRig) { DemoEntity* const entiry = (DemoEntity*)NewtonBodyGetUserData(me->m_currentRig->GetNewtonBody()); dAnimationCharacterUserData* const controlData = (dAnimationCharacterUserData*)entiry->GetUserData(); dVector color(1.0f, 1.0f, 0.0f, 0.0f); scene->Print(color, "Sliders control"); dFloat32 val0 = dFloat32(controlData->m_walkSpeed); ImGui::SliderFloat_DoubleSpace("walkSpeed", &val0, 0.0f, 1.0f); controlData->m_walkSpeed = val0; dFloat32 val1 = dFloat32(controlData->m_hipHigh); ImGui::SliderFloat_DoubleSpace("hip high", &val1, -0.5f, 1.5f); controlData->m_hipHigh = val1; } */ } void OnDebug(dCustomJoint::dDebugDisplay* const debugContext) { dAnimIKManager::OnDebug(debugContext); //for (dListNode* node = GetFirst(); node; node = node->GetNext()) { // dSixAxisController* const controller = &node->GetInfo(); // controller->Debug(debugContext); //} } /* DemoEntity* FindMesh(const DemoEntity* const bodyPart) const { for (DemoEntity* child = bodyPart->GetChild(); child; child = child->GetSibling()) { if (child->GetMesh()) { return child; } } dAssert(0); return NULL; } NewtonCollision* MakeConvexHull(const DemoEntity* const bodyPart) const { dVector points[1024 * 16]; const DemoEntity* const meshEntity = FindMesh(bodyPart); DemoMesh* const mesh = (DemoMesh*)meshEntity->GetMesh(); dAssert(mesh->IsType(DemoMesh::GetRttiType())); dAssert(mesh->m_vertexCount && (mesh->m_vertexCount < int(sizeof(points) / sizeof(points[0])))); // go over the vertex array and find and collect all vertices's weighted by this bone. const dFloat* const array = mesh->m_vertex; for (int i = 0; i < mesh->m_vertexCount; i++) { points[i][0] = array[i * 3 + 0]; points[i][1] = array[i * 3 + 1]; points[i][2] = array[i * 3 + 2]; points[i][3] = 0.0f; } dMatrix matrix(meshEntity->GetMeshMatrix()); matrix = matrix * meshEntity->GetCurrentMatrix(); //matrix = matrix * bodyPart->GetParent()->GetCurrentMatrix(); matrix.TransformTriplex(&points[0][0], sizeof(dVector), &points[0][0], sizeof(dVector), mesh->m_vertexCount); //return NewtonCreateConvexHull(GetWorld(), mesh->m_vertexCount, &points[0][0], sizeof(dVector), 1.0e-3f, SERVO_VEHICLE_DEFINITION::m_bodyPart, NULL); return NewtonCreateConvexHull(GetWorld(), mesh->m_vertexCount, &points[0][0], sizeof(dVector), 1.0e-3f, 0, NULL); } NewtonBody* CreateBodyPart(DemoEntity* const bodyPart, const dRagDollConfig& definition) { NewtonCollision* const shape = MakeConvexHull(bodyPart); // calculate the bone matrix dMatrix matrix(bodyPart->CalculateGlobalMatrix()); NewtonWorld* const world = GetWorld(); // create the rigid body that will make this bone NewtonBody* const body = NewtonCreateDynamicBody(world, shape, &matrix[0][0]); // destroy the collision helper shape NewtonDestroyCollision(shape); // get the collision from body NewtonCollision* const collision = NewtonBodyGetCollision(body); // calculate the moment of inertia and the relative center of mass of the solid NewtonBodySetMassProperties(body, definition.m_mass, collision); // save the user lifterData with the bone body (usually the visual geometry) NewtonBodySetUserData(body, bodyPart); // assign a body part id //NewtonCollisionSetUserID(collision, definition.m_bodyPartID); // set the bod part force and torque call back to the gravity force, skip the transform callback NewtonBodySetForceAndTorqueCallback(body, PhysicsApplyGravityForce); return body; } void OnUpdateTransform(const dAnimIDRigJoint* const bone, const dMatrix& localMatrix) const { DemoEntityManager* const scene = (DemoEntityManager*)NewtonWorldGetUserData(GetWorld()); NewtonBody* const newtonBody = bone->GetNewtonBody(); DemoEntity* const meshEntity = (DemoEntity*)NewtonBodyGetUserData(newtonBody); dQuaternion rot(localMatrix); meshEntity->SetMatrix(*scene, rot, localMatrix.m_posit); } */ void UpdatePlayer(dAnimIKController* const controller, dFloat timestep) { DemoEntityManager* const scene = (DemoEntityManager*)NewtonWorldGetUserData(GetWorld()); dAnimIKManager::UpdatePlayer(controller, timestep); // const dAnimPose& pose = controller->GetBasePose(); const dAnimPose& pose = controller->GetAnimationTree()->GetPose(); for (dAnimPose::dListNode* node = pose.GetFirst(); node; node = node->GetNext()) { const dAnimKeyframe& frame = node->GetInfo(); DemoEntity* const entity = (DemoEntity*)frame.m_userData; //if ( //(entity->GetName() == "mixamorig:Hips") || //(entity->GetName() == "mixamorig:RightUpLeg") || //(entity->GetName() == "mixamorig:RightLeg") || //(entity->GetName() == "mixamorig:RightFoot") || //(entity->GetName() == "mixamorig:RightToeBase") || //(entity->GetName() == "mixamorig:LeftLeg") || //(entity->GetName() == "mixamorig:LeftUpLeg") || //(entity->GetName() == "mixamorig:LeftShoulder") || //(entity->GetName() == "mixamorig:Spine1") || //(entity->GetName() == "Bone002") || //(entity->GetName() == "xxxxxxxx")) //{ //dVector euler0; //dVector euler1; //dMatrix xxxx(frame.m_rotation, frame.m_posit); //xxxx.GetEulerAngles(euler0, euler1); //euler0 = euler0.Scale(dRadToDegree); //dTrace(("%s %f %f %f\n", entity->GetName().GetStr(), euler0.m_x, euler0.m_y, euler0.m_z)); //frame.m_rotation = dQuaternion (dYawMatrix(15.0f * dDegreeToRad)) * frame.m_rotation; entity->SetMatrix(*scene, frame.m_rotation, frame.m_posit); //} } } void PreUpdate(dFloat timestep) { /* if (m_currentRig) { DemoEntity* const entiry = (DemoEntity*)NewtonBodyGetUserData(m_currentRig->GetNewtonBody()); dAnimationCharacterUserData* const controlData = (dAnimationCharacterUserData*)entiry->GetUserData(); dAnimationEffectorBlendTwoWay* const walkBlend = controlData->m_walk; walkBlend->SetParam(controlData->m_walkSpeed); dAnimationBipeHipController* const posture = controlData->m_posture; posture->m_position.m_y = 0.25f * controlData->m_hipHigh; } */ dAnimIKManager::PreUpdate(timestep); } dAnimTakeData* LoadAnimation(dAnimIKController* const controller, const char* const animName) { dTree::dTreeNode* cachedAnimNode = m_animCache.Find(animName); if (!cachedAnimNode) { dScene scene(GetWorld()); char pathName[2048]; dGetWorkingFileName(animName, pathName); scene.Deserialize(pathName); dScene::dTreeNode* const animTakeNode = scene.FindChildByType(scene.GetRootNode(), dAnimationTake::GetRttiType()); if (animTakeNode) { dTree map; const dAnimPose& basePose = controller->GetBasePose(); dAnimTakeData* const animdata = new dAnimTakeData(basePose.GetCount()); dAnimationTake* const animTake = (dAnimationTake*)scene.GetInfoFromNode(animTakeNode); animdata->SetPeriod(animTake->GetPeriod()); cachedAnimNode = m_animCache.Insert(animdata, animName); dList& tracks = animdata->GetTracks(); dList::dListNode* ptr = tracks.GetFirst(); for (dAnimPose::dListNode* ptrNode = basePose.GetFirst(); ptrNode; ptrNode = ptrNode->GetNext()) { DemoEntity* const entity = (DemoEntity*)ptrNode->GetInfo().m_userData; map.Insert(&ptr->GetInfo(), entity->GetName()); ptr = ptr->GetNext(); } for (void* link = scene.GetFirstChildLink(animTakeNode); link; link = scene.GetNextChildLink(animTakeNode, link)) { dScene::dTreeNode* const node = scene.GetNodeFromLink(link); dAnimationTrack* const srcTrack = (dAnimationTrack*)scene.GetInfoFromNode(node); if (srcTrack->IsType(dAnimationTrack::GetRttiType())) { dTree::dTreeNode* const ptrNode = map.Find(srcTrack->GetName()); dAssert(ptrNode); dAnimTakeData::dAnimTakeTrack* const dstTrack = ptrNode->GetInfo(); const dList& rotations = srcTrack->GetRotations(); dstTrack->m_rotation.Resize(rotations.GetCount()); int index = 0; for (dList::dListNode* node = rotations.GetFirst(); node; node = node->GetNext()) { dAnimationTrack::dCurveValue keyFrame (node->GetInfo()); dMatrix matrix(dPitchMatrix(keyFrame.m_x) * dYawMatrix(keyFrame.m_y) * dRollMatrix(keyFrame.m_z)); dQuaternion rot(matrix); dstTrack->m_rotation[index].m_rotation = rot; dstTrack->m_rotation[index].m_time = keyFrame.m_time; index++; } for (int i = 0; i < rotations.GetCount() - 1; i++) { dFloat dot = dstTrack->m_rotation[i].m_rotation.DotProduct(dstTrack->m_rotation[i + 1].m_rotation); if (dot < 0.0f) { dstTrack->m_rotation[i + 1].m_rotation.m_x *= -1.0f; dstTrack->m_rotation[i + 1].m_rotation.m_y *= -1.0f; dstTrack->m_rotation[i + 1].m_rotation.m_z *= -1.0f; dstTrack->m_rotation[i + 1].m_rotation.m_w *= -1.0f; } } const dList& positions = srcTrack->GetPositions(); dstTrack->m_position.Resize(positions.GetCount()); index = 0; for (dList::dListNode* node = positions.GetFirst(); node; node = node->GetNext()) { dAnimationTrack::dCurveValue keyFrame(node->GetInfo()); dstTrack->m_position[index].m_posit = dVector(keyFrame.m_x, keyFrame.m_y, keyFrame.m_z, dFloat(1.0f)); dstTrack->m_position[index].m_time = keyFrame.m_time; index++; } } } } } dAssert(cachedAnimNode); return cachedAnimNode->GetInfo(); } void PopulateBasePose(dAnimPose& basePose, DemoEntity* const character) { basePose.Clear(); int stack = 1; DemoEntity* pool[32]; pool[0] = character; while (stack) { stack--; DemoEntity* const entity = pool[stack]; dAnimKeyframe& transform = basePose.Append()->GetInfo(); dMatrix matrix(entity->GetCurrentMatrix()); transform.m_posit = matrix.m_posit; transform.m_rotation = dQuaternion(matrix); transform.m_userData = entity; for (DemoEntity* node = entity->GetChild(); node; node = node->GetSibling()) { pool[stack] = node; stack++; } } } DemoEntity* FindRigRoot(DemoEntity* const character) { int stack = 1; DemoEntity* pool[32]; pool[0] = character; const int nodesCount = sizeof(inverseKinematicsRidParts) / sizeof(inverseKinematicsRidParts[0]); while (stack) { stack--; DemoEntity* const entity = pool[stack]; for (int i = 0; i < nodesCount; i++) { if (entity->GetName() == inverseKinematicsRidParts[i].m_name) { if (inverseKinematicsRidParts[i].m_type == dRigType::m_root) { return entity; } break; } } for (DemoEntity* node = entity->GetChild(); node; node = node->GetSibling()) { pool[stack] = node; stack++; } } dAssert(0); return NULL; } dSkeletonRigDefinition* FindDefinition(DemoEntity* const entity) const { const int nodesCount = sizeof(inverseKinematicsRidParts) / sizeof(inverseKinematicsRidParts[0]); for (int i = 0; i < nodesCount; i++) { if (entity->GetName() == inverseKinematicsRidParts[i].m_name) { switch (inverseKinematicsRidParts[i].m_type) { case dRigType::m_root: case dRigType::m_bone: { return &inverseKinematicsRidParts[i]; } default:; } } } return NULL; } dAnimIKController* CreateSkeletonRig(DemoEntity* const character) { DemoEntity* const rootEntity = FindRigRoot(character); dAnimIKController* const controller = CreateIKController(); controller->SetUserData(rootEntity); int stack = 0; DemoEntity* entityStack[32]; dAnimIKRigJoint* parentJointStack[32]; for (DemoEntity* node = rootEntity->GetChild(); node; node = node->GetSibling()) { entityStack[stack] = node; parentJointStack[stack] = controller->GetAsIKRigJoint(); stack ++; } while (stack) { stack--; DemoEntity* const entity = entityStack[stack]; dAnimIKRigJoint* const parentJoint = parentJointStack[stack]; dSkeletonRigDefinition* const definitions = FindDefinition(entity); if (definitions) { dAnimIK3dofJoint* const joint = new dAnimIK3dofJoint(parentJoint); joint->SetUserData(entity); for (DemoEntity* node = entity->GetChild(); node; node = node->GetSibling()) { entityStack[stack] = node; parentJointStack[stack] = joint; stack++; } } } return controller; } dAnimIKController* CreateHuman(DemoEntity* const model, const dMatrix& origin) { DemoEntityManager* const scene = (DemoEntityManager*) NewtonWorldGetUserData(GetWorld()); DemoEntity* const character = (DemoEntity*)model->CreateClone(); character->SetNameID("dommyRoot"); character->ResetMatrix(*scene, character->GetCurrentMatrix() * origin); scene->Append(character); dAnimIKController* const controller = CreateSkeletonRig(character); // dAnimCharacterUserData* const userData = new dAnimCharacterUserData(controller); // character->SetUserData(userData); // populate base pose PopulateBasePose(controller->GetBasePose(), character); //dAnimTakeData* const walkCycle = LoadAnimation(controller, "whiteman_walk.ngd"); dAnimTakeData* const walkCycle = LoadAnimation(controller, "whiteman_idle.ngd"); dAnimIKBlendNodeTake* const walk = new dAnimIKBlendNodeTake(controller, walkCycle); //dAnimIKBlendNodePose* const walk = new dAnimIKBlendNodePose(controller); //dAnimIKBlendNodePose* const pose = new dAnimIKBlendNodePose(controller); dAnimIKBlendNodeRoot* const animTree = new dAnimIKBlendNodeRoot(controller, walk); //dAnimIKBlendNodeRoot* const animTree = new dAnimIKBlendNodeRoot(controller, pose); controller->SetAnimationTree(animTree); return controller; } dAnimIKController* m_currentRig; dTree m_animCache; }; #endif void AnimatedPlayerController(DemoEntityManager* const scene) { // load the sky box scene->CreateSkyBox(); dTrace(("sorry demo %s temporarilly disabled\n", __FUNCTION__)); return; #if 0 CreateLevelMesh(scene, "flatPlane.ngd", true); dMatrix origin (dGetIdentityMatrix()); origin.m_posit.m_y = -0.0f; dMatrix origin1 (origin); InverseKinematicAnimationManager* const animationManager = new InverseKinematicAnimationManager(scene); dPointer humanModel (DemoEntity::LoadNGD_mesh("whiteman.ngd", scene->GetNewton(), scene->GetShaderCache())); //dAnimIKController* const human = animationManager->CreateHuman("whiteman.ngd", origin1); dAnimIKController* const human = animationManager->CreateHuman(&(*humanModel), origin1); //dAnimIKController* const human = animationManager->CreateHuman("skintest.ngd", origin1); DemoEntity* const referenceModel = DemoEntity::LoadNGD_mesh("viper.ngd", scene->GetNewton(), scene->GetShaderCache()); origin1.m_posit.m_z = 2.0f; referenceModel->ResetMatrix(*scene, referenceModel->GetCurrentMatrix() * origin1); scene->Append(referenceModel); dMatrix xxxx(origin1); for (int i = 0; i < 10; i ++) { xxxx.m_posit.m_x += 2; dMatrix xxxx1(xxxx); for (int j = 0; j < 10; j ++) { xxxx1.m_posit.m_z -= 2; animationManager->CreateHuman(&(*humanModel), xxxx1); } } origin.m_posit = dVector(-4.0f, 1.0f, 0.0f, 1.0f); scene->SetCameraMatrix(dGetIdentityMatrix(), origin.m_posit); #endif } 10-100 #include #include #include #include #include // main() has 6 lock-unlock pairs and other_func also has 6 int other_func(); int main(int argc, char *argv[]) { printf("Test starting\n"); std::mutex mut1, mut2; pthread_mutex_t mut3, mut4; pthread_mutex_init(&mut3, NULL); pthread_mutex_init(&mut4, NULL); mut1.lock(); // pair 1 (mut 1) pthread_mutex_lock(&mut4); // pair 5 (mut 4) int a = argc; if (a % 2) { mut1.unlock(); // pair 1 (mut 1) pthread_mutex_unlock(&mut4); // pair 6 (mut 4) printf("Early abort\n"); return 1; } // other_func(); mut2.lock(); // pair 2 (mut 2) pthread_mutex_lock(&mut3); // pair 4 (mut 3) a = a + 1; pthread_mutex_unlock(&mut3); // pair 4 (mut 3) mut2.unlock(); // pair 2 (mut 2) mut1.unlock(); // pair 3 (mut 1) pthread_mutex_unlock(&mut4); // pair 5 (mut 4) printf("a == %d\n", a); return 0; } #if 0 int other_func() { printf("Other func starting\n"); std::mutex mut1, mut2; pthread_mutex_t mut3, mut4; pthread_mutex_init(&mut3, NULL); pthread_mutex_init(&mut4, NULL); mut1.lock(); pthread_mutex_lock(&mut4); int b = rand() % 10 + 1; if (b % 2) { mut1.unlock(); pthread_mutex_unlock(&mut4); printf("Early other func abort\n"); return 1; } mut2.lock(); pthread_mutex_lock(&mut3); b = b + 1; pthread_mutex_unlock(&mut3); mut2.unlock(); mut1.unlock(); pthread_mutex_unlock(&mut4); printf("b == %d\n", b); return 0; } #endif #include "timer.hh" #include #include int main(){ const int n = 1000000; const double delta = 1.0/(double)n; double s = 0; double t0 = time(); for (int i = 0; i < n; ++i) { s += std::cos(i*delta) * delta; } double te = time()-t0; std::printf(" sin(1) ~= %10.6e\n", s); std::printf(" elapsed time = %10.6e seconds\n", te); }OpenARDF/Arducon /* * MIT License * * Copyright (c) 2020 DigitalConfections * * 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 "ardooweeno.h" #include void pinMode(uint8_t pin, uint8_t mode) { switch(pin) { case PIN_RXD: { if(mode == OUTPUT) { DDRD |= (1 << PORTD0); } else { DDRD &= ~(1 << PORTD0); if(mode == INPUT_PULLUP) { PORTD |= (1 << PORTD0); } else { PORTD &= ~(1 << PORTD0); } } } break; case PIN_TXD: { if(mode == OUTPUT) { DDRD |= (1 << PORTD1); } else { DDRD &= ~(1 << PORTD1); if(mode == INPUT_PULLUP) { PORTD |= (1 << PORTD1); } else { PORTD &= ~(1 << PORTD1); } } } break; case D2: { if(mode == OUTPUT) { DDRD |= (1 << PORTD2); } else { DDRD &= ~(1 << PORTD2); if(mode == INPUT_PULLUP) { PORTD |= (1 << PORTD2); } else { PORTD &= ~(1 << PORTD2); } } } break; case D3: { if(mode == OUTPUT) { DDRD |= (1 << PORTD3); } else { DDRD &= ~(1 << PORTD3); if(mode == INPUT_PULLUP) { PORTD |= (1 << PORTD3); } else { PORTD &= ~(1 << PORTD3); } } } break; case D4: { if(mode == OUTPUT) { DDRD |= (1 << PORTD4); } else { DDRD &= ~(1 << PORTD4); if(mode == INPUT_PULLUP) { PORTD |= (1 << PORTD4); } else { PORTD &= ~(1 << PORTD4); } } } break; case D5: { if(mode == OUTPUT) { DDRD |= (1 << PORTD5); } else { DDRD &= ~(1 << PORTD5); if(mode == INPUT_PULLUP) { PORTD |= (1 << PORTD5); } else { PORTD &= ~(1 << PORTD5); } } } break; case D6: { if(mode == OUTPUT) { DDRD |= (1 << PORTD6); } else { DDRD &= ~(1 << PORTD6); if(mode == INPUT_PULLUP) { PORTD |= (1 << PORTD6); } else { PORTD &= ~(1 << PORTD6); } } } break; case D7: { if(mode == OUTPUT) { DDRD |= (1 << PORTD7); } else { DDRD &= ~(1 << PORTD7); if(mode == INPUT_PULLUP) { PORTD |= (1 << PORTD7); } else { PORTD &= ~(1 << PORTD7); } } } break; case D8: { if(mode == OUTPUT) { DDRB |= (1 << PORTB0); } else { DDRB &= ~(1 << PORTB0); if(mode == INPUT_PULLUP) { PORTB |= (1 << PORTB0); } else { PORTB &= ~(1 << PORTB0); } } } break; case D9: { if(mode == OUTPUT) { DDRB |= (1 << PORTB1); } else { DDRB &= ~(1 << PORTB1); if(mode == INPUT_PULLUP) { PORTB |= (1 << PORTB1); } else { PORTB &= ~(1 << PORTB1); } } } break; case D10: { if(mode == OUTPUT) { DDRB |= (1 << PORTB2); } else { DDRB &= ~(1 << PORTB2); if(mode == INPUT_PULLUP) { PORTB |= (1 << PORTB2); } else { PORTB &= ~(1 << PORTB2); } } } break; case D13: { if(mode == OUTPUT) { DDRB |= (1 << PORTB5); } else { DDRB &= ~(1 << PORTB5); if(mode == INPUT_PULLUP) { PORTD |= (1 << PORTB5); } else { PORTD &= ~(1 << PORTB5); } } } break; case A0: { if(mode == OUTPUT) { DDRC |= (1 << PORTC0); } else { DDRC &= ~(1 << PORTC0); if(mode == INPUT_PULLUP) { PORTC |= (1 << PORTC0); } else { PORTC &= ~(1 << PORTC0); } } } break; case A1: { if(mode == OUTPUT) { DDRC |= (1 << PORTC1); } else { DDRC &= ~(1 << PORTC1); if(mode == INPUT_PULLUP) { PORTC |= (1 << PORTC1); } else { PORTC &= ~(1 << PORTC1); } } } break; case A2: { if(mode == OUTPUT) { DDRC |= (1 << PORTC2); } else { DDRC &= ~(1 << PORTC2); if(mode == INPUT_PULLUP) { PORTC |= (1 << PORTC2); } else { PORTC &= ~(1 << PORTC2); } } } break; case A3: { if(mode == OUTPUT) { DDRC |= (1 << PORTC3); } else { DDRC &= ~(1 << PORTC3); if(mode == INPUT_PULLUP) { PORTC |= (1 << PORTC3); } else { PORTC &= ~(1 << PORTC3); } } } break; case A4: { if(mode == OUTPUT) { DDRC |= (1 << PORTC4); } else { DDRC &= ~(1 << PORTC4); if(mode == INPUT_PULLUP) { PORTC |= (1 << PORTC4); } else { PORTC &= ~(1 << PORTC4); } } } break; case A5: { if(mode == OUTPUT) { DDRC |= (1 << PORTC5); } else { DDRC &= ~(1 << PORTC5); if(mode == INPUT_PULLUP) { PORTC |= (1 << PORTC5); } else { PORTC &= ~(1 << PORTC5); } } } break; default: { } break; } } BOOL digitalRead(uint8_t pin) { int result = 0; switch(pin) { case D2: { result = PIND & (1 << PORTD2); } break; case D3: { result = PIND & (1 << PORTD3); } break; case D4: { result = PIND & (1 << PORTD4); } break; case D5: { result = PIND & (1 << PORTD5); } break; case D6: { result = PIND & (1 << PORTD6); } break; case D7: { result = PIND & (1 << PORTD7); } break; case D8: { result = PINB & (1 << PORTB0); } break; case D9: { result = PINB & (1 << PORTB1); } break; case D10: { result = PINB & (1 << PORTB2); } break; case D13: { result = PINB & (1 << PORTB5); } break; case A0: { result = PINC & (1 << PORTC0); } break; case A1: { result = PINC & (1 << PORTC1); } break; case A2: { result = PINC & (1 << PORTC2); } break; case A3: { result = PINC & (1 << PORTC3); } break; default: { } break; } return(result != 0); } void digitalWrite(uint8_t pin, uint8_t value) { switch(pin) { case PIN_RXD: { if(value) { PORTD |= (1 << PORTD0); } else { PORTD &= ~(1 << PORTD0); } } break; case PIN_TXD: { if(value) { PORTD |= (1 << PORTD1); } else { PORTD &= ~(1 << PORTD1); } } break; case D2: { if(value) { PORTD |= (1 << PORTD2); } else { PORTD &= ~(1 << PORTD2); } } break; case D3: { if(value) { PORTD |= (1 << PORTD3); } else { PORTD &= ~(1 << PORTD3); } } break; case D4: { if(value) { PORTD |= (1 << PORTD4); } else { PORTD &= ~(1 << PORTD4); } } break; case D5: { if(value) { PORTD |= (1 << PORTD5); } else { PORTD &= ~(1 << PORTD5); } } break; case D6: { if(value) { PORTD |= (1 << PORTD6); } else { PORTD &= ~(1 << PORTD6); } } break; case D7: { if(value) { PORTD |= (1 << PORTD7); } else { PORTD &= ~(1 << PORTD7); } } break; case D8: { if(value) { PORTB |= (1 << PORTB0); } else { PORTB &= ~(1 << PORTB0); } } break; case D9: { if(value) { PORTB |= (1 << PORTB1); } else { PORTB &= ~(1 << PORTB1); } } break; case D10: { if(value) { PORTB |= (1 << PORTB2); } else { PORTB &= ~(1 << PORTB2); } } break; case D13: { if(value) { PORTB |= (1 << PORTB5); } else { PORTB &= ~(1 << PORTB5); } } break; case A0: { if(value) { PORTC |= (1 << PORTC0); } else { PORTC &= ~(1 << PORTC0); } } break; case A1: { if(value) { PORTC |= (1 << PORTC1); } else { PORTC &= ~(1 << PORTC1); } } break; case A2: { if(value) { PORTC |= (1 << PORTC2); } else { PORTC &= ~(1 << PORTC2); } } break; case A3: { if(value) { PORTC |= (1 << PORTC3); } else { PORTC &= ~(1 << PORTC3); } } break; default: { } break; } } //Bloc 2 // Problema 5 #include #include using namespace std; int numarAparitii(list lista, int n, int x) { int result = 0; list::iterator it = lista.begin(); for (it=lista.begin();it!=lista.end();it++) if (x == *it) result++; std::advance(it, 1); return result; } int main() { list lista = {5, 7, 8, 8, 5, 8, 7, 6, 7, 7}; list::iterator it = lista.begin(); int n = sizeof(lista); cout << "Lista originala: "; for (it=lista.begin();it!=lista.end();it++) cout << *it <<" "; std::advance(it, 1); cout <<"\nNumarul de aparitii al cifrei 8 este : " << numarAparitii(lista, n, 7); return 0; } // // Created by caedus on 22.12.2020. // #include #include #include #include "Builtins/BuiltinsException.hpp" #include "Modules/ModuleException.hpp" #include "TypeSystem/Types/LabelObject.hpp" #include "TypeSystem/Types/ListObject.hpp" #include "VirtualMachine/CallWrapper.hpp" #include "VirtualMachine/LambdaCallEvaluator.hpp" #include "VirtualMachine/Machine.hpp" #include "VirtualMachine/MachineRuntimeException.hpp" namespace nastya::vm { using namespace utils; Machine::Machine(const modules::IModuleRegistry& registry) : m_modules{registry} { } typesystem::ObjectStorage Machine::run(const typesystem::ObjectStorage& list) { const auto label_computation_result = computeLabel(list); if (label_computation_result) { return *label_computation_result; } if (list.getType() != typesystem::ObjectType::List) { return list; } // GCOVR_EXCL_START // // Casts does not required to be check for bad_cast error because type are checked with enum. // Index is correct because earlier we checked if it is not empty list. const auto& raw_object = Cast::as_list(list); if (raw_object.isEmpty()) { return typesystem::ObjectStorage(list); } auto content = raw_object.getContent(); if (content[0].getType() != typesystem::ObjectType::Label) { BUT_THROW(MachineRuntimeException, "Invalid command format"); } auto label = dynamic_cast(content[0].getRawObject()); // GCOVR_EXCL_STOP auto lambda = computeLabel(content[0]); const auto isLambda = (lambda and lambda.value().getType() == typesystem::ObjectType::Lambda); std::unique_ptr call; if (isLambda) { call = std::make_unique(new LambdaCallEvaluator(lambda.value(), content, *this)); } else { call = std::make_unique(m_modules.getFunction(label.getValue())); } const auto arguments = call->preExecute(raw_object, *this); const auto result = call->evaluate(*this, arguments); call->postExecute(*this); return result; } bool Machine::registerVariableOnHeap(const typesystem::LabelObject& variableName, const typesystem::ObjectStorage& objectStorage) { auto [it, state] = m_heap.try_emplace(variableName.getValue(), objectStorage); return state; } const typesystem::ObjectStorage& Machine::getFromHeap(const typesystem::LabelObject& variableName) const { return m_heap.at(variableName.getValue()); } bool Machine::isSymbolAvailable(const typesystem::ObjectStorage& object) const { const auto& label = utils::Cast::as_label(object); const auto reversed_stack = m_stack | ranges::views::reverse; for (const auto frame : reversed_stack) { if (frame.find(label.getValue()) != frame.end()) { return true; } } return (m_heap.find(label.getValue()) != m_heap.end()); } void Machine::pushStackFrame() { m_stack.emplace_back(std::map()); } bool Machine::popStackFrame() { if (not m_stack.empty()) { m_stack.pop_back(); return true; } return false; } bool Machine::registerVariableOnStack(const typesystem::LabelObject& variableName, const typesystem::ObjectStorage& objectStorage) { if (m_stack.empty()) { pushStackFrame(); } const auto top = m_stack.size() - 1; auto [it, state] = m_stack[top].try_emplace(variableName.toString(), objectStorage); return false; } const typesystem::ObjectStorage& Machine::getFromStack(const typesystem::LabelObject& variableName) const { auto it = m_stack.rbegin(); while (it != m_stack.rend()) { const auto result = it->find(variableName.getValue()); if (result != it->end()) { return result->second; } it += 1; } BUT_THROW(MachineRuntimeException, "Variable is not available"); } std::optional Machine::computeLabel(const typesystem::ObjectStorage& label) const { if (label.getType() != typesystem::ObjectType::Label) { return {}; } if (not isSymbolAvailable(label)) { return label; } try { std::unique_ptr copied(getFromStack(Cast::as_label(label)).getRawObject().clone()); typesystem::ObjectStorage result(std::move(copied)); return {result}; } catch (MachineRuntimeException& e) { const auto result = getFromHeap(Cast::as_label(label)); return {result}; } } } // namespace nastya::vm 0 #include #include #include #include #include #include int main() { std::cout << CryptoPP::AES::DEFAULT_KEYLENGTH << std::endl; std::cout << CryptoPP::AES::BLOCKSIZE << std::endl; CryptoPP::AutoSeededRandomPool pool; byte key[CryptoPP::AES::DEFAULT_KEYLENGTH]; pool.GenerateBlock(key, sizeof(key)); for(int i=0; i::Encryption enc; enc.SetKeyWithIV(key, sizeof(key), iv, sizeof(iv)); CryptoPP::StringSource ss1(pdata, true, new CryptoPP::AuthenticatedEncryptionFilter(enc, new CryptoPP::StringSink(cipher), false, TAG_SIZE)); std::cout << cipher; // std::cout << crypted.size() << std::endl; // std::cout << decrypted << std::endl; // std::cout << decrypted.size() << std::endl; return 0; } 10-100 #include using namespace std; int main() { char str[10] = { 0 }; cin.getline(str, sizeof(str)); cout << str << endl; return 0; } #pragma once #include "golos.config/parameters.hpp" #include #include namespace golos { using namespace eosio; // NOTE: not finished yet, delayed until we require median, etc… class configer: public contract { public: using contract::contract; // own parameters void validateprms(std::vector); void setparams(std::vector); // base for recalculatable parameters void updateparams(name, std::vector); [[eosio::action]] void updateparamse(name who, std::vector params); // TODO: maybe combine into 1 action accepting all params [[eosio::action]] void notifytop(std::vector top); private: std::vector get_top_witnesses(); bool is_top_witness(name account); void recalculate_state(std::vector); }; } // golos class CombinationIterator { public: CombinationIterator(string characters, int combinationLength) { string path; dfs(characters, 0, combinationLength, path, result); reverse(result.begin(), result.end()); } string next() { string s = result.back(); result.pop_back(); return s; } bool hasNext() { return !result.empty(); } private: vector result; void dfs(string characters, int start, int combinationLength, string& path, vector& result) { int curr = path.size(); if (curr == combinationLength) { result.push_back(path); return; } int diff = combinationLength - curr; for (int i = start; i <= characters.size() - diff; ++i) { path.push_back(characters[i]); dfs(characters, i + 1, combinationLength, path, result); path.pop_back(); } } }; /** * Your CombinationIterator object will be instantiated and called as such: * CombinationIterator* obj = new CombinationIterator(characters, combinationLength); * string param_1 = obj->next(); * bool param_2 = obj->hasNext(); */ takekoputa/project-euler // Problem: https://projecteuler.net/problem=171 // g++ problem171.cpp -O3 --std=c++2a /* Strategy: - The maximum sum of square of 20 digits is 20 * (9^2) = 1620 -> there are 40 different possibilities for the sum (e.g. 1, 4, 9, 16, 25, etc.) - It's fast to generate a monotonically sequence of 20 digits that sums up to a certain number. -> generate such sequences that each sequence sums up to one of the above square numbers. - For each of sequence, the distribution of digits in the sequence is different than that of other sequences. -> we can permutate each sequence and find the sum. - Since we only need the sum of permutations, we can exploit the "symmetry" of permutations of a certain set. -> we don't need to iterate through all the permutations! -> how to find the sums? -> first, we find the number of unique permutations of the set where the order of number matters -> this can be done using multinomial coefficient (https://mathworld.wolfram.com/MultinomialCoefficient.html) -> for a set of x1 object 1, x2 object 2, ..., xm object m, the number of permutations where the order matters is factorial(x1+x2+...+xm) / [factorial(x1) * factorial(x2) * ... * factorial(xm)] -> second, let's lay the permutation vertically. Let say we have a set {a,a,b,b,c}, then, we have {a, a, b, b, c} {a, a, b, c, b} {a, a, c, b, b} {a, b, a, b, c} {a, b, a, c, b} {a, b, b, a, c} {a, b, b, c, a} {a, b, c, a, b} {a, b, c, b, a} {a, c, a, b, b} {a, c, b, a, b} {a, c, b, b, a} {b, a, a, b, c} {b, a, a, c, b} {b, a, b, a, c} {b, a, b, c, a} {b, a, c, a, b} {b, a, c, b, a} {b, b, a, a, c} {b, b, a, c, a} {b, b, c, a, a} {b, c, a, a, b} {b, c, a, b, a} {b, c, b, a, a} {c, a, a, b, b} {c, a, b, a, b} {c, a, b, b, a} {c, b, a, a, b} {c, b, a, b, a} {c, b, b, a, a} Let a, b, c be the digits and we want to find the sum of the numbers formed by the digits. Note that, each column has the same distribution of a, b, c. This leads to a couple of nice properties: -> each column has the same sum -> we know the distribution of digits of each column (|a|:|b|:|c| = 2:2:1 in this case) (1) -> we know the number of digits of each colomn (= number of permutations) (2) -> from (1) and (2), we can figure out how many each digit appears in a column, and from this, we can find the sum of each column -> we can find the sum of all permutations without having to iterate through all permutations. */ #include #include #include #include #include #include using namespace std; typedef uint64_t ui; #define endl "\n" const ui N = 20; const ui M = 9; const ui MOD = 1'000'000'000ULL; unordered_map squares_map = {{0, 0}, {1, 1}, {4, 2}, {9, 3}, {16, 4}, {25, 5}, {36, 6}, {49, 7}, {64, 8}, {81, 9}}; constexpr ui factorial(ui n) { if (n == 0) return 1; else return n * factorial(n-1); } ui calculate_all_permutation_mod(vector digits) { vector digit_freq = vector(10, 0); for (ui i = 1; i <= N; i++) digit_freq[digits[i]] = digit_freq[digits[i]] + 1; // Multinomial coeff C(N, (freq1, freq2, ...)) ui n_permutations = factorial(20); for (auto freq: digit_freq) n_permutations = n_permutations / factorial(freq); // Reduce the ratio so that n_permutations is divisible by the sum of the ratio ui GCD = digit_freq[0]; for (ui i = 1; i <= 9; i++) GCD = gcd(GCD, digit_freq[i]); for (ui i = 0; i <= 9; i++) digit_freq[i] = digit_freq[i] / GCD; ui freq_sum = 0; for (auto freq: digit_freq) freq_sum = freq_sum + freq; vector digit_freq_per_column = vector(10, 0); for (ui i = 0; i < digit_freq_per_column.size(); i++) digit_freq_per_column[i] = n_permutations / freq_sum * digit_freq[i]; ui column_sum = 0; for (ui i = 1; i < digit_freq_per_column.size(); i++) column_sum = column_sum + digit_freq_per_column[i] * i; ui mod = 0; ui coeff = 1; column_sum = column_sum % MOD; for (ui i = 0; i < M; i++) { mod = mod + column_sum * coeff; mod = mod % MOD; coeff = coeff * 10; } return mod; } ui DFS(ui depth, ui curr_sum, const ui& target, vector& digits) { if (depth == N) { ui digit_square = target - curr_sum; if (squares_map.find(digit_square) != squares_map.end()) { digits[depth] = squares_map[digit_square]; if (digits[depth] < digits[depth-1]) return 0; ui total = calculate_all_permutation_mod(digits); return total; } return 0; } ui total = 0; for (ui digit = digits[depth-1]; digit <= 9; digit++) { ui next_sum = curr_sum + digit * digit; digits[depth] = digit; if (next_sum > target) break; ui max_remaining_sum = (N-depth) * (9*9); if (max_remaining_sum < target - next_sum) continue; total = total + DFS(depth + 1, next_sum, target, digits); total = total % MOD; } return total; } struct ThreadResult { ui ans; }; void worker(vector valid_sums, ThreadResult& output) { ui ans = 0; vector digits = vector(N+1); digits[0] = 0; for (auto& valid_sum: valid_sums) { ans = ans + DFS(1, 0, valid_sum, digits); ans = ans % MOD; } output.ans = ans; } int main() { ui ans = 0; ui n_threads = 8; ui max_sum_of_digit_squares = N * (9*9); vector valid_sums; for (ui i = 1; i*i <= max_sum_of_digit_squares; i++) valid_sums.push_back(i*i); vector threads; vector thread_results = vector(n_threads); for (ui i = 0; i < n_threads; i++) { vector jobs; for (ui j = i; j < valid_sums.size(); j += n_threads) jobs.push_back(valid_sums[j]); thread new_thread(worker, jobs, ref(thread_results[i])); threads.push_back(move(new_thread)); } for (ui i = 0; i < n_threads; i++) threads[i].join(); for (auto& result: thread_results) ans = (ans + result.ans) % MOD; cout << ans << endl; return 0; } seahorn/crab-llvm #pragma once /** * The HeapAnalysis class wraps a Dsa-like analysis. **/ #include "clam/config.h" #include "crab/support/debug.hpp" #include "llvm/IR/Value.h" #include "llvm/Support/raw_ostream.h" #include // forward declarations namespace llvm { class Module; class Function; class Instruction; class StringRef; class CallInst; } // namespace llvm namespace clam { //// // Dsa analysis for memory disambiguation //// enum class heap_analysis_t { // disable heap analysis NONE, // use context-insensitive sea-dsa CI_SEA_DSA, // use context-sensitive sea-dsa CS_SEA_DSA }; enum class region_type_t { UNTYPED_REGION = 0, BOOL_REGION = 1, INT_REGION = 2, PTR_REGION = 3 }; class RegionInfo { region_type_t m_region_type; // if PTR_REGION then bitwidth is the pointer size // if INT_REGION or BOOL_REGION then bitwidth is the integer's // bitwidth or 1. unsigned m_bitwidth; // number of bits //--------------------------------------// /// Auxiliary bits about the region //--------------------------------------// // whether the region is coming from a "sequence" sea-dsa node bool m_is_sequence; // whether the region is possibly allocated in the heap bool m_is_heap; // whether the region is possibly cyclic bool m_is_cyclic; public: RegionInfo(region_type_t t, unsigned b, bool is_seq, bool is_heap, bool is_cyclic) : m_region_type(t), m_bitwidth(b), m_is_sequence(is_seq), m_is_heap(is_heap), m_is_cyclic(is_cyclic) {} RegionInfo(const RegionInfo &other) = default; RegionInfo &operator=(const RegionInfo &other) = default; bool isUntyped() const { return m_region_type == region_type_t::UNTYPED_REGION; } bool hasSameType(const RegionInfo &o) const { // note that ignores flags m_is_sequence and m_is_heap return (m_region_type == o.m_region_type && m_bitwidth == o.m_bitwidth); } bool operator==(const RegionInfo &o) const { return hasSameType(o); } bool operator<(const RegionInfo &o) const { // note that ignores flags m_is_sequence and m_is_heap return (m_region_type == o.m_region_type ? m_bitwidth < o.m_bitwidth : m_region_type < o.m_region_type); } bool hasCompatibleType(const RegionInfo &o) const { if (isUntyped() || o.isUntyped()) { return true; } else { return hasSameType(o); } } bool containScalar() const { return m_region_type == region_type_t::BOOL_REGION || m_region_type == region_type_t::INT_REGION; } bool containPointer() const { return m_region_type == region_type_t::PTR_REGION; } // Return a pair with the type (boolean, integer or pointer) and // bitwidth in **bits**. The bitwidth is 1 if boolean region, size // of the pointer if pointer region, or size of the integer if // integer region. Otherwise, it returns 0 if bitwdith cannot be // determined. std::pair getType() const { return std::make_pair(m_region_type, m_bitwidth); } // Whether the region corresponds to a "sequence" node bool isSequence() const { return m_is_sequence; } // Whether the region is potentially allocated via a malloc-like // function. bool isHeap() const { return m_is_heap; } // Whether the region is cyclic (linked lists, trees, etc) bool isCyclic() const { return m_is_cyclic; } void write(llvm::raw_ostream &o) const { switch (m_region_type) { case region_type_t::UNTYPED_REGION: o << "U"; break; case region_type_t::BOOL_REGION: o << "B"; break; case region_type_t::INT_REGION: o << "I" << ":" << m_bitwidth; break; case region_type_t::PTR_REGION: o << "P"; break; } } friend llvm::raw_ostream &operator<<(llvm::raw_ostream &o, const RegionInfo &rgnInfo) { rgnInfo.write(o); return o; } }; /** * A region abstracts a Dsa node field to create a symbolic name. **/ class Region { public: using RegionId = long unsigned int; private: // A region different from unknown should represent a consecutive // sequence of bytes in memory that have compatible types and are // accessed uniformly so the analysis can use it in a safe // manner. // Unique id RegionId m_id; // type of the region RegionInfo m_info; // whether the region contains a singleton value or not. const llvm::Value *m_singleton; public: Region(RegionId id, RegionInfo info, const llvm::Value *singleton) : m_id(id), m_info(info), m_singleton(singleton) {} Region() : m_id(0), m_info(RegionInfo(region_type_t::UNTYPED_REGION, 0, false, false, false)), m_singleton(nullptr) {} Region(const Region &other) = default; Region(Region &&other) = default; Region &operator=(const Region &other) = default; RegionId getId() const { return m_id; } bool isUnknown() const { return (m_info.getType().first == region_type_t::UNTYPED_REGION); } const llvm::Value *getSingleton() const { return m_singleton; } RegionInfo getRegionInfo() const { return m_info; } bool operator<(const Region &o) const { return (m_id < o.m_id); } bool operator==(const Region &o) const { return (m_id == o.m_id); } void write(llvm::raw_ostream &o) const { o << "R_" << m_id << ":" << getRegionInfo(); } friend llvm::raw_ostream &operator<<(llvm::raw_ostream &o, const Region &r) { r.write(o); return o; } }; inline llvm::raw_ostream &operator<<(llvm::raw_ostream &o, std::vector s) { o << "{"; for (typename std::vector::iterator it = s.begin(), et = s.end(); it != et;) { o << *it; ++it; if (it != et) o << ","; } o << "}"; return o; } /* A convenient wrapper for a Dsa-like analysis */ class HeapAbstraction { friend class Region; public: typedef std::vector RegionVec; typedef typename Region::RegionId RegionId; // Add a new value if a new HeapAbstraction subclass is created // This is used to use static_cast. enum class ClassId { DUMMY, SEA_DSA }; HeapAbstraction() {} virtual ~HeapAbstraction() {} virtual ClassId getClassId() const = 0; virtual llvm::StringRef getName() const = 0; // TODO: mark all these methods as const. // fun is used to know in which function ptr lives. // If not null, i is the instruction that uses ptr. virtual Region getRegion(const llvm::Function &fun, const llvm::Value &ptr) = 0; /**======== These functions allow to purify functions ========**/ // Read-Only regions reachable by function parameters and globals // but not returns virtual RegionVec getOnlyReadRegions(const llvm::Function &) const = 0; // Written regions reachable by function parameters and globals but // not returns virtual RegionVec getModifiedRegions(const llvm::Function &) const = 0; // Regions that are reachable only from the return of the function virtual RegionVec getNewRegions(const llvm::Function &) const = 0; // Read-only regions at the caller that are mapped to callee's // formal parameters and globals. virtual RegionVec getOnlyReadRegions(const llvm::CallInst &) const = 0; // Written regions at the caller that are mapped to callee's formal // parameters and globals. virtual RegionVec getModifiedRegions(const llvm::CallInst &) const = 0; // Regions at the caller that are mapped to those that are only // reachable from callee's returns. virtual RegionVec getNewRegions(const llvm::CallInst &) const = 0; }; } // namespace clam #include "PbbamInternalConfig.h" #include #include #include #include #include #include #include #include #include "VirtualStitching.h" #include "VirtualZmwReader.h" namespace PacBio { namespace BAM { class ZmwReadStitcher::ZmwReadStitcherPrivate { public: ZmwReadStitcherPrivate(std::string primaryBamFilePath, std::string scrapsBamFilePath, PbiFilter filter) : filter_{std::move(filter)} { sources_.push_back({std::move(primaryBamFilePath), std::move(scrapsBamFilePath)}); OpenNextReader(); } ZmwReadStitcherPrivate(const DataSet& dataset) : filter_{PbiFilter::FromDataSet(dataset)} { sources_ = SourcesFromDataset(dataset); OpenNextReader(); } bool HasNext() const { return (currentReader_ && currentReader_->HasNext()); } VirtualZmwBamRecord Next() { if (currentReader_) { const auto result = currentReader_->Next(); if (!currentReader_->HasNext()) { OpenNextReader(); } return result; } // no reader active throw std::runtime_error{ "[pbbam] ZMW stitching ERROR: " "no readers active, make sure you use " "ZmwReadStitcher::HasNext before " "requesting next record"}; } std::vector NextRaw() { if (currentReader_) { const auto result = currentReader_->NextRaw(); if (!currentReader_->HasNext()) { OpenNextReader(); } return result; } // no reader active throw std::runtime_error{ "[pbbam] ZMW stitching ERROR: " "no readers active, make sure you use " "ZmwReadStitcher::HasNext before " "requesting next group of records"}; } BamHeader PrimaryHeader() const { return currentReader_->PrimaryHeader(); } BamHeader ScrapsHeader() const { return currentReader_->ScrapsHeader(); } BamHeader StitchedHeader() const { return currentReader_->StitchedHeader(); } private: StitchingSources sources_; std::unique_ptr currentReader_; PbiFilter filter_; void OpenNextReader() { currentReader_.reset(nullptr); // find next source pair with data while (!sources_.empty()) { const auto nextSource = sources_.front(); sources_.pop_front(); currentReader_ = std::make_unique(nextSource.first, nextSource.second, filter_); if (currentReader_->HasNext()) { return; } } } }; // -------------------------------- // ZmwReadStitcher implementation // -------------------------------- ZmwReadStitcher::ZmwReadStitcher(std::string primaryBamFilePath, std::string scrapsBamFilePath) : ZmwReadStitcher{std::move(primaryBamFilePath), std::move(scrapsBamFilePath), PbiFilter{}} { } ZmwReadStitcher::ZmwReadStitcher(std::string primaryBamFilePath, std::string scrapsBamFilePath, PbiFilter filter) : d_{std::make_unique(std::move(primaryBamFilePath), std::move(scrapsBamFilePath), std::move(filter))} { } ZmwReadStitcher::ZmwReadStitcher(const DataSet& dataset) : d_{std::make_unique(dataset)} { } ZmwReadStitcher::~ZmwReadStitcher() = default; bool ZmwReadStitcher::HasNext() { return d_->HasNext(); } VirtualZmwBamRecord ZmwReadStitcher::Next() { return d_->Next(); } std::vector ZmwReadStitcher::NextRaw() { return d_->NextRaw(); } BamHeader ZmwReadStitcher::PrimaryHeader() const { return d_->PrimaryHeader().DeepCopy(); } BamHeader ZmwReadStitcher::ScrapsHeader() const { return d_->ScrapsHeader().DeepCopy(); } BamHeader ZmwReadStitcher::StitchedHeader() const { return d_->StitchedHeader().DeepCopy(); } } // namespace BAM } // namespace PacBio /* * Copyright (c) 2017-2019, NVIDIA CORPORATION. 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 NVIDIA 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 ``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 "priv/EngineAST.h" #include "priv/Profile.h" #include "priv/Tensor.h" #include "ErrorMacros.h" #include using std::map; using std::vector; using std::endl; namespace nvdla { namespace priv { //---------------------------------------------------------------------- // Compiler Utils //---------------------------------------------------------------------- /*--------------------------Register Surface Desc---------------------*/ /* idempotent */ NvDlaError engine_ast::Edge::registerSurface() { NvDlaError e = NvDlaError_Success; surface::TensorSurfaceDesc* tsd = NULL; TensorType tt; NvU16 numBatches = graph()->profile()->multiBatchSize(); if ( !isDataEdge() ) { goto fail; } tt = originalTensor() ? originalTensor()->getTensorType() : TensorType::kDEBUG; if ( tt == TensorType::kUNKNOWN ) { ORIGINATE_ERROR_FAIL(NvDlaError_BadParameter, "Unidentified TensorType '%d' in edge '%s'", tt, id().c_str()); } tsd = tensorSurfaceDesc(); if ( !tsd ) { tsd = graph()->resourceMgr()->regTensorSurfaceDesc(tt, numBatches); tsd->setName(std::string(originalTensor()->getName())); tsd->setBufferOffset(0); // default offset tsd->setDimensions(originalTensor()->getDimensions()); tsd->setCopyOutDebugSurface(tt == TensorType::kDEBUG); tsd->setDataFormat(originalTensor()->getDataFormat()); tsd->setParentEdge(this); setTensorSurfaceDesc(tsd); // // is this edge related to a bindable resource? // if so we need to maintain that connection. // if ( bindable() ) { enum IOD bindDomain; NvS16 bid = bindId(bindDomain); tsd->setBindId(bid, bindDomain); if ( debugBinding() ) { gLogInfo << "set bind id " << bid << " for " << id() << " " << tsd->id() << endl; } // tbd: theoretically could be cvsram as well? // choosing not to support it for now. //tsd->setMemoryLoc(memory::LocationEnum::lDRAM); } if ( graph()->debugSurfaces() ) { gLogInfo << ((tt == TensorType::kDEBUG) ? "(debug) ":"" ) << "edge: " << id() << " tsd: " << tsd->id() << " registered" << endl; } } fail: return e; } /*----------------------Determine Surface Clients----------------------*/ NvDlaError engine_ast::Edge::determineSurfaceClients() { NvDlaError e = NvDlaSuccess; Graph::NodeSequence upNodes, downNodes; surface::TensorSurfaceDesc* tsd = tensorSurfaceDesc(); if (!isDataEdge()) { goto fail; } else if (!tsd) { ORIGINATE_ERROR_FAIL(NvDlaError_BadValue, "Surface Desc not yet registered for %s", id().c_str()); } tsd->clearProducers(); upNodes = graph()->upstreamNodes(this); for (vector< engine_ast::Node* >::const_iterator ni = upNodes.begin(); ni != upNodes.end(); ++ni) { tsd->addProducer((*ni)); } tsd->clearConsumers(); downNodes = graph()->downstreamNodes(this); for (vector< engine_ast::Node* >::const_iterator ni = downNodes.begin(); ni != downNodes.end(); ++ni) { tsd->addConsumer((*ni)); } fail: return e; } /*----------------------Determine Surface Format-----------------------*/ NvDlaError engine_ast::Edge::determineSurfaceFormat() { NvDlaError e = NvDlaSuccess; TensorType tt; Graph::NodeUnorderedSet producers; Graph::NodeUnorderedSet consumers; bool isAUXSurface, isInterimSurface, isBindableSurface; surface::TensorSurfaceDesc* tsd = tensorSurfaceDesc(); std::set producerProposedSFs; std::set consumerProposedSFs; std::set proposedSFs; std::vector suggestedSFs; std::vector supportedSFs; if (!isDataEdge()) { goto fail; } tt = originalTensor()->getTensorType(); isAUXSurface = (tt == TensorType::kWEIGHT || tt == TensorType::kBIAS || tt == TensorType::kBATCH_NORM || tt == TensorType::kSCALE); isInterimSurface = (tt == TensorType::kIO || tt == TensorType::kSTREAM || tt == TensorType::kDEBUG); isBindableSurface = (tt == TensorType::kNW_INPUT || tt == TensorType::kNW_OUTPUT); if (!isAUXSurface && !isInterimSurface && !isBindableSurface) { ORIGINATE_ERROR_FAIL(NvDlaError_NotSupported, "Unsupported tensor type %d", (int)tt); } if (!tsd) { ORIGINATE_ERROR_FAIL(NvDlaError_BadValue, "Surface Desc not yet registered for %s", id().c_str()); } else if (tsd->surfaceFormat().v() != surface::SurfaceFormatEnum::NVDLA_UNKNOWN_FORMAT) { if ( graph()->debugSurfaces() ) { gLogInfo << id() << " edge already has set surface format " << tsd->surfaceFormat().c_str() << endl; } goto fail; } producers = tsd->producers(); consumers = tsd->consumers(); // Step-1: Capture surf formats suggested by consumer nodes for (Graph::NodeUnorderedSetIterator ci = consumers.begin(); ci != consumers.end(); ++ci) { suggestedSFs.clear(); if (isAUXSurface) { suggestedSFs = (*ci)->suggestAuxSurfaceFormats(this); } else if (isInterimSurface) { suggestedSFs = (*ci)->suggestInputSurfaceFormats(); } else if (isBindableSurface) { suggestedSFs = std::vector(1, graph()->suggestNwSurfaceFormat(TensorType::kNW_INPUT)); } std::copy(suggestedSFs.begin(), suggestedSFs.end(), std::inserter(consumerProposedSFs, consumerProposedSFs.end())); } // Step-2: Capture surf formats suggested by producer nodes for (Graph::NodeUnorderedSetIterator pi = producers.begin(); pi != producers.end(); ++pi) { suggestedSFs.clear(); if (isInterimSurface) { suggestedSFs = (*pi)->suggestOutputSurfaceFormats(); } else if (isBindableSurface) { suggestedSFs = std::vector(1, graph()->suggestNwSurfaceFormat(TensorType::kNW_OUTPUT)); } std::copy(suggestedSFs.begin(), suggestedSFs.end(), std::inserter(producerProposedSFs, producerProposedSFs.end())); } // Step-3: Find intersection of suggested surf formats from producers and consumers if (isBindableSurface) { std::copy(producerProposedSFs.begin(), producerProposedSFs.end(), std::inserter(proposedSFs, proposedSFs.end())); std::copy(consumerProposedSFs.begin(), consumerProposedSFs.end(), std::inserter(proposedSFs, proposedSFs.end())); } else if (isAUXSurface) { std::copy(consumerProposedSFs.begin(), consumerProposedSFs.end(), std::inserter(proposedSFs, proposedSFs.end())); } else if (isInterimSurface) { for (std::set::iterator csfi = consumerProposedSFs.begin(); csfi != consumerProposedSFs.end(); ++csfi) { if (producerProposedSFs.find(*csfi) != producerProposedSFs.end()) { proposedSFs.insert(*csfi); } } for (std::set::iterator psfi = producerProposedSFs.begin(); psfi != producerProposedSFs.end(); ++psfi) { if (consumerProposedSFs.find(*psfi) != consumerProposedSFs.end()) { proposedSFs.insert(*psfi); } } } // prune the proposed surface formats based on criteria // Criteria-1: prune those SFs that don't fit with #chnls of the TSD for (std::set::iterator sfi = proposedSFs.begin(); sfi != proposedSFs.end(); ) { // allow surface formats that work with any #channels if ((*sfi).channelsPerAtom() == -1) ++sfi; else if ((*sfi).channelsPerAtom() != tsd->dimensions().c) proposedSFs.erase(sfi++); else ++sfi; } if (proposedSFs.size() == 0) { PROPAGATE_ERROR_FAIL(NvDlaError_BadValue, "Couldn't narrow down to suitable SF for %s/%s", id().c_str(), tsd->id().c_str()); } else if (proposedSFs.size() > 1) { gLogInfo << "More than 1 proposed SFs for " << id() << "/" << tsd->id() << endl; for (std::set::iterator sfi = proposedSFs.begin(); sfi != proposedSFs.end(); ++sfi) gLogInfo << (*sfi).c_str() << endl; } //TODO: in future, loop over all proposed sfs and fork graphs for (Graph::NodeUnorderedSetIterator ci = consumers.begin(); ci != consumers.end(); ++ci) { supportedSFs.clear(); if (isAUXSurface) { supportedSFs = (*ci)->supportedAuxSurfFormats(); } else if (isInterimSurface || isBindableSurface) { supportedSFs = (*ci)->supportedInSurfFormats(); } PROPAGATE_ERROR_FAIL((*ci)->supportsSurfaceFormat(*(proposedSFs.begin()), supportedSFs)); } for (Graph::NodeUnorderedSetIterator pi = producers.begin(); pi != producers.end(); ++pi) { supportedSFs.clear(); if (isInterimSurface || isBindableSurface) { supportedSFs = (*pi)->supportedOutSurfFormats(); } PROPAGATE_ERROR_FAIL((*pi)->supportsSurfaceFormat(*(proposedSFs.begin()), supportedSFs)); } ASSERT(proposedSFs.size() >= 1); tsd->setSurfaceFormat(*(proposedSFs.begin())); if ( graph()->debugSurfaces() ) { gLogInfo << id() << " edge setting new surface format " << tsd->surfaceFormat().c_str() << endl; } fail: return e; } /*----------------------Determine Surface Strides----------------------*/ NvDlaError engine_ast::Edge::determineSurfaceStrides() { NvDlaError e = NvDlaSuccess; surface::TensorSurfaceDesc* tsd = tensorSurfaceDesc(); NvU32 commonLS = 0; NvU32 commonSS = 0; Graph::NodeUnorderedSet producers; Graph::NodeUnorderedSet consumers; Graph::NodeUnorderedSet clients; if ( !isDataEdge() ) { goto fail; } else if (!tsd) { ORIGINATE_ERROR_FAIL(NvDlaError_BadValue, "TSD not yet registered for edge %s", id().c_str()); } tsd->resetLineStride(); tsd->resetSurfaceStride(); /* * The readers and writers of a tensor could have differing stride alignment * limitations. DLA supports reading/writing of smaller cubes within a larger cube * provided the strides and dimensions are programmed correctly. * To allow that, the strides for the surface should always represent the larger cube. */ producers = tsd->producers(); consumers = tsd->consumers(); clients.insert(producers.begin(), producers.end()); clients.insert(consumers.begin(), consumers.end()); for (Graph::NodeUnorderedSetIterator cli = clients.begin(); cli != clients.end(); ++cli) { commonLS = std::max(commonLS, (*cli)->suggestLineStride(tsd)); commonSS = std::max(commonSS, (*cli)->suggestSurfaceStride(tsd)); } tsd->setLineStride(commonLS); tsd->setSurfaceStride(commonSS); fail: return e; } NvDlaError engine_ast::Edge::determineSurfaceSize() { NvDlaError e = NvDlaSuccess; surface::TensorSurfaceDesc* tsd = tensorSurfaceDesc(); NvU64 commonSize = 0; Graph::NodeUnorderedSet producers; Graph::NodeUnorderedSet consumers; Graph::NodeUnorderedSet clients; if ( !isDataEdge() ) { goto fail; } else if (!tsd) { ORIGINATE_ERROR_FAIL(NvDlaError_BadValue, "TSD not yet registered for edge %s", id().c_str()); } tsd->resetSize(); /* * The readers and writers of a tensor could have differing stride and size * requirements. DLA supports reading/writing of smaller cubes within a larger cube. * To allow that, the size for the surface should always represent the larger cube. */ producers = tsd->producers(); consumers = tsd->consumers(); clients.insert(producers.begin(), producers.end()); clients.insert(consumers.begin(), consumers.end()); for (Graph::NodeUnorderedSetIterator cli = clients.begin(); cli != clients.end(); ++cli) { commonSize = std::max(commonSize, (*cli)->suggestSurfaceSize(tsd)); } tsd->setSize(commonSize); fail: return e; } NvDlaError engine_ast::Edge::determineSurfaceOffsetInBuffer() { NvDlaError e = NvDlaSuccess; surface::TensorSurfaceDesc* tsd = tensorSurfaceDesc(); NvU64 bufferOffset = 0; Graph::NodeUnorderedSet producers; Graph::NodeUnorderedSet consumers; Graph::NodeUnorderedSet clients; if ( !isDataEdge() ) { goto fail; } else if (!tsd) { ORIGINATE_ERROR_FAIL(NvDlaError_BadValue, "TSD not yet registered for edge %s", id().c_str()); } tsd->resetBufferOffset(); producers = tsd->producers(); consumers = tsd->consumers(); clients.insert(producers.begin(), producers.end()); clients.insert(consumers.begin(), consumers.end()); for (Graph::NodeUnorderedSetIterator cli = clients.begin(); cli != clients.end(); ++cli) { // arguably, all client nodes should report the same surface offset in buffer bufferOffset = std::max(bufferOffset, (*cli)->suggestSurfaceOffsetInBuffer(tsd)); } tsd->setBufferOffset(bufferOffset); fail: return e; } NvDlaError engine_ast::Edge::verifySurfaceClients() { NvDlaError e = NvDlaSuccess; Graph::NodeUnorderedSet producers; Graph::NodeUnorderedSet consumers; Graph::NodeSequence upNodes; Graph::NodeSequence downNodes; Graph::NodeUnorderedSet producerNodes; Graph::NodeUnorderedSet consumerNodes; surface::TensorSurfaceDesc* tsd = tensorSurfaceDesc(); if ( !isDataEdge() ) { goto fail; } else if (!tsd) { ORIGINATE_ERROR_FAIL(NvDlaError_BadValue, "TSD not yet registered for edge %s", id().c_str()); } upNodes = graph()->upstreamNodes(this); producers = tensorSurfaceDesc()->producers(); for (Graph::NodeSequenceIterator uni = upNodes.begin(); uni != upNodes.end(); ++uni) producerNodes.insert(*uni); downNodes = graph()->downstreamNodes(this); consumers = tensorSurfaceDesc()->consumers(); for (Graph::NodeSequenceIterator dni = downNodes.begin(); dni != downNodes.end(); ++dni) consumerNodes.insert(*dni); if (producers != producerNodes) { ORIGINATE_ERROR_FAIL(NvDlaError_BadValue, "Producer nodes (%d) != upstream nodes (%d) for %s", producerNodes.size(), producers.size(), tsd->id().c_str()); } else if (consumers != consumerNodes) { ORIGINATE_ERROR_FAIL(NvDlaError_BadValue, "Consumer nodes (%d) != downstream nodes (%d) for %s", consumerNodes.size(), consumers.size(), tsd->id().c_str()); } fail: return e; } NvDlaError engine_ast::Edge::verifySurfaceFormat() { NvDlaError e = NvDlaSuccess; TensorType tt; surface::SurfaceFormat sf; Graph::NodeUnorderedSet producers; Graph::NodeUnorderedSet consumers; bool isAUXSurface, isInterimSurface, isBindableSurface; surface::TensorSurfaceDesc* tsd = tensorSurfaceDesc(); std::vector supportedSFs; if ( !isDataEdge() ) { goto fail; } tt = originalTensor()->getTensorType(); isAUXSurface = (tt == TensorType::kWEIGHT || tt == TensorType::kBIAS || tt == TensorType::kBATCH_NORM || tt == TensorType::kSCALE); isInterimSurface = (tt == TensorType::kIO || tt == TensorType::kSTREAM || tt == TensorType::kDEBUG); isBindableSurface = (tt == TensorType::kNW_INPUT || tt == TensorType::kNW_OUTPUT); if (!tsd) { ORIGINATE_ERROR_FAIL(NvDlaError_BadValue, "TSD not yet registered for edge %s", id().c_str()); } sf = tsd->surfaceFormat(); if (sf.v() == surface::SurfaceFormatEnum::NVDLA_UNKNOWN_FORMAT) { PROPAGATE_ERROR_FAIL(NvDlaError_BadValue, "Surface format not yet determined for %s", tsd->id().c_str()); } producers = tsd->producers(); consumers = tsd->consumers(); for (Graph::NodeUnorderedSetIterator ci = consumers.begin(); ci != consumers.end(); ++ci) { supportedSFs.clear(); if (isAUXSurface) { supportedSFs = (*ci)->supportedAuxSurfFormats(); } else if (isInterimSurface || isBindableSurface) { supportedSFs = (*ci)->supportedInSurfFormats(); } PROPAGATE_ERROR_FAIL((*ci)->supportsSurfaceFormat(sf, supportedSFs)); } for (Graph::NodeUnorderedSetIterator pi = producers.begin(); pi != producers.end(); ++pi) { supportedSFs.clear(); if (isInterimSurface || isBindableSurface) { supportedSFs = (*pi)->supportedOutSurfFormats(); } PROPAGATE_ERROR_FAIL((*pi)->supportsSurfaceFormat(sf, supportedSFs)); } fail: return e; } NvDlaError engine_ast::Edge::verifySurfaceDims() { NvDlaError e = NvDlaSuccess; surface::TensorSurfaceDesc* tsd = tensorSurfaceDesc(); Graph::NodeUnorderedSet producers; Graph::NodeUnorderedSet consumers; Graph::NodeUnorderedSet clients; if ( !isDataEdge() ) { goto fail; } else if (!tsd) { ORIGINATE_ERROR_FAIL(NvDlaError_BadValue, "TSD not yet registered for edge %s", id().c_str()); } producers = tsd->producers(); consumers = tsd->consumers(); clients.insert(producers.begin(), producers.end()); clients.insert(consumers.begin(), consumers.end()); for (Graph::NodeUnorderedSetIterator cli = clients.begin(); cli != clients.end(); ++cli) { PROPAGATE_ERROR_FAIL( (*cli)->verifySurfaceDims(tsd) ); } fail: return e; } NvDlaError engine_ast::Edge::verifySurfaceStrides() { NvDlaError e = NvDlaSuccess; surface::TensorSurfaceDesc* tsd = tensorSurfaceDesc(); Graph::NodeUnorderedSet producers; Graph::NodeUnorderedSet consumers; Graph::NodeUnorderedSet clients; if ( !isDataEdge() ) { goto fail; } else if (!tsd) { ORIGINATE_ERROR_FAIL(NvDlaError_BadValue, "TSD not yet registered for edge %s", id().c_str()); } /* * The readers and writers of a tensor could have differing stride alignment * limitations. DLA supports reading/writing of smaller cubes within a larger cube * provided the strides and dimensions are programmed correctly. * Verify that, the strides for the surface should always represent the larger cube. */ producers = tsd->producers(); consumers = tsd->consumers(); clients.insert(producers.begin(), producers.end()); clients.insert(consumers.begin(), consumers.end()); for (Graph::NodeUnorderedSetIterator cli = clients.begin(); cli != clients.end(); ++cli) { ASSERT(tsd->lineStride() >= (*cli)->suggestLineStride(tsd)); ASSERT(tsd->surfaceStride() >= (*cli)->suggestSurfaceStride(tsd)); } fail: return e; } NvDlaError engine_ast::Edge::verifySurfaceSize() { NvDlaError e = NvDlaSuccess; surface::TensorSurfaceDesc* tsd = tensorSurfaceDesc(); Graph::NodeUnorderedSet producers; Graph::NodeUnorderedSet consumers; Graph::NodeUnorderedSet clients; if ( !isDataEdge() ) { goto fail; } else if (!tsd) { ORIGINATE_ERROR_FAIL(NvDlaError_BadValue, "TSD not yet registered for edge %s", id().c_str()); } /* * The readers and writers of a tensor could have differing stride alignment * limitations. DLA supports reading/writing of smaller cubes within a larger cube * provided the strides, size and dimensions are programmed correctly. * Verify that, the size for the surface should always represent the larger cube. */ producers = tsd->producers(); consumers = tsd->consumers(); clients.insert(producers.begin(), producers.end()); clients.insert(consumers.begin(), consumers.end()); for (Graph::NodeUnorderedSetIterator cli = clients.begin(); cli != clients.end(); ++cli) { ASSERT(tsd->size() >= (*cli)->suggestSurfaceSize(tsd)); } fail: return e; } NvDlaError engine_ast::Edge::verifySurfaceOffsetInBuffer() { NvDlaError e = NvDlaSuccess; surface::TensorSurfaceDesc* tsd = tensorSurfaceDesc(); Graph::NodeUnorderedSet producers; Graph::NodeUnorderedSet consumers; Graph::NodeUnorderedSet clients; if ( !isDataEdge() ) { goto fail; } else if (!tsd) { ORIGINATE_ERROR_FAIL(NvDlaError_BadValue, "TSD not yet registered for edge %s", id().c_str()); } producers = tsd->producers(); consumers = tsd->consumers(); clients.insert(producers.begin(), producers.end()); clients.insert(consumers.begin(), consumers.end()); for (Graph::NodeUnorderedSetIterator cli = clients.begin(); cli != clients.end(); ++cli) { // all client nodes should report the same surface offset in buffer ASSERT(tsd->bufferOffset() == (*cli)->suggestSurfaceOffsetInBuffer(tsd)); } fail: return e; } NvDlaError engine_ast::Edge::verifySurfaceTensorScales() { NvDlaError e = NvDlaSuccess; Tensor* tensor = originalTensor(); Dims4 tensorDims; std::vector tensorScales; NvF32 perTensorScale; if ( !isDataEdge() ) { goto fail; } else if ( isAuxEdge() ) { goto fail; } else if (graph()->profile()->computePrecision().v() != surface::SurfacePrecisionEnum::NVDLA_PRECISION_INT8) { goto fail; } else if (!tensor) { ORIGINATE_ERROR_FAIL(NvDlaError_BadValue, "Tensor not yet registered for edge %s", id().c_str()); } if (graph()->profile()->tensorScalingMode().v() != nvdla::TensorScalingMode::PER_TENSOR) { ORIGINATE_ERROR_FAIL(NvDlaError_NotSupported, "Don't support any tensor scaling mode other " " than PER_TENSOR for this network\n"); } tensorDims = tensor->getDimensions(); tensorScales = tensor->getChannelScales(); ASSERT (tensorScales.size() == static_cast(tensorDims.c)); perTensorScale = tensorScales.at(0); for (int cc = 0; cc < tensorDims.c; ++cc) { ASSERT (tensorScales.at(cc) != 0); ASSERT (!std::isnan(tensorScales.at(cc))); ASSERT (!std::isinf(tensorScales.at(cc))); ASSERT (tensorScales.at(cc) == perTensorScale); } fail: return e; } NvDlaError engine_ast::Edge::verifySurface() { NvDlaError e = NvDlaSuccess; /* Verify that the producers and consumers of the tsd are * the same as the physical upstream and downstream nodes */ PROPAGATE_ERROR_FAIL( verifySurfaceClients() ); /* Verify that the surface format determined for the tsd are * compatible with all the node(s) operating on it. */ PROPAGATE_ERROR_FAIL( verifySurfaceFormat() ); /* Verify that none of the node(s) changed the dims of any tsd, * such that the node(s) on the other end of that tsd couln't * operate on it anymore */ PROPAGATE_ERROR_FAIL( verifySurfaceDims() ); /* Verify that the surface strides determined for the tsd are * compatible with all the node(s) operating on it. */ PROPAGATE_ERROR_FAIL( verifySurfaceStrides() ); /* Verify that the size determined for the tsd are * compatible with all the node(s) operating on it. */ PROPAGATE_ERROR_FAIL( verifySurfaceSize() ); /* Verify that the surface offset determined in the buffer * for the tsd is compatible with all the node(s) operating on it. */ PROPAGATE_ERROR_FAIL( verifySurfaceOffsetInBuffer() ); /* Verify that each tensor has channel scales set and * that they are valid */ PROPAGATE_ERROR_FAIL( verifySurfaceTensorScales() ); fail: return e; } /*----------------------I/O Buffer Descriptor Registration------------*/ NvDlaError engine_ast::Edge::registerBuffer() { NvDlaError e = NvDlaError_Success; typedef memory::TensorBufferDesc TBD; surface::TensorSurfaceDesc *tsd; Graph::NodeUnorderedSet producers; Graph::NodeUnorderedSet consumers; Graph::NodeUnorderedSet clients; TBD* currTBD = NULL; TBD* commonTBD = NULL; std::map clientBufferMap; tsd = tensorSurfaceDesc(); if ( !isDataEdge() ) { goto fail; } else if (!tsd) { ORIGINATE_ERROR_FAIL(NvDlaError_BadValue, "TSD not yet registered for edge %s", id().c_str()); } else if ( tsd->tensorCategory().v() == memory::TensorCategoryEnum::UNKNOWN_TENSOR ) { ORIGINATE_ERROR_FAIL(NvDlaError_BadParameter, "Edge %s has 'unknown' tensor category", tsd->id().c_str()); } producers = tsd->producers(); consumers = tsd->consumers(); clients.insert(producers.begin(), producers.end()); clients.insert(consumers.begin(), consumers.end()); commonTBD = tsd->tensorBufferDesc(); if ( !commonTBD ) { Graph::NodeUnorderedSetIterator cli; for (cli = clients.begin(); cli != clients.end(); ++cli) { if ((*cli)->isSoftwareNode()) { commonTBD = (*cli)->suggestBuffer(tsd); break; } } // Step-1: If there's a software client, prefer its suggested TBD // don't bother querying the TBDs from non-software clients if (commonTBD) { tsd->setTensorBufferDesc(commonTBD); } // Step-2: If there's no software client, assert that all clients suggested 1 common TBD else { for (cli = clients.begin(); cli != clients.end(); ++cli) { currTBD = (*cli)->suggestBuffer(tsd); if (cli == clients.begin()) { commonTBD = currTBD; tsd->setTensorBufferDesc(commonTBD); } else { ASSERT(currTBD == commonTBD); } } } } PROPAGATE_ERROR_FAIL( commonTBD->addSurface(tsd) ); if ( graph()->debugBuffers() ) { gLogInfo << commonTBD->id() << " for " << tsd->id() << " for " << id() << " with " << tsd->surfaceFormat().c_str() << endl; } fail: return e; } NvDlaError engine_ast::Edge::verifyBuffer() { NvDlaError e = NvDlaError_Success; surface::TensorSurfaceDesc *tsd; Graph::NodeUnorderedSet producers; Graph::NodeUnorderedSet consumers; Graph::NodeUnorderedSet clients; tsd = tensorSurfaceDesc(); if ( !isDataEdge() ) { goto fail; } else if (!tsd) { ORIGINATE_ERROR_FAIL(NvDlaError_BadValue, "TSD not yet registered for edge %s", id().c_str()); } else if ( tsd->tensorCategory().v() == memory::TensorCategoryEnum::UNKNOWN_TENSOR ) { ORIGINATE_ERROR_FAIL(NvDlaError_BadParameter, "Edge %s has 'unknown' tensor category", tsd->id().c_str()); } producers = tsd->producers(); consumers = tsd->consumers(); clients.insert(producers.begin(), producers.end()); clients.insert(consumers.begin(), consumers.end()); for (Graph::NodeUnorderedSetIterator cli = clients.begin(); cli != clients.end(); ++cli) { // all client nodes should report the same buffer ASSERT(tsd->tensorBufferDesc() == (*cli)->suggestBuffer(tsd)); } fail: return e; } /*----------------------I/O Buffer Reservation-------------------------*/ /* idempotent */ NvDlaError engine_ast::Edge::reserveBuffer() { NvDlaError e = NvDlaError_Success; NvU64 existingSize = 0; NvU64 proposedSize = 0; memory::TensorCategory tc; memory::TensorBufferDesc* tbd; surface::TensorSurfaceDesc* tsd = tensorSurfaceDesc(); NvU16 numBatches = graph()->profile()->multiBatchSize(); if ( !isDataEdge() ) { goto fail; } else if (!tsd) { ORIGINATE_ERROR_FAIL(NvDlaError_BadValue, "TSD not yet registered for edge %s", id().c_str()); } else if (!tsd->size()) { ORIGINATE_ERROR_FAIL(NvDlaError_BadValue, "surface size == 0 for %s", tsd->id().c_str()); } tbd = tsd->tensorBufferDesc(); tc = tsd->tensorCategory(); existingSize = tbd->size(); proposedSize = tsd->size(); switch(tc.v()) { case memory::TensorCategoryEnum::GLOBAL_TENSOR: case memory::TensorCategoryEnum::LOCAL_TENSOR: tbd->setSize( std::max(existingSize, proposedSize) ); break; case memory::TensorCategoryEnum::EXTERNAL_TENSOR: ASSERT( bindable() ); // adjust buffer size for multiple batches on the bindable tensor if ( existingSize ) { tbd->setSize( std::max(existingSize, proposedSize * numBatches) ); } else { tbd->setSize(proposedSize * numBatches); } break; case memory::TensorCategoryEnum::STREAM_TENSOR: tbd->setMemoryLoc(memory::LocationEnum::lSTREAM); break; default: ORIGINATE_ERROR_FAIL(NvDlaError_BadValue, "Tensor Category:%s not recognized", tc.c_str()); } fail: return e; } /*----------------------Handle Multi Batch-----------------------------*/ NvDlaError engine_ast::Edge::handleMultiBatch() { NvDlaError e = NvDlaSuccess; surface::TensorSurfaceDesc* mbTSD = tensorSurfaceDesc(); NvU32 numBatches = graph()->profile()->multiBatchSize(); if ( !isDataEdge() ) { goto fail; } else if (!mbTSD) { ORIGINATE_ERROR_FAIL(NvDlaError_BadValue, "TSD not yet registered for edge %s", id().c_str()); } if ( bindable() ) { NvU64 offsetInBindableBuffer = 0; if ( mbTSD->dimensions().n != (NvS32)numBatches ) { ORIGINATE_ERROR_FAIL(NvDlaError_BadParameter, "Nw edge %s doesn't represent a multi batch bindable tensor", id().c_str()); } for (NvU16 nn = 0; nn < numBatches; ++nn) { // for a bindable tensor surf desc, different batches scribble at different offsets in the same buffer mbTSD->setBufferOffset(offsetInBindableBuffer, nn); offsetInBindableBuffer += mbTSD->size(); } } else { memory::Location firstBatchMemLoc = mbTSD->tensorBufferDesc()->memoryLoc(0); NvU64 offsetInNonBindableBuffer = mbTSD->bufferOffset(/*batchId*/0); if ( !isAuxEdge() && mbTSD->dimensions().n != 1 ) { // FIXME: allow true NCHW contiguous multibatch for intermediate tensors as well. atleast for FC first ORIGINATE_ERROR_FAIL(NvDlaError_NotSupported, "Contiguous multi-batch non-bindable tensor at %s/%s is not yet supported", id().c_str(), mbTSD->id().c_str()); } for ( NvU16 nn = 0; nn < numBatches; ++nn ) { /* For a non-bindable tensor surf desc, different batches scribble at same offset in different buffers * If a non-bindable tensor shares the buffer with a bindable tensor, then account for the existing offsets * of each batch in the NCHW bindable tensor. */ NvU64 batchOffsetInBindableBuffer = mbTSD->tensorBufferDesc()->boundSurface(0) ? mbTSD->tensorBufferDesc()->boundSurface(0)->bufferOffset(nn) : 0; mbTSD->setBufferOffset(batchOffsetInBindableBuffer + offsetInNonBindableBuffer, nn); mbTSD->tensorBufferDesc()->setMemoryLoc(firstBatchMemLoc, nn); } } fail: return e; } }; // nvdla::priv:: }; // nvdla:: mariusbancila/dotnetinstaller // ExtractCabDlg.cpp : implementation file // #include "stdafx.h" #include "dotNetInstaller.h" #include "InstallStatus.h" #include "ExtractCabDlg.h" IMPLEMENT_DYNAMIC(ExtractCabDlg, CDialog) ExtractCabDlg::ExtractCabDlg(CWnd * pParent) : CDialog(ExtractCabDlg::IDD, pParent) , m_iTimer(0) { } ExtractCabDlg::~ExtractCabDlg() { } void ExtractCabDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); DDX_Control(pDX, IDC_HELP_INSTALL, m_InstallMessage); DDX_Control(pDX, IDC_BUSYCONTROL, m_BusyControl); } BEGIN_MESSAGE_MAP(ExtractCabDlg, CDialog) ON_MESSAGE(WM_USER_SETSTATUSINSTALL, OnSetStatusInstall) ON_WM_TIMER() END_MESSAGE_MAP() // ExtractCabDlg message handlers void ExtractCabDlg::LoadComponent(const ConfigurationPtr& configuration, const ExtractCabProcessorPtr& component) { m_Configuration = configuration; m_Component = component; } void ExtractCabDlg::OnBnClickedSkip() { OnCancel(); } void ExtractCabDlg::OnCancel() { if (get(m_Component) != NULL) { m_Component->cancelled = true; } } void ExtractCabDlg::OnTimer(UINT nIDEvent) { try { if (get(m_Component) != NULL) { if (m_Component->IsExecuting() == false && m_iTimer != 0) { m_BusyControl.End(); KillTimer(m_iTimer); m_iTimer = 0; OnOK(); } } } catch(...) { _ASSERT(false); } CDialog::OnTimer(nIDEvent); } BOOL ExtractCabDlg::OnInitDialog() { CDialog::OnInitDialog(); m_BusyControl.SetNumSteps(16); m_BusyControl.SetSpeed(100); m_BusyControl.SetMode(BPC_MODE_BUSY); m_BusyControl.SetColBlockFace( RGB(255, 255, 255) ); m_BusyControl.SetColBlockFaceHi( GetSysColor(COLOR_HIGHLIGHT) ); m_BusyControl.SetBusyType( BPC_BUSY_PINGPONG ); m_BusyControl.SetColBlockEdge( RGB(0, 0, 0) ); m_BusyControl.SetColBlockEdgeHi( RGB(0, 0, 0) ); m_BusyControl.Recalc(); m_BusyControl.Start(); InstallConfiguration * p_configuration = reinterpret_cast(get(m_Configuration)); CHECK_BOOL(p_configuration != NULL, L"Invalid configuration"); SetWindowText(p_configuration->cab_dialog_caption.GetValue().c_str()); std::wstring l_tmp = DVLib::FormatMessage(const_cast( p_configuration->cab_dialog_message.GetValue().c_str()), p_configuration->cab_dialog_caption.GetValue().c_str()); m_InstallMessage.SetWindowText(l_tmp.c_str()); m_iTimer = this->SetTimer(1,1000,NULL); return TRUE; } // WM_USER_SETSTATUSINSTALL afx_msg LRESULT ExtractCabDlg::OnSetStatusInstall(WPARAM wParam, LPARAM /*lParam*/) { if (wParam != NULL) { InstallStatusPtr status(reinterpret_cast(wParam)); InstallConfiguration * p_configuration = reinterpret_cast(get(m_Configuration)); CHECK_BOOL(p_configuration != NULL, L"Invalid configuration"); std::wstring tmp = DVLib::FormatMessage(const_cast( p_configuration->cab_dialog_message.GetValue().c_str()), status->status.c_str()); m_InstallMessage.SetWindowText(tmp.c_str()); } return 0; } arangod/IResearch/IResearchViewOptimizerRules.cpp //////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2017 ArangoDB GmbH, Cologne, Germany /// /// 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. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author /// @author //////////////////////////////////////////////////////////////////////////////// #include "IResearchViewOptimizerRules.h" #include "IResearchViewNode.h" #include "IResearchFilterFactory.h" #include "IResearchOrderFactory.h" #include "AqlHelper.h" #include "Aql/ExecutionNode.h" #include "Aql/ExecutionPlan.h" #include "Aql/ClusterNodes.h" #include "Aql/Condition.h" #include "Aql/Query.h" #include "Aql/SortNode.h" #include "Aql/Optimizer.h" #include "Aql/WalkerWorker.h" #include "Cluster/ServerState.h" #include "Utils/CollectionNameResolver.h" #include "VocBase/LogicalCollection.h" using namespace arangodb::iresearch; using namespace arangodb::aql; using EN = arangodb::aql::ExecutionNode; namespace { size_t numberOfShards( arangodb::CollectionNameResolver const& resolver, arangodb::LogicalView const& view ) { size_t numberOfShards = 0; auto visitor = [&numberOfShards]( arangodb::LogicalCollection const& collection ) noexcept { numberOfShards += collection.numberOfShards(); return true; }; resolver.visitCollections(visitor, view.id()); return numberOfShards; } std::vector buildSort( ExecutionPlan const& plan, arangodb::aql::Variable const& ref, std::vector> const& sorts, std::unordered_map const& vars, bool scorersOnly ) { std::vector entries; QueryContext const ctx { nullptr, nullptr, nullptr, nullptr, &ref }; for (auto& sort : sorts) { auto const* var = sort.first; auto varId = var->id; AstNode const* rootNode = nullptr; auto it = vars.find(varId); if (it != vars.end()) { auto const* node = rootNode = it->second; while (node && NODE_TYPE_ATTRIBUTE_ACCESS == node->type) { node = node->getMember(0); } if (node && NODE_TYPE_REFERENCE == node->type) { var = reinterpret_cast(node->getData()); } } else { auto const* setter = plan.getVarSetBy(varId); if (setter && EN::CALCULATION == setter->getType()) { auto const* expr = static_cast(setter)->expression(); if (expr) { rootNode = expr->node(); } } } if (var && rootNode && (!scorersOnly || OrderFactory::scorer(nullptr, *rootNode, ctx))) { entries.emplace_back(var, rootNode, sort.second); } } return entries; } bool addView( arangodb::LogicalView const& view, arangodb::aql::Query& query ) { auto* collections = query.collections(); if (!collections) { return false; } // linked collections auto visitor = [collections](TRI_voc_cid_t cid) { collections->add( arangodb::basics::StringUtils::itoa(cid), arangodb::AccessMode::Type::READ ); return true; }; return view.visitCollections(visitor); } /////////////////////////////////////////////////////////////////////////////// /// @class IResearchViewConditionFinder /////////////////////////////////////////////////////////////////////////////// class IResearchViewConditionFinder final : public arangodb::aql::WalkerWorker { public: IResearchViewConditionFinder( ExecutionPlan* plan, std::unordered_map* changes, bool* hasEmptyResult) noexcept : _plan(plan), _changes(changes), _hasEmptyResult(hasEmptyResult) { } virtual bool before(ExecutionNode*) override; virtual bool enterSubquery(ExecutionNode*, ExecutionNode*) override { return false; } private: bool handleFilterCondition( ExecutionNode* en, Condition& condition ); ExecutionPlan* _plan; std::unordered_map _variableDefinitions; std::unordered_set _filters; std::vector> _sorts; // note: this class will never free the contents of this map std::unordered_map* _changes; bool* _hasEmptyResult; }; // IResearchViewConditionFinder bool IResearchViewConditionFinder::before(ExecutionNode* en) { switch (en->getType()) { case EN::LIMIT: // LIMIT invalidates the sort expression we already found _sorts.clear(); _filters.clear(); break; case EN::SINGLETON: case EN::NORESULTS: // in all these cases we better abort return true; case EN::FILTER: { std::vector invars(en->getVariablesUsedHere()); TRI_ASSERT(invars.size() == 1); // register which variable is used in a FILTER _filters.emplace(invars[0]->id); break; } case EN::SORT: { // register which variables are used in a SORT if (_sorts.empty()) { for (auto& it : EN::castTo(en)->elements()) { _sorts.emplace_back(it.var, it.ascending); TRI_IF_FAILURE("IResearchViewConditionFinder::sortNode") { THROW_ARANGO_EXCEPTION(TRI_ERROR_DEBUG); } } } break; } case EN::CALCULATION: { auto outvars = en->getVariablesSetHere(); TRI_ASSERT(outvars.size() == 1); _variableDefinitions.emplace( outvars[0]->id, EN::castTo(en)->expression()->node()); TRI_IF_FAILURE("IResearchViewConditionFinder::variableDefinition") { THROW_ARANGO_EXCEPTION(TRI_ERROR_DEBUG); } break; } case EN::ENUMERATE_IRESEARCH_VIEW: { auto node = EN::castTo(en); auto& view = *node->view(); // add view and linked collections to the query TRI_ASSERT(_plan && _plan->getAst() && _plan->getAst()->query()); if (!addView(view, *_plan->getAst()->query())) { THROW_ARANGO_EXCEPTION_MESSAGE( TRI_ERROR_QUERY_PARSE, "failed to process all collections linked with the view '" + view.name() + "'" ); } if (_changes->find(node->id()) != _changes->end()) { // already optimized this node break; } Condition filterCondition(_plan->getAst()); if (!handleFilterCondition(en, filterCondition)) { break; } auto sortCondition = buildSort( *_plan, node->outVariable(), _sorts, _variableDefinitions, true // node->isInInnerLoop() // build scorers only in case if we're inside a loop ); if (filterCondition.isEmpty() && sortCondition.empty()) { // no conditions left break; } auto const canUseView = !filterCondition.root() || FilterFactory::filter( nullptr, { nullptr, nullptr, nullptr, nullptr, &node->outVariable() }, *filterCondition.root() ); if (canUseView) { auto newNode = std::make_unique( *_plan, _plan->nextId(), node->vocbase(), node->view(), node->outVariable(), filterCondition.root(), std::move(sortCondition) ); TRI_IF_FAILURE("IResearchViewConditionFinder::insertViewNode") { THROW_ARANGO_EXCEPTION(TRI_ERROR_DEBUG); } // We keep this node's change _changes->emplace(node->id(), newNode.get()); newNode.release(); } else { THROW_ARANGO_EXCEPTION_MESSAGE(TRI_ERROR_QUERY_PARSE, "filter clause " "not yet supported with view"); } break; } default: // in these cases we simply ignore the intermediate nodes, note // that we have taken care of nodes that could throw exceptions // above. break; } return false; } bool IResearchViewConditionFinder::handleFilterCondition( ExecutionNode* en, Condition& condition) { bool foundCondition = false; for (auto& it : _variableDefinitions) { if (_filters.find(it.first) != _filters.end()) { // a variable used in a FILTER AstNode* var = const_cast(it.second); if (!var->canThrow() && var->isDeterministic() && var->isSimple()) { // replace all variables inside the FILTER condition with the // expressions represented by the variables var = it.second->clone(_plan->getAst()); auto func = [this](AstNode* node) -> AstNode* { if (node->type == NODE_TYPE_REFERENCE) { auto variable = static_cast(node->getData()); if (variable != nullptr) { auto setter = _plan->getVarSetBy(variable->id); if (setter != nullptr && setter->getType() == EN::CALCULATION) { auto s = EN::castTo(setter); auto filterExpression = s->expression(); AstNode* inNode = filterExpression->nodeForModification(); if (!inNode->canThrow() && inNode->isDeterministic() && inNode->isSimple()) { return inNode; } } } } return node; }; var = Ast::traverseAndModify(var, func); } condition.andCombine(var); foundCondition = true; } } // normalize the condition condition.normalize(_plan); TRI_IF_FAILURE("ConditionFinder::normalizePlan") { THROW_ARANGO_EXCEPTION(TRI_ERROR_DEBUG); } bool const conditionIsImpossible = (foundCondition && condition.isEmpty()); if (conditionIsImpossible) { // condition is always false for (auto const& x : en->getParents()) { auto noRes = new NoResultsNode(_plan, _plan->nextId()); _plan->registerNode(noRes); _plan->insertDependency(x, noRes); *_hasEmptyResult = true; } return false; } auto const& varsValid = en->getVarsValid(); // remove all invalid variables from the condition if (condition.removeInvalidVariables(varsValid)) { // removing left a previously non-empty OR block empty... // this means we can't use the index to restrict the results return false; } return true; } } NS_BEGIN(arangodb) NS_BEGIN(iresearch) /// @brief move filters and sort conditions into views void handleViewsRule( arangodb::aql::Optimizer* opt, std::unique_ptr plan, arangodb::aql::OptimizerRule const* rule ) { SmallVector::allocator_type::arena_type a; SmallVector nodes{a}; std::unordered_map changes; auto cleanupChanges = [&changes](){ for (auto& v : changes) { delete v.second; } }; TRI_DEFER(cleanupChanges()); // newly created view nodes (replacement) std::unordered_set createdViewNodes; // try to find `EnumerateViewNode`s and push corresponding filters and sorts inside plan->findEndNodes(nodes, true); bool hasEmptyResult = false; for (auto const& n : nodes) { IResearchViewConditionFinder finder(plan.get(), &changes, &hasEmptyResult); n->walk(finder); } createdViewNodes.reserve(changes.size()); for (auto& it : changes) { auto*& node = it.second; if (!node || ExecutionNode::ENUMERATE_IRESEARCH_VIEW != node->getType()) { // filter out invalid nodes continue; } plan->registerNode(node); plan->replaceNode(plan->getNodeById(it.first), node); // necessary here, because replaceNode will set "varUsageComputed" to false // however, we want to keep the *original* variable definitions here (e.g. // CalculationNodes create the sort and filter statements and not the // EnumerateViewNode). If we recalculated the variable usage here, from now // on the EnumerateViewNode would produce the sort and filter variables, and // the below logic (that filters on the variable setters being CalculationNodes) // would fail plan->setVarUsageComputed(); createdViewNodes.insert(node); // prevent double deletion by cleanupChanges() node = nullptr; } if (!changes.empty()) { std::unordered_set toUnlink; // remove filters covered by a view nodes.clear(); // ensure array is empty plan->findNodesOfType(nodes, ExecutionNode::FILTER, true); // `createdViewNodes` will not change auto const noMatch = createdViewNodes.end(); for (auto* node : nodes) { TRI_ASSERT(node); // find the node with the filter expression auto inVar = EN::castTo(node)->getVariablesUsedHere(); TRI_ASSERT(inVar.size() == 1); auto setter = plan->getVarSetBy(inVar[0]->id); if (!setter || setter->getType() != EN::CALCULATION) { continue; } auto const it = createdViewNodes.find(setter->getLoop()); if (it != noMatch) { toUnlink.emplace(node); toUnlink.emplace(setter); EN::castTo(setter)->canRemoveIfThrows(true); } } // FIXME remove all sorts in case if view doesn't located inside a loop, // otherwise remove setters for covered sorts // remove setters covered by a view internally for (auto* node : createdViewNodes) { TRI_ASSERT(node); auto& viewNode = *EN::castTo(node); for (auto const& sort : viewNode.sortCondition()) { auto const* var = sort.var; if (!var) { continue; } auto* setter = plan->getVarSetBy(var->id); if (!setter || EN::CALCULATION != setter->getType()) { continue; } toUnlink.emplace(setter); EN::castTo(setter)->canRemoveIfThrows(true); } } // nodes.clear(); // ensure array is empty // plan->findNodesOfType(nodes, ExecutionNode::SORT, true); // // for (auto* node : nodes) { // // find the node with the sort expression // auto inVar = static_cast(node)->getVariablesUsedHere(); // TRI_ASSERT(!inVar.empty()); // // for (auto& var : inVar) { // auto setter = plan->getVarSetBy(var->id); // // if (!setter || setter->getType() != ExecutionNode::CALCULATION) { // continue; // } // // auto const it = createdViewNodes.find(setter->getLoop()); // // if (it != noMatch) { // if (!(*it)->isInInnerLoop()) { // toUnlink.emplace(node); // toUnlink.emplace(setter); // } ////FIXME uncomment when EnumerateViewNode can create variables //// toUnlink.emplace(setter); //// if (!(*it)->isInInnerLoop()) { //// toUnlink.emplace(node); //// } // static_cast(setter)->canRemoveIfThrows(true); // } // } // } // plan->unlinkNodes(toUnlink); } opt->addPlan(std::move(plan), rule, !changes.empty()); } void scatterViewInClusterRule( arangodb::aql::Optimizer* opt, std::unique_ptr plan, arangodb::aql::OptimizerRule const* rule ) { TRI_ASSERT(arangodb::ServerState::instance()->isCoordinator()); bool wasModified = false; SmallVector::allocator_type::arena_type a; SmallVector nodes{a}; // find subqueries std::unordered_map subqueries; plan->findNodesOfType(nodes, ExecutionNode::SUBQUERY, true); for (auto& it : nodes) { subqueries.emplace( EN::castTo(it)->getSubquery(), it ); } // we are a coordinator. now look in the plan for nodes of type // EnumerateIResearchViewNode nodes.clear(); plan->findNodesOfType(nodes, ExecutionNode::ENUMERATE_IRESEARCH_VIEW, true); TRI_ASSERT( plan->getAst() && plan->getAst()->query() && plan->getAst()->query()->trx() ); auto* resolver = plan->getAst()->query()->trx()->resolver(); TRI_ASSERT(resolver); for (auto* node : nodes) { TRI_ASSERT(node); auto& viewNode = *EN::castTo(node); if (viewNode.empty()) { // FIXME we have to invalidate plan cache (if exists) // in case if corresponding view has been modified // view has no associated collection, nothing to scatter continue; } auto const& parents = node->getParents(); auto const& deps = node->getDependencies(); TRI_ASSERT(deps.size() == 1); // don't do this if we are already distributing! if (deps[0]->getType() == ExecutionNode::REMOTE) { auto const* firstDep = deps[0]->getFirstDependency(); if (!firstDep || firstDep->getType() == ExecutionNode::DISTRIBUTE) { continue; } } if (plan->shouldExcludeFromScatterGather(node)) { continue; } auto& vocbase = viewNode.vocbase(); auto& view = *viewNode.view(); bool const isRootNode = plan->isRoot(node); plan->unlinkNode(node, true); // insert a scatter node auto scatterNode = plan->registerNode( std::make_unique( plan.get(), plan->nextId() )); TRI_ASSERT(!deps.empty()); scatterNode->addDependency(deps[0]); // insert a remote node auto* remoteNode = plan->registerNode( std::make_unique( plan.get(), plan->nextId(), &vocbase, "", "", "" )); TRI_ASSERT(scatterNode); remoteNode->addDependency(scatterNode); node->addDependency(remoteNode); // re-link with the remote node // insert another remote node remoteNode = plan->registerNode( std::make_unique( plan.get(), plan->nextId(), &vocbase, "", "", "" )); TRI_ASSERT(node); remoteNode->addDependency(node); // insert gather node auto const sortMode = GatherNode::evaluateSortMode( numberOfShards(*resolver, view) ); auto* gatherNode = plan->registerNode( std::make_unique( plan.get(), plan->nextId(), sortMode )); TRI_ASSERT(remoteNode); gatherNode->addDependency(remoteNode); // and now link the gather node with the rest of the plan if (parents.size() == 1) { parents[0]->replaceDependency(deps[0], gatherNode); } // check if the node that we modified was at the end of a subquery auto it = subqueries.find(node); if (it != subqueries.end()) { auto* subQueryNode = EN::castTo((*it).second); subQueryNode->setSubquery(gatherNode, true); } if (isRootNode) { // if we replaced the root node, set a new root node plan->root(gatherNode); } wasModified = true; } opt->addPlan(std::move(plan), rule, wasModified); } NS_END // iresearch NS_END // arangodb // ----------------------------------------------------------------------------- // --SECTION-- END-OF-FILE // ----------------------------------------------------------------------------- 1-10 // Copyright (c) 2001-2010 // http://spirit.sourceforge.net/ // // 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 BOOST_SPIRIT_SCOPED_ENUM_EMULATION_HPP #define BOOST_SPIRIT_SCOPED_ENUM_EMULATION_HPP #if defined(_MSC_VER) #pragma once #endif #include #include #if BOOST_VERSION >= 104000 # include #else # if !defined(BOOST_NO_SCOPED_ENUMS) # define BOOST_NO_SCOPED_ENUMS # endif # define BOOST_SCOPED_ENUM_START(name) struct name { enum enum_type # define BOOST_SCOPED_ENUM_END }; # define BOOST_SCOPED_ENUM(name) name::enum_type #endif #endif tests/helics/application_api/application-api-tests.cpp /* Copyright (c) 2017-2019, Battelle Memorial Institute; Lawrence Livermore National Security, LLC; Alliance for Sustainable Energy, LLC. See the top-level NOTICE for additional details. All rights reserved. SPDX-License-Identifier: BSD-3-Clause */ //#include #include "helics/helics-config.h" #include //#include #ifndef BOOST_STATIC #define BOOST_TEST_DYN_LINK #endif #define BOOST_TEST_MODULE application_api_tests #define BOOST_TEST_DETECT_MEMORY_LEAK 0 #include struct globalTestConfig { globalTestConfig () = default; ~globalTestConfig () { // std::cout << "cleaning up" << std::endl; helics::cleanupHelicsLibrary (); // std::cout << "finished cleaning up" << std::endl; } }; //____________________________________________________________________________// BOOST_GLOBAL_FIXTURE (globalTestConfig); jeyboy/palyo2 #include "tabdialog.h" #include "ui_tabdialog.h" CBHash TabDialog::VKSettings(int uid) { CBHash res; res.insert("d", 0); res.insert("i", 0); res.insert("p", 1); res.insert("t", VIEW_VK); res.insert("uid", uid); return res; } CBHash TabDialog::soundcloudSettings(int uid) { CBHash res; res.insert("d", 0); res.insert("i", 0); res.insert("p", 1); res.insert("t", VIEW_SOUNDCLOUD); res.insert("uid", uid); return res; } TabDialog::TabDialog(QWidget *parent) : QDialog(parent), ui(new Ui::TabDialog) { ui->setupUi(this); setWindowTitle("Tab settings"); ui -> interactive -> setEnabled(false); ui -> isVkRadio -> setEnabled(false); } TabDialog::~TabDialog() { delete ui; } QString TabDialog::getName() { return ui ->tabName ->text(); } void TabDialog::setName(QString name) { ui -> tabName -> setText(name); } CBHash TabDialog::getSettings() { CBHash res; res.insert("d", ui -> deleteFile -> checkState() == Qt::Checked ? 1 : 0); res.insert("i", ui -> interactive -> checkState() == Qt::Checked ? 1 : 0); res.insert("p", ui -> playlist -> checkState() == Qt::Checked ? 1 : 0); if (ui -> isListRadio -> isChecked()) res.insert("t", VIEW_LIST); else if (ui -> isOneLevelTreeRadio -> isChecked()) res.insert("t", VIEW_LEVEL_TREE); else if (ui -> isTreeRadio -> isChecked()) res.insert("t", VIEW_TREE); else if (ui -> isOneLevelTreeBreadcrumbRadio -> isChecked()) res.insert("t", VIEW_LEVEL_TREE_BREADCRUMB); else res.insert("t", VIEW_VK); return res; } void TabDialog::setSettings(CBHash hash) { ui -> deleteFile -> setChecked(hash.value("d") == 1); ui -> interactive -> setChecked(hash.value("i") == 1); ui -> playlist -> setChecked(hash.value("p") == 1); ui -> isListRadio -> setChecked(hash.value("t") == VIEW_LIST); ui -> isOneLevelTreeRadio -> setChecked(hash.value("t") == VIEW_LEVEL_TREE); ui -> isOneLevelTreeBreadcrumbRadio -> setChecked(hash.value("t") == VIEW_LEVEL_TREE_BREADCRUMB); ui -> isVkRadio -> setChecked(hash.value("t") == VIEW_VK); ui -> isTreeRadio -> setChecked(hash.value("t") == VIEW_TREE); ui -> isListRadio -> setEnabled(false); ui -> isTreeRadio -> setEnabled(false); ui -> isOneLevelTreeRadio -> setEnabled(false); ui -> isOneLevelTreeBreadcrumbRadio -> setEnabled(false); ui -> isVkRadio -> setEnabled(false); } const int MAX_CHARS = 26; class Trie { public: /** Initialize your data structure here. */ Trie() { for (int i = 0; i < MAX_CHARS; i++) { children[i] = nullptr; } } /** Inserts a word into the trie. */ void insert(string word) { Trie* cur = this; for (int i = 0; i < word.size(); i++) { int ind = word[i] - 'a'; if (cur->children[ind] == nullptr) { cur->children[ind] = new Trie(); } cur = cur->children[ind]; } cur->isEndOfWord = true; } /** Returns if the word is in the trie. */ bool search(string word) { Trie* cur = this; for (int i = 0; i < word.size(); i++) { int ind = word[i] - 'a'; if (cur->children[ind] == nullptr) { return false; } cur = cur->children[ind]; } return cur->isEndOfWord; } /** Returns if there is any word in the trie that starts with the given prefix. */ bool startsWith(string prefix) { Trie* cur = this; for (int i = 0; i < prefix.size(); i++) { int ind = prefix[i] - 'a'; if (cur->children[ind] == nullptr) { return false; } cur = cur->children[ind]; } return true; } private: Trie* children[MAX_CHARS]; bool isEndOfWord = false; }; /** * Your Trie object will be instantiated and called as such: * Trie* obj = new Trie(); * obj->insert(word); * bool param_2 = obj->search(word); * bool param_3 = obj->startsWith(prefix); */#include #include #include using namespace std; void print(vector< vector > A) { int n = A.size(); for (int i=0; i >& A) { int n = A.size(); for (int i=0; i maxEl) { maxEl = A[k][i]; maxRow = k; } } // Swap maximum row with current row (column by column) for (int k=i; k<2*n;k++) { double tmp = A[maxRow][k]; A[maxRow][k] = A[i][k]; A[i][k] = tmp; } // Make all rows below this one 0 in current column for (int k=i+1; k=0; i--) { for (int k=n; k<2*n;k++) { A[i][k] /= A[i][i]; } // this is not necessary, but the output looks nicer: A[i][i] = 1; for (int rowModify=i-1;rowModify>=0; rowModify--) { for (int columModify=n;columModify<2*n;columModify++) { A[rowModify][columModify] -= A[i][columModify] * A[rowModify][i]; } // this is not necessary, but the output looks nicer: A[rowModify][i] = 0; } } } int main() { int n; cin >> n; vector line(2*n,0); vector< vector > A(n,line); // Read input data for (int i=0; i> A[i][j]; } } for (int i=0; i(tally); const uint32_t* share_ptr = reinterpret_cast(share); uint32_t* dst_ptr = reinterpret_cast(dst); size_t ptr_sz = sz / sizeof(uint32_t); for (size_t i = 0; i < ptr_sz; i++) { dst_ptr[i] = tally_ptr[i] ^ share_ptr[i]; } } } // namespace std::vector GenerateAdditiveSecretShares(size_t n) { std::vector shares; preshare_t acc{}; // 0-initialized. for (size_t i = 0; i < n - 1; i++) { shares.emplace_back(); preshare_t& share = shares.back(); randombytes_buf(share.data(), share.size()); XOR(acc.data(), share.data(), acc.data(), share.size()); } shares.push_back(acc); return shares; } void AdditiveReconstruct(const Response& tally, const preshare_t& share, Response* target) { const char* tally_ptr = reinterpret_cast(&tally); char* target_ptr = reinterpret_cast(target); XOR(tally_ptr, share.data(), target_ptr, share.size()); } } // namespace sharing } // namespace DPPIR #include "shared.h" #include using namespace media; namespace { //получение ближайшей сверху степени двойки size_t get_next_higher_power_of_two (size_t k) { if (!k) return 1; k--; for (size_t i=1; i < sizeof (size_t) * 8; i *= 2) k |= k >> i; return k + 1; } unsigned int next_aligned_int (unsigned int value, unsigned int alignment) { if (alignment < 2) return value; // cast quotent to integer to find floor value of a number int quotient = value / alignment; return quotient * alignment == value ? value : (quotient + 1) * alignment; } media::PixelFormat max_image_format (media::PixelFormat format_1, media::PixelFormat format_2) { static const char* METHOD_NAME = "media::max_image_format"; switch (format_2) { case PixelFormat_RGB8: case PixelFormat_RGB16: case PixelFormat_BGR8: case PixelFormat_RGBA8: case PixelFormat_RGBA16: case PixelFormat_BGRA8: case PixelFormat_L8: case PixelFormat_A8: case PixelFormat_LA8: break; default: throw xtl::make_argument_exception (METHOD_NAME, "format_1", format_1); } switch (format_1) { case PixelFormat_RGB8: case PixelFormat_BGR8: { switch (format_2) { case PixelFormat_RGBA8: case PixelFormat_BGRA8: case PixelFormat_RGBA16: case PixelFormat_RGB16: return format_2; case PixelFormat_A8: case PixelFormat_LA8: return PixelFormat_RGBA8; default: return format_1; } } case PixelFormat_RGB16: { switch (format_2) { case PixelFormat_RGBA8: case PixelFormat_BGRA8: case PixelFormat_RGBA16: case PixelFormat_A8: case PixelFormat_LA8: return PixelFormat_RGBA16; default: return format_1; } } case PixelFormat_RGBA8: case PixelFormat_BGRA8: { switch (format_2) { case PixelFormat_RGBA16: case PixelFormat_RGB16: return PixelFormat_RGBA16; default: return format_1; } } case PixelFormat_RGBA16: return format_1; case PixelFormat_L8: { switch (format_2) { case PixelFormat_RGB8: case PixelFormat_RGB16: case PixelFormat_BGR8: case PixelFormat_RGBA8: case PixelFormat_RGBA16: case PixelFormat_BGRA8: case PixelFormat_LA8: return format_2; case PixelFormat_A8: return PixelFormat_LA8; default: return format_1; } } case PixelFormat_A8: { switch (format_2) { case PixelFormat_RGB8: case PixelFormat_BGR8: case PixelFormat_RGBA8: case PixelFormat_BGRA8: return PixelFormat_RGBA8; case PixelFormat_RGB16: case PixelFormat_RGBA16: return PixelFormat_RGBA16; case PixelFormat_LA8: case PixelFormat_L8: return PixelFormat_LA8; default: return format_1; } } case PixelFormat_LA8: { switch (format_2) { case PixelFormat_RGB8: case PixelFormat_BGR8: case PixelFormat_RGBA8: case PixelFormat_BGRA8: return PixelFormat_RGBA8; case PixelFormat_RGB16: case PixelFormat_RGBA16: return PixelFormat_RGBA16; default: return format_1; } } default: throw xtl::make_argument_exception (METHOD_NAME, "format_1", format_1); } } //класс предоставляющий информацию о картинке class IImageHolder : public xtl::reference_counter { public: virtual ~IImageHolder () {} //Загрузка/выгрузка картинки virtual void LoadImage () {}; virtual void UnloadImage () {}; //Получение атрибутов картинки virtual const void* ImageBitmap () = 0; virtual unsigned int ImageWidth () = 0; virtual unsigned int ImageHeight () = 0; virtual size_t ImageHash () = 0; virtual PixelFormat ImageFormat () = 0; virtual const char* ImageName () = 0; virtual unsigned int ImageTag () = 0; }; //Класс, хранящий картинку в памяти class MemoryImageHolder : public IImageHolder { public: MemoryImageHolder (const media::Image& in_image, unsigned int in_tag) : image (in_image) , tag (in_tag) { image_hash = common::crc32 (image.Bitmap (), image.Width () * image.Height () * get_bytes_per_pixel (image.Format ())); } //Получение атрибутов картинки const void* ImageBitmap () { return image.Bitmap (); } unsigned int ImageWidth () { return image.Width (); } unsigned int ImageHeight () { return image.Height (); } size_t ImageHash () { return image_hash; } PixelFormat ImageFormat () { return image.Format (); } const char* ImageName () { return image.Name (); } unsigned int ImageTag () { return tag; } private: media::Image image; size_t image_hash; unsigned int tag; }; //Класс, загружающий картинку из файла по требованию class LoadOnDemandImageHolder : public IImageHolder { public: LoadOnDemandImageHolder (const char* in_image_name, unsigned int in_tag) : image_name (in_image_name) , tag (in_tag) { media::Image tmp_image (in_image_name); image_format = tmp_image.Format (); image_width = tmp_image.Width (); image_height = tmp_image.Height (); image_hash = common::crc32 (tmp_image.Bitmap (), tmp_image.Width () * tmp_image.Height () * get_bytes_per_pixel (tmp_image.Format ())); } //Загрузка/выгрузка картинки void LoadImage () { image.Load (image_name.c_str ()); } void UnloadImage () { Image ().Swap (image); } //Получение атрибутов картинки const void* ImageBitmap () { return image.Bitmap (); } unsigned int ImageWidth () { return image_width; } unsigned int ImageHeight () { return image_height; } size_t ImageHash () { return image_hash; } PixelFormat ImageFormat () { return image_format; } const char* ImageName () { return image_name.c_str (); } unsigned int ImageTag () { return tag; } private: Image image; stl::string image_name; PixelFormat image_format; unsigned int image_width; unsigned int image_height; size_t image_hash; unsigned int tag; }; //Класс, хранящий данные о картинке class DataImageHolder : public IImageHolder { public: DataImageHolder (unsigned int in_width, unsigned int in_height, PixelFormat in_format, const void* in_data, const char* in_name, unsigned int in_tag) : width (in_width) , height (in_height) , hash (common::crc32 (in_data, in_width * in_height * get_bytes_per_pixel (in_format))) , tag (in_tag) , data (in_data) , format (in_format) , name (in_name) {} //Получение атрибутов картинки const void* ImageBitmap () { return data; } unsigned int ImageWidth () { return width; } unsigned int ImageHeight () { return height; } size_t ImageHash () { return hash; } PixelFormat ImageFormat () { return format; } const char* ImageName () { return name.c_str (); } unsigned int ImageTag () { return tag; } private: unsigned int width; unsigned int height; size_t hash; unsigned int tag; const void* data; PixelFormat format; stl::string name; }; typedef xtl::intrusive_ptr ImageHolderPtr; //Описание экземпляра картинки struct ImageDesc : public xtl::reference_counter { ImageHolderPtr image_holder; //картинка unsigned int duplicate_of_index; //индекс картинки в массиве images, дубликатом которой является эта картинка }; struct PackResult : public xtl::reference_counter { unsigned int image_width; //ширина результирующей картинки unsigned int image_height; //высота результирующей картинки xtl::uninitialized_storage origins; //позиции картинок xtl::uninitialized_storage indices; //индексы картинок }; typedef stl::vector IndexArray; typedef xtl::intrusive_ptr PackResultPtr; typedef stl::vector PackResultsArray; typedef xtl::intrusive_ptr ImageDescPtr; typedef stl::vector ImagesDescsArray; typedef stl::hash_map BitmapHashMap; typedef AtlasBuilder::PackHandler PackHandler; } /* Реализация построителя атласа изображений */ struct AtlasBuilder::Impl { PackHandler pack_handler; //обработчик упаковки ImagesDescsArray images; //картинки BitmapHashMap images_hash_map; //карта хешей картинок PackResultsArray pack_results; //результаты упаковки unsigned int max_image_size; //максимальный размер одного атласа unsigned int margin; //размер поля unsigned int alignment; //выравнивание картинок unsigned int pack_flags; //флаги сжатия bool needs_rebuild; //необходимо ли перестроить атлас ///Конструктор Impl (const PackHandler& in_pack_handler) : pack_handler (in_pack_handler) , max_image_size (-1) , margin (0) , alignment (1) , pack_flags (0) , needs_rebuild (true) {} ///Добавление изображений void Insert (Image& image, AtlasBuilderInsertMode mode, unsigned int tag) { try { switch (mode) { case AtlasBuilderInsertMode_Copy: images.push_back (GetImageDesc (ImageHolderPtr (new MemoryImageHolder (image.Clone (), tag), false))); break; case AtlasBuilderInsertMode_Capture: { Image new_image; new_image.Swap (image); images.push_back (GetImageDesc (ImageHolderPtr (new MemoryImageHolder (new_image, tag), false))); break; } case AtlasBuilderInsertMode_Reference: { images.push_back (GetImageDesc (ImageHolderPtr (new MemoryImageHolder (image, tag), false))); break; } default: throw xtl::make_argument_exception ("", "mode", mode, "Unknown insert mode"); } } catch (xtl::exception& exception) { exception.touch ("media::AtlasBuilder::Insert"); throw; } } void Insert (const char* image_name, bool keep_in_memory, unsigned int tag) { try { if (images.size () >= (unsigned int)-1) throw xtl::format_operation_exception ("", "Images count limit exceeded"); ImageHolderPtr image_holder; if (keep_in_memory) image_holder = ImageHolderPtr (new MemoryImageHolder (Image (image_name), tag), false); else image_holder = ImageHolderPtr (new LoadOnDemandImageHolder (image_name, tag), false); images.push_back (GetImageDesc (image_holder)); } catch (xtl::exception& exception) { exception.touch ("media::AtlasBuilder::Insert"); throw; } } void Insert (unsigned int width, unsigned int height, PixelFormat format, const void* data, bool copy_data, const char* name, unsigned int tag) { if (copy_data) { Image image (width, height, 1, format, data); image.Rename (name); Insert (image, AtlasBuilderInsertMode_Reference, tag); return; } images.push_back (GetImageDesc (ImageHolderPtr (new DataImageHolder (width, height, format, data, name, tag), false))); } ImageDescPtr GetImageDesc (ImageHolderPtr image_holder) { ImageDescPtr image_desc (new ImageDesc); image_desc->image_holder = image_holder; size_t bitmap_hash = image_holder->ImageHash (); BitmapHashMap::iterator iter = images_hash_map.find (bitmap_hash); if (iter == images_hash_map.end ()) { image_desc->duplicate_of_index = (unsigned int)images.size (); images_hash_map.insert_pair (bitmap_hash, image_desc->duplicate_of_index); } else { image_desc->duplicate_of_index = iter->second; } return image_desc; } void Build () { if (!needs_rebuild) return; pack_results.clear (); if (images.empty ()) return; try { //построение массива индексов уникальных картинок IndexArray images_to_process; for (unsigned int i = 0, count = (unsigned int)images.size (); i != count; i++) { ImageDescPtr image_desc = images [i]; if (i == image_desc->duplicate_of_index) images_to_process.push_back (i); } //упаковка xtl::uninitialized_storage sizes (images_to_process.size ()), origins (images_to_process.size ()), success_origins (images_to_process.size ()); xtl::uninitialized_storage was_packed (images_to_process.size ()); IndexArray packed_indices; while (!images_to_process.empty ()) { unsigned int images_count = (unsigned int)images_to_process.size (); for (unsigned int i = 0; i < images_count; i++) { unsigned int image_index = images_to_process [i]; ImageHolderPtr image_holder = images [image_index]->image_holder; //it's enough to ensure that image size + margin is aligned to have all images aligned sizes.data () [i].x = next_aligned_int (image_holder->ImageWidth () + margin, alignment) - margin; sizes.data () [i].y = next_aligned_int (image_holder->ImageHeight () + margin, alignment) - margin; } PackHandlerParams pack_params; memset (&pack_params, 0, sizeof (pack_params)); pack_params.images_count = images_count; pack_params.in_sizes = sizes.data (); pack_params.out_origins = origins.data (); pack_params.out_was_packed = was_packed.data (); pack_params.margin = margin; pack_params.max_image_size = max_image_size; pack_params.pack_flags = (pack_flags & ~AtlasPackFlag_InvertTilesX & ~AtlasPackFlag_InvertTilesY) | AtlasPackFlag_PackToMaxImageSize; pack_handler (pack_params); math::vec2ui *current_origin = origins.data (), *current_size = sizes.data (); bool *current_was_packed = was_packed.data (); unsigned int result_image_width = 0, result_image_height = 0; packed_indices.clear (); packed_indices.reserve (images_count); unsigned int top_right_edge_margin = pack_flags & AtlasPackFlag_TopRightEdgeMargin ? margin : 0; for (unsigned int i = 0; i < images_count; i++, current_origin++, current_size++, current_was_packed++) { if (!*current_was_packed) continue; packed_indices.push_back (i); unsigned int right = current_origin->x + current_size->x, top = current_origin->y + current_size->y; if (current_origin->x) right += top_right_edge_margin; if (current_origin->y) top += top_right_edge_margin; if (result_image_width < right) result_image_width = right; if (result_image_height < top) result_image_height = top; } if (packed_indices.empty ()) throw xtl::format_operation_exception ("", "Can't pack images, image '%s' greater then maximum image size %u", images [images_to_process.front ()]->image_holder->ImageName (), max_image_size); if (pack_flags & AtlasPackFlag_PowerOfTwoEdges) { result_image_width = (unsigned int)get_next_higher_power_of_two (result_image_width); result_image_height = (unsigned int)get_next_higher_power_of_two (result_image_height); } if (pack_flags & AtlasPackFlag_SquareAxises) { result_image_width = result_image_height = stl::max (result_image_width, result_image_height); } //подсчет количества упакованных неуникальных картинок unsigned int packed_images_count = 0; for (unsigned int i = 0, images_count = (unsigned int)images.size (); i < images_count; i++) { unsigned int duplicate_of_index = images [i]->duplicate_of_index; for (IndexArray::iterator iter = packed_indices.begin (), end = packed_indices.end (); iter != end; ++iter) { unsigned int image_index = images_to_process [*iter]; if (image_index == duplicate_of_index) { packed_images_count++; break; } } } //формирование результата упаковки PackResultPtr pack_result (new PackResult, false); pack_result->image_width = result_image_width; pack_result->image_height = result_image_height; pack_result->origins.resize (packed_images_count); pack_result->indices.resize (packed_images_count); current_origin = pack_result->origins.data (); unsigned int* current_index = pack_result->indices.data (); for (unsigned int i = 0, images_count = (unsigned int)images.size (); i < images_count; i++) { unsigned int duplicate_of_index = images [i]->duplicate_of_index; for (IndexArray::iterator iter = packed_indices.begin (), end = packed_indices.end (); iter != end; ++iter) { unsigned int image_index = images_to_process [*iter]; if (image_index == duplicate_of_index) { *current_origin = origins.data () [*iter]; *current_index = i; current_origin++; current_index++; break; } } } pack_results.push_back (pack_result); for (IndexArray::reverse_iterator iter = packed_indices.rbegin (), end = packed_indices.rend (); iter != end; ++iter) images_to_process.erase (images_to_process.begin () + *iter); } } catch (xtl::exception& exception) { exception.touch ("media::AtlasBuilder::Build"); throw; } needs_rebuild = false; } void BuildAtlas (unsigned int index, const char* atlas_image_name, Atlas& out_atlas) { Atlas result; PackResult& pack_result = *pack_results [index]; unsigned int* current_index = pack_result.indices.data (); math::vec2ui* current_origin = pack_result.origins.data (); for (unsigned int i = 0, count = (unsigned int)pack_result.indices.size (); i < count; i++, current_index++, current_origin++) { ImageDescPtr current_image_desc = images [*current_index]; ImageHolderPtr image_holder = current_image_desc->image_holder; Tile new_tile; math::vec2ui origin = *current_origin, size (image_holder->ImageWidth (), image_holder->ImageHeight ()); if (pack_flags & AtlasPackFlag_InvertTilesX) origin.x = pack_result.image_width - origin.x - size.x; if (pack_flags & AtlasPackFlag_InvertTilesY) origin.y = pack_result.image_height - origin.y - size.y; new_tile.name = image_holder->ImageName (); new_tile.image = atlas_image_name; new_tile.origin = origin; new_tile.size = size; new_tile.tag = image_holder->ImageTag (); result.Insert (new_tile); } result.SetImageSize (atlas_image_name, pack_result.image_width, pack_result.image_height); result.Swap (out_atlas); } void BuildAtlasImage (unsigned int index, Image& out_atlas_image) { PackResult& pack_result = *pack_results [index]; media::PixelFormat atlas_format = (*images.begin ())->image_holder->ImageFormat (); unsigned int* current_index = pack_result.indices.data (); for (unsigned int i = 0, count = (unsigned int)pack_result.indices.size (); i < count; i++, current_index++) atlas_format = max_image_format (atlas_format, images [*current_index]->image_holder->ImageFormat ()); Image result_image (pack_result.image_width, pack_result.image_height, 1, atlas_format); memset (result_image.Bitmap (), 0, pack_result.image_width * pack_result.image_height * get_bytes_per_pixel (result_image.Format ())); current_index = pack_result.indices.data (); math::vec2ui* current_origin = pack_result.origins.data (); for (unsigned int i = 0, count = (unsigned int)pack_result.indices.size (); i < count; i++, current_index++, current_origin++) { ImageDescPtr current_image_desc = images [*current_index]; ImageHolderPtr image_holder = current_image_desc->image_holder; if (current_image_desc->duplicate_of_index != *current_index) continue; image_holder->LoadImage (); result_image.PutImage (current_origin->x, current_origin->y, 0, image_holder->ImageWidth (), image_holder->ImageHeight (), 1, image_holder->ImageFormat (), image_holder->ImageBitmap ()); image_holder->UnloadImage (); } result_image.Swap (out_atlas_image); } }; /* Построитель атласа изображений */ /* Конструкторы / деструктор */ AtlasBuilder::AtlasBuilder (const char* pack_handler_name) { try { const PackHandler& pack_handler = AtlasBuilderManager::GetPacker (pack_handler_name); impl = new Impl (pack_handler); } catch (xtl::exception& exception) { exception.touch ("media::AtlasBuilder::AtlasBuilder"); throw; } } AtlasBuilder::AtlasBuilder (const PackHandler& pack_handler) : impl (new Impl (pack_handler)) { } AtlasBuilder::~AtlasBuilder () { } /* Установка/получение максимального размера одного атласа */ void AtlasBuilder::SetMaxImageSize (unsigned int max_image_size) { impl->max_image_size = max_image_size; impl->needs_rebuild = true; } unsigned int AtlasBuilder::MaxImageSize () const { return impl->max_image_size; } /* Установка/получение выравнивания картинок */ void AtlasBuilder::SetAlignment (unsigned int alignment) { if (!alignment) throw xtl::make_argument_exception ("media::AtlasBuilder::SetAlignment", "alignment", (int)alignment, "Alignment must be greater than 0"); impl->alignment = alignment; impl->needs_rebuild = true; } unsigned int AtlasBuilder::Alignment () const { return impl->alignment; } /* Установка/получение размера поля */ void AtlasBuilder::SetMargin (unsigned int margin) { impl->margin = margin; impl->needs_rebuild = true; } unsigned int AtlasBuilder::Margin () const { return impl->margin; } /* Установка/получение флагов упаковки */ void AtlasBuilder::SetPackFlags (unsigned int pack_flags) { impl->pack_flags = pack_flags; impl->needs_rebuild = true; } unsigned int AtlasBuilder::PackFlags () const { return impl->pack_flags; } /* Добавление изображений */ void AtlasBuilder::Insert (Image& image, AtlasBuilderInsertMode mode, unsigned int tag) { impl->Insert (image, mode, tag); impl->needs_rebuild = true; } void AtlasBuilder::Insert (const char* image_name, bool keep_in_memory, unsigned int tag) { if (!image_name) throw xtl::make_null_argument_exception ("media::AtlasBuilder::Insert (const char*, bool, unsigned int)", "image_name"); impl->Insert (image_name, keep_in_memory, tag); impl->needs_rebuild = true; } void AtlasBuilder::Insert (unsigned int width, unsigned int height, PixelFormat format, const void* data, bool copy_data, const char* name, unsigned int tag) { static const char* METHOD_NAME = "media::AtlasBuilder::Insert (unsigned int, unsigned int, PixelFormat, const void*, bool, const char*, unsigned int)"; if (!data) throw xtl::make_null_argument_exception (METHOD_NAME, "data"); if (!name) throw xtl::make_null_argument_exception (METHOD_NAME, "name"); impl->Insert (width, height, format, data, copy_data, name, tag); impl->needs_rebuild = true; } /* Сброс */ void AtlasBuilder::Reset () { AtlasBuilder ().Swap (*this); } /* Получение результатов упаковки */ unsigned int AtlasBuilder::AtlasesCount () { try { impl->Build (); return (unsigned int)impl->pack_results.size (); } catch (xtl::exception& e) { e.touch ("media::AtlasBuilder::AtlasesCount"); throw; } } void AtlasBuilder::BuildAtlas (unsigned int index, const char* atlas_image_name, Atlas& result) { try { if (!atlas_image_name) throw xtl::make_null_argument_exception ("", "atlas_image_name"); impl->Build (); if (index >= impl->pack_results.size ()) throw xtl::make_range_exception ("", "index", index, 0u, impl->pack_results.size ()); impl->BuildAtlas (index, atlas_image_name, result); } catch (xtl::exception& e) { e.touch ("media::AtlasBuilder::BuildAtlas"); throw; } } void AtlasBuilder::BuildAtlasImage (unsigned int index, Image& result) { try { impl->Build (); if (index >= impl->pack_results.size ()) throw xtl::make_range_exception ("", "index", index, 0u, impl->pack_results.size ()); impl->BuildAtlasImage (index, result); } catch (xtl::exception& e) { e.touch ("media::AtlasBuilder::BuildAtlasImage"); throw; } } /* Обмен */ void AtlasBuilder::Swap (AtlasBuilder& atlas_builder) { stl::swap (impl, atlas_builder.impl); } namespace media { /* Обмен */ void swap (AtlasBuilder& atlas_builder1, AtlasBuilder& atlas_builder2) { atlas_builder1.Swap (atlas_builder2); } } // // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE.md file in the project root for full license information. // // CNTKLibraryCPPEvalGPUExamples.cpp : Sample application shows how to evaluate a model using CNTK V2 API. // #include void MultiThreadsEvaluation(bool); int main() { fprintf(stderr, "\n##### Run CNTKLibraryCPPEvalGPUExamples on CPU and GPU. #####\n"); MultiThreadsEvaluation(true); fprintf(stderr, "Evaluation complete.\n"); fflush(stderr); } #include "godot_transform.h" #include "math/transform.h" #ifdef __cplusplus extern "C" { #endif void _transform_api_anchor() { } void GDAPI godot_transform_new(godot_transform *p_trans) { Transform *trans = (Transform *)p_trans; *trans = Transform(); } void GDAPI godot_transform_new_with_basis(godot_transform *p_trans, const godot_basis *p_basis) { Transform *trans = (Transform *)p_trans; const Basis *basis = (const Basis *)p_basis; *trans = Transform(*basis); } void GDAPI godot_transform_new_with_basis_origin(godot_transform *p_trans, const godot_basis *p_basis, const godot_vector3 *p_origin) { Transform *trans = (Transform *)p_trans; const Basis *basis = (const Basis *)p_basis; const Vector3 *origin = (const Vector3 *)p_origin; *trans = Transform(*basis, *origin); } godot_basis GDAPI *godot_transform_get_basis(godot_transform *p_trans) { Transform *trans = (Transform *)p_trans; return (godot_basis *)&trans->basis; } godot_vector3 GDAPI *godot_transform_get_origin(godot_transform *p_trans) { Transform *trans = (Transform *)p_trans; return (godot_vector3 *)&trans->origin; } #ifdef __cplusplus } #endif 0 /* * Copyright 2017 Aldebaran * * 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 SET_LANGUAGE_SERVICE_HPP #define SET_LANGUAGE_SERVICE_HPP #include #include #include #include namespace naoqi { namespace service { class SetLanguageService { public: SetLanguageService( const std::string& name, const std::string& topic, const qi::SessionPtr& session ); ~SetLanguageService(){}; std::string name() const { return name_; } std::string topic() const { return topic_; } void reset( rclcpp::Node* node ); void callback( const std::shared_ptr req, std::shared_ptr resp ); private: const std::string name_; const std::string topic_; const qi::SessionPtr& session_; rclcpp::Service::SharedPtr service_; }; } // service } // naoqi #endif #include "Tools/Exception/exception.hpp" #include "Tools/Math/max.h" #include "Module/Decoder/LDPC/BP/Flooding/SPA/Decoder_LDPC_BP_flooding_sum_product.hpp" #include "Module/Decoder/LDPC/BP/Flooding/LSPA/Decoder_LDPC_BP_flooding_log_sum_product.hpp" #include "Module/Decoder/LDPC/BP/Flooding/ONMS/Decoder_LDPC_BP_flooding_offset_normalize_min_sum.hpp" #include "Module/Decoder/LDPC/BP/Flooding/AMS/Decoder_LDPC_BP_flooding_approximate_min_star.hpp" #include "Module/Decoder/LDPC/BP/Flooding/Gallager/Decoder_LDPC_BP_flooding_Gallager_A.hpp" #include "Module/Decoder/LDPC/BP/Layered/SPA/Decoder_LDPC_BP_layered_sum_product.hpp" #include "Module/Decoder/LDPC/BP/Layered/LSPA/Decoder_LDPC_BP_layered_log_sum_product.hpp" #include "Module/Decoder/LDPC/BP/Layered/ONMS/Decoder_LDPC_BP_layered_offset_normalize_min_sum.hpp" #include "Module/Decoder/LDPC/BP/Layered/ONMS/Decoder_LDPC_BP_layered_ONMS_inter.hpp" #include "Decoder_LDPC.hpp" using namespace aff3ct; using namespace aff3ct::factory; const std::string aff3ct::factory::Decoder_LDPC_name = "Decoder LDPC"; const std::string aff3ct::factory::Decoder_LDPC_prefix = "dec"; Decoder_LDPC::parameters ::parameters(const std::string &prefix) : Decoder::parameters(Decoder_LDPC_name, prefix) { this->type = "BP_FLOODING"; this->implem = "SPA"; } Decoder_LDPC::parameters ::~parameters() { } Decoder_LDPC::parameters* Decoder_LDPC::parameters ::clone() const { return new Decoder_LDPC::parameters(*this); } void Decoder_LDPC::parameters ::get_description(arg_map &req_args, arg_map &opt_args) const { Decoder::parameters::get_description(req_args, opt_args); auto p = this->get_prefix(); opt_args[{p+"-h-path"}] = {"string", "path to the H matrix (AList or QC formated file)."}; opt_args[{p+"-h-reorder"}] = {"string", "specify if the check nodes (CNs) from H have to be reordered, 'NONE': do nothing (default), 'ASC': from the " "smallest to the biggest CNs, 'DSC': from the biggest to the smallest CNs.", "NONE, ASC, DSC"}; opt_args[{p+"-min"}] = {"string", "the MIN implementation for the nodes (AMS decoder).", "MIN, MINL, MINS"}; opt_args[{p+"-type", "D"}][2] += ", BP, BP_FLOODING, BP_LAYERED"; opt_args[{p+"-implem" }][2] += ", ONMS, SPA, LSPA, GALA, AMS"; opt_args[{p+"-ite", "i"}] = {"positive_int", "maximal number of iterations in the LDPC decoder."}; opt_args[{p+"-off"}] = {"float", "offset used in the offset min-sum BP algorithm (works only with \"--dec-implem ONMS\")."}; opt_args[{p+"-norm"}] = {"positive_float", "normalization factor used in the normalized min-sum BP algorithm (works only with \"--dec-implem ONMS\")."}; opt_args[{p+"-no-synd"}] = {"", "disable the syndrome detection (disable the stop criterion in the LDPC decoders)."}; opt_args[{p+"-synd-depth"}] = {"strictly_positive_int", "successive number of iterations to validate the syndrome detection."}; opt_args[{p+"-simd"}] = {"string", "the SIMD strategy you want to use.", "INTER"}; } void Decoder_LDPC::parameters ::store(const arg_val_map &vals) { Decoder::parameters::store(vals); auto p = this->get_prefix(); if(exist(vals, {p+"-h-path" })) this->H_path = vals.at({p+"-h-path" }); if(exist(vals, {p+"-h-reorder" })) this->H_reorder = vals.at({p+"-h-reorder" }); if(exist(vals, {p+"-min" })) this->min = vals.at({p+"-min" }); if(exist(vals, {p+"-ite", "i"})) this->n_ite = std::stoi(vals.at({p+"-ite", "i"})); if(exist(vals, {p+"-off" })) this->offset = std::stof(vals.at({p+"-off" })); if(exist(vals, {p+"-norm" })) this->norm_factor = std::stof(vals.at({p+"-norm" })); if(exist(vals, {p+"-synd-depth"})) this->syndrome_depth = std::stoi(vals.at({p+"-synd-depth"})); if(exist(vals, {p+"-simd" })) this->simd_strategy = vals.at({p+"-simd" }); if(exist(vals, {p+"-no-synd" })) this->enable_syndrome = false; } void Decoder_LDPC::parameters ::get_headers(std::map& headers, const bool full) const { Decoder::parameters::get_headers(headers, full); if (this->type != "ML" && this->type != "CHASE") { auto p = this->get_prefix(); if (!this->H_path.empty()) { headers[p].push_back(std::make_pair("H matrix path", this->H_path)); headers[p].push_back(std::make_pair("H matrix reordering", this->H_reorder)); } if (!this->simd_strategy.empty()) headers[p].push_back(std::make_pair("SIMD strategy", this->simd_strategy)); headers[p].push_back(std::make_pair("Num. of iterations (i)", std::to_string(this->n_ite))); if (this->implem == "ONMS") { headers[p].push_back(std::make_pair("Offset", std::to_string(this->offset))); headers[p].push_back(std::make_pair("Normalize factor", std::to_string(this->norm_factor))); } std::string syndrome = this->enable_syndrome ? "on" : "off"; headers[p].push_back(std::make_pair("Stop criterion (syndrome)", syndrome)); if (this->enable_syndrome) headers[p].push_back(std::make_pair("Stop criterion depth", std::to_string(this->syndrome_depth))); if (this->implem == "AMS") headers[p].push_back(std::make_pair("Min type", this->min)); } } template module::Decoder_SISO_SIHO* Decoder_LDPC::parameters ::build_siso(const tools::Sparse_matrix &H, const std::vector &info_bits_pos, module::Encoder *encoder) const { if ((this->type == "BP" || this->type == "BP_FLOODING") && this->simd_strategy.empty()) { if (this->implem == "ONMS") return new module::Decoder_LDPC_BP_flooding_ONMS (this->K, this->N_cw, this->n_ite, H, info_bits_pos, this->norm_factor, (Q)this->offset, this->enable_syndrome, this->syndrome_depth, this->n_frames); else if (this->implem == "SPA" ) return new module::Decoder_LDPC_BP_flooding_SPA (this->K, this->N_cw, this->n_ite, H, info_bits_pos, this->enable_syndrome, this->syndrome_depth, this->n_frames); else if (this->implem == "LSPA") return new module::Decoder_LDPC_BP_flooding_LSPA (this->K, this->N_cw, this->n_ite, H, info_bits_pos, this->enable_syndrome, this->syndrome_depth, this->n_frames); else if (this->implem == "AMS" ) { if (this->min == "MIN") return new module::Decoder_LDPC_BP_flooding_AMS> (this->K, this->N_cw, this->n_ite, H, info_bits_pos, this->enable_syndrome, this->syndrome_depth, this->n_frames); else if (this->min == "MINL") return new module::Decoder_LDPC_BP_flooding_AMS> (this->K, this->N_cw, this->n_ite, H, info_bits_pos, this->enable_syndrome, this->syndrome_depth, this->n_frames); else if (this->min == "MINS") return new module::Decoder_LDPC_BP_flooding_AMS> (this->K, this->N_cw, this->n_ite, H, info_bits_pos, this->enable_syndrome, this->syndrome_depth, this->n_frames); } } else if (this->type == "BP_LAYERED" && this->simd_strategy.empty()) { if (this->implem == "ONMS") return new module::Decoder_LDPC_BP_layered_ONMS (this->K, this->N_cw, this->n_ite, H, info_bits_pos, this->norm_factor, (Q)this->offset, this->enable_syndrome, this->syndrome_depth, this->n_frames); else if (this->implem == "SPA" ) return new module::Decoder_LDPC_BP_layered_SPA (this->K, this->N_cw, this->n_ite, H, info_bits_pos, this->enable_syndrome, this->syndrome_depth, this->n_frames); else if (this->implem == "LSPA") return new module::Decoder_LDPC_BP_layered_LSPA (this->K, this->N_cw, this->n_ite, H, info_bits_pos, this->enable_syndrome, this->syndrome_depth, this->n_frames); } else if (this->type == "BP_LAYERED" && this->simd_strategy == "INTER") { if (this->implem == "ONMS") return new module::Decoder_LDPC_BP_layered_ONMS_inter(this->K, this->N_cw, this->n_ite, H, info_bits_pos, this->norm_factor, (Q)this->offset, this->enable_syndrome, this->syndrome_depth, this->n_frames); } throw tools::cannot_allocate(__FILE__, __LINE__, __func__); } template module::Decoder_SIHO* Decoder_LDPC::parameters ::build(const tools::Sparse_matrix &H, const std::vector &info_bits_pos, module::Encoder *encoder) const { try { return Decoder::parameters::build(encoder); } catch (tools::cannot_allocate const&) { if ((this->type == "BP" || this->type == "BP_FLOODING") && this->simd_strategy.empty()) { if (this->implem == "GALA") return new module::Decoder_LDPC_BP_flooding_GALA(this->K, this->N_cw, this->n_ite, H, info_bits_pos, this->enable_syndrome, this->syndrome_depth, this->n_frames); } return build_siso(H, info_bits_pos); } throw tools::cannot_allocate(__FILE__, __LINE__, __func__); } template module::Decoder_SISO_SIHO* Decoder_LDPC ::build_siso(const parameters& params, const tools::Sparse_matrix &H, const std::vector &info_bits_pos, module::Encoder *encoder) { return params.template build_siso(H, info_bits_pos, encoder); } template module::Decoder_SIHO* Decoder_LDPC ::build(const parameters& params, const tools::Sparse_matrix &H, const std::vector &info_bits_pos, module::Encoder *encoder) { return params.template build(H, info_bits_pos, encoder); } // ==================================================================================== explicit template instantiation #include "Tools/types.h" #ifdef MULTI_PREC template aff3ct::module::Decoder_SISO_SIHO* aff3ct::factory::Decoder_LDPC::parameters::build_siso(const aff3ct::tools::Sparse_matrix&, const std::vector&, module::Encoder*) const; template aff3ct::module::Decoder_SISO_SIHO* aff3ct::factory::Decoder_LDPC::parameters::build_siso(const aff3ct::tools::Sparse_matrix&, const std::vector&, module::Encoder*) const; template aff3ct::module::Decoder_SISO_SIHO* aff3ct::factory::Decoder_LDPC::parameters::build_siso(const aff3ct::tools::Sparse_matrix&, const std::vector&, module::Encoder*) const; template aff3ct::module::Decoder_SISO_SIHO* aff3ct::factory::Decoder_LDPC::parameters::build_siso(const aff3ct::tools::Sparse_matrix&, const std::vector&, module::Encoder*) const; template aff3ct::module::Decoder_SISO_SIHO* aff3ct::factory::Decoder_LDPC::build_siso(const aff3ct::factory::Decoder_LDPC::parameters&, const aff3ct::tools::Sparse_matrix&, const std::vector&, module::Encoder*); template aff3ct::module::Decoder_SISO_SIHO* aff3ct::factory::Decoder_LDPC::build_siso(const aff3ct::factory::Decoder_LDPC::parameters&, const aff3ct::tools::Sparse_matrix&, const std::vector&, module::Encoder*); template aff3ct::module::Decoder_SISO_SIHO* aff3ct::factory::Decoder_LDPC::build_siso(const aff3ct::factory::Decoder_LDPC::parameters&, const aff3ct::tools::Sparse_matrix&, const std::vector&, module::Encoder*); template aff3ct::module::Decoder_SISO_SIHO* aff3ct::factory::Decoder_LDPC::build_siso(const aff3ct::factory::Decoder_LDPC::parameters&, const aff3ct::tools::Sparse_matrix&, const std::vector&, module::Encoder*); #else template aff3ct::module::Decoder_SISO_SIHO* aff3ct::factory::Decoder_LDPC::parameters::build_siso(const aff3ct::tools::Sparse_matrix&, const std::vector&, module::Encoder*) const; template aff3ct::module::Decoder_SISO_SIHO* aff3ct::factory::Decoder_LDPC::build_siso(const aff3ct::factory::Decoder_LDPC::parameters&, const aff3ct::tools::Sparse_matrix&, const std::vector&, module::Encoder*); #endif #include "Tools/types.h" #ifdef MULTI_PREC template aff3ct::module::Decoder_SIHO* aff3ct::factory::Decoder_LDPC::parameters::build(const aff3ct::tools::Sparse_matrix&, const std::vector&, module::Encoder*) const; template aff3ct::module::Decoder_SIHO* aff3ct::factory::Decoder_LDPC::parameters::build(const aff3ct::tools::Sparse_matrix&, const std::vector&, module::Encoder*) const; template aff3ct::module::Decoder_SIHO* aff3ct::factory::Decoder_LDPC::parameters::build(const aff3ct::tools::Sparse_matrix&, const std::vector&, module::Encoder*) const; template aff3ct::module::Decoder_SIHO* aff3ct::factory::Decoder_LDPC::parameters::build(const aff3ct::tools::Sparse_matrix&, const std::vector&, module::Encoder*) const; template aff3ct::module::Decoder_SIHO* aff3ct::factory::Decoder_LDPC::build(const aff3ct::factory::Decoder_LDPC::parameters&, const aff3ct::tools::Sparse_matrix&, const std::vector&, module::Encoder*); template aff3ct::module::Decoder_SIHO* aff3ct::factory::Decoder_LDPC::build(const aff3ct::factory::Decoder_LDPC::parameters&, const aff3ct::tools::Sparse_matrix&, const std::vector&, module::Encoder*); template aff3ct::module::Decoder_SIHO* aff3ct::factory::Decoder_LDPC::build(const aff3ct::factory::Decoder_LDPC::parameters&, const aff3ct::tools::Sparse_matrix&, const std::vector&, module::Encoder*); template aff3ct::module::Decoder_SIHO* aff3ct::factory::Decoder_LDPC::build(const aff3ct::factory::Decoder_LDPC::parameters&, const aff3ct::tools::Sparse_matrix&, const std::vector&, module::Encoder*); #else template aff3ct::module::Decoder_SIHO* aff3ct::factory::Decoder_LDPC::parameters::build(const aff3ct::tools::Sparse_matrix&, const std::vector&, module::Encoder*) const; template aff3ct::module::Decoder_SIHO* aff3ct::factory::Decoder_LDPC::build(const aff3ct::factory::Decoder_LDPC::parameters&, const aff3ct::tools::Sparse_matrix&, const std::vector&, module::Encoder*); #endif // ==================================================================================== explicit template instantiation #include #include #include #include namespace mana = mitama::mana; TEST_CASE("slidify variadic", "[functional][slidify]") { auto sliding = mana::slidify<3>(1,2,3,4,5,6); REQUIRE(std::get<0>(sliding) == std::tuple{1,2,3}); REQUIRE(std::get<1>(sliding) == std::tuple{2,3,4}); REQUIRE(std::get<2>(sliding) == std::tuple{3,4,5}); REQUIRE(std::get<3>(sliding) == std::tuple{4,5,6}); } TEST_CASE("slidify tuple", "[functional][slidify]") { auto sliding = mana::slidify<3>(std::tuple{1,2,3,4,5,6}); REQUIRE(std::get<0>(sliding) == std::tuple{1,2,3}); REQUIRE(std::get<1>(sliding) == std::tuple{2,3,4}); REQUIRE(std::get<2>(sliding) == std::tuple{3,4,5}); REQUIRE(std::get<3>(sliding) == std::tuple{4,5,6}); } TEST_CASE("slidify view", "[functional][slidify]") { auto sliding_view = mana::slidify<3>.view(1,2,3,4,5,6); REQUIRE(mana::get<0>(sliding_view) == std::tuple{1,2,3}); REQUIRE(mana::get<1>(sliding_view) == std::tuple{2,3,4}); REQUIRE(mana::get<2>(sliding_view) == std::tuple{3,4,5}); REQUIRE(mana::get<3>(sliding_view) == std::tuple{4,5,6}); } TEST_CASE("slidify view-map", "[functional][slidify]") { auto sum = [](std::tuple t){ return std::apply([](auto... v){ return (v + ...); }, t); }; auto sliding_sum = mana::slidify<3>.view(1,2,3,4,5,6).map(sum); REQUIRE(mana::get<0>(sliding_sum) == 6); REQUIRE(mana::get<1>(sliding_sum) == 9); REQUIRE(mana::get<2>(sliding_sum) == 12); REQUIRE(mana::get<3>(sliding_sum) == 15); } TEST_CASE("slidify view-apply_map", "[functional][slidify]") { auto sum = [](auto... v){ return (v + ...); }; auto sliding_sum = mana::slidify<3>.view(1,2,3,4,5,6).apply_map(sum); REQUIRE(mana::get<0>(sliding_sum) == 6); REQUIRE(mana::get<1>(sliding_sum) == 9); REQUIRE(mana::get<2>(sliding_sum) == 12); REQUIRE(mana::get<3>(sliding_sum) == 15); } TEST_CASE("slidify-flatten", "[functional][chunkify]") { mana::apply_view( [](auto... values) { REQUIRE(std::tuple{values...} == std::tuple{1,2,3,2,3,4,3,4,5,4,5,6}); }, mana::slidify<3>.view(1,2,3,4,5,6).flatten() ); } GabrielRavier/CaveStoryRecoded #include "stage.h" #include #include #include #include "render.h" #include "mathUtils.h" #include "game.h" #include "player.h" #include "script.h" #include "flags.h" #include "filesystem.h" #include "boss.h" #include "bullet.h" #include "caret.h" #include "log.h" #include "main.h" #include "valueview.h" int gCurrentLevel; MAPNAME gMapName; //Loaded level stuff MAP gMap; BACKGROUND gBackground; //Effect things int gCurrentEffect = 0; //water level (used in core area) int gWaterY = 0; //Get stage data STAGE_TABLE *gStageTable; void loadStageTable() { SDL_RWops *tblStream = SDL_RWFromFile("data/stage.tbl", "rb"); if (tblStream == nullptr) doError(); const auto stages = static_cast(tblStream->size(tblStream)) / sizeof(STAGE_TABLE); gStageTable = new STAGE_TABLE[stages]; if (gStageTable == nullptr) doCustomError("Could not allocate memory for stage table"); for (size_t i = 0; i < stages; i++) { tblStream->read(tblStream, gStageTable[i].tileset, 0x20, 1); tblStream->read(tblStream, gStageTable[i].filename, 0x20, 1); gStageTable[i].backgroundScroll = SDL_ReadLE32(tblStream); tblStream->read(tblStream, gStageTable[i].background, 0x20, 1); tblStream->read(tblStream, gStageTable[i].npc1, 0x20, 1); tblStream->read(tblStream, gStageTable[i].npc2, 0x20, 1); tblStream->read(tblStream, &gStageTable[i].boss, 1, 1); tblStream->read(tblStream, gStageTable[i].name, 0x23, 1); if (!strcmp(gStageTable[i].name, "u")) strcpy(gStageTable[i].name, "Studio Pixel presents"); } } uint8_t getTileAttribute(size_t xTile, size_t yTile) { if (xTile < static_cast(gMap.width) && yTile < static_cast(gMap.height)) // Make sure coordinates are valid return gMap.attribute[gMap.tile[xTile + yTile * gMap.width]]; // Coordinates are invalid return 0; } void deleteTile(size_t x, size_t y) { gMap.tile[x + y * gMap.width] = 0; } void shiftTile(size_t x, size_t y) { --gMap.tile[x + y * gMap.width]; } bool changeTile(size_t x, size_t y, uint8_t tile) { if (gMap.tile[y * gMap.width + x] == tile) return false; gMap.tile[x + y * gMap.width] = tile; for (int i = 0; i < 3; ++i) createNpc(NPC_Smoke, tilesToUnits(x), tilesToUnits(y)); return true; } void loadPxm(const std::string &name) { //frees old map memory delete[] gMap.tile; auto tmp = loadFile("data/Stage/" + name + ".pxm"); auto pxmSize = tmp.first; auto pxm = tmp.second; gMap.width = readLEshort(pxm.data(), 4); gMap.height = readLEshort(pxm.data(), 6); gMap.tile = new uint8_t[pxmSize - 8]; memcpy(gMap.tile, pxm.data() + 8, pxmSize - 8); } void loadPxa(const std::string &name) { //free old tile attribute memory delete[] gMap.attribute; auto tmp = loadFile("data/Stage/" + name + ".pxa"); auto pxaSize = tmp.first; auto pxa = tmp.second; gMap.attribute = new uint8_t[pxaSize]; memcpy(gMap.attribute, pxa.data(), pxaSize); } void loadPxe(const std::string &name) { //Clear old npcs gNPC.clear(); gNPC.shrink_to_fit(); auto pxe = loadFile("data/Stage/" + name + ".pxe").second; //Load npcs const int npcAmount = readLElong(pxe.data(), 4); for (int i = 0; i < npcAmount; i++) { const int offset = (i * 12) + 8; if (readLEshort(pxe.data(), offset + 10) & npc_appearSet && !(getFlag(readLEshort(pxe.data(), offset + 4)))) continue; if (readLEshort(pxe.data(), offset + 10) & npc_hideSet && getFlag(readLEshort(pxe.data(), offset + 4))) continue; npc newNPC; newNPC.init(readLEshort(pxe.data(), offset + 8), tilesToUnits(readLEshort(pxe.data(), offset)), tilesToUnits(readLEshort(pxe.data(), offset + 2)), 0, 0, 0, nullptr); newNPC.code_event = readLEshort(pxe.data(), offset + 6); newNPC.code_flag = readLEshort(pxe.data(), offset + 4); newNPC.bits |= readLEshort(pxe.data(), offset + 10); if (readLEshort(pxe.data(), offset + 10) & npc_altDir) newNPC.direct = dirRight; gNPC.push_back(newNPC); } } void iniBackground(const std::string &name, int mode) { gBackground.mode = mode; gBackground.tileWidth = gMap.width; gBackground.tileHeight = gMap.height; gBackground.flag = 1; loadImage(name, &gSprites[TEX_BACKGROUND]); // Load background texture gWaterY = tilesToUnits(240); } void loadLevel(size_t levelIndex, int w, int x, int y) { logInfo("Loading level " + std::to_string(levelIndex)); gCurrentPlayer.setPos(tilesToUnits(x), tilesToUnits(y)); // -- clears/frees stuff from last map -- // gCarets.clear(); gCarets.shrink_to_fit(); gBullets.clear(); gBullets.shrink_to_fit(); gValueviews.clear(); gValueviews.shrink_to_fit(); //load tileset loadImage(std::string("Stage/Prt") + gStageTable[levelIndex].tileset, &gSprites[TEX_TILESET]); //load pxm, pxa, pxe, and tsc loadPxa(gStageTable[levelIndex].tileset); loadPxm(gStageTable[levelIndex].filename); loadPxe(gStageTable[levelIndex].filename); loadStageTsc(gStageTable[levelIndex].filename); //Load background iniBackground(gStageTable[levelIndex].background, gStageTable[levelIndex].backgroundScroll); // -- loads map images -- // //load sheet 1 loadImage(std::string("Npc/Npc") + gStageTable[levelIndex].npc1, &gSprites[TEX_NPC_1]); //load sheet 2 loadImage(std::string("Npc/Npc") + gStageTable[levelIndex].npc2, &gSprites[TEX_NPC_2]); // -- loads some map stuff -- // //Set up map name gMapName.flag = 0; gMapName.wait = 0; strcpy(gMapName.name, gStageTable[levelIndex].name); startTscEvent(gTsc, w); SetFrameMyChar(); initBoss(gStageTable[levelIndex].boss); gCurrentLevel = levelIndex; // -- fix gViewport -- // // gViewport.x = gCurrentPlayer.x - (gScreenWidth << 8); // gViewport.y = gCurrentPlayer.y - (gScreenHeight << 8); // gViewport.lookX = &gCurrentPlayer.tgt_x; // gViewport.lookY = &gCurrentPlayer.tgt_y; gViewport.quake = 0; gViewport.quake2 = 0; viewBounds(); } void drawForeground(void) { RECT rect; if (gBackground.mode == 3) { const int xOff = gViewport.x % pixelsToUnits(32); rect.left = 0; rect.right = 32; rect.top = 0; rect.bottom = 16; //draws top of water for (int x = gViewport.x - xOff; x < gViewport.x + pixelsToUnits(gScreenWidth); x += pixelsToUnits(32)) drawTexture(gSprites[TEX_BACKGROUND], &rect, unitsToPixels(x) - unitsToPixels(gViewport.x), unitsToPixels(gWaterY) - unitsToPixels(gViewport.y)); //draws bottom of water rect.top = 16; rect.bottom = 32; for (int y = gWaterY; y < gViewport.y + pixelsToUnits(gScreenHeight); y += pixelsToUnits(16)) { for (int x = gViewport.x - xOff; x < gViewport.x + pixelsToUnits(gScreenWidth); x += pixelsToUnits(32)) drawTexture(gSprites[TEX_BACKGROUND], &rect, unitsToPixels(x) - unitsToPixels(gViewport.x), unitsToPixels(y) - unitsToPixels(gViewport.y)); } } } static void updateBackgroundEffect(int w) { if (gGameFlags & 1) { if (gBackground.mode == 5) { gBackground.effect += 0xC00; } else if (gBackground.mode >= 5 && gBackground.mode <= 7) { ++gBackground.effect; gBackground.effect %= (w * 2); } } } void drawBackground(void) { int w, h; SDL_QueryTexture(gSprites[TEX_BACKGROUND], nullptr, nullptr, &w, &h); RECT rect = { 0, 0, w, h }; updateBackgroundEffect(w); switch (gBackground.mode) { case 0: for (int x = 0; x < gScreenWidth; x += w) { for (int y = 0; y < gScreenHeight; y += h) drawTexture(gSprites[TEX_BACKGROUND], &rect, x, y); } break; case 1: for (int x = -(gViewport.x / 0x400 % w); x < gScreenWidth; x += w) { for (int y = -(gViewport.y / 0x400 % h); y < gScreenHeight; y += h) drawTexture(gSprites[TEX_BACKGROUND], &rect, x, y); } break; case 2: for (int x = -(gViewport.x / 0x200 % w); x < gScreenWidth; x += w) { for (int y = -(gViewport.y / 0x200 % h); y < gScreenHeight; y += h) drawTexture(gSprites[TEX_BACKGROUND], &rect, x, y); } break; case 5: for (int x = -(gBackground.effect / 0x200 % w); x < gScreenWidth; x += w) { for (int y = 0; y < gScreenHeight; y += h) drawTexture(gSprites[TEX_BACKGROUND], &rect, x, y); } break; case 6: case 7: //Draw sky rect = { 0, 0, w / 2, 88 }; int skyOff = (((w / 2) - gScreenWidth) / 2); //Draw middle drawTexture(gSprites[0x1C], &rect, -skyOff, 0); //Repeat stars or whatever rect = { w / 2, 0, w, 88 }; for (int i = 0; i < gScreenWidth - (skyOff / 2 + rect.left); i += rect.left) { drawTexture(gSprites[TEX_BACKGROUND], &rect, -skyOff + (rect.left + i), 0); drawTexture(gSprites[TEX_BACKGROUND], &rect, -skyOff - (rect.left + i), 0); } //Cloud layers rect.left = 0; rect.right = w; rect.top = 88; rect.bottom = 123; for (int i = 0; i <= (gScreenWidth / w) + 1; ++i) drawTexture(gSprites[TEX_BACKGROUND], &rect, (w * i) - (gBackground.effect / 2) % w, rect.top); rect.top = 123; rect.bottom = 146; for (int i = 0; i <= (gScreenWidth / w) + 1; ++i) drawTexture(gSprites[TEX_BACKGROUND], &rect, (w * i) - gBackground.effect % w, rect.top); rect.top = 146; rect.bottom = 176; for (int i = 0; i <= (gScreenWidth / w) + 1; ++i) drawTexture(gSprites[TEX_BACKGROUND], &rect, (w * i) - (gBackground.effect * 2) % w, rect.top); rect.top = 176; rect.bottom = 240; for (int i = 0; i <= (gScreenWidth / w) + 1; ++i) drawTexture(gSprites[TEX_BACKGROUND], &rect, (w * i) - (gBackground.effect * 4) % w, rect.top); break; } } void drawLevel(bool foreground) { if (!foreground) //Draw background { drawBackground(); } //Animate currents if (gGameFlags & 1 && foreground) gCurrentEffect += 2; //Render tiles RECT tileRect; const int xFrom = clamp(unitsToTiles(gViewport.x + 0x1000), 0, gMap.width); const int xTo = clamp((unitsToTiles((gViewport.x + 0x1000) + (gScreenWidth << 9))) + 1, 0, gMap.width); //add 1 because edge wouldn't appear const int yFrom = clamp(unitsToTiles(gViewport.y + 0x1000), 0, gMap.height); const int yTo = clamp((unitsToTiles((gViewport.y + 0x1000) + (gScreenWidth << 9))) + 1, 0, gMap.height); //add 1 because edge wouldn't appear for (int x = xFrom; x < xTo; x++) { for (int y = yFrom; y < yTo; y++) { const int i = x + y * gMap.width; const int tile = gMap.tile[i]; if (tile) { const int attribute = gMap.attribute[tile]; if ((attribute < 0x20 && !foreground) || (attribute >= 0x40 && foreground)) { const int drawX = i % gMap.width; const int drawY = i / gMap.width; if (attribute < 0x80) { tileRect = { (tile % 16) * 16, (tile / 16) * 16, (tile % 16) * 16 + 16, (tile / 16) * 16 + 16 }; drawTexture(gSprites[TEX_TILESET], &tileRect, tilesToPixels(drawX) - unitsToPixels(gViewport.x) - 8, tilesToPixels(drawY) - unitsToPixels(gViewport.y) - 8); if (attribute == 0x43) //Star block { tileRect = { 256, 48, 272, 64 }; drawTexture(gSprites[TEX_NPC_SYM], &tileRect, tilesToPixels(drawX) - unitsToPixels(gViewport.x) - 8, tilesToPixels(drawY) - unitsToPixels(gViewport.y) - 8); } } else { switch (attribute) { case 0x80: case 0xA0: tileRect.left = (gCurrentEffect & 0xF) + 224; tileRect.right = (gCurrentEffect & 0xF) + 240; tileRect.top = 48; tileRect.bottom = 64; break; case 0x81: case 0xA1: tileRect.left = 224; tileRect.right = 240; tileRect.top = (gCurrentEffect & 0xF) + 48; tileRect.bottom = (gCurrentEffect & 0xF) + 64; break; case 0x82: case 0xA2: tileRect.left = 240 - (gCurrentEffect & 0xF); tileRect.right = 256 - (gCurrentEffect & 0xF); tileRect.top = 48; tileRect.bottom = 64; break; case 0x83: case 0xA3: tileRect.left = 224; tileRect.right = 240; tileRect.top = 64 - (gCurrentEffect & 0xF); tileRect.bottom = 80 - (gCurrentEffect & 0xF); break; default: return; } drawTexture(gSprites[TEX_CARET], &tileRect, tilesToPixels(drawX) - unitsToPixels(gViewport.x) - 8, tilesToPixels(drawY) - unitsToPixels(gViewport.y) - 8); } } } } } if (foreground) { //draw foreground drawForeground(); //Render black bars in foreground SDL_SetRenderDrawColor(gRenderer, 0, 0, 32, 255); //Left and right const int leftBorder = -(gViewport.x / 0x200); const int rightBorder = ((gViewport.x / 0x200) + gScreenWidth) - ((gMap.width - 1) << 4); drawRect(0, 0, leftBorder, gScreenHeight); drawRect(gScreenWidth - rightBorder, 0, rightBorder, gScreenHeight); //Top and bottom const int topBorder = -(gViewport.y / 0x200); const int bottomBorder = ((gViewport.y / 0x200) + gScreenHeight) - ((gMap.height - 1) << 4); drawRect(0, 0, gScreenWidth, topBorder); drawRect(0, gScreenHeight - bottomBorder, gScreenWidth, bottomBorder); } } industriousonesoft/MyLeetCodes62.Unique Paths/main.cpp /* A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below). How many possible unique paths are there? Example 1: Input: m = 3, n = 7 Output: 28 Example 2: Input: m = 3, n = 2 Output: 3 Explanation: From the top-left corner, there are a total of 3 ways to reach the bottom-right corner: 1. Right -> Down -> Down 2. Down -> Down -> Right 3. Down -> Right -> Down Example 3: Input: m = 7, n = 3 Output: 28 Example 4: Input: m = 3, n = 3 Output: 6   Constraints: 1 <= m, n <= 100 It's guaranteed that the answer will be less than or equal to 2 * 109. 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/unique-paths 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 */ #include using namespace std; int uniquePaths(int m, int n) { if (m <= 0 || n <= 0) { return 0; } int dp[m][n]; memset(dp, 0, sizeof(dp)); for (size_t i = 0; i < m; i++) { for (size_t j = 0; j < n; j++) { // 到与起点在同一维度的点,只有一条路径可选 // 起点到自身的路径也是1 if (i == 0 || j == 0) { dp[i][j] = 1; }else { // 与起点不再同一维度的点,存在向右和向下选择 dp[i][j] = dp[i-1][j] + dp[i][j-1]; } } } return dp[m-1][n-1]; } int main(int argc, const char* argv[]) { int m = 3, n = 0; cout << "m: " << m << " n: " << n << " res: " << uniquePaths(m, n) << endl; return 0; }vocab.cpp // Copyright (c) 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) // #include #include #include #include #include #include #include #include #include #include #include "documents.hpp" namespace fs = std::experimental::filesystem; int main(int argc, char ** argv) { bool histogram = false; std::size_t filterlb = 0; std::size_t filterub = std::numeric_limits::max(); UnicodeString regexp(u"[\\p{L}\\p{M}]+"); fs::path pth{}; { bool halt = false; while(!halt) { int option_index = 0; static struct option long_options[] = { {"corpus_dir", required_argument, NULL, 'c' }, {"regex", optional_argument, NULL, 'r' }, {"histogram", optional_argument, NULL, 'h' }, {"filterlb", optional_argument, NULL, 'l' }, {"filterub", optional_argument, NULL, 'u' }, {NULL, 0, NULL, 0 } }; int c = getopt_long(argc, argv, "c:r:", long_options, &option_index); if(c == -1) { halt = true; } else { switch(c) { case 'c': { std::string carg{optarg}; pth = fs::path{carg}; break; } case 'r': { regexp = UnicodeString::fromUTF8(std::string{optarg}); break; } case 'h': { histogram = true; break; } case 'l': { std::string sval{optarg}; char * svalend = nullptr; filterlb = static_cast(std::strtoul(sval.c_str(), &svalend, 10)); break; } case 'u': { std::string sval{optarg}; char * svalend = nullptr; filterub = static_cast(std::strtoul(sval.c_str(), &svalend, 10)); break; } } } } bool exit = false; if(pth.string().size() < 1) { std::cerr << "Please specify '--corpus_dir= (required), --regex= (optional), --histogram (optional) --filterlb=integer (optional) --filterub=integer (optional)'" << std::endl; exit = true; } if(exit) { return 1; } } std::vector< fs::path > paths; path_to_vector( pth, paths ); inverted_index_t ii{}; std::vector< fs::path >::iterator beg = paths.begin(); std::vector< fs::path >::iterator end = paths.end(); document_path_to_inverted_index(beg, end, regexp, ii); if(!histogram) { if(filterlb == 0 && filterub == std::numeric_limits::max()) { for(const auto& e : ii) { std::cout << e.first << std::endl; } } else { std::plus addr{}; for(const auto& e : ii) { const std::size_t count = std::transform_reduce(e.second.begin(), e.second.end(), 0, addr, [](const auto& entry){ return entry.second; }); if(count >= filterlb && count <= filterub) { std::cout << e.first << std::endl; } } } } else { if(filterlb == 0 && filterub == std::numeric_limits::max()) { std::plus addr{}; for(const auto& e : ii) { const std::size_t count = std::transform_reduce(e.second.begin(), e.second.end(), 0, addr, [](const auto& entry){ return entry.second; }); std::cout << e.first << ',' << count << std::endl; } } else { std::plus addr{}; for(const auto& e : ii) { const std::size_t count = std::transform_reduce(e.second.begin(), e.second.end(), 0, addr, [](const auto& entry){ return entry.second; }); if(count >= filterlb && count <= filterub) { std::cout << e.first << ',' << count << std::endl; } } } } } vm/vm/main/builtins.hh // Copyright © 2011, Université catholique de Louvain // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. #ifndef MOZART_BUILTINS_H #define MOZART_BUILTINS_H #include "mozartcore.hh" #ifndef MOZART_GENERATOR namespace mozart { namespace builtins { ///////////////// // BaseBuiltin // ///////////////// atom_t BaseBuiltin::getModuleNameAtom(VM vm) { return vm->getAtom(_moduleName); } atom_t BaseBuiltin::getNameAtom(VM vm) { return vm->getAtom(_name); } atom_t BaseBuiltin::getPrintName(VM vm) { /* It is intentional that we stream _moduleName on the one hand (the string) * and getNameAtom() on the other hand (the atom), so that we get results * like Port.is, Value.'.', Int.'div' and Value.'\\='. */ std::stringstream ss; ss << _moduleName << '.' << getNameAtom(vm); auto str = ss.str(); return vm->getAtom(ss.str()); } void BaseBuiltin::getCallInfo( RichNode self, VM vm, size_t& arity, ProgramCounter& start, size_t& Xcount, StaticArray& Gs, StaticArray& Ks) { if (_codeBlock == nullptr) buildCodeBlock(vm, self); arity = _arity; start = _codeBlock; Xcount = 2*_arity; Gs = nullptr; Ks = StaticArray(&*_selfValue, 1); } void BaseBuiltin::buildCodeBlock(VM vm, RichNode self) { const size_t arity = _arity; // Compute size of the code block size_t count = 0; count += 1 /* opcode */ + 1 /* K(0) */ + (arity > 5 ? 1 : 0) /* arity */; count += arity /* actual arguments */; for (size_t i = 0; i < arity; i++) if (_params[i].kind == ParamInfo::pkOut) count += 1 /* opcode */ + 2 /* args */; count += 1 /* OpReturn */; // Allocate the code block _codeBlock = new ByteCode[count]; size_t index = 0; // OpCallBuiltin switch (arity) { case 0: _codeBlock[index++] = OpCallBuiltin0; break; case 1: _codeBlock[index++] = OpCallBuiltin1; break; case 2: _codeBlock[index++] = OpCallBuiltin2; break; case 3: _codeBlock[index++] = OpCallBuiltin3; break; case 4: _codeBlock[index++] = OpCallBuiltin4; break; case 5: _codeBlock[index++] = OpCallBuiltin5; break; default: _codeBlock[index++] = OpCallBuiltinN; break; } _codeBlock[index++] = 0; // K(0) if (arity > 5) _codeBlock[index++] = arity; for (size_t i = 0; i < arity; i++) { if (_params[i].kind == ParamInfo::pkIn) { _codeBlock[index++] = i; } else { _codeBlock[index++] = i + arity; } } // Unify with outputs for (size_t i = 0; i < arity; i++) { if (_params[i].kind == ParamInfo::pkOut) { _codeBlock[index++] = OpUnifyXX; _codeBlock[index++] = i; _codeBlock[index++] = i + arity; } } // Return _codeBlock[index++] = OpReturn; // Finalize assert(index == count); // Set _selfValue _selfValue = vm->protect(self); } } } #endif // MOZART_GENERATOR #endif // MOZART_BUILTINS_H 100-1000 #include "Group.h" #include "Hub.h" namespace cWS { template void Group::setUserData(void *user) { this->userData = user; } template void *Group::getUserData() { return userData; } template void Group::timerCallback(cS::Timer *timer) { Group *group = (Group *) timer->getData(); // finish bugs if (group->userPingMessageLength > 0) { group->broadcast(group->userPingMessage, group->userPingMessageLength, group->pingMessageType, true); } else { group->broadcast(nullptr, 0, OpCode::PING, true); } } template // const char *message, size_t length, OpCode opCode void Group::startAutoPing(int intervalMs, const char *message, size_t length, OpCode opCode) { timer = new cS::Timer(loop); timer->setData(this); timer->start(timerCallback, intervalMs, intervalMs); userPingMessage = message; userPingMessageLength = length; pingMessageType = opCode; } template void Group::addHttpSocket(HttpSocket *httpSocket) { if (httpSocketHead) { httpSocketHead->prev = httpSocket; httpSocket->next = httpSocketHead; } else { httpSocket->next = nullptr; // start timer httpTimer = new cS::Timer(hub->getLoop()); httpTimer->setData(this); httpTimer->start([](cS::Timer *httpTimer) { Group *group = (Group *) httpTimer->getData(); group->forEachHttpSocket([](HttpSocket *httpSocket) { if (httpSocket->missedDeadline) { httpSocket->terminate(); } else if (!httpSocket->outstandingResponsesHead) { httpSocket->missedDeadline = true; } }); }, 1000, 1000); } httpSocketHead = httpSocket; httpSocket->prev = nullptr; } template void Group::removeHttpSocket(HttpSocket *httpSocket) { if (iterators.size()) { iterators.top() = httpSocket->next; } if (httpSocket->prev == httpSocket->next) { httpSocketHead = nullptr; httpTimer->stop(); httpTimer->close(); } else { if (httpSocket->prev) { ((HttpSocket *) httpSocket->prev)->next = httpSocket->next; } else { httpSocketHead = (HttpSocket *) httpSocket->next; } if (httpSocket->next) { ((HttpSocket *) httpSocket->next)->prev = httpSocket->prev; } } } template void Group::addWebSocket(WebSocket *webSocket) { if (webSocketHead) { webSocketHead->prev = webSocket; webSocket->next = webSocketHead; } else { webSocket->next = nullptr; } webSocketHead = webSocket; webSocket->prev = nullptr; } template void Group::removeWebSocket(WebSocket *webSocket) { if (iterators.size()) { iterators.top() = webSocket->next; } if (webSocket->prev == webSocket->next) { webSocketHead = nullptr; } else { if (webSocket->prev) { ((WebSocket *) webSocket->prev)->next = webSocket->next; } else { webSocketHead = (WebSocket *) webSocket->next; } if (webSocket->next) { ((WebSocket *) webSocket->next)->prev = webSocket->prev; } } } template Group::Group(int extensionOptions, unsigned int maxPayload, Hub *hub, cS::NodeData *nodeData) : cS::NodeData(*nodeData), maxPayload(maxPayload), hub(hub), extensionOptions(extensionOptions) { connectionHandler = [](WebSocket *, HttpRequest) {}; transferHandler = [](WebSocket *) {}; messageHandler = [](WebSocket *, char *, size_t, OpCode) {}; disconnectionHandler = [](WebSocket *, int, char *, size_t) {}; pingHandler = pongHandler = [](WebSocket *, char *, size_t) {}; errorHandler = [](errorType) {}; httpRequestHandler = [](HttpResponse *, HttpRequest, char *, size_t, size_t) {}; httpConnectionHandler = [](HttpSocket *) {}; httpDisconnectionHandler = [](HttpSocket *) {}; httpCancelledRequestHandler = [](HttpResponse *) {}; httpDataHandler = [](HttpResponse *, char *, size_t, size_t) {}; this->extensionOptions |= CLIENT_NO_CONTEXT_TAKEOVER | SERVER_NO_CONTEXT_TAKEOVER; } template void Group::stopListening() { if (isServer) { if (user) { // todo: we should allow one group to listen to many ports! cS::ListenSocket *listenSocket = (cS::ListenSocket *) user; if (listenSocket->timer) { listenSocket->timer->stop(); listenSocket->timer->close(); } listenSocket->closeSocket(); // mark as stopped listening (extra care?) user = nullptr; } } if (async) { async->close(); } } template void Group::onConnection(std::function *, HttpRequest)> handler) { connectionHandler = handler; } template void Group::onTransfer(std::function *)> handler) { transferHandler = handler; } template void Group::onMessage(std::function *, char *, size_t, OpCode)> handler) { messageHandler = handler; } template void Group::onDisconnection(std::function *, int, char *, size_t)> handler) { disconnectionHandler = handler; } template void Group::onPing(std::function *, char *, size_t)> handler) { pingHandler = handler; } template void Group::onPong(std::function *, char *, size_t)> handler) { pongHandler = handler; } template void Group::onError(std::function handler) { errorHandler = handler; } template void Group::onHttpConnection(std::function *)> handler) { httpConnectionHandler = handler; } template void Group::onHttpRequest(std::function handler) { httpRequestHandler = handler; } template void Group::onHttpData(std::function handler) { httpDataHandler = handler; } template void Group::onHttpDisconnection(std::function *)> handler) { httpDisconnectionHandler = handler; } template void Group::onCancelledHttpRequest(std::function handler) { httpCancelledRequestHandler = handler; } template void Group::onHttpUpgrade(std::function *, HttpRequest)> handler) { httpUpgradeHandler = handler; } template void Group::broadcast(const char *message, size_t length, OpCode opCode, bool isPing) { #ifdef CWS_THREADSAFE std::lock_guard lockGuard(*asyncMutex); #endif typename WebSocket::PreparedMessage *preparedMessage = WebSocket::prepareMessage((char *) message, length, opCode, false); if(isPing) { forEach([preparedMessage](cWS::WebSocket *ws) { if (ws->hasOutstandingPong) { ws->terminate(); } else { ws->hasOutstandingPong = true; ws->sendPrepared(preparedMessage); } }); } else { forEach([preparedMessage](cWS::WebSocket *ws) { ws->sendPrepared(preparedMessage); }); } WebSocket::finalizeMessage(preparedMessage); } template void Group::terminate() { stopListening(); forEach([](cWS::WebSocket *ws) { ws->terminate(); }); forEachHttpSocket([](HttpSocket *httpSocket) { httpSocket->terminate(); }); } template void Group::close(int code, char *message, size_t length) { stopListening(); forEach([code, message, length](cWS::WebSocket *ws) { ws->close(code, message, length); }); forEachHttpSocket([](HttpSocket *httpSocket) { httpSocket->shutdown(); }); if (timer) { timer->stop(); timer->close(); } } template struct Group; template struct Group; } #include using namespace std; string N; int main() { ios_base::sync_with_stdio(0); cin.tie(0); cin >> N; int dv3 = 0; for(int i = 0 ; i < N.size() ; i++) dv3 += (N[i] - '0'); if(dv3 % 3 != 0){ cout << -1; return 0; } sort(N.begin(), N.end()); for(int i = N.size() - 1 ; i >= 0 ; i--) cout << N[i]; return 0; } // -------------------------------------------------------------------------- // TestRankSets.cpp // -------------------------------------------------------------------------- // An example to test resizing with a disallowed rank set. // This test is supposed to fail. // -------------------------------------------------------------------------- #include #include #include // -------------------------------------------------------------------------- int main(int argc, char *argv[]) { BoxLib::Initialize(argc,argv); int myProcAll(ParallelDescriptor::MyProcAll()); int nProcs(ParallelDescriptor::NProcs()); int nSidecars(1), totalSidecarProcs(4); bool printRanks(true); if(nProcs < 8) { BoxLib::Abort("**** Error: must use at least 8 processes."); } Array compProcsInAll; compProcsInAll.push_back(0); for(int i(1); i < nProcs - totalSidecarProcs; ++i) { compProcsInAll.push_back(nProcs - totalSidecarProcs - i); // ---- backwards } Array > sidecarProcsInAll(nSidecars); for(int i(nProcs - totalSidecarProcs); i < nProcs; ++i) { sidecarProcsInAll[0].push_back(i); } if(myProcAll == 0) { std::cout << myProcAll << ":: Set initial sidecar sizes." << std::endl; std::cout << std::endl; } BoxLib::USleep(myProcAll); ParallelDescriptor::SetNProcsSidecars(compProcsInAll, sidecarProcsInAll, printRanks); // ---- now move some procs to the sidecar sidecarProcsInAll[0].push_back(compProcsInAll[compProcsInAll.size() - 1]); compProcsInAll.pop_back(); if(myProcAll == 0) { std::cout << myProcAll << ":: Move elements from comp to sidecar." << std::endl; std::cout << std::endl; } BoxLib::USleep(myProcAll); ParallelDescriptor::SetNProcsSidecars(compProcsInAll, sidecarProcsInAll, printRanks); // ---- now swap the last elements, this test should fail int cLast(compProcsInAll[compProcsInAll.size() - 1]); compProcsInAll[compProcsInAll.size() - 1] = sidecarProcsInAll[0][sidecarProcsInAll.size() - 1]; sidecarProcsInAll[0][sidecarProcsInAll.size() - 1] = cLast; if(myProcAll == 0) { std::cout << myProcAll << ":: Move elements both from and to comp. This test should fail." << std::endl; std::cout << std::endl; } BoxLib::USleep(myProcAll); ParallelDescriptor::SetNProcsSidecars(compProcsInAll, sidecarProcsInAll, printRanks); nSidecars = 0; ParallelDescriptor::SetNProcsSidecars(nSidecars); if(myProcAll == 0) { std::cout << myProcAll << ":: Finished." << std::endl; } BoxLib::Finalize(); return 0; } // -------------------------------------------------------------------------- // -------------------------------------------------------------------------- Ron423c/chromium0 // Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/webui/sync_internals/sync_internals_ui.h" #include #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/webui/sync_internals/sync_internals_message_handler.h" #include "chrome/browser/ui/webui/webui_util.h" #include "chrome/common/url_constants.h" #include "components/grit/sync_driver_resources.h" #include "components/sync/driver/sync_internals_util.h" #include "content/public/browser/web_ui.h" #include "content/public/browser/web_ui_data_source.h" #include "services/network/public/mojom/content_security_policy.mojom.h" namespace { content::WebUIDataSource* CreateSyncInternalsHTMLSource() { content::WebUIDataSource* source = content::WebUIDataSource::Create(chrome::kChromeUISyncInternalsHost); source->OverrideContentSecurityPolicy( network::mojom::CSPDirectiveName::ScriptSrc, "script-src chrome://resources 'self' 'unsafe-eval';"); source->OverrideContentSecurityPolicy( network::mojom::CSPDirectiveName::TrustedTypes, "trusted-types jstemplate cr-ui-tree-js-static;"); source->UseStringsJs(); static constexpr webui::ResourcePath kResources[] = { {syncer::sync_ui_util::kSyncIndexJS, IDR_SYNC_DRIVER_SYNC_INTERNALS_INDEX_JS}, {syncer::sync_ui_util::kChromeSyncJS, IDR_SYNC_DRIVER_SYNC_INTERNALS_CHROME_SYNC_JS}, {syncer::sync_ui_util::kSyncLogJS, IDR_SYNC_DRIVER_SYNC_INTERNALS_SYNC_LOG_JS}, {syncer::sync_ui_util::kSyncNodeBrowserJS, IDR_SYNC_DRIVER_SYNC_INTERNALS_SYNC_NODE_BROWSER_JS}, {syncer::sync_ui_util::kSyncSearchJS, IDR_SYNC_DRIVER_SYNC_INTERNALS_SYNC_SEARCH_JS}, {syncer::sync_ui_util::kAboutJS, IDR_SYNC_DRIVER_SYNC_INTERNALS_ABOUT_JS}, {syncer::sync_ui_util::kDataJS, IDR_SYNC_DRIVER_SYNC_INTERNALS_DATA_JS}, {syncer::sync_ui_util::kEventsJS, IDR_SYNC_DRIVER_SYNC_INTERNALS_EVENTS_JS}, {syncer::sync_ui_util::kSearchJS, IDR_SYNC_DRIVER_SYNC_INTERNALS_SEARCH_JS}, {syncer::sync_ui_util::kUserEventsJS, IDR_SYNC_DRIVER_SYNC_INTERNALS_USER_EVENTS_JS}, {syncer::sync_ui_util::kTrafficLogJS, IDR_SYNC_DRIVER_SYNC_INTERNALS_TRAFFIC_LOG_JS}, {syncer::sync_ui_util::kInvalidationsJS, IDR_SYNC_DRIVER_SYNC_INTERNALS_INVALIDATIONS_JS}, }; source->AddResourcePaths(kResources); source->SetDefaultResource(IDR_SYNC_DRIVER_SYNC_INTERNALS_INDEX_HTML); return source; } } // namespace SyncInternalsUI::SyncInternalsUI(content::WebUI* web_ui) : WebUIController(web_ui) { Profile* profile = Profile::FromWebUI(web_ui); content::WebUIDataSource::Add(profile, CreateSyncInternalsHTMLSource()); web_ui->AddMessageHandler(std::make_unique()); } SyncInternalsUI::~SyncInternalsUI() {} RomanWlm/lib-ledger-core // AUTOGENERATED FILE - DO NOT MODIFY! // This file generated by Djinni from tezos_like_wallet.djinni #include "TezosConfiguration.hpp" // my header namespace ledger { namespace core { namespace api { std::string const TezosConfiguration::TEZOS_XPUB_CURVE = {"TEZOS_XPUB_CURVE"}; std::string const TezosConfiguration::TEZOS_PROTOCOL_UPDATE = {"TEZOS_PROTOCOL_UPDATE"}; std::string const TezosConfiguration::TEZOS_NODE = {"TEZOS_NODE"}; } } } // namespace ledger::core::api src/cdi_analytic/test/tstAnalytic_EICoupling.cc //----------------------------------*-C++-*----------------------------------// /*! * \file cdi_analytic/test/tstAnalytic_EICoupling.cc * \author * \date March 2019 * \brief Analytic_EICoupling test. * \note Copyright (C) 2016-2019 Triad National Security, LLC. * All rights reserved. */ //---------------------------------------------------------------------------// #include "cdi/CDI.hh" #include "cdi_analytic/Analytic_EICoupling.hh" #include "ds++/Release.hh" #include "ds++/ScalarUnitTest.hh" using namespace std; using rtt_cdi::CDI; using rtt_cdi::EICoupling; using rtt_cdi_analytic::Analytic_EICoupling; using rtt_cdi_analytic::Analytic_EICoupling_Model; using rtt_cdi_analytic::Constant_Analytic_EICoupling_Model; using rtt_dsxx::soft_equiv; using std::dynamic_pointer_cast; //---------------------------------------------------------------------------// // TESTS //---------------------------------------------------------------------------// void analytic_ei_coupling_test(rtt_dsxx::UnitTest &ut) { typedef Constant_Analytic_EICoupling_Model Constant_Model; // make an analytic model (constant ei_coupling) shared_ptr model(new Constant_Model(1.1)); if (!model) FAILMSG("Failed to build an Analytic EICoupling Model!"); // make an analtyic electron-ion coupling Analytic_EICoupling analytic(model); // checks { double Te = 1.0; double Ti = 2.0; double rho = 3.0; double w_e = 4.0; double w_i = 5.0; double ei_coupling = 1.1; // specific heats if (!soft_equiv(analytic.getElectronIonCoupling(Te, Ti, rho, w_e, w_i), ei_coupling)) ITFAILS; } // field check { vector Te = {0.993, 0.882, 0.590, 0.112, 0.051, 0.001}; vector Ti = {0.993, 0.882, 0.590, 0.112, 0.051, 0.001}; vector rho = {0.993, 0.882, 0.590, 0.112, 0.051, 0.001}; vector w_e = {0.993, 0.882, 0.590, 0.112, 0.051, 0.001}; vector w_i = {0.993, 0.882, 0.590, 0.112, 0.051, 0.001}; double ei_coupling_ref = 1.1; vector ei_coupling = analytic.getElectronIonCoupling(Te, Ti, rho, w_e, w_i); if (ei_coupling.size() != 6) ITFAILS; for (int i = 0; i < 6; i++) { if (!soft_equiv(ei_coupling[i], ei_coupling_ref)) ITFAILS; } } // Test the get_Analytic_Model() member function. { shared_ptr myEICoupling_model = dynamic_pointer_cast( analytic.get_Analytic_Model()); shared_ptr expected_model(model); if (expected_model == myEICoupling_model) PASSMSG("get_Analytic_Model() returned the expected EICoupling model."); else FAILMSG( "get_Analytic_Model() did not return the expected EICoupling model."); } // Test the get_parameters() members function { std::vector params(model->get_parameters()); std::vector expectedValue(1, 1.1); double const tol(1.0e-12); if (params.size() != expectedValue.size()) ITFAILS; if (soft_equiv(params.begin(), params.end(), expectedValue.begin(), expectedValue.end(), tol)) PASSMSG( "get_parameters() returned the analytic expression coefficients."); else FAILMSG("get_parameters() did not return the analytic expression " "coefficients."); } return; } //---------------------------------------------------------------------------// void CDI_test(rtt_dsxx::UnitTest &ut) { typedef Constant_Analytic_EICoupling_Model Constant_Model; // cdi object CDI eiCouplingData; // analytic model shared_ptr model(new Constant_Model(1.1)); // assign the electron-ion coupling object shared_ptr analytic_ei_coupling( new Analytic_EICoupling(model)); // EICoupling object shared_ptr ei_coupling = analytic_ei_coupling; if (typeid(*ei_coupling) != typeid(Analytic_EICoupling)) ITFAILS; // Assign the object to cdi eiCouplingData.setEICoupling(ei_coupling); // check if (!eiCouplingData.ei_coupling()) FAILMSG("Can't reference EICoupling smart pointer"); // make temperature and density fields vector Te = {0.993, 0.882, 0.590, 0.112, 0.051, 0.001}; vector Ti = {0.993, 0.882, 0.590, 0.112, 0.051, 0.001}; vector rho = {0.993, 0.882, 0.590, 0.112, 0.051, 0.001}; vector w_e = {0.993, 0.882, 0.590, 0.112, 0.051, 0.001}; vector w_i = {0.993, 0.882, 0.590, 0.112, 0.051, 0.001}; vector EICoupling; // test the data { EICoupling = eiCouplingData.ei_coupling()->getElectronIonCoupling( Te, Ti, rho, w_e, w_i); if (EICoupling.size() != 6) ITFAILS; for (int i = 0; i < 6; i++) { double ei_coupling_ref = 1.1; if (!soft_equiv(EICoupling[i], ei_coupling_ref)) ITFAILS; } } // now reset the CDI eiCouplingData.reset(); // should catch this bool caught = false; try { eiCouplingData.ei_coupling(); } catch (const rtt_dsxx::assertion & /* except */) { PASSMSG("Good, caught an unreferenced EICoupling shared_ptr!"); caught = true; } if (!caught) FAILMSG("Failed to catch an unreferenced shared_ptr!"); // now assign the analytic electron-ion coupling to CDI directly eiCouplingData.setEICoupling(analytic_ei_coupling); if (!eiCouplingData.ei_coupling()) ITFAILS; if (typeid(*eiCouplingData.ei_coupling()) != typeid(Analytic_EICoupling)) ITFAILS; // now test the data again // test the data { EICoupling = eiCouplingData.ei_coupling()->getElectronIonCoupling( Te, Ti, rho, w_e, w_i); if (EICoupling.size() != 6) ITFAILS; for (int i = 0; i < 6; i++) { double ei_coupling_ref = 1.1; if (!soft_equiv(EICoupling[i], ei_coupling_ref)) ITFAILS; } } return; } //---------------------------------------------------------------------------// void packing_test(rtt_dsxx::UnitTest &ut) { typedef Constant_Analytic_EICoupling_Model Constant_Model; vector packed; { // make an analytic model (polynomial specific heats) shared_ptr model(new Constant_Model(1.1)); // make an analtyic electron-ion coupling shared_ptr ei_coupling(new Analytic_EICoupling(model)); packed = ei_coupling->pack(); } Analytic_EICoupling n_ei_coupling(packed); // checks { double Te = 5.0; double Ti = 5.0; double rho = 3.0; double w_e = 3.0; double w_i = 3.0; double ei_coupling_ref = 1.1; // specific heats if (!soft_equiv(n_ei_coupling.getElectronIonCoupling(Te, Ti, rho, w_e, w_i), ei_coupling_ref)) ITFAILS; } if (ut.numFails == 0) PASSMSG("Analytic EICoupling packing/unpacking test successfull."); return; } //---------------------------------------------------------------------------// int main(int argc, char *argv[]) { rtt_dsxx::ScalarUnitTest ut(argc, argv, rtt_dsxx::release); try { // >>> UNIT TESTS analytic_ei_coupling_test(ut); CDI_test(ut); packing_test(ut); } UT_EPILOG(ut); } //---------------------------------------------------------------------------// // end of tstAnalytic_EICoupling.cc //---------------------------------------------------------------------------// // Copyright 2015 XLGAMES Inc. // // Distributed under the MIT License (See // accompanying file "LICENSE" or the website // http://www.opensource.org/licenses/mit-license.php) #include "PlacementsManager.h" #include "PlacementsQuadTree.h" #include "DynamicImposters.h" #include "PreparedScene.h" #include "../RenderCore/Assets/SharedStateSet.h" #include "../RenderCore/Assets/Material.h" #include "../RenderCore/Assets/ModelRunTime.h" #include "../Assets/CompileAndAsyncManager.h" #include "../Assets/IntermediateAssets.h" #include "../RenderCore/Assets/DelayedDrawCall.h" #include "../RenderCore/Assets/ModelCache.h" #include "../RenderCore/Techniques/ParsingContext.h" #include "../Assets/Assets.h" #include "../Assets/ChunkFile.h" #include "../Assets/AssetUtils.h" #include "../Assets/InvalidAssetManager.h" #include "../RenderCore/RenderUtils.h" #include "../ConsoleRig/Log.h" #include "../ConsoleRig/Console.h" #include "../Math/Matrix.h" #include "../Math/Transformations.h" #include "../Math/ProjectionMath.h" #include "../Math/Geometry.h" #include "../Utility/PtrUtils.h" #include "../Utility/MemoryUtils.h" #include "../Utility/HeapUtils.h" #include "../Utility/IteratorUtils.h" #include "../Utility/StringFormat.h" #include "../Utility/Streams/FileUtils.h" #include "../Utility/Streams/PathUtils.h" #include "../Utility/Streams/StreamFormatter.h" #include "../Utility/Streams/StreamDOM.h" #include "../Utility/Conversion.h" #include "../Core/Types.h" #include namespace RenderCore { extern char VersionString[]; extern char BuildDateString[]; } namespace SceneEngine { using Assets::ResChar; using RenderCore::Assets::ModelRenderer; using RenderCore::Assets::ModelScaffold; using RenderCore::Assets::MaterialScaffold; using RenderCore::Assets::ModelCache; using RenderCore::Assets::DelayedDrawCall; using RenderCore::Assets::DelayedDrawCallSet; using SupplementRange = ModelCache::SupplementRange; /////////////////////////////////////////////////////////////////////////////////////////////////// // Note that "placements" that interface methods in Placements are actually // very rarely called. So it should be fine to make those methods into virtual // methods, and use an abstract base class. class Placements : public ::Assets::ChunkFileAsset { public: typedef std::pair BoundingBox; class ObjectReference { public: Float3x4 _localToCell; BoundingBox _cellSpaceBoundary; unsigned _modelFilenameOffset; // note -- hash values should be stored with the filenames unsigned _materialFilenameOffset; unsigned _supplementsOffset; uint64 _guid; }; const ObjectReference* GetObjectReferences() const; unsigned GetObjectReferenceCount() const; const void* GetFilenamesBuffer() const; const uint64* GetSupplementsBuffer() const; void Write(const Assets::ResChar destinationFile[]) const; void LogDetails(const char title[]) const; Placements(const ResChar filename[]); Placements(); ~Placements(); protected: std::vector _objects; std::vector _filenamesBuffer; std::vector _supplementsBuffer; std::shared_ptr<::Assets::DependencyValidation> _dependencyValidation; void ReplaceString(const char oldString[], const char newString[]); static void Resolver(void*, IteratorRange<::Assets::AssetChunkResult*>); }; auto Placements::GetObjectReferences() const -> const ObjectReference* { return AsPointer(_objects.begin()); } unsigned Placements::GetObjectReferenceCount() const { return unsigned(_objects.size()); } const void* Placements::GetFilenamesBuffer() const { return AsPointer(_filenamesBuffer.begin()); } const uint64* Placements::GetSupplementsBuffer() const { return AsPointer(_supplementsBuffer.begin()); } static const uint64 ChunkType_Placements = ConstHash64<'Plac','emen','ts'>::Value; class PlacementsHeader { public: unsigned _version; unsigned _objectRefCount; unsigned _filenamesBufferSize; unsigned _supplementsBufferSize; unsigned _dummy; }; void Placements::Write(const Assets::ResChar destinationFile[]) const { using namespace Serialization::ChunkFile; SimpleChunkFileWriter fileWriter( 1, RenderCore::VersionString, RenderCore::BuildDateString, std::make_tuple(destinationFile, "wb", 0)); fileWriter.BeginChunk(ChunkType_Placements, 0, "Placements"); PlacementsHeader hdr; hdr._version = 0; hdr._objectRefCount = (unsigned)_objects.size(); hdr._filenamesBufferSize = unsigned(_filenamesBuffer.size()); hdr._supplementsBufferSize = unsigned(_supplementsBuffer.size() * sizeof(uint64)); hdr._dummy = 0; auto writeResult0 = fileWriter.Write(&hdr, sizeof(hdr), 1); auto writeResult1 = fileWriter.Write(AsPointer(_objects.begin()), sizeof(ObjectReference), hdr._objectRefCount); auto writeResult2 = fileWriter.Write(AsPointer(_filenamesBuffer.begin()), 1, hdr._filenamesBufferSize); auto writeResult3 = fileWriter.Write(AsPointer(_supplementsBuffer.begin()), 1, hdr._supplementsBufferSize); if ( writeResult0 != 1 || writeResult1 != hdr._objectRefCount || writeResult2 != hdr._filenamesBufferSize || writeResult3 != hdr._supplementsBufferSize) Throw(::Exceptions::BasicLabel("Failure in file write while saving placements")); } void Placements::LogDetails(const char title[]) const { // write some details about this placements file to the log LogInfo << "---<< Placements file: " << title << " >>---"; LogInfo << " (" << _objects.size() << ") object references -- " << sizeof(ObjectReference) * _objects.size() / 1024.f << "k in objects, " << _filenamesBuffer.size() / 1024.f << "k in string table"; unsigned configCount = 0; auto i = _objects.cbegin(); while (i != _objects.cend()) { auto starti = i; while (i != _objects.cend() && i->_materialFilenameOffset == starti->_materialFilenameOffset && i->_modelFilenameOffset == starti->_modelFilenameOffset && i->_supplementsOffset == starti->_supplementsOffset) { ++i; } ++configCount; } LogInfo << " (" << configCount << ") configurations"; i = _objects.cbegin(); while (i != _objects.cend()) { auto starti = i; while (i != _objects.cend() && i->_materialFilenameOffset == starti->_materialFilenameOffset && i->_modelFilenameOffset == starti->_modelFilenameOffset && i->_supplementsOffset == starti->_supplementsOffset) { ++i; } auto modelName = (const ResChar*)PtrAdd(AsPointer(_filenamesBuffer.begin()), starti->_modelFilenameOffset + sizeof(uint64)); auto materialName = (const ResChar*)PtrAdd(AsPointer(_filenamesBuffer.begin()), starti->_materialFilenameOffset + sizeof(uint64)); auto supplementCount = !_supplementsBuffer.empty() ? _supplementsBuffer[starti->_supplementsOffset] : 0; LogInfo << " [" << (i-starti) << "] objects (" << modelName << "), (" << materialName << "), (" << supplementCount << ")"; } } void Placements::ReplaceString(const ResChar oldString[], const ResChar newString[]) { unsigned replacementStart = 0, preReplacementEnd = 0; unsigned postReplacementEnd = 0; uint64 oldHash = Hash64(oldString); uint64 newHash = Hash64(newString); // first, look through and find the old string. // then, auto i = _filenamesBuffer.begin(); for(;i !=_filenamesBuffer.end();) { auto starti = i; if (std::distance(i, _filenamesBuffer.end()) < sizeof(uint64)) { assert(0); break; // not enough room for a full hash code. Seems like the string table is corrupted } i += sizeof(uint64); while (i != _filenamesBuffer.end() && *i) { ++i; } if (i != _filenamesBuffer.end()) { ++i; } // one more increment to include the null character if (*(const uint64*)AsPointer(starti) == oldHash) { // if this is our string, then we need to erase the old content and insert // the new auto length = XlStringLen(newString); std::vector replacementContent(sizeof(uint64) + (length + 1) * sizeof(ResChar), 0); *(uint64*)AsPointer(replacementContent.begin()) = newHash; XlCopyString( (ResChar*)AsPointer(replacementContent.begin() + sizeof(uint64)), length+1, newString); replacementStart = (unsigned)std::distance(_filenamesBuffer.begin(), starti); preReplacementEnd = (unsigned)std::distance(_filenamesBuffer.begin(), i); postReplacementEnd = unsigned(replacementStart + replacementContent.size()); i = _filenamesBuffer.erase(starti, i); auto dst = std::distance(_filenamesBuffer.begin(), i); _filenamesBuffer.insert(i, replacementContent.begin(), replacementContent.end()); i = _filenamesBuffer.begin(); std::advance(i, dst + replacementContent.size()); // Now we have to adjust all of the offsets in the ObjectReferences for (auto o=_objects.begin(); o!=_objects.end(); ++o) { if (o->_modelFilenameOffset > replacementStart) { o->_modelFilenameOffset -= preReplacementEnd - postReplacementEnd; assert(o->_modelFilenameOffset > replacementStart); } if (o->_materialFilenameOffset > replacementStart) { o->_materialFilenameOffset -= preReplacementEnd - postReplacementEnd; assert(o->_materialFilenameOffset > replacementStart); } } return; } } } static const ::Assets::AssetChunkRequest PlacementsChunkRequests[] { ::Assets::AssetChunkRequest { "Placements", ChunkType_Placements, 0, ::Assets::AssetChunkRequest::DataType::Raw } }; Placements::Placements(const ResChar filename[]) : ChunkFileAsset("Placements") { Prepare(filename, ResolveOp{MakeIteratorRange(PlacementsChunkRequests), Resolver}); } void Placements::Resolver(void* obj, IteratorRange<::Assets::AssetChunkResult*> chunks) { assert(chunks.size() == 1); auto* plc = (Placements*)obj; // // Extremely simple file format for placements // We just need 2 blocks: // * list of object references // * list of filenames / strings // The strings are kept separate from the object placements // because many of the string will be referenced multiple // times. It just helps reduce file size. // void const* i = chunks[0]._buffer.get(); const auto& hdr = *(const PlacementsHeader*)i; if (hdr._version != 0) Throw(::Exceptions::BasicLabel( StringMeld<128>() << "Unexpected version number (" << hdr._version << ")")); i = PtrAdd(i, sizeof(PlacementsHeader)); plc->_objects.clear(); plc->_filenamesBuffer.clear(); plc->_supplementsBuffer.clear(); plc->_objects.insert(plc->_objects.end(), (const ObjectReference*)i, (const ObjectReference*)i + hdr._objectRefCount); i = (const ObjectReference*)i + hdr._objectRefCount; plc->_filenamesBuffer.insert(plc->_filenamesBuffer.end(), (const uint8*)i, (const uint8*)i + hdr._filenamesBufferSize); i = (const uint8*)i + hdr._filenamesBufferSize; plc->_supplementsBuffer.insert(plc->_supplementsBuffer.end(), (const uint64*)i, (const uint64*)PtrAdd(i, hdr._supplementsBufferSize)); i = PtrAdd(i, hdr._supplementsBufferSize); #if defined(_DEBUG) const auto* filename = plc->Filename().c_str(); if (!plc->_objects.empty()) plc->LogDetails(filename); #endif } Placements::Placements() : ChunkFileAsset("Placements") { auto depValidation = std::make_shared(); _dependencyValidation = std::move(depValidation); } Placements::~Placements() {} /////////////////////////////////////////////////////////////////////////////////////////////////// class PlacementCell { public: uint64 _filenameHash; Float3x4 _cellToWorld; Float3 _aabbMin, _aabbMax; Float2 _captureMins, _captureMaxs; ResChar _filename[256]; }; class PlacementsQuadTree; class PlacementsCache { public: class Item { public: ::Assets::rstring _filename; std::unique_ptr _placements; void Reload(); Item() {} Item(Item&& moveFrom) : _filename(std::move(moveFrom._filename)), _placements(std::move(moveFrom._placements)) {} Item& operator=(Item&& moveFrom) { _filename = std::move(moveFrom._filename); _placements = std::move(moveFrom._placements); return *this; } Item& operator=(const Item&) = delete; Item(const Item&) = delete; }; Item* Get(uint64 filenameHash, const ResChar filename[] = nullptr); PlacementsCache(); ~PlacementsCache(); protected: std::vector>> _items; }; auto PlacementsCache::Get(uint64 filenameHash, const ResChar filename[]) -> Item* { auto i = LowerBound(_items, filenameHash); if (i != _items.end() && i->first == filenameHash) { if (i->second->_placements->GetDependencyValidation()->GetValidationIndex()!=0) i->second->Reload(); return i->second.get(); } // When filename is null, we can only return an object that has been created before. // if it hasn't been created, we will return null if (!filename) return nullptr; auto newItem = std::make_unique(); newItem->_filename = filename; newItem->Reload(); i = _items.emplace(i, std::make_pair(filenameHash, std::move(newItem))); return i->second.get(); } void PlacementsCache::Item::Reload() { _placements.reset(); _placements = std::make_unique(_filename.c_str()); } PlacementsCache::PlacementsCache() {} PlacementsCache::~PlacementsCache() {} /////////////////////////////////////////////////////////////////////////////////////////////////// static ::Assets::AssetState TryGetBoundingBox( Placements::BoundingBox& result, ModelCache& modelCache, const ResChar modelFilename[], unsigned LOD = 0, bool stallWhilePending = false) { auto model = modelCache.GetModelScaffold(modelFilename); if (!model) return ::Assets::AssetState::Invalid; ::Assets::AssetState state; if (stallWhilePending) { state = model->StallAndResolve(); } else { state = model->TryResolve(); } if (state != ::Assets::AssetState::Ready) return state; result = model->GetStaticBoundingBox(LOD); return ::Assets::AssetState::Ready; } class PlacementsRenderer::Pimpl { public: void BeginPrepare(); void EndPrepare(); void ClearPrepared(); void CommitPrepared( RenderCore::Metal::DeviceContext* context, RenderCore::Techniques::ParsingContext& parserContext, unsigned techniqueIndex, RenderCore::Assets::DelayStep delayStep); void FilterDrawCalls(const std::function& predicate); bool HasPrepared(RenderCore::Assets::DelayStep delayStep) const; Placements* CullCell( std::vector& visiblePlacements, RenderCore::Techniques::ParsingContext& parserContext, const PlacementCell& cell); void CullCell( std::vector& visiblePlacements, RenderCore::Techniques::ParsingContext& parserContext, const Placements& placements, const PlacementsQuadTree* quadTree, const Float3x4& cellToWorld); void Render( RenderCore::Metal::DeviceContext* context, RenderCore::Techniques::ParsingContext& parserContext, const Placements& placements, IteratorRange objects, const Float3x4& cellToWorld, const uint64* filterStart = nullptr, const uint64* filterEnd = nullptr); auto GetCachedQuadTree(uint64 cellFilenameHash) const -> const PlacementsQuadTree*; ModelCache& GetModelCache() { return *_cache; } Pimpl( std::shared_ptr placementsCache, std::shared_ptr modelCache); ~Pimpl(); class CellRenderInfo { public: PlacementsCache::Item* _placements; std::unique_ptr _quadTree; CellRenderInfo() {} CellRenderInfo(CellRenderInfo&& moveFrom) never_throws : _placements(moveFrom._placements) , _quadTree(std::move(moveFrom._quadTree)) { moveFrom._placements = nullptr; } CellRenderInfo& operator=(CellRenderInfo&& moveFrom) never_throws { _placements = moveFrom._placements; moveFrom._placements = nullptr; _quadTree = std::move(moveFrom._quadTree); return *this; } private: CellRenderInfo(const CellRenderInfo&); CellRenderInfo& operator=(const CellRenderInfo&); }; std::vector> _cells; std::shared_ptr _placementsCache; std::shared_ptr _cache; DelayedDrawCallSet _preparedRenders; std::shared_ptr _modelFormat; std::shared_ptr _imposters; }; class PlacementsManager::Pimpl { public: std::shared_ptr _renderer; std::shared_ptr _placementsCache; std::shared_ptr _modelCache; std::shared_ptr _intersections; }; class PlacementCellSet::Pimpl { public: std::vector _cells; std::vector>> _cellOverrides; void SetOverride(uint64 guid, std::shared_ptr placements); Placements* GetOverride(uint64 guid); }; Placements* PlacementCellSet::Pimpl::GetOverride(uint64 guid) { auto i = LowerBound(_cellOverrides, guid); if (i != _cellOverrides.end() && i->first == guid) return i->second.get(); return nullptr; } /////////////////////////////////////////////////////////////////////////////////////////////////// void PlacementsRenderer::Pimpl::BeginPrepare() { _preparedRenders.Reset(); if (_imposters) _imposters->Reset(); } void PlacementsRenderer::Pimpl::EndPrepare() { ModelRenderer::Sort(_preparedRenders); } void PlacementsRenderer::Pimpl::ClearPrepared() { _preparedRenders.Reset(); } void PlacementsRenderer::Pimpl::CommitPrepared( RenderCore::Metal::DeviceContext* context, RenderCore::Techniques::ParsingContext& parserContext, unsigned techniqueIndex, RenderCore::Assets::DelayStep delayStep) { // Draw the opaque & translucent parts of models that were previously prepared { auto capture = _cache->GetSharedStateSet().CaptureState( *context, parserContext.GetStateSetResolver(), parserContext.GetStateSetEnvironment()); ModelRenderer::RenderPrepared( RenderCore::Assets::ModelRendererContext(*context, parserContext, techniqueIndex), _cache->GetSharedStateSet(), _preparedRenders, delayStep); } if (delayStep == RenderCore::Assets::DelayStep::OpaqueRender) { if (_imposters) _imposters->Render(*context, parserContext, techniqueIndex); } } void PlacementsRenderer::Pimpl::FilterDrawCalls( const std::function& predicate) { _preparedRenders.Filter(predicate); } bool PlacementsRenderer::Pimpl::HasPrepared(RenderCore::Assets::DelayStep delayStep) const { assert(unsigned(delayStep) < unsigned(RenderCore::Assets::DelayStep::Max)); return !_preparedRenders.IsEmpty(delayStep); } auto PlacementsRenderer::Pimpl::GetCachedQuadTree(uint64 cellFilenameHash) const -> const PlacementsQuadTree* { auto i2 = LowerBound(_cells, cellFilenameHash); if (i2!=_cells.end() && i2->first == cellFilenameHash) { return i2->second._quadTree.get(); } return nullptr; } Placements* PlacementsRenderer::Pimpl::CullCell( std::vector& visibleObjects, RenderCore::Techniques::ParsingContext& parserContext, const PlacementCell& cell) { // Look for a "RenderInfo" for this cell.. and create it if it doesn't exist // Note that there's a bit of extra overhead here: // * in this design, we need to search for the cell by guid id // * however, the cells are probably arranged in a 2d grid, and we probably // know the 2d address -- which means we could go right to the correct // cell. // // But this design allows for a little extra flexibility. We're no restricted // on how the placement cells are arranged, so we can have overlapping cells, or // separate cells for inside/outside/underwater/etc. Or we can have cells that // represent different states (like stages of building a castle, or if a zone // changes over time). // // It seems useful to me. But if the overhead becomes too great, we can just change // to a basic 2d addressing model. if (cell._filename[0] == '[') return nullptr; // hack -- if the cell filename begins with '[', it is a cell from the editor (and should be using _cellOverrides) auto i2 = LowerBound(_cells, cell._filenameHash); if (i2 == _cells.end() || i2->first != cell._filenameHash) { CellRenderInfo newRenderInfo; newRenderInfo._placements = _placementsCache->Get(cell._filenameHash, cell._filename); i2 = _cells.insert(i2, std::make_pair(cell._filenameHash, std::move(newRenderInfo))); } // check if we need to reload placements if (i2->second._placements->_placements->GetDependencyValidation()->GetValidationIndex() != 0) { i2->second._placements->Reload(); i2->second._quadTree.reset(); } if (!i2->second._quadTree) { i2->second._quadTree = std::make_unique( &i2->second._placements->_placements->GetObjectReferences()->_cellSpaceBoundary, sizeof(Placements::ObjectReference), i2->second._placements->_placements->GetObjectReferenceCount()); } CullCell( visibleObjects, parserContext, *i2->second._placements->_placements, i2->second._quadTree.get(), cell._cellToWorld); return i2->second._placements->_placements.get(); } static SupplementRange AsSupplements(const uint64* supplementsBuffer, unsigned supplementsOffset) { if (!supplementsOffset) return SupplementRange(); return SupplementRange( supplementsBuffer+supplementsOffset+1, supplementsBuffer+supplementsOffset+1+supplementsBuffer[supplementsOffset]); } namespace Internal { class RendererHelper { public: template void Render( ModelCache& cache, DelayedDrawCallSet& delayedDrawCalls, const void* filenamesBuffer, const uint64* supplementsBuffer, const Placements::ObjectReference& obj, const Float3x4& cellToWorld, const Float3& cameraPosition); class Metrics { public: unsigned _instancesPrepared; unsigned _uniqueModelsPrepared; unsigned _impostersQueued; Metrics() { _instancesPrepared = 0; _uniqueModelsPrepared = 0; _impostersQueued = 0; } }; Metrics _metrics; RendererHelper(DynamicImposters* imposters) { _currentModel = _currentMaterial = 0ull; _currentSupplements = 0u; auto maxDistance = 1000.f; if (imposters && imposters->IsEnabled()) maxDistance = imposters->GetThresholdDistance(); _maxDistanceSq = maxDistance * maxDistance; _imposters = imposters; _currentModelRendered = false; } protected: uint64 _currentModel, _currentMaterial; unsigned _currentSupplements; ModelCache::Model _current; float _maxDistanceSq; bool _currentModelRendered; DynamicImposters* _imposters; }; template void RendererHelper::Render( ModelCache& cache, DelayedDrawCallSet& delayedDrawCalls, const void* filenamesBuffer, const uint64* supplementsBuffer, const Placements::ObjectReference& obj, const Float3x4& cellToWorld, const Float3& cameraPosition) { // Basic draw distance calculation // many objects don't need to render out to the far clip float distanceSq = MagnitudeSquared( .5f * (obj._cellSpaceBoundary.first + obj._cellSpaceBoundary.second) - cameraPosition); if (constant_expression::result() && distanceSq > _maxDistanceSq) return; // Objects should be sorted by model & material. This is important for // reducing the work load in "_cache". Typically cells will only refer // to a limited number of different types of objects, but the same object // may be repeated many times. In these cases, we want to minimize the // workload for every repeat. auto modelHash = *(uint64*)PtrAdd(filenamesBuffer, obj._modelFilenameOffset); auto materialHash = *(uint64*)PtrAdd(filenamesBuffer, obj._materialFilenameOffset); materialHash = HashCombine(materialHash, modelHash); // Simple LOD calculation based on distanceSq from camera... // Currently all models have only the single LOD. But this // may cause problems with models with multiple LOD, because // it may mean rapidly switching back and forth between // renderers (which can be expensive) // todo -- we need to improve this in 2 critical ways: // 1) more complex metric for selecting the LOD (eg, considering size on screen, maybe triangle density) // - also consider best approach for selecting LOD for very large objects // 2) we need to record the result from last frame, so we can do transitions (eg, using a dither based fade) // // However, that functionality should probably be combined with a change to the scene parser that // to add a more formal "prepare" step. So it will have to wait for now. auto LOD = unsigned(distanceSq / (75.f*75.f)); if ( modelHash != _currentModel || materialHash != _currentMaterial || obj._supplementsOffset != _currentSupplements || std::min(_current._maxLOD, LOD) != _current._selectedLOD) { _current = cache.GetModel( (const ResChar*)PtrAdd(filenamesBuffer, obj._modelFilenameOffset + sizeof(uint64)), (const ResChar*)PtrAdd(filenamesBuffer, obj._materialFilenameOffset + sizeof(uint64)), AsSupplements(supplementsBuffer, obj._supplementsOffset), LOD); _currentModel = modelHash; _currentMaterial = materialHash; _currentSupplements = obj._supplementsOffset; _currentModelRendered = false; } auto localToWorld = Combine(obj._localToCell, cellToWorld); if (constant_expression::result() && distanceSq > _maxDistanceSq) { assert(_imposters); _imposters->Queue(*_current._renderer, *_current._model, localToWorld, cameraPosition); ++_metrics._impostersQueued; return; } // if we have internal transforms, we must use them. // But some models don't have any internal transforms -- in these // cases, the _defaultTransformCount will be zero _current._renderer->Prepare( delayedDrawCalls, cache.GetSharedStateSet(), AsFloat4x4(localToWorld), RenderCore::Assets::MeshToModel(*_current._model)); ++_metrics._instancesPrepared; _metrics._uniqueModelsPrepared += !_currentModelRendered; _currentModelRendered = true; } } static Utility::Internal::StringMeldInPlace QuickMetrics(RenderCore::Techniques::ParsingContext& parserContext) { return StringMeldAppend(parserContext._stringHelpers->_quickMetrics); } void PlacementsRenderer::Pimpl::CullCell( std::vector& visiblePlacements, RenderCore::Techniques::ParsingContext& parserContext, const Placements& placements, const PlacementsQuadTree* quadTree, const Float3x4& cellToWorld) { auto placementCount = placements.GetObjectReferenceCount(); if (!placementCount) return; __declspec(align(16)) auto cellToCullSpace = Combine(cellToWorld, parserContext.GetProjectionDesc()._worldToProjection); const auto* objRef = placements.GetObjectReferences(); if (quadTree) { auto cullResults = quadTree->GetMaxResults(); visiblePlacements.resize(cullResults); PlacementsQuadTree::Metrics metrics; quadTree->CalculateVisibleObjects( cellToCullSpace, &objRef->_cellSpaceBoundary, sizeof(Placements::ObjectReference), AsPointer(visiblePlacements.begin()), cullResults, cullResults, &metrics); visiblePlacements.resize(cullResults); QuickMetrics(parserContext) << "Cull placements cell... AABB test: (" << metrics._nodeAabbTestCount << ") nodes + (" << metrics._payloadAabbTestCount << ") payloads\n"; // we have to sort to return to our expected order std::sort(visiblePlacements.begin(), visiblePlacements.end()); } else { visiblePlacements.reserve(placementCount); for (unsigned c=0; c objects, const Float3x4& cellToWorld, const uint64* filterStart, const uint64* filterEnd) { // // Here we render all of the placements defined by the placement // file in renderInfo._placements. // // Many engines would drop back to a scene-tree representation // for this kind of thing. The advantage of the scene-tree, is that // nodes can become many different things. // // But here, in this case, we want to deal with exactly one type // of thing -- just an object placed in the world. We can always // render other types of things afterwards. So long as we use // the same shared state set and the same prepared state objects, // they will be sorted efficiently for rendering. // // If we know that all objects are just placements -- we can write // a very straight-forward and efficient implementation of exactly // the behaviour we want. That's the advantage of this model. // // Using a scene tree, or some other generic structure, often the // true behaviour of the system can be obscured by layers of // generality. But the behaviour of the system is the most critical // thing in a system like this. We want to be able to design and chart // out the behaviour, and get the exact results we want. Especially // when the behaviour is actually fairly simple. // // So, to that end... Let's find all of the objects to render (using // whatever culling/occlusion methods we need) and prepare them all // for rendering. // const uint64* filterIterator = filterStart; const bool doFilter = filterStart != filterEnd; Internal::RendererHelper helper(_imposters.get()); auto cameraPositionCell = ExtractTranslation(parserContext.GetProjectionDesc()._cameraToWorld); cameraPositionCell = TransformPointByOrthonormalInverse(cellToWorld, cameraPositionCell); const auto* filenamesBuffer = placements.GetFilenamesBuffer(); const auto* supplementsBuffer = placements.GetSupplementsBuffer(); const auto* objRef = placements.GetObjectReferences(); // Filtering is required in some cases (for example, if we want to render only // a single object in highlighted state). Rendering only part of a cell isn't // ideal for this architecture. Mostly the cell is intended to work as a // immutable atomic object. However, we really need filtering for some things. if (_imposters && _imposters->IsEnabled()) { ////////////////////////////////////////////////////////////////// if (doFilter) { for (auto o:objects) { auto& obj = objRef[o]; while (filterIterator != filterEnd && *filterIterator < obj._guid) { ++filterIterator; } if (filterIterator == filterEnd || *filterIterator != obj._guid) { continue; } helper.Render( *_cache, _preparedRenders, filenamesBuffer, supplementsBuffer, obj, cellToWorld, cameraPositionCell); } } else { for (auto o:objects) helper.Render( *_cache, _preparedRenders, filenamesBuffer, supplementsBuffer, objRef[o], cellToWorld, cameraPositionCell); } } else { ////////////////////////////////////////////////////////////////////////////////////////////////////// if (doFilter) { for (auto o:objects) { auto& obj = objRef[o]; while (filterIterator != filterEnd && *filterIterator < obj._guid) { ++filterIterator; } if (filterIterator == filterEnd || *filterIterator != obj._guid) { continue; } helper.Render( *_cache, _preparedRenders, filenamesBuffer, supplementsBuffer, obj, cellToWorld, cameraPositionCell); } } else { for (auto o:objects) helper.Render( *_cache, _preparedRenders, filenamesBuffer, supplementsBuffer, objRef[o], cellToWorld, cameraPositionCell); } } ///////////////////////////////////////////////////////////////////////////////////////////////////////////// QuickMetrics(parserContext) << "Placements cell: (" << helper._metrics._instancesPrepared << ") instances from (" << helper._metrics._uniqueModelsPrepared << ") models. Imposters: (" << helper._metrics._impostersQueued << ")\n"; } PlacementsRenderer::Pimpl::Pimpl( std::shared_ptr placementsCache, std::shared_ptr modelCache) : _placementsCache(std::move(placementsCache)) , _cache(std::move(modelCache)) , _preparedRenders(typeid(ModelRenderer).hash_code()) {} PlacementsRenderer::Pimpl::~Pimpl() {} /////////////////////////////////////////////////////////////////////////////////////////////////// void PlacementsRenderer::SetImposters(std::shared_ptr imposters) { _pimpl->_imposters = std::move(imposters); } PlacementsRenderer::PlacementsRenderer( std::shared_ptr placementsCache, std::shared_ptr modelCache) { _pimpl = std::make_unique(std::move(placementsCache), std::move(modelCache)); } PlacementsRenderer::~PlacementsRenderer() {} class PreCulledPlacements { public: class Cell { public: unsigned _cellIndex; std::vector _objects; Placements* _placements; Float3x4 _cellToWorld; }; std::vector> _cells; }; void PlacementsRenderer::Render( RenderCore::Metal::DeviceContext* context, RenderCore::Techniques::ParsingContext& parserContext, unsigned techniqueIndex, const PlacementCellSet& cellSet) { if (!Tweakable("DoPlacements", true)) { _pimpl->ClearPrepared(); return; } _pimpl->BeginPrepare(); static std::vector visibleObjects; // Render every registered cell // We catch exceptions on a cell based level (so pending cells won't cause other cells to flicker) // non-asset exceptions will throw back to the caller and bypass EndRender() auto& cells = cellSet._pimpl->_cells; const auto& worldToProj = parserContext.GetProjectionDesc()._worldToProjection; for (auto i=cells.begin(); i!=cells.end(); ++i) { if (CullAABB_Aligned(worldToProj, i->_aabbMin, i->_aabbMax)) continue; CATCH_ASSETS_BEGIN // We need to look in the "_cellOverride" list first. // The overridden cells are actually designed for tools. When authoring // placements, we need a way to render them before they are flushed to disk. Placements* plc; visibleObjects.clear(); auto ovr = LowerBound(cellSet._pimpl->_cellOverrides, i->_filenameHash); if (ovr != cellSet._pimpl->_cellOverrides.end() && ovr->first == i->_filenameHash) { _pimpl->CullCell(visibleObjects, parserContext, *ovr->second.get(), nullptr, i->_cellToWorld); plc = ovr->second.get(); } else { plc = _pimpl->CullCell(visibleObjects, parserContext, *i); if (!plc) continue; } _pimpl->Render(context, parserContext, *plc, MakeIteratorRange(visibleObjects), i->_cellToWorld); CATCH_ASSETS_END(parserContext) } // note that exceptions that occur inside the EndRender will throw // back to the caller. _pimpl->EndPrepare(); // Commit opaque now _pimpl->CommitPrepared( context, parserContext, techniqueIndex, RenderCore::Assets::DelayStep::OpaqueRender); } void PlacementsRenderer::Render( RenderCore::Metal::DeviceContext* context, RenderCore::Techniques::ParsingContext& parserContext, PreparedScene& preparedScene, unsigned techniqueIndex, const PlacementCellSet& cellSet) { if (!Tweakable("DoPlacements", true)) { _pimpl->ClearPrepared(); return; } _pimpl->BeginPrepare(); auto* prepared = preparedScene.Get((PreparedScene::Id)&cellSet); if (!prepared) return; for (auto&i:prepared->_cells) _pimpl->Render(context, parserContext, *i->_placements, MakeIteratorRange(i->_objects), i->_cellToWorld); _pimpl->EndPrepare(); _pimpl->CommitPrepared( context, parserContext, techniqueIndex, RenderCore::Assets::DelayStep::OpaqueRender); } void PlacementsRenderer::CommitTransparent( RenderCore::Metal::DeviceContext* context, RenderCore::Techniques::ParsingContext& parserContext, unsigned techniqueIndex, RenderCore::Assets::DelayStep delayStep) { // Assuming that we previously called "Render" to render // the main opaque part of the placements, let's now go // over each cell and render the transluent parts. // we don't need to cull the cells again, because the previous // render should have prepared a list of all the draw calls we // need for this step _pimpl->CommitPrepared(context, parserContext, techniqueIndex, delayStep); } bool PlacementsRenderer::HasPrepared(RenderCore::Assets::DelayStep delayStep) { return _pimpl->HasPrepared(delayStep); } void PlacementsRenderer::CullToPreparedScene( PreparedScene& preparedScene, RenderCore::Techniques::ParsingContext& parserContext, const PlacementCellSet& cellSet) { auto* prepared = preparedScene.Allocate((PreparedScene::Id)&cellSet); auto& cells = cellSet._pimpl->_cells; const auto& worldToProj = parserContext.GetProjectionDesc()._worldToProjection; for (unsigned c=0; c<(unsigned)cells.size(); ++c) { auto& cell = cells[c]; if (CullAABB_Aligned(worldToProj, cell._aabbMin, cell._aabbMax)) continue; auto pcell = std::make_unique(); pcell->_cellIndex = c; pcell->_cellToWorld = cell._cellToWorld; auto ovr = LowerBound(cellSet._pimpl->_cellOverrides, cell._filenameHash); if (ovr != cellSet._pimpl->_cellOverrides.end() && ovr->first == cell._filenameHash) { _pimpl->CullCell(pcell->_objects, parserContext, *ovr->second.get(), nullptr, cell._cellToWorld); pcell->_placements = ovr->second.get(); } else { pcell->_placements = _pimpl->CullCell(pcell->_objects, parserContext, cell); if (!pcell->_placements) continue; } #if 0 auto filenamesBuffer = pcell->_placements->GetFilenamesBuffer(); auto supplementsBuffer = pcell->_placements->GetSupplementsBuffer(); unsigned currentModel = 0; unsigned currentMaterial = 0; unsigned currentSupplements = 0; unsigned currentLOD = 0; for (auto o=pcell->_objects.cbegin(); o!=pcell->_objects.cend(); ++o) { const auto& obj = pcell->_placements->GetObjectReferences()[*o]; auto LOD = 0u; // todo -- clamp the LOD against max somehow if ( obj._modelFilenameOffset != currentModel || obj._materialFilenameOffset != currentMaterial || obj._supplementsOffset != currentSupplements || LOD != currentLOD) { _pimpl->_cache->PrepareModel( (const ResChar*)PtrAdd(filenamesBuffer, obj._modelFilenameOffset + sizeof(uint64)), (const ResChar*)PtrAdd(filenamesBuffer, obj._materialFilenameOffset + sizeof(uint64)), AsSupplements(supplementsBuffer, obj._supplementsOffset), LOD); currentModel = obj._modelFilenameOffset; currentMaterial = obj._materialFilenameOffset; currentSupplements = obj._supplementsOffset; } } #endif prepared->_cells.emplace_back(std::move(pcell)); } } void PlacementsRenderer::RenderFiltered( RenderCore::Metal::DeviceContext* context, RenderCore::Techniques::ParsingContext& parserContext, unsigned techniqueIndex, const PlacementCellSet& cellSet, const PlacementGUID* begin, const PlacementGUID* end, const std::function& predicate) { _pimpl->BeginPrepare(); static std::vector visibleObjects; // We need to take a copy, so we don't overwrite // and reorder the caller's version. if (begin || end) { std::vector copy(begin, end); std::sort(copy.begin(), copy.end()); auto ci = cellSet._pimpl->_cells.begin(); for (auto i=copy.begin(); i!=copy.end();) { auto i2 = i+1; for (; i2!=copy.end() && i2->first == i->first; ++i2) {} while (ci != cellSet._pimpl->_cells.end() && ci->_filenameHash < i->first) { ++ci; } if (ci != cellSet._pimpl->_cells.end() && ci->_filenameHash == i->first) { // re-write the object guids for the renderer's convenience uint64* tStart = &i->first; uint64* t = tStart; while (i < i2) { *t++ = i->second; i++; } CATCH_ASSETS_BEGIN Placements* plcmnts; visibleObjects.clear(); auto ovr = LowerBound(cellSet._pimpl->_cellOverrides, ci->_filenameHash); if (ovr != cellSet._pimpl->_cellOverrides.end() && ovr->first == ci->_filenameHash) { _pimpl->CullCell(visibleObjects, parserContext, *ovr->second.get(), nullptr, ci->_cellToWorld); plcmnts = ovr->second.get(); } else { plcmnts = _pimpl->CullCell(visibleObjects, parserContext, *ci); if (!plcmnts) continue; } _pimpl->Render(context, parserContext, *plcmnts, MakeIteratorRange(visibleObjects), ci->_cellToWorld, tStart, t); CATCH_ASSETS_END(parserContext) } else { i = i2; } } } else { // in this case we're not filtering by object GUID (though we may apply a predicate on the prepared draw calls) for (auto i=cellSet._pimpl->_cells.begin(); i!=cellSet._pimpl->_cells.end(); ++i) { CATCH_ASSETS_BEGIN Placements* plcmnts; visibleObjects.clear(); auto ovr = LowerBound(cellSet._pimpl->_cellOverrides, i->_filenameHash); if (ovr != cellSet._pimpl->_cellOverrides.end() && ovr->first == i->_filenameHash) { _pimpl->CullCell(visibleObjects, parserContext, *ovr->second.get(), nullptr, i->_cellToWorld); plcmnts = ovr->second.get(); } else { plcmnts = _pimpl->CullCell(visibleObjects, parserContext, *i); if (!plcmnts) continue; } _pimpl->Render(context, parserContext, *plcmnts, MakeIteratorRange(visibleObjects), i->_cellToWorld); CATCH_ASSETS_END(parserContext) } } if (predicate) _pimpl->FilterDrawCalls(predicate); _pimpl->EndPrepare(); // we also have to commit translucent steps. We must use the geometry from all translucent steps for (unsigned c=unsigned(RenderCore::Assets::DelayStep::OpaqueRender); cCommitPrepared(context, parserContext, techniqueIndex, RenderCore::Assets::DelayStep(c)); } auto PlacementsRenderer::GetVisibleQuadTrees(const PlacementCellSet& cellSet, const Float4x4& worldToClip) const -> std::vector> { std::vector> result; for (auto i=cellSet._pimpl->_cells.begin(); i!=cellSet._pimpl->_cells.end(); ++i) { if (!CullAABB(worldToClip, i->_aabbMin, i->_aabbMax)) { auto* tree = _pimpl->GetCachedQuadTree(i->_filenameHash); result.push_back(std::make_pair(i->_cellToWorld, tree)); } } return std::move(result); } auto PlacementsRenderer::GetObjectBoundingBoxes(const PlacementCellSet& cellSet, const Float4x4& worldToClip) const -> std::vector> { std::vector> result; for (auto i=cellSet._pimpl->_cells.begin(); i!=cellSet._pimpl->_cells.end(); ++i) { if (!CullAABB(worldToClip, i->_aabbMin, i->_aabbMax)) { auto& placements = Assets::GetAsset(i->_filename); ObjectBoundingBoxes obb; obb._boundingBox = &placements.GetObjectReferences()->_cellSpaceBoundary; obb._stride = sizeof(Placements::ObjectReference); obb._count = placements.GetObjectReferenceCount(); result.push_back(std::make_pair(i->_cellToWorld, obb)); } } return std::move(result); } /////////////////////////////////////////////////////////////////////////////////////////////////// const std::shared_ptr& PlacementsManager::GetRenderer() { return _pimpl->_renderer; } const std::shared_ptr& PlacementsManager::GetIntersections() { return _pimpl->_intersections; } std::shared_ptr PlacementsManager::CreateEditor( const std::shared_ptr& cellSet) { return std::make_shared( cellSet, shared_from_this(), _pimpl->_placementsCache, _pimpl->_modelCache); } PlacementsManager::PlacementsManager(std::shared_ptr modelCache) { // Using the given config file, let's construct the list of // placement cells _pimpl = std::make_unique(); _pimpl->_placementsCache = std::make_shared(); _pimpl->_modelCache = modelCache; _pimpl->_renderer = std::make_shared(_pimpl->_placementsCache, modelCache); _pimpl->_intersections = std::make_shared(_pimpl->_placementsCache, modelCache); } PlacementsManager::~PlacementsManager() {} /////////////////////////////////////////////////////////////////////////////////////////////////// void PlacementCellSet::Pimpl::SetOverride(uint64 guid, std::shared_ptr placements) { auto i = LowerBound(_cellOverrides, guid); if (i ==_cellOverrides.end() || i->first != guid) { if (placements) { _cellOverrides.insert(i, std::make_pair(guid, std::move(placements))); } } else { if (placements) { i->second = std::move(placements); // override the previous one } else { _cellOverrides.erase(i); } } } PlacementCellSet::PlacementCellSet(const WorldPlacementsConfig& cfg, const Float3& worldOffset) { _pimpl = std::make_unique(); _pimpl->_cells.reserve(cfg._cells.size()); for (auto c=cfg._cells.cbegin(); c!=cfg._cells.cend(); ++c) { PlacementCell cell; XlCopyString(cell._filename, c->_file); cell._filenameHash = Hash64(cell._filename); cell._cellToWorld = AsFloat3x4(worldOffset + c->_offset); // note -- we could shrink wrap this bounding box around the objects // inside. This might be necessary, actually, because some objects // may be straddling the edges of the area, so the cell bounding box // should be slightly larger. cell._aabbMin = c->_offset + c->_mins; cell._aabbMax = c->_offset + c->_maxs; _pimpl->_cells.push_back(cell); } } PlacementCellSet::~PlacementCellSet() {} /////////////////////////////////////////////////////////////////////////////////////////////////// class DynamicPlacements : public Placements { public: uint64 AddPlacement( const Float3x4& objectToCell, const std::pair& cellSpaceBoundary, StringSection modelFilename, StringSection materialFilename, SupplementRange supplements, uint64 objectGuid); std::vector& GetObjects() { return _objects; } bool HasObject(uint64 guid); unsigned AddString(StringSection str); unsigned AddSupplements(SupplementRange supplements); DynamicPlacements(const Placements& copyFrom); DynamicPlacements(); }; static uint32 BuildGuid32() { static std::mt19937 generator(std::random_device().operator()()); return generator(); } unsigned DynamicPlacements::AddString(StringSection str) { unsigned result = ~unsigned(0x0); auto stringHash = Hash64(str.begin(), str.end()); auto* start = AsPointer(_filenamesBuffer.begin()); auto* end = AsPointer(_filenamesBuffer.end()); for (auto i=start; i& cellSpaceBoundary, StringSection modelFilename, StringSection materialFilename, SupplementRange supplements, uint64 objectGuid) { assert(modelFilename.Length() > 0); ObjectReference newReference; newReference._localToCell = objectToCell; newReference._cellSpaceBoundary = cellSpaceBoundary; newReference._modelFilenameOffset = AddString(modelFilename); newReference._materialFilenameOffset = AddString(materialFilename); newReference._supplementsOffset = AddSupplements(supplements); newReference._guid = objectGuid; // Insert the new object in sorted order // We're sorting by GUID, which is an arbitrary random number. So the final // order should end up very arbitrary. We could alternatively also sort by model name // (or just encode the model name into to guid somehow) auto i = std::lower_bound(_objects.begin(), _objects.end(), newReference, [](const ObjectReference& lhs, const ObjectReference& rhs) { return lhs._guid < rhs._guid; }); assert(i == _objects.end() || i->_guid != newReference._guid); // hitting this means a GUID collision. Should be extremely unlikely _objects.insert(i, newReference); return newReference._guid; } bool DynamicPlacements::HasObject(uint64 guid) { ObjectReference dummy; XlZeroMemory(dummy); dummy._guid = guid; auto i = std::lower_bound(_objects.begin(), _objects.end(), dummy, [](const ObjectReference& lhs, const ObjectReference& rhs) { return lhs._guid < rhs._guid; }); return (i != _objects.end() && i->_guid == guid); } DynamicPlacements::DynamicPlacements(const Placements& copyFrom) : Placements(copyFrom) {} DynamicPlacements::DynamicPlacements() {} /////////////////////////////////////////////////////////////////////////////////////////////////// struct CompareFilenameHash { public: bool operator()(const PlacementCell& lhs, const PlacementCell& rhs) const { return lhs._filenameHash < rhs._filenameHash; } bool operator()(const PlacementCell& lhs, uint64 rhs) const { return lhs._filenameHash < rhs; } bool operator()(uint64 lhs, const PlacementCell& rhs) const { return lhs < rhs._filenameHash; } }; class PlacementsEditor::Pimpl { public: std::vector>> _dynPlacements; std::shared_ptr _placementsCache; std::shared_ptr _modelCache; std::shared_ptr _cellSet; std::shared_ptr _manager; std::shared_ptr GetDynPlacements(uint64 cellGuid); Float3x4 GetCellToWorld(uint64 cellGuid); const PlacementCell* GetCell(uint64 cellGuid); }; const PlacementCell* PlacementsEditor::Pimpl::GetCell(uint64 cellGuid) { auto p = std::lower_bound(_cellSet->_pimpl->_cells.cbegin(), _cellSet->_pimpl->_cells.cend(), cellGuid, CompareFilenameHash()); if (p != _cellSet->_pimpl->_cells.end() && p->_filenameHash == cellGuid) return AsPointer(p); return nullptr; } Float3x4 PlacementsEditor::Pimpl::GetCellToWorld(uint64 cellGuid) { auto p = std::lower_bound(_cellSet->_pimpl->_cells.cbegin(), _cellSet->_pimpl->_cells.cend(), cellGuid, CompareFilenameHash()); if (p != _cellSet->_pimpl->_cells.end() && p->_filenameHash == cellGuid) return p->_cellToWorld; return Identity(); } static const Placements* GetPlacements(const PlacementCell& cell, const PlacementCellSet& set, PlacementsCache& cache) { auto* ovr = set._pimpl->GetOverride(cell._filenameHash); if (ovr) return ovr; // We can get an invalid resource here. It probably means the file // doesn't exist -- which can happen with an uninitialized data // directory. assert(cell._filename[0]); if (cell._filename[0] != '[') { // used in the editor for dynamic placements TRY { auto* i = cache.Get(cell._filenameHash, cell._filename); return i ? i->_placements.get() : nullptr; } CATCH (const std::exception& e) { LogWarning << "Got invalid resource while loading placements file (" << cell._filename << "). Error: (" << e.what() << ")."; } CATCH_END } return nullptr; } std::shared_ptr PlacementsEditor::Pimpl::GetDynPlacements(uint64 cellGuid) { auto p = LowerBound(_dynPlacements, cellGuid); if (p == _dynPlacements.end() || p->first != cellGuid) { std::shared_ptr placements; // We can get an invalid resource here. It probably means the file // doesn't exist -- which can happen with an uninitialized data // directory. auto cell = GetCell(cellGuid); assert(cell && cell->_filename[0]); if (cell->_filename[0] != '[') { // used in the editor for dynamic placements TRY { auto& sourcePlacements = Assets::GetAsset(cell->_filename); placements = std::make_shared(sourcePlacements); } CATCH (const std::exception& e) { LogWarning << "Got invalid resource while loading placements file (" << cell->_filename << "). If this file exists, but is corrupted, the next save will overwrite it. Error: (" << e.what() << ")."; } CATCH_END } if (!placements) placements = std::make_shared(); _cellSet->_pimpl->SetOverride(cellGuid, placements); p = _dynPlacements.insert(p, std::make_pair(cellGuid, std::move(placements))); } return p->second; } /////////////////////////////////////////////////////////////////////////////////////////////////// class PlacementsIntersections::Pimpl { public: void Find_RayIntersection( const PlacementCellSet& set, std::vector& result, const PlacementCell& cell, const std::pair& cellSpaceRay, const std::function& predicate); void Find_FrustumIntersection( const PlacementCellSet& set, std::vector& result, const PlacementCell& cell, const Float4x4& cellToProjection, const std::function& predicate); void Find_BoxIntersection( const PlacementCellSet& set, std::vector& result, const PlacementCell& cell, const std::pair& cellSpaceBB, const std::function& predicate); std::shared_ptr _placementsCache; std::shared_ptr _modelCache; }; void PlacementsIntersections::Pimpl::Find_RayIntersection( const PlacementCellSet& set, std::vector& result, const PlacementCell& cell, const std::pair& cellSpaceRay, const std::function& predicate) { auto* p = GetPlacements(cell, set, *_placementsCache); if (!p) return; for (unsigned c=0; cGetObjectReferenceCount(); ++c) { auto& obj = p->GetObjectReferences()[c]; // We're only doing a very rough world space bounding box vs ray test here... // Ideally, we should follow up with a more accurate test using the object local // space bounding box if (!RayVsAABB(cellSpaceRay, obj._cellSpaceBoundary.first, obj._cellSpaceBoundary.second)) continue; Placements::BoundingBox localBoundingBox; auto assetState = TryGetBoundingBox( localBoundingBox, *_modelCache, (const ResChar*)PtrAdd(p->GetFilenamesBuffer(), obj._modelFilenameOffset + sizeof(uint64))); // When assets aren't yet ready, we can't perform any intersection tests on them if (assetState != ::Assets::AssetState::Ready) continue; if (!RayVsAABB( cellSpaceRay, AsFloat4x4(obj._localToCell), localBoundingBox.first, localBoundingBox.second)) { continue; } if (predicate) { IntersectionDef def; def._localToWorld = Combine(obj._localToCell, cell._cellToWorld); // note -- we have access to the cell space bounding box. But the local // space box would be better. def._localSpaceBoundingBox = localBoundingBox; def._model = *(uint64*)PtrAdd(p->GetFilenamesBuffer(), obj._modelFilenameOffset); def._material = *(uint64*)PtrAdd(p->GetFilenamesBuffer(), obj._materialFilenameOffset); // allow the predicate to exclude this item if (!predicate(def)) { continue; } } result.push_back(std::make_pair(cell._filenameHash, obj._guid)); } } void PlacementsIntersections::Pimpl::Find_FrustumIntersection( const PlacementCellSet& set, std::vector& result, const PlacementCell& cell, const Float4x4& cellToProjection, const std::function& predicate) { auto* p = GetPlacements(cell, set, *_placementsCache); if (!p) return; for (unsigned c=0; cGetObjectReferenceCount(); ++c) { auto& obj = p->GetObjectReferences()[c]; // We're only doing a very rough world space bounding box vs ray test here... // Ideally, we should follow up with a more accurate test using the object loca // space bounding box if (CullAABB(cellToProjection, obj._cellSpaceBoundary.first, obj._cellSpaceBoundary.second)) { continue; } Placements::BoundingBox localBoundingBox; auto assetState = TryGetBoundingBox( localBoundingBox, *_modelCache, (const ResChar*)PtrAdd(p->GetFilenamesBuffer(), obj._modelFilenameOffset + sizeof(uint64))); // When assets aren't yet ready, we can't perform any intersection tests on them if (assetState != ::Assets::AssetState::Ready) continue; if (CullAABB(Combine(AsFloat4x4(obj._localToCell), cellToProjection), localBoundingBox.first, localBoundingBox.second)) { continue; } if (predicate) { IntersectionDef def; def._localToWorld = Combine(obj._localToCell, cell._cellToWorld); // note -- we have access to the cell space bounding box. But the local // space box would be better. def._localSpaceBoundingBox = localBoundingBox; def._model = *(uint64*)PtrAdd(p->GetFilenamesBuffer(), obj._modelFilenameOffset); def._material = *(uint64*)PtrAdd(p->GetFilenamesBuffer(), obj._materialFilenameOffset); // allow the predicate to exclude this item if (!predicate(def)) { continue; } } result.push_back(std::make_pair(cell._filenameHash, obj._guid)); } } void PlacementsIntersections::Pimpl::Find_BoxIntersection( const PlacementCellSet& set, std::vector& result, const PlacementCell& cell, const std::pair& cellSpaceBB, const std::function& predicate) { auto* p = GetPlacements(cell, set, *_placementsCache); if (!p) return; for (unsigned c=0; cGetObjectReferenceCount(); ++c) { auto& obj = p->GetObjectReferences()[c]; if ( cellSpaceBB.second[0] < obj._cellSpaceBoundary.first[0] || cellSpaceBB.second[1] < obj._cellSpaceBoundary.first[1] || cellSpaceBB.second[2] < obj._cellSpaceBoundary.first[2] || cellSpaceBB.first[0] > obj._cellSpaceBoundary.second[0] || cellSpaceBB.first[1] > obj._cellSpaceBoundary.second[1] || cellSpaceBB.first[2] > obj._cellSpaceBoundary.second[2]) { continue; } if (predicate) { IntersectionDef def; def._localToWorld = Combine(obj._localToCell, cell._cellToWorld); Placements::BoundingBox localBoundingBox; auto assetState = TryGetBoundingBox( localBoundingBox, *_modelCache, (const ResChar*)PtrAdd(p->GetFilenamesBuffer(), obj._modelFilenameOffset + sizeof(uint64))); // When assets aren't yet ready, we can't perform any intersection tests on them if (assetState != ::Assets::AssetState::Ready) continue; // note -- we have access to the cell space bounding box. But the local // space box would be better. def._localSpaceBoundingBox = localBoundingBox; def._model = *(uint64*)PtrAdd(p->GetFilenamesBuffer(), obj._modelFilenameOffset); def._material = *(uint64*)PtrAdd(p->GetFilenamesBuffer(), obj._materialFilenameOffset); // allow the predicate to exclude this item if (!predicate(def)) { continue; } } result.push_back(std::make_pair(cell._filenameHash, obj._guid)); } } std::vector PlacementsIntersections::Find_RayIntersection( const PlacementCellSet& cellSet, const Float3& rayStart, const Float3& rayEnd, const std::function& predicate) { std::vector result; const float placementAssumedMaxRadius = 100.f; for (auto i=cellSet._pimpl->_cells.cbegin(); i!=cellSet._pimpl->_cells.cend(); ++i) { Float3 cellMin = i->_aabbMin - Float3(placementAssumedMaxRadius, placementAssumedMaxRadius, placementAssumedMaxRadius); Float3 cellMax = i->_aabbMax + Float3(placementAssumedMaxRadius, placementAssumedMaxRadius, placementAssumedMaxRadius); if (!RayVsAABB(std::make_pair(rayStart, rayEnd), cellMin, cellMax)) continue; // We need to suppress any exception that occurs (we can get invalid/pending assets here) // \todo -- we need to prepare all shaders and assets required here. It's better to stall // and load the asset than it is to miss an intersection auto worldToCell = InvertOrthonormalTransform(i->_cellToWorld); TRY { _pimpl->Find_RayIntersection( cellSet, result, *i, std::make_pair( TransformPoint(worldToCell, rayStart), TransformPoint(worldToCell, rayEnd)), predicate); } CATCH (const ::Assets::Exceptions::AssetException&) {} CATCH_END } return std::move(result); } std::vector PlacementsIntersections::Find_FrustumIntersection( const PlacementCellSet& cellSet, const Float4x4& worldToProjection, const std::function& predicate) { std::vector result; const float placementAssumedMaxRadius = 100.f; for (auto i=cellSet._pimpl->_cells.cbegin(); i!=cellSet._pimpl->_cells.cend(); ++i) { Float3 cellMin = i->_aabbMin - Float3(placementAssumedMaxRadius, placementAssumedMaxRadius, placementAssumedMaxRadius); Float3 cellMax = i->_aabbMax + Float3(placementAssumedMaxRadius, placementAssumedMaxRadius, placementAssumedMaxRadius); if (CullAABB(worldToProjection, cellMin, cellMax)) { continue; } auto cellToProjection = Combine(i->_cellToWorld, worldToProjection); TRY { _pimpl->Find_FrustumIntersection(cellSet, result, *i, cellToProjection, predicate); } CATCH (const ::Assets::Exceptions::AssetException&) {} CATCH_END } return std::move(result); } std::vector PlacementsIntersections::Find_BoxIntersection( const PlacementCellSet& cellSet, const Float3& worldSpaceMins, const Float3& worldSpaceMaxs, const std::function& predicate) { // Look through all placements to find any that intersect with the given // world space bounding box. // // Note that there's a potential issue here -- the world space bounding // box of the cell isn't updated when the dynamic placements change. So // it's possible that some dynamic placements might intersect with our // test bounding box, but not the cell bounding box... We have to be // careful about this. It might mean that we have to test more cells than // expected. std::vector result; const float placementAssumedMaxRadius = 100.f; for (auto i=cellSet._pimpl->_cells.cbegin(); i!=cellSet._pimpl->_cells.cend(); ++i) { if ( worldSpaceMaxs[0] < (i->_aabbMin[0] - placementAssumedMaxRadius) || worldSpaceMaxs[1] < (i->_aabbMin[1] - placementAssumedMaxRadius) || worldSpaceMins[0] > (i->_aabbMax[0] + placementAssumedMaxRadius) || worldSpaceMins[1] > (i->_aabbMax[1] + placementAssumedMaxRadius)) { continue; } // This cell intersects with the bounding box (or almost does). // We have to test all internal objects. First, transform the bounding // box into local cell space. auto cellSpaceBB = TransformBoundingBox( InvertOrthonormalTransform(i->_cellToWorld), std::make_pair(worldSpaceMins, worldSpaceMaxs)); // We need to use the renderer to get either the asset or the // override placements associated with this cell. It's a little awkward // Note that we could use the quad tree to acceleration these tests. TRY { _pimpl->Find_BoxIntersection(cellSet, result, *i, cellSpaceBB, predicate); } CATCH (const ::Assets::Exceptions::AssetException&) {} CATCH_END } return std::move(result); } PlacementsIntersections::PlacementsIntersections( std::shared_ptr placementsCache, std::shared_ptr modelCache) { _pimpl = std::make_unique(); _pimpl->_placementsCache = std::move(placementsCache); _pimpl->_modelCache = std::move(modelCache); } PlacementsIntersections::~PlacementsIntersections() {} /////////////////////////////////////////////////////////////////////////////////////////////////// class CompareObjectId { public: bool operator()(const Placements::ObjectReference& lhs, uint64 rhs) { return lhs._guid < rhs; } bool operator()(uint64 lhs, const Placements::ObjectReference& rhs) { return lhs < rhs._guid; } bool operator()(const Placements::ObjectReference& lhs, const Placements::ObjectReference& rhs) { return lhs._guid < rhs._guid; } }; class Transaction : public PlacementsEditor::ITransaction { public: typedef PlacementsEditor::ObjTransDef ObjTransDef; typedef PlacementsEditor::PlacementsTransform PlacementsTransform; const ObjTransDef& GetObject(unsigned index) const; const ObjTransDef& GetObjectOriginalState(unsigned index) const; PlacementGUID GetGuid(unsigned index) const; PlacementGUID GetOriginalGuid(unsigned index) const; unsigned GetObjectCount() const; std::pair GetLocalBoundingBox(unsigned index) const; std::pair GetWorldBoundingBox(unsigned index) const; std::string GetMaterialName(unsigned objectIndex, uint64 materialGuid) const; virtual void SetObject(unsigned index, const ObjTransDef& newState); virtual bool Create(const ObjTransDef& newState); virtual bool Create(PlacementGUID guid, const ObjTransDef& newState); virtual void Delete(unsigned index); virtual void Commit(); virtual void Cancel(); virtual void UndoAndRestart(); Transaction( PlacementsEditor::Pimpl* editorPimpl, const PlacementGUID* placementsBegin, const PlacementGUID* placementsEnd, PlacementsEditor::TransactionFlags::BitField transactionFlags = 0); ~Transaction(); protected: PlacementsEditor::Pimpl* _editorPimpl; std::vector _originalState; std::vector _objects; std::vector _originalGuids; std::vector _pushedGuids; void PushObj(unsigned index, const ObjTransDef& newState); bool GetLocalBoundingBox_Stall( std::pair& result, const ResChar filename[]) const; enum State { Active, Committed }; State _state; }; auto Transaction::GetObject(unsigned index) const -> const ObjTransDef& { return _objects[index]; } auto Transaction::GetObjectOriginalState(unsigned index) const -> const ObjTransDef& { return _originalState[index]; } auto Transaction::GetGuid(unsigned index) const -> PlacementGUID { return _pushedGuids[index]; } auto Transaction::GetOriginalGuid(unsigned index) const -> PlacementGUID { return _originalGuids[index]; } unsigned Transaction::GetObjectCount() const { assert(_originalGuids.size() == _originalState.size()); assert(_originalGuids.size() == _objects.size()); assert(_originalGuids.size() == _pushedGuids.size()); return (unsigned)_originalGuids.size(); } bool Transaction::GetLocalBoundingBox_Stall(std::pair& result, const ResChar filename[]) const { // get the local bounding box for a model // ... but stall waiting for any pending resources auto* model = _editorPimpl->_modelCache->GetModelScaffold(filename); auto state = model->StallAndResolve(); if (state != ::Assets::AssetState::Ready) { result = std::make_pair(Float3(FLT_MAX, FLT_MAX, FLT_MAX), Float3(-FLT_MAX, -FLT_MAX, -FLT_MAX)); return false; } result = model->GetStaticBoundingBox(); return true; } std::pair Transaction::GetLocalBoundingBox(unsigned index) const { std::pair result; GetLocalBoundingBox_Stall(result, _objects[index]._model.c_str()); return result; } std::pair Transaction::GetWorldBoundingBox(unsigned index) const { auto guid = _pushedGuids[index]; auto cellToWorld = _editorPimpl->GetCellToWorld(guid.first); const Placements* placements = nullptr; auto* cell = _editorPimpl->GetCell(guid.first); if (cell) placements = GetPlacements(*cell, *_editorPimpl->_cellSet, *_editorPimpl->_placementsCache); if (!placements) return std::make_pair(Float3(FLT_MAX, FLT_MAX, FLT_MAX), Float3(-FLT_MAX, -FLT_MAX, -FLT_MAX)); auto count = placements->GetObjectReferenceCount(); auto* objects = placements->GetObjectReferences(); auto dst = std::lower_bound(objects, &objects[count], guid.second, CompareObjectId()); return TransformBoundingBox(cellToWorld, dst->_cellSpaceBoundary); } std::string Transaction::GetMaterialName(unsigned objectIndex, uint64 materialGuid) const { if (objectIndex >= _objects.size()) return std::string(); // attempt to get the auto scaff = _editorPimpl->_modelCache->GetScaffolds( _objects[objectIndex]._model.c_str(), _objects[objectIndex]._material.c_str()); if (!scaff._material) return std::string(); auto res = scaff._material->GetMaterialName(materialGuid); return res ? std::string(res) : std::string(); } void Transaction::SetObject(unsigned index, const ObjTransDef& newState) { auto& currentState = _objects[index]; auto currTrans = currentState._transaction; if (currTrans != ObjTransDef::Deleted) { currentState = newState; currentState._transaction = (currTrans == ObjTransDef::Created || currTrans == ObjTransDef::Error) ? ObjTransDef::Created : ObjTransDef::Modified; PushObj(index, currentState); } } static bool CompareGUID(const PlacementGUID& lhs, const PlacementGUID& rhs) { if (lhs.first == rhs.first) { return lhs.second < rhs.second; } return lhs.first < rhs.first; } static uint32 EverySecondBit(uint64 input) { uint32 result = 0; for (unsigned c=0; c<32; ++c) { result |= uint32((input >> (uint64(c)*2ull)) & 0x1ull)< StringToSupplementGuids(const char stringNames[]) { if (!stringNames || !*stringNames) return std::vector(); std::vector result; const auto* i = stringNames; const auto* end = XlStringEnd(stringNames); for (;;) { auto comma = XlFindChar(i, ','); if (!comma) comma = end; if (i == comma) break; // if the string is exactly a hex number, then // will we just use that value. (otherwise we // need to hash the string) const char* parseEnd = nullptr; auto hash = XlAtoUI64(i, &parseEnd, 16); if (parseEnd != comma) hash = ConstHash64FromString(i, comma); result.push_back(hash); i = comma; } return std::move(result); } static std::string SupplementsGuidsToString(SupplementRange guids) { if (guids.empty()) return std::string(); std::stringstream str; const auto* i = guids.begin(); str << std::hex << *i++; for (;i boundingBox; if (!GetLocalBoundingBox_Stall(boundingBox, newState._model.c_str())) { // if we can't get a bounding box, then we can't really // create this object. We need to cancel the creation operation return false; } auto boundingBoxCentre = LinearInterpolate(boundingBox.first, boundingBox.second, 0.5f); auto worldSpaceCenter = TransformPoint(newState._localToWorld, boundingBoxCentre); std::string materialFilename = newState._material; PlacementGUID guid(0, 0); PlacementsTransform localToCell = Identity(); auto& cells = _editorPimpl->_cellSet->_pimpl->_cells; for (auto i=cells.cbegin(); i!=cells.cend(); ++i) { if ( worldSpaceCenter[0] >= i->_captureMins[0] && worldSpaceCenter[0] < i->_captureMaxs[0] && worldSpaceCenter[1] >= i->_captureMins[1] && worldSpaceCenter[1] < i->_captureMaxs[1]) { // This is the correct cell. Look for a dynamic placement associated auto dynPlacements = _editorPimpl->GetDynPlacements(i->_filenameHash); localToCell = Combine(newState._localToWorld, InvertOrthonormalTransform(i->_cellToWorld)); // Build a GUID for this object. We're going to sort by GUID, and we want // objects with the name model and material to appear together. So let's // build the top 32 bits from the model and material hash. The bottom // 32 bits can be a random number. // Note that it's possible that the bottom 32 bits could collide with an // existing object. It's unlikely, but possible. So let's make sure we // have a unique GUID before we add it. uint64 id, idTopPart = ObjectIdTopPart(newState._model, materialFilename); for (;;) { auto id32 = BuildGuid32(); id = idTopPart | uint64(id32); if (!dynPlacements->HasObject(id)) { break; } } auto suppGuid = StringToSupplementGuids(newState._supplements.c_str()); dynPlacements->AddPlacement( localToCell, TransformBoundingBox(localToCell, boundingBox), MakeStringSection(newState._model), MakeStringSection(materialFilename), MakeIteratorRange(suppGuid), id); guid = PlacementGUID(i->_filenameHash, id); break; } } if (guid.first == 0 && guid.second == 0) return false; // couldn't find a way to create this object ObjTransDef newObj = newState; newObj._transaction = ObjTransDef::Created; ObjTransDef originalState; originalState._localToWorld = Identity(); originalState._transaction = ObjTransDef::Error; auto insertLoc = std::lower_bound(_originalGuids.begin(), _originalGuids.end(), guid, CompareGUID); auto insertIndex = std::distance(_originalGuids.begin(), insertLoc); _originalState.insert(_originalState.begin() + insertIndex, originalState); _objects.insert(_objects.begin() + insertIndex, newObj); _originalGuids.insert(_originalGuids.begin() + insertIndex, guid); _pushedGuids.insert(_pushedGuids.begin() + insertIndex, guid); return true; } bool Transaction::Create(PlacementGUID guid, const ObjTransDef& newState) { std::pair boundingBox; if (!GetLocalBoundingBox_Stall(boundingBox, newState._model.c_str())) { // if we can't get a bounding box, then we can't really // create this object. We need to cancel the creation operation return false; } auto boundingBoxCentre = LinearInterpolate(boundingBox.first, boundingBox.second, 0.5f); auto worldSpaceCenter = TransformPoint(newState._localToWorld, boundingBoxCentre); std::string materialFilename = newState._material; PlacementsTransform localToCell = Identity(); bool foundCell = false; auto& cells = _editorPimpl->_cellSet->_pimpl->_cells; for (auto i=cells.cbegin(); i!=cells.cend(); ++i) { if (i->_filenameHash == guid.first) { auto dynPlacements = _editorPimpl->GetDynPlacements(i->_filenameHash); localToCell = Combine(newState._localToWorld, InvertOrthonormalTransform(i->_cellToWorld)); auto idTopPart = ObjectIdTopPart(newState._model, materialFilename); uint64 id = idTopPart | uint64(guid.second & 0xffffffffull); if (dynPlacements->HasObject(id)) { assert(0); // got a hash collision or duplicated id return false; } auto supp = StringToSupplementGuids(newState._supplements.c_str()); dynPlacements->AddPlacement( localToCell, TransformBoundingBox(localToCell, boundingBox), MakeStringSection(newState._model), MakeStringSection(materialFilename), MakeIteratorRange(supp), id); guid.second = id; foundCell = true; break; } } if (!foundCell) return false; // couldn't find a way to create this object ObjTransDef newObj = newState; newObj._transaction = ObjTransDef::Created; ObjTransDef originalState; originalState._localToWorld = Identity(); originalState._transaction = ObjTransDef::Error; auto insertLoc = std::lower_bound(_originalGuids.begin(), _originalGuids.end(), guid, CompareGUID); auto insertIndex = std::distance(_originalGuids.begin(), insertLoc); _originalState.insert(_originalState.begin() + insertIndex, originalState); _objects.insert(_objects.begin() + insertIndex, newObj); _originalGuids.insert(_originalGuids.begin() + insertIndex, guid); _pushedGuids.insert(_pushedGuids.begin() + insertIndex, guid); return true; } void Transaction::Delete(unsigned index) { if (_objects[index]._transaction != ObjTransDef::Error) { _objects[index]._transaction = ObjTransDef::Deleted; PushObj(index, _objects[index]); } } void Transaction::PushObj(unsigned index, const ObjTransDef& newState) { // update the DynPlacements object with the changes to the object at index "index" std::vector originalState; auto& guid = _pushedGuids[index]; auto cellToWorld = _editorPimpl->GetCellToWorld(guid.first); auto dynPlacements = _editorPimpl->GetDynPlacements(guid.first); auto& objects = dynPlacements->GetObjects(); auto dst = std::lower_bound(objects.begin(), objects.end(), guid.second, CompareObjectId()); std::pair cellSpaceBoundary; PlacementsTransform localToCell; std::string materialFilename = newState._material; if (newState._transaction != ObjTransDef::Deleted && newState._transaction != ObjTransDef::Error) { localToCell = Combine(newState._localToWorld, InvertOrthonormalTransform(cellToWorld)); std::pair boundingBox; if (GetLocalBoundingBox_Stall(boundingBox, newState._model.c_str())) { cellSpaceBoundary = TransformBoundingBox(localToCell, boundingBox); } else { LogWarning << "Cannot get bounding box for model (" << newState._model << ") while updating placement object."; cellSpaceBoundary = std::make_pair(Float3(FLT_MAX, FLT_MAX, FLT_MAX), Float3(-FLT_MAX, -FLT_MAX, -FLT_MAX)); } } // todo -- handle the case where an object should move to another cell! // this should actually change the first part of the GUID // Also, if the type of the object changes, it should change the guid... Which // means that it should change location in the list of objects. In this case // we should erase the old object and create a new one bool isDeleteOp = newState._transaction == ObjTransDef::Deleted || newState._transaction == ObjTransDef::Error; bool destroyExisting = isDeleteOp; bool hasExisting = dst != objects.end() && dst->_guid == guid.second; // awkward case where the object id has changed... This can happen // if the object model or material was changed auto newIdTopPart = ObjectIdTopPart(newState._model, materialFilename); bool objectIdChanged = newIdTopPart != (guid.second & 0xffffffff00000000ull); if (objectIdChanged) { auto id32 = uint32(guid.second); for (;;) { guid.second = newIdTopPart | uint64(id32); if (!dynPlacements->HasObject(guid.second)) { break; } id32 = BuildGuid32(); } // destroy & re-create destroyExisting = true; } if (destroyExisting && hasExisting) { objects.erase(dst); hasExisting = false; } if (!isDeleteOp) { auto suppGuids = StringToSupplementGuids(newState._supplements.c_str()); if (hasExisting) { dst->_localToCell = localToCell; dst->_modelFilenameOffset = dynPlacements->AddString(MakeStringSection(newState._model)); dst->_materialFilenameOffset = dynPlacements->AddString(MakeStringSection(materialFilename)); dst->_supplementsOffset = dynPlacements->AddSupplements(MakeIteratorRange(suppGuids)); dst->_cellSpaceBoundary = cellSpaceBoundary; } else { dynPlacements->AddPlacement( localToCell, cellSpaceBoundary, MakeStringSection(newState._model), MakeStringSection(materialFilename), MakeIteratorRange(suppGuids), guid.second); } } } void Transaction::Commit() { _state = Committed; } void Transaction::Cancel() { if (_state == Active) { // we need to revert all of the objects to their original state UndoAndRestart(); } _state = Committed; } void Transaction::UndoAndRestart() { if (_state != Active) return; // we just have to reset all objects to their previous state for (unsigned c=0; c<_objects.size(); ++c) { _objects[c] = _originalState[c]; PushObj(c, _originalState[c]); } } Transaction::Transaction( PlacementsEditor::Pimpl* editorPimpl, const PlacementGUID* guidsBegin, const PlacementGUID* guidsEnd, PlacementsEditor::TransactionFlags::BitField transactionFlags) { // We need to sort; because this method is mostly assuming we're working // with a sorted list. Most of the time originalPlacements will be close // to sorted order (which, of course, means that quick sort isn't ideal, but, anyway...) auto guids = std::vector(guidsBegin, guidsEnd); std::sort(guids.begin(), guids.end(), CompareGUID); std::vector originalState; auto& cells = editorPimpl->_cellSet->_pimpl->_cells; auto cellIterator = cells.begin(); for (auto i=guids.begin(); i!=guids.end();) { auto iend = std::find_if(i, guids.end(), [&](const PlacementGUID& guid) { return guid.first != i->first; }); cellIterator = std::lower_bound(cellIterator, cells.end(), i->first, CompareFilenameHash()); if (cellIterator == cells.end() || cellIterator->_filenameHash != i->first) { i = guids.erase(i, iend); continue; } auto cellToWorld = cellIterator->_cellToWorld; auto* placements = GetPlacements(*cellIterator, *editorPimpl->_cellSet, *editorPimpl->_placementsCache); if (!placements) { // If we didn't get an actual "placements" object, it means that nothing has been created // in this cell yet (and maybe the original asset is invalid/uncreated). // We should treat this the same as if the object didn't exists previously. for (; i != iend; ++i) { ObjTransDef def; def._localToWorld = Identity(); def._transaction = ObjTransDef::Error; originalState.push_back(def); } continue; } if (transactionFlags & PlacementsEditor::TransactionFlags::IgnoreIdTop32Bits) { // Sometimes we want to ignore the top 32 bits of the id. It works, but it's // much less efficient, because we can't take advantage of the sorting. // Ideally we should avoid this path for (;i != iend; ++i) { uint32 comparison = uint32(i->second); auto pend = &placements->GetObjectReferences()[placements->GetObjectReferenceCount()]; auto pIterator = std::find_if( placements->GetObjectReferences(), pend, [=](const Placements::ObjectReference& obj) { return uint32(obj._guid) == comparison; }); if (pIterator!=pend) { i->second = pIterator->_guid; // set the recorded guid to the full guid ObjTransDef def; def._localToWorld = Combine(pIterator->_localToCell, cellToWorld); def._model = (const ResChar*)PtrAdd(placements->GetFilenamesBuffer(), sizeof(uint64) + pIterator->_modelFilenameOffset); def._material = (const ResChar*)PtrAdd(placements->GetFilenamesBuffer(), sizeof(uint64) + pIterator->_materialFilenameOffset); def._supplements = SupplementsGuidsToString(AsSupplements(placements->GetSupplementsBuffer(), pIterator->_supplementsOffset)); def._transaction = ObjTransDef::Unchanged; originalState.push_back(def); } else { // we couldn't find an original for this object. It's invalid ObjTransDef def; def._localToWorld = Identity(); def._transaction = ObjTransDef::Error; originalState.push_back(def); } } } else { auto pIterator = placements->GetObjectReferences(); auto pEnd = &placements->GetObjectReferences()[placements->GetObjectReferenceCount()]; for (;i != iend; ++i) { // Here, we're assuming everything is sorted, so we can just march forward // through the destination placements list pIterator = std::lower_bound(pIterator, pEnd, i->second, CompareObjectId()); if (pIterator != pEnd && pIterator->_guid == i->second) { // Build a ObjTransDef object from this object, and record it ObjTransDef def; def._localToWorld = Combine(pIterator->_localToCell, cellToWorld); def._model = (const ResChar*)PtrAdd(placements->GetFilenamesBuffer(), sizeof(uint64) + pIterator->_modelFilenameOffset); def._material = (const ResChar*)PtrAdd(placements->GetFilenamesBuffer(), sizeof(uint64) + pIterator->_materialFilenameOffset); def._supplements = SupplementsGuidsToString(AsSupplements(placements->GetSupplementsBuffer(), pIterator->_supplementsOffset)); def._transaction = ObjTransDef::Unchanged; originalState.push_back(def); } else { // we couldn't find an original for this object. It's invalid ObjTransDef def; def._localToWorld = Identity(); def._transaction = ObjTransDef::Error; originalState.push_back(def); } } } } _objects = originalState; _originalState = std::move(originalState); _originalGuids = guids; _pushedGuids = std::move(guids); _editorPimpl = editorPimpl; _state = Active; } Transaction::~Transaction() { if (_state == Active) { Cancel(); } } uint64 PlacementsEditor::CreateCell( const ::Assets::ResChar name[], const Float2& mins, const Float2& maxs) { // The implementation here is not great. Originally, PlacementsManager // was supposed to be constructed with all of it's cells already created. // But we need create/delete for the interface with the editor PlacementCell newCell; XlCopyString(newCell._filename, name); newCell._filenameHash = Hash64(newCell._filename); newCell._cellToWorld = Identity(); newCell._aabbMin = Expand(mins, -10000.f); newCell._aabbMax = Expand(maxs, 10000.f); newCell._captureMins = mins; newCell._captureMaxs = maxs; _pimpl->_cellSet->_pimpl->_cells.push_back(newCell); return newCell._filenameHash; } bool PlacementsEditor::RemoveCell(uint64 id) { auto i = std::lower_bound(_pimpl->_cellSet->_pimpl->_cells.begin(), _pimpl->_cellSet->_pimpl->_cells.end(), id, CompareFilenameHash()); if (i != _pimpl->_cellSet->_pimpl->_cells.end() && i->_filenameHash == id) { _pimpl->_cellSet->_pimpl->_cells.erase(i); return true; } return false; } uint64 PlacementsEditor::GenerateObjectGUID() { return uint64(BuildGuid32()); } void PlacementsEditor::PerformGUIDFixup(PlacementGUID* begin, PlacementGUID* end) const { std::sort(begin, end); auto ci = _pimpl->_cellSet->_pimpl->_cells.begin(); for (auto i = begin; i != end;) { auto i2 = i + 1; for (; i2 != end && i2->first == i->first; ++i2) {} while (ci != _pimpl->_cellSet->_pimpl->_cells.end() && ci->_filenameHash < i->first) { ++ci; } if (ci != _pimpl->_cellSet->_pimpl->_cells.end() && ci->_filenameHash == i->first) { // The ids will usually have their // top 32 bit zeroed out. We must fix them by finding the match placements // in our cached placements, and fill in the top 32 bits... const auto* cachedPlacements = GetPlacements(*ci, *_pimpl->_cellSet, *_pimpl->_placementsCache); if (!cachedPlacements) { i = i2; continue; } auto count = cachedPlacements->GetObjectReferenceCount(); const auto* placements = cachedPlacements->GetObjectReferences(); for (auto i3 = i; i3 < i2; ++i3) { auto p = std::find_if(placements, &placements[count], [=](const Placements::ObjectReference& obj) { return uint32(obj._guid) == uint32(i3->second); }); if (p != &placements[count]) i3->second = p->_guid; } } i = i2; } // re-sort again std::sort(begin, end); } std::pair PlacementsEditor::CalculateCellBoundary(uint64 cellId) const { // Find the given cell within our list, and calculate the true boundary // of all the placements within it std::pair result(Float3(FLT_MAX, FLT_MAX, FLT_MAX), Float3(-FLT_MAX, -FLT_MAX, -FLT_MAX)); const Placements* p = nullptr; for (auto i = _pimpl->_dynPlacements.begin(); i!=_pimpl->_dynPlacements.end(); ++i) if (i->first == cellId) { p = i->second.get(); break; } if (!p) { auto* c = _pimpl->GetCell(cellId); if (c) p = GetPlacements(*c, *_pimpl->_cellSet, *_pimpl->_placementsCache); } if (!p) return result; auto*r = p->GetObjectReferences(); for (unsigned c=0; cGetObjectReferenceCount(); ++c) { result.first[0] = std::min(result.first[0], r[c]._cellSpaceBoundary.first[0]); result.first[1] = std::min(result.first[1], r[c]._cellSpaceBoundary.first[1]); result.first[2] = std::min(result.first[2], r[c]._cellSpaceBoundary.first[2]); result.second[0] = std::max(result.second[0], r[c]._cellSpaceBoundary.second[0]); result.second[1] = std::max(result.second[1], r[c]._cellSpaceBoundary.second[1]); result.second[2] = std::max(result.second[2], r[c]._cellSpaceBoundary.second[2]); } return result; } static void SavePlacements(const ResChar outputFilename[], Placements& placements) { placements.Write(outputFilename); ConsoleRig::Console::GetInstance().Print( StringMeld<256>() << "Writing placements to: " << outputFilename << "\n"); } void PlacementsEditor::WriteAllCells() { // Save all of the placement files that have changed. // // Changed placement cells will have a "dynamic" placements object associated. // These should get flushed to disk. Then we can delete the dynamic placements, // because the changed static placements should get automatically reloaded from // disk (making the dynamic placements cells now redundant) // // We may need to commit or cancel any active transaction. How do we know // if we need to commit or cancel them? for (auto i = _pimpl->_dynPlacements.begin(); i!=_pimpl->_dynPlacements.end(); ++i) { auto cellGuid = i->first; auto& placements = *i->second; const auto* cell = _pimpl->GetCell(cellGuid); if (cell) { SavePlacements(cell->_filename, placements); // clear the renderer links _pimpl->_cellSet->_pimpl->SetOverride(cellGuid, nullptr); } } _pimpl->_dynPlacements.clear(); } void PlacementsEditor::WriteCell(uint64 cellId, const Assets::ResChar destinationFile[]) const { // Save a single placement cell file // This function is intended for tools, so we will aggressively throw exceptions on errors for (auto i=_pimpl->_dynPlacements.begin(); i!=_pimpl->_dynPlacements.end(); ++i) { if (i->first != cellId) continue; auto& placements = *i->second; placements.Write(destinationFile); return; } Throw( ::Exceptions::BasicLabel("Could not find cell with given id (0x%08x%08x). Saving cancelled", uint32(cellId>>32), uint32(cellId))); } std::string PlacementsEditor::GetMetricsString(uint64 cellId) const { auto* cell = _pimpl->GetCell(cellId); if (!cell) return "Placements not found"; auto* placements = GetPlacements(*cell, *_pimpl->_cellSet, *_pimpl->_placementsCache); if (!placements) return "Placements not found"; // create a breakdown of the contents of the placements, showing // some important metrics std::stringstream result; result << "[Model Name] [Material Name] Count" << std::endl; auto count = placements->GetObjectReferenceCount(); auto* refs = placements->GetObjectReferences(); const auto* fns = (const char*)placements->GetFilenamesBuffer(); for (unsigned c=0; c PlacementsEditor::GetModelBoundingBox(const ResChar modelName[]) const { Placements::BoundingBox boundingBox; auto assetState = TryGetBoundingBox(boundingBox, *_pimpl->_modelCache, modelName, 0, true); if (assetState != ::Assets::AssetState::Ready) return std::make_pair(Float3(FLT_MAX, FLT_MAX, FLT_MAX), Float3(-FLT_MAX, -FLT_MAX, -FLT_MAX)); return boundingBox; } auto PlacementsEditor::Transaction_Begin( const PlacementGUID* placementsBegin, const PlacementGUID* placementsEnd, TransactionFlags::BitField transactionFlags) -> std::shared_ptr { return std::make_shared(_pimpl.get(), placementsBegin, placementsEnd, transactionFlags); } std::shared_ptr PlacementsEditor::GetManager() { return _pimpl->_manager; } const PlacementCellSet& PlacementsEditor::GetCellSet() const { return *_pimpl->_cellSet; } PlacementsEditor::PlacementsEditor( std::shared_ptr cellSet, std::shared_ptr manager, std::shared_ptr placementsCache, std::shared_ptr modelCache) { _pimpl = std::make_unique(); _pimpl->_cellSet = std::move(cellSet); _pimpl->_placementsCache = std::move(placementsCache); _pimpl->_modelCache = std::move(modelCache); _pimpl->_manager = std::move(manager); } PlacementsEditor::~PlacementsEditor() {} /////////////////////////////////////////////////////////////////////////////////////////////////// WorldPlacementsConfig::WorldPlacementsConfig( InputStreamFormatter& formatter, const ::Assets::DirectorySearchRules& searchRules) : WorldPlacementsConfig() { Document> doc(formatter); for (auto c=doc.FirstChild(); c; c=c.NextSibling()) { Cell cell; cell._offset = c(u("Offset"), Float3(0,0,0)); cell._mins = c(u("Mins"), Float3(0,0,0)); cell._maxs = c(u("Maxs"), Float3(0,0,0)); auto baseFile = Conversion::Convert<::Assets::rstring>( c.Attribute(u("NativeFile")).Value().AsString()); searchRules.ResolveFile( cell._file, dimof(cell._file), baseFile.c_str()); _cells.push_back(cell); } } WorldPlacementsConfig::WorldPlacementsConfig() { } } 1-10 /* * _____ ___ ___ | * | _ |___ ___ _ _|_ |_ | | C/C++ framework for 32-bit AVRs * | | -_| _| | |_ | _| | * |__|__|___|_| |_ |___|___| | https://github.com/aery32 * |___| | * * Copyright (c) 2012-2013, * All rights reserved. * * LICENSE * * New BSD License, see the LICENSE.txt bundled with this package. If you did * not receive a copy of the license and are unable to obtain it through the * world-wide-web, please send an email to so we can send * you a copy. */ #include "aery32/pm.h" namespace aery { volatile avr32_pm_t *pm = &AVR32_PM; volatile avr32_pm_pll_t *pll0 = &AVR32_PM.PLL[0]; volatile avr32_pm_pll_t *pll1 = &AVR32_PM.PLL[1]; } #define CKSEL_RESET_MASK(SEL) \ (~(AVR32_PM_CKSEL_##SEL##SEL_MASK | AVR32_PM_CKSEL_##SEL##DIV_MASK)) #define CKSEL_PRESCALER_MASK(VAR, SEL) \ (((VAR - 1) << AVR32_PM_CKSEL_##SEL##SEL_OFFSET) | AVR32_PM_CKSEL_##SEL##DIV_MASK) #define CKSEL_HASDIV(VAR, SEL) \ ((VAR & AVR32_PM_CKSEL_##SEL##DIV_MASK) != 0) #define CKSEL_GETDIV(VAR, SEL) \ ((VAR & AVR32_PM_CKSEL_##SEL##SEL_MASK) >> AVR32_PM_CKSEL_##SEL##SEL_OFFSET) int aery::pm_start_osc(uint8_t oscnum, enum Pm_osc_mode mode, enum Pm_osc_startup startup) { switch (oscnum) { case 0: if (AVR32_PM.MCCTRL.osc0en == 1) return -1; if (mode == OSC_MODE_OSC32) return -1; AVR32_PM.OSCCTRL0.mode = mode; AVR32_PM.OSCCTRL0.startup = startup; AVR32_PM.MCCTRL.osc0en = 1; break; case 1: if (AVR32_PM.MCCTRL.osc1en == 1) return -1; if (mode == OSC_MODE_OSC32) return -1; AVR32_PM.OSCCTRL1.mode = mode; AVR32_PM.OSCCTRL1.startup = startup; AVR32_PM.MCCTRL.osc1en = 1; break; case 32: if (AVR32_PM.OSCCTRL32.osc32en == 1) return -1; if (mode != OSC_MODE_OSC32 || mode != OSC_MODE_EXTERNAL) return -1; AVR32_PM.OSCCTRL32.mode = mode; AVR32_PM.OSCCTRL32.startup = startup; AVR32_PM.OSCCTRL32.osc32en = 1; break; default: return -1; } return 0; } int aery::pm_init_pllvco(volatile avr32_pm_pll_t *ppll, enum Pm_pll_source src, uint8_t mul, uint8_t div, bool hifreq) { bool was_enabled = (bool) ppll->pllen; if (mul < 3 || mul > 16) /* mul < 3, is not a typo */ return -1; ppll->pllen = 0; ppll->plltest = 0; ppll->plliotesten = 0; ppll->pllcount = 63; ppll->pllmul = mul - 1; ppll->plldiv = (div & ~(0xf0)); ppll->pllopt = (hifreq == true) ? 0b001 : 0b101; ppll->pllosc = src; if (was_enabled) ppll->pllen = 1; return 0; } int aery::pm_init_gclk(enum Pm_gclk clknum, enum Pm_gclk_source clksrc, uint16_t clkdiv) { volatile avr32_pm_gcctrl_t *gclock = &(AVR32_PM.GCCTRL[clknum]); bool was_enabled = (bool) gclock->cen; if (clkdiv > 256) return -1; /* * Disable general clock before init to prevent glitches on the clock * during the possible reinitialization. */ aery::pm_disable_gclk(clknum); /* Select clock source */ gclock->oscsel = (bool) (clksrc & 1); gclock->pllsel = (bool) (clksrc & 2); if (clkdiv > 0) { gclock->diven = 1; gclock->div = clkdiv - 1; } else { gclock->diven = 0; } if (was_enabled) aery::pm_enable_gclk(clknum); return 0; } void aery::pm_wait_osc_to_stabilize(uint8_t oscnum) { switch (oscnum) { case 0: while (!(AVR32_PM.isr & AVR32_PM_ISR_OSC0RDY_MASK)); break; case 1: while (!(AVR32_PM.isr & AVR32_PM_ISR_OSC1RDY_MASK)); break; case 32: while (!(AVR32_PM.isr & AVR32_PM_ISR_OSC32RDY_MASK)); break; } } void aery::pm_wait_pll_to_lock(volatile avr32_pm_pll_t *ppll) { if (ppll == &AVR32_PM.PLL[0]) { while (!(AVR32_PM.isr & AVR32_PM_ISR_LOCK0_MASK)); } else if (ppll == &AVR32_PM.PLL[1]) { while (!(AVR32_PM.isr & AVR32_PM_ISR_LOCK1_MASK)); } } void aery::pm_enable_gclk(enum Pm_gclk clknum) { AVR32_PM.GCCTRL[clknum].cen = 1; } void aery::pm_disable_gclk(enum Pm_gclk clknum) { AVR32_PM.GCCTRL[clknum].cen = 0; /* We have to wait before cen reads zero. */ while (AVR32_PM.GCCTRL[clknum].cen); } void aery::pm_select_mck(enum Pm_mck_source mcksrc) { AVR32_PM.MCCTRL.mcsel = mcksrc; } uint32_t aery::pm_get_fmck(void) { uint32_t mck = 0; volatile avr32_pm_pll_t *pll0 = &AVR32_PM.PLL[0]; switch (AVR32_PM.MCCTRL.mcsel) { case 0: mck = F_SLOWCLK; break; case 1: mck = F_OSC0; break; case 2: if (pll0->pllosc == 0) mck = F_OSC0; else mck = F_OSC1; if (pll0->plldiv > 0) mck *= (pll0->pllmul + 1) / pll0->plldiv; else mck *= 2 * (pll0->pllmul + 1); if (pll0->pllopt & 2) mck /= 2; break; } return mck; } int aery::pm_setup_clkdomain(uint8_t prescal, uint8_t domain) { uint32_t cksel = AVR32_PM.cksel; if (prescal != 0 && prescal > 8) return -1; if (domain & CLKDOMAIN_CPU) { cksel &= CKSEL_RESET_MASK(CPU); if (prescal != 0) { cksel |= CKSEL_PRESCALER_MASK(prescal, CPU); cksel |= CKSEL_PRESCALER_MASK(prescal, HSB); } } if (domain & CLKDOMAIN_PBA) { cksel &= CKSEL_RESET_MASK(PBA); if (prescal != 0) cksel |= CKSEL_PRESCALER_MASK(prescal, PBA); } if (domain & CLKDOMAIN_PBB) { cksel &= CKSEL_RESET_MASK(PBB); if (prescal != 0) cksel |= CKSEL_PRESCALER_MASK(prescal, PBB); } /* Check that PBA and PBB clocks are equal or smaller than CPU clock */ if (CKSEL_HASDIV(cksel, CPU)) { if (!CKSEL_HASDIV(cksel, PBA) || !CKSEL_HASDIV(cksel, PBB)) return -1; if (CKSEL_GETDIV(cksel, CPU) > CKSEL_GETDIV(cksel, PBA)) return -1; if (CKSEL_GETDIV(cksel, CPU) > CKSEL_GETDIV(cksel, PBB)) return -1; } /* The register must not be re-written until CKRDY goes high. */ while (!(AVR32_PM.isr & AVR32_PM_ISR_CKRDY_MASK)); AVR32_PM.cksel = cksel; return 0; } uint32_t aery::pm_get_fclkdomain(uint8_t domain) { uint32_t f = aery::pm_get_fmck(); switch (domain) { case CLKDOMAIN_CPU: if (CKSEL_HASDIV(AVR32_PM.cksel, CPU)) f = f >> (CKSEL_GETDIV(AVR32_PM.cksel, CPU) + 1); break; case CLKDOMAIN_PBA: if (CKSEL_HASDIV(AVR32_PM.cksel, PBA)) f = f >> (CKSEL_GETDIV(AVR32_PM.cksel, PBA) + 1); break; case CLKDOMAIN_PBB: if (CKSEL_HASDIV(AVR32_PM.cksel, PBB)) f = f >> (CKSEL_GETDIV(AVR32_PM.cksel, PBB) + 1); break; default: f = 0; /* error */ } return f; } void aery::pm_enable_pll(volatile avr32_pm_pll_t *ppll, bool divby2) { if (divby2 == true) ppll->pllopt |= 2; else ppll->pllopt &= ~2; ppll->pllen = 1; } void aery::pm_disable_pll(volatile avr32_pm_pll_t *ppll) { ppll->pllen = 0; }#include #include #include "baseast.hpp" #include "visitor.hpp" #include "symtab.hpp" void Visitor::TypecheckerVisitor::visit(AST::StmtBlockStmt *stmtBlock) { EnterScope(); for (auto &stmt : stmtBlock->stmt_list) { stmt->accept(this); } LeaveScope(); } void Visitor::TypecheckerVisitor::visit(AST::VarDeclStmt *stmt) { for (auto& var : stmt->decls) { if (!_symTab->addSymbol(var.name, var.type)) throw Exception("redeclaring variable " + var.name, ExceptionType::Type); } } void Visitor::TypecheckerVisitor::visit(AST::ArrayDeclStmt *stmt) { for (auto& var : stmt->decls) { var.expr->accept(this); // check if this expression is an int value if (!var.expr->result->isIntValue()) throw Exception("Expected an expression with value int"); if (!_symTab->addSymbol(var.name, Token::Type_array)) throw Exception("redeclaring array " + var.name, ExceptionType::Type); } } void Visitor::TypecheckerVisitor::visit(AST::PrintStmt *stmt) { for (auto& expr : stmt->args) { expr->accept(this); if (!expr->result->isStringValue() && !expr->result->isIntValue()) throw Exception("only string literals and int identifiers allowed in print args", ExceptionType::Type); } } void Visitor::TypecheckerVisitor::visit(AST::IfStmt *stmt) { stmt->cond->accept(this); if (!stmt->cond->result->isBoolValue()) throw Exception("Only bool value allowed as if stmt condition.", ExceptionType::Type); stmt->trueStmt->accept(this); if (stmt->falseStmt) { stmt->falseStmt->accept(this); } } void Visitor::TypecheckerVisitor::visit(AST::WhileStmt *stmt) { stmt->cond->accept(this); if (!stmt->cond->result->isBoolValue()) throw Exception("Only bool value allowed as while stmt condition.", ExceptionType::Type); stmt->body->accept(this); } void Visitor::TypecheckerVisitor::visit(AST::ForStmt *stmt) { EnterScope(); // declare variable before : in the for statement AST::IdExpr* idExpr = dynamic_cast(stmt->ident.get()); if (!idExpr) throw Exception("Malformed for statement; expected an identifier, got something else."); if (!_symTab->addSymbol(idExpr->name, Token::Type_int)) throw Exception("Redeclaring identifier, " + idExpr->name + " in for statement."); stmt->ident->accept(this); if (!stmt->ident->result->isIntValue()) throw Exception("Id expected in for stmt before colon", ExceptionType::Type); stmt->container->accept(this); if (!stmt->container->result->isArrayValue()) throw Exception("array expected in for stmt after colon", ExceptionType::Type); stmt->body->accept(this); LeaveScope(); } void Visitor::TypecheckerVisitor::visit(AST::ReturnStmt *stmt) { Token retExprType = Token::Type_void; auto m = _symTab->getEnclosingFnProto(); Token expectedRetType = m->fnType; if (stmt->returnExpr) { stmt->returnExpr->accept(this); retExprType = stmt->returnExpr->result->getType(); } if (retExprType != expectedRetType) throw Exception("Return type mismatch from fn def", ExceptionType::Type); } void Visitor::TypecheckerVisitor::visit(AST::AbortStmt *stmt) { for (auto& expr : stmt->args) { expr->accept(this); if (!expr->result->isStringValue() && !expr->result->isIntValue()) throw Exception("only string or int allowed as abort stmt arguments", ExceptionType::Type); } } void Visitor::TypecheckerVisitor::visit(AST::ArrayAssignment *stmt) { SymbolInfo* info = nullptr; if (!(info = _symTab->hasSymbol(stmt->name))) throw Exception("Assigning element to an undeclared array."); if (info->_type != SymbolType::Array) throw Exception("Only arrays can be indexed using [] operator"); stmt->idxExpr->accept(this); if (!stmt->idxExpr->result->isIntValue()) throw Exception("only int allowed as array index"); stmt->expr->accept(this); if (!stmt->expr->result->isIntValue()) throw Exception("rhs of array assignment must be int"); } void Visitor::TypecheckerVisitor::visit(AST::VarAssignment *stmt) { SymbolInfo* info = nullptr; if (!(info =_symTab->hasSymbol(stmt->name))) throw Exception("Undeclared variable is being assigned."); stmt->expr->accept(this); const Token rhsType = stmt->expr->result->getType(); const Token lhsType = SymbolToTokenType(info->_type); if (lhsType != rhsType) throw Exception("unmatched types in var assignment."); } void Visitor::TypecheckerVisitor::visit(AST::BaseExpr* expr) { } void Visitor::TypecheckerVisitor::visit(AST::TrueExpr *expr) { expr->result = AST::createValue(Token::Type_bool); } void Visitor::TypecheckerVisitor::visit(AST::FalseExpr *expr) { expr->result = AST::createValue(Token::Type_bool); } void Visitor::TypecheckerVisitor::visit(AST::NumExpr *expr) { expr->result = AST::createValue(Token::Type_int); } void Visitor::TypecheckerVisitor::visit(AST::IdExpr *expr) { SymbolInfo* sym = nullptr; if (!(sym = _symTab->hasSymbol(expr->name))) throw Exception("undefined symbol " + expr->name, ExceptionType::Type); expr->result = AST::createValue(SymbolToTokenType(sym->_type)); } void Visitor::TypecheckerVisitor::visit(AST::LiteralExpr *expr) { std::cout << "Literal expr" << std::endl; } void Visitor::TypecheckerVisitor::visit(AST::StringLiteralExpr *expr) { expr->result = std::make_unique(); } void Visitor::TypecheckerVisitor::visit(AST::TernaryExpr* expr) { expr->condExpr->accept(this); if (!expr->condExpr->result->isBoolValue()) throw Exception("first arg to ternary expr should be bool type"); expr->trueExpr->accept(this); Token trueType = expr->trueExpr->result->getType(); expr->falseExpr->accept(this); Token falseType = expr->falseExpr->result->getType(); if (trueType != falseType) throw Exception("ternary: true and false expression should be same type"); expr->result = AST::createValue(trueType); } void Visitor::TypecheckerVisitor::visit(AST::BinopExpr* expr) { const Token op = expr->op; expr->leftExpr->accept(this); Token lType = expr->leftExpr->result->getType(); expr->rightExpr->accept(this); Token rType = expr->rightExpr->result->getType(); if (lType != rType) { throw Exception("binop operands must be same type."); } else if (isAndOr(op)) { if (lType != Token::Type_bool) throw Exception("only bool operands allowed with & and |"); expr->result = AST::createValue(Token::Type_bool); } else if (isEqOrNeq(op)) { if (lType != Token::Type_int && lType != Token::Type_bool) throw Exception("only int and bool allowed with == and !="); expr->result = AST::createValue(Token::Type_bool); } else if (isCompOp(op)) { if (lType != Token::Type_int) throw Exception("only int opearnds allowed with comparison operator"); expr->result = AST::createValue(Token::Type_bool); } else if (isBinOp(op)) { if (lType != Token::Type_int) throw Exception("only int operands allowed with this operator."); expr->result = AST::createValue(Token::Type_int); } else assert(false && "unhandled operator found"); } void Visitor::TypecheckerVisitor::visit(AST::UnaryExpr *expr) { const Token op = expr->type; expr->expr->accept(this); if (op == Token::Op_bang) { if (!expr->expr->result->isBoolValue()) throw Exception("Bool expected with bang operator"); } else if (op == Token::Op_minus) { if (!expr->expr->result->isIntValue()) throw Exception("Only int allowed with minus unary op"); } else assert("Wrong operator found in unary Expr."); expr->result = AST::createValue(expr->expr->result->getType()); } void Visitor::TypecheckerVisitor::visit(AST::SizeofExpr *expr) { expr->idExpr->accept(this); if (!expr->idExpr->result->isArrayValue()) throw Exception("Sizeof argument should be an array value"); expr->result = AST::createValue(Token::Type_int); } void Visitor::TypecheckerVisitor::visit(AST::InputExpr *expr) { expr->result = AST::createValue(Token::Type_int); } void Visitor::TypecheckerVisitor::visit(AST::ArrayExpr *expr) { expr->expr->accept(this); if (!expr->expr->result->isIntValue()) throw Exception("Only int allowed as array expression argument"); expr->result = AST::createValue(Token::Type_int); } void Visitor::TypecheckerVisitor::visit(AST::FnCallExpr *expr) { if (!_symTab->hasSymbol(expr->name)) throw Exception("calling undefined function : " + expr->name, ExceptionType::Type); AST::FunctionPrototype* fnProto = _symTab->getFnProto(expr->name); if (expr->fnArgs.size() != fnProto->fnParams.size()) throw Exception("Function " + fnProto->fnName + " expects different number of arguments than given."); int i = 0; for (auto& arg: expr->fnArgs) { arg->accept(this); const Token argType = arg->result->getType(); const Token paramType = fnProto->fnParams[i].type; if (argType != paramType) throw Exception("Fn call arg types mismatch."); i++; } expr->result = AST::createValue(fnProto->fnType); } void Visitor::TypecheckerVisitor::visit(AST::Program* program) { // add functions to symbol table in first pass for (auto &fnDef : program->fnDefinitions) { if (!_symTab->addFnSymbol(fnDef->proto->fnName, fnDef->proto.get())) throw Exception("redefining function :" + fnDef->proto->fnName, ExceptionType::Type); } // exactly one main should be there. if (!_symTab->hasSymbolInCurrentScope("main")) throw Exception("one main function required", ExceptionType::Type); // iterate over individual funcs for (auto& fnDef : program->fnDefinitions) { // following hack is because return statement wants to know the type of the function in which it's enclosed in // And we cannot make use of top-level symbol table (which contains all the functions) because we don't know the name of the function // in which the return statement is enclosed. // functions have a completely new scope with only internal function name in that scope EnterScope(); _symTab->addFnSymbol("lilfn_ " + fnDef->proto->fnName, fnDef->proto.get()); EnterScope(); for(auto& param : fnDef->proto->fnParams) { if(!_symTab->addSymbol(param.name, param.type)) throw Exception("redeclaring variable : " + param.name, ExceptionType::Type); } fnDef->body->accept(this); // check if the last statement of non-void function body is return/abort or not auto& lastStmt = fnDef->body->stmt_list.back(); // condition = last statement of "non-void" functions should be abort or return bool lastStmtConditionMet = true; if (fnDef->proto->fnType != Token::Type_void) { lastStmtConditionMet = false; if (dynamic_cast(lastStmt.get()) || dynamic_cast(lastStmt.get())) lastStmtConditionMet = true; } if (!lastStmtConditionMet) throw Exception("Last statement of non-void function should be return or abort."); LeaveScope(); LeaveScope(); } }#include "CloudMessaging.h" String FCM::buildMessage(const Message &message, bool validateOnly) { String str = "{"; str += (validateOnly ? "\"validate_only\":true," : "\"validate_only\":false,"); str += message.toString("message"); str += "}"; str.replace(",}", "}"); return str; } /** * Copyright (C) 2010 (). 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. * * 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 COPYRIGHT HOLDERS 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. * * The views and conclusions contained in the software and documentation are * those of the authors and should not be interpreted as representing official * policies, either expressed or implied, of the copyright holders. */ #include #include #include "DXUT.h" #include "DXUTgui.h" #include "DXUTmisc.h" #include "DXUTSettingsDlg.h" #include "SDKmisc.h" #include "SMAA.h" #include "Timer.h" using namespace std; CDXUTDialogResourceManager dialogResourceManager; CDXUTDialog hud; ID3DXFont *font = NULL; Timer *timer = NULL; SMAA *smaa = NULL; IDirect3DSurface9 *backbufferSurface = NULL; IDirect3DTexture9 *finalbufferColorTex = NULL; IDirect3DSurface9 *finalbufferColorSurface = NULL; IDirect3DTexture9 *finalbufferDepthTex = NULL; IDirect3DSurface9 *finalbufferDepthSurface = NULL; IDirect3DTexture9 *colorTex = NULL; IDirect3DTexture9 *depthTex = NULL; ID3DXSprite *sprite = NULL; CDXUTTextHelper *txtHelper = NULL; bool showHud = true; #define IDC_TOGGLE_FULLSCREEN 1 #define IDC_PRESET 2 #define IDC_DETECTION_MODE 3 #define IDC_ANTIALIASING 4 #define IDC_PROFILE 5 bool CALLBACK isDeviceAcceptable(D3DCAPS9 *caps, D3DFORMAT adapterFormat, D3DFORMAT backBufferFormat, bool windowed, void *userContext) { if (caps->PixelShaderVersion < D3DPS_VERSION(3, 0) || caps->VertexShaderVersion < D3DVS_VERSION(3, 0)) return false; else return true; } HRESULT CALLBACK onCreateDevice(IDirect3DDevice9 *device, const D3DSURFACE_DESC *desc, void *userContext) { HRESULT hr; V_RETURN(dialogResourceManager.OnD3D9CreateDevice(device)); V_RETURN(D3DXCreateFont(device, 15, 0, FW_BOLD, 1, FALSE, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE, L"Arial", &font)); return S_OK; } void CALLBACK onDestroyDevice(void* pUserContext) { dialogResourceManager.OnD3D9DestroyDevice(); SAFE_RELEASE(font); } HRESULT CALLBACK onResetDevice(IDirect3DDevice9 *device, const D3DSURFACE_DESC *desc, void *userContext) { HRESULT hr; V_RETURN(dialogResourceManager.OnD3D9ResetDevice()); if (font) V_RETURN(font->OnResetDevice()); timer = new Timer(device); timer->setEnabled(hud.GetCheckBox(IDC_PROFILE)->GetChecked()); timer->setRepetitionsCount(100); SMAA::Preset preset = SMAA::Preset(int(hud.GetComboBox(IDC_PRESET)->GetSelectedData())); smaa = new SMAA(device, desc->Width, desc->Height, preset); V(device->GetBackBuffer(0, 0, D3DBACKBUFFER_TYPE_MONO, &backbufferSurface)); V(device->CreateTexture(desc->Width, desc->Height, 1, D3DUSAGE_RENDERTARGET, D3DFMT_A8R8G8B8, D3DPOOL_DEFAULT, &finalbufferColorTex, NULL)); V(finalbufferColorTex->GetSurfaceLevel(0, &finalbufferColorSurface)); V(device->CreateTexture(desc->Width, desc->Height, 1, D3DUSAGE_RENDERTARGET, D3DFMT_R32F, D3DPOOL_DEFAULT, &finalbufferDepthTex, NULL)); V(finalbufferDepthTex->GetSurfaceLevel(0, &finalbufferDepthSurface)); D3DXIMAGE_INFO info; V(D3DXGetImageInfoFromResource(NULL, L"Unigine02.png", &info)); V(D3DXCreateTextureFromResourceEx(device, NULL, L"Unigine02.png", info.Width, info.Height, 1, 0, D3DFMT_A8R8G8B8, D3DPOOL_DEFAULT, D3DX_FILTER_NONE, D3DX_FILTER_NONE, 0, &info, NULL, &colorTex)); V(D3DXGetImageInfoFromResource(NULL, L"Unigine02.dds", &info)); V(D3DXCreateTextureFromResourceEx(device, NULL, L"Unigine02.dds", info.Width, info.Height, 1, 0, D3DFMT_R32F, D3DPOOL_DEFAULT, D3DX_FILTER_NONE, D3DX_FILTER_NONE, 0, &info, NULL, &depthTex)); V_RETURN(D3DXCreateSprite(device, &sprite)); txtHelper = new CDXUTTextHelper(font, sprite, NULL, NULL, 15); hud.SetLocation(desc->Width - 170, 0); hud.SetSize(170, 170); return S_OK; } void CALLBACK onLostDevice(void *userContext) { dialogResourceManager.OnD3D9LostDevice(); if (font) font->OnLostDevice(); SAFE_DELETE(timer); SAFE_DELETE(smaa); SAFE_RELEASE(backbufferSurface); SAFE_RELEASE(finalbufferColorTex); SAFE_RELEASE(finalbufferColorSurface); SAFE_RELEASE(finalbufferDepthTex); SAFE_RELEASE(finalbufferDepthSurface); SAFE_RELEASE(colorTex); SAFE_RELEASE(depthTex); SAFE_RELEASE(sprite); SAFE_DELETE(txtHelper); } void drawHud(float elapsedTime) { HRESULT hr; D3DPERF_BeginEvent(D3DCOLOR_XRGB(0, 0, 0), L"HUD"); if (showHud) { V(hud.OnRender(elapsedTime)); txtHelper->Begin(); txtHelper->SetInsertionPos(2, 0); txtHelper->SetForegroundColor(D3DXCOLOR(1.0f, 1.0f, 1.0f, 1.0f)); txtHelper->DrawTextLine(DXUTGetFrameStats(DXUTIsVsyncEnabled())); txtHelper->DrawTextLine(DXUTGetDeviceStats()); txtHelper->SetForegroundColor(D3DXCOLOR(1.0f, 0.5f, 0.0f, 1.0f)); if (timer->isEnabled()) { wstringstream s; s << setprecision(2) << std::fixed; s << *timer; txtHelper->DrawTextLine(s.str().c_str()); } txtHelper->End(); } D3DPERF_EndEvent(); } void mainPass(IDirect3DDevice9 *device) { HRESULT hr; // A dummy copy over here. IDirect3DSurface9 *colorSurface = NULL; V(colorTex->GetSurfaceLevel(0, &colorSurface)); D3DSURFACE_DESC desc; colorSurface->GetDesc(&desc); const D3DSURFACE_DESC *backbufferDesc = DXUTGetD3D9BackBufferSurfaceDesc(); RECT rect = {0, 0, min(desc.Width, backbufferDesc->Width), min(desc.Height, backbufferDesc->Height)}; V(device->StretchRect(colorSurface, &rect, finalbufferColorSurface, &rect, D3DTEXF_POINT)); SAFE_RELEASE(colorSurface); // And another one over here. IDirect3DSurface9 *depthSurface = NULL; V(depthTex->GetSurfaceLevel(0, &depthSurface)); V(device->StretchRect(depthSurface, &rect, finalbufferDepthSurface, &rect, D3DTEXF_POINT)); SAFE_RELEASE(depthSurface); } void copy(IDirect3DDevice9 *device) { HRESULT hr; // A dummy copy over here. IDirect3DSurface9 *colorSurface = NULL; V(colorTex->GetSurfaceLevel(0, &colorSurface)); D3DSURFACE_DESC desc; colorSurface->GetDesc(&desc); const D3DSURFACE_DESC *backbufferDesc = DXUTGetD3D9BackBufferSurfaceDesc(); RECT rect = {0, 0, min(desc.Width, backbufferDesc->Width), min(desc.Height, backbufferDesc->Height)}; V(device->StretchRect(colorSurface, &rect, backbufferSurface, &rect, D3DTEXF_POINT)); SAFE_RELEASE(colorSurface); } void CALLBACK onFrameRender(IDirect3DDevice9 *device, double time, float elapsedTime, void *userContext) { HRESULT hr; // IMPORTANT: stencil must be cleared to zero before executing 'smaa->go' V(device->Clear(0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER | D3DCLEAR_STENCIL, D3DCOLOR_ARGB(0, 0, 0, 0), 1.0f, 0)); V(device->BeginScene()); // This emulates main pass. mainPass(device); // Run SMAA if (hud.GetCheckBox(IDC_ANTIALIASING)->GetChecked()) { SMAA::Input input = SMAA::Input(int(hud.GetComboBox(IDC_DETECTION_MODE)->GetSelectedData())); int n = hud.GetCheckBox(IDC_PROFILE)->GetChecked()? timer->getRepetitionsCount() : 1; timer->start(); for (int i = 0; i < n; i++) { // This loop is just for profiling. switch (input) { case SMAA::INPUT_LUMA: case SMAA::INPUT_COLOR: smaa->go(finalbufferColorTex, finalbufferColorTex, backbufferSurface, input); break; case SMAA::INPUT_DEPTH: smaa->go(finalbufferDepthTex, finalbufferColorTex, backbufferSurface, input); break; } } timer->clock(L"SMAA"); } else { copy(device); } // Draw the HUD drawHud(elapsedTime); V(device->EndScene()); } LRESULT CALLBACK msgProc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam, bool *finished, void *userContext) { *finished = dialogResourceManager.MsgProc(hwnd, msg, wparam, lparam); if (*finished) return 0; *finished = hud.MsgProc(hwnd, msg, wparam, lparam); if (*finished) return 0; return 0; } void CALLBACK onKeyboard(UINT nchar, bool keyDown, bool altDown, void *userContext) { if (keyDown) switch (nchar) { case VK_TAB: { if (keyDown) showHud = !showHud; break; } case '1': case '2': case '3': case '4': case '5': { hud.GetComboBox(IDC_PRESET)->SetSelectedByIndex(nchar - '1'); onLostDevice(NULL); onResetDevice(DXUTGetD3D9Device(), DXUTGetD3D9BackBufferSurfaceDesc(), NULL); break; } case 'X': hud.GetCheckBox(IDC_PROFILE)->SetChecked(!hud.GetCheckBox(IDC_PROFILE)->GetChecked()); timer->setEnabled(hud.GetCheckBox(IDC_PROFILE)->GetChecked()); break; case 'Z': hud.GetCheckBox(IDC_ANTIALIASING)->SetChecked(!hud.GetCheckBox(IDC_ANTIALIASING)->GetChecked()); break; } } void setAdapter(DXUTDeviceSettings *settings) { HRESULT hr; // Look for 'NVIDIA PerfHUD' adapter. If it is present, override default settings. IDirect3D9 *d3d = DXUTGetD3D9Object(); for (UINT i = 0; i < d3d->GetAdapterCount(); i++) { D3DADAPTER_IDENTIFIER9 id; V(d3d->GetAdapterIdentifier(i, 0, &id)); if (strstr(id.Description, "PerfHUD") != 0) { settings->d3d9.AdapterOrdinal = i; settings->d3d9.DeviceType = D3DDEVTYPE_REF; break; } } } bool CALLBACK modifyDeviceSettings(DXUTDeviceSettings *settings, void *userContext) { setAdapter(settings); if (settings->ver == DXUT_D3D9_DEVICE) { // Debugging vertex shaders requires either REF or software vertex processing // and debugging pixel shaders requires REF. #ifdef DEBUG_VS if (settings->d3d9.DeviceType != D3DDEVTYPE_REF) { settings->d3d9.BehaviorFlags &= ~D3DCREATE_HARDWARE_VERTEXPROCESSING; settings->d3d9.BehaviorFlags &= ~D3DCREATE_PUREDEVICE; settings->d3d9.BehaviorFlags |= D3DCREATE_SOFTWARE_VERTEXPROCESSING; } #endif #ifdef DEBUG_PS settings->d3d9.DeviceType = D3DDEVTYPE_REF; #endif } settings->d3d9.pp.AutoDepthStencilFormat = D3DFMT_D24S8; return true; } void CALLBACK onGUIEvent(UINT event, int controlId, CDXUTControl* control, void *userContext) { switch(controlId) { case IDC_TOGGLE_FULLSCREEN: DXUTToggleFullScreen(); break; case IDC_PRESET: if (event == EVENT_COMBOBOX_SELECTION_CHANGED) { SMAA::Preset selected; selected = SMAA::Preset(int(hud.GetComboBox(IDC_PRESET)->GetSelectedData())); onLostDevice(NULL); onResetDevice(DXUTGetD3D9Device(), DXUTGetD3D9BackBufferSurfaceDesc(), NULL); } break; case IDC_ANTIALIASING: if (event == EVENT_CHECKBOX_CHANGED) timer->reset(); break; case IDC_PROFILE: if (event == EVENT_CHECKBOX_CHANGED) { timer->reset(); timer->setEnabled(hud.GetCheckBox(IDC_PROFILE)->GetChecked()); } break; } } void initApp() { hud.Init(&dialogResourceManager); hud.SetCallback(onGUIEvent); int iY = 10; hud.AddButton(IDC_TOGGLE_FULLSCREEN, L"Toggle full screen", 35, iY, 125, 22); iY += 24; hud.AddComboBox(IDC_PRESET, 35, iY += 24, 125, 22, 0, false); hud.GetComboBox(IDC_PRESET)->AddItem(L"SMAA Low", (LPVOID) 0); hud.GetComboBox(IDC_PRESET)->AddItem(L"SMAA Medium", (LPVOID) 1); hud.GetComboBox(IDC_PRESET)->AddItem(L"SMAA High", (LPVOID) 2); hud.GetComboBox(IDC_PRESET)->AddItem(L"SMAA Ultra", (LPVOID) 3); hud.GetComboBox(IDC_PRESET)->AddItem(L"SMAA Custom", (LPVOID) 4); hud.GetComboBox(IDC_PRESET)->SetSelectedByData((LPVOID) 2); hud.AddComboBox(IDC_DETECTION_MODE, 35, iY += 24, 125, 22, 0, false); hud.GetComboBox(IDC_DETECTION_MODE)->AddItem(L"Luma edge det.", (LPVOID) 0); hud.GetComboBox(IDC_DETECTION_MODE)->AddItem(L"Color edge det.", (LPVOID) 1); hud.GetComboBox(IDC_DETECTION_MODE)->AddItem(L"Depth edge det.", (LPVOID) 2); hud.AddCheckBox(IDC_ANTIALIASING, L"SMAA Anti-Aliasing", 35, iY += 24, 125, 22, true); hud.AddCheckBox(IDC_PROFILE, L"Profile", 35, iY += 24, 125, 22, false); } int WINAPI wWinMain(HINSTANCE, HINSTANCE, LPWSTR, int) { // Enable run-time memory check for debug builds. #if defined(DEBUG) | defined(_DEBUG) _CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF ); #endif DXUTSetCallbackD3D9DeviceAcceptable(isDeviceAcceptable); DXUTSetCallbackD3D9DeviceCreated(onCreateDevice); DXUTSetCallbackD3D9DeviceReset(onResetDevice); DXUTSetCallbackD3D9DeviceLost(onLostDevice); DXUTSetCallbackD3D9DeviceDestroyed(onDestroyDevice); DXUTSetCallbackD3D9FrameRender(onFrameRender); DXUTSetCallbackMsgProc(msgProc); DXUTSetCallbackKeyboard(onKeyboard); DXUTSetCallbackDeviceChanging(modifyDeviceSettings); initApp(); if (FAILED(DXUTInit(true, true, L"-forcevsync:0"))) return -1; DXUTSetCursorSettings( true, true ); if (FAILED(DXUTCreateWindow(L"SMAA: Subpixel Morphological Antialiasing"))) return -1; if (FAILED(DXUTCreateDevice(true, 1280, 720))) return -1; DXUTMainLoop(); return DXUTGetExitCode(); }#ifndef ONLINEDISPATCHER_HPP_ #define ONLINEDISPATCHER_HPP_ #include #include #include #include #include #include #include #include #include #include #include #include "Predictor.hpp" using namespace std; namespace optimization_core { // ============================================================================= // = OnlineDispatcher class = // ============================================================================= /* Class to wrap dispatching problems in a online framework. * This is a fundamental class to simulate the 'online' behaviour of a real * job dispatcher. OnlineDispatcher has knowledge of all the jobs in the job * instance and simulate their arrival following their arrival times. */ class OnlineDispatcher { private: // Optmizer used Optimizer* _opt; Predictor* _predictor; vector& _jobs; vector& _queues; vector& _nodes; int _ndims; /* Internal random generator */ unsigned int seed_; /* Assumption: all nodes with higher id are 3.1GHz nodes, * lower ids imply 2.1GHz nodes */ int _nodeType_threshold; /* Threshold used for a performance metric * Minimum duration (s) of jobs considered when computing BSLD. */ double _bsld_threshold = 60; /* Jobs already added to the problem */ vector _added_jobs; /* Dummy jobs added to simulate hot startup */ vector _fake_jobs; /* Power Cap constraint */ long long _power_cap; /* Varying power cap constraint (read from file) * map */ map _power_caps; /* Power cap may be not enforced * But we may still want to compare the dispatcher * behaviour w.r.t. a "target" power. * Target sys power might be different from the power cap. * * For example if we use let assume we want to have a EASY-BF * scheduler that manages the power trough RAPL-like action. * We cannot directly use BackFillingScheduler because it * would directly enforce the power cap passed as parameter (thus * nullifying the RAPL-action. Instead, we can pass a fake, * larger than desired power cap to BackFillingScheduler and * then use RAPL-like mechanism to respect the target * (desired) power budget */ long long _target_sys_power; long long _target_node_power; /* Parameters for the dynamic RAPL-based power capping */ int _dynPowerShare_firstMeasure; // power allocated to each node map _nodes_alloc_power; map _nodes_reclaim; /* Not defined in the paper: parameter to account the * measurement jitter. In this implementation * an arbitrary value is set */ long long _target_node_wastedPower = 5; /* Not explained in the paper */ double _reclaim_factor = 0.9; // min and max allocable power depend on the HW long long _node_min_alloc_power = 1; long long _node_max_alloc_power = 400; /* Power counters */ /* The real time power consumption should be measured directly * Currently, we rely on the power prediction of each * running job */ int _current_power; map _historical_powers; /* Alternative set of power counters: these * should better simulate a real-time measuring * framework */ int _system_power; // should coincide with _current_power map _nodes_power; // power consumed in each node map _system_power_profile; map > _nodes_power_profile; /* Every _step_ seconds we simulate a power measurements. * Power measurements are treated as special events * within the simulator; they don't trigger computation * of new schedules but might trigger the RAPL-action ( * if it is necessary and dynamic power management is * selected */ long long _power_measure_step_fixed = 5; /* For the dynamic frequency scaling based on RAPL we distinguish * 3 methods for deciding the impact of power consumption cap * on the interested jobs durations. * -1) No dynamic RAPL power mechanism * 0) No impact: if we bound the power consumption of a node in * which a job is running, its duration doesn't change * 1) Max impact: if we reduce the power consumption of x% * the duration increase will be of x% * 3) Intermediate impact: if we reduce the power consumption of x% * the duration increase will be of perfModel_factor_ * x% */ int _dyn_RAPL_mode; /* Input parameter that specifies the performance reduction w.r.t. * the power reduction (decided by user) */ double perfModel_factor_; /* We can simulate the dispatcher behaviour with different * startup settings, namely we can specify the utilization * of the system at start time. The utilization is simulated through * fake jobs already in the system. To simplify these jobs only * require CPU resources. Moreover, these jobs power consumption is * artificially low (much smaller than the power cap) * 0 means a system totally empty. * 100 means a system completely full. * Intermediate values define intermediate situations */ int startup_hotness_; /* Input parameter that decides the underlying optimizer * used to compute a schedule */ int opt_type_; /* Timers information */ vector _freq_timers; /* Mode to reassign execution frequencies: * - 0: greedy algorithm * - 1: CP model */ int _freqAssign_mode; /* Max frequencies allowed - cached for later use. * Depend on the real frequencies allowed by Eurora nodes, * 2.1 GHz for half of the nodes, 3.4GHz for the remaining ones */ vector _max_freqs = {2100, 3400}; // data structure to store information about a job typedef struct _job_info { long long job_idx; long long dur; // Job (real) duration long long original_dur; // Job duration at eqt long long ewt; // Expected waiting time long long qet; double power_pred; // Predicted Consumed Power - whole job double power_pred_perNode; // predicted power, per node double cur_power; // Current consumed power - may vary double cur_power_perNode; // requirements for each job unit vector< vector > reqs; // sum of requirements for each dimensions vector tot_reqs; // nodes mapping vector node_mapping; long long start_time; // when job execution begins long long end_time; // estimated end time (may change) long long node_type; // type of used nodes (we assume no mixed nodes) int application_type; // 0: average, 1: cpu-intensive, 2: mem-intensive int frequency; long long energy; /* execution history is used to keep track of the different power * consumptions that a job can have due to changing frequency. * It's a list of (power, duration) which can be summed to * return the total energy consumed by a job. If the list is empty * then no frequency change happened, therefore the total energy is * simply power * duration. * The final energy of a job can be computed when noticing its * end-time event. */ vector< pair > exec_hist; // track the execution hist } _job_info; /* Support function to help sorting job info: job with larger predicted * powers are preferred */ struct job_info_byPower_sorter { inline bool operator() (const _job_info& ji1, const _job_info& ji2) { return (ji1.power_pred > ji2.power_pred); } }; /* Map with the info of all jobs in the problem - useful for compute metrics */ map _jobs_info; /* Set of running jobs */ map _running_jobs; /* Set of running jobs grouped by node */ map > _node_running_jobs; /* Set of waiting jobs */ map _waiting_jobs; /* Set of completed jobs */ map _ended_jobs; // custom type to store start/end time and mapping of a job typedef struct _job_schedule { long long start; long long end; vector mapping; } _job_schedule; // map with the final schedule map _final_schedule; long long _ref_time; long long prev_notMeasure_time_; /* In our simulator we can know _a priori_ how many times * the power cap will vary: this is a useful information * to promptly terminate our dispatcher when all the * meaningful events happened */ int _power_cap_variations_left; int _power_measurements_left; // custom enumeration to divise jobs in arriving/startin/ending /* - events are used also to track the varying power cap, * these events have a fake job idx (negative) and are treated like normal * events, i.e. generating a new schedule if needed * - events are used also to simulate a power measuring framework: * at each event the system and node power are measured * (no new scheduling) */ typedef enum _job_evt_type { job_arriving, job_starting, job_ending, power_cap_variation, power_measure } _job_evt_type; // custom type to store the jobs that arrive/start/end at certain event /* Events representing power cap variations have a fake * job_idx, a negative value (usual idxs must have only positive finite * values); the absolute value of this negative number is the power cap * at such event */ typedef struct _job_evt { long long job_ext_idx; _job_evt_type type; } _job_evt; // map with the ending jobs (this is needed to find quickly the next // time point to process). Iterators of the map container stay valid // even if a new element is inserted map > _events; // cached resource capacities // a vector of size ndims for each resource vector< vector > _res_caps; // cumulative resource capacities vector _cumul_res_caps; vector _max_cumul_res_caps; /* Values to keep track machine utilization */ map> _sys_util; vector _cumul_res_usgs; vector< vector > _res_usgs; // cached minumum resource requirements (jobs in q) vector _min_reqs; // computation time stats for each scheduling event vector _nscheduled_jobs; // number of scheduled jobs vector _treq_sched; // time required by the scheduling /* RAPL implementation with the power-duration model factor * dependent on the application type. We compute the perfModel * factor for each job the first time the function is called. * Such values are stored for future calls (the perfModel * factor of a job is constant) */ map jobs_perfModel_factors_; double compute_job_perfModel_factor(long long job_idx, int application_type){ auto it = jobs_perfModel_factors_.find(job_idx); // the job has already a perfModel factor if(it != jobs_perfModel_factors_.end()){ return it->second; } // we compute the new perfModel factor else{ /* Assumptions: the factor can range between 0 and 1; * the factor is a random value extracted from a normal * distribution. Application type has its own distribution * mean (std are the same for all application types) */ // create internal random generator // seeded with the instance name random_device rdev; unsigned int seed = seed_ + job_idx; seed_seq seeder{seed}; //mt19937 e2(seeder); mt19937 e2; // normal distributions for each application type normal_distribution dist_CPUbound(0.8, 0.2); normal_distribution dist_QE(0.7, 0.1); normal_distribution dist_MEMbound(0.3, 0.2); double perfModel_factor; switch(application_type){ case 0: perfModel_factor = dist_QE(e2); break; case 1: perfModel_factor = dist_CPUbound(e2); break; case 2: perfModel_factor = dist_MEMbound(e2); break; default: perfModel_factor = dist_QE(e2); break; } if(perfModel_factor > 1) perfModel_factor = 1; if(perfModel_factor < 0) perfModel_factor = 0; jobs_perfModel_factors_[job_idx] = perfModel_factor; return perfModel_factor; } } /* return the job consumed energy * !!! This function has not been properly tested !!! */ long long get_job_final_energy(int job_idx, long long cur_time){ long long energy = 0; // if the job has not started yet if(_jobs_info.find(job_idx) ==_jobs_info.end()) return 0; /* if no frequency re-assignment happened, great! */ if(_jobs_info[job_idx].exec_hist.size() == 0){ energy = _jobs_info[job_idx].cur_power * _jobs_info[job_idx].dur; } /* If the job execution saw changes in frequency the * computation needs to consider the different phases */ else{ /* suppose a job had N phases: the first N-1 are stored * in the execution history list; the N phase is the * current one (no change in freq. since it started */ // add the energy contributions of the N-1 phases long long energy_except_last = 0; long long dur_except_last = 0; for(auto eh : _jobs_info[job_idx].exec_hist){ dur_except_last += eh.second; energy_except_last += eh.first * eh.second; } energy += energy_except_last; // add the contribution of the last phase long long last_phase_dur = cur_time - _jobs_info[job_idx].start_time - dur_except_last; energy += last_phase_dur * _jobs_info[job_idx].cur_power; } return energy; } // add the jobs that need to be scheduled void addJob(int job_idx) { // Obtain a reference to the job Job& job = _jobs[job_idx]; // auxiliary structure with job-related info _job_info j_info; j_info.job_idx = job_idx; // Obtain the job duration // this is the duration used to compute schedules long long dur = job.getEstimatedDuration(); // Obtain the job predicted power consumption // This power is used to respect the power cap double power_pred; power_pred = ceil(_predictor->get_power_prediction(job)); /* Some power predictions could be wrong. Extreme small values * (smaller than 1) are extremely suspicious (and can cause later problems): * just in case we set them to 1. In this way we are also being robust * and conservative by overestimating the power consumptions */ if(power_pred < 1) power_pred = 1; double power_pred_perNode = ceil(power_pred / _jobs[job_idx].getNumberOfNodes()); if(power_pred_perNode <= 1){ power_pred_perNode = 1; power_pred = _jobs[job_idx].getNumberOfNodes(); } /* Later experiments shown that there are inconsistencies * (my fault) when dealing with power predictions - sometimes treated as * double and sometimes as long. This cause problems, namely * pred_power doesn't correspond to pred_powerPerNode times * number of nodes. This is bad for many reasons. So here we forcefully * impose this relationship */ long long temp_power_pred = power_pred; long long temp_power_pred_perNode = power_pred_perNode; if(temp_power_pred_perNode * _jobs[job_idx].getNumberOfNodes() != temp_power_pred) power_pred = power_pred_perNode * _jobs[job_idx].getNumberOfNodes(); /* Some job power predictions are very large values. * They are outliers - we know they exist and are described in our paper * In order to simplify the implementation here we force * a maximum power consumption for each job: if the power * prediction is larger we bound the prediction. * The maximum power prediction is the * maximum power allowed on a node */ if(power_pred_perNode > _node_max_alloc_power){ power_pred_perNode = _node_max_alloc_power; power_pred = power_pred_perNode * _jobs[job_idx].getNumberOfNodes(); } j_info.power_pred = power_pred; j_info.power_pred_perNode = power_pred_perNode; /* We can force our prediction to be treated as perfect - thus * the initial power consumption (cur_power) would be equal to * the predicted power. * This is an obviously wrong assumption but however it enables * a fair comparison between different policies (and anyway the * power consumption prediction model needs to be changed on * different HPC systems) */ // initially, the job power is the predicted one double cur_power = power_pred; j_info.cur_power = power_pred; j_info.cur_power_perNode = power_pred_perNode; /* OR we can take into account the possible mis-predictions: the * initial power is therefore different from the predicted one */ /* In this example we force that 10% of jobs in an instance are * under-estimated by 40% */ /* double underestimate_factor = 1.4; int understimate_probability = 10; bool underprediction; random_device rdev; unsigned int seed = seed_ + job_idx; seed_seq seeder{seed}; mt19937 rng(seeder); uniform_int_distribution int_distr(1,100); int rnd = int_distr(rng); rnd <= understimate_probability ? underprediction = true : underprediction = false; if(underprediction){ cur_power *= underestimate_factor; j_info.cur_power *= underestimate_factor; j_info.cur_power_perNode *= underestimate_factor; } */ int application_type = _jobs[job_idx].getApplicationType(); j_info.application_type = application_type; // sanitize strange input: if real duration longer than expected (this shouldn't happen // but it does), reduce real duration -> simplify testing, we should change // this restriction in the real dispatcher, allow some flexibility (job.getEstimatedDuration() < job.getRealDuration() ? j_info.dur = job.getEstimatedDuration() : j_info.dur = job.getRealDuration()); j_info.original_dur = j_info.dur; // Obtain the job waiting time long long ewt = 1800; // default value for reservations for (JobQueue& q : _queues){ if (q.getId().compare(job.getQueue()) == 0) { ewt = q.getMaxMinutesToWait(); break; } } j_info.ewt = ewt; // the job frequency is decided only after mapping j_info.frequency = -1; // The time already spent in queue long long qet = job.getEnterQueueTime(); j_info.qet = qet; j_info.start_time = -1; j_info.end_time = -1; // Add job units one by one int nunits = job.getNumberOfNodes(); vector > unit_reqs; j_info.reqs.resize(nunits); j_info.tot_reqs.resize(_ndims,0); for (int u = 0; u < nunits; ++u) { j_info.reqs[u].resize(_ndims); // get the requirement of each job unit // (and store them for the internal job_info map) long long rcores = job.getNumberOfCores() / nunits; j_info.reqs[u][0] = rcores; j_info.tot_reqs[0] += rcores; long long rgpus = job.getNumberOfGPU() / nunits; j_info.reqs[u][1] = rgpus; j_info.tot_reqs[1] += rgpus; long long rmics = job.getNumberOfMIC() / nunits; j_info.reqs[u][2] = rmics; j_info.tot_reqs[2] += rmics; long long rmem = job.getMemory() / nunits; j_info.reqs[u][3] = rmem; j_info.tot_reqs[3] += rmem; // store the unit requirements unit_reqs.push_back({rcores, rgpus, rmics, rmem}); } j_info.energy = -1; // Add the job to the optimizer _opt->addJob(job_idx, dur, power_pred, cur_power, qet, ewt, application_type, unit_reqs); _opt->setFrequency(job_idx,-1); // store the information about the job in the internal map _jobs_info[job_idx] = {j_info}; /* Add job to those in the waiting queue */ auto itr = _waiting_jobs.find(job_idx); // only if the job have not been seen before if(itr == _waiting_jobs.end()) _waiting_jobs[job_idx] = _jobs_info[job_idx]; _added_jobs.push_back(job_idx); // compute job powerPerfModel factor (to be used // also by some optimiezers - those using RAPL) compute_job_perfModel_factor(job_idx, application_type); } /* Update the cached resource capacities * -1: starting job * 1: ending job */ void update_caps (int job_idx, int job_type, vector mapping){ int nunits; if(job_idx <= _jobs.size()) nunits = _jobs[job_idx].getNumberOfNodes(); else nunits = _jobs_info[job_idx].node_mapping.size(); for(int u = 0; u < nunits; u++){ int res_idx = mapping[u]; for(int d = 0; d < _ndims; d++){ // update single res capacities _res_caps[res_idx][d] = _res_caps[res_idx][d] + job_type * _jobs_info[job_idx].reqs[u][d]; // update cumulative capacities _cumul_res_caps[d] = _cumul_res_caps[d] + job_type * _jobs_info[job_idx].reqs[u][d]; // update single res usages _res_usgs[res_idx][d] = _res_usgs[res_idx][d] - job_type * _jobs_info[job_idx].reqs[u][d]; // update cumulative usages _cumul_res_usgs[d] = _cumul_res_usgs[d] - job_type * _jobs_info[job_idx].reqs[u][d]; } } } /* Update the cached system power * 1: starting job * -1: ending job */ void update_power (int job_idx, int job_type){ _current_power = _current_power + job_type * _jobs_info[job_idx].cur_power; if( _current_power < 0) cout << "Something wrong... ---> negative power" << endl; } /* Check if newly arrived job could fit in the system * - given the current cached resource state * TODO: very inefficient (check every dim, res, etc..) * possible much smarter implementation */ bool check_res_avail(int job_idx){ int nunits = _jobs[job_idx].getNumberOfNodes(); // 1) check cumulative resource capacities for(int d = 0; d < _ndims; d++) if(_jobs_info[job_idx].tot_reqs[d] > _cumul_res_caps[d]) return false; // 2) check if each job unit can fit for(int u = 0; u < nunits; u++){ // check every dimension for(int d = 0; d < _ndims; d++){ bool fit = false; // consider every resource for(int r = 0; r < _nodes.size(); r++) // if the unit could fit in at least one resource, OK if(_jobs_info[job_idx].reqs[u][d] <= _res_caps[r][d]){ fit = true; break; } if(!fit) return false; } // dims loop } // units loop return true; } /* Change dynamically (at run-time) the frequency * of a running job. The change must affect the job remained * duration (in all nodes, the duration is the maximum among all * possible ones - for jobs which run on both slowed and not slowed * nodes), its power consumption, * change the ending event in the system. * For simplicity we assume that if the job frequency changes, it * changes in every node is running (the duration considered * would be the longest anyway), therefore it will consume less * power also in nodes which were not forced to slow down * by RAPL (or other mechanisms). * In input is given the power allocated to the job - * computed by other function - and the job frequency is changed * accordingly (it may increase or increase given the current * job power consumption and frequency). * * !!! The implementation of this function is _not_ entirely bug-free * In some (rare) case the resulting duration is wrongly * computed - basically it explodes to meaningless values !!! * * This is the method that perform the actual power reduction and * subsequent duration increase. It must be changed to implement * a different power-dilation model. Important thing to remember: * after having decided a new power and duration for the job passed * as input we have to (if necessary): * 1) change the Dispatcher's problem descriptor (_jobs_info) * and auxiliary structure (_running_jobs, _final_schedule) * 2) change the event list - removing the old ones and adding * the new ones * 3) notify the optimizer internal problem description (_opt) * about the changes */ bool setJob_FreqPowDur_dynamic( int job_idx, int job_allocated_power, long long cur_time){ long long elapsed_dur = cur_time - _jobs_info[job_idx].start_time; long long remained_dur = _jobs_info[job_idx].dur - elapsed_dur; double old_power = _jobs_info[job_idx].cur_power; long long new_remained_dur; double new_power, new_power_perNode; long long old_end_time = _jobs_info[job_idx].end_time; // the duration increase is proportional to the power variation if(_dyn_RAPL_mode == 1){ /* Reducing the job power */ if(_jobs_info[job_idx].cur_power_perNode > job_allocated_power){ double powMul_desired = job_allocated_power / _jobs_info[job_idx].cur_power_perNode; double durMul = 1 / powMul_desired; /* In this mode, it is possible to indefinitely decrease * a job power consumption - there's no check on the minimal * power reduction nor on the maximal duration increment * We force the minimal node allocation power to 1W */ new_remained_dur = durMul * remained_dur; if(new_power < 0) new_power = _node_min_alloc_power; new_power = powMul_desired * _jobs_info[job_idx].cur_power; if(new_power_perNode < 0) new_power_perNode = _node_min_alloc_power; new_power_perNode = powMul_desired * _jobs_info[job_idx].cur_power_perNode; } /* Job power may increase */ else if(_jobs_info[job_idx].cur_power_perNode <= job_allocated_power){ // job not at max frequency if(_jobs_info[job_idx].original_dur < _jobs_info[job_idx].dur){ double powMul_desired = job_allocated_power / _jobs_info[job_idx].cur_power_perNode; double durMul = 1 / powMul_desired; /* when increasing the power of a job, the maximum power * consumption (specified by it predicted power) must * not be exceeded - also the duration cannot become smaller * than the original one */ double np = powMul_desired * _jobs_info[job_idx].cur_power; double npp = powMul_desired * _jobs_info[job_idx].cur_power_perNode; long long nrd = durMul * remained_dur; (np > _jobs_info[job_idx].power_pred ? new_power = _jobs_info[job_idx].power_pred : new_power = np); (npp > _jobs_info[job_idx].power_pred_perNode ? new_power_perNode = _jobs_info[job_idx].power_pred_perNode : new_power_perNode = npp); (nrd + elapsed_dur < _jobs_info[job_idx].original_dur ? new_remained_dur = _jobs_info[job_idx].original_dur - elapsed_dur : new_remained_dur = nrd); } // job already at max frequency else{ new_power = _jobs_info[job_idx].power_pred; new_power_perNode = _jobs_info[job_idx].power_pred_perNode; new_remained_dur = _jobs_info[job_idx].original_dur - elapsed_dur; } } } // end of _dyn_RAPL_mode == 1 // the duration increase is proportional to the power variation // multiplied by a factor (real value between 0 and 1) else if(_dyn_RAPL_mode == 3){ /* Reducing the job power */ if(_jobs_info[job_idx].cur_power_perNode > job_allocated_power){ double powMul_desired = job_allocated_power / _jobs_info[job_idx].cur_power_perNode; double durMul = 1 / powMul_desired * perfModel_factor_; if(powMul_desired == 1) durMul = 1; // if the powMul is very close to 1 (curPower_perNode very close to // allocated_power), durMul risks to become smaller than 1 (after // having been multiplied by the perfModel_factor): this must not // happen, reducing the power/freq cannot lead a job to last less // time. We fix it imposing a durMult of at least 1 if(durMul < 1) durMul = 1; /* In this mode, it is possible to indefinitely decrease * a job power consumption - there's no check on the minimal * power reduction nor on the maximal duration increment. * We force the minimal node allocation power to 1W */ new_remained_dur = durMul * remained_dur; if(new_power < 0) new_power = _node_min_alloc_power; new_power = powMul_desired * _jobs_info[job_idx].cur_power; if(new_power_perNode < 0) new_power_perNode = _node_min_alloc_power; new_power_perNode = powMul_desired * _jobs_info[job_idx].cur_power_perNode; } /* Job power may increase */ else if(_jobs_info[job_idx].cur_power_perNode <= job_allocated_power){ /* This is not true if the duration increase is not directly * proportional to the power decrease: we may reach situation when * the duration went back to the original one while the power * is still smaller than the predicted one */ // job not at max frequency if(_jobs_info[job_idx].power_pred > _jobs_info[job_idx].cur_power){ double powMul_desired = job_allocated_power / _jobs_info[job_idx].cur_power_perNode; double durMul = 1 / powMul_desired; if(powMul_desired == 1) durMul = 1; if(durMul > 1) durMul = 1; /* when increasing the power of a job, the maximum power * consumption (specified by its predicted power) must * not be exceeded - also the duration cannot become smaller * than the original one */ double np = powMul_desired * _jobs_info[job_idx].cur_power; double npp = powMul_desired * _jobs_info[job_idx].cur_power_perNode; long long nrd = durMul * remained_dur; if(nrd > remained_dur) nrd = remained_dur; long long dur_decrease = remained_dur - nrd; double dur_decr_factorized = dur_decrease * perfModel_factor_; nrd = remained_dur - dur_decr_factorized; assert(powMul_desired >= 1); assert(durMul >= 0); assert(durMul <= 1); assert(nrd <= remained_dur); (np > _jobs_info[job_idx].power_pred ? new_power = _jobs_info[job_idx].power_pred : new_power = np); (npp > _jobs_info[job_idx].power_pred_perNode ? new_power_perNode = _jobs_info[job_idx].power_pred_perNode : new_power_perNode = npp); (nrd + elapsed_dur < _jobs_info[job_idx].original_dur ? new_remained_dur = _jobs_info[job_idx].original_dur - elapsed_dur : new_remained_dur = nrd); } // job already at max frequency else{ new_power = _jobs_info[job_idx].power_pred; new_power_perNode = _jobs_info[job_idx].power_pred_perNode; new_remained_dur = _jobs_info[job_idx].original_dur - elapsed_dur; } } } // end of _dyn_RAPL_mode == 3 // the duration-power changes differ for each job (mixed approach) // each job class has its own performance-model factor else if(_dyn_RAPL_mode == 4){ double jobClass_perfModel_factor = compute_job_perfModel_factor(job_idx, _jobs_info[job_idx].application_type); /* Reducing the job power */ if(_jobs_info[job_idx].cur_power_perNode > job_allocated_power){ double powMul_desired = job_allocated_power / _jobs_info[job_idx].cur_power_perNode; double durMul = 1 / powMul_desired * jobClass_perfModel_factor; if(powMul_desired == 1) durMul = 1; // if the powMul is very close to 1 (curPower_perNode very close to // allocated_power), durMul risks to become smaller than 1 (after // having been multiplied by the perfModel_factor): this must not // happen, reducing the power/freq cannot lead a job to last less // time. We fix it imposing a durMult of at least 1 if(durMul < 1) durMul = 1; /* In this mode, it is possible to indefinitely decrease * a job power consumption - there's no check on the minimal * power reduction nor on the maximal duration increment * We force the minimal node allocation power to 1W */ new_remained_dur = durMul * remained_dur; if(new_power < 0) new_power = _node_min_alloc_power; new_power = powMul_desired * _jobs_info[job_idx].cur_power; if(new_power_perNode < 0) new_power_perNode = _node_min_alloc_power; new_power_perNode = powMul_desired * _jobs_info[job_idx].cur_power_perNode; } /* Job power may increase */ else if(_jobs_info[job_idx].cur_power_perNode <= job_allocated_power){ /* This is not true if the duration increase is not directly * proportional to the power decrease: we may reach situation when * the duration went back to the original one while the power * is still smaller than the predicted one */ if(_jobs_info[job_idx].power_pred > _jobs_info[job_idx].cur_power){ double powMul_desired = job_allocated_power / _jobs_info[job_idx].cur_power_perNode; double durMul = 1 / powMul_desired; if(powMul_desired == 1) durMul = 1; if(durMul > 1) durMul = 1; double np = powMul_desired * _jobs_info[job_idx].cur_power; double npp = powMul_desired * _jobs_info[job_idx].cur_power_perNode; /* when increasing the power of a job, the maximum power * consumption (specified by its predicted power) must * not be exceeded - also the duration cannot become smaller * than the original one */ long long nrd = durMul * remained_dur; if(nrd > remained_dur) nrd = remained_dur; long long dur_decrease = remained_dur - nrd; double dur_decr_factorized = dur_decrease * jobClass_perfModel_factor; nrd = remained_dur - dur_decr_factorized; (np > _jobs_info[job_idx].power_pred ? new_power = _jobs_info[job_idx].power_pred : new_power = np); (npp > _jobs_info[job_idx].power_pred_perNode ? new_power_perNode = _jobs_info[job_idx].power_pred_perNode : new_power_perNode = npp); (nrd + elapsed_dur < _jobs_info[job_idx].original_dur ? new_remained_dur = _jobs_info[job_idx].original_dur - elapsed_dur : new_remained_dur = nrd); } // job already at max frequency else{ new_power = _jobs_info[job_idx].power_pred; new_power_perNode = _jobs_info[job_idx].power_pred_perNode; new_remained_dur = _jobs_info[job_idx].original_dur - elapsed_dur; } } } // end of _dyn_RAPL_mode == 4 // the duration doesn't change if we modify the power consumption else{ // wheter the job power increases or decreases there's no // impact on job duration /* Reducing the job power */ if(_jobs_info[job_idx].cur_power_perNode > job_allocated_power){ double powMul_desired = job_allocated_power / _jobs_info[job_idx].power_pred_perNode; double durMul = 1; new_remained_dur = durMul * remained_dur; new_power = powMul_desired * _jobs_info[job_idx].power_pred; new_power_perNode = powMul_desired * _jobs_info[job_idx].power_pred_perNode; } /* Job power may increase */ else if(_jobs_info[job_idx].cur_power_perNode <= job_allocated_power){ // job not at max frequency if(_jobs_info[job_idx].cur_power_perNode < _jobs_info[job_idx].power_pred_perNode){ double powMul_desired = job_allocated_power / _jobs_info[job_idx].cur_power_perNode; double durMul = 1; double np = powMul_desired * _jobs_info[job_idx].cur_power; double npp = powMul_desired * _jobs_info[job_idx].cur_power_perNode; (np > _jobs_info[job_idx].power_pred ? new_power = _jobs_info[job_idx].power_pred : new_power = np); (npp > _jobs_info[job_idx].power_pred_perNode ? new_power_perNode = _jobs_info[job_idx].power_pred_perNode : new_power_perNode = npp); new_remained_dur = durMul * remained_dur; } // job already at max frequency else{ new_power = _jobs_info[job_idx].power_pred; new_power_perNode = _jobs_info[job_idx].power_pred_perNode; new_remained_dur = _jobs_info[job_idx].dur - elapsed_dur; } } } // end of _dyn_RAPL_mode == 0 long long new_end_time = cur_time + new_remained_dur; if(new_end_time != cur_time){ // apply changes to online dispatcher // remove end events of slowed down jobs and add new end events auto it = _events.find(old_end_time); assert(it != _events.end()); // remove old ending event // iterate over all events registered at end time of the slowed job for(auto it2 = it->second.begin(); it2 != it->second.end();){ if(it2->job_ext_idx == job_idx) it2 = it->second.erase(it2); else ++it2; } // add new ending event auto itne = _events.find(new_end_time); if (itne != _events.end()) itne->second.push_back({job_idx, job_ending}); else _events[new_end_time] = {{job_idx, job_ending}}; // update auxiliary structures _jobs_info[job_idx].end_time = new_end_time; _running_jobs[job_idx].end_time = new_end_time; _final_schedule[job_idx].end = new_end_time; if(new_power < 1){ new_power = 1; } if(new_power_perNode < 1){ new_power_perNode = 1; } _jobs_info[job_idx].cur_power = new_power; _running_jobs[job_idx].cur_power = new_power; _jobs_info[job_idx].cur_power_perNode = new_power_perNode; _running_jobs[job_idx].cur_power_perNode = new_power_perNode; _jobs_info[job_idx].dur = elapsed_dur + new_remained_dur; _running_jobs[job_idx].dur = elapsed_dur + new_remained_dur; /* Track power variation in the job execution trace */ // if the vector is empty this is the first frequency re-assignment if(_jobs_info[job_idx].exec_hist.size() == 0){ /* We must add a pair in the vector: the one related to * the first part of the execution */ _jobs_info[job_idx].exec_hist.push_back( make_pair(old_power, elapsed_dur)); _running_jobs[job_idx].exec_hist.push_back( make_pair(old_power, elapsed_dur)); } else{ /* We add a new event-pair: the one related to the last * part of the execution before the new change of freq. */ // the power was the one before the change /* The duration of the N part is given as: current_time - * job_start_time - sum(duration previous subparts) */ long long dur_so_far = 0; for(auto eh : _jobs_info[job_idx].exec_hist) dur_so_far += eh.second; long long new_part_dur = elapsed_dur - dur_so_far; _jobs_info[job_idx].exec_hist.push_back( make_pair(old_power, new_part_dur)); _running_jobs[job_idx].exec_hist.push_back( make_pair(old_power, new_part_dur)); } } // Notify optimizer _opt->setPower(job_idx, _jobs_info[job_idx].cur_power); _opt->setPowerPred(job_idx, _jobs_info[job_idx].power_pred); _opt->setFrequency(job_idx, _jobs_info[job_idx].frequency); _opt->setDur(job_idx, _jobs_info[job_idx].dur); // measure again the power (to update auxiliary structure) measure_power(cur_time); return true; } /* Simulate power measuring framework: here the power * measured corresponds to the job predicted power * (which could have been previously change by * frequency modifications) */ void measure_power(long long time){ _system_power = 0; for(auto np : _nodes_power) _nodes_power[np.first] = 0; for(auto rj : _running_jobs){ _system_power += rj.second.cur_power; for(int n : rj.second.node_mapping) _nodes_power[n] += rj.second.cur_power_perNode; } _system_power_profile[time] = _system_power; _nodes_power_profile[time] = _nodes_power; } /* Dynamic power capping based on RAPL * The RAPL-based power capping is loosely based on * Ellsworth et al 2015, * "Dynamic Power Sharing for Higher Job Throughput" * , in particular the algorithm that decides how the amount * of power to allocate to each CPU * * This is the method deciding the amount of power to be * allocated to each node */ void enforce_dyn_power_cap(long long cur_time){ int numdown; int temp_pow_alloc; // according to paper should be: _power_cap / number of nodes // when using only the dynamic control _power_cap has a fake value: // use _target_sys_power instead // in this implementation the user specified node power // budget can prevail (if node_power_cap > _power_cap / #nodes // a violations of the overall cap may happen) int node_power_cap; node_power_cap = int(round((double) _target_sys_power / _nodes.size())); if(_dynPowerShare_firstMeasure){ // initially, the system available power is allocated uniformly // to all nodes // identify nodes where the cap is currently not respected vector nodes_overCap; for(auto np : _nodes_power){ // allocate the node power if(node_power_cap < _node_min_alloc_power) _nodes_alloc_power[np.first] = _node_min_alloc_power; else _nodes_alloc_power[np.first] = node_power_cap; } _dynPowerShare_firstMeasure = 0; } else{ double used_power = 0; for(auto np : _nodes_power) used_power += np.second; // power-capped scheduler with relaxed constraint or pure RAPL // after the first measure used for initialization // the power sharing algorithm starts working temp_pow_alloc = 0; for(auto na : _nodes_alloc_power) temp_pow_alloc += na.second; /* Alloc down */ numdown = 0; long long alloc_sum = 0; long long downNodes_alloc_sum = 0; for(auto np : _nodes_power){ if(np.second < _nodes_alloc_power[np.first] - _target_node_wastedPower){ _nodes_alloc_power[np.first] = max( np.second + _target_node_wastedPower, _node_min_alloc_power); _nodes_reclaim[np.first] = 0; ++numdown; downNodes_alloc_sum += _nodes_alloc_power[np.first]; } else{ _nodes_reclaim[np.first] = 1; } alloc_sum += _nodes_alloc_power[np.first]; } if(numdown == 0 && alloc_sum + _nodes.size() >= _target_sys_power){ alloc_sum = 0; for(auto np : _nodes_power){ if(_nodes_alloc_power[np.first] > node_power_cap){ _nodes_reclaim[np.first] = 1; _nodes_alloc_power[np.first] = _nodes_alloc_power[np.first] - (_nodes_alloc_power[np.first] - node_power_cap) * (1 - _reclaim_factor); } alloc_sum += _nodes_alloc_power[np.first]; } } temp_pow_alloc = 0; for(auto na : _nodes_alloc_power) temp_pow_alloc += na.second; /* Alloc up */ int u = 0; /* _power_cap is used by the dispatcher during scheduling * phase: if we want to apply only dynamic power sharing * its value its meaningless --> the power target * should be used */ if(_nodes.size() > numdown) u = round((_target_sys_power - alloc_sum) / (double) (_nodes.size() - numdown)); int spare_power = _target_sys_power - downNodes_alloc_sum; for(auto np : _nodes_power){ if(_nodes_reclaim[np.first]){ _nodes_alloc_power[np.first] = min( _nodes_alloc_power[np.first] + u, _node_max_alloc_power); spare_power -= _nodes_alloc_power[np.first]; } } } temp_pow_alloc = 0; for(auto na : _nodes_alloc_power) temp_pow_alloc += na.second; /* After deciding the power allocation, apply RAPL */ for(auto na : _nodes_alloc_power) apply_nodeRAPL(na.first, na.second, cur_time); } /* Emulate RAPL behaviour: all jobs running on the * input node will be slowed down in order to * force the power consumption under the desired value. * * This is the method that decide how much power must be allocated * to each job running on the node passed as parameter */ bool apply_nodeRAPL(int node, int node_power_cap, long long cur_time){ // if the desired reduced power is smaller than the idle // node power then it's impossible to decrease the power if(node_power_cap < _node_min_alloc_power && opt_type_ != 0 && opt_type_ != 2){ return false; } bool result = true; // count the number of jobs not at max frequency int jobNotMaxFreq = 0; for(long long j : _node_running_jobs[node]) if(_jobs_info[j].power_pred_perNode > _jobs_info[j].cur_power_perNode) ++jobNotMaxFreq; if(_nodes_power[node] <= node_power_cap){ if(jobNotMaxFreq == 0){ /* if the power consumed by the node is already within the * budget, and no job on the node was previously slowed, * RAPL doesn't need to * change frequency/voltage to reduce power */ } else{ /* if the power consumed by the node is already within the * budget but some jobs on the node were previously slowed, * the frequency/voltage can be increased by RAPL */ // we try to uniformly reduce the power consumption of all // interested jobs map pow_weights; for(long long j : _node_running_jobs[node]){ double pow_weight = _nodes_power[node] / (double) _jobs_info[j].cur_power_perNode; pow_weights[j] = pow_weight; } for(long long j : _node_running_jobs[node]){ double pow_weight = _nodes_power[node] / (double) _jobs_info[j].cur_power_perNode; // power allocation based on current power consumption int new_job_alloc_power = node_power_cap / pow_weights[j]; // uniform power allocation to all jobs running on the node if(new_job_alloc_power == 0) new_job_alloc_power = 1; bool setFreq_result = setJob_FreqPowDur_dynamic( j, new_job_alloc_power, cur_time); } } } /* if the power exceeds the available budgets, all jobs * running on the nodes will be slowed by RAPL */ else{ // we try to uniformly reduce the power consumption of all // interested jobs map pow_weights; for(long long j : _node_running_jobs[node]){ double pow_weight = _nodes_power[node] / (double) _jobs_info[j].cur_power_perNode; pow_weights[j] = pow_weight; } for(long long j : _node_running_jobs[node]){ // power allocation based on current power consumption int new_job_alloc_power = node_power_cap / pow_weights[j]; // uniform power allocation to all jobs running on the node if(new_job_alloc_power == 0) new_job_alloc_power = 1; bool setFreq_result = setJob_FreqPowDur_dynamic( j, new_job_alloc_power, cur_time); if(!setFreq_result){ result = false; } } } return result; } /* Return the maximum system power consumption. * Computed using the input scheduler and * without power cap */ double get_max_power_consumption( long long from_time, long long until_time){ double max_sysPower = 0; for(auto spp : _system_power_profile){ // skip previous event if(spp.first < from_time) continue; // stop when reaches the last event if(spp.first > until_time) break; if(spp.second > max_sysPower) max_sysPower = spp.second; } return max_sysPower; } /* Function to compute information regarding the * system power * - a time window is given as input */ void analyse_power_usage( long long from_time, long long until_time){ double avg_sysPower = 0; map avg_nodePow; int measures_count = 0; long long total_time = 0; long long time_overTarget = 0; double avg_trgtDistance = 0; double avg_dist_overTrgt = 0; double avg_dist_underTrgt = 0; map time_overTarget_node; map avg_overTarget_node; double mean_time_overTarget_nodes = 0; double mean_distance_overTarget_nodes = 0; double mean_nodePower = 0; double max_sysPower = 0; long long longest_timeOverTarget = 0; vector times_overTarget; double avg_time_overTarget; int energy_available_tot = 0; int energy_used_tot = 0; for(auto np : _nodes_power){ avg_nodePow[np.first] = 0; time_overTarget_node[np.first] = 0; avg_overTarget_node[np.first] = 0; } long long prev_time = from_time; for(auto spp : _system_power_profile){ // skip previous event if(spp.first < from_time) continue; // stop when reaches the last event if(spp.first > until_time) break; avg_sysPower += spp.second; ++measures_count; if(spp.second > max_sysPower) max_sysPower = spp.second; long long time = spp.first; long long time_dif = time - prev_time; total_time += time_dif; energy_available_tot += _target_sys_power * time_dif; energy_used_tot += spp.second * time_dif; double trgtDistance = _target_sys_power - spp.second; trgtDistance /= _target_sys_power; avg_trgtDistance += trgtDistance; if(spp.second > _target_sys_power){ time_overTarget += time_dif; avg_dist_overTrgt += trgtDistance; } else avg_dist_underTrgt += trgtDistance; prev_time = time; } avg_trgtDistance /= measures_count; avg_dist_underTrgt /= measures_count; avg_dist_overTrgt /= measures_count; prev_time = from_time; for(auto npp : _nodes_power_profile){ // skip previous event if(npp.first < from_time) continue; // stop when reaches the last event if(npp.first > until_time) break; long long time = npp.first; long long time_dif = time - prev_time; for(auto np : npp.second){ avg_nodePow[np.first] += np.second; double trgtDistance = _target_node_power - np.second; trgtDistance /= _target_node_power; if(np.second > _target_node_power){ time_overTarget_node[np.first] += time_dif; avg_overTarget_node[np.first] += trgtDistance; } } prev_time = time; } avg_sysPower /= (double) measures_count; for(auto np : _nodes_power){ avg_nodePow[np.first] /= double(measures_count); avg_overTarget_node[np.first] /= double(measures_count); time_overTarget_node[np.first] /= double(measures_count); mean_time_overTarget_nodes += time_overTarget_node[np.first]; mean_distance_overTarget_nodes += avg_overTarget_node[np.first]; mean_nodePower += avg_nodePow[np.first]; } mean_time_overTarget_nodes /= _nodes_power.size(); mean_distance_overTarget_nodes /= _nodes_power.size(); mean_nodePower /= _nodes_power.size(); cout << "System average power: " << avg_sysPower << endl; cout << "Tot time: " << total_time << endl; cout << "Time over target (%) " << (double)time_overTarget / total_time * 100 << endl; cout << "Avg distance from target: " << avg_trgtDistance << endl; cout << "Avg. over target: " << avg_dist_overTrgt << endl; cout << "Avg. under target: " << avg_dist_underTrgt << endl; cout << "Node average power: " << mean_nodePower << endl; cout << "Time over target (%), per node, avg among nodes: "; cout << mean_time_overTarget_nodes; cout << endl; cout << "Avg. distance from node target (over only), avg among nodes: "; cout << mean_distance_overTarget_nodes; cout << endl; cout << "Total available energy: " << energy_available_tot << endl; cout << "Total used energy: " << energy_used_tot << endl; cout << "Used/Available %: " << (double) energy_used_tot / energy_available_tot * 100 << endl; cout << "System max power: " << max_sysPower << endl; cout << "Measures Count: " << measures_count << endl; double avg_jobs_perfModel_factors = 0; for(auto it : jobs_perfModel_factors_) avg_jobs_perfModel_factors += it.second; avg_jobs_perfModel_factors /= jobs_perfModel_factors_.size(); cout << "Avg. jobs_perfModel_factors: " << avg_jobs_perfModel_factors << endl; } /* Power budget have been exceeded * Typically the dispatcher respond to power cap variations by computing * a new schedule - if needed jobs in the queue are postponed until * the power budget rises again or some jobs complete. * The "excessive power" situation arises when current system power * consumption exceeds the new power constraint: * - no new jobs can start * - running jobs need to be slowed down */ void manage_excessive_power(long long power_slack, long long cur_time){ /* There are no current stable implementation to address this * problem. Still subject of current research. * Relatively simple solution would be to apply DVFS/RAPL * to already running jobs */ } /* Method to generate different startup situations. * The system may be already partially (even fully) occupied * at the beginning of the simulation */ void initiate_startup(){ /* Very simple dummy jobs: each one occupies a single node * and requires half/all of the cores in the node (and 1/8 of the * total memory). The power consumption is negligible (or not). * As many job as to fill the machine in the * percentage selected as input */ int power = 5; int nfake_jobs = double(_nodes.size()) / 100 * startup_hotness_; for(int i = 0; i < nfake_jobs; ++i){ _job_info j_info; j_info.job_idx = _jobs.size() * 2 + i; if(i < nfake_jobs / 2) j_info.dur = 600; else j_info.dur = 1200; j_info.original_dur = j_info.dur; j_info.ewt = 1800; j_info.qet = _ref_time; j_info.power_pred = power; j_info.power_pred_perNode = power; j_info.cur_power = power; j_info.cur_power_perNode = power; j_info.frequency = -1; j_info.energy = -1; // nodes mapping int node; j_info.start_time = _ref_time; j_info.end_time = _ref_time + j_info.dur; // half of the nodes use high nodes, the other half low nodes if(i < nfake_jobs / 2){ j_info.node_type = 0; node = i; } else{ j_info.node_type = 1; node = _nodeType_threshold + i - nfake_jobs / 2; } j_info.node_mapping.push_back(node); j_info.application_type = 0; int nunits = 1; vector > unit_reqs; j_info.reqs.resize(nunits); j_info.tot_reqs.resize(_ndims,0); int ncores; for (int u = 0; u < nunits; ++u) { j_info.reqs[u].resize(_ndims); // get the requirement of each job unit // (and store them for the internal job_info map) long long rcores = _nodes[node].getCoresNumber(); ncores = rcores; j_info.reqs[u][0] = rcores; j_info.tot_reqs[0] += rcores; long long rgpus = 0; j_info.reqs[u][1] = rgpus; j_info.tot_reqs[1] += rgpus; long long rmics = 0; j_info.reqs[u][2] = rmics; j_info.tot_reqs[2] += rmics; long long rmem = _nodes[node].getTotalMemory() / 8; j_info.reqs[u][3] = rmem; j_info.tot_reqs[3] += rmem; // store the unit requirements unit_reqs.push_back({rcores, rgpus, rmics, rmem}); } // add the job to the optimizer _opt->addJob(j_info.job_idx, j_info.dur, j_info.power_pred, j_info.cur_power, j_info.qet, j_info.ewt, j_info.application_type, unit_reqs); _opt->setDur(j_info.job_idx, j_info.dur); _opt->setPower(j_info.job_idx, j_info.cur_power); _opt->setPowerPred(j_info.job_idx, j_info.power_pred); _opt->setFrequency(j_info.job_idx,-1); _opt->setStartAndMapping(j_info.job_idx, j_info.start_time, j_info.node_mapping); // store the information about the job in the internal map _jobs_info[j_info.job_idx] = {j_info}; _running_jobs[j_info.job_idx] = {j_info}; vector exec_nodes = j_info.node_mapping; for(int en : exec_nodes){ if(find(_node_running_jobs[en].begin(), _node_running_jobs[en].end(), j_info.job_idx) == _node_running_jobs[en].end() ) _node_running_jobs[en].push_back(j_info.job_idx); } // update cached resources capacities update_caps(j_info.job_idx, -1, j_info.node_mapping); // update power update_power(j_info.job_idx, 1); // add ending event long long end_time = j_info.end_time; auto it = _events.find(end_time); if (it != _events.end()) it->second.push_back({j_info.job_idx, job_ending}); else _events[end_time] = {{j_info.job_idx, job_ending}}; _fake_jobs.push_back(j_info.job_idx); // compute job powerPerfModel factor (to be used // also by some optimiezers - those using RAPL) compute_job_perfModel_factor( j_info.job_idx, j_info.application_type); } } public: void setSystemPowerCap(double power_cap){ assert(power_cap > 0); _power_cap = power_cap; } double getSystemCurrentPower(){ return _current_power; } double getSystemPower_atTime(long long time){ double power; auto it = _historical_powers.find(time); (it != _historical_powers.end()) ? power = it->second : power = -1; return power; } /* Constructor */ OnlineDispatcher(Optimizer* opt, Predictor* predictor, vector& jobs, vector& qs, vector& nodes, long long ref_time, int ndims, long long power_cap, long long target_sys_power, long long target_node_power, map& power_caps, int freqAssign_mode, int dynControl_mode, double perfModel_factor, int startup_hotness, int opt_type, string job_instance) : _opt(opt), _predictor(predictor), _jobs(jobs), _queues(qs), _nodes(nodes), _ref_time(ref_time), _ndims(ndims), _power_cap(power_cap), _power_caps(power_caps), _dyn_RAPL_mode(dynControl_mode), _freqAssign_mode(freqAssign_mode), perfModel_factor_(perfModel_factor), startup_hotness_(startup_hotness), opt_type_(opt_type) { unsigned int hashed_job_instance = std::hash{}(job_instance); seed_ = hashed_job_instance; // add an event at the reference time _events[_ref_time] = {}; prev_notMeasure_time_ = _ref_time; (target_sys_power == -1) ? _target_sys_power = power_cap : _target_sys_power = target_sys_power; (target_node_power == -1) ? _target_node_power = int(round(_target_sys_power / nodes.size())) : _target_node_power = target_node_power; // add fake events corresponding to power cap variations // assumption: only one power cap for each time _power_cap_variations_left = 0; for(auto pce : power_caps){ _power_cap_variations_left += 1; long long time = pce.first; auto it = _events.find(time); if(it == _events.end()) _events[time] = {{-pce.second, power_cap_variation}}; else it->second.push_back({-pce.second, power_cap_variation}); } // add fake events corresponding to power measurements long long max_mks = 0; _power_measurements_left = 0; for(auto j : jobs) max_mks += j.getEstimatedDuration(); // the power measurement evenents have a fake event id // positive number that cannot be confonded with the jobs ids long long fake_evnt_id = jobs.size() + 50; long long time_counter = 0; while(time_counter < max_mks){ time_counter += _power_measure_step_fixed; _power_measurements_left++; long long time = _ref_time + time_counter; auto it = _events.find(time); if(it == _events.end()) _events[time] = {{fake_evnt_id, power_measure}}; else it->second.push_back({fake_evnt_id, power_measure}); } // set the initial used resources _cumul_res_usgs.resize(_ndims, 0); _cumul_res_caps.resize(_ndims, 0); _max_cumul_res_caps.resize(_ndims, 0); // init cached resource capacities for(auto node : nodes){ vector res_cap(ndims); res_cap[0] = node.getCoresNumber(); _cumul_res_caps[0] += node.getCoresNumber(); _max_cumul_res_caps[0] += node.getCoresNumber(); res_cap[1] = node.getGPUsNumber(); _cumul_res_caps[1] += node.getGPUsNumber(); _max_cumul_res_caps[1] += node.getGPUsNumber(); res_cap[2] = node.getMICsNumber(); _cumul_res_caps[2] += node.getMICsNumber(); _max_cumul_res_caps[2] += node.getMICsNumber(); res_cap[3] = node.getTotalMemory(); _cumul_res_caps[3] += node.getTotalMemory(); _max_cumul_res_caps[3] += node.getTotalMemory(); _res_caps.push_back(res_cap); vector res_usg; res_usg.resize(ndims, 0); _res_usgs.push_back(res_usg); _nodes_power[node.getNodeNumber()] = 0; _dynPowerShare_firstMeasure = 1; } _min_reqs.resize(_ndims, std::numeric_limits::max()); _system_power = 0; /* This depends on the target system characteristics: * the nodes with lower ids (first half) are low_freq, * nodes ids in the second half are high_freq */ _nodeType_threshold = nodes.size() / 2; CompatibilityChecker chk; // default checker IntervalManager mng; // default manager // Add all nodes to the problem for (int idx = 0; idx < nodes.size(); ++idx) { // Obtain a reference to the node Node& node = nodes[idx]; // Obtain the node capacity for all resource types long long ccores = node.getCoresNumber(); long long cgpus = node.getGPUsNumber(); long long cmics = node.getMICsNumber(); long long cmem = node.getTotalMemory(); } // startup situation initiate_startup(); } void writeSchedule(std::ostream& out){ _opt->writeSched(out); } /* This function controls if it would make sense to compute a * new schedule or not: it makes sense only if the current * available resources capacity is larger than the min amount * of resources asked (by one of the jobs waiting to * be scheduled) */ bool is_schedule_needed(){ // if there is at least one job that can fit with the current capacities for(auto job : _waiting_jobs){ bool fit = true; for(int d = 0; d < _ndims; ++d) if(job.second.tot_reqs[d] > _cumul_res_caps[d]) fit = false; if(fit) return true; } return false; } /* Main dispatching function. * After having initialized the internal status, the methods begins * processing time events (starting from the reference time (i.e. the * arrival of the first job in the system). * The dispatching continues until there are remaining events (i.e. new * job arrivals, job completions, power cap variations, power measurements). * At each scheduling event (job arrival/completion, power cap variation) * a new schedule is computed (if needed) using the chosen optimizer (i.e. * EASY-BF) */ void dispatch(bool dry_run){ CustomTimer iterTimer; // number of schedules computed int n_scheds = 0; long long last_time = _ref_time; vector jobs_to_schedule; // jobs that need to be scheduled for (int i = 0; i < _jobs.size(); ++i) { // Jobs that do not yet have a start time must be scheduled jobs_to_schedule.push_back(i); } // loop as long as: // 1) there are time points to process // 2) there are jobs to dispatch // In practice the loop should always end because of condition 2 for (auto evt : _events) { iterTimer.reset(); iterTimer.start(); // tells if a new schedule must be computed or not bool compute_schedule = false; // access the current time long long cur_time = evt.first; long long time_dif = cur_time - last_time; last_time = cur_time; /* If we don't need to have power cap variations or * power measuring events (it was useful to test pure scheduling * and allocation policies without considering a power budget) * the dispatching can stop when all jobs have been scheduled. * If this is the case, de-commenting the following lines will * quicken the simulation */ //if (jobs_to_schedule.size() == 0) { // cout << "no more jobs to schedule" << endl; // break; // EARLY EXIT //} /* Stop processing events when * all jobs have been scheduled and we know there won't be more * power constraint variations - this is clearly possible * only because in our simulator we know in advance the * number of power variations. * With this condition the simulation stop when all jobs have * been scheduled and no more power variations are expected: * there could be still power measuring events pending but we * disregard them */ if (jobs_to_schedule.size() == 0 && _power_cap_variations_left == 0) { break; // EARLY EXIT } /* This last condition is used to process all the events, * included the power measurements. The simulation takes * longer and some results may change (in RAPL case). */ //if (jobs_to_schedule.size() == 0 && // _power_cap_variations_left == 0 && // _power_measurements_left == 0) { // break; // EXIT //} // check if the event list contains only measurements events; // in this case we don't print some information bool only_power_measure_event = true; for(auto je : evt.second) if(je.type != power_measure) only_power_measure_event = false; if(!only_power_measure_event){ //cout << "=== processing time " << cur_time - _ref_time << // " (" << cur_time << " - " << Util::timeToStr(cur_time) // << ")" << endl; //cout << "Current power cap value: " << _power_cap << // " - system power consumption: " << getSystemCurrentPower() // << endl; } // add resources usage ratio at event vector usg_ratio(_ndims); for(int i = 0; i < _ndims; i++){ double ratio = (double) _cumul_res_usgs[i] / (double) _max_cumul_res_caps[i]; usg_ratio[i] = ratio; } _sys_util[cur_time] = usg_ratio; if(evt.second.size() == 0) compute_schedule = true; vector just_arrived; for (_job_evt jdesc : evt.second) { long long job_idx = jdesc.job_ext_idx; if (jdesc.type == job_starting) { } else if (jdesc.type == job_arriving) { // An arriving job is treated as a schedulable job from now on // In the text-based framework, arriving jobs might be in the // jobs_to_schedule list already --> in this case we should not // add them again if(std::find(jobs_to_schedule.begin(), jobs_to_schedule.end(), job_idx) == jobs_to_schedule.end()) jobs_to_schedule.push_back(job_idx); if(std::find(just_arrived.begin(), just_arrived.end(), job_idx) == just_arrived.end()) just_arrived.push_back(job_idx); } else if (jdesc.type == job_ending){ // remove the job from the optimizer _opt->remJob(job_idx); if(job_idx <= _jobs.size()){ // update cached resources capacities update_caps(job_idx, 1, _final_schedule[job_idx].mapping); // update power update_power(job_idx, -1); // compute energy consumed by job in its life _jobs_info[job_idx].energy = get_job_final_energy(job_idx, cur_time); } else{ // update cached resources capacities update_caps(job_idx, 1, _jobs_info[job_idx].node_mapping); // update power update_power(job_idx, -1); // remove the job from the fake-jobs list if(find(_fake_jobs.begin(), _fake_jobs.end(), job_idx) != _fake_jobs.end() ) _fake_jobs.erase( remove(_fake_jobs.begin(), _fake_jobs.end(), job_idx), _fake_jobs.end()); } auto itr = _running_jobs.find(job_idx); assert(itr != _running_jobs.end()); // add ending job to completed set _ended_jobs[job_idx] = itr->second; // delete ending job from running set _running_jobs.erase(itr); // delete ending job from node running set vector exec_nodes = _jobs_info[job_idx].node_mapping; for(int en : exec_nodes){ if(find(_node_running_jobs[en].begin(), _node_running_jobs[en].end(), job_idx) != _node_running_jobs[en].end() ) _node_running_jobs[en].erase( remove(_node_running_jobs[en].begin(), _node_running_jobs[en].end(), job_idx), _node_running_jobs[en].end()); } } // power cap variation else if(jdesc.type == power_cap_variation){ int power_cap = abs(job_idx); // set the new power budget assert(power_cap > 0); setSystemPowerCap(power_cap); _power_cap_variations_left--; } // power measurement else if(jdesc.type == power_measure){ // measure current system and node power _power_measurements_left--; measure_power(cur_time); /* If we are employing dynamic power capping methods, * a power measurements event triggers the mechanisms */ if(_dyn_RAPL_mode != -1){ /* Enforce the power cap: problem in this implementation * the power cap is enforced only AFTER scheduling - * the power consumption could already exceed the limit. * It's important that this periodical check and enforcing * is performed very frequently */ enforce_dyn_power_cap(cur_time); } } } // Move to the next event if the reference time (i.e. "now") has // not yet been reached. if (cur_time < _ref_time) { continue; // EARLY EXIT } if (jobs_to_schedule.size() == 0) { continue; } /* Dispatcher-level power control: before trying to compute * a new schedule and start new jobs the dispatcher compares * the current system power with the power cap to check if * the constraint is still respected --> useful only if the * power cap is not fixed (TODO: add this feature) * - we check the estimated power consumption of each job to * be scheduled; if none can fit within the power budget * no new job is started * - if the power constraint is already broken we do not * start new jobs and we try to slow down (decrease frequency * and power, increase duration) those already running */ int nfittin_jobs = 1; // no job consumes a (predicted) power small enough if(nfittin_jobs == 0){ // the power budget is exceeded by the currently running jobs /* The system power can be larger than the power cap if we * employ RAPL-like mechanism: the power consumption of the * scheduled jobs will be reduced by RAPL */ if(int(getSystemCurrentPower()) > _power_cap && _dyn_RAPL_mode == -1){ long long power_slack = getSystemCurrentPower() - _power_cap; /* if we reach this point to ensure not to exceed the power * budget we must reduce the power consumption of the * currently running jobs (the power must decrease of * power slack */ manage_excessive_power(power_slack, cur_time); } continue; } /* The power budget may change at run-time: we must let the * optimizer know */ _opt->setMaxPower(_power_cap); // prepare the new list of ranked jobs vector new_jobs_to_schedule; map scheduled_jobs; int sched_job_counter = 0; // try to dispatch each job for (auto i : jobs_to_schedule) { // Skip the job if its QET has not yet been reached if (_jobs[i].getEnterQueueTime() > cur_time) { // Add a new event at the arrival time, to be sure that it will // be processed long long qet = _jobs[i].getEnterQueueTime(); auto it = _events.find(qet); if (it == _events.end()) _events[qet] = {{i, job_arriving}}; else{ // check that the arriving event has not been added yet bool already_in = false; for(auto job_evts : it->second) if(i == job_evts.job_ext_idx) already_in = true; if(!already_in) it->second.push_back({i, job_arriving}); } continue; } // add to the optimizer those jobs which arrived in this time event if(find(_added_jobs.begin(), _added_jobs.end(), i) == _added_jobs.end()) addJob(i); sched_job_counter++; } // schedule the jobs using the chosen optimizer long long tmp_job_idx; vector tmp_unit_mapping; int tmp_frequency; typedef struct tmp_job_info{ long long tmp_job_idx; vector tmp_unit_mapping; int tmp_frequency; } tmp_job_info; vector started_jobs; started_jobs.clear(); /* Compute a new schedule when: * 1) a job arrives and there are enough available resources * 2) a job terminates (freeing busy resources) */ if(!only_power_measure_event){ for(auto je : evt.second){ //cout << "(" << je.job_ext_idx << "," << je.type << ") "; if((je.type == job_arriving && check_res_avail(je.job_ext_idx)) || je.type == job_ending) compute_schedule = true; } } if(!compute_schedule){ continue; } if(!is_schedule_needed()){ continue; } n_scheds++; /* This is the call to the dispatching function to the chosen * optimizer: _opt->nextJob(). * Inside nextJob() a start time and resource allocation is * assigned to each job to be scheduled; some jobs will have a start * time equal to cur_time, other will be scheduled for future events. * * nextJob() will send as output only those jobs with a start time * equal to the current time (thus this value is passed as * parameter). Consequently, the online dispatcher only starts the * jobs with that start time - the remaining ones * will be considered at future events (and possibly their start * times could change) */ while(_opt->nextJob( cur_time, tmp_job_idx, tmp_unit_mapping, tmp_frequency)){ scheduled_jobs[tmp_job_idx] = {cur_time}; // Check if an event for the end time exists. If this is the // case, register the jobs as "ending" at the event. Otherwise, // build a new job vector for the event containing only "i". /* Important: the optimizer takes its decision based on the * "estimated" duration (the values indicated by users at * submission time - the durations registered in _opt). * In reality, jobs can finish before the estimated duration * and the online dispatcher must set the end event corresponding * to a job just started according to the real duration. * In our case we have the real jobs' durations thanks to the * historical Eurora's traces (even the synthetic benchmarks * have both an estimated and a real duration) */ /* The job duration is the Real one - the estimated one * is still used when computing a schedule */ int realDur; /* Due to some data collection problems, we can have in certain * situation real duration greater than the expected one. * This is a bug due to the information gathering system and here * we force the real duration to smaller than the estimated one */ (_jobs[tmp_job_idx].getEstimatedDuration() < _jobs[tmp_job_idx].getRealDuration() ? realDur = _jobs[tmp_job_idx].getEstimatedDuration() : realDur = _jobs[tmp_job_idx].getRealDuration()); long long end_time = cur_time + realDur; auto it = _events.find(end_time); if (it != _events.end()) it->second.push_back({tmp_job_idx, job_ending}); else _events[end_time] = {{tmp_job_idx, job_ending}}; // we keep track of the started jobs started_jobs.push_back({tmp_job_idx,tmp_unit_mapping,tmp_frequency}); // Check if a starting event for the start time exists. If this is the // case, register the jobs as "starting" at the event. Otherwise, // build a new job vector for the event containing only "i". long long start_time = cur_time; it = _events.find(start_time); if (it != _events.end()) it->second.push_back({tmp_job_idx, job_starting}); else _events[start_time] = {{tmp_job_idx, job_starting}}; // update the map with the info for each job _jobs_info[tmp_job_idx].start_time = start_time; _jobs_info[tmp_job_idx].end_time = end_time; _jobs_info[tmp_job_idx].node_mapping = tmp_unit_mapping; // update cached resources capacities update_caps(tmp_job_idx, -1, tmp_unit_mapping); // update power update_power(tmp_job_idx, 1); // update waiting jobs set auto w_itr = _waiting_jobs.find(tmp_job_idx); if(w_itr != _waiting_jobs.end()) // delete ending job from waiting set _waiting_jobs.erase(w_itr); auto itr = _running_jobs.find(tmp_job_idx); // only if the job was not seen before if(itr == _running_jobs.end()) _running_jobs[tmp_job_idx] = _jobs_info[tmp_job_idx]; vector exec_nodes = tmp_unit_mapping; for(int en : exec_nodes){ if(find(_node_running_jobs[en].begin(), _node_running_jobs[en].end(), tmp_job_idx) == _node_running_jobs[en].end() ) _node_running_jobs[en].push_back(tmp_job_idx); } // update final schedule // if the job is not the final schedule yet, add it auto sched_it = _final_schedule.find(tmp_job_idx); _job_schedule tmp_jsched; tmp_jsched.start = start_time; tmp_jsched.end = end_time; tmp_jsched.mapping = tmp_unit_mapping; if (sched_it == _final_schedule.end()) _final_schedule[tmp_job_idx] = {tmp_jsched}; tmp_unit_mapping.clear(); } // notify optimizer of the newly dispatched jobs for(auto job : started_jobs){ _opt->setStartAndMapping(job.tmp_job_idx, cur_time, job.tmp_unit_mapping); _opt->setDur(job.tmp_job_idx, _jobs[job.tmp_job_idx].getEstimatedDuration()); _opt->setDur(job.tmp_job_idx, _jobs_info[job.tmp_job_idx].dur); _opt->setPower(job.tmp_job_idx, _jobs_info[job.tmp_job_idx].cur_power); _opt->setPowerPred(job.tmp_job_idx, _jobs_info[job.tmp_job_idx].power_pred); _opt->setFrequency(job.tmp_job_idx, _jobs_info[job.tmp_job_idx].frequency); } // put the remaining jobs (those not scheduled yet) in the new_ranked_jobs for(auto job_idx : jobs_to_schedule){ auto it = scheduled_jobs.find(job_idx); if(it == scheduled_jobs.end()) new_jobs_to_schedule.push_back(job_idx); } auto it = _historical_powers.find(cur_time); if(it == _historical_powers.end()) _historical_powers[cur_time] = _current_power; // update the list of ranked jobs jobs_to_schedule = new_jobs_to_schedule; iterTimer.stop(); // update job info with node mappings for(auto job_sched : _final_schedule){ int job_idx = job_sched.first; /* The 2 following assumptions strictly depend on the target * system (Eurora). They could be dropped for a more * general simulator */ // assumption 1): a job with a job unit on a 3.1GHz node is considered // a 3.1 node type even if all remaining job units executed // on 2.1GHz nodes int node_type = 0; for(int u = 0; u < _jobs[job_idx].getNumberOfNodes(); ++u) if(job_sched.second.mapping[u] >= _nodeType_threshold) node_type = 1; /* assumption 2): all job units must run on nodes of * the same type * - when a job is mapped on a node for the first time its frequency * is set to the max * - the frequency must be set only when the job is started: * if the frequency is already assigned we must not change it * (we could interfere with previous slow-downs) */ if(_jobs_info[job_idx].frequency == -1){ (node_type == 0) ? _jobs_info[job_idx].frequency = 2100 : _jobs_info[job_idx].frequency = 3400; (node_type == 0) ? _opt->setFrequency(job_idx,2100) : _opt->setFrequency(job_idx,3400); } _jobs_info[job_idx].node_type = node_type; _jobs_info[job_idx].node_mapping = job_sched.second.mapping; /* In _final_schedule there are all jobs scheduled (present and past) * Here we must control that the job whose node_type we're setting * has not already finished (if we don't check the setting operation * will automatically create a corresponding item in the * _running_jobs map) */ auto itr = _ended_jobs.find(job_idx); if(itr == _ended_jobs.end()){ // the job has NOT ended _running_jobs[job_idx].node_type = node_type; _running_jobs[job_idx].node_mapping = job_sched.second.mapping; if(_running_jobs[job_idx].frequency == -1) (node_type == 0) ? _running_jobs[job_idx].frequency = 2100 : _running_jobs[job_idx].frequency = 3400; } } /* Quite verbose print of all internal events */ //cout << "(OnlineDispatcher) Events status recap --------------" << endl; //for(auto e : _events){ // vector added_jobs; // // cout << (e.first == cur_time ? "--->" : "" ) << " Time " << e.first << // " - " << ": " ; // for(auto te: e.second){ // if(te.type != job_arriving){ // bool toMark = false; // if(e.first == cur_time) // added_jobs.push_back(te.job_ext_idx); // toMark = find(added_jobs.begin(), // added_jobs.end(), // te.job_ext_idx) != added_jobs.end(); // cout << (toMark ? "**" : "" ) << "(" << // te.job_ext_idx << "; " ; // cout << (te.type == job_starting ? "S" : "E" ) << // te.type << "), "; // } // else // cout << "(" << te.job_ext_idx << "; A" << te.type << "), "; // } // cout << endl; //} _nscheduled_jobs.push_back(sched_job_counter); _treq_sched.push_back(iterTimer.getVal() / 1000.0); } // end of the event loop /* Now we have final recap prints. * Dry-run: execution without power cap used to estimate * the maximum power consumption of a job instance (computed * using List Scheduler as optimizer). * The different output with or without dry-run is related to * my experimental setting */ /* The alternative BSLD is computed excluding outliers */ int alternative_bsld_threshold = 1000; if(!dry_run){ cout << "****" << endl; cout << "FINAL SCHEDULE " << endl; double avg_bsld_alt = 0; double avg_dur_increase = 0; for(auto job_sched : _final_schedule){ cout << job_sched.first << "\tST: " << job_sched.second.start; cout << "\tFreq: " << _jobs_info[job_sched.first].frequency; cout << "\tFinal Duration: " << _jobs_info[job_sched.first].dur; cout << "\tOriginal Duration: " << _jobs_info[job_sched.first].original_dur; avg_dur_increase += _jobs_info[job_sched.first].dur / _jobs_info[job_sched.first].original_dur; double wait_time = job_sched.second.start - _jobs_info[job_sched.first].qet; double run_time = _jobs_info[job_sched.first].end_time - _jobs_info[job_sched.first].start_time; cout << "\tWait Time: " << wait_time; double bsld = max((double)1, (wait_time + run_time) / (double) max(_bsld_threshold, (double)_jobs_info[job_sched.first].original_dur)); if(bsld < alternative_bsld_threshold) avg_bsld_alt += bsld; cout << "\tBSLD: " << bsld; cout << "\tUsed resources: "; for(int r : job_sched.second.mapping) cout << r << ";"; cout << endl; } avg_dur_increase /= _final_schedule.size(); avg_bsld_alt = avg_bsld_alt / _jobs.size(); cout << "Alternative BSLD: " << avg_bsld_alt << endl; //cout << "Avg. duration increase: " << avg_dur_increase << endl; cout << "&&" << endl; printMetrics(cout); //cout << "&&" << endl; //writeSolution_stdFormat(cout); //cout << "&&" << endl; cout << "- # Computed Schedules: " << n_scheds << endl; double avg_nsched = 0; for(int ns : _nscheduled_jobs) avg_nsched += ns; avg_nsched /= double(_nscheduled_jobs.size()); cout << "- Avg. # Jobs per schedule: " << avg_nsched << endl; double avg_treq = 0; for(double ts : _treq_sched) avg_treq += ts; avg_treq /= _treq_sched.size(); cout << "- Avg. Schedule computation time: " << avg_treq << endl; analyse_power_usage(_ref_time, last_time); } else{ double max_sysPower = get_max_power_consumption(_ref_time, last_time); cout << "Maximum power consumption: " << max_sysPower << endl; } } /* The makespan is a quite useless metric in online settings */ double getMKS(){ // Find the maximum EWT and the makespan double max_ewt = numeric_limits::min(); double mks = 0; for(auto job_sched : _final_schedule){ int idx = job_sched.first; max_ewt = (_ref_time > _jobs_info[idx].ewt ? _ref_time : _jobs_info[idx].ewt); mks = (mks > job_sched.second.end ? mks : job_sched.second.end); } mks -= _ref_time; return mks; } void printMetrics(ostream& out){ // Compute some metrics double nqt = 0; // weighted queue time double tqt = 0; // total queue time vector utl(_ndims, 0); // utilization double tbsld; // ratio between time in the system and runtime long long total_energy = 0; // the system consumption int njobs_atMaxFreq = 0; // number of jobs runnign at max freq int nslowed_jobs = 0; // number of slowed down jobs double perc_slowedJobs = 0; double avg_start_time = 0; for(auto job_sched : _final_schedule){ int idx = job_sched.first; if(idx > _jobs.size()) continue; avg_start_time += job_sched.second.start - _ref_time; // Waiting time for this job double wait_time = job_sched.second.start - _jobs_info[idx].qet; // Update total queue time tqt += wait_time; // Weight for this this job double wgt = 1.0 / _jobs_info[idx].ewt; // Update weighted queue time nqt += wgt * wait_time; // Compute the total utilization of each resource for (int d = 0; d < _ndims; ++d) utl[d] += _jobs_info[idx].tot_reqs[d] * _jobs_info[idx].dur; double run_time = _jobs_info[idx].end_time - _jobs_info[idx].start_time; if(_jobs_info[idx].dur == _jobs_info[idx].original_dur) njobs_atMaxFreq++; else{ nslowed_jobs++; } /* bsld_threshold is used to exclude too short jobs from the computation */ tbsld += max((double)1, (wait_time + run_time) / (double) max(_bsld_threshold, (double)_jobs_info[idx].original_dur)); if(_jobs_info[idx].energy != -1) total_energy += _jobs_info[idx].energy; } // Average normalized queue time double avg_nqt = nqt / _jobs.size(); avg_start_time = avg_start_time / _jobs.size(); // One more metric (utilization ratio) vector utl_ratio(_ndims, 0); for (int d = 0; d < _ndims; ++d) utl_ratio[d] = utl[d] / (_opt->getCap(d) * getMKS()) ; double avg_bsld = tbsld / _jobs.size(); // Instance descriptor (utilization in an ideal schedule) vector uis(_ndims, 0); for (auto job_sched : _final_schedule) { int idx = job_sched.first; for (int d = 0; d < _ndims; ++d) uis[d] += _jobs_info[idx].tot_reqs[d] * _jobs_info[idx].dur; } double max_uis = 0; for (int d = 0; d < _ndims; ++d){ uis[d] /= (double) _opt->getCap(d); max_uis = (max_uis > uis[d] ? max_uis : uis[d]); } for (int d = 0; d < _ndims; ++d) uis[d] /= max_uis; vector avg_util(_ndims); vector tot_util(_ndims); int n_event; for(auto event_util : _sys_util){ vector util = event_util.second; for(int d = 0; d < _ndims; ++d) tot_util[d] += util[d]; n_event++; } for(int d = 0; d < _ndims; ++d) avg_util[d] = tot_util[d] / n_event; perc_slowedJobs = (double) nslowed_jobs / _jobs.size() * 100; out << "STATS:" << endl; out << "- makespan (sec): " << getMKS() << endl; out << "- total queue time (sec): " << tqt << endl; out << "- avg. normalized queue time (#EWTs): " << avg_nqt << endl; out << "- avg. start time (s): " << avg_start_time << endl; out << "- BSLD: " << avg_bsld << endl; out << "- Slowed jobs %: " << perc_slowedJobs << endl; out << "- Total Energy: " << total_energy / 1000 << endl; out << "- utilization ratio: " << utl_ratio[0]; for (int d = 1; d < _ndims; ++d) out << " / " << utl_ratio[d]; out << endl; out << "- utilization in an ideal schedule: " << uis[0]; for (int d = 1; d < _ndims; ++d) cout << " / " << uis[d]; out << endl; out << "- avg. system utilization: " << avg_util[0]; for (int d = 1; d < _ndims; ++d) cout << " / " << avg_util[d]; out << endl; } /* Write a solution in the standard format * - print all the jobs started so far (even the completed ones) */ void writeSolution_stdFormat(ostream& out){ for(auto job_sched : _final_schedule){ int job_idx = job_sched.first; out << _jobs[job_idx].getJobId() << ";" << _jobs[job_idx].getJobName() << ";"; out << _jobs[job_idx].getUserName() << ";" << _jobs[job_idx].getQueue() << ";"; out << Util::timeToStr(_jobs[job_idx].getEnterQueueTime()) << "__"; for(int u = 0; u < _jobs[job_idx].getNumberOfNodes(); ++u){ out << job_sched.second.mapping[u] << ";"; out << _jobs_info[job_idx].reqs[u][0] << ";" << _jobs_info[job_idx].reqs[u][1] << ";"; out << _jobs_info[job_idx].reqs[u][2] << ";" << _jobs_info[job_idx].reqs[u][3]*1024; out << "#"; } out << "__" << Util::timeToStr(job_sched.second.start) << ";"; out << Util::timeToStr(job_sched.second.end) << ";"; out << _jobs[job_idx].getNumberOfNodes() << ";" << _jobs[job_idx].getNumberOfCores() << ";"; out << _jobs[job_idx].getMemory()/1024 << ";" << _jobs_info[job_idx].dur << endl; } } /* Write the dispatcher state in standard format * - do not consider finished job (at the reference time) * - consider the running jobs with the solver computed start times * - use future knowledge (text-based only) for jobs not seen yet by dispatcher */ void writeDispState_stdFormat(ostream& out, long long ref_time){ // started jobs for(auto job_sched : _final_schedule){ int job_idx = job_sched.first; // consider only running jobs if(job_sched.second.end >= ref_time){ out << _jobs[job_idx].getJobId() << ";" << _jobs[job_idx].getJobName() << ";"; out << _jobs[job_idx].getUserName() << ";" << _jobs[job_idx].getQueue() << ";"; out << Util::timeToStr(_jobs[job_idx].getEnterQueueTime()) << "__"; for(int u = 0; u < _jobs[job_idx].getNumberOfNodes(); ++u){ out << job_sched.second.mapping[u] << ";"; out << _jobs_info[job_idx].reqs[u][0] << ";" << _jobs_info[job_idx].reqs[u][1] << ";"; out << _jobs_info[job_idx].reqs[u][2] << ";" << _jobs_info[job_idx].reqs[u][3]*1024; out << "#"; } out << "__" << Util::timeToStr(job_sched.second.start) << ";"; out << Util::timeToStr(job_sched.second.end) << ";"; out << _jobs[job_idx].getNumberOfNodes() << ";" << _jobs[job_idx].getNumberOfCores() << ";"; out << _jobs[job_idx].getMemory()/1024 << ";" << Util::timeHHMMToStr(_jobs_info[job_idx].dur); out << ";NA;NA;COMPLETED" << endl; } } // future jobs // TODO: very inefficient (but actually only debug purpose) // run through all job for(int job_idx = 0; job_idx < _jobs.size(); job_idx++){ // if a job is not in the final schedule, then it has not // been scheduled yet if(_final_schedule.find(job_idx) == _final_schedule.end()){ out << _jobs[job_idx].getJobId() << ";" << _jobs[job_idx].getJobName() << ";"; out << _jobs[job_idx].getUserName() << ";" << _jobs[job_idx].getQueue() << ";"; out << Util::timeToStr(_jobs[job_idx].getEnterQueueTime()) << "__"; int nunits = _jobs[job_idx].getNumberOfNodes(); for(int u = 0; u < nunits; ++u){ // -1 for the not assigned nodes out << "-1;"; out << _jobs[job_idx].getNumberOfCores()/nunits << ";" << _jobs[job_idx].getNumberOfGPU()/nunits << ";"; out << _jobs[job_idx].getNumberOfMIC()/nunits << ";" << _jobs[job_idx].getMemory()/nunits*1024; out << "#"; } // fixed impossible value for not assingned end/start times out << "__2007-01-15 00:00:00;2007-01-15 00:00:00;"; out << _jobs[job_idx].getNumberOfNodes() << ";" << _jobs[job_idx].getNumberOfCores() << ";"; out << _jobs[job_idx].getMemory()/1024 << ";" << Util::timeHHMMToStr(_jobs_info[job_idx].dur); out << ";NA;NA;COMPLETED" << endl; } } } }; // end of OnlineDispatcher } // end of optimization_core namespace #endif Project/test_firmware/main.cpp #include #include int main([[maybe_unused]] int argc, [[maybe_unused]] char *argv[]) { SystemInit(); NVIC_PriorityGroupConfig(NVIC_PriorityGroup_4); ::testing::InitGoogleTest(&argc, argv); int result = RUN_ALL_TESTS(); std::cout << "Testing programm finished. Awaiting shutdown." << std::endl; while(true) { } return result; } #include #include #include using namespace std; /** * This file is generated by leetcode_add.py v1.0 * * 283. * Move Zeroes * * ––––––––––––––––––––––––––––– Description ––––––––––––––––––––––––––––– * * Given an integer array ‘nums’ , move all ‘0’ 's to the end of it while * maintaining the relative order of the non-zero * “Note” that you must do this in-place without making a copy of the * array. * * ––––––––––––––––––––––––––––– Constraints ––––––––––––––––––––––––––––– * * • ‘1 ≤ nums.length ≤ 10⁴’ * • ‘-2³¹ ≤ nums[i] ≤ 2³¹ - 1’ * */ struct q283 : public ::testing::Test { // Leetcode answer here class Solution { public: void moveZeroes(vector& nums) { int fillindex = -1; for (int i = 0; i < nums.size(); ++i) { if (nums[i] != 0) { nums[++fillindex] = nums[i]; } } while (fillindex < nums.size() - 1) { nums[++fillindex] = 0; } } }; class Solution *solution; }; TEST_F(q283, sample_input01) { solution = new Solution(); vector nums = {0, 1, 0, 3, 12}; vector exp = {1, 3, 12, 0, 0}; solution->moveZeroes(nums); // Assume the first argument is answer. EXPECT_EQ(nums, exp); delete solution; } TEST_F(q283, sample_input02) { solution = new Solution(); vector nums = {0}; vector exp = {0}; solution->moveZeroes(nums); // Assume the first argument is answer. EXPECT_EQ(nums, exp); delete solution; }yujinrobot/yujin_lidar_v2driver_general/yujinrobot_yrldriver/yujinrobot_yrldriver/src/test/test_yrl_library.cpp /********************************************************************* * Copyright (c) 2022, YujinRobot Corp. * * Non-monifiable freely redistributable software(FRS) * * - Redistribution. Redistribution and use in binary form, without modification, * are permitted provided that the following conditions are met: * - Redistributions must reproduce the above copyright notice and the following * disclaimer in the documentation and/or other materials provided with the distribution. * - Neither the name of YujinRobot Corporation nor the names of its suppliers may be used * to endorse or promote products derived from this software without specific prior written permission. * * 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 OFOR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. *********************************************************************/ #include #include "../../include/yujinrobot_yrldriver/yujinrobot_yrldriver.hpp" #ifdef _WIN32 bool ctrlcpressed = false; BOOL WINAPI CtrlHandler(DWORD fdwCtrlType) { switch (fdwCtrlType) { // Handle the CTRL-C signal. case CTRL_C_EVENT: //printf("Ctrl-C event\n\n"); Beep(750, 300); ctrlcpressed = true; return TRUE; // Pass other signals to the next handler. case CTRL_BREAK_EVENT: Beep(900, 200); ctrlcpressed = true; //printf("Ctrl-Break event\n\n"); return TRUE; default: return FALSE; } } int threadFucntion() { if (SetConsoleCtrlHandler(CtrlHandler, TRUE)) { printf("\nPress Ctrl + C to exit the program.\n\n"); while (1) { } } else { printf("\nERROR: Could not set control handler"); return 1; } return 0; } #endif int main( int argc, char ** argv) { #ifdef _WIN32 std::thread thread(threadFucntion); #endif std::cout << "========================================" << std::endl; std::cout << " Test YRL driver " << std::endl; std::cout << "========================================\n" << std::endl; if (argc != 2) { LOGPRINT(main, YRL_LOG_USER, ("WRONG ARGUMENT! USAGE: [./test_yrl_library] [IP_ADDRESS]\n")); return -1; } std::string ip = argv[1]; #ifdef _WIN32 WSADATA wsaData; if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) { printf("WSAStartup() error!"); } #endif //== 1. CREATE DRIVER INSTANCE =========================================== YujinRobotYrlDriver* instance = new YujinRobotYrlDriver(); //======================================================================== //== 2. SET IP =========================================================== // THIS MUST BE SET BEFOR CALLING Start(). // THIS WILL BE USED TO CONNECT LIDAR instance->SetIPAddrParam(ip); //======================================================================== //== 3. START DRIVER ===================================================== // THIS FUNCTION SHOULD BE ONLY ONCE CALLED. int ret = instance->Start(); if (ret < 0) { std::string IpAddress = instance->GetIPAddrParam(); int PortNumber = instance->GetPortNumParam (); LOGPRINT(main, YRL_LOG_USER, ("CANNOT START COMMUNICATION WITH LIDAR.\n")); LOGPRINT(main, YRL_LOG_USER, ("CONNECT TO [IP:%s PORT:%d] FAILED. CHECK YOUR NETWORK CONNECTION.\n", IpAddress.c_str(), PortNumber)); delete instance; return -1; } std::this_thread::sleep_for(std::chrono::milliseconds(3000)); instance->FWCMD(1, 14); //======================================================================== //== 4. APPLY LiDAR POSE ================================================= // APPLY POSITION AND ORIENTATION OF LiDAR // YOU CAN USE GET/SET FUNCTION OF LiDAR POSE // // GetExtrinsicTransformParam (float &x, float &y, float &z, float &rx, float &ry, float &rz) // SetExtrinsicTransformMatParam (const float x, const float y, const float z, const float rx, const float ry, const float rz) // // x, y, z ARE POSITION OF LiDAR // rx, ry, rz ARE ORIENTATION OF LiDAR float SensorX; float SensorY; float SensorZ; float SensorRX; float SensorRY; float SensorRZ; instance->GetExtrinsicTransformParam (SensorX, SensorY, SensorZ, SensorRX, SensorRY, SensorRZ); std::cout << "SensorX : " << SensorX << std::endl; std::cout << "SensorY : " << SensorY << std::endl; std::cout << "SensorZ : " << SensorZ << std::endl; std::cout << "SensorRX : " << SensorRX << std::endl; std::cout << "SensorRY : " << SensorRY << std::endl; std::cout << "SensorRZ : " << SensorRZ << std::endl; instance->SetExtrinsicTransformMatParam ( 0, 0, 1.0f, 0, 0, 0 ); //======================================================================== //== 5. OTHER GET PARAMETER FUNCTIONS ==================================== // GetIPAddrParam() // GetPortNumParam () // GetMinZParam () // GetMaxZParam () // GetMinYParam () // GetMaxYParam () // GetMinXParam () // GetMaxXParam () // GetMinRangeParam () // GetMaxRangeParam () // GetMaxVertiAngleParam () // GetMinVertiAngleParam () // GetMaxHoriAngleParam () // GetMinHoriAngleParam () // GetNoiseFilterLevelParam () std::string IpAddress = instance->GetIPAddrParam(); std::cout << "inputIpAddress : " << IpAddress << std::endl; int PortNumber = instance->GetPortNumParam (); std::cout << "PortNumber : " << PortNumber << std::endl; float MinZ = instance->GetMinZParam(); std::cout << "MinZ : " << MinZ << std::endl; float MaxZ = instance->GetMaxZParam(); std::cout << "MaxZ : " << MaxZ << std::endl; float MinY = instance->GetMinYParam(); std::cout << "MinY : " << MinY << std::endl; float MaxY = instance->GetMaxYParam(); std::cout << "MaxY : " << MaxY << std::endl; float MinX = instance->GetMinXParam(); std::cout << "MinX : " << MinX << std::endl; float MaxX = instance->GetMaxXParam(); std::cout << "MaxX : " << MaxX << std::endl; float MinRange = instance->GetMinRangeParam(); std::cout << "MinRange : " << MinRange << std::endl; float MaxRange = instance->GetMaxRangeParam(); std::cout << "MaxRange : " << MaxRange << std::endl; float MaxVertiAngle = instance->GetMaxVertiAngleParam(); std::cout << "MaxVertiAngle : " << MaxVertiAngle << std::endl; float MinVertiAngle = instance->GetMinVertiAngleParam(); std::cout << "MinVertiAngle : " << MinVertiAngle << std::endl; float MaxHoriAngle = instance->GetMaxHoriAngleParam(); std::cout << "MaxHoriAngle : " << MaxHoriAngle << std::endl; float MinHoriAngle = instance->GetMinHoriAngleParam(); std::cout << "MinHoriAngle : " << MinHoriAngle << std::endl; float NoiseFilterLevel = instance->GetNoiseFilterLevelParam(); std::cout << "NoiseFilterLevel : " << NoiseFilterLevel << std::endl; //======================================================================== //== 6. OTHER SET PARAMETER FUNCTIONS ==================================== // SetMinZParam (const float z_min) // SetMaxZParam (const float z_max) // SetMinYParam (const float y_min) // SetMaxYParam (const float y_max) // SetMinXParam (const float x_min) // SetMaxXParam (const float x_max) // SetMinRangeParam (const float range_min) // SetMaxRangeParam (const float range_max) // SetMaxVertiAngleParam (const float verti_angle_max) // SetMinVertiAngleParam (const float verti_angle_min) // SetMaxHoriAngleParam (const float hori_angle_max) // SetMinHoriAngleParam (const float hori_angle_min) // SetNoiseFilterLevelParam (const float filter_level) instance->SetMinZParam ( 0 ); instance->SetMaxZParam ( 5.0f ); instance->SetMinYParam (-35.0f); instance->SetMaxYParam ( 35.0f ); instance->SetMinXParam ( -35.0f ); instance->SetMaxXParam ( 35.0f ); instance->SetMinRangeParam ( 0 ); instance->SetMaxRangeParam ( 35.0f ); instance->SetMaxVertiAngleParam ( Degree2Radian()( +40.0 ) ); instance->SetMinVertiAngleParam ( Degree2Radian()( -40.0 ) ); instance->SetMaxHoriAngleParam ( Degree2Radian()( +180.0 ) ); instance->SetMinHoriAngleParam ( Degree2Radian()( -180.0 ) ); instance->SetNoiseFilterLevelParam (30.0); //======================================================================== //== 7. START GETTING SENSOR DATA ======================================== // YOU CAN GET SW DATA PACKET RATE THROUGH GetDPR() // void GetDPR(float &dpr) // // THERE ARE 2 OUTPUT FUNCTIONS. // YOU SHOULD USE ONLY ONE OF THEM. // // 1. int GetCartesianOutputsWithIntensity( double _SystemTime, // std::vector & _IntensityArray, // std::vector & _XCoordArray, // std::vector & _YCoordArray, // std::vector & _ZCoordArray); // // 2. int GetSphericalOutputsWithIntensity( double _SystemTime, // std::vector & _IntensityArray, // std::vector & _RangeArray, // std::vector & _HorizontalAngleArray, // std::vector & _VerticalAngleArray); // // WE WILL GET DATA DURING 20SECS. instance->FWCMD(1, 13); instance->StartStreaming(); StopWatch sw; double SystemTime; std::vector IntensityArray; std::vector XCoordArray; std::vector YCoordArray; std::vector ZCoordArray; float dpr; sw.Start(); while (sw.GetTimeElapsedInSec() < 10) { #ifdef _WIN32 if (ctrlcpressed) { ctrlcpressed = false; break; } #endif instance->GetDPR(dpr); // std::cout << "DPR: " << dpr << std::endl; int ret = instance->GetCartesianOutputsWithIntensity (SystemTime, IntensityArray, XCoordArray, YCoordArray, ZCoordArray); if (ret == -1) { std::this_thread::sleep_for(std::chrono::milliseconds(40)); continue; } // for (int i(0); i < intensity.size(); i++) // { // std::cout << "intensity : " << intensity.at(i) << ", (" << coord_x.at(i) << ", " << coord_y.at(i) << ", " << coord_z.at(i) << ")" << std::endl; // } std::this_thread::sleep_for(std::chrono::milliseconds(40)); } //======================================================================== delete instance; #ifdef _WIN32 WSACleanup(); #endif return 0; }/* * Copyright (c) 2011-2017 The University of Utah * * 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 namespace Expr{ /** * @class ExpressionRegistry * @author * @date May, 2007 * * @brief Registry for Expression objects. * * The ExpressionRegistry should not be created. Rather, it should * only be accessed through the ExpressionFactory. It is used to * hold a list of Expressions that have been registered. It does not * provide functionality to construct new expressions or return * references to existing expressions. The ExpressionFactory should * be used for that purpose. * * @todo Ensure that ExpressionRegistry can only be created by the * ExpressionFactory. Perhaps these two classes should be * combined? */ class ExpressionRegistry { public: /** * @brief Obtain the ExpressionID for the expression * with the given Tag. */ ExpressionID get_id( const Tag& label ) const; const Tag& get_label( const ExpressionID id ) const; TagList get_labels( const ExpressionID id ) const; /** @brief query if an expression with the given Tag exists in the registry. */ bool have_entry( const Tag& label ) const; /** @brief query if an expression with the given ExpressionID exists in the registry. */ bool have_entry( const ExpressionID id ) const; /** @brief Print the contents of the registry to the specified output stream. */ void dump_registry( std::ostream& os ) const; /** * @brief Add a new entry to the registry. Returns true if the * entry was successfully added. */ bool add_entry( const ExpressionID id, const Tag& label, const bool allowOverWrite=false ); /** * @brief Remove an entry from the registry. Returns true if the * entry was successfully removed. */ bool remove_entry( const ExpressionID id ); bool remove_entries( const TagList& tags ); ExpressionRegistry(){}; ///< should only be constructed by an ExpressionFactory IDLabelMap; typedef std::map LabelIDMap; IDLabelMap idLabelMap_; LabelIDMap labelIDMap_; void check_unique_entry( const ExpressionID, const std::string ) const; }; //-------------------------------------------------------------------- ExpressionID ExpressionRegistry::get_id( const Tag& label ) const { const LabelIDMap::const_iterator iid = labelIDMap_.find(label); if( iid == labelIDMap_.end() ){ std::ostringstream errmsg; errmsg << "ERROR: Could not find an ID for Expression with label: " << std::endl << " '" << label << "'" << std::endl << " You must register this Expression with the ExpressionFactory prior to using it." << std::endl << " Registry contents follow." << std::endl << std::endl; dump_registry( errmsg ); throw FactoryException( errmsg.str() ); } return iid->second; } //-------------------------------------------------------------------- const Tag& ExpressionRegistry::get_label( const ExpressionID id ) const { check_unique_entry( id, "get_label()" ); const IDLabelMap::const_iterator ilbl = idLabelMap_.find( id ); if( ilbl == idLabelMap_.end() ){ std::ostringstream errmsg; errmsg << "ERROR: Could not find a label for Expression with ID: '" << id << "'" << std::endl << " You must register this Expression with the ExpressionFactory before using it." << std::endl << " Registry contents follow." << std::endl; dump_registry( errmsg ); throw FactoryException( errmsg.str() ); } return ilbl->second; } //-------------------------------------------------------------------- TagList ExpressionRegistry::get_labels( const ExpressionID id ) const { TagList tags; std::pair iters = idLabelMap_.equal_range( id ); if( iters.first == idLabelMap_.end() ){ std::ostringstream errmsg; errmsg << "ERROR: Could not find a label for Expression with ID: '" << id << "'" << std::endl << " You must register this Expression with the ExpressionFactory before using it." << std::endl << " Registry contents follow." << std::endl; dump_registry( errmsg ); throw FactoryException( errmsg.str() ); } for( IDLabelMap::const_iterator i=iters.first; i!=iters.second; ++i ){ tags.push_back( i->second ); } return tags; } //-------------------------------------------------------------------- bool ExpressionRegistry::add_entry( const ExpressionID id, const Tag& label, const bool allowOverwrite ) { idLabelMap_.insert( std::make_pair(id,label) ); std::pair result2 = labelIDMap_.insert( std::make_pair(label,id) ); if( !result2.second ){ if( allowOverwrite ){ remove_entry( id ); return( add_entry(id,label,false) ); } else{ std::ostringstream errmsg; errmsg << "ERROR from " << __FILE__ << " : " << __LINE__ << std::endl << " Failed to add entry '" << label << "' to registry" << std::endl << " This is likely because an expression with this label already exists." << std::endl << " Set the 'allowOverwrite' flag in ExpressionRegistry::add_entry() to enable re-registration" << std::endl << " A list of registered expressions follows:" << std::endl; dump_registry( errmsg ); throw FactoryException( errmsg.str() ); } } return result2.second; } //-------------------------------------------------------------------- bool ExpressionRegistry::have_entry( const Tag& label ) const { return ( labelIDMap_.find(label)!=labelIDMap_.end() ); } //-------------------------------------------------------------------- bool ExpressionRegistry::have_entry( const ExpressionID id ) const { return ( idLabelMap_.find(id) != idLabelMap_.end() ); } //-------------------------------------------------------------------- void ExpressionRegistry::dump_registry( std::ostream& os ) const { using namespace std; os.setf(ios::left); os << "_______________________________________________________" << endl << setw(4) << left << "ID" << setw(30) << left << "Expression Name" << setw(15) << left << " State" << endl << "-------------------------------------------------------" << endl; for( IDLabelMap::const_iterator ii=idLabelMap_.begin(); ii!=idLabelMap_.end(); ++ii ){ os << setw(4) << left << ii->first << setw(30) << left << ii->second.name() << " " << ii->second.context() << endl; } os << "_______________________________________________________" << endl << endl; } //-------------------------------------------------------------------- bool ExpressionRegistry::remove_entry( const ExpressionID id ) { check_unique_entry( id, "remove_entry()" ); size_t n1=0, n2=0; std::pair iirange = idLabelMap_.equal_range(id); for( IDLabelMap::const_iterator ii=iirange.first; ii!=iirange.second; ++ii ){ n1 += labelIDMap_.erase( ii->second ); } n2 = idLabelMap_.erase( id ); return (n1>0 && n2>0); } //-------------------------------------------------------------------- bool ExpressionRegistry::remove_entries( const TagList& tags ) { size_t n1=0, n2=0; for( TagList::const_iterator it=tags.begin(); it!=tags.end(); ++it ){ LabelIDMap::iterator il = labelIDMap_.find( *it ); if( il == labelIDMap_.end() ) continue; std::pair iirange = idLabelMap_.equal_range(il->second); for( IDLabelMap::const_iterator ii=iirange.first; ii!=iirange.second; ++ii ){ n1 += labelIDMap_.erase( ii->second ); } n2 += idLabelMap_.erase( il->second ); } return (n1>0 && n2>0); } //-------------------------------------------------------------------- void ExpressionRegistry::check_unique_entry( const ExpressionID id, const std::string method ) const { if( idLabelMap_.count( id ) > 1 ){ std::pair iters = idLabelMap_.equal_range( id ); std::ostringstream msg; msg << std::endl << __FILE__ << " : " << __LINE__ << std::endl << " ExpressionRegistry::" << method << " cannot be used for an ExpressionID that has multiple" << std::endl << " fields evaluated by the expression. Use ExpressionRegistry::get_labels() instead." << std::endl << std::endl << " The following fields are evaluated by the expression with id " << id << ":" << std::endl; for( IDLabelMap::const_iterator i=iters.first; i!=iters.second; ++i ){ msg << " " << i->second << std::endl; } throw FactoryException( msg.str() ); } } //-------------------------------------------------------------------- ExpressionFactory::ExpressionFactory( const bool log ) : outputLog_( log ), registry_( std::shared_ptr(new ExpressionRegistry() ) ) { patchIDRequired_ = false; } //-------------------------------------------------------------------- void ExpressionFactory::require_patch_id_specification() { patchIDRequired_ = true; } //-------------------------------------------------------------------- void ExpressionFactory::set_ghosts( const Tag& tag, const SpatialOps::GhostData nghost ) { set_ghosts( get_id(tag), nghost ); } void ExpressionFactory::set_ghosts( const ExpressionID id, const SpatialOps::GhostData nghost ) { CallBackMap::iterator i = callBacks_.find( id ); assert( i != callBacks_.end() ); i->second->set_ghosts( nghost ); } //-------------------------------------------------------------------- ExpressionID ExpressionFactory::register_expression( ExpressionBuilder* builder, const bool allowOverWrite ) { assert( builder != NULL ); if( patchIDRequired_ && !didSetPatchID_ ){ std::ostringstream msg; msg << "Error registering expression that computes\n" << builder->get_tags() << std::endl << std::endl << "You must provide a patch ID when registering expressions. This is because\n\t" << "ExpressionFactory::require_patch_id_specification() \nwas called at some point.\n\n" << __FILE__ << " : " << __LINE__ << std::endl << std::endl; throw FactoryException( msg.str() ); } const TagList& names = builder->get_tags(); if( names.empty() ){ std::ostringstream msg; msg << "ERROR! attempted to register an expression that does not apparently compute any fields!" << std::endl << " " << __FILE__ << " : " << __LINE__ << std::endl; throw FactoryException( msg.str() ); } { bool hasInvalidTag = false; std::ostringstream msg; msg << std::endl << __FILE__ << " : " << __LINE__ << std::endl << "ERROR: attempted to register an expression computes a tag with an invalid context:" << std::endl; for( const Tag& tag: names ){ if( tag.context() == INVALID_CONTEXT ){ hasInvalidTag = true; msg << " " << tag << std::endl; } } if( hasInvalidTag ) throw FactoryException( msg.str() ); } // define the ID for this expression. ExpressionID id; if( outputLog_ ){ std::cout << "ExpressionFactory : adding "; for( TagList::const_iterator inm=names.begin(); inm!=names.end(); ++inm ){ std::cout << *inm << ", "; } std::cout << " ID: " << id << std::endl; } callBacks_.insert( std::make_pair( id, std::shared_ptr(builder) ) ); try{ if( allowOverWrite ){ registry_->remove_entries(names); for( PatchExprMap::value_type& vt: exprMap_ ){ IDExprMap& idmap = vt.second; const IDExprMap::iterator iexpr = idmap.find(id); if( iexpr != idmap.end() ){ idmap.erase(iexpr); } } } for( TagList::const_iterator inm=names.begin(); inm!=names.end(); ++inm ){ registry_->add_entry( id, *inm, allowOverWrite ); } } catch( std::exception& err ){ std::ostringstream msg; msg << err.what() << std::endl << std::endl << "ERROR from " << __FILE__ << " : " << __LINE__ << std::endl << " while trying to register expression that calculates:" << std::endl << " " << names << std::endl << " It appears that an expression to calculate one or more" << std::endl << " of these quantities has already been registered" << std::endl; throw FactoryException( msg.str() ); } return id; } //-------------------------------------------------------------------- ExpressionID ExpressionFactory::register_expression( ExpressionBuilder* builder, const bool allowOverWrite, const int fmlID ) { didSetPatchID_ = true; const ExpressionID id = register_expression( builder, allowOverWrite ); set_field_manager_list_id( id, fmlID ); didSetPatchID_ = false; return id; } //-------------------------------------------------------------------- PollerPtr ExpressionFactory::get_poller( const Tag& tag ) { for( PollerPtr p: pollerList_ ){ if( tag == p->target_tag() ) return p; } // if we get here, it wasn't found in the list, so build one. PollerPtr p( new Expr::Poller(tag) ); pollerList_.insert( p ); return p; } //-------------------------------------------------------------------- NonBlockingPollerPtr ExpressionFactory::get_nonblocking_poller( const Tag& tag ) { for( NonBlockingPollerPtr p: nonBlockingPollers_ ){ if( tag == p->target_tag() ) return p; } // if we get here, it wasn't found in the list, so build one. NonBlockingPollerPtr p( new Expr::NonBlockingPoller(tag) ); nonBlockingPollers_.insert( p ); return p; } //-------------------------------------------------------------------- void ExpressionFactory::attach_dependency_to_expression( const Tag& srcTermTag, const Tag& targetTag, const SourceExprOp op ) { if( outputLog_ ){ std::cout << "Making '" << srcTermTag << "' a dependent of '" << targetTag << "'\n"; } const ExpressionID targetID = registry_->get_id(targetTag); const TagList& targNames = registry_->get_labels( targetID ); const TagList::const_iterator itarg = std::find( targNames.begin(), targNames.end(), targetTag ); const int ixtarg = itarg - targNames.begin(); DepInfo info; info.srcTag = srcTermTag; info.op = op; info.targFieldIndex = ixtarg; idSetMap_[ targetID ].insert( info ); } //-------------------------------------------------------------------- void ExpressionFactory::attach_modifier_expression( const Tag& modifierTag, const Tag& targetTag, const int patchID, const bool allowOverWrite ) { /* * Disallow a modifier from being attached to multiple targets. This is for * several reasons: * - The modifiers will only be associated with fields from one of the targets. * - This would not be thread safe, since it is possible that multiple targets * would be executing the same modifier simultaneously. Recall that modifiers * are not seen by the scheduler. */ for( ModifierMap::value_type& vt: modifiers_ ){ const TagList& modTags = vt.second[patchID]; for( const Tag& tag: modTags ){ if( modifierTag == tag && vt.first != targetTag ){ std::ostringstream msg; msg << "\n" __FILE__ << " : " << __LINE__ << "\nERROR: modifiers may not be shared among expressions.\n" << "\tTried to attach modifier " << modifierTag << " to target " << targetTag << "\n" << "\tbut this was already attached to target " << vt.first << "\n"; throw std::invalid_argument( msg.str() ); } } } ModifierMap::iterator imod = modifiers_.find( targetTag ); if( imod == modifiers_.end() ){ TagList tags; IDTagListMap idmap; imod = modifiers_.insert( make_pair(targetTag,idmap) ).first; } if( outputLog_ ){ std::cout << "attaching modifier expression " << modifierTag << " to " << targetTag << " on patch " << patchID << std::endl; } IDTagListMap& idmap = imod->second; TagList& tl = idmap[patchID]; TagList::iterator itl = std::find( tl.begin(), tl.end(), modifierTag ); if( itl != tl.end() ){ // we found a duplicate if( allowOverWrite ){ *itl = modifierTag; return; } else{ std::ostringstream msg; msg << std::endl << __FILE__ << " : " << __LINE__ << std::endl << "ERROR: a duplicate modifier:" << std::endl << " " << modifierTag << std::endl << "was added to target:" << std::endl << " " << targetTag << std::endl << "but overwriting was forbidden." << std::endl; throw FactoryException( msg.str() ); } } tl.push_back( modifierTag ); } //-------------------------------------------------------------------- void ExpressionFactory::cleave_from_parents( const ExpressionID id ) { if( !query_expression(id) ){ std::ostringstream msg; msg << std::endl << __FILE__ << " : " << __LINE__ << std::endl << std::endl << " from ExpressionFactory::cleave_from_parents( id )" << std::endl << " ERROR: no expression exists for expression with id " << id << std::endl << std::endl; throw FactoryException( msg.str() ); } cleaveFromParents_.insert( id ); } //-------------------------------------------------------------------- void ExpressionFactory::cleave_from_children( const ExpressionID id ) { if( !query_expression(id) ){ std::ostringstream msg; msg << std::endl << __FILE__ << " : " << __LINE__ << std::endl << std::endl << " from ExpressionFactory::cleave_from_children( id )" << std::endl << " ERROR: no expression exists for expression with id " << id << std::endl << std::endl; throw FactoryException( msg.str() ); } cleaveFromChildren_.insert( id ); } //-------------------------------------------------------------------- bool ExpressionFactory::query_expression( const ExpressionID id ) const { return (callBacks_.find(id) != callBacks_.end()); } //-------------------------------------------------------------------- bool ExpressionFactory::remove_expression( const ExpressionID id ) { bool erased = false; // remove the callback entry CallBackMap::iterator icb = callBacks_.find( id ); if( icb != callBacks_.end() ){ callBacks_.erase(icb); erased = true; } // remove the id-expression map entry for( PatchExprMap::iterator ip=exprMap_.begin(); ip!=exprMap_.end(); ++ip ){ IDExprMap& idmap=ip->second; IDExprMap::iterator iimp = idmap.find(id); if( iimp!=idmap.end() ){ idmap.erase(iimp); } } erased = registry_->remove_entry(id); return erased; } //-------------------------------------------------------------------- ExpressionBase& ExpressionFactory::retrieve_expression( const Tag& tag, const int patchID, const bool mustExist ) { return retrieve_expression( get_id(tag), patchID, mustExist ); } ExpressionBase& ExpressionFactory::retrieve_expression( const ExpressionID id, const int patchID, const bool mustExist ) { return retrieve_internal(id,patchID,mustExist,false); } ExpressionBase& ExpressionFactory::retrieve_modifier_expression( const Tag& tag, const int patchID, const bool mustExist ) { return retrieve_internal(get_id(tag),patchID,mustExist,true); } ExpressionBase& ExpressionFactory::retrieve_internal( const ExpressionID id, const int patchID, const bool mustExist, const bool isModifier ) { ExprPtr expr; if( outputLog_ ){ std::cout << "retrieving expression for: " << get_labels(id) << " on patch " << patchID << std::endl; } // do we already have one built? PatchExprMap::iterator ipm = exprMap_.find( patchID ); if( ipm == exprMap_.end() ){ ipm = exprMap_.insert( std::make_pair( patchID, IDExprMap() ) ).first; } IDExprMap& idmap = ipm->second; const IDExprMap::iterator iexpr = idmap.find(id); if( iexpr != idmap.end() ){ // an expression exists. expr = iexpr->second; } else{ // creating a new expression if( mustExist ){ std::ostringstream msg; msg << std::endl << __FILE__ << " : " << __LINE__ << std::endl << std::endl << "ERROR: no expression exists for expression with id " << id << " and label " << registry_->get_labels(id)[0] << std::endl << " and creation of a new expression was forbidden.\n\n" << "Registered expressions:\n"; dump_expressions( msg ); throw FactoryException( msg.str() ); } // need to build a new one... CallBackMap::iterator ifcn = callBacks_.find( id ); if( ifcn == callBacks_.end() ){ std::ostringstream errmsg; errmsg << "ERROR: No create function for expression with ID:" << id << " and label " << registry_->get_labels(id)[0] << " has been registered!" << std::endl; throw FactoryException( errmsg.str() ); } if( outputLog_ ){ std::cout << " building expression " << get_labels(id) << std::endl; } // build the function and set the fields that it computes. ExprBuilderPtr builder = ifcn->second; expr.reset( builder->build() ); //_______________________________________________________________ // now that we have the expression built, add it to the map: idmap.insert( std::make_pair( id, expr ) ); //_______________________________________________________________ // set the field manager list if relevant IDFMLMap::const_iterator ifml = idFMLMap_.find(id); if( ifml != idFMLMap_.end() ){ expr->set_field_manager_list_id( ifml->second ); } if( !isModifier ){ // Tags on modifiers are only used to identify the expression, not to // associate it with a field. Therefore, we only set tags on expressions // that are not modifiers. expr->set_computed_tags( builder->get_tags(), builder->get_ghosts() ); } } // create new expression //_______________________________________________________________ // cleave as necessary if( cleaveFromParents_.find(id) != cleaveFromParents_.end() ) expr->cleave_from_parents(true); if( cleaveFromChildren_.find(id) != cleaveFromChildren_.end() ) expr->cleave_from_children(true); //_______________________________________________________________ // Handle modifier expressions. These are special. Also, a modifier // cannot have a modifier attached to it. So we only look to attach // modifiers to expressions that are not modifiers if( !isModifier ){ // Attach any relevant modifiers to this expression, looking at each of its // computed tags to see if a modifier is associated with any one of them. for( const Tag& comptag: expr->get_tags() ){ // Modifier expressions are only allowed on non-modifier expressions; // hence this if statement. ModifierMap::const_iterator imm = modifiers_.find( comptag ); if( imm != modifiers_.end() ){ const IDTagListMap& idtl = imm->second; TagList modTags; // all of the modifiers that are relevant to this expression { // look for a modifier on this patch: const IDTagListMap::const_iterator ii = idtl.find(patchID); if( ii != idtl.end() ) modTags = ii->second; // check to see if there are any that were wanted on all patches: const IDTagListMap::const_iterator iiall = idtl.find(ALL_PATCHES); if( iiall != idtl.end() ){ const TagList& tl = iiall->second; modTags.insert( modTags.begin(), tl.begin(), tl.end() ); } } // if we have a modifier, plug it in if( !modTags.empty() ){ for( const Tag& tag: modTags ){ if( outputLog_ ){ std::cout << " attaching modifier " << tag << " to " << comptag << ", " << imm->first << " for patch " << patchID << std::endl; } ExpressionBase& modifier = retrieve_internal( get_id(tag), patchID, false, true ); modifier.set_computed_tags( tag_list(imm->first), expr->ghosts() ); // modifier has same ghosts as the target if( modifier.field_type_name() != expr->field_type_name() ){ std::ostringstream msg; msg << __FILE__ << " : " << __LINE__ << std::endl << "ERROR: modifier expression: " << modifier.get_tags()[0] << std::endl << " has a different field type than the target expression: " << comptag << std::endl; throw FactoryException( msg.str() ); } if( expr->is_gpu_runnable() ){ // Non-Modifier Expression if( !modifier.is_gpu_runnable() ){ // Modifier Expression expr->set_gpu_runnable(false); if( outputLog_ ){ std::cout << "Warning: Modifier Expression " << tag << " attached to" << std::endl << " Expression: " << comptag << " is not GPU runnable" << std::endl << " Expression: " << comptag << " has been modified to CPU runnable" << std::endl << " to comply with Modifier Expression tag." << std::endl; } } } else{ if( modifier.is_gpu_runnable() ){ modifier.set_gpu_runnable(false); if( outputLog_ ){ std::cout << "Warning: Modifier Expression " << tag << " is GPU runnable\n" << " but the expression it is attached to " << comptag << " is not GPU runnable. The modifier has been changed to CPU runnable\n"; } } } expr->add_modifier( &modifier, tag ); } } } } // BOOST_FOREACH } // modifier // if any source expressions were attached, inform this expression. IDSetMap::const_iterator ids = idSetMap_.find( id ); if( ids!=idSetMap_.end() ){ const IDSet& idset = ids->second; for( const DepInfo& depInfo: idset ){ ExpressionBase& childExpr = retrieve_expression( depInfo.srcTag, patchID ); if( childExpr.field_type_name() != expr->field_type_name() ){ std::ostringstream msg; msg << __FILE__ << " : " << __LINE__ << std::endl << "ERROR: source expression: " << childExpr.get_tags()[0] << std::endl << " has a different field type than the target expression: " << expr->get_tags()[0] << std::endl; throw FactoryException( msg.str() ); } if( expr->is_gpu_runnable() ){ // Target Expression if( !childExpr.is_gpu_runnable() ){ // Source Expression expr->set_gpu_runnable(false); if( outputLog_ ){ std::cout << "Warning - Source Expression :" << childExpr.get_tags()[0] << "attached to" << std::endl << "Target Expression :" << expr->get_tags()[0] << "is not GPU runnable" << std::endl << "Target Expression :" << expr->get_tags()[0] << "tag has been modified to CPU runnable" << std::endl << "to comply with Source Expression tag." << std::endl; } } } else if( childExpr.is_gpu_runnable() ){ childExpr.set_gpu_runnable(false); if( outputLog_ ){ std::cout << "Warning - Source Expression :" << childExpr.get_tags()[0] << "attached to" << std::endl << "Target Expression :" << expr->get_tags()[0] << "is GPU runnable" << std::endl << "Source Expression :" << childExpr.get_tags()[0] << "tag has been modified to CPU runnable" << std::endl << "to comply with Target Expression tag." << std::endl; } } expr->attach_source_expression( &childExpr, depInfo.op, depInfo.targFieldIndex, depInfo.src_field_index( *this ) ); } // loop over source expressions } // if sources are found return *expr; } //-------------------------------------------------------------------- void ExpressionFactory::dump_expressions( std::ostream& os ) const { registry_->dump_registry(os); } const Tag& ExpressionFactory::get_label( const ExpressionID id ) const { return registry_->get_label(id); } TagList ExpressionFactory::get_labels( const ExpressionID id ) const { return registry_->get_labels(id); } ExpressionID ExpressionFactory::get_id( const Tag& tag ) const { return registry_->get_id(tag); // jcs don't we need the patch ID also? } bool ExpressionFactory::have_entry( const Tag& tag ) const { return registry_->have_entry(tag); } //-------------------------------------------------------------------- std::pair ExpressionFactory::get_associated_fml_id( const int patchID, const Tag& tag ) const { const IDFMLMap::const_iterator i = idFMLMap_.find( get_id(tag) ); if( i == idFMLMap_.end() ) return std::make_pair( false, DEFAULT_FML_ID ); return std::make_pair( true, i->second ); } //-------------------------------------------------------------------- void ExpressionFactory::set_field_manager_list_id( const ExpressionID id, const int listID ) { idFMLMap_[id] = listID; } //-------------------------------------------------------------------- int ExpressionFactory::DepInfo::src_field_index( const ExpressionFactory& factory ) const { const ExpressionID srcID = factory.get_id( srcTag ); const TagList& srcNames = factory.get_labels(srcID); const TagList::const_iterator isrc = std::find( srcNames.begin(), srcNames.end(), srcTag ); return isrc - srcNames.begin(); } //-------------------------------------------------------------------- } // namespace Expr tools/AssimpImporter/src/AssimpAnimationImporter.cpp //============================================================================ // Name : AssimpAnimationImporter.h // Author : // Version : // Copyright : ;) // Description : Loads model formats based on Assimp //============================================================================ #include "AssimpAnimationImporter.h" namespace p3d { AssimpAnimationImporter::AssimpAnimationImporter() {} AssimpAnimationImporter::~AssimpAnimationImporter() {} bool AssimpAnimationImporter::Load(const std::string& Filename) { return Load(Filename, -1, -1); } bool AssimpAnimationImporter::Load(const std::string& Filename, const int32 init, const int32 end, const std::string &AnimationName) { // Assimp Importer Assimp::Importer Importer; assimp_model = Importer.ReadFile(Filename.c_str(), aiProcessPreset_TargetRealtime_Fast | aiProcess_OptimizeMeshes | aiProcess_JoinIdenticalVertices | aiProcess_LimitBoneWeights | aiProcess_FlipUVs | aiProcess_CalcTangentSpace); if (!assimp_model) { echo("Failed To Import Model: " + std::string(Filename)); return false; } else { int32 positionsInit = init; int32 scalesInit = init; int32 rotationsInit = init; int32 positionsEnd = end; int32 scalesEnd = end; int32 rotationsEnd = end; int32 positionsCount = -1; int32 rotationsCount = -1; int32 scalesCount = -1; f32 positionsTime = 0.f; f32 positionsTimeOffset = 0.f; f32 rotationsTime = 0.f; f32 rotationsTimeOffset = 0.f; f32 scalesTime = 0.f; f32 scalesTimeOffset = 0.f; f32 positionsTimeOffsetEnd = 0.f; f32 rotationsTimeOffsetEnd = 0.f; f32 scalesTimeOffsetEnd = 0.f; // Get Animations if (assimp_model->HasAnimations() == true) { for (uint32 i = 0; i < assimp_model->mNumAnimations; i++) { Animation animation; // Set Animation Name if (positionsInit > -1 && positionsEnd > -1 && AnimationName.size() > 0) animation.AnimationName = AnimationName; else animation.AnimationName = assimp_model->mAnimations[i]->mName.data; // Set Animation Duration animation.Duration = (f32)assimp_model->mAnimations[i]->mDuration; // Set Ticks Per Second animation.TicksPerSecond = (f32)assimp_model->mAnimations[i]->mTicksPerSecond; // allocate std::vector space animation.Channels.reserve(assimp_model->mAnimations[i]->mNumChannels); for (uint32 k = 0; k < assimp_model->mAnimations[i]->mNumChannels; k++) { Channel channel; // Set Channel Node Name channel.NodeName = assimp_model->mAnimations[i]->mChannels[k]->mNodeName.data; // allocate space channel.positions.reserve(assimp_model->mAnimations[i]->mChannels[k]->mNumPositionKeys); channel.rotations.reserve(assimp_model->mAnimations[i]->mChannels[k]->mNumRotationKeys); channel.scales.reserve(assimp_model->mAnimations[i]->mChannels[k]->mNumScalingKeys); // Get Positions, Rotations and Scales // Positions if (positionsInit > -1 && positionsEnd > -1) { positionsCount = -1; positionsTimeOffset = 0.f; } for (uint32 l = 0; l < assimp_model->mAnimations[i]->mChannels[k]->mNumPositionKeys; l++) { if (positionsInit > -1 && positionsEnd > -1) { positionsCount++; if (positionsCount >= positionsInit && positionsCount < positionsEnd) { Vec3 Pos; Pos.x = assimp_model->mAnimations[i]->mChannels[k]->mPositionKeys[l].mValue.x; Pos.y = assimp_model->mAnimations[i]->mChannels[k]->mPositionKeys[l].mValue.y; Pos.z = assimp_model->mAnimations[i]->mChannels[k]->mPositionKeys[l].mValue.z; positionsTime = (f32)assimp_model->mAnimations[i]->mChannels[k]->mPositionKeys[l].mTime - positionsTimeOffset; channel.positions.push_back(PositionData(positionsTime, Pos)); } else { if (positionsCount < positionsInit) positionsTimeOffset = (f32)assimp_model->mAnimations[i]->mChannels[k]->mPositionKeys[l].mTime; else if (positionsCount >= positionsEnd) positionsTimeOffsetEnd = (f32)assimp_model->mAnimations[i]->mChannels[k]->mPositionKeys[l].mTime - positionsTimeOffset; } } else { Vec3 Pos; Pos.x = assimp_model->mAnimations[i]->mChannels[k]->mPositionKeys[l].mValue.x; Pos.y = assimp_model->mAnimations[i]->mChannels[k]->mPositionKeys[l].mValue.y; Pos.z = assimp_model->mAnimations[i]->mChannels[k]->mPositionKeys[l].mValue.z; channel.positions.push_back(PositionData((f32)assimp_model->mAnimations[i]->mChannels[k]->mPositionKeys[l].mTime, Pos)); } } // Rotations if (rotationsInit > -1 && rotationsEnd > -1) { rotationsCount = -1; rotationsTimeOffset = 0.f; } for (uint32 l = 0; l < assimp_model->mAnimations[i]->mChannels[k]->mNumRotationKeys; l++) { if (rotationsInit > -1 && rotationsEnd > -1) { rotationsCount++; if (rotationsCount >= rotationsInit && rotationsCount < rotationsEnd) { Quaternion Rot; Rot.w = assimp_model->mAnimations[i]->mChannels[k]->mRotationKeys[l].mValue.w; Rot.x = assimp_model->mAnimations[i]->mChannels[k]->mRotationKeys[l].mValue.x; Rot.y = assimp_model->mAnimations[i]->mChannels[k]->mRotationKeys[l].mValue.y; Rot.z = assimp_model->mAnimations[i]->mChannels[k]->mRotationKeys[l].mValue.z; rotationsTime = (f32)assimp_model->mAnimations[i]->mChannels[k]->mRotationKeys[l].mTime - rotationsTimeOffset; channel.rotations.push_back(RotationData(rotationsTime, Rot)); } else { if (rotationsCount < rotationsInit) rotationsTimeOffset = (f32)assimp_model->mAnimations[i]->mChannels[k]->mRotationKeys[l].mTime; else if (rotationsCount >= rotationsEnd) rotationsTimeOffsetEnd = (f32)assimp_model->mAnimations[i]->mChannels[k]->mRotationKeys[l].mTime - rotationsTimeOffset; } } else { Quaternion Rot; Rot.w = assimp_model->mAnimations[i]->mChannels[k]->mRotationKeys[l].mValue.w; Rot.x = assimp_model->mAnimations[i]->mChannels[k]->mRotationKeys[l].mValue.x; Rot.y = assimp_model->mAnimations[i]->mChannels[k]->mRotationKeys[l].mValue.y; Rot.z = assimp_model->mAnimations[i]->mChannels[k]->mRotationKeys[l].mValue.z; channel.rotations.push_back(RotationData((f32)assimp_model->mAnimations[i]->mChannels[k]->mRotationKeys[l].mTime, Rot)); } } // Scales if (scalesInit > -1 && scalesEnd > -1) { scalesCount = -1; scalesTimeOffset = 0.f; } for (uint32 l = 0; l < assimp_model->mAnimations[i]->mChannels[k]->mNumScalingKeys; l++) { if (scalesInit > -1 && scalesEnd > -1) { scalesCount++; if (scalesCount >= scalesInit && scalesCount < scalesEnd) { Vec3 Scale; Scale.x = assimp_model->mAnimations[i]->mChannels[k]->mScalingKeys[l].mValue.x; Scale.y = assimp_model->mAnimations[i]->mChannels[k]->mScalingKeys[l].mValue.y; Scale.z = assimp_model->mAnimations[i]->mChannels[k]->mScalingKeys[l].mValue.z; scalesTime = (f32)assimp_model->mAnimations[i]->mChannels[k]->mScalingKeys[l].mTime - scalesTimeOffset; channel.scales.push_back(ScalingData(scalesTime, Scale)); } else { if (scalesCount < scalesInit) scalesTimeOffset = (f32)assimp_model->mAnimations[i]->mChannels[k]->mScalingKeys[l].mTime; else if (scalesCount >= scalesEnd) scalesTimeOffsetEnd = (f32)assimp_model->mAnimations[i]->mChannels[k]->mScalingKeys[l].mTime - scalesTimeOffset; } } else { Vec3 Scale; Scale.x = assimp_model->mAnimations[i]->mChannels[k]->mScalingKeys[l].mValue.x; Scale.y = assimp_model->mAnimations[i]->mChannels[k]->mScalingKeys[l].mValue.y; Scale.z = assimp_model->mAnimations[i]->mChannels[k]->mScalingKeys[l].mValue.z; channel.scales.push_back(ScalingData((f32)assimp_model->mAnimations[i]->mChannels[k]->mScalingKeys[l].mTime, Scale)); } } // add channel to animation animation.Channels.push_back(channel); } if (positionsInit > -1 && positionsEnd > -1) animation.Duration = animation.Duration - (positionsTimeOffset + positionsTimeOffsetEnd) + positionsTime; // add animation animations.push_back(animation); } } else { echo("No Animations Found in Model: " + std::string(Filename)); } return true; } } bool AssimpAnimationImporter::ConvertToPyrosFormat(const std::string &Filename) { BinaryFile* bin = new BinaryFile(); if (bin->Open(Filename.c_str(), 'w')) { int32 animationsSize = animations.size(); bin->Write(&animationsSize, sizeof(int32)); for (int32 i = 0; i < animationsSize; i++) { // Animation Name int32 nameSize = animations[i].AnimationName.size(); bin->Write(&nameSize, sizeof(int32)); bin->Write(animations[i].AnimationName.c_str(), sizeof(char)*nameSize); // Channels int32 channelsSize = animations[i].Channels.size(); bin->Write(&channelsSize, sizeof(int32)); // Duration bin->Write(&animations[i].Duration, sizeof(f32)); // Ticks Per Second bin->Write(&animations[i].TicksPerSecond, sizeof(f32)); for (int32 k = 0; k < channelsSize; k++) { // Node Name int32 channelNameSize = animations[i].Channels[k].NodeName.size(); bin->Write(&channelNameSize, sizeof(int32)); bin->Write(animations[i].Channels[k].NodeName.c_str(), sizeof(char)*channelNameSize); // Positions int32 positionSize = animations[i].Channels[k].positions.size(); bin->Write(&positionSize, sizeof(int32)); bin->Write(&animations[i].Channels[k].positions[0], sizeof(PositionData)*positionSize); // Rotations int32 rotationSize = animations[i].Channels[k].rotations.size(); bin->Write(&rotationSize, sizeof(int32)); bin->Write(&animations[i].Channels[k].rotations[0], sizeof(RotationData)*rotationSize); // Scales int32 scalingSize = animations[i].Channels[k].scales.size(); bin->Write(&scalingSize, sizeof(int32)); bin->Write(&animations[i].Channels[k].scales[0], sizeof(ScalingData)*scalingSize); } } bin->Close(); delete bin; return true; } else return false; } }lmrodriguezr/nonpareilnonpareil.cpp10-100 // nonpareil - Calculation of nonpareil curves // @author // @author . // @license Artistic-2.0 #include #include #include "enveomics/universal.h" #include "enveomics/multinode.h" #include "enveomics/sequence.h" #include "enveomics/nonpareil_mating.h" #include "enveomics/nonpareil_sampling.h" #include "enveomics/References.h" #include "enveomics/KmerCounter.h" #include #define LARGEST_PATH 4096 #define NP_VERSION 3.304 using namespace std; int processID; int processes; void help(const char *msg){ if(processID==0 && msg!=NULL && strlen(msg) != 0) cerr < : Path to the (input) file containing the sequences" < : Nonpareil algorithm, 'kmer' or 'alignment' accepted" < : Path to the prefix for all the output files" << endl <<" -f : The format of the sequence. Can be 'fasta' or fastq'"< : Maximum number of reads to use as query." < : kmer length. By default: 24" < : Number of sub-samples to generate per point." < : Minimum overlapping percentage of the aligned region" < : Maximum RAM usage in Mib. Ideally this value should" < : Number of threads. By default: 2" < : Verbosity level. By default 7" <1)) help("Bad argument for -m option, accepted range: [0, 1]"); if((max<0) | (max>1)) help("Bad argument for -M option, accepted range: [0, 1]"); if((itv<=0) | (itv>1)) help("Bad argument for -i option, accepted range: (0, 1]"); if((ovl<=0.0) | (ovl>1.0)) help("Bad argument for -L option, accepted range: (0, 100]"); if(thr<=0) help("Bad argumement for -t option, accepted: positive non-zero integers"); if(n<=0) help("Bad argument for -n option, accepted: positive non-zero integers"); if(ram<=0) help("Bad argument for -R option, accepted: positive non-zero integers"); if(thr<=0) help("Bad argument for -t option, accepted: positive non-zero integers"); if((min_sim<=0) | (min_sim>1)) help("Bad argument for -S option, accepted range: (0, 1]"); if((qry_portion<0) | (qry_portion>1)) help("Bad argument for -x option, accepted range: (0, 1]"); if((divide<0) | (divide>=1)) help("Bad argument for -d option, accepted range: (0, 1)"); if((k < 1) | (k > 32)) help("Bad argument for -k option, accepted range: [1, 32]"); char alldataTmp[LARGEST_PATH], outfileTmp[LARGEST_PATH], cntfileTmp[LARGEST_PATH]; if(baseout && (strlen(baseout)>0)){ if(!alldata || (strlen(alldata)<=0)){ sprintf(alldataTmp, "%s.npa", baseout); alldata=alldataTmp; } if(!cntfile || (strlen(cntfile)<=0)){ sprintf(cntfileTmp, "%s.npc", baseout); cntfile=cntfileTmp; } if(!outfile || (strcmp(outfile, "-")==0)){ sprintf(outfileTmp, "%s.npo", baseout); outfile=outfileTmp; } if(processID==0 && !log_is_open()) { char logfile[LARGEST_PATH]; sprintf(logfile, "%s.npl", baseout); open_log(logfile); } } //file checking if(strcmp(nonpareiltype,"kmer")==0){ int count = 0; int limit = 10 * hX; //metagenome should have 10 times more than query reads Sequence test_temp; if(strcmp(format,"fasta")==0){ ifstream testifs((string(file))); FastaReader testfastaReader(testifs); while(testfastaReader.readNextSeq(test_temp) != (size_t)(-1)) { count++; if (count > limit) break; } if (count < limit) error( "Sequence file should have at least 10X the number of query reads"); }else if(strcmp(format,"fastq")==0){ ifstream testifs((string(file))); FastqReader testfastqReader(testifs); while(testfastqReader.readNextSeq(test_temp) != (size_t)(-1)) { count++; if (count > limit) break; } if (count < limit) error( "Sequence file should have at least 10X the number of query reads"); } } if(alldata && (strlen(alldata)>0)) remove(alldata); if(cntfile && (strlen(cntfile)>0)) remove(cntfile); if(outfile && (strlen(outfile)>0) & (strcmp(outfile,"-")!=0)) remove(outfile); if(strcmp(nonpareiltype,"kmer")==0) { if(alt_query) { if(strcmp(format,"fasta")==0) { say("1ss$","WARNING: The kmer kernel implements an error correction ", "function only compatible with FastQ"); ifstream qifs((string(qfile))); say("1ss$","reading query", file); FastaReader qfastaReader(qifs); References references = References(qfastaReader, k, alt_query); say("1s$","Started counting"); ifstream ifs((string(file))); FastaReader fastaReader(ifs); KmerCounter counter = KmerCounter(references, fastaReader, string(cntfile)); mates = new int[counter.getTotalSeqs()]; counter.getCounts(mates); avg_seq_len = counter.getAvgLen(); total_seqs = counter.getTotalSeqs(); qry_seqs_no = counter.getTotalQSeqs(); adj_avg_seq_len = avg_seq_len - k + 1; say("1sus$", "Read file with ", total_seqs, " sequences"); say("1sfs$", "Average read length is ", avg_seq_len, "bp"); goto restart_samples; } }else{ if(strcmp(format,"fastq")==0) { ifstream ifs((string(file))); say("1ss$","reading ", file); FastqReader fastqReader(ifs); say("1sus$","Picking ", hX, " random sequences"); References references = References(fastqReader, hX, k); say("1s$","Started counting"); KmerCounter counter = KmerCounter(references, fastqReader, string(cntfile)); mates = new int[hX]; counter.getCounts(mates); avg_seq_len = counter.getAvgLen(); total_seqs = counter.getTotalSeqs(); qry_seqs_no = counter.getTotalQSeqs(); adj_avg_seq_len = avg_seq_len - k + 1; say("1sus$", "Read file with ", total_seqs, " sequences"); say("1sfs$", "Average read length is ", avg_seq_len, "bp"); goto restart_samples; }else if(strcmp(format,"fasta")==0) { say("1ss$","WARNING: The kmer kernel implements an error correction ", "function only compatible with FastQ"); ifstream ifs((string(file))); say("1ss$","reading ", file); FastaReader fastaReader(ifs); say("1sus$","Picking ", hX, " random sequences"); References references = References(fastaReader, hX, k); say("1s$","Started counting"); KmerCounter counter = KmerCounter(references, fastaReader, string(cntfile)); mates = new int[hX]; counter.getCounts(mates); avg_seq_len = counter.getAvgLen(); total_seqs = counter.getTotalSeqs(); qry_seqs_no = counter.getTotalQSeqs(); adj_avg_seq_len = avg_seq_len - k + 1; say("1sus$", "Read file with ", total_seqs, " sequences"); say("1sfs$", "Average read length is ", avg_seq_len, "bp"); goto restart_samples; } } } srand(rseed+processID); say("9si$", "Hello from worker ", processID); barrier_multinode(); // Parse file if(processID==0) say("1s$", "Counting sequences"); namFile = (char *)malloc(LARGEST_PATH * (sizeof *namFile)); seqFile = (char *)malloc(LARGEST_PATH * (sizeof *seqFile)); if(processID==0){ total_seqs = build_index(file, format, namFile, seqFile, largest_seq, avg_seq_len); if(largest_seq<1) error("Empty sequences or internal error. Largest sequence: ", largest_seq); say("2sss$", "The file ", seqFile, " was just created"); say("4sis$", "Longest sequence has ", largest_seq, " characters"); say("4sfs$", "Average read length is ", avg_seq_len, " bp"); if(total_seqs==0) error("No input sequences. Before re-running please delete the file ", seqFile); say("1sus$", "Reading file with ", total_seqs, " sequences"); say("9s$", "Broadcasting"); } total_seqs = broadcast_int(total_seqs); namFile = broadcast_char(namFile, LARGEST_PATH); seqFile = broadcast_char(seqFile, LARGEST_PATH); largest_seq = broadcast_int(largest_seq); avg_seq_len = broadcast_double(avg_seq_len); barrier_multinode(); // Parse Q-File qNamFile = (char *)malloc(LARGEST_PATH * (sizeof *qNamFile)); qSeqFile = (char *)malloc(LARGEST_PATH * (sizeof *qSeqFile)); if(processID==0){ say("1s$", "Counting query sequences"); if(alt_query){ q_total_seqs = build_index(qfile, format, qNamFile, qSeqFile, q_largest_seq, q_avg_seq_len); if(q_largest_seq<1) error("No input sequences or internal error. Largest sequence: ", q_largest_seq); say("2sss$", "The file ", qSeqFile, " was just created"); say("4sis$", "Longest query sequence has ", q_largest_seq, " characters"); say("4sfs$", "Average query read length is ", q_avg_seq_len, " bp"); if(q_total_seqs==0) error("No input sequences. Before re-running please delete the file ", qSeqFile); say("1sus$", "Reading query file with ", q_total_seqs, " sequences"); }else{ q_total_seqs=0; qNamFile=(char *)""; qSeqFile=(char *)""; q_largest_seq = 0; q_avg_seq_len = 0.0; } say("9s$", "Broadcasting"); } q_total_seqs = broadcast_int(q_total_seqs); qNamFile = broadcast_char(qNamFile, LARGEST_PATH); qSeqFile = broadcast_char(qSeqFile, LARGEST_PATH); q_largest_seq = broadcast_int(q_largest_seq); q_avg_seq_len = broadcast_double(q_avg_seq_len); barrier_multinode(); restart_vars: say("9sis$", "Worker ", processID, " @start_vars."); if(processID==0){ // Re-wire query portion if(qry_portion!=0) hX = (size_t)total_seqs*qry_portion; qry_portion = (double)hX/(alt_query ? q_total_seqs : total_seqs); // Prepare memory arguments if((size_t)ram > UINT_MAX/1024) error("The memory to allocate is too large, reduce -R", ram); ram_Kb = ram*1024; required_ram_Kb = 2*(int)hX*sizeof(int)*thr/1024 + 2048; if(ram_Kb < required_ram_Kb) error("The amount of memory allowed is too small, increase -R to over ", (double)required_ram_Kb/1024); lines_in_ram = (ram_Kb - required_ram_Kb)/(largest_seq + 3); if(lines_in_ram > UINT_MAX/1024){ say("1sfs$", "WARNING: Unable to represent RAM in bits, lowering to ", (double)UINT_MAX/(1024*1024), "Mb"); lines_in_ram = UINT_MAX; }else lines_in_ram *= 1024; // <- Rounding down to the Kibi. say("3sfsisfs$", "Sequences to store in ", (double)(ram_Kb - required_ram_Kb)/1024, "Mb free: ", lines_in_ram, " (", (double)lines_in_ram*100.0/total_seqs, "%)"); } hX = broadcast_int(hX); qry_portion = broadcast_double(qry_portion); ram_Kb = broadcast_int(ram_Kb); required_ram_Kb = broadcast_int(required_ram_Kb); lines_in_ram = broadcast_int(lines_in_ram); barrier_multinode(); // Run comparisons restart_mates: say("9sis$", "Worker ", processID, " @start_mates."); matepar.overlap = ovl; matepar.similarity = min_sim; matepar.qryportion = qry_portion; matepar.revcom = revcom; matepar.n_as_mismatch = n_as_mismatch; matepar.k = k; if(processID==0) say("1sfsis$", "Querying library with ", qry_portion, " times the total size (", hX," seqs)"); if(alt_query){ qry_seqs_no = nonpareil_mate(mates, seqFile, qSeqFile, thr, lines_in_ram, total_seqs, largest_seq, q_largest_seq, matepar); }else{ qry_seqs_no = nonpareil_mate(mates, seqFile, thr, lines_in_ram, total_seqs, largest_seq, matepar); } if(processID==0){ if(alt_query) for(size_t a=0; a0)) nonpareil_save_mates(mates, qry_seqs_no, cntfile); } barrier_multinode(); // Sampling restart_samples: say("9sis$", "Worker ", processID, " @start_samples."); sampling_points = (divide==0) ? ((int)ceil((max-min)/itv)+1) : ((int)ceil( (log(2) - log(total_seqs))/log(divide) )+2); sample_t sample_summary[sampling_points]; size_t dummy=0; if(processID==0) { if(strcmp(nonpareiltype,"kmer")!=0) { sample_i=sample_after_20=0; samplepar.np_version = NP_VERSION; samplepar.replicates = n; samplepar.mates = &mates; samplepar.mates_size = qry_seqs_no; samplepar.portion_min = min; samplepar.portion_max = max; samplepar.portion_itv = itv; samplepar.seq_overlap = ovl; samplepar.total_reads = total_seqs; samplepar.max_read_len = largest_seq; samplepar.avg_read_len = avg_seq_len; samplepar.portion_as_label = portion_label; samplepar.divide = divide; samplepar.type = 1; } else { sample_i=sample_after_20=0; samplepar.np_version = NP_VERSION; samplepar.replicates = n; samplepar.mates = &mates; samplepar.mates_size = qry_seqs_no; samplepar.portion_min = min; samplepar.portion_max = max; samplepar.portion_itv = itv; samplepar.seq_overlap = ovl; samplepar.total_reads = total_seqs; samplepar.max_read_len = largest_seq; samplepar.avg_read_len = avg_seq_len; samplepar.portion_as_label = portion_label; samplepar.divide = divide; samplepar.k = k; samplepar.adj_avg_read_len = adj_avg_seq_len; samplepar.type = 2; //kmer } say("1s$", "Sub-sampling library"); while(sample_i < sampling_points){ if(divide==0){ samplepar.portion = min + itv*sample_i; }else{ samplepar.portion = sample_i==0 ? 0 : pow(divide, sampling_points-sample_i-1); } samplepar.replicates = n; samples_no = nonpareil_sample_portion(sample_result, thr, samplepar); //if(processID==0){ sample_summary[sample_i++] = nonpareil_sample_summary(sample_result, samples_no, alldata, outfile, samplepar); if(samplepar.portion<=0.2) sample_after_20 = sample_i; //} } dummy = 1; } dummy = broadcast_int(dummy); barrier_multinode(); goto restart_checkings; // Check results restart_checkings: say("9sis$", "Worker ", processID, " @start_checkings."); if(processID==0){ say("1s>", "Evaluating consistency"); ok = true; // Low sequencing depth if(sample_after_20<=sample_i && sample_summary[sample_after_20].q2==0.0){ say("1ss$", "WARNING: The estimation at 20% has median zero, ", "possibly reflecting inaccurate estimations"); if(qry_portion<1.0 && hX<3000){ if(autoadjust){ hX = 0; qry_portion *= 2.0; if(qry_portion >= 1.0) qry_portion = 1.0; say("1sf$", "AUTOADJUST: -x ", qry_portion); goto restart_vars; } else say("1sf$", "To increase the sensitivity increase -X, currently set at ", hX); } else if(ovl > 0.25) { if(autoadjust){ if(ovl>1.0) ovl = 1.0;// This should never happen else if(ovl>0.75) ovl = 0.75; else if(ovl>0.5) ovl = 0.5; else if(ovl>0.25) ovl = 0.25; else error("Impossible to reduce -L further, sequencing depth under detection level"); say("1sf$", "AUTOADJUST: -L ", ovl*100); goto restart_mates; } else say("1sf$", "To increase sensitivity, decrease -L, currently set at ", ovl*100); } else { say("1ss$", "The portion used as query (-x) is currently set to the maximum, ", "and the overlap (-L) is set to the minimum"); say("1s$", "The dataset is probably too small for reliable estimations"); if(min_sim>0.75) say("1s$", "You could decrease the -S but values other than 0.95 are untested"); error("Sequencing depth under detection limit."); } ok = false; } // High sequencing depth if(sample_summary[sample_i-1].avg >= 0.95){ say("1ss$", "WARNING: The curve reached near-saturation, ", "hence coverage estimations could be unreliable"); if(ovl<1.0){ if(autoadjust){ if(ovl<0.25) ovl = 0.25; else if(ovl<0.5) ovl = 0.5; else if(ovl<0.75) ovl = 0.75; else if(ovl<1.0) ovl = 1.0; say("1sf$", "AUTOADJUST: -L ", ovl*100.0); goto restart_mates; }else say("1sf$", "To avoid saturation increase the -L parameter, currently set at ", ovl*100); } else { say("1ss$", "The overlap (-L) is currently set to the maximum, ", "meaning that the actual coverage is probably above 100X"); if(min_sim<1.0) say("1s$", "You could increase -S but values other than 0.95 are untested"); error("Sequencing depth above detection limit."); } ok = false; } // Low resolution if(sample_i>5 && sample_summary[5].avg >= 0.95){ say("1ss$", "WARNING: The curve reached near-saturation in 6 or less points, ", "hence diversity estimations could be unreliable"); if(autoadjust){ itv *= 0.5; say("1sf$", "AUTOADJUST: -i ", itv); goto restart_samples; } else say("1ssf$", "To increase the resolution of the curve increase the -i parameter, ", "currently set at ", itv); ok = false; } if(ok) say("1s$", "Everything seems correct"); dummy = 2; } dummy = broadcast_int(dummy); barrier_multinode(); goto exit; exit: say("9sis$", "Worker ", processID, " @exit."); // Clean temporals if(processID==0){ remove(namFile); remove(seqFile); close_log(); } barrier_multinode(); finalize_multinode(); return 0; } pact-js/pact-node #include #include "ffi.h" #include "consumer.h" #include "provider.h" #include "plugin.h" Napi::Object Init(Napi::Env env, Napi::Object exports) { exports.Set(Napi::String::New(env, "pactffiVersion"), Napi::Function::New(env, PactffiVersion)); exports.Set(Napi::String::New(env, "pactffiInit"), Napi::Function::New(env, PactffiInit)); exports.Set(Napi::String::New(env, "pactffiInitWithLogLevel"), Napi::Function::New(env, PactffiInitWithLogLevel)); // Consumer exports.Set(Napi::String::New(env, "pactffiMockServerMatched"), Napi::Function::New(env, PactffiMockServerMatched)); exports.Set(Napi::String::New(env, "pactffiMockServerMismatches"), Napi::Function::New(env, PactffiMockServerMismatches)); exports.Set(Napi::String::New(env, "pactffiCreateMockServerForPact"), Napi::Function::New(env, PactffiCreateMockServerForPact)); exports.Set(Napi::String::New(env, "pactffiCleanupMockServer"), Napi::Function::New(env, PactffiCleanupMockServer)); exports.Set(Napi::String::New(env, "pactffiWritePactFile"), Napi::Function::New(env, PactffiWritePactFile)); exports.Set(Napi::String::New(env, "pactffiNewPact"), Napi::Function::New(env, PactffiNewPact)); exports.Set(Napi::String::New(env, "pactffiNewInteraction"), Napi::Function::New(env, PactffiNewInteraction)); exports.Set(Napi::String::New(env, "pactffiUponReceiving"), Napi::Function::New(env, PactffiUponReceiving)); exports.Set(Napi::String::New(env, "pactffiGiven"), Napi::Function::New(env, PactffiGiven)); exports.Set(Napi::String::New(env, "pactffiGivenWithParam"), Napi::Function::New(env, PactffiGivenWithParam)); exports.Set(Napi::String::New(env, "pactffiWithRequest"), Napi::Function::New(env, PactffiWithRequest)); exports.Set(Napi::String::New(env, "pactffiWithQueryParameter"), Napi::Function::New(env, PactffiWithQueryParameter)); exports.Set(Napi::String::New(env, "pactffiWithSpecification"), Napi::Function::New(env, PactffiWithSpecification)); exports.Set(Napi::String::New(env, "pactffiWithPactMetadata"), Napi::Function::New(env, PactffiWithPactMetadata)); exports.Set(Napi::String::New(env, "pactffiWithHeader"), Napi::Function::New(env, PactffiWithHeader)); exports.Set(Napi::String::New(env, "pactffiWithBody"), Napi::Function::New(env, PactffiWithBody)); exports.Set(Napi::String::New(env, "pactffiWithBinaryFile"), Napi::Function::New(env, PactffiWithBinaryFile)); exports.Set(Napi::String::New(env, "pactffiWithMultipartFile"), Napi::Function::New(env, PactffiWithMultipartFile)); exports.Set(Napi::String::New(env, "pactffiResponseStatus"), Napi::Function::New(env, PactffiResponseStatus)); exports.Set(Napi::String::New(env, "pactffiUsingPlugin"), Napi::Function::New(env, PactffiUsingPlugin)); exports.Set(Napi::String::New(env, "pactffiCleanupPlugins"), Napi::Function::New(env, PactffiCleanupPlugins)); exports.Set(Napi::String::New(env, "pactffiPluginInteractionContents"), Napi::Function::New(env, PactffiPluginInteractionContents)); // exports.Set(Napi::String::New(env, "pactffiNewMessagePact"), Napi::Function::New(env, PactffiNewMessagePact)); // exports.Set(Napi::String::New(env, "pactffiWriteMessagePactFile"), Napi::Function::New(env, PactffiWriteMessagePactFile)); // exports.Set(Napi::String::New(env, "pactffiWithMessagePactMetadata"), Napi::Function::New(env, PactffiWithMessagePactMetadata)); exports.Set(Napi::String::New(env, "pactffiNewAsyncMessage"), Napi::Function::New(env, PactffiNewAsyncMessage)); exports.Set(Napi::String::New(env, "pactffiNewSyncMessage"), Napi::Function::New(env, PactffiNewSyncMessage)); // exports.Set(Napi::String::New(env, "pactffiNewMessage"), Napi::Function::New(env, PactffiNewMessage)); exports.Set(Napi::String::New(env, "pactffiMessageReify"), Napi::Function::New(env, PactffiMessageReify)); exports.Set(Napi::String::New(env, "pactffiMessageGiven"), Napi::Function::New(env, PactffiMessageGiven)); exports.Set(Napi::String::New(env, "pactffiMessageGivenWithParam"), Napi::Function::New(env, PactffiMessageGivenWithParam)); exports.Set(Napi::String::New(env, "pactffiMessageWithContents"), Napi::Function::New(env, PactffiMessageWithContents)); exports.Set(Napi::String::New(env, "pactffiMessageWithMetadata"), Napi::Function::New(env, PactffiMessageWithMetadata)); exports.Set(Napi::String::New(env, "pactffiMessageExpectsToReceive"), Napi::Function::New(env, PactffiMessageExpectsToReceive)); // Provider exports.Set(Napi::String::New(env, "pactffiVerifierNewForApplication"), Napi::Function::New(env, PactffiVerifierNewForApplication)); exports.Set(Napi::String::New(env, "pactffiVerifierSetVerificationOptions"), Napi::Function::New(env, PactffiVerifierSetVerificationOptions)); exports.Set(Napi::String::New(env, "pactffiVerifierSetPublishOptions"), Napi::Function::New(env, PactffiVerifierSetPublishOptions)); exports.Set(Napi::String::New(env, "pactffiVerifierExecute"), Napi::Function::New(env, PactffiVerifierExecute)); exports.Set(Napi::String::New(env, "pactffiVerifierShutdown"), Napi::Function::New(env, PactffiVerifierShutdown)); exports.Set(Napi::String::New(env, "pactffiVerifierSetProviderInfo"), Napi::Function::New(env, PactffiVerifierSetProviderInfo)); exports.Set(Napi::String::New(env, "pactffiVerifierSetFilterInfo"), Napi::Function::New(env, PactffiVerifierSetFilterInfo)); exports.Set(Napi::String::New(env, "pactffiVerifierSetProviderState"), Napi::Function::New(env, PactffiVerifierSetProviderState)); exports.Set(Napi::String::New(env, "pactffiVerifierSetConsumerFilters"), Napi::Function::New(env, PactffiVerifierSetConsumerFilters)); exports.Set(Napi::String::New(env, "pactffiVerifierAddCustomHeader"), Napi::Function::New(env, PactffiVerifierAddCustomHeader)); exports.Set(Napi::String::New(env, "pactffiVerifierAddFileSource"), Napi::Function::New(env, PactffiVerifierAddFileSource)); exports.Set(Napi::String::New(env, "pactffiVerifierAddDirectorySource"), Napi::Function::New(env, PactffiVerifierAddDirectorySource)); exports.Set(Napi::String::New(env, "pactffiVerifierUrlSource"), Napi::Function::New(env, PactffiVerifierUrlSource)); exports.Set(Napi::String::New(env, "pactffiVerifierBrokerSourceWithSelectors"), Napi::Function::New(env, PactffiVerifierBrokerSourceWithSelectors)); return exports; } NODE_API_MODULE(pact, Init)/* * * * * * * * * * * * * * * * * * * * * @author: * @date: 2021-02-24 19:10:43 * @description: * * * @notes: * g++ -fsanitize=address -ftrapv -O2 * * * * * * * * * * * * * * * * * */ #include #define F first #define S second #define MP make_pair #define TIME (double)clock()/CLOCKS_PER_SEC using namespace std; typedef long long ll; typedef long double ld; typedef pair pii; const int mod = 1000000007; const ll oo = 1e18; const ld eps = 1e-8; #define debug(x) cerr << "(debug mod) " << #x << " = " << x << endl double limit = 100.0; int m, n, n2, n3, n4, n_ing = 0; map ing; struct P { vector ing; int bel, id; void output () { cerr << "output pizza " << id << ", ing: "; for (int i = 0; i < ing.size(); i ++) cerr << ing[i] << " "; cerr << ".\n"; } }; vector

pizzas; ll pans = 0; struct T { int size, id, ni, fake; T () {} T (int s, int i) {size = s; id = i; ni = 0; fake = 0;} int value () {return ni * ni;} map ing; vector piz; void output () { cerr << "output team " << id << " : s = " << size << ", piz: "; for (int i = 0; i < piz.size(); i ++) cerr << piz[i] << " "; cerr << ", ing = " << ni << ".\n"; } void add_piz(int id) { pans -= value() * (!fake); piz.push_back(id); for (int i = 0; i < pizzas[id].ing.size(); i ++) ni += (ing[pizzas[id].ing[i]] ++) == 0; pans += value() * (!fake); } void rem_piz(int id) { pans -= value() * (!fake); for (int i = 0; i < pizzas[id].ing.size(); i ++) ni -= (-- ing[pizzas[id].ing[i]]) == 0; for (int pi = 0; pi < piz.size(); pi ++) if (piz[pi] == id) { for (int i = pi; i < piz.size() - 1; i ++) piz[i] = piz[i + 1]; piz.pop_back(); break; } pans += value() * (!fake); } }; vector teams; namespace Final { ll fans = 0; ll bd = 0; vector fteams; void record() { if (pans <= fans) return ; if (pans > bd) { cerr << "UPD: " << pans << endl; bd = pans / 100 * 100 + 100; } fans = pans; fteams.resize(0); for (int i = 0; i < teams.size(); i ++) fteams.push_back(teams[i]); } } namespace Tools { void pre_shuffle () { random_shuffle(teams.begin(), teams.end()); } void clear () { for (int i = 0; i < n; i ++) { for (int j = 0; j < teams[i].piz.size(); j ++) teams[i].rem_piz(teams[i].piz[j]); teams[i].piz.resize(0); } } void formal_output() { using namespace Final; int have = 0; for (int i = 0; i < n; i ++) if (fteams[i].ni) have ++; cout << have << endl; for (int i = 0; i < n; i ++) if (fteams[i].ni) { cout << fteams[i].size << ' '; for (int j = 0; j < fteams[i].piz.size(); j ++) cout << fteams[i].piz[j] << ' '; cout << endl; } cerr << "answer gained: " << fans << endl; } void input () { cin >> m >> n2 >> n3 >> n4; n = n2 + n3 + n4; for (int c, i = 0; i < m; i ++ ) { P p; p.bel = -1; cin >> c; for (int j = 0; j < c; j ++) { string s; cin >> s; if (!ing[s]) ing[s] = ++ n_ing; p.ing.push_back(ing[s]); } p.id = i; pizzas.push_back(p); } for (int i = 0; i < n4; i ++) teams.push_back(T(4, n2 + n3 + i)); for (int i = 0; i < n3; i ++) teams.push_back(T(3, n2 + i)); for (int i = 0; i < n2; i ++) teams.push_back(T(2, i)); // cerr << "finished input: " << TIME << endl; int pt[5] = {0, 0, n4 + n3, n4, 0}; int cnt =0 ; cin >> cnt; for (int i = 0; i < cnt; i ++) { int num, x; cin >> num; for (int j = 0; j < num; j ++) { cin >> x; teams[pt[num]].add_piz(x); } pt[num] ++; } } void BF() { pre_shuffle(); clear(); vector rt; for (int i = 0; i < m; i ++) rt.push_back(i); random_shuffle(rt.begin(), rt.end()); int pter = 0; for (int i = 0; i < n; i ++) if (m - pter >= teams[i].size){ for (int j = pter; j < pter + teams[i].size; j ++) teams[i].add_piz(rt[j]); pter += teams[i].size; } Final::record(); } void swap_two (int ta, int tb, int px, int py) { teams[ta].rem_piz(px); teams[tb].rem_piz(py); teams[ta].add_piz(py); teams[tb].add_piz(px); } int pred_swap_two (int ta, int tb, int px, int py) { T a = teams[ta], b = teams[tb]; a.fake = b.fake = true; int dt = -a.value() - b.value(); a.rem_piz(px); b.rem_piz(py); a.add_piz(py); b.add_piz(px); dt += a.value() + b.value(); return dt; } void adjusting () { int ta, tb, ia, ib, px, py, dt; int cnt = 0; do { do { ta = rand() % n; tb = rand() % n; } while (ta == tb || teams[ta].piz.size() == 0 || teams[tb].piz.size() == 0); ia = rand() % teams[ta].size; ib = rand() % teams[tb].size; px = teams[ta].piz[ia]; py = teams[tb].piz[ib]; dt = pred_swap_two(ta, tb, px, py); } while (dt <= 0 && ((++cnt) % 100 || TIME < limit)); if (dt <= 0) return ; ll cans = pans; swap_two(ta, tb, px, py); Final::record(); } double Random () {return (double)rand()/RAND_MAX;} void SA () { const ld initT = 1e1, endT = 1e-20, dT = 0.99998; int cnt = 0; for (ld T = initT; T >= endT; T *= dT) { if ((++ cnt) % 100000 == 0) cerr << "T : " << T << endl; int ta, tb, ia, ib, px, py, dE; do { ta = rand() % n; tb = rand() % n; } while (ta == tb || teams[ta].piz.size() == 0 || teams[tb].piz.size() == 0); ia = rand() % teams[ta].size; ib = rand() % teams[tb].size; px = teams[ta].piz[ia]; py = teams[tb].piz[ib]; dE = pred_swap_two(ta, tb, px, py); if(dE > 0 || exp(dE/T) > Random()) { swap_two(ta, tb, px, py); Final::record(); } } } void wrapUp() { // for (int i = 0; i < m; i ++) // pizzas[i].output(); // for (int i = 0; i < n; i ++) // teams[i].output(); formal_output(); } }using namespace Tools; int main() { srand(time(0)); ios::sync_with_stdio(false); input(); Final::record(); int cnt = 0; // BF(); // SA(); while (TIME < limit) { adjusting(); cnt ++; } // cerr << "cnt : " << cnt << endl; wrapUp(); return 0; }// Copyright 2019 Smarter Grid Solutions // // 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 permissionsand // limitations under the License. // This test file just says to let catch2 (the unit test framwork) // define the main function. This way, we get the nice catch2 command // line interface automatically out of the box. #define CATCH_CONFIG_MAIN #include "catch.hpp" 0 #include #include #include std::mutex gmutex; extern bool gstarted; extern std::thread gstartup; std::thread gstarting([](int){ spdlog::info("gstarting unblocked gstarted={}", gstarted); }, (spdlog::info("gstarting waits.."), []{ try{ gstartup.join(); }catch(...){ spdlog::info("gstartup join failed"); std::terminate(); } }(), 0)); Source/AliveLibAO/ScreenClipper.cpp #include "stdafx_ao.h" #include "Function.hpp" #include "ScreenClipper.hpp" #include "stdlib.hpp" #include "Game.hpp" #include "PsxDisplay.hpp" #undef min #undef max namespace AO { BaseGameObject* ScreenClipper::Vdtor_40BF40(unsigned int flags) { dtor_40BDE0(); if (flags & 1) { ao_delete_free_447540(this); } return this; } BaseGameObject* ScreenClipper::dtor_40BDE0() { SetVTable(this, 0x4BA428); gObjList_drawables_504618->Remove_Item(this); return dtor_487DF0(); } void ScreenClipper::VRender_40BEB0(PrimHeader** ppOt) { PSX_RECT clipRect = {}; clipRect.x = field_30_rect.x; clipRect.y = field_30_rect.y; clipRect.w = field_30_rect.w - field_30_rect.x; clipRect.h = field_30_rect.h - field_30_rect.y; if (gPsxDisplay_504C78.field_A_buffer_index) { // Move to the lower buffer if not using the top buffer clipRect.y += gPsxDisplay_504C78.field_2_height; } Prim_PrimClipper* pClipper = &field_10_clippers[gPsxDisplay_504C78.field_A_buffer_index]; Init_PrimClipper_495FD0(pClipper, &clipRect); OrderingTable_Add_498A80(OtLayer(ppOt, field_38_ot_layer), &pClipper->mBase); } void ScreenClipper::VUpdate() { // Empty } void ScreenClipper::VScreenChanged() { // Empty } void ScreenClipper::VRender(PrimHeader** ppOt) { VRender_40BEB0(ppOt); } BaseGameObject* ScreenClipper::VDestructor(signed int flags) { return Vdtor_40BF40(flags); } ScreenClipper* ScreenClipper::ctor_40BD60(PSX_Point xy, PSX_Point wh, Layer layer) { ctor_487E10(1); SetVTable(this, 0x4BA428); field_4_typeId = Types::eScreenClipper_78; field_6_flags.Set(Options::eUpdateDuringCamSwap_Bit10); field_6_flags.Set(Options::eDrawable_Bit4); field_30_rect.x = xy.field_0_x; field_30_rect.y = xy.field_2_y; field_30_rect.w = wh.field_0_x; field_30_rect.h = wh.field_2_y; field_38_ot_layer = layer; gObjList_drawables_504618->Push_Back(this); return this; } void ScreenClipper::Update_Clip_Rect_40BE40(PSX_Point xy, PSX_Point wh) { field_30_rect.x = std::min(xy.field_0_x, field_30_rect.x); field_30_rect.y = std::min(xy.field_2_y, field_30_rect.y); field_30_rect.w = std::max(wh.field_0_x, field_30_rect.w); field_30_rect.h = std::max(wh.field_2_y, field_30_rect.h); } } mfkiwl/ICE /* $Id$ * Xendweek.c - Test scaffold for demonstrating correctness of the * SVPCodeGen class. In this case, the test is to correctly generate * the P-code for the last 6 seconds of the week for each possible * GPS PRN. * * August 2003 * Applied Reserach Laboratories, The University of Texas at Austin */ //============================================================================ // // This file is part of GPSTk, the GPS Toolkit. // // The GPSTk is free software; you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 2.1 of the License, or // any later version. // // The GPSTk 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 GPSTk; if not, write to the Free Software Foundation, // Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA // // Copyright 2009, The University of Texas at Austin // //============================================================================ // Language headers #include #include #include // Project headers #include "PCodeConst.hpp" #include "SVPCodeGen.hpp" #include "CodeBuffer.hpp" #include "X1Sequence.hpp" #include "X2Sequence.hpp" /** * @file Xendweek.cpp * */ using namespace std; // for map and pair access using namespace gpstk; // Convenience structure for grouping all the data objects associated // with a single SV. These structs are commonly placed in maps for // processing. struct SVData { SVPCodeGen * PCodeGen; CodeBuffer * PCodeBuf; codeType cType; SVData( SVPCodeGen * a1, CodeBuffer * a2, codeType c ) { PCodeGen = a1; PCodeBuf = a2; cType = c; }; }; const int NUM_SATS = 38; int main(int argc, char* argv[] ) { printf("Ryan's Xendweek\n"); if (argc < 2) { printf("Usage: >>Xendweek \n"); exit(1); } // Open an output file. printf(" Opening output file.\n"); FILE *outFile = fopen( argv[1], "wt" ); if (outFile==NULL) { printf(" Cannot open Xendweek.out for output.\n"); exit(-1); } fprintf(outFile," XENDWEEK.OUT - Demonstrating P-Code End of Week Generation..\n"); fprintf(outFile," Reproducing ICD-GPS-200, Table 3-IV\n"); // Set time to end of week minus six seconds printf(" Setting time to end of week.\n"); //DayTime dt( 1233, 604794.0, 2003 ); DayTime dt( 1233, 604794.0 ); // NOTE: The P-code generator works in 6-second "chunks". This implies // that there are 6 seconds of X1 bitstream and 6 seconds of X2 bitstreams // held in memory. To mimimize the memory footprint, these bitstreams // are shared between all coders and are located in dynamically allocated // buffers referenced through static pointers. THEREFORE, before any // SVPCodeGen objects are instantiated, these buffers must be allocated // and initialized via the following two calls. Failure to do so will // resort in abnormal program termination (unless the exceptions are // trapped). try { X1Sequence::allocateMemory(); X2Sequence::allocateMemory(); } catch (gpstk::Exception e) { printf(" Memory allocation failure.\n"); printf(" Xbegweek will terminate.\n"); return(1); } // Instantiate a map to hold SVPCodeGen and CodeBuffer objects printf(" Instantiating the PRN map.\n"); mapsvdMap; typedef map::iterator SVDataI; // Instantiate and initialize the P-coder objects SVPCodeGen * svp[NUM_SATS]; CodeBuffer * pcb[NUM_SATS]; for (int n=0;n ps( PRNndx, svd ); svdMap.insert( ps ); } fprintf(outFile," PRN Last word "); // Calculate X1count where X2 starts to transition to end of week "hold" long EndOfWeekTestCount = 3 * (XA_COUNT * XA_MAX_EPOCH) + (XA_COUNT * (XA_MAX_EPOCH-1)) + 3023; long EndOfWeekTestWord = (EndOfWeekTestCount / MAX_BIT); long EndOfWeekTestEnd = EndOfWeekTestWord+(XA_EPOCH_DELAY+104)/MAX_BIT+3; long chip = EndOfWeekTestWord * MAX_BIT - 3 * (XA_COUNT * XA_MAX_EPOCH) - (XA_COUNT * (XA_MAX_EPOCH-1)); for (long j=EndOfWeekTestWord;jfirst; SVData& rsvd = p->second; SVPCodeGen& rsvp = *(rsvd.PCodeGen); CodeBuffer& rcb = *(rsvd.PCodeBuf); rsvp.getCurrentSixSeconds( rcb ); temp = rcb[NUM_6SEC_WORDS-1]; fprintf( outFile," %02d x%08X",PRNID,temp); for (long n=EndOfWeekTestWord;n. /// 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 EAGINE_LOGGING_PROXY_BACKEND_HPP #define EAGINE_LOGGING_PROXY_BACKEND_HPP #include "backend.hpp" #include #include namespace eagine { //------------------------------------------------------------------------------ class proxy_log_backend : public logger_backend { public: proxy_log_backend(log_stream_info info) noexcept : _info{std::move(info)} {} auto configure(application_config&) -> bool final; auto entry_backend( const identifier source, const log_event_severity severity) noexcept -> logger_backend* final; auto allocator() noexcept -> memory::shared_byte_allocator final; auto type_id() noexcept -> identifier final; void enter_scope(const identifier source) noexcept final; void leave_scope(const identifier source) noexcept final; void set_description( const identifier source, const logger_instance_id instance, const string_view name, const string_view desc) noexcept final; auto begin_message( const identifier source, const identifier tag, const logger_instance_id instance, const log_event_severity severity, const string_view format) noexcept -> bool final; void add_nothing(const identifier arg, const identifier tag) noexcept final; void add_identifier( const identifier arg, const identifier tag, const identifier value) noexcept final; void add_message_id( const identifier arg, const identifier tag, const message_id value) noexcept final; void add_bool( const identifier arg, const identifier tag, const bool value) noexcept final; void add_integer( const identifier arg, const identifier tag, const std::intmax_t value) noexcept final; void add_unsigned( const identifier arg, const identifier tag, const std::uintmax_t value) noexcept final; void add_float( const identifier arg, const identifier tag, const float value) noexcept final; void add_float( const identifier arg, const identifier tag, const float min, const float value, const float max) noexcept final; void add_duration( const identifier arg, const identifier tag, const std::chrono::duration value) noexcept final; void add_string( const identifier arg, const identifier tag, const string_view value) noexcept final; void add_blob( const identifier arg, const identifier tag, const memory::const_block value) noexcept final; void finish_message() noexcept final; void finish_log() noexcept final; void log_chart_sample( const identifier source, const logger_instance_id instance, const identifier series, const float value) noexcept final; private: std::unique_ptr _delegate; std::unique_ptr>> _delayed{ std::make_unique>>()}; log_stream_info _info; }; //------------------------------------------------------------------------------ } // namespace eagine #if !EAGINE_CORE_LIBRARY || defined(EAGINE_IMPLEMENTING_CORE_LIBRARY) #include #endif #endif // EAGINE_LOGGING_PROXY_BACKEND_HPP TISparta/competitive-programming-solutions // Segment Tree // 3 // 10-09-2020 #include #define all(A) begin(A), end(A) #define rall(A) rbegin(A), rend(A) #define sz(A) int(A.size()) #define pb push_back #define mp make_pair using namespace std; typedef long long ll; typedef pair pii; typedef pair pll; typedef vector vi; typedef vector vll; typedef vector vpii; typedef vector vpll; int main () { ios::sync_with_stdio(false); cin.tie(0); struct node { int l, r, val = 0, left = -1, right = -1; }; vector tree; function update = [&] (int u, int l, int r, int pos, int val) { if (not (l <= pos and pos <= r)) return; if (l == pos and pos == r) { tree[u].val = val; return; } int m = (l + r) >> 1; if (tree[u].left == -1) { tree[u].left = sz(tree); tree.pb({l, m, 0, -1, -1}); } if (tree[u].right == -1) { tree[u].right = sz(tree); tree.pb({m + 1, r, 0, -1, -1}); } update(tree[u].left, l, m, pos, val); update(tree[u].right, m + 1, r, pos, val); tree[u].val = max(tree[tree[u].left].val, tree[tree[u].right].val); }; function get_max = [&] (int u, int l, int r, int L, int R) -> int { if (u == -1 or R < l or r < L) return 0; if (L <= l and r <= R) return tree[u].val; int m = (l + r) >> 1; return max(get_max(tree[u].left, l, m, L, R), get_max(tree[u].right, m + 1, r, L, R)); }; tree.pb({0, int(1e9), 0, -1, -1}); int n; cin >> n; for (int i = 1; i <= n; i++) { int ai; cin >> ai; cout << get_max(0, 0, 1e9, 0, ai - 1) << " \n"[i == n]; update(0, 0, 1e9, ai, i); } return (0); } /* * This file is part of the opmsg crypto message framework. * * (C) 2015 by , * sebastian [dot] krahmer [at] gmail [dot] com * * opmsg 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. * * opmsg 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 opmsg. If not, see . */ #include #include namespace opmsg { static const char *b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; using namespace std; /* The base64 routines have been taken from the Samba 3 source (GPL) * and have been C++-ified */ string &b64_decode(const string &src, string &dst) { unsigned int bit_offset, byte_offset, idx, i = 0, n = 0, j = 0; const char *p = NULL; dst = ""; string::size_type srclen = src.size(); dst.reserve(srclen); dst.resize(srclen); while (j < srclen && (p = strchr(b64, src[j]))) { idx = (int)(p - b64); byte_offset = (i*6)/8; bit_offset = (i*6)%8; dst[byte_offset] &= ~((1<<(8-bit_offset))-1); if (bit_offset < 3) { dst[byte_offset] |= (idx << (2-bit_offset)); n = byte_offset+1; } else { dst[byte_offset] |= (idx >> (bit_offset-2)); dst[byte_offset+1] = 0; dst[byte_offset+1] |= (idx << (8-(bit_offset-2))) & 0xFF; n = byte_offset+2; } j++; i++; } if (src[j] == '=') n -= 1; dst.resize(n); return dst; } string &b64_encode(const string &src, string &dst) { unsigned int bits = 0; int char_count = 0, i = 0; dst = ""; dst.reserve(src.size() + src.size()/3 + 10); string::size_type len = src.size(); while (len--) { unsigned int c = (unsigned char)src[i++]; bits += c; char_count++; if (char_count == 3) { dst += b64[bits >> 18]; dst += b64[(bits >> 12) & 0x3f]; dst += b64[(bits >> 6) & 0x3f]; dst += b64[bits & 0x3f]; bits = 0; char_count = 0; } else { bits <<= 8; } } if (char_count != 0) { bits <<= 16 - (8 * char_count); dst += b64[bits >> 18]; dst += b64[(bits >> 12) & 0x3f]; if (char_count == 1) { dst += '='; dst += '='; } else { dst += b64[(bits >> 6) & 0x3f]; dst += '='; } } return dst; } string &b64_encode(const char *src, size_t srclen, string &dst) { unsigned int bits = 0; int char_count = 0, i = 0; dst = ""; dst.reserve(srclen + srclen/3 + 10); while (srclen--) { unsigned int c = (unsigned char)src[i++]; bits += c; char_count++; if (char_count == 3) { dst += b64[bits >> 18]; dst += b64[(bits >> 12) & 0x3f]; dst += b64[(bits >> 6) & 0x3f]; dst += b64[bits & 0x3f]; bits = 0; char_count = 0; } else { bits <<= 8; } } if (char_count != 0) { bits <<= 16 - (8 * char_count); dst += b64[bits >> 18]; dst += b64[(bits >> 12) & 0x3f]; if (char_count == 1) { dst += '='; dst += '='; } else { dst += b64[(bits >> 6) & 0x3f]; dst += '='; } } return dst; } string &b64_decode(const char *src, size_t srclen, string &dst) { unsigned int bit_offset, byte_offset, idx, i = 0, n = 0, j = 0; const char *p = NULL; dst = ""; dst.reserve(srclen); dst.resize(srclen); while (j < srclen && (p = strchr(b64, src[j]))) { idx = (int)(p - b64); byte_offset = (i*6)/8; bit_offset = (i*6)%8; dst[byte_offset] &= ~((1<<(8-bit_offset))-1); if (bit_offset < 3) { dst[byte_offset] |= (idx << (2-bit_offset)); n = byte_offset+1; } else { dst[byte_offset] |= (idx >> (bit_offset-2)); dst[byte_offset+1] = 0; dst[byte_offset+1] |= (idx << (8-(bit_offset-2))) & 0xFF; n = byte_offset+2; } j++; i++; } if (src[j] == '=') n -= 1; dst.resize(n); return dst; } } hxb1997/Mengesrc/Menge/MengeCore/resources/PortalPath.cpp /* License Menge Copyright © and trademark ™ 2012-14 University of North Carolina at Chapel Hill. All rights reserved. Permission to use, copy, modify, and distribute this software and its documentation for educational, research, and non-profit purposes, without fee, and without a written agreement is hereby granted, provided that the above copyright notice, this paragraph, and the following four paragraphs appear in all copies. This software program and documentation are copyrighted by the University of North Carolina at Chapel Hill. The software program and documentation are supplied "as is," without any accompanying services from the University of North Carolina at Chapel Hill or the authors. The University of North Carolina at Chapel Hill and the authors do not warrant that the operation of the program will be uninterrupted or error-free. The end-user understands that the program was developed for research purposes and is advised not to rely exclusively on the program for any reason. IN NO EVENT SHALL THE UNIVERSITY OF NORTH CAROLINA AT CHAPEL HILL OR THE AUTHORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF NORTH CAROLINA AT CHAPEL HILL OR THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. THE UNIVERSITY OF NORTH CAROLINA AT CHAPEL HILL AND THE AUTHORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE AND ANY STATUTORY WARRANTY OF NON-INFRINGEMENT. THE SOFTWARE PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE UNIVERSITY OF NORTH CAROLINA AT CHAPEL HILL AND THE AUTHORS HAVE NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. Any questions or comments should be sent to the authors { */ #include "MengeCore/resources/PortalPath.h" #include #include "MengeCore/Agents/BaseAgent.h" #include "MengeCore/BFSM/Goals/Goal.h" #include "MengeCore/BFSM/fsmCommon.h" #include "MengeCore/Core.h" #include "MengeCore/resources/Funnel.h" #include "MengeCore/resources/NavMeshLocalizer.h" #include "MengeCore/resources/PathPlanner.h" #include "MengeCore/resources/WayPortal.h" #include namespace Menge { ///////////////////////////////////////////////////////////////////// // Implementation of PortalPath ///////////////////////////////////////////////////////////////////// PortalPath::PortalPath(const Vector2& startPos, const BFSM::Goal* goal, const PortalRoute* route, float agentRadius) : _route(route), _goal(goal), _currPortal(0), _waypoints(0x0), _headings(0x0) { computeCrossing(startPos, agentRadius); } ///////////////////////////////////////////////////////////////////// PortalPath::~PortalPath() { if (_waypoints) delete[] _waypoints; if (_headings) delete[] _headings; } ///////////////////////////////////////////////////////////////////// void PortalPath::setPreferredDirection(const Agents::BaseAgent* agent, float headingCos, Agents::PrefVelocity& pVel) { const size_t PORTAL_COUNT = _route->getPortalCount(); Vector2 dir; if (_currPortal >= PORTAL_COUNT) { // assume that the path is clear // TODO: See GoalVC _goal->setDirections(agent->_pos, agent->_radius, pVel); // speed Vector2 goalPoint = pVel.getTarget(); Vector2 disp = goalPoint - agent->_pos; const float distSq = absSq(disp); float speed = agent->_prefSpeed; if (distSq <= 0.0001f) { // I've basically arrived -- speed should be zero. speed = 0.f; } else { const float speedSq = speed * speed; const float TS_SQD = SIM_TIME_STEP * SIM_TIME_STEP; if (distSq / speedSq < TS_SQD) { // The distance is less than I would travel in a single time step. speed = sqrtf(distSq) / SIM_TIME_STEP; } } pVel.setSpeed(speed); } else { const WayPortal* portal = _route->getPortal(_currPortal); Vector2 goalDir(_waypoints[_currPortal] - agent->_pos); float dist = abs(goalDir); // If the displacement to the next way point is large enough // (i.e., not essentially zero), use it, otherwise, peek // into the next waypoint. // // The goal is to always provide a goalDir to the portal // that is well-defined and unit-length. bool bigEnough = dist >= EPS; if (bigEnough) { goalDir /= dist; if (goalDir * _headings[_currPortal] < headingCos) { // Heading has deviated too far recompute crossing FunnelPlanner planner; planner.computeCrossing(agent->_radius, agent->_pos, this, _currPortal); goalDir = _waypoints[_currPortal] - agent->_pos; dist = abs(goalDir); if ((bigEnough = (dist >= EPS))) { goalDir /= dist; } } } if (!bigEnough) { // simply cross the wayportal perpendicularly // goalDir.set( portal->getCrossingDir( agent->_pos ) ); if (_currPortal + 1 < getPortalCount()) { // calculate w.r.t. next waypoint goalDir = norm(_waypoints[_currPortal + 1] - agent->_pos); } else { // calculate w.r.t. goal Vector2 gp; _goal->getTargetPoint(gp, agent->_radius); goalDir = norm(gp - agent->_pos); } } assert(abs(goalDir) > EPS && "Providing a goal direction that is too small"); pVel.setTarget(_waypoints[_currPortal]); portal->setPreferredDirection(agent->_pos, agent->_radius, goalDir, pVel); } } ///////////////////////////////////////////////////////////////////// unsigned int PortalPath::updateLocation(const Agents::BaseAgent* agent, const NavMeshPtr& navMesh, const NavMeshLocalizer* localizer, PathPlanner* planner) { // If off path, replan get a new route // TODO: If off "approach" vector, recompute crossing bool changed = false; unsigned int currNodeID = getNode(); const NavMeshNode* currNode = &(navMesh->getNode(currNodeID)); // test current location const Vector2& p = agent->_pos; const unsigned int PORTAL_COUNT = static_cast(_route->getPortalCount()); if (!currNode->containsPoint(p)) { // test to see if I've progressed to the next bool gotoNext = false; const NavMeshNode* nextNode = 0x0; if (_currPortal + 1 < PORTAL_COUNT) { // there is another way portal to test const WayPortal* nextPortal = _route->getPortal(_currPortal + 1); size_t nextID = nextPortal->_nodeID; nextNode = &(navMesh->getNode((unsigned int)nextID)); gotoNext = nextNode->containsPoint(p); } else if (_currPortal < PORTAL_COUNT) { // the next node is the goal polygon nextNode = &(navMesh->getNode((unsigned int)_route->getEndNode())); gotoNext = nextNode->containsPoint(p); } if (gotoNext) { // I've made progress, simply advance ++_currPortal; assert(_currPortal <= PORTAL_COUNT && "Incremented current portal larger than goal"); changed = true; } else { const NavMeshNode* prevNode = 0x0; // test to see if I've gone backwards bool gotoPrev = false; if (_currPortal > 0) { const WayPortal* prevPortal = _route->getPortal(_currPortal - 1); size_t prevID = prevPortal->_nodeID; prevNode = &(navMesh->getNode((unsigned int)prevID)); gotoPrev = prevNode->containsPoint(p); } if (gotoPrev) { // back up to previous way portal in path --_currPortal; changed = true; } else { // Agent is not in current, previous or next polygons - agent got // pushed off path - find a new path // Path needs the nav mesh // Assume that I must be in a neighboring node (the alternative is // catstrophic) // search current node's neighbors that aren't previous and aren't next const size_t NBR_COUNT = currNode->getNeighborCount(); for (size_t n = 0; n < NBR_COUNT; ++n) { const NavMeshNode* node = currNode->getNeighbor(n); if (node == nextNode || node == prevNode) continue; if (node->containsPoint(p)) { // find a new path from this node to the goal replan(p, node->getID(), _route->getEndNode(), agent->_radius, planner); changed = true; } } // It is possible for the agent, in some cases, to advance several nodes in a // single time step (e.g., when the navigation mesh has many long, skinny // triangles and the agent steps across the narrow fan). // In this case, the agent should search forwards along the path before // blindly searching. // TODO: // If it gets "lost" at the beginning of a long path, I'm doing a bunch of // wasted testing. Given how far the agent is from a particular portal, I // know I should probably stop looking as the portals are only going to // get farther. So, that means the inside query should CHEAPLY compute // some sense of distance to the polygon so I can drop out. if (changed == false) { size_t testPortal = _currPortal + 2; while (testPortal < PORTAL_COUNT) { const WayPortal* nextPortal = _route->getPortal(testPortal); size_t testID = nextPortal->_nodeID; const NavMeshNode* testNode = &(navMesh->getNode((unsigned int)testID)); if (testNode->containsPoint(p)) { _currPortal = testPortal; changed = true; break; } ++testPortal; } } if (changed == false) { // I exited the loop without finding an intermediate node -- test the goal // node const NavMeshNode* testNode = &(navMesh->getNode((unsigned int)_route->getEndNode())); if (testNode->containsPoint(p)) { _currPortal = PORTAL_COUNT; changed = true; } } if (!changed) { #ifdef _DEBUG logger << Logger::WARN_MSG << "Agent " << agent->_id; logger << " got pushed from its goal into a non-adjacent goal!!\n"; #endif // do a full find path searching for the agent position float lastElevation = currNode->getElevation(p); unsigned int nodeID = localizer->findNodeBlind(p, lastElevation); if (nodeID != NavMeshLocation::NO_NODE) { try { replan(p, nodeID, _route->getEndNode(), agent->_radius, planner); } catch (PathPlannerException) { std::stringstream ss; ss << "Agent " << agent->_id << " trying to find a path from "; ss << nodeID << " to " << _route->getEndNode(); ss << ". A* finished without a route!"; throw PathPlannerException(ss.str()); } } changed = true; } } } } /* // TODO: Implement the idea of replanning the path based on getting pushed off // approach vector if ( !changed && _currPortal < _route->getPortalCount() ) { // vector from crossing point to current position. // examine angle between original approach vector and current approach vector. // If the angle > some threshold, replan. } */ if (_currPortal < _route->getPortalCount()) { return _route->getPortal(_currPortal)->_nodeID; } else { return _route->getEndNode(); } } ///////////////////////////////////////////////////////////////////// void PortalPath::updateGoalLocation(const Agents::BaseAgent* agent, unsigned int goal_node, PathPlanner* planner) { replan(agent->_pos, getNode(), goal_node, agent->_radius, planner); } ///////////////////////////////////////////////////////////////////// unsigned int PortalPath::getNode() const { if (_currPortal == _route->getPortalCount()) { return _route->getEndNode(); } else { return _route->getPortalNode(_currPortal); } } ///////////////////////////////////////////////////////////////////// void PortalPath::computeCrossing(const Vector2& startPos, float agentRadius) { const size_t PORTAL_COUNT = _route->getPortalCount(); if (PORTAL_COUNT > 0) { assert(_waypoints == 0x0 && "Computing the crossing for a path that already exists"); _currPortal = 0; _waypoints = new Vector2[PORTAL_COUNT]; _headings = new Vector2[PORTAL_COUNT]; FunnelPlanner planner; planner.computeCrossing(agentRadius, startPos, this); } } ///////////////////////////////////////////////////////////////////// void PortalPath::replan(const Vector2& startPos, unsigned int startNode, unsigned int endNode, float agentRadius, PathPlanner* planner) { PortalRoute* route = planner->getRoute(startNode, endNode, agentRadius * 2.f); if (_waypoints != 0x0) { delete[] _waypoints; _waypoints = 0x0; delete[] _headings; _headings = 0x0; } _currPortal = 0; _route = route; computeCrossing(startPos, agentRadius); } ///////////////////////////////////////////////////////////////////// Vector2 PortalPath::getWayPoint(size_t i) const { const size_t PORTAL_COUNT = _route->getPortalCount(); assert(i >= 0 && i < PORTAL_COUNT && "Invalid index into the path!"); return _waypoints[i]; } ///////////////////////////////////////////////////////////////////// unsigned int PortalPath::getNode(size_t i) const { const size_t PORTAL_COUNT = _route->getPortalCount(); assert(i >= 0 && i <= PORTAL_COUNT && "Invalid index into the path!"); if (i < PORTAL_COUNT) { return _route->getPortalNode(i); } else { return _route->getEndNode(); } } ///////////////////////////////////////////////////////////////////// void PortalPath::setWaypoints(size_t start, size_t end, const Vector2& p0, const Vector2& dir) { for (size_t i = start; i < end; ++i) { _waypoints[i].set(_route->getPortal(i)->intersectionPoint(p0, dir)); //_waypoints[ i ].set( p0 ); _headings[i].set(dir); } } ///////////////////////////////////////////////////////////////////// void PortalPath::updateCrossingFromMovingGoal(const Agents::BaseAgent& agent) { const size_t portal_count = _route->getPortalCount(); if (portal_count > 0 && _currPortal < portal_count) { // There's only work to be done if the agent is *not* in the same node as the goal; in other // words, if _currPortal is still heading to a valid portal. const BFSM::Goal& goal = *getGoal(); const size_t last_portal_idx = portal_count - 1; const WayPortal& last_portal = *_route->getPortal(last_portal_idx); const Vector2& last_waypoint = _waypoints[last_portal_idx]; // TODO: This purely local operation is not globally optimal. If there was originally a straight // line from the last waypoint through *multiple* prevous way portals, this won't update all // of those portals (i.e., instead of a *new* straight line, I put a kink in the straight // line). I considered using the _heading vectors to determine if sequential crossings are all // co-linear. However, that test is still insufficient. What I *really* need to do, for the // general solution, is a reverse Funnel algorithm. The goal is to only work my way backwards // until I've converged to the path already there. const Vector2& prev_waypoint = last_portal_idx > 0 ? _waypoints[last_portal_idx - 1] : agent._pos; // Description // Cases: // 1: current crossing point is all the way left (symmetrically for all the way right). // "Position" of the goal: // a. Projects onto the portal "left" of "all the way left" // X no change to funnel! // b. Projects onto the portal "right" of all the way left" // O Compute new crossing point from goal to penultimate waypoint. // 2: current crossing point is on the "interior" // a. Goal projects all the way left (or beyond) // X crossing point all the way left (or right) // b. Goal projects on "interior" of portal // Set the last waypoint crossing based on goal position and penultimate waypoint // To accomplish the above, I need the following: // 1. I need the current waypoint categorized from [0-1] based on the radius-truncated portal // length. // 2. I need the parameterization of the crossing point of goal -> penultimate point vis a vis // the clearance portal. // 3. Following cases // Waypoint | New Waypoint | Action // -----------+---------------+-------------- // <= 0 | <= 0 | Pick s = 0 (crossing point doesn't change) // <= 0 | > 0 | Pick min(new s, 1) // > 0, < 1 | <= 0 | Pick s = 0 end // > 0, < 1 | >= 1 | Pick s = 1 end // > 0, < 1 | > 0, < 1 | Pick new waypoint s // >= 1 | < 1 | Pick max(new s, 0) // >= 1 | >= 1 | Pick s = 1 (crossing point doesn't change) // The parameterization of the current crossing point w.r.t. the crossable extent of the // wayportal. const float s_wp = last_portal.clearanceParameter(last_waypoint, agent._radius); // A similar parameterization of the crossing point for connecting current goal position with // the penultimate way point position w.r.t. the crossable extent of the wayportal. const float s_new = last_portal.clearanceParameter(goal.getCentroid(), prev_waypoint, agent._radius); float s = 0; if (s_wp <= 0) { if (s_new <= 0) return; if (s_new > 0) s = std::min(s_new, 1.f); } else if (s_wp >= 1) { if (s_new >= 1) return; if (s_new < 1) s = std::max(s_new, 0.f); } else { s = std::max(std::min(s_new, 1.f), 0.f); } Vector2 new_way_point = last_portal.clearPoint(s, agent._radius); _waypoints[last_portal_idx] = new_way_point; _headings[last_portal_idx] = (new_way_point - prev_waypoint); _headings[last_portal_idx].normalize(); } } } // namespace MengeMongoose/MATLAB/mex_util/mex_get_options.cpp100-1000 #include "mongoose_mex.hpp" namespace Mongoose { #define MEX_STRUCT_READINT(F) returner->F = (Int) readField(matOptions, #F); #define MEX_STRUCT_READDOUBLE(F) returner->F = readField(matOptions, #F); #define MEX_STRUCT_READBOOL(F) returner->F = static_cast((readField(matOptions, #F) != 0.0)); #define MEX_STRUCT_READENUM(F,T) returner->F = (T) (readField(matOptions, #F)); EdgeCut_Options *mex_get_options ( const mxArray *matOptions ) { EdgeCut_Options *returner = EdgeCut_Options::create(); if(!returner) return NULL; if(matOptions == NULL) return returner; MEX_STRUCT_READINT(random_seed); MEX_STRUCT_READINT(coarsen_limit); MEX_STRUCT_READENUM(matching_strategy, MatchingStrategy); MEX_STRUCT_READBOOL(do_community_matching); MEX_STRUCT_READDOUBLE(high_degree_threshold); /** Guess Partitioning Options *******************************************/ MEX_STRUCT_READENUM(initial_cut_type, InitialEdgeCutType); /** Waterdance Options ***************************************************/ MEX_STRUCT_READINT(num_dances); /**** Fidducia-Mattheyes Options *****************************************/ MEX_STRUCT_READBOOL(use_FM); MEX_STRUCT_READINT(FM_search_depth); MEX_STRUCT_READINT(FM_consider_count); MEX_STRUCT_READINT(FM_max_num_refinements); /**** Quadratic Programming Options **************************************/ MEX_STRUCT_READBOOL(use_QP_gradproj); MEX_STRUCT_READDOUBLE(gradproj_tolerance); MEX_STRUCT_READINT(gradproj_iteration_limit); /** Final Partition Target Metrics ***************************************/ MEX_STRUCT_READDOUBLE(target_split); MEX_STRUCT_READDOUBLE(soft_split_tolerance); return returner; } } #include "souffle/CompiledSouffle.h" namespace functors { extern "C" { } } namespace souffle { static const RamDomain RAM_BIT_SHIFT_MASK = RAM_DOMAIN_SIZE - 1; struct t_btree_iii__0_1_2__111 { static constexpr Relation::arity_type Arity = 3; using t_tuple = Tuple; struct t_comparator_0{ int operator()(const t_tuple& a, const t_tuple& b) const { return (ramBitCast(a[0]) < ramBitCast(b[0])) ? -1 : (ramBitCast(a[0]) > ramBitCast(b[0])) ? 1 :((ramBitCast(a[1]) < ramBitCast(b[1])) ? -1 : (ramBitCast(a[1]) > ramBitCast(b[1])) ? 1 :((ramBitCast(a[2]) < ramBitCast(b[2])) ? -1 : (ramBitCast(a[2]) > ramBitCast(b[2])) ? 1 :(0))); } bool less(const t_tuple& a, const t_tuple& b) const { return (ramBitCast(a[0]) < ramBitCast(b[0]))|| ((ramBitCast(a[0]) == ramBitCast(b[0])) && ((ramBitCast(a[1]) < ramBitCast(b[1]))|| ((ramBitCast(a[1]) == ramBitCast(b[1])) && ((ramBitCast(a[2]) < ramBitCast(b[2])))))); } bool equal(const t_tuple& a, const t_tuple& b) const { return (ramBitCast(a[0]) == ramBitCast(b[0]))&&(ramBitCast(a[1]) == ramBitCast(b[1]))&&(ramBitCast(a[2]) == ramBitCast(b[2])); } }; using t_ind_0 = btree_set; t_ind_0 ind_0; using iterator = t_ind_0::iterator; struct context { t_ind_0::operation_hints hints_0_lower; t_ind_0::operation_hints hints_0_upper; }; context createContext() { return context(); } bool insert(const t_tuple& t) { context h; return insert(t, h); } bool insert(const t_tuple& t, context& h) { if (ind_0.insert(t, h.hints_0_lower)) { return true; } else return false; } bool insert(const RamDomain* ramDomain) { RamDomain data[3]; std::copy(ramDomain, ramDomain + 3, data); const t_tuple& tuple = reinterpret_cast(data); context h; return insert(tuple, h); } bool insert(RamDomain a0,RamDomain a1,RamDomain a2) { RamDomain data[3] = {a0,a1,a2}; return insert(data); } bool contains(const t_tuple& t, context& h) const { return ind_0.contains(t, h.hints_0_lower); } bool contains(const t_tuple& t) const { context h; return contains(t, h); } std::size_t size() const { return ind_0.size(); } iterator find(const t_tuple& t, context& h) const { return ind_0.find(t, h.hints_0_lower); } iterator find(const t_tuple& t) const { context h; return find(t, h); } range lowerUpperRange_000(const t_tuple& /* lower */, const t_tuple& /* upper */, context& /* h */) const { return range(ind_0.begin(),ind_0.end()); } range lowerUpperRange_000(const t_tuple& /* lower */, const t_tuple& /* upper */) const { return range(ind_0.begin(),ind_0.end()); } range lowerUpperRange_111(const t_tuple& lower, const t_tuple& upper, context& h) const { t_comparator_0 comparator; int cmp = comparator(lower, upper); if (cmp == 0) { auto pos = ind_0.find(lower, h.hints_0_lower); auto fin = ind_0.end(); if (pos != fin) {fin = pos; ++fin;} return make_range(pos, fin); } if (cmp > 0) { return make_range(ind_0.end(), ind_0.end()); } return make_range(ind_0.lower_bound(lower, h.hints_0_lower), ind_0.upper_bound(upper, h.hints_0_upper)); } range lowerUpperRange_111(const t_tuple& lower, const t_tuple& upper) const { context h; return lowerUpperRange_111(lower,upper,h); } bool empty() const { return ind_0.empty(); } std::vector> partition() const { return ind_0.getChunks(400); } void purge() { ind_0.clear(); } iterator begin() const { return ind_0.begin(); } iterator end() const { return ind_0.end(); } void printStatistics(std::ostream& o) const { o << " arity 3 direct b-tree index 0 lex-order [0,1,2]\n"; ind_0.printStats(o); } }; struct t_btree_i__0__1 { static constexpr Relation::arity_type Arity = 1; using t_tuple = Tuple; struct t_comparator_0{ int operator()(const t_tuple& a, const t_tuple& b) const { return (ramBitCast(a[0]) < ramBitCast(b[0])) ? -1 : (ramBitCast(a[0]) > ramBitCast(b[0])) ? 1 :(0); } bool less(const t_tuple& a, const t_tuple& b) const { return (ramBitCast(a[0]) < ramBitCast(b[0])); } bool equal(const t_tuple& a, const t_tuple& b) const { return (ramBitCast(a[0]) == ramBitCast(b[0])); } }; using t_ind_0 = btree_set; t_ind_0 ind_0; using iterator = t_ind_0::iterator; struct context { t_ind_0::operation_hints hints_0_lower; t_ind_0::operation_hints hints_0_upper; }; context createContext() { return context(); } bool insert(const t_tuple& t) { context h; return insert(t, h); } bool insert(const t_tuple& t, context& h) { if (ind_0.insert(t, h.hints_0_lower)) { return true; } else return false; } bool insert(const RamDomain* ramDomain) { RamDomain data[1]; std::copy(ramDomain, ramDomain + 1, data); const t_tuple& tuple = reinterpret_cast(data); context h; return insert(tuple, h); } bool insert(RamDomain a0) { RamDomain data[1] = {a0}; return insert(data); } bool contains(const t_tuple& t, context& h) const { return ind_0.contains(t, h.hints_0_lower); } bool contains(const t_tuple& t) const { context h; return contains(t, h); } std::size_t size() const { return ind_0.size(); } iterator find(const t_tuple& t, context& h) const { return ind_0.find(t, h.hints_0_lower); } iterator find(const t_tuple& t) const { context h; return find(t, h); } range lowerUpperRange_0(const t_tuple& /* lower */, const t_tuple& /* upper */, context& /* h */) const { return range(ind_0.begin(),ind_0.end()); } range lowerUpperRange_0(const t_tuple& /* lower */, const t_tuple& /* upper */) const { return range(ind_0.begin(),ind_0.end()); } range lowerUpperRange_1(const t_tuple& lower, const t_tuple& upper, context& h) const { t_comparator_0 comparator; int cmp = comparator(lower, upper); if (cmp == 0) { auto pos = ind_0.find(lower, h.hints_0_lower); auto fin = ind_0.end(); if (pos != fin) {fin = pos; ++fin;} return make_range(pos, fin); } if (cmp > 0) { return make_range(ind_0.end(), ind_0.end()); } return make_range(ind_0.lower_bound(lower, h.hints_0_lower), ind_0.upper_bound(upper, h.hints_0_upper)); } range lowerUpperRange_1(const t_tuple& lower, const t_tuple& upper) const { context h; return lowerUpperRange_1(lower,upper,h); } bool empty() const { return ind_0.empty(); } std::vector> partition() const { return ind_0.getChunks(400); } void purge() { ind_0.clear(); } iterator begin() const { return ind_0.begin(); } iterator end() const { return ind_0.end(); } void printStatistics(std::ostream& o) const { o << " arity 1 direct b-tree index 0 lex-order [0]\n"; ind_0.printStats(o); } }; struct t_btree_uif__0_1_2__111 { static constexpr Relation::arity_type Arity = 3; using t_tuple = Tuple; struct t_comparator_0{ int operator()(const t_tuple& a, const t_tuple& b) const { return (ramBitCast(a[0]) < ramBitCast(b[0])) ? -1 : (ramBitCast(a[0]) > ramBitCast(b[0])) ? 1 :((ramBitCast(a[1]) < ramBitCast(b[1])) ? -1 : (ramBitCast(a[1]) > ramBitCast(b[1])) ? 1 :((ramBitCast(a[2]) < ramBitCast(b[2])) ? -1 : (ramBitCast(a[2]) > ramBitCast(b[2])) ? 1 :(0))); } bool less(const t_tuple& a, const t_tuple& b) const { return (ramBitCast(a[0]) < ramBitCast(b[0]))|| ((ramBitCast(a[0]) == ramBitCast(b[0])) && ((ramBitCast(a[1]) < ramBitCast(b[1]))|| ((ramBitCast(a[1]) == ramBitCast(b[1])) && ((ramBitCast(a[2]) < ramBitCast(b[2])))))); } bool equal(const t_tuple& a, const t_tuple& b) const { return (ramBitCast(a[0]) == ramBitCast(b[0]))&&(ramBitCast(a[1]) == ramBitCast(b[1]))&&(ramBitCast(a[2]) == ramBitCast(b[2])); } }; using t_ind_0 = btree_set; t_ind_0 ind_0; using iterator = t_ind_0::iterator; struct context { t_ind_0::operation_hints hints_0_lower; t_ind_0::operation_hints hints_0_upper; }; context createContext() { return context(); } bool insert(const t_tuple& t) { context h; return insert(t, h); } bool insert(const t_tuple& t, context& h) { if (ind_0.insert(t, h.hints_0_lower)) { return true; } else return false; } bool insert(const RamDomain* ramDomain) { RamDomain data[3]; std::copy(ramDomain, ramDomain + 3, data); const t_tuple& tuple = reinterpret_cast(data); context h; return insert(tuple, h); } bool insert(RamDomain a0,RamDomain a1,RamDomain a2) { RamDomain data[3] = {a0,a1,a2}; return insert(data); } bool contains(const t_tuple& t, context& h) const { return ind_0.contains(t, h.hints_0_lower); } bool contains(const t_tuple& t) const { context h; return contains(t, h); } std::size_t size() const { return ind_0.size(); } iterator find(const t_tuple& t, context& h) const { return ind_0.find(t, h.hints_0_lower); } iterator find(const t_tuple& t) const { context h; return find(t, h); } range lowerUpperRange_000(const t_tuple& /* lower */, const t_tuple& /* upper */, context& /* h */) const { return range(ind_0.begin(),ind_0.end()); } range lowerUpperRange_000(const t_tuple& /* lower */, const t_tuple& /* upper */) const { return range(ind_0.begin(),ind_0.end()); } range lowerUpperRange_111(const t_tuple& lower, const t_tuple& upper, context& h) const { t_comparator_0 comparator; int cmp = comparator(lower, upper); if (cmp == 0) { auto pos = ind_0.find(lower, h.hints_0_lower); auto fin = ind_0.end(); if (pos != fin) {fin = pos; ++fin;} return make_range(pos, fin); } if (cmp > 0) { return make_range(ind_0.end(), ind_0.end()); } return make_range(ind_0.lower_bound(lower, h.hints_0_lower), ind_0.upper_bound(upper, h.hints_0_upper)); } range lowerUpperRange_111(const t_tuple& lower, const t_tuple& upper) const { context h; return lowerUpperRange_111(lower,upper,h); } bool empty() const { return ind_0.empty(); } std::vector> partition() const { return ind_0.getChunks(400); } void purge() { ind_0.clear(); } iterator begin() const { return ind_0.begin(); } iterator end() const { return ind_0.end(); } void printStatistics(std::ostream& o) const { o << " arity 3 direct b-tree index 0 lex-order [0,1,2]\n"; ind_0.printStats(o); } }; class Sf_edge_cases : public SouffleProgram { private: static inline std::string substr_wrapper(const std::string& str, std::size_t idx, std::size_t len) { std::string result; try { result = str.substr(idx,len); } catch(...) { std::cerr << "warning: wrong index position provided by substr(\""; std::cerr << str << "\"," << (int32_t)idx << "," << (int32_t)len << ") functor.\n"; } return result; } public: // -- initialize symbol table -- SymbolTableImpl symTable{ R"_()_", R"_(abc)_", R"_(long_string_from_DL:...............................................................................................................................................................................................................................................................................................end)_", R"_(∀)_", R"_(∀∀)_", };// -- initialize record table -- SpecializedRecordTable<0> recordTable{}; // -- Table: empty_strings Own rel_1_empty_strings = mk(); souffle::RelationWrapper wrapper_rel_1_empty_strings; // -- Table: long_strings Own rel_2_long_strings = mk(); souffle::RelationWrapper wrapper_rel_2_long_strings; // -- Table: no_strings Own rel_3_no_strings = mk(); souffle::RelationWrapper wrapper_rel_3_no_strings; // -- Table: unicode Own rel_4_unicode = mk(); souffle::RelationWrapper wrapper_rel_4_unicode; public: Sf_edge_cases() : wrapper_rel_1_empty_strings(0, *rel_1_empty_strings, *this, "empty_strings", std::array{{"s:symbol","s:symbol","i:number"}}, std::array{{"s","s2","n"}}, 0) , wrapper_rel_2_long_strings(1, *rel_2_long_strings, *this, "long_strings", std::array{{"s:symbol"}}, std::array{{"s"}}, 0) , wrapper_rel_3_no_strings(2, *rel_3_no_strings, *this, "no_strings", std::array{{"u:unsigned","i:number","f:float"}}, std::array{{"u","n","f"}}, 0) , wrapper_rel_4_unicode(3, *rel_4_unicode, *this, "unicode", std::array{{"s:symbol"}}, std::array{{"s"}}, 0) { addRelation("empty_strings", wrapper_rel_1_empty_strings, true, true); addRelation("long_strings", wrapper_rel_2_long_strings, true, true); addRelation("no_strings", wrapper_rel_3_no_strings, true, true); addRelation("unicode", wrapper_rel_4_unicode, true, true); } ~Sf_edge_cases() { } private: std::string inputDirectory; std::string outputDirectory; SignalHandler* signalHandler {SignalHandler::instance()}; std::atomic ctr {}; std::atomic iter {}; void runFunction(std::string inputDirectoryArg, std::string outputDirectoryArg, bool performIOArg, bool pruneImdtRelsArg) { this->inputDirectory = std::move(inputDirectoryArg); this->outputDirectory = std::move(outputDirectoryArg); this->performIO = performIOArg; this->pruneImdtRels = pruneImdtRelsArg; // set default threads (in embedded mode) // if this is not set, and omp is used, the default omp setting of number of cores is used. #if defined(_OPENMP) if (0 < getNumThreads()) { omp_set_num_threads(static_cast(getNumThreads())); } #endif signalHandler->set(); // -- query evaluation -- { std::vector args, ret; subroutine_0(args, ret); } { std::vector args, ret; subroutine_1(args, ret); } { std::vector args, ret; subroutine_2(args, ret); } { std::vector args, ret; subroutine_3(args, ret); } // -- relation hint statistics -- signalHandler->reset(); } public: void run() override { runFunction("", "", false, false); } public: void runAll(std::string inputDirectoryArg = "", std::string outputDirectoryArg = "", bool performIOArg=true, bool pruneImdtRelsArg=true) override { runFunction(inputDirectoryArg, outputDirectoryArg, performIOArg, pruneImdtRelsArg); } public: void printAll(std::string outputDirectoryArg = "") override { try {std::map directiveMap({{"IO","file"},{"attributeNames","s"},{"auxArity","0"},{"name","long_strings"},{"operation","output"},{"output-dir","."},{"params","{\"records\": {}, \"relation\": {\"arity\": 1, \"params\": [\"s\"]}}"},{"types","{\"ADTs\": {}, \"records\": {}, \"relation\": {\"arity\": 1, \"types\": [\"s:symbol\"]}}"}}); if (!outputDirectoryArg.empty()) {directiveMap["output-dir"] = outputDirectoryArg;} IOSystem::getInstance().getWriter(directiveMap, symTable, recordTable)->writeAll(*rel_2_long_strings); } catch (std::exception& e) {std::cerr << e.what();exit(1);} try {std::map directiveMap({{"IO","file"},{"attributeNames","s"},{"auxArity","0"},{"name","unicode"},{"operation","output"},{"output-dir","."},{"params","{\"records\": {}, \"relation\": {\"arity\": 1, \"params\": [\"s\"]}}"},{"types","{\"ADTs\": {}, \"records\": {}, \"relation\": {\"arity\": 1, \"types\": [\"s:symbol\"]}}"}}); if (!outputDirectoryArg.empty()) {directiveMap["output-dir"] = outputDirectoryArg;} IOSystem::getInstance().getWriter(directiveMap, symTable, recordTable)->writeAll(*rel_4_unicode); } catch (std::exception& e) {std::cerr << e.what();exit(1);} try {std::map directiveMap({{"IO","file"},{"attributeNames","s\ts2\tn"},{"auxArity","0"},{"name","empty_strings"},{"operation","output"},{"output-dir","."},{"params","{\"records\": {}, \"relation\": {\"arity\": 3, \"params\": [\"s\", \"s2\", \"n\"]}}"},{"types","{\"ADTs\": {}, \"records\": {}, \"relation\": {\"arity\": 3, \"types\": [\"s:symbol\", \"s:symbol\", \"i:number\"]}}"}}); if (!outputDirectoryArg.empty()) {directiveMap["output-dir"] = outputDirectoryArg;} IOSystem::getInstance().getWriter(directiveMap, symTable, recordTable)->writeAll(*rel_1_empty_strings); } catch (std::exception& e) {std::cerr << e.what();exit(1);} try {std::map directiveMap({{"IO","file"},{"attributeNames","u\tn\tf"},{"auxArity","0"},{"name","no_strings"},{"operation","output"},{"output-dir","."},{"params","{\"records\": {}, \"relation\": {\"arity\": 3, \"params\": [\"u\", \"n\", \"f\"]}}"},{"types","{\"ADTs\": {}, \"records\": {}, \"relation\": {\"arity\": 3, \"types\": [\"u:unsigned\", \"i:number\", \"f:float\"]}}"}}); if (!outputDirectoryArg.empty()) {directiveMap["output-dir"] = outputDirectoryArg;} IOSystem::getInstance().getWriter(directiveMap, symTable, recordTable)->writeAll(*rel_3_no_strings); } catch (std::exception& e) {std::cerr << e.what();exit(1);} } public: void loadAll(std::string inputDirectoryArg = "") override { try {std::map directiveMap({{"IO","file"},{"attributeNames","u\tn\tf"},{"auxArity","0"},{"fact-dir","."},{"name","no_strings"},{"operation","input"},{"params","{\"records\": {}, \"relation\": {\"arity\": 3, \"params\": [\"u\", \"n\", \"f\"]}}"},{"types","{\"ADTs\": {}, \"records\": {}, \"relation\": {\"arity\": 3, \"types\": [\"u:unsigned\", \"i:number\", \"f:float\"]}}"}}); if (!inputDirectoryArg.empty()) {directiveMap["fact-dir"] = inputDirectoryArg;} IOSystem::getInstance().getReader(directiveMap, symTable, recordTable)->readAll(*rel_3_no_strings); } catch (std::exception& e) {std::cerr << "Error loading no_strings data: " << e.what() << '\n';} try {std::map directiveMap({{"IO","file"},{"attributeNames","s\ts2\tn"},{"auxArity","0"},{"fact-dir","."},{"name","empty_strings"},{"operation","input"},{"params","{\"records\": {}, \"relation\": {\"arity\": 3, \"params\": [\"s\", \"s2\", \"n\"]}}"},{"types","{\"ADTs\": {}, \"records\": {}, \"relation\": {\"arity\": 3, \"types\": [\"s:symbol\", \"s:symbol\", \"i:number\"]}}"}}); if (!inputDirectoryArg.empty()) {directiveMap["fact-dir"] = inputDirectoryArg;} IOSystem::getInstance().getReader(directiveMap, symTable, recordTable)->readAll(*rel_1_empty_strings); } catch (std::exception& e) {std::cerr << "Error loading empty_strings data: " << e.what() << '\n';} try {std::map directiveMap({{"IO","file"},{"attributeNames","s"},{"auxArity","0"},{"fact-dir","."},{"name","unicode"},{"operation","input"},{"params","{\"records\": {}, \"relation\": {\"arity\": 1, \"params\": [\"s\"]}}"},{"types","{\"ADTs\": {}, \"records\": {}, \"relation\": {\"arity\": 1, \"types\": [\"s:symbol\"]}}"}}); if (!inputDirectoryArg.empty()) {directiveMap["fact-dir"] = inputDirectoryArg;} IOSystem::getInstance().getReader(directiveMap, symTable, recordTable)->readAll(*rel_4_unicode); } catch (std::exception& e) {std::cerr << "Error loading unicode data: " << e.what() << '\n';} try {std::map directiveMap({{"IO","file"},{"attributeNames","s"},{"auxArity","0"},{"fact-dir","."},{"name","long_strings"},{"operation","input"},{"params","{\"records\": {}, \"relation\": {\"arity\": 1, \"params\": [\"s\"]}}"},{"types","{\"ADTs\": {}, \"records\": {}, \"relation\": {\"arity\": 1, \"types\": [\"s:symbol\"]}}"}}); if (!inputDirectoryArg.empty()) {directiveMap["fact-dir"] = inputDirectoryArg;} IOSystem::getInstance().getReader(directiveMap, symTable, recordTable)->readAll(*rel_2_long_strings); } catch (std::exception& e) {std::cerr << "Error loading long_strings data: " << e.what() << '\n';} } public: void dumpInputs() override { try {std::map rwOperation; rwOperation["IO"] = "stdout"; rwOperation["name"] = "no_strings"; rwOperation["types"] = "{\"relation\": {\"arity\": 3, \"auxArity\": 0, \"types\": [\"u:unsigned\", \"i:number\", \"f:float\"]}}"; IOSystem::getInstance().getWriter(rwOperation, symTable, recordTable)->writeAll(*rel_3_no_strings); } catch (std::exception& e) {std::cerr << e.what();exit(1);} try {std::map rwOperation; rwOperation["IO"] = "stdout"; rwOperation["name"] = "empty_strings"; rwOperation["types"] = "{\"relation\": {\"arity\": 3, \"auxArity\": 0, \"types\": [\"s:symbol\", \"s:symbol\", \"i:number\"]}}"; IOSystem::getInstance().getWriter(rwOperation, symTable, recordTable)->writeAll(*rel_1_empty_strings); } catch (std::exception& e) {std::cerr << e.what();exit(1);} try {std::map rwOperation; rwOperation["IO"] = "stdout"; rwOperation["name"] = "unicode"; rwOperation["types"] = "{\"relation\": {\"arity\": 1, \"auxArity\": 0, \"types\": [\"s:symbol\"]}}"; IOSystem::getInstance().getWriter(rwOperation, symTable, recordTable)->writeAll(*rel_4_unicode); } catch (std::exception& e) {std::cerr << e.what();exit(1);} try {std::map rwOperation; rwOperation["IO"] = "stdout"; rwOperation["name"] = "long_strings"; rwOperation["types"] = "{\"relation\": {\"arity\": 1, \"auxArity\": 0, \"types\": [\"s:symbol\"]}}"; IOSystem::getInstance().getWriter(rwOperation, symTable, recordTable)->writeAll(*rel_2_long_strings); } catch (std::exception& e) {std::cerr << e.what();exit(1);} } public: void dumpOutputs() override { try {std::map rwOperation; rwOperation["IO"] = "stdout"; rwOperation["name"] = "long_strings"; rwOperation["types"] = "{\"relation\": {\"arity\": 1, \"auxArity\": 0, \"types\": [\"s:symbol\"]}}"; IOSystem::getInstance().getWriter(rwOperation, symTable, recordTable)->writeAll(*rel_2_long_strings); } catch (std::exception& e) {std::cerr << e.what();exit(1);} try {std::map rwOperation; rwOperation["IO"] = "stdout"; rwOperation["name"] = "unicode"; rwOperation["types"] = "{\"relation\": {\"arity\": 1, \"auxArity\": 0, \"types\": [\"s:symbol\"]}}"; IOSystem::getInstance().getWriter(rwOperation, symTable, recordTable)->writeAll(*rel_4_unicode); } catch (std::exception& e) {std::cerr << e.what();exit(1);} try {std::map rwOperation; rwOperation["IO"] = "stdout"; rwOperation["name"] = "empty_strings"; rwOperation["types"] = "{\"relation\": {\"arity\": 3, \"auxArity\": 0, \"types\": [\"s:symbol\", \"s:symbol\", \"i:number\"]}}"; IOSystem::getInstance().getWriter(rwOperation, symTable, recordTable)->writeAll(*rel_1_empty_strings); } catch (std::exception& e) {std::cerr << e.what();exit(1);} try {std::map rwOperation; rwOperation["IO"] = "stdout"; rwOperation["name"] = "no_strings"; rwOperation["types"] = "{\"relation\": {\"arity\": 3, \"auxArity\": 0, \"types\": [\"u:unsigned\", \"i:number\", \"f:float\"]}}"; IOSystem::getInstance().getWriter(rwOperation, symTable, recordTable)->writeAll(*rel_3_no_strings); } catch (std::exception& e) {std::cerr << e.what();exit(1);} } public: SymbolTable& getSymbolTable() override { return symTable; } RecordTable& getRecordTable() override { return recordTable; } void setNumThreads(std::size_t numThreadsValue) override { SouffleProgram::setNumThreads(numThreadsValue); symTable.setNumLanes(getNumThreads()); recordTable.setNumLanes(getNumThreads()); } void executeSubroutine(std::string name, const std::vector& args, std::vector& ret) override { if (name == "stratum_0") { subroutine_0(args, ret); return;} if (name == "stratum_1") { subroutine_1(args, ret); return;} if (name == "stratum_2") { subroutine_2(args, ret); return;} if (name == "stratum_3") { subroutine_3(args, ret); return;} fatal("unknown subroutine"); } #ifdef _MSC_VER #pragma warning(disable: 4100) #endif // _MSC_VER void subroutine_0(const std::vector& args, std::vector& ret) { if (performIO) { try {std::map directiveMap({{"IO","file"},{"attributeNames","s\ts2\tn"},{"auxArity","0"},{"fact-dir","."},{"name","empty_strings"},{"operation","input"},{"params","{\"records\": {}, \"relation\": {\"arity\": 3, \"params\": [\"s\", \"s2\", \"n\"]}}"},{"types","{\"ADTs\": {}, \"records\": {}, \"relation\": {\"arity\": 3, \"types\": [\"s:symbol\", \"s:symbol\", \"i:number\"]}}"}}); if (!inputDirectory.empty()) {directiveMap["fact-dir"] = inputDirectory;} IOSystem::getInstance().getReader(directiveMap, symTable, recordTable)->readAll(*rel_1_empty_strings); } catch (std::exception& e) {std::cerr << "Error loading empty_strings data: " << e.what() << '\n';} } signalHandler->setMsg(R"_(empty_strings("","",42). in file edge_cases.dl [20:1-20:27])_"); [&](){ CREATE_OP_CONTEXT(rel_1_empty_strings_op_ctxt,rel_1_empty_strings->createContext()); Tuple tuple{{ramBitCast(RamSigned(0)),ramBitCast(RamSigned(0)),ramBitCast(RamSigned(42))}}; rel_1_empty_strings->insert(tuple,READ_OP_CONTEXT(rel_1_empty_strings_op_ctxt)); } ();signalHandler->setMsg(R"_(empty_strings("","abc",42). in file edge_cases.dl [21:1-21:30])_"); [&](){ CREATE_OP_CONTEXT(rel_1_empty_strings_op_ctxt,rel_1_empty_strings->createContext()); Tuple tuple{{ramBitCast(RamSigned(0)),ramBitCast(RamSigned(1)),ramBitCast(RamSigned(42))}}; rel_1_empty_strings->insert(tuple,READ_OP_CONTEXT(rel_1_empty_strings_op_ctxt)); } ();signalHandler->setMsg(R"_(empty_strings("abc","",42). in file edge_cases.dl [22:1-22:30])_"); [&](){ CREATE_OP_CONTEXT(rel_1_empty_strings_op_ctxt,rel_1_empty_strings->createContext()); Tuple tuple{{ramBitCast(RamSigned(1)),ramBitCast(RamSigned(0)),ramBitCast(RamSigned(42))}}; rel_1_empty_strings->insert(tuple,READ_OP_CONTEXT(rel_1_empty_strings_op_ctxt)); } ();if (performIO) { try {std::map directiveMap({{"IO","file"},{"attributeNames","s\ts2\tn"},{"auxArity","0"},{"name","empty_strings"},{"operation","output"},{"output-dir","."},{"params","{\"records\": {}, \"relation\": {\"arity\": 3, \"params\": [\"s\", \"s2\", \"n\"]}}"},{"types","{\"ADTs\": {}, \"records\": {}, \"relation\": {\"arity\": 3, \"types\": [\"s:symbol\", \"s:symbol\", \"i:number\"]}}"}}); if (!outputDirectory.empty()) {directiveMap["output-dir"] = outputDirectory;} IOSystem::getInstance().getWriter(directiveMap, symTable, recordTable)->writeAll(*rel_1_empty_strings); } catch (std::exception& e) {std::cerr << e.what();exit(1);} } } #ifdef _MSC_VER #pragma warning(default: 4100) #endif // _MSC_VER #ifdef _MSC_VER #pragma warning(disable: 4100) #endif // _MSC_VER void subroutine_1(const std::vector& args, std::vector& ret) { if (performIO) { try {std::map directiveMap({{"IO","file"},{"attributeNames","s"},{"auxArity","0"},{"fact-dir","."},{"name","long_strings"},{"operation","input"},{"params","{\"records\": {}, \"relation\": {\"arity\": 1, \"params\": [\"s\"]}}"},{"types","{\"ADTs\": {}, \"records\": {}, \"relation\": {\"arity\": 1, \"types\": [\"s:symbol\"]}}"}}); if (!inputDirectory.empty()) {directiveMap["fact-dir"] = inputDirectory;} IOSystem::getInstance().getReader(directiveMap, symTable, recordTable)->readAll(*rel_2_long_strings); } catch (std::exception& e) {std::cerr << "Error loading long_strings data: " << e.what() << '\n';} } signalHandler->setMsg(R"_(long_strings("long_string_from_DL:...............................................................................................................................................................................................................................................................................................end"). in file edge_cases.dl [25:1-25:328])_"); [&](){ CREATE_OP_CONTEXT(rel_2_long_strings_op_ctxt,rel_2_long_strings->createContext()); Tuple tuple{{ramBitCast(RamSigned(2))}}; rel_2_long_strings->insert(tuple,READ_OP_CONTEXT(rel_2_long_strings_op_ctxt)); } ();if (performIO) { try {std::map directiveMap({{"IO","file"},{"attributeNames","s"},{"auxArity","0"},{"name","long_strings"},{"operation","output"},{"output-dir","."},{"params","{\"records\": {}, \"relation\": {\"arity\": 1, \"params\": [\"s\"]}}"},{"types","{\"ADTs\": {}, \"records\": {}, \"relation\": {\"arity\": 1, \"types\": [\"s:symbol\"]}}"}}); if (!outputDirectory.empty()) {directiveMap["output-dir"] = outputDirectory;} IOSystem::getInstance().getWriter(directiveMap, symTable, recordTable)->writeAll(*rel_2_long_strings); } catch (std::exception& e) {std::cerr << e.what();exit(1);} } } #ifdef _MSC_VER #pragma warning(default: 4100) #endif // _MSC_VER #ifdef _MSC_VER #pragma warning(disable: 4100) #endif // _MSC_VER void subroutine_2(const std::vector& args, std::vector& ret) { if (performIO) { try {std::map directiveMap({{"IO","file"},{"attributeNames","u\tn\tf"},{"auxArity","0"},{"fact-dir","."},{"name","no_strings"},{"operation","input"},{"params","{\"records\": {}, \"relation\": {\"arity\": 3, \"params\": [\"u\", \"n\", \"f\"]}}"},{"types","{\"ADTs\": {}, \"records\": {}, \"relation\": {\"arity\": 3, \"types\": [\"u:unsigned\", \"i:number\", \"f:float\"]}}"}}); if (!inputDirectory.empty()) {directiveMap["fact-dir"] = inputDirectory;} IOSystem::getInstance().getReader(directiveMap, symTable, recordTable)->readAll(*rel_3_no_strings); } catch (std::exception& e) {std::cerr << "Error loading no_strings data: " << e.what() << '\n';} } signalHandler->setMsg(R"_(no_strings(42,-100,1.5). in file edge_cases.dl [33:1-33:27])_"); [&](){ CREATE_OP_CONTEXT(rel_3_no_strings_op_ctxt,rel_3_no_strings->createContext()); Tuple tuple{{ramBitCast(RamUnsigned(42)),ramBitCast(RamSigned(-100)),ramBitCast(RamFloat(1.5))}}; rel_3_no_strings->insert(tuple,READ_OP_CONTEXT(rel_3_no_strings_op_ctxt)); } ();signalHandler->setMsg(R"_(no_strings(123,-456,3.14). in file edge_cases.dl [34:1-34:29])_"); [&](){ CREATE_OP_CONTEXT(rel_3_no_strings_op_ctxt,rel_3_no_strings->createContext()); Tuple tuple{{ramBitCast(RamUnsigned(123)),ramBitCast(RamSigned(-456)),ramBitCast(RamFloat(3.1400001))}}; rel_3_no_strings->insert(tuple,READ_OP_CONTEXT(rel_3_no_strings_op_ctxt)); } ();if (performIO) { try {std::map directiveMap({{"IO","file"},{"attributeNames","u\tn\tf"},{"auxArity","0"},{"name","no_strings"},{"operation","output"},{"output-dir","."},{"params","{\"records\": {}, \"relation\": {\"arity\": 3, \"params\": [\"u\", \"n\", \"f\"]}}"},{"types","{\"ADTs\": {}, \"records\": {}, \"relation\": {\"arity\": 3, \"types\": [\"u:unsigned\", \"i:number\", \"f:float\"]}}"}}); if (!outputDirectory.empty()) {directiveMap["output-dir"] = outputDirectory;} IOSystem::getInstance().getWriter(directiveMap, symTable, recordTable)->writeAll(*rel_3_no_strings); } catch (std::exception& e) {std::cerr << e.what();exit(1);} } } #ifdef _MSC_VER #pragma warning(default: 4100) #endif // _MSC_VER #ifdef _MSC_VER #pragma warning(disable: 4100) #endif // _MSC_VER void subroutine_3(const std::vector& args, std::vector& ret) { if (performIO) { try {std::map directiveMap({{"IO","file"},{"attributeNames","s"},{"auxArity","0"},{"fact-dir","."},{"name","unicode"},{"operation","input"},{"params","{\"records\": {}, \"relation\": {\"arity\": 1, \"params\": [\"s\"]}}"},{"types","{\"ADTs\": {}, \"records\": {}, \"relation\": {\"arity\": 1, \"types\": [\"s:symbol\"]}}"}}); if (!inputDirectory.empty()) {directiveMap["fact-dir"] = inputDirectory;} IOSystem::getInstance().getReader(directiveMap, symTable, recordTable)->readAll(*rel_4_unicode); } catch (std::exception& e) {std::cerr << "Error loading unicode data: " << e.what() << '\n';} } signalHandler->setMsg(R"_(unicode("∀"). in file edge_cases.dl [30:1-30:16])_"); [&](){ CREATE_OP_CONTEXT(rel_4_unicode_op_ctxt,rel_4_unicode->createContext()); Tuple tuple{{ramBitCast(RamSigned(3))}}; rel_4_unicode->insert(tuple,READ_OP_CONTEXT(rel_4_unicode_op_ctxt)); } ();signalHandler->setMsg(R"_(unicode("∀∀"). in file edge_cases.dl [31:1-31:19])_"); [&](){ CREATE_OP_CONTEXT(rel_4_unicode_op_ctxt,rel_4_unicode->createContext()); Tuple tuple{{ramBitCast(RamSigned(4))}}; rel_4_unicode->insert(tuple,READ_OP_CONTEXT(rel_4_unicode_op_ctxt)); } ();if (performIO) { try {std::map directiveMap({{"IO","file"},{"attributeNames","s"},{"auxArity","0"},{"name","unicode"},{"operation","output"},{"output-dir","."},{"params","{\"records\": {}, \"relation\": {\"arity\": 1, \"params\": [\"s\"]}}"},{"types","{\"ADTs\": {}, \"records\": {}, \"relation\": {\"arity\": 1, \"types\": [\"s:symbol\"]}}"}}); if (!outputDirectory.empty()) {directiveMap["output-dir"] = outputDirectory;} IOSystem::getInstance().getWriter(directiveMap, symTable, recordTable)->writeAll(*rel_4_unicode); } catch (std::exception& e) {std::cerr << e.what();exit(1);} } } #ifdef _MSC_VER #pragma warning(default: 4100) #endif // _MSC_VER }; SouffleProgram *newInstance_edge_cases(){return new Sf_edge_cases;} SymbolTable *getST_edge_cases(SouffleProgram *p){return &reinterpret_cast(p)->getSymbolTable();} #ifdef __EMBEDDED_SOUFFLE__ class factory_Sf_edge_cases: public souffle::ProgramFactory { SouffleProgram *newInstance() { return new Sf_edge_cases(); }; public: factory_Sf_edge_cases() : ProgramFactory("edge_cases"){} }; extern "C" { factory_Sf_edge_cases __factory_Sf_edge_cases_instance; } } #else } int main(int argc, char** argv) { try{ souffle::CmdOptions opt(R"(edge_cases.dl)", R"()", R"()", false, R"()", 1); if (!opt.parse(argc,argv)) return 1; souffle::Sf_edge_cases obj; #if defined(_OPENMP) obj.setNumThreads(opt.getNumJobs()); #endif obj.runAll(opt.getInputFileDir(), opt.getOutputFileDir()); return 0; } catch(std::exception &e) { souffle::SignalHandler::instance()->error(e.what());} } #endif haukkagu/friday #include "SaveCommand.h" #include "Utils.h" SaveCommand::SaveCommand() : ICommand("save") { } void SaveCommand::execute(const std::vector& arguments, TerminalContext& context) { saveContext(context); } #include "SkyboxRenderer.h" #include #include "ResourceManager.h" #include "MeshFactory.h" #include "ShaderFactory.h" #include "CubemapFactory.h" SkyboxRenderer::SkyboxRenderer(Camera* camera) : Renderer(camera), m_cubeMesh(nullptr), m_skyboxShader(nullptr), m_skyboxCubemap(nullptr) { ResourceManager::bind("skybox", "models/cube.obj"); ResourceManager::bind("skybox", "shaders/skybox.vert", "shaders/skybox.frag"); ResourceManager::bind("skybox", std::vector({ "textures/posx.png", "textures/negx.png", "textures/posy.png", "textures/negy.png", "textures/posz.png", "textures/negz.png" })); m_cubeMesh = ResourceManager::get("skybox"); m_skyboxShader = ResourceManager::get("skybox"); m_skyboxCubemap = ResourceManager::get("skybox"); m_skyboxShader->setAttribute(0, "vPosition"); m_skyboxShader->setAttribute(1, "vTextureCoords"); m_skyboxShader->bind(); m_skyboxShader->setUniform("diffuseTexture", 0); m_skyboxShader->unbind(); } void SkyboxRenderer::draw() { if (m_camera == nullptr || m_skyboxCubemap == nullptr) { return; } m_skyboxShader->bind(); m_skyboxShader->setUniform("cameraRotation", m_camera->getRotationMatrix()); m_skyboxShader->setUniform("cameraProjection", m_camera->getProjection()); glDisable(GL_CULL_FACE); glDepthFunc(GL_LEQUAL); m_skyboxCubemap->bind(0); m_cubeMesh->draw(); m_skyboxCubemap->unbind(); glDepthFunc(GL_LESS); glEnable(GL_CULL_FACE); m_skyboxShader->unbind(); } void SkyboxRenderer::setSkybox(Cubemap * cubemap) { m_skyboxCubemap = cubemap; } Cubemap * SkyboxRenderer::getSkybox() { return m_skyboxCubemap; } #pragma once #include "gradient.hpp" #include "mean_slope.hpp" #include #include "semantic_version.h" #include #include namespace { std::string_view ExtractSuffixData( std::string_view& strView, char separator ) { std::string_view data; if ( size_t pos = strView.find_first_of( separator ); std::string::npos != pos ) { data = strView.substr( pos + 1 ); strView.remove_suffix( strView.size() - pos ); } return data; } } // namespace namespace qwr { SemVer::SemVer( const std::string& strVer ) { const auto ret = ParseString( strVer ); if ( !ret ) { throw std::runtime_error( "Parsing failed" ); } *this = *ret; } std::optional SemVer::ParseString( const std::string& strVer ) { SemVer semVer; std::string_view curScope( strVer ); semVer.metadata = ExtractSuffixData( curScope, '+' ); semVer.prerelease = ExtractSuffixData( curScope, '-' ); if ( curScope.empty() ) { return std::nullopt; } std::vector> versionNums; for ( const auto& splitView: qwr::string::Split( curScope, '.' ) ) { const auto numRet = qwr::string::GetNumber( splitView ); if ( !numRet ) { return std::nullopt; } versionNums.emplace_back( numRet ); } if ( versionNums.empty() || versionNums.size() > 3 ) { return std::nullopt; } versionNums.resize( 3 ); semVer.major = *versionNums[0]; semVer.minor = versionNums[1].value_or( 0 ); semVer.patch = versionNums[2].value_or( 0 ); return semVer; } bool SemVer::operator==( const SemVer& other ) const { // metadata is ignored during comparison return ( major == other.major && minor == other.minor && patch == other.patch && prerelease == other.prerelease ); } bool SemVer::operator!=( const SemVer& other ) const { return ( !( *this == other ) ); } bool SemVer::operator<( const SemVer& other ) const { if ( major != other.major ) { return ( major < other.major ); } if ( minor != other.minor ) { return ( minor < other.minor ); } if ( patch != other.patch ) { return ( patch < other.patch ); } // metadata is ignored during comparison return IsPreleaseNewer( other.prerelease, prerelease ); } bool SemVer::operator>( const SemVer& other ) const { return ( other < *this ); } bool SemVer::operator<=( const SemVer& other ) const { return ( !( other < *this ) ); } bool SemVer::operator>=( const SemVer& other ) const { return ( !( *this < other ) ); } bool SemVer::IsPreleaseNewer( std::string_view a, std::string_view b ) { if ( a == b ) { return false; } if ( a.empty() || b.empty() ) { // Pre-release versions have a lower precedence than the associated normal version return a.empty(); } const auto isNumber = []( std::string_view str ) { return ( str.cend() == ranges::find_if_not( str, []( char c ) { return std::isdigit( c ); } ) ); }; while ( !a.empty() && !b.empty() ) { const std::string_view a_Token = ExtractSuffixData( a, '.' ); const std::string_view b_Token = ExtractSuffixData( b, '.' ); if ( a_Token != b_Token ) { const bool a_isNumber = isNumber( a_Token ); const bool b_isNumber = isNumber( b_Token ); if ( a_isNumber != b_isNumber ) { // Numeric identifiers always have lower precedence than non-numeric identifiers return !a_isNumber; } else if ( a_isNumber && b_isNumber ) { auto numRet = qwr::string::GetNumber( a_Token ); assert( numRet ); // should be valid, because of `isNumber` check const int8_t aNum = *numRet; numRet = qwr::string::GetNumber( a_Token ); assert( numRet ); // should be valid, because of `isNumber` check const int8_t bNum = *numRet; assert( aNum != bNum ); // tokens would've been equal otherwise return aNum > bNum; } else { return a_Token > b_Token; } } else { if ( a.empty() != b.empty() ) { // A larger set of pre-release fields has a higher precedence than a smaller set return !a.empty(); } } } // They are equal (should not reach here) assert( 0 ); return false; } } // namespace qwr ash/wm/video_detector_unittest.cc100-1000 // Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ash/wm/video_detector.h" #include #include "ash/session/session_controller_impl.h" #include "ash/shell.h" #include "ash/test/ash_test_base.h" #include "ash/test/test_window_builder.h" #include "ash/wm/window_state.h" #include "ash/wm/wm_event.h" #include "base/compiler_specific.h" #include "base/containers/circular_deque.h" #include "base/time/time.h" #include "third_party/skia/include/core/SkColor.h" #include "ui/aura/client/aura_constants.h" #include "ui/aura/client/window_types.h" #include "ui/aura/test/test_windows.h" #include "ui/aura/window.h" #include "ui/aura/window_event_dispatcher.h" #include "ui/gfx/geometry/rect.h" namespace ash { // Implementation that just records video state changes. class TestObserver : public VideoDetector::Observer { public: TestObserver() = default; bool empty() const { return states_.empty(); } void reset() { states_.clear(); } // Pops and returns the earliest-received state. VideoDetector::State PopState() { CHECK(!states_.empty()); VideoDetector::State first_state = states_.front(); states_.pop_front(); return first_state; } // VideoDetector::Observer implementation. void OnVideoStateChanged(VideoDetector::State state) override { states_.push_back(state); } private: // States in the order they were received. base::circular_deque states_; DISALLOW_COPY_AND_ASSIGN(TestObserver); }; class VideoDetectorTest : public AshTestBase { public: VideoDetectorTest() = default; ~VideoDetectorTest() override = default; void SetUp() override { AshTestBase::SetUp(); observer_.reset(new TestObserver); detector_ = Shell::Get()->video_detector(); detector_->AddObserver(observer_.get()); } void TearDown() override { detector_->RemoveObserver(observer_.get()); AshTestBase::TearDown(); } protected: // Creates and returns a new window with |bounds|. std::unique_ptr CreateTestWindow(const gfx::Rect& bounds) { return TestWindowBuilder() .SetColorWindowDelegate(SK_ColorRED) .SetBounds(bounds) .AllowAllWindowStates() .Build(); } VideoDetector* detector_; // not owned std::unique_ptr observer_; private: DISALLOW_COPY_AND_ASSIGN(VideoDetectorTest); }; // Verify that the video detector can distinguish fullscreen and windowed video // activity. TEST_F(VideoDetectorTest, ReportFullscreen) { UpdateDisplay("1024x768,1024x768"); std::unique_ptr window = CreateTestWindow(gfx::Rect(0, 0, 1024, 768)); WindowState* window_state = WindowState::Get(window.get()); const WMEvent toggle_fullscreen_event(WM_EVENT_TOGGLE_FULLSCREEN); window_state->OnWMEvent(&toggle_fullscreen_event); ASSERT_TRUE(window_state->IsFullscreen()); window->Focus(); detector_->OnVideoActivityStarted(); EXPECT_EQ(VideoDetector::State::PLAYING_FULLSCREEN, observer_->PopState()); EXPECT_TRUE(observer_->empty()); // Make the window non-fullscreen. observer_->reset(); window_state->OnWMEvent(&toggle_fullscreen_event); ASSERT_FALSE(window_state->IsFullscreen()); EXPECT_EQ(VideoDetector::State::PLAYING_WINDOWED, observer_->PopState()); EXPECT_TRUE(observer_->empty()); // Open a second, fullscreen window. Fullscreen video should still be reported // due to the second window being fullscreen. This avoids situations where // non-fullscreen video could be reported when multiple videos are playing in // fullscreen and non-fullscreen windows. observer_->reset(); std::unique_ptr other_window = CreateTestWindow(gfx::Rect(1024, 0, 1024, 768)); WindowState* other_window_state = WindowState::Get(other_window.get()); other_window_state->OnWMEvent(&toggle_fullscreen_event); ASSERT_TRUE(other_window_state->IsFullscreen()); EXPECT_EQ(VideoDetector::State::PLAYING_FULLSCREEN, observer_->PopState()); EXPECT_TRUE(observer_->empty()); // Make the second window non-fullscreen and check that the observer is // immediately notified about windowed video. observer_->reset(); other_window_state->OnWMEvent(&toggle_fullscreen_event); ASSERT_FALSE(other_window_state->IsFullscreen()); EXPECT_EQ(VideoDetector::State::PLAYING_WINDOWED, observer_->PopState()); EXPECT_TRUE(observer_->empty()); } } // namespace ash /* * RESTinio */ /*! * @file * @brief Stuff related to value of Authorization HTTP-field. * * @since v.0.6.7 */ #pragma once #include #include #include namespace restinio { namespace http_field_parsers { namespace authorization_details { namespace hfp_impl = restinio::http_field_parsers::impl; // // is_token68_char_predicate_t // /*! * @brief A preducate for symbol_producer_template that checks that * a symbol can be used inside token68 from RFC7235. * * @since v.0.6.7 */ struct is_token68_char_predicate_t : protected hfp_impl::is_alphanum_predicate_t { using base_type_t = hfp_impl::is_alphanum_predicate_t; RESTINIO_NODISCARD bool operator()( const char actual ) const noexcept { return base_type_t::operator()(actual) || '-' == actual || '.' == actual || '_' == actual || '~' == actual || '+' == actual || '/' == actual ; } }; // // token68_symbol_p // RESTINIO_NODISCARD inline auto token68_symbol_p() { return restinio::easy_parser::impl::symbol_producer_template_t< is_token68_char_predicate_t >{}; } // // token68_t // /*! * @brief A structure for holding a value of token68 from RFC7235. * * The actual value of token68 is stored as `std::string` inside that * struct. * * @since v.0.6.7 */ struct token68_t { std::string value; }; inline std::ostream & operator<<( std::ostream & to, const token68_t & v ) { return (to << v.value); } // // token68_p // RESTINIO_NODISCARD inline auto token68_p() { return produce< token68_t >( produce< std::string >( repeat( 1, N, token68_symbol_p() >> to_container() ), repeat( 0, N, symbol_p('=') >> to_container() ) ) >> &token68_t::value ); } } /* authorization_details */ // // authorization_value_t // /*! * @brief Tools for working with the value of Authorization HTTP-field. * * This struct represents parsed value of HTTP-field Authorization * (see https://tools.ietf.org/html/rfc7235): @verbatim Authorization = credentials credentials = auth-scheme [ 1*SP ( token68 / [ #auth-param ] ) ] auth-scheme = token auth-param = token BWS "=" BWS ( token / quoted-string ) token68 = 1*( ALPHA / DIGIT / "-" / "." / "_" / "~" / "+" / "/" ) *"=" @endverbatim * * @since v.0.6.7 */ struct authorization_value_t { //! An indicator of the source form of the value of a parameter. enum class value_form_t { //! The value of a parameter was specified as token. token, //! The value of a parameter was specified as quoted_string. quoted_string }; //! A storage for the value of a parameter. struct param_value_t { //! The value of a parameter. std::string value; //! How this value was represented: as a token, or a quoted string? value_form_t form; }; //! A storage for a parameter with a name and a value. struct param_t { //! The name of a parameter. std::string name; //! The value of a parameter. param_value_t value; }; //! Type of container for holding parameters. using param_container_t = std::vector< param_t >; //! Type for holding a value of token68 from RFC7235. using token68_t = authorization_details::token68_t; //! Type for holding a parameter for authorization. using auth_param_t = variant_t< token68_t, param_container_t >; //! A value of auth-scheme. std::string auth_scheme; //! A parameter for authorization. /*! * @note * It can be empty. */ auth_param_t auth_param; /*! * @brief A factory function for a parser of Authorization value. * * @since v.0.6.7 */ RESTINIO_NODISCARD static auto make_parser() { using namespace authorization_details; auto token_to_v = []( std::string v ) -> param_value_t { return { std::move(v), value_form_t::token }; }; auto qstring_to_v = []( std::string v ) -> param_value_t { return { std::move(v), value_form_t::quoted_string }; }; // NOTE: token68 should consume all input. // So there should not be any symbols after the value. auto token68_seq = sequence( token68_p() >> as_result(), not_clause( any_symbol_p() >> skip() ) ); // Parameters list can be empty. auto params_seq = maybe_empty_comma_separated_list_p< param_container_t >( produce< param_t >( token_p() >> to_lower() >> ¶m_t::name, ows(), symbol('='), ows(), produce< param_value_t >( alternatives( token_p() >> convert( token_to_v ) >> as_result(), quoted_string_p() >> convert( qstring_to_v ) >> as_result() ) ) >> ¶m_t::value ) ) >> as_result(); return produce< authorization_value_t >( token_p() >> to_lower() >> &authorization_value_t::auth_scheme, maybe( repeat( 1, N, space() ), produce< auth_param_t >( alternatives( token68_seq, params_seq ) ) >> &authorization_value_t::auth_param ) ); } /*! * @brief An attempt to parse Authorization HTTP-field. * * @since v.0.6.7 */ RESTINIO_NODISCARD static expected_t< authorization_value_t, restinio::easy_parser::parse_error_t > try_parse( string_view_t what ) { return restinio::easy_parser::try_parse( what, make_parser() ); } }; // // Various helpers for dumping values to std::ostream. // inline std::ostream & operator<<( std::ostream & to, const authorization_value_t::param_value_t & v ) { if(authorization_value_t::value_form_t::token == v.form) to << v.value; else to << '"' << v.value << '"'; return to; } inline std::ostream & operator<<( std::ostream & to, const authorization_value_t::param_t & v ) { return (to << v.name << '=' << v.value); } inline std::ostream & operator<<( std::ostream & to, const authorization_value_t::auth_param_t & p ) { struct printer_t { std::ostream & to; void operator()( const authorization_value_t::token68_t & t ) const { to << t; } void operator()( const authorization_value_t::param_container_t & c ) const { bool first = true; to << '{'; for( const auto & param : c ) { if( !first ) to << ", "; else first = false; to << param; } to << '}'; } }; restinio::visit( printer_t{ to }, p ); return to; } inline std::ostream & operator<<( std::ostream & to, const authorization_value_t & v ) { return (to << v.auth_scheme << ' ' << v.auth_param); } } /* namespace http_field_parsers */ } /* namespace restinio */ npocmaka/Windows-Server-200310-100 /*++ Copyright (c) 1999 Microsoft Corporation. All rights reserved. MODULE NAME: kcccache.cxx ABSTRACT: KCC_DS_CACHE DETAILS: This class acts as a cache for configuration information from the DS. CREATED: 04/28/99 JeffParh REVISION HISTORY: --*/ #include extern "C" { #include #include #include } #include #include "kcc.hxx" #include "kcctask.hxx" #include "kccconn.hxx" #include "kcctopl.hxx" #include "kcccref.hxx" #include "kccdsa.hxx" #include "kcctools.hxx" #include "kcctrans.hxx" #include "kccsconn.hxx" #include "kccdynar.hxx" #include "kccsite.hxx" #include "kccduapi.hxx" #define FILENO FILENO_KCC_KCCCACHE BOOL KCC_DS_CACHE::Init() { BOOL fSuccess = FALSE; NTSTATUS ntStatus = 0; LSAPR_POLICY_INFORMATION * pPolicyInfo = NULL; DSNAME *pdnLocalSite; ULONG cBytes; DWORD i, dsid = 0; Reset(); __try { ////////////////////////////////////////////////////////////////////// // Stage 0 Initialization Begins // Cache the DNS name of the root domain. ntStatus = LsaIQueryInformationPolicyTrusted( PolicyDnsDomainInformation, &pPolicyInfo); if (!NT_SUCCESS(ntStatus)) { // LsaIQueryInformationPolicyTrusted() failed. dsid = DSID(FILENO_KCC_KCCCACHE, __LINE__); __leave; } // NULL-terminate the root domain DNS name. // Note: We depend on memory from new being zeroed here m_pszForestDnsName = (WCHAR *) new BYTE[pPolicyInfo->PolicyDnsDomainInfo.DnsForestName.Length + 2]; memcpy(m_pszForestDnsName, pPolicyInfo->PolicyDnsDomainInfo.DnsForestName.Buffer, pPolicyInfo->PolicyDnsDomainInfo.DnsForestName.Length); // Get the system partition and ntdsDsa DNs. cBytes = 0; ntStatus = GetConfigurationName(DSCONFIGNAME_CONFIGURATION, &cBytes, m_pdnConfiguration); if (STATUS_BUFFER_TOO_SMALL == ntStatus) { m_pdnConfiguration = (DSNAME *) new BYTE[cBytes]; ntStatus = GetConfigurationName(DSCONFIGNAME_CONFIGURATION, &cBytes, m_pdnConfiguration); } if (NT_SUCCESS(ntStatus)) { cBytes = 0; ntStatus = GetConfigurationName(DSCONFIGNAME_DMD, &cBytes, m_pdnSchema); if (STATUS_BUFFER_TOO_SMALL == ntStatus) { m_pdnSchema = (DSNAME *) new BYTE[cBytes]; ntStatus = GetConfigurationName(DSCONFIGNAME_DMD, &cBytes, m_pdnSchema); } } if (NT_SUCCESS(ntStatus)) { #if DBG m_fRunningUnderAltID = GetAltIdentity(&m_pdnLocalDSA); #else m_fRunningUnderAltID = FALSE; #endif if (!m_fRunningUnderAltID) { cBytes = 0; ntStatus = GetConfigurationName(DSCONFIGNAME_DSA, &cBytes, m_pdnLocalDSA); if (STATUS_BUFFER_TOO_SMALL == ntStatus) { m_pdnLocalDSA = (DSNAME *) new BYTE[cBytes]; ntStatus = GetConfigurationName(DSCONFIGNAME_DSA, &cBytes, m_pdnLocalDSA); } } } if (!NT_SUCCESS(ntStatus)) { dsid = DSID(FILENO_KCC_KCCCACHE, __LINE__); __leave; } ////////////////////////////////////////////////////////////////////// // Stage 0 Initialization Complete. Stage 1 Initialization Begins m_initializationStage = KCC_CACHE_STAGE_0_COMPLETE; // Initialize the schedule cache if (!(m_hScheduleCache = ToplScheduleCacheCreate())) { dsid = DSID(FILENO_KCC_KCCCACHE, __LINE__); __leave; } // Read the interSiteTransport objects. if (!m_TransportList.Init()) { dsid = DSID(FILENO_KCC_KCCCACHE, __LINE__); __leave; } // Find the IP transport. for (i = 0; i < m_TransportList.GetCount(); i++) { KCC_TRANSPORT * pTransport = m_TransportList.GetTransport(i); if (pTransport->IsIntersiteIP()) { m_pdnIpTransport = pTransport->GetDN(); break; } } if (NULL == m_pdnIpTransport) { dsid = DSID(FILENO_KCC_KCCCACHE, __LINE__); __leave; } ////////////////////////////////////////////////////////////////////// // Stage 1 Initialization Complete. Stage 2 Initialization Begins m_initializationStage = KCC_CACHE_STAGE_1_COMPLETE; // Initialize all site objects here. However, none of the sites // will contain any DSA objects yet. if (!m_SiteList.InitAllSites()) { // Failed to initialize site / DSA objects dsid = DSID(FILENO_KCC_KCCCACHE, __LINE__); __leave; } ////////////////////////////////////////////////////////////////////// // Stage 2 Initialization Complete. Stage 3 Initialization Begins m_initializationStage = KCC_CACHE_STAGE_2_COMPLETE; // Add all the DSA objects to their sites. m_SiteList.PopulateDSAs(); // Read the crossRef objects. if (!m_CrossRefList.Init()) { dsid = DSID(FILENO_KCC_KCCCACHE, __LINE__); __leave; } // Check that the crossRef for the Config NC could be loaded. if( !m_CrossRefList.GetCrossRefForNC(m_pdnConfiguration) ) { dsid = DSID(FILENO_KCC_KCCCACHE, __LINE__); __leave; } ////////////////////////////////////////////////////////////////////// // Stage 3 Initialization Complete. Stage 4 Initialization Begins m_initializationStage = KCC_CACHE_STAGE_3_COMPLETE; // Find KCC_SITE object for local site pdnLocalSite = KCC_DSA::GetSiteDNSyntacticNoGuid( m_pdnLocalDSA ); m_pLocalSite = m_SiteList.GetSite( pdnLocalSite ); if( ! m_pLocalSite ) { // A match for the local site was not read. This can occur if // the site was renamed or deleted while the KCC was running. // Abort this KCC run. KCC_EXCEPT(ERROR_DS_OBJ_NOT_FOUND, 0); } ////////////////////////////////////////////////////////////////////// // Stage 4 Initialization Complete. Stage 5 Initialization Begins m_initializationStage = KCC_CACHE_STAGE_4_COMPLETE; // Find KCC_DSA object for local DSA m_pLocalDSA = m_pLocalSite->GetDsaList()->GetDsa( m_pdnLocalDSA ); if( ! m_pLocalDSA ) { KCC_EXCEPT(ERROR_DS_OBJ_NOT_FOUND, 0); } ////////////////////////////////////////////////////////////////////// // All Initialization Complete m_initializationStage = KCC_CACHE_INITIALIZATION_COMPLETE; fSuccess = TRUE; } __finally { if (NULL != pPolicyInfo) { LsaIFree_LSAPR_POLICY_INFORMATION(PolicyDnsDomainInformation, pPolicyInfo); } } if (!fSuccess) { DPRINT(0, "KCC_DS_CACHE::Init() failed!\n"); LogEvent(DS_EVENT_CAT_KCC, DS_EVENT_SEV_ALWAYS, DIRLOG_KCC_CACHE_INIT_FAILED, szInsertHex(dsid), 0, 0); } return fSuccess; } void KCC_DS_CACHE::Reset() { m_initializationStage = KCC_CACHE_NOT_INITIALIZED; m_fRunningUnderAltID = FALSE; m_pdnLocalDSA = NULL; m_pLocalDSA = NULL; m_pLocalSite = NULL; m_pdnConfiguration = NULL; m_pdnSchema = NULL; m_pdnIpTransport = NULL; m_pszForestDnsName = NULL; m_hScheduleCache = NULL; m_dwStayOfExecution = 0; m_fReadStayOfExecution = FALSE; m_globalDSAListByGUID = NULL; m_globalDSAListByString = NULL; m_CrossRefList.Reset(); m_TransportList.Reset(); m_SiteList.Reset(); m_fReachableMarkingComplete = FALSE; m_fAnySiteUnreachable = FALSE; } // Check that the cache finished up to 'initStage' of its initialization. BOOL KCC_DS_CACHE::IsValid( KCC_CACHE_INIT_STAGE initStage ) { Assert(NULL != this); if( m_initializationStage < initStage ) { Assert("KCC Cache initialization not complete"); return FALSE; } if( m_initializationStage>=KCC_CACHE_STAGE_0_COMPLETE ) { Assert(NULL != m_pszForestDnsName); Assert(NULL != m_pdnConfiguration); Assert(NULL != m_pdnSchema); Assert(NULL != m_pdnLocalDSA); } if( m_initializationStage>=KCC_CACHE_STAGE_1_COMPLETE ) { Assert(NULL != m_hScheduleCache); ASSERT_VALID(&m_TransportList); Assert(NULL != m_pdnIpTransport); Assert(1 <= m_TransportList.GetCount()); } if( m_initializationStage>=KCC_CACHE_STAGE_2_COMPLETE ) { ASSERT_VALID(&m_SiteList); Assert(1 <= m_SiteList.GetCount()); } if( m_initializationStage>=KCC_CACHE_STAGE_3_COMPLETE ) { ASSERT_VALID(&m_CrossRefList); Assert(3 <= m_CrossRefList.GetCount()); } if( m_initializationStage>=KCC_CACHE_STAGE_4_COMPLETE ) { ASSERT_VALID(m_pLocalSite); } if( m_initializationStage>=KCC_CACHE_INITIALIZATION_COMPLETE ) { ASSERT_VALID(m_pLocalDSA); } // The cache is valid up to the requested stage. return TRUE; } ULONG KCC_DS_CACHE::GetStayOfExecution() // // Retrieve the length of time (in seconds) between when a server object is // deleted and when we declare that it's dead forever. // // (This period allows the deletion to propagate to the server corresponding // to the deleted server object and for that server to revive the object and // propagate it back to the rest of the enterprise.) // { ATTR rgAttrs[] = { { ATT_TOMBSTONE_LIFETIME, { 0, NULL } }, { ATT_REPL_TOPOLOGY_STAY_OF_EXECUTION, { 0, NULL } } }; ENTINFSEL Sel = { EN_ATTSET_LIST, { sizeof( rgAttrs )/sizeof( rgAttrs[ 0 ] ), rgAttrs }, EN_INFOTYPES_TYPES_VALS }; ULONG dirError; READRES * pReadRes = NULL; NTSTATUS status; DWORD cBytes = 0; DSNAME * pdnDirectoryService = NULL; ULONG ulTombstoneLifetimeDays; ULONG ulStayOfExecutionDays, ulStayOfExecutionDaysMax; ULONG ulStayOfExecutionSecs; BOOL fSkipRangeCheck = FALSE; ASSERT_VALID(this); // If the stay of execution length is stored in the cache, we // don't bother to read it from the directory again. if( m_fReadStayOfExecution ) { return m_dwStayOfExecution; } status = GetConfigurationName( DSCONFIGNAME_DS_SVC_CONFIG, &cBytes, pdnDirectoryService); Assert(STATUS_BUFFER_TOO_SMALL == status); pdnDirectoryService = (DSNAME *) new BYTE[ cBytes ]; status = GetConfigurationName( DSCONFIGNAME_DS_SVC_CONFIG, &cBytes, pdnDirectoryService); if ( STATUS_SUCCESS != status ) { // Name derivation failed. LogUnhandledError( DIRERR_NAME_TOO_LONG ); KCC_EXCEPT( DIRERR_NAME_TOO_LONG, status ); } ulStayOfExecutionDays = 0; ulTombstoneLifetimeDays = DEFAULT_TOMBSTONE_LIFETIME; dirError = KccRead( pdnDirectoryService, &Sel, &pReadRes ); if ( 0 != dirError ) { if ( attributeError == dirError ) { INTFORMPROB * pprob = &pReadRes->CommRes.pErrInfo->AtrErr.FirstProblem.intprob; if ( ( PR_PROBLEM_NO_ATTRIBUTE_OR_VAL == pprob->problem ) && ( DIRERR_NO_REQUESTED_ATTS_FOUND == pprob->extendedErr ) ) { // No value; use default (as set above). dirError = 0; } } if ( 0 != dirError ) { KCC_LOG_READ_FAILURE( pdnDirectoryService, dirError ); // Other error; bail. KCC_EXCEPT( DIRERR_MISSING_EXPECTED_ATT, dirError ); } } else { // Read succeeded; parse returned attributes. for ( DWORD iAttr = 0; iAttr < pReadRes->entry.AttrBlock.attrCount; iAttr++ ) { ATTR * pattr = &pReadRes->entry.AttrBlock.pAttr[ iAttr ]; switch ( pattr->attrTyp ) { case ATT_TOMBSTONE_LIFETIME: Assert( 1 == pattr->AttrVal.valCount ); Assert( sizeof( ULONG ) == pattr->AttrVal.pAVal->valLen ); ulTombstoneLifetimeDays = *( (ULONG *) pattr->AttrVal.pAVal->pVal ); break; case ATT_REPL_TOPOLOGY_STAY_OF_EXECUTION: Assert( 1 == pattr->AttrVal.valCount ); Assert( sizeof( ULONG ) == pattr->AttrVal.pAVal->valLen ); ulStayOfExecutionDays = *( (ULONG *) pattr->AttrVal.pAVal->pVal ); if( 0 == ulStayOfExecutionDays ) { DPRINT( 3, "Stay of Execution Disabled\n" ); fSkipRangeCheck = TRUE; } break; default: DPRINT1( 0, "Received unrequested attribute 0x%X.\n", pattr->attrTyp ); break; } } if ( ulTombstoneLifetimeDays < DRA_TOMBSTONE_LIFE_MIN ) { // Invalid value; use default. ulTombstoneLifetimeDays = DEFAULT_TOMBSTONE_LIFETIME; } } if( ! fSkipRangeCheck ) { // Calculate max stay of execution based on runtime value of tombstone life // DRA_TOMBSTONE_LIFE_MIN/2 <= DEFAULT_STAY_OF_EXECUTION <= tombstone-lifetime/2 ulStayOfExecutionDaysMax = (ulTombstoneLifetimeDays / 2); // If stay is not specified, or is too small or too large if ( (ulStayOfExecutionDays < (DRA_TOMBSTONE_LIFE_MIN / 2) ) || (ulStayOfExecutionDays > ulStayOfExecutionDaysMax) ) { // Use the default stay, unless that, too, is too large if ( DEFAULT_STAY_OF_EXECUTION <= ulStayOfExecutionDaysMax ) { Assert( DEFAULT_STAY_OF_EXECUTION >= (DRA_TOMBSTONE_LIFE_MIN / 2) ); ulStayOfExecutionDays = DEFAULT_STAY_OF_EXECUTION; } else { ulStayOfExecutionDays = ulStayOfExecutionDaysMax; } } Assert( ulStayOfExecutionDays ); DPRINT1( 5, "Stay of Execution days = %d\n", ulStayOfExecutionDays ); } // Calculate number of seconds and store in cache m_fReadStayOfExecution = TRUE; m_dwStayOfExecution = ( ulStayOfExecutionDays * 24 * 60 * 60 ); delete[] pdnDirectoryService; return m_dwStayOfExecution; } KCC_DSA_LIST* KCC_DS_CACHE::GetGlobalDSAListByGUID() // Retrieves a list of all DSAs in the enterprise, sorted by GUID { Assert(IsValid()); if(!m_globalDSAListByGUID) { m_globalDSAListByGUID = new KCC_DSA_LIST; m_globalDSAListByGUID->InitUnionOfSites( GetSiteList(), KCC_DSA::CompareIndirectByNtdsDsaGuid ); } return m_globalDSAListByGUID; } KCC_DSA_LIST* KCC_DS_CACHE::GetGlobalDSAListByString() // Retrieves a list of all DSAs in the enterprise, sorted by string-name { Assert(IsValid()); if(!m_globalDSAListByString) { m_globalDSAListByString = new KCC_DSA_LIST; m_globalDSAListByString->InitUnionOfSites( GetSiteList(), KCC_DSA::CompareIndirectByNtdsDsaString ); } return m_globalDSAListByString; } KCC_DSA* KCC_DS_CACHE::GetDSAByGUID( GUID *pDsaGuid ) // // Find the KCC_DSA object matching 'pDsaGuid'. If the object is in the // cache, we return it. If the object is not found, return NULL. // { KCC_DSA *pDsa; DSNAME DN = {0}; Assert(IsValid()); Assert(!fNullUuid(pDsaGuid)); DN.Guid = *pDsaGuid; DN.structLen = DSNameSizeFromLen(0); // Do an in-memory search of all DSA objects. pDsa = GetGlobalDSAListByGUID()->GetDsa( &DN, NULL ); // Note: pDsa may be NULL if the server was not found. return pDsa; } // Indicates that all sites have been marked as reachable / unreachable. VOID KCC_DS_CACHE::SetReachableMarkingComplete() { m_fReachableMarkingComplete = TRUE; } // Checks if the KCC has finished marking all sites as reachable / unreachable BOOL KCC_DS_CACHE::IsReachableMarkingComplete() { return m_fReachableMarkingComplete; } // Indicates that atleast one site found unreachable VOID KCC_DS_CACHE::SetAnySiteUnreachable() { m_fAnySiteUnreachable = TRUE; } // Checks if atleast one site found unreachable // Reachability marking may not be complete yet. BOOL KCC_DS_CACHE::IsAnySiteUnreachable() { return m_fAnySiteUnreachable; } #if DBG BOOL KCC_DS_CACHE::GetAltIdentity( OUT DSNAME ** ppAltDsa ) // // Hook to allow KCC to be run as if it were on a different DC. // This is primarily here to support CDermody's scalability testing. // { ATTR rgAttrs[] = { { ATT_OBJ_DIST_NAME, {0, NULL} } }; ENTINFSEL Sel = { EN_ATTSET_LIST, { sizeof(rgAttrs)/sizeof(rgAttrs[0]), rgAttrs }, EN_INFOTYPES_TYPES_VALS }; DWORD winError; DSNAME * pAltDsa; ULONG dirError; READRES * pResults; ATTRBLOCK * pAttrBlock; pAltDsa = GetConfigDsName(MAKE_WIDE(KCC_RUN_AS_NTDSDSA_DN)); if (!pAltDsa) { DPRINT(5, "No alternate identity defined.\n"); return FALSE; } Assert(0 == pAltDsa->SidLen); Assert(fNullUuid(&pAltDsa->Guid)); dirError = KccRead(pAltDsa, &Sel, &pResults); if (0 != dirError) { DPRINT2(0, "Error %d reading %ls; alternate identity will be ignored.\n", dirError, pAltDsa->StringName); KCC_LOG_READ_FAILURE( pAltDsa, dirError ); THFree(pAltDsa); return FALSE; } pAttrBlock = &pResults->entry.AttrBlock; Assert(1 == pAttrBlock->attrCount); Assert(ATT_OBJ_DIST_NAME == pAttrBlock->pAttr->attrTyp); Assert(1 == pAttrBlock->pAttr->AttrVal.valCount); *ppAltDsa = (DSNAME *) pAttrBlock->pAttr->AttrVal.pAVal->pVal; Assert(pAttrBlock->pAttr->AttrVal.pAVal->valLen == (*ppAltDsa)->structLen); DPRINT1(0, "KCC running under alternate identity %ls.\n", (*ppAltDsa)->StringName); // // Cleanup // THFree(pAltDsa); return TRUE; } #endif #include #include class lvkDynamicStateApp : public IVKSampleApp { private: lvkDemoFramework DemoFramework; lvkShaderModuleLibrary ShaderModuleLibrary; std::unique_ptr Swapchain; lvkRenderPass RenderPass; std::unique_ptr DemoSwapchainFramebuffers; lvkPipelineLayout PipelineLayout; lvkPipeline Pipeline; std::vector CommandBuffers; std::unique_ptr CommandPoolResetObserver; std::vector > CommandRecorders; lvkDemoTaskGraph TaskGraph; public: virtual void Loop() override { TaskGraph.Submit(DemoFramework.Device.get(),*Swapchain.get(),CommandBuffers.data()); } lvkDynamicStateApp(IVKWindow &window) :DemoFramework(window) { ShaderModuleLibrary = {DemoFramework.Device.get()}; Swapchain = std::unique_ptr(new lvkSwapchain(DemoFramework.Device.get(),DemoFramework.PhysicalDevice,DemoFramework.Surface.get())); RenderPass = DemoFramework.CreateSimpleRenderPass(DemoFramework.Device.get(),Swapchain->GetFormat()); DemoSwapchainFramebuffers = std::unique_ptr(new lvkDemoSwapchainFramebuffers(DemoFramework.Device.get(),RenderPass.get(),*Swapchain.get())); PipelineLayout = DemoFramework.CreateEmptyPipelineLayout(); { lvkDemoShaderStages DemoShaderStages; lvkPipelineFixedFunctionState FixedFunctionState; lvkPipelineDynamicState DynamicState; lvkDemoColorBlendAttachments DemoColorBlendAttachments; VkGraphicsPipelineCreateInfo PipelineCreateInfo = LVK_EMPTY_PIPELINE_CREATE_INFO; DemoShaderStages.SetShaders( ShaderModuleLibrary.GetShaderModule("../Shaders/HardcodedVertexShader.spv"), ShaderModuleLibrary.GetShaderModule("../Shaders/FragmentShader.spv") ); DynamicState.AddDynamicState(VK_DYNAMIC_STATE_VIEWPORT); DynamicState.AddDynamicState(VK_DYNAMIC_STATE_SCISSOR); PipelineCreateInfo.renderPass = RenderPass.get(); PipelineCreateInfo.subpass = 0; PipelineCreateInfo.layout = PipelineLayout.get(); DemoShaderStages.AssignToPipelineCreateInfo(PipelineCreateInfo); FixedFunctionState.AssignToPipelineCreateInfo(PipelineCreateInfo); DynamicState.AssignToPipelineCreateInfo(PipelineCreateInfo); DemoColorBlendAttachments.AssignToPipelineCreateInfo(PipelineCreateInfo); std::cout << "Creating graphics pipeline" << std::endl; VkPipeline NewPipeline; if(vkCreateGraphicsPipelines(DemoFramework.Device.get(),VK_NULL_HANDLE,1,&PipelineCreateInfo,nullptr,&NewPipeline) != VK_SUCCESS) { std::cout << "Error while creating pipeline" << std::endl; } Pipeline = lvkPipeline{NewPipeline,{DemoFramework.Device.get()}}; } CommandPoolResetObserver = std::unique_ptr( new lvkDemoCommandPool(DemoFramework.Device.get(),DemoFramework.GraphicsQueueFamilyIndex,0x0,Swapchain.get()) ); CommandBuffers = CommandPoolResetObserver->Allocate(Swapchain->GetImageCount()); CommandRecorders.resize(CommandBuffers.size()); for(int i=0;i < CommandRecorders.size();i++) { CommandRecorders[i] = std::unique_ptr( new lvkDemoBufferRecorder( [this,i]() { lvkRecordCmdBufferGuard RecordCmdBufferGuard(CommandBuffers[i],VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT); lvkDemoRecordSimpleRenderPassGuard RecordSimpleRenderPassGuard( CommandBuffers[i], RenderPass.get(), DemoSwapchainFramebuffers->GetFramebuffer(i), Swapchain->GetExtent() ); VkViewport Viewport = {}; Viewport.x = 0.0; Viewport.y = 0.0; Viewport.width = Swapchain->GetExtent().width; Viewport.height = Swapchain->GetExtent().height; Viewport.minDepth = 0.0f; Viewport.maxDepth = 1.0f; VkRect2D Scissor = {}; Scissor.offset = {0, 0}; Scissor.extent.width = Swapchain->GetExtent().width; Scissor.extent.height = Swapchain->GetExtent().height; vkCmdSetViewport(CommandBuffers[i],0,1,&Viewport); vkCmdSetScissor(CommandBuffers[i],0,1,&Scissor); vkCmdBindPipeline(CommandBuffers[i],VK_PIPELINE_BIND_POINT_GRAPHICS,Pipeline.get()); vkCmdDraw(CommandBuffers[i],3,1,0,0); }, *Swapchain.get() ) ); } TaskGraph.Initialize(DemoFramework.Device.get(),DemoFramework.GraphicsQueue,DemoFramework.PresentQueue); } ~lvkDynamicStateApp() { vkDeviceWaitIdle(DemoFramework.Device.get()); } }; const bool IsResizable = true; std::unique_ptr CreateSampleApp(IVKWindow &window) { return std::unique_ptr(new lvkDynamicStateApp(window)); } 0 /* * Copyright (c) 2021 Huawei Device 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 "faultlogger_service_ohos.h" #include #include #include #include "if_system_ability_manager.h" #include "ipc_skeleton.h" #include "iservice_registry.h" #include "logger.h" #include "faultlog_info.h" #include "faultlog_info_ohos.h" #include "faultlog_query_result_inner.h" #include "faultlog_query_result_ohos.h" #include "faultlogger.h" DEFINE_LOG_TAG("FaultloggerServiceOhos"); namespace OHOS { namespace HiviewDFX { constexpr int32_t UID_SHELL = 2000; constexpr int32_t UID_ROOT = 0; constexpr int32_t DFX_ABILITY_FAULTLOGGER_ID = 1202; void FaultloggerServiceOhos::ClearQueryStub(int32_t uid) { std::lock_guard lock(mutex_); queries_.erase(uid); } int32_t FaultloggerServiceOhos::Dump(int32_t fd, const std::vector &args) { int32_t uid = IPCSkeleton::GetCallingUid(); if ((uid != UID_SHELL) && (uid != UID_ROOT)) { dprintf(fd, "No permission for uid:%d.\n", uid); return -1; } std::vector cmdList; std::transform(args.begin(), args.end(), std::back_inserter(cmdList), [](const std::u16string &arg) { std::wstring_convert, char16_t> convertor; return convertor.to_bytes(arg); }); auto service = GetOrSetFaultlogger(); if (service == nullptr) { dprintf(fd, "Service is not ready.\n"); return -1; } service->Dump(fd, cmdList); return 0; } void FaultloggerServiceOhos::StartService(OHOS::HiviewDFX::Faultlogger *service) { GetOrSetFaultlogger(service); sptr serviceManager = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); if (serviceManager == nullptr) { HIVIEW_LOGE("Failed to find samgr, exit."); return; } serviceManager->AddSystemAbility(DFX_ABILITY_FAULTLOGGER_ID, &(FaultloggerServiceOhos::GetInstance())); HIVIEW_LOGI("FaultLogger Service started."); } OHOS::HiviewDFX::Faultlogger *FaultloggerServiceOhos::GetOrSetFaultlogger( OHOS::HiviewDFX::Faultlogger *service) { static OHOS::HiviewDFX::Faultlogger *ref = nullptr; if (service != nullptr) { ref = service; } return ref; } void FaultloggerServiceOhos::AddFaultLog(const FaultLogInfoOhos& info) { auto service = GetOrSetFaultlogger(); if (service == nullptr) { return; } int32_t uid = IPCSkeleton::GetCallingUid(); if (((uid != static_cast(getuid()))) && (uid != info.uid)) { HIVIEW_LOGW("Fail to add fault log, mismatch uid:%{public}d(%{public})", uid, info.uid); return; } FaultLogInfo outInfo; outInfo.time = info.time; outInfo.id = info.uid; outInfo.pid = info.pid; outInfo.faultLogType = info.faultLogType; outInfo.fd = (info.fd > 0) ? dup(info.fd) : -1; outInfo.module = info.module; outInfo.reason = info.reason; outInfo.summary = info.summary; outInfo.logPath = info.logPath; outInfo.sectionMap = info.sectionMaps; service->AddFaultLog(outInfo); } sptr FaultloggerServiceOhos::QuerySelfFaultLog(int32_t faultType, int32_t maxNum) { auto service = GetOrSetFaultlogger(); if (service == nullptr) { return nullptr; } int32_t uid = IPCSkeleton::GetCallingUid(); int32_t pid = IPCSkeleton::GetCallingPid(); std::lock_guard lock(mutex_); if ((queries_.find(uid) != queries_.end()) && (queries_[uid]->pid == pid)) { HIVIEW_LOGW("Ongoing query is still alive for uid:%d", uid); return nullptr; } auto queryResult = service->QuerySelfFaultLog(uid, faultType, maxNum); if (queryResult == nullptr) { HIVIEW_LOGW("Fail to query fault log for uid:%d", uid); return nullptr; } sptr resultRef = new FaultLogQueryResultOhos(std::move(queryResult)); auto queryStub = std::make_unique(); queryStub->pid = pid; queryStub->ptr = resultRef; queries_[uid] = std::move(queryStub); return resultRef->AsObject(); } void FaultloggerServiceOhos::Destroy() { auto service = GetOrSetFaultlogger(); if (service == nullptr) { return; } int32_t uid = IPCSkeleton::GetCallingUid(); HIVIEW_LOGI("Destroy Query from uid:%d", uid); ClearQueryStub(uid); } } // namespace HiviewDFX } // namespace OHOSmikerainey/taskparts0 extern "C" void str0(); extern "C" void str0_rf(); extern "C" void str1(); extern "C" void str1_rf(); extern "C" void str2(); extern "C" void str2_rf(); extern "C" void str3(); extern "C" void str3_rf(); extern "C" void str4(); extern "C" void str4_rf(); extern "C" void str5(); extern "C" void str5_rf(); extern "C" void str6(); extern "C" void str6_rf(); extern "C" void str7(); extern "C" void str7_rf(); extern "C" void str8(); extern "C" void str8_rf(); extern "C" void str9(); extern "C" void str9_rf(); extern "C" void str10(); extern "C" void str10_rf(); extern "C" void str11(); extern "C" void str11_rf(); extern "C" void str12(); extern "C" void str12_rf(); extern "C" void str13(); extern "C" void str13_rf(); extern "C" void str14(); extern "C" void str14_rf(); extern "C" void str15(); extern "C" void str15_rf(); extern "C" void str16(); extern "C" void str16_rf(); extern "C" void str17(); extern "C" void str17_rf(); extern "C" void str18(); extern "C" void str18_rf(); extern "C" void str19(); extern "C" void str19_rf(); extern "C" void str20(); extern "C" void str20_rf(); extern "C" void str21(); extern "C" void str21_rf(); extern "C" void str22(); extern "C" void str22_rf(); extern "C" void str23(); extern "C" void str23_rf(); extern "C" void str24(); extern "C" void str24_rf(); extern "C" void str25(); extern "C" void str25_rf(); extern "C" void str26(); extern "C" void str26_rf(); extern "C" void str27(); extern "C" void str27_rf(); extern "C" void str28(); extern "C" void str28_rf(); extern "C" void str29(); extern "C" void str29_rf(); extern "C" void str30(); extern "C" void str30_rf(); extern "C" void str31(); extern "C" void str31_rf(); extern "C" void str32(); extern "C" void str32_rf(); extern "C" void str33(); extern "C" void str33_rf(); extern "C" void str34(); extern "C" void str34_rf(); extern "C" void str35(); extern "C" void str35_rf(); extern "C" void str36(); extern "C" void str36_rf(); extern "C" void str37(); extern "C" void str37_rf(); extern "C" void str38(); extern "C" void str38_rf(); extern "C" void str39(); extern "C" void str39_rf(); extern "C" void str40(); extern "C" void str40_rf(); extern "C" void str41(); extern "C" void str41_rf(); extern "C" void str42(); extern "C" void str42_rf(); extern "C" void str43(); extern "C" void str43_rf(); extern "C" void str44(); extern "C" void str44_rf(); extern "C" void str45(); extern "C" void str45_rf(); extern "C" void str46(); extern "C" void str46_rf(); extern "C" void str47(); extern "C" void str47_rf(); extern "C" void str48(); extern "C" void str48_rf(); extern "C" void str49(); extern "C" void str49_rf(); extern "C" void str50(); extern "C" void str50_rf(); extern "C" void str51(); extern "C" void str51_rf(); extern "C" void str52(); extern "C" void str52_rf(); extern "C" void str53(); extern "C" void str53_rf(); extern "C" void str54(); extern "C" void str54_rf(); extern "C" void str55(); extern "C" void str55_rf(); extern "C" void str56(); extern "C" void str56_rf(); extern "C" void str57(); extern "C" void str57_rf(); extern "C" void str58(); extern "C" void str58_rf(); extern "C" void str59(); extern "C" void str59_rf(); extern "C" void str60(); extern "C" void str60_rf(); extern "C" void str61(); extern "C" void str61_rf(); extern "C" void str62(); extern "C" void str62_rf(); extern "C" void str63(); extern "C" void str63_rf(); extern "C" void str64(); extern "C" void str64_rf(); extern "C" void str65(); extern "C" void str65_rf(); extern "C" void str66(); extern "C" void str66_rf(); extern "C" void str67(); extern "C" void str67_rf(); extern "C" void str68(); extern "C" void str68_rf(); extern "C" void str69(); extern "C" void str69_rf(); extern "C" void str70(); extern "C" void str70_rf(); extern "C" void str71(); extern "C" void str71_rf(); extern "C" void str72(); extern "C" void str72_rf(); extern "C" void str73(); extern "C" void str73_rf(); extern "C" void str74(); extern "C" void str74_rf(); extern "C" void str75(); extern "C" void str75_rf(); extern "C" void str76(); extern "C" void str76_rf(); extern "C" void str77(); extern "C" void str77_rf(); extern "C" void str78(); extern "C" void str78_rf(); extern "C" void str79(); extern "C" void str79_rf(); extern "C" void str80(); extern "C" void str80_rf(); extern "C" void str81(); extern "C" void str81_rf(); extern "C" void str82(); extern "C" void str82_rf(); extern "C" void str83(); extern "C" void str83_rf(); extern "C" void str84(); extern "C" void str84_rf(); extern "C" void str85(); extern "C" void str85_rf(); extern "C" void str86(); extern "C" void str86_rf(); extern "C" void str87(); extern "C" void str87_rf(); extern "C" void str88(); extern "C" void str88_rf(); extern "C" void str89(); extern "C" void str89_rf(); extern "C" void str90(); extern "C" void str90_rf(); extern "C" void str91(); extern "C" void str91_rf(); extern "C" void str92(); extern "C" void str92_rf(); extern "C" void str93(); extern "C" void str93_rf(); extern "C" void str94(); extern "C" void str94_rf(); extern "C" void str95(); extern "C" void str95_rf(); extern "C" void str96(); extern "C" void str96_rf(); extern "C" void str97(); extern "C" void str97_rf(); extern "C" void str98(); extern "C" void str98_rf(); extern "C" void str99(); extern "C" void str99_rf(); extern "C" void str100(); extern "C" void str100_rf(); extern "C" void str101(); extern "C" void str101_rf(); extern "C" void str102(); extern "C" void str102_rf(); extern "C" void str103(); extern "C" void str103_rf(); extern "C" void str104(); extern "C" void str104_rf(); extern "C" void str105(); extern "C" void str105_rf(); extern "C" void str106(); extern "C" void str106_rf(); extern "C" void str107(); extern "C" void str107_rf(); extern "C" void str108(); extern "C" void str108_rf(); extern "C" void str109(); extern "C" void str109_rf(); extern "C" void str110(); extern "C" void str110_rf(); extern "C" void str111(); extern "C" void str111_rf(); extern "C" void str112(); extern "C" void str112_rf(); extern "C" void str113(); extern "C" void str113_rf(); extern "C" void str114(); extern "C" void str114_rf(); extern "C" void str115(); extern "C" void str115_rf(); extern "C" void str116(); extern "C" void str116_rf(); extern "C" void str117(); extern "C" void str117_rf(); extern "C" void str118(); extern "C" void str118_rf(); extern "C" void str119(); extern "C" void str119_rf(); extern "C" void str120(); extern "C" void str120_rf(); extern "C" void str121(); extern "C" void str121_rf(); extern "C" void str122(); extern "C" void str122_rf(); extern "C" void str123(); extern "C" void str123_rf(); extern "C" void str124(); extern "C" void str124_rf(); extern "C" void str125(); extern "C" void str125_rf(); extern "C" void str126(); extern "C" void str126_rf(); extern "C" void str127(); extern "C" void str127_rf(); extern "C" void str128(); extern "C" void str128_rf(); extern "C" void str129(); extern "C" void str129_rf(); extern "C" void str130(); extern "C" void str130_rf(); extern "C" void str131(); extern "C" void str131_rf(); extern "C" void str132(); extern "C" void str132_rf(); extern "C" void str133(); extern "C" void str133_rf(); extern "C" void str134(); extern "C" void str134_rf(); extern "C" void str135(); extern "C" void str135_rf(); extern "C" void str136(); extern "C" void str136_rf(); extern "C" void str137(); extern "C" void str137_rf(); extern "C" void str138(); extern "C" void str138_rf(); extern "C" void str139(); extern "C" void str139_rf(); extern "C" void str140(); extern "C" void str140_rf(); extern "C" void str141(); extern "C" void str141_rf(); extern "C" void str142(); extern "C" void str142_rf(); extern "C" void str143(); extern "C" void str143_rf(); extern "C" void str144(); extern "C" void str144_rf(); extern "C" void str145(); extern "C" void str145_rf(); extern "C" void str146(); extern "C" void str146_rf(); extern "C" void str147(); extern "C" void str147_rf(); extern "C" void str148(); extern "C" void str148_rf(); extern "C" void str149(); extern "C" void str149_rf(); extern "C" void str150(); extern "C" void str150_rf(); extern "C" void str151(); extern "C" void str151_rf(); extern "C" void str152(); extern "C" void str152_rf(); extern "C" void str153(); extern "C" void str153_rf(); extern "C" void str154(); extern "C" void str154_rf(); extern "C" void str155(); extern "C" void str155_rf(); extern "C" void str156(); extern "C" void str156_rf(); extern "C" void str157(); extern "C" void str157_rf(); extern "C" void str158(); extern "C" void str158_rf(); extern "C" void str159(); extern "C" void str159_rf(); extern "C" void str160(); extern "C" void str160_rf(); extern "C" void str161(); extern "C" void str161_rf(); extern "C" void str162(); extern "C" void str162_rf(); extern "C" void str163(); extern "C" void str163_rf(); extern "C" void str164(); extern "C" void str164_rf(); extern "C" void str165(); extern "C" void str165_rf(); extern "C" void str166(); extern "C" void str166_rf(); extern "C" void str167(); extern "C" void str167_rf(); extern "C" void str168(); extern "C" void str168_rf(); extern "C" void str169(); extern "C" void str169_rf(); extern "C" void str170(); extern "C" void str170_rf(); extern "C" void str171(); extern "C" void str171_rf(); extern "C" void str172(); extern "C" void str172_rf(); extern "C" void str173(); extern "C" void str173_rf(); extern "C" void str174(); extern "C" void str174_rf(); extern "C" void str175(); extern "C" void str175_rf(); extern "C" void str176(); extern "C" void str176_rf(); extern "C" void str177(); extern "C" void str177_rf(); extern "C" void str178(); extern "C" void str178_rf(); extern "C" void str179(); extern "C" void str179_rf(); extern "C" void str180(); extern "C" void str180_rf(); extern "C" void str181(); extern "C" void str181_rf(); extern "C" void str182(); extern "C" void str182_rf(); extern "C" void str183(); extern "C" void str183_rf(); extern "C" void str184(); extern "C" void str184_rf(); extern "C" void str185(); extern "C" void str185_rf(); extern "C" void str186(); extern "C" void str186_rf(); extern "C" void str187(); extern "C" void str187_rf(); extern "C" void str188(); extern "C" void str188_rf(); extern "C" void str189(); extern "C" void str189_rf(); extern "C" void str190(); extern "C" void str190_rf(); extern "C" void str191(); extern "C" void str191_rf(); extern "C" void str192(); extern "C" void str192_rf(); extern "C" void str193(); extern "C" void str193_rf(); extern "C" void str194(); extern "C" void str194_rf(); extern "C" void str195(); extern "C" void str195_rf(); extern "C" void str196(); extern "C" void str196_rf(); extern "C" void str197(); extern "C" void str197_rf(); extern "C" void str198(); extern "C" void str198_rf(); extern "C" void str199(); extern "C" void str199_rf(); extern "C" void str200(); extern "C" void str200_rf(); extern "C" void str201(); extern "C" void str201_rf(); extern "C" void str202(); extern "C" void str202_rf(); extern "C" void str203(); extern "C" void str203_rf(); extern "C" void str204(); extern "C" void str204_rf(); extern "C" void str205(); extern "C" void str205_rf(); extern "C" void str206(); extern "C" void str206_rf(); extern "C" void str207(); extern "C" void str207_rf(); extern "C" void str208(); extern "C" void str208_rf(); extern "C" void str209(); extern "C" void str209_rf(); extern "C" void str210(); extern "C" void str210_rf(); extern "C" void str211(); extern "C" void str211_rf(); extern "C" void str212(); extern "C" void str212_rf(); extern "C" void str213(); extern "C" void str213_rf(); extern "C" void str214(); extern "C" void str214_rf(); extern "C" void str215(); extern "C" void str215_rf(); extern "C" void str216(); extern "C" void str216_rf(); extern "C" void str217(); extern "C" void str217_rf(); extern "C" void str218(); extern "C" void str218_rf(); extern "C" void str219(); extern "C" void str219_rf(); extern "C" void str220(); extern "C" void str220_rf(); extern "C" void str221(); extern "C" void str221_rf(); extern "C" void str222(); extern "C" void str222_rf(); extern "C" void str223(); extern "C" void str223_rf(); extern "C" void str224(); extern "C" void str224_rf(); extern "C" void str225(); extern "C" void str225_rf(); extern "C" void str226(); extern "C" void str226_rf(); extern "C" void str227(); extern "C" void str227_rf(); extern "C" void str228(); extern "C" void str228_rf(); extern "C" void str229(); extern "C" void str229_rf(); extern "C" void str230(); extern "C" void str230_rf(); extern "C" void str231(); extern "C" void str231_rf(); extern "C" void str232(); extern "C" void str232_rf(); extern "C" void str233(); extern "C" void str233_rf(); extern "C" void str234(); extern "C" void str234_rf(); extern "C" void str235(); extern "C" void str235_rf(); extern "C" void str236(); extern "C" void str236_rf(); extern "C" void str237(); extern "C" void str237_rf(); extern "C" void str238(); extern "C" void str238_rf(); extern "C" void str239(); extern "C" void str239_rf(); extern "C" void str240(); extern "C" void str240_rf(); extern "C" void str241(); extern "C" void str241_rf(); extern "C" void str242(); extern "C" void str242_rf(); extern "C" void str243(); extern "C" void str243_rf(); extern "C" void str244(); extern "C" void str244_rf(); extern "C" void str245(); extern "C" void str245_rf(); extern "C" void str246(); extern "C" void str246_rf(); extern "C" void str247(); extern "C" void str247_rf(); extern "C" void str248(); extern "C" void str248_rf(); extern "C" void str249(); extern "C" void str249_rf(); extern "C" void str250(); extern "C" void str250_rf(); extern "C" void str251(); extern "C" void str251_rf(); extern "C" void str252(); extern "C" void str252_rf(); extern "C" void str253(); extern "C" void str253_rf(); extern "C" void str254(); extern "C" void str254_rf(); extern "C" void str255(); extern "C" void str255_rf(); extern "C" void str256(); extern "C" void str256_rf(); extern "C" void str257(); extern "C" void str257_rf(); extern "C" void str258(); extern "C" void str258_rf(); extern "C" void str259(); extern "C" void str259_rf(); extern "C" void str260(); extern "C" void str260_rf(); extern "C" void str261(); extern "C" void str261_rf(); extern "C" void str262(); extern "C" void str262_rf(); extern "C" void str263(); extern "C" void str263_rf(); extern "C" void str264(); extern "C" void str264_rf(); extern "C" void str265(); extern "C" void str265_rf(); extern "C" void str266(); extern "C" void str266_rf(); extern "C" void str267(); extern "C" void str267_rf(); extern "C" void str268(); extern "C" void str268_rf(); extern "C" void str269(); extern "C" void str269_rf(); extern "C" void str270(); extern "C" void str270_rf(); extern "C" void str271(); extern "C" void str271_rf(); extern "C" void str272(); extern "C" void str272_rf(); extern "C" void str273(); extern "C" void str273_rf(); extern "C" void str274(); extern "C" void str274_rf(); extern "C" void str275(); extern "C" void str275_rf(); extern "C" void str276(); extern "C" void str276_rf(); extern "C" void str277(); extern "C" void str277_rf(); extern "C" void str278(); extern "C" void str278_rf(); extern "C" void str279(); extern "C" void str279_rf(); extern "C" void str280(); extern "C" void str280_rf(); extern "C" void str281(); extern "C" void str281_rf(); extern "C" void str282(); extern "C" void str282_rf(); extern "C" void str283(); extern "C" void str283_rf(); extern "C" void str284(); extern "C" void str284_rf(); extern "C" void str285(); extern "C" void str285_rf(); extern "C" void str286(); extern "C" void str286_rf(); extern "C" void str287(); extern "C" void str287_rf(); extern "C" void str288(); extern "C" void str288_rf(); extern "C" void str289(); extern "C" void str289_rf(); extern "C" void str290(); extern "C" void str290_rf(); extern "C" void str291(); extern "C" void str291_rf(); extern "C" void str292(); extern "C" void str292_rf(); extern "C" void str293(); extern "C" void str293_rf(); extern "C" void str294(); extern "C" void str294_rf(); extern "C" void str295(); extern "C" void str295_rf(); extern "C" void str296(); extern "C" void str296_rf(); extern "C" void str297(); extern "C" void str297_rf(); extern "C" void str298(); extern "C" void str298_rf(); extern "C" void str299(); extern "C" void str299_rf(); extern "C" void str300(); extern "C" void str300_rf(); extern "C" void str301(); extern "C" void str301_rf(); extern "C" void str302(); extern "C" void str302_rf(); extern "C" void str303(); extern "C" void str303_rf(); extern "C" void str304(); extern "C" void str304_rf(); extern "C" void str305(); extern "C" void str305_rf(); extern "C" void str306(); extern "C" void str306_rf(); extern "C" void str307(); extern "C" void str307_rf(); extern "C" void str308(); extern "C" void str308_rf(); extern "C" void str309(); extern "C" void str309_rf(); extern "C" void str310(); extern "C" void str310_rf(); extern "C" void str311(); extern "C" void str311_rf(); extern "C" void str312(); extern "C" void str312_rf(); extern "C" void str313(); extern "C" void str313_rf(); extern "C" void str314(); extern "C" void str314_rf(); extern "C" void str315(); extern "C" void str315_rf(); extern "C" void str316(); extern "C" void str316_rf(); extern "C" void str317(); extern "C" void str317_rf(); extern "C" void str318(); extern "C" void str318_rf(); extern "C" void str319(); extern "C" void str319_rf(); extern "C" void str320(); extern "C" void str320_rf(); extern "C" void str321(); extern "C" void str321_rf(); extern "C" void str322(); extern "C" void str322_rf(); extern "C" void str323(); extern "C" void str323_rf(); extern "C" void str324(); extern "C" void str324_rf(); extern "C" void str325(); extern "C" void str325_rf(); extern "C" void str326(); extern "C" void str326_rf(); extern "C" void str327(); extern "C" void str327_rf(); extern "C" void str328(); extern "C" void str328_rf(); extern "C" void str329(); extern "C" void str329_rf(); extern "C" void str330(); extern "C" void str330_rf(); extern "C" void str331(); extern "C" void str331_rf(); extern "C" void str332(); extern "C" void str332_rf(); extern "C" void str333(); extern "C" void str333_rf(); extern "C" void str334(); extern "C" void str334_rf(); extern "C" void str335(); extern "C" void str335_rf(); extern "C" void str336(); extern "C" void str336_rf(); extern "C" void str337(); extern "C" void str337_rf(); extern "C" void str338(); extern "C" void str338_rf(); Mindjolt2406/Competitive-Programming int bsearch(int k,int*memo,int n) { int beg = 1,end = k-1,max1 = -1; while(beg<=end) { int mid = (beg+end)/2; if(memo[mid]=n) {end = mid-1;} } return max1; } int main() { int n; sc(n); int*l = new int[n]; for(int i=0;iouxianghui/ezcam /** * Copyright (c) 2011-2016 by . All rights reserved. * * This file is part of the QCAD project. * * QCAD 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. * * QCAD 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 QCAD. */ #include "RLayout.h" #include "RDocument.h" RPropertyTypeId RLayout::PropertyCustom; RPropertyTypeId RLayout::PropertyName; RPropertyTypeId RLayout::PropertyTabOrder; RPropertyTypeId RLayout::PropertyMinLimitsX; RPropertyTypeId RLayout::PropertyMinLimitsY; RPropertyTypeId RLayout::PropertyMinLimitsZ; RPropertyTypeId RLayout::PropertyMaxLimitsX; RPropertyTypeId RLayout::PropertyMaxLimitsY; RPropertyTypeId RLayout::PropertyMaxLimitsZ; RPropertyTypeId RLayout::PropertyInsertionBaseX; RPropertyTypeId RLayout::PropertyInsertionBaseY; RPropertyTypeId RLayout::PropertyInsertionBaseZ; RPropertyTypeId RLayout::PropertyMinExtentsX; RPropertyTypeId RLayout::PropertyMinExtentsY; RPropertyTypeId RLayout::PropertyMinExtentsZ; RPropertyTypeId RLayout::PropertyMaxExtentsX; RPropertyTypeId RLayout::PropertyMaxExtentsY; RPropertyTypeId RLayout::PropertyMaxExtentsZ; //RPropertyTypeId RLayout::PropertyPlotPaperMarginLeftMM; //RPropertyTypeId RLayout::PropertyPlotPaperMarginBottomMM; //RPropertyTypeId RLayout::PropertyPlotPaperMarginRightMM; //RPropertyTypeId RLayout::PropertyPlotPaperMarginTopMM; //RPropertyTypeId RLayout::PropertyPlotPaperSizeWidth; //RPropertyTypeId RLayout::PropertyPlotPaperSizeHeight; //RPropertyTypeId RLayout::PropertyPlotOriginX; //RPropertyTypeId RLayout::PropertyPlotOriginY; //RPropertyTypeId RLayout::PropertyPlotWindowAreaMinX; //RPropertyTypeId RLayout::PropertyPlotWindowAreaMinY; //RPropertyTypeId RLayout::PropertyPlotWindowAreaMaxX; //RPropertyTypeId RLayout::PropertyPlotWindowAreaMaxY; //RPropertyTypeId RLayout::PropertyNumeratorCustomScale; //RPropertyTypeId RLayout::PropertyDenominatorCustomScale; //RPropertyTypeId RLayout::PropertyPlotPaperUnits; //RPropertyTypeId RLayout::PropertyPlotRotation; RLayout::RLayout() : RObject(), tabOrder(0) { } RLayout::RLayout(RDocument* document, const QString& name) : RObject(document), name(name.trimmed()), tabOrder(0) { } RLayout::~RLayout() { } void RLayout::init() { RLayout::PropertyCustom.generateId(typeid(RLayout), RObject::PropertyCustom); RLayout::PropertyName.generateId(typeid(RLayout), "", QT_TRANSLATE_NOOP("REntity", "Name")); RLayout::PropertyTabOrder.generateId(typeid(RLayout), "", QT_TRANSLATE_NOOP("REntity", "Tab Order")); RLayout::PropertyMinLimitsX.generateId(typeid(RLayout), QT_TRANSLATE_NOOP("REntity", "Min Limits"), QT_TRANSLATE_NOOP("REntity", "X")); RLayout::PropertyMinLimitsY.generateId(typeid(RLayout), QT_TRANSLATE_NOOP("REntity", "Min Limits"), QT_TRANSLATE_NOOP("REntity", "Y")); RLayout::PropertyMinLimitsZ.generateId(typeid(RLayout), QT_TRANSLATE_NOOP("REntity", "Min Limits"), QT_TRANSLATE_NOOP("REntity", "Z")); RLayout::PropertyMaxLimitsX.generateId(typeid(RLayout), QT_TRANSLATE_NOOP("REntity", "Max Limits"), QT_TRANSLATE_NOOP("REntity", "X")); RLayout::PropertyMaxLimitsY.generateId(typeid(RLayout), QT_TRANSLATE_NOOP("REntity", "Max Limits"), QT_TRANSLATE_NOOP("REntity", "Y")); RLayout::PropertyMaxLimitsZ.generateId(typeid(RLayout), QT_TRANSLATE_NOOP("REntity", "Max Limits"), QT_TRANSLATE_NOOP("REntity", "Z")); RLayout::PropertyInsertionBaseX.generateId(typeid(RLayout), QT_TRANSLATE_NOOP("REntity", "Insertion Base"), QT_TRANSLATE_NOOP("REntity", "X")); RLayout::PropertyInsertionBaseY.generateId(typeid(RLayout), QT_TRANSLATE_NOOP("REntity", "Insertion Base"), QT_TRANSLATE_NOOP("REntity", "Y")); RLayout::PropertyInsertionBaseZ.generateId(typeid(RLayout), QT_TRANSLATE_NOOP("REntity", "Insertion Base"), QT_TRANSLATE_NOOP("REntity", "Z")); RLayout::PropertyMinExtentsX.generateId(typeid(RLayout), QT_TRANSLATE_NOOP("REntity", "Min Extents"), QT_TRANSLATE_NOOP("REntity", "X")); RLayout::PropertyMinExtentsY.generateId(typeid(RLayout), QT_TRANSLATE_NOOP("REntity", "Min Extents"), QT_TRANSLATE_NOOP("REntity", "Y")); RLayout::PropertyMinExtentsZ.generateId(typeid(RLayout), QT_TRANSLATE_NOOP("REntity", "Min Extents"), QT_TRANSLATE_NOOP("REntity", "Z")); RLayout::PropertyMaxExtentsX.generateId(typeid(RLayout), QT_TRANSLATE_NOOP("REntity", "Max Extents"), QT_TRANSLATE_NOOP("REntity", "X")); RLayout::PropertyMaxExtentsY.generateId(typeid(RLayout), QT_TRANSLATE_NOOP("REntity", "Max Extents"), QT_TRANSLATE_NOOP("REntity", "Y")); RLayout::PropertyMaxExtentsZ.generateId(typeid(RLayout), QT_TRANSLATE_NOOP("REntity", "Max Extents"), QT_TRANSLATE_NOOP("REntity", "Z")); // RLayout::PropertyPlotPaperMarginLeftMM.generateId(typeid(RLayout), QT_TRANSLATE_NOOP("REntity", "Plot Margins"), QT_TRANSLATE_NOOP("REntity", "Left")); // RLayout::PropertyPlotPaperMarginBottomMM.generateId(typeid(RLayout), QT_TRANSLATE_NOOP("REntity", "Plot Margins"), QT_TRANSLATE_NOOP("REntity", "Bottom")); // RLayout::PropertyPlotPaperMarginRightMM.generateId(typeid(RLayout), QT_TRANSLATE_NOOP("REntity", "Plot Margins"), QT_TRANSLATE_NOOP("REntity", "Right")); // RLayout::PropertyPlotPaperMarginTopMM.generateId(typeid(RLayout), QT_TRANSLATE_NOOP("REntity", "Plot Margins"), QT_TRANSLATE_NOOP("REntity", "Top")); // RLayout::PropertyPlotPaperSizeWidth.generateId(typeid(RLayout), QT_TRANSLATE_NOOP("REntity", "Plot Paper Size"), QT_TRANSLATE_NOOP("REntity", "Width")); // RLayout::PropertyPlotPaperSizeHeight.generateId(typeid(RLayout), QT_TRANSLATE_NOOP("REntity", "Plot Paper Size"), QT_TRANSLATE_NOOP("REntity", "Height")); // RLayout::PropertyPlotOriginX.generateId(typeid(RLayout), QT_TRANSLATE_NOOP("REntity", "Plot Origin"), QT_TRANSLATE_NOOP("REntity", "X")); // RLayout::PropertyPlotOriginY.generateId(typeid(RLayout), QT_TRANSLATE_NOOP("REntity", "Plot Origin"), QT_TRANSLATE_NOOP("REntity", "Y")); // RLayout::PropertyPlotWindowAreaMinX.generateId(typeid(RLayout), QT_TRANSLATE_NOOP("REntity", "Plot Window Area Min"), QT_TRANSLATE_NOOP("REntity", "X")); // RLayout::PropertyPlotWindowAreaMinY.generateId(typeid(RLayout), QT_TRANSLATE_NOOP("REntity", "Plot Window Area Min"), QT_TRANSLATE_NOOP("REntity", "Y")); // RLayout::PropertyPlotWindowAreaMaxX.generateId(typeid(RLayout), QT_TRANSLATE_NOOP("REntity", "Plot Window Area Max"), QT_TRANSLATE_NOOP("REntity", "X")); // RLayout::PropertyPlotWindowAreaMaxY.generateId(typeid(RLayout), QT_TRANSLATE_NOOP("REntity", "Plot Window Area Max"), QT_TRANSLATE_NOOP("REntity", "Y")); // RLayout::PropertyNumeratorCustomScale.generateId(typeid(RLayout), QT_TRANSLATE_NOOP("REntity", "Custom Scale"), QT_TRANSLATE_NOOP("REntity", "Numerator")); // RLayout::PropertyDenominatorCustomScale.generateId(typeid(RLayout), QT_TRANSLATE_NOOP("REntity", "Custom Scale"), QT_TRANSLATE_NOOP("REntity", "Denominator")); // RLayout::PropertyPlotPaperUnits.generateId(typeid(RLayout), "", QT_TRANSLATE_NOOP("REntity", "Plot Paper Units")); // RLayout::PropertyPlotRotation.generateId(typeid(RLayout), "", QT_TRANSLATE_NOOP("REntity", "Plot Rotation")); } RLayout* RLayout::clone() const { return new RLayout(*this); } void RLayout::setName(const QString& n) { name = n.trimmed(); } bool RLayout::setProperty(RPropertyTypeId propertyTypeId, const QVariant& value, RTransaction* transaction) { bool ret = RObject::setProperty(propertyTypeId, value, transaction); if (PropertyName == propertyTypeId) { // never change name of layouts starting with * (model space, paper space, ...): if (name.startsWith("*")) { return false; } // never change layout name to empty string: if (value.toString().isEmpty()) { return false; } } ret = ret || RObject::setMember(name, value.toString().trimmed(), PropertyName == propertyTypeId); ret = ret || RObject::setMember(tabOrder, value, PropertyTabOrder == propertyTypeId); ret = ret || RObject::setMember(minLimits.x, value, PropertyMinLimitsX == propertyTypeId); ret = ret || RObject::setMember(minLimits.y, value, PropertyMinLimitsY == propertyTypeId); ret = ret || RObject::setMember(minLimits.z, value, PropertyMinLimitsZ == propertyTypeId); ret = ret || RObject::setMember(maxLimits.x, value, PropertyMaxLimitsX == propertyTypeId); ret = ret || RObject::setMember(maxLimits.y, value, PropertyMaxLimitsY == propertyTypeId); ret = ret || RObject::setMember(maxLimits.z, value, PropertyMaxLimitsZ == propertyTypeId); ret = ret || RObject::setMember(insertionBase.x, value, PropertyInsertionBaseX == propertyTypeId); ret = ret || RObject::setMember(insertionBase.y, value, PropertyInsertionBaseY == propertyTypeId); ret = ret || RObject::setMember(insertionBase.z, value, PropertyInsertionBaseZ == propertyTypeId); ret = ret || RObject::setMember(minExtents.x, value, PropertyMinExtentsX == propertyTypeId); ret = ret || RObject::setMember(minExtents.y, value, PropertyMinExtentsY == propertyTypeId); ret = ret || RObject::setMember(minExtents.z, value, PropertyMinExtentsZ == propertyTypeId); ret = ret || RObject::setMember(maxExtents.x, value, PropertyMaxExtentsX == propertyTypeId); ret = ret || RObject::setMember(maxExtents.y, value, PropertyMaxExtentsY == propertyTypeId); ret = ret || RObject::setMember(maxExtents.z, value, PropertyMaxExtentsZ == propertyTypeId); // ret = ret || RObject::setMember(plotPaperMarginLeftMM, value, PropertyPlotPaperMarginLeftMM == propertyTypeId); // ret = ret || RObject::setMember(plotPaperMarginBottomMM, value, PropertyPlotPaperMarginBottomMM == propertyTypeId); // ret = ret || RObject::setMember(plotPaperMarginRightMM, value, PropertyPlotPaperMarginRightMM == propertyTypeId); // ret = ret || RObject::setMember(plotPaperMarginTopMM, value, PropertyPlotPaperMarginTopMM == propertyTypeId); // ret = ret || RObject::setMember(plotPaperSize.x, value, PropertyPlotPaperSizeWidth == propertyTypeId); // ret = ret || RObject::setMember(plotPaperSize.y, value, PropertyPlotPaperSizeHeight == propertyTypeId); // ret = ret || RObject::setMember(plotOrigin.x, value, PropertyPlotOriginX == propertyTypeId); // ret = ret || RObject::setMember(plotOrigin.y, value, PropertyPlotOriginY == propertyTypeId); // ret = ret || RObject::setMember(plotWindowAreaMin.x, value, PropertyPlotWindowAreaMinX == propertyTypeId); // ret = ret || RObject::setMember(plotWindowAreaMin.y, value, PropertyPlotWindowAreaMinY == propertyTypeId); // ret = ret || RObject::setMember(plotWindowAreaMax.x, value, PropertyPlotWindowAreaMaxX == propertyTypeId); // ret = ret || RObject::setMember(plotWindowAreaMax.y, value, PropertyPlotWindowAreaMaxY == propertyTypeId); // ret = ret || RObject::setMember(numeratorCustomScale, value, PropertyNumeratorCustomScale == propertyTypeId); // ret = ret || RObject::setMember(denominatorCustomScale, value, PropertyDenominatorCustomScale == propertyTypeId); // ret = ret || RObject::setMember(plotPaperUnits, value, PropertyPlotPaperUnits == propertyTypeId); // ret = ret || RObject::setMember(plotRotation, value, PropertyPlotRotation == propertyTypeId); return ret; } QPair RLayout::getProperty( RPropertyTypeId& propertyTypeId, bool humanReadable, bool noAttributes) { if (propertyTypeId == PropertyName) { return qMakePair(QVariant(name), RPropertyAttributes()); } else if (propertyTypeId == PropertyTabOrder) { return qMakePair(QVariant(tabOrder), RPropertyAttributes()); } else if (propertyTypeId == PropertyMinLimitsX) { return qMakePair(QVariant(minLimits.x), RPropertyAttributes()); } else if (propertyTypeId == PropertyMinLimitsY) { return qMakePair(QVariant(minLimits.y), RPropertyAttributes()); } else if (propertyTypeId == PropertyMinLimitsZ) { return qMakePair(QVariant(minLimits.z), RPropertyAttributes()); } else if (propertyTypeId == PropertyMaxLimitsX) { return qMakePair(QVariant(maxLimits.x), RPropertyAttributes()); } else if (propertyTypeId == PropertyMaxLimitsY) { return qMakePair(QVariant(maxLimits.y), RPropertyAttributes()); } else if (propertyTypeId == PropertyMaxLimitsZ) { return qMakePair(QVariant(maxLimits.z), RPropertyAttributes()); } else if (propertyTypeId == PropertyInsertionBaseX) { return qMakePair(QVariant(insertionBase.x), RPropertyAttributes()); } else if (propertyTypeId == PropertyInsertionBaseY) { return qMakePair(QVariant(insertionBase.y), RPropertyAttributes()); } else if (propertyTypeId == PropertyInsertionBaseZ) { return qMakePair(QVariant(insertionBase.z), RPropertyAttributes()); } else if (propertyTypeId == PropertyMinExtentsX) { return qMakePair(QVariant(minExtents.x), RPropertyAttributes()); } else if (propertyTypeId == PropertyMinExtentsY) { return qMakePair(QVariant(minExtents.y), RPropertyAttributes()); } else if (propertyTypeId == PropertyMinExtentsZ) { return qMakePair(QVariant(minExtents.z), RPropertyAttributes()); } else if (propertyTypeId == PropertyMaxExtentsX) { return qMakePair(QVariant(maxExtents.x), RPropertyAttributes()); } else if (propertyTypeId == PropertyMaxExtentsY) { return qMakePair(QVariant(maxExtents.y), RPropertyAttributes()); } else if (propertyTypeId == PropertyMaxExtentsZ) { return qMakePair(QVariant(maxExtents.z), RPropertyAttributes()); } // else if (propertyTypeId == PropertyPlotPaperMarginLeftMM) { // return qMakePair(QVariant(plotPaperMarginLeftMM), RPropertyAttributes()); // } // else if (propertyTypeId == PropertyPlotPaperMarginBottomMM) { // return qMakePair(QVariant(plotPaperMarginBottomMM), RPropertyAttributes()); // } // else if (propertyTypeId == PropertyPlotPaperMarginRightMM) { // return qMakePair(QVariant(plotPaperMarginRightMM), RPropertyAttributes()); // } // else if (propertyTypeId == PropertyPlotPaperMarginTopMM) { // return qMakePair(QVariant(plotPaperMarginTopMM), RPropertyAttributes()); // } // else if (propertyTypeId == PropertyPlotPaperSizeWidth) { // return qMakePair(QVariant(plotPaperSize.x), RPropertyAttributes()); // } // else if (propertyTypeId == PropertyPlotPaperSizeHeight) { // return qMakePair(QVariant(plotPaperSize.y), RPropertyAttributes()); // } // else if (propertyTypeId == PropertyPlotOriginX) { // return qMakePair(QVariant(plotOrigin.x), RPropertyAttributes()); // } // else if (propertyTypeId == PropertyPlotOriginY) { // return qMakePair(QVariant(plotOrigin.y), RPropertyAttributes()); // } // else if (propertyTypeId == PropertyPlotWindowAreaMinX) { // return qMakePair(QVariant(plotWindowAreaMin.x), RPropertyAttributes()); // } // else if (propertyTypeId == PropertyPlotWindowAreaMinY) { // return qMakePair(QVariant(plotWindowAreaMin.y), RPropertyAttributes()); // } // else if (propertyTypeId == PropertyPlotWindowAreaMaxX) { // return qMakePair(QVariant(plotWindowAreaMax.x), RPropertyAttributes()); // } // else if (propertyTypeId == PropertyPlotWindowAreaMaxY) { // return qMakePair(QVariant(plotWindowAreaMax.y), RPropertyAttributes()); // } // else if (propertyTypeId == PropertyNumeratorCustomScale) { // return qMakePair(QVariant(numeratorCustomScale), RPropertyAttributes()); // } // else if (propertyTypeId == PropertyDenominatorCustomScale) { // return qMakePair(QVariant(denominatorCustomScale), RPropertyAttributes()); // } // else if (propertyTypeId == PropertyPlotPaperUnits) { // return qMakePair(QVariant(plotPaperUnits), RPropertyAttributes()); // } // else if (propertyTypeId == PropertyPlotRotation) { // return qMakePair(QVariant(plotRotation), RPropertyAttributes()); // } return RObject::getProperty(propertyTypeId, humanReadable, noAttributes); } bool RLayout::isSelectedForPropertyEditing() { return false; } void RLayout::print(QDebug dbg) const { dbg.nospace() << "RLayout("; RObject::print(dbg); dbg.nospace() << ", name: " << getName() << ", insertionBase: " << getInsertionBase() << ")"; } surround360_render/source/render/Camera.cpp /** * Copyright (c) 2016-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE_render file in the root directory of this subproject. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ #include "Camera.h" namespace surround360 { const Camera::Real Camera::kNearInfinity = 1e6; void Camera::setRotation( const Vector3& forward, const Vector3& up, const Vector3& right) { CHECK_LT(right.cross(up).dot(forward), 0) << "rotation must be right-handed"; rotation.row(2) = -forward; // +z is back rotation.row(1) = up; // +y is up rotation.row(0) = right; // +x is right // re-unitarize const Camera::Real tol = 0.001; CHECK(rotation.isUnitary(tol)) << rotation << " is not close to unitary"; Eigen::AngleAxis aa(rotation); rotation = aa.toRotationMatrix(); } void Camera::setRotation(const Vector3& forward, const Vector3& up) { setRotation(forward, up, forward.cross(up)); } Camera::Camera(const Type type, const Vector2& res, const Vector2& focal): type(type), resolution(res), focal(focal) { position.setZero(); rotation.setIdentity(); principal = resolution / 2; distortion.setZero(); setDefaultFov(); } Camera::Camera(const dynamic& json) { CHECK_GE(json["version"].asDouble(), 1.0); id = json["id"].getString(); type = deserializeType(json["type"]); position = deserializeVector<3>(json["origin"]); setRotation( deserializeVector<3>(json["forward"]), deserializeVector<3>(json["up"]), deserializeVector<3>(json["right"])); resolution = deserializeVector<2>(json["resolution"]); if (json.count("principal")) { principal = deserializeVector<2>(json["principal"]); } else { principal = resolution / 2; } if (json.count("distortion")) { distortion = deserializeVector<2>(json["distortion"]); } else { distortion.setZero(); } if (json.count("fov")) { setFov(json["fov"].asDouble()); } else { setDefaultFov(); } focal = deserializeVector<2>(json["focal"]); if (json.count("group")) { group = json["group"].getString(); } } #ifndef SUPPRESS_RIG_IO dynamic Camera::serialize() const { dynamic result = dynamic::object ("version", 1) ("type", serializeType(type)) ("origin", serializeVector(position)) ("forward", serializeVector(forward())) ("up", serializeVector(up())) ("right", serializeVector(right())) ("resolution", serializeVector(resolution)) ("principal", serializeVector(principal)) ("focal", serializeVector(focal)) ("id", id); if (!distortion.isZero()) { result["distortion"] = serializeVector(distortion); } if (!isDefaultFov()) { result["fov"] = getFov(); } if (!group.empty()) { result["group"] = group; } return result; } #endif // SUPPRESS_RIG_IO void Camera::setRotation(const Vector3& angleAxis) { // convert angle * axis to rotation matrix Real angle = angleAxis.norm(); Vector3 axis = angleAxis / angle; if (angle == 0) { axis = Vector3::UnitX(); } rotation = Eigen::AngleAxis(angle, axis).toRotationMatrix(); } Camera::Vector3 Camera::getRotation() const { // convert rotation matrix to angle * axis Eigen::AngleAxis angleAxis(rotation); if (angleAxis.angle() > M_PI) { angleAxis.angle() = 2 * M_PI - angleAxis.angle(); angleAxis.axis() = -angleAxis.axis(); } return angleAxis.angle() * angleAxis.axis(); } void Camera::setScalarFocal(const Real& scalar) { focal = { scalar, -scalar }; } Camera::Real Camera::getScalarFocal() const { CHECK_EQ(focal.x(), -focal.y()) << "pixels are not square"; return focal.x(); } void Camera::setFov(const Real& fov) { CHECK(fov <= M_PI / 2 || type == Type::FTHETA); Real cosFov = std::cos(fov); fovThreshold = cosFov * std::abs(cosFov); } Camera::Real Camera::getFov() const { return fovThreshold < 0 ? std::acos(-std::sqrt(-fovThreshold)) : std::acos(std::sqrt(fovThreshold)); } void Camera::setDefaultFov() { if (type == Type::FTHETA) { fovThreshold = -1; } else { CHECK(type == Type::RECTILINEAR) << "unexpected: " << int(type); fovThreshold = 0; } } bool Camera::isDefaultFov() const { return type == Type::FTHETA ? fovThreshold == -1 : fovThreshold == 0; } Camera::Real cross2(const Camera::Vector2& a, const Camera::Vector2& b) { return -a.y() * b.x() + a.x() * b.y(); } Camera::Vector3 midpoint( const Camera::Ray& a, const Camera::Ray& b, const bool forceInFront) { // this is the mid-point method // find ta and tb that minimizes the distance between // a(ta) = pa + ta * va and b(tb) = pb + tb * vb: // then return the mid-point between a(ta) and b(tb) // d(a - b)^2/dta = 0 && // d(a - b)^2/dtb = 0 <=> // dot( va, 2 * (a(ta) - b(tb))) = 0 && // dot(-vb, 2 * (a(ta) - b(tb))) = 0 <=> // dot(va, a(ta) - b(tb)) = 0 && // dot(vb, a(ta) - b(tb)) = 0 <=> // dot(va, pa) + ta * dot(va, va) - dot(va, pb) - tb * dot(va, vb) = 0 && // dot(vb, pa) + ta * dot(vb, va) - dot(vb, pb) - tb * dot(vb, vb) = 0 <=> // reformulate as vectors // fa * ta - fb * tb + fc = (0, 0), where // m = rows(va, vb) // fa = m * va // fb = m * vb // fc = m * (pa - pb) // -det(fa, fb) * ta + det(fb, fc) = 0 && // -det(fa, fb) * tb + det(fa, fc) = 0 <=> // ta = det(fb, fc) / det(fa, fb) && // tb = det(fa, fc) / det(fa, fb) Eigen::Matrix m; m.row(0) = a.direction(); m.row(1) = b.direction(); Camera::Vector2 fa = m * a.direction(); Camera::Vector2 fb = m * b.direction(); Camera::Vector2 fc = m * (a.origin() - b.origin()); Camera::Real det = cross2(fa, fb); Camera::Real ta = cross2(fb, fc) / det; Camera::Real tb = cross2(fa, fc) / det; // check for parallel lines if (!std::isfinite(ta) || !std::isfinite(tb)) { ta = tb = Camera::kNearInfinity; } // check whether intersection is behind camera if (forceInFront && (ta < 0 || tb < 0)) { ta = tb = Camera::kNearInfinity; } Camera::Vector3 pa = a.pointAt(ta); Camera::Vector3 pb = b.pointAt(tb); return (pa + pb) / 2; } #ifdef WIN32 Camera::Rig Camera::loadRig(const std::string& filename) { boost::property_tree::ptree tree; boost::property_tree::json_parser::read_json(std::ifstream(filename), tree); Camera::Rig rig; for (const auto& camera : tree.get_child("cameras")) { rig.emplace_back(camera.second); } return rig; } #else // WIN32 std::vector Camera::loadRig(const std::string& filename) { std::string json; folly::readFile(filename.c_str(), json); CHECK(!json.empty()) << "could not read JSON file: " << filename; dynamic dynamic = folly::parseJson(json); std::vector cameras; for (const auto& camera : dynamic["cameras"]) { cameras.emplace_back(camera); } return cameras; } #endif // WIN32 #ifndef SUPPRESS_RIG_IO void Camera::saveRig( const std::string& filename, const std::vector& cameras) { dynamic dynamic = dynamic::object( "cameras", dynamic::array()); for (const auto& camera : cameras) { dynamic["cameras"].push_back(camera.serialize()); } folly::writeFile(folly::toPrettyJson(dynamic), filename.c_str()); } // takes a camera and a scale factor. returns a camera model equivalent to // changing the resolution of the original camera Camera Camera::createRescaledCamera( const Camera& cam, const float scale) { Camera scaledCam(cam); scaledCam.resolution = Camera::Vector2( int(cam.resolution.x() * scale), int(cam.resolution.y() * scale)); const float scaleX = scaledCam.resolution.x() / cam.resolution.x(); const float scaleY = scaledCam.resolution.y() / cam.resolution.y(); scaledCam.principal.x() *= scaleX; scaledCam.principal.y() *= scaleY; scaledCam.focal.x() *= scaleX; scaledCam.focal.y() *= scaleY; return scaledCam; } void Camera::unitTest() { dynamic serialized = dynamic::object ("version", 1) ("type", "FTHETA") ("origin", dynamic::array( -10.51814, 13.00734, -4.22656)) ("forward", dynamic::array( -0.6096207796429852, 0.7538922995778138, -0.24496715221587234)) ("up", dynamic::array( 0.7686134846014325, 0.6376793279268061, 0.050974366338976666)) ("right", dynamic::array( 0.19502945167097138, -0.15702371237098722, -0.9681462011153862)) ("resolution", dynamic::array(2448, 2048)) ("focal", dynamic::array(1240, -1240)) ("id", "cam9"); Camera camera(serialized); CHECK_EQ(camera.id, "cam9"); CHECK_EQ(camera.position, Camera::Vector3(-10.51814, 13.00734, -4.22656)); // use isApprox() because camera orthogonalizes the rotation Camera::Vector3 right( 0.19502945167097138, -0.15702371237098722, -0.9681462011153862); CHECK(camera.right().isApprox(right, 1e-3)) << camera.right(); auto center = camera.pixel(camera.position + camera.forward()); CHECK_NEAR(2448 / 2, center.x(), 1e-10); CHECK_NEAR(2048 / 2, center.y(), 1e-10); // check fov CHECK(camera.isDefaultFov()); CHECK(camera.sees(camera.rigNearInfinity({ 1, 1 }))); camera.setFov(0.9 * M_PI); CHECK_NEAR(camera.getFov(), 0.9 * M_PI, 1e-10); camera.setFov(0.1 * M_PI); CHECK_NEAR(camera.getFov(), 0.1 * M_PI, 1e-10); CHECK(!camera.sees(camera.rigNearInfinity({ 1, 1 }))); CHECK(camera.sees(camera.rigNearInfinity({ 1200, 1000 }))); camera.setDefaultFov(); CHECK(camera.sees(camera.rigNearInfinity({ 1, 1 }))); { // check that rig undoes pixel auto d = 3.1; auto expected = camera.position + d * Camera::Vector3(-2, 3, -1).normalized(); auto actual = camera.rig(camera.pixel(expected)).pointAt(d); CHECK(expected.isApprox(actual)) << actual << " " << expected; // check that this survives getting/setting parameters Camera modified = camera; modified.setRotation(camera.getRotation()); auto modifiedActual = modified.rig(modified.pixel(expected)).pointAt(d); CHECK(expected.isApprox(modifiedActual)) << expected << "\n\n" << modifiedActual; CHECK(modified.getRotation().isApprox(camera.getRotation())) << modified.getRotation() << "\n\n" << camera.getRotation(); } { // check that undistort undoes no-op distort Real expected = 3; Real distorted = camera.distort(expected); Real undistorted = camera.undistort(distorted); CHECK_NEAR(expected, undistorted, 1.0 / kNearInfinity); } { // check that undistort undoes distort camera.distortion[0] = 0.20; camera.distortion[1] = 0.02; Real expected = 3; Real distorted = camera.distort(expected); Real undistorted = camera.undistort(distorted); CHECK_NEAR(expected, undistorted, 1.0 / kNearInfinity); } // lines intersect at (1, 2, 3) Camera::Ray a(Camera::Vector3(11, 12, -17), Camera::Vector3(-1, -1, 2)); Camera::Ray b(Camera::Vector3(-8, -4, 0), Camera::Vector3(3, 2, 1)); auto ab = midpoint(a, b, false); CHECK(ab.isApprox(Camera::Vector3(1, 2, 3))) << ab; // lines do not intersect, but are at their closest near (1, 1, 1) Camera::Ray c(Camera::Vector3(2, 2, 2), Camera::Vector3(-1, -1, 0)); Camera::Ray d(Camera::Vector3(0, 2, 0), Camera::Vector3(1, -1, 0)); auto cd = midpoint(c, d, false); CHECK(cd.isApprox(Camera::Vector3(1, 1, 1))) << cd; // lines are parallel Camera::Ray e(Camera::Vector3(2, 2, 2), Camera::Vector3(1, 2, 3)); Camera::Ray f(Camera::Vector3(1, 2, 3), Camera::Vector3(-1, -2, -3)); auto ef = midpoint(e, f, false); CHECK(ef.isApprox(Camera::Vector3(1.5, 2, 2.5))) << ef; { Camera::Ray a(Camera::Vector3(11, 12, -17), Camera::Vector3(-1, -1, 2)); Camera::Ray b(Camera::Vector3(-7, 5, -7), Camera::Vector3(0, 0, 0)); b.direction() = (a.pointAt(10) - b.origin()) / 10; Camera::Vector3 i = midpoint(a, b, false); CHECK(i.isApprox(a.pointAt(10))) << i; Camera::Vector3 ortho = a.direction().cross(b.direction()); a.origin() += ortho; b.origin() -= ortho; CHECK(midpoint(a, b, false).isApprox(i)) << midpoint(a, b, false); } } #endif // SUPPRESS_RIG_IO } // namespace surround360 /* * Copyright 2013 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkPdfNativeObject.h" #include "SkBitmap.h" #include "SkFlate.h" #include "SkPdfFont.h" #include "SkPdfNativeTokenizer.h" #include "SkPdfReporter.h" #include "SkStream.h" // TODO(edisonn): mac builder does not find the header ... but from headers is ok //#include "SkPdfStreamCommonDictionary_autogen.h" #include "SkPdfHeaders_autogen.h" SkPdfNativeObject SkPdfNativeObject::kNull = SkPdfNativeObject::makeNull(); bool SkPdfNativeObject::applyFlateDecodeFilter() { if (!SkFlate::HaveFlate()) { SkPdfReport(kIgnoreError_SkPdfIssueSeverity, kNoFlateLibrary_SkPdfIssue, "forgot to link with flate library?", NULL, NULL); return false; } const unsigned char* old = fStr.fBuffer; bool deleteOld = isStreamOwned(); SkMemoryStream skstream(fStr.fBuffer, fStr.fBytes >> 2, false); SkDynamicMemoryWStream uncompressedData; if (SkFlate::Inflate(&skstream, &uncompressedData)) { fStr.fBytes = (uncompressedData.bytesWritten() << 2) + kOwnedStreamBit + kUnfilteredStreamBit; fStr.fBuffer = (const unsigned char*)new unsigned char[uncompressedData.bytesWritten()]; uncompressedData.copyTo((void*)fStr.fBuffer); if (deleteOld) { delete[] old; } return true; } else { SkPdfReport(kIgnoreError_SkPdfIssueSeverity, kBadStream_SkPdfIssue, "inflate failed", this, NULL); return false; } } bool SkPdfNativeObject::applyDCTDecodeFilter() { // applyDCTDecodeFilter will fail, and it won't allow any more filters. // technically, it would be possible, but not a real world scenario. // in this way we create the image from the DCT stream directly. return false; } bool SkPdfNativeObject::applyFilter(const char* name) { if (strcmp(name, "FlateDecode") == 0) { return applyFlateDecodeFilter(); } else if (strcmp(name, "DCTDecode") == 0) { return applyDCTDecodeFilter(); } SkPdfReport(kCodeWarning_SkPdfIssueSeverity, kNYI_SkPdfIssue, "filter not supported", this, NULL); return false; } bool SkPdfNativeObject::filterStream() { SkPdfMarkObjectUsed(); if (!hasStream()) { SkPdfReport(kIgnoreError_SkPdfIssueSeverity, kBadStream_SkPdfIssue, "No Stream", this, NULL); return false; } if (isStreamFiltered()) { return true; } SkPdfStreamCommonDictionary* stream = (SkPdfStreamCommonDictionary*)this; if (!stream->has_Filter()) { fStr.fBytes = ((fStr.fBytes >> 1) << 1) + kFilteredStreamBit; } else if (stream->isFilterAName(NULL)) { SkString filterName = stream->getFilterAsName(NULL); applyFilter(filterName.c_str()); } else if (stream->isFilterAArray(NULL)) { const SkPdfArray* filters = stream->getFilterAsArray(NULL); int cnt = (int) filters->size(); for (int i = cnt - 1; i >= 0; i--) { const SkPdfNativeObject* filterName = filters->objAtAIndex(i); if (filterName != NULL && filterName->isName()) { if (!applyFilter(filterName->nameValue())) { break; } } else { SkPdfReport(kIgnoreError_SkPdfIssueSeverity, kIncositentSyntax_SkPdfIssue, "filter name should be a Name", this, NULL); } } } return true; } void SkPdfNativeObject::releaseData() { #ifdef PDF_TRACK_OBJECT_USAGE SkPdfReportIf(!fUsed, kInfo_SkPdfIssueSeverity, kUnusedObject_SkPdfIssue, "Unused object in rendering", this, NULL); #endif // PDF_TRACK_OBJECT_USAGE SkPdfMarkObjectUnused(); if (fData) { switch (fDataType) { case kFont_Data: delete (SkPdfFont*)fData; break; case kBitmap_Data: delete (SkBitmap*)fData; break; default: SkASSERT(false); break; } } fData = NULL; fDataType = kEmpty_Data; } #include #include #include //#include #include namespace yosemite { namespace native_token { bool ntoken::check_identity_auth_for_transfer(account_name account, const ntoken_kyc_rule_type &kycrule_type) { eosio_assert(static_cast(!identity::has_account_state(account, YOSEMITE_ID_ACC_STATE_BLACKLISTED)), "account is blacklisted by identity authority"); switch (kycrule_type) { case NTOKEN_KYC_RULE_TYPE_TRANSFER_SEND: eosio_assert(static_cast(!identity::has_account_state(account, YOSEMITE_ID_ACC_STATE_BLACKLISTED_NTOKEN_SEND)), "account is send-blacklisted by identity authority"); break; case NTOKEN_KYC_RULE_TYPE_TRANSFER_RECEIVE: eosio_assert(static_cast(!identity::has_account_state(account, YOSEMITE_ID_ACC_STATE_BLACKLISTED_NTOKEN_RECEIVE)), "account is receive-blacklisted by identity authority"); break; case NTOKEN_KYC_RULE_TYPE_MAX: // ignored break; } kyc_rule_index kyc_rule(get_self(), get_self()); const auto &rule = kyc_rule.get(kycrule_type, "KYC rule is not set; use setkycrule operation to set"); return identity::has_all_kyc_status(account, rule.kyc_flags); } void ntoken::nissue(const account_name &to, const yx_asset &token, const string &memo) { eosio_assert(static_cast(token.is_valid()), "invalid token"); eosio_assert(static_cast(token.amount > 0), "must be positive token"); eosio_assert(static_cast(token.symbol.value == YOSEMITE_NATIVE_TOKEN_SYMBOL), "cannot issue non-native token with this operation or wrong precision is specified"); eosio_assert(static_cast(memo.size() <= 256), "memo has more than 256 bytes"); require_auth(token.issuer); //eosio_assert(static_cast(is_authorized_sys_depository(token.issuer)), // "issuer account is not system depository"); stats_native stats(get_self(), token.issuer); const auto &tstats = stats.find(NTOKEN_BASIC_STATS_KEY); if (tstats == stats.end()) { stats.emplace(get_self(), [&](auto &s) { s.key = NTOKEN_BASIC_STATS_KEY; s.supply = asset{token.amount, YOSEMITE_NATIVE_TOKEN_SYMBOL}; }); } else { stats.modify(tstats, 0, [&](auto &s) { s.supply.amount += token.amount; eosio_assert(static_cast(s.supply.amount > 0 && s.supply.amount <= asset::max_amount), "cannot issue token more than 2^62 - 1"); }); } add_native_token_balance(token.issuer, token); if (to != token.issuer) { INLINE_ACTION_SENDER(ntoken, ntransfer) (get_self(), {{token.issuer, N(active)}, {YOSEMITE_SYSTEM_ACCOUNT, N(active)}}, {token.issuer, to, token, memo}); } charge_transaction_fee(token.issuer, YOSEMITE_TX_FEE_OP_NAME_NTOKEN_ISSUE); } void ntoken::nredeem(const yx_asset &token, const string &memo) { eosio_assert(static_cast(token.is_valid()), "invalid token"); eosio_assert(static_cast(token.amount > 0), "must be positive token"); eosio_assert(static_cast(token.symbol.value == YOSEMITE_NATIVE_TOKEN_SYMBOL), "cannot redeem non-native token with this operation or wrong precision is specified"); eosio_assert(static_cast(memo.size() <= 256), "memo has more than 256 bytes"); require_auth(token.issuer); //eosio_assert(static_cast(is_authorized_sys_depository(token.issuer)), // "issuer account is not system depository"); stats_native stats(get_self(), token.issuer); const auto &tstats = stats.get(NTOKEN_BASIC_STATS_KEY, "createn for the issuer is not called"); eosio_assert(static_cast(tstats.supply.amount >= token.amount), "insufficient supply of the native token of the specified depository"); stats.modify(tstats, 0, [&](auto &s) { s.supply.amount -= token.amount; }); sub_native_token_balance(token.issuer, token); charge_transaction_fee(token.issuer, YOSEMITE_TX_FEE_OP_NAME_NTOKEN_REDEEM); } void ntoken::transfer(account_name from, account_name to, eosio::asset amount, const string &memo) { bool called_by_system_contract = has_auth(YOSEMITE_SYSTEM_ACCOUNT); if (!called_by_system_contract) { eosio_assert(static_cast(yx_asset{amount, 0}.is_valid()), "invalid amount"); eosio_assert(static_cast(amount.amount > 0), "must transfer positive amount"); eosio_assert(static_cast(amount.symbol.value == YOSEMITE_NATIVE_TOKEN_SYMBOL), "only native token is supported; use yx.token::transfer instead"); eosio_assert(static_cast(from != to), "from and to account cannot be the same"); eosio_assert(static_cast(memo.size() <= 256), "memo has more than 256 bytes"); require_auth(from); eosio_assert(static_cast(is_account(to)), "to account does not exist"); } // NOTE:We don't need notification to from and to account here. It's done by several ntransfer operation. eosio_assert(static_cast(check_identity_auth_for_transfer(from, NTOKEN_KYC_RULE_TYPE_TRANSFER_SEND)), "KYC authentication for from account is failed"); eosio_assert(static_cast(check_identity_auth_for_transfer(to, NTOKEN_KYC_RULE_TYPE_TRANSFER_RECEIVE)), "KYC authentication for to account is failed"); const account_name tx_fee_payer = trx_fee_payer(); const account_name payer = tx_fee_payer != 0 ? tx_fee_payer : from; accounts_native accounts_table_native(get_self(), from); for (auto &balance_holder : accounts_table_native) { yx_symbol native_token_symbol{YOSEMITE_NATIVE_TOKEN_SYMBOL, balance_holder.token.issuer}; int64_t to_balance = 0; if (balance_holder.token.amount <= amount.amount) { to_balance = balance_holder.token.amount; amount.amount -= to_balance; } else { to_balance = amount.amount; amount.amount = 0; } INLINE_ACTION_SENDER(ntoken, ntransfer) (get_self(), {{from, N(active)}, {YOSEMITE_SYSTEM_ACCOUNT, N(active)}}, {from, to, {to_balance, native_token_symbol}, memo}); if (amount.amount == 0) { break; } } eosio_assert(static_cast(amount.amount == 0), "from account cannot afford native token amount"); if (!called_by_system_contract) { charge_transaction_fee(payer, YOSEMITE_TX_FEE_OP_NAME_NTOKEN_TRANSFER); } } void ntoken::ntransfer(account_name from, account_name to, const yx_asset &token, const string &memo) { bool called_by_system_contract = has_auth(YOSEMITE_SYSTEM_ACCOUNT); if (!called_by_system_contract) { eosio_assert(static_cast(token.is_valid()), "invalid token"); eosio_assert(static_cast(token.amount > 0), "must transfer positive amount"); eosio_assert(static_cast(token.symbol.value == YOSEMITE_NATIVE_TOKEN_SYMBOL), "only native token is supported; use yx.token::transfer instead"); eosio_assert(static_cast(from != to), "from and to account cannot be the same"); eosio_assert(static_cast(memo.size() <= 256), "memo has more than 256 bytes"); require_auth(from); eosio_assert(static_cast(is_account(to)), "to account does not exist"); } eosio_assert(static_cast(check_identity_auth_for_transfer(from, NTOKEN_KYC_RULE_TYPE_TRANSFER_SEND)), "KYC authentication for from account is failed"); eosio_assert(static_cast(check_identity_auth_for_transfer(to, NTOKEN_KYC_RULE_TYPE_TRANSFER_RECEIVE)), "KYC authentication for to account is failed"); require_recipient(from); require_recipient(to); sub_native_token_balance(from, token); add_native_token_balance(to, token); if (!called_by_system_contract) { charge_transaction_fee(from, YOSEMITE_TX_FEE_OP_NAME_NTOKEN_NTRANSFER); } } void ntoken::payfee(account_name payer, const asset &fee) { require_auth(payer); // just for sure require_auth(YOSEMITE_SYSTEM_ACCOUNT); if (fee.amount <= 0) return; eosio_assert(static_cast(check_identity_auth_for_transfer(payer, NTOKEN_KYC_RULE_TYPE_TRANSFER_SEND)), "KYC authentication for the fee payer account is failed"); require_recipient(payer); require_recipient(YOSEMITE_TX_FEE_ACCOUNT); auto remained_fee = fee.amount; accounts_native accounts_table_native(YOSEMITE_NATIVE_TOKEN_ACCOUNT, payer); for (auto &balance_holder : accounts_table_native) { yx_asset yxfee{0, yx_symbol{YOSEMITE_NATIVE_TOKEN_SYMBOL, balance_holder.token.issuer}}; if (balance_holder.token.amount >= remained_fee) { yxfee.amount = remained_fee; remained_fee = 0; } else { yxfee.amount = balance_holder.token.amount; remained_fee -= balance_holder.token.amount; } sub_native_token_balance(payer, yxfee); add_native_token_balance(YOSEMITE_TX_FEE_ACCOUNT, yxfee); if (remained_fee == 0) { break; } } eosio_assert(static_cast(remained_fee == 0), "payer account cannot afford transaction fee"); // transaction fee cannot exceed 32-bit integer in reality cast_transaction_vote(static_cast(fee.amount)); } void ntoken::add_native_token_balance(const account_name &owner, const yx_asset &token) { accounts_native accounts_table_native(get_self(), owner); const auto &native_holder = accounts_table_native.find(token.issuer); if (native_holder == accounts_table_native.end()) { accounts_table_native.emplace(get_self(), [&](auto &holder) { holder.token = token; }); } else { accounts_table_native.modify(native_holder, 0, [&](auto &holder) { holder.token += token; eosio_assert(static_cast(holder.token.amount > 0 && holder.token.amount <= asset::max_amount), "token amount cannot be more than 2^62 - 1"); }); } accounts_native_total accounts_table_total(get_self(), owner); const auto &total_holder = accounts_table_total.find(NTOKEN_TOTAL_BALANCE_KEY); if (total_holder == accounts_table_total.end()) { accounts_table_total.emplace(get_self(), [&](auto &tot_holder) { tot_holder.amount.amount = token.amount; tot_holder.amount.symbol = token.symbol; }); } else { accounts_table_total.modify(total_holder, 0, [&](auto &tot_holder) { tot_holder.amount.amount += token.amount; eosio_assert(static_cast(tot_holder.amount.amount > 0 && tot_holder.amount.amount <= asset::max_amount), "token amount cannot be more than 2^62 - 1"); }); } } void ntoken::sub_native_token_balance(const account_name &owner, const yx_asset &token) { accounts_native accounts_table_native(get_self(), owner); const auto &native_holder = accounts_table_native.get(token.issuer, "account doesn't have native token of the specified depository"); eosio_assert(static_cast(native_holder.token.amount >= token.amount), "insufficient native token of the specified depository"); bool erase; accounts_table_native.modify(native_holder, 0, [&](auto &holder) { holder.token -= token; erase = holder.token.amount == 0; }); if (erase) { accounts_table_native.erase(native_holder); } accounts_native_total accounts_table_total(get_self(), owner); const auto &total_holder = accounts_table_total.get(NTOKEN_TOTAL_BALANCE_KEY, "account doesn't have native token balance"); eosio_assert(static_cast(total_holder.amount.amount >= token.amount), "insufficient total native token"); accounts_table_total.modify(total_holder, 0, [&](auto &tot_holder) { tot_holder.amount.amount -= token.amount; erase = tot_holder.amount.amount == 0; }); if (erase) { accounts_table_total.erase(total_holder); } } void ntoken::setkycrule(uint8_t type, identity::identity_kyc_t kyc) { eosio_assert(static_cast(type < NTOKEN_KYC_RULE_TYPE_MAX), "invalid type"); require_auth(YOSEMITE_SYSTEM_ACCOUNT); kyc_rule_index kyc_rule(get_self(), get_self()); auto itr = kyc_rule.find(type); if (itr == kyc_rule.end()) { kyc_rule.emplace(get_self(), [&](auto &holder) { holder.type = type; holder.kyc_flags = kyc; }); } else { kyc_rule.modify(itr, 0, [&](auto &holder) { holder.kyc_flags = kyc; }); } } }} // namespace native_token yosemite EOSIO_ABI(yosemite::native_token::ntoken, (nissue)(nredeem)(transfer)(ntransfer)(payfee)(setkycrule) ) #include "MotionLayer.h" #include "BlendTree.h" #include "Base/GlobalEnum.h" #include "FileSystem/YamlNode.h" #include "Reflection/ReflectionRegistrator.h" #include "Reflection/ReflectedMeta.h" ENUM_DECLARE(DAVA::MotionLayer::eMotionBlend) { ENUM_ADD_DESCR(DAVA::MotionLayer::eMotionBlend::BLEND_OVERRIDE, "Override"); ENUM_ADD_DESCR(DAVA::MotionLayer::eMotionBlend::BLEND_ADD, "Add"); ENUM_ADD_DESCR(DAVA::MotionLayer::eMotionBlend::BLEND_DIFF, "Diff"); }; namespace DAVA { DAVA_REFLECTION_IMPL(MotionLayer) { ReflectionRegistrator::Begin() .Field("layerID", &MotionLayer::layerID)[M::ReadOnly()] .End(); } void MotionLayer::TriggerEvent(const FastName& trigger) { const Motion::TransitionInfo& transitionInfo = (nextMotion != nullptr && motionTransition.IsStarted()) ? nextMotion->GetTransitionInfo(trigger) : currentMotion->GetTransitionInfo(trigger); if (transitionInfo.info != nullptr && transitionInfo.motion != nullptr) { pendingTransition = transitionInfo.info; pendingMotion = transitionInfo.motion; } } void MotionLayer::Update(float32 dTime) { if (pendingMotion != nullptr) { if (currentMotion != nullptr) { if (nextMotion != nullptr && motionTransition.IsStarted()) { if (pendingTransition != nullptr && motionTransition.CanBeInterrupted(pendingTransition, nextMotion, pendingMotion)) { motionTransition.Interrupt(pendingTransition, nextMotion, pendingMotion); currentMotion = nextMotion; nextMotion = pendingMotion; pendingMotion = nullptr; pendingTransition = nullptr; } } else { if (pendingTransition != nullptr) { motionTransition.Reset(pendingTransition, currentMotion, pendingMotion); nextMotion = pendingMotion; nextMotion->Reset(); pendingMotion = nullptr; pendingTransition = nullptr; } } } else { currentMotion = pendingMotion; currentMotion->Reset(); } } ////////////////////////////////////////////////////////////////////////// if (nextMotion != nullptr) //transition is active { motionTransition.Update(dTime); } else { currentMotion->Update(dTime); } ////////////////////////////////////////////////////////////////////////// reachedMarkers.clear(); for (const FastName& m : currentMotion->GetReachedMarkers()) reachedMarkers.emplace_back(currentMotion->GetID(), m); if (nextMotion != nullptr && motionTransition.IsStarted()) { for (const FastName& m : nextMotion->GetReachedMarkers()) reachedMarkers.emplace_back(nextMotion->GetID(), m); } endedMotions.clear(); if (currentMotion->IsAnimationEndReached()) endedMotions.emplace_back(currentMotion->GetID()); ////////////////////////////////////////////////////////////////////////// currentPose.Reset(); if (nextMotion != nullptr) //transition is active { motionTransition.Evaluate(¤tPose, ¤tRootOffsetDelta); } else { currentMotion->EvaluatePose(¤tPose); currentMotion->GetRootOffsetDelta(¤tRootOffsetDelta); } ////////////////////////////////////////////////////////////////////////// if (nextMotion != nullptr) //transition is active { if (motionTransition.IsComplete()) { currentMotion = nextMotion; nextMotion = nullptr; } } ////////////////////////////////////////////////////////////////////////// currentRootOffsetDelta *= rootExtractionMask; if (rootNodeJointIndex != SkeletonComponent::INVALID_JOINT_INDEX) { Vector3 rootPosition = currentPose.GetJointTransform(rootNodeJointIndex).GetPosition(); rootPosition *= rootResetMask; currentPose.SetPosition(rootNodeJointIndex, rootPosition); } } void MotionLayer::BindSkeleton(const SkeletonComponent* skeleton) { for (Motion& s : motions) s.BindSkeleton(skeleton); if (currentMotion != nullptr) { currentPose.Reset(); currentMotion->Reset(); currentMotion->EvaluatePose(¤tPose); currentMotion->GetRootOffsetDelta(¤tRootOffsetDelta); } rootNodeJointIndex = skeleton->GetJointIndex(rootNodeID); } bool MotionLayer::BindParameter(const FastName& parameterID, const float32* param) { bool success = false; for (Motion& s : motions) success |= s.BindParameter(parameterID, param); return success; } bool MotionLayer::UnbindParameter(const FastName& parameterID) { return BindParameter(parameterID, nullptr); } void MotionLayer::UnbindParameters() { for (Motion& m : motions) m.UnbindParameters(); } const Vector& MotionLayer::GetMotionIDs() const { return motionsIDs; } MotionLayer* MotionLayer::LoadFromYaml(const YamlNode* motionNode) { MotionLayer* motionLayer = new MotionLayer(); int32 enumValue; Set motionsParameters; const YamlNode* layerIDNode = motionNode->Get("layer-id"); if (layerIDNode != nullptr && layerIDNode->GetType() == YamlNode::TYPE_STRING) { motionLayer->layerID = layerIDNode->AsFastName(); } const YamlNode* blendModeNode = motionNode->Get("blend-mode"); if (blendModeNode != nullptr && blendModeNode->GetType() == YamlNode::TYPE_STRING) { if (GlobalEnumMap::Instance()->ToValue(blendModeNode->AsString().c_str(), enumValue)) motionLayer->blendMode = eMotionBlend(enumValue); } FastName defaultMotionID; const YamlNode* defaultMotionNode = motionNode->Get("default-motion"); if (defaultMotionNode != nullptr && defaultMotionNode->GetType() == YamlNode::TYPE_STRING) { defaultMotionID = defaultMotionNode->AsFastName(); } const YamlNode* motionsNode = motionNode->Get("motions"); if (motionsNode != nullptr && motionsNode->GetType() == YamlNode::TYPE_ARRAY) { uint32 motionsCount = motionsNode->GetCount(); motionLayer->motions.resize(motionsCount); motionLayer->motionsIDs.resize(motionsCount); for (uint32 m = 0; m < motionsCount; ++m) { Motion& motion = motionLayer->motions[m]; motion.LoadFromYaml(motionsNode->Get(m)); motionLayer->motionsIDs[m] = motion.GetID(); const Vector& blendTreeParams = motion.GetBlendTreeParameters(); motionsParameters.insert(blendTreeParams.begin(), blendTreeParams.end()); if (defaultMotionID == motion.GetID()) motionLayer->currentMotion = motionLayer->motions.data() + m; } if (motionLayer->currentMotion == nullptr && motionsCount > 0) motionLayer->currentMotion = motionLayer->motions.data(); } const YamlNode* transitionsNode = motionNode->Get("transitions"); if (transitionsNode != nullptr && transitionsNode->GetType() == YamlNode::TYPE_ARRAY) { uint32 transitionsCount = transitionsNode->GetCount(); motionLayer->transitions.resize(transitionsCount); for (uint32 t = 0; t < transitionsCount; ++t) { const YamlNode* transitionNode = transitionsNode->Get(t); const YamlNode* srcNode = transitionNode->Get("src-motion"); const YamlNode* dstNode = transitionNode->Get("dst-motion"); const YamlNode* triggerNode = transitionNode->Get("trigger"); if (srcNode != nullptr && srcNode->GetType() == YamlNode::TYPE_STRING && dstNode != nullptr && dstNode->GetType() == YamlNode::TYPE_STRING && triggerNode != nullptr && triggerNode->GetType() == YamlNode::TYPE_STRING) { uint32 srcPhase = std::numeric_limits::max(); const YamlNode* srcPhaseNode = transitionNode->Get("src-phase"); if (srcPhaseNode != nullptr && srcPhaseNode->GetType() == YamlNode::TYPE_STRING) srcPhase = srcPhaseNode->AsUInt32(); FastName srcName = srcNode->AsFastName(); FastName dstName = dstNode->AsFastName(); FastName trigger = triggerNode->AsFastName(); auto foundSrc = std::find_if(motionLayer->motions.begin(), motionLayer->motions.end(), [&srcName](const Motion& motion) { return motion.GetID() == srcName; }); auto foundDst = std::find_if(motionLayer->motions.begin(), motionLayer->motions.end(), [&dstName](const Motion& motion) { return motion.GetID() == dstName; }); if (foundSrc != motionLayer->motions.end() && foundDst != motionLayer->motions.end()) { motionLayer->transitions[t] = MotionTransitionInfo::LoadFromYaml(transitionNode); foundSrc->AddTransition(trigger, &motionLayer->transitions[t], &(*foundDst), srcPhase); } } } } const YamlNode* rootTransformNode = motionNode->Get("root-transform"); if (rootTransformNode != nullptr && rootTransformNode->GetType() == YamlNode::TYPE_MAP) { const YamlNode* rootIDNode = rootTransformNode->Get("root-node"); if (rootIDNode != nullptr && rootIDNode->GetType() == YamlNode::TYPE_STRING) { FastName rootID = rootIDNode->AsFastName(); for (Motion& motion : motionLayer->motions) motion.BindRootNode(rootID); motionLayer->rootNodeID = rootID; const YamlNode* extractPositionNode = nullptr; { extractPositionNode = rootTransformNode->Get("extract-position-x"); if (extractPositionNode != nullptr && extractPositionNode->GetType() == YamlNode::TYPE_STRING && extractPositionNode->AsBool() == true) motionLayer->rootExtractionMask.x = 1.f; extractPositionNode = rootTransformNode->Get("extract-position-y"); if (extractPositionNode != nullptr && extractPositionNode->GetType() == YamlNode::TYPE_STRING && extractPositionNode->AsBool() == true) motionLayer->rootExtractionMask.y = 1.f; extractPositionNode = rootTransformNode->Get("extract-position-z"); if (extractPositionNode != nullptr && extractPositionNode->GetType() == YamlNode::TYPE_STRING && extractPositionNode->AsBool() == true) motionLayer->rootExtractionMask.z = 1.f; } const YamlNode* resetPositionNode = nullptr; { resetPositionNode = rootTransformNode->Get("reset-position-x"); if (resetPositionNode != nullptr && resetPositionNode->GetType() == YamlNode::TYPE_STRING && resetPositionNode->AsBool() == true) motionLayer->rootResetMask.x = 0.f; resetPositionNode = rootTransformNode->Get("reset-position-y"); if (resetPositionNode != nullptr && resetPositionNode->GetType() == YamlNode::TYPE_STRING && resetPositionNode->AsBool() == true) motionLayer->rootResetMask.y = 0.f; resetPositionNode = rootTransformNode->Get("reset-position-z"); if (resetPositionNode != nullptr && resetPositionNode->GetType() == YamlNode::TYPE_STRING && resetPositionNode->AsBool() == true) motionLayer->rootResetMask.z = 0.f; } } } motionLayer->parameterIDs.insert(motionLayer->parameterIDs.begin(), motionsParameters.begin(), motionsParameters.end()); return motionLayer; } } //ns#include "ToyParser.h" ToyParser::ToyParser(std::vector tokens) : m_Tokens(tokens), m_CurrentToken(Token(Token::TokenType::END_OF_FILE, "")) { //Create space for token to avoid reallocating space, hence increase performance m_Tokens.reserve(tokens.size()); if (tokens.size() > 0) { m_CurrentToken = tokens[m_CurrentIndex]; } } void ToyParser::Advance() { if (m_CurrentIndex < m_Tokens.size() - 1) { m_CurrentIndex++; m_CurrentToken = m_Tokens[m_CurrentIndex]; } else { m_CurrentToken = Token(Token::TokenType::END_OF_FILE, "EOF"); } } Node* ToyParser::Parse() { if (m_CurrentToken.GetTokenType() == Token::TokenType::END_OF_FILE) { return nullptr; } Node* result = Expr(); if (m_CurrentToken.GetTokenType() != Token::TokenType::END_OF_FILE) { throw std::string("SYNTAX ERROR: ") + m_CurrentToken.GetTokenValue(); } return result; } Node* ToyParser::Expr() { Node* result = (Node*)Term(); while ( &m_CurrentToken != nullptr && (m_CurrentToken.GetTokenType() == Token::TokenType::PLUS || m_CurrentToken.GetTokenType() == Token::TokenType::MINUS) ) { if (m_CurrentToken.GetTokenType() == Token::TokenType::PLUS) { Advance(); Node* right = Term(); result = new AddNode((Node*)result, right); } else if (m_CurrentToken.GetTokenType() == Token::TokenType::MINUS) { Advance(); Node* right = Term(); result = new SubtractNode((Node*)result, right); } } std::string str = ((Node*)result)->ToString(); return result; } Node* ToyParser::Term() { Node* result = Factor(); while ( &m_CurrentToken != nullptr && (m_CurrentToken.GetTokenType() == Token::TokenType::MUL || m_CurrentToken.GetTokenType() == Token::TokenType::DIV || m_CurrentToken.GetTokenType() == Token::TokenType::MODULUS) ) { if (m_CurrentToken.GetTokenType() == Token::TokenType::MUL) { Advance(); Node* right = (Node*)Factor(); result = new MultiplyNode((Node*)result, right); } else if (m_CurrentToken.GetTokenType() == Token::TokenType::DIV) { Advance(); Node* right = (Node*)Factor(); result = new DivideNode((Node*)result, right); } else if (m_CurrentToken.GetTokenType() == Token::TokenType::MODULUS) { Advance(); Node* right = (Node*)Factor(); result = new ModulusNode((Node*)result, right); } } return result; } Node* ToyParser::Factor() { Token currentToken = m_CurrentToken; if (currentToken.GetTokenType() == Token::TokenType::PLUS) { Advance(); Node* result = new PlusNode(Power()); return result; } else if (m_CurrentToken.GetTokenType() == Token::TokenType::MINUS) { Advance(); Node* result = new MinusNode(Power()); return result; } else { Node* result = Power(); return result; } std::string errStr = "SYNTAX ERROR: " + errorInfo; throw errStr; } Node* ToyParser::Power() { Node* result = Atom(); while(&m_CurrentToken != nullptr && m_CurrentToken.GetTokenType() == Token::TokenType::POWER) { Advance(); Node* right = Factor(); result = new PowerNode(result, right); } return result; } Node* ToyParser::Atom() { Token currentToken = m_CurrentToken; if (currentToken.GetTokenType() == Token::TokenType::NUMBER) { Advance(); Node* result = new NumberNode(currentToken.GetTokenValue()); return result; } else if (currentToken.GetTokenType() == Token::TokenType::L_PAREN) { Advance(); Node* expr = Expr(); if (m_CurrentToken.GetTokenType() != Token::TokenType::R_PAREN) { errorInfo = "Expected ')'"; } else { Advance(); return expr; } } std::string errStr = "SYNTAX ERROR: " + errorInfo; throw errStr; } void ToyParser::Dispose(void* obj) { delete (Node*)obj; } #include using namespace std; int g[305]; int dp[305][305]; int main() { int n; cin >> n; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { dp[i][j] = 1000000000; } } for (int i = 0; i < n; i++) { cin >> g[i]; dp[i][i] = 1; } for (int i = n - 1; i >= 0; i--) { for (int j = i + 1; j < n; j++) { if (g[i] == g[j]) { dp[i][j] = min(dp[i + 1][j], dp[i][j - 1]); } else { for (int k = i; k < j; k++) { dp[i][j] = min(dp[i][j], dp[i][k] + dp[k + 1][j]); } } } } cout << dp[0][n - 1] << endl; return 0; }1-10 /* -------------------------------------------------------------------------- * File: iloparbenders.cpp * Version 12.8.0 * -------------------------------------------------------------------------- * Licensed Materials - Property of IBM * 5725-A06 5725-A29 5724-Y48 5724-Y49 5724-Y54 5724-Y55 5655-Y21 * Copyright IBM Corporation, 2012, 2017. All Rights Reserved. * * US Government Users Restricted Rights - Use, duplication or * disclosure restricted by GSA ADP Schedule Contract with * IBM Corp. * -------------------------------------------------------------------------- */ /* ********************************************************************** * * * * Parallel distributed Benders decomposition * * * * This file illustrates how a distributed Benders' decomposition * * can be implemented by means of the CPLEX remote object. * * * * ********************************************************************** */ /* The example is focused on a MILP model for the facility location problem, * but can be easily extended to any MILP model. * * The MILP model used in this example is * minimize sum(f in F) sum(j in J) C[f,j]*x[f,j] + sum(f in F) F[f]*y[f] * such that * sum(f in F) x[f,j] >= 1 forall j in J * sum (f in F) y[f] <= 2 * y[f] >= x[f,j] forall f in F, j in J * x[f,j] >= 0 forall f in F, j in J * y[f] in { 0, 1 } forall f in F * where y[f] = 1 if factory f is opened and 0 otherwise and * x[f,j] is the fraction of demand serviced from factory f to customer j. * F[f] is the fixed charge cost for opening factory f and C[f,j] is the * cost for servicing customer j from f. * * The model is decomposed in a master block involving the y binary variables * only, and in |J| blocks B[j], one for each customer j in J, that are used * to separate Bender's cuts. * * The master block is solved on a local machine, by adding Benders' cuts * through a lazyconstraint callback, while the blocks B[j] (j in J) are * solved in parallel on different remote machines, and are used to separate * violated Benders' cuts to be added to the current master. * * The MILP master block is: * minimize sum(j in J) eta[j] + sum(f in F) F[f]*y[f] * such that * sum (f in F) y[f] <= 2 * y[f] in { 0, 1 } forall f in F * eta[j] >= 0 for all j in J * where, for each j in J, the variable eta[j] = sum(f in F) C[f,j]*x[f,j] * takes into account the objective function associated with variables * x[f,j] (f in F) * * The LP block B[j] associated with each fixed customer j in J is * minimize sum(f in F) C[f,j]*x[f,j] * such that * sum(f in F) x[f,j] >= 1 * x[f,j] <= y[f] forall f in F * x[f,j] >= 0 forall f in F * where the binary variables y are fixed and their value is provided * by the current solution of the master block. * * Given the current solution (y[F], eta[j]) of the master, for each customer * j in J a Bender's cut is separated by solving the dual of B[j], that is, * the following LP D[j]: * maximize beta - sum(f in F) y[f]*alpha[f] * such that * beta - alpha[f] <= C[f,j] forall f in F * alpha[f] >= 0 forall f in F * beta >= 0 * * An unbounded ray (beta, alpha[f]) of D[j] gives raise to the ray cut * (feasibility cut) * beta - sum(f in F) alpha[f]*y[f] <= 0 * in the master problem. * A vertex (beta, alpha[f]) of D[j] give raises to the point cut * (optimality cut) * eta[j] >= beta - sum(f in F) alpha[f]*y[f] * in the master problem. */ #include #include #include #if defined(USE_MPI) # define OMPI_SKIP_MPICXX 1 /* We don't use the C++ bindings of OpenMPI. */ # include # define TRANSPORT "mpitransport" #elif defined(USE_PROCESS) # define TRANSPORT "processtransport" #elif defined(USE_TCPIP) # define TRANSPORT "tcpiptransport" #else # error "No transport type selected" #endif // The epsilon we use in comparion of double precision values #define EPSILON 1e-6 /* ********************************************************************** * * * * M a s t e r s i d e i m p l e m e n t a t i o n * * * * ********************************************************************** */ #if defined(COMPILE_MASTER) #include #include #include #include // ---------------------------------------------------------------------- /** A comparator for extractables. * All sub-classes of IloExtractable have a getId() member function that * returns a unique id for the extractable. We can use this id to compare * extractables that are used as keys in maps or in sets. */ template struct ExtractableLess { bool operator() (T const &e1, T const &e2) const { return e1.getId() < e2.getId(); } }; /** A set of rows. */ typedef std::set > RowSet; // ---------------------------------------------------------------------- /** A class that solves problems by means of parallel distributed Benders * decomposition. The public API of this class consists of only two things: * - An abstract (interface) class Problem that describes problems that * can be solved by this class. * - A function solve() that solves instances of Problem. */ struct BendersOpt { /** Interface to problems that can be solved by the BendersOpt class. */ struct Problem { Problem() {} virtual ~Problem() {} /** Get the number of blocks in this problem. */ virtual IloInt getNBlocks() const = 0; /** Get the model for this problem. */ virtual IloModel getModel() const = 0; /** Get the variables in this problem. */ virtual IloNumVarArray getVariables() const = 0; /** Get the linear constraints in this problem. */ virtual IloRangeArray getRows() const = 0; /** Get the block number for variable x. * @return The block number (in [0,getNBlocks()-1]) for x * or -1 if x is in the master. */ virtual IloInt getBlock(IloNumVar x) const = 0; /** Get the set of rows that intersect x. */ virtual RowSet const &getIntersectedRows(IloNumVar x) const = 0; /** Get the objective function coefficient for x. */ virtual double getObjCoef(IloNumVar x) const = 0; /** Get the objective function sense in this model. */ virtual IloObjective::Sense getObjSense() const = 0; }; static bool solve (Problem const *problem, int argc, char const *const *argv, std::vector const &machines); private: struct Block; struct LazyConstraintCallback; typedef std::vector BlockVector; /** A block (either master or Benders) in a Benders decomposition. */ struct Block { typedef std::map > ObjMap; typedef std::map > IdxMap; typedef std::map >VarMap; IloEnv env; IloInt const number; /**< Serial number of this block. */ IloNumVarArray vars; /**< Variables in this block's model. */ IloRangeArray rows; /**< Rows in this block's model. */ IloCplex cplex; /**< The solver that (re)solves this block's model. */ LazyConstraintCallback *cb; /** Description of variables that are fixed by master solves. */ struct FixData { IloInt row; IloInt col; double val; FixData(IloInt r, IloInt c, double v) : row(r), col(c), val(v) {} }; std::vector fixed; IloObjective obj; /**< Objective function in this block. */ ObjMap objMap; /**< Objective coefficient for each variable. */ VarMap varMap; /**< Map variables in this block to variables * in original model. */ // Extract a block from a problem. Block(Problem const *problem, IloInt n, int argc, char const *const *argv, std::vector const &machines); // Extract master block from a problem. Block(Problem const *problem, BlockVector const &blocks); ~Block(); }; /** The callback that is used to separate Benders cuts at integer * feasible solutions. */ struct LazyConstraintCallback : public IloCplex::LazyConstraintCallbackI { Block *const master; /**< Master block. */ BlockVector const &blocks; /**< Array of sub-blocks. */ IloInt const etaind; /**< Index of first eta variablein master. */ IloCplex::AsyncHandle *handles; LazyConstraintCallback(IloEnv env, Block *m, BlockVector const &b, IloInt e); ~LazyConstraintCallback(); IloCplex::CallbackI *duplicateCallback() const; void main(); }; // Create dual of a linear program. static void makeDual(IloObjective const &primalObj, IloNumVarArray const &primalVars, IloRangeArray const &primalRows, IloObjective *dualObj, IloNumVarArray *dualVars, IloRangeArray *dualRows); }; /** Extract sub block number n from problem. * The constructor creates a representation of block number n * as described in problem. * The constructor will also connect the newly created block to a remote * object solver instance. * @param problem The problem from which the block is to be extracted. * @param n Index of the block to be extracted. * @param argc Argument for IloCplex constructor. * @param argv Argument for IloCplex constructor. * @param machines List of machines to which to connect. If the code is * compiled for the TCP/IP transport then the block will * be connected to machines[n]. */ BendersOpt::Block::Block(Problem const *problem, IloInt n, int argc, char const *const *argv, std::vector const &machines) : env(), number(n), vars(0), rows(0), cplex(0), cb(0) { IloNumVarArray problemVars = problem->getVariables(); IloRangeArray problemRanges = problem->getRows(); // Create a map that maps variables in the original model to their // respective index in problemVars. std::map > origIdxMap; for (IloInt j = 0; j < problemVars.getSize(); ++j) origIdxMap.insert(std::map >::value_type(problemVars[j], j)); // Copy non-fixed variables from original problem into primal problem. IloExpr primalObj(env); IloNumVarArray primalVars(env); IloRangeArray primalRows(env); IdxMap idxMap; // Index of original variable in block's primal model RowSet rowSet; for (IloInt j = 0; j < problemVars.getSize(); ++j) { IloNumVar x = problemVars[j]; if ( problem->getBlock(x) == number ) { // Create column in block LP with exactly the same data. if ( x.getType() != IloNumVar::Float ) { std::stringstream s; s << "Cannot create non-continuous block variable " << x; std::cerr << s.str() << std::endl; throw s.str(); } IloNumVar v(env, x.getLB(), x.getUB(), x.getType(), x.getName()); // Normalize objective function to 'minimize' double coef = problem->getObjCoef(x); if ( problem->getObjSense() != IloObjective::Minimize ) coef *= -1.0; primalObj += coef * v; // Record the index that the copied variable has in the // block model. idxMap.insert(IdxMap::value_type(x, primalVars.getSize())); primalVars.add(v); // Mark the rows that are intersected by this column // so that we can collect them later. RowSet const &intersected = problem->getIntersectedRows(x); for (RowSet::const_iterator it = intersected.begin(); it != intersected.end(); ++it) rowSet.insert(*it); } else idxMap.insert(IdxMap::value_type(x, -1)); } // Now copy all rows that intersect block variables. for (IloInt i = 0; i < problemRanges.getSize(); ++i) { IloRange r = problemRanges[i]; if ( rowSet.find(r) == rowSet.end() ) continue; // Create a copy of the row, normalizing it to '<=' double factor = 1.0; if ( r.getLB() > -IloInfinity ) factor = -1.0; IloRange primalR(env, factor < 0 ? -r.getUB() : r.getLB(), factor < 0 ? -r.getLB() : r.getUB(), r.getName()); IloExpr lhs(env); for (IloExpr::LinearIterator it = r.getLinearIterator(); it.ok(); ++it) { IloNumVar v = it.getVar(); double const val = factor * it.getCoef(); if ( problem->getBlock(v) != number ) { // This column is not explicitly in this block. This means // that it is a column that will be fixed by the master. // We collect all such columns so that we can adjust the // dual objective function according to concrete fixings. // Store information about variables in this block that // will be fixed by master solves. fixed.push_back(FixData(primalRows.getSize(), origIdxMap[v], -val)); } else { // The column is an ordinary in this block. Just copy it. lhs += primalVars[idxMap[v]] * val; } } primalR.setExpr(lhs); primalRows.add(primalR); lhs.end(); } // Create the dual of the primal model we just created. // Note that makeDual _always_ returns a 'maximize' objective. IloObjective objective(env, primalObj, IloObjective::Minimize); makeDual(objective, primalVars, primalRows, &obj, &vars, &rows); objective.end(); primalRows.endElements(); primalRows.end(); primalVars.endElements(); primalVars.end(); primalObj.end(); // Create a model. IloModel model(env); model.add(obj); model.add(vars); model.add(rows); for (IloExpr::LinearIterator it = obj.getLinearIterator(); it.ok(); ++it) objMap.insert(ObjMap::value_type(it.getVar(), it.getCoef())); // Finally create the IloCplex instance that will solve // the problems associated with this block. char const **transargv = new char const *[argc + 3]; for (int i = 0; i < argc; ++i) transargv[i] = argv[i]; #if defined(USE_MPI) char extra[128]; sprintf (extra, "-remoterank=%d", static_cast(number + 1)); transargv[argc++] = extra; (void)machines; #elif defined(USE_PROCESS) char extra[128]; sprintf (extra, "-logfile=block%04d.log", static_cast(number)); transargv[argc++] = extra; (void)machines; #elif defined(USE_TCPIP) transargv[argc++] = machines[number]; #endif cplex = IloCplex(model, TRANSPORT, argc, transargv); delete[] transargv; // Suppress output from this block's solver. cplex.setOut(env.getNullStream()); cplex.setWarning(env.getNullStream()); } /** Extract the master block from problem. * The constructor also sets up the solver for the newly created master * block. The master block can only be extracted if all sub-blocks have * already been extracted. * @param problem The problem from which to extract the master. * @param blocks The sub blocks that have already been extracted. */ BendersOpt::Block::Block(Problem const *problem, BlockVector const &blocks) : env(), number(-1), vars(0), rows(0), cplex(0), cb(0) { IloNumVarArray problemVars = problem->getVariables(); IloRangeArray problemRanges = problem->getRows(); IloExpr masterObj(env); IloNumVarArray masterVars(env); IloRangeArray masterRows(env); // Find columns that do not intersect block variables and // copy them to the master block. IdxMap idxMap; RowSet rowSet; for (IloInt j = 0; j < problemVars.getSize(); ++j) { IloNumVar x = problemVars[j]; if ( problem->getBlock(x) < 0 ) { // Column is not in a block. Copy it to the master. IloNumVar v(env, x.getLB(), x.getUB(), x.getType(), x.getName()); varMap.insert(VarMap::value_type(v, x)); masterObj += problem->getObjCoef(x) * v; idxMap[x] = masterVars.getSize(); masterVars.add(v); } else { // Column is in a block. Collect all rows that intersect // this column. RowSet const &intersected = problem->getIntersectedRows(x); for (RowSet::const_iterator it = intersected.begin(); it != intersected.end(); ++it) rowSet.insert(*it); idxMap[x] = -1; } } // Pick up the rows that we need to copy. // These are the rows that are only intersected by master variables, // that is, the rows that are not in any block's rowset. for (IloInt i = 0; i < problemRanges.getSize(); ++i) { IloRange r = problemRanges[i]; if ( rowSet.find(r) == rowSet.end() ) { IloRange masterRow(env, r.getLB(), r.getUB(), r.getName()); IloExpr lhs(env); for (IloExpr::LinearIterator it = r.getLinearIterator(); it.ok(); ++it) { lhs += it.getCoef() * masterVars[idxMap[it.getVar()]]; } masterRow.setExpr(lhs); masterRows.add(masterRow); } } // Adjust variable indices in blocks so that reference to variables // in the original problem become references to variables in the master. for (BlockVector::const_iterator b = blocks.begin(); b != blocks.end(); ++b) { for (std::vector::iterator it = (*b)->fixed.begin(); it != (*b)->fixed.end(); ++it) it->col = idxMap[problemVars[it->col]]; } // Create the eta variables, one for each block. // See the comments at the top of this file for details about the // eta variables. IloInt const firsteta = masterVars.getSize(); for (BlockVector::size_type i = 0; i < blocks.size(); ++i) { std::stringstream s; s << "_eta" << i; IloNumVar eta(env, 0.0, IloInfinity, s.str().c_str()); masterObj += eta; masterVars.add(eta); } // Create model and solver instance vars = masterVars; rows = masterRows; IloModel model(env); model.add(obj = IloObjective(env, masterObj, problem->getObjSense())); model.add(vars); model.add(rows); cplex = IloCplex(model); cplex.use(cb = new (env) LazyConstraintCallback(env, this, blocks, firsteta)); for (IloExpr::LinearIterator it = obj.getLinearIterator(); it.ok(); ++it) objMap.insert(ObjMap::value_type(it.getVar(), it.getCoef())); } /** Destructor. */ BendersOpt::Block::~Block() { if ( cb ) cb->~LazyConstraintCallback(); cplex.end(); env.end(); } /** Create the dual of a linear program. * The function can only dualize programs of the form * Ax <= b, x >= 0. The data in primalVars and * dualRows as well as in primalRows and * dualVars is in 1-to-1-correspondence. * @param primalObj Objective function of primal problem. * @param primalVars Variables in primal problem. * @param primalRows Rows in primal problem. * @param dualObj Objective function of dual will be stored here. * @param dualVars All dual variables will be stored here. * @param dualRows All dual rows will be stored here. */ void BendersOpt::makeDual(IloObjective const &primalObj, IloNumVarArray const &primalVars, IloRangeArray const &primalRows, IloObjective *dualObj, IloNumVarArray *dualVars, IloRangeArray *dualRows) { // To keep the code simple we only support problems // of the form Ax <= b, b >= 0 here. We leave it as a reader's // exercise to extend the function to something that can handle // any kind of linear model. for (IloInt j = 0; j < primalVars.getSize(); ++j) if ( primalVars[j].getLB() != 0 || primalVars[j].getUB() < IloInfinity ) { std::stringstream s; s << "Cannot dualize variable " << primalVars[j]; throw s.str(); } for (IloInt i = 0; i < primalRows.getSize(); ++i) if ( primalRows[i].getLB() > -IloInfinity || primalRows[i].getUB() >= IloInfinity ) { std::stringstream s; s << "Cannot dualize constraint " << primalRows[i]; std::cerr << s.str() << std::endl; throw s.str(); } // The dual of // min/max c^T x // Ax <= b // x >= 0 // is // max/min y^T b // y^T A <= c // y <= 0 // We scale y by -1 to get >= 0 IloEnv env = primalVars.getEnv(); IloObjective obj(env, 0.0, primalObj.getSense() == IloObjective::Minimize ? IloObjective::Maximize : IloObjective::Minimize); IloRangeArray rows(env); IloNumVarArray y(env); std::map > v2i; for (IloInt j = 0; j < primalVars.getSize(); ++j) { IloNumVar x = primalVars[j]; v2i.insert(std::map >::value_type(x, j)); rows.add(IloRange(env, -IloInfinity, 0, x.getName())); } for (IloExpr::LinearIterator it = primalObj.getLinearIterator(); it.ok(); ++it) rows[v2i[it.getVar()]].setUB(it.getCoef()); for (IloInt i = 0; i < primalRows.getSize(); ++i) { IloRange r = primalRows[i]; IloNumColumn col(env); col += obj(-r.getUB()); for (IloExpr::LinearIterator it = r.getLinearIterator(); it.ok(); ++it) col += rows[v2i[it.getVar()]](-it.getCoef()); y.add(IloNumVar(col, 0, IloInfinity, IloNumVar::Float, r.getName())); } *dualObj = obj; *dualVars = y; *dualRows = rows; } /** Create callback. * The newly created callback separates Benders cuts for the problem * described by m (the master) and b (the * sub blocks). * @param env Environment in which the callback is created. * @param m Master block for Benders decomposition. * @param b Sub blocks for Benders decomposition. * @param e Index of first eta variable in master problem. */ BendersOpt::LazyConstraintCallback::LazyConstraintCallback(IloEnv env, Block *m, BlockVector const &b, IloInt e) : IloCplex::LazyConstraintCallbackI(env), master(m), blocks(b), etaind(e), handles(new IloCplex::AsyncHandle [blocks.size()]) { } /** Destructor. */ BendersOpt::LazyConstraintCallback::~LazyConstraintCallback() { delete[] handles; } /** Clone function as required by IloCplex::CallbackI. */ IloCplex::CallbackI *BendersOpt::LazyConstraintCallback::duplicateCallback() const { return new (getEnv()) LazyConstraintCallback(getEnv(), master, blocks, etaind); } /** Separation function. * This function is invoked whenever CPLEX finds an integer feasible * solution. It then separates either feasibility or optimality cuts * on this solution. */ void BendersOpt::LazyConstraintCallback::main() { std::cout << "Callback invoked. Separate Benders cuts." << std::endl; IloNumArray x(getEnv()); IloNumArray rayVals(getEnv()); IloNumVarArray rayVars(getEnv()); IloNumArray cutVal(getEnv()); IloNumVarArray cutVar(getEnv()); getValues(x, master->vars); bool error = false; // Iterate over blocks and trigger a separation on each of them. // The separation is triggered asynchronously so that it can happen // on different remote objects simultaneously. for (BlockVector::size_type b = 0; b < blocks.size(); ++b) { Block *const block = blocks[b]; // Remove current objective from the block's model. IloModel model = block->cplex.getModel(); IloObjective obj = block->obj; model.remove(obj); IloExpr newObj = obj.getExpr(); // Iterate over the fixed master variables in this block to update // the block's objective function. // Each fixed variable goes to the right-hand side and therefore // into the objective function. for (std::vector::const_iterator it = block->fixed.begin(); it != block->fixed.end(); ++it) newObj -= block->vars[it->row] * (it->val * x[it->col]); obj.setExpr(newObj); model.add(obj); newObj.end(); // If the problem is unbounded we need to get an infinite ray in // order to be able to generate the respective Benders cut. If // CPLEX proves unboundedness in presolve then it will return // CPX_STAT_INForUNBD and no ray will be available. So we need to // disable presolve. block->cplex.setParam(IloCplex::Param::Preprocessing::Presolve, false); block->cplex.setParam(IloCplex::Param::Preprocessing::Reduce, 0); // Solve the updated problem to optimality. block->cplex.setParam(IloCplex::Param::RootAlgorithm, IloCplex::Primal); try { handles[b] = block->cplex.solve(true); } catch (...) { // If there is an exception then we need to kill and join // all remaining solves. Otherwise we may leak handles. while (--b > 0) { handles[b].kill(); handles[b].join(); } throw; } } // Wait for the various LP solves to complete. for (BlockVector::size_type b = 0; b < blocks.size(); ++b) handles[b].join(); // See if we need to generate cuts. for (BlockVector::size_type b = 0; b < blocks.size(); ++b) { Block *const block = blocks[b]; cutVal.clear(); cutVar.clear(); double cutlb = -IloInfinity; double cutub = IloInfinity; // We ust STL types here since they are exception safe. std::vector tmp(master->vars.getSize(), 0); std::map > rayMap; // Depending on the status either seperate a feasibility or an // optimality cut. switch (block->cplex.getStatus()) { case IloAlgorithm::Unbounded: { // The subproblem is unbounded. We need to extract a feasibility // cut from an unbounded ray of the problem (see also the comments // at the top of this file). std::cout << "Block " << b << " unbounded "; block->cplex.getRay(rayVals, rayVars); cutub = 0.0; for (IloInt j = 0; j < rayVars.getSize(); ++j) { cutub -= rayVals[j] * block->objMap[rayVars[j]]; rayMap[rayVars[j]] = rayVals[j]; } for (std::vector::const_iterator it = block->fixed.begin(); it != block->fixed.end(); ++it) tmp[it->col] -= it->val * rayMap[block->vars[it->row]]; for (IloInt j = 0; j < master->vars.getSize(); ++j) { if ( fabs (tmp[j]) > EPSILON ) { cutVar.add(master->vars[j]); cutVal.add(tmp[j]); } } } break; case IloAlgorithm::Optimal: { // The subproblem has a finite optimal solution. // We need to check if this gives rise to an optimality cut (see // also the comments at the top of this file). std::cout << "Block " << b << " optimal "; double const objval = block->cplex.getObjValue(); double const eta = x[etaind + b]; block->cplex.getValues(block->vars, rayVals); if ( objval > eta + EPSILON ) { cutub = 0.0; for (IloInt j = 0; j < block->vars.getSize(); ++j) cutub -= rayVals[j] * block->objMap[block->vars[j]]; for (std::vector::const_iterator it = block->fixed.begin(); it != block->fixed.end(); ++it) tmp[it->col] -= it->val * rayVals[it->row]; for (IloInt j = 0; j < master->vars.getSize(); ++j) { if ( fabs (tmp[j]) > EPSILON ) { cutVal.add(tmp[j]); cutVar.add(master->vars[j]); } } cutVal.add(-1.0); cutVar.add(master->vars[etaind + b]); } } break; default: std::cerr << "Block " << b << " Unexpected status " << block->cplex.getStatus() << std::endl; error = true; break; } // If a cut was found then add that. if ( cutVar.getSize() > 0 ) { IloExpr expr(master->env); for (IloInt i = 0; i < cutVar.getSize(); ++i) expr += cutVar[i] * cutVal[i]; IloRange cut(getEnv(), cutlb, expr, cutub); expr.end(); std::cout << "cut found: " << cut << std::endl; add(cut).end(); } else std::cout << "no cuts." << std::endl; } cutVar.end(); cutVal.end(); rayVars.end(); rayVals.end(); x.end(); if ( error ) throw -1; } /** Solve the problem using a distributed implementation of * Benders' decomposition. */ bool BendersOpt::solve (Problem const *problem, int argc, char const *const *argv, std::vector const &machines) { IloEnv env = problem->getModel().getEnv(); std::vector blocks; Block *master = 0; bool result = false; try { // Extract blocks and master problem. std::cout << "Extracting " << problem->getNBlocks() << " blocks." << std::endl; for (IloInt b = 0; b < problem->getNBlocks(); ++b) blocks.push_back(new Block(problem, b, argc, argv, machines)); master = new Block(problem, blocks); // Write out the master and all blocks (for debugging). master->cplex.exportModel("master.lp"); for (BlockVector::size_type b = 0; b < blocks.size(); ++b) { std::stringstream s; s << "block" << b << ".lp"; blocks[b]->cplex.exportModel(s.str().c_str()); } // Solve the master. // If we find a feasible solution then perform a final solve // with the original problem so that we get solution values for // all variables in the original problem. if ( master->cplex.solve() ) { // Perform a last solve to get the solution values. IloNumArray vals(env), startVals(env); IloNumVarArray startVars(env); master->cplex.getValues(vals, master->vars); IloCplex cplex(problem->getModel()); // Fix integral variables to their value in the master solution // and add them as MIP start. for (IloInt i = 0; i < vals.getSize(); ++i) if ( master->vars[i].getType() != IloNumVar::Float ) { double const v = IloRound(vals[i]); IloNumVar x = master->varMap[master->vars[i]]; startVals.add(v); startVars.add(x); // We add lazy constraints so as to make sure that // - we don't modify the original model // - the problem has only the unique optimal solution // we are interested in cplex.addLazyConstraint(x == v); } cplex.addMIPStart(startVars, startVals); cplex.solve(); // Report the results. std::cout << "#### Problem solved (" << cplex.getObjValue() << ", " << cplex.getCplexStatus() << ")." << std::endl; IloNumVarArray vars = problem->getVariables(); for (IloInt i = 0; i < vars.getSize(); ++i) std::cout << "#### \tx[" << i << "] = " << cplex.getValue(vars[i]) << std::endl; cplex.end(); result = true; } } catch (...) { if ( master ) delete master; while ( blocks.size() > 0 ) { delete blocks.back(); blocks.pop_back(); } throw; } delete master; while ( blocks.size() > 0 ) { delete blocks.back(); blocks.pop_back(); } return result; } // ---------------------------------------------------------------------- /** Create an example problem. * The function creates the following facility location problem: * * minimize sum(f in F) sum(j in J) C[f,j]*x[f,j] + sum(f in F) F[f]*y[f] * such that sum(f in F) x[f,j] >= 1 forall j in J * sum (f in F) y[f] <= 2 * y[f] >= x[f,j] forall f in F, j in J * x[f,j] >= 0 forall f in F, j in J * y[f] in { 0, 1 } forall f in F * where y[f] = 1 if factory f is opened and 0 otherwise and * x[f,j] is the fraction of demand serviced from factory f to customer j. * F[f] is the fixed charge cost for opening factory f and C[f,j] is the * cost for servicing customer j from f. * * The output of the function is an CPXLPptr instance and a description * of the blocks in this problem. The description of blocks is as follows: * *NBLOCKS_P specifies the number of blocks (not accounting for the * master block). * *BLOCK_P is an array that has one entry for each column in the * returned CPXLPptr object. A negative entry specifies that * the column appears only in the master. A non-negative entry * specifies that the variable is in a block and gives the * block index. */ class Example : public BendersOpt::Problem { typedef std::map > BlockMap; typedef std::map > IntersectMap; typedef std::map > ObjMap; IloInt nblocks; IloModel model; IloNumVarArray vars; IloRangeArray ranges; BlockMap blockMap; IntersectMap intersectMap; ObjMap objMap; IloObjective::Sense objSense; public: Example(IloEnv env) : nblocks(0), model(env), vars(env), ranges(env) { // Model data. // fixed[] is the fixed cost for opening a facility, // cost[i,j] is the cost for serving customer i from facility j. static double const fixed[] = { 2.0, 3.0, 3.0 }; static double const cost[] = { 2.0, 3.0, 4.0, 5.0, 7.0, 4.0, 3.0, 1.0, 2.0, 6.0, 5.0, 4.0, 2.0, 1.0, 3.0 }; #define NFACTORY ((CPXDIM)(sizeof(fixed) / sizeof(fixed[0]))) #define NCUSTOMER ((CPXDIM)((sizeof(cost) / sizeof(cost[0])) / NFACTORY)) nblocks = NCUSTOMER; IloExpr obj(env); // Create integer y variables. IloNumVarArray y(env); for (IloInt f = 0; f < NFACTORY; ++f) { std::stringstream s; s << "y" << f; IloIntVar v(env, 0, 1, s.str().c_str()); obj += fixed[f] * v; objMap[v] = fixed[f]; y.add(v); blockMap.insert(BlockMap::value_type(v, -1)); intersectMap.insert(IntersectMap::value_type(v, RowSet())); } // Create continuous x variables. IloNumVarArray x(env); for (IloInt f = 0; f < NFACTORY; ++f) { for (IloInt c = 0; c < NCUSTOMER; ++c) { std::stringstream s; s << "x" << f << "#" << c; IloNumVar v(env, 0.0, IloInfinity, s.str().c_str()); obj += v * cost[f * NCUSTOMER + c]; objMap[v] = cost[f * NCUSTOMER + c]; x.add(v); blockMap.insert(BlockMap::value_type(v, c)); intersectMap.insert(IntersectMap::value_type(v, RowSet())); } } vars.add(y); vars.add(x); model.add(vars); // Add objective function. model.add(IloMinimize(env, obj, "obj")); objSense = IloObjective::Minimize; obj.end(); // Satisfy each customer's demand. for (IloInt c = 0; c < NCUSTOMER; ++c) { std::stringstream s; s << "c1_" << c; IloRange r(env, 1.0, IloInfinity, s.str().c_str()); IloExpr lhs(env); for (IloInt f = 0; f < NFACTORY; ++f) { lhs += x[f * NCUSTOMER + c]; intersectMap[x[f * NCUSTOMER + c]].insert(r); } r.setExpr(lhs); ranges.add(r); lhs.end(); } // A factory must be open if we service from it. for (IloInt c = 0; c < NCUSTOMER; ++c) { for (IloInt f = 0; f < NFACTORY; ++f) { std::stringstream s; s << "c2_" << c << "#" << f; IloRange r(env, 0.0, IloInfinity, s.str().c_str()); intersectMap[x[f * NCUSTOMER + c]].insert(r); intersectMap[y[f]].insert(r); r.setExpr(-x[f * NCUSTOMER + c] + y[f]); ranges.add(r); } } // Capacity constraint. IloRange r(env, -IloInfinity, NFACTORY - 1, "c3"); IloExpr lhs(env); for (IloInt f = 0; f < NFACTORY; ++f) { lhs += y[f]; intersectMap[y[f]].insert(r); } r.setExpr(lhs); ranges.add(r); lhs.end(); model.add(ranges); #undef NFACTORY #undef NCUSTOMER } // Implementation of functions required by the BendersOpt::Problem // interface. IloInt getNBlocks() const { return nblocks; } IloModel getModel() const { return model; } IloNumVarArray getVariables() const { return vars; } IloRangeArray getRows() const { return ranges; } IloInt getBlock(IloNumVar x) const { BlockMap::const_iterator const it = blockMap.find(x); return (it == blockMap.end()) ? -1 : it->second; } RowSet const &getIntersectedRows(IloNumVar x) const { static RowSet const empty; IntersectMap::const_iterator const it = intersectMap.find(x); return (it == intersectMap.end()) ? empty : it->second; } double getObjCoef(IloNumVar x) const { ObjMap::const_iterator const it = objMap.find(x); return (it == objMap.end()) ? 0.0 : it->second; } IloObjective::Sense getObjSense() const { return objSense; } }; // ---------------------------------------------------------------------- int main (int argc, char **argv) { int myargc; char const **myargv = NULL; std::vector machines; int nmachines = 0; #if defined(USE_MPI) MPI_Init (&argc, &argv); MPI_Comm_size (MPI_COMM_WORLD, &nmachines); --nmachines; myargc = 0; #elif defined(USE_PROCESS) nmachines = INT_MAX; myargc = 2; #elif defined(USE_TCPIP) nmachines = 0; myargc = 0; #endif // Process the command line. myargv = new char const *[argc]; for (int i = 1; i < argc; ++i) { #if defined(USE_MPI) /* Nothing to do. */ if ( 0 ) ; #elif defined(USE_PROCESS) if ( strncmp (argv[i], "-bin=", 5) == 0 ) { myargv[0] = argv[i] + 5; myargv[1] = "-worker=process"; } #elif defined(USE_TCPIP) if ( strncmp (argv[i], "-address=", 9) == 0 ) { machines.push_back (argv[i]); ++nmachines; } #endif else myargv[myargc++] = argv[i]; } IloEnv env; try { Example problem(env); if ( nmachines < problem.getNBlocks() ) { std::cerr << "We have " << problem.getNBlocks() << " blocks blocks but only " << nmachines << " machines!" << std::endl; throw -1; } BendersOpt::solve (&problem, myargc, myargv, machines); } catch (...) { env.end(); delete[] myargv; throw; } env.end(); delete[] myargv; #if defined(USE_MPI) MPI_Finalize (); #endif return 0; } #endif /* COMPILE_MASTER */ samples/OutputOnly/nowruz/solution/dfs.cpp10-100 #include #include #include #include #include #define For(a, b) for (int a = 0; a < b; a++) #define MAX (2048 + 64) const int rplus[4] = {0,0,1,-1}, cplus[4] = {-1, 1, 0, 0}; using namespace std; int m, n; double leaf_prob = 0.2; vector table; int counter; void rand_perm(int* p) { for (int i = 0; i < 4; i++) { p[i] = i; swap(p[i], p[rand() % (i + 1)]); } } bool check2(int r, int c) { return (r < 0 || r >= m || c < 0 || c >= n || table[r][c] != 'X'); } bool check(int pr, int pc, int r, int c) { if (r < 0 || r >= m || c < 0 || c >= n || table[r][c] != '.') return false; For(i, 4) if ((r + rplus[i] != pr || c + cplus[i] != pc) && ! check2(r + rplus[i], c + cplus[i])) return false; return true; } void DFS(int r, int c) { table[r][c] = 'X'; if (counter++ > 10 && ((double) rand() / RAND_MAX) < leaf_prob) return; int p[4]; rand_perm(p); For(i, 4) if (check(r, c, r + rplus[p[i]], c + cplus[p[i]])) DFS(r + rplus[p[i]], c + cplus[p[i]]); } bool inside(int a, int b) { return (a >= 0 && a < m && b >= 0 && b < n); } int neighbors(int x, int y) { int count = 0; For(i, 4) { int a = x + rplus[i], b = y + cplus[i]; if (inside(a, b) && table[a][b] == 'X') count ++; } return count; } void add_leaves() { For(i, m) For(j, n) if (table[i][j] == '.' && neighbors(i, j) == 1) table[i][j] = 'X'; } int main(int argc, char ** argv) { // leaf_prob = atof(argv[1]); // cerr << leaf_prob << endl; cin >> m >> n; int tmp; cin >> tmp; string s; int blocks = 0; For(i, m) { cin >> s; table.push_back(s); blocks += count(s.begin(), s.end(), '#'); } leaf_prob -= (double) blocks / (m * n); bool found = false; for (int i = 0; i < m && ! found; i++) For(j, n) if (table[i][j] == '.') { DFS(i, j); found = true; break; } add_leaves(); For(i, m) For (j, n) if (table[i][j] == '.' || table[i][j] == 'X') table[i][j] = '.' + 'X' - table[i][j]; For (i, m) cout << table[i] << endl; } /* Original Numerical Semigroups Code by : https://www.lri.fr/~hivert/ Link: https://github.com/hivert/NumericMonoid/blob/master/src/Cilk++/monoid.hpp */ #include #include #include #include #include "YewPar.hpp" #include "skeletons/Seq.hpp" #include "skeletons/DepthBounded.hpp" #include "skeletons/StackStealing.hpp" #include "skeletons/Budget.hpp" #include "monoid.hpp" // Numerical Semigroups don't have a space struct Empty {}; struct NodeGen : YewPar::NodeGenerator { Monoid group; generator_iter it; NodeGen(const Empty &, const Monoid & s) : group(s), it(generator_iter(s)){ this->numChildren = it.count(group); it.move_next(group); // Original code skips begin } Monoid next() override { auto res = remove_generator(group, it.get_gen()); it.move_next(group); return res; } }; int hpx_main(boost::program_options::variables_map & opts) { auto spawnDepth = opts["spawn-depth"].as(); auto maxDepth = opts["genus"].as(); auto skeleton = opts["skeleton"].as(); //auto stealAll = opts["stealall"].as(); Monoid root; init_full_N(root); auto start_time = std::chrono::steady_clock::now(); std::vector counts; if (skeleton == "depthbounded") { YewPar::Skeletons::API::Params<> searchParameters; searchParameters.maxDepth = maxDepth; searchParameters.spawnDepth = spawnDepth; counts = YewPar::Skeletons::DepthBounded ::search(Empty(), root, searchParameters); } else if (skeleton == "stacksteal"){ YewPar::Skeletons::API::Params<> searchParameters; searchParameters.maxDepth = maxDepth; searchParameters.stealAll = static_cast(opts.count("chunked")); // EXTENSION if (opts.count("nodes")) { counts = YewPar::Skeletons::StackStealing ::search(Empty(), root, searchParameters); } else if (opts.count("backtracks")) { counts = YewPar::Skeletons::StackStealing ::search(Empty(), root, searchParameters); } else if (opts.count("regularity")) { counts = YewPar::Skeletons::StackStealing ::search(Empty(), root, searchParameters); } else { counts = YewPar::Skeletons::StackStealing ::search(Empty(), root, searchParameters); } // END EXTENSION } else if (skeleton == "budget"){ YewPar::Skeletons::API::Params<> searchParameters; searchParameters.backtrackBudget = opts["backtrack-budget"].as(); searchParameters.maxDepth = maxDepth; // EXTENSION if (opts.count("nodes")) { counts = YewPar::Skeletons::Budget ::search(Empty(), root, searchParameters); } else if (opts.count("backtracks")) { counts = YewPar::Skeletons::Budget ::search(Empty(), root, searchParameters); } else if (opts.count("regularity")) { counts = YewPar::Skeletons::Budget ::search(Empty(), root, searchParameters); } else { counts = YewPar::Skeletons::Budget ::search(Empty(), root, searchParameters); } // END EXTENSION } else { hpx::cout << "Invalid skeleton type: " << skeleton << hpx::endl; return hpx::finalize(); } auto overall_time = std::chrono::duration_cast (std::chrono::steady_clock::now() - start_time); hpx::cout << "Results Table: " << hpx::endl; for (auto i = 0; i <= maxDepth; ++i) { hpx::cout << i << ": " << counts[i] << hpx::endl; } hpx::cout << "=====" << hpx::endl; hpx::cout << "cpu = " << overall_time.count() << hpx::endl; return hpx::finalize(); } int main(int argc, char* argv[]) { boost::program_options::options_description desc_commandline("Usage: " HPX_APPLICATION_STRING " [options]"); desc_commandline.add_options() ( "skeleton", boost::program_options::value()->default_value("seq"), "Which skeleton to use: seq, depthbound, stacksteal, or budget" ) ( "spawn-depth,d", boost::program_options::value()->default_value(0), "Depth in the tree to spawn until (for parallel skeletons only)" ) ( "genus,g", boost::program_options::value()->default_value(0), "Depth in the tree to count until" ) ( "backtrack-budget,b", boost::program_options::value()->default_value(500), "Number of backtracks before spawning work" ) ( "verbose,v", boost::program_options::value()->default_value(false), "Enable verbose output" ) ("chunked", "Use chunking with stack stealing") // EXTENSION ("backtracks", "Collect the backtracks metric") ("nodes", "Collect the backtracks metric") ("regularity", "Collect the backtracks metric"); // END EXTENSION YewPar::registerPerformanceCounters(); return hpx::init(desc_commandline, argc, argv); } // // @file: msgQServer.cpp // // @Created on: Jul 22, 2017 // @Author: // // // @brief - // // // // @copyright Copyright // All Rights Reserved. // // This file is subject to the terms and conditions defined in // file 'LICENSE', which is part of this source code package. // // //INCLUDES #include "msgQServer.h" #include #include "logClient.h" #include #include #include namespace tarsim { //namespaces-------------------------------------------------------------------- //consts------------------------------------------------------------------------ //eumeration-------------------------------------------------------------------- /** * @brief initialize message queue data members * @param qName - the thread name * @param[in] priority - set the thread priority */ MsgQServer::MsgQServer( const std::string &qName, int policy, int priority) : m_qName(qName), m_threadPolicy(policy), m_threadPriority(priority) { m_qId = -1; m_attr.mq_curmsgs = 0; m_attr.mq_flags = 0; m_attr.mq_maxmsg = MAX_QUEUE_SIZE ; m_attr.mq_msgsize = MAX_MSG_SIZE; m_runforEver = true; m_ready = false; m_printingStdio = m_qName.compare(LogServerThreadName) == 0; m_printingStdio = true; } /** * @brief spawns the thread and waits for the thread to start before returning * @return NO_ERR */ Errors MsgQServer::start() { std::unique_lock lck(m_mtx); if (nullptr != m_pthread.get()) { printf("Failed: Thread already exists\n"); return ERR_INVALID; } m_pthread = std::unique_ptr(new pthread_t); int ret = 0; /* Initialize pthread attributes (default values) */ pthread_attr_t attr; ret = pthread_attr_init(&attr); if (ret) { printf("Failed to initialize pthread attributes (error = %d)\n", ret); return ERR_INVALID; } /* Set scheduler policy and priority of pthread */ ret = pthread_attr_setschedpolicy(&attr, m_threadPolicy); if (ret) { printf("Failed to set scheduling policy of pthread (error = %d)\n", ret); return ERR_INVALID; } struct sched_param param; param.sched_priority = m_threadPriority; ret = pthread_attr_setschedparam(&attr, ¶m); if (ret) { printf("Failed to set scheduling parameters of pthread %d\n", ret); return ERR_INVALID; } /* Use scheduling parameters of attr */ ret = pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED); if (ret) { printf("Failed to set inherit scheduling of pthread (error = %d)\n", ret); return ERR_INVALID; } pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); /* Create a pthread with specified attributes */ ret = pthread_create( m_pthread.get(), &attr, MsgQServer::threadFunctionHelper, (void*)this); if (ret) { pthread_attr_setschedpolicy(&attr, 0); param.sched_priority = 0; pthread_attr_setschedparam(&attr, ¶m); ret = pthread_create( m_pthread.get(), &attr, MsgQServer::threadFunctionHelper, (void*)this); if (ret) { printf("Failed to create non-realtime thread %s (error = %d)\n", m_qName.c_str(), ret); return ERR_INVALID; } printf("Create non-realtime thread %s\n", m_qName.c_str()); } // Set the thread name pthread_setname_np(*m_pthread.get(), m_qName.c_str()); pthread_attr_destroy(&attr); // Wait for thread to come up //LOG_FAILURE("Wait %s\n",m_qName.c_str()); while (!m_ready) { //LOG_FAILURE("looping\n"); m_cv.wait(lck); } LOG_INFO("Started: %s\n",m_qName.c_str()); return Errors::NO_ERR; } void* MsgQServer::threadFunctionHelper( void* void_ptr_to_this_threaded_object) { MsgQServer* ptr_to_this_threaded_object = static_cast(void_ptr_to_this_threaded_object); Errors err = ptr_to_this_threaded_object->running(); if (NO_ERR != err) { printf("Tarsim server failed...\n"); } return nullptr; } /** * @brief - core routine which creates and the message queue and waits for incoming * messages * @return NO_ERR - if the thread started successfully. * @returns ERR_FAILED_SPAWNED - if it fails to create the message queue */ Errors MsgQServer::running() { /* receive the message */ GenericData_t data;// buffer; std::string serverName = m_qName; m_qName ="/" + m_qName; mq_unlink(m_qName.c_str()); // Remove if already exists in /dev/mq m_qId = mq_open(m_qName.c_str(), O_CREAT | O_RDONLY, 0644, &m_attr); if (-1 == m_qId) { printf("Failed to create queue (%s) %d %s \n",m_qName.c_str(), errno, strerror(errno)); return ERR_FAILED_SPAWNED; } //Ready to go std::unique_lock lck(m_mtx); m_ready = true; lck.unlock(); m_cv.notify_one(); while(m_runforEver) { ssize_t bytesRead; bytesRead = mq_receive(m_qId, (char *)&data, MAX_MSG_SIZE, NULL); if (bytesRead <= 0) { if (m_printingStdio) { LOG_INFO("qName(%s) bytesRead is less than 0. bytesRead(%d)\n", m_qName.c_str(), int(bytesRead)); } } else { m_runforEver = (MSG_EXIT_EVENT != data.simpleMsg.msgId); if (!m_runforEver ) { onExit(); //tell the child class to clean up. cleanup(); // clean MsgQServer Objects; } else { onMessage(data); } } } return Errors::NO_ERR; } void MsgQServer::onExit() { //allow cleanup for the child if needed } /** * @brief - does not thing. child class performs the task * @param inComingData */ void MsgQServer::onMessage(const GenericData_t &inComingData) { } /** * @brief Close the message queue * @return NO_ERR: if closed successfully; * false: otherwise */ Errors MsgQServer::cleanup() { Errors errCode = Errors::NO_ERR; if ((mqd_t) -1 != m_qId ) { int status; status = mq_close(m_qId); m_qId = (mqd_t) - 1; if( -1 == status ) { if (m_printingStdio) { LOG_FAILURE("Failed to close the message queue %s, errno (%d)=(%s)\n", m_qName.c_str(), errno, strerror(errno)); } errCode = ERR_MQ_FAILED_CLOSE; } } mq_unlink(m_qName.c_str()); // Remove if already exists in /dev/mqueue if (m_allowedToForceExit) { exit(EXIT_SUCCESS); } return errCode; } MsgQServer::~MsgQServer() { endAndExit(); } void MsgQServer::endAndExit() { m_runforEver = false; printf("Closing server %s\n", m_qName.c_str()); if (Errors::NO_ERR != stop()) { printf("Failed to properly close server\n"); } } /** * @brief it is intended to stop the server * @returns NO_ERR * */ Errors MsgQServer::stop() { mqd_t qId; struct mq_attr attr; if ((mqd_t)-1 == m_qId) { return Errors::NO_ERR; } //Initialize qId = -1; attr.mq_curmsgs = 0; attr.mq_flags = 0; attr.mq_maxmsg = 0; attr.mq_msgsize = 0; //Make Connection qId = mq_open(m_qName.c_str(), O_WRONLY); m_printingStdio = true; if ((mqd_t)-1 == m_qId) { if (m_printingStdio) { LOG_FAILURE("Failed to connect to message queue (%s) error(%d=%s)\n", m_qName.c_str(), errno, strerror(errno)); } return ERR_MQ_FAILED_OPEN; } SimpleMsg_t data; data.msgId = MSG_EXIT_EVENT; int result = mq_send(qId,(char *)&data, sizeof(SimpleMsg_t), 0); if (result == -1) { if (m_printingStdio) { LOG_FAILURE("Failed to send to receiver %s message queue, errno(%d)=%s\n", m_qName.c_str(),errno, strerror(errno)); } return ERR_MQ_FAILED_SEND; } mq_close(qId); // Wait for thread to go away m_runforEver = false; int ret = pthread_join(*m_pthread.get(), nullptr); if (ret) { printf("Failed to join cthread %s -> %m (error = %d) for thread %s", m_qName.c_str(), ret, m_qName.c_str()); return ERR_INVALID; } return Errors::NO_ERR; } } // end of namespace tarsim sumo/src/utils/geom/Bresenham.cpp0 /****************************************************************************/ /// @file Bresenham.cpp /// @author /// @author /// @date Fri, 07 Jun 2002 /// @version $Id$ /// // A class to realise a uniform n:m - relationship using the /****************************************************************************/ // SUMO, Simulation of Urban MObility; see http://sumo.dlr.de/ // Copyright (C) 2001-2017 DLR (http://www.dlr.de/) and contributors /****************************************************************************/ // // This file is part of SUMO. // SUMO 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. // /****************************************************************************/ // =========================================================================== // included modules // =========================================================================== #ifdef _MSC_VER #include #else #include #endif #include #include #include "Bresenham.h" // =========================================================================== // method definitions // =========================================================================== void Bresenham::compute(BresenhamCallBack* callBack, const int val1, const int val2) { const int smaller = MIN2(val1, val2); const int greater = MAX2(val1, val2); int pos = 0; int c = smaller; for (int i = 0; i < greater; i++) { if (smaller == val1) { callBack->execute(pos, i); } else { callBack->execute(i, pos); } c += 2 * smaller; if (c >= 2 * greater) { pos++; c -= 2 * greater; } } } /****************************************************************************/ 1-10 // Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ash/login/screens/app_downloading_screen.h" #include #include "ash/constants/ash_features.h" #include "base/bind.h" #include "base/run_loop.h" #include "base/strings/string_piece.h" #include "base/strings/utf_string_conversions.h" #include "chrome/browser/ash/login/login_wizard.h" #include "chrome/browser/ash/login/oobe_screen.h" #include "chrome/browser/ash/login/test/js_checker.h" #include "chrome/browser/ash/login/test/login_manager_mixin.h" #include "chrome/browser/ash/login/test/oobe_base_test.h" #include "chrome/browser/ash/login/test/oobe_screen_exit_waiter.h" #include "chrome/browser/ash/login/test/oobe_screen_waiter.h" #include "chrome/browser/ash/login/ui/login_display_host.h" #include "chrome/browser/ash/login/wizard_controller.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/ui/webui/chromeos/login/app_downloading_screen_handler.h" #include "chrome/browser/ui/webui/chromeos/login/gaia_screen_handler.h" #include "chrome/browser/ui/webui/chromeos/login/oobe_ui.h" #include "chrome/grit/generated_resources.h" #include "components/arc/arc_prefs.h" #include "components/prefs/pref_service.h" #include "content/public/test/browser_test.h" #include "ui/base/l10n/l10n_util.h" namespace ash { namespace { constexpr char kAppDownloadingId[] = "app-downloading"; const test::UIPath kTitle = {kAppDownloadingId, "title"}; const test::UIPath kTitlePlural = {kAppDownloadingId, "title-plural"}; const test::UIPath kTitleSingular = {kAppDownloadingId, "title-singular"}; const test::UIPath kContinueSetupButton = {kAppDownloadingId, "continue-setup-button"}; class AppDownloadingScreenTest : public OobeBaseTest { public: AppDownloadingScreenTest() = default; ~AppDownloadingScreenTest() override = default; // OobeBaseTest: void SetUpOnMainThread() override { OobeBaseTest::SetUpOnMainThread(); app_downloading_screen_ = WizardController::default_controller() ->GetScreen(); app_downloading_screen_->set_exit_callback_for_testing(base::BindRepeating( &AppDownloadingScreenTest::HandleScreenExit, base::Unretained(this))); } void Login() { login_manager_.LoginAsNewRegularUser(); OobeScreenExitWaiter(GetFirstSigninScreen()).Wait(); } void ShowAppDownloadingScreen() { LoginDisplayHost::default_host()->StartWizard( AppDownloadingScreenView::kScreenId); OobeScreenWaiter(AppDownloadingScreenView::kScreenId).Wait(); } void WaitForScreenExit() { if (screen_exited_) return; base::RunLoop run_loop; screen_exit_callback_ = run_loop.QuitClosure(); run_loop.Run(); } AppDownloadingScreen* app_downloading_screen_; bool screen_exited_ = false; private: void HandleScreenExit() { ASSERT_FALSE(screen_exited_); screen_exited_ = true; if (screen_exit_callback_) std::move(screen_exit_callback_).Run(); } base::OnceClosure screen_exit_callback_; LoginManagerMixin login_manager_{&mixin_host_}; }; IN_PROC_BROWSER_TEST_F(AppDownloadingScreenTest, NoAppsSelected) { Login(); ShowAppDownloadingScreen(); test::OobeJS().CreateVisibilityWaiter(true, kContinueSetupButton)->Wait(); test::OobeJS().ExpectEnabledPath(kContinueSetupButton); if (features::IsNewOobeLayoutEnabled()) { test::OobeJS().ExpectVisiblePath(kTitle); } else { test::OobeJS().ExpectVisiblePath(kTitlePlural); test::OobeJS().ExpectHiddenPath(kTitleSingular); test::OobeJS().ExpectElementText( l10n_util::GetStringFUTF8(IDS_LOGIN_APP_DOWNLOADING_SCREEN_TITLE_PLURAL, u"0"), kTitlePlural); } test::OobeJS().TapOnPath(kContinueSetupButton); WaitForScreenExit(); } IN_PROC_BROWSER_TEST_F(AppDownloadingScreenTest, SingleAppSelected) { Login(); base::Value apps(base::Value::Type::LIST); apps.Append("app.test.package.1"); ProfileManager::GetActiveUserProfile()->GetPrefs()->Set( arc::prefs::kArcFastAppReinstallPackages, std::move(apps)); ShowAppDownloadingScreen(); test::OobeJS().CreateVisibilityWaiter(true, kContinueSetupButton)->Wait(); test::OobeJS().ExpectEnabledPath(kContinueSetupButton); if (features::IsNewOobeLayoutEnabled()) { test::OobeJS().ExpectVisiblePath(kTitle); } else { test::OobeJS().ExpectVisiblePath(kTitleSingular); test::OobeJS().ExpectHiddenPath(kTitlePlural); test::OobeJS().ExpectElementText( l10n_util::GetStringUTF8( IDS_LOGIN_APP_DOWNLOADING_SCREEN_TITLE_SINGULAR), kTitleSingular); } test::OobeJS().TapOnPath(kContinueSetupButton); WaitForScreenExit(); } IN_PROC_BROWSER_TEST_F(AppDownloadingScreenTest, MultipleAppsSelected) { Login(); base::Value apps(base::Value::Type::LIST); apps.Append("app.test.package.1"); apps.Append("app.test.package.2"); ProfileManager::GetActiveUserProfile()->GetPrefs()->Set( arc::prefs::kArcFastAppReinstallPackages, std::move(apps)); ShowAppDownloadingScreen(); test::OobeJS().CreateVisibilityWaiter(true, kContinueSetupButton)->Wait(); test::OobeJS().ExpectEnabledPath(kContinueSetupButton); if (features::IsNewOobeLayoutEnabled()) { test::OobeJS().ExpectVisiblePath(kTitle); } else { test::OobeJS().ExpectVisiblePath(kTitlePlural); test::OobeJS().ExpectHiddenPath(kTitleSingular); test::OobeJS().ExpectElementText( l10n_util::GetStringFUTF8(IDS_LOGIN_APP_DOWNLOADING_SCREEN_TITLE_PLURAL, u"2"), kTitlePlural); } test::OobeJS().TapOnPath(kContinueSetupButton); WaitForScreenExit(); } } // namespace } // namespace ash // EnergyPlus, Copyright (c) 1996-2018, The Board of Trustees of the University of Illinois, // 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), Oak Ridge // National Laboratory, managed by UT-Battelle, Alliance for Sustainable Energy, LLC, and other // contributors. All rights reserved. // // 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 others to do so. // // 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 University of California, Lawrence Berkeley National Laboratory, // the University of Illinois, U.S. Dept. of Energy nor the names of its contributors may be // used to endorse or promote products derived from this software without specific prior // written permission. // // (4) Use of EnergyPlus(TM) Name. If Licensee (i) distributes the software in stand-alone form // without changes from the version obtained under this License, or (ii) Licensee makes a // reference solely to the software portion of its product, Licensee must refer to the // software as "EnergyPlus version X" software, where "X" is the version number Licensee // obtained under this License and may not use a different name for the software. Except as // specifically required in this Section (4), Licensee shall not use in a company name, a // product name, in advertising, publicity, or other promotional activities any name, trade // name, trademark, logo, or other designation of "EnergyPlus", "E+", "e+" or confusingly // similar designation, without the U.S. Department of Energy's prior written consent. // // 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 DataWater_hh_INCLUDED #define DataWater_hh_INCLUDED // ObjexxFCL Headers #include // EnergyPlus Headers #include #include namespace EnergyPlus { namespace DataWater { // Using/Aliasing // Data // -only module should be available to other modules and routines. // Thus, all variables in this module must be PUBLI // MODULE PARAMETER DEFINITION extern int const ScheduledTankTemp; // tank water temperature is user input via schedule extern int const TankZoneThermalCoupled; // tank water temperature is modeled using simple UA extern int const RainSchedDesign; // mode of Rainfall determination is Scheduled Design extern int const IrrSchedDesign; // mode of Irrigation determination is Scheduled Design (DJS -PSU) extern int const IrrSmartSched; // mode of irrigation DJS - PSU extern int const ConstantRainLossFactor; extern int const ScheduledRainLossFactor; extern int const AmbientTempSchedule; // ambient temperature around tank (or HPWH inlet air) is scheduled extern int const AmbientTempZone; // tank is located in a zone or HPWH inlet air is zone air only extern int const AmbientTempExterior; // tank is located outdoors or HPWH inlet air is outdoor air only extern int const ConstantWaterTable; extern int const ScheduledWaterTable; extern int const NoControlLevel; extern int const MainsFloatValve; extern int const WellFloatValve; extern int const WellFloatMainsBackup; extern int const OtherTankFloatValve; extern int const TankMainsBackup; extern int const OverflowDiscarded; extern int const OverflowToTank; // DERIVED TYPE DEFINITIONS: // MODULE VARIABLE DECLARATIONS: extern int NumWaterStorageTanks; // number of water Storage tanks in model extern int NumRainCollectors; // number of rainfall collectors in model extern int NumGroundWaterWells; // number of extern int NumSiteRainFall; extern int NumIrrigation; // DJS PSU Dec 2006 number of irrigation descriptions (1 allowed) extern bool AnyWaterSystemsInModel; // control flag set true if any water systems extern bool WaterSystemGetInputCalled; // set true once input data gotten. extern bool AnyIrrigationInModel; // control flag set true if irrigation input for ecoroof DJS PSU Dec 2006 // Types struct StorageTankDataStruct { // Members // user input data std::string Name; // name of this Storage Tank std::string QualitySubCategoryName; // name of water subcategory // INTEGER :: QualitySubCategory = 0 ! Real64 MaxCapacity; // tank capacity Limit [m3] int OverflowMode; std::string OverflowTankName; int OverflowTankID; int OverflowTankSupplyARRID; Real64 ValveOnCapacity; // tank capacity at lower control range [m3] Real64 ValveOffCapacity; // tank capacity at upper control range [m3] int ControlSupplyType; // mode for tank controlled resupply int GroundWellID; // index "pointer" to well if present std::string SupplyTankName; int SupplyTankID; int SupplyTankDemandARRID; Real64 BackupMainsCapacity; Real64 InitialVolume; // water in tank at start of simulation period [m3] Real64 MaxInFlowRate; // limit on rate of inlet [m3/s] Real64 MaxOutFlowRate; // limit on rate of outlet [m3/s] int ThermalMode; Real64 InitialTankTemp; // initial tank temperature [C] int TempSchedID; // index "pointer" to schedule int AmbientTempIndicator; // Indicator for ambient tank losses (SCHEDULE, ZONE, EXTERIOR) int AmbientTempSchedule; // Schedule index pointer int ZoneID; // index "pointer" to zone where tank is Real64 UValue; // U-value for tank [W/m2-k] Real64 SurfArea; // surface are of tank on Zone side... [m2] int InternalMassID; // index "pointer" to internal mass object for thermal coupling std::string SurfMaterialName; // surface properties // calculated data and from elsewhere Real64 ThisTimeStepVolume; Real64 LastTimeStepVolume; Real64 LastTimeStepTemp; // previous temperature of tank water int NumWaterSupplies; Array1D VdotAvailSupply; // Each supply component has its own term Array1D TwaterSupply; // Each supply component has its own term Array1D_string SupplyCompNames; Array1D_string SupplyCompTypes; int NumWaterDemands; Array1D VdotRequestDemand; // each demand componennt has a slot Array1D VdotAvailDemand; // each demand componennt has a slot Array1D_string DemandCompNames; Array1D_string DemandCompTypes; Real64 VdotFromTank; Real64 VdotToTank; Real64 VdotOverflow; Real64 VolOverflow; // report variables Real64 NetVdot; Real64 Twater; Real64 TouterSkin; Real64 TwaterOverflow; Real64 MainsDrawVdot; Real64 MainsDrawVol; Real64 SkinLossPower; // heat loss to surrounding zone [W] Real64 SkinLossEnergy; // heat loss to surround zone [J] Real64 SkinLossConvect; // convective heat loss to zone [W] Real64 SkinLossRadiat; // radiative heat loss to zone [W} // Default Constructor StorageTankDataStruct() : MaxCapacity(0.0), OverflowMode(0), OverflowTankID(0), OverflowTankSupplyARRID(0), ValveOnCapacity(0.0), ValveOffCapacity(0.0), ControlSupplyType(0), GroundWellID(0), SupplyTankID(0), SupplyTankDemandARRID(0), BackupMainsCapacity(0.0), InitialVolume(0.0), MaxInFlowRate(0.0), MaxOutFlowRate(0.0), ThermalMode(0), InitialTankTemp(20.0), TempSchedID(0), AmbientTempIndicator(0), AmbientTempSchedule(0), ZoneID(0), UValue(0.0), SurfArea(0.0), InternalMassID(0), ThisTimeStepVolume(0.0), LastTimeStepVolume(0.0), LastTimeStepTemp(0.0), NumWaterSupplies(0), NumWaterDemands(0), VdotFromTank(0.0), VdotToTank(0.0), VdotOverflow(0.0), VolOverflow(0.0), NetVdot(0.0), Twater(0.0), TouterSkin(0.0), TwaterOverflow(0.0), MainsDrawVdot(0.0), MainsDrawVol(0.0), SkinLossPower(0.0), SkinLossEnergy(0.0), SkinLossConvect(0.0), SkinLossRadiat(0.0) { } }; struct RainfallCollectorDataStruct { // Members // user input data std::string Name; // name of this rain collector std::string StorageTankName; int StorageTankID; // index "pointer" to storage tank array int StorageTankSupplyARRID; int LossFactorMode; // control how loss factor(s) are entered Real64 LossFactor; // loss factor when constant int LossFactorSchedID; // index "pointer" to schedule Real64 MaxCollectRate; int NumCollectSurfs; // number of surfaces used in the collector Array1D_string SurfName; Array1D_int SurfID; // calculated and from elsewhere Real64 HorizArea; // area of surfaces in the vertical normal direction Real64 VdotAvail; Real64 VolCollected; Real64 MeanHeight; // Default Constructor RainfallCollectorDataStruct() : StorageTankID(0), StorageTankSupplyARRID(0), LossFactorMode(0), LossFactor(0.0), LossFactorSchedID(0), MaxCollectRate(0.0), NumCollectSurfs(0), HorizArea(0.0), VdotAvail(0.0), VolCollected(0.0), MeanHeight(0.0) { } }; struct GroundwaterWellDataStruct { // Members // user input data std::string Name; // name of this std::string StorageTankName; int StorageTankID; // index "pointer" to water storage tank int StorageTankSupplyARRID; // index "pointer" to storage supply arrays Real64 PumpDepth; // depth of pump [m] Real64 PumpNomVolFlowRate; // nominal flow rate of pump [m3/s] Real64 PumpNomHead; // design nominal capacity of pump Real64 PumpNomPowerUse; // design nominal power of pump at nom capacity Real64 PumpEfficiency; Real64 WellRecoveryRate; // rate at which groundwater can enter well [m3/s] Real64 NomWellStorageVol; // water storage in well at average water table depth [m3] int GroundwaterTableMode; // method of determining water table depth Real64 WaterTableDepth; int WaterTableDepthSchedID; // calculated and from elsewhere Real64 VdotRequest; // rate of flow over timestep requested by tank Real64 VdotDelivered; // rate of flow provided [m3/s] Real64 VolDelivered; // water provided [m3] Real64 PumpPower; Real64 PumpEnergy; // Default Constructor GroundwaterWellDataStruct() : StorageTankID(0), StorageTankSupplyARRID(0), PumpDepth(0.0), PumpNomVolFlowRate(0.0), PumpNomHead(0.0), PumpNomPowerUse(0.0), PumpEfficiency(0.0), WellRecoveryRate(0.0), NomWellStorageVol(0.0), GroundwaterTableMode(0), WaterTableDepth(0.0), WaterTableDepthSchedID(0), VdotRequest(0.0), VdotDelivered(0.0), VolDelivered(0.0), PumpPower(0.0), PumpEnergy(0.0) { } }; struct SiteRainFallDataStruct { // Members int ModeID; // type of rainfall modeling Real64 DesignAnnualRain; int RainSchedID; Real64 NomAnnualRain; // calculated and from elsewhere. Real64 CurrentRate; Real64 CurrentAmount; // Default Constructor SiteRainFallDataStruct() : ModeID(0), DesignAnnualRain(0.0), RainSchedID(0), NomAnnualRain(0.0), CurrentRate(0.0), CurrentAmount(0.0) { } }; struct IrrigationDataStruct { // Members int ModeID; // type of irrigation modeling int IrrSchedID; Real64 ScheduledAmount; Real64 ActualAmount; Real64 IrrigationThreshold; // percent at which no irrigation happens (smart schedule) // Default Constructor IrrigationDataStruct() : ModeID(0), IrrSchedID(0), ScheduledAmount(0.0), ActualAmount(0.0), IrrigationThreshold(0.4) { } }; // Object Data extern SiteRainFallDataStruct RainFall; // type of rainfall modeling | design annual rain | rain sched id | nominal annual rain | current rate | current amount extern IrrigationDataStruct Irrigation; // type of irrigation modeling | Irrigation schedule id | scheduled amount | actual amount | irrigation threshold extern Array1D WaterStorage; extern Array1D RainCollector; extern Array1D GroundwaterWell; } // namespace DataWater } // namespace EnergyPlus #endif /* Copyright (c) 2014, Trail of Bits 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 Trail of Bits 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 "peToCFG.h" #include "X86.h" #include #include "../common/to_string.h" #include "llvm/Support/Debug.h" using namespace std; using namespace boost; using namespace llvm; InstPtr LLVMByteDecoder::getInstFromBuff(VA addr, llvm::MemoryObject *bmo) { InstPtr inst; llvm::MCInst mcInst; ::uint64_t insLen; VA nextVA = addr; ::uint32_t arch_type; llvm::MCDisassembler::DecodeStatus s; s = DisAsm->getInstruction( mcInst, insLen, *bmo, ((::uint64_t)nextVA), llvm::nulls(), llvm::nulls()); Inst::Prefix pfx = Inst::NoPrefix; if(s == llvm::MCDisassembler::Success) { if( mcInst.getOpcode() == llvm::X86::MOVSL && mcInst.hasPrefix(0xF3) ) { mcInst.setOpcode(llvm::X86::REP_MOVSD_32); } else if( mcInst.hasPrefix(0xF2) ) { pfx = Inst::RepNePrefix; } else if( mcInst.hasPrefix(0xF3) ) { pfx = Inst::RepPrefix; } else if ( mcInst.hasPrefix(0x64) ) { pfx = Inst::FSPrefix; } else if ( mcInst.hasPrefix(0x64) ) { pfx = Inst::GSPrefix; } string outS; llvm::raw_string_ostream osOut(outS); MCOperand oper; this->IP->printInst(&mcInst, osOut, ""); vector bytes; //store the bytes from the MO in the inst for(unsigned int i = 0; i < insLen; i++) { uint8_t b; int k = bmo->readByte(addr+i, &b); LASSERT(k == 0, "Failed to read data when decoder could"); bytes.push_back(b); } inst = InstPtr(new Inst( addr, insLen, mcInst, osOut.str(), pfx, bytes)); for (unsigned i = 0; i < mcInst.getNumOperands(); ++i) { const MCOperand &Op = mcInst.getOperand(i); if (Op.isReg() && Op.getReg() == X86::RIP) inst->set_rip_relative(i); } //ask if this is a jmp, and figure out what the true / false follows are switch(mcInst.getOpcode()) { case X86::JMP32m: case X86::JMP32r: case X86::JMP64m: case X86::JMP64r: inst->set_terminator(); break; //throw LErr(__LINE__, __FILE__, "Branch through register not okay yet"); //break; case X86::RETL: case X86::RETIL: case X86::RETIQ: case X86::RETIW: case X86::RETQ: inst->set_terminator(); break; case X86::JMP_4: case X86::JMP_1: oper = mcInst.getOperand(0); if(oper.isImm()) { nextVA += oper.getImm() + insLen; inst->set_tr(nextVA); } else { throw LErr(__LINE__, __FILE__, "Indirect branches not there yet"); } break; case X86::LOOP: case X86::LOOPE: case X86::LOOPNE: case X86::JO_4: case X86::JO_1: case X86::JNO_4: case X86::JNO_1: case X86::JB_4: case X86::JB_1: case X86::JAE_4: case X86::JAE_1: case X86::JE_4: case X86::JE_1: case X86::JNE_4: case X86::JNE_1: case X86::JBE_4: case X86::JBE_1: case X86::JA_4: case X86::JA_1: case X86::JS_4: case X86::JS_1: case X86::JNS_4: case X86::JNS_1: case X86::JP_4: case X86::JP_1: case X86::JNP_4: case X86::JNP_1: case X86::JL_4: case X86::JL_1: case X86::JGE_4: case X86::JGE_1: case X86::JLE_4: case X86::JLE_1: case X86::JG_4: case X86::JG_1: case X86::JCXZ: case X86::JECXZ_32: case X86::JRCXZ: oper = mcInst.getOperand(0); LASSERT(oper.isImm(), "Should not be of this type"); inst->set_tr(addr + oper.getImm() + insLen); inst->set_fa(addr + insLen); break; } } else { string s = to_string(addr, hex); throw LErr(__LINE__, __FILE__, "Failed to decode address 0x"+s); } return inst; } #include "../Header/CombSort.h" #include "../Header/Swap.h" #include "../Header/Analysis.h" Analysis combSort(int vet[], int n) { Analysis an; clock_t start = clock(); int indiceA = 0; for (int gap = (n/1.3); gap > 0 && indiceA != n - 1;) { while((indiceA + gap) < n) { int indiceB = gap; an.nCopias++; an.nComparacoes++; if (vet[indiceA] > vet[indiceB]) { swap(&vet[indiceA], &vet[indiceB]); an.nCopias += 3; } indiceA++; } gap = (gap/1.3); indiceA = 0; } clock_t end = clock(); float tempoGasto = ((float)end - start)/CLOCKS_PER_SEC; an.tempoGasto = tempoGasto; return an; }#ifndef __SGE_IMAGE_LOADER_HPP #define __SGE_IMAGE_LOADER_HPP #include #include #include namespace sge { class Image : public Asset { using Asset::Asset; }; class ImageDescriptor : public AssetDescriptor { using AssetDescriptor::AssetDescriptor; }; class ImageLoader : public AssetLoader { public: virtual void load(std::shared_ptr asset, SDL_RWops *input); virtual void unload(BaseAsset *asset); }; } #endif /* __SGE_IMAGE_LOADER_HPP */ library/src/javascript/JSON/BP-LibJSMN.cc // include blockparty main #include "../../../include/BP-Main.h" /** * Allocates a fresh unused token from the token pull. */ static jsmntok_t *jsmn_alloc_token ( P_BP_JSON json, jsmn_parser *parser, jsmntok_t *tokens, size_t num_tokens ) { jsmntok_t *tok; if (parser->toknext >= num_tokens) { BP_JSONParseAddErrorMsg(json, NULL, "parser->toknext >= num_tokens. JSON parsing attempt exhausted preallocated token space. Likely cause is JSON being too large."); return NULL; } tok = &tokens[parser->toknext++]; // note, this was modified by JM due to compilation errors from this = that = -1; tok->end = -1; tok->start = tok->end; tok->size = 0; tok->parent = -1; return tok; } /** * Fills token type and boundaries. */ static void jsmn_fill_token ( P_BP_JSON json, jsmntok_t *token, jsmntype_t type, int start, int end ) { if(!token) { BP_JSONParseAddErrorMsg(json, NULL, "jsmn_fill_token was called with a NULL token."); return; } token->type = type; token->start = start; token->end = end; token->size = 0; } /** * Fills next available token with JSON primitive. */ static int jsmn_parse_primitive ( P_BP_JSON json, jsmn_parser *parser, const char *js, size_t len, jsmntok_t *tokens, size_t num_tokens ) { jsmntok_t *token = NULL; int start = 0; start = parser->pos; for ( ; parser->pos < len && js[parser->pos] != '\0'; parser->pos++ ) { // switch on current character switch (js[parser->pos]) { case '\t': case '\r': case '\n': case ' ': case ',': case ']': case '}': goto found; } if ( js[parser->pos] < 32 || js[parser->pos] >= 127 ) { // create a small temporary stack buffer char tmp_err_buff[512]; BP_ZERO_STACK(tmp_err_buff); // convert values for output sprintf((char *) &tmp_err_buff, "jsmn_parse_primitive() reports that an invalid character \\x%.02x (%c) was found within the json buffer at byte-position: %u.",js[parser->pos], js[parser->pos], parser->pos); // add the error message BP_JSONParseAddErrorMsg(json, NULL, (char *) &tmp_err_buff); parser->pos = start; return JSMN_ERROR_INVAL; } } /* In strict mode primitive must be followed by a comma/object/array */ parser->pos = start; // add the error message BP_JSONParseAddErrorMsg(json, NULL, "jsmn_parse_primitive() reports that the JSON provided was 'too short'. This meaning that the json was parsing fine, except the buffer ended prematurely with regards to parse logic."); return JSMN_ERROR_PART; // token was found to be acceptable found: if (tokens == NULL) { parser->pos--; return 0; } // attempt to allocate token token = jsmn_alloc_token(json, parser, tokens, num_tokens); if (!token) { parser->pos = start; BP_JSONParseAddErrorMsg(json, NULL, "Parser indicates that we've run out of memory."); return JSMN_ERROR_NOMEM; } jsmn_fill_token(json, token, JSMN_PRIMITIVE, start, parser->pos); token->parent = parser->toksuper; parser->pos--; return 0; } /** * Fills next token with JSON string. */ static int jsmn_parse_string ( P_BP_JSON json, jsmn_parser *parser, const char * js, size_t len, jsmntok_t * tokens, size_t num_tokens ) { jsmntok_t *token; int start = parser->pos; parser->pos++; // temporary error buffer char tmp_err_buff[512]; BP_ZERO_STACK(tmp_err_buff); /* Skip starting quote */ for ( ; parser->pos < len && js[parser->pos] != '\0'; parser->pos++ ) { // set reference to current character char c = js[parser->pos]; /* Quote: end of string */ if (c == '\"') { // if tokens is unset, exit immediately if (!tokens) return 0; token = jsmn_alloc_token(json, parser, tokens, num_tokens); if (token == NULL) { parser->pos = start; BP_JSONParseAddErrorMsg(json, NULL, "Parser indicates that jsmn_alloc_token() has failed (potentially out of memory)."); return JSMN_ERROR_NOMEM; } jsmn_fill_token(json, token, JSMN_STRING, start+1, parser->pos); token->parent = parser->toksuper; return 0; } /* Backslash: Quoted symbol expected */ if (c == '\\' && parser->pos + 1 < len) { int i; parser->pos++; switch (js[parser->pos]) { /* Allowed escaped symbols */ case '\"': case '/' : case '\\' : case 'b' : case 'f' : case 'r' : case 'n' : case 't' : break; /* Allows escaped symbol \uXXXX */ case 'u': parser->pos++; // inner search loop for \uXXXX chars for ( i = 0; i < 4 && parser->pos < len && js[parser->pos] != '\0'; i++ ) { /* If it isn't a hex character we have an error */ if ( !( (js[parser->pos] >= 48 && js[parser->pos] <= 57) || /* 0-9 */ (js[parser->pos] >= 65 && js[parser->pos] <= 70) || /* A-F */ (js[parser->pos] >= 97 && js[parser->pos] <= 102) /* a-f */ ) ) { parser->pos = start; // create a small temporary stack buffer BP_ZERO_STACK(tmp_err_buff); // convert values for output sprintf((char *) &tmp_err_buff, "jsmn_parse_string() reports that an invalid character \\x%.02x (%c) was found within the json buffer at byte-position: %u.", js[parser->pos], js[parser->pos], parser->pos); // add the error message BP_JSONParseAddErrorMsg(json, NULL, (char *) &tmp_err_buff); return JSMN_ERROR_INVAL; } parser->pos++; } parser->pos--; break; /* Unexpected symbol */ default: parser->pos = start; // create a small temporary stack buffer BP_ZERO_STACK(tmp_err_buff); // convert values for output sprintf((char *) &tmp_err_buff, "jsmn_parse_string() reports that an invalid character \\x%.02x (%c) was found within the json buffer at byte-position: %u.", js[parser->pos], js[parser->pos], parser->pos); // add the error message BP_JSONParseAddErrorMsg(json, NULL, (char *) &tmp_err_buff); return JSMN_ERROR_INVAL; } } } parser->pos = start; BP_JSONParseAddErrorMsg(json, NULL, "jsmn_parse_string() indicates that we have recieved only partial data. In short, we were parsing fine, but then we unexpectedly ran out of data to parse."); return JSMN_ERROR_PART; } /** * Parse JSON string and fill tokens. This routine has been modified in * order to provide error output information and increase readability. */ int jsmn_parse ( P_BP_JSON json, jsmn_parser *parser, const char * js, size_t len, jsmntok_t * tokens, unsigned int num_tokens ) { // ensure we have js if(!js) { BP_JSONParseAddErrorMsg(json, NULL, "jsmn_parse() was called with a NULL json buffer."); return JSMN_ERROR_INVAL; } // ensure the buffer isn't zero length if(!bpstrlen(js)) { BP_JSONParseAddErrorMsg(json, NULL, "jsmn_parse() was called with a zero length json buffer."); return JSMN_ERROR_INVAL; } // ensure the string is reasonable/printable if(!BP_StringIsReasonablePrintableString((char*) js, bpstrlen(js), BP_TRUE, BP_TRUE)) { BP_JSONParseAddErrorMsg(json, NULL, "jsmn_parse() was called with a len parameter set to zero."); return JSMN_ERROR_INVAL; } // check for length mismatch if(len != bpstrlen(js)) { BP_JSONParseAddErrorMsg(json, NULL, "jsmn_parse() was called with a len parameter set to zero."); return JSMN_ERROR_INVAL; } // ensure the byte parameter matches up if(!len) { BP_JSONParseAddErrorMsg(json, NULL, "jsmn_parse() was called with a len parameter set to zero."); return JSMN_ERROR_INVAL; } // ensure we have a parser if(!parser) { BP_JSONParseAddErrorMsg(json, NULL, "jsmn_parse() was called without a parser."); return JSMN_ERROR_INVAL; } int r = 0; int i = 0; jsmntok_t *token = NULL; int count = parser->toknext; // create and zero a temporary buffer char tmp_err_buff[512]; BP_ZERO_STACK(tmp_err_buff); for ( ; parser->pos < len && js[parser->pos] != '\0'; parser->pos++ ) { char c; jsmntype_t type; c = js[parser->pos]; switch (c) { case '{': case '[': // increase the count count++; // exit case if tokens is unset if (!tokens) break; // attempt to allocate new token token = jsmn_alloc_token(json, parser, tokens, num_tokens); if (token == NULL) { BP_JSONParseAddErrorMsg(json, NULL, "Parser indicates that we've run out of memory.", (int) parser->pos, c); return JSMN_ERROR_NOMEM; } if (parser->toksuper != -1) { tokens[parser->toksuper].size++; token->parent = parser->toksuper; } token->type = (c == '{' ? JSMN_OBJECT : JSMN_ARRAY); token->start = parser->pos; parser->toksuper = parser->toknext - 1; break; case '}': case ']': if(!tokens) break; type = (c == '}' ? JSMN_OBJECT : JSMN_ARRAY); if (parser->toknext < 1) { // convert values for output BP_ZERO_STACK(tmp_err_buff); sprintf((char *) &tmp_err_buff, "jsmn_parse() reports that an invalid character \\x%.02x (%c) was found within the json buffer at byte-position: %u.", js[parser->pos], js[parser->pos], parser->pos); // add the error message BP_JSONParseAddErrorMsg(json, NULL, (char *) &tmp_err_buff, (int) parser->pos, c); return JSMN_ERROR_INVAL; } token = &tokens[parser->toknext - 1]; for (;;) { if (token->start != -1 && token->end == -1) { if (token->type != type) { // convert values for output BP_ZERO_STACK(tmp_err_buff); sprintf((char *) &tmp_err_buff, "jsmn_parse() reports that an invalid character \\x%.02x (%c) was found within the json buffer at byte-position: %u.", js[parser->pos], js[parser->pos], parser->pos); // add the error message BP_JSONParseAddErrorMsg(json, NULL, (char *) &tmp_err_buff, (int) parser->pos, c); return JSMN_ERROR_INVAL; } token->end = parser->pos + 1; parser->toksuper = token->parent; break; } if (token->parent == -1) { break; } token = &tokens[token->parent]; } break; case '\"': r = jsmn_parse_string(json, parser, js, len, tokens, num_tokens); if (r < 0) return r; count++; if (parser->toksuper != -1 && tokens != NULL) tokens[parser->toksuper].size++; break; case '\t' : case '\r' : case '\n' : case ' ': break; case ':': parser->toksuper = parser->toknext - 1; break; case ',': if (tokens != NULL && parser->toksuper != -1 && tokens[parser->toksuper].type != JSMN_ARRAY && tokens[parser->toksuper].type != JSMN_OBJECT) { parser->toksuper = tokens[parser->toksuper].parent; } break; /* In strict mode primitives are: numbers and booleans */ case '-': case '0': case '1' : case '2': case '3' : case '4': case '5': case '6': case '7' : case '8': case '9': case 't': case 'f': case 'n' : /* And they must not be keys of the object */ if (tokens != NULL && parser->toksuper != -1) { jsmntok_t *t = &tokens[parser->toksuper]; if ( t->type == JSMN_OBJECT || (t->type == JSMN_STRING && t->size != 0) ) { // convert values for output BP_ZERO_STACK(tmp_err_buff); sprintf((char *) &tmp_err_buff, "jsmn_parse() reports that an invalid character \\x%.02x (%c) was found within the json buffer at byte-position: %u.", js[parser->pos], js[parser->pos], parser->pos); // add the error message BP_JSONParseAddErrorMsg(json, NULL, (char *) &tmp_err_buff, (int) parser->pos, c); return JSMN_ERROR_INVAL; } } r = jsmn_parse_primitive(json, parser, js, len, tokens, num_tokens); if (r < 0) return r; count++; if (parser->toksuper != -1 && tokens != NULL) tokens[parser->toksuper].size++; break; /* Unexpected char in strict mode */ default: // convert values for output BP_ZERO_STACK(tmp_err_buff); sprintf((char *) &tmp_err_buff, "jsmn_parse() reports that an invalid character \\x%.02x (%c) was found within the json buffer at byte-position: %u.", js[parser->pos], js[parser->pos], parser->pos); // add the error message BP_JSONParseAddErrorMsg(json, NULL, (char *) &tmp_err_buff, (int) parser->pos, c); return JSMN_ERROR_INVAL; } } if (tokens != NULL) { for (i = parser->toknext - 1; i >= 0; i--) { /* Unmatched opened object or array */ if (tokens[i].start != -1 && tokens[i].end == -1) { BP_JSONParseAddErrorMsg(json, NULL, "json_parse() was parsing OK but ran out of data to parse before state was balanced."); return JSMN_ERROR_PART; } } } return count; } /** * Creates a new parser based over a given buffer with an array of tokens * available. */ void jsmn_init ( P_BP_JSON json, jsmn_parser *parser ) { // basic null checks if(!json) return; if(!parser) return; parser->pos = 0; parser->toknext = 0; parser->toksuper = -1; } Grosskopf/openoffice /************************************************************** * * 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. * *************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_drawinglayer.hxx" #include #include #include #include #include #include #include #include #include #include #include ////////////////////////////////////////////////////////////////////////////// namespace drawinglayer { namespace primitive2d { void TextDecoratedPortionPrimitive2D::impCreateGeometryContent( std::vector< Primitive2DReference >& rTarget, basegfx::tools::B2DHomMatrixBufferedOnDemandDecompose& rDecTrans, const String& rText, xub_StrLen aTextPosition, xub_StrLen aTextLength, const ::std::vector< double >& rDXArray, const attribute::FontAttribute& rFontAttribute) const { // create the SimpleTextPrimitive needed in any case rTarget.push_back(Primitive2DReference( new TextSimplePortionPrimitive2D( rDecTrans.getB2DHomMatrix(), rText, aTextPosition, aTextLength, rDXArray, rFontAttribute, getLocale(), getFontColor()))); // see if something else needs to be done const bool bOverlineUsed(TEXT_LINE_NONE != getFontOverline()); const bool bUnderlineUsed(TEXT_LINE_NONE != getFontUnderline()); const bool bStrikeoutUsed(TEXT_STRIKEOUT_NONE != getTextStrikeout()); if(bUnderlineUsed || bStrikeoutUsed || bOverlineUsed) { // common preparations TextLayouterDevice aTextLayouter; // TextLayouterDevice is needed to get metrics for text decorations like // underline/strikeout/emphasis marks from it. For setup, the font size is needed aTextLayouter.setFontAttribute( getFontAttribute(), rDecTrans.getScale().getX(), rDecTrans.getScale().getY(), getLocale()); // get text width double fTextWidth(0.0); if(rDXArray.empty()) { fTextWidth = aTextLayouter.getTextWidth(rText, aTextPosition, aTextLength); } else { fTextWidth = rDXArray.back() * rDecTrans.getScale().getX(); const double fFontScaleX(rDecTrans.getScale().getX()); if(!basegfx::fTools::equal(fFontScaleX, 1.0) && !basegfx::fTools::equalZero(fFontScaleX)) { // need to take FontScaling out of the DXArray fTextWidth /= fFontScaleX; } } if(bOverlineUsed) { // create primitive geometry for overline rTarget.push_back(Primitive2DReference( new TextLinePrimitive2D( rDecTrans.getB2DHomMatrix(), fTextWidth, aTextLayouter.getOverlineOffset(), aTextLayouter.getOverlineHeight(), getFontOverline(), getOverlineColor()))); } if(bUnderlineUsed) { // create primitive geometry for underline rTarget.push_back(Primitive2DReference( new TextLinePrimitive2D( rDecTrans.getB2DHomMatrix(), fTextWidth, aTextLayouter.getUnderlineOffset(), aTextLayouter.getUnderlineHeight(), getFontUnderline(), getTextlineColor()))); } if(bStrikeoutUsed) { // create primitive geometry for strikeout if(TEXT_STRIKEOUT_SLASH == getTextStrikeout() || TEXT_STRIKEOUT_X == getTextStrikeout()) { // strikeout with character const sal_Unicode aStrikeoutChar(TEXT_STRIKEOUT_SLASH == getTextStrikeout() ? '/' : 'X'); rTarget.push_back(Primitive2DReference( new TextCharacterStrikeoutPrimitive2D( rDecTrans.getB2DHomMatrix(), fTextWidth, getFontColor(), aStrikeoutChar, getFontAttribute(), getLocale()))); } else { // strikeout with geometry rTarget.push_back(Primitive2DReference( new TextGeometryStrikeoutPrimitive2D( rDecTrans.getB2DHomMatrix(), fTextWidth, getFontColor(), aTextLayouter.getUnderlineHeight(), aTextLayouter.getStrikeoutOffset(), getTextStrikeout()))); } } } // TODO: Handle Font Emphasis Above/Below } Primitive2DSequence TextDecoratedPortionPrimitive2D::create2DDecomposition(const geometry::ViewInformation2D& /*rViewInformation*/) const { if(getWordLineMode()) { // support for single word mode; split to single word primitives // using TextBreakupHelper const TextBreakupHelper aTextBreakupHelper(*this); const Primitive2DSequence aBroken(aTextBreakupHelper.getResult(BreakupUnit_word)); if(aBroken.hasElements()) { // was indeed split to several words, use as result return aBroken; } else { // no split, was already a single word. Continue to // decompse local entity } } std::vector< Primitive2DReference > aNewPrimitives; basegfx::tools::B2DHomMatrixBufferedOnDemandDecompose aDecTrans(getTextTransform()); Primitive2DSequence aRetval; // create basic geometry such as SimpleTextPrimitive, Overline, Underline, // Strikeout, etc... // prepare new font attributes WITHOUT outline const attribute::FontAttribute aNewFontAttribute( getFontAttribute().getFamilyName(), getFontAttribute().getStyleName(), getFontAttribute().getWeight(), getFontAttribute().getSymbol(), getFontAttribute().getVertical(), getFontAttribute().getItalic(), false, // no outline anymore, handled locally getFontAttribute().getRTL(), getFontAttribute().getBiDiStrong()); // handle as one word impCreateGeometryContent(aNewPrimitives, aDecTrans, getText(), getTextPosition(), getTextLength(), getDXArray(), aNewFontAttribute); // convert to Primitive2DSequence const sal_uInt32 nMemberCount(aNewPrimitives.size()); if(nMemberCount) { aRetval.realloc(nMemberCount); for(sal_uInt32 a(0); a < nMemberCount; a++) { aRetval[a] = aNewPrimitives[a]; } } // Handle Shadow, Outline and TextRelief if(aRetval.hasElements()) { // outline AND shadow depend on NO TextRelief (see dialog) const bool bHasTextRelief(TEXT_RELIEF_NONE != getTextRelief()); const bool bHasShadow(!bHasTextRelief && getShadow()); const bool bHasOutline(!bHasTextRelief && getFontAttribute().getOutline()); if(bHasShadow || bHasTextRelief || bHasOutline) { Primitive2DReference aShadow; if(bHasShadow) { // create shadow with current content (in aRetval). Text shadow // is constant, relative to font size, rotated with the text and has a // constant color. // shadow parameter values static double fFactor(1.0 / 24.0); const double fTextShadowOffset(aDecTrans.getScale().getY() * fFactor); static basegfx::BColor aShadowColor(0.3, 0.3, 0.3); // preapare shadow transform matrix const basegfx::B2DHomMatrix aShadowTransform(basegfx::tools::createTranslateB2DHomMatrix( fTextShadowOffset, fTextShadowOffset)); // create shadow primitive aShadow = Primitive2DReference(new ShadowPrimitive2D( aShadowTransform, aShadowColor, aRetval)); } if(bHasTextRelief) { // create emboss using an own helper primitive since this will // be view-dependent const basegfx::BColor aBBlack(0.0, 0.0, 0.0); const bool bDefaultTextColor(aBBlack == getFontColor()); TextEffectStyle2D aTextEffectStyle2D(TEXTEFFECTSTYLE2D_RELIEF_EMBOSSED); if(bDefaultTextColor) { if(TEXT_RELIEF_ENGRAVED == getTextRelief()) { aTextEffectStyle2D = TEXTEFFECTSTYLE2D_RELIEF_ENGRAVED_DEFAULT; } else { aTextEffectStyle2D = TEXTEFFECTSTYLE2D_RELIEF_EMBOSSED_DEFAULT; } } else { if(TEXT_RELIEF_ENGRAVED == getTextRelief()) { aTextEffectStyle2D = TEXTEFFECTSTYLE2D_RELIEF_ENGRAVED; } else { aTextEffectStyle2D = TEXTEFFECTSTYLE2D_RELIEF_EMBOSSED; } } Primitive2DReference aNewTextEffect(new TextEffectPrimitive2D( aRetval, aDecTrans.getTranslate(), aDecTrans.getRotate(), aTextEffectStyle2D)); aRetval = Primitive2DSequence(&aNewTextEffect, 1); } else if(bHasOutline) { // create outline using an own helper primitive since this will // be view-dependent Primitive2DReference aNewTextEffect(new TextEffectPrimitive2D( aRetval, aDecTrans.getTranslate(), aDecTrans.getRotate(), TEXTEFFECTSTYLE2D_OUTLINE)); aRetval = Primitive2DSequence(&aNewTextEffect, 1); } if(aShadow.is()) { // put shadow in front if there is one to paint timely before // but placed behind content const Primitive2DSequence aContent(aRetval); aRetval = Primitive2DSequence(&aShadow, 1); appendPrimitive2DSequenceToPrimitive2DSequence(aRetval, aContent); } } } return aRetval; } TextDecoratedPortionPrimitive2D::TextDecoratedPortionPrimitive2D( // TextSimplePortionPrimitive2D parameters const basegfx::B2DHomMatrix& rNewTransform, const String& rText, xub_StrLen aTextPosition, xub_StrLen aTextLength, const ::std::vector< double >& rDXArray, const attribute::FontAttribute& rFontAttribute, const ::com::sun::star::lang::Locale& rLocale, const basegfx::BColor& rFontColor, // local parameters const basegfx::BColor& rOverlineColor, const basegfx::BColor& rTextlineColor, TextLine eFontOverline, TextLine eFontUnderline, bool bUnderlineAbove, TextStrikeout eTextStrikeout, bool bWordLineMode, TextEmphasisMark eTextEmphasisMark, bool bEmphasisMarkAbove, bool bEmphasisMarkBelow, TextRelief eTextRelief, bool bShadow) : TextSimplePortionPrimitive2D(rNewTransform, rText, aTextPosition, aTextLength, rDXArray, rFontAttribute, rLocale, rFontColor), maOverlineColor(rOverlineColor), maTextlineColor(rTextlineColor), meFontOverline(eFontOverline), meFontUnderline(eFontUnderline), meTextStrikeout(eTextStrikeout), meTextEmphasisMark(eTextEmphasisMark), meTextRelief(eTextRelief), mbUnderlineAbove(bUnderlineAbove), mbWordLineMode(bWordLineMode), mbEmphasisMarkAbove(bEmphasisMarkAbove), mbEmphasisMarkBelow(bEmphasisMarkBelow), mbShadow(bShadow) { } bool TextDecoratedPortionPrimitive2D::decoratedIsNeeded() const { return (TEXT_LINE_NONE != getFontOverline() || TEXT_LINE_NONE != getFontUnderline() || TEXT_STRIKEOUT_NONE != getTextStrikeout() || TEXT_EMPHASISMARK_NONE != getTextEmphasisMark() || TEXT_RELIEF_NONE != getTextRelief() || getShadow()); } bool TextDecoratedPortionPrimitive2D::operator==(const BasePrimitive2D& rPrimitive) const { if(TextSimplePortionPrimitive2D::operator==(rPrimitive)) { const TextDecoratedPortionPrimitive2D& rCompare = (TextDecoratedPortionPrimitive2D&)rPrimitive; return (getOverlineColor() == rCompare.getOverlineColor() && getTextlineColor() == rCompare.getTextlineColor() && getFontOverline() == rCompare.getFontOverline() && getFontUnderline() == rCompare.getFontUnderline() && getTextStrikeout() == rCompare.getTextStrikeout() && getTextEmphasisMark() == rCompare.getTextEmphasisMark() && getTextRelief() == rCompare.getTextRelief() && getUnderlineAbove() == rCompare.getUnderlineAbove() && getWordLineMode() == rCompare.getWordLineMode() && getEmphasisMarkAbove() == rCompare.getEmphasisMarkAbove() && getEmphasisMarkBelow() == rCompare.getEmphasisMarkBelow() && getShadow() == rCompare.getShadow()); } return false; } // #i96475# // Added missing implementation. Decorations may (will) stick out of the text's // inking area, so add them if needed basegfx::B2DRange TextDecoratedPortionPrimitive2D::getB2DRange(const geometry::ViewInformation2D& rViewInformation) const { if(decoratedIsNeeded()) { // decoration is used, fallback to BufferedDecompositionPrimitive2D::getB2DRange which uses // the own local decomposition for computation and thus creates all necessary // geometric objects return BufferedDecompositionPrimitive2D::getB2DRange(rViewInformation); } else { // no relevant decoration used, fallback to TextSimplePortionPrimitive2D::getB2DRange return TextSimplePortionPrimitive2D::getB2DRange(rViewInformation); } } // provide unique ID ImplPrimitrive2DIDBlock(TextDecoratedPortionPrimitive2D, PRIMITIVE2D_ID_TEXTDECORATEDPORTIONPRIMITIVE2D) } // end of namespace primitive2d } // end of namespace drawinglayer ////////////////////////////////////////////////////////////////////////////// // eof 1-10 // Copyright 2006 - 2019. // 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 SGE_INPUT_KEYBOARD_DEVICE_HPP_INCLUDED #define SGE_INPUT_KEYBOARD_DEVICE_HPP_INCLUDED #include #include #include #include #include namespace sge::input::keyboard { class SGE_CORE_DETAIL_CLASS_SYMBOL device { FCPPT_NONMOVABLE(device); protected: SGE_INPUT_DETAIL_SYMBOL device(); public: SGE_INPUT_DETAIL_SYMBOL virtual ~device(); [[nodiscard]] virtual sge::window::object &window() const = 0; }; } #endif // This file is a modified version of the sdl2_gl_single_file_example.cpp // from https://github.com/jherico/OpenXR-Samples/blob/master/src/examples/sdl2_gl_single_file_example.cpp // Created by on 2019/09/18 // // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #define XR_USE_GRAPHICS_API_OPENGL #define GL_GLEXT_PROTOTYPES #define GL3_PROTOTYPES #include #include #if defined(WIN32) #define XR_USE_PLATFORM_WIN32 #else #define XR_USE_PLATFORM_XLIB #include #endif #include #include #include #include #include #include #include #include #include #include #include #include namespace logging { using Time = std::chrono::time_point; } template std::string string_format( const std::string& format, Args ... args ) { int size_s = snprintf( nullptr, 0, format.c_str(), args ... ) + 1; // Extra space for '\0' if( size_s <= 0 ){ throw std::runtime_error( "Error during formatting." ); } auto size = static_cast( size_s ); auto buf = std::make_unique( size ); snprintf( buf.get(), size, format.c_str(), args ... ); return std::string( buf.get(), buf.get() + size - 1 ); // We don't want the '\0' inside } namespace logging { // Values picked to match the OpenXR XrDebugUtilsMessageSeverityFlagBitsEXT values enum class Level : uint32_t { Debug = 0x00000001, Info = 0x00000010, Warning = 0x00000100, Error = 0x00001000, }; inline std::string to_string(Level level) { uint32_t levelRaw = reinterpret_cast(level); if (0x00001000 == (levelRaw & 0x00001000)) { return "ERROR"; } else if (0x00000100 == (levelRaw & 0x00000100)) { return "WARNING"; } else if (0x00000010 == (levelRaw & 0x00000010)) { return "INFO"; } return "DEBUG"; } inline void log(Level level, const std::string& message) { std::string output = "[" + to_string(level) + "] " + message; std::cout << output << std::endl; } } // namespace logging #define LOG_FORMATTED(level, str, ...) logging::log(level, string_format(str, __VA_ARGS__)) #define LOG_DEBUG(str, ...) logging::log(logging::Level::Debug, string_format(str, __VA_ARGS__)) #define LOG_INFO(str, ...) logging::log(logging::Level::Info, string_format(str, __VA_ARGS__)) #define LOG_WARN(str, ...) logging::log(logging::Level::Warning, string_format(str, __VA_ARGS__)) #define LOG_ERROR(str, ...) logging::log(logging::Level::Error, string_format(str, __VA_ARGS__)) namespace xrs { namespace DebugUtilsEXT { using MessageSeverityFlagBits = xr::DebugUtilsMessageSeverityFlagBitsEXT; using MessageTypeFlagBits = xr::DebugUtilsMessageTypeFlagBitsEXT; using MessageSeverityFlags = xr::DebugUtilsMessageSeverityFlagsEXT; using MessageTypeFlags = xr::DebugUtilsMessageTypeFlagsEXT; using CallbackData = xr::DebugUtilsMessengerCallbackDataEXT; using Messenger = xr::DebugUtilsMessengerEXT; // Raw C callback static XrBool32 debugCallback(XrDebugUtilsMessageSeverityFlagsEXT sev_, XrDebugUtilsMessageTypeFlagsEXT type_, const XrDebugUtilsMessengerCallbackDataEXT* data_, void* userData) { LOG_FORMATTED((logging::Level)sev_, "%s: %s", data_->functionName, data_->message); return XR_TRUE; } Messenger create(const xr::Instance& instance, const MessageSeverityFlags& severityFlags = MessageSeverityFlagBits::AllBits, const MessageTypeFlags& typeFlags = MessageTypeFlagBits::AllBits, void* userData = nullptr) { return instance.createDebugUtilsMessengerEXT({ severityFlags, typeFlags, debugCallback, userData }, xr::DispatchLoaderDynamic{ instance }); } } // namespace DebugUtilsEXT } // namespace xrs namespace xr { inline void for_each_side_index(std::function lambda) { for (uint32_t i = 0; i < 2; ++i) { lambda(i); } } } inline void debugMessageCallback(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar* message, const void* userParam) { std::cout << message << std::endl; } std::string formatToString(GLenum format) { switch (format) { case GL_COMPRESSED_R11_EAC: return "COMPRESSED_R11_EAC"; case GL_COMPRESSED_RED_RGTC1: return "COMPRESSED_RED_RGTC1"; case GL_COMPRESSED_RG_RGTC2: return "COMPRESSED_RG_RGTC2"; case GL_COMPRESSED_RG11_EAC: return "COMPRESSED_RG11_EAC"; case GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT: return "COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT"; case GL_COMPRESSED_RGB8_ETC2: return "COMPRESSED_RGB8_ETC2"; case GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2: return "COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2"; case GL_COMPRESSED_RGBA8_ETC2_EAC: return "COMPRESSED_RGBA8_ETC2_EAC"; case GL_COMPRESSED_SIGNED_R11_EAC: return "COMPRESSED_SIGNED_R11_EAC"; case GL_COMPRESSED_SIGNED_RG11_EAC: return "COMPRESSED_SIGNED_RG11_EAC"; case GL_COMPRESSED_SRGB_ALPHA_BPTC_UNORM: return "COMPRESSED_SRGB_ALPHA_BPTC_UNORM"; case GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC: return "COMPRESSED_SRGB8_ALPHA8_ETC2_EAC"; case GL_COMPRESSED_SRGB8_ETC2: return "COMPRESSED_SRGB8_ETC2"; case GL_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2: return "COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2"; case GL_DEPTH_COMPONENT16: return "DEPTH_COMPONENT16"; case GL_DEPTH_COMPONENT24: return "DEPTH_COMPONENT24"; case GL_DEPTH_COMPONENT32: return "DEPTH_COMPONENT32"; case GL_DEPTH_COMPONENT32F: return "DEPTH_COMPONENT32F"; case GL_DEPTH24_STENCIL8: return "DEPTH24_STENCIL8"; case GL_R11F_G11F_B10F: return "R11F_G11F_B10F"; case GL_R16_SNORM: return "R16_SNORM"; case GL_R16: return "R16"; case GL_R16F: return "R16F"; case GL_R16I: return "R16I"; case GL_R16UI: return "R16UI"; case GL_R32F: return "R32F"; case GL_R32I: return "R32I"; case GL_R32UI: return "R32UI"; case GL_R8_SNORM: return "R8_SNORM"; case GL_R8: return "R8"; case GL_R8I: return "R8I"; case GL_R8UI: return "R8UI"; case GL_RG16_SNORM: return "RG16_SNORM"; case GL_RG16: return "RG16"; case GL_RG16F: return "RG16F"; case GL_RG16I: return "RG16I"; case GL_RG16UI: return "RG16UI"; case GL_RG32F: return "RG32F"; case GL_RG32I: return "RG32I"; case GL_RG32UI: return "RG32UI"; case GL_RG8_SNORM: return "RG8_SNORM"; case GL_RG8: return "RG8"; case GL_RG8I: return "RG8I"; case GL_RG8UI: return "RG8UI"; case GL_RGB10_A2: return "RGB10_A2"; case GL_RGB8: return "RGB8"; case GL_RGB9_E5: return "RGB9_E5"; case GL_RGBA16_SNORM: return "RGBA16_SNORM"; case GL_RGBA16: return "RGBA16"; case GL_RGBA16F: return "RGBA16F"; case GL_RGBA16I: return "RGBA16I"; case GL_RGBA16UI: return "RGBA16UI"; case GL_RGBA2: return "RGBA2"; case GL_RGBA32F: return "RGBA32F"; case GL_RGBA32I: return "RGBA32I"; case GL_RGBA32UI: return "RGBA32UI"; case GL_RGBA8_SNORM: return "RGBA8_SNORM"; case GL_RGBA8: return "RGBA8"; case GL_RGBA8I: return "RGBA8I"; case GL_RGBA8UI: return "RGBA8UI"; case GL_SRGB8_ALPHA8: return "SRGB8_ALPHA8"; case GL_SRGB8: return "SRGB8"; case GL_RGB16F: return "RGB16F"; case GL_DEPTH32F_STENCIL8: return "DEPTH32F_STENCIL8"; case GL_BGR: return "BGR (Out of spec)"; case GL_BGRA: return "BGRA (Out of spec)"; } return "unknown"; } struct OpenXrExample { bool quit{ false }; // Application main function void run() { // Startup work prepare(); // Loop while (!quit) { frame(); } // Teardown work destroy(); } ////////////////////////////////////// // One-time setup work // ////////////////////////////////////// // The top level prepare function, which is broken down by task void prepare() { // The OpenXR instance and the OpenXR system provide information we'll require to create our window // and rendering backend, so it has to come first prepareXrInstance(); prepareXrSystem(); prepareWindow(); prepareXrSession(); prepareXrSwapchain(); prepareXrCompositionLayers(); prepareGlFramebuffer(); } bool enableDebug{ true }; xr::Instance instance; xr::DispatchLoaderDynamic dispatch; xrs::DebugUtilsEXT::Messenger messenger; void prepareXrInstance() { std::unordered_map discoveredExtensions; for (const auto& extensionProperties : xr::enumerateInstanceExtensionPropertiesToVector(nullptr)) { discoveredExtensions.insert({ extensionProperties.extensionName, extensionProperties }); } #if !defined(SUPPRESS_DEBUG_UTILS) if (0 == discoveredExtensions.count(XR_EXT_DEBUG_UTILS_EXTENSION_NAME)) { enableDebug = false; } #else enableDebug = false; #endif std::vector requestedExtensions; if (0 == discoveredExtensions.count(XR_KHR_OPENGL_ENABLE_EXTENSION_NAME)) { throw std::runtime_error( string_format("Required Graphics API extension not available: %s", XR_KHR_OPENGL_ENABLE_EXTENSION_NAME)); } requestedExtensions.push_back(XR_KHR_OPENGL_ENABLE_EXTENSION_NAME); if (enableDebug) { requestedExtensions.push_back(XR_EXT_DEBUG_UTILS_EXTENSION_NAME); } xr::InstanceCreateInfo ici{ {}, { "gl_single_file_example", 0, "openXrSamples", 0, xr::Version::current() }, 0, nullptr, (uint32_t)requestedExtensions.size(), requestedExtensions.data() }; xr::DebugUtilsMessengerCreateInfoEXT dumci; if (enableDebug) { dumci.messageSeverities = xr::DebugUtilsMessageSeverityFlagBitsEXT::AllBits; dumci.messageTypes = xr::DebugUtilsMessageTypeFlagBitsEXT::AllBits; dumci.userData = this; dumci.userCallback = &xrs::DebugUtilsEXT::debugCallback; ici.next = &dumci; } // Create the actual instance instance = xr::createInstance(ici); // Turn on debug logging if (enableDebug) { messenger = xrs::DebugUtilsEXT::create(instance); } // Having created the isntance, the very first thing to do is populate the dynamic dispatch, loading // all the available functions from the runtime dispatch = xr::DispatchLoaderDynamic::createFullyPopulated(instance, &xrGetInstanceProcAddr); // Log the instance properties xr::InstanceProperties instanceProperties = instance.getInstanceProperties(); LOG_INFO("OpenXR Runtime %s version %d.%d.%d", // (const char*)instanceProperties.runtimeName, instanceProperties.runtimeVersion.major(), instanceProperties.runtimeVersion.minor(), instanceProperties.runtimeVersion.patch()); } xr::SystemId systemId; std::vector renderTargetSize; xr::GraphicsRequirementsOpenGLKHR graphicsRequirements; void prepareXrSystem() { // We want to create an HMD example, so we ask for a runtime that supposts that form factor // and get a response in the form of a systemId systemId = instance.getSystem(xr::SystemGetInfo{ xr::FormFactor::HeadMountedDisplay }); // Log the system properties { xr::SystemProperties systemProperties = instance.getSystemProperties(systemId); LOG_INFO("OpenXR System %s max layers %d max swapchain image size %dx%d", // (const char*)systemProperties.systemName, (uint32_t)systemProperties.graphicsProperties.maxLayerCount, (uint32_t)systemProperties.graphicsProperties.maxSwapchainImageWidth, (uint32_t)systemProperties.graphicsProperties.maxSwapchainImageHeight); } // Find out what view configurations we have available { auto viewConfigTypes = instance.enumerateViewConfigurationsToVector(systemId); auto viewConfigType = viewConfigTypes[0]; if (viewConfigType != xr::ViewConfigurationType::PrimaryStereo) { throw std::runtime_error("Example only supports stereo-based HMD rendering"); } } std::vector viewConfigViews = instance.enumerateViewConfigurationViewsToVector(systemId, xr::ViewConfigurationType::PrimaryStereo); // Instead of creating a swapchain per-eye, we create a single swapchain of double width. // Even preferable would be to create a swapchain texture array with one layer per eye, so that we could use the // VK_KHR_multiview to render both eyes with a single set of draws, but sadly the Oculus runtime doesn't currently // support texture array swapchains if (viewConfigViews.size() != 2) { throw std::runtime_error("Unexpected number of view configurations"); } if (viewConfigViews[0].recommendedImageRectHeight != viewConfigViews[1].recommendedImageRectHeight) { throw std::runtime_error("Per-eye images have different recommended heights"); } renderTargetSize = { viewConfigViews[0].recommendedImageRectWidth * 2, viewConfigViews[0].recommendedImageRectHeight }; graphicsRequirements = instance.getOpenGLGraphicsRequirementsKHR(systemId, dispatch); } SDL_Window* window; SDL_GLContext context; std::vector windowSize; void prepareWindow() { assert(renderTargetSize[0] != 0 && renderTargetSize[1] != 0); windowSize = renderTargetSize; windowSize[0] /= 4; windowSize[1] /= 4; if (SDL_Init(SDL_INIT_VIDEO) < 0) { LOG_ERROR("Unable to initialize SDL", ""); return; } SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); SDL_GL_SetAttribute(SDL_GL_ACCELERATED_VISUAL, 1); SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, graphicsRequirements.maxApiVersionSupported.major()); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, graphicsRequirements.maxApiVersionSupported.minor()); SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_DEBUG_FLAG); window = SDL_CreateWindow("", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, windowSize[0], windowSize[1], SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN); context = SDL_GL_CreateContext(window); SDL_GL_MakeCurrent(window, context); SDL_GL_SetSwapInterval(0); glDebugMessageCallback(debugMessageCallback, NULL); glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS); } xr::Session session; void prepareXrSession() { # if defined(WIN32) xr::GraphicsBindingOpenGLWin32KHR graphicsBinding{ wglGetCurrentDC(), wglGetCurrentContext() }; #else xr::GraphicsBindingOpenGLXlibKHR graphicsBinding; graphicsBinding.xDisplay = glXGetCurrentDisplay(); graphicsBinding.glxContext = glXGetCurrentContext(); graphicsBinding.glxDrawable = glXGetCurrentDrawable(); #endif xr::SessionCreateInfo sci{ {}, systemId }; sci.next = &graphicsBinding; session = instance.createSession(sci); auto referenceSpaces = session.enumerateReferenceSpacesToVector(); space = session.createReferenceSpace(xr::ReferenceSpaceCreateInfo(xr::ReferenceSpaceType::Local, xr::Posef())); auto swapchainFormats = session.enumerateSwapchainFormatsToVector(); for (const auto& format : swapchainFormats) { LOG_INFO(" %s", formatToString((GLenum)format).c_str()); } } xr::SwapchainCreateInfo swapchainCreateInfo; xr::Swapchain swapchain; std::vector swapchainImages; void prepareXrSwapchain() { swapchainCreateInfo.usageFlags = xr::SwapchainUsageFlagBits::TransferDst; swapchainCreateInfo.format = (int64_t)GL_SRGB8_ALPHA8; swapchainCreateInfo.sampleCount = 1; swapchainCreateInfo.arraySize = 1; swapchainCreateInfo.faceCount = 1; swapchainCreateInfo.mipCount = 1; swapchainCreateInfo.width = renderTargetSize[0]; swapchainCreateInfo.height = renderTargetSize[1]; swapchain = session.createSwapchain(swapchainCreateInfo); swapchainImages = swapchain.enumerateSwapchainImagesToVector(); } std::array projectionLayerViews; xr::CompositionLayerProjection projectionLayer{ {}, {}, 2, projectionLayerViews.data() }; xr::Space& space{ projectionLayer.space }; std::vector layersPointers; void prepareXrCompositionLayers() { //session.getReferenceSpaceBoundsRect(xr::ReferenceSpaceType::Local, bounds); projectionLayer.viewCount = 2; projectionLayer.views = projectionLayerViews.data(); layersPointers.push_back(&projectionLayer); // Finish setting up the layer submission xr::for_each_side_index([&](uint32_t eyeIndex) { auto& layerView = projectionLayerViews[eyeIndex]; layerView.subImage.swapchain = swapchain; layerView.subImage.imageRect.extent.width = (int32_t)renderTargetSize[0] / 2; layerView.subImage.imageRect.extent.height = (int32_t)renderTargetSize[1]; if (eyeIndex == 1) { layerView.subImage.imageRect.offset.x = layerView.subImage.imageRect.extent.width; } }); } struct GLFBO { GLuint id{ 0 }; GLuint depthBuffer{ 0 }; } fbo; void prepareGlFramebuffer() { // Create a depth renderbuffer compatible with the Swapchain sample count and size glGenRenderbuffers(1, &fbo.depthBuffer); glBindRenderbuffer(GL_RENDERBUFFER, fbo.depthBuffer); if (swapchainCreateInfo.sampleCount == 1) { glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, swapchainCreateInfo.width, swapchainCreateInfo.height); } else { glRenderbufferStorageMultisample(GL_RENDERBUFFER, swapchainCreateInfo.sampleCount, GL_DEPTH24_STENCIL8, swapchainCreateInfo.width, swapchainCreateInfo.height); } // Create a framebuffer and attach the depth buffer to it glGenFramebuffers(1, &fbo.id); glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo.id); glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, fbo.depthBuffer); glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); } ////////////////////////////////////// // Per-frame work // ////////////////////////////////////// void frame() { pollSdlEvents(); pollXrEvents(); if (quit) { return; } if (startXrFrame()) { updateXrViews(); if (frameState.shouldRender) { render(); } endXrFrame(); } } void pollSdlEvents() { SDL_Event event; while (SDL_PollEvent(&event)) { switch (event.type) { case SDL_KEYUP: if (event.key.keysym.sym == SDLK_ESCAPE) { quit = true; } break; } } } void pollXrEvents() { while (true) { xr::EventDataBuffer eventBuffer; auto pollResult = instance.pollEvent(eventBuffer); if (pollResult == xr::Result::EventUnavailable) { break; } switch (eventBuffer.type) { case xr::StructureType::EventDataSessionStateChanged: onSessionStateChanged(reinterpret_cast(eventBuffer)); break; default: break; } } } xr::SessionState sessionState{ xr::SessionState::Idle }; void onSessionStateChanged(const xr::EventDataSessionStateChanged& sessionStateChangedEvent) { sessionState = sessionStateChangedEvent.state; switch (sessionState) { case xr::SessionState::Ready: if (!quit) { session.beginSession(xr::SessionBeginInfo{ xr::ViewConfigurationType::PrimaryStereo }); } break; case xr::SessionState::Stopping: session.endSession(); quit = true; break; default: break; } } xr::FrameState frameState; bool startXrFrame() { switch (sessionState) { case xr::SessionState::Ready: case xr::SessionState::Focused: case xr::SessionState::Synchronized: case xr::SessionState::Visible: session.waitFrame(xr::FrameWaitInfo{}, frameState); return xr::Result::Success == session.beginFrame(xr::FrameBeginInfo{}); default: break; } return false; } void endXrFrame() { xr::FrameEndInfo frameEndInfo{ frameState.predictedDisplayTime, xr::EnvironmentBlendMode::Opaque, 0 , nullptr}; if (frameState.shouldRender) { xr::for_each_side_index([&](uint32_t eyeIndex) { auto& layerView = projectionLayerViews[eyeIndex]; const auto& eyeView = eyeViewStates[eyeIndex]; layerView.fov = eyeView.fov; layerView.pose = eyeView.pose; }); frameEndInfo.layerCount = (uint32_t)layersPointers.size(); frameEndInfo.layers = layersPointers.data(); } session.endFrame(frameEndInfo); } std::vector eyeViewStates; void updateXrViews() { xr::ViewState vs; xr::ViewLocateInfo vi{ xr::ViewConfigurationType::PrimaryStereo, frameState.predictedDisplayTime, space }; eyeViewStates = session.locateViewsToVector(vi, &(vs.operator XrViewState&())); } void render() { uint32_t swapchainIndex; swapchain.acquireSwapchainImage(xr::SwapchainImageAcquireInfo{}, &swapchainIndex); swapchain.waitSwapchainImage(xr::SwapchainImageWaitInfo{ xr::Duration::infinite() }); glBindFramebuffer(GL_FRAMEBUFFER, fbo.id); glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, swapchainImages[swapchainIndex].image, 0); // "render" to the swapchain image glEnable(GL_SCISSOR_TEST); glScissor(0, 0, renderTargetSize[0] / 2, renderTargetSize[1]); glClearColor(0, 1, 0, 1); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glScissor(renderTargetSize[0] / 2, 0, renderTargetSize[0] / 2, renderTargetSize[1]); glClearColor(0, 0, 1, 1); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // fast blit from the fbo to the window surface glDisable(GL_SCISSOR_TEST); glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); glBlitFramebuffer(0, 0, renderTargetSize[0], renderTargetSize[1], 0, 0, windowSize[0], windowSize[1], GL_COLOR_BUFFER_BIT, GL_NEAREST); glFramebufferTexture(GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, 0, 0); glBindFramebuffer(GL_READ_FRAMEBUFFER, 0); swapchain.releaseSwapchainImage(xr::SwapchainImageReleaseInfo{}); SDL_GL_SwapWindow(window); } ////////////////////////////////////// // Shutdown // ////////////////////////////////////// void destroy() { if (fbo.id != 0) { glDeleteFramebuffers(1, &fbo.id); fbo.id = 0; } if (fbo.depthBuffer != 0) { glDeleteRenderbuffers(1, &fbo.depthBuffer); fbo.depthBuffer = 0; } if (swapchain) { swapchain.destroy(); swapchain = nullptr; } if (session) { session.destroy(); session = nullptr; } SDL_GL_DeleteContext(context); SDL_DestroyWindow(window); if (messenger) { messenger.destroy(dispatch); } if (instance) { instance.destroy(); instance = nullptr; } SDL_Quit(); } }; int main(int argc, char* argv[]) { try { OpenXrExample().run(); } catch (const std::exception& err) { logging::log(logging::Level::Error, err.what()); } return 0; } /* * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or * its licensors. * * For complete copyright and license terms please see the LICENSE at the root of this * distribution (the "License"). All use of this software is governed by the License, * or, if provided, by the license below or the license accompanying this file. Do not * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * */ // Original file Copyright Crytek GMBH or its affiliates, used under license. // Description : Places Environment on terrain. #include "StdAfx.h" #include "EnvironmentTool.h" #include "EnvironmentPanel.h" #include "MainWindow.h" ////////////////////////////////////////////////////////////////////////// CEnvironmentTool::CEnvironmentTool() { SetStatusText(tr("Click Apply to accept changes")); m_panelId = 0; m_panel = 0; } ////////////////////////////////////////////////////////////////////////// CEnvironmentTool::~CEnvironmentTool() { } ////////////////////////////////////////////////////////////////////////// void CEnvironmentTool::BeginEditParams(IEditor* ie, int flags) { m_ie = ie; if (!m_panelId) { m_panel = new CEnvironmentPanel; m_panelId = m_ie->AddRollUpPage(ROLLUP_TERRAIN, "Environment", m_panel); MainWindow::instance()->setFocus(); } } ////////////////////////////////////////////////////////////////////////// void CEnvironmentTool::EndEditParams() { if (m_panelId) { m_ie->RemoveRollUpPage(ROLLUP_TERRAIN, m_panelId); m_panel = 0; } } #include JaapDanielse/VirtualPanel /* VirtualPanel.cpp MIT Licence - Copyright (c) 2019 - https://github.com/JaapDanielse/VirtualPanel VirtualPanel is a small libray implementing the comunication from an Arduino to VirtualPanel.exe on a PC. This library uses the ArduinoPort library as communications protocol. V1.2.0 19-7-2020 */ #include "VirtualPanel.h" VirtualPanel Panel(PanelCallback); // instantiation of the Panel object vpsrq_Stats PanelSrqStatus = vpsrq_Success; // Synchronous request handling bool PanelSyncRequest(int event) { static bool SyncBusy = false; unsigned long SyncTimeout = 0; if(SyncBusy) { PanelSrqStatus = vpsrq_ConcurrencyErr; // ConcurrencyErr return false; } for (uint16_t i=0; i < sizeof(vpsrq_Channels)/2; i++) { if(event == vpsrq_Channels[i]) { SyncBusy = true; Panel.send(event); SyncTimeout = millis() + 100; while(SyncTimeout > millis()) { if(Panel.receive(event)) { SyncBusy = false; PanelSrqStatus = vpsrq_Success; // Succes! return true; } } SyncBusy = false; PanelSrqStatus = vpsrq_Timeout; // error Timeout return false; } } PanelSrqStatus = vpsrq_InvalidChannel; // error not a SyncRequest event return false; } // _Line Graph draw helper function. Packs four bytes into a uint32_t. uint32_t _Line( uint8_t xs, uint8_t ys, uint8_t xe, uint8_t ye) { uint32_t linepoints; linepoints = ye; linepoints += (uint32_t)xe << 8 ; linepoints += (uint32_t)ys << 16 ; linepoints += (uint32_t)xs << 24 ; return(linepoints); } uint32_t _VLine( uint8_t xs, uint8_t ys, uint8_t xe, uint8_t ye) { uint32_t linepoints; ye = map(ye,0,255,0,220); ys = map(ys,0,255,0,220); linepoints = ye; linepoints += (uint32_t)xe << 8 ; linepoints += (uint32_t)ys << 16 ; linepoints += (uint32_t)xs << 24 ; return(linepoints); } // _Point Graph draw helper funtion. Packs two bytes into a uint16_t. uint16_t _Point( uint8_t x, uint8_t y) { uint16_t point; point = y; point += (uint16_t)x << 8 ; return(point); } // _Point Graph draw helper funtion. Packs two bytes into a uint16_t. uint16_t _VPoint( uint8_t x, uint8_t y) { uint16_t point; point = map(y,0,255,0,220); point += (uint16_t)x << 8 ; return(point); } // _Circle Graph draw helper function. Packs centre point (2xbyte) and radius (int16) into string. char * _Circle( uint8_t x, uint8_t y, uint8_t rad) { return (_Circle(x,y,rad, (uint16_t)0, (uint16_t)360)); } // _Circle Graph draw helper function. Packs centre point (2xbyte), radius, start angle and arc (int16) into string. char * _Circle( uint8_t x, uint8_t y, uint8_t rad, uint16_t angle, uint16_t arc) { static char circleparams[17]; if (arc <= (uint16_t)360) sprintf(circleparams, "$$%02X%02X%02X%04X%04X", x, y, rad, angle%(uint16_t)360, arc); return(circleparams); } char * _VCircle( uint8_t x, uint8_t y, uint8_t rad) { uint8_t Vy = map(y,0,255,0,220); return (_Circle(x,Vy,rad, (uint16_t)0, (uint16_t)360)); } char * _VCircle( uint8_t x, uint8_t y, uint8_t rad, uint16_t angle, uint16_t arc) { uint8_t Vy = map(y,0,255,0,220); return (_Circle(x,Vy,rad, angle, arc)); } // _Line Graph draw helper function. Packs four bytes into a uint32_t. uint32_t _Sound( uint16_t frequency, uint16_t duration) { uint32_t BeepParam; BeepParam = duration; BeepParam += (uint32_t)frequency << 16 ; return(BeepParam); } #ifndef ARDUINO_ARCH_SAM // _FString - dtostrf wrapper for use in sendf. char * _FString(float FloatValue, int16_t StringSize, int16_t Decimals) { static char FloatString[11]; return(_FString(FloatValue, StringSize, Decimals, FloatString)); } // _FString - dtostrf wrapper for use in sendf. char * _FString(float FloatValue, int16_t StringSize, int16_t Decimals, char * ReturnBuffer) { dtostrf(FloatValue, StringSize, Decimals, ReturnBuffer); int i=0; while (ReturnBuffer[i]==' ') ReturnBuffer[i++]='0'; return(ReturnBuffer); } #endif tools/ifaceed/ifaceed/gui/uiblocks/uiconsoleblock.cpp #include #include #include "uiconsoleblock.h" #include #include #include "../gui/codeedit/codeedit.h" gui::uiblocks::UIConsoleBlock::UIConsoleBlock() : txtConsoleCode(nullptr), btnConsoleRun(nullptr), txtConsoleResults(nullptr), btnConsoleHelp(nullptr), btnConsoleSave(nullptr), btnConsoleLoad(nullptr) { } void gui::uiblocks::UIConsoleBlock::init(QWidget* w) { assert(w); this->txtConsoleCode = w->findChild("txtConsoleCode"); assert(this->txtConsoleCode); this->btnConsoleRun = w->findChild("btnConsoleRun"); assert(this->btnConsoleRun); this->txtConsoleResults = w->findChild("txtConsoleResults"); assert(this->txtConsoleResults); this->btnConsoleHelp = w->findChild("btnConsoleHelp"); assert(this->btnConsoleHelp); this->btnConsoleSave = w->findChild("btnConsoleSave"); assert(this->btnConsoleSave); this->btnConsoleLoad = w->findChild("btnConsoleLoad"); assert(this->btnConsoleLoad); } gui::uiblocks::UIConsoleBlock::~UIConsoleBlock() { } #ifndef JEB_MATH_COMPARISONS_HPP #define JEB_MATH_COMPARISONS_HPP #include #include #include "Constants.hpp" namespace JEBMath { template bool equal(T a, T b, T tolerance) { return std::abs(a - b) <= tolerance; } template <> inline bool equal(double a, double b, double tolerance) { return std::fabs(a - b) <= tolerance; } template <> inline bool equal(float a, float b, float tolerance) { return std::fabs(a - b) <= tolerance; } template bool equal(T a, T b) { return a == b; } template <> inline bool equal(double a, double b) { return equal(a, b, DoubleTolerance); } template bool less(T a, T b, T tolerance) { return a < b - tolerance; } template bool lessOrEqual(T a, T b, T tolerance) { return a <= b + tolerance; } template bool greater(T a, T b, T tolerance) { return a > b + tolerance; } template bool greaterOrEqual(T a, T b, T tolerance) { return a >= b - tolerance; } template bool between(T from, T value, T to, T tolerance) { return greater(value, from, tolerance) && less(value, to, tolerance); } template bool inRange(T from, T value, T to, T tolerance) { return greaterOrEqual(value, from, tolerance) && lessOrEqual(value, to, tolerance); } } #endif 1-10 // // Created by PinkySmile on 11/05/2021. // #ifndef SOKULIB_USER32_DLL_HPP #define SOKULIB_USER32_DLL_HPP #include namespace SokuLib::DLL { struct DLLUSER32 { int (__cdecl *wsprintfA)(LPSTR param_1, LPCSTR param_2, ...); BOOL (__stdcall *UpdateWindow)(HWND hWnd); BOOL (__stdcall *ShowWindow)(HWND hWnd, int nCmdShow); HWND (__stdcall *CreateWindowExA)(DWORD dwExStyle, LPCSTR lpClassName, LPCSTR lpWindowName, DWORD dwStyle, int X, int Y, int nWidth, int nHeight, HWND hWndParent, HMENU hMenu, HINSTANCE hInstance, LPVOID lpParam); ATOM (__stdcall *RegisterClassExA)(WNDCLASSEXA * param_1); HCURSOR (__stdcall *LoadCursorA)(HINSTANCE hInstance, LPCSTR lpCursorName); int (__stdcall *LoadStringA)(HINSTANCE hInstance, UINT uID, LPSTR lpBuffer, int cchBufferMax); BOOL (__stdcall *SetWindowPos)(HWND hWnd, HWND hWndInsertAfter, int X, int Y, int cx, int cy, UINT uFlags); BOOL (__stdcall *GetWindowInfo)(HWND hwnd, PWINDOWINFO pwi); LONG (__stdcall *GetWindowLongA)(HWND hWnd, int nIndex); HDC (__stdcall *GetDC)(HWND hWnd); int (__stdcall *ReleaseDC)(HWND hWnd, HDC hDC); int (__stdcall *ToAscii)(UINT uVirtKey, UINT uScanCode, BYTE * lpKeyState, LPWORD lpChar, UINT uFlags); BOOL (__stdcall *GetWindowRect)(HWND hWnd, LPRECT lpRect); HANDLE (__stdcall *GetClipboardData)(UINT uFormat); BOOL (__stdcall *CloseClipboard)(void); BOOL (__stdcall *OpenClipboard)(HWND hWndNewOwner); BOOL (__stdcall *GetMessageA)(LPMSG lpMsg, HWND hWnd, UINT wMsgFilterMin, UINT wMsgFilterMax); int (__stdcall *ShowCursor)(BOOL bShow); BOOL (__stdcall *SetWindowTextA)(HWND hWnd, LPCSTR lpString); BOOL (__stdcall *PeekMessageA)(LPMSG lpMsg, HWND hWnd, UINT wMsgFilterMin, UINT wMsgFilterMax, UINT wRemoveMsg); LRESULT (__stdcall *DefWindowProcA)(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam); LRESULT (__stdcall *DispatchMessageA)(MSG * lpMsg); void (__stdcall *PostQuitMessage)(int nExitCode); BOOL (__stdcall *TranslateMessage)(MSG * lpMsg); HANDLE (__stdcall *LoadImageA)(HINSTANCE hInst, LPCSTR name, UINT type, int cx, int cy, UINT fuLoad); HICON (__stdcall *LoadIconA)(HINSTANCE hInstance, LPCSTR lpIconName); int (__stdcall *GetSystemMetrics)(int nIndex); LRESULT (__stdcall *SendMessageA)(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam); BOOL (__stdcall *SetRect)(LPRECT lprc, int xLeft, int yTop, int xRight, int yBottom); int (__stdcall *MessageBoxA)(HWND hWnd, LPCSTR lpText, LPCSTR lpCaption, UINT uType); }; extern DLLUSER32 &user32; } #endif //SOKULIB_USER32_DLL_HPP #include namespace prf { inline namespace plugins { class BiasPlugin : public PluginBase { public: BiasPlugin(); ~BiasPlugin(); int init() override; std::string name() override; std::string brief() override; std::string help() override; bool has_update(std::string nm) const override; bool has_energy_term(std::string nm) const override; prf::Update* get_new_update(std::string nm) override; prf::Energy* get_new_energy_term(std::string nm) override; }; } } #include using namespace std; // String Inputs int main() { /* char s[20]; cout << "Will only take one word of less than 19 characters : "; cin >> s; cout << s << endl; */ char str[50]; cout << sizeof(string); cout << "Will take a sentence of less than 49 characters : "; // cin.getline(char_arr, max_element) cin.getline(str, 50); cout << str << endl; // or cin.get(str, 50) // Browse problem with get() function return 0; }lib/webserver/outgoinghttpmessage.cpp1-10 // Embedded web-server library // // Copyright 2010 LibWebserver Authors. All rights reserved. #include "outgoinghttpmessage.h" #include namespace webserver { tbb::atomic OutgoingHttpMessage::header_reservation_; OutgoingHttpMessage::OutgoingHttpMessage(const clocks::HiResTimer* timer) : method_(webserver::RESPONSE) , response_code_(webserver::HTTP_OK) , data_len_(0) , len_(0) , data_(0) , message_(0) , timer_(0) { header_.reserve(header_reservation_); if (timer) { timer_ = (new clocks::HiResTimer(*timer)); } } OutgoingHttpMessage::OutgoingHttpMessage(const clocks::HiResTimer& timer) : method_(webserver::RESPONSE) , response_code_(webserver::HTTP_OK) , data_len_(0) , len_(0) , data_(0) , message_(0) , timer_(new clocks::HiResTimer(timer)) { header_.reserve(header_reservation_); } OutgoingHttpMessage::OutgoingHttpMessage() : method_(webserver::RESPONSE) , response_code_(webserver::HTTP_OK) , data_len_(0) , len_(0) , data_(0) , message_(0) , timer_(0) { header_.reserve(header_reservation_); } OutgoingHttpMessage::~OutgoingHttpMessage() { if (timer_) { delete timer_; } if (message_) { delete[] message_; } if (data_) { delete[] data_; } } void OutgoingHttpMessage::Serialize() { size_t pos = 0; if (method_ == GET) { len_ = uri_.length() + header_.length() + data_len_ + 19; message_ = new char[len_]; ::memcpy(message_, "GET ", 4); pos += 4; ::memcpy(message_ + pos, uri_.c_str(), uri_.length()); pos += uri_.length(); ::memcpy(message_ + pos, "?", 1); pos += 1; ::memcpy(message_ + pos, data_, data_len_); pos += data_len_; ::memcpy(message_ + pos, " HTTP/1.1\r\n", 11); pos += 11; ::memcpy(message_ + pos, header_.c_str(), header_.length()); pos += header_.length(); ::memcpy(message_ + pos, "\r\n", 2); pos += 2; } else if (method_ == POST) { header_.append("Content-Length: "); header_.append(base::ToString(data_len_)); header_.append("\r\n"); len_ = uri_.length() + header_.length() + data_len_ + 19; message_ = new char[len_]; ::memcpy(message_, "POST ", 5); pos += 5; ::memcpy(message_ + pos, uri_.c_str(), uri_.length()); pos += uri_.length(); ::memcpy(message_ + pos, " HTTP/1.1\r\n", 11); pos += 11; ::memcpy(message_ + pos, header_.c_str(), header_.length()); pos += header_.length(); ::memcpy(message_ + pos, "\r\n", 2); pos += 2; ::memcpy(message_ + pos, data_, data_len_); pos += data_len_; } // method_ == RESPONSE else { if (response_code_ == HTTP_OK && data_len_ == 0) { response_code_ = HTTP_NO_CONTENT; } else { header_.append("Content-Length: "); header_.append(base::ToString(data_len_)); header_.append("\r\n"); } len_ = HTTP_CODES_LENGTH[response_code_] + header_.length() + data_len_ + 14; message_ = new char[len_]; ::memcpy(message_, "HTTP/1.1 ", 9); pos += 9; ::memcpy(message_ + pos, HTTP_CODES[response_code_][HTTP_MESSAGE], HTTP_CODES_LENGTH[response_code_]); pos += HTTP_CODES_LENGTH[response_code_]; ::memcpy(message_ + pos, "\r\n", 2); pos += 2; ::memcpy(message_ + pos, header_.c_str(), header_.length()); pos += header_.length(); ::memcpy(message_ + pos, "\r\n", 2); pos += 2; ::memcpy(message_ + pos, data_, data_len_); pos += data_len_; } message_[pos] = 0; UpdateReservation_(header_.length()); } const char* OutgoingHttpMessage::GetSerializedMessage() const { return message_; } size_t OutgoingHttpMessage::GetLength() const { return len_ - 1; } void OutgoingHttpMessage::SetPersistence(const bool is_persistent) { OutgoingMessage::SetPersistence(is_persistent); if (is_persistent) { header_.append("Connection: keep-alive\r\n"); } else { header_.append("Connection: close\r\n"); } } HttpCode OutgoingHttpMessage::GetResponseCode() const { return response_code_; } void OutgoingHttpMessage::SetMethod(const HttpMethod method) { method_ = method; } void OutgoingHttpMessage::SetResponseCode(const HttpCode code) { response_code_ = code; } void OutgoingHttpMessage::AddHeader(const char* key, const char* value) { header_.append(key); header_.append(": "); header_.append(value); header_.append("\r\n"); } void OutgoingHttpMessage::SetData(const char* data, const size_t len) { data_ = new char[len]; ::memcpy(data_, data, len); data_len_ = len; } clocks::HiResTimer* OutgoingHttpMessage::GetTimer() const { return timer_; } void OutgoingHttpMessage::UpdateReservation_(const size_t length) { if (length > header_reservation_) { header_reservation_ = length; } } OutgoingHttpMessage::sptr OutgoingHttpMessage::OK(const std::string& request_id, const bool is_persistent, const clocks::HiResTimer* t) { sptr response = sptr(new OutgoingHttpMessage(t)); response->SetMethod(RESPONSE); response->SetResponseCode(HTTP_OK); response->SetPersistence(is_persistent); if (!request_id.empty()) { response->AddHeader("X-Request-Id", request_id.c_str()); } response->SetData(HTTP_CODES[HTTP_OK][HTTP_MESSAGE], HTTP_CODES_LENGTH[HTTP_OK]); return response; } OutgoingHttpMessage::sptr OutgoingHttpMessage::NoContent(const std::string& request_id, const bool is_persistent, const clocks::HiResTimer* t) { sptr response = sptr(new OutgoingHttpMessage(t)); response->SetMethod(RESPONSE); response->SetResponseCode(HTTP_NO_CONTENT); response->SetPersistence(is_persistent); if (!request_id.empty()) { response->AddHeader("X-Request-Id", request_id.c_str()); } response->SetData(HTTP_CODES[HTTP_NO_CONTENT][HTTP_MESSAGE], HTTP_CODES_LENGTH[HTTP_NO_CONTENT]); return response; } OutgoingHttpMessage::sptr OutgoingHttpMessage::BadRequest() { sptr response = sptr(new OutgoingHttpMessage()); response->SetMethod(RESPONSE); response->SetResponseCode(HTTP_BAD_REQUEST); response->SetPersistence(false); response->SetData(HTTP_CODES[HTTP_BAD_REQUEST][HTTP_MESSAGE], HTTP_CODES_LENGTH[HTTP_BAD_REQUEST]); return response; } OutgoingHttpMessage::sptr OutgoingHttpMessage::BadRequest(const std::string& request_id) { sptr response = sptr(new OutgoingHttpMessage()); response->SetMethod(RESPONSE); response->SetResponseCode(HTTP_BAD_REQUEST); response->SetPersistence(false); if (!request_id.empty()) { response->AddHeader("X-Request-Id", request_id.c_str()); } response->SetData(HTTP_CODES[HTTP_BAD_REQUEST][HTTP_MESSAGE], HTTP_CODES_LENGTH[HTTP_BAD_REQUEST]); return response; } OutgoingHttpMessage::sptr OutgoingHttpMessage::Forbidden(const clocks::HiResTimer* t) { sptr response = sptr(new OutgoingHttpMessage(t)); response->SetMethod(RESPONSE); response->SetResponseCode(HTTP_FORBIDDEN); response->SetPersistence(false); response->SetData(HTTP_CODES[HTTP_FORBIDDEN][HTTP_MESSAGE], HTTP_CODES_LENGTH[HTTP_FORBIDDEN]); return response; } OutgoingHttpMessage::sptr OutgoingHttpMessage::Forbidden(const std::string& request_id, const clocks::HiResTimer* t) { sptr response = sptr(new OutgoingHttpMessage(t)); response->SetMethod(RESPONSE); response->SetResponseCode(HTTP_FORBIDDEN); response->SetPersistence(false); if (!request_id.empty()) { response->AddHeader("X-Request-Id", request_id.c_str()); } response->SetData(HTTP_CODES[HTTP_FORBIDDEN][HTTP_MESSAGE], HTTP_CODES_LENGTH[HTTP_FORBIDDEN]); return response; } OutgoingHttpMessage::sptr OutgoingHttpMessage::NotFound(const bool is_persistent, const clocks::HiResTimer* t) { sptr response = sptr(new OutgoingHttpMessage(t)); response->SetMethod(RESPONSE); response->SetResponseCode(HTTP_NOT_FOUND); response->SetPersistence(is_persistent); response->SetData(HTTP_CODES[HTTP_NOT_FOUND][HTTP_MESSAGE], HTTP_CODES_LENGTH[HTTP_NOT_FOUND]); return response; } OutgoingHttpMessage::sptr OutgoingHttpMessage::NotFound(const std::string& content, const bool is_persistent, const clocks::HiResTimer* t) { sptr response = sptr(new OutgoingHttpMessage(t)); response->SetMethod(RESPONSE); response->SetResponseCode(HTTP_NOT_FOUND); response->SetPersistence(is_persistent); if (!content.empty()) { response->SetData(content.c_str(), content.length()); } else { response->SetData(HTTP_CODES[HTTP_NOT_FOUND][HTTP_MESSAGE], HTTP_CODES_LENGTH[HTTP_NOT_FOUND]); } return response; } OutgoingHttpMessage::sptr OutgoingHttpMessage::NotFound(const std::string& request_id, const std::string& content, const bool is_persistent, const clocks::HiResTimer* t) { sptr response = sptr(new OutgoingHttpMessage(t)); response->SetMethod(RESPONSE); response->SetResponseCode(HTTP_NOT_FOUND); response->SetPersistence(is_persistent); if (!request_id.empty()) { response->AddHeader("X-Request-Id", request_id.c_str()); } if (!content.empty()) { response->SetData(content.c_str(), content.length()); } else { response->SetData(HTTP_CODES[HTTP_NOT_FOUND][HTTP_MESSAGE], HTTP_CODES_LENGTH[HTTP_NOT_FOUND]); } return response; } OutgoingHttpMessage::sptr OutgoingHttpMessage::NotAcceptable(const bool is_persistent, const clocks::HiResTimer* t) { sptr response = sptr(new OutgoingHttpMessage(t)); response->SetMethod(RESPONSE); response->SetResponseCode(HTTP_NOT_ACCEPTABLE); response->SetPersistence(is_persistent); response->SetData(HTTP_CODES[HTTP_NOT_ACCEPTABLE][HTTP_MESSAGE], HTTP_CODES_LENGTH[HTTP_NOT_ACCEPTABLE]); return response; } OutgoingHttpMessage::sptr OutgoingHttpMessage::NotAcceptable(const std::string& content, const bool is_persistent, const clocks::HiResTimer* t) { sptr response = sptr(new OutgoingHttpMessage(t)); response->SetMethod(RESPONSE); response->SetResponseCode(HTTP_NOT_ACCEPTABLE); response->SetPersistence(is_persistent); if (!content.empty()) { response->SetData(content.c_str(), content.length()); } else { response->SetData(HTTP_CODES[HTTP_NOT_ACCEPTABLE][HTTP_MESSAGE], HTTP_CODES_LENGTH[HTTP_NOT_ACCEPTABLE]); } return response; } OutgoingHttpMessage::sptr OutgoingHttpMessage::NotAcceptable(const std::string& request_id, const std::string& content, const bool is_persistent, const clocks::HiResTimer* t) { sptr response = sptr(new OutgoingHttpMessage(t)); response->SetMethod(RESPONSE); response->SetResponseCode(HTTP_NOT_ACCEPTABLE); response->SetPersistence(is_persistent); if (!request_id.empty()) { response->AddHeader("X-Request-Id", request_id.c_str()); } if (!content.empty()) { response->SetData(content.c_str(), content.length()); } else { response->SetData(HTTP_CODES[HTTP_NOT_ACCEPTABLE][HTTP_MESSAGE], HTTP_CODES_LENGTH[HTTP_NOT_ACCEPTABLE]); } return response; } OutgoingHttpMessage::sptr OutgoingHttpMessage::RequestTimeout(const std::string& request_id, const bool is_persistent, const clocks::HiResTimer* t) { sptr response = sptr(new OutgoingHttpMessage(t)); response->SetMethod(RESPONSE); response->SetResponseCode(HTTP_TIMEOUT); response->SetPersistence(is_persistent); if (!request_id.empty()) { response->AddHeader("X-Request-Id", request_id.c_str()); } response->SetData(HTTP_CODES[HTTP_TIMEOUT][HTTP_MESSAGE], HTTP_CODES_LENGTH[HTTP_TIMEOUT]); return response; } OutgoingHttpMessage::sptr OutgoingHttpMessage::TooManyConnections(const clocks::HiResTimer* t) { sptr response = sptr(new OutgoingHttpMessage(t)); response->SetMethod(RESPONSE); response->SetResponseCode(HTTP_TOO_MANY_CONNECTIONS); response->SetPersistence(false); response->SetData(HTTP_CODES[HTTP_TOO_MANY_CONNECTIONS][HTTP_MESSAGE], HTTP_CODES_LENGTH[HTTP_TOO_MANY_CONNECTIONS]); return response; } } // namespace webserver 1-10 /* -------------------------------------------------------------------------- * * (C) Copyright … * * --------------------------------------------------------------------------- */ /*! * @file MatVisualPointFeatureVector3DTest.cpp * @date 01/12/2017 * @author */ /*! * @addtogroup CommonTests * * Testing conversion from Mat to VisualPointFeaturesVector3D and viceversa. * * * @{ */ /* -------------------------------------------------------------------------- * * Includes * * -------------------------------------------------------------------------- */ #include #include #include #include #include using namespace Converters; using namespace VisualPointFeatureVector3DWrapper; TEST_CASE( "Mat to VisualPointFeatureVector3D", "[MatToVisualPointFeatureVector3D]" ) { MatToVisualPointFeatureVector3DConverter firstConverter; VisualPointFeatureVector3DToMatConverter secondConverter; cv::Mat inputMatrix(100, 5, CV_32FC1, cv::Scalar(0)); for(int rowIndex = 0; rowIndex < inputMatrix.rows; rowIndex++) { for(int columnIndex = 0; columnIndex < inputMatrix.cols; columnIndex++) { inputMatrix.at(rowIndex, columnIndex) = (float) (rowIndex + columnIndex); } } VisualPointFeatureVector3DSharedConstPtr asnVector = firstConverter.ConvertShared(inputMatrix); REQUIRE(GetNumberOfPoints(*asnVector) == inputMatrix.rows); int descriptorSize = GetNumberOfDescriptorComponents(*asnVector, 0); REQUIRE(descriptorSize == inputMatrix.cols - 3); for(int rowIndex = 0; rowIndex < inputMatrix.rows; rowIndex++) { REQUIRE(GetXCoordinate(*asnVector, rowIndex) == inputMatrix.at(rowIndex, 0) ); REQUIRE(GetYCoordinate(*asnVector, rowIndex) == inputMatrix.at(rowIndex, 1) ); REQUIRE(GetZCoordinate(*asnVector, rowIndex) == inputMatrix.at(rowIndex, 2) ); REQUIRE(descriptorSize == GetNumberOfDescriptorComponents(*asnVector, rowIndex) ); for(int columnIndex = 3; columnIndex < inputMatrix.cols; columnIndex++) { REQUIRE(GetDescriptorComponent(*asnVector, rowIndex, columnIndex-3) == inputMatrix.at(rowIndex, columnIndex) ); } } cv::Mat outputMatrix = secondConverter.ConvertShared(asnVector); REQUIRE(outputMatrix.rows == inputMatrix.rows); REQUIRE(outputMatrix.cols == inputMatrix.cols); REQUIRE(outputMatrix.type() == inputMatrix.type()); for(int rowIndex = 0; rowIndex < inputMatrix.rows; rowIndex++) { for(int columnIndex = 0; columnIndex < inputMatrix.cols; columnIndex++) { REQUIRE(outputMatrix.at(rowIndex, columnIndex) == inputMatrix.at(rowIndex, columnIndex)); } } asnVector.reset(); } TEST_CASE( "VisualPointFeatureVector3D to Mat", "[VisualPointFeatureVector3DToMat]" ) { MatToVisualPointFeatureVector3DConverter firstConverter; VisualPointFeatureVector3DToMatConverter secondConverter; cv::Mat inputMatrix(100, 5, CV_32FC1, cv::Scalar(0)); for(int rowIndex = 0; rowIndex < inputMatrix.rows; rowIndex++) { for(int columnIndex = 0; columnIndex < inputMatrix.cols; columnIndex++) { inputMatrix.at(rowIndex, columnIndex) = (float) (rowIndex + columnIndex); } } VisualPointFeatureVector3DSharedConstPtr asnVector = firstConverter.ConvertShared(inputMatrix); cv::Mat intermediateMatrix = secondConverter.ConvertShared(asnVector); VisualPointFeatureVector3DSharedConstPtr outputVector = firstConverter.ConvertShared(intermediateMatrix); REQUIRE(GetNumberOfPoints(*asnVector) == GetNumberOfPoints(*outputVector)); REQUIRE(GetNumberOfPoints(*asnVector) > 0); int descriptorSize = GetNumberOfDescriptorComponents(*asnVector, 0); for(int pointIndex = 0; pointIndex < GetNumberOfPoints(*asnVector); pointIndex++) { REQUIRE(GetXCoordinate(*asnVector, pointIndex) == GetXCoordinate(*outputVector, pointIndex) ); REQUIRE(GetYCoordinate(*asnVector, pointIndex) == GetYCoordinate(*outputVector, pointIndex) ); REQUIRE(GetZCoordinate(*asnVector, pointIndex) == GetZCoordinate(*outputVector, pointIndex) ); REQUIRE(GetNumberOfDescriptorComponents(*asnVector, pointIndex) == descriptorSize ); REQUIRE(GetNumberOfDescriptorComponents(*outputVector, pointIndex) == descriptorSize ); for(int componentIndex = 0; componentIndex < descriptorSize; componentIndex++) { REQUIRE(GetDescriptorComponent(*asnVector, pointIndex, componentIndex) == GetDescriptorComponent(*outputVector, pointIndex, componentIndex) ); } } asnVector.reset(); outputVector.reset(); } TEST_CASE( "Attempt conversion of a Bad VisualPointFeatureVector3D", "[BadVisualPointFeatureVector3D]") { VisualPointFeatureVector3DSharedPtr asnVector = std::make_shared(); AddPoint(*asnVector, 0, 0, 0); AddDescriptorComponent(*asnVector, 0, 0); AddPoint(*asnVector, 1, 1, 1); AddDescriptorComponent(*asnVector, 1, 1); AddDescriptorComponent(*asnVector, 1, 2); VisualPointFeatureVector3DToMatConverter converter; REQUIRE_THROWS_AS( converter.ConvertShared(asnVector), AssertException); asnVector.reset(); } TEST_CASE( "3D points with empty descriptors", "[EmptyDescriptors3D]") { MatToVisualPointFeatureVector3DConverter firstConverter; VisualPointFeatureVector3DToMatConverter secondConverter; cv::Mat inputMatrix(100, 3, CV_32FC1, cv::Scalar(0)); for(int rowIndex = 0; rowIndex < inputMatrix.rows; rowIndex++) { for(int columnIndex = 0; columnIndex < inputMatrix.cols; columnIndex++) { inputMatrix.at(rowIndex, columnIndex) = (float) (rowIndex + columnIndex); } } VisualPointFeatureVector3DSharedConstPtr asnVector = firstConverter.ConvertShared(inputMatrix); cv::Mat outputMatrix = secondConverter.ConvertShared(asnVector); REQUIRE(outputMatrix.rows == inputMatrix.rows); REQUIRE(outputMatrix.cols == inputMatrix.cols); REQUIRE(outputMatrix.type() == inputMatrix.type()); for(int rowIndex = 0; rowIndex < inputMatrix.rows; rowIndex++) { for(int columnIndex = 0; columnIndex < inputMatrix.cols; columnIndex++) { REQUIRE(outputMatrix.at(rowIndex, columnIndex) == inputMatrix.at(rowIndex, columnIndex)); } } asnVector.reset(); } TEST_CASE("Empty Features Vector 3D", "[EmptyFeaturesVector3D]") { MatToVisualPointFeatureVector3DConverter firstConverter; VisualPointFeatureVector3DToMatConverter secondConverter; cv::Mat inputMatrix; VisualPointFeatureVector3DSharedConstPtr asnVector = firstConverter.ConvertShared(inputMatrix); cv::Mat outputMatrix = secondConverter.ConvertShared(asnVector); REQUIRE(outputMatrix.cols == 0); REQUIRE(outputMatrix.rows == 0); asnVector.reset(); } TEST_CASE("Reference Features Conversion", "[ReferenceFeaturesConversion]") { VisualPointFeatureVector3DToMatConverter converter; VisualPointFeatureVector3DPtr featuresVector = NewVisualPointFeatureVector3D(); AddPoint(*featuresVector, 10, 0); REQUIRE(GetPointType(*featuresVector, 0) == VISUAL_POINT_REFERENCE); REQUIRE(GetVectorType(*featuresVector) == ALL_REFERENCES_VECTOR ); REQUIRE_THROWS( converter.Convert(featuresVector) ); delete(featuresVector); } TEST_CASE("Hybrid Features Conversion", "[HybridFeaturesConversion]") { VisualPointFeatureVector3DToMatConverter converter; VisualPointFeatureVector3DPtr featuresVector = NewVisualPointFeatureVector3D(); AddPoint(*featuresVector, 10, 0); AddPoint(*featuresVector, 1.00, 2.10, 3.00); REQUIRE(GetPointType(*featuresVector, 0) == VISUAL_POINT_REFERENCE); REQUIRE(GetPointType(*featuresVector, 1) == VISUAL_POINT_POSITION); REQUIRE(GetVectorType(*featuresVector) == HYBRID_VECTOR); REQUIRE_THROWS( converter.Convert(featuresVector) ); delete(featuresVector); } /*************************************************************************** * Copyright (C) 2008-2021 by * * * * * * 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 St, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #include #include "curses/menu_impl.h" #include "screens/browser.h" #include "charset.h" #include "display.h" #include "format_impl.h" #include "helpers.h" #include "screens/song_info.h" #include "screens/playlist.h" #include "global.h" #include "screens/tag_editor.h" #include "utility/string.h" #include "utility/type_conversions.h" using Global::myScreen; namespace { const wchar_t *toColumnName(char c) { switch (c) { case 'l': return L"Time"; case 'f': return L"Filename"; case 'D': return L"Directory"; case 'a': return L"Artist"; case 'A': return L"Album Artist"; case 't': return L"Title"; case 'b': return L"Album"; case 'y': return L"Date"; case 'n': case 'N': return L"Track"; case 'g': return L"Genre"; case 'c': return L"Composer"; case 'p': return L"Performer"; case 'd': return L"Disc"; case 'C': return L"Comment"; case 'P': return L"Priority"; default: return L"?"; } } template void setProperties(NC::Menu &menu, const MPD::Song &s, const SongList &list, bool &separate_albums, bool &is_now_playing, bool &is_selected, bool &is_in_playlist, bool &discard_colors) { size_t drawn_pos = menu.drawn() - menu.begin(); separate_albums = false; if (Config.playlist_separate_albums) { auto next = list.beginS() + drawn_pos + 1; if (next != list.endS()) { if (next->song() != nullptr) { // Draw a separator when the next album is different than the current // one. In case there are two albums with the same name, but a different // album artist, compare also album artists. separate_albums = next->song()->getAlbum() != s.getAlbum() || next->song()->getAlbumArtist() != s.getAlbumArtist(); } } } if (separate_albums) { menu << NC::Format::Underline; mvwhline(menu.raw(), menu.getY(), 0, NC::Key::Space, menu.getWidth()); } int song_pos = s.getPosition(); is_now_playing = Status::State::player() != MPD::psStop && myPlaylist->isActiveWindow(menu) && song_pos == Status::State::currentSongPosition(); if (is_now_playing) menu << Config.now_playing_prefix; is_in_playlist = !myPlaylist->isActiveWindow(menu) && myPlaylist->checkForSong(s); if (is_in_playlist) menu << NC::Format::Bold; is_selected = menu.drawn()->isSelected(); discard_colors = Config.discard_colors_if_item_is_selected && is_selected; } template void unsetProperties(NC::Menu &menu, bool separate_albums, bool is_now_playing, bool is_in_playlist) { if (is_in_playlist) menu << NC::Format::NoBold; if (is_now_playing) menu << Config.now_playing_suffix; if (separate_albums) menu << NC::Format::NoUnderline; } template void showSongs(NC::Menu &menu, const MPD::Song &s, const SongList &list, const Format::AST &ast) { bool separate_albums, is_now_playing, is_selected, is_in_playlist, discard_colors; setProperties(menu, s, list, separate_albums, is_now_playing, is_selected, is_in_playlist, discard_colors); const size_t y = menu.getY(); NC::Buffer right_aligned; Format::print(ast, menu, &s, &right_aligned, discard_colors ? Format::Flags::Tag | Format::Flags::OutputSwitch : Format::Flags::All ); if (!right_aligned.str().empty()) { size_t x_off = menu.getWidth() - wideLength(ToWString(right_aligned.str())); if (menu.isHighlighted() && list.currentS()->song() == &s) { if (menu.highlightSuffix() == Config.current_item_suffix) x_off -= Config.current_item_suffix_length; else x_off -= Config.current_item_inactive_column_suffix_length; } if (is_now_playing) x_off -= Config.now_playing_suffix_length; if (is_selected) x_off -= Config.selected_item_suffix_length; menu << NC::TermManip::ClearToEOL << NC::XY(x_off, y) << right_aligned; } unsetProperties(menu, separate_albums, is_now_playing, is_in_playlist); } template void showSongsInColumns(NC::Menu &menu, const MPD::Song &s, const SongList &list) { if (Config.columns.empty()) return; bool separate_albums, is_now_playing, is_selected, is_in_playlist, discard_colors; setProperties(menu, s, list, separate_albums, is_now_playing, is_selected, is_in_playlist, discard_colors); int menu_width = menu.getWidth(); if (menu.isHighlighted() && list.currentS()->song() == &s) { if (menu.highlightPrefix() == Config.current_item_prefix) menu_width -= Config.current_item_prefix_length; else menu_width -= Config.current_item_inactive_column_prefix_length; if (menu.highlightSuffix() == Config.current_item_suffix) menu_width -= Config.current_item_suffix_length; else menu_width -= Config.current_item_inactive_column_suffix_length; } if (is_now_playing) { menu_width -= Config.now_playing_prefix_length; menu_width -= Config.now_playing_suffix_length; } if (is_selected) { menu_width -= Config.selected_item_prefix_length; menu_width -= Config.selected_item_suffix_length; } int width; int y = menu.getY(); int remained_width = menu_width; std::vector::const_iterator it, last = Config.columns.end() - 1; for (it = Config.columns.begin(); it != Config.columns.end(); ++it) { // check current X coordinate int x = menu.getX(); // column has relative width and all after it have fixed width, // so stretch it so it fills whole screen along with these after. if (it->stretch_limit >= 0) // (*) width = remained_width - it->stretch_limit; else width = it->fixed ? it->width : it->width * menu_width * 0.01; // columns with relative width may shrink to 0, omit them if (width == 0) continue; // if column is not last, we need to have spacing between it // and next column, so we substract it now and restore later. if (it != last) --width; // if column doesn't fit into screen, discard it and any other after it. if (remained_width-width < 0 || width < 0 /* this one may come from (*) */) break; std::wstring tag; for (size_t i = 0; i < it->type.length(); ++i) { MPD::Song::GetFunction get = charToGetFunction(it->type[i]); assert(get); tag = ToWString(Charset::utf8ToLocale(s.getTags(get))); if (!tag.empty()) break; } if (tag.empty() && it->display_empty_tag) tag = ToWString(Config.empty_tag); wideCut(tag, width); if (!discard_colors && it->color != NC::Color::Default) menu << it->color; int x_off = 0; // if column uses right alignment, calculate proper offset. // otherwise just assume offset is 0, ie. we start from the left. if (it->right_alignment) x_off = std::max(0, width - int(wideLength(tag))); whline(menu.raw(), NC::Key::Space, width); menu.goToXY(x + x_off, y); menu << tag; menu.goToXY(x + width, y); if (it != last) { // add missing width's part and restore the value. menu << ' '; remained_width -= width+1; } if (!discard_colors && it->color != NC::Color::Default) menu << NC::Color::End; } unsetProperties(menu, separate_albums, is_now_playing, is_in_playlist); } } std::string Display::Columns(size_t list_width) { std::string result; if (Config.columns.empty()) return result; int width; int remained_width = list_width; std::vector::const_iterator it, last = Config.columns.end() - 1; for (it = Config.columns.begin(); it != Config.columns.end(); ++it) { // column has relative width and all after it have fixed width, // so stretch it so it fills whole screen along with these after. if (it->stretch_limit >= 0) // (*) width = remained_width - it->stretch_limit; else width = it->fixed ? it->width : it->width * list_width * 0.01; // columns with relative width may shrink to 0, omit them if (width == 0) continue; // if column is not last, we need to have spacing between it // and next column, so we substract it now and restore later. if (it != last) --width; // if column doesn't fit into screen, discard it and any other after it. if (remained_width-width < 0 || width < 0 /* this one may come from (*) */) break; std::wstring name; if (it->name.empty()) { size_t j = 0; while (true) { name += toColumnName(it->type[j]); ++j; if (j < it->type.length()) name += '/'; else break; } } else name = it->name; wideCut(name, width); int x_off = std::max(0, width - int(wideLength(name))); if (it->right_alignment) { result += std::string(x_off, NC::Key::Space); result += Charset::utf8ToLocale(ToString(name)); } else { result += Charset::utf8ToLocale(ToString(name)); result += std::string(x_off, NC::Key::Space); } if (it != last) { // add missing width's part and restore the value. remained_width -= width+1; result += ' '; } } return result; } void Display::SongsInColumns(NC::Menu &menu, const SongList &list) { showSongsInColumns(menu, menu.drawn()->value(), list); } void Display::Songs(NC::Menu &menu, const SongList &list, const Format::AST &ast) { showSongs(menu, menu.drawn()->value(), list, ast); } #ifdef HAVE_TAGLIB_H void Display::Tags(NC::Menu &menu) { const MPD::MutableSong &s = menu.drawn()->value(); if (s.isModified()) menu << Config.modified_item_prefix; size_t i = myTagEditor->TagTypes->choice(); if (i < 11) { ShowTag(menu, Charset::utf8ToLocale(s.getTags(SongInfo::Tags[i].Get))); } else if (i == 12) { if (s.getNewName().empty()) menu << Charset::utf8ToLocale(s.getName()); else menu << Charset::utf8ToLocale(s.getName()) << Config.color2 << " -> " << NC::FormattedColor::End<>(Config.color2) << Charset::utf8ToLocale(s.getNewName()); } } #endif // HAVE_TAGLIB_H void Display::Items(NC::Menu &menu, const SongList &list) { const MPD::Item &item = menu.drawn()->value(); switch (item.type()) { case MPD::Item::Type::Directory: menu << "[" << Charset::utf8ToLocale(getBasename(item.directory().path())) << "]"; break; case MPD::Item::Type::Song: switch (Config.browser_display_mode) { case DisplayMode::Classic: showSongs(menu, item.song(), list, Config.song_list_format); break; case DisplayMode::Columns: showSongsInColumns(menu, item.song(), list); break; } break; case MPD::Item::Type::Playlist: menu << Config.browser_playlist_prefix << Charset::utf8ToLocale(getBasename(item.playlist().path())); break; } } void Display::SEItems(NC::Menu &menu, const SongList &list) { const SEItem &si = menu.drawn()->value(); if (si.isSong()) { switch (Config.search_engine_display_mode) { case DisplayMode::Classic: showSongs(menu, si.song(), list, Config.song_list_format); break; case DisplayMode::Columns: showSongsInColumns(menu, si.song(), list); break; } } else menu << si.buffer(); } #ifdef SHDRFX_SUPPORT #include "shdrfx.hpp" #include "ogm/common/types.hpp" #include "common/sdl.hpp" #include namespace ogm::project::fx { static SDL_Window* g_window; static SDL_Renderer* g_renderer; static SDL_GLContext g_context; static unsigned int VBO; static unsigned int VAO; bool shdrfx_begin() { if ( SDL_Init( SDL_INIT_VIDEO ) != 0 ) { return 1; } #ifdef EMSCRIPTEN SDL_CreateWindowAndRenderer(1, 1, SDL_WINDOW_HIDDEN, &g_window, &g_renderer); #else g_window = SDL_CreateWindow( "opengml compiler", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 1, 1, SDL_WINDOW_OPENGL | SDL_WINDOW_HIDDEN); #endif if (!g_window) { printf("Unable to create SDL window.\n"); return true; } #ifdef EMSCRIPTEN if (!g_renderer) { // TODO: do we care about the renderer? printf("Unable to create SDL renderer.\n"); return true; } SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24); #else SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 8); SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); g_context = SDL_GL_CreateContext(g_window); // init GLEW glewExperimental = GL_TRUE; GLenum result = glewInit(); if (result != GLEW_OK) { std::cerr << "Error (glew): " << glewGetErrorString(result) << std::endl; std::cerr << "could not initialize glew.\n"; return false; } if (!GLEW_VERSION_3_0) { std::cerr << "Error (glew): OpenGL 3.0 not supported.\n"; return true; } #endif // square static const float vertices[] = { -1.0f, -1.0f, 0.0f, 1.0f, -1.0f, 0.0f, 1.0f, 1.0f, 0.0f, -1.0f, 1.0f, 0.0f }; // VBO glGenBuffers(1, &VBO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); // VAO glGenVertexArrays(1, &VAO); glBindVertexArray(VAO); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0); glEnableVertexAttribArray(0); return 0; } void render(const char * vshader, const char* fshader, const uint8_t* data, uint16_t iw, uint16_t ih, uint16_t ow, uint16_t oh) { //glUseProgram(shader_program); glBindVertexArray(VAO); glDrawArrays(GL_TRIANGLES, 0, 4); } void shdrfx_end() { glDeleteVertexArrays(1, &VAO); glDeleteBuffers(1, &VBO); SDL_Quit(); } } #endif/********************************************************************************** Copyright (C) 2012 (www.syedrezaali.com) 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 "ofxUITabBar.h" #include "ofxUI.h" ofxUITabBar::ofxUITabBar() : ofxUICanvas() { initTabBar(); } ofxUITabBar::~ofxUITabBar() { ofRemoveListener(newGUIEvent, this, &ofxUITabBar::mainUiEvent); } ofxUITabBar::ofxUITabBar(float x, float y, float w, float h) : ofxUICanvas(x,y,w,h) { initTabBar(); } void ofxUITabBar::initTabBar() { kind = OFX_UI_WIDGET_TABBAR; autoSizeToFitWidgets(); ofAddListener(newGUIEvent, this, &ofxUITabBar::mainUiEvent); active = NULL; } void ofxUITabBar::addCanvas(ofxUICanvas *_canvas) { ofxUIToggle* newToggle = addToggle(_canvas->getName(), false); canvases.insert ( pair( newToggle, _canvas) ); _canvas->disable(); autoSizeToFitWidgets(); } void ofxUITabBar::addCanvas(ofxUIScrollableCanvas *_canvas) { ofxUIToggle* newToggle = addToggle(_canvas->getName(), false); canvases.insert ( pair( newToggle, _canvas) ); _canvas->disable(); autoSizeToFitWidgets(); } void ofxUITabBar::mainUiEvent(ofxUIEventArgs &event) { string name = event.getName(); for (map::iterator it=canvases.begin(); it!=canvases.end(); ++it) { if(it->second->getName() == name) { active = it->second; it->first->setValue(true); it->second->enable(); } else { it->first->setValue(false); it->second->disable(); } } } void ofxUITabBar::enable() { ofxUICanvas::enable(); if (active != NULL) { active->enable(); } } void ofxUITabBar::disable() { ofxUICanvas::disable(); if (active != NULL) { active->disable(); } } void ofxUITabBar::toggleVisible() { ofxUICanvas::toggleVisible(); if (active != NULL) { active->toggleVisible(); } } ofxUICanvas* ofxUITabBar::getActiveCanvas() { return active; } bool ofxUITabBar::isHit(int x, int y) { if (ofxUICanvas::isHit(x, y)) { return true; } else { if (active != NULL) { return active->isHit(x, y); } } return false; } void ofxUITabBar::saveSettings(string pathToSaveTo, string fileNamePrefix) { for (map::iterator it=canvases.begin(); it!=canvases.end(); ++it) { it->second->saveSettings(pathToSaveTo + fileNamePrefix + it->second->getName() + ".xml"); } } void ofxUITabBar::loadSettings(string pathToLoadFrom, string fileNamePrefix) { for (map::iterator it=canvases.begin(); it!=canvases.end(); ++it) { it->second->loadSettings(pathToLoadFrom + fileNamePrefix + it->second->getName() + ".xml"); } }// //////////////////////////////////////////////////////// // # Title // Champernowne's constant // // # URL // https://projecteuler.net/problem=40 // http://euler.stephan-brumme.com/40/ // // # Problem // An irrational decimal fraction is created by concatenating the positive integers: // // `0.12345678910\red{1}112131415161718192021...` // // It can be seen that the 12th digit of the fractional part is 1. // If `d_n` represents the nth digit of the fractional part, find the value of the following expression. // // `d_1 * d_10 * d_100 * d_1000 * d_10000 * d_100000 * d_1000000` // // # Solved by // // February 2017 // // # Algorithm // The original problem can be solved in a trivial way: // - a ''for''-loop appends numbers to a long string until that string contains enough digits // - read relevant digits, convert them from ASCII to integers and multiply them // // The Hackerrank problem asks for digits at positions up to `2^18` which cannot be done the brute force way // because we would be running out of memory (and CPU time). // // My function ''getDigit'' finds a digit without building such a long string. // It is based on the following observation: // - there are 9 numbers with one digit (1 to 9) // - there are 90 numbers with one digit (10 to 99) // - there are 900 numbers with one digit (100 to 999) // - ... and so on // // The first part of ''getDigit'' figures out how many digits the number has which is pointed to by the parameter ''pos''. // - the first 9 numbers are represented by 1*9 digits in Champernowne's constant // - the next 90 numbers are represented by 2*90=180 digits // - the next 900 numbers are represented by 3*900=2700 digits // - ... and so on: ''range'' will be 9, 90, 900, ... and ''digits'' will be 1, 2, 3, ... // // The variable ''skip'' will contain 9, 9+2*90 = 189, 9+2*90+3*900 = 2890 until the next step would exceed ''pos''. // Now that the function knows how many digit the number (pointed to by ''pos'') has, ''getDigit'' process its digits. // // To do so, it moves ''first'' closer to ''pos'' by repeated adding ''range''. // Whenever ''range'' becomes too large, the next (smaller) digit has to be adjusted until we have the final value of ''first''. // That number is converted to a string and the desired digit returned. #include #include // return the digit at position "pos" // first digit after then decimal dot has pos = 1 (not zero !) unsigned int getDigit(unsigned long long pos) { // assume pos has one digit unsigned int digits = 1; // then there are 9 other numbers unsigned long long range = 9; // the smallest of them is 1 unsigned long long first = 1; // there are 9 numbers with 1 digit // there are 90 numbers with 2 digits // there are 900 numbers with 3 digits // there are 9000 numbers with 4 digits // ... // let's figure out the number of digits // skip numbers with too few digits unsigned long long skip = 0; while (skip + digits*range < pos) { skip += digits*range; // digits = 2 => range = 90 and // digits = 3 => range = 900 // digits = 4 => range = 9000, etc. digits++; range *= 10; first *= 10; } // now that we know the number of digits // adjust "first" and "skip" such that the left-most/highest digit of pos and skip are identical // then continue with the next digit while (range > 9) { // could be replace by some modular arithmetic, but I'm too lazy for tough thinking ;-) while (skip + digits*range < pos) { skip += digits*range; first += range; } // next lower digit range /= 10; } // right-most digit (basically same inner loop as above when range == 1) while (skip + digits < pos) { first++; skip += digits; } // skip all "skippable" digits pos -= skip; // strings are zero-based whereas input is one-based pos--; // create a string version of our number auto s = std::to_string(first); // extract digit and convert from ASCII to an integer return s[pos] - '0'; } int main() { unsigned int tests; std::cin >> tests; while (tests--) { unsigned int product = 1; // read 7 positions for (unsigned int i = 0; i < 7; i++) { unsigned long long pos; std::cin >> pos; // multiply all digits product *= getDigit(pos); } // print result std::cout << product << std::endl; } return 0; } #include "Utility.hpp" #include "llvm/Support/raw_ostream.h" #include using namespace llvm; using namespace std; // Separate namespaces for error-prop and program2vec namespace ep { Location getSource(Instruction *I) { if (I == nullptr) { errs() << "getSource requested for nullptr\n"; abort(); } Location location; DILocation *loc = I->getDebugLoc(); if (loc) { std::string file = loc->getFilename(); unsigned line = loc->getLine(); std::string dir = loc->getDirectory(); location = Location(file, line); } return location; } }; namespace p2v { // Read the list of interesting functions from a file // One function name per line unordered_set read_interesting_functions(string path) { unordered_set ret; ifstream f_functions(path); string line; while (getline(f_functions, line)) { ret.insert(line); } return ret; } // For some functions LLVM will string getName(llvm::Function &F) { string name = F.getName(); auto idx = name.find('.'); if (idx != string::npos) { name = name.substr(0, idx); } return name; } }; #pragma once #include #include #include namespace fc { class variant; } namespace eosio { using chain::bytes; using std::shared_ptr; typedef shared_ptr state_history_ptr; class state_history_plugin : public plugin { public: APPBASE_PLUGIN_REQUIRES((chain_plugin)) state_history_plugin(); virtual ~state_history_plugin(); virtual void set_program_options(options_description& cli, options_description& cfg) override; void plugin_initialize(const variables_map& options); void plugin_startup(); void plugin_shutdown(); private: state_history_ptr my; }; } // namespace eosio // Copyright 1998-2015 Epic Games, Inc. All Rights Reserved. #include "PhATModule.h" #include "PhysicsPublic.h" #include "EditorSupportDelegates.h" #include "ScopedTransaction.h" #include "SPhATNewAssetDlg.h" #include "PhATEdSkeletalMeshComponent.h" #include "PhATSharedData.h" #include "Developer/MeshUtilities/Public/MeshUtilities.h" #include "PhysicsEngine/BodySetup.h" #include "Engine/CollisionProfile.h" #include "PhysicsEngine/PhysicsConstraintTemplate.h" #include "PhysicsEngine/PhysicsHandleComponent.h" #include "Vehicles/WheeledVehicleMovementComponent.h" #include "Engine/StaticMesh.h" #define LOCTEXT_NAMESPACE "PhATShared" FPhATSharedData::FPhATSharedData() : PreviewScene( FPreviewScene::ConstructionValues().ShouldSimulatePhysics(true) ) , COMRenderColor(255,255,100) , CopiedBodySetup(NULL) , CopiedConstraintTemplate(NULL) , bInsideSelChange(false) { // Editor variables BodyEdit_MeshViewMode = PRM_Solid; BodyEdit_CollisionViewMode = PRM_Wireframe; BodyEdit_ConstraintViewMode = PCV_AllPositions; ConstraintEdit_MeshViewMode = PRM_None; ConstraintEdit_CollisionViewMode = PRM_Wireframe; ConstraintEdit_ConstraintViewMode = PCV_AllPositions; Sim_MeshViewMode = PRM_Solid; Sim_CollisionViewMode = PRM_Wireframe; Sim_ConstraintViewMode = PCV_None; EditingMode = PEM_BodyEdit; bShowCOM = false; bShowHierarchy = false; bShowInfluences = false; bDrawGround = true; bShowFixedStatus = true; bShowAnimSkel = false; bSelectionLock = false; bRunningSimulation = false; bNoGravitySimulation = false; bShowInstanceProps = false; bManipulating = false; // Construct mouse handle MouseHandle = NewObject(); // Construct sim options. EditorSimOptions = NewObject(GetTransientPackage(), TEXT("EditorSimOptions")); check(EditorSimOptions); EditorSimOptions->HandleLinearDamping = MouseHandle->LinearDamping; EditorSimOptions->HandleLinearStiffness = MouseHandle->LinearStiffness; EditorSimOptions->HandleAngularDamping = MouseHandle->AngularDamping; EditorSimOptions->HandleAngularStiffness = MouseHandle->AngularStiffness; EditorSimOptions->InterpolationSpeed = MouseHandle->InterpolationSpeed; // when record simulation, we'd like to record local to world change Recorder.bRecordLocalToWorld = true; } FPhATSharedData::~FPhATSharedData() { } void FPhATSharedData::Initialize() { EditorSkelComp = NULL; USkeletalMesh * PreviewMesh = NULL; FStringAssetReference PreviewMeshStringRef = PhysicsAsset->PreviewSkeletalMesh.ToStringReference(); // load it since now is the time to load if (!PreviewMeshStringRef.ToString().IsEmpty()) { PreviewMesh = Cast(StaticLoadObject(USkeletalMesh::StaticClass(), NULL, *PreviewMeshStringRef.ToString(), NULL, LOAD_None, NULL)); } if ( PreviewMesh == NULL) { // Fall back to the default skeletal mesh in the EngineMeshes package. // This is statically loaded as the package is likely not fully loaded // (otherwise, it would have been found in the above iteration). PreviewMesh = (USkeletalMesh*)StaticLoadObject( USkeletalMesh::StaticClass(), NULL, TEXT("/Engine/EngineMeshes/SkeletalCube.SkeletalCube"), NULL, LOAD_None, NULL); check(PreviewMesh); FMessageDialog::Open(EAppMsgType::Ok, FText::Format( NSLOCTEXT("UnrealEd", "Error_PhysicsAssetHasNoSkelMesh", "Warning: Physics Asset has no skeletal mesh assigned! For now, a simple default skeletal mesh ({0}) will be used. You can fix this by opening PhAT, selecting the appropriate skeletal mesh in the content browser, and using (Asset -> Change Mesh) before saving this asset."), FText::FromString(PreviewMesh->GetFullName()))); } EditorSkelMesh = PreviewMesh; // Create SkeletalMeshComponent for rendering skeletal mesh EditorSkelComp = NewObject(); EditorSkelComp->SharedData = this; // first disable collision first to avoid creating physics body EditorSkelComp->SetCollisionProfileName(UCollisionProfile::BlockAll_ProfileName); EditorSkelComp->SetAnimationMode(EAnimationMode::Type::AnimationSingleNode); // Create floor component UStaticMesh* FloorMesh = LoadObject(NULL, TEXT("/Engine/EditorMeshes/PhAT_FloorBox.PhAT_FloorBox"), NULL, LOAD_None, NULL); check(FloorMesh); EditorFloorComp = NewObject(); EditorFloorComp->StaticMesh = FloorMesh; EditorFloorComp->SetRelativeScale3D(FVector(4.f)); PreviewScene.AddComponent(EditorSkelComp, FTransform::Identity); PreviewScene.AddComponent(EditorFloorComp, FTransform::Identity); // Look for body setups with no shapes (how does this happen?). // If we find one- just bang on a default box. bool bFoundEmptyShape = false; for (int32 i = 0; i BodySetup.Num(); ++i) { UBodySetup* BodySetup = PhysicsAsset->BodySetup[i]; if (BodySetup->AggGeom.GetElementCount() == 0) { FKBoxElem BoxElem; BoxElem.SetTransform(FTransform::Identity); BoxElem.X = 15.f; BoxElem.Y = 15.f; BoxElem.Z = 15.f; BodySetup->AggGeom.BoxElems.Add(BoxElem); check(BodySetup->AggGeom.BoxElems.Num() == 1); bFoundEmptyShape = true; } } // Pop up a warning about what we did. if (bFoundEmptyShape) { FMessageDialog::Open(EAppMsgType::Ok, NSLOCTEXT("UnrealEd", "EmptyBodyFound", "Bodies was found with no primitives!\nThey have been reset to have a box.")); } IMeshUtilities& MeshUtilities = FModuleManager::Get().LoadModuleChecked("MeshUtilities"); // Used for viewing bone influences, resetting bone geometry etc. MeshUtilities.CalcBoneVertInfos(EditorSkelMesh, DominantWeightBoneInfos, true); MeshUtilities.CalcBoneVertInfos(EditorSkelMesh, AnyWeightBoneInfos, false); EditorSkelComp->SetSkeletalMesh(EditorSkelMesh); EditorSkelComp->SetPhysicsAsset(PhysicsAsset); // Ensure PhysicsAsset mass properties are up to date. PhysicsAsset->UpdateBoundsBodiesArray(); // Check if there are any bodies in the Asset which do not have bones in the skeletal mesh. // If so, put up a warning. TArray MissingBodyIndices; FString BoneNames; for (int32 i = 0; i BodySetup.Num(); ++i) { FName BoneName = PhysicsAsset->BodySetup[i]->BoneName; int32 BoneIndex = EditorSkelMesh->RefSkeleton.FindBoneIndex(BoneName); if (BoneIndex == INDEX_NONE) { MissingBodyIndices.Add( i ); BoneNames += FString::Printf(TEXT("\t%s\n"), *BoneName.ToString()); } } const FText MissingBodyMsg = FText::Format( LOCTEXT( "MissingBones", "The following Bodies are in the PhysicsAsset, but have no corresponding bones in the SkeletalMesh.\nClick OK to delete them, or Cancel to ignore.\n\n{0}" ), FText::FromString( BoneNames ) ); if ( MissingBodyIndices.Num() ) { if ( FMessageDialog::Open( EAppMsgType::OkCancel, MissingBodyMsg ) == EAppReturnType::Ok ) { // Delete the bodies with no associated bones const FScopedTransaction Transaction( LOCTEXT( "DeleteUnusedPhysicsBodies", "Delete Physics Bodies With No Bones" ) ); PhysicsAsset->SetFlags(RF_Transactional); PhysicsAsset->Modify(); // Iterate backwards, as PhysicsAsset->BodySetup is a TArray and UE4 containers don't support remove_if() for ( int32 i = MissingBodyIndices.Num() - 1; i >= 0; --i ) { DeleteBody( MissingBodyIndices[i] ); } } } // Register handle component MouseHandle->RegisterComponentWithWorld(PreviewScene.GetWorld()); // Support undo/redo PhysicsAsset->SetFlags(RF_Transactional); EditorSkelComp->Stop(); SetSelectedBody(NULL); SetSelectedConstraint(INDEX_NONE); ResetTM = EditorSkelComp->GetComponentToWorld(); EnableSimulation(false); } void FPhATSharedData::CopyConstraintProperties(UPhysicsConstraintTemplate * FromConstraintSetup, UPhysicsConstraintTemplate * ToConstraintSetup) { //We want to copy frame2 relative to frame1. To do this we need to go from body2 into body1, compute relative. //Then apply relative inside body1 of the destination constraint, and finally move it into body2 of destination constraint //In total there are 4 bodies, body a and b are the frame1 frame2 bodies of the copied // body c and d are frame 1 and frame 2 of the destination constraint //we use the body letter to denote which space we're in, for example Frame1a would be frame1 inside BodyA //Frame1b would be frame 1 inside body b. In this case BodyA * Frame1a == BodyB * Frame1b FTransform Frame1A = FromConstraintSetup->DefaultInstance.GetRefFrame(EConstraintFrame::Frame1); FTransform BodyA = GetConstraintBodyTM(FromConstraintSetup, EConstraintFrame::Frame1); FTransform BodyB = GetConstraintBodyTM(FromConstraintSetup, EConstraintFrame::Frame2); FTransform BodyAFrame1A = GetConstraintWorldTM(FromConstraintSetup, EConstraintFrame::Frame1); FTransform BodyBFrame2B = GetConstraintWorldTM(FromConstraintSetup, EConstraintFrame::Frame2); FTransform Frame1C = ToConstraintSetup->DefaultInstance.GetRefFrame(EConstraintFrame::Frame1); FTransform BodyC = GetConstraintBodyTM(ToConstraintSetup, EConstraintFrame::Frame1); FTransform BodyD = GetConstraintBodyTM(ToConstraintSetup, EConstraintFrame::Frame2); FTransform FromF1AToF2A = BodyBFrame2B * BodyA.Inverse() * Frame1A.Inverse(); FTransform Frame2C = FromF1AToF2A * Frame1C; FTransform Frame2D = Frame2C* BodyC * BodyD.Inverse(); ToConstraintSetup->Modify(); FConstraintInstance OldInstance = ToConstraintSetup->DefaultInstance; ToConstraintSetup->DefaultInstance.CopyConstraintParamsFrom(&FromConstraintSetup->DefaultInstance); // recover certain data that we'd like to keep - i.e. bone indices // those still should stay ToConstraintSetup->DefaultInstance.ConstraintIndex = OldInstance.ConstraintIndex; ToConstraintSetup->DefaultInstance.ConstraintData = OldInstance.ConstraintData; ToConstraintSetup->DefaultInstance.JointName = OldInstance.JointName; ToConstraintSetup->DefaultInstance.ConstraintBone1 = OldInstance.ConstraintBone1; ToConstraintSetup->DefaultInstance.ConstraintBone2 = OldInstance.ConstraintBone2; ToConstraintSetup->DefaultInstance.Pos1 = OldInstance.Pos1; ToConstraintSetup->DefaultInstance.Pos2 = OldInstance.Pos2; //frame1 stays the same ToConstraintSetup->DefaultInstance.PriAxis1 = OldInstance.PriAxis1; ToConstraintSetup->DefaultInstance.SecAxis1 = OldInstance.SecAxis1; //frame2 is copied but relative to frame1 ToConstraintSetup->DefaultInstance.PriAxis2 = Frame2D.GetUnitAxis(EAxis::X); ToConstraintSetup->DefaultInstance.SecAxis2 = Frame2D.GetUnitAxis(EAxis::Y); } struct FMirrorInfo { FName BoneName; int32 BoneIndex; int32 BodyIndex; int32 ConstraintIndex; FMirrorInfo() { BoneIndex = INDEX_NONE; BodyIndex = INDEX_NONE; ConstraintIndex = INDEX_NONE; BoneName = NAME_None; } }; void FPhATSharedData::Mirror() { TArray MirrorInfos; if (EditingMode == PEM_BodyEdit) //grab all selected bodies { for (const FSelection& Selection : SelectedBodies) { MirrorInfos.AddUninitialized(); FMirrorInfo & MirrorInfo = MirrorInfos[MirrorInfos.Num() - 1]; MirrorInfo.BoneName = PhysicsAsset->BodySetup[Selection.Index]->BoneName; MirrorInfo.BodyIndex = Selection.Index; MirrorInfo.ConstraintIndex = PhysicsAsset->FindConstraintIndex(MirrorInfo.BoneName); } } else if (EditingMode == PEM_ConstraintEdit) //grab all selected constraints { for (const FSelection& Selection : SelectedConstraints) { MirrorInfos.AddUninitialized(); FMirrorInfo & MirrorInfo = MirrorInfos[MirrorInfos.Num() - 1]; MirrorInfo.BoneName = PhysicsAsset->ConstraintSetup[Selection.Index]->DefaultInstance.ConstraintBone1; MirrorInfo.BodyIndex = PhysicsAsset->FindBodyIndex(MirrorInfo.BoneName); MirrorInfo.ConstraintIndex = Selection.Index; } } for (FMirrorInfo & MirrorInfo : MirrorInfos) //mirror all selected bodies/constraints { int32 BoneIndex = EditorSkelMesh->RefSkeleton.FindBoneIndex(MirrorInfo.BoneName); int32 MirrorBoneIndex = PhysicsAsset->FindMirroredBone(EditorSkelMesh, BoneIndex); if (MirrorBoneIndex != INDEX_NONE) { UBodySetup * SrcBody = PhysicsAsset->BodySetup[MirrorInfo.BodyIndex]; const FScopedTransaction Transaction(NSLOCTEXT("PhAT", "MirrorBody", "MirrorBody")); MakeNewBody(MirrorBoneIndex, false); int32 MirrorBodyIndex = PhysicsAsset->FindControllingBodyIndex(EditorSkelMesh, MirrorBoneIndex); UBodySetup * DestBody = PhysicsAsset->BodySetup[MirrorBodyIndex]; DestBody->Modify(); DestBody->CopyBodyPropertiesFrom(SrcBody); int32 MirrorConstraintIndex = PhysicsAsset->FindConstraintIndex(DestBody->BoneName); UPhysicsConstraintTemplate * FromConstraint = PhysicsAsset->ConstraintSetup[MirrorInfo.ConstraintIndex]; UPhysicsConstraintTemplate * ToConstraint = PhysicsAsset->ConstraintSetup[MirrorConstraintIndex]; CopyConstraintProperties(FromConstraint, ToConstraint); } } } FPhATSharedData::EPhATRenderMode FPhATSharedData::GetCurrentMeshViewMode() { if (bRunningSimulation) { return Sim_MeshViewMode; } else if (EditingMode == PEM_BodyEdit) { return BodyEdit_MeshViewMode; } else { return ConstraintEdit_MeshViewMode; } } FPhATSharedData::EPhATRenderMode FPhATSharedData::GetCurrentCollisionViewMode() { if (bRunningSimulation) { return Sim_CollisionViewMode; } else if (EditingMode == PEM_BodyEdit) { return BodyEdit_CollisionViewMode; } else { return ConstraintEdit_CollisionViewMode; } } FPhATSharedData::EPhATConstraintViewMode FPhATSharedData::GetCurrentConstraintViewMode() { if (bRunningSimulation) { return Sim_ConstraintViewMode; } else if (EditingMode == PEM_BodyEdit) { return BodyEdit_ConstraintViewMode; } else { return ConstraintEdit_ConstraintViewMode; } } void FPhATSharedData::HitBone(int32 BodyIndex, EKCollisionPrimitiveType PrimType, int32 PrimIndex, bool bGroupSelect /* = false*/, bool bGroupSelectRemove /* = true */) { if (EditingMode == FPhATSharedData::PEM_BodyEdit && !bSelectionLock && !bRunningSimulation) { FPhATSharedData::FSelection Selection(BodyIndex, PrimType, PrimIndex); SetSelectedBody( &Selection, bGroupSelect, bGroupSelectRemove); } } void FPhATSharedData::HitConstraint(int32 ConstraintIndex, bool bGroupSelect) { if (EditingMode == FPhATSharedData::PEM_ConstraintEdit && !bSelectionLock && !bRunningSimulation) { SetSelectedConstraint(ConstraintIndex, bGroupSelect); } } void FPhATSharedData::RefreshPhysicsAssetChange(const UPhysicsAsset* InPhysAsset) { if (InPhysAsset) { for (FObjectIterator Iter(USkeletalMeshComponent::StaticClass()); Iter; ++Iter) { USkeletalMeshComponent* SkeletalMeshComponent = Cast(*Iter); if (SkeletalMeshComponent->GetPhysicsAsset() == InPhysAsset) { // it needs to recreate IF it already has been created if (SkeletalMeshComponent->IsPhysicsStateCreated()) { SkeletalMeshComponent->RecreatePhysicsState(); } } } for (FObjectIterator Iter(UWheeledVehicleMovementComponent::StaticClass()); Iter; ++Iter) { UWheeledVehicleMovementComponent * WheeledVehicleMovementComponent = Cast(*Iter); if (USkeletalMeshComponent * SkeltalMeshComponent = Cast(WheeledVehicleMovementComponent->UpdatedComponent)) { if (SkeltalMeshComponent->GetPhysicsAsset() == InPhysAsset) { //Need to recreate car data WheeledVehicleMovementComponent->RecreatePhysicsState(); } } } FEditorSupportDelegates::RedrawAllViewports.Broadcast(); // since we recreate physicsstate, a lot of transient state data will be gone // so have to turn simulation off again. // ideally maybe in the future, we'll fix it by controlling tick? EnableSimulation(false); } } void FPhATSharedData::SetSelectedBodyAnyPrim(int32 BodyIndex, bool bGroupSelect /* = false */) { if (BodyIndex == INDEX_NONE) { SetSelectedBody(NULL); return; } UBodySetup* BodySetup = PhysicsAsset->BodySetup[BodyIndex]; check(BodySetup); if (BodySetup->AggGeom.SphereElems.Num() > 0) { FSelection Selection(BodyIndex, KPT_Sphere, 0); SetSelectedBody(&Selection, bGroupSelect); } else if (BodySetup->AggGeom.BoxElems.Num() > 0) { FSelection Selection(BodyIndex, KPT_Box, 0); SetSelectedBody(&Selection, bGroupSelect); } else if (BodySetup->AggGeom.SphylElems.Num() > 0) { FSelection Selection(BodyIndex, KPT_Sphyl, 0); SetSelectedBody(&Selection, bGroupSelect); } else if (BodySetup->AggGeom.ConvexElems.Num() > 0) { FSelection Selection(BodyIndex, KPT_Convex, 0); SetSelectedBody(&Selection, bGroupSelect); } else { UE_LOG(LogPhAT, Fatal, TEXT("Body Setup with No Primitives!")); } } void FPhATSharedData::SetSelectedBody(const FSelection* Body, bool bGroupSelect /*= false*/, bool bGroupSelectRemove /* = true */) { if(bInsideSelChange) { return; } if(bGroupSelect == false) { SelectedBodies.Empty(); } if(Body) { bool bAlreadySelected = false; //unselect if already selected for(int32 i=0; iIndex >= 0 && GetSelectedBody()->Index < PhysicsAsset->BodySetup.Num()); // Set properties dialog to display selected bone (or bone instance) info. TArray Objs; for(int i=0; iBodySetup[SelectedBodies[i].Index]); } GroupSelectionChangedEvent.Broadcast(Objs); } //bInsideSelChange = true; //HierarchySelectionChangedEvent.Broadcast(); //TODO: disable for now bInsideSelChange = false; ControlledBones.Empty(); if(!GetSelectedBody()) { return; } for (int32 i = 0; i RefSkeleton.GetNum(); ++i) { int32 ControllerBodyIndex = PhysicsAsset->FindControllingBodyIndex(EditorSkelMesh, i); if (ControllerBodyIndex == GetSelectedBody()->Index) { ControlledBones.Add(i); } } UpdateNoCollisionBodies(); PreviewChangedEvent.Broadcast(); } void FPhATSharedData::SetSelectedBodiesFromConstraints() { if(SelectedConstraints.Num() == 0) { return; } SetSelectedBody(nullptr, false); for (const FSelection& Selection : SelectedConstraints) { UPhysicsConstraintTemplate* ConstraintTemplate = PhysicsAsset->ConstraintSetup[Selection.Index]; FConstraintInstance & DefaultInstance = ConstraintTemplate->DefaultInstance; for (int32 BodyIdx = 0; BodyIdx < PhysicsAsset->BodySetup.Num(); ++BodyIdx) { UBodySetup* BodySetup = PhysicsAsset->BodySetup[BodyIdx]; if (DefaultInstance.JointName == BodySetup->BoneName && BodySetup->AggGeom.GetElementCount() > 0) { FSelection NewSelection(BodyIdx, KPT_Unknown, 0); int32 PrimIndex = 0; for(int32 GeomType = 0; GeomType < KPT_Unknown; ++GeomType) { if(BodySetup->AggGeom.GetElementCount(GeomType) > 0) { NewSelection.PrimitiveType = (EKCollisionPrimitiveType)GeomType; break; } } SetSelectedBody(&NewSelection, true); } } } } void FPhATSharedData::SetSelectedConstraintsFromBodies() { if (SelectedBodies.Num() == 0) { return; } TSet TmpSelectedConstraints; //We could have multiple shapes selected which would cause us to add and remove the same constraint. SetSelectedConstraint(INDEX_NONE, false); for (const FSelection& Selection : SelectedBodies) { UBodySetup* BodySetup = PhysicsAsset->BodySetup[Selection.Index]; for(int32 ConstraintIdx = 0; ConstraintIdx < PhysicsAsset->ConstraintSetup.Num(); ++ConstraintIdx) { const UPhysicsConstraintTemplate* ConstraintTemplate = PhysicsAsset->ConstraintSetup[ConstraintIdx]; if(ConstraintTemplate->DefaultInstance.JointName == BodySetup->BoneName && !TmpSelectedConstraints.Contains(ConstraintIdx)) { TmpSelectedConstraints.Add(ConstraintIdx); SetSelectedConstraint(ConstraintIdx, true); } } } } void FPhATSharedData::UpdateNoCollisionBodies() { NoCollisionBodies.Empty(); // Query disable table with selected body and every other body. for (int32 i = 0; i BodySetup.Num(); ++i) { // Add any bodies with bNoCollision if (PhysicsAsset->BodySetup[i]->DefaultInstance.GetCollisionEnabled() == ECollisionEnabled::NoCollision) { NoCollisionBodies.Add(i); } else if (GetSelectedBody() && i != GetSelectedBody()->Index) { // Add this body if it has disabled collision with selected. FRigidBodyIndexPair Key(i, GetSelectedBody()->Index); if (PhysicsAsset->BodySetup[GetSelectedBody()->Index]->DefaultInstance.GetCollisionEnabled() == ECollisionEnabled::NoCollision || PhysicsAsset->CollisionDisableTable.Find(Key)) { NoCollisionBodies.Add(i); } } } } void FPhATSharedData::SetSelectedConstraint(int32 ConstraintIndex, bool bGroupSelect /*= false*/) { if(bGroupSelect == false) { SelectedConstraints.Empty(); } if(ConstraintIndex != INDEX_NONE) { bool bAlreadySelected = false; for(int32 i=0; iIndex >= 0 && GetSelectedConstraint()->Index < PhysicsAsset->ConstraintSetup.Num()); TArray Objs; for(int i=0; iConstraintSetup[SelectedConstraints[i].Index]); } GroupSelectionChangedEvent.Broadcast(Objs); } PreviewChangedEvent.Broadcast(); } void FPhATSharedData::SetCollisionBetweenSelected(bool bEnableCollision) { if (bRunningSimulation || SelectedBodies.Num() == 0) { return; } PhysicsAsset->Modify(); for(int32 i=0; iEnableCollision(SelectedBodies[i].Index, SelectedBodies[j].Index); }else { PhysicsAsset->DisableCollision(SelectedBodies[i].Index, SelectedBodies[j].Index); } } } UpdateNoCollisionBodies(); PreviewChangedEvent.Broadcast(); } void FPhATSharedData::SetCollisionBetween(int32 Body1Index, int32 Body2Index, bool bEnableCollision) { if (bRunningSimulation) { return; } PhysicsAsset->Modify(); if (Body1Index != INDEX_NONE && Body2Index != INDEX_NONE && Body1Index != Body2Index) { if (bEnableCollision) { PhysicsAsset->EnableCollision(Body1Index, Body2Index); } else { PhysicsAsset->DisableCollision(Body1Index, Body2Index); } UpdateNoCollisionBodies(); } PreviewChangedEvent.Broadcast(); } void FPhATSharedData::CopyBody() { check(SelectedBodies.Num() == 1); CopiedBodySetup = PhysicsAsset->BodySetup[GetSelectedBody()->Index]; } void FPhATSharedData::PasteBodyProperties() { // Can't do this while simulating! if (bRunningSimulation) { return; } // Must have two valid bodies (which are different) if(CopiedBodySetup == NULL) { return; } const FScopedTransaction Transaction( NSLOCTEXT("PhAT", "PasteBodyProperties", "Paste Body Properties") ); for(int32 i=0; iBodySetup[SelectedBodies[i].Index]; UBodySetup* FromBodySetup = CopiedBodySetup; ToBodySetup->Modify(); ToBodySetup->CopyBodyPropertiesFrom(FromBodySetup); } else { FBodyInstance* ToBodyInstance = &PhysicsAsset->BodySetup[SelectedBodies[i].Index]->DefaultInstance; FBodyInstance* FromBodyInstance = &CopiedBodySetup->DefaultInstance; ToBodyInstance->CopyBodyInstancePropertiesFrom(FromBodyInstance); } } SetSelectedBody(NULL); //paste can change the primitives on our selected bodies. There's probably a way to properly update this, but for now just deselect PreviewChangedEvent.Broadcast(); } bool FPhATSharedData::WeldSelectedBodies(bool bWeld /* = true */) { bool bCanWeld = false; if (bRunningSimulation) { return false; } if(SelectedBodies.Num() <= 1) { return false; } //we only support two body weld int BodyIndex0 = 0; int BodyIndex1 = INDEX_NONE; for(int32 i=1; iBodySetup[Body0.Index]->BoneName; int32 Bone0Index = EditorSkelMesh->RefSkeleton.FindBoneIndex(Bone0Name); check(Bone0Index != INDEX_NONE); FName Bone1Name = PhysicsAsset->BodySetup[Body1.Index]->BoneName; int32 Bone1Index = EditorSkelMesh->RefSkeleton.FindBoneIndex(Bone1Name); check(Bone1Index != INDEX_NONE); int32 Bone0ParentIndex = EditorSkelMesh->RefSkeleton.GetParentIndex(Bone0Index); int32 Bone1ParentIndex = EditorSkelMesh->RefSkeleton.GetParentIndex(Bone1Index); int ParentBodyIndex = INDEX_NONE; int ChildBodyIndex = INDEX_NONE; FName ParentBoneName; EKCollisionPrimitiveType ParentPrimitiveType = KPT_Unknown; EKCollisionPrimitiveType ChildPrimitiveType = KPT_Unknown; int32 ParentPrimitiveIndex = INDEX_NONE; int32 ChildPrimitiveIndex = INDEX_NONE; if (PhysicsAsset->FindControllingBodyIndex(EditorSkelMesh, Bone1ParentIndex) == Body0.Index) { ParentBodyIndex = Body0.Index; ParentBoneName = Bone0Name; ChildBodyIndex = Body1.Index; ParentPrimitiveType = Body0.PrimitiveType; ChildPrimitiveType = Body1.PrimitiveType; ParentPrimitiveIndex = Body0.PrimitiveIndex; //Child geoms get appended so just add it. This is kind of a hack but this whole indexing scheme needs to be rewritten anyway ChildPrimitiveIndex = Body1.PrimitiveIndex + PhysicsAsset->BodySetup[Body0.Index]->AggGeom.GetElementCount(ChildPrimitiveType); bCanWeld = true; }else if(PhysicsAsset->FindControllingBodyIndex(EditorSkelMesh, Bone0ParentIndex) == Body1.Index) { ParentBodyIndex = Body1.Index; ParentBoneName = Bone1Name; ChildBodyIndex = Body0.Index; ParentPrimitiveType = Body1.PrimitiveType; ChildPrimitiveType = Body0.PrimitiveType; ParentPrimitiveIndex = Body1.PrimitiveIndex; //Child geoms get appended so just add it. This is kind of a hack but this whole indexing scheme needs to be rewritten anyway ChildPrimitiveIndex = Body0.PrimitiveIndex + PhysicsAsset->BodySetup[Body1.Index]->AggGeom.GetElementCount(ChildPrimitiveType); bCanWeld = true; } //function is used for the action and the check if(bWeld == false) { return bCanWeld; } check(ParentBodyIndex != INDEX_NONE); check(ChildBodyIndex != INDEX_NONE); { const FScopedTransaction Transaction( NSLOCTEXT("UnrealEd", "WeldBodies", "Weld Bodies") ); // .. the asset itself.. PhysicsAsset->Modify(); // .. the parent and child bodies.. PhysicsAsset->BodySetup[ParentBodyIndex]->Modify(); PhysicsAsset->BodySetup[ChildBodyIndex]->Modify(); // .. and any constraints of the 'child' body.. TArray Constraints; PhysicsAsset->BodyFindConstraints(ChildBodyIndex, Constraints); for (int32 i = 0; i ConstraintSetup[ConstraintIndex]->Modify(); } // Do the actual welding FPhysicsAssetUtils::WeldBodies(PhysicsAsset, ParentBodyIndex, ChildBodyIndex, EditorSkelComp); } // update the tree HierarchyChangedEvent.Broadcast(); // Body index may have changed, so we re-find it. int32 BodyIndex = PhysicsAsset->FindBodyIndex(ParentBoneName); FSelection SelectionParent(BodyIndex, ParentPrimitiveType, ParentPrimitiveIndex); SetSelectedBody(&SelectionParent); // This redraws the viewport as well... FSelection SelectionChild(BodyIndex, ChildPrimitiveType, ChildPrimitiveIndex); SetSelectedBody(&SelectionChild, true); // This redraws the viewport as well... // Just to be safe - deselect any selected constraints SetSelectedConstraint(INDEX_NONE); RefreshPhysicsAssetChange(PhysicsAsset); return true; } void FPhATSharedData::InitConstraintSetup(UPhysicsConstraintTemplate* ConstraintSetup, int32 ChildBodyIndex, int32 ParentBodyIndex) { check(ConstraintSetup); ConstraintSetup->Modify(false); UBodySetup* ChildBodySetup = PhysicsAsset->BodySetup[ ChildBodyIndex ]; UBodySetup* ParentBodySetup = PhysicsAsset->BodySetup[ ParentBodyIndex ]; check(ChildBodySetup && ParentBodySetup); const int32 ChildBoneIndex = EditorSkelMesh->RefSkeleton.FindBoneIndex(ChildBodySetup->BoneName); const int32 ParentBoneIndex = EditorSkelMesh->RefSkeleton.FindBoneIndex(ParentBodySetup->BoneName); check(ChildBoneIndex != INDEX_NONE && ParentBoneIndex != INDEX_NONE); // Transform of child from parent is just child ref-pose entry. FMatrix ChildBoneTM = EditorSkelComp->GetBoneMatrix(ChildBoneIndex); ChildBoneTM.RemoveScaling(); FMatrix ParentBoneTM = EditorSkelComp->GetBoneMatrix(ParentBoneIndex); ParentBoneTM.RemoveScaling(); FMatrix RelTM = ChildBoneTM * ParentBoneTM.Inverse(); // Place joint at origin of child ConstraintSetup->DefaultInstance.ConstraintBone1 = ChildBodySetup->BoneName; ConstraintSetup->DefaultInstance.Pos1 = FVector::ZeroVector; ConstraintSetup->DefaultInstance.PriAxis1 = FVector(1.f, 0.f, 0.f); ConstraintSetup->DefaultInstance.SecAxis1 = FVector(0.f, 1.f, 0.f); ConstraintSetup->DefaultInstance.ConstraintBone2 = ParentBodySetup->BoneName; ConstraintSetup->DefaultInstance.Pos2 = RelTM.GetOrigin(); ConstraintSetup->DefaultInstance.PriAxis2 = RelTM.GetScaledAxis( EAxis::X ); ConstraintSetup->DefaultInstance.SecAxis2 = RelTM.GetScaledAxis( EAxis::Y ); // Disable collision between constrained bodies by default. SetCollisionBetween(ChildBodyIndex, ParentBodyIndex, false); } void FPhATSharedData::MakeNewBody(int32 NewBoneIndex, bool bAutoSelect) { FName NewBoneName = EditorSkelMesh->RefSkeleton.GetBoneName(NewBoneIndex); // If this body is already physical - do nothing. int32 NewBodyIndex = PhysicsAsset->FindBodyIndex(NewBoneName); if (NewBodyIndex != INDEX_NONE) { return; } // Find body that currently controls this bone. int32 ParentBodyIndex = PhysicsAsset->FindControllingBodyIndex(EditorSkelMesh, NewBoneIndex); PhysicsAsset->Modify(); // Create the physics body. NewBodyIndex = FPhysicsAssetUtils::CreateNewBody(PhysicsAsset, NewBoneName); UBodySetup* BodySetup = PhysicsAsset->BodySetup[ NewBodyIndex ]; check(BodySetup->BoneName == NewBoneName); BodySetup->Modify(); bool bCreatedBody = false; // Create a new physics body for this bone. if (NewBodyData.VertWeight == EVW_DominantWeight) { bCreatedBody = FPhysicsAssetUtils::CreateCollisionFromBone(BodySetup, EditorSkelMesh, NewBoneIndex, NewBodyData, DominantWeightBoneInfos); } else { bCreatedBody = FPhysicsAssetUtils::CreateCollisionFromBone(BodySetup, EditorSkelMesh, NewBoneIndex, NewBodyData, AnyWeightBoneInfos); } if (bCreatedBody == false) { FPhysicsAssetUtils::DestroyBody(PhysicsAsset, NewBodyIndex); return; } // Check if the bone of the new body has any physical children bones for (int32 i = 0; i < EditorSkelMesh->RefSkeleton.GetNum(); ++i) { if (EditorSkelMesh->RefSkeleton.BoneIsChildOf(i, NewBoneIndex)) { const int32 ChildBodyIndex = PhysicsAsset->FindBodyIndex(EditorSkelMesh->RefSkeleton.GetBoneName(i)); // If the child bone is physical, it may require fixing up in regards to constraints if (ChildBodyIndex != INDEX_NONE) { UBodySetup* ChildBody = PhysicsAsset->BodySetup[ ChildBodyIndex ]; check(ChildBody); int32 ConstraintIndex = PhysicsAsset->FindConstraintIndex(ChildBody->BoneName); // If the child body is not constrained already, create a new constraint between // the child body and the new body if (ConstraintIndex == INDEX_NONE) { ConstraintIndex = FPhysicsAssetUtils::CreateNewConstraint(PhysicsAsset, ChildBody->BoneName); check(ConstraintIndex != INDEX_NONE); } // If there's a pre-existing constraint, see if it needs to be fixed up else { UPhysicsConstraintTemplate* ExistingConstraintSetup = PhysicsAsset->ConstraintSetup[ ConstraintIndex ]; check(ExistingConstraintSetup); const int32 ExistingConstraintBoneIndex = EditorSkelMesh->RefSkeleton.FindBoneIndex(ExistingConstraintSetup->DefaultInstance.ConstraintBone2); check(ExistingConstraintBoneIndex != INDEX_NONE); // If the constraint exists between two child bones, then no fix up is required if (EditorSkelMesh->RefSkeleton.BoneIsChildOf(ExistingConstraintBoneIndex, NewBoneIndex)) { continue; } // If the constraint isn't between two child bones, then it is between a physical bone higher in the bone // hierarchy than the new bone, so it needs to be fixed up by setting the constraint to point to the new bone // instead. Additionally, collision needs to be re-enabled between the child bone and the identified "grandparent" // bone. const int32 ExistingConstraintBodyIndex = PhysicsAsset->FindBodyIndex(ExistingConstraintSetup->DefaultInstance.ConstraintBone2); check(ExistingConstraintBodyIndex != INDEX_NONE); check(ExistingConstraintBodyIndex == ParentBodyIndex); SetCollisionBetween(ChildBodyIndex, ExistingConstraintBodyIndex, true); } UPhysicsConstraintTemplate* ChildConstraintSetup = PhysicsAsset->ConstraintSetup[ ConstraintIndex ]; check(ChildConstraintSetup); InitConstraintSetup(ChildConstraintSetup, ChildBodyIndex, NewBodyIndex); } } } // If we have a physics parent, create a joint to it. if (ParentBodyIndex != INDEX_NONE) { const int32 NewConstraintIndex = FPhysicsAssetUtils::CreateNewConstraint(PhysicsAsset, NewBoneName); UPhysicsConstraintTemplate* ConstraintSetup = PhysicsAsset->ConstraintSetup[ NewConstraintIndex ]; check(ConstraintSetup); InitConstraintSetup(ConstraintSetup, NewBodyIndex, ParentBodyIndex); } // update the tree HierarchyChangedEvent.Broadcast(); if (bAutoSelect) { SetSelectedBodyAnyPrim(NewBodyIndex); } RefreshPhysicsAssetChange(PhysicsAsset); } void FPhATSharedData::SetSelectedConstraintRelTM(const FTransform& RelTM) { FTransform WParentFrame = GetConstraintWorldTM(GetSelectedConstraint(), EConstraintFrame::Frame2); FTransform WNewChildFrame = RelTM * WParentFrame; UPhysicsConstraintTemplate* ConstraintSetup = PhysicsAsset->ConstraintSetup[GetSelectedConstraint()->Index]; ConstraintSetup->Modify(); // Get child bone transform int32 BoneIndex = EditorSkelMesh->RefSkeleton.FindBoneIndex(ConstraintSetup->DefaultInstance.ConstraintBone1); if (BoneIndex != INDEX_NONE) { FTransform BoneTM = EditorSkelComp->GetBoneTransform(BoneIndex); BoneTM.RemoveScaling(); ConstraintSetup->DefaultInstance.SetRefFrame(EConstraintFrame::Frame1, WNewChildFrame.GetRelativeTransform(BoneTM)); } } void FPhATSharedData::CopyConstraint() { check(SelectedConstraints.Num() == 1); CopiedConstraintTemplate = PhysicsAsset->ConstraintSetup[GetSelectedConstraint()->Index]; } void FPhATSharedData::PasteConstraintProperties() { if (CopiedConstraintTemplate == NULL) { return; } const FScopedTransaction Transaction( NSLOCTEXT("PhAT", "PasteConstraintProperties", "Paste Constraint Properties") ); UPhysicsConstraintTemplate* FromConstraintSetup = CopiedConstraintTemplate; for(int32 i=0; iConstraintSetup[SelectedConstraints[i].Index]; CopyConstraintProperties(FromConstraintSetup, ToConstraintSetup); } } void CycleMatrixRows(FMatrix* TM) { float Tmp[3]; Tmp[0] = TM->M[0][0]; Tmp[1] = TM->M[0][1]; Tmp[2] = TM->M[0][2]; TM->M[0][0] = TM->M[1][0]; TM->M[0][1] = TM->M[1][1]; TM->M[0][2] = TM->M[1][2]; TM->M[1][0] = TM->M[2][0]; TM->M[1][1] = TM->M[2][1]; TM->M[1][2] = TM->M[2][2]; TM->M[2][0] = Tmp[0]; TM->M[2][1] = Tmp[1]; TM->M[2][2] = Tmp[2]; } void FPhATSharedData::CycleCurrentConstraintOrientation() { UPhysicsConstraintTemplate* ConstraintTemplate = PhysicsAsset->ConstraintSetup[GetSelectedConstraint()->Index]; FMatrix ConstraintTransform = ConstraintTemplate->DefaultInstance.GetRefFrame(EConstraintFrame::Frame2).ToMatrixWithScale(); FTransform WParentFrame = GetConstraintWorldTM(GetSelectedConstraint(), EConstraintFrame::Frame2); FTransform WChildFrame = GetConstraintWorldTM(GetSelectedConstraint(), EConstraintFrame::Frame1); FTransform RelativeTransform = WChildFrame * WParentFrame.Inverse(); CycleMatrixRows(&ConstraintTransform); ConstraintTemplate->DefaultInstance.SetRefFrame(EConstraintFrame::Frame2, FTransform(ConstraintTransform)); SetSelectedConstraintRelTM(RelativeTransform); } void FPhATSharedData::CycleCurrentConstraintActive() { for(int32 i=0; iConstraintSetup[GetSelectedConstraint()->Index]; FConstraintInstance & DefaultInstance = ConstraintTemplate->DefaultInstance; if(DefaultInstance.AngularSwing1Motion != ACM_Limited && DefaultInstance.AngularSwing2Motion != ACM_Limited) { DefaultInstance.AngularSwing1Motion = ACM_Limited; DefaultInstance.AngularSwing2Motion = ACM_Locked; DefaultInstance.AngularTwistMotion = ACM_Locked; }else if(DefaultInstance.AngularSwing2Motion != ACM_Limited && DefaultInstance.AngularTwistMotion != ACM_Limited) { DefaultInstance.AngularSwing1Motion = ACM_Locked; DefaultInstance.AngularSwing2Motion = ACM_Limited; DefaultInstance.AngularTwistMotion = ACM_Locked; }else { DefaultInstance.AngularSwing1Motion = ACM_Locked; DefaultInstance.AngularSwing2Motion = ACM_Locked; DefaultInstance.AngularTwistMotion = ACM_Limited; } } } void FPhATSharedData::ToggleConstraint(EPhATConstraintType Constraint) { for(int32 i=0; iConstraintSetup[GetSelectedConstraint()->Index]; FConstraintInstance & DefaultInstance = ConstraintTemplate->DefaultInstance; if(Constraint == PCT_Swing1) { DefaultInstance.AngularSwing1Motion = DefaultInstance.AngularSwing1Motion == ACM_Limited ? ACM_Locked : ACM_Limited; }else if(Constraint == PCT_Swing2) { DefaultInstance.AngularSwing2Motion = DefaultInstance.AngularSwing2Motion == ACM_Limited ? ACM_Locked : ACM_Limited; }else { DefaultInstance.AngularTwistMotion = DefaultInstance.AngularTwistMotion == ACM_Limited ? ACM_Locked : ACM_Limited; } } } void FPhATSharedData::DeleteBody(int32 DelBodyIndex, bool bRefreshComponent) { const FScopedTransaction Transaction( NSLOCTEXT("UnrealEd", "DeleteBody", "Delete Body") ); // The physics asset and default instance.. PhysicsAsset->Modify(); // .. the body.. UBodySetup * BodySetup = PhysicsAsset->BodySetup[DelBodyIndex]; BodySetup->Modify(); // .. and any constraints to the body. TArray Constraints; PhysicsAsset->BodyFindConstraints(DelBodyIndex, Constraints); //we want to fixup constraints so that nearest child bodies get constraint with parent body TArray NearestBodiesBelow; PhysicsAsset->GetNearestBodyIndicesBelow(NearestBodiesBelow, BodySetup->BoneName, EditorSkelMesh); int32 BoneIndex = EditorSkelMesh->RefSkeleton.FindBoneIndex(BodySetup->BoneName); if (BoneIndex != INDEX_NONE) //it's possible to delete bodies that have no bones. In this case just ignore all of this fixup code { int32 ParentBodyIndex = PhysicsAsset->FindParentBodyIndex(EditorSkelMesh, BoneIndex); UBodySetup * ParentBody = ParentBodyIndex != INDEX_NONE ? PhysicsAsset->BodySetup[ParentBodyIndex] : NULL; for (const int32 ConstraintIndex : Constraints) { UPhysicsConstraintTemplate * Constraint = PhysicsAsset->ConstraintSetup[ConstraintIndex]; Constraint->Modify(); if (ParentBody) { //for all constraints that contain a nearest child of this body, create a copy of the constraint between the child and parent for (const int32 BodyBelowIndex : NearestBodiesBelow) { UBodySetup * BodyBelow = PhysicsAsset->BodySetup[BodyBelowIndex]; if (Constraint->DefaultInstance.ConstraintBone1 == BodyBelow->BoneName) { int32 NewConstraintIndex = FPhysicsAssetUtils::CreateNewConstraint(PhysicsAsset, BodyBelow->BoneName, Constraint); UPhysicsConstraintTemplate * NewConstraint = PhysicsAsset->ConstraintSetup[NewConstraintIndex]; InitConstraintSetup(NewConstraint, BodyBelowIndex, ParentBodyIndex); } } } } } // Now actually destroy body. This will destroy any constraints associated with the body as well. FPhysicsAssetUtils::DestroyBody(PhysicsAsset, DelBodyIndex); // Select nothing. SetSelectedBody(NULL); SetSelectedConstraint(INDEX_NONE); HierarchyChangedEvent.Broadcast(); if (bRefreshComponent) { RefreshPhysicsAssetChange(PhysicsAsset); } } void FPhATSharedData::DeleteCurrentPrim() { if (bRunningSimulation) { return; } if (!GetSelectedBody()) { return; } // Make sure rendering is done - so we are not changing data being used by collision drawing. FlushRenderingCommands(); //We will first get all the bodysetups we're interested in. The number of duplicates each bodysetup has tells us how many geoms are being deleted //We need to do this first because deleting will modify our selection TMap> BodySelectionMap; TArray BodySetups; for(int32 i=0; iBodySetup[SelectedBodies[i].Index]; BodySelectionMap.FindOrAdd(BodySetup).Add(SelectedBodies[i]); } const FScopedTransaction Transaction( NSLOCTEXT("UnrealEd", "DeletePrimitive", "Delete Primitive") ); for (TMap >::TConstIterator It(BodySelectionMap); It; ++It) { UBodySetup * BodySetup = It.Key(); const TArray & SelectedPrimitives = It.Value(); int32 SphereDeletedCount = 0; int32 BoxDeletedCount = 0; int32 SphylDeletedCount = 0; int32 ConvexDeletedCount = 0; for (int32 i = 0; i < SelectedPrimitives.Num(); ++i) { const FSelection& SelectedBody = SelectedPrimitives[i]; int32 BodyIndex = PhysicsAsset->FindBodyIndex(BodySetup->BoneName); BodySetup->Modify(); if (SelectedBody.PrimitiveType == KPT_Sphere) { BodySetup->AggGeom.SphereElems.RemoveAt(SelectedBody.PrimitiveIndex - (SphereDeletedCount++)); } else if (SelectedBody.PrimitiveType == KPT_Box) { BodySetup->AggGeom.BoxElems.RemoveAt(SelectedBody.PrimitiveIndex - (BoxDeletedCount++)); } else if (SelectedBody.PrimitiveType == KPT_Sphyl) { BodySetup->AggGeom.SphylElems.RemoveAt(SelectedBody.PrimitiveIndex - (SphylDeletedCount++)); } else if (SelectedBody.PrimitiveType == KPT_Convex) { BodySetup->AggGeom.ConvexElems.RemoveAt(SelectedBody.PrimitiveIndex - (ConvexDeletedCount++)); // Need to invalidate GUID in this case as cooked data must be updated BodySetup->InvalidatePhysicsData(); } // If this bone has no more geometry - remove it totally. if (BodySetup->AggGeom.GetElementCount() == 0) { check(i == SelectedPrimitives.Num() - 1); //we should really only delete on last prim - only reason this is even in for loop is because of API needing body index if (BodyIndex != INDEX_NONE) { DeleteBody(BodyIndex, false); } if (CopiedBodySetup == BodySetup) { CopiedBodySetup = NULL; } } } } HierarchyChangedEvent.Broadcast(); SetSelectedBodyAnyPrim(INDEX_NONE); // Will call UpdateViewport RefreshPhysicsAssetChange(PhysicsAsset); } FTransform FPhATSharedData::GetConstraintBodyTM(const UPhysicsConstraintTemplate* ConstraintSetup, EConstraintFrame::Type Frame) const { if (ConstraintSetup == NULL) { return FTransform::Identity; } int32 BoneIndex; if (Frame == EConstraintFrame::Frame1) { BoneIndex = EditorSkelMesh->RefSkeleton.FindBoneIndex(ConstraintSetup->DefaultInstance.ConstraintBone1); } else { BoneIndex = EditorSkelMesh->RefSkeleton.FindBoneIndex(ConstraintSetup->DefaultInstance.ConstraintBone2); } // If we couldn't find the bone - fall back to identity. if (BoneIndex == INDEX_NONE) { return FTransform::Identity; } else { FTransform BoneTM = EditorSkelComp->GetBoneTransform(BoneIndex); BoneTM.RemoveScaling(); return BoneTM; } } FTransform FPhATSharedData::GetConstraintWorldTM(const UPhysicsConstraintTemplate* ConstraintSetup, EConstraintFrame::Type Frame, float Scale) const { if (ConstraintSetup == NULL) { return FTransform::Identity; } FVector Scale3D(Scale); int32 BoneIndex; FTransform LFrame = ConstraintSetup->DefaultInstance.GetRefFrame(Frame); if (Frame == EConstraintFrame::Frame1) { BoneIndex = EditorSkelMesh->RefSkeleton.FindBoneIndex(ConstraintSetup->DefaultInstance.ConstraintBone1); } else { BoneIndex = EditorSkelMesh->RefSkeleton.FindBoneIndex(ConstraintSetup->DefaultInstance.ConstraintBone2); } // If we couldn't find the bone - fall back to identity. if (BoneIndex == INDEX_NONE) { return FTransform::Identity; } else { FTransform BoneTM = EditorSkelComp->GetBoneTransform(BoneIndex); BoneTM.RemoveScaling(); LFrame.ScaleTranslation(Scale3D); return LFrame * BoneTM; } } FTransform FPhATSharedData::GetConstraintMatrix(int32 ConstraintIndex, EConstraintFrame::Type Frame, float Scale) const { UPhysicsConstraintTemplate* ConstraintSetup = PhysicsAsset->ConstraintSetup[ConstraintIndex]; return GetConstraintWorldTM(ConstraintSetup, Frame, Scale); } FTransform FPhATSharedData::GetConstraintWorldTM(const FSelection* Constraint, EConstraintFrame::Type Frame) const { int32 ConstraintIndex = Constraint ? Constraint->Index : INDEX_NONE; if (ConstraintIndex == INDEX_NONE) { return FTransform::Identity; } UPhysicsConstraintTemplate* ConstraintSetup = PhysicsAsset->ConstraintSetup[ConstraintIndex]; return GetConstraintWorldTM(ConstraintSetup, Frame, 1.f); } void FPhATSharedData::DeleteCurrentConstraint() { if (EditingMode != PEM_ConstraintEdit || !GetSelectedConstraint()) { return; } const FScopedTransaction Transaction( NSLOCTEXT("PhAT", "DeleteConstraint", "Delete Constraint") ); //Save indices before delete because delete modifies our Selected array TArray Indices; for(int32 i=0; i= 0; --i) { if(PhysicsAsset->ConstraintSetup[Indices[i]] == CopiedConstraintTemplate) { CopiedConstraintTemplate = NULL; } PhysicsAsset->Modify(); FPhysicsAssetUtils::DestroyConstraint(PhysicsAsset, Indices[i]); } SetSelectedConstraint(INDEX_NONE); HierarchyChangedEvent.Broadcast(); PreviewChangedEvent.Broadcast(); } void FPhATSharedData::ToggleInstanceProperties() { bShowInstanceProps = !bShowInstanceProps; PreviewChangedEvent.Broadcast(); if (EditingMode == PEM_ConstraintEdit) { if (GetSelectedConstraint()) { UPhysicsConstraintTemplate* ConSetup = PhysicsAsset->ConstraintSetup[GetSelectedConstraint()->Index]; FSelection Selection(GetSelectedConstraint()->Index, KPT_Unknown, INDEX_NONE); SelectionChangedEvent.Broadcast(ConSetup, &Selection); } } else if (EditingMode == PEM_BodyEdit) { if (GetSelectedBody()) { UBodySetup* BodySetup = PhysicsAsset->BodySetup[GetSelectedBody()->Index]; // Set properties dialog to display selected bone (or bone instance) info. SelectionChangedEvent.Broadcast(BodySetup, GetSelectedBody()); } } } void FPhATSharedData::ToggleSimulation() { // don't start simulation if there are no bodies or if we are manipulating a body if (PhysicsAsset->BodySetup.Num() == 0 || bManipulating) { return; } EnableSimulation(!bRunningSimulation); bRunningSimulation = !bRunningSimulation; } void FPhATSharedData::EnableSimulation(bool bEnableSimulation) { if (bEnableSimulation) { // Flush geometry cache inside the asset (don't want to use cached version of old geometry!) PhysicsAsset->InvalidateAllPhysicsMeshes(); // We should not already have an instance (destroyed when stopping sim). EditorSkelComp->SetSimulatePhysics(true); EditorSkelComp->SetPhysicsBlendWeight(EditorSimOptions->PhysicsBlend); EditorSkelComp->InitArticulated(PreviewScene.GetWorld()->GetPhysicsScene()); // Make it start simulating EditorSkelComp->WakeAllRigidBodies(); // Set the properties window to point at the simulation options object. SelectionChangedEvent.Broadcast(EditorSimOptions, NULL); } else { // Stop any animation and clear node when stopping simulation. EditorSkelComp->SetAnimation(NULL); // Turn off/remove the physics instance for this thing, and move back to start location. EditorSkelComp->TermArticulated(); EditorSkelComp->SetSimulatePhysics(false); EditorSkelComp->SetPhysicsBlendWeight(0.f); // Since simulation, actor location changes. Reset to identity EditorSkelComp->SetWorldTransform(ResetTM); // Force an update of the skeletal mesh to get it back to ref pose EditorSkelComp->RefreshBoneTransforms(); PreviewChangedEvent.Broadcast(); // Put properties window back to selected. if (EditingMode == FPhATSharedData::PEM_BodyEdit) { SetSelectedBody(NULL, true); } else { SetSelectedConstraint(INDEX_NONE, true); } } } void FPhATSharedData::OpenNewBodyDlg() { OpenNewBodyDlg(&NewBodyData, &NewBodyResponse); } void FPhATSharedData::OpenNewBodyDlg(FPhysAssetCreateParams* NewBodyData, EAppReturnType::Type* NewBodyResponse) { auto ModalWindow = SNew(SWindow) .Title( NSLOCTEXT("PhAT", "NewAssetTitle", "New Asset") ) .SizingRule( ESizingRule::Autosized ) .SupportsMinimize(false) .SupportsMaximize(false); auto MessageBox = SNew(SPhATNewAssetDlg) .ParentWindow(ModalWindow) .NewBodyData(NewBodyData) .NewBodyResponse(NewBodyResponse); ModalWindow->SetContent(MessageBox); GEditor->EditorAddModalWindow(ModalWindow); } void FPhATSharedData::PostUndo() { if (bRunningSimulation) { return; } bool bInvalidSelection = false; for (int32 BodyIndex = 0; BodyIndex < SelectedBodies.Num() && bInvalidSelection == false; ++BodyIndex) { const FSelection& Selection = SelectedBodies[BodyIndex]; if (PhysicsAsset->BodySetup.Num() <= Selection.Index) { bInvalidSelection = true; } else { if (UBodySetup * BodySetup = PhysicsAsset->BodySetup[Selection.Index]) { switch (Selection.PrimitiveType) { case KPT_Box: bInvalidSelection = BodySetup->AggGeom.BoxElems.Num() <= Selection.PrimitiveIndex ? true : bInvalidSelection; break; case KPT_Convex: bInvalidSelection = BodySetup->AggGeom.ConvexElems.Num() <= Selection.PrimitiveIndex ? true : bInvalidSelection; break; case KPT_Sphere: bInvalidSelection = BodySetup->AggGeom.SphereElems.Num() <= Selection.PrimitiveIndex ? true : bInvalidSelection; break; case KPT_Sphyl: bInvalidSelection = BodySetup->AggGeom.SphylElems.Num() <= Selection.PrimitiveIndex ? true : bInvalidSelection; break; default: bInvalidSelection = true; } } else { bInvalidSelection = true; } } } for (int32 ConstraintIndex = 0; ConstraintIndex < SelectedConstraints.Num() && bInvalidSelection == false; ++ConstraintIndex) { const FSelection& Selection = SelectedConstraints[ConstraintIndex]; if (PhysicsAsset->ConstraintSetup.Num() <= Selection.Index) { bInvalidSelection = true; } } if (bInvalidSelection) { // Clear selection before we undo. We don't transact the editor itself - don't want to have something selected that is then removed. SetSelectedBody(NULL); SetSelectedConstraint(INDEX_NONE); } PreviewChangedEvent.Broadcast(); HierarchyChangedEvent.Broadcast(); } void FPhATSharedData::Redo() { if (bRunningSimulation) { return; } SetSelectedBody(NULL); SetSelectedConstraint(INDEX_NONE); GEditor->RedoTransaction(); PhysicsAsset->UpdateBodySetupIndexMap(); PreviewChangedEvent.Broadcast(); HierarchyChangedEvent.Broadcast(); } #undef LOCTEXT_NAMESPACE#include using namespace std; typedef long long int ll; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int t; cin>>t; while(t--) { int n; cin>>n; int arr[n]; for(int i=0;i>arr[i]; int flag = 1; int ans = 1; for(int i=0;i * * 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. * * In no event and under no legal theory, whether in tort (including negligence), * contract, or otherwise, unless required by applicable law (such as deliberate * and grossly negligent acts) or agreed to in writing, shall any Contributor be * liable for any damages, including any direct, indirect, special, incidental, * or consequential damages of any character arising as a result of this License or * out of the use or inability to use the software (including but not limited to damages * for loss of goodwill, work stoppage, computer failure or malfunction, or any and * all other commercial damages or losses), even if such Contributor has been advised * of the possibility of such damages. */ #include #include "HashUtils.hpp" #include "gtest/gtest.h" using namespace Diligent; namespace { TEST(Common_HashUtils, HashMapStringKey) { { const char* Str = "Test String"; HashMapStringKey Key1{Str}; EXPECT_EQ(Key1.GetStr(), Str); EXPECT_STREQ(Key1.GetStr(), Str); HashMapStringKey Key2{Str, true}; EXPECT_NE(Key2.GetStr(), Str); EXPECT_STREQ(Key2.GetStr(), Str); EXPECT_EQ(Key1, Key1); EXPECT_EQ(Key2, Key2); EXPECT_EQ(Key1, Key2); HashMapStringKey Key3{std::string{Str}}; EXPECT_NE(Key3.GetStr(), Str); EXPECT_STREQ(Key3.GetStr(), Str); EXPECT_EQ(Key3, Key1); EXPECT_EQ(Key3, Key2); EXPECT_EQ(Key3, Key3); } { const char* Str1 = "Test String 1"; const char* Str2 = "Test String 2"; HashMapStringKey Key1{Str1}; HashMapStringKey Key2{Str2, true}; EXPECT_NE(Key1, Key2); HashMapStringKey Key3{std::move(Key1)}; EXPECT_NE(Key1, Key2); EXPECT_NE(Key2, Key1); HashMapStringKey Key4{std::move(Key2)}; EXPECT_EQ(Key1, Key2); EXPECT_EQ(Key2, Key1); EXPECT_NE(Key3, Key4); } { std::unordered_map TestMap; const char* Str1 = "String1"; const char* Str2 = "String2"; const char* Str3 = "String3"; const int Val1 = 1; const int Val2 = 2; auto it_ins = TestMap.emplace(HashMapStringKey{Str1, true}, Val1); EXPECT_TRUE(it_ins.second); EXPECT_NE(it_ins.first->first.GetStr(), Str1); EXPECT_STREQ(it_ins.first->first.GetStr(), Str1); it_ins = TestMap.emplace(Str2, Val2); EXPECT_TRUE(it_ins.second); EXPECT_EQ(it_ins.first->first, Str2); auto it = TestMap.find(Str1); ASSERT_NE(it, TestMap.end()); EXPECT_EQ(it->second, Val1); EXPECT_NE(it->first.GetStr(), Str1); EXPECT_STREQ(it->first.GetStr(), Str1); it = TestMap.find(Str2); ASSERT_NE(it, TestMap.end()); EXPECT_EQ(it->second, Val2); EXPECT_EQ(it->first.GetStr(), Str2); it = TestMap.find(Str3); EXPECT_EQ(it, TestMap.end()); it = TestMap.find(HashMapStringKey{std::string{Str3}}); EXPECT_EQ(it, TestMap.end()); } } } // namespace /* * Copyright (C) 2008-2010, 2012, . * * This software is provided "as is" without warranty of any kind, * either expressed or implied, including but not limited to the * implied warranties of fitness for a particular purpose. * * See the LICENSE file for more information. */ #ifndef FLOWER_FLOWER_HH # define FLOWER_FLOWER_HH # include # include namespace flower { /// Transform goto-like control-flow structures into tag-based code. /// /// The following syntactic constructs are eliminated: /// - "break", "continue" (which impacts "while" and "foreach") /// - "return" (which impacts "function", not "closure"). class Flower : public ast::Analyzer { public: typedef ast::Analyzer super_type; using super_type::visit; Flower(); protected: CONST_VISITOR_VISIT_NODES((Break) (Catch) (Continue) (Foreach) (Return) (Routine) (Throw) (Try) (While)); private: void err(const ast::loc& loc, const std::string& msg); bool has_break_; bool has_continue_; bool has_general_catch_; bool has_return_; bool in_catch_; bool in_function_; bool in_loop_; unsigned int catch_all_; }; } // namespace flower #endif // FLOWER_FLOWER_HH //--------------------------------------------------------------------------- // File: // BFFileHelper.cpp BFFileHelper.hpp // // Module: // CBFFileHelper // // History: // May. 7, 2002 Created by //--------------------------------------------------------------------------- #include "BFPch.h" #if !defined(BFFILEHELPER_H) #include "BFFileHelper.h" #endif //-------------------------------------------------------------------- //-------------------------------------------------------------------- CBFFileHelper::CBFFileHelper() { } CBFFileHelper::~CBFFileHelper() { } //-------------------------------------------------------------------- //-------------------------------------------------------------------- bool CBFFileHelper::removeFile(LPCTSTR filename) { return _tremove(filename) == 0; } //-------------------------------------------------------------------- //-------------------------------------------------------------------- void CBFFileHelper::splitPath(LPCTSTR fullPath, CString& drive, CString& dir, CString& fname, CString& ext) { TCHAR tDrive[_MAX_DRIVE]; TCHAR tDir[_MAX_DIR]; TCHAR tFname[_MAX_FNAME]; TCHAR tExt[_MAX_EXT]; _tsplitpath_s(fullPath, tDrive, tDir, tFname, tExt); drive = tDrive; dir = tDir; fname = tFname; ext = tExt; } //-------------------------------------------------------------------- //-------------------------------------------------------------------- bool CBFFileHelper::replaceExtension(LPCTSTR fname, LPCTSTR ext, CString& res) { res = fname; int dotPos = res.ReverseFind(TCHAR('.')); if (dotPos == -1) { res.Empty(); return false; } res = res.Left(dotPos + 1); res += ext; return true; }// // Copyright (c) 2014, Facebook, Inc. // All rights reserved. // // This source code is licensed under the University of Illinois/NCSA Open // Source License found in the LICENSE file in the root directory of this // source tree. An additional grant of patent rights can be found in the // PATENTS file in the same directory. // #define __DS2_LOG_CLASS_NAME__ "Session" #include "DebugServer2/GDBRemote/SessionBase.h" #include "DebugServer2/GDBRemote/SessionDelegate.h" #include "DebugServer2/GDBRemote/ProtocolHelpers.h" #include "DebugServer2/Host/Platform.h" #include "DebugServer2/Utils/HexValues.h" #include "DebugServer2/Utils/Log.h" #include #include using ds2::Host::Platform; namespace ds2 { namespace GDBRemote { SessionBase::SessionBase() : _channel(nullptr), _delegate(nullptr), _ackmode(true) { _processor.setDelegate(&_interpreter); _interpreter.setSession(this); } SessionBase::~SessionBase() { delete _channel; } bool SessionBase::create(Host::Channel *channel) { if (_channel != nullptr || channel == nullptr) return false; _channel = channel; return true; } bool SessionBase::receive(bool cooked) { if (_channel == nullptr) return false; if (!_channel->wait()) return false; std::string data; if (!_channel->receive(data)) return false; if (data.empty()) return true; if (cooked) { // // If data is 'cooked', then it has been already processed // by the Packet Processor, so we just need to forward it // to the interpreter. // _interpreter.onPacketData(data, true); return true; } return parse(data); } bool SessionBase::parse(std::string const &data) { if (data.empty()) return false; _processor.parse(data); return true; } bool SessionBase::send(std::string const &data, bool escaped) { std::ostringstream ss; std::string encoded; std::string const *datap = &data; // // If data contains $, #, } or * we need to escape the // stream. // if (!escaped && data.find_first_of("$#}*") != std::string::npos) { encoded = Escape(data); datap = &encoded; } uint8_t csum = Checksum(*datap); ss << '$' << *datap << '#' << std::hex << std::setw(2) << std::setfill('0') << (unsigned)csum; std::string final_data = ss.str(); DS2LOG(Packet, "putpkt(\"%s\", %u)", final_data.c_str(), (unsigned)final_data.length()); return _channel->send(final_data); } // // Functions used by the ProtocolInterpreter // bool SessionBase::onACK() { // TODO implement me return true; } bool SessionBase::onNAK() { // TODO implement me return true; } bool SessionBase::onCommandReceived(bool valid) { // // Send ACK or NAK if in acknowledge mode. // if (!_ackmode) return true; return valid ? sendACK() : sendNAK(); } void SessionBase::onInvalidData(std::string const &) { // // Send NAK in acknowledge mode. // sendNAK(); } // // Send commands // bool SessionBase::sendACK() { return _channel->send("+", 1) == 1; } bool SessionBase::sendNAK() { return _channel->send("-", 1) == 1; } bool SessionBase::sendError(ErrorCode code) { switch (code) { case kSuccess: return sendOK(); case kErrorUnsupported: case kErrorUnknown: return send(""); default: break; } char message[4]; message[0] = 'E'; message[1] = NibbleToHex(code >> 4); message[2] = NibbleToHex(code & 15); message[3] = '\0'; return send(message); } using ds2::GDBRemote::SessionDelegate; SessionDelegate::~SessionDelegate() = default; } } modules/iswa/util/dataprocessorkameleon.cpp /***************************************************************************************** * * * OpenSpace * * * * Copyright (c) 2014-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. * ****************************************************************************************/ #include #include #include #include #include #include #include #include namespace openspace { DataProcessorKameleon::DataProcessorKameleon() : DataProcessor() {} DataProcessorKameleon::~DataProcessorKameleon() {} std::vector DataProcessorKameleon::readMetadata(const std::string& path, glm::size3_t&) { if (path.empty()) { return std::vector(); } if ((path != _kwPath) || !_kw) { initializeKameleonWrapper(path); } std::vector opts = _kw->variables(); opts.erase( std::remove_if( opts.begin(), opts.end(), [this](const std::string& opt) { return (opt.size() > 3 || _coordinateVariables.find(opt) != _coordinateVariables.end()); } ), opts.end() ); return opts; } void DataProcessorKameleon::addDataValues(const std::string& path, properties::SelectionProperty& dataOptions) { int numOptions = static_cast(dataOptions.options().size()); initializeVectors(numOptions); if (path.empty()) { return; } if ((path != _kwPath) || !_kw) { initializeKameleonWrapper(path); } std::vector sum(numOptions, 0.f); std::vector> optionValues(numOptions, std::vector()); const std::vector& options = dataOptions.options(); const int numValues = static_cast(_dimensions.x * _dimensions.y * _dimensions.z); for (int i = 0; i < numOptions; ++i) { //0.5 to gather interesting values for the normalization/histograms. float* values = _kw->uniformSliceValues( options[i].description, _dimensions, 0.5f ); for (int j=0; j DataProcessorKameleon::processData(const std::string& path, properties::SelectionProperty& optionProp, glm::size3_t& dimensions) { const int numOptions = static_cast(optionProp.options().size()); if (path.empty()) { return std::vector(numOptions, nullptr); } if ((path != _kwPath) || !_kw) { initializeKameleonWrapper(path); } const std::vector& selectedOptions = optionProp; const std::vector& options = optionProp.options(); const int numValues = static_cast(glm::compMul(dimensions)); std::vector dataOptions(numOptions, nullptr); for (int option : selectedOptions) { dataOptions[option] = _kw->uniformSliceValues( options[option].description, dimensions, _slice ); for (int i = 0; i < numValues; i++) { const float value = dataOptions[option][i]; dataOptions[option][i] = processDataPoint(value, option); } } calculateFilterValues(selectedOptions); return dataOptions; } void DataProcessorKameleon::setSlice(float slice) { _slice = slice; } void DataProcessorKameleon::setDimensions(glm::size3_t dimensions) { _dimensions = std::move(dimensions); } void DataProcessorKameleon::initializeKameleonWrapper(std::string path) { const std::string& extension = ghoul::filesystem::File(absPath(path)).fileExtension(); if (FileSys.fileExists(absPath(path)) && extension == "cdf") { if (_kw) { _kw->close(); } _kwPath = std::move(path); _kw = std::make_shared(absPath(_kwPath)); } } } //namespace openspace ZLW07/RobWork /******************************************************************************** * Copyright 2009 The Robotics Group, The Maersk Mc-Kinney Moller Institute, * Faculty of Engineering, University of Southern Denmark * * 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 "StateData.hpp" #include "State.hpp" #include using namespace rw::kinematics; StateData::StateData (int size, const std::string& name) : _id (-1), _size (size), _name (name), _hasCache (false) { RW_ASSERT (0 <= size); } StateData::StateData (int size, const std::string& name, rw::core::Ptr< StateCache > cache) : _id (-1), _size (size), _name (name), _hasCache (true), _cache (cache) { RW_ASSERT (0 <= size); } StateData::~StateData () {} rw::core::Ptr< StateCache > StateData::getCache (const State& state) const { if (_hasCache == false) return NULL; // stop early if we know size is 0 return state.getCache (_id); } StateCache::Ptr StateData::getCache (State& state) { if (_hasCache == false) return NULL; // stop early if we know size is 0 return state.getCache (_id); } void StateData::setCache (rw::core::Ptr< StateCache > cache, State& state) { if (_hasCache == false) return; // stop early if we know size is 0 state.setCache (_id, cache); } qianbinbin/leetcode #include "StringToIntegerAtoi.h" #include using namespace lcpp; int Solution8_1::myAtoi(std::string str) { auto I = str.begin(), E = str.end(); while (I != E && *I == ' ') ++I; if (I == E) return 0; bool IsNegative = false; if (*I == '+') { ++I; } else if (*I == '-') { IsNegative = true; ++I; } const auto Limit = INT_MAX / 10; int Value = 0; for (; I != E && isdigit(*I); ++I) { if (Value > Limit || (Value == Limit && *I - '0' > 7)) return IsNegative ? INT_MIN : INT_MAX; // int overflow, dupe LeetCode compiler // Value = Value * 10 + *I - '0'; Value = Value * 10 + (*I - '0'); } return static_cast(IsNegative ? -Value : Value); } mpforums/Jupitersrc/Plugins/RenX/RenX.Core/RenX_Functions.cpp /** * Copyright (C) 2014-2017 . * * 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. * * Written by <> */ #include #include "Jupiter/Functions.h" #include "IRC_Bot.h" #include "ServerManager.h" #include "RenX_Functions.h" #include "RenX_Core.h" #include "RenX_Server.h" #include "RenX_PlayerInfo.h" using namespace Jupiter::literals; /** Team color translations */ Jupiter::ReferenceString NodColor = "04"; Jupiter::ReferenceString GDIColor = "08"; Jupiter::ReferenceString OtherColor = "14"; /** Short team name translations */ Jupiter::ReferenceString NodShortName = "Nod"; Jupiter::ReferenceString GDIShortName = "GDI"; Jupiter::ReferenceString OtherShortName = "N/A"; /** Long team name translations */ Jupiter::ReferenceString NodLongName = "Brotherhood of Nod"; Jupiter::ReferenceString GDILongName = "Global Defense Initiative"; Jupiter::ReferenceString OtherLongName = "Unknown"; /** RenegadeX RCON protocol message deliminator */ const char RenX::DelimC = '\x02'; const char RenX::DelimC3 = '\xA0'; const Jupiter::ReferenceString RenX::DevBotName = "DevBot"_jrs; /** WinType translations */ Jupiter::ReferenceString scoreWinTypeTranslation = "Domination (High Score)"; Jupiter::ReferenceString baseWinTypeTranslation = "Conquest (Base Destruction)"; Jupiter::ReferenceString beaconWinTypeTranslation = "Espionage (Beacon)"; Jupiter::ReferenceString tieWinTypeTranslation = "Draw (Tie)"; Jupiter::ReferenceString shutdownWinTypeTranslation = "Ceasefire (Shutdown)"; Jupiter::ReferenceString surrenderWinTypeTranslation = "Forfeit (Surrender)"; Jupiter::ReferenceString unknownWinTypeTranslation = "Aliens (Unknown)"; /** WinType plain translations */ Jupiter::ReferenceString scoreWinTypePlainTranslation = "High Score"; Jupiter::ReferenceString baseWinTypePlainTranslation = "Base Destruction"; Jupiter::ReferenceString beaconWinTypePlainTranslation = "Beacon"; Jupiter::ReferenceString tieWinTypePlainTranslation = "Tie"; Jupiter::ReferenceString shutdownWinTypePlainTranslation = "Shutdown"; Jupiter::ReferenceString surrenderWinTypePlainTranslation = "Surrender"; Jupiter::ReferenceString unknownWinTypePlainTranslation = "Unknown"; /** Vote translations */ Jupiter::ReferenceString translated_VoteMenuChoice_AddBots = STRING_LITERAL_AS_REFERENCE("Add Bots"); Jupiter::ReferenceString translated_VoteMenuChoice_ChangeMap = STRING_LITERAL_AS_REFERENCE("Change Map"); Jupiter::ReferenceString translated_VoteMenuChoice_Donate = STRING_LITERAL_AS_REFERENCE("Donate"); Jupiter::ReferenceString translated_VoteMenuChoice_Kick = STRING_LITERAL_AS_REFERENCE("Kick"); Jupiter::ReferenceString translated_VoteMenuChoice_RemoveBots = STRING_LITERAL_AS_REFERENCE("Remove Bots"); Jupiter::ReferenceString translated_VoteMenuChoice_RestartMatch = STRING_LITERAL_AS_REFERENCE("Restart Match"); Jupiter::ReferenceString translated_VoteMenuChoice_StartMatch = STRING_LITERAL_AS_REFERENCE("Start Match"); Jupiter::ReferenceString translated_VoteMenuChoice_Survey = STRING_LITERAL_AS_REFERENCE("Survey"); /** Object / damage type translations */ /** Nod Vehicles */ Jupiter::ReferenceString translated_Vehicle_Harvester_Nod = STRING_LITERAL_AS_REFERENCE("Nod Harvester"); Jupiter::ReferenceString translated_Vehicle_Buggy = STRING_LITERAL_AS_REFERENCE("Buggy"); Jupiter::ReferenceString translated_Vehicle_Artillery = STRING_LITERAL_AS_REFERENCE("Mobile Artillery"); Jupiter::ReferenceString translated_Vehicle_APC_Nod = STRING_LITERAL_AS_REFERENCE("Nod APC"); Jupiter::ReferenceString translated_Vehicle_LightTank = STRING_LITERAL_AS_REFERENCE("Light Tank"); Jupiter::ReferenceString translated_Vehicle_FlameTank = STRING_LITERAL_AS_REFERENCE("Flame Tank"); Jupiter::ReferenceString translated_Vehicle_StealthTank = STRING_LITERAL_AS_REFERENCE("Stealth Tank"); Jupiter::ReferenceString translated_Vehicle_Chinook_Nod = STRING_LITERAL_AS_REFERENCE("Nod Chinook"); Jupiter::ReferenceString translated_Vehicle_Apache = STRING_LITERAL_AS_REFERENCE("Apache"); Jupiter::ReferenceString translated_Vehicle_ReconBike = STRING_LITERAL_AS_REFERENCE("Recon Bike"); Jupiter::ReferenceString translated_Vehicle_TickTank = STRING_LITERAL_AS_REFERENCE("Tick Tank"); /** GDI Vehicles */ Jupiter::ReferenceString translated_Vehicle_Harvester_GDI = STRING_LITERAL_AS_REFERENCE("GDI Harvester"); Jupiter::ReferenceString translated_Vehicle_Humvee = STRING_LITERAL_AS_REFERENCE("Humvee"); Jupiter::ReferenceString translated_Vehicle_MRLS = STRING_LITERAL_AS_REFERENCE("Mobile Rocket Launcher System"); Jupiter::ReferenceString translated_Vehicle_APC_GDI = STRING_LITERAL_AS_REFERENCE("GDI APC"); Jupiter::ReferenceString translated_Vehicle_MediumTank = STRING_LITERAL_AS_REFERENCE("Medium Tank"); Jupiter::ReferenceString translated_Vehicle_MammothTank = STRING_LITERAL_AS_REFERENCE("Mammoth Tank"); Jupiter::ReferenceString translated_Vehicle_Chinook_GDI = STRING_LITERAL_AS_REFERENCE("GDI Chinook"); Jupiter::ReferenceString translated_Vehicle_Orca = STRING_LITERAL_AS_REFERENCE("Orca"); Jupiter::ReferenceString translated_Vehicle_HoverMRLS = STRING_LITERAL_AS_REFERENCE("Hover MRLS"); Jupiter::ReferenceString translated_Vehicle_Titan = STRING_LITERAL_AS_REFERENCE("Titan"); Jupiter::ReferenceString translated_Vehicle_Wolverine = STRING_LITERAL_AS_REFERENCE("Wolverine"); /** Other Vehicles */ Jupiter::ReferenceString translated_Vehicle_A10_DmgType_GattlingGun = STRING_LITERAL_AS_REFERENCE("A10 Thunderbolt Gattling Gun"); Jupiter::ReferenceString translated_Vehicle_A10_DmgType_Bomb = STRING_LITERAL_AS_REFERENCE("A10 Thunderbolt Bomb"); Jupiter::ReferenceString translated_Vehicle_AC130_DmgType_HeavyCannon = STRING_LITERAL_AS_REFERENCE("AC130 Heavy Cannon"); Jupiter::ReferenceString translated_Vehicle_AC130_DmgType_AutoCannon = STRING_LITERAL_AS_REFERENCE("AC130 Auto Cannon"); /** Weapons */ Jupiter::ReferenceString translated_Weapon_HeavyPistol = STRING_LITERAL_AS_REFERENCE("Heavy Pistol"); Jupiter::ReferenceString translated_Weapon_Carbine = STRING_LITERAL_AS_REFERENCE("Carbine"); Jupiter::ReferenceString translated_Weapon_Airstrike_GDI = STRING_LITERAL_AS_REFERENCE("GDI Airstrike"); Jupiter::ReferenceString translated_Weapon_Airstrike_Nod = STRING_LITERAL_AS_REFERENCE("Nod Airstrike"); Jupiter::ReferenceString translated_Weapon_TiberiumFlechetteRifle = STRING_LITERAL_AS_REFERENCE("Tiberium Flechette Gun"); Jupiter::ReferenceString translated_Weapon_TiberiumAutoRifle = STRING_LITERAL_AS_REFERENCE("Tiberium Automatic Rifle"); Jupiter::ReferenceString translated_Weapon_TiberiumAutoRifle_Blue = STRING_LITERAL_AS_REFERENCE("Blue Tiberium Automatic Rifle Burst"); Jupiter::ReferenceString translated_Weapon_EMPGrenade = STRING_LITERAL_AS_REFERENCE("EMP Grenade"); Jupiter::ReferenceString translated_Weapon_SmokeGrenade = STRING_LITERAL_AS_REFERENCE("Smoke Grenade"); Jupiter::ReferenceString translated_Weapon_TimedC4 = STRING_LITERAL_AS_REFERENCE("Timed C4"); Jupiter::ReferenceString translated_Weapon_RemoteC4 = STRING_LITERAL_AS_REFERENCE("Remote C4"); Jupiter::ReferenceString translated_Weapon_ProxyC4 = STRING_LITERAL_AS_REFERENCE("Proximity C4"); Jupiter::ReferenceString translated_Weapon_ATMine = STRING_LITERAL_AS_REFERENCE("Anti-Tank Mine"); Jupiter::ReferenceString translated_Weapon_IonCannonBeacon = STRING_LITERAL_AS_REFERENCE("Ion Cannon Beacon"); Jupiter::ReferenceString translated_Weapon_NukeBeacon = STRING_LITERAL_AS_REFERENCE("Nuclear Missile Beacon"); Jupiter::ReferenceString translated_Weapon_DeployedC4 = STRING_LITERAL_AS_REFERENCE("Timed C4"); Jupiter::ReferenceString translated_Weapon_DeployedTimedC4 = STRING_LITERAL_AS_REFERENCE("Timed C4"); Jupiter::ReferenceString translated_Weapon_DeployedRemoteC4 = STRING_LITERAL_AS_REFERENCE("Remote C4"); Jupiter::ReferenceString translated_Weapon_DeployedProxyC4 = STRING_LITERAL_AS_REFERENCE("Proximity C4"); Jupiter::ReferenceString translated_Weapon_DeployedATMine = STRING_LITERAL_AS_REFERENCE("Anti-Tank Mine"); Jupiter::ReferenceString translated_Weapon_DeployedIonCannonBeacon = STRING_LITERAL_AS_REFERENCE("Ion Cannon Beacon"); Jupiter::ReferenceString translated_Weapon_DeployedNukeBeacon = STRING_LITERAL_AS_REFERENCE("Nuclear Missile Beacon"); Jupiter::ReferenceString translated_Weapon_CrateNuke = STRING_LITERAL_AS_REFERENCE("Nuclear Crate Explosion"); Jupiter::ReferenceString translated_Weapon_DevNuke = STRING_LITERAL_AS_REFERENCE("Nuclear Dev Explosion"); /** Projectiles */ Jupiter::ReferenceString translated_Projectile_EMPGrenade = STRING_LITERAL_AS_REFERENCE("EMP Grenade"); Jupiter::ReferenceString translated_Projectile_SmokeGrenade = STRING_LITERAL_AS_REFERENCE("Smoke Grenade"); /** GDI Characters */ Jupiter::ReferenceString translated_GDI_Deadeye = STRING_LITERAL_AS_REFERENCE("Deadeye"); Jupiter::ReferenceString translated_GDI_Engineer = STRING_LITERAL_AS_REFERENCE("GDI Engineer"); Jupiter::ReferenceString translated_GDI_Grenadier = STRING_LITERAL_AS_REFERENCE("Grenadier"); Jupiter::ReferenceString translated_GDI_Gunner = STRING_LITERAL_AS_REFERENCE("Gunner"); Jupiter::ReferenceString translated_GDI_Havoc = STRING_LITERAL_AS_REFERENCE("Havoc"); Jupiter::ReferenceString translated_GDI_Hotwire = STRING_LITERAL_AS_REFERENCE("Hotwire"); Jupiter::ReferenceString translated_GDI_Marksman = STRING_LITERAL_AS_REFERENCE("GDI Marksman"); Jupiter::ReferenceString translated_GDI_McFarland = STRING_LITERAL_AS_REFERENCE("McFarland"); Jupiter::ReferenceString translated_GDI_Mobius = STRING_LITERAL_AS_REFERENCE("Mobius"); Jupiter::ReferenceString translated_GDI_Officer = STRING_LITERAL_AS_REFERENCE("GDI Officer"); Jupiter::ReferenceString translated_GDI_Patch = STRING_LITERAL_AS_REFERENCE("Patch"); Jupiter::ReferenceString translated_GDI_RocketSoldier = STRING_LITERAL_AS_REFERENCE("GDI Rocket Soldier"); Jupiter::ReferenceString translated_GDI_Shotgunner = STRING_LITERAL_AS_REFERENCE("GDI Shotgunner"); Jupiter::ReferenceString translated_GDI_Soldier = STRING_LITERAL_AS_REFERENCE("GDI Soldier"); Jupiter::ReferenceString translated_GDI_Sydney = STRING_LITERAL_AS_REFERENCE("Sydney"); /** Nod Characters */ Jupiter::ReferenceString translated_Nod_BlackHandSniper = STRING_LITERAL_AS_REFERENCE("Black Hand Sniper"); Jupiter::ReferenceString translated_Nod_ChemicalTrooper = STRING_LITERAL_AS_REFERENCE("Chemical Trooper"); Jupiter::ReferenceString translated_Nod_Engineer = STRING_LITERAL_AS_REFERENCE("Nod Engineer"); Jupiter::ReferenceString translated_Nod_FlameTrooper = STRING_LITERAL_AS_REFERENCE("Flame Trooper"); Jupiter::ReferenceString translated_Nod_LaserChainGunner = STRING_LITERAL_AS_REFERENCE("Laser Chain Gunner"); Jupiter::ReferenceString translated_Nod_Marksman = STRING_LITERAL_AS_REFERENCE("Nod Marksman"); Jupiter::ReferenceString translated_Nod_Mendoza = STRING_LITERAL_AS_REFERENCE("Mendoza"); Jupiter::ReferenceString translated_Nod_Officer = STRING_LITERAL_AS_REFERENCE("Nod Officer"); Jupiter::ReferenceString translated_Nod_Raveshaw = STRING_LITERAL_AS_REFERENCE("Raveshaw"); Jupiter::ReferenceString translated_Nod_RocketSoldier = STRING_LITERAL_AS_REFERENCE("Nod Rocket Soldier"); Jupiter::ReferenceString translated_Nod_Sakura = STRING_LITERAL_AS_REFERENCE("Sakura"); Jupiter::ReferenceString translated_Nod_Shotgunner = STRING_LITERAL_AS_REFERENCE("Nod Shotgunner"); Jupiter::ReferenceString translated_Nod_Soldier = STRING_LITERAL_AS_REFERENCE("Nod Soldier"); Jupiter::ReferenceString translated_Nod_StealthBlackHand = STRING_LITERAL_AS_REFERENCE("Stealth Black Hand"); Jupiter::ReferenceString translated_Nod_Technician = STRING_LITERAL_AS_REFERENCE("Technician"); /** Non-weapon damage types */ Jupiter::ReferenceString translated_DmgType_Suicided = STRING_LITERAL_AS_REFERENCE("Suicide"); Jupiter::ReferenceString translated_DmgType_Fell = STRING_LITERAL_AS_REFERENCE("Fall"); Jupiter::ReferenceString translated_DmgType_Tiberium = STRING_LITERAL_AS_REFERENCE("Tiberium"); Jupiter::ReferenceString translated_DmgType_TiberiumBleed = STRING_LITERAL_AS_REFERENCE("Tiberium Decay"); Jupiter::ReferenceString translated_DmgType_TiberiumBleed_Blue = STRING_LITERAL_AS_REFERENCE("Blue Tiberium Decay"); Jupiter::ReferenceString translated_DmgType_RanOver = STRING_LITERAL_AS_REFERENCE("Crushed"); /** Infantry weapons */ Jupiter::ReferenceString translated_DmgType_Pistol = STRING_LITERAL_AS_REFERENCE("Pistol"); Jupiter::ReferenceString translated_DmgType_SMG = STRING_LITERAL_AS_REFERENCE("Machine Pistol"); Jupiter::ReferenceString translated_DmgType_HeavyPistol = STRING_LITERAL_AS_REFERENCE("Heavy Pistol"); Jupiter::ReferenceString translated_DmgType_Carbine = STRING_LITERAL_AS_REFERENCE("Carbine"); Jupiter::ReferenceString translated_DmgType_TiberiumFlechetteRifle = STRING_LITERAL_AS_REFERENCE("Tiberium Flechette Gun"); // Not a rifle. Jupiter::ReferenceString translated_DmgType_TiberiumAutoRifle = STRING_LITERAL_AS_REFERENCE("Tiberium Automatic Rifle"); Jupiter::ReferenceString translated_DmgType_TiberiumAutoRifle_Blue = STRING_LITERAL_AS_REFERENCE("Blue Tiberium Automatic Rifle Burst"); Jupiter::ReferenceString translated_DmgType_TiberiumAutoRifle_Flechette_Blue = STRING_LITERAL_AS_REFERENCE("Blue Tiberium Automatic Rifle"); Jupiter::ReferenceString translated_DmgType_Grenade = STRING_LITERAL_AS_REFERENCE("Grenade"); Jupiter::ReferenceString translated_DmgType_TimedC4 = STRING_LITERAL_AS_REFERENCE("Timed C4"); Jupiter::ReferenceString translated_DmgType_RemoteC4 = STRING_LITERAL_AS_REFERENCE("Remote C4"); Jupiter::ReferenceString translated_DmgType_ProxyC4 = STRING_LITERAL_AS_REFERENCE("Proximity C4"); Jupiter::ReferenceString translated_DmgType_ATMine = STRING_LITERAL_AS_REFERENCE("Anti-Tank Mine"); Jupiter::ReferenceString translated_DmgType_EMPGrenade = STRING_LITERAL_AS_REFERENCE("EMP Grenade"); Jupiter::ReferenceString translated_DmgType_BurnC4 = STRING_LITERAL_AS_REFERENCE("C4 Burn"); Jupiter::ReferenceString translated_DmgType_FireBleed = STRING_LITERAL_AS_REFERENCE("Fire Burn"); // Caused by C4 or flame weapons Jupiter::ReferenceString translated_DmgType_AutoRifle = STRING_LITERAL_AS_REFERENCE("Automatic Rifle"); Jupiter::ReferenceString translated_DmgType_Shotgun = STRING_LITERAL_AS_REFERENCE("Shotgun"); Jupiter::ReferenceString translated_DmgType_FlameThrower = STRING_LITERAL_AS_REFERENCE("Flamethrower"); Jupiter::ReferenceString translated_DmgType_GrenadeLauncher = STRING_LITERAL_AS_REFERENCE("Grenade Launcher"); Jupiter::ReferenceString translated_DmgType_MarksmanRifle = STRING_LITERAL_AS_REFERENCE("Marksman's Rifle"); Jupiter::ReferenceString translated_DmgType_ChainGun = STRING_LITERAL_AS_REFERENCE("Chain Gun"); Jupiter::ReferenceString translated_DmgType_MissileLauncher = STRING_LITERAL_AS_REFERENCE("Missile Launcher"); Jupiter::ReferenceString translated_DmgType_MissileLauncher_Alt = STRING_LITERAL_AS_REFERENCE("Missile Launcher"); Jupiter::ReferenceString translated_DmgType_ChemicalThrower = STRING_LITERAL_AS_REFERENCE("Chemical Spray Gun"); Jupiter::ReferenceString translated_DmgType_LaserRifle = STRING_LITERAL_AS_REFERENCE("Laser Rifle"); Jupiter::ReferenceString translated_DmgType_TacticalRifle = STRING_LITERAL_AS_REFERENCE("Tactical Rifle"); Jupiter::ReferenceString translated_DmgType_RocketLauncher = STRING_LITERAL_AS_REFERENCE("Rocket Launcher"); Jupiter::ReferenceString translated_DmgType_LaserChainGun = STRING_LITERAL_AS_REFERENCE("Laser Chain Gun"); Jupiter::ReferenceString translated_DmgType_FlakCannon = STRING_LITERAL_AS_REFERENCE("Flak"); Jupiter::ReferenceString translated_DmgType_FlakCannon_Alt = STRING_LITERAL_AS_REFERENCE("Concentrated Flak"); Jupiter::ReferenceString translated_DmgType_SniperRifle = STRING_LITERAL_AS_REFERENCE("Sniper Rifle"); Jupiter::ReferenceString translated_DmgType_RamjetRifle = STRING_LITERAL_AS_REFERENCE("Ramjet"); Jupiter::ReferenceString translated_DmgType_Railgun = STRING_LITERAL_AS_REFERENCE("Railgun"); Jupiter::ReferenceString translated_DmgType_PersonalIonCannon = STRING_LITERAL_AS_REFERENCE("Personal Ion Cannon"); Jupiter::ReferenceString translated_DmgType_VoltRifle = STRING_LITERAL_AS_REFERENCE("Volt Rifle"); Jupiter::ReferenceString translated_DmgType_VoltRifle_Alt = STRING_LITERAL_AS_REFERENCE("Volt Rifle Burst"); Jupiter::ReferenceString translated_DmgType_VoltAutoRifle = STRING_LITERAL_AS_REFERENCE("Volt Automatic Rifle"); Jupiter::ReferenceString translated_DmgType_VoltAutoRifle_Alt = STRING_LITERAL_AS_REFERENCE("Volt Automatic Rifle Burst"); /** Vehicle weapons */ Jupiter::ReferenceString translated_DmgType_MammothTank_Missile = STRING_LITERAL_AS_REFERENCE("Mammoth Tank Missile"); Jupiter::ReferenceString translated_DmgType_MammothTank_Cannon = STRING_LITERAL_AS_REFERENCE("Mammoth Tank Cannon"); Jupiter::ReferenceString translated_DmgType_Orca_Missile = STRING_LITERAL_AS_REFERENCE("Orca Missile"); Jupiter::ReferenceString translated_DmgType_Orca_Gun = STRING_LITERAL_AS_REFERENCE("Orca Gun"); Jupiter::ReferenceString translated_DmgType_Orca_Passenger = STRING_LITERAL_AS_REFERENCE("Orca Passenger Missile"); Jupiter::ReferenceString translated_DmgType_Apache_Rocket = STRING_LITERAL_AS_REFERENCE("Apache Rocket"); Jupiter::ReferenceString translated_DmgType_Apache_Gun = STRING_LITERAL_AS_REFERENCE("Apache Gun"); Jupiter::ReferenceString translated_DmgType_Apache_Passenger = STRING_LITERAL_AS_REFERENCE("Apache Passenger Missile"); /** Other weapons */ Jupiter::ReferenceString translated_DmgType_AGT_MG = STRING_LITERAL_AS_REFERENCE("Machine Gun"); Jupiter::ReferenceString translated_DmgType_AGT_Rocket = STRING_LITERAL_AS_REFERENCE("Rocket"); Jupiter::ReferenceString translated_DmgType_Obelisk = STRING_LITERAL_AS_REFERENCE("Obelisk Laser"); Jupiter::ReferenceString translated_DmgType_GuardTower = STRING_LITERAL_AS_REFERENCE("Guard Tower"); Jupiter::ReferenceString translated_DmgType_Turret = STRING_LITERAL_AS_REFERENCE("Turret"); Jupiter::ReferenceString translated_DmgType_SAMSite = STRING_LITERAL_AS_REFERENCE("SAM Site"); Jupiter::ReferenceString translated_DmgType_AATower = STRING_LITERAL_AS_REFERENCE("Anti-Air Guard Tower"); Jupiter::ReferenceString translated_DmgType_GunEmpl = STRING_LITERAL_AS_REFERENCE("Gun Emplacement Gattling Gun"); Jupiter::ReferenceString translated_DmgType_GunEmpl_Alt = STRING_LITERAL_AS_REFERENCE("Gun Emplacement Automatic Cannon"); Jupiter::ReferenceString translated_DmgType_RocketEmpl_Swarm = STRING_LITERAL_AS_REFERENCE("Rocket Emplacement Swarm Missile"); Jupiter::ReferenceString translated_DmgType_RocketEmpl_Missile = STRING_LITERAL_AS_REFERENCE("Rocket Emplacement Hellfire Missile"); Jupiter::ReferenceString translated_DmgType_Nuke = STRING_LITERAL_AS_REFERENCE("Nuclear Missile Strike"); Jupiter::ReferenceString translated_DmgType_IonCannon = STRING_LITERAL_AS_REFERENCE("Ion Cannon Strike"); /** Nod Vehicles */ Jupiter::ReferenceString translated_DmgType_Harvester_Nod = STRING_LITERAL_AS_REFERENCE("Nod Harvester"); Jupiter::ReferenceString translated_DmgType_Buggy = STRING_LITERAL_AS_REFERENCE("Buggy"); Jupiter::ReferenceString translated_DmgType_Artillery = STRING_LITERAL_AS_REFERENCE("Mobile Artillery"); Jupiter::ReferenceString translated_DmgType_APC_Nod = STRING_LITERAL_AS_REFERENCE("Nod APC"); Jupiter::ReferenceString translated_DmgType_LightTank = STRING_LITERAL_AS_REFERENCE("Light Tank"); Jupiter::ReferenceString translated_DmgType_FlameTank = STRING_LITERAL_AS_REFERENCE("Flame Tank"); Jupiter::ReferenceString translated_DmgType_StealthTank = STRING_LITERAL_AS_REFERENCE("Stealth Tank"); Jupiter::ReferenceString translated_DmgType_Chinook_Nod = STRING_LITERAL_AS_REFERENCE("Nod Chinook"); Jupiter::ReferenceString translated_DmgType_Apache = STRING_LITERAL_AS_REFERENCE("Apache"); Jupiter::ReferenceString translated_Vehicle_ReconBike_DmgType = STRING_LITERAL_AS_REFERENCE("Recon Bike"); Jupiter::ReferenceString translated_Vehicle_TickTank_DmgType = STRING_LITERAL_AS_REFERENCE("Tick Tank"); /** GDI Vehicles */ Jupiter::ReferenceString translated_DmgType_Harvester_GDI = STRING_LITERAL_AS_REFERENCE("GDI Harvester"); Jupiter::ReferenceString translated_DmgType_Humvee = STRING_LITERAL_AS_REFERENCE("Humvee"); Jupiter::ReferenceString translated_DmgType_MRLS = STRING_LITERAL_AS_REFERENCE("Mobile Rocket Launcher System"); Jupiter::ReferenceString translated_DmgType_APC_GDI = STRING_LITERAL_AS_REFERENCE("GDI APC"); Jupiter::ReferenceString translated_DmgType_MediumTank = STRING_LITERAL_AS_REFERENCE("Medium Tank"); Jupiter::ReferenceString translated_DmgType_MammothTank = STRING_LITERAL_AS_REFERENCE("Mammoth Tank"); Jupiter::ReferenceString translated_DmgType_Chinook_GDI = STRING_LITERAL_AS_REFERENCE("GDI Chinook"); Jupiter::ReferenceString translated_DmgType_Orca = STRING_LITERAL_AS_REFERENCE("Orca"); Jupiter::ReferenceString translated_Vehicle_HoverMRLS_DmgType = STRING_LITERAL_AS_REFERENCE("Hover MRLS"); Jupiter::ReferenceString translated_Vehicle_Titan_DmgType = STRING_LITERAL_AS_REFERENCE("Titan"); Jupiter::ReferenceString translated_Vehicle_Wolverine_DmgType = STRING_LITERAL_AS_REFERENCE("Wolverine"); /** Other Vehicles */ Jupiter::ReferenceString translated_DmgType_A10_Missile = STRING_LITERAL_AS_REFERENCE("A10 Missile"); /** Nod structures */ Jupiter::ReferenceString translated_Building_HandOfNod = STRING_LITERAL_AS_REFERENCE("Hand of Nod"); Jupiter::ReferenceString translated_Building_AirTower = STRING_LITERAL_AS_REFERENCE("Airstrip"); Jupiter::ReferenceString translated_Building_Airstrip = STRING_LITERAL_AS_REFERENCE("Airstrip"); Jupiter::ReferenceString translated_Building_Refinery_Nod = STRING_LITERAL_AS_REFERENCE("Nod Refinery"); Jupiter::ReferenceString translated_Building_PowerPlant_Nod = STRING_LITERAL_AS_REFERENCE("Nod Power Plant"); Jupiter::ReferenceString translated_Building_HandOfNod_Internals = STRING_LITERAL_AS_REFERENCE("Hand of Nod"); Jupiter::ReferenceString translated_Building_AirTower_Internals = STRING_LITERAL_AS_REFERENCE("Airstrip"); Jupiter::ReferenceString translated_Building_Airstrip_Internals = STRING_LITERAL_AS_REFERENCE("Airstrip"); Jupiter::ReferenceString translated_Building_Refinery_Nod_Internals = STRING_LITERAL_AS_REFERENCE("Nod Refinery"); Jupiter::ReferenceString translated_Building_PowerPlant_Nod_Internals = STRING_LITERAL_AS_REFERENCE("Nod Power Plant"); /** GDI structures */ Jupiter::ReferenceString translated_Building_Barracks = STRING_LITERAL_AS_REFERENCE("Barracks"); Jupiter::ReferenceString translated_Building_WeaponsFactory = STRING_LITERAL_AS_REFERENCE("Weapons Factory"); Jupiter::ReferenceString translated_Building_Refinery_GDI = STRING_LITERAL_AS_REFERENCE("GDI Refinery"); Jupiter::ReferenceString translated_Building_PowerPlant_GDI = STRING_LITERAL_AS_REFERENCE("GDI Power Plant"); Jupiter::ReferenceString translated_Building_Barracks_Internals = STRING_LITERAL_AS_REFERENCE("Barracks"); Jupiter::ReferenceString translated_Building_WeaponsFactory_Internals = STRING_LITERAL_AS_REFERENCE("Weapons Factory"); Jupiter::ReferenceString translated_Building_Refinery_GDI_Internals = STRING_LITERAL_AS_REFERENCE("GDI Refinery"); Jupiter::ReferenceString translated_Building_PowerPlant_GDI_Internals = STRING_LITERAL_AS_REFERENCE("GDI Power Plant"); /** Defense structures */ Jupiter::ReferenceString translated_Building_AdvancedGuardTower = STRING_LITERAL_AS_REFERENCE("Advanced Guard Tower"); Jupiter::ReferenceString translated_Building_Obelisk = STRING_LITERAL_AS_REFERENCE("Obelisk of Light"); Jupiter::ReferenceString translated_Building_AdvancedGuardTower_Internals = STRING_LITERAL_AS_REFERENCE("Advanced Guard Tower"); Jupiter::ReferenceString translated_Building_Obelisk_Internals = STRING_LITERAL_AS_REFERENCE("Obelisk of Light"); /** Other structures */ Jupiter::ReferenceString translated_Building_Silo = STRING_LITERAL_AS_REFERENCE("Tiberium Silo"); Jupiter::ReferenceString translated_Building_CommCentre = STRING_LITERAL_AS_REFERENCE("Communications Center"); Jupiter::ReferenceString translated_Building_Silo_Internals = STRING_LITERAL_AS_REFERENCE("Tiberium Silo"); Jupiter::ReferenceString translated_Building_CommCentre_Internals = STRING_LITERAL_AS_REFERENCE("Communications Center"); /** Fort structures */ Jupiter::ReferenceString translated_CapturableMCT_Fort = STRING_LITERAL_AS_REFERENCE("Fort"); Jupiter::ReferenceString translated_CapturableMCT_MC = STRING_LITERAL_AS_REFERENCE("Medical Center"); Jupiter::ReferenceString translated_CapturableMCT_Fort_Internals = STRING_LITERAL_AS_REFERENCE("Fort"); Jupiter::ReferenceString translated_CapturableMCT_MC_Internals = STRING_LITERAL_AS_REFERENCE("Medical Center"); /** Defences */ Jupiter::ReferenceString translated_Defence_GuardTower = STRING_LITERAL_AS_REFERENCE("Guard Tower"); Jupiter::ReferenceString translated_Defence_Turret = STRING_LITERAL_AS_REFERENCE("Turret"); Jupiter::ReferenceString translated_Defence_SAMSite = STRING_LITERAL_AS_REFERENCE("SAM Site"); Jupiter::ReferenceString translated_Defence_AATower = STRING_LITERAL_AS_REFERENCE("Anti-Air Guard Tower"); Jupiter::ReferenceString translated_Defence_GunEmplacement = STRING_LITERAL_AS_REFERENCE("Gun Emplacement"); Jupiter::ReferenceString translated_Defence_RocketEmplacement = STRING_LITERAL_AS_REFERENCE("Rocket Emplacement"); /** Defences - Sentinels */ Jupiter::ReferenceString translated_Sentinel_AGT_MG_Base = STRING_LITERAL_AS_REFERENCE("Advanced Guard Tower"); Jupiter::ReferenceString translated_Sentinel_AGT_Rockets_Base = STRING_LITERAL_AS_REFERENCE("Advanced Guard Tower"); Jupiter::ReferenceString translated_Sentinel_Obelisk_Laser_Base = STRING_LITERAL_AS_REFERENCE("Obelisk of Light"); /** UT damage types */ Jupiter::ReferenceString translated_UTDmgType_VehicleExplosion = STRING_LITERAL_AS_REFERENCE("Vehicle Explosion"); Jupiter::ReferenceString translated_UTDmgType_Drowned = STRING_LITERAL_AS_REFERENCE("Drowned"); /** Beacons */ Jupiter::ReferenceString translated_IonCannonBeacon = STRING_LITERAL_AS_REFERENCE("Ion Cannon Beacon"); Jupiter::ReferenceString translated_NukeBeacon = STRING_LITERAL_AS_REFERENCE("Nuclear Strike Beacon"); Jupiter::ReferenceString translated_KillZDamageType = STRING_LITERAL_AS_REFERENCE("Kill Zone"); RenX::TeamType RenX::getTeam(int teamNum) { switch (teamNum) { case 0: return RenX::TeamType::GDI; case 1: return RenX::TeamType::Nod; case 255: return RenX::TeamType::None; default: return RenX::TeamType::Other; } } RenX::TeamType RenX::getTeam(const Jupiter::ReadableString &team) { if (team.equalsi("GDI")) return RenX::TeamType::GDI; if (team.equalsi("Nod")) return RenX::TeamType::Nod; if (team.isEmpty() || team.equalsi("Neutral") || team.equalsi("Civilians")) return RenX::TeamType::None; return RenX::TeamType::Other; } const Jupiter::ReadableString &RenX::getTeamColor(TeamType team) { switch (team) { case RenX::TeamType::GDI: return GDIColor; case RenX::TeamType::Nod: return NodColor; default: return OtherColor; } } const Jupiter::ReadableString &RenX::getTeamName(TeamType team) { switch (team) { case RenX::TeamType::GDI: return GDIShortName; case RenX::TeamType::Nod: return NodShortName; default: return OtherShortName; } } const Jupiter::ReadableString &RenX::getFullTeamName(TeamType team) { switch (team) { case RenX::TeamType::GDI: return GDILongName; case RenX::TeamType::Nod: return NodLongName; default: return OtherLongName; } } RenX::TeamType RenX::getEnemy(TeamType team) { switch (team) { case RenX::TeamType::GDI: return RenX::TeamType::Nod; case RenX::TeamType::Nod: return RenX::TeamType::GDI; default: return RenX::TeamType::Other; } } const Jupiter::ReadableString &RenX::getCharacter(const Jupiter::ReadableString &chr) { static Jupiter::ReferenceString object; object = chr; if (object.find(STRING_LITERAL_AS_REFERENCE("Rx_")) == 0) object.shiftRight(3); if (object.find(STRING_LITERAL_AS_REFERENCE("InventoryManager_")) == 0) object.shiftRight(17); else if (object.find(STRING_LITERAL_AS_REFERENCE("FamilyInfo_")) == 0) object.shiftRight(11); return object; } const Jupiter::ReferenceString &translateCharacter(Jupiter::ReferenceString &object) { if (object.find(STRING_LITERAL_AS_REFERENCE("GDI_")) == 0) { object.shiftRight(4); if (object.equals(STRING_LITERAL_AS_REFERENCE("Deadeye"))) return translated_GDI_Deadeye; if (object.equals(STRING_LITERAL_AS_REFERENCE("Engineer"))) return translated_GDI_Engineer; if (object.equals(STRING_LITERAL_AS_REFERENCE("Grenadier"))) return translated_GDI_Grenadier; if (object.equals(STRING_LITERAL_AS_REFERENCE("Gunner"))) return translated_GDI_Gunner; if (object.equals(STRING_LITERAL_AS_REFERENCE("Havoc"))) return translated_GDI_Havoc; if (object.equals(STRING_LITERAL_AS_REFERENCE("Hotwire"))) return translated_GDI_Hotwire; if (object.equals(STRING_LITERAL_AS_REFERENCE("Marksman"))) return translated_GDI_Marksman; if (object.equals(STRING_LITERAL_AS_REFERENCE("McFarland"))) return translated_GDI_McFarland; if (object.equals(STRING_LITERAL_AS_REFERENCE("Mobius"))) return translated_GDI_Mobius; if (object.equals(STRING_LITERAL_AS_REFERENCE("Officer"))) return translated_GDI_Officer; if (object.equals(STRING_LITERAL_AS_REFERENCE("Patch"))) return translated_GDI_Patch; if (object.equals(STRING_LITERAL_AS_REFERENCE("RocketSoldier"))) return translated_GDI_RocketSoldier; if (object.equals(STRING_LITERAL_AS_REFERENCE("Shotgunner"))) return translated_GDI_Shotgunner; if (object.equals(STRING_LITERAL_AS_REFERENCE("Soldier"))) return translated_GDI_Soldier; if (object.equals(STRING_LITERAL_AS_REFERENCE("Sydney"))) return translated_GDI_Sydney; } else if (object.find(STRING_LITERAL_AS_REFERENCE("Nod_")) == 0) { object.shiftRight(4); if (object.equals(STRING_LITERAL_AS_REFERENCE("BlackHandSniper"))) return translated_Nod_BlackHandSniper; if (object.equals(STRING_LITERAL_AS_REFERENCE("ChemicalTrooper"))) return translated_Nod_ChemicalTrooper; if (object.equals(STRING_LITERAL_AS_REFERENCE("Engineer"))) return translated_Nod_Engineer; if (object.equals(STRING_LITERAL_AS_REFERENCE("FlameTrooper"))) return translated_Nod_FlameTrooper; if (object.equals(STRING_LITERAL_AS_REFERENCE("LaserChainGunner"))) return translated_Nod_LaserChainGunner; if (object.equals(STRING_LITERAL_AS_REFERENCE("Marksman"))) return translated_Nod_Marksman; if (object.equals(STRING_LITERAL_AS_REFERENCE("Mendoza"))) return translated_Nod_Mendoza; if (object.equals(STRING_LITERAL_AS_REFERENCE("Officer"))) return translated_Nod_Officer; if (object.equals(STRING_LITERAL_AS_REFERENCE("Raveshaw"))) return translated_Nod_Raveshaw; if (object.equals(STRING_LITERAL_AS_REFERENCE("RocketSoldier"))) return translated_Nod_RocketSoldier; if (object.equals(STRING_LITERAL_AS_REFERENCE("Sakura"))) return translated_Nod_Sakura; if (object.equals(STRING_LITERAL_AS_REFERENCE("Shotgunner"))) return translated_Nod_Shotgunner; if (object.equals(STRING_LITERAL_AS_REFERENCE("Soldier"))) return translated_Nod_Soldier; if (object.equals(STRING_LITERAL_AS_REFERENCE("StealthBlackHand"))) return translated_Nod_StealthBlackHand; if (object.equals(STRING_LITERAL_AS_REFERENCE("Technician"))) return translated_Nod_Technician; } return object; } const Jupiter::ReferenceString RenX::translateName(const Jupiter::ReadableString &obj) { if (obj.isEmpty()) return Jupiter::ReferenceString::empty; Jupiter::ReferenceString iniTranslation = RenX::getCore()->getConfig()["Name"_jrs].get(obj); if (iniTranslation.isNotEmpty()) return iniTranslation; Jupiter::ReferenceString object = obj; if (object.find(STRING_LITERAL_AS_REFERENCE("nBab_")) == 0) object.shiftRight(5); if (object.find(STRING_LITERAL_AS_REFERENCE("Rx_")) == 0) object.shiftRight(3); else if (object.find(STRING_LITERAL_AS_REFERENCE("TS_")) == 0) object.shiftRight(3); if (object.find(STRING_LITERAL_AS_REFERENCE("Vehicle_")) == 0) { object.shiftRight(8); /** Nod Vehicles */ if (object.equals(STRING_LITERAL_AS_REFERENCE("Harvester_Nod"))) return translated_Vehicle_Harvester_Nod; if (object.equals(STRING_LITERAL_AS_REFERENCE("Buggy"))) return translated_Vehicle_Buggy; if (object.equals(STRING_LITERAL_AS_REFERENCE("Artillery"))) return translated_Vehicle_Artillery; if (object.equals(STRING_LITERAL_AS_REFERENCE("APC_Nod"))) return translated_Vehicle_APC_Nod; if (object.equals(STRING_LITERAL_AS_REFERENCE("LightTank"))) return translated_Vehicle_LightTank; if (object.equals(STRING_LITERAL_AS_REFERENCE("FlameTank"))) return translated_Vehicle_FlameTank; if (object.equals(STRING_LITERAL_AS_REFERENCE("StealthTank"))) return translated_Vehicle_StealthTank; if (object.equals(STRING_LITERAL_AS_REFERENCE("Chinook_Nod"))) return translated_Vehicle_Chinook_Nod; if (object.equals(STRING_LITERAL_AS_REFERENCE("Apache"))) return translated_Vehicle_Apache; if (object.equals(STRING_LITERAL_AS_REFERENCE("ReconBike"))) return translated_Vehicle_ReconBike; if (object.equals(STRING_LITERAL_AS_REFERENCE("TickTank"))) return translated_Vehicle_TickTank; /** GDI Vehicles */ if (object.equals(STRING_LITERAL_AS_REFERENCE("Harvester_GDI"))) return translated_Vehicle_Harvester_GDI; if (object.equals(STRING_LITERAL_AS_REFERENCE("Humvee"))) return translated_Vehicle_Humvee; if (object.equals(STRING_LITERAL_AS_REFERENCE("MRLS"))) return translated_Vehicle_MRLS; if (object.equals(STRING_LITERAL_AS_REFERENCE("APC_GDI"))) return translated_Vehicle_APC_GDI; if (object.equals(STRING_LITERAL_AS_REFERENCE("MediumTank"))) return translated_Vehicle_MediumTank; if (object.equals(STRING_LITERAL_AS_REFERENCE("MammothTank"))) return translated_Vehicle_MammothTank; if (object.equals(STRING_LITERAL_AS_REFERENCE("Chinook_GDI"))) return translated_Vehicle_Chinook_GDI; if (object.equals(STRING_LITERAL_AS_REFERENCE("Orca"))) return translated_Vehicle_Orca; if (object.equals(STRING_LITERAL_AS_REFERENCE("HoverMRLS"))) return translated_Vehicle_HoverMRLS; if (object.equals(STRING_LITERAL_AS_REFERENCE("Titan"))) return translated_Vehicle_Titan; if (object.equals(STRING_LITERAL_AS_REFERENCE("Wolverine"))) return translated_Vehicle_Wolverine; /** Other Vehicles */ if (object.equals(STRING_LITERAL_AS_REFERENCE("A10_DmgType_GattlingGun"))) return translated_Vehicle_A10_DmgType_GattlingGun; if (object.equals(STRING_LITERAL_AS_REFERENCE("A10_DmgType_Bomb"))) return translated_Vehicle_A10_DmgType_Bomb; if (object.equals(STRING_LITERAL_AS_REFERENCE("AC130_DmgType_HeavyCannon"))) return translated_Vehicle_AC130_DmgType_HeavyCannon; if (object.equals(STRING_LITERAL_AS_REFERENCE("AC130_DmgType_AutoCannon"))) return translated_Vehicle_AC130_DmgType_AutoCannon; } else if (object.find(STRING_LITERAL_AS_REFERENCE("Weapon_")) == 0) { object.shiftRight(7); if (object.equals(STRING_LITERAL_AS_REFERENCE("HeavyPistol"))) return translated_Weapon_HeavyPistol; if (object.equals(STRING_LITERAL_AS_REFERENCE("Carbine"))) return translated_Weapon_Carbine; if (object.equals(STRING_LITERAL_AS_REFERENCE("Airstrike_GDI"))) return translated_Weapon_Airstrike_GDI; if (object.equals(STRING_LITERAL_AS_REFERENCE("Airstrike_Nod"))) return translated_Weapon_Airstrike_Nod; if (object.equals(STRING_LITERAL_AS_REFERENCE("TiberiumFlechetteRifle"))) return translated_Weapon_TiberiumFlechetteRifle; if (object.equals(STRING_LITERAL_AS_REFERENCE("TiberiumAutoRifle"))) return translated_Weapon_TiberiumAutoRifle; if (object.equals(STRING_LITERAL_AS_REFERENCE("TiberiumAutoRifle_Blue"))) return translated_Weapon_TiberiumAutoRifle_Blue; if (object.equals(STRING_LITERAL_AS_REFERENCE("EMPGrenade"))) return translated_Weapon_EMPGrenade; if (object.equals(STRING_LITERAL_AS_REFERENCE("SmokeGrenade"))) return translated_Weapon_SmokeGrenade; if (object.equals(STRING_LITERAL_AS_REFERENCE("TimedC4"))) return translated_Weapon_TimedC4; if (object.equals(STRING_LITERAL_AS_REFERENCE("RemoteC4"))) return translated_Weapon_RemoteC4; if (object.equals(STRING_LITERAL_AS_REFERENCE("ProxyC4"))) return translated_Weapon_ProxyC4; if (object.equals(STRING_LITERAL_AS_REFERENCE("ATMine"))) return translated_Weapon_ATMine; if (object.equals(STRING_LITERAL_AS_REFERENCE("IonCannonBeacon"))) return translated_Weapon_IonCannonBeacon; if (object.equals(STRING_LITERAL_AS_REFERENCE("NukeBeacon"))) return translated_Weapon_NukeBeacon; if (object.equals(STRING_LITERAL_AS_REFERENCE("DeployedC4"))) return translated_Weapon_DeployedC4; if (object.equals(STRING_LITERAL_AS_REFERENCE("DeployedTimedC4"))) return translated_Weapon_DeployedTimedC4; if (object.equals(STRING_LITERAL_AS_REFERENCE("DeployedRemoteC4"))) return translated_Weapon_DeployedRemoteC4; if (object.equals(STRING_LITERAL_AS_REFERENCE("DeployedProxyC4"))) return translated_Weapon_DeployedProxyC4; if (object.equals(STRING_LITERAL_AS_REFERENCE("DeployedATMine"))) return translated_Weapon_DeployedATMine; if (object.equals(STRING_LITERAL_AS_REFERENCE("DeployedIonCannonBeacon"))) return translated_Weapon_DeployedIonCannonBeacon; if (object.equals(STRING_LITERAL_AS_REFERENCE("DeployedNukeBeacon"))) return translated_Weapon_DeployedNukeBeacon; if (object.equals(STRING_LITERAL_AS_REFERENCE("CrateNuke"))) return translated_Weapon_CrateNuke; } else if (object.find(STRING_LITERAL_AS_REFERENCE("Projectile_")) == 0) { object.shiftRight(11); if (object.equals(STRING_LITERAL_AS_REFERENCE("EMPGrenade"))) return translated_Projectile_EMPGrenade; if (object.equals(STRING_LITERAL_AS_REFERENCE("SmokeGrenade"))) return translated_Projectile_SmokeGrenade; } else if (object.find(STRING_LITERAL_AS_REFERENCE("InventoryManager_")) == 0) { object.shiftRight(17); return translateCharacter(object); } else if (object.find(STRING_LITERAL_AS_REFERENCE("FamilyInfo_")) == 0) { object.shiftRight(11); return translateCharacter(object); } else if (object.find(STRING_LITERAL_AS_REFERENCE("DmgType_")) == 0) { object.shiftRight(8); /** Non-weapon damage types */ if (object.equals(STRING_LITERAL_AS_REFERENCE("Suicided"))) return translated_DmgType_Suicided; if (object.equals(STRING_LITERAL_AS_REFERENCE("Fell"))) return translated_DmgType_Fell; if (object.equals(STRING_LITERAL_AS_REFERENCE("Tiberium"))) return translated_DmgType_Tiberium; if (object.equals(STRING_LITERAL_AS_REFERENCE("TiberiumBleed"))) return translated_DmgType_TiberiumBleed; if (object.equals(STRING_LITERAL_AS_REFERENCE("TiberiumBleed_Blue"))) return translated_DmgType_TiberiumBleed_Blue; if (object.equals(STRING_LITERAL_AS_REFERENCE("RanOver"))) return translated_DmgType_RanOver; /** Infantry weapons */ if (object.equals(STRING_LITERAL_AS_REFERENCE("Pistol"))) return translated_DmgType_Pistol; if (object.equals(STRING_LITERAL_AS_REFERENCE("SMG"))) return translated_DmgType_SMG; if (object.equals(STRING_LITERAL_AS_REFERENCE("HeavyPistol"))) return translated_DmgType_HeavyPistol; if (object.equals(STRING_LITERAL_AS_REFERENCE("Carbine"))) return translated_DmgType_Carbine; if (object.equals(STRING_LITERAL_AS_REFERENCE("TiberiumFlechetteRifle"))) return translated_DmgType_TiberiumFlechetteRifle; // Not a rifle. if (object.equals(STRING_LITERAL_AS_REFERENCE("TiberiumAutoRifle"))) return translated_DmgType_TiberiumAutoRifle; if (object.equals(STRING_LITERAL_AS_REFERENCE("TiberiumAutoRifle_Blue"))) return translated_DmgType_TiberiumAutoRifle_Blue; if (object.equals(STRING_LITERAL_AS_REFERENCE("TiberiumAutoRifle_Flechette_Blue"))) return translated_DmgType_TiberiumAutoRifle_Flechette_Blue; if (object.equals(STRING_LITERAL_AS_REFERENCE("Grenade"))) return translated_DmgType_Grenade; if (object.equals(STRING_LITERAL_AS_REFERENCE("TimedC4"))) return translated_DmgType_TimedC4; if (object.equals(STRING_LITERAL_AS_REFERENCE("RemoteC4"))) return translated_DmgType_RemoteC4; if (object.equals(STRING_LITERAL_AS_REFERENCE("ProxyC4"))) return translated_DmgType_ProxyC4; if (object.equals(STRING_LITERAL_AS_REFERENCE("ATMine"))) return translated_DmgType_ATMine; if (object.equals(STRING_LITERAL_AS_REFERENCE("EMPGrenade"))) return translated_DmgType_EMPGrenade; if (object.equals(STRING_LITERAL_AS_REFERENCE("BurnC4"))) return translated_DmgType_BurnC4; if (object.equals(STRING_LITERAL_AS_REFERENCE("FireBleed"))) return translated_DmgType_FireBleed; // Caused by C4 or flame weapons if (object.equals(STRING_LITERAL_AS_REFERENCE("AutoRifle"))) return translated_DmgType_AutoRifle; if (object.equals(STRING_LITERAL_AS_REFERENCE("Shotgun"))) return translated_DmgType_Shotgun; if (object.equals(STRING_LITERAL_AS_REFERENCE("FlameThrower"))) return translated_DmgType_FlameThrower; if (object.equals(STRING_LITERAL_AS_REFERENCE("GrenadeLauncher"))) return translated_DmgType_GrenadeLauncher; if (object.equals(STRING_LITERAL_AS_REFERENCE("MarksmanRifle"))) return translated_DmgType_MarksmanRifle; if (object.equals(STRING_LITERAL_AS_REFERENCE("ChainGun"))) return translated_DmgType_ChainGun; if (object.equals(STRING_LITERAL_AS_REFERENCE("MissileLauncher"))) return translated_DmgType_MissileLauncher; if (object.equals(STRING_LITERAL_AS_REFERENCE("MissileLauncher_Alt"))) return translated_DmgType_MissileLauncher_Alt; if (object.equals(STRING_LITERAL_AS_REFERENCE("ChemicalThrower"))) return translated_DmgType_ChemicalThrower; if (object.equals(STRING_LITERAL_AS_REFERENCE("LaserRifle"))) return translated_DmgType_LaserRifle; if (object.equals(STRING_LITERAL_AS_REFERENCE("TacticalRifle"))) return translated_DmgType_TacticalRifle; if (object.equals(STRING_LITERAL_AS_REFERENCE("RocketLauncher"))) return translated_DmgType_RocketLauncher; if (object.equals(STRING_LITERAL_AS_REFERENCE("LaserChainGun"))) return translated_DmgType_LaserChainGun; if (object.equals(STRING_LITERAL_AS_REFERENCE("FlakCannon"))) return translated_DmgType_FlakCannon; if (object.equals(STRING_LITERAL_AS_REFERENCE("FlakCannon_Alt"))) return translated_DmgType_FlakCannon_Alt; if (object.equals(STRING_LITERAL_AS_REFERENCE("SniperRifle"))) return translated_DmgType_SniperRifle; if (object.equals(STRING_LITERAL_AS_REFERENCE("RamjetRifle"))) return translated_DmgType_RamjetRifle; if (object.equals(STRING_LITERAL_AS_REFERENCE("Railgun"))) return translated_DmgType_Railgun; if (object.equals(STRING_LITERAL_AS_REFERENCE("PersonalIonCannon"))) return translated_DmgType_PersonalIonCannon; if (object.equals(STRING_LITERAL_AS_REFERENCE("VoltRifle"))) return translated_DmgType_VoltRifle; if (object.equals(STRING_LITERAL_AS_REFERENCE("VoltRifle_Alt"))) return translated_DmgType_VoltRifle_Alt; if (object.equals(STRING_LITERAL_AS_REFERENCE("VoltAutoRifle"))) return translated_DmgType_VoltAutoRifle; if (object.equals(STRING_LITERAL_AS_REFERENCE("VoltAutoRifle_Alt"))) return translated_DmgType_VoltAutoRifle_Alt; /** Vehicle weapons */ if (object.equals(STRING_LITERAL_AS_REFERENCE("MammothTank_Missile"))) return translated_DmgType_MammothTank_Missile; if (object.equals(STRING_LITERAL_AS_REFERENCE("MammothTank_Cannon"))) return translated_DmgType_MammothTank_Cannon; if (object.equals(STRING_LITERAL_AS_REFERENCE("Orca_Missile"))) return translated_DmgType_Orca_Missile; if (object.equals(STRING_LITERAL_AS_REFERENCE("Orca_Gun"))) return translated_DmgType_Orca_Gun; if (object.equals(STRING_LITERAL_AS_REFERENCE("Orca_Passenger"))) return translated_DmgType_Orca_Passenger; if (object.equals(STRING_LITERAL_AS_REFERENCE("Apache_Rocket"))) return translated_DmgType_Apache_Rocket; if (object.equals(STRING_LITERAL_AS_REFERENCE("Apache_Gun"))) return translated_DmgType_Apache_Gun; if (object.equals(STRING_LITERAL_AS_REFERENCE("Apache_Passenger"))) return translated_DmgType_Apache_Passenger; /** Base Defence Weapons */ if (object.equals(STRING_LITERAL_AS_REFERENCE("AGT_MG"))) return translated_DmgType_AGT_MG; if (object.equals(STRING_LITERAL_AS_REFERENCE("AGT_Rocket"))) return translated_DmgType_AGT_Rocket; if (object.equals(STRING_LITERAL_AS_REFERENCE("Obelisk"))) return translated_DmgType_Obelisk; /** Defence Structure Weapons */ if (object.equals(STRING_LITERAL_AS_REFERENCE("AGT_MG"))) return translated_DmgType_AGT_MG; if (object.equals(STRING_LITERAL_AS_REFERENCE("AGT_Rocket"))) return translated_DmgType_AGT_Rocket; if (object.equals(STRING_LITERAL_AS_REFERENCE("Obelisk"))) return translated_DmgType_Obelisk; if (object.equals(STRING_LITERAL_AS_REFERENCE("GuardTower"))) return translated_DmgType_GuardTower; if (object.equals(STRING_LITERAL_AS_REFERENCE("Turret"))) return translated_DmgType_Turret; if (object.equals(STRING_LITERAL_AS_REFERENCE("SAMSite"))) return translated_DmgType_SAMSite; if (object.equals(STRING_LITERAL_AS_REFERENCE("AATower"))) return translated_DmgType_AATower; if (object.equals(STRING_LITERAL_AS_REFERENCE("GunEmpl"))) return translated_DmgType_GunEmpl; if (object.equals(STRING_LITERAL_AS_REFERENCE("GunEmpl_Alt"))) return translated_DmgType_GunEmpl_Alt; if (object.equals(STRING_LITERAL_AS_REFERENCE("RocketEmpl_Swarm"))) return translated_DmgType_RocketEmpl_Swarm; if (object.equals(STRING_LITERAL_AS_REFERENCE("RocketEmpl_Missile"))) return translated_DmgType_RocketEmpl_Missile; /** Other Weapons */ if (object.equals(STRING_LITERAL_AS_REFERENCE("Nuke"))) return translated_DmgType_Nuke; if (object.equals(STRING_LITERAL_AS_REFERENCE("IonCannon"))) return translated_DmgType_IonCannon; /** Nod Vehicles */ if (object.equals(STRING_LITERAL_AS_REFERENCE("Harvester_Nod"))) return translated_DmgType_Harvester_Nod; if (object.equals(STRING_LITERAL_AS_REFERENCE("Buggy"))) return translated_DmgType_Buggy; if (object.equals(STRING_LITERAL_AS_REFERENCE("Artillery"))) return translated_DmgType_Artillery; if (object.equals(STRING_LITERAL_AS_REFERENCE("APC_Nod"))) return translated_DmgType_APC_Nod; if (object.equals(STRING_LITERAL_AS_REFERENCE("LightTank"))) return translated_DmgType_LightTank; if (object.equals(STRING_LITERAL_AS_REFERENCE("FlameTank"))) return translated_DmgType_FlameTank; if (object.equals(STRING_LITERAL_AS_REFERENCE("StealthTank"))) return translated_DmgType_StealthTank; if (object.equals(STRING_LITERAL_AS_REFERENCE("Chinook_Nod"))) return translated_DmgType_Chinook_Nod; if (object.equals(STRING_LITERAL_AS_REFERENCE("Apache"))) return translated_DmgType_Apache; /** GDI Vehicles */ if (object.equals(STRING_LITERAL_AS_REFERENCE("Harvester_GDI"))) return translated_DmgType_Harvester_GDI; if (object.equals(STRING_LITERAL_AS_REFERENCE("Humvee"))) return translated_DmgType_Humvee; if (object.equals(STRING_LITERAL_AS_REFERENCE("MRLS"))) return translated_DmgType_MRLS; if (object.equals(STRING_LITERAL_AS_REFERENCE("APC_GDI"))) return translated_DmgType_APC_GDI; if (object.equals(STRING_LITERAL_AS_REFERENCE("MediumTank"))) return translated_DmgType_MediumTank; if (object.equals(STRING_LITERAL_AS_REFERENCE("MammothTank"))) return translated_DmgType_MammothTank; if (object.equals(STRING_LITERAL_AS_REFERENCE("Chinook_GDI"))) return translated_DmgType_Chinook_GDI; if (object.equals(STRING_LITERAL_AS_REFERENCE("Orca"))) return translated_DmgType_Orca; /** Other Vehicles */ if (object.equals(STRING_LITERAL_AS_REFERENCE("A10_Missile"))) return translated_DmgType_A10_Missile; } else if (object.find(STRING_LITERAL_AS_REFERENCE("Building_")) == 0) { object.shiftRight(9); /** Nod structures */ if (object.equals(STRING_LITERAL_AS_REFERENCE("HandOfNod"))) return translated_Building_HandOfNod; if (object.equals(STRING_LITERAL_AS_REFERENCE("AirTower"))) return translated_Building_AirTower; if (object.equals(STRING_LITERAL_AS_REFERENCE("Airstrip"))) return translated_Building_Airstrip; if (object.equals(STRING_LITERAL_AS_REFERENCE("Refinery_Nod"))) return translated_Building_Refinery_Nod; if (object.equals(STRING_LITERAL_AS_REFERENCE("PowerPlant_Nod"))) return translated_Building_PowerPlant_Nod; if (object.equals(STRING_LITERAL_AS_REFERENCE("HandOfNod_Internals"))) return translated_Building_HandOfNod_Internals; if (object.equals(STRING_LITERAL_AS_REFERENCE("AirTower_Internals"))) return translated_Building_AirTower_Internals; if (object.equals(STRING_LITERAL_AS_REFERENCE("Airstrip_Internals"))) return translated_Building_Airstrip_Internals; if (object.equals(STRING_LITERAL_AS_REFERENCE("Refinery_Nod_Internals"))) return translated_Building_Refinery_Nod_Internals; if (object.equals(STRING_LITERAL_AS_REFERENCE("PowerPlant_Nod_Internals"))) return translated_Building_PowerPlant_Nod_Internals; /** GDI structures */ if (object.equals(STRING_LITERAL_AS_REFERENCE("Barracks"))) return translated_Building_Barracks; if (object.equals(STRING_LITERAL_AS_REFERENCE("WeaponsFactory"))) return translated_Building_WeaponsFactory; if (object.equals(STRING_LITERAL_AS_REFERENCE("Refinery_GDI"))) return translated_Building_Refinery_GDI; if (object.equals(STRING_LITERAL_AS_REFERENCE("PowerPlant_GDI"))) return translated_Building_PowerPlant_GDI; if (object.equals(STRING_LITERAL_AS_REFERENCE("Barracks_Internals"))) return translated_Building_Barracks_Internals; if (object.equals(STRING_LITERAL_AS_REFERENCE("WeaponsFactory_Internals"))) return translated_Building_WeaponsFactory_Internals; if (object.equals(STRING_LITERAL_AS_REFERENCE("Refinery_GDI_Internals"))) return translated_Building_Refinery_GDI_Internals; if (object.equals(STRING_LITERAL_AS_REFERENCE("PowerPlant_GDI_Internals"))) return translated_Building_PowerPlant_GDI_Internals; /** Defense structures */ if (object.equals(STRING_LITERAL_AS_REFERENCE("AdvancedGuardTower"))) return translated_Building_AdvancedGuardTower; if (object.equals(STRING_LITERAL_AS_REFERENCE("Obelisk"))) return translated_Building_Obelisk; if (object.equals(STRING_LITERAL_AS_REFERENCE("AdvancedGuardTower_Internals"))) return translated_Building_AdvancedGuardTower_Internals; if (object.equals(STRING_LITERAL_AS_REFERENCE("Obelisk_Internals"))) return translated_Building_Obelisk_Internals; /** Other structures */ if (object.equals(STRING_LITERAL_AS_REFERENCE("Silo"))) return translated_Building_Silo; if (object.equals(STRING_LITERAL_AS_REFERENCE("CommCentre"))) return translated_Building_CommCentre; if (object.equals(STRING_LITERAL_AS_REFERENCE("Silo_Internals"))) return translated_Building_Silo_Internals; if (object.equals(STRING_LITERAL_AS_REFERENCE("CommCentre_Internals"))) return translated_Building_CommCentre_Internals; } else if (object.find(STRING_LITERAL_AS_REFERENCE("CapturableMCT_")) == 0) { object.shiftRight(14); if (object.equals(STRING_LITERAL_AS_REFERENCE("Fort"))) return translated_CapturableMCT_Fort; if (object.equals(STRING_LITERAL_AS_REFERENCE("MC"))) return translated_CapturableMCT_MC; if (object.equals(STRING_LITERAL_AS_REFERENCE("Fort_Internals"))) return translated_CapturableMCT_Fort_Internals; if (object.equals(STRING_LITERAL_AS_REFERENCE("MC_Internals"))) return translated_CapturableMCT_MC_Internals; } else if (object.find(STRING_LITERAL_AS_REFERENCE("Defence_")) == 0) { object.shiftRight(8); if (object.equals(STRING_LITERAL_AS_REFERENCE("GuardTower"))) return translated_Defence_GuardTower; if (object.equals(STRING_LITERAL_AS_REFERENCE("Turret"))) return translated_Defence_Turret; if (object.equals(STRING_LITERAL_AS_REFERENCE("SAMSite"))) return translated_Defence_SAMSite; if (object.equals(STRING_LITERAL_AS_REFERENCE("AATower"))) return translated_Defence_AATower; if (object.equals(STRING_LITERAL_AS_REFERENCE("GunEmplacement"))) return translated_Defence_GunEmplacement; if (object.equals(STRING_LITERAL_AS_REFERENCE("RocketEmplacement"))) return translated_Defence_RocketEmplacement; } else if (object.find(STRING_LITERAL_AS_REFERENCE("Sentinel_")) == 0) { object.shiftRight(9); if (object.equals(STRING_LITERAL_AS_REFERENCE("AGT_MG_Base"))) return translated_Sentinel_AGT_MG_Base; if (object.equals(STRING_LITERAL_AS_REFERENCE("AGT_Rockets_Base"))) return translated_Sentinel_AGT_Rockets_Base; if (object.equals(STRING_LITERAL_AS_REFERENCE("Obelisk_Laser_Base"))) return translated_Sentinel_Obelisk_Laser_Base; } else if (object.find(STRING_LITERAL_AS_REFERENCE("UTDmgType_")) == 0) { object.shiftRight(10); if (object.equals(STRING_LITERAL_AS_REFERENCE("VehicleExplosion"))) return translated_UTDmgType_VehicleExplosion; if (object.equals(STRING_LITERAL_AS_REFERENCE("Drowned"))) return translated_UTDmgType_Drowned; } else if (object.find(STRING_LITERAL_AS_REFERENCE("VoteMenuChoice_")) == 0) { object.shiftRight(15); if (object.equals(STRING_LITERAL_AS_REFERENCE("AddBots"))) return translated_VoteMenuChoice_AddBots; if (object.equals(STRING_LITERAL_AS_REFERENCE("ChangeMap"))) return translated_VoteMenuChoice_ChangeMap; if (object.equals(STRING_LITERAL_AS_REFERENCE("Donate"))) return translated_VoteMenuChoice_Donate; if (object.equals(STRING_LITERAL_AS_REFERENCE("Kick"))) return translated_VoteMenuChoice_Kick; if (object.equals(STRING_LITERAL_AS_REFERENCE("RemoveBots"))) return translated_VoteMenuChoice_RemoveBots; if (object.equals(STRING_LITERAL_AS_REFERENCE("RestartMatch"))) return translated_VoteMenuChoice_RestartMatch; if (object.equals(STRING_LITERAL_AS_REFERENCE("StartMatch"))) return translated_VoteMenuChoice_StartMatch; if (object.equals(STRING_LITERAL_AS_REFERENCE("Survey"))) return translated_VoteMenuChoice_Survey; } else if (object.equals(STRING_LITERAL_AS_REFERENCE("IonCannonBeacon"))) return translated_IonCannonBeacon; else if (object.equals(STRING_LITERAL_AS_REFERENCE("NukeBeacon"))) return translated_NukeBeacon; else if (object.equals(STRING_LITERAL_AS_REFERENCE("KillZDamageType"))) return translated_KillZDamageType; return translateCharacter(object); } const Jupiter::ReadableString &RenX::translateWinType(RenX::WinType winType) { switch (winType) { case RenX::WinType::Score: return scoreWinTypeTranslation; case RenX::WinType::Base: return baseWinTypeTranslation; case RenX::WinType::Beacon: return beaconWinTypeTranslation; case RenX::WinType::Tie: return tieWinTypeTranslation; case RenX::WinType::Shutdown: return shutdownWinTypeTranslation; case RenX::WinType::Surrender: return surrenderWinTypeTranslation; case RenX::WinType::Unknown: default: return unknownWinTypeTranslation; } } const Jupiter::ReadableString &RenX::translateWinTypePlain(RenX::WinType winType) { switch (winType) { case RenX::WinType::Score: return scoreWinTypePlainTranslation; case RenX::WinType::Base: return baseWinTypePlainTranslation; case RenX::WinType::Beacon: return beaconWinTypePlainTranslation; case RenX::WinType::Tie: return tieWinTypePlainTranslation; case RenX::WinType::Shutdown: return shutdownWinTypePlainTranslation; case RenX::WinType::Surrender: return surrenderWinTypePlainTranslation; case RenX::WinType::Unknown: default: return unknownWinTypePlainTranslation; } } void RenX::initTranslations(Jupiter::Config &translationsFile) { NodColor = translationsFile["TeamColor"_jrs].get("Nod"_jrs, "04"_jrs); GDIColor = translationsFile["TeamColor"_jrs].get("GDI"_jrs, "08"_jrs); OtherColor = translationsFile["TeamColor"_jrs].get("Other"_jrs, "14"_jrs); NodShortName = translationsFile["ShortTeamName"_jrs].get("Nod"_jrs, "Nod"_jrs); GDIShortName = translationsFile["ShortTeamName"_jrs].get("GDI"_jrs, "GDI"_jrs); OtherShortName = translationsFile["ShortTeamName"_jrs].get("Other"_jrs, "N/A"_jrs); NodLongName = translationsFile["LongTeamName"_jrs].get("Nod"_jrs, "Brotherhood of Nod"_jrs); GDILongName = translationsFile["LongTeamName"_jrs].get("GDI"_jrs, "Global Defense Initiative"_jrs); OtherLongName = translationsFile["LongTeamName"_jrs].get("Other"_jrs, "Unknown"_jrs); scoreWinTypeTranslation = translationsFile["WinType"_jrs].get("Score"_jrs, "Domination (High Score)"_jrs); baseWinTypeTranslation = translationsFile["WinType"_jrs].get("Base"_jrs, "Conquest (Base Destruction)"_jrs); beaconWinTypeTranslation = translationsFile["WinType"_jrs].get("Beacon"_jrs, "Espionage (Beacon)"_jrs); tieWinTypeTranslation = translationsFile["WinType"_jrs].get("Tie"_jrs, "Draw (Tie)"_jrs); shutdownWinTypeTranslation = translationsFile["WinType"_jrs].get("Shutdown"_jrs, "Ceasefire (Shutdown)"_jrs); surrenderWinTypeTranslation = translationsFile["WinType"_jrs].get("Surrender"_jrs, "Forfeit (Surrender)"_jrs); unknownWinTypeTranslation = translationsFile["WinType"_jrs].get("Unknown"_jrs, "Aliens (Unknown)"_jrs); scoreWinTypePlainTranslation = translationsFile["WinTypePlain"_jrs].get("Score"_jrs, "High Score"_jrs); baseWinTypePlainTranslation = translationsFile["WinTypePlain"_jrs].get("Base"_jrs, "Base Destruction"_jrs); beaconWinTypePlainTranslation = translationsFile["WinTypePlain"_jrs].get("Beacon"_jrs, "Beacon"_jrs); tieWinTypePlainTranslation = translationsFile["WinTypePlain"_jrs].get("Tie"_jrs, "Tie"_jrs); shutdownWinTypePlainTranslation = translationsFile["WinTypePlain"_jrs].get("Shutdown"_jrs, "Shutdown"_jrs); surrenderWinTypePlainTranslation = translationsFile["WinTypePlain"_jrs].get("Surrender"_jrs, "Surrender"_jrs); unknownWinTypePlainTranslation = translationsFile["WinTypePlain"_jrs].get("Unknown"_jrs, "Unknown"_jrs); } Jupiter::String RenX::getFormattedPlayerName(const RenX::PlayerInfo &player) { Jupiter::String r = player.formatNamePrefix; r += IRCCOLOR; r += RenX::getTeamColor(player.team); r += player.name; return r; } Jupiter::StringS RenX::formatGUID(const RenX::Map &map) { return Jupiter::StringS::Format("%.16llX%.16llX", map.guid[0], map.guid[1]); } std::chrono::milliseconds RenX::getServerTime(const RenX::PlayerInfo &player) { return std::chrono::duration_cast(std::chrono::steady_clock::now() - player.joinTime); } Jupiter::StringS RenX::default_uuid_func(RenX::PlayerInfo &player) { if (player.steamid != 0U) return Jupiter::StringS::Format("0x%.16llX", player.steamid); return Jupiter::StringS(); } double RenX::getKillDeathRatio(const RenX::PlayerInfo &player, bool includeSuicides) { double deaths = player.deaths; if (includeSuicides == false) deaths -= player.suicides; if (deaths == 0) deaths = 1; return static_cast(player.kills) / deaths; } double RenX::getHeadshotKillRatio(const RenX::PlayerInfo &player) { if (player.kills == 0) return 0; return static_cast(player.headshots) / static_cast(player.kills); } Jupiter::String RenX::escapifyRCON(const Jupiter::ReadableString &str) { const char *ptr = str.ptr(); size_t length = str.size(); Jupiter::String result(str.size() + 32); uint16_t value; while (length != 0) { if ((*ptr & 0x80) != 0) // UTF-8 sequence { if (length < 2) break; if ((*ptr & 0x40) != 0) // validity check { // get codepoint value if ((*ptr & 0x20) != 0) { if (length < 3) break; if ((*ptr & 0x10) != 0) // This is a 4 byte sequence, which we can not fit into a 16-bit codepoint. ignore it. { if (length < 4) break; ptr += 4; length -= 4; continue; } else { // this is a 3 byte sequence value = (*ptr & 0x0F) << 12; value += (*++ptr & 0x3F) << 6; value += *++ptr & 0x3F; length -= 3; } } else { // This is a 2 byte sequence value = (*ptr & 0x1F) << 6; value += *++ptr & 0x3F; length -= 2; } // write escape sequence result += '\\'; result += 'u'; result += Jupiter_asHex_upper(value >> 8); result += Jupiter_asHex_upper(value & 0x00FF); } // else // This is an invalid 1 byte sequence } else if (*ptr == '\\') // backslash, which is used for escape sequencing { result += '\\'; result += '\\'; --length; } else // an ordinary character { result += *ptr; --length; } ++ptr; } return result; } #ifndef CONSTANTS_HPP #define CONSTANTS_HPP namespace ice { namespace core { namespace constants { constexpr double MS_PER_UPDATE = 6.0; } // namespace constants } // namespace core } // namespace ice #endif // CONSTANTS_HPP main/drawinglayer/inc/drawinglayer/primitive3d/sdrpolypolygonprimitive3d.hxx /************************************************************** * * 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. * *************************************************************/ #ifndef INCLUDED_DRAWINGLAYER_PRIMITIVE3D_SDRPOLYPOLYGONPRIMITIVE3D_HXX #define INCLUDED_DRAWINGLAYER_PRIMITIVE3D_SDRPOLYPOLYGONPRIMITIVE3D_HXX #include #include ////////////////////////////////////////////////////////////////////////////// namespace drawinglayer { namespace primitive3d { /** SdrPolyPolygonPrimitive3D class This 3D primitive defines a PolyPolgon in space which may have Line- and FillStyles and extra 3D surface attributes. It is assumed that the given 3D PolyPolgon (which may contain texture and normal information) is planar in 3D. The decomposition will include all needed 3D data for visualisation, including FatLines and fill styles. */ class DRAWINGLAYER_DLLPUBLIC SdrPolyPolygonPrimitive3D : public SdrPrimitive3D { private: /// the planar polyPolygon evtl with normals and texture coordinates basegfx::B3DPolyPolygon maPolyPolygon3D; protected: /// local decomposition. virtual Primitive3DSequence create3DDecomposition(const geometry::ViewInformation3D& rViewInformation) const; public: /// constructor SdrPolyPolygonPrimitive3D( const basegfx::B3DPolyPolygon& rPolyPolygon3D, const basegfx::B3DHomMatrix& rTransform, const basegfx::B2DVector& rTextureSize, const attribute::SdrLineFillShadowAttribute3D& rSdrLFSAttribute, const attribute::Sdr3DObjectAttribute& rSdr3DObjectAttribute); /// data access const basegfx::B3DPolyPolygon& getPolyPolygon3D() const { return maPolyPolygon3D; } /// compare operator virtual bool operator==(const BasePrimitive3D& rPrimitive) const; /// get range virtual basegfx::B3DRange getB3DRange(const geometry::ViewInformation3D& rViewInformation) const; /// provide unique ID DeclPrimitrive3DIDBlock() }; } // end of namespace primitive3d } // end of namespace drawinglayer ////////////////////////////////////////////////////////////////////////////// #endif //INCLUDED_DRAWINGLAYER_PRIMITIVE3D_SDRPOLYPOLYGONPRIMITIVE3D_HXX ////////////////////////////////////////////////////////////////////////////// // eof #include "hardforkromming_motta.h" #include "ui_hardforkromming_motta.h" hardforkromming_motta::hardforkromming_motta(QWidget *parent) : QWidget(parent), ui(new Ui::hardforkromming_motta) { ui->setupUi(this); ui->stackedWidget->setCurrentIndex(0); // start alltid på side 1 - SEND QPixmap pix0("C:/Users/Kirisan/Pictures/PVR_local/tePVRlogo.png"); //481x94 ui->logo_tepvr_0->setPixmap(pix0); ui->logo_tepvr_1->setPixmap(pix0); ui->logo_tepvr_2->setPixmap(pix0); ui->stackedWidget->insertWidget(0, &_GjenkjennMotta); } hardforkromming_motta::~hardforkromming_motta() { delete ui; } void hardforkromming_motta::on_norsk_everit_clicked() { ui->stackedWidget->setCurrentIndex(0); } void hardforkromming_motta::on_eiker_clicked() { ui->stackedWidget->setCurrentIndex(0); } // Tilleggs widgets: -------------------------------------------------------------------------------------------------------- void hardforkromming_motta::on_tilbake_0_harforkromming_bedrifter_clicked() { emit tilbake_0_hardforkromming_bedrifter_clicked(); } void hardforkromming_motta::on_tilbake_1_hardforkromming_norsk_everit_clicked() { ui->stackedWidget->setCurrentIndex(0); } void hardforkromming_motta::on_tilbake_2_hardforkromming_eiker_clicked() { ui->stackedWidget->setCurrentIndex(0); } #include "videocapturethread.h" #include "seeta/QualityOfPoseEx.h" #include "seeta/Struct.h" #include #include #include #include #include #include "QDebug" using namespace std::chrono; extern const QString gcrop_prefix; extern Config_Paramter gparamters; extern std::string gmodelpath;// = "/wqy/seeta_sdk/SF3/libs/SF3.0_v1/models/"; void clone_image( const SeetaImageData &src, SeetaImageData &dst) { if(src.width != dst.width || src.height != dst.height || src.channels != dst.channels) { if(dst.data) { delete [] dst.data; dst.data = nullptr; } dst.width = src.width; dst.height = src.height; dst.channels = src.channels; dst.data = new unsigned char[src.width * src.height * src.channels]; } memcpy(dst.data, src.data, src.width * src.height * src.channels); } ////////////////////////////// WorkThread::WorkThread(VideoCaptureThread * main) { m_mainthread = main; } WorkThread::~WorkThread() { qDebug() << "WorkThread exited"; } int WorkThread::recognize(const SeetaTrackingFaceInfo & faceinfo)//, std::vector & datas) { auto points = m_mainthread->m_pd->mark(*m_mainthread->m_mainImage, faceinfo.pos); m_mainthread->m_qa->feed(*(m_mainthread->m_mainImage), faceinfo.pos, points.data(), 5); auto result1 = m_mainthread->m_qa->query(seeta::BRIGHTNESS); auto result2 = m_mainthread->m_qa->query(seeta::RESOLUTION); auto result3 = m_mainthread->m_qa->query(seeta::CLARITY); auto result4 = m_mainthread->m_qa->query(seeta::INTEGRITY); auto result = m_mainthread->m_qa->query(seeta::POSE_EX); qDebug() << "PID:" << faceinfo.PID; if(result.level == 0 || result1.level == 0 || result2.level == 0 || result3.level == 0 || result4.level == 0 ) { qDebug() << "Quality check failed!"; return -1; } auto status = m_mainthread->m_spoof->Predict( *m_mainthread->m_mainImage, faceinfo.pos, points.data() ); if( status != seeta::FaceAntiSpoofing::REAL) { qDebug() << "antispoofing check failed!"; return -2; } seeta::ImageData cropface = m_mainthread->m_fr->CropFaceV2(*m_mainthread->m_mainImage, points.data() ); float features[1024]; memset(features, 0, 1024 * sizeof(float)); m_mainthread->m_fr->ExtractCroppedFace(cropface, features); std::map::iterator iter = m_mainthread->m_datalst->begin(); //std::vector datas; for(; iter != m_mainthread->m_datalst->end(); ++iter) { if(m_mainthread->m_exited) { return -3; } float score = m_mainthread->m_fr->CalculateSimilarity(features, iter->second->features); qDebug() << "PID:" << faceinfo.PID << ", score:" << score; if(score >= gparamters.Fr_Threshold) { //datas.push_back(faceinfo.PID); //m_lastpids.push_back(faceinfo.PID); int x = faceinfo.pos.x - faceinfo.pos.width / 2; if((x) < 0) x = 0; int y = faceinfo.pos.y - faceinfo.pos.height / 2; if(y < 0) y = 0; int x2 = faceinfo.pos.x + faceinfo.pos.width * 1.5; if(x2 >= m_mainthread->m_mainImage->width) { x2 = m_mainthread->m_mainImage->width -1; } int y2 = faceinfo.pos.y + faceinfo.pos.height * 1.5; if(y2 >= m_mainthread->m_mainImage->height) { y2 = m_mainthread->m_mainImage->height -1; } //qDebug() << "----x:" << faceinfo.pos.x << ",y:" << faceinfo.pos.y << ",w:" << faceinfo.pos.width << ",h:" << faceinfo.pos.height; cv::Rect rect(x, y, x2-x, y2 - y); //qDebug() << "x:" << x << ",y:" << y << ",w:" << x2-x << ",h:" << y2-y; //cv::Rect rect(faceinfo.pos.x, faceinfo.pos.y, faceinfo.pos.width, faceinfo.pos.height); cv::Mat mat = m_mainthread->m_mainmat(rect).clone(); //cv::imwrite("/tmp/ddd.png",mat); //qDebug() << "----mat---"; QImage image((const unsigned char *)mat.data, mat.cols,mat.rows,mat.step, QImage::Format_RGB888); //image.save("/tmp/wwww.png"); //qDebug() << "PID:" << faceinfo.PID << ", score:" << score; QRect rc(iter->second->x, iter->second->y, iter->second->width, iter->second->height); emit sigRecognize(faceinfo.PID, iter->second->name, iter->second->image_path, score, image, rc); return 0; } } //m_lastpids.clear(); //m_lastpids.resize(datas.size()); //std::copy(datas.begin(), datas.end(), m_lastpids.begin()); return -3; } void WorkThread::run() { //m_begin = system_clock::now(); m_lastpids.clear(); m_lasterrorpids.clear(); bool bfind = false; std::vector datas; std::vector errordatas; int nret = 0; while(!m_mainthread->m_exited) { if(!m_mainthread->m_readimage) { QThread::msleep(1); continue; } auto end = system_clock::now(); //auto duration = duration_cast(end - m_begin); //int spent = duration.count(); //if(spent > 10) // m_lastpids.clear(); datas.clear(); errordatas.clear(); for(int i=0; im_mainfaceinfos.size(); i++) { if(m_mainthread->m_exited) { return; } bfind = false; for(int k=0; km_mainfaceinfos[i].PID == m_lastpids[k]) { datas.push_back(m_lastpids[k]); bfind = true; break; } } if(!bfind) { SeetaTrackingFaceInfo & faceinfo = m_mainthread->m_mainfaceinfos[i]; nret = recognize(faceinfo);//(m_mainthread->m_mainfaceinfos[i]);//, datas); if(nret < 0) { Fr_DataInfo info; info.pid = faceinfo.PID; info.state = nret; errordatas.push_back(info); bool bsend = true; for(int k=0; k= m_mainthread->m_mainImage->width) { x2 = m_mainthread->m_mainImage->width -1; } int y2 = faceinfo.pos.y + faceinfo.pos.height * 1.5; if(y2 >= m_mainthread->m_mainImage->height) { y2 = m_mainthread->m_mainImage->height -1; } //qDebug() << "----x:" << faceinfo.pos.x << ",y:" << faceinfo.pos.y << ",w:" << faceinfo.pos.width << ",h:" << faceinfo.pos.height; cv::Rect rect(x, y, x2-x, y2 - y); //qDebug() << "x:" << x << ",y:" << y << ",w:" << x2-x << ",h:" << y2-y; //cv::Rect rect(faceinfo.pos.x, faceinfo.pos.y, faceinfo.pos.width, faceinfo.pos.height); cv::Mat mat = m_mainthread->m_mainmat(rect).clone(); //cv::imwrite("/tmp/ddd.png",mat); //qDebug() << "----mat---"; QImage image((const unsigned char *)mat.data, mat.cols,mat.rows,mat.step, QImage::Format_RGB888); QString str; if(info.state == -1) { str = "QA ERROR"; }else if(info.state == -2) { str = "SPOOFING"; }else if(info.state == -3) { str = "MISS"; } emit sigRecognize(info.pid, "", str, 0.0, image, QRect(0,0,0,0)); } }else { datas.push_back(m_mainthread->m_mainfaceinfos[i].PID); } } } m_lastpids.clear(); m_lastpids.resize(datas.size()); std::copy(datas.begin(), datas.end(), m_lastpids.begin()); m_lasterrorpids.clear(); m_lasterrorpids.resize(errordatas.size()); std::copy(errordatas.begin(), errordatas.end(), m_lasterrorpids.begin()); auto end2 = system_clock::now(); auto duration2= duration_cast(end2 - end); int spent2 = duration2.count(); //qDebug() << "----spent:" << spent2; m_mainthread->m_mutex.lock(); m_mainthread->m_readimage = false; m_mainthread->m_mutex.unlock(); } } ///////////////////////////////// ResetModelThread::ResetModelThread(const QString &imagepath, const QString & tmpimagepath) { //m_mainthread = main; m_image_path = imagepath; m_image_tmp_path = tmpimagepath; m_exited = false; } ResetModelThread::~ResetModelThread() { qDebug() << "ResetModelThread exited"; } void ResetModelThread::start(std::map *datalst, const QString & table, seeta::FaceRecognizer * fr) { m_table = table; m_datalst = datalst; m_fr = fr; m_exited = false; QThread::start(); } typedef struct DataInfoTmp { int id; float features[ 1024]; }DataInfoTmp; void ResetModelThread::run() { int num = m_datalst->size(); QString fileName; float lastvalue = 0.0; float value = 0.0; ////////////////////////////////// QSqlQuery query; query.exec("drop table " + m_table + "_tmp"); if(!query.exec("create table " + m_table + "_tmp (id int primary key, name varchar(64), image_path varchar(256), feature_data blob)")) { qDebug() << "failed to create table:" + m_table + "_tmp"<< query.lastError(); emit sigResetModelEnd(-1); return; } //////////////////////////////// float features[1024]; std::vector vecs; std::map::iterator iter = m_datalst->begin(); //std::vector datas; int i=0; for(; iter != m_datalst->end(); ++iter,i++) { if(m_exited) { break; } value = (i + 1) / num; value = value * 90; if(value - lastvalue >= 1.0) { emit sigprogress(value); lastvalue = value; } //QString str = QString("current progress : %1%").arg(QString::number(value, 'f',1)); emit sigprogress(value); fileName = m_image_path + "crop_" + iter->second->image_path; cv::Mat mat = cv::imread(fileName.toStdString().c_str()); if(mat.data == NULL) { continue; } SeetaImageData image; image.height = mat.rows; image.width = mat.cols; image.channels = mat.channels(); image.data = mat.data; memset(features, 0, 1024 * sizeof(float)); m_fr->ExtractCroppedFace(image, features); //////////////////////////////////////////////////////// /* /// QSqlQuery query; query.prepare("update " + m_table + " set feature_data = :feature_data where id=:id"); query.bindValue(":id", iter->second->id); QByteArray bytearray; bytearray.resize(1024 * sizeof(float)); memcpy(bytearray.data(), features, 1024 * sizeof(float)); query.bindValue(":feature_data", QVariant(bytearray)); if(!query.exec()) { //vecs.push_back(iter->second->id); qDebug() << "failed to update table:" << query.lastError(); continue; } */ ////////////////////////////////////////////////////// QSqlQuery query2; query2.prepare("insert into " + m_table + "_tmp (id, name, image_path, feature_data) values (:id, :name, :image_path, :feature_data)"); query2.bindValue(":id", iter->second->id); query2.bindValue(":name",iter->second->name); query2.bindValue(":image_path", iter->second->image_path); QByteArray bytearray; bytearray.resize(1024 * sizeof(float)); memcpy(bytearray.data(), features, 1024 * sizeof(float)); query2.bindValue(":feature_data", QVariant(bytearray)); if(!query2.exec()) { qDebug() << "failed to update table:" << query.lastError(); continue; break; } /////////////////////////////////////////////// DataInfoTmp * info = new DataInfoTmp; info->id = iter->second->id; memcpy(info->features, features, 1024 * sizeof(float)); vecs.push_back(info); memcpy(iter->second->features, features, 1024 * sizeof(float)); } if(i < m_datalst->size()) { QSqlQuery deltable("drop table " + m_table + "_tmp"); deltable.exec(); for(int k=0; kfind(vecs[k]->id); if(iter != m_datalst->end()) { memcpy(iter->second->features, vecs[k]->features, 1024 * sizeof(float)); delete vecs[k]; } } vecs.clear(); } emit sigprogress(100.0); qDebug() << "------ResetModelThread---ok:"; emit sigResetModelEnd(0); } /// ///////////////////////////////// InputFilesThread::InputFilesThread(VideoCaptureThread * main, const QString &imagepath, const QString & tmpimagepath) { m_mainthread = main; m_image_path = imagepath; m_image_tmp_path = tmpimagepath; m_exited = false; } InputFilesThread::~InputFilesThread() { qDebug() << "InputFilesThread exited"; } void InputFilesThread::start(const QStringList * files, unsigned int id, const QString & table) { m_table = table; m_files = files; m_id = id; m_exited = false; QThread::start(); } void InputFilesThread::run() { int num = m_files->size(); float features[1024]; QString strerror; int nret; QString fileName; int index; float lastvalue = 0.0; float value = 0.0; SeetaRect rect; std::vector datalst; for(int i=0; isize(); i++) { if(m_exited) break; value = (i + 1) / num; value = value * 100 * 0.8; if(value - lastvalue >= 1.0) { emit sigprogress(value); lastvalue = value; } QString str = QString("current progress : %1%").arg(QString::number(value, 'f',1)); emit sigprogress(value); fileName = m_files->at(i); QImage image(fileName); if(image.isNull()) continue; QFile file(fileName); QFileInfo fileinfo(fileName); ////////////////////////////// QSqlQuery query; query.prepare("insert into " + m_table + " (id, name, image_path, feature_data, facex,facey,facewidth,faceheight) values (:id, :name, :image_path, :feature_data,:facex,:facey,:facewidth,:faceheight)"); index = m_id + 1; QString strfile = QString::number(index) + "_" + fileinfo.fileName(); QString cropfile = m_image_path + "crop_" + strfile; memset(features, 0, sizeof(float) * 1024); nret = m_mainthread->checkimage(fileName, cropfile, features, rect); strerror = ""; if(nret == -2) { strerror = "do not find face!"; }else if(nret == -1) { strerror = fileName + " is invalid!"; }else if(nret == 1) { strerror = "find more than one face!"; }else if(nret == 2) { strerror = "quality check failed!"; } if(!strerror.isEmpty()) { //QMessageBox::critical(NULL,"critical", strerror, QMessageBox::Yes); continue; } QString name = fileinfo.completeBaseName();//fileName(); int n = name.indexOf("_"); if(n >= 1) { name = name.left(n); } query.bindValue(0, index); query.bindValue(1,name); query.bindValue(2, strfile); QByteArray bytearray; bytearray.resize(1024 * sizeof(float)); memcpy(bytearray.data(), features, 1024 * sizeof(float)); query.bindValue(3, QVariant(bytearray)); query.bindValue(4, rect.x); query.bindValue(5, rect.y); query.bindValue(6, rect.width); query.bindValue(7, rect.height); if(!query.exec()) { QFile::remove(cropfile); qDebug() << "failed to insert table:" << query.lastError(); //QMessageBox::critical(NULL, "critical", tr("save face data to database failed!"), QMessageBox::Yes); continue; } file.copy(m_image_path + strfile); DataInfo * info = new DataInfo(); info->id = index; info->name = name; info->image_path = strfile; memcpy(info->features, features, 1024 * sizeof(float)); info->x = rect.x; info->y = rect.y; info->width = rect.width; info->height = rect.height; datalst.push_back(info); m_id++; } if(datalst.size() > 0) { emit sigInputFilesUpdateUI( &datalst); } emit sigprogress(100.0); datalst.clear(); emit sigInputFilesEnd(); } /// VideoCaptureThread::VideoCaptureThread(std::map * datalst, int videowidth, int videoheight) { m_exited = false; //m_haveimage = false; m_datalst = datalst; //m_width = 800; //m_height = 600; qDebug() << "video width:" << videowidth << "," << videoheight; //std::string modelpath = "/wqy/seeta_sdk/SF3/libs/SF3.0_v1/models/"; seeta::ModelSetting fd_model; fd_model.append(gmodelpath + "face_detector.csta"); fd_model.set_device( seeta::ModelSetting::CPU ); fd_model.set_id(0); m_fd = new seeta::FaceDetector(fd_model); m_fd->set(seeta::FaceDetector::PROPERTY_MIN_FACE_SIZE, 100); m_tracker = new seeta::FaceTracker(fd_model, videowidth,videoheight); m_tracker->SetMinFaceSize(100); //set(seeta::FaceTracker::PROPERTY_MIN_FACE_SIZE, 100); seeta::ModelSetting pd_model; pd_model.append(gmodelpath + "face_landmarker_pts5.csta"); pd_model.set_device( seeta::ModelSetting::CPU ); pd_model.set_id(0); m_pd = new seeta::FaceLandmarker(pd_model); seeta::ModelSetting spoof_model; spoof_model.append(gmodelpath + "fas_first.csta"); spoof_model.append(gmodelpath + "fas_second.csta"); spoof_model.set_device( seeta::ModelSetting::CPU ); spoof_model.set_id(0); m_spoof = new seeta::FaceAntiSpoofing(spoof_model); m_spoof->SetThreshold(0.30, 0.80); seeta::ModelSetting fr_model; fr_model.append(gmodelpath + "face_recognizer.csta"); fr_model.set_device( seeta::ModelSetting::CPU ); fr_model.set_id(0); m_fr = new seeta::FaceRecognizer(fr_model); /////////////////////////////// seeta::ModelSetting setting68; setting68.set_id(0); setting68.set_device( SEETA_DEVICE_CPU ); setting68.append(gmodelpath + "face_landmarker_pts68.csta" ); m_pd68 = new seeta::FaceLandmarker( setting68 ); seeta::ModelSetting posemodel; posemodel.set_device(SEETA_DEVICE_CPU); posemodel.set_id(0); posemodel.append(gmodelpath + "pose_estimation.csta"); m_poseex = new seeta::QualityOfPoseEx(posemodel); m_poseex->set(seeta::QualityOfPoseEx::YAW_LOW_THRESHOLD, 20); m_poseex->set(seeta::QualityOfPoseEx::YAW_HIGH_THRESHOLD, 10); m_poseex->set(seeta::QualityOfPoseEx::PITCH_LOW_THRESHOLD, 20); m_poseex->set(seeta::QualityOfPoseEx::PITCH_HIGH_THRESHOLD, 10); seeta::ModelSetting lbnmodel; lbnmodel.set_device(SEETA_DEVICE_CPU); lbnmodel.set_id(0); lbnmodel.append(gmodelpath + "quality_lbn.csta"); m_lbn = new seeta::QualityOfLBN(lbnmodel); m_lbn->set(seeta::QualityOfLBN::PROPERTY_BLUR_THRESH, 0.80); m_qa = new seeta::QualityAssessor(); m_qa->add_rule(seeta::INTEGRITY); m_qa->add_rule(seeta::RESOLUTION); m_qa->add_rule(seeta::BRIGHTNESS); m_qa->add_rule(seeta::CLARITY); m_qa->add_rule(seeta::POSE_EX, m_poseex, true); ////////////////////// //m_capture = new cv::VideoCapture(0); m_capture = NULL;//new cv::VideoCapture; //m_capture->set( cv::CAP_PROP_FRAME_WIDTH, videowidth ); //m_capture->set( cv::CAP_PROP_FRAME_HEIGHT, videoheight ); //int videow = vc.get( CV_CAP_PROP_FRAME_WIDTH ); //int videoh = vc.get( CV_CAP_PROP_FRAME_HEIGHT ); m_workthread = new WorkThread(this); m_mainImage = new SeetaImageData(); //m_curImage = new SeetaImageData(); m_mainImage->width = m_mainImage->height = m_mainImage->channels= 0; m_mainImage->data = NULL; //m_curImage->width = m_curImage->height = m_curImage->channels= 0; //m_curImage->data = NULL; } VideoCaptureThread::~VideoCaptureThread() { m_exited = true; while(!isFinished()) { QThread::msleep(1); } qDebug() << "VideoCaptureThread exited"; if( m_capture) delete m_capture; delete m_fd; delete m_pd; delete m_spoof; delete m_tracker; delete m_lbn; delete m_qa; delete m_workthread; } void VideoCaptureThread::setparamter() { /* qDebug() << gparamters.MinFaceSize << ", " << gparamters.Fd_Threshold; qDebug() << gparamters.VideoWidth << ", " << gparamters.VideoHeight; qDebug() << gparamters.AntiSpoofClarity << ", " << gparamters.AntiSpoofReality; qDebug() << gparamters.YawLowThreshold << ", " << gparamters.YawHighThreshold; qDebug() << gparamters.PitchLowThreshold << ", " << gparamters.PitchHighThreshold; */ m_fd->set(seeta::FaceDetector::PROPERTY_MIN_FACE_SIZE, gparamters.MinFaceSize); m_fd->set(seeta::FaceDetector::PROPERTY_THRESHOLD, gparamters.Fd_Threshold); m_tracker->SetMinFaceSize(gparamters.MinFaceSize); m_tracker->SetThreshold(gparamters.Fd_Threshold); m_tracker->SetVideoSize(gparamters.VideoWidth, gparamters.VideoHeight); m_spoof->SetThreshold(gparamters.AntiSpoofClarity, gparamters.AntiSpoofReality); m_poseex->set(seeta::QualityOfPoseEx::YAW_LOW_THRESHOLD, gparamters.YawLowThreshold); m_poseex->set(seeta::QualityOfPoseEx::YAW_HIGH_THRESHOLD, gparamters.YawHighThreshold); m_poseex->set(seeta::QualityOfPoseEx::PITCH_LOW_THRESHOLD, gparamters.PitchLowThreshold); m_poseex->set(seeta::QualityOfPoseEx::PITCH_HIGH_THRESHOLD, gparamters.PitchHighThreshold); } seeta::FaceRecognizer * VideoCaptureThread::CreateFaceRecognizer(const QString & modelfile) { seeta::ModelSetting fr_model; fr_model.append(gmodelpath + modelfile.toStdString()); fr_model.set_device( seeta::ModelSetting::CPU ); fr_model.set_id(0); seeta::FaceRecognizer * fr = new seeta::FaceRecognizer(fr_model); return fr; } void VideoCaptureThread::set_fr(seeta::FaceRecognizer * fr) { if(m_fr != NULL) { delete m_fr; } m_fr = fr; } void VideoCaptureThread::start(const RecognizeType &type) { m_type.type = type.type; m_type.filename = type.filename; QThread::start(); } void VideoCaptureThread::run() { int nret = 0; if(m_type.type == 0) { m_capture = new cv::VideoCapture; m_capture->open(m_type.type); m_capture->set( cv::CAP_PROP_FRAME_WIDTH, gparamters.VideoWidth ); m_capture->set( cv::CAP_PROP_FRAME_HEIGHT, gparamters.VideoHeight ); }else if(m_type.type == 1) { m_capture = new cv::VideoCapture; m_capture->open(m_type.filename.toStdString().c_str()); m_capture->set( cv::CAP_PROP_FRAME_WIDTH, gparamters.VideoWidth ); m_capture->set( cv::CAP_PROP_FRAME_HEIGHT, gparamters.VideoHeight ); } //m_capture->open("/tmp/test.avi"); //m_capture->open(0); //m_capture->set( cv::CAP_PROP_FRAME_WIDTH, gparamters.VideoWidth ); //m_capture->set( cv::CAP_PROP_FRAME_HEIGHT, gparamters.VideoHeight ); if((m_capture != NULL) && (!m_capture->isOpened())) { m_capture->release(); emit sigEnd(-1); return; } cv::Mat mat, mat2; cv::Scalar color; color = CV_RGB( 0, 255, 0 ); m_workthread->start(); /* //mp4,h263,flv cv::VideoWriter outputvideo; cv::Size s(800,600); int codec = outputvideo.fourcc('M', 'P', '4', '2'); outputvideo.open("/tmp/test.avi", codec, 50.0, s, true); if(!outputvideo.isOpened()) { qDebug() << " write video failed"; } */ while(!m_exited) { if(m_type.type == 2) { mat = cv::imread(m_type.filename.toStdString().c_str()); if(mat.data == NULL) { qDebug() << "VideoCapture read failed"; m_exited = true; nret = -2; break; } }else { if(!m_capture->read(mat)) { qDebug() << "VideoCapture read failed"; m_exited = true; nret = -2; break; } } //(*m_capture) >> mat; //cv::imwrite("/tmp/www_test.png",mat); auto start = system_clock::now(); if(m_type.type == 1) { cv::flip(mat, mat, 1); }else { cv::Size size (gparamters.VideoWidth, gparamters.VideoHeight); cv::resize(mat, mat2, size, 0, 0, cv::INTER_CUBIC); mat = mat2.clone(); } if(mat.channels() == 4) { cv::cvtColor(mat, mat, cv::COLOR_RGBA2BGR); } SeetaImageData image; image.height = mat.rows; image.width = mat.cols; image.channels = mat.channels(); image.data = mat.data; cv::cvtColor(mat, mat2, cv::COLOR_BGR2RGB); auto faces = m_tracker->Track(image); //qDebug() << "-----track size:" << faces.size; if( faces.size > 0 ) { m_mutex.lock(); if(!m_readimage) { clone_image(image, *m_mainImage); //cv::Mat tmpmat; //cv::cvtColor(mat, tmpmat, cv::COLOR_BGR2RGB); m_mainmat = mat2.clone();//tmpmat.clone(); m_mainfaceinfos.clear(); for(int i=0; i(end - start); int spent = duration.count() / 1000; if(spent - 50 > 0) { QThread::msleep(spent - 50); } if(m_type.type == 2) { nret = -2; m_exited = true; break; } } if(m_capture != NULL) { m_capture->release(); } while(!m_workthread->isFinished()) { QThread::msleep(1); } emit sigEnd(nret); } //return 0:success, -1:src image is invalid, -2:do not find face, 1: find more than one face, 2: quality check failed int VideoCaptureThread::checkimage(const QString & image, const QString & crop, float * features, SeetaRect &rect) { std::string strimage = image.toStdString(); std::string strcrop = crop.toStdString(); cv::Mat mat = cv::imread(strimage.c_str()); if(mat.empty()) return -1; SeetaImageData img; img.width = mat.cols; img.height = mat.rows; img.channels = mat.channels(); img.data = mat.data; auto face_array = m_fd->detect(img); if(face_array.size <= 0) { return -2; }else if(face_array.size > 1) { return 1; } SeetaRect& face = face_array.data[0].pos; SeetaPointF points[5]; m_pd->mark(img, face, points); m_qa->feed(img, face, points, 5); auto result1 = m_qa->query(seeta::BRIGHTNESS); auto result2 = m_qa->query(seeta::RESOLUTION); auto result3 = m_qa->query(seeta::CLARITY); auto result4 = m_qa->query(seeta::INTEGRITY); //auto result5 = m_qa->query(seeta::POSE); auto result = m_qa->query(seeta::POSE_EX); if(result.level == 0 || result1.level == 0 || result2.level == 0 || result3.level == 0 || result4.level == 0 ) { return 2; } /* SeetaPointF points68[68]; memset( points68, 0, sizeof( SeetaPointF ) * 68 ); m_pd68->mark(img, face,points68); int light, blur, noise; light = blur = noise = -1; m_lbn->Detect( img, points68, &light, &blur, &noise ); */ //std::cout << "light:" << light << ", blur:" << blur << ", noise:" << noise << std::endl; seeta::ImageData cropface = m_fr->CropFaceV2(img, points); cv::Mat imgmat(cropface.height, cropface.width, CV_8UC(cropface.channels), cropface.data); m_fr->ExtractCroppedFace(cropface, features); cv::imwrite(strcrop.c_str(), imgmat); /////////////////////////////////////////////// int x = face.x - face.width / 2; if((x) < 0) x = 0; int y = face.y - face.height / 2; if(y < 0) y = 0; int x2 = face.x + face.width * 1.5; if(x2 >= img.width) { x2 = img.width -1; } int y2 = face.y + face.height * 1.5; if(y2 >= img.height) { y2 = img.height -1; } rect.x = x; rect.y = y; rect.width = x2 - x; rect.height = y2 - y; return 0; } #include "LogManager.h" #include LogManager::LogManager() { ZeroMemory(outputString_, MAX_OUTPUT_LENGTH * 2 * sizeof(CHAR)); logInfoLevel_.resize(MAX_LOG_TYPE); windowHandle_ = NULL; isInit_ = FALSE; } LogManager::~LogManager() { CloseAllLog(); DestroyThread(); } BOOL LogManager::InitLog(LogConfig& logConfig) { return LogManager::GetInstance()->Init(logConfig); } void LogManager::CloseLog() { LogManager::GetInstance()->CloseAllLog(); } void LogManager::Log(LoggingLevel logInfoType, const std::string outputString, ...) { LogMsg* log = new LogMsg; log->logType = logInfoType; // 로그 종류 설정 // 로그 스트링 설정 va_list argptr; va_start(argptr, outputString); _vsnprintf_s(log->outputString, MAX_OUTPUT_LENGTH, outputString.c_str(), argptr); va_end(argptr); LogManager::GetInstance()->PushMsgQueue(log); } void LogManager::SetEnabled(LogType type, BOOL enable) { LogManager::GetInstance()->SetEnable(type, enable); } BOOL LogManager::Init(LogConfig& logConfig) { std::lock_guard lock(lock_); CloseAllLog(); logConfig_ = logConfig; windowHandle_ = logConfig.hWnd; logInfoLevel_ = logConfig.maxLoggingLevel; loggingList_.clear(); // 파일 로그 설정 loggingList_.push_back(new FileLogging(logConfig)); // 콘솔 로그 설정 loggingList_.push_back(new ConsoleLogging(logConfig)); // 디버그 로그 설정 loggingList_.push_back(new DebugLogging(logConfig)); for (auto logging : loggingList_) { logging->Init(); } isInit_ = TRUE; CreateThread(logConfig.processTick); Run(); return TRUE; } void LogManager::LogOutput(LoggingLevel logInfo, CHAR* outputString) { if (isInit_ == FALSE) { return; } //저장 타입에 해당하는 로그 레벨을 가져온다. INT loggingLevel = (INT)logInfo; // 로그 시간 설정 CHAR loggingTime[25]; time_t curTime; curTime = time(NULL); struct tm localTime; localtime_s(&localTime, &curTime); // curTime을 localTime에 저장 strftime(loggingTime, 25, "%Y/%m/%d(%H:%M:%S)", &localTime); // 구한 localTime의 형식 조절 loggingTime[24] = NULL; // 로그 스트링 설정 outputString[MAX_OUTPUT_LENGTH - 1] = NULL; _snprintf_s(outputString_, MAX_OUTPUT_LENGTH * 2, "%s | %s | %s\n", loggingTime, loggingLevelString[loggingLevel].c_str(), outputString); for (auto log : loggingList_) { log->Logging(outputString_, localTime, logInfo); } } void LogManager::CloseAllLog() { std::lock_guard lock(lock_); OnProcess(); logInfoLevel_.resize(MAX_LOG_TYPE, 0); windowHandle_ = NULL; for (auto logging : loggingList_) { logging->Close(); } //쓰레드 종료 Stop(); } void LogManager::SetEnable(LogType type, BOOL enable) { loggingList_[type]->SetEnable(enable); } void LogManager::CloseWindowLog() { windowHandle_ = NULL; } void LogManager::OnProcess() { std::lock_guard lock(lock_); while (!logQueue_.IsEmpty()) { LogMsg* logMsg = logQueue_.Front(); if (logMsg == NULL) { return; } //로그를 찍는다. LogOutput(logMsg->logType, logMsg->outputString); logQueue_.Pop(); delete logMsg; } } void LogManager::PushMsgQueue(LogMsg* logMsg) { logQueue_.Push(logMsg); } void LoggingInterface::SetEnable(BOOL enable) { isEnabled_ = enable; } /************************************************************** * * 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. * *************************************************************/ #ifndef SC_TABVWSH_HXX #define SC_TABVWSH_HXX #include #include #include #include #include "scdllapi.h" #include "dbfunc.hxx" // -> tabview #include "target.hxx" #include "rangelst.hxx" // ScRangeListRef #include "shellids.hxx" #include "tabprotection.hxx" // for ScPasswordHash class FmFormShell; class SbxObject; class SdrOle2Obj; class SfxBindings; class SfxChildWindow; class SfxModelessDialog; class SvxBorderLine; class SvxBoxObjectRef; class SvxNumberInfoItem; struct SfxChildWinInfo; class ScArea; class ScAuditingShell; class ScDrawShell; class ScDrawTextObjectBar; class ScEditShell; class ScInputHandler; class ScPivotShell; class ScDrawFormShell; class ScCellShell; class ScOleObjectShell; class ScGraphicShell; class ScMediaShell; class ScChartShell; class ScPageBreakShell; class ScDPObject; class ScNavigatorSettings; struct ScHeaderFieldData; namespace com { namespace sun { namespace star { namespace frame { class XDispatchProviderInterceptor; } } } } namespace svx { class ExtrusionBar; class FontworkBar; } enum ObjectSelectionType { OST_NONE, OST_Cell, OST_Editing, OST_DrawText, OST_Drawing, OST_DrawForm, OST_Pivot, OST_Auditing, OST_OleObject, OST_Chart, OST_Graphic, OST_Media }; //================================================================== class ScTabViewShell: public SfxViewShell, public ScDBFunc { private: static sal_uInt16 nInsertCtrlState; static sal_uInt16 nInsCellsCtrlState; static sal_uInt16 nInsObjCtrlState; SvxHtmlOptions aHTMLOpt; ObjectSelectionType eCurOST; sal_uInt16 nDrawSfxId; sal_uInt16 nCtrlSfxId; sal_uInt16 nFormSfxId; String sDrawCustom; // current custom shape type ScDrawShell* pDrawShell; ScDrawTextObjectBar* pDrawTextShell; ScEditShell* pEditShell; ScPivotShell* pPivotShell; ScAuditingShell* pAuditingShell; ScDrawFormShell* pDrawFormShell; ScCellShell* pCellShell; ScOleObjectShell* pOleObjectShell; ScChartShell* pChartShell; ScGraphicShell* pGraphicShell; ScMediaShell* pMediaShell; ScPageBreakShell* pPageBreakShell; svx::ExtrusionBar* pExtrusionBarShell; svx::FontworkBar* pFontworkBarShell; FmFormShell* pFormShell; ScInputHandler* pInputHandler; // fuer OLE-Eingabezeile SvxBorderLine* pCurFrameLine; ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProviderInterceptor > xDisProvInterceptor; Point aWinPos; ScTabViewTarget aTarget; ScArea* pPivotSource; ScDPObject* pDialogDPObject; ScNavigatorSettings* pNavSettings; // used in first Activate sal_Bool bFirstActivate; sal_Bool bActiveDrawSh; sal_Bool bActiveDrawTextSh; sal_Bool bActivePivotSh; sal_Bool bActiveAuditingSh; sal_Bool bActiveDrawFormSh; sal_Bool bActiveOleObjectSh; sal_Bool bActiveChartSh; sal_Bool bActiveGraphicSh; sal_Bool bActiveMediaSh; sal_Bool bActiveEditSh; sal_Bool bFormShellAtTop; // does the FormShell need to be on top? sal_Bool bDontSwitch; // EditShell nicht abschalten sal_Bool bInFormatDialog; // fuer GetSelectionText sal_Bool bPrintSelected; // for result of SvxPrtQryBox sal_Bool bReadOnly; // um Status-Aenderungen zu erkennen sal_Bool bIsActive; SbxObject* pScSbxObject; //UNUSED2008-05 sal_Bool bChartDlgIsEdit; // Datenbereich aendern sal_Bool bChartAreaValid; // wenn Chart aufgezogen wird String aEditChartName; ScRangeListRef aChartSource; Rectangle aChartPos; SCTAB nChartDestTab; sal_uInt16 nCurRefDlgId; SfxBroadcaster* pAccessibilityBroadcaster; static const int MASTERENUMCOMMANDS = 6; String aCurrShapeEnumCommand[ MASTERENUMCOMMANDS ]; sal_Bool bForceFocusOnCurCell; // i123629 sal_Bool bSearchJustOpened; // i35093 private: void Construct( sal_uInt8 nForceDesignMode = SC_FORCEMODE_NONE ); //UNUSED2008-05 void SetMySubShell( SfxShell* pShell ); SfxShell* GetMySubShell() const; void DoReadUserData( const String& rData ); void DoReadUserDataSequence( const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& rSettings ); DECL_LINK( SimpleRefClose, String* ); DECL_LINK( SimpleRefDone, String* ); DECL_LINK( SimpleRefAborted, String* ); DECL_LINK( SimpleRefChange, String* ); DECL_LINK( FormControlActivated, FmFormShell* ); DECL_LINK( HtmlOptionsHdl, void * ); protected: virtual void Activate(sal_Bool bMDI); virtual void Deactivate(sal_Bool bMDI); virtual sal_uInt16 PrepareClose( sal_Bool bUI = sal_True, sal_Bool bForBrowsing = sal_False ); virtual void ShowCursor(FASTBOOL bOn); virtual void Move(); // Benachrichtigung virtual void AdjustPosSizePixel( const Point &rPos, const Size &rSize ); // alt virtual void InnerResizePixel( const Point &rOfs, const Size &rSize ); // neu virtual void OuterResizePixel( const Point &rOfs, const Size &rSize ); virtual void SetZoomFactor( const Fraction &rZoomX, const Fraction &rZoomY ); virtual void QueryObjAreaPixel( Rectangle& rRect ) const; virtual Size GetOptimalSizePixel() const; virtual String GetSelectionText( sal_Bool bWholeWord ); virtual sal_Bool HasSelection( sal_Bool bText ) const; virtual String GetDescription() const; virtual void WriteUserData(String &, sal_Bool bBrowse = sal_False); virtual void ReadUserData(const String &, sal_Bool bBrowse = sal_False); virtual void WriteUserDataSequence (::com::sun::star::uno::Sequence < ::com::sun::star::beans::PropertyValue >&, sal_Bool bBrowse = sal_False ); virtual void ReadUserDataSequence (const ::com::sun::star::uno::Sequence < ::com::sun::star::beans::PropertyValue >&, sal_Bool bBrowse = sal_False ); virtual void UIDeactivated( SfxInPlaceClient* pClient ); virtual FASTBOOL KeyInput( const KeyEvent &rKeyEvent ); virtual SdrView* GetDrawView() const; public: TYPEINFO_VISIBILITY(SC_DLLPUBLIC); SFX_DECL_INTERFACE(SCID_TABVIEW_SHELL) SFX_DECL_VIEWFACTORY(ScTabViewShell); // -> Clone-Methode fuer Factory //UNUSED2008-05 ScTabViewShell( SfxViewFrame* pViewFrame, //UNUSED2008-05 const ScTabViewShell& rWin ); // aus einer allgemeinen Shell konstruieren und // soviel wie moeglich uebernehmen (SliderPos etc.): ScTabViewShell( SfxViewFrame* pViewFrame, SfxViewShell* pOldSh ); virtual ~ScTabViewShell(); Window* GetDialogParent(); bool IsRefInputMode() const; void ExecuteInputDirect(); ScInputHandler* GetInputHandler() const; void UpdateInputHandler( sal_Bool bForce = sal_False, sal_Bool bStopEditing = sal_True ); void UpdateInputHandlerCellAdjust( SvxCellHorJustify eJust ); sal_Bool TabKeyInput(const KeyEvent& rKEvt); sal_Bool SfxKeyInput(const KeyEvent& rKEvt); void SetActive(); SvxBorderLine* GetDefaultFrameLine() const { return pCurFrameLine; } void SetDefaultFrameLine(const SvxBorderLine* pLine ); //UNUSED2008-05 void ExecuteShowNIY( SfxRequest& rReq ); //UNUSED2008-05 void StateDisabled( SfxItemSet& rSet ); SC_DLLPUBLIC void Execute( SfxRequest& rReq ); SC_DLLPUBLIC void GetState( SfxItemSet& rSet ); void ExecuteTable( SfxRequest& rReq ); void GetStateTable( SfxItemSet& rSet ); void WindowChanged(); void ExecDraw(SfxRequest&); void ExecDrawIns(SfxRequest& rReq); void GetDrawState(SfxItemSet &rSet); void GetDrawInsState(SfxItemSet &rSet); void ExecGallery(SfxRequest& rReq); // StarGallery void GetGalleryState(SfxItemSet& rSet); void ExecChildWin(SfxRequest& rReq); void GetChildWinState( SfxItemSet& rSet ); void ExecImageMap( SfxRequest& rReq ); void GetImageMapState( SfxItemSet& rSet ); void ExecTbx( SfxRequest& rReq ); void GetTbxState( SfxItemSet& rSet ); void ExecuteSave( SfxRequest& rReq ); void GetSaveState( SfxItemSet& rSet ); void ExecSearch( SfxRequest& rReq ); void ExecuteUndo(SfxRequest& rReq); void GetUndoState(SfxItemSet &rSet); void ExecuteSbx( SfxRequest& rReq ); void GetSbxState( SfxItemSet& rSet ); void ExecuteObject(SfxRequest& rReq); void GetObjectState(SfxItemSet &rSet); void ExecDrawOpt(SfxRequest& rReq); void GetDrawOptState(SfxItemSet &rSet); void UpdateDrawShell(); void SetDrawShell( sal_Bool bActive ); void SetDrawTextShell( sal_Bool bActive ); void SetPivotShell( sal_Bool bActive ); ScArea* GetPivotSource(){return pPivotSource;} void SetPivotSource(ScArea* pSrc){pPivotSource=pSrc;} void SetDialogDPObject( const ScDPObject* pObj ); const ScDPObject* GetDialogDPObject() const { return pDialogDPObject; } sal_Bool GetDontSwitch(){return bDontSwitch;} void SetDontSwitch(sal_Bool bFlag){bDontSwitch=bFlag;} void SetAuditShell( sal_Bool bActive ); void SetDrawFormShell( sal_Bool bActive ); void SetEditShell(EditView* pView, sal_Bool bActive ); void SetOleObjectShell( sal_Bool bActive ); void SetChartShell( sal_Bool bActive ); void SetGraphicShell( sal_Bool bActive ); void SetMediaShell( sal_Bool bActive ); void SetDrawShellOrSub(); void SetCurSubShell( ObjectSelectionType eOST, sal_Bool bForce = sal_False ); void SetFormShellAtTop( sal_Bool bSet ); ObjectSelectionType GetCurObjectSelectionType(); virtual ErrCode DoVerb(long nVerb); void StopEditShell(); sal_Bool IsDrawTextShell() const; sal_Bool IsAuditShell() const; void SetDrawTextUndo( ::svl::IUndoManager* pUndoMgr ); void FillFieldData( ScHeaderFieldData& rData ); //UNUSED2008-05 void ResetChartArea(); void SetChartArea( const ScRangeListRef& rSource, const Rectangle& rDest ); sal_Bool GetChartArea( ScRangeListRef& rSource, Rectangle& rDest, SCTAB& rTab ) const; //UNUSED2008-05 sal_Bool IsChartDlgEdit() const; //UNUSED2008-05 void SetChartDlgEdit(sal_Bool bFlag){bChartDlgIsEdit=bFlag;} void SetEditChartName(const String& aStr){aEditChartName=aStr;} //UNUSED2008-05 const String& GetEditChartName() const; virtual void Notify( SfxBroadcaster& rBC, const SfxHint& rHint ); ScNavigatorSettings* GetNavigatorSettings(); // Drucken: virtual SfxPrinter* GetPrinter( sal_Bool bCreate = sal_False ); virtual sal_uInt16 SetPrinter( SfxPrinter* pNewPrinter, sal_uInt16 nDiffFlags = SFX_PRINTER_ALL, bool bIsApi=false ); virtual SfxTabPage* CreatePrintOptionsPage( Window *pParent, const SfxItemSet &rOptions ); void ConnectObject( SdrOle2Obj* pObj ); sal_Bool ActivateObject( SdrOle2Obj* pObj, long nVerb ); void DeactivateOle(); SC_DLLPUBLIC static ScTabViewShell* GetActiveViewShell(); SfxModelessDialog* CreateRefDialog( SfxBindings* pB, SfxChildWindow* pCW, SfxChildWinInfo* pInfo, Window* pParent, sal_uInt16 nSlotId ); void UpdateOleZoom(); inline SbxObject* GetScSbxObject() const { return pScSbxObject; } inline void SetScSbxObject( SbxObject* pOb ) { pScSbxObject = pOb; } FmFormShell* GetFormShell() const { return pFormShell; } void InsertURL( const String& rName, const String& rURL, const String& rTarget, sal_uInt16 nMode ); void InsertURLButton( const String& rName, const String& rURL, const String& rTarget, const Point* pInsPos = NULL ); void InsertURLField( const String& rName, const String& rURL, const String& rTarget ); sal_Bool SelectObject( const String& rName ); void SetInFormatDialog(sal_Bool bFlag) {bInFormatDialog=bFlag;} sal_Bool IsInFormatDialog() {return bInFormatDialog;} void ForceMove() { Move(); } void MakeNumberInfoItem ( ScDocument* pDoc, ScViewData* pViewData, SvxNumberInfoItem** ppItem ); void UpdateNumberFormatter ( ScDocument* pDoc, const SvxNumberInfoItem& rInfoItem ); void ExecuteCellFormatDlg ( SfxRequest& rReq, sal_uInt16 nTabPage = 0xffff ); sal_Bool GetFunction( String& rFuncStr, sal_uInt16 nErrCode = 0 ); void StartSimpleRefDialog( const String& rTitle, const String& rInitVal, sal_Bool bCloseOnButtonUp, sal_Bool bSingleCell, sal_Bool bMultiSelection ); void StopSimpleRefDialog(); void SetCurRefDlgId( sal_uInt16 nNew ); void AddAccessibilityObject( SfxListener& rObject ); void RemoveAccessibilityObject( SfxListener& rObject ); void BroadcastAccessibility( const SfxHint &rHint ); sal_Bool HasAccessibilityObjects(); bool ExecuteRetypePassDlg(ScPasswordHash eDesiredHash); using ScTabView::ShowCursor; sal_Bool IsActive(){ return bIsActive; } rtl::OUString GetFormula(ScAddress& rAddress); const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > & GetForms() const; // i123629 sal_Bool GetForceFocusOnCurCell(){return bForceFocusOnCurCell;} void SetForceFocusOnCurCell(sal_Bool bFlag){bForceFocusOnCurCell=bFlag;} }; //================================================================== #endif /****************************************************************************** - domain: Codeforces - contest: 1145 - problem: C - title: Mystery Circuit - link: https://codeforces.com/contest/1145/problem/C - hash: CF_1145_C - author: - version: 1.0 02/04/2019 - tags: implementation - language: C++17 ******************************************************************************/ /* This solution is WA */ /****************************************************************************** - time: 1s - memory: 256mb - test: input: | 3 output: | 13 ******************************************************************************/ #ifndef math_topology_sico_property_ID #define math_topology_sico_property_ID // ::math::topology::sico::property::ID #include "../simplex/loaded.hpp" namespace math { namespace topology { namespace sico { namespace property { template < typename data_name //!< Essentially whatever. Copyable > inline std::size_t const & ID ( ::math::topology::sico::simplex::loaded const& simplex ) { static std::size_t id=0; return id; } } } } } #endif prasoonbatham11/ProjectEulerPlus #include unsigned long long lim = (unsigned long long )(9e18); unsigned long long mulmod(unsigned long long a, unsigned long long b, unsigned long long modulo) { a %= modulo; b %= modulo; if (a <= lim && b <= lim) return (a * b) % modulo; if (b > a) std::swap(a, b); unsigned long long result = 0; while (a > 0 && b > 0) { if (b & 1) { result += a; if (result >= modulo) result -= modulo; } a <<= 1; if (a >= modulo) a -= modulo; b >>= 1; } return result; } unsigned long long nugget(unsigned long long n, unsigned long long modulo) { n *= 2; unsigned long long fibo [2][2]= { { 1, 1 }, { 1, 0 } }; unsigned long long result[2][2]= { { 1, 0 }, // { { F(n+1), F(n) }, { 0, 1 } }; // { F(n), F(n-1) } } while (n > 0) { if (n & 1) { unsigned long long t00 = mulmod(result[0][0], fibo[0][0], modulo) + mulmod(result[0][1], fibo[1][0], modulo); unsigned long long t01 = mulmod(result[0][0], fibo[0][1], modulo) + mulmod(result[0][1], fibo[1][1], modulo); unsigned long long t10 = mulmod(result[1][0], fibo[0][0], modulo) + mulmod(result[1][1], fibo[1][0], modulo); unsigned long long t11 = mulmod(result[1][0], fibo[0][1], modulo) + mulmod(result[1][1], fibo[1][1], modulo); if (t00 >= modulo) t00 -= modulo; if (t01 >= modulo) t01 -= modulo; if (t10 >= modulo) t10 -= modulo; if (t11 >= modulo) t11 -= modulo; result[0][0] = t00; result[0][1] = t01; result[1][0] = t10; result[1][1] = t11; } unsigned long long t00 = mulmod(fibo[0][0], fibo[0][0], modulo) + mulmod(fibo[0][1], fibo[1][0], modulo); unsigned long long t01 = mulmod(fibo[0][0], fibo[0][1], modulo) + mulmod(fibo[0][1], fibo[1][1], modulo); unsigned long long t10 = mulmod(fibo[1][0], fibo[0][0], modulo) + mulmod(fibo[1][1], fibo[1][0], modulo); unsigned long long t11 = mulmod(fibo[1][0], fibo[0][1], modulo) + mulmod(fibo[1][1], fibo[1][1], modulo); if (t00 >= modulo) t00 -= modulo; if (t01 >= modulo) t01 -= modulo; if (t10 >= modulo) t10 -= modulo; if (t11 >= modulo) t11 -= modulo; fibo[0][0] = t00; fibo[0][1] = t01; fibo[1][0] = t10; fibo[1][1] = t11; n >>= 1; } return (result[0][0] * result[0][1]) % modulo; } int main() { const unsigned long long Modulo = 1000000007; unsigned int tests = 1; std::cin >> tests; while (tests--) { unsigned long long n; std::cin >> n; std::cout << nugget(n, Modulo) << std::endl; } return 0; } source/typecheck/polymorph/instantiator.cpp // instantiator.cpp // Copyright (c) 2017, // Licensed under the Apache License Version 2.0. #include "ast.h" #include "sst.h" #include "ir/type.h" #include "typecheck.h" #include "polymorph.h" #include "resolver.h" namespace sst { namespace poly { namespace internal { static SimpleError* complainAboutMissingSolutions(const Location& l, ast::Parameterisable* thing, const std::vector& missing) { auto strs = util::map(missing, [](fir::PolyPlaceholderType* p) -> std::string { return p->str().substr(1); }); auto mstr = util::listToEnglish(strs); return SimpleError::make(l, "type %s %s could not be inferred", util::plural("parameter", strs.size()), mstr); } std::vector getMissingSolutions(const std::unordered_map& needed, const TypeParamMap_t& solution, bool allowPlaceholders) { std::vector missing; for(const auto& [ name, constr ] : needed) { (void) constr; if(auto it = solution.find(name); it == solution.end()) missing.push_back(name); else if(!allowPlaceholders && it->second->containsPlaceholders()) missing.push_back(name); } return missing; } std::pair solvePolymorphWithPlaceholders(TypecheckState* fs, ast::Parameterisable* thing, const std::string& name, const TypeParamMap_t& partial) { TypeParamMap_t copy = partial; int session = getNextSessionId(); for(const auto& p : thing->generics) { if(copy.find(p.first) == copy.end()) copy[p.first] = fir::PolyPlaceholderType::get(p.first, session); } return attemptToInstantiatePolymorph(fs, thing, name, copy, /* return_infer: */ 0, /* type_infer: */ 0, /* isFnCall: */ false, /* args: */ { }, /* fillplaceholders: */ false); } } std::pair attemptToInstantiatePolymorph(TypecheckState* fs, ast::Parameterisable* thing, const std::string& name, const TypeParamMap_t& _gmaps, fir::Type* return_infer, fir::Type* type_infer, bool isFnCall, std::vector* args, bool fillplaceholders, fir::Type* problem_infer) { if(!isFnCall && type_infer == 0 && fillplaceholders) return internal::solvePolymorphWithPlaceholders(fs, thing, name, _gmaps); // used below. std::unordered_map origParamOrder; auto [ soln, err ] = internal::inferTypesForPolymorph(fs, thing, name, thing->generics, *args, _gmaps, return_infer, type_infer, isFnCall, problem_infer, &origParamOrder); if(err) return { TCResult(err), soln }; if(auto d = fullyInstantiatePolymorph(fs, thing, soln.solutions); d.isDefn()) { if(isFnCall) { // if(auto missing = internal::getMissingSolutions(thing->generics, soln.solutions, /* allowPlaceholders: */ false); missing.size() > 0) if(auto missing = d.defn()->type->getContainedPlaceholders(); missing.size() > 0) { auto se = SpanError::make(internal::complainAboutMissingSolutions(thing->loc, thing, missing)); return std::make_pair( TCResult(err->append(se)->append(SimpleError::make(fs->loc(), "partial solution: %s", util::listToString(util::map(util::pairs(soln.solutions), [](const std::pair& p) -> std::string { return strprintf("%s = %s", p.first, p.second); }), [](const std::string& s) -> std::string { return s; } )))), soln ); } else { size_t counter = 0; for(auto& arg : *args) { if(arg.value->type->containsPlaceholders() && arg.orig) { //! ACHTUNG ! /* * note * the implication here is that by calling 'inferTypesForPolymorph', which itself calls 'solveTypeList', we will have weeded out all of the function candidates that don't match (ie. overload distance == -1) therefore, we can operate under the assumption that the _parameter_ type of the function will be fully substituted and not have any placeholders, and that it will be a valid infer target for the _argument_. using the newly-gained arg_infer information, we can re-typecheck the argument with concrete types. - zhiayang - 06/10/18/2318 */ auto arg_infer = d.defn()->type->toFunctionType()->getArgumentN(arg.name.empty() ? counter : origParamOrder[arg.name]); auto tc = arg.orig->typecheck(fs, arg_infer); arg.value = tc.expr(); } counter += 1; } } } return std::make_pair(TCResult(d.defn()), soln); } else { iceAssert(d.isError()); return std::make_pair(TCResult(d.error()), soln); } } //* gets an generic type in the AST form and returns a concrete SST node from it, given the mappings. TCResult fullyInstantiatePolymorph(TypecheckState* fs, ast::Parameterisable* thing, const TypeParamMap_t& mappings) { iceAssert(thing); // iceAssert(!thing->generics.empty()); // try to see if we already have a generic version. if(auto [ found, def ] = thing->checkForExistingDeclaration(fs, mappings); found && def) return TCResult(def); fs->pushGenericContext(); defer(fs->popGenericContext()); //* allowFail is only allowed to forgive a failure when we're checking for type conformance to protocols or something like that. //* we generally don't look into type or function bodies when checking stuff, and it'd be hard to check for something like this (eg. //* T passes all the checks, but causes some kind of type-checking failure when substituted in) // TODO: ??? do we want this to be the behaviour ??? for(auto map : mappings) { int ptrs = 0; { auto t = map.second; while(t->isPointerType()) t = t->getPointerElementType(), ptrs++; } if(thing->generics.find(map.first) != thing->generics.end() && ptrs < thing->generics[map.first].pointerDegree) { return TCResult( SimpleError::make(fs->loc(), "cannot map type '%s' to type parameter '%s' in instantiation of generic type '%s'", map.second, map.first, thing->name)->append( SimpleError::make(MsgType::Note, thing->loc, "replacement type has pointer degree %d, which is less than the required %d", ptrs, thing->generics[map.first].pointerDegree) ) ); } // TODO: check if the type conforms to the protocols specified. //* check if it satisfies the protocols. // ok, push the thing. fs->addGenericMapping(map.first, map.second); } fir::Type* self_infer = 0; if(thing->parentType) { // instantiate that as well, I guess. auto res = fullyInstantiatePolymorph(fs, thing->parentType, mappings); if(res.isError()) return TCResult(res); self_infer = res.defn()->type; } if(auto missing = internal::getMissingSolutions(thing->generics, mappings, true); missing.size() > 0) { auto mstr = util::listToEnglish(missing); return TCResult(SimpleError::make(fs->loc(), "type %s %s could not be inferred", util::plural("parameter", missing.size()), mstr)); } return thing->typecheck(fs, self_infer, mappings); } } } #include "precompiled.h" // // Copyright (c) 2002-2013 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. // // utilities.cpp: Conversion functions and other utility routines. #include "libGLESv2/utilities.h" #include "libGLESv2/mathutil.h" namespace gl { int UniformComponentCount(GLenum type) { switch (type) { case GL_BOOL: case GL_FLOAT: case GL_INT: case GL_SAMPLER_2D: case GL_SAMPLER_CUBE: return 1; case GL_BOOL_VEC2: case GL_FLOAT_VEC2: case GL_INT_VEC2: return 2; case GL_INT_VEC3: case GL_FLOAT_VEC3: case GL_BOOL_VEC3: return 3; case GL_BOOL_VEC4: case GL_FLOAT_VEC4: case GL_INT_VEC4: case GL_FLOAT_MAT2: return 4; case GL_FLOAT_MAT3: return 9; case GL_FLOAT_MAT4: return 16; default: UNREACHABLE(); } return 0; } GLenum UniformComponentType(GLenum type) { switch(type) { case GL_BOOL: case GL_BOOL_VEC2: case GL_BOOL_VEC3: case GL_BOOL_VEC4: return GL_BOOL; case GL_FLOAT: case GL_FLOAT_VEC2: case GL_FLOAT_VEC3: case GL_FLOAT_VEC4: case GL_FLOAT_MAT2: case GL_FLOAT_MAT3: case GL_FLOAT_MAT4: return GL_FLOAT; case GL_INT: case GL_SAMPLER_2D: case GL_SAMPLER_CUBE: case GL_INT_VEC2: case GL_INT_VEC3: case GL_INT_VEC4: return GL_INT; default: UNREACHABLE(); } return GL_NONE; } size_t UniformComponentSize(GLenum type) { switch(type) { case GL_BOOL: return sizeof(GLint); case GL_FLOAT: return sizeof(GLfloat); case GL_INT: return sizeof(GLint); default: UNREACHABLE(); } return 0; } size_t UniformInternalSize(GLenum type) { // Expanded to 4-element vectors return UniformComponentSize(UniformComponentType(type)) * VariableRowCount(type) * 4; } size_t UniformExternalSize(GLenum type) { return UniformComponentSize(UniformComponentType(type)) * UniformComponentCount(type); } int VariableRowCount(GLenum type) { switch (type) { case GL_NONE: return 0; case GL_BOOL: case GL_FLOAT: case GL_INT: case GL_BOOL_VEC2: case GL_FLOAT_VEC2: case GL_INT_VEC2: case GL_INT_VEC3: case GL_FLOAT_VEC3: case GL_BOOL_VEC3: case GL_BOOL_VEC4: case GL_FLOAT_VEC4: case GL_INT_VEC4: case GL_SAMPLER_2D: case GL_SAMPLER_CUBE: return 1; case GL_FLOAT_MAT2: return 2; case GL_FLOAT_MAT3: return 3; case GL_FLOAT_MAT4: return 4; default: UNREACHABLE(); } return 0; } int VariableColumnCount(GLenum type) { switch (type) { case GL_NONE: return 0; case GL_BOOL: case GL_FLOAT: case GL_INT: case GL_SAMPLER_2D: case GL_SAMPLER_CUBE: return 1; case GL_BOOL_VEC2: case GL_FLOAT_VEC2: case GL_INT_VEC2: case GL_FLOAT_MAT2: return 2; case GL_INT_VEC3: case GL_FLOAT_VEC3: case GL_BOOL_VEC3: case GL_FLOAT_MAT3: return 3; case GL_BOOL_VEC4: case GL_FLOAT_VEC4: case GL_INT_VEC4: case GL_FLOAT_MAT4: return 4; default: UNREACHABLE(); } return 0; } int AllocateFirstFreeBits(unsigned int *bits, unsigned int allocationSize, unsigned int bitsSize) { ASSERT(allocationSize <= bitsSize); unsigned int mask = std::numeric_limits::max() >> (std::numeric_limits::digits - allocationSize); for (unsigned int i = 0; i < bitsSize - allocationSize + 1; i++) { if ((*bits & mask) == 0) { *bits |= mask; return i; } mask <<= 1; } return -1; } GLsizei ComputePitch(GLsizei width, GLint internalformat, GLint alignment) { ASSERT(alignment > 0 && isPow2(alignment)); GLsizei rawPitch = ComputePixelSize(internalformat) * width; return (rawPitch + alignment - 1) & ~(alignment - 1); } GLsizei ComputeCompressedPitch(GLsizei width, GLenum internalformat) { return ComputeCompressedSize(width, 1, internalformat); } GLsizei ComputeCompressedSize(GLsizei width, GLsizei height, GLenum internalformat) { switch (internalformat) { case GL_COMPRESSED_RGB_S3TC_DXT1_EXT: case GL_COMPRESSED_RGBA_S3TC_DXT1_EXT: return 8 * ((width + 3) / 4) * ((height + 3) / 4); case GL_COMPRESSED_RGBA_S3TC_DXT3_ANGLE: case GL_COMPRESSED_RGBA_S3TC_DXT5_ANGLE: return 16 * ((width + 3) / 4) * ((height + 3) / 4); default: return 0; } } GLsizei ComputeTypeSize(GLenum type) { switch (type) { case GL_BYTE: return 1; case GL_UNSIGNED_BYTE: return 1; case GL_SHORT: return 2; case GL_UNSIGNED_SHORT: return 2; case GL_INT: return 4; case GL_UNSIGNED_INT: return 4; case GL_FLOAT: return 4; case GL_HALF_FLOAT_OES: return 2; case GL_UNSIGNED_SHORT_5_6_5: return 2; case GL_UNSIGNED_SHORT_4_4_4_4: return 2; case GL_UNSIGNED_SHORT_5_5_5_1: return 2; case GL_UNSIGNED_SHORT_4_4_4_4_REV_EXT: return 2; case GL_UNSIGNED_SHORT_1_5_5_5_REV_EXT: return 2; case GL_UNSIGNED_INT_2_10_10_10_REV_EXT: return 4; case GL_UNSIGNED_INT_24_8_OES: return 4; default: UNREACHABLE(); return 0; } } bool IsCompressed(GLenum format) { if(format == GL_COMPRESSED_RGB_S3TC_DXT1_EXT || format == GL_COMPRESSED_RGBA_S3TC_DXT1_EXT || format == GL_COMPRESSED_RGBA_S3TC_DXT3_ANGLE || format == GL_COMPRESSED_RGBA_S3TC_DXT5_ANGLE) { return true; } else { return false; } } bool IsDepthTexture(GLenum format) { if (format == GL_DEPTH_COMPONENT || format == GL_DEPTH_STENCIL_OES || format == GL_DEPTH_COMPONENT16 || format == GL_DEPTH_COMPONENT32_OES || format == GL_DEPTH24_STENCIL8_OES) { return true; } return false; } bool IsStencilTexture(GLenum format) { if (format == GL_DEPTH_STENCIL_OES || format == GL_DEPTH24_STENCIL8_OES) { return true; } return false; } void MakeValidSize(bool isImage, bool isCompressed, GLsizei *requestWidth, GLsizei *requestHeight, int *levelOffset) { int upsampleCount = 0; if (isCompressed) { // Don't expand the size of full textures that are at least 4x4 // already. if (isImage || *requestWidth < 4 || *requestHeight < 4) { while (*requestWidth % 4 != 0 || *requestHeight % 4 != 0) { *requestWidth <<= 1; *requestHeight <<= 1; upsampleCount++; } } } *levelOffset = upsampleCount; } // Returns the size, in bytes, of a single texel in an Image int ComputePixelSize(GLint internalformat) { switch (internalformat) { case GL_ALPHA8_EXT: return sizeof(unsigned char); case GL_LUMINANCE8_EXT: return sizeof(unsigned char); case GL_ALPHA32F_EXT: return sizeof(float); case GL_LUMINANCE32F_EXT: return sizeof(float); case GL_ALPHA16F_EXT: return sizeof(unsigned short); case GL_LUMINANCE16F_EXT: return sizeof(unsigned short); case GL_LUMINANCE8_ALPHA8_EXT: return sizeof(unsigned char) * 2; case GL_LUMINANCE_ALPHA32F_EXT: return sizeof(float) * 2; case GL_LUMINANCE_ALPHA16F_EXT: return sizeof(unsigned short) * 2; case GL_RGB8_OES: return sizeof(unsigned char) * 3; case GL_RGB565: return sizeof(unsigned short); case GL_RGB32F_EXT: return sizeof(float) * 3; case GL_RGB16F_EXT: return sizeof(unsigned short) * 3; case GL_RGBA8_OES: return sizeof(unsigned char) * 4; case GL_RGBA4: return sizeof(unsigned short); case GL_RGB5_A1: return sizeof(unsigned short); case GL_RGBA32F_EXT: return sizeof(float) * 4; case GL_RGBA16F_EXT: return sizeof(unsigned short) * 4; case GL_BGRA8_EXT: return sizeof(unsigned char) * 4; case GL_BGRA4_ANGLEX: return sizeof(unsigned short); case GL_BGR5_A1_ANGLEX: return sizeof(unsigned short); default: UNREACHABLE(); } return 0; } bool IsCubemapTextureTarget(GLenum target) { return (target >= GL_TEXTURE_CUBE_MAP_POSITIVE_X && target <= GL_TEXTURE_CUBE_MAP_NEGATIVE_Z); } bool IsInternalTextureTarget(GLenum target) { return target == GL_TEXTURE_2D || IsCubemapTextureTarget(target); } GLint ConvertSizedInternalFormat(GLenum format, GLenum type) { switch (format) { case GL_ALPHA: switch (type) { case GL_UNSIGNED_BYTE: return GL_ALPHA8_EXT; case GL_FLOAT: return GL_ALPHA32F_EXT; case GL_HALF_FLOAT_OES: return GL_ALPHA16F_EXT; default: UNIMPLEMENTED(); } break; case GL_LUMINANCE: switch (type) { case GL_UNSIGNED_BYTE: return GL_LUMINANCE8_EXT; case GL_FLOAT: return GL_LUMINANCE32F_EXT; case GL_HALF_FLOAT_OES: return GL_LUMINANCE16F_EXT; default: UNIMPLEMENTED(); } break; case GL_LUMINANCE_ALPHA: switch (type) { case GL_UNSIGNED_BYTE: return GL_LUMINANCE8_ALPHA8_EXT; case GL_FLOAT: return GL_LUMINANCE_ALPHA32F_EXT; case GL_HALF_FLOAT_OES: return GL_LUMINANCE_ALPHA16F_EXT; default: UNIMPLEMENTED(); } break; case GL_RGB: switch (type) { case GL_UNSIGNED_BYTE: return GL_RGB8_OES; case GL_UNSIGNED_SHORT_5_6_5: return GL_RGB565; case GL_FLOAT: return GL_RGB32F_EXT; case GL_HALF_FLOAT_OES: return GL_RGB16F_EXT; default: UNIMPLEMENTED(); } break; case GL_RGBA: switch (type) { case GL_UNSIGNED_BYTE: return GL_RGBA8_OES; case GL_UNSIGNED_SHORT_4_4_4_4: return GL_RGBA4; case GL_UNSIGNED_SHORT_5_5_5_1: return GL_RGB5_A1; case GL_FLOAT: return GL_RGBA32F_EXT; case GL_HALF_FLOAT_OES: return GL_RGBA16F_EXT; break; default: UNIMPLEMENTED(); } break; case GL_BGRA_EXT: switch (type) { case GL_UNSIGNED_BYTE: return GL_BGRA8_EXT; case GL_UNSIGNED_SHORT_4_4_4_4_REV_EXT: return GL_BGRA4_ANGLEX; case GL_UNSIGNED_SHORT_1_5_5_5_REV_EXT: return GL_BGR5_A1_ANGLEX; default: UNIMPLEMENTED(); } break; case GL_COMPRESSED_RGB_S3TC_DXT1_EXT: case GL_COMPRESSED_RGBA_S3TC_DXT1_EXT: case GL_COMPRESSED_RGBA_S3TC_DXT3_ANGLE: case GL_COMPRESSED_RGBA_S3TC_DXT5_ANGLE: return format; case GL_DEPTH_COMPONENT: switch (type) { case GL_UNSIGNED_SHORT: return GL_DEPTH_COMPONENT16; case GL_UNSIGNED_INT: return GL_DEPTH_COMPONENT32_OES; default: UNIMPLEMENTED(); } break; case GL_DEPTH_STENCIL_OES: switch (type) { case GL_UNSIGNED_INT_24_8_OES: return GL_DEPTH24_STENCIL8_OES; default: UNIMPLEMENTED(); } break; default: UNIMPLEMENTED(); } return GL_NONE; } GLenum ExtractFormat(GLenum internalformat) { switch (internalformat) { case GL_RGB565: return GL_RGB; case GL_RGBA4: return GL_RGBA; case GL_RGB5_A1: return GL_RGBA; case GL_RGB8_OES: return GL_RGB; case GL_RGBA8_OES: return GL_RGBA; case GL_LUMINANCE8_ALPHA8_EXT: return GL_LUMINANCE_ALPHA; case GL_LUMINANCE8_EXT: return GL_LUMINANCE; case GL_ALPHA8_EXT: return GL_ALPHA; case GL_COMPRESSED_RGB_S3TC_DXT1_EXT: return GL_COMPRESSED_RGB_S3TC_DXT1_EXT; case GL_COMPRESSED_RGBA_S3TC_DXT1_EXT: return GL_COMPRESSED_RGBA_S3TC_DXT1_EXT; case GL_COMPRESSED_RGBA_S3TC_DXT3_ANGLE: return GL_COMPRESSED_RGBA_S3TC_DXT3_ANGLE; case GL_COMPRESSED_RGBA_S3TC_DXT5_ANGLE: return GL_COMPRESSED_RGBA_S3TC_DXT5_ANGLE; case GL_RGBA32F_EXT: return GL_RGBA; case GL_RGB32F_EXT: return GL_RGB; case GL_ALPHA32F_EXT: return GL_ALPHA; case GL_LUMINANCE32F_EXT: return GL_LUMINANCE; case GL_LUMINANCE_ALPHA32F_EXT: return GL_LUMINANCE_ALPHA; case GL_RGBA16F_EXT: return GL_RGBA; case GL_RGB16F_EXT: return GL_RGB; case GL_ALPHA16F_EXT: return GL_ALPHA; case GL_LUMINANCE16F_EXT: return GL_LUMINANCE; case GL_LUMINANCE_ALPHA16F_EXT: return GL_LUMINANCE_ALPHA; case GL_BGRA8_EXT: return GL_BGRA_EXT; case GL_DEPTH_COMPONENT16: return GL_DEPTH_COMPONENT; case GL_DEPTH_COMPONENT32_OES: return GL_DEPTH_COMPONENT; case GL_DEPTH24_STENCIL8_OES: return GL_DEPTH_STENCIL_OES; default: return GL_NONE; // Unsupported } } GLenum ExtractType(GLenum internalformat) { switch (internalformat) { case GL_RGB565: return GL_UNSIGNED_SHORT_5_6_5; case GL_RGBA4: return GL_UNSIGNED_SHORT_4_4_4_4; case GL_RGB5_A1: return GL_UNSIGNED_SHORT_5_5_5_1; case GL_RGB8_OES: return GL_UNSIGNED_BYTE; case GL_RGBA8_OES: return GL_UNSIGNED_BYTE; case GL_LUMINANCE8_ALPHA8_EXT: return GL_UNSIGNED_BYTE; case GL_LUMINANCE8_EXT: return GL_UNSIGNED_BYTE; case GL_ALPHA8_EXT: return GL_UNSIGNED_BYTE; case GL_COMPRESSED_RGB_S3TC_DXT1_EXT: return GL_UNSIGNED_BYTE; case GL_COMPRESSED_RGBA_S3TC_DXT1_EXT: return GL_UNSIGNED_BYTE; case GL_COMPRESSED_RGBA_S3TC_DXT3_ANGLE: return GL_UNSIGNED_BYTE; case GL_COMPRESSED_RGBA_S3TC_DXT5_ANGLE: return GL_UNSIGNED_BYTE; case GL_RGBA32F_EXT: return GL_FLOAT; case GL_RGB32F_EXT: return GL_FLOAT; case GL_ALPHA32F_EXT: return GL_FLOAT; case GL_LUMINANCE32F_EXT: return GL_FLOAT; case GL_LUMINANCE_ALPHA32F_EXT: return GL_FLOAT; case GL_RGBA16F_EXT: return GL_HALF_FLOAT_OES; case GL_RGB16F_EXT: return GL_HALF_FLOAT_OES; case GL_ALPHA16F_EXT: return GL_HALF_FLOAT_OES; case GL_LUMINANCE16F_EXT: return GL_HALF_FLOAT_OES; case GL_LUMINANCE_ALPHA16F_EXT: return GL_HALF_FLOAT_OES; case GL_BGRA8_EXT: return GL_UNSIGNED_BYTE; case GL_DEPTH_COMPONENT16: return GL_UNSIGNED_SHORT; case GL_DEPTH_COMPONENT32_OES: return GL_UNSIGNED_INT; case GL_DEPTH24_STENCIL8_OES: return GL_UNSIGNED_INT_24_8_OES; default: return GL_NONE; // Unsupported } } bool IsColorRenderable(GLenum internalformat) { switch (internalformat) { case GL_RGBA4: case GL_RGB5_A1: case GL_RGB565: case GL_RGB8_OES: case GL_RGBA8_OES: return true; case GL_DEPTH_COMPONENT16: case GL_STENCIL_INDEX8: case GL_DEPTH24_STENCIL8_OES: return false; case GL_BGRA8_EXT: return true; default: UNIMPLEMENTED(); } return false; } bool IsDepthRenderable(GLenum internalformat) { switch (internalformat) { case GL_DEPTH_COMPONENT16: case GL_DEPTH24_STENCIL8_OES: return true; case GL_STENCIL_INDEX8: case GL_RGBA4: case GL_RGB5_A1: case GL_RGB565: case GL_RGB8_OES: case GL_RGBA8_OES: return false; default: UNIMPLEMENTED(); } return false; } bool IsStencilRenderable(GLenum internalformat) { switch (internalformat) { case GL_STENCIL_INDEX8: case GL_DEPTH24_STENCIL8_OES: return true; case GL_RGBA4: case GL_RGB5_A1: case GL_RGB565: case GL_RGB8_OES: case GL_RGBA8_OES: case GL_DEPTH_COMPONENT16: return false; default: UNIMPLEMENTED(); } return false; } bool IsFloat32Format(GLint internalformat) { switch (internalformat) { case GL_RGBA32F_EXT: case GL_RGB32F_EXT: case GL_ALPHA32F_EXT: case GL_LUMINANCE32F_EXT: case GL_LUMINANCE_ALPHA32F_EXT: return true; default: return false; } } bool IsFloat16Format(GLint internalformat) { switch (internalformat) { case GL_RGBA16F_EXT: case GL_RGB16F_EXT: case GL_ALPHA16F_EXT: case GL_LUMINANCE16F_EXT: case GL_LUMINANCE_ALPHA16F_EXT: return true; default: return false; } } unsigned int GetAlphaSize(GLenum colorFormat) { switch (colorFormat) { case GL_RGBA16F_EXT: return 16; case GL_RGBA32F_EXT: return 32; case GL_RGBA4: return 4; case GL_RGBA8_OES: case GL_BGRA8_EXT: return 8; case GL_RGB5_A1: return 1; case GL_RGB8_OES: case GL_RGB565: case GL_RGB32F_EXT: case GL_RGB16F_EXT: return 0; default: return 0; } } unsigned int GetRedSize(GLenum colorFormat) { switch (colorFormat) { case GL_RGBA16F_EXT: case GL_RGB16F_EXT: return 16; case GL_RGBA32F_EXT: case GL_RGB32F_EXT: return 32; case GL_RGBA4: return 4; case GL_RGBA8_OES: case GL_BGRA8_EXT: case GL_RGB8_OES: return 8; case GL_RGB5_A1: case GL_RGB565: return 5; default: return 0; } } unsigned int GetGreenSize(GLenum colorFormat) { switch (colorFormat) { case GL_RGBA16F_EXT: case GL_RGB16F_EXT: return 16; case GL_RGBA32F_EXT: case GL_RGB32F_EXT: return 32; case GL_RGBA4: return 4; case GL_RGBA8_OES: case GL_BGRA8_EXT: case GL_RGB8_OES: return 8; case GL_RGB5_A1: return 5; case GL_RGB565: return 6; default: return 0; } } unsigned int GetBlueSize(GLenum colorFormat) { switch (colorFormat) { case GL_RGBA16F_EXT: case GL_RGB16F_EXT: return 16; case GL_RGBA32F_EXT: case GL_RGB32F_EXT: return 32; case GL_RGBA4: return 4; case GL_RGBA8_OES: case GL_BGRA8_EXT: case GL_RGB8_OES: return 8; case GL_RGB5_A1: case GL_RGB565: return 5; default: return 0; } } unsigned int GetDepthSize(GLenum depthFormat) { switch (depthFormat) { case GL_DEPTH_COMPONENT16: return 16; case GL_DEPTH_COMPONENT32_OES: return 32; case GL_DEPTH24_STENCIL8_OES: return 24; default: return 0; } } unsigned int GetStencilSize(GLenum stencilFormat) { switch (stencilFormat) { case GL_DEPTH24_STENCIL8_OES: return 8; default: return 0; } } bool IsTriangleMode(GLenum drawMode) { switch (drawMode) { case GL_TRIANGLES: case GL_TRIANGLE_FAN: case GL_TRIANGLE_STRIP: return true; case GL_POINTS: case GL_LINES: case GL_LINE_LOOP: case GL_LINE_STRIP: return false; default: UNREACHABLE(); } return false; } } std::string getTempPath() { char path[MAX_PATH]; DWORD pathLen = GetTempPathA(sizeof(path) / sizeof(path[0]), path); if (pathLen == 0) { UNREACHABLE(); return std::string(); } UINT unique = GetTempFileNameA(path, "sh", 0, path); if (unique == 0) { UNREACHABLE(); return std::string(); } return path; } void writeFile(const char* path, const void* content, size_t size) { FILE* file = fopen(path, "w"); if (!file) { UNREACHABLE(); return; } fwrite(content, sizeof(char), size, file); fclose(file); } eniomoreira/trex-core /* TRex team Cisco Systems, Inc. */ /* Copyright (c) 2016-2016 Cisco Systems, 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 "bp_sim.h" #include "trex_stack_base.h" #include "trex_stack_legacy.h" #include "trex_stack_linux_based.h" #include #include #include /*************************************** * CStackBase * ***************************************/ CStackBase::CStackBase(RXFeatureAPI *api, CRXCoreIgnoreStat *ignore_stats) { debug("base stack ctor"); m_api = api; m_ignore_stats = ignore_stats; m_is_running_tasks = false; } CStackBase::~CStackBase(void) { debug("base stack dtor"); assert(m_nodes.size() == 0); } void CStackBase::add_port_node_async(void) { debug("add port node"); uint8_t port_id = m_api->get_port_id(); string port_mac((char*)CGlobalInfo::m_options.m_mac_addr[port_id].u.m_mac.src, 6); add_node_async(port_mac); } void CStackBase::attr_to_json(Json::Value &res) { debug("attr json"); assert(!m_is_running_tasks); // CP should check this Json::Value &cfg = res["layer_cfg"]; // MAC cfg["ether"]["src"] = utl_macaddr_to_str((uint8_t *)m_port_node->get_src_mac().data()); cfg["ether"]["dst"] = utl_macaddr_to_str((uint8_t *)m_port_node->get_dst_mac().data()); cfg["ether"]["state"] = m_port_node->is_dst_mac_valid() ? "configured" : "unconfigured"; // VLAN res["vlan"]["tags"] = Json::arrayValue; for (auto tag : m_port_node->get_vlan()) { res["vlan"]["tags"].append(tag); } // IPv4 if ( m_port_node->get_src_ip4().size() ) { char buf[INET_ADDRSTRLEN]; inet_ntop(AF_INET, m_port_node->get_src_ip4().c_str(), buf, INET_ADDRSTRLEN); cfg["ipv4"]["src"] = buf; inet_ntop(AF_INET, m_port_node->get_dst_ip4().c_str(), buf, INET_ADDRSTRLEN); cfg["ipv4"]["dst"] = buf; if ( m_port_node->is_dst_mac_valid() ) { cfg["ipv4"]["state"] = "resolved"; } else { cfg["ipv4"]["state"] = "unresolved"; } } else { cfg["ipv4"]["state"] = "none"; } if ( m_port_node->is_ip6_enabled() ) { cfg["ipv6"]["enabled"] = true; string ipv6_src = m_port_node->get_src_ip6(); if ( ipv6_src.size() ) { char buf[INET6_ADDRSTRLEN]; inet_ntop(AF_INET6, ipv6_src.c_str(), buf, INET6_ADDRSTRLEN); ipv6_src = buf; } cfg["ipv6"]["src"] = ipv6_src; } else { cfg["ipv6"]["enabled"] = false; } } void CStackBase::grat_to_json(Json::Value &res) { assert(!m_is_running_tasks); // CP should check this res["is_active"] = false; } void CStackBase::add_node_async(const string &mac_buf) { debug("add node"); assert(mac_buf.size()==6); m_add_macs_list.insert(mac_buf); } void CStackBase::del_node_async(const string &mac_buf) { debug("del node"); assert(mac_buf.size()==6); m_del_macs_list.insert(mac_buf); } CNodeBase* CStackBase::get_node(const string &mac_buf) { assert(!m_is_running_tasks); return get_node_internal(mac_buf); } CNodeBase* CStackBase::get_node_internal(const string &mac_buf) { assert(mac_buf.size()==6); auto iter_pair = m_nodes.find(mac_buf); if ( iter_pair != m_nodes.end() ) { return iter_pair->second; } return nullptr; } CNodeBase* CStackBase::get_port_node(void) { assert(m_port_node!=nullptr); assert(!m_is_running_tasks); return m_port_node; } bool CStackBase::has_port(const string &mac_buf) { assert(m_port_node!=nullptr); assert(mac_buf.size()==6); return m_port_node->get_src_mac() == mac_buf; } bool CStackBase::has_capa(capa_enum capa) { return get_capa() & capa; } #define MAX_RESULTS_MAP_ITEMS 128 void clean_old_results(stack_result_map_t &results) { while ( results.size() > MAX_RESULTS_MAP_ITEMS ) { results.erase(results.begin()); } } bool CStackBase::get_tasks_results(uint64_t ticket_id, stack_result_t &results) { auto it = m_results.find(ticket_id); if ( it == m_results.end() ) { return false; } results = it->second; // copy the results if ( it->second.is_ready ) { m_results.erase(it); } return true; } void CStackBase::wait_on_tasks(uint64_t ticket_id, stack_result_t &results, double timeout) { dsec_t start_sec = now_sec(); while ( m_is_running_tasks ) { if ( timeout > 0 && now_sec() > start_sec + timeout ) { cancel_running_tasks(); throw TrexException("Timeout on waiting for results for of ticket " + to_string(ticket_id)); } rte_pause_or_delay_lowend(); } bool found = get_tasks_results(ticket_id, results); if ( !found ) { throw TrexException("Results on ticket " + to_string(ticket_id) + " got deleted"); } } void CStackBase::run_pending_tasks_internal(uint64_t ticket_id) { if ( m_add_macs_list.size() ) { // add nodes CNodeBase *node; for(auto &mac : m_add_macs_list) { try { node = add_node_internal(mac); if ( m_nodes.size() == 1 ) { m_port_node = node; } } catch (const TrexException &ex) { m_results[ticket_id].err_per_mac[mac] = ex.what(); } } m_add_macs_list.clear(); } else if ( m_del_macs_list.size() ) { // del nodes for(auto &mac : m_del_macs_list) { try { del_node_internal(mac); if ( m_nodes.size() == 0 ) { m_port_node = nullptr; } } catch (const TrexException &ex) { m_results[ticket_id].err_per_mac[mac] = ex.what(); } } m_del_macs_list.clear(); } else { // nodes cfg tasks for (auto &node_pair : m_nodes) { debug("another cfg"); try { for (auto &task : node_pair.second->m_tasks) { task(); } } catch (const TrexException &ex) { m_results[ticket_id].err_per_mac[node_pair.first] = ex.what(); } node_pair.second->m_tasks.clear(); } } m_results[ticket_id].is_ready = true; m_is_running_tasks = false; } bool CStackBase::has_pending_tasks(void) { if ( m_add_macs_list.size() || m_del_macs_list.size() ) { return true; } for (auto &node_pair : m_nodes) { if ( node_pair.second->m_tasks.size() ) { return true; } } return false; } void CStackBase::cancel_pending_tasks(void) { debug("Canceling pending tasks"); m_add_macs_list.clear(); m_del_macs_list.clear(); for (auto &node_pair : m_nodes) { node_pair.second->m_tasks.clear(); } } void CStackBase::cancel_running_tasks(void) { debug("Canceling running tasks"); if ( m_is_running_tasks ) { pthread_cancel(m_thread_handle); m_is_running_tasks = false; } } void CStackBase::run_pending_tasks_async(uint64_t ticket_id) { debug({"Run pending tasks for ticket", to_string(ticket_id)}); assert(!m_is_running_tasks); clean_old_results(m_results); if ( !has_pending_tasks() ) { debug("No pending tasks"); m_results[ticket_id].is_ready = true; return; } m_is_running_tasks = true; m_results[ticket_id].is_ready = false; if ( has_capa(FAST_OPS) ) { debug("Running in FG"); run_pending_tasks_internal(ticket_id); } else { debug("Running in BG"); cpu_set_t cpuset; CPU_ZERO(&cpuset); CPU_SET(CGlobalInfo::m_socket.get_master_phy_id(), &cpuset); thread thrd = thread(&CStackBase::run_pending_tasks_internal, this, ticket_id); m_thread_handle = thrd.native_handle(); // run with same affinity as master pthread_setaffinity_np(m_thread_handle, sizeof(cpu_set_t), &cpuset); pthread_setname_np(m_thread_handle, "Trex RX async task"); thrd.detach(); } } void CStackBase::reset_async(void) { cancel_running_tasks(); cancel_pending_tasks(); if ( m_nodes.size() <= 1 ) { return; } for (auto &iter_pair : m_nodes) { if ( iter_pair.second != m_port_node ) { del_node_async(iter_pair.first); } } } void CStackBase::cleanup_async(void) { debug("cleanup"); cancel_running_tasks(); cancel_pending_tasks(); m_results.clear(); for (auto &iter_pair : m_nodes) { del_node_async(iter_pair.first); } } bool CStackBase::is_running_tasks(void) { return m_is_running_tasks; } /*************************************** * CNodeBase * ***************************************/ CNodeBase::CNodeBase() { m_dst_mac_valid = false; m_is_loopback = false; m_ip6_enabled = false; } CNodeBase::~CNodeBase() {} // public conf void CNodeBase::conf_dst_mac_async(const string &dst_mac) { assert(dst_mac.size()==6); debug("conf dst"); if ( dst_mac != m_dst_mac ) { m_tasks.push_back(bind(&CNodeBase::conf_dst_mac_internal, this, dst_mac)); } } void CNodeBase::set_dst_mac_valid_async(void) { debug("set dst valid"); if ( !m_dst_mac_valid ) { m_tasks.push_back(bind(&CNodeBase::set_dst_mac_valid_internal, this, true)); } } void CNodeBase::set_dst_mac_invalid(void) { set_dst_mac_valid_internal(false); } void CNodeBase::set_is_loopback_async(void) { debug("set is loop"); if ( !m_is_loopback ) { m_tasks.push_back(bind(&CNodeBase::set_is_loopback_internal, this, true)); } } void CNodeBase::set_not_loopback(void) { debug("set no loop"); set_is_loopback_internal(false); } void CNodeBase::conf_vlan_async(const vlan_list_t &vlans) { debug("conf vlan"); if ( vlans != m_vlan_tags ) { m_tasks.push_back(bind(&CNodeBase::conf_vlan_internal, this, vlans)); } } void CNodeBase::conf_ip4_async(const string &ip4_buf, const string &gw4_buf) { assert(ip4_buf.size()==4); assert(gw4_buf.size()==4); debug("conf ip4"); if ( ip4_buf != m_ip4 || gw4_buf != m_gw4 ) { m_tasks.push_back(bind(&CNodeBase::conf_ip4_internal, this, ip4_buf, gw4_buf)); } } void CNodeBase::clear_ip4_async(void) { debug("clear ip4"); if ( m_ip4.size() || m_gw4.size() ) { m_tasks.push_back(bind(&CNodeBase::clear_ip4_internal, this)); } } void CNodeBase::conf_ip6_async(bool enabled, const string &ip6_buf) { assert(ip6_buf.size()==16 || ip6_buf.size()==0); debug("conf ip6"); if ( enabled != m_ip6_enabled || ip6_buf != m_ip6 ) { m_tasks.push_back(bind(&CNodeBase::conf_ip6_internal, this, enabled, ip6_buf)); } } void CNodeBase::clear_ip6_async(void) { debug("clear ip6"); if ( m_ip6_enabled || m_ip6.size() ) { m_tasks.push_back(bind(&CNodeBase::clear_ip6_internal, this)); } } // internal conf void CNodeBase::set_dst_mac_valid_internal(bool valid) { debug("conf dst valid internal"); m_dst_mac_valid = valid; } void CNodeBase::set_is_loopback_internal(bool is_loopback) { debug("conf loop internal"); m_is_loopback = is_loopback; } void CNodeBase::conf_dst_mac_internal(const string &dst_mac) { debug("conf dst internal"); m_dst_mac = dst_mac; } void CNodeBase::conf_vlan_internal(const vlan_list_t &vlans) { throw TrexException("VLAN is not supported with current stack"); } void CNodeBase::conf_ip4_internal(const string &ip4_buf, const string &gw4_buf) { throw TrexException("IPv4 is not supported with current stack"); } void CNodeBase::clear_ip4_internal(void) { m_ip4.clear(); m_gw4.clear(); } void CNodeBase::conf_ip6_internal(bool enabled, const string &ip6_buf) { throw TrexException("IPv6 is not supported with current stack"); } void CNodeBase::clear_ip6_internal(void) { m_ip6_enabled = false; m_ip6.clear(); } // getters bool CNodeBase::is_dst_mac_valid(void) { return m_dst_mac_valid; } bool CNodeBase::is_loopback(void) { return m_is_loopback; } bool CNodeBase::is_ip6_enabled(void) { return m_ip6_enabled; } const string &CNodeBase::get_src_mac(void) { return m_src_mac; } const string &CNodeBase::get_dst_mac(void) { return m_dst_mac; } const vlan_list_t &CNodeBase::get_vlan(void) { return m_vlan_tags; } const string &CNodeBase::get_src_ip4(void) { return m_ip4; } const string &CNodeBase::get_dst_ip4(void) { return m_gw4; } const string &CNodeBase::get_src_ip6(void) { return m_ip6; } /*************************************** * Helper funcs * ***************************************/ // print with -v 7 void debug(const string &msg) { if ( CGlobalInfo::m_options.preview.getVMode() > 6 ) { cout << msg << endl; } } void debug(const initializer_list &msg_list) { if ( CGlobalInfo::m_options.preview.getVMode() > 6 ) { for (auto &msg : msg_list) { printf("%s ", msg.c_str()); } printf("\n"); } } /*************************************** * CStackFactory * ***************************************/ CStackBase* CStackFactory::create(std::string &type_name, RXFeatureAPI *api, CRXCoreIgnoreStat *ignore_stats) { if ( type_name == "legacy" ) { return new CStackLegacy(api, ignore_stats); } if ( type_name == "linux_based" ) { return new CStackLinuxBased(api, ignore_stats); } string err; err = "ERROR: Unknown stack type \"" + type_name + "\"\n"; err += "Valid types are: legacy, linux_based"; throw TrexException(err); } //------------------------------------------------------------------------------------------------------- // Copyright (C) Microsoft Corporation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. //------------------------------------------------------------------------------------------------------- #include "RuntimeLanguagePch.h" #if defined(_M_ARM32_OR_ARM64) namespace Js { SIMDValue SIMDUint16x8Operation::OpUint16x8(uint16 values[]) { SIMDValue result; for (uint i = 0; i < 8; i++) { result.u16[i] = values[i]; } return result; } SIMDValue SIMDUint16x8Operation::OpMin(const SIMDValue& aValue, const SIMDValue& bValue) { SIMDValue result; for (uint idx = 0; idx < 8; ++idx) { result.u16[idx] = (aValue.u16[idx] < bValue.u16[idx]) ? aValue.u16[idx] : bValue.u16[idx]; } return result; } SIMDValue SIMDUint16x8Operation::OpMax(const SIMDValue& aValue, const SIMDValue& bValue) { SIMDValue result; for (uint idx = 0; idx < 8; ++idx) { result.u16[idx] = (aValue.u16[idx] > bValue.u16[idx]) ? aValue.u16[idx] : bValue.u16[idx]; } return result; } SIMDValue SIMDUint16x8Operation::OpLessThan(const SIMDValue& aValue, const SIMDValue& bValue) //arun::ToDo return bool types { SIMDValue result; for(uint idx = 0; idx < 8; ++idx) { result.u16[idx] = (aValue.u16[idx] < bValue.u16[idx]) ? 0xff : 0x0; } return result; } SIMDValue SIMDUint16x8Operation::OpLessThanOrEqual(const SIMDValue& aValue, const SIMDValue& bValue) //arun::ToDo return bool types { SIMDValue result; for (uint idx = 0; idx < 8; ++idx) { result.u16[idx] = (aValue.u16[idx] <= bValue.u16[idx]) ? 0xff : 0x0; } return result; } SIMDValue SIMDUint16x8Operation::OpGreaterThanOrEqual(const SIMDValue& aValue, const SIMDValue& bValue) { SIMDValue result; result = SIMDUint16x8Operation::OpLessThan(aValue, bValue); result = SIMDInt32x4Operation::OpNot(result); return result; } SIMDValue SIMDUint16x8Operation::OpGreaterThan(const SIMDValue& aValue, const SIMDValue& bValue) { SIMDValue result; result = SIMDUint16x8Operation::OpLessThanOrEqual(aValue, bValue); result = SIMDInt32x4Operation::OpNot(result); return result; } SIMDValue SIMDUint16x8Operation::OpShiftRightByScalar(const SIMDValue& value, int count) { SIMDValue result; if (count > 16) //Similar to polyfill, maximum shift will happen if the shift amounts and invalid { count = 16; } for (uint idx = 0; idx < 8; ++idx) { result.u16[idx] = (value.u16[idx] >> count); } return result; } SIMDValue SIMDUint16x8Operation::OpAddSaturate(const SIMDValue& aValue, const SIMDValue& bValue) { SIMDValue result; for (uint idx = 0; idx < 8; ++idx) { uint32 a = (uint32)aValue.u16[idx]; uint32 b = (uint32)bValue.u16[idx]; result.u16[idx] = ((a + b) > MAXUINT16) ? MAXUINT16 : (uint16)(a + b); } return result; } SIMDValue SIMDUint16x8Operation::OpSubSaturate(const SIMDValue& aValue, const SIMDValue& bValue) { SIMDValue result; for (uint idx = 0; idx < 8; ++idx) { int a = (int)aValue.u16[idx]; int b = (int)bValue.u16[idx]; result.u16[idx] = ((a - b) < 0) ? 0 : (uint16)(a - b); } return result; } } #endif /* * Copyright 2011 Intel Corporation. * * This program is licensed under the terms and conditions of the * Apache License, version 2.0. The full text of the Apache License is at * http://www.apache.org/licenses/LICENSE-2.0 */ #include "plugin.h" #include "meegolocale.h" #include "localelistmodel.h" //QML_DECLARE_TYPE(meego::Locale); //QML_DECLARE_TYPE(meego::LocaleListModel); void MeeGoUxLabsLocalePlugin::registerTypes(const char *uri) { qmlRegisterType(uri, 0, 1, "LocaleHelper"); qmlRegisterType(uri, 0, 1, "LocaleListModel"); } void MeeGoUxLabsLocalePlugin::initializeEngine(QDeclarativeEngine *engine, const char *uri) { Q_UNUSED(engine); Q_UNUSED(uri); } Q_EXPORT_PLUGIN(MeeGoUxLabsLocalePlugin); /// \copyright 2019-2021 /// Distributed under the Boost Software License, Version 1.0. /// See accompanying file LICENSE or copy at http://boost.org/LICENSE_1_0.txt #ifndef TETL_CMATH_FLOOR_HPP #define TETL_CMATH_FLOOR_HPP #include "etl/_3rd_party/gcem/gcem.hpp" #include "etl/_type_traits/enable_if.hpp" #include "etl/_type_traits/is_integral.hpp" namespace etl { /// \brief Computes the largest integer value not greater than arg. /// https://en.cppreference.com/w/cpp/numeric/math/floor [[nodiscard]] constexpr auto floor(float arg) noexcept -> float { return etl::detail::gcem::floor(arg); } /// \brief Computes the largest integer value not greater than arg. /// https://en.cppreference.com/w/cpp/numeric/math/floor [[nodiscard]] constexpr auto floorf(float arg) noexcept -> float { return etl::detail::gcem::floor(arg); } /// \brief Computes the largest integer value not greater than arg. /// https://en.cppreference.com/w/cpp/numeric/math/floor [[nodiscard]] constexpr auto floor(double arg) noexcept -> double { return etl::detail::gcem::floor(arg); } /// \brief Computes the largest integer value not greater than arg. /// https://en.cppreference.com/w/cpp/numeric/math/floor [[nodiscard]] constexpr auto floor(long double arg) noexcept -> long double { return etl::detail::gcem::floor(arg); } /// \brief Computes the largest integer value not greater than arg. /// https://en.cppreference.com/w/cpp/numeric/math/floor [[nodiscard]] constexpr auto floorl(long double arg) noexcept -> long double { return etl::detail::gcem::floor(arg); } /// \brief Computes the largest integer value not greater than arg. /// https://en.cppreference.com/w/cpp/numeric/math/floor template [[nodiscard]] constexpr auto floor(T arg) noexcept -> etl::enable_if_t, double> { return etl::detail::gcem::floor(static_cast(arg)); } } // namespace etl #endif // TETL_CMATH_FLOOR_HPP///////////////////////////RAW DATA ANALYSIS ////////////////////////// #include #include #include #include #include #include #include #include "json.hpp" using namespace std; using json = nlohmann::json; #include "data.hh" /// Selects which raw data analysis to perform void Data::raw() { //fractional_change("IR_England_age"); //fractional_change("ca_England_age"); //fractional_change("IH_England_age"); //fractional_change("D_England_wales_age"); emsg("done"); //fractional_change2("HD_England_age_data"); emsg("done"); //calculate_IR(); emsg("done"); //cases_age(); emsg("done"); //split_deaths_age_data(); emsg("done"); //deaths_age(); emsg("done"); //generate_admission_age(); emsg("done"); //generatehospdata(); emsg("done"); //generatedeathdata_england_wales(); emsg("generate death data"); //generatedeathdata_scotland(); emsg("done"); //death_age_distribution(); emsg("done"); //case_age_distribution(); emsg("done"); //generatedeathdata_england_wales(); emsg("done"); //plotrawdata(); emsg("done"); //IFR(); emsg("done"); //deaths_hospital_england(); emsg("done"); //generate_initpop(); emsg("done"); //generate_tvcovar(); emsg("done"); //generate_level_effect(); emsg("done"); //reducesize_geojson("areas2.geojson"); emsg("done"); } void Data::deaths_hospital_england() { Table tab = load_table("deaths_hospital_England_age.txt"); auto files = details.output_directory+"/HD_England_age_data.txt"; ofstream IGageout(files.c_str()); IGageout << "date\tday\t0-19\t20-39\t40-59\t60-79\t80+\ttotal\n"; for(auto col = 1u; col < tab.ncol; col++){ auto t = details.gettime(tab.heading[col],"Error") - details.start; IGageout << tab.heading[col] << "\t" << t; auto sum = 0u; for(auto row = 0u; row < tab.nrow; row++){ IGageout << "\t" << tab.ele[row][col]; sum += get_int( tab.ele[row][col],"erro"); } IGageout << "\t" << sum << "\n"; } } void Data::case_age_distribution() { //Table tab = load_table("ca_England_age.txt"); Table tab = load_table("IH_England_age.txt"); const unsigned int nage = 4; vector num(nage); for(auto a = 0u; a < nage; a++) num[a] = 0; for(auto row = 0u; row < tab.nrow; row++){ if(get_int(tab.ele[row][1],"error") < 217){ cout << tab.ele[row][0] << "\n"; for(auto a = 0u; a < nage; a++){ num[a] += get_int(tab.ele[row][2+a],"error"); } } } for(auto a = 0u; a < nage; a++) cout << a << " " << num[a] << " age dist\n"; } void Data::death_age_distribution() { Table tabHD = load_table("HD_England_wales_age.txt"); Table tabCD = load_table("CD_England_wales_age.txt"); const unsigned int nage = 4; vector num(nage); for(auto a = 0u; a < nage; a++) num[a] = 0; for(auto row = 0u; row < tabHD.nrow; row++){ if(get_int(tabHD.ele[row][1],"error") < 217){ cout << tabHD.ele[row][0] << "\n"; for(auto a = 0u; a < nage; a++){ num[a] += get_int(tabHD.ele[row][2+a],"error"); num[a] += get_int(tabCD.ele[row][2+a],"error"); } } } for(auto a = 0u; a < nage; a++) cout << a << " " << num[a] << " age dist\n"; } /// Finds the infection fatality rate for a given set of ages void Data::IFR() { const int nage = 19; // From https://www.imperial.ac.uk/media/imperial-college/medicine/mrc-gida/2020-10-29-COVID19-Report-34.pdf double IFR[nage] = {0.0,0.01,0.01,0.02,0.02,0.04,0.06,0.09,0.15,0.23,0.36,0.57,0.89,1.39,2.17,3.39,5.3,9.28,16.19}; // From https:www.ons.gov.uk/peoplepopulationandcommunity/populationandmigration/populationestimates/datasets/populationestimatesforukenglandandwalesscotlandandnorthernireland double pop[nage] = {3465179,3721990,3535065,3262613,3690265,4009669,4000908,3918562,3583853,3914884,4127941,3888131,3304688,2978882,2958612,2067471,1529682,933656,547789}; double sum, sum2; sum = 0.0; sum2 = 0.0; for(auto i = 0u; i < 4; i++){ sum += IFR[i]*pop[i]; sum2 += pop[i];} cout << sum/sum2 << " ifr\n"; sum = 0.0; sum2 = 0.0; for(auto i = 4u; i < 13; i++){ sum += IFR[i]*pop[i]; sum2 += pop[i];} cout << sum/sum2 << " ifr\n"; sum = 0.0; sum2 = 0.0; for(auto i = 13u; i < 17; i++){ sum += IFR[i]*pop[i]; sum2 += pop[i];} cout << sum/sum2 << " ifr\n"; sum = 0.0; sum2 = 0.0; for(auto i = 17u; i < 19; i++){ sum += IFR[i]*pop[i]; sum2 += pop[i];} cout << sum/sum2 << " ifr\n"; double inf[4]; inf[0] = 100.0*15/0.00985515; inf[1] = 100.0*5555/0.258672; inf[2] = 100.0*24541/2.69301; inf[3] = 100.0*21984/11.8351; double suminf = inf[0]+inf[1]+inf[2]+inf[3]; double sumdeath = 15+ 5555+24541+ 21984; //double fac = sumdeath/(0.0115*suminf); cout << "\n" << sumdeath/suminf << " IFR\n"; for(auto a = 0u; a < 4; a++){ cout << inf[a] << " inf\n"; } //0.00985515 ifr //0.258672 ifr //2.69301 ifr //11.8351 ifr //0 15 age dist //1 5555 age dist //2 24541 age dist //3 21984 age dist } // Estimates the weekly number of infected recovery (i.e. not counting those hospitalised void Data::calculate_IR() { Table cases = load_table("ca_England_age.txt"); Table admi = load_table("IH_England_age.txt"); auto files = details.output_directory+"/IR_England_age.txt"; ofstream IGageout(files.c_str()); auto rowst = 0u; while(rowst < cases.nrow && cases.ele[rowst][0] != admi.ele[0][0]) rowst++; cout << rowst << " " << cases.nrow << "rowst\n"; IGageout << "date\tday\t0-19\t20-64\t65-84\t85+\ttotal\n"; for(auto row = 0u; row < admi.nrow-6; row += 7){ IGageout << admi.ele[row][0] << "\t" << admi.ele[row][1]; for(auto col = 2u; col < admi.ncol; col++){ int sum = 0; for(auto day = 0u; day < 7; day++){ sum += get_int(cases.ele[rowst+row+day][col],"error") - get_int(admi.ele[row+day][col],"error"); } if(sum < 0) sum = 0; IGageout << "\t" << sum; } IGageout << "\n"; } } /// Calculates fractional change as a function of time void Data::fractional_change(string file) { Table tab = load_table(file+".txt"); auto files = details.output_directory+"/"+file+"_frac.txt"; ofstream IGageout(files.c_str()); IGageout << "date\tday\t0\t20\t65\t85\ttotal\n"; for(auto row = 0u; row < tab.nrow; row++){ double valst[4]; double sum = 0; for(auto col = 0; col < 4; col++){ valst[col] = sum; sum += get_int(tab.ele[row][col+2],"error"); } if(sum > 10){ IGageout << tab.ele[row][0] << "\t" << tab.ele[row][1]; for(auto col = 0; col < 4; col++) IGageout << "\t" << (valst[col]/sum); IGageout << "\t" << tab.ele[row][6]; IGageout << "\n"; } } } /// Calculates fractional change as a function of time void Data::fractional_change2(string file) { Table tab = load_table(file+".txt"); auto files = details.output_directory+"/"+file+"_frac.txt"; ofstream IGageout(files.c_str()); IGageout << "date\tday\t0\t20\t40\t60\t80\ttotal\n"; for(auto row = 0u; row < tab.nrow; row++){ double valst[5]; double sum = 0; for(auto col = 0; col < 5; col++){ valst[col] = sum; sum += get_int(tab.ele[row][col+2],"error"); } if(sum > 10){ IGageout << tab.ele[row][0] << "\t" << tab.ele[row][1]; for(auto col = 0; col < 5; col++) IGageout << "\t" << (valst[col]/sum); IGageout << "\t" << tab.ele[row][7]; IGageout << "\n"; } } } void Data::cases_age() { Table tab = load_table("cases_England_age.txt"); auto files = details.output_directory+"/ca_England_age.txt"; ofstream IGageout(files.c_str()); IGageout << "date\tday\t0-19\t20-64\t65-84\t85+\ttotal\n"; auto typecol = find_column(tab,"areaType"); auto datecol = find_column(tab,"date"); double sum; double sum0to19 = 0u, sum20to64 = 0u, sum65to84 = 0u, sum85 = 0u; for(auto row = 0u; row < tab.nrow; row++){ if(tab.ele[row][typecol] == "overview"){ auto t = details.gettime(tab.ele[row][datecol],"Error") - details.start; IGageout << tab.ele[row][datecol] << "\t" << t; auto sumtot = 0.0; sum = 0; for(auto col = 0u; col < tab.ncol; col++){ if(tab.heading[col] == "newCasesBySpecimenDate-0_4") sum += get_int(tab.ele[row][col],"error"); if(tab.heading[col] == "newCasesBySpecimenDate-5_9") sum += get_int(tab.ele[row][col],"error"); if(tab.heading[col] == "newCasesBySpecimenDate-10_14") sum += get_int(tab.ele[row][col],"error"); if(tab.heading[col] == "newCasesBySpecimenDate-15_19") sum += get_int(tab.ele[row][col],"error"); } IGageout << "\t" << sum; sum0to19 += sum; sumtot += sum; sum = 0; for(auto col = 0u; col < tab.ncol; col++){ if(tab.heading[col] == "newCasesBySpecimenDate-20_24") sum += get_int(tab.ele[row][col],"error"); if(tab.heading[col] == "newCasesBySpecimenDate-25_29") sum += get_int(tab.ele[row][col],"error"); if(tab.heading[col] == "newCasesBySpecimenDate-30_34") sum += get_int(tab.ele[row][col],"error"); if(tab.heading[col] == "newCasesBySpecimenDate-35_39") sum += get_int(tab.ele[row][col],"error"); if(tab.heading[col] == "newCasesBySpecimenDate-40_44") sum += get_int(tab.ele[row][col],"error"); if(tab.heading[col] == "newCasesBySpecimenDate-45_49") sum += get_int(tab.ele[row][col],"error"); if(tab.heading[col] == "newCasesBySpecimenDate-50_54") sum += get_int(tab.ele[row][col],"error"); if(tab.heading[col] == "newCasesBySpecimenDate-55_59") sum += get_int(tab.ele[row][col],"error"); if(tab.heading[col] == "newCasesBySpecimenDate-60_64") sum += get_int(tab.ele[row][col],"error"); } IGageout << "\t" << sum; sum20to64 += sum; sumtot += sum; sum = 0; for(auto col = 0u; col < tab.ncol; col++){ if(tab.heading[col] == "newCasesBySpecimenDate-65_69") sum += get_int(tab.ele[row][col],"error"); if(tab.heading[col] == "newCasesBySpecimenDate-70_74") sum += get_int(tab.ele[row][col],"error"); if(tab.heading[col] == "newCasesBySpecimenDate-75_79") sum += get_int(tab.ele[row][col],"error"); if(tab.heading[col] == "newCasesBySpecimenDate-80_84") sum += get_int(tab.ele[row][col],"error"); } IGageout << "\t" << sum; sum65to84 += sum; sumtot += sum; sum = 0; for(auto col = 0u; col < tab.ncol; col++){ if(tab.heading[col] == "newCasesBySpecimenDate-85_89") sum += get_int(tab.ele[row][col],"error"); if(tab.heading[col] == "newCasesBySpecimenDate-90+") sum += get_int(tab.ele[row][col],"error"); } IGageout << "\t" << sum; sum85 += sum; sumtot += sum; IGageout << "\t" << sumtot; IGageout << "\n"; } } double total = sum0to19 + sum20to64 + sum65to84 + sum85; auto fac= 1.0; cout << fac*sum0to19 / total << " " << fac*sum20to64 / total << " " << fac*sum65to84 / total << " " << fac*sum85 / total << "dist\n"; fac= 3000000; cout << fac*sum0to19 / total << " " << fac*sum20to64 / total << " " << fac*sum65to84 / total << " " << fac*sum85 / total << "dist\n"; } string Data::remove_comma(string st) { auto i = 0u; while(i < st.length()){ if(st.substr(i,1) ==",") st = st.substr(0,i)+st.substr(i+1,st.length()-(i+1)); else i++; } return st; } void Data::deaths_age() { Table tab = load_table("England_wales_deaths_age_occurance.txt"); //Table tab = load_table("England_wales_deaths_age.txt"); //auto files = details.output_directory+"/D_England_wales_age.txt"; auto files = details.output_directory+"/D_England_wales_age_occurance.txt"; ofstream IGageout(files.c_str()); IGageout << "date\tday\t0-19\t20-64\t65-84\t85+\ttotal\tcum total\n"; unsigned int sum, cum = 0; for(auto col = 1u; col < tab.ncol; col++){ IGageout << details.getdate((col-1)*7) << "\t" << (col-1)*7; sum = 0; for(auto row = 0u; row < 5; row++) sum += get_int(remove_comma(tab.ele[row][col]),"error"); IGageout << "\t" << sum; sum = 0; for(auto row = 5u; row < 14; row++) sum += get_int(remove_comma(tab.ele[row][col]),"error"); IGageout << "\t" << sum; sum = 0; for(auto row = 14u; row < 18; row++) sum += get_int(remove_comma(tab.ele[row][col]),"error"); IGageout << "\t" << sum; sum = 0; for(auto row = 18u; row < 20; row++) sum += get_int(remove_comma(tab.ele[row][col]),"error"); IGageout << "\t" << sum; auto sumtot = 0u; for(auto row = 0u; row < 20; row++) sumtot += get_int(remove_comma(tab.ele[row][col]),"error"); IGageout << "\t" << sumtot; cum += sumtot; IGageout << "\t" << cum; IGageout << "\n"; } cout << tab.nrow << "nrow\n"; } /// Splits up the deaths age data into community void Data::split_deaths_age_data() { Table CDtab = load_table("CD_region_england_wales.txt"); auto CDcol = find_column(CDtab,"all"); Table HDtab = load_table("HD_region_england_wales.txt"); auto HDcol = find_column(HDtab,"all"); //Table tab = load_table("D_England_wales_age.txt"); Table tab = load_table("D_England_wales_age_occurance.txt"); auto files = details.output_directory+"/agree.txt"; cout << tab.nrow << " " << CDtab.nrow << " " << HDtab.nrow << "y\n"; auto nrow = CDtab.nrow; /* ofstream IGageout(files.c_str()); for(auto row = 0u; row < nrow; row++){ IGageout << row << " " << get_int(tab.ele[row][6],"error") << " " << get_int(tab2.ele[row][6],"error") << " " << get_int(CDtab.ele[row][CDcol],"error") + get_int(HDtab.ele[row][HDcol],"error") << " " << get_int(CDtab.ele[row][CDcol],"error") << " " << get_int(HDtab.ele[row][HDcol],"error") << "\n"; } return; */ for(auto loop = 0u; loop < 2; loop++){ string st; if(loop == 0) st = "CD"; else st = "HD"; auto files = details.output_directory+"/"+st+"_England_wales_age.txt"; ofstream IGageout(files.c_str()); IGageout << "date\tday\t0-19\t20-64\t65-84\t85+\ttotal\tcum total\n"; auto cum = 0.0; for(auto row = 0u; row < nrow; row++){ auto numCD = get_int(CDtab.ele[row][CDcol],"error"); auto numHD = get_int(HDtab.ele[row][HDcol],"error"); double fac; if(loop == 0) fac = double(numCD)/(numCD+numHD+TINY); else fac = double(numHD)/(numCD+numHD+TINY); IGageout << tab.ele[row][0] << "\t" << tab.ele[row][1]; auto sum = 0.0; for(auto a = 0; a < 4; a++){ auto val = (unsigned int)(0.5+fac*get_int(tab.ele[row][2+a],"error")); //auto val = (double)(0.5+fac*get_int(tab.ele[row][2+a],"error")); IGageout << "\t" << val; sum += val; } cum += sum; IGageout << "\t" << sum << "\t" << cum << "\n"; } } } void Data::generate_admission_age() { const unsigned int nage = 5; const string agegroup[5] = {"0_to_5","6_to_17","18_to_64","65_to_84","85+"}; const unsigned int tmax = 350; vector date(tmax); vector > val; val.resize(tmax); for(auto t = 0u; t < tmax; t++){ val[t].resize(nage); for(auto a = 0u; a < nage; a++) val[t][a] = UNSET; } Table tab = load_table("hospital admissions_england_age2.txt"); auto datecol = find_column(tab,"date"); auto agecol = find_column(tab,"age"); auto valuecol = find_column(tab,"value"); //for(auto row = 0u; row < tab.nrow; row++){ //auto value = tab.ele[row][valuecol]; //auto t = details.gettime(tab.ele[row][datecol],"Error") - details.start; //cout << value << " " << t << " h\n"; //} for(auto row = 0u; row < tab.nrow; row++){ auto value = tab.ele[row][valuecol]; auto age = tab.ele[row][agecol]; if(value != ""){ auto t = details.gettime(tab.ele[row][datecol],"Error") - details.start; date[t] = tab.ele[row][datecol]; cout << t << " " << age << "age\n"; auto a = 0u; while(a < nage && agegroup[a] != age) a++; if(a == nage) emsg("Prob"); val[t][a] = get_int(value,"error"); } } auto files = details.output_directory+"/IH_England_age.txt"; ofstream IGageout(files.c_str()); IGageout << "date\tday\t0-19\t20-64\t65-84\t85+\ttotal\n"; for(auto t = 0u; t < tmax-1; t++){ if(val[t][0] != UNSET && val[t+1][0] != UNSET){ IGageout << date[t] << "\t" << t; //for(auto a = 0u; a < nage; a++) IGageout << "\t" << val[t+1][a]-val[t][a]; auto sum = 0u; for(auto a = 0u; a < 2; a++) sum += val[t+1][a]-val[t][a]; IGageout << "\t" << sum; for(auto a = 2u; a < nage; a++) IGageout << "\t" << val[t+1][a]-val[t][a]; auto sumtot=0u; for(auto a = 0u; a < nage; a++) sumtot += val[t+1][a]-val[t][a]; IGageout << "\t" < areaused(area.nrow); vector < vector > HDnum; vector < vector > CDnum; const int nweek = 56; HDnum.resize(area.nrow); CDnum.resize(area.nrow); for(auto c = 0u; c < area.nrow; c++){ areaused[c] = 0; HDnum[c].resize(nweek); CDnum[c].resize(nweek); for(auto w = 0u; w < nweek; w++){ HDnum[c][w] = 0; CDnum[c][w] = 0; } } vector < vector > locnum; locnum.resize(nloc); for(auto l = 0u; l < nloc; l++){ locnum[l].resize(nweek); for(auto w = 0u; w < nweek; w++){ locnum[l][w] = 0; } } for(auto row = 0u; row < tab.nrow; row++){ cout << row << " " << tab.nrow << " row\n"; if(tab.ele[row][7] == "covid-19" && tab.ele[row][12] == "Occurrences"){ auto st = tab.ele[row][5]; auto w = get_int(st.substr(5,st.length()-5),"error")-1; auto code = tab.ele[row][3]; auto num = get_int(tab.ele[row][0],"error"); auto c = 0u; while(c < area.nrow && code != area.ele[c][0]) c++; if(c == area.nrow){ cout << "cannot find\n"; } else{ if(tab.ele[row][10] == "Hospital"){ if(HDnum[c][w] != 0) cout << num << "pr\n"; HDnum[c][w] += num; } else CDnum[c][w] += num; } auto lo = 0u; while(lo < nloc && loc[lo] != tab.ele[row][10]) lo++; if(lo == nloc) emsg("error"); locnum[lo][w] += num; areaused[c] = 1; //cout << code << " " << w << " "<< num << " " << c<< "he \n"; //emsg("P"); } } auto fileb = details.output_directory+"/HD_region_england_wales.txt"; ofstream data(fileb.c_str()); data << "date\tday"; for(auto c = 0u; c < area.nrow; c++){ if(areaused[c] == 1) data << "\t" << area.ele[c][0]; } data << "\tall\tcum\n"; auto cum = 0u; for(auto w = 0u; w < nweek; w++){ data << details.getdate(w*7) << "\t" << w*7; auto sum = 0u; for(auto c = 0u; c < area.nrow; c++){ if(areaused[c] == 1){ data << "\t" << HDnum[c][w]; sum += HDnum[c][w]; } } cum += sum; data << "\t" << sum << "\t" << cum; data << "\n"; } auto fileb2 = details.output_directory+"/CD_region_england_wales.txt"; ofstream data2(fileb2.c_str()); data2 << "date\tday"; for(auto c = 0u; c < area.nrow; c++){ if(areaused[c] == 1) data2 << "\t" << area.ele[c][0]; } data2 << "\tall\tcum"; data2 << "\n"; cum = 0; for(auto w = 0u; w < nweek; w++){ data2 << details.getdate(w*7) << "\t" << w*7; auto sum = 0u; for(auto c = 0u; c < area.nrow; c++){ if(areaused[c] == 1){ data2 << "\t" << CDnum[c][w]; sum += CDnum[c][w]; } } cum += sum; data2 << "\t" << sum << "\t" << cum; data2 << "\n"; } auto filec = details.output_directory+"/D_locationofdeath_england_wales.txt"; ofstream data3(filec.c_str()); data3 << "date\tday"; for(auto l = 0u; l < nloc; l++){ data3 << "\t" << loc[l]; } data3 << "\tall\tcum\n"; cum = 0; for(auto w = 0u; w < nweek; w++){ data3 << details.getdate(w*7) << "\t" << w*7; auto sum = 0u; for(auto l = 0u; l < nloc; l++){ data3 << "\t" << locnum[l][w]; sum +=locnum[l][w]; } cum += sum; data3 << "\t" << sum << "\t" << cum; data3 << "\n"; } /* auto filec = details.output_directory+"/HD_tot_england_wales_plot.txt"; ofstream datac(filec.c_str()); for(auto w = 0u; w < nweek; w++){ auto sum = 0.0; for(auto c = 0u; c < area.nrow; c++){ if(areaused[c] == 1) sum += HDnum[c][w]; } datac << w*7 << " " << sum << "\n"; } auto filed = details.output_directory+"/CD_tot_england_wales_plot.txt"; ofstream datad(filed.c_str()); for(auto w = 0u; w < nweek; w++){ auto sum = 0.0; for(auto c = 0u; c < area.nrow; c++){ if(areaused[c] == 1) sum += CDnum[c][w]; } datad << w*7 << " " << sum << "\n"; } auto filee = details.output_directory+"/HD_tot_england_wales.txt"; ofstream datae(filee.c_str()); datae << "date\tall\n"; for(auto w = 0u; w < nweek; w++){ auto sum = 0.0; for(auto c = 0u; c < area.nrow; c++){ if(areaused[c] == 1) sum += HDnum[c][w]; } datae << details.getdate(w*7) << " " << sum << "\n"; } auto filef = details.output_directory+"/CD_tot_england_wales.txt"; ofstream dataf(filef.c_str()); dataf << "date\tall\n"; for(auto w = 0u; w < nweek; w++){ auto sum = 0.0; for(auto c = 0u; c < area.nrow; c++){ if(areaused[c] == 1) sum += CDnum[c][w]; } dataf << details.getdate(w*7) << " " << sum << "\n"; } */ } void Data::generatedeathdata_scotland() { Table area = load_table("areadata_Scotland_National.txt"); Table tab = load_table("deaths scotland_11-26.txt"); auto nweek = 36u; vector< vector > num; vector linedate; vector HDnum; vector IDnum; vector carehome(nweek), hospital(nweek), other(nweek), home(nweek); num.resize(nweek); linedate.resize(nweek); HDnum.resize(nweek); IDnum.resize(nweek); for(auto w = 0u; w < nweek; w++){ HDnum[w] = 0; IDnum[w] = 0; carehome[w] = 0; hospital[w] = 0; other[w] = 0; home[w] = 0; num[w].resize(area.nrow); for(auto r = 0u; r < area.nrow; r++) num[w][r] = 0; } auto tmin = 10000u, tmax = 0u; auto tt = 75u; auto sum = 0.0, sumI = 0.0, sumH = 0.0; for(auto row = 0u; row < tab.nrow; row++){ auto reg = tab.ele[row][0]; auto date = tab.ele[row][1]; auto n = stoi(tab.ele[row][4]); auto sex = tab.ele[row][5]; auto age = tab.ele[row][6]; auto cause = tab.ele[row][7]; auto loc = tab.ele[row][8]; if(loc != "All") cout << loc << " loc\n"; if(sex == "All" && age == "All" && cause == "COVID-19 related" && date.substr(0,4) == "w/c "){ date = date.substr(4,date.length()-4) ; //cout << date << " dat\n"; //cout << details.start+tt << " " << details.gettime(date,"Error") << " yy\n"; if(details.start+tt > details.gettime(date,"Error")) emsg("Problem"); auto t = details.gettime(date,"Error") - (details.start+tt); if(t < tmin) tmin = t; if(t > tmax) tmax = t; auto w = t/7; if(w > nweek) emsg("out"); auto r = 0u; while(r < area.nrow && area.ele[r][0] != reg) r++; if(1 == 0 && r < area.nrow){ if(loc == "All"){ linedate[w] = date; num[w][r] += n; sum += n; } } else{ if(reg == "S92000003"){ if(loc != "All"){ linedate[w] = date; cout << loc << " loc\n"; if(loc == "Hospital") hospital[w] += n; else{ if(loc == "Care Home") carehome[w] += n; else{ if(loc == "Home / Non-institution") home[w] += n; else{ if(loc == "Other institution") other[w] += n; else{ emsg("P"); } } } } if(loc == "Hospital"){ HDnum[w] += n; sumH += n;} else{ IDnum[w] += n; sumI += n;} } } } } } cout << tmin << " " << tmax <<" max\n"; //emsg("P"); cout << "Total in regions: " << sum << endl; cout << "Total from hospitals: " << sumH << endl; cout << "Total from community: " << sumI << endl; ofstream compare(details.output_directory+"/comp.txt"); compare << "Week\tHospital\tCare Home\tHome\tOther\n"; for(auto w = 0u; w < nweek; w++){ compare << w << "\t" << hospital[w] << "\t" << carehome[w] << "\t" << home[w] << "\t" << other[w] << "\n"; } string file = details.output_directory+"/D_reg_NRS.txt"; ofstream deathout(file.c_str()); deathout << "date"; for(auto r = 0u; r < area.nrow; r++) deathout << "\t" << area.ele[r][0]; deathout << endl; for(auto w = 0u; w < nweek; w++){ deathout << linedate[w]; for(auto r = 0u; r < area.nrow; r++){ //sum = 0; for(auto ww = 0u; ww < w; ww++) sum +=; deathout << "\t" << num[w][r]; } deathout << endl; } file = details.output_directory+"/deaths_NRS.txt"; ofstream allout(file.c_str()); allout << "date\tday\tall" << endl; for(auto w = 0u; w < nweek; w++){ allout << linedate[w] << "\t" << 75 + w*7 << " " << HDnum[w]+IDnum[w] << endl; } file = details.output_directory+"/HD_NRS.txt"; ofstream HDout(file.c_str()); HDout << "date\tall" << endl; for(auto w = 0u; w < nweek; w++){ HDout << linedate[w] << "\t" << HDnum[w] << endl; } file = details.output_directory+"/CD_NRS.txt"; ofstream IDout(file.c_str()); IDout << "date\tall" << endl; for(auto w = 0u; w < nweek; w++){ IDout << linedate[w] << "\t" << IDnum[w] << endl; } vector < vector > agedist; const int nagecat = 7; const string agecat[nagecat] = {"0 years","1-14 years","15-44 years","45-64 years","65-74 years","75-84 years","85 years and over"}; agedist.resize(nagecat); for(auto a = 0u; a < nagecat; a++){ agedist[a].resize(nweek); for(auto w = 0u; w < nweek; w++) agedist[a][w] = UNSET; } for(auto row = 0u; row < tab.nrow; row++){ auto reg = tab.ele[row][0]; auto date = tab.ele[row][1]; auto n = stoi(tab.ele[row][4]); auto sex = tab.ele[row][5]; auto age = tab.ele[row][6]; auto cause = tab.ele[row][7]; auto loc = tab.ele[row][8]; if(sex == "All" && age != "All" && loc == "All" && cause == "COVID-19 related" && date.substr(0,4) == "w/c "){ date = date.substr(4,date.length()-4) ; //cout << date << " dat\n"; if(details.start+tt > details.gettime(date,"Error")) emsg("Problem"); auto t = details.gettime(date,"Error") - (details.start+tt); if(t < tmin) tmin = t; if(t > tmax) tmax = t; auto w = t/7; if(w > nweek) emsg("out"); linedate[w] = date; auto a = 0u; for(a = 0; a < nagecat; a++) if(agecat[a] == age) break; if(a == nagecat){ cout << age << " age\n"; emsg("Problem2");} if(agedist[a][w] != UNSET) emsg("P"); agedist[a][w] = n; } } file = details.output_directory+"/D_age.txt"; ofstream Dageout(file.c_str()); Dageout << "date"; for(auto a = 0u; a < nagecat; a++) Dageout << "\t" << agecat[a]; Dageout<< endl; for(auto w = 0u; w < nweek; w++){ Dageout << linedate[w]; for(auto a = 0u; a < nagecat; a++) Dageout << "\t" << agedist[a][w]; Dageout << endl; } file = details.output_directory+"/D_age_plot.txt"; ofstream Dageplot(file.c_str()); for(auto w = 0u; w < nweek; w++){ Dageplot << tt + w*7; for(auto a = 0u; a < nagecat; a++) Dageplot << "\t" << agedist[a][w]; vector sumst(nagecat); auto sum = 0.0; for(auto a = 0u; a < nagecat; a++){ sumst[a] = sum; sum += agedist[a][w]; } for(auto a = 0u; a < nagecat; a++) Dageplot << "\t" << sumst[a]/sum; Dageplot << endl; } file = details.output_directory+"/age_dist.txt"; ofstream Dagedist(file.c_str()); for(auto a = 0u; a < nagecat; a++){ auto sum = 0.0; for(auto w = 0u; w < nweek; w++) sum += agedist[a][w]; Dagedist << agecat[a] << "\t" << sum << "\n"; } file = details.output_directory+"/age_dist_short.txt"; ofstream Dagedistshort(file.c_str()); for(auto a = 0u; a < nagecat; a++){ auto sum = 0.0; for(auto w = 0u; w < 3; w++) sum += agedist[a][w]; Dagedistshort << agecat[a] << "\t" << sum << "\n"; } for(auto a = 0u; a < nagecat; a++){ auto sum = 0.0; for(auto w = 0u; w < 3; w++) sum += agedist[a][w]; Dagedistshort << agecat[a] << "\t" << sum << "\n"; } for(auto w = 0u; w < nweek; w++){ cout << w << " " << linedate[w] << " dat\n"; } for(auto a = 0u; a < nagecat; a++){ auto sum = 0.0; for(auto w = 0u; w < 20; w++) sum += agedist[a][w]; cout << agecat[a] << "\t" << sum << "\n"; } } /// Converts the matrix sent by stephen void Data::convert_Mdata() { ifstream regin(data_directory+"/contact matrix regional names.txt"); ofstream regdat(data_directory+"/regiondata.txt"); ofstream areadat(data_directory+"/areadata.txt"); regdat << "name\tcode" << endl; areadat << "area\teasting\tnorthing\tregion\tdensity\tage0-14\tage15-44\tage45-64\t65+\tMale\tFemale" << endl; do{ string line, code, name; getline(regin,line); if(line.length() > 2){ code = line.substr(1,9); int j = line.length()-10; while(line.substr(j,1) != "\"") j++; name = line.substr(13,j); strip(name); regdat << name << "\t" << code << endl; areadat << code << "\t" << ran() << "\t" << ran() << "\t" << code << "\t1\t50000\t100000\t100000\t100000\t50\t50" << endl; } }while(!regin.eof()); const unsigned int si=171; double M[si][si]; ifstream ip(data_directory+"/contactmatrix.txt"); unsigned int i, j; for(i = 0; i < si; i++){ for(j = 0; j < si; j++){ ip >> M[i][j]; } } ofstream op(data_directory+"/Mdata.txt"); op << "'region1' 'region2' 'contact'" << endl; for(i = 0; i < si; i++){ for(j = i; j < si; j++){ op << i << "\t" << j << "\t" << M[i][j] << endl; } } /* Table tabarea = load_table("areadata.txt"); Table tabcheck = load_table("datazones.txt"); vector conv(tabarea.nrow); for(auto r = 0u; r < tabarea.nrow; r++){ auto st = tabcheck.ele[r][0]; auto code = st.substr(st.size()-9,9); unsigned int a; for(a = 0; a < tabarea.nrow; a++) if(tabarea.ele[a][1] == code) break; if(a == tabarea.nrow) cout << "cannot find\n"; conv[r] = a; cout << tabarea.ele[a][1] << " " << tabcheck.ele[a][0] << " g:" << code << " samz\n"; } cout << tabarea.nrow << " " << tabcheck.nrow << " jj\n"; unsigned int i, j; double val; ifstream inp(data_directory+"/M.txt"); ofstream op(data_directory+"/Mdata.txt"); op << "DZ1 DS2 contact" << endl; op << setprecision(5); do{ inp >> i >> j >> val; cout << i << " " << j << " " << val << " k\n"; auto a1 = conv[i-1]; auto a2 = conv[j-1]; if(a1 > a2){ auto a = a1; a1 =a2; a2= a;} op << a1 << "\t" << a2 << "\t" << val << endl; }while(!inp.eof()); */ } /// Plots raw data void Data::plotrawdata() { Table tab = load_table("apple_mobility.txt"); auto row_walk = 0u; while(row_walk < tab.nrow && !(tab.ele[row_walk][1] == "Scotland" && tab.ele[row_walk][2] == "walking")) row_walk++; auto row_drive = 0u; while(row_drive < tab.nrow && !(tab.ele[row_drive][1] == "Scotland" && tab.ele[row_drive][2] == "driving")) row_drive++; auto row_transit = 0u; while(row_transit < tab.nrow && !(tab.ele[row_transit][1] == "Scotland" && tab.ele[row_transit][2] == "transit")) row_transit++; cout << row_walk << " " << row_drive << " " << row_transit << "row\n"; vector val_walk, val_driving, val_transit; for(auto col = 9u; col < tab.ncol-4; col++){ auto sum = 0.0; for(unsigned int c = col-3; c <= col+3; c++) sum += get_double(tab.ele[row_walk][c],"error"); val_walk.push_back(sum); sum = 0.0; for(unsigned int c = col-3; c <= col+3; c++) sum += get_double(tab.ele[row_drive][c],"error"); val_driving.push_back(sum); sum = 0.0; for(unsigned int c = col-3; c <= col+3; c++) sum += get_double(tab.ele[row_transit][c],"error"); val_transit.push_back(sum); } ofstream data(details.output_directory+"/apple_mobility_plot.txt"); for(auto i = 0u; i < val_walk.size(); i++){ data << i + 15 << " " << 100*val_walk[i]/val_walk[0] << " " << 100*val_driving[i]/val_driving[0] << " " << 100*val_transit[i]/val_transit[0] << "\n"; } /* string fileraw = details.output_directory+"/rawdeaths.txt"; ofstream raw(fileraw.c_str()); for(auto &tdata : transdata){ // Loads transition data for inference cout << tdata.fromstr << " " << tdata.tostr << " fro to\n"; auto sum = 0.0; for(auto col = 0u; col < tdata.num[0].size(); col++){ //raw << tdata.start+col*tdata.units << " " << sum << "\n"; auto sum2 = 0.0; for(auto row = 0u; row < tdata.num.size(); row++){ sum += tdata.num[row][col]; sum2 += tdata.num[row][col]; } raw << tdata.start+(col+0.5)*tdata.units << " " << sum2 << "\n"; } } Table tab = load_table("areadata.txt"); auto col = find_column(tab,"density"); string file = details.output_directory+"/death_vs_density.txt"; ofstream outp(file.c_str()); for(auto &tdata : transdata){ // Loads transition data for inference string file2 = tdata.file; Table tab2 = load_table(file2); for(auto r = 0u; r < nregion; r++){ auto col2 = find_column(tab2,region[r].code); auto sum = 0.0; for(auto row = 0u; row < tab2.nrow; row++){ sum += get_double(tab2.ele[row][col2].c_str()); } outp << get_double(tab.ele[r][col].c_str()) << " " << sum << "\n"; } } */ } /// Generates a initpop file void Data::generate_initpop() { ofstream fout(details.output_directory+"/initpop.csv"); fout << "area"; for(auto d = 0u; d < ndemocat; d++){ if(democat[d].value.size() > 1){ fout << "," << democat[d].name; } } fout << ",compartment,population" << endl; for(auto a=0u; a < narea; a++){ for(auto dp = 0u; dp < ndemocatpos; dp++){ fout << area[a].code; for(auto d = 0u; d < ndemocat; d++){ if(democat[d].value.size() > 1){ fout << "," << democat[d].value[democatpos[dp][d]]; } } fout << ",S," << area[a].pop_init[0][dp] << endl; } } } // Simulates files for time-varying covariates void Data::generate_tvcovar() { ofstream fout(details.output_directory+"/tvcovar.csv"); fout << "Date,Temperature" << endl; auto mu = 20.0, sd = 1.0, lam = 0.1; auto T = mu; for(auto t = 0u; t < details.period; t++){ T += -lam*(T-mu) + normal_sample(0,sd); fout << details.getdate(t) << "," << T << endl; } ofstream fout2(details.output_directory+"/areatvcovar.csv"); fout2 << "Date"; for(auto c = 0u; c < narea; c++){ fout2 << "," << area[c].code; } fout2 << endl; vector Tvec(narea); for(auto c = 0u; c < narea; c++) Tvec[c] = mu + normal_sample(0,3*sd); for(auto t = 0u; t < details.period; t++){ fout2 << details.getdate(t); for(auto c = 0u; c < narea; c++){ Tvec[c] += -lam*(Tvec[c]-mu) + normal_sample(0,sd); fout2 << "," << Tvec[c]; } fout2 << endl; } } /// Simulates a file that can be used to test algorithm void Data::generate_level_effect() { auto file = details.output_directory+"/level.csv"; string levels = "level1,level2"; auto levs = split(levels,','); ofstream lout(file.c_str()); lout << "Date"; for(auto c = 0u; c < narea; c++) lout << "," << area[c].code; lout << endl; auto T = details.end- details.start; vector< vector > map; map.resize(T); for(auto t = 0u; t < T; t++) map[t].resize(narea); for(auto c = 0u; c < narea; c++){ auto t = 0u; do{ auto val = (unsigned int)(levs.size()*ran()); auto tnext = t + (unsigned int)(30*ran()); if(tnext > T) tnext = T; while(t < tnext){ map[t][c] = levs[val]; t++;} }while(t < T); } for(auto t = 0u; t < T; t++){ lout << details.getdate(t); for(auto c = 0u; c < narea; c++) lout << "," << map[t][c]; lout << endl; } } /// Loads up a GEOJSON file and reduces its size (so it can be put on the GitHub repository) void Data::reducesize_geojson(const string file) { auto filefull = data_directory+"/"+file; ifstream boundfile(filefull); if(!boundfile) emsg("Cannot open the file '"+file+"'."); string s; do{ string st; getline( boundfile,st); s += st; if( boundfile.eof()) break; }while(true); json jso = json::parse(s); auto &h = jso["features"]; vector rem(h.size()); auto loop= 0u; for(auto &it : h.items()){ // Deletes unused areas json val = it.value(); //cout << val << " val\n"; auto h2 = val["type"]; if(h2 == "Feature"){ auto c = UNSET; auto h3 = val["properties"]; for(auto &it3 : h3.items()){ // Checks if one of the properties contains the name of the area if(it3.value().is_string()){ string name = it3.value(); strip(name); c = 0; while(c < narea && name != area[c].code) c++; if(c < narea) break; } } if(c == UNSET || c == narea) rem[loop] = 1; } loop++; } for(int loop = h.size()-1; loop >= 0; loop--){ if(rem[loop] == 1) h.erase(h.begin()+loop); } const double acc = 1000; for(auto &it : h.items()){ // Removes significant figures json &val = it.value(); auto h2 = val["type"]; if(h2 == "Feature"){ auto &h3 = val["geometry"]; auto h4 = h3["type"]; if(h4 == "Polygon"){ auto &h5 = h3["coordinates"]; for(auto &it2 : h5.items()){ json &val2 = it2.value(); for(auto &it3 : val2.items()){ json &val3 = it3.value(); double sx = val3[0]; val3[0] = int(sx*acc)/acc; double sy = val3[1]; val3[1] = int(sy*acc)/acc; } } } if(h4 == "MultiPolygon"){ auto &h5 = h3["coordinates"]; for(auto &it : h5.items()){ json &val = it.value(); for(auto &it2 : val.items()){ json &val2 = it2.value(); for(auto &it3 : val2.items()){ json &val3 = it3.value(); double sx = val3[0]; val3[0] = int(sx*acc)/acc; double sy = val3[1]; val3[1] = int(sy*acc)/acc; } } } } } } double dif = 0.004; auto nump = 0u; for(auto &it : h.items()){ // Removes fine details json &val = it.value(); auto &h2 = val["type"]; if(h2 == "Feature"){ auto &h3 = val["geometry"]; auto &h4 = h3["type"]; double xst=0, yst=0; if(h4 == "Polygon"){ auto &h5 = h3["coordinates"]; for(auto &it2 : h5.items()){ json &val2 = it2.value(); auto loop = 0u; vector rem(val2.size()); for(auto i = 0u; i = 0; loop--){ if(rem[loop] == 1) val2.erase(val2.begin()+loop); } nump += val2.size(); } } if(h4 == "MultiPolygon"){ auto &h5 = h3["coordinates"]; for(auto &it : h5.items()){ json &val = it.value(); for(auto &it2 : val.items()){ json &val2 = it2.value(); auto loop = 0u; vector rem(val2.size()); for(auto i = 0u; i = 0; loop--){ if(rem[loop] == 1) val2.erase(val2.begin()+loop); } nump += val2.size(); } } } } } cout << nump <<" nump\n"; auto fi = details.output_directory+"/Scotland_areas.geojson"; ofstream fiout(fi); fiout << jso.dump() << endl; //cout << jso.dump() << "dum\n"; } alexeyche/vespa // Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "collectiondatatype.h" namespace document { CollectionDataType::CollectionDataType(vespalib::stringref name, const DataType& nestedType) noexcept : DataType(name), _nestedType(&nestedType) { } CollectionDataType::CollectionDataType(vespalib::stringref name, const DataType& nestedType, int32_t id) noexcept : DataType(name, id), _nestedType(&nestedType) { } CollectionDataType::~CollectionDataType() = default; bool CollectionDataType::equals(const DataType& other) const noexcept { if (!DataType::equals(other)) return false; const CollectionDataType * o = other.cast_collection(); return o && _nestedType->equals(*o->_nestedType); } } // document /* this file has been autogenerated by vtkNodeJsWrap */ /* editing this might proof futile */ #define VTK_WRAPPING_CXX #define VTK_STREAMS_FWD_ONLY #include #include "vtkImageProcessingPassWrap.h" #include "vtkSobelGradientMagnitudePassWrap.h" #include "vtkObjectWrap.h" #include "vtkWindowWrap.h" #include "../../plus/plus.h" using namespace v8; extern Nan::Persistent vtkNodeJsNoWrap; Nan::Persistent VtkSobelGradientMagnitudePassWrap::ptpl; VtkSobelGradientMagnitudePassWrap::VtkSobelGradientMagnitudePassWrap() { } VtkSobelGradientMagnitudePassWrap::VtkSobelGradientMagnitudePassWrap(vtkSmartPointer _native) { native = _native; } VtkSobelGradientMagnitudePassWrap::~VtkSobelGradientMagnitudePassWrap() { } void VtkSobelGradientMagnitudePassWrap::Init(v8::Local exports) { Nan::SetAccessor(exports, Nan::New("vtkSobelGradientMagnitudePass").ToLocalChecked(), ConstructorGetter); Nan::SetAccessor(exports, Nan::New("SobelGradientMagnitudePass").ToLocalChecked(), ConstructorGetter); } void VtkSobelGradientMagnitudePassWrap::ConstructorGetter( v8::Local property, const Nan::PropertyCallbackInfo& info) { InitPtpl(); info.GetReturnValue().Set(Nan::New(ptpl)->GetFunction()); } void VtkSobelGradientMagnitudePassWrap::InitPtpl() { if (!ptpl.IsEmpty()) return; v8::Local tpl = Nan::New(New); VtkImageProcessingPassWrap::InitPtpl( ); tpl->Inherit(Nan::New(VtkImageProcessingPassWrap::ptpl)); tpl->SetClassName(Nan::New("VtkSobelGradientMagnitudePassWrap").ToLocalChecked()); tpl->InstanceTemplate()->SetInternalFieldCount(1); Nan::SetPrototypeMethod(tpl, "GetClassName", GetClassName); Nan::SetPrototypeMethod(tpl, "getClassName", GetClassName); Nan::SetPrototypeMethod(tpl, "IsA", IsA); Nan::SetPrototypeMethod(tpl, "isA", IsA); Nan::SetPrototypeMethod(tpl, "NewInstance", NewInstance); Nan::SetPrototypeMethod(tpl, "newInstance", NewInstance); Nan::SetPrototypeMethod(tpl, "ReleaseGraphicsResources", ReleaseGraphicsResources); Nan::SetPrototypeMethod(tpl, "releaseGraphicsResources", ReleaseGraphicsResources); Nan::SetPrototypeMethod(tpl, "SafeDownCast", SafeDownCast); Nan::SetPrototypeMethod(tpl, "safeDownCast", SafeDownCast); #ifdef VTK_NODE_PLUS_VTKSOBELGRADIENTMAGNITUDEPASSWRAP_INITPTPL VTK_NODE_PLUS_VTKSOBELGRADIENTMAGNITUDEPASSWRAP_INITPTPL #endif ptpl.Reset( tpl ); } void VtkSobelGradientMagnitudePassWrap::New(const Nan::FunctionCallbackInfo& info) { if(!info.IsConstructCall()) { Nan::ThrowError("Constructor not called in a construct call."); return; } if(info.Length() == 0) { vtkSmartPointer native = vtkSmartPointer::New(); VtkSobelGradientMagnitudePassWrap* obj = new VtkSobelGradientMagnitudePassWrap(native); obj->Wrap(info.This()); } else { if(info[0]->ToObject() != vtkNodeJsNoWrap ) { Nan::ThrowError("Parameter Error"); return; } } info.GetReturnValue().Set(info.This()); } void VtkSobelGradientMagnitudePassWrap::GetClassName(const Nan::FunctionCallbackInfo& info) { VtkSobelGradientMagnitudePassWrap *wrapper = ObjectWrap::Unwrap(info.Holder()); vtkSobelGradientMagnitudePass *native = (vtkSobelGradientMagnitudePass *)wrapper->native.GetPointer(); char const * r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetClassName(); info.GetReturnValue().Set(Nan::New(r).ToLocalChecked()); } void VtkSobelGradientMagnitudePassWrap::IsA(const Nan::FunctionCallbackInfo& info) { VtkSobelGradientMagnitudePassWrap *wrapper = ObjectWrap::Unwrap(info.Holder()); vtkSobelGradientMagnitudePass *native = (vtkSobelGradientMagnitudePass *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsString()) { Nan::Utf8String a0(info[0]); int r; if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } r = native->IsA( *a0 ); info.GetReturnValue().Set(Nan::New(r)); return; } Nan::ThrowError("Parameter mismatch"); } void VtkSobelGradientMagnitudePassWrap::NewInstance(const Nan::FunctionCallbackInfo& info) { VtkSobelGradientMagnitudePassWrap *wrapper = ObjectWrap::Unwrap(info.Holder()); vtkSobelGradientMagnitudePass *native = (vtkSobelGradientMagnitudePass *)wrapper->native.GetPointer(); vtkSobelGradientMagnitudePass * r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->NewInstance(); VtkSobelGradientMagnitudePassWrap::InitPtpl(); v8::Local argv[1] = { Nan::New(vtkNodeJsNoWrap) }; v8::Local cons = Nan::New(VtkSobelGradientMagnitudePassWrap::ptpl)->GetFunction(); v8::Local wo = cons->NewInstance(1, argv); VtkSobelGradientMagnitudePassWrap *w = new VtkSobelGradientMagnitudePassWrap(); w->native = r; w->Wrap(wo); info.GetReturnValue().Set(wo); } void VtkSobelGradientMagnitudePassWrap::ReleaseGraphicsResources(const Nan::FunctionCallbackInfo& info) { VtkSobelGradientMagnitudePassWrap *wrapper = ObjectWrap::Unwrap(info.Holder()); vtkSobelGradientMagnitudePass *native = (vtkSobelGradientMagnitudePass *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkWindowWrap::ptpl))->HasInstance(info[0])) { VtkWindowWrap *a0 = ObjectWrap::Unwrap(info[0]->ToObject()); if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->ReleaseGraphicsResources( (vtkWindow *) a0->native.GetPointer() ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkSobelGradientMagnitudePassWrap::SafeDownCast(const Nan::FunctionCallbackInfo& info) { VtkSobelGradientMagnitudePassWrap *wrapper = ObjectWrap::Unwrap(info.Holder()); vtkSobelGradientMagnitudePass *native = (vtkSobelGradientMagnitudePass *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkObjectWrap::ptpl))->HasInstance(info[0])) { VtkObjectWrap *a0 = ObjectWrap::Unwrap(info[0]->ToObject()); vtkSobelGradientMagnitudePass * r; if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } r = native->SafeDownCast( (vtkObject *) a0->native.GetPointer() ); VtkSobelGradientMagnitudePassWrap::InitPtpl(); v8::Local argv[1] = { Nan::New(vtkNodeJsNoWrap) }; v8::Local cons = Nan::New(VtkSobelGradientMagnitudePassWrap::ptpl)->GetFunction(); v8::Local wo = cons->NewInstance(1, argv); VtkSobelGradientMagnitudePassWrap *w = new VtkSobelGradientMagnitudePassWrap(); w->native = r; w->Wrap(wo); info.GetReturnValue().Set(wo); return; } Nan::ThrowError("Parameter mismatch"); } #include namespace SerialPortUtils { /** * @brief Convert SerialPortInfo List to Friendly Name list. * * @param serialPorts SerialPortInfo List * @return Return the Friendly Name list. */ std::vector SerialPortInfo::toFriendlyNameList(std::vector serialPorts) { std::vector result; for (int i = 0; i < serialPorts.size(); i++) { result.push_back(serialPorts[i].friendlyName); } return result; } /** * @brief Convert SerialPortInfo List to Port list. * * @param serialPorts SerialPortInfo List * @return Return the Port list. */ std::vector SerialPortInfo::toPortList(std::vector serialPorts) { std::vector result; for (int i = 0; i < serialPorts.size(); i++) { result.push_back(serialPorts[i].port); } return result; } }/* * snmptrapsource.{cc,hh} -- element generates SNMP traps * * * Copyright (c) 2001 Mazu Networks, 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 "snmptrapsource.hh" #include "snmpbasics.hh" #include "snmpber.hh" #include "snmpvarinfo.hh" #include #include #include #include #include // NOTE: Cannot send packets directly from a handler because of SMP concerns. // So we put the packets onto an internal queue, then emit them through // run_task(). SNMPTrapSource::SNMPTrapSource() : _task(this) { _head = _tail = 0; _capacity = QSIZE; } SNMPTrapSource::~SNMPTrapSource() { } void * SNMPTrapSource::cast(const char *n) { if (strcmp(n, "Storage") == 0) return (Storage *)this; else if (strcmp(n, "SNMPTrapSource") == 0) return (Element *)this; else return 0; } int SNMPTrapSource::add_trap(const String &str, ErrorHandler *errh) { Vector words; String name; cp_spacevec(str, words); if (words.size() < 1 || !cp_word(words[0], &name)) return errh->error("should be 'NAME [SPECIFIC] [VARIABLES...]'"); int first_var = 1; int trap_type; if (name == "coldStart") trap_type = 0; else if (name == "warmStart") trap_type = -1; else if (name == "linkDown") trap_type = -2; else if (name == "linkUp") trap_type = -3; else if (name == "authenticationFailure") trap_type = -4; else if (name == "egpNeighborLoss") trap_type = -5; else { if (words.size() < 2 || !cp_integer(words[1], &trap_type)) trap_type = -6; else if (trap_type < 0) return errh->error("specific trap code must be >= 0"); else { if (trap_type == 0) trap_type = -6; first_var = 2; } } int snmp_var; _names.push_back(name); _offsets.push_back(_snmp_vars.size()); _trap_types.push_back(trap_type); ArgContext args(this, errh); for (int j = first_var; j < words.size(); j++) if (!SNMPVariableArg::parse(words[j], snmp_var, args)) errh->error("%<%s%> is not an SNMP variable", words[j].c_str()); else _snmp_vars.push_back(snmp_var); return 0; } int SNMPTrapSource::configure(Vector &conf, ErrorHandler *errh) { Vector traps; _src = _dst = IPAddress(); _sport = 0; _dport = 162; _community = "public"; _udp_encap = true; _ip_ttl = 255; _active = true; if (Args(conf, this, errh) .read("UDP", _udp_encap) .read("TTL", _ip_ttl) .read("SRC", _src) .read("SPORT", IPPortArg(IP_PROTO_UDP), _sport) .read("DST", _dst) .read("DPORT", IPPortArg(IP_PROTO_UDP), _dport) .read("COMMUNITY", _community) .read_m("ENTERPRISE", SNMPOidArg(), _enterprise) .read_all_with("TRAP", AnyArg(), traps) .read("ACTIVE", _active) .complete() < 0) return -1; if (_udp_encap && (!_src || !_dst)) return errh->error("must specify source and destination addresses"); if (_udp_encap && (!_sport || !_dport)) return errh->error("must specify source and destination ports"); if (_enterprise.size() == 0) return errh->error("must specify enterprise SNMP OID"); if (traps.size() == 0) errh->warning("no TRAP specifications"); _agent = _src; int before = errh->nerrors(); for (int i = 0; i < traps.size(); i++) { PrefixErrorHandler cerrh(errh, "TRAP " + String(i+1) + ": "); add_trap(traps[i], &cerrh); } _offsets.push_back(_snmp_vars.size()); return (errh->nerrors() == before ? 0 : -1); } int SNMPTrapSource::initialize(ErrorHandler *) { _task.initialize(this, false); _jiffies0 = snmp_time_ticks_since(0); _id = click_random(); return 0; } void SNMPTrapSource::cleanup(CleanupStage) { for (unsigned i = _head; i != _tail; i = next_i(i)) _queue[i]->kill(); } int SNMPTrapSource::generate_trap(int trap) { if (!_active) return 0; SNMPBEREncoder ber; ber.push_long_sequence(); ber.encode_integer(SNMP_VERSION_1); ber.encode_octet_string(_community); ber.push_long_sequence(SNMP_TAG_V1_TRAP); ber.encode_snmp_oid(_enterprise); ber.encode_ip_address(_agent); if (_trap_types[trap] <= 0) { ber.encode_integer(-_trap_types[trap]); ber.encode_integer(0); } else { ber.encode_integer(6 /* enterpriseSpecific */); ber.encode_integer(_trap_types[trap]); } ber.encode_time_ticks(snmp_time_ticks_since(_jiffies0)); ber.push_long_sequence(); for (int i = _offsets[trap]; i < _offsets[trap+1]; i++) SNMPVariableInfo::encode_binding(_snmp_vars[i], ber, this); ber.pop_sequence(); ber.pop_sequence(); ber.pop_sequence(); // check for out-of-memory condition if (ber.memory_error()) { _drops++; return -ENOMEM; } WritablePacket *p; if (_udp_encap) p = Packet::make(ber.length() + sizeof(click_ip) + sizeof(click_udp)); else p = Packet::make(ber.length()); if (!p) { _drops++; return -ENOMEM; } if (_udp_encap) { click_ip *iph = (click_ip *)p->data(); iph->ip_v = 4; iph->ip_hl = sizeof(click_ip) >> 2; iph->ip_len = htons(p->length()); iph->ip_id = htons(_id.fetch_and_add(1)); iph->ip_p = IP_PROTO_UDP; iph->ip_src = _src; iph->ip_dst = _dst; iph->ip_tos = 0; iph->ip_off = 0; iph->ip_ttl = _ip_ttl; iph->ip_sum = 0; #if HAVE_FAST_CHECKSUM iph->ip_sum = ip_fast_csum((unsigned char *)iph, sizeof(click_ip) >> 2); #else iph->ip_sum = click_in_cksum((unsigned char *)iph, sizeof(click_ip)); #endif p->set_dst_ip_anno(_dst); p->set_ip_header(iph, sizeof(click_ip)); click_udp *udph = (click_udp *)(p->data() + sizeof(click_ip)); int ulen = ber.length() + sizeof(click_udp); udph->uh_sport = htons(_sport); udph->uh_dport = htons(_dport); udph->uh_ulen = htons(ulen); udph->uh_sum = 0; memcpy(udph + 1, ber.data(), ber.length()); unsigned csum = click_in_cksum((unsigned char *)udph, ulen); udph->uh_sum = click_in_cksum_pseudohdr(csum, iph, ulen); } else memcpy(p->data(), ber.data(), ber.length()); // enqueue packet on Queue; drop packets at head unsigned next = next_i(_tail); if (next == _head) { _drops++; p->kill(); } else { _queue[_tail] = p; _tail = next; _task.reschedule(); } return 0; } bool SNMPTrapSource::run_task(Task *) { // see NOTE above while (_head != _tail) { int next = next_i(_head); output(0).push(_queue[_head]); _head = next; } return true; } static int trap_write_handler(const String &, Element *e, void *thunk, ErrorHandler *errh) { SNMPTrapSource *ts = (SNMPTrapSource *)e; intptr_t which = reinterpret_cast(thunk); int result = ts->generate_trap(which); if (result == -ENOMEM) errh->error("out of memory"); else if (result < 0) errh->error("error %d while generating trap", -result); return result; } String SNMPTrapSource::read_handler(Element *e, void *thunk) { SNMPTrapSource *ts = (SNMPTrapSource *)e; switch (reinterpret_cast(thunk)) { case H_drops: return String(ts->_drops.value()); case H_enterprise: return SNMPOidArg::unparse(ts->_enterprise); case H_src: return ts->_src.unparse(); case H_dst: return ts->_dst.unparse(); case H_sport: return String(ts->_sport); case H_dport: return String(ts->_dport); case H_active: return cp_unparse_bool(ts->_active); case H_traps: { StringAccum sa; for (int i = 0; i < ts->_names.size(); i++) sa << ts->_names[i] << '\n'; return sa.take_string(); } default: return ""; } } int SNMPTrapSource::write_handler(const String &str_in, Element *e, void *thunk, ErrorHandler *errh) { SNMPTrapSource *ts = (SNMPTrapSource *)e; String str = cp_uncomment(str_in); intptr_t which = reinterpret_cast(thunk); switch (which) { case H_src: case H_dst: { IPAddress a; if (!cp_ip_address(str, &a, e)) return errh->error("expected IP address"); (which == H_src ? ts->_src = a : ts->_dst = a); return 0; } case H_sport: case H_dport: { int x; if (!cp_integer(str, &x) || x < 0 || x > 0xFFFF) return errh->error("expected port number"); (which == H_sport ? ts->_sport = x : ts->_dport = x); return 0; } case H_active: { bool x; if (!cp_bool(str, &x)) return errh->error("expected boolean value"); ts->_active = x; return 0; } default: return -EINVAL; } } void SNMPTrapSource::add_handlers() { add_read_handler("drops", read_handler, H_drops); add_read_handler("enterprise", read_handler, H_enterprise); add_read_handler("src", read_handler, H_src); add_write_handler("src", write_handler, H_src); add_read_handler("dst", read_handler, H_dst); add_write_handler("dst", write_handler, H_dst); add_read_handler("sport", read_handler, H_sport); add_write_handler("sport", write_handler, H_sport); add_read_handler("dport", read_handler, H_dport); add_write_handler("dport", write_handler, H_dport); add_read_handler("traps", read_handler, H_traps); add_write_handler("active", write_handler, H_active, Handler::CHECKBOX); add_read_handler("active", read_handler, H_active); for (int i = 0; i < _names.size(); i++) add_write_handler("send_" + _names[i], trap_write_handler, i, Handler::BUTTON); } ELEMENT_REQUIRES(SNMPBasics SNMPBER SNMPVariableInfo) EXPORT_ELEMENT(SNMPTrapSource) #include "win32textfield.h" Win32TextField::Win32TextField( BBGroup *group,int style ):BBTextField(group,style){ HWND parent=(HWND)group->query( BBQID_WIN32CLIENTHWND ); int xstyle=WS_EX_CLIENTEDGE; int wstyle=WS_CHILD|WS_TABSTOP|ES_AUTOHSCROLL; if( style&1 ) wstyle|=ES_PASSWORD; HWND hwnd=CreateWindowEx( xstyle,"EDIT","",wstyle,0,0,0,0,parent,0,GetModuleHandle(0),0 ); _gadget.setHwnd( hwnd ); _gadget.setWndProc( this ); } void *Win32TextField::query( int qid ){ if( void *p=_gadget.query( qid ) ) return p; return BBTextField::query( qid ); } void Win32TextField::setFont( BBFont *font ){ _gadget.setFont(font); BBTextField::setFont(font); } void Win32TextField::setText( BBString *text ){ DWORD from,to; SendMessage( _gadget.hwnd(),EM_GETSEL,(WPARAM)&from,(LPARAM)&to ); _gadget.setText( text ); SendMessage( _gadget.hwnd(),EM_SETSEL,(WPARAM)from,(LPARAM)to ); BBTextField::setText(text); } void Win32TextField::setShape( int x,int y,int w,int h ){ _gadget.setShape(x,y,w,h); BBTextField::setShape(x,y,w,h); } void Win32TextField::setVisible( bool visible ){ _gadget.setVisible(visible); BBTextField::setVisible(visible); } void Win32TextField::setEnabled( bool enabled ){ _gadget.setEnabled(enabled); BBTextField::setEnabled(enabled); } void Win32TextField::activate(){ _gadget.activate(); BBTextField::activate(); } BBString *Win32TextField::textFieldText(){ int len=SendMessage( _gadget.hwnd(),WM_GETTEXTLENGTH,0,0 ); char *buff=new char[len+1]; SendMessage( _gadget.hwnd(),WM_GETTEXT,len+1,(LPARAM)buff ); BBString *t=new BBString( buff,len ); delete[] buff; return t; } LRESULT Win32TextField::wndProc( HWND hwnd,UINT msg,WPARAM wp,LPARAM lp,WNDPROC proc ){ static int wm_char; switch( msg ){ case WM_CHAR: if( wp=='\r' ){ emit( BBEvent::GADGET_ACTION,wp ); return 0; } wm_char=wp; break; case WM_COMMAND: if( HIWORD(wp)==EN_UPDATE ){ emit( BBEvent::GADGET_ACTION,wm_char ); } return 0; } return CallWindowProc( proc,hwnd,msg,wp,lp ); } 1-10 //************************************ bs::framework - Copyright 2018 **************************************// //*********** Licensed under the MIT license. See LICENSE.md for full terms. This notice is not to be removed. ***********// #include "Scene/BsSceneActor.h" #include "Scene/BsSceneObject.h" namespace bs { SceneActor::SceneActor() :mMobility(ObjectMobility::Movable), mActive(true), mHash(0) { } SceneActor::~SceneActor() { } void SceneActor::setTransform(const Transform& transform) { if (mMobility != ObjectMobility::Movable) return; mTransform = transform; _markCoreDirty(ActorDirtyFlag::Transform); } void SceneActor::setMobility(ObjectMobility mobility) { mMobility = mobility; _markCoreDirty(ActorDirtyFlag::Mobility); } void SceneActor::setActive(bool active) { mActive = active; _markCoreDirty(ActorDirtyFlag::Active); } void SceneActor::_updateState(const SceneObject& so, bool force) { UINT32 curHash = so.getTransformHash(); if (curHash != mHash || force) { setTransform(so.getTransform()); mHash = curHash; } if (so.getActive() != mActive || force) setActive(so.getActive()); if (so.getMobility() != mMobility || force) setMobility(so.getMobility()); } char* SceneActor::syncActorTo(char* data) { data = rttiWriteElem(mTransform.getPosition(), data); data = rttiWriteElem(mTransform.getRotation(), data); data = rttiWriteElem(mTransform.getScale(), data); data = rttiWriteElem(mActive, data); data = rttiWriteElem(mMobility, data); return data; } char* SceneActor::syncActorFrom(char* data) { Vector3 position; Quaternion rotation; Vector3 scale; data = rttiReadElem(position, data); data = rttiReadElem(rotation, data); data = rttiReadElem(scale, data); data = rttiReadElem(mActive, data); data = rttiReadElem(mMobility, data); mTransform.setPosition(position); mTransform.setRotation(rotation); mTransform.setScale(scale); return data; } UINT32 SceneActor::getActorSyncDataSize() const { UINT32 size = rttiGetElemSize(mTransform.getPosition()) + rttiGetElemSize(mTransform.getRotation()) + rttiGetElemSize(mTransform.getScale()) + rttiGetElemSize(mActive) + rttiGetElemSize(mMobility); return size; } } /* Copyright (c) 2012-2017, ARM Limited and Contributors * * SPDX-License-Identifier: MIT * * 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 "PlaneModel.h" #include "Mathematics.h" namespace MaliSDK { /** Please see header for the specification. */ void PlaneModel::getNormals(float** normalsPtrPtr, int* numberOfCoordinatesPtr) { ASSERT(normalsPtrPtr != NULL, "Cannot use null pointer while calculating coordinates."); /* 2 triangles, 3 points of triangle, 3 coordinates for each point. */ const int numberOfNormalsCoordinates = NUMBER_OF_TRIANGLES_IN_QUAD * NUMBER_OF_TRIANGLE_VERTICES * NUMBER_OF_POINT_COORDINATES; /* Allocate memory for result array. */ *normalsPtrPtr = (float*) malloc(numberOfNormalsCoordinates * sizeof(float)); /* Is allocation successful? */ ASSERT(*normalsPtrPtr != NULL, "Could not allocate memory for result array."); /* Index of an array we will put new point coordinates at. */ int currentIndex = 0; for (int i = 0; i < numberOfNormalsCoordinates; i += NUMBER_OF_TRIANGLE_VERTICES) { (*normalsPtrPtr)[currentIndex++] = 0.0f; (*normalsPtrPtr)[currentIndex++] = 1.0f; (*normalsPtrPtr)[currentIndex++] = 0.0f; } if (numberOfCoordinatesPtr != NULL) { *numberOfCoordinatesPtr = numberOfNormalsCoordinates; } } /** Please see header for the specification. */ void PlaneModel::getTriangleRepresentation(float** coordinatesPtrPtr, int* numberOfCoordinatesPtr, float scalingFactor) { /* Example: * z D __________ C * . | / | * / \ | / | * | | / | * | |/_________| * | A B * |----------> x */ /* Coordinates of a points: A, B, C and D as shown in a schema above. */ const Vec3f coordinatesOfPointA = {-1.0f, 0.0f, -1.0f }; const Vec3f coordinatesOfPointB = { 1.0f, 0.0f, -1.0f }; const Vec3f coordinatesOfPointC = { 1.0f, 0.0f, 1.0f }; const Vec3f coordinatesOfPointD = {-1.0f, 0.0f, 1.0f }; ASSERT(coordinatesPtrPtr != NULL, "Cannot use null pointer while calculating plane coordinates.") /* 2 triangles, 3 points of triangle, 3 coordinates for each point. */ const int numberOfSquareCoordinates = NUMBER_OF_TRIANGLES_IN_QUAD * NUMBER_OF_TRIANGLE_VERTICES * NUMBER_OF_POINT_COORDINATES; /* Allocate memory for result array. */ *coordinatesPtrPtr = (float*) malloc(numberOfSquareCoordinates * sizeof(float)); /* Is allocation successful? */ ASSERT(*coordinatesPtrPtr != NULL, "Could not allocate memory for plane coordinates result array.") /* Index of an array we will put new point coordinates at. */ int currentIndex = 0; /* First triangle. */ /* A */ (*coordinatesPtrPtr)[currentIndex++] = coordinatesOfPointA.x; (*coordinatesPtrPtr)[currentIndex++] = coordinatesOfPointA.y; (*coordinatesPtrPtr)[currentIndex++] = coordinatesOfPointA.z; /* B */ (*coordinatesPtrPtr)[currentIndex++] = coordinatesOfPointB.x; (*coordinatesPtrPtr)[currentIndex++] = coordinatesOfPointB.y; (*coordinatesPtrPtr)[currentIndex++] = coordinatesOfPointB.z; /* C */ (*coordinatesPtrPtr)[currentIndex++] = coordinatesOfPointC.x; (*coordinatesPtrPtr)[currentIndex++] = coordinatesOfPointC.y; (*coordinatesPtrPtr)[currentIndex++] = coordinatesOfPointC.z; /* Second triangle. */ /* A */ (*coordinatesPtrPtr)[currentIndex++] = coordinatesOfPointA.x; (*coordinatesPtrPtr)[currentIndex++] = coordinatesOfPointA.y; (*coordinatesPtrPtr)[currentIndex++] = coordinatesOfPointA.z; /* C */ (*coordinatesPtrPtr)[currentIndex++] = coordinatesOfPointC.x; (*coordinatesPtrPtr)[currentIndex++] = coordinatesOfPointC.y; (*coordinatesPtrPtr)[currentIndex++] = coordinatesOfPointC.z; /* D */ (*coordinatesPtrPtr)[currentIndex++] = coordinatesOfPointD.x; (*coordinatesPtrPtr)[currentIndex++] = coordinatesOfPointD.y; (*coordinatesPtrPtr)[currentIndex++] = coordinatesOfPointD.z; if (scalingFactor != 1.0f) { for (int i = 0; i < numberOfSquareCoordinates; i++) { (*coordinatesPtrPtr)[i] *= scalingFactor; } } if (numberOfCoordinatesPtr != NULL) { *numberOfCoordinatesPtr = numberOfSquareCoordinates; } } } #include #include #include #include "common.h" #include "ds/list.h" #include "gtest/gtest.h" using namespace std; using ds::List; TEST(List, default_constructor) { List list; } TEST(List, initializer_list_constructor) { List list{1, 2, 3}; auto iter = list.begin(); ASSERT_EQ(1, *iter); ++iter; ASSERT_EQ(2, *iter); ++iter; ASSERT_EQ(3, *iter); } TEST(List, copy_constructor) { List list{1, 2, 3}; List list2(list); auto iter = list2.begin(); ASSERT_EQ(1, *iter); ++iter; ASSERT_EQ(2, *iter); ++iter; ASSERT_EQ(3, *iter); } TEST(List, move_constructor) { List list{1, 2, 3}; List list2(std::move(list)); ASSERT_EQ(true, list.empty()); ASSERT_EQ(0, list.size()); auto iter = list2.begin(); ASSERT_EQ(1, *iter); ++iter; ASSERT_EQ(2, *iter); ++iter; ASSERT_EQ(3, *iter); } TEST(List, iterator) { List list{1, 2, 3}; for (const auto &elem : list) { cout << elem << endl; } } TEST(List, front) { List list{1, 2, 3}; ASSERT_EQ(1, list.front()); } TEST(List, back) { List list{1, 2, 3}; ASSERT_EQ(3, list.back()); } TEST(List, empty) { List list; ASSERT_EQ(true, list.empty()); list.insert(list.begin(), "value"); ASSERT_EQ(false, list.empty()); } TEST(List, size) { List list; ASSERT_EQ(0, list.size()); list.insert(list.begin(), "value"); ASSERT_EQ(1, list.size()); } TEST(List, clear) { List list{1, 2, 3}; list.clear(); ASSERT_EQ(true, list.empty()); ASSERT_EQ(0, list.size()); } TEST(List, insert_lvalue) { List list; int v1 = 1; int v2 = 2; int v3 = 3; list.insert(list.begin(), v1); // h, 1, t list.insert(list.end(), v2); // h, 1, 2, t list.insert(list.begin(), v3); // h, 3, 1, 2, t auto iter = list.begin(); ASSERT_EQ(v3, *iter); ++iter; ASSERT_EQ(v1, *iter); ++iter; ASSERT_EQ(v2, *iter); } TEST(List, insert_rvalue) { List list; UnCopyable o1(1); UnCopyable o2(2); UnCopyable o3(3); list.insert(list.begin(), std::move(o1)); // h, 1, t list.insert(list.end(), std::move(o2)); // h, 1, 2, t list.insert(list.begin(), std::move(o3)); // h, 3, 1, 2, t auto iter = list.begin(); ASSERT_EQ(3, iter->get_id()); ++iter; ASSERT_EQ(1, iter->get_id()); ++iter; ASSERT_EQ(2, iter->get_id()); } TEST(List, erase) { List list{1, 2, 3}; list.erase(list.begin()); ASSERT_EQ(2, list.front()); list.erase(--list.end()); ASSERT_EQ(2, list.back()); auto iter = list.erase(list.begin()); ASSERT_EQ(iter, list.end()); ASSERT_EQ(true, list.empty()); } TEST(List, push_back_lvalue) { List list; int v1 = 1; int v2 = 2; int v3 = 3; list.push_back(v1); list.push_back(v2); list.push_back(v3); auto iter = list.begin(); ASSERT_EQ(v1, *iter); ++iter; ASSERT_EQ(v2, *iter); ++iter; ASSERT_EQ(v3, *iter); } TEST(List, push_back_rvalue) { List list; list.push_back(1); list.push_back(2); list.push_back(3); auto iter = list.begin(); ASSERT_EQ(1, *iter); ++iter; ASSERT_EQ(2, *iter); ++iter; ASSERT_EQ(3, *iter); } TEST(List, pop_back) { List list{1, 2, 3}; list.pop_back(); ASSERT_EQ(2, list.back()); list.pop_back(); ASSERT_EQ(1, list.back()); } TEST(List, push_front_lvalue) { List list; int v1 = 1; int v2 = 2; int v3 = 3; list.push_front(v1); list.push_front(v2); list.push_front(v3); auto iter = list.begin(); ASSERT_EQ(v3, *iter); ++iter; ASSERT_EQ(v2, *iter); ++iter; ASSERT_EQ(v1, *iter); } TEST(List, push_front_rvalue) { List list; list.push_front(1); list.push_front(2); list.push_front(3); auto iter = list.begin(); ASSERT_EQ(3, *iter); ++iter; ASSERT_EQ(2, *iter); ++iter; ASSERT_EQ(1, *iter); } TEST(List, pop_front) { List list{1, 2, 3}; list.pop_front(); ASSERT_EQ(2, list.front()); list.pop_front(); ASSERT_EQ(3, list.front()); } TEST(List, massive_insert) { List list; for (int i = 0; i < iteration_count / 1000; ++i) { switch (i % 3) { case 0: { list.insert(list.begin(), i); break; } case 1: { list.push_back(i); break; } case 2: { list.push_front(i); break; } } } ASSERT_EQ(iteration_count / 1000, list.size()); for (int i = 0; i < iteration_count / 1000; ++i) { auto iter = list.find(i); ASSERT_NE(list.end(), iter); ASSERT_EQ(i, *iter); } } TEST(List, find) { List list; list.push_front(1); list.push_front(2); list.push_front(3); auto iter = list.find(3); ASSERT_EQ(3, *iter); } 0 #include //Hola mundo cruel */ int main(){ printf("Hola mundo"); return 0; } 0 /****************************************************************************/ // Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo // Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. // This program and the accompanying materials are made available under the // terms of the Eclipse Public License 2.0 which is available at // https://www.eclipse.org/legal/epl-2.0/ // This Source Code may also be made available under the following Secondary // Licenses when the conditions for such availability set forth in the Eclipse // Public License 2.0 are satisfied: GNU General Public License, version 2 // or later which is available at // https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html // SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later /****************************************************************************/ /// @file GNENet.cpp /// @author /// @date Feb 2011 /// // A visual container for GNE-network-components such as GNEEdge and GNEJunction. // GNE components wrap netbuild-components and supply visualisation and editing // capabilities (adapted from GUINet) // // WorkrouteFlow (rough draft) // use NILoader to fill // do netedit stuff // call compute to save results // /****************************************************************************/ #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 #include "GNEApplicationWindow.h" #include "GNENet.h" #include "GNEViewNet.h" #include "GNEUndoList.h" #include "GNEViewParent.h" // =========================================================================== // FOX callback mapping // =========================================================================== FXIMPLEMENT_ABSTRACT(GNENetHelper::GNEChange_ReplaceEdgeInTLS, GNEChange, nullptr, 0) // =========================================================================== // static members // =========================================================================== const double GNENet::Z_INITIALIZED = 1; // =========================================================================== // member method definitions // =========================================================================== GNENet::GNENet(NBNetBuilder* netBuilder) : GUIGlObject(GLO_NETWORK, ""), myViewNet(nullptr), myNetBuilder(netBuilder), myAttributeCarriers(new GNENetHelper::AttributeCarriers(this)), myPathCalculator(new GNENetHelper::PathCalculator(this)), myEdgeIDSupplier("gneE", netBuilder->getEdgeCont().getAllNames()), myJunctionIDSupplier("gneJ", netBuilder->getNodeCont().getAllNames()), myNeedRecompute(true), myNetSaved(true), myAdditionalsSaved(true), myTLSProgramsSaved(true), myDemandElementsSaved(true), myDataElementsSaved(true), myUpdateGeometryEnabled(true) { // set net in gIDStorage GUIGlObjectStorage::gIDStorage.setNetObject(this); // Write GL debug information WRITE_GLDEBUG("initJunctionsAndEdges function called in GNENet constructor"); // init junction and edges initJunctionsAndEdges(); // check Z boundary if (myZBoundary.ymin() != Z_INITIALIZED) { myZBoundary.add(0, 0); } } GNENet::~GNENet() { // delete route calculator Instance delete myPathCalculator; // delete AttributeCarriers delete myAttributeCarriers; // show extra information for tests WRITE_DEBUG("Deleting net builder in GNENet destructor"); delete myNetBuilder; } GNENetHelper::AttributeCarriers* GNENet::getAttributeCarriers() const { return myAttributeCarriers; } GNENetHelper::PathCalculator* GNENet::getPathCalculator() { return myPathCalculator; } const Boundary& GNENet::getBoundary() const { // SUMORTree is also a Boundary return myGrid; } SUMORTree& GNENet::getGrid() { return myGrid; } GUIGLObjectPopupMenu* GNENet::getPopUpMenu(GUIMainWindow& app, GUISUMOAbstractView& parent) { GUIGLObjectPopupMenu* ret = new GUIGLObjectPopupMenu(app, parent, *this); buildPopupHeader(ret, app); buildCenterPopupEntry(ret); buildPositionCopyEntry(ret, false); return ret; } GUIParameterTableWindow* GNENet::getParameterWindow(GUIMainWindow& app, GUISUMOAbstractView&) { // Nets lanes don't have attributes GUIParameterTableWindow* ret = new GUIParameterTableWindow(app, *this); // close building ret->closeBuilding(); return ret; } void GNENet::drawGL(const GUIVisualizationSettings& /*s*/) const { // nothing to drawn } Boundary GNENet::getCenteringBoundary() const { return getBoundary(); } void GNENet::expandBoundary(const Boundary& newBoundary) { myGrid.add(newBoundary); } const Boundary& GNENet::getZBoundary() const { return myZBoundary; } void GNENet::addZValueInBoundary(const double z) { // @todo let Boundary class track z-coordinate natively if (z != 0) { myZBoundary.add(z, Z_INITIALIZED); } } GNEJunction* GNENet::createJunction(const Position& pos, GNEUndoList* undoList) { std::string id = myJunctionIDSupplier.getNext(); // create new NBNode NBNode* nbn = new NBNode(id, pos); // create GNEJunciton GNEJunction* junction = new GNEJunction(this, nbn); undoList->add(new GNEChange_Junction(junction, true), true); return junction; } GNEEdge* GNENet::createEdge( GNEJunction* src, GNEJunction* dest, GNEEdge* tpl, GNEUndoList* undoList, const std::string& suggestedName, bool wasSplit, bool allowDuplicateGeom, bool recomputeConnections) { // prevent duplicate edge (same geometry) const EdgeVector& outgoing = src->getNBNode()->getOutgoingEdges(); for (EdgeVector::const_iterator it = outgoing.begin(); it != outgoing.end(); it++) { if ((*it)->getToNode() == dest->getNBNode() && (*it)->getGeometry().size() == 2) { if (!allowDuplicateGeom) { return nullptr; } } } std::string id; if (suggestedName != "" && !retrieveEdge(suggestedName, false)) { id = suggestedName; reserveEdgeID(id); } else { id = myEdgeIDSupplier.getNext(); } GNEEdge* edge; if (tpl) { NBEdge* nbeTpl = tpl->getNBEdge(); NBEdge* nbe = new NBEdge(id, src->getNBNode(), dest->getNBNode(), nbeTpl); edge = new GNEEdge(this, nbe, wasSplit); } else { // default if no template is given const OptionsCont& oc = OptionsCont::getOptions(); double defaultSpeed = oc.getFloat("default.speed"); std::string defaultType = oc.getString("default.type"); int defaultNrLanes = oc.getInt("default.lanenumber"); int defaultPriority = oc.getInt("default.priority"); double defaultWidth = NBEdge::UNSPECIFIED_WIDTH; double defaultOffset = NBEdge::UNSPECIFIED_OFFSET; NBEdge* nbe = new NBEdge(id, src->getNBNode(), dest->getNBNode(), defaultType, defaultSpeed, defaultNrLanes, defaultPriority, defaultWidth, defaultOffset); edge = new GNEEdge(this, nbe, wasSplit); } undoList->p_begin("create " + toString(SUMO_TAG_EDGE)); undoList->add(new GNEChange_Edge(edge, true), true); if (recomputeConnections) { src->setLogicValid(false, undoList); dest->setLogicValid(false, undoList); } requireRecompute(); undoList->p_end(); return edge; } void GNENet::deleteJunction(GNEJunction* junction, GNEUndoList* undoList) { // we have to delete all incident edges because they cannot exist without that junction // all deletions must be undone/redone together so we start a new command group // @todo if any of those edges are dead-ends should we remove their orphan junctions as well? undoList->p_begin("delete " + toString(SUMO_TAG_JUNCTION)); // invalidate path elements junction->invalidatePathElements(); // delete all crossings vinculated with junction while (junction->getGNECrossings().size() > 0) { deleteCrossing(junction->getGNECrossings().front(), undoList); } // find all crossings of neightbour junctions that shares an edge of this junction std::vector crossingsToRemove; std::vector junctionNeighbours = junction->getJunctionNeighbours(); for (const auto& junction : junctionNeighbours) { // iterate over crossing of neighbour juntion for (const auto& crossing : junction->getGNECrossings()) { // if at least one of the edges of junction to remove belongs to a crossing of the neighbour junction, delete it if (crossing->checkEdgeBelong(junction->getChildEdges())) { crossingsToRemove.push_back(crossing); } } } // delete crossings top remove for (const auto& crossing : crossingsToRemove) { deleteCrossing(crossing, undoList); } // deleting edges changes in the underlying EdgeVector so we have to make a copy const EdgeVector incidentEdges = junction->getNBNode()->getEdges(); for (const auto& edge : incidentEdges) { deleteEdge(myAttributeCarriers->getEdges().at(edge->getID()), undoList, true); } // remove any traffic lights from the traffic light container (avoids lots of warnings) junction->setAttribute(SUMO_ATTR_TYPE, toString(SumoXMLNodeType::PRIORITY), undoList); // delete edge undoList->add(new GNEChange_Junction(junction, false), true); undoList->p_end(); } void GNENet::deleteEdge(GNEEdge* edge, GNEUndoList* undoList, bool recomputeConnections) { undoList->p_begin("delete " + toString(SUMO_TAG_EDGE)); // iterate over lanes for (const auto& lane : edge->getLanes()) { // invalidate path elements lane->invalidatePathElements(); // delete lane additionals while (lane->getChildAdditionals().size() > 0) { deleteAdditional(lane->getChildAdditionals().front(), undoList); } // delete lane shapes while (lane->getChildShapes().size() > 0) { deleteShape(lane->getChildShapes().front(), undoList); } // delete lane demand elements while (lane->getChildDemandElements().size() > 0) { deleteDemandElement(lane->getChildDemandElements().front(), undoList); } // delete lane generic data elements while (lane->getChildGenericDatas().size() > 0) { deleteGenericData(lane->getChildGenericDatas().front(), undoList); } } // delete edge child additionals while (edge->getChildAdditionals().size() > 0) { deleteAdditional(edge->getChildAdditionals().front(), undoList); } // delete edge child shapes while (edge->getChildShapes().size() > 0) { deleteShape(edge->getChildShapes().front(), undoList); } // delete edge child demand elements while (edge->getChildDemandElements().size() > 0) { deleteDemandElement(edge->getChildDemandElements().front(), undoList); } // delete edge child generic datas while (edge->getChildGenericDatas().size() > 0) { deleteGenericData(edge->getChildGenericDatas().front(), undoList); } // remove edge from crossings related with this edge edge->getParentJunctions().front()->removeEdgeFromCrossings(edge, undoList); edge->getParentJunctions().back()->removeEdgeFromCrossings(edge, undoList); // update affected connections if (recomputeConnections) { edge->getParentJunctions().front()->setLogicValid(false, undoList); edge->getParentJunctions().back()->setLogicValid(false, undoList); } else { edge->getParentJunctions().front()->removeConnectionsTo(edge, undoList, true); edge->getParentJunctions().front()->removeConnectionsFrom(edge, undoList, true); } // if junction source is a TLS and after deletion will have only an edge, remove TLS if (edge->getParentJunctions().front()->getNBNode()->isTLControlled() && (edge->getParentJunctions().front()->getGNEOutgoingEdges().size() <= 1)) { edge->getParentJunctions().front()->setAttribute(SUMO_ATTR_TYPE, toString(SumoXMLNodeType::PRIORITY), undoList); } // if junction destiny is a TLS and after deletion will have only an edge, remove TLS if (edge->getParentJunctions().back()->getNBNode()->isTLControlled() && (edge->getParentJunctions().back()->getGNEIncomingEdges().size() <= 1)) { edge->getParentJunctions().back()->setAttribute(SUMO_ATTR_TYPE, toString(SumoXMLNodeType::PRIORITY), undoList); } // Delete edge undoList->add(new GNEChange_Edge(edge, false), true); // remove edge requires always a recompute (due geometry and connections) requireRecompute(); // finish delete edge undoList->p_end(); } void GNENet::replaceIncomingEdge(GNEEdge* which, GNEEdge* by, GNEUndoList* undoList) { undoList->p_begin("replace " + toString(SUMO_TAG_EDGE)); undoList->p_add(new GNEChange_Attribute(by, SUMO_ATTR_TO, which->getAttribute(SUMO_ATTR_TO))); // iterate over lane for (const auto& lane : which->getLanes()) { // replace in additionals std::vector copyOfLaneAdditionals = lane->getChildAdditionals(); for (const auto& additional : copyOfLaneAdditionals) { undoList->p_add(new GNEChange_Attribute(additional, SUMO_ATTR_LANE, by->getNBEdge()->getLaneID(lane->getIndex()))); } // replace in shapes std::vector copyOfLaneShapes = lane->getChildShapes(); for (const auto& shape : copyOfLaneShapes) { undoList->p_add(new GNEChange_Attribute(shape, SUMO_ATTR_LANE, by->getNBEdge()->getLaneID(lane->getIndex()))); } // replace in demand elements std::vector copyOfLaneDemandElements = lane->getChildDemandElements(); for (const auto& demandElement : copyOfLaneDemandElements) { undoList->p_add(new GNEChange_Attribute(demandElement, SUMO_ATTR_LANE, by->getNBEdge()->getLaneID(lane->getIndex()))); } // replace in generic datas std::vector copyOfLaneGenericDatas = lane->getChildGenericDatas(); for (const auto& demandElement : copyOfLaneGenericDatas) { undoList->p_add(new GNEChange_Attribute(demandElement, SUMO_ATTR_LANE, by->getNBEdge()->getLaneID(lane->getIndex()))); } } // replace in edge additionals children while (which->getChildAdditionals().size() > 0) { undoList->p_add(new GNEChange_Attribute(which->getChildAdditionals().front(), SUMO_ATTR_EDGE, by->getID())); } // replace in edge shapes children while (which->getChildShapes().size() > 0) { undoList->p_add(new GNEChange_Attribute(which->getChildShapes().front(), SUMO_ATTR_EDGE, by->getID())); } // replace in edge demand elements children while (which->getChildDemandElements().size() > 0) { undoList->p_add(new GNEChange_Attribute(which->getChildDemandElements().front(), SUMO_ATTR_EDGE, by->getID())); } // replace in edge demand elements children while (which->getChildGenericDatas().size() > 0) { undoList->p_add(new GNEChange_Attribute(which->getChildGenericDatas().front(), SUMO_ATTR_EDGE, by->getID())); } // replace in rerouters for (const auto& rerouter : which->getParentAdditionals()) { replaceInListAttribute(rerouter, SUMO_ATTR_EDGES, which->getID(), by->getID(), undoList); } // replace in crossings for (const auto& crossing : which->getParentJunctions().back()->getGNECrossings()) { // if at least one of the edges of junction to remove belongs to a crossing of the source junction, delete it replaceInListAttribute(crossing, SUMO_ATTR_EDGES, which->getID(), by->getID(), undoList); } // fix connections (make a copy because they will be modified std::vector NBConnections = which->getNBEdge()->getConnections(); for (const auto& NBConnection : NBConnections) { undoList->add(new GNEChange_Connection(which, NBConnection, false, false), true); undoList->add(new GNEChange_Connection(by, NBConnection, false, true), true); } undoList->add(new GNENetHelper::GNEChange_ReplaceEdgeInTLS(getTLLogicCont(), which->getNBEdge(), by->getNBEdge()), true); // Delete edge undoList->add(new GNEChange_Edge(which, false), true); // finish replace edge undoList->p_end(); } void GNENet::deleteLane(GNELane* lane, GNEUndoList* undoList, bool recomputeConnections) { GNEEdge* edge = lane->getParentEdge(); if (edge->getNBEdge()->getNumLanes() == 1) { // remove the whole edge instead deleteEdge(edge, undoList, recomputeConnections); } else { undoList->p_begin("delete " + toString(SUMO_TAG_LANE)); // invalidate path elements lane->invalidatePathElements(); // delete lane additional children while (lane->getChildAdditionals().size() > 0) { deleteAdditional(lane->getChildAdditionals().front(), undoList); } // delete lane shape children while (lane->getChildShapes().size() > 0) { deleteShape(lane->getChildShapes().front(), undoList); } // delete lane demand element children while (lane->getChildDemandElements().size() > 0) { deleteDemandElement(lane->getChildDemandElements().front(), undoList); } // delete lane generic data children while (lane->getChildGenericDatas().size() > 0) { deleteGenericData(lane->getChildGenericDatas().front(), undoList); } // update affected connections if (recomputeConnections) { edge->getParentJunctions().front()->setLogicValid(false, undoList); edge->getParentJunctions().back()->setLogicValid(false, undoList); } else { edge->getParentJunctions().front()->removeConnectionsTo(edge, undoList, true, lane->getIndex()); edge->getParentJunctions().front()->removeConnectionsFrom(edge, undoList, true, lane->getIndex()); } // delete lane const NBEdge::Lane& laneAttrs = edge->getNBEdge()->getLaneStruct(lane->getIndex()); undoList->add(new GNEChange_Lane(edge, lane, laneAttrs, false, recomputeConnections), true); // remove lane requires always a recompute (due geometry and connections) requireRecompute(); undoList->p_end(); } } void GNENet::deleteConnection(GNEConnection* connection, GNEUndoList* undoList) { undoList->p_begin("delete " + toString(SUMO_TAG_CONNECTION)); // obtain NBConnection to remove NBConnection deleted = connection->getNBConnection(); GNEJunction* junctionDestiny = connection->getEdgeFrom()->getParentJunctions().back(); junctionDestiny->markAsModified(undoList); undoList->add(new GNEChange_Connection(connection->getEdgeFrom(), connection->getNBEdgeConnection(), connection->isAttributeCarrierSelected(), false), true); junctionDestiny->invalidateTLS(undoList, deleted); // remove connection requires always a recompute (due geometry and connections) requireRecompute(); undoList->p_end(); } void GNENet::deleteCrossing(GNECrossing* crossing, GNEUndoList* undoList) { undoList->p_begin("delete crossing"); // remove it using GNEChange_Crossing undoList->add(new GNEChange_Crossing( crossing->getParentJunction(), crossing->getNBCrossing()->edges, crossing->getNBCrossing()->width, crossing->getNBCrossing()->priority, crossing->getNBCrossing()->customTLIndex, crossing->getNBCrossing()->customTLIndex2, crossing->getNBCrossing()->customShape, crossing->isAttributeCarrierSelected(), false), true); // remove crossing requires always a recompute (due geometry and connections) requireRecompute(); undoList->p_end(); } void GNENet::deleteAdditional(GNEAdditional* additional, GNEUndoList* undoList) { undoList->p_begin("delete " + additional->getTagStr()); // remove all demand element children of this additional deleteDemandElement this function recursively while (additional->getChildDemandElements().size() > 0) { deleteDemandElement(additional->getChildDemandElements().front(), undoList); } // remove all generic data children of this additional deleteGenericData this function recursively while (additional->getChildGenericDatas().size() > 0) { deleteGenericData(additional->getChildGenericDatas().front(), undoList); } // remove all additional children of this additional calling this function recursively while (additional->getChildAdditionals().size() > 0) { deleteAdditional(additional->getChildAdditionals().front(), undoList); } // remove additional undoList->add(new GNEChange_Additional(additional, false), true); undoList->p_end(); } void GNENet::deleteShape(GNEShape* shape, GNEUndoList* undoList) { undoList->p_begin("delete " + shape->getTagStr()); // delete shape undoList->add(new GNEChange_Shape(shape, false), true); undoList->p_end(); } void GNENet::deleteTAZElement(GNETAZElement* TAZElement, GNEUndoList* undoList) { undoList->p_begin("delete " + TAZElement->getTagStr()); // remove all demand element children of this TAZElement deleteDemandElement this function recursively while (TAZElement->getChildDemandElements().size() > 0) { deleteDemandElement(TAZElement->getChildDemandElements().front(), undoList); } // remove all generic data children of this TAZElement deleteGenericData this function recursively while (TAZElement->getChildGenericDatas().size() > 0) { deleteGenericData(TAZElement->getChildGenericDatas().front(), undoList); } // remove all TAZElement children of this TAZElement calling this function recursively while (TAZElement->getChildTAZElements().size() > 0) { deleteTAZElement(TAZElement->getChildTAZElements().front(), undoList); } // remove TAZElement undoList->add(new GNEChange_TAZElement(TAZElement, false), true); undoList->p_end(); } void GNENet::deleteDemandElement(GNEDemandElement* demandElement, GNEUndoList* undoList) { // check that default VTypes aren't removed if ((demandElement->getTagProperty().getTag() == SUMO_TAG_VTYPE) && (GNEAttributeCarrier::parse(demandElement->getAttribute(GNE_ATTR_DEFAULT_VTYPE)))) { throw ProcessError("Trying to delete a default Vehicle Type"); } else { // check if currently is being inspected if (myViewNet->getInspectedAttributeCarrier() == demandElement) { myViewNet->getViewParent()->getInspectorFrame()->clearInspectedAC(); } undoList->p_begin("delete " + demandElement->getTagStr()); // remove all child demand elements of this demandElement calling this function recursively while (demandElement->getChildDemandElements().size() > 0) { deleteDemandElement(demandElement->getChildDemandElements().front(), undoList); } // remove all generic data children of this additional deleteGenericData this function recursively while (demandElement->getChildGenericDatas().size() > 0) { deleteGenericData(demandElement->getChildGenericDatas().front(), undoList); } // remove demandElement undoList->add(new GNEChange_DemandElement(demandElement, false), true); undoList->p_end(); } } void GNENet::deleteDataSet(GNEDataSet* dataSet, GNEUndoList* undoList) { undoList->p_begin("delete " + dataSet->getTagStr()); // make a copy of all generic data children auto copyOfDataIntervalChildren = dataSet->getDataIntervalChildren(); // clear all data intervals (this will be delete also the dataSet) for (const auto& dataInterval : copyOfDataIntervalChildren) { deleteDataInterval(dataInterval.second, undoList); } undoList->p_end(); } void GNENet::deleteDataInterval(GNEDataInterval* dataInterval, GNEUndoList* undoList) { undoList->p_begin("delete " + dataInterval->getTagStr()); // make a copy of all generic data children auto copyOfGenericDataChildren = dataInterval->getGenericDataChildren(); // clear all generic datas (this will be delete also the data intervals) for (const auto& genericData : copyOfGenericDataChildren) { deleteGenericData(genericData, undoList); } undoList->p_end(); } void GNENet::deleteGenericData(GNEGenericData* genericData, GNEUndoList* undoList) { undoList->p_begin("delete " + genericData->getTagStr()); // remove all child demand elements of this demandElement calling this function recursively while (genericData->getChildDemandElements().size() > 0) { deleteDemandElement(genericData->getChildDemandElements().front(), undoList); } // remove all generic data children of this additional deleteGenericData this function recursively while (genericData->getChildGenericDatas().size() > 0) { deleteGenericData(genericData->getChildGenericDatas().front(), undoList); } // get pointer to dataInterval and dataSet GNEDataInterval* dataInterval = genericData->getDataIntervalParent(); GNEDataSet* dataSet = dataInterval->getDataSetParent(); // remove generic data undoList->add(new GNEChange_GenericData(genericData, false), true); // check if data interval is empty if (dataInterval->getGenericDataChildren().empty()) { // remove data interval undoList->add(new GNEChange_DataInterval(genericData->getDataIntervalParent(), false), true); // now check if data set is empty if (dataSet->getDataIntervalChildren().empty()) { // remove data set undoList->add(new GNEChange_DataSet(genericData->getDataIntervalParent()->getDataSetParent(), false), true); } } undoList->p_end(); } void GNENet::duplicateLane(GNELane* lane, GNEUndoList* undoList, bool recomputeConnections) { undoList->p_begin("duplicate " + toString(SUMO_TAG_LANE)); GNEEdge* edge = lane->getParentEdge(); const NBEdge::Lane& laneAttrs = edge->getNBEdge()->getLaneStruct(lane->getIndex()); if (recomputeConnections) { edge->getParentJunctions().front()->setLogicValid(false, undoList); edge->getParentJunctions().front()->setLogicValid(false, undoList); } GNELane* newLane = new GNELane(edge, lane->getIndex()); undoList->add(new GNEChange_Lane(edge, newLane, laneAttrs, true, recomputeConnections), true); requireRecompute(); undoList->p_end(); } bool GNENet::restrictLane(SUMOVehicleClass vclass, GNELane* lane, GNEUndoList* undoList) { bool addRestriction = true; if (vclass == SVC_PEDESTRIAN) { GNEEdge* edge = lane->getParentEdge(); for (const auto& edgeLane : edge->getLanes()) { if (edgeLane->isRestricted(SVC_PEDESTRIAN)) { // prevent adding a 2nd sidewalk addRestriction = false; } else { // ensure that the sidewalk is used exclusively const SVCPermissions allOldWithoutPeds = edge->getNBEdge()->getPermissions(edgeLane->getIndex()) & ~SVC_PEDESTRIAN; edgeLane->setAttribute(SUMO_ATTR_ALLOW, getVehicleClassNames(allOldWithoutPeds), undoList); } } } // restrict the lane if (addRestriction) { const double width = (vclass == SVC_PEDESTRIAN || vclass == SVC_BICYCLE ? OptionsCont::getOptions().getFloat("default.sidewalk-width") : OptionsCont::getOptions().getFloat("default.lanewidth")); lane->setAttribute(SUMO_ATTR_ALLOW, toString(vclass), undoList); lane->setAttribute(SUMO_ATTR_WIDTH, toString(width), undoList); return true; } else { return false; } } bool GNENet::addRestrictedLane(SUMOVehicleClass vclass, GNEEdge* edge, int index, GNEUndoList* undoList) { // First check that edge don't have a restricted lane of the given vclass for (const auto& lane : edge->getLanes()) { if (lane->isRestricted(vclass)) { return false; } } // check that index is correct (index == size adds to the left of the leftmost lane) const int numLanes = (int)edge->getLanes().size(); if (index > numLanes) { return false; } if (index < 0) { // guess index from vclass if (vclass == SVC_PEDESTRIAN) { index = 0; } else if (vclass == SVC_BICYCLE) { // add bikelanes to the left of an existing sidewalk index = edge->getLanes()[0]->isRestricted(SVC_PEDESTRIAN) ? 1 : 0; } else if (vclass == SVC_IGNORING || vclass == SVC_BUS) { // add greenVerge to the left of an existing sidewalk or bikeLane // add busLane to the left of an existing sidewalk, bikeLane or greenVerge index = 0; while (index < numLanes && (edge->getNBEdge()->getPermissions(index) & ~(SVC_PEDESTRIAN | SVC_BICYCLE)) == 0) { index++; } } } // duplicate selected lane duplicateLane(edge->getLanes().at(MIN2(index, numLanes - 1)), undoList, true); // transform the created lane return restrictLane(vclass, edge->getLanes().at(index), undoList); } bool GNENet::removeRestrictedLane(SUMOVehicleClass vclass, GNEEdge* edge, GNEUndoList* undoList) { // iterate over lanes of edge for (const auto& lane : edge->getLanes()) { if (lane->isRestricted(vclass)) { // Delete lane deleteLane(lane, undoList, true); return true; } } return false; } GNEJunction* GNENet::splitEdge(GNEEdge* edge, const Position& pos, GNEUndoList* undoList, GNEJunction* newJunction) { // begin undo list undoList->p_begin("split " + toString(SUMO_TAG_EDGE)); // check if we have to create a new edge if (newJunction == nullptr) { newJunction = createJunction(pos, undoList); } // obtain edge geometry and split position const PositionVector& oldEdgeGeometry = edge->getNBEdge()->getGeometry(); const double edgeSplitPosition = oldEdgeGeometry.nearest_offset_to_point2D(pos, false); // obtain lane geometry and split position (needed for adjust additional and demand childs) const PositionVector& oldLaneGeometry = edge->getLanes().front()->getLaneShape(); const double laneSplitPosition = oldLaneGeometry.nearest_offset_to_point2D(pos, false); // split edge geometry in two new geometries using edgeSplitPosition std::pair newGeoms = oldEdgeGeometry.splitAt(edgeSplitPosition); // get shape end const std::string shapeEnd = edge->getAttribute(GNE_ATTR_SHAPE_END); // figure out the new name int posBase = 0; // set baseName std::string baseName = edge->getMicrosimID(); if (edge->wasSplit()) { const std::string::size_type sep_index = baseName.rfind('.'); // edge may have been renamed in between if (sep_index != std::string::npos) { std::string posString = baseName.substr(sep_index + 1); if (GNEAttributeCarrier::canParse(posString.c_str())) { ; posBase = GNEAttributeCarrier::parse(posString.c_str()); baseName = baseName.substr(0, sep_index); // includes the . } } } baseName += '.'; // create a new edge from the new junction to the previous destination GNEEdge* secondPart = createEdge(newJunction, edge->getParentJunctions().back(), edge, undoList, baseName + toString(posBase + (int)edgeSplitPosition), true, false, false); // fix connections from the split edge (must happen before changing SUMO_ATTR_TO) edge->getParentJunctions().back()->replaceIncomingConnections(edge, secondPart, undoList); // remove affected crossings from junction (must happen before changing SUMO_ATTR_TO) std::vector affectedCrossings; for (GNECrossing* crossing : edge->getParentJunctions().back()->getGNECrossings()) { if (crossing->checkEdgeBelong(edge)) { NBNode::Crossing nbC = *crossing->getNBCrossing(); undoList->add(new GNEChange_Crossing(edge->getParentJunctions().back(), nbC, false), true); EdgeVector newEdges; for (NBEdge* nbEdge : nbC.edges) { if (nbEdge == edge->getNBEdge()) { newEdges.push_back(secondPart->getNBEdge()); } else { newEdges.push_back(nbEdge); } } nbC.edges = newEdges; affectedCrossings.push_back(nbC); } } // modify the edge so that it ends at the new junction (and all incoming connections are preserved undoList->p_add(new GNEChange_Attribute(edge, SUMO_ATTR_TO, newJunction->getID())); // set first part of geometry newGeoms.first.pop_back(); newGeoms.first.erase(newGeoms.first.begin()); edge->setAttribute(GNE_ATTR_SHAPE_END, "", undoList); edge->setAttribute(SUMO_ATTR_SHAPE, toString(newGeoms.first), undoList); // set second part of geometry secondPart->setAttribute(GNE_ATTR_SHAPE_END, shapeEnd, undoList); newGeoms.second.pop_back(); newGeoms.second.erase(newGeoms.second.begin()); secondPart->setAttribute(SUMO_ATTR_SHAPE, toString(newGeoms.second), undoList); // reconnect across the split for (int i = 0; i < (int)edge->getLanes().size(); ++i) { undoList->add(new GNEChange_Connection(edge, NBEdge::Connection(i, secondPart->getNBEdge(), i), false, true), true); } // re-add modified crossings for (const auto& nbC : affectedCrossings) { undoList->add(new GNEChange_Crossing(secondPart->getParentJunctions().back(), nbC, true), true); } // Split geometry of all child additional for (const auto& additional : edge->getChildAdditionals()) { additional->splitEdgeGeometry(edgeSplitPosition, edge, secondPart, undoList); } // Split geometry of all child lane additional for (int i = 0; i < (int)edge->getLanes().size(); i++) { for (const auto& additional : edge->getLanes().at(i)->getChildAdditionals()) { additional->splitEdgeGeometry(laneSplitPosition, edge->getLanes().at(i), secondPart->getLanes().at(i), undoList); } } // Split geometry of all child demand elements for (const auto& demandElement : edge->getChildDemandElements()) { demandElement->splitEdgeGeometry(edgeSplitPosition, edge, secondPart, undoList); } // Split geometry of all child lane demand elements for (int i = 0; i < (int)edge->getLanes().size(); i++) { for (const auto& demandElement : edge->getLanes().at(i)->getChildDemandElements()) { demandElement->splitEdgeGeometry(laneSplitPosition, edge->getLanes().at(i), secondPart->getLanes().at(i), undoList); } } // finish undo list undoList->p_end(); // return new junction return newJunction; } void GNENet::splitEdgesBidi(GNEEdge* edge, GNEEdge* oppositeEdge, const Position& pos, GNEUndoList* undoList) { GNEJunction* newJunction = nullptr; undoList->p_begin("split " + toString(SUMO_TAG_EDGE) + "s"); // split edge and save created junction newJunction = splitEdge(edge, pos, undoList, newJunction); // split second edge splitEdge(oppositeEdge, pos, undoList, newJunction); undoList->p_end(); } void GNENet::reverseEdge(GNEEdge* edge, GNEUndoList* undoList) { undoList->p_begin("reverse " + toString(SUMO_TAG_EDGE)); deleteEdge(edge, undoList, false); // still exists. we delete it so we can reuse the name in case of resplit GNEEdge* reversed = createEdge(edge->getParentJunctions().back(), edge->getParentJunctions().front(), edge, undoList, edge->getID(), false, true); assert(reversed != 0); reversed->setAttribute(SUMO_ATTR_SHAPE, toString(edge->getNBEdge()->getInnerGeometry().reverse()), undoList); reversed->setAttribute(GNE_ATTR_SHAPE_START, edge->getAttribute(GNE_ATTR_SHAPE_END), undoList); reversed->setAttribute(GNE_ATTR_SHAPE_END, edge->getAttribute(GNE_ATTR_SHAPE_START), undoList); undoList->p_end(); } GNEEdge* GNENet::addReversedEdge(GNEEdge* edge, GNEUndoList* undoList) { undoList->p_begin("add reversed " + toString(SUMO_TAG_EDGE)); GNEEdge* reversed = nullptr; if (edge->getNBEdge()->getLaneSpreadFunction() == LaneSpreadFunction::RIGHT || isRailway(edge->getNBEdge()->getPermissions())) { // for rail edges, we assume bi-directional tracks are wanted reversed = createEdge(edge->getParentJunctions().back(), edge->getParentJunctions().front(), edge, undoList, "-" + edge->getID(), false, true); assert(reversed != 0); reversed->setAttribute(SUMO_ATTR_SHAPE, toString(edge->getNBEdge()->getInnerGeometry().reverse()), undoList); reversed->setAttribute(GNE_ATTR_SHAPE_START, edge->getAttribute(GNE_ATTR_SHAPE_END), undoList); reversed->setAttribute(GNE_ATTR_SHAPE_END, edge->getAttribute(GNE_ATTR_SHAPE_START), undoList); } else { // if the edge is centered it should probably connect somewhere else // make it easy to move and reconnect it PositionVector orig = edge->getNBEdge()->getGeometry(); PositionVector origInner = edge->getNBEdge()->getInnerGeometry(); const double tentativeShift = edge->getNBEdge()->getTotalWidth() + 2; orig.move2side(-tentativeShift); origInner.move2side(-tentativeShift); GNEJunction* src = createJunction(orig.back(), undoList); GNEJunction* dest = createJunction(orig.front(), undoList); reversed = createEdge(src, dest, edge, undoList, "-" + edge->getID(), false, true); assert(reversed != 0); reversed->setAttribute(SUMO_ATTR_SHAPE, toString(origInner.reverse()), undoList); reversed->setAttribute(SUMO_ATTR_SHAPE, toString(origInner.reverse()), undoList); // select the new edge and its nodes reversed->setAttribute(GNE_ATTR_SELECTED, "true", undoList); src->setAttribute(GNE_ATTR_SELECTED, "true", undoList); dest->setAttribute(GNE_ATTR_SELECTED, "true", undoList); } undoList->p_end(); return reversed; } void GNENet::mergeJunctions(GNEJunction* moved, GNEJunction* target, GNEUndoList* undoList) { undoList->p_begin("merge " + toString(SUMO_TAG_JUNCTION) + "s"); // place moved junction in the same position of target junction moved->setAttribute(SUMO_ATTR_POSITION, target->getAttribute(SUMO_ATTR_POSITION), undoList); // deleting edges changes in the underlying EdgeVector so we have to make a copy const EdgeVector incomingNBEdges = moved->getNBNode()->getIncomingEdges(); for (const auto& incomingNBEdge : incomingNBEdges) { // delete edges between the merged junctions GNEEdge* edge = myAttributeCarriers->getEdges().at(incomingNBEdge->getID()); if (edge->getParentJunctions().front() == target) { deleteEdge(edge, undoList, false); } else { undoList->p_add(new GNEChange_Attribute(edge, SUMO_ATTR_TO, target->getID())); } } // deleting edges changes in the underlying EdgeVector so we have to make a copy const EdgeVector outgoingNBEdges = moved->getNBNode()->getOutgoingEdges(); for (const auto& outgoingNBEdge : outgoingNBEdges) { // delete edges between the merged junctions GNEEdge* edge = myAttributeCarriers->getEdges().at(outgoingNBEdge->getID()); if (edge->getParentJunctions().back() == target) { deleteEdge(edge, undoList, false); } else { undoList->p_add(new GNEChange_Attribute(edge, SUMO_ATTR_FROM, target->getID())); } } // deleted moved junction deleteJunction(moved, undoList); undoList->p_end(); } void GNENet::selectRoundabout(GNEJunction* junction, GNEUndoList* undoList) { for (const EdgeSet& roundabout : myNetBuilder->getEdgeCont().getRoundabouts()) { for (NBEdge* edge : roundabout) { if (edge->getFromNode() == junction->getNBNode()) { undoList->p_begin("select roundabout"); for (NBEdge* roundaboutEdge : roundabout) { GNEEdge* e = retrieveEdge(roundaboutEdge->getID()); e->setAttribute(GNE_ATTR_SELECTED, "true", undoList); e->getParentJunctions().back()->setAttribute(GNE_ATTR_SELECTED, "true", undoList); } undoList->p_end(); return; } } } } void GNENet::createRoundabout(GNEJunction* junction, GNEUndoList* undoList) { undoList->p_begin("create roundabout"); junction->getNBNode()->updateSurroundingGeometry(); double radius = junction->getNBNode()->getRadius(); if (radius == NBNode::UNSPECIFIED_RADIUS) { radius = OptionsCont::getOptions().getFloat("default.junctions.radius"); } std::vector edges; // use clockwise sorting for (NBEdge* nbEdge : junction->getNBNode()->getEdges()) { edges.push_back(retrieveEdge(nbEdge->getID())); } const bool lefthand = OptionsCont::getOptions().getBool("lefthand"); const double lefthandSign = lefthand ? -1 : 1; std::vector newJunctions; GNEEdge* prevOpposite = nullptr; // split incoming/outgoing edges for (GNEEdge* edge : edges) { GNEJunction* newJunction = nullptr; if (edge == prevOpposite) { newJunction = newJunctions.back(); } //std::cout << " edge=" << edge->getID() << " prevOpposite=" << Named::getIDSecure(prevOpposite) << " newJunction=" << Named::getIDSecure(newJunction) << "\n"; prevOpposite = edge->getOppositeEdge(); const double geomLength = edge->getNBEdge()->getGeometry().length2D(); const double splitOffset = (edge->getParentJunctions().back() == junction ? MAX2(POSITION_EPS, geomLength - radius) : MIN2(geomLength - POSITION_EPS, radius)); Position pos = edge->getNBEdge()->getGeometry().positionAtOffset2D(splitOffset); newJunction = splitEdge(edge, pos, undoList, newJunction); if (newJunctions.empty() || newJunction != newJunctions.back()) { newJunctions.push_back(newJunction); } } Position center = junction->getPositionInView(); deleteJunction(junction, undoList); // create new edges to connect roundabout junctions (counter-clockwise) GNEEdge* tpl = myViewNet->getViewParent()->getInspectorFrame()->getTemplateEditor()->getEdgeTemplate(); const double resolution = OptionsCont::getOptions().getFloat("opendrive.curve-resolution") * 3; for (int i = 0; i < (int)newJunctions.size(); i++) { GNEJunction* from = newJunctions[(i + 1) % newJunctions.size()]; GNEJunction* to = newJunctions[i]; GNEEdge* newEdge = createEdge(from, to, tpl, undoList); const double angle1 = center.angleTo2D(from->getPositionInView()); const double angle2 = center.angleTo2D(to->getPositionInView()); // insert geometry points every resolution meters const double angleDiff = fabs(GeomHelper::angleDiff(angle2, angle1)); // circumference = 2 * M_PI * radius, angularFraction = angleDiff / 2 * M_PI int numSegments = MAX2(2, (int)ceil(angleDiff * radius / resolution)); PositionVector innerGeom; for (int j = 1; j < numSegments; j++) { const double angle = angle1 + lefthandSign * j * angleDiff / numSegments; innerGeom.push_back(center + Position(cos(angle) * radius, sin(angle) * radius)); } //std::cout << " newEdge=" << newEdge->getID() << " angle1=" << angle1 << " angle2=" << angle2 << " angleDiff=" << angleDiff // << " numSegments=" << numSegments << " innerGeom=" << innerGeom << "\n"; newEdge->setAttribute(SUMO_ATTR_SHAPE, toString(innerGeom), undoList); } undoList->p_end(); } bool GNENet::checkJunctionPosition(const Position& pos) { // Check that there isn't another junction in the same position as Pos for (auto i : myAttributeCarriers->getJunctions()) { if (i.second->getPositionInView() == pos) { return false; } } return true; } void GNENet::requireSaveNet(bool value) { if (myNetSaved == true) { WRITE_DEBUG("net has to be saved"); std::string additionalsSaved = (myAdditionalsSaved ? "saved" : "unsaved"); std::string demandElementsSaved = (myDemandElementsSaved ? "saved" : "unsaved"); std::string dataSetsSaved = (myDataElementsSaved ? "saved" : "unsaved"); WRITE_DEBUG("Current saving Status: net unsaved, additionals " + additionalsSaved + ", demand elements " + demandElementsSaved + ", data sets " + dataSetsSaved); } myNetSaved = !value; } bool GNENet::isNetSaved() const { return myNetSaved; } void GNENet::save(OptionsCont& oc) { // compute without volatile options and update network computeAndUpdate(oc, false); // write network NWFrame::writeNetwork(oc, *myNetBuilder); myNetSaved = true; } void GNENet::savePlain(OptionsCont& oc) { // compute without volatile options computeAndUpdate(oc, false); NWWriter_XML::writeNetwork(oc, *myNetBuilder); } void GNENet::saveJoined(OptionsCont& oc) { // compute without volatile options computeAndUpdate(oc, false); NWWriter_XML::writeJoinedJunctions(oc, myNetBuilder->getNodeCont()); } void GNENet::setViewNet(GNEViewNet* viewNet) { // set view net myViewNet = viewNet; // add default vTypes myAttributeCarriers->addDefaultVTypes(); // update geometry of all lanes (needed for dotted geometry) for (const auto& edge : myAttributeCarriers->getEdges()) { for (const auto& lane : edge.second->getLanes()) { lane->updateGeometry(); } } } GNEJunction* GNENet::retrieveJunction(const std::string& id, bool failHard) const { if (myAttributeCarriers->getJunctions().count(id)) { return myAttributeCarriers->getJunctions().at(id); } else if (failHard) { // If junction wasn't found, throw exception throw UnknownElement("Junction " + id); } else { return nullptr; } } GNEEdge* GNENet::retrieveEdge(const std::string& id, bool failHard) const { auto i = myAttributeCarriers->getEdges().find(id); // If edge was found if (i != myAttributeCarriers->getEdges().end()) { return i->second; } else if (failHard) { // If edge wasn't found, throw exception throw UnknownElement("Edge " + id); } else { return nullptr; } } GNEEdge* GNENet::retrieveEdge(GNEJunction* from, GNEJunction* to, bool failHard) const { if ((from != nullptr) && (to != nullptr)) { // iterate over Junctions of net for (const auto& edge : myAttributeCarriers->getEdges()) { if ((edge.second->getParentJunctions().front() == from) && (edge.second->getParentJunctions().back() == to)) { return edge.second; } } // if edge wasn't found, throw exception or return nullptr if (failHard) { throw UnknownElement("Edge with from='" + from->getID() + "' and to='" + to->getID() + "'"); } else { return nullptr; } } else { throw UnknownElement("Junctions cannot be nullptr"); } } GNEConnection* GNENet::retrieveConnection(const std::string& id, bool failHard) const { // iterate over junctions for (auto i : myAttributeCarriers->getJunctions()) { // iterate over connections for (auto j : i.second->getGNEConnections()) { if (j->getID() == id) { return j; } } } if (failHard) { // If POI wasn't found, throw exception throw UnknownElement("Connection " + id); } else { return nullptr; } } std::vector GNENet::retrieveConnections(bool onlySelected) const { std::vector result; // iterate over junctions for (auto i : myAttributeCarriers->getJunctions()) { // iterate over connections for (auto j : i.second->getGNEConnections()) { if (!onlySelected || j->isAttributeCarrierSelected()) { result.push_back(j); } } } return result; } GNECrossing* GNENet::retrieveCrossing(const std::string& id, bool failHard) const { // iterate over junctions for (auto i : myAttributeCarriers->getJunctions()) { // iterate over crossings for (auto j : i.second->getGNECrossings()) { if (j->getID() == id) { return j; } } } if (failHard) { // If POI wasn't found, throw exception throw UnknownElement("Crossing " + id); } else { return nullptr; } } std::vector GNENet::retrieveCrossings(bool onlySelected) const { std::vector result; // iterate over junctions for (auto i : myAttributeCarriers->getJunctions()) { // iterate over crossings for (auto j : i.second->getGNECrossings()) { if (!onlySelected || j->isAttributeCarrierSelected()) { result.push_back(j); } } } return result; } std::vector GNENet::retrieveEdges(bool onlySelected) { std::vector result; // returns edges depending of selection for (auto i : myAttributeCarriers->getEdges()) { if (!onlySelected || i.second->isAttributeCarrierSelected()) { result.push_back(i.second); } } return result; } std::vector GNENet::retrieveLanes(bool onlySelected) { std::vector result; // returns lanes depending of selection for (auto i : myAttributeCarriers->getEdges()) { for (auto j : i.second->getLanes()) { if (!onlySelected || j->isAttributeCarrierSelected()) { result.push_back(j); } } } return result; } GNELane* GNENet::retrieveLane(const std::string& id, bool failHard, bool checkVolatileChange) { const std::string edge_id = SUMOXMLDefinitions::getEdgeIDFromLane(id); GNEEdge* edge = retrieveEdge(edge_id, failHard); if (edge != nullptr) { GNELane* lane = nullptr; // search lane in lane's edges for (auto it : edge->getLanes()) { if (it->getID() == id) { lane = it; } } // throw exception or return nullptr if lane wasn't found if (lane == nullptr) { if (failHard) { // Throw exception if failHard is enabled throw UnknownElement(toString(SUMO_TAG_LANE) + " " + id); } } else { // check if the recomputing with volatile option has changed the number of lanes (needed for additionals and demand elements) if (checkVolatileChange && (myEdgesAndNumberOfLanes.count(edge_id) == 1) && myEdgesAndNumberOfLanes[edge_id] != (int)edge->getLanes().size()) { return edge->getLanes().at(lane->getIndex() + 1); } return lane; } } else if (failHard) { // Throw exception if failHard is enabled throw UnknownElement(toString(SUMO_TAG_EDGE) + " " + edge_id); } return nullptr; } std::vector GNENet::retrieveJunctions(bool onlySelected) { std::vector result; // returns junctions depending of selection for (auto i : myAttributeCarriers->getJunctions()) { if (!onlySelected || i.second->isAttributeCarrierSelected()) { result.push_back(i.second); } } return result; } std::vector GNENet::retrieveShapes(SumoXMLTag shapeTag, bool onlySelected) { std::vector result; // return all polys depending of onlySelected for (const auto& shape : myAttributeCarriers->getShapes().at(shapeTag)) { if (!onlySelected || shape.second->isAttributeCarrierSelected()) { result.push_back(shape.second); } } return result; } std::vector GNENet::retrieveShapes(bool onlySelected) { std::vector result; // return all polygons and POIs for (const auto& shapeTag : myAttributeCarriers->getShapes()) { for (const auto& shape : shapeTag.second) { if (!onlySelected || shape.second->isAttributeCarrierSelected()) { result.push_back(shape.second); } } } return result; } void GNENet::addGLObjectIntoGrid(GNEAttributeCarrier* AC) { // first check if given object has an associated GUIGlObject if (AC->getGUIGlObject()) { // check if object must be inserted in RTREE if (AC->getTagProperty().isPlacedInRTree()) { myGrid.addAdditionalGLObject(AC->getGUIGlObject()); } } } void GNENet::removeGLObjectFromGrid(GNEAttributeCarrier* AC) { // first check if given object has an associated GUIGlObject if (AC->getGUIGlObject()) { // check if object must be inserted in RTREE if (AC->getTagProperty().isPlacedInRTree()) { myGrid.removeAdditionalGLObject(AC->getGUIGlObject()); } } } GNEAttributeCarrier* GNENet::retrieveAttributeCarrier(const GUIGlID id, bool failHard) const { // obtain blocked GUIGlObject GUIGlObject* object = GUIGlObjectStorage::gIDStorage.getObjectBlocking(id); // Make sure that object exists if (object != nullptr) { // unblock and try to parse to AtributeCarrier GUIGlObjectStorage::gIDStorage.unblockObject(id); GNEAttributeCarrier* ac = dynamic_cast(object); // If was sucesfully parsed, return it if (ac == nullptr) { throw ProcessError("GUIGlObject does not match the declared type"); } else { return ac; } } else if (failHard) { throw ProcessError("Attempted to retrieve non-existant GUIGlObject"); } else { return nullptr; } } std::vector GNENet::retrieveAttributeCarriers(SumoXMLTag type) { std::vector result; if (type == SUMO_TAG_NOTHING) { // return all elements for (const auto& junction : myAttributeCarriers->getJunctions()) { result.push_back(junction.second); for (const auto& crossing : junction.second->getGNECrossings()) { result.push_back(crossing); } } for (const auto& edge : myAttributeCarriers->getEdges()) { result.push_back(edge.second); for (const auto& lane : edge.second->getLanes()) { result.push_back(lane); } for (const auto& connection : edge.second->getGNEConnections()) { result.push_back(connection); } } for (const auto& additionalSet : myAttributeCarriers->getAdditionals()) { for (const auto& additional : additionalSet.second) { result.push_back(additional.second); } } for (const auto& shapeSet : myAttributeCarriers->getShapes()) { for (const auto& shape : shapeSet.second) { result.push_back(shape.second); } } for (const auto& TAZSet : myAttributeCarriers->getTAZElements()) { for (const auto& TAZElement : TAZSet.second) { result.push_back(TAZElement.second); } } for (const auto& demandElementSet : myAttributeCarriers->getDemandElements()) { for (const auto& demandElement : demandElementSet.second) { result.push_back(demandElement.second); } } for (const auto& dataSet : myAttributeCarriers->getDataSets()) { result.push_back(dataSet.second); for (const auto& dataInterval : dataSet.second->getDataIntervalChildren()) { result.push_back(dataInterval.second); for (const auto& genericData : dataInterval.second->getGenericDataChildren()) { result.push_back(genericData); } } } } else if (GNEAttributeCarrier::getTagProperties(type).isAdditionalElement()) { // iterate over all additionals for (const auto& additionalTag : myAttributeCarriers->getAdditionals()) { for (const auto& additional : additionalTag.second) { if (additional.second->getTagProperty().getTag() == type) { result.push_back(additional.second); } else { // check additional children for (const auto& additionalChild : additional.second->getChildAdditionals()) { if (additionalChild->getTagProperty().getTag() == type) { result.push_back(additionalChild); } } } } } } else if (GNEAttributeCarrier::getTagProperties(type).isShape()) { // only returns shapes of a certain type. for (const auto& shape : myAttributeCarriers->getShapes().at(type)) { result.push_back(shape.second); } } else if (GNEAttributeCarrier::getTagProperties(type).isTAZElement()) { // only returns TAZ of a certain type. for (const auto& TAZElement : myAttributeCarriers->getTAZElements().at(type)) { result.push_back(TAZElement.second); } } else if (GNEAttributeCarrier::getTagProperties(type).isDemandElement()) { // only returns demand elements of a certain type. for (const auto& demandElemet : myAttributeCarriers->getDemandElements().at(type)) { result.push_back(demandElemet.second); } } else if (GNEAttributeCarrier::getTagProperties(type).isGenericData()) { for (const auto& dataSet : myAttributeCarriers->getDataSets()) { for (const auto& dataInterval : dataSet.second->getDataIntervalChildren()) { for (const auto& genericData : dataInterval.second->getGenericDataChildren()) { if (genericData->getTagProperty().getTag() == type) { result.push_back(genericData); } } } } } else { // return only a part of elements, depending of type switch (type) { case SUMO_TAG_JUNCTION: for (const auto& junction : myAttributeCarriers->getJunctions()) { result.push_back(junction.second); } break; case SUMO_TAG_EDGE: for (const auto& edge : myAttributeCarriers->getEdges()) { result.push_back(edge.second); } break; case SUMO_TAG_LANE: for (const auto& edge : myAttributeCarriers->getEdges()) { for (const auto& lane : edge.second->getLanes()) { result.push_back(lane); } } break; case SUMO_TAG_CONNECTION: for (const auto& edge : myAttributeCarriers->getEdges()) { for (const auto& connection : edge.second->getGNEConnections()) { result.push_back(connection); } } break; case SUMO_TAG_CROSSING: for (const auto& junction : myAttributeCarriers->getJunctions()) { for (const auto& crossing : junction.second->getGNECrossings()) { result.push_back(crossing); } } break; case SUMO_TAG_DATASET: for (const auto& dataSet : myAttributeCarriers->getDataSets()) { result.push_back(dataSet.second); } break; case SUMO_TAG_DATAINTERVAL: for (const auto& dataSet : myAttributeCarriers->getDataSets()) { for (const auto& dataInterval : dataSet.second->getDataIntervalChildren()) { result.push_back(dataInterval.second); } } break; default: // return nothing break; } } return result; } void GNENet::computeNetwork(GNEApplicationWindow* window, bool force, bool volatileOptions, std::string additionalPath, std::string demandPath, std::string dataPath) { if (!myNeedRecompute) { if (force) { if (volatileOptions) { window->setStatusBarText("Forced computing junctions with volatile options ..."); } else { window->setStatusBarText("Forced computing junctions ..."); } } else { return; } } else { if (volatileOptions) { window->setStatusBarText("Computing junctions with volatile options ..."); } else { window->setStatusBarText("Computing junctions ..."); } } // save current number of lanes for every edge if recomputing is with volatile options if (volatileOptions) { for (auto it : myAttributeCarriers->getEdges()) { myEdgesAndNumberOfLanes[it.second->getID()] = (int)it.second->getLanes().size(); } } // compute and update OptionsCont& oc = OptionsCont::getOptions(); computeAndUpdate(oc, volatileOptions); // load additionals if was recomputed with volatile options if (additionalPath != "") { // Create additional handler GNEAdditionalHandler additionalHandler(additionalPath, this); // Run parser if (!XMLSubSys::runParser(additionalHandler, additionalPath, false)) { WRITE_MESSAGE("Loading of " + additionalPath + " failed."); } // clear myEdgesAndNumberOfLanes after reload additionals myEdgesAndNumberOfLanes.clear(); } // load demand elements if was recomputed with volatile options if (demandPath != "") { // Create demandElement handler GNERouteHandler demandElementHandler(demandPath, this, false); // Run parser if (!XMLSubSys::runParser(demandElementHandler, demandPath, false)) { WRITE_MESSAGE("Loading of " + demandPath + " failed."); } // clear myEdgesAndNumberOfLanes after reload demandElements myEdgesAndNumberOfLanes.clear(); } UNUSED_PARAMETER(dataPath); window->getApp()->endWaitCursor(); window->setStatusBarText("Finished computing junctions."); } void GNENet::computeDemandElements(GNEApplicationWindow* window) { window->setStatusBarText("Computing demand elements ..."); // if we aren't in Demand mode, update path calculator if (!myViewNet->getEditModes().isCurrentSupermodeDemand()) { myPathCalculator->updatePathCalculator(); } // iterate over all demand elements and compute for (const auto& i : myAttributeCarriers->getDemandElements()) { for (const auto& j : i.second) { j.second->computePath(); } } window->setStatusBarText("Finished computing demand elements."); } void GNENet::computeDataElements(GNEApplicationWindow* window) { window->setStatusBarText("Computing data elements ..."); /* // iterate over all demand elements and compute for (const auto& i : myAttributeCarriers->getDemandElements()) { for (const auto& j : i.second) { j.second->computePath(); } } */ window->setStatusBarText("Finished computing data elements."); } void GNENet::computeJunction(GNEJunction* junction) { // recompute tl-logics OptionsCont& oc = OptionsCont::getOptions(); NBTrafficLightLogicCont& tllCont = getTLLogicCont(); // iterate over traffic lights definitions. Make a copy because invalid // definitions will be removed (and would otherwise destroy the iterator) const std::set tlsDefs = junction->getNBNode()->getControllingTLS(); for (auto it : tlsDefs) { it->setParticipantsInformation(); it->setTLControllingInformation(); tllCont.computeSingleLogic(oc, it); } // @todo compute connections etc... } void GNENet::requireRecompute() { myNeedRecompute = true; } bool GNENet::isNetRecomputed() const { return (myNeedRecompute == false); } bool GNENet::netHasGNECrossings() const { for (auto n : myAttributeCarriers->getJunctions()) { if (n.second->getGNECrossings().size() > 0) { return true; } } return false; } FXApp* GNENet::getApp() { return myViewNet->getApp(); } NBNetBuilder* GNENet::getNetBuilder() const { return myNetBuilder; } bool GNENet::joinSelectedJunctions(GNEUndoList* undoList) { std::vector selectedJunctions = retrieveJunctions(true); if (selectedJunctions.size() < 2) { return false; } EdgeVector allIncoming; EdgeVector allOutgoing; std::set cluster; for (auto it : selectedJunctions) { cluster.insert(it->getNBNode()); const EdgeVector& incoming = it->getNBNode()->getIncomingEdges(); allIncoming.insert(allIncoming.end(), incoming.begin(), incoming.end()); const EdgeVector& outgoing = it->getNBNode()->getOutgoingEdges(); allOutgoing.insert(allOutgoing.end(), outgoing.begin(), outgoing.end()); } // create new junction Position pos; Position oldPos; bool setTL; std::string id = "cluster"; TrafficLightType type; SumoXMLNodeType nodeType = SumoXMLNodeType::UNKNOWN; myNetBuilder->getNodeCont().analyzeCluster(cluster, id, pos, setTL, type, nodeType); // save position oldPos = pos; // Check that there isn't another junction in the same position as Pos but doesn't belong to cluster for (auto i : myAttributeCarriers->getJunctions()) { if ((i.second->getPositionInView() == pos) && (cluster.find(i.second->getNBNode()) == cluster.end())) { // show warning in gui testing debug mode WRITE_DEBUG("Opening FXMessageBox 'Join non-selected junction'"); // Ask confirmation to user FXuint answer = FXMessageBox::question(getApp(), MBOX_YES_NO, ("Position of joined " + toString(SUMO_TAG_JUNCTION)).c_str(), "%s", ("There is another unselected " + toString(SUMO_TAG_JUNCTION) + " in the same position of joined " + toString(SUMO_TAG_JUNCTION) + + ".\nIt will be joined with the other selected " + toString(SUMO_TAG_JUNCTION) + "s. Continue?").c_str()); if (answer != 1) { // 1:yes, 2:no, 4:esc // write warning if netedit is running in testing mode if (answer == 2) { WRITE_DEBUG("Closed FXMessageBox 'Join non-selected junction' with 'No'"); } else if (answer == 4) { WRITE_DEBUG("Closed FXMessageBox 'Join non-selected junction' with 'ESC'"); } return false; } else { // write warning if netedit is running in testing mode WRITE_DEBUG("Closed FXMessageBox 'Join non-selected junction' with 'Yes'"); // select conflicted junction an join all again i.second->setAttribute(GNE_ATTR_SELECTED, "true", undoList); return joinSelectedJunctions(undoList); } } } // use checkJunctionPosition to avoid conflicts with junction in the same position as others while (checkJunctionPosition(pos) == false) { pos.setx(pos.x() + 0.1); pos.sety(pos.y() + 0.1); } // start with the join selected junctions undoList->p_begin("Join selected " + toString(SUMO_TAG_JUNCTION) + "s"); GNEJunction* joined = createJunction(pos, undoList); joined->setAttribute(SUMO_ATTR_TYPE, toString(nodeType), undoList); // i.e. rail crossing if (setTL) { joined->setAttribute(SUMO_ATTR_TLTYPE, toString(type), undoList); } // #3128 this is not undone when calling 'undo' myNetBuilder->getNodeCont().registerJoinedCluster(cluster); // first remove all crossing of the involved junctions and edges // (otherwise edge removal will trigger discarding) std::vector oldCrossings; for (auto i : selectedJunctions) { while (i->getGNECrossings().size() > 0) { GNECrossing* crossing = i->getGNECrossings().front(); oldCrossings.push_back(*crossing->getNBCrossing()); deleteCrossing(crossing, undoList); } } // preserve old connections for (auto it : selectedJunctions) { it->setLogicValid(false, undoList); } // remap edges for (auto it : allIncoming) { undoList->p_add(new GNEChange_Attribute(myAttributeCarriers->getEdges().at(it->getID()), SUMO_ATTR_TO, joined->getID())); } EdgeSet edgesWithin; for (auto it : allOutgoing) { // delete edges within the cluster GNEEdge* edge = myAttributeCarriers->getEdges().at(it->getID()); if (edge->getParentJunctions().back() == joined) { edgesWithin.insert(it); deleteEdge(edge, undoList, false); } else { undoList->p_add(new GNEChange_Attribute(myAttributeCarriers->getEdges().at(it->getID()), SUMO_ATTR_FROM, joined->getID())); } } // remap all crossing of the involved junctions and edges for (auto nbc : oldCrossings) { bool keep = true; for (NBEdge* e : nbc.edges) { if (edgesWithin.count(e) != 0) { keep = false; break; } }; if (keep) { undoList->add(new GNEChange_Crossing(joined, nbc.edges, nbc.width, nbc.priority || joined->getNBNode()->isTLControlled(), nbc.customTLIndex, nbc.customTLIndex2, nbc.customShape, false, true), true); } } // delete original junctions for (auto it : selectedJunctions) { deleteJunction(it, undoList); } joined->setAttribute(SUMO_ATTR_ID, id, undoList); // check if joined junction had to change their original position to avoid errors if (pos != oldPos) { joined->setAttribute(SUMO_ATTR_POSITION, toString(oldPos), undoList); } undoList->p_end(); return true; } bool GNENet::cleanInvalidCrossings(GNEUndoList* undoList) { // obtain current net's crossings std::vector myNetCrossings; for (auto it : myAttributeCarriers->getJunctions()) { myNetCrossings.reserve(myNetCrossings.size() + it.second->getGNECrossings().size()); myNetCrossings.insert(myNetCrossings.end(), it.second->getGNECrossings().begin(), it.second->getGNECrossings().end()); } // obtain invalid crossigns std::vector myInvalidCrossings; for (auto i = myNetCrossings.begin(); i != myNetCrossings.end(); i++) { if ((*i)->getNBCrossing()->valid == false) { myInvalidCrossings.push_back(*i); } } if (myInvalidCrossings.empty()) { // show warning in gui testing debug mode WRITE_DEBUG("Opening FXMessageBox 'No crossing to remove'"); // open a dialog informing that there isn't crossing to remove FXMessageBox::warning(getApp(), MBOX_OK, ("Clear " + toString(SUMO_TAG_CROSSING) + "s").c_str(), "%s", ("There is no invalid " + toString(SUMO_TAG_CROSSING) + "s to remove").c_str()); // show warning in gui testing debug mode WRITE_DEBUG("Closed FXMessageBox 'No crossing to remove' with 'OK'"); } else { std::string plural = myInvalidCrossings.size() == 1 ? ("") : ("s"); // show warning in gui testing debug mode WRITE_DEBUG("Opening FXMessageBox 'clear crossings'"); // Ask confirmation to user FXuint answer = FXMessageBox::question(getApp(), MBOX_YES_NO, ("Clear " + toString(SUMO_TAG_CROSSING) + "s").c_str(), "%s", ("Clear " + toString(SUMO_TAG_CROSSING) + plural + " will be removed. Continue?").c_str()); if (answer != 1) { // 1:yes, 2:no, 4:esc // write warning if netedit is running in testing mode if (answer == 2) { WRITE_DEBUG("Closed FXMessageBox 'clear crossings' with 'No'"); } else if (answer == 4) { WRITE_DEBUG("Closed FXMessageBox 'clear crossings' with 'ESC'"); } } else { undoList->p_begin("Clean " + toString(SUMO_TAG_CROSSING) + "s"); for (auto i = myInvalidCrossings.begin(); i != myInvalidCrossings.end(); i++) { deleteCrossing((*i), undoList); } undoList->p_end(); } } return 1; } void GNENet::removeSolitaryJunctions(GNEUndoList* undoList) { undoList->p_begin("Clean " + toString(SUMO_TAG_JUNCTION) + "s"); std::vector toRemove; for (auto it : myAttributeCarriers->getJunctions()) { GNEJunction* junction = it.second; if (junction->getNBNode()->getEdges().size() == 0) { toRemove.push_back(junction); } } for (auto it : toRemove) { deleteJunction(it, undoList); } undoList->p_end(); } void GNENet::cleanUnusedRoutes(GNEUndoList* undoList) { // first declare a vector to save all routes without children std::vector routesWithoutChildren; routesWithoutChildren.reserve(myAttributeCarriers->getDemandElements().at(SUMO_TAG_ROUTE).size()); // iterate over routes for (const auto& i : myAttributeCarriers->getDemandElements().at(SUMO_TAG_ROUTE)) { if (i.second->getChildDemandElements().empty()) { routesWithoutChildren.push_back(i.second); } } // finally remove all routesWithoutChildren if (routesWithoutChildren.size() > 0) { // begin undo list undoList->p_begin("clean unused routes"); // iterate over routesWithoutChildren for (const auto& i : routesWithoutChildren) { // due route doesn't have children, simply call GNEChange_DemandElement undoList->add(new GNEChange_DemandElement(i, false), true); } // end undo list undoList->p_end(); } } void GNENet::joinRoutes(GNEUndoList* undoList) { // first declare a sorted set of sorted route's edges in string format std::set > mySortedRoutes; // iterate over routes and save it in mySortedRoutes (only if it doesn't have Stop Children) for (const auto& i : myAttributeCarriers->getDemandElements().at(SUMO_TAG_ROUTE)) { // first check route has stops bool hasStops = false; for (const auto& j : i.second->getChildDemandElements()) { if (j->getTagProperty().isStop()) { hasStops = true; } } if (!hasStops) { mySortedRoutes.insert(std::make_pair(GNEAttributeCarrier::parseIDs(i.second->getParentEdges()), i.second)); } } // now declare a matrix in which organice routes to be merged std::vector > routesToMerge; auto index = mySortedRoutes.begin(); // iterate over mySortedRoutes for (auto i = mySortedRoutes.begin(); i != mySortedRoutes.end(); i++) { if (routesToMerge.empty()) { routesToMerge.push_back({i->second}); } else { if (index->first == i->first) { routesToMerge.back().push_back(i->second); } else { routesToMerge.push_back({i->second}); index = i; } } } // now check if there is routes to merge bool thereIsRoutesToMerge = false; for (const auto& i : routesToMerge) { if (i.size() > 1) { thereIsRoutesToMerge = true; } } // if exist if (thereIsRoutesToMerge) { // begin undo list undoList->p_begin("merge routes"); // iterate over route to edges for (const auto& i : routesToMerge) { if (i.size() > 1) { // iterate over duplicated routes for (int j = 1; j < (int)i.size(); j++) { // move all vehicles of every duplicated route while (i.at(j)->getChildDemandElements().size() > 0) { i.at(j)->getChildDemandElements().front()->setAttribute(SUMO_ATTR_ROUTE, i.at(0)->getID(), undoList); } // finally remove route undoList->add(new GNEChange_DemandElement(i.at(j), false), true); } } } // end undo list undoList->p_end(); } } void GNENet::cleanInvalidDemandElements(GNEUndoList* undoList) { // first declare a vector to save all invalid demand elements std::vector invalidDemandElements; invalidDemandElements.reserve(myAttributeCarriers->getDemandElements().at(SUMO_TAG_ROUTE).size() + myAttributeCarriers->getDemandElements().at(SUMO_TAG_FLOW).size() + myAttributeCarriers->getDemandElements().at(SUMO_TAG_TRIP).size()); // iterate over routes for (const auto& i : myAttributeCarriers->getDemandElements().at(SUMO_TAG_ROUTE)) { if (!i.second->isDemandElementValid()) { invalidDemandElements.push_back(i.second); } } // iterate over flows for (const auto& i : myAttributeCarriers->getDemandElements().at(SUMO_TAG_FLOW)) { if (!i.second->isDemandElementValid()) { invalidDemandElements.push_back(i.second); } } // iterate over trip for (const auto& i : myAttributeCarriers->getDemandElements().at(SUMO_TAG_TRIP)) { if (!i.second->isDemandElementValid()) { invalidDemandElements.push_back(i.second); } } // continue if there is invalidDemandElements to remove if (invalidDemandElements.size() > 0) { // begin undo list undoList->p_begin("remove invalid demand elements"); // iterate over invalidDemandElements for (const auto& i : invalidDemandElements) { // simply call GNEChange_DemandElement undoList->add(new GNEChange_DemandElement(i, false), true); } // end undo list undoList->p_end(); } } void GNENet::replaceJunctionByGeometry(GNEJunction* junction, GNEUndoList* undoList) { if (junction->getNBNode()->checkIsRemovable()) { // start operation undoList->p_begin("Replace junction by geometry"); // obtain Edges to join std::vector > toJoin = junction->getNBNode()->getEdgesToJoin(); // clear connections of junction to replace clearJunctionConnections(junction, undoList); // iterate over NBEdges to join for (auto j : toJoin) { // obtain GNEEdges GNEEdge* begin = myAttributeCarriers->getEdges().at(j.first->getID()); GNEEdge* continuation = myAttributeCarriers->getEdges().at(j.second->getID()); // remove connections between the edges std::vector connections = begin->getNBEdge()->getConnections(); for (auto con : connections) { undoList->add(new GNEChange_Connection(begin, con, false, false), true); } // fix shape of replaced edge PositionVector newShape = begin->getNBEdge()->getInnerGeometry(); if (begin->getNBEdge()->hasDefaultGeometryEndpointAtNode(begin->getNBEdge()->getToNode())) { newShape.push_back(junction->getNBNode()->getPosition()); } else { newShape.push_back(begin->getNBEdge()->getGeometry()[-1]); } if (continuation->getNBEdge()->hasDefaultGeometryEndpointAtNode(begin->getNBEdge()->getToNode())) { newShape.push_back_noDoublePos(junction->getNBNode()->getPosition()); } else { newShape.push_back_noDoublePos(continuation->getNBEdge()->getGeometry()[0]); } // replace incoming edge replaceIncomingEdge(continuation, begin, undoList); newShape.append(continuation->getNBEdge()->getInnerGeometry()); begin->setAttribute(GNE_ATTR_SHAPE_END, continuation->getAttribute(GNE_ATTR_SHAPE_END), undoList); begin->setAttribute(SUMO_ATTR_ENDOFFSET, continuation->getAttribute(SUMO_ATTR_ENDOFFSET), undoList); begin->setAttribute(SUMO_ATTR_SHAPE, toString(newShape), undoList); begin->getNBEdge()->resetNodeBorder(begin->getNBEdge()->getToNode()); } //delete replaced junction deleteJunction(junction, undoList); // finish operation undoList->p_end(); } else { throw ProcessError("Junction isn't removable"); } } void GNENet::splitJunction(GNEJunction* junction, bool reconnect, GNEUndoList* undoList) { std::vector > endpoints = junction->getNBNode()->getEndPoints(); if (endpoints.size() < 2) { return; } // start operation undoList->p_begin("Split junction"); // record connections std::map> straightConnections; for (GNEEdge* e : junction->getGNEIncomingEdges()) { for (const auto& c : e->getNBEdge()->getConnections()) { if (c.fromLane >= 0 && junction->getNBNode()->getDirection(e->getNBEdge(), c.toEdge) == LinkDirection::STRAIGHT) { straightConnections[e].push_back(c); } }; } //std::cout << "split junction at endpoints:\n"; junction->setLogicValid(false, undoList); for (const auto& pair : endpoints) { const Position& pos = pair.first; const std::string& origID = pair.second; GNEJunction* newJunction = createJunction(pos, undoList); std::string newID = origID != "" ? origID : newJunction->getID(); // make a copy because the original vectors are modified during iteration const std::vector incoming = junction->getGNEIncomingEdges(); const std::vector outgoing = junction->getGNEOutgoingEdges(); //std::cout << " checkEndpoint " << pair.first << " " << pair.second << " newID=" << newID << "\n"; for (GNEEdge* e : incoming) { //std::cout << " incoming " << e->getID() << " pos=" << pos << " origTo=" << e->getNBEdge()->getParameter("origTo") << " newID=" << newID << "\n"; if (e->getNBEdge()->getGeometry().back().almostSame(pos) || e->getNBEdge()->getParameter("origTo") == newID) { //std::cout << " match\n"; undoList->p_add(new GNEChange_Attribute(e, SUMO_ATTR_TO, newJunction->getID())); } } for (GNEEdge* e : outgoing) { //std::cout << " outgoing " << e->getID() << " pos=" << pos << " origFrom=" << e->getNBEdge()->getParameter("origFrom") << " newID=" << newID << "\n"; if (e->getNBEdge()->getGeometry().front().almostSame(pos) || e->getNBEdge()->getParameter("origFrom") == newID) { //std::cout << " match\n"; undoList->p_add(new GNEChange_Attribute(e, SUMO_ATTR_FROM, newJunction->getID())); } } if (newID != newJunction->getID()) { if (newJunction->isValid(SUMO_ATTR_ID, newID)) { undoList->p_add(new GNEChange_Attribute(newJunction, SUMO_ATTR_ID, newID)); } else { WRITE_WARNING("Could not rename split node to '" + newID + "'"); } } } // recreate edges from straightConnections if (reconnect) { for (const auto& item : straightConnections) { GNEEdge* in = item.first; std::map newEdges; for (auto& c : item.second) { GNEEdge* out = retrieveEdge(c.toEdge->getID()); GNEEdge* newEdge = nullptr; if (in->getParentJunctions().back() == out->getParentJunctions().front()) { continue; } if (newEdges.count(c.toEdge) == 0) { newEdge = createEdge(in->getParentJunctions().back(), out->getParentJunctions().front(), in, undoList); newEdges[c.toEdge] = newEdge; newEdge->setAttribute(SUMO_ATTR_NUMLANES, "1", undoList); } else { newEdge = newEdges[c.toEdge]; duplicateLane(newEdge->getLanes().back(), undoList, true); } // copy permissions newEdge->getLanes().back()->setAttribute(SUMO_ATTR_ALLOW, in->getLanes()[c.fromLane]-> getAttribute(SUMO_ATTR_ALLOW), undoList); } } } deleteJunction(junction, undoList); // finish operation undoList->p_end(); } void GNENet::clearJunctionConnections(GNEJunction* junction, GNEUndoList* undoList) { undoList->p_begin("clear junction connections"); std::vector connections = junction->getGNEConnections(); // Iterate over all connections and clear it for (auto i : connections) { deleteConnection(i, undoList); } undoList->p_end(); } void GNENet::resetJunctionConnections(GNEJunction* junction, GNEUndoList* undoList) { undoList->p_begin("reset junction connections"); // first clear connections clearJunctionConnections(junction, undoList); // invalidate logic to create new connections in the next recomputing junction->setLogicValid(false, undoList); undoList->p_end(); } void GNENet::changeEdgeEndpoints(GNEEdge* edge, const std::string& newSource, const std::string& newDest) { NBNode* from = retrieveJunction(newSource)->getNBNode(); NBNode* to = retrieveJunction(newDest)->getNBNode(); edge->getNBEdge()->reinitNodes(from, to); requireRecompute(); } GNEViewNet* GNENet::getViewNet() const { return myViewNet; } std::vector GNENet::getSelectedAttributeCarriers(bool ignoreCurrentSupermode) { // declare vector to save result std::vector result; result.reserve(gSelected.getSelected().size()); // iterate over all elements of global selection for (const auto& glID : gSelected.getSelected()) { // obtain AC GNEAttributeCarrier* AC = retrieveAttributeCarrier(glID, false); // check if attribute carrier exist and is selected if (AC && AC->isAttributeCarrierSelected()) { bool insert = false; if (ignoreCurrentSupermode) { insert = true; } else if (myViewNet->getEditModes().isCurrentSupermodeNetwork() && (AC->getTagProperty().isNetworkElement() || AC->getTagProperty().isAdditionalElement() || AC->getTagProperty().isShape() || AC->getTagProperty().isTAZElement())) { insert = true; } else if (myViewNet->getEditModes().isCurrentSupermodeDemand() && AC->getTagProperty().isDemandElement()) { insert = true; } else if (myViewNet->getEditModes().isCurrentSupermodeData() && AC->getTagProperty().isDataElement()) { insert = true; } if (insert) { result.push_back(AC); } } } return result; } NBTrafficLightLogicCont& GNENet::getTLLogicCont() { return myNetBuilder->getTLLogicCont(); } NBEdgeCont& GNENet::getEdgeCont() { return myNetBuilder->getEdgeCont(); } void GNENet::addExplicitTurnaround(std::string id) { myExplicitTurnarounds.insert(id); } void GNENet::removeExplicitTurnaround(std::string id) { myExplicitTurnarounds.erase(id); } GNEAdditional* GNENet::retrieveAdditional(SumoXMLTag type, const std::string& id, bool hardFail) const { if ((myAttributeCarriers->getAdditionals().count(type) > 0) && (myAttributeCarriers->getAdditionals().at(type).count(id) != 0)) { return myAttributeCarriers->getAdditionals().at(type).at(id); } else if (hardFail) { throw ProcessError("Attempted to retrieve non-existant additional"); } else { return nullptr; } } std::vector GNENet::retrieveAdditionals(bool onlySelected) const { std::vector result; // returns additionals depending of selection for (const auto& additionalTag : myAttributeCarriers->getAdditionals()) { for (const auto& additional : additionalTag.second) { if (!onlySelected || additional.second->isAttributeCarrierSelected()) { result.push_back(additional.second); } // iterate over children for (const auto& additionalChild : additional.second->getChildAdditionals()) { if (!onlySelected || additionalChild->isAttributeCarrierSelected()) { result.push_back(additionalChild); } } } } return result; } int GNENet::getNumberOfAdditionals(SumoXMLTag type) const { int counter = 0; for (auto i : myAttributeCarriers->getAdditionals()) { if ((type == SUMO_TAG_NOTHING) || (type == i.first)) { counter += (int)i.second.size(); } } return counter; } void GNENet::requireSaveAdditionals(bool value) { if (myAdditionalsSaved) { WRITE_DEBUG("Additionals has to be saved"); std::string netSaved = (myNetSaved ? "saved" : "unsaved"); std::string demandElementsSaved = (myDemandElementsSaved ? "saved" : "unsaved"); std::string dataSetSaved = (myDataElementsSaved ? "saved" : "unsaved"); WRITE_DEBUG("Current saving Status: net " + netSaved + ", additionals unsaved, demand elements " + demandElementsSaved + ", data sets " + dataSetSaved); } myAdditionalsSaved = !value; if (myViewNet != nullptr) { if (myAdditionalsSaved) { myViewNet->getViewParent()->getGNEAppWindows()->disableSaveAdditionalsMenu(); } else { myViewNet->getViewParent()->getGNEAppWindows()->enableSaveAdditionalsMenu(); } } } void GNENet::saveAdditionals(const std::string& filename) { // obtain invalid additionals depending of number of their parent lanes std::vector invalidSingleLaneAdditionals; std::vector invalidMultiLaneAdditionals; // iterate over additionals and obtain invalids for (const auto& additionalPair : myAttributeCarriers->getAdditionals()) { for (const auto& addditional : additionalPair.second) { // check if has to be fixed if (addditional.second->getTagProperty().hasAttribute(SUMO_ATTR_LANE) && !addditional.second->isAdditionalValid()) { invalidSingleLaneAdditionals.push_back(addditional.second); } else if (addditional.second->getTagProperty().hasAttribute(SUMO_ATTR_LANES) && !addditional.second->isAdditionalValid()) { invalidMultiLaneAdditionals.push_back(addditional.second); } } } // if there are invalid StoppingPlaces or detectors, open GNEFixAdditionalElements if (invalidSingleLaneAdditionals.size() > 0 || invalidMultiLaneAdditionals.size() > 0) { // 0 -> Canceled Saving, with or whithout selecting invalid stopping places and E2 // 1 -> Invalid stoppingPlaces and E2 fixed, friendlyPos enabled, or saved with invalid positions GNEFixAdditionalElements fixAdditionalElementsDialog(myViewNet, invalidSingleLaneAdditionals, invalidMultiLaneAdditionals); if (fixAdditionalElementsDialog.execute() == 0) { // show debug information WRITE_DEBUG("Additionals saving aborted"); } else { saveAdditionalsConfirmed(filename); // change value of flag myAdditionalsSaved = true; // show debug information WRITE_DEBUG("Additionals saved after dialog"); } // update view myViewNet->updateViewNet(); // set focus again in net myViewNet->setFocus(); } else { saveAdditionalsConfirmed(filename); // change value of flag myAdditionalsSaved = true; // show debug information WRITE_DEBUG("Additionals saved"); } } bool GNENet::isAdditionalsSaved() const { return myAdditionalsSaved; } std::string GNENet::generateAdditionalID(SumoXMLTag type) const { int counter = 0; while (myAttributeCarriers->getAdditionals().at(type).count(toString(type) + "_" + toString(counter)) != 0) { counter++; } return (toString(type) + "_" + toString(counter)); } GNEDemandElement* GNENet::retrieveDemandElement(SumoXMLTag type, const std::string& id, bool hardFail) const { if ((myAttributeCarriers->getDemandElements().count(type) > 0) && (myAttributeCarriers->getDemandElements().at(type).count(id) != 0)) { return myAttributeCarriers->getDemandElements().at(type).at(id); } else if (hardFail) { throw ProcessError("Attempted to retrieve non-existant demand element"); } else { return nullptr; } } std::vector GNENet::retrieveDemandElements(bool onlySelected) const { std::vector result; // returns demand elements depending of selection for (auto i : myAttributeCarriers->getDemandElements()) { for (auto j : i.second) { if (!onlySelected || j.second->isAttributeCarrierSelected()) { result.push_back(j.second); } } } return result; } int GNENet::getNumberOfDemandElements(SumoXMLTag type) const { int counter = 0; for (auto i : myAttributeCarriers->getDemandElements()) { if ((type == SUMO_TAG_NOTHING) || (type == i.first)) { counter += (int)i.second.size(); } } return counter; } void GNENet::requireSaveDemandElements(bool value) { if (myDemandElementsSaved == true) { WRITE_DEBUG("DemandElements has to be saved"); std::string netSaved = (myNetSaved ? "saved" : "unsaved"); std::string additionalsSaved = (myAdditionalsSaved ? "saved" : "unsaved"); std::string dataSetsSaved = (myDemandElementsSaved ? "saved" : "unsaved"); WRITE_DEBUG("Current saving Status: net " + netSaved + ", additionals " + additionalsSaved + ", demand elements unsaved, data sets " + dataSetsSaved); } myDemandElementsSaved = !value; if (myViewNet != nullptr) { if (myDemandElementsSaved) { myViewNet->getViewParent()->getGNEAppWindows()->disableSaveDemandElementsMenu(); } else { myViewNet->getViewParent()->getGNEAppWindows()->enableSaveDemandElementsMenu(); } } } void GNENet::saveDemandElements(const std::string& filename) { // first recompute demand elements computeDemandElements(myViewNet->getViewParent()->getGNEAppWindows()); // obtain invalid demandElements depending of number of their parent lanes std::vector invalidSingleLaneDemandElements; // iterate over demandElements and obtain invalids for (const auto& demandElementSet : myAttributeCarriers->getDemandElements()) { for (const auto& demandElement : demandElementSet.second) { // compute before check if demand element is valid demandElement.second->computePath(); // check if has to be fixed if (!demandElement.second->isDemandElementValid()) { invalidSingleLaneDemandElements.push_back(demandElement.second); } } } // if there are invalid demand elements, open GNEFixDemandElements if (invalidSingleLaneDemandElements.size() > 0) { // 0 -> Canceled Saving, with or whithout selecting invalid demand elements // 1 -> Invalid demand elements fixed, friendlyPos enabled, or saved with invalid positions GNEFixDemandElements fixDemandElementsDialog(myViewNet, invalidSingleLaneDemandElements); if (fixDemandElementsDialog.execute() == 0) { // show debug information WRITE_DEBUG("demand elements saving aborted"); } else { saveDemandElementsConfirmed(filename); // change value of flag myDemandElementsSaved = true; // show debug information WRITE_DEBUG("demand elements saved after dialog"); } // update view myViewNet->updateViewNet(); // set focus again in net myViewNet->setFocus(); } else { saveDemandElementsConfirmed(filename); // change value of flag myDemandElementsSaved = true; // show debug information WRITE_DEBUG("demand elements saved"); } } bool GNENet::isDemandElementsSaved() const { return myDemandElementsSaved; } std::string GNENet::generateDemandElementID(SumoXMLTag tag) const { // get references to vehicle maps const std::map& vehicles = myAttributeCarriers->getDemandElements().at(SUMO_TAG_VEHICLE); const std::map& trips = myAttributeCarriers->getDemandElements().at(SUMO_TAG_TRIP); const std::map& vehiclesEmbebbed = myAttributeCarriers->getDemandElements().at(GNE_TAG_VEHICLE_WITHROUTE); const std::map& routeFlows = myAttributeCarriers->getDemandElements().at(GNE_TAG_FLOW_ROUTE); const std::map& flows = myAttributeCarriers->getDemandElements().at(SUMO_TAG_FLOW); const std::map& flowsEmbebbed = myAttributeCarriers->getDemandElements().at(GNE_TAG_FLOW_WITHROUTE); // get references to persons maps const std::map& persons = myAttributeCarriers->getDemandElements().at(SUMO_TAG_PERSON); const std::map& personFlows = myAttributeCarriers->getDemandElements().at(SUMO_TAG_PERSONFLOW); // declare flags const bool isVehicle = ((tag == SUMO_TAG_VEHICLE) || (tag == SUMO_TAG_TRIP) || (tag == GNE_TAG_VEHICLE_WITHROUTE)); const bool isFlow = ((tag == GNE_TAG_FLOW_ROUTE) || (tag == SUMO_TAG_FLOW) || (tag == GNE_TAG_FLOW_WITHROUTE)); const bool isPerson = ((tag == SUMO_TAG_PERSON) || (tag == SUMO_TAG_PERSONFLOW)); // declare counter int counter = 0; if (isVehicle || isFlow) { // declare tag const std::string tagStr = isVehicle ? toString(SUMO_TAG_VEHICLE) : toString(SUMO_TAG_FLOW); // special case for vehicles (Vehicles, Flows, Trips and routeFlows share nameSpaces) while ((vehicles.count(tagStr + "_" + toString(counter)) != 0) || (trips.count(tagStr + "_" + toString(counter)) != 0) || (vehiclesEmbebbed.count(tagStr + "_" + toString(counter)) != 0) || (routeFlows.count(tagStr + "_" + toString(counter)) != 0) || (flows.count(tagStr + "_" + toString(counter)) != 0) || (flowsEmbebbed.count(tagStr + "_" + toString(counter)) != 0) || (vehicles.count(tagStr + "_" + toString(counter)) != 0)) { counter++; } // return new vehicle ID return (tagStr + "_" + toString(counter)); } else if (isPerson) { // special case for persons (person and personFlows share nameSpaces) while ((persons.count(toString(tag) + "_" + toString(counter)) != 0) || (personFlows.count(toString(tag) + "_" + toString(counter)) != 0)) { counter++; } // return new person ID return (toString(tag) + "_" + toString(counter)); } else { while (myAttributeCarriers->getDemandElements().at(tag).count(toString(tag) + "_" + toString(counter)) != 0) { counter++; } // return new element ID return (toString(tag) + "_" + toString(counter)); } } GNEDataSet* GNENet::retrieveDataSet(const std::string& id, bool hardFail) const { if (myAttributeCarriers->getDataSets().count(id) > 0) { return myAttributeCarriers->getDataSets().at(id); } else if (hardFail) { throw ProcessError("Attempted to retrieve non-existant data set"); } else { return nullptr; } } std::vector GNENet::retrieveDataSets() const { std::vector result; result.reserve(myAttributeCarriers->getDataSets().size()); // returns data sets for (const auto& dataSet : myAttributeCarriers->getDataSets()) { result.push_back(dataSet.second); } return result; } std::vector GNENet::retrieveGenericDatas(bool onlySelected) const { std::vector result; size_t numGenericDatas = 0; // first reserve for (const auto& dataSet : myAttributeCarriers->getDataSets()) { for (const auto& dataInterval : dataSet.second->getDataIntervalChildren()) { numGenericDatas += dataInterval.second->getGenericDataChildren().size(); } } result.reserve(numGenericDatas); // returns generic datas depending of selection for (const auto& dataSet : myAttributeCarriers->getDataSets()) { for (const auto& dataInterval : dataSet.second->getDataIntervalChildren()) { for (const auto& genericData : dataInterval.second->getGenericDataChildren()) { if (!onlySelected || genericData->isAttributeCarrierSelected()) { result.push_back(genericData); } } } } return result; } int GNENet::getNumberOfDataSets() const { return (int)myAttributeCarriers->getDataSets().size(); } void GNENet::requireSaveDataElements(bool value) { if (myDataElementsSaved == true) { WRITE_DEBUG("DataSets has to be saved"); std::string netSaved = (myNetSaved ? "saved" : "unsaved"); std::string additionalsSaved = (myAdditionalsSaved ? "saved" : "unsaved"); std::string demandEleementsSaved = (myDemandElementsSaved ? "saved" : "unsaved"); WRITE_DEBUG("Current saving Status: net " + netSaved + ", additionals " + additionalsSaved + ", demand elements " + demandEleementsSaved + ", data sets unsaved"); } myDataElementsSaved = !value; if (myViewNet != nullptr) { if (myDataElementsSaved) { myViewNet->getViewParent()->getGNEAppWindows()->disableSaveDataElementsMenu(); } else { myViewNet->getViewParent()->getGNEAppWindows()->enableSaveDataElementsMenu(); } } } void GNENet::saveDataElements(const std::string& filename) { // first recompute data sets computeDataElements(myViewNet->getViewParent()->getGNEAppWindows()); // save data elements saveDataElementsConfirmed(filename); // change value of flag myDataElementsSaved = true; // show debug information WRITE_DEBUG("data sets saved"); } bool GNENet::isDataElementsSaved() const { return myDataElementsSaved; } std::string GNENet::generateDataSetID(const std::string& prefix) const { const std::string dataSetTagStr = toString(SUMO_TAG_DATASET); int counter = 0; while (myAttributeCarriers->getDataSets().count(prefix + dataSetTagStr + "_" + toString(counter)) != 0) { counter++; } return (prefix + dataSetTagStr + "_" + toString(counter)); } std::set GNENet::retrieveGenericDataParameters(const std::string& genericDataTag, const double begin, const double end) const { // declare solution std::set attributesSolution; // declare generic data vector std::vector genericDatas; // iterate over all data sets for (const auto& dataSet : myAttributeCarriers->getDataSets()) { for (const auto& interval : dataSet.second->getDataIntervalChildren()) { // check interval if ((interval.second->getAttributeDouble(SUMO_ATTR_BEGIN) >= begin) && (interval.second->getAttributeDouble(SUMO_ATTR_END) <= end)) { // iterate over generic datas for (const auto& genericData : interval.second->getGenericDataChildren()) { if (genericDataTag.empty() || (genericData->getTagProperty().getTagStr() == genericDataTag)) { genericDatas.push_back(genericData); } } } } } // iterate over generic datas for (const auto& genericData : genericDatas) { for (const auto& attribute : genericData->getParametersMap()) { attributesSolution.insert(attribute.first); } } return attributesSolution; } std::set GNENet::retrieveGenericDataParameters(const std::string& dataSetID, const std::string& genericDataTag, const std::string& beginStr, const std::string& endStr) const { // declare solution std::set attributesSolution; // vector of data sets and intervals std::vector dataSets; std::vector dataIntervals; // if dataSetID is empty, return all parameters if (dataSetID.empty()) { // add all data sets dataSets.reserve(myAttributeCarriers->getDataSets().size()); for (const auto& dataSet : myAttributeCarriers->getDataSets()) { dataSets.push_back(dataSet.second); } } else if (myAttributeCarriers->getDataSets().count(dataSetID) > 0) { dataSets.push_back(myAttributeCarriers->getDataSets().at(dataSetID)); } else { return attributesSolution; } // now continue with data intervals int numberOfIntervals = 0; for (const auto& dataSet : dataSets) { numberOfIntervals += (int)dataSet->getDataIntervalChildren().size(); } // resize dataIntervals dataIntervals.reserve(numberOfIntervals); // add intervals for (const auto& dataSet : dataSets) { for (const auto& dataInterval : dataSet->getDataIntervalChildren()) { // continue depending of begin and end if (beginStr.empty() && endStr.empty()) { dataIntervals.push_back(dataInterval.second); } else if (endStr.empty()) { // parse begin const double begin = GNEAttributeCarrier::parse(beginStr); if (dataInterval.second->getAttributeDouble(SUMO_ATTR_BEGIN) >= begin) { dataIntervals.push_back(dataInterval.second); } } else if (beginStr.empty()) { // parse end const double end = GNEAttributeCarrier::parse(endStr); if (dataInterval.second->getAttributeDouble(SUMO_ATTR_END) <= end) { dataIntervals.push_back(dataInterval.second); } } else { // parse both begin end const double begin = GNEAttributeCarrier::parse(beginStr); const double end = GNEAttributeCarrier::parse(endStr); if ((dataInterval.second->getAttributeDouble(SUMO_ATTR_BEGIN) >= begin) && (dataInterval.second->getAttributeDouble(SUMO_ATTR_END) <= end)) { dataIntervals.push_back(dataInterval.second); } } } } // finally iterate over intervals and get attributes for (const auto& dataInterval : dataIntervals) { for (const auto& genericData : dataInterval->getGenericDataChildren()) { // check generic data tag if (genericDataTag.empty() || (genericData->getTagProperty().getTagStr() == genericDataTag)) { for (const auto& attribute : genericData->getParametersMap()) { attributesSolution.insert(attribute.first); } } } } return attributesSolution; } double GNENet::getDataSetIntervalMinimumBegin() const { double minimumBegin = 0; // update with first minimum (if exist) if ((myAttributeCarriers->getDataSets().size() > 0) && (myAttributeCarriers->getDataSets().begin()->second->getDataIntervalChildren().size() > 0)) { minimumBegin = myAttributeCarriers->getDataSets().begin()->second->getDataIntervalChildren().begin()->second->getAttributeDouble(SUMO_ATTR_BEGIN); } // iterate over all data sets for (const auto& dataSet : myAttributeCarriers->getDataSets()) { // iterate over interval for (const auto& interval : dataSet.second->getDataIntervalChildren()) { if (interval.second->getAttributeDouble(SUMO_ATTR_BEGIN) < minimumBegin) { minimumBegin = interval.second->getAttributeDouble(SUMO_ATTR_BEGIN); } } } return minimumBegin; } double GNENet::getDataSetIntervalMaximumEnd() const { double maximumEnd = 0; // update with first maximum (if exist) if ((myAttributeCarriers->getDataSets().size() > 0) && (myAttributeCarriers->getDataSets().begin()->second->getDataIntervalChildren().size() > 0)) { maximumEnd = myAttributeCarriers->getDataSets().begin()->second->getDataIntervalChildren().begin()->second->getAttributeDouble(SUMO_ATTR_END); } // iterate over all data sets for (const auto& dataSet : myAttributeCarriers->getDataSets()) { // iterate over interval for (const auto& interval : dataSet.second->getDataIntervalChildren()) { if (interval.second->getAttributeDouble(SUMO_ATTR_END) > maximumEnd) { maximumEnd = interval.second->getAttributeDouble(SUMO_ATTR_END); } } } return maximumEnd; } void GNENet::saveAdditionalsConfirmed(const std::string& filename) { OutputDevice& device = OutputDevice::getDevice(filename); device.writeXMLHeader("additional", "additional_file.xsd"); // now write all route probes (see Ticket #4058) for (const auto& additionalPair : myAttributeCarriers->getAdditionals()) { if (additionalPair.first == SUMO_TAG_ROUTEPROBE) { for (const auto& additional : additionalPair.second) { additional.second->writeAdditional(device); } } } // now write all stoppingPlaces for (const auto& additionalPair : myAttributeCarriers->getAdditionals()) { if (GNEAttributeCarrier::getTagProperties(additionalPair.first).isStoppingPlace()) { for (const auto& additional : additionalPair.second) { // only save stoppingPlaces that doesn't have Additional parents, because they are automatically writed by writeAdditional(...) parent's function if (additional.second->getParentAdditionals().empty()) { additional.second->writeAdditional(device); } } } } // now write all detectors for (const auto& additionalPair : myAttributeCarriers->getAdditionals()) { if (GNEAttributeCarrier::getTagProperties(additionalPair.first).isDetector()) { for (const auto& additional : additionalPair.second) { // only save Detectors that doesn't have Additional parents, because they are automatically writed by writeAdditional(...) parent's function if (additional.second->getParentAdditionals().empty()) { additional.second->writeAdditional(device); } } } } // now write rest of additionals for (const auto& additionalPair : myAttributeCarriers->getAdditionals()) { const auto& tagValue = GNEAttributeCarrier::getTagProperties(additionalPair.first); if (!tagValue.isStoppingPlace() && !tagValue.isDetector() && (additionalPair.first != SUMO_TAG_ROUTEPROBE) && (additionalPair.first != SUMO_TAG_VTYPE) && (additionalPair.first != SUMO_TAG_ROUTE)) { for (const auto& additional : additionalPair.second) { // only save additionals that doesn't have Additional parents, because they are automatically writed by writeAdditional(...) parent's function if (additional.second->getParentAdditionals().empty()) { additional.second->writeAdditional(device); } } } } // write TAZs for (const auto& TAZ : myAttributeCarriers->getTAZElements().at(SUMO_TAG_TAZ)) { TAZ.second->writeTAZElement(device); } // write Polygons for (const auto& poly : myAttributeCarriers->getShapes().at(SUMO_TAG_POLY)) { poly.second->writeShape(device); } // write POIs for (const auto& shape : myAttributeCarriers->getShapes()) { for (const auto& POI : shape.second) { if (POI.second->getTagProperty().getTag() != SUMO_TAG_POLY) { POI.second->writeShape(device); } } } device.close(); } void GNENet::saveDemandElementsConfirmed(const std::string& filename) { OutputDevice& device = OutputDevice::getDevice(filename); device.writeXMLHeader("routes", "routes_file.xsd"); // first write all vehicle types for (auto i : myAttributeCarriers->getDemandElements().at(SUMO_TAG_VTYPE)) { i.second->writeDemandElement(device); } // first write all person types for (auto i : myAttributeCarriers->getDemandElements().at(SUMO_TAG_PTYPE)) { i.second->writeDemandElement(device); } // now write all routes (and their associated stops) for (auto i : myAttributeCarriers->getDemandElements().at(SUMO_TAG_ROUTE)) { i.second->writeDemandElement(device); } // sort vehicles/persons by depart std::map > vehiclesSortedByDepart; for (const auto& demandElementTag : myAttributeCarriers->getDemandElements()) { for (const auto& demandElement : demandElementTag.second) { if (demandElement.second->getTagProperty().isPerson() || demandElement.second->getTagProperty().isVehicle()) { // save it in myVehiclesSortedByDepart vehiclesSortedByDepart[GNEAttributeCarrier::parse(demandElement.second->getBegin())].push_back(demandElement.second); } } } // finally write all vehicles and persons sorted by depart time (and their associated stops, personPlans, etc.) for (const auto& vehicleTag : vehiclesSortedByDepart) { for (const auto& vehicle : vehicleTag.second) { vehicle->writeDemandElement(device); } } device.close(); } void GNENet::saveDataElementsConfirmed(const std::string& filename) { OutputDevice& device = OutputDevice::getDevice(filename); device.writeXMLHeader("meandata", "meandata_file.xsd"); // write all data sets for (const auto& dataSet : myAttributeCarriers->getDataSets()) { dataSet.second->writeDataSet(device); } // close device device.close(); } GNEShape* GNENet::retrieveShape(SumoXMLTag type, const std::string& id, bool hardFail) const { if ((myAttributeCarriers->getShapes().count(type) > 0) && (myAttributeCarriers->getShapes().at(type).count(id) != 0)) { return myAttributeCarriers->getShapes().at(type).at(id); } else if (hardFail) { throw ProcessError("Attempted to retrieve non-existant shape"); } else { return nullptr; } } std::vector GNENet::retrieveShapes(bool onlySelected) const { std::vector result; // returns shapes depending of selection for (auto i : myAttributeCarriers->getShapes()) { for (auto j : i.second) { if (!onlySelected || j.second->isAttributeCarrierSelected()) { result.push_back(j.second); } } } return result; } std::string GNENet::generateShapeID(SumoXMLTag tag) const { int counter = 0; // generate tag depending of shape type if (tag == SUMO_TAG_POLY) { while (myAttributeCarriers->getShapes().at(tag).count(toString(tag) + "_" + toString(counter)) != 0) { counter++; } return (toString(tag) + "_" + toString(counter)); } else { while (myAttributeCarriers->getShapes().at(tag).count(toString(SUMO_TAG_POI) + "_" + toString(counter)) != 0) { counter++; } return (toString(SUMO_TAG_POI) + "_" + toString(counter)); } } int GNENet::getNumberOfShapes(SumoXMLTag type) const { int counter = 0; for (auto i : myAttributeCarriers->getShapes()) { if ((type == SUMO_TAG_NOTHING) || (type == i.first)) { counter += (int)i.second.size(); } } return counter; } GNETAZElement* GNENet::retrieveTAZElement(SumoXMLTag type, const std::string& id, bool hardFail) const { if ((myAttributeCarriers->getTAZElements().count(type) > 0) && (myAttributeCarriers->getTAZElements().at(type).count(id) != 0)) { return myAttributeCarriers->getTAZElements().at(type).at(id); } else if (hardFail) { throw ProcessError("Attempted to retrieve non-existant TAZElement"); } else { return nullptr; } } std::vector GNENet::retrieveTAZElements(bool onlySelected) const { std::vector result; // returns TAZElements depending of selection for (auto i : myAttributeCarriers->getTAZElements()) { for (auto j : i.second) { if (!onlySelected || j.second->isAttributeCarrierSelected()) { result.push_back(j.second); } } } return result; } std::string GNENet::generateTAZElementID(SumoXMLTag tag) const { int counter = 0; while (myAttributeCarriers->getTAZElements().at(tag).count(toString(tag) + "_" + toString(counter)) != 0) { counter++; } return (toString(tag) + "_" + toString(counter)); } int GNENet::getNumberOfTAZElements(SumoXMLTag type) const { int counter = 0; for (auto i : myAttributeCarriers->getTAZElements()) { if ((type == SUMO_TAG_NOTHING) || (type == i.first)) { counter += (int)i.second.size(); } } return counter; } void GNENet::requireSaveTLSPrograms() { if (myTLSProgramsSaved == true) { WRITE_DEBUG("TLSPrograms has to be saved"); } myTLSProgramsSaved = false; myViewNet->getViewParent()->getGNEAppWindows()->enableSaveTLSProgramsMenu(); } void GNENet::saveTLSPrograms(const std::string& filename) { // open output device OutputDevice& device = OutputDevice::getDevice(filename); device.openTag("additionals"); // write traffic lights using NWWriter NWWriter_SUMO::writeTrafficLights(device, getTLLogicCont()); device.close(); // change flag to true myTLSProgramsSaved = true; // show debug information WRITE_DEBUG("TLSPrograms saved"); } int GNENet::getNumberOfTLSPrograms() const { return -1; } void GNENet::enableUpdateGeometry() { myUpdateGeometryEnabled = true; } void GNENet::disableUpdateGeometry() { myUpdateGeometryEnabled = false; } bool GNENet::isUpdateGeometryEnabled() const { return myUpdateGeometryEnabled; } // =========================================================================== // private // =========================================================================== void GNENet::initJunctionsAndEdges() { // init junctions (by default Crossing and walking areas aren't created) NBNodeCont& nodeContainer = myNetBuilder->getNodeCont(); for (auto name_it : nodeContainer.getAllNames()) { NBNode* nbn = nodeContainer.retrieve(name_it); myAttributeCarriers->registerJunction(new GNEJunction(this, nbn, true)); } // init edges NBEdgeCont& ec = myNetBuilder->getEdgeCont(); for (auto name_it : ec.getAllNames()) { // create edge using NBEdge GNEEdge* edge = new GNEEdge(this, ec.retrieve(name_it), false, true); // register edge myAttributeCarriers->registerEdge(edge); // add manually child references due initJunctionsAndEdges doesn't use undo-redo edge->getParentJunctions().front()->addChildElement(edge); edge->getParentJunctions().back()->addChildElement(edge); // check grid if (myGrid.getWidth() > 10e16 || myGrid.getHeight() > 10e16) { throw ProcessError("Network size exceeds 1 Lightyear. Please reconsider your inputs.\n"); } } // make sure myGrid is initialized even for an empty net if (myAttributeCarriers->getEdges().size() == 0) { myGrid.add(Boundary(0, 0, 100, 100)); } // recalculate all lane2lane connections for (const auto& edge : myAttributeCarriers->getEdges()) { for (const auto& lane : edge.second->getLanes()) { lane->updateGeometry(); } } // sort nodes edges so that arrows can be drawn correctly NBNodesEdgesSorter::sortNodesEdges(nodeContainer); } void GNENet::reserveEdgeID(const std::string& id) { myEdgeIDSupplier.avoid(id); } void GNENet::reserveJunctionID(const std::string& id) { myJunctionIDSupplier.avoid(id); } void GNENet::initGNEConnections() { for (const auto& edge : myAttributeCarriers->getEdges()) { // remake connections edge.second->remakeGNEConnections(); // update geometry of connections for (const auto& connection : edge.second->getGNEConnections()) { connection->updateGeometry(); } } } void GNENet::computeAndUpdate(OptionsCont& oc, bool volatileOptions) { // make sure we only add turn arounds to edges which currently exist within the network std::set liveExplicitTurnarounds; for (const auto& explicitTurnarounds : myExplicitTurnarounds) { if (myAttributeCarriers->getEdges().count(explicitTurnarounds) > 0) { liveExplicitTurnarounds.insert(explicitTurnarounds); } } // removes all junctions of grid WRITE_GLDEBUG("Removing junctions during recomputing"); for (const auto& it : myAttributeCarriers->getJunctions()) { myGrid.removeAdditionalGLObject(it.second); } // remove all edges from grid WRITE_GLDEBUG("Removing edges during recomputing"); for (const auto& it : myAttributeCarriers->getEdges()) { myGrid.removeAdditionalGLObject(it.second); } // compute using NetBuilder myNetBuilder->compute(oc, liveExplicitTurnarounds, volatileOptions); // remap ids if necessary if (oc.getBool("numerical-ids") || oc.isSet("reserved-ids")) { myAttributeCarriers->remapJunctionAndEdgeIds(); } // update rtree if necessary if (!oc.getBool("offset.disable-normalization")) { for (const auto& edge : myAttributeCarriers->getEdges()) { // refresh edge geometry edge.second->updateGeometry(); } } // Clear current inspected ACs in inspectorFrame if a previous net was loaded if (myViewNet != nullptr) { myViewNet->getViewParent()->getInspectorFrame()->clearInspectedAC(); } // Reset Grid myGrid.reset(); myGrid.add(GeoConvHelper::getFinal().getConvBoundary()); // if volatile options are true if (volatileOptions) { // check that net exist if (myViewNet == nullptr) { throw ProcessError("ViewNet doesn't exist"); } // disable update geometry before clear undo list myUpdateGeometryEnabled = false; // clear undo list (This will be remove additionals and shapes) myViewNet->getUndoList()->p_clear(); // clear all elements (it will also removed from grid) myAttributeCarriers->clearJunctions(); myAttributeCarriers->clearEdges(); myAttributeCarriers->clearAdditionals(); myAttributeCarriers->clearShapes(); myAttributeCarriers->clearTAZElements(); myAttributeCarriers->clearDemandElements(); // enable update geometry again myUpdateGeometryEnabled = true; // Write GL debug information WRITE_GLDEBUG("initJunctionsAndEdges function called in computeAndUpdate(...) due recomputing with volatile options"); // init again junction an edges (Additionals and shapes will be loaded after the end of this function) initJunctionsAndEdges(); } else { // insert all junctions of grid again WRITE_GLDEBUG("Add junctions during recomputing after calling myNetBuilder->compute(...)"); for (const auto& junction : myAttributeCarriers->getJunctions()) { myGrid.addAdditionalGLObject(junction.second); } // insert all edges from grid again WRITE_GLDEBUG("Add edges during recomputing after calling myNetBuilder->compute(...)"); for (const auto& edge : myAttributeCarriers->getEdges()) { myGrid.addAdditionalGLObject(edge.second); } // remake connections for (const auto& connection : myAttributeCarriers->getEdges()) { connection.second->remakeGNEConnections(); } // iterate over junctions of net for (const auto& junction : myAttributeCarriers->getJunctions()) { // undolist may not yet exist but is also not needed when just marking junctions as valid junction.second->setLogicValid(true, nullptr); // updated geometry junction.second->updateGeometryAfterNetbuild(); } // iterate over all edges of net for (const auto& edge : myAttributeCarriers->getEdges()) { // update geometry edge.second->updateGeometry(); } } // net recomputed, then return false; myNeedRecompute = false; } void GNENet::replaceInListAttribute(GNEAttributeCarrier* ac, SumoXMLAttr key, const std::string& which, const std::string& by, GNEUndoList* undoList) { assert(ac->getTagProperty().getAttributeProperties(key).isList()); std::vector values = GNEAttributeCarrier::parse >(ac->getAttribute(key)); std::vector newValues; for (auto v : values) { newValues.push_back(v == which ? by : v); } ac->setAttribute(key, toString(newValues), undoList); } /****************************************************************************/ #include "friendly_graph.h" #include "../../Constants.h" #include "../../navtypes.h" #include "../../Util.h" #include #include #include #include using namespace navtypes; using util::toPose; using util::toTransform; using util::toTransformRotateFirst; namespace filters::pose_graph { constexpr int LM_SIZE = 2; constexpr int POSE_SIZE = 3; FriendlyGraph::FriendlyGraph(int num_landmarks, int max_num_poses, float camera_std, float gps_xy_std, float wheel_noise_rate) : _num_landmarks(num_landmarks), _max_pose_id(0), _min_pose_id(0), _max_num_poses(max_num_poses), _current_guess(LM_SIZE * num_landmarks), _landmark_factor_ids(num_landmarks), _odom_cov_inv(), _sensor_cov_inv(), _gps_cov_inv(), _graph() { covariance<3> odom_cov = covariance<3>::Zero(); // TODO what are the right numbers here? Should y be correlated with theta? odom_cov << wheel_noise_rate, 0, 0, 0, wheel_noise_rate, wheel_noise_rate / 2.0, 0, wheel_noise_rate / 2.0, wheel_noise_rate; _odom_cov_inv = odom_cov.inverse(); covariance<2> sensor_cov = covariance<2>::Zero(); sensor_cov << camera_std * camera_std, 0, 0, camera_std * camera_std; _sensor_cov_inv = sensor_cov.inverse(); // GPS has no heading measurements // which we represent using a large covariance covariance<3> gps_cov = covariance<3>::Zero(); gps_cov << gps_xy_std * gps_xy_std, 0, 0, 0, gps_xy_std * gps_xy_std, 0, 0, 0, 50.0 * 50.0; _gps_cov_inv = gps_cov.inverse(); for (int id = 0; id < num_landmarks; id++) { _landmark_factor_ids[id] = -1; } } int FriendlyGraph::numPoses() { return _max_pose_id - _min_pose_id; } int FriendlyGraph::nonincrementingPoseIdx(int pose_id) { return _num_landmarks * LM_SIZE + (pose_id - _min_pose_id) * POSE_SIZE; } void FriendlyGraph::incrementNumPoses() { _max_pose_id++; _current_guess.conservativeResize(nonincrementingPoseIdx(_max_pose_id)); } int FriendlyGraph::poseIdx(int pose_id) { if (pose_id == _max_pose_id) { incrementNumPoses(); } else if (pose_id > _max_pose_id) { printf("Error: skipped a pose id (given %d, current %d)\n", pose_id, _max_pose_id); throw 1; } return nonincrementingPoseIdx(pose_id); } int FriendlyGraph::landmarkIdx(int lm_id) { assert(lm_id < _num_landmarks); return lm_id * LM_SIZE; } void FriendlyGraph::trimToMaxNumPoses() { if (numPoses() > _max_num_poses) { if (numPoses() != _max_num_poses + 1) { printf("Error: skipped a trim\n"); throw 2; } hessian sol_cov = _graph.covariance(); int base_idx = poseIdx(_min_pose_id + 1); measurement<3> first_pose = getPoseEstimate(_min_pose_id + 1); covariance<3> first_pose_cov = sol_cov.block(base_idx, base_idx, POSE_SIZE, POSE_SIZE); values old_guess = _current_guess; // printf("Trimming. Current uncertainty on base pose: %f %f %f\n", // sqrt(first_pose_cov(0,0)), sqrt(first_pose_cov(1,1)), // sqrt(first_pose_cov(2,2))); _graph.shiftIndices(POSE_SIZE, poseIdx(_min_pose_id)); _min_pose_id += 1; _current_guess.conservativeResize(nonincrementingPoseIdx(_max_pose_id)); _current_guess.block(poseIdx(_min_pose_id), 0, _max_num_poses * POSE_SIZE, 1) = old_guess.block(poseIdx(_min_pose_id + 1), 0, _max_num_poses * POSE_SIZE, 1); addPosePrior(_min_pose_id, toTransform(first_pose), first_pose_cov); } } pose_t FriendlyGraph::getPoseEstimate(int pose_id) { assert("bad pose id" && pose_id >= _min_pose_id && pose_id < _max_pose_id); pose_t p = _current_guess.block(poseIdx(pose_id), 0, POSE_SIZE, 1); return p; } void FriendlyGraph::addGPSMeasurement(int pose_id, const transform_t& gps_tf) { pose_t gps = toPose(gps_tf, 0); // heading doesn't matter _graph.add(new OdomFactor2D(poseIdx(pose_id), -1, _gps_cov_inv, gps)); } void FriendlyGraph::addOdomMeasurement(int pose2_id, int pose1_id, const transform_t& pose2_tf, const transform_t& pose1_tf) { transform_t rel_tf = pose2_tf * pose1_tf.inverse(); pose_t diff = toPose(rel_tf, 0.0); float lin_dist = diff(0); // Turning introduces more noise than going in a straight line float ang_dist = Constants::WHEEL_BASE * diff(2) * 4; float noise_distance_sq = lin_dist * lin_dist + ang_dist * ang_dist; _graph.add(new OdomFactor2D(poseIdx(pose2_id), poseIdx(pose1_id), _odom_cov_inv / noise_distance_sq, diff)); pose_t pose1_est = getPoseEstimate(pose1_id); transform_t new_pose_tf = rel_tf * toTransform(pose1_est); pose_t pose2_est = toPose(new_pose_tf, pose1_est(2)); _current_guess.block(poseIdx(pose2_id), 0, POSE_SIZE, 1) = pose2_est; } void FriendlyGraph::addLandmarkMeasurement(int pose_id, int lm_id, const point_t& bearing, bool overwrite) { measurement<2> lm = measurement<2>{bearing(0), bearing(1)}; if (overwrite && _landmark_factor_ids[lm_id] != -1) { _graph.deleteFactor(_landmark_factor_ids[lm_id]); } int id = _graph.add( new LandmarkFactor2D(landmarkIdx(lm_id), poseIdx(pose_id), _sensor_cov_inv, lm)); _landmark_factor_ids[lm_id] = id; } void FriendlyGraph::addLandmarkPrior(int lm_id, point_t location, double xy_std) { covariance<2> prior_cov = covariance<2>::Zero(); prior_cov << xy_std * xy_std, 0, 0, xy_std * xy_std; covariance<2> prior_cov_inv = prior_cov.inverse(); measurement<2> lm = measurement<2>{location(0), location(1)}; _graph.add(new LandmarkFactor2D(landmarkIdx(lm_id), -1, prior_cov_inv, lm)); _current_guess.block(landmarkIdx(lm_id), 0, LM_SIZE, 1) = lm; } void FriendlyGraph::addPosePrior(int pose_id, const transform_t& pose_tf, covariance<3>& cov) { covariance<3> prior_cov_inv = cov.inverse(); pose_t pose = toPose(pose_tf, 0); _graph.add(new OdomFactor2D(poseIdx(pose_id), -1, prior_cov_inv, pose)); _current_guess.block(poseIdx(pose_id), 0, POSE_SIZE, 1) = pose; } // Guarantee: after solve(), _graph.solution() == _current_guess void FriendlyGraph::solve() { trimToMaxNumPoses(); _graph.solve(_current_guess, 0.99); _current_guess = _graph.solution(); } points_t FriendlyGraph::getLandmarkLocations() { points_t lms({}); for (int i = 0; i < _num_landmarks * LM_SIZE; i += LM_SIZE) { point_t lm({0, 0, 1}); lm.topRows(LM_SIZE) = _current_guess.block(i, 0, LM_SIZE, 1); lms.push_back(lm); } return lms; } trajectory_t FriendlyGraph::getSmoothedTrajectory() { const values& x = _current_guess; trajectory_t tfs({}); for (int i = poseIdx(_min_pose_id); i < nonincrementingPoseIdx(_max_pose_id); i += POSE_SIZE) { if (POSE_SIZE == 3) { // 2D tfs.push_back(toTransformRotateFirst(0, 0, x(i + 2)) * toTransformRotateFirst(x(i), x(i + 1), 0)); } else { // 1D tfs.push_back(toTransformRotateFirst(x(i), 0, 0)); } } return tfs; } int FriendlyGraph::getMaxNumPoses() const { return _max_num_poses; } } // namespace filters::pose_graph #include #include using namespace cpp11; [[cpp11::register]] data_frame compress_(integers encoded) { using namespace cpp11::literals; vector stdv_e(encoded.begin(), encoded.end()); tuple, vector> compressed = spress::compress(stdv_e); return writable::data_frame({ "index"_nm = std::get<0>(compressed), "order"_nm = std::get<1>(compressed) }); } [[cpp11::register]] integers decompress_(integers x, integers order) { vector stdv_x(x.begin(), x.end()); vector stdv_o(order.begin(), order.end()); return as_sexp(spress::decompress(stdv_x, stdv_o)); } [[cpp11::register]] integers encode_(size_t n, doubles x, doubles y) { return as_sexp( spress::encode( n, as_cpp>(x), as_cpp>(y) ) ); } [[cpp11::register]] data_frame decode_(size_t n, integers h, doubles bb) { using namespace cpp11::literals; vector h_vec(h.begin(), h.end()); tuple, vector> decoded = spress::decode( n, h_vec, bb["xmax"], bb["xmin"], bb["ymax"], bb["ymin"] ); return writable::data_frame({ "x"_nm = std::get<0>(decoded), "y"_nm = std::get<1>(decoded) }); } [[cpp11::register]] data_frame grid_(size_t n, doubles bb) { using namespace cpp11::literals; tuple, vector, vector, vector, vector> hgrid = spress::grid::grid( n, bb["xmax"], bb["xmin"], bb["ymax"], bb["ymin"] ); writable::data_frame grd({ "x"_nm = std::get<0>(hgrid), "y"_nm = std::get<1>(hgrid), "gx"_nm = std::get<2>(hgrid), "gy"_nm = std::get<3>(hgrid), "h"_nm = std::get<4>(hgrid) }); grd.attr("spress_n") = n; return grd; }/*============================================================================= Copyright (c) 1998-2003 Copyright (c) 2001 Copyright (c) 2002 http://spirit.sourceforge.net/ Use, modification and distribution is subject to the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) =============================================================================*/ #if !defined(BOOST_SPIRIT_OPERATORS_HPP) #define BOOST_SPIRIT_OPERATORS_HPP #include #include #include #include #include #include #include #include #include #include #include #endif patrykbajos/zinot-projectzinot-utils/zinot-utils/zimesh-json/MaterialDao.hpp0 // // Created by patryk on 01.11.16. // #ifndef ZINOT_PROJECT_MATERIAL_HPP #define ZINOT_PROJECT_MATERIAL_HPP #include #include #include namespace Zimesh { class MaterialDao { public: enum EnvprobeType { None, EnvprobeObject, TextureCubemap }; enum RenderPass { Deferred, Forward }; private: QString name; bool drawable; QString shaderPath; QMap shaderUniforms; QMap shaderAttributes; EnvprobeType envprobeType; RenderPass renderPass; QString lightingModel; bool loadShaderProperties(const QJsonValue & shaderPropVal, QMap & map); bool loadShaderUniforms(const QJsonValue & shaderUniVal); bool loadShaderAttributes(const QJsonValue & shaderAttrVal); bool loadEnvprobeType(const QJsonValue & envProbeVal); bool loadRenderPass(const QJsonValue & renderPassVal); bool loadLightingModel(const QJsonValue & lightingMdlVal); public: bool loadFromJsonValue(const QString & matName, const QJsonValue & matVal); }; } #endif //ZINOT_PROJECT_MATERIAL_HPP // Copyright 2015 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 "chromecast/base/cast_sys_info_dummy.h" namespace chromecast { CastSysInfoDummy::CastSysInfoDummy() { } CastSysInfoDummy::~CastSysInfoDummy() { } CastSysInfo::BuildType CastSysInfoDummy::GetBuildType() { return BUILD_ENG; } std::string CastSysInfoDummy::GetSystemReleaseChannel() { return ""; } std::string CastSysInfoDummy::GetSerialNumber() { return "dummy.serial.number"; } std::string CastSysInfoDummy::GetProductName() { return ""; } std::string CastSysInfoDummy::GetDeviceModel() { return ""; } std::string CastSysInfoDummy::GetBoardName() { return ""; } std::string CastSysInfoDummy::GetBoardRevision() { return ""; } std::string CastSysInfoDummy::GetManufacturer() { return ""; } std::string CastSysInfoDummy::GetSystemBuildNumber() { return ""; } std::string CastSysInfoDummy::GetFactoryCountry() { return "US"; } std::string CastSysInfoDummy::GetFactoryLocale(std::string* second_locale) { return "en-US"; } std::string CastSysInfoDummy::GetWifiInterface() { return ""; } std::string CastSysInfoDummy::GetApInterface() { return ""; } std::string CastSysInfoDummy::GetGlVendor() { return ""; } std::string CastSysInfoDummy::GetGlRenderer() { return ""; } std::string CastSysInfoDummy::GetGlVersion() { return ""; } } // namespace chromecast // Copyright 1998-2016 Epic Games, Inc. All Rights Reserved. #include "LauncherServicesPrivatePCH.h" /* ILauncher overrides *****************************************************************************/ ILauncherWorkerPtr FLauncher::Launch( const ITargetDeviceProxyManagerRef& DeviceProxyManager, const ILauncherProfileRef& Profile ) { if (Profile->IsValidForLaunch()) { FLauncherWorker* LauncherWorker = new FLauncherWorker(DeviceProxyManager, Profile); if ((LauncherWorker != nullptr) && (FRunnableThread::Create(LauncherWorker, TEXT("LauncherWorker")) != nullptr)) { return MakeShareable(LauncherWorker); } } return nullptr; } #include #include #include using namespace std; typedef struct proccess { float at,bt,ct,ta,wt,btt; string pro_id; } Schedule; bool compare(Schedule a,Schedule b) { return a.at "; cin>>n; cout<<"======================================================================="< "; for(i=0;i>pro[i].pro_id; cin>>pro[i].at; cin>>pro[i].bt; pro[i].btt=pro[i].bt; } sort(pro,pro+n,compare);i=0; pcom=0; while(pcomi) break; } sort(pro,pro+j,compare2); if(j>0) { for(j=0;ji) { i=pro[j].at; } pro[j].ct=i+1; pro[j].bt--; } i++; pcom=0; for(j=0;jNicowcow/Minotaur #include #include #include namespace MinoGame { void Game::step() { GameState* gameState = static_cast(_state); if(!gameState) return; gameState->tick(); } bool Game::operator()(MinoUtils::Event e) { std::cout << "Game received event!" << std::endl; if(StateMachine::operator()(e)) return true; else { std::cout << "Forwarding to state!" << std::endl; GameState* gameState = static_cast(_state); if(!gameState) return false; return (*gameState)(e); }; return false; } } //////////////////////////////////////////////////////////////////////////////////////////////////// // // Project: Embedded Learning Library (ELL) // File: JsonArchiver.cpp (utilities) // Authors: // //////////////////////////////////////////////////////////////////////////////////////////////////// #include "JsonArchiver.h" #include "Archiver.h" #include "IArchivable.h" #include "Unused.h" #include #include #include #include namespace ell { namespace utilities { // // Serialization // JsonArchiver::JsonArchiver() : _out(std::cout) { } JsonArchiver::JsonArchiver(std::ostream& outputStream) : _out(outputStream) { } #define ARCHIVE_TYPE_OP(t) IMPLEMENT_ARCHIVE_VALUE(JsonArchiver, t); ARCHIVABLE_TYPES_LIST #undef ARCHIVE_TYPE_OP // strings void JsonArchiver::ArchiveValue(const char* name, const std::string& value) { WriteScalar(name, value); } void JsonArchiver::ArchiveNull(const char* name) { FinishPreviousLine(); auto indent = GetCurrentIndent(); _out << indent; _out << "\"" << name << "\": null"; } // IArchivable void JsonArchiver::BeginArchiveObject(const char* name, const IArchivable& value) { FinishPreviousLine(); auto indent = GetCurrentIndent(); _out << indent; bool hasName = name != std::string(""); if (hasName) { _out << "\"" << name << "\": "; } if (value.ArchiveAsPrimitive()) { return; } _out << "{\n"; WriteObjectType(value); WriteObjectVersion(value); IncrementIndent(); } void JsonArchiver::EndArchiveObject(const char* name, const IArchivable& value) { bool hasName = name != std::string(""); if (!value.ArchiveAsPrimitive()) { _out << "\n"; // Output newline instead of calling "FinishPreviousLine" DecrementIndent(); auto indent = GetCurrentIndent(); _out << indent << "}"; } // need to output a comma if we're serializing a field (that is, if name != "") SetEndOfLine(hasName ? ",\n" : "\n"); } void JsonArchiver::EndArchiving() { FinishPreviousLine(); } // // Arrays // #define ARCHIVE_TYPE_OP(t) IMPLEMENT_ARCHIVE_ARRAY(JsonArchiver, t); ARCHIVABLE_TYPES_LIST #undef ARCHIVE_TYPE_OP void JsonArchiver::ArchiveArray(const char* name, const std::vector& array) { WriteArray(name, array); } void JsonArchiver::ArchiveArray(const char* name, const std::string& baseTypeName, const std::vector& array) { UNUSED(baseTypeName); FinishPreviousLine(); auto indent = GetCurrentIndent(); bool hasName = name != std::string(""); _out << indent; if (hasName) { _out << "\"" << name << "\": "; } _out << "[\n"; auto numItems = array.size(); for (size_t index = 0; index < numItems; ++index) { Archive(*array[index]); if (index != numItems - 1) { _out << ", "; } } _out << "]"; SetEndOfLine(",\n"); } void JsonArchiver::WriteObjectType(const IArchivable& value) { FinishPreviousLine(); auto indent = GetCurrentIndent(); _out << indent << " \"_type\": \"" << GetArchivedTypeName(value) << "\""; SetEndOfLine(",\n"); } void JsonArchiver::WriteObjectVersion(const IArchivable& value) { FinishPreviousLine(); auto indent = GetCurrentIndent(); auto version = GetArchiveVersion(value); _out << indent << " \"_version\": \"" << version.versionNumber << "\""; SetEndOfLine(",\n"); } void JsonArchiver::Indent() { _out << GetCurrentIndent(); } void JsonArchiver::FinishPreviousLine() { _out << _endOfPreviousLine; _endOfPreviousLine = ""; } void JsonArchiver::SetEndOfLine(std::string endOfLine) { _endOfPreviousLine = endOfLine; } // // Deserialization // JsonUnarchiver::JsonUnarchiver(SerializationContext context) : Unarchiver(std::move(context)), _tokenizer(std::cin, ",:{}[]'\"") { } JsonUnarchiver::JsonUnarchiver(std::istream& inputStream, SerializationContext context) : Unarchiver(std::move(context)), _tokenizer(inputStream, ",:{}[]'\"") { } #define ARCHIVE_TYPE_OP(t) IMPLEMENT_UNARCHIVE_VALUE(JsonUnarchiver, t); ARCHIVABLE_TYPES_LIST #undef ARCHIVE_TYPE_OP // strings void JsonUnarchiver::UnarchiveValue(const char* name, std::string& value) { ReadScalar(name, value); } bool JsonUnarchiver::UnarchiveNull(const char* name) { bool result = false; PeekStack stack(_tokenizer); if (stack.Peek() == "\"" && stack.Peek() == name && stack.Peek() == "\"" && stack.Peek() == ":") { result = stack.Peek() == "null"; if (result) { stack.Consume(); } } return result; } // IArchivable ArchivedObjectInfo JsonUnarchiver::BeginUnarchiveObject(const char* name, const std::string& typeName) { UNUSED(typeName); bool hasName = name != std::string(""); if (hasName) { MatchFieldName(name); } _tokenizer.MatchToken("{"); MatchFieldName("_type"); _tokenizer.MatchToken("\""); auto encodedTypeName = _tokenizer.ReadNextToken(); if (encodedTypeName == "") { throw utilities::DataFormatException(DataFormatErrors::badFormat, "JSON format is invalid, expecting a non empty object _type name"); } _tokenizer.MatchToken("\""); int version = 0; if (_tokenizer.PeekNextToken() == ",") { _tokenizer.ReadNextToken(); // eat the comma MatchFieldName("_version"); _tokenizer.MatchToken("\""); auto versionString = _tokenizer.ReadNextToken(); // parse it version = std::stoi(versionString); _tokenizer.MatchToken("\""); if (_tokenizer.PeekNextToken() == ",") { _tokenizer.ReadNextToken(); // eat the comma } } return { encodedTypeName, version }; } void JsonUnarchiver::UnarchiveObjectAsPrimitive(const char* name, IArchivable& value) { bool hasName = name != std::string(""); if (hasName) { MatchFieldName(name); } UnarchiveObject(name, value); // eat a comma if it exists if (hasName) { if (_tokenizer.PeekNextToken() == ",") { _tokenizer.ReadNextToken(); } } } bool JsonUnarchiver::HasNextPropertyName(const std::string& name) { bool ok = true; std::string nextPropertyName = ""; std::vector readTokens; if (_tokenizer.TryMatchToken("\"")) { readTokens.push_back("\""); nextPropertyName = _tokenizer.ReadNextToken(); readTokens.push_back(nextPropertyName); if (_tokenizer.TryMatchToken("\"")) { readTokens.push_back("\""); if (_tokenizer.TryMatchToken(":")) { readTokens.push_back(":"); } else { ok = false; } } else { ok = false; } } // put back all read tokens while (!readTokens.empty()) { _tokenizer.PutBackToken(readTokens.back()); readTokens.pop_back(); } return ok && nextPropertyName == name; } void JsonUnarchiver::EndUnarchiveObject(const char* name, const std::string& typeName) { UNUSED(typeName); bool hasName = name != std::string(""); _tokenizer.MatchToken("}"); // eat a comma if it exists if (hasName) { if (_tokenizer.PeekNextToken() == ",") { _tokenizer.ReadNextToken(); } } } // // Arrays // #define ARCHIVE_TYPE_OP(t) IMPLEMENT_UNARCHIVE_ARRAY(JsonUnarchiver, t); ARCHIVABLE_TYPES_LIST #undef ARCHIVE_TYPE_OP void JsonUnarchiver::UnarchiveArray(const char* name, std::vector& array) { ReadArray(name, array); } void JsonUnarchiver::BeginUnarchiveArray(const char* name, const std::string& typeName) { UNUSED(typeName); bool hasName = name != std::string(""); if (hasName) { MatchFieldName(name); } _tokenizer.MatchToken("["); } bool JsonUnarchiver::BeginUnarchiveArrayItem(const std::string& typeName) { UNUSED(typeName); auto maybeEndArray = _tokenizer.PeekNextToken(); if (maybeEndArray == "]") { return false; } else { return true; } } void JsonUnarchiver::EndUnarchiveArrayItem(const std::string& typeName) { UNUSED(typeName); if (_tokenizer.PeekNextToken() == ",") { _tokenizer.ReadNextToken(); } } void JsonUnarchiver::EndUnarchiveArray(const char* name, const std::string& typeName) { UNUSED(typeName); bool hasName = name != std::string(""); _tokenizer.MatchToken("]"); // eat a comma if it exists if (hasName) { if (_tokenizer.PeekNextToken() == ",") { _tokenizer.ReadNextToken(); } } } bool JsonUnarchiver::TryMatchFieldName(const char* key, std::string& found) { bool ok = _tokenizer.TryMatchToken("\""); if (!ok) { return false; } auto s = _tokenizer.PeekNextToken(); if (s != key) { found = s; return false; } _tokenizer.ReadNextToken(); _tokenizer.MatchTokens({ "\"", ":" }); return true; } void JsonUnarchiver::MatchFieldName(const char* key) { std::string found = "non literal"; if (!TryMatchFieldName(key, found)) { throw InputException(InputExceptionErrors::badStringFormat, std::string{ "Failed to match field " } + key + ", instead found token '" + found + "'"); } } // // JsonUtilities // // Characters that must be escaped in JSON strings: ', ", \, newline (\n), carriage return (\r), tab (\t), backspace (\b), form feed (\f) std::string JsonUtilities::EncodeString(const std::string& str) { std::vector charCodes(127, '\0'); charCodes['\''] = '\''; charCodes['\"'] = '\"'; charCodes['\\'] = '\\'; charCodes['/'] = '/'; charCodes['\n'] = 'n'; charCodes['\r'] = 'r'; charCodes['\t'] = 't'; charCodes['\b'] = 'b'; charCodes['\f'] = 'f'; // copy characters from str until we hit an escaped character, then prepend it with a backslash std::stringstream s; for (auto ch : str) { auto encoding = ch >= 127 ? '\0' : charCodes[ch]; if (encoding == '\0') // no encoding { s.put(ch); } else { s.put('\\'); s.put(encoding); } } return s.str(); } std::string JsonUtilities::DecodeString(const std::string& str) { std::vector charCodes(127, '\0'); charCodes['\''] = '\''; charCodes['\"'] = '\"'; charCodes['\\'] = '\\'; charCodes['/'] = '/'; charCodes['n'] = '\n'; charCodes['r'] = '\r'; charCodes['t'] = '\t'; charCodes['b'] = '\b'; charCodes['f'] = '\f'; std::stringstream s; bool prevWasBackslash = false; for (auto ch : str) { if (prevWasBackslash) { auto encoding = ch >= 127 ? '\0' : charCodes[ch]; if (encoding == '\0') // nothing special { s.put('\\'); // emit previous backslash s.put(ch); // emit character } else { s.put(encoding); } prevWasBackslash = false; } else { if (ch == '\\') { prevWasBackslash = true; } else { prevWasBackslash = false; s.put(ch); } } } if (prevWasBackslash) { s.put('\\'); } return s.str(); } std::string JsonUtilities::EncodeTypeName(const std::string& str) { return str; } std::string JsonUtilities::DecodeTypeName(const std::string& str) { return str; } } // namespace utilities } // namespace ell /*重写1.6节中的书店程序,使用一个vector保存交易记录,使用不同算法完成处理。 使用sort和conpareIsbn函数来排序交易记录,然后使用find和accumulate求和。 */ #include #include #include #include #include #include"Sales_item.h" using namespace std; int main() { istream_iterator item_iter(cin), eof; ostream_iterator out_iter(cout, "\n"); vector items; while (item_iter != eof) items.push_back(*item_iter++); sort(items.begin(), items.end(), [](const Sales_item &lhs, const Sales_item &rhs) {return lhs.isbn() < rhs.isbn(); }); for (auto beg = items.cbegin(), end = beg; beg != items.cend(); beg = end) { end = find_if(beg, items.cend(), [beg](const Sales_item &item) {return item.isbn() != beg->isbn(); }); cout << accumulate(beg, end, Sales_item(beg->isbn())) << endl; } return 0; }/*! * Copyright 2017 by Contributors * \file count_descendant.cc * \brief Count number of descendants for each AST node */ #include "./builder.h" namespace treelite { namespace compiler { DMLC_REGISTRY_FILE_TAG(count_descendant); static int count(ASTNode* node) { if (dynamic_cast(node)) { node->num_descendant_ast_node = 0; return 0; // descendants of CodeFolderNode are exempt from // ASTBuilder::BreakUpLargeTranslationUnits } int accum = 0; for (ASTNode* child : node->children) { accum += count(child) + 1; } node->num_descendant_ast_node = accum; return accum; } void ASTBuilder::CountDescendant() { count(this->main_node); } } // namespace compiler } // namespace treelite // { Driver Code Starts #include using namespace std; // } Driver Code Ends class Solution{ public: int thirdLargest(int a[], int n) { sort(a, a + n); int first_lar = a[n - 1]; int second_lar; int second_lar_index = -1; int third = -1; int i = n - 2; while(i >= 0) { if(first_lar != a[i] && second_lar_index == -1) { second_lar = a[i]; second_lar_index = i; i--; continue; } if(second_lar_index != -1) { if(a[i] != second_lar) { third = a[i]; break; } } i--; } return third; } }; // { Driver Code Starts. int main() { int t; cin>>t; while(t--) { int n; cin>>n; int a[n]; for(int i=0;i>a[i]; Solution obj; cout< { /// friend class writer_base ; /// private: /// // Returns the number of bytes that have been written to this archive. /// virtual std::size_t size_impl () const; /// /// // An optional method which flushes any remaining output. /// virtual void flush_impl (); /// /// // Wrties an instance of standard-layout type T to the archive. /// template /// void put_impl (T const & ); /// }; /// \endcode /// /// See the zlib_archive.cpp example. /// /// \section archive-readers Archive Readers /// archive-readers: /// \code /// struct range_reader { /// // Reads and returns a single instance of a standard-layout type T from the archive and /// returns the value /// // extracted. /// template /// T get (); /// }; /// \endcode /// \example ostream_writer.cpp /// \brief A simple archive-writer which writes data to a std::ostream stream. /// /// It will produce the following output: /// /// 3 /// 73 /// 127 /// 179 /// /// The first of these values is produced by the std::set<> serializer: it is the number of members /// in the set. The following numbers are the contents of the container in normal iteration order. /// /// \see istream_reader.cpp /// \example istream_reader.cpp /// \brief A simple archive-reader which reads data from a std::istream stream. /// /// It will produce the following output: /// /// 73 /// 127 /// 179 /// /// \see ostream_writer.cpp /// \example zlib_archive.cpp /// \brief An example of writing a non-trivial archive-writer. /// This example uses ZLib to compress any data that is written to it, recording the result in a /// byte vector (std::vector). /// /// It will produce output which looks like: /// /// Started with these 197 bytes: /// 53 70 61 63 65 20 69 73 20 62 69 67 2e 20 52 65 61 6c 6c 79 20 62 69 67 2e 20 59 6f 75 20 6a /// 75 73 74 20 77 6f 6e 27 74 20 62 65 6c 69 65 76 65 20 68 6f 77 20 76 61 73 74 6c 79 2c 20 68 /// 75 67 65 6c 79 2c 20 6d 69 6e 64 2d 62 6f 67 67 6c 69 6e 67 6c 79 20 62 69 67 20 69 74 20 69 /// 73 2e 20 49 20 6d 65 61 6e 2c 20 79 6f 75 20 6d 61 79 20 74 68 69 6e 6b 20 69 74 27 73 20 61 /// 20 6c 6f 6e 67 20 77 61 79 20 64 6f 77 6e 20 74 68 65 20 72 6f 61 64 20 74 6f 20 74 68 65 20 /// 63 68 65 6d 69 73 74 2c 20 62 75 74 20 74 68 61 74 27 73 20 6a 75 73 74 20 70 65 61 6e 75 74 /// 73 20 74 6f 20 73 70 61 63 65 2e /// /// Wrote these 147 bytes: /// 78 da 25 8e b1 12 c3 20 0c 43 fb 29 da b2 a4 f9 8f ae ed d4 11 12 1f b8 05 9c 2b 26 1c 7f 5f /// 48 26 eb 24 eb 9d 5e bb 59 09 9c 61 d9 2d 78 92 09 a1 5d fa 2d 05 9f 92 15 55 d2 a4 b0 14 98 /// 0e 82 97 8a c3 64 0d 6d 86 2f 8e c6 8d 9c b6 bb 15 e7 02 27 77 f5 c1 da a9 0b 1e 88 64 d2 8c /// d6 69 d1 34 a8 e7 f4 ed e1 94 61 10 24 39 d4 ee 6e 52 53 8f 08 3f 31 1b 54 4e bd 7a 8a 9c 75 /// 86 2d da 0d 33 3a e7 a0 bd 13 8b e6 f1 97 c7 fc e5 f6 07 e6 0e 45 39 #ifndef PSTORE_SERIALIZE_ARCHIVE_HPP #define PSTORE_SERIALIZE_ARCHIVE_HPP #include #include "pstore/serialize/common.hpp" #include "pstore/support/error.hpp" namespace pstore { namespace serialize { /// \brief Containts the serialization archive types. namespace archive { template auto unsigned_cast (T const & t) -> typename std::make_unsigned::type { using unsigned_type = typename std::make_unsigned::type; PSTORE_ASSERT (t >= 0); return static_cast (t); } /// The archiver put() and [optional] putn() methods can optionally return a /// value to the caller. By convention, the return value represents the location /// to which the value(s) were written. However, for some archivers this doesn't /// make sense. For example, an archiver which writes to stdout can't really say /// anything useful. In these cases, we use 'void_type' to be a standin for the /// void type. struct void_type {}; // ***************************** // * w r i t e r _ b a s e * // ***************************** /// \brief The base class for archive-writer objects. template class writer_base { public: using policy_type = WriterPolicy; using result_type = typename policy_type::result_type; writer_base (writer_base const &) = delete; writer_base (writer_base &&) noexcept = default; virtual ~writer_base () noexcept { no_ex_escape ([this] () { this->flush (); }); } writer_base & operator= (writer_base &&) noexcept = default; writer_base & operator= (writer_base const &) = delete; ///@{ /// \brief Writes one or more instances of a standard-layout type Ty to the output. /// Must not be used once the stream has been flushed. /// \param t The value to be written to the output. template auto put (Ty const & t) -> result_type { static_assert (std::is_standard_layout::value, "writer_base can only write standard-layout types!"); PSTORE_ASSERT (!flushed_); result_type r = policy_.put (t); bytes_consumed_ += sizeof (t); return r; } /// \brief Writes a span of values to the output. /// /// This will call either the put() or putn() method on the archive type depending /// on whether the latter is available. /// /// \param sp The span of values to be written. /// \returns The value returned by the archive putn() function. template auto putn (Span sp) -> result_type { using element_type = typename Span::element_type; static_assert (std::is_standard_layout::value, "writer_base can only write standard-layout types!"); PSTORE_ASSERT (!flushed_); auto r = putn_helper::template putn (policy_, sp); bytes_consumed_ += unsigned_cast (sp.size_bytes ()); return r; } ///@} /// \brief Flushes the stream to the output. void flush () { if (!flushed_) { policy_.flush (); flushed_ = true; } } /// \brief Returns the number of bytes that have been written via this archive. std::size_t bytes_consumed () const { return bytes_consumed_; } /// \brief Returns the number of bytes that the policy object wrote to its final /// destination. std::size_t bytes_produced () const { return bytes_produced_helper (*this).get (policy_, nullptr); } ///@{ /// Returns the writer_base output policy object. WriterPolicy & writer_policy () noexcept { return policy_; } WriterPolicy const & writer_policy () const noexcept { return policy_; } ///@} protected: explicit writer_base (WriterPolicy policy = WriterPolicy ()) : policy_{std::move (policy)} {} private: /// A wrapper class which is used to call either policy.bytes_produced() if it is /// supported by the policy object and writer_base.bytes_consumed() if it is not. class bytes_produced_helper { public: explicit bytes_produced_helper (writer_base const & writer) : writer_{writer} {} // (This is a varargs function so that it is considered last in template // resolution.) template std::size_t get (Policy const & /*policy*/, ...) { // NOLINT(cert-dcl50-cpp) return writer_.bytes_consumed (); } template std::size_t get (Policy const & policy, decltype (&Policy::bytes_produced)) { return policy.bytes_produced (); } private: writer_base const & writer_; }; struct putn_helper { public: using result_type = typename policy_type::result_type; template static auto putn (WriterPolicy & policy, Span span) -> result_type { return invoke (policy, span, nullptr); } private: // This overload is always in the set of overloads but a function with // ellipsis parameter has the lowest ranking for overload resolution. template static auto invoke (P & policy, Span span, ...) // NOLINT(cert-dcl50-cpp) -> result_type { sticky_assign r; for (auto & v : span) { r = policy.put (v); } return r.get (); } // This overload is called if P has a putn<>() method. SFINAE means that we fall // back to the ellipsis overload if it does not. template static auto invoke (P & policy, Span span, decltype (&P::template putn)) -> result_type { return policy.putn (span); } }; WriterPolicy policy_; std::size_t bytes_consumed_ = 0U; bool flushed_{false}; ///< Has the stream been flushed? }; namespace details { class vector_writer_policy { public: using result_type = std::size_t; using container = std::vector; using const_iterator = container::const_iterator; explicit vector_writer_policy (container & bytes) noexcept : bytes_ (bytes) {} template auto put (Ty const & t) -> result_type { auto const old_size = bytes_.size (); auto const * const first = reinterpret_cast (&t); std::copy (first, first + sizeof (Ty), std::back_inserter (bytes_)); return old_size; } template auto putn (SpanType sp) -> result_type { auto const old_size = bytes_.size (); auto const * const first = reinterpret_cast (sp.data ()); std::copy (first, first + sp.size_bytes (), std::back_inserter (bytes_)); return old_size; } /// Returns the size of the byte vector managed by the object. std::size_t size () const noexcept { return bytes_.size (); } void flush () noexcept {} /// Returns a const_iterator for the beginning of the byte vector managed by the /// object. container::const_iterator begin () const { return std::begin (bytes_); } /// Returns a const_iterator for the end of the byte vector managed by the /// object. container::const_iterator end () const { return std::end (bytes_); } private: container & bytes_; ///< The container into which written data is accumulated. }; } // namespace details // ******************************* // * v e c t o r _ w r i t e r * // ******************************* /// \brief An archive-writer which writes data to a std::vector of std::uint8_t bytes. /// Owns a vector of bytes to which data is appended when the put<>() method is called. class vector_writer final : public writer_base { public: explicit vector_writer (std::vector & container) : writer_base ( details::vector_writer_policy{container}) {} vector_writer (vector_writer const &) = delete; vector_writer (vector_writer &&) = delete; ~vector_writer () noexcept override; vector_writer & operator= (vector_writer const &) = delete; vector_writer & operator= (vector_writer &&) = delete; using container = policy_type::container; using const_iterator = policy_type::const_iterator; /// Returns a const_iterator for the beginning of the byte vector managed by the /// object. const_iterator begin () const { return writer_policy ().begin (); } /// Returns a const_iterator for the end of the byte vector managed by the object. const_iterator end () const { return writer_policy ().end (); } }; /// Writes the contents of a vector_writer object to an ostream as a stream of /// space-separated two-digit hexadecimal values. /// /// \param os The output stream to which output will be written. /// \param writer The vector_writer whose contents are to be dumped to the output /// stream. /// \result The value passed as the 'os' parameter. std::ostream & operator<< (std::ostream & os, vector_writer const & writer); // ********************************* // * b u f f e r _ w r i t e r * // ********************************* namespace details { class buffer_writer_policy { public: using result_type = void *; buffer_writer_policy (void * const first, void * const last) noexcept : begin_ (static_cast (first)) #ifndef NDEBUG , end_ (static_cast (last)) #endif , it_ (static_cast (first)) { (void) last; PSTORE_ASSERT (end_ >= it_); } /// Writes an object to the output buffer. /// \param v The value to be written to the output container. template auto put (Ty const & v) -> result_type { auto const size = sizeof (v); PSTORE_ASSERT (it_ + size <= end_); auto const result = it_; std::memcpy (it_, &v, size); it_ += size; PSTORE_ASSERT (it_ <= end_); return result; } /// Returns the number of bytes written to the buffer. std::size_t size () const noexcept { PSTORE_ASSERT (it_ >= begin_); static_assert (sizeof (std::size_t) >= sizeof (std::ptrdiff_t), "sizeof size_t should be at least sizeof ptrdiff_t"); return static_cast (it_ - begin_); } void flush () noexcept {} using const_iterator = std::uint8_t const *; /// Returns a const_iterator for the beginning of the byte range. const_iterator begin () const noexcept { return begin_; } /// Returns a const_iterator for the end of byte range written to the buffer. const_iterator end () const noexcept { return it_; } private: /// The start of the input buffer. std::uint8_t * begin_; #ifndef NDEBUG /// The end of the input buffer range. std::uint8_t * end_; #endif /// Initially equal to begin_, but incremented as data is written to the /// archive. Always <= end_; std::uint8_t * it_; }; } // namespace details class buffer_writer final : public writer_base { public: /// \brief Constructs the writer using the range [first, last). /// \param first The start address of the buffer to which the buffer_writer will /// write data. /// \param last The end of the range of address to which the buffer_writer will /// write data. buffer_writer (void * const first, void * const last) : writer_base (policy_type{first, last}) {} buffer_writer (buffer_writer const &) = delete; buffer_writer (buffer_writer &&) = delete; /// \brief Constructs the writer starting at the address given by 'first' and with a /// number of bytes 'size'. /// \param first The start address of the buffer to which buffer_writer will write /// data. /// \param size The size, in bytes, of the buffer pointed to by 'first'. buffer_writer (void * const first, std::size_t const size) : buffer_writer (static_cast (first), static_cast (first) + size) {} /// \brief Constructs a buffer_writer from a pointer to allocated uninitialized /// storage. template explicit buffer_writer (T * t) : buffer_writer (t, sizeof (T)) {} ~buffer_writer () noexcept override; buffer_writer & operator= (buffer_writer const &) = delete; buffer_writer & operator= (buffer_writer &&) = delete; using const_iterator = policy_type::const_iterator; /// Returns a const_iterator for the beginning of the byte vector managed by the /// object. const_iterator begin () const { return writer_policy ().begin (); } /// Returns a const_iterator for the end of the byte vector managed by the object. const_iterator end () const { return writer_policy ().end (); } }; /// Writes the contents of a buffer_writer object to an ostream as a stream of /// space-separated two-digit hexadecimal values. /// /// \param os The output stream to which output will be written. /// \param writer The buffer_writer whose contents are to be dumped to the output /// stream. /// \result The value passed as the 'os' parameter. std::ostream & operator<< (std::ostream & os, buffer_writer const & writer); // *************** // * n u l l * // *************** namespace details { class null_policy { public: using result_type = void_type; template auto put (Ty const &) -> result_type { return {}; } template auto putn (SpanType) -> result_type { return {}; } void flush () noexcept {} }; } // end namespace details /// \brief An archive-writer which simply discards any data that it writes. /// write. class null final : public writer_base { public: null () = default; null (null const &) = delete; null (null &&) = delete; ~null () noexcept override; null & operator= (null const &) = delete; null & operator= (null &&) = delete; }; // ******************************* // * r a n g e _ r e a d e r * // ******************************* /// \brief An archive-reader which consumes data from an iterator. template class range_reader { static_assert (sizeof (typename std::iterator_traits::value_type) == 1, "archive_reader reads from a byte-wide sequence"); public: /// Constructs the writer using an input iterator. explicit range_reader (InputIterator first) : first_ (first) {} InputIterator iterator () { return first_; } /// Reads a single instance of a standard-layout type Ty from the input iterator and /// returns the value extracted. template void get (Ty & v) { static_assert (std::is_standard_layout::value, "range_reader can only read standard-layout types"); auto ptr = reinterpret_cast (&v); auto const last = ptr + sizeof (Ty); while (ptr != last) { *(ptr++) = *(first_++); } } template void getn (SpanType span) { using element_type = typename SpanType::element_type; static_assert (std::is_standard_layout::value, "range_reader can only read standard-layout types"); auto out = reinterpret_cast (span.data ()); auto last = out + span.size_bytes (); while (out != last) { *(out++) = *(first_++); } } private: InputIterator first_; ///< The iterator from which data is read. }; /// Constructs an archive-reader which will read from an iterator. /// /// \param first The iterator from which bytes will be read. /// \result Returns an instance of range_reader which will consume bytes from the /// iterator. template range_reader make_reader (InputIterator first) { return range_reader{first}; } // ********************************* // * b u f f e r _ r e a d e r * // ********************************* /// \brief An archive-reader which consumes data from a supplied pointer range. class buffer_reader { public: /// Constructs the writer using a pair of pointer to define the range [first, last). constexpr buffer_reader (void const * const first, void const * const last) noexcept : first_ (static_cast (first)) , last_ (static_cast (last)) {} /// Constructs the writer using a pointer and size to define the range [first, /// first+size). constexpr buffer_reader (void const * const first, std::size_t const size) noexcept : first_ (static_cast (first)) , last_ (static_cast (first) + size) {} /// Constructs the writer using a pointer and size to define the range [first, /// first+size). template explicit buffer_reader (SpanType const span) noexcept : first_ (reinterpret_cast (span.data ())) , last_ (first_ + span.size_bytes ()) {} /// Reads a single instance of a standard-layout type T from the input iterator and /// returns the value extracted. template T get () { typename std::remove_const::type result; static_assert (std::is_standard_layout::value, "buffer_reader(T&) can only read standard-layout types"); if (first_ + sizeof (T) > last_) { raise (std::errc::no_buffer_space, "Attempted to read past the end of a buffer."); } std::memcpy (&result, first_, sizeof (T)); first_ += sizeof (T); return result; } private: std::uint8_t const * first_; ///< The start of the range from which data is read. std::uint8_t const * last_; ///< The end of the range from which data is read. }; } // end namespace archive } // end namespace serialize } // end namespace pstore #endif // PSTORE_SERIALIZE_ARCHIVE_HPP /*** Extensions.cpp example: register use of extended element names */ //! @file //! @brief example: register use of extended element names #include #include "E57Foundation.h" using namespace e57; using namespace std; //! @brief Example use of E57 extension functions int main(int /*argc*/, char** /*argv*/) { try { ImageFile imf("temp._e57", "w"); imf.extensionsAdd("ext1", "http://www.example.com/MyExtension1"); ustring uri; if (!imf.extensionsLookupPrefix("ext1", uri)) cout << "Oops, ext1 should have been defined" << endl; else cout << "ext1 is prefix for uri=" << uri << endl; ustring prefix; if (!imf.extensionsLookupUri("http://www.example.com/MyExtension1", prefix)) cout << "Oops, URI http://www.example.com/MyExtension1 should have been defined" << endl; else cout << "URI http://www.example.com/MyExtension1 has prefix=" << prefix << endl; cout << "Defined extensions:" << endl; for (int i = 0; i < imf.extensionsCount(); i++) cout << " prefix:" << imf.extensionsPrefix(i) << " URI:" << imf.extensionsUri(i) << endl; imf.root().set("ext1:greeting", StringNode(imf, "Hello world.")); imf.close(); // don't forget to explicitly close the ImageFile } catch(E57Exception& ex) { ex.report(__FILE__, __LINE__, __FUNCTION__); return(-1); } return(0); } stack deleteMidUtil(stack s,int sof, int mid); stack deleteMid(stacks,int sizeOfStack,int current) { if(sizeOfStack <= 1){return(s);} int mid=ceil(sizeOfStack/2.0); return(deleteMidUtil(s,sizeOfStack,mid)); } stack deleteMidUtil(stack s,int sof, int mid) { int item=s.top(); s.pop(); if(sof == mid){return(s);} s=deleteMidUtil(s,sof-1,mid); s.push(item); return(s); } //----------------------recursive, throws error: void rec_func(stack&x,int index,int n) { if (index<0) return; if(index!=(n/2)){ int temp = x.top(); x.pop(); rec_func(x,index-1,n); x.push(temp); } else{ x.pop(); rec_func(x,index-1,n); } } stack DeleteMid(stacks,int sizeOfStack,int current) { rec_func(s,sizeOfStack-1,sizeOfStack-1); return s; } tybl/tybl // License: The Unlicense (https://unlicense.org) #include "money.hpp" #include "doctest/doctest.h" #include namespace ledger { money_t::money_t() : value(0) { } money_t::money_t(const std::string& new_value) { int64_t whole, frac; int result = sscanf(new_value.c_str(), "%ld.%2ld", &whole, &frac); if (result > 0) { value = whole * 100; if (result > 1) { value += frac; } } } money_t::money_t(const money_t &other) : value(other.value) { } std::string money_t::to_string() const { //TODO: Force frac to positive (whole should also be affected) int64_t whole = value / 100; int64_t frac = value % 100; char buffer[24]; std::snprintf(buffer, 24, "%ld.%02ld", whole, frac); return std::string(buffer); } money_t& money_t::operator = (money_t other) { //TODO: This is not implemented in the standard copy-and-swap paradigm std::swap(value, other.value); return *this; } money_t& money_t::operator += (const money_t &other) { value += other.value; return *this; } bool money_t::operator == (const money_t &other) const { return value == other.value; } std::ostream& operator << (std::ostream &out, const money_t &a) { return out << a.to_string(); } ledger::money_t operator + (money_t lhs, const money_t &rhs) { return lhs += rhs; } } // namespace ledger TEST_CASE("ledger::money_t") { std::string amount_a_str("12345678.90"); std::string amount_b_str("98765432.10"); std::string amount_sum_str("111111111.00"); ledger::money_t amount_a(amount_a_str); ledger::money_t amount_b(amount_b_str); ledger::money_t amount_sum(amount_sum_str); CHECK(amount_a.to_string() == amount_a_str); CHECK(amount_b.to_string() == amount_b_str); CHECK(amount_sum.to_string() == amount_sum_str); amount_a += amount_b; CHECK(amount_a == amount_sum); } #include "NPC\AllyNPC.h" #include "NPC\EnemyNPC.h" #include "logging\Logger.h" #include "Utils\TypedCallback.h" #include "DialogPane.h" #include "Map.h" #include "NpcManager.h" NpcManager::NpcManager(Player* player, Physics* physics) : player(player) { for (unsigned int i = 0; i < (unsigned int)NpcType::COUNT; i++) { npcs[(NpcType)i] = std::vector(); targets[(NpcType)i] = NpcTarget(); } // TODO make this not order-dependent. npcs[NpcType::KEY].push_back(new NPC("", "Giver of yer gear.", NPC::Shape::DIAMOND, glm::vec4(0.0f, 1.0f, 0.10f, 0.80f), NPC::INVULNERABLE)); npcs[NpcType::KEY].push_back(new NPC("", "Giver of yer data.", NPC::Shape::DIAMOND, glm::vec4(0.0f, 0.20f, 1.0f, 0.70f), NPC::INVULNERABLE)); npcs[NpcType::KEY].push_back(new NPC("", "Nominal strategy director.", NPC::Shape::CUBOID, glm::vec4(1.0f, 0.10f, 0.0f, 0.90f), NPC::INVULNERABLE)); npcs[NpcType::KEY].push_back(new NPC("", "Battle assistant extraordinaire.", NPC::Shape::CUBOID, glm::vec4(1.0f, 0.50f, 0.0f, 0.50f), NPC::INVULNERABLE)); npcs[NpcType::ENEMY].push_back(new EnemyNPC(this, physics)); npcs[NpcType::ALLY].push_back(new AllyNPC()); } void NpcManager::LoadNpcPhysics(Physics* physics, RegionManager* regionManager) { // TODO configurable. glm::vec2 gearSciPos = Map::GetPoint(Map::POI::GEAR_SCIENTIST); glm::vec2 intelSciPos = Map::GetPoint(Map::POI::INTELLIGENCE_SCIENTIST); glm::vec2 generalMilPos = Map::GetPoint(Map::POI::GENERAL_MILITARY); glm::vec2 sergeantMilPos = Map::GetPoint(Map::POI::SERGEANT_MILITARY); npcs[NpcType::KEY][KeyNpcs::GEAR]->LoadNpcPhysics(physics, glm::vec3(gearSciPos.x, gearSciPos.y, 2 + regionManager->GetPointHeight(physics, gearSciPos)), 100); npcs[NpcType::KEY][KeyNpcs::INTEL]->LoadNpcPhysics(physics, glm::vec3(intelSciPos.x, intelSciPos.y, 2 + regionManager->GetPointHeight(physics, intelSciPos)), 90); npcs[NpcType::KEY][KeyNpcs::GENERAL]->LoadNpcPhysics(physics, glm::vec3(generalMilPos.x, generalMilPos.y, 2 + regionManager->GetPointHeight(physics, generalMilPos)), 80); npcs[NpcType::KEY][KeyNpcs::SERGEANT]->LoadNpcPhysics(physics, glm::vec3(sergeantMilPos.x, sergeantMilPos.y, 2 + regionManager->GetPointHeight(physics, sergeantMilPos)), 65); // TODO test code remove glm::vec2 enemyPos = generalMilPos + glm::vec2(3.0f, 3.0f); npcs[NpcType::ENEMY][0]->LoadNpcPhysics(physics, glm::vec3(enemyPos.x, enemyPos.y, 2 + regionManager->GetPointHeight(physics, enemyPos)), 200.0f); glm::vec2 allyPos = generalMilPos - glm::vec2(8.0f, 8.0f); npcs[NpcType::ALLY][0]->LoadNpcPhysics(physics, glm::vec3(allyPos.x, allyPos.y, 2 + regionManager->GetPointHeight(physics, allyPos)), 70.0f); } void NpcManager::LoadGraphics(FontManager* fontManager) { for (auto iter = npcs.begin(); iter != npcs.end(); iter++) { for (auto innerIter = iter->second.begin(); innerIter != iter->second.end(); innerIter++) { (*innerIter)->LoadGraphics(fontManager); } } } void NpcManager::Converse(Events* events, DialogPane* dialogPane) { for (auto iter = npcs.begin(); iter != npcs.end(); iter++) { for (auto innerIter = iter->second.begin(); innerIter != iter->second.end(); innerIter++) { if ((*innerIter)->Converse(dialogPane)) { // Successful conversation. Logger::Log("Talked to ", (*innerIter)->GetName()); return; } } } // TODO configurable. dialogPane->QueueText(StyleText("[HUD]", "There is no one to talk to.", StyleText::Effect::MINI)); events->AddSingleEvent(TypedCallback(EventType::ADD_DIALOG, dialogPane, new DialogData(StyleText("[HUD]", "[Except for me].", StyleText::Effect::ITALICS)), true), 8.0f); } void NpcManager::Update(float gameTime, float frameTime) { for (auto iter = npcs.begin(); iter != npcs.end(); iter++) { for (auto innerIter = iter->second.begin(); innerIter != iter->second.end(); innerIter++) { (*innerIter)->Update(gameTime, frameTime); } } } void NpcManager::Render(FontManager* fontManager, ModelManager* modelManager, glm::mat4 projectionMatrix) { for (auto iter = npcs.begin(); iter != npcs.end(); iter++) { for (auto innerIter = iter->second.begin(); innerIter != iter->second.end(); innerIter++) { (*innerIter)->Render(fontManager, modelManager, projectionMatrix); } } } void NpcManager::UnloadNpcPhysics(Physics* physics) { for (auto iter = npcs.begin(); iter != npcs.end(); iter++) { for (auto innerIter = iter->second.begin(); innerIter != iter->second.end(); innerIter++) { (*innerIter)->UnloadNpcPhysics(physics); } } } bool NpcManager::IsTargettedEnemy(NpcType npcType, unsigned int* npcId) { if (targets[npcType].targetSet) { if (targets[npcType].targetType != npcType) { *npcId = targets[npcType].targetNpcId; return true; } } return false; } bool NpcManager::IsTargettedAlly(NpcType npcType, unsigned int* npcId) { if (targets[npcType].targetSet) { if (targets[npcType].targetType == npcType) { *npcId = targets[npcType].targetNpcId; return true; } } return false; } bool NpcManager::IsNearbyEnemy(const glm::vec3& pos, float radius, NpcType npcType, unsigned int* enemyId) { return AreManyNearbyEnemies(pos, radius, 1, npcType, enemyId); } bool NpcManager::AreManyNearbyEnemies(const glm::vec3& pos, float radius, int manyThreshold, NpcType npcType, unsigned int* singularEnemyId) { if (npcs[npcType].size() >= (unsigned int)manyThreshold) { int count = 0; for (unsigned int i = 0; i < npcs[npcType].size(); i++) { if (glm::distance(npcs[npcType][i]->GetPosition(), pos) < radius) { ++count; *singularEnemyId = i; if (count >= manyThreshold) { return true; } } } } return false; } bool NpcManager::IsEnemyAlive(NpcType npcType, unsigned int* npcId) { if (*npcId == PLAYER_ID) { // If the player is dead, we have our own handling logic. return false; } if (*npcId >= npcs[npcType].size()) { Logger::LogWarn("IsEnemyAlive of NpcManager attempted to get an NPC off the end of the list: [", npcType, ", ", *npcId, "]."); return true; } return npcs[npcType][*npcId]->IsAlive(); } glm::vec3 NpcManager::GetNpcPosition(NpcType npcType, unsigned int npcId) { if (npcId == PLAYER_ID) { return player->GetPosition(); } if (npcId >= npcs[npcType].size()) { Logger::LogWarn("GetNpcPosition of NpcManager attempted to get an NPC off the end of the list: [", npcType, ", ", npcId, "]."); return player->GetPosition(); } return npcs[npcType][npcId]->GetPosition(); }arash16/prays #include inline int readchar() { const int N = 1048576; static char buf[N]; static char *p = buf, *end = buf; if(p == end) { if((end = buf + fread(buf, 1, N, stdin)) == buf) return EOF; p = buf; } return *p++; } bool isdigit(char ch) { return ch>='0' && ch<='9'; } inline unsigned int readUInt() { char ch; unsigned int r=0; while (!isdigit(ch=readchar())); r = ch-'0'; while (isdigit(ch=readchar())) r = (r<<3) + (r<<1) + ch-'0'; return r; } // -------------------------------------------------------------------------- class FastStack { int data[1024], sz; public: FastStack():sz(0){} void clear() { sz=0; } bool empty() { return !sz; } void push(int x) { data[sz++] = x; } int pop() { return data[--sz]; } int top() { return data[sz-1]; } int size() { return sz; } }; int blocks[1001]; FastStack src, station; bool test(int n) { src.clear(); station.clear(); for (int i=n; i>0; i--) src.push(i); for (int i=0; ileet/ac/0814.binary-tree-pruning.cpp0 #include "../TreeNode.hpp" class Solution { public: TreeNode *pruneTree(TreeNode *root) { if (root == NULL) return NULL; root->left = pruneTree(root->left); root->right = pruneTree(root->right); return (root->val || root->left || root->right) ? root : NULL; } }; vector manacher(const string &s){ vector res(s.size()); int i = 0, j = 0; while(i < s.size()){ while(i >= j && i + j < s.size() && s[i-j] == s[i+j]) ++j; res[i] = j; int k = 1; while(i >= k && i + k < s.size() && k + res[i-k] < j) res[i+k] = res[i-k], ++k; i += k; j -= k; } return res; }wield/tests/unit_test/testColorDispatcher-UT.cpp #include "./platform/UnitTestSupport.hpp" #include "./test_color/ProcessingFunctor.hpp" #include "./test_color/Message.hpp" #include "./test_color/Traits.hpp" #include #include namespace { TEST(verifyColorDispatcherInstantiation) { using namespace wield::schedulers::color; using Stages = typename test_color::Traits::StageEnumType; using Stage = typename test_color::Traits::Stage; using Queue = Concurrency::concurrent_queue; Queue q; Dispatcher dispatcher(q); } TEST(verifyAddsStageNameWhenMessageDispatched) { using namespace wield::schedulers::color; using Message = typename test_color::Traits::Message; using Stages = typename test_color::Traits::StageEnumType; using Stage = typename test_color::Traits::Stage; using ColorQueue = Concurrency::concurrent_queue; using Queue = typename test_color::Traits::Queue; Message::smartptr m = new test_color::TestMessage(); ColorQueue colorQueue; Dispatcher dispatcher(colorQueue); Queue q; test_color::ProcessingFunctor pf; Stage stage1(Stages::Stage1, dispatcher, q, pf); Stage stage2(Stages::Stage2, dispatcher, q, pf); Stage stage3(Stages::Stage3, dispatcher, q, pf); dispatcher.dispatch(Stages::Stage1, *m); dispatcher.dispatch(Stages::Stage1, *m); dispatcher.dispatch(Stages::Stage3, *m); dispatcher.dispatch(Stages::Stage2, *m); dispatcher.dispatch(Stages::Stage1, *m); CHECK_EQUAL(5U, q.unsafe_size()); std::array stages = {{Stages::NumberOfEntries}}; for(auto& s : stages) { colorQueue.try_pop(s); } CHECK_EQUAL(Stages::Stage1, stages[0]); CHECK_EQUAL(Stages::Stage1, stages[1]); CHECK_EQUAL(Stages::Stage3, stages[2]); CHECK_EQUAL(Stages::Stage2, stages[3]); CHECK_EQUAL(Stages::Stage1, stages[4]); // cleanup memory in queues stage1.process(); stage1.process(); stage3.process(); stage2.process(); stage1.process(); } } thing/src/flarmer_esp.cpp0 #include #include #include #include #include #include //#include #include #include #include "credentials.h" #include "color_engine.h" static uint8_t macAddr[WL_MAC_ADDR_LENGTH]; volatile static bool isUpdating = false; static unsigned long lastTime = 0; static const unsigned long UPLOAD_PERIOD_BLYNK = 1000; static const unsigned long UPLOAD_PERIOD_FLARMER = 5000; static unsigned long uploadTimeFlarmer = 0; #define DHT_PIN 0 // D3, 10k Pull-up, GPIO0 DHT dht(DHT_PIN, DHT22, 0); ColorEngine colorEngine; ADC_MODE(ADC_VCC); void setup() { Serial.begin(115200); Serial.println("Booting"); // DHT pinMode(DHT_PIN, INPUT_PULLUP); dht.begin(); // WIFI WiFi.mode(WIFI_STA); WiFi.begin(WLAN_SSID, WLAN_PASSWD); while (WiFi.waitForConnectResult() != WL_CONNECTED) { Serial.println("Connection Failed! Rebooting..."); delay(5000); ESP.restart(); } WiFi.macAddress(macAddr); Serial.print("MAC: "); Serial.println(WiFi.macAddress()); // Color sensors if (!colorEngine.init()) { Serial.println("Color measurements not available! Rebooting..."); delay(5000); ESP.restart(); } // BLYNK Blynk.config(BLYNK_AUTH); // OTA // Port defaults to 8266 // ArduinoOTA.setPort(8266); // Hostname defaults to esp8266-[ChipID] // ArduinoOTA.setHostname("myesp8266"); // No authentication by default // ArduinoOTA.setPassword(""); // Password can be set with it's md5 value as well // MD5(admin) = // ArduinoOTA.setPassword(""); ArduinoOTA.onStart([]() { String type; if (ArduinoOTA.getCommand() == U_FLASH) type = "sketch"; else // U_SPIFFS type = "filesystem"; // NOTE: if updating SPIFFS this would be the place to unmount SPIFFS using SPIFFS.end() Serial.println("Start updating " + type); isUpdating = true; }); ArduinoOTA.onEnd([]() { isUpdating = false; Serial.println("\nEnd"); }); ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) { Serial.printf("Progress: %u%%\r", (progress / (total / 100))); }); ArduinoOTA.onError([](ota_error_t error) { Serial.printf("Error[%u]: ", error); if (error == OTA_AUTH_ERROR) Serial.println("Auth Failed"); else if (error == OTA_BEGIN_ERROR) Serial.println("Begin Failed"); else if (error == OTA_CONNECT_ERROR) Serial.println("Connect Failed"); else if (error == OTA_RECEIVE_ERROR) Serial.println("Receive Failed"); else if (error == OTA_END_ERROR) Serial.println("End Failed"); }); ArduinoOTA.begin(); Serial.println("Ready"); } uint16_t mapTcsToBlynk(uint16_t chn) { return map(chn, 0, 2000, 0, 1023); } void uploadToBlynk(const ColorMsmt& msm) { Blynk.run(); Blynk.virtualWrite(V0, mapTcsToBlynk(msm.r)); Blynk.virtualWrite(V1, mapTcsToBlynk(msm.g)); Blynk.virtualWrite(V2, mapTcsToBlynk(msm.b)); Blynk.virtualWrite(V3, mapTcsToBlynk(msm.c)); } enum WarmerState { WRMR_STATE_OFF, WRMR_STATE_STANDBY, WRMR_STATE_WARMING }; WarmerState convertColorToState(const ColorMsmt& clr) { if (clr.c < 50) return WRMR_STATE_OFF; else if (clr.g > clr.r) return WRMR_STATE_STANDBY; else return WRMR_STATE_WARMING; } struct Measurement { WarmerState wstate; float temperature; float humidity; }; size_t writeFloat(WiFiClient& wifi, float value) { uint32_t u4 = htonl(*(uint32_t*)&value); return wifi.write((char*) &u4, 4); } size_t writeInt32(WiFiClient& wifi, uint32_t value) { uint32_t u4 = htonl(value); return wifi.write((char*) &u4, 4); } void uploadToFlarmer(const Measurement& msm) { static WiFiClient wifi; if (!wifi.connect("192.168.0.101", 9268)) { Serial.printf("Failed to connect Flarmer, status %d\n", wifi.status()); return; } // '!B6cBff' wifi.write(1); // version - B // MAC-48 - 6c wifi.write(macAddr, WL_MAC_ADDR_LENGTH); // wstate - B wifi.write(msm.wstate); // temp - f writeFloat(wifi, msm.temperature); // humidity - f writeFloat(wifi, msm.humidity); wifi.stop(); } void uploadMsm(const Measurement& th, const ColorMsmt& clr) { Serial.printf("{ %4u %4u %4u %4u } -> %5u K, %3u lx\n", clr.r, clr.g, clr.b, clr.c, clr.colorTemp, clr.lux); uploadToBlynk(clr); unsigned long now = millis(); if (now > uploadTimeFlarmer + UPLOAD_PERIOD_FLARMER) { Measurement msm; msm.humidity = th.humidity; msm.temperature = th.temperature; msm.wstate = convertColorToState(clr); Serial.printf("State: %d, Temp: %.1f, Humidity: %.1f\n", msm.wstate, msm.temperature, msm.humidity); uploadToFlarmer(msm); uploadTimeFlarmer = now; } } void loop() { ArduinoOTA.handle(); if (!isUpdating) { unsigned long now = millis(); Measurement msm; msm.temperature = dht.readTemperature(); msm.humidity = dht.readHumidity(); ColorMsmt clr; if (colorEngine.readColors(clr)) { uploadMsm(msm, clr); } else { if (now > lastTime + UPLOAD_PERIOD_BLYNK) { Serial.println("Failed to read colors"); Serial.print("MAC: "); Serial.println(WiFi.macAddress()); Serial.print("IP: "); Serial.println(WiFi.localIP()); Serial.printf("ChipId %x, FlashId %x, FSize %u, FRsize %u, Freq %d, VCC: %hu\n", ESP.getChipId(), ESP.getFlashChipId(), ESP.getFlashChipSize(), ESP.getFlashChipRealSize(), ESP.getCpuFreqMHz(), ESP.getVcc()); lastTime = now; } } } }#include "abonent.h" void abonent::id_checker(const std::string &id, const int &i) const { int j = 0; for (iterator it=begin(); it != end(); it = it->next) { if (id == it->item.get_id() && j != i) { throw id_repit(); } ++j; } } abonent::abonent(const data_type &d, const std::string &O, const std::string &U, const std::initializer_list &v): list(v) { data = d; oper = O; uprav = U; } abonent::abonent(const data_type &d, const std::string &O, const std::string &U, const list &other): list(other) { data = d; oper = O; uprav = U; } abonent::abonent(const data_type &d, const std::string &O, const std::string &U, list&& other): list(other) { data = d; oper = O; uprav = U; other.clear(); } abonent::abonent(const abonent& other) noexcept: list(other) { oper = other.oper; uprav = other.uprav; data = other.data; } abonent::abonent(abonent &&other) noexcept: list(std::move(other)), oper(other.oper), uprav(other.uprav), data(other.data) { other.uprav.clear(); other.oper.clear(); other.data = data_type(1, 1, 2000); } void abonent::rand() { clear(); std::random_device re; std::uniform_int_distribution dis(1, 9); std::uniform_int_distribution disdata(1, 3000); std::uniform_real_distribution disd(1, 500); int n = dis(re); for (int i=0; inext) { if (i->item.get_id() == id) { return i; } } return i; } list abonent::find_tele(std::string tele) { list f; for (iterator i=begin(); i != nullptr; i = i->next) { if (i->item.get_tel() == tele) { f.push_back(i->item); } } return f; } list abonent::find_tarif(double t) { list f; for (iterator i=begin(); i != nullptr; i = i->next) { if ((t - i->item.get_tar()) < 0.001) { f.push_back(i->item); } } return f; } list abonent::find_tarif_less(double t) { list f; for (iterator i=begin(); i != nullptr; i = i->next) { if (t > i->item.get_tar()) { f.push_back(i->item); } } return f; } list abonent::find_tarif_more(double t) { list f; for (iterator i=begin(); i != nullptr; i = i->next) { if (t < i->item.get_tar()) { f.push_back(i->item); } } return f; } std::string abonent::toString() const noexcept { return ("Фамилия оператора: " + oper + "\n Управляющий списоком: " + uprav + "\n Дата создания: " + std::to_string(std::get<0>(data)) + "д" + std::to_string(std::get<1>(data)) + "м" + std::to_string(std::get<2>(data)) + "г" + '\n' + to_String()); } himanshuMaheshwari2311/Compiler-Construction-Lab #include #include int hello( int a , int b ) { return a ; } void foo( int a , int b ) { } int main() { struct { int a ; int b ; } structure ; int i ; char data ; int num ; float x ; short y ; for ( i = 0 ; i < 10 ; i ++ ) { cout << i ; } } // This file auto generated by plugin for ida pro. Generated code only for x64. Please, dont change manually #pragma once #include #include <_D3DSTATUS.hpp> START_ATF_NAMESPACE struct _D3DEXECUTEDATA { unsigned int dwSize; unsigned int dwVertexOffset; unsigned int dwVertexCount; unsigned int dwInstructionOffset; unsigned int dwInstructionLength; unsigned int dwHVertexOffset; _D3DSTATUS dsStatus; }; END_ATF_NAMESPACE src/game/world.hpp // The MIT License (MIT) // Copyright (c) 2016 nabijaczleweli // 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 "entity/entity.hpp" #include #include #include #include #include #include #include class game_world { private: std::map> entities; std::vector sheduled_for_deletion; bool ticking = false; std::pair save_text; std::pair save_error_text; std::vector save_threads; std::size_t reserve_eid(); std::size_t spawn_p(std::size_t id, std::unique_ptr ep); public: entity & ent(std::size_t id); const entity & ent(std::size_t id) const; void tick(sf::Vector2u screen_size); void handle_event(const sf::Event & event); void draw(sf::RenderTarget & upon); template std::size_t spawn(AT &&... at) { const auto id = reserve_eid(); return spawn_p(id, std::make_unique(std::ref(*this), id, std::forward(at)...)); } template std::size_t spawn_create(AT &&... at) { const auto id = reserve_eid(); return spawn_p(id, ET::create(*this, id, std::forward(at)...)); } void despawn(std::size_t id); game_world() = default; game_world(const json::object & save, std::size_t & pid); ~game_world(); }; ericmehl/cortex ////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2011-2013, Image Engine Design 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 Image Engine Design nor the names of any // other contributors to this software 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 "boost/format.hpp" #include "boost/python.hpp" #include "IECorePython/MurmurHashBinding.h" #include "IECore/DataAlgo.h" #include "IECore/MurmurHash.h" #include "IECore/VectorTypedData.h" using namespace boost::python; using namespace IECore; namespace { static std::string repr( const MurmurHash &hash ) { return "IECore.MurmurHash( \"" + hash.toString() + "\" )"; } template static void appendArray( MurmurHash &hash, typename TypedData >::ConstPtr data ) { hash.append( data->readable() ); } static void appendInt( MurmurHash &hash, int64_t v ) { // Function that keeps backward compatibility for int types. // \todo Consider removing this function in Cortex 8 if ( v == int64_t(int(v)) ) { hash.append( int(v) ); } else { hash.append( v ); } } static long hash( MurmurHash *h ) { return h->h1(); } #define IECORETEST_ASSERT( x ) \ if( !( x ) ) \ { \ throw IECore::Exception( boost::str( \ boost::format( "Failed assertion \"%s\" : %s line %d" ) % #x % __FILE__ % __LINE__ \ ) ); \ } struct HashDispatchFunctor { template< class T> IECore::MurmurHash operator()( const T *data ) { IECore::MurmurHash result; result.append( data->readable() ); return result; } IECore::MurmurHash operator()( const IECore::Data *data ) { throw IECore::Exception( "Unsupported" ); } }; void testMurmurHashDispatch() { // If the dispatch can even compile, that means we have hash functions defined for all the types // that dispatch uses. We should also check a few types to make sure the Data dispatch actually works HashDispatchFunctor hashFunctor; IECore::MurmurHash h; h.append( 42.37f ); IECORETEST_ASSERT( h == IECore::dispatch( IECore::FloatDataPtr( new IECore::FloatData( 42.37 ) ).get(), hashFunctor ) ); h = IECore::MurmurHash(); h.append( std::string("foo") ); IECORETEST_ASSERT( h == IECore::dispatch( IECore::StringDataPtr( new IECore::StringData( "foo" ) ).get(), hashFunctor ) ); h = IECore::MurmurHash(); h.append( std::vector{ 1, 3, 37.03 } ); IECORETEST_ASSERT( h == IECore::dispatch( IECore::FloatVectorDataPtr( new IECore::FloatVectorData( std::vector{ 1, 3, 37.03 } ) ).get(), hashFunctor ) ); } } // namespace void IECorePython::bindMurmurHash() { class_( "MurmurHash" ) .def( init<>() ) .def( init() ) .def( init() ) .def( "append", (MurmurHash &(MurmurHash::*)( const float & ))&MurmurHash::append, return_self<>() ) .def( "append", (MurmurHash &(MurmurHash::*)( const double & ))&MurmurHash::append, return_self<>() ) .def( "append", &appendInt, return_self<>() ) .def( "append", (MurmurHash &(MurmurHash::*)( const std::string & ))&MurmurHash::append, return_self<>() ) .def( "append", (MurmurHash &(MurmurHash::*)( const InternedString & ))&MurmurHash::append, return_self<>() ) .def( "append", (MurmurHash &(MurmurHash::*)( const Imath::V2i & ))&MurmurHash::append, return_self<>() ) .def( "append", (MurmurHash &(MurmurHash::*)( const Imath::V2f & ))&MurmurHash::append, return_self<>() ) .def( "append", (MurmurHash &(MurmurHash::*)( const Imath::V2d & ))&MurmurHash::append, return_self<>() ) .def( "append", (MurmurHash &(MurmurHash::*)( const Imath::V3i & ))&MurmurHash::append, return_self<>() ) .def( "append", (MurmurHash &(MurmurHash::*)( const Imath::V3f & ))&MurmurHash::append, return_self<>() ) .def( "append", (MurmurHash &(MurmurHash::*)( const Imath::V3d & ))&MurmurHash::append, return_self<>() ) .def( "append", (MurmurHash &(MurmurHash::*)( const Imath::Color3f & ))&MurmurHash::append, return_self<>() ) .def( "append", (MurmurHash &(MurmurHash::*)( const Imath::Color4f & ))&MurmurHash::append, return_self<>() ) .def( "append", (MurmurHash &(MurmurHash::*)( const Imath::M33f & ))&MurmurHash::append, return_self<>() ) .def( "append", (MurmurHash &(MurmurHash::*)( const Imath::M33d & ))&MurmurHash::append, return_self<>() ) .def( "append", (MurmurHash &(MurmurHash::*)( const Imath::M44f & ))&MurmurHash::append, return_self<>() ) .def( "append", (MurmurHash &(MurmurHash::*)( const Imath::M44d & ))&MurmurHash::append, return_self<>() ) .def( "append", (MurmurHash &(MurmurHash::*)( const Imath::Box2i & ))&MurmurHash::append, return_self<>() ) .def( "append", (MurmurHash &(MurmurHash::*)( const Imath::Box2f & ))&MurmurHash::append, return_self<>() ) .def( "append", (MurmurHash &(MurmurHash::*)( const Imath::Box2d & ))&MurmurHash::append, return_self<>() ) .def( "append", (MurmurHash &(MurmurHash::*)( const Imath::Box3i & ))&MurmurHash::append, return_self<>() ) .def( "append", (MurmurHash &(MurmurHash::*)( const Imath::Box3f & ))&MurmurHash::append, return_self<>() ) .def( "append", (MurmurHash &(MurmurHash::*)( const Imath::Box3d & ))&MurmurHash::append, return_self<>() ) .def( "append", (MurmurHash &(MurmurHash::*)( const Imath::Quatf & ))&MurmurHash::append, return_self<>() ) .def( "append", (MurmurHash &(MurmurHash::*)( const Imath::Quatd & ))&MurmurHash::append, return_self<>() ) .def( "append", (MurmurHash &(MurmurHash::*)( const MurmurHash & ))&MurmurHash::append, return_self<>() ) // array append functions .def( "append", &appendArray, return_self<>() ) .def( "append", &appendArray, return_self<>() ) .def( "append", &appendArray, return_self<>() ) .def( "append", &appendArray, return_self<>() ) .def( "append", &appendArray, return_self<>() ) .def( "append", &appendArray, return_self<>() ) .def( "append", &appendArray, return_self<>() ) .def( "append", &appendArray, return_self<>() ) .def( "append", &appendArray, return_self<>() ) .def( "append", &appendArray, return_self<>() ) .def( "append", &appendArray, return_self<>() ) .def( "append", &appendArray, return_self<>() ) .def( "append", &appendArray, return_self<>() ) .def( "append", &appendArray, return_self<>() ) .def( "append", &appendArray, return_self<>() ) .def( "append", &appendArray, return_self<>() ) .def( "append", &appendArray, return_self<>() ) .def( "append", &appendArray, return_self<>() ) .def( "append", &appendArray, return_self<>() ) .def( "append", &appendArray, return_self<>() ) .def( "append", &appendArray, return_self<>() ) .def( "append", &appendArray, return_self<>() ) .def( "append", &appendArray, return_self<>() ) .def( "append", &appendArray, return_self<>() ) .def( "append", &appendArray, return_self<>() ) .def( "append", &appendArray, return_self<>() ) .def( "append", &appendArray, return_self<>() ) .def( "append", &appendArray, return_self<>() ) .def( "append", &appendArray, return_self<>() ) .def( "append", &appendArray, return_self<>() ) .def( "append", &appendArray, return_self<>() ) .def( "append", &appendArray, return_self<>() ) .def( "append", &appendArray, return_self<>() ) .def( "append", &appendArray, return_self<>() ) .def( self == self ) .def( self != self ) .def( self < self ) .def( "copyFrom", &MurmurHash::operator=, return_self<>() ) .def( "__repr__", &repr ) .def( "__str__", &MurmurHash::toString ) .def( "__hash__", &hash ) .def( "toString", &MurmurHash::toString ) .def( "h1", &MurmurHash::h1 ) .def( "h2", &MurmurHash::h2 ) ; def( "testMurmurHashDispatch", &testMurmurHashDispatch ); } #include "core.h" #include "rosagame.h" #include "wbeventmanager.h" #include "rosaframework.h" #include "rosaworld.h" #include "wbworld.h" #include "rosasaveload.h" #include "rosapersistence.h" #include "rosacampaign.h" #include "rosamusic.h" #include "rosaconversation.h" #include "rosasupertitles.h" #include "rosahudlog.h" #include "rosawardrobe.h" #include "rosalockpicking.h" #include "configmanager.h" #include "texturemanager.h" #include "irenderer.h" #include "mesh.h" #include "rosatargetmanager.h" #include "meshfactory.h" #include "irendertarget.h" #include "shadermanager.h" #include "Common/uimanagercommon.h" #include "uiscreen.h" #include "uiwidget.h" #include "uistack.h" #include "Components/wbcomprosahealth.h" #include "Components/wbcomprosatransform.h" #include "Components/wbcomprosacamera.h" #include "Components/wbcomprosaplayer.h" #include "Components/wbcomprosavisible.h" #include "Components/wbcomprosacollision.h" #include "Widgets/uiwidget-image.h" #include "allocator.h" #include "wbcomponentarrays.h" #include "ivertexdeclaration.h" #include "rosadifficulty.h" #include "mathcore.h" #include "iaudiosystem.h" #include "hsv.h" #if BUILD_WINDOWS #include // For ShellExecute #endif RosaGame::RosaGame() : m_GoToLevelInNumTicks( 0 ) , m_IsRestarting( false ) , m_IsReturningToHub( false ) , m_RestoreSpawnPoint( false ) , m_TeleportLabel() , m_NextLevelName() , m_LoadSlotInNumTicks( 0 ) , m_LoadSlotName() , m_CurrentLevelName() , m_TravelPersistence() , m_SaveLoad( NULL ) , m_GenerationPersistence( NULL ) , m_Campaign( NULL ) , m_Music( NULL ) , m_Conversation( NULL ) , m_Supertitles( NULL ) , m_HUDLog( NULL ) , m_Wardrobe( NULL ) , m_Lockpicking( NULL ) , m_Gamma( 0.0f ) , m_GlobalCubemap( NULL ) , m_GlobalAmbientQuad( NULL ) , m_UpscaleQuad( NULL ) , m_PostQuad( NULL ) , m_PostCheapQuad( NULL ) , m_UsePostCheapQuad( false ) #if BUILD_ROSA_TOOLS , m_PostToolsQuad( NULL ) #endif , m_SSAOQuad( NULL ) , m_GradientQuad( NULL ) , m_EdgeQuad( NULL ) , m_LightCombineQuad( NULL ) #if ROSA_USE_WATERCOLOR_POST , m_EdgeQuad( NULL ) #endif , m_BloomQuads() , m_FXAAQuad( NULL ) , m_MinimapBQuad( NULL ) , m_MinimapFXAAQuad( NULL ) , m_MinimapTonesTexture() , m_MinimapFloorTexture() , m_MinimapSolidTexture() , m_MinimapHeightThreshold( 0.0f ) , m_MinimapHeightOffset( 0.0f ) , m_MinimapHeightDiffScale( 0.0f ) , m_MinimapHeightToneScale( 0.0f ) , m_MinimapRenderEdges( 0.0f ) , m_MinimapRcpTileSize( 0.0f ) #if ROSA_USE_MAXIMAP , m_MaximapBQuad( NULL ) , m_MaximapFXAAQuad( NULL ) #endif , m_ColorGradingTexture() , m_NoiseTexture() , m_NoiseScaleRange() , m_NoiseRange( 0.0f ) , m_HalosEnabled( false ) , m_DirtyLensTexture() , m_BloomKernelTexture() , m_DisplaceTexture() , m_BlotTexture() , m_CanvasTexture() , m_EdgeColorHSV() , m_EdgeBackColor() , m_EdgeColor() , m_EdgeLuminanceMul( 0.0f ) , m_EdgeLuminanceAdd( 0.0f ) , m_WatercolorParams() , m_DisplacePct( 0.0f ) , m_FogEnabled( false ) , m_FogColors() , m_FogNearFarCurve() , m_FogLoHiCurve() , m_FogParams() , m_HeightFogParams() , m_RegionFogScalar() , m_FogLightParams() , m_SunVector() , m_SkyColorHi() , m_SkyColorLo() , m_WindMatrix() , m_WindPhaseTime() , m_WindPhaseSpace() , m_WindWaterVector() , m_InvExposure( 0.0f ) , m_BloomVerticalRadius( 0.0f ) , m_BloomAspectRatio( 0.0f ) , m_BloomStepRadiusH() , m_BloomStepRadiusV() , m_BloomParams() , m_ReturnVerticalBloomRadius( false ) , m_CurrentMinimapScalar( 0.0f ) , m_CurrentMusic() , m_CurrentAmbience() , m_CurrentReverbDef() { m_MinimapTonesTexture = DEFAULT_TEXTURE; m_MinimapFloorTexture = DEFAULT_TEXTURE; m_MinimapSolidTexture = DEFAULT_TEXTURE; m_ColorGradingTexture = DEFAULT_TEXTURE; m_NoiseTexture = DEFAULT_TEXTURE; m_DirtyLensTexture = DEFAULT_TEXTURE; m_BloomKernelTexture = DEFAULT_TEXTURE; m_DisplaceTexture = DEFAULT_TEXTURE; m_BlotTexture = DEFAULT_TEXTURE; m_CanvasTexture = DEFAULT_TEXTURE; m_SaveLoad = new RosaSaveLoad; m_GenerationPersistence = new RosaPersistence; m_Campaign = new RosaCampaign; m_Music = new RosaMusic; m_Conversation = new RosaConversation; m_Supertitles = new RosaSupertitles; m_HUDLog = new RosaHUDLog; m_Wardrobe = new RosaWardrobe; m_Lockpicking = new RosaLockpicking; } RosaGame::~RosaGame() { SafeDelete( m_SaveLoad ); SafeDelete( m_GenerationPersistence ); SafeDelete( m_Campaign ); SafeDelete( m_Music ); SafeDelete( m_Conversation ); SafeDelete( m_Supertitles ); SafeDelete( m_HUDLog ); SafeDelete( m_Wardrobe ); SafeDelete( m_Lockpicking ); SafeDelete( m_GlobalAmbientQuad ); SafeDelete( m_UpscaleQuad ); SafeDelete( m_PostQuad ); SafeDelete( m_PostCheapQuad ); #if BUILD_ROSA_TOOLS SafeDelete( m_PostToolsQuad ); #endif SafeDelete( m_SSAOQuad ); SafeDelete( m_GradientQuad ); SafeDelete( m_EdgeQuad ); SafeDelete( m_LightCombineQuad ); #if ROSA_USE_WATERCOLOR_POST SafeDelete( m_EdgeQuad ); #endif SafeDelete( m_FXAAQuad ); SafeDelete( m_MinimapBQuad ); SafeDelete( m_MinimapFXAAQuad ); #if ROSA_USE_MAXIMAP SafeDelete( m_MaximapBQuad ); SafeDelete( m_MaximapFXAAQuad ); #endif FOR_EACH_ARRAY( BloomQuadIter, m_BloomQuads, Mesh* ) { Mesh* pBloomQuad = BloomQuadIter.GetValue(); SafeDelete( pBloomQuad ); } } void RosaGame::SetCurrentLevelName( const SimpleString& LevelName ) { XTRACE_FUNCTION; m_CurrentLevelName = LevelName; const SimpleString LevelFriendlyName = GetCurrentFriendlyLevelName(); STATICHASH( HUD ); STATICHASH( WorldName ); ConfigManager::SetString( sWorldName, LevelFriendlyName.CStr(), sHUD ); } SimpleString RosaGame::GetCurrentFriendlyLevelName() const { XTRACE_FUNCTION; return GetFriendlyLevelName( m_CurrentLevelName ); } /*static*/ SimpleString RosaGame::GetFriendlyLevelName( const SimpleString& LevelName ) { XTRACE_FUNCTION; MAKEHASH( LevelName ); STATICHASH( Name ); return ConfigManager::GetString( sName, "", sLevelName ); } void RosaGame::ClearTravelPersistence() { m_TravelPersistence.Clear(); } /*static*/ TPersistence& RosaGame::StaticGetTravelPersistence() { return RosaFramework::GetInstance()->GetGame()->GetTravelPersistence(); } // NOTE: Player component forwards all its events to this function, // so the game can be targeted from script via the player, and it // doesn't have to register for events. /*virtual*/ void RosaGame::HandleEvent( const WBEvent& Event ) { XTRACE_FUNCTION; STATIC_HASHED_STRING( GoToInitialLevel ); STATIC_HASHED_STRING( GoToHubLevel ); STATIC_HASHED_STRING( GoToNextLevel ); STATIC_HASHED_STRING( GoToPrevLevel ); STATIC_HASHED_STRING( GoToLevel ); STATIC_HASHED_STRING( GoToTitleLevel ); STATIC_HASHED_STRING( Checkpoint ); STATIC_HASHED_STRING( Autosave ); STATIC_HASHED_STRING( FlushWorldFiles ); STATIC_HASHED_STRING( PlayMusic ); STATIC_HASHED_STRING( PlayMusicAndAmbience ); STATIC_HASHED_STRING( StopMusic ); STATIC_HASHED_STRING( StopMusicAndAmbience ); STATIC_HASHED_STRING( SetMusicLevels ); STATIC_HASHED_STRING( LaunchWebSite ); STATIC_HASHED_STRING( OpenUserDataPath ); STATIC_HASHED_STRING( GoToLevelImmediate ); STATIC_HASHED_STRING( StartConversation ); STATIC_HASHED_STRING( SkipConversationLine ); STATIC_HASHED_STRING( ProgressConversation ); STATIC_HASHED_STRING( SelectConversationChoice ); STATIC_HASHED_STRING( StartSupertitles ); STATIC_HASHED_STRING( CycleMenuDifficulty ); STATIC_HASHED_STRING( SetMenuDifficulty ); const HashedString EventName = Event.GetEventName(); if( EventName == sGoToInitialLevel ) { RequestGoToInitialLevel(); } else if( EventName == sGoToHubLevel ) { RequestGoToHubLevel(); } else if( EventName == sGoToNextLevel ) { STATIC_HASHED_STRING( TeleportLabel ); const HashedString TeleportLabel = Event.GetHash( sTeleportLabel ); RequestGoToNextLevel( TeleportLabel ); } else if( EventName == sGoToPrevLevel ) { STATIC_HASHED_STRING( TeleportLabel ); const HashedString TeleportLabel = Event.GetHash( sTeleportLabel ); RequestGoToPrevLevel( TeleportLabel ); } else if( EventName == sGoToLevel ) { STATIC_HASHED_STRING( Level ); const SimpleString Level = Event.GetString( sLevel ); STATIC_HASHED_STRING( TeleportLabel ); const HashedString TeleportLabel = Event.GetHash( sTeleportLabel ); STATIC_HASHED_STRING( SuppressLoadingScreen ); const bool SuppressLoadingScreen = Event.GetBool( sSuppressLoadingScreen ); RequestGoToLevel( Level, TeleportLabel, SuppressLoadingScreen ); } else if( EventName == sGoToTitleLevel ) { RequestReturnToTitle(); } else if( EventName == sCheckpoint || EventName == sAutosave ) { Autosave(); } else if( EventName == sFlushWorldFiles ) { GetSaveLoad()->FlushWorldFiles(); } else if( EventName == sLaunchWebSite ) { STATIC_HASHED_STRING( URL ); const SimpleString URL = Event.GetString( sURL ); LaunchWebSite( URL ); } else if( EventName == sOpenUserDataPath ) { OpenUserDataPath(); } else if( EventName == sPlayMusic ) { STATIC_HASHED_STRING( Music ); const SimpleString Music = Event.GetString( sMusic ); const SimpleString MusicDef = ( Music == "" ) ? m_CurrentMusic : Music; STATIC_HASHED_STRING( TrackBits ); const uint TrackBits = Event.GetInt( sTrackBits ); STATIC_HASHED_STRING( TrackMask ); const uint TrackMask = Event.GetInt( sTrackMask, -1 ); m_Music->PlayMusic( MusicDef, TrackBits, TrackMask ); } else if( EventName == sPlayMusicAndAmbience ) { STATIC_HASHED_STRING( Music ); const SimpleString MusicDef = Event.GetString( sMusic, m_CurrentMusic ); STATIC_HASHED_STRING( TrackBits ); const uint TrackBits = Event.GetInt( sTrackBits ); STATIC_HASHED_STRING( TrackMask ); const uint TrackMask = Event.GetInt( sTrackMask, -1 ); STATIC_HASHED_STRING( Ambience ); const SimpleString AmbienceDef = Event.GetString( sAmbience, m_CurrentAmbience ); m_Music->PlayMusic( MusicDef, TrackBits, TrackMask ); m_Music->PlayAmbience( AmbienceDef ); } else if( EventName == sStopMusic ) { m_Music->StopMusic(); } else if( EventName == sStopMusicAndAmbience ) { m_Music->StopMusic(); m_Music->StopAmbience(); } else if( EventName == sSetMusicLevels ) { STATIC_HASHED_STRING( TrackBits ); const uint TrackBits = Event.GetInt( sTrackBits ); STATIC_HASHED_STRING( TrackMask ); const uint TrackMask = Event.GetInt( sTrackMask, -1 ); STATIC_HASHED_STRING( Duration ); const float Duration = Event.GetFloat( sDuration ); m_Music->SetMusicLevels( TrackBits, TrackMask, Duration ); } else if( EventName == sGoToLevelImmediate ) { // This should only be called after we've queued a go-to. ASSERT( m_GoToLevelInNumTicks > 0 ); if( m_GoToLevelInNumTicks > 0 ) { GoToLevel(); } } else if( EventName == sStartConversation ) { STATIC_HASHED_STRING( Conversation ); const HashedString Conversation = Event.GetHash( sConversation ); STATIC_HASHED_STRING( ConvoTarget ); WBEntity* const pConvoTarget = Event.GetEntity( sConvoTarget ); m_Conversation->StartConversation( Conversation, pConvoTarget ); } else if( EventName == sSkipConversationLine ) { m_Conversation->SkipLine(); } else if( EventName == sProgressConversation ) { m_Conversation->ProgressConversation(); } else if( EventName == sSelectConversationChoice ) { STATIC_HASHED_STRING( ChoiceIndex ); const uint ChoiceIndex = Event.GetInt( sChoiceIndex ); m_Conversation->SelectChoice( ChoiceIndex ); } else if( EventName == sStartSupertitles ) { STATIC_HASHED_STRING( Supertitles ); const HashedString Supertitles = Event.GetHash( sSupertitles ); m_Supertitles->StartSupertitles( Supertitles ); } else if( EventName == sCycleMenuDifficulty ) { RosaDifficulty::CycleMenuDifficulty(); } else if( EventName == sSetMenuDifficulty ) { STATIC_HASHED_STRING( Difficulty ); const uint Difficulty = Event.GetInt( sDifficulty ); RosaDifficulty::SetMenuDifficulty( Difficulty ); } } void RosaGame::Initialize() { // If we need to load any state on the title screen (like // campaign state for a single-profile game), do it here. //GetSaveLoad()->TryLoadAutosave( 0 ); SetCurrentLevelName( GetTitleScreenLevelName() ); MAKEHASH( m_CurrentLevelName ); STATICHASH( WorldDef ); const SimpleString TitleScreenWorldDef = ConfigManager::GetString( sWorldDef, "", sm_CurrentLevelName ); RosaFramework* const pFramework = RosaFramework::GetInstance(); RosaWorld* const pWorld = pFramework->GetWorld(); pWorld->SetCurrentWorld( TitleScreenWorldDef ); pWorld->Create(); pFramework->InitializeTools(); RefreshUIRetreatEnabled(); } void RosaGame::ShutDown() { PRINTF( "Shutting down game\n" ); m_Lockpicking->ShutDown(); Autosave(); GetSaveLoad()->FlushWorldFiles(); } void RosaGame::Tick( const float DeltaTime ) { XTRACE_FUNCTION; GetSupertitles()->Tick(); m_Lockpicking->Tick( DeltaTime ); m_HUDLog->Tick(); m_Music->Tick( DeltaTime ); // This is done in a tick instead of being event-driven, // because it needs to happen before the world tick. if( m_GoToLevelInNumTicks > 0 && --m_GoToLevelInNumTicks == 0 ) { GoToLevel(); } if( m_LoadSlotInNumTicks > 0 && --m_LoadSlotInNumTicks == 0 ) { LoadSlot(); } } void RosaGame::TickPaused( const float DeltaTime ) { // Tick conversation when we're paused because the convo screen pauses the game GetConversation()->Tick(); m_Music->Tick( DeltaTime ); if( m_GoToLevelInNumTicks > 0 && --m_GoToLevelInNumTicks == 0 ) { GoToLevel(); } if( m_LoadSlotInNumTicks > 0 && --m_LoadSlotInNumTicks == 0 ) { LoadSlot(); } } void RosaGame::Render() const { XTRACE_FUNCTION; // HACKHACK so I'm not doing so many lookups for player feet in minimap SDPs CachePlayerFeetLocation(); RosaFramework* const pFramework = RosaFramework::GetInstance(); ASSERT( pFramework ); IRenderer* const pRenderer = pFramework->GetRenderer(); ASSERT( pRenderer ); pRenderer->AddMesh( GetGlobalAmbientQuad() ); pRenderer->AddMesh( GetSSAOQuad() ); pRenderer->AddMesh( GetGradientQuad() ); pRenderer->AddMesh( GetEdgeQuad() ); pRenderer->AddMesh( GetLightCombineQuad() ); #if ROSA_USE_WATERCOLOR_POST pRenderer->AddMesh( GetEdgeQuad() ); #endif pRenderer->AddMesh( m_UsePostCheapQuad ? GetPostCheapQuad() : GetPostQuad() ); #if BUILD_ROSA_TOOLS pRenderer->AddMesh( m_PostToolsQuad ); #endif pRenderer->AddMesh( GetFXAAQuad() ); pRenderer->AddMesh( GetMinimapBQuad() ); pRenderer->AddMesh( GetMinimapFXAAQuad() ); #if ROSA_USE_MAXIMAP pRenderer->AddMesh( GetMaximapBQuad() ); pRenderer->AddMesh( GetMaximapFXAAQuad() ); #endif pRenderer->AddMesh( GetUpscaleQuad() ); FOR_EACH_ARRAY( BloomQuadIter, m_BloomQuads, Mesh* ) { Mesh* const pBloomQuad = BloomQuadIter.GetValue(); pRenderer->AddMesh( pBloomQuad ); } } void RosaGame::RequestReturnToTitle() { XTRACE_FUNCTION; DEVPRINTF( "RosaGame::RequestReturnToTitle\n" ); const SimpleString TitleScreenLevelName = GetTitleScreenLevelName(); const HashedString TeleportLabel = HashedString::NullString; const bool RestoreSpawnPoint = false; const bool SuppressLoadingScreen = false; RequestGoToLevelInternal( TitleScreenLevelName, TeleportLabel, RestoreSpawnPoint, SuppressLoadingScreen ); m_IsRestarting = true; ClearTravelPersistence(); // Make sure we don't pull persistence over any default inventory, etc. } void RosaGame::RequestGoToInitialLevel() { XTRACE_FUNCTION; DEVPRINTF( "RosaGame::RequestGoToInitialLevel\n" ); const SimpleString InitialLevelName = GetInitialLevelName(); const HashedString TeleportLabel = HashedString::NullString; const bool RestoreSpawnPoint = false; const bool SuppressLoadingScreen = false; RequestGoToLevelInternal( InitialLevelName, TeleportLabel, RestoreSpawnPoint, SuppressLoadingScreen ); m_IsRestarting = true; ClearTravelPersistence(); // Make sure we don't pull persistence over any default inventory, etc. } void RosaGame::RequestGoToHubLevel() { XTRACE_FUNCTION; DEVPRINTF( "RosaGame::RequestGoToHubLevel\n" ); const SimpleString HubLevelName = GetHubLevelName(); const HashedString TeleportLabel = HashedString::NullString; const bool RestoreSpawnPoint = false; const bool SuppressLoadingScreen = false; RequestGoToLevelInternal( HubLevelName, TeleportLabel, RestoreSpawnPoint, SuppressLoadingScreen ); m_IsReturningToHub = true; } void RosaGame::RequestGoToNextLevel( const HashedString& TeleportLabel ) { XTRACE_FUNCTION; DEVPRINTF( "RosaGame::RequestGoToNextLevel\n" ); MAKEHASH( m_CurrentLevelName ); STATICHASH( NextLevel ); const SimpleString NextLevelName = ConfigManager::GetString( sNextLevel, "", sm_CurrentLevelName ); const bool RestoreSpawnPoint = true; const bool SuppressLoadingScreen = false; RequestGoToLevelInternal( NextLevelName, TeleportLabel, RestoreSpawnPoint, SuppressLoadingScreen ); } void RosaGame::RequestGoToPrevLevel( const HashedString& TeleportLabel ) { XTRACE_FUNCTION; DEVPRINTF( "RosaGame::RequestGoToPrevLevel\n" ); MAKEHASH( m_CurrentLevelName ); STATICHASH( PrevLevel ); const SimpleString PrevLevelName = ConfigManager::GetString( sPrevLevel, "", sm_CurrentLevelName ); const bool RestoreSpawnPoint = false; const bool SuppressLoadingScreen = false; RequestGoToLevelInternal( PrevLevelName, TeleportLabel, RestoreSpawnPoint, SuppressLoadingScreen ); } void RosaGame::RequestGoToLevel( const SimpleString& NextLevel, const HashedString& TeleportLabel, const bool SuppressLoadingScreen ) { XTRACE_FUNCTION; DEVPRINTF( "RosaGame::RequestGoToLevel %s\n", NextLevel.CStr() ); const bool RestoreSpawnPoint = false; RequestGoToLevelInternal( NextLevel, TeleportLabel, RestoreSpawnPoint, SuppressLoadingScreen ); } void RosaGame::RequestGoToLevelInternal( const SimpleString& NextLevel, const HashedString& TeleportLabel, const bool RestoreSpawnPoint, const bool SuppressLoadingScreen ) { XTRACE_FUNCTION; if( NextLevel == "" ) { WARN; return; } if( m_GoToLevelInNumTicks > 0 || m_LoadSlotInNumTicks > 0 ) { // We have something scheduled already! return; } // NOTE: No longer doing a crash protection checkpoint save; // level transitions should be stable, and the player may be // intersecting a level end trigger at this point so the // checkpoint state would not be good! ASSERT( m_GoToLevelInNumTicks == 0 ); m_GoToLevelInNumTicks = 2; // Add an extra tick so we get a chance to show the "Loading..." UI before starting the load m_RestoreSpawnPoint = RestoreSpawnPoint; m_TeleportLabel = TeleportLabel; m_NextLevelName = NextLevel; WBEventManager* const pEventManager = WBWorld::GetInstance()->GetEventManager(); WB_MAKE_EVENT( PreLevelTransition, NULL ); WB_DISPATCH_EVENT( pEventManager, PreLevelTransition, NULL ); if( !SuppressLoadingScreen ) { // Push the loading screen STATIC_HASHED_STRING( LoadingScreen ); WB_MAKE_EVENT( PushUIScreen, NULL ); WB_SET_AUTO( PushUIScreen, Hash, Screen, sLoadingScreen ); WB_DISPATCH_EVENT( pEventManager, PushUIScreen, NULL ); // HACKHACK: Force the loading screen to render RosaFramework::GetInstance()->RequestRenderTick(); } } void RosaGame::RequestLoadSlot( const SimpleString& Slot ) { XTRACE_FUNCTION; if( Slot == "" ) { WARN; return; } RosaSaveLoad::SSaveSlotInfo SlotInfo; RosaSaveLoad::GetSaveSlotInfo( Slot, SlotInfo ); if( SlotInfo.m_Empty ) { return; } if( m_GoToLevelInNumTicks > 0 || m_LoadSlotInNumTicks > 0 ) { // We have something scheduled already! return; } // *Don't* checkpoint when loading a slot ASSERT( m_LoadSlotInNumTicks == 0 ); m_LoadSlotInNumTicks = 2; // Add an extra tick so we get a chance to show the "Loading..." UI before starting the load m_LoadSlotName = Slot; // Push the loading screen STATIC_HASHED_STRING( LoadingScreen ); WB_MAKE_EVENT( PushUIScreen, NULL ); WB_SET_AUTO( PushUIScreen, Hash, Screen, sLoadingScreen ); WB_DISPATCH_EVENT( WBWorld::GetInstance()->GetEventManager(), PushUIScreen, NULL ); // HACKHACK: Force the loading screen to render RosaFramework::GetInstance()->RequestRenderTick(); } void RosaGame::LoadSlot() { m_LoadSlotInNumTicks = 0; const bool ForceResetToGameScreens = true; RosaFramework::GetInstance()->PrepareForLoad( ForceResetToGameScreens ); GetSaveLoad()->TryLoadSlot( m_LoadSlotName ); } // ROSANOTE: No longer decorating the world filename with the save/load path, // because that prevents migration of the saved game to other accounts/systems. SimpleString RosaGame::DecorateWorldFileName( const SimpleString& LevelName ) const { return SimpleString::PrintF( "%s.rosaworldsave", LevelName.CStr() ); } void RosaGame::Autosave() const { XTRACE_FUNCTION; if( GetSaveLoad()->ShouldSaveCurrentWorld() ) { #if ROSA_USE_ACTIVESAVESLOT // Save directly to slot instead of autosaves GetSaveLoad()->SaveSlot( GetSaveLoad()->GetActiveSaveSlot() ); #else GetSaveLoad()->SaveAutosave(); #endif } } void RosaGame::GoToLevel() { XTRACE_FUNCTION; DEVPRINTF( "RosaGame::GoToLevel: %s\n", m_NextLevelName.CStr() ); // This may modify m_NextLevelName PreGoToLevel(); PRINTF( "Traveling to level %s\n", m_NextLevelName.CStr() ); m_GoToLevelInNumTicks = 0; m_IsRestarting = false; m_IsReturningToHub = false; SetCurrentLevelName( m_NextLevelName ); // ZETANOTE: I don't expect the player to return to serialized/persistent // worlds in this game, so no need to try to load the world from file. #if ROSA_USE_PERSISTENT_WORLDS // Try to load persistent world data first, else create the world. if( GetSaveLoad()->TryLoadWorld( DecorateWorldFileName( m_NextLevelName ) ) ) { // We're good! } else #endif { // HACKHACK: Allow the campaign to override the world def; this lets me evolve the hub // without it being influenced by e.g. dark/dusk/foggy twists from the selected mission. // CAMTODO: Revisit this, it may not be needed and could simplify campaign code by getting rid of the ForceModify stuff. // (Basically, do I need to modify the hub or can I use actually different hub levels? Or maybe I want both?) STATICHASH( WorldDef ); const SimpleString WorldDef = GetCampaign()->OverrideString( m_NextLevelName, ConfigManager::GetString( sWorldDef, "", m_NextLevelName ), true /*ForceModify*/ ); DEVASSERT( WorldDef != "" ); RosaFramework::GetInstance()->GoToLevel( WorldDef ); } PostGoToLevel(); PRINTF( "Travel finished\n" ); } void RosaGame::PreGoToLevel() { // CAMTODO: I may want to introduce a third option here, between "restarting" (resetting everything) // and "returning to hub" (advancing to the next stage), for failing and restarting in the roguelike // while keeping persistence. This was sort of handled in Vamp by failing at the campaign level and // advancing to the next legacy, but here it'll probably also be linked to loading into a different // map so I might as well model it at the game level. if( m_IsRestarting ) // Completely restarting game, clearing persistence (i.e., returning to title or starting a new game) { DEVPRINTF( "RosaGame::PreGoToLevel: m_IsRestarting\n" ); // Don't save the current world, and flush everything including persistence. GetSaveLoad()->FlushWorldFiles(); // I think this sort of persistence is only used for tutorials and achievements. // If those should be persistent between profiles/slots, don't clear this, but I // think this is the best option. GetPersistence()->Reset(); // Reset the campaign and take the first turn GetCampaign()->Reset(); GetCampaign()->TakePreGenTurn(); } else if( m_IsReturningToHub ) // Returning to hub within a game, flushing world files but keeping persistence { DEVPRINTF( "RosaGame::PreGoToLevel: m_IsReturningToHub\n" ); #if !ROSA_USE_PERSISTENT_WORLDS // CAMTODO: Figure out what the "hub" will be in light of roguelike campaign/persistence structure. // I'll probably need separate initial level and hub maps, which will do different campaign things. // Probably get rid of "Overworld" map and make "Start" and "Hub" maps instead. Or call them, like, // "Home" and "Camp" or whatever fictional purpose they serve. // CAMTODO: Get rid of this warning when the above part is done. Or make a different #define // instead of ROSA_USE_PERSISTENT_WORLDS that suits what I'm trying to do here. // ZETANOTE: There is no hub anymore, we should never get here WARNDESC( "Returning to hub; this should never happen in Zeta." ); #endif // Don't save the current world, and flush any other world files. // ROSANOTE: In Eldritch, I had to defer this flush so I could return to the // previous instance of the hub. In Rosa, I'm building a new hub every time. GetSaveLoad()->FlushWorldFiles(); // The campaign needs to run some things in the hub before world generation GetCampaign()->TakePreGenTurn(); } else { DEVPRINTF( "RosaGame::PreGoToLevel\n" ); // ZETANOTE: I don't expect the player to return to serialized/persistent // worlds in this game, so no need to save the world (which also means no // need to manually flush world files. // ZETANOTE: Except I _might_ serialize the overworld. Probably best to // avoid that unless there's a compelling reason, though. #if ROSA_USE_PERSISTENT_WORLDS // Store a record of the world we're leaving so we can come back to it. if( GetSaveLoad()->ShouldSaveCurrentWorld() ) { GetSaveLoad()->SaveWorld( DecorateWorldFileName( m_CurrentLevelName ) ); } #endif } } void RosaGame::PostGoToLevel() { RefreshUIRetreatEnabled(); WBEventManager* const pEventManager = WBWorld::GetInstance()->GetEventManager(); WB_MAKE_EVENT( PostLevelTransition, NULL ); WB_SET_AUTO( PostLevelTransition, Bool, RestoreSpawnPoint, m_RestoreSpawnPoint ); WB_SET_AUTO( PostLevelTransition, Hash, TeleportLabel, m_TeleportLabel ); WB_DISPATCH_EVENT( pEventManager, PostLevelTransition, NULL ); // Make a checkpoint save, for crash protection // (Queued because we want to pump the event queue once to initialize the world.) WB_MAKE_EVENT( Checkpoint, NULL ); WB_LOG_EVENT( Checkpoint ); WB_QUEUE_EVENT( pEventManager, Checkpoint, this ); // Clear travel persistence now that we've successfully traveled and don't need it. ClearTravelPersistence(); } void RosaGame::RefreshRTDependentSystems() { XTRACE_FUNCTION; CreateGlobalAmbientQuad(); CreatePostQuad(); CreateSSAOQuad(); CreateGradientQuad(); CreateEdgeQuad(); CreateLightCombineQuad(); #if ROSA_USE_WATERCOLOR_POST CreateEdgeQuad(); #endif CreateBloomQuads(); CreateFXAAQuad(); CreateMinimapBQuad(); CreateMinimapFXAAQuad(); #if ROSA_USE_MAXIMAP CreateMaximapBQuad(); CreateMaximapFXAAQuad(); #endif CreateUpscaleQuad(); UpdateMinimap(); #if ROSA_USE_MAXIMAP UpdateMaximap(); #endif RefreshBloomParams(); // Notify the world and any other observers that RTs are updated WBEventManager* const pEventManager = WBWorld::GetInstance()->GetEventManager(); RosaWorld* const pWorld = RosaFramework::GetInstance()->GetWorld(); WB_MAKE_EVENT( OnRenderTargetsUpdated, NULL ); WB_DISPATCH_EVENT( pEventManager, OnRenderTargetsUpdated, pWorld ); } void RosaGame::UpdateMinimap() { XTRACE_FUNCTION; UIWidgetImage* const pMinimapImage = GetMinimapImage(); if( !pMinimapImage ) { return; } RosaFramework* const pFramework = RosaFramework::GetInstance(); DEVASSERT( pFramework ); RosaTargetManager* const pTargetManager = pFramework->GetTargetManager(); DEVASSERT( pTargetManager ); STATIC_HASHED_STRING( MinimapA ); IRenderTarget* const pMinimapART = pTargetManager->GetRenderTarget( sMinimapA ); DEVASSERT( pMinimapART ); ITexture* const pTexture = pMinimapART->GetColorTextureHandle( 0 ); DEVASSERT( pTexture ); pMinimapImage->SetTexture( pTexture, 0 ); } #if ROSA_USE_MAXIMAP void RosaGame::UpdateMaximap() { XTRACE_FUNCTION; UIWidgetImage* const pMaximapImage = GetMaximapImage(); if( !pMaximapImage ) { return; } RosaFramework* const pFramework = RosaFramework::GetInstance(); DEVASSERT( pFramework ); RosaTargetManager* const pTargetManager = pFramework->GetTargetManager(); DEVASSERT( pTargetManager ); STATIC_HASHED_STRING( MaximapA ); IRenderTarget* const pMaximapART = pTargetManager->GetRenderTarget( sMaximapA ); DEVASSERT( pMaximapART ); ITexture* const pTexture = pMaximapART->GetColorTextureHandle( 0 ); DEVASSERT( pTexture ); pMaximapImage->SetTexture( pTexture, 0 ); } #endif void RosaGame::SetGlobalCubemap( ITexture* const pCubemap ) { XTRACE_FUNCTION; m_GlobalCubemap = pCubemap; DEVASSERT( m_GlobalAmbientQuad ); if( !m_GlobalAmbientQuad ) { return; } m_GlobalAmbientQuad->SetTexture( 3, GetGlobalCubemap() ); } void RosaGame::CreateGlobalAmbientQuad() { XTRACE_FUNCTION; SafeDelete( m_GlobalAmbientQuad ); RosaFramework* const pFramework = RosaFramework::GetInstance(); Display* const pDisplay = pFramework->GetDisplay(); IRenderer* const pRenderer = pFramework->GetRenderer(); RosaTargetManager* const pTargetManager = pFramework->GetTargetManager(); m_GlobalAmbientQuad = CreateFullscreenQuad( pDisplay->m_Width, pDisplay->m_Height, "GlobalAmbient", "Material_GlobalAmbient" ); m_GlobalAmbientQuad->SetVertexDeclaration( pRenderer->GetVertexDeclaration( VD_POSITIONS ) ); // We don't use UVs for ambient light shaders m_GlobalAmbientQuad->SetTexture( 0, pTargetManager->GetRenderTarget( "GB_Albedo" )->GetColorTextureHandle( 0 ) ); m_GlobalAmbientQuad->SetTexture( 1, pTargetManager->GetRenderTarget( "GB_Normal" )->GetColorTextureHandle( 0 ) ); m_GlobalAmbientQuad->SetTexture( 2, pTargetManager->GetRenderTarget( "GB_Depth" )->GetColorTextureHandle( 0 ) ); m_GlobalAmbientQuad->SetTexture( 3, GetGlobalCubemap() ); } void RosaGame::CreateUpscaleQuad() { XTRACE_FUNCTION; SafeDelete( m_UpscaleQuad ); RosaFramework* const pFramework = RosaFramework::GetInstance(); Display* const pDisplay = pFramework->GetDisplay(); RosaTargetManager* const pTargetManager = pFramework->GetTargetManager(); // Accomodate different aspect ratios by using the proportional dimensions const float LocationX = static_cast( ( pDisplay->m_FrameWidth - pDisplay->m_PropWidth ) / 2 ); const float LocationY = static_cast( ( pDisplay->m_FrameHeight - pDisplay->m_PropHeight ) / 2 ); m_UpscaleQuad = CreateFullscreenQuad( pDisplay->m_PropWidth, pDisplay->m_PropHeight, "Upscale", "Material_Upscale" ); m_UpscaleQuad->SetTexture( 0, pTargetManager->GetRenderTarget( "UI" )->GetColorTextureHandle( 0 ) ); m_UpscaleQuad->m_Location.x += LocationX; m_UpscaleQuad->m_Location.z += LocationY; } void RosaGame::CreatePostQuad() { XTRACE_FUNCTION; SafeDelete( m_PostQuad ); SafeDelete( m_PostCheapQuad ); RosaFramework* const pFramework = RosaFramework::GetInstance(); Display* const pDisplay = pFramework->GetDisplay(); IRenderer* const pRenderer = pFramework->GetRenderer(); RosaTargetManager* const pTargetManager = pFramework->GetTargetManager(); TextureManager* const pTextureManager = pRenderer->GetTextureManager(); #if ROSA_USE_FILMIC_POST m_PostQuad = CreateFullscreenQuad( pDisplay->m_Width, pDisplay->m_Height, "Post", "Material_Post" ); m_PostQuad->SetTexture( 0, pTargetManager->GetRenderTarget( "Primary" )->GetColorTextureHandle( 0 ) ); m_PostQuad->SetTexture( 1, pTextureManager->GetTextureNoMips( m_ColorGradingTexture.CStr() ) ); m_PostQuad->SetTexture( 2, pTextureManager->GetTextureNoMips( m_NoiseTexture.CStr() ) ); m_PostQuad->SetTexture( 3, pTargetManager->GetRenderTarget( "BloomAV" )->GetColorTextureHandle( 0 ) ); m_PostQuad->SetTexture( 4, pTargetManager->GetRenderTarget( "BloomCV" )->GetColorTextureHandle( 0 ) ); // Use the lowest blur level for dirty lens effect, it's the most blurry (can switch to BloomBV if I see artifacts) m_PostQuad->SetTexture( 5, pTextureManager->GetTextureNoMips( m_DirtyLensTexture.CStr() ) ); UpdateNoiseEnabled(); UpdateDirtyLensEnabled(); UpdateColorGradingEnabled(); #elif ROSA_USE_WATERCOLOR_POST m_PostQuad = CreateFullscreenQuad( pDisplay->m_Width, pDisplay->m_Height, "Post", "Material_PostWatercolor" ); m_PostQuad->SetTexture( 0, pTargetManager->GetRenderTarget( "Primary" )->GetColorTextureHandle( 0 ) ); // Main m_PostQuad->SetTexture( 1, pTargetManager->GetRenderTarget( "BloomAV" )->GetColorTextureHandle( 0 ) ); // Bloom/blur m_PostQuad->SetTexture( 2, pTextureManager->GetTextureNoMips( m_DisplaceTexture.CStr() ) ); // Displacement m_PostQuad->SetTexture( 3, pTextureManager->GetTextureNoMips( m_BlotTexture.CStr() ) ); // Blotting m_PostQuad->SetTexture( 4, pTextureManager->GetTextureNoMips( m_CanvasTexture.CStr() ) ); // Canvas m_PostQuad->SetTexture( 5, pTargetManager->GetRenderTarget( "GB_Albedo" )->GetColorTextureHandle( 0 ) ); // GB_Albedo is repurposed to store edges m_PostQuad->SetTexture( 6, pTextureManager->GetTextureNoMips( m_ColorGradingTexture.CStr() ) ); // Color grading m_PostQuad->SetTexture( 7, pTargetManager->GetRenderTarget( "GB_Depth" )->GetColorTextureHandle( 0 ) ); // Depth UpdateDisplaceEnabled(); UpdateBlurEnabled(); UpdateBlotEnabled(); UpdateCanvasEnabled(); UpdateEdgeEnabled(); UpdateColorGradingEnabled(); #endif m_PostCheapQuad = CreateFullscreenQuad( pDisplay->m_Width, pDisplay->m_Height, "Post", "Material_PostCheap" ); m_PostCheapQuad->SetTexture( 0, pTargetManager->GetRenderTarget( "Primary" )->GetColorTextureHandle( 0 ) ); // Main #if BUILD_ROSA_TOOLS SafeDelete( m_PostToolsQuad ); m_PostToolsQuad = CreateFullscreenQuad( pDisplay->m_Width, pDisplay->m_Height, "PostTools", "Material_PostTools" ); m_PostToolsQuad->SetTexture( 0, pTargetManager->GetRenderTarget( "Primary" )->GetColorTextureHandle( 0 ) ); #endif } void RosaGame::CreateSSAOQuad() { XTRACE_FUNCTION; SafeDelete( m_SSAOQuad ); RosaFramework* const pFramework = RosaFramework::GetInstance(); Display* const pDisplay = pFramework->GetDisplay(); IRenderer* const pRenderer = pFramework->GetRenderer(); RosaTargetManager* const pTargetManager = pFramework->GetTargetManager(); TextureManager* const pTextureManager = pRenderer->GetTextureManager(); m_SSAOQuad = CreateFullscreenQuad( pDisplay->m_Width, pDisplay->m_Height, "SSAO", "Material_SSAO" ); m_SSAOQuad->SetTexture( 0, pTargetManager->GetRenderTarget( "GB_Depth" )->GetColorTextureHandle( 0 ) ); m_SSAOQuad->SetTexture( 1, pTextureManager->GetTexture( "Textures/Post/random-cos-sin.tga" ) ); // HACKHACK: Hard-coded asset! } void RosaGame::CreateGradientQuad() { XTRACE_FUNCTION; SafeDelete( m_GradientQuad ); RosaFramework* const pFramework = RosaFramework::GetInstance(); Display* const pDisplay = pFramework->GetDisplay(); RosaTargetManager* const pTargetManager = pFramework->GetTargetManager(); m_GradientQuad = CreateFullscreenQuad( pDisplay->m_Width, pDisplay->m_Height, "Gradient", "Material_Gradient" ); m_GradientQuad->SetTexture( 0, pTargetManager->GetRenderTarget( "GB_Normal" )->GetColorTextureHandle( 0 ) ); m_GradientQuad->SetTexture( 1, pTargetManager->GetRenderTarget( "GB_Depth" )->GetColorTextureHandle( 0 ) ); } void RosaGame::CreateEdgeQuad() { XTRACE_FUNCTION; SafeDelete( m_EdgeQuad ); RosaFramework* const pFramework = RosaFramework::GetInstance(); Display* const pDisplay = pFramework->GetDisplay(); RosaTargetManager* const pTargetManager = pFramework->GetTargetManager(); m_EdgeQuad = CreateFullscreenQuad( pDisplay->m_Width, pDisplay->m_Height, "Edge", "Material_Edge" ); m_EdgeQuad->SetTexture( 0, pTargetManager->GetRenderTarget( "GB_Normal" )->GetColorTextureHandle( 0 ) ); m_EdgeQuad->SetTexture( 1, pTargetManager->GetRenderTarget( "GB_Depth" )->GetColorTextureHandle( 0 ) ); } void RosaGame::CreateLightCombineQuad() { XTRACE_FUNCTION; SafeDelete( m_LightCombineQuad ); RosaFramework* const pFramework = RosaFramework::GetInstance(); Display* const pDisplay = pFramework->GetDisplay(); RosaTargetManager* const pTargetManager = pFramework->GetTargetManager(); IRenderTarget* const pGB_LAccum = pTargetManager->GetRenderTarget( "GB_LAccum" ); IRenderTarget* const pGB_Albedo = pTargetManager->GetRenderTarget( "GB_Albedo" ); IRenderTarget* const pGB_Depth = pTargetManager->GetRenderTarget( "GB_Depth" ); m_LightCombineQuad = CreateFullscreenQuad( pDisplay->m_Width, pDisplay->m_Height, "LightCombine", "Material_LightCombine" ); m_LightCombineQuad->SetTexture( 0, pGB_LAccum->GetColorTextureHandle( 0 ) ); m_LightCombineQuad->SetTexture( 1, pGB_Albedo->GetColorTextureHandle( 0 ) ); m_LightCombineQuad->SetTexture( 2, pGB_Depth->GetColorTextureHandle( 0 ) ); } #if ROSA_USE_WATERCOLOR_POST void RosaGame::CreateEdgeQuad() { XTRACE_FUNCTION; SafeDelete( m_EdgeQuad ); RosaFramework* const pFramework = RosaFramework::GetInstance(); Display* const pDisplay = pFramework->GetDisplay(); RosaTargetManager* const pTargetManager = pFramework->GetTargetManager(); IRenderTarget* const pGB_Normal = pTargetManager->GetRenderTarget( "GB_Normal" ); IRenderTarget* const pGB_Depth = pTargetManager->GetRenderTarget( "GB_Depth" ); m_EdgeQuad = CreateFullscreenQuad( pDisplay->m_Width, pDisplay->m_Height, "Edge", "Material_Edge" ); m_EdgeQuad->SetTexture( 0, pGB_Normal->GetColorTextureHandle( 0 ) ); m_EdgeQuad->SetTexture( 1, pGB_Depth->GetColorTextureHandle( 0 ) ); } #endif void RosaGame::CreateBloomQuads() { XTRACE_FUNCTION; FOR_EACH_ARRAY( BloomQuadIter, m_BloomQuads, Mesh* ) { Mesh* pBloomQuad = BloomQuadIter.GetValue(); SafeDelete( pBloomQuad ); } m_BloomQuads.Clear(); RosaFramework* const pFramework = RosaFramework::GetInstance(); Display* const pDisplay = pFramework->GetDisplay(); IRenderer* const pRenderer = pFramework->GetRenderer(); RosaTargetManager* const pTargetManager = pFramework->GetTargetManager(); TextureManager* const pTextureManager = pRenderer->GetTextureManager(); const uint BloomWidthA = pDisplay->m_Width / ROSA_BLOOMA_SCALE; const uint BloomHeightA = pDisplay->m_Height / ROSA_BLOOMA_SCALE; const uint BloomWidthB = pDisplay->m_Width / ROSA_BLOOMB_SCALE; const uint BloomHeightB = pDisplay->m_Height / ROSA_BLOOMB_SCALE; const uint BloomWidthC = pDisplay->m_Width / ROSA_BLOOMC_SCALE; const uint BloomHeightC = pDisplay->m_Height / ROSA_BLOOMC_SCALE; // Bloom A { Mesh* const pBloomQuad = CreateFullscreenQuad( BloomWidthA, BloomHeightA, "BloomA", "Material_BloomClip" ); pBloomQuad->SetTexture( 0, pTargetManager->GetRenderTarget( "Primary" )->GetColorTextureHandle( 0 ) ); m_BloomQuads.PushBack( pBloomQuad ); } { Mesh* const pBloomQuad = CreateFullscreenQuad( BloomWidthA, BloomHeightA, "BloomAH", "Material_Bloom" ); pBloomQuad->SetTexture( 0, pTargetManager->GetRenderTarget( "BloomAV" )->GetColorTextureHandle( 0 ) ); pBloomQuad->SetTexture( 1, pTextureManager->GetTextureNoMips( m_BloomKernelTexture.CStr() ) ); m_BloomQuads.PushBack( pBloomQuad ); } { Mesh* const pBloomQuad = CreateFullscreenQuad( BloomWidthA, BloomHeightA, "BloomAV", "Material_BloomSum" ); pBloomQuad->SetTexture( 0, pTargetManager->GetRenderTarget( "BloomAH" )->GetColorTextureHandle( 0 ) ); pBloomQuad->SetTexture( 1, pTextureManager->GetTextureNoMips( m_BloomKernelTexture.CStr() ) ); pBloomQuad->SetTexture( 2, pTargetManager->GetRenderTarget( "BloomBV" )->GetColorTextureHandle( 0 ) ); m_BloomQuads.PushBack( pBloomQuad ); } // Bloom B { Mesh* const pBloomQuad = CreateFullscreenQuad( BloomWidthB, BloomHeightB, "BloomB", "Material_BloomCopy" ); pBloomQuad->SetTexture( 0, pTargetManager->GetRenderTarget( "BloomAV" )->GetColorTextureHandle( 0 ) ); m_BloomQuads.PushBack( pBloomQuad ); } { Mesh* const pBloomQuad = CreateFullscreenQuad( BloomWidthB, BloomHeightB, "BloomBH", "Material_Bloom" ); pBloomQuad->SetTexture( 0, pTargetManager->GetRenderTarget( "BloomBV" )->GetColorTextureHandle( 0 ) ); pBloomQuad->SetTexture( 1, pTextureManager->GetTextureNoMips( m_BloomKernelTexture.CStr() ) ); m_BloomQuads.PushBack( pBloomQuad ); } { Mesh* const pBloomQuad = CreateFullscreenQuad( BloomWidthB, BloomHeightB, "BloomBV", "Material_BloomSum" ); pBloomQuad->SetTexture( 0, pTargetManager->GetRenderTarget( "BloomBH" )->GetColorTextureHandle( 0 ) ); pBloomQuad->SetTexture( 1, pTextureManager->GetTextureNoMips( m_BloomKernelTexture.CStr() ) ); pBloomQuad->SetTexture( 2, pTargetManager->GetRenderTarget( "BloomCV" )->GetColorTextureHandle( 0 ) ); m_BloomQuads.PushBack( pBloomQuad ); } // Bloom C { Mesh* const pBloomQuad = CreateFullscreenQuad( BloomWidthC, BloomHeightC, "BloomC", "Material_BloomCopy" ); pBloomQuad->SetTexture( 0, pTargetManager->GetRenderTarget( "BloomBV" )->GetColorTextureHandle( 0 ) ); m_BloomQuads.PushBack( pBloomQuad ); } { Mesh* const pBloomQuad = CreateFullscreenQuad( BloomWidthC, BloomHeightC, "BloomCH", "Material_Bloom" ); pBloomQuad->SetTexture( 0, pTargetManager->GetRenderTarget( "BloomCV" )->GetColorTextureHandle( 0 ) ); pBloomQuad->SetTexture( 1, pTextureManager->GetTextureNoMips( m_BloomKernelTexture.CStr() ) ); m_BloomQuads.PushBack( pBloomQuad ); } { Mesh* const pBloomQuad = CreateFullscreenQuad( BloomWidthC, BloomHeightC, "BloomCV", "Material_Bloom" ); pBloomQuad->SetTexture( 0, pTargetManager->GetRenderTarget( "BloomCH" )->GetColorTextureHandle( 0 ) ); pBloomQuad->SetTexture( 1, pTextureManager->GetTextureNoMips( m_BloomKernelTexture.CStr() ) ); m_BloomQuads.PushBack( pBloomQuad ); } } void RosaGame::CreateFXAAQuad() { XTRACE_FUNCTION; SafeDelete( m_FXAAQuad ); RosaFramework* const pFramework = RosaFramework::GetInstance(); Display* const pDisplay = pFramework->GetDisplay(); RosaTargetManager* const pTargetManager = pFramework->GetTargetManager(); m_FXAAQuad = CreateFullscreenQuad( pDisplay->m_Width, pDisplay->m_Height, "FXAA", "Material_FXAA" ); m_FXAAQuad->SetTexture( 0, pTargetManager->GetRenderTarget( "Post" )->GetColorTextureHandle( 0 ) ); } void RosaGame::CreateMinimapBQuad() { XTRACE_FUNCTION; SafeDelete( m_MinimapBQuad ); RosaFramework* const pFramework = RosaFramework::GetInstance(); RosaTargetManager* const pTargetManager = pFramework->GetTargetManager(); TextureManager* const pTextureManager = pFramework->GetRenderer()->GetTextureManager(); IRenderTarget* const pMinimapART = pTargetManager->GetRenderTarget( "MinimapA" ); const uint MinimapRTWidth = pMinimapART->GetWidth(); const uint MinimapRTHeight = pMinimapART->GetHeight(); m_MinimapBQuad = CreateFullscreenQuad( MinimapRTWidth, MinimapRTHeight, "MinimapB", "Material_MinimapB" ); m_MinimapBQuad->SetTexture( 0, pMinimapART->GetColorTextureHandle( 0 ) ); m_MinimapBQuad->SetTexture( 1, pTextureManager->GetTextureNoMips( m_MinimapTonesTexture.CStr() ) ); m_MinimapBQuad->SetTexture( 2, pTextureManager->GetTextureNoMips( m_MinimapFloorTexture.CStr() ) ); m_MinimapBQuad->SetTexture( 3, pTextureManager->GetTextureNoMips( m_MinimapSolidTexture.CStr() ) ); } void RosaGame::CreateMinimapFXAAQuad() { XTRACE_FUNCTION; SafeDelete( m_MinimapFXAAQuad ); RosaFramework* const pFramework = RosaFramework::GetInstance(); RosaTargetManager* const pTargetManager = pFramework->GetTargetManager(); IRenderTarget* const pMinimapBRT = pTargetManager->GetRenderTarget( "MinimapB" ); const uint MinimapRTWidth = pMinimapBRT->GetWidth(); const uint MinimapRTHeight = pMinimapBRT->GetHeight(); m_MinimapFXAAQuad = CreateFullscreenQuad( MinimapRTWidth, MinimapRTHeight, "MinimapFXAA", "Material_MinimapFXAA" ); m_MinimapFXAAQuad->SetTexture( 0, pMinimapBRT->GetColorTextureHandle( 0 ) ); } #if ROSA_USE_MAXIMAP void RosaGame::CreateMaximapBQuad() { XTRACE_FUNCTION; SafeDelete( m_MaximapBQuad ); RosaFramework* const pFramework = RosaFramework::GetInstance(); RosaTargetManager* const pTargetManager = pFramework->GetTargetManager(); TextureManager* const pTextureManager = pFramework->GetRenderer()->GetTextureManager(); IRenderTarget* const pMaximapART = pTargetManager->GetRenderTarget( "MaximapA" ); const uint MaximapRTWidth = pMaximapART->GetWidth(); const uint MaximapRTHeight = pMaximapART->GetHeight(); m_MaximapBQuad = CreateFullscreenQuad( MaximapRTWidth, MaximapRTHeight, "MaximapB", "Material_MinimapB" ); m_MaximapBQuad->SetTexture( 0, pMaximapART->GetColorTextureHandle( 0 ) ); m_MaximapBQuad->SetTexture( 1, pTextureManager->GetTextureNoMips( m_MinimapTonesTexture.CStr() ) ); m_MaximapBQuad->SetTexture( 2, pTextureManager->GetTextureNoMips( m_MinimapFloorTexture.CStr() ) ); m_MaximapBQuad->SetTexture( 3, pTextureManager->GetTextureNoMips( m_MinimapSolidTexture.CStr() ) ); } #endif #if ROSA_USE_MAXIMAP void RosaGame::CreateMaximapFXAAQuad() { XTRACE_FUNCTION; SafeDelete( m_MaximapFXAAQuad ); RosaFramework* const pFramework = RosaFramework::GetInstance(); RosaTargetManager* const pTargetManager = pFramework->GetTargetManager(); IRenderTarget* const pMaximapBRT = pTargetManager->GetRenderTarget( "MaximapB" ); const uint MaximapRTWidth = pMaximapBRT->GetWidth(); const uint MaximapRTHeight = pMaximapBRT->GetHeight(); m_MaximapFXAAQuad = CreateFullscreenQuad( MaximapRTWidth, MaximapRTHeight, "MaximapFXAA", "Material_MinimapFXAA" ); m_MaximapFXAAQuad->SetTexture( 0, pMaximapBRT->GetColorTextureHandle( 0 ) ); } #endif Mesh* RosaGame::CreateFullscreenQuad( const uint Width, const uint Height, const HashedString& PrescribedBucket, const SimpleString& MaterialDef ) { RosaFramework* const pFramework = RosaFramework::GetInstance(); IRenderer* const pRenderer = pFramework->GetRenderer(); const float QuadWidth = static_cast( Width ); const float QuadHeight = static_cast( Height ); const float OffsetWidth = 0.5f * QuadWidth; const float OffsetHeight = 0.5f * QuadHeight; Mesh* const pFSQuadMesh = pRenderer->GetMeshFactory()->CreatePlane( QuadWidth, QuadHeight, 1, 1, XZ_PLANE, false ); pFSQuadMesh->m_Location = Vector( OffsetWidth, 0.0f, OffsetHeight ); pFSQuadMesh->SetVertexDeclaration( pRenderer->GetVertexDeclaration( VD_POSITIONS | VD_UVS ) ); // Override what CreatePlane gives us pFSQuadMesh->SetBucket( PrescribedBucket ); pFSQuadMesh->SetMaterialDefinition( MaterialDef, pRenderer ); return pFSQuadMesh; } void RosaGame::SetMinimapTextures( const SimpleString& TonesFilename, const SimpleString& FloorFilename, const SimpleString& SolidFilename ) { XTRACE_FUNCTION; m_MinimapTonesTexture = TonesFilename; m_MinimapFloorTexture = FloorFilename; m_MinimapSolidTexture = SolidFilename; // HACKHACK: Do this here because why not. It's sure to be called before minimap is rendered. STATICHASH( RosaMinimap ); STATICHASH( MinimapHeightThreshold ); m_MinimapHeightThreshold = ConfigManager::GetFloat( sMinimapHeightThreshold, 0.0f, sRosaMinimap ); STATICHASH( MinimapHeightOffset ); m_MinimapHeightOffset = ConfigManager::GetFloat( sMinimapHeightOffset, 0.0f, sRosaMinimap ); STATICHASH( MinimapHeightDiffScale ); m_MinimapHeightDiffScale = ConfigManager::GetFloat( sMinimapHeightDiffScale, 1.0f, sRosaMinimap ); STATICHASH( MinimapHeightToneScale ); m_MinimapHeightToneScale = ConfigManager::GetFloat( sMinimapHeightToneScale, 1.0f, sRosaMinimap ); STATICHASH( MinimapRenderEdges ); m_MinimapRenderEdges = ConfigManager::GetBool( sMinimapRenderEdges, false, sRosaMinimap ) ? 1.0f : 0.0f; STATICHASH( MinimapTileSize ); m_MinimapRcpTileSize = 1.0f / ConfigManager::GetFloat( sMinimapTileSize, 1.0f, sRosaMinimap ); if( m_MinimapBQuad ) { RosaFramework* const pFramework = RosaFramework::GetInstance(); DEVASSERT( pFramework ); TextureManager* const pTextureManager = pFramework->GetRenderer()->GetTextureManager(); DEVASSERT( pTextureManager ); m_MinimapBQuad->SetTexture( 1, pTextureManager->GetTextureNoMips( m_MinimapTonesTexture.CStr() ) ); m_MinimapBQuad->SetTexture( 2, pTextureManager->GetTextureNoMips( m_MinimapFloorTexture.CStr() ) ); m_MinimapBQuad->SetTexture( 3, pTextureManager->GetTextureNoMips( m_MinimapSolidTexture.CStr() ) ); } #if ROSA_USE_MAXIMAP if( m_MaximapBQuad ) { RosaFramework* const pFramework = RosaFramework::GetInstance(); DEVASSERT( pFramework ); TextureManager* const pTextureManager = pFramework->GetRenderer()->GetTextureManager(); DEVASSERT( pTextureManager ); m_MaximapBQuad->SetTexture( 1, pTextureManager->GetTextureNoMips( m_MinimapTonesTexture.CStr() ) ); m_MaximapBQuad->SetTexture( 2, pTextureManager->GetTextureNoMips( m_MinimapFloorTexture.CStr() ) ); m_MaximapBQuad->SetTexture( 3, pTextureManager->GetTextureNoMips( m_MinimapSolidTexture.CStr() ) ); } #endif } void RosaGame::SetColorGradingTexture( const SimpleString& TextureFilename ) { XTRACE_FUNCTION; m_ColorGradingTexture = TextureFilename; UpdateColorGradingEnabled(); } void RosaGame::UpdateColorGradingEnabled() { DEVASSERT( m_PostQuad ); if( !m_PostQuad ) { return; } STATICHASH( ColorGrading ); const bool ColorGrading = ConfigManager::GetBool( sColorGrading ); RosaFramework* const pFramework = RosaFramework::GetInstance(); ASSERT( pFramework ); TextureManager* const pTextureManager = pFramework->GetRenderer()->GetTextureManager(); ASSERT( pTextureManager ); STATICHASH( ColorGradingDisabledTexture ); const SimpleString DisabledTexture = ConfigManager::GetString( sColorGradingDisabledTexture, "" ); const SimpleString& TextureFilename = ColorGrading ? m_ColorGradingTexture : DisabledTexture; ITexture* const pTexture = pTextureManager->GetTextureNoMips( TextureFilename.CStr() ); #if ROSA_USE_FILMIC_POST m_PostQuad->SetTexture( 1, pTexture ); #elif ROSA_USE_WATERCOLOR_POST m_PostQuad->SetTexture( 6, pTexture ); #endif } void RosaGame::SetNoiseTexture( const SimpleString& TextureFilename ) { XTRACE_FUNCTION; m_NoiseTexture = TextureFilename; UpdateNoiseEnabled(); } void RosaGame::UpdateNoiseEnabled() { #if ROSA_USE_FILMIC_POST DEVASSERT( m_PostQuad ); if( !m_PostQuad ) { return; } STATICHASH( FilmGrain ); const bool FilmGrain = ConfigManager::GetBool( sFilmGrain ); RosaFramework* const pFramework = RosaFramework::GetInstance(); ASSERT( pFramework ); TextureManager* const pTextureManager = pFramework->GetRenderer()->GetTextureManager(); ASSERT( pTextureManager ); STATICHASH( FilmGrainDisabledTexture ); const SimpleString DisabledTexture = ConfigManager::GetString( sFilmGrainDisabledTexture, "" ); const SimpleString& TextureFilename = FilmGrain ? m_NoiseTexture : DisabledTexture; ITexture* const pTexture = pTextureManager->GetTextureNoMips( TextureFilename.CStr() ); m_PostQuad->SetTexture( 2, pTexture ); #endif } void RosaGame::SetNoiseScaleRange( const float NoiseScaleLo, const float NoiseScaleHi ) { m_NoiseScaleRange.x = NoiseScaleLo; m_NoiseScaleRange.y = NoiseScaleHi; } void RosaGame::SetNoiseRange( const float NoiseRange ) { m_NoiseRange = NoiseRange; } void RosaGame::UpdateGraphicsOptionWidgets() { STATIC_HASHED_STRING( GraphicsOptionsScreen ); // Filmic STATIC_HASHED_STRING( BloomButton ); STATIC_HASHED_STRING( DirtyLensButton ); STATIC_HASHED_STRING( HalosButton ); STATIC_HASHED_STRING( FilmGrainButton ); // Watercolor STATIC_HASHED_STRING( DisplaceButton ); STATIC_HASHED_STRING( BlurButton ); STATIC_HASHED_STRING( BlotButton ); STATIC_HASHED_STRING( EdgeButton ); STATIC_HASHED_STRING( CanvasButton ); STATIC_HASHED_STRING( ColorGradingButton ); WBEventManager* const pEventManager = WBWorld::GetInstance()->GetEventManager(); const bool Disabled = m_UsePostCheapQuad; STATICHASH( Bloom ); const bool BloomDisabled = Disabled || !ConfigManager::GetBool( sBloom ); { WB_MAKE_EVENT( SetWidgetDisabled, NULL ); WB_SET_AUTO( SetWidgetDisabled, Hash, Screen, sGraphicsOptionsScreen ); WB_SET_AUTO( SetWidgetDisabled, Hash, Widget, sBloomButton ); WB_SET_AUTO( SetWidgetDisabled, Bool, Disabled, Disabled ); WB_DISPATCH_EVENT( pEventManager, SetWidgetDisabled, NULL ); } { WB_MAKE_EVENT( SetWidgetDisabled, NULL ); WB_SET_AUTO( SetWidgetDisabled, Hash, Screen, sGraphicsOptionsScreen ); WB_SET_AUTO( SetWidgetDisabled, Hash, Widget, sDirtyLensButton ); WB_SET_AUTO( SetWidgetDisabled, Bool, Disabled, BloomDisabled ); WB_DISPATCH_EVENT( pEventManager, SetWidgetDisabled, NULL ); } { WB_MAKE_EVENT( SetWidgetDisabled, NULL ); WB_SET_AUTO( SetWidgetDisabled, Hash, Screen, sGraphicsOptionsScreen ); WB_SET_AUTO( SetWidgetDisabled, Hash, Widget, sHalosButton ); WB_SET_AUTO( SetWidgetDisabled, Bool, Disabled, BloomDisabled ); WB_DISPATCH_EVENT( pEventManager, SetWidgetDisabled, NULL ); } { WB_MAKE_EVENT( SetWidgetDisabled, NULL ); WB_SET_AUTO( SetWidgetDisabled, Hash, Screen, sGraphicsOptionsScreen ); WB_SET_AUTO( SetWidgetDisabled, Hash, Widget, sFilmGrainButton ); WB_SET_AUTO( SetWidgetDisabled, Bool, Disabled, Disabled ); WB_DISPATCH_EVENT( pEventManager, SetWidgetDisabled, NULL ); } { WB_MAKE_EVENT( SetWidgetDisabled, NULL ); WB_SET_AUTO( SetWidgetDisabled, Hash, Screen, sGraphicsOptionsScreen ); WB_SET_AUTO( SetWidgetDisabled, Hash, Widget, sDisplaceButton ); WB_SET_AUTO( SetWidgetDisabled, Bool, Disabled, Disabled ); WB_DISPATCH_EVENT( pEventManager, SetWidgetDisabled, NULL ); } { WB_MAKE_EVENT( SetWidgetDisabled, NULL ); WB_SET_AUTO( SetWidgetDisabled, Hash, Screen, sGraphicsOptionsScreen ); WB_SET_AUTO( SetWidgetDisabled, Hash, Widget, sBlurButton ); WB_SET_AUTO( SetWidgetDisabled, Bool, Disabled, Disabled ); WB_DISPATCH_EVENT( pEventManager, SetWidgetDisabled, NULL ); } { WB_MAKE_EVENT( SetWidgetDisabled, NULL ); WB_SET_AUTO( SetWidgetDisabled, Hash, Screen, sGraphicsOptionsScreen ); WB_SET_AUTO( SetWidgetDisabled, Hash, Widget, sBlotButton ); WB_SET_AUTO( SetWidgetDisabled, Bool, Disabled, Disabled ); WB_DISPATCH_EVENT( pEventManager, SetWidgetDisabled, NULL ); } #if ROSA_USE_WATERCOLOR_POST { WB_MAKE_EVENT( SetWidgetDisabled, NULL ); WB_SET_AUTO( SetWidgetDisabled, Hash, Screen, sGraphicsOptionsScreen ); WB_SET_AUTO( SetWidgetDisabled, Hash, Widget, sEdgeButton ); WB_SET_AUTO( SetWidgetDisabled, Bool, Disabled, Disabled ); WB_DISPATCH_EVENT( pEventManager, SetWidgetDisabled, NULL ); } #endif { WB_MAKE_EVENT( SetWidgetDisabled, NULL ); WB_SET_AUTO( SetWidgetDisabled, Hash, Screen, sGraphicsOptionsScreen ); WB_SET_AUTO( SetWidgetDisabled, Hash, Widget, sCanvasButton ); WB_SET_AUTO( SetWidgetDisabled, Bool, Disabled, Disabled ); WB_DISPATCH_EVENT( pEventManager, SetWidgetDisabled, NULL ); } { WB_MAKE_EVENT( SetWidgetDisabled, NULL ); WB_SET_AUTO( SetWidgetDisabled, Hash, Screen, sGraphicsOptionsScreen ); WB_SET_AUTO( SetWidgetDisabled, Hash, Widget, sColorGradingButton ); WB_SET_AUTO( SetWidgetDisabled, Bool, Disabled, Disabled ); WB_DISPATCH_EVENT( pEventManager, SetWidgetDisabled, NULL ); } } void RosaGame::UpdateBloomEnabled() { UpdateGraphicsOptionWidgets(); } void RosaGame::SetDirtyLensTexture( const SimpleString& TextureFilename ) { XTRACE_FUNCTION; m_DirtyLensTexture = TextureFilename; UpdateDirtyLensEnabled(); } void RosaGame::UpdateDirtyLensEnabled() { #if ROSA_USE_FILMIC_POST DEVASSERT( m_PostQuad ); if( !m_PostQuad ) { return; } STATICHASH( DirtyLens ); const bool DirtyLens = ConfigManager::GetBool( sDirtyLens ); RosaFramework* const pFramework = RosaFramework::GetInstance(); ASSERT( pFramework ); TextureManager* const pTextureManager = pFramework->GetRenderer()->GetTextureManager(); ASSERT( pTextureManager ); STATICHASH( DirtyLensDisabledTexture ); const SimpleString DisabledTexture = ConfigManager::GetString( sDirtyLensDisabledTexture, "" ); const SimpleString& TextureFilename = DirtyLens ? m_DirtyLensTexture : DisabledTexture; ITexture* const pTexture = pTextureManager->GetTextureNoMips( TextureFilename.CStr() ); m_PostQuad->SetTexture( 5, pTexture ); #endif } void RosaGame::UpdateHalosEnabled() { #if ROSA_USE_FILMIC_POST STATICHASH( Halos ); m_HalosEnabled = ConfigManager::GetBool( sHalos ); #endif } void RosaGame::SetBloomKernelTexture( const SimpleString& TextureFilename ) { XTRACE_FUNCTION; RosaFramework* const pFramework = RosaFramework::GetInstance(); ASSERT( pFramework ); TextureManager* const pTextureManager = pFramework->GetRenderer()->GetTextureManager(); ASSERT( pTextureManager ); m_BloomKernelTexture = TextureFilename; FOR_EACH_ARRAY( BloomQuadIter, m_BloomQuads, Mesh* ) { // HACKHACK: Skip clip/copy bloom quads if( BloomQuadIter.GetIndex() % 3 == 0 ) { continue; } Mesh* pBloomQuad = BloomQuadIter.GetValue(); pBloomQuad->SetTexture( 1, pTextureManager->GetTextureNoMips( m_BloomKernelTexture.CStr() ) ); } } void RosaGame::SetDisplaceTexture( const SimpleString& TextureFilename ) { XTRACE_FUNCTION; m_DisplaceTexture = TextureFilename; UpdateDisplaceEnabled(); } void RosaGame::UpdateBlurEnabled() { #if ROSA_USE_WATERCOLOR_POST DEVASSERT( m_PostQuad ); if( !m_PostQuad ) { return; } STATICHASH( Blur ); const bool Blur = ConfigManager::GetBool( sBlur ); RosaFramework* const pFramework = RosaFramework::GetInstance(); ASSERT( pFramework ); RosaTargetManager* const pTargetManager = pFramework->GetTargetManager(); ASSERT( pTargetManager ); const SimpleString TargetName = Blur ? "BloomAV" : "Primary"; ITexture* const pTexture = pTargetManager->GetRenderTarget( TargetName )->GetColorTextureHandle( 0 ); m_PostQuad->SetTexture( 1, pTexture ); #endif } void RosaGame::UpdateEdgeEnabled() { #if ROSA_USE_WATERCOLOR_POST DEVASSERT( m_PostQuad ); if( !m_PostQuad ) { return; } STATICHASH( Edge ); const bool Edge = ConfigManager::GetBool( sEdge ); RosaFramework* const pFramework = RosaFramework::GetInstance(); ASSERT( pFramework ); TextureManager* const pTextureManager = pFramework->GetRenderer()->GetTextureManager(); ASSERT( pTextureManager ); RosaTargetManager* const pTargetManager = pFramework->GetTargetManager(); ASSERT( pTargetManager ); STATICHASH( EdgeDisabledTexture ); const SimpleString DisabledTexture = ConfigManager::GetString( sEdgeDisabledTexture, "" ); ITexture* const pNoEdgeTexture = pTextureManager->GetTextureNoMips( DisabledTexture.CStr() ); ITexture* const pEdgeTexture = pTargetManager->GetRenderTarget( "GB_Albedo" )->GetColorTextureHandle( 0 ); ITexture* const pTexture = Edge ? pEdgeTexture : pNoEdgeTexture; m_PostQuad->SetTexture( 5, pTexture ); #endif } void RosaGame::UpdateDisplaceEnabled() { #if ROSA_USE_WATERCOLOR_POST DEVASSERT( m_PostQuad ); if( !m_PostQuad ) { return; } STATICHASH( Displace ); const bool Displace = ConfigManager::GetBool( sDisplace ); RosaFramework* const pFramework = RosaFramework::GetInstance(); ASSERT( pFramework ); TextureManager* const pTextureManager = pFramework->GetRenderer()->GetTextureManager(); ASSERT( pTextureManager ); STATICHASH( DisplaceDisabledTexture ); const SimpleString DisabledTexture = ConfigManager::GetString( sDisplaceDisabledTexture, "" ); const SimpleString& TextureFilename = Displace ? m_DisplaceTexture : DisabledTexture; ITexture* const pTexture = pTextureManager->GetTextureNoMips( TextureFilename.CStr() ); m_PostQuad->SetTexture( 2, pTexture ); #endif } void RosaGame::SetBlotTexture( const SimpleString& TextureFilename ) { XTRACE_FUNCTION; m_BlotTexture = TextureFilename; UpdateBlotEnabled(); } void RosaGame::UpdateBlotEnabled() { #if ROSA_USE_WATERCOLOR_POST DEVASSERT( m_PostQuad ); if( !m_PostQuad ) { return; } STATICHASH( Blot ); const bool Blot = ConfigManager::GetBool( sBlot ); RosaFramework* const pFramework = RosaFramework::GetInstance(); ASSERT( pFramework ); TextureManager* const pTextureManager = pFramework->GetRenderer()->GetTextureManager(); ASSERT( pTextureManager ); STATICHASH( BlotDisabledTexture ); const SimpleString DisabledTexture = ConfigManager::GetString( sBlotDisabledTexture, "" ); const SimpleString& TextureFilename = Blot ? m_BlotTexture : DisabledTexture; ITexture* const pTexture = pTextureManager->GetTextureNoMips( TextureFilename.CStr() ); m_PostQuad->SetTexture( 3, pTexture ); #endif } void RosaGame::SetCanvasTexture( const SimpleString& TextureFilename ) { XTRACE_FUNCTION; m_CanvasTexture = TextureFilename; UpdateCanvasEnabled(); } void RosaGame::UpdateCanvasEnabled() { #if ROSA_USE_WATERCOLOR_POST DEVASSERT( m_PostQuad ); if( !m_PostQuad ) { return; } STATICHASH( Canvas ); const bool Canvas = ConfigManager::GetBool( sCanvas ); RosaFramework* const pFramework = RosaFramework::GetInstance(); ASSERT( pFramework ); TextureManager* const pTextureManager = pFramework->GetRenderer()->GetTextureManager(); ASSERT( pTextureManager ); STATICHASH( CanvasDisabledTexture ); const SimpleString DisabledTexture = ConfigManager::GetString( sCanvasDisabledTexture, "" ); const SimpleString& TextureFilename = Canvas ? m_CanvasTexture : DisabledTexture; ITexture* const pTexture = pTextureManager->GetTextureNoMips( TextureFilename.CStr() ); m_PostQuad->SetTexture( 4, pTexture ); #endif } void RosaGame::UpdatePostCheapEnabled() { STATICHASH( PostCheap ); m_UsePostCheapQuad = ConfigManager::GetBool( sPostCheap ); // HACKHACK: Also set UI button state UpdateGraphicsOptionWidgets(); } void RosaGame::SetFogColors( const Vector4& FogColorNearLo, const Vector4& FogColorFarLo, const Vector4& FogColorNearHi, const Vector4& FogColorFarHi ) { m_FogColors = Matrix( FogColorNearLo, FogColorFarLo, FogColorNearHi, FogColorFarHi ); #if BUILD_WINDOWS_NO_SDL RosaFramework* const pFramework = RosaFramework::GetInstance(); DEVASSERT( pFramework ); IRenderer* const pRenderer = pFramework->GetRenderer(); DEVASSERT( pRenderer ); if( pRenderer->IsOpenGL() ) #endif // BUILD_WINDOWS_NO_SDL { // HACKHACK: Transpose this on GL, since we're just using this as a container of 4 vec4s and GLSL uses column-major indexing. m_FogColors.Transpose(); } } void RosaGame::SetFogCurves( const Vector4& FogNearFarCurve, const Vector4& FogLoHiCurve ) { // HACKHACK: Save this off, it's used for height fog const float HeightFogExp = m_FogLoHiCurve.y; m_FogNearFarCurve = FogNearFarCurve; m_FogLoHiCurve = FogLoHiCurve; // HACKHACK: Restore this, it's used for height fog m_FogLoHiCurve.y = HeightFogExp; } void RosaGame::SetFogParams( const float FogNear, const float FogFar, const float EmissiveMax, const float Exposure, const float FogLightDensity ) { XTRACE_FUNCTION; const float FogRange = FogFar - FogNear; const bool HasValidRange = Abs( FogRange ) > EPSILON; m_FogParams.x = FogNear; m_FogParams.y = HasValidRange ? ( 1.0f / FogRange ) : 0.0f; m_FogParams.z = EmissiveMax; m_FogLightParams.x = FogLightDensity; SetExposure( Exposure ); } void RosaGame::UpdateFogEnabled() { STATICHASH( Fog ); m_FogEnabled = ConfigManager::GetBool( sFog ); } void RosaGame::SetHeightFogParams( const float HeightFogLo, const float HeightFogHi, const float HeightFogExp, const float HeightFogLoExp, const float HeightFogHiExp ) { XTRACE_FUNCTION; const float HeightFogRange = HeightFogHi - HeightFogLo; const bool HasValidRange = Abs( HeightFogRange ) > EPSILON; m_HeightFogParams.x = HeightFogLo; m_HeightFogParams.y = HasValidRange ? ( 1.0f / HeightFogRange ) : 0.0f; m_HeightFogParams.z = HeightFogLoExp; m_HeightFogParams.w = HeightFogHiExp; // HACKHACK: Shove height fog exp (the curve between lo/hi points) into unused member here m_FogLoHiCurve.y = HeightFogExp; } void RosaGame::AdjustFogRegionScalar( const Vector4& RegionFogScalar, const float DeltaTime ) { const float ClampedDT = Min( DeltaTime, 1.0f ); // Prevent overshooting const Vector4 Deltas = RegionFogScalar - m_RegionFogScalar; const Vector4 NewScalar = m_RegionFogScalar + Deltas * ClampedDT; SetRegionFogScalar( NewScalar ); } void RosaGame::AdjustExposure( const float Exposure, const float DeltaTime ) { const float OldExposure = m_FogParams.w; const float LoExposure = Min( OldExposure, Exposure ); const float HiExposure = Max( OldExposure, Exposure ); // HACKHACK: Hard-coded velocity scalar, relative to exposure delta // This makes the eye adjust quickly at first and then ease toward stability // Use a lower velocity if exposure is increasing (i.e. we're moving into a darker region); // this emulates the eye adjusting more slowly to darkness than to light. const float Delta = Exposure - OldExposure; const bool Increasing = ( Delta > 0.0f ); const float Velocity = Delta * ( Increasing ? 0.5f : 2.0f ); const float NewExposure = Clamp( OldExposure + Velocity * DeltaTime, LoExposure, HiExposure ); SetExposure( NewExposure ); } void RosaGame::AdjustMinimapScalar( const float MinimapScalar, const float DeltaTime ) { const float OldMinimapScalar = m_CurrentMinimapScalar; const float LoMinimapScalar = Min( OldMinimapScalar, MinimapScalar ); const float HiMinimapScalar = Max( OldMinimapScalar, MinimapScalar ); // HACKHACK: Hard-coded velocity scalar, relative to delta const float Delta = MinimapScalar - OldMinimapScalar; const float Velocity = Delta * 5.0f; const float NewMinimapScalar = Clamp( OldMinimapScalar + Velocity * DeltaTime, LoMinimapScalar, HiMinimapScalar ); SetMinimapScalar( NewMinimapScalar ); } void RosaGame::AdjustEdgeColorHSV( const Vector& EdgeColorHSV, const float DeltaTime ) { const float Velocity = 4.0f; // TODO: Configure? const float ClampedDT = Min( Velocity * DeltaTime, 1.0f ); // Prevent overshooting const Vector Deltas = EdgeColorHSV - m_EdgeColorHSV; const Vector NewEdgeColorHSV = m_EdgeColorHSV + Deltas * ClampedDT; SetEdgeColorHSV( NewEdgeColorHSV ); } void RosaGame::SetAmbience( const SimpleString& Ambience ) { if( Ambience == m_CurrentAmbience ) { return; } m_CurrentAmbience = Ambience; m_Music->PlayAmbience( Ambience ); } void RosaGame::SetReverb( const SimpleString& ReverbDef ) { if( ReverbDef == m_CurrentReverbDef ) { return; } RosaFramework* const pFramework = RosaFramework::GetInstance(); DEVASSERT( pFramework ); IAudioSystem* const pAudioSystem = pFramework->GetAudioSystem(); DEVASSERT( pAudioSystem ); m_CurrentReverbDef = ReverbDef; pAudioSystem->SetReverbParams( ReverbDef ); } void RosaGame::SetSkyParams( const Vector4& SunVector, const Vector4& SkyColorHi, const Vector4& SkyColorLo ) { m_SunVector = SunVector; m_SkyColorHi = SkyColorHi; m_SkyColorLo = SkyColorLo; } void RosaGame::SetEdgeColorHSV( const Vector& EdgeColorHSV ) { m_EdgeColorHSV = EdgeColorHSV; const Vector EdgeColorRGB = HSV::HSVToRGB( EdgeColorHSV ); m_EdgeColor = Vector4( EdgeColorRGB, 1.0f ); m_EdgeBackColor = Vector4( EdgeColorRGB, 0.0f ); } void RosaGame::SetBloomRadius( const float VerticalRadius, const float AspectRatio ) { m_BloomVerticalRadius = VerticalRadius; m_BloomAspectRatio = AspectRatio; RefreshBloomParams(); } void RosaGame::RefreshBloomParams() { RosaFramework* const pFramework = RosaFramework::GetInstance(); DEVASSERT( pFramework ); Display* const pDisplay = pFramework->GetDisplay(); DEVASSERT( pDisplay ); const float DisplayWidth = static_cast( pDisplay->m_Width ); const float DisplayHeight = static_cast( pDisplay->m_Height ); const float AspectRatio = m_BloomAspectRatio * ( DisplayHeight / DisplayWidth ); const float BloomStepRadius = m_BloomVerticalRadius / ROSA_BLOOM_TAPS; // NOTE: Must be kept in tune with the number of steps in shader! m_BloomStepRadiusH = Vector2( AspectRatio * BloomStepRadius, 0.0f ); m_BloomStepRadiusV = Vector2( 0.0f, BloomStepRadius ); } Vector2 RosaGame::GetBloomRadius() { // HACKHACK: Alternate between providing the horizontal and vertical params const bool ReturnVertical = m_ReturnVerticalBloomRadius; m_ReturnVerticalBloomRadius = !m_ReturnVerticalBloomRadius; return ReturnVertical ? m_BloomStepRadiusV : m_BloomStepRadiusH; } SimpleString RosaGame::GetTitleScreenLevelName() const { STATICHASH( RosaWorld ); STATICHASH( TitleScreenLevel ); return ConfigManager::GetString( sTitleScreenLevel, "", sRosaWorld ); } bool RosaGame::IsInTitleScreen() const { return m_CurrentLevelName == GetTitleScreenLevelName(); } SimpleString RosaGame::GetInitialLevelName() const { STATICHASH( RosaWorld ); STATICHASH( InitialLevel ); return ConfigManager::GetString( sInitialLevel, "", sRosaWorld ); } SimpleString RosaGame::GetHubLevelName() const { STATICHASH( RosaWorld ); STATICHASH( HubLevel ); return ConfigManager::GetString( sHubLevel, "", sRosaWorld ); } bool RosaGame::IsInHub() const { STATICHASH( IsHub ); return ConfigManager::GetBool( sIsHub, false, m_CurrentLevelName ); } bool RosaGame::ShouldLowerWeapon() const { STATICHASH( LowerWeapon ); return ConfigManager::GetBool( sLowerWeapon, false, m_CurrentLevelName ); } void RosaGame::SetUIRetreatDisabled( const bool Disabled ) { STATIC_HASHED_STRING( PauseScreen ); STATIC_HASHED_STRING( PausedRetreatButton ); WB_MAKE_EVENT( SetWidgetDisabled, NULL ); WB_SET_AUTO( SetWidgetDisabled, Hash, Screen, sPauseScreen ); WB_SET_AUTO( SetWidgetDisabled, Hash, Widget, sPausedRetreatButton ); WB_SET_AUTO( SetWidgetDisabled, Bool, Disabled, Disabled ); WB_DISPATCH_EVENT( WBWorld::GetInstance()->GetEventManager(), SetWidgetDisabled, NULL ); } void RosaGame::RefreshUIRetreatEnabled() { SetUIRetreatDisabled( IsInHub() ); } // For a purchase link in the demo, if I do that. void RosaGame::LaunchWebSite( const SimpleString& URL ) { #if BUILD_WINDOWS ShellExecute( NULL, "open", URL.CStr(), NULL, NULL, SW_SHOWNORMAL ); #elif BUILD_MAC const SimpleString Command = SimpleString::PrintF( "open %s", URL.CStr() ); system( Command.CStr() ); #elif BUILD_LINUX const SimpleString Command = SimpleString::PrintF( "xdg-open %s", URL.CStr() ); system( Command.CStr() ); #endif } void RosaGame::OpenUserDataPath() { RosaFramework* const pFramework = RosaFramework::GetInstance(); DEVASSERT( pFramework ); const SimpleString UserDataPath = pFramework->GetUserDataPath(); #if BUILD_WINDOWS ShellExecute( NULL, "open", UserDataPath.CStr(), NULL, NULL, SW_SHOWNORMAL ); #elif BUILD_MAC // HACKHACK: Escape spaces on Mac because of "Application\ Support" const SimpleString EscapedPath = UserDataPath.Replace( " ", "\\ " ); const SimpleString Command = SimpleString::PrintF( "open %s", EscapedPath.CStr() ); system( Command.CStr() ); #elif BUILD_LINUX // HACKHACK: Probably need to escape spaces Linux too (untested) const SimpleString EscapedPath = UserDataPath.Replace( " ", "\\ " ); const SimpleString Command = SimpleString::PrintF( "xdg-open %s", EscapedPath.CStr() ); system( Command.CStr() ); #endif } /*static*/ WBEntity* RosaGame::GetPlayer() { const Array* const pPlayers = WBComponentArrays::GetComponents(); if( !pPlayers ) { return NULL; } const Array& Players = *pPlayers; if( Players.Empty() ) { return NULL; } WBCompRosaPlayer* const pPlayer = Players[0]; DEVASSERT( pPlayer ); return pPlayer->GetEntity(); } /*static*/ Vector RosaGame::GetPlayerLocation() { WBEntity* const pPlayer = GetPlayer(); DEVASSERT( pPlayer ); WBCompRosaTransform* const pTransform = pPlayer->GetTransformComponent(); DEVASSERT( pTransform ); return pTransform->GetLocation(); } /*static*/ Angles RosaGame::GetPlayerOrientation() { WBEntity* const pPlayer = GetPlayer(); DEVASSERT( pPlayer ); WBCompRosaTransform* const pTransform = pPlayer->GetTransformComponent(); DEVASSERT( pTransform ); return pTransform->GetOrientation(); } /*static*/ Vector RosaGame::GetPlayerViewLocation() { WBEntity* const pPlayer = GetPlayer(); DEVASSERT( pPlayer ); WBCompRosaTransform* const pTransform = pPlayer->GetTransformComponent(); DEVASSERT( pTransform ); WBCompRosaCamera* const pCamera = WB_GETCOMP( pPlayer, RosaCamera ); DEVASSERT( pCamera ); return pCamera->GetModifiedTranslation( WBCompRosaCamera::EVM_All, pTransform->GetLocation() ); } /*static*/ Angles RosaGame::GetPlayerViewOrientation() { WBEntity* const pPlayer = GetPlayer(); DEVASSERT( pPlayer ); WBCompRosaTransform* const pTransform = pPlayer->GetTransformComponent(); DEVASSERT( pTransform ); WBCompRosaCamera* const pCamera = WB_GETCOMP( pPlayer, RosaCamera ); DEVASSERT( pCamera ); return pCamera->GetModifiedOrientation( WBCompRosaCamera::EVM_All, pTransform->GetOrientation() ); } /*static*/ Vector RosaGame::GetPlayerFeetLocation() { WBEntity* const pPlayer = GetPlayer(); DEVASSERT( pPlayer ); WBCompRosaTransform* const pTransform = pPlayer->GetTransformComponent(); DEVASSERT( pTransform ); WBCompRosaCollision* const pCollision = WB_GETCOMP( pPlayer, RosaCollision ); DEVASSERT( pCollision ); return pTransform->GetLocation() - Vector( 0.0f, 0.0f, pCollision->GetExtents().z ); } // HACKHACK so I'm not doing so many lookups for player feet in minimap SDPs static Vector sCachedPlayerFeetLocation; /*static*/ void RosaGame::CachePlayerFeetLocation() { sCachedPlayerFeetLocation = GetPlayerFeetLocation(); } /*static*/ Vector& RosaGame::GetCachedPlayerFeetLocation() { return sCachedPlayerFeetLocation; } /*static*/ bool RosaGame::IsPlayerAlive() { WBEntity* const pPlayer = GetPlayer(); if( !pPlayer ) { return false; } WBCompRosaHealth* const pHealth = WB_GETCOMP( pPlayer, RosaHealth ); DEVASSERT( pHealth ); if( pHealth->IsDead() ) { return false; } return true; } /*static*/ bool RosaGame::IsPlayerDisablingPause() { WBEntity* const pPlayer = GetPlayer(); if( !pPlayer ) { return false; } WBCompRosaPlayer* const pPlayerComponent = WB_GETCOMP( pPlayer, RosaPlayer ); DEVASSERT( pPlayerComponent ); return pPlayerComponent->IsDisablingPause(); } /*static*/ bool RosaGame::IsPlayerVisible() { WBEntity* const pPlayer = GetPlayer(); if( !pPlayer ) { return false; } WBCompRosaVisible* const pVisible = WB_GETCOMP( pPlayer, RosaVisible ); DEVASSERT( pVisible ); return pVisible->IsVisible(); } /*static*/ bool RosaGame::IsGamePaused() { RosaFramework* const pFramework = RosaFramework::GetInstance(); DEVASSERT( pFramework ); UIManager* const pUIManager = pFramework->GetUIManager(); DEVASSERT( pUIManager ); UIStack* const pUIStack = pUIManager->GetUIStack(); DEVASSERT( pUIStack ); return pUIStack->PausesGame(); } /*static*/ UIWidgetImage* RosaGame::GetMinimapImage() { RosaFramework* const pFramework = RosaFramework::GetInstance(); DEVASSERT( pFramework ); UIManager* const pUIManager = pFramework->GetUIManager(); DEVASSERT( pUIManager ); STATIC_HASHED_STRING( HUD ); UIScreen* const pHUDScreen = pUIManager->GetScreen( sHUD ); DEVASSERT( pHUDScreen ); STATIC_HASHED_STRING( Minimap ); UIWidgetImage* const pMinimapImage = pHUDScreen->GetWidget( sMinimap ); return pMinimapImage; } #if ROSA_USE_MAXIMAP /*static*/ UIWidgetImage* RosaGame::GetMaximapImage() { RosaFramework* const pFramework = RosaFramework::GetInstance(); DEVASSERT( pFramework ); UIManager* const pUIManager = pFramework->GetUIManager(); DEVASSERT( pUIManager ); STATIC_HASHED_STRING( HUD ); UIScreen* const pHUDScreen = pUIManager->GetScreen( sHUD ); DEVASSERT( pHUDScreen ); STATIC_HASHED_STRING( Maximap ); UIWidgetImage* const pMaximapImage = pHUDScreen->GetWidget( sMaximap ); return pMaximapImage; } #endif #include #include #include #include namespace graphlab { } // end of namespace graphlab shared_model/validators/query_validator.hpp /** * Copyright Soramitsu Co., Ltd. 2017 All Rights Reserved. * http://soramitsu.co.jp * * 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 IROHA_SHARED_MODEL_QUERY_VALIDATOR_HPP #define IROHA_SHARED_MODEL_QUERY_VALIDATOR_HPP #include #include "interfaces/queries/query.hpp" #include "validators/answer.hpp" namespace shared_model { namespace validation { /** * Visitor used by query validator to validate each concrete query * @tparam FieldValidator - field validator type */ template class QueryValidatorVisitor : public boost::static_visitor { public: QueryValidatorVisitor(const FieldValidator &validator = FieldValidator()) : validator_(validator) {} ReasonsGroupType operator()(const interface::GetAccount &qry) const { ReasonsGroupType reason; reason.first = "GetAccount"; validator_.validateAccountId(reason, qry.accountId()); return reason; } ReasonsGroupType operator()(const interface::GetSignatories &qry) const { ReasonsGroupType reason; reason.first = "GetSignatories"; validator_.validateAccountId(reason, qry.accountId()); return reason; } ReasonsGroupType operator()( const interface::GetAccountTransactions &qry) const { ReasonsGroupType reason; reason.first = "GetAccountTransactions"; validator_.validateAccountId(reason, qry.accountId()); return reason; } ReasonsGroupType operator()( const interface::GetAccountAssetTransactions &qry) const { ReasonsGroupType reason; reason.first = "GetAccountAssetTransactions"; validator_.validateAccountId(reason, qry.accountId()); validator_.validateAssetId(reason, qry.assetId()); return reason; } ReasonsGroupType operator()(const interface::GetTransactions &qry) const { ReasonsGroupType reason; reason.first = "GetTransactions"; return reason; } ReasonsGroupType operator()( const interface::GetAccountAssets &qry) const { ReasonsGroupType reason; reason.first = "GetAccountAssets"; validator_.validateAccountId(reason, qry.accountId()); return reason; } ReasonsGroupType operator()( const interface::GetAccountDetail &qry) const { ReasonsGroupType reason; reason.first = "GetAccountDetail"; validator_.validateAccountId(reason, qry.accountId()); return reason; } ReasonsGroupType operator()(const interface::GetRoles &qry) const { ReasonsGroupType reason; reason.first = "GetRoles"; return reason; } ReasonsGroupType operator()( const interface::GetRolePermissions &qry) const { ReasonsGroupType reason; reason.first = "GetRolePermissions"; validator_.validateRoleId(reason, qry.roleId()); return reason; } ReasonsGroupType operator()(const interface::GetAssetInfo &qry) const { ReasonsGroupType reason; reason.first = "GetAssetInfo"; validator_.validateAssetId(reason, qry.assetId()); return reason; } private: FieldValidator validator_; }; /** * Class that validates query field from query * @tparam FieldValidator - field validator type * @tparam QueryFieldValidator - concrete query validator type */ template class QueryValidator { public: QueryValidator(const FieldValidator &field_validator = FieldValidator(), const QueryFieldValidator &query_field_validator = QueryFieldValidator()) : field_validator_(field_validator), query_field_validator_(query_field_validator) {} /** * Applies validation to given query * @param qry - query to validate * @return Answer containing found error if any */ Answer validate(const interface::Query &qry) const { Answer answer; std::string qry_reason_name = "Query"; ReasonsGroupType qry_reason(qry_reason_name, GroupedReasons()); field_validator_.validateCreatorAccountId(qry_reason, qry.creatorAccountId()); field_validator_.validateCreatedTime(qry_reason, qry.createdTime()); field_validator_.validateCounter(qry_reason, qry.queryCounter()); if (not qry_reason.second.empty()) { answer.addReason(std::move(qry_reason)); } auto reason = boost::apply_visitor(query_field_validator_, qry.get()); if (not reason.second.empty()) { answer.addReason(std::move(reason)); } return answer; } private: Answer answer_; FieldValidator field_validator_; QueryFieldValidator query_field_validator_; }; } // namespace validation } // namespace shared_model #endif // IROHA_SHARED_MODEL_QUERY_VALIDATOR_HPP kukkalli/oai-cn5g-fed /** * Namf_Communication * AMF Communication Service © 2019, 3GPP Organizational Partners (ARIB, ATIS, * CCSA, ETSI, TSDSI, TTA, TTC). All rights reserved. * * The version of the OpenAPI document: 1.1.0.alpha-1 * * * NOTE: This class is auto generated by OpenAPI Generator * (https://openapi-generator.tech). https://openapi-generator.tech Do not edit * the class manually. */ #include "Arp.h" namespace oai { namespace amf { namespace model { Arp::Arp() { m_PriorityLevel = 0; } Arp::~Arp() {} void Arp::validate() { // TODO: implement validation } void to_json(nlohmann::json& j, const Arp& o) { j = nlohmann::json(); j["priorityLevel"] = o.m_PriorityLevel; j["preemptCap"] = o.m_PreemptCap; j["preemptVuln"] = o.m_PreemptVuln; } void from_json(const nlohmann::json& j, Arp& o) { j.at("priorityLevel").get_to(o.m_PriorityLevel); j.at("preemptCap").get_to(o.m_PreemptCap); j.at("preemptVuln").get_to(o.m_PreemptVuln); } int32_t Arp::getPriorityLevel() const { return m_PriorityLevel; } void Arp::setPriorityLevel(int32_t const value) { m_PriorityLevel = value; } PreemptionCapability Arp::getPreemptCap() const { return m_PreemptCap; } void Arp::setPreemptCap(PreemptionCapability const& value) { m_PreemptCap = value; } PreemptionVulnerability Arp::getPreemptVuln() const { return m_PreemptVuln; } void Arp::setPreemptVuln(PreemptionVulnerability const& value) { m_PreemptVuln = value; } } // namespace model } // namespace amf } // namespace oai memset0x3f/usaco /* ID: cloudzf2 PROG: subset LANG: C++11 */ #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; int main(int argc, const char * argv[]) { ifstream fin ("subset.in"); ofstream fout ("subset.out"); int N; fin >> N; int sum = N * (1 + N) / 2; if (sum % 2 == 1) { fout << 0 << endl; return 0; } int M = sum / 2 + 1; vector dp(M, 0); dp[0] = 1; for (int i = 1; i <= N; i++) { for (int j = M - 1; j >= 0; j--) { if (dp[j] > 0 && j + i < M) dp[j + i] += dp[j]; } } fout << dp[M - 1] / 2 << endl; return 0; } #include "text.h" #include #include CommandText::CommandText(){ }; bool CommandText::isMultiLine(){ return false; }; ICommand *CommandText::create(){ return new CommandText(); }; QString CommandText::name(){ return "text"; }; /* * @command line * @author * @usage text * @param x1 - requared, integer * @param y1 - requared, integer * @param text - requared, string * */ void CommandText::setParams(QStringList list){ m_listParams << list; m_sCheck = ""; m_bCheck = true; QString sUsage = " Usage: 'text '"; if(m_listParams.size() != 3){ m_sCheck = "Expected 3 params. " + sUsage; m_bCheck = false; return; } bool bConvert = false; m_nX1 = m_listParams[0].toInt(&bConvert,10); if(!bConvert){ m_sCheck = "Parameter x1 must be integer. " + sUsage; m_bCheck = false; return; } bConvert = false; m_nY1 = m_listParams[1].toInt(&bConvert,10); if(!bConvert){ m_sCheck = "Parameter y1 must be integer. " + sUsage; m_bCheck = false; return; } bConvert = false; m_nColor = m_listParams[2].toInt(&bConvert,16); if(!bConvert){ m_sCheck = "Parameter color must be integer. " + sUsage; m_bCheck = false; return; } QString m_sText = m_listParams[3]; }; bool CommandText::check(){ return m_bCheck; }; bool CommandText::check(QString &strCheck){ strCheck = m_sCheck; return m_bCheck; }; QString CommandText::code(){ return name() + " " + m_listParams.join(" "); } void CommandText::appendCode(QString){ // this command is single line }; void CommandText::run(ICore *pCore){ if(!m_bCheck) return; // if(vFrames) }; //Program Pembayaran Parkir //Dibuat Pada : Desember 2021 //Tugas dibuat untuk memenuhi nilai Tugas Besar Akhir Semester DDP (Dasar-dasar Pemrograman) //Prodi : D3 Teknik Informatika //Politeknik Negeri Bandung //Kelompok B5 : 211511038 // 211511063 #include #include "Main.h"; #include using namespace std; /* run this program using the console pauser or add your own getch, system("pause") or input loop */ int main() { menu_utama(); return 0; } 1-10 /* ****************************************************************** ** ** OpenSees - Open System for Earthquake Engineering Simulation ** ** Pacific Earthquake Engineering Research Center ** ** ** ** ** ** (C) Copyright 2001, The Regents of the University of California ** ** All Rights Reserved. ** ** ** ** Commercial use of this program without express permission of the ** ** University of California, Berkeley, is strictly prohibited. See ** ** file 'COPYRIGHT' in main directory for information on usage and ** ** redistribution, and for a DISCLAIMER OF ALL WARRANTIES. ** ** ** ** Developed by: ** ** () ** ** () ** ** () ** ** ** ** Reliability module developed by: ** ** () ** ** () ** ** ** ** ****************************************************************** */ // $Revision: 1.21 $ // $Date: 2010-09-13 21:38:31 $ // $Source: /usr/local/cvs/OpenSees/SRC/reliability/analysis/sensitivity/FiniteDifferenceGradient.cpp,v $ // // Written by: // () // () // #include #include #include #include #include #include FiniteDifferenceGradient::FiniteDifferenceGradient(FunctionEvaluator *passedGFunEvaluator, ReliabilityDomain *passedReliabilityDomain, Domain *passedOpenSeesDomain) :GradientEvaluator(passedReliabilityDomain, passedGFunEvaluator), theOpenSeesDomain(passedOpenSeesDomain) { int nparam = theOpenSeesDomain->getNumParameters(); grad_g = new Vector(nparam); } FiniteDifferenceGradient::~FiniteDifferenceGradient() { if (grad_g != 0) delete grad_g; } const Vector& FiniteDifferenceGradient::getGradient() { return *grad_g; } int FiniteDifferenceGradient::computeGradient(double g) { // note FiniteDifferentGradient presumes that the expression has already been evaluated once with // default parameter values and the result is passed in with variable g. Therefore it is only // computing the perturbations from this default state // Initialize gradient vector grad_g->Zero(); // get limit-state function from reliability domain int lsf = theReliabilityDomain->getTagOfActiveLimitStateFunction(); LimitStateFunction *theLimitStateFunction = theReliabilityDomain->getLimitStateFunctionPtr(lsf); const char *lsfExpression = theLimitStateFunction->getExpression(); // get parameters created in the domain int nparam = theOpenSeesDomain->getNumParameters(); // now loop through to create gradient vector // note this is a for loop because there may be some conflict from a nested iterator already // called at a higher level. for (int i = 0; i < nparam; i++) { // get parameter tag Parameter *theParam = theOpenSeesDomain->getParameterFromIndex(i); int tag = theParam->getTag(); double result = 0; // check for analytic gradient first const char *gradExpression = theLimitStateFunction->getGradientExpression(tag); if (gradExpression != 0) { theFunctionEvaluator->setExpression(gradExpression); if (theFunctionEvaluator->setVariables() < 0) { opserr << "ERROR FiniteDifferenceGradient -- error setting variables in namespace" << endln; return -1; } result = theFunctionEvaluator->evaluateExpression(); // Reset limit state function in evaluator -- subsequent calls could receive gradient expression theFunctionEvaluator->setExpression(lsfExpression); } // if no analytic gradient automatically do finite differences else { // use parameter defined perturbation double h = theParam->getPerturbation(); double original = theParam->getValue(); theParam->update(original+h); // set perturbed values in the variable namespace if (theFunctionEvaluator->setVariables() < 0) { opserr << "ERROR FiniteDifferenceGradient -- error setting variables in namespace" << endln; return -1; } // run analysis if (theFunctionEvaluator->runAnalysis() < 0) { opserr << "ERROR FiniteDifferenceGradient -- error running analysis" << endln; return -1; } // evaluate LSF and obtain result theFunctionEvaluator->setExpression(lsfExpression); // Add gradient contribution double g_perturbed = theFunctionEvaluator->evaluateExpression(); result = (g_perturbed-g)/h; // return values to previous state theParam->update(original); //opserr << "g_pert " << g_perturbed << ", g0 = " << g << endln; } (*grad_g)(i) = result; } return 0; } // (C) Copyright 1996,1998 by Autodesk, Inc. // // Permission to use, copy, modify, and distribute this software in // object code form for any purpose and without fee is hereby granted, // provided that the above copyright notice appears in all copies and // that both that copyright notice and the limited warranty and // restricted rights notice below appear in all supporting // documentation. // // AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS. // AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF // MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC. // DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE // UNINTERRUPTED OR ERROR FREE. // // Use, duplication, or disclosure by the U.S. Government is subject to // restrictions set forth in FAR 52.227-19 (Commercial Computer // Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii) // (Rights in Technical Data and Computer Software), as applicable. // // stylcvrt.cpp // #include #include #include "aced.h" #include "dbsymtb.h" #include "dbapserv.h" #include "acgi.h" // globals // static AcGiTextStyle AsdkStyle; class AsdkTxtStyleSamp: public AcDbEntity { public: ACRX_DECLARE_MEMBERS(AsdkTxtStyleSamp); virtual Adesk::Boolean worldDraw(AcGiWorldDraw *); Acad::ErrorStatus transformBy(const AcGeMatrix3d &); }; ACRX_DXF_DEFINE_MEMBERS(AsdkTxtStyleSamp,AcDbEntity, AcDb::kDHL_CURRENT, AcDb::kMReleaseCurrent, 0,\ AsdkTxtStyleSamp,AsdkTextStyle Sample); Acad::ErrorStatus AsdkTxtStyleSamp::transformBy( const AcGeMatrix3d &xfm) { return Acad::eOk; } Adesk::Boolean AsdkTxtStyleSamp::worldDraw(AcGiWorldDraw* pW) { AcGePoint3d pos(0.0, 0.0, 0.0); AcGeVector3d norm(0.0, 0.0, 1.0); AcGeVector3d dir(1.0, 0.2, 0.0); char *pStr = "Test string"; int len = strlen(pStr); pW->geometry().text(pos, norm, dir, pStr, len, Adesk::kFalse, AsdkStyle); return Adesk::kTrue; } // THE FOLLOWING CODE APPEARS IN THE SDK DOCUMENT. // Get an AcGiTextStyle from an acDbTextStyleTableRecord. // Try to map as many characteristics as possible. // void getTextStyle(AcGiTextStyle& newStyle, AcDbObjectId styleId) { AcDbTextStyleTableRecord *pOldStyle; acdbOpenObject((AcDbObject*&)pOldStyle, styleId, AcDb::kForRead); const char *pTmpStr; pOldStyle->fileName(pTmpStr); newStyle.setFileName(pTmpStr); pOldStyle->bigFontFileName(pTmpStr); newStyle.setBigFontFileName(pTmpStr); newStyle.setTextSize(pOldStyle->textSize()); newStyle.setXScale(pOldStyle->xScale()); newStyle.setObliquingAngle(pOldStyle->obliquingAngle()); pOldStyle->close(); newStyle.loadStyleRec(); } // END CODE APPEARING IN SDK DOCUMENT. void addAsdkTxtStyleSampObject() { // First set up the styleId global with a valid // ObjectId for an AcDbTextStyleTableRecord. // AcDbTextStyleTable *pStyleTable; acdbHostApplicationServices()->workingDatabase() ->getSymbolTable(pStyleTable, AcDb::kForRead); AcDbTextStyleTableIterator *pIterator; pStyleTable->newIterator(pIterator); // get ObjectId of first record in table // AcDbObjectId styleId; pIterator->getRecordId(styleId); delete pIterator; pStyleTable->close(); // convert the AcDbTextStyleTableRecord to an // AcGiTextStyle using the global AsdkStyle // AcGiTextStyle object as the recipient. // getTextStyle(AsdkStyle, styleId); // Ok, now make one of our AsdkTxtStyleSamp entities // and add it to Model Space. AsdkTxtStyleSamp *pNewObj = new AsdkTxtStyleSamp; AcDbBlockTable *pBlockTable; acdbHostApplicationServices()->workingDatabase() ->getSymbolTable(pBlockTable, AcDb::kForRead); AcDbBlockTableRecord *pBlock; pBlockTable->getAt(ACDB_MODEL_SPACE, pBlock, AcDb::kForWrite); AcDbObjectId objId; pBlock->appendAcDbEntity(objId, pNewObj); pBlockTable->close(); pBlock->close(); pNewObj->close(); } static void initAsdkTxtStyleSamp() { AsdkTxtStyleSamp::rxInit(); acrxBuildClassHierarchy(); acedRegCmds->addCommand("ASDK_STYLE_CONVERT_SAMP", "ASDKSTYLECVRT", "STYLECVRT", ACRX_CMD_TRANSPARENT, addAsdkTxtStyleSampObject); } extern "C" AcRx::AppRetCode acrxEntryPoint(AcRx::AppMsgCode msg, void* appId) { switch(msg) { case AcRx::kInitAppMsg: acrxDynamicLinker->unlockApplication(appId); acrxDynamicLinker->registerAppMDIAware(appId); initAsdkTxtStyleSamp(); break; case AcRx::kUnloadAppMsg: acedRegCmds->removeGroup("ASDK_STYLE_CONVERT_SAMP"); deleteAcRxClass(AsdkTxtStyleSamp::desc()); } return AcRx::kRetOK; } engine/src/cython/errors.cpp #include #include #include // TODO: temporal generic error handler. // Build a custom exception hierarchy for RAL, Calcite and pyBlazing #define RAISE_ERROR(E) \ extern PyObject * E##Error_; \ void raise##E##Error() { \ try { \ if(PyErr_Occurred()) \ ; \ else \ throw; \ } catch(const std::exception & e) { \ std::string message = std::string{"[" #E " Error] "} + e.what(); \ PyErr_SetString(E##Error_, message.c_str()); \ } catch(...) { \ PyErr_SetString(PyExc_RuntimeError, "Unknown " #E " Error"); \ } \ } RAISE_ERROR(Initialize) RAISE_ERROR(Finalize) RAISE_ERROR(RunQuery) RAISE_ERROR(ParseSchema) RAISE_ERROR(RegisterFileSystemHDFS) RAISE_ERROR(RegisterFileSystemGCS) RAISE_ERROR(RegisterFileSystemS3) RAISE_ERROR(RegisterFileSystemLocal) 0 #include #include int main(int argc, char **argv) { const auto cwd = std::filesystem::current_path().string(); std::cout << "Hello " << cwd << std::endl; return 0; } anirbandey303/Hack-Codes class Solution { public: int findDuplicate(vector& nums) { int duplicate = -1; for (int i = 0; i < nums.size(); i++) { int cur = abs(nums[i]); if (nums[cur] < 0) { duplicate = cur; break; } nums[cur] *= -1; } // Restore numbers for (auto& num : nums) num = abs(num); return duplicate; } };ash/system/session/tray_session_length_limit.cc // 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 "ash/system/session/tray_session_length_limit.h" #include #include #include #include "ash/resources/vector_icons/vector_icons.h" #include "ash/session/session_controller.h" #include "ash/shell.h" #include "ash/strings/grit/ash_strings.h" #include "ash/system/model/session_length_limit_model.h" #include "ash/system/model/system_tray_model.h" #include "ash/system/tray/label_tray_view.h" #include "ash/system/tray/system_tray.h" #include "ash/system/tray/tray_constants.h" #include "base/logging.h" #include "base/strings/utf_string_conversions.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/l10n/time_format.h" #include "ui/gfx/paint_vector_icon.h" #include "ui/views/view.h" namespace ash { TraySessionLengthLimit::TraySessionLengthLimit(SystemTray* system_tray) : SystemTrayItem(system_tray, UMA_SESSION_LENGTH_LIMIT), model_(Shell::Get()->system_tray_model()->session_length_limit()) { model_->AddObserver(this); OnSessionLengthLimitUpdated(); } TraySessionLengthLimit::~TraySessionLengthLimit() { model_->RemoveObserver(this); } // Add view to tray bubble. views::View* TraySessionLengthLimit::CreateDefaultView(LoginStatus status) { CHECK(!tray_bubble_view_); if (model_->limit_state() == SessionLengthLimitModel::LIMIT_NONE) return nullptr; tray_bubble_view_ = new LabelTrayView(nullptr, kSystemMenuTimerIcon); tray_bubble_view_->SetMessage(ComposeTrayBubbleMessage()); return tray_bubble_view_; } // View has been removed from tray bubble. void TraySessionLengthLimit::OnDefaultViewDestroyed() { tray_bubble_view_ = nullptr; } void TraySessionLengthLimit::OnSessionLengthLimitUpdated() { // Don't show tray item until the user is logged in. if (!Shell::Get()->session_controller()->IsActiveUserSessionStarted()) return; UpdateTrayBubbleView(); } void TraySessionLengthLimit::UpdateTrayBubbleView() const { if (!tray_bubble_view_) return; if (model_->limit_state() == SessionLengthLimitModel::LIMIT_NONE) tray_bubble_view_->SetMessage(base::string16()); else tray_bubble_view_->SetMessage(ComposeTrayBubbleMessage()); tray_bubble_view_->Layout(); } base::string16 TraySessionLengthLimit::ComposeTrayBubbleMessage() const { return l10n_util::GetStringFUTF16( IDS_ASH_STATUS_TRAY_BUBBLE_SESSION_LENGTH_LIMIT, ui::TimeFormat::Detailed(ui::TimeFormat::FORMAT_DURATION, ui::TimeFormat::LENGTH_LONG, 10, model_->remaining_session_time())); } } // namespace ash kas1e/Eldritch #include "core.h" #include "wbpebinaryop.h" #include "configmanager.h" #include "../wbparamevaluatorfactory.h" WBPEBinaryOp::WBPEBinaryOp() : m_InputA(nullptr), m_InputB(nullptr) {} WBPEBinaryOp::~WBPEBinaryOp() { SafeDelete(m_InputA); SafeDelete(m_InputB); } void WBPEBinaryOp::InitializeFromDefinition( const SimpleString& DefinitionName) { STATICHASH(InputA); STATICHASH(InputB); MAKEHASH(DefinitionName); m_InputA = WBParamEvaluatorFactory::Create( ConfigManager::GetString(sInputA, "", sDefinitionName)); m_InputB = WBParamEvaluatorFactory::Create( ConfigManager::GetString(sInputB, "", sDefinitionName)); }10-100 #include "ndicomm.h" #include "ui_ndicomm.h" #include #include QString serialName = "COM1"; int baudRate = 1228739; QSerialPort::Parity parity = QSerialPort::NoParity; QSerialPort::StopBits stopBits = QSerialPort::OneStop; QSerialPort::DataBits dataBits = QSerialPort::Data8; QSerialPort::FlowControl flowControl = QSerialPort::HardwareControl; bool openSuccess = false; NdiComm::NdiComm(QWidget *parent) : QWidget(parent), ui(new Ui::NdiComm), isPortOpened(false), isStarted(false) { qRegisterMetaType>("Coordinates"); qRegisterMetaType>("QVector&"); ui->setupUi(this); initPort(); ndiCommProc = new NdiCommProc(); connect(ndiCommProc, &NdiCommProc::initFinished, this, [=](QString msg){emit this->initFinished(msg);}); connect(ndiCommProc, &NdiCommProc::dataReady, this, [=](const QVector& data){ this->markers = data; emit this->dataReady(markers);}); connect(this, &NdiComm::serialOpened, ndiCommProc, &NdiCommProc::openSerial, Qt::BlockingQueuedConnection); connect(this, &NdiComm::commStarted, ndiCommProc, &NdiCommProc::ndiCommStart); } NdiComm::~NdiComm() { delete ui; ndiCommProc->isRunning = false; //ndiThread->quit(); //Not recommand, but can work } void NdiComm::initPort() { //query available ports foreach (const QSerialPortInfo &info, QSerialPortInfo::availablePorts()) { qDebug() << tr("Name: ") << info.portName(); qDebug() << tr("Description: ") << info.description(); qDebug() << tr("Manufacturer: ") << info.manufacturer(); QSerialPort tempSerial; tempSerial.setPort(info); if(tempSerial.open(QIODevice::ReadWrite)){ ui->cmbPortName->addItem(info.portName()); tempSerial.close(); } } //set buadrate combobox QStringList baudList; baudList << "9600" << "14400" << "38400" << "57600" << "115200" << "921600" << "1228739"; ui->cmbBuadrate->addItems(baudList); ui->cmbBuadrate->setCurrentText("1228739"); //set parity combobox QStringList parityList; parityList << tr("None") << tr("Odd") << tr("Even"); ui->cmbParity->addItems(parityList); ui->cmbParity->setCurrentText("None"); //set databits combobox QStringList dataBitsList; dataBitsList << "5" << "6" << "7" << "8"; ui->cmbDataBits->addItems(dataBitsList); ui->cmbDataBits->setCurrentText("8"); //set stopbits combobox QStringList stopBitsList; stopBitsList << "1" << "1.5" << "2"; ui->cmbStopBits->addItems(stopBitsList); ui->cmbStopBits->setCurrentText("1"); QStringList flowCtrlList; flowCtrlList << tr("None") << tr("Hardware") << tr("Software"); ui->cmbFlowCtrl->addItems(flowCtrlList); ui->cmbFlowCtrl->setCurrentText(tr("Hardware")); } QSerialPort::Parity NdiComm::getParity(QString text) { if(text == tr("None")) return QSerialPort::NoParity; else if(text == tr("Odd")) return QSerialPort::OddParity; else if(text == tr("Even")) return QSerialPort::EvenParity; else return QSerialPort::NoParity; } QSerialPort::DataBits NdiComm::getDataBits(QString text) { switch(text.toInt()){ case 5: return QSerialPort::Data5; case 6: return QSerialPort::Data6; case 7: return QSerialPort::Data7; case 8: return QSerialPort::Data8; default: return QSerialPort::Data8; } } QSerialPort::StopBits NdiComm::getStopBits(QString text) { if(text == "1") return QSerialPort::OneStop; else if(text == "1.5") return QSerialPort::OneAndHalfStop; else if(text == "2") return QSerialPort::TwoStop; else return QSerialPort::OneStop; } QSerialPort::FlowControl NdiComm::getFlowCtrl(QString text) { if(text == tr("None")) return QSerialPort::NoFlowControl; else if(text == tr("Hardware")) return QSerialPort::HardwareControl; else if(text == tr("Software")) return QSerialPort::SoftwareControl; else return QSerialPort::NoFlowControl; } void NdiComm::printThread(QString front) { qDebug()<< front << tr(" Thread is: ") << QThread::currentThreadId(); } void NdiComm::recvProc() { } void NdiComm::on_refreshButton_clicked() { initPort(); //refresh available ports } void NdiComm::on_openCloseButton_clicked() { if(!isPortOpened){ // serial not open serialName = ui->cmbPortName->currentText(); baudRate = ui->cmbBuadrate->currentText().toInt(); parity = getParity(ui->cmbParity->currentText()); dataBits = getDataBits(ui->cmbDataBits->currentText()); stopBits = getStopBits(ui->cmbStopBits->currentText()); flowControl = getFlowCtrl(ui->cmbFlowCtrl->currentText()); emit serialOpened(true); if(openSuccess){ // serial open success isPortOpened = true; ui->openCloseButton->setText(tr("Close")); ui->openCloseButton->setIcon(QIcon(":/icon/res/stop.ico")); qDebug() << "Open serial port success!"; } else { // serial open failed qDebug() << "Open serial port failed!"; } } else { // serial is already open if(isStarted){ // is communicating with ndi qDebug() << tr("Please stop running first!"); } else { // not communicating with ndi emit serialOpened(false); if(!openSuccess){ // serial close success isPortOpened = false; ui->openCloseButton->setText(tr("Open")); ui->openCloseButton->setIcon(QIcon(":/icon/res/start.ico")); qDebug() << "Close serial port success!"; } else { qDebug() << "Close serial port failed!"; } } } } void NdiComm::on_startButton_clicked() { if(!isStarted){ //Not start if(isPortOpened){ // serial is already opened emit commStarted(); ui->startButton->setText(tr("Stop")); isStarted = true; ndiCommProc->isRunning = true; } else { // serial not open qDebug() << tr("Please Open Serial Port First!"); } } else { // is already start ndiCommProc->isRunning = false; ui->startButton->setText(tr("Start")); isStarted = false; // ndiThread->quit(); // connect(ndiCommProc->ndiThread, &QThread::finished, this, [=](){ // ui->startButton->setText(tr("Start")); // isStarted = false;}); } } void NdiComm::changeEvent(QEvent *event) { if(event->type() == QEvent::LanguageChange) { ui->retranslateUi(this); } else { QWidget::changeEvent(event); } } /********************NdiCommProc*****************************/ /* * * * Processing time consuming operation * * ************************************************************/ NdiCommProc::NdiCommProc(QObject *parent) : QObject (parent), isRunning(false) { ndiThread = new QThread(); this->moveToThread(ndiThread); serialPort = new QSerialPort(); serialPort->moveToThread(ndiThread); //connect(ndiThread, &QThread::started, this, &NdiCommProc::ndiCommStart); //connect(ndiThread, &QThread::finished, ndiThread, &QThread::deleteLater); ndiThread->start(); } NdiCommProc::~NdiCommProc() { } void NdiCommProc::openSerial(bool open) { if(open){ serialPort->setPortName(serialName); if(serialPort->open(QIODevice::ReadWrite)){ //open serial port success serialPort->setBaudRate(9600); serialPort->setParity(QSerialPort::NoParity); serialPort->setDataBits(QSerialPort::Data8); serialPort->setStopBits(QSerialPort::OneStop); serialPort->setFlowControl(QSerialPort::NoFlowControl); openSuccess = true; } else { openSuccess = false; } } else { if(isRunning == false){ serialPort->close(); openSuccess = false; } else { qDebug() << tr("Please Open Serial Port First!"); } } } void NdiCommProc::ndiCommStart() { if(!initsensor()){ //init Ndi return; } while (isRunning) { // data_read(); get_data(); QThread::msleep(10); } } void NdiCommProc::printThread(QString front) { qDebug()<< front << tr(" Thread is: ") << QThread::currentThreadId(); QVector markers; markers.push_back(QVector3D(1,2,3)); markers.push_back(QVector3D(2,4,5)); emit dataReady(markers); } //bool NdiCommProc::writeReadMsg(QByteArray msg) //{ // if(isRunning){ // serialPort->write(msg); // while (this->serialPort->waitForReadyRead(50)) // { // this->serialPort->readAll(); // } // return true; // } // else { // return false; // } //} bool NdiCommProc::writeReadMsg(QByteArray sendmsg, QByteArray recvmsg, int delay_ms, int read_ms) { if(isRunning){ serialPort->write(sendmsg); QThread::msleep(static_cast(delay_ms)); QByteArray recvbuf; while (this->serialPort->waitForReadyRead(read_ms)) { recvbuf.append(this->serialPort->readAll()); } if(recvbuf.contains(recvmsg)){ return true; } else{ qDebug() << "Response error!"; return false; } } else { return false; } } bool NdiCommProc::initsensor() { //FOR SU SHUN qDebug() << "Initializing~~"; QVector msgList; if(!writeReadMsg("VER 4\r", "Northern Digital Inc.",0,50)){ qDebug() << "Waiting for reset..."; writeReadMsg("RESET 0", "RESET", 8000, 50); } //QThread::msleep(5000); msgList << "APIREV \r" << "COMM 70001\r"; foreach(const QByteArray msg, msgList){ if(!writeReadMsg(msg,"",0,50)) return false; QThread::msleep(50); } QThread::msleep(60); serialPort->setBaudRate(baudRate); serialPort->setFlowControl(flowControl); msgList.clear(); msgList << "VER 5\r" << "GETINFO:Config.*1110\r" << "GET:Device.*722D\r"; foreach(const QByteArray msg, msgList){ if(!writeReadMsg(msg, "" , 0, 50)) return false; QThread::msleep(50); } msgList.clear(); msgList << "INIT:E3A5\r" << "GET:Device.*722D\r" << "PHSR:0020FF\r" << "PINIT:0131EA\r" << "PHSR:0020FF\r" << "GETINFO:Param.Tracking.*8D17\r" << "GETINFO:Features.Firmware.Version0492\r" << "GETINFO:Info.Status.Alerts340A\r" << "GETINFO:Info.Status.New Alerts33A3\r" << "GETINFO:Features.Hardware.Serial Number68E4\r" << "VER 4\r" << "GETINFO:Features.Tools.*F635\r" << "SFLIST:03500F\r" << "GETINFO:Param.Tracking.Selected VolumeC200\r" << "PHINF:0100753CAF\r" << "GETINFO:SCU-0.Info.Status.New AlertsAF34\r" << "GETINFO:SCU-0.Info.Status.AlertsC917\r" << "GETINFO:Info.Status.New Alerts33A3\r" << "GETINFO:Info.Status.Alerts340A\r" << "GETINFO:STB-0.Info.Status.New AlertsCC4F\r" << "GETINFO:STB-0.Info.Status.Alerts389B\r" << "TSTART:5423\r" << "BX:18033D6C\r" << "TSTOP:2C14\r" << "SET:Param.Tracking.Illuminator Rate=2237A\r" << "PHRQ:*********1****A4C1\r" << "PVWR:0200004E444900AF12000001000000000000010000000002DC32355A00000004000000040000000000403F000000000000000000000000000000000000000000000000610B\r" << "PVWR:0200400000204100000000000000000000000000000000000000001F853D4285EBE74100000000000000003333B24200000000A4700DC2A4700D4200000000000000002B7A\r" << "PVWR:020080000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000005DEA\r" << "PVWR:0200C0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000006EF1\r" << "PVWR:02010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000803F00000000678F\r" << "PVWR:020140000000000000803F00000000000000000000803F00000000000000000000803F00000000000000000000000000000000000000000000000000000000000000008535\r" << "PVWR:020180000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000009DD2\r" << "PVWR:0201C000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000AEC9\r" << "PVWR:0202000000000000000000000000000000000000000000000000000000000000000000000000000000000000010203000000000000000000000000000000001F1F1F1FC0FA\r" << "PVWR:020240090000004E44490000000000000000003837303034343900000000000000000000000000090101010100000000000000000000000000000000010101010000008755\r" << "PVWR:020280000000000000000000000000008000290000000000000000000080BF0000000000000000000000000000000000000000000000000000000000000000000000002FB1\r" << "PVWR:0202C000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000AE82\r" << "PINIT:0230AA\r" << "PHINF:0200753CEB\r" << "TSTART:5423\r" << "BX:18033D6C\r" << "TSTOP:2C14\r" << "PENA:02D9D3B\r" << "TSTART:5423\r" << "BX:18033D6C\r"; foreach(const QByteArray msg, msgList){ if(!writeReadMsg(msg, "", 0, 50)) return false; QThread::msleep(50); } qDebug() << "Init OK!"; return true; } void NdiCommProc::get_data() { // QElapsedTimer timer; // timer.start(); this->serialPort->clear(); QByteArray msg = "BX:18033D6C\r"; //msg = "BX:1000FEAD\r"; serialPort->write(msg); int index = 0; recvbuf.clear(); while(this->serialPort->waitForReadyRead(10)){ recvbuf.append(this->serialPort->readAll()); } const char* p = recvbuf.data(); //get a pointer to received data index += 30; unsigned char numofpoints = getNum(&(p[index])); if (numofpoints > 8) index += 1; index += 2; if(recvbuf.size() < (index + numofpoints*12)){ if(this->serialPort->waitForReadyRead(50)) return; recvbuf.append(this->serialPort->readAll()); if(recvbuf.size() < (index + numofpoints*12)){ qDebug() <<"NdiCommProc: received data length is wrong!"; return; } } QVector markers; for (int i = 0; i < numofpoints; i++) { float coordinate[3] = {0}; for (int j = 0; j < 3; j++) { coordinate[j] = getNum(&(p[index])); index += 4; } markers.push_back(QVector3D(coordinate[0], coordinate[1], coordinate[2])); } emit dataReady(markers); // QThread::msleep(10); //这个地方我怀疑是发的快了 所以出问题了 // qDebug() << "Communication time consuming:" << (double)timer.nsecsElapsed()/(double)1000000 < T NdiCommProc::getNum(const char *p) { T temp; memcpy(&temp, p, sizeof (T)); return temp; } /************************************************* Function: calculate_crc16 Description: 通用的16位CRC校验算法 Input: wCRCin:CRC16算法的初始值 wCPoly:特征多项式 wResultXOR:结果异或值 input_invert:输入值是否反转 ouput_invert:输出值是否反转 puchMsg:开始校验的数据的起始地址 usDataLen:校验的数据长度 Output: 无输出 Return: 16位CRC校验结果 Others: example:CRC-16/CCITT由本函数实现则填充参数如下: calculate_crc(0,0x1021,0,true,true,puchMsg,usDataLen) NDI校验 char* msg = "GET:Device.*"; quint16 x = calculate_crc16(0,0x8005,0, true, true, msg,12); *************************************************/ quint16 NdiCommProc::calculate_crc16(quint16 wCRCin, quint16 wCPoly, quint16 wResultXOR, bool input_invert, bool ouput_invert, const char *puchMsg, int usDataLen) { quint8 wChar = 0; while (usDataLen--) { wChar = *(puchMsg++); if(input_invert)//输入值反转 { quint8 temp_char = wChar; wChar=0; for(int i=0;i<8;++i) { if(temp_char&0x01) wChar|=0x01<<(7-i); temp_char>>=1; } } wCRCin ^= (wChar << 8); for (int i = 0; i < 8; i++) { if (wCRCin & 0x8000) wCRCin = (wCRCin << 1) ^ wCPoly; else wCRCin = wCRCin << 1; } } if(ouput_invert) { quint16 temp_short = wCRCin; wCRCin=0; for(int i=0;i<16;++i) { if(temp_short&0x01) wCRCin|=0x01<<(15-i); temp_short>>=1; } } return (wCRCin^wResultXOR); } #include "capturephotothread.h" CapturePhotoThread::CapturePhotoThread(QObject *parent) : QThread(parent) { } void CapturePhotoThread::takePhoto(const QString &path, QCameraImageCapture *img) { m_path = path; imgCapture = img; waitCondition.wakeAll(); } void CapturePhotoThread::run() { _positionSource = QGeoPositionInfoSource::createDefaultSource (0);//this); if (_positionSource) _positionSource->startUpdates (); forever { mutex.lock(); waitCondition.wait(&mutex); if (_positionSource) { _lastPosition = _positionSource->lastKnownPosition(); #ifdef SHOW_DEBUG qDebug () << "last position: " << _lastPosition; #endif emit lastCoordinate(_lastPosition.coordinate()); } imgCapture->capture(m_path); mutex.unlock(); } } tomgey/hidden-content /* * Window for showing out-of-viewport zoom- and panable preview * * Created on: Oct 21, 2014 * Author: tom */ #ifndef QTF_PREVIEW_WINDOW_HPP_ #define QTF_PREVIEW_WINDOW_HPP_ #include #include #include #include #include #include #include #include namespace qtfullscreensystem { namespace LR = LinksRouting; class QtPreviewWindow: public QWindow, protected QOpenGLFunctions, public LR::PreviewWindow { public: QtPreviewWindow(); void subscribeSlots(LR::SlotSubscriber& slot_subscriber); virtual void initialize(); /// Send geometry for preview (excluding space for margin/border) virtual void setPreviewGeometry(QRect const&); virtual void render(QPainter *painter) = 0; virtual void render(); virtual void update(double dt); virtual void release(); public slots: void renderLater(); void renderNow(); void onTileChanged(size_t x, size_t y, size_t zoom); protected: QRect _geometry; int _margin; bool _do_drag; float2 _last_mouse_pos; GLImageCache _image_cache; unsigned int _tile_map_change_id; LR::slot_t::type _subscribe_mouse; LR::slot_t::type _subscribe_popups; LR::slot_t::type _subscribe_tile_handler; virtual QRect getGeometry() const = 0; virtual HierarchicTileMapPtr getTilemap() const = 0; virtual void onMouseMove(float2 const& delta) {} virtual void onMouseDrag(float2 const& delta) {} virtual void onMouseLeave() {} virtual bool event(QEvent*); virtual void exposeEvent(QExposeEvent*); virtual void mouseReleaseEvent(QMouseEvent*); virtual void mouseMoveEvent(QMouseEvent*); virtual void wheelEvent(QWheelEvent*); private: bool _update_pending; HierarchicTileMapWeakPtr _last_tilemap; QOpenGLContext *_context; QOpenGLPaintDevice *_device; void init(); void updateGeometry(); }; class PopupWindow: public QtPreviewWindow { public: explicit PopupWindow(Popup* popup); virtual void render(QPainter *painter); virtual void update(double dt); virtual void onMouseMove(float2 const& delta); virtual void onMouseDrag(float2 const& delta); virtual void onMouseLeave(); protected: Popup *_popup; virtual QRect getGeometry() const; virtual HierarchicTileMapPtr getTilemap() const; }; class SeeThroughWindow: public QtPreviewWindow { public: explicit SeeThroughWindow(SeeThrough* seethrough); virtual void render(QPainter *painter); virtual void onMouseMove(float2 const& delta); virtual void onMouseDrag(float2 const& delta); virtual void onMouseLeave(); protected: SeeThrough *_see_through; virtual QRect getGeometry() const; virtual HierarchicTileMapPtr getTilemap() const; }; class SemanticPreviewWindow: public QtPreviewWindow { public: explicit SemanticPreviewWindow(LR::ClientWeakRef client); virtual void render(QPainter *painter); virtual void onMouseMove(float2 const& delta); virtual void onMouseDrag(float2 const& delta); virtual void onMouseLeave(); virtual void wheelEvent(QWheelEvent*); protected: LR::ClientWeakRef _client; virtual QRect getGeometry() const; virtual HierarchicTileMapPtr getTilemap() const; }; } // namespace qtfullscreensystem #endif /* PREVIEW_WINDOW_HPP_ */ 1000+ /*============================================================================= Copyright (c) 2011 Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) ==============================================================================*/ #if !defined(BOOST_FUSION_SINGLE_VIEW_DISTANCE_IMPL_JUL_07_2011_1348PM) #define BOOST_FUSION_SINGLE_VIEW_DISTANCE_IMPL_JUL_07_2011_1348PM #include #include namespace boost { namespace fusion { struct single_view_iterator_tag; namespace extension { template struct distance_impl; template<> struct distance_impl { template struct apply : mpl::minus { typedef typename mpl::minus::type type; BOOST_CONSTEXPR BOOST_FUSION_GPU_ENABLED static type call(First const& /*first*/, Last const& /*last*/) { return type(); } }; }; } }} #endif // Copyright (c) 2022 The Orbit 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 #include #include "OrbitBase/SharedState.h" #include "OrbitBase/StopSource.h" #include "OrbitBase/StopToken.h" namespace orbit_base { class StopTokenTest : public testing::Test { protected: StopTokenTest() : stop_token_(stop_source_.GetStopToken()) {} void RequestStop() { stop_source_.RequestStop(); } private: StopSource stop_source_; protected: StopToken stop_token_; }; TEST_F(StopTokenTest, RequestStop) { ASSERT_TRUE(stop_token_.IsStopPossible()); EXPECT_FALSE(stop_token_.IsStopRequested()); RequestStop(); ASSERT_TRUE(stop_token_.IsStopPossible()); EXPECT_TRUE(stop_token_.IsStopRequested()); } TEST_F(StopTokenTest, Copy) { StopToken stop_token_copy{stop_token_}; ASSERT_TRUE(stop_token_copy.IsStopPossible()); EXPECT_FALSE(stop_token_copy.IsStopRequested()); RequestStop(); ASSERT_TRUE(stop_token_copy.IsStopPossible()); EXPECT_TRUE(stop_token_copy.IsStopRequested()); } TEST_F(StopTokenTest, Move) { StopToken moved_stop_token{std::move(stop_token_)}; ASSERT_TRUE(moved_stop_token.IsStopPossible()); EXPECT_FALSE(moved_stop_token.IsStopRequested()); RequestStop(); ASSERT_TRUE(moved_stop_token.IsStopPossible()); EXPECT_TRUE(moved_stop_token.IsStopRequested()); // Moved from token is not valid anymore. EXPECT_FALSE(stop_token_.IsStopPossible()); } } // namespace orbit_baseshreyasvj25/turicreate1-10 /* Copyright © 2017 Apple Inc. All rights reserved. * * Use of this source code is governed by a BSD-3-clause license that can * be found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause */ #include #include #include #include #include #include #include namespace turi { namespace fileio { // Endpoint addresses specified on http://docs.aws.amazon.com/general/latest/gr/rande.html const std::vector AWS_S3_END_POINTS { "s3.amazonaws.com", "s3-us-west-1.amazonaws.com", "s3-us-west-2.amazonaws.com", "s3-eu-west-1.amazonaws.com", "s3-eu-central-1.amazonaws.com", "s3-ap-southeast-1.amazonaws.com", "s3-ap-southeast-2.amazonaws.com", "s3-ap-northeast-1.amazonaws.com", "s3-ap-northeast-2.amazonaws.com", "s3-sa-east-1.amazonaws.com", "s3-ap-south-1.amazonaws.com", }; const std::map AWS_S3_ENDPOINT_TO_REGION { {"s3.amazonaws.com","us-east-1"}, {"s3-us-west-1.amazonaws.com","us-west-1"}, {"s3-us-west-2.amazonaws.com","us-west-2"}, {"s3-eu-west-1.amazonaws.com","eu-west-1"}, {"s3-eu-central-1.amazonaws.com","eu-central-1"}, {"s3-ap-southeast-1.amazonaws.com","ap-southeast-1"}, {"s3-ap-southeast-2.amazonaws.com","ap-southeast-2"}, {"s3-ap-northeast-1.amazonaws.com","ap-northeast-1"}, {"s3-ap-northeast-2.amazonaws.com","ap-northeast-2"}, {"s3-sa-east-1.amazonaws.com","sa-east-1"}, {"s3-ap-south-1.amazonaws.com","ap-south-1"}}; std::vector get_s3_endpoints() { if (S3_ENDPOINT.empty()) { return AWS_S3_END_POINTS; } else { // we need to trim the https:// from the front auto ret = S3_ENDPOINT; if (boost::algorithm::starts_with(ret, "https://")) { ret = ret.substr(8); } return {ret}; } } std::string get_region_name_from_endpoint(std::string endpoint) { auto iter = AWS_S3_ENDPOINT_TO_REGION.find(endpoint); if (iter != AWS_S3_ENDPOINT_TO_REGION.end()) return iter->second; else return ""; } std::string get_bucket_path(const std::string& bucket) { if (S3_ENDPOINT.empty()) { return "https://" + bucket + ".s3.amazonaws.com" + '/'; } else { if (boost::algorithm::ends_with(S3_ENDPOINT, "/")) { return S3_ENDPOINT + bucket + "/"; } else { return S3_ENDPOINT + "/" + bucket + "/"; } } } } // fileio } // turi include/count-mongo-files-in-collection.cpp0 #include #include #include #include #include int print_query_count (mongoc_collection_t *collection, bson_t *query) { bson_error_t error; int64_t count; count = mongoc_collection_count_documents ( collection, bson_new(), NULL, NULL, NULL, &error); return count; } int main () { std::string mod = "mongo_local";// = config_json["mongo_agent_mod"].get(); std::string db_name ="test"; // (config_json[mod]["database"]).get(); std::string coll_name = "test"; // (config_json[mod]["collection"]).get(); mongoc_client_t* client; mongoc_collection_t* collection; mongoc_cursor_t* cursor; mongoc_uri_t *uri_mongoc; const bson_t* doc; bson_t* query; char* str; bson_error_t error; const char* database_name{ db_name.c_str() }; const char* collection_name{ coll_name.c_str() }; mongoc_init(); std::string uri {"mongodb://localhost:27017"};//{config_json[mod]["uri"] }; uri+="/?appname="; uri+="counting-mongo-agent";// config_json["mongo_agent_application_name"]; //parseing uri string uri_mongoc = mongoc_uri_new_with_error (uri.c_str(), &error); if (!uri_mongoc) { std::cout << "Faild to parse uri." <<"Check uri in config."<kevinlq/Qt-Creator-Opensource-Study /**************************************************************************** ** ** Copyright (C) 2016 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of Qbs. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 3 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL3 included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 3 requirements ** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 2.0 or (at your option) the GNU General ** Public license version 3 or any later version approved by the KDE Free ** Qt Foundation. The licenses are as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-2.0.html and ** https://www.gnu.org/licenses/gpl-3.0.html. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "propertymapinternal.h" #include #include #include #include namespace qbs { namespace Internal { /*! * \class PropertyMapInternal * \brief The \c PropertyMapInternal class contains a set of properties and their values. * An instance of this class is attached to every \c ResolvedProduct. * \c ResolvedGroups inherit their properties from the respective \c ResolvedProduct, \c SourceArtifacts * inherit theirs from the respective \c ResolvedGroup. \c ResolvedGroups can override the value of an * inherited property, \c SourceArtifacts cannot. If a property value is overridden, a new * \c PropertyMapInternal object is allocated, otherwise the pointer is shared. * \sa ResolvedGroup * \sa ResolvedProduct * \sa SourceArtifact */ PropertyMapInternal::PropertyMapInternal() { } PropertyMapInternal::PropertyMapInternal(const PropertyMapInternal &other) : m_value(other.m_value) { } QVariant PropertyMapInternal::moduleProperty(const QString &moduleName, const QString &key) const { return ::qbs::Internal::moduleProperty(m_value, moduleName, key); } QVariant PropertyMapInternal::qbsPropertyValue(const QString &key) const { return moduleProperty(StringConstants::qbsModule(), key); } QVariant PropertyMapInternal::property(const QStringList &name) const { return getConfigProperty(m_value, name); } void PropertyMapInternal::setValue(const QVariantMap &map) { m_value = map; } void PropertyMapInternal::load(PersistentPool &pool) { pool.load(m_value); } void PropertyMapInternal::store(PersistentPool &pool) const { pool.store(m_value); } QVariant moduleProperty(const QVariantMap &properties, const QString &moduleName, const QString &key) { return properties.value(moduleName).toMap().value(key); } } // namespace Internal } // namespace qbs #include "FontPopup.h" #include "ui_FontPopup.h" #include #include "ListModel.h" struct FontPopup::Style { public: Style(const BString& name, BMessage* message) : fName(name), fMessage(message) { } ~Style() { delete fMessage; } const BString& Name() const { return fName; } BMessage* Message() const { return fMessage; } private: BString fName; BMessage* fMessage; }; struct FontPopup::Family { Family(const BString& name) : fName(name) { } ~Family() { foreach (Style* style, fStyles) delete style; } const BString& Name() const { return fName; } void AddStyle(const BString& name, BMessage* message) { fStyles.append(new Style(name, message)); } const QList& Styles() const { return fStyles; } Style* FindStyle(const char* name) const { foreach (Style* style, fStyles) { if (style->Name() == name) return style; } return NULL; } private: BString fName; QList fStyles; }; struct FontPopup::FamilyListModel : public ListModel { FamilyListModel(QObject* parent = NULL) : ListModel(parent) { } virtual QString ItemText(Family* const& item) const { return item->Name(); } }; struct FontPopup::StyleListModel : public ListModel { StyleListModel(QObject* parent = NULL) : ListModel(parent) { } virtual QString ItemText(Style* const& item) const { return item->Name(); } }; FontPopup::FontPopup(QWidget* parent) : QWidget(parent), fUi(new Ui::FontPopup), fFamilyListModel(new FamilyListModel(this)), fStyleListModel(new StyleListModel(this)), fNotificationsEnabled(true) { fUi->setupUi(this); fUi->familyComboBox->setModel(fFamilyListModel); fUi->styleComboBox->setModel(fStyleListModel); connect(fUi->familyComboBox, SIGNAL(currentIndexChanged(int)), SLOT(_FamilyChanged())); connect(fUi->styleComboBox, SIGNAL(currentIndexChanged(int)), SLOT(_StyleChanged())); } FontPopup::~FontPopup() { MakeEmpty(); delete fUi; } void FontPopup::AddFont(const BString& fontFamily, const BString& fontStyle, BMessage* message) { Family* family = _FindFamily(fontFamily); if (family == NULL) { family = new Family(fontFamily); fFamilyListModel->AppendItem(family); } family->AddStyle(fontStyle, message); } void FontPopup::MakeEmpty() { foreach (Family* family, fFamilyListModel->Items()) delete family; fStyleListModel->MakeEmpty(); fFamilyListModel->MakeEmpty(); } void FontPopup::SetFamilyAndStyle(const char* familyName, const char* styleName) { Family* family = _FindFamily(familyName); Style* style = family != NULL ? family->FindStyle(styleName) : NULL; if (style != NULL) { fNotificationsEnabled = false; fUi->familyComboBox->setCurrentIndex(fFamilyListModel->IndexOf(family)); fUi->styleComboBox->setCurrentIndex(fStyleListModel->IndexOf(style)); fNotificationsEnabled = true; } } FontPopup::Family* FontPopup::_FindFamily(const BString& name) const { foreach (Family* family, fFamilyListModel->Items()) { if (family->Name() == name) return family; } return NULL; } FontPopup::Family* FontPopup::_CurrentFamily() const { return fFamilyListModel->ItemAt(fUi->familyComboBox->currentIndex()); } FontPopup::Style* FontPopup::_CurrentStyle() const { return fStyleListModel->ItemAt(fUi->styleComboBox->currentIndex()); } void FontPopup::_FamilyChanged() { if (Family* family = _CurrentFamily()) { fStyleListModel->SetItems(family->Styles()); fUi->styleComboBox->setCurrentIndex(0); } else fStyleListModel->MakeEmpty(); } void FontPopup::_StyleChanged() { if (!fNotificationsEnabled) return; Style* style = _CurrentStyle(); if (style != NULL) Invoke(style->Message()); } #include "Outfit.h" namespace Gotobed { Outfit::Outfit(std::int32_t a_obj) { if (a_obj) { auto domain = jc::domain::get(); name = jc::JMap::getStr(domain, a_obj, "name"); items = jc::JMap::getObj(domain, a_obj, "items"); mask = jc::JMap::getObj(domain, a_obj, "mask"); } } Outfit::Outfit(EquipList&& a_list) : items(std::move(a_list)) { } Outfit::Outfit(const RE::BGSOutfit& a_outfit) { for (auto& item : a_outfit.outfitItems) { if (item && item->IsBoundObject()) { items.entries.push_back({ static_cast(item), 1, nullptr }); } } } Outfit::operator std::int32_t() const { auto domain = jc::domain::get(); auto outfitObj = jc::JMap::object(domain); jc::JMap::setStr(domain, outfitObj, "name", name); jc::JMap::setObj(domain, outfitObj, "items", items); jc::JMap::setObj(domain, outfitObj, "mask", mask); return outfitObj; } }harderthan/gazebo /* * Copyright (C) 2015 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. * */ #include "gazebo/common/Console.hh" #include "gazebo/common/Time.hh" #include "gazebo/gui/Actions.hh" #include "gazebo/gui/LogPlayWidget.hh" #include "gazebo/gui/LogPlayWidgetPrivate.hh" using namespace gazebo; using namespace gui; ///////////////////////////////////////////////// LogPlayWidget::LogPlayWidget(QWidget *_parent) : QWidget(_parent), dataPtr(new LogPlayWidgetPrivate) { this->setObjectName("logPlayWidget"); this->dataPtr->timePanel = dynamic_cast(_parent); QSize bigSize(70, 70); QSize bigIconSize(40, 40); QSize smallSize(50, 50); QSize smallIconSize(30, 30); // Empty space on the left QWidget *leftSpacer = new QWidget(); leftSpacer->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); // Play QToolButton *playButton = new QToolButton(this); playButton->setFixedSize(bigSize); playButton->setCheckable(false); playButton->setIcon(QPixmap(":/images/log_play.png")); playButton->setIconSize(bigIconSize); playButton->setStyleSheet( QString("border-radius: %1px").arg(bigSize.width()/2-2)); connect(playButton, SIGNAL(clicked()), this, SLOT(OnPlay())); connect(this, SIGNAL(ShowPlay()), playButton, SLOT(show())); connect(this, SIGNAL(HidePlay()), playButton, SLOT(hide())); // Pause QToolButton *pauseButton = new QToolButton(this); pauseButton->setFixedSize(bigSize); pauseButton->setCheckable(false); pauseButton->setIcon(QPixmap(":/images/log_pause.png")); pauseButton->setIconSize(bigIconSize); pauseButton->setStyleSheet( QString("border-radius: %1px").arg(bigSize.width()/2-2)); connect(pauseButton, SIGNAL(clicked()), this, SLOT(OnPause())); connect(this, SIGNAL(ShowPause()), pauseButton, SLOT(show())); connect(this, SIGNAL(HidePause()), pauseButton, SLOT(hide())); // Step forward QToolButton *stepForwardButton = new QToolButton(this); stepForwardButton->setFixedSize(smallSize); stepForwardButton->setCheckable(false); stepForwardButton->setIcon(QPixmap(":/images/log_step_forward.png")); stepForwardButton->setIconSize(smallIconSize); stepForwardButton->setStyleSheet( QString("border-radius: %1px").arg(smallSize.width()/2-2)); connect(stepForwardButton, SIGNAL(clicked()), this, SLOT(OnStepForward())); // Play layout QHBoxLayout *playLayout = new QHBoxLayout(); playLayout->addWidget(playButton); playLayout->addWidget(pauseButton); playLayout->addWidget(stepForwardButton); // View this->dataPtr->view = new LogPlayView(this); connect(this, SIGNAL(SetCurrentTime(common::Time)), this->dataPtr->view, SLOT(SetCurrentTime(common::Time))); connect(this, SIGNAL(SetStartTime(common::Time)), this->dataPtr->view, SLOT(SetStartTime(common::Time))); connect(this, SIGNAL(SetEndTime(common::Time)), this->dataPtr->view, SLOT(SetEndTime(common::Time))); // Time QLineEdit *currentTime = new QLineEdit(); currentTime->setObjectName("logPlayCurrentTime"); currentTime->setMaximumWidth(110); currentTime->setAlignment(Qt::AlignRight); connect(this, SIGNAL(SetCurrentTime(const QString &)), currentTime, SLOT(setText(const QString &))); QLabel *endTime = new QLabel(); connect(this, SIGNAL(SetEndTime(const QString &)), endTime, SLOT(setText(const QString &))); QHBoxLayout *timeLayout = new QHBoxLayout(); timeLayout->addWidget(currentTime); timeLayout->addWidget(endTime); // Empty space on the right QWidget *rightSpacer = new QWidget(); rightSpacer->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); // Main layout QHBoxLayout *mainLayout = new QHBoxLayout; mainLayout->addWidget(leftSpacer); mainLayout->addLayout(playLayout); mainLayout->addWidget(this->dataPtr->view); mainLayout->addLayout(timeLayout); mainLayout->addWidget(rightSpacer); this->setLayout(mainLayout); mainLayout->setAlignment(playLayout, Qt::AlignRight); mainLayout->setAlignment(timeLayout, Qt::AlignLeft); this->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); this->layout()->setContentsMargins(0, 0, 0, 0); } ///////////////////////////////////////////////// LogPlayWidget::~LogPlayWidget() { delete this->dataPtr; this->dataPtr = NULL; } ///////////////////////////////////////////////// bool LogPlayWidget::IsPaused() const { return this->dataPtr->paused; } ///////////////////////////////////////////////// void LogPlayWidget::SetPaused(const bool _paused) { this->dataPtr->paused = _paused; if (_paused) { emit ShowPlay(); emit HidePause(); } else { emit HidePlay(); emit ShowPause(); } } ///////////////////////////////////////////////// void LogPlayWidget::OnPlay() { g_playAct->trigger(); } ///////////////////////////////////////////////// void LogPlayWidget::OnPause() { g_pauseAct->trigger(); } ///////////////////////////////////////////////// void LogPlayWidget::OnStepForward() { g_stepAct->trigger(); } ///////////////////////////////////////////////// void LogPlayWidget::EmitSetCurrentTime(const common::Time &_time) { // Make sure it's within limits common::Time time = std::max(_time, this->dataPtr->startTime); if (this->dataPtr->endTime != common::Time::Zero) time = std::min(time, this->dataPtr->endTime); this->dataPtr->currentTime = time; // Update current time line edit if (this->dataPtr->lessThan1h) { this->SetCurrentTime(QString::fromStdString(time.FormattedString( common::Time::FormatOption::MINUTES))); } else { this->SetCurrentTime(QString::fromStdString(time.FormattedString())); } // Update current time item in view this->SetCurrentTime(time); } ///////////////////////////////////////////////// void LogPlayWidget::EmitSetStartTime(const common::Time &_time) { if (this->dataPtr->endTime != common::Time::Zero && _time >= this->dataPtr->endTime) { gzwarn << "Start time [" << _time << "] after end time [" << this->dataPtr->endTime << "]. Not updating." << std::endl; return; } this->dataPtr->startTime = _time; // Update start time in view this->SetStartTime(this->dataPtr->startTime); // Keep current time within bounds if (this->dataPtr->startTime > this->dataPtr->currentTime) this->EmitSetCurrentTime(this->dataPtr->startTime); } ///////////////////////////////////////////////// void LogPlayWidget::EmitSetEndTime(const common::Time &_time) { if (_time <= this->dataPtr->startTime) { gzwarn << "End time [" << _time << "] before start time [" << this->dataPtr->startTime << "]. Not updating." << std::endl; return; } this->dataPtr->endTime = _time; // Use shorter string if less than 1h if (_time < common::Time::Hour) this->dataPtr->lessThan1h = true; // Update end time label std::string timeString; if (this->dataPtr->lessThan1h) { timeString = _time.FormattedString(common::Time::FormatOption::MINUTES); } else { timeString = _time.FormattedString(); } timeString = "/ " + timeString; this->SetEndTime(QString::fromStdString(timeString)); // Update end time in view this->SetEndTime(_time); // Keep current time within bounds if (this->dataPtr->endTime < this->dataPtr->currentTime) this->EmitSetCurrentTime(this->dataPtr->endTime); } ///////////////////////////////////////////////// LogPlayView::LogPlayView(LogPlayWidget *_parent) : QGraphicsView(_parent), dataPtr(new LogPlayViewPrivate) { this->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); this->dataPtr->sceneWidth = 1000; this->dataPtr->sceneHeight = 120; this->dataPtr->margin = 50; QGraphicsScene *graphicsScene = new QGraphicsScene(); graphicsScene->setBackgroundBrush(QColor(128, 128, 128)); this->setScene(graphicsScene); this->setMinimumWidth(this->dataPtr->sceneHeight); this->setViewportUpdateMode(QGraphicsView::FullViewportUpdate); this->setStyleSheet("QGraphicsView{border-style: none;}"); this->setSceneRect(0, 0, this->dataPtr->sceneWidth, this->dataPtr->sceneHeight); // Time line QGraphicsLineItem *line = new QGraphicsLineItem(this->dataPtr->margin, this->dataPtr->sceneHeight/2, this->dataPtr->sceneWidth - this->dataPtr->margin, this->dataPtr->sceneHeight/2); line->setPen(QPen(QColor(50, 50, 50, 255), 2)); graphicsScene->addItem(line); // Current time item this->dataPtr->currentTimeItem = new CurrentTimeItem(); this->dataPtr->currentTimeItem->setPos(this->dataPtr->margin, this->dataPtr->sceneHeight/2); graphicsScene->addItem(this->dataPtr->currentTimeItem); this->dataPtr->startTimeSet = false; this->dataPtr->endTimeSet = false; } ///////////////////////////////////////////////// void LogPlayView::SetCurrentTime(const common::Time &_time) { common::Time totalTime = this->dataPtr->endTime - this->dataPtr->startTime; if (totalTime == common::Time::Zero) return; double relPos = ((_time - this->dataPtr->startTime) / totalTime).Double(); this->dataPtr->currentTimeItem->setPos(this->dataPtr->margin + (this->dataPtr->sceneWidth - 2 * this->dataPtr->margin)*relPos, this->dataPtr->sceneHeight/2); } ///////////////////////////////////////////////// void LogPlayView::SetStartTime(const common::Time &_time) { this->dataPtr->startTime = _time; this->dataPtr->startTimeSet = true; } ///////////////////////////////////////////////// void LogPlayView::SetEndTime(const common::Time &_time) { this->dataPtr->endTime = _time; this->dataPtr->endTimeSet = true; if (this->dataPtr->startTimeSet) this->DrawTimeline(); } ///////////////////////////////////////////////// void LogPlayView::DrawTimeline() { if (this->dataPtr->timelineDrawn || !this->dataPtr->startTimeSet || !this->dataPtr->endTimeSet) return; common::Time totalTime = this->dataPtr->endTime - this->dataPtr->startTime; if (totalTime == common::Time::Zero) return; // Aim for this number, but some samples might be added/removed int intervals = 10; // All ticks are shifted from a round number of seconds (no msec or nsec) common::Time roundStartTime = common::Time(this->dataPtr->startTime.sec, 0); // Time between ticks (round seconds) common::Time interval = totalTime/intervals; interval.nsec = 0; if (interval == common::Time::Zero) interval = common::Time::Second; // Time line int tickHeight = 15; common::Time tickTime = this->dataPtr->startTime; int i = 0; while (tickTime >= this->dataPtr->startTime && tickTime < this->dataPtr->endTime) { // Intermediate samples have a round number if (i != 0) { tickTime = roundStartTime + interval * i; } // If first interval too close, shift by 1s common::Time endSpace = interval * 0.9; if (tickTime != this->dataPtr->startTime && tickTime < this->dataPtr->startTime + endSpace) { roundStartTime += common::Time::Second; tickTime = roundStartTime + interval * i; } // If last interval too close, skip to end if (tickTime > this->dataPtr->endTime - endSpace) { tickTime = this->dataPtr->endTime; } ++i; // Relative position double relPos = ((tickTime - this->dataPtr->startTime) / totalTime) .Double(); // Tick vertical line QGraphicsLineItem *tick = new QGraphicsLineItem(0, -tickHeight, 0, 0); tick->setPos(this->dataPtr->margin + (this->dataPtr->sceneWidth - 2 * this->dataPtr->margin)*relPos, this->dataPtr->sceneHeight/2); tick->setPen(QPen(QColor(50, 50, 50, 255), 2)); this->scene()->addItem(tick); // Text std::string timeText; if (tickTime == this->dataPtr->startTime || tickTime == this->dataPtr->endTime) { timeText = tickTime.FormattedString(common::Time::FormatOption::MINUTES); } else { timeText = tickTime.FormattedString(common::Time::FormatOption::MINUTES, common::Time::FormatOption::SECONDS); } QGraphicsSimpleTextItem *tickText = new QGraphicsSimpleTextItem( QString::fromStdString(timeText)); tickText->setBrush(QBrush(QColor(50, 50, 50, 255))); tickText->setPos( this->dataPtr->margin - tickText->boundingRect().width()*0.5 + (this->dataPtr->sceneWidth - 2 * this->dataPtr->margin)*relPos, this->dataPtr->sceneHeight/2 - 3 * tickHeight); this->scene()->addItem(tickText); } this->dataPtr->timelineDrawn = true; } ///////////////////////////////////////////////// CurrentTimeItem::CurrentTimeItem() { this->setEnabled(true); this->setZValue(10); } ///////////////////////////////////////////////// void CurrentTimeItem::paint(QPainter *_painter, const QStyleOptionGraphicsItem */*_option*/, QWidget */*_widget*/) { int lineHeight = 50; int lineWidth = 3; // Vertical line QLineF vLine(-lineWidth/10.0, -lineHeight/2.0, -lineWidth/10.0, +lineHeight/2.0); QPen linePen; linePen.setColor(QColor(50, 50, 50, 255)); linePen.setWidth(lineWidth); _painter->setPen(linePen); _painter->drawLine(vLine); // Triangle QVector trianglePts; trianglePts.push_back(QPointF(-8, -lineHeight/2 - 1)); trianglePts.push_back(QPointF(8, -lineHeight/2 - 1)); trianglePts.push_back(QPointF(0, -lineHeight/2 + 10)); QPolygonF triangle(trianglePts); QPen whitePen(Qt::white, 0); QPen orangePen(QColor(245, 129, 19, 255), 0); QBrush whiteBrush(Qt::white); QBrush orangeBrush(QColor(245, 129, 19, 255)); _painter->setPen(orangePen); _painter->setBrush(orangeBrush); _painter->drawPolygon(triangle); } // Copyright 2019-2021 Cambridge Quantum Computing // // 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 namespace tket { namespace graphs { // NOTE: GRAPH DATA STRUCTURES/FORMATS: // in the long term, ideally we should use boost graph data formats // (i.e., adjacency_list) or some other type for ALL graphs in tket. // // Assuming that we do like boost::adjacency_list, which has a lot // of extra template parameters, it seems there are 4 options. // In increasing order of work/code complexity: // // (i): do nothing (the short term option!) // // (ii): create boost::... -> {our data structures} conversion routines, // and continue to use our routines unchanged. // (e.g., brute force colouring is the bottleneck, not conversion). // // (iii): create {general boost::...} -> {special restricted boost::...} // conversion routines, and change our algorithms to use the // restricted boost objects. (With all template parameters fixed, // and all irrelevant extra vertex data stripped, so at least // we can be sure of efficiency in implementation). // // (iv): change all routines to use general boost::... directly, // with templates everywhere, and POSSIBLY unavoidable inefficiencies, // because the boost graph stuff is very general. // // Another option is to go Java-style and use interfaces/virtual functions // everywhere instead of templates. /** * Data for an undirected graph. Once stored inside here, the data has * automatically been checked and cleaned: the vertices in neighbour lists * actually exist, there are no missing vertices, no duplicate edge data, etc. * The vertices are {0,1,2,...,v-1}. * The number of vertices must be known at the start * (or, it can be reset later, but only by clearing all data), * so it is not completely dynamic. The constructors throw upon invalid data. */ class AdjacencyData { public: /** * Initialise with N vertices, no edges. */ explicit AdjacencyData(std::size_t number_of_vertices = 0); /** * Construct from a known graph in simple raw format. A sparse format: * we don't explicitly need to list vertices if they have no edges. * @param raw_data A mapping (vertex i) -> {list of neighbours of i}. * If i->j is an edge, j->i will be automatically deduced also. * @param number_of_vertices Optional: if not specified, the number of * vertices will be deduced. */ AdjacencyData( const std::map>& raw_data, std::size_t number_of_vertices = 0); /** * The vertices are {0,1,2,...,n}. * @param raw_data element[i] lists vertices j such that there is an edge * i->j. There is no need to list j->i also, it will be automatically deduced. * @param allow_loops Optional: default is false. Loops i->i make no sense for * colouring. */ AdjacencyData( const std::vector>& raw_data, // For colouring, loops i -> i are obviously not allowed bool allow_loops = false); /** * Changes the number of vertices and clears all data. * @param number_of_vertices The number of vertices, v. * The actual vertices will be {0,1,2,...,v-1}. */ void clear(std::size_t number_of_vertices); /** For a given vertex v, return all vertices j such that j-v is an edge. */ const std::set& get_neighbours(std::size_t vertex) const; /** Returns the total number of vertices in the graph. */ std::size_t get_number_of_vertices() const; /** Returns the total number of edges in the graph (i->j and j->i counting as * one edge). */ std::size_t get_number_of_edges() const; /** Returns true if and only if the edge i-j exists. */ bool edge_exists(std::size_t i, std::size_t j) const; /** You must set the number of vertices BEFORE calling this. * If the edge i-j does not already exist, adds it, and return true. * If it already existed, do nothing and return false. * If (i,j) is invalid, throws. */ bool add_edge(std::size_t i, std::size_t j); /** to_string is useful for debugging. You can copy the graph data * and easily paste it back into C++ code. */ std::string to_string() const; private: // Element i gives all neighbours j for vertex i, including j> m_cleaned_data; }; } // namespace graphs } // namespace tket render_algorithms/holodepth/src/main.cpp /* 09_vertex_lighting.c - OpenGL-based per-vertex lighting example using Cg program from Chapter 5 of "The Cg Tutorial" (Addison-Wesley, ISBN 0321194969). */ /* Requires the OpenGL Utility Toolkit (GLUT) and Cg runtime (version 1.5 or higher). */ //for profiling, can auto-quit after set number of seconds (try 60). set to 0 to disable auto-quit #define QUIT_AFTER_SECONDS 0 //#define USE_GLEW 0 //this disables view rendering from mesh. Not currently used. #define DISABLE_VIEW_RENDERING 0 #define HOLOGRAM_DOWNSCALE_DEBUG 0 #define REVERSE_VIEW_ORDER 1 #define MODEL_TO_USE 0 //0,1 or 2 #define DISABLE_SECOND_OBJECT 1 #define DRAW_WIRE_CUBE_ONLY 0 //#define ENABLE_REMOTEQT #define DISABLE_HOLOGRAM_CREATION 0 #define WRITE_VIEWS_AND_EXIT 0 #define WRITE_LUMA_VIEW_FILES 0 #define WRITE_HOLOGRAM_AND_EXIT 0 //enable both to use kinect. Disable both for cube-only or obj-file modes. //#define VIEWS_FROM_CLOUD //(M_PI/20), (M_PI/200) #define ANGLE_THRESH (M_PI/20) //16, 100 #define VIEWS_TO_LOAD 16 //SET TO 0 for images loaded from file //set to 2 for kinect demos //set to 3 to use dual-kinect setup //set to 4 for PointCloudLibrary-based kinect driver #define KINECT_MODE 0 //don't draw cloud samples darker than this value (out of 2048). Set to 0 to remove check. 300 for crane/arizona #define REMOVE_PIXELS_DARKER_THAN 300 //for debugging hologram shader: //#define SOLO_VIEW 16 //only draw one view. undefine to show all views //DECIMATE of n means only use every n+1 points (0 means no skipping) #define OPENNI_DECIMATE 0 #ifdef __APPLE__ //#define WRITE_VIEWS_AND_EXIT 1 //#define KINECT_MODE 0 //#define VIEWS_FROM_CLOUD #define DRAW_WIRE_CUBE_ONLY 1 //#define WRITE_LUMA_VIEW_FILES 1 #define DISABLE_VIEW_RENDERING 0 #define DISABLE_HOLOGRAM_CREATION 0 #define WRITE_HOLOGRAM_AND_EXIT 0 #define HOLOGRAM_DOWNSCALE_DEBUG 0 //fit hologram onto smaller screen for debugging overall layout. #endif #ifdef __APPLE__ #define IMAGE_PATH_TEMPLATE "/Users/barabas/Dropbox/James Storage/Range Images/Images/%s/capture_batch_%.4d/testCloud0000.txt" #else #define IMAGE_PATH_TEMPLATE "/home/holo/Range_Images/Images/%s/capture_batch_%.4d/testCloud0000.txt" #endif #if KINECT_MODE == 4 #include "JVertexRender.h" static JVertexRender *KinectPCL; #endif #ifdef WIN32 #include #undef near #undef far #undef BI_RGB #undef BI_RLE8 #undef BI_RLE4 #undef BI_BITFIELDS #define M_PI 3.14159265358979323846 #endif #ifdef __APPLE__ #include #include #else #if USE_GLEW #include #endif #include #include #include #endif #include /* for printf and NULL */ #include /* for exit */ #include /* for sqrt, sin, cos, and fabs */ #include /* for assert */ #include #include /* Can't include this? Is Cg Toolkit installed! */ #include #include "myobj.h" #include "transforms.h" #include "mytexture.h" #include "shapes.h" #ifdef REMOTEQT_GUI #include "JDisplayState.h" #include "JSharedMemory.h" //For interfacing with QTRemote UI static JDisplayState statecopy; static volatile JDisplayStatus *displaystatus; static JSharedMemory *sharedstate; //controller to this process static JSharedMemory *sharedstatus; //this process to controller #endif #if KINECT_MODE > 0 #include "JKinectFrame.h" static JSharedMemory *sharedkinect; static JKinectFrame *kinectframe; #if (KINECT_MODE > 1) //for Kreylos Kinect code #include "KinectProjector.h" #include "GL/GLContextData.h" #include #include "Vrui/Vrui.h" // 04/09/2011 SKJ: Add includes #include #include #include #include #include #include #include #include #include #include KinectProjector *kprojector; GLContextData *projectorDataContext; GLExtensionManager *glextmgr; #if KINECT_MODE != 3 //#define PROJECTION_CONFIG_FILENAME "/home/holo/Dropbox/Holovideo/Configuration/Kinect1/CameraCalibrationMatrices-B00361710470044B.dat" #define PROJECTION_CONFIG_FILENAME "/home/holo/Dropbox/Holovideo/Configuration/Kinect3/CameraCalibrationMatrices-A00362A06614047A.dat" #endif FrameBuffer *depthFrameBuffer; FrameBuffer *colorFrameBuffer; int kinectCloudHeight=480; int kinectCloudWidth=640; // 04/09/2011 SKJ: Added to handle second Kinect #if KINECT_MODE == 3 static JSharedMemory *sharedkinect2; static JKinectFrame *kinectframe2; KinectProjector *kprojector2; GLContextData *projectorDataContext2; // GLExtensionManager *glextmgr2; #define PROJECTION_CONFIG_FILENAME_2 "/home/holo/Dropbox/Holovideo/Configuration/Kinect2/CameraCalibrationMatrices-A00364817648045A.dat" #define PROJECTION_CONFIG_FILENAME "/home/holo/Dropbox/Holovideo/Configuration/Kinect1/CameraCalibrationMatrices-B00361710470044B.dat" FrameBuffer *depthFrameBuffer2; FrameBuffer *colorFrameBuffer2; static float depthMatrixKinect1; static float textureMatrixKinect1; static float depthMatrixKinect2; static float textureMatrixKinect2; static float projectorTransform1; static float projectorTransform2; static int kinectNum; #endif #endif #endif #ifdef VIEWS_FROM_CLOUD #include "JZCameraCloud.h" #endif //#include "framebufferObject.h" //#include "renderbuffer.h" #include "glErrorUtil.h" static float MasterHologramGain = 1.0f; int ViewEnableBitmask = 0xffffffff; //set bits to zero to skip rendering views bool zeroDepth = 0; //should we set depth-view to zero (for debuging) bool zeroModulation = 0; // " " " color float fakeZ = 0.5; //pretend all points on object is at this z-depth float fakeModulation = 0.5; //pretend all points on object is at this z-depth int hologramOutputDebugSwitch = 0; //send different intermediate variables to color buffer when rendering #define hologramOutputDebugSwitches 10 //total number of debug modes in shader /* Scalar */ GLuint DLid; int headnumber = 0; //0,1,2 -- which instance of three (3 graphics cards) int frame = 0, thetime, timebase = 0; int rotateOn = 0; int drawdepthOn = 0; //dimensions of the framebuffer for output to video signals //int imwidth = 2048; int imwidth = 2045; //int imheight = 3444; //1722*2; //new DisplayPort mode int imheight = 3514;// 1757*2.; //old VGA mode //int MarkIIGLWindowWidth = 2032; //New DisplayPort Mode int MarkIIGLWindowWidth = 2045; //old VGA mode //int MarkIIGLWindowHeight = 3444; //1722*2; //This is display height for DisplayPort connected displays on K5000 cards int MarkIIGLWindowHeight = 3514; //1757*2; //This is display height for onboard VGA connector displays #if WRITE_LUMA_VIEW_FILES != 1 int numx = 512;//512;//horizontal resolution of view to render (also number of emitters per line in hologram), 200 Arizona mode int numy = 144;//144//48;//vertical resolution of views rendered. 48 for single-head tests. 144 for 3-head mode, 600 Arizona mode int tiley = 2;//2//tiling of views in view texture int tilex = 2;//2 int numrgb = 4;//4//number of views per pixel (stored in R, G, B, A) #else int numx = 400;//512;//horizontal resolution of view to render (also number of emitters per line in hologram), 200 Arizona mode int numy = 1200;//144//48;//vertical resolution of views rendered. 48 for single-head tests. 144 for 3-head mode, 600 Arizona mode int tiley = 100;//2//tiling of views in view texture int tilex = 1;//2 int numrgb = 1;//4//number of views per pixel (stored in R, G, B, A) #endif //size of texture used for writing views int VIEWTEX_WIDTH = numx * tilex; int VIEWTEX_HEIGHT = numy * tiley * 2;//tiley views of numy pixels, X 2 (depth, luminance) was 256; GLubyte *localFramebufferStore; int numview=tilex*tiley*numrgb; #if WRITE_LUMA_VIEW_FILES !=1 float HologramPlaneWidth_mm = 150.0; float HologramPlaneHeight_mm = 75.0; #else //ARIZONA plane dimensions float HologramPlaneWidth_mm = 100.0; float HologramPlaneHeight_mm = 100.0; #endif float near = 400.0f, far = 800.0f; //mm, near and far planes for hologram volume (relative to camera) float lx = 0, ly = -790, lz = -110; //Light location (direction?) inside volume //int imwidth=2048; //int imheight=1780; //int numx=320, numy=120, tile9.coy=2, numrgb=4; //5/int numview=64; /*numview=numx*tily*numrgb=320*2*4=2560'*/ float mag = 1.; float fov = 30. /* /7 */; float hogelSwitch = 1.; //float fov=30; GLfloat LightAmbient[] = { 0.5f, 0.5f, 0.5f, 1.0f }; // Ambient Light Values GLfloat LightDiffuse[] = { 1.0f, 1.0f, 1.0f, 1.0f }; // Diffuse Light Values GLfloat LightPosition[] = { 0.0f, 0.0f, 2.0f, 1.0f }; // Light Position static CGcontext normalMapLightingCgContext; static CGprofile normalMapLightingCgVertexProfile; static CGprofile normalMapLightingCgFragmentProfile; static CGprogram normalMapLightingCgVertexProgram, normalMapLightingCgFragmentProgram; static CGparameter myCgVertexParam_modelUIScale; static CGparameter myCgVertexParam_modelViewProj; static CGparameter myCgFragmentParam_globalAmbient, myCgFragmentParam_lightColor, myCgFragmentParam_lightPosition, myCgFragmentParam_eyePosition, myCgFragmentParam_Ke, myCgFragmentParam_Ka, myCgFragmentParam_Kd, myCgFragmentParam_Ks, myCgFragmentParam_shininess, myCgFragmentParam_drawdepth, myCgFragmentParam_headnum; static CGparameter myCgFragmentParam_hogelYes; static CGparameter myCgFragmentParam_hologramGain; static CGparameter myCgFragmentParam_hologramDebugSwitch; static CGparameter myCgVertexParam_textureMatrix; static CGparameter myCgVertexParam_depthMatrix; static CGparameter myCgVertexParam_drawdepth; // 04/10/2011 SKJ: Handle multiple Kinects static CGparameter myCgVertexParam_textureMatrixSecond; static CGparameter myCgVertexParam_depthMatrixSecond; static CGparameter myCgVertexParam_drawdepthSecond; static CGparameter myCgVertexParam_kinectNum; static CGparameter myCgVertexParam_projectorTransform; static CGparameter myCgVertexParam_projectorTransform2; static const char *normalMapLightingProgramName = "09_vertex_lighting"; #ifndef VIEWS_FROM_CLOUD static const char *normalMapLightingProgramFileName = "C5E1v_basicLightperFrag.cg"; static const char *normalMapLightingVertexProgramFileName = "C5E1f_basicNormMap.cg"; #else // 04/09/2011 SKJ: Or KINECT_MODE == 3?? #if KINECT_MODE == 2 static const char *normalMapLightingProgramFileName = "../src/kinect_vertex_shader.cg"; static const char *normalMapLightingVertexProgramFileName = "../src/kinect_fragment_shader.cg"; #else #if KINECT_MODE == 3 static const char *normalMapLightingProgramFileName = "../src/multi_kinect_vertex_shader.cg"; static const char *normalMapLightingVertexProgramFileName = "../src/multi_kinect_fragment_shader.cg"; #else static const char *normalMapLightingProgramFileName = "../src/cloud_vertex_shader.cg"; static const char *normalMapLightingVertexProgramFileName = "../src/cloud_fragment_shader.cg"; #endif #endif #endif /* Page 111 */static const char *normalMapLightingVertexProgramName = "C5E1v_basicLight"; /* Page 85 */static const char *normalMapLightingFragmentProgramName = "C5E1f_basicLight"; //static CGcontext myCgContext; //static CGprofile myCgVertexProfile, static CGprofile myCgVertexProfile2, myCgFragmentProfile2; static CGprogram myCgVertexProgram2, myCgFragmentProgram2; // myCgFragmentProgram1; static CGparameter myCgFragmentParam_decal, myCgFragmentParam_decal2, myCgFragmentParam_decal0, myCgFragmentParam_decal1; //myCgFragmentParam_layer0; static const char *myProgramName2 = "Holo_myTextures", *myVertexProgramFileName2 = "Holov_myTextures.cg", /* Page 83 */*myVertexProgramName2 = "Holov_myTextures", *myFragmentProgramFileName2 = "Holof_myTextures.cg", /* Page 85 */*myFragmentProgramName2 = "Holof_myTextures"; GLuint allviewsfbo; //frame buffer object GLuint depthbuffer; //GLenum buffers[]={GL_COLOR_ATTACHMENT0_EXT,GL_COLOR_ATTACHMENT1_EXT}; GLfloat myProjectionMatrix1[16]; GLfloat myProjectionMatrix2[16]; #define MAX_CLOUDS 255 #ifdef VIEWS_FROM_CLOUD JZCameraCloud * allClouds[MAX_CLOUDS]; int numLoadedClouds = 0; #endif //FramebufferObject* rectifiedfbo; static float myGlobalAmbient[3] = { 0.1, 0.1, 0.1 }; /* Dim */ static float myLightColor[3] = { 0.95, 0.95, 0.95 }; /* White */ float ty0 = -9; static float tz = 0, tx = 0, ty = ty0, rot = 0, rotx = 0; GLuint texture_id[3]; GLuint meshTexID; // GLuint tex_num = 0; void writeViewsToFile(); void writeToFile2(); void printmatrix(float* m) { printf("["); float*p = m; printf("[%g\t%g\t%g\t%g]\n",p[0],p[1],p[2],p[3]); printf("[%g\t%g\t%g\t%g]\n",p[4],p[5],p[6],p[7]); printf("[%g\t%g\t%g\t%g]\n",p[8],p[9],p[10],p[11]); printf("[%g\t%g\t%g\t%g]\n",p[12],p[13],p[14],p[15]); printf("]\n"); } void checkErrors(void) { GLenum error; while ((error = glGetError()) != GL_NO_ERROR) { //fprintf(stderr, "Error: %s\n", (char *) gluErrorString(error)); } } #define checkForCgError(a) checkForCgErrorLine(a,__LINE__) static void checkForCgErrorLine(const char *situation,int line = 0) { CGerror error; const char *string = cgGetLastErrorString(&error); if (error != CG_NO_ERROR) { printf("line %d: %s: %s: %s\n", line, normalMapLightingProgramName, situation, string); if (error == CG_COMPILER_ERROR) { printf("%s\n", cgGetLastListing(normalMapLightingCgContext)); } exit(1); } } static void checkForCgError2(const char *situation) { CGerror error; const char *string = cgGetLastErrorString(&error); if (error != CG_NO_ERROR) { printf("%s: %s: %s\n", myProgramName2, situation, string); if (error == CG_COMPILER_ERROR) { printf("%s\n", cgGetLastListing(normalMapLightingCgContext)); } exit(1); } } /* Forward declared GLUT callbacks registered by main. */ //static void reshape(int width, int height); //static void display(void); //static void keyboard(unsigned char c, int x, int y); //static void menu(int item); //static void requestSynchornizedSwapBuffers(void); static void setBrassMaterial(void) { const float brassEmissive[3] = { 0.0, 0.0, 0.0 }, brassAmbient[3] = { 0.33 * 2, 0.33 * 2, 0.33 * 2 }, brassDiffuse[3] = { 0.78, 0.78, 0.78 }, brassSpecular[3] = { 0.99, 0.99, 0.99 }, brassShininess = 27.8; cgSetParameter3fv(myCgFragmentParam_Ke, brassEmissive); cgSetParameter3fv(myCgFragmentParam_Ka, brassAmbient); cgSetParameter3fv(myCgFragmentParam_Kd, brassDiffuse); cgSetParameter3fv(myCgFragmentParam_Ks, brassSpecular); cgSetParameter1f(myCgFragmentParam_shininess, brassShininess); } static void setRedPlasticMaterial(void) { const float redPlasticEmissive[3] = { 0.0, 0.0, 0.0 }, redPlasticAmbient[3] = { 0.2, 0.2, 0.2 }, redPlasticDiffuse[3] = { 0.5, 0.5, 0.5 }, redPlasticSpecular[3] = { 0.6, 0.6, 0.6 }, redPlasticShininess = 32.0; cgSetParameter3fv(myCgFragmentParam_Ke, redPlasticEmissive); checkForCgError("setting Ke parameter"); cgSetParameter3fv(myCgFragmentParam_Ka, redPlasticAmbient); checkForCgError("setting Ka parameter"); cgSetParameter3fv(myCgFragmentParam_Kd, redPlasticDiffuse); checkForCgError("setting Kd parameter"); cgSetParameter3fv(myCgFragmentParam_Ks, redPlasticSpecular); checkForCgError("setting Ks parameter"); cgSetParameter1f(myCgFragmentParam_shininess, redPlasticShininess); checkForCgError("setting shininess parameter"); } static void setEmissiveLightColorOnly(void) { const float zero[3] = { 0.0, 0.0, 0.0 }; cgSetParameter3fv(myCgFragmentParam_Ke, myLightColor); checkForCgError("setting Ke parameter"); cgSetParameter3fv(myCgFragmentParam_Ka, zero); checkForCgError("setting Ka parameter"); cgSetParameter3fv(myCgFragmentParam_Kd, zero); checkForCgError("setting Kd parameter"); cgSetParameter3fv(myCgFragmentParam_Ks, zero); checkForCgError("setting Ks parameter"); cgSetParameter1f(myCgFragmentParam_shininess, 0); checkForCgError("setting shininess parameter"); } #ifdef VIEWS_FROM_CLOUD //use this for drawing point clouds when we have multiple image sources/camera positions void drawPointCloudFromZImage(JZCameraCloud **cloud, float shearAngle, float threshAngle) { float scale = 100; // for converting units from meters (camera) to scene units float x,y,z,l; glDisable(GL_LIGHTING); glDisable(GL_TEXTURE_2D); //glPointParameter //glEnable(GL_POINT_SMOOTH); glPointSize(2.0f); //glPointSize(2.0f); //Arizona: use 2.0 point size, turn on smooth. //float attenparams[3] = {0,0,0}; //a b c //size × 1 a + b × d + c × d 2 //glPointParameterfv(GL_POINT_DISTANCE_ATTENUATION,attenparams); glBegin(GL_POINTS); float dif; for(int c=0;cresx*cloud[c]->resy;i++) { dif = fabs(cloud[c]->xangles[i] - shearAngle); if(dif > threshAngle) continue; //filter off-angle pixels #if REMOVE_PIXELS_DARKER_THAN != 0 if(cloud[c]->ls[i] < REMOVE_PIXELS_DARKER_THAN) continue; //hack to remove dark samples (gets rid of dark noisy stuff in front of model. Makes holes in shadows on models) #endif x = (cloud[c]->xs[i]+cloud[c]->cop[0])*scale; y = (cloud[c]->ys[i]+cloud[c]->cop[1])*scale; z = (cloud[c]->zs[i]+cloud[c]->cop[2])*scale; l = cloud[c]->ls[i]*cloud[c]->gain; glColor3f(l,l,l); glVertex4f(x, y, z, 1.0); } } glEnd(); } #endif #if KINECT_MODE > 0 && KINECT_MODE < 4 void updateKinectCloud() { unsigned short* dptr = (unsigned short*)depthFrameBuffer->getBuffer(); unsigned char* cptr = (unsigned char*)colorFrameBuffer->getBuffer(); //copy shared buffer into FrameBuffer format (for now) int ystride = 1; //only render every ystride lines int i=0; for(int y=0;ydepth[y*kinectCloudWidth + x]; cptr[i] = kinectframe->luma[y*kinectCloudWidth + x]; i++; } } kprojector->setColorFrame(*colorFrameBuffer); kprojector->setDepthFrame(*depthFrameBuffer); // 04/09/2011 SKJ: Add updating for second Kinect #if KINECT_MODE == 3 unsigned short* dptr2 = (unsigned short*)depthFrameBuffer2->getBuffer(); unsigned char* cptr2 = (unsigned char*)colorFrameBuffer2->getBuffer(); //copy shared buffer into FrameBuffer format (for now) i=0; for(int y=0;ydepth[y*kinectCloudWidth + x]; cptr2[i] = kinectframe2->luma[y*kinectCloudWidth + x]; i++; } } kprojector2->setColorFrame(*colorFrameBuffer2); kprojector2->setDepthFrame(*depthFrameBuffer2); #endif } void drawPointCloudFromKinect_Calibrated() { glDisable(GL_LIGHTING); glEnable(GL_TEXTURE_2D); //glPointParameter //glEnable(GL_POINT_SMOOTH); glPointSize(2.0f); //float attenparams[3] = {0,0,0}; //a b c //size × 1 a + b × d + c × d 2 //glPointParameterfv(GL_POINT_DISTANCE_ATTENUATION,attenparams); // 04/09/2011 SKJ: This is where I can apply the matrix multiply (by projectorTransform) and draw per Kinect #if KINECT_MODE == 3 /* Vrui::OGTransform projectorTransform; std::string transformFileName="/home/holo/Dropbox/Holovideo/Configuration/Kinect1/ProjectorTransform-B00361710470044B.txt"; Misc::File transformFile(transformFileName.c_str(),"rt"); char transform[1024]; transformFile.gets(transform,sizeof(transform)); projectorTransform=Misc::ValueCoder::decode(transform,transform+strlen(transform),0); Vrui::OGTransform projectorTransform2; std::string transformFileName2="/home/holo/Dropbox/Holovideo/Configuration/Kinect2/ProjectorTransform-A00364817648045A.txt"; Misc::File transformFile2(transformFileName2.c_str(),"rt"); char transform2[1024]; transformFile2.gets(transform2,sizeof(transform2)); projectorTransform2=Misc::ValueCoder::decode(transform2,transform2+strlen(transform2),0); */ // glPushMatrix(); // glMultMatrix(projectorTransform); //cgSetMatrixParameterfr(myCgVertexParam_depthMatrix, &depthMatrixKinect1); //checkForCgError("ln 534"); //cgSetMatrixParameterfr(myCgVertexParam_textureMatrix, &textureMatrixKinect1); //checkForCgError("ln 536"); //cgSetMatrixParameterfr(myCgVertexParam_projectorTransform, &projectorTransform1); kinectNum = 0; cgSetParameter1f(myCgVertexParam_kinectNum, kinectNum); checkForCgError("ln 538"); //glMatrixMode(GL_MODELVIEW); //glPushMatrix(); //glRotatef(-45,0,1,0); //glMultMatrixf(*projectorTransform1); kprojector->draw(*projectorDataContext); //glPopMatrix(); // glPushMatrix(); // glMultMatrix(projectorTransform2); //if(check){ //cgSetMatrixParameterfr(myCgVertexParam_depthMatrix, &depthMatrixKinect2); //checkForCgError("ln 546"); //cgSetMatrixParameterfr(myCgVertexParam_textureMatrix, &textureMatrixKinect2); //checkForCgError("ln 548"); //cgSetMatrixParameterfr(myCgVertexParam_projectorTransform, &projectorTransform2); kinectNum = 1; cgSetParameter1f(myCgVertexParam_kinectNum, kinectNum); checkForCgError("ln 550"); //glPushMatrix(); //glRotatef(45,0,1,0); //glMultMatrixf(*projectorTransform2); kprojector2->draw(*projectorDataContext2); //glPopMatrix(); //} #endif #if KINECT_MODE == 2 kprojector->draw(*projectorDataContext); #endif } void drawPointCloudFromKinect() { // 04/09/2011 SKJ: Is this relevant anymore? //TODO: convert to vertex buffer int ystride = 8; //only render every ystride lines float scale = 0.07; // for converting units from pixel (camera) to scene units. Arbitrary. float gain = 1/256.0; // converting from char units to float float x,y,z,l; glDisable(GL_LIGHTING); glDisable(GL_TEXTURE_2D); //glPointParameter glEnable(GL_POINT_SMOOTH); glPointSize(1.0f); //float attenparams[3] = {0,0,0}; //a b c //size × 1 a + b × d + c × d 2 //glPointParameterfv(GL_POINT_DISTANCE_ATTENUATION,attenparams); glBegin(GL_POINTS); int i = 0; for (int yi = 0;yi<480;yi+=ystride/*+(headnumber/ystride)*/) { for (int xi = 0;xi<640;xi++) { x = -xi*scale; y = -yi*scale; i = yi*640 + xi; z = kinectframe->depth[i]*scale; l = kinectframe->luma[i]*gain; //glColor3f(1,1,1); glColor3f(l,l,l); glVertex4f(x, y, z, 1.0); } } glEnd(); } #endif // KINECT_MODE > 0 void getFilenameForView( int viewnum, int modelnum, char* buff) { char modelname[255]; switch (modelnum) { case 0: sprintf(modelname,"crane"); break; case 1: sprintf(modelname,"Book"); break; case 2: sprintf(modelname,"flower"); break; default: printf("unsupported model number\n"); sprintf(buff,""); return; } sprintf(buff,IMAGE_PATH_TEMPLATE,modelname,viewnum); } #ifdef VIEWS_FROM_CLOUD void loadAllClouds() { int totalimages; int firstimage; int modeltouse = MODEL_TO_USE; float baseline; // length of view set in meters float gain; float imzcenter; //distance from original camera to be placed at diffuser for hologram if(modeltouse==0) { //for crane totalimages = 100; //100 firstimage = 0; baseline = 1.0; imzcenter = 0.5; gain = 1/1500.0; }else if(modeltouse == 2) { //for flowers totalimages = 64; //64 firstimage = 0; baseline = 0.5; imzcenter = 0.5; gain = 1/2048.0; }else { modeltouse = 1; totalimages = 16; //16 firstimage = 0; baseline = 1.0; imzcenter = 0.5; gain = 1/2048.0; } char filename[2048]; int viewsToLoad = VIEWS_TO_LOAD;//totalimages; for (int i = 0; i < viewsToLoad; i++) { int nextview = firstimage + (int)floor(i*totalimages/float(viewsToLoad)); allClouds[i] = new JZCameraCloud(); getFilenameForView(nextview,modeltouse,filename); printf("loading view at %s\n",filename); allClouds[i]->gain = gain; allClouds[i]->cop[0] = -i*baseline/float(viewsToLoad) + baseline/2.0; allClouds[i]->cop[2] = -imzcenter; allClouds[i]->loadFromFile(filename); } numLoadedClouds = viewsToLoad; } #endif void drawDebugShape(float size) { //glEnable(GL_LINE_SMOOTH); //glLineWidth(5.); //glBegin(GL_LINE_STRIP); glBegin(GL_TRIANGLES); //simple vertical line glVertex3f(-4.*size/2.,-size,-100); glVertex3f(-4.*size/2.,size,-100); //sloping horizontal line //glVertex3f(-HologramPlaneWidth_mm/2.0, 0.0, -100.0); //glVertex3f(HologramPlaneWidth_mm/2.0, 0.0, 100.0); glVertex3f(4.*size/2.,-size,100); glEnd(); //glLineWidth(1.); //glDisable(GL_LINE_SMOOTH); //glutSolidCube(size*8); //glutWireCube(size); } static void drawme(float *eyePosition, float *modelMatrix_sphere, float *invModelMatrix_sphere, float *objSpaceLightPosition_sphere, float *modelMatrix_cone, float *invModelMatrix_cone, float *objSpaceLightPosition_cone, float h, float v, int drawdepthOn, float myobject, int viewnumber) { // const float lightPosition[4] = { 10*mag+lx,20*mag+ly,-605*mag+lz, 1 }; const float lightPosition[4] = { 100, 100, -605, 1 }; //const float eyePosition[4] = { 0,0,0, 1 }; float translateMatrix[16], rotateMatrix[16], viewMatrix[16], modelViewMatrix[16], modelViewProjMatrix[16], modelViewProjMatrix2[16]; float objSpaceEyePosition[4], objSpaceLightPosition[4]; int j; buildLookAtMatrix(eyePosition[0], eyePosition[1], eyePosition[2], 0, 0, -425, 0, 1, 0, viewMatrix); /*** Render brass solid sphere ***/ #ifndef VIEWS_FROM_CLOUD //setRedPlasticMaterial(); setBrassMaterial(); //setEmissiveLightColorOnly(); #endif cgSetParameter1f(myCgFragmentParam_drawdepth, drawdepthOn); /* Transform world-space eye and light positions to sphere's object-space. */ //transform (objSpaceEyePosition, invModelMatrix_sphere, eyePosition); cgSetParameter3fv(myCgFragmentParam_eyePosition, objSpaceEyePosition); //transform(objSpaceLightPosition, invModelMatrix_sphere, lightPosition); cgSetParameter3fv(myCgFragmentParam_lightPosition, objSpaceLightPosition_sphere); // 04/10/2011 SKJ: Change to KINECT_MODE > 1 // #if KINECT_MODE == 2 #if KINECT_MODE > 1 && KINECT_MODE < 4 cgSetParameter1f(myCgVertexParam_drawdepth,drawdepthOn); //checkForCgError("ln715"); #if KINECT_MODE == 3 cgSetParameter1f(myCgVertexParam_drawdepthSecond,drawdepthOn); checkForCgError("ln718"); #endif float pmatrix[16]; float m[16]; //JB Testing: was /* kprojector->getDepthProjTransform(pmatrix); //cgSetMatrixParameterfr(myCgVertexParam_modelViewProj, pmatrix); //cgUpdateProgramParameters(normalMapLightingCgVertexProgram); multMatrix(modelViewMatrix, modelMatrix_sphere, pmatrix); //multMatrix(m, pmatrix, modelViewMatrix); makeScaleMatrix(1,1,1,m); //multMatrix(m, pmatrix, modelViewMatrix); //multMatrix(modelViewProjMatrix, myProjectionMatrix1,m); //multMatrix(modelViewMatrix, viewMatrix, modelMatrix_sphere); multMatrix(modelViewProjMatrix, myProjectionMatrix1, modelViewMatrix); */ multMatrix(modelViewProjMatrix, myProjectionMatrix1, modelMatrix_sphere); #else multMatrix(modelViewMatrix, viewMatrix, modelMatrix_sphere); multMatrix(modelViewProjMatrix, myProjectionMatrix1, modelViewMatrix); #endif // glEnable(GL_LIGHTING); glEnable(GL_TEXTURE_2D); //glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fbo); // bind the frame buffer object //glViewport(h,v,64,440); /* Set matrix parameter with row-major matrix. */ cgSetMatrixParameterfr(myCgVertexParam_modelViewProj, modelViewProjMatrix); cgUpdateProgramParameters(normalMapLightingCgVertexProgram); /* glBegin(GL_LINES); { //glVertex3f(0,20,40); //glVertex3f(0,-20,40); glVertex3f(-10,20,1); glVertex3f(-10,-20,10); } glEnd(); glBegin(GL_LINES); { glVertex3f(0,20,10); glVertex3f(0,-20,10); // glVertex3f(-10,20,1); // glVertex3f(-10,-20,1); } glEnd(); glBegin(GL_LINES); { glVertex3f(10,20,20); glVertex3f(10,-20,20); } glEnd();*/ /* if (myobject == 0) { glBlendFunc(GL_SRC_ALPHA, GL_ONE); glColor4f(0.5, 0.5, 0.5, 0.5f); glutSolidCube(8); } if (myobject == 1) { glBlendFunc(GL_SRC_ALPHA, GL_ONE); glColor4f(1.0f, 1.0f, 1.0f, 1.0f); glutSolidCone(5, 5, 5, 5); } */ #if KINECT_MODE > 0 #if KINECT_MODE == 1 drawPointCloudFromKinect(); #endif //glMatrixMode(GL_MODELVIEW); //glLoadIdentity(); //glMultMatrixf(modelViewMatrix); //glMatrixMode(GL_PROJECTION); //glLoadIdentity(); //glMultMatrixf(myProjectionMatrix1); // 04/09/2011 SKJ: Needs to change for KINECT_MODE == 3 #if KINECT_MODE > 1 && KINECT_MODE < 4 drawPointCloudFromKinect_Calibrated(); #endif #if KINECT_MODE == 4 glDisable(GL_TEXTURE_2D); glDisable(GL_LIGHTING); if(viewnumber == 0) {KinectPCL->uploadToGPU();} //TODO: check if frame is fresh, upload as soon as new one available glPointSize(2.0f); KinectPCL->draw(); #endif //glutPostRedisplay(); #else //not kinect mode: #if DRAW_WIRE_CUBE_ONLY == 1 //glutWireCube(16); //draw cube drawDebugShape(16); #else //not "wire cube" #ifndef VIEWS_FROM_CLOUD glCallList(DLid); //draw rabbit from display list #else float ang = (viewnumber/float(numview) - 0.5) * (fov * M_PI/ 180.); drawPointCloudFromZImage(allClouds,ang,ANGLE_THRESH); #endif #endif #endif //glColor4f(1.0f, 1.0f, 1.0f, 1.0f); //glutSolidCube(10); /* modelViewProj = projectionMatrix * modelViewMatrix */ // multMatrix(modelViewProjMatrix2, myProjectionMatrix1, modelViewMatrix); } //Get state from external gui. Update renderer state variables & request redraw if changes detected in gui state. void refreshState(bool force = false) { #ifdef REMOTEQT_GUI //get state from external gui JDisplayState statecopy_old; memcpy(&statecopy_old, &statecopy, sizeof(JDisplayState)); sharedstate->getDataCopy(&statecopy); if(force | memcmp(&statecopy,&statecopy_old,sizeof(JDisplayState))) { MasterHologramGain = statecopy.gain/5.0; //scale down gain from slider to use more of range cgSetParameter1f(myCgFragmentParam_hologramGain, MasterHologramGain); //ripParams->m_render->models->orient->rotate[0] = statecopy.xrot; rot = statecopy.yrot; rotx = statecopy.xrot; //ripParams->m_render->models->orient->rotate[2] = statecopy.zrot; tx = 10.0*statecopy.xpos; ty = /*ty0 +*/ 10.0*statecopy.ypos; tz = 40.0*statecopy.zpos; float sc = statecopy.scale; printf("New model location: (%g,\t %g,\t %g) x %g\n", tx, ty, tz, sc); hologramOutputDebugSwitch = statecopy.shaderMode; cgSetParameter1f(myCgFragmentParam_hologramDebugSwitch, hologramOutputDebugSwitch); cgSetParameter1f(myCgVertexParam_modelUIScale, statecopy.scale); zeroDepth = statecopy.rendermode1; zeroModulation = statecopy.rendermode2; fakeZ = (statecopy.flatdepth1 + 99)/198.0; //slider internal range is -99 to 99, map to 0-1 fakeModulation = (statecopy.flatdepth2 + 99)/198.0; ViewEnableBitmask = statecopy.viewmask; printf("view bitmask = %x\n", ViewEnableBitmask); glutPostRedisplay(); //new state -- new stuff to draw } #endif } //Draw text string to current buffer using GLUT void drawString(float x, float y, char *string) { int len, i; glRasterPos2f(x, y); len = (int) strlen(string); for (i = 0; i < len; i++) { glutBitmapCharacter(GLUT_BITMAP_HELVETICA_18, string[i]); } } void saveSingleView(int viewnum,int chan) { GLenum frmt; switch(chan) { case -1: frmt = GL_LUMINANCE; break; case 0: frmt = GL_RED; break; case 1: frmt = GL_GREEN; break; case 2: frmt = GL_BLUE; break; case 3: frmt = GL_ALPHA; break; } glReadPixels(0, 0, numx, numy, frmt, GL_UNSIGNED_BYTE, localFramebufferStore); system("mkdir views 2> /dev/null"); char fname[512]; sprintf(fname, "view_%04d.raw", viewnum); FILE *fp = fopen(fname,"w"); if(!fp) {printf("failed to create file %s\n", fname);return;} fwrite(localFramebufferStore, sizeof(char), numx*numy, fp); fclose(fp); } static void display(void) { //get state from UI & update model refreshState(); // 04/09/2011 SKJ: Needs to change for KINECT_MODE == 3 #if KINECT_MODE > 1 && KINECT_MODE < 3 updateKinectCloud(); //get fresh kinect data #endif #if KINECT_MODE == 4 //KinectPCL->uploadToGPU(); //actually do this as we render each view to have absolute latest data (with possible tearing) #endif /* World-space positions for light and eye. */ float eyePosition[4] = { 0, 0, 0, 1 }; // const float lightPosition[4] = { 0, 500*mag,-500*mag, 1 }; const float lightPosition[4] = { 10 * mag + lx, 20 * mag + ly, -605 * mag + lz, 1 }; float xpos, h, v, rgba, scale; int i, j; float myobject; float translateMatrix[16], rotateMatrix[16], rotateMatrix1[16], translateNegMatrix[16], rotateTransposeMatrix[16], rotateTransposeMatrix1[16], scaleMatrix[16], scaleNegMatrix[16], translateMatrixB[16], rotateMatrixB[16], rotateMatrix1B[16], translateNegMatrixB[16], rotateTransposeMatrixB[16], rotateTransposeMatrix1B[16], scaleMatrixB[16], scaleNegMatrixB[16], modelMatrix_sphere[16], invModelMatrix_sphere[16], modelMatrix_cone[16], invModelMatrix_cone[16], objSpaceLightPosition_sphere[16], objSpaceLightPosition_cone[16], objSpaceEyePosition_sphere[16], objSpaceEyePosition_sphereB[16], modelMatrix_sphereB[16], invModelMatrix_sphereB[16], modelMatrix_coneB[16], invModelMatrix_coneB[16], objSpaceLightPosition_sphereB[16], objSpaceLightPosition_coneB[16]; #if DISABLE_VIEW_RENDERING == 0 //can skip view rendering for debug of hologram layout glPushAttrib(GL_VIEWPORT_BIT | GL_COLOR_BUFFER_BIT); glEnable(GL_TEXTURE_2D); #ifndef VIEWS_FROM_CLOUD glBindTexture(GL_TEXTURE_2D, meshTexID); #endif cgGLBindProgram(normalMapLightingCgVertexProgram); //checkForCgError("ln943 binding vertex program lighting"); cgGLEnableProfile(normalMapLightingCgVertexProfile); //checkForCgError("ln945 enabling vertex profile lighting"); cgGLBindProgram(normalMapLightingCgFragmentProgram); //checkForCgError("ln949 binding vertex program lighting"); cgGLEnableProfile(normalMapLightingCgFragmentProfile); //checkForCgError("ln951 enabling vertex profile lighting"); /*for sphere find model and invModelMatrix */ //TODO: recompute these only on change: makeRotateMatrix(rot, 0, 1, 0, rotateMatrix); makeRotateMatrix(-rot, 0, 1, 0, rotateTransposeMatrix); makeRotateMatrix(180 + rotx, 1, 0, 0, rotateMatrix1); makeRotateMatrix(-180 - rotx, 1, 0, 0, rotateTransposeMatrix1); multMatrix(rotateMatrix, rotateMatrix1, rotateMatrix); multMatrix(rotateTransposeMatrix, rotateTransposeMatrix1, rotateTransposeMatrix); //z is -600 + tz (z shift tz is centered halfway between near & far planes) makeTranslateMatrix(tx, ty, -(far + near) * 0.5 * mag + tz * mag, translateMatrix); makeTranslateMatrix(-tx, -ty, (far + near) * 0.5 * mag - tz * mag, translateNegMatrix); scale = 2; makeScaleMatrix(scale, scale, scale, scaleMatrix); makeScaleMatrix(1 / scale, 1 / scale, 1 / scale, scaleNegMatrix); multMatrix(modelMatrix_sphere, translateMatrix, rotateMatrix); multMatrix(invModelMatrix_sphere, rotateTransposeMatrix, translateNegMatrix); multMatrix(modelMatrix_sphere, modelMatrix_sphere, scaleMatrix); multMatrix(invModelMatrix_sphere, scaleNegMatrix, invModelMatrix_sphere); /* Transform world-space eye and light positions to sphere's object-space. */ transform(objSpaceLightPosition_sphere, invModelMatrix_sphere, lightPosition); transform(objSpaceEyePosition_sphere, invModelMatrix_sphere, eyePosition); //manipulations for "second object" (mostly disabled) #if DISABLE_SECOND_OBJECT == 0 { // ? makeRotateMatrix(90 - 30 - rot * 2 * 0, 0, 1, 0, rotateMatrixB); makeRotateMatrix(-90 + 30 + rot * 2 * 0, 0, 1, 0, rotateTransposeMatrixB); makeRotateMatrix(180, 1, 0, 0, rotateMatrix1B); makeRotateMatrix(-180, 1, 0, 0, rotateTransposeMatrix1B); multMatrix(rotateMatrixB, rotateMatrix1B, rotateMatrixB); multMatrix(rotateTransposeMatrixB, rotateTransposeMatrix1B, rotateTransposeMatrixB); makeTranslateMatrix(tx * 0 + 25, ty * 0 - 5 + 10, -600.0 * mag - 70 * mag, translateMatrixB); makeTranslateMatrix(-tx * 0 - 25, -ty * 0 + 5 - 10, 600.0 * mag + 70 * mag, translateNegMatrixB); scale = 2; makeScaleMatrix(scale, scale, scale, scaleMatrixB); makeScaleMatrix(1 / scale, 1 / scale, 1 / scale, scaleNegMatrixB); multMatrix(modelMatrix_sphereB, translateMatrixB, rotateMatrixB); multMatrix(invModelMatrix_sphereB, rotateTransposeMatrixB, translateNegMatrixB); multMatrix(modelMatrix_sphereB, modelMatrix_sphereB, scaleMatrixB); multMatrix(invModelMatrix_sphereB, scaleNegMatrixB, invModelMatrix_sphereB); /* Transform world-space eye and light positions to sphere's object-space. */ transform(objSpaceLightPosition_sphereB, invModelMatrix_sphereB, lightPosition); transform(objSpaceEyePosition_sphereB, invModelMatrix_sphereB, eyePosition); } #endif // glViewport(0,0,640,480); // glEnable(GL_CULL_FACE); i = 0; j = 0; xpos = 0; h = 0; v = 0; //glClearColor(0.5,0.5,0.5,0.5);//JB Hack: clear view buffer to gray for debugging glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); //glDrawBuffer(GL_COLOR_ATTACHMENT0_EXT); for (i = 0; i < numview; i++) { #ifdef SOLO_VIEW if(i != SOLO_VIEW) continue; #endif if((ViewEnableBitmask & (1< 1000) { const int len = 1024; char msg[len]; // printf("here\n"); fps = frame * 1000.0 / (thetime - timebase); timebase = thetime; frame = 0; sprintf(msg,"Wafel %d render Mode: %d fps: %f\n", headnumber, (int)KINECT_MODE, fps); printf("%s",msg); #ifdef REMOTEQT_GUI for(int i=0;istatusMessage[headnumber][i] = msg[i]; } //memcpy(&(displaystatus->statusMessage[headnumber][0]),msg,len); #endif fflush(stdout); } #if QUIT_AFTER_SECONDS if (thetime > 1000 * QUIT_AFTER_SECONDS) exit(0); #endif refreshState(); } //void ShutDown(void) //{ // // glDeleteFramebuffersEXT(1, &fbo); // glDeleteTextures(1, &texture_id[0]); //} void writeViewsToFile() { glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, texture_id[0]); glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_UNSIGNED_BYTE, localFramebufferStore); glDisable(GL_TEXTURE_2D); FILE *f; if ((f = fopen("views.raw", "w")) == NULL) { printf("failure opening file.\n"); exit(0); } else { fwrite(localFramebufferStore,1,sizeof(localFramebufferStore),f); printf("wrote %d bytes\n",sizeof(localFramebufferStore)); fclose(f); } } void writeToFile2(void) { unsigned char *pic; unsigned char *bptr; FILE *fp; int allocfail = 0; int screenWidth = imwidth; int screenHeight = imheight;//1757 * 2;//1780*2; printf("attempting to write framebuffer to file"); if ((pic = (unsigned char*) malloc(screenWidth * screenHeight * 3 * sizeof(unsigned char))) == NULL) { printf("couldn't allocate memory for framebuffer dump.\n"); allocfail = 1; } if (!allocfail) { char fname[255]; glReadBuffer(GL_FRONT); bptr = pic; glReadPixels(0, 0, screenWidth, screenHeight, GL_RGB, GL_UNSIGNED_BYTE, pic); printf("saving %dx%dx3 to file...\n", screenWidth, screenHeight); if ((fp = fopen("holodump3.raw", "w")) == NULL) { printf("failure opening file.\n"); exit(0); } else { if (fwrite(pic, 1, 3 * screenWidth * screenHeight, fp) != screenWidth * screenHeight * 3) { printf("failure writing file.\n"); //exit(0); } fclose(fp); } free(pic); } } static void keyboard(unsigned char c, int x, int y) { //printf("keyboard \n"); switch (c) { case 'z': //invert set of disabled views ViewEnableBitmask = ~ViewEnableBitmask; break; case 'Z': //enable all views ViewEnableBitmask = -1; break; case 'x': //cycle through debug modes in shader (output intermediate variables) hologramOutputDebugSwitch++; hologramOutputDebugSwitch = hologramOutputDebugSwitch % hologramOutputDebugSwitches; cgSetParameter1f(myCgFragmentParam_hologramDebugSwitch, hologramOutputDebugSwitch); break; case 'X': hologramOutputDebugSwitch--; hologramOutputDebugSwitch = hologramOutputDebugSwitch % hologramOutputDebugSwitches; cgSetParameter1f(myCgFragmentParam_hologramDebugSwitch, hologramOutputDebugSwitch); break; case 'j': tx = tx + 5; printf("tx %f \n", tx); break; case 'l': tx = tx - 5; printf("tx %f \n", tx); break; case 'i': ty = ty - 1; printf("ty %f \n", ty); break; case 'k': ty = ty + 1; printf("ty %f \n", ty); break; case 'w': tz = tz - 1; printf("%f \n", tz - 675); break; case 's': tz = tz + 1; printf("%f \n", tz - 675); break; case 'f': writeToFile2(); break; case 'F': printf("writing view texture\n"); writeViewsToFile(); break; case 'e': tz = tz - 10; printf("%f \n", tz - 675); break; case 'd': tz = tz + 10; printf("%f \n", tz - 675); break; case 'c': tz = 0; printf("%f \n", tz - 675); break; case 'r': rotateOn = (rotateOn * -1) + 1; printf("rotate %i \n", rotateOn); break; case ' ': //makeViewtexFromFile(); break; case ']': lz = lz - 10; printf("%f \n", lz); break; case '[': lz = lz + 10; printf("%f \n", lz); break; case '=': ly = ly - 10; printf("%f \n", ly); break; case '-': ly = ly + 10; printf("%f \n", ly); break; case ';': lx = lx - 10; printf("%f \n", lx); break; case '/': lx = lx + 10; printf("%f \n", lx); break; case '1': //cgSetParameter1f(myCgFragmentParam_hogelYes, 0.); //cgUpdateProgramParameters(myCgFragmentProgram2); //printf("Wafel"); break; case '2': //cgSetParameter1f(myCgFragmentParam_hogelYes, 1.); //cgUpdateProgramParameters(myCgFragmentProgram2); //printf("Hogel"); break; case 27: /* Esc key */ /* Demonstrate proper deallocation of Cg runtime data structures. Not strictly necessary if we are simply going to exit. */ cgDestroyProgram(normalMapLightingCgVertexProgram); cgDestroyContext(normalMapLightingCgContext); // ShutDown(); exit(0); break; } int mods = glutGetModifiers(); if(mods != 0) { if(c >= '0' && c <= '9') ViewEnableBitmask ^= 1<<(c-'0'+10); //toggle view enable bit for numbered view 10-19 (only 16 views used) } else { if(c >= '0' && c <= '9') ViewEnableBitmask ^= 1<<(c-'0'); //toggle view enable bit for numbered view 0-9 } glutPostRedisplay(); } void init(const char *filename_obj, char *filename_tex) { GLfloat lightpos[] = { 20.0f, 20.0f, -550.0f, 1.0f }; // Initialize OpenGL context glClearColor(0.f, 0.f, 0.f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // glShadeModel (GL_SMOOTH); glLightfv(GL_LIGHT0, GL_POSITION, lightpos); glShadeModel(GL_SMOOTH); // Enable Smooth Shading glClearColor(0.0f, 0.0f, 0.0f, 1.0f); // Black Background // Depth Buffer Setup glEnable(GL_DEPTH_TEST); // Enables Depth Testing glLightfv(GL_LIGHT0, GL_AMBIENT, LightAmbient); // Setup The Ambient Light glLightfv(GL_LIGHT0, GL_DIFFUSE, LightDiffuse); // Setup The Diffuse Light glLightfv(GL_LIGHT0, GL_POSITION, LightPosition); // Position The Light glEnable(GL_LIGHT0); // Enable Light One glEnable(GL_LIGHTING); glEnable(GL_COLOR_MATERIAL); glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); // Initialize OpenGL context glClearColor(0.f, 0.f, 0.f, 1.0f); // glShadeModel (GL_SMOOTH); glEnable(GL_DEPTH_TEST); glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glLightfv(GL_LIGHT0, GL_POSITION, lightpos); //glDrawBuffers(2,buffers); #if KINECT_MODE < 1 printf("load textures\n"); //Load BMP texture from file meshTexID = loadBMPTexture(filename_tex); printf("done \n"); if (!meshTexID) exit(EXIT_FAILURE); // Load OBJ model file if (!ReadOBJModel(filename_obj, &objfile)) exit(EXIT_FAILURE); // Make display list DLid = glGenLists(1); glNewList(DLid, GL_COMPILE); RenderOBJModel(&objfile); glEndList(); FreeModel(&objfile); #endif glDisable(GL_LIGHTING); } void cleanup() { #if KINECT_MODE < 1 glDeleteLists(DLid, 1); glDeleteTextures(1, &meshTexID); #endif // glDeleteFramebuffersEXT(1,&fbo); // glDeleteRenderbuffersEXT(1,&depthbuffer); // FreeModel (&objfile); delete localFramebufferStore; } int main(int argc, char **argv) { if(argc == 2) { headnumber = atoi(argv[1]); if (headnumber > 2 || headnumber < 0) headnumber = 0; } localFramebufferStore = new GLubyte[VIEWTEX_WIDTH*VIEWTEX_HEIGHT*4]; #ifdef REMOTEQT_GUI //state for slaving to separate UI sharedstate = new JSharedMemory(sizeof(JDisplayState),ALL_STATE_KEY); sharedstatus = new JSharedMemory(sizeof(JDisplayStatus),ALL_STATUS_KEY); displaystatus = (JDisplayStatus*)sharedstatus->getptr(); sharedstate->getDataCopy(&statecopy); #endif #if DISABLE_HOLOGRAM_CREATION == 1 glutInitWindowSize(VIEWTEX_WIDTH, VIEWTEX_HEIGHT); //170*12 (so 170 lines, not 440lines) #else #if HOLOGRAM_DOWNSCALE_DEBUG != 0 glutInitWindowSize(imwidth/HOLOGRAM_DOWNSCALE_DEBUG, imheight/HOLOGRAM_DOWNSCALE_DEBUG); //170*12 (so 170 lines, not 440lines) #else glutInitWindowSize(MarkIIGLWindowWidth, MarkIIGLWindowHeight); //170*12 (so 170 lines, not 440lines) #endif #endif glutInitDisplayMode(GLUT_RGBA | GLUT_ALPHA | GLUT_DOUBLE | GLUT_DEPTH); //original code did not ask for alpha, resulting in no alpha on linux. glutInit(&argc, argv); glutCreateWindow(normalMapLightingProgramName); glutDisplayFunc(display); glutKeyboardFunc(keyboard); glutIdleFunc(idle); atexit(cleanup); #ifndef __APPLE__ #if USE_GLEW GLenum err = glewInit(); if (GLEW_OK != err) { printf("GLEW init failed\n"); } #endif #endif // Setup our FBO // glGenFramebuffersEXT(1, &fbo); // glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fbo); // Setup our depthbuffer //glGenRenderbuffersEXT(1, &depthbuffer); //glBindRenderbufferEXT(GL_FRAMEBUFFER_EXT, depthbuffer); //glRenderbufferStorageEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_COMPONENT, imheight,imwidth); char *filename_obj = "models/bunny502uvA.obj\0"; char *filename_tex = "models/bunny502uv_normtex2.bmp\0"; init(filename_obj, filename_tex); glGenTextures(2, texture_id); // requestSynchornizedSwapBuffers(); glClearColor(0.0, 0.0, 0.0, 0); // Gray background. glEnable(GL_DEPTH_TEST); // Hidden surface removal. double q = tan(0.1); buildShearOrthographicMatrix2(-75. * mag, 75. * mag, -37.5 * mag, 37.5 * mag, 450. * mag, 750. * mag, q / mag, myProjectionMatrix1); normalMapLightingCgContext = cgCreateContext(); checkForCgError("creating context"); cgGLSetDebugMode(CG_FALSE); //cgSetParameterSettingMode(myCgContext, CG_DEFERRED_PARAMETER_SETTING); normalMapLightingCgVertexProfile = cgGLGetLatestProfile(CG_GL_VERTEX); cgGLSetOptimalOptions(normalMapLightingCgVertexProfile); checkForCgError("selecting vertex profile1"); normalMapLightingCgVertexProgram = cgCreateProgramFromFile(normalMapLightingCgContext, // Cg runtime context CG_SOURCE, //Program in human-readable form normalMapLightingProgramFileName, // Name of file containing program normalMapLightingCgVertexProfile, // Profile: OpenGL ARB vertex program normalMapLightingVertexProgramName, // Entry function name NULL); // No extra commyPiler options checkForCgError("creating vertex program from file"); printf("created vertex program from file...\n"); cgGLLoadProgram(normalMapLightingCgVertexProgram); checkForCgError("loading vertex program"); printf("loaded vertex program\n"); #define GET_PARAM(name) \ myCgVertexParam_##name = \ cgGetNamedParameter(normalMapLightingCgVertexProgram, #name); \ checkForCgError("could not get " #name " parameter"); GET_PARAM(modelViewProj); #if KINECT_MODE > 1 && KINECT_MODE < 4 GET_PARAM(textureMatrix); checkForCgError("could not get textureMatrix vertex parameter ln 1707"); GET_PARAM(depthMatrix); checkForCgError("could not get depthMatrix vertex parameter ln 1707"); GET_PARAM(drawdepth); checkForCgError("could not get drawDepth vertex parameter ln 1707"); #endif // 04/10/2011 SKJ: Handle second Kinect #if KINECT_MODE == 3 GET_PARAM(textureMatrixSecond); GET_PARAM(depthMatrixSecond); GET_PARAM(drawdepthSecond); GET_PARAM(projectorTransform); GET_PARAM(projectorTransform2); GET_PARAM(kinectNum); #endif #if KINECT_MODE == 4 GET_PARAM(modelUIScale); KinectPCL = new JVertexRender(); KinectPCL->setDecimate(OPENNI_DECIMATE); //GET_PARAM(drawdepth); //checkForCgError("could not get drawDepth parameter"); #endif normalMapLightingCgFragmentProfile = cgGLGetLatestProfile(CG_GL_FRAGMENT); cgGLSetOptimalOptions(normalMapLightingCgFragmentProfile); checkForCgError("selecting fragment profile"); normalMapLightingCgFragmentProgram = cgCreateProgramFromFile(normalMapLightingCgContext, // Cg runtime context CG_SOURCE, // Program in human-readable form normalMapLightingVertexProgramFileName, normalMapLightingCgFragmentProfile, // Profile: latest fragment profile normalMapLightingFragmentProgramName, // Entry function name NULL); // No extra commyPiler options checkForCgError("creating fragment program from string2"); cgGLLoadProgram(normalMapLightingCgFragmentProgram); checkForCgError("loading fragment program"); #define GET_FRAGMENT_PARAM(name) \ myCgFragmentParam_##name = \ cgGetNamedParameter(normalMapLightingCgFragmentProgram, #name); \ checkForCgError("could not get " #name " parameter"); GET_FRAGMENT_PARAM(globalAmbient); GET_FRAGMENT_PARAM(lightColor); GET_FRAGMENT_PARAM(lightPosition); GET_FRAGMENT_PARAM(eyePosition); GET_FRAGMENT_PARAM(Ke); GET_FRAGMENT_PARAM(Ka); GET_FRAGMENT_PARAM(Kd); GET_FRAGMENT_PARAM(Ks); GET_FRAGMENT_PARAM(shininess); GET_FRAGMENT_PARAM(drawdepth); GET_FRAGMENT_PARAM(headnum); myCgFragmentParam_decal = cgGetNamedParameter(normalMapLightingCgFragmentProgram, "decal"); checkForCgError("getting decal parameter"); cgGLSetTextureParameter(myCgFragmentParam_decal, meshTexID); checkForCgError("setting decal texture"); // Set light source color parameters once. cgSetParameter3fv(myCgFragmentParam_globalAmbient, myGlobalAmbient); checkForCgError("ln1750"); cgSetParameter3fv(myCgFragmentParam_lightColor, myLightColor); checkForCgError("ln1753"); //set up head number for rendering/loading with skipped lines cgSetParameter1i(myCgFragmentParam_headnum, headnumber); checkForCgError("setting head number parameter"); //set up view texture (holds all view images. TODO: convert to 2 3d textures glBindTexture(GL_TEXTURE_2D, texture_id[0]); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP); glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, VIEWTEX_WIDTH, VIEWTEX_HEIGHT, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); // glBindTexture(GL_TEXTURE_2D,texture_id[1]); // glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); // glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); // glTexImage2D(GL_TEXTURE_2D, 0,GL_RGBA,imwidth, imheight, 0, GL_RGBA, //GL_UNSIGNED_BYTE,myTexture2); // And attach it to the FBO so we can render to it // glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D,texture_id[0], 0); // GLenum status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT); //if(status != GL_FRAMEBUFFER_COMPLETE_EXT) // exit(1); // glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0); // Unbind the FBO for now // buildTexture(); // glBindTexture(GL_TEXTURE_2D,texture_id[1]); // // glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); // glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); // glTexImage2D(GL_TEXTURE_2D, 0,GL_RGBA,imheight,128, 0, GL_RGBA, GL_FLOAT, myTexture2); myCgVertexProfile2 = cgGLGetLatestProfile(CG_GL_VERTEX); cgGLSetOptimalOptions(myCgVertexProfile2); checkForCgError("selecting vertex profile2"); myCgVertexProgram2 = cgCreateProgramFromFile(normalMapLightingCgContext, // Cg runtime context CG_SOURCE, // Program in human-readable form myVertexProgramFileName2, // Name of file containing program // "/home/holo/Quinn/holodepth/holodepth/src/Holov_myTextures.cg", myCgVertexProfile2, // Profile: OpenGL ARB vertex program myVertexProgramName2, // Entry function name // "Holov_myTextures", NULL); // No extra compiler options checkForCgError2("creating vertex program from file"); cgGLLoadProgram(myCgVertexProgram2); checkForCgError2("loading vertex program"); myCgFragmentProfile2 = cgGLGetLatestProfile(CG_GL_FRAGMENT); cgGLSetOptimalOptions(myCgFragmentProfile2); checkForCgError2("selecting fragment profile"); myCgFragmentProgram2 = cgCreateProgramFromFile(normalMapLightingCgContext, // Cg runtime context CG_SOURCE, // Program in human-readable form myFragmentProgramFileName2, // Name of file containing program myCgFragmentProfile2, // Profile: OpenGL ARB vertex program myFragmentProgramName2, // Entry function name NULL); // No extra compiler options checkForCgError2("creating fragment program from file"); cgGLLoadProgram(myCgFragmentProgram2); checkForCgError2("loading fragment program"); #define GET_FRAGMENT_PARAM2(name) \ myCgFragmentParam_##name = \ cgGetNamedParameter(myCgFragmentProgram2, #name); \ checkForCgError("could not get " #name " parameter"); GET_FRAGMENT_PARAM2(hogelYes); cgSetParameter1f(myCgFragmentParam_hogelYes, 0.); GET_FRAGMENT_PARAM2(hologramGain); cgSetParameter1f(myCgFragmentParam_hologramGain, MasterHologramGain); GET_FRAGMENT_PARAM2(hologramDebugSwitch); cgSetParameter1f(myCgFragmentParam_hologramDebugSwitch, hologramOutputDebugSwitch); GET_FRAGMENT_PARAM2(headnum); cgSetParameter1i(myCgFragmentParam_headnum, headnumber); //TODO: investigate possible conflict with other shader using same uniform myCgFragmentParam_decal0 = cgGetNamedParameter(myCgFragmentProgram2, "decal0"); checkForCgError2("getting decal parameter0"); cgGLSetTextureParameter(myCgFragmentParam_decal0, texture_id[0]); // cgGLSetTextureParameter(myCgFragmentParam_decal0, 0); checkForCgError2("setting decal 3D texture0"); // myCgFragmentParam_decal1 =cgGetNamedParameter(myCgFragmentProgram2, "decal1"); // checkForCgError2("getting decal parameter1"); // cgGLSetTextureParameter(myCgFragmentParam_decal1, texture_id[1]); //// cgGLSetTextureParameter(myCgFragmentParam_decal1, 1); //checkForCgError2("setting decal 1D texture1"); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); #ifdef VIEWS_FROM_CLOUD #if KINECT_MODE < 1 //loading of pre-rendered data loadAllClouds(); //makeViewtexFromFile(); #endif #endif #ifdef VIEWS_FROM_CLOUD //makeViewtexFromFile(); glutSwapBuffers(); #endif // 04/09/2011 SKJ: Needs to change for KINECT_MODE == 3 #if KINECT_MODE > 0 sharedkinect = new JSharedMemory(sizeof(JKinectFrame),KINECT_SHMEM_KEY); kinectframe = (JKinectFrame*)sharedkinect->getptr(); char** appDefaults = 0; Vrui::init(argc,argv,appDefaults); glextmgr = new GLExtensionManager(); GLExtensionManager::makeCurrent(glextmgr); #if KINECT_MODE > 1 && KINECT_MODE < 4 depthFrameBuffer = new FrameBuffer(kinectCloudWidth,kinectCloudHeight,kinectCloudWidth*kinectCloudHeight*sizeof(unsigned short)); colorFrameBuffer = new FrameBuffer(kinectCloudWidth,kinectCloudHeight,kinectCloudWidth*kinectCloudHeight*sizeof(unsigned char)); #if KINECT_MODE == 3 kprojector = new KinectProjector(PROJECTION_CONFIG_FILENAME,1); checkForCgError("ln1875"); #else #if KINECT_MODE == 2 kprojector = new KinectProjector(PROJECTION_CONFIG_FILENAME,0); checkForCgError("ln1880"); #endif #endif projectorDataContext = new GLContextData(1000); kprojector->initContext(*projectorDataContext); checkForCgError("ln1884"); float tmatrix[16]; float tmatrix4[16]; kprojector->getColorProjTransform(tmatrix); printf("Kinect 1 Texture Matrix:\n"); printmatrix(tmatrix); cgSetMatrixParameterfr(myCgVertexParam_textureMatrix, tmatrix); checkForCgError("ln1890"); //textureMatrixKinect1 = *tmatrix; kprojector->getDepthProjTransform(tmatrix); cgSetMatrixParameterfr(myCgVertexParam_depthMatrix, tmatrix); printf("Kinect 1 Depth Matrix:\n"); printmatrix(tmatrix); //depthMatrixKinect1 = *tmatrix; checkForCgError("ln1894"); // 04/09/2011 SKJ: Added to handle second Kinect #if KINECT_MODE == 3 //kprojector->getProjTransform(tmatrix); //makeRotateMatrix(0, 0, 0, 0, tmatrix); //makeTranslateMatrix(0, 0, 0, tmatrix4); makeRotateMatrix(16.092324735547, -0.0672037642388, -0.98912306374287, -0.13084043275702, tmatrix); makeTranslateMatrix(6, 5, 0, tmatrix4); //makeRotateMatrix(39.092324735547, -0.0672037642388, -0.98912306374287, -0.13084043275702, tmatrix); //makeTranslateMatrix(-35.602902491527, -16.875347318442, 170.02844480397, tmatrix4); //makeRotateMatrix(25.819859391758, 0, 1, 0, tmatrix); //makeTranslateMatrix(-50, 0, 0, tmatrix4); //multMatrix(tmatrix, tmatrix, tmatrix4); //tmatrix[12] = 0; tmatrix[3] = tmatrix4[3]; tmatrix[7] = tmatrix4[7]; tmatrix[11] = tmatrix4[11]; //transposeMatrix(tmatrix, tmatrix); cgSetMatrixParameterfr(myCgVertexParam_projectorTransform, tmatrix); printf("Kinect 1 Projection Matrix:\n"); printmatrix(tmatrix); //projectorTransform1 = *tmatrix; // checkForCgError("ln1934"); //kinectNum = 0; //cgSetParameter1f(myCgVertexParam_kinectNum, kinectNum); checkForCgError("ln1934"); sharedkinect2 = new JSharedMemory(sizeof(JKinectFrame),KINECT_SHMEM_KEY_2); // KINECT_SHMEM_KEY_2 is defined in JKinectFrame.h kinectframe2 = (JKinectFrame*)sharedkinect2->getptr(); depthFrameBuffer2 = new FrameBuffer(kinectCloudWidth,kinectCloudHeight,kinectCloudWidth*kinectCloudHeight*sizeof(unsigned short)); colorFrameBuffer2 = new FrameBuffer(kinectCloudWidth,kinectCloudHeight,kinectCloudWidth*kinectCloudHeight*sizeof(unsigned char)); // std::string transformFileName2="/home/holo/Dropbox/Holovideo/Configuration/Kinect2/ProjectorTransform-A00364817648045A.txt"; kprojector2 = new KinectProjector(PROJECTION_CONFIG_FILENAME_2,2); projectorDataContext2 = new GLContextData(1000); checkForCgError("ln1907"); kprojector2->initContext(*projectorDataContext2); checkForCgError("ln1909"); float tmatrix2[16]; kprojector2->getColorProjTransform(tmatrix2); cgSetMatrixParameterfr(myCgVertexParam_textureMatrixSecond, tmatrix2); printf("Kinect 2 Texture Matrix:\n"); printmatrix(tmatrix2); textureMatrixKinect2 = *tmatrix2; checkForCgError("ln1915"); kprojector2->getDepthProjTransform(tmatrix2); cgSetMatrixParameterfr(myCgVertexParam_depthMatrixSecond, tmatrix2); printf("Kinect 2 Depth Matrix:\n"); printmatrix(tmatrix2); depthMatrixKinect2 = *tmatrix2; checkForCgError("ln1920"); // 04/11/2011 float tmatrix3[16]; //kprojector2->getProjTransform(tmatrix2); //makeRotateMatrix(0, 0, 0, 0, tmatrix2); //makeTranslateMatrix(0, 0, 0, tmatrix3); makeRotateMatrix(26.819859391758, -0.03949171492209, 0.99856646911515, -0.036130474829529, tmatrix2); makeTranslateMatrix(-35, 0, 0, tmatrix3); //makeRotateMatrix(25.819859391758, -0.03949171492209, 0.99856646911515, -0.036130474829529, tmatrix2); //makeTranslateMatrix(55.962614888047, -22.307618594269, 171.3241052946, tmatrix3); //makeRotateMatrix(39.092324735547, -0.0672037642388, -0.98912306374287, -0.13084043275702, tmatrix2); //makeTranslateMatrix(50, 0, 0, tmatrix3); tmatrix2[3] = tmatrix3[3]; tmatrix2[7] = tmatrix3[7]; tmatrix2[11] = tmatrix3[11]; //multMatrix(tmatrix2, tmatrix2, tmatrix3); //tmatrix2[12]=0; //transposeMatrix(tmatrix2, tmatrix2); cgSetMatrixParameterfr(myCgVertexParam_projectorTransform2, tmatrix2); printf("Kinect 2 Projection Matrix:\n"); printmatrix(tmatrix2); //projectorTransform2 = *tmatrix2; checkForCgError("ln1936"); #endif #endif #endif refreshState(1); glutMainLoop(); return 0; } //BONEYARD /* void makeViewtexFromFile() { //build texture for rendering point clouds GLuint rtTexture, rtDepthTexture; float rtexheight = 640; float rtexwidth = 480; glGenTextures(1, &rtTexture); glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, rtTexture); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,GL_LINEAR_MIPMAP_NEAREST ); // when texture area is large, bilinear filter the original glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); // the texture wraps over at the edges (repeat) glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT ); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT ); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, rtexwidth, rtexheight, 0, GL_RGBA, GL_FLOAT, NULL); // copy luma image into GL texture //build texture for depth buffer glGenTextures(1, &rtDepthTexture); glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, rtDepthTexture); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,GL_LINEAR_MIPMAP_NEAREST ); // when texture area is large, bilinear filter the original glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); glTexParameterf(GL_TEXTURE_2D, GL_DEPTH_TEXTURE_MODE, GL_INTENSITY); // the texture wraps over at the edges (repeat) glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT ); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT ); glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, rtexwidth, rtexheight, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_BYTE, NULL); // copy luma image into GL texture //build fbo for rectified view rectifiedfbo = new FramebufferObject(); rectifiedfbo->Bind(); rectifiedfbo->AttachTexture( GL_COLOR_ATTACHMENT0_EXT, //attachment point in FBO GL_TEXTURE_2D, //type of attachment rtTexture); //texture identifier to attach rectifiedfbo->AttachTexture( GL_DEPTH_ATTACHMENT_EXT, //attachment point in FBO GL_TEXTURE_2D, //type of attachment rtDepthTexture); //texture identifier to attach if(!rectifiedfbo->IsValid()) { printf("Created FBO, but it says it isn't valid\n"); } CheckErrorsGL("END : creating fbo"); //build fbo for texture containing all views GLuint texToWrite = texture_id[0]; FramebufferObject *allviewsfbo = new FramebufferObject(); if (!allviewsfbo) { printf("Framebuffer did not allocate.\n"); } //activate the FBO allviewsfbo->Bind(); //link to texture allviewsfbo->AttachTexture( GL_COLOR_ATTACHMENT0_EXT, //attachment point in FBO GL_TEXTURE_2D, //type of attachment texToWrite); //texture identifier to attach Renderbuffer *rb = new Renderbuffer(); rb->Set( GL_DEPTH_COMPONENT24, VIEWTEX_WIDTH, VIEWTEX_HEIGHT ); allviewsfbo->AttachRenderBuffer( GL_DEPTH_ATTACHMENT_EXT, rb->GetId() ); glClearColor(0,0,0,0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); if(!allviewsfbo->IsValid()) { printf("Created FBO, but it says it isn't valid\n"); } CheckErrorsGL("END : creating fbo"); glEnable(GL_TEXTURE_2D); glDisable(GL_DEPTH_TEST); glLoadIdentity(); for (int i = 0; i < numview; i++) { //int nextview = firstimage + (int)floor(i*totalimages/float(numview)); //getFilenameForView(nextview,modeltouse,filename); //printf("loading view at %s\n",filename); //c.loadFromFile(filename); //c.buildFlatLumaGLTexture();//load and bind next luma texture //draw luminance map //glBindTexture(GL_TEXTURE_2D, c.lumtextureGL); //not needed here - already bound //drawQuadOverNumberedView(i,false); //setupDrawToNumberedView(i,false); rectifiedfbo->Bind(); glDisable(GL_TEXTURE_2D); glEnable(GL_DEPTH_TEST); glClearColor(0,0,0,0); glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT); glViewport(0, 0, rtexwidth, rtexwidth); drawPointCloudFromZImage(allClouds[i],0,M_PI); //render to stack of views //allviewsfbo->Bind(); rectifiedfbo->Disable(); glClear(GL_DEPTH_BUFFER_BIT); //clear depth buffer but keep accumulating color glDisable(GL_DEPTH_TEST); glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D,rtTexture); glGenerateMipmap(GL_TEXTURE_2D); drawQuadOverNumberedView(i,false); glBindTexture(GL_TEXTURE_2D,rtDepthTexture); glGenerateMipmap(GL_TEXTURE_2D); drawQuadOverNumberedView(i,true); glColorMask(1,1,1,1); //glDisable(GL_TEXTURE_2D);//disable texture to draw flat depth map instead //float falsedepth = 1.0; //glColor4f(falsedepth,falsedepth,falsedepth,falsedepth); //draw depth map //c.buildFlatDepthGLTexture();//load and bind next depth texture //drawQuadOverNumberedView(i,true); //glEnable(GL_TEXTURE_2D); //glColor4f(1.0,1.0,1.0,1.0); } glColorMask(1, 1, 1,1); allviewsfbo->Disable(); //back to drawing in main viewport glEnable(GL_DEPTH_TEST); } */ /* void setupDrawToNumberedView(int viewnum, bool isdepthview) { //glClear(GL_DEPTH_BUFFER_BIT); int rgba = ((viewnum / 4.) - int(viewnum / 4.)) * 4.; int h = int(viewnum / (tiley * 4)) * numx; int v = (int(viewnum / 4.) / ((float) tiley) - int(int(viewnum / 4.) / ((float) tiley))) * numy * tiley; glColorMask((rgba == 0), (rgba == 1), (rgba == 2), (rgba == 3)); if(!isdepthview) { glViewport(h, v, numx, numy); } else { glViewport(h, v + numy * tiley, numx, numy); //setup viewport for depthbuffer render } } void drawQuadOverNumberedView(int viewnum, bool isdepthview) { setupDrawToNumberedView(viewnum,isdepthview); float polywidth = 0.7; //arbitrary, use to correct for aspect ratio of display glBegin(GL_QUADS); glNormal3f(0.0, 0.0, 1.0); glTexCoord4f(0, 1, 0, 1); glVertex3f(-polywidth, 1, 0); glTexCoord4f(1, 1, 0, 1); glVertex3f(polywidth, 1, 0); glTexCoord4f(1, 0, 0, 1); glVertex3f(polywidth, -1, 0); glTexCoord4f(0, 0, 0, 1); glVertex3f(-polywidth, -1, 0); glEnd(); } */ AFriemann/LowCarb0 /** * @file Protein.cpp * @author see AUTHORS * @brief Protein definitions file. */ #include "Protein.hpp" Protein::Protein(const std::shared_ptr & file) : atoms(file->get_atoms()), secondary_structure_file() { this->init(); } Protein::Protein(const std::shared_ptr & protein_file, const std::shared_ptr & secondary_structure_file) : atoms(protein_file->get_atoms()), secondary_structure_file(secondary_structure_file) { this->init(); } void Protein::init(){ for (Atom const & atom : this->atoms) { if (atom.is_c_alpha()) { std::vector residuum_atoms; for(Atom const & residuum_atom : this->atoms) { if (residuum_atom.get_residuum_number() == atom.get_atom_number()) residuum_atoms.push_back(residuum_atom); } Residuum residuum(atom, residuum_atoms); this->residues.push_back(residuum); } } LOGD << "initialized Protein with " << this->atoms.size() << " atoms and " << this->residues.size() << " CA atoms."; } bool Protein::has_secondary_structure_information() const { std::vector alpha_helices = this->secondary_structure_file->get_alpha_helix_ranges(); std::vector beta_strands = this->secondary_structure_file->get_alpha_helix_ranges(); std::vector> beta_pairs = this->secondary_structure_file->get_beta_pairs(); return alpha_helices.size() != 0 || beta_strands.size() != 0 || beta_pairs.size() != 0; } bool Protein::has_secondary_structure_interaction_in_atom_pair(int atom_nr1, int atom_nr2) const { return get_secondary_structure_type_of_atom_pair(atom_nr1, atom_nr2) != NONE; } StructureType Protein::get_secondary_structure_type_of_atom_pair(int atom_nr1, int atom_nr2) const { //check alpha helices, beta strands and beta pairs size_t i; std::vector> beta_pairs = this->secondary_structure_file->get_beta_pairs(); for (i = 0; i < beta_pairs.size(); ++i){ if ((beta_pairs[i].first == atom_nr1 || beta_pairs[i].first == atom_nr2) && (beta_pairs[i].second == atom_nr1 || beta_pairs[i].second == atom_nr2)){ return BETA_PAIR; } } std::vector beta_strands = this->secondary_structure_file->get_beta_strand_ranges(); if (abs(atom_nr1 - atom_nr2) <= 3) { for (i = 0; i < beta_strands.size(); ++i){ if (beta_strands[i].start <= atom_nr1 && beta_strands[i].end >= atom_nr1 && beta_strands[i].start <= atom_nr2 && beta_strands[i].end >= atom_nr2){ return BETA_STRAND; } } } std::vector alpha_helices = this->secondary_structure_file->get_alpha_helix_ranges(); if (abs(atom_nr1 - atom_nr2) <= 4) { for (i = 0; i < alpha_helices.size(); ++i){ if (alpha_helices[i].start <= atom_nr1 && alpha_helices[i].end >= atom_nr1 && alpha_helices[i].start <= atom_nr2 && alpha_helices[i].end >= atom_nr2){ return ALPHA_HELIX; } } } return NONE; } //LCOV_EXCL_START std::vector Protein::get_atoms() const { return this->atoms; } std::vector Protein::get_residues() const { return this->residues; } std::vector> Protein::get_beta_pairs() { return this->secondary_structure_file->get_beta_pairs(); } size_t Protein::residue_count() const { return this->residues.size(); } std::vector Protein::get_alpha_helix_ranges() const { return this->secondary_structure_file->get_alpha_helix_ranges(); } std::vector Protein::get_beta_strand_ranges() const { return this->secondary_structure_file->get_beta_strand_ranges(); } //LCOV_EXCL_STOP // vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4 alexxlzhou/scone-core1-10 /* ** PerturbationController.cpp ** ** Copyright (C) 2013-2019 and contributors. All rights reserved. ** ** This file is part of SCONE. For more information, see http://scone.software. */ #include "PerturbationController.h" #include "scone/model/Model.h" #include "scone/core/string_tools.h" #include "xo/numerical/math.h" #include "scone/core/Log.h" namespace scone { PerturbationController::PerturbationController( const PropNode& props, Params& par, Model& model, const Location& target_area ) : Controller( props, par, model, target_area ), body( *FindByName( model.GetBodies(), props.get< String >( "body" ) ) ), random_seed( props.get( "random_seed", 5489 ) ), rng_( random_seed ), active_( false ), current_force(), current_moment() { INIT_PROP( props, force, Vec3::zero() ); INIT_PROP( props, moment, Vec3::zero() ); INIT_PROP( props, position_offset, Vec3::zero() ); INIT_PROP( props, interval, xo::bounds( 0, 0 ) ); INIT_PROP( props, duration, xo::bounds( 0.1, 0.1 ) ); SCONE_THROW_IF( !interval.is_null() && duration.upper > interval.lower, "Duration cannot be longer than interval" ); SCONE_ERROR_IF( !model.GetFeatures().allow_external_forces, "External forces are not enabled for this model, please add:\n\nenable_external_forces = 1" ); AddPerturbation(); // set force point, make sure it's not set yet if ( !position_offset.is_null() ) { if ( !body.GetExternalForcePoint().is_null() && !xo::equal( body.GetExternalForcePoint(), position_offset, double( xo::constantsf::ample_epsilon() ) ) ) SCONE_THROW( "Cannot apply multiple external forces at different points on one body" ); body.SetExternalForceAtPoint( Vec3::zero(), position_offset ); } } void PerturbationController::AddPerturbation() { Perturbation p; p.start = perturbations.empty() ? start_time : perturbations.back().start + rng_.uni( interval ); p.stop = p.start + rng_.uni( duration ); p.force = force; p.moment = moment; perturbations.emplace_back( p ); } bool PerturbationController::ComputeControls( Model& model, double timestamp ) { if ( !interval.is_null() && perturbations.back().start < timestamp && ( stop_time == 0.0 || timestamp < stop_time ) ) AddPerturbation(); bool active = false; auto it = std::upper_bound( perturbations.begin(), perturbations.end(), timestamp, [&]( const TimeInSeconds& t, const Perturbation& p ) { return t < p.start; } ); if ( it != perturbations.begin() ) active = ( --it )->is_active( timestamp ); if ( active != active_ ) { log::trace( timestamp, ": Changing perturbation state to ", active ); body.AddExternalForce( active ? force : -force ); body.AddExternalMoment( active ? moment : -moment ); active_ = active; } return false; } String PerturbationController::GetClassSignature() const { return stringf( "P%d", int( xo::length( force ) + xo::length( moment ) ) ); } } // ========================================================================== // SeqAn - The Library for Sequence Analysis // ========================================================================== // // Copyright (c) 2006-2018, , FU Berlin // Copyright (c) 2016-2018, & // 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 or the FU Berlin 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 KNUT REINERT OR THE FU BERLIN 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 using namespace std::literals; using namespace seqan3; // Some test struct to get the name for. namespace foo { template struct bar {}; } // namespace foo // Some types to test if reflection works. using reflection_types = ::testing::Types, foo::bar>, foo::bar>>; template class reflection : public ::testing::Test { // The corresponding list of names that should be generated. Must have the same order as `reflection_types`. inline static const std::vector names{"char", "char16_t", "char32_t", "short int", "short int", "unsigned int", "double", "const char*", "foo::bar", "foo::bar >", "foo::bar >"}; // Helper function to obtain the index of the current type `param_type` within the list of `reflection_types`. template auto type_to_index(::testing::Types const & /*tuple*/) { return 0; } template size_t type_to_index(::testing::Types const & /*tuple*/) { return 1 + type_to_index(::testing::Types{}); } public: // Public interface to query the expected name for the current test instance. std::string expected_name() { return names[type_to_index(reflection_types{})]; } }; TYPED_TEST_CASE(reflection, reflection_types); TYPED_TEST(reflection, size) { EXPECT_EQ(detail::get_display_name_size_v, this->expected_name().size()); } TYPED_TEST(reflection, name) { EXPECT_EQ(detail::get_display_name_v.string(), this->expected_name()); } namespace seqan3::detail { template struct pretty_function { static auto to_string() { return std::string{__PRETTY_FUNCTION__}; } }; } // namespace seqan3::detail // NOTE: This does not test a seqan3 library feature, but the underlying magic // of how seqan3::detail::get_display_name_v works. This is needed, because // __PRETTY_FUNCTION__ has vendor specific output which is not standardised. TEST(pretty_function, to_string) { std::string int_name = seqan3::detail::pretty_function::to_string(); #if defined(__clang__) EXPECT_EQ(int_name, "static auto seqan3::detail::pretty_function::to_string() [type = int]"); #elif defined(__GNUC__) EXPECT_EQ(int_name, "static auto seqan3::detail::pretty_function::to_string() [with type = int]"); #endif std::string foo_bar_char_name = seqan3::detail::pretty_function>::to_string(); #if defined(__clang__) EXPECT_EQ(foo_bar_char_name, "static auto seqan3::detail::pretty_function >::to_string() [type = foo::bar]"); #elif defined(__GNUC__) EXPECT_EQ(foo_bar_char_name, "static auto seqan3::detail::pretty_function::to_string() [with type = foo::bar]"); #endif } ucpu/cage #include #include #include namespace cage { namespace detail { uintPtr readLine(PointerRange &output, PointerRange input, bool streaming) { const uintPtr size = input.size(); const char *buffer = input.data(); if (size == 0) return 0; uintPtr len = 0; while (len < size && buffer[len] != '\n') len++; if (streaming && len == size) return 0; output = { buffer, buffer + len }; if (len && output[output.size() - 1] == '\r') output = { buffer, buffer + len - 1 }; return len + (len < size); // plus the new line } uintPtr readLine(String &output, PointerRange input, bool streaming) { PointerRange tmp; uintPtr res = readLine(tmp, input, streaming); output = String(tmp); // may throw return res; } } namespace { class LineReaderImpl : public LineReader { public: LineReaderImpl(const char *buff, uintPtr size) : buffer(buff), size(size) {} LineReaderImpl(MemoryBuffer &&buff) : mb(std::move(buff)), buffer(mb.data()), size(mb.size()) {} MemoryBuffer mb; const char *buffer = nullptr; uintPtr size = 0; }; } bool LineReader::readLine(PointerRange &line) { LineReaderImpl *impl = (LineReaderImpl *)this; uintPtr l = detail::readLine(line, { impl->buffer, impl->buffer + impl->size }, false); impl->buffer += l; impl->size -= l; return !!l; } bool LineReader::readLine(String &line) { LineReaderImpl *impl = (LineReaderImpl *)this; uintPtr l = detail::readLine(line, { impl->buffer, impl->buffer + impl->size }, false); impl->buffer += l; impl->size -= l; return !!l; } uintPtr LineReader::remaining() const { LineReaderImpl *impl = (LineReaderImpl*)this; return impl->size; } Holder newLineReader(PointerRange buffer) { return systemMemory().createImpl(buffer.data(), buffer.size()); } Holder newLineReader(MemoryBuffer &&buffer) { return systemMemory().createImpl(std::move(buffer)); } } 0 /* -*- mode: c++; c-basic-offset: 4; indent-tabs-mode: nil -*- this file is part of rcssserver3D Fri May 9 2003 Copyright (C) 2002,2003 Koblenz University Copyright (C) 2003 RoboCup Soccer Server 3D Maintenance Group $Id$ 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., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include "openglsystemsdl.h" #include #include #include #ifndef WIN32 #include #else #include #endif using namespace std; using namespace boost; using namespace kerosin; using namespace zeitgeist; OpenGLSystemSDL *gInputSystem; OpenGLSystemSDL::OpenGLSystemSDL() : OpenGLSystem(), mWantsToQuit(false) { } OpenGLSystemSDL::~OpenGLSystemSDL() { SDL_Quit(); } void OpenGLSystemSDL::Update() { // Our SDL event placeholder. SDL_Event event; // Grab all the events off the queue. while( SDL_PollEvent( &event ) ) { if (event.type == SDL_QUIT) mWantsToQuit = true; } } void OpenGLSystemSDL::SwapBuffers() { SDL_GL_SwapBuffers(); } bool OpenGLSystemSDL::Init() { int result = SDL_Init(SDL_INIT_VIDEO); if( result < 0 ) { GetLog()->Error() << "ERROR: (OpenGLSystemSDL) Could not init SDL." << "SDL_Init returned error " << result << "\n"; return false; } const SDL_VideoInfo* info = SDL_GetVideoInfo(); int redBits; int greenBits; int blueBits; int alphaBits; int depthBits; int stencilBits; bool doubleBuffer; bool fullScreen; int xRes, yRes; string title; bool getConfig = ( GetScript()->GetVariable("Viewport.RedBits", redBits) && GetScript()->GetVariable("Viewport.GreenBits", greenBits) && GetScript()->GetVariable("Viewport.BlueBits", blueBits) && GetScript()->GetVariable("Viewport.AlphaBits", alphaBits) && GetScript()->GetVariable("Viewport.DepthBits", depthBits) && GetScript()->GetVariable("Viewport.StencilBits", stencilBits) && GetScript()->GetVariable("Viewport.DoubleBuffer", doubleBuffer) && GetScript()->GetVariable("Viewport.FullScreen", fullScreen) && GetScript()->GetVariable("Viewport.XRes", xRes) && GetScript()->GetVariable("Viewport.YRes", yRes) && GetScript()->GetVariable("Application.Title", title) ); if (! getConfig) { GetLog()->Error() << "(OpenGLSystemSDL) error reading config from ScriptServer\n"; return false; } GetLog()->Debug() << "(OpenGLSystemSDL) bits per channel (RGB): " << redBits << " " << greenBits << " " << blueBits << "\n"; GetLog()->Debug() << "(OpenGLSystemSDL)" << " depth bits= " << depthBits << " alpha depth= " << alphaBits << " stencil depth= " << stencilBits << "\n"; GetLog()->Debug() << "(OpenGLSystemSDL)" << " doubleBuffer= " << doubleBuffer << " fullScreen= " << fullScreen << "\n"; GetLog()->Debug() << "(OpenGLSystemSDL)" << " xRes = " << xRes << " yRes = " << yRes << "\n"; SDL_GL_SetAttribute(SDL_GL_RED_SIZE, redBits); SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, greenBits); SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, blueBits); SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, alphaBits); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, depthBits); SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, stencilBits); SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, doubleBuffer ? 1:0); int flags = SDL_OPENGL; if (fullScreen) { flags |= SDL_FULLSCREEN; } SDL_Surface *screen = SDL_SetVideoMode (xRes, yRes, info->vfmt->BitsPerPixel, flags); if (screen == 0) { GetLog()->Error() << "ERROR: (OpenGLSystemSDL) SDL_SetVideoMode() failed\n"; return false; } SDL_WarpMouse(xRes/2,yRes/2); SDL_WM_SetCaption(title.c_str(), NULL); glClear(GL_COLOR_BUFFER_BIT); GetLog()->Normal() << "(OpenGLSystemSDL) Initialized OpenGL Window\n"; const unsigned char* glRenderer = glGetString(GL_RENDERER); const unsigned char* glVersion = glGetString(GL_VERSION); const unsigned char* glExtensions = glGetString(GL_EXTENSIONS); GetLog()->Debug() << "(OpenGLSystemSDL) GL_RENDERER: " << glRenderer << "\n"; GetLog()->Debug() << "(OpenGLSystemSDL) GL_VERSION: " << glVersion << "\n"; GetLog()->Debug() << "(OpenGLSystemSDL) GL_EXTENSIONS: " << glExtensions << "\n"; GetLog()->Debug() << "(OpenGLSystemSDL) GL_MAX_LIGHTS: " << GL_MAX_LIGHTS << "\n"; return true; } bool OpenGLSystemSDL::WantsToQuit() const { return mWantsToQuit; } /* Temas: Convex hull Distancia minima entre N puntos Distancia maxima entre N puntos Cosas a recordar: CW = Clockwise CCW = Counter Clockwise Recomendaria leer las funciones en el siguiente orden: 1.- solveBrute (para ver el problema original) 2.- minDist (Como obtener la distancia minima en NlogN) 3.- maxDist (Como obtener la distancia maxima en NlogN) 4.- convexHull (Como obtener la convex hull de un poligono) Notas adicionales: Use vectores para las implementaciones porque no queria modificar el arreglo original, en un concurso se vale lo que sea, no se limiten a vectores y recuerden que arreglos son mas rapidos que vectores. */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #define INF 1000000000000000000LL #define FOR(i, a, b) for (int i = int(a); i < int(b); i++) #define FORC(cont, it) \ for (decltype((cont).begin()) it = (cont).begin(); it != (cont).end(); it++) #define pb push_back using namespace std; typedef long long ll; typedef pair ii; typedef pair pdd; typedef vector vi; typedef vector vii; typedef vector vvi; // Notar que maxN puede valer 10^5, solo es 1k para probar que funcionan los // algoritmos #define maxN 1000 #define PI 3.14159265358979 struct Point { double x, y; bool operator<(const Point &r) const { return x < r.x || x == r.x && y < r.y; } }; int N; Point p[maxN]; double dist(Point &l, Point &r) { return sqrt((l.x - r.x) * (l.x - r.x) + (l.y - r.y) * (l.y - r.y)); } // Encuentra la minima y maxima distancia entre N puntos O(N^2) pdd solveBrute() { pdd ret = pdd{INF, 0}; FOR(i, 0, N) { FOR(j, i + 1, N) { double d = dist(p[i], p[j]); ret.first = min(ret.first, d); ret.second = max(ret.second, d); } } return ret; } // Regresa la distancia minima usando divide and conquer // Se le envian los puntos sorteados por x y los regresa sorteados por y // Sabemos que la distancia minima va a ser la minima entre la respuesta de // left, la respuesta de right y juntarlos. Ahora usamos la misma idea de // mergesort para mergear los puntos, esta vez ordenandolos por y, pero hacemos // un paso intermedio. Para este paso intermedio llamenos minDist a la distancia // minima de left y right. Sabemos que originalmente los teniamos ordenados en // x, asi que sabemos que los puntos de l tendran una x <= a todos los puntos de // r. Si agarramos la x mas grande en l (llamemosla mx) podemos descartar todos // los puntos con una x menor o igual a mx-minDist De igual manera podemos // descartar todos los puntos de r con una x mayor o igual a mx+minDist Pero // notamos algo, entre los puntos validos solo vamos a tener maximo 6 puntos al // mismo tiempo. Esto se debe a que si la distancia entre la minima y y la // maxima y de los puntos validos es mayor a minDist, podemos sacar la minima y. // Segunda cosa que notamos, como solo metemos puntos con distancia menor o // igual a minDist de mx y sabemos que todos los puntos de l estan a minimo una // distancia minDist (lo mismo para r) El pero caso seria asi: Supongamos que // minDist=2 y mx cruza por la columna 3 012345 (columnas) // . . . // // . . . // Otra manera de pensarlo es cual es la mayor cantidad de puntos que caben tal // que todos tienen una distancia entre ellos de al menos minDist, pero no mayor // a minDist en Y y no mayor a 2*minDist en X Estas premisas siempre se cumplen // porque si encontramos una nueva minDist la actualizamos. La respuesta a ese // problema es 6, por ende requerimos de 6*N itearciones para mergear, y por ser // divide and conquer O(N*logN) double minDDC(vector &v) { if (v.size() == 1) return INF; vector l, r; int half = v.size() / 2, mx = v[half - 1].x; FOR(i, 0, half) l.push_back(v[i]); FOR(i, half, v.size()) r.push_back(v[i]); double minDist = min(minDDC(l), minDDC(r)); int lc = 0, rc = 0, cc = 0, vl = 0; vector valids; while (lc < l.size() || rc < r.size()) { Point t; if (rc >= r.size() || lc < l.size() && l[lc].y < r[rc].y) t = l[lc++]; else t = r[rc++]; v[cc++] = t; if (fabs(t.x - mx) <= minDist) { FOR(i, vl, valids.size()) { double d = dist(valids[i], t); if (d < minDist) { minDist = d; } } valids.push_back(t); while (t.y - valids[vl].y > minDist) vl++; } } return minDist; } // Obtiene la minima distancia entre 2 puntos usando la tecnica de divide and // conquer O(NlogN) double minDist() { vector s(N); FOR(i, 0, N) s[i] = p[i]; sort(s.begin(), s.end()); double ret = minDDC(s); return ret; } // Regres el doble del area del triangulo abc (nota que si abc es CCW es // positiva y CW es negativa, si no es un triangulo, sino estan en la misma // recta los 3 puntos regresa 0) Gauss shoelace double areaTriangulo(Point &a, Point &b, Point &c) { return a.x * b.y - a.y * b.x + b.x * c.y - b.y * c.x + c.x * a.y - c.y * a.x; } // Regresa el convex hull en CCW dados N puntos (nota que el primer y ultimo // punto de la hull es el mismo punto, aparece 2 veces) Primero sortea los // puntos en X y luego itera sobre todos usando la idea de stack, primero forma // la mitad de abajo y luego la de arriba Notas de la construccion del hull: // 1) Siempre suponemos que vamos a meter a la stack el punto en el cual vamos. // 2) Antes de meter un punto a la stack hay que ver que pasa si lo //metemos, solo hay 2 opciones: 1.- El poligono seria convexo en dicho caso lo //metemos a la stack 2.- El poligono seria concavo (error, hay que sacar el //ultimo punto que metimos a la stack) y volvemos a checar // 3) Para determinar si el nuevo poligono sera concavo o convexo agarramos los // ultimos 2 puntos de la stack y el nuevo a meter // Obtenemos el area de dicho triangulo y si el area es positiva el // poligono es convexo, sino concavo. // Esto es cierto porque estamos construyendo la hull en CCW order y //por definicion 3 puntos consecutivos cualesquiera de un poligono convexo en //CCW tienen que estar en CCW. vector convexHull() { vector hull(N + 1), sorted(N); FOR(i, 0, N) sorted[i] = p[i]; sort(sorted.begin(), sorted.end()); // Construimos la lower hull // Suponemos que tenemos al menos 3 puntos y forzamos a que el punto con la // x mas peque�a (y en empate con y mas peque�a) sea parte de la hull, ya // que siempre es cierto hull[0] = sorted[0]; int hc = 1; FOR(i, 1, N) { while (hc > 1 && areaTriangulo(hull[hc - 2], hull[hc - 1], sorted[i]) <= 0) hc--; hull[hc++] = sorted[i]; } // Construimos el upper hull // Nos saltamos todos los puntos con la x mas grande, ya que al terminar el // lower hull estamos garantizados que tenemos el punto con la x mas grande // (y en empate la y mas grande) dentro de la hull Al igual que al constuir // la mitad de abajo, aqui forzamos al que sigue del mas grande a estar en // la hull, De esta manera lo que hacemos es pretender que empezamos en otra // stack desde 0, pero sin pedir memoria para 2 stacks int st = N - 2; while (sorted[st].x == sorted[N - 1].x) st--; hull[hc++] = sorted[st--]; for (int i = st; i >= 0; i--) { while (hc > 1 && areaTriangulo(hull[hc - 2], hull[hc - 1], sorted[i]) <= 0) hc--; hull[hc++] = sorted[i]; } hull.resize(hc); return hull; } // Regresa el angulo (la inclinacion de la pendiente, pero infinitamente mejor // que pendientes porque maneja cualquier valor) Nota: En caso de que el angulo // que se obtiene sea menor que el angulo previo, significa que terminamos un // ciclo sobre el poligono En dicho caso incrementamos en 2*PI hasta que sea // mayor al previo, para poder aplicar una logica sencilla en el double pointer // (ya que los angulos son ciclicos y en este caso para facilitarnos la vida no // queremos eso) double angConsecutivePoints(const vector &hull, int i, double prev) { double ang = atan2(hull[(i + 1) % hull.size()].y - hull[i].y, hull[(i + 1) % hull.size()].x - hull[i].x); while (ang < prev) ang += 2 * PI; return ang; } // Usamos la tecnica de rotating calipers con double pointers // Primero imaginemonos un circulo en vez de un poligono. // El punto mas lejano a un punto en la circumferencia del circulo esta del lado // opuesto Ahora si agarramos una linea tangente a dicho circulo y que se // intersecte con ese punto, En el punto opuesto existe una recta tangente con // la misma pendiente. Para este caso no nos interesan pendientes, asi que // usaremos angulos, diremos que la que intersecta con el punto original tiene // angulo A La que intersecta con el punto opuesto tiene angulo A+PI (en // radianes) Ahora regresemos al poligono, y elegimos un vertice V Pasa lo mismo // que con el circulo, excepto que ya no hay un unico angulo, sino ahora hay // infinitos angulos El rango de los angulos para un punto esta dado por [L,R] // Donde L es el angulo del segmento que une a V y el vertice previo en el // poligono R es el angulo del segmento entre V y el siguiente vertice cen el // poligono. Notemos que dado un rango [L,R] puede haber entre 1 y N puntos // opuestos por los cuales pasa una recta con algun angulo entre L+PI y R+PI Sin // embargo notemos que entre puntos consecutivos la R de uno se vuelve la L del // otro (en el vertice V+1 el rango seria [R,R2] Entonces podemos usar double // pointers ya que siempre vamos creciendo y una vez que pasamos un angulo no // necesitamos regresarnos, ergo O(N) Ahora bien a la implementacion: Si vamos // en el punto i obtenemos el angulo del segmento que une a i e i+1 (llamemoslo // ang) y lo comparamos con el de la r y r+1 (llamemoslo angr) Si el angulo // entre r y r+1 es menor a ang+PI, significa que r es una potencial respuesta // (punto opuesto), checamos la distancia y nos saltamos a r+1 double maxDist() { // Ya que la respuesta esta en los puntos que se encuentran sobre la convex // hull vector hull = convexHull(); int r = 1; double prev = -2 * PI, prevR = -2 * PI, ret = 0; FOR(i, 0, hull.size()) { double ang = angConsecutivePoints(hull, i, prev), angr; while (ang + PI > (angr = angConsecutivePoints(hull, r, prevR))) { ret = max(ret, dist(hull[i], hull[r])); prevR = angr; r = (r + 1) % hull.size(); } prev = ang; ret = max(ret, dist(hull[i], hull[r])); } return ret; } pdd solveFast() { return pdd{minDist(), maxDist()}; } int main() { // Algo asi es la idea de como se hace un generador de casos prueba para ver // si una solucion esta bien Suponiendo que el solucionador de bruteforce es // correcto :P FOR(i, 0, 1000) { N = rand() % maxN + 2; FOR(i, 0, N) { p[i].x = rand(); p[i].y = rand(); } if (solveBrute() != solveFast()) { // En teoria esto nunca deberia entrar porque las respuestas son // iguales cout << "ERROR" << endl; } } return 0; } game/cpp/query.cpp #include "query.h" bool Pakmen::is_game_over(GameBoard *board) { for (int i = 0; i < Pakmen::BOARD_HEIGHT; i++) { for (int j = 0; j < Pakmen::BOARD_WIDTH; j++) { if (board->board[i][j] == Pakmen::USER_CELL) return false; } } return true; } std::tuple Pakmen::find_object(Pakmen::GameBoard* board, int object) { for (int i = 0; i < Pakmen::BOARD_HEIGHT; i++) { for (int j = 0; j < Pakmen::BOARD_WIDTH; j++) { if (board->board[i][j] == object) return std::make_tuple(i, j); } } return std::make_tuple(-1, -1); } std::vector> Pakmen::find_all_objects(Pakmen::GameBoard* board, int object) { std::vector> list; for (int i = 0; i < Pakmen::BOARD_HEIGHT; i++) { for (int j = 0; j < Pakmen::BOARD_WIDTH; j++) { if (board->board[i][j] == object) list.push_back(std::make_tuple(i, j)); } } return list; } bool Pakmen::is_player_cell(Pakmen::GameBoard* board, std::tuple pos) { int x, y; std::tie (y, x) = pos; return board->board[y][x] == Pakmen::USER_CELL; } bool Pakmen::is_ghost_movable_cell(Pakmen::GameBoard* board, std::tuple pos) { int x, y; std::tie (y, x) = pos; if (x < 0 || y < 0) return false; int board_cell = board->board[y][x]; return board_cell != Pakmen::WALL_CELL; } bool Pakmen::is_movable_cell(Pakmen::GameBoard* board, std::tuple pos) { int x, y; std::tie (y, x) = pos; if (x < 0 || y < 0) return false; int board_cell = board->board[y][x]; if (board_cell == Pakmen::WALL_CELL) return false; return (board_cell != Pakmen::GHOST_CELL && board_cell != Pakmen::DUMMIE_GHOST_CELL) || board->powered != 0; } bool Pakmen::is_eatable_cell(Pakmen::GameBoard* board, std::tuple pos) { int x, y; std::tie (y, x) = pos; if (x < 0 || y < 0) { return false; } int board_cell = board->board[y][x]; if (board_cell == Pakmen::WALL_CELL){ return false; } return (board_cell == Pakmen::EATABLE_CELL || board_cell == Pakmen::POWER_CELL); } bool Pakmen::is_eatable_cherry_cell(Pakmen::GameBoard* board, std::tuple pos) { int x, y; std::tie (y, x) = pos; if (x < 0 || y < 0) { return false; } int board_cell = board->board[y][x]; if (board_cell == Pakmen::WALL_CELL){ return false; } return (board_cell == Pakmen::CHERRY_CELL); } // Copyright (c) 2017-2021, Lawrence Livermore National Security, LLC and // other Shroud Project Developers. // See the top-level COPYRIGHT file for details. // // SPDX-License-Identifier: (BSD-3-Clause) #include "namespace.hpp" static std::string last_function_called; const std::string& LastFunctionCalled() { return last_function_called; } void outer::One() { last_function_called = "outer::One"; } void One() { last_function_called = "One"; } #pragma once #include #include #include #include #include "tello/logger/logger_interface.hpp" #include "tello/native/network_interface.hpp" #include #include #include using ip_address = unsigned long; using std::unordered_map; using std::thread; using std::promise; using std::future; using tello::LoggerInterface; using tello::LoggerType; using std::shared_ptr; namespace tello { class Tello; template class UdpListener { public: UdpListener(const ConnectionData& connectionData, shared_ptr networkInterface, unordered_map& telloMapping, std::shared_mutex& telloMappingMutex, std::shared_mutex& connectionMutex, LoggerType loggerType) : _exitSignal(), _worker(thread(&UdpListener::listen, std::ref(connectionData), networkInterface, std::ref(telloMapping), std::ref(telloMappingMutex), std::ref(connectionMutex), _exitSignal.get_future(), loggerType)) { } void stop() { _exitSignal.set_value(); _worker.join(); } private: promise _exitSignal; thread _worker; static void listen(const tello::ConnectionData& connectionData, shared_ptr networkInterface, unordered_map& telloMapping, std::shared_mutex& telloMappingMutex, std::shared_mutex& connectionMutex, future exitListener, LoggerType loggerType) { bool isFirstAccessToFileDescriptor = true; while (exitListener.wait_for(std::chrono::nanoseconds(100)) == std::future_status::timeout) { connectionMutex.lock_shared(); if (connectionData._fileDescriptor == -1) { connectionMutex.unlock_shared(); continue; } else if (isFirstAccessToFileDescriptor) { LoggerInterface::info(loggerType, string("Start listen to port {}"), std::to_string(connectionData._networkData._port)); isFirstAccessToFileDescriptor = false; } NetworkResponse networkResponse = networkInterface->read(connectionData._fileDescriptor); connectionMutex.unlock_shared(); telloMappingMutex.lock_shared(); auto telloIt = telloMapping.find(networkResponse._sender._ip); if (telloIt != telloMapping.end()) { invoke(networkResponse, telloIt->second); } else if (networkResponse._length > 0) { LoggerInterface::warn(loggerType, string("Received data {0} from unknown Tello {1}"), networkResponse.response(), std::to_string(networkResponse._sender._ip)); } telloMappingMutex.unlock_shared(); } LoggerInterface::info(loggerType, string("Stop listen to port {0}"), std::to_string(connectionData._networkData._port)); } }; }not522/Competitive-Programming #pragma once #include "template.hpp" class EofValidator { public: ~EofValidator() { assert(getchar() == EOF); } } eofValidator; const static int LOWER = 1; const static int UPPER = 2; const static int DIGIT = 4; const static int SYMBOL = 8; bool isSeparator(char c) { return c == ' ' || c == '\n' || c == '\t' || c == EOF; } int readInt(int a, int b) { char c = getchar(); int64_t n; if (c == '-') { c = getchar(); assert('1' <= c && c <= '9'); n = -(c - '0'); } else { assert('0' <= c && c <= '9'); n = c - '0'; } if (n == 0) { assert(!isdigit(c = getchar())); ungetc(c, stdin); assert(a <= n && n <= b); return 0; } while (true) { c = getchar(); if (!isdigit(c)) { break; } if (n > 0) { n = n * 10 + c - '0'; } else { n = n * 10 - (c - '0'); } assert(std::numeric_limits::lowest() <= n && n <= std::numeric_limits::max()); } ungetc(c, stdin); assert(a <= n && n <= b); return n; } int64_t readLong(int64_t a, int64_t b) { char c = getchar(); __int128 n; if (c == '-') { c = getchar(); assert('1' <= c && c <= '9'); n = -(c - '0'); } else { assert('0' <= c && c <= '9'); n = c - '0'; } if (n == 0) { assert(!isdigit(c = getchar())); ungetc(c, stdin); assert(a <= n && n <= b); return 0; } while (true) { c = getchar(); if (!isdigit(c)) { break; } if (n > 0) { n = n * 10 + c - '0'; } else { n = n * 10 - (c - '0'); } assert(std::numeric_limits::lowest() <= n && n <= std::numeric_limits::max()); } ungetc(c, stdin); assert(a <= n && n <= b); return n; } std::string readString(int flag, size_t a, size_t b) { std::string s; char c; while (!isSeparator(c = getchar())) { s += c; } ungetc(c, stdin); assert(a <= s.size() && s.size() <= b); for (const auto &c : s) { assert(isgraph(c)); if (islower(c)) { assert(flag & LOWER); } else if (isupper(c)) { assert(flag & UPPER); } else if (isdigit(c)) { assert(flag & DIGIT); } else { assert(flag & SYMBOL); } } return s; } std::string readLine(size_t a, size_t b) { std::string s; char c; while ((c = getchar()) != '\n') { s += c; } ungetc(c, stdin); assert(a <= s.size() && s.size() <= b); return s; } void readSpace() { assert(getchar() == ' '); } void readEoln() { assert(getchar() == '\n'); } /** * @file HostTexture.cpp * @author <> * @date 2017.02.20 * * @brief Implementation of a general host accessible Vulkan image. */ #include "gfx/vk/textures/HostTexture.h" #include namespace vkfw_core::gfx { HostTexture::HostTexture(const LogicalDevice* device, std::string_view name, const TextureDescriptor& desc, vk::ImageLayout initialLayout, const std::vector& queueFamilyIndices) : Texture{device, name, TextureDescriptor(desc, vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent), initialLayout, queueFamilyIndices} { } HostTexture::~HostTexture() = default; HostTexture::HostTexture(const HostTexture& rhs) : Texture{rhs.CopyWithoutData(fmt::format("{}-Copy", rhs.GetName()))} { auto texSize = rhs.GetSize(); auto mipLevels = rhs.GetMipLevels(); InitializeImage(texSize, mipLevels); std::vector tmp(static_cast(texSize.x) * static_cast(texSize.y) * static_cast(texSize.z)); for (auto ml = 0U; ml < mipLevels; ++ml) { for (auto al = 0U; al < texSize.w; ++al) { rhs.DownloadData(ml, al, glm::xyz(texSize), tmp.data()); UploadData(ml, al, glm::u32vec3(0), glm::xyz(texSize), tmp.data()); } } } HostTexture& HostTexture::operator=(const HostTexture& rhs) { if (this != &rhs) { auto tmp{ rhs }; std::swap(*this, tmp); } return *this; } HostTexture::HostTexture(HostTexture&& rhs) noexcept : Texture{ std::move(rhs) } { } HostTexture& HostTexture::operator=(HostTexture&& rhs) noexcept { this->~HostTexture(); Texture::operator=(std::move(rhs)); return *this; } void HostTexture::InitializeData(const glm::u32vec4& textureSize, std::uint32_t mipLevels, const glm::u32vec4& dataSize, const void* data) { auto byData = reinterpret_cast(data); // NOLINT InitializeImage(textureSize, mipLevels); for (auto al = 0U; al < dataSize.w; ++al) { auto layerData = &byData[dataSize.x * dataSize.y * dataSize.z * al]; // NOLINT UploadData(0, al, glm::u32vec3(0), glm::xyz(dataSize), layerData); } } void HostTexture::InitializeData(const glm::u32vec4& size, std::uint32_t mipLevels, const void* data) { InitializeData(size, mipLevels, glm::u32vec4(size.x * GetDescriptor().m_bytesPP, size.y, size.z, size.w), data); } void HostTexture::UploadData(std::uint32_t mipLevel, std::uint32_t arrayLayer, const glm::u32vec3& offset, const glm::u32vec3& size, const void* data) { assert(offset.x + size.x <= GetSize().x); assert(offset.y + size.y <= GetSize().y); assert(offset.z + size.z <= GetSize().z); assert(arrayLayer < GetSize().w); assert(mipLevel < GetMipLevels()); vk::ImageSubresource subresource{ GetValidAspects(), mipLevel, arrayLayer }; auto layout = GetSubresourceLayout(subresource); GetDeviceMemory().CopyToHostMemory(0, offset, layout, size, data); } void HostTexture::DownloadData(std::uint32_t mipLevel, std::uint32_t arrayLayer, const glm::u32vec3& size, void* data) const { vk::ImageSubresource subresource{ GetValidAspects(), mipLevel, arrayLayer }; auto layout = GetSubresourceLayout(subresource); GetDeviceMemory().CopyFromHostMemory(0, glm::u32vec3(0), layout, size, data); } } Camp_1-2563/ControlFlowStatement/LoopPractice.cpp /* * AUTHOR : Hydrolyzed~ * SCHOOL : RYW * LANG : C++ * TASK : * EDITOR : VsCode * */ #include using namespace std; #define endl '\n' #define int long long void solution(){ int a; cin >> a; for(int i=1;i<=a;++i){ printf("%d ", i); } printf("\n"); int it = a; while(it>0){ printf("%d ",it); it--; } printf("\n"); it=1; do{ if(it%2==0){ printf("%d ",it); } it++; }while(it <= a); printf("\n"); for(int i=a;i>0;--i){ if(i%2==0){ printf("%d ", i); } } printf("\n"); it = 1; while(it<=a){ if(it%2==1){ printf("%d ",it); } it++; } printf("\n"); it = a; do{ if(it%2==1){ printf("%d ", it); } it--; }while(it>=1); return ; } int32_t main(){ ios::sync_with_stdio(false); cin.tie(nullptr); int t = 1; // cin >> t; for(int i=1; i<=t; ++i){ // cout << "Case #" << i << ": "; solution(); // cout << endl; } return 0; } src/lib/access/ScriptOperation.cpp #include "access/ScriptOperation.h" #include #include #include #include #include #include #include "log4cxx/logger.h" #ifdef WITH_V8 #include #endif #include #include namespace hyrise { namespace access { namespace { log4cxx::LoggerPtr _logger(log4cxx::Logger::getLogger("hyrise.access")); auto _ = QueryParser::registerPlanOperation("ScriptOperation"); } ScriptOperation::ScriptOperation() {} #ifdef WITH_V8 template v8::Local wrapAttributeVector(std::shared_ptr table, size_t internal); // This is the context data that we use in the isolate data per process. // Basically it contains a map of all available tables to the plan operation // with given keys. The key is the offset in this table. The first tables in // this list are always the input tables of the plan operation struct IsolateContextData { std::vector tables; }; template void releaseTableSharedPtr(v8::Isolate* isolate, v8::Persistent persistentObj, void* pData) { auto pspNative = reinterpret_cast*>(pData); delete pspNative; // Manually dispose of the Persistent handle persistentObj.Dispose(isolate); persistentObj.Clear(); } /// This is a helper function that frees allocated objects that were /// created using new. template void deleteAllocated(v8::Isolate* isolate, v8::Persistent persitentObj, void* data) { auto native = reinterpret_cast(data); delete native; persitentObj.Dispose(isolate); persitentObj.Clear(); } /// Helper function that wraps the current local handle in a /// persistent handle to register destructors and embedd native data v8::Persistent makePersistent(v8::Isolate* isolate, v8::Handle object, void* embedded, v8::NearDeathCallback callback) { v8::Persistent persistentObj(v8::Persistent::New(isolate, object)); persistentObj.MakeWeak(isolate, embedded, callback); return persistentObj; } v8::Handle LogMessage(const v8::Arguments& args) { v8::String::Utf8Value str(args[0]); LOG4CXX_DEBUG(_logger, *str); return v8::Undefined(); } // This function is used to read a JS file from disk into a std::string object. // // @param name The name / relative path of the file // @param suffix The suffix of the file, that defaults to ".j" std::string readScript(const std::string& name, const std::string& suffix = ".js") { FILE* file = fopen((Settings::getInstance()->getScriptPath() + "/" + name + suffix).c_str(), "rb"); if (file == nullptr) throw std::runtime_error("Could not find file " + name); fseek(file, 0, SEEK_END); int size = ftell(file); rewind(file); char* chars = new char[size + 1]; chars[size] = '\0'; for (int i = 0; i < size;) { int read = static_cast(fread(&chars[i], 1, size - i, file)); i += read; } fclose(file); std::string result(chars, size); delete[] chars; return result; } // Implementation of the helper method that allows to include other JavaScript // file read from local files and compile and run them into the VM v8::Handle Include(const v8::Arguments& args) { for (int i = 0; i < args.Length(); i++) { v8::String::Utf8Value str(args[i]); std::string js_file; try { js_file = readScript(*str); } catch (std::exception& e) { return v8::ThrowException(v8::String::New(e.what())); } if (js_file.length() > 0) { v8::Handle source = v8::String::New(js_file.c_str()); v8::Handle script = v8::Script::Compile(source); return script->Run(); } } return v8::Undefined(); } // Return the value Id for the Value given to this class, based on the type of // the argument call the right method v8::Handle TableGetValueIdForValue(const v8::Arguments& args) { v8::Isolate* isolate = v8::Isolate::GetCurrent(); v8::HandleScope handle_scope(isolate); auto val = args[1]; auto tabId = args.Length() > 2 ? args[2]->Uint32Value() : 0u; auto wrap = v8::Local::Cast(args.This()->GetInternalField(0)); void* ptr = wrap->Value(); auto tab = static_cast(ptr); if (val->IsNumber()) { auto num = val->ToNumber(); return handle_scope.Close(v8::Integer::New( tab->getValueIdForValue(args[0]->Uint32Value(), val->IntegerValue(), false, tabId).valueId)); } else { // val == string v8::String::Utf8Value u(val->ToString()); return handle_scope.Close( v8::Integer::New(tab->getValueIdForValue(args[0]->Uint32Value(), *u, false, tabId).valueId)); } } // These are the wrapped functions of the abstract table v8::Handle TableGetSize(const v8::Arguments& args) { v8::Isolate* isolate = v8::Isolate::GetCurrent(); v8::HandleScope handle_scope(isolate); auto wrap = v8::Local::Cast(args.This()->GetInternalField(0)); void* ptr = wrap->Value(); size_t value = static_cast(ptr)->size(); return handle_scope.Close(v8::Integer::New(value)); } // Implementation that returns number of columns of the table v8::Handle TableGetColumnCount(const v8::Arguments& args) { v8::Isolate* isolate = v8::Isolate::GetCurrent(); v8::HandleScope handle_scope(isolate); auto wrap = v8::Local::Cast(args.This()->GetInternalField(0)); void* ptr = wrap->Value(); size_t value = static_cast(ptr)->columnCount(); return handle_scope.Close(v8::Integer::New(value)); } // Simple Converter form std::string to v8::String struct StringToV8String { static v8::Handle New(std::string a) { return v8::String::New(a.c_str()); } }; // Templated method to allow easy wrapping of the getValue method from // the table template v8::Handle TableGetValue(const v8::Arguments& args) { v8::Isolate* isolate = v8::Isolate::GetCurrent(); v8::HandleScope handle_scope(isolate); auto wrap = v8::Local::Cast(args.This()->GetInternalField(0)); void* ptr = wrap->Value(); auto value = static_cast(ptr)->getValue(args[0]->Uint32Value(), args[1]->Uint32Value()); return handle_scope.Close(Out::New(value)); } // Helper function that checks if the object has a property set that is called // _isModifiable. This property defines if the table is modifiable or not bool IsModifiable(const v8::Local& ext) { return ext->Get(v8::String::New("_isModifiable"))->ToBoolean()->Value(); } // methods to allow easy wrapping of the setValue method from // the table v8::Handle TableSetValueInt(const v8::Arguments& args) { v8::Isolate* isolate = v8::Isolate::GetCurrent(); v8::HandleScope handle_scope(isolate); auto wrap = v8::Local::Cast(args.This()->GetInternalField(0)); if (!IsModifiable(args.This())) { return v8::ThrowException(v8::String::New("Table is not modifiable.")); } void* ptr = wrap->Value(); static_cast(ptr) ->setValue(args[0]->Uint32Value(), args[1]->Uint32Value(), args[2]->Int32Value()); return handle_scope.Close(v8::Undefined()); } v8::Handle TableSetValueFloat(const v8::Arguments& args) { v8::Isolate* isolate = v8::Isolate::GetCurrent(); v8::HandleScope handle_scope(isolate); auto wrap = v8::Local::Cast(args.This()->GetInternalField(0)); if (!IsModifiable(args.This())) { return v8::ThrowException(v8::String::New("Table is not modifiable.")); } void* ptr = wrap->Value(); static_cast(ptr)->setValue( args[0]->Uint32Value(), args[1]->Uint32Value(), v8::Local::Cast(args[2])->Value()); return handle_scope.Close(v8::Undefined()); } v8::Handle TableSetValueString(const v8::Arguments& args) { v8::Isolate* isolate = v8::Isolate::GetCurrent(); v8::HandleScope handle_scope(isolate); auto wrap = v8::Local::Cast(args.This()->GetInternalField(0)); if (!IsModifiable(args.This())) { return v8::ThrowException(v8::String::New("Table is not modifiable.")); } void* ptr = wrap->Value(); v8::String::Utf8Value u(args[2]->ToString()); static_cast(ptr) ->setValue(args[0]->Uint32Value(), args[1]->Uint32Value(), hyrise_string_t(*u)); return handle_scope.Close(v8::Undefined()); } // Implementation of the function that calls AbstractTable->resize() This // function is required for all cases where new rows are appended to the table, // if resize is not called the table will not know how many rows it should // allocate v8::Handle TableResize(const v8::Arguments& args) { v8::Isolate* isolate = v8::Isolate::GetCurrent(); v8::HandleScope handle_scope(isolate); auto wrap = v8::Local::Cast(args.This()->GetInternalField(0)); if (!IsModifiable(args.This())) { return v8::ThrowException(v8::String::New("Table is not modifiable.")); } void* ptr = wrap->Value(); auto tab = static_cast(ptr); auto casted = dynamic_cast(tab); if (casted) { casted->resize(args[0]->Uint32Value()); } else { auto casted2 = dynamic_cast*>(tab); casted2->resize(args[0]->Uint32Value()); } return handle_scope.Close(v8::Undefined()); } // Returns an object of the value id v8::Handle TableGetValueId(const v8::Arguments& args) { v8::Isolate* isolate = v8::Isolate::GetCurrent(); v8::HandleScope handle_scope(isolate); auto wrap = v8::Local::Cast(args.This()->GetInternalField(0)); void* ptr = wrap->Value(); auto vid = static_cast(ptr)->getValueId(args[0]->Uint32Value(), args[1]->Uint32Value()); v8::Handle templ = v8::Object::New(); templ->Set(v8::String::New("valueId"), v8::Integer::New(vid.valueId)); templ->Set(v8::String::New("tableId"), v8::Integer::New(vid.table)); return templ; } // Returns the value ID of the value id v8::Handle TableGetValueIdV(const v8::Arguments& args) { v8::Isolate* isolate = v8::Isolate::GetCurrent(); v8::HandleScope handle_scope(isolate); auto wrap = v8::Local::Cast(args.This()->GetInternalField(0)); void* ptr = wrap->Value(); auto vid = static_cast(ptr)->getValueId(args[0]->Uint32Value(), args[1]->Uint32Value()).valueId; return v8::Number::New(vid); } // Returns the value ID of the value id v8::Handle TableGetValueIdVRange(const v8::Arguments& args) { v8::Isolate* isolate = v8::Isolate::GetCurrent(); v8::HandleScope handle_scope(isolate); size_t col = args[0]->ToInteger()->Value(); size_t row = args[1]->ToInteger()->Value(); size_t stop = args[2]->ToInteger()->Value(); auto wrap = v8::Local::Cast(args.This()->GetInternalField(0)); void* ptr = wrap->Value(); auto tab = static_cast(ptr); auto data = v8::Object::New(); auto vids = new std::vector; for (size_t i = row, j = 0; i < stop; ++i, ++j) { auto vid = tab->getValueId(col, i).valueId; vids->push_back(vid); } // We wrap the data in a persistent object to be able to free the vids once we are done data->SetIndexedPropertiesToExternalArrayData(&(vids->at(0)), v8::kExternalUnsignedIntArray, (stop - row)); auto persistent = makePersistent(isolate, data, vids, deleteAllocated>); return persistent; } v8::Handle AttributeVectorGetSize(const v8::Arguments& args) { auto wrap = v8::Local::Cast(args.This()->GetInternalField(0)); auto ptr = static_cast(wrap->Value()); auto casted = dynamic_cast*>(ptr); size_t value = casted->size(); return v8::Integer::New(value); } v8::Handle AttributeVectorGet(const v8::Arguments& args) { auto wrap = v8::Local::Cast(args.This()->GetInternalField(0)); auto ptr = static_cast(wrap->Value()); auto casted = dynamic_cast*>(ptr); auto col = args[0]->ToInteger()->Value(); auto row = args[1]->ToInteger()->Value(); value_id_t value = casted->get(col, row); return v8::Integer::New(value); } v8::Handle AttributeVectorGetRange(const v8::Arguments& args) { v8::Isolate* isolate = v8::Isolate::GetCurrent(); v8::HandleScope handle_scope(isolate); auto wrap = v8::Local::Cast(args.This()->GetInternalField(0)); auto ptr = static_cast(wrap->Value()); auto casted = dynamic_cast*>(ptr); size_t col = args[0]->ToInteger()->Value(); size_t row = args[1]->ToInteger()->Value(); size_t stop = args[2]->ToInteger()->Value(); auto data = v8::Object::New(); auto vids = new std::vector(); for (size_t i = row; i < stop; ++i) { auto vid = casted->get(col, i); vids->push_back(vid); } // FIXME: we have to make sure that data has no longer lifespan than data data->SetIndexedPropertiesToExternalArrayData(vids->data(), v8::kExternalUnsignedIntArray, (stop - row)); return handle_scope.Close(data); } // Represents the Internal id of the table in the input list of the plan // operation v8::Handle GetInternalId(v8::Local property, const v8::AccessorInfo& info) { return v8::Local::Cast(info.Data()); } template v8::Local wrapAttributeVector(std::shared_ptr table, size_t internal) { v8::Isolate* isolate = v8::Isolate::GetCurrent(); v8::HandleScope handle_scope(isolate); v8::Handle templ = v8::ObjectTemplate::New(); templ->SetInternalFieldCount(1); templ->Set(v8::String::New("size"), v8::FunctionTemplate::New(AttributeVectorGetSize)); templ->Set(v8::String::New("get"), v8::FunctionTemplate::New(AttributeVectorGet)); templ->Set(v8::String::New("getRange"), v8::FunctionTemplate::New(AttributeVectorGetRange)); templ->SetAccessor(v8::String::New("_internalId"), GetInternalId, nullptr, v8::Integer::New(internal)); auto obj = templ->NewInstance(); obj->SetInternalField(0, v8::External::New(table.get())); return handle_scope.Close(obj); } v8::Handle TableGetAttributeVectors(const v8::Arguments& args) { v8::Isolate* isolate = v8::Isolate::GetCurrent(); v8::HandleScope handle_scope(isolate); auto wrap = v8::Local::Cast(args.This()->GetInternalField(0)); void* ptr = wrap->Value(); auto tab = static_cast(ptr); auto attr_vectors = tab->getAttributeVectors(args[0]->ToInteger()->Value()); auto result = v8::Array::New(attr_vectors.size()); size_t i = 0; for (auto& av : attr_vectors) { auto obj = v8::Object::New(); obj->Set(v8::String::New("attribute_vector"), wrapAttributeVector(av.attribute_vector, i)); obj->Set(v8::String::New("attribute_offset"), v8::Number::New(av.attribute_offset)); result->Set(i++, obj); } return result; } // Basic function to wrap an abstract table and expose the main methods, the // most important methods are to access the number of fields, size and the // valueId and values at a given set of column row coordinates template v8::Local wrapTable(std::shared_ptr table, size_t internal) { v8::Isolate* isolate = v8::Isolate::GetCurrent(); v8::HandleScope handle_scope(isolate); v8::Handle templ = v8::ObjectTemplate::New(); templ->SetInternalFieldCount(1); // Set wrapped methods templ->Set(v8::String::New("size"), v8::FunctionTemplate::New(TableGetSize)); templ->Set(v8::String::New("columnCount"), v8::FunctionTemplate::New(TableGetColumnCount)); templ->Set(v8::String::New("valueId"), v8::FunctionTemplate::New(TableGetValueId)); templ->Set(v8::String::New("valueIdV"), v8::FunctionTemplate::New(TableGetValueIdV)); templ->Set(v8::String::New("valueIdVRange"), v8::FunctionTemplate::New(TableGetValueIdVRange)); templ->Set(v8::String::New("getValueInt"), v8::FunctionTemplate::New(TableGetValue)); templ->Set(v8::String::New("getValueFloat"), v8::FunctionTemplate::New(TableGetValue)); templ->Set(v8::String::New("getValueString"), v8::FunctionTemplate::New(TableGetValue)); templ->Set(v8::String::New("setValueInt"), v8::FunctionTemplate::New(TableSetValueInt)); templ->Set(v8::String::New("setValueFloat"), v8::FunctionTemplate::New(TableSetValueFloat)); templ->Set(v8::String::New("setValueString"), v8::FunctionTemplate::New(TableSetValueString)); templ->Set(v8::String::New("resize"), v8::FunctionTemplate::New(TableResize)); templ->Set(v8::String::New("getAttributeVectors"), v8::FunctionTemplate::New(TableGetAttributeVectors)); // Map ValueIds to Values templ->Set(v8::String::New("getValueIdForValue"), v8::FunctionTemplate::New(TableGetValueIdForValue)); templ->SetAccessor(v8::String::New("_internalId"), GetInternalId, nullptr, v8::Integer::New(internal)); auto obj = templ->NewInstance(); obj->Set(v8::String::New("_isModifiable"), v8::Boolean::New(false)); obj->SetInternalField(0, v8::External::New(const_cast(table.get()))); auto persistentObj = makePersistent(isolate, obj, new std::shared_ptr(table), releaseTableSharedPtr); return handle_scope.Close(persistentObj); } // Create a pointer calculator based on the input, the function has two // arguments, first the table and second the position list v8::Handle createPointerCalculator(const v8::Arguments& args) { v8::Isolate* isolate = v8::Isolate::GetCurrent(); v8::HandleScope handle_scope(isolate); IsolateContextData* isoContext = static_cast(isolate->GetData()); // The base table auto object = v8::Local::Cast(args[0]); auto internal = object->Get(v8::String::New("_internalId"))->Uint32Value(); // Get the JS Array and build a vector auto positions = v8::Local::Cast(args[1]); auto size = positions->Length(); auto pos = new pos_list_t; for (size_t i = 0; i < size; ++i) { pos->push_back(positions->Get(v8::Integer::New(i))->Uint32Value()); } // Create a new table based from the position list and input table auto result = std::make_shared(isoContext->tables[internal], pos); isoContext->tables.push_back(result); auto obj = wrapTable(result, isoContext->tables.size() - 1); return handle_scope.Close(obj); } // Create an empty modifiable based on the input, the function has two // arguments, first the table and second the position list v8::Handle CopyStructureModifiable(const v8::Arguments& args) { v8::Isolate* isolate = v8::Isolate::GetCurrent(); v8::HandleScope handle_scope(isolate); IsolateContextData* isoContext = static_cast(isolate->GetData()); // The base table auto object = v8::Local::Cast(args[0]); auto internal = object->Get(v8::String::New("_internalId"))->Uint32Value(); // Create a new table based from the position list and input table auto result = isoContext->tables[internal]->copy_structure_modifiable(); isoContext->tables.push_back(result); auto obj = wrapTable(result, isoContext->tables.size() - 1); obj->Set(v8::String::New("_isModifiable"), v8::Boolean::New(true)); return handle_scope.Close(obj); } // Build a new table using the table builder object // // The first arguments are a list of the field names with types and names, the // second argument are the groups of attributes v8::Handle BuildTable(const v8::Arguments& args) { v8::Isolate* isolate = v8::Isolate::GetCurrent(); v8::HandleScope handle_scope(isolate); IsolateContextData* isoContext = static_cast(isolate->GetData()); if (!args[0]->IsArray() && !args[1]->IsArray()) { return v8::ThrowException(v8::String::New("Arguments must be two arrays with field decls and groups")); } auto fields = v8::Local::Cast(args[0]); auto groups = v8::Local::Cast(args[1]); TableBuilder::param_list list; for (size_t i = 0; i < fields->Length(); ++i) { auto tmp = v8::Local::Cast(fields->Get(i)); list.append().set_type(*v8::String::Utf8Value(tmp->Get(v8::String::New("type")))).set_name( *v8::String::Utf8Value(tmp->Get(v8::String::New("name")))); } for (size_t i = 0; i < groups->Length(); ++i) { auto tmp = v8::Local::Cast(groups->Get(i)); list.appendGroup(tmp->Value()); } storage::atable_ptr_t result = TableBuilder::build(list); isoContext->tables.push_back(result); auto obj = wrapTable(result, isoContext->tables.size() - 1); obj->Set(v8::String::New("_isModifiable"), v8::Boolean::New(true)); return handle_scope.Close(obj); } // Create a new vertical table based on the number of arguments in the input // list. We use the internal id of the object to lookup all tables in the // global table list. v8::Handle BuildVerticalTable(const v8::Arguments& args) { v8::Isolate* isolate = v8::Isolate::GetCurrent(); v8::HandleScope handle_scope(isolate); IsolateContextData* isoContext = static_cast(isolate->GetData()); std::vector tabs; for (int i = 0; i < args.Length(); ++i) { // The base table auto object = v8::Local::Cast(args[i]); auto internal = object->Get(v8::String::New("_internalId"))->Uint32Value(); // FIXME tabs.push_back(std::const_pointer_cast(isoContext->tables[internal])); } // Create a new table based from the position list and input table auto result = std::make_shared(tabs); isoContext->tables.push_back(result); auto obj = wrapTable(result, isoContext->tables.size() - 1); obj->Set(v8::String::New("_isModifiable"), v8::Boolean::New(false)); return handle_scope.Close(obj); } // The goal of the result helpers is to provide the necessary functions to // present a usable result. This includes basically the following // possibilities: // * create a PC with a pos List // * create a new modifiable table based on the old table meta data // * create a new modifiable table using the table builder // * create a combination as a vertical table void ScriptOperation::createResultHelpers(v8::Persistent& context) { auto global = context->Global(); global->Set(v8::String::New("createPointerCalculator"), v8::FunctionTemplate::New(createPointerCalculator)->GetFunction()); global->Set(v8::String::New("copyStructureModifiable"), v8::FunctionTemplate::New(CopyStructureModifiable)->GetFunction()); global->Set(v8::String::New("buildTable"), v8::FunctionTemplate::New(BuildTable)->GetFunction()); global->Set(v8::String::New("buildVerticalTable"), v8::FunctionTemplate::New(BuildVerticalTable)->GetFunction()); global->Set(v8::String::New("include"), v8::FunctionTemplate::New(Include)->GetFunction()); global->Set(v8::String::New("log"), v8::FunctionTemplate::New(LogMessage)->GetFunction()); } // Helper method that wraps the input of the plan operation into table objects // that provide the necessary fields in the JS world. The most important // methods are wrapped and available for callers in JS v8::Handle ScriptOperation::prepareInputs() { v8::Isolate* isolate = v8::Isolate::GetCurrent(); v8::HandleScope handle_scope(isolate); v8::Handle result = v8::Array::New(input.size()); // Fill out the values for (size_t i = 0; i < input.size(); ++i) { // FIXME evil wrapper handling for our const inputs result->Set(i, wrapTable(input.getTable(i), i)); } // Return the value through Close. return handle_scope.Close(result); } v8::Handle ScriptOperation::prepareParameters() { v8::Isolate* isolate = v8::Isolate::GetCurrent(); v8::HandleScope handle_scope(isolate); v8::Handle templ = v8::Object::New(); for (auto& k : _parameters) { const auto& kcstr = k.first.data(); const auto& vcstr = k.second.data(); templ->Set(v8::String::New(kcstr, k.first.size()), v8::String::New(vcstr, k.second.size())); } return handle_scope.Close(templ); } #endif void ScriptOperation::executePlanOperation() { #ifdef WITH_V8 v8::Isolate* isolate = v8::Isolate::GetCurrent(); if (isolate == nullptr) { isolate = v8::Isolate::New(); isolate->Enter(); } // Set the data in the isolate context auto isoContext = new IsolateContextData(); for (const auto& t : input.allOf()) { isoContext->tables.push_back(t); } isolate->SetData(isoContext); // Create a stack-allocated handle scope. v8::HandleScope handle_scope(isolate); // Create a new context. v8::Persistent context = v8::Context::New(); // Enter the created context for compiling and // running the script. v8::Context::Scope context_scope(context); // Create a string containing the JavaScript source code. auto content = readScript(_scriptName); if (content.size() == 0) { throw std::runtime_error("Script is empty, cannot run empty script: " + _scriptName); } v8::Handle source = v8::String::New(content.c_str(), content.size()); // Add Helper Functions createResultHelpers(context); // Compile the source code. { v8::TryCatch trycatch; v8::Handle script = v8::Script::Compile(source); if (script.IsEmpty()) { throw std::runtime_error(*v8::String::Utf8Value(trycatch.Exception())); } auto check = script->Run(); if (check.IsEmpty()) { throw std::runtime_error(*v8::String::Utf8Value(trycatch.Exception())); } // Once the source is compiled there must be a method available whis is // called hyrise_run_op v8::Local fun = v8::Local::Cast(context->Global()->Get(v8::String::New("hyrise_run_op"))); if (fun->IsFunction()) { // Call the plan op with the inputs we converted v8::Handle argv[] = {prepareInputs(), prepareParameters()}; auto result = v8::Local::Cast(fun->Call(fun, 2, argv)); if (result.IsEmpty()) { throw std::runtime_error(*v8::String::Utf8Value(trycatch.Exception())); } // Unwrap the data and extract the shared_ptr for the result size_t internal = result->Get(v8::String::New("_internalId"))->Uint32Value(); addResult(isoContext->tables[internal]); } } // free the isolation context data we use delete isoContext; // Dispose the persistent context. context.Dispose(isolate); #endif } std::shared_ptr ScriptOperation::parse(const Json::Value& data) { auto op = std::make_shared(); op->setScriptName(data["script"].asString()); for (const auto& v : data.getMemberNames()) { op->_parameters[v] = data[v].asString(); } return op; } } } Rombur/adamantine /* Copyright (c) 2021, the adamantine authors. * * This file is subject to the Modified BSD License and may not be distributed * without copyright and license information. Please refer to the file LICENSE * for the text and further information on this license. */ #ifndef MATERIAL_DEPOSITION_HH #define MATERIAL_DEPOSITION_HH #include #include #include #include namespace adamantine { /** * Return a vector of bounding boxes and a vector of deposition times */ template std::pair>, std::vector> create_material_deposition_boxes( boost::property_tree::ptree const &geometry_database, std::vector>> &heat_sources); /** * Read the material deposition file and return a vector of bounding boxes * and a vector of deposition times. */ template std::pair>, std::vector> read_material_deposition(boost::property_tree::ptree const &geometry_database); /** * Return a vector of bounding boxes and a vector of deposition times based on * the scan path. */ template std::pair>, std::vector> deposition_along_scan_path(boost::property_tree::ptree const &geometry_database, ScanPath const &scan_path); /** * Merge a vector of pairs of bounding boxes and a deposition times into a * single pair of vectors, sorted by deposition time. */ template std::pair>, std::vector> merge_bounding_box_lists( std::vector< std::pair>, std::vector>> bounding_box_lists); /** * Return a vector of cells to activate for each time deposition. */ template std::vector::active_cell_iterator>> get_elements_to_activate( dealii::DoFHandler const &dof_handler, std::vector> const &material_deposition_boxes); } // namespace adamantine #endif #pragma once #include "utilities/rule_of_five.hpp" #include #include #include class ImplementationBase { public: using value_t = int; ImplementationBase() = default; RULE_OF_FIVE_VIRTUAL_DESTRUCTOR_FOR_BASE(ImplementationBase); [[nodiscard]] virtual auto action(value_t value) const -> std::string = 0; }; class Implementation1 : public ImplementationBase { public: Implementation1() = default; RULE_OF_FIVE_VIRTUAL_DESTRUCTOR_FOR_BASE(Implementation1); [[nodiscard]] auto action(value_t value) const -> std::string override { return "Implementation 1 called with value '" + std::to_string(value) + "'"; } }; class Implementation2 : public ImplementationBase { public: Implementation2() = default; RULE_OF_FIVE_VIRTUAL_DESTRUCTOR_FOR_BASE(Implementation2); [[nodiscard]] auto action(value_t value) const -> std::string override { return "Implementation 2 called with value '" + std::to_string(value) + "'"; } }; class AbstractionBase { public: [[nodiscard]] virtual auto base_function() const -> std::string = 0; }; class Abstraction : public AbstractionBase { public: Abstraction(std::unique_ptr impl, const ImplementationBase::value_t val) : implementation{std::move(impl)}, value{val} {}; [[nodiscard]] auto base_function() const -> std::string override { return "Abstraction called Implementation action and got '" + implementation->action(value) + "'"; } [[nodiscard]] auto abstraction_function() const -> std::string { return "Abstraction called its own function"; } public: std::unique_ptr implementation{}; ImplementationBase::value_t value{}; }; namespace clove { id MetalShader::getFunction() const { return function; } } // license:BSD-3-Clause // copyright-holders: /*************************************************************************** version.c Version string source file for MAME. ***************************************************************************/ #define BARE_BUILD_VERSION "0.238" extern const char bare_build_version[]; extern const char build_version[]; const char bare_build_version[] = BARE_BUILD_VERSION; #if defined(GIT_VERSION) #define VERSION_TO_STRING(s) XVERSION_TO_STRING(s) #define XVERSION_TO_STRING(ver) #ver const char build_version[] = BARE_BUILD_VERSION " (" VERSION_TO_STRING(GIT_VERSION) ")"; #else const char build_version[] = BARE_BUILD_VERSION " (" __DATE__")"; #endif #define DEBUG_TYPE "live-values" #include "llvm/IR/CFG.h" #include "llvm/IR/InstIterator.h" #include "llvm/IR/Instructions.h" #include "llvm/Support/Debug.h" #include "llvm/Support/MathExtras.h" #include "llvm/Support/raw_ostream.h" #include "scaf/Utilities/LiveValues.h" namespace liberty { using namespace llvm; typedef GraphTraits GB; typedef GB::ChildIteratorType GBI; typedef GraphTraits> GR; typedef GR::ChildIteratorType GRI; LiveValues::LiveValues(const Function &fcn, bool includeFcnArgs) : numbers(), revNumbers(), OUT() { LLVM_DEBUG(errs() << "\t- Performing dataflow analysis"); // Now we are going to do some data flow analysis // in order to identify the live values at each // callsite. // We say that each use GENs a value, and that // each def KILLs a value. // // In order to efficiently operate on these // sets, we first assign unique, consecutive integers // to each value in this function, so that we may use // dense bit vectors to represent the sets. if (includeFcnArgs) { for (Function::const_arg_iterator i = fcn.arg_begin(), e = fcn.arg_end(); i != e; ++i) assignValueNumber(&*i); } for (const_inst_iterator i = inst_begin(fcn), e = inst_end(fcn); i != e; ++i) assignValueNumber(&*i); const unsigned num_blocks = NextPowerOf2(fcn.size()); const unsigned num_values = revNumbers.size(); // Next, we will compute the GEN and KILL // sets for each basic block. ValueSets GEN(num_blocks), NOT_KILL(num_blocks); for (Function::const_iterator i = fcn.begin(), e = fcn.end(); i != e; ++i) { const BasicBlock *bb = &*i; GEN[bb].resize(num_values); BitVector KILL(num_values); // visit instructions in REVERSE; BasicBlock::const_iterator j = bb->end(), f = bb->begin(); while (j != f) { --j; const Instruction *def = &*j; if (numbers.count(def)) { // Record the defs KILL.set(numbers[def]); GEN[bb].reset(numbers[def]); } // Record the uses // UNLESS it's a PHI node, // since PHIs only use the valus for some preds... if (!isa(def)) { typedef Instruction::const_op_iterator OpIt; for (OpIt k = def->op_begin(), g = def->op_end(); k != g; ++k) { const Value *use = *k; if (!numbers.count(use)) continue; GEN[bb].set(numbers[use]); } } } NOT_KILL[bb].swap(KILL); NOT_KILL[bb].flip(); } // We will repeatedly apply the following // update: // IN(bb) = UNION [succ bb] OUT // OUT(bb) = IN(bb) - KILL(bb) + GEN(bb) // This is a BACKWARDS dataflow problem. // We will visit each block at least once, and // re-visit predecessors when OUT sets change // ValueSets OUT(num_blocks); typedef std::vector Fringe; Fringe fringe; for (Function::const_iterator i = fcn.begin(), e = fcn.end(); i != e; ++i) fringe.push_back(&*i); BitVector newOUT(num_values); while (!fringe.empty()) { LLVM_DEBUG(errs() << '.'); const BasicBlock *bb = fringe.back(); fringe.pop_back(); newOUT.reset(); computeIN(bb, newOUT); newOUT &= NOT_KILL[bb]; newOUT |= GEN[bb]; if (OUT[bb] != newOUT) { for (GRI i = GR::child_begin(bb), e = GR::child_end(bb); i != e; ++i) fringe.push_back(*i); OUT[bb].swap(newOUT); } } LLVM_DEBUG(errs() << '\n'); /* errs() << "===================================================================\n\n\n"; errs() << fcn.getName() << "\n\n"; ValueList xxx; for(Function::const_iterator i=fcn.begin(), e=fcn.end(); i!=e; ++i) { const BasicBlock *bb = &*i; errs() << "Live-ins: "; xxx.clear(); findLiveInToBB(bb,xxx); for(ValueList::iterator i=xxx.begin(), e=xxx.end(); i!=e; ++i) errs() << (*i)->getName() << ", "; errs() << '\n'; errs() << *bb << '\n'; errs() << "Live-outs: "; xxx.clear(); findLiveOutFromBB(bb,xxx); for(ValueList::iterator i=xxx.begin(), e=xxx.end(); i!=e; ++i) errs() << (*i)->getName() << ", "; errs() << '\n'; } */ } void LiveValues::assignValueNumber(const Value *v) { // only bother for values with at least one use. // this makes our bit-vectors smaller. if (v->use_empty()) return; numbers[v] = revNumbers.size(); revNumbers.push_back(v); } static void translateBitVectorToValues(const BitVector &bitset, const LiveValues::Num2Value &revNumbers, LiveValues::ValueList &valueset) { valueset.reserve(bitset.count()); // translate this bit vector into a set // of values. // For each true-bit in the bit vector // <==> for each live value in the set. for (int j = bitset.find_first(); j >= 0; j = bitset.find_next(j)) { const Value *lv = revNumbers[j]; // sanity: ensure this is a definition if (isa(lv)) continue; if (const Instruction *lvi = dyn_cast(lv)) if (lvi->isTerminator()) if (!isa(lv)) continue; if (lv->getType()->isVoidTy()) continue; valueset.push_back(lv); } } void LiveValues::findLiveInToBB(const BasicBlock *bb, ValueList &liveIns) const { ValueSets::const_iterator i = OUT.find(bb); if (i == OUT.end()) return; BitVector liveins(i->second); liveins.resize(revNumbers.size()); // Be conservative, since the query // doesn't provide specific info. if (const PHINode *phi = dyn_cast(&bb->front())) for (unsigned j = 0, N = phi->getNumIncomingValues(); j < N; ++j) { const BasicBlock *pred = phi->getIncomingBlock(j); addUsesFromPHI(pred, bb, liveins); } translateBitVectorToValues(liveins, revNumbers, liveIns); } void LiveValues::findLiveValuesAcrossEdge(const BasicBlock *pred, unsigned succno, ValueList &liveIns) const { const BasicBlock *bb = pred->getTerminator()->getSuccessor(succno); ValueSets::const_iterator i = OUT.find(bb); if (i == OUT.end()) return; BitVector liveins(i->second); liveins.resize(revNumbers.size()); addUsesFromPHI(pred, bb, liveins); translateBitVectorToValues(liveins, revNumbers, liveIns); } void LiveValues::addUsesFromPHI(const BasicBlock *pred, const BasicBlock *succ, BitVector &IN) const { // Also, OR-in the uses for the PHI nodes in this // successor. for (BasicBlock::const_iterator k = succ->begin(), z = succ->end(); k != z; ++k) { const PHINode *phi = dyn_cast(&*k); if (!phi) break; const Value *use = phi->getIncomingValueForBlock(pred); assert(use); Value2Num::const_iterator l = numbers.find(use); if (l != numbers.end()) IN.set(l->second); } } void LiveValues::computeIN(const BasicBlock *bb, BitVector &IN) const { IN.resize(revNumbers.size()); for (GBI i = GB::child_begin(bb), e = GB::child_end(bb); i != e; ++i) { const BasicBlock *succ = *i; ValueSets::const_iterator j = OUT.find(succ); if (j != OUT.end()) IN |= j->second; addUsesFromPHI(bb, succ, IN); } } void LiveValues::findLiveOutFromBB(const BasicBlock *bb, ValueList &liveIns) const { BitVector inbb; computeIN(bb, inbb); translateBitVectorToValues(inbb, revNumbers, liveIns); } void LiveValues::findLiveValuesAfterInst(const Instruction *inst, // input ValueList &liveValues) const // output { const BasicBlock *bb = inst->getParent(); BitVector bitset; computeIN(bb, bitset); // visit instructions in REVERSE; BasicBlock::const_iterator j = bb->end(), f = bb->begin(); while (j != f) { --j; const Instruction *def = &*j; if (def == inst) break; Value2Num::const_iterator i = numbers.find(def); if (i != numbers.end()) { // Record the defs bitset.reset(i->second); // Record the uses typedef Instruction::const_op_iterator OpIt; for (OpIt k = def->op_begin(), g = def->op_end(); k != g; ++k) { const Value *use = *k; Value2Num::const_iterator i = numbers.find(use); if (i == numbers.end()) continue; bitset.set(i->second); } } } translateBitVectorToValues(bitset, revNumbers, liveValues); } } // namespace liberty 1-10 /* =========================================================================== Doom 3 GPL Source Code Copyright (C) 1999-2011 id Software LLC, a ZeniMax Media company. Copyright (C) 2012 dhewg (dhewm3) Copyright (C) 2012-2014 Copyright (C) 2013 This file is part of the Doom 3 GPL Source Code ("Doom 3 Source Code"). Doom 3 Source Code 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. Doom 3 Source 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 for more details. You should have received a copy of the GNU General Public License along with Doom 3 Source Code. If not, see . In addition, the Doom 3 Source Code is also subject to certain additional terms. You should have received a copy of these additional terms immediately following the terms and conditions of the GNU General Public License which accompanied the Doom 3 Source Code. If not, please request a copy in writing from id Software at the address below. If you have questions concerning this license or the applicable additional terms, you may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA. =========================================================================== */ #include "../../idlib/precompiled.h" // DG: SDL.h somehow needs the following functions, so #undef those silly // "don't use" #defines from Str.h #undef strncmp #undef strcasecmp #undef vsnprintf // DG end #include #include "renderer/tr_local.h" #include "sdl_local.h" idCVar in_nograb( "in_nograb", "0", CVAR_SYSTEM | CVAR_NOCHEAT, "prevents input grabbing" ); // RB: FIXME this shit. We need the OpenGL alpha channel for advanced rendering effects idCVar r_waylandcompat( "r_waylandcompat", "0", CVAR_SYSTEM | CVAR_NOCHEAT | CVAR_ARCHIVE, "wayland compatible framebuffer" ); // RB: only relevant if using SDL 2.0 #if defined(__APPLE__) // only core profile is supported on OS X idCVar r_useOpenGL32( "r_useOpenGL32", "2", CVAR_INTEGER, "0 = OpenGL 3.x, 1 = OpenGL 3.2 compatibility profile, 2 = OpenGL 3.2 core profile", 0, 2 ); #elif defined(__linux__) // Linux open source drivers suck idCVar r_useOpenGL32( "r_useOpenGL32", "0", CVAR_INTEGER, "0 = OpenGL 3.x, 1 = OpenGL 3.2 compatibility profile, 2 = OpenGL 3.2 core profile", 0, 2 ); #else idCVar r_useOpenGL32( "r_useOpenGL32", "1", CVAR_INTEGER, "0 = OpenGL 3.x, 1 = OpenGL 3.2 compatibility profile, 2 = OpenGL 3.2 core profile", 0, 2 ); #endif // RB end static bool grabbed = false; #if SDL_VERSION_ATLEAST(2, 0, 0) static SDL_Window* window = NULL; static SDL_GLContext context = NULL; #else static SDL_Surface* window = NULL; #define SDL_WINDOW_OPENGL SDL_OPENGL #define SDL_WINDOW_FULLSCREEN SDL_FULLSCREEN #define SDL_WINDOW_RESIZABLE SDL_RESIZABLE #endif /* =================== GLimp_PreInit R_GetModeListForDisplay is called before GLimp_Init(), but SDL needs SDL_Init() first. So do that in GLimp_PreInit() Calling that function more than once doesn't make a difference =================== */ void GLimp_PreInit() // DG: added this function for SDL compatibility { if( !SDL_WasInit( SDL_INIT_VIDEO ) ) { if( SDL_Init( SDL_INIT_VIDEO ) ) common->Error( "Error while initializing SDL: %s", SDL_GetError() ); } } /* =================== GLimp_Init =================== */ bool GLimp_Init( glimpParms_t parms ) { common->Printf( "Initializing OpenGL subsystem\n" ); GLimp_PreInit(); // DG: make sure SDL is initialized // DG: make window resizable Uint32 flags = SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE; // DG end if( parms.fullScreen ) flags |= SDL_WINDOW_FULLSCREEN; int colorbits = 24; int depthbits = 24; int stencilbits = 8; for( int i = 0; i < 16; i++ ) { // 0 - default // 1 - minus colorbits // 2 - minus depthbits // 3 - minus stencil if( ( i % 4 ) == 0 && i ) { // one pass, reduce switch( i / 4 ) { case 2 : if( colorbits == 24 ) colorbits = 16; break; case 1 : if( depthbits == 24 ) depthbits = 16; else if( depthbits == 16 ) depthbits = 8; case 3 : if( stencilbits == 24 ) stencilbits = 16; else if( stencilbits == 16 ) stencilbits = 8; } } int tcolorbits = colorbits; int tdepthbits = depthbits; int tstencilbits = stencilbits; if( ( i % 4 ) == 3 ) { // reduce colorbits if( tcolorbits == 24 ) tcolorbits = 16; } if( ( i % 4 ) == 2 ) { // reduce depthbits if( tdepthbits == 24 ) tdepthbits = 16; else if( tdepthbits == 16 ) tdepthbits = 8; } if( ( i % 4 ) == 1 ) { // reduce stencilbits if( tstencilbits == 24 ) tstencilbits = 16; else if( tstencilbits == 16 ) tstencilbits = 8; else tstencilbits = 0; } int channelcolorbits = 4; if( tcolorbits == 24 ) channelcolorbits = 8; SDL_GL_SetAttribute( SDL_GL_RED_SIZE, channelcolorbits ); SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE, channelcolorbits ); SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE, channelcolorbits ); SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 ); SDL_GL_SetAttribute( SDL_GL_DEPTH_SIZE, tdepthbits ); SDL_GL_SetAttribute( SDL_GL_STENCIL_SIZE, tstencilbits ); if( r_waylandcompat.GetBool() ) SDL_GL_SetAttribute( SDL_GL_ALPHA_SIZE, 0 ); else SDL_GL_SetAttribute( SDL_GL_ALPHA_SIZE, channelcolorbits ); SDL_GL_SetAttribute( SDL_GL_STEREO, parms.stereo ? 1 : 0 ); SDL_GL_SetAttribute( SDL_GL_MULTISAMPLEBUFFERS, parms.multiSamples ? 1 : 0 ); SDL_GL_SetAttribute( SDL_GL_MULTISAMPLESAMPLES, parms.multiSamples ); #if SDL_VERSION_ATLEAST(2, 0, 0) // RB begin if( r_useOpenGL32.GetInteger() > 0 ) { glConfig.driverType = GLDRV_OPENGL32_COMPATIBILITY_PROFILE; SDL_GL_SetAttribute( SDL_GL_CONTEXT_MAJOR_VERSION, 3 ); SDL_GL_SetAttribute( SDL_GL_CONTEXT_MINOR_VERSION, 2 ); if( r_debugContext.GetBool() ) { SDL_GL_SetAttribute( SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_DEBUG_FLAG ); } } if( r_useOpenGL32.GetInteger() > 1 ) { glConfig.driverType = GLDRV_OPENGL32_CORE_PROFILE; SDL_GL_SetAttribute( SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE ); } // RB end // DG: set display num for fullscreen int windowPos = SDL_WINDOWPOS_UNDEFINED; if( parms.fullScreen > 0 ) { if( parms.fullScreen > SDL_GetNumVideoDisplays() ) { common->Warning( "Couldn't set display to num %i because we only have %i displays", parms.fullScreen, SDL_GetNumVideoDisplays() ); } else { // -1 because SDL starts counting displays at 0, while parms.fullScreen starts at 1 windowPos = SDL_WINDOWPOS_UNDEFINED_DISPLAY( ( parms.fullScreen - 1 ) ); } } // TODO: if parms.fullScreen == -1 there should be a borderless window spanning multiple displays /* * NOTE that this implicitly handles parms.fullScreen == -2 (from r_fullscreen -2) meaning * "do fullscreen, but I don't care on what monitor", at least on my box it's the monitor with * the mouse cursor. */ window = SDL_CreateWindow( GAME_NAME, windowPos, windowPos, parms.width, parms.height, flags ); // DG end context = SDL_GL_CreateContext( window ); if( !window ) { common->DPrintf( "Couldn't set GL mode %d/%d/%d: %s", channelcolorbits, tdepthbits, tstencilbits, SDL_GetError() ); continue; } if( SDL_GL_SetSwapInterval( r_swapInterval.GetInteger() ) < 0 ) common->Warning( "SDL_GL_SWAP_CONTROL not supported" ); // RB begin SDL_GetWindowSize( window, &glConfig.nativeScreenWidth, &glConfig.nativeScreenHeight ); // RB end glConfig.isFullscreen = ( SDL_GetWindowFlags( window ) & SDL_WINDOW_FULLSCREEN ) == SDL_WINDOW_FULLSCREEN; #else glConfig.driverType = GLDRV_OPENGL3X; SDL_WM_SetCaption( GAME_NAME, GAME_NAME ); if( SDL_GL_SetAttribute( SDL_GL_SWAP_CONTROL, r_swapInterval.GetInteger() ) < 0 ) common->Warning( "SDL_GL_SWAP_CONTROL not supported" ); window = SDL_SetVideoMode( parms.width, parms.height, colorbits, flags ); if( !window ) { common->DPrintf( "Couldn't set GL mode %d/%d/%d: %s", channelcolorbits, tdepthbits, tstencilbits, SDL_GetError() ); continue; } glConfig.nativeScreenWidth = window->w; glConfig.nativeScreenHeight = window->h; glConfig.isFullscreen = ( window->flags & SDL_FULLSCREEN ) == SDL_FULLSCREEN; #endif common->Printf( "Using %d color bits, %d depth, %d stencil display\n", channelcolorbits, tdepthbits, tstencilbits ); glConfig.colorBits = tcolorbits; glConfig.depthBits = tdepthbits; glConfig.stencilBits = tstencilbits; // RB begin glConfig.displayFrequency = 60; glConfig.isStereoPixelFormat = parms.stereo; glConfig.multisamples = parms.multiSamples; glConfig.pixelAspect = 1.0f; // FIXME: some monitor modes may be distorted // should side-by-side stereo modes be consider aspect 0.5? // RB end break; } if( !window ) { common->Printf( "No usable GL mode found: %s", SDL_GetError() ); return false; } #ifdef __APPLE__ glewExperimental = GL_TRUE; #endif GLenum glewResult = glewInit(); if( GLEW_OK != glewResult ) { // glewInit failed, something is seriously wrong common->Printf( "^3GLimp_Init() - GLEW could not load OpenGL subsystem: %s", glewGetErrorString( glewResult ) ); } else { common->Printf( "Using GLEW %s\n", glewGetString( GLEW_VERSION ) ); } // DG: disable cursor, we have two cursors in menu (because mouse isn't grabbed in menu) SDL_ShowCursor( SDL_DISABLE ); // DG end return true; } /* =================== Helper functions for GLimp_SetScreenParms() =================== */ #if SDL_VERSION_ATLEAST(2, 0, 0) // SDL1 doesn't support multiple displays, so the source is much shorter and doesn't need separate functions // makes sure the window will be full-screened on the right display and returns the SDL display index static int ScreenParmsHandleDisplayIndex( glimpParms_t parms ) { int displayIdx; if( parms.fullScreen > 0 ) { displayIdx = parms.fullScreen - 1; // first display for SDL is 0, in parms it's 1 } else // -2 == use current display { displayIdx = SDL_GetWindowDisplayIndex( window ); if( displayIdx < 0 ) // for some reason the display for the window couldn't be detected displayIdx = 0; } if( parms.fullScreen > SDL_GetNumVideoDisplays() ) { common->Warning( "Can't set fullscreen mode to display number %i, because SDL2 only knows about %i displays!", parms.fullScreen, SDL_GetNumVideoDisplays() ); return -1; } if( parms.fullScreen != glConfig.isFullscreen ) { // we have to switch to another display if( glConfig.isFullscreen ) { // if we're already in fullscreen mode but want to switch to another monitor // we have to go to windowed mode first to move the window.. SDL-oddity. SDL_SetWindowFullscreen( window, SDL_FALSE ); } // select display ; SDL_WINDOWPOS_UNDEFINED_DISPLAY() doesn't work. int x = SDL_WINDOWPOS_CENTERED_DISPLAY( displayIdx ); // move window to the center of selected display SDL_SetWindowPosition( window, x, x ); } return displayIdx; } static bool SetScreenParmsFullscreen( glimpParms_t parms ) { SDL_DisplayMode m = {0}; int displayIdx = ScreenParmsHandleDisplayIndex( parms ); if( displayIdx < 0 ) return false; // get current mode of display the window should be full-screened on SDL_GetCurrentDisplayMode( displayIdx, &m ); // change settings in that display mode according to parms // FIXME: check if refreshrate, width and height are supported? // m.refresh_rate = parms.displayHz; m.w = parms.width; m.h = parms.height; // set that displaymode if( SDL_SetWindowDisplayMode( window, &m ) < 0 ) { common->Warning( "Couldn't set window mode for fullscreen, reason: %s", SDL_GetError() ); return false; } // if we're currently not in fullscreen mode, we need to switch to fullscreen if( !( SDL_GetWindowFlags( window ) & SDL_WINDOW_FULLSCREEN ) ) { if( SDL_SetWindowFullscreen( window, SDL_TRUE ) < 0 ) { common->Warning( "Couldn't switch to fullscreen mode, reason: %s!", SDL_GetError() ); return false; } } return true; } static bool SetScreenParmsWindowed( glimpParms_t parms ) { SDL_SetWindowSize( window, parms.width, parms.height ); SDL_SetWindowPosition( window, parms.x, parms.y ); // if we're currently in fullscreen mode, we need to disable that if( SDL_GetWindowFlags( window ) & SDL_WINDOW_FULLSCREEN ) { if( SDL_SetWindowFullscreen( window, SDL_FALSE ) < 0 ) { common->Warning( "Couldn't switch to windowed mode, reason: %s!", SDL_GetError() ); return false; } } return true; } #endif // SDL_VERSION_ATLEAST(2, 0, 0) /* =================== GLimp_SetScreenParms =================== */ bool GLimp_SetScreenParms( glimpParms_t parms ) { #if SDL_VERSION_ATLEAST(2, 0, 0) if( parms.fullScreen > 0 || parms.fullScreen == -2 ) { if( !SetScreenParmsFullscreen( parms ) ) return false; } else if( parms.fullScreen == 0 ) // windowed mode { if( !SetScreenParmsWindowed( parms ) ) return false; } else { common->Warning( "GLimp_SetScreenParms: fullScreen -1 (borderless window for multiple displays) currently unsupported!" ); return false; } #else // SDL 1.2 - so much shorter, but doesn't handle multiple displays SDL_Surface* s = SDL_GetVideoSurface(); if( s == NULL ) { common->Warning( "GLimp_SetScreenParms: Couldn't get video information, reason: %s", SDL_GetError() ); return false; } int bitsperpixel = 24; if( s->format ) bitsperpixel = s->format->BitsPerPixel; Uint32 flags = s->flags; if( parms.fullScreen ) flags |= SDL_FULLSCREEN; else flags &= ~SDL_FULLSCREEN; s = SDL_SetVideoMode( parms.width, parms.height, bitsperpixel, flags ); if( s == NULL ) { common->Warning( "GLimp_SetScreenParms: Couldn't set video information, reason: %s", SDL_GetError() ); return false; } #endif // SDL_VERSION_ATLEAST(2, 0, 0) // Note: the following stuff would also work with SDL1.2 SDL_GL_SetAttribute( SDL_GL_STEREO, parms.stereo ? 1 : 0 ); SDL_GL_SetAttribute( SDL_GL_MULTISAMPLEBUFFERS, parms.multiSamples ? 1 : 0 ); SDL_GL_SetAttribute( SDL_GL_MULTISAMPLESAMPLES, parms.multiSamples ); glConfig.isFullscreen = parms.fullScreen; glConfig.isStereoPixelFormat = parms.stereo; glConfig.nativeScreenWidth = parms.width; glConfig.nativeScreenHeight = parms.height; glConfig.displayFrequency = parms.displayHz; glConfig.multisamples = parms.multiSamples; return true; } /* =================== GLimp_Shutdown =================== */ void GLimp_Shutdown() { common->Printf( "Shutting down OpenGL subsystem\n" ); #if SDL_VERSION_ATLEAST(2, 0, 0) if( context ) { SDL_GL_DeleteContext( context ); context = NULL; } if( window ) { SDL_DestroyWindow( window ); window = NULL; } #endif } /* =================== GLimp_SwapBuffers =================== */ void GLimp_SwapBuffers() { #if SDL_VERSION_ATLEAST(2, 0, 0) SDL_GL_SwapWindow( window ); #else SDL_GL_SwapBuffers(); #endif } /* ================= GLimp_SetGamma ================= */ void GLimp_SetGamma( unsigned short red[256], unsigned short green[256], unsigned short blue[256] ) { if( !window ) { common->Warning( "GLimp_SetGamma called without window" ); return; } #if SDL_VERSION_ATLEAST(2, 0, 0) if( SDL_SetWindowGammaRamp( window, red, green, blue ) ) #else if( SDL_SetGammaRamp( red, green, blue ) ) #endif common->Warning( "Couldn't set gamma ramp: %s", SDL_GetError() ); } /* =================== GLimp_ExtensionPointer =================== */ /* GLExtension_t GLimp_ExtensionPointer(const char *name) { assert(SDL_WasInit(SDL_INIT_VIDEO)); return (GLExtension_t)SDL_GL_GetProcAddress(name); } */ void GLimp_GrabInput( int flags ) { bool grab = flags & GRAB_ENABLE; if( grab && ( flags & GRAB_REENABLE ) ) grab = false; if( flags & GRAB_SETSTATE ) grabbed = grab; if( in_nograb.GetBool() ) grab = false; if( !window ) { common->Warning( "GLimp_GrabInput called without window" ); return; } #if SDL_VERSION_ATLEAST(2, 0, 0) // DG: disabling the cursor is now done once in GLimp_Init() because it should always be disabled // DG: check for GRAB_ENABLE instead of GRAB_HIDECURSOR because we always wanna hide it SDL_SetRelativeMouseMode( flags & GRAB_ENABLE ? SDL_TRUE : SDL_FALSE ); SDL_SetWindowGrab( window, grab ? SDL_TRUE : SDL_FALSE ); #else // DG end SDL_WM_GrabInput( grab ? SDL_GRAB_ON : SDL_GRAB_OFF ); #endif } /* ==================== DumpAllDisplayDevices ==================== */ void DumpAllDisplayDevices() { common->DPrintf( "TODO: DumpAllDisplayDevices\n" ); } class idSort_VidMode : public idSort_Quick< vidMode_t, idSort_VidMode > { public: int Compare( const vidMode_t& a, const vidMode_t& b ) const { int wd = a.width - b.width; int hd = a.height - b.height; int fd = a.displayHz - b.displayHz; return ( hd != 0 ) ? hd : ( wd != 0 ) ? wd : fd; } }; // RB: resolutions supported by XreaL static void FillStaticVidModes( idList& modeList ) { modeList.AddUnique( vidMode_t( 320, 240, 60 ) ); modeList.AddUnique( vidMode_t( 400, 300, 60 ) ); modeList.AddUnique( vidMode_t( 512, 384, 60 ) ); modeList.AddUnique( vidMode_t( 640, 480, 60 ) ); modeList.AddUnique( vidMode_t( 800, 600, 60 ) ); modeList.AddUnique( vidMode_t( 960, 720, 60 ) ); modeList.AddUnique( vidMode_t( 1024, 768, 60 ) ); modeList.AddUnique( vidMode_t( 1152, 864, 60 ) ); modeList.AddUnique( vidMode_t( 1280, 720, 60 ) ); modeList.AddUnique( vidMode_t( 1280, 768, 60 ) ); modeList.AddUnique( vidMode_t( 1280, 800, 60 ) ); modeList.AddUnique( vidMode_t( 1280, 1024, 60 ) ); modeList.AddUnique( vidMode_t( 1360, 768, 60 ) ); modeList.AddUnique( vidMode_t( 1440, 900, 60 ) ); modeList.AddUnique( vidMode_t( 1680, 1050, 60 ) ); modeList.AddUnique( vidMode_t( 1600, 1200, 60 ) ); modeList.AddUnique( vidMode_t( 1920, 1080, 60 ) ); modeList.AddUnique( vidMode_t( 1920, 1200, 60 ) ); modeList.AddUnique( vidMode_t( 2048, 1536, 60 ) ); modeList.AddUnique( vidMode_t( 2560, 1600, 60 ) ); modeList.SortWithTemplate( idSort_VidMode() ); } /* ==================== R_GetModeListForDisplay ==================== */ bool R_GetModeListForDisplay( const int requestedDisplayNum, idList& modeList ) { assert( requestedDisplayNum >= 0 ); modeList.Clear(); #if SDL_VERSION_ATLEAST(2, 0, 0) // DG: SDL2 implementation if( requestedDisplayNum >= SDL_GetNumVideoDisplays() ) { // requested invalid displaynum return false; } int numModes = SDL_GetNumDisplayModes( requestedDisplayNum ); if( numModes > 0 ) { for( int i = 0; i < numModes; i++ ) { SDL_DisplayMode m; int ret = SDL_GetDisplayMode( requestedDisplayNum, i, &m ); if( ret != 0 ) { common->Warning( "Can't get video mode no %i, because of %s\n", i, SDL_GetError() ); continue; } vidMode_t mode; mode.width = m.w; mode.height = m.h; mode.displayHz = m.refresh_rate ? m.refresh_rate : 60; // default to 60 if unknown (0) modeList.AddUnique( mode ); } if( modeList.Num() < 1 ) { common->Warning( "Couldn't get a single video mode for display %i, using default ones..!\n", requestedDisplayNum ); FillStaticVidModes( modeList ); } // sort with lowest resolution first modeList.SortWithTemplate( idSort_VidMode() ); } else { common->Warning( "Can't get Video Info, using default modes...\n" ); if( numModes < 0 ) { common->Warning( "Reason was: %s\n", SDL_GetError() ); } FillStaticVidModes( modeList ); } return true; // DG end #else // SDL 1 // DG: SDL1 only knows of one display - some functions rely on // R_GetModeListForDisplay() returning false for invalid displaynum to iterate all displays if( requestedDisplayNum >= 1 ) { return false; } // DG end const SDL_VideoInfo* videoInfo = SDL_GetVideoInfo(); if( videoInfo == NULL ) { // DG: yes, this can actually fail, e.g. if SDL_Init( SDL_INIT_VIDEO ) wasn't called common->Warning( "Can't get Video Info, using default modes...\n" ); FillStaticVidModes( modeList ); return true; } SDL_Rect** modes = SDL_ListModes( videoInfo->vfmt, SDL_OPENGL | SDL_FULLSCREEN ); if( !modes ) { common->Warning( "Can't get list of available modes, using default ones...\n" ); FillStaticVidModes( modeList ); return true; } if( modes == ( SDL_Rect** ) - 1 ) { common->Printf( "Display supports any resolution\n" ); FillStaticVidModes( modeList ); return true; } int numModes; for( numModes = 0; modes[numModes]; numModes++ ); if( numModes > 1 ) { for( int i = 0; i < numModes; i++ ) { vidMode_t mode; mode.width = modes[i]->w; mode.height = modes[i]->h; mode.displayHz = 60; // FIXME; modeList.AddUnique( mode ); } // sort with lowest resolution first modeList.SortWithTemplate( idSort_VidMode() ); return true; } return false; #endif } #include "acc-lite.h" 1-10 /* * Copyright (c) 2001-2008 * DecisionSoft Limited. All rights reserved. * Copyright (c) 2004-2008 * Oracle. 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. * * $Id$ */ #ifndef _RESULTBUFFER_HPP #define _RESULTBUFFER_HPP #include #include /** A reference counting wrapper for the result buffer */ class XQILLA_API ResultBuffer { public: ResultBuffer(const Result &result, unsigned int readCount = ResultBufferImpl::UNLIMITED_COUNT); ResultBuffer(const Item::Ptr &item, unsigned int readCount = ResultBufferImpl::UNLIMITED_COUNT); ResultBuffer(ResultBufferImpl *impl); /// Creates a result that returns the same items as the one used to construct this buffer Result createResult(); bool isNull() const { return _impl.isNull(); } private: ResultBufferImpl::Ptr _impl; }; #endif #ifndef SERVICES_SPI_MULTIPLE_ACCESS_HPP #define SERVICES_SPI_MULTIPLE_ACCESS_HPP #include "hal/interfaces/Spi.hpp" #include "infra/event/ClaimableResource.hpp" #include "infra/util/AutoResetFunction.hpp" #ifndef SERVICES_SPI_MULTIPLE_ACCESS_FUNCTION_EXTRA_SIZE //TICS !POR#021 #define SERVICES_SPI_MULTIPLE_ACCESS_FUNCTION_EXTRA_SIZE (INFRA_DEFAULT_FUNCTION_EXTRA_SIZE + (7 * sizeof(void*))) #endif namespace services { class SpiMultipleAccessMaster //TICS !OOP#013 : public hal::SpiMaster , public infra::ClaimableResource { public: explicit SpiMultipleAccessMaster(hal::SpiMaster& master); virtual void SendAndReceive(infra::ConstByteRange sendData, infra::ByteRange receiveData, hal::SpiAction nextAction, const infra::Function& onDone) override; virtual void SetChipSelectConfigurator(hal::ChipSelectConfigurator& configurator) override; virtual void SetCommunicationConfigurator(hal::CommunicationConfigurator& configurator) override; virtual void ResetCommunicationConfigurator() override; private: hal::SpiMaster& master; hal::CommunicationConfigurator* communicationConfigurator = nullptr; }; class SpiMultipleAccess : public hal::SpiMaster , private hal::ChipSelectConfigurator { public: explicit SpiMultipleAccess(SpiMultipleAccessMaster& master); virtual void SendAndReceive(infra::ConstByteRange sendData, infra::ByteRange receiveData, hal::SpiAction nextAction, const infra::Function& onDone) override; virtual void SetChipSelectConfigurator(hal::ChipSelectConfigurator& configurator) override; virtual void SetCommunicationConfigurator(hal::CommunicationConfigurator& configurator) override; virtual void ResetCommunicationConfigurator() override; private: virtual void StartSession() override; virtual void EndSession() override; void SendAndReceiveOnClaimed(infra::ConstByteRange sendData, infra::ByteRange receiveData, hal::SpiAction nextAction, const infra::Function& onDone); private: SpiMultipleAccessMaster& master; infra::ClaimableResource::Claimer::WithSize claimer; hal::ChipSelectConfigurator* chipSelectConfigurator = nullptr; hal::CommunicationConfigurator* communicationConfigurator = nullptr; }; } #endif src/util.cpp #include namespace sortnet { double FloatPrecision(double v, double p) { return (floor((v * pow(10, p) + 0.5)) / pow(10, p)); } } // namespace sortnet/** * @file libsvm_parser_test.cpp * @author */ #include "bandit/bandit.h" #include "meta/io/libsvm_parser.h" using namespace bandit; using namespace snowhouse; using namespace meta; go_bandit([]() { describe("[libsvm-parser]", []() { it("should parse lines with class labels", []() { auto same = {"a 12:2e-3 15:4.01 99:22 122:1", "a 12:2e-3 15:4.01 99:22 122:1 "}; const double delta = 0.000001; for (auto& text : same) { AssertThat(io::libsvm_parser::label(text), Equals(class_label{"a"})); auto counts = io::libsvm_parser::counts(text); AssertThat(counts.size(), Equals(std::size_t{4})); AssertThat(counts[0].first, Equals(11ul)); AssertThat(counts[0].second, EqualsWithDelta(2e-3, delta)); AssertThat(counts[1].first, Equals(14ul)); AssertThat(counts[1].second, EqualsWithDelta(4.01, delta)); AssertThat(counts[2].first, Equals(98ul)); AssertThat(counts[2].second, EqualsWithDelta(22.0, delta)); AssertThat(counts[3].first, Equals(121ul)); AssertThat(counts[3].second, EqualsWithDelta(1.0, delta)); } }); it("should parse lines without class labels", []() { auto same = {"1:2e-3 2:4.01 3:22 13:1", "1:2e-3 2:4.01 3:22 13:1 "}; const double delta = 0.000001; for (auto& text : same) { auto counts = io::libsvm_parser::counts(text, false); AssertThat(counts.size(), Equals(std::size_t{4})); AssertThat(counts[0].first, Equals(0ul)); AssertThat(counts[0].second, EqualsWithDelta(2e-3, delta)); AssertThat(counts[1].first, Equals(1ul)); AssertThat(counts[1].second, EqualsWithDelta(4.01, delta)); AssertThat(counts[2].first, Equals(2ul)); AssertThat(counts[2].second, EqualsWithDelta(22.0, delta)); AssertThat(counts[3].first, Equals(12ul)); AssertThat(counts[3].second, EqualsWithDelta(1.0, delta)); } }); it("should throw an exception if missing labels", []() { AssertThrows(io::libsvm_parser::libsvm_parser_exception, io::libsvm_parser::label(" missing")); }); it("should throw an exception if a line has bad count data", []() { using exception = io::libsvm_parser::libsvm_parser_exception; using namespace io::libsvm_parser; AssertThrows(exception, counts("")); AssertThrows(exception, counts("lis:uvfs agi uy:")); AssertThrows(exception, counts("label :9 5:5")); AssertThrows(exception, counts("label 9: 5:5")); AssertThrows(exception, counts("label : :::")); AssertThrows(exception, counts("label 9:9 fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b")); AssertThrows(exception, counts("label 5:")); }); }); }); TheInterventionCentre/NorMIT-Plan-App /*=auto========================================================================= Portions (c) Copyright 2005 Brigham and Women's Hospital (BWH) All Rights Reserved. See COPYRIGHT.txt or http://www.slicer.org/copyright/copyright.txt for details. Program: 3D Slicer Module: $RCSfile: vtkMRMLVolumeNode.cxx,v $ Date: $Date: 2006/03/17 17:01:53 $ Version: $Revision: 1.14 $ =========================================================================auto=*/ // MRML includes #include "vtkMRMLDiffusionTensorVolumeDisplayNode.h" #include "vtkMRMLDiffusionTensorVolumeNode.h" #include "vtkMRMLNRRDStorageNode.h" #include "vtkMRMLScene.h" // VTK includes #include #include //------------------------------------------------------------------------------ vtkMRMLNodeNewMacro(vtkMRMLDiffusionTensorVolumeNode); //---------------------------------------------------------------------------- vtkMRMLDiffusionTensorVolumeNode::vtkMRMLDiffusionTensorVolumeNode() { this->Order = 2; //Second order Tensor } //---------------------------------------------------------------------------- void vtkMRMLDiffusionTensorVolumeNode::SetAndObserveDisplayNodeID(const char *displayNodeID) { this->Superclass::SetAndObserveDisplayNodeID(displayNodeID); // Make sure the node added is a DiffusionTensorVolumeDisplayNode vtkMRMLNode* displayNode = this->GetDisplayNode(); if (displayNode && !vtkMRMLDiffusionTensorVolumeDisplayNode::SafeDownCast(displayNode)) { vtkWarningMacro("SetAndObserveDisplayNodeID: The node to display " << displayNodeID << " can NOT display diffusion tensors"); } } //---------------------------------------------------------------------------- vtkMRMLDiffusionTensorVolumeNode::~vtkMRMLDiffusionTensorVolumeNode() { } //---------------------------------------------------------------------------- void vtkMRMLDiffusionTensorVolumeNode::PrintSelf(ostream& os, vtkIndent indent) { Superclass::PrintSelf(os,indent); } //---------------------------------------------------------------------------- vtkMRMLDiffusionTensorVolumeDisplayNode* vtkMRMLDiffusionTensorVolumeNode ::GetDiffusionTensorVolumeDisplayNode() { return vtkMRMLDiffusionTensorVolumeDisplayNode::SafeDownCast(this->GetDisplayNode()); } //---------------------------------------------------------------------------- vtkMRMLStorageNode* vtkMRMLDiffusionTensorVolumeNode::CreateDefaultStorageNode() { return vtkMRMLNRRDStorageNode::New(); } //---------------------------------------------------------------------------- void vtkMRMLDiffusionTensorVolumeNode::CreateDefaultDisplayNodes() { if (vtkMRMLDiffusionTensorVolumeDisplayNode::SafeDownCast(this->GetDisplayNode())!=NULL) { // display node already exists return; } if (this->GetScene()==NULL) { vtkErrorMacro("vtkMRMLDiffusionTensorVolumeNode::CreateDefaultDisplayNodes failed: scene is invalid"); return; } vtkNew dispNode; this->GetScene()->AddNode(dispNode.GetPointer()); dispNode->SetDefaultColorMap(); this->SetAndObserveDisplayNodeID(dispNode->GetID()); // add slice display nodes dispNode->AddSliceGlyphDisplayNodes( this ); } src/PBGWraps/Boundary/BoundaryTypes.hh #ifndef __PBGWRAPS_BOUNDARYTYPES__ #define __PBGWRAPS_BOUNDARYTYPES__ #include #include "Boundary/Boundary.hh" #include "Boundary/PlanarBoundary.hh" #include "Boundary/ReflectingBoundary.hh" #include "Boundary/RigidBoundary.hh" #include "Boundary/PeriodicBoundary.hh" #include "Boundary/ConstantVelocityBoundary.hh" #include "Boundary/ConstantXVelocityBoundary.hh" #include "Boundary/ConstantYVelocityBoundary.hh" #include "Boundary/ConstantZVelocityBoundary.hh" #include "Boundary/ConstantRVelocityBoundary.hh" #include "Boundary/ConstantBoundary.hh" #include "Boundary/CRKSPHVoidBoundary.hh" #include "Boundary/SphericalBoundary.hh" #include "Boundary/CylindricalBoundary.hh" #include "Boundary/AxialSymmetryBoundary.hh" #include "Boundary/AxisBoundaryRZ.hh" #include "PBGWraps/referenceAsPointer.hh" //------------------------------------------------------------------------------ // Names! //------------------------------------------------------------------------------ namespace Spheral { typedef Boundary > Boundary1d; typedef Boundary > Boundary2d; typedef Boundary > Boundary3d; typedef PlanarBoundary > PlanarBoundary1d; typedef PlanarBoundary > PlanarBoundary2d; typedef PlanarBoundary > PlanarBoundary3d; typedef ReflectingBoundary > ReflectingBoundary1d; typedef ReflectingBoundary > ReflectingBoundary2d; typedef ReflectingBoundary > ReflectingBoundary3d; typedef RigidBoundary > RigidBoundary1d; typedef RigidBoundary > RigidBoundary2d; typedef RigidBoundary > RigidBoundary3d; typedef PeriodicBoundary > PeriodicBoundary1d; typedef PeriodicBoundary > PeriodicBoundary2d; typedef PeriodicBoundary > PeriodicBoundary3d; typedef ConstantVelocityBoundary > ConstantVelocityBoundary1d; typedef ConstantVelocityBoundary > ConstantVelocityBoundary2d; typedef ConstantVelocityBoundary > ConstantVelocityBoundary3d; typedef ConstantXVelocityBoundary > ConstantXVelocityBoundary1d; typedef ConstantXVelocityBoundary > ConstantXVelocityBoundary2d; typedef ConstantXVelocityBoundary > ConstantXVelocityBoundary3d; typedef ConstantYVelocityBoundary > ConstantYVelocityBoundary2d; typedef ConstantYVelocityBoundary > ConstantYVelocityBoundary3d; typedef ConstantZVelocityBoundary > ConstantZVelocityBoundary3d; typedef ConstantRVelocityBoundary > ConstantRVelocityBoundary1d; typedef ConstantRVelocityBoundary > ConstantRVelocityBoundary2d; typedef ConstantRVelocityBoundary > ConstantRVelocityBoundary3d; typedef ConstantBoundary > ConstantBoundary1d; typedef ConstantBoundary > ConstantBoundary2d; typedef ConstantBoundary > ConstantBoundary3d; typedef CRKSPHVoidBoundary > CRKSPHVoidBoundary1d; typedef CRKSPHVoidBoundary > CRKSPHVoidBoundary2d; typedef CRKSPHVoidBoundary > CRKSPHVoidBoundary3d; //------------------------------------------------------------------------------ // Extract the BoundaryNodes for the given NodeList. //------------------------------------------------------------------------------ template inline typename Boundary::BoundaryNodes* accessBoundaryNodesFromBoundary(Boundary& self, NodeList& nodes) { return &(self.accessBoundaryNodes(nodes)); } //------------------------------------------------------------------------------ // Extract the various sets from a BoundaryNode instance. //------------------------------------------------------------------------------ template inline std::vector* controlNodesFromBoundaryNodes(typename Boundary::BoundaryNodes& bn) { return &(bn.controlNodes); } template inline std::vector* ghostNodesFromBoundaryNodes(typename Boundary::BoundaryNodes& bn) { return &(bn.ghostNodes); } template inline std::vector* violationNodesFromBoundaryNodes(typename Boundary::BoundaryNodes& bn) { return &(bn.violationNodes); } //------------------------------------------------------------------------------ // Support dynamic_casting from a Boundary to one of descendent types. Kind of // an ugly collision between having C++ vector's of boundaries and needing // dynamic_cast at the python level. //------------------------------------------------------------------------------ template Boundary2* dynamicCastBoundary(Boundary1* boundPtr) { if (Boundary2* result = dynamic_cast(boundPtr)) { return result; } else { PyErr_SetString(PyExc_ValueError, "Failed attempt to dynamic_cast a Boundary class"); return NULL; } } } typedef std::vector vector_of_Boundary1d; typedef std::vector vector_of_Boundary2d; typedef std::vector vector_of_Boundary3d; #endif MTO-parallel-dual-buffer/src/island_EA.cc0 #include "island_EA.h" IslandEA::IslandEA() { } IslandEA::~IslandEA() { } int IslandEA::CheckAndCreatRecordFile() { #ifndef NO_INTERACTION file_name_ = "./Results/MTO_parallel.csv"; #else file_name_ = "./Results/MTO_parallel_wo_interaction.csv"; #endif ifstream exist_file; ofstream file; exist_file.open(file_name_.c_str()); if(!exist_file) { file.open(file_name_.c_str()); file<< "problem_ID,task_num,run_ID,min_time,avg_time,max_time,total_FEs,island_num,pop_size_per_task"; for(int i = 0; i < problem_info_.task_num; i++) file<<','<<"fitness_value_"<> s_task_num; debug_file_name_ = "./Results/Debug/problems_task_num=" + s_task_num + ".csv"; EA_CPU_->PrintTaskDetails(debug_file_name_); } #endif return 0; } int IslandEA::Initilize(IslandInfo island_info, ProblemInfo problem_info, NodeInfo node_info) { problem_info_ = problem_info; island_info_ = island_info; node_info_ = node_info; EA_CPU_ = new DE_CPU(); EA_CPU_->Initilize(island_info_, problem_info_, node_info_); CheckAndCreatRecordFile(); srand(problem_info_.seed); EA_CPU_->InitilizePopulation(sub_population_); migrate_.Initilize(island_info_, problem_info_, node_info_); return 0; } int IslandEA::Unitilize() { sub_population_.clear(); EA_CPU_->Unitilize(); delete EA_CPU_; migrate_.Unitilize(); return 0; } int IslandEA::Finish() { migrate_.Finish(); MPI_Barrier(MPI_COMM_WORLD); if(node_info_.node_ID != 0) { SendResultToIsland0(); } else { vector total_display_unit; RecvResultFromOtherIsland(total_display_unit); MergeResults(total_display_unit); } return 0; } int IslandEA::RunEA(DisplayUnit display_unit, int &flag_converge) { EA_CPU_->Run(sub_population_); if(display_unit.fitness_value < 1e-8 && flag_converge == 0) { display_unit_ = display_unit; flag_converge = 1; } return 0; } int IslandEA::CalIslandNumCurrentTask() { int current_task_ID = node_info_.task_IDs[node_info_.node_ID]; int count = 0; for(int i = 0; i < node_info_.node_num; i++) { if(current_task_ID == node_info_.task_IDs[i]) count++; } return count; } int IslandEA::Execute() { int generation = 0; int current_FEs = island_info_.island_size; double start_time = MPI_Wtime(); real communication_time = 0; int flag_converge = 0; int task_count = CalIslandNumCurrentTask(); long int total_FEs = problem_info_.max_base_FEs * problem_info_.dim / (task_count + 0.0); int success_count = 0; DisplayUnit display_unit; #ifndef COMPUTING_TIME while(current_FEs < total_FEs) #else while(MPI_Wtime() - start_time < problem_info_.computing_time) #endif { display_unit = RecordDisplayUnit((real) (MPI_Wtime() - start_time), communication_time, current_FEs, migrate_.TotalInsert(), migrate_.TotalSuccessInsert()); RunEA(display_unit, flag_converge); if (island_info_.interval > 1) { if ( generation % island_info_.interval == 0) { double tmp_time = MPI_Wtime(); success_count += migrate_.MigrateIn(sub_population_, EA_CPU_); communication_time += (real) (MPI_Wtime() - tmp_time); #ifndef NO_INTERACTION current_FEs += island_info_.island_size * problem_info_.task_num; #endif } if ( generation % island_info_.interval_tmp == 0) { double tmp_time = MPI_Wtime(); migrate_.UpdateBuffer(EA_CPU_); communication_time += (real) (MPI_Wtime() - tmp_time); #ifndef NO_INTERACTION current_FEs += island_info_.island_size * problem_info_.task_num; #endif } double tmp_time = MPI_Wtime(); migrate_.MigrateOut(); communication_time += (real) (MPI_Wtime() - tmp_time); } generation++; current_FEs += island_info_.island_size; } if(flag_converge == 0) display_unit_ = RecordDisplayUnit((real) (MPI_Wtime() - start_time), communication_time, current_FEs, migrate_.TotalInsert(), migrate_.TotalSuccessInsert()); Finish(); return 0; } DisplayUnit IslandEA::RecordDisplayUnit(real current_time, real communication_time, int current_FEs, int total_insert, int total_success_insert) { DisplayUnit display_unit; display_unit.time = current_time; display_unit.FEs = current_FEs; display_unit.fitness_value = EA_CPU_->FindBestIndividual(sub_population_).fitness_value; display_unit.communication_percentage = communication_time / current_time; display_unit.total_success_insert = total_success_insert; display_unit.total_insert = total_insert; return display_unit; } int IslandEA::MergeResults(vector &total_display_unit) { vector fitness_values(problem_info_.task_num, 1e20); vector times_tasks(problem_info_.task_num, 1e20); vector FEs_tasks(problem_info_.task_num, 0); vector communication_percentage(problem_info_.task_num, 0); vector total_insert(problem_info_.task_num, 0); vector total_success_insert(problem_info_.task_num, 0); real min_time = 1e20, avg_time = 0, max_time = 0; total_display_unit[0] = display_unit_; //printf("%d\t%d\n", node_info_.node_ID, node_info_.node_num); for(int i = 0; i < node_info_.node_num; i++) { int task_ID = node_info_.task_IDs[i]; if(fitness_values[task_ID] > total_display_unit[i].fitness_value) { fitness_values[task_ID] = total_display_unit[i].fitness_value; times_tasks[task_ID] = total_display_unit[i].time; FEs_tasks[task_ID] = total_display_unit[i].FEs; communication_percentage[task_ID] = total_display_unit[i].communication_percentage; } if(max_time < total_display_unit[i].time) max_time = total_display_unit[i].time; if(min_time > total_display_unit[i].time) min_time = total_display_unit[i].time; avg_time += total_display_unit[i].time; total_insert[task_ID] += total_display_unit[i].total_insert; total_success_insert[task_ID] += total_display_unit[i].total_success_insert; } avg_time = avg_time / node_info_.node_num; ofstream file; file.open(file_name_.c_str(), ios::app); int run_ID = problem_info_.run_ID; int dim = problem_info_.dim; long int total_FEs = problem_info_.max_base_FEs * problem_info_.dim; int pop_size_per_task = island_info_.island_num * island_info_.island_size / problem_info_.task_num; #ifdef COMPUTING_TIME file< &total_display_unit) { MPI_Status mpi_status; DisplayUnit tmp_display_unit; for(int i = 0; i < node_info_.node_num; i++) total_display_unit.push_back(tmp_display_unit); real *msg = new real[6]; for(int i = 1; i < node_info_.node_num; i++) { int tag = 10 * problem_info_.run_ID + FLAG_DISPLAY_UNIT; MPI_Recv(msg, 6, MPI_DOUBLE, MPI_ANY_SOURCE, tag, MPI_COMM_WORLD, &mpi_status); DisplayUnit tmp_display_unit; tmp_display_unit.time = msg[0]; tmp_display_unit.FEs = msg[1]; tmp_display_unit.communication_percentage = msg[2]; tmp_display_unit.fitness_value = msg[3]; tmp_display_unit.total_insert = msg[4]; tmp_display_unit.total_success_insert = msg[5]; total_display_unit[mpi_status.MPI_SOURCE] = tmp_display_unit; } delete []msg; return 0; }KeinR/Danzun #include "Shader.h" #include #include #include #include #include #include #include "../core/Context.h" #include "../core/debug.h" #include "../core/error.h" #include "../core/Engine.h" #include "../lib/opengl.h" static constexpr unsigned int LOG_BUFFER_SIZE = 512; /** * Compiles the given shader and returns a handle to the OpenGL object. * @param [in] type The type (GL_VERTEX_SHADER/GL_FRAGMENT_SHADER) * @param [in] data Pointer to shader data * @param [in] length Length of `data` * @param [out] error String to dump errors. Untouched if no errors occurred. * @return ID of the newly created shader object, or 0 on error [ref] */ static GLuint compileShader(GLenum type, const char *data, int length); /** * Links two shaders (vertex and fragment) and returns the resulting * shader program. * @param [in] vertObject The vertex object * @param [in] fragObject The fragment object * @param [out] error String to dump errors. Untouched if no errors occurred. * @return ID of the resulting shader program, or [undefined] on error (I don't see it specified anywhere in the docs(?)) */ static GLuint linkShaders(GLuint vertObject, GLuint fragObject); static char *loadFile(const std::string &path, int &length); static void delShaders(GLuint vert, GLuint frag); static const char *getShaderTypeName(GLenum type); dan::Shader::Shader(): c(nullptr), handle(0) { } dan::Shader::Shader(Context &c, const char *vertexData, unsigned int vertexLength, const char *fragmentData, unsigned int fragmentLength): c(&c) { createShader(vertexData, vertexLength, fragmentData, fragmentLength); } dan::Shader::Shader(Context &c, const std::string &vertexPath, const std::string &fragmentPath): c(&c) { int vertLen, fragLen; char *vertData = nullptr; char *fragData = nullptr; try { vertData = loadFile(vertexPath, vertLen); fragData = loadFile(fragmentPath, fragLen); createShader(vertData, vertLen, fragData, fragLen); } catch (std::exception &e) { if (vertData != nullptr) { delete[] vertData; } if (fragData != nullptr) { delete[] fragData; } err("dan::Shader::Shader(strings...)", c.getEngine().getState()) << "Failed to load shader resource files: " << e.what(); } } dan::Shader::Shader(Shader &&other) { steal(other); } dan::Shader::~Shader() { free(); } dan::Shader &dan::Shader::operator=(Shader &&other) { free(); steal(other); return *this; } void dan::Shader::createShader(const char *vertexData, unsigned int vertexLength, const char *fragmentData, unsigned int fragmentLength) { #define FCLEAN delShaders(vertShader, fragShader) GLuint vertShader = 0; GLuint fragShader = 0; handle = 0; try { vertShader = compileShader(GL_VERTEX_SHADER, vertexData, vertexLength); fragShader = compileShader(GL_FRAGMENT_SHADER, fragmentData, fragmentLength); handle = linkShaders(vertShader, fragShader); } catch (std::exception &e) { FCLEAN; throw e; } FCLEAN; #undef FCLEAN } void dan::Shader::steal(Shader &other) { handle = other.handle; c = other.c; other.handle = 0; other.c = nullptr; // Don't bother moving the uniforms } dan::Shader::uniform_t dan::Shader::uni(const std::string &name) { uniforms_t::iterator loc = uniforms.find(name); uniform_t location; if (loc == uniforms.end()) { // Cache miss GLenum error; error = glGetError(); if (error != GL_NO_ERROR) { err("Shader::uni", c->getEngine().getState()) << "OpenGL error BEFORE getting uniform location: " << err::glErrStr(error); } location = glGetUniformLocation(handle, name.c_str()); uniforms[name] = location; error = glGetError(); if (error != GL_NO_ERROR) { err("Shader::uni", c->getEngine().getState()) << "OpenGL error AFTER getting uniform location: " << err::glErrStr(error); } } else { location = loc->second; } return location; } void dan::Shader::free() { if (handle != 0) { glDeleteProgram(handle); } } void dan::Shader::doUse() const { glUseProgram(handle); } void dan::Shader::use(const self_t &s) { DANZUN_ASSERT(s.get() == this); // Pointers must match c->setShader(s); } bool dan::Shader::isFailed() { return handle == 0; } dan::Shader::uniform_t dan::Shader::getUniform(const std::string &name) { return uni(name); } dan::Shader::program_t dan::Shader::getHandle() const { return handle; } void dan::Shader::setMatrix4fv(const std::string &name, const float *data) { glUniformMatrix4fv(getUniform(name), 1, GL_FALSE, data); } void dan::Shader::set1i(const std::string &name, int a) { glUniform1i(getUniform(name), a); } void dan::Shader::set2i(const std::string &name, int a, int b) { glUniform2i(getUniform(name), a, b); } void dan::Shader::set3i(const std::string &name, int a, int b, int c) { glUniform3i(getUniform(name), a, b, c); } void dan::Shader::set4i(const std::string &name, int a, int b, int c, int d) { glUniform4i(getUniform(name), a, b, c, d); } void dan::Shader::set1f(const std::string &name, float a) { glUniform1f(getUniform(name), a); } void dan::Shader::set2f(const std::string &name, float a, float b) { glUniform2f(getUniform(name), a, b); } void dan::Shader::set3f(const std::string &name, float a, float b, float c) { glUniform3f(getUniform(name), a, b, c); } void dan::Shader::set4f(const std::string &name, float a, float b, float c, float d) { glUniform4f(getUniform(name), a, b, c, d); } // Static members void dan::Shader::disuse() { glUseProgram(0); } // Non-members GLuint compileShader(GLenum type, const char *data, int length) { GLuint shader; shader = glCreateShader(type); // Load shader source code glShaderSource(shader, 1, &data, &length); // Compile code glCompileShader(shader); // Check for failure int success; glGetShaderiv(shader, GL_COMPILE_STATUS, &success); if (!success) { std::array log; glGetShaderInfoLog(shader, log.size(), NULL, log.data()); glDeleteShader(shader); std::string msg; msg += "["; msg += getShaderTypeName(type); msg += " shader]: \n"; msg += log.data(); throw std::runtime_error(msg); } return shader; } GLuint linkShaders(GLuint vertObject, GLuint fragObject) { GLuint shaderProgram = glCreateProgram(); glAttachShader(shaderProgram, vertObject); glAttachShader(shaderProgram, fragObject); glLinkProgram(shaderProgram); // Check for failure int success; glGetProgramiv(shaderProgram, GL_LINK_STATUS, &success); if (!success) { std::array log; glGetProgramInfoLog(shaderProgram, log.size(), NULL, log.data()); glDeleteProgram(shaderProgram); throw std::runtime_error("Shader linking failed:\n " + std::string(log.data())); } return shaderProgram; } char *loadFile(const std::string &path, int &length) { std::ifstream file; // Ensure exception safety file.exceptions(std::ios::goodbit); file.open(path); if (!file.good()) { throw std::invalid_argument("Cannot open file \"" + path + "\""); } file.seekg(0, file.end); length = file.tellg(); file.seekg(0, file.beg); char *data = new char[length]; file.read(data, length); if (!file.good()) { delete[] data; throw std::invalid_argument("Failed to read from file \"" + path + "\""); } return data; } void delShaders(GLuint vert, GLuint frag) { glDeleteShader(vert); glDeleteShader(frag); } const char *getShaderTypeName(GLenum type) { switch (type) { case GL_VERTEX_SHADER: return "vertex"; case GL_FRAGMENT_SHADER: return "fragment"; default: return "unknown"; } } #include "planeswwindow.h" PlanesWWindow::PlanesWWindow(QWidget *parent) : QMainWindow(parent) { //builds the game object - the controller mRound = new PlaneRound(10, 10, 3); //builds the view object mPlanesView = new PlanesWView(mRound); setCentralWidget(mPlanesView); //starts the game mRound->initRound(); } PlanesWWindow::~PlanesWWindow() { delete mPlanesView; delete mRound; } // test04 Not using OO #include using namespace std; // Declare a Class (类) class ClsBox { public: // Properties of the Class int intWidth; int intDepth; int intHeight; // Contructor of the Class // Means: when this class is initiated, what should be done ONCE ClsBox() { // Initialize all box to 1 x 1 x 1 intWidth = 1; intDepth = 1; intHeight = 1; } }; int main() { int intWidth = 1; int intDepth = 1; int intHeight = 1; // New Object cout << "The Initial Volume of the Box is: "; cout << intHeight * intWidth * intDepth << "\n"; cout << "Enter Height of the Box: "; cin >> intHeight; cout << "Enter Width of the Box: "; cin >> intWidth; cout << "Enter Depth of the Box: "; cin >> intDepth; cout << "The Volume of the Box is: "; cout << intHeight * intWidth * intDepth << "\n"; } // Copyright 2014 -http://graehl.org/ // // 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 GRAEHL__SHARED__FORMAT_HPP #define GRAEHL__SHARED__FORMAT_HPP #pragma once #include #include namespace fm { using std::string; using '\n'; using std::flush; using boost::format; using boost::io::group; using boost::io::str; using std::setfill; using std::setw; using std::hex; using std::dec; using std::showbase; using std::left; using std::right; using std::internal; } #define FSTR(x, y) fm::str(fm::format(x) % y) #endif 0 // Copyright (C) 2018-2019 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #pragma once #include #include "ie_built_in_impl.hpp" #include #include #include #include #include namespace InferenceEngine { namespace ShapeInfer { /** *@brief Implementation of Shape inference for Resample layer */ class ResampleShapeProp : public BuiltInShapeInferImpl { public: explicit ResampleShapeProp(const std::string& type) : BuiltInShapeInferImpl(type) {} void inferShapesImpl(const std::vector& inBlobs, const std::map& params, const std::map& blobs, std::vector& outShapes) override { LayerParams lp{}; CNNLayer cnnLayer(lp); cnnLayer.params = params; cnnLayer.type = _type; validate(&cnnLayer, inBlobs, params, blobs); SizeVector outShape; if (inBlobs.size() == 2) { auto* buffer = inBlobs[1]->cbuffer().as(); if (buffer != nullptr) { for (int i = 0; i < inBlobs[1]->size(); i++) { outShape.push_back(static_cast(buffer[i])); } } else { THROW_IE_EXCEPTION << "Second input must have allocated data"; } } else { auto scale = cnnLayer.GetParamAsFloat("factor"); outShape = {inShapes[0][0], inShapes[0][1]}; for (int i = 2; i < inShapes[0].size(); i++) outShape.push_back(static_cast(std::ceil(inShapes[0][i] * scale))); } outShapes.push_back(outShape); } }; } // namespace ShapeInfer } // namespace InferenceEngine EthanSK/C-to-MIPS-Compiler #include "primitiveType.hpp" void PrimitiveType::printC(std::ostream &os) const { os << primitiveTypeToString(); } std::string PrimitiveType::primitiveTypeToString() const { switch (_type) { case PrimitiveType::_void: return "void"; case PrimitiveType::_int: return "int"; case PrimitiveType::_float: return "float"; case PrimitiveType::_double: return "double"; case PrimitiveType::_char: return "char"; case PrimitiveType::_signed: return "signed"; case PrimitiveType::_unsigned: return "unsigned"; case PrimitiveType::_long: return "long"; default: return "UNKNOWN TYPE"; } } int PrimitiveType::getTypeSize() const { switch (_type) { case PrimitiveType::_void: return 0; case PrimitiveType::_int: return 4; case PrimitiveType::_float: return 4; case PrimitiveType::_double: return 8; case PrimitiveType::_char: return 1; case PrimitiveType::_signed: return 4; case PrimitiveType::_unsigned: return 4; case PrimitiveType::_long: return 4; default: return 0; } }// AUTOGENERATED FILE - DO NOT MODIFY! // This file generated by Djinni from interface_inheritance.djinni #include "NativeSubObjcJavaInterfaceInheritance.hpp" // my header #include "Marshal.hpp" namespace djinni_generated { NativeSubObjcJavaInterfaceInheritance::NativeSubObjcJavaInterfaceInheritance() : ::djinni::JniInterface<::testsuite::SubObjcJavaInterfaceInheritance, NativeSubObjcJavaInterfaceInheritance>() {} NativeSubObjcJavaInterfaceInheritance::~NativeSubObjcJavaInterfaceInheritance() = default; NativeSubObjcJavaInterfaceInheritance::JavaProxy::JavaProxy(JniType j) : Handle(::djinni::jniGetThreadEnv(), j) { } NativeSubObjcJavaInterfaceInheritance::JavaProxy::~JavaProxy() = default; std::string NativeSubObjcJavaInterfaceInheritance::JavaProxy::base_method() { auto jniEnv = ::djinni::jniGetThreadEnv(); ::djinni::JniLocalScope jscope(jniEnv, 10); const auto& data = ::djinni::JniClass<::djinni_generated::NativeSubObjcJavaInterfaceInheritance>::get(); auto jret = (jstring)jniEnv->CallObjectMethod(Handle::get().get(), data.method_baseMethod); ::djinni::jniExceptionCheck(jniEnv); return ::djinni::String::toCpp(jniEnv, jret); } std::string NativeSubObjcJavaInterfaceInheritance::JavaProxy::override_method() { auto jniEnv = ::djinni::jniGetThreadEnv(); ::djinni::JniLocalScope jscope(jniEnv, 10); const auto& data = ::djinni::JniClass<::djinni_generated::NativeSubObjcJavaInterfaceInheritance>::get(); auto jret = (jstring)jniEnv->CallObjectMethod(Handle::get().get(), data.method_overrideMethod); ::djinni::jniExceptionCheck(jniEnv); return ::djinni::String::toCpp(jniEnv, jret); } std::string NativeSubObjcJavaInterfaceInheritance::JavaProxy::sub_method() { auto jniEnv = ::djinni::jniGetThreadEnv(); ::djinni::JniLocalScope jscope(jniEnv, 10); const auto& data = ::djinni::JniClass<::djinni_generated::NativeSubObjcJavaInterfaceInheritance>::get(); auto jret = (jstring)jniEnv->CallObjectMethod(Handle::get().get(), data.method_subMethod); ::djinni::jniExceptionCheck(jniEnv); return ::djinni::String::toCpp(jniEnv, jret); } } // namespace djinni_generated auto Cartridge::MBC7::serialize(serializer& s) -> void { eeprom.serialize(s); s.integer(io.rom.bank); s.integer(io.ram.enable[0]); s.integer(io.ram.enable[1]); s.integer(io.accelerometer.x); s.integer(io.accelerometer.y); } auto Cartridge::MBC7::EEPROM::serialize(serializer& s) -> void { s.array(data); s.integer(size); s.integer(width); s.boolean(select); s.boolean(clock); s.boolean(writable); s.integer(busy); input.serialize(s); output.serialize(s); } auto Cartridge::MBC7::EEPROM::InputShiftRegister::serialize(serializer& s) -> void { s.integer(value); s.integer(count); s.integer(addressLength); s.integer(dataLength); } auto Cartridge::MBC7::EEPROM::OutputShiftRegister::serialize(serializer& s) -> void { s.integer(value); s.integer(count); } src/RDP/SpeechRecognition/SpeechRecognitionServer.cpp #include "SpeechRecognitionServer.h" #include "SpeechRecognitionClient.h" #include #include #include #include #include extern "C"{ #include } using namespace std; namespace nui{ SpeechRecognitionServer::SpeechRecognitionServer(int argc, char *argv[], ros::NodeHandle &node) : m_isValid(initJulius(argc, argv)), m_node(node), m_isOpenStream(false), m_isPausedStream(false), m_resultPub(m_node.advertise(RESULT_SPEECH_RECOGNITION, 100)), m_startSub(m_node.subscribe(START_SPEECH_RECOGNITION, 100, &SpeechRecognitionServer::startRecognition, this)), m_pauseSub(m_node.subscribe(PAUSE_SPEECH_RECOGNITION, 100, &SpeechRecognitionServer::pauseRecognition, this)), m_finishSub(m_node.subscribe(FINISH_SPEECH_RECOGNITION, 100, &SpeechRecognitionServer::finishRecognition, this)) { sleep(1); } bool SpeechRecognitionServer::initJulius(int argc, char *argv[]){ const int insArgc = 3; char *insArgv[3]; insArgv[0] = argv[0]; insArgv[1] = "-C"; string insStr = std::string(SHARE_DIR) + "/julius.jconf"; insArgv[2] = &insStr[0]; cout << "julius load file = " << insArgv[2] << endl; Jconf *jconf = j_config_load_args_new(insArgc, insArgv); if(jconf == NULL) return false; m_recog = boost::shared_ptr(j_create_instance_from_jconf(jconf),boost::bind(j_recog_free, boost::lambda::_1)); if(m_recog == NULL) return false; callback_add(m_recog.get(), CALLBACK_RESULT,&SpeechRecognitionServer::callWhenResult, this); callback_add(m_recog.get(), CALLBACK_EVENT_PAUSE, &SpeechRecognitionServer::callInPause, this); callback_add(m_recog.get(), CALLBACK_EVENT_RESUME, &SpeechRecognitionServer::callWhenResume, this); return j_adin_init(m_recog.get()) != FALSE; } void SpeechRecognitionServer::finishRecognition(const std_msgs::EmptyConstPtr &msg){ if(m_isOpenStream){ m_isOpenStream = false; j_close_stream(m_recog.get()); } } void SpeechRecognitionServer::pauseRecognition(const std_msgs::EmptyConstPtr &msg){ if(m_isOpenStream) j_request_pause(m_recog.get()); } void SpeechRecognitionServer::callInPause(Recog *recog, void *receiver){ SpeechRecognitionServer* srObj = (SpeechRecognitionServer*)receiver; srObj->m_isPausedStream = true; while(true){ atlas::Timer::sleep(1); cout << "callInPause" << endl; } } void SpeechRecognitionServer::callWhenResume(Recog *recog, void *receiver){ SpeechRecognitionServer* srObj = (SpeechRecognitionServer*)receiver; srObj->m_isPausedStream = false; cout << "callWhenResume" << endl; } void SpeechRecognitionServer::callWhenResult(Recog *recog, void *receiver){ std::cout << "callWhenResult" << std::endl; SpeechRecognitionServer* srObj = (SpeechRecognitionServer*)receiver; for(RecogProcess *process = recog->process_list; process ; process = process->next){ if(! process->live) continue; if(process->result.status < 0){ switch(process->result.status){ case J_RESULT_STATUS_REJECT_POWER: cout << "" << endl; break; case J_RESULT_STATUS_TERMINATE: cout << "" << endl; break; case J_RESULT_STATUS_ONLY_SILENCE: std::cout << "" << std::endl; break; case J_RESULT_STATUS_REJECT_GMM: std::cout << "" << std::endl; break; case J_RESULT_STATUS_REJECT_SHORT: std::cout << "" << std::endl; break; case J_RESULT_STATUS_FAIL: std::cout << "" << std::endl; break; } continue; } WORD_INFO *winfo = process->lm->winfo; for(int n = 0; n < process->result.sentnum; n++){ Sentence *sentence = &(process->result.sent[n]); WORD_ID *seq = sentence->word; const int seqnum = sentence->word_num; string ret; for(int i=0; i < seqnum; i++){ string woutput = srObj->stringConvert(string(winfo->woutput[seq[i]]), "euc-jp", "utf8"); cout << "woutput[" << i << "] = " << woutput << endl; ret += woutput; } cout << "Result String" << n+1 << " = " << ret << endl; std_msgs::String msg; msg.data = ret; srObj->m_resultPub.publish(msg); } } } string SpeechRecognitionServer::stringConvert(const string &src, const char *srcEnc, const char *retEnc){ icu::UnicodeString unicode(src.c_str(), srcEnc); const int32_t len = unicode.extract(0, unicode.length(), NULL, retEnc); char *ins = new char[len + 1]; unicode.extract(0, unicode.length(), ins, retEnc); string ret = ins; delete []ins; return ret; } void SpeechRecognitionServer::startRecognition(const std_msgs::EmptyConstPtr &msg){ ROS_INFO("StartSpeechRecognition"); if(m_isPausedStream){ j_request_resume(m_recog.get()); return; } switch(j_open_stream(m_recog.get(), NULL)) { case 0: m_isOpenStream = true; break; case -1: fprintf(stderr, "error in input stream\n"); return; case -2: fprintf(stderr, "failed to begin input stream\n"); return; } //m_timer.singleShot(timeout, boost::bind(&SpeechRecognition::finishRecognition, this)); j_recognize_stream(m_recog.get()); } void SpeechRecognitionServer::runServer(){ switch(j_open_stream(m_recog.get(), NULL)) { case 0: m_isOpenStream = true; break; case -1: fprintf(stderr, "error in input stream\n"); return; case -2: fprintf(stderr, "failed to begin input stream\n"); return; } j_recognize_stream(m_recog.get()); ros::Rate loopRate(5); while(ros::ok()){ ros::spinOnce(); loopRate.sleep(); } } } //namespace nui #include "ofApp.h" #define PARTICLE_COUNT 25 // 15 25 #define COLUMNS 128 // 32 128 #define ROWS 64 // 32 64 void ofApp::setup(){ ofSetWindowTitle("2D Metaballs"); ofSetBackgroundColor(0); m_cell_grid.setup(COLUMNS, ROWS); m_cell_grid.setMode(PATH); #ifdef TEST_PARTICLE_SYSTEM m_mouse_particle.push_back(Particle(ofGetWidth()*0.5f, ofGetHeight()*0.5f, 75)); #else m_particle_system.setup(PARTICLE_COUNT); #endif m_hsb_color.set(ofRandom(1.f), ofRandom(0.2f, 0.8f), 0.9f, 0.75f); m_show_gui = false; m_panel.setup(); m_panel.setName("Metaballs"); m_panel.add(m_fitting.set("contour fitting", 0.75f, 0.5f, 1.f)); m_panel.add(m_move_particles.set("move particles", true)); m_panel.add(m_show_particles.set("show particles", false)); m_panel.add(m_show_cells.set("show cells", false)); m_panel.add(m_show_mesh.set("show mesh", true)); m_panel.add(m_interpolate.set("interpolate", false)); m_panel.add(m_infill.set("infill", false)); m_panel.add(m_wireframe.set("wireframe", false)); } void ofApp::update() { #ifdef TEST_PARTICLE_SYSTEM m_cell_grid.update(m_mouse_particle, m_interpolate, m_infill, m_fitting); #else if (m_move_particles) { m_particle_system.update(); } m_cell_grid.update(m_particle_system.getParticles(), m_interpolate, m_infill, m_fitting); #endif float h = m_hsb_color.getHue() + ofRandom(-0.01f, 0.01f); if (h < 0.f) h = 1 + h; if (h > 1.f) h = h - 1; m_hsb_color.setHue(h); float b = m_hsb_color.getBrightness() + ofRandom(-0.01f, 0.01f); if (b < 0.2f) b = 0.2f; if (b > 0.8f) b = 0.8f; m_hsb_color.setBrightness(b); info = "FPS: " + to_string((int) ofGetFrameRate()); info += " - MODE: "; info += m_cell_grid.inPathMode() ? "PATH" : "MESH"; if (m_show_mesh) { info += "\nNUM VERTICES: " + to_string((int) m_cell_grid.getMesh().getNumVertices()); if (m_infill) { info += "\nNUM TRIANGLES: " + to_string((int) (m_cell_grid.getMesh().getNumVertices()/3)); } else { if (m_cell_grid.inMeshMode()) { info += "\nNUM LINES: " + to_string((int) (m_cell_grid.getMesh().getNumVertices()/2)); } } } } void ofApp::draw(){ if (m_show_particles) { #ifdef TEST_PARTICLE_SYSTEM ofPushMatrix(); ofTranslate(m_mouse_particle[0].getPosition()); ofPushStyle(); ofSetCircleResolution(64); ofSetColor(255, 255, 255, 127); ofDrawCircle(0.f, 0.f, m_mouse_particle[0].getRadius()); ofPopStyle(); ofPopMatrix(); #else m_particle_system.draw(); #endif } if (m_show_cells) { m_cell_grid.draw(); } if (m_show_mesh) { if (m_cell_grid.inPathMode() && !m_infill) { m_cell_grid.getPath().setStrokeColor(m_hsb_color); m_cell_grid.getPath().setStrokeWidth(1); m_cell_grid.getPath().draw(); } else { ofPushStyle(); ofSetColor(m_hsb_color); if (m_wireframe) { m_cell_grid.getMesh().drawWireframe(); } else { m_cell_grid.getMesh().draw(); } ofPopStyle(); } } ofPushStyle(); ofSetColor(255, 0, 127, 255); ofDrawBitmapString(info, 10, 21); ofPopStyle(); if (m_show_gui) { m_panel.draw(); } } void ofApp::keyPressed(int key){ switch (key) { case 'g': m_show_gui = !m_show_gui; break; case ' ': m_move_particles = !m_move_particles; break; case 'p': m_show_particles = !m_show_particles; break; case 'c': m_show_cells = !m_show_cells; break; case 'm': m_show_mesh = !m_show_mesh; break; case 'i': m_interpolate = !m_interpolate; break; case 'f': m_infill = !m_infill; break; case 'w': m_wireframe = !m_wireframe; break; case OF_KEY_TAB: if (m_cell_grid.inPathMode()) { m_cell_grid.setMode(MESH); } else { m_cell_grid.setMode(PATH); } break; default: break; } } #ifdef TEST_PARTICLE_SYSTEM void ofApp::mouseMoved(int x, int y ) { if (m_move_particles) { if (x < m_mouse_particle[0].getRadius()) x = m_mouse_particle[0].getRadius(); else if (x > ofGetWidth() - m_mouse_particle[0].getRadius()) x = ofGetWidth() - m_mouse_particle[0].getRadius(); if (y < m_mouse_particle[0].getRadius()) y = m_mouse_particle[0].getRadius(); else if (y > ofGetHeight() - m_mouse_particle[0].getRadius()) y = ofGetHeight() - m_mouse_particle[0].getRadius(); m_mouse_particle[0].setPosition(ofVec3f(x,y,0.f)); } } #endif 100-1000 /* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT license. * * Helper methods used in various parts. */ #include "utils.h" /** * Busy waits until a input from serial is received. * Once a character is available, reads and returns it. */ char waitForSerialInput(){ while(!(Serial.available() > 0)); return Serial.read(); }python_derived_caller/ext/pet.cpp #include #include #include "pet.hpp" Pet::Pet() : name() {} Pet::Pet(const std::string &name) : name(name) {} std::string Pet::getName() { return name; } std::string Pet::getNameCaller() { return getName(); } #include #include #include #include const int MAX_N = 200050; typedef long long ll; ll w[MAX_N], v[MAX_N]; ll ql[MAX_N], qr[MAX_N]; ll q[MAX_N], sum[MAX_N]; template T read(); int main() { freopen("qc.in", "r", stdin); freopen("qc.out", "w", stdout); ll l = 0, r, min = LLONG_MAX; ll n = read(), m = read(), s = read(); for (int i = 1; i <= n; i++) { w[i] = read(); v[i] = read(); r = std::max(r, w[i]); } for (int i = 1; i <= m; i++) { ql[i] = read(); qr[i] = read(); } while (l <= r) { ll ans = 0, mid = (l + r) / 2; for (int i = 1; i <= n; i++) { if (w[i] > mid) { q[i] = q[i - 1] + 1; sum[i] = sum[i - 1] + v[i]; } else { q[i] = q[i - 1]; sum[i] = sum[i - 1]; } } for (int i = 1; i <= m; i++) { ans += (q[qr[i]] - q[ql[i] - 1]) * (sum[qr[i]] - sum[ql[i] - 1]); } ans = s - ans; if (ans < 0) { l = mid + 1; } else { r = mid - 1; } min = std::min(min, std::abs(ans)); } std::cout << min << '\n'; fclose(stdin); fclose(stdout); return 0; } template T read() { T 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; }// ---------------------------------------------------------------------------- // @file lpc84x_swm.hpp // @brief NXP LPC84x Switch Matrix (SWM) class. // @date 18 May 2018 // ---------------------------------------------------------------------------- // // Xarmlib 0.1.0 - https://github.com/hparracho/Xarmlib // Copyright (c) 2018 () // // See README.md file for additional credits and acknowledgments. // // 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 __XARMLIB_TARGETS_LPC84X_SWM_HPP #define __XARMLIB_TARGETS_LPC84X_SWM_HPP #include "targets/LPC84x/lpc84x_pin.hpp" namespace xarmlib { namespace targets { namespace lpc84x { class Swm { public: // -------------------------------------------------------------------- // PUBLIC DEFINITIONS // -------------------------------------------------------------------- // Switch Matrix movable pins enum class PinMovable { U0_TXD_O = 0x00, // PINASSIGN0 - UART0 TXD Output U0_RXD_I = 0x01, // PINASSIGN0 - UART0 RXD Input U0_RTS_O = 0x02, // PINASSIGN0 - UART0 RTS Output U0_CTS_I = 0x03, // PINASSIGN0 - UART0 CTS Input U0_SCLK_IO = 0x10, // PINASSIGN1 - UART0 SCLK I/O U1_TXD_O = 0x11, // PINASSIGN1 - UART1 TXD Output U1_RXD_I = 0x12, // PINASSIGN1 - UART1 RXD Input U1_RTS_O = 0x13, // PINASSIGN1 - UART1 RTS Output U1_CTS_I = 0x20, // PINASSIGN2 - UART1 CTS Input U1_SCLK_IO = 0x21, // PINASSIGN2 - UART1 SCLK I/O U2_TXD_O = 0x22, // PINASSIGN2 - UART2 TXD Output U2_RXD_I = 0x23, // PINASSIGN2 - UART2 RXD Input U2_RTS_O = 0x30, // PINASSIGN3 - UART2 RTS Output U2_CTS_I = 0x31, // PINASSIGN3 - UART2 CTS Input U2_SCLK_IO = 0x32, // PINASSIGN3 - UART2 SCLK I/O SPI0_SCK_IO = 0x33, // PINASSIGN3 - SPI0 SCK I/O SPI0_MOSI_IO = 0x40, // PINASSIGN4 - SPI0 MOSI I/O SPI0_MISO_IO = 0x41, // PINASSIGN4 - SPI0 MISO I/O SPI0_SSEL0_IO = 0x42, // PINASSIGN4 - SPI0 SSEL0 I/O SPI0_SSEL1_IO = 0x43, // PINASSIGN4 - SPI0 SSEL1 I/O SPI0_SSEL2_IO = 0x50, // PINASSIGN5 - SPI0 SSEL2 I/O SPI0_SSEL3_IO = 0x51, // PINASSIGN5 - SPI0 SSEL3 I/O SPI1_SCK_IO = 0x52, // PINASSIGN5 - SPI1 SCK I/O SPI1_MOSI_IO = 0x53, // PINASSIGN5 - SPI1 MOSI I/O SPI1_MISO_IO = 0x60, // PINASSIGN6 - SPI1 MISO I/O SPI1_SSEL0_IO = 0x61, // PINASSIGN6 - SPI1 SSEL0 I/O SPI1_SSEL1_IO = 0x62, // PINASSIGN6 - SPI1 SSEL1 I/O SCT_PIN0_I = 0x63, // PINASSIGN6 - SCT PIN0 Input SCT_PIN1_I = 0x70, // PINASSIGN7 - SCT PIN1 Input SCT_PIN2_I = 0x71, // PINASSIGN7 - SCT PIN2 Input SCT_PIN3_I = 0x72, // PINASSIGN7 - SCT PIN3 Input SCT_OUT0_O = 0x73, // PINASSIGN7 - SCT OUT0 Output SCT_OUT1_O = 0x80, // PINASSIGN8 - SCT OUT1 Output SCT_OUT2_O = 0x81, // PINASSIGN8 - SCT OUT2 Output SCT_OUT3_O = 0x82, // PINASSIGN8 - SCT OUT3 Output SCT_OUT4_O = 0x83, // PINASSIGN8 - SCT OUT4 Output SCT_OUT5_O = 0x90, // PINASSIGN9 - SCT OUT5 Output SCT_OUT6_O = 0x91, // PINASSIGN9 - SCT OUT6 Output I2C1_SDA_IO = 0x92, // PINASSIGN9 - I2C1 SDA I/O I2C1_SCL_IO = 0x93, // PINASSIGN9 - I2C1 SCL I/O I2C2_SDA_IO = 0xA0, // PINASSIGN10 - I2C2 SDA I/O I2C2_SCL_IO = 0xA1, // PINASSIGN10 - I2C2 SCL I/O I2C3_SDA_IO = 0xA2, // PINASSIGN10 - I2C3 SDA I/O I2C3_SCL_IO = 0xA3, // PINASSIGN10 - I2C3 SCL I/O ACMP_O_O = 0xB0, // PINASSIGN11 - Analog comparator Output CLKOUT_O = 0xB1, // PINASSIGN11 - CLKOUT Output GPIO_INT_BMAT_O = 0xB3, // PINASSIGN11 - GPIO INT BMAT Output U3_TXD_O = 0xB4, // PINASSIGN11 - UART3 TXD Output U3_RXD_I = 0xC0, // PINASSIGN12 - UART3 RXD Input U3_SCK_IO = 0xC1, // PINASSIGN12 - UART3 SCLK I/O U4_TXD_O = 0xC2, // PINASSIGN12 - UART4 TXD Output U4_RXD_I = 0xC3, // PINASSIGN12 - UART4 RXD Input U4_SCK_IO = 0xD0, // PINASSIGN13 - UART4 SCLK I/O T0_MAT0_O = 0xD1, // PINASSIGN13 - Timer0 Match0 Output T0_MAT1_O = 0xD2, // PINASSIGN13 - Timer0 Match1 Output T0_MAT2_O = 0xD3, // PINASSIGN13 - Timer0 Match2 Output T0_MAT3_O = 0xE0, // PINASSIGN14 - Timer0 Match3 Output T0_CAP0_I = 0xE1, // PINASSIGN14 - Timer0 Capture0 Input T0_CAP1_I = 0xE2, // PINASSIGN14 - Timer0 Capture1 Input T0_CAP2_I = 0xE3, // PINASSIGN14 - Timer0 Capture2 Input }; // Switch Matrix fixed pins enum class PinFixed { ACMP_I1 = 0, // ACMP I1 ACMP_I2, // ACMP I2 ACMP_I3, // ACMP I3 ACMP_I4, // ACMP I4 ACMP_I5, // ACMP I5 SWCLK, // SWCLK SWDIO, // SWDIO XTALIN, // XTALIN XTALOUT, // XTALOUT RESETN, // Reset CLKIN, // Clock Input VDDCMP, // VDDCMP I2C0_SDA, // I2C0_SDA I2C0_SCL, // I2C0_SCL ADC_0, // ADC_0 ADC_1, // ADC_1 ADC_2, // ADC_2 ADC_3, // ADC_3 ADC_4, // ADC_4 ADC_5, // ADC_5 ADC_6, // ADC_6 ADC_7, // ADC_7 ADC_8, // ADC_8 ADC_9, // ADC_9 ADC_10, // ADC_10 ADC_11, // ADC_11 DACOUT0, // DACOUT0 DACOUT1, // DACOUT1 CAPT_X0, // CAPT_X0 CAPT_X1, // CAPT_X1 CAPT_X2, // CAPT_X2 CAPT_X3, // CAPT_X3 CAPT_X4 = 32, // CAPT_X4 CAPT_X5, // CAPT_X5 CAPT_X6, // CAPT_X6 CAPT_X7, // CAPT_X7 CAPT_X8, // CAPT_X8 CAPT_YL, // CAPT YL CAPT_YH // CAPT YH }; // -------------------------------------------------------------------- // PUBLIC MEMBER FUNCTIONS // -------------------------------------------------------------------- // Assign a movable pin function to a physical pin in Switch Matrix static void assign(const PinMovable movable, const Pin::Name pin) { if(pin == Pin::Name::NC) { return; } const int32_t pin_index = static_cast(movable) >> 4; const uint32_t pin_shift = (static_cast(movable) & 0x0F) << 3; const uint32_t reg_value = LPC_SWM->PINASSIGN[pin_index] & (~(0xFF << pin_shift)); LPC_SWM->PINASSIGN[pin_index] = reg_value | (static_cast(pin) << pin_shift); } // Unassign a movable pin function from a physical pin in Switch Matrix static void unassign(const PinMovable movable) { (void)movable; // @ 22 March 2018 // @TODO: Implement this function for completeness sake. } // Enable a fixed function pin in the Switch Matrix static void enable(const PinFixed fixed) { if(static_cast(fixed) < 32) { LPC_SWM->PINENABLE0 &= ~(1 << static_cast(fixed)); } else { LPC_SWM->PINENABLE1 &= ~(1 << (static_cast(fixed) - 32)); } } // Disable a fixed function pin in the Switch Matrix static void disable(const PinFixed fixed) { if(static_cast(fixed) < 32) { LPC_SWM->PINENABLE0 |= (1 << static_cast(fixed)); } else { LPC_SWM->PINENABLE1 |= (1 << (static_cast(fixed) - 32)); } } }; } // namespace lpc84x } // namespace targets } // namespace xarmlib #endif // __XARMLIB_TARGETS_LPC84X_SWM_HPP poj/2/2159.cc1-10 #include #include using namespace std; int main(void) { string encrypted, original; cin >> encrypted >> original; vector a(26, 0), b(26, 0); for (int i = 0; i < original.size(); i++) { a[encrypted[i]-'A']++; b[original[i]-'A']++; } for (int i = 0; i < 26; i++) { if (a[i] != 0) { int j = 0; for (; j < 26; j++) { if (a[i] == b[j]) { b[j] = -1; break; } } if (j == 26) { cout << "NO" << endl; return 0; } } } cout << "YES" << endl; return 0; } #include "src/metafs/storage/pstore/mss_on_disk.h" #include namespace pos { TEST(MssIoCompletion, MssIoCompletion_) { } TEST(MssIoCompletion, _DoSpecificJob_) { } } // namespace pos namespace pos { TEST(MssOnDisk, MssOnDisk_) { } TEST(MssOnDisk, CreateMetaStore_) { } TEST(MssOnDisk, Open_) { } TEST(MssOnDisk, Close_) { } TEST(MssOnDisk, GetCapacity_) { } TEST(MssOnDisk, ReadPage_) { } TEST(MssOnDisk, WritePage_) { } TEST(MssOnDisk, IsAIOSupport_) { } TEST(MssOnDisk, ReadPageAsync_) { } TEST(MssOnDisk, WritePageAsync_) { } TEST(MssOnDisk, TrimFileData_) { } TEST(MssOnDisk, _CheckSanityErr_) { } TEST(MssOnDisk, _SendSyncRequest_) { } TEST(MssOnDisk, _SendAsyncRequest_) { } TEST(MssOnDisk, _AdjustPageIoToFitTargetPartition_) { } TEST(MssOnDisk, _Finalize_) { } } // namespace pos /* * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved. * 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 "gc/g1/g1FullGCScope.hpp" G1FullGCScope::G1FullGCScope(GCMemoryManager* memory_manager, bool explicit_gc, bool clear_soft) : _rm(), _explicit_gc(explicit_gc), _g1h(G1CollectedHeap::heap()), _gc_id(), _svc_marker(SvcGCMarker::FULL), _timer(), _tracer(), _active(), _cpu_time(), _soft_refs(clear_soft, _g1h->soft_ref_policy()), _memory_stats(memory_manager, _g1h->gc_cause()), _collector_stats(_g1h->g1mm()->full_collection_counters()), _heap_transition(_g1h) { _timer.register_gc_start(); _tracer.report_gc_start(_g1h->gc_cause(), _timer.gc_start()); _g1h->pre_full_gc_dump(&_timer); _g1h->trace_heap_before_gc(&_tracer); } G1FullGCScope::~G1FullGCScope() { // We must call G1MonitoringSupport::update_sizes() in the same scoping level // as an active TraceMemoryManagerStats object (i.e. before the destructor for the // TraceMemoryManagerStats is called) so that the G1 memory pools are updated // before any GC notifications are raised. _g1h->g1mm()->update_sizes(); _g1h->trace_heap_after_gc(&_tracer); _g1h->post_full_gc_dump(&_timer); _timer.register_gc_end(); _tracer.report_gc_end(_timer.gc_end(), _timer.time_partitions()); } bool G1FullGCScope::is_explicit_gc() { return _explicit_gc; } bool G1FullGCScope::should_clear_soft_refs() { return _soft_refs.should_clear(); } STWGCTimer* G1FullGCScope::timer() { return &_timer; } G1FullGCTracer* G1FullGCScope::tracer() { return &_tracer; } G1HeapTransition* G1FullGCScope::heap_transition() { return &_heap_transition; } VikashTiwari1208/Anthology-of-Algorithms-and-Data-structures #pragma GCC optimize ("Ofast") #include #define endl '\n' using namespace std; typedef int64_t ll; void Fast() { cin.sync_with_stdio(0); cin.tie(0);cout.tie(0); } const int N = 1e5; int n, k, arr[N]; int SPLTK() { int l = 0, prod = 1, ans = 0; for(int r = 0; r < n; ++r) { prod *= arr[r]; for(; l <= r && prod >= k; ++l) prod /= arr[l]; ans += r - l + 1; } return ans; } void Solve() { cin >> n >> k; for(int i = 0; i < n; ++i) cin >> arr[i]; cout << SPLTK() << endl; } int main() { Fast(); int tc = 1; for(int i = 1; i <= tc; ++i) Solve(); } #include "FileLoader.hpp" namespace SilentMedia { namespace Media { namespace Container { // -------------------------------------------------------------------- // Public methods // -------------------------------------------------------------------- FileLoader::FileLoader() { } FileLoader::~FileLoader() { } bool FileLoader::open(const string &fileName) { this -> fileName = fileName; Path path(fileName); if (!boost::filesystem::exists(path)) { throw SilentMedia::Throw::FileNotFound(fileName); } if (!boost::filesystem::is_regular_file(path)) { throw SilentMedia::Throw::NotRegularFile(fileName); } this -> infile.open(fileName.c_str(), ios::binary); if (!this -> infile.is_open()) { throw SilentMedia::Throw::ErrorOpenFile(fileName); } return true; } void FileLoader::close() { this -> infile.close(); if (this -> infile.is_open()) { throw SilentMedia::Throw::ErrorCloseFile(this -> fileName); } } ContainerType FileLoader::getContainer() { // offset = 0, length = 4 string signature = this -> readFileSegment(0, 4); if (!signature.compare("OggS")) { this -> container = OGG; } else if (!signature.compare("RIFF")) { // RIFF have WAVE and AVI, so clarify it string containerDetail = this -> readFileSegment(8, 4); if (!containerDetail.compare("WAVE")) { this -> container = RIFF_WAVE; } else if (!containerDetail.compare("AVI")) { this -> container = RIFF_AVI; } else { this -> container = RIFF_UNKNOW; } } else { this -> container = UNKNOW_CONTAINER; } return this -> container; } //TODO: Need to return 2 codecs, audio & video CodecType FileLoader::getCodec() { /* OGG */ if (this -> container == OGG) { // offset = 29, length = 6 string mediaCodec = this -> readFileSegment(29, 6); if (!mediaCodec.compare("vorbis")) { this -> codec = VORBIS; } else if (!mediaCodec.compare("theora")) { this -> codec = THEORA; } } else { this -> codec = UNKNOW_CODEC; } return this -> codec; } string FileLoader::getFileSignature() { return this -> readFileSegment(0, 4); } // -------------------------------------------------------------------- // Private methods // -------------------------------------------------------------------- string FileLoader::readFileSegment(int offset, int length) { // need to be every time set to global start point this -> infile.seekg(offset, ios_base::beg); char buf[length + 1]; this -> infile.read(buf, length); buf[length] = 0; return buf; } } } } Abiram-Narayanaswamy/hall-switch /** * @file hall-switch-ino.hpp * @brief Hall Switch Arduino API * @date July 2019 * @copyright Copyright (c) 2019-2020 Infineon Technologies AG * * SPDX-License-Identifier: MIT */ #ifndef HALL_SWITCH_INO_HPP_ #define HALL_SWITCH_INO_HPP_ #include "config/hall-conf.hpp" #if (HALL_SWITCH_FRAMEWORK == HALL_SWITCH_FRMWK_ARDUINO) #include "corelib/hall-switch.hpp" #include "framework/arduino/wrapper/hall-platf-ino.hpp" /** * @addtogroup hsinoapi * @{ */ class HallSwitchIno { public: HallSwitchIno (uint8_t outputPin, HallSwitch::CBack_t cBack = NULL, uint8_t powerPin = UNUSED_PIN); HallSwitchIno (PlatformIno_t hwPlatf, HallSwitch::CBack_t cBack = NULL); ~HallSwitchIno (); int begin (); int end (); int getBField (); private: HallSwitch sw; }; /** @} */ #endif /** HALL_SWITCH_FRAMEWORK **/ #endif /** HALL_SWITCH_INO_HPP_ **/0 #include "inputManager.h" #include #include #include #include template struct InputInstance : std::pair { typedef std::pair base_class; inline InputInstance(T value) : base_class(value, inputManager::InputInvalid) {} inline InputInstance(T value, inputManager::InputState state) : base_class(value, state) {} inline bool operator==(const InputInstance &rhs) const { return this->first == rhs.first; } }; // Instance types typedef InputInstance KeyInstance; typedef InputInstance ButtonInstance; // Container types typedef std::vector KeyContainer; typedef std::vector ButtonContainer; // Globals static KeyContainer sg_keyInstances; static ButtonContainer sg_buttonInstances; static QPoint sg_mouseCurrPosition; static QPoint sg_mousePrevPosition; static QPoint sg_mouseTriggeredPosition; static QPoint sg_mouseDelta; static QPoint sg_mouseTriggeredDelta; static inline KeyContainer::iterator FindKey(Qt::Key value) { return std::find(sg_keyInstances.begin(), sg_keyInstances.end(), value); } static inline ButtonContainer::iterator FindButton(Qt::MouseButton value) { return std::find(sg_buttonInstances.begin(), sg_buttonInstances.end(), value); } template static inline void UpdateStates(TPair &instance) { switch (instance.second) { case inputManager::InputRegistered: instance.second = inputManager::InputTriggered; break; case inputManager::InputTriggered: instance.second = inputManager::InputPressed; break; case inputManager::InputUnregistered: instance.second = inputManager::InputReleased; break; default: break; } } // template static inline bool CheckReleased(const TPair &instance) { return instance.second == inputManager::InputReleased; } template static inline void Update(Container &container) { // container is actual a // std::vector < InputInstance > // std::vector< std::pair< Qt::Key, Input::InputState>> typedef typename Container::iterator Iter; typedef typename Container::value_type TPair; // Remove old data // remove if the key is not pressed anymore Iter remove = std::remove_if(container.begin(), container.end(), &CheckReleased); container.erase(remove, container.end()); // Update existing data std::for_each(container.begin(), container.end(), &UpdateStates); } inputManager::InputState inputManager::keyState(Qt::Key key) { KeyContainer::iterator it = FindKey(key); return (it != sg_keyInstances.end()) ? it->second : InputInvalid; } inputManager::InputState inputManager::buttonState(Qt::MouseButton button) { ButtonContainer::iterator it = FindButton(button); return (it != sg_buttonInstances.end()) ? it->second : InputInvalid; } QPoint inputManager::mousePosition() { return sg_mouseCurrPosition; } QPoint inputManager::mouseTriggeredPosition() { return sg_mouseTriggeredPosition; } QPoint inputManager::mouseDelta() { return sg_mouseDelta; } void inputManager::setMouseTriggeredPosition() { sg_mouseTriggeredPosition = sg_mouseCurrPosition; } void inputManager::update(const QPoint &_localMousePos) { // Update Mouse Delta sg_mousePrevPosition = sg_mouseCurrPosition; sg_mouseCurrPosition = _localMousePos; sg_mouseDelta = sg_mouseCurrPosition - sg_mousePrevPosition; sg_mouseTriggeredDelta = sg_mouseCurrPosition - sg_mouseTriggeredPosition; Update(sg_buttonInstances); Update(sg_keyInstances); } void inputManager::registerKeyPress(int key) { // get interator KeyContainer::iterator it = FindKey((Qt::Key)key); // if Qt:key doenst exist yet add it to the container if (it == sg_keyInstances.end()) { sg_keyInstances.push_back(KeyInstance((Qt::Key)key, InputRegistered)); } } void inputManager::registerKeyRelease(int key) { KeyContainer::iterator it = FindKey((Qt::Key)key); if (it != sg_keyInstances.end()) { it->second = InputUnregistered; } } void inputManager::registerMousePress(Qt::MouseButton button) { ButtonContainer::iterator it = FindButton(button); if (it == sg_buttonInstances.end()) { sg_buttonInstances.push_back(ButtonInstance(button, InputRegistered)); } } void inputManager::registerMouseRelease(Qt::MouseButton button) { ButtonContainer::iterator it = FindButton(button); if (it != sg_buttonInstances.end()) { it->second = InputUnregistered; } } void inputManager::reset() { sg_keyInstances.clear(); sg_buttonInstances.clear(); } elasota/rdx2 #include #include "rdx_comp_sm.hpp" #include "rdx_comp_blocksort.hpp" #include "rdx_comp_mtf.hpp" #include "rdx_comp_config.hpp" #include "rdx_comp_rangecoder.hpp" #include "rdx_comp_rle.hpp" #include "../rdx/rdx_api.hpp" namespace rdxCompress { namespace bssm { const void *R5BlockSort(const void *input, void *tempspace, rdxUInt32 count, rdxUInt32 *pindex) { // Prep blocksort rdxUInt32 *arr1 = static_cast(tempspace); rdxUInt32 *arr2 = arr1 + count; memcpy(arr2, input, count); // Sort rdxUInt32 ftab[65537]; bssm::BlockSort(ftab, static_cast(count), 30, arr1, arr2); // Dump BWT output in the arr2 space const rdxUInt8 *inc = static_cast(input); rdxUInt8 *outc = static_cast(tempspace) + count*4; rdxUInt32 pi = 0; for(rdxUInt32 i=0;i(tempspace); rdxUInt8 *bitstream = finaloutput + headerSize; rdxLargeUInt bitstreamMax = count - headerSize; CRangeEnc rc; CSModelSet smodel; CRLE0EncStage rle0; CMTFStage mtf; rc.Init(); smodel.Init(); rle0.Init(); mtf.Init(); const rdxUInt8 *bitstreamBase = bitstream; for(rdxLargeUInt i=0;i(bwtoutput)[i], rle0, smodel, rc, &bitstream); if(static_cast(bitstream - bitstreamBase) >= bitstreamMax) return 0; } rle0.Flush(smodel, rc, &bitstream); if(static_cast(bitstream - bitstreamBase) >= bitstreamMax) return 0; rc.Flush(&bitstream); if(static_cast(bitstream - bitstreamBase) >= bitstreamMax) return 0; finaloutput[0] = static_cast(pindex >> 16); finaloutput[1] = static_cast(pindex >> 8); finaloutput[2] = static_cast(pindex); finaloutput[3] = static_cast(rle0.NumValuesEmitted() >> 16); finaloutput[4] = static_cast(rle0.NumValuesEmitted() >> 8); finaloutput[5] = static_cast(rle0.NumValuesEmitted() ); return static_cast(bitstream - bitstreamBase) + headerSize; } } } RDX_COMPRESSION_DYNLIB_API rdxLargeUInt rdxR5GetWorkBufferSize(rdxLargeUInt inputSize) { return inputSize * 8 + 160; } RDX_COMPRESSION_DYNLIB_API rdxLargeUInt rdxR5CompressBlock(const void *input, rdxLargeUInt size, void *workBuffer) { return rdxCompress::bssm::R5CompressBlock(input, size, workBuffer); } NMMI/qbmove-simulink // ----------------------------------------------------------------------------- // BSD 3-Clause License // // Copyright (c) 2015-2018, qbrobotics // 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 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. // ----------------------------------------------------------------------------- // File: qbemg.cpp // // Description: Communication s-function to obtain EMG measurements of qbHand. // To be used with RS-485 on a Virtual COM. //------------------------------------------------------------------------------ //============================================================================== // main definitions //============================================================================== #define S_FUNCTION_NAME qbemg #define S_FUNCTION_LEVEL 2 //============================================================================== // includes //============================================================================== #include "definitions.h" #include "simstruc.h" #include "../../../qbAPI/src/qbmove_communications.h" // #include //============================================================================== // definitions //============================================================================== //=============================================================== parameters #define params_qbot_id(i) ( mxGetPr( ssGetSFcnParam( S, 0 ) )[ \ i >= NUM_OF_QBOTS ? NUM_OF_QBOTS -1 : i ] ) #define params_daisy_chaining ( (bool)mxGetScalar( ssGetSFcnParam( S, 1 ) ) ) //=================================================================== inputs #if (defined(_WIN32) || defined(_WIN64)) #define in_handle ( *(const HANDLE* *)ssGetInputPortSignal( S, 0 ) )[0] #else #define in_handle ( *(const int* *)ssGetInputPortSignal( S, 0 ) )[0] #endif //================================================================== outputs #define out_emg_a ( ssGetOutputPortRealSignal ( S, 0 ) ) #define out_emg_b ( ssGetOutputPortRealSignal ( S, 1 ) ) #if (defined(_WIN32) || defined(_WIN64)) #define out_handle_single ( (HANDLE* *)ssGetOutputPortSignal( S, 0 ) )[0] #define out_handle_full ( (HANDLE* *)ssGetOutputPortSignal( S, 2 ) )[0] #else #define out_handle_single ( (int* *)ssGetOutputPortSignal( S, 0 ) )[0] #define out_handle_full ( (int* *)ssGetOutputPortSignal( S, 2 ) )[0] #endif //================================================================== dworks #define dwork_out(i) ( (real_T *)ssGetDWork( S, i ) ) //================================================================ constants #define BUFFER_SIZES 15 //============================================================= enumerations enum QBOT_MODE { PRIME_MOVERS_POS = 1, EQ_POS_AND_PRESET = 2 }; enum COMM_DIRS { RX = 1, TX = 2, BOTH = 3, NONE = 4 }; //=================================================================== macros #define NUM_OF_QBOTS ( (int)mxGetNumberOfElements( ssGetSFcnParam( S, 0 ) ) ) #define REF_A_WIDTH ssGetInputPortWidth( S, 1 ) #define REF_B_WIDTH ssGetInputPortWidth( S, 2 ) #define SIGN(x) ( ( (x) < 0) ? -1 : ( (x) > 0 ) ) //============================================================================== // function prototypes //============================================================================== unsigned char checksum_ ( unsigned char * buf, int size ); void showOutputHandle( SimStruct *S ); // unsigned int verifychecksum_( unsigned char * buffer ); //============================================================================== // mdlInitializeSizes //============================================================================== // The sizes information is used by Simulink to determine the S-function block's // characteristics (number of inputs, outputs, states, etc.). //============================================================================== static void mdlInitializeSizes( SimStruct *S ) { int_T status; // for new type definition DTypeId COM_HANDLE_id; // for new type definition #if (defined(_WIN32) || defined(_WIN64)) HANDLE handle_aux; // for new type definition #else int handle_aux; #endif int i; // for cycles //====================================================== new type definition COM_HANDLE_id = ssRegisterDataType( S, "COM_HANDLE" ); if( COM_HANDLE_id == INVALID_DTYPE_ID ) return; status = ssSetDataTypeSize( S, COM_HANDLE_id, sizeof(handle_aux) ); if( status == 0) return; status = ssSetDataTypeZero( S, COM_HANDLE_id, &handle_aux ); if( status == 0 ) return; //=================================================================== states ssSetNumContStates( S, 0 ); ssSetNumDiscStates( S, 1 ); //=============================================================== parameters ssSetNumSFcnParams( S, 2 ); // 2 parameters: // - qbot I2C id // - daisy chaining //=================================================================== inputs if ( !ssSetNumInputPorts( S, 1 ) ) return; /////////////////////////////////////// 0 ) pointer to HANDLE //////////////// ssSetInputPortWidth ( S, 0, DYNAMICALLY_SIZED ); ssSetInputPortDataType ( S, 0, COM_HANDLE_id ); ssSetInputPortDirectFeedThrough ( S, 0, 1 ); ssSetInputPortRequiredContiguous( S, 0, 1 ); //================================================================== outputs if(params_daisy_chaining) { if (!ssSetNumOutputPorts(S, 3)) return; ///////////////////////////////// 3 ) com handle //////////////////////////// ssSetOutputPortWidth ( S, 2, 1 ); ssSetOutputPortDataType( S, 2, COM_HANDLE_id ); } else { if (!ssSetNumOutputPorts(S, 2)) return; } //////////////////////////////// emg A ////////////////////////////// ssSetOutputPortWidth ( S, 0, NUM_OF_QBOTS ); ssSetOutputPortDataType ( S, 0, SS_DOUBLE ); //////////////////////////////// emg B ////////////////////////////// ssSetOutputPortWidth ( S, 1, NUM_OF_QBOTS ); ssSetOutputPortDataType ( S, 1, SS_DOUBLE ); //============================================================= sample times ssSetNumSampleTimes(S, 1); //============================================================= work vectors ssSetNumDWork(S, NUM_OF_QBOTS); // 0 dwork vector elements ssSetNumRWork(S, 0); // 0 real work vector elements ssSetNumIWork(S, 0); // 0 work vector elements ssSetNumPWork(S, 0); // 0 pwork vector elements: ssSetNumModes(S, 0); // 0 mode work vector elements ssSetNumNonsampledZCs(S, 0); // 0 nonsampled zero crossings for( i = 0; i < NUM_OF_QBOTS; ++i) { ssSetDWorkWidth(S, i, 4); ssSetDWorkDataType(S, i, SS_DOUBLE); } //=================================================================== others ssSetOptions(S, SS_OPTION_ALLOW_INPUT_SCALAR_EXPANSION); } //============================================================================== // mdlSetInputPortWidth //============================================================================== // This method is called with the candidate width for a dynamically sized port. // If the proposed width is acceptable, the actual port width is set using // ssSetInputPortWidth. //============================================================================== #undef MDL_SET_INPUT_PORT_WIDTH // Change to #undef to remove function #if defined(MDL_SET_INPUT_PORT_WIDTH) && defined(MATLAB_MEX_FILE) static void mdlSetInputPortWidth( SimStruct *S, int portIndex, int width ) { switch( portIndex ) { case 0: ssSetInputPortWidth( S, portIndex, 1 ); break; default: ssSetInputPortWidth( S, portIndex, width ); break; } } #endif /* MDL_SET_INPUT_PORT_WIDTH */ //============================================================================== // mdlSetOutputPortWidth //============================================================================== // This method is called with the candidate width for a dynamically sized port. // If the proposed width is acceptable, the actual port width is set using // ssSetOutputPortWidth. //============================================================================== #undef MDL_SET_OUTPUT_PORT_WIDTH // Change to #undef to remove function #if defined(MDL_SET_OUTPUT_PORT_WIDTH) && defined(MATLAB_MEX_FILE) static void mdlSetOutputPortWidth( SimStruct *S, int portIndex, int width ) { ssSetOutputPortWidth( S, portIndex, NUM_OF_QBOTS ); } #endif /* MDL_SET_OUTPUT_PORT_WIDTH */ //============================================================================== // mdlInitializeSampleTimes //============================================================================== // This function is used to specify the sample time(s) for your S-function. // o The sample times are specified as pairs "[sample_time, offset_time]" via // the following macros: // ssSetSampleTime(S, sampleTimePairIndex, sample_time) // ssSetOffsetTime(S, offsetTimePairIndex, offset_time) // Where sampleTimePairIndex starts at 0. // o A discrete function that changes at a specified rate should register the // discrete sample time pair // [discrete_sample_period, offset] // where // discrete_sample_period > 0.0 // and // 0.0 <= offset < discrete_sample_period //============================================================================== static void mdlInitializeSampleTimes( SimStruct *S ) { ssSetSampleTime(S, 0, INHERITED_SAMPLE_TIME); ssSetOffsetTime(S, 0, 0.0); } //============================================================================== // mdlStart //============================================================================== // This function is called once at start of model execution. //============================================================================== #define MDL_START // Change to #undef to remove function #if defined(MDL_START) static void mdlStart( SimStruct *S ) { } #endif /* MDL_START */ //============================================================================== // mdlOutputs //============================================================================== // Values are assigned to requested outputs in this function. //============================================================================== static void mdlOutputs( SimStruct *S, int_T tid ) { short int emg[2]; uint8_T qbot_id; // qbot id's comm_settings comm_settings_t; int i; //============================= should an output handle appear in the block? if(params_daisy_chaining) showOutputHandle(S); //==================================================== should we keep going? #if defined(_WIN32) || defined(_WIN64) if(in_handle == INVALID_HANDLE_VALUE) return; #else if(in_handle == -1) return; #endif //========================================== asking emg for each motor comm_settings_t.file_handle = in_handle; for(i = 0; i < NUM_OF_QBOTS; i++) { //============================================================ qbot ID check qbot_id = params_qbot_id(i); qbot_id = qbot_id <= 0 ? 1 : qbot_id; // inferior limit qbot_id = qbot_id >= 128 ? 127 : qbot_id; // superior limit out_emg_a[i] = dwork_out(i)[0]; out_emg_b[i] = dwork_out(i)[1]; if(!commGetEmg(&comm_settings_t, qbot_id, emg)) { out_emg_a[i] = (double) emg[0]; out_emg_b[i] = (double) emg[1]; dwork_out(i)[0] = out_emg_a[i]; dwork_out(i)[1] = out_emg_b[i]; } } } //============================================================================== // mdlUpdate //============================================================================== // This function is called once for every major integration time step. //============================================================================== #define MDL_UPDATE // Change to #undef to remove function #if defined(MDL_UPDATE) static void mdlUpdate( SimStruct *S, int_T tid ) { } #endif /* MDL_UPDATE */ //============================================================================== // mdlTerminate //============================================================================== // In this function, you should perform any actions that are necessary at the // termination of a simulation. //============================================================================== static void mdlTerminate( SimStruct *S ) { } //============================================================================== // showOutputHandle //============================================================================== // TODO //============================================================================== void showOutputHandle( SimStruct *S ) { #if (defined(_WIN32) || defined(_WIN64)) out_handle_full = (HANDLE *) &in_handle; // appear in output 3 #else out_handle_full = (int *) &in_handle; // appear in output 3 #endif } //============================================================================== // Required S-function trailer //============================================================================== #ifdef MATLAB_MEX_FILE // Is this file being compiled as a MEX-file? #include "simulink.c" // MEX-file interface mechanism #else #include "cg_sfun.h" // Code generation registration function #endif /** * The MIT License * * Copyright (c) 2020 (https://github.com/ilwoong) * * 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/mac/hmac.h" #include "../../include/hash/sha2.h" #include "../../include/util/hex.h" #include "../../include/util/console.h" #include "../test_vector_reader.h" using namespace mockup::crypto; using namespace mockup::crypto::hash; using namespace mockup::crypto::mac; using namespace mockup::crypto::util; static std::shared_ptr getMacInstance(int sha2size) { std::shared_ptr mac = nullptr; switch(sha2size) { case 256: mac = std::make_shared(std::make_shared()); break; case 512: mac = std::make_shared(std::make_shared()); break; default: break; } return mac; } static TestVectorReader getTestVector(std::string title) { std::ostringstream path; path << "testvector/sha2/"<< title << ".rsp"; TestVectorReader tvr; tvr.open(path.str()); return tvr; } static void print_verify_result(const std::string& title, size_t countPassed, size_t countTotal) { std::cout << title; std::cout << ((countPassed == countTotal) ? " passed" : " FAILED"); std::cout << std::dec; std::cout << " (" << countPassed << " / " << countTotal << ")" << std::endl; } static void test_hmac_sha2(int sha2size, int outsize) { auto mac = getMacInstance(sha2size); auto title = mac->name(); auto tvr = getTestVector(title); auto len = tvr.get("Count"); size_t countPassed = 0; for (int i = 0; i < len.size(); ++i) { auto key = tvr.getByteArray(i, "Key"); auto msg = tvr.getByteArray(i, "Msg"); auto tag = tvr.getByteArray(i, "Mac"); mac->init(key); mac->update(msg); auto digest = mac->doFinal(); if (std::equal(tag.begin(), tag.end(), digest.begin())) { countPassed += 1; } else { console_print("EXP", tag); console_print("BUT", digest); std::cout << std::endl; } } print_verify_result(title, countPassed, len.size()); } int main(int argc, const char** argv) { test_hmac_sha2(256, mockup::crypto::BIT_256); test_hmac_sha2(512, mockup::crypto::BIT_512); return 0; }include/bencode/detail/bview/conversion.hpp #pragma once #include #include #include "bencode/detail/symbol.hpp" #include "bencode/detail/utils.hpp" #include "bencode/detail/concepts.hpp" #include "bencode/detail/bad_conversion.hpp" #include "bencode/detail/bview/concepts.hpp" #include "bencode/detail/bview/bview.hpp" #include "bencode/detail/bview/accessors.hpp" namespace bencode::detail { namespace rng = std::ranges; template constexpr nonstd::expected convert_from_bview_default_integer_impl(customization_point_type, const bview& v) noexcept { if (!holds_integer(v)) [[unlikely]] return nonstd::make_unexpected(conversion_errc::not_integer_type); return static_cast(get_integer(v)); } // Conversion via iterators pair constructor template requires std::same_as, char> && std::constructible_from constexpr nonstd::expected convert_from_bview_default_string_impl( customization_point_type, const bview& b, priority_tag<2>) noexcept { if (!holds_string(b)) [[unlikely]] return nonstd::make_unexpected(conversion_errc::not_string_type); const auto& bstring = get_string(b); try { return T(rng::begin(bstring), rng::end(bstring)); } catch (...) { return nonstd::make_unexpected(conversion_errc::construction_error); } } // Conversion through std::string_view. template requires std::constructible_from constexpr nonstd::expected convert_from_bview_default_string_impl( customization_point_type, const bview& b, priority_tag<1>) noexcept { if (!holds_string(b)) [[unlikely]] return nonstd::make_unexpected(conversion_errc::not_string_type); try { return T(static_cast(get_string(b))); } catch (...) { return nonstd::make_unexpected(conversion_errc::construction_error); } } // Conversion of byte stringsauto template requires std::same_as, std::byte> && std::constructible_from constexpr nonstd::expected convert_from_bview_default_string_impl( customization_point_type, const bview& b, priority_tag<2>) noexcept { if (!holds_string(b)) [[unlikely]] return nonstd::make_unexpected(conversion_errc::not_string_type); const auto& bstring = get_string(b); try { return T(reinterpret_cast(rng::data(bstring)), reinterpret_cast(rng::data(bstring)+rng::size(bstring))); } catch (...) { return nonstd::make_unexpected(conversion_errc::construction_error); } } // Conversion to list like types supporting front_inserter/back_inserter/inserter. template requires std::constructible_from && rng::range && retrievable_from_bview> && (supports_back_inserter || supports_front_inserter || supports_inserter) constexpr nonstd::expected convert_from_bview_default_list_impl( customization_point_type, const bview& bv, priority_tag<1>) noexcept { if (!holds_list(bv)) [[unlikely]] return nonstd::make_unexpected(conversion_errc::not_list_type); auto& blist = get_list(bv); T value {}; if constexpr (rng::sized_range && has_reserve_member) { value.reserve(rng::size(blist)); } auto func = [](auto&& x) -> decltype(auto) { return get_as>(x); }; try { if constexpr (supports_back_inserter) { std::transform(rng::begin(blist), rng::end(blist), std::back_inserter(value), func); } else if constexpr (supports_front_inserter) { std::transform(rng::rbegin(blist), rng::rend(blist), std::front_inserter(value), func); } else if constexpr (supports_inserter) { std::transform(rng::begin(blist), rng::end(blist), std::inserter(value, rng::begin(value)), func); } } catch (const bad_conversion& e) { return nonstd::make_unexpected(e.errc()); } catch (...) { return nonstd::make_unexpected(conversion_errc::construction_error); } return value; } // Conversion to std::tuple, std::pair, array template requires has_tuple_like_structured_binding && convertible_from_bview_to_tuple_elements constexpr nonstd::expected convert_from_bview_default_list_impl( customization_point_type, const bview& b, priority_tag<0>) noexcept { if (!holds_list(b)) [[unlikely]] return nonstd::make_unexpected(conversion_errc::not_list_type); auto& blist = get_list(b); if (rng::size(blist) != std::tuple_size_v) [[unlikely]] { return nonstd::make_unexpected(conversion_errc::size_mismatch); } T out {}; try { std::apply( [&](std::index_sequence&&) constexpr { using std::get; ( (get(out) = get_as>(blist[IS])) , ... ); }, std::forward_as_tuple(std::make_index_sequence>{}) ); } catch (const bad_conversion& e) { return nonstd::make_unexpected(conversion_errc::list_value_type_construction_error); } catch (...) { return nonstd::make_unexpected(conversion_errc::construction_error); } return out; } // Dict conversion template requires key_value_associative_container && retrievable_from_bview && std::constructible_from inline constexpr nonstd::expected convert_from_bview_default_dict_impl( customization_point_type, const bview& b, priority_tag<0>) noexcept { if (!holds_dict(b)) [[unlikely]] return nonstd::make_unexpected(conversion_errc::not_dict_type); auto& bdict = get_dict(b); T out{}; try { for ( auto&& [k, v] : bdict) { out.emplace(k, get_as(v)); } } catch (const bad_conversion& e) { return nonstd::make_unexpected(conversion_errc::dict_mapped_type_construction_error); } catch (...) { return nonstd::make_unexpected(conversion_errc::construction_error); } return out; } // multimap style template requires key_value_associative_container && retrievable_from_bview && std::constructible_from && ( is_instantiation_of_v || is_instantiation_of_v) inline constexpr nonstd::expected convert_from_bview_default_dict_impl( customization_point_type, const bview& b, priority_tag<0>) noexcept { if (!holds_dict(b)) [[unlikely]] return nonstd::make_unexpected(conversion_errc::not_dict_type); T out{}; auto& bdict = get_dict(b); try { for (auto&& [k, v] : bdict) { if (holds_list(v)) { for (auto&& v2 : get_list(v)) { out.emplace(k, get_as(v2)); } } else { out.emplace(k, get_as(v)); } } } catch (const bad_conversion& e) { return nonstd::make_unexpected(conversion_errc::dict_mapped_type_construction_error); } catch (...) { return nonstd::make_unexpected(conversion_errc::construction_error); } return out; } template requires requires () { typename std::pointer_traits::element_type; } inline nonstd::expected convert_from_bview_to_pointer_impl(customization_point_type, const bview& b) noexcept { using E = typename std::pointer_traits::element_type; // default construct pointer type auto result = convert_from_bview_to(b); if (!result.has_value()) { return nonstd::make_unexpected(result.error()); } using E = typename std::pointer_traits::element_type; if constexpr (std::same_as>) { return std::make_unique(std::move(*result)); } else if constexpr (std::same_as>) { return std::make_shared(std::move(*result)); } else { return T(new E(std::move(*result))); } } template constexpr nonstd::expected convert_from_bview_to_impl_dispatcher(customization_point_type, const bview& b) noexcept { // Use bencode::serialisation_traits to split the overload set per bencode_type bvalue. // This makes build errors easier to debug since we have to check less candidates. if constexpr (serialization_traits::type == bencode_type::integer) { return convert_from_bview_default_integer_impl(customization_for, b); } else if constexpr (serialization_traits::type == bencode_type::string) { return convert_from_bview_default_string_impl(customization_for, b, priority_tag<5>{}); } else if constexpr (serialization_traits::type == bencode_type::list) { return convert_from_bview_default_list_impl(customization_for, b, priority_tag<5>{}); } else if constexpr (serialization_traits::type == bencode_type::dict) { return convert_from_bview_default_dict_impl(customization_for, b, priority_tag<5>{}); } else { static_assert(detail::always_false::value, "no serializer for T found, check if the correct trait class is included!"); } } template constexpr nonstd::expected convert_from_bview_to(const bview& ref) { // Check if there is a user-provided specialization found by ADL. if constexpr (conversion_from_bview_is_adl_overloaded) { return bencode_convert_from_bview(customization_for, ref); } else if constexpr (serialization_traits::is_pointer) { return convert_from_bview_to_pointer_impl(customization_for, ref); } else { return convert_from_bview_to_impl_dispatcher(customization_for, ref); } return nonstd::make_unexpected(conversion_errc::undefined_conversion); } } // namespace bencode::detail /********************************************//** * Author: * Desc: strange language ***********************************************/ #include using namespace std; int main() { int i = 1; for(int i = 0; i < 10; i++); const int LEN = 1000; char frase[LEN]; cout << "Dai una frase (termina con a capo): "; cin.getline(frase,LEN); for(int i = 0; frase[i] != '\0' && i < LEN; i++) { if((frase[i] >= 'A') && (frase[i] <= 'Z')) frase[i] += 32; if((frase[i] == 'a') || (frase[i] == 'e') || (frase[i] == 'i') || (frase[i] == 'u') || (frase[i] == 'o')) cout << frase[i] << "f" << frase[i]; else cout << frase[i]; } cout << endl; return 0; } // Copyright (C) 2010-2015 // See the file COPYING for copying permission. #pragma once #include #include #include #include #include #include #include #include #include #include #include #include #include // TODO: Add tests. namespace hadesmem { class Relocation { public: explicit Relocation(Process const& process, PeFile const& pe_file, std::uint16_t* base) : process_{&process}, pe_file_{&pe_file}, base_{reinterpret_cast(base)} { UpdateRead(); } explicit Relocation(Process const&& process, PeFile const& pe_file, std::uint16_t* base) = delete; explicit Relocation(Process const& process, PeFile&& pe_file, std::uint16_t* base) = delete; explicit Relocation(Process const&& process, PeFile&& pe_file, std::uint16_t* base) = delete; void* GetBase() const noexcept { return base_; } void UpdateRead() { auto const data_tmp = Read(*process_, base_); type_ = static_cast(data_tmp >> 12); offset_ = data_tmp & 0x0FFF; } void UpdateWrite() { auto const data_tmp = static_cast(static_cast(offset_) | (static_cast(type_) << 12)); Write(*process_, base_, data_tmp); } std::uint8_t GetType() const noexcept { return type_; } void SetType(std::uint8_t type) noexcept { type_ = type; } std::uint16_t GetOffset() const noexcept { return offset_; } void SetOffset(std::uint16_t offset) noexcept { offset_ = offset; } private: Process const* process_; PeFile const* pe_file_; std::uint8_t* base_; std::uint8_t type_{}; std::uint16_t offset_{}; }; inline bool operator==(Relocation const& lhs, Relocation const& rhs) noexcept { return lhs.GetBase() == rhs.GetBase(); } inline bool operator!=(Relocation const& lhs, Relocation const& rhs) noexcept { return !(lhs == rhs); } inline bool operator<(Relocation const& lhs, Relocation const& rhs) noexcept { return lhs.GetBase() < rhs.GetBase(); } inline bool operator<=(Relocation const& lhs, Relocation const& rhs) noexcept { return lhs.GetBase() <= rhs.GetBase(); } inline bool operator>(Relocation const& lhs, Relocation const& rhs) noexcept { return lhs.GetBase() > rhs.GetBase(); } inline bool operator>=(Relocation const& lhs, Relocation const& rhs) noexcept { return lhs.GetBase() >= rhs.GetBase(); } inline std::ostream& operator<<(std::ostream& lhs, Relocation const& rhs) { std::locale const old = lhs.imbue(std::locale::classic()); lhs << rhs.GetBase(); lhs.imbue(old); return lhs; } inline std::wostream& operator<<(std::wostream& lhs, Relocation const& rhs) { std::locale const old = lhs.imbue(std::locale::classic()); lhs << rhs.GetBase(); lhs.imbue(old); return lhs; } } /****************************************************************************** * 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/canbus/vehicle/gem/gem_controller.h" #include #include "modules/common/proto/vehicle_signal.pb.h" #include "cyber/common/log.h" #include "modules/canbus/vehicle/gem/gem_message_manager.h" #include "modules/canbus/vehicle/vehicle_controller.h" #include "modules/common/time/time.h" #include "modules/drivers/canbus/can_comm/can_sender.h" #include "modules/drivers/canbus/can_comm/protocol_data.h" namespace apollo { namespace canbus { namespace gem { using ::apollo::common::ErrorCode; using ::apollo::control::ControlCommand; using ::apollo::drivers::canbus::ProtocolData; namespace { const int32_t kMaxFailAttempt = 10; const int32_t CHECK_RESPONSE_STEER_UNIT_FLAG = 1; const int32_t CHECK_RESPONSE_SPEED_UNIT_FLAG = 2; } // namespace ErrorCode GemController::Init( const VehicleParameter& params, CanSender<::apollo::canbus::ChassisDetail>* const can_sender, MessageManager<::apollo::canbus::ChassisDetail>* const message_manager) { if (is_initialized_) { AINFO << "GemController has already been initialized."; return ErrorCode::CANBUS_ERROR; } vehicle_params_.CopyFrom( common::VehicleConfigHelper::Instance()->GetConfig().vehicle_param()); params_.CopyFrom(params); if (!params_.has_driving_mode()) { AERROR << "Vehicle conf pb not set driving_mode."; return ErrorCode::CANBUS_ERROR; } if (can_sender == nullptr) { return ErrorCode::CANBUS_ERROR; } can_sender_ = can_sender; if (message_manager == nullptr) { AERROR << "Protocol manager is null."; return ErrorCode::CANBUS_ERROR; } message_manager_ = message_manager; // Sender part brake_cmd_6b_ = dynamic_cast( message_manager_->GetMutableProtocolDataById(Brakecmd6b::ID)); if (brake_cmd_6b_ == nullptr) { AERROR << "Brakecmd6b does not exist in the GemMessageManager!"; return ErrorCode::CANBUS_ERROR; } accel_cmd_67_ = dynamic_cast( message_manager_->GetMutableProtocolDataById(Accelcmd67::ID)); if (accel_cmd_67_ == nullptr) { AERROR << "Accelcmd67 does not exist in the GemMessageManager!"; return ErrorCode::CANBUS_ERROR; } steering_cmd_6d_ = dynamic_cast( message_manager_->GetMutableProtocolDataById(Steeringcmd6d::ID)); if (steering_cmd_6d_ == nullptr) { AERROR << "Steeringcmd6d does not exist in the GemMessageManager!"; return ErrorCode::CANBUS_ERROR; } shift_cmd_65_ = dynamic_cast( message_manager_->GetMutableProtocolDataById(Shiftcmd65::ID)); if (shift_cmd_65_ == nullptr) { AERROR << "Shiftcmd65 does not exist in the GemMessageManager!"; return ErrorCode::CANBUS_ERROR; } turn_cmd_63_ = dynamic_cast( message_manager_->GetMutableProtocolDataById(Turncmd63::ID)); if (turn_cmd_63_ == nullptr) { AERROR << "Turncmd63 does not exist in the GemMessageManager!"; return ErrorCode::CANBUS_ERROR; } global_cmd_69_ = dynamic_cast( message_manager_->GetMutableProtocolDataById(Globalcmd69::ID)); if (global_cmd_69_ == nullptr) { AERROR << "Turncmd63 does not exist in the GemMessageManager!"; return ErrorCode::CANBUS_ERROR; } can_sender_->AddMessage(Brakecmd6b::ID, brake_cmd_6b_, false); can_sender_->AddMessage(Accelcmd67::ID, accel_cmd_67_, false); can_sender_->AddMessage(Steeringcmd6d::ID, steering_cmd_6d_, false); can_sender_->AddMessage(Shiftcmd65::ID, shift_cmd_65_, false); can_sender_->AddMessage(Turncmd63::ID, turn_cmd_63_, false); can_sender_->AddMessage(Globalcmd69::ID, global_cmd_69_, false); // Need to sleep to ensure all messages received. AINFO << "GemController is initialized."; is_initialized_ = true; return ErrorCode::OK; } GemController::~GemController() {} bool GemController::Start() { if (!is_initialized_) { AERROR << "GemController has NOT been initiated."; return false; } const auto& update_func = [this] { SecurityDogThreadFunc(); }; thread_.reset(new std::thread(update_func)); return true; } void GemController::Stop() { if (!is_initialized_) { AERROR << "GemController stops or starts improperly!"; return; } if (thread_ != nullptr && thread_->joinable()) { thread_->join(); thread_.reset(); AINFO << "GemController stopped."; } } Chassis GemController::chassis() { chassis_.Clear(); ChassisDetail chassis_detail; message_manager_->GetSensorData(&chassis_detail); // 21, 22, previously 1, 2 if (driving_mode() == Chassis::EMERGENCY_MODE) { set_chassis_error_code(Chassis::NO_ERROR); } chassis_.set_driving_mode(driving_mode()); chassis_.set_error_code(chassis_error_code()); // 3 chassis_.set_engine_started(true); // 5 if (chassis_detail.gem().has_vehicle_speed_rpt_6f() && chassis_detail.gem().vehicle_speed_rpt_6f().has_vehicle_speed()) { chassis_.set_speed_mps(static_cast( chassis_detail.gem().vehicle_speed_rpt_6f().vehicle_speed())); } else { chassis_.set_speed_mps(0); } // 7 chassis_.set_fuel_range_m(0); // 8 if (chassis_detail.gem().has_accel_rpt_68() && chassis_detail.gem().accel_rpt_68().has_output_value()) { chassis_.set_throttle_percentage( static_cast(chassis_detail.gem().accel_rpt_68().output_value())); } else { chassis_.set_throttle_percentage(0); } // 9 if (chassis_detail.gem().has_brake_rpt_6c() && chassis_detail.gem().brake_rpt_6c().has_output_value()) { chassis_.set_brake_percentage( static_cast(chassis_detail.gem().brake_rpt_6c().output_value())); } else { chassis_.set_brake_percentage(0); } // 23, previously 10 if (chassis_detail.gem().has_shift_rpt_66() && chassis_detail.gem().shift_rpt_66().has_output_value()) { Chassis::GearPosition gear_pos = Chassis::GEAR_INVALID; if (chassis_detail.gem().shift_rpt_66().output_value() == Shift_rpt_66::OUTPUT_VALUE_NEUTRAL) { gear_pos = Chassis::GEAR_NEUTRAL; } if (chassis_detail.gem().shift_rpt_66().output_value() == Shift_rpt_66::OUTPUT_VALUE_REVERSE) { gear_pos = Chassis::GEAR_REVERSE; } if (chassis_detail.gem().shift_rpt_66().output_value() == Shift_rpt_66::OUTPUT_VALUE_FORWARD) { gear_pos = Chassis::GEAR_DRIVE; } chassis_.set_gear_location(gear_pos); } else { chassis_.set_gear_location(Chassis::GEAR_NONE); } // 11 // TODO(QiL) : verify the unit here. if (chassis_detail.gem().has_steering_rpt_1_6e() && chassis_detail.gem().steering_rpt_1_6e().has_output_value()) { chassis_.set_steering_percentage(static_cast( chassis_detail.gem().steering_rpt_1_6e().output_value() * 100.0 / vehicle_params_.max_steer_angle())); } else { chassis_.set_steering_percentage(0); } if (chassis_detail.gem().has_global_rpt_6a() && chassis_detail.gem().global_rpt_6a().has_pacmod_status()) { if (chassis_detail.gem().global_rpt_6a().pacmod_status() == Global_rpt_6a::PACMOD_STATUS_CONTROL_ENABLED) { chassis_.set_driving_mode(Chassis::COMPLETE_AUTO_DRIVE); global_cmd_69_->set_clear_override( Global_cmd_69::CLEAR_OVERRIDE_DON_T_CLEAR_ACTIVE_OVERRIDES); } else { chassis_.set_driving_mode(Chassis::COMPLETE_MANUAL); } } else { chassis_.set_driving_mode(Chassis::COMPLETE_MANUAL); } // TODO(QiL) : implement the turn light signal here // 16, 17 if (chassis_detail.has_light() && chassis_detail.light().has_turn_light_type() && chassis_detail.light().turn_light_type() != Light::TURN_LIGHT_OFF) { if (chassis_detail.light().turn_light_type() == Light::TURN_LEFT_ON) { chassis_.mutable_signal()->set_turn_signal( common::VehicleSignal::TURN_LEFT); } else if (chassis_detail.light().turn_light_type() == Light::TURN_RIGHT_ON) { chassis_.mutable_signal()->set_turn_signal( common::VehicleSignal::TURN_RIGHT); } else { chassis_.mutable_signal()->set_turn_signal( common::VehicleSignal::TURN_NONE); } } else { chassis_.mutable_signal()->set_turn_signal( common::VehicleSignal::TURN_NONE); } // TODO(all): implement the rest here/ // 26 if (chassis_error_mask_) { chassis_.set_chassis_error_mask(chassis_error_mask_); } // Give engage_advice based on error_code and canbus feedback if (!chassis_error_mask_ && !chassis_.parking_brake() && chassis_.throttle_percentage() == 0.0 && chassis_.brake_percentage() != 0.0) { chassis_.mutable_engage_advice()->set_advice( apollo::common::EngageAdvice::READY_TO_ENGAGE); } else { chassis_.mutable_engage_advice()->set_advice( apollo::common::EngageAdvice::DISALLOW_ENGAGE); chassis_.mutable_engage_advice()->set_reason( "CANBUS not ready, firmware error or emergency button pressed!"); } return chassis_; } void GemController::Emergency() { set_driving_mode(Chassis::EMERGENCY_MODE); ResetProtocol(); set_chassis_error_code(Chassis::CHASSIS_ERROR); } ErrorCode GemController::EnableAutoMode() { if (driving_mode() == Chassis::COMPLETE_AUTO_DRIVE) { AINFO << "Already in COMPLETE_AUTO_DRIVE mode"; return ErrorCode::OK; } global_cmd_69_->set_pacmod_enable( Global_cmd_69::PACMOD_ENABLE_CONTROL_ENABLED); global_cmd_69_->set_clear_override( Global_cmd_69::CLEAR_OVERRIDE_CLEAR_ACTIVE_OVERRIDES); can_sender_->Update(); const int32_t flag = CHECK_RESPONSE_STEER_UNIT_FLAG | CHECK_RESPONSE_SPEED_UNIT_FLAG; if (!CheckResponse(flag, true)) { AERROR << "Failed to switch to COMPLETE_AUTO_DRIVE mode."; Emergency(); set_chassis_error_code(Chassis::CHASSIS_ERROR); return ErrorCode::CANBUS_ERROR; } set_driving_mode(Chassis::COMPLETE_AUTO_DRIVE); AINFO << "Switch to COMPLETE_AUTO_DRIVE mode ok."; return ErrorCode::OK; } ErrorCode GemController::DisableAutoMode() { ResetProtocol(); can_sender_->Update(); set_driving_mode(Chassis::COMPLETE_MANUAL); set_chassis_error_code(Chassis::NO_ERROR); AINFO << "Switch to COMPLETE_MANUAL ok."; return ErrorCode::OK; } ErrorCode GemController::EnableSteeringOnlyMode() { AFATAL << "Not supported!"; return ErrorCode::OK; } ErrorCode GemController::EnableSpeedOnlyMode() { AFATAL << "Not supported!"; return ErrorCode::OK; } // NEUTRAL, REVERSE, DRIVE void GemController::Gear(Chassis::GearPosition gear_position) { if (driving_mode() != Chassis::COMPLETE_AUTO_DRIVE && driving_mode() != Chassis::AUTO_SPEED_ONLY) { AINFO << "This drive mode no need to set gear."; return; } switch (gear_position) { case Chassis::GEAR_NEUTRAL: { shift_cmd_65_->set_shift_cmd(Shift_cmd_65::SHIFT_CMD_NEUTRAL); break; } case Chassis::GEAR_REVERSE: { shift_cmd_65_->set_shift_cmd(Shift_cmd_65::SHIFT_CMD_REVERSE); break; } case Chassis::GEAR_DRIVE: { shift_cmd_65_->set_shift_cmd(Shift_cmd_65::SHIFT_CMD_FORWARD); break; } case Chassis::GEAR_INVALID: { AERROR << "Gear command is invalid!"; shift_cmd_65_->set_shift_cmd(Shift_cmd_65::SHIFT_CMD_NEUTRAL); break; } default: { shift_cmd_65_->set_shift_cmd(Shift_cmd_65::SHIFT_CMD_NEUTRAL); break; } } } // brake with new acceleration // acceleration:0.00~99.99, unit: // acceleration:0.0 ~ 7.0, unit:m/s^2 // acceleration_spd:60 ~ 100, suggest: 90 // -> pedal void GemController::Brake(double pedal) { // double real_value = params_.max_acc() * acceleration / 100; // TODO(QiL) Update brake value based on mode if (driving_mode() != Chassis::COMPLETE_AUTO_DRIVE && driving_mode() != Chassis::AUTO_SPEED_ONLY) { AINFO << "The current drive mode does not need to set acceleration."; return; } brake_cmd_6b_->set_brake_cmd(pedal / 100.0); } // drive with old acceleration // gas:0.00~99.99 unit: void GemController::Throttle(double pedal) { if (driving_mode() != Chassis::COMPLETE_AUTO_DRIVE && driving_mode() != Chassis::AUTO_SPEED_ONLY) { AINFO << "The current drive mode does not need to set acceleration."; return; } accel_cmd_67_->set_accel_cmd(pedal / 100.0); } // drive with acceleration/deceleration // acc:-7.0 ~ 5.0, unit:m/s^2 void GemController::Acceleration(double acc) { if (driving_mode() != Chassis::COMPLETE_AUTO_DRIVE && driving_mode() != Chassis::AUTO_SPEED_ONLY) { AINFO << "The current drive mode does not need to set acceleration."; return; } // None } // gem default, -470 ~ 470, left:+, right:- // need to be compatible with control module, so reverse // steering with old angle speed // angle:-99.99~0.00~99.99, unit:, left:-, right:+ void GemController::Steer(double angle) { if (driving_mode() != Chassis::COMPLETE_AUTO_DRIVE && driving_mode() != Chassis::AUTO_STEER_ONLY) { AINFO << "The current driving mode does not need to set steer."; return; } const double real_angle = vehicle_params_.max_steer_angle() * angle / 100.0; steering_cmd_6d_->set_position_value(real_angle)->set_speed_limit(9.0); } // steering with new angle speed // angle:-99.99~0.00~99.99, unit:, left:-, right:+ // angle_spd:0.00~99.99, unit:deg/s void GemController::Steer(double angle, double angle_spd) { if (driving_mode() != Chassis::COMPLETE_AUTO_DRIVE && driving_mode() != Chassis::AUTO_STEER_ONLY) { AINFO << "The current driving mode does not need to set steer."; return; } const double real_angle = vehicle_params_.max_steer_angle() * angle / 100.0; const double real_angle_spd = ProtocolData<::apollo::canbus::ChassisDetail>::BoundedValue( vehicle_params_.min_steer_angle_rate(), vehicle_params_.max_steer_angle_rate(), vehicle_params_.max_steer_angle_rate() * angle_spd / 100.0); steering_cmd_6d_->set_position_value(real_angle) ->set_speed_limit(real_angle_spd); } void GemController::SetEpbBreak(const ControlCommand& command) { if (command.parking_brake()) { // None } else { // None } } void GemController::SetBeam(const ControlCommand& command) { if (command.signal().high_beam()) { // None } else if (command.signal().low_beam()) { // None } else { // None } } void GemController::SetHorn(const ControlCommand& command) { if (command.signal().horn()) { // None } else { // None } } void GemController::SetTurningSignal(const ControlCommand& command) { // Set Turn Signal auto signal = command.signal().turn_signal(); if (signal == common::VehicleSignal::TURN_LEFT) { turn_cmd_63_->set_turn_signal_cmd(Turn_cmd_63::TURN_SIGNAL_CMD_LEFT); } else if (signal == common::VehicleSignal::TURN_RIGHT) { turn_cmd_63_->set_turn_signal_cmd(Turn_cmd_63::TURN_SIGNAL_CMD_RIGHT); } else { turn_cmd_63_->set_turn_signal_cmd(Turn_cmd_63::TURN_SIGNAL_CMD_NONE); } } void GemController::ResetProtocol() { message_manager_->ResetSendMessages(); } bool GemController::CheckChassisError() { // TODO(QiL) : implement it here return false; } void GemController::SecurityDogThreadFunc() { int32_t vertical_ctrl_fail = 0; int32_t horizontal_ctrl_fail = 0; if (can_sender_ == nullptr) { AERROR << "Failed to run SecurityDogThreadFunc() because can_sender_ is " "nullptr."; return; } while (!can_sender_->IsRunning()) { std::this_thread::yield(); } std::chrono::duration default_period{50000}; int64_t start = 0; int64_t end = 0; while (can_sender_->IsRunning()) { start = ::apollo::common::time::AsInt64<::apollo::common::time::micros>( ::apollo::common::time::Clock::Now()); const Chassis::DrivingMode mode = driving_mode(); bool emergency_mode = false; // 1. horizontal control check if ((mode == Chassis::COMPLETE_AUTO_DRIVE || mode == Chassis::AUTO_STEER_ONLY) && !CheckResponse(CHECK_RESPONSE_STEER_UNIT_FLAG, false)) { ++horizontal_ctrl_fail; if (horizontal_ctrl_fail >= kMaxFailAttempt) { emergency_mode = true; set_chassis_error_code(Chassis::MANUAL_INTERVENTION); } } else { horizontal_ctrl_fail = 0; } // 2. vertical control check if ((mode == Chassis::COMPLETE_AUTO_DRIVE || mode == Chassis::AUTO_SPEED_ONLY) && !CheckResponse(CHECK_RESPONSE_SPEED_UNIT_FLAG, false)) { ++vertical_ctrl_fail; if (vertical_ctrl_fail >= kMaxFailAttempt) { emergency_mode = true; set_chassis_error_code(Chassis::MANUAL_INTERVENTION); } } else { vertical_ctrl_fail = 0; } if (CheckChassisError()) { set_chassis_error_code(Chassis::CHASSIS_ERROR); emergency_mode = true; } if (emergency_mode && mode != Chassis::EMERGENCY_MODE) { set_driving_mode(Chassis::EMERGENCY_MODE); message_manager_->ResetSendMessages(); } end = ::apollo::common::time::AsInt64<::apollo::common::time::micros>( ::apollo::common::time::Clock::Now()); std::chrono::duration elapsed{end - start}; if (elapsed < default_period) { std::this_thread::sleep_for(default_period - elapsed); } else { AERROR << "Too much time consumption in GemController looping process:" << elapsed.count(); } } } bool GemController::CheckResponse(const int32_t flags, bool need_wait) { /* ADD YOUR OWN CAR CHASSIS OPERATION */ return true; } void GemController::set_chassis_error_mask(const int32_t mask) { std::lock_guard lock(chassis_mask_mutex_); chassis_error_mask_ = mask; } int32_t GemController::chassis_error_mask() { std::lock_guard lock(chassis_mask_mutex_); return chassis_error_mask_; } Chassis::ErrorCode GemController::chassis_error_code() { std::lock_guard lock(chassis_error_code_mutex_); return chassis_error_code_; } void GemController::set_chassis_error_code( const Chassis::ErrorCode& error_code) { std::lock_guard lock(chassis_error_code_mutex_); chassis_error_code_ = error_code; } } // namespace gem } // namespace canbus } // namespace apollo 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 SHARE_SCHEMA #include "share/schema/ob_dependency_info.h" #include "ob_schema_getter_guard.h" #include "lib/mysqlclient/ob_mysql_transaction.h" #include "lib/string/ob_sql_string.h" #include "share/ob_dml_sql_splicer.h" #include "share/schema/ob_schema_utils.h" #include "observer/ob_server_struct.h" #include "share/schema/ob_schema_struct.h" #include "share/inner_table/ob_inner_table_schema_constants.h" namespace oceanbase { using namespace common; namespace share { namespace schema { ObDependencyInfo::ObDependencyInfo() { reset(); } ObDependencyInfo::ObDependencyInfo(ObIAllocator* allocator) : ObSchema(allocator) { reset(); } ObDependencyInfo::ObDependencyInfo(const ObDependencyInfo& src_schema) : ObSchema() { reset(); *this = src_schema; } ObDependencyInfo::~ObDependencyInfo() {} ObDependencyInfo& ObDependencyInfo::operator=(const ObDependencyInfo& src_schema) { if (this != &src_schema) { reset(); int& ret = error_ret_; tenant_id_ = src_schema.tenant_id_; dep_obj_id_ = src_schema.dep_obj_id_; dep_obj_type_ = src_schema.dep_obj_type_; order_ = src_schema.order_; dep_timestamp_ = src_schema.dep_timestamp_; ref_obj_id_ = src_schema.ref_obj_id_; ref_obj_type_ = src_schema.ref_obj_type_; ref_timestamp_ = src_schema.ref_timestamp_; dep_obj_owner_id_ = src_schema.dep_obj_owner_id_; property_ = src_schema.property_; schema_version_ = src_schema.schema_version_; if (OB_FAIL(deep_copy_str(src_schema.dep_attrs_, dep_attrs_))) { LOG_WARN("deep copy attr text failed", K(ret), K(src_schema.dep_attrs_)); } else if (OB_FAIL(deep_copy_str(src_schema.dep_reason_, dep_reason_))) { LOG_WARN("deep copy reason text failed", K(ret), K(src_schema.dep_reason_)); } else if (OB_FAIL(deep_copy_str(src_schema.ref_obj_name_, ref_obj_name_))) { LOG_WARN("deep copy ref obj name failed", K(ret), K(src_schema.ref_obj_name_)); } error_ret_ = ret; } return *this; } int ObDependencyInfo::assign(const ObDependencyInfo& other) { int ret = OB_SUCCESS; this->operator=(other); ret = this->error_ret_; return ret; } bool ObDependencyInfo::is_user_field_valid() const { bool ret = false; if (ObSchema::is_valid()) { ret = (OB_INVALID_ID != tenant_id_); } return ret; } bool ObDependencyInfo::is_valid() const { bool ret = false; if (ObSchema::is_valid()) { if (is_user_field_valid()) { ret = (OB_INVALID_ID != dep_obj_id_) && (OB_INVALID_ID != ref_obj_id_) && (OB_INVALID_VERSION != schema_version_); } else { } } else { } return ret; } int ObDependencyInfo::gen_dependency_dml(const uint64_t exec_tenant_id, ObDMLSqlSplicer& dml) { int ret = OB_SUCCESS; const ObDependencyInfo& dep_info = *this; // uint64_t ref_obj_id = OB_SYS_TENANT_ID == common::extract_tenant_id(dep_info.get_ref_obj_id()) ? // dep_info.get_ref_obj_id() : // extract_obj_id(exec_tenant_id, dep_info.get_ref_obj_id()); if (OB_FAIL(dml.add_pk_column("tenant_id", ObSchemaUtils::get_extract_tenant_id(exec_tenant_id, tenant_id_))) || OB_FAIL(dml.add_pk_column("dep_obj_id", extract_obj_id(exec_tenant_id, dep_info.get_dep_obj_id()))) || OB_FAIL(dml.add_pk_column("dep_obj_type", dep_info.get_dep_obj_type())) || OB_FAIL(dml.add_pk_column("dep_order", dep_info.get_order())) || OB_FAIL(dml.add_column("schema_version", dep_info.get_schema_version())) || OB_FAIL(dml.add_time_column("dep_timestamp", dep_info.get_dep_timestamp())) || OB_FAIL(dml.add_column("ref_obj_id", extract_ref_obj_id())) || OB_FAIL(dml.add_column("ref_obj_type", dep_info.get_ref_obj_type())) || OB_FAIL(dml.add_time_column("ref_timestamp", dep_info.get_ref_timestamp())) || OB_FAIL(dml.add_column("dep_obj_owner_id", extract_obj_id(exec_tenant_id, dep_info.get_dep_obj_owner_id()))) || OB_FAIL(dml.add_column("property", dep_info.get_property())) || OB_FAIL(dml.add_column("dep_attrs", ObHexEscapeSqlStr(dep_info.get_dep_attrs()))) || OB_FAIL(dml.add_column("dep_reason", ObHexEscapeSqlStr(dep_info.get_dep_reason()))) || OB_FAIL(dml.add_column("ref_obj_name", ObHexEscapeSqlStr(dep_info.get_ref_obj_name()))) || OB_FAIL(dml.add_gmt_create()) || OB_FAIL(dml.add_gmt_modified())) { LOG_WARN("add column failed", K(ret)); } return ret; } // The ref obj id may be the id of a system package. // This id is under the system tenant and has a tenant id, // so special treatment is required here. uint64_t ObDependencyInfo::extract_ref_obj_id() const { uint64_t ref_oid = get_ref_obj_id(); if (OB_SYS_TENANT_ID != common::extract_tenant_id(ref_oid)) { const uint64_t tenant_id = get_tenant_id(); const uint64_t exec_tenant_id = ObSchemaUtils::get_exec_tenant_id(tenant_id); ref_oid = ObSchemaUtils::get_extract_schema_id(exec_tenant_id, get_ref_obj_id()); } return ref_oid; } uint64_t ObDependencyInfo::extract_obj_id(uint64_t exec_tenant_id, uint64_t id) { return ObSchemaUtils::get_extract_schema_id(exec_tenant_id, id); } int ObDependencyInfo::get_object_create_time( ObISQLClient& sql_client, ObObjectType obj_type, int64_t& create_time, ObString& ref_obj_name) { int ret = OB_SUCCESS; uint64_t exec_tenant_id = ObSchemaUtils::get_exec_tenant_id(get_tenant_id()); #define BUILD_OBJ_QUERY_SQL(table_name, field_name, ref_obj_id) \ do { \ OZ(sql.assign_fmt("SELECT * FROM %s WHERE %s = %ld and tenant_id = %ld", \ table_name, \ field_name, \ ref_obj_id, \ ObSchemaUtils::get_extract_tenant_id(exec_tenant_id, get_tenant_id()))); \ } while (0) ObSqlString sql; ObString type_name(ob_object_type_str(obj_type)); const char* all_tbl_name = NULL; if (false == is_valid()) { ret = OB_ERR_UNEXPECTED; LOG_WARN("error info is invalid", K(ret)); } else if (OB_FAIL( ObSchemaUtils::get_all_table_name(ObSchemaUtils::get_exec_tenant_id(get_tenant_id()), all_tbl_name))) { LOG_WARN("failed to get all table name", K(ret)); } else { const char* tbl_name = (ObObjectType::PACKAGE_BODY == obj_type || ObObjectType::PACKAGE == obj_type) ? OB_ALL_PACKAGE_TNAME : (ObObjectType::TYPE == obj_type || ObObjectType::TYPE_BODY == obj_type) ? OB_ALL_TYPE_TNAME : (ObObjectType::PROCEDURE == obj_type || ObObjectType::FUNCTION == obj_type) ? OB_ALL_ROUTINE_TNAME : (ObObjectType::INDEX == obj_type || ObObjectType::TABLE == obj_type || ObObjectType::VIEW == obj_type) ? all_tbl_name : NULL; const char* field_name = (ObObjectType::PACKAGE_BODY == obj_type || ObObjectType::PACKAGE == obj_type) ? "package_id" : (ObObjectType::TYPE == obj_type || ObObjectType::TYPE_BODY == obj_type) ? "type_id" : (ObObjectType::PROCEDURE == obj_type || ObObjectType::FUNCTION == obj_type) ? "routine_id" : (ObObjectType::INDEX == obj_type || ObObjectType::TABLE == obj_type || ObObjectType::VIEW == obj_type) ? "table_id" : NULL; const char* field_obj_name = (ObObjectType::PACKAGE_BODY == obj_type || ObObjectType::PACKAGE == obj_type) ? "package_name" : (ObObjectType::TYPE == obj_type || ObObjectType::TYPE_BODY == obj_type) ? "type_name" : (ObObjectType::PROCEDURE == obj_type || ObObjectType::FUNCTION == obj_type) ? "routine_name" : (ObObjectType::INDEX == obj_type || ObObjectType::TABLE == obj_type || ObObjectType::VIEW == obj_type) ? "table_name" : NULL; if (OB_NOT_NULL(tbl_name) && OB_NOT_NULL(field_name) && OB_NOT_NULL(field_obj_name)) { // uint64_t ref_obj_id = OB_SYS_TENANT_ID == common::extract_tenant_id(ref_obj_id_) ? // ref_obj_id_ : extract_ref_obj_id(); BUILD_OBJ_QUERY_SQL(tbl_name, field_name, extract_ref_obj_id()); if (OB_SUCC(ret)) { SMART_VAR(ObMySQLProxy::MySQLResult, res) { if (OB_FAIL(sql_client.read(res, exec_tenant_id, sql.ptr()))) { LOG_WARN("execute query failed", K(ret), K(sql)); } else { sqlclient::ObMySQLResult* result = res.get_result(); if (NULL != result) { ObString tmp_ref_name; common::ObTimeZoneInfo* tz_info; OZ(result->next()); OZ(result->get_timestamp("gmt_create", tz_info, create_time)); OZ(result->get_varchar(field_obj_name, tmp_ref_name)); OZ(deep_copy_str(tmp_ref_name, ref_obj_name)); // OZ (result->get_int("gmt_create", create_time)); } else { create_time = -1; } } } } } else { create_time = -1; } } if (OB_ITER_END == ret) { ret = OB_SUCCESS; } return ret; } int ObDependencyInfo::delete_schema_object_dependency(common::ObISQLClient& trans, uint64_t tenant_id, uint64_t dep_obj_id, int64_t schema_version, ObObjectType dep_obj_type) { UNUSED(schema_version); int ret = OB_SUCCESS; if (IS_CLUSTER_VERSION_BEFORE_3100) { // do nothing LOG_DEBUG("all_dependency schema only support after version 3.1"); } else { const uint64_t exec_tenant_id = ObSchemaUtils::get_exec_tenant_id(tenant_id); const uint64_t extract_tid = ObSchemaUtils::get_extract_tenant_id(exec_tenant_id, tenant_id); ObSqlString sql; int64_t affected_rows = 0; if (OB_INVALID_ID == tenant_id || OB_INVALID_ID == dep_obj_id || ObObjectType::MAX_TYPE == dep_obj_type) { ret = OB_ERR_UNEXPECTED; LOG_WARN("delete error info unexpected.", K(ret), K(tenant_id), K(dep_obj_id), K(dep_obj_type)); } else if (sql.assign_fmt("delete FROM %s WHERE dep_obj_id = %ld \ AND tenant_id = %ld \ AND dep_obj_type = %ld", OB_ALL_TENANT_DEPENDENCY_TNAME, extract_obj_id(tenant_id, dep_obj_id), extract_tid, static_cast(dep_obj_type))) { LOG_WARN("delete from __all_tenant_dependency table failed.", K(ret), K(tenant_id), K(extract_tid), K(dep_obj_id), K(dep_obj_type)); } else { if (OB_FAIL(trans.write(exec_tenant_id, sql.ptr(), affected_rows))) { LOG_WARN("execute query failed", K(ret), K(sql)); } else { // do nothing } } } return ret; } int ObDependencyInfo::insert_schema_object_dependency(common::ObISQLClient& trans, bool is_replace, bool only_history) { int ret = OB_SUCCESS; if (IS_CLUSTER_VERSION_BEFORE_3100) { // do nothing LOG_DEBUG("all_dependency schema only support after version 3.1"); } else { ObDependencyInfo& dep_info = *this; const uint64_t exec_tenant_id = ObSchemaUtils::get_exec_tenant_id(dep_info.get_tenant_id()); ObDMLSqlSplicer dml; int64_t ref_obj_create_time = -1; ObString ref_obj_name; if (OB_FAIL(ret)) { LOG_WARN("get ref object time failed", K(ret), K(dep_info.get_ref_obj_type()), K(dep_info.get_ref_obj_id())); } else if (OB_FAIL(gen_dependency_dml(exec_tenant_id, dml))) { LOG_WARN("gen table dml failed", K(ret)); } else { ObDMLExecHelper exec(trans, exec_tenant_id); int64_t affected_rows = 0; if (!only_history) { ObDMLExecHelper exec(trans, exec_tenant_id); if (is_replace) { if (OB_FAIL(exec.exec_update(OB_ALL_TENANT_DEPENDENCY_TNAME, dml, affected_rows))) { LOG_WARN("execute update failed", K(ret)); } } else { if (OB_FAIL(exec.exec_insert(OB_ALL_TENANT_DEPENDENCY_TNAME, dml, affected_rows))) { LOG_WARN("execute insert failed", K(ret)); } } if (OB_SUCC(ret) && !is_single_row(affected_rows)) { ret = OB_ERR_UNEXPECTED; LOG_WARN("affected_rows unexpected to be one", K(affected_rows), K(ret)); } } } } return ret; } int ObDependencyInfo::collect_dep_infos(ObIArray& schema_objs, ObIArray& deps, ObObjectType dep_obj_type, uint64_t property, ObString& dep_attrs, ObString& dep_reason) { int ret = OB_SUCCESS; if (IS_CLUSTER_VERSION_BEFORE_3100) { // do nothing LOG_DEBUG("all_dependency schema only support after version 3.1"); } else { int64_t order = 0; for (int64_t i = 0; OB_SUCC(ret) && i < schema_objs.count(); ++i) { ObDependencyInfo dep; ObSchemaObjVersion& s_objs = schema_objs.at(i); if (!s_objs.is_valid() // object may depend on self || dep_obj_type == s_objs.get_schema_object_type()) { continue; } dep.set_dep_obj_id(OB_INVALID_ID); dep.set_dep_obj_type(dep_obj_type); dep.set_dep_obj_owner_id(OB_INVALID_ID); dep.set_ref_obj_id(s_objs.get_object_id()); dep.set_ref_obj_type(s_objs.get_schema_object_type()); dep.set_order(order); ++order; dep.set_dep_timestamp(-1); dep.set_ref_timestamp(s_objs.get_version()); dep.set_property(property); if (dep_attrs.length() >= OB_MAX_ORACLE_RAW_SQL_COL_LENGTH || dep_reason.length() >= OB_MAX_ORACLE_RAW_SQL_COL_LENGTH) { ret = OB_ERR_UNEXPECTED; LOG_WARN("dep attrs or dep reason is too long", K(ret), K(dep_attrs.length()), K(dep_reason.length())); } else { if (!dep_attrs.empty()) OZ(dep.set_dep_attrs(dep_attrs)); if (!dep_reason.empty()) OZ(dep.set_dep_reason(dep_reason)); } OZ(deps.push_back(dep)); } } return ret; } void ObDependencyInfo::reset() { tenant_id_ = OB_INVALID_ID; dep_obj_id_ = OB_INVALID_ID; dep_obj_type_ = ObObjectType::MAX_TYPE; order_ = 0; dep_timestamp_ = -1; ref_obj_id_ = OB_INVALID_ID; ref_obj_type_ = ObObjectType::MAX_TYPE; ref_timestamp_ = -1; dep_obj_owner_id_ = OB_INVALID_ID; property_ = 0; reset_string(dep_attrs_); reset_string(dep_reason_); reset_string(ref_obj_name_); schema_version_ = OB_INVALID_VERSION; } int64_t ObDependencyInfo::get_convert_size() const { int64_t len = 0; len += static_cast(sizeof(ObDependencyInfo)); len += dep_attrs_.length() + 1; len += dep_reason_.length() + 1; len += ref_obj_name_.length() + 1; return len; } OB_DEF_SERIALIZE(ObDependencyInfo) { int ret = OB_SUCCESS; LST_DO_CODE(OB_UNIS_ENCODE, tenant_id_, dep_obj_id_, dep_obj_type_, order_, dep_timestamp_, ref_obj_id_, ref_obj_type_, ref_timestamp_, dep_obj_owner_id_, property_, dep_attrs_, dep_reason_, ref_obj_name_, schema_version_); return ret; } OB_DEF_DESERIALIZE(ObDependencyInfo) { int ret = OB_SUCCESS; reset(); LST_DO_CODE(OB_UNIS_DECODE, tenant_id_, dep_obj_id_, dep_obj_type_, order_, dep_timestamp_, ref_obj_id_, ref_obj_type_, ref_timestamp_, dep_obj_owner_id_, property_, dep_attrs_, dep_reason_, ref_obj_name_, schema_version_); return ret; } OB_DEF_SERIALIZE_SIZE(ObDependencyInfo) { int64_t len = 0; LST_DO_CODE(OB_UNIS_ADD_LEN, tenant_id_, dep_obj_id_, dep_obj_type_, order_, dep_timestamp_, ref_obj_id_, ref_obj_type_, ref_timestamp_, dep_obj_owner_id_, property_, dep_attrs_, dep_reason_, ref_obj_name_, schema_version_); return len; } } // namespace schema } // namespace share } // namespace oceanbase // Copyright © 2017-2021 Trust Wallet. // // This file is part of Trust. The full Trust copyright notice, including // terms governing use, modification, and redistribution, is contained in the // file LICENSE at the root of the source code distribution tree. #include "ParamBase.h" namespace TW::Ethereum::ABI { // Default implementation for simple types: return encoded value (32 bytes) Data ParamBase::hashStruct() const { Data encoded; encode(encoded); return encoded; } } // namespace TW::Ethereum::ABI #include "MQ135.h" MQ135::MQ135(uint8_t pin) : BaseMQ(pin) { } MQ135::MQ135(uint8_t pin, uint8_t pinHeater) : BaseMQ(pin, pinHeater) { } unsigned long MQ135::readCO2() { return readScaled(-0.42 , 1.92); } TheLongRunSmoke/utility-boilerplate-qtsrc/utility_boilerplate_qt5/tests/settings/items/checkboxitem_test.cpp #include #include "../../fixtures.hpp" #include namespace ubTestSuit { TEST_F(UiFixture, SettingItems_CheckBoxItem) { // NOLINT(cert-err58-cpp) auto* item = new CheckBoxItem("key", "name"); EXPECT_EQ(item->key(), "key"); auto* label = findQWidgetByClass(item->view(window)); EXPECT_EQ(label->text(), "name"); delete item; } TEST_F(UiFixture, SettingItems_CheckBoxItem_defaultValue) { // NOLINT(cert-err58-cpp) auto* item = new CheckBoxItem("key", "name"); EXPECT_EQ(item->defaultValue(), "false"); auto* field = findQWidgetByClass(item->view(window)); EXPECT_EQ(field->checkState(), Qt::Unchecked); delete item; item = new CheckBoxItem("key", "name", false); EXPECT_EQ(item->defaultValue(), "false"); field = findQWidgetByClass(item->view(window)); EXPECT_EQ(field->checkState(), Qt::Unchecked); delete item; item = new CheckBoxItem("key", "name", true); EXPECT_EQ(item->defaultValue(), "true"); field = findQWidgetByClass(item->view(window)); EXPECT_EQ(field->checkState(), Qt::Checked); delete item; } TEST_F(UiFixture, SettingItems_CheckBoxItem_value) { // NOLINT(cert-err58-cpp) auto* item = new CheckBoxItem("key", "name"); EXPECT_EQ(item->value(), "false"); auto* field = findQWidgetByClass(item->view(window)); EXPECT_EQ(field->checkState(), Qt::Unchecked); delete item; item = new CheckBoxItem("key", "name", false); EXPECT_EQ(item->value(), "false"); field = findQWidgetByClass(item->view(window)); EXPECT_EQ(field->checkState(), Qt::Unchecked); delete item; item = new CheckBoxItem("key", "name", true); EXPECT_EQ(item->value(), "true"); field = findQWidgetByClass(item->view(window)); EXPECT_EQ(field->checkState(), Qt::Checked); item->setValue("false"); EXPECT_EQ(item->value(), "false"); field = findQWidgetByClass(item->view(window)); EXPECT_EQ(field->checkState(), Qt::Unchecked); delete item; } } // namespace ubTestSuit wjezxujian/WildMagic4 // Geometric Tools, Inc. // http://www.geometrictools.com // Copyright (c) 1998-2006. All Rights Reserved // // The Wild Magic Version 4 Restricted Libraries source code is supplied // under the terms of the license agreement // http://www.geometrictools.com/License/Wm4RestrictedLicense.pdf // and may not be copied or disclosed except in accordance with the terms // of that agreement. #include "BloodCellController.h" using namespace Wm4; WM4_IMPLEMENT_RTTI(Wm4,BloodCellController,ParticleController); WM4_IMPLEMENT_STREAM(BloodCellController); WM4_IMPLEMENT_DEFAULT_STREAM(BloodCellController,ParticleController); WM4_IMPLEMENT_DEFAULT_NAME_ID(BloodCellController,ParticleController); //---------------------------------------------------------------------------- BloodCellController::BloodCellController () { } //---------------------------------------------------------------------------- void BloodCellController::UpdatePointMotion (float) { Particles* pkParticle = StaticCast(m_pkObject); int iLQuantity = pkParticle->Locations->GetQuantity(); Vector3f* akLocation = pkParticle->Locations->GetData(); float* afSize = pkParticle->Sizes->GetData(); for (int i = 0; i < iLQuantity; i++) { for (int j = 0; j < 3; j++) { akLocation[i][j] += 0.01f*Mathf::SymmetricRandom(); if (akLocation[i][j] > 1.0f) { akLocation[i][j] = 1.0f; } else if (akLocation[i][j] < -1.0f) { akLocation[i][j] = -1.0f; } } afSize[i] *= (1.0f + 0.01f*Mathf::SymmetricRandom()); if (afSize[i] > 0.25f) { afSize[i] = 0.25f; } } pkParticle->VBuffer->Release(); } //---------------------------------------------------------------------------- SqLemon/Robotics_HAL /* * Pin.cpp * * Created on: Jan 2, 2021 * Author: ianicknoejovich */ #include #include Pin::Pin(uint8_t port, uint8_t pin) { _pin = pin; _port = port; } #include using namespace std; int main() { int t; cin >> t; for (int tc=1; tc<=t; tc++) { string x; cin >> x; int ans = 0; ans += (x[0]-48-1) * 10; ans += ((float)x.size()/2)*(2+x.size()-1); // sum of arithmetic progression cout << ans << endl; } return 0; } #include using namespace std; void printNSeries(int n) { if (n > 0) { cout << n << " "; printNSeries(n-1); } } int main() { printNSeries(10); return 0; } tly000/rellictests/tools/headergen/templates.hpp template class W { public: template static int X(void); template class Y { public: template static int Z(void); }; template class Y { public: template static int Z(void); }; class Evil { public: static int Monster(void); }; }; template template class W::Y { public: template static int Z(void); }; template template int W::X(void) { return 1; } template template template int W::Y::Z(void) { return 1; } template int W::Evil::Monster(void) { return 1; } int main(void) { return W::X() + W::Y::Z() + W::Y::Z() + W::Y::Z() + W::Evil::Monster() + W::Evil::Monster(); }/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* */ /* This file is part of the library KASKADE 7 */ /* see http://www.zib.de/projects/kaskade7-finite-element-toolbox */ /* */ /* Copyright (C) 2002-2016 Zuse Institute Berlin */ /* */ /* KASKADE 7 is distributed under the terms of the ZIB Academic License. */ /* see $KASKADE/academic.txt */ /* */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ #include #include #include #include #include "io/iobase.hh" #include "utilities/date_and_time.hh" #include "utilities/save_file.hh" namespace Kaskade { std::string createFileName(std::string const& desiredName, std::string const& ending, bool useEnding, int length) { std::ifstream infile; std::string fileName = desiredName + "_" + paddedString(0,length) + ending; // file name does not yet exist // open and close file -> set failbit infile.open(fileName.c_str()); infile.close(); size_t index = 1; size_t const maxIndex = (int)pow(10,length); while(!infile.fail()) { // reset streams internal failbit state infile.clear(std::ios::failbit); // change filename fileName = desiredName + "_" + paddedString(index, length) + ending; // open and close file -> set failbit infile.open(fileName.c_str()); infile.close(); ++index; if(index==maxIndex) { std::cerr << __FILE__ << ": " << __LINE__ << ": Tried " << maxIndex << " names, all of them are currently used." << std::endl; } } if(!useEnding) fileName = desiredName + "_" + paddedString(index-1, length); return fileName; } bool createFolder(std::string folder_name) { return ( mkdir(folder_name.c_str(), 0777) == 0 ); } std::string createFileNameInFolder(std::string folderName, std::string const& desiredName, std::string const& ending, bool useEnding, int length) { if(folderName.empty()) folderName = desiredName; createFolder( appendDate(folderName) ); folderName += "/" + desiredName; return createFileName(folderName, ending, useEnding, length); } } #include "gtest/gtest.h" #include "union_types/union_with_parameter/TestUnion.h" #include "zserio/BitStreamWriter.h" #include "zserio/BitStreamReader.h" #include "zserio/CppRuntimeException.h" namespace union_types { namespace union_with_parameter { TEST(UnionWithParameterTest, emptyConstructor) { TestUnion testUnion; ASSERT_THROW(testUnion.getCase1Allowed(), zserio::CppRuntimeException); } TEST(UnionWithParameterTest, bitStreamReaderConstructor) { TestUnion testUnion; testUnion.initialize(true); testUnion.setCase3Field(-1); zserio::BitBuffer bitBuffer = zserio::BitBuffer(1024 * 8); zserio::BitStreamWriter writer(bitBuffer); testUnion.write(writer); zserio::BitStreamReader reader(writer.getWriteBuffer(), writer.getBitPosition(), zserio::BitsTag()); TestUnion readTestUnion(reader, true); ASSERT_EQ(testUnion.choiceTag(), readTestUnion.choiceTag()); ASSERT_EQ(testUnion.getCase3Field(), readTestUnion.getCase3Field()); } TEST(UnionWithParameter, copyConstructor) { TestUnion testUnion; TestUnion testUnionCopy1(testUnion); ASSERT_THROW(testUnion.getCase1Allowed(), zserio::CppRuntimeException); ASSERT_THROW(testUnionCopy1.getCase1Allowed(), zserio::CppRuntimeException); testUnion.initialize(true); testUnion.setCase1Field(33); TestUnion testUnionCopy2(testUnion); ASSERT_EQ(testUnion.getCase1Allowed(), testUnionCopy2.getCase1Allowed()); ASSERT_EQ(testUnion.getCase1Field(), testUnionCopy2.getCase1Field()); testUnion.initialize(false); testUnion.setCase2Field(13); TestUnion testUnionCopy3(testUnion); ASSERT_EQ(testUnion.getCase1Allowed(), testUnionCopy3.getCase1Allowed()); ASSERT_EQ(testUnion.getCase2Field(), testUnionCopy3.getCase2Field()); } TEST(UnionWithParameter, assignmentOperator) { TestUnion testUnion; TestUnion testUnionAssign; testUnionAssign = testUnion; ASSERT_THROW(testUnion.getCase1Allowed(), zserio::CppRuntimeException); ASSERT_THROW(testUnionAssign.getCase1Allowed(), zserio::CppRuntimeException); testUnion.initialize(true); testUnion.setCase1Field(33); testUnionAssign = testUnion; ASSERT_EQ(testUnion.getCase1Allowed(), testUnionAssign.getCase1Allowed()); ASSERT_EQ(testUnion.getCase1Field(), testUnionAssign.getCase1Field()); testUnion.initialize(false); testUnion.setCase2Field(13); testUnionAssign = testUnion; ASSERT_EQ(testUnion.getCase1Allowed(), testUnionAssign.getCase1Allowed()); ASSERT_EQ(testUnion.getCase2Field(), testUnionAssign.getCase2Field()); } TEST(UnionWithParameter, moveConstructor) { { TestUnion testUnion; TestUnion testUnionMoved1(std::move(testUnion)); ASSERT_THROW(testUnionMoved1.getCase1Allowed(), zserio::CppRuntimeException); } { TestUnion testUnion; testUnion.initialize(true); testUnion.setCase1Field(33); TestUnion testUnionMoved2(std::move(testUnion)); ASSERT_EQ(true, testUnionMoved2.getCase1Allowed()); ASSERT_EQ(33, testUnionMoved2.getCase1Field()); } { TestUnion testUnion; testUnion.initialize(false); testUnion.setCase2Field(13); TestUnion testUnionMoved3(std::move(testUnion)); ASSERT_EQ(false, testUnionMoved3.getCase1Allowed()); ASSERT_EQ(13, testUnionMoved3.getCase2Field()); } } TEST(UnionWithParameter, moveAssignmentOperator) { TestUnion testUnionMoved; { TestUnion testUnion; testUnionMoved = std::move(testUnion); ASSERT_THROW(testUnionMoved.getCase1Allowed(), zserio::CppRuntimeException); } { TestUnion testUnion; testUnion.initialize(true); testUnion.setCase1Field(33); testUnionMoved = testUnion; ASSERT_EQ(true, testUnionMoved.getCase1Allowed()); ASSERT_EQ(33, testUnionMoved.getCase1Field()); } { TestUnion testUnion; testUnion.initialize(false); testUnion.setCase2Field(13); testUnionMoved = testUnion; ASSERT_EQ(false, testUnionMoved.getCase1Allowed()); ASSERT_EQ(13, testUnionMoved.getCase2Field()); } } TEST(UnionWithParameter, propagateAllocatorCopyConstructor) { TestUnion testUnion; TestUnion testUnionCopy1(zserio::PropagateAllocator, testUnion, TestUnion::allocator_type()); ASSERT_THROW(testUnion.getCase1Allowed(), zserio::CppRuntimeException); ASSERT_THROW(testUnionCopy1.getCase1Allowed(), zserio::CppRuntimeException); testUnion.initialize(true); testUnion.setCase1Field(33); TestUnion testUnionCopy2(zserio::PropagateAllocator, testUnion, TestUnion::allocator_type()); ASSERT_EQ(testUnion.getCase1Allowed(), testUnionCopy2.getCase1Allowed()); ASSERT_EQ(testUnion.getCase1Field(), testUnionCopy2.getCase1Field()); testUnion.initialize(false); testUnion.setCase2Field(13); TestUnion testUnionCopy3(zserio::PropagateAllocator, testUnion, TestUnion::allocator_type()); ASSERT_EQ(testUnion.getCase1Allowed(), testUnionCopy3.getCase1Allowed()); ASSERT_EQ(testUnion.getCase2Field(), testUnionCopy3.getCase2Field()); } TEST(UnionWithParameterTest, initialize) { zserio::BitBuffer bitBuffer = zserio::BitBuffer(1024 * 8); zserio::BitStreamWriter writer(bitBuffer); TestUnion testUnion; ASSERT_THROW(testUnion.getCase1Allowed(), zserio::CppRuntimeException); ASSERT_THROW(testUnion.write(writer), zserio::CppRuntimeException); testUnion.setCase2Field(33); // not initialized but doesn't touch parameter - OK ASSERT_NO_THROW(testUnion.write(writer)); testUnion.setCase1Field(13); // not initialized but touch parameter! ASSERT_THROW(testUnion.write(writer), zserio::CppRuntimeException); testUnion.initialize(true); ASSERT_TRUE(testUnion.getCase1Allowed()); ASSERT_NO_THROW(testUnion.write(writer)); } TEST(UnionWithParameterTestTest, isInitialized) { TestUnion testUnion; ASSERT_FALSE(testUnion.isInitialized()); testUnion.initialize(true); ASSERT_TRUE(testUnion.isInitialized()); } } //namespace union_with_parameter } // namespace union_types #include #include #include #include "test_utils_input.hpp" #include #include #include #include #include namespace { std::string runInputSimulation (omni::core::input::syntax_element & statementElement, std::size_t templateIndex, std::vector > & simulatedInput) { using namespace omni::core; std::string output; while (simulatedInput.size () > 0) { std::tuple input = simulatedInput.front (); simulatedInput.erase (simulatedInput.begin ()); std::vector suggestions = statementElement.suggest (std::get <0> (input), templateIndex); BOOST_CHECK_GT (suggestions.size (), 0u); BOOST_CHECK_LT (std::get <1> (input), suggestions.size ()); if (! suggestions.empty () && std::get <1> (input) < suggestions.size ()) { input::syntax_suggestion selectedSuggestion = suggestions [std::get <1> (input)]; output += selectedSuggestion.text; if (selectedSuggestion.syntaxElement != nullptr) { input::syntax_element & selectedSyntaxElem = * selectedSuggestion.syntaxElement; for (std::size_t t = 1u; t < selectedSyntaxElem.templateElementCount (); ++t) { std::shared_ptr element = selectedSyntaxElem.templateElementAt (t)->dive (); if (element != nullptr) { output += runInputSimulation (* element, 0u, simulatedInput); } else { std::shared_ptr textTemplateElement = std::dynamic_pointer_cast (selectedSyntaxElem.templateElementAt (t)); if (textTemplateElement != nullptr) { output += textTemplateElement->getText (); } } } } } break; } return output; } } BOOST_AUTO_TEST_SUITE (inputStateTests) BOOST_AUTO_TEST_CASE (basic) { using namespace omni::core; std::shared_ptr statementElement = omni::tests::makeTestSyntaxElement (); // Simulates the input of "iforf" // with the desired output of "if (foo) return foo" // first: Text that has been typed // second: Index of the suggestion that has been accepted // third: Dive into the suggested element, or step to the next element on the same level? std::vector > simulatedInput { std::make_tuple ("i", 0u), // "if (...)" std::make_tuple ("fo", 0u), // "foo" std::make_tuple ("w", 0u), // "while (...)" std::make_tuple ("f", 0u), // "foo" std::make_tuple ("r", 0u), // "return ..." std::make_tuple ("f", 0u), // "foo" }; std::string output = runInputSimulation (* statementElement, 0u, simulatedInput); std::string desiredOutput = R"(if (foo) { while (foo) { return foo } } )"; BOOST_CHECK_EQUAL (output, desiredOutput); } BOOST_AUTO_TEST_SUITE_END () // // File: L95.cpp // Created by: // Created on: Tue Nov 4 11:46 2008 // /* Copyright or © or Copr. Bio++ Development Team, (November 16, 2004) This software is a computer program whose purpose is to provide classes for phylogenetic data analysis. This software is governed by the CeCILL license under French law and abiding by the rules of distribution of free software. You can use, modify and/ or redistribute the software under the terms of the CeCILL license as circulated by CEA, CNRS and INRIA at the following URL "http://www.cecill.info". As a counterpart to the access to the source code and rights to copy, modify and redistribute granted by the license, users are provided only with a limited warranty and the software's author, the holder of the economic rights, and the successive licensors have only limited liability. In this respect, the user's attention is drawn to the risks associated with loading, using, modifying and/or developing or reproducing the software by the user in light of its specific status of free software, that may mean that it is complicated to manipulate, and that also therefore means that it is reserved for developers and experienced professionals having in-depth computer knowledge. Users are therefore encouraged to load and test the software's suitability as regards their requirements in conditions enabling the security of their systems and/or data to be ensured and, more generally, to use and operate it in the same conditions as regards security. The fact that you are presently reading this means that you have had knowledge of the CeCILL license and that you accept its terms. */ #include "L95.h" #include "../FrequenciesSet/NucleotideFrequenciesSet.h" #include // From SeqLib: #include // From the STL: #include using namespace bpp; using namespace std; /******************************************************************************/ L95::L95( const NucleicAlphabet* alphabet, double alpha, double beta, double gamma, double kappa, double theta): AbstractParameterAliasable("L95."), AbstractNucleotideSubstitutionModel(alphabet, new CanonicalStateMap(alphabet, false), "L95."), alpha_(alpha), beta_(beta), gamma_(gamma), kappa_(kappa), theta_(theta) { addParameter_(new Parameter("L95.alpha", alpha, &Parameter::PROP_CONSTRAINT_IN)); addParameter_(new Parameter("L95.beta", beta, &Parameter::PROP_CONSTRAINT_IN)); addParameter_(new Parameter("L95.gamma", gamma, &Parameter::PROP_CONSTRAINT_IN)); addParameter_(new Parameter("L95.kappa", kappa, new IntervalConstraint(0, 1000, false, false, NumConstants::MILLI()), true)); addParameter_(new Parameter("L95.theta", theta, new IntervalConstraint(0, 1, false, false, NumConstants::MILLI()), true)); computeFrequencies(false); updateMatrices(); } /******************************************************************************/ void L95::updateMatrices() { alpha_ = getParameterValue("alpha"); beta_ = getParameterValue("beta"); gamma_ = getParameterValue("gamma"); kappa_ = getParameterValue("kappa"); theta_ = getParameterValue("theta"); freq_[0] = (1-theta_)/2; freq_[1] = theta_/2; freq_[2] = theta_/2; freq_[3] = (1-theta_)/2; // Generator matrix: generator_(0,0) = -kappa_ * theta_ - gamma_; generator_(0,1) = kappa_* beta_ * theta_; generator_(0,2) = kappa_ * (1-beta_) * theta_; generator_(0,3) = gamma_; generator_(1,0) = kappa_ * alpha_ * ( 1- theta_); generator_(1,1) = -kappa_ * (1 - theta_) + gamma_ - 1; generator_(1,2) = 1 - gamma_; generator_(1,3) = kappa_ * (1 - theta_) * (1 - alpha_); generator_(2,0) = kappa_ * (1 - theta_) * (1 - alpha_); generator_(2,1) = 1 - gamma_; generator_(2,2) = -kappa_ * (1 - theta_) + gamma_ - 1; generator_(2,3) = kappa_ * alpha_ * (1 - theta_); generator_(3,0) = gamma_; generator_(3,1) = kappa_ * (1-beta_) * theta_; generator_(3,2) = kappa_* beta_ * theta_; generator_(3,3) = -kappa_ * theta_ - gamma_; setScale(1. / (2*kappa_*theta_*(1-theta_)+gamma_+theta_-2*theta_*gamma_)); AbstractSubstitutionModel::updateMatrices(); } /******************************************************************************/ void L95::setFreq(map& freqs) { setParameterValue("theta",freqs[1]+freqs[2]); updateMatrices(); } /******************************************************************************/ /******************************************************************************* * Copyright 2016 ROBOTIS 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. *******************************************************************************/ /* Authors: (Darby) */ #include "dynamixel_workbench_operators/my_operator.h" JointOperator::JointOperator() :node_handle_(""), priv_node_handle_("~"), is_loop_(false) { std::string yaml_file = node_handle_.param("trajectory_info", ""); std::string yaml_file1 = node_handle_.param("serving_trajectory_info", ""); std::string yaml_file2 = node_handle_.param("cleaning_trajectory_info", ""); jnt_tra_msg_ = new trajectory_msgs::JointTrajectory; serving_motion_msg_ = new trajectory_msgs::JointTrajectory; bool result = getTrajectoryInfo(yaml_file, jnt_tra_msg_); bool result1 = getTrajectoryInfo(yaml_file1, serving_motion_msg_); if (result1 == false) { ROS_ERROR("Please check YAML file"); exit(0); } dynamixel_command_subscriber_ = node_handle_.subscribe("dynamixel_position_command", 1000, &JointOperator::CommandMsgCallback, this); joint_trajectory_pub_ = node_handle_.advertise("joint_trajectory", 100); move_command_server_ = node_handle_.advertiseService("execution", &JointOperator::moveCommandMsgCallback, this); is_loop_ = priv_node_handle_.param("is_loop", "false"); } JointOperator::~JointOperator() { delete jnt_tra_msg_; } void JointOperator::CommandMsgCallback(const d2c_robot_msgs::DynamixelCommand::ConstPtr& msg) { std::vector> target_joint_position; float motion_command = msg -> motion; if (motion_command == 0.0) { joint_trajectory_pub_.publish(*jnt_tra_msg_); ROS_INFO("publish dynamixel control info : %f", motion_command); } else if (motion_command == 1.0) { joint_trajectory_pub_.publish(*serving_motion_msg_); ROS_INFO("publish dynamixel control info : %f", motion_command); } else if (motion_command == 2.0) { target_joint_position.resize(5); for (int i = 0; i < 4; ++i) { target_joint_position[i].resize(4); } for(int i = 0; i < 3; i++) { for (int j = 0; j < 4; j++) { target_joint_position[i][j] = msg->joint_position[i].positions.at(j); } } cleaning_motion_msg_ = new trajectory_msgs::JointTrajectory; bool result2 = getTrajectoryInfo2(target_joint_position, cleaning_motion_msg_); joint_trajectory_pub_.publish(*cleaning_motion_msg_); ROS_INFO("publish dynamixel control info : %f", motion_command); } } bool JointOperator::getTrajectoryInfo(const std::string yaml_file, trajectory_msgs::JointTrajectory *jnt_tra_msg) { YAML::Node file; file = YAML::LoadFile(yaml_file.c_str()); if (file == NULL) return false; YAML::Node joint = file["joint"]; uint8_t joint_size = joint["names"].size(); for (uint8_t index = 0; index < joint_size; index++) { std::string joint_name = joint["names"][index].as(); jnt_tra_msg->joint_names.push_back(joint["names"][index].as()); } YAML::Node motion = file["motion"]; uint8_t motion_size = motion["names"].size(); for (uint8_t index = 0; index < motion_size; index++) { trajectory_msgs::JointTrajectoryPoint jnt_tra_point; //jnt_tra_point.positions.resize(10); //jnt_tra_point.time_from_start.resize(10); std::string name = motion["names"][index].as(); YAML::Node motion_name = motion[name]; for (uint8_t size = 0; size < joint_size; size++) { if (joint_size != motion_name["step"].size()) { ROS_ERROR("Please check motion step size. It must be equal to joint size"); return 0; } jnt_tra_point.positions.push_back(motion_name["step"][size].as()); ROS_INFO("motion_name : %s, step : %f", name.c_str(), motion_name["step"][size].as()); } if (motion_name["time_from_start"] == NULL) { ROS_ERROR("Please check time_from_start. It must be set time_from_start each step"); return 0; } jnt_tra_point.time_from_start.fromSec(motion_name["time_from_start"].as()); ROS_INFO("time_from_start : %f", motion_name["time_from_start"].as()); jnt_tra_msg->points.push_back(jnt_tra_point); } return true; } bool JointOperator::getTrajectoryInfo2(std::vector> joint_position, trajectory_msgs::JointTrajectory *jnt_tra_msg) { std::vector joint = {"joint1", "joint2", "joint3","joint4"}; for (uint8_t index = 0; index < joint.size(); index++) { jnt_tra_msg->joint_names.push_back(joint[index]); } std::vector p1 = joint_position[0]; std::vector p2 = joint_position[1]; std::vector p3 = joint_position[2]; ROS_INFO("%f, %f, %f,%f",p1[0], p1[1],p1[2],p1[3]); ROS_INFO("%f, %f, %f,%f",p2[0], p2[1],p2[2],p2[3]); ROS_INFO("%f, %f, %f,%f",joint_position[2][0], p3[1],p3[2],p3[3]); std::vector motion_name = {"motion1","motion2","motion3","motion4","motion5","motion6","motion7","motion8"}; std::vector> motion = {p1,p2,p3,{0.0, 0.0, 0.0, 0.0},{0.538, -0.06348, -0.58844, 0.65272},{0.538, -0.231, -0.672, 0.905},{-0.5, -0.150858, -0.804671, 0.956325},{0.0, 0.0, 0.0, 0.0} }; std::vector time_from_start = {1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0}; for (uint8_t index = 0; index < motion_name.size(); index++) { trajectory_msgs::JointTrajectoryPoint jnt_tra_point; for (uint8_t size = 0; size < joint.size(); size++) { if (joint.size() != 4) { ROS_ERROR("Please check motion step size. It must be equal to joint size"); return 0; } jnt_tra_point.positions.push_back(motion[index][size]); ROS_INFO("motion_name : %s, step : %f", motion_name[index].c_str(), motion[index][size]); } jnt_tra_point.time_from_start.fromSec(time_from_start[index]); ROS_INFO("time_from_start : %f", time_from_start[index]); jnt_tra_msg->points.push_back(jnt_tra_point); } return true; } bool JointOperator::moveCommandMsgCallback(std_srvs::Trigger::Request &req, std_srvs::Trigger::Response &res) { joint_trajectory_pub_.publish(*jnt_tra_msg_); res.success = true; res.message = "Success to publish joint trajectory"; return true; } int main(int argc, char **argv) { // Init ROS node ros::init(argc, argv, "joint_operator"); JointOperator joint_operator; ROS_INFO("For now, you can use publish joint trajectory msgs by triggering service(/execution)"); if (joint_operator.isLoop()) { while(1) { std_srvs::Trigger trig; joint_operator.moveCommandMsgCallback(trig.request, trig.response); } } ros::spin(); return 0; } #include "initDB.hpp" #include "Database.hpp" #include void initDB() { }0 #include "D3D.h" ID3D11Device* D3D::d3dDevice = NULL; ID3D11DeviceContext* D3D::d3dDevCon = NULL; IDXGISwapChain* D3D::SwapChain = NULL; ID3D11RenderTargetView* D3D::renderTargetView = NULL; ID3D11DepthStencilView* D3D::depthStencilView = NULL; ID3D11Texture2D* D3D::depthStencilBuffer = NULL; IDXGIAdapter1* D3D::Adapter = NULL;snehnakrani14/HactoberFest211-10 #include #include using namespace std; #define ll long long #define MOD 1000000007 #define vi vector void solve(); int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int t=1; cin>>t; while(t--) { solve(); cout << "\n"; } return 0; } void solve() { long double W, H; cin >> W >> H; long double x1, x2, y1, y2; cin >> x1 >> y1 >> x2 >> y2; long double w, h; cin >> w >> h; long double left = x1; long double right = W - x2; long double down = y1; long double up = H - y2; long double ans = INT_MAX; long double hor = max(left, right); long double ver = max(up, down); if(hor >= w || ver >= h) { ans = 0; cout<= SURVIVOR_FRAME_COUNT ) survivorFrame = 0; } // drawSurvivors // draws every active survivor in the list to the display void drawSurvivors() { if (arduboy.everyXFrames(30)) showHelp = !showHelp; // draw the survivor! for (byte id = 0; id < SURVIVOR_MAX; id++) { Element &surv = survivors[id]; if (!surv.active) continue; sprites.drawErase(surv.x - mapPositionX, surv.y - mapPositionY, survivorMask, survivorType[id]); sprites.drawSelfMasked(surv.x - mapPositionX, surv.y - mapPositionY, survivor, survivorFrame + (4 * survivorType[id])); if (showHelp)sprites.drawPlusMask(surv.x + 16 - mapPositionX, surv.y - 9 - mapPositionY, help_plus_mask, 0); } } // survivorCollision // takes a survivor, collision box to test against // returns true if collision boxes intersect bool survivorCollision(Element& obj, int x, int y, sint w, sint h) { return ( obj.active ) && ( obj.x < x + w ) && ( obj.x + SURVIVOR_WIDTH > x ) && ( obj.y < y + h ) && ( obj.y + SURVIVOR_HEIGHT > y ); } // collectSurvivor // takes a survivor, sets it inactive. // returns false if no survivors are left on the map, otherwise true bool collectSurvivor(Element& obj) { byte id; obj.active = false; sound.tone(660, 20); rollingScore += 500; for (id = 0; id < SURVIVOR_MAX; id++) { if (survivors[id].active) return false; } return true; } // clearSurvivors // clears the entire list of survivors void clearSurvivors() { byte id; for (id = 0; id < SURVIVOR_MAX; id++) { survivors[id].active = false; } } void drawAmountSurvivors() { for (byte amountSurvivors = 0; amountSurvivors < countAmountActiveSurvivors(); amountSurvivors++) // needs the amount of active survivors { sprites.drawPlusMask(40 + amountSurvivors * 9, 0, HUD_plus_mask, 2); } if (!countAmountActiveSurvivors()) { if (showHelp) { sprites.drawPlusMask(45, 0, HUD_plus_mask, 3); //55 sprites.drawPlusMask(54, 0, HUD_plus_mask, 4); //64 } sprites.drawPlusMask(65, 0, HUD_plus_mask, 5); sprites.drawPlusMask(74, 0, HUD_plus_mask, 6); drawNumbers(68, 1, FONT_TINY, DATA_TIMER); } } byte countAmountActiveSurvivors() { byte id; byte countAmount = 0; for (id = 0; id < SURVIVOR_MAX; id++) { if (survivors[id].active) countAmount++; } return countAmount; }; void survivorCollide(int x, int y) { byte id; for (id = 0; id < SURVIVOR_MAX; id++) { if (survivorCollision(survivors[id], x, y, PLAYER_WIDTH, PLAYER_HEIGHT)) { if (collectSurvivor(survivors[id])) { exitDoor.active = true; } } } } BIJOY-SUST/ACM---ICPC #include #include #include #include #include using namespace std; int main(){ int i,n,T,j,ara[10000],d,mid,sum; scanf("%d",&T); while(T--){ scanf("%d",&n); for(i=1;i<=n;i++){ scanf("%d",&ara[i]); } sort(ara,ara+n+1); if(n%2==0){ d=n/2; mid=ara[d]; } else{ d=(n/2)+1; mid=ara[d]; } sum=0; for(j=1;j<=n;j++){ sum+=abs(mid-ara[j]); } printf("%d\n",sum); } return 0; } maurossi/drm_hwcomposer /* * Copyright (C) 2015 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. */ #define LOG_TAG "hwc-platform-drm-generic" #include "drmdevice.h" #include "platform.h" #include "platformdrmgeneric.h" #include #include #include #include #include #include namespace android { #ifdef USE_DRM_GENERIC_IMPORTER // static Importer *Importer::CreateInstance(DrmDevice *drm) { DrmGenericImporter *importer = new DrmGenericImporter(drm); if (!importer) return NULL; int ret = importer->Init(); if (ret) { ALOGE("Failed to initialize the nv importer %d", ret); delete importer; return NULL; } return importer; } #endif DrmGenericImporter::DrmGenericImporter(DrmDevice *drm) : drm_(drm) { } DrmGenericImporter::~DrmGenericImporter() { } int DrmGenericImporter::Init() { int ret = hw_get_module(GRALLOC_HARDWARE_MODULE_ID, (const hw_module_t **)&gralloc_); if (ret) { ALOGE("Failed to open gralloc module"); return ret; } return 0; } uint32_t DrmGenericImporter::ConvertHalFormatToDrm(uint32_t hal_format) { switch (hal_format) { case HAL_PIXEL_FORMAT_RGB_888: return DRM_FORMAT_BGR888; case HAL_PIXEL_FORMAT_BGRA_8888: return DRM_FORMAT_ARGB8888; case HAL_PIXEL_FORMAT_RGBX_8888: return DRM_FORMAT_XBGR8888; case HAL_PIXEL_FORMAT_RGBA_8888: return DRM_FORMAT_ABGR8888; case HAL_PIXEL_FORMAT_RGB_565: return DRM_FORMAT_BGR565; case HAL_PIXEL_FORMAT_YV12: return DRM_FORMAT_YVU420; default: ALOGE("Cannot convert hal format to drm format %u", hal_format); return -EINVAL; } } int DrmGenericImporter::ImportBuffer(buffer_handle_t handle, hwc_drm_bo_t *bo) { gralloc_handle_t *gr_handle = gralloc_handle(handle); if (!gr_handle) return -EINVAL; uint32_t gem_handle; int ret = drmPrimeFDToHandle(drm_->fd(), gr_handle->prime_fd, &gem_handle); if (ret) { ALOGE("failed to import prime fd %d ret=%d", gr_handle->prime_fd, ret); return ret; } memset(bo, 0, sizeof(hwc_drm_bo_t)); bo->width = gr_handle->width; bo->height = gr_handle->height; bo->format = ConvertHalFormatToDrm(gr_handle->format); bo->usage = gr_handle->usage; bo->pitches[0] = gr_handle->stride; bo->gem_handles[0] = gem_handle; bo->offsets[0] = 0; ret = drmModeAddFB2(drm_->fd(), bo->width, bo->height, bo->format, bo->gem_handles, bo->pitches, bo->offsets, &bo->fb_id, 0); if (ret) { ALOGE("could not create drm fb %d", ret); return ret; } return ret; } int DrmGenericImporter::ReleaseBuffer(hwc_drm_bo_t *bo) { if (bo->fb_id) if (drmModeRmFB(drm_->fd(), bo->fb_id)) ALOGE("Failed to rm fb"); struct drm_gem_close gem_close; memset(&gem_close, 0, sizeof(gem_close)); int num_gem_handles = sizeof(bo->gem_handles) / sizeof(bo->gem_handles[0]); for (int i = 0; i < num_gem_handles; i++) { if (!bo->gem_handles[i]) continue; gem_close.handle = bo->gem_handles[i]; int ret = drmIoctl(drm_->fd(), DRM_IOCTL_GEM_CLOSE, &gem_close); if (ret) { ALOGE("Failed to close gem handle %d %d", i, ret); } else { for (int j = i + 1; j < num_gem_handles; j++) if (bo->gem_handles[j] == bo->gem_handles[i]) bo->gem_handles[j] = 0; bo->gem_handles[i] = 0; } } return 0; } #ifdef USE_DRM_GENERIC_IMPORTER std::unique_ptr Planner::CreateInstance(DrmDevice *) { std::unique_ptr planner(new Planner); planner->AddStage(); return planner; } #endif } ghi-electronics/NETMF-Open-Firmware //----------------------------------------------------------------------------- // // ** WARNING! ** // This file was generated automatically by a tool. // Re-running the tool will overwrite this file. // You should copy this file to a custom location // before adding any customization in the copy to // prevent loss of your changes when the tool is // re-run. // //----------------------------------------------------------------------------- #include "Lib.h" #include "Lib_GHI_Networking_WiFiRS9110.h" using namespace GHI::Networking; UINT16 WiFiRS9110::NativeGetLastJoinError( CLR_RT_HeapBlock* pMngObj, HRESULT &hr ) { hr = CLR_E_NOT_SUPPORTED; return 0; } INT32 WiFiRS9110::NativeGetScanResponseSize( CLR_RT_HeapBlock* pMngObj, HRESULT &hr ) { hr = CLR_E_NOT_SUPPORTED; return 0; } INT32 WiFiRS9110::NativeGetBssidReponseSize( CLR_RT_HeapBlock* pMngObj, HRESULT &hr ) { hr = CLR_E_NOT_SUPPORTED; return 0; } void WiFiRS9110::NativeSetHalConfig( CLR_RT_HeapBlock* pMngObj, HRESULT &hr ) { hr = CLR_E_NOT_SUPPORTED; } void WiFiRS9110::NativeTriggerContinuation( CLR_RT_HeapBlock* pMngObj, HRESULT &hr ) { hr = CLR_E_NOT_SUPPORTED; } void WiFiRS9110::NativeInitializeContinuations( CLR_RT_HeapBlock* pMngObj, HRESULT &hr ) { hr = CLR_E_NOT_SUPPORTED; } void WiFiRS9110::NativeUninitializeContinuations( CLR_RT_HeapBlock* pMngObj, HRESULT &hr ) { hr = CLR_E_NOT_SUPPORTED; } INT8 WiFiRS9110::NativeInitializeSpiInterfaceRequest( CLR_RT_HeapBlock* pMngObj, HRESULT &hr ) { hr = CLR_E_NOT_SUPPORTED; return 0; } INT32 WiFiRS9110::NativeGetEvent( CLR_RT_HeapBlock* pMngObj, HRESULT &hr ) { hr = CLR_E_NOT_SUPPORTED; return 0; } INT8 WiFiRS9110::NativeSetBootloaderOption( CLR_RT_HeapBlock* pMngObj, INT32 param0, HRESULT &hr ) { hr = CLR_E_NOT_SUPPORTED; return 0; } INT8 WiFiRS9110::NativeQueryMacAddress( CLR_RT_HeapBlock* pMngObj, HRESULT &hr ) { hr = CLR_E_NOT_SUPPORTED; return 0; } void WiFiRS9110::NativeGetInternalMacAddress( CLR_RT_HeapBlock* pMngObj, CLR_RT_TypedArray_UINT8 param0, HRESULT &hr ) { hr = CLR_E_NOT_SUPPORTED; } void WiFiRS9110::NativeSendBandRequest( CLR_RT_HeapBlock* pMngObj, INT32 param0, HRESULT &hr ) { hr = CLR_E_NOT_SUPPORTED; } void WiFiRS9110::NativeInitializeRequest( CLR_RT_HeapBlock* pMngObj, HRESULT &hr ) { hr = CLR_E_NOT_SUPPORTED; } INT8 WiFiRS9110::NativeScan( CLR_RT_HeapBlock* pMngObj, UINT32 param0, LPCSTR param1, HRESULT &hr ) { hr = CLR_E_NOT_SUPPORTED; return 0; } INT8 WiFiRS9110::NativeSendBssidRequest( CLR_RT_HeapBlock* pMngObj, HRESULT &hr ) { hr = CLR_E_NOT_SUPPORTED; return 0; } INT32 WiFiRS9110::NativeGetBssidResponse( CLR_RT_HeapBlock* pMngObj, CLR_RT_TypedArray_UINT8 param0, HRESULT &hr ) { hr = CLR_E_NOT_SUPPORTED; return 0; } INT8 WiFiRS9110::NativeDisconnect( CLR_RT_HeapBlock* pMngObj, HRESULT &hr ) { hr = CLR_E_NOT_SUPPORTED; return 0; } INT8 WiFiRS9110::NativeQueryConnectionStatus( CLR_RT_HeapBlock* pMngObj, HRESULT &hr ) { hr = CLR_E_NOT_SUPPORTED; return 0; } INT32 WiFiRS9110::NativeGetConnectionStatus( CLR_RT_HeapBlock* pMngObj, HRESULT &hr ) { hr = CLR_E_NOT_SUPPORTED; return 0; } INT8 WiFiRS9110::NativeQueryFirmwareVersion( CLR_RT_HeapBlock* pMngObj, HRESULT &hr ) { hr = CLR_E_NOT_SUPPORTED; return 0; } LPCSTR WiFiRS9110::NativeGetFirmwareVersion( CLR_RT_HeapBlock* pMngObj, HRESULT &hr ) { hr = CLR_E_NOT_SUPPORTED; return 0; } INT8 WiFiRS9110::NativeJoin( CLR_RT_HeapBlock* pMngObj, INT32 param0, INT32 param1, CLR_RT_TypedArray_UINT8 param2, CLR_RT_TypedArray_UINT8 param3, INT32 param4, INT32 param5, INT32 param6, INT32 param7, INT32 param8, HRESULT &hr ) { hr = CLR_E_NOT_SUPPORTED; return 0; } INT8 WiFiRS9110::NativeExecuteCompletion( CLR_RT_HeapBlock* pMngObj, HRESULT &hr ) { INT8 retVal = 0; return retVal; } /** * @file GimbalCtrl.cpp * Class to send to control camera gimbal * Designed for the LIS-EPFL DroneCourse * * @author <> * @author <> */ #include "GimbalCtrl.hpp" #include #include #include #include #include #include #include GimbalCtrl::GimbalCtrl() { // -------------------------------------------------- // TODO subscribe to uORB messages: // target_position_ned_filtered, // vehicle_attitude and vehicle_local_position // -------------------------------------------------- _target_position_ned_filtered_sub = orb_subscribe(ORB_ID(target_position_ned_filtered)); _vehicle_attitude_sub = orb_subscribe(ORB_ID(vehicle_attitude)); _local_pos_sub = orb_subscribe(ORB_ID(vehicle_local_position)); // set publishing handle for gimbal_command to nullptr _gimbal_command_pub = nullptr; // Set inital angles downward facing set_command(-M_PI / 2, 0.0f); } GimbalCtrl::~GimbalCtrl() { // -------------------------------------------------- // TODO unsubscribe from uORB messages: // target_position_ned_filtered, // vehicle_attitude and vehicle_local_position // -------------------------------------------------- orb_unsubscribe(_target_position_ned_filtered_sub); orb_unsubscribe(_vehicle_attitude_sub); orb_unsubscribe(_local_pos_sub); // Unadvertise if(_gimbal_command_pub != nullptr) { orb_unadvertise(_gimbal_command_pub); _gimbal_command_pub = nullptr; } } void GimbalCtrl::set_command(float pitch, float yaw) { _mode = MODE::MANUAL; // Limit pitch if (pitch > 0.0f) { pitch = 0.0f; } else if (pitch < (float)(- M_PI)) { pitch = - M_PI; } publish_gimbal_command(pitch, yaw); } void GimbalCtrl::update() { if (_mode == MODE::AUTOMATIC) { // target position in local frame target_position_ned_filtered_s target_pos_lf; // drone's attitude //matrix::Quaternion att_vehicle; vehicle_attitude_s att_vehicle; // drone's position vehicle_local_position_s pos_vehicle; // ------------------------------------------------ // TODO set target position from uORB // ------------------------------------------------ orb_copy(ORB_ID(target_position_ned_filtered), _target_position_ned_filtered_sub, &target_pos_lf); matrix::Vector3f _target_pos; _target_pos(0) = target_pos_lf.x; _target_pos(1) = target_pos_lf.y; _target_pos(2) = target_pos_lf.z; // ------------------------------------------------ // TODO set drone's attitude from uORB // ------------------------------------------------ orb_copy(ORB_ID(vehicle_attitude), _vehicle_attitude_sub, &att_vehicle); matrix::Quaternion attitude; attitude = att_vehicle.q; // ------------------------------------------------ // TODO set drone position from uORB // ------------------------------------------------ orb_copy(ORB_ID(vehicle_local_position), _local_pos_sub, &pos_vehicle); matrix::Vector3f position_vehicle; position_vehicle(0) = pos_vehicle.x; position_vehicle(1) = pos_vehicle.y; position_vehicle(2) = pos_vehicle.z; // create variable for target direction const matrix::Vector3f target_dir = compute_target_direction(_target_pos, position_vehicle); // create variables for drone's Z and Y axis in local frame const matrix::Vector3f down_lf = compute_down_axis(attitude); const matrix::Vector3f east_lf = compute_east_axis(attitude); // create variable for normal vector of auxiliary plane // containing target direction and drone's Z axis in local frame const matrix::Vector3f n = compute_normal_vector(target_dir, down_lf); // create variable for yaw and pitch float yaw = compute_yaw(target_dir, n, down_lf, east_lf); float pitch = compute_pitch(target_dir, n, down_lf, east_lf); // publish uORB message publish_gimbal_command(pitch, yaw); } } matrix::Vector3f GimbalCtrl::compute_target_direction(const matrix::Vector3f target_pos_ned, const matrix::Vector3f pos_vehicle) { // ------------------------------------------------ // TODO compute target direction // i.e., vector from drone to target // ------------------------------------------------ matrix::Vector3f T; T = target_pos_ned - pos_vehicle; T.normalize(); return T; } matrix::Vector3f GimbalCtrl::compute_down_axis(matrix::Quaternion attitude) { // ------------------------------------------------ // TODO compute drone's Z axis in local frame // ------------------------------------------------ //matrix::Dcm Z_local_frame_int(attitude.inversed()); matrix::Vector3f Z(0,0,1); //matrix::Vector3f Z_local_frame; //Z_local_frame = Z_local_frame_int*Z; return attitude.conjugate_inversed(Z); } matrix::Vector3f GimbalCtrl::compute_east_axis(matrix::Quaternion attitude) { // ------------------------------------------------ // TODO compute drone's Y axis in local frame // ------------------------------------------------ //matrix::Dcm Y_local_frame_int(attitude.inversed()); matrix::Vector3f Y(0,1,0); //matrix::Vector3f Y_local_frame; //Y_local_frame = Y_local_frame_int*Y; //return Y_local_frame; return attitude.conjugate_inversed(Y); } matrix::Vector3f GimbalCtrl::compute_normal_vector(const matrix::Vector3f target_direction, const matrix::Vector3f down_lf) { // --------------------------------------------------- // TODO find normal vector of auxiliary plane // containing target direction and // drone's Z axis in local frame // --------------------------------------------------- matrix::Vector3f normal_V; normal_V = target_direction.cross(down_lf); normal_V.normalize(); //normal_V(0) = target_direction(1)*down_lf(2) - target_direction(2)*down_lf(1); //normal_V(1) = target_direction(2)*down_lf(0) - target_direction(0)*down_lf(2); //normal_V(2) = target_direction(0)*down_lf(1) - target_direction(1)*down_lf(0); return normal_V; } float GimbalCtrl::compute_yaw(matrix::Vector3f target_direction, matrix::Vector3f n, matrix::Vector3f down_lf, matrix::Vector3f east_lf) { // --------------------------------------------------------------------- // TODO find desired yaw angle as angle between // the plane's normal vector and the drone's Y axis in local frame // --------------------------------------------------------------------- float Y; double dot_P; double yaw_Direction; matrix::Vector3f cross_Product; dot_P = east_lf.dot(n); cross_Product = east_lf.cross(n); yaw_Direction = cross_Product.dot(down_lf); if (yaw_Direction < 0) { Y = -acos((double)dot_P/(double)((east_lf.norm())*(n.norm()))); } if (yaw_Direction >= 0) { Y = acos((double)dot_P/(double)((east_lf.norm())*(n.norm()))); } return Y; } float GimbalCtrl::compute_pitch(matrix::Vector3f target_direction, matrix::Vector3f n, matrix::Vector3f down_lf, matrix::Vector3f east_lf) { // ---------------------------------------------------------- // TODO find desired pitch angle as angle between // drone's Z axis in local frame and target direction // ---------------------------------------------------------- float P; double dot_Product; dot_Product = down_lf.dot(target_direction); P = -M_PI/2 - acos((double)dot_Product); return P; } void GimbalCtrl::publish_gimbal_command(float pitch, float yaw) { // -------------------------------------------------------- // TODO publish gimbal_command over uORB // -------------------------------------------------------- gimbal_command_s gimbal_command_msg; gimbal_command_msg.timestamp = hrt_absolute_time(); gimbal_command_msg.pitch = pitch; gimbal_command_msg.yaw = yaw; int instance; orb_publish_auto(ORB_ID(gimbal_command), &_gimbal_command_pub, &gimbal_command_msg, &instance, ORB_PRIO_HIGH); } Darker1990/Project-TZK-Since2.12TZK_Objects/Scripts/RHS_Hind/CfgAmmo.hpp class CfgAmmo { class Default{}; class AT3: Default{}; class Hellfire: AT3{}; class Zuni: Hellfire{}; class RHS_57mmS5: Zuni { model = "\RHS_hind\RHS_S5.p3d"; soundHit[]={\RHS_hind\sounds\S5_explo,100,1}; hit=200;indirectHit=100;indirectHitRange=2.5; initTime=0.020; thrustTime=8; thrust=1200; minRange=50; minRangeProbab=0.300000; midRange=500; midRangeProbab=0.990000; maxRange=1000; maxRangeProbab=0.650000; }; class RHS_80mmS8: Zuni { model = "\RHS_hind\RHS_S8.p3d"; soundHit[]={\RHS_hind\sounds\S8_explo,100,1}; hit=300;indirectHit=200;indirectHitRange=2.5; initTime=0.020; thrustTime=8; thrust=1200; minRange=50; minRangeProbab=0.300000; midRange=500; midRangeProbab=0.990000; maxRange=1000; maxRangeProbab=0.650000; }; class RHS_Gunpodammo: RHS_57mmS5 { soundHit[]={"\RHS_hind\sounds\23hit",10,1}; soundHitArmor[]={"\RHS_hind\sounds\23hitarmor",10,1}; hitGround[]={"soundHit",1}; hitMan[]={"soundHit",1}; hitArmor[]={"soundHitArmor",1}; hitBuilding[]={"soundHit",1}; hit=40;indirectHit=15;indirectHitRange=2.5; minRange=30; minRangeProbab=0.600000; midRange=450; midRangeProbab=0.990000; maxRange=750; maxRangeProbab=0.350000; model = "\RHS_hind\RHS_23mm.p3d"; irLock=1; explosive=0; airLock=1; manualControl=0; initTime=10; thrustTime=16; thrust=2400; }; class RHS_AGS17ammo: RHS_57mmS5 { soundHit[]={"\RHS_hind\sounds\AGS_explo",10,0.7}; hit=40;indirectHit=20;indirectHitRange=5; minRange=30; minRangeProbab=0.500000; midRange=450; midRangeProbab=0.990000; maxRange=750; maxRangeProbab=0.300000; model = "\RHS_hind\RHS_AGS17.p3d"; irLock=0; explosive=1; airLock=0; manualControl=0; initTime=10; thrustTime=2; thrust=50; }; class RHS_AT2:Hellfire { hit=400; indirectHit=120; indirectHitRange=2; proxyShape="\RHS_Hind\RHS_AT2_Proxy.p3d"; model="\RHS_Hind\RHS_AT2.p3d"; soundHit[]={"\RHS_hind\sounds\AT2_explo",100,1}; initTime=0.015; thrustTime=8; thrust=250; maneuvrability=3; minRange=500; minRangeProbab=0.010000; midRange=1200; midRangeProbab=0.900000; maxRange=1750; maxRangeProbab=0.400000; }; class AT6: Hellfire {}; class RHS_AT6a: AT6 { model = "\RHS_Hind\RHS_AT6.p3d"; proxyShape="\RHS_Hind\RHS_AT6a_Proxy.p3d"; hit=790;indirectHit=450;indirectHitRange=5; soundHit[]={"\RHS_hind\sounds\AT6_explo",100,1}; initTime=0.015; thrustTime=10; thrust=300; maneuvrability=10; minRange=50; minRangeProbab=0.030000; midRange=1000; midRangeProbab=0.950000; maxRange=1800; maxRangeProbab=0.500000; }; class RHS_AT6b: RHS_AT6a { proxyShape="\RHS_Hind\RHS_AT6b_Proxy.p3d"; maneuvrability=20; minRange=500; minRangeProbab=0.050000; midRange=1000; midRangeProbab=0.990000; maxRange=1800; maxRangeProbab=0.500000; }; class RHS_AT6c: RHS_AT6a { proxyShape="\RHS_Hind\RHS_AT6c_Proxy.p3d"; }; class RHS_AT6d: RHS_AT6a { proxyShape="\RHS_Hind\RHS_AT6d_Proxy.p3d"; maneuvrability=20; minRange=500; minRangeProbab=0.050000; midRange=1000; midRangeProbab=0.990000; maxRange=1800; maxRangeProbab=0.500000; }; class BulletSingle : Default {}; class ExplosiveBullet: BulletSingle {}; class Bullet30: ExplosiveBullet{}; class Bullet30E: Bullet30{}; class RHS_30mm: Bullet30E { soundHit[]={"\RHS_hind\sounds\30hit",1,1}; soundHitMan[]={"\RHS_hind\sounds\30hitman",1,1}; soundHitArmor1[]={"\RHS_hind\sounds\30hitarmor1",1,1}; soundHitArmor2[]={"\RHS_hind\sounds\30hitarmor2",1,1}; soundHitArmor3[]={"\RHS_hind\sounds\30hitarmor3",1,1}; hitGround[]={"soundHit",1}; hitMan[]={"soundHitMan",1}; hitArmor[]={"soundHitArmor1",0.7,"soundHitArmor2",0.15,"soundHitArmor3",0.15}; hitBuilding[]={"soundHit",1}; explosive=0; hit=50; indirectHit=20; indirectHitRange=3; tracerColor[]={0,0,0,0.000000}; tracerColorR[]={0,0,0,0.000000}; // DASH: вероятности как у 30мм снаряда от БИС minRange=10; minRangeProbab=0.2; midRange=250; midRangeProbab=0.5; maxRange=1000; maxRangeProbab=0.05; }; class Bullet7_6: BulletSingle{}; class Bullet12_7: Bullet7_6{}; class RHS_12_7mm: Bullet30E { soundHit1[]={"weapons\bulletricochet1",0.4,1}; soundHit2[]={"weapons\bulletricochet2",0.4,1}; soundHit3[]={"weapons\bulletricochet3",0.4,1}; soundHitMan1[]={"weapons\bullethitman1",0.3,1}; soundHitMan2[]={"weapons\bullethitman2",0.3,1}; soundHitArmor1[]={"weapons\small_impact1",0.5,1}; soundHitArmor2[]={"weapons\Big_Impact2",0.5,1}; soundHitBuilding1[]={"weapons\bulletricochet4",0.4,1}; soundHitBuilding2[]={"weapons\bulletricochet5",0.4,1}; hitGround[]={"soundHit1",0.33,"soundHit2",0.33,"soundHit3",0.33}; hitMan[]={"soundHitMan1",0.5,"soundHitMan2",0.5}; hitArmor[]={"soundHitArmor1",0.7,"soundHitArmor2",0.3}; hitBuilding[]={"soundHitBuilding1",0.5,"soundHitBuilding2",0.5}; /* DASH: убрал нах непрямой урон прямой урон позволяет ботам гасить цели с броней до 250 hit=20; indirectHit=8; indirectHitRange=1.5; */ hit=25; indirectHit=0; indirectHitRange=0; explosive=0; tracerColor[]={0,0,0,0.000000}; tracerColorR[]={0,0,0,0.000000}; // DASH: вероятности как у 30мм снаряда от БИС minRange=10; minRangeProbab=0.2; midRange=250; midRangeProbab=0.5; maxRange=1000; maxRangeProbab=0.05; }; }; Dawlau/target-followerheaders/Follower.hpp #ifndef FOLLOWER_H #define FOLLOWER_H #include "glm/glm.hpp" #include "glm/gtc/matrix_transform.hpp" #include "glm/gtx/transform.hpp" #include "glm/gtc/type_ptr.hpp" #include #include "geometry.hpp" #include "Target.hpp" class Follower { private: static constexpr float rotationAngleOffset = 0.0005f; static constexpr float translationOffset = 0.0005f; static constexpr float collisionDistance = 0.1f; std::vector< glm::vec4 > points; float rotation; float xTranslation; float yTranslation; float liveRotation; float livexTranslation; float liveyTranslation; public: Follower(); glm::vec3 getCentroid(); glm::mat4 getTransformation(); bool getLiveAnimation(); void updateAnimation(const Target &); bool detectCollision(const Target &); void reInitAnimation(); void updatePoints(); std::vector < glm::vec4 > getPoints(); }; #endif#include "CondFormats/DataRecord/interface/FFTJetCorrectorParametersRcdTypes.h" #include "FWCore/Framework/interface/eventsetuprecord_registration_macro.h" EVENTSETUP_RECORD_REG(FFTBasicJetCorrectorParametersRcd); EVENTSETUP_RECORD_REG(FFTGenJetCorrectorParametersRcd); EVENTSETUP_RECORD_REG(FFTCaloJetCorrectorParametersRcd); EVENTSETUP_RECORD_REG(FFTPFJetCorrectorParametersRcd); EVENTSETUP_RECORD_REG(FFTTrackJetCorrectorParametersRcd); EVENTSETUP_RECORD_REG(FFTJPTJetCorrectorParametersRcd); EVENTSETUP_RECORD_REG(FFTPFCHS0CorrectorParametersRcd); EVENTSETUP_RECORD_REG(FFTPFCHS1CorrectorParametersRcd); EVENTSETUP_RECORD_REG(FFTPFCHS2CorrectorParametersRcd); EVENTSETUP_RECORD_REG(FFTBasicJetSysCorrectorParametersRcd); EVENTSETUP_RECORD_REG(FFTGenJetSysCorrectorParametersRcd); EVENTSETUP_RECORD_REG(FFTCaloJetSysCorrectorParametersRcd); EVENTSETUP_RECORD_REG(FFTPFJetSysCorrectorParametersRcd); EVENTSETUP_RECORD_REG(FFTTrackJetSysCorrectorParametersRcd); EVENTSETUP_RECORD_REG(FFTJPTJetSysCorrectorParametersRcd); EVENTSETUP_RECORD_REG(FFTPFCHS0SysCorrectorParametersRcd); EVENTSETUP_RECORD_REG(FFTPFCHS1SysCorrectorParametersRcd); EVENTSETUP_RECORD_REG(FFTPFCHS2SysCorrectorParametersRcd); EVENTSETUP_RECORD_REG(FFTGen0CorrectorParametersRcd); EVENTSETUP_RECORD_REG(FFTGen1CorrectorParametersRcd); EVENTSETUP_RECORD_REG(FFTGen2CorrectorParametersRcd); EVENTSETUP_RECORD_REG(FFTPF0CorrectorParametersRcd); EVENTSETUP_RECORD_REG(FFTPF1CorrectorParametersRcd); EVENTSETUP_RECORD_REG(FFTPF2CorrectorParametersRcd); EVENTSETUP_RECORD_REG(FFTPF3CorrectorParametersRcd); EVENTSETUP_RECORD_REG(FFTPF4CorrectorParametersRcd); EVENTSETUP_RECORD_REG(FFTCalo0CorrectorParametersRcd); EVENTSETUP_RECORD_REG(FFTCalo1CorrectorParametersRcd); EVENTSETUP_RECORD_REG(FFTCalo2CorrectorParametersRcd); EVENTSETUP_RECORD_REG(FFTCalo3CorrectorParametersRcd); EVENTSETUP_RECORD_REG(FFTCalo4CorrectorParametersRcd); EVENTSETUP_RECORD_REG(FFTGen0SysCorrectorParametersRcd); EVENTSETUP_RECORD_REG(FFTGen1SysCorrectorParametersRcd); EVENTSETUP_RECORD_REG(FFTGen2SysCorrectorParametersRcd); EVENTSETUP_RECORD_REG(FFTPF0SysCorrectorParametersRcd); EVENTSETUP_RECORD_REG(FFTPF1SysCorrectorParametersRcd); EVENTSETUP_RECORD_REG(FFTPF2SysCorrectorParametersRcd); EVENTSETUP_RECORD_REG(FFTPF3SysCorrectorParametersRcd); EVENTSETUP_RECORD_REG(FFTPF4SysCorrectorParametersRcd); EVENTSETUP_RECORD_REG(FFTPF5SysCorrectorParametersRcd); EVENTSETUP_RECORD_REG(FFTPF6SysCorrectorParametersRcd); EVENTSETUP_RECORD_REG(FFTPF7SysCorrectorParametersRcd); EVENTSETUP_RECORD_REG(FFTPF8SysCorrectorParametersRcd); EVENTSETUP_RECORD_REG(FFTPF9SysCorrectorParametersRcd); EVENTSETUP_RECORD_REG(FFTCalo0SysCorrectorParametersRcd); EVENTSETUP_RECORD_REG(FFTCalo1SysCorrectorParametersRcd); EVENTSETUP_RECORD_REG(FFTCalo2SysCorrectorParametersRcd); EVENTSETUP_RECORD_REG(FFTCalo3SysCorrectorParametersRcd); EVENTSETUP_RECORD_REG(FFTCalo4SysCorrectorParametersRcd); EVENTSETUP_RECORD_REG(FFTCalo5SysCorrectorParametersRcd); EVENTSETUP_RECORD_REG(FFTCalo6SysCorrectorParametersRcd); EVENTSETUP_RECORD_REG(FFTCalo7SysCorrectorParametersRcd); EVENTSETUP_RECORD_REG(FFTCalo8SysCorrectorParametersRcd); EVENTSETUP_RECORD_REG(FFTCalo9SysCorrectorParametersRcd); EVENTSETUP_RECORD_REG(FFTCHS0SysCorrectorParametersRcd); EVENTSETUP_RECORD_REG(FFTCHS1SysCorrectorParametersRcd); EVENTSETUP_RECORD_REG(FFTCHS2SysCorrectorParametersRcd); EVENTSETUP_RECORD_REG(FFTCHS3SysCorrectorParametersRcd); EVENTSETUP_RECORD_REG(FFTCHS4SysCorrectorParametersRcd); EVENTSETUP_RECORD_REG(FFTCHS5SysCorrectorParametersRcd); EVENTSETUP_RECORD_REG(FFTCHS6SysCorrectorParametersRcd); EVENTSETUP_RECORD_REG(FFTCHS7SysCorrectorParametersRcd); EVENTSETUP_RECORD_REG(FFTCHS8SysCorrectorParametersRcd); EVENTSETUP_RECORD_REG(FFTCHS9SysCorrectorParametersRcd); EVENTSETUP_RECORD_REG(FFTEtaFlatteningFactorsParametersRcd); EVENTSETUP_RECORD_REG(FFTPileupRhoCalibrationParametersRcd); EVENTSETUP_RECORD_REG(FFTPileupRhoEtaDependenceParametersRcd); EVENTSETUP_RECORD_REG(FFTLUT0ParametersRcd); EVENTSETUP_RECORD_REG(FFTLUT1ParametersRcd); EVENTSETUP_RECORD_REG(FFTLUT2ParametersRcd); EVENTSETUP_RECORD_REG(FFTLUT3ParametersRcd); EVENTSETUP_RECORD_REG(FFTLUT4ParametersRcd); EVENTSETUP_RECORD_REG(FFTLUT5ParametersRcd); EVENTSETUP_RECORD_REG(FFTLUT6ParametersRcd); EVENTSETUP_RECORD_REG(FFTLUT7ParametersRcd); EVENTSETUP_RECORD_REG(FFTLUT8ParametersRcd); EVENTSETUP_RECORD_REG(FFTLUT9ParametersRcd); EVENTSETUP_RECORD_REG(FFTLUT10ParametersRcd); EVENTSETUP_RECORD_REG(FFTLUT11ParametersRcd); EVENTSETUP_RECORD_REG(FFTLUT12ParametersRcd); EVENTSETUP_RECORD_REG(FFTLUT13ParametersRcd); EVENTSETUP_RECORD_REG(FFTLUT14ParametersRcd); EVENTSETUP_RECORD_REG(FFTLUT15ParametersRcd); /** * Created by Xiaozhong on 2020/10/31. * Copyright (c) 2020/10/31 Xiaozhong. All rights reserved. */ #include #include #include using namespace std; class Solution { public: int countSubstrings(string s, string t) { int ans = 0; int m = s.size(), n = t.size(); for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { int diff = 0; for (int k = 0; i + k < m && j + k < n; ++k) { diff += (s[i + k] != t[j + k]); if (diff > 1) break; if (diff == 1) ++ans; } } } return ans; } };Ginkgo-Biloba/Cpp-Repo1-VS #include "leetcode.hpp" /* 1114. 按序打印 我们提供了一个类: public class Foo { public void one() { print("one"); } public void two() { print("two"); } public void three() { print("three"); } } 三个不同的线程将会共用一个 Foo 实例。 线程 A 将会调用 one() 方法 线程 B 将会调用 two() 方法 线程 C 将会调用 three() 方法 请设计修改程序,以确保 two() 方法在 one() 方法之后被执行,three() 方法在 two() 方法之后被执行。 示例 1: 输入: [1,2,3] 输出: "onetwothree" 解释: 有三个线程会被异步启动。 输入 [1,2,3] 表示线程 A 将会调用 one() 方法,线程 B 将会调用 two() 方法,线程 C 将会调用 three() 方法。 正确的输出是 "onetwothree"。 示例 2: 输入: [1,3,2] 输出: "onetwothree" 解释: 输入 [1,3,2] 表示线程 A 将会调用 one() 方法,线程 B 将会调用 three() 方法,线程 C 将会调用 two() 方法。 正确的输出是 "onetwothree"。 注意: 尽管输入中的数字似乎暗示了顺序,但是我们并不保证线程在操作系统中的调度顺序。 你看到的输入格式主要是为了确保测试的全面性。 */ #include class Foo { int n; public: Foo() : n(0) {} void first(std::function printFirst) { // printFirst() outputs "first". Do not change or remove this line. printFirst(); __sync_fetch_and_add(&n, 1); } void second(std::function printSecond) { while (__sync_fetch_and_add(&n, 0) != 1) _mm_pause(); // printSecond() outputs "second". Do not change or remove this line. printSecond(); __sync_fetch_and_add(&n, 1); } void third(std::function printThird) { while (__sync_fetch_and_add(&n, 0) != 2) _mm_pause(); // printThird() outputs "third". Do not change or remove this line. printThird(); } }; int main() {} 0 #include "BulletC.h" #include "ComponentsManager.h" #include "Entity.h" #include "FactoriesFactory.h" #include "RigidbodyPC.h" #include "Scene.h" #include "TransformComponent.h" #include #include BulletC::BulletC() {} BulletC::~BulletC() {} void BulletC::destroy() { setActive(false); scene_->getComponentsManager()->eraseDC(this); } void BulletC::setDamage(float d) { damage_ = d; } float BulletC::getDamage() { return damage_; } void BulletC::dealCollision() { scene_->deleteEntity(father_); } // FACTORY INFRASTRUCTURE BulletCFactory::BulletCFactory() = default; Component* BulletCFactory::create(Entity* _father, Json::Value& _data, Scene* _scene) { BulletC* bullet = new BulletC(); _scene->getComponentsManager()->addDC(bullet); bullet->setFather(_father); bullet->setScene(_scene); return bullet; }; DEFINE_FACTORY(BulletC); 0@P`p�������� 0@P`p�������� 0@P`p�������� 0@P`p�������� 0@P`p�������� 0@P`p�������� 0@P`p�������� 0@P`p�������� 0@P`p��������  0 @ P ` p � � � � � � � �  0 @ P ` p � � � � � � � �  0 @ P ` p � � � � � � � �  0 @ P ` p � � � � � � � �  0 @ P ` p � � � � � � � �  0@P`p�������� 0@P`p�������� 0@P`p�������� 0@P`p�������� 0@P`p�������� 0@P`p�������� 0@P`p�������� 0@P`p�������� 0@P`p�������� 0@P`p�������� 0@P`p�������� 0@P`p�������� 0@P`p�������� 0@P`p�������� 0@P`p�������� 0@P`p�������� 0@P`p�������� 0@P`p��������  0 @ P ` p � � � � � � � � !! !0!@!P!`!p!�!�!�!�!�!�!�!�!"" "0"@"P"`"p"�"�"�"�"�"�"�"�"## #0#@#P#`#p#�#�#�#�#�#�#�#�#$$ $0$@$P$`$p$�$�$�$�$�$�$�$�$%% %0%@%P%`%p%�%�%�%�%�%�%�%�%&& &0&@&P&`&p&�&�&�&�&�&�&�&�&'' '0'@'P'`'p'�'�'�'�'�'�'�'�'(( (0(@(P(`(p(�(�(�(�(�(�(�(�()) )0)@)P)`)p)�)�)�)�)�)�)�)�)** *0*@*P*`*p*�*�*�*�*�*�*�*�*++ +0+@+P+`+p+�+�+�+�+�+�+�+�+,, ,0,@,P,`,p,�,�,�,�,�,�,�,�,-- -0-@-P-`-p-�-�-�-�-�-�-�-�-.. .0.@.P.`.p.�.�.�.�.�.�.�.�.// /0/@/P/`/p/�/�/�/�/�/�/�/�/00 000@0P0`0p0�0�0�0�0�0�0�0�011 101@1P1`1p1�1�1�1�1�1�1�1�122 202@2P2`2p2�2�2�2�2�2�2�2�233 303@3P3`3p3�3�3�3�3�3�3�3�344 404@4P4`4p4�4�4�4�4�4�4�4�455 505@5P5`5p5�5�5�5�5�5�5�5�566 606@6P6`6p6�6�6�6�6�6�6�6�677 707@7P7`7p7�7�7�7�7�7�7�7�788 808@8P8`8p8�8�8�8�8�8�8�8�899 909@9P9`9p9�9�9�9�9�9�9�9�9:: :0:@:P:`:p:�:�:�:�:�:�:�:�:;; ;0;@;P;`;p;�;�;�;�;�;�;�;�;<< <0<@<P<`<p<�<�<�<�<�<�<�<�<== =0=@=P=`=p=�=�=�=�=�=�=�=�=>> >0>@>P>`>p>�>StarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCppStarcoderdataCpp����  �IA   �@   mxx �![�@�A�A �%A$@@@"(/6=DKRY`gnu|�������������������  '.5<CJQX_elsz�������������������  '.5<CJQX_fmt{������������������� ")07>ELSZahov}�������������������  &-4;BIPU\cjqx������������������#*17>ELSZahou|������������������� !(/6=DKRY`fmt{�������������������  '.5<CJQX_elsy������������������� &-4;BIPW]dkry�������������������    % + 2 9 ? F K R Y ` g n t { � � � � � � � � � � � � � � � � � � �    ' . 4 : A G N U \ b i p w ~ � � � � � � � � � � � � � � � � � � �    ' . 5 < C J Q X _ f m t { � � � � � � � � � � � � � � � � � � �    ! ( - 3 : A G N U \ c j p w ~ � � � � � � � � � � � � � � � � � � �    ! ( / 6 = D K R Y ` g n u | � � � � � � � � � � � � � � � � � � ")07>ELSZahov}������������������")/6=DJQX_fm6211255291519397972546668205576891249645329422839333971203833559020647815954597019348814233762834677620390446850203283872144626140283185254471295560888320545622838731218226184637628843323514670383687206860428145773394788384915533091822575018603764375942955157841459013547940877187817254675913582480855255653871936642395837927812263236109555894961643717601335777421212792340286893134040415729139618111333502503194361206252835576568482043833611161778347349737212128879313129675517140321434384057144446120438564356128887171095858562754355933764197273821352554601271786184950341493724975285112554129769695113666495391112472683484950294060339600962490284412405862868491152972446895154882737486355573012260342774660115332651674940410122402191444808267260756094892605347534514323795786319476474156130045246420161344945226711835024269613263431213056661465008153463403354078554969233528986199655335688145727505061482572858268809417117962650862481953469101741034453802977372346394925767911815710084103360525299752669783791417323475911262965363984196011757223065942743639953765830506655652809482027915413131126684317786951927841520091498977335431432966015304552547610822719276269774293220360304532488030128004174375611531585792048461947249696531546191117983566958635406791807620298721439387953283722173360839730483110550323602312292326197097197746016129309969148862525178965406971954065981026493570670382247511760911746699348215256150736333557463222206215512172147028336146788200777926240236232389509241739053572433802458745643251983710548422748613063982600213632515914636623618512032097250400724041503969694542864039699213887867105159414118009608073018683349060253375871434259287594570194160782894463034194133660709235367705212384451046059142154539483133775150237282558618192505714752601378754552567249181655961604433623319755259020404125204203346562178122565772358955232133012036970475665816741324281694736413360778918358839849473163698428931053595323745871462913945248672123445221552317716326026463191703047275001990479332075758824251755723272146133040944345665816312571070952750711468484311569613481256314672858366562631826124155131258472244841839022780424486126429055160192553252786182485228966238623465879277557895423220054013178429142430310101153903212255447761062692801365013171879054926172344934921295360703158228363031822378809537937042924876792673556643815575155555245900205967904790768586311726304585015469257718636462425339422759582141149235623511126090541230224095352127648457984252198622186727126683307367998388168499852674171237301524137915301461280789312336732454835697307222141550728365122609613194331777829523034889147975854834725258229747655209864281428608569977833130821123144901280414633854122350293161868550230359556269602028512180765760980466134249305730019284755320875469051147899215213592394044175950574268432835631421916018823947696613300228827435506024142369328001381114314453687539959681887372250761733273566015287325284554144813437704119148360168097702095894342162904536448316321831131779837352422532673188841288503828697771715402427043537540425793147491504249931624804505579215043797674306422309045260304066062117857258102323344942937075125755835218636102632568420376374656482421094521149943498233935471604032211350715145665764953719153685315303104860904794573847445230319383445443734503936638547924720372513291170138210355990301852345089480106388820948551043373556609442832482910509227091714609725105210186150453790265622626482155672974737587705694600193938255560783019170314980534056593004275617710762047381058028556018255065743641454263021449501236002191403505917785372841300224486756936435052042943151138669941199635209527220874726243544629554478335249785015304923166432035821311039217522477710464815927142195377420470326312211907785447521412807752686809251427938355451953379265555408570251604011984245491440011684802518707605681383008739556434433264613671794795362165693604114360071612033445813371503032418530445143565952863�s$Q'We�i8nco �����A��V�պ��s��l�/$CMe�f�g��0�Ţ� ��o�� v%7jg�i:u����6��)�1u@ F[e�h�j�zn��%�t�l���`�X���Z�=��/w! ) JQM��d�����i;+<�Gg`rp�x$�A�D���2�%�K�����J6$#c#]$�$�B��� ������4_?�R�S����P��. zG �c �i cl � 3> *C /N X �_ �c �j ?} |� � _� G� � � � ̵ ͸ �� � �� �� � � �/ 2 �: i? �] �` �} �� 3� M� J� �� �� 9� � H� �� z� s � [ & @E UZ �m �� �� � q� T� �2�$�P�\Q`�iylo�o�s;�:���V����/�8YW�Yr�+lXo�p�v� �?��v�w�q������)�5IdMjQMS�a�cDy�q�K�t��%�����$&�R^�s����[���.��A[D�Om[��W�J��cA<]X[f�h,w�{ۏǐє�Χ�%�O���o������5�6�H�ju�z����e 9�Kn��� J 7(l)l~���b�a��n�O���G�ȼ&��Ϛ֠,��,�N�W�^?di��?�E������=@�Ysdf�jnOq��N � � �B Xy � E� �� � %� �� u� �� �� �� $� b� OO!Z}!��!ܢ!'�!�"�P"�V"�o"�|"/�"��" �""�"��"��"9�"�#@#�R#`U#&X#�g#<�#)�#֣#%�#��#��#^�#;�#s$�$t$r$ 2$�y$��$l�$ %\ %;%%@%�#%�&%p/%�B%�U%�Y%�h%|q%s%�s%��%� &� &B"&4�&X�&�&��'��'��'| (�V(Q](P_(_i(t(�w( z(��(��(�( �(d�(��(��(D�(�)))A�-��-]�-��-�.�).�-.D/.05.�7.�A.�O.�W.�c.��.}�.�.�.B�.-�.��.K�.//'2/�N/�\/�b/-{/މ/��/��/��/r�/2�/ �0�0:�0r�0��0z1�1�1�1R 1*01:C1�N1CY1�Z15�1B�18�1z�1h�1h�1L�1� 2� 2pa2�o2�w2у2�2#�2��27�2K3 3�!3�03tD3�U3�Y3�`3��3�3m�3�3��3��3��3��3J434�4V"4�&4|)4�44�94�B4 W4�a4��4�4��4v�4g�4_�4u�4��48565�C5^Q5o5��5j6�6S 6� 6-y6�z6�6�6��6Ң6�6-�6��6��6P�6�6��6��6��6��67�7a7T75<7\A7[D7Ǽ7O�7�73�7G8zN>~P>�Z>�v>�>��>�??�?�!?�"?�+?�T?�h?��?�?�?�{@�~@��@[�@c++/Palm/PalmWindow.hpp //////////////////////////////////////////////////////////////////////////////////////// //...................................................................................... // This is a part of AI Library [Arthur's Interfaces Library]. . // 1998-2001 . //...................................................................................... // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND . // DO NOT REMOVE MY NAME AND THIS NOTICE FROM THE SOURCE . //...................................................................................... //////////////////////////////////////////////////////////////////////////////////////// #ifndef __PALM_WINDOW_H__ #define __PALM_WINDOW_H__ #ifdef __PALM_OS__ #pragma once __BEGIN_NAMESPACE__ //////////////////////////////////////////////////////////////////////////////////////// // class PalmWindow // ----- ---------- class __DECLSPEC__ PalmWindow { private: WinHandle Handle; public: // ctor/dtor PalmWindow(WinHandle = 0); ~PalmWindow(); // operators operator const WindowType* () const; operator WindowType* (); // access bool IsValid() const; bool IsModal() const; WinHandle GetHandle() const; // api bool ValidateHandle(WinHandle); void CreateWindow(const Rect&, FrameType, bool, bool, uint16&); void CreateOffscreenWindow(Coord, Coord, WindowFormatType, uint16&); void CreateOffscreenWindow(const Size&, WindowFormatType, uint16&); void CreateBitmapWindow(const PalmBitmap&, uint16&); void DestroyWindow(bool = true); void InitializeWindow(); void AddWindow(); void RemoveWindow(); void MoveWindowAddr(WindowType*); static WinHandle GetActiveWindow(); void SetActiveWindow(); static WinHandle GetDrawWindow(); WinHandle SetDrawWindow(); void EnableWindow(); void DisableWindow(); static WinHandle GetDisplayWindow(); static WinHandle GetFirstWindow(); void GetWindowFrameRect(Rect&); static void EraseWindow(); static void DrawWindowFrame(); BitmapType* GetBitmap(); static WinHandle SaveBits(const Rect&, uint16&); void RestoreBits(Coord, Coord); void RestoreBits(const Point&); #if (__PALM_OS__ >= 0x0400) static void GetDrawWindowBounds(Rect&); void GetBounds(Rect&); void SetBounds(const Rect&); #else static void GetWindowBounds(Rect&); void SetWindowBounds(const Rect&); #endif void CopyRectangle(WinHandle, const Rect&, Coord, Coord, WinDrawOperation); void CopyRectangle(WinHandle, const Rect&, const Point&, WinDrawOperation); static void GetDisplayExtent(Coord&, Coord&); static void GetDisplayExtent(Size&); static void GetWindowExtent(Coord&, Coord&); static void GetWindowExtent(Size&); static void DisplayToWindowPt(Coord&, Coord&); static void DisplayToWindowPt(Point&); static void WindowToDisplayPt(Coord&, Coord&); static void WindowToDisplayPt(Point&); static void GetClip(Rect&); static void SetClip (const Rect&); static void ResetClip(); static void ClipRectangle(Rect&); static void ScrollRectangle(const Rect&, WinDirectionType, Coord, Rect&); static void ScreenInit(); static Err ScreenMode(WinScreenModeOperation, uint32&, uint32&, uint32&, bool&); static uint8* ScreenLock(WinLockInitType); static void ScreenUnlock(); public: class __DECLSPEC__ XPalmWindow : public PalmError { public: enum EErrors { // appErrorClass+'wind' }; protected: virtual void LoadErrorDescriptions(); }; friend class XPalmWindow; }; //////////////////////////////////////////////////////////////////////////////////////// __END_NAMESPACE__ #endif // __PALM_OS__ #endif // __PALM_WINDOW_H__ //--------------------------------------------------------------------------- // // Module: cn.cpp // // Description: // // //@@BEGIN_MSINTERNAL // Development Team: // // // History: Date Author Comment // // To Do: Date Author Comment // //@@END_MSINTERNAL // // 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) 1996-1999 Microsoft Corporation. All Rights Reserved. // //--------------------------------------------------------------------------- #include "common.h" //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- NTSTATUS CConnectNode::Create( PCONNECT_NODE *ppConnectNode, PLOGICAL_FILTER_NODE pLogicalFilterNode, PCONNECT_NODE pConnectNodeNext, PGRAPH_PIN_INFO pGraphPinInfo, PPIN_NODE pPinNode1, PPIN_NODE pPinNode2, ULONG ulFlagsCurrent, PGRAPH_NODE pGraphNode ) { NTSTATUS Status = STATUS_SUCCESS; PCONNECT_NODE pConnectNode; Assert(pPinNode1); Assert(pPinNode2); pConnectNode = new CConnectNode(pConnectNodeNext); if(pConnectNode == NULL) { Status = STATUS_INSUFFICIENT_RESOURCES; goto exit; } switch(pPinNode1->pPinInfo->Communication) { case KSPIN_COMMUNICATION_BOTH: switch(pPinNode2->pPinInfo->Communication) { case KSPIN_COMMUNICATION_SINK: pConnectNode->pPinNodeSource = pPinNode1; pConnectNode->pPinNodeSink = pPinNode2; break; case KSPIN_COMMUNICATION_BOTH: case KSPIN_COMMUNICATION_SOURCE: pConnectNode->pPinNodeSource = pPinNode2; pConnectNode->pPinNodeSink = pPinNode1; break; default: ASSERT(FALSE); Status = STATUS_INVALID_PARAMETER; goto exit; } break; case KSPIN_COMMUNICATION_SINK: pConnectNode->pPinNodeSink = pPinNode1; pConnectNode->pPinNodeSource = pPinNode2; ASSERT( pPinNode2->pPinInfo->Communication == KSPIN_COMMUNICATION_BOTH || pPinNode2->pPinInfo->Communication == KSPIN_COMMUNICATION_SOURCE); break; case KSPIN_COMMUNICATION_SOURCE: pConnectNode->pPinNodeSink = pPinNode2; pConnectNode->pPinNodeSource = pPinNode1; ASSERT( pPinNode2->pPinInfo->Communication == KSPIN_COMMUNICATION_SINK || pPinNode2->pPinInfo->Communication == KSPIN_COMMUNICATION_BOTH); break; default: ASSERT(FALSE); Status = STATUS_INVALID_PARAMETER; goto exit; } Status = CConnectInfo::Create( pConnectNode, pLogicalFilterNode, pConnectNodeNext->GetConnectInfo(), pGraphPinInfo, ulFlagsCurrent, pGraphNode); if(!NT_SUCCESS(Status)) { Trap(); goto exit; } if(pLogicalFilterNode->GetFlags() & LFN_FLAGS_NO_BYPASS) { Status = pGraphNode->lstLogicalFilterNodeNoBypass.AddList( pLogicalFilterNode, pConnectNode); if(!NT_SUCCESS(Status)) { Trap(); goto exit; } } DPF3(80, "CConnectNode::Create %08x PN %08x %08x", pConnectNode, pConnectNode->pPinNodeSink, pConnectNode->pPinNodeSource); exit: if(!NT_SUCCESS(Status)) { if (pConnectNode) { pConnectNode->Destroy(); } pConnectNode = NULL; } *ppConnectNode = pConnectNode; return(Status); } CConnectNode::CConnectNode( PCONNECT_NODE pConnectNodeNext ) { this->pConnectNodeNext = pConnectNodeNext; pConnectNodeNext->AddRef(); AddRef(); DPF1(80, "CConnectNode:%08x PN:%08x %08x", this); } CConnectNode::~CConnectNode( ) { Assert(this); DPF1(80, "~CConnectNode: %08x", this); pConnectInfo->Destroy(); pConnectNodeNext->Destroy(); } //--------------------------------------------------------------------------- SDL/Game5/InputComponent.cpp #include "InputComponent.h" #include "Actor.h" InputComponent::InputComponent(class Actor* owner) : MoveComponent(owner), maxForwardSpeed(0.0f), maxAngularSpeed(0.0f), forwardKey(0), backKey(0), clockwiseKey(0), counterClockwiseKey(0) {} void InputComponent::ProcessInput(const std::uint8_t* keyState) { float forwardSpeed = 0.0f; if (keyState[forwardKey]) forwardSpeed += maxForwardSpeed; if (keyState[backKey]) forwardSpeed -= maxForwardSpeed; SetForwardSpeed(forwardSpeed); float angularSpeed = 0.0f; if (keyState[clockwiseKey]) angularSpeed += maxAngularSpeed; if (keyState[counterClockwiseKey]) angularSpeed -= maxAngularSpeed; SetAngularSpeed(angularSpeed); }Setting.cpp #include "StdAfx.h" #include "Resource.h" #include "setting.h" #include "LanguageDialog.h" CSetting::CSetting ( void ) : m_SettingFile ( _T ( "" ) ) { m_TestReadMode = false; m_IgnoreError = false; m_SwapChannel = false; m_AutoDetectMethod = true; m_Speed_Audio = 0xff; m_Speed_Data = 0xff; m_ReadAudioMethod = 1; m_SubQMethod = 0; m_CopyTempFile = ""; m_BurstErrorCount = 5; m_BurstErrorSkip = 100; { LPSTR p; int l, fg; char Buffer[2048]; p = GetCommandLine(); fg = 0; if ( *p == '\"' ) { p++; fg = 1; } l = lstrlen ( p ); if ( l > 1 ) { lstrcpy ( Buffer, p ); p = Buffer; if ( fg == 1 ) { while ( *p != '\"' ) { p++; } } else { while ( *p != '\0' && *p != ' ' ) { p++; } } while ( *p != '\\' && p > Buffer ) { p--; } *p = '\0'; lstrcat ( Buffer, "\\" ); } else { lstrcpy ( Buffer, ".\\" ); } m_Dir = Buffer; m_SettingFile.Format ( "%sCarbonCD.ini", Buffer ); } // Load(); } CSetting::~CSetting ( void ) { Save(); } int CSetting::BoolToInt ( bool value ) { return ( value == true ) ? 1 : 0; } bool CSetting::IntToBool ( int value ) { return ( value != 0 ) ? true : false; } void CSetting::WriteInt ( LPCSTR lpAppName, LPCSTR lpKeyName, int Value ) { CString cs; cs.Format ( "%d", Value ); WritePrivateProfileString ( lpAppName, lpKeyName, ( LPCSTR ) cs, m_SettingFile ); } void CSetting::WriteString ( LPCSTR lpAppName, LPCSTR lpKeyName, LPCSTR Value ) { WritePrivateProfileString ( lpAppName, lpKeyName, Value, m_SettingFile ); } int CSetting::ReadInt ( LPCSTR lpAppName, LPCSTR lpKeyName, int DefaultValue ) { return GetPrivateProfileInt ( lpAppName, lpKeyName, DefaultValue, m_SettingFile ); } void CSetting::ReadString ( LPCSTR lpAppName, LPCSTR lpKeyName, LPCSTR DefaultValue, CString &String ) { char Buffer[1024]; GetPrivateProfileString ( lpAppName, lpKeyName, DefaultValue, Buffer, 1024, m_SettingFile ); Buffer[1023] = '\0'; String = Buffer; return; } void CSetting::Load ( void ) { // general m_DriveNo = ReadInt ( "General", "DriveNo", 0 ); ReadString ( "General", "AspiDLL", "", m_AspiDLL ); ReadString ( "General", "LogFile", "", m_AutoLogFile ); ReadString ( "General", "Language", "", m_LangFile ); ReadString ( "General", "Skin", "", m_SkinFile ); ReadString ( "General", "WavOnSuccess", "", m_WavOnSuccess ); ReadString ( "General", "WavOnFail", "", m_WavOnFail ); ReadString ( "General", "LastAccessFile", "", m_LastAccessFile ); m_ShowLogWnd = ReadInt ( "General", "LogWindow", 0 ); m_ShowTocWnd = ReadInt ( "General", "TOCWindow", 1 ); m_Speed_SubQ = ReadInt ( "General", "SubQSpeed", 0xff ); m_PriorityClass = ReadInt ( "General", "PriorityClass", 0 ); m_UseSPTI = ReadInt ( "General", "UseSPTI", 1 ); m_MainDlgPos.x = ReadInt ( "General", "MainDlgX", 100 ); m_MainDlgPos.y = ReadInt ( "General", "MainDlgy", 100 ); if ( m_MainDlgPos.x < 0 ) { m_MainDlgPos.x = 0; } if ( m_MainDlgPos.y < 0 ) { m_MainDlgPos.y = 0; } m_TocWnd.left = ReadInt ( "General", "TocWndX", 100 ); m_TocWnd.top = ReadInt ( "General", "TocWndY", 350 ); m_TocWnd.right = ReadInt ( "General", "TocWndCX", 600 ); m_TocWnd.bottom = ReadInt ( "General", "TocWndCY", 300 ); if ( m_TocWnd.left < 0 ) { m_TocWnd.left = 0; } if ( m_TocWnd.top < 0 ) { m_TocWnd.top = 0; } if ( m_TocWnd.right < 0 ) { m_TocWnd.right = 0; } if ( m_TocWnd.bottom < 0 ) { m_TocWnd.bottom = 0; } m_LogWnd.left = ReadInt ( "General", "LogWndX", 30 ); m_LogWnd.top = ReadInt ( "General", "LogWndY", 30 ); m_LogWnd.right = ReadInt ( "General", "LogWndCX", 400 ); m_LogWnd.bottom = ReadInt ( "General", "LogWndCY", 200 ); if ( m_LogWnd.left < 0 ) { m_LogWnd.left = 0; } if ( m_LogWnd.top < 0 ) { m_LogWnd.top = 0; } if ( m_LogWnd.right < 0 ) { m_LogWnd.right = 0; } if ( m_LogWnd.bottom < 0 ) { m_LogWnd.bottom = 0; } // read setting m_TestReadMode = IntToBool ( ReadInt ( "ReadSetting", "TestReadMode", 0 ) ); m_IgnoreError = IntToBool ( ReadInt ( "ReadSetting", "IgnoreError", 0 ) ); m_FastErrorSkip = IntToBool ( ReadInt ( "ReadSetting", "FastErrorSkip", 0 ) ); m_SwapChannel = IntToBool ( ReadInt ( "ReadSetting", "SwapAudioChannel", 0 ) ); m_AutoDetectMethod = IntToBool ( ReadInt ( "ReadSetting", "AutoDetectCommand", 1 ) ); m_Speed_Audio = ReadInt ( "ReadSetting", "AudioSpeed", 0xff ); m_Speed_Data = ReadInt ( "ReadSetting", "DataSpeed", 0xff ); m_ReadAudioMethod = ReadInt ( "ReadSetting", "ReadCommand", 1 ); m_SubQMethod = ReadInt ( "ReadSetting", "SubQMethod", 0 ); m_AnalyzeSubQ = IntToBool ( ReadInt ( "ReadSetting", "AnalyzeSubQ", 0 ) ); m_BurstErrorScan = ReadInt ( "ReadSetting", "BurstErrorScan", 0 ); // m_MultiSession = ReadInt("ReadSetting","MultiSession",0); m_AnalyzePregap = ReadInt ( "ReadSetting", "AnalyzePregap", 0 ); m_ExtSetting_Read = ReadInt ( "ReadSetting", "ExtendedSettings", 0 ); m_ReadEngine = ReadInt ( "ReadSetting", "Engine", 0 ); // write setting m_Write_BurnProof = ReadInt ( "WriteSetting", "BurnProof", 1 ); m_Write_EjectTray = ReadInt ( "WriteSetting", "EjectTray", 1 ); m_Write_TestMode = ReadInt ( "WriteSetting", "TestMode", 0 ); m_Write_Opc = ReadInt ( "WriteSetting", "PowerCalibration", 1 ); m_Write_CheckDrive = ReadInt ( "WriteSetting", "CheckDrive", 1 ); m_Write_WritingMode = ReadInt ( "WriteSetting", "WritingMode", 0 ); m_Write_AutoDetectMethod = ReadInt ( "WriteSetting", "AutoDetectCommand", 1 ); m_Write_Speed = ReadInt ( "WriteSetting", "Speed", 255 ); m_Write_Buffer = ReadInt ( "WriteSetting", "Buffer", 15 ); m_ExtSetting_Write = ReadInt ( "WriteSetting", "ExtendedSettings", 0 ); { OSVERSIONINFO osver; osver.dwOSVersionInfoSize = sizeof ( osver ); if ( GetVersionEx ( &osver ) ) { if ( osver.dwPlatformId != VER_PLATFORM_WIN32_NT ) { m_UseSPTI = 0; } } } // copy setting ReadString ( "CopySetting", "TemporaryFile", "", m_CopyTempFile ); // mastering setting m_Mastering_AlwaysOnTop = ReadInt ( "MasteringSetting", "AlwaysOnTop", 0 ); m_Mastering_NotifyTruncated = ReadInt ( "MasteringSetting", "NotifyTruncated", 1 ); #if COPY_PROTECTION m_CopyProtectionSize = ReadInt ( "MasteringSetting", "CopyProtectionSize", 0 ); #else m_CopyProtectionSize = 0; #endif // load language if ( m_LangFile == "" ) { CLanguageDialog dlg; if ( dlg.DoModal() == IDCANCEL ) { m_LangFile.Format ( "%sEnglish.cml", m_Dir ); } } else if ( m_LangFile[0] == '\\' || ( m_LangFile[0] >= 'a' && m_LangFile[0] <= 'z' && m_LangFile[1] == ':' ) || ( m_LangFile[0] >= 'A' && m_LangFile[0] <= 'Z' && m_LangFile[1] == ':' ) ) { } else { CString cs; cs.Format ( "%s%s", m_Dir, m_LangFile ); m_LangFile = cs; } m_Lang.ReadLanguage ( m_LangFile ); SetPriority(); } void CSetting::Save ( void ) { BYTE *q; LPCSTR lf; // split language file name q = ( BYTE* ) ( ( LPCSTR ) ( m_LangFile ) ); lf = NULL; while ( *q != '\0' ) { if ( ( *q >= 0x80 && *q <= 0x9f ) || *q > 0xe0 ) { q++; } else if ( *q == '\\' ) { lf = ( LPCSTR ) ( q + 1 ); } q++; } if ( lf == NULL ) { lf = m_LangFile; } // general WriteInt ( "General", "DriveNo", m_DriveNo ); WriteString ( "General", "AspiDLL", m_AspiDLL ); WriteString ( "General", "LogFile", m_AutoLogFile ); WriteString ( "General", "Language", lf ); WriteString ( "General", "Skin", m_SkinFile ); WriteString ( "General", "WavOnSuccess", m_WavOnSuccess ); WriteString ( "General", "WavOnFail", m_WavOnFail ); WriteString ( "General", "LastAccessFile", m_LastAccessFile ); WriteInt ( "General", "LogWindow", m_ShowLogWnd ); WriteInt ( "General", "TOCWindow", m_ShowTocWnd ); WriteInt ( "General", "SubQSpeed", m_Speed_SubQ ); WriteInt ( "General", "MainDlgX", m_MainDlgPos.x ); WriteInt ( "General", "MainDlgy", m_MainDlgPos.y ); WriteInt ( "General", "TocWndX", m_TocWnd.left ); WriteInt ( "General", "TocWndY", m_TocWnd.top ); WriteInt ( "General", "TocWndCX", m_TocWnd.right ); WriteInt ( "General", "TocWndCY", m_TocWnd.bottom ); WriteInt ( "General", "LogWndX", m_LogWnd.left ); WriteInt ( "General", "LogWndY", m_LogWnd.top ); WriteInt ( "General", "LogWndCX", m_LogWnd.right ); WriteInt ( "General", "LogWndCY", m_LogWnd.bottom ); WriteInt ( "General", "PriorityClass", m_PriorityClass ); WriteInt ( "General", "UseSPTI", m_UseSPTI ); // read setting WriteInt ( "ReadSetting", "TestReadMode", BoolToInt ( m_TestReadMode ) ); WriteInt ( "ReadSetting", "IgnoreError", BoolToInt ( m_IgnoreError ) ); WriteInt ( "ReadSetting", "FastErrorSkip", BoolToInt ( m_FastErrorSkip ) ); WriteInt ( "ReadSetting", "SwapAudioChannel", BoolToInt ( m_SwapChannel ) ); WriteInt ( "ReadSetting", "AutoDetectCommand", BoolToInt ( m_AutoDetectMethod ) ); WriteInt ( "ReadSetting", "AudioSpeed", m_Speed_Audio ); WriteInt ( "ReadSetting", "DataSpeed", m_Speed_Data ); WriteInt ( "ReadSetting", "ReadCommand", m_ReadAudioMethod ); WriteInt ( "ReadSetting", "SubQMethod", m_SubQMethod ); WriteInt ( "ReadSetting", "AnalyzeSubQ", BoolToInt ( m_AnalyzeSubQ ) ); WriteInt ( "ReadSetting", "BurstErrorScan", m_BurstErrorScan ); // WriteInt("ReadSetting","MultiSession",m_MultiSession); WriteInt ( "ReadSetting", "AnalyzePregap", m_AnalyzePregap ); WriteInt ( "ReadSetting", "ExtendedSettings", m_ExtSetting_Read ); WriteInt ( "ReadSetting", "Engine", m_ReadEngine ); WriteInt ( "WriteSetting", "BurnProof", m_Write_BurnProof ); WriteInt ( "WriteSetting", "EjectTray", m_Write_EjectTray ); WriteInt ( "WriteSetting", "TestMode", m_Write_TestMode ); WriteInt ( "WriteSetting", "PowerCalibration", m_Write_Opc ); WriteInt ( "WriteSetting", "CheckDrive", m_Write_CheckDrive ); WriteInt ( "WriteSetting", "WritingMode", m_Write_WritingMode ); WriteInt ( "WriteSetting", "AutoDetectCommand", m_Write_AutoDetectMethod ); WriteInt ( "WriteSetting", "Speed", m_Write_Speed ); WriteInt ( "WriteSetting", "Buffer", m_Write_Buffer ); WriteInt ( "WriteSetting", "ExtendedSettings", m_ExtSetting_Write ); WriteString ( "CopySetting", "TemporaryFile", m_CopyTempFile ); WriteInt ( "MasteringSetting", "AlwaysOnTop", m_Mastering_AlwaysOnTop ); WriteInt ( "MasteringSetting", "NotifyTruncated", m_Mastering_NotifyTruncated ); #if COPY_PROTECTION WriteInt ( "MasteringSetting", "CopyProtectionSize", m_CopyProtectionSize ); #endif } void CSetting::SetPriority ( void ) { if ( m_PriorityClass == 0 ) { SetPriorityClass ( GetCurrentProcess(), NORMAL_PRIORITY_CLASS ); } else if ( m_PriorityClass == 1 ) { SetPriorityClass ( GetCurrentProcess(), IDLE_PRIORITY_CLASS ); } else if ( m_PriorityClass == 2 ) { SetPriorityClass ( GetCurrentProcess(), HIGH_PRIORITY_CLASS ); } } sp/src/game/client/firefightreloaded/vgui/fr_mainmenu.cpp0 #include "cbase.h" #include "fr_mainmenu.h" #include "fr_mainmenu_interface.h" #include #include using namespace vgui; // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" // See interface.h/.cpp for specifics: basically this ensures that we actually Sys_UnloadModule the dll and that we don't call Sys_LoadModule // over and over again. static CDllDemandLoader g_GameUIDLL("GameUI"); CFRMainMenu *guiroot = NULL; void OverrideMainMenu() { if (!MainMenu->GetPanel()) { MainMenu->Create(NULL); } if (guiroot->GetGameUI()) { guiroot->GetGameUI()->SetMainMenuOverride(guiroot->GetVPanel()); return; } } //----------------------------------------------------------------------------- // Purpose: Constructor //----------------------------------------------------------------------------- CFRMainMenu::CFRMainMenu(VPANEL parent) : vgui::EditablePanel(NULL, "MainMenu") { SetParent(parent); guiroot = this; gameui = NULL; LoadGameUI(); SetScheme("ClientScheme"); SetDragEnabled(false); SetShowDragHelper(false); SetProportional(false); SetVisible(true); surface()->GetScreenSize(width, height); SetSize(width, height); SetPos(0, 0); MainMenuPanel = new CFRMainMenuPanel(this); vgui::ivgui()->AddTickSignal(GetVPanel(), 100); } //----------------------------------------------------------------------------- // Purpose: Destructor //----------------------------------------------------------------------------- CFRMainMenu::~CFRMainMenu() { gameui = NULL; g_GameUIDLL.Unload(); } void CFRMainMenu::ShowPanel(MenuPanel iPanel) { switch (iPanel) { case MAIN_MENU: MainMenuPanel->SetVisible(true); break; default: break; } } void CFRMainMenu::HidePanel(MenuPanel iPanel) { switch (iPanel) { case MAIN_MENU: MainMenuPanel->SetVisible(false); break; default: break; } } IGameUI *CFRMainMenu::GetGameUI() { if (!gameui) { if (!LoadGameUI()) return NULL; } return gameui; } bool CFRMainMenu::LoadGameUI() { if (!gameui) { CreateInterfaceFn gameUIFactory = g_GameUIDLL.GetFactory(); if (gameUIFactory) { gameui = (IGameUI *)gameUIFactory(GAMEUI_INTERFACE_VERSION, NULL); if (!gameui) { return false; } } else { return false; } } return true; } void CFRMainMenu::ApplySchemeSettings(vgui::IScheme *pScheme) { BaseClass::ApplySchemeSettings(pScheme); } void CFRMainMenu::PerformLayout() { BaseClass::PerformLayout(); }; void CFRMainMenu::OnCommand(const char* command) { engine->ExecuteClientCmd(command); } void CFRMainMenu::OnTick() { BaseClass::OnTick(); if (!engine->IsDrawingLoadingImage() && !IsVisible()) { SetVisible(true); } int newWidth, newHeight; surface()->GetScreenSize(newWidth, newHeight); if (width != newWidth || height != newHeight) { //restart the panel after applying res settings. width = newWidth; height = newHeight; SetSize(width, height); MainMenuPanel->SetParent((vgui::Panel *)NULL); delete MainMenuPanel; MainMenuPanel = new CFRMainMenuPanel(this); } }; void CFRMainMenu::OnThink() { BaseClass::OnThink(); if (engine->IsDrawingLoadingImage() && IsVisible()) { SetVisible(false); } }; void CFRMainMenu::PaintBackground() { SetPaintBackgroundType(0); BaseClass::PaintBackground(); } bool CFRMainMenu::InGame() { C_BasePlayer *pPlayer = C_BasePlayer::GetLocalPlayer(); if (pPlayer && IsVisible()) { return true; } else { return false; } }1-10 // Given an array arr[] of size N and two elements x and y, use counter variables to find which element appears most in the array, x or y. If both elements have the same frequency, then return the smaller element. // https://practice.geeksforgeeks.org/problems/who-has-the-majority/1/ // time is O(n) | space is O(1) int majorityWins(int arr[], int n, int x,int y){ int x_count = 0; int y_count = 0; for (int i = 0; i < n; i++){ if (x == arr[i]){ x_count++; } else if (y == arr[i]){ y_count += 1; } } if (x_count == y_count){ return min(x,y); } else if (x_count > y_count){ return x; } else { return y; } } int main() { int t; //Testcases cin>>t; // Input the testcases while(t--) //Until all testcases are exhausted { int n; //Size of array cin>>n; //Input the size int arr[n]; //Declaring array of size n for(int i=0;i>arr[i]; int x,y; //declare x and y cin>>x>>y; // input x and y cout << majorityWins(arr,n,x,y) << endl; //calling the function that you complete } return 0; }#include "opencv_modules.h" #ifdef HAVE_OPENCV_FACE #include "FacemarkLBF.h" #include "FacemarkLBFParams.h" #if CV_VERSION_GREATER_EQUAL(3, 4, 0) Nan::Persistent FacemarkLBF::constructor; NAN_MODULE_INIT(FacemarkLBF::Init) { v8::Local ctor = Nan::New(FacemarkLBF::New); v8::Local instanceTemplate = ctor->InstanceTemplate(); Facemark::Init(ctor); constructor.Reset(ctor); ctor->SetClassName(Nan::New("FacemarkLBF").ToLocalChecked()); instanceTemplate->SetInternalFieldCount(1); Nan::Set(target,Nan::New("FacemarkLBF").ToLocalChecked(), FF::getFunction(ctor)); }; NAN_METHOD(FacemarkLBF::New) { FF::TryCatch tryCatch("FacemarkLBF::New"); FF_ASSERT_CONSTRUCT_CALL(); cv::face::FacemarkLBF::Params params; if (FacemarkLBFParams::Converter::optArg(0, ¶ms, info)) { return tryCatch.reThrow(); } FacemarkLBF *self = new FacemarkLBF(); self->Wrap(info.Holder()); self->facemark = cv::face::FacemarkLBF::create(params); info.GetReturnValue().Set(info.Holder()); }; #endif #endif #ifndef CURRENT_DIALOGUE_BLOCK_HPP #define CURRENT_DIALOGUE_BLOCK_HPP #include #include "Packet.hpp" #define PACKET_CURRENT_DIALOGUE_BLOCK ('k') template <> class Packet { public: static void onReceive(const ENetEvent &event); }; #endif Programs/Binary Tree/BinaryTree.cpp // // BinaryTree.cpp // TestApps // // Created by on 8/7/14. // Copyright (c) 2014 . All rights reserved. // #include "BinaryTree.h" using namespace std; #include BinaryTree::BinaryTree(){ cout<< " Constructing a Binary Tree "<left)){ return false; } if (prev != NULL && prev->data >= root->data) { return false; } prev = root; return isBST(root->right); } node * BinaryTree::getParent(node * root, int data) { if(!root){ return NULL; } if (root->left && root->left->data == data) { return root; } if (root->right && root->right->data == data) { return root; } node * lh = getParent(root->left,data); node * rh = getParent(root->right, data); return (lh!=NULL) ? lh: rh; } node * BinaryTree::getNewNode(int data) { node * newNode =(node *) malloc(sizeof(node)); newNode->data = data; newNode->left = NULL; newNode->right = NULL; return newNode; } node * BinaryTree::findLCA(node * root ,int node1, int node2) { if (!root) { return NULL; } if (node1 == root->data) { return root; } if( node2 == root->data ){ return root; } node * lh = findLCA(root->left, node1, node2); node * rh = findLCA(root->right, node1, node2); if (lh && rh) { return root; } return (lh != NULL)?lh:rh; } int BinaryTree::findRangeSum(node * root, int min, int max) { if (!root) { return 0; } int value = 0; if (root->data >= min && root->data <= max) { value += root->data; } value += findRangeSum(root->left, min, max); value += findRangeSum(root->right, min, max); return value; } bool BinaryTree::hasPathSum(node * root, int sum) { if (!root) { return (sum == 0); } return hasPathSum(root->left, sum-root->data) || hasPathSum(root->right, sum-root->data); } void printAllPathsRecursive(node * root, int * paths, int pathLen) { if (!root) { return; } paths[pathLen] = root->data; pathLen++; if (root->left == NULL && root->right == NULL) { for (int i=0 ; i < pathLen; i++) { cout << paths[i] << " "; } cout<left, paths, pathLen); printAllPathsRecursive(root->right, paths, pathLen); } void BinaryTree::printAllPaths(node * root){ int paths[1000]; printAllPathsRecursive(root, paths, 0); } void inOrder(node* root) { if(!root) return; inOrder(root->left); cout<data<<" "; inOrder(root->right); } void preOrder(node * root){ if (!root) { return; } cout<data<<" "; preOrder(root->left); preOrder(root->right); } void postOrder(node * root) { if (!root) { return; } preOrder(root->left); preOrder(root->right); cout<data<<" "; } void levelOrderTraversal(node * root) { queue q; q.push(root); while (!q.empty()) { node * node = q.front(); cout<< node->data << " "; q.pop(); if (node->left) { q.push(node->left); } if (node->right) { q.push(node->right); } } } void BinaryTree::allTraversals(node * root) { cout<<"Inoder:" << endl; inOrder(root); cout<left); if (leftHeight == -1) { return -1; } int rightHeight = checkHeight(root->right); if (rightHeight == -1) { return -1; } int heightDiff = leftHeight - rightHeight; if (abs(heightDiff) > 1) { return -1; } else { return std::max(leftHeight, rightHeight) + 1; } } bool BinaryTree::isBalanced(node * root) { if (checkHeight(root) == -1) { return false; } else{ return true; } } node * createBSTFromArrayHelper(int * arr, int low, int high) { if (high < low) { return NULL; } int mid = (low + high )/ 2; node * node = BinaryTree::getNewNode(arr[mid]); node->left = createBSTFromArrayHelper(arr, low, mid-1); node->right = createBSTFromArrayHelper(arr, mid+1, high); return node; } node * BinaryTree::createBSTFromArray(int * arr, int n) { return createBSTFromArrayHelper(arr, 0, n-1); } node * findNodeInTree(node * root, int data){ if (!root) { return NULL; } if (root->data == data) { return root; } node * left = findNodeInTree(root->left, data); if (!left) { return findNodeInTree(root->right, data); } return NULL; } int BinaryTree::inOrderSuccesor(node * root, int data) { node * curr = findNodeInTree(root, data); if (curr->right) { // Find left most node in this } else{ node * successor = NULL; node * ancestor = root; while (ancestor != curr) { if (curr->data < ancestor ->data) { successor = ancestor; ancestor = ancestor->left; } else ancestor = ancestor->right; } } return 0; } bool matchTree(node * tree1, node * tree2){ if (tree1 == NULL && tree2 == NULL) { return true; } if (tree1 == NULL || tree2 == NULL) { return false; } if (tree1->data == tree2->data) { return matchTree(tree1->left, tree2->left) && matchTree(tree1->left, tree2->left); } return false; } bool findSubtree(node * tree1, node * tree2) { if (tree1 == NULL) { return false; } if (tree1->data == tree2->data) { return matchTree(tree1, tree2); } return matchTree(tree1->left, tree2) || matchTree(tree1->right, tree2); } bool BinaryTree::checkIfOneTreeExistsinOther(node * tree1, node * tree2) { if (tree2 == NULL) { return true; // Null tree is also a subtree } return false; } // Idea is to get max from left, and right and add to root // Also check if left is max than right, and get overall max int findOverallMax(node * root, int * res){ if (!root) { return 0; } int leftMax = findOverallMax(root->left, res); int rightMax = findOverallMax(root->right, res); int currMax = std::max((leftMax + rightMax + root->data), std::max(leftMax, rightMax)); if (*res < currMax) { *res = currMax; } return max(leftMax, rightMax) + root->data; } int BinaryTree::findMaxSumPath(node * root){ int res = 0; findOverallMax(root, &res); return res; } void findHorizontalDistance(node * root, int *left, int * right, int hd){ if (root == NULL) { return; } if (*left>hd) { *left = hd; } if (*right < hd) { *right = hd; } findHorizontalDistance(root->left, left, right, hd-1); findHorizontalDistance(root->right, left, right, hd+1); } void printAtLevel(node * root, int level, int hd){ if (!root) { return; } if (level == hd) { cout<< root-> data; } printAtLevel(root->left, level, hd-1); printAtLevel(root->right, level, hd+1); } void BinaryTree::printTreeVertical(node * root){ int leftMax = 0; int rightMax = 0; int horizontalDist = 0; findHorizontalDistance(root, &leftMax, &rightMax, horizontalDist); // Now using left and right max print the values for (int i = leftMax; i < rightMax; i++) { printAtLevel(root, i, 0); } } // -*- coding: utf-8 -*- // Copyright (C) 2012, 2014-2015, 2017-2018 Laboratoire de Recherche // et Développement de l'Epita (LRDE). // // This file is part of Spot, a model checking library. // // Spot 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. // // Spot 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 . #include "config.h" #include namespace spot { void strip_acceptance_here(twa_graph_ptr a) { unsigned n = a->num_states(); for (unsigned s = 0; s < n; ++s) for (auto& t: a->out(s)) t.acc = {}; a->set_generalized_buchi(0); a->release_named_properties(); a->prop_weak(true); } } mux-led/mux-led.cpp10-100 #include "Particle.h" #include "Adafruit_GFX_RK.h" #include "Adafruit_LEDBackpack_RK.h" #include "TCA9548A-RK.h" SYSTEM_THREAD(ENABLED); Adafruit_7segment sevenSeg; Adafruit_AlphaNum4 alphaNum; // Note: Because the default address for the TCA9548A is 0x70, which is also the address of the // LED backpack, we need to change the address. Connect the TCA9548A A0 line 1 to avoid the conflict! TCA9548A mux(Wire, 1); unsigned long blinkCheck = 0; bool blinkState = false; int counter1 = 0; int counter2 = 0; void setup() { Serial.begin(9600); mux.begin(); mux.setChannel(0); sevenSeg.begin(0x70); mux.setChannel(1); alphaNum.begin(0x70); // Set timezone offset from UTC. // -4 = EDT, Eastern Daylight Time in the United States // -5 = EST or CDT // ... // -8 = PST Time.zone(-4); } void loop() { if (millis() - blinkCheck >= 500) { blinkCheck = millis(); // Use 7-segment display on channel 0 mux.setChannel(0); blinkState = !blinkState; sevenSeg.drawColon(blinkState); // Time.isValid() requires system firmware 0.6.0 or later if (Time.isValid()) { int hour = Time.hour(); if (hour < 10) { sevenSeg.writeDigitRaw(0, 0); // blank } else { sevenSeg.writeDigitNum(0, hour / 10); } sevenSeg.writeDigitNum(1, hour % 10); int minute = Time.minute(); sevenSeg.writeDigitNum(3, minute / 10); sevenSeg.writeDigitNum(4, minute % 10); } sevenSeg.writeDisplay(); // Use alpha numeric display on channel 1 mux.setChannel(1); alphaNum.writeDigitAscii(0, 'A' + (counter1++ % 26)); alphaNum.writeDigitAscii(1, '0' + ((counter2 / 100) % 10)); alphaNum.writeDigitAscii(2, '0' + ((counter2 / 10) % 10)); alphaNum.writeDigitAscii(3, '0' + (counter2 % 10)); counter2++; alphaNum.writeDisplay(); } } Acidburn0zzz/audacious-plugins /* * settings.c * Copyright 2013 * * 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 * provided with the distribution. * * This software is provided "as is" and without any warranty, express or * implied. In no event shall the authors be liable for any damages arising from * the use of this software. */ #include "gtkui.h" #include #include #include "ui_playlist_notebook.h" #include "ui_playlist_widget.h" static void redisplay_playlists (void) { ui_playlist_notebook_empty (); ui_playlist_notebook_populate (); } static const PreferencesWidget gtkui_widgets[] = { WidgetLabel (N_("Playlist Tabs")), WidgetCheck (N_("Always show tabs"), {VALUE_BOOLEAN, 0, "gtkui", "playlist_tabs_visible", show_hide_playlist_tabs}), WidgetCheck (N_("Show entry counts"), {VALUE_BOOLEAN, 0, "gtkui", "entry_count_visible", redisplay_playlists}), WidgetCheck (N_("Show close buttons"), {VALUE_BOOLEAN, 0, "gtkui", "close_button_visible", redisplay_playlists}), WidgetLabel (N_("Playlist Columns")), WidgetCustom (pw_col_create_chooser), WidgetCheck (N_("Show column headers"), {VALUE_BOOLEAN, 0, "gtkui", "playlist_headers", redisplay_playlists}), WidgetLabel (N_("Miscellaneous")), WidgetSpin (N_("Arrow keys seek by:"), {VALUE_FLOAT, 0, "gtkui", "step_size", update_step_size}, {0.1, 60, 0.1, N_("seconds")}), WidgetCheck (N_("Scroll on song change"), {VALUE_BOOLEAN, 0, "gtkui", "autoscroll"}) }; const PluginPreferences gtkui_prefs = { gtkui_widgets, ARRAY_LEN (gtkui_widgets) }; #pragma once #include #include #include #include namespace yoshi { namespace internal { /// Stores a benchmark to add it later on the Google's benchmarks struct Benchmark { using Function = std::function; std::string name; Function benchmark; bool shortArgs; Benchmark(const char* n, Function f, bool s = false) : name(n) , benchmark(f) , shortArgs(s) { } }; /// Benchmark pointer type using BenchmarkPtr = std::unique_ptr; /// Holder class class Benchmarks { public: static Benchmarks* instance(); /// Adds the benchmark in the list Benchmark* add(Benchmark* b); /// Returns all the benchmarks const std::vector& get(); private: Benchmarks() = default; std::vector m_benchmarks; }; Benchmark* add(Benchmark* b); } } // Macro to register benchmarks // Check that __COUNTER__ is defined and that __COUNTER__ increases by 1 // every time it is expanded. X + 1 == X + 0 is used in case X is defined to be // empty. If X is empty the expression becomes (+1 == +0). #if defined(__COUNTER__) && (__COUNTER__ + 1 == __COUNTER__ + 0) #define YOSHI_PRIVATE_UNIQUE_ID __COUNTER__ #else #define YOSHI_PRIVATE_UNIQUE_ID __LINE__ #endif // Helpers for generating unique variable names #define YOSHI_PRIVATE_NAME(n) \ YOSHI_PRIVATE_CONCAT(_yoshi_benchmark_, YOSHI_PRIVATE_UNIQUE_ID, n) #define YOSHI_PRIVATE_CONCAT(a, b, c) YOSHI_PRIVATE_CONCAT2(a, b, c) #define YOSHI_PRIVATE_CONCAT2(a, b, c) a##b##c // Helper to add a benchmark #define YOSHI_ADD_BENCHMARK(f, ...) \ static yoshi::internal::Benchmark* \ YOSHI_PRIVATE_NAME(f) = yoshi::internal::add( \ new yoshi::internal::Benchmark( \ #f "<" #__VA_ARGS__ ">", \ [](auto& st) { f<__VA_ARGS__>(st);})); #define YOSHI_ADD_SHORT_BENCHMARK(f, ...) \ static yoshi::internal::Benchmark* \ YOSHI_PRIVATE_NAME(f) = yoshi::internal::add( \ new yoshi::internal::Benchmark( \ #f "<" #__VA_ARGS__ ">", \ [](auto& st) { f<__VA_ARGS__>(st);}, \ true)); #include void init(void); void display(void); void keyboard(unsigned char key, int x, int y); //função principal int main(int argc, char** argv){ glutInit(&argc, argv); //inicia o glut glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); //especifica o uso d cores e buffers glutInitWindowSize(256,256); //especifica as dimensões da janela glutInitWindowPosition(100,100); //especifica aonde a janela aparece na tela glutCreateWindow("Exemplo Um solido Vermelho"); //cria a janela init(); glutDisplayFunc(display); //função que será redesenhada pelo GLUT glutKeyboardFunc(keyboard); //função de teclado glutMainLoop(); //mostra todas as janelas criadas return 0; } //Definição de cada função void init(void){ glClearColor (1.0, 1.0, 1.0, 1.0); // cor de fundo glOrtho (0, 256, 0, 256, -45.0 ,45.0); // modo de projecao ortogonal } void display(void){ glClear (GL_COLOR_BUFFER_BIT); //limpa a janela glColor3f(0.0, 0.0, 0.0); //cor do ponto glPushMatrix(); glTranslated(150.0, 150.0, 0.0); glutSolidCube(40); //negro glColor3f (1.0, 0.0, 0.0); //cor vermelha glutSolidCube(40); //vermelho glFlush(); } void keyboard(unsigned char key, int x, int y){ switch(key){ case 27: exit(0); break; } } // g++ umSolidCuboVermelho.cpp -o firstOpenGlApp -lglut -lGLU -lGL // ./firstOpenGlApp// Copyright (c) 2012 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "debugd/src/ping_tool.h" #include #include #include "debugd/src/error_utils.h" #include "debugd/src/process_with_id.h" #include "debugd/src/variant_utils.h" namespace debugd { namespace { const char kSetuidHack[] = "/usr/libexec/debugd/helpers/minijail-setuid-hack.sh"; const char kPing[] = "/bin/ping"; const char kPing6[] = "/bin/ping6"; const char kPingToolErrorString[] = "org.chromium.debugd.error.Ping"; } // namespace bool PingTool::Start(const base::ScopedFD& outfd, const std::string& destination, const brillo::VariantDictionary& options, std::string* out_id, brillo::ErrorPtr* error) { ProcessWithId* p = CreateProcess(true /* sandboxed */, false /* access_root_mount_ns */); if (!p) { DEBUGD_ADD_ERROR( error, kPingToolErrorString, "Could not create ping process"); return false; } p->AddArg(kSetuidHack); if (brillo::GetVariantValueOrDefault(options, "v6")) p->AddArg(kPing6); else p->AddArg(kPing); if (options.count("broadcast") == 1) p->AddArg("-b"); if (!AddIntOption(p, options, "count", "-c", error)) return false; if (!AddIntOption(p, options, "interval", "-i", error)) return false; if (options.count("numeric") == 1) p->AddArg("-n"); if (!AddIntOption(p, options, "packetsize", "-s", error)) return false; if (!AddIntOption(p, options, "waittime", "-W", error)) return false; p->AddArg(destination); p->BindFd(outfd.get(), STDOUT_FILENO); p->BindFd(outfd.get(), STDERR_FILENO); LOG(INFO) << "ping: running process id: " << p->id(); p->Start(); *out_id = p->id(); return true; } } // namespace debugd DrawnzerGames/TPCE // This source code is licensed under the MIT license found in the LICENSE file in the root directory of this source tree. #include "Blueprint/ActorWidget.h" UActorWidget::UActorWidget(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { } void UActorWidget::OnWidgetComponentChanged(UActorWidgetComponent* OldWidgetComponent) { } void UActorWidget::SetWidgetComponent(UActorWidgetComponent* NewWidgetComponent) { if (ActorWidgetComponent != NewWidgetComponent) { auto OldWidgetComponent = ActorWidgetComponent; ActorWidgetComponent = NewWidgetComponent; OnWidgetComponentChanged(OldWidgetComponent); K2_OnWidgetComponentChanged(OldWidgetComponent); } } // Copyright #include "GHAMModelLoader.h" #include "GHXMLNode.h" #include "GHPlatform/GHDebugMessage.h" #include "GHPlatform/GHFileOpener.h" #include "GHModel.h" #include "GHGeometryRenderable.h" #include "GHGeometry.h" #include "GHVBFactory.h" #include "GHEntityHashes.h" #include "GHAMAnimFactory.h" #include "GHFrameAnimControllerVB.h" #include "GHVBAnimData.h" #include "GHTransformAnimController.h" #include "GHTransformAnimData.h" #include "GHFrameAnimSet.h" #include "GHSkinAnimController.h" #include "GHModelTransformAnimCloner.h" #include "GHModelFrameAnimVBAnimCloner.h" #include "GHModelSkinAnimCloner.h" #include "GHSkeletonAnimController.h" #include "GHModelSkeletonAnimCloner.h" #include "GHVertexBufferUtil.h" GHAMModelLoader::GHAMModelLoader(const GHXMLObjFactory& objFactory, const GHStringIdFactory& hashTable, const GHFileOpener& fileOpener, GHVBFactory& vbFactory, const GHIdentifierMap& enumStore, GHAMAnimFactory* animFactory) : GHModelLoader(objFactory, hashTable) , mFileOpener(fileOpener) , mVBFactory(vbFactory) , mEnumStore(enumStore) , mAnimFactory(animFactory) { assert(mAnimFactory); } GHAMModelLoader::~GHAMModelLoader(void) { delete mAnimFactory; } void* GHAMModelLoader::create(const GHXMLNode& node, GHPropertyContainer& extraData) const { GHModel* ret = new GHModel; loadTransformNode(*ret, node, false); void* prevModel = (void*)extraData.getProperty(GHEntityHashes::MODEL); extraData.setProperty(GHEntityHashes::MODEL, ret); const char* ghamFileName = node.getAttribute("file"); if (!ghamFileName) { GHDebugMessage::outputString("GHAM node with no file listed"); return ret; } bool combinedBounds = false; node.readAttrBool("combinedBounds", combinedBounds); GHTransformNode* modelTopNode = 0; if (ret->getSkeleton()) { const char* modelTopNodeName = node.getAttribute("ghamTopNode"); GHIdentifier modelTopNodeId = mIdFactory.generateHash(modelTopNodeName); modelTopNode = ret->getSkeleton()->findChild(modelTopNodeId); if (!modelTopNode) modelTopNode = ret->getSkeleton(); } GHFile* file = mFileOpener.openFile(ghamFileName, GHFile::FT_BINARY, GHFile::FM_READONLY); if (file) { size_t bufferSize = 0; char* bufferStart = 0; // todo? read in the file a bit at a time instead of duplicating it. if (file->readIntoBuffer() && file->getFileBuffer(bufferStart, bufferSize)) { const char* buffer = bufferStart; loadGHAM(*ret, combinedBounds, buffer, modelTopNode); } delete file; } else { GHDebugMessage::outputString("Could not load gham file %s", ghamFileName); } bool disableBounds = false; node.readAttrBool("disableBounds", disableBounds); if (disableBounds) { GHGeometryRenderable* geoRend = ret->getRenderable(); if (geoRend) { for (size_t i = 0; i < geoRend->getGeometry().size(); ++i) { geoRend->getGeometry()[i]->setBounds(0); } } } loadChildren(*ret, node); loadMatReplace(*ret, node); loadAnimSet(*ret, node); loadPhysics(*ret, node, extraData); extraData.setProperty(GHEntityHashes::MODEL, prevModel); return ret; } void GHAMModelLoader::loadGHAM(GHModel& model, bool combinedBounds, const char* buffer, GHTransformNode* modelTopNode) const { const GHAM::Header* ghamHeader = (const GHAM::Header*)buffer; buffer += sizeof(GHAM::Header); GHGeometryRenderable* renderable = new GHGeometryRenderable(); model.setRenderable(renderable); buffer = loadSkeleton(model, ghamHeader->mNumSkeletonNodes, buffer, modelTopNode); if (!modelTopNode) { modelTopNode = model.getSkeleton(); } for (int meshIdx = 0; meshIdx < ghamHeader->mNumMeshes; ++meshIdx) { buffer = loadMesh(model, combinedBounds, buffer, modelTopNode, *ghamHeader); } } const char* GHAMModelLoader::loadMesh(GHModel& model, bool combinedBounds, const char* buffer, GHTransformNode* modelTopNode, const GHAM::Header& ghamHeader) const { GHGeometryRenderable* renderable = model.getRenderable(); assert(renderable); const GHAM::MeshHeader* meshHeader = (const GHAM::MeshHeader*)buffer; buffer += sizeof(GHAM::MeshHeader); // test hack. //GHDebugMessage::outputString("", meshHeader->mName); //GHDebugMessage::outputString("numverts %d", meshHeader->mNumVerts); GHGeometry* geo = new GHGeometry; geo->setId(mIdFactory.generateHash(meshHeader->mName)); GHTransformNode* modelParent = modelTopNode->findChild(mIdFactory.generateHash(meshHeader->mSkeletonName)); if (!modelParent) modelParent = modelTopNode; geo->setTransform(modelParent); if (meshHeader->mIsSkinned) { geo->setCloneType(GHGeometry::CT_CLONEVB); } else { geo->setCloneType(GHGeometry::CT_SAMEVB); } std::vector skinIds; if (meshHeader->mIsSkinned) { buffer = loadMeshSkinDesc(skinIds, buffer); } // todo: add static/dynamic GHVBDescription vbDesc(meshHeader->mNumVerts, meshHeader->mNumIndices, GHVBBlitter::BT_INDEX); buffer = loadStreamDescriptions(*meshHeader, vbDesc, meshHeader->mNumStreams, buffer); bool needGeneratedComps = addGeneratedStreamDescription(vbDesc); GHVertexBuffer* vb = mVBFactory.createVB(vbDesc); assert(vb); geo->setVB(new GHVertexBufferPtr(vb)); buffer = loadStreamData(*vb, meshHeader->mNumStreams, buffer); buffer = loadIBData(*vb, buffer); // version 1 added an extra padding short if there are an odd number of indices. if (ghamHeader.mVersion > 0) { if (meshHeader->mNumIndices % 2 != 0) { buffer += 2; } } buffer = loadMeshAnim(*meshHeader, *geo, model, buffer); if (needGeneratedComps) { // Do we also need to generate components for the mesh anim frames? populateGeneratedVertexComponents(*vb); } GHSphereBounds* bounds = 0; buffer = loadMeshBounds(bounds, buffer); if (bounds) { if (!combinedBounds) { geo->setBounds(bounds); } else { // todo: instead of adding a bunch of bounds to the model, // combine them into a single bounds. bounds->setTransform(modelParent); model.addBounds(*bounds); delete bounds; } } renderable->addGeometry(geo); if (meshHeader->mIsSkinned) { GHSkinAnimController* skinController = mAnimFactory->createSkinAnim(skinIds); skinController->setTarget(vb, model.getSkeleton()); model.addAnimController(skinController, new GHModelSkinAnimCloner(*skinController)); } return buffer; } bool GHAMModelLoader::addGeneratedStreamDescription(GHVBDescription& vbDesc) const { // Look for SI_TANGENT. If not found then add a new stream. const std::vector& existingStreams = vbDesc.getStreamDescriptions(); for (auto streamIter = existingStreams.begin(); streamIter != existingStreams.end(); ++streamIter) { const GHVBDescription::StreamDescription& streamDesc = *streamIter; for (auto compIter = streamDesc.mComps.begin(); compIter != streamDesc.mComps.end(); ++compIter) { const GHVertexComponent& comp = *compIter; if (comp.mID == GHVertexComponentShaderID::SI_TANGENT) { // Found our missing component, don't add a new stream. // This function will need to be more complex if we want to generate more than tangents. return false; } } } // Need to add a new stream to hold tangents. GHVBDescription::StreamDescription generatedDesc; generatedDesc.mComps.push_back(GHVertexComponent(GHVertexComponentShaderID::SI_TANGENT, GHVertexComponentType::CT_FLOAT, 3) ); vbDesc.addStreamDescription(generatedDesc); return true; } void GHAMModelLoader::populateGeneratedVertexComponents(GHVertexBuffer& vb) const { // It would be better to generate these offline but we need to generate them if not found. GHVertexBufferUtil::populateTangents(vb); } const char* GHAMModelLoader::loadMeshSkinDesc(std::vector& skinIds, const char* buffer) const { int numBones = *((int*)buffer); buffer += sizeof(int); for (int i = 0; i < numBones; ++i) { GHIdentifier nodeId = mIdFactory.generateHash(buffer); skinIds.push_back(nodeId); buffer += sizeof(char)*256; } return buffer; } const char* GHAMModelLoader::loadMeshAnim(const GHAM::MeshHeader& meshHeader, GHGeometry& geo, GHModel& model, const char* buffer) const { if (!meshHeader.mNumAnimFrames) { return buffer; } // load in the anim frame format, assume all are the same and one stream. GHVBDescription animDesc(meshHeader.mNumVerts, 0, GHVBBlitter::BT_UNKNOWN); buffer = loadStreamDescriptions(meshHeader, animDesc, 1, buffer); GHFrameAnimControllerVB* animController = mAnimFactory->createMeshAnim(); GHVBAnimData* animData = animController->getAnimData(); for (int i = 0; i < meshHeader.mNumAnimFrames; ++i) { GHVertexBuffer* frameVB = mVBFactory.createVB(animDesc); buffer = loadStreamData(*frameVB, 1, buffer); animData->addFrame(new GHVertexBufferPtr(frameVB)); } animController->setTarget(&geo); model.addGeometryAnimController(animController, new GHModelFrameAnimVBAnimCloner(*animController)); return buffer; } const char* GHAMModelLoader::loadStreamDescriptions(const GHAM::MeshHeader& meshHeader, GHVBDescription& vbDesc, int numStreams, const char* buffer) const { for (int streamIdx = 0; streamIdx < numStreams; ++streamIdx) { GHVBDescription::StreamDescription streamDesc; int numComponents = *((int*)buffer); buffer += sizeof(int); for (int compIdx = 0; compIdx < numComponents; ++compIdx) { const GHAM::ComponentDef* compDef = (const GHAM::ComponentDef*)buffer; buffer += sizeof(GHAM::ComponentDef); const int* shaderId = mEnumStore.find(compDef->mShaderID); assert(shaderId); const int* compType = mEnumStore.find(compDef->mDataType); assert(compType); streamDesc.mComps.push_back(GHVertexComponent((GHVertexComponentShaderID::Enum)*shaderId, (GHVertexComponentType::Enum)*compType, compDef->mDataCount)); } mAnimFactory->modifyStreamDesc(meshHeader, streamDesc); vbDesc.addStreamDescription(streamDesc); } return buffer; } const char* GHAMModelLoader::loadStreamData(GHVertexBuffer& vb, int numStreams, const char* buffer) const { for (int streamIdx = 0; streamIdx < numStreams; ++streamIdx) { GHVertexStreamPtr* streamPtr = vb.getStream(streamIdx); float* vertData = streamPtr->get()->lockWriteBuffer(); int dataSize = streamPtr->get()->getNumVerts() * streamPtr->get()->getFormat().getVertexSize() * sizeof(float); memcpy(vertData, buffer, dataSize); buffer += dataSize; streamPtr->get()->unlockWriteBuffer(); } return buffer; } const char* GHAMModelLoader::loadIBData(GHVertexBuffer& vb, const char* buffer) const { GHVBBlitterIndex* ibBlitter = (GHVBBlitterIndex*)(vb.getBlitter()->get()); unsigned short* ibBuf = ibBlitter->lockWriteBuffer(); size_t ibSize = ibBlitter->getNumIndices()*sizeof(unsigned short); ::memcpy(ibBuf, buffer, ibSize); ibBlitter->unlockWriteBuffer(); buffer += ibSize; return buffer; } const char* GHAMModelLoader::loadSkeleton(GHModel& model, int numNodes, const char* buffer, GHTransformNode* modelTopNode) const { const GHAM::SkeletonNode* nodeArr = (const GHAM::SkeletonNode*)buffer; // first create the nodes std::vector newNodes; for (int i = 0; i < numNodes; ++i) { newNodes.push_back(new GHTransformNode); GHTransformNode* currNode = newNodes.back(); currNode->setId(mIdFactory.generateHash(nodeArr[i].mName)); currNode->getLocalTransform().getMatrix().setCoords(nodeArr[i].mTransform); currNode->getLocalTransform().incrementVersion(); } // find which node should be top if one doesn't exist if (!modelTopNode) { if (!model.getSkeleton()) { GHTransformNode* topNode = 0; for (int i = 0; i < numNodes; ++i) { if (nodeArr[i].mParentName[0] == 0 && !nodeArr[i].mNumAnimFrames) { if (topNode != 0) { // two nodes want to be top, // so flag to make a new node instead. topNode = 0; break; } else { topNode = newNodes[i]; } } } if (!topNode) { GHTransformNode* modelTop = new GHTransformNode(); modelTop->setId(mIdFactory.generateHash("ModelTop")); model.setSkeleton(modelTop); } else { model.setSkeleton(topNode); } modelTopNode = model.getSkeleton(); } else { modelTopNode = model.getSkeleton(); } } // then fix up the parenting for (int i = 0; i < numNodes; ++i) { if (nodeArr[i].mParentName[0] == 0 && newNodes[i] != modelTopNode) { modelTopNode->addChild(newNodes[i]); } else { GHIdentifier nodeId = mIdFactory.generateHash(nodeArr[i].mParentName); bool foundParent = false; for (int j = 0; j < numNodes; ++j) { if (j == i) continue; if (newNodes[j]->getId() == nodeId) { newNodes[j]->addChild(newNodes[i]); foundParent = true; break; } } if (!foundParent && newNodes[i] != modelTopNode) { GHDebugMessage::outputString("GHAM loading: failed to find parent node %s", nodeArr[i].mParentName); modelTopNode->addChild(newNodes[i]); } } } buffer += sizeof(GHAM::SkeletonNode)*numNodes; bool hasAnims = false; for (int i = 0; i < numNodes; ++i) { if (nodeArr[i].mNumAnimFrames) { hasAnims = true; break; } } GHSkeletonAnimController* skelAnim = 0; if (hasAnims) { skelAnim = mAnimFactory->createSkeletonAnim(*modelTopNode); model.addSkeletonAnimController(skelAnim, new GHModelSkeletonAnimCloner(*skelAnim)); } // and load in animations for (int i = 0; i < numNodes; ++i) { if (!nodeArr[i].mNumAnimFrames) continue; GHTransformAnimData* animData = skelAnim->getAnimForNode(newNodes[i]->getId()); std::vector& animFrames = animData->getFrames(); animFrames.resize(nodeArr[i].mNumAnimFrames); const int animSize = sizeof(float)*16; for (int animFrameIdx = 0; animFrameIdx < nodeArr[i].mNumAnimFrames; ++animFrameIdx) { memcpy(animFrames[animFrameIdx].getArr(), buffer, animSize); buffer += animSize; } // a define for autoplaying any animations on load. //#define DEBUG_AUTOPLAY_ANIMATION #ifdef DEBUG_AUTOPLAY_ANIMATION GHTransformAnimController* animController = mAnimFactory->createNodeAnim(); animController->setTarget(newNodes[i]); model.addTransformAnimController(animController, new GHModelTransformAnimCloner(*animController)); assert(animController->getAnimData()); animController->getAnimData()->getFrames() = animFrames; // add a dumb anim sequence that just loops through all frames. GHFrameAnimSet* animSet = new GHFrameAnimSet; GHFrameAnimSequence seq; seq.mFirstFrame = 0; seq.mEndFrame = nodeArr[i].mNumAnimFrames; seq.mLoopFrames = seq.mEndFrame - seq.mFirstFrame; seq.mFramesPerSecond = 1; seq.mId = mIdFactory.generateHash("default"); animSet->addSequence(seq); animController->setAnimSet(animSet); animController->setAnim(seq.mId, 0); #endif } if (hasAnims) { skelAnim->convertToModelSpace(); } if (numNodes == 0 && !model.getSkeleton()) { // make a default skeleton if none is found. GHTransformNode* transform = new GHTransformNode; transform->setId(mIdFactory.generateHash("ModelTop")); model.setSkeleton(transform); } return buffer; } const char* GHAMModelLoader::loadMeshBounds(GHSphereBounds*& ret, const char* buffer) const { GHRect boundRect((float*)buffer); // don't add an empty bounds. if (!(boundRect.mMax == boundRect.mMin)) { ret = new GHSphereBounds; GHSphere sphere; sphere.fromAABB(boundRect); ret->setSphere(sphere); } buffer += sizeof(float)*6; return buffer; } eliemichel/CodenameGogh #include #include #include #include #include #include #include "MainWindow.h" #include "MainWindowStyle.h" #include "dialogs/WelcomeDialog.h" #include "widgets/AddNodeMenu.h" using QtNodes::ConnectionStyle; static void setNodeStyle() { using namespace QtNodes; // Set style for node editor QFile nodeEditorStyleFile(":NodeEditorStyle.json"); if (nodeEditorStyleFile.open(QIODevice::ReadOnly)) { QString nodeEditorStyle = nodeEditorStyleFile.readAll(); FlowViewStyle::setStyle(nodeEditorStyle); NodeStyle::setNodeStyle(nodeEditorStyle); ConnectionStyle::setConnectionStyle(nodeEditorStyle); } Connection::SetPolicy(Connection::Policy::OverrideExistingConnections); } int main(int argc, char *argv[]) { std::cout << "This is a DEVELOPMENT version of Gogh." << std::endl << "Build number: 20201020-001" << std::endl << "Copyright (c) 2018 - 2020 -- Gogh Team. All right reserved." << std::endl << std::endl << "This version is not meant for production and is still a work in progress." << std::endl << "Please address all your remarks to the Gogh team on the bug tracker:" << std::endl << " https://github.com/eliemichel/CodenameGogh/issues" << std::endl << std::endl << "NB: ffmpeg and ffprobe commands must be installed and present in your PATH environment variable." << std::endl << " You can download it at: https://www.ffmpeg.org/download.html" << std::endl ; QApplication app(argc, argv); setNodeStyle(); app.setStyle(new MainWindowStyle()); app.setPalette(app.style()->standardPalette()); MainWindow w; // TEST //AddNodeMenu tmp; //tmp.showNormal(); //return app.exec(); // END TEST WelcomeDialog welcomeDialog; welcomeDialog.exec(); switch (welcomeDialog.selectedAction()) { case WelcomeDialog::OpenGraph: w.openFile(); break; case WelcomeDialog::NewGraph: break; default: case WelcomeDialog::Cancel: return EXIT_SUCCESS; } w.showNormal(); w.raise(); return app.exec(); } #include "pearlpch.h" #include "AssetStack.h" #include "Pearl/Core/Core.h" namespace Pearl { AssetStack::AssetStack() { } AssetStack::~AssetStack() { // Dispose of textures for (auto texture : m_TextureCache) { if (texture.second != NULL) { texture.second->Dispose(); } } // Dispose of sounds for (auto sound : m_SoundCache) { if (sound.second != NULL) { sound.second->Dispose(); } } // Dispose of fonts for (auto font : m_FontCache) { if (font.second != NULL) { font.second->free(); } } } void AssetStack::LoadTexture(std::string filePath) { // Create new texture asset Texture* texture = new Texture(); // Final texture hardware SDL_Texture* newTexture = NULL; // Surface loaded at file path SDL_Surface* loadedSurface = IMG_Load(filePath.c_str()); if (loadedSurface == NULL) { PL_LOG_ERROR("Unable to load image at path: \"{}\"! SDL_image Error: {}", filePath.c_str(), IMG_GetError()); } else { // Create texture from loaded surface's pixels newTexture = SDL_CreateTextureFromSurface(PL_RENDERER, loadedSurface); // Set texture blending SDL_SetTextureBlendMode(newTexture, SDL_BLENDMODE_BLEND); if (newTexture == NULL) { PL_LOG_ERROR("Unable to create texture from: \"{}\"! SDL Error: {}", filePath.c_str(), SDL_GetError()); } else { texture->image = newTexture; texture->width = loadedSurface->w; texture->height = loadedSurface->h; } } // Place new texture into cache m_TextureCache.insert(std::make_pair(filePath, texture)); } void AssetStack::LoadSound(SoundType type, std::string filePath) { // Create new sound asset Sound* sound = new Sound(); sound->filePath = filePath; sound->type = type; // Load sound if (type == SoundType::Sample) { sound->sample = Mix_LoadWAV(filePath.c_str()); if (sound->sample == NULL) { PL_LOG_ERROR("Failed to load sample: \"{}\"! SDL_mixer Error: {}", filePath.c_str(), Mix_GetError()); } else { sound->SetVolume(MIX_MAX_VOLUME / 2); m_SoundCache.insert(std::make_pair(filePath, sound)); } } else if (type == SoundType::Music) { sound->music = Mix_LoadMUS(filePath.c_str()); if (sound->music == NULL) { PL_LOG_ERROR("Failed to load music: \"{}\"! SDL_mixer Error: {}", filePath.c_str(), Mix_GetError()); } else { sound->SetVolume(MIX_MAX_VOLUME / 2); m_SoundCache.insert(std::make_pair(filePath, sound)); } } } /** * Loads an NFont object into the cache. * @param filePath Path to the font file * @param id The tag which will be referenced to retrieve fonts from the cache * @param pointSize Font point size * @param color An NFont::Color object for the font color * @param style The font style */ void AssetStack::LoadFont(std::string filePath, std::string id, Uint32 pointSize, const NFont::Color& color, int style) { // Check if id is already in the cache if (m_FontCache.count(id) > 0) { PL_LOG_ERROR("Could not load font file \"{}\" with id \"{}\" because that id already exists in the cache!", filePath.c_str(), id.c_str()); } else { // NFont object asset NFont* font = new NFont(); // Load the asset if (!font->load(PL_RENDERER, filePath.c_str(), pointSize, color, style)) { PL_LOG_ERROR("Unable to load font file \"{}\"!", filePath.c_str()); } else { // Insert asset m_FontCache.insert(std::make_pair(id, font)); } } } }//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // allocator: // pointer address(reference x) const; // const_pointer address(const_reference x) const; #include #include template void test_address() { T* tp = new T(); const T* ctp = tp; const std::allocator a; assert(a.address(*tp) == tp); assert(a.address(*ctp) == tp); delete tp; } struct A { void operator&() const {} }; int main() { test_address(); test_address(); } data-structures/cpp/isUnique.cpp0 /* Data Structure: Arrays and Strings * * Implement an algorithm to determine if a string has all unique chracters * Additionally: Implement this without using additional data structures or memory space. * -- basic use for arrays and strings * -- brute force : O(n^2) complexity and O(1) space complexity * * Notes: * consider ASCII for this problem. * UNICODE will increase the size of storage from char (1 byte) to int (4 bytes) * * If we can't use additional data structure then compare every char of the * string with every other char, and the time complexity is O(n^s) and O(1) space. * * * If we are allowed to modify the input string then we could sort the string * in O(n log n) time and then check linearly for neighboring chars are identical. * * The time complexity for this code is O(n) (one which stores a bitmask), where * n is the length of the string. The space complexity is O(1). * * The time complexity can also be thought of O(1) , since the for loop will * never iterate through more than 128 characters. * * Time complexity : O( Min(C, N) ) * Space complexity : O(C) * where C is the size of the character set and N is the length of string * */ #include #include using namespace std; // O(n2) worst case, but without using any additional memory bool isUniqueChars (string str) { if (str.size() > 128) return false; // looping and figure out for (int i = 0; i < str.size(); i++) { for (int j = i+1; j < str.size(); j++) { if (str[i] == str[j]) { //cout << str << ":does not have unique chars" << endl; return false; } } } //cout << str << ":does have unique chars" << endl; return true; } // use a bitmask to store the characters /* Bitmask will not be an optimized solution for a UNICODE use case, where there * are 2^32 possibilities and the bitmask (space requirements) will be a * constraint. Using a hash or dictionary to store known chars will be optimized. */ bool isUniqueChars_Ver2 (string str) { if (str.size() > 128) return false; //assumign ascii chars only char *charset = new char[128/8]; //one bit to store a char value for (int i = 0; i < str.size(); i++) { char c = str[i]; if (charset[c/8] & (0x1 << (c%8))) { //cout << "non unique char " << c << endl; delete [] charset; return false; } else { charset[c/8] |= (0x1 << (c%8)); } } delete [] charset; return true; } int main (int argc, char **argv) { //cout << "Program: isUnique" << endl << endl; if (argc != 2) { cout << "Error: Incorrect number of arguments." << endl; return -1; } std::string str(argv[1]); //if (isUniqueChars(str) == true) { if (isUniqueChars_Ver2(str) == true) { cout << str << ": has all unique chars" << endl; return 0; } else { cout << str << ": does not have all unique chars" << endl; return -1; } } dyna-mis/Hilabeling /* * This file is a part of QTerminal - http://gitorious.org/qterminal * * This file was un-linked from KDE and modified * by <> * */ /* This file is part of Konsole, an X terminal. Copyright 1997,1998 by <> 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. */ // Own #include "Pty.h" // System #include #include #include #include #include #include // Qt #include #include #include "kpty.h" #include "kptydevice.h" using namespace Konsole; void Pty::setWindowSize(int lines, int cols) { _windowColumns = cols; _windowLines = lines; if (pty()->masterFd() >= 0) pty()->setWinSize(lines, cols); } QSize Pty::windowSize() const { return QSize(_windowColumns,_windowLines); } void Pty::setFlowControlEnabled(bool enable) { _xonXoff = enable; if (pty()->masterFd() >= 0) { struct ::termios ttmode; pty()->tcGetAttr(&ttmode); if (!enable) ttmode.c_iflag &= ~(IXOFF | IXON); else ttmode.c_iflag |= (IXOFF | IXON); if (!pty()->tcSetAttr(&ttmode)) qWarning() << "Unable to set terminal attributes."; } } bool Pty::flowControlEnabled() const { if (pty()->masterFd() >= 0) { struct ::termios ttmode; pty()->tcGetAttr(&ttmode); return ttmode.c_iflag & IXOFF && ttmode.c_iflag & IXON; } qWarning() << "Unable to get flow control status, terminal not connected."; return false; } void Pty::setUtf8Mode(bool enable) { #ifdef IUTF8 // XXX not a reasonable place to check it. _utf8 = enable; if (pty()->masterFd() >= 0) { struct ::termios ttmode; pty()->tcGetAttr(&ttmode); if (!enable) ttmode.c_iflag &= ~IUTF8; else ttmode.c_iflag |= IUTF8; if (!pty()->tcSetAttr(&ttmode)) qWarning() << "Unable to set terminal attributes."; } #endif } void Pty::setErase(char erase) { _eraseChar = erase; if (pty()->masterFd() >= 0) { struct ::termios ttmode; pty()->tcGetAttr(&ttmode); ttmode.c_cc[VERASE] = erase; if (!pty()->tcSetAttr(&ttmode)) qWarning() << "Unable to set terminal attributes."; } } char Pty::erase() const { if (pty()->masterFd() >= 0) { struct ::termios ttyAttributes; pty()->tcGetAttr(&ttyAttributes); return ttyAttributes.c_cc[VERASE]; } return _eraseChar; } void Pty::addEnvironmentVariables(const QStringList& environment) { QListIterator iter(environment); while (iter.hasNext()) { QString pair = iter.next(); // split on the first '=' character int pos = pair.indexOf('='); if ( pos >= 0 ) { QString variable = pair.left(pos); QString value = pair.mid(pos+1); setEnv(variable,value); } } } int Pty::start(const QString& program, const QStringList& programArguments, const QStringList& environment, ulong winid, bool addToUtmp //const QString& dbusService, //const QString& dbusSession ) { clearProgram(); // For historical reasons, the first argument in programArguments is the // name of the program to execute, so create a list consisting of all // but the first argument to pass to setProgram() Q_ASSERT(programArguments.count() >= 1); setProgram(program.toLatin1(),programArguments.mid(1)); addEnvironmentVariables(environment); setEnv(QStringLiteral("WINDOWID"), QString::number(winid)); // unless the LANGUAGE environment variable has been set explicitly // set it to a null string // this fixes the problem where KCatalog sets the LANGUAGE environment // variable during the application's startup to something which // differs from LANG,LC_* etc. and causes programs run from // the terminal to display messages in the wrong language // // this can happen if LANG contains a language which KDE // does not have a translation for // // BR:149300 setEnv(QStringLiteral("LANGUAGE"),QString(),false /* do not overwrite existing value if any */); setUseUtmp(addToUtmp); struct ::termios ttmode; pty()->tcGetAttr(&ttmode); if (!_xonXoff) ttmode.c_iflag &= ~(IXOFF | IXON); else ttmode.c_iflag |= (IXOFF | IXON); #ifdef IUTF8 // XXX not a reasonable place to check it. if (!_utf8) ttmode.c_iflag &= ~IUTF8; else ttmode.c_iflag |= IUTF8; #endif if (_eraseChar != 0) ttmode.c_cc[VERASE] = _eraseChar; if (!pty()->tcSetAttr(&ttmode)) qWarning() << "Unable to set terminal attributes."; pty()->setWinSize(_windowLines, _windowColumns); KProcess::start(); if (!waitForStarted()) return -1; return 0; } void Pty::setEmptyPTYProperties() { struct ::termios ttmode; pty()->tcGetAttr(&ttmode); if (!_xonXoff) ttmode.c_iflag &= ~(IXOFF | IXON); else ttmode.c_iflag |= (IXOFF | IXON); #ifdef IUTF8 // XXX not a reasonable place to check it. if (!_utf8) ttmode.c_iflag &= ~IUTF8; else ttmode.c_iflag |= IUTF8; #endif if (_eraseChar != 0) ttmode.c_cc[VERASE] = _eraseChar; if (!pty()->tcSetAttr(&ttmode)) qWarning() << "Unable to set terminal attributes."; } void Pty::setWriteable(bool writeable) { struct stat sbuf; stat(pty()->ttyName(), &sbuf); if (writeable) chmod(pty()->ttyName(), sbuf.st_mode | S_IWGRP); else chmod(pty()->ttyName(), sbuf.st_mode & ~(S_IWGRP|S_IWOTH)); } Pty::Pty(int masterFd, QObject* parent) : KPtyProcess(masterFd,parent) { init(); } Pty::Pty(QObject* parent) : KPtyProcess(parent) { init(); } void Pty::init() { _windowColumns = 0; _windowLines = 0; _eraseChar = 0; _xonXoff = true; _utf8 =true; connect(pty(), &QIODevice::readyRead , this , &Pty::dataReceived); setPtyChannels(KPtyProcess::AllChannels); } Pty::~Pty() { } void Pty::sendData(const char* data, int length) { if (!length) return; if (!pty()->write(data,length)) { qWarning() << "Pty::doSendJobs - Could not send input data to terminal process."; return; } } void Pty::dataReceived() { QByteArray data = pty()->readAll(); emit receivedData(data.constData(),data.count()); } void Pty::lockPty(bool lock) { Q_UNUSED(lock); // TODO: Support for locking the Pty //if (lock) //suspend(); //else //resume(); } int Pty::foregroundProcessGroup() const { int pid = tcgetpgrp(pty()->masterFd()); if ( pid != -1 ) { return pid; } return 0; } void Pty::setupChildProcess() { KPtyProcess::setupChildProcess(); // reset all signal handlers // this ensures that terminal applications respond to // signals generated via key sequences such as Ctrl+C // (which sends SIGINT) struct sigaction action; sigset_t sigset; sigemptyset(&action.sa_mask); action.sa_handler = SIG_DFL; action.sa_flags = 0; for (int signal=1;signal < NSIG; signal++) { sigaction(signal,&action,0L); sigaddset(&sigset, signal); } sigprocmask(SIG_UNBLOCK, &sigset, NULL); } #include "Gwen/Gwen.h" #include "Gwen/BaseRender.h" #include "Gwen/Utility.h" #include "Gwen/Font.h" #include "Gwen/Texture.h" #include "Gwen/Renderers/SFML.h" #include #include namespace Gwen { namespace Renderer { struct TextureData { TextureData(sf::Image* img): image(img), texture(NULL) { } TextureData(sf::Texture* text): texture(text), image(NULL) { } ~TextureData() { if (texture != NULL) delete texture; if (image != NULL) delete image; } sf::Texture* texture; sf::Image* image; }; SFML::SFML( sf::RenderTarget& target ) : m_Target(target), m_pixelShape( sf::Vector2f( 1, 1 ) ) { } SFML::~SFML() { } void SFML::SetDrawColor( Gwen::Color color ) { m_Color.r = color.r; m_Color.g = color.g; m_Color.b = color.b; m_Color.a = color.a; } void SFML::DrawFilledRect( Gwen::Rect rect ) { Translate( rect ); #if SFML_VERSION_MAJOR == 2 sf::RectangleShape rectShape( sf::Vector2f( rect.w, rect.h ) ); rectShape.setPosition( rect.x, rect.y ); rectShape.setFillColor( m_Color ); m_Target.draw( rectShape ); #else m_Target.Draw( sf::Shape::Rectangle( rect.x, rect.y, rect.x + rect.w, rect.y + rect.h, m_Color ) ); #endif } void SFML::DrawLinedRect( Gwen::Rect rect ) { #if SFML_VERSION_MAJOR == 2 Translate( rect ); sf::RectangleShape rectShape( sf::Vector2f( rect.w-2, rect.h-2 ) ); rectShape.setPosition( rect.x+1, rect.y+1 ); rectShape.setFillColor( sf::Color::Transparent ); rectShape.setOutlineColor( m_Color ); rectShape.setOutlineThickness( 1.f ); m_Target.draw( rectShape ); #else Base::DrawLinedRect( rect ); #endif } void SFML::DrawPixel( int x, int y ) { #if SFML_VERSION_MAJOR == 2 Translate( x, y ); sf::Vertex vert( sf::Vector2f( x, y ), m_Color ); m_Target.draw( &vert, 1, sf::PrimitiveType::Points ); #else Base::DrawPixel( x, y ); #endif } void SFML::LoadFont( Gwen::Font* font ) { font->realsize = font->size * Scale(); sf::Font* pFont = new sf::Font(); #if SFML_VERSION_MAJOR == 2 if ( !pFont->loadFromFile( Utility::UnicodeToString( font->facename ) ) ) #else if ( !pFont->LoadFromFile( Utility::UnicodeToString( font->facename ), font->realsize ) ) #endif { // Ideally here we should be setting the font to a system default font here. delete pFont; #if SFML_VERSION_MAJOR == 2 pFont = NULL; // SFML 2 doesn't have a default font anymore #else static sf::Font defaultFont = sf::Font::GetDefaultFont(); pFont = &defaultFont; #endif } font->data = pFont; } void SFML::FreeFont( Gwen::Font* pFont ) { if ( !pFont->data ) return; sf::Font* font = ((sf::Font*)pFont->data); #if SFML_VERSION_MAJOR != 2 // If this is the default font then don't delete it! if ( font != &sf::Font::GetDefaultFont() ) { delete font; } #endif pFont->data = NULL; } void SFML::RenderText( Gwen::Font* pFont, Gwen::Point pos, const Gwen::UnicodeString& text ) { Translate( pos.x, pos.y ); // If the font doesn't exist, or the font size should be changed if ( !pFont->data || fabs( pFont->realsize - pFont->size * Scale() ) > 2 ) { FreeFont( pFont ); LoadFont( pFont ); } const sf::Font* pSFFont = (sf::Font*)(pFont->data); #if SFML_VERSION_MAJOR != 2 if ( !pSFFont ) { static sf::Font defaultFont = sf::Font::GetDefaultFont(); pSFFont = &defaultFont; } #endif #if SFML_VERSION_MAJOR == 2 sf::Text sfStr; sfStr.setString( text ); sfStr.setFont( *pSFFont ); sfStr.move( pos.x, pos.y ); sfStr.setCharacterSize( pFont->realsize ); sfStr.setColor( m_Color ); m_Target.draw( sfStr ); #else sf::String sfStr( text ); sfStr.SetFont( *pSFFont ); sfStr.Move( pos.x, pos.y ); sfStr.SetSize( pFont->realsize ); sfStr.SetColor( m_Color ); m_Target.Draw( sfStr ); #endif } Gwen::Point SFML::MeasureText( Gwen::Font* pFont, const Gwen::UnicodeString& text ) { // If the font doesn't exist, or the font size should be changed if ( !pFont->data || fabs( pFont->realsize - pFont->size * Scale() ) > 2 ) { FreeFont( pFont ); LoadFont( pFont ); } const sf::Font* pSFFont = (sf::Font*)(pFont->data); #if SFML_VERSION_MAJOR != 2 if ( !pSFFont ) { static sf::Font defaultFont = sf::Font::GetDefaultFont(); pSFFont = &defaultFont; } #endif #if SFML_VERSION_MAJOR == 2 sf::Text sfStr; sfStr.setString( text ); sfStr.setFont( *pSFFont ); sfStr.setCharacterSize( pFont->realsize ); sf::FloatRect sz = sfStr.getLocalBounds(); return Gwen::Point( sz.left + sz.width, sz.top + sz.height ); #else sf::String sfStr( text ); sfStr.SetFont( *pSFFont ); sfStr.SetSize( pFont->realsize ); sf::FloatRect sz = sfStr.GetRect(); return Gwen::Point( sz.GetWidth(), sz.GetHeight() ); #endif } void SFML::StartClip() { Gwen::Rect rect = ClipRegion(); // OpenGL's coords are from the bottom left // so we need to translate them here. { GLint view[4]; glGetIntegerv( GL_VIEWPORT, &view[0] ); rect.y = view[3] - (rect.y + rect.h); } glScissor( rect.x * Scale(), rect.y * Scale(), rect.w * Scale(), rect.h * Scale() ); glEnable( GL_SCISSOR_TEST ); }; void SFML::EndClip() { glDisable( GL_SCISSOR_TEST ); }; void SFML::LoadTexture( Gwen::Texture* pTexture ) { if ( !pTexture ) return; if ( pTexture->data ) FreeTexture( pTexture ); #if SFML_VERSION_MAJOR == 2 sf::Texture* tex = new sf::Texture(); tex->setSmooth( true ); if ( !tex->loadFromFile( pTexture->name.Get() ) ) #else sf::Image* tex = new sf::Image(); tex->SetSmooth( true ); if ( !tex->LoadFromFile( pTexture->name.Get() ) ) #endif { delete( tex ); pTexture->failed = true; return; } #if SFML_VERSION_MAJOR == 2 pTexture->height = tex->getSize().x; pTexture->width = tex->getSize().y; #else pTexture->height = tex->GetHeight(); pTexture->width = tex->GetWidth(); #endif pTexture->data = new TextureData(tex); }; void SFML::FreeTexture( Gwen::Texture* pTexture ) { TextureData* data = static_cast( pTexture->data ); if ( data ) { delete data; } pTexture->data = NULL; } void SFML::DrawTexturedRect( Gwen::Texture* pTexture, Gwen::Rect rect, float u1, float v1, float u2, float v2 ) { TextureData* data = static_cast( pTexture->data ); if ( !data ) return DrawMissingImage( rect ); #if SFML_VERSION_MAJOR == 2 const sf::Texture* tex = data->texture; #else const sf::Image* tex = data->image; #endif if ( !tex ) return DrawMissingImage( rect ); Translate( rect ); #if SFML_VERSION_MAJOR == 2 sf::Vector2u texSize = tex->getSize(); u1 *= texSize.x; v1 *= texSize.y; u2 *= texSize.x; u2 -= u1; v2 *= texSize.y; v2 -= v1; sf::RectangleShape rectShape( sf::Vector2f( rect.w, rect.h ) ); rectShape.setPosition( rect.x, rect.y ); rectShape.setTexture( tex ); rectShape.setTextureRect( sf::IntRect( u1, v1, u2, v2 ) ); m_Target.draw( rectShape ); #else tex->Bind(); glColor4f(1, 1, 1, 1 ); glBegin( GL_QUADS ); glTexCoord2f( u1, v1 ); glVertex2f(rect.x, rect.y); glTexCoord2f( u1, v2 ); glVertex2f(rect.x, rect.y + rect.h); glTexCoord2f( u2, v2 ); glVertex2f(rect.x + rect.w, rect.y + rect.h); glTexCoord2f( u2, v1 ); glVertex2f(rect.x + rect.w, rect.y) ; glEnd(); glBindTexture( GL_TEXTURE_2D, 0); #endif } Gwen::Color SFML::PixelColour( Gwen::Texture* pTexture, unsigned int x, unsigned int y, const Gwen::Color& col_default ) { TextureData* data = static_cast( pTexture->data ); #if SFML_VERSION_MAJOR == 2 if ( !data->texture && !data->image ) return col_default; if ( !data->image ) { sf::Image copy = data->texture->copyToImage(); data->image = new sf::Image(copy); } sf::Color col = data->image->getPixel( x, y ); return Gwen::Color( col.r, col.g, col.b, col.a ); #else const sf::Image* tex = data->image; if ( !tex ) return col_default; sf::Color col = tex->GetPixel( x, y ); return Gwen::Color( col.r, col.g, col.b, col.a ); #endif } } } // // GameManager.cpp // CutTheRopeDemo // // Created by guanghui on 5/11/13. // // #include "GameManager.h" GameManager* GameManager::_pGameManager = NULL; GameManager* GameManager::getInstance() { if (_pGameManager == NULL) { _pGameManager = new GameManager; } return _pGameManager; }0 #include #include #include using namespace std; int main() { string sentence; cout << "Podaj ciag znakow: "; getline(cin, sentence); if (sentence.length()%2 == 0) cout << "Nie ma srodkowego znaku."; else cout << "Srodkowy znak: " << sentence[ceil(sentence.length()/2)]; } // Distributed under the MIT License. // See LICENSE.txt for details. #pragma once #include "DataStructures/DataBox/DataBox.hpp" #include "DataStructures/Variables.hpp" #include "DataStructures/VariablesTag.hpp" #include "Domain/ElementLogicalCoordinates.hpp" #include "Domain/FunctionsOfTime/FunctionOfTime.hpp" #include "Domain/Tags.hpp" #include "Domain/TagsTimeDependent.hpp" #include "NumericalAlgorithms/Interpolation/IrregularInterpolant.hpp" #include "Parallel/GlobalCache.hpp" #include "Parallel/Invoke.hpp" #include "ParallelAlgorithms/Interpolation/InterpolationTargetDetail.hpp" #include "ParallelAlgorithms/Interpolation/Tags.hpp" #include "Utilities/Gsl.hpp" #include "Utilities/TMPL.hpp" #include "Utilities/TaggedTuple.hpp" #include "Utilities/TypeTraits/CreateHasTypeAlias.hpp" /// \cond namespace intrp { template struct InterpolationTarget; namespace Actions { template struct InterpolationTargetReceiveVars; } // namespace Actions } // namespace intrp /// \endcond namespace intrp { namespace interpolator_detail { namespace detail { CREATE_HAS_TYPE_ALIAS(compute_vars_to_interpolate) CREATE_HAS_TYPE_ALIAS_V(compute_vars_to_interpolate) template using any_index_in_frame_impl = TensorMetafunctions::any_index_in_frame; } // namespace detail // Returns true if any of the tensors in TagList have any of their // indices in the given frame. template constexpr bool any_index_in_frame_v = tmpl::any>::value; // Interpolates data onto a set of points desired by an InterpolationTarget. template void interpolate_data(const gsl::not_null*> box, Parallel::GlobalCache& cache, const typename InterpolationTargetTag::temporal_id::type& temporal_id) noexcept { db::mutate_apply< tmpl::list< ::intrp::Tags::InterpolatedVarsHolders, ::intrp::Tags::VolumeVarsInfo< Metavariables, typename InterpolationTargetTag::temporal_id>>, tmpl::list>>( [&cache, &temporal_id]( const gsl::not_null::type*> holders, const gsl::not_null::type*> volume_vars_info, const Domain& domain) noexcept { auto& interp_info = get>( *holders) .infos.at(temporal_id); // Avoid compiler warning for unused variable in some 'if // constexpr' branches. (void)cache; for (auto& volume_info_outer : *volume_vars_info) { // Are we at the right time? if (volume_info_outer.first != temporal_id) { continue; } // Get list of ElementIds that have the correct temporal_id and that // have not yet been interpolated. std::vector> element_ids; for (const auto& volume_info_inner : volume_info_outer.second) { // Have we interpolated this element before? if (interp_info.interpolation_is_done_for_these_elements.find( volume_info_inner.first) == interp_info.interpolation_is_done_for_these_elements.end()) { interp_info.interpolation_is_done_for_these_elements.emplace( volume_info_inner.first); element_ids.push_back(volume_info_inner.first); } } // Get element logical coordinates. const auto element_coord_holders = element_logical_coordinates( element_ids, interp_info.block_coord_holders); // Construct local vars and interpolate. for (const auto& element_coord_pair : element_coord_holders) { const auto& element_id = element_coord_pair.first; auto& volume_info = volume_info_outer.second.at(element_id); auto& vars_to_interpolate = get<::intrp::Tags::VarsToInterpolateToTarget< InterpolationTargetTag>>(volume_info.vars_to_interpolate); if constexpr (detail::has_compute_vars_to_interpolate_v< InterpolationTargetTag>) { if (vars_to_interpolate.size() == 0) { // vars_to_interpolate has not been filled for // this element at this temporal_id. So fill it. How we // fill it will depend on whether we need to change frames. vars_to_interpolate.initialize( volume_info.vars_from_element.number_of_grid_points()); if constexpr (any_index_in_frame_v and any_index_in_frame_v< typename InterpolationTargetTag:: vars_to_interpolate_to_target, Frame::Grid>) { // Need to do frame transformations. // The functions of time are always guaranteed to be // up-to-date here, because they are guaranteed to be // up-to-date before calling SendPointsToInterpolator // (which is guaranteed to be called before // interpolate_data is called). const auto& functions_of_time = get(cache); const auto& block = domain.blocks().at(element_id.block_id()); ElementMap<3, ::Frame::Grid> map_logical_to_grid{ element_id, block.moving_mesh_logical_to_grid_map().get_clone()}; const auto invjac_logical_to_grid = map_logical_to_grid.inv_jacobian( logical_coordinates(volume_info.mesh)); const auto jac_grid_to_inertial = block.moving_mesh_grid_to_inertial_map().jacobian( map_logical_to_grid( logical_coordinates(volume_info.mesh)), InterpolationTarget_detail:: evaluate_temporal_id_for_expiration(temporal_id), functions_of_time); InterpolationTargetTag::compute_vars_to_interpolate::apply( make_not_null(&vars_to_interpolate), volume_info.vars_from_element, volume_info.mesh, jac_grid_to_inertial, invjac_logical_to_grid); } else { InterpolationTargetTag::compute_vars_to_interpolate::apply( make_not_null(&vars_to_interpolate), volume_info.vars_from_element, volume_info.mesh); } } } // Now interpolate. const auto& element_coord_holder = element_coord_pair.second; intrp::Irregular interpolator( volume_info.mesh, element_coord_holder.element_logical_coords); if constexpr (detail::has_compute_vars_to_interpolate_v< InterpolationTargetTag>) { interp_info.vars.emplace_back( interpolator.interpolate(vars_to_interpolate)); } else { // If compute_vars_to_interpolate does not exist, then // volume_info.vars_from_element is the same as // volume_info.vars_to_interpolate. interp_info.vars.emplace_back( interpolator.interpolate(volume_info.vars_from_element)); } interp_info.global_offsets.emplace_back( element_coord_holder.offsets); } } }, box); } } // namespace interpolator_detail /// Check if we have enough information to interpolate. If so, do the /// interpolation and send data to the InterpolationTarget. template void try_to_interpolate( const gsl::not_null*> box, const gsl::not_null*> cache, const typename InterpolationTargetTag::temporal_id::type& temporal_id) noexcept { const auto& holders = db::get>(*box); const auto& vars_infos = get>(holders) .infos; // If we don't yet have any points for this InterpolationTarget at // this temporal_id, we should exit (we can't interpolate anyway). if (vars_infos.count(temporal_id) == 0) { return; } interpolator_detail::interpolate_data( box, *cache, temporal_id); // Send interpolated data only if interpolation has been done on all // of the local elements. const auto& num_elements = db::get(*box); if (vars_infos.at(temporal_id) .interpolation_is_done_for_these_elements.size() == num_elements) { // Send data to InterpolationTarget, but only if the list of points is // non-empty. if (not vars_infos.at(temporal_id).global_offsets.empty()) { const auto& info = vars_infos.at(temporal_id); auto& receiver_proxy = Parallel::get_parallel_component< InterpolationTarget>(*cache); Parallel::simple_action< Actions::InterpolationTargetReceiveVars>( receiver_proxy, info.vars, info.global_offsets, temporal_id); } // Clear interpolated data, since we don't need it anymore. db::mutate>( box, [&temporal_id]( const gsl::not_null< typename Tags::InterpolatedVarsHolders::type*> holders_l) noexcept { get>( *holders_l) .infos.erase(temporal_id); }); } } } // namespace intrp Game/Game/SweptAABB.cpp #include "SweptAABB.h" SweptAABB* SweptAABB::instance=0; SweptAABB* SweptAABB::getInstance() { if(instance==0) instance = new SweptAABB(); return instance; } RectF SweptAABB::getSweptBroadphase(GObject* M) { float x, y, w, h; x = M->dx > 0 ? M->x : M->x + M->dx; y = M->dy < 0 ? M->y : M->y + M->dy; w = abs(M->dx) + M->width; h = abs( M->dy) + M->height; RectF broadphasebox; broadphasebox.init(x, y, w, h); return broadphasebox; } bool SweptAABB::AABBCheck(RectF * M, RectF * S) { return (M->bottom() < S->top() && M->top() > S->bottom() && M->left() < S->right() && M->right() > S->left()); } float SweptAABB::sweptAABB(GObject * M, GObject * S, int & normalx, int & normaly) { normalx = 0.0f; normaly = 0.0f; float xInvEntry, yInvEntry; float xInvExit, yInvExit; if (M->dx > 0.0f) { xInvEntry = S->x - (M->x + M->width); xInvExit = (S->x + S->width) - M->x; } else { xInvEntry = (S->x + S->width) - M->x; xInvExit = S->x - (M->x + M->width); } if (M->dy > 0.0f) { yInvEntry = S->y - (M->y + M->height); yInvExit = (S->y + S->height) - M->y; } else { yInvEntry = (S->y + S->height) - M->y; yInvExit = S->y - (M->y + M->height); } float xEntry, yEntry; float xExit, yExit; if (M->dx == 0.0f) { xEntry = -std::numeric_limits::infinity(); xExit = std::numeric_limits::infinity(); } else { xEntry = xInvEntry / M->dx; xExit = xInvExit / M->dx; } if (M->dy == 0.0f) { yEntry = -std::numeric_limits::infinity(); yExit = std::numeric_limits::infinity(); } else { yEntry = yInvEntry / M->dy; yExit = yInvExit / M->dy; } float entryTime = MAX(xEntry, yEntry); float exitTime = MIN(xExit, yExit); //if (entryTime > exitTime || xEntry < 0.0f && yEntry < 0.0f || xEntry > 1.0f || yEntry > 1.0f) if (entryTime > exitTime || xEntry > 1.0f || yEntry > 1.0f) { normalx = 0.0f; normaly = 0.0f; return 1.0f; } else { normalx = 0; normaly = 0; if (M->left() < S->right() && M->right() > S->left()) { if (M->dy>0) normaly = -1; else normaly = 1; normalx = 0; return entryTime; } if (M->top() < S->bottom() && M->bottom() > S->top()) { if (M->dx>0) normalx = -1; else normalx = 1; normaly = 0; } return entryTime; } } void SweptAABB::checkCollision(GObject * M, GObject * S) { if (!M->alive || !S->alive) return; //tru de su dung thuat toan AABB //M->y = -M->y; //M->dy = -M->dy; //tinh broadphasebox RectF movBroadPhase = getSweptBroadphase(M); //kiem tra broadphase box co giao nhau voi S hay khong if (AABBCheck(&movBroadPhase, S)) { if (AABBCheck(S, M)) { //khoi phuc lai toa do ban dau M->onInterserct(S); S->onInterserct(M); return; } M->y = -M->y; S->y = -S->y; M->dy = -M->dy; //neu co thi co the xay ra va cham int nx, ny; //tinh sweptTime float sweptTime = sweptAABB(M, S, nx, ny); if (sweptTime < 1.0) { //chac chan co va cham //khoi phuc lai toa do ban dau M->y = -M->y; S->y = -S->y; M->dy = -M->dy; M->onCollision(S, nx, ny); S->onCollision(M, nx, ny); return; } M->y = -M->y; S->y = -S->y; M->dy = -M->dy; } } void SweptAABB::preventMove(GObject * M, GObject * S) { if (M->top() > S->bottom() && M->bottom() < S->top() && M->dx != 0) { if (M->dx > 0) M->dx = S->left() - M->right(); else M->dx = S->right() - M->left(); M->biDoiVanToc = true; return; } if (M->left() < S->right() && M->right() > S->left() && M->dy != 0) { if (M->dy > 0) M->dy = S->bottom() - M->top(); else M->dy = S->top() - M->bottom(); M->biDoiVanToc = true; return; } M->coVaChamCheo = true; } // 2021/04/06 22:47:26 (c) e-mail : #include "stdafx.h" #include "Client.h" #include "Network/MapLivingRooms.h" #include "Network/Other/ConnectorTCP_v.h" #include "Network/Other/ConnectorUDP_v.h" #include "Utils/GlobalFunctions_.h" void Client::HandlerUpdate(StringHash, VariantMap &) { MapLivingRooms::Update(); } void Client::HandlerPostRenderUpdate(StringHash, VariantMap &) { } #include #include #include #include int main() { std::vector processors; processors.push_back(std::atoi); processors.push_back(reinterpret_cast(std::strlen)); const char data[] = "1.23"; for (std::vector::iterator it = processors.begin(); it != processors.end(); ++it) std::cout << (*it)(data) << std::endl; } 0 // Copyright (C) 2018-2020 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include #include #include #include #include #include namespace vpu { VPU_PACKED(Elf32Shdr { uint32_t shName; uint32_t pad0[3]; uint32_t shOffset; uint32_t shSize; uint32_t pad1[4]; };) VPU_PACKED(Elf32Ehdr { uint32_t pad0[7]; uint32_t ePhoff; uint32_t eShoff; uint32_t pad1[3]; uint16_t eShnum; uint16_t eShstrndx; };) VPU_PACKED(Elf32Section { uint32_t shName; uint32_t shType; uint32_t shFlags; uint32_t shAddr; uint32_t shOffset; uint32_t shSize; uint32_t shLink; uint32_t shInfo; uint32_t shAddralign; uint32_t shEntsize; };) VPU_PACKED(Elf32Phdr { uint32_t pType; // Identifies program segment type uint32_t pOffset; // Segment file offset uint32_t pVaddr; // Segment virtual address uint32_t pPaddr; // Segment physical address uint32_t pFilesz; // Segment size in file uint32_t pMemsz; // Segment size in memory uint32_t pFlags; // Flags position from ELF standard spec uint32_t pAlign; // Segment alignment, file & memory };) VPU_PACKED(Elf32Sym { uint32_t stName; uint32_t stValue; uint32_t stSize; uint8_t stInfo; uint8_t stOther; uint16_t stShndx; };) VPU_PACKED(KernelHdr { uint32_t address; // Kernel address uint32_t flags; // Should be 0 for now uint32_t sectionSize; // Section size, offset to the next kernel uint32_t argOffset; // offset to arguments uint32_t stackSize; // Size of the stack required for kernel uint32_t stackSizeWI; // Size of the stack required for kernel per WI };) VPU_PACKED(KernelArgHdr { uint32_t stringOffset; uint32_t addressSpace; uint32_t typeOffset; uint32_t size; uint32_t laneSize; };) std::pair findSymbolTable( const char* ELFData) { const uint32_t SYMTAB = 2; // Link editing symbol table const uint32_t STRTAB = 3; // A string table IE_ASSERT(ELFData != nullptr); auto ehdr = reinterpret_cast(ELFData); auto shdr = reinterpret_cast(ELFData + ehdr->eShoff); const Elf32Section* strShdr = nullptr; const Elf32Section* symShdr = nullptr; for (size_t i = 0; i < ehdr->eShnum; i++) { if (shdr[i].shType == STRTAB && strShdr == nullptr) { strShdr = &shdr[i]; } else if (shdr[i].shType == SYMTAB && symShdr == nullptr) { symShdr = &shdr[i]; } if (symShdr != nullptr && strShdr != nullptr) break; } IE_ASSERT(symShdr != nullptr && strShdr != nullptr); return std::make_pair(strShdr, symShdr); } SmallVector deduceKernelParameters(const md_parser_t& parser, int kernelId) { const auto kernelDesc = parser.get_kernel(kernelId); IE_ASSERT(kernelDesc != nullptr); // Number of elements we get from parser is always greater by one const auto argCount = kernelDesc->arg_count - 1; auto arguments = SmallVector{}; arguments.reserve(argCount); for (uint32_t i = 0; i < argCount; i++) { const auto arg = parser.get_argument(kernelDesc, i); VPU_THROW_UNLESS(arg, "Error while parsing custom layer elf file."); // skip hoisted buffers if (arg->flags & md_arg_flags_generated_prepost) { continue; } const auto argName = parser.get_name(arg); arguments.emplace_back(argName); } return arguments; } static const Elf32Shdr *get_elf_section_with_name(const uint8_t *elf_data, const char* section_name) { IE_ASSERT(elf_data); IE_ASSERT(section_name); const auto *ehdr = reinterpret_cast(elf_data); IE_ASSERT(0 != ehdr->eShoff); IE_ASSERT(0 != ehdr->ePhoff); // Pointer to the first section header const Elf32Shdr *shdr = reinterpret_cast(elf_data + ehdr->eShoff); // Pointer to section header string table header const Elf32Shdr *strShdr = &shdr[ehdr->eShstrndx]; // We couldn't find sections for the symbol string names and for the symbols // entries if (!strShdr) { return nullptr; } // The string at index 0, which corresponds to the first byte, is a null // character const char *firstStr = reinterpret_cast(elf_data + strShdr->shOffset); // Find the section with the custom SHAVEComputeAorta data for (uint16_t i = 0; i < ehdr->eShnum; i++) { const char *currentSectionName = firstStr + shdr[i].shName; if (0 == strcmp(currentSectionName, section_name)) { return shdr + i; } } // If we reached this point, it means that there wasn't a section with // the name we were looking for return nullptr; } uint32_t getKernelEntry(const char* ELFData, const std::string& kernelName) { IE_ASSERT(ELFData != nullptr); const auto cmp = ie::details::CaselessEq{}; auto ehdr = reinterpret_cast(ELFData); auto phdr = reinterpret_cast(ELFData + ehdr->ePhoff); const Elf32Section* strShdr = nullptr; const Elf32Section* symShdr = nullptr; std::tie(strShdr, symShdr) = findSymbolTable(ELFData); IE_ASSERT(symShdr != nullptr && strShdr != nullptr); auto numSymEntries = symShdr->shSize / symShdr->shEntsize; auto sym = reinterpret_cast(ELFData + symShdr->shOffset); auto firstStr = ELFData + strShdr->shOffset; for (size_t i = 0; i < numSymEntries; i++) { if (cmp(firstStr + sym[i].stName, kernelName)) { return sym[i].stValue - phdr->pVaddr; } } THROW_IE_EXCEPTION << "Cannot find kernel entry point for custom kernel " << kernelName; } CustomKernel::CustomKernel(const pugi::xml_node& kernel, std::string configDir): _configDir {std::move(configDir)} { _maxShaves = XMLParseUtils::GetIntAttr(kernel, "max-shaves", 0); std::string fileName; FOREACH_CHILD(source, kernel, "Source") { fileName = _configDir + "/" + XMLParseUtils::GetStrAttr(source, "filename", ""); std::ifstream inputFile(fileName, std::ios::binary); if (!inputFile.is_open()) { THROW_IE_EXCEPTION << "Couldn't open kernel file " << fileName; } std::ostringstream contentStream; contentStream << inputFile.rdbuf(); _kernelBinary.append(contentStream.str()); } const auto kernelEntryName = XMLParseUtils::GetStrAttr(kernel, "entry"); const auto elf = reinterpret_cast(_kernelBinary.data()); const Elf32Shdr *neoMetadataShdr = get_elf_section_with_name(elf, ".neo_metadata"); VPU_THROW_UNLESS(neoMetadataShdr, "Error while parsing custom layer elf: Couldn't find .neo_metadata section"); const uint8_t *neoMetadata = elf + neoMetadataShdr->shOffset; const size_t neoMetadataSize = neoMetadataShdr->shSize; const Elf32Shdr *neoMetadataStrShdr = get_elf_section_with_name(elf, ".neo_metadata.str"); VPU_THROW_UNLESS(neoMetadataStrShdr, "Error while parsing custom layer elf: Couldn't find .neo_metadata.str section"); const char *neoMetadataStr = reinterpret_cast(elf + neoMetadataStrShdr->shOffset); const size_t neoMetadataStrSize = neoMetadataStrShdr->shSize; const auto parser = md_parser_t{neoMetadata, neoMetadataSize, neoMetadataStr, neoMetadataStrSize}; _kernelId = parser.get_kernel_id(kernelEntryName); VPU_THROW_UNLESS(_kernelId != -1, "Failed to find kernel with name `%l`", kernelEntryName); VPU_THROW_UNLESS(parser.get_kernel_count() == 1, "Failed to load kernel binary '%l'\n" "\tReason: binary should contain only one kernel, but contains %l", fileName, parser.get_kernel_count()); _parameters = deduceKernelParameters(parser, _kernelId); processParametersNode(kernel); processWorkSizesNode(kernel); const auto isInputData = [&](const CustomKernel::KernelParam& param) { return param.type == CustomParamType::Input || param.type == CustomParamType::InputBuffer || param.type == CustomParamType::Data; }; _inputDataCount = static_cast(std::count_if(begin(_kernelParams), end(_kernelParams), isInputData)); } std::pair parseDimSource(const std::string& dims) { const auto cmp = ie::details::CaselessEq{}; const auto pos = dims.find_first_of(','); const auto source = dims.substr(0, pos); const auto dimSource = [&] { if (cmp(source, "input")) { return CustomDimSource::Input; } else if (cmp(source, "output")) { return CustomDimSource::Output; } else { THROW_IE_EXCEPTION << "Invalid dim source argument" << source; } }(); const auto idx = [&] { if (pos == std::string::npos) { return -1; } const auto idxString = dims.substr(pos + 1, std::string::npos); return std::stoi(idxString); }(); return std::make_pair(dimSource, idx); } CustomDataFormat formatFromString(const std::string& str) { static const ie::details::caseless_map FormatNameToType = { { "BFYX" , CustomDataFormat::BFYX }, { "BYXF" , CustomDataFormat::BYXF }, { "FYX" , CustomDataFormat::FYX }, { "YXF" , CustomDataFormat::YXF }, { "BF" , CustomDataFormat::BF }, { "ANY" , CustomDataFormat::Any } }; auto it = FormatNameToType.find(str); if (it != FormatNameToType.end()) { return it->second; } THROW_IE_EXCEPTION << "Tensor node has an invalid format '" << str << "'"; } SmallVector parseSizeRule(const std::string& size) { auto result = SmallVector(); result.reserve(std::count(begin(size), end(size), ',') + 1); std::stringstream sizeRules{size}; std::string bufferSize; while (std::getline(sizeRules, bufferSize, ',')) { result.push_back(bufferSize); } return result; } void CustomKernel::processParametersNode(const pugi::xml_node& node) { const auto cmp = ie::details::CaselessEq {}; const auto parameters = node.child("Parameters"); FOREACH_CHILD(tensor, parameters, "Tensor") { KernelParam kp; auto typeStr = XMLParseUtils::GetStrAttr(tensor, "type"); if (cmp(typeStr, "input")) { kp.type = CustomParamType::Input; } else if (cmp(typeStr, "output")) { kp.type = CustomParamType::Output; } else if (cmp(typeStr, "input_buffer")) { kp.type = CustomParamType::InputBuffer; } else if (cmp(typeStr, "output_buffer")) { kp.type = CustomParamType::OutputBuffer; } else if (cmp(typeStr, "data")) { kp.type = CustomParamType::Data; } else { THROW_IE_EXCEPTION << "Tensor node has an invalid type '" << typeStr << "'"; } if (kp.type == CustomParamType::InputBuffer || kp.type == CustomParamType::OutputBuffer) { const auto sizeRule = XMLParseUtils::GetStrAttr(tensor, "size"); kp.bufferSizeRule = parseSizeRule(sizeRule)[0]; const auto dimString = XMLParseUtils::GetStrAttr(tensor, "dim"); std::tie(kp.dimSource, kp.dimIdx) = parseDimSource(dimString); } kp.format = formatFromString(XMLParseUtils::GetStrAttr(tensor, "format", "BFYX")); kp.argName = XMLParseUtils::GetStrAttr(tensor, "arg-name"); kp.portIndex = XMLParseUtils::GetIntAttr(tensor, "port-index"); _kernelParams.push_back(std::move(kp)); } FOREACH_CHILD(data, parameters, "Data") { KernelParam kp; auto typeStr = XMLParseUtils::GetStrAttr(data, "type"); if (cmp(typeStr, "data")) { kp.type = CustomParamType::Data; } else if (cmp(typeStr, "local_data")) { kp.type = CustomParamType::LocalData; } else { THROW_IE_EXCEPTION << "Data node has an invalid type '" << typeStr << "'"; } kp.argName = XMLParseUtils::GetStrAttr(data, "arg-name"); kp.irSource = XMLParseUtils::GetStrAttr(data, "source", ""); const auto dimString = XMLParseUtils::GetStrAttr(data, "dim", ""); if (kp.irSource.empty() && dimString.empty()) { THROW_IE_EXCEPTION << "Data node has no source or dim"; } if (!kp.irSource.empty() && !dimString.empty()) { THROW_IE_EXCEPTION << "Data node can only have source or dim"; } if (kp.type == CustomParamType::LocalData) { const auto bufferSize = XMLParseUtils::GetStrAttr(data, "size", ""); kp.bufferSizeRule = bufferSize; if (!dimString.empty()) { std::tie(kp.dimSource, kp.dimIdx) = parseDimSource(dimString); } } _kernelParams.push_back(std::move(kp)); } FOREACH_CHILD(scalar, parameters, "Scalar") { KernelParam kp; const auto type = XMLParseUtils::GetStrAttr(scalar, "type"); if (cmp(type, "int")) { kp.type = CustomParamType::Int; } else if (cmp(type, "float")) { kp.type = CustomParamType::Float; } else { THROW_IE_EXCEPTION << "Scalar node has an invalid type " << type; } kp.argName = XMLParseUtils::GetStrAttr(scalar, "arg-name"); kp.portIndex = XMLParseUtils::GetIntAttr(scalar, "port-index", -1); kp.irSource = XMLParseUtils::GetStrAttr(scalar, "source", ""); _kernelParams.push_back(std::move(kp)); } } void CustomKernel::processWorkSizesNode(const pugi::xml_node& node) { const auto workSizes = node.child("WorkSizes"); const auto dims = XMLParseUtils::GetStrAttr(workSizes, "dim"); std::tie(_wgDimSource, _wgDimIdx) = parseDimSource(dims); const auto gwgs = XMLParseUtils::GetStrAttr(workSizes, "global"); _globalGridSizeRules = parseSizeRule(gwgs); const auto lwgs = XMLParseUtils::GetStrAttr(workSizes, "local"); _localGridSizeRules = parseSizeRule(lwgs); } } // namespace vpu /* HyExplorer - hyperspectral images management system * Copyright (c) 2015-2016 HyExplorer team * http://virtualglobe.ru/hyexplorer/ * * 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 "DataSet.hpp" #include "ClipInfo.hpp" #include #include #include #include #include #include #include #include #include #include #include namespace portal { class DataManager { public: DataManager(osgViewer::View* view, osgEarth::MapNode* mapNode); osgViewer::View* view() const { return _view; } osgEarth::MapNode* mapNode() const { return _mapNode; } bool atmosphereVisibility() const; void setAtmosphereVisibility(bool b); //------------------- void addReportHandler(osgGA::GUIEventHandler* handler); void removeReportHandler(osgGA::GUIEventHandler* handler); void setDefaultActionHandler(osgGA::GUIEventHandler* handler); void setActionHandler(osgGA::GUIEventHandler* handler); //------------------- void setDataSet(const DataSetPtr& dataset); void showOverview(const ScenePtr& scene, const QString& filepath); void showScene(const ScenePtr& scene, int band, const ClipInfoPtr& clipInfo); void zoomToScene(const ScenePtr& scene); //------------------- void setCircleNode(const osgEarth::GeoPoint& center, double radius); void removeCircleNode(); //------------------- const QStringList& coverageNames() const { return _coverageNames; } void setCoverage(const QString& coverageName); //------------------- const boost::optional& bounds() const { return _bounds; } void setBounds(const osgEarth::Bounds& b); void drawBounds(const osgEarth::Bounds& b); //------------------- QNetworkAccessManager& networkAccessManager() { return _networkManager; } protected: DataManager(const DataManager&) = delete; DataManager& operator=(const DataManager&) = delete; osg::ref_ptr _view; osg::ref_ptr _mapNode; osg::ref_ptr _defaultHandler; osg::ref_ptr _currentHandler; osg::ref_ptr _sky; DataSetPtr _dataset; ScenePtr _scene; osg::ref_ptr _circleNode; osg::ref_ptr _overlayNode; QStringList _coverageNames; std::map _coverageMap; osg::ref_ptr _sceneLayer; QNetworkAccessManager _networkManager; boost::optional _bounds; osg::ref_ptr _ring; osg::ref_ptr _feature; osg::ref_ptr _featureNode; }; typedef std::shared_ptr DataManagerPtr; } /* Create a program that takes number as input and returns its square root in the form of a string.*/ #include #include int main() { int number; std::cout << "Enter a number: "; std::cin >> number; std::cout << "The square root of " << number << " is " << sqrt(number) << std::endl; return 0; } Source/AllProjects/Utilities/CQCDocComp/CQCDocComp_IntfWidget.cpp // // FILE NAME: CQCDocComp_IntfWdg.Cpp // // AUTHOR: // // CREATED: 09/19/2016 // // COPYRIGHT: Charmed Quark Systems, Ltd @ 2020 // // This software is copyrighted by 'Charmed Quark Systems, Ltd' and // the author (.) It is licensed under the MIT Open Source // license: // // https://opensource.org/licenses/MIT // // DESCRIPTION: // // The implementation of the interface widget reference docs class. // // CAVEATS/GOTCHAS: // // LOG: // // $_CIDLib_Log_$ // // ---------------------------------------------------------------------------- // Includes // ---------------------------------------------------------------------------- #include "CQCDocComp.hpp" // --------------------------------------------------------------------------- // CLASS: TDocIntfWidget // PREFIX: actt // --------------------------------------------------------------------------- // --------------------------------------------------------------------------- // TDocIntfWidget: Constructors and Destructor // --------------------------------------------------------------------------- TDocIntfWidget::TDocIntfWidget() { } TDocIntfWidget::~TDocIntfWidget() { } // --------------------------------------------------------------------------- // TDocIntfWidget: Public, inherited methods // --------------------------------------------------------------------------- tCIDLib::TBoolean TDocIntfWidget::bParseXML( const TXMLTreeElement& xtnodeWdg , const TString& strName , const TTopic& topicPar) { // Call our parent first if (!TBasePage::bParseXML(xtnodeWdg, strName, topicPar)) return kCIDLib::False; // If we have any commands, process them tCIDLib::TCard4 c4At; const TXMLTreeElement* pxtnodeCur = xtnodeWdg.pxtnodeFindElement(L"IntfCmds", 0, c4At); if (pxtnodeCur) { if (!bParseCmds(*pxtnodeCur)) return kCIDLib::False; } // If we have any events, process them c4At = 0; pxtnodeCur = xtnodeWdg.pxtnodeFindElement(L"IntfEvents", 0, c4At); if (pxtnodeCur) { if (!bParseItems(*pxtnodeCur, m_colEvents, m_hnEvents)) return kCIDLib::False; } // If we have any RTVs, process them c4At = 0; pxtnodeCur = xtnodeWdg.pxtnodeFindElement(L"IntfRTVs", 0, c4At); if (pxtnodeCur) { if (!bParseItems(*pxtnodeCur, m_colRTVs, m_hnRTVs)) return kCIDLib::False; } // Process the overall widget description text return bProcessHelpText(xtnodeWdg, L"WdgDescr", m_hnDescr, kCIDLib::False); } tCIDLib::TVoid TDocIntfWidget::GenerateOutput(TTextOutStream& strmTar) const { strmTar << L"\n" L""; strmTar << m_strTitle; strmTar << L"

"; // Spit out the main target docs strmTar << L"
"; OutputNodes(strmTar, m_hnDescr, m_strPath); strmTar << L"
"; // If any events do those { const tCIDLib::TCard4 c4EvCnt = m_colEvents.c4ElemCount(); if (c4EvCnt) { strmTar << L"

Supported Events

"; if (!m_hnEvents.bIsEmpty()) { strmTar << L"
"; OutputNodes(strmTar, m_hnEvents, m_strPath); strmTar << L"
"; } strmTar << L"
    \n"; for (tCIDLib::TCard4 c4Index = 0; c4Index < c4EvCnt; c4Index++) { const TKeyValuePair& kvalCur = m_colEvents[c4Index]; strmTar << L"
  • " << kvalCur.strKey() << L". " << kvalCur.strValue() << L"
  • "; } strmTar << L"
"; } } // If any commands do those { const tCIDLib::TCard4 c4CmdCnt = m_colCmds.c4ElemCount(); if (c4CmdCnt) { strmTar << L"

Supported Commands

"; if (!m_hnCmds.bIsEmpty()) { strmTar << L"
"; OutputNodes(strmTar, m_hnCmds, m_strPath); strmTar << L"
"; } strmTar << L"
\n"; for (tCIDLib::TCard4 c4Index = 0; c4Index < c4CmdCnt; c4Index++) m_colCmds[c4Index].GenerateOutput(strmTar, m_strPath); strmTar << L"
"; } strmTar << L""; } // If any RTVs do those { const tCIDLib::TCard4 c4RTVCnt = m_colRTVs.c4ElemCount(); if (c4RTVCnt) { strmTar << L"

Provded Runtime Values

"; if (!m_hnRTVs.bIsEmpty()) { strmTar << L"
"; OutputNodes(strmTar, m_hnRTVs, m_strPath); strmTar << L"
"; } strmTar << L"
    \n"; for (tCIDLib::TCard4 c4Index = 0; c4Index < c4RTVCnt; c4Index++) { const TKeyValuePair& kvalCur = m_colRTVs[c4Index]; strmTar << L"
  • " << kvalCur.strKey() << L". " << kvalCur.strValue() << L"
  • "; } strmTar << L"
"; } } } // --------------------------------------------------------------------------- // TDocIntfWidget: Private, non-virtual methods // --------------------------------------------------------------------------- tCIDLib::TBoolean TDocIntfWidget::bParseCmds(const TXMLTreeElement& xtnodeCmds) { // The first child can be a helper text tCIDLib::TCard4 c4Index = 0; const TXMLTreeElement& xtnodeFirst = xtnodeCmds.xtnodeChildAtAsElement(0); if (xtnodeFirst.strQName() == L"WdgDescr") { if (!bProcessHelpText(xtnodeFirst, m_hnCmds)) return kCIDLib::False; c4Index++; } TDocActionCmd actcEmpty; const tCIDLib::TCard4 c4ChildCnt = xtnodeCmds.c4ChildCount(); for (; c4Index < c4ChildCnt; c4Index++) { const TXMLTreeElement& xtnodeCmd = xtnodeCmds.xtnodeChildAtAsElement(c4Index); CIDAssert(xtnodeCmd.strQName() == L"CQCActCmd", L"Expected an action command here"); TDocActionCmd& actcCur = m_colCmds.objAdd(actcEmpty); if (!actcCur.bParseXML(xtnodeCmd)) return kCIDLib::False; } return kCIDLib::True; } tCIDLib::TBoolean TDocIntfWidget::bParseItems(const TXMLTreeElement& xtnodePar , tCIDLib::TKVPList& colToFill , THelpNode& hnToFill) { // The first child can be a helper text tCIDLib::TCard4 c4Index = 0; const TXMLTreeElement& xtnodeFirst = xtnodePar.xtnodeChildAtAsElement(0); if (xtnodeFirst.strQName() == L"WdgDescr") { if (!bProcessHelpText(xtnodeFirst, hnToFill)) return kCIDLib::False; c4Index++; } TString strDescr; TKeyValuePair kvalEmpty; const tCIDLib::TCard4 c4ChildCnt = xtnodePar.c4ChildCount(); for (; c4Index < c4ChildCnt; c4Index++) { const TXMLTreeElement& xtnodeCur = xtnodePar.xtnodeChildAtAsElement(c4Index); // Get the child text which is the description const TXMLTreeText& xtnodeDescr = xtnodeCur.xtnodeChildAtAsText(0); TKeyValuePair& kvalCur = colToFill.objAdd(kvalEmpty); kvalCur.Set ( xtnodeCur.xtattrNamed(L"Name").strValue(), xtnodeDescr.strText() ); } return kCIDLib::True; } test/test1.cpp /** * @file * * Distributed under the Boost Software License, Version 1.0. * See accompanying file LICENSE or copy at http://www.boost.org/LICENSE_1_0.txt */ #include "corefungi.hpp" #include "ostream.hpp" #include corefungi::sprout const options = { "Corefungi options", { { "another.test", "alternate config file", corefungi::bool_switch }, { "test.size_t", "a size_t parameter", corefungi::of_type< size_t >() } } }; int main(int argc, char const* argv[]) { namespace cfg = ::corefungi; cfg::node n; cfg::init(argc, argv); std::clog << "command: " << cfg::command << std::endl; std::clog << "local: " << cfg::local << std::endl; std::clog << "global: " << cfg::global << std::endl; std::clog << "system: " << cfg::system << std::endl; bool result = cfg::get("another.test"); // *INDENT-OFF*/ n = cfg::dict { { cfg::spore {"value"}, cfg::value { "bla" } }, { cfg::spore {"list-value"}, cfg::list { cfg::value {"bar"}, cfg::value {"bar"} } }, { cfg::spore {"dict-value"}, cfg::dict { { cfg::spore {"bar"}, cfg::value {"bar"} } } }, { cfg::spore {"dict-value-2"}, cfg::dict { { cfg::spore {"bar"}, cfg::list { cfg::value {"bar0"}, cfg::value {"bar1"} } } } } }; // *INDENT-ON*/ std::cout << cfg::collect(n, "*.bar.#0") << std::endl; cfg::node m; std::cout << m << std::endl; auto sprinklings = cfg::grow(m, "foo.#.bla"); std::cout << sprinklings << std::endl; for (auto& n : sprinklings) { n = cfg::spore {"bla"}; } std::cout << m << std::endl; cfg::put(m, "foo.#.*", "bar"); std::cout << m << std::endl; for (auto& pair : cfg::items(n)) { std::cout << pair.first << ": " << pair.second << std::endl; } for (auto& key : cfg::keys(n)) { std::cout << key << std::endl; } for (auto& value : cfg::values(n)) { std::cout << value << std::endl; } std::cout << n << std::endl; // try { // cfg::spore sp = cfg::list { // "bar", "bar" // }; // std::cout << sp << std::endl; // size_t v = sp; // std::cout << sp << ": " << v << std::endl; // } catch (std::exception const& e) { // std::clog << "Exception raised: " << e.what() << std::endl; // } try { auto const sp = cfg::spore {"0"}; size_t const v = sp; std::cout << sp << ": " << v << std::endl; } catch (std::exception const& e) { std::clog << "Exception raised: " << e.what() << std::endl; } return 0; } // main AllaMaevskaya/AliRoot10-100 /************************************************************************** * 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. * **************************************************************************/ /// \class AliTPCCalibRawBase /// \brief Base class for the calibration algorithms using raw data as input /// /// \author //Root includes #include #include //Aliroot includes #include "AliRawReaderDate.h" #include "AliRawReader.h" #include "AliRawEventHeaderBase.h" #include "AliAltroMapping.h" #include "AliAltroRawStream.h" #include "AliTPCROC.h" #include "AliTPCRawStreamV3.h" #include "AliLog.h" #include "TTreeStream.h" #include "event.h" #include "AliTPCCalibRawBase.h" /// \cond CLASSIMP ClassImp(AliTPCCalibRawBase) /// \endcond AliTPCCalibRawBase::AliTPCCalibRawBase() : TNamed(), fFirstTimeBin(0), fLastTimeBin(1000), fNevents(0), fDebugLevel(0), fStreamLevel(0), fRunNumber(0), fFirstTimeStamp(0), fLastTimeStamp(0), fTimeStamp(0), fEventType(0), fAltroL1Phase(0), fAltroL1PhaseTB(0), fCurrRCUId(-1), fPrevRCUId(-1), fCurrDDLNum(-1), fPrevDDLNum(-1), fUseL1Phase(kTRUE), fDebugStreamer(0x0), fAltroRawStream(0x0), fMapping(0x0), fROC(AliTPCROC::Instance()) { // // default ctor // } //_____________________________________________________________________ AliTPCCalibRawBase::AliTPCCalibRawBase(const AliTPCCalibRawBase &calib) : TNamed(calib), fFirstTimeBin(calib.fFirstTimeBin), fLastTimeBin(calib.fLastTimeBin), fNevents(calib.fNevents), fDebugLevel(calib.fDebugLevel), fStreamLevel(calib.fStreamLevel), fRunNumber(calib.fRunNumber), fFirstTimeStamp(calib.fFirstTimeStamp), fLastTimeStamp(calib.fLastTimeStamp), fTimeStamp(0), fEventType(0), fAltroL1Phase(0), fAltroL1PhaseTB(0), fCurrRCUId(-1), fPrevRCUId(-1), fCurrDDLNum(-1), fPrevDDLNum(-1), fUseL1Phase(kTRUE), fDebugStreamer(0x0), fAltroRawStream(0x0), fMapping(0x0), fROC(AliTPCROC::Instance()) { /// copy ctor } //_____________________________________________________________________ AliTPCCalibRawBase::~AliTPCCalibRawBase() { /// dtor if (fDebugStreamer) delete fDebugStreamer; } //_____________________________________________________________________ AliTPCCalibRawBase& AliTPCCalibRawBase::operator = (const AliTPCCalibRawBase &source) { /// assignment operator if (&source == this) return *this; new (this) AliTPCCalibRawBase(source); return *this; } //_____________________________________________________________________ Bool_t AliTPCCalibRawBase::ProcessEvent(AliTPCRawStreamV3 * const rawStreamV3) { /// Event Processing loop - AliTPCRawStreamV3 ResetEvent(); Bool_t withInput = kFALSE; fAltroL1Phase=0; fAltroL1PhaseTB=0; // fAltroRawStream = static_cast(rawStreamV3); while ( rawStreamV3->NextDDL() ){ if (AliLog::GetGlobalDebugLevel()>2) rawStreamV3->PrintRCUTrailer(); fPrevDDLNum=-1; fCurrRCUId=rawStreamV3->GetRCUId(); fCurrDDLNum=rawStreamV3->GetDDLNumber(); if (fUseL1Phase){ // fAltroL1Phase = fAltroRawStream->GetL1Phase(); fAltroL1Phase = rawStreamV3->GetL1Phase(); fAltroL1PhaseTB = (fAltroL1Phase*1e09/100.); AliDebug(1, Form("L1Phase: %.2e (%03d)\n",fAltroL1PhaseTB,fCurrDDLNum)); } UpdateDDL(); while ( rawStreamV3->NextChannel() ){ Int_t isector = rawStreamV3->GetSector(); // current sector Int_t iRow = rawStreamV3->GetRow(); // current row Int_t iPad = rawStreamV3->GetPad(); // current pad while ( rawStreamV3->NextBunch() ){ UInt_t startTbin = rawStreamV3->GetStartTimeBin(); // Int_t endTbin = (Int_t)rawStreamV3->GetEndTimeBin(); Int_t bunchlength = rawStreamV3->GetBunchLength(); const UShort_t *sig = rawStreamV3->GetSignals(); ProcessBunch(isector,iRow,iPad,bunchlength,startTbin,sig); for (Int_t iTimeBin = 0; iTimeBinGetEventHeader(); if (eventHeader){ fTimeStamp = eventHeader->Get("Timestamp"); fRunNumber = eventHeader->Get("RunNb"); fEventType = eventHeader->Get("Type"); } if (!fFirstTimeStamp) fFirstTimeStamp=fTimeStamp; AliTPCRawStreamV3 *rawStreamV3 = new AliTPCRawStreamV3(rawReader, (AliAltroMapping**)fMapping); Bool_t res=ProcessEvent(rawStreamV3); fLastTimeStamp=fTimeStamp; delete rawStreamV3; return res; } //_____________________________________________________________________ Bool_t AliTPCCalibRawBase::ProcessEvent(eventHeaderStruct * const event) { /// Event processing loop - date event fRunNumber=event->eventRunNb; fTimeStamp=event->eventTimestamp; if (!fFirstTimeStamp) fFirstTimeStamp=fTimeStamp; fLastTimeStamp=fTimeStamp; fEventType=event->eventType; AliRawReader *rawReader = new AliRawReaderDate((void*)event); AliTPCRawStreamV3 *rawStreamV3 = new AliTPCRawStreamV3(rawReader, (AliAltroMapping**)fMapping); Bool_t result=ProcessEvent(rawStreamV3); delete rawStreamV3; delete rawReader; return result; } //_____________________________________________________________________ void AliTPCCalibRawBase::DumpToFile(const Char_t *filename, const Char_t *dir, Bool_t append) { /// Write class to file TString sDir(dir); TString option; if ( append ) option = "update"; else option = "recreate"; TDirectory *backup = gDirectory; TFile f(filename,option.Data()); f.cd(); if ( !sDir.IsNull() ){ f.mkdir(sDir.Data()); f.cd(sDir); } this->Write(); f.Close(); if ( backup ) backup->cd(); } //_____________________________________________________________________ TTreeSRedirector *AliTPCCalibRawBase::GetDebugStreamer(){ /// Get Debug streamer /// In case debug streamer not yet initialized and StreamLevel>0 create new one if (fStreamLevel==0) return 0; if (fDebugStreamer) return fDebugStreamer; TString dsName; dsName=GetName(); dsName+="Debug.root"; dsName.ReplaceAll(" ",""); fDebugStreamer = new TTreeSRedirector(dsName.Data()); return fDebugStreamer; } //_____________________________________________________________________ void AliTPCCalibRawBase::MergeBase(const AliTPCCalibRawBase *calib) { /// merge this with base if (calib->fFirstTimeStampfFirstTimeStamp; if (calib->fLastTimeStamp>fLastTimeStamp) fLastTimeStamp =calib->fLastTimeStamp; } /* MIT License - Copyright (c) 2019-2021 For full license information read the LICENSE file in the project folder */ /* Multi threaded asynchronous paho client */ #include #include "hasp_conf.h" #if HASP_USE_MQTT_ASYNC > 0 #ifdef USE_PAHO /******************************************************************************* * Copyright (c) 2012, 2020 IBM Corp. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v2.0 * and Eclipse Distribution License v1.0 which accompany this distribution. * * The Eclipse Public License is available at * https://www.eclipse.org/legal/epl-2.0/ * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * - initial contribution *******************************************************************************/ #include #include #include #include #include #include #include "MQTTAsync.h" #include "hasp_mqtt.h" // functions to implement here #include "hasp/hasp_dispatch.h" // for dispatch_topic_payload #include "hasp_debug.h" // for logging #if !defined(_WIN32) #include #else #include #endif #if defined(_WRS_KERNEL) #include #endif #define ADDRESS "10.4.0.5:1883" #define CLIENTID "ExampleClientSub" #define TOPIC "hasp/plate35/" #define QOS 1 #define TIMEOUT 10000L const char* mqttNodeTopic = TOPIC; const char* mqttGroupTopic = TOPIC; // char mqttNodeTopic[24]; // char mqttGroupTopic[24]; bool mqttEnabled = false; bool mqttHAautodiscover = true; std::recursive_mutex dispatch_mtx; std::recursive_mutex publish_mtx; char mqttServer[16] = MQTT_HOST; char mqttUser[23] = MQTT_USER; char mqttPassword[32] = MQTT_PASSW; // char mqttNodeName[16] = MQTT_NODENAME; char mqttGroupName[16] = MQTT_GROUPNAME; uint16_t mqttPort = MQTT_PORT; MQTTAsync mqtt_client; int disc_finished = 0; int subscribed = 0; int connected = 0; static bool mqttPublish(const char* topic, const char* payload, size_t len, bool retain = false); /* ===== Paho event callbacks ===== */ void connlost(void* context, char* cause) { printf("\nConnection lost\n"); if(cause) printf(" cause: %s\n", cause); printf("Reconnecting\n"); mqttStart(); } // Receive incoming messages static void mqtt_message_cb(char* topic, char* payload, size_t length) { // Handle incoming commands from MQTT if(length + 1 >= MQTT_MAX_PACKET_SIZE) { LOG_ERROR(TAG_MQTT_RCV, F(D_MQTT_PAYLOAD_TOO_LONG), (uint32_t)length); return; } else { payload[length] = '\0'; } LOG_TRACE(TAG_MQTT_RCV, F("%s = %s"), topic, (char*)payload); if(topic == strstr(topic, mqttNodeTopic)) { // startsWith mqttNodeTopic // Node topic topic += strlen(mqttNodeTopic); // shorten topic } else if(topic == strstr(topic, mqttGroupTopic)) { // startsWith mqttGroupTopic // Group topic topic += strlen(mqttGroupTopic); // shorten topic dispatch_mtx.lock(); dispatch_topic_payload(topic, (const char*)payload); dispatch_mtx.unlock(); return; #ifdef HASP_USE_HA } else if(topic == strstr_P(topic, PSTR("homeassistant/status"))) { // HA discovery topic if(mqttHAautodiscover && !strcasecmp_P((char*)payload, PSTR("online"))) { dispatch_current_state(); mqtt_ha_register_auto_discovery(); } return; #endif } else { // Other topic LOG_ERROR(TAG_MQTT, F(D_MQTT_INVALID_TOPIC)); return; } // catch a dangling LWT from a previous connection if it appears if(!strcmp_P(topic, PSTR(MQTT_TOPIC_LWT))) { // endsWith LWT if(!strcasecmp_P((char*)payload, PSTR("offline"))) { { char msg[8]; char tmp_topic[strlen(mqttNodeTopic) + 8]; snprintf_P(tmp_topic, sizeof(tmp_topic), PSTR("%s" MQTT_TOPIC_LWT), mqttNodeTopic); snprintf_P(msg, sizeof(msg), PSTR("online")); // /*bool res =*/mqttClient.publish(tmp_topic, msg, true); mqttPublish(tmp_topic, msg, true); } } else { // LOG_TRACE(TAG_MQTT, F("ignoring LWT = online")); } } else { dispatch_mtx.lock(); dispatch_topic_payload(topic, (const char*)payload); dispatch_mtx.unlock(); } } int msgarrvd(void* context, char* topicName, int topicLen, MQTTAsync_message* message) { // printf("MQT RCV >> "); // printf("%s => %.*s (%d)\n", topicName, message->payloadlen, (char *)message->payload, message->payloadlen); char msg[message->payloadlen + 1]; memcpy(msg, (char*)message->payload, message->payloadlen); msg[message->payloadlen] = '\0'; mqtt_message_cb(topicName, (char*)message->payload, message->payloadlen); MQTTAsync_freeMessage(&message); MQTTAsync_free(topicName); return 1; } void onDisconnectFailure(void* context, MQTTAsync_failureData* response) { printf("Disconnect failed, rc %d\n", response->code); disc_finished = 1; } void onDisconnect(void* context, MQTTAsync_successData* response) { printf("Successful disconnection\n"); disc_finished = 1; connected = 0; } void onSubscribe(void* context, MQTTAsync_successData* response) { printf("Subscribe succeeded %d\n", response->token); subscribed = 1; } void onSubscribeFailure(void* context, MQTTAsync_failureData* response) { printf("Subscribe failed, rc %d\n", response->code); } void onConnectFailure(void* context, MQTTAsync_failureData* response) { connected = 0; printf("Connect failed, rc %d\n", response->code); } void mqtt_subscribe(void* context, const char* topic) { MQTTAsync client = (MQTTAsync)context; MQTTAsync_responseOptions opts = MQTTAsync_responseOptions_initializer; int rc; printf("Subscribing to topic %s\nfor client %s using QoS%d\n\n", topic, CLIENTID, QOS); opts.onSuccess = onSubscribe; opts.onFailure = onSubscribeFailure; opts.context = client; if((rc = MQTTAsync_subscribe(client, topic, QOS, &opts)) != MQTTASYNC_SUCCESS) { printf("Failed to start subscribe, return code %d\n", rc); } } void onConnect(void* context, MQTTAsync_successData* response) { MQTTAsync client = (MQTTAsync)context; connected = 1; printf("Successful connection\n"); mqtt_subscribe(context, TOPIC MQTT_TOPIC_COMMAND "/#"); mqtt_subscribe(context, TOPIC MQTT_TOPIC_COMMAND); mqtt_subscribe(context, TOPIC "light"); mqtt_subscribe(context, TOPIC "dim"); mqttPublish(TOPIC MQTT_TOPIC_LWT, "online", false); mqtt_send_object_state(0, 0, "connected"); std::cout << std::endl; } void onSendFailure(void* context, MQTTAsync_failureData* response) { MQTTAsync client = (MQTTAsync)context; MQTTAsync_disconnectOptions opts = MQTTAsync_disconnectOptions_initializer; int rc; printf("Message send failed token %d error code %d\n", response->token, response->code); opts.onSuccess = onDisconnect; opts.onFailure = onDisconnectFailure; opts.context = client; if((rc = MQTTAsync_disconnect(client, &opts)) != MQTTASYNC_SUCCESS) { printf("Failed to start disconnect, return code %d\n", rc); // exit(EXIT_FAILURE); } } void onSend(void* context, MQTTAsync_successData* response) { MQTTAsync client = (MQTTAsync)context; MQTTAsync_disconnectOptions opts = MQTTAsync_disconnectOptions_initializer; int rc; // printf("Message with token value %d delivery confirmed\n", response->token); // opts.onSuccess = onDisconnect; // opts.onFailure = onDisconnectFailure; // opts.context = client; // if ((rc = MQTTAsync_disconnect(client, &opts)) != MQTTASYNC_SUCCESS) // { // printf("Failed to start disconnect, return code %d\n", rc); // exit(EXIT_FAILURE); // } } /* ===== Local HASP MQTT functions ===== */ static bool mqttPublish(const char* topic, const char* payload, size_t len, bool retain) { if(mqttIsConnected()) { MQTTAsync_responseOptions opts = MQTTAsync_responseOptions_initializer; MQTTAsync_message pubmsg = MQTTAsync_message_initializer; int rc; opts.onSuccess = onSend; opts.onFailure = onSendFailure; opts.context = mqtt_client; pubmsg.payload = (char*)payload; pubmsg.payloadlen = (int)strlen(payload); pubmsg.qos = QOS; pubmsg.retained = 0; dispatch_mtx.lock(); if((rc = MQTTAsync_sendMessage(mqtt_client, topic, &pubmsg, &opts)) != MQTTASYNC_SUCCESS) { dispatch_mtx.unlock(); LOG_ERROR(TAG_MQTT_PUB, F(D_MQTT_FAILED " %s => %s"), topic, payload); } else { dispatch_mtx.unlock(); LOG_TRACE(TAG_MQTT_PUB, F("%s => %s"), topic, payload); return true; } } else { LOG_ERROR(TAG_MQTT, F(D_MQTT_NOT_CONNECTED)); } return false; } /* ===== Public HASP MQTT functions ===== */ bool mqttIsConnected() { return connected == 1; } void mqtt_send_state(const __FlashStringHelper* subtopic, const char* payload) { char tmp_topic[strlen(mqttNodeTopic) + 20]; printf(("%s" MQTT_TOPIC_STATE "/%s\n"), mqttNodeTopic, subtopic); snprintf_P(tmp_topic, sizeof(tmp_topic), ("%s" MQTT_TOPIC_STATE "/%s"), mqttNodeTopic, subtopic); mqttPublish(tmp_topic, payload, false); } void mqtt_send_object_state(uint8_t pageid, uint8_t btnid, const char* payload) { char tmp_topic[strlen(mqttNodeTopic) + 20]; snprintf_P(tmp_topic, sizeof(tmp_topic), PSTR("%s" MQTT_TOPIC_STATE "/p%ub%u"), mqttNodeTopic, pageid, btnid); mqttPublish(tmp_topic, payload, false); } void mqttStart() { MQTTAsync_connectOptions conn_opts = MQTTAsync_connectOptions_initializer; MQTTAsync_willOptions will_opts = MQTTAsync_willOptions_initializer; int rc; int ch; if((rc = MQTTAsync_create(&mqtt_client, ADDRESS, CLIENTID, MQTTCLIENT_PERSISTENCE_NONE, NULL)) != MQTTASYNC_SUCCESS) { printf("Failed to create client, return code %d\n", rc); rc = EXIT_FAILURE; return; } if((rc = MQTTAsync_setCallbacks(mqtt_client, mqtt_client, connlost, msgarrvd, NULL)) != MQTTASYNC_SUCCESS) { printf("Failed to set callbacks, return code %d\n", rc); rc = EXIT_FAILURE; return; } conn_opts.will = &will_opts; conn_opts.will->message = "offline"; conn_opts.will->qos = 1; conn_opts.will->retained = 0; conn_opts.will->topicName = "hasp/plate35/LWT"; conn_opts.keepAliveInterval = 20; conn_opts.cleansession = 1; conn_opts.onSuccess = onConnect; conn_opts.onFailure = onConnectFailure; conn_opts.context = mqtt_client; if((rc = MQTTAsync_connect(mqtt_client, &conn_opts)) != MQTTASYNC_SUCCESS) { printf("Failed to start connect, return code %d\n", rc); rc = EXIT_FAILURE; // goto destroy_exit; } else { } // while (!subscribed && !finished) // #if defined(_WIN32) // Sleep(100); // #else // usleep(10000L); // #endif // if (finished) // goto exit; } void mqttStop() { int rc; MQTTAsync_disconnectOptions disc_opts = MQTTAsync_disconnectOptions_initializer; disc_opts.onSuccess = onDisconnect; disc_opts.onFailure = onDisconnectFailure; if((rc = MQTTAsync_disconnect(mqtt_client, &disc_opts)) != MQTTASYNC_SUCCESS) { printf("Failed to start disconnect, return code %d\n", rc); rc = EXIT_FAILURE; // goto destroy_exit; } // while (!disc_finished) // { // #if defined(_WIN32) // Sleep(100); // #else // usleep(10000L); // #endif // } // destroy_exit: // MQTTAsync_destroy(&client); // exit: // return rc; } void mqttSetup(){}; IRAM_ATTR void mqttLoop(){}; void mqttEvery5Seconds(bool wifiIsConnected){}; #endif // USE_PAHO #endif // USE_MQTT loyio/leetcode class Solution { public: int lengthOfLongestSubstring(string s) { const int n = s.size(); unordered_map mp; int maxLength = 0, preLength = 1, curLength; for(int i = 0; i < n; i++){ if(mp.count(s[i]) == 1){ curLength = min(preLength, i-mp[s[i]]-1)+1; }else{ curLength = min(preLength, i)+1; } mp[s[i]] = i; maxLength = max(maxLength, curLength); preLength = curLength; } return maxLength; } }; /* * Copyright (c) 2014-2015, Hewlett-Packard Development Company, LP. * 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 * * HP designates this particular file as subject to the "Classpath" exception * as provided by HP in the LICENSE.txt file that accompanied this code. */ #ifndef FOEDUS_MEMORY_MEMORY_HIERARCHY_HPP_ #define FOEDUS_MEMORY_MEMORY_HIERARCHY_HPP_ /** * @defgroup MEMHIERARCHY Memory Hierarchy * @brief NUMA-Aware \b Memory \b Hierarchy in libfoedus-core * @ingroup MEMORY * @details * @par Overview * We have a memory hierarchy of three levels in libfoedus, resembling the memory hiearchy in * NUMA architecture: * \li Memories shared engine-wide (EngineMemory) * \li Memories shared NUMA-Node-wide (NumaNodeMemory) * \li Private Memories in each core (NumaCoreMemory) * * The resemblance is intentinal to achieve the best performance of memory * allocation/deallocation/sharing in NUMA setting. * * @par Absolutely no global nor truly TLS variables * You might notice that the top level of the hierarchy is \e engine-wide, not \e global. * libfoedus uses absolutely no global nor static variables except const primitive types. * This simplifies the design of memory management in the library and allows * running multiple instances (engines) of our library even in one process. * What we have in Engine object is everything. When Engine's uninitialize() is invoked, * everything the Engine acquired is released, separately from other Engine's. * This also means that memory-leak checkers like valgrind can easily check for potential errors. * * @note Unfortunately, there is one exception to this rule; google-logging. * google::InitGoogleLogging() and ShutdownGoogleLogging() must be called exactly once in the * process. So, we do them in Engine's initialize()/uninitialize() with a process-global atomic * counter to make sure we call them only once. * * @par Memories shared engine-wide (EngineMemory) * @copydetails foedus::memory::EngineMemory * * @par Memories shared NUMA-Node-wide (NumaNodeMemory) * @copydetails foedus::memory::NumaNodeMemory * * @par Private Memories in each core (NumaCoreMemory) * @copydetails foedus::memory::NumaCoreMemory * */ #endif // FOEDUS_MEMORY_MEMORY_HIERARCHY_HPP_ MonikaBhasin7/leetcode // Copyright (c) 2018-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. class Solution { public: int findNthDigit(int n) { int mn = 1, mx = 10, digits = 1; // Attempt to subtract the total number of digits for all numbers in the // range [mn, mx] while n is large enough. Each iteration advances the // each bound by a factor of 10, and therefore increases the number of digits // for each number in the range by 1 each time. // // If digits is >= 9, then the total number of digits exceeds the maximum value // of n (a 32-bit signed integer) so it is not possible to have more than 9 digits. // Do not continue iteration past this point. while(digits < 9 && n > digits * (mx - mn)) { n -= digits * (mx - mn); mn *= 10; mx *= 10; digits += 1; } // Calculate the number of skipped numbers before n is too small to have enough // digits for a number in the [mn, mx] range. int n_skipped_nums = (n - 1) / digits; // Subtract the digits of all the skipped numbers. n -= digits * n_skipped_nums; // Calculate the next number. N is only big enough to index into // this number now. int num = mn + n_skipped_nums; // Return the n-th most sigificant digit. int r = digits - n; while(r-- > 0) num /= 10; return num % 10; } }; #include "io_ConcatenatedStream_TestClass.h" #include #include "StreamTestUtil.h" #include #include void io_ConcatenatedStream_TestClass::runAllTests(void) { fmt::print("[tc::io::ConcatenatedStream] START\n"); test_DefaultConstructor(); test_CreateConstructor_ThrowsOnBadInput(); test_CreateConstructor_SetsCorrectStreamState(); test_setLength_ThrowsOnUse(); test_read_ThrowsOnUnsupported(); test_write_ThrowsOnUnsupported(); test_seek_ThrowsOnUnsupported(); test_seek_SeeksToBeginOnNegativeSeek(); test_seek_SeeksToEndOnTooLargeSeek(); test_seek_CanFindCorrectStreamForSeek(); test_read_CanReadFromSingleStream(); test_read_CanReadFromMultipleStreamWithSeekSupport(); test_read_CanReadFromMultipleStreamWithNoSeekSupport(); test_read_ReadFromMultiStream_NoSeekSupport_ThrowsOnSeekRequired(); test_write_CanWriteFromSingleStream(); test_write_CanWriteFromMultipleStreamWithSeekSupport(); test_write_CanWriteFromMultipleStreamWithNoSeekSupport(); test_write_WriteFromMultiStream_NoSeekSupport_ThrowsOnSeekRequired(); test_MoveOperator_MoveDisposedToDisposed(); test_MoveOperator_MoveInitializedToDisposed(); test_MoveOperator_MoveDisposedToInitialized(); test_MoveOperator_MoveInitializedToInitialized(); test_MoveConstructor_MoveDisposed(); test_MoveConstructor_MoveInitialized(); fmt::print("[tc::io::ConcatenatedStream] END\n"); } void io_ConcatenatedStream_TestClass::test_DefaultConstructor() { fmt::print("[tc::io::ConcatenatedStream] test_DefaultConstructor : "); try { tc::io::ConcatenatedStream stream = tc::io::ConcatenatedStream(); // test state of stream StreamTestUtil::constructor_TestHelper(stream, 0, 0, false, false, false); try { stream.read(nullptr, 0); throw tc::Exception(".read() failed to throw tc::ObjectDisposedException when class was not initilaized."); } catch (const tc::ObjectDisposedException&) { // do nothing } try { stream.write(nullptr, 0); throw tc::Exception(".write() failed to throw tc::ObjectDisposedException when class was not initilaized."); } catch (const tc::ObjectDisposedException&) { // do nothing } try { stream.seek(0, tc::io::SeekOrigin::Begin); throw tc::Exception(".seek() failed to throw tc::ObjectDisposedException when class was not initilaized."); } catch (const tc::ObjectDisposedException&) { // do nothing } try { stream.setLength(0); throw tc::Exception(".setLength() failed to throw tc::ObjectDisposedException when class was not initilaized."); } catch (const tc::ObjectDisposedException&) { // do nothing } try { stream.flush(); throw tc::Exception(".flush() failed to throw tc::ObjectDisposedException when class was not initilaized."); } catch (const tc::ObjectDisposedException&) { // do nothing } fmt::print("PASS\n"); } catch (const tc::Exception& e) { fmt::print("FAIL ({:s})\n", e.error()); } catch (const std::exception& e) { fmt::print("FAIL (unhandled exception) ({})\n", e.what()); } } void io_ConcatenatedStream_TestClass::test_CreateConstructor_ThrowsOnBadInput() { fmt::print("[tc::io::ConcatenatedStream] test_CreateConstructor_ThrowsOnBadInput : "); try { try { std::vector> streams { }; tc::io::ConcatenatedStream stream = tc::io::ConcatenatedStream(streams); throw tc::Exception(".ctor() did not throw tc::NotSupportedException where there were no input streams"); } catch (tc::NotSupportedException&) { // do nothing } try { std::vector> streams { nullptr, nullptr, nullptr }; tc::io::ConcatenatedStream stream = tc::io::ConcatenatedStream(streams); throw tc::Exception(".ctor() did not throw tc::NotSupportedException where there were null input streams"); } catch (tc::NotSupportedException&) { // do nothing } try { std::vector> streams { std::make_shared(StreamTestUtil::DummyStreamBase(0x0)), std::make_shared(StreamTestUtil::DummyStreamBase(0x0)), std::make_shared(StreamTestUtil::DummyStreamBase(0x0)) }; tc::io::ConcatenatedStream stream = tc::io::ConcatenatedStream(streams); throw tc::Exception(".ctor() did not throw tc::NotSupportedException where there total length of input streams was 0."); } catch (tc::NotSupportedException&) { // do nothing } try { std::vector> streams { std::make_shared(StreamTestUtil::DummyStreamBase(0x100, false, true, true, false, false)), // canRead=false, canWrite=true, canSeek=true, ... std::make_shared(StreamTestUtil::DummyStreamBase(0x100, true, false, true, false, false)), // canRead=true, canWrite=false, canSeek=true, ... std::make_shared(StreamTestUtil::DummyStreamBase(0x100, true, true, true, false, false)) // canRead=true, canWrite=true, canSeek=true, ... }; tc::io::ConcatenatedStream stream = tc::io::ConcatenatedStream(streams); throw tc::Exception(".ctor() did not throw tc::NotSupportedException where the input streams did not all support atleast either read or write."); } catch (tc::NotSupportedException&) { // do nothing } fmt::print("PASS\n"); } catch (const tc::Exception& e) { fmt::print("FAIL ({:s})\n", e.error()); } catch (const std::exception& e) { fmt::print("FAIL (unhandled exception) ({})\n", e.what()); } } void io_ConcatenatedStream_TestClass::test_CreateConstructor_SetsCorrectStreamState() { fmt::print("[tc::io::ConcatenatedStream] test_CreateConstructor_SetsCorrectStreamState : "); try { // test 1) (all input streams, length=0x100, canRead=true, canWrite=false, canSeek=false) try { std::vector> streams { std::make_shared(StreamTestUtil::DummyStreamBase(0x100, true, false, false, false, false)), std::make_shared(StreamTestUtil::DummyStreamBase(0x100, true, false, false, false, false)), std::make_shared(StreamTestUtil::DummyStreamBase(0x100, true, false, false, false, false)) }; tc::io::ConcatenatedStream stream = tc::io::ConcatenatedStream(streams); StreamTestUtil::constructor_TestHelper(stream, 0x300, 0, true, false, false); } catch (const tc::Exception& e) { throw tc::Exception(fmt::format("Test 1 Failed: {}", e.error())); } // test 2) (all input streams, length=0x100, canRead=true, canWrite=mixed, canSeek=false) try { std::vector> streams { std::make_shared(StreamTestUtil::DummyStreamBase(0x100, true, false, false, false, false)), std::make_shared(StreamTestUtil::DummyStreamBase(0x100, true, true, false, false, false)), std::make_shared(StreamTestUtil::DummyStreamBase(0x100, true, false, false, false, false)) }; tc::io::ConcatenatedStream stream = tc::io::ConcatenatedStream(streams); StreamTestUtil::constructor_TestHelper(stream, 0x300, 0, true, false, false); } catch (const tc::Exception& e) { throw tc::Exception(fmt::format("Test 2 Failed: {}", e.error())); } // test 3) (all input streams, length=0x100, canRead=true, canWrite=true, canSeek=false) try { std::vector> streams { std::make_shared(StreamTestUtil::DummyStreamBase(0x100, true, true, false, false, false)), std::make_shared(StreamTestUtil::DummyStreamBase(0x100, true, true, false, false, false)), std::make_shared(StreamTestUtil::DummyStreamBase(0x100, true, true, false, false, false)) }; tc::io::ConcatenatedStream stream = tc::io::ConcatenatedStream(streams); StreamTestUtil::constructor_TestHelper(stream, 0x300, 0, true, true, false); } catch (const tc::Exception& e) { throw tc::Exception(fmt::format("Test 3 Failed: {}", e.error())); } // test 4) (all input streams, length=0x100, canRead=true, canWrite=true, canSeek=mixed) try { std::vector> streams { std::make_shared(StreamTestUtil::DummyStreamBase(0x100, true, true, true, false, false)), std::make_shared(StreamTestUtil::DummyStreamBase(0x100, true, true, false, false, false)), std::make_shared(StreamTestUtil::DummyStreamBase(0x100, true, true, false, false, false)) }; tc::io::ConcatenatedStream stream = tc::io::ConcatenatedStream(streams); StreamTestUtil::constructor_TestHelper(stream, 0x300, 0, true, true, false); } catch (const tc::Exception& e) { throw tc::Exception(fmt::format("Test 4 Failed: {}", e.error())); } // test 5) (all input streams, length=0x100, canRead=true, canWrite=true, canSeek=true) try { std::vector> streams { std::make_shared(StreamTestUtil::DummyStreamBase(0x100, true, true, true, false, false)), std::make_shared(StreamTestUtil::DummyStreamBase(0x100, true, true, true, false, false)), std::make_shared(StreamTestUtil::DummyStreamBase(0x100, true, true, true, false, false)) }; tc::io::ConcatenatedStream stream = tc::io::ConcatenatedStream(streams); StreamTestUtil::constructor_TestHelper(stream, 0x300, 0, true, true, true); } catch (const tc::Exception& e) { throw tc::Exception(fmt::format("Test 5 Failed: {}", e.error())); } // test 6) (all input streams, length=0x100, canRead=mixed, canWrite=true, canSeek=true) try { std::vector> streams { std::make_shared(StreamTestUtil::DummyStreamBase(0x100, true, true, true, false, false)), std::make_shared(StreamTestUtil::DummyStreamBase(0x100, false, true, true, false, false)), std::make_shared(StreamTestUtil::DummyStreamBase(0x100, true, true, true, false, false)) }; tc::io::ConcatenatedStream stream = tc::io::ConcatenatedStream(streams); StreamTestUtil::constructor_TestHelper(stream, 0x300, 0, false, true, true); } catch (const tc::Exception& e) { throw tc::Exception(fmt::format("Test 6 Failed: {}", e.error())); } // test 7) (all input streams, length=0x100, canRead=false, canWrite=true, canSeek=true) try { std::vector> streams { std::make_shared(StreamTestUtil::DummyStreamBase(0x100, false, true, true, false, false)), std::make_shared(StreamTestUtil::DummyStreamBase(0x100, false, true, true, false, false)), std::make_shared(StreamTestUtil::DummyStreamBase(0x100, false, true, true, false, false)) }; tc::io::ConcatenatedStream stream = tc::io::ConcatenatedStream(streams); StreamTestUtil::constructor_TestHelper(stream, 0x300, 0, false, true, true); } catch (const tc::Exception& e) { throw tc::Exception(fmt::format("Test 7 Failed: {}", e.error())); } // test 8) (all input streams, length=0x100, canRead=false, canWrite=true, canSeek=mixed) try { std::vector> streams { std::make_shared(StreamTestUtil::DummyStreamBase(0x100, false, true, false, false, false)), std::make_shared(StreamTestUtil::DummyStreamBase(0x100, false, true, true, false, false)), std::make_shared(StreamTestUtil::DummyStreamBase(0x100, false, true, true, false, false)) }; tc::io::ConcatenatedStream stream = tc::io::ConcatenatedStream(streams); StreamTestUtil::constructor_TestHelper(stream, 0x300, 0, false, true, false); } catch (const tc::Exception& e) { throw tc::Exception(fmt::format("Test 8 Failed: {}", e.error())); } // test 9) (all input streams, length=0x100, canRead=false, canWrite=true, canSeek=false) try { std::vector> streams { std::make_shared(StreamTestUtil::DummyStreamBase(0x100, false, true, false, false, false)), std::make_shared(StreamTestUtil::DummyStreamBase(0x100, false, true, false, false, false)), std::make_shared(StreamTestUtil::DummyStreamBase(0x100, false, true, false, false, false)) }; tc::io::ConcatenatedStream stream = tc::io::ConcatenatedStream(streams); StreamTestUtil::constructor_TestHelper(stream, 0x300, 0, false, true, false); } catch (const tc::Exception& e) { throw tc::Exception(fmt::format("Test 9 Failed: {}", e.error())); } // test 10) (all input streams, length=0x100, canRead=true, canWrite=true, canSeek=true) & one empty stream with only read try { std::vector> streams { std::make_shared(StreamTestUtil::DummyStreamBase(0x100, true, true, true, false, false)), std::make_shared(StreamTestUtil::DummyStreamBase(0x100, true, true, true, false, false)), std::make_shared(StreamTestUtil::DummyStreamBase(0x000, true, false, false, false, false)), // this should be skipped because it has no size std::make_shared(StreamTestUtil::DummyStreamBase(0x100, true, true, true, false, false)), }; tc::io::ConcatenatedStream stream = tc::io::ConcatenatedStream(streams); StreamTestUtil::constructor_TestHelper(stream, 0x300, 0, true, true, true); } catch (const tc::Exception& e) { throw tc::Exception(fmt::format("Test 10 Failed: {}", e.error())); } // test 11) (all input streams, length=0x100, canRead=true, canWrite=true, canSeek=true) & one populated stream with only no read/write try { std::vector> streams { std::make_shared(StreamTestUtil::DummyStreamBase(0x100, true, true, true, false, false)), std::make_shared(StreamTestUtil::DummyStreamBase(0x100, true, true, true, false, false)), std::make_shared(StreamTestUtil::DummyStreamBase(0x100, false, false, false, false, false)), // this should be skipped because it cannot be read or written too std::make_shared(StreamTestUtil::DummyStreamBase(0x100, true, true, true, false, false)), }; tc::io::ConcatenatedStream stream = tc::io::ConcatenatedStream(streams); StreamTestUtil::constructor_TestHelper(stream, 0x300, 0, true, true, true); } catch (const tc::Exception& e) { throw tc::Exception(fmt::format("Test 11 Failed: {}", e.error())); } // test 12) (all input streams, length=0x100, canRead=true, canWrite=true, canSeek=true) & one nullptr stream try { std::vector> streams { std::make_shared(StreamTestUtil::DummyStreamBase(0x100, true, true, true, false, false)), std::make_shared(StreamTestUtil::DummyStreamBase(0x100, true, true, true, false, false)), nullptr, // this should be skipped because it is null std::make_shared(StreamTestUtil::DummyStreamBase(0x100, true, true, true, false, false)), }; tc::io::ConcatenatedStream stream = tc::io::ConcatenatedStream(streams); StreamTestUtil::constructor_TestHelper(stream, 0x300, 0, true, true, true); } catch (const tc::Exception& e) { throw tc::Exception(fmt::format("Test 12 Failed: {}", e.error())); } fmt::print("PASS\n"); } catch (const tc::Exception& e) { fmt::print("FAIL ({:s})\n", e.error()); } catch (const std::exception& e) { fmt::print("FAIL (unhandled exception) ({})\n", e.what()); } } void io_ConcatenatedStream_TestClass::test_setLength_ThrowsOnUse() { fmt::print("[tc::io::ConcatenatedStream] test_setLength_ThrowsOnUse : "); try { std::vector> streams { std::make_shared(StreamTestUtil::DummyStreamBase(0x100, true, true, true, false, false)), std::make_shared(StreamTestUtil::DummyStreamBase(0x100, true, true, true, false, false)), std::make_shared(StreamTestUtil::DummyStreamBase(0x100, true, true, true, false, false)) }; tc::io::ConcatenatedStream stream = tc::io::ConcatenatedStream(streams); try { stream.setLength(0); throw tc::Exception(".setLength() did not throw tc::NotImplementedException when called from an initalized class."); } catch (const tc::NotImplementedException&) { // do nothing } fmt::print("PASS\n"); } catch (const tc::Exception& e) { fmt::print("FAIL ({:s})\n", e.error()); } catch (const std::exception& e) { fmt::print("FAIL (unhandled exception) ({})\n", e.what()); } } void io_ConcatenatedStream_TestClass::test_read_ThrowsOnUnsupported() { fmt::print("[tc::io::ConcatenatedStream] test_read_ThrowsOnUnsupported : "); try { std::vector> streams { std::make_shared(StreamTestUtil::DummyStreamBase(0x100, false, true, true, false, false)), std::make_shared(StreamTestUtil::DummyStreamBase(0x100, false, true, true, false, false)), std::make_shared(StreamTestUtil::DummyStreamBase(0x100, false, true, true, false, false)) }; tc::io::ConcatenatedStream stream = tc::io::ConcatenatedStream(streams); try { stream.read(nullptr, 0); throw tc::Exception(".read() did not throw tc::NotSupportedException when canRead() == false."); } catch (const tc::NotSupportedException&) { // do nothing } fmt::print("PASS\n"); } catch (const tc::Exception& e) { fmt::print("FAIL ({:s})\n", e.error()); } catch (const std::exception& e) { fmt::print("FAIL (unhandled exception) ({})\n", e.what()); } } void io_ConcatenatedStream_TestClass::test_write_ThrowsOnUnsupported() { fmt::print("[tc::io::ConcatenatedStream] test_write_ThrowsOnUnsupported : "); try { std::vector> streams { std::make_shared(StreamTestUtil::DummyStreamBase(0x100, true, false, true, false, false)), std::make_shared(StreamTestUtil::DummyStreamBase(0x100, true, false, true, false, false)), std::make_shared(StreamTestUtil::DummyStreamBase(0x100, true, false, true, false, false)) }; tc::io::ConcatenatedStream stream = tc::io::ConcatenatedStream(streams); try { stream.write(nullptr, 0); throw tc::Exception(".write() did not throw tc::NotSupportedException when canWrite() == false."); } catch (const tc::NotSupportedException&) { // do nothing } fmt::print("PASS\n"); } catch (const tc::Exception& e) { fmt::print("FAIL ({:s})\n", e.error()); } catch (const std::exception& e) { fmt::print("FAIL (unhandled exception) ({})\n", e.what()); } } void io_ConcatenatedStream_TestClass::test_seek_ThrowsOnUnsupported() { fmt::print("[tc::io::ConcatenatedStream] test_seek_ThrowsOnUnsupported : "); try { std::vector> streams { std::make_shared(StreamTestUtil::DummyStreamBase(0x100, true, true, false, false, false)), std::make_shared(StreamTestUtil::DummyStreamBase(0x100, true, true, false, false, false)), std::make_shared(StreamTestUtil::DummyStreamBase(0x100, true, true, false, false, false)) }; tc::io::ConcatenatedStream stream = tc::io::ConcatenatedStream(streams); try { stream.seek(0, tc::io::SeekOrigin::Begin); throw tc::Exception(".seek() did not throw tc::NotSupportedException when canSeek() == false."); } catch (const tc::NotSupportedException&) { // do nothing } fmt::print("PASS\n"); } catch (const tc::Exception& e) { fmt::print("FAIL ({:s})\n", e.error()); } catch (const std::exception& e) { fmt::print("FAIL (unhandled exception) ({})\n", e.what()); } } void io_ConcatenatedStream_TestClass::test_seek_SeeksToBeginOnNegativeSeek() { fmt::print("[tc::io::ConcatenatedStream] test_seek_SeeksToBeginOnNegativeSeek : "); try { class ValidateSeekParamDummyStream : public StreamTestUtil::DummyStreamBase { public: ValidateSeekParamDummyStream(int64_t seek_offset, tc::io::SeekOrigin seek_origin) : DummyStreamBase(0x100, true, true, true, false, false), mExpectedSeekOffset(seek_offset), mExpectedSeekOrigin(seek_origin) {} int64_t seek(int64_t offset, tc::io::SeekOrigin origin) { if (offset != mExpectedSeekOffset) { throw tc::Exception(fmt::format("offset passed to seek() was 0x{:x} (expected 0x{:x}", offset, mExpectedSeekOffset)); } if (origin != mExpectedSeekOrigin) { std::string origin_str; switch (origin) { case tc::io::SeekOrigin::Begin: origin_str = "SeekOrigin::Begin"; break; case tc::io::SeekOrigin::Current: origin_str = "SeekOrigin::Current"; break; case tc::io::SeekOrigin::End: origin_str = "SeekOrigin::End"; break; } std::string expected_origin_str; switch (mExpectedSeekOrigin) { case tc::io::SeekOrigin::Begin: expected_origin_str = "SeekOrigin::Begin"; break; case tc::io::SeekOrigin::Current: expected_origin_str = "SeekOrigin::Current"; break; case tc::io::SeekOrigin::End: expected_origin_str = "SeekOrigin::End"; break; } throw tc::Exception(fmt::format("origin passed to seek() was {:s} (expected {:s}", origin_str, expected_origin_str)); } return DummyStreamBase::seek(offset, origin); } private: int64_t mExpectedSeekOffset; tc::io::SeekOrigin mExpectedSeekOrigin; }; std::vector> streams { std::make_shared(ValidateSeekParamDummyStream(0, tc::io::SeekOrigin::Begin)), std::make_shared(StreamTestUtil::DummyStreamBase(0x100, true, true, true, false, false)), std::make_shared(StreamTestUtil::DummyStreamBase(0x100, true, true, true, false, false)) }; tc::io::ConcatenatedStream stream = tc::io::ConcatenatedStream(streams); struct Test { int64_t seek_pos, exp_seek_res; }; std::vector tests { {0x0, 0x0}, {-1, 0x0}, {-2, 0x0}, {-3, 0x0}, {-10, 0x0}, {-1000, 0x0}, {-20000, 0x0}, }; for (auto test = tests.begin(); test != tests.end(); test++) { int64_t seek_res = stream.seek(test->seek_pos, tc::io::SeekOrigin::Begin); if (seek_res != test->exp_seek_res) { throw tc::Exception(fmt::format(".seek({}, tc::io::SeekOrigin::Begin) returned {} (expected {})", test->seek_pos, seek_res, test->exp_seek_res)); } } fmt::print("PASS\n"); } catch (const tc::Exception& e) { fmt::print("FAIL ({:s})\n", e.error()); } catch (const std::exception& e) { fmt::print("FAIL (unhandled exception) ({})\n", e.what()); } } void io_ConcatenatedStream_TestClass::test_seek_SeeksToEndOnTooLargeSeek() { fmt::print("[tc::io::ConcatenatedStream] test_seek_SeeksToEndOnTooLargeSeek : "); try { class ValidateSeekParamDummyStream : public StreamTestUtil::DummyStreamBase { public: ValidateSeekParamDummyStream(int64_t seek_offset, tc::io::SeekOrigin seek_origin) : DummyStreamBase(0x100, true, true, true, false, false), mExpectedSeekOffset(seek_offset), mExpectedSeekOrigin(seek_origin) {} int64_t seek(int64_t offset, tc::io::SeekOrigin origin) { if (offset != mExpectedSeekOffset) { throw tc::Exception(fmt::format("offset passed to seek() was 0x{:x} (expected 0x{:x}", offset, mExpectedSeekOffset)); } if (origin != mExpectedSeekOrigin) { std::string origin_str; switch (origin) { case tc::io::SeekOrigin::Begin: origin_str = "SeekOrigin::Begin"; break; case tc::io::SeekOrigin::Current: origin_str = "SeekOrigin::Current"; break; case tc::io::SeekOrigin::End: origin_str = "SeekOrigin::End"; break; } std::string expected_origin_str; switch (mExpectedSeekOrigin) { case tc::io::SeekOrigin::Begin: expected_origin_str = "SeekOrigin::Begin"; break; case tc::io::SeekOrigin::Current: expected_origin_str = "SeekOrigin::Current"; break; case tc::io::SeekOrigin::End: expected_origin_str = "SeekOrigin::End"; break; } throw tc::Exception(fmt::format("origin passed to seek() was {:s} (expected {:s}", origin_str, expected_origin_str)); } return DummyStreamBase::seek(offset, origin); } private: int64_t mExpectedSeekOffset; tc::io::SeekOrigin mExpectedSeekOrigin; }; std::vector> streams { std::make_shared(StreamTestUtil::DummyStreamBase(0x100, true, true, true, false, false)), std::make_shared(StreamTestUtil::DummyStreamBase(0x100, true, true, true, false, false)), std::make_shared(ValidateSeekParamDummyStream(0, tc::io::SeekOrigin::End)) }; tc::io::ConcatenatedStream stream = tc::io::ConcatenatedStream(streams); struct Test { int64_t seek_pos, exp_seek_res; }; std::vector tests { {0x300, 0x300}, {0x301, 0x300}, {0x302, 0x300}, {0x310, 0x300}, {0x400, 0x300}, {0x1000, 0x300}, {0x20000, 0x300}, }; for (auto test = tests.begin(); test != tests.end(); test++) { int64_t seek_res = stream.seek(test->seek_pos, tc::io::SeekOrigin::Begin); if (seek_res != test->exp_seek_res) { throw tc::Exception(fmt::format(".seek({}, tc::io::SeekOrigin::Begin) returned {} (expected {})", test->seek_pos, seek_res, test->exp_seek_res)); } } fmt::print("PASS\n"); } catch (const tc::Exception& e) { fmt::print("FAIL ({:s})\n", e.error()); } catch (const std::exception& e) { fmt::print("FAIL (unhandled exception) ({})\n", e.what()); } } void io_ConcatenatedStream_TestClass::test_seek_CanFindCorrectStreamForSeek() { fmt::print("[tc::io::ConcatenatedStream] test_seek_CanFindCorrectStreamForSeek : "); try { struct SeekReport { int64_t seek_pos; size_t stream_id; }; class ReportsSeekPosParamDummyStream : public StreamTestUtil::DummyStreamBase { public: ReportsSeekPosParamDummyStream(SeekReport& seek_resport, size_t stream_id) : DummyStreamBase(0x100, true, true, true, false, false), mSeekReport(seek_resport), mStreamId(stream_id) {} int64_t seek(int64_t offset, tc::io::SeekOrigin origin) { mSeekReport.seek_pos = DummyStreamBase::seek(offset, origin); mSeekReport.stream_id = mStreamId; return mSeekReport.seek_pos; } private: SeekReport& mSeekReport; size_t mStreamId; }; SeekReport seek_report; std::vector> streams { std::make_shared(ReportsSeekPosParamDummyStream(seek_report, 0)), // 0x000 - 0x0ff std::make_shared(ReportsSeekPosParamDummyStream(seek_report, 1)), // 0x100 - 0x1ff std::make_shared(ReportsSeekPosParamDummyStream(seek_report, 2)), // 0x200 - 0x2ff std::make_shared(ReportsSeekPosParamDummyStream(seek_report, 3)), // 0x300 - 0x3ff std::make_shared(ReportsSeekPosParamDummyStream(seek_report, 4)), // 0x400 - 0x4ff std::make_shared(ReportsSeekPosParamDummyStream(seek_report, 5)), // 0x500 - 0x5ff std::make_shared(ReportsSeekPosParamDummyStream(seek_report, 6)), // 0x600 - 0x6ff std::make_shared(ReportsSeekPosParamDummyStream(seek_report, 7)), // 0x700 - 0x7ff }; tc::io::ConcatenatedStream stream = tc::io::ConcatenatedStream(streams); struct Test { int64_t seek_pos; int64_t exp_seek_res; SeekReport exp_seek_report; }; std::vector tests { {0x0, 0x0, {0x0, 0}}, {0x20, 0x20, {0x20, 0}}, {0xff, 0xff, {0xff, 0}}, {0x100, 0x100, {0x0, 1}}, {0x101, 0x101, {0x1, 1}}, {0x1ff, 0x1ff, {0xff, 1}}, {0x200, 0x200, {0x0, 2}}, {0x600, 0x600, {0x0, 6}}, {0x378, 0x378, {0x78, 3}}, {0x7ff, 0x7ff, {0xff, 7}}, {0x8, 0x8, {0x8, 0}}, // prior of stream case {-1, 0x0, {0x0, 0}}, {-120, 0x0, {0x0, 0}}, // end of stream case {0x800, 0x800, {0x100, 7}}, {0x1000, 0x800, {0x100, 7}}, }; for (auto test = tests.begin(); test != tests.end(); test++) { int64_t seek_res = stream.seek(test->seek_pos, tc::io::SeekOrigin::Begin); if (seek_res != test->exp_seek_res) { throw tc::Exception(fmt::format(".seek({}) returned {} (expected {})", test->seek_pos, seek_res, test->exp_seek_res)); } if (seek_report.seek_pos != test->exp_seek_report.seek_pos || seek_report.stream_id != test->exp_seek_report.stream_id) { throw tc::Exception(fmt::format(".seek({}) triggered .seek({}) in stream {} (expected .seek({}) in stream {})", test->seek_pos, test->exp_seek_report.seek_pos, test->exp_seek_report.stream_id, seek_report.seek_pos, seek_report.stream_id)); } } fmt::print("PASS\n"); } catch (const tc::Exception& e) { fmt::print("FAIL ({:s})\n", e.error()); } catch (const std::exception& e) { fmt::print("FAIL (unhandled exception) ({})\n", e.what()); } } void io_ConcatenatedStream_TestClass::test_read_CanReadFromSingleStream() { fmt::print("[tc::io::ConcatenatedStream] test_read_CanReadFromSingleStream : "); class ReportDummyStream : public StreamTestUtil::DummyStreamBase { public: struct SeekReport { int64_t seek_offset; size_t stream_id; bool operator==(const SeekReport& other) const { return seek_offset == other.seek_offset \ && stream_id == other.stream_id; } }; struct ReadReport { const byte_t* read_ptr; size_t read_count; size_t stream_id; bool operator==(const ReadReport& other) const { return read_ptr == other.read_ptr \ && read_count == other.read_count \ && stream_id == other.stream_id; } }; ReportDummyStream(std::vector& read_report, std::vector& seek_report, size_t stream_id) : DummyStreamBase(0x100, true, true, true, false, false), mReadReport(read_report), mSeekReport(seek_report), mStreamId(stream_id) {} size_t read(byte_t* ptr, size_t count) { mReadReport.push_back({ptr, count, mStreamId}); size_t readable_count = tc::io::IOUtil::getReadableCount(DummyStreamBase::length(), DummyStreamBase::position(), count); // update stream position DummyStreamBase::seek(int64_t(readable_count), tc::io::SeekOrigin::Current); return readable_count; } int64_t seek(int64_t offset, tc::io::SeekOrigin origin) { SeekReport seek_report = {DummyStreamBase::seek(offset, origin), mStreamId}; mSeekReport.push_back(seek_report); return seek_report.seek_offset; } private: std::vector& mReadReport; std::vector& mSeekReport; size_t mStreamId; }; try { // declare report logs std::vector read_report; std::vector seek_report; // create stream list with links to report logs std::vector> streams { std::make_shared(ReportDummyStream(read_report, seek_report, 0)), // 0x000 - 0x0ff std::make_shared(ReportDummyStream(read_report, seek_report, 1)), // 0x100 - 0x1ff std::make_shared(ReportDummyStream(read_report, seek_report, 2)), // 0x200 - 0x2ff std::make_shared(ReportDummyStream(read_report, seek_report, 3)), // 0x300 - 0x3ff std::make_shared(ReportDummyStream(read_report, seek_report, 4)), // 0x400 - 0x4ff std::make_shared(ReportDummyStream(read_report, seek_report, 5)), // 0x500 - 0x5ff std::make_shared(ReportDummyStream(read_report, seek_report, 6)), // 0x600 - 0x6ff std::make_shared(ReportDummyStream(read_report, seek_report, 7)), // 0x700 - 0x7ff }; // create concatenated stream tc::io::ConcatenatedStream stream = tc::io::ConcatenatedStream(streams); // define test struct Test { // test name std::string test_name; // these seeks are done then seek log is cleared std::vector unlogged_seeks; // these seeks are done before reading but will be logged std::vector logged_seeks; // read param byte_t* read_ptr; size_t read_count; // expected log reports std::vector exp_read_report; std::vector exp_seek_report; }; // create tests std::vector tests { {"ReadFromBeginning", {0}, {}, (byte_t*)0x1000, 0x30, {{(byte_t*)0x1000, 0x30, 0}}, {}}, {"ContinueReadingFromBeginning", {}, {}, (byte_t*)0x1000, 0x30, {{(byte_t*)0x1000, 0x30, 0}}, {}}, {"ReadFromSomewhereElseInExistingStream", {0xe0}, {}, (byte_t*)0x1000, 0x20, {{(byte_t*)0x1000, 0x20, 0}}, {}}, }; // run tests for (auto test = tests.begin(); test != tests.end(); test++) { for (auto itr = test->unlogged_seeks.begin(); itr != test->unlogged_seeks.end(); itr++) { stream.seek(*itr, tc::io::SeekOrigin::Begin); } read_report.clear(); seek_report.clear(); for (auto itr = test->logged_seeks.begin(); itr != test->logged_seeks.end(); itr++) { stream.seek(*itr, tc::io::SeekOrigin::Begin); } stream.read(test->read_ptr, test->read_count); if (read_report != test->exp_read_report) { throw tc::Exception(fmt::format("Test \"{}\" Failed: .read() issued to base streams were not as expected", test->test_name)); } if (seek_report != test->exp_seek_report) { throw tc::Exception(fmt::format("Test \"{}\" Failed: .seek() issued to base streams were not as expected", test->test_name)); } } fmt::print("PASS\n"); } catch (const tc::Exception& e) { fmt::print("FAIL ({:s})\n", e.error()); } catch (const std::exception& e) { fmt::print("FAIL (unhandled exception) ({})\n", e.what()); } } void io_ConcatenatedStream_TestClass::test_read_CanReadFromMultipleStreamWithSeekSupport() { fmt::print("[tc::io::ConcatenatedStream] test_read_CanReadFromMultipleStreamWithSeekSupport : "); class ReportDummyStream : public StreamTestUtil::DummyStreamBase { public: struct SeekReport { int64_t seek_offset; size_t stream_id; bool operator==(const SeekReport& other) const { return seek_offset == other.seek_offset \ && stream_id == other.stream_id; } }; struct ReadReport { const byte_t* read_ptr; size_t read_count; size_t stream_id; bool operator==(const ReadReport& other) const { return read_ptr == other.read_ptr \ && read_count == other.read_count \ && stream_id == other.stream_id; } }; ReportDummyStream(std::vector& read_report, std::vector& seek_report, size_t stream_id) : DummyStreamBase(0x100, true, true, true, false, false), mReadReport(read_report), mSeekReport(seek_report), mStreamId(stream_id) {} size_t read(byte_t* ptr, size_t count) { mReadReport.push_back({ptr, count, mStreamId}); size_t readable_count = tc::io::IOUtil::getReadableCount(DummyStreamBase::length(), DummyStreamBase::position(), count); // update stream position DummyStreamBase::seek(int64_t(readable_count), tc::io::SeekOrigin::Current); return readable_count; } int64_t seek(int64_t offset, tc::io::SeekOrigin origin) { SeekReport seek_report = {DummyStreamBase::seek(offset, origin), mStreamId}; mSeekReport.push_back(seek_report); return seek_report.seek_offset; } private: std::vector& mReadReport; std::vector& mSeekReport; size_t mStreamId; }; try { // declare report logs std::vector read_report; std::vector seek_report; // create stream list with links to report logs std::vector> streams { std::make_shared(ReportDummyStream(read_report, seek_report, 0)), // 0x000 - 0x0ff std::make_shared(ReportDummyStream(read_report, seek_report, 1)), // 0x100 - 0x1ff std::make_shared(ReportDummyStream(read_report, seek_report, 2)), // 0x200 - 0x2ff std::make_shared(ReportDummyStream(read_report, seek_report, 3)), // 0x300 - 0x3ff std::make_shared(ReportDummyStream(read_report, seek_report, 4)), // 0x400 - 0x4ff std::make_shared(ReportDummyStream(read_report, seek_report, 5)), // 0x500 - 0x5ff std::make_shared(ReportDummyStream(read_report, seek_report, 6)), // 0x600 - 0x6ff std::make_shared(ReportDummyStream(read_report, seek_report, 7)), // 0x700 - 0x7ff }; // create concatenated stream tc::io::ConcatenatedStream stream = tc::io::ConcatenatedStream(streams); // define test struct Test { // test name std::string test_name; // these seeks are done then seek log is cleared std::vector unlogged_seeks; // these seeks are done before reading but will be logged std::vector logged_seeks; // read param byte_t* read_ptr; size_t read_count; // expected log reports std::vector exp_read_report; std::vector exp_seek_report; }; // create tests std::vector tests { {"ReadAllOfStream 0-7 (stream 0x0 positions)", {0x000, 0x100, 0x200, 0x300, 0x400, 0x500, 0x600, 0x700, 0x000}, {}, (byte_t*)0x1000, 0x800, {{(byte_t*)0x1000, 0x100, 0}, {(byte_t*)0x1100, 0x100, 1}, {(byte_t*)0x1200, 0x100, 2}, {(byte_t*)0x1300, 0x100, 3}, {(byte_t*)0x1400, 0x100, 4}, {(byte_t*)0x1500, 0x100, 5}, {(byte_t*)0x1600, 0x100, 6}, {(byte_t*)0x1700, 0x100, 7}}, {}}, {"ReadAllOfStream 0-7 (stream 0x80 positions)", {0x080, 0x180, 0x280, 0x380, 0x480, 0x580, 0x680, 0x780, 0x000}, {}, (byte_t*)0x1000, 0x800, {{(byte_t*)0x1000, 0x100, 0}, {(byte_t*)0x1100, 0x100, 1}, {(byte_t*)0x1200, 0x100, 2}, {(byte_t*)0x1300, 0x100, 3}, {(byte_t*)0x1400, 0x100, 4}, {(byte_t*)0x1500, 0x100, 5}, {(byte_t*)0x1600, 0x100, 6}, {(byte_t*)0x1700, 0x100, 7}}, {{0x0, 1}, {0x0, 2}, {0x0, 3}, {0x0, 4}, {0x0, 5}, {0x0, 6}, {0x0, 7}}}, {"ReadAllOfStream 0-7 (stream 0x00 or 0x80 positions)", {0x080, 0x100, 0x280, 0x300, 0x480, 0x500, 0x680, 0x700, 0x000}, {}, (byte_t*)0x1000, 0x800, {{(byte_t*)0x1000, 0x100, 0}, {(byte_t*)0x1100, 0x100, 1}, {(byte_t*)0x1200, 0x100, 2}, {(byte_t*)0x1300, 0x100, 3}, {(byte_t*)0x1400, 0x100, 4}, {(byte_t*)0x1500, 0x100, 5}, {(byte_t*)0x1600, 0x100, 6}, {(byte_t*)0x1700, 0x100, 7}}, {{0x0, 2}, {0x0, 4}, {0x0, 6}}}, {"ReadAllOfStream 3-6 (stream 0x0 positions)", {0x000, 0x100, 0x200, 0x300, 0x400, 0x500, 0x600, 0x700, 0x300}, {}, (byte_t*)0x1000, 0x400, {{(byte_t*)0x1000, 0x100, 3}, {(byte_t*)0x1100, 0x100, 4}, {(byte_t*)0x1200, 0x100, 5}, {(byte_t*)0x1300, 0x100, 6}}, {}}, {"ReadAllOfStream 3-6 (stream 0x80 positions)", {0x080, 0x180, 0x280, 0x380, 0x480, 0x580, 0x680, 0x780, 0x300}, {}, (byte_t*)0x1000, 0x400, {{(byte_t*)0x1000, 0x100, 3}, {(byte_t*)0x1100, 0x100, 4}, {(byte_t*)0x1200, 0x100, 5}, {(byte_t*)0x1300, 0x100, 6}}, {{0x0, 4}, {0x0, 5}, {0x0, 6}}}, {"ReadStream (partial)3,4-5,(partial)6 (stream 0x0 positions)", {0x000, 0x100, 0x200, 0x300, 0x400, 0x500, 0x600, 0x700, 0x350}, {}, (byte_t*)0x1000, 0x300, {{(byte_t*)0x1000, 0xB0, 3}, {(byte_t*)0x10B0, 0x100, 4}, {(byte_t*)0x11B0, 0x100, 5}, {(byte_t*)0x12B0, 0x50, 6}}, {}}, {"ReadStream (partial)3,4-5,(partial)6 (stream 0x80 positions)", {0x080, 0x180, 0x280, 0x380, 0x480, 0x580, 0x680, 0x780, 0x350}, {}, (byte_t*)0x1000, 0x300, {{(byte_t*)0x1000, 0xB0, 3}, {(byte_t*)0x10B0, 0x100, 4}, {(byte_t*)0x11B0, 0x100, 5}, {(byte_t*)0x12B0, 0x50, 6}}, {{0x0, 4}, {0x0, 5}, {0x0, 6}}}, }; // run tests for (auto test = tests.begin(); test != tests.end(); test++) { for (auto itr = test->unlogged_seeks.begin(); itr != test->unlogged_seeks.end(); itr++) { stream.seek(*itr, tc::io::SeekOrigin::Begin); } read_report.clear(); seek_report.clear(); for (auto itr = test->logged_seeks.begin(); itr != test->logged_seeks.end(); itr++) { stream.seek(*itr, tc::io::SeekOrigin::Begin); } stream.read(test->read_ptr, test->read_count); if (read_report != test->exp_read_report) { throw tc::Exception(fmt::format("Test \"{}\" Failed: .read() issued to base streams were not as expected", test->test_name)); } if (seek_report != test->exp_seek_report) { throw tc::Exception(fmt::format("Test \"{}\" Failed: .seek() issued to base streams were not as expected", test->test_name)); } } fmt::print("PASS\n"); } catch (const tc::Exception& e) { fmt::print("FAIL ({:s})\n", e.error()); } catch (const std::exception& e) { fmt::print("FAIL (unhandled exception) ({})\n", e.what()); } } void io_ConcatenatedStream_TestClass::test_read_CanReadFromMultipleStreamWithNoSeekSupport() { fmt::print("[tc::io::ConcatenatedStream] test_read_CanReadFromMultipleStreamWithNoSeekSupport : "); class ReportDummyStream : public StreamTestUtil::DummyStreamBase { public: struct SeekReport { int64_t seek_offset; size_t stream_id; bool operator==(const SeekReport& other) const { return seek_offset == other.seek_offset \ && stream_id == other.stream_id; } }; struct ReadReport { const byte_t* read_ptr; size_t read_count; size_t stream_id; bool operator==(const ReadReport& other) const { return read_ptr == other.read_ptr \ && read_count == other.read_count \ && stream_id == other.stream_id; } }; ReportDummyStream(std::vector& read_report, std::vector& seek_report, size_t stream_id) : DummyStreamBase(0x100, true, true, false, false, false), mReadReport(read_report), mSeekReport(seek_report), mStreamId(stream_id) {} size_t read(byte_t* ptr, size_t count) { mReadReport.push_back({ptr, count, mStreamId}); size_t readable_count = tc::io::IOUtil::getReadableCount(DummyStreamBase::length(), DummyStreamBase::position(), count); // update stream position DummyStreamBase::seek(int64_t(readable_count), tc::io::SeekOrigin::Current); return readable_count; } int64_t seek(int64_t offset, tc::io::SeekOrigin origin) { SeekReport seek_report = {DummyStreamBase::seek(offset, origin), mStreamId}; mSeekReport.push_back(seek_report); return seek_report.seek_offset; } private: std::vector& mReadReport; std::vector& mSeekReport; size_t mStreamId; }; try { // declare report logs std::vector read_report; std::vector seek_report; // create stream list with links to report logs std::vector> streams { std::make_shared(ReportDummyStream(read_report, seek_report, 0)), // 0x000 - 0x0ff std::make_shared(ReportDummyStream(read_report, seek_report, 1)), // 0x100 - 0x1ff std::make_shared(ReportDummyStream(read_report, seek_report, 2)), // 0x200 - 0x2ff std::make_shared(ReportDummyStream(read_report, seek_report, 3)), // 0x300 - 0x3ff std::make_shared(ReportDummyStream(read_report, seek_report, 4)), // 0x400 - 0x4ff std::make_shared(ReportDummyStream(read_report, seek_report, 5)), // 0x500 - 0x5ff std::make_shared(ReportDummyStream(read_report, seek_report, 6)), // 0x600 - 0x6ff std::make_shared(ReportDummyStream(read_report, seek_report, 7)), // 0x700 - 0x7ff }; // create concatenated stream tc::io::ConcatenatedStream stream = tc::io::ConcatenatedStream(streams); // define test struct Test { // test name std::string test_name; // these seeks are done then seek log is cleared std::vector unlogged_seeks; // these seeks are done before reading but will be logged std::vector logged_seeks; // read param byte_t* read_ptr; size_t read_count; // expected log reports std::vector exp_read_report; std::vector exp_seek_report; }; // create tests std::vector tests { {"ReadStream (partial)0", {}, {}, (byte_t*)0x1000, 0xA0, {{(byte_t*)0x1000, 0xA0, 0}}, {}}, {"ReadStream (partial)0,1-4", {}, {}, (byte_t*)0x1000, 0x460, {{(byte_t*)0x1000, 0x60, 0}, {(byte_t*)0x1060, 0x100, 1}, {(byte_t*)0x1160, 0x100, 2}, {(byte_t*)0x1260, 0x100, 3}, {(byte_t*)0x1360, 0x100, 4}}, {}}, {"ReadStream 5-7", {}, {}, (byte_t*)0x1000, 0x300, {{(byte_t*)0x1000, 0x100, 5}, {(byte_t*)0x1100, 0x100, 6}, {(byte_t*)0x1200, 0x100, 7}}, {}}, }; // run tests for (auto test = tests.begin(); test != tests.end(); test++) { for (auto itr = test->unlogged_seeks.begin(); itr != test->unlogged_seeks.end(); itr++) { stream.seek(*itr, tc::io::SeekOrigin::Begin); } read_report.clear(); seek_report.clear(); for (auto itr = test->logged_seeks.begin(); itr != test->logged_seeks.end(); itr++) { stream.seek(*itr, tc::io::SeekOrigin::Begin); } stream.read(test->read_ptr, test->read_count); if (read_report != test->exp_read_report) { fmt::print("\n"); fmt::print("ReadLog:\n"); for (auto itr = read_report.begin(); itr != read_report.end(); itr++) { fmt::print("ReadReport (ptr: 0x{:x}, count: 0x{:x}, stream: {:d})\n", (size_t)itr->read_ptr, itr->read_count, itr->stream_id); } fmt::print("ExpReadLog:\n"); for (auto itr = test->exp_read_report.begin(); itr != test->exp_read_report.end(); itr++) { fmt::print("ReadReport (ptr: 0x{:x}, count: 0x{:x}, stream: {:d})\n", (size_t)itr->read_ptr, itr->read_count, itr->stream_id); } throw tc::Exception(fmt::format("Test \"{}\" Failed: .read() issued to base streams were not as expected", test->test_name)); } if (seek_report != test->exp_seek_report) { throw tc::Exception(fmt::format("Test \"{}\" Failed: .seek() issued to base streams were not as expected", test->test_name)); } } fmt::print("PASS\n"); } catch (const tc::Exception& e) { fmt::print("FAIL ({:s})\n", e.error()); } catch (const std::exception& e) { fmt::print("FAIL (unhandled exception) ({})\n", e.what()); } } void io_ConcatenatedStream_TestClass::test_read_ReadFromMultiStream_NoSeekSupport_ThrowsOnSeekRequired() { fmt::print("[tc::io::ConcatenatedStream] test_read_ReadFromMultiStream_NoSeekSupport_ThrowsOnSeekRequired : "); class ReportDummyStream : public StreamTestUtil::DummyStreamBase { public: struct SeekReport { int64_t seek_offset; size_t stream_id; bool operator==(const SeekReport& other) const { return seek_offset == other.seek_offset \ && stream_id == other.stream_id; } }; struct ReadReport { const byte_t* read_ptr; size_t read_count; size_t stream_id; bool operator==(const ReadReport& other) const { return read_ptr == other.read_ptr \ && read_count == other.read_count \ && stream_id == other.stream_id; } }; ReportDummyStream(std::vector& read_report, std::vector& seek_report, size_t stream_id) : DummyStreamBase(0x100, 0x80, true, true, false, false, false), // the initial position is 0x80 mReadReport(read_report), mSeekReport(seek_report), mStreamId(stream_id) {} size_t read(byte_t* ptr, size_t count) { mReadReport.push_back({ptr, count, mStreamId}); size_t readable_count = tc::io::IOUtil::getReadableCount(DummyStreamBase::length(), DummyStreamBase::position(), count); // update stream position DummyStreamBase::seek(int64_t(readable_count), tc::io::SeekOrigin::Current); return readable_count; } int64_t seek(int64_t offset, tc::io::SeekOrigin origin) { SeekReport seek_report = {DummyStreamBase::seek(offset, origin), mStreamId}; mSeekReport.push_back(seek_report); return seek_report.seek_offset; } private: std::vector& mReadReport; std::vector& mSeekReport; size_t mStreamId; }; try { // declare report logs std::vector read_report; std::vector seek_report; // create stream list with links to report logs std::vector> streams { std::make_shared(ReportDummyStream(read_report, seek_report, 0)), // 0x000 - 0x0ff std::make_shared(ReportDummyStream(read_report, seek_report, 1)), // 0x100 - 0x1ff std::make_shared(ReportDummyStream(read_report, seek_report, 2)), // 0x200 - 0x2ff std::make_shared(ReportDummyStream(read_report, seek_report, 3)), // 0x300 - 0x3ff std::make_shared(ReportDummyStream(read_report, seek_report, 4)), // 0x400 - 0x4ff std::make_shared(ReportDummyStream(read_report, seek_report, 5)), // 0x500 - 0x5ff std::make_shared(ReportDummyStream(read_report, seek_report, 6)), // 0x600 - 0x6ff std::make_shared(ReportDummyStream(read_report, seek_report, 7)), // 0x700 - 0x7ff }; // create concatenated stream tc::io::ConcatenatedStream stream = tc::io::ConcatenatedStream(streams); try { stream.read((byte_t*)0x1000, 0x200); throw tc::Exception(".read() did not throw tc::io::IOException where stream required seeking to begining but did not support seeking."); } catch (const tc::io::IOException&) { // do nothing } fmt::print("PASS\n"); } catch (const tc::Exception& e) { fmt::print("FAIL ({:s})\n", e.error()); } catch (const std::exception& e) { fmt::print("FAIL (unhandled exception) ({})\n", e.what()); } } void io_ConcatenatedStream_TestClass::test_write_CanWriteFromSingleStream() { fmt::print("[tc::io::ConcatenatedStream] test_write_CanWriteFromSingleStream : "); class ReportDummyStream : public StreamTestUtil::DummyStreamBase { public: struct SeekReport { int64_t seek_offset; size_t stream_id; bool operator==(const SeekReport& other) const { return seek_offset == other.seek_offset \ && stream_id == other.stream_id; } }; struct WriteReport { const byte_t* write_ptr; size_t write_count; size_t stream_id; bool operator==(const WriteReport& other) const { return write_ptr == other.write_ptr \ && write_count == other.write_count \ && stream_id == other.stream_id; } }; ReportDummyStream(std::vector& write_report, std::vector& seek_report, size_t stream_id) : DummyStreamBase(0x100, true, true, true, false, false), mWriteReport(write_report), mSeekReport(seek_report), mStreamId(stream_id) {} size_t write(const byte_t* ptr, size_t count) { mWriteReport.push_back({ptr, count, mStreamId}); size_t writable_count = tc::io::IOUtil::getWritableCount(DummyStreamBase::length(), DummyStreamBase::position(), count); // update stream position DummyStreamBase::seek(int64_t(writable_count), tc::io::SeekOrigin::Current); return writable_count; } int64_t seek(int64_t offset, tc::io::SeekOrigin origin) { SeekReport seek_report = {DummyStreamBase::seek(offset, origin), mStreamId}; mSeekReport.push_back(seek_report); return seek_report.seek_offset; } private: std::vector& mWriteReport; std::vector& mSeekReport; size_t mStreamId; }; try { // declare report logs std::vector write_report; std::vector seek_report; // create stream list with links to report logs std::vector> streams { std::make_shared(ReportDummyStream(write_report, seek_report, 0)), // 0x000 - 0x0ff std::make_shared(ReportDummyStream(write_report, seek_report, 1)), // 0x100 - 0x1ff std::make_shared(ReportDummyStream(write_report, seek_report, 2)), // 0x200 - 0x2ff std::make_shared(ReportDummyStream(write_report, seek_report, 3)), // 0x300 - 0x3ff std::make_shared(ReportDummyStream(write_report, seek_report, 4)), // 0x400 - 0x4ff std::make_shared(ReportDummyStream(write_report, seek_report, 5)), // 0x500 - 0x5ff std::make_shared(ReportDummyStream(write_report, seek_report, 6)), // 0x600 - 0x6ff std::make_shared(ReportDummyStream(write_report, seek_report, 7)), // 0x700 - 0x7ff }; // create concatenated stream tc::io::ConcatenatedStream stream = tc::io::ConcatenatedStream(streams); // define test struct Test { // test name std::string test_name; // these seeks are done then seek log is cleared std::vector unlogged_seeks; // these seeks are done before writing but will be logged std::vector logged_seeks; // write param byte_t* write_ptr; size_t write_count; // expected log reports std::vector exp_write_report; std::vector exp_seek_report; }; // create tests std::vector tests { {"WriteFromBeginning", {0}, {}, (byte_t*)0x1000, 0x30, {{(byte_t*)0x1000, 0x30, 0}}, {}}, {"ContinueWritingFromBeginning", {}, {}, (byte_t*)0x1000, 0x30, {{(byte_t*)0x1000, 0x30, 0}}, {}}, {"WriteFromSomewhereElseInExistingStream", {0xe0}, {}, (byte_t*)0x1000, 0x20, {{(byte_t*)0x1000, 0x20, 0}}, {}}, }; // run tests for (auto test = tests.begin(); test != tests.end(); test++) { for (auto itr = test->unlogged_seeks.begin(); itr != test->unlogged_seeks.end(); itr++) { stream.seek(*itr, tc::io::SeekOrigin::Begin); } write_report.clear(); seek_report.clear(); for (auto itr = test->logged_seeks.begin(); itr != test->logged_seeks.end(); itr++) { stream.seek(*itr, tc::io::SeekOrigin::Begin); } stream.write(test->write_ptr, test->write_count); if (write_report != test->exp_write_report) { throw tc::Exception(fmt::format("Test \"{}\" Failed: .write() issued to base streams were not as expected", test->test_name)); } if (seek_report != test->exp_seek_report) { throw tc::Exception(fmt::format("Test \"{}\" Failed: .seek() issued to base streams were not as expected", test->test_name)); } } fmt::print("PASS\n"); } catch (const tc::Exception& e) { fmt::print("FAIL ({:s})\n", e.error()); } catch (const std::exception& e) { fmt::print("FAIL (unhandled exception) ({})\n", e.what()); } } void io_ConcatenatedStream_TestClass::test_write_CanWriteFromMultipleStreamWithSeekSupport() { fmt::print("[tc::io::ConcatenatedStream] test_write_CanWriteFromMultipleStreamWithSeekSupport : "); class ReportDummyStream : public StreamTestUtil::DummyStreamBase { public: struct SeekReport { int64_t seek_offset; size_t stream_id; bool operator==(const SeekReport& other) const { return seek_offset == other.seek_offset \ && stream_id == other.stream_id; } }; struct WriteReport { const byte_t* write_ptr; size_t write_count; size_t stream_id; bool operator==(const WriteReport& other) const { return write_ptr == other.write_ptr \ && write_count == other.write_count \ && stream_id == other.stream_id; } }; ReportDummyStream(std::vector& write_report, std::vector& seek_report, size_t stream_id) : DummyStreamBase(0x100, true, true, true, false, false), mWriteReport(write_report), mSeekReport(seek_report), mStreamId(stream_id) {} size_t write(const byte_t* ptr, size_t count) { mWriteReport.push_back({ptr, count, mStreamId}); size_t writable_count = tc::io::IOUtil::getWritableCount(DummyStreamBase::length(), DummyStreamBase::position(), count); // update stream position DummyStreamBase::seek(int64_t(writable_count), tc::io::SeekOrigin::Current); return writable_count; } int64_t seek(int64_t offset, tc::io::SeekOrigin origin) { SeekReport seek_report = {DummyStreamBase::seek(offset, origin), mStreamId}; mSeekReport.push_back(seek_report); return seek_report.seek_offset; } private: std::vector& mWriteReport; std::vector& mSeekReport; size_t mStreamId; }; try { // declare report logs std::vector write_report; std::vector seek_report; // create stream list with links to report logs std::vector> streams { std::make_shared(ReportDummyStream(write_report, seek_report, 0)), // 0x000 - 0x0ff std::make_shared(ReportDummyStream(write_report, seek_report, 1)), // 0x100 - 0x1ff std::make_shared(ReportDummyStream(write_report, seek_report, 2)), // 0x200 - 0x2ff std::make_shared(ReportDummyStream(write_report, seek_report, 3)), // 0x300 - 0x3ff std::make_shared(ReportDummyStream(write_report, seek_report, 4)), // 0x400 - 0x4ff std::make_shared(ReportDummyStream(write_report, seek_report, 5)), // 0x500 - 0x5ff std::make_shared(ReportDummyStream(write_report, seek_report, 6)), // 0x600 - 0x6ff std::make_shared(ReportDummyStream(write_report, seek_report, 7)), // 0x700 - 0x7ff }; // create concatenated stream tc::io::ConcatenatedStream stream = tc::io::ConcatenatedStream(streams); // define test struct Test { // test name std::string test_name; // these seeks are done then seek log is cleared std::vector unlogged_seeks; // these seeks are done before writeing but will be logged std::vector logged_seeks; // write param byte_t* write_ptr; size_t write_count; // expected log reports std::vector exp_write_report; std::vector exp_seek_report; }; // create tests std::vector tests { {"WriteAllOfStream 0-7 (stream 0x0 positions)", {0x000, 0x100, 0x200, 0x300, 0x400, 0x500, 0x600, 0x700, 0x000}, {}, (byte_t*)0x1000, 0x800, {{(byte_t*)0x1000, 0x100, 0}, {(byte_t*)0x1100, 0x100, 1}, {(byte_t*)0x1200, 0x100, 2}, {(byte_t*)0x1300, 0x100, 3}, {(byte_t*)0x1400, 0x100, 4}, {(byte_t*)0x1500, 0x100, 5}, {(byte_t*)0x1600, 0x100, 6}, {(byte_t*)0x1700, 0x100, 7}}, {}}, {"WriteAllOfStream 0-7 (stream 0x80 positions)", {0x080, 0x180, 0x280, 0x380, 0x480, 0x580, 0x680, 0x780, 0x000}, {}, (byte_t*)0x1000, 0x800, {{(byte_t*)0x1000, 0x100, 0}, {(byte_t*)0x1100, 0x100, 1}, {(byte_t*)0x1200, 0x100, 2}, {(byte_t*)0x1300, 0x100, 3}, {(byte_t*)0x1400, 0x100, 4}, {(byte_t*)0x1500, 0x100, 5}, {(byte_t*)0x1600, 0x100, 6}, {(byte_t*)0x1700, 0x100, 7}}, {{0x0, 1}, {0x0, 2}, {0x0, 3}, {0x0, 4}, {0x0, 5}, {0x0, 6}, {0x0, 7}}}, {"WriteAllOfStream 0-7 (stream 0x00 or 0x80 positions)", {0x080, 0x100, 0x280, 0x300, 0x480, 0x500, 0x680, 0x700, 0x000}, {}, (byte_t*)0x1000, 0x800, {{(byte_t*)0x1000, 0x100, 0}, {(byte_t*)0x1100, 0x100, 1}, {(byte_t*)0x1200, 0x100, 2}, {(byte_t*)0x1300, 0x100, 3}, {(byte_t*)0x1400, 0x100, 4}, {(byte_t*)0x1500, 0x100, 5}, {(byte_t*)0x1600, 0x100, 6}, {(byte_t*)0x1700, 0x100, 7}}, {{0x0, 2}, {0x0, 4}, {0x0, 6}}}, {"WriteAllOfStream 3-6 (stream 0x0 positions)", {0x000, 0x100, 0x200, 0x300, 0x400, 0x500, 0x600, 0x700, 0x300}, {}, (byte_t*)0x1000, 0x400, {{(byte_t*)0x1000, 0x100, 3}, {(byte_t*)0x1100, 0x100, 4}, {(byte_t*)0x1200, 0x100, 5}, {(byte_t*)0x1300, 0x100, 6}}, {}}, {"WriteAllOfStream 3-6 (stream 0x80 positions)", {0x080, 0x180, 0x280, 0x380, 0x480, 0x580, 0x680, 0x780, 0x300}, {}, (byte_t*)0x1000, 0x400, {{(byte_t*)0x1000, 0x100, 3}, {(byte_t*)0x1100, 0x100, 4}, {(byte_t*)0x1200, 0x100, 5}, {(byte_t*)0x1300, 0x100, 6}}, {{0x0, 4}, {0x0, 5}, {0x0, 6}}}, {"WriteStream (partial)3,4-5,(partial)6 (stream 0x0 positions)", {0x000, 0x100, 0x200, 0x300, 0x400, 0x500, 0x600, 0x700, 0x350}, {}, (byte_t*)0x1000, 0x300, {{(byte_t*)0x1000, 0xB0, 3}, {(byte_t*)0x10B0, 0x100, 4}, {(byte_t*)0x11B0, 0x100, 5}, {(byte_t*)0x12B0, 0x50, 6}}, {}}, {"WriteStream (partial)3,4-5,(partial)6 (stream 0x80 positions)", {0x080, 0x180, 0x280, 0x380, 0x480, 0x580, 0x680, 0x780, 0x350}, {}, (byte_t*)0x1000, 0x300, {{(byte_t*)0x1000, 0xB0, 3}, {(byte_t*)0x10B0, 0x100, 4}, {(byte_t*)0x11B0, 0x100, 5}, {(byte_t*)0x12B0, 0x50, 6}}, {{0x0, 4}, {0x0, 5}, {0x0, 6}}}, }; // run tests for (auto test = tests.begin(); test != tests.end(); test++) { for (auto itr = test->unlogged_seeks.begin(); itr != test->unlogged_seeks.end(); itr++) { stream.seek(*itr, tc::io::SeekOrigin::Begin); } write_report.clear(); seek_report.clear(); for (auto itr = test->logged_seeks.begin(); itr != test->logged_seeks.end(); itr++) { stream.seek(*itr, tc::io::SeekOrigin::Begin); } stream.write(test->write_ptr, test->write_count); if (write_report != test->exp_write_report) { throw tc::Exception(fmt::format("Test \"{}\" Failed: .write() issued to base streams were not as expected", test->test_name)); } if (seek_report != test->exp_seek_report) { throw tc::Exception(fmt::format("Test \"{}\" Failed: .seek() issued to base streams were not as expected", test->test_name)); } } fmt::print("PASS\n"); } catch (const tc::Exception& e) { fmt::print("FAIL ({:s})\n", e.error()); } catch (const std::exception& e) { fmt::print("FAIL (unhandled exception) ({})\n", e.what()); } } void io_ConcatenatedStream_TestClass::test_write_CanWriteFromMultipleStreamWithNoSeekSupport() { fmt::print("[tc::io::ConcatenatedStream] test_write_CanWriteFromMultipleStreamWithNoSeekSupport : "); class ReportDummyStream : public StreamTestUtil::DummyStreamBase { public: struct SeekReport { int64_t seek_offset; size_t stream_id; bool operator==(const SeekReport& other) const { return seek_offset == other.seek_offset \ && stream_id == other.stream_id; } }; struct WriteReport { const byte_t* write_ptr; size_t write_count; size_t stream_id; bool operator==(const WriteReport& other) const { return write_ptr == other.write_ptr \ && write_count == other.write_count \ && stream_id == other.stream_id; } }; ReportDummyStream(std::vector& write_report, std::vector& seek_report, size_t stream_id) : DummyStreamBase(0x100, true, true, false, false, false), mWriteReport(write_report), mSeekReport(seek_report), mStreamId(stream_id) {} size_t write(const byte_t* ptr, size_t count) { mWriteReport.push_back({ptr, count, mStreamId}); size_t writable_count = tc::io::IOUtil::getWritableCount(DummyStreamBase::length(), DummyStreamBase::position(), count); // update stream position DummyStreamBase::seek(int64_t(writable_count), tc::io::SeekOrigin::Current); return writable_count; } int64_t seek(int64_t offset, tc::io::SeekOrigin origin) { SeekReport seek_report = {DummyStreamBase::seek(offset, origin), mStreamId}; mSeekReport.push_back(seek_report); return seek_report.seek_offset; } private: std::vector& mWriteReport; std::vector& mSeekReport; size_t mStreamId; }; try { // declare report logs std::vector write_report; std::vector seek_report; // create stream list with links to report logs std::vector> streams { std::make_shared(ReportDummyStream(write_report, seek_report, 0)), // 0x000 - 0x0ff std::make_shared(ReportDummyStream(write_report, seek_report, 1)), // 0x100 - 0x1ff std::make_shared(ReportDummyStream(write_report, seek_report, 2)), // 0x200 - 0x2ff std::make_shared(ReportDummyStream(write_report, seek_report, 3)), // 0x300 - 0x3ff std::make_shared(ReportDummyStream(write_report, seek_report, 4)), // 0x400 - 0x4ff std::make_shared(ReportDummyStream(write_report, seek_report, 5)), // 0x500 - 0x5ff std::make_shared(ReportDummyStream(write_report, seek_report, 6)), // 0x600 - 0x6ff std::make_shared(ReportDummyStream(write_report, seek_report, 7)), // 0x700 - 0x7ff }; // create concatenated stream tc::io::ConcatenatedStream stream = tc::io::ConcatenatedStream(streams); // define test struct Test { // test name std::string test_name; // these seeks are done then seek log is cleared std::vector unlogged_seeks; // these seeks are done before writeing but will be logged std::vector logged_seeks; // write param byte_t* write_ptr; size_t write_count; // expected log reports std::vector exp_write_report; std::vector exp_seek_report; }; // create tests std::vector tests { {"WriteStream (partial)0", {}, {}, (byte_t*)0x1000, 0xA0, {{(byte_t*)0x1000, 0xA0, 0}}, {}}, {"WriteStream (partial)0,1-4", {}, {}, (byte_t*)0x1000, 0x460, {{(byte_t*)0x1000, 0x60, 0}, {(byte_t*)0x1060, 0x100, 1}, {(byte_t*)0x1160, 0x100, 2}, {(byte_t*)0x1260, 0x100, 3}, {(byte_t*)0x1360, 0x100, 4}}, {}}, {"WriteStream 5-7", {}, {}, (byte_t*)0x1000, 0x300, {{(byte_t*)0x1000, 0x100, 5}, {(byte_t*)0x1100, 0x100, 6}, {(byte_t*)0x1200, 0x100, 7}}, {}}, }; // run tests for (auto test = tests.begin(); test != tests.end(); test++) { for (auto itr = test->unlogged_seeks.begin(); itr != test->unlogged_seeks.end(); itr++) { stream.seek(*itr, tc::io::SeekOrigin::Begin); } write_report.clear(); seek_report.clear(); for (auto itr = test->logged_seeks.begin(); itr != test->logged_seeks.end(); itr++) { stream.seek(*itr, tc::io::SeekOrigin::Begin); } stream.write(test->write_ptr, test->write_count); if (write_report != test->exp_write_report) { fmt::print("\n"); fmt::print("WriteLog:\n"); for (auto itr = write_report.begin(); itr != write_report.end(); itr++) { fmt::print("WriteReport (ptr: 0x{:x}, count: 0x{:x}, stream: {:d})\n", (size_t)itr->write_ptr, itr->write_count, itr->stream_id); } fmt::print("ExpWriteLog:\n"); for (auto itr = test->exp_write_report.begin(); itr != test->exp_write_report.end(); itr++) { fmt::print("WriteReport (ptr: 0x{:x}, count: 0x{:x}, stream: {:d})\n", (size_t)itr->write_ptr, itr->write_count, itr->stream_id); } throw tc::Exception(fmt::format("Test \"{}\" Failed: .write() issued to base streams were not as expected", test->test_name)); } if (seek_report != test->exp_seek_report) { throw tc::Exception(fmt::format("Test \"{}\" Failed: .seek() issued to base streams were not as expected", test->test_name)); } } fmt::print("PASS\n"); } catch (const tc::Exception& e) { fmt::print("FAIL ({:s})\n", e.error()); } catch (const std::exception& e) { fmt::print("FAIL (unhandled exception) ({})\n", e.what()); } } void io_ConcatenatedStream_TestClass::test_write_WriteFromMultiStream_NoSeekSupport_ThrowsOnSeekRequired() { fmt::print("[tc::io::ConcatenatedStream] test_write_WriteFromMultiStream_NoSeekSupport_ThrowsOnSeekRequired : "); class ReportDummyStream : public StreamTestUtil::DummyStreamBase { public: struct SeekReport { int64_t seek_offset; size_t stream_id; bool operator==(const SeekReport& other) const { return seek_offset == other.seek_offset \ && stream_id == other.stream_id; } }; struct WriteReport { const byte_t* write_ptr; size_t write_count; size_t stream_id; bool operator==(const WriteReport& other) const { return write_ptr == other.write_ptr \ && write_count == other.write_count \ && stream_id == other.stream_id; } }; ReportDummyStream(std::vector& write_report, std::vector& seek_report, size_t stream_id) : DummyStreamBase(0x100, 0x80, true, true, false, false, false), // the initial position is 0x80 mWriteReport(write_report), mSeekReport(seek_report), mStreamId(stream_id) {} size_t write(const byte_t* ptr, size_t count) { mWriteReport.push_back({ptr, count, mStreamId}); size_t writable_count = tc::io::IOUtil::getWritableCount(DummyStreamBase::length(), DummyStreamBase::position(), count); // update stream position DummyStreamBase::seek(int64_t(writable_count), tc::io::SeekOrigin::Current); return writable_count; } int64_t seek(int64_t offset, tc::io::SeekOrigin origin) { SeekReport seek_report = {DummyStreamBase::seek(offset, origin), mStreamId}; mSeekReport.push_back(seek_report); return seek_report.seek_offset; } private: std::vector& mWriteReport; std::vector& mSeekReport; size_t mStreamId; }; try { // declare report logs std::vector write_report; std::vector seek_report; // create stream list with links to report logs std::vector> streams { std::make_shared(ReportDummyStream(write_report, seek_report, 0)), // 0x000 - 0x0ff std::make_shared(ReportDummyStream(write_report, seek_report, 1)), // 0x100 - 0x1ff std::make_shared(ReportDummyStream(write_report, seek_report, 2)), // 0x200 - 0x2ff std::make_shared(ReportDummyStream(write_report, seek_report, 3)), // 0x300 - 0x3ff std::make_shared(ReportDummyStream(write_report, seek_report, 4)), // 0x400 - 0x4ff std::make_shared(ReportDummyStream(write_report, seek_report, 5)), // 0x500 - 0x5ff std::make_shared(ReportDummyStream(write_report, seek_report, 6)), // 0x600 - 0x6ff std::make_shared(ReportDummyStream(write_report, seek_report, 7)), // 0x700 - 0x7ff }; // create concatenated stream tc::io::ConcatenatedStream stream = tc::io::ConcatenatedStream(streams); try { stream.write((byte_t*)0x1000, 0x200); throw tc::Exception(".write() did not throw tc::io::IOException where stream required seeking to begining but did not support seeking."); } catch (const tc::io::IOException&) { // do nothing } fmt::print("PASS\n"); } catch (const tc::Exception& e) { fmt::print("FAIL ({:s})\n", e.error()); } catch (const std::exception& e) { fmt::print("FAIL (unhandled exception) ({})\n", e.what()); } } void io_ConcatenatedStream_TestClass::test_MoveOperator_MoveDisposedToDisposed() { fmt::print("[tc::io::ConcatenatedStream] test_MoveOperator_MoveDisposedToDisposed : "); try { // create streams a and b (both disposed) tc::io::ConcatenatedStream stream_a; tc::io::ConcatenatedStream stream_b; // ensure stream a had valid properties to begin with try { StreamTestUtil::constructor_TestHelper(stream_a, 0x0, 0x0, false, false, false); } catch (const tc::Exception& e) { throw tc::Exception(fmt::format("stream_a had wrong properies after default .ctor() ({})", e.error())); } try { stream_a.seek(0, tc::io::SeekOrigin::Current); throw tc::Exception("stream_a was disposed upon construction, but failed throw tc::ObjectDisposedException when seek() was called"); } catch (const tc::ObjectDisposedException&) { // do nothing } // ensure stream b had valid properties to begin with try { StreamTestUtil::constructor_TestHelper(stream_b, 0x0, 0x0, false, false, false); } catch (const tc::Exception& e) { throw tc::Exception(fmt::format("stream_b had wrong properies after default .ctor() ({})", e.error())); } try { stream_b.seek(0, tc::io::SeekOrigin::Current); throw tc::Exception("stream_b was disposed upon construction, but failed throw tc::ObjectDisposedException when seek() was called"); } catch (const tc::ObjectDisposedException&) { // do nothing } // move stream_a to stream_b stream_b = std::move(stream_a); // ensure stream a had valid properties after being moved from try { StreamTestUtil::constructor_TestHelper(stream_a, 0x0, 0x0, false, false, false); } catch (const tc::Exception& e) { throw tc::Exception(fmt::format("stream_a had wrong properies after it was move assigned to stream_b ({})", e.error())); } try { stream_a.seek(0, tc::io::SeekOrigin::Current); throw tc::Exception("stream_a was disposed upon being move assigned to stream_b, but failed throw tc::ObjectDisposedException when seek() was called"); } catch (const tc::ObjectDisposedException&) { // do nothing } // ensure stream b had valid properties after being moved to try { StreamTestUtil::constructor_TestHelper(stream_b, 0x0, 0x0, false, false, false); } catch (const tc::Exception& e) { throw tc::Exception(fmt::format("stream_b has wrong properties after being move assigned from stream_a ({})", e.error())); } try { stream_b.seek(0, tc::io::SeekOrigin::Current); throw tc::Exception("stream_b was disposed upon move assignment from stream_a, but failed throw tc::ObjectDisposedException when seek() was called"); } catch (const tc::ObjectDisposedException&) { // do nothing } fmt::print("PASS\n"); } catch (const tc::Exception& e) { fmt::print("FAIL ({:s})\n", e.error()); } catch (const std::exception& e) { fmt::print("FAIL (unhandled exception) ({})\n", e.what()); } } void io_ConcatenatedStream_TestClass::test_MoveOperator_MoveInitializedToDisposed() { fmt::print("[tc::io::ConcatenatedStream] test_MoveOperator_MoveInitializedToDisposed : "); try { std::vector> streams { std::make_shared(StreamTestUtil::DummyStreamBase(0x100, true, true, true, false, false)), std::make_shared(StreamTestUtil::DummyStreamBase(0x100, true, true, true, false, false)), std::make_shared(StreamTestUtil::DummyStreamBase(0x100, true, true, true, false, false)) }; // create streams a and b tc::io::ConcatenatedStream stream_a(streams); tc::io::ConcatenatedStream stream_b; // ensure stream a had valid properties to begin with try { StreamTestUtil::constructor_TestHelper(stream_a, 0x300, 0x0, true, true, true); } catch (const tc::Exception& e) { throw tc::Exception(fmt::format("stream_a had wrong properies after create .ctor() ({})", e.error())); } try { stream_a.seek(0, tc::io::SeekOrigin::Current); } catch (const tc::ObjectDisposedException&) { throw tc::Exception("stream_a was initialized upon construction, but threw tc::ObjectDisposedException when seek() was called"); } // ensure stream b had valid properties to begin with try { StreamTestUtil::constructor_TestHelper(stream_b, 0x0, 0x0, false, false, false); } catch (const tc::Exception& e) { throw tc::Exception(fmt::format("stream_b had wrong properies after default .ctor() ({})", e.error())); } try { stream_b.seek(0, tc::io::SeekOrigin::Current); throw tc::Exception("stream_b was disposed upon construction, but failed throw tc::ObjectDisposedException when seek() was called"); } catch (const tc::ObjectDisposedException&) { // do nothing } // move stream_a to stream_b stream_b = std::move(stream_a); // ensure stream a had valid properties after being moved from try { StreamTestUtil::constructor_TestHelper(stream_a, 0x0, 0x0, false, false, false); } catch (const tc::Exception& e) { throw tc::Exception(fmt::format("stream_a had wrong properies after it was move assigned to stream_b ({})", e.error())); } try { stream_a.seek(0, tc::io::SeekOrigin::Current); throw tc::Exception("stream_a was disposed upon being move assigned to stream_b, but failed throw tc::ObjectDisposedException when seek() was called"); } catch (const tc::ObjectDisposedException&) { // do nothing } // ensure stream b had valid properties after being moved to try { StreamTestUtil::constructor_TestHelper(stream_b, 0x300, 0x0, true, true, true); } catch (const tc::Exception& e) { throw tc::Exception(fmt::format("stream_b has wrong properties after being move assigned from stream_a ({})", e.error())); } try { stream_b.seek(0, tc::io::SeekOrigin::Current); } catch (const tc::ObjectDisposedException&) { throw tc::Exception("stream_b was initialized upon move assignment from stream_a, but threw tc::ObjectDisposedException when seek() was called"); } fmt::print("PASS\n"); } catch (const tc::Exception& e) { fmt::print("FAIL ({:s})\n", e.error()); } catch (const std::exception& e) { fmt::print("FAIL (unhandled exception) ({})\n", e.what()); } } void io_ConcatenatedStream_TestClass::test_MoveOperator_MoveDisposedToInitialized() { fmt::print("[tc::io::ConcatenatedStream] test_MoveOperator_MoveDisposedToInitialized : "); try { std::vector> streams { std::make_shared(StreamTestUtil::DummyStreamBase(0x100, true, true, true, false, false)), std::make_shared(StreamTestUtil::DummyStreamBase(0x100, true, true, true, false, false)), std::make_shared(StreamTestUtil::DummyStreamBase(0x100, true, true, true, false, false)) }; // create streams a and b tc::io::ConcatenatedStream stream_a; tc::io::ConcatenatedStream stream_b(streams); // ensure stream b had valid properties to begin with try { StreamTestUtil::constructor_TestHelper(stream_a, 0x0, 0x0, false, false, false); } catch (const tc::Exception& e) { throw tc::Exception(fmt::format("stream_a had wrong properies after default .ctor() ({})", e.error())); } try { stream_a.seek(0, tc::io::SeekOrigin::Current); throw tc::Exception("stream_a was disposed upon construction, but failed throw tc::ObjectDisposedException when seek() was called"); } catch (const tc::ObjectDisposedException&) { // do nothing } // ensure stream a had valid properties to begin with try { StreamTestUtil::constructor_TestHelper(stream_b, 0x300, 0x0, true, true, true); } catch (const tc::Exception& e) { throw tc::Exception(fmt::format("stream_b had wrong properies after create .ctor() ({})", e.error())); } try { stream_b.seek(0, tc::io::SeekOrigin::Current); } catch (const tc::ObjectDisposedException&) { throw tc::Exception("stream_b was initialized upon construction, but threw tc::ObjectDisposedException when seek() was called"); } // move stream_a to stream_b stream_b = std::move(stream_a); // ensure stream a had valid properties after being moved from try { StreamTestUtil::constructor_TestHelper(stream_a, 0x0, 0x0, false, false, false); } catch (const tc::Exception& e) { throw tc::Exception(fmt::format("stream_a had wrong properies after it was move assigned to stream_b ({})", e.error())); } try { stream_a.seek(0, tc::io::SeekOrigin::Current); throw tc::Exception("stream_a was disposed upon being move assigned to stream_b, but failed throw tc::ObjectDisposedException when seek() was called"); } catch (const tc::ObjectDisposedException&) { // do nothing } // ensure stream b had valid properties after being moved to try { StreamTestUtil::constructor_TestHelper(stream_b, 0x0, 0x0, false, false, false); } catch (const tc::Exception& e) { throw tc::Exception(fmt::format("stream_b has wrong properties after being move assigned from stream_a ({})", e.error())); } try { stream_b.seek(0, tc::io::SeekOrigin::Current); throw tc::Exception("stream_b was disposed upon move assignment from stream_a, but failed throw tc::ObjectDisposedException when seek() was called"); } catch (const tc::ObjectDisposedException&) { // do nothing } fmt::print("PASS\n"); } catch (const tc::Exception& e) { fmt::print("FAIL ({:s})\n", e.error()); } catch (const std::exception& e) { fmt::print("FAIL (unhandled exception) ({})\n", e.what()); } } void io_ConcatenatedStream_TestClass::test_MoveOperator_MoveInitializedToInitialized() { fmt::print("[tc::io::ConcatenatedStream] test_MoveOperator_MoveInitializedToInitialized : "); try { std::vector> streams_a { std::make_shared(StreamTestUtil::DummyStreamBase(0x100, true, true, true, false, false)), std::make_shared(StreamTestUtil::DummyStreamBase(0x100, true, true, true, false, false)), std::make_shared(StreamTestUtil::DummyStreamBase(0x100, true, true, true, false, false)) }; std::vector> streams_b { std::make_shared(StreamTestUtil::DummyStreamBase(0x200, true, true, true, false, false)), std::make_shared(StreamTestUtil::DummyStreamBase(0x200, true, true, true, false, false)), std::make_shared(StreamTestUtil::DummyStreamBase(0x200, true, true, true, false, false)) }; // create streams a and b tc::io::ConcatenatedStream stream_a(streams_a); tc::io::ConcatenatedStream stream_b(streams_b); // ensure stream a had valid properties to begin with try { StreamTestUtil::constructor_TestHelper(stream_a, 0x300, 0x0, true, true, true); } catch (const tc::Exception& e) { throw tc::Exception(fmt::format("stream_a had wrong properies after create .ctor() ({})", e.error())); } try { stream_a.seek(0, tc::io::SeekOrigin::Current); } catch (const tc::ObjectDisposedException&) { throw tc::Exception("stream_a was initialized upon construction, but threw tc::ObjectDisposedException when seek() was called"); } // ensure stream a had valid properties to begin with try { StreamTestUtil::constructor_TestHelper(stream_b, 0x600, 0x0, true, true, true); } catch (const tc::Exception& e) { throw tc::Exception(fmt::format("stream_b had wrong properies after create .ctor() ({})", e.error())); } try { stream_b.seek(0, tc::io::SeekOrigin::Current); } catch (const tc::ObjectDisposedException&) { throw tc::Exception("stream_b was initialized upon construction, but threw tc::ObjectDisposedException when seek() was called"); } // move stream_a to stream_b stream_b = std::move(stream_a); // ensure stream a had valid properties after being moved from try { StreamTestUtil::constructor_TestHelper(stream_a, 0x0, 0x0, false, false, false); } catch (const tc::Exception& e) { throw tc::Exception(fmt::format("stream_a had wrong properies after it was move assigned to stream_b ({})", e.error())); } try { stream_a.seek(0, tc::io::SeekOrigin::Current); throw tc::Exception("stream_a was disposed upon being move assigned to stream_b, but failed throw tc::ObjectDisposedException when seek() was called"); } catch (const tc::ObjectDisposedException&) { // do nothing } // ensure stream b had valid properties after being moved to try { StreamTestUtil::constructor_TestHelper(stream_b, 0x300, 0x0, true, true, true); } catch (const tc::Exception& e) { throw tc::Exception(fmt::format("stream_b has wrong properties after being move assigned from stream_a ({})", e.error())); } try { stream_b.seek(0, tc::io::SeekOrigin::Current); } catch (const tc::ObjectDisposedException&) { throw tc::Exception("stream_b was initialized upon move assignment from stream_a, but threw tc::ObjectDisposedException when seek() was called"); } fmt::print("PASS\n"); } catch (const tc::Exception& e) { fmt::print("FAIL ({:s})\n", e.error()); } catch (const std::exception& e) { fmt::print("FAIL (unhandled exception) ({})\n", e.what()); } } void io_ConcatenatedStream_TestClass::test_MoveConstructor_MoveDisposed() { fmt::print("[tc::io::ConcatenatedStream] test_MoveConstructor_MoveDisposed : "); try { // create stream a tc::io::ConcatenatedStream stream_a; // ensure stream a had valid properties to begin with try { StreamTestUtil::constructor_TestHelper(stream_a, 0x0, 0x0, false, false, false); } catch (const tc::Exception& e) { throw tc::Exception(fmt::format("stream_a had wrong properies after default .ctor() ({})", e.error())); } try { stream_a.seek(0, tc::io::SeekOrigin::Current); throw tc::Exception("stream_a was disposed upon construction, but failed throw tc::ObjectDisposedException when seek() was called"); } catch (const tc::ObjectDisposedException&) { // do nothing } // move stream_a to stream_b tc::io::ConcatenatedStream stream_b(std::move(stream_a)); // ensure stream a had valid properties after being moved from try { StreamTestUtil::constructor_TestHelper(stream_a, 0x0, 0x0, false, false, false); } catch (const tc::Exception& e) { throw tc::Exception(fmt::format("stream_a had wrong properies after it was move assigned to stream_b ({})", e.error())); } try { stream_a.seek(0, tc::io::SeekOrigin::Current); throw tc::Exception("stream_a was disposed upon being move assigned to stream_b, but failed throw tc::ObjectDisposedException when seek() was called"); } catch (const tc::ObjectDisposedException&) { // do nothing } // ensure stream b had valid properties after being moved to try { StreamTestUtil::constructor_TestHelper(stream_b, 0x0, 0x0, false, false, false); } catch (const tc::Exception& e) { throw tc::Exception(fmt::format("stream_b has wrong properties after being move assigned from stream_a ({})", e.error())); } try { stream_b.seek(0, tc::io::SeekOrigin::Current); throw tc::Exception("stream_b was disposed upon move assignment from stream_a, but failed throw tc::ObjectDisposedException when seek() was called"); } catch (const tc::ObjectDisposedException&) { // do nothing } fmt::print("PASS\n"); } catch (const tc::Exception& e) { fmt::print("FAIL ({:s})\n", e.error()); } catch (const std::exception& e) { fmt::print("FAIL (unhandled exception) ({})\n", e.what()); } } void io_ConcatenatedStream_TestClass::test_MoveConstructor_MoveInitialized() { fmt::print("[tc::io::ConcatenatedStream] test_MoveConstructor_MoveInitialized : "); try { std::vector> streams { std::make_shared(StreamTestUtil::DummyStreamBase(0x100, true, true, true, false, false)), std::make_shared(StreamTestUtil::DummyStreamBase(0x100, true, true, true, false, false)), std::make_shared(StreamTestUtil::DummyStreamBase(0x100, true, true, true, false, false)) }; // create stream a tc::io::ConcatenatedStream stream_a(streams); // ensure stream a had valid properties to begin with try { StreamTestUtil::constructor_TestHelper(stream_a, 0x300, 0x0, true, true, true); } catch (const tc::Exception& e) { throw tc::Exception(fmt::format("stream_a had wrong properies after create .ctor() ({})", e.error())); } try { stream_a.seek(0, tc::io::SeekOrigin::Current); } catch (const tc::ObjectDisposedException&) { throw tc::Exception("stream_a was initialized upon construction, but threw tc::ObjectDisposedException when seek() was called"); } // move stream_a to stream_b tc::io::ConcatenatedStream stream_b(std::move(stream_a)); // ensure stream a had valid properties after being moved from try { StreamTestUtil::constructor_TestHelper(stream_a, 0x0, 0x0, false, false, false); } catch (const tc::Exception& e) { throw tc::Exception(fmt::format("stream_a had wrong properies after it was move assigned to stream_b ({})", e.error())); } try { stream_a.seek(0, tc::io::SeekOrigin::Current); throw tc::Exception("stream_a was disposed upon being move assigned to stream_b, but failed throw tc::ObjectDisposedException when seek() was called"); } catch (const tc::ObjectDisposedException&) { // do nothing } // ensure stream b had valid properties after being moved to try { StreamTestUtil::constructor_TestHelper(stream_b, 0x300, 0x0, true, true, true); } catch (const tc::Exception& e) { throw tc::Exception(fmt::format("stream_b has wrong properties after being move assigned from stream_a ({})", e.error())); } try { stream_b.seek(0, tc::io::SeekOrigin::Current); } catch (const tc::ObjectDisposedException&) { throw tc::Exception("stream_b was initialized upon move assignment from stream_a, but threw tc::ObjectDisposedException when seek() was called"); } fmt::print("PASS\n"); } catch (const tc::Exception& e) { fmt::print("FAIL ({:s})\n", e.error()); } catch (const std::exception& e) { fmt::print("FAIL (unhandled exception) ({})\n", e.what()); } }src/leaf/wrapper/weru/mcrew/ManageData.cxx // Copyright 2017 Battelle Energy Alliance, 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. // --- LEAF Includes --- // #include namespace leaf { namespace wrapper { namespace weru { namespace mcrew { //////////////////////////////////////////////////////////////////////////////// ManageData::ManageData() : java::lang::Object( java::NewObject( GetJclass(), GetJmid( "" ) ) ) { ; } //////////////////////////////////////////////////////////////////////////////// ManageData::ManageData( jobject const& o ) : java::lang::Object( o ) { ; } //////////////////////////////////////////////////////////////////////////////// ManageData::~ManageData() { ; } //////////////////////////////////////////////////////////////////////////////// int const& ManageData::CHECK_PASSED() { static int const CHECK_PASSED = java::GetStaticField< jint >( GetJclass(), GetJfid( "CHECK_PASSED" ) ); return CHECK_PASSED; } //////////////////////////////////////////////////////////////////////////////// int const& ManageData::CHECK_FAILED() { static int const CHECK_FAILED = java::GetStaticField< jint >( GetJclass(), GetJfid( "CHECK_FAILED" ) ); return CHECK_FAILED; } //////////////////////////////////////////////////////////////////////////////// int const& ManageData::kSuccess() { static int const kSuccess = java::GetStaticField< jint >( GetJclass(), GetJfid( "kSuccess" ) ); return kSuccess; } //////////////////////////////////////////////////////////////////////////////// bool ManageData::CheckAllConditions( java::util::Vector< java::lang::String > const& msgs ) const { int check = java::CallMethod< jint >( m_jobject, GetJmid( "checkAllConditions" ), msgs.Jobj() ); return ( check == CHECK_PASSED() ); } //////////////////////////////////////////////////////////////////////////////// int ManageData::CheckRotationYears() const { return java::CallMethod< jint >( m_jobject, GetJmid( "checkRotationYears" ) ); } //////////////////////////////////////////////////////////////////////////////// int ManageData::GetRotationYears() const { return java::CallMethod< jint >( m_jobject, GetJmid( "getRotationYears" ) ); } //////////////////////////////////////////////////////////////////////////////// java::util::Vector< RowInfo >::SPtr ManageData::GetRows() const { return Create< java::util::Vector< RowInfo > >( java::CallMethod< jobject >( m_jobject, GetJmid( "getRows" ) ) ); } //////////////////////////////////////////////////////////////////////////////// bool ManageData::ReadDataFile( java::lang::String const& pFileName ) const { int success = java::CallMethod< jint >( m_jobject, GetJmid( "readDataFile" ), pFileName.Jobj() ); return ( success == kSuccess() ); } //////////////////////////////////////////////////////////////////////////////// bool ManageData::WriteDataFile( java::lang::String const& pFileName ) const { int success = java::CallMethod< jint >( m_jobject, GetJmid( "writeDataFile" ), pFileName.Jobj() ); return ( success == kSuccess() ); } //////////////////////////////////////////////////////////////////////////////// jclass const& ManageData::GetJclass() { static jclass const clazz = java::FindClass( "usda/weru/mcrew/ManageData" ); return clazz; } //////////////////////////////////////////////////////////////////////////////// jmethodID const& ManageData::GetJmid( std::string const& name ) { static java::JMIDMAP const jmidMap = boost::assign::map_list_of ( "", java::GetMethodID( GetJclass(), "", "()V" ) ) ( "checkAllConditions", java::GetMethodID( GetJclass(), "checkAllConditions", "(Ljava/util/List;)I" ) ) ( "checkRotationYears", java::GetMethodID( GetJclass(), "checkRotationYears", "()I" ) ) ( "getRotationYears", java::GetMethodID( GetJclass(), "getRotationYears", "()I" ) ) ( "getRows", java::GetMethodID( GetJclass(), "getRows", "()Ljava/util/Vector;" ) ) ( "readDataFile", java::GetMethodID( GetJclass(), "readDataFile", "(Ljava/lang/String;)I" ) ) ( "writeDataFile", java::GetMethodID( GetJclass(), "writeDataFile", "(Ljava/lang/String;)I" ) ); java::JMIDMAP::const_iterator itr = jmidMap.find( name ); return itr->second; } //////////////////////////////////////////////////////////////////////////////// jfieldID const& ManageData::GetJfid( std::string const& name ) { static java::JFIDMAP const jfidMap = boost::assign::map_list_of ( "CHECK_PASSED", java::GetStaticFieldID( GetJclass(), "CHECK_PASSED", "I" ) ) ( "CHECK_FAILED", java::GetStaticFieldID( GetJclass(), "CHECK_FAILED", "I" ) ) ( "kSuccess", java::GetStaticFieldID( GetJclass(), "kSuccess", "I" ) ); java::JFIDMAP::const_iterator itr = jfidMap.find( name ); return itr->second; } //////////////////////////////////////////////////////////////////////////////// } //end mcrew } //end weru } //end wrapper } //end leaf // Copyright (c) 2021 PokeMaster Team // , // We are making my contributions/submissions to this project solely in our // personal capacity and are not conveying any rights to any intellectual // property of any third parties. #include #include #include #include #include namespace PokeMaster::Move { void LoadData(entt::registry& registry) { // Read Item data from JSON file std::ifstream moveFile(RESOURCES_DIR "moves.json"); nlohmann::json j; moveFile >> j; for (auto& data : j) { auto entity = registry.create(); registry.emplace(entity); registry.emplace(entity, data["identifier"].get()); } moveFile.close(); } } // namespace PokeMaster::Moveinclude/osram/extractor/intersection/constants.hxx #ifndef OSRAM_EXTRACTOR_INTERSECTION_CONSTANTS #define OSRAM_EXTRACTOR_INTERSECTION_CONSTANTS namespace osram { namespace extractor { namespace intersection { // what angle is interpreted as going straight const double constexpr STRAIGHT_ANGLE = 180.; const double constexpr ORTHOGONAL_ANGLE = 90.; // if a turn deviates this much from going straight, it will be kept straight const double constexpr MAXIMAL_ALLOWED_NO_TURN_DEVIATION = 3.; // angle that lies between two nearly indistinguishable roads const double constexpr NARROW_TURN_ANGLE = 40.; const double constexpr GROUP_ANGLE = 60; // angle difference that can be classified as straight, if its the only narrow // turn const double constexpr FUZZY_ANGLE_DIFFERENCE = 25.; // Road priorities give an idea of how obvious a turn is. If two priorities // differ greatly (e.g. service road over a primary road, the better priority // can be seen as obvious due to its road category). const double constexpr PRIORITY_DISTINCTION_FACTOR = 1.75; // the lane width we assume for a single lane const auto constexpr ASSUMED_LANE_WIDTH = 3.25; // how far apart can roads be at the most, when thinking about merging them? const auto constexpr MERGABLE_ANGLE_DIFFERENCE = 95.0; } // namespace intersection } // namespace extractor } // namespace osram #endif thejkane/AGM1-10 // Copyright 2010-2013 The Trustees of Indiana University. // // 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. // 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. // // Authors: // #ifndef AMPLUSPLUS_LOCK_FREE_COALESCED_MESSAGE_TYPE_PACKED_HPP #define AMPLUSPLUS_LOCK_FREE_COALESCED_MESSAGE_TYPE_PACKED_HPP #include #include #include #include #include #include #include #include #include namespace amplusplus { // Thread-safe functions: // Handler calls (from progress on underlying engine) // send // flush (both versions) // // This version is like the basic lock_free_coalesced_message_type but with the // message buffer pointer and size packed into 64 bits to avoid cmpxchg16b on // old Opterons that don't have it. Assumptions are that the message buffer // has size at most (1 << 16) - 1 and only the last 48 bits (signed) of // pointers are significant. namespace detail { template inline uint64_t pack_pointer_and_size(T* p, unsigned int n) { BOOST_ASSERT (((int64_t(p) << 16) >> 16) == intptr_t(p)); return ((uint64_t)(uintptr_t)p << 16) | (n & 0xffffu); } template inline T* unpack_pointer(uint64_t packed) { return (T*)(int64_t(packed) >> 16); // Sign extension is important here } inline unsigned int unpack_size(uint64_t packed) { return (unsigned int)(packed & 0xffffu); } } template class lock_free_coalesced_message_type_packed { BOOST_STATIC_ASSERT(BufferSize <= 0xffff); struct message_buffer { volatile size_t elements_written; Arg data[BufferSize]; message_buffer(): elements_written(0), data(data) {} }; public: typedef Arg arg_type; typedef AMEngine engine_type; typedef Handler handler_type; typedef typename am_engine_traits::rank_type rank_type; lock_free_coalesced_message_type_packed(AMEngine& engine) : engine(engine), mpi_datatype(), handler_scope(engine, BufferSize, mpi_datatype.get(), BufferSize * sizeof(Arg), raw_message_handler(*this)), buffers_to_swap_in((void (*)(message_buffer*))0) { message_index = handler_scope.get_message_index(); size_t nranks = num_processes(engine); for (size_t i = 0; i < 2 * nranks + 1; ++i) { buffer_pool.push_back(create_buffer()); } for (size_t i = 0; i < nranks; ++i) { outgoing_buffers_packed.push_back(detail::pack_pointer_and_size(alloc_buffer(), 0)); } flush_signal(engine, message_index).connect(typename lock_free_coalesced_message_type_packed::flush_message_buffer(*this)); } private: void send_buffer(message_buffer* buf, uintptr_t count, typename am_engine_traits::rank_type dest) { while (buf->elements_written != count) {} // Wait for all elements to be written, not just allocated send(engine, message_index, buf->data, count, mpi_datatype.get(), dest, typename lock_free_coalesced_message_type_packed::free_buffer(*this, buf)); } struct flush_message_buffer { lock_free_coalesced_message_type_packed& mt; flush_message_buffer(lock_free_coalesced_message_type_packed& mt): mt(mt) {} void operator()(typename am_engine_traits::rank_type dest) { BOOST_ASSERT (is_valid_rank(mt.engine, dest)); if (mt.buffers_to_swap_in.get() == NULL) { mt.buffers_to_swap_in.reset(mt.alloc_buffer()); } message_buffer* buffer_to_swap_in = mt.buffers_to_swap_in.get(); volatile uint64_t* old_buf_ptr = &mt.outgoing_buffers_packed[dest]; uint64_t old_buf_packed = *old_buf_ptr; while (true) { // Use CAS for atomic swap if (detail::unpack_size(old_buf_packed) == 0) return; message_buffer* new_buf_first = buffer_to_swap_in; uintptr_t new_buf_second = 0; uint64_t old_val = detail::atomic_cas(*old_buf_ptr, old_buf_packed, detail::pack_pointer_and_size(new_buf_first, new_buf_second)); if (old_val == old_buf_packed) break; old_buf_packed = old_val; } uintptr_t count = detail::unpack_size(old_buf_packed); mt.send_buffer(detail::unpack_pointer(old_buf_packed), count, dest); mt.buffers_to_swap_in.reset(mt.alloc_buffer()); } }; struct raw_message_handler { lock_free_coalesced_message_type_packed& mt; raw_message_handler(lock_free_coalesced_message_type_packed& mt): mt(mt) {} void operator()(typename am_engine_traits::rank_type src, const void* buf, size_t count) { const Arg* actual_buf = (const Arg*)buf; for (size_t i = 0; i < count; ++i) { mt.handler(src, actual_buf[i]); } } }; public: friend void set_handler(lock_free_coalesced_message_type_packed& mt, const handler_type& handler) { mt.handler = handler; } friend void send(lock_free_coalesced_message_type_packed& mt, const arg_type& arg, rank_type dest) { BOOST_ASSERT (is_valid_rank(mt.engine, dest)); if (mt.buffers_to_swap_in.get() == NULL) { mt.buffers_to_swap_in.reset(mt.alloc_buffer()); } message_buffer* buffer_to_swap_in = mt.buffers_to_swap_in.get(); volatile uint64_t* old_buf_ptr = &mt.outgoing_buffers_packed[dest]; uint64_t old_buf_packed = *old_buf_ptr; while (true) { message_buffer* new_buf_first = detail::unpack_size(old_buf_packed) + 1 == BufferSize ? buffer_to_swap_in : detail::unpack_pointer(old_buf_packed); uintptr_t new_buf_second = detail::unpack_size(old_buf_packed) + 1 == BufferSize ? 0 : detail::unpack_size(old_buf_packed) + 1; uint64_t old_val = detail::atomic_cas(*old_buf_ptr, old_buf_packed, detail::pack_pointer_and_size(new_buf_first, new_buf_second)); if (old_val == old_buf_packed) break; old_buf_packed = old_val; } uintptr_t count = detail::unpack_size(old_buf_packed); message_buffer* old_buf_first = detail::unpack_pointer(old_buf_packed); old_buf_first->data[count] = arg; detail::atomic_inc(old_buf_first->elements_written); if (count + 1 == BufferSize) { mt.send_buffer(old_buf_first, count + 1, dest); mt.buffers_to_swap_in.reset(mt.alloc_buffer()); } } friend void flush(lock_free_coalesced_message_type_packed& mt) { flush(mt.engine, mt.message_index); // Calls my flush through hook signal } friend void flush(lock_free_coalesced_message_type_packed& mt, typename am_engine_traits::rank_type dest) { flush(mt.engine, dest, mt.message_index); // Calls my flush through hook signal } private: AMEngine& engine; make_mpi_datatype mpi_datatype; typename am_engine_traits::msg_index_type message_index; handler_type handler; scoped_raw_handler handler_scope; std::vector > all_buffers; // Free and used, keeps ownership of them boost::mutex buffer_pool_lock; std::vector buffer_pool; std::vector outgoing_buffers_packed; // Packed using functions in detail boost::thread_specific_ptr buffers_to_swap_in; // One per thread message_buffer* create_buffer() { boost::shared_ptr buf = alloc_memory(engine, sizeof(message_buffer)); all_buffers.push_back(buf); message_buffer* result = (message_buffer*)buf.get(); result->elements_written = 0; return result; } message_buffer* alloc_buffer() { #if 0 boost::lock_guard l(buffer_pool_lock); if (buffer_pool.empty()) { return create_buffer(); } else { message_buffer* buf = buffer_pool.back(); buffer_pool.pop_back(); buf->elements_written = 0; return buf; } #endif return create_buffer(); } struct free_buffer { lock_free_coalesced_message_type_packed& mt; message_buffer* buf; free_buffer(lock_free_coalesced_message_type_packed& mt, message_buffer* buf): mt(mt), buf(buf) {} void operator()(const MPI_Status&) const { #if 0 boost::lock_guard l(mt.buffer_pool_lock); mt.buffer_pool.push_back(buf); #endif } }; }; } #endif // AMPLUSPLUS_LOCK_FREE_COALESCED_MESSAGE_TYPE_PACKED_HPP #ifndef BLISS_UINTSEQHASH_HH #define BLISS_UINTSEQHASH_HH #include /* Copyright (c) 2003-2015 Released under the GNU Lesser General Public License version 3. This file is part of bliss. bliss 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 3 of the License. bliss 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 bliss. If not, see . */ namespace bliss { /** \internal * \brief A hash for sequences of unsigned ints. */ class UintSeqHash { protected: unsigned int h; public: UintSeqHash() { h = 0; } UintSeqHash(const UintSeqHash &other) { h = other.h; } UintSeqHash &operator=(const UintSeqHash &other) { h = other.h; return *this; } /** Reset the hash value. */ void reset() { h = 0; } /** Add the unsigned int \a n to the sequence. */ void update(unsigned int n); /** Get the hash value of the sequence seen so far. */ unsigned int get_value() const { return h; } /** Compare the hash values of this and \a other. * Return -1/0/1 if the value of this is smaller/equal/greater than * that of \a other. */ int cmp(const UintSeqHash &other) const { return (h < other.h) ? -1 : ((h == other.h) ? 0 : 1); } /** An abbreviation for cmp(other) < 0 */ bool is_lt(const UintSeqHash &other) const { return (cmp(other) < 0); } /** An abbreviation for cmp(other) <= 0 */ bool is_le(const UintSeqHash &other) const { return (cmp(other) <= 0); } /** An abbreviation for cmp(other) == 0 */ bool is_equal(const UintSeqHash &other) const { return (cmp(other) == 0); } }; } // namespace bliss #endif akashhansda/llvm-projectlibc/src/math/generic/expf.cpp //===-- Single-precision e^x function -------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// #include "src/math/expf.h" #include "common_constants.h" // Lookup tables EXP_M1 and EXP_M2. #include "src/__support/FPUtil/BasicOperations.h" #include "src/__support/FPUtil/FEnvImpl.h" #include "src/__support/FPUtil/FMA.h" #include "src/__support/FPUtil/FPBits.h" #include "src/__support/FPUtil/PolyEval.h" #include "src/__support/common.h" #include namespace __llvm_libc { INLINE_FMA LLVM_LIBC_FUNCTION(float, expf, (float x)) { using FPBits = typename fputil::FPBits; FPBits xbits(x); uint32_t x_u = xbits.uintval(); uint32_t x_abs = x_u & 0x7fff'ffffU; // Exceptional values if (unlikely(x_u == 0xc236'bd8cU)) { // x = -0x1.6d7b18p+5f return 0x1.108a58p-66f - x * 0x1.0p-95f; } // When |x| >= 89, |x| < 2^-25, or x is nan if (unlikely(x_abs >= 0x42b2'0000U || x_abs <= 0x3280'0000U)) { // |x| < 2^-25 if (xbits.get_unbiased_exponent() <= 101) { return 1.0f + x; } // When x < log(2^-150) or nan if (xbits.uintval() >= 0xc2cf'f1b5U) { // exp(-Inf) = 0 if (xbits.is_inf()) return 0.0f; // exp(nan) = nan if (xbits.is_nan()) return x; if (fputil::get_round() == FE_UPWARD) return static_cast(FPBits(FPBits::MIN_SUBNORMAL)); errno = ERANGE; return 0.0f; } // x >= 89 or nan if (!xbits.get_sign() && (xbits.uintval() >= 0x42b2'0000)) { // x is finite if (xbits.uintval() < 0x7f80'0000U) { int rounding = fputil::get_round(); if (rounding == FE_DOWNWARD || rounding == FE_TOWARDZERO) return static_cast(FPBits(FPBits::MAX_NORMAL)); errno = ERANGE; } // x is +inf or nan return x + static_cast(FPBits::inf()); } } // For -104 < x < 89, to compute exp(x), we perform the following range // reduction: find hi, mid, lo such that: // x = hi + mid + lo, in which // hi is an integer, // mid * 2^7 is an integer // -2^(-8) <= lo < 2^-8. // In particular, // hi + mid = round(x * 2^7) * 2^(-7). // Then, // exp(x) = exp(hi + mid + lo) = exp(hi) * exp(mid) * exp(lo). // We store exp(hi) and exp(mid) in the lookup tables EXP_M1 and EXP_M2 // respectively. exp(lo) is computed using a degree-4 minimax polynomial // generated by Sollya. // x_hi = (hi + mid) * 2^7 = round(x * 2^7). // The default rounding mode for float-to-int conversion in C++ is // round-toward-zero. To make it round-to-nearest, we add (-1)^sign(x) * 0.5 // before conversion. int x_hi = static_cast(x * 0x1.0p7f + (xbits.get_sign() ? -0.5f : 0.5f)); // Subtract (hi + mid) from x to get lo. x -= static_cast(x_hi) * 0x1.0p-7f; double xd = static_cast(x); x_hi += 104 << 7; // hi = x_hi >> 7 double exp_hi = EXP_M1[x_hi >> 7]; // mid * 2^7 = x_hi & 0x0000'007fU; double exp_mid = EXP_M2[x_hi & 0x7f]; // Degree-4 minimax polynomial generated by Sollya with the following // commands: // > display = hexadecimal; // > Q = fpminimax(expm1(x)/x, 3, [|D...|], [-2^-8, 2^-8]); // > Q; double exp_lo = fputil::polyeval(xd, 0x1p0, 0x1.ffffffffff777p-1, 0x1.000000000071cp-1, 0x1.555566668e5e7p-3, 0x1.55555555ef243p-5); return static_cast(exp_hi * exp_mid * exp_lo); } } // namespace __llvm_libc /* This file belongs to the LibM2 library (http://github.com/imermcmaps/LibM2) * Copyright (c) 2013, iMer (www.imer.cc) * All rights reserved. * Licensed under the BSD 3-clause license (http://opensource.org/licenses/BSD-3-Clause) */ #ifndef __LIBM2_GAME_MISC_HPP #define __LIBM2_GAME_MISC_HPP #include "stdInclude.hpp" namespace libm2 { enum e_overtime { OT_NONE, OT_3HOUR, OT_5HOUR }; enum eFileUpdatedOptions { e_FileUpdate_None = -1, e_FileUpdate_Error, e_FileUpdate_Deleted, e_FileUpdate_Modified, e_FileUpdate_AttrModified, e_FileUpdate_Linked, e_FileUpdate_Renamed, e_FileUpdate_Revoked }; int get_global_time(); const char* locale_find(const char*); const char* two_arguments(const char * src, char * one, size_t size_one, char * two, size_t size_two); DWORD thecore_random(); int number_ex(int from, int to, const char* file, int line); void sys_err(const char *func, int line, const char *format, ...); void sys_log(unsigned int bit, char const* format, ...); long long MIN(long long val, long long val2); long long MINMAX(long long min, long long val, long long max); long long MAX(long long val, long long val2); void TransformRefineItem(LPITEM a1, LPITEM a2); void BroadcastNotice(const char *, ...); void SendNotice(const char *, ...); } #endif // __LIBM2_GAME_MISC_HPP /*============================================================================= NiftyLink: A software library to facilitate communication over OpenIGTLink. Copyright (c) University College London (UCL). All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt in the top level directory for details. =============================================================================*/ #include "NiftyLinkMessageContainer.h" #include #include #include "QsLog.h" #include "QsLogDest.h" #include namespace niftk { //----------------------------------------------------------------------------- NiftyLinkMessageContainer::NiftyLinkMessageContainer() : m_Message(NULL) , m_Id(0) , m_TimeArrived(0) , m_TimeReceived(0) , m_SenderHostName("") , m_SenderPortNumber(-1) , m_OwnerName("") { } //----------------------------------------------------------------------------- NiftyLinkMessageContainer::NiftyLinkMessageContainer(const NiftyLinkMessageContainer& another) { this->ShallowCopy(another); } //----------------------------------------------------------------------------- NiftyLinkMessageContainer& NiftyLinkMessageContainer::operator=(const NiftyLinkMessageContainer& another) { this->ShallowCopy(another); return *this; } //----------------------------------------------------------------------------- void NiftyLinkMessageContainer::ShallowCopy(const NiftyLinkMessageContainer& another) { m_Message = another.m_Message; m_Id = another.m_Id; m_SenderHostName = another.m_SenderHostName; m_SenderPortNumber = another.m_SenderPortNumber; m_OwnerName = another.m_OwnerName; m_TimeArrived = another.m_TimeArrived; m_TimeReceived = another.m_TimeReceived; } //----------------------------------------------------------------------------- NiftyLinkMessageContainer::~NiftyLinkMessageContainer(void) { } //----------------------------------------------------------------------------- igtlUint64 NiftyLinkMessageContainer::GetNiftyLinkMessageId() const { return m_Id; } //----------------------------------------------------------------------------- void NiftyLinkMessageContainer::SetMessage(igtl::MessageBase::Pointer mp) { assert(mp.IsNotNull()); m_Message = mp; } //----------------------------------------------------------------------------- igtl::MessageBase::Pointer NiftyLinkMessageContainer::GetMessage() const { return m_Message; } //----------------------------------------------------------------------------- void NiftyLinkMessageContainer::SetTimeArrived(const igtl::TimeStamp::Pointer& time) { m_TimeArrived = time->GetTimeStampInNanoseconds(); } //----------------------------------------------------------------------------- igtlUint64 NiftyLinkMessageContainer::GetTimeArrived() const { return m_TimeArrived; } //----------------------------------------------------------------------------- void NiftyLinkMessageContainer::SetTimeReceived(const igtl::TimeStamp::Pointer& time) { m_TimeReceived = time->GetTimeStampInNanoseconds(); } //----------------------------------------------------------------------------- igtlUint64 NiftyLinkMessageContainer::GetTimeReceived() const { return m_TimeReceived; } //----------------------------------------------------------------------------- void NiftyLinkMessageContainer::SetSenderHostName(const QString &host) { this->m_SenderHostName = host; } //----------------------------------------------------------------------------- QString NiftyLinkMessageContainer::GetSenderHostName() const { return m_SenderHostName; } //----------------------------------------------------------------------------- void NiftyLinkMessageContainer::SetSenderPortNumber(const int& portNumber) { this->m_SenderPortNumber = portNumber; } //----------------------------------------------------------------------------- int NiftyLinkMessageContainer::GetSenderPortNumber() const { return this->m_SenderPortNumber; } //----------------------------------------------------------------------------- void NiftyLinkMessageContainer::SetOwnerName(const QString& str) { this->m_OwnerName = str; } //----------------------------------------------------------------------------- QString NiftyLinkMessageContainer::GetOwnerName(void) { return this->m_OwnerName; } //----------------------------------------------------------------------------- void NiftyLinkMessageContainer::GetTimeCreated(igtl::TimeStamp::Pointer& time) const { assert(this->m_Message.IsNotNull()); this->m_Message->GetTimeStamp(time); } //----------------------------------------------------------------------------- igtlInt64 NiftyLinkMessageContainer::GetLatency() const { if (m_Message.IsNull()) { return 0; } igtlUint32 secCreated; igtlUint32 fracCreated; this->m_Message->GetTimeStamp(&secCreated, &fracCreated); igtlUint64 secCreatedInNano = static_cast(secCreated)*1000000000; igtlUint64 fracCreatedInNano = igtl_frac_to_nanosec(static_cast(fracCreated)); igtlUint64 timeCreated = secCreatedInNano + fracCreatedInNano; igtlInt64 latency = m_TimeReceived - timeCreated; // may be negative if clock shifts. return latency; } } // end namespace niftk #include #include "game_of_life.h" namespace cppchallenge::algorithms_data_structs::game_of_life { World::World(size_t width, size_t height) : width(width), height(height), _map(create_empty_world(width, height)) { } bool World::get(size_t x, size_t y) const { return _map[x][y]; } void World::set(size_t x, size_t y, bool value) { _map[y][x] = value; } void World::display(std::ostream &out) const { for (const auto& row : _map) { for (const auto& cell : row) { out << (cell ? 'x' : '.'); } out << '\n'; } } void World::simulate() { auto next_map = create_empty_world(width, height); for (auto y{0u}; y < height; ++y) { for (auto x{0u}; x < width; ++x) { auto neighbours = count_neighbours(x, y); if (_map[y][x]) { // die if underpopulated or overpopulated, live otherwise next_map[y][x] = !(neighbours < 2 || neighbours > 3); } else { // create life by reproduction next_map[y][x] = neighbours == 3; } } } _map = next_map; } size_t World::count_neighbours(size_t x, size_t y) const { auto neighbours{0u}; // xxx // ... // ... if (y > 0) { if (x > 0 && _map[y - 1][x - 1]) ++neighbours; if (_map[y - 1][x]) ++neighbours; if (x < width - 1 && _map[y - 1][x + 1]) ++neighbours; } // ... // x.x // ... if (x > 0 && _map[y][x - 1]) ++neighbours; if (x < width - 1 && _map[y][x + 1]) ++neighbours; // ... // ... // xxx if (y < height - 1) { if (x > 0 && _map[y + 1][x - 1]) ++neighbours; if (_map[y + 1][x]) ++neighbours; if (x < width - 1 && _map[y + 1][x + 1]) ++neighbours; } return neighbours; } World::world_data_type World::create_empty_world(size_t width, size_t height) { return std::vector>{height, std::vector(width)}; } void CrazyWorld::randomize(std::mt19937& mt) { std::uniform_int_distribution dist(0,1); for (auto y{0u}; y < height; ++y) { for (auto x{0u}; x < width; ++x) { set(x,y, dist(mt) % 2); } } } CrazyWorld::CrazyWorld(size_t width, size_t height) : World(width, height) {} } // Copyright (c) 2017-2020 // // Distributed under the MIT Software License // (See accompanying file LICENSE) #ifndef DSL_DATAACCESS_ACCESSPATTERNS_HPP #define DSL_DATAACCESS_ACCESSPATTERNS_HPP namespace HPM::AccessPatterns { //! \name //! AccessPatterns //! //! These patterns describe a topological relationship between some entity in the mesh with some other entity in the mesh. //! By providing them to access definitions in a loop the run time system is able to provide the correct local views to the kernels. //! //! \{ auto SimplePattern = [](auto&& entity) { return entity; }; auto NeighboringMeshElementOrSelfPattern = [](auto&& entity) { return entity.GetTopology().GetNeighboringCell(); }; auto ContainingMeshElementPattern = [](auto&& entity) { return entity.GetTopology().GetContainingCell(); }; //! \} } // namespace HPM::AccessPatterns #endiftools/clang/blink_gc_plugin/tests/trace_if_needed_resolved.cpp // 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 "trace_if_needed_resolved.h" namespace blink { void HeapObject::Trace(Visitor* visitor) { // Using TraceIfNeeded with a non-template type should count as tracing a // field. TraceIfNeeded>::Trace(visitor, m_one); TraceIfNeeded::Trace(visitor, m_two); } } // namespace blink #include "PostProcessRenderer.h" #include "MasterRenderer.h" #include "../Clock.h" namespace Atlas { namespace Renderer { PostProcessRenderer::PostProcessRenderer() { shader.AddStage(AE_VERTEX_STAGE, "postprocessing.vsh"); shader.AddStage(AE_FRAGMENT_STAGE, "postprocessing.fsh"); shader.Compile(); GetUniforms(); sharpenShader.AddStage(AE_COMPUTE_STAGE, "sharpen.csh"); sharpenShader.Compile(); sharpenFactor = sharpenShader.GetUniform("sharpenFactor"); } void PostProcessRenderer::Render(Viewport* viewport, RenderTarget* target, Camera* camera, Scene::Scene* scene) { target->postProcessFramebuffer.Bind(); auto& postProcessing = scene->postProcessing; auto& chromaticAberration = postProcessing.chromaticAberration; auto& vignette = postProcessing.vignette; auto& taa = postProcessing.taa; auto& sharpen = postProcessing.sharpen; bool hasFilmicTonemappingMacro = shader.HasMacro("FILMIC_TONEMAPPING"); bool hasVignetteMacro = shader.HasMacro("VIGNETTE"); bool hasChromaticAberrationMacro = shader.HasMacro("CHROMATIC_ABERRATION"); if (postProcessing.filmicTonemapping && !hasFilmicTonemappingMacro) { shader.AddMacro("FILMIC_TONEMAPPING"); } else if (!postProcessing.filmicTonemapping && hasFilmicTonemappingMacro) { shader.RemoveMacro("FILMIC_TONEMAPPING"); } if (postProcessing.vignette.enable && !hasVignetteMacro) { shader.AddMacro("VIGNETTE"); } else if (!postProcessing.vignette.enable && hasVignetteMacro) { shader.RemoveMacro("VIGNETTE"); } if (postProcessing.chromaticAberration.enable && !hasChromaticAberrationMacro) { shader.AddMacro("CHROMATIC_ABERRATION"); } else if (!postProcessing.chromaticAberration.enable && hasChromaticAberrationMacro) { shader.RemoveMacro("CHROMATIC_ABERRATION"); } shader.Bind(); ivec2 resolution = ivec2(target->GetWidth(), target->GetHeight()); hdrTextureResolution->SetValue(vec2(resolution)); exposure->SetValue(camera->exposure); saturation->SetValue(postProcessing.saturation); timeInMilliseconds->SetValue(1000.0f * Clock::Get()); if (chromaticAberration.enable) { float reversedValue = chromaticAberration.colorsReversed ? 1.0f : 0.0f; aberrationStrength->SetValue(chromaticAberration.strength); aberrationReversed->SetValue(reversedValue); } if (vignette.enable) { vignetteOffset->SetValue(vignette.offset); vignettePower->SetValue(vignette.power); vignetteStrength->SetValue(vignette.strength); vignetteColor->SetValue(vignette.color); } if (taa.enable) { target->GetHistory()->Bind(GL_TEXTURE0); } else { target->lightingFramebuffer.GetComponentTexture(GL_COLOR_ATTACHMENT0)->Bind(GL_TEXTURE0); } glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); target->postProcessFramebuffer.Unbind(); if (sharpen.enable) { sharpenShader.Bind(); ivec2 groupCount = resolution / 8; groupCount.x += ((groupCount.x * 8 == resolution.x) ? 0 : 1); groupCount.y += ((groupCount.y * 8 == resolution.y) ? 0 : 1); target->postProcessTexture.Bind(GL_WRITE_ONLY, 0); target->postProcessFramebuffer.GetComponentTexture(GL_COLOR_ATTACHMENT0)->Bind(GL_TEXTURE1); sharpenFactor->SetValue(sharpen.factor); glMemoryBarrier(GL_SHADER_IMAGE_ACCESS_BARRIER_BIT); glDispatchCompute(groupCount.x, groupCount.y, 1); } } void PostProcessRenderer::GetUniforms() { hdrTextureResolution = shader.GetUniform("hdrTextureResolution"); exposure = shader.GetUniform("exposure"); saturation = shader.GetUniform("saturation"); bloomPassses = shader.GetUniform("bloomPassses"); aberrationStrength = shader.GetUniform("aberrationStrength"); aberrationReversed = shader.GetUniform("aberrationReversed"); vignetteOffset = shader.GetUniform("vignetteOffset"); vignettePower = shader.GetUniform("vignettePower"); vignetteStrength = shader.GetUniform("vignetteStrength"); vignetteColor = shader.GetUniform("vignetteColor"); timeInMilliseconds = shader.GetUniform("timeInMilliseconds"); } } }10-100 #include #include #include #include #include "devices/GCodeDevice.h" #include "Job.h" #include "ui/FileChooser.h" #include "ui/DRO.h" #include "ui/GrblDRO.h" #include "InetServer.h" HardwareSerial PrinterSerial(2); #ifdef DEBUGF #undef DEBUGF #endif #define DEBUGF(...) { Serial.printf(__VA_ARGS__); } #define DEBUGFI(...) { log_printf(__VA_ARGS__); } #define DEBUGS(s) { Serial.println(s); } #define PIN_POT1 33 #define PIN_POT2 32 #define PIN_BT1 14 #define PIN_BT2 12 #define PIN_BT3 13 #define PIN_ENC1 26 #define PIN_ENC2 27 #define PIN_CE_SD 5 #define PIN_CE_LCD 4 #define PIN_RST_LCD 22 U8G2_ST7920_128X64_F_HW_SPI u8g2_{U8G2_R3, PIN_CE_LCD, PIN_RST_LCD}; U8G2 &Display::u8g2 = u8g2_; WebServer server; GCodeDevice *dev = nullptr; Job *job; enum class Mode { DRO, FILECHOOSER }; Display display; FileChooser fileChooser; uint8_t droBuffer[ sizeof(GrblDRO) ]; DRO *dro; Mode cMode = Mode::DRO; void encISR(); void bt1ISR(); void bt2ISR(); void bt3ISR(); bool detectPrinterAttempt(uint32_t speed, uint8_t type); void detectPrinter(); void deviceLoop(void* ); TaskHandle_t deviceTask; void wifiLoop(void * ); TaskHandle_t wifiTask; void setup() { Serial.begin(115200); pinMode(PIN_BT1, INPUT_PULLUP); pinMode(PIN_BT2, INPUT_PULLUP); pinMode(PIN_BT3, INPUT_PULLUP); pinMode(PIN_ENC1, INPUT_PULLUP); pinMode(PIN_ENC2, INPUT_PULLUP); attachInterrupt(PIN_ENC1, encISR, CHANGE); attachInterrupt(PIN_BT1, bt1ISR, CHANGE); attachInterrupt(PIN_BT2, bt2ISR, CHANGE); attachInterrupt(PIN_BT3, bt3ISR, CHANGE); u8g2_.begin(); u8g2_.setBusClock(600000); u8g2_.setFont(u8g2_font_5x8_tr); u8g2_.setFontPosTop(); u8g2_.setFontMode(1); digitalWrite(PIN_RST_LCD, LOW); delay(100); digitalWrite(PIN_RST_LCD, HIGH); Serial.print("Initializing SD card..."); if (!SD.begin(PIN_CE_SD)) { Serial.println("initialization failed!"); while (1); } Serial.println("initialization done."); DynamicJsonDocument cfg(512); File file = SD.open("/config.json"); DeserializationError error = deserializeJson(cfg, file); if (error) Serial.println(F("Failed to read file, using default configuration")); server.config( cfg["web"].as() ); server.add_observer(display); xTaskCreatePinnedToCore(deviceLoop, "DeviceTask", 4096, nullptr, 1, &deviceTask, 1); // cpu1 xTaskCreatePinnedToCore(wifiLoop, "WifiTask", 4096, nullptr, 1, &wifiTask, 1); // cpu1 job = Job::getJob(); job->add_observer( display ); //dro.config(cfg["menu"].as() ); fileChooser.begin(); fileChooser.setCallback( [&](bool res, String path){ if(res) { DEBUGF("Starting job %s\n", path.c_str() ); job->setFile(path); job->start(); Display::getDisplay()->setScreen(dro); // select file } else { Display::getDisplay()->setScreen(dro); // cancel } } ); file.close(); } void deviceLoop(void* pvParams) { PrinterSerial.begin(115200); PrinterSerial.setTimeout(1000); dev = DeviceDetector::detectPrinterAttempt(PrinterSerial, 115200, 1); if(dev==nullptr ) { dev = DeviceDetector::detectPrinter(PrinterSerial); } //GCodeDevice::setDevice(dev); dev->add_observer( *job ); dev->add_observer(display); //dev->add_observer(dro); // dro.setDevice(dev); //dev->add_observer(fileChooser); dev->addReceivedLineHandler( [](const char* d, size_t l) {server.resendDeviceResponse(d,l);} ); dev->begin(); if(dev->getType() == "grbl") { dro = new (droBuffer) GrblDRO(); } else dro = new (droBuffer) DRO(); dro->begin( ); display.setScreen(dro); while(1) { dev->loop(); } vTaskDelete( NULL ); } void wifiLoop(void* args) { server.begin(); vTaskDelete( NULL ); } void readPots() { Display::potVal[0] = analogRead(PIN_POT1); Display::potVal[1] = analogRead(PIN_POT2); } void loop() { readPots(); job->loop(); display.loop(); if(dev==nullptr) return; static String s; while(Serial.available()!=0) { char c = Serial.read(); if(c=='\n' || c=='\r') { if(s.length()>0) DEBUGF("send %s, result: %d\n", s.c_str(), dev->schedulePriorityCommand(s) ); s=""; continue; } s += c; } } IRAM_ATTR void encISR() { static int lastV1=0; static unsigned int lastISRTime = millis(); if(millis()(); GrGLSLFPFragmentBuilder* fragBuilder = args.fFragBuilder; SkString srgbFuncName; static const GrShaderVar gSrgbArgs[] = { GrShaderVar("x", kFloat_GrSLType), }; switch (srgbe.mode()) { case GrSRGBEffect::Mode::kLinearToSRGB: fragBuilder->emitFunction(kFloat_GrSLType, "linear_to_srgb", SK_ARRAY_COUNT(gSrgbArgs), gSrgbArgs, "return (x <= 0.0031308) ? (x * 12.92) " ": (1.055 * pow(x, 0.416666667) - 0.055);", &srgbFuncName); break; case GrSRGBEffect::Mode::kSRGBToLinear: fragBuilder->emitFunction(kFloat_GrSLType, "srgb_to_linear", SK_ARRAY_COUNT(gSrgbArgs), gSrgbArgs, "return (x <= 0.04045) ? (x / 12.92) " ": pow((x + 0.055) / 1.055, 2.4);", &srgbFuncName); break; } if (nullptr == args.fInputColor) { args.fInputColor = "vec4(1)"; } fragBuilder->codeAppendf("vec4 color = %s;", args.fInputColor); if (srgbe.alpha() == GrSRGBEffect::Alpha::kPremul) { fragBuilder->codeAppendf("float nonZeroAlpha = max(color.a, 0.00001);"); fragBuilder->codeAppendf("color = vec4(color.rgb / nonZeroAlpha, color.a);"); } fragBuilder->codeAppendf("color = vec4(%s(color.r), %s(color.g), %s(color.b), color.a);", srgbFuncName.c_str(), srgbFuncName.c_str(), srgbFuncName.c_str()); if (srgbe.alpha() == GrSRGBEffect::Alpha::kPremul) { fragBuilder->codeAppendf("color = vec4(color.rgb, 1) * color.a;"); } fragBuilder->codeAppendf("%s = color;", args.fOutputColor); } static inline void GenKey(const GrProcessor& processor, const GrShaderCaps&, GrProcessorKeyBuilder* b) { const GrSRGBEffect& srgbe = processor.cast(); uint32_t key = static_cast(srgbe.mode()) | (static_cast(srgbe.alpha()) << 1); b->add32(key); } private: typedef GrGLSLFragmentProcessor INHERITED; }; /////////////////////////////////////////////////////////////////////////////// GrSRGBEffect::GrSRGBEffect(Mode mode, Alpha alpha) : INHERITED(kPreservesOpaqueInput_OptimizationFlag | kConstantOutputForConstantInput_OptimizationFlag) , fMode(mode) , fAlpha(alpha) { this->initClassID(); } bool GrSRGBEffect::onIsEqual(const GrFragmentProcessor& s) const { const GrSRGBEffect& other = s.cast(); return other.fMode == fMode; } static inline float srgb_to_linear(float srgb) { return (srgb <= 0.04045f) ? srgb / 12.92f : powf((srgb + 0.055f) / 1.055f, 2.4f); } static inline float linear_to_srgb(float linear) { return (linear <= 0.0031308) ? linear * 12.92f : 1.055f * powf(linear, 1.f / 2.4f) - 0.055f; } GrColor4f GrSRGBEffect::constantOutputForConstantInput(GrColor4f color) const { color = color.unpremul(); switch (fMode) { case Mode::kLinearToSRGB: color = GrColor4f(linear_to_srgb(color.fRGBA[0]), linear_to_srgb(color.fRGBA[1]), linear_to_srgb(color.fRGBA[2]), color.fRGBA[3]); break; case Mode::kSRGBToLinear: color = GrColor4f(srgb_to_linear(color.fRGBA[0]), srgb_to_linear(color.fRGBA[1]), srgb_to_linear(color.fRGBA[2]), color.fRGBA[3]); break; } return color.premul(); } /////////////////////////////////////////////////////////////////////////////// GR_DEFINE_FRAGMENT_PROCESSOR_TEST(GrSRGBEffect); #if GR_TEST_UTILS sk_sp GrSRGBEffect::TestCreate(GrProcessorTestData* d) { Mode testMode = static_cast(d->fRandom->nextRangeU(0, 1)); return GrSRGBEffect::Make(testMode, Alpha::kPremul); } #endif /////////////////////////////////////////////////////////////////////////////// void GrSRGBEffect::onGetGLSLProcessorKey(const GrShaderCaps& caps, GrProcessorKeyBuilder* b) const { GrGLSRGBEffect::GenKey(*this, caps, b); } GrGLSLFragmentProcessor* GrSRGBEffect::onCreateGLSLInstance() const { return new GrGLSRGBEffect; } Gotta_Catch_Em_All.cpp #include using namespace std; int main() { int dp[202][202]; int points[202][202]; int row,column; cin >> row >> column; for(int i=0;i> points[i][j]; } } dp[row-1][column-1]=1; for (int i = row-2; i >= 0; i--) dp[i][column-1] = max(dp[i+1][column-1] - points[i][column-1], 1); for (int j = column-2; j >= 0; j--) dp[row-1][j] = max(dp[row-1][j+1] - points[row-1][j], 1); for (int i=row-2; i>=0; i--){ for (int j=column-2; j>=0; j--){ int minPoint = min(dp[i+1][j], dp[i][j+1]); dp[i][j] = max(minPoint - points[i][j], 1); } } cout << dp[0][0]; }MyMuduo/Lib/ThreadPool.cc #include "ThreadPool.h" #include "Exception.h" ThreadPool::ThreadPool( const string& nameArg) : m_nMutex(), m_nNotEmpty(m_nMutex), m_nNotFull(m_nMutex), m_strName(nameArg), m_nMaxQueueSize(0), m_bRunning(false) { } ThreadPool::~ThreadPool() { if (m_bRunning) { stop(); } } void ThreadPool::start(int numThreads) { assert(m_vecThreads.empty()); m_bRunning = true; m_vecThreads.reserve(numThreads); for (int i = 0; i < numThreads; ++i) { char id[32]; snprintf( id, sizeof(id), "%d", i+1); m_vecThreads.emplace_back( new Thread( std::bind( &ThreadPool::runInThread, this), m_strName+id)); m_vecThreads[i]->start(); } if (numThreads == 0 && m_nThreadInitCallback) { m_nThreadInitCallback(); } } void ThreadPool::stop() { { MutexLockGuard lock(m_nMutex); m_bRunning = false; m_nNotEmpty.notifyAll(); } for (auto& thr : m_vecThreads) { thr->join(); } } size_t ThreadPool::queueSize() const { MutexLockGuard lock(m_nMutex); return m_nQueue.size(); } void ThreadPool::run(Task task) { if (m_vecThreads.empty()) { task(); } else { MutexLockGuard lock(m_nMutex); while (isFull()) { m_nNotFull.wait(); } assert(!isFull()); m_nQueue.push_back(std::move(task)); m_nNotEmpty.notify(); } } ThreadPool::Task ThreadPool::take() { MutexLockGuard lock(m_nMutex); while (m_nQueue.empty() && m_bRunning) { m_nNotEmpty.wait(); } Task task; if (!m_nQueue.empty()) { task = m_nQueue.front(); m_nQueue.pop_front(); if (m_nMaxQueueSize > 0) { m_nNotFull.notify(); } } return task; } bool ThreadPool::isFull() const { m_nMutex.assertLocked(); return m_nMaxQueueSize > 0 && m_nQueue.size() >= m_nMaxQueueSize; } void ThreadPool::runInThread() { try { if (m_nThreadInitCallback) { m_nThreadInitCallback(); } while (m_bRunning) { Task task(take()); if (task) { task(); } } } catch (const Exception& ex) { fprintf( stderr, "exception caught in ThreadPool %s\n", m_strName.c_str()); fprintf( stderr, "reason: %s\n", ex.what()); fprintf( stderr, "stack trace: %s\n", ex.stackTrace()); abort(); } catch (const std::exception& ex) { fprintf( stderr, "exception caught in ThreadPool %s\n", m_strName.c_str()); fprintf( stderr, "reason: %s\n", ex.what()); abort(); } catch (...) { fprintf( stderr, "unknown exception caught in ThreadPool %s\n", m_strName.c_str()); throw; } } #include "Partie.hpp" using namespace std; Partie::Partie(int taille) { m_taille = taille; m_grille.resize(taille); for(int i = 0; i < taille; ++i) m_grille[i].resize(taille); initialiser(); m_nbCombos = 0; m_tirsRestants = 10; m_niveau = 1; } Partie::~Partie() { } void Partie::initialiser() { random_device rd; mt19937 gen(rd()); uniform_int_distribution valeurCase(0, m_taille-1); for(int i = 0; i < m_taille; ++i) for(int j = 0; j < m_taille; ++j) m_grille[i][j]= valeurCase(gen); } void Partie::afficher() const { cout<<"Nombre de tirs Restants : "<< m_tirsRestants<= 0) { if(m_grille[x][i] != 0) { if(m_grille[x][i] == 3) exploserCase(x, i); else ++m_grille[x][i]; break; } --i; } //Vers le bas i = y+1; while(i < m_taille) { if(m_grille[x][i] != 0) { if(m_grille[x][i] == 3) exploserCase(x, i); else ++m_grille[x][i]; break; } ++i; } //Vers la gauche i = x-1; while(i >=0) { if(m_grille[i][y] != 0) { if(m_grille[i][y] == 3) exploserCase(i, y); else ++m_grille[i][y]; break; } --i; } //Vers la droite i = x+1; while(i < m_taille) { if(m_grille[i][y] != 0) { if(m_grille[i][y] == 3) exploserCase(i, y); else ++m_grille[i][y]; break; } ++i; } } bool Partie::resolu() const { for(int i = 0; i < m_taille; ++i) for(int j = 0; j < m_taille; ++j) if(m_grille[i][j] != 0) return false; return true; } void Partie::majCombos() { if(m_nbCombos >= 2) m_tirsRestants += m_nbCombos - 1; m_nbCombos = 0; } void Partie::jouer() { int l, c; bool fin = false; while(!fin) { while(!resolu() && m_tirsRestants != 0) { afficher(); cout<<"ligne ?"<>l; cout<<"colonne ?"<>c; choixCaseConsole(l, c); majCombos(); } if(m_tirsRestants == 0) { cout<<"Perdu !"< #include "Sort.h" int main() { bool ascendent = false; int* vect = new int[5]{ 1,5,2,4,3 }; const char* string = "0,40,100,5,70"; Sort s1(5, 10, 20); Sort s3(vect, 5); Sort s4(6, 1, 6, 3, 5, 4, 2); Sort s5(string); s3.InsertSort(ascendent); s4.BubbleSort(ascendent); s5.QuickSort(ascendent); s3.Print(); s4.Print(); s5.Print(); delete[] vect; }0 #ifndef BOOST_SMART_PTR_DETAIL_SP_COUNTED_BASE_SOLARIS_HPP_INCLUDED #define BOOST_SMART_PTR_DETAIL_SP_COUNTED_BASE_SOLARIS_HPP_INCLUDED // // detail/sp_counted_base_solaris.hpp // based on: detail/sp_counted_base_w32.hpp // // Copyright (c) 2001, 2002, 2003 and Multi Media Ltd. // Copyright 2004-2005 // Copyright 2006 // // 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) // // // Lock-free algorithm by // // Thanks to for the #weak + (#shared != 0) // formulation // #include #include #include namespace boost { namespace detail { class BOOST_SYMBOL_VISIBLE sp_counted_base { private: sp_counted_base(sp_counted_base const &); sp_counted_base &operator=(sp_counted_base const &); uint32_t use_count_; // #shared uint32_t weak_count_; // #weak + (#shared != 0) public: sp_counted_base() : use_count_(1), weak_count_(1) {} virtual ~sp_counted_base() // nothrow {} // dispose() is called when use_count_ drops to zero, to release // the resources managed by *this. virtual void dispose() = 0; // nothrow // destroy() is called when weak_count_ drops to zero. virtual void destroy() // nothrow { delete this; } virtual void *get_deleter(sp_typeinfo_ const &ti) = 0; virtual void *get_local_deleter(sp_typeinfo_ const &ti) = 0; virtual void *get_untyped_deleter() = 0; void add_ref_copy() { atomic_inc_32(&use_count_); } bool add_ref_lock() // true on success { for (;;) { uint32_t tmp = static_cast(use_count_); if (tmp == 0) return false; if (atomic_cas_32(&use_count_, tmp, tmp + 1) == tmp) return true; } } void release() // nothrow { if (atomic_dec_32_nv(&use_count_) == 0) { dispose(); weak_release(); } } void weak_add_ref() // nothrow { atomic_inc_32(&weak_count_); } void weak_release() // nothrow { if (atomic_dec_32_nv(&weak_count_) == 0) { destroy(); } } long use_count() const // nothrow { return static_cast(use_count_); } }; } // namespace detail } // namespace boost #endif // #ifndef BOOST_SMART_PTR_DETAIL_SP_COUNTED_BASE_SOLARIS_HPP_INCLUDED /* * Copyright (C) 2018 Microchip Technology Inc. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 */ #include "egt/tools.h" #include #include #include namespace egt { inline namespace v1 { namespace experimental { static void get_cpu_times(std::vector& times) { std::ifstream in("/proc/stat"); if (in.is_open()) { in.ignore(5, ' '); size_t time{}; while (in >> time) times.push_back(time); } } static bool get_cpu_times(size_t& idle_time, size_t& total_time) { static std::vector times; times.clear(); get_cpu_times(times); if (times.size() < 4) return false; idle_time = times[3]; total_time = std::accumulate(times.begin(), times.end(), static_cast(0)); return true; } void CPUMonitorUsage::update() { size_t idle_time{}; size_t total_time{}; if (get_cpu_times(idle_time, total_time)) { const double idle_time_diff = idle_time - m_last_idle_time; const double total_time_diff = total_time - m_last_total_time; m_cpu_usage = 100.0 * (1.0 - idle_time_diff / total_time_diff); m_last_idle_time = idle_time; m_last_total_time = total_time; } } } } } #include #include namespace zap::fetchers { struct curl_context; class curl : public zap::fetcher { public: curl(const zap::env_paths& ep); virtual ~curl(); void download( const std::string& url, const std::string& dir ) const final; private: void download(curl_context& ctx) const; }; } #include "etl/stm32f4xx/rcc.h" #include "etl/assert.h" #include "etl/armv7m/instructions.h" #include "etl/stm32f4xx/flash.h" using etl::armv7m::data_synchronization_barrier; namespace etl { namespace stm32f4xx { void Rcc::enter_reset(ApbPeripheral p) { unsigned bus = get_bus_index(p); unsigned slot = get_slot_index(p); switch (bus) { case 0: write_apb1rstr(read_apb1rstr().with_bit(slot, true)); break; case 1: write_apb2rstr(read_apb2rstr().with_bit(slot, true)); break; } data_synchronization_barrier(); } void Rcc::leave_reset(ApbPeripheral p) { unsigned bus = get_bus_index(p); unsigned slot = get_slot_index(p); switch (bus) { case 0: write_apb1rstr(read_apb1rstr().with_bit(slot, false)); break; case 1: write_apb2rstr(read_apb2rstr().with_bit(slot, false)); break; } data_synchronization_barrier(); } void Rcc::enable_clock(ApbPeripheral p) { unsigned bus = get_bus_index(p); unsigned slot = get_slot_index(p); switch (bus) { case 0: write_apb1enr(read_apb1enr().with_bit(slot, true)); break; case 1: write_apb2enr(read_apb2enr().with_bit(slot, true)); break; } data_synchronization_barrier(); } void Rcc::disable_clock(ApbPeripheral p) { unsigned bus = get_bus_index(p); unsigned slot = get_slot_index(p); switch (bus) { case 0: write_apb1enr(read_apb1enr().with_bit(slot, false)); break; case 1: write_apb2enr(read_apb2enr().with_bit(slot, false)); break; } data_synchronization_barrier(); } void Rcc::enter_reset(AhbPeripheral p) { unsigned bus = get_bus_index(p); unsigned slot = get_reset_index(p); switch (bus) { case 0: write_ahb1rstr(read_ahb1rstr().with_bit(slot, true)); break; case 1: write_ahb2rstr(read_ahb2rstr().with_bit(slot, true)); break; case 2: write_ahb3rstr(read_ahb3rstr().with_bit(slot, true)); break; } data_synchronization_barrier(); } void Rcc::leave_reset(AhbPeripheral p) { unsigned bus = get_bus_index(p); unsigned slot = get_reset_index(p); switch (bus) { case 0: write_ahb1rstr(read_ahb1rstr().with_bit(slot, false)); break; case 1: write_ahb2rstr(read_ahb2rstr().with_bit(slot, false)); break; case 2: write_ahb3rstr(read_ahb3rstr().with_bit(slot, false)); break; } data_synchronization_barrier(); } void Rcc::enable_clock(AhbPeripheral p) { unsigned bus = get_bus_index(p); unsigned slot = get_enable_index(p); switch (bus) { case 0: write_ahb1enr(read_ahb1enr().with_bit(slot, true)); break; case 1: write_ahb2enr(read_ahb2enr().with_bit(slot, true)); break; case 2: write_ahb3enr(read_ahb3enr().with_bit(slot, true)); break; } data_synchronization_barrier(); } void Rcc::disable_clock(AhbPeripheral p) { unsigned bus = get_bus_index(p); unsigned slot = get_enable_index(p); switch (bus) { case 0: write_ahb1enr(read_ahb1enr().with_bit(slot, false)); break; case 1: write_ahb2enr(read_ahb2enr().with_bit(slot, false)); break; case 2: write_ahb3enr(read_ahb3enr().with_bit(slot, false)); break; } data_synchronization_barrier(); } static ClockSpeeds clock_speeds; static Rcc::cfgr_value_t::hpre_t get_hpre(unsigned divisor) { switch (divisor) { #define X(x) case x: return Rcc::cfgr_value_t::hpre_t::div ## x; X( 1) X( 2) X( 4) X( 8) X( 16) X( 64) X(128) X(256) X(512) #undef X default: ETL_ASSERT(false); } } static Rcc::pprex_t get_ppre(unsigned divisor) { switch (divisor) { #define X(x) case x: return Rcc::pprex_t::div ## x; X( 1) X( 2) X( 4) X( 8) X( 16) #undef X default: ETL_ASSERT(false); } } float Rcc::get_cpu_clock_hz() const { return clock_speeds.cpu; } float Rcc::get_ahb_clock_hz() const { return clock_speeds.ahb; } float Rcc::get_apb1_clock_hz() const { return clock_speeds.apb1; } float Rcc::get_apb2_clock_hz() const { return clock_speeds.apb2; } float Rcc::get_pll48_clock_hz() const { return clock_speeds.pll48; } float Rcc::get_clock_hz(ApbPeripheral p) const { unsigned bus = get_bus_index(p); switch (bus) { case 0: return clock_speeds.apb1; case 1: return clock_speeds.apb2; default: ETL_ASSERT(false); } } void Rcc::configure_clocks(ClockConfig const &cfg) { cfg.compute_speeds(&clock_speeds); auto prescalers = cfgr_value_t() .with_hpre(get_hpre(cfg.ahb_divisor)) .with_ppre1(get_ppre(cfg.apb1_divisor)) .with_ppre2(get_ppre(cfg.apb2_divisor)); // Switch to the internal 16MHz oscillator while messing with the PLL. write_cr(read_cr().with_hsion(true)); while (!read_cr().get_hsirdy()); // Wait for it to stabilize. write_cfgr(read_cfgr().with_sw(cfgr_value_t::sw_t::hsi)); while (read_cfgr().get_sws() != cfgr_value_t::sws_t::hsi); // Wait for it. // Turn off the PLL. write_cr(read_cr().with_pllon(false)); while (read_cr().get_pllrdy()); // Wait for it to unlock. // Apply divisors before boosting frequency. write_cfgr(read_cfgr() .with_hpre(prescalers.get_hpre()) .with_ppre1(prescalers.get_ppre1()) .with_ppre2(prescalers.get_ppre2())); flash.write_acr(flash.read_acr().with_latency(cfg.flash_latency)); // Switch on the crystal oscillator. write_cr(read_cr().with_hseon(true)); while (!read_cr().get_hserdy()); // Wait for it. // Configure the PLL. auto pllp = pllcfgr_value_t::pllp_t((cfg.general_divisor >> 1) - 1); write_pllcfgr(read_pllcfgr() .with_pllm(cfg.crystal_divisor) .with_plln(cfg.vco_multiplier) .with_pllp(pllp) .with_pllq(cfg.pll48_divisor) .with_pllsrc(pllcfgr_value_t::pllsrc_t::hse)); // Turn it on. write_cr(read_cr().with_pllon(true)); while (!read_cr().get_pllrdy()); // Select PLL as clock source. write_cfgr(read_cfgr().with_sw(cfgr_value_t::sw_t::pll)); while (read_cfgr().get_sws() != cfgr_value_t::sws_t::pll); } void ClockConfig::compute_speeds(ClockSpeeds *out) const { float vco_in_hz = crystal_hz / static_cast(crystal_divisor); float vco_out_hz = vco_in_hz * static_cast(vco_multiplier); out->cpu = vco_out_hz / static_cast(general_divisor); out->pll48 = vco_out_hz / static_cast(pll48_divisor); out->ahb = out->cpu / static_cast(ahb_divisor); out->apb1 = out->cpu / static_cast(apb1_divisor); out->apb2 = out->cpu / static_cast(apb2_divisor); } } // namespace stm32f4xx } // namespace etl Robotic_Arm_Code/Project/Arm.cpp #include "Arm.h" Arm::Arm() {} Arm::~Arm() {} void Arm::init() { // Sets components initial values _frontArmServo.init(FRONT_ARM_SERVO_PIN, _frontArmMinAngle, _frontArmMaxAngle); _backArmServo.init(BACK_ARM_SERVO_PIN, _backArmMinAngle, _backArmMaxAngle); _myClaw.init(); // Sets arm initial position _myClaw.open(); _frontArmServo.moveToPosition(_FrontArmPosition.RETRACTED); _backArmServo.moveToPosition(_BackArmPosition.RETRACTED); // Sets arm initial state _isGrabbing = false; } void Arm::toggle() { if (_isGrabbing){ // Move arm to release position _frontArmServo.moveToPosition(_FrontArmPosition.REACHING); _backArmServo.moveToPosition(_BackArmPosition.REACHING); delay(500); _myClaw.open(); delay(500); _frontArmServo.moveToPosition(_FrontArmPosition.RETRACTED); _backArmServo.moveToPosition(_BackArmPosition.RETRACTED); _isGrabbing = false; } else { // Move arm to grabbing position _frontArmServo.moveToPosition(_FrontArmPosition.REACHING); _backArmServo.moveToPosition(_BackArmPosition.REACHING); delay(500); _myClaw.close(); delay(500); _frontArmServo.moveToPosition(_FrontArmPosition.RAISED); _backArmServo.moveToPosition(_BackArmPosition.RAISED); _isGrabbing = true; } } // Copyright (C) 2018-2022 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include #include "low_precision_transformations/move_fake_quantize_transformation.hpp" #include "common_test_utils/test_constants.hpp" using namespace LayerTestsDefinitions; const std::vector netPrecisions = { ngraph::element::f32, //ngraph::element::f16 }; const std::vector trasformationParamValues = { LayerTestsUtils::LayerTransformationParamsNGraphFactory::createParams().setUpdatePrecisions(true) }; namespace testValues1 { const std::vector params = { // without operation { 3, "", { 256ul, {}, {0.f}, {2.55f}, {0.f}, {2.55f}}, {}, {}, "Concatenation", "U8", 1, }, // with ReLU operation { 3, "relu", { 256ul, {}, { -12.7f }, { 12.7f }, { -12.7f }, { 12.7f }}, {}, {}, "Concatenation", "U8", 1 }, // Q/DQ { 3, "", { 256ul, {}, {0.f}, {2.55f}, {0.f}, {255.f} }, { ngraph::element::u8 }, { { ngraph::element::f32 }, {}, { 0.01f } }, "Concatenation", "U8", 1 }, // Q/DQ with ReLU { 3, "relu", { 256ul, {}, {0.f}, {2.55f}, {0.f}, {255.f} }, { ngraph::element::u8 }, { { ngraph::element::f32 }, {}, { 0.01f } }, "Concatenation", "U8", 1 }, // multi-chanels { 3, "relu", { 256ul, {{1, 6, 1, 1}, {1, 6, 1, 1}, {1, 6, 1, 1}, {1, 6, 1, 1}}, {0.f, 0.f, 0.f, 0.f, 0.f, 0.f}, {2.55f, 2.55f / 2.f, 2.55f / 3.f, 2.55f / 4.f, 2.55f / 5.f, 2.55f / 6.f}, {-128.f, -128.f, -128.f, -128.f, -128.f, -128.f}, {127.f, 127.f, 127.f, 127.f, 127.f, 127.f} }, {}, {}, "Concatenation", "I8", 1 }, // Q/DQ with multi-channels multiply { 3, "", { 256ul, {{1, 6, 1, 1}, {1, 6, 1, 1}, {1, 6, 1, 1}, {1, 6, 1, 1}}, {0.f, 0.f, 0.f, 0.f, 0.f, 0.f}, {2.55f, 2.55f / 2.f, 2.55f / 3.f, 2.55f / 4.f, 2.55f / 5.f, 2.55f / 6.f}, {0.f, 0.f, 0.f, 0.f, 0.f, 0.f}, {255.f, 255.f / 2.f, 255.f / 3.f, 255.f / 4.f, 255.f / 5.f, 255.f / 6.f}, }, { ngraph::element::u8 }, { { ngraph::element::f32 }, {}, { {0.01f, 0.02f, 0.03f, 0.04f, 0.05f, 0.06f}, ngraph::element::f32, {1, 6, 1, 1} }, }, "Concatenation", "U8", 1 }, // Q/DQ with multi-channels subtract { 3, "", { 256ul, {{1, 6, 1, 1}, {1, 6, 1, 1}, {1, 6, 1, 1}, {1, 6, 1, 1}}, {0.f, 0.f, 0.f, 0.f, 0.f, 0.f}, {2.55f, 2.55f / 2.f, 2.55f / 3.f, 2.55f / 4.f, 2.55f / 5.f, 2.55f / 6.f}, {0.f, 0.f, 0.f, 0.f, 0.f, 0.f}, {255.f, 255.f / 2.f, 255.f / 3.f, 255.f / 4.f, 255.f / 5.f, 255.f / 6.f}, }, { ngraph::element::u8 }, { { ngraph::element::f32 }, { {-127.f, -127.f / 2.f, -127.f / 3.f, -127.f / 4.f, -127.f / 5.f, -127.f / 6.f}, ngraph::element::f32, {1, 6, 1, 1} }, { 0.01f }, }, "Concatenation", "U8", 1 }, }; const std::vector> shapes = { {{ 1, 1, 16, 16 }, { 1, 2, 16, 16 }, { 1, 3, 16, 16 }}, {{ 4, 1, 16, 16 }, { 4, 2, 16, 16 }, { 4, 3, 16, 16 }} }; INSTANTIATE_TEST_SUITE_P(smoke_LPT, MoveFakeQuantizeTransformation, ::testing::Combine( ::testing::ValuesIn(netPrecisions), ::testing::ValuesIn(shapes), ::testing::Values(CommonTestUtils::DEVICE_CPU), ::testing::ValuesIn(trasformationParamValues), ::testing::ValuesIn({false, true}), ::testing::ValuesIn(params)), MoveFakeQuantizeTransformation::getTestCaseName); } // namespace testValues1 namespace testValues2 { const std::vector params = { // negative axis { 3, "", {256ul, {}, {-1.28f}, {1.27f}, {-1.28f}, {1.27f}}, {}, {}, "Concatenation", "FP32", -1 }, }; const std::vector> shapes = { {{ 1, 1, 16, 16 }, { 1, 1, 16, 16 }, { 1, 1, 16, 16 }}, {{ 4, 1, 16, 16 }, { 4, 1, 16, 16 }, { 4, 1, 16, 16 }} }; INSTANTIATE_TEST_SUITE_P(smoke_LPT, MoveFakeQuantizeTransformation, ::testing::Combine( ::testing::ValuesIn(netPrecisions), ::testing::ValuesIn(shapes), ::testing::Values(CommonTestUtils::DEVICE_CPU), ::testing::ValuesIn(trasformationParamValues), ::testing::ValuesIn({false}), ::testing::ValuesIn(params)), MoveFakeQuantizeTransformation::getTestCaseName); } // namespace testValues2 0 #define _USE_MATH_DEFINES #include #include "GestureListener.h" GestureListener::GestureListener() : onArm(false), isUnlocked(false), roll_w(0), pitch_w(0), yaw_w(0), currentPose() { } // onUnpair() is called whenever the Myo is disconnected from Myo Connect by the user. void GestureListener::onUnpair(myo::Myo* myo, uint64_t timestamp) { // We've lost a Myo. // Let's clean up some leftover state. roll_w = 0; pitch_w = 0; yaw_w = 0; onArm = false; isUnlocked = false; } // onOrientationData() is called whenever the Myo device provides its current orientation, which is represented // as a unit quaternion. void GestureListener::onOrientationData(myo::Myo* myo, uint64_t timestamp, const myo::Quaternion& quat) { using std::atan2; using std::asin; using std::sqrt; using std::max; using std::min; // Calculate Euler angles (roll, pitch, and yaw) from the unit quaternion. float roll = atan2(2.0f * (quat.w() * quat.x() + quat.y() * quat.z()), 1.0f - 2.0f * (quat.x() * quat.x() + quat.y() * quat.y())); float pitch = asin(max(-1.0f, min(1.0f, 2.0f * (quat.w() * quat.y() - quat.z() * quat.x())))); float yaw = atan2(2.0f * (quat.w() * quat.z() + quat.x() * quat.y()), 1.0f - 2.0f * (quat.y() * quat.y() + quat.z() * quat.z())); // Convert the floating point angles in radians to a scale from 0 to 18. roll_w = static_cast((roll + (float)M_PI) / (M_PI * 2.0f) * 18); pitch_w = static_cast((pitch + (float)M_PI / 2.0f) / M_PI * 18); yaw_w = static_cast((yaw + (float)M_PI) / (M_PI * 2.0f) * 18); } // onPose() is called whenever the Myo detects that the person wearing it has changed their pose, for example, // making a fist, or not making a fist anymore. void GestureListener::onPose(myo::Myo* myo, uint64_t timestamp, myo::Pose pose) { currentPose = pose; if (pose != myo::Pose::unknown && pose != myo::Pose::rest) { // Tell the Myo to stay unlocked until told otherwise. We do that here so you can hold the poses without the // Myo becoming locked. myo->unlock(myo::Myo::unlockHold); // Notify the Myo that the pose has resulted in an action, in this case changing // the text on the screen. The Myo will vibrate. myo->notifyUserAction(); } else { // Tell the Myo to stay unlocked only for a short period. This allows the Myo to stay unlocked while poses // are being performed, but lock after inactivity. myo->unlock(myo::Myo::unlockTimed); } } // onArmSync() is called whenever Myo has recognized a Sync Gesture after someone has put it on their // arm. This lets Myo know which arm it's on and which way it's facing. void GestureListener::onArmSync(myo::Myo* myo, uint64_t timestamp, myo::Arm arm, myo::XDirection xDirection, float rotation, myo::WarmupState warmupState) { onArm = true; whichArm = arm; } // onArmUnsync() is called whenever Myo has detected that it was moved from a stable position on a person's arm after // it recognized the arm. Typically this happens when someone takes Myo off of their arm, but it can also happen // when Myo is moved around on the arm. void GestureListener::onArmUnsync(myo::Myo* myo, uint64_t timestamp) { onArm = false; } // onUnlock() is called whenever Myo has become unlocked, and will start delivering pose events. void GestureListener::onUnlock(myo::Myo* myo, uint64_t timestamp) { isUnlocked = true; } // onLock() is called whenever Myo has become locked. No pose events will be sent until the Myo is unlocked again. void GestureListener::onLock(myo::Myo* myo, uint64_t timestamp) { isUnlocked = false; } // There are other virtual functions in DeviceListener that we could override here, like onAccelerometerData(). // For this example, the functions overridden above are sufficient. // We define this function to print the current values that were updated by the on...() functions above. void GestureListener::print() { // Clear the current line std::cout << '\r'; // Print out the orientation. Orientation data is always available, even if no arm is currently recognized. std::cout << '[' << std::string(roll_w, '*') << std::string(18 - roll_w, ' ') << ']' << '[' << std::string(pitch_w, '*') << std::string(18 - pitch_w, ' ') << ']' << '[' << std::string(yaw_w, '*') << std::string(18 - yaw_w, ' ') << ']'; if (onArm) { // Print out the lock state, the currently recognized pose, and which arm Myo is being worn on. // Pose::toString() provides the human-readable name of a pose. We can also output a Pose directly to an // output stream (e.g. std::cout << currentPose;). In this case we want to get the pose name's length so // that we can fill the rest of the field with spaces below, so we obtain it as a string using toString(). std::string poseString = currentPose.toString(); std::cout << '[' << (isUnlocked ? "unlocked" : "locked ") << ']' << '[' << (whichArm == myo::armLeft ? "L" : "R") << ']' << '[' << poseString << std::string(14 - poseString.size(), ' ') << ']'; } else { // Print out a placeholder for the arm and pose when Myo doesn't currently know which arm it's on. std::cout << '[' << std::string(8, ' ') << ']' << "[?]" << '[' << std::string(14, ' ') << ']'; } std::cout << std::flush; } /* * defs.cpp */ #if defined(mikroXmega) #if __AVR_XMEGA__ #include #endif #include "defs.h" #include #include #include #include #include ioSetCfgGpio(rf_dio_1, "rf_dio_1", pin_mux_convert_to_pin(IOB, 0),CfgGpio::GPIO_IN_PULL_UP, false, false, 0); ioSetCfgGpio(rf_dio_2, "rf_dio_2", pin_mux_convert_to_pin(IOB, 1),CfgGpio::GPIO_IN_PULL_UP, false, false, 0); ioSetCfgGpio(rf_dio_3, "rf_dio_3", pin_mux_convert_to_pin(IOB, 2),CfgGpio::GPIO_IN_PULL_UP, false, false, 0); ioSetCfgGpio(rf_dio_4, "rf_dio_4", pin_mux_convert_to_pin(IOB, 3),CfgGpio::GPIO_IN_PULL_UP, false, false, 0); ioSetCfgGpio(rf_dio_5, "rf_dio_5", pin_mux_convert_to_pin(IOB, 4),CfgGpio::GPIO_IN_PULL_UP, false, false, 0); ioSetCfgGpio(rf_rst, "rf_rst", pin_mux_convert_to_pin(IOE, 2),CfgGpio::GPIO_OUT_PUSH_PULL, false, false, 0); ioSetCfgGpio(rf_irq, "rf_irq", pin_mux_convert_to_pin(IOE, 3),CfgGpio::GPIO_IN_PULL_UP, false, false, 0); ioSetCfgUart(uart_0, "uart-0", pin_mux_convert_to_pin(IOC, 3) , pin_mux_convert_to_pin(IOC, 2) , 2000000 , CfgUart::WORD_LEN_8 , CfgUart::STOP_BITS_ONE , CfgUart::PAR_NONE , CfgUart::MODE_ASYNC); //ioSetCfgI2c(i2c_0, "i2c-0", pin_mux_convert_to_pin(IOB, 8), pin_mux_convert_to_pin(IOB, 9), 100000); ioSetCfgSpi(spi_2_0, "spi-2.0", pin_mux_convert_to_pin(IOE, 5), pin_mux_convert_to_pin(IOE, 7), pin_mux_convert_to_pin(IOE, 6), pin_mux_convert_to_pin(IOE, 4), CfgSpi::spiMode0, 25000000, false); ioSetCfgSpi(spi_3_0, "spi-3.0", pin_mux_convert_to_pin(IOF, 5), pin_mux_convert_to_pin(IOF, 7), pin_mux_convert_to_pin(IOF, 6), pin_mux_convert_to_pin(IOF, 4), CfgSpi::spiMode0, 25000000, false); ioSetCfgEnd(ioTableEnd); ioSettings *ioSetCfg[] = { &rf_dio_1, &rf_dio_2, &rf_dio_3, &rf_dio_4, &rf_dio_5, &rf_rst, &rf_irq, &uart_0, //&i2c_0, &spi_2_0, &spi_3_0, &ioTableEnd, (ioSettings *)-1/* This is an artifice to force linker to put this structure ito .data section, to be secure that this will be initiated before the call of init() function. */ }; #endif/*!FRDM_KEAZ*/ virtuald/allwpilibwpilibc/shared/src/Buttons/Trigger.cpp /*----------------------------------------------------------------------------*/ /* Copyright (c) FIRST 2011-2016. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ /*----------------------------------------------------------------------------*/ #include "Buttons/Button.h" #include "Buttons/CancelButtonScheduler.h" #include "Buttons/HeldButtonScheduler.h" #include "Buttons/PressedButtonScheduler.h" #include "Buttons/ReleasedButtonScheduler.h" #include "Buttons/ToggleButtonScheduler.h" using namespace frc; bool Trigger::Grab() { if (Get()) { return true; } else if (m_table != nullptr) { return m_table->GetBoolean("pressed", false); } else { return false; } } void Trigger::WhenActive(Command* command) { auto pbs = new PressedButtonScheduler(Grab(), this, command); pbs->Start(); } void Trigger::WhileActive(Command* command) { auto hbs = new HeldButtonScheduler(Grab(), this, command); hbs->Start(); } void Trigger::WhenInactive(Command* command) { auto rbs = new ReleasedButtonScheduler(Grab(), this, command); rbs->Start(); } void Trigger::CancelWhenActive(Command* command) { auto cbs = new CancelButtonScheduler(Grab(), this, command); cbs->Start(); } void Trigger::ToggleWhenActive(Command* command) { auto tbs = new ToggleButtonScheduler(Grab(), this, command); tbs->Start(); } std::string Trigger::GetSmartDashboardType() const { return "Button"; } void Trigger::InitTable(std::shared_ptr subtable) { m_table = subtable; if (m_table != nullptr) { m_table->PutBoolean("pressed", Get()); } } std::shared_ptr Trigger::GetTable() const { return m_table; } 1-10 /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "mitkExceptionMacro.h" #include "mitkModelFitParameterValueExtraction.h" #include "QmitkFitParameterModel.h" QmitkFitParameterModel:: QmitkFitParameterModel(QObject* parent) : QAbstractTableModel(parent) { m_CurrentPos.Fill(0.0); } const QmitkFitParameterModel::FitVectorType& QmitkFitParameterModel:: getFits() const { return m_Fits; }; mitk::Point3D QmitkFitParameterModel:: getCurrentPosition() const { return m_CurrentPos; }; const mitk::PointSet* QmitkFitParameterModel:: getPositionBookmarks() const { return m_Bookmarks; }; void QmitkFitParameterModel:: setFits(const FitVectorType& fits) { emit beginResetModel(); m_Fits = fits; emit endResetModel(); }; void QmitkFitParameterModel:: setCurrentPosition(const mitk::Point3D& currentPos) { emit beginResetModel(); m_CurrentPos = currentPos; emit endResetModel(); }; void QmitkFitParameterModel:: setPositionBookmarks(const mitk::PointSet* bookmarks) { emit beginResetModel(); m_Bookmarks = bookmarks; emit endResetModel(); }; bool QmitkFitParameterModel:: hasSingleFit() const { return this->m_Fits.size() == 1; }; int QmitkFitParameterModel:: rowCount(const QModelIndex& parent) const { if (this->hasSingleFit()) { if (parent.isValid()) { return 0; } else { return this->m_Fits.front()->GetParameters().size() + this->m_Fits.front()->staticParamMap.Size(); } } else { if (parent.isValid()) { auto row = static_cast(parent.row()); assert(row < this->m_Fits.size()); return this->m_Fits[row]->GetParameters().size() + this->m_Fits[row]->staticParamMap.Size(); } else { return this->m_Fits.size(); } } } std::size_t QmitkFitParameterModel:: getBookmarksCount() const { if (m_Bookmarks.IsNotNull()) { return m_Bookmarks->GetSize(); } return 0; } int QmitkFitParameterModel:: columnCount(const QModelIndex&) const { return 3 + this->getBookmarksCount(); } /** Helper function returns the name of the static parameter indicates by the index. If the index does not indicate a static parameter an empty string will be returned.*/ std::string GetStaticParameterName(const mitk::modelFit::ModelFitInfo* currentFit, const QModelIndex& index) { const auto paramSize = static_cast(currentFit->GetParameters().size()); std::string staticParamName; if (index.row() >= paramSize) { int pos = paramSize; for (const auto& iter : currentFit->staticParamMap) { if (pos == index.row()) { staticParamName = iter.first; break; } ++pos; } } return staticParamName; } QVariant QmitkFitParameterModel:: data(const QModelIndex& index, int role) const { if (!index.isValid()) { return QVariant(); } QVariant result; if (!index.parent().isValid() && !this->hasSingleFit()) { //we need the fit names if (index.row() < static_cast(m_Fits.size()) && index.column() == 0) { if (role == Qt::DisplayRole || role == Qt::EditRole) { result = QVariant(QString::fromStdString(m_Fits[index.row()]->fitName)+QString("(") + QString::fromStdString(m_Fits[index.row()]->uid) + QString(")")); } else if (role == Qt::ToolTipRole) { result = QVariant("Name (UID) of the fit."); } } } else { // realy want to get the values of the current fit const mitk::modelFit::ModelFitInfo* currentFit = nullptr; if (this->hasSingleFit() && !index.parent().isValid()) { currentFit = m_Fits.front(); } else if (index.parent().isValid() && index.parent().row() < static_cast(m_Fits.size())) { currentFit = m_Fits[index.parent().row()]; } if (currentFit) { const auto paramSize = static_cast(currentFit->GetParameters().size()); const auto staticParamSize = static_cast(currentFit->staticParamMap.Size()); if (index.row() < paramSize + staticParamSize) { std::string staticParamName = GetStaticParameterName(currentFit, index); switch (index.column()) { case 0: if (role == Qt::DisplayRole || role == Qt::EditRole) { if (index.row() < paramSize) { const auto& param = currentFit->GetParameters()[index.row()]; result = QVariant(QString::fromStdString(param->name)); } else { result = QVariant(QString::fromStdString(staticParamName)); } } else if (role == Qt::ToolTipRole) { result = QVariant("Name of the parameter."); } break; case 1: if (role == Qt::DisplayRole || role == Qt::EditRole) { if (index.row() < paramSize) { const auto& param = currentFit->GetParameters()[index.row()]; std::string paramType = mitk::ModelFitConstants::PARAMETER_TYPE_VALUE_PARAMETER(); if (param->type == mitk::modelFit::Parameter::DerivedType) { paramType = mitk::ModelFitConstants::PARAMETER_TYPE_VALUE_DERIVED_PARAMETER(); } else if (param->type == mitk::modelFit::Parameter::CriterionType) { paramType = mitk::ModelFitConstants::PARAMETER_TYPE_VALUE_CRITERION(); } else if (param->type == mitk::modelFit::Parameter::EvaluationType) { paramType = mitk::ModelFitConstants::PARAMETER_TYPE_VALUE_EVALUATION_PARAMETER(); } result = QVariant(QString::fromStdString(paramType)); } else { result = QVariant("static"); } } else if (role == Qt::ToolTipRole) { result = QVariant("Type of the parameter."); } break; default: if (index.column() - 2 < static_cast(this->getBookmarksCount()+1)) { mitk::Point3D pos = m_CurrentPos; if (index.column() > 2) { pos = m_Bookmarks->GetPoint(index.column() - 3); } if (role == Qt::DisplayRole || role == Qt::EditRole) { if (index.row() < paramSize) { auto value = mitk::ReadVoxel(currentFit->GetParameters()[index.row()]->image, pos); result = QVariant(QString::number(value)); } else { auto value = currentFit->staticParamMap.Get(staticParamName).front(); result = QVariant(QString::number(value)); } } else if (role == Qt::ToolTipRole) { result = QVariant("Value of a (static) fit parameter"); } } break; } } } } return result; } Qt::ItemFlags QmitkFitParameterModel:: flags(const QModelIndex& index) const { Qt::ItemFlags flags = QAbstractItemModel::flags(index); return flags; } QVariant QmitkFitParameterModel:: headerData(int section, Qt::Orientation orientation, int role) const { if ((Qt::DisplayRole == role) && (Qt::Horizontal == orientation)) { if (section == 0) { return QVariant("Name"); } else if (section == 1) { return QVariant("Type"); } else if (section == 2) { return QVariant("Value"); } else if (section - 3 < static_cast(this->getBookmarksCount())) { const auto & pos = m_Bookmarks->GetPoint(section - 3); std::ostringstream strm; strm.imbue(std::locale("C")); strm << std::setprecision(3) << "Value @ Pos " << section -3 << " (" << pos[0] << "|" << pos[1] << "|" << pos[2] << ")"; return QVariant(QString::fromStdString(strm.str())); } } return QVariant(); } bool QmitkFitParameterModel:: setData(const QModelIndex&, const QVariant&, int) { return false; }; #include #include "cut_the_sticks.h" namespace hackerrank { namespace bmgandre { namespace algorithms { namespace implementation { using cut_the_sticks_test = hackerrank::bmgandre::tests::hackerrank_gtest; TEST_F(cut_the_sticks_test, test_case_1) { input_stream << "6\n5 4 4 2 2 8"; cut_the_sticks::solve(); std::string output = output_stream.str(); ASSERT_EQ(output, "6\n4\n2\n1\n"); } TEST_F(cut_the_sticks_test, test_case_2) { input_stream << "8\n1 2 3 4 3 3 2 1"; cut_the_sticks::solve(); std::string output = output_stream.str(); ASSERT_EQ(output, "8\n6\n4\n1\n"); } } // namespace implementation } // namespace algorithms } // namespace bmgandre } // namespace hackerrank int main(int argc, char** argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } #include "stdafx.h" #include "CDM.h" #include "MasteringFileDialog.h" #include "IsoCreator.h" #include "CreateProgressDialog.h" #include "WriteSettingDialog.h" #include "WriteProgressDialog.h" #include "Setting.h" // test #include "ThemeController.h" #include ".\masteringfiledialog.h" #define STR(i) (theSetting.m_Lang.m_Str[LP_MASTERING + i]) IMPLEMENT_DYNAMIC ( CMasteringFileDialog, CDialog ) CMasteringFileDialog::CMasteringFileDialog ( CWnd* pParent /*=NULL*/ ) : CDialog ( CMasteringFileDialog::IDD, pParent ) , m_LogWnd ( NULL ) , m_Size ( _T ( "" ) ) { m_LeadOutPos = 0; m_TrackList = & ( m_Page1.m_TrackList ); m_VolumeLabel = & ( m_Page2.m_VolumeLabel ); m_List = & ( m_Page2.m_List ); m_Tree = & ( m_Page2.m_Tree ); m_ImageSize = 0; } CMasteringFileDialog::~CMasteringFileDialog() { } void CMasteringFileDialog::DoDataExchange ( CDataExchange* pDX ) { CDialog::DoDataExchange ( pDX ); DDX_Control ( pDX, IDC_TAB, m_Tab ); DDX_Text ( pDX, IDC_IMAGESIZE, m_Size ); DDX_Control ( pDX, IDC_DRIVELIST, m_DriveList ); } BEGIN_MESSAGE_MAP ( CMasteringFileDialog, CDialog ) ON_COMMAND ( ID_EDIT_ADDFOLDER, OnEditAddfolder ) ON_COMMAND ( ID_EDIT_LABEL, OnEditLabel ) ON_COMMAND ( ID_EDIT_DELETEFOLDER, OnEditDeletefolder ) ON_COMMAND ( ID_EDIT_ADDFILE, OnEditAddfile ) ON_BN_CLICKED ( IDC_CREATE_ISO, OnBnClickedCreateIso ) ON_BN_CLICKED ( IDOK, OnBnClickedOk ) ON_COMMAND ( ID_EDIT_ADDAUDIO, OnEditAddaudio ) ON_COMMAND ( ID_EDIT_DELETETRACK, OnEditDeletetrack ) ON_COMMAND ( ID_EDIT_ADDDATA, OnEditAdddata ) ON_NOTIFY ( TCN_SELCHANGE, IDC_TAB, OnTcnSelchangeTab ) ON_BN_CLICKED ( IDC_WRITING, OnBnClickedWriting ) ON_COMMAND ( ID_WINDOW_CLOSE, OnWindowClose ) ON_COMMAND ( ID_EDIT_INSERTFOLDER, OnEditInsertfolder ) ON_WM_SETFOCUS() ON_COMMAND ( ID_TRACK_ISO, OnTrackIso ) ON_BN_CLICKED ( IDC_EXPLORER, OnBnClickedExplorer ) ON_CBN_SELCHANGE ( IDC_DRIVELIST, OnCbnSelchangeDrivelist ) ON_COMMAND ( ID_CD_ERASE, OnCdErase ) ON_COMMAND ( ID_CD_ERASE_FAST, OnCdEraseFast ) END_MESSAGE_MAP() BOOL CMasteringFileDialog::OnInitDialog() { CDialog::OnInitDialog(); m_Dir.m_RealFileName = "image.iso"; m_Dir.m_ImageFileName = "ISO_Image:\\"; m_Tab.InsertItem ( 0, STR ( 3 ) ); m_Tab.InsertItem ( 1, STR ( 4 ) ); m_Tab.InsertItem ( 2, STR ( 19 ) ); m_Tab.SetCurSel ( 1 ); m_Size = STR ( 5 ) + " 00:00:00"; SetLanguage(); m_Page1.m_MainDialog = this; m_Page2.m_Dir = &m_Dir; m_Page2.m_Page1 = &m_Page1; m_Page2.m_MainDialog = this; m_Page3.m_MainDialog = this; m_Page1.Create ( IDD_MASTERING_1, this ); m_Page2.Create ( IDD_MASTERING_2, this ); m_Page3.Create ( IDD_MASTERING_3, this ); m_TrackList = & ( m_Page1.m_TrackList ); theTheme.EnableThemeDialogTexture ( m_Page1.m_hWnd, ETDT_ENABLETAB ); theTheme.EnableThemeDialogTexture ( m_Page2.m_hWnd, ETDT_ENABLETAB ); theTheme.EnableThemeDialogTexture ( m_Page3.m_hWnd, ETDT_ENABLETAB ); ChangeTab(); UpdateDialog ( FALSE ); CalcSize(); m_Tab.SetWindowPos ( &wndBottom, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE ); m_DriveList.InitializeShortVer ( m_CD->GetAspiCtrl() ); m_DriveList.SetCurSel ( m_CD->GetAspiCtrl()->GetCurrentDevice() ); if ( theSetting.m_Mastering_AlwaysOnTop ) { SetWindowPos ( &wndTopMost, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE ); } return TRUE; // return TRUE unless you set the focus to a control } void CMasteringFileDialog::OnEditAddfolder() { if ( m_Page2.GetStyle() & 0x10000000 ) { CString cs; int i; HTREEITEM ht; ht = m_Tree->GetSelectedItem(); for ( i = 0; i < 100; i++ ) { if ( i == 0 ) { cs = MSG ( 83 ); } else { cs.Format ( MSG ( 84 ), i ); } if ( m_Page2.AddFolder ( cs ) ) { m_Tree->Expand ( ht, TVE_EXPAND ); break; } } } } void CMasteringFileDialog::OnEditLabel() { if ( m_Page2.GetStyle() & 0x10000000 ) { int id; POSITION pos; pos = m_List->GetFirstSelectedItemPosition(); if ( pos != NULL ) { id = m_List->GetNextSelectedItem ( pos ); m_List->EditLabel ( id ); } } } void CMasteringFileDialog::OnEditDeletefolder() { if ( m_Page2.GetStyle() & 0x10000000 ) { m_Page2.DeleteSelectedItems(); } } void CMasteringFileDialog::OnEditAddfile() { if ( m_Page2.GetStyle() & 0x10000000 ) { CFileDialog Dlg ( TRUE ); UpdateDialog ( TRUE ); if ( Dlg.DoModal() == IDOK ) { m_Page2.AddFile ( Dlg.GetPathName() ); } UpdateDialog ( FALSE ); CalcSize(); } } void CMasteringFileDialog::OnBnClickedOk() { OnOK(); } void CMasteringFileDialog::OnEditAddaudio() { if ( m_Page1.GetStyle() & 0x10000000 ) { m_Page1.InsertWaveAudioTrack(); } return; } void CMasteringFileDialog::OnEditDeletetrack() { if ( m_Page1.GetStyle() & 0x10000000 ) { m_Page1.DeleteSelectedTracks(); } return; } void CMasteringFileDialog::OnEditAdddata() { if ( m_Page1.GetStyle() & 0x10000000 ) { m_Page1.InsertMode1MasteringTrack(); m_Tab.SetCurSel ( 1 ); ChangeTab(); } } void CMasteringFileDialog::OnTrackIso() { if ( m_Page1.GetStyle() & 0x10000000 ) { CFileDialog dlg ( TRUE, NULL, NULL, OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT | OFN_ALLOWMULTISELECT, MSG ( 90 ) ); char buf[2048]; char *p; m_Page1.UpdateData ( TRUE ); buf[0] = '\0'; p = dlg.m_ofn.lpstrFile; dlg.m_ofn.lpstrFile = buf; dlg.m_ofn.nMaxFile = 2048; if ( dlg.DoModal() == IDOK ) { m_Page1.InsertIsoTrack ( dlg.GetPathName() ); } dlg.m_ofn.lpstrFile = p; m_Page1.UpdateData ( FALSE ); CalcSize(); } } void CMasteringFileDialog::OnTcnSelchangeTab ( NMHDR *pNMHDR, LRESULT *pResult ) { *pResult = 0; ChangeTab(); } void CMasteringFileDialog::OnBnClickedCreateIso() { CFileDialog Dlg ( FALSE, ".cue", "", OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT, MSG ( 91 ) ); UpdateDialog ( TRUE ); if ( m_TrackList->GetItemCount() == 0 ) { MessageBox ( MSG ( 92 ), CONF_MSG ); return; } SetWindowPos ( &wndNoTopMost, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE ); if ( Dlg.DoModal() == IDOK ) { CCreateProgressDialog CreateDlg; CreateDlg.CreateIso ( Dlg.GetPathName(), ( LPCSTR ) ( *m_VolumeLabel ), m_TrackList, &m_Dir, m_LogWnd ); } if ( theSetting.m_Mastering_AlwaysOnTop ) { SetWindowPos ( &wndTopMost, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE ); } } void CMasteringFileDialog::OnBnClickedWriting() { CWriteSettingDialog Dlg; UpdateDialog ( TRUE ); if ( m_TrackList->GetItemCount() == 0 ) { MessageBox ( MSG ( 93 ), CONF_MSG ); return; } CalcSize(); if ( m_LeadOutPos > 0 && m_ImageSize > ( m_LeadOutPos - 150 ) ) { if ( MessageBox ( STR ( 5 ), CONF_MSG, MB_YESNO ) == IDNO ) { return; } } SetWindowPos ( &wndNoTopMost, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE ); Dlg.m_CD = m_CD; Dlg.m_CueSheetName = MSG ( 94 ); Dlg.m_DisableChangingFile = true; if ( Dlg.DoModal() == IDOK ) { CWriteProgressDialog WriteDlg; WriteDlg.Mastering ( &m_Dir, ( LPCSTR ) ( *m_VolumeLabel ), m_TrackList, m_CD, m_LogWnd ); } if ( theSetting.m_Mastering_AlwaysOnTop ) { SetWindowPos ( &wndTopMost, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE ); } } void CMasteringFileDialog::GetLeadOutPos ( void ) { BYTE Buffer[400]; memset ( Buffer, 0, 400 ); if ( m_CD->ReadATIP ( Buffer ) ) { m_LeadOutPos = ( ( Buffer[12] * 60 ) + Buffer[13] ) * 75 + Buffer[14]; } else { m_LeadOutPos = 0; } } void CMasteringFileDialog::CalcSize ( void ) { MSFAddress msf; DWORD size; int i; UpdateData ( TRUE ); size = 0; for ( i = 0; i < m_TrackList->GetItemCount(); i++ ) { if ( m_TrackList->GetItemData ( i ) == 0 ) { CString tt; tt = m_Page1.m_TrackList.GetItemText ( 0, 1 ); if ( tt == "Mastering" ) { CIsoCreator iso; iso.SetParams ( "", theSetting.m_CopyProtectionSize ); iso.CreateJolietHeader ( &m_Dir ); size += iso.GetImageSize(); } else { DWORD FileSize; HANDLE hFile; CString cs; cs = m_TrackList->GetItemText ( i, 2 ); hFile = CreateFile ( cs, 0, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL ); FileSize = GetFileSize ( hFile, NULL ); CloseHandle ( hFile ); if ( tt == "MODE1/2048" ) { size += FileSize / 2048; } else if ( tt == "MODE1/2352" || tt == "MODE2/2352" ) { size += FileSize / 2352; } } } else { HANDLE hFile; CString cs; cs = m_TrackList->GetItemText ( i, 2 ); hFile = CreateFile ( cs, 0, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL ); size += ( GetFileSize ( hFile, NULL ) + 2352 - 45 ) / 2352; CloseHandle ( hFile ); } } msf = size; m_ImageSize = size; GetLeadOutPos(); if ( m_LeadOutPos == 0 ) { m_Size.Format ( "%02d:%02d:%02d / **:**:**", msf.Minute, msf.Second, msf.Frame ); } else { MSFAddress lo; lo = m_LeadOutPos - 150; m_Size.Format ( "%02d:%02d:%02d / %02d:%02d:%02d", msf.Minute, msf.Second, msf.Frame, lo.Minute, lo.Second, lo.Frame ); } UpdateData ( FALSE ); } void CMasteringFileDialog::SetLanguage ( void ) { int i; DWORD MenuString[][2] = { {IDCANCEL , 4}, {ID_CREATE_IMAGE , 5}, {ID_CREATE_CD , 6}, {ID_EDIT_ADDDATA , 7}, {ID_EDIT_ADDAUDIO , 8}, {ID_EDIT_DELETETRACK , 9}, {ID_EDIT_ADDFOLDER , 10}, {ID_EDIT_ADDFILE , 11}, {ID_EDIT_DELETEFOLDER , 12}, {ID_EDIT_LABEL , 13}, {ID_EDIT_INSERTFOLDER , 14}, {ID_TRACK_ISO , 15}, {IDC_EXPLORER , 16}, }; DWORD CtrlString[][2] = { {IDC_CREATE_ISO , 6}, {IDC_WRITING , 7}, {IDCANCEL , 8}, {IDC_SELECTDRIVE , 20}, {IDC_EXPLORER , 24}, }; for ( i = 0; i < 4; i++ ) { GetMenu()->ModifyMenu ( i, MF_BYPOSITION | MF_STRING, 0, theSetting.m_Lang.m_Str[LP_MASTERINGMENU + i] ); } for ( i = 0; i < 13; i++ ) { GetMenu()->ModifyMenu ( MenuString[i][0], MF_BYCOMMAND | MF_STRING, MenuString[i][0], theSetting.m_Lang.m_Str[LP_MASTERINGMENU + MenuString[i][1]] ); } SetWindowText ( STR ( 0 ) ); for ( i = 0; i < 5; i++ ) { this->SetDlgItemText ( CtrlString[i][0], STR ( CtrlString[i][1] ) ); } GetMenu()->ModifyMenu ( ID_CD_ERASE, MF_BYCOMMAND | MF_STRING, ID_CD_ERASE, theSetting.m_Lang.m_Str[LP_MAINMENU + 9] ); GetMenu()->ModifyMenu ( ID_CD_ERASE_FAST, MF_BYCOMMAND | MF_STRING, ID_CD_ERASE_FAST, theSetting.m_Lang.m_Str[LP_MAINMENU + 10] ); this->SetDlgItemText ( ID_CD_ERASE, theSetting.m_Lang.m_Str[LP_MAINMENU + 9] ); this->SetDlgItemText ( ID_CD_ERASE_FAST, theSetting.m_Lang.m_Str[LP_MAINMENU + 10] ); } void CMasteringFileDialog::OnWindowClose() { OnOK(); } void CMasteringFileDialog::OnEditInsertfolder() { if ( m_Page2.GetStyle() & 0x10000000 ) { UpdateDialog ( TRUE ); BROWSEINFO brinfo; LPMALLOC p; LPITEMIDLIST brid; char PathList[MAX_PATH + 1]; char PathName[MAX_PATH]; PathList[0] = '\0'; PathName[0] = '\0'; SHGetMalloc ( &p ); brinfo.hwndOwner = m_hWnd; brinfo.pidlRoot = NULL; brinfo.pszDisplayName = PathList; brinfo.lpszTitle = STR ( 18 ); brinfo.ulFlags = BIF_RETURNONLYFSDIRS; brinfo.lpfn = NULL; brid = SHBrowseForFolder ( &brinfo ); if ( brid ) { SHGetPathFromIDList ( brid, PathName ); p->Free ( brid ); m_Page2.AddFileRec ( PathName ); } else { return; } UpdateDialog ( FALSE ); CalcSize(); } } void CMasteringFileDialog::ChangeTab ( void ) { m_Page1.ShowWindow ( SW_HIDE ); m_Page2.ShowWindow ( SW_HIDE ); m_Page3.ShowWindow ( SW_HIDE ); if ( m_Tab.GetCurSel() == 0 ) { m_Page1.ShowWindow ( SW_SHOW ); } else if ( m_Tab.GetCurSel() == 1 ) { m_Page2.ShowWindow ( SW_SHOW ); } else if ( m_Tab.GetCurSel() == 2 ) { m_Page3.ShowWindow ( SW_SHOW ); } } void CMasteringFileDialog::UpdateDialog ( bool bSaveAndValidate ) { m_Page1.UpdateData ( bSaveAndValidate ); m_Page2.UpdateData ( bSaveAndValidate ); m_Page3.UpdateData ( bSaveAndValidate ); UpdateData ( bSaveAndValidate ); } void CMasteringFileDialog::OnSetFocus ( CWnd* pOldWnd ) { CDialog::OnSetFocus ( pOldWnd ); if ( m_Tab.GetCurSel() == 0 ) { m_Page1.SetFocus(); } else if ( m_Tab.GetCurSel() == 1 ) { m_Page2.SetFocus(); } else if ( m_Tab.GetCurSel() == 2 ) { m_Page3.SetFocus(); } } void CMasteringFileDialog::OnBnClickedExplorer() { ShellExecute ( m_hWnd, "explore", NULL, NULL, NULL, SW_SHOWNORMAL ); } void CMasteringFileDialog::OnCbnSelchangeDrivelist() { int Index; Index = m_DriveList.GetCurSel(); if ( Index == CB_ERR ) { return; } m_CD->GetAspiCtrl()->SetDevice ( Index ); GetLeadOutPos(); CalcSize(); } void CMasteringFileDialog::OnCancel() { CDialog::OnCancel(); } void CMasteringFileDialog::OnOK() { // CDialog::OnOK(); } void CMasteringFileDialog::OnCdErase() { GetParent()->SendMessage ( WM_COMMAND, ID_CD_ERASE, 0 ); } void CMasteringFileDialog::OnCdEraseFast() { GetParent()->SendMessage ( WM_COMMAND, ID_CD_ERASE_FAST, 0 ); } // // Copyright (C) 2008 by sinamas // // 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 version 2 for more details. // // You should have received a copy of the GNU General Public License // version 2 along with this program; if not, write to the // Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. // #include "quartztoggler.h" #include #include #include static bool operator!=(ResInfo const &l, ResInfo const &r) { return l.w != r.w || l.h != r.h; } static bool operator>(ResInfo const &l, ResInfo const &r) { return l.w > r.w || (l.w == r.w && l.h > r.h); } static void addMode(CFDictionaryRef mode, std::vector &infoVector, std::size_t *resIndex, std::size_t *rateIndex) { ResInfo info; short rate; { int w = 0; int h = 0; double r = 0.0; CFNumberGetValue(CFNumberRef(CFDictionaryGetValue(mode, kCGDisplayWidth)), kCFNumberIntType, &w); CFNumberGetValue(CFNumberRef(CFDictionaryGetValue(mode, kCGDisplayHeight)), kCFNumberIntType, &h); CFNumberGetValue(CFNumberRef(CFDictionaryGetValue(mode, kCGDisplayRefreshRate)), kCFNumberDoubleType, &r); info.w = w; info.h = h; rate = static_cast(r * 10.0 + 0.5); } std::vector::iterator it = std::lower_bound(infoVector.begin(), infoVector.end(), info, std::greater()); if (it == infoVector.end() || *it != info) it = infoVector.insert(it, info); std::vector::iterator rateIt = std::lower_bound(it->rates.begin(), it->rates.end(), rate, std::greater()); if (rateIt == it->rates.end() || *rateIt != rate) rateIt = it->rates.insert(rateIt, rate); if (resIndex) *resIndex = std::distance(infoVector.begin(), it); if (rateIndex) *rateIndex = std::distance(it->rates.begin(), rateIt); } QuartzToggler::QuartzToggler() : originalMode() , widgetScreen(0) , isFull(false) { CGDisplayCount dspyCnt = 0; CGGetActiveDisplayList(0, 0, &dspyCnt); activeDspys.reset(dspyCnt); CGGetActiveDisplayList(dspyCnt, activeDspys, &dspyCnt); infoVector.resize(dspyCnt); fullResIndex.resize(dspyCnt); fullRateIndex.resize(dspyCnt); for (CGDisplayCount i = 0; i < dspyCnt; ++i) { CGDirectDisplayID display = activeDspys[i]; CFDictionaryRef currentMode = CGDisplayCurrentMode(display); CFArrayRef modesArray = CGDisplayAvailableModes(display); CFIndex numModes = CFArrayGetCount(modesArray); CFNumberRef bpp = CFNumberRef(CFDictionaryGetValue(currentMode, kCGDisplayBitsPerPixel)); for (CFIndex j = 0; j < numModes; ++j) { CFDictionaryRef mode = CFDictionaryRef(CFArrayGetValueAtIndex(modesArray, j)); CFNumberRef mbpp = CFNumberRef(CFDictionaryGetValue(mode, kCGDisplayBitsPerPixel)); if (CFNumberCompare(bpp, mbpp, 0) == kCFCompareEqualTo) addMode(mode, infoVector[i], 0, 0); } } originalMode = CGDisplayCurrentMode(activeDspys[widgetScreen]); for (CGDisplayCount i = 0; i < dspyCnt; ++i) { std::size_t resIndex = 0; std::size_t rateIndex = 0; addMode(CGDisplayCurrentMode(activeDspys[i]), infoVector[i], &resIndex, &rateIndex); fullResIndex[i] = resIndex; fullRateIndex[i] = rateIndex; } } QRect const QuartzToggler::fullScreenRect(QWidget const *) const { CGRect r = CGDisplayBounds(activeDspys[widgetScreen]); return QRectF(r.origin.x, r.origin.y, r.size.width, r.size.height).toRect(); } void QuartzToggler::setScreen(QWidget const *widget) { std::size_t n = QApplication::desktop()->screenNumber(widget); if (n != widgetScreen && n < infoVector.size()) { if (isFullMode()) { setFullMode(false); widgetScreen = n; setFullMode(true); } else { widgetScreen = n; emitRate(); } } } void QuartzToggler::setMode(std::size_t screen, std::size_t resIndex, std::size_t rateIndex) { fullResIndex[screen] = resIndex; fullRateIndex[screen] = rateIndex; if (isFullMode() && screen == widgetScreen) setFullMode(true); } void QuartzToggler::setFullMode(bool const enable) { CGDirectDisplayID display = activeDspys[widgetScreen]; CFDictionaryRef currentMode = CGDisplayCurrentMode(display); CFDictionaryRef mode = currentMode; if (enable) { int bpp = 0; CFNumberGetValue( CFNumberRef(CFDictionaryGetValue(currentMode, kCGDisplayBitsPerPixel)), kCFNumberIntType, &bpp); mode = CGDisplayBestModeForParametersAndRefreshRate( display, bpp, infoVector[widgetScreen][fullResIndex[widgetScreen]].w, infoVector[widgetScreen][fullResIndex[widgetScreen]].h, infoVector[widgetScreen][fullResIndex[widgetScreen]].rates[fullRateIndex[widgetScreen]] / 10.0, 0); if (!isFull) originalMode = currentMode; } else if (isFull) mode = originalMode; if (mode != currentMode) { CGDisplaySwitchToMode(display, mode); double oldRate = 0.0; double newRate = 0.0; CFNumberGetValue( CFNumberRef(CFDictionaryGetValue(currentMode, kCGDisplayRefreshRate)), kCFNumberDoubleType, &oldRate); CFNumberGetValue( CFNumberRef(CFDictionaryGetValue(mode, kCGDisplayRefreshRate)), kCFNumberDoubleType, &newRate); if (static_cast(oldRate * 10.0 + 0.5) != static_cast(newRate * 10.0 + 0.5)) emit rateChange(static_cast(newRate * 10.0 + 0.5)); } isFull = enable; } void QuartzToggler::emitRate() { double rate = 0.0; CFDictionaryRef mode = CGDisplayCurrentMode(activeDspys[widgetScreen]); CFNumberGetValue(CFNumberRef(CFDictionaryGetValue(mode, kCGDisplayRefreshRate)), kCFNumberDoubleType, &rate); emit rateChange(static_cast(rate * 10.0 + 0.5)); } RenderX/src/RenderX/Utils/FileDialogs.cpp #include "pch.h" #define GLFW_EXPOSE_NATIVE_WIN32 #include #include #include "FileDialogs.h" #include "../Base/Window.h" namespace renderx::utils { std::string FileDialogs::OpenFile(const std::string& path) { OPENFILENAMEA ofn; //common dialog box structure CHAR szFile[260] = { 0 }; //initialize OPENFILENAME ZeroMemory(&ofn, sizeof(OPENFILENAME)); ofn.lStructSize = sizeof(OPENFILENAME); ofn.hwndOwner = glfwGetWin32Window(base::Window::Get()->GetNativeWindow()); ofn.lpstrFile = szFile; ofn.nMaxFile = sizeof(szFile); ofn.lpstrFilter = path.c_str(); ofn.nFilterIndex = 1; ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_NOCHANGEDIR; if (GetOpenFileNameA(&ofn) == TRUE) { return ofn.lpstrFile; } return std::string(); } std::string FileDialogs::GetFileName(const std::string& path) { std::string name = ""; int index = path.size() - 1; if (index != -1) { while (path[index] != '.') { index--; } index--; while (path[index] != '\\') { name += path[index]; index--; } } std::reverse(name.begin(), name.end()); return name; } std::string FileDialogs::GetRawNameOfRenderer(const std::string& name) { std::string rawName; int index = 0; while (name[index]!='_') { rawName += name[index]; index++; } return rawName; } }android-31/java/util/concurrent/PriorityBlockingQueue.cpp #include "../../../JLongArray.hpp" #include "../../../JObjectArray.hpp" #include "../../io/ObjectInputStream.hpp" #include "../../io/ObjectOutputStream.hpp" #include "../../../JObject.hpp" #include "../../../JString.hpp" #include "../PriorityQueue.hpp" #include "./TimeUnit.hpp" #include "./locks/ReentrantLock.hpp" #include "./PriorityBlockingQueue.hpp" namespace java::util::concurrent { // Fields // QJniObject forward PriorityBlockingQueue::PriorityBlockingQueue(QJniObject obj) : java::util::AbstractQueue(obj) {} // Constructors PriorityBlockingQueue::PriorityBlockingQueue() : java::util::AbstractQueue( "java.util.concurrent.PriorityBlockingQueue", "()V" ) {} PriorityBlockingQueue::PriorityBlockingQueue(jint arg0) : java::util::AbstractQueue( "java.util.concurrent.PriorityBlockingQueue", "(I)V", arg0 ) {} PriorityBlockingQueue::PriorityBlockingQueue(JObject arg0) : java::util::AbstractQueue( "java.util.concurrent.PriorityBlockingQueue", "(Ljava/util/Collection;)V", arg0.object() ) {} PriorityBlockingQueue::PriorityBlockingQueue(jint arg0, JObject arg1) : java::util::AbstractQueue( "java.util.concurrent.PriorityBlockingQueue", "(ILjava/util/Comparator;)V", arg0, arg1.object() ) {} // Methods jboolean PriorityBlockingQueue::add(JObject arg0) const { return callMethod( "add", "(Ljava/lang/Object;)Z", arg0.object() ); } void PriorityBlockingQueue::clear() const { callMethod( "clear", "()V" ); } JObject PriorityBlockingQueue::comparator() const { return callObjectMethod( "comparator", "()Ljava/util/Comparator;" ); } jboolean PriorityBlockingQueue::contains(JObject arg0) const { return callMethod( "contains", "(Ljava/lang/Object;)Z", arg0.object() ); } jint PriorityBlockingQueue::drainTo(JObject arg0) const { return callMethod( "drainTo", "(Ljava/util/Collection;)I", arg0.object() ); } jint PriorityBlockingQueue::drainTo(JObject arg0, jint arg1) const { return callMethod( "drainTo", "(Ljava/util/Collection;I)I", arg0.object(), arg1 ); } void PriorityBlockingQueue::forEach(JObject arg0) const { callMethod( "forEach", "(Ljava/util/function/Consumer;)V", arg0.object() ); } JObject PriorityBlockingQueue::iterator() const { return callObjectMethod( "iterator", "()Ljava/util/Iterator;" ); } jboolean PriorityBlockingQueue::offer(JObject arg0) const { return callMethod( "offer", "(Ljava/lang/Object;)Z", arg0.object() ); } jboolean PriorityBlockingQueue::offer(JObject arg0, jlong arg1, java::util::concurrent::TimeUnit arg2) const { return callMethod( "offer", "(Ljava/lang/Object;JLjava/util/concurrent/TimeUnit;)Z", arg0.object(), arg1, arg2.object() ); } JObject PriorityBlockingQueue::peek() const { return callObjectMethod( "peek", "()Ljava/lang/Object;" ); } JObject PriorityBlockingQueue::poll() const { return callObjectMethod( "poll", "()Ljava/lang/Object;" ); } JObject PriorityBlockingQueue::poll(jlong arg0, java::util::concurrent::TimeUnit arg1) const { return callObjectMethod( "poll", "(JLjava/util/concurrent/TimeUnit;)Ljava/lang/Object;", arg0, arg1.object() ); } void PriorityBlockingQueue::put(JObject arg0) const { callMethod( "put", "(Ljava/lang/Object;)V", arg0.object() ); } jint PriorityBlockingQueue::remainingCapacity() const { return callMethod( "remainingCapacity", "()I" ); } jboolean PriorityBlockingQueue::remove(JObject arg0) const { return callMethod( "remove", "(Ljava/lang/Object;)Z", arg0.object() ); } jboolean PriorityBlockingQueue::removeAll(JObject arg0) const { return callMethod( "removeAll", "(Ljava/util/Collection;)Z", arg0.object() ); } jboolean PriorityBlockingQueue::removeIf(JObject arg0) const { return callMethod( "removeIf", "(Ljava/util/function/Predicate;)Z", arg0.object() ); } jboolean PriorityBlockingQueue::retainAll(JObject arg0) const { return callMethod( "retainAll", "(Ljava/util/Collection;)Z", arg0.object() ); } jint PriorityBlockingQueue::size() const { return callMethod( "size", "()I" ); } JObject PriorityBlockingQueue::spliterator() const { return callObjectMethod( "spliterator", "()Ljava/util/Spliterator;" ); } JObject PriorityBlockingQueue::take() const { return callObjectMethod( "take", "()Ljava/lang/Object;" ); } JObjectArray PriorityBlockingQueue::toArray() const { return callObjectMethod( "toArray", "()[Ljava/lang/Object;" ); } JObjectArray PriorityBlockingQueue::toArray(JObjectArray arg0) const { return callObjectMethod( "toArray", "([Ljava/lang/Object;)[Ljava/lang/Object;", arg0.object() ); } JString PriorityBlockingQueue::toString() const { return callObjectMethod( "toString", "()Ljava/lang/String;" ); } } // namespace java::util::concurrent // https://bitbucket.org/xwang/mdict-analysis // https://github.com/zhansliu/writemdict/blob/master/fileformat.md // https://github.com/goldendict/goldendict/blob/master/mdictparser.cc // Octopus MDict Dictionary File (.mdx) and Resource File (.mdd) Analyser #include "mdictparser.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include "ripemd.hh" namespace MDict { #define CHUNK_SIZE 2048 QByteArray zlibDecompress(const char *bufptr, unsigned length) { z_stream zs; char buf[CHUNK_SIZE]; QByteArray str; int res; memset(&zs, 0, sizeof(zs)); zs.next_in = (Bytef *)bufptr; zs.avail_in = length; while (1) { res = inflateInit(&zs); if (res != Z_OK) break; while (res != Z_STREAM_END) { zs.next_out = (Bytef *)buf; zs.avail_out = CHUNK_SIZE; res = inflate(&zs, Z_SYNC_FLUSH); str.append(buf, CHUNK_SIZE - zs.avail_out); if (res != Z_OK && res != Z_STREAM_END) break; } break; } inflateEnd(&zs); if (res != Z_STREAM_END) str.clear(); return str; } enum EncryptedSection { EcryptedHeadWordHeader = 1, EcryptedHeadWordIndex = 2 }; static inline int u16StrSize(const ushort *unicode) { int size = 0; if (unicode) { while (unicode[size] != 0) size++; } return size; } static QDomNamedNodeMap parseHeaderAttributes(const QString &headerText) { QDomNamedNodeMap attributes; QDomDocument doc; doc.setContent(headerText); QDomElement docElem = doc.documentElement(); attributes = docElem.attributes(); for (int i = 0; i < attributes.count(); i++) { QDomAttr attr = attributes.item(i).toAttr(); } return attributes; } size_t MdictParser::RecordIndex::bsearch( const vector &offsets, qint64 val) { if (offsets.size() == 0) return (size_t)(-1); size_t lo = 0; size_t hi = offsets.size() - 1; while (lo <= hi) { size_t mid = (lo + hi) >> 1; RecordIndex const &p = offsets[mid]; if (p == val) return mid; else if (p < val) lo = mid + 1; else hi = mid - 1; } return (size_t)(-1); } MdictParser::MdictParser() : version_(0), numHeadWordBlocks_(0), headWordBlockInfoSize_(0), headWordBlockSize_(0), headWordBlockInfoPos_(0), headWordPos_(0), totalRecordsSize_(0), recordPos_(0), wordCount_(0), numberTypeSize_(0), encrypted_(0), rtl_(false) {} MdictParser::~MdictParser() { if (!file_.isNull()) file_->close(); } bool MdictParser::checkAdler32(const char *buffer, unsigned int len, quint32 checksum) { uLong adler = adler32(0L, Z_NULL, 0); adler = adler32(adler, (const Bytef *)buffer, len); return (adler & 0xFFFFFFFF) == checksum; } QString MdictParser::toUtf16(const char *fromCode, const char *from, size_t fromSize) { QTextCodec *codec = QTextCodec::codecForName(fromCode); QString r = codec->toUnicode(from, fromSize); r.truncate(r.indexOf(QChar::Null)); return r; } bool MdictParser::decryptHeadWordIndex(char *buffer, qint64 len) { RIPEMD128 ripemd; ripemd.update((const uchar *)buffer + 4, 4); ripemd.update((const uchar *)"\x95\x36\x00\x00", 4); uint8_t key[16]; ripemd.digest(key); buffer += 8; len -= 8; uint8_t prev = 0x36; for (qint64 i = 0; i < len; ++i) { uint8_t byte = buffer[i]; byte = (byte >> 4) | (byte << 4); byte = byte ^ prev ^ (i & 0xFF) ^ key[i % 16]; prev = buffer[i]; buffer[i] = byte; } return true; } bool MdictParser::parseCompressedBlock(qint64 compressedBlockSize, const char *compressedBlockPtr, qint64 decompressedBlockSize, QByteArray &decompressedBlock) { if (compressedBlockSize <= 8) return false; // compression type quint32 type = qFromBigEndian((const uchar *)compressedBlockPtr); quint32 checksum = qFromBigEndian((const uchar *)compressedBlockPtr + 4); const char *buf = compressedBlockPtr + 8; qint64 size = compressedBlockSize - 8; switch (type) { case 0x00000000: // No compression if (!checkAdler32(buf, size, checksum)) { qDebug("MDict: parseCompressedBlock: plain: checksum not match"); return false; } decompressedBlock = QByteArray(buf, size); return true; case 0x01000000: { // LZO compression int result; lzo_uint blockSize = (lzo_uint)decompressedBlockSize; decompressedBlock.resize(blockSize); result = lzo1x_decompress_safe((const uchar *)buf, size, (uchar *)decompressedBlock.data(), &blockSize, NULL); if (result != LZO_E_OK || blockSize != (lzo_uint)decompressedBlockSize) { qDebug("MDict: parseCompressedBlock: decompression failed"); return false; } if (checksum != lzo_adler32(lzo_adler32(0, NULL, 0), (const uchar *)decompressedBlock.constData(), blockSize)) { qDebug("MDict: parseCompressedBlock: lzo: checksum does not match"); return false; } } break; case 0x02000000: // zlib compression decompressedBlock = zlibDecompress(buf, size); if (!checkAdler32(decompressedBlock.constData(), decompressedBlock.size(), checksum)) { qDebug("MDict: parseCompressedBlock: zlib: checksum does not match"); return false; } break; default: qDebug("MDict: parseCompressedBlock: unknown type"); return false; } return true; } qint64 MdictParser::readNumber(QDataStream &in) { if (numberTypeSize_ == 8) { qint64 val; in >> val; return val; } else { quint32 val; in >> val; return val; } } quint32 MdictParser::readU8OrU16(QDataStream &in, bool isU16) { if (isU16) { quint16 val; in >> val; return val; } else { quint8 val; in >> val; return val; } } bool MdictParser::open(const QString &filename) { filename_ = filename; file_ = new QFile(filename); if (file_.isNull() || !file_->exists()) return false; if (!file_->open(QIODevice::ReadOnly)) return false; QDataStream in(file_); in.setByteOrder(QDataStream::BigEndian); if (!readHeader(in)) return false; if (!readHeadWordBlockInfos(in)) return false; if (!readRecordBlockInfos()) return false; return true; } bool MdictParser::readNextHeadWordIndex( MdictParser::HeadWordIndex &headWordIndex) { if (headWordBlockInfosIter_ == headWordBlockInfos_.end()) return false; qint64 compressedSize = headWordBlockInfosIter_->first; qint64 decompressedSize = headWordBlockInfosIter_->second; if (compressedSize < 8) return false; ScopedMemMap compressed(*file_, headWordPos_, compressedSize); if (!compressed.startAddress()) return false; headWordPos_ += compressedSize; QByteArray decompressed; if (!parseCompressedBlock(compressedSize, (char *)compressed.startAddress(), decompressedSize, decompressed)) return false; headWordIndex = splitHeadWordBlock(decompressed); headWordBlockInfosIter_++; return true; } MdictParser::HeadWordIndex MdictParser::splitHeadWordBlock( QByteArray const &block) { HeadWordIndex index; const char *p = block.constData(); const char *end = p + block.size(); while (p < end) { qint64 headWordId = (numberTypeSize_ == 8) ? qFromBigEndian((const uchar *)p) : qFromBigEndian((const uchar *)p); p += numberTypeSize_; QByteArray headWordBuf; if (encoding_ == "UTF-16LE") { int headWordLength = u16StrSize((const ushort *)p); headWordBuf = QByteArray(p, (headWordLength + 1) * 2); } else { int headWordLength = strlen(p); headWordBuf = QByteArray(p, headWordLength + 1); } p += headWordBuf.size(); QString headWord = toUtf16(encoding_, headWordBuf.constBegin(), headWordBuf.size()); index.push_back(HeadWordIndex::value_type(headWordId, headWord)); } return index; } bool MdictParser::readRecordBlock(MdictParser::HeadWordIndex &headWordIndex, MdictParser::RecordHandler &recordHandler) { // cache the index, the headWordIndex is already sorted size_t idx = 0; for (HeadWordIndex::const_iterator i = headWordIndex.begin(); i != headWordIndex.end(); i++) { if (recordBlockInfos_[idx].endPos <= i->first) idx = RecordIndex::bsearch(recordBlockInfos_, i->first); if (idx == (size_t)(-1)) return false; RecordIndex const &recordIndex = recordBlockInfos_[idx]; HeadWordIndex::const_iterator iNext = i + 1; qint64 recordSize; if (iNext == headWordIndex.end()) recordSize = recordIndex.shadowEndPos - i->first; else recordSize = iNext->first - i->first; RecordInfo recordInfo; recordInfo.compressedBlockPos = recordPos_ + recordIndex.startPos; recordInfo.recordOffset = i->first - recordIndex.shadowStartPos; recordInfo.decompressedBlockSize = recordIndex.decompressedSize; recordInfo.compressedBlockSize = recordIndex.compressedSize; recordInfo.recordSize = recordSize; recordHandler.handleRecord(i->second, recordInfo); } return true; } bool MdictParser::readHeader(QDataStream &in) { qint32 headerTextSize; in >> headerTextSize; QByteArray headerTextUtf16 = file_->read(headerTextSize); if (headerTextUtf16.size() != headerTextSize) return false; quint32 checksum; in.setByteOrder(QDataStream::LittleEndian); in >> checksum; if (!checkAdler32(headerTextUtf16.constData(), headerTextUtf16.size(), checksum)) { qDebug("MDict: readHeader: checksum does not match"); return false; } in.setByteOrder(QDataStream::BigEndian); QString headerText = toUtf16("UTF-16LE", headerTextUtf16.constData(), headerTextUtf16.size()); headerTextUtf16.clear(); QDomNamedNodeMap headerAttributes = parseHeaderAttributes(headerText); encoding_ = headerAttributes.namedItem("Encoding").toAttr().value(); if (encoding_ == "GBK" || encoding_ == "GB2312") { encoding_ = "GB18030"; } else if (encoding_.isEmpty() || encoding_ == "UTF-16") { encoding_ = "UTF-16LE"; } // stylesheet attribute if present takes form of: // styleId # 1-255 // style.prefix // style.suffix if (headerAttributes.contains("StyleSheet")) { QString styleSheets = headerAttributes.namedItem("StyleSheet").toAttr().value(); QStringList lines = styleSheets.split(QRegExp("[\r\n]"), QString::KeepEmptyParts); for (int i = 0; i < lines.size() - 3; i += 3) { styleSheets_[lines[i].toInt()] = pair(lines[i + 1], lines[i + 2]); } } // before version 2.0, number is 4 bytes integer // version 2.0 and above uses 8 bytes version_ = headerAttributes.namedItem("GeneratedByEngineVersion") .toAttr() .value() .toDouble(); if (version_ < 2.0) numberTypeSize_ = 4; else numberTypeSize_ = 8; // Encrypted ? encrypted_ = headerAttributes.namedItem("Encrypted").toAttr().value().toInt(); // Read metadata rtl_ = headerAttributes.namedItem("Left2Right").toAttr().value() != "Yes"; QString title = headerAttributes.namedItem("Title").toAttr().value(); if (title.isEmpty() || title.length() < 5 || title == "Title (No HTML code allowed)") { // Use filename instead QFileInfo fi(filename_); title_ = fi.baseName(); } else { if (title.contains('<') || title.contains('>')) title_ = QTextDocumentFragment::fromHtml(title).toPlainText(); else title_ = title; } QString description = headerAttributes.namedItem("Description").toAttr().value(); // description_ = QTextDocumentFragment::fromHtml(description).toPlainText(); description_ = description; return true; } bool MdictParser::readHeadWordBlockInfos(QDataStream &in) { QByteArray header = file_->read(version_ >= 2.0 ? (numberTypeSize_ * 5) : (numberTypeSize_ * 4)); QDataStream stream(header); // number of headword blocks numHeadWordBlocks_ = readNumber(stream); // number of entries wordCount_ = readNumber(stream); // number of bytes of a headword block info after decompression qint64 decompressedSize; if (version_ >= 2.0) stream >> decompressedSize; // number of bytes of a headword block info before decompression headWordBlockInfoSize_ = readNumber(stream); // number of bytes of a headword block headWordBlockSize_ = readNumber(stream); // Adler-32 checksum of the header. If those are encrypted, it is // the checksum of the decrypted version if (version_ >= 2.0) { quint32 checksum; in >> checksum; if (!checkAdler32(header.constData(), numberTypeSize_ * 5, checksum)) return false; } headWordBlockInfoPos_ = file_->pos(); // read headword block info QByteArray headWordBlockInfo = file_->read(headWordBlockInfoSize_); if (headWordBlockInfo.size() != headWordBlockInfoSize_) return false; if (version_ >= 2.0) { // decrypt if (encrypted_ & EcryptedHeadWordIndex) { if (!decryptHeadWordIndex(headWordBlockInfo.data(), headWordBlockInfo.size())) return false; } QByteArray decompressed; if (!parseCompressedBlock(headWordBlockInfo.size(), headWordBlockInfo.data(), decompressedSize, decompressed)) return false; headWordBlockInfos_ = decodeHeadWordBlockInfo(decompressed); } else { headWordBlockInfos_ = decodeHeadWordBlockInfo(headWordBlockInfo); } headWordPos_ = file_->pos(); headWordBlockInfosIter_ = headWordBlockInfos_.begin(); return true; } bool MdictParser::readRecordBlockInfos() { file_->seek(headWordBlockInfoPos_ + headWordBlockInfoSize_ + headWordBlockSize_); QDataStream in(file_); in.setByteOrder(QDataStream::BigEndian); qint64 numRecordBlocks = readNumber(in); readNumber(in); // total number of records, skip qint64 recordInfoSize = readNumber(in); totalRecordsSize_ = readNumber(in); recordPos_ = file_->pos() + recordInfoSize; // Build record block index recordBlockInfos_.reserve(numRecordBlocks); qint64 acc1 = 0; qint64 acc2 = 0; for (qint64 i = 0; i < numRecordBlocks; i++) { RecordIndex r; r.compressedSize = readNumber(in); r.decompressedSize = readNumber(in); r.startPos = acc1; r.endPos = acc1 + r.compressedSize; r.shadowStartPos = acc2; r.shadowEndPos = acc2 + r.decompressedSize; recordBlockInfos_.push_back(r); acc1 = r.endPos; acc2 = r.shadowEndPos; } return true; } MdictParser::BlockInfoVector MdictParser::decodeHeadWordBlockInfo( QByteArray const &headWordBlockInfo) { BlockInfoVector headWordBlockInfos; QDataStream s(headWordBlockInfo); s.setByteOrder(QDataStream::BigEndian); bool isU16 = false; int textTermSize = 0; if (version_ >= 2.0) { isU16 = true; textTermSize = 1; } while (!s.atEnd()) { // Number of keywords in the block s.skipRawData(numberTypeSize_); // Size of the first headword in the block quint32 textHeadSize = readU8OrU16(s, isU16); // The first headword if (encoding_ != "UTF-16LE") s.skipRawData(textHeadSize + textTermSize); else s.skipRawData((textHeadSize + textTermSize) * 2); // Size of the last headword in the block quint32 textTailSize = readU8OrU16(s, isU16); // The last headword if (encoding_ != "UTF-16LE") s.skipRawData(textTailSize + textTermSize); else s.skipRawData((textTailSize + textTermSize) * 2); // headword block compressed size qint64 compressedSize = readNumber(s); // headword block decompressed size qint64 decompressedSize = readNumber(s); headWordBlockInfos.push_back( BlockInfoVector::value_type(compressedSize, decompressedSize)); } return headWordBlockInfos; } QString &MdictParser::substituteStylesheet( QString &article, MdictParser::StyleSheets const &styleSheets) { QRegExp rx("`(\\d+)`"); QString endStyle; int pos = 0; while ((pos = rx.indexIn(article, pos)) != -1) { int styleId = rx.cap(1).toInt(); StyleSheets::const_iterator iter = styleSheets.find(styleId); if (iter != styleSheets.end()) { QString rep = endStyle + iter->second.first; article.replace(pos, rx.cap(0).length(), rep); pos += rep.length(); endStyle = iter->second.second; } else { article.replace(pos, rx.cap(0).length(), endStyle); pos += endStyle.length(); endStyle = ""; } } article += endStyle; return article; } } platform/mt6592/hardware/mtkcam/device/DefaultCamDevice.cpp /* Copyright Statement: * * This software/firmware and related documentation ("MediaTek Software") are * protected under relevant copyright laws. The information contained herein is * confidential and proprietary to MediaTek Inc. and/or its licensors. Without * the prior written permission of MediaTek inc. and/or its licensors, any * reproduction, modification, use or disclosure of MediaTek Software, and * information contained herein, in whole or in part, shall be strictly * prohibited. * * MediaTek Inc. (C) 2010. All rights reserved. * * BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES * THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE") * RECEIVED FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO RECEIVER * ON AN "AS-IS" BASIS ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR * NONINFRINGEMENT. NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY WHATSOEVER WITH * RESPECT TO THE SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY, * INCORPORATED IN, OR SUPPLIED WITH THE MEDIATEK SOFTWARE, AND RECEIVER AGREES * TO LOOK ONLY TO SUCH THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. * RECEIVER EXPRESSLY ACKNOWLEDGES THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO * OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES CONTAINED IN MEDIATEK * SOFTWARE. MEDIATEK SHALL ALSO NOT BE RESPONSIBLE FOR ANY MEDIATEK SOFTWARE * RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR * STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S * ENTIRE AND CUMULATIVE LIABILITY WITH RESPECT TO THE MEDIATEK SOFTWARE * RELEASED HEREUNDER WILL BE, AT MEDIATEK'S OPTION, TO REVISE OR REPLACE THE * MEDIATEK SOFTWARE AT ISSUE, OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE * CHARGE PAID BY RECEIVER TO MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE. * * The following software/firmware and/or related documentation ("MediaTek * Software") have been modified by MediaTek Inc. All revisions are subject to * any receiver's applicable license agreements with MediaTek Inc. */ #define LOG_TAG "MtkCam/CamDevice" #include // #include #include #include #include #include // using namespace android; using namespace NSCamDevice; #define CHANGE_THREAD_PRIO 1 /****************************************************************************** * *******************************************************************************/ #define MY_LOGV(fmt, arg...) CAM_LOGV("(%d)(%s:%d)[%s] "fmt, ::gettid(), getDevName(), getOpenId(), __FUNCTION__, ##arg) #define MY_LOGD(fmt, arg...) CAM_LOGD("(%d)(%s:%d)[%s] "fmt, ::gettid(), getDevName(), getOpenId(), __FUNCTION__, ##arg) #define MY_LOGI(fmt, arg...) CAM_LOGI("(%d)(%s:%d)[%s] "fmt, ::gettid(), getDevName(), getOpenId(), __FUNCTION__, ##arg) #define MY_LOGW(fmt, arg...) CAM_LOGW("(%d)(%s:%d)[%s] "fmt, ::gettid(), getDevName(), getOpenId(), __FUNCTION__, ##arg) #define MY_LOGE(fmt, arg...) CAM_LOGE("(%d)(%s:%d)[%s] "fmt, ::gettid(), getDevName(), getOpenId(), __FUNCTION__, ##arg) #define MY_LOGA(fmt, arg...) CAM_LOGA("(%d)(%s:%d)[%s] "fmt, ::gettid(), getDevName(), getOpenId(), __FUNCTION__, ##arg) #define MY_LOGF(fmt, arg...) CAM_LOGF("(%d)(%s:%d)[%s] "fmt, ::gettid(), getDevName(), getOpenId(), __FUNCTION__, ##arg) // #define MY_LOGV_IF(cond, ...) do { if ( (cond) ) { MY_LOGV(__VA_ARGS__); } }while(0) #define MY_LOGD_IF(cond, ...) do { if ( (cond) ) { MY_LOGD(__VA_ARGS__); } }while(0) #define MY_LOGI_IF(cond, ...) do { if ( (cond) ) { MY_LOGI(__VA_ARGS__); } }while(0) #define MY_LOGW_IF(cond, ...) do { if ( (cond) ) { MY_LOGW(__VA_ARGS__); } }while(0) #define MY_LOGE_IF(cond, ...) do { if ( (cond) ) { MY_LOGE(__VA_ARGS__); } }while(0) #define MY_LOGA_IF(cond, ...) do { if ( (cond) ) { MY_LOGA(__VA_ARGS__); } }while(0) #define MY_LOGF_IF(cond, ...) do { if ( (cond) ) { MY_LOGF(__VA_ARGS__); } }while(0) /****************************************************************************** * ******************************************************************************/ extern "C" ICamDevice* createCamDevice_Default( String8 const& rDevName, int32_t const i4OpenId ) { return new DefaultCamDevice(rDevName, i4OpenId); } /****************************************************************************** * *******************************************************************************/ DefaultCamDevice:: DefaultCamDevice( String8 const& rDevName, int32_t const i4OpenId ) : CamDevice(rDevName, i4OpenId) // #if '1'==MTKCAM_HAVE_SENSOR_HAL , mpSensorHal(NULL) #endif // #if '1'==MTKCAM_HAVE_3A_HAL , mp3AHal(NULL) #endif // { } /****************************************************************************** * *******************************************************************************/ DefaultCamDevice:: ~DefaultCamDevice() { } /****************************************************************************** * *******************************************************************************/ bool DefaultCamDevice:: onInit() { MY_LOGD("+"); initCameraProfile(); AutoCPTLog cptlog(Event_Hal_DefaultCamDevice_init); CamProfile profile(__FUNCTION__, "DefaultCamDevice"); // bool ret = false; int err = 0; int const iHalSensorDevId = DevMetaInfo::queryHalSensorDev(getOpenId()); IResManager* pResManager; // #if CHANGE_THREAD_PRIO //-------------------------------------------------------------------------- // change thread's priority int old_policy; int old_priority; bool prio_changed = false; struct sched_param sched_p; pthread_getschedparam(pthread_self(), &old_policy, &sched_p); old_priority = sched_p.sched_priority; sched_p.sched_priority = PRIO_RT_CAMERA_INIT; if ( pthread_setschedparam(pthread_self(), SCHED_RR, &sched_p) ) { MY_LOGE("setschedparam failed"); goto lbExit; } prio_changed = true; #if 0 { //verify int policy; struct sched_param param; pthread_getschedparam(pthread_self(), &policy, ¶m); MY_LOGD("change thread's priority, old/current: policy(%d/%d), prio(%d/%d)", old_policy, policy, old_priority, param.sched_priority); } #endif #endif //-------------------------------------------------------------------------- CPTLogStr(Event_Hal_DefaultCamDevice_init, CPTFlagSeparator, "Resource +"); pResManager = IResManager::getInstance(); // if ( pResManager != NULL ) { if(!(pResManager->open("DefaultCamDevice"))) { MY_LOGE("pResManager->open fail"); goto lbExit; } } // profile.print("Resource -"); CPTLogStr(Event_Hal_DefaultCamDevice_init, CPTFlagSeparator, "Resource -"); //-------------------------------------------------------------------------- // (1) Open Sensor #if '1'==MTKCAM_HAVE_SENSOR_HAL CPTLogStr(Event_Hal_DefaultCamDevice_init, CPTFlagSeparator, "Sensor Hal +"); MY_LOGD("SensorHal::createInstance(), iHalSensorDevId:%#x", iHalSensorDevId); mpSensorHal = SensorHal::createInstance(); if ( ! mpSensorHal ) { MY_LOGE("mpSensorHal == NULL"); goto lbExit; } // err = mpSensorHal->sendCommand((halSensorDev_e)iHalSensorDevId, SENSOR_CMD_SET_SENSOR_DEV); if ( err ) { mpSensorHal->destroyInstance(); mpSensorHal = NULL; goto lbExit; } err = mpSensorHal->init(); if ( err ) { mpSensorHal->uninit(); mpSensorHal->destroyInstance(); mpSensorHal = NULL; goto lbExit; } profile.print("Sensor Hal -"); CPTLogStr(Event_Hal_DefaultCamDevice_init, CPTFlagSeparator, "Sensor Hal -"); #endif //MTKCAM_HAVE_SENSOR_HAL //-------------------------------------------------------------------------- // (2) Open 3A #if '1'==MTKCAM_HAVE_3A_HAL CPTLogStr(Event_Hal_DefaultCamDevice_init, CPTFlagSeparator, "3A Hal +"); mp3AHal = NS3A::Hal3ABase::createInstance(iHalSensorDevId); if ( ! mp3AHal ) { MY_LOGE("Hal3ABase::createInstance() fail"); goto lbExit; } profile.print("3A Hal -"); CPTLogStr(Event_Hal_DefaultCamDevice_init, CPTFlagSeparator, "3A Hal -"); #endif //MTKCAM_HAVE_3A_HAL //-------------------------------------------------------------------------- // (3) Init Base. if ( ! CamDevice::onInit() ) { goto lbExit; } // //-------------------------------------------------------------------------- // ret = true; lbExit: #if CHANGE_THREAD_PRIO // restore thread's priority if( prio_changed ) { sched_p.sched_priority = old_priority; if ( pthread_setschedparam(pthread_self(), old_policy, &sched_p) ) { MY_LOGE("restore setschedparam failed"); goto lbExit; } #if 0 { //verify int policy; struct sched_param param; pthread_getschedparam(pthread_self(), &policy, ¶m); MY_LOGD("restore thread's priority, current: policy(%d), prio(%d)", policy, param.sched_priority); } #endif } #endif profile.print(""); MY_LOGD("- ret(%d)", ret); return ret; } /****************************************************************************** * *******************************************************************************/ bool DefaultCamDevice:: onUninit() { MY_LOGD("+"); AutoCPTLog cptlog(Event_Hal_DefaultCamDevice_uninit); CamProfile profile(__FUNCTION__, "DefaultCamDevice"); // //-------------------------------------------------------------------------- // (1) Uninit Base CamDevice::onUninit(); profile.print("CamDevice::onUninit() -"); //-------------------------------------------------------------------------- // (2) Close 3A #if '1'==MTKCAM_HAVE_3A_HAL CPTLogStr(Event_Hal_DefaultCamDevice_init, CPTFlagSeparator, "3A Hal +"); if ( mp3AHal ) { mp3AHal->destroyInstance(); mp3AHal = NULL; } profile.print("3A Hal -"); CPTLogStr(Event_Hal_DefaultCamDevice_init, CPTFlagSeparator, "3A Hal -"); #endif //MTKCAM_HAVE_3A_HAL //-------------------------------------------------------------------------- // (4) Close Sensor #if '1'==MTKCAM_HAVE_SENSOR_HAL CPTLogStr(Event_Hal_DefaultCamDevice_init, CPTFlagSeparator, "Sensor Hal +"); if ( mpSensorHal ) { mpSensorHal->uninit(); mpSensorHal->destroyInstance(); mpSensorHal = NULL; MY_LOGD("SensorHal::destroyInstance()"); } profile.print("Sensor Hal -"); CPTLogStr(Event_Hal_DefaultCamDevice_init, CPTFlagSeparator, "Sensor Hal -"); #endif //MTKCAM_HAVE_SENSOR_HAL //-------------------------------------------------------------------------- CPTLogStr(Event_Hal_DefaultCamDevice_init, CPTFlagSeparator, "Resource +"); IResManager* pResManager = IResManager::getInstance(); // if ( pResManager != NULL ) { if(!(pResManager->close("DefaultCamDevice"))) { MY_LOGE("pResManager->close fail"); } } profile.print("Resource -"); CPTLogStr(Event_Hal_DefaultCamDevice_init, CPTFlagSeparator, "Resource -"); //-------------------------------------------------------------------------- // profile.print(""); MY_LOGD("-"); return true; } /****************************************************************************** * [Template method] Called by startPreview(). *******************************************************************************/ bool DefaultCamDevice:: onStartPreview() { bool ret = false; // // (1) Update Hal App Mode. if ( ! mpParamsMgr->updateHalAppMode() ) { MY_LOGE("mpParamsMgr->updateHalAppMode() fail"); goto lbExit; } // (2) Initialize Camera Adapter. if ( ! initCameraAdapter() ) { MY_LOGE("NULL Camera Adapter"); goto lbExit; } // ret = true; lbExit: return ret; } /****************************************************************************** * [Template method] Called by stopPreview(). *******************************************************************************/ void DefaultCamDevice:: onStopPreview() { if ( mpCamAdapter != 0 ) { mpCamAdapter->cancelPicture(); mpCamAdapter->uninit(); mpCamAdapter.clear(); } } /****************************************************************************** * Set the camera parameters. This returns BAD_VALUE if any parameter is * invalid or not supported. *******************************************************************************/ status_t DefaultCamDevice:: setParameters(const char* params) { status_t status = OK; // // (1) Update params to mpParamsMgr. status = mpParamsMgr->setParameters(String8(params)); if ( OK != status ) { goto lbExit; } // Here (1) succeeded. // (2) If CamAdapter exists, apply mpParamsMgr to CamAdapter; // otherwise it will be applied when CamAdapter is created. { sp pCamAdapter = mpCamAdapter; if ( pCamAdapter != 0 ) { status = pCamAdapter->setParameters(); } #if '1'==MTKCAM_HAVE_3A_HAL else if ( mp3AHal ) { // Flashlight may turn on/off in case that CamAdapter doesn't exist (i.e. never call startPreview) using namespace NS3A; Param_T param; // if ( ! mp3AHal->getParams(param) ) { MY_LOGW("3A Hal::getParams() fail - err(%x)", mp3AHal->getErrorCode()); } // String8 const s8FlashMode = mpParamsMgr->getStr(CameraParameters::KEY_FLASH_MODE); if ( ! s8FlashMode.isEmpty() ) { param.u4StrobeMode = PARAMSMANAGER_MAP_INST(eMapFlashMode)->valueFor(s8FlashMode); } // if ( ! mp3AHal->setParams(param) ) { MY_LOGW("3A Hal::setParams() fail - err(%x)", mp3AHal->getErrorCode()); } } else { MY_LOGW("mp3AHal==NULL"); } #endif } lbExit: return status; } #include using namespace eeros::control; void Block::setName(std::string name) { this->name = name; } std::string Block::getName() const { return name; }VirtA/RAM.cpp // // RAM.cpp // Implementation of RAM // Simulates a system's random access memory // // Created by on 2017/07/06. // // MIT License // // Copyright (c) 2017 // // 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 "RAM.h" using namespace std; /** * Initializes internal storage for the memory */ RAM::RAM(uint_fast8_t kb, uint16_t himem) : himem(himem) { // Size of memory must be a power of two assert(((kb != 0) && !(kb & (kb - 1)))); // Compute and initialize memory size = kb * 1024; memory = new uint8_t[size]; } /** * Frees the internal storage for the memory */ RAM::~RAM() { // Free the memory delete memory; } /** * Reads a byte from memory */ uint8_t RAM::readByte(uint16_t address) { // Check whether the range is valid if (address >= size) { // Check for disjoint memory segment above 1000 if (!((himem > 0 && size > 0x1000) && (address < himem + size - 0x1000))) { return 0; } } return memory[address]; } /** * Writes a byte to memory */ void RAM::writeByte(uint16_t address, uint8_t value) { // Check whether the range is valid if (address >= size) { // Check for disjoint memory segment above 1000 if (!((himem > 0 && size >= 0x1000) && (address < himem + size - 0x1000))) { return; } } // Set the value memory[address] = value; } void RAM::loadFile(uint16_t startAddress, string filename) { // Create a stream pointing to the file ifstream input(filename, std::ios::binary | std::ios::ate); streamsize size = input.tellg(); input.seekg(0, std::ios::beg); // Read and close the file input.read(reinterpret_cast(memory + startAddress), size); input.close(); } 0 #include "s3key_writer.h" void S3KeyWriter::open(const S3Params& params) { this->params = params; S3_CHECK_OR_DIE(this->s3Interface != NULL, S3RuntimeError, "s3Interface must not be NULL"); S3_CHECK_OR_DIE(this->params.getChunkSize() > 0, S3RuntimeError, "chunkSize must not be zero"); buffer.reserve(this->params.getChunkSize()); this->uploadId = this->s3Interface->getUploadId(this->params.getS3Url()); S3_CHECK_OR_DIE(!this->uploadId.empty(), S3RuntimeError, "Failed to get upload id"); S3DEBUG("key: %s, upload id: %s", this->params.getS3Url().getFullUrlForCurl().c_str(), this->uploadId.c_str()); } // write() first fills up the data buffer before flush it out uint64_t S3KeyWriter::write(const char* buf, uint64_t count) { // Defensive code S3_CHECK_OR_DIE(buf != NULL, S3RuntimeError, "Buffer is NULL"); this->checkQueryCancelSignal(); uint64_t offset = 0; while (offset < count) { if (sharedError) { std::rethrow_exception(sharedException); } uint64_t bufferRemaining = this->params.getChunkSize() - this->buffer.size(); uint64_t dataRemaining = count - offset; uint64_t dataToBuffer = bufferRemaining < dataRemaining ? bufferRemaining : dataRemaining; this->buffer.insert(this->buffer.end(), buf + offset, buf + offset + dataToBuffer); if (this->buffer.size() == this->params.getChunkSize()) { this->flushBuffer(); } offset += dataToBuffer; } return count; } // This should be reentrant, has no side effects when called multiple times. void S3KeyWriter::close() { if (!this->uploadId.empty()) { this->completeKeyWriting(); } } void S3KeyWriter::checkQueryCancelSignal() { if (S3QueryIsAbortInProgress() && !this->uploadId.empty()) { // to avoid dead-lock when other upload threads hold the lock pthread_mutex_unlock(&this->mutex); // wait for all threads to complete for (size_t i = 0; i < threadList.size(); i++) { pthread_join(threadList[i], NULL); } this->threadList.clear(); // to avoid double unlock as other parts may lock it pthread_mutex_lock(&this->mutex); S3DEBUG("Start aborting multipart uploading (uploadID: %s, %lu parts uploaded)", this->uploadId.c_str(), this->etagList.size()); this->s3Interface->abortUpload(this->params.getS3Url(), this->uploadId); S3DEBUG("Finished aborting multipart uploading (uploadID: %s)", this->uploadId.c_str()); this->etagList.clear(); this->uploadId.clear(); S3_DIE(S3QueryAbort, "Uploading is interrupted"); } } struct ThreadParams { S3KeyWriter* keyWriter; S3VectorUInt8 data; uint64_t currentNumber; }; void* S3KeyWriter::UploadThreadFunc(void* data) { MaskThreadSignals(); ThreadParams* params = (ThreadParams*)data; S3KeyWriter* writer = params->keyWriter; try { S3DEBUG("Upload thread start: %" PRIX64 ", part number: %" PRIu64 ", data size: %" PRIu64, (uint64_t) pthread_self(), params->currentNumber, params->data.size()); string etag = writer->s3Interface->uploadPartOfData( params->data, writer->params.getS3Url(), params->currentNumber, writer->uploadId); // when unique_lock destructs it will automatically unlock the mutex. UniqueLock threadLock(&writer->mutex); // etag is empty if the query is cancelled by user. if (!etag.empty()) { writer->etagList[params->currentNumber] = etag; } writer->activeThreads--; pthread_cond_broadcast(&writer->cv); S3DEBUG("Upload part finish: %" PRIX64 ", eTag: %s, part number: %" PRIu64, (uint64_t) pthread_self(), etag.c_str(), params->currentNumber); } catch (S3Exception& e) { S3ERROR("Upload thread error: %s", e.getMessage().c_str()); UniqueLock exceptLock(&writer->exceptionMutex); writer->sharedError = true; writer->sharedException = std::current_exception(); // notify the flushBuffer, otherwise it will be locked when trying to create a new thread. writer->activeThreads--; pthread_cond_broadcast(&writer->cv); } delete params; return NULL; } void S3KeyWriter::flushBuffer() { if (!this->buffer.empty()) { UniqueLock queueLock(&this->mutex); while (this->activeThreads >= this->params.getNumOfChunks()) { pthread_cond_wait(&this->cv, &this->mutex); } // Most time query is canceled during uploadPartOfData(). This is the first chance to cancel // and clean up upload. this->checkQueryCancelSignal(); this->activeThreads++; pthread_t writerThread; ThreadParams* params = new ThreadParams(); params->keyWriter = this; params->data.swap(this->buffer); params->currentNumber = ++this->partNumber; pthread_create(&writerThread, NULL, UploadThreadFunc, params); threadList.emplace_back(writerThread); this->buffer.reserve(this->params.getChunkSize()); } } void S3KeyWriter::completeKeyWriting() { // make sure the buffer is clear this->flushBuffer(); // wait for all threads to complete for (size_t i = 0; i < threadList.size(); i++) { pthread_join(threadList[i], NULL); } this->threadList.clear(); this->checkQueryCancelSignal(); vector etags; // it is equivalent to foreach(e in etagList) push_back(e.second); // transform(etagList.begin(), etagList.end(), etags.begin(), // [](std::pair& p) { return p.second; }); etags.reserve(etagList.size()); for (map::iterator i = etagList.begin(); i != etagList.end(); i++) { etags.push_back(i->second); } if (!this->etagList.empty() && !this->uploadId.empty()) { this->s3Interface->completeMultiPart(this->params.getS3Url(), this->uploadId, etags); } S3DEBUG("Segment %d has finished uploading \"%s\"", s3ext_segid, this->params.getS3Url().getFullUrlForCurl().c_str()); this->buffer.clear(); this->etagList.clear(); this->uploadId.clear(); } mathiaseitz/imdb_framework #ifndef FILTER_HPP #define FILTER_HPP #include #include const double PI = 3.14159265358979323846; /* * image image buffer to be filled * peakFreq central or peak frequency of the filter response * deltaFreq distance of the half-magnitude and peak frequency * orientAngle orientation of the filter * deltaAngle distance of the half-magnitude and peak frequency */ template void generate_gabor_filter(image_t& image, double peakFreq, double deltaFreq, double orientAngle, double deltaAngle) { const double C = std::sqrt(log(2.0) / PI); const double Ka = (deltaFreq - 1.0) / (deltaFreq + 1.0); const double Kb = std::tan(0.5 * deltaAngle); //const double lambda = Ka / Kb; // scaling factors of the gaussian envelope const double a = peakFreq * (Ka / C); //const double b = a / lambda; const double b = Kb * peakFreq/C * std::sqrt(1.0 - Ka*Ka); // spatial frequency in cartesian coordinates const double u0 = peakFreq * std::cos(orientAngle); const double v0 = peakFreq * std::sin(orientAngle); // default: set orientation of gaussian envelope (theta) equal to orientation of filter const double theta = orientAngle; // generate filter const size_t w = image.width(); const size_t h = image.height(); const double stepx = 1.0 / static_cast(w); const double stepy = 1.0 / static_cast(h); const double cos_theta = std::cos(theta); const double sin_theta = std::sin(theta); double v = 0.5 - v0; for (size_t yy = 0; yy < h; yy++) { size_t y = (yy + (h / 2)) % h; double u = -0.5 - u0; for (size_t xx = 0; xx < w; xx++) { size_t x = (xx + (w / 2)) % w; double ur = u * cos_theta + v * sin_theta; double vr = -u * sin_theta + v * cos_theta; double U = ur / a; double V = vr / b; double value = std::exp(-PI * (U*U + V*V)); image(x, y) = value; u += stepx; } v -= stepy; } } template void generate_polargabor_filter(image_t& image, double peakFreq, double deltaFreq, double orientAngle, double deltaAngle) { // sigma_omega = 1 / (kappa * omega) double kappa = (deltaFreq - 1) / ((deltaFreq + 1) * std::sqrt(2*std::log(2))); // double sigma_theta = std::sqrt(2*PI)*4.0*numorients/32.0; // torralba double sigma_theta = std::sqrt(std::log(2.0)) * 2.0 / deltaAngle; // generate filter const size_t w = image.width(); const size_t h = image.height(); const double stepx = 1.0 / static_cast(w); const double stepy = 1.0 / static_cast(h); double v = -0.5; for (size_t yy = 0; yy < h; yy++) { size_t y = (yy + (h / 2)) % h; double u = -0.5; for (size_t xx = 0; xx < w; xx++) { size_t x = (xx + (w / 2)) % w; double omega = std::sqrt(u*u + v*v); double theta = std::atan2(v, u); double Omega = omega/peakFreq - 1; double Theta = theta + orientAngle; if (Theta < -PI) Theta += 2*PI; if (Theta > PI) Theta -= 2*PI; double value = std::exp(-1/(2*kappa*kappa) * Omega*Omega - sigma_theta*sigma_theta * Theta*Theta); image(x, y) = value; // image(xx, yy) = value; u += stepx; } v += stepy; } } template void generate_gaussian_filter(image_t& image, double sigma) { const int w = image.width(); const int h = image.height(); const int wh = w / 2; const int hh = h / 2; const double s = 1.0 / (sigma*sigma); for (int y = -hh; y < hh; y++) { size_t yy = (y + h) % h; for (int x = -wh; x < wh; x++) { size_t xx = (x + w) % w; double fx = x; double fy = y; image(xx, yy) = std::exp(-(fx*fx + fy*fy) * s); } } } #endif // FILTER_HPP yoni206/pono0 #include #include #include "core/fts.h" #include "core/rts.h" #include "engines/mbic3.h" #include "gtest/gtest.h" #include "smt/available_solvers.h" #include "utils/ts_analysis.h" using namespace pono; using namespace smt; using namespace std; namespace pono_tests { class IC3UnitTests : public ::testing::Test, public ::testing::WithParamInterface { protected: void SetUp() override { s = create_solver(GetParam()); s->set_opt("incremental", "true"); s->set_opt("produce-models", "true"); s->set_opt("produce-unsat-cores", "true"); boolsort = s->make_sort(BOOL); bvsort8 = s->make_sort(BV, 8); } SmtSolver s; Sort boolsort, bvsort8; }; TEST_P(IC3UnitTests, SimpleSystemSafe) { RelationalTransitionSystem rts(s); Term s1 = rts.make_statevar("s1", boolsort); Term s2 = rts.make_statevar("s2", boolsort); // INIT !s1 & !s2 rts.constrain_init(s->make_term(Not, s1)); rts.constrain_init(s->make_term(Not, s2)); // TRANS next(s1) = (s1 | s2) // TRANS next(s2) = s2 rts.assign_next(s1, s->make_term(Or, s1, s2)); rts.assign_next(s2, s2); Property p(rts, s->make_term(Not, s1)); ModelBasedIC3 mbic3(p, s); ProverResult r = mbic3.prove(); ASSERT_EQ(r, TRUE); // get the invariant Term invar = mbic3.invar(); ASSERT_TRUE(check_invar(rts, p.prop(), invar)); } TEST_P(IC3UnitTests, SimpleSystemUnsafe) { FunctionalTransitionSystem fts(s); Term s1 = fts.make_statevar("s1", boolsort); Term s2 = fts.make_statevar("s2", boolsort); // INIT !s1 & s2 fts.constrain_init(s->make_term(Not, s1)); fts.constrain_init(s2); // TRANS next(s1) = (s1 | s2) // TRANS next(s2) = s2 fts.assign_next(s1, s->make_term(Or, s1, s2)); fts.assign_next(s2, s2); Property p(fts, s->make_term(Not, s1)); ModelBasedIC3 mbic3(p, s); ProverResult r = mbic3.prove(); ASSERT_EQ(r, FALSE); } INSTANTIATE_TEST_SUITE_P(ParameterizedSolverIC3UnitTests, IC3UnitTests, testing::ValuesIn(available_solver_enums())); } // namespace pono_tests /* * TRYTE * Tryte implementation. * * 2019 */ #ifndef __TRYTE_HPP #define __TRYTE_HPP #include #include "trit.hpp" namespace iii { // powers of 3 0 1 2 3 4 5 6 7 8 static int pow3_lut[] = {1, 3, 9, 27, 81, 243, 729, 2187, 6561}; // powers of 3 8 7 6 5 4 3 2 1 0 static int inv_pow3_lut[] = {6561, 2187, 729, 243, 81, 27, 9, 3, 1}; class Tryte { Trit trits[9]; Trit carry; public: Tryte(); Tryte(const int v); Tryte(const Tryte& that); ~Tryte(); // assignment operators Tryte& operator=(const int v); Tryte& operator=(const Tryte& t); // logic operators Trit operator==(const Tryte& t) const; Trit operator!=(const Tryte& t) const; Tryte operator&(const Tryte& t) const; Tryte operator|(const Tryte& t) const; Tryte operator^(const Tryte& t) const; Tryte operator~(void) const; // comparison operators Trit comp(const Tryte& t); bool operator<(const Tryte& t); bool operator<=(const Tryte& t) const; bool operator>(const Tryte& t) const; bool operator>=(const Tryte& t) const; // arithmetic operators Tryte operator+(const Tryte& t); //Tryte operator+(const int v); Tryte operator-(const Tryte& t); // other operators const Trit& operator[](const int i) const; Trit& operator[](const int i); // getters Trit getCarry(void) const; Trit getTrit(const int trit) const; // operations with no suitable overloads bool eqZero(void) const; // setters void setTrit(const int trit, const Trit& t); void allClear(void); void allSet(void); void invert(void); // display void printTrits(void); // type conversion void fromInt(const int v); int toInt(void); int nonaryhex(void); std::string toString(void); }; } // namespace iii #endif /*__TRYTE_HPP*/ /** * Swagger Petstore * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. * * OpenAPI spec version: 1.0.0 * Contact: * * NOTE: This class is auto generated by the swagger code generator 2.3.0-SNAPSHOT. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ #include "Category.h" #include #include #include #include using boost::property_tree::ptree; using boost::property_tree::read_json; using boost::property_tree::write_json; namespace io { namespace swagger { namespace server { namespace model { Category::Category() { m_Id = 0L; m_Name = ""; } Category::~Category() { } std::string Category::toJsonString() { std::stringstream ss; ptree pt; pt.put("Id", m_Id); pt.put("Name", m_Name); write_json(ss, pt, false); return ss.str(); } void Category::fromJsonString(std::string const& jsonString) { std::stringstream ss(jsonString); ptree pt; read_json(ss,pt); m_Id = pt.get("Id", 0L); m_Name = pt.get("Name", ""); } int64_t Category::getId() const { return m_Id; } void Category::setId(int64_t value) { m_Id = value; } std::string Category::getName() const { return m_Name; } void Category::setName(std::string value) { m_Name = value; } } } } } #pragma once #include #include #include #include /// дефолтный размер буфера для wbuffer_convert #ifndef EXT_CODECVT_CONV_WBUFFER_CONVERT_BUFFER_SIZE #define EXT_CODECVT_CONV_WBUFFER_CONVERT_BUFFER_SIZE 4096 #endif namespace ext { namespace codecvt_convert { //template template > class wbuffer_convert : public std::basic_streambuf { public: using state_type = std::mbstate_t; using streambuf = std::basic_streambuf; using codecvt = std::codecvt; using narrow_streambuf = std::basic_streambuf; using typename streambuf::traits_type; using typename streambuf::char_type; using typename streambuf::int_type; using typename streambuf::pos_type; using typename streambuf::off_type; wbuffer_convert(narrow_streambuf * wrapped, const codecvt * cvt) : wrapped(wrapped), cvt(cvt) {} wbuffer_convert(wbuffer_convert const &) = delete; wbuffer_convert & operator =(wbuffer_convert const &) = delete; protected: using streambuf::gptr; using streambuf::pptr; protected: int_type underflow() override; //std::streamsize showmanyc() override; //std::streamsize xsgetn(char_type * ptr, std::streamsize count) override; //int_type pbackfail(int_type ch/* = Traits::eof() */) override; int_type overflow(int_type ch/* = Traits::eof() */) override; int sync() override; //for flush private: typedef std::size_t buffer_size_type; ///streambuf can be used both for in and out dataflow ///we have to context to track state and dataflow, they are unrelated. ///we don't support seek operations, so we can't have united buffer, we use 2 independent struct input_buffer_ctx_type : internal::make_from_bytes_context::type { std::unique_ptr from_buffer; std::unique_ptr to_buffer; }; struct output_buffer_ctx_type : internal::make_to_bytes_context::type { std::unique_ptr from_buffer; std::unique_ptr to_buffer; }; const buffer_size_type from_buffer_capacity = EXT_CODECVT_CONV_WBUFFER_CONVERT_BUFFER_SIZE; const buffer_size_type to_buffer_capacity = EXT_CODECVT_CONV_WBUFFER_CONVERT_BUFFER_SIZE; const buffer_size_type history_buffer_capacity = 8; std::unique_ptr input_bufctx; std::unique_ptr output_bufctx; narrow_streambuf * wrapped; const codecvt * cvt; template void initialize_base(Context & ctx) { ctx.from_buffer = std::make_unique(to_buffer_capacity); ctx.from_beg = ctx.from_buffer.get(); ctx.from_end = ctx.from_beg + to_buffer_capacity; ctx.to_buffer = std::make_unique(from_buffer_capacity); ctx.to_beg = ctx.to_buffer.get(); ctx.to_end = ctx.to_beg + from_buffer_capacity; ctx.state = state_type {}; } void initialize(input_buffer_ctx_type & ctx) { initialize_base(ctx); ctx.from_stopped = ctx.from_end; ctx.to_stopped = ctx.to_end; } void initialize(output_buffer_ctx_type & ctx) { initialize_base(ctx); ctx.from_stopped = ctx.from_beg; ctx.to_stopped = ctx.to_beg; } /// after convert there are can be some left data which is not converted /// ctx.from_stopped points to it /// let unconverted_len = ctx.from_end - ctx.from_stopped /// it will move [ctx.from_stopped, ctx.from_end) to [ctx.from_beg, ctx.from_beg + unconverted_len) /// and set ctx.from_stopped = to point after last moved character(ctx.from_beg + unconverted_len) template void move_unconverted(Context & ctx) { auto unconverted_len = ctx.from_end - ctx.from_stopped; memmove(ext::unconst(ctx.from_beg), ctx.from_stopped, unconverted_len * sizeof(*ctx.from_end)); //std::move(ctx.from_stopped, ctx.from_end, ext::unconst(ctx.from_beg)); //or via std C++ ctx.from_stopped = ctx.from_beg + unconverted_len; } /// tries to convert [ctx.from_beg, ctx.from_end) to [ctx.to_beg, ctx.to_end) /// sets ctx.from_stopped/ctx.to_stopped after last consumed/produced character /// throws in case or error template void from_bytes(CvtContext & ctx) const { from_bytes_step(*cvt, ctx); switch (ctx.res) { case codecvt::ok: break; case codecvt::partial: // we read some characters, convert them, got partial and converted nothing // we definitely stopped at some partial input if (ctx.is_partial_input && ctx.from_beg == ctx.from_stopped) throw conversion_failure("partial input"); break; case codecvt::noconv: internal::noconv_copy(ctx); break; default: throw conversion_failure(); } } /// tries to read more characters from wrapped streambuf and convert them to intern_type /// returns true if read some bool readsome(input_buffer_ctx_type & ctx) { move_unconverted(ctx); auto read = wrapped->sgetn(ext::unconst(ctx.from_stopped), ctx.from_end - ctx.from_stopped); ctx.from_end = ctx.from_stopped + read; if (ctx.from_beg == ctx.from_end) //nothing to convert after read, we are finished return false; from_bytes(ctx); return true; } template void to_bytes(CvtContext & ctx) const { to_bytes_step(*cvt, ctx); switch (ctx.res) { case codecvt::ok: break; case codecvt::partial: // we were given some characters via input from ostream, convert them, got partial and converted nothing // we definitely stopped at some partial input if (ctx.is_partial_input && ctx.from_beg == ctx.from_stopped) throw conversion_failure("partial input"); break; case codecvt::noconv: internal::noconv_copy(ctx); break; default: throw conversion_failure(); } } /// converts data and tries to write it to wrapped streambuf /// after write move unconverted data to the beginning of the input buffer /// setting ctx.from_stopped to ctx.from_beg + unconverted_len bool writesome(output_buffer_ctx_type & ctx) { to_bytes(ctx); std::streamsize ntowrite = ctx.to_stopped - ctx.to_beg; auto written = wrapped->sputn(ctx.to_beg, ntowrite); if (written != ntowrite) return false; move_unconverted(ctx); return true; } }; template auto wbuffer_convert::underflow() -> int_type { if (!input_bufctx) { input_bufctx = std::make_unique(); initialize(*input_bufctx); } auto read = readsome(*input_bufctx); if (!read) return traits_type::eof(); setg(input_bufctx->to_beg, input_bufctx->to_beg, input_bufctx->to_stopped); return traits_type::to_int_type(*gptr()); } template auto wbuffer_convert::overflow(int_type ch) -> int_type { if (!output_bufctx) { output_bufctx = std::make_unique(); initialize(*output_bufctx); } else { //first time there is nothing to write if (!writesome(*output_bufctx)) //throw std::runtime_error("write to wrapped failed"); return traits_type::eof(); } setp(ext::unconst(output_bufctx->from_beg), ext::unconst(output_bufctx->from_stopped), ext::unconst(output_bufctx->from_end)); if (!traits_type::eq_int_type(ch, traits_type::eof())) sputc(ch); return traits_type::not_eof(ch); } template int wbuffer_convert::sync() { if (output_bufctx) { output_bufctx->from_end = pptr(); //current position in put area while (output_bufctx->from_end - output_bufctx->from_beg) { if (!writesome(*output_bufctx)) return -1; //failure output_bufctx->from_end = output_bufctx->from_stopped; } } return wrapped->pubsync(); } } //namespace codecvt_convert } //namespace ext #include #include #include "utils.h" #include "CController.h" #include "CTimer.h" #include "resource.h" #include "CParams.h" ///////////////////////GLOBALS //////////////////////////////////// char* szApplicationName = "Chapter 11 - NEAT evolution"; char* szWindowClassName = "sweeper"; char* szInfoWindowClassName = "Info Window"; //The controller class for this simulation CController* g_pController = NULL; CParams g_Params; //global handle to the info window HWND g_hwndInfo = NULL; //global handle to the main window HWND g_hwndMain = NULL; //---------------------------- Cleanup ---------------------------------- // // simply cleans up any memory issues when the application exits //----------------------------------------------------------------------- void Cleanup() { if (g_pController) delete g_pController; } //-----------------------------------WinProc----------------------------- // //----------------------------------------------------------------------- LRESULT CALLBACK WindowProc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam) { //these hold the dimensions of the client window area static int cxClient, cyClient; //used to create the back buffer static HDC hdcBackBuffer; static HBITMAP hBitmap; static HBITMAP hOldBitmap; switch(msg) { case WM_CREATE: { //seed the random number generator srand((unsigned) time(NULL)); //get the size of the client window RECT rect; GetClientRect(hwnd, &rect); cxClient = rect.right; cyClient = rect.bottom; //setup the controller g_pController = new CController(hwnd, cxClient, cyClient); //create a surface for us to render to(backbuffer) hdcBackBuffer = CreateCompatibleDC(NULL); HDC hdc = GetDC(hwnd); hBitmap = CreateCompatibleBitmap(hdc, cxClient, cyClient); ReleaseDC(hwnd, hdc); hOldBitmap = (HBITMAP)SelectObject(hdcBackBuffer, hBitmap); } break; //check key press messages case WM_KEYUP: { switch(wparam) { case VK_ESCAPE: { PostQuitMessage(0); } break; case 'F': { g_pController->FastRenderToggle(); } break; case 'B': { g_pController->RenderBestToggle(); } break; case 'R': { if (g_pController) { delete g_pController; } //setup the new controller g_pController = new CController(hwnd, cxClient, cyClient); //give the info window's handle to the controller g_pController->PassInfoHandle(g_hwndInfo); //clear info window InvalidateRect(g_hwndInfo, NULL, TRUE); UpdateWindow(g_hwndInfo); } break; case '1': { g_pController->ViewBest(1); } break; case '2': { g_pController->ViewBest(2); } break; case '3': { g_pController->ViewBest(3); } break; case '4': { g_pController->ViewBest(4); } break; }//end WM_KEYUP switch } break; //has the user resized the client area? case WM_SIZE: { cxClient = LOWORD(lparam); cyClient = HIWORD(lparam); } break; case WM_PAINT: { PAINTSTRUCT ps; BeginPaint(hwnd, &ps); //fill our backbuffer with white BitBlt(hdcBackBuffer, 0, 0, cxClient, cyClient, NULL, NULL, NULL, WHITENESS); //render the sweepers g_pController->Render(hdcBackBuffer); //now blit backbuffer to front BitBlt(ps.hdc, 0, 0, cxClient, cyClient, hdcBackBuffer, 0, 0, SRCCOPY); EndPaint(hwnd, &ps); } break; case WM_DESTROY: { SelectObject(hdcBackBuffer, hOldBitmap); //clean up our backbuffer objects DeleteDC(hdcBackBuffer); DeleteObject(hBitmap); // kill the application, this sends a WM_QUIT message PostQuitMessage(0); } break; default:break; }//end switch // default msg handler return (DefWindowProc(hwnd, msg, wparam, lparam)); }//end WinProc //-----------------------------------InfoWinProc----------------------------- // //----------------------------------------------------------------------- LRESULT CALLBACK InfoWindowProc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam) { //these hold the dimensions of the client window area static int cxClient, cyClient; switch(msg) { case WM_CREATE: { //get the size of the client window RECT rect; GetClientRect(hwnd, &rect); cxClient = rect.right; cyClient = rect.bottom; } break; //has the user resized the client area? case WM_SIZE: { cxClient = LOWORD(lparam); cyClient = HIWORD(lparam); } break; case WM_PAINT: { PAINTSTRUCT ps; BeginPaint(hwnd, &ps); g_pController->RenderNetworks(ps.hdc); EndPaint(hwnd, &ps); } break; default:break; }//end switch // default msg handler return (WindowProc(hwnd, msg, wparam, lparam)); }//end WinProc //---------------------------------CreateInfoWindow--------------------------- // // creates and displays the info window // //---------------------------------------------------------------------------- void CreateInfoWindow(HWND hwndParent) { // Create and register the window class WNDCLASSEX wcInfo = {sizeof(WNDCLASSEX), CS_HREDRAW | CS_VREDRAW, InfoWindowProc, 0, 0, GetModuleHandle(NULL), NULL, NULL, (HBRUSH)(GetStockObject(WHITE_BRUSH)), NULL, "Info", NULL }; RegisterClassEx( &wcInfo ); // Create the application's info window g_hwndInfo = CreateWindow("Info", "Previous generation's best four phenotypes", WS_OVERLAPPED | WS_VISIBLE | WS_CAPTION | WS_SYSMENU, GetSystemMetrics(SM_CXSCREEN)/2, GetSystemMetrics(SM_CYSCREEN)/2 - CParams::WindowHeight/2, CParams::InfoWindowWidth, CParams::InfoWindowHeight, hwndParent, NULL, wcInfo.hInstance, NULL ); // Show the info ShowWindow(g_hwndInfo, SW_SHOWDEFAULT); UpdateWindow(g_hwndInfo); //give the info window's handle to the controller g_pController->PassInfoHandle(g_hwndInfo); return; } //-----------------------------------WinMain----------------------------------------- // Entry point for our windows application //----------------------------------------------------------------------------------- int WINAPI WinMain( HINSTANCE hinstance, HINSTANCE hprevinstance, LPSTR lpcmdline, int ncmdshow) { WNDCLASSEX winclass; HWND hwnd; MSG msg; //load in the parameters for the program if (!g_Params.Initialize()) { return false; } // first fill in the window class stucture winclass.cbSize = sizeof(WNDCLASSEX); winclass.style = CS_HREDRAW | CS_VREDRAW; winclass.lpfnWndProc = WindowProc; winclass.cbClsExtra = 0; winclass.cbWndExtra = 0; winclass.hInstance = hinstance; winclass.hIcon = LoadIcon(hinstance, MAKEINTRESOURCE(IDI_ICON1)); winclass.hCursor = LoadCursor(NULL, IDC_ARROW); winclass.hbrBackground= NULL; winclass.lpszMenuName = NULL; winclass.lpszClassName= szWindowClassName; winclass.hIconSm = LoadIcon(hinstance, MAKEINTRESOURCE(IDI_ICON1)); // register the window class if (!RegisterClassEx(&winclass)) { MessageBox(NULL, "Error Registering Class!", "Error", 0); return 0; } // create the window (one that cannot be resized) if (!(hwnd = CreateWindowEx(NULL, szWindowClassName, szApplicationName, WS_OVERLAPPED | WS_VISIBLE | WS_CAPTION | WS_SYSMENU, GetSystemMetrics(SM_CXSCREEN)/2 - CParams::WindowWidth, GetSystemMetrics(SM_CYSCREEN)/2 - CParams::WindowHeight/2, CParams::WindowWidth, CParams::WindowHeight, NULL, NULL, hinstance, NULL))) { MessageBox(NULL, "Error Creating Window!", "Error", 0); return 0; } //keep a global record of the window handle g_hwndMain = hwnd; //create and show the info window CreateInfoWindow(hwnd); //Show the window ShowWindow(hwnd, SW_SHOWDEFAULT ); UpdateWindow(hwnd); //create a timer CTimer timer(CParams::iFramesPerSecond); //start the timer timer.Start(); // Enter the message loop bool bDone = FALSE; while(!bDone) { while( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) ) { if( msg.message == WM_QUIT ) { // Stop loop if it's a quit message bDone = TRUE; } else { TranslateMessage( &msg ); DispatchMessage( &msg ); } } if (timer.ReadyForNextFrame() || g_pController->FastRender()) { if(!g_pController->Update()) { //we have a problem, end app bDone = TRUE; } //this will call WM_PAINT which will render our scene InvalidateRect(hwnd, NULL, TRUE); UpdateWindow(hwnd); } }//end while // Clean up everything and exit the app Cleanup(); UnregisterClass( szWindowClassName, winclass.hInstance ); return 0; } // end WinMain src/ast/expr.cpp #include "expr.hpp" #include #include #include "../base/common.hpp" #include "param.hpp" void NumberExpr::UpdateDepth(int depth) { Expr::UpdateDepth(depth); if (p_number_) p_number_->UpdateDepth(depth + 1); } void NumberExpr::Print(std::ostream& os) const { Expr::Print(os); if (p_number_) p_number_->Print(os); } std::string NumberExpr::value() const { auto number = p_number_ ? p_number_->value() : ""; return number; } void LvalueExpr::UpdateDepth(int depth) { Expr::UpdateDepth(depth); if (p_lvalue_) p_lvalue_->UpdateDepth(depth + 1); } void LvalueExpr::Print(std::ostream& os) const { Expr::Print(os); if (p_lvalue_) p_lvalue_->Print(os); } std::string LvalueExpr::value() const { auto lvalue = p_lvalue_ ? p_lvalue_->value() : ""; return lvalue; } void ParenExpr::UpdateDepth(int depth) { Expr::UpdateDepth(depth); if (p_expr_) p_expr_->UpdateDepth(depth + 1); } void ParenExpr::Print(std::ostream& os) const { Expr::Print(os); if (p_expr_) p_expr_->Print(os); } std::string ParenExpr::value() const { auto expr = p_expr_ ? p_expr_->value() : ""; return "(" + expr + ")"; } void UnaryExpr::UpdateDepth(int depth) { Expr::UpdateDepth(depth); if (p_op_) p_op_->UpdateDepth(depth + 1); if (p_expr_) p_expr_->UpdateDepth(depth + 1); } void UnaryExpr::Print(std::ostream& os) const { Expr::Print(os); if (p_op_) p_op_->Print(os); if (p_expr_) p_expr_->Print(os); } std::string UnaryExpr::value() const { auto op = p_op_ ? p_op_->value() : ""; auto expr = p_expr_ ? p_expr_->value() : ""; return op + expr; } void BinaryExpr::UpdateDepth(int depth) { Expr::UpdateDepth(depth); if (p_expr1_) p_expr1_->UpdateDepth(depth + 1); if (p_op_) p_op_->UpdateDepth(depth + 1); if (p_expr2_) p_expr2_->UpdateDepth(depth + 1); } void BinaryExpr::Print(std::ostream& os) const { Expr::Print(os); if (p_expr1_) p_expr1_->Print(os); if (p_op_) p_op_->Print(os); if (p_expr2_) p_expr2_->Print(os); } std::string BinaryExpr::value() const { auto expr1 = p_expr1_ ? p_expr1_->value() : ""; auto op = p_op_ ? p_op_->value() : ""; auto expr2 = p_expr2_ ? p_expr2_->value() : ""; return expr1 + " " + op + " " + expr2; } void ProcCallExpr::UpdateDepth(int depth) { Expr::UpdateDepth(depth); if (p_id_) p_id_->UpdateDepth(depth + 1); if (p_actual_params_) p_actual_params_->UpdateDepth(depth + 1); } void ProcCallExpr::Print(std::ostream& os) const { Expr::Print(os); if (p_id_) p_id_->Print(os); if (p_actual_params_) p_actual_params_->Print(os); } std::string ProcCallExpr::value() const { auto id = p_id_ ? p_id_->value() : ""; return id + "()"; } void CompValues::UpdateDepth(int depth) { Node::UpdateDepth(depth); if (p_assign_exprs_) p_assign_exprs_->UpdateDepth(depth + 1); } void CompValues::Print(std::ostream& os) const { Node::Print(os); if (p_assign_exprs_) p_assign_exprs_->Print(os); } void RecordConstrExpr::UpdateDepth(int depth) { Expr::UpdateDepth(depth); if (p_id_) p_id_->UpdateDepth(depth + 1); if (p_comp_values_) p_comp_values_->UpdateDepth(depth + 1); } void RecordConstrExpr::Print(std::ostream& os) const { Expr::Print(os); if (p_id_) p_id_->Print(os); if (p_comp_values_) p_comp_values_->Print(os); } std::string RecordConstrExpr::value() const { auto id = p_id_ ? p_id_->value() : ""; return id + "{}"; } void ArrayValues::UpdateDepth(int depth) { Node::UpdateDepth(depth); if (p_array_exprs_) p_array_exprs_->UpdateDepth(depth + 1); } void ArrayValues::Print(std::ostream& os) const { Node::Print(os); if (p_array_exprs_) p_array_exprs_->Print(os); } void ArrayConstrExpr::UpdateDepth(int depth) { Expr::UpdateDepth(depth); if (p_id_) p_id_->UpdateDepth(depth + 1); if (p_array_values_) p_array_values_->UpdateDepth(depth + 1); } void ArrayConstrExpr::Print(std::ostream& os) const { Expr::Print(os); if (p_id_) p_id_->Print(os); if (p_array_values_) p_array_values_->Print(os); } std::string ArrayConstrExpr::value() const { auto id = p_id_ ? p_id_->value() : ""; return id + "[<>]"; } void WriteExpr::UpdateDepth(int depth) { Expr::UpdateDepth(depth); auto visitor = Overloaded{ [depth](auto&& p) { if (p) p->UpdateDepth(depth + 1); }, }; std::visit(visitor, p_write_expr_); } void WriteExpr::Print(std::ostream& os) const { Expr::Print(os); auto visitor = Overloaded{ [&os](auto&& p) { if (p) p->Print(os); }, }; std::visit(visitor, p_write_expr_); } std::string WriteExpr::value() const { auto visitor = Overloaded{ [](const auto& p) { auto value = p ? p->value() : ""; return value; }, }; return std::visit(visitor, p_write_expr_); } void AssignExpr::UpdateDepth(int depth) { Expr::UpdateDepth(depth); if (p_id_) p_id_->UpdateDepth(depth + 1); if (p_expr_) p_expr_->UpdateDepth(depth + 1); } void AssignExpr::Print(std::ostream& os) const { Expr::Print(os); if (p_id_) p_id_->Print(os); if (p_expr_) p_expr_->Print(os); } std::string AssignExpr::value() const { auto id = p_id_ ? p_id_->value() : ""; auto expr = p_expr_ ? p_expr_->value() : ""; return id + " := " + expr; } void ArrayExpr::UpdateDepth(int depth) { Expr::UpdateDepth(depth); if (p_value_) p_value_->UpdateDepth(depth + 1); if (p_num_) p_num_->UpdateDepth(depth + 1); } void ArrayExpr::Print(std::ostream& os) const { Expr::Print(os); if (p_value_) p_value_->Print(os); if (p_num_) p_num_->Print(os); } std::string ArrayExpr::value() const { auto value = p_value_ ? p_value_->value() : ""; auto num = p_num_ ? p_num_->value() + " OF " : ""; return num + value; } #include #include using namespace std; int main(){ int i, j, k, sp, space = 4; char prt = '$'; //printing the upper half of the first diamond for (i = 1; i <= 5; i++){ //printing the spaces in the front for (sp = space; sp >= 1; sp--){ cout << " "; } //printing $ character for (j = 1; j <= i; j++){ cout << prt; } for (k = 1; k <= (i - 1); k++){ if (i == 1){ continue; } cout << prt; } cout << "\n"; space--; } space = 1; //printing the lower half of the first diamond for (i = 4; i >= 1; i--){ for (sp = space; sp >= 1; sp--) { cout << " "; } for (j = 1; j <= i; j++){ cout << prt; } for (k = 1; k <= (i - 1); k++){ cout << prt; } space++; cout << "\n"; } space = 3; //printing the second incomplete diamond for (i = 2; i <= 5; i++){ if ((i % 2) != 0){ for (sp = space; sp >= 1; sp--){ cout << " "; } for (j = 1; j <= i; j++){ cout << prt; } } if ((i % 2) != 0) { cout << "\n"; space--; } } return 0; }// // Copyright (C) 2004-2011 by Autodesk, Inc. // // This library is free software; you can redistribute it and/or // modify it under the terms of version 2.1 of the GNU Lesser // General Public License as published by the Free Software Foundation. // // 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 St, Fifth Floor, Boston, MA 02110-1301 USA // #include "MapGuideCommon.h" #include "ServerStreamData.h" //------------------------------------------------------------------------- // Constructors/Destructors //------------------------------------------------------------------------- /////////////////////////////////////////////////////////////////////////// // // Constructs a MgServerStreamData object with the given parameters/ // // // // The ClientHandler object that is handling this stream. // // // // The ACE_HANDLE underlying the stream. // // // // The MgStreamHelper object that handles data I/O for this stream. // MgServerStreamData::MgServerStreamData( MgClientHandler* pHandler, ACE_HANDLE handle, MgStreamHelper* pStreamHelper ) : m_pClientHandler( SAFE_ADDREF(pHandler) ), MgStreamData( handle, pStreamHelper ) { ACE_ASSERT( pHandler != NULL ); }; /////////////////////////////////////////////////////////////////////////// // // Constructs a new MgServerStreamData object with the given MgServerStreamData object // // // // The MgServerStreamData object to copy for the new object. // MgServerStreamData::MgServerStreamData( MgServerStreamData © ) : m_pClientHandler( copy.m_pClientHandler.Detach() ), MgStreamData( copy ) { ACE_ASSERT( NULL != (MgClientHandler*) m_pClientHandler ); }; /////////////////////////////////////////////////////////////////////////// // // The destructor for the MgServerStreamData object. // MgServerStreamData::~MgServerStreamData() { }; //------------------------------------------------------------------------- // Properties //------------------------------------------------------------------------- /////////////////////////////////////////////////////////////////////////// // // Gets a pointer to the MgClientHandler that owns this stream. // // // // Returns a pointer to a MgClientHandler. // MgClientHandler* MgServerStreamData::GetClientHandler() { return SAFE_ADDREF((MgClientHandler*)m_pClientHandler); }; // Debugging code... void LogStream(char* buf, ...) { va_list ap; va_start(ap, buf); static FILE* fp = NULL; if (NULL == fp) { fp = fopen("c:\\temp\\logStream.log","w"); } time_t timeNow; time(&timeNow); if (NULL != fp) { fprintf(fp, ctime(&timeNow)); vfprintf(fp, buf, ap); fflush(fp); } va_end(ap); } CodeForces/Practice/235A.cpp /*coderanant*/ #include using namespace std; #define int long long #define ll long long #define f1(i,a,b) for(int i=a;i=b;i--) #define endl '\n' #define pb push_back #define gp " " #define ff first #define ss second #define mp make_pair const int mod=1000000007; ll temp; int mul(int a, int b, int c) { a = a*b/__gcd(a, b); a = a*c/__gcd(a, c); return a; } int32_t main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int n; cin>>n; int ans = 1; f1(i, max(1ll, n-50), n+1) { f1(j, max(1ll, n-50), n+1) { f1(k, max(1ll, n-50), n+1) { ans = max(ans, mul(i, j, k)); } } } cout<0 #ifndef jm4R_STRING_BUILDER #define jm4R_STRING_BUILDER #include "strcat.hpp" #include #include #include namespace mj { template struct basic_string_builder { std::tuple vals; template constexpr static bool needs_to_string = !std::is_constructible_v, T&>; template constexpr auto operator<<(const T& v) && -> basic_string_builder< CharT, Args..., std::conditional_t, std::basic_string, const T&>> { if constexpr (!needs_to_string) return {std::tuple_cat(vals, std::tuple{v})}; else return {std::tuple_cat( vals, std::tuple>{std::to_string(v)})}; } constexpr operator std::basic_string() && { return std::apply( [&](auto&... vals) { return mj::basic_strcat(vals...); }, vals); } }; template using string_builder = basic_string_builder; template using wstring_builder = basic_string_builder; template constexpr auto basic_build_string() { return basic_string_builder{}; } constexpr auto build_string() { return string_builder<>{}; } constexpr auto build_wstring() { return wstring_builder<>{}; } } #endif //jm4R_STRING_BUILDER vovkos/axl //.............................................................................. // // This file is part of the AXL library. // // AXL is distributed under the MIT license. // For details see accompanying license.txt file, // the public copy of which is also available at: // http://tibbo.com/downloads/archive/axl/license.txt // //.............................................................................. #include "pch.h" #include "axl_enc_HexEncoding.h" namespace axl { namespace enc { //.............................................................................. class InsertNoSpace { public: size_t operator () ( char* p, size_t i ) { return 0; } }; class InsertNoSpaceMultiline { public: size_t operator () ( char* p, size_t i ) { if (i & 0x0f) return 0; *p = '\n'; return 1; } }; class InsertSpace { public: size_t operator () ( char* p, size_t i ) { *p = ' '; return 1; } }; class InsertSpaceMultiline { public: size_t operator () ( char* p, size_t i ) { *p = (i & 0x0f) ? ' ' : '\n'; return 1; } }; // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . template < typename GetHexChar, typename InsertSpace > void encodeImpl( char* dst, const uchar_t* src, size_t size ) { uchar_t x = src[0]; *dst++ = GetHexChar()(x >> 4); *dst++ = GetHexChar()(x); for (size_t i = 1; i < size; i++) { uchar_t x = src[i]; dst += InsertSpace()(dst, i); *dst++ = GetHexChar()(x >> 4); *dst++ = GetHexChar()(x); } } //.............................................................................. size_t HexEncoding::encode( sl::String* string, const void* p, size_t size, uint_t flags ) { if (!size) { string->clear(); return 0; } const uchar_t* src = (const uchar_t*) p; size_t length; if ((flags & HexEncodingFlag_NoSpace)) { length = size * 2; if (flags & HexEncodingFlag_Multiline) { size_t lineCount = length / 16; if (lineCount & 0x0f) lineCount++; length += lineCount - 1; } char* dst = string->createBuffer(length); if (!dst) return -1; if (flags & HexEncodingFlag_Multiline) if (flags & HexEncodingFlag_UpperCase) encodeImpl(dst, src, size); else encodeImpl(dst, src, size); else if (flags & HexEncodingFlag_UpperCase) encodeImpl(dst, src, size); else encodeImpl(dst, src, size); } else { length = size * 3 - 1; char* dst = string->createBuffer(length); if (!dst) return -1; if (flags & HexEncodingFlag_Multiline) if (flags & HexEncodingFlag_UpperCase) encodeImpl(dst, src, size); else encodeImpl(dst, src, size); else if (flags & HexEncodingFlag_UpperCase) encodeImpl(dst, src, size); else encodeImpl(dst, src, size); } return length; } size_t HexEncoding::decode( sl::Array* buffer, const sl::StringRef& source ) { enum State { State_Normal = 0, State_Hex }; State state = State_Normal; buffer->clear(); buffer->reserve(source.getLength() / 2); char hexCodeString[4] = { 0 }; char* hexCodeEnd; size_t hexCodeLen; uchar_t x; const char* p = source.cp(); const char* end = source.getEnd(); for (; p < end; p++) { bool_t isSpace = isspace(*p); switch (state) { case State_Normal: if (isSpace) break; hexCodeString[0] = *p; hexCodeLen = 1; state = State_Hex; break; case State_Hex: if (!isSpace) { hexCodeString[hexCodeLen++] = *p; if (hexCodeLen < 2) break; } hexCodeString[hexCodeLen] = 0; x = (uchar_t)strtoul(hexCodeString, &hexCodeEnd, 16); if (hexCodeEnd == &hexCodeString[hexCodeLen]) buffer->append(x); else p = end; // not a hex string anymore, break the loop state = State_Normal; break; } } if (state == State_Hex) { hexCodeString[hexCodeLen] = 0; x = (uchar_t)strtoul(hexCodeString, &hexCodeEnd, 16); if (hexCodeEnd == &hexCodeString[hexCodeLen]) buffer->append(x); } return buffer->getCount(); } //.............................................................................. } // namespace enc } // namespace axl /************************************************************** * * 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. * *************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_svx.hxx" #include // header for class OGuard #include // header for class Application #include #include "unomlstr.hxx" using namespace ::com::sun::star; SvxUnoShapeModifyListener::SvxUnoShapeModifyListener( SdrObject* pObj ) throw() { mpObj = pObj; } SvxUnoShapeModifyListener::~SvxUnoShapeModifyListener() throw() { } // ::com::sun::star::util::XModifyListener void SAL_CALL SvxUnoShapeModifyListener::modified(const lang::EventObject& ) throw( uno::RuntimeException ) { ::vos::OGuard aGuard( Application::GetSolarMutex() ); if( mpObj ) { mpObj->SetChanged(); mpObj->BroadcastObjectChange(); } } // ::com::sun::star::lang::XEventListener void SvxUnoShapeModifyListener::disposing(const lang::EventObject& ) throw( uno::RuntimeException ) { invalidate(); } // internal void SvxUnoShapeModifyListener::invalidate() throw() { mpObj = NULL; } 1-10 /** * 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 AppMesh { namespace Model { MeshSpec::MeshSpec() : m_egressFilterHasBeenSet(false) { } MeshSpec::MeshSpec(JsonView jsonValue) : m_egressFilterHasBeenSet(false) { *this = jsonValue; } MeshSpec& MeshSpec::operator =(JsonView jsonValue) { if(jsonValue.ValueExists("egressFilter")) { m_egressFilter = jsonValue.GetObject("egressFilter"); m_egressFilterHasBeenSet = true; } return *this; } JsonValue MeshSpec::Jsonize() const { JsonValue payload; if(m_egressFilterHasBeenSet) { payload.WithObject("egressFilter", m_egressFilter.Jsonize()); } return payload; } } // namespace Model } // namespace AppMesh } // namespace Aws // Copyright (c) 2017-2018 Telos Foundation & contributors // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #pragma once #include "xbasic/xns_macro.h" #include #include NS_BEG1(top) template class xtop_range final { public: T begin{}; T end{}; constexpr xtop_range() = default; xtop_range(xtop_range const &) = default; xtop_range & operator=(xtop_range const &) = default; xtop_range(xtop_range &&) = default; xtop_range & operator=(xtop_range &&) = default; ~xtop_range() = default; constexpr xtop_range(T const & b, T const & e) noexcept(std::is_nothrow_copy_constructible::value) : begin{ b }, end{ e } { } constexpr xtop_range(T && b, T && e) noexcept(std::is_nothrow_move_constructible::value) : begin{ std::move(b) }, end{ std::move(e) } { } constexpr bool empty() const noexcept { return begin == end; } bool operator==(xtop_range const & other) const noexcept { return begin == other.begin && end == other.end; } bool operator!=(xtop_range const & other) const noexcept { return !(*this == other); } void clear() noexcept { begin = T{}; end = T{}; } }; template using xrange_t = xtop_range; NS_END1 demo6/math/foo.cpp int foo() { return 600; }#include #import "LinkedList.h" int main() { LinkedList list; list.append(1); list.append(2); list.append(3); list.append(4); list.print(); list.recursive_reverse(); list.print(); return 0; }weikm/sandcarSimulation2 #include "Dynamics/RigidBody/Transformation6d.h" namespace PhysIKA { }Include/Types/Vector4.hpp #pragma once #include "Core/Common.h" #include #include #include #include namespace vk2d { /// @brief This is a 4D vector containing 4 values in {XYZW} order. A vector can /// be a unit vector meaning it's lenght is always 1.0 or it can /// represent a location in coordinate space. /// @tparam T /// Type precision of this vector. template class Vector4Base { public: T x = {}; T y = {}; T z = {}; T w = {}; Vector4Base() = default; Vector4Base( T x, T y, T z, T w ) : x( x ), y( y ), z( z ), w( w ) {}; Vector4Base( const vk2d::Vector4Base & other ) = default; Vector4Base( vk2d::Vector4Base && other ) = default; Vector4Base( const std::initializer_list & elements ) { auto s = elements.size(); assert( s <= 4 ); auto e = elements.begin(); x = ( s >= 1 ) ? *e++ : T{}; y = ( s >= 2 ) ? *e++ : T{}; z = ( s >= 3 ) ? *e++ : T{}; w = ( s >= 4 ) ? *e++ : T{}; } vk2d::Vector4Base & operator=( const vk2d::Vector4Base & other ) = default; vk2d::Vector4Base & operator=( vk2d::Vector4Base && other ) = default; /// @brief Simple add vector to vector. Directly adds each value of this with /// each value of other. /// @param[in] other /// Other vector to add to this. /// @return A new vector. vk2d::Vector4Base operator+( vk2d::Vector4Base other ) const { return { x + other.x, y + other.y, z + other.z, w + other.w }; } /// @brief Simple substract from this vector. Directly substracts each value /// of this with each value of other. /// @param[in] other /// Other vector to substract from this. /// @return A new vector. vk2d::Vector4Base operator-( vk2d::Vector4Base other ) const { return { x - other.x, y - other.y, z - other.z, w - other.w }; } /// @brief Simple multiplication of this and other. Directly multiplies each /// value of this with each value of other. /// @param[in] other /// Other vector to multiply this with. /// @return A new vector. vk2d::Vector4Base operator*( vk2d::Vector4Base other ) const { return { x * other.x, y * other.y, z * other.z, w * other.w }; } /// @brief Simple division of this and other. Directly divide each value of /// this with each value of other. /// @param[in] other /// Other vector to devide with this. /// @return A new vector. vk2d::Vector4Base operator/( vk2d::Vector4Base other ) const { return { x / other.x, y / other.y, z / other.z, w / other.w }; } /// @brief Simple multiplication with a single value. Directly multiply each /// value of this with scalar. /// @param[in] scalar /// Multiply this with scalar. /// @return A new vector. vk2d::Vector4Base operator*( T scalar ) const { return { x * scalar, y * scalar, z * scalar, w * scalar }; } /// @brief Simple division with a single value. Directly divide each value of /// this with scalar. /// @param[in] scalar /// Divide this vector with scalar. /// @return A new vector. vk2d::Vector4Base operator/( T scalar ) const { return { x / scalar, y / scalar, z / scalar, w / scalar }; } /// @brief Simple add vector to vector. Directly adds each value of this with /// each value of other and store the result back to itself. /// @param[in] other /// Other vector to add to this. /// @return A reference to this. vk2d::Vector4Base & operator+=( vk2d::Vector4Base other ) { x += other.x; y += other.y; z += other.z; w += other.w; return *this; } /// @brief Simple divide from this vector. Directly substracts each value of /// this with each value of other and store the result back to itself. /// @param[in] other /// Other vector to substract from this. /// @return A reference to this. vk2d::Vector4Base & operator-=( vk2d::Vector4Base other ) { x -= other.x; y -= other.y; z -= other.z; w -= other.w; return *this; } /// @brief Simple multiplication of this and other. Directly multiplies each /// value of this with each value of other and store the result back /// to itself. /// @param[in] other /// Other vector to multiply this with. /// @return A reference to this. vk2d::Vector4Base & operator*=( vk2d::Vector4Base other ) { x *= other.x; y *= other.y; z *= other.z; w *= other.w; return *this; } /// @brief Simple division of this and other. Directly divide each value of /// this with each value of other and store the result back to itself. /// @param[in] other /// Other vector to devide with this. /// @return A reference to this. vk2d::Vector4Base & operator/=( vk2d::Vector4Base other ) { x /= other.x; y /= other.y; z /= other.z; w /= other.w; return *this; } /// @brief Simple multiplication with a single value. Directly multiply each /// value of this with scalar and store the result back to itself. /// @param[in] scalar /// Multiply this with scalar. /// @return A reference to this. vk2d::Vector4Base & operator*=( T scalar ) { x *= scalar; y *= scalar; z *= scalar; w *= scalar; return *this; } /// @brief Simple division with a single value. Directly divide each value of /// this with scalar and store the result back to itself. /// @param[in] scalar /// Divide this vector with scalar. /// @return A reference to this. vk2d::Vector4Base & operator/=( T scalar ) { x /= scalar; y /= scalar; z /= scalar; w /= scalar; return *this; } bool operator==( vk2d::Vector4Base other ) { return x == other.x && y == other.y && z == other.z && w == other.w; } bool operator!=( vk2d::Vector4Base other ) { return x != other.x || y != other.y || z != other.z || w != other.w; } /// @brief Calculate basic distance between this and another vector. /// If vector is integer type then distance is rounded as per math rules. /// @param other /// Other vector to calculate distance to. /// @return Distance between the vectors. T CalculateDistanceTo( vk2d::Vector4Base other ) { if constexpr( std::is_integral_v ) { vk2d::Vector4Base temp = *this - other; return T( std::round( std::sqrt( double( temp.x ) * double( temp.x ) + double( temp.y ) * double( temp.y ) + double( temp.z ) * double( temp.z ) + double( temp.w ) * double( temp.w ) ) ) ); } else { vk2d::Vector4Base temp = *this - other; return T( std::sqrt( temp.x * temp.x + temp.y * temp.y + temp.z * temp.z + temp.w * temp.w ) ); } } /// @brief Calculates normalized/unit vector of this. Changes the coordinates /// so that the lenght of the vector is 1.0 without changing where the /// vector is pointing. /// @return A new vector as unit vector. vk2d::Vector4Base CalculateNormalized() { auto distance = CalculateDistanceTo( {} ); if( distance <= T( vk2d::KINDA_SMALL_VALUE ) ) return vk2d::Vector4Base{ T( 1.0 ), T( 0.0 ), T( 0.0 ), T( 0.0 ) }; return *this / distance; } }; template std::ostream& operator<<(std::ostream& os, const Vector4Base& v) { return os << "[" << v.x << ", " << v.y << ", " << v.z << ", " << v.w << "]"; } /// @brief 4D vector with float precision. using Vector4f = vk2d::Vector4Base; /// @brief 4D vector with double precision. using Vector4d = vk2d::Vector4Base; /// @brief 4D vector with int32_t precision. using Vector4i = vk2d::Vector4Base; /// @brief 4D vector with uint32_t precision. using Vector4u = vk2d::Vector4Base; } // vk2d cl_dll/hl/hl_baseentity.cpp10-100 /*** * * Copyright (c) 1996-2002, Valve LLC. All rights reserved. * * This product contains software technology licensed from Id * Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. * All Rights Reserved. * * Use, distribution, and modification of this source code and/or resulting * object code is restricted to non-commercial enhancements to products from * Valve LLC. All other use, distribution, or modification is prohibited * without written permission from Valve LLC. * ****/ /* ========================== This file contains "stubs" of class member implementations so that we can predict certain weapons client side. From time to time you might find that you need to implement part of the these functions. If so, cut it from here, paste it in hl_weapons.cpp or somewhere else and add in the functionality you need. ========================== */ #include "extdll.h" #include "util.h" #include "cbase.h" #include "player.h" #include "weapons.h" #include "nodes.h" #include "soundent.h" #include "skill.h" void EMIT_SOUND_DYN(edict_t* entity, int channel, const char* sample, float volume, float attenuation, int flags, int pitch) {} // CBaseEntity Stubs bool CBaseEntity::TakeHealth(float flHealth, int bitsDamageType) { return true; } bool CBaseEntity::TakeDamage(entvars_t* pevInflictor, entvars_t* pevAttacker, float flDamage, int bitsDamageType) { return true; } CBaseEntity* CBaseEntity::GetNextTarget() { return NULL; } bool CBaseEntity::Save(CSave& save) { return true; } bool CBaseEntity::Restore(CRestore& restore) { return true; } void CBaseEntity::SetObjectCollisionBox() {} bool CBaseEntity::Intersects(CBaseEntity* pOther) { return false; } void CBaseEntity::MakeDormant() {} bool CBaseEntity::IsDormant() { return false; } bool CBaseEntity::IsInWorld() { return true; } bool CBaseEntity::ShouldToggle(USE_TYPE useType, bool currentState) { return false; } int CBaseEntity::DamageDecal(int bitsDamageType) { return -1; } CBaseEntity* CBaseEntity::Create(const char* szName, const Vector& vecOrigin, const Vector& vecAngles, edict_t* pentOwner) { return NULL; } void CBaseEntity::SUB_Remove() {} // CBaseDelay Stubs bool CBaseDelay::KeyValue(struct KeyValueData_s*) { return false; } bool CBaseDelay::Restore(class CRestore&) { return true; } bool CBaseDelay::Save(class CSave&) { return true; } // CBaseAnimating Stubs bool CBaseAnimating::Restore(class CRestore&) { return true; } bool CBaseAnimating::Save(class CSave&) { return true; } // DEBUG Stubs edict_t* DBG_EntOfVars(const entvars_t* pev) { return NULL; } void DBG_AssertFunction(bool fExpr, const char* szExpr, const char* szFile, int szLine, const char* szMessage) {} // UTIL_* Stubs void UTIL_PrecacheOther(const char* szClassname) {} void UTIL_BloodDrips(const Vector& origin, const Vector& direction, int color, int amount) {} void UTIL_DecalTrace(TraceResult* pTrace, int decalNumber) {} void UTIL_GunshotDecalTrace(TraceResult* pTrace, int decalNumber) {} void UTIL_MakeVectors(const Vector& vecAngles) {} bool UTIL_IsValidEntity(edict_t* pent) { return true; } void UTIL_SetOrigin(entvars_t*, const Vector& org) {} void UTIL_LogPrintf(char*, ...) {} void UTIL_ClientPrintAll(int, char const*, char const*, char const*, char const*, char const*) {} void ClientPrint(entvars_t* client, int msg_dest, const char* msg_name, const char* param1, const char* param2, const char* param3, const char* param4) {} // CBaseToggle Stubs bool CBaseToggle::Restore(class CRestore&) { return true; } bool CBaseToggle::Save(class CSave&) { return true; } bool CBaseToggle::KeyValue(struct KeyValueData_s*) { return false; } // CGrenade Stubs void CGrenade::BounceSound() {} void CGrenade::Explode(Vector, Vector) {} void CGrenade::Explode(TraceResult*, int) {} void CGrenade::Killed(entvars_t*, int) {} void CGrenade::Spawn() {} CGrenade* CGrenade::ShootTimed(entvars_t* pevOwner, Vector vecStart, Vector vecVelocity, float time) { return 0; } CGrenade* CGrenade::ShootContact(entvars_t* pevOwner, Vector vecStart, Vector vecVelocity) { return 0; } void CGrenade::DetonateUse(CBaseEntity* pActivator, CBaseEntity* pCaller, USE_TYPE useType, float value) {} void UTIL_Remove(CBaseEntity* pEntity) {} void UTIL_SetSize(entvars_t* pev, const Vector& vecMin, const Vector& vecMax) {} CBaseEntity* UTIL_FindEntityInSphere(CBaseEntity* pStartEntity, const Vector& vecCenter, float flRadius) { return 0; } Vector UTIL_VecToAngles(const Vector& vec) { return 0; } CSprite* CSprite::SpriteCreate(const char* pSpriteName, const Vector& origin, bool animate) { return 0; } void CBeam::PointEntInit(const Vector& start, int endIndex) {} CBeam* CBeam::BeamCreate(const char* pSpriteName, int width) { return NULL; } void CSprite::Expand(float scaleSpeed, float fadeSpeed) {} CBaseEntity* CBaseMonster::CheckTraceHullAttack(float flDist, int iDamage, int iDmgType) { return NULL; } void CBaseMonster::Eat(float flFullDuration) {} bool CBaseMonster::FShouldEat() { return true; } void CBaseMonster::BarnacleVictimBitten(entvars_t* pevBarnacle) {} void CBaseMonster::BarnacleVictimReleased() {} void CBaseMonster::Listen() {} float CBaseMonster::FLSoundVolume(CSound* pSound) { return 0.0; } bool CBaseMonster::FValidateHintType(short sHint) { return false; } void CBaseMonster::Look(int iDistance) {} int CBaseMonster::ISoundMask() { return 0; } CSound* CBaseMonster::PBestSound() { return NULL; } CSound* CBaseMonster::PBestScent() { return NULL; } float CBaseAnimating::StudioFrameAdvance(float flInterval) { return 0.0; } void CBaseMonster::MonsterThink() {} void CBaseMonster::MonsterUse(CBaseEntity* pActivator, CBaseEntity* pCaller, USE_TYPE useType, float value) {} int CBaseMonster::IgnoreConditions() { return 0; } void CBaseMonster::RouteClear() {} void CBaseMonster::RouteNew() {} bool CBaseMonster::FRouteClear() { return false; } bool CBaseMonster::FRefreshRoute() { return false; } bool CBaseMonster::MoveToEnemy(Activity movementAct, float waitTime) { return false; } bool CBaseMonster::MoveToLocation(Activity movementAct, float waitTime, const Vector& goal) { return false; } bool CBaseMonster::MoveToTarget(Activity movementAct, float waitTime) { return false; } bool CBaseMonster::MoveToNode(Activity movementAct, float waitTime, const Vector& goal) { return false; } bool ShouldSimplify(int routeType) { return true; } void CBaseMonster::RouteSimplify(CBaseEntity* pTargetEnt) {} bool CBaseMonster::FBecomeProne() { return true; } bool CBaseMonster::CheckRangeAttack1(float flDot, float flDist) { return false; } bool CBaseMonster::CheckRangeAttack2(float flDot, float flDist) { return false; } bool CBaseMonster::CheckMeleeAttack1(float flDot, float flDist) { return false; } bool CBaseMonster::CheckMeleeAttack2(float flDot, float flDist) { return false; } void CBaseMonster::CheckAttacks(CBaseEntity* pTarget, float flDist) {} bool CBaseMonster::FCanCheckAttacks() { return false; } bool CBaseMonster::CheckEnemy(CBaseEntity* pEnemy) { return false; } void CBaseMonster::PushEnemy(CBaseEntity* pEnemy, Vector& vecLastKnownPos) {} bool CBaseMonster::PopEnemy() { return false; } void CBaseMonster::SetActivity(Activity NewActivity) {} void CBaseMonster::SetSequenceByName(const char* szSequence) {} int CBaseMonster::CheckLocalMove(const Vector& vecStart, const Vector& vecEnd, CBaseEntity* pTarget, float* pflDist) { return 0; } float CBaseMonster::OpenDoorAndWait(entvars_t* pevDoor) { return 0.0; } void CBaseMonster::AdvanceRoute(float distance) {} int CBaseMonster::RouteClassify(int iMoveFlag) { return 0; } bool CBaseMonster::BuildRoute(const Vector& vecGoal, int iMoveFlag, CBaseEntity* pTarget) { return false; } void CBaseMonster::InsertWaypoint(Vector vecLocation, int afMoveFlags) {} bool CBaseMonster::FTriangulate(const Vector& vecStart, const Vector& vecEnd, float flDist, CBaseEntity* pTargetEnt, Vector* pApex) { return false; } void CBaseMonster::Move(float flInterval) {} bool CBaseMonster::ShouldAdvanceRoute(float flWaypointDist) { return false; } void CBaseMonster::MoveExecute(CBaseEntity* pTargetEnt, const Vector& vecDir, float flInterval) {} void CBaseMonster::MonsterInit() {} void CBaseMonster::MonsterInitThink() {} void CBaseMonster::StartMonster() {} void CBaseMonster::MovementComplete() {} bool CBaseMonster::TaskIsRunning() { return false; } int CBaseMonster::IRelationship(CBaseEntity* pTarget) { return 0; } bool CBaseMonster::FindCover(Vector vecThreat, Vector vecViewOffset, float flMinDist, float flMaxDist) { return false; } bool CBaseMonster::BuildNearestRoute(Vector vecThreat, Vector vecViewOffset, float flMinDist, float flMaxDist) { return false; } CBaseEntity* CBaseMonster::BestVisibleEnemy() { return NULL; } bool CBaseMonster::FInViewCone(CBaseEntity* pEntity) { return false; } bool CBaseMonster::FInViewCone(Vector* pOrigin) { return false; } bool CBaseEntity::FVisible(CBaseEntity* pEntity) { return false; } bool CBaseEntity::FVisible(const Vector& vecOrigin) { return false; } void CBaseMonster::MakeIdealYaw(Vector vecTarget) {} float CBaseMonster::FlYawDiff() { return 0.0; } float CBaseMonster::ChangeYaw(int yawSpeed) { return 0; } float CBaseMonster::VecToYaw(Vector vecDir) { return 0.0; } int CBaseAnimating::LookupActivity(int activity) { return 0; } int CBaseAnimating::LookupActivityHeaviest(int activity) { return 0; } void CBaseMonster::SetEyePosition() {} int CBaseAnimating::LookupSequence(const char* label) { return 0; } void CBaseAnimating::ResetSequenceInfo() {} int CBaseAnimating::GetSequenceFlags() { return 0; } void CBaseAnimating::DispatchAnimEvents(float flInterval) {} void CBaseMonster::HandleAnimEvent(MonsterEvent_t* pEvent) {} float CBaseAnimating::SetBoneController(int iController, float flValue) { return 0.0; } void CBaseAnimating::InitBoneControllers() {} float CBaseAnimating::SetBlending(int iBlender, float flValue) { return 0; } void CBaseAnimating::GetBonePosition(int iBone, Vector& origin, Vector& angles) {} void CBaseAnimating::GetAttachment(int iAttachment, Vector& origin, Vector& angles) {} int CBaseAnimating::FindTransition(int iEndingSequence, int iGoalSequence, int* piDir) { return -1; } void CBaseAnimating::GetAutomovement(Vector& origin, Vector& angles, float flInterval) {} void CBaseAnimating::SetBodygroup(int iGroup, int iValue) {} int CBaseAnimating::GetBodygroup(int iGroup) { return 0; } Vector CBaseMonster::GetGunPosition() { return g_vecZero; } void CBaseEntity::TraceAttack(entvars_t* pevAttacker, float flDamage, Vector vecDir, TraceResult* ptr, int bitsDamageType) {} void CBaseEntity::FireBullets(unsigned int cShots, Vector vecSrc, Vector vecDirShooting, Vector vecSpread, float flDistance, int iBulletType, int iTracerFreq, int iDamage, entvars_t* pevAttacker) {} void CBaseEntity::TraceBleed(float flDamage, Vector vecDir, TraceResult* ptr, int bitsDamageType) {} void CBaseMonster::MakeDamageBloodDecal(int cCount, float flNoise, TraceResult* ptr, const Vector& vecDir) {} bool CBaseMonster::FGetNodeRoute(Vector vecDest) { return true; } int CBaseMonster::FindHintNode() { return NO_NODE; } void CBaseMonster::ReportAIState() {} bool CBaseMonster::KeyValue(KeyValueData* pkvd) { return false; } bool CBaseMonster::FCheckAITrigger() { return false; } bool CBaseMonster::CanPlaySequence(bool fDisregardMonsterState, int interruptLevel) { return false; } bool CBaseMonster::FindLateralCover(const Vector& vecThreat, const Vector& vecViewOffset) { return false; } Vector CBaseMonster::ShootAtEnemy(const Vector& shootOrigin) { return g_vecZero; } bool CBaseMonster::FacingIdeal() { return false; } bool CBaseMonster::FCanActiveIdle() { return false; } void CBaseMonster::PlaySentence(const char* pszSentence, float duration, float volume, float attenuation) {} void CBaseMonster::PlayScriptedSentence(const char* pszSentence, float duration, float volume, float attenuation, bool bConcurrent, CBaseEntity* pListener) {} void CBaseMonster::SentenceStop() {} void CBaseMonster::CorpseFallThink() {} void CBaseMonster::MonsterInitDead() {} bool CBaseMonster::BBoxFlat() { return true; } bool CBaseMonster::GetEnemy() { return false; } void CBaseMonster::TraceAttack(entvars_t* pevAttacker, float flDamage, Vector vecDir, TraceResult* ptr, int bitsDamageType) {} CBaseEntity* CBaseMonster::DropItem(const char* pszItemName, const Vector& vecPos, const Vector& vecAng) { return NULL; } bool CBaseMonster::ShouldFadeOnDeath() { return false; } void CBaseMonster::RadiusDamage(entvars_t* pevInflictor, entvars_t* pevAttacker, float flDamage, int iClassIgnore, int bitsDamageType) {} void CBaseMonster::RadiusDamage(Vector vecSrc, entvars_t* pevInflictor, entvars_t* pevAttacker, float flDamage, int iClassIgnore, int bitsDamageType) {} void CBaseMonster::FadeMonster() {} void CBaseMonster::GibMonster() {} bool CBaseMonster::HasHumanGibs() { return false; } bool CBaseMonster::HasAlienGibs() { return false; } Activity CBaseMonster::GetDeathActivity() { return ACT_DIE_HEADSHOT; } MONSTERSTATE CBaseMonster::GetIdealState() { return MONSTERSTATE_ALERT; } Schedule_t* CBaseMonster::GetScheduleOfType(int Type) { return NULL; } Schedule_t* CBaseMonster::GetSchedule() { return NULL; } void CBaseMonster::RunTask(Task_t* pTask) {} void CBaseMonster::StartTask(Task_t* pTask) {} Schedule_t* CBaseMonster::ScheduleFromName(const char* pName) { return NULL; } void CBaseMonster::BecomeDead() {} void CBaseMonster::RunAI() {} void CBaseMonster::Killed(entvars_t* pevAttacker, int iGib) {} bool CBaseMonster::TakeHealth(float flHealth, int bitsDamageType) { return false; } bool CBaseMonster::TakeDamage(entvars_t* pevInflictor, entvars_t* pevAttacker, float flDamage, int bitsDamageType) { return false; } bool CBaseMonster::Restore(class CRestore&) { return true; } bool CBaseMonster::Save(class CSave&) { return true; } int TrainSpeed(int iSpeed, int iMax) { return 0; } void CBasePlayer::DeathSound() {} bool CBasePlayer::TakeHealth(float flHealth, int bitsDamageType) { return false; } void CBasePlayer::TraceAttack(entvars_t* pevAttacker, float flDamage, Vector vecDir, TraceResult* ptr, int bitsDamageType) {} bool CBasePlayer::TakeDamage(entvars_t* pevInflictor, entvars_t* pevAttacker, float flDamage, int bitsDamageType) { return false; } void CBasePlayer::PackDeadPlayerItems() {} void CBasePlayer::RemoveAllItems(bool removeSuit) {} void CBasePlayer::SetAnimation(PLAYER_ANIM playerAnim) {} void CBasePlayer::WaterMove() {} bool CBasePlayer::IsOnLadder() { return false; } void CBasePlayer::PlayerDeathThink() {} void CBasePlayer::StartDeathCam() {} void CBasePlayer::StartObserver(Vector vecPosition, Vector vecViewAngle) {} void CBasePlayer::PlayerUse() {} void CBasePlayer::Jump() {} void CBasePlayer::Duck() {} int CBasePlayer::Classify() { return 0; } void CBasePlayer::PreThink() {} void CBasePlayer::CheckTimeBasedDamage() {} void CBasePlayer::UpdateGeigerCounter() {} void CBasePlayer::CheckSuitUpdate() {} void CBasePlayer::SetSuitUpdate(const char* name, bool fgroup, int iNoRepeatTime) {} void CBasePlayer::UpdatePlayerSound() {} void CBasePlayer::PostThink() {} void CBasePlayer::Precache() {} bool CBasePlayer::Save(CSave& save) { return false; } void CBasePlayer::RenewItems() {} bool CBasePlayer::Restore(CRestore& restore) { return false; } void CBasePlayer::SelectNextItem(int iItem) {} bool CBasePlayer::HasWeapons() { return false; } void CBasePlayer::SelectPrevItem(int iItem) {} bool CBasePlayer::FlashlightIsOn() { return false; } void CBasePlayer::FlashlightTurnOn() {} void CBasePlayer::FlashlightTurnOff() {} void CBasePlayer::ForceClientDllUpdate() {} void CBasePlayer::ImpulseCommands() {} void CBasePlayer::CheatImpulseCommands(int iImpulse) {} bool CBasePlayer::AddPlayerItem(CBasePlayerItem* pItem) { return false; } bool CBasePlayer::RemovePlayerItem(CBasePlayerItem* pItem) { return false; } void CBasePlayer::ItemPreFrame() {} void CBasePlayer::ItemPostFrame() {} int CBasePlayer::AmmoInventory(int iAmmoIndex) { return -1; } int CBasePlayer::GetAmmoIndex(const char* psz) { return -1; } void CBasePlayer::SendAmmoUpdate() {} void CBasePlayer::UpdateClientData() {} bool CBasePlayer::FBecomeProne() { return true; } void CBasePlayer::BarnacleVictimBitten(entvars_t* pevBarnacle) {} void CBasePlayer::BarnacleVictimReleased() {} int CBasePlayer::Illumination() { return 0; } void CBasePlayer::EnableControl(bool fControl) {} Vector CBasePlayer::GetAutoaimVector(float flDelta) { return g_vecZero; } Vector CBasePlayer::GetAutoaimVectorFromPoint(const Vector& vecSrc, float flDelta) { return g_vecZero; } Vector CBasePlayer::AutoaimDeflection(const Vector& vecSrc, float flDist, float flDelta) { return g_vecZero; } void CBasePlayer::ResetAutoaim() {} void CBasePlayer::SetCustomDecalFrames(int nFrames) {} int CBasePlayer::GetCustomDecalFrames() { return -1; } void CBasePlayer::DropPlayerItem(char* pszItemName) {} bool CBasePlayer::HasPlayerItem(CBasePlayerItem* pCheckItem) { return false; } bool CBasePlayer::SwitchWeapon(CBasePlayerItem* pWeapon) { return false; } Vector CBasePlayer::GetGunPosition() { return g_vecZero; } const char* CBasePlayer::TeamID() { return ""; } int CBasePlayer::GiveAmmo(int iCount, const char* szName, int iMax) { return 0; } void CBasePlayer::AddPoints(int score, bool bAllowNegativeScore) {} void CBasePlayer::AddPointsToTeam(int score, bool bAllowNegativeScore) {} void CBasePlayer::TabulateAmmo() {} void ClearMultiDamage() {} void ApplyMultiDamage(entvars_t* pevInflictor, entvars_t* pevAttacker) {} void AddMultiDamage(entvars_t* pevInflictor, CBaseEntity* pEntity, float flDamage, int bitsDamageType) {} void SpawnBlood(Vector vecSpot, int bloodColor, float flDamage) {} int DamageDecal(CBaseEntity* pEntity, int bitsDamageType) { return 0; } void DecalGunshot(TraceResult* pTrace, int iBulletType) {} void EjectBrass(const Vector& vecOrigin, const Vector& vecVelocity, float rotation, int model, int soundtype) {} bool CBasePlayerItem::Restore(class CRestore&) { return true; } bool CBasePlayerItem::Save(class CSave&) { return true; } bool CBasePlayerWeapon::Restore(class CRestore&) { return true; } bool CBasePlayerWeapon::Save(class CSave&) { return true; } float CBasePlayerWeapon::GetNextAttackDelay(float flTime) { return flTime; } void CBasePlayerItem::SetObjectCollisionBox() {} void CBasePlayerItem::FallInit() {} void CBasePlayerItem::FallThink() {} void CBasePlayerItem::Materialize() {} void CBasePlayerItem::AttemptToMaterialize() {} void CBasePlayerItem::CheckRespawn() {} CBaseEntity* CBasePlayerItem::Respawn() { return NULL; } void CBasePlayerItem::DefaultTouch(CBaseEntity* pOther) {} void CBasePlayerItem::DestroyItem() {} bool CBasePlayerItem::AddToPlayer(CBasePlayer* pPlayer) { return true; } void CBasePlayerItem::Drop() {} void CBasePlayerItem::Kill() {} void CBasePlayerItem::Holster() {} void CBasePlayerItem::AttachToPlayer(CBasePlayer* pPlayer) {} bool CBasePlayerWeapon::AddDuplicate(CBasePlayerItem* pOriginal) { return false; } bool CBasePlayerWeapon::AddToPlayer(CBasePlayer* pPlayer) { return false; } bool CBasePlayerWeapon::UpdateClientData(CBasePlayer* pPlayer) { return false; } bool CBasePlayerWeapon::AddPrimaryAmmo(int iCount, char* szName, int iMaxClip, int iMaxCarry) { return true; } bool CBasePlayerWeapon::AddSecondaryAmmo(int iCount, char* szName, int iMax) { return true; } bool CBasePlayerWeapon::IsUseable() { return true; } int CBasePlayerWeapon::PrimaryAmmoIndex() { return m_iPrimaryAmmoType; } int CBasePlayerWeapon::SecondaryAmmoIndex() { return m_iSecondaryAmmoType; } void CBasePlayerAmmo::Spawn() {} CBaseEntity* CBasePlayerAmmo::Respawn() { return this; } void CBasePlayerAmmo::Materialize() {} void CBasePlayerAmmo::DefaultTouch(CBaseEntity* pOther) {} bool CBasePlayerWeapon::ExtractAmmo(CBasePlayerWeapon* pWeapon) { return false; } bool CBasePlayerWeapon::ExtractClipAmmo(CBasePlayerWeapon* pWeapon) { return false; } void CBasePlayerWeapon::RetireWeapon() {} void CSoundEnt::InsertSound(int iType, const Vector& vecOrigin, int iVolume, float flDuration) {} void RadiusDamage(Vector vecSrc, entvars_t* pevInflictor, entvars_t* pevAttacker, float flDamage, float flRadius, int iClassIgnore, int bitsDamageType) {}#include #include "common.h" #include "config.h" #include "MapXMLLoader.h" #include "MapData.h" #include "MapGraphics.h" #include "MapOperation.h" #include "MapGUI.h" #include "MapTaxiRoute.h" #include "MapPerformanceTest.h" #include "str2type.h" #include "wstr.h" #ifdef ZBY_OS_LINUX //#define ENABLE_HEAP_PROFILE //#define ENABLE_CPU_PROFILE #endif #ifdef ENABLE_CPU_PROFILE #include #endif #ifdef ENABLE_HEAP_PROFILE #include #endif static ConfigFilePraser cfgp; static MapData md; static MapXMLLoader xmlldr; static MapGraphics mg; static MapGUI mgui; static MapOperation mo; static MapShortestPath msp; static MapTaxiRoute mtr; static MapPerformanceTest mpt; int main(int argc, char *argv[]) { #ifdef ZBY_OS_LINUX setlocale(LC_ALL, "zh_CN.UTF-8"); #endif #ifdef ENABLE_HEAP_PROFILE HeapProfilerStart("pj_heap"); #endif cfgp.load("config.txt"); // load level configurations int tot_lvl; tot_lvl = str2LL(cfgp.query("LEVEL_TOTAL")); md.dfactor = str2double(cfgp.query("DISPLAY_FACTOR")); md.line_detail_dist_low_limit_factor = str2double(cfgp.query("LINE_DETAIL_DIST_LOW_LIMIT_FACTOR")); md.line_detail_dist_high_limit_factor = str2double(cfgp.query("LINE_DETAIL_DIST_HIGH_LIMIT_FACTOR")); md.line_detail_angle_limit = str2double(cfgp.query("LINE_DETAIL_ANGLE_LIMIT")); for (int lvl = 0; lvl < tot_lvl; lvl++) { char buf[MAXLINE]; double res; sprintf(buf, "LEVEL_RES%d", lvl); res = str2double(cfgp.query(buf)); md.ml.add_level(res); } // load waytype configurations int tot_waytype; tot_waytype = str2LL(cfgp.query("WAYTYPE_TOTAL")); for (int tid = 0; tid < tot_waytype; tid++) { char buf[MAXLINE]; sprintf(buf, "WAYTYPE_TYPE%d", tid); md.wt.insert(cfgp.query(buf)); } // load maptag configurations int tot_maptag; tot_maptag = str2LL(cfgp.query("MAPTAG_TOTAL")); for (int tid = 0; tid < tot_maptag; tid++) { char buf[MAXLINE]; sprintf(buf, "MAPTAG%d", tid); md.mt.insert(cfgp.query(buf)); } md.prepare(); xmlldr.target(&md); xmlldr.load(cfgp.query("MAPDATA")); #ifdef ENABLE_HEAP_PROFILE HeapProfilerDump("xml file loaded"); #endif md.construct(); md.print_stat(); // load graphics configurations mg.initial_window_height = str2double(cfgp.query("INITIAL_WINDOW_HEIGHT")); mg.move_step = str2double(cfgp.query("MOVE_STEP")); mg.zoom_step = str2double(cfgp.query("ZOOM_STEP")); mg.zoom_bysize_factor = str2double(cfgp.query("ZOOM_BYSIZE_FACTOR")); mg.use_rtree_for_drawing = str2LL(cfgp.query("USE_RTREE_FOR_DRAWING")); mg.use_double_buffer = str2LL(cfgp.query("USE_DOUBLE_BUFFER")); mg.use_line_smooth = str2LL(cfgp.query("USE_LINE_SMOOTH")); mg.multisample_level = str2LL(cfgp.query("MULTISAMPLE_LEVEL")); mg.mouse_btn_zoomin = str2LL(cfgp.query("MOUSE_BUTTON_ZOOMIN")); mg.mouse_btn_zoomout = str2LL(cfgp.query("MOUSE_BUTTON_ZOOMOUT")); mg.zoom_low_limit = str2double(cfgp.query("ZOOM_LOW_LIMIT")); mg.zoom_high_limit = str2double(cfgp.query("ZOOM_HIGH_LIMIT")); // load graphics color and thickness if (sscanf(cfgp.query("SELECTED_COLOR"), "%f | %f | %f", // selected colors &mg.scolor[0], &mg.scolor[1], &mg.scolor[2]) != 3) fail("can't parse scolor"); mg.selected_point_rect_size = str2double(cfgp.query("SELECTED_POINT_RECT_SIZE")); mg.selected_point_rect_thick = str2double(cfgp.query("SELECTED_POINT_RECT_THICK")); mg.selected_way_thick = str2double(cfgp.query("SELECTED_WAY_THICK")); for (int num = 0; num < MapOperation::MAX_KBDNUM; num++) { char buf[MAXLINE]; sprintf(buf, "SELECTED_COLOR_NUM%d", num); if (sscanf(cfgp.query(buf), "%f | %f | %f", &mg.ncolor[num][0], &mg.ncolor[num][1], &mg.ncolor[num][2]) != 3) fail("can't parse %s", buf); } if (sscanf(cfgp.query("POLY_COLOR"), "%f | %f | %f", // poly colors &mg.pcolor[0], &mg.pcolor[1], &mg.pcolor[2]) != 3) fail("can't parse pcolor"); mg.pthickness = str2double(cfgp.query("POLY_THICK")); if (sscanf(cfgp.query("NODE_RESULT_COLOR"), "%f | %f | %f", // node result colors &mg.nrcolor[0], &mg.nrcolor[1], &mg.nrcolor[2]) != 3) fail("can't parse nrcolor"); mg.nrsize = str2double(cfgp.query("NODE_RESULT_RECT_SIZE")); mg.nrthick = str2double(cfgp.query("NODE_RESULT_RECT_THICK")); if (sscanf(cfgp.query("WAY_RESULT_COLOR"), "%f | %f | %f", // way result colors &mg.wrcolor[0], &mg.wrcolor[1], &mg.wrcolor[2]) != 3) fail("can't parse wrcolor"); mg.wrthick = str2double(cfgp.query("WAY_RESULT_THICK")); mg.sp_vertex_rect_size = str2double(cfgp.query("SHORTESTPATH_VERTEX_RECT_SIZE")); // shortest path colors mg.sp_vertex_rect_thick = str2double(cfgp.query("SHORTESTPATH_VERTEX_RECT_THICK")); if (sscanf(cfgp.query("SHORTESTPATH_SRC_COLOR"), "%f | %f | %f", &mg.sp_src_color[0], &mg.sp_src_color[1], &mg.sp_src_color[2]) != 3) fail("can't parse sp_src_color"); if (sscanf(cfgp.query("SHORTESTPATH_DEST_COLOR"), "%f | %f | %f", &mg.sp_dest_color[0], &mg.sp_dest_color[1], &mg.sp_dest_color[2]) != 3) fail("can't parse sp_dest_color"); if (sscanf(cfgp.query("SHORTESTPATH_PATH_COLOR"), "%f | %f | %f", &mg.sp_path_color[0], &mg.sp_path_color[1], &mg.sp_path_color[2]) != 3) fail("can't parse sp_path_color"); mg.sp_path_thick = str2double(cfgp.query("SHORTESTPATH_PATH_THICK")); if (sscanf(cfgp.query("TAXI_ROUTE_COLOR"), "%f | %f | %f", // taxi route colors &mg.trcolor[0], &mg.trcolor[1], &mg.trcolor[2]) != 3) fail("can't parse trcolor"); if (sscanf(cfgp.query("TAXI_ROUTE_EMPTY_COLOR"), "%f | %f | %f", &mg.trecolor[0], &mg.trecolor[1], &mg.trecolor[2]) != 3) fail("can't parse trecolor"); mg.trthickness = str2double(cfgp.query("TAXI_ROUTE_THICK")); if (sscanf(cfgp.query("TAXI_ROUTE_NODE_COLOR"), "%f | %f | %f", &mg.trncolor[0], &mg.trncolor[1], &mg.trncolor[2]) != 3) fail("can't parse trncolor"); mg.trnrectsize = str2double(cfgp.query("TAXI_ROUTE_NODE_RECT_SIZE")); mg.trnrectthick = str2double(cfgp.query("TAXI_ROUTE_NODE_RECT_THICK")); mo.clean_up_nospeed_taxi_node = str2LL(cfgp.query("CLEAN_UP_NOSPEED_TAXI_NODE")); mg.target(&md); mg.target_gui(&mgui); mg.target_shortestpath(&msp); mg.target_taxiroute(&mtr); mg.target_operation(&mo); mpt.target(&md); mpt.target_shortestpath(&msp); mtr.set_filename(cfgp.query("TAXIDATA")); timing_start("preprocess taxi data"); mtr.preprocess(); timing_end(); #ifdef ENABLE_HEAP_PROFILE HeapProfilerDump("construct finished"); HeapProfilerStop(); #endif #ifdef ENABLE_CPU_PROFILE ProfilerStart("pj_cpu"); #endif const char *window_title = cfgp.query("TITLE"); int performance_test_mode = str2LL(cfgp.query("ENABLE_PERFORMANCE_TEST_MODE")); cfgp.check_not_queried_keys(); if (!performance_test_mode) { mg.show(window_title, argc, argv); // ui loop, never return assert(0); } else { mpt.run(); } return 0; } #include "../lib/battle.h" #include "../lib/attackMove.h" #include #include Battle::Battle(Pokemon* a, Pokemon* b) : playerA(a), playerB(b) { playerAturn = (bool) (std::rand() % 2); std::cout << " , .::." << std::endl; std::cout << " .;:**' AMC" << std::endl; std::cout << " ` 0" << std::endl; std::cout << " .:XHHHHk. db. .;;. dH MX 0" << std::endl; std::cout << "oMMMMMMMMMMM ~MM dMMP :MMMMMR MMM MR ~MRMN" << std::endl; std::cout << "QMMMMMb \"MMX MMMMMMP !MX' :M~ MMM MMM .oo. XMMM 'MMM" << std::endl; std::cout << " `MMMM. )M> :X!Hk. MMMM XMM.o\" . MMMMMMM X?XMMM MMM>!MMP" << std::endl; std::cout << " 'MMMb.dM! XM M'?M MMMMMX.`MMMMMMMM~ MM MMM XM `\" MX MMXXMM" << std::endl; std::cout << " ~MMMMM~ XMM. .XM XM`\"MMMb.~*?**~ .MMX M t MMbooMM XMMMMMP" << std::endl; std::cout << " ?MMM> YMMMMMM! MM `?MMRb. `\"\"\" !L\"MMMMM XM IMMM" << std::endl; std::cout << " MMMX \"MMMM\" MM ~0: !Mh.\"\"\" dMI IMMP" << std::endl; std::cout << " 'MMM. IMX" << std::endl; std::cout << " ~M!M IMP" << std::endl << std::endl; } void Battle::run() { unsigned int microseconds = 500000; while (playerA->getHP() && playerB->getHP()) { usleep(microseconds); std::cout << playerA->getName() << ": " << playerA->getHP() << "HP" << std::endl; std::cout << playerB->getName() << ": " << playerB->getHP() << "HP" << std::endl; Pokemon *offense, *defense; if (playerAturn) { offense = playerA; defense = playerB; } else { offense = playerB; defense = playerA; } int chooseMove = std::rand() % 4; int dmg = defense->attackedBy(offense->attackPowerOf(chooseMove)); std::cout << offense->getName() << " uses " << offense->getMove(chooseMove); std::cout << ". It did " << dmg << " damage!" << std::endl << std::endl; playerAturn = !playerAturn; } if(playerA->getHP()) { std::cout << playerA->getName() << " wins!" << std::endl; } else { std::cout << playerB->getName() << " wins!" << std::endl; } }0 #include using namespace std; int missing_element(vector v) { int n = v.size(); int l(0),h(n-1); while(l<=h) { int mid = (l+h)/2; if(v[mid] != mid+1 && v[mid-1] == mid) return mid+1; if(v[mid] == mid+1) l = mid+1; else h = mid -1; } return -1; } int main(){ int n; cin >> n; vector v(n-1); for(int i=0;i> v[i]; } }tools/minesweeper/minesweeper.cpp0 #include using namespace std; #define NEW 0 #define EXPERT 1 int bomb = 10; class Cell { public: Cell(): number(0), isRevealed(false), isMarked(false), isBomb(false) {} // Cell(bool isRevealed, bool isMarked): number(0), isRevealed(isRevealed), isMarked(isMarked){} int getNumber() const { return number;} bool getIsRevealed() const { return isRevealed;} bool getIsMarked() const { return isMarked;} bool getIsBomb() const {return isBomb;} void setNumber(const int& number) {this->number = number;} void setisRevealed(const bool& isRevealed) {this->isRevealed = isRevealed;} void setIsMarked(const bool& isMarked) {this->isMarked = isMarked;} private: int number; // number can be -1,0,1,2,3,4,5,6,7,8. -1 means the cell has a bomb. bool isRevealed; // Is the cell selected by the user bool isMarked; // Is the cell marked by the user bool isBomb;//Is the cell bomb bool isValid;//Is the cell on the board. }; //Cell grid[8][8]; //Initialize 8x8 grid // A Function to choose the difficulty level void gameLevel () { int difficulty; cout << "Enter the Difficulty Level\n"; cout << "Press 0 for BEGINNER (8 * 8 Cells and 10 Bombs)\n"; cout << "Press 1 for EXPERT (8 * 8 Cells and 30 Bombs)\n"; cin >> difficulty; if (difficulty == NEW) { bomb = 10; } if (difficulty == EXPERT) { bomb = 30; } return; } //tested: worked for 8x8 grid and bomb <= 64 // integrated into Minesweeper class // void generateBombs(){ // int mineCount = 0; // int rrow, rcol; // do{ // do{ // rrow = rand()%8; // rcol = rand()%8; // cout<<"rrow"<rowNum = rowNum; this->colNum = colNum; this->numPlayers = numPlayers; this->mineCount = mineCount; this->gameGrid = new Cell*[rowNum]; for (int i = 0; i < rowNum; i++) { gameGrid[i] = new Cell[colNum]; } } void setHasWon(const bool& hasWon) {this->hasWon = hasWon;} bool getHasWon() const {return hasWon;} Cell** getGameGrid() const {return gameGrid;} int getMineCount() const {return mineCount;} bool isBomb(int row, int col) { if (gameGrid[row][col].getIsBomb() == true) { return true; } else { return false; } } bool isValidMove(int row, int col) { return (row >= 0) && (row < rowNum) && (col >= 0) && (col < colNum); } // not sure about why the get number is being set to -1 // -1 is bomb ... void generateBombs(){ int mineCount = 0; int rrow, rcol; do{ do{ rrow = rand()%rowNum; rcol = rand()%colNum; //cout<<"rrow"<mineCount); } void draw(){ for (int i = 0; i < this->rowNum; i++){ for(int j = 0; j < this->colNum; j++){ if(gameGrid[i][j].getIsMarked()){ std::cout << "M "; } else if (!gameGrid[i][j].getIsRevealed()){ std::cout << "* "; } else if (gameGrid[i][j].getNumber() == -1){ std::cout << "X "; } else { std::cout << gameGrid[i][j].getNumber() << " "; } } std::cout << "\n"; } std::cout << "Number of bombs left: " << mineCount << "\n"; } void checkLose(int row, int col) { if (gameGrid[row][col].getNumber() == -1) { for (int i = 0; i < this->rowNum; i++) { for (int j = 0; j < this->colNum; j++) { gameGrid[i][j].setisRevealed(true); } } draw(); std::cout << "You lose" << "\n"; this->hasWon = true; } } void checkWin() { int remainCells = 0; for (int i = 0; i < this->rowNum; i++) { for (int j = 0; j < this->colNum; j++) { if (gameGrid[i][j].getNumber() != -1 && !gameGrid[i][j].getIsRevealed()) { remainCells++; } } } if (remainCells == 0) { for (int i = 0; i < this->rowNum; i++) { for (int j = 0; j < this->colNum; j++) { gameGrid[i][j].setisRevealed(true); } } draw(); std::cout << "You win" << "\n"; this->hasWon = true; //break; } } //check adjacent bomb nearby,and return the number of bumb. /* Count all the mines in the 8 adjacent cells N.W N N.E \ | / \ | / W----Cell----E / | \ / | \ S.W S S.E Cell-->Current Cell (row, col) N --> North (row-1, col) S --> South (row+1, col) E --> East (row, col+1) W --> West (row, col-1) N.E--> North-East (row-1, col+1) N.W--> North-West (row-1, col-1) S.E--> South-East (row+1, col+1) S.W--> South-West (row+1, col-1) */ int check_adjacent(int row, int col){ int count = 0; // N --> North (row-1, col) if (isValidMove (row-1, col) == true) { if (isBomb (row-1, col) == true) count++; } //S --> South (row+1, col) if (isValidMove(row+1, col) == true) { if (isBomb (row+1, col) == true) count++; } // E --> East (row, col+1) if (isValidMove(row, col+1) == true) { if (isBomb (row, col+1) == true) count++; } // W --> West (row, col-1) if (isValidMove(row, col-1) == true) { if (isBomb (row, col-1) == true) count++; } // N.E--> North-East (row-1, col+1) if (isValidMove(row-1, col+1l) == true) { if (isBomb (row-1, col+1) == true) count++; } // N.W--> North-West (row-1, col-1) if (isValidMove(row-1, col-1) == true) { if (isBomb (row-1, col-1) == true) count++; } //S.E--> South-East (row+1, col+1) if (isValidMove(row+1, col+1) == true) { if (isBomb (row+1, col+1) == true) count++; } //S.W--> South-West (row+1, col-1) if (isValidMove(row+1, col-1) == true) { if (isBomb (row+1, col-1) == true) count++; } return count; } private: bool hasWon = false; Cell** gameGrid; }; // int placeFlag(int row, int col,int realboard[][8]){ // bool mark[64]; // memset (mark, false, sizeof (mark)); // // Continue until all random mines have been created. // for (int i = 0; i < bomb; ) // { // int random = rand() % (64); // int temp1 = random / 8; // int temp2 = random % 8; // // Add the mine if no mine is placed at this // // position on the board // if (mark[random] == false) // { // // Row Index of the Mine // row = temp1; // // Column Index of the Mine // col = temp2; // // Place the mine // realBoard[row][col] = '*'; // mark[random] = true; // i++; // } // } // return; // } // A Function to print the current gameplay board // duplicate of draw()? void printB(char bombset[][8]) { cout << " "; for (int i = 0; i < 8; i++) cout << i; cout << "\n\n"; for (int i = 0; i < 8; i++) { cout << i; for (int j = 0; j < 8; j++) cout << bombset[i][j]; cout << "\n\n"; } return; } // A Function to cheat by revealing where the mines are // under constructioni void showBomb(char bombset[][8]) { cout << "The bombs locations are-\n"; printB(bombset); return; } int main() { //generateBombs(); //draw(); //// test code for Minesweeper class//// int rowNum = 20; int colNum = 20; int mineNum = 10; int numPlayers = 2; // game doesn't deal with multiple players yet Minesweeper* game = new Minesweeper(rowNum, colNum, mineNum, numPlayers); game->generateBombs(); // bool testIsBomb = game->isBomb(0,0); // bool testIsValid1 = game->isValidMove(10,10); // cout << "RowNum: " << game->rowNum << endl; // test rowNum is correct // cout << "colNum: " << game->colNum << endl; // cout << "numPlayers: " << game->numPlayers << endl; // cout << "hasWon: " << game->getHasWon() << endl; // cout << "gameGrid[0][0]: " << game->getGameGrid()[0][0].getNumber() << endl; // cout << "isBomb result: " << testIsBomb << endl; // cout << "isValid result: " << testIsValid1 << endl; // cout << "isValid result: " << testIsValid2 << endl; while(game->getHasWon() == false) { game->draw(); int row, column; std::cout << "Please enter the cell you want to access ex) 1 1: "; std::cin >> row >> column; char markOrReveal; std::cout << "Enter m for mark, r to reveal it: "; std::cin >> markOrReveal; if (markOrReveal == 'm') { game->getGameGrid()[row][column].setIsMarked(true); game->mineCount--; } else if (markOrReveal == 'r') { game->getGameGrid()[row][column].setisRevealed(true); game->checkLose(row, column); //set it to a number of bomb nearby. std::cout<<"It has "<check_adjacent<<"bomb near it "; } else { game->checkWin(); } } return 0; } #include "WaterSurface.h" #include "ObstDefinition.h" #include "Shizuku.Core/Ogl/Shader.h" #include "Shizuku.Core/Ogl/Ogl.h" #include "CudaLbm.h" #include "Domain.h" #include #include #include #include #include #include #include using namespace Shizuku::Core; using namespace Shizuku::Core::Types; using namespace Shizuku::Flow; WaterSurface::WaterSurface() { m_surfaceRayTrace = std::make_shared(); m_surfaceContour = std::make_shared(); m_lightingProgram = std::make_shared(); m_obstProgram = std::make_shared(); m_outputProgram = std::make_shared(); Ogl = std::make_shared < Shizuku::Core::Ogl >(); m_cameraDatum = std::make_shared(Ogl); } void WaterSurface::CreateCudaLbm() { m_cudaLbm = std::make_shared(); } std::shared_ptr WaterSurface::GetCudaLbm() { return m_cudaLbm; } cudaGraphicsResource* WaterSurface::GetCudaPosColorResource() { return m_cudaPosColorResource; } cudaGraphicsResource* WaterSurface::GetCudaNormalResource() { return m_cudaNormalResource; } cudaGraphicsResource* WaterSurface::GetCudaEnvTextureResource() { return m_cudaEnvTextureResource; } std::shared_ptr WaterSurface::GetVbo() { return m_vbo; } void WaterSurface::CreateVboForCudaInterop() { unsigned int solutionMemorySize = MAX_XDIM*MAX_YDIM * 4 * sizeof(float); unsigned int floorSize = MAX_XDIM*MAX_YDIM * 4 * sizeof(float); const unsigned int size = solutionMemorySize + floorSize; std::shared_ptr posColor = Ogl->CreateBuffer(GL_ARRAY_BUFFER, 0, size, "surface", GL_DYNAMIC_DRAW); cudaGraphicsGLRegisterBuffer(&m_cudaPosColorResource, posColor->GetId(), cudaGraphicsMapFlagsWriteDiscard); std::shared_ptr normals = Ogl->CreateBuffer(GL_ARRAY_BUFFER, 0, size, "surface_normals", GL_DYNAMIC_DRAW); cudaGraphicsGLRegisterBuffer(&m_cudaNormalResource, normals->GetId(), cudaGraphicsMapFlagsWriteDiscard); CreateElementArrayBuffer(); m_vbo = posColor; } void WaterSurface::CreateElementArrayBuffer() { const int numberOfElements = (MAX_XDIM - 1)*(MAX_YDIM - 1); const int numberOfNodes = MAX_XDIM*MAX_YDIM; GLuint* elementIndices = new GLuint[numberOfElements * 3 * 2]; for (int j = 0; j < MAX_YDIM-1; j++){ for (int i = 0; i < MAX_XDIM-1; i++){ //going clockwise, since y orientation will be flipped when rendered elementIndices[j*(MAX_XDIM-1)*6+i*6+0] = (i)+(j)*MAX_XDIM; elementIndices[j*(MAX_XDIM-1)*6+i*6+1] = (i+1)+(j)*MAX_XDIM; elementIndices[j*(MAX_XDIM-1)*6+i*6+2] = (i+1)+(j+1)*MAX_XDIM; elementIndices[j*(MAX_XDIM-1)*6+i*6+3] = (i)+(j)*MAX_XDIM; elementIndices[j*(MAX_XDIM-1)*6+i*6+4] = (i+1)+(j+1)*MAX_XDIM; elementIndices[j*(MAX_XDIM-1)*6+i*6+5] = (i)+(j+1)*MAX_XDIM; } } Ogl->CreateBuffer(GL_ELEMENT_ARRAY_BUFFER, elementIndices, numberOfElements * 3 * 2, "surface_indices", GL_DYNAMIC_DRAW); free(elementIndices); } template void WaterSurface::CreateShaderStorageBuffer(T defaultValue, const unsigned int numberOfElements, const std::string name) { T* data = new T[numberOfElements]; for (int i = 0; i < numberOfElements; i++) { data[i] = defaultValue; } GLuint temp = Ogl->CreateBuffer(GL_SHADER_STORAGE_BUFFER, data, numberOfElements, name, GL_STATIC_DRAW)->GetId(); m_ssbos.push_back(Ssbo{ temp, name }); } GLuint WaterSurface::GetShaderStorageBuffer(const std::string name) { for (std::vector::iterator it = m_ssbos.begin(); it != m_ssbos.end(); ++it) { if (it->m_name == name) { return it->m_id; } } return NULL; } void WaterSurface::CompileShaders() { m_surfaceRayTrace->Initialize("SurfaceRayTrace"); m_surfaceRayTrace->CreateShader("Assets/SurfaceShader.vert.glsl", GL_VERTEX_SHADER); m_surfaceRayTrace->CreateShader("Assets/SurfaceShader.frag.glsl", GL_FRAGMENT_SHADER); m_surfaceContour->Initialize("SurfaceContour"); m_surfaceContour->CreateShader("Assets/SurfaceContour.vert.glsl", GL_VERTEX_SHADER); m_surfaceContour->CreateShader("Assets/SurfaceContour.frag.glsl", GL_FRAGMENT_SHADER); m_lightingProgram->Initialize("Lighting"); m_lightingProgram->CreateShader("Assets/SurfaceShader.comp.glsl", GL_COMPUTE_SHADER); m_obstProgram->Initialize("Obstructions"); m_obstProgram->CreateShader("Assets/Obstructions.comp.glsl", GL_COMPUTE_SHADER); m_outputProgram->Initialize("Output"); m_outputProgram->CreateShader("Assets/Output.vert.glsl", GL_VERTEX_SHADER); m_outputProgram->CreateShader("Assets/Output.frag.glsl", GL_FRAGMENT_SHADER); } void WaterSurface::AllocateStorageBuffers() { CreateShaderStorageBuffer(GLfloat(0), MAX_XDIM*MAX_YDIM*9, "LbmA"); CreateShaderStorageBuffer(GLfloat(0), MAX_XDIM*MAX_YDIM*9, "LbmB"); CreateShaderStorageBuffer(GLint(0), MAX_XDIM*MAX_YDIM, "Floor"); CreateShaderStorageBuffer(ObstDefinition{}, MAXOBSTS, "Obstructions"); CreateShaderStorageBuffer(float4{0,0,0,1e6}, 1, "RayIntersection"); } void WaterSurface::SetUpEnvironmentTexture() { int width, height; unsigned char* image = SOIL_load_image("Assets/Environment.png", &width, &height, 0, SOIL_LOAD_RGB); assert(image != NULL); float* tex = new float[4 * width*height]; for (int i = 0; i < width*height; ++i) { tex[4 * i] = image[3 * i]; tex[4 * i + 1] = image[3 * i + 1]; tex[4 * i + 2] = image[3 * i + 2]; tex[4 * i + 3] = unsigned char(255);// color[3]; } glGenTextures(1, &m_envTexture); glBindTexture(GL_TEXTURE_2D, m_envTexture); //glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8UI, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, tex); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F, width, height, 0, GL_RGBA, GL_FLOAT, tex); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); cudaGraphicsGLRegisterImage(&m_cudaEnvTextureResource, m_envTexture, GL_TEXTURE_2D, cudaGraphicsMapFlagsReadOnly); SOIL_free_image_data(image); glBindTexture(GL_TEXTURE_2D, 0); } void WaterSurface::SetUpOutputTexture(const Rect& p_viewSize) { //! Output Fbo glGenTextures(1, &m_outputTexture); glBindTexture(GL_TEXTURE_2D, m_outputTexture); const GLuint outWidth = p_viewSize.Width; const GLuint outHeight = p_viewSize.Height; glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F, outWidth, outHeight, 0, GL_RGBA, GL_FLOAT, 0); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glBindTexture(GL_TEXTURE_2D, 0); glGenRenderbuffers(1, &m_outputRbo); glBindRenderbuffer(GL_RENDERBUFFER, m_outputRbo); glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, outWidth, outHeight); glBindRenderbuffer(GL_RENDERBUFFER, 0); // set up FBO and texture to render to glGenFramebuffers(1, &m_outputFbo); glBindFramebuffer(GL_FRAMEBUFFER, m_outputFbo); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, m_outputTexture, 0); glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, m_outputRbo); if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) throw "Framebuffer creation failed"; glBindFramebuffer(GL_FRAMEBUFFER, 0); } void WaterSurface::InitializeObstSsbo() { std::shared_ptr cudaLbm = GetCudaLbm(); ObstDefinition* obst_h = cudaLbm->GetHostObst(); std::shared_ptr obstSsbo = Ogl->GetBuffer("Obstructions"); Ogl->BindSSBO(0, *obstSsbo, GL_SHADER_STORAGE_BUFFER); glBufferData(GL_SHADER_STORAGE_BUFFER, MAXOBSTS*sizeof(ObstDefinition), obst_h, GL_STATIC_DRAW); Ogl->UnbindBO(GL_SHADER_STORAGE_BUFFER); } int WaterSurface::RayCastMouseClick(glm::vec3 &rayCastIntersection, const glm::vec3 rayOrigin, const glm::vec3 rayDir) { Domain domain = *m_cudaLbm->GetDomain(); int xDim = domain.GetXDim(); int yDim = domain.GetYDim(); glm::vec4 intersectionCoord{ 0, 0, 0, 0 }; std::shared_ptr rayIntSsbo = Ogl->GetBuffer("RayIntersection"); Ogl->BindSSBO(4, *rayIntSsbo); std::shared_ptr const shader = m_lightingProgram; shader->Use(); shader->SetUniform("maxXDim", MAX_XDIM); shader->SetUniform("maxyDim", MAX_YDIM); shader->SetUniform("maxObsts", MAXOBSTS); shader->SetUniform("xDim", xDim); shader->SetUniform("yDim", yDim); shader->SetUniform("xDimVisible", domain.GetXDimVisible()); shader->SetUniform("yDimVisible", domain.GetYDimVisible()); shader->SetUniform("rayOrigin", rayOrigin); shader->SetUniform("rayDir", rayDir); shader->RunSubroutine("ResetRayCastData", glm::ivec3{ 1, 1, 1 }); shader->RunSubroutine("RayCast", glm::ivec3{ xDim, yDim, 1 }); glBindBuffer(GL_SHADER_STORAGE_BUFFER, rayIntSsbo->GetId()); GLfloat* intersect = (GLfloat*)glMapBufferRange(GL_SHADER_STORAGE_BUFFER, 0, sizeof(glm::vec4), GL_MAP_READ_BIT); std::memcpy(&intersectionCoord, intersect, sizeof(glm::vec4)); glUnmapBuffer(GL_SHADER_STORAGE_BUFFER); int returnVal; if (intersectionCoord.w > 1e5) //ray did not intersect with any objects { returnVal = 1; } else { shader->RunSubroutine("ResetRayCastData", glm::ivec3{ 1, 1, 1 }); rayCastIntersection.x = intersectionCoord.x; rayCastIntersection.y = intersectionCoord.y; rayCastIntersection.z = intersectionCoord.z; returnVal = 0; } shader->Unset(); glBindBuffer(GL_SHADER_STORAGE_BUFFER, 0); return returnVal; } void WaterSurface::SetUpSurfaceVao() { std::shared_ptr surface = Ogl->CreateVao("surface"); surface->Bind(); Ogl->BindBO(GL_ARRAY_BUFFER, *Ogl->GetBuffer("surface")); Ogl->BindBO(GL_ELEMENT_ARRAY_BUFFER, *Ogl->GetBuffer("surface_indices")); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 16, 0); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 1, GL_FLOAT, GL_FALSE, 16, (GLvoid*)(3 * sizeof(GLfloat))); Ogl->BindBO(GL_ARRAY_BUFFER, *Ogl->GetBuffer("surface_normals")); glEnableVertexAttribArray(2); glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, 16, 0); surface->Unbind(); } void WaterSurface::SetUpOutputVao() { std::shared_ptr output = Ogl->CreateVao("output"); output->Bind(); const GLfloat quadVertices[] = { -1.0f, -1.0f, 0.0f, 1.0f, -1.0f, 0.0f, -1.0f, 1.0f, 0.0f, -1.0f, 1.0f, 0.0f, 1.0f, -1.0f, 0.0f, 1.0f, 1.0f, 0.0f, }; Ogl->CreateBuffer(GL_ARRAY_BUFFER, quadVertices, 18, "output", GL_STATIC_DRAW); Ogl->BindBO(GL_ARRAY_BUFFER, *Ogl->GetBuffer("output")); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0); output->Unbind(); } void WaterSurface::SetUpWallVao() { std::shared_ptr wall = Ogl->CreateVao("wall"); wall->Bind(); const GLfloat quadVertices[] = { -1.0f, -1.0f, -1.0f, 1.0f, -1.0f, -1.0f, -1.0f, 1.0f, -1.0f, -1.0f, 1.0f, -1.0f, 1.0f, -1.0f, -1.0f, 1.0f, 1.0f, -1.0f, }; Ogl->CreateBuffer(GL_ARRAY_BUFFER, quadVertices, 18, "wall", GL_STATIC_DRAW); Ogl->BindBO(GL_ARRAY_BUFFER, *Ogl->GetBuffer("wall")); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0); wall->Unbind(); } void WaterSurface::RunComputeShader(const glm::vec3 p_cameraPosition, const ContourVariable p_contVar, const MinMax& p_minMax) { std::shared_ptr ssbo_lbmA = Ogl->GetBuffer("LbmA"); Ogl->BindSSBO(0, *ssbo_lbmA); std::shared_ptr ssbo_lbmB = Ogl->GetBuffer("LbmB"); Ogl->BindSSBO(1, *ssbo_lbmB); Ogl->BindBO(GL_SHADER_STORAGE_BUFFER, *Ogl->GetBuffer("surface")); std::shared_ptr vbo = Ogl->GetBuffer("surface"); Ogl->BindSSBO(2, *vbo); std::shared_ptr ssbo_floor = Ogl->GetBuffer("Floor"); Ogl->BindSSBO(3, *ssbo_floor); std::shared_ptr ssbo_obsts = Ogl->GetBuffer("Obstructions"); Ogl->BindSSBO(5, *ssbo_obsts); std::shared_ptr const shader = m_lightingProgram; shader->Use(); Domain domain = *m_cudaLbm->GetDomain(); const int xDim = domain.GetXDim(); const int yDim = domain.GetYDim(); shader->SetUniform("maxXDim", MAX_XDIM); shader->SetUniform("maxyDim", MAX_YDIM); shader->SetUniform("maxObsts", MAXOBSTS); shader->SetUniform("xDim", xDim); shader->SetUniform("yDim", yDim); shader->SetUniform("xDimVisible", domain.GetXDimVisible()); shader->SetUniform("yDimVisible", domain.GetYDimVisible()); shader->SetUniform("cameraPosition", p_cameraPosition); shader->SetUniform("uMax", m_inletVelocity); shader->SetUniform("omega", m_omega); shader->SetUniform("contourVar", p_contVar); shader->SetUniform("contourMin", p_minMax.Min); shader->SetUniform("contourMax", p_minMax.Max); for (int i = 0; i < 5; i++) { shader->RunSubroutine("MarchLbm", glm::ivec3{ xDim, yDim, 1 }); Ogl->BindSSBO(1, *ssbo_lbmA); Ogl->BindSSBO(0, *ssbo_lbmB); shader->RunSubroutine("MarchLbm", glm::ivec3{ xDim, yDim, 1 }); Ogl->BindSSBO(0, *ssbo_lbmA); Ogl->BindSSBO(1, *ssbo_lbmB); } shader->RunSubroutine("UpdateFluidVbo", glm::ivec3{ xDim, yDim, 1 }); shader->RunSubroutine("DeformFloorMeshUsingCausticRay", glm::ivec3{ xDim, yDim, 1 }); shader->RunSubroutine("ComputeFloorLightIntensitiesFromMeshDeformation", glm::ivec3{ xDim, yDim, 1 }); shader->RunSubroutine("ApplyCausticLightingToFloor", glm::ivec3{ xDim, yDim, 1 }); shader->RunSubroutine("PhongLighting", glm::ivec3{ xDim, yDim, 2 }); shader->RunSubroutine("UpdateObstructionTransientStates", glm::ivec3{ xDim, yDim, 1 }); shader->RunSubroutine("CleanUpVbo", glm::ivec3{ MAX_XDIM, MAX_YDIM, 2 }); shader->Unset(); glBindBuffer(GL_SHADER_STORAGE_BUFFER, 0); } void WaterSurface::UpdateObstructionsUsingComputeShader(const int obstId, ObstDefinition &newObst, const float scaleFactor) { std::shared_ptr ssbo_obsts = Ogl->GetBuffer("Obstructions"); Ogl->BindSSBO(0, *ssbo_obsts); std::shared_ptr const shader = m_obstProgram; shader->Use(); shader->SetUniform("targetObst.shape", newObst.shape); shader->SetUniform("targetObst.x", newObst.x); shader->SetUniform("targetObst.y", newObst.y); shader->SetUniform("targetObst.r1", newObst.r1); shader->SetUniform("targetObst.u", newObst.u); shader->SetUniform("targetObst.v", newObst.v); shader->SetUniform("targetObst.state", newObst.state); shader->SetUniform("targetObstId", obstId); shader->RunSubroutine("UpdateObstruction", glm::ivec3{ 1, 1, 1 }); shader->Unset(); glBindBuffer(GL_SHADER_STORAGE_BUFFER, 0); } void WaterSurface::InitializeComputeShaderData() { std::shared_ptr ssbo_lbmA = Ogl->GetBuffer("LbmA"); Ogl->BindSSBO(0, *ssbo_lbmA); std::shared_ptr ssbo_lbmB = Ogl->GetBuffer("LbmB"); Ogl->BindSSBO(1, *ssbo_lbmB); std::shared_ptr ssbo_obsts = Ogl->GetBuffer("Obstructions"); Ogl->BindSSBO(5, *ssbo_obsts); std::shared_ptr const shader = m_lightingProgram; shader->Use(); Domain domain = *m_cudaLbm->GetDomain(); shader->SetUniform("maxXDim", MAX_XDIM); shader->SetUniform("maxYDim", MAX_YDIM); shader->SetUniform("maxObsts", MAXOBSTS);// shader->SetUniform("xDim", domain.GetXDim()); shader->SetUniform("yDim", domain.GetYDim()); shader->SetUniform("xDimVisible", domain.GetXDim()); shader->SetUniform("yDimVisible", domain.GetYDim()); shader->SetUniform("uMax", m_inletVelocity); shader->RunSubroutine("InitializeDomain", glm::ivec3{ MAX_XDIM, MAX_YDIM, 1 }); shader->Unset(); glBindBuffer(GL_SHADER_STORAGE_BUFFER, 0); } void WaterSurface::BindFloorLightTexture() { glBindTexture(GL_TEXTURE_2D, m_floorLightTexture); } void WaterSurface::BindEnvTexture() { glBindTexture(GL_TEXTURE_2D, m_envTexture); } void WaterSurface::UnbindFloorTexture() { glBindTexture(GL_TEXTURE_2D, 0); } void WaterSurface::SetOmega(const float omega) { m_omega = omega; } float WaterSurface::GetOmega() { return m_omega; } void WaterSurface::SetInletVelocity(const float u) { m_inletVelocity = u; } float WaterSurface::GetInletVelocity() { return m_inletVelocity; } void WaterSurface::UpdateLbmInputs(const float u, const float omega) { SetInletVelocity(u); SetOmega(omega); } void WaterSurface::Render(const ContourVariable p_contour , Domain &p_domain, const RenderParams& p_params, const bool p_drawFloorWireframe, const Rect& p_viewSize, const float p_obstHeight, const int obstCount, GLuint p_causticsTex) { glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LESS); //! Disabling for now. Need to recreate correct size textures on window resize const bool offscreenRender = false; if (offscreenRender) { glBindFramebuffer(GL_FRAMEBUFFER, m_outputFbo); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); } if (p_contour == ContourVariable::WATER_RENDERING) RenderSurface(p_domain, p_params, p_viewSize, p_obstHeight, obstCount, p_causticsTex); else RenderSurfaceContour(p_contour, p_domain, p_params); if (offscreenRender) { glBindFramebuffer(GL_FRAMEBUFFER, 0); //Draw quad std::shared_ptr outputVao = Ogl->GetVao("output"); outputVao->Bind(); m_outputProgram->Use(); glBindTexture(GL_TEXTURE_2D, m_outputTexture); glDrawArrays(GL_TRIANGLES, 0 , 6); glBindTexture(GL_TEXTURE_2D, 0); m_outputProgram->Unset(); outputVao->Unbind(); } } void WaterSurface::RenderSurface(Domain &domain, const RenderParams& p_params, const Rect& p_viewSize, const float p_obstHeight, const int p_obstCount, GLuint p_causticsTex) { glDepthMask(GL_FALSE); glActiveTexture(GL_TEXTURE0); m_surfaceRayTrace->Use(); m_surfaceRayTrace->SetUniform("modelMatrix", p_params.ModelView); m_surfaceRayTrace->SetUniform("projectionMatrix", p_params.Projection); m_surfaceRayTrace->SetUniform("topViewMode", p_params.TopViewMode); m_surfaceRayTrace->SetUniform("cameraPos", p_params.Camera); m_surfaceRayTrace->SetUniform("obstHeight", p_obstHeight); m_surfaceRayTrace->SetUniform("obstCount", p_obstCount); m_surfaceRayTrace->SetUniform("obstColor", p_params.Schema.Obst.Value()); m_surfaceRayTrace->SetUniform("obstColorHighlight", p_params.Schema.ObstHighlight.Value()); m_surfaceRayTrace->SetUniform("viewSize", glm::vec2((float)p_viewSize.Width, (float)p_viewSize.Height)); std::shared_ptr surface = Ogl->GetVao("surface"); surface->Bind(); glBindTexture(GL_TEXTURE_2D, p_causticsTex); std::shared_ptr obstSsbo = Ogl->GetBuffer("managed_obsts"); Ogl->BindSSBO(0, *obstSsbo, GL_SHADER_STORAGE_BUFFER); const int yDimVisible = domain.GetYDimVisible(); glDrawElements(GL_TRIANGLES, (MAX_XDIM - 1)*(yDimVisible - 1)*3*2 , GL_UNSIGNED_INT, (GLvoid*)0); surface->Unbind(); glBindTexture(GL_TEXTURE_2D, 0); Ogl->UnbindBO(GL_SHADER_STORAGE_BUFFER); m_surfaceRayTrace->Unset(); glDepthMask(GL_TRUE); #ifdef DRAW_CAMERA RenderCameraPos(p_shadingMode, domain, modelMatrix, projectionMatrix, p_cameraPos, p_viewSize, obstHeight); #endif } void WaterSurface::RenderSurfaceContour(const ContourVariable p_contour, Domain &domain, const RenderParams& p_params) { m_surfaceContour->Use(); m_surfaceContour->SetUniform("modelMatrix", p_params.ModelView); m_surfaceContour->SetUniform("projectionMatrix", p_params.Projection); m_surfaceContour->SetUniform("cameraPos", p_params.Camera); std::shared_ptr surface = Ogl->GetVao("surface"); surface->Bind(); const int yDimVisible = domain.GetYDimVisible(); glDrawElements(GL_TRIANGLES, (MAX_XDIM - 1)*(yDimVisible - 1)*3*2 , GL_UNSIGNED_INT, (GLvoid*)0); surface->Unbind(); m_surfaceContour->Unset(); #ifdef DRAW_CAMERA RenderCameraPos(p_shadingMode, domain, modelMatrix, projectionMatrix, p_cameraPos, p_viewSize, obstHeight); #endif } void WaterSurface::RenderCameraPos(const RenderParams& p_params) { if (m_cameraDatum->IsInitialized()) { m_cameraDatum->Render(p_params); } } void WaterSurface::UpdateCameraDatum(const PillarDefinition& p_def) { if (!m_cameraDatum->IsInitialized()) { m_cameraDatum->Initialize(); } m_cameraDatum->SetDefinition(p_def); }10-100 // // Created by npchitman on 6/29/21. // #include "Math.h" #define GLM_ENABLE_EXPERIMENTAL #include #include "pch.h" namespace Aph::Math { std::tuple DecomposeTransform(const glm::mat4& transform) { // From glm::decompose in matrix_decompose.inl glm::vec3 translation, rotation, scale; glm::mat4 LocalMatrix(transform); // Normalize the matrix. if (glm::epsilonEqual(LocalMatrix[3][3], static_cast(0), glm::epsilon())) return {}; // First, isolate perspective. This is the messiest. if (glm::epsilonNotEqual(LocalMatrix[0][3], static_cast(0), glm::epsilon()) || glm::epsilonNotEqual(LocalMatrix[1][3], static_cast(0), glm::epsilon()) || glm::epsilonNotEqual(LocalMatrix[2][3], static_cast(0), glm::epsilon())) { // Clear the perspective partition LocalMatrix[0][3] = LocalMatrix[1][3] = LocalMatrix[2][3] = static_cast(0); LocalMatrix[3][3] = static_cast(1); } // Next take care of translation (easy). translation = glm::vec3(LocalMatrix[3]); LocalMatrix[3] = glm::vec4(0, 0, 0, LocalMatrix[3].w); glm::vec3 Row[3], Pdum3; // Now get scale and shear. for (glm::length_t i = 0; i < 3; ++i) for (glm::length_t j = 0; j < 3; ++j) Row[i][j] = LocalMatrix[i][j]; // Compute X scale factor and normalize first row. scale.x = length(Row[0]); Row[0] = glm::detail::scale(Row[0], static_cast(1)); scale.y = length(Row[1]); Row[1] = glm::detail::scale(Row[1], static_cast(1)); scale.z = length(Row[2]); Row[2] = glm::detail::scale(Row[2], static_cast(1)); // At this point, the matrix (in rows[]) is orthonormal. // Check for a coordinate system flip. If the determinant // is -1, then negate the matrix and the scaling factors. #if 0 Pdum3 = cross(Row[1], Row[2]); // v3Cross(row[1], row[2], Pdum3); if (dot(Row[0], Pdum3) < 0) { for (length_t i = 0; i < 3; i++) { scale[i] *= static_cast(-1); Row[i] *= static_cast(-1); } } #endif rotation.y = std::asin(-Row[0][2]); if (cos(rotation.y) != 0) { rotation.x = std::atan2(Row[1][2], Row[2][2]); rotation.z = std::atan2(Row[0][1], Row[0][0]); } else { rotation.x = std::atan2(-Row[2][0], Row[1][1]); rotation.z = 0; } return std::make_tuple(translation, rotation, scale); } }// namespace Aph::Math /* * Copyright (C) 2005-2019 Centre National d'Etudes Spatiales (CNES) * * This file is part of Orfeo Toolbox * * https://www.orfeo-toolbox.org/ * * 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 otbAngularProjectionImageFilter_hxx #define otbAngularProjectionImageFilter_hxx #include "otbAngularProjectionImageFilter.h" #include #include #include namespace otb { template < class TInputImage, class TOutputImage, class TAngleArray, class TPrecision > AngularProjectionImageFilter< TInputImage, TOutputImage, TAngleArray, TPrecision > ::AngularProjectionImageFilter () { //this->SetNumberOfRequiredInputs(NumberOfInputImages); this->SetNumberOfRequiredOutputs(1); } template < class TInputImage, class TOutputImage, class TAngleArray, class TPrecision > void AngularProjectionImageFilter< TInputImage, TOutputImage, TAngleArray, TPrecision > ::SetInput ( unsigned int i, const InputImageType * img ) { this->itk::ProcessObject::SetNthInput(i, const_cast< InputImageType * >( img ) ); } template < class TInputImage, class TOutputImage, class TAngleArray, class TPrecision > const TInputImage * AngularProjectionImageFilter< TInputImage, TOutputImage, TAngleArray, TPrecision > ::GetInput ( unsigned int i ) const { if ( i >= this->GetNumberOfInputs() ) { return nullptr; } return static_cast (this->itk::ProcessObject::GetInput(i) ); } template < class TInputImage, class TOutputImage, class TAngleArray, class TPrecision > void AngularProjectionImageFilter< TInputImage, TOutputImage, TAngleArray, TPrecision > ::ThreadedGenerateData ( const OutputImageRegionType & outputRegionForThread, itk::ThreadIdType threadId ) { itk::ProgressReporter reporter(this, threadId, outputRegionForThread.GetNumberOfPixels() ); InputImageRegionType inputRegionForThread; this->CallCopyOutputRegionToInputRegion( inputRegionForThread, outputRegionForThread ); bool iteratorsAtEnd = false; ImageRegionConstIteratorVectorType it ( this->GetNumberOfInputs() ); for ( unsigned int i = 0; i < this->GetNumberOfInputs(); ++i ) { it[i] = ImageRegionConstIteratorType( this->GetInput(i), inputRegionForThread ); it[i].GoToBegin(); if ( it[i].IsAtEnd() ) iteratorsAtEnd = true; } itk::ImageRegionIterator outIter ( this->GetOutput(), outputRegionForThread ); outIter.GoToBegin(); while ( !iteratorsAtEnd && !outIter.IsAtEnd() ) { outIter.Set( InternalGenerateData( it ) ); ++outIter; for ( unsigned int i = 0; i < this->GetNumberOfInputs(); ++i ) { ++(it[i]); if ( it[i].IsAtEnd() ) iteratorsAtEnd = true; } reporter.CompletedPixel(); } } template < class TInputImage, class TOutputImage, class TAngleArray, class TPrecision > typename AngularProjectionImageFilter< TInputImage, TOutputImage, TAngleArray, TPrecision > ::OutputImagePixelType AngularProjectionImageFilter< TInputImage, TOutputImage, TAngleArray, TPrecision > ::InternalGenerateData ( const ImageRegionConstIteratorVectorType & it ) const { PrecisionType output = 0; if ( this->GetNumberOfInputs() == 2 ) { PrecisionType alpha = static_cast( m_AngleArray[0] ); output = static_cast( it[0].Get() ) * std::cos( alpha ) - static_cast( it[1].Get() ) * std::sin( alpha ); } else if ( this->GetNumberOfInputs() == 3 ) { PrecisionType alpha = static_cast( m_AngleArray[0] ); PrecisionType beta = static_cast( m_AngleArray[1] ); output = static_cast( it[0].Get() ) * std::cos( alpha ) - static_cast( it[1].Get() ) * std::sin( alpha ) * std::cos ( beta ) + static_cast( it[2].Get() ) * std::sin( alpha ) * std::sin ( beta ); } else { unsigned int i = this->GetNumberOfInputs()-1; output = static_cast( it[i--].Get() ); do { PrecisionType alpha = static_cast( m_AngleArray[i] ); output = static_cast( it[i].Get() ) * std::cos( alpha ) - output * std::sin( alpha ); } while ( i-- == 0 ); } return static_cast( output ); } } // end of namespace otb #endif #pragma once #include class social : public module { private: bool handle_channel_message( const std::string& user, const std::string& message ) override; bool handle_private_message( const std::string& user, const std::string& message ) override; }; Tests/DataImportTest.cpp0 /////////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2007, 2010 for BlueQuartz Software // All rights reserved. // BSD License: http://www.opensource.org/licenses/bsd-license.html // // This code was written under United States Air Force Contract number // FA8650-04-C-5229 // /////////////////////////////////////////////////////////////////////////////// #include "MXA/MXA.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "Tests/MXAUnitTestDataFileLocations.h" #include "H5ImportTest.h" #include "TiffMaker.h" #include "UnitTestSupport.hpp" static std::vector createdPaths; // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- void RemoveTestFiles() { // std::cout << logTime() << "Removing Test files" << std::endl; #if REMOVE_TEST_FILES bool success; MXADir::remove(MXAUnitTest::DataImportTest::SimpleImport); MXADir::remove(MXAUnitTest::DataImportTest::H5TiffOutputFile); for (std::vector::iterator iter = createdPaths.begin(); iter != createdPaths.end(); ++iter ) { success = MXADir::remove(*iter); MXA_REQUIRE_EQUAL(success, true); } success = MXADir::rmdir(MXAUnitTest::MXATempDir + MXAUnitTest::DataImportTest::TestDir + MXADir::Separator + "test_data", false); MXA_REQUIRE_EQUAL(success, true); success = MXADir::rmdir(MXAUnitTest::MXATempDir + MXAUnitTest::DataImportTest::TestDir, false); MXA_REQUIRE_EQUAL(success, true); #endif } // ----------------------------------------------------------------------------- // Creates a DataImport class and some DataSources that then delegate out to // an instance of an IDataImportDelegate to do the actual import of data. // ----------------------------------------------------------------------------- void ImportSimpleData(MXADataModel::Pointer model, std::string outputFilePath) { IDataFile::Pointer dataFile = H5MXADataFile::CreateFileWithModel(outputFilePath, model); MXA_REQUIRE (NULL != dataFile.get() ); //Create the DataImport Class MXADataImport::Pointer dataImport( new MXADataImport() ); dataImport->setDataFile(dataFile); // Register the known ImportDelegates, which will also instantiate the ImportDelegateManager instance. // The ImportDelegateManager instance is a singleton so only one can ever be active per program. ImportDelegateManager::registerKnownImportDelegateFactories(); // Register our Import Delegate by using the static methods from ImportDelegateManager AbstractImportDelegateFactory::Pointer h5ImportTestDelegateFactory ( new H5ImportTestDelegateFactory() ); ImportDelegateManager::registerImportDelegateFactory(h5ImportTestDelegateFactory); // Get an Instance to the ImportDelegateManager ImportDelegateManager::Pointer importManager = ImportDelegateManager::instance(); // Run a comparison of 2 AbstractImportDelegateFactory::Pointers to make sure they are the same. AbstractImportDelegateFactory::Pointer factoryPtr2 = importManager->getImportDelegateFactory(H5ImportTest::Detail::ClassName); MXA_REQUIRE (h5ImportTestDelegateFactory.get() == factoryPtr2.get() ); // Create an Import Delegate to use for the DataSources IImportDelegate::Pointer delegatePtr = ImportDelegateManager::createNewImportDelegate(H5ImportTest::Detail::ClassName); // We are now going to get a reference to the ImportDelegate so we can set the default value that it writes. H5ImportTestDelegate* h5ImportDelegate = dynamic_cast(delegatePtr.get() ); h5ImportDelegate->setValue(55); // We have two dimensions for this model, create a loop to create data sets for each possible dimension value IDataDimension::Pointer dim0 = model->getDataDimension(0); // Get the first Dimension, since there is only one this works MXA_REQUIRE(dim0 != NULL); // Used for Boost Unit Test Framework IDataDimension::Pointer dim1 = model->getDataDimension(1); MXA_REQUIRE(dim1 != NULL); // Used for Boost Unit Test Framework // Create a DataRecord entry for the Data Model IDataRecord::Pointer record = model->getDataRecordByNamedPath("DataRecordContainer/Test Data/Deep Nested Data"); MXA_REQUIRE(NULL != record.get()); // Used for Boost Unit Test Framework // Set the start/end/increment values for each Data Dimension int32_t dim0Start = dim0->getStartValue(); int32_t dim0End = dim0->getEndValue(); int32_t dim0Increment = dim0->getIncrement(); int32_t dim1Start = dim1->getStartValue(); int32_t dim1End = dim1->getEndValue(); int32_t dim1Increment = dim1->getIncrement(); // Create a nested loop to create the necessary DataSource objects that will // be used to import the data into the HDF5 file //std::cout << "CREATING DATA SOURCES" << std::endl; for( int32_t i = dim0Start; i <= dim0End; i += dim0Increment ) { for (int j = dim1Start; j <= dim1End; j = j+ dim1Increment) { //Create some Data Sources MXADataSource::Pointer ds( new MXADataSource() ); std::vector dimValues; dimValues.push_back(i); dimValues.push_back(j); ds->setDimensionValues(dimValues); ds->setDataRecord(record); ds->setSourcePath(""); //Since we are doing everything in software, this is unused ds->setImportDelegate(delegatePtr); ds->setDataModel(model); dataImport->addDataSource(ds); } } // Import the Data into the HDF5 File //std::cout << "IMPORTING DATA NOW" << std::endl; int32_t err = dataImport->import(); MXA_REQUIRE(err >= 0); // Used for Boost Unit Test Framework dataFile->closeFile(false); } // ----------------------------------------------------------------------------- // Creates a Data Model programmitically to use with our data import // ----------------------------------------------------------------------------- MXADataModel::Pointer createSimpleModel() { MXADataModel::Pointer modelPtr = MXADataModel::New(); MXADataModel* model = modelPtr.get(); model->setDataRoot(std::string("Our Experiment/Laboratory Data")); model->setModelType(MXA::MXACurrentFileType); model->setModelVersion(MXA::MXACurrentFileVersion); // ---------- Create 2 Data Dimensions MXADataDimension::Pointer dim0 = MXADataDimension::New("Dimension 1", "Dim1", 0, 2, 1, 2, 1, 1); model->addDataDimension(dim0); MXADataDimension::Pointer dim1 = MXADataDimension::New("Dimension 2", "Dim2", 1, 3, 1, 3, 1, 1); model->addDataDimension(dim1); // ---------- Create Data Records MXADataRecord::Pointer rec1 = MXADataRecord::New(0, std::string("DataRecordContainer"), std::string("DRC1") ); model->addDataRecord(rec1); // ---------- Create Data Records with Parents MXADataRecord::Pointer rec2 = MXADataRecord::New(0, std::string("Test Data"), std::string("Test Data") ); model->addDataRecord(rec2, rec1); MXADataRecord::Pointer rec3 = MXADataRecord::New(0, std::string("Deep Nested Data"), std::string("Nested Data") ); model->addDataRecord(rec3, rec2); // ---------- Create the Required MetaData std::map md; md[MXA::MXA_CREATOR_TAG] = ""; md[MXA::MXA_DATE_TAG] = "2006:12:24 15:34.51"; md[MXA::MXA_DSET_NAME_TAG] = "Testing Data Import"; md[MXA::MXA_DESCRIPTION_TAG] = "Application to test importing data to the data file"; md[MXA::MXA_PEDIGREE_TAG] = "Original"; md[MXA::MXA_DERIVED_SRC_TAG] = "Original Data Files"; md[MXA::MXA_RIGHTS_TAG] = "Unlimited"; md[MXA::MXA_RELEASE_NUMBER_TAG] = "Not Applicable"; model->setRequiredMetaData(md); return modelPtr; } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- int SimpleTest() { // std::cout << logTime() << "Running SimpleImportTest ------------------------" << std::endl; int32_t err = 0; MXADataModel::Pointer model = createSimpleModel(); ImportSimpleData(model, MXAUnitTest::DataImportTest::SimpleImport); // std::cout << logTime() << "Ending SimpleImportTest" << std::endl; return err; } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- void CreateTiffImages() { // Create the XMLParser/Importer Object DataImportXmlParser importer; importer.setXMLInputFile(MXAUnitTest::DataImportTest::ImportXMLFile); // The xmlfile will define the output file so we do NOT need to set it here. int32_t err = importer.parseXMLFile(); MXA_REQUIRE(err >= 0); IDataSource::Collection dataSources = importer.getDataSources(); TiffMaker tiffMaker; std::cout << logTime() << "Creating Tiff Images to import" << std::endl; for (IDataSource::Collection::iterator iter = dataSources.begin(); iter != dataSources.end(); ++iter ) { std::string tiffPath = (*iter).get()->getSourcePath(); // std::cout << "Making Tiff at " << tiffPath << std::endl; tiffMaker.createTiffFile(tiffPath); createdPaths.push_back(tiffPath); } } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- int XMLImportTest() { bool success = MXADir::mkdir(MXAUnitTest::MXATempDir + MXAUnitTest::DataImportTest::TestDir, true); MXA_REQUIRE_EQUAL(success, true); success = MXADir::mkdir(MXAUnitTest::MXATempDir + MXAUnitTest::DataImportTest::TestDir + MXADir::Separator + "test_data", true); MXA_REQUIRE_EQUAL(success, true); //std::cout << logTime() << "Starting XMLImportTest -----------------" << std::endl; // Instantiate the Instance Manager for import delegates ImportDelegateManager::Pointer idManager = ImportDelegateManager::instance(); //Register to be able to import Tiff images H5TiffImportDelegateFactory* ptr = new H5TiffImportDelegateFactory(); AbstractImportDelegateFactory::Pointer h5TiffImportDelegateFactory(ptr); ptr->setImportAsGrayScale(true); ptr->setFileNotFoundIsError(false); ImportDelegateManager::registerImportDelegateFactory(h5TiffImportDelegateFactory); // Create the tiff images to use for the import test CreateTiffImages(); DataImportXmlParser importer; importer.setXMLInputFile(MXAUnitTest::DataImportTest::ImportXMLFile); // The xmlfile will define the output file so we do NOT need to set it here. int32_t err = importer.import(); // Run the Import // if (err < 0) // { // std::cout << logTime() << "Error Importing Data Files. Check any output for possible error logs." << std::endl; // } MXA_REQUIRE (err >= 0); // std::cout << logTime() << "Done With XML Based H5 Tiff import Test -----------------" << std::endl; return err; } // ----------------------------------------------------------------------------- // Use Boost unit test framework // ----------------------------------------------------------------------------- int main(int argc, char **argv) { int err = EXIT_SUCCESS; MXA_REGISTER_TEST( XMLImportTest() ); MXA_REGISTER_TEST( SimpleTest() ); MXA_REGISTER_TEST( RemoveTestFiles() ); PRINT_TEST_SUMMARY(); return err; } /* * 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. */ #include #include #include #include #include #include #include #include LOGGER_TAG("aws.kinesis.kinesis_manager_unittest"); using namespace std; using namespace Aws; using namespace Aws::Kinesis; /** * Parameter reader that sets the output using provided std::mapS. */ class TestParameterReader : public ParameterReaderInterface { public: TestParameterReader(map int_map, map bool_map, map string_map, map> map_map) : int_map_(int_map), bool_map_(bool_map), string_map_(string_map), map_map_(map_map) { } TestParameterReader(string test_prefix) { int_map_ = { {test_prefix + "retention_period", 2}, {test_prefix + "streaming_type", 0}, {test_prefix + "max_latency", 0}, {test_prefix + "fragment_duration", 2}, {test_prefix + "timecode_scale", 1}, {test_prefix + "nal_adaptation_flags", NAL_ADAPTATION_ANNEXB_NALS | NAL_ADAPTATION_ANNEXB_CPD_NALS}, {test_prefix + "frame_rate", 24}, {test_prefix + "avg_bandwidth_bps", 4 * 1024 * 1024}, {test_prefix + "buffer_duration", 120}, {test_prefix + "replay_duration", 40}, {test_prefix + "connection_staleness", 30}, }; bool_map_ = { {test_prefix + "key_frame_fragmentation", true}, {test_prefix + "frame_timecodes", true}, {test_prefix + "absolute_fragment_time", true}, {test_prefix + "fragment_acks", true}, {test_prefix + "restart_on_error", true}, {test_prefix + "recalculate_metrics", true}, }; string_map_ = { {test_prefix + "stream_name", "testStream"}, {test_prefix + "kms_key_id", ""}, {test_prefix + "content_type", "video/h264"}, {test_prefix + "codec_id", "V_MPEG4/ISO/AVC"}, {test_prefix + "track_name", "kinesis_video"}, }; map_map_ = { {test_prefix + "tags", {{"someKey", "someValue"}}}, }; } AwsError ReadInt(const char * name, int & out) const { AwsError result = AWS_ERR_NOT_FOUND; if (int_map_.count(name) > 0) { out = int_map_.at(name); result = AWS_ERR_OK; } return result; } AwsError ReadBool(const char * name, bool & out) const { AwsError result = AWS_ERR_NOT_FOUND; if (bool_map_.count(name) > 0) { out = bool_map_.at(name); result = AWS_ERR_OK; } return result; } AwsError ReadStdString(const char * name, string & out) const { AwsError result = AWS_ERR_NOT_FOUND; if (string_map_.count(name) > 0) { out = string_map_.at(name); result = AWS_ERR_OK; } return result; } AwsError ReadString(const char * name, Aws::String & out) const { return AWS_ERR_EMPTY; } AwsError ReadMap(const char * name, map & out) const { AwsError result = AWS_ERR_NOT_FOUND; if (map_map_.count(name) > 0) { out = map_map_.at(name); result = AWS_ERR_OK; } return result; } AwsError ReadList(const char * name, std::vector & out) const { return AWS_ERR_EMPTY; } AwsError ReadDouble(const char * name, double & out) const { return AWS_ERR_EMPTY; } map int_map_; map bool_map_; map string_map_; map> map_map_; }; /** * Tests stream definitions for equivalence. * @param stream1 * @param stream2 * @return true if the streams are equivalent, false otherwise. */ static bool are_streams_equivalent(unique_ptr stream1, unique_ptr stream2) { bool result = true; StreamInfo stream1_info = stream1->getStreamInfo(); StreamInfo stream2_info = stream2->getStreamInfo(); /** * Compare complex structures first */ if (stream1_info.streamCaps.codecPrivateDataSize != stream2_info.streamCaps.codecPrivateDataSize) { return false; } else { result &= (0 == memcmp((void *)&(stream1_info.streamCaps.codecPrivateData), (void *)&(stream2_info.streamCaps.codecPrivateData), stream1_info.streamCaps.codecPrivateDataSize)); } if (stream1_info.tagCount != stream2_info.tagCount) { return false; } else { for (int tag_idx = 0; tag_idx < stream1_info.tagCount; tag_idx++) { result &= (stream1_info.tags[tag_idx].version == stream2_info.tags[tag_idx].version); result &= (0 == strncmp(stream1_info.tags[tag_idx].name, stream2_info.tags[tag_idx].name, MAX_TAG_NAME_LEN)); result &= (0 == strncmp(stream1_info.tags[tag_idx].value, stream2_info.tags[tag_idx].value, MAX_TAG_VALUE_LEN)); } } /** * Zero out pointers contained within the structs and use memcmp. */ stream2_info.streamCaps.codecPrivateData = nullptr; stream1_info.streamCaps.codecPrivateData = nullptr; stream1_info.tags = nullptr; stream2_info.tags = nullptr; result &= (0 == memcmp((void *)&(stream1_info), (void *)&(stream2_info), sizeof(stream1_info))); return result; } /** * Tests that GetCodecPrivateData successfully reads and decodes the given base64-encoded buffer. */ TEST(StreamDefinitionProviderSuite, getCodecPrivateDataTest) { string test_prefix = "some/test/prefix"; Aws::Kinesis::StreamDefinitionProvider stream_definition_provider; string decoded_string = "hello world"; string encoded_string = "aGVsbG8gd29ybGQ="; map int_map = {}; map bool_map = {}; map tags; map> map_map = {}; map string_map = { {test_prefix + "codecPrivateData", encoded_string}, }; TestParameterReader parameter_reader(int_map, bool_map, string_map, map_map); PBYTE codec_private_data; uint32_t codec_private_data_size; ASSERT_TRUE(KINESIS_MANAGER_STATUS_SUCCEEDED(stream_definition_provider.GetCodecPrivateData( test_prefix.c_str(), parameter_reader, &codec_private_data, &codec_private_data_size))); ASSERT_EQ(decoded_string.length(), codec_private_data_size); ASSERT_TRUE(0 == strncmp(decoded_string.c_str(), (const char *)codec_private_data, codec_private_data_size)); /* Invalid input tests */ KinesisManagerStatus status = stream_definition_provider.GetCodecPrivateData( nullptr, parameter_reader, &codec_private_data, &codec_private_data_size); ASSERT_TRUE(KINESIS_MANAGER_STATUS_FAILED(status) && KINESIS_MANAGER_STATUS_INVALID_INPUT == status); status = stream_definition_provider.GetCodecPrivateData(test_prefix.c_str(), parameter_reader, nullptr, &codec_private_data_size); ASSERT_TRUE(KINESIS_MANAGER_STATUS_FAILED(status) && KINESIS_MANAGER_STATUS_INVALID_INPUT == status); status = stream_definition_provider.GetCodecPrivateData(test_prefix.c_str(), parameter_reader, &codec_private_data, nullptr); ASSERT_TRUE(KINESIS_MANAGER_STATUS_FAILED(status) && KINESIS_MANAGER_STATUS_INVALID_INPUT == status); /* Empty input */ string_map = {}; TestParameterReader empty_parameter_reader(int_map, bool_map, string_map, map_map); codec_private_data = nullptr; ASSERT_TRUE(KINESIS_MANAGER_STATUS_SUCCEEDED(stream_definition_provider.GetCodecPrivateData( test_prefix.c_str(), empty_parameter_reader, &codec_private_data, &codec_private_data_size)) && !codec_private_data); /* Dependency failure */ string_map = { {test_prefix + "codecPrivateData", "1"}, }; TestParameterReader parameter_reader_with_invalid_values(int_map, bool_map, string_map, map_map); status = stream_definition_provider.GetCodecPrivateData( test_prefix.c_str(), parameter_reader_with_invalid_values, &codec_private_data, &codec_private_data_size); ASSERT_TRUE(KINESIS_MANAGER_STATUS_FAILED(status) && KINESIS_MANAGER_STATUS_BASE64DECODE_FAILED == status); } /** * Tests that GetStreamDefinition returns the expected StreamDefinition object by comparing it to a * manually created StreamDefinition. */ TEST(StreamDefinitionProviderSuite, getStreamDefinitionTest) { string test_prefix = "some/test/prefix"; Aws::Kinesis::StreamDefinitionProvider stream_definition_provider; TestParameterReader parameter_reader = TestParameterReader(test_prefix); map string_map = parameter_reader.string_map_; map bool_map = parameter_reader.bool_map_; map int_map = parameter_reader.int_map_; map> map_map = parameter_reader.map_map_; unique_ptr generated_stream_definition = stream_definition_provider.GetStreamDefinition(test_prefix.c_str(), parameter_reader, nullptr, 0); auto equivalent_stream_definition = make_unique( string_map[test_prefix + "stream_name"], hours(int_map[test_prefix + "retention_period"]), &map_map[test_prefix + "tags"], string_map[test_prefix + "kms_key_id"], static_cast(int_map[test_prefix + "streaming_type"]), string_map[test_prefix + "content_type"], milliseconds(int_map[test_prefix + "max_latency"]), seconds(int_map[test_prefix + "fragment_duration"]), milliseconds(int_map[test_prefix + "timecode_scale"]), bool_map[test_prefix + "key_frame_fragmentation"], bool_map[test_prefix + "frame_timecodes"], bool_map[test_prefix + "absolute_fragment_time"], bool_map[test_prefix + "fragment_acks"], bool_map[test_prefix + "restart_on_error"], bool_map[test_prefix + "recalculate_metrics"], static_cast(int_map[test_prefix + "nal_adaptation_flags"]), int_map[test_prefix + "frame_rate"], int_map[test_prefix + "avg_bandwidth_bps"], seconds(int_map[test_prefix + "buffer_duration"]), seconds(int_map[test_prefix + "replay_duration"]), seconds(int_map[test_prefix + "connection_staleness"]), string_map[test_prefix + "codec_id"], string_map[test_prefix + "track_name"], nullptr, 0); ASSERT_TRUE( are_streams_equivalent(move(equivalent_stream_definition), move(generated_stream_definition))); auto different_stream_definition = make_unique( string_map[test_prefix + "stream_name"], hours(int_map[test_prefix + "retention_period"]), &map_map[test_prefix + "tags"], string_map[test_prefix + "kms_key_id"], static_cast(int_map[test_prefix + "streaming_type"]), string_map[test_prefix + "content_type"], milliseconds(int_map[test_prefix + "max_latency"]), seconds(int_map[test_prefix + "fragment_duration"]), milliseconds(int_map[test_prefix + "timecode_scale"]), bool_map[test_prefix + "key_frame_fragmentation"], bool_map[test_prefix + "frame_timecodes"], bool_map[test_prefix + "absolute_fragment_time"], bool_map[test_prefix + "fragment_acks"], bool_map[test_prefix + "restart_on_error"], bool_map[test_prefix + "recalculate_metrics"], static_cast(int_map[test_prefix + "nal_adaptation_flags"]), 4914918, int_map[test_prefix + "avg_bandwidth_bps"], seconds(int_map[test_prefix + "buffer_duration"]), seconds(int_map[test_prefix + "replay_duration"]), seconds(int_map[test_prefix + "connection_staleness"]), string_map[test_prefix + "codec_id"], string_map[test_prefix + "track_name"], nullptr, 0); generated_stream_definition = stream_definition_provider.GetStreamDefinition( test_prefix.c_str(), parameter_reader, nullptr, 0); ASSERT_FALSE( are_streams_equivalent(move(different_stream_definition), move(generated_stream_definition))); /* Invalid input tests */ generated_stream_definition = stream_definition_provider.GetStreamDefinition(nullptr, parameter_reader, nullptr, 0); ASSERT_FALSE(generated_stream_definition); generated_stream_definition = stream_definition_provider.GetStreamDefinition( test_prefix.c_str(), parameter_reader, nullptr, 100); ASSERT_FALSE(generated_stream_definition); } /** * Initializes the video producer and generates a basic stream definition. */ unique_ptr DefaultProducerSetup( Aws::Kinesis::KinesisStreamManager & stream_manager, string region, string test_prefix) { #ifdef PLATFORM_TESTING_ACCESS_KEY setenv("AWS_ACCESS_KEY_ID", PLATFORM_TESTING_ACCESS_KEY, 1); #endif #ifdef PLATFORM_TESTING_SECRET_KEY setenv("AWS_SECRET_ACCESS_KEY", PLATFORM_TESTING_SECRET_KEY, 1); #endif stream_manager.InitializeVideoProducer(region); Aws::Kinesis::StreamDefinitionProvider stream_definition_provider; TestParameterReader parameter_reader = TestParameterReader(test_prefix); unique_ptr stream_definition = stream_definition_provider.GetStreamDefinition( test_prefix.c_str(), parameter_reader, nullptr, 0); return move(stream_definition); } /** * Tests the InitializeVideoProducer function. */ TEST(KinesisStreamManagerSuite, videoInitializationTest) { string test_prefix = "some/test/prefix"; Aws::Kinesis::KinesisStreamManager stream_manager; KinesisManagerStatus status = stream_manager.InitializeVideoProducer("us-west-2"); ASSERT_TRUE(KINESIS_MANAGER_STATUS_SUCCEEDED(status)); ASSERT_TRUE(stream_manager.get_video_producer()); /* Duplicate initialization */ KinesisVideoProducer * video_producer = stream_manager.get_video_producer(); status = stream_manager.InitializeVideoProducer("us-west-2"); ASSERT_TRUE(KINESIS_MANAGER_STATUS_FAILED(status) && KINESIS_MANAGER_STATUS_VIDEO_PRODUCER_ALREADY_INITIALIZED == status); KinesisVideoProducer * video_producer_post_call = stream_manager.get_video_producer(); ASSERT_EQ(video_producer, video_producer_post_call); } #ifdef BUILD_AWS_TESTING // the following tests perform AWS API calls and require user confiugration // to enable them run: colcon build --cmake-args -DBUILD_AWS_TESTING=1 /** * Tests the InitializeVideoStream function. This will attempt to create and load a test stream in * the test account. */ TEST(KinesisStreamManagerSuite, streamInitializationTest) { Aws::Kinesis::KinesisStreamManager stream_manager; /* Before calling InitializeVideoProducer */ KinesisManagerStatus status = stream_manager.InitializeVideoStream(move(unique_ptr())); ASSERT_TRUE(KINESIS_MANAGER_STATUS_FAILED(status) && KINESIS_MANAGER_STATUS_VIDEO_PRODUCER_NOT_INITIALIZED == status); ASSERT_FALSE(stream_manager.get_video_producer()); unique_ptr stream_definition = DefaultProducerSetup(stream_manager, string("us-west-2"), string("stream/test")); ASSERT_TRUE(stream_manager.get_video_producer()); /* Video producer has been created but the stream definition is empty. */ status = stream_manager.InitializeVideoStream(unique_ptr{}); ASSERT_TRUE(KINESIS_MANAGER_STATUS_FAILED(status) && KINESIS_MANAGER_STATUS_INVALID_INPUT == status); status = stream_manager.InitializeVideoStream(move(stream_definition)); ASSERT_TRUE(KINESIS_MANAGER_STATUS_SUCCEEDED(status)); } /** * Tests the PutFrame function. This will load the test stream and attempt to transmit a dummy frame * to it. */ TEST(KinesisStreamManagerSuite, putFrameTest) { Aws::Kinesis::KinesisStreamManager stream_manager; Frame frame; string stream_name("testStream"); /* Before calling InitializeVideoProducer */ KinesisManagerStatus status = stream_manager.PutFrame(stream_name, frame); ASSERT_TRUE(KINESIS_MANAGER_STATUS_FAILED(status) && KINESIS_MANAGER_STATUS_VIDEO_PRODUCER_NOT_INITIALIZED == status); /* Stream name not found (i.e. before calling InitializeVideoStream) */ unique_ptr stream_definition = DefaultProducerSetup(stream_manager, string("us-west-2"), string("frame/test")); status = stream_manager.PutFrame(string(stream_name), frame); ASSERT_TRUE(KINESIS_MANAGER_STATUS_FAILED(status) && KINESIS_MANAGER_STATUS_PUTFRAME_STREAM_NOT_FOUND == status); status = stream_manager.InitializeVideoStream(move(stream_definition)); ASSERT_TRUE(KINESIS_MANAGER_STATUS_SUCCEEDED(status)); /* Invalid frame */ frame.size = 0; status = stream_manager.PutFrame(stream_name, frame); ASSERT_TRUE(KINESIS_MANAGER_STATUS_FAILED(status) && KINESIS_MANAGER_STATUS_PUTFRAME_FAILED == status); /* Valid (but dummy) frame */ frame.size = 4; std::vector bytes = {0x00, 0x01, 0x02, 0x03}; frame.frameData = reinterpret_cast((void *)(bytes.data())); frame.duration = 5000000; frame.index = 1; UINT64 timestamp = 0; timestamp = std::chrono::duration_cast( std::chrono::system_clock::now().time_since_epoch()) .count() / DEFAULT_TIME_UNIT_IN_NANOS; frame.decodingTs = timestamp; frame.presentationTs = timestamp; frame.flags = (FRAME_FLAGS)0; status = stream_manager.PutFrame(stream_name, frame); ASSERT_TRUE(KINESIS_MANAGER_STATUS_SUCCEEDED(status)); } #endif int main(int argc, char ** argv) { LOG_CONFIGURE_STDOUT("ERROR"); Aws::SDKOptions options; Aws::InitAPI(options); testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } boards/src/hls/xfopencv_erosion/include/imgproc/xf_pyr_dense_optical_flow_scale.hpp10-100 /*************************************************************************** Copyright (c) 2018, Xilinx, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of 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. ***************************************************************************/ #ifndef __XF_PYR_DENSE_OPTICAL_FLOW_SCALE__ #define __XF_PYR_DENSE_OPTICAL_FLOW_SCALE__ template void load_data (hls::stream< ap_fixed > &inStrm0, hls::stream< ap_fixed > &inStrm1, ap_fixed buf[2][MAXWIDTH], int rows, int cols, bool &flagLoaded, int i, ap_ufixed scaleI, ap_fixed &fracI, int &prevIceil) { #pragma HLS inline off ap_fixed iSmall = i * scaleI; int iSmallFloor = (int) iSmall; fracI = iSmall - (ap_fixed)iSmallFloor; if ((iSmallFloor + 1 > prevIceil || i<2) && (iSmallFloor < rows-1)) { flagLoaded = 1; for (int i=0; i ap_fixed compute_result(ap_fixed fracI, ap_fixed fracJ, ap_fixed i0, ap_fixed i1, ap_fixed i2, ap_fixed i3) { #pragma HLS inline off ap_fixed<18,1> fi = (fracI); ap_fixed<18,1> fj = (fracJ); ap_fixed<36,1> fij = (ap_fixed<36,1>)fi * (ap_fixed<36,1>)fj; ap_fixed<18,1> p3 = (ap_fixed<18,1>) fij; ap_fixed<18,1> p2 = (ap_fixed<18,1>)((ap_fixed<36,1>) fi - fij); ap_fixed<18,1> p1 = (ap_fixed<18,1>)((ap_fixed<36,1>) fj - fij); ap_fixed<21,4> p0 = ap_fixed<21,4>(1.0) - ap_fixed<21,4>(p1) - ap_fixed<21,4>(p2) - ap_fixed<21,4>(p3); ap_fixed resIf = (ap_fixed)i0*p0 + (ap_fixed)i1*p1 + (ap_fixed)i2*p2 + (ap_fixed)i3*p3; return (ap_fixed)resIf; } // end compute_result() template void process(ap_fixed buf[2][MAXWIDTH], ap_fixed buffer[2][2][MAXWIDTH], unsigned short int outRows, unsigned short int outCols, hls::stream< ap_fixed >& outStrm0, hls::stream< ap_fixed >& outStrm1, bool flagLoaded, int row, ap_ufixed scaleI, ap_ufixed scaleJ, ap_fixed fracI, int mul) { #pragma HLS inline off int bufCount = 0; ap_fixed regLoad; int prevJceil = -1; ap_fixed i0[2]={0,0}; ap_fixed i1[2]={0,0}; ap_fixed i2[2]={0,0}; ap_fixed i3[2]={0,0}; L3:for (ap_uint<16> j=0; j jSmall = j * scaleJ; int jSmallFloor = (int) jSmall; ap_fixed iSmall = row * scaleI; int iSmallFloor = (int) iSmall; ap_fixed fracI = iSmall - (ap_fixed)iSmallFloor; ap_fixed fracJ = jSmall - (ap_fixed)jSmallFloor; if (row == 0) { fracI = 1; if (j==0) { for (int k=0; k<2; k++) { ap_fixed reg = buf[k][bufCount]; buffer[k][1][bufCount] = reg; i3[k] = reg; } fracI = 1; fracJ = 1; bufCount++; prevJceil = 0; } else if (j reg = buf[k][bufCount]; buffer[k][1][bufCount] = reg; i3[k] = reg; } bufCount++; prevJceil = jSmallFloor + 1; } } else { i3[0] = buffer[0][1][bufCount-1]; i3[1] = buffer[1][1][bufCount-1]; fracI = 1; fracJ = 1; } } else if (row < outRows-1) { if (j==0) { i0[0] = 0; i2[0] = 0; i0[1] = 0; i2[1] = 0; fracJ = 1; if (flagLoaded) { for (int k=0; k<2; k++) { ap_fixed reg = buf[k][bufCount]; ap_fixed tmp = buffer[k][1][bufCount]; buffer[k][0][bufCount] = tmp; i1[k] = tmp; buffer[k][1][bufCount] = reg; i3[k] = reg; } bufCount++; } else { for (int k=0; k<2; k++) { i1[k] = buffer[k][0][bufCount]; i3[k] = buffer[k][1][bufCount]; } bufCount++; } prevJceil = 0; } else if (j < outCols) { if (prevJceil == jSmallFloor) { i0[0] = i1[0]; i2[0] = i3[0]; i0[1] = i1[1]; i2[1] = i3[1]; if (flagLoaded) { for (int k=0; k<2; k++) { ap_fixed reg = buf[k][bufCount]; ap_fixed tmp = buffer[k][1][bufCount]; buffer[k][0][bufCount] = tmp; i1[k] = tmp; buffer[k][1][bufCount] = reg; i3[k] = reg; } bufCount++; } else { for (int k=0; k<2; k++) { i1[k] = buffer[k][0][bufCount]; i3[k] = buffer[k][1][bufCount]; } bufCount++; } prevJceil = jSmallFloor + 1; } } else { fracJ = 1; } } else { if (j==0) { i3[0] = buffer[0][1][bufCount]; i3[1] = buffer[1][1][bufCount]; fracI = 1; fracJ = 1; bufCount++; prevJceil = 0; } else if (j < outCols) { if (prevJceil == jSmallFloor) { for (int k=0; k<2; k++) { i2[k] = i3[k]; ap_fixed reg = buffer[k][1][bufCount]; i3[k] = reg; } bufCount++; prevJceil = jSmallFloor + 1; } fracI = 1; } else { i3[0] = buffer[0][1][bufCount-1]; i3[1] = buffer[1][1][bufCount-1]; fracI = 1; fracJ = 1; } } // end else ap_fixed resIf0 = compute_result (fracI, fracJ, i0[0], i1[0], i2[0], i3[0]); outStrm0.write(resIf0<<1); ap_fixed resIf1 = compute_result (fracI, fracJ, i0[1], i1[1], i2[1], i3[1]); outStrm1.write(resIf1<<1); } // end L3 } // end process() template void scale_up( hls::stream< ap_fixed > &inStrm0, hls::stream< ap_fixed > &outStrm0, hls::stream< ap_fixed > &inStrm1, hls::stream< ap_fixed > &outStrm1, unsigned short int inRows, unsigned short int inCols, unsigned short int outRows, unsigned short int outCols, int mul, const bool scale_up_flag, float scale_comp) { #pragma HLS inline off ap_fixed buffer[2][2][MAXWIDTH]; #pragma HLS array_reshape variable=buffer dim=1 complete #pragma HLS array_reshape variable=buffer dim=2 complete ap_fixed buf0[2][MAXWIDTH], buf1[2][MAXWIDTH]; #pragma HLS array_reshape variable=buf0 dim=1 complete #pragma HLS array_reshape variable=buf1 dim=1 complete if (USE_URAM) { //#pragma HLS RESOURCE variable=buffer core=XPM_MEMORY uram //#pragma HLS RESOURCE variable=buf0 core=XPM_MEMORY uram //#pragma HLS RESOURCE variable=buf1 core=XPM_MEMORY uram #pragma HLS RESOURCE variable=buffer core=RAM_S2P_URAM #pragma HLS RESOURCE variable=buf0 core=RAM_S2P_URAM #pragma HLS RESOURCE variable=buf1 core=RAM_S2P_URAM } ap_ufixed scaleI = (ap_ufixed)scale_comp; ap_ufixed scaleJ = (ap_ufixed)scale_comp; #if DEBUG cout << "Scale Flag: " << scale_up_flag << "\n"; cout << "Scale Comp: " << scale_comp << "\n"; cout << "Scale: " << float(scaleJ) << " " << float(scaleI) << "\n"; #endif ap_fixed fracI0, fracI1; bool flagLoaded0, flagLoaded1; bool flag = 0; if(scale_up_flag==0){ for (ap_uint<16> i=0; i j=0; j)inStrm0.read()); outStrm1.write((ap_fixed)inStrm1.read()); } } } else{ int prevIceil = -1; load_data(inStrm0, inStrm1, buf0, inRows, inCols, flagLoaded0, 0, scaleI, fracI0, prevIceil); L2:for (ap_uint<16> i=0; i(inStrm0, inStrm1, buf1, inRows, inCols, flagLoaded1, i+1, scaleI, fracI1, prevIceil); process(buf0, buffer, outRows, outCols, outStrm0, outStrm1, flagLoaded0, i, scaleI, scaleJ, fracI0, mul); flag = 1; } else { load_data(inStrm0, inStrm1, buf0, inRows, inCols, flagLoaded0, i+1, scaleI, fracI0, prevIceil); process(buf1, buffer, outRows, outCols, outStrm0, outStrm1, flagLoaded1, i, scaleI, scaleJ, fracI1, mul); flag = 0; } } // end L2 if (flag ==0) { process(buf0, buffer, outRows, outCols, outStrm0, outStrm1, flagLoaded0, outRows-1, scaleI, scaleJ, fracI0, mul); } else { process(buf1, buffer, outRows, outCols, outStrm0, outStrm1, flagLoaded1, outRows-1, scaleI, scaleJ, fracI1, mul); } } } // end scale_up #endif0 // -*-Mode: C++;-*- // * BeginRiceCopyright ***************************************************** // // $HeadURL$ // $Id$ // // -------------------------------------------------------------------------- // Part of HPCToolkit (hpctoolkit.org) // // Information about sources of support for research and development of // HPCToolkit is at 'hpctoolkit.org' and in 'README.Acknowledgments'. // -------------------------------------------------------------------------- // // Copyright ((c)) 2020, Rice University // 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 Rice University (RICE) 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 RICE 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 RICE 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. // // ******************************************************* EndRiceCopyright * #ifndef HPCTOOLKIT_PROFILE_UTIL_RAGGED_VECTOR_H #define HPCTOOLKIT_PROFILE_UTIL_RAGGED_VECTOR_H #include "once.hpp" #include "locked_unordered.hpp" #include "log.hpp" #include "../stdshim/shared_mutex.hpp" #include #include #include #include namespace hpctoolkit { class ProfilePipeline; namespace util { template class ragged_vector; template class ragged_map; namespace detail { /// Structure definition for a set of ragged vectors. One of these must be /// available to construct a ragged_vector, and stay available to ensure /// validity. template class ragged_struct { public: ragged_struct() : complete(false), m_size(0), m_entries() {}; ~ragged_struct() = default; using initializer_t = std::function; using destructor_t = std::function; private: struct entry { entry(initializer_t&& i, destructor_t&& d, std::size_t s, std::size_t o) : initializer(std::move(i)), destructor(std::move(d)), size(s), offset(o) {}; initializer_t initializer; destructor_t destructor; std::size_t size; std::size_t offset; }; // General member, which contains all the info that may be copied into either // kind of member. Automatically converts into the correct version when // needed. struct generic_member { generic_member(ragged_struct& b, std::size_t i, const entry& e) : m_base(b), m_index(i), m_entry(e) {}; ragged_struct& m_base; std::size_t m_index; entry m_entry; }; template class generic_typed_member : public generic_member { public: generic_typed_member(generic_member&& m) : generic_member(std::move(m)) {}; ~generic_typed_member() = default; }; public: /// Member of a ragged_vector. These references are required for access into /// applicable ragged_vectors. Otherwise they're mostly opaque. class member { public: member() : m_base(nullptr) {}; ~member() = default; member(const member&) = default; member(member&&) = default; member(generic_member&& g) : m_base(&g.m_base), m_index(g.m_index), m_offset(g.m_entry.offset), m_size(g.m_entry.size) {}; member& operator=(const member&) = default; member& operator=(member&&) = default; member& operator=(generic_member&& g) { return operator=(member(std::move(g))); } std::size_t index() const noexcept { return m_index; } std::size_t offset() const noexcept { return m_offset; } std::size_t size() const noexcept { return m_size; } private: friend class ragged_struct; ragged_struct* m_base; std::size_t m_index; std::size_t m_offset; // Copied out for faster accesses. std::size_t m_size; // Also copied out for faster accesses. }; /// Register an arbitrary block of memory for future ragged_vectors. /// `init` is called to initialize the block, `des` to destroy it. // MT: Internally Synchronized generic_member add(std::size_t sz, std::size_t align, initializer_t&& init, destructor_t&& des) { if(complete) util::log::fatal() << "Cannot add entries to a frozen ragged_struct!"; std::unique_lock l(m_mtex); auto idx = m_entries.size(); m_size = (m_size + (align - 1)) & -align; m_entries.emplace_back(std::move(init), std::move(des), sz, m_size); m_size += sz; return generic_member(*this, idx, m_entries[idx]); } /// Typed version of member, to allow for (more) compile-type type safety. template class typed_member : public member { public: typed_member() : member() {}; typed_member(const member& m) : member(m) {}; typed_member(member&& m) : member(std::move(m)) {}; typed_member(generic_typed_member&& g) : member(std::move(g)) {}; typed_member& operator=(generic_typed_member&& g) { member::operator=(std::move(g)); return *this; } ~typed_member() = default; }; /// Register a typed memory block for future ragged_vectors. The constructor /// and destructor of T are used for initialization and destruction. // MT: Internally Synchronized template generic_typed_member add(Args&&... args) { return add(sizeof(T), alignof(T), [args...](void* v, InitArgs&&... iargs){ new(v) T(std::forward(iargs)..., args...); }, [](void* v){ ((T*)v)->~T(); }); } /// Register a typed memory block for future ragged_vectors. Unlike add(...), /// this uses the default constructor and the given function for initialization. // MT: Internally Synchonized template generic_typed_member add_default(std::function&& init) { return add(sizeof(T), alignof(T), [init](void* v, InitArgs&&... iargs){ new(v) T; init(*(T*)v, std::forward(iargs)...); }, [](void* v){ ((T*)v)->~T(); }); } /// Register a typed memory block for future ragged_vectors. Unlike add(...), /// this uses the default constructor for initialization. // MT: Internally Synchonized template generic_typed_member add_default() { return add(sizeof(T), alignof(T), [](void* v, InitArgs&&... iargs){ new(v) T; }, [](void* v){ ((T*)v)->~T(); }); } /// Register a typed memory block for future ragged_vectors. Uses the /// constructor add() would use, but still calls a custom function after. // MT: Internally Synchonized template generic_typed_member add_initializer( std::function&& init, Args&&... args) { return add(sizeof(T), alignof(T), [init, args...](void* v, InitArgs&&... iargs){ new(v) T(std::forward(iargs)..., args...); init(*(T*)v, std::forward(iargs)...); }, [](void* v){ ((T*)v)->~T(); }); } /// Freeze additions to the struct, allowing ragged_vectors to be generated. // MT: Externally Synchonized void freeze() noexcept { complete = true; } /// Check whether the ragged_struct is frozen and ready for actual use. // MT: Externally Synchronized (after freeze()) void valid() { if(!complete) util::log::fatal() << "Cannot use a ragged_struct before freezing!"; } /// Check whether a member (or typed_member) is valid with respect to this /// ragged_struct. Throws if its not. /// NOTE: For ragged_* only. // MT: Safe (const) void valid(const member& m) const { if(!m.m_base) util::log::fatal() << "Attempt to use an empty member!"; if(m.m_base != this) util::log::fatal() << "Attempt to use an incompatible member!"; } /// Initialize the given member in the given data block. Adding `direct` means /// the data block starts with that member (sparse). /// NOTE: For ragged_* only. // MT: Externally Synchronized (after freeze()) void initialize(const member& m, void* d, InitArgs&&... args) { valid(); m_entries[m.m_index].initializer((char*)d + m.m_offset, std::forward(args)...); } /// Destroy the given memeber in the given data block. // MT: Externally Synchronized (after freeze()) void destruct(const member& m, void* d) { valid(); m_entries[m.m_index].destructor((char*)d + m.m_offset); } /// Access the entry table, with or without locking. // MT: Externally Synchronized (after freeze()) const std::vector& entries() { valid(); return m_entries; } /// Get a member for the given index. NOTE: For ragged_* only. // MT: Externally Synchronized (after freeze()) member memberFor(std::size_t i) { valid(); return generic_member(*this, i, m_entries[i]); } /// Get the final total size of the struct. // MT: Externally Synchronized (after freeze()) std::size_t size() { valid(); return m_size; } private: bool complete; stdshim::shared_mutex m_mtex; std::size_t m_size; std::vector m_entries; }; } /// Ragged vectors are vectors with a runtime-defined structure. Unlike normal /// vectors, their size can't be changed after allocation. Like normal vectors, /// the items are allocated in one big block without any other mess. template class ragged_vector { public: using struct_t = detail::ragged_struct; using member_t = typename struct_t::member; template using typed_member_t = typename struct_t::template typed_member; template ragged_vector(struct_t& rs, Args&&... args) : m_base(rs), flags(m_base.entries().size()), data(new char[m_base.size()]) { auto base_r = std::ref(m_base); auto data_r = data.get(); init = [base_r, data_r, args...](const member_t& m){ base_r.get().initialize(m, data_r, args...); }; } ragged_vector(const ragged_vector& o) = delete; ragged_vector(ragged_vector&& o) : m_base(o.m_base), flags(std::move(o.flags)), init(std::move(o.init)), data(std::move(o.data)) {}; template ragged_vector(ragged_vector&& o, Args&&... args) : m_base(o.m_base), flags(std::move(o.flags)), data(std::move(o.data)) { auto base_r = std::ref(m_base); auto data_r = data.get(); init = [base_r, data_r, args...](const member_t& m){ base_r.get().initialize(m, data_r, args...); }; } ~ragged_vector() noexcept { if(!data) return; // Not our problem anymore. const auto& es = m_base.entries(); for(std::size_t i = 0; i < es.size(); i++) { if(flags[i].query()) m_base.destruct(m_base.memberFor(i), data.get()); } } /// Eagerly initialize every entry in the vector. If this is not called, /// members will be initialized lazily. // MT: Internally Synchronized void initialize() noexcept { const auto& es = m_base.entries(); for(std::size_t i = 0; i < es.size(); i++) flags[i].call_nowait(init, m_base.memberFor(i)); } /// Get a pointer to an entry in the vector. Throws if the member is invalid. // MT: Internally Synchronized [[nodiscard]] void* at(const member_t& m) noexcept { m_base.valid(m); flags[m.index()].call(init, m); return &data[m.offset()]; } /// Typed version of at(), that works with typed_members. // MT: Internally Synchronized template [[nodiscard]] T* at(const typed_member_t& m) { return static_cast(at((const member_t&)m)); } // operator[], for ease of use. // MT: Internally Synchronized template [[nodiscard]] T& operator[](const typed_member_t& m) { return *at(m); } template [[nodiscard]] auto& operator[](const K& k) { return *at(k(*this)); } struct_t& base() { return m_base; } private: struct_t& m_base; struct cleanup { void operator()(char* d) { delete[] d; } }; std::vector flags; std::function init; std::unique_ptr data; }; } } #endif // HPCTOOLKIT_PROFILE_UTIL_RAGGED_VECTOR_H kernyan/ananas10-100 /*- * SPDX-License-Identifier: Zlib * * Copyright (c) 2009-2018 <> * For conditions of distribution and use, see LICENSE file */ /* * The usbbus is the root of all USB devices; it is connected directly to the * HCD driver device, and takes care of things like device attachment, power * and bandwidth regulation and the like. * * Directly attached to the usbbus are the actual USB devices; the USB_DEVICE * structure is obtained as a resource and takes care of the USB details. * * For example: * * ohci0 <--- usbbus0 * | * +-----< usbhub0 * | * +-----< usb-keyboard0 */ #include #include #include "kernel/device.h" #include "kernel/driver.h" #include "kernel/lib.h" #include "kernel/mm.h" #include "kernel/result.h" #include "kernel/thread.h" #include "usb-bus.h" #include "usb-device.h" namespace usb { typedef util::List BusList; namespace { Thread* usbbus_thread{}; Semaphore usbbus_semaphore("usbbus-sem", 0); USBDeviceList usbbus_pendingqueue; Spinlock usbbus_spl_pendingqueue; /* protects usbbus_pendingqueue */ BusList usbbus_busses; Mutex usbbus_mutex("usbbus"); /* protects usbbus_busses */ } // unnamed namespace void ScheduleAttach(USBDevice& usb_dev) { /* Add the device to our queue */ { SpinlockGuard g(usbbus_spl_pendingqueue); usbbus_pendingqueue.push_back(usb_dev); } /* Wake up our thread */ usbbus_semaphore.Signal(); } Result Bus::Attach() { bus_NeedsExplore = true; /* * Create the root hub device; it will handle all our children - the HCD may * need to know about this as the root hub may be polling... */ auto roothub = new USBDevice(*this, nullptr, 0, USB_DEVICE_FLAG_ROOT_HUB); d_Parent->GetUSBDeviceOperations()->SetRootHub(*roothub); ScheduleAttach(*roothub); /* Register ourselves within the big bus list */ { MutexGuard g(usbbus_mutex); usbbus_busses.push_back(*this); } return Result::Success(); } Result Bus::Detach() { panic("detach"); return Result::Success(); } int Bus::AllocateAddress() { /* XXX crude */ static int cur_addr = 1; return cur_addr++; } void Bus::ScheduleExplore() { Lock(); bus_NeedsExplore = true; Unlock(); usbbus_semaphore.Signal(); } /* Must be called with lock held! */ void Bus::Explore() { AssertLocked(); bus_NeedsExplore = false; for (auto& usb_dev : bus_devices) { Device* dev = usb_dev.ud_device; if (dev->GetUSBHubDeviceOperations() != nullptr) dev->GetUSBHubDeviceOperations()->HandleExplore(); } } /* Must be called with lock held! */ Result Bus::DetachHub(Hub& hub) { AssertLocked(); for (auto it = bus_devices.begin(); it != bus_devices.end(); /* nothing */) { auto& usb_dev = *it; ++it; if (usb_dev.ud_hub != &hub) continue; Result err = usb_dev.Detach(); (void)err; // XXX what to do in this case? } return Result::Success(); } static void usb_bus_thread(void* unused) { /* Note that this thread is used for _all_ USB busses */ while (1) { /* Wait until we have to wake up... */ usbbus_semaphore.Wait(); while (1) { /* * See if any USB busses need to be explored; we do this first because * exploring may trigger new devices to attach or old ones to remove. */ { MutexGuard g(usbbus_mutex); for (auto& bus : usbbus_busses) { bus.Lock(); if (bus.bus_NeedsExplore) bus.Explore(); bus.Unlock(); } } /* Handle attaching devices */ USBDevice* usb_dev; { SpinlockGuard g(usbbus_spl_pendingqueue); if (usbbus_pendingqueue.empty()) break; usb_dev = &usbbus_pendingqueue.front(); usbbus_pendingqueue.pop_front(); } /* * Note that attaching will block until completed, which is intentional * as it ensures we will never attach more than one device in the system * at any given time. */ Result result = usb_dev->Attach(); KASSERT( result.IsSuccess(), "cannot yet deal with failures %d", result.AsStatusCode()); /* This worked; hook the device to the bus' device list */ Bus& bus = usb_dev->ud_bus; bus.Lock(); bus.bus_devices.push_back(*usb_dev); bus.Unlock(); } } } namespace { struct USBBus_Driver : public Driver { USBBus_Driver() : Driver("usbbus") {} const char* GetBussesToProbeOn() const override { return "ohci,uhci"; } Device* CreateDevice(const CreateDeviceProperties& cdp) override { return new Bus(cdp); } }; const init::OnInit initializeUSBBus(init::SubSystem::Device, init::Order::First, []() { /* * Create a kernel thread to handle USB device attachments. We use a thread for this * since we can only attach one at the same time. */ if (auto result = kthread_alloc("usbbus", &usb_bus_thread, NULL, usbbus_thread); result.IsFailure()) panic("cannot create usbbus thread"); usbbus_thread->Resume(); }); const RegisterDriver registerDriver; } // unnamed namespace } // namespace usb packages/monte_carlo/core/src/MonteCarlo_SimulationGeneralProperties.hpp //---------------------------------------------------------------------------// //! //! \file MonteCarlo_SimulationGeneralProperties.hpp //! \author , //! \brief Simulation general properties class decl. //! //---------------------------------------------------------------------------// #ifndef MONTE_CARLO_SIMULATION_GENERAL_PROPERTIES_HPP #define MONTE_CARLO_SIMULATION_GENERAL_PROPERTIES_HPP // Boost Includes #include #include #include #include // FRENSIE Includes #include "MonteCarlo_ParticleModeType.hpp" #include "Utility_QuantityTraits.hpp" #include "Utility_ExplicitSerializationTemplateInstantiationMacros.hpp" namespace MonteCarlo{ /*! The general simulation properties class * * Use this class in all parts of code that require runtime configuration. */ class SimulationGeneralProperties { public: //! Constructor SimulationGeneralProperties(); //! Destructor virtual ~SimulationGeneralProperties() { /* ... */ } //! Set the particle mode void setParticleMode( const ParticleModeType particle_mode ); //! Return the particle mode type ParticleModeType getParticleMode() const; //! Set the number of histories to run void setNumberOfHistories( const uint64_t histories ); //! Return the number of histories to run uint64_t getNumberOfHistories() const; //! Set the minimum number of rendezvous per simulation void setMinNumberOfRendezvous( const uint64_t rendezvous ); //! Return the mimimum number of rendezvous per simulation uint64_t getMinNumberOfRendezvous() const; //! Set the maximum rendezvous batch size void setMaxRendezvousBatchSize( const uint64_t max_batch_size ); //! Get the maximum rendezvous batch size uint64_t getMaxRendezvousBatchSize() const; //! Set the minimum number of batches per rendezvous void setMinNumberOfBatchesPerRendezvous( const uint64_t batches ); //! Get the minimum number of batches per rendezvous uint64_t getMinNumberOfBatchesPerRendezvous() const; //! Set the maximum batch size void setMaxBatchSize( const uint64_t max_batch_size ); //! Get the maximum batch size uint64_t getMaxBatchSize() const; //! Set the number of batches for an MPI configuration void setNumberOfBatchesPerProcessor( const uint64_t batches_per_processor ); //! Return the number of batches for an MPI configuration uint64_t getNumberOfBatchesPerProcessor() const; //! Set the number of snapshots per batch void setNumberOfSnapshotsPerBatch( const uint64_t snapshots_per_batch ); //! Get the number of snapshots per batch uint64_t getNumberOfSnapshotsPerBatch() const; //! Set the history simulation wall time (s) void setSimulationWallTime( const double wall_time ); //! Return the history simulation wall time (s) double getSimulationWallTime() const; //! Set implicit capture mode to on (off by default) void setImplicitCaptureModeOn(); //! Set analogue capture mode to on (on by default) void setAnalogueCaptureModeOn(); //! Return if implicit capture mode has been set bool isImplicitCaptureModeOn() const; private: // Save the state to an archive template void save( Archive& ar, const unsigned version ) const; // Load the state from an archive template void load( Archive& ar, const unsigned version ); BOOST_SERIALIZATION_SPLIT_MEMBER(); // Declare the boost serialization access object as a friend friend class boost::serialization::access; // The particle mode ParticleModeType d_particle_mode; // The number of histories to run uint64_t d_number_of_histories; // The minimum number of rendezvous per simulation uint64_t d_min_number_of_rendezvous; // The maximum rendezvous batch size uint64_t d_max_rendezvous_batch_size; // The minimum number of batches per rendezvous uint64_t d_min_number_of_batches_per_rendezvous; // The maximum batch size uint64_t d_max_batch_size; // The number of batches to run for MPI configuration uint64_t d_number_of_batches_per_processor; // The number of snapshots per batch uint64_t d_number_of_snapshots_per_batch; // The simulation wall time double d_wall_time; // The capture mode (true = implicit, false = analogue - default) bool d_implicit_capture_mode_on; }; // Save the state to an archive template void SimulationGeneralProperties::save( Archive& ar, const unsigned version ) const { ar & BOOST_SERIALIZATION_NVP( d_particle_mode ); ar & BOOST_SERIALIZATION_NVP( d_number_of_histories ); ar & BOOST_SERIALIZATION_NVP( d_min_number_of_rendezvous ); ar & BOOST_SERIALIZATION_NVP( d_max_rendezvous_batch_size ); ar & BOOST_SERIALIZATION_NVP( d_min_number_of_batches_per_rendezvous ); ar & BOOST_SERIALIZATION_NVP( d_max_batch_size ); ar & BOOST_SERIALIZATION_NVP( d_number_of_batches_per_processor ); ar & BOOST_SERIALIZATION_NVP( d_number_of_snapshots_per_batch ); // We cannot safely serialize inf to all archive types - create a flag that // records if the simulation wall time is inf const bool __inf_wall_time__ = (d_wall_time == Utility::QuantityTraits::inf()); ar & BOOST_SERIALIZATION_NVP( __inf_wall_time__ ); if( __inf_wall_time__ ) { double tmp_wall_time = Utility::QuantityTraits::max(); ar & boost::serialization::make_nvp( "d_wall_time", tmp_wall_time ); } else { ar & BOOST_SERIALIZATION_NVP( d_wall_time ); } ar & BOOST_SERIALIZATION_NVP( d_implicit_capture_mode_on ); } // Load the state to an archive template void SimulationGeneralProperties::load( Archive& ar, const unsigned version ) { ar & BOOST_SERIALIZATION_NVP( d_particle_mode ); ar & BOOST_SERIALIZATION_NVP( d_number_of_histories ); ar & BOOST_SERIALIZATION_NVP( d_min_number_of_rendezvous ); ar & BOOST_SERIALIZATION_NVP( d_max_rendezvous_batch_size ); ar & BOOST_SERIALIZATION_NVP( d_min_number_of_batches_per_rendezvous ); ar & BOOST_SERIALIZATION_NVP( d_max_batch_size ); ar & BOOST_SERIALIZATION_NVP( d_number_of_batches_per_processor ); ar & BOOST_SERIALIZATION_NVP( d_number_of_snapshots_per_batch ); // Load the wall time bool __inf_wall_time__; ar & BOOST_SERIALIZATION_NVP( __inf_wall_time__ ); ar & BOOST_SERIALIZATION_NVP( d_wall_time ); if( __inf_wall_time__ ) d_wall_time = Utility::QuantityTraits::inf(); ar & BOOST_SERIALIZATION_NVP( d_implicit_capture_mode_on ); } } // end MonteCarlo namespace #if !defined SWIG BOOST_CLASS_VERSION( MonteCarlo::SimulationGeneralProperties, 0 ); BOOST_CLASS_EXPORT_KEY2( MonteCarlo::SimulationGeneralProperties, "SimulationGeneralProperties" ); EXTERN_EXPLICIT_CLASS_SERIALIZE_INST( MonteCarlo, SimulationGeneralProperties ); #endif // end !defined SWIG #endif // end MONTE_CARLO_SIMULATION_GENERAL_PROPERTIES_HPP //---------------------------------------------------------------------------// // end MonteCarlo_SimulationGeneralProperties.cpp //---------------------------------------------------------------------------// 1-10 /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "berryPropertyTester.h" #include "berryPlatform.h" namespace berry { void PropertyTester::InternalInitialize(PropertyTesterDescriptor::Pointer descriptor) { fProperties= descriptor->GetProperties(); fNamespace= descriptor->GetNamespace(); fConfigElement= descriptor->GetExtensionElement(); } PropertyTesterDescriptor::Pointer PropertyTester::InternalCreateDescriptor() { PropertyTesterDescriptor::Pointer tester(new PropertyTesterDescriptor(fConfigElement, fNamespace, fProperties)); return tester; } bool PropertyTester::Handles(const std::string& namespaze, const std::string& property) { return fNamespace == namespaze && fProperties.find("," + property + ",") != std::string::npos; } bool PropertyTester::IsInstantiated() { return true; } bool PropertyTester::IsDeclaringPluginActive() { IBundle::Pointer bundle= Platform::GetBundle(fConfigElement->GetContributor()); return bundle->IsActive(); } IPropertyTester* PropertyTester::Instantiate() { return this; } } // namespace berry #include #include #include "URDFRigidBodyManipulator.h" #include "../RigidBodyConstraint.h" using namespace std; int main() { URDFRigidBodyManipulator* model = loadURDFfromFile("../../../../examples/Atlas/urdf/atlas_minimal_contact.urdf"); if(!model) { cerr << "ERROR: Failed to load model"<0 // Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #define FML_USED_ON_EMBEDDER #include #include "embedder.h" #include "embedder_engine.h" #include "flutter/flow/raster_cache.h" #include "flutter/fml/file.h" #include "flutter/fml/make_copyable.h" #include "flutter/fml/mapping.h" #include "flutter/fml/message_loop.h" #include "flutter/fml/paths.h" #include "flutter/fml/synchronization/count_down_latch.h" #include "flutter/fml/synchronization/waitable_event.h" #include "flutter/fml/thread.h" #include "flutter/runtime/dart_vm.h" #include "flutter/shell/platform/embedder/tests/embedder_assertions.h" #include "flutter/shell/platform/embedder/tests/embedder_config_builder.h" #include "flutter/shell/platform/embedder/tests/embedder_test.h" #include "flutter/testing/assertions_skia.h" #include "flutter/testing/testing.h" #include "third_party/skia/include/core/SkSurface.h" #include "third_party/tonic/converter/dart_converter.h" namespace flutter { namespace testing { using EmbedderTest = testing::EmbedderTest; TEST(EmbedderTestNoFixture, MustNotRunWithInvalidArgs) { EmbedderTestContext context; EmbedderConfigBuilder builder( context, EmbedderConfigBuilder::InitializationPreference::kNoInitialize); auto engine = builder.LaunchEngine(); ASSERT_FALSE(engine.is_valid()); } TEST_F(EmbedderTest, CanLaunchAndShutdownWithValidProjectArgs) { auto& context = GetEmbedderContext(); fml::AutoResetWaitableEvent latch; context.AddIsolateCreateCallback([&latch]() { latch.Signal(); }); EmbedderConfigBuilder builder(context); builder.SetSoftwareRendererConfig(); auto engine = builder.LaunchEngine(); ASSERT_TRUE(engine.is_valid()); // Wait for the root isolate to launch. latch.Wait(); engine.reset(); } // TODO(41999): Disabled because flaky. TEST_F(EmbedderTest, DISABLED_CanLaunchAndShutdownMultipleTimes) { EmbedderConfigBuilder builder(GetEmbedderContext()); builder.SetSoftwareRendererConfig(); for (size_t i = 0; i < 3; ++i) { auto engine = builder.LaunchEngine(); ASSERT_TRUE(engine.is_valid()); FML_LOG(INFO) << "Engine launch count: " << i + 1; } } TEST_F(EmbedderTest, CanInvokeCustomEntrypoint) { auto& context = GetEmbedderContext(); static fml::AutoResetWaitableEvent latch; Dart_NativeFunction entrypoint = [](Dart_NativeArguments args) { latch.Signal(); }; context.AddNativeCallback("SayHiFromCustomEntrypoint", entrypoint); EmbedderConfigBuilder builder(context); builder.SetSoftwareRendererConfig(); builder.SetDartEntrypoint("customEntrypoint"); auto engine = builder.LaunchEngine(); latch.Wait(); ASSERT_TRUE(engine.is_valid()); } TEST_F(EmbedderTest, CanInvokeCustomEntrypointMacro) { auto& context = GetEmbedderContext(); fml::AutoResetWaitableEvent latch1; fml::AutoResetWaitableEvent latch2; fml::AutoResetWaitableEvent latch3; // Can be defined separately. auto entry1 = [&latch1](Dart_NativeArguments args) { FML_LOG(INFO) << "In Callback 1"; latch1.Signal(); }; auto native_entry1 = CREATE_NATIVE_ENTRY(entry1); context.AddNativeCallback("SayHiFromCustomEntrypoint1", native_entry1); // Can be wrapped in in the args. auto entry2 = [&latch2](Dart_NativeArguments args) { FML_LOG(INFO) << "In Callback 2"; latch2.Signal(); }; context.AddNativeCallback("SayHiFromCustomEntrypoint2", CREATE_NATIVE_ENTRY(entry2)); // Everything can be inline. context.AddNativeCallback( "SayHiFromCustomEntrypoint3", CREATE_NATIVE_ENTRY([&latch3](Dart_NativeArguments args) { FML_LOG(INFO) << "In Callback 3"; latch3.Signal(); })); EmbedderConfigBuilder builder(context); builder.SetSoftwareRendererConfig(); builder.SetDartEntrypoint("customEntrypoint1"); auto engine = builder.LaunchEngine(); latch1.Wait(); latch2.Wait(); latch3.Wait(); ASSERT_TRUE(engine.is_valid()); } //------------------------------------------------------------------------------ /// @brief A task runner that we expect the embedder to provide but whose /// implementation is a real FML task runner. /// class EmbedderTestTaskRunner { public: using TaskExpiryCallback = std::function; EmbedderTestTaskRunner(fml::RefPtr real_task_runner, TaskExpiryCallback on_task_expired) : identifier_(++sEmbedderTaskRunnerIdentifiers), real_task_runner_(real_task_runner), on_task_expired_(on_task_expired) { FML_CHECK(real_task_runner_); FML_CHECK(on_task_expired_); task_runner_description_.struct_size = sizeof(FlutterTaskRunnerDescription); task_runner_description_.user_data = this; task_runner_description_.runs_task_on_current_thread_callback = [](void* user_data) -> bool { return reinterpret_cast(user_data) ->real_task_runner_->RunsTasksOnCurrentThread(); }; task_runner_description_.post_task_callback = [](FlutterTask task, uint64_t target_time_nanos, void* user_data) -> void { auto thiz = reinterpret_cast(user_data); auto target_time = fml::TimePoint::FromEpochDelta( fml::TimeDelta::FromNanoseconds(target_time_nanos)); auto on_task_expired = thiz->on_task_expired_; auto invoke_task = [task, on_task_expired]() { on_task_expired(task); }; auto real_task_runner = thiz->real_task_runner_; real_task_runner->PostTaskForTime(invoke_task, target_time); }; task_runner_description_.identifier = identifier_; } const FlutterTaskRunnerDescription& GetFlutterTaskRunnerDescription() { return task_runner_description_; } private: static std::atomic_size_t sEmbedderTaskRunnerIdentifiers; const size_t identifier_; fml::RefPtr real_task_runner_; TaskExpiryCallback on_task_expired_; FlutterTaskRunnerDescription task_runner_description_ = {}; FML_DISALLOW_COPY_AND_ASSIGN(EmbedderTestTaskRunner); }; std::atomic_size_t EmbedderTestTaskRunner::sEmbedderTaskRunnerIdentifiers = {}; TEST_F(EmbedderTest, CanSpecifyCustomPlatformTaskRunner) { auto& context = GetEmbedderContext(); fml::AutoResetWaitableEvent latch; // Run the test on its own thread with a message loop so that it can safely // pump its event loop while we wait for all the conditions to be checked. auto platform_task_runner = CreateNewThread("test_platform_thread"); static std::mutex engine_mutex; static bool signaled_once = false; UniqueEngine engine; EmbedderTestTaskRunner test_task_runner( platform_task_runner, [&](FlutterTask task) { std::scoped_lock lock(engine_mutex); if (!engine.is_valid()) { return; } // There may be multiple tasks posted but we only need to check // assertions once. if (signaled_once) { FlutterEngineRunTask(engine.get(), &task); return; } signaled_once = true; ASSERT_TRUE(engine.is_valid()); ASSERT_EQ(FlutterEngineRunTask(engine.get(), &task), kSuccess); latch.Signal(); }); platform_task_runner->PostTask([&]() { EmbedderConfigBuilder builder(context); const auto task_runner_description = test_task_runner.GetFlutterTaskRunnerDescription(); builder.SetSoftwareRendererConfig(); builder.SetPlatformTaskRunner(&task_runner_description); builder.SetDartEntrypoint("invokePlatformTaskRunner"); std::scoped_lock lock(engine_mutex); engine = builder.LaunchEngine(); ASSERT_TRUE(engine.is_valid()); }); // Signaled when all the assertions are checked. latch.Wait(); ASSERT_TRUE(engine.is_valid()); // Since the engine was started on its own thread, it must be killed there as // well. fml::AutoResetWaitableEvent kill_latch; platform_task_runner->PostTask(fml::MakeCopyable([&]() mutable { std::scoped_lock lock(engine_mutex); engine.reset(); // There may still be pending tasks on the platform thread that were queued // by the test_task_runner. Signal the latch after these tasks have been // consumed. platform_task_runner->PostTask([&kill_latch] { kill_latch.Signal(); }); })); kill_latch.Wait(); ASSERT_TRUE(signaled_once); signaled_once = false; } TEST(EmbedderTestNoFixture, CanGetCurrentTimeInNanoseconds) { auto point1 = fml::TimePoint::FromEpochDelta( fml::TimeDelta::FromNanoseconds(FlutterEngineGetCurrentTime())); auto point2 = fml::TimePoint::Now(); ASSERT_LT((point2 - point1), fml::TimeDelta::FromMilliseconds(1)); } TEST_F(EmbedderTest, CanReloadSystemFonts) { auto& context = GetEmbedderContext(); EmbedderConfigBuilder builder(context); builder.SetSoftwareRendererConfig(); auto engine = builder.LaunchEngine(); ASSERT_TRUE(engine.is_valid()); auto result = FlutterEngineReloadSystemFonts(engine.get()); ASSERT_EQ(result, kSuccess); } TEST_F(EmbedderTest, CanCreateOpenGLRenderingEngine) { EmbedderConfigBuilder builder(GetEmbedderContext()); builder.SetOpenGLRendererConfig(SkISize::Make(1, 1)); auto engine = builder.LaunchEngine(); ASSERT_TRUE(engine.is_valid()); } TEST_F(EmbedderTest, IsolateServiceIdSent) { auto& context = GetEmbedderContext(); fml::AutoResetWaitableEvent latch; fml::Thread thread; UniqueEngine engine; std::string isolate_message; thread.GetTaskRunner()->PostTask([&]() { EmbedderConfigBuilder builder(context); builder.SetSoftwareRendererConfig(); builder.SetDartEntrypoint("main"); builder.SetPlatformMessageCallback( [&](const FlutterPlatformMessage* message) { if (strcmp(message->channel, "flutter/isolate") == 0) { isolate_message = {reinterpret_cast(message->message), message->message_size}; latch.Signal(); } }); engine = builder.LaunchEngine(); ASSERT_TRUE(engine.is_valid()); }); // Wait for the isolate ID message and check its format. latch.Wait(); ASSERT_EQ(isolate_message.find("isolates/"), 0ul); // Since the engine was started on its own thread, it must be killed there as // well. fml::AutoResetWaitableEvent kill_latch; thread.GetTaskRunner()->PostTask( fml::MakeCopyable([&engine, &kill_latch]() mutable { engine.reset(); kill_latch.Signal(); })); kill_latch.Wait(); } //------------------------------------------------------------------------------ /// Creates a platform message response callbacks, does NOT send them, and /// immediately collects the same. /// TEST_F(EmbedderTest, CanCreateAndCollectCallbacks) { auto& context = GetEmbedderContext(); EmbedderConfigBuilder builder(context); builder.SetSoftwareRendererConfig(); builder.SetDartEntrypoint("platform_messages_response"); context.AddNativeCallback( "SignalNativeTest", CREATE_NATIVE_ENTRY([](Dart_NativeArguments args) {})); auto engine = builder.LaunchEngine(); ASSERT_TRUE(engine.is_valid()); FlutterPlatformMessageResponseHandle* response_handle = nullptr; auto callback = [](const uint8_t* data, size_t size, void* user_data) -> void {}; auto result = FlutterPlatformMessageCreateResponseHandle( engine.get(), callback, nullptr, &response_handle); ASSERT_EQ(result, kSuccess); ASSERT_NE(response_handle, nullptr); result = FlutterPlatformMessageReleaseResponseHandle(engine.get(), response_handle); ASSERT_EQ(result, kSuccess); } //------------------------------------------------------------------------------ /// Sends platform messages to Dart code than simply echoes the contents of the /// message back to the embedder. The embedder registers a native callback to /// intercept that message. /// TEST_F(EmbedderTest, PlatformMessagesCanReceiveResponse) { struct Captures { fml::AutoResetWaitableEvent latch; std::thread::id thread_id; }; Captures captures; CreateNewThread()->PostTask([&]() { captures.thread_id = std::this_thread::get_id(); auto& context = GetEmbedderContext(); EmbedderConfigBuilder builder(context); builder.SetSoftwareRendererConfig(); builder.SetDartEntrypoint("platform_messages_response"); fml::AutoResetWaitableEvent ready; context.AddNativeCallback( "SignalNativeTest", CREATE_NATIVE_ENTRY( [&ready](Dart_NativeArguments args) { ready.Signal(); })); auto engine = builder.LaunchEngine(); ASSERT_TRUE(engine.is_valid()); static std::string kMessageData = "Hello from embedder."; FlutterPlatformMessageResponseHandle* response_handle = nullptr; auto callback = [](const uint8_t* data, size_t size, void* user_data) -> void { ASSERT_EQ(size, kMessageData.size()); ASSERT_EQ(strncmp(reinterpret_cast(kMessageData.data()), reinterpret_cast(data), size), 0); auto captures = reinterpret_cast(user_data); ASSERT_EQ(captures->thread_id, std::this_thread::get_id()); captures->latch.Signal(); }; auto result = FlutterPlatformMessageCreateResponseHandle( engine.get(), callback, &captures, &response_handle); ASSERT_EQ(result, kSuccess); FlutterPlatformMessage message = {}; message.struct_size = sizeof(FlutterPlatformMessage); message.channel = "test_channel"; message.message = reinterpret_cast(kMessageData.data()); message.message_size = kMessageData.size(); message.response_handle = response_handle; ready.Wait(); result = FlutterEngineSendPlatformMessage(engine.get(), &message); ASSERT_EQ(result, kSuccess); result = FlutterPlatformMessageReleaseResponseHandle(engine.get(), response_handle); ASSERT_EQ(result, kSuccess); }); captures.latch.Wait(); } //------------------------------------------------------------------------------ /// Tests that a platform message can be sent with no response handle. Instead /// of the platform message integrity checked via a response handle, a native /// callback with the response is invoked to assert integrity. /// TEST_F(EmbedderTest, PlatformMessagesCanBeSentWithoutResponseHandles) { auto& context = GetEmbedderContext(); EmbedderConfigBuilder builder(context); builder.SetSoftwareRendererConfig(); builder.SetDartEntrypoint("platform_messages_no_response"); const std::string message_data = "Hello but don't call me back."; fml::AutoResetWaitableEvent ready, message; context.AddNativeCallback( "SignalNativeTest", CREATE_NATIVE_ENTRY( [&ready](Dart_NativeArguments args) { ready.Signal(); })); context.AddNativeCallback( "SignalNativeMessage", CREATE_NATIVE_ENTRY( ([&message, &message_data](Dart_NativeArguments args) { auto received_message = tonic::DartConverter::FromDart( Dart_GetNativeArgument(args, 0)); ASSERT_EQ(received_message, message_data); message.Signal(); }))); auto engine = builder.LaunchEngine(); ASSERT_TRUE(engine.is_valid()); ready.Wait(); FlutterPlatformMessage platform_message = {}; platform_message.struct_size = sizeof(FlutterPlatformMessage); platform_message.channel = "test_channel"; platform_message.message = reinterpret_cast(message_data.data()); platform_message.message_size = message_data.size(); platform_message.response_handle = nullptr; // No response needed. auto result = FlutterEngineSendPlatformMessage(engine.get(), &platform_message); ASSERT_EQ(result, kSuccess); message.Wait(); } //------------------------------------------------------------------------------ /// Tests that a null platform message can be sent. /// TEST_F(EmbedderTest, NullPlatformMessagesCanBeSent) { auto& context = GetEmbedderContext(); EmbedderConfigBuilder builder(context); builder.SetSoftwareRendererConfig(); builder.SetDartEntrypoint("null_platform_messages"); fml::AutoResetWaitableEvent ready, message; context.AddNativeCallback( "SignalNativeTest", CREATE_NATIVE_ENTRY( [&ready](Dart_NativeArguments args) { ready.Signal(); })); context.AddNativeCallback( "SignalNativeMessage", CREATE_NATIVE_ENTRY(([&message](Dart_NativeArguments args) { auto received_message = tonic::DartConverter::FromDart( Dart_GetNativeArgument(args, 0)); ASSERT_EQ("true", received_message); message.Signal(); }))); auto engine = builder.LaunchEngine(); ASSERT_TRUE(engine.is_valid()); ready.Wait(); FlutterPlatformMessage platform_message = {}; platform_message.struct_size = sizeof(FlutterPlatformMessage); platform_message.channel = "test_channel"; platform_message.message = nullptr; platform_message.message_size = 0; platform_message.response_handle = nullptr; // No response needed. auto result = FlutterEngineSendPlatformMessage(engine.get(), &platform_message); ASSERT_EQ(result, kSuccess); message.Wait(); } //------------------------------------------------------------------------------ /// Tests that a null platform message cannot be send if the message_size /// isn't equals to 0. /// TEST_F(EmbedderTest, InvalidPlatformMessages) { auto& context = GetEmbedderContext(); EmbedderConfigBuilder builder(context); builder.SetSoftwareRendererConfig(); auto engine = builder.LaunchEngine(); ASSERT_TRUE(engine.is_valid()); FlutterPlatformMessage platform_message = {}; platform_message.struct_size = sizeof(FlutterPlatformMessage); platform_message.channel = "test_channel"; platform_message.message = nullptr; platform_message.message_size = 1; platform_message.response_handle = nullptr; // No response needed. auto result = FlutterEngineSendPlatformMessage(engine.get(), &platform_message); ASSERT_EQ(result, kInvalidArguments); } //------------------------------------------------------------------------------ /// Asserts behavior of FlutterProjectArgs::shutdown_dart_vm_when_done (which is /// set to true by default in these unit-tests). /// TEST_F(EmbedderTest, VMShutsDownWhenNoEnginesInProcess) { auto& context = GetEmbedderContext(); EmbedderConfigBuilder builder(context); builder.SetSoftwareRendererConfig(); const auto launch_count = DartVM::GetVMLaunchCount(); { auto engine = builder.LaunchEngine(); ASSERT_EQ(launch_count + 1u, DartVM::GetVMLaunchCount()); } { auto engine = builder.LaunchEngine(); ASSERT_EQ(launch_count + 2u, DartVM::GetVMLaunchCount()); } } //------------------------------------------------------------------------------ /// These snapshots may be materialized from symbols and the size field may not /// be relevant. Since this information is redundant, engine launch should not /// be gated on a non-zero buffer size. /// TEST_F(EmbedderTest, VMAndIsolateSnapshotSizesAreRedundantInAOTMode) { if (!DartVM::IsRunningPrecompiledCode()) { GTEST_SKIP(); return; } auto& context = GetEmbedderContext(); EmbedderConfigBuilder builder(context); builder.SetSoftwareRendererConfig(); // The fixture sets this up correctly. Intentionally mess up the args. builder.GetProjectArgs().vm_snapshot_data_size = 0; builder.GetProjectArgs().vm_snapshot_instructions_size = 0; builder.GetProjectArgs().isolate_snapshot_data_size = 0; builder.GetProjectArgs().isolate_snapshot_instructions_size = 0; auto engine = builder.LaunchEngine(); ASSERT_TRUE(engine.is_valid()); } //------------------------------------------------------------------------------ /// If an incorrectly configured compositor is set on the engine, the engine /// must fail to launch instead of failing to render a frame at a later point in /// time. /// TEST_F(EmbedderTest, MustPreventEngineLaunchWhenRequiredCompositorArgsAreAbsent) { auto& context = GetEmbedderContext(); EmbedderConfigBuilder builder(context); builder.SetOpenGLRendererConfig(SkISize::Make(1, 1)); builder.SetCompositor(); builder.GetCompositor().create_backing_store_callback = nullptr; builder.GetCompositor().collect_backing_store_callback = nullptr; builder.GetCompositor().present_layers_callback = nullptr; auto engine = builder.LaunchEngine(); ASSERT_FALSE(engine.is_valid()); } //------------------------------------------------------------------------------ /// Must be able to render to a custom compositor whose render targets are fully /// complete OpenGL textures. /// TEST_F(EmbedderTest, CompositorMustBeAbleToRenderToOpenGLFramebuffer) { auto& context = GetEmbedderContext(); EmbedderConfigBuilder builder(context); builder.SetOpenGLRendererConfig(SkISize::Make(800, 600)); builder.SetCompositor(); builder.SetDartEntrypoint("can_composite_platform_views"); context.GetCompositor().SetRenderTargetType( EmbedderTestCompositor::RenderTargetType::kOpenGLFramebuffer); fml::CountDownLatch latch(3); context.GetCompositor().SetNextPresentCallback( [&](const FlutterLayer** layers, size_t layers_count) { ASSERT_EQ(layers_count, 3u); { FlutterBackingStore backing_store = *layers[0]->backing_store; backing_store.struct_size = sizeof(backing_store); backing_store.type = kFlutterBackingStoreTypeOpenGL; backing_store.did_update = true; backing_store.open_gl.type = kFlutterOpenGLTargetTypeFramebuffer; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypeBackingStore; layer.backing_store = &backing_store; layer.size = FlutterSizeMake(800.0, 600.0); layer.offset = FlutterPointMake(0, 0); ASSERT_EQ(*layers[0], layer); } { FlutterPlatformView platform_view = {}; platform_view.struct_size = sizeof(platform_view); platform_view.identifier = 42; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypePlatformView; layer.platform_view = &platform_view; layer.size = FlutterSizeMake(123.0, 456.0); layer.offset = FlutterPointMake(1.0, 2.0); ASSERT_EQ(*layers[1], layer); } { FlutterBackingStore backing_store = *layers[2]->backing_store; backing_store.struct_size = sizeof(backing_store); backing_store.type = kFlutterBackingStoreTypeOpenGL; backing_store.did_update = true; backing_store.open_gl.type = kFlutterOpenGLTargetTypeFramebuffer; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypeBackingStore; layer.backing_store = &backing_store; layer.size = FlutterSizeMake(800.0, 600.0); layer.offset = FlutterPointMake(0.0, 0.0); ASSERT_EQ(*layers[2], layer); } latch.CountDown(); }); context.AddNativeCallback( "SignalNativeTest", CREATE_NATIVE_ENTRY( [&latch](Dart_NativeArguments args) { latch.CountDown(); })); auto engine = builder.LaunchEngine(); // Send a window metrics events so frames may be scheduled. FlutterWindowMetricsEvent event = {}; event.struct_size = sizeof(event); event.width = 800; event.height = 600; event.pixel_ratio = 1.0; ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kSuccess); ASSERT_TRUE(engine.is_valid()); latch.Wait(); } //------------------------------------------------------------------------------ /// Layers in a hierarchy containing a platform view should not be cached. The /// other layers in the hierarchy should be, however. TEST_F(EmbedderTest, RasterCacheDisabledWithPlatformViews) { auto& context = GetEmbedderContext(); EmbedderConfigBuilder builder(context); builder.SetOpenGLRendererConfig(SkISize::Make(800, 600)); builder.SetCompositor(); builder.SetDartEntrypoint("can_composite_platform_views_with_opacity"); context.GetCompositor().SetRenderTargetType( EmbedderTestCompositor::RenderTargetType::kOpenGLFramebuffer); fml::CountDownLatch setup(3); fml::CountDownLatch verify(1); context.GetCompositor().SetNextPresentCallback( [&](const FlutterLayer** layers, size_t layers_count) { ASSERT_EQ(layers_count, 3u); { FlutterBackingStore backing_store = *layers[0]->backing_store; backing_store.struct_size = sizeof(backing_store); backing_store.type = kFlutterBackingStoreTypeOpenGL; backing_store.did_update = true; backing_store.open_gl.type = kFlutterOpenGLTargetTypeFramebuffer; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypeBackingStore; layer.backing_store = &backing_store; layer.size = FlutterSizeMake(800.0, 600.0); layer.offset = FlutterPointMake(0, 0); ASSERT_EQ(*layers[0], layer); } { FlutterPlatformView platform_view = {}; platform_view.struct_size = sizeof(platform_view); platform_view.identifier = 42; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypePlatformView; layer.platform_view = &platform_view; layer.size = FlutterSizeMake(123.0, 456.0); layer.offset = FlutterPointMake(1.0, 2.0); ASSERT_EQ(*layers[1], layer); } { FlutterBackingStore backing_store = *layers[2]->backing_store; backing_store.struct_size = sizeof(backing_store); backing_store.type = kFlutterBackingStoreTypeOpenGL; backing_store.did_update = true; backing_store.open_gl.type = kFlutterOpenGLTargetTypeFramebuffer; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypeBackingStore; layer.backing_store = &backing_store; layer.size = FlutterSizeMake(800.0, 600.0); layer.offset = FlutterPointMake(0.0, 0.0); ASSERT_EQ(*layers[2], layer); } setup.CountDown(); }); context.AddNativeCallback( "SignalNativeTest", CREATE_NATIVE_ENTRY( [&setup](Dart_NativeArguments args) { setup.CountDown(); })); UniqueEngine engine = builder.LaunchEngine(); // Send a window metrics events so frames may be scheduled. FlutterWindowMetricsEvent event = {}; event.struct_size = sizeof(event); event.width = 800; event.height = 600; event.pixel_ratio = 1.0; ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kSuccess); ASSERT_TRUE(engine.is_valid()); setup.Wait(); const flutter::Shell& shell = ToEmbedderEngine(engine.get())->GetShell(); shell.GetTaskRunners().GetGPUTaskRunner()->PostTask([&] { const flutter::RasterCache& raster_cache = shell.GetRasterizer()->compositor_context()->raster_cache(); // 3 layers total, but one of them had the platform view. So the cache // should only have 2 entries. ASSERT_EQ(raster_cache.GetCachedEntriesCount(), 2u); verify.CountDown(); }); verify.Wait(); } //------------------------------------------------------------------------------ /// The RasterCache should normally be enabled. /// TEST_F(EmbedderTest, RasterCacheEnabled) { auto& context = GetEmbedderContext(); EmbedderConfigBuilder builder(context); builder.SetOpenGLRendererConfig(SkISize::Make(800, 600)); builder.SetCompositor(); builder.SetDartEntrypoint("can_composite_with_opacity"); context.GetCompositor().SetRenderTargetType( EmbedderTestCompositor::RenderTargetType::kOpenGLFramebuffer); fml::CountDownLatch setup(3); fml::CountDownLatch verify(1); context.GetCompositor().SetNextPresentCallback( [&](const FlutterLayer** layers, size_t layers_count) { ASSERT_EQ(layers_count, 1u); { FlutterBackingStore backing_store = *layers[0]->backing_store; backing_store.struct_size = sizeof(backing_store); backing_store.type = kFlutterBackingStoreTypeOpenGL; backing_store.did_update = true; backing_store.open_gl.type = kFlutterOpenGLTargetTypeFramebuffer; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypeBackingStore; layer.backing_store = &backing_store; layer.size = FlutterSizeMake(800.0, 600.0); layer.offset = FlutterPointMake(0, 0); ASSERT_EQ(*layers[0], layer); } setup.CountDown(); }); context.AddNativeCallback( "SignalNativeTest", CREATE_NATIVE_ENTRY( [&setup](Dart_NativeArguments args) { setup.CountDown(); })); UniqueEngine engine = builder.LaunchEngine(); // Send a window metrics events so frames may be scheduled. FlutterWindowMetricsEvent event = {}; event.struct_size = sizeof(event); event.width = 800; event.height = 600; event.pixel_ratio = 1.0; ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kSuccess); ASSERT_TRUE(engine.is_valid()); setup.Wait(); const flutter::Shell& shell = ToEmbedderEngine(engine.get())->GetShell(); shell.GetTaskRunners().GetGPUTaskRunner()->PostTask([&] { const flutter::RasterCache& raster_cache = shell.GetRasterizer()->compositor_context()->raster_cache(); ASSERT_EQ(raster_cache.GetCachedEntriesCount(), 1u); verify.CountDown(); }); verify.Wait(); } //------------------------------------------------------------------------------ /// Must be able to render using a custom compositor whose render targets for /// the individual layers are OpenGL textures. /// TEST_F(EmbedderTest, CompositorMustBeAbleToRenderToOpenGLTexture) { auto& context = GetEmbedderContext(); EmbedderConfigBuilder builder(context); builder.SetOpenGLRendererConfig(SkISize::Make(800, 600)); builder.SetCompositor(); builder.SetDartEntrypoint("can_composite_platform_views"); context.GetCompositor().SetRenderTargetType( EmbedderTestCompositor::RenderTargetType::kOpenGLTexture); fml::CountDownLatch latch(3); context.GetCompositor().SetNextPresentCallback( [&](const FlutterLayer** layers, size_t layers_count) { ASSERT_EQ(layers_count, 3u); { FlutterBackingStore backing_store = *layers[0]->backing_store; backing_store.struct_size = sizeof(backing_store); backing_store.type = kFlutterBackingStoreTypeOpenGL; backing_store.did_update = true; backing_store.open_gl.type = kFlutterOpenGLTargetTypeTexture; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypeBackingStore; layer.backing_store = &backing_store; layer.size = FlutterSizeMake(800.0, 600.0); layer.offset = FlutterPointMake(0, 0); ASSERT_EQ(*layers[0], layer); } { FlutterPlatformView platform_view = {}; platform_view.struct_size = sizeof(platform_view); platform_view.identifier = 42; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypePlatformView; layer.platform_view = &platform_view; layer.size = FlutterSizeMake(123.0, 456.0); layer.offset = FlutterPointMake(1.0, 2.0); ASSERT_EQ(*layers[1], layer); } { FlutterBackingStore backing_store = *layers[2]->backing_store; backing_store.struct_size = sizeof(backing_store); backing_store.type = kFlutterBackingStoreTypeOpenGL; backing_store.did_update = true; backing_store.open_gl.type = kFlutterOpenGLTargetTypeTexture; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypeBackingStore; layer.backing_store = &backing_store; layer.size = FlutterSizeMake(800.0, 600.0); layer.offset = FlutterPointMake(0.0, 0.0); ASSERT_EQ(*layers[2], layer); } latch.CountDown(); }); context.AddNativeCallback( "SignalNativeTest", CREATE_NATIVE_ENTRY( [&latch](Dart_NativeArguments args) { latch.CountDown(); })); auto engine = builder.LaunchEngine(); // Send a window metrics events so frames may be scheduled. FlutterWindowMetricsEvent event = {}; event.struct_size = sizeof(event); event.width = 800; event.height = 600; event.pixel_ratio = 1.0; ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kSuccess); ASSERT_TRUE(engine.is_valid()); latch.Wait(); } //------------------------------------------------------------------------------ /// Must be able to render using a custom compositor whose render target for the /// individual layers are software buffers. /// TEST_F(EmbedderTest, CompositorMustBeAbleToRenderToSoftwareBuffer) { auto& context = GetEmbedderContext(); EmbedderConfigBuilder builder(context); builder.SetOpenGLRendererConfig(SkISize::Make(800, 600)); builder.SetCompositor(); builder.SetDartEntrypoint("can_composite_platform_views"); context.GetCompositor().SetRenderTargetType( EmbedderTestCompositor::RenderTargetType::kSoftwareBuffer); fml::CountDownLatch latch(3); context.GetCompositor().SetNextPresentCallback( [&](const FlutterLayer** layers, size_t layers_count) { ASSERT_EQ(layers_count, 3u); { FlutterBackingStore backing_store = *layers[0]->backing_store; backing_store.struct_size = sizeof(backing_store); backing_store.type = kFlutterBackingStoreTypeSoftware; backing_store.did_update = true; ASSERT_FLOAT_EQ( backing_store.software.row_bytes * backing_store.software.height, 800 * 4 * 600.0); FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypeBackingStore; layer.backing_store = &backing_store; layer.size = FlutterSizeMake(800.0, 600.0); layer.offset = FlutterPointMake(0, 0); ASSERT_EQ(*layers[0], layer); } { FlutterPlatformView platform_view = {}; platform_view.struct_size = sizeof(platform_view); platform_view.identifier = 42; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypePlatformView; layer.platform_view = &platform_view; layer.size = FlutterSizeMake(123.0, 456.0); layer.offset = FlutterPointMake(1.0, 2.0); ASSERT_EQ(*layers[1], layer); } { FlutterBackingStore backing_store = *layers[2]->backing_store; backing_store.struct_size = sizeof(backing_store); backing_store.type = kFlutterBackingStoreTypeSoftware; backing_store.did_update = true; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypeBackingStore; layer.backing_store = &backing_store; layer.size = FlutterSizeMake(800.0, 600.0); layer.offset = FlutterPointMake(0.0, 0.0); ASSERT_EQ(*layers[2], layer); } latch.CountDown(); }); context.AddNativeCallback( "SignalNativeTest", CREATE_NATIVE_ENTRY( [&latch](Dart_NativeArguments args) { latch.CountDown(); })); auto engine = builder.LaunchEngine(); // Send a window metrics events so frames may be scheduled. FlutterWindowMetricsEvent event = {}; event.struct_size = sizeof(event); event.width = 800; event.height = 600; event.pixel_ratio = 1.0; ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kSuccess); ASSERT_TRUE(engine.is_valid()); latch.Wait(); } static sk_sp CreateRenderSurface(const FlutterLayer& layer, GrContext* context) { const auto image_info = SkImageInfo::MakeN32Premul(layer.size.width, layer.size.height); auto surface = context ? SkSurface::MakeRenderTarget( context, // context SkBudgeted::kNo, // budgeted image_info, // image info 1, // sample count kTopLeft_GrSurfaceOrigin, // surface origin nullptr, // surface properties false // mipmaps ) : SkSurface::MakeRaster(image_info); FML_CHECK(surface != nullptr); return surface; } static bool RasterImagesAreSame(sk_sp a, sk_sp b) { FML_CHECK(!a->isTextureBacked()); FML_CHECK(!b->isTextureBacked()); if (!a || !b) { return false; } SkPixmap pixmapA; SkPixmap pixmapB; if (!a->peekPixels(&pixmapA)) { FML_LOG(ERROR) << "Could not peek pixels of image A."; return false; } if (!b->peekPixels(&pixmapB)) { FML_LOG(ERROR) << "Could not peek pixels of image B."; return false; } const auto sizeA = pixmapA.rowBytes() * pixmapA.height(); const auto sizeB = pixmapB.rowBytes() * pixmapB.height(); if (sizeA != sizeB) { FML_LOG(ERROR) << "Pixmap sizes were inconsistent."; return false; } return ::memcmp(pixmapA.addr(), pixmapB.addr(), sizeA) == 0; } static bool WriteImageToDisk(const fml::UniqueFD& directory, const std::string& name, sk_sp image) { if (!image) { return false; } auto data = image->encodeToData(SkEncodedImageFormat::kPNG, 100); if (!data) { return false; } fml::NonOwnedMapping mapping(static_cast(data->data()), data->size()); return WriteAtomically(directory, name.c_str(), mapping); } static bool ImageMatchesFixture(const std::string& fixture_file_name, sk_sp scene_image) { fml::FileMapping fixture_image_mapping(OpenFixture(fixture_file_name)); FML_CHECK(fixture_image_mapping.GetSize() != 0u) << "Could not find fixture: " << fixture_file_name; auto encoded_image = SkData::MakeWithoutCopy( fixture_image_mapping.GetMapping(), fixture_image_mapping.GetSize()); auto fixture_image = SkImage::MakeFromEncoded(std::move(encoded_image))->makeRasterImage(); FML_CHECK(fixture_image) << "Could not create image from fixture: " << fixture_file_name; auto scene_image_subset = scene_image->makeSubset( SkIRect::MakeWH(fixture_image->width(), fixture_image->height())); FML_CHECK(scene_image_subset) << "Could not create image subset for fixture comparison: " << scene_image_subset; const auto images_are_same = RasterImagesAreSame(scene_image_subset, fixture_image); // If the images are not the same, this predicate is going to indicate test // failure. Dump both the actual image and the expectation to disk to the // test author can figure out what went wrong. if (!images_are_same) { const auto fixtures_path = GetFixturesPath(); const auto actual_file_name = "actual_" + fixture_file_name; const auto expect_file_name = "expectation_" + fixture_file_name; auto fixtures_fd = OpenFixturesDirectory(); FML_CHECK( WriteImageToDisk(fixtures_fd, actual_file_name, scene_image_subset)) << "Could not write file to disk: " << actual_file_name; FML_CHECK(WriteImageToDisk(fixtures_fd, expect_file_name, fixture_image)) << "Could not write file to disk: " << expect_file_name; FML_LOG(ERROR) << "Image did not match expectation." << std::endl << "Expected:" << fml::paths::JoinPaths({fixtures_path, expect_file_name}) << std::endl << "Got:" << fml::paths::JoinPaths({fixtures_path, actual_file_name}) << std::endl; } return images_are_same; } //------------------------------------------------------------------------------ /// Test the layer structure and pixels rendered when using a custom compositor. /// TEST_F(EmbedderTest, CompositorMustBeAbleToRenderKnownScene) { auto& context = GetEmbedderContext(); EmbedderConfigBuilder builder(context); builder.SetOpenGLRendererConfig(SkISize::Make(800, 600)); builder.SetCompositor(); builder.SetDartEntrypoint("can_composite_platform_views_with_known_scene"); context.GetCompositor().SetRenderTargetType( EmbedderTestCompositor::RenderTargetType::kOpenGLTexture); fml::CountDownLatch latch(6); sk_sp scene_image; context.SetNextSceneCallback([&](sk_sp scene) { scene_image = std::move(scene); latch.CountDown(); }); context.GetCompositor().SetNextPresentCallback( [&](const FlutterLayer** layers, size_t layers_count) { ASSERT_EQ(layers_count, 5u); // Layer Root { FlutterBackingStore backing_store = *layers[0]->backing_store; backing_store.type = kFlutterBackingStoreTypeOpenGL; backing_store.did_update = true; backing_store.open_gl.type = kFlutterOpenGLTargetTypeTexture; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypeBackingStore; layer.backing_store = &backing_store; layer.size = FlutterSizeMake(800.0, 600.0); layer.offset = FlutterPointMake(0.0, 0.0); ASSERT_EQ(*layers[0], layer); } // Layer 1 { FlutterPlatformView platform_view = {}; platform_view.struct_size = sizeof(platform_view); platform_view.identifier = 1; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypePlatformView; layer.platform_view = &platform_view; layer.size = FlutterSizeMake(50.0, 150.0); layer.offset = FlutterPointMake(20.0, 20.0); ASSERT_EQ(*layers[1], layer); } // Layer 2 { FlutterBackingStore backing_store = *layers[2]->backing_store; backing_store.type = kFlutterBackingStoreTypeOpenGL; backing_store.did_update = true; backing_store.open_gl.type = kFlutterOpenGLTargetTypeTexture; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypeBackingStore; layer.backing_store = &backing_store; layer.size = FlutterSizeMake(800.0, 600.0); layer.offset = FlutterPointMake(0.0, 0.0); ASSERT_EQ(*layers[2], layer); } // Layer 3 { FlutterPlatformView platform_view = {}; platform_view.struct_size = sizeof(platform_view); platform_view.identifier = 2; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypePlatformView; layer.platform_view = &platform_view; layer.size = FlutterSizeMake(50.0, 150.0); layer.offset = FlutterPointMake(40.0, 40.0); ASSERT_EQ(*layers[3], layer); } // Layer 4 { FlutterBackingStore backing_store = *layers[4]->backing_store; backing_store.type = kFlutterBackingStoreTypeOpenGL; backing_store.did_update = true; backing_store.open_gl.type = kFlutterOpenGLTargetTypeTexture; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypeBackingStore; layer.backing_store = &backing_store; layer.size = FlutterSizeMake(800.0, 600.0); layer.offset = FlutterPointMake(0.0, 0.0); ASSERT_EQ(*layers[4], layer); } latch.CountDown(); }); context.GetCompositor().SetPlatformViewRendererCallback( [&](const FlutterLayer& layer, GrContext* context) -> sk_sp { auto surface = CreateRenderSurface(layer, context); auto canvas = surface->getCanvas(); FML_CHECK(canvas != nullptr); switch (layer.platform_view->identifier) { case 1: { SkPaint paint; // See dart test for total order. paint.setColor(SK_ColorGREEN); paint.setAlpha(127); const auto& rect = SkRect::MakeWH(layer.size.width, layer.size.height); canvas->drawRect(rect, paint); latch.CountDown(); } break; case 2: { SkPaint paint; // See dart test for total order. paint.setColor(SK_ColorMAGENTA); paint.setAlpha(127); const auto& rect = SkRect::MakeWH(layer.size.width, layer.size.height); canvas->drawRect(rect, paint); latch.CountDown(); } break; default: // Asked to render an unknown platform view. FML_CHECK(false) << "Test was asked to composite an unknown platform view."; } return surface->makeImageSnapshot(); }); context.AddNativeCallback( "SignalNativeTest", CREATE_NATIVE_ENTRY( [&latch](Dart_NativeArguments args) { latch.CountDown(); })); auto engine = builder.LaunchEngine(); // Send a window metrics events so frames may be scheduled. FlutterWindowMetricsEvent event = {}; event.struct_size = sizeof(event); event.width = 800; event.height = 600; event.pixel_ratio = 1.0; ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kSuccess); ASSERT_TRUE(engine.is_valid()); latch.Wait(); ASSERT_TRUE(ImageMatchesFixture("compositor.png", scene_image)); // There should no present calls on the root surface. ASSERT_EQ(context.GetSoftwareSurfacePresentCount(), 0u); ASSERT_EQ(context.GetGLSurfacePresentCount(), 0u); } //------------------------------------------------------------------------------ /// Test the layer structure and pixels rendered when using a custom software /// compositor. /// TEST_F(EmbedderTest, CompositorMustBeAbleToRenderKnownSceneWithSoftwareCompositor) { auto& context = GetEmbedderContext(); EmbedderConfigBuilder builder(context); builder.SetSoftwareRendererConfig(SkISize::Make(800, 600)); builder.SetCompositor(); builder.SetDartEntrypoint("can_composite_platform_views_with_known_scene"); context.GetCompositor().SetRenderTargetType( EmbedderTestCompositor::RenderTargetType::kSoftwareBuffer); fml::CountDownLatch latch(6); sk_sp scene_image; context.SetNextSceneCallback([&](sk_sp scene) { scene_image = std::move(scene); latch.CountDown(); }); context.GetCompositor().SetNextPresentCallback( [&](const FlutterLayer** layers, size_t layers_count) { ASSERT_EQ(layers_count, 5u); // Layer Root { FlutterBackingStore backing_store = *layers[0]->backing_store; backing_store.type = kFlutterBackingStoreTypeSoftware; backing_store.did_update = true; backing_store.software.height = 600; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypeBackingStore; layer.backing_store = &backing_store; layer.size = FlutterSizeMake(800.0, 600.0); layer.offset = FlutterPointMake(0.0, 0.0); ASSERT_EQ(*layers[0], layer); } // Layer 1 { FlutterPlatformView platform_view = {}; platform_view.struct_size = sizeof(platform_view); platform_view.identifier = 1; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypePlatformView; layer.platform_view = &platform_view; layer.size = FlutterSizeMake(50.0, 150.0); layer.offset = FlutterPointMake(20.0, 20.0); ASSERT_EQ(*layers[1], layer); } // Layer 2 { FlutterBackingStore backing_store = *layers[2]->backing_store; backing_store.type = kFlutterBackingStoreTypeSoftware; backing_store.did_update = true; backing_store.software.height = 600; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypeBackingStore; layer.backing_store = &backing_store; layer.size = FlutterSizeMake(800.0, 600.0); layer.offset = FlutterPointMake(0.0, 0.0); ASSERT_EQ(*layers[2], layer); } // Layer 3 { FlutterPlatformView platform_view = {}; platform_view.struct_size = sizeof(platform_view); platform_view.identifier = 2; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypePlatformView; layer.platform_view = &platform_view; layer.size = FlutterSizeMake(50.0, 150.0); layer.offset = FlutterPointMake(40.0, 40.0); ASSERT_EQ(*layers[3], layer); } // Layer 4 { FlutterBackingStore backing_store = *layers[4]->backing_store; backing_store.type = kFlutterBackingStoreTypeSoftware; backing_store.did_update = true; backing_store.software.height = 600; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypeBackingStore; layer.backing_store = &backing_store; layer.size = FlutterSizeMake(800.0, 600.0); layer.offset = FlutterPointMake(0.0, 0.0); ASSERT_EQ(*layers[4], layer); } latch.CountDown(); }); context.GetCompositor().SetPlatformViewRendererCallback( [&](const FlutterLayer& layer, GrContext * /* don't use because software compositor */) -> sk_sp { auto surface = CreateRenderSurface( layer, nullptr /* null because software compositor */); auto canvas = surface->getCanvas(); FML_CHECK(canvas != nullptr); switch (layer.platform_view->identifier) { case 1: { SkPaint paint; // See dart test for total order. paint.setColor(SK_ColorGREEN); paint.setAlpha(127); const auto& rect = SkRect::MakeWH(layer.size.width, layer.size.height); canvas->drawRect(rect, paint); latch.CountDown(); } break; case 2: { SkPaint paint; // See dart test for total order. paint.setColor(SK_ColorMAGENTA); paint.setAlpha(127); const auto& rect = SkRect::MakeWH(layer.size.width, layer.size.height); canvas->drawRect(rect, paint); latch.CountDown(); } break; default: // Asked to render an unknown platform view. FML_CHECK(false) << "Test was asked to composite an unknown platform view."; } return surface->makeImageSnapshot(); }); context.AddNativeCallback( "SignalNativeTest", CREATE_NATIVE_ENTRY( [&latch](Dart_NativeArguments args) { latch.CountDown(); })); auto engine = builder.LaunchEngine(); // Send a window metrics events so frames may be scheduled. FlutterWindowMetricsEvent event = {}; event.struct_size = sizeof(event); event.width = 800; event.height = 600; event.pixel_ratio = 1.0; ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kSuccess); ASSERT_TRUE(engine.is_valid()); latch.Wait(); ASSERT_TRUE(ImageMatchesFixture("compositor_software.png", scene_image)); // There should no present calls on the root surface. ASSERT_EQ(context.GetSoftwareSurfacePresentCount(), 0u); ASSERT_EQ(context.GetGLSurfacePresentCount(), 0u); } //------------------------------------------------------------------------------ /// Custom compositor must play nicely with a custom task runner. The GPU thread /// merging mechanism must not interfere with the custom compositor. /// TEST_F(EmbedderTest, CustomCompositorMustWorkWithCustomTaskRunner) { auto& context = GetEmbedderContext(); EmbedderConfigBuilder builder(context); builder.SetOpenGLRendererConfig(SkISize::Make(800, 600)); builder.SetCompositor(); builder.SetDartEntrypoint("can_composite_platform_views"); auto platform_task_runner = CreateNewThread("test_platform_thread"); static std::mutex engine_mutex; UniqueEngine engine; fml::AutoResetWaitableEvent sync_latch; EmbedderTestTaskRunner test_task_runner( platform_task_runner, [&](FlutterTask task) { std::scoped_lock lock(engine_mutex); if (!engine.is_valid()) { return; } ASSERT_EQ(FlutterEngineRunTask(engine.get(), &task), kSuccess); }); context.GetCompositor().SetRenderTargetType( EmbedderTestCompositor::RenderTargetType::kOpenGLTexture); fml::CountDownLatch latch(3); context.GetCompositor().SetNextPresentCallback( [&](const FlutterLayer** layers, size_t layers_count) { ASSERT_EQ(layers_count, 3u); { FlutterBackingStore backing_store = *layers[0]->backing_store; backing_store.struct_size = sizeof(backing_store); backing_store.type = kFlutterBackingStoreTypeOpenGL; backing_store.did_update = true; backing_store.open_gl.type = kFlutterOpenGLTargetTypeTexture; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypeBackingStore; layer.backing_store = &backing_store; layer.size = FlutterSizeMake(800.0, 600.0); layer.offset = FlutterPointMake(0, 0); ASSERT_EQ(*layers[0], layer); } { FlutterPlatformView platform_view = {}; platform_view.struct_size = sizeof(platform_view); platform_view.identifier = 42; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypePlatformView; layer.platform_view = &platform_view; layer.size = FlutterSizeMake(123.0, 456.0); layer.offset = FlutterPointMake(1.0, 2.0); ASSERT_EQ(*layers[1], layer); } { FlutterBackingStore backing_store = *layers[2]->backing_store; backing_store.struct_size = sizeof(backing_store); backing_store.type = kFlutterBackingStoreTypeOpenGL; backing_store.did_update = true; backing_store.open_gl.type = kFlutterOpenGLTargetTypeTexture; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypeBackingStore; layer.backing_store = &backing_store; layer.size = FlutterSizeMake(800.0, 600.0); layer.offset = FlutterPointMake(0.0, 0.0); ASSERT_EQ(*layers[2], layer); } latch.CountDown(); }); const auto task_runner_description = test_task_runner.GetFlutterTaskRunnerDescription(); builder.SetPlatformTaskRunner(&task_runner_description); context.AddNativeCallback( "SignalNativeTest", CREATE_NATIVE_ENTRY( [&latch](Dart_NativeArguments args) { latch.CountDown(); })); platform_task_runner->PostTask([&]() { std::scoped_lock lock(engine_mutex); engine = builder.LaunchEngine(); ASSERT_TRUE(engine.is_valid()); // Send a window metrics events so frames may be scheduled. FlutterWindowMetricsEvent event = {}; event.struct_size = sizeof(event); event.width = 800; event.height = 600; event.pixel_ratio = 1.0; ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kSuccess); ASSERT_TRUE(engine.is_valid()); sync_latch.Signal(); }); sync_latch.Wait(); latch.Wait(); platform_task_runner->PostTask([&]() { std::scoped_lock lock(engine_mutex); engine.reset(); sync_latch.Signal(); }); sync_latch.Wait(); } //------------------------------------------------------------------------------ /// Test the layer structure and pixels rendered when using a custom compositor /// and a single layer. /// TEST_F(EmbedderTest, CompositorMustBeAbleToRenderWithRootLayerOnly) { auto& context = GetEmbedderContext(); EmbedderConfigBuilder builder(context); builder.SetOpenGLRendererConfig(SkISize::Make(800, 600)); builder.SetCompositor(); builder.SetDartEntrypoint( "can_composite_platform_views_with_root_layer_only"); context.GetCompositor().SetRenderTargetType( EmbedderTestCompositor::RenderTargetType::kOpenGLTexture); fml::CountDownLatch latch(4); sk_sp scene_image; context.SetNextSceneCallback([&](sk_sp scene) { scene_image = std::move(scene); latch.CountDown(); }); context.GetCompositor().SetNextPresentCallback( [&](const FlutterLayer** layers, size_t layers_count) { ASSERT_EQ(layers_count, 1u); // Layer Root { FlutterBackingStore backing_store = *layers[0]->backing_store; backing_store.type = kFlutterBackingStoreTypeOpenGL; backing_store.did_update = true; backing_store.open_gl.type = kFlutterOpenGLTargetTypeTexture; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypeBackingStore; layer.backing_store = &backing_store; layer.size = FlutterSizeMake(800.0, 600.0); layer.offset = FlutterPointMake(0.0, 0.0); ASSERT_EQ(*layers[0], layer); } latch.CountDown(); }); context.AddNativeCallback( "SignalNativeTest", CREATE_NATIVE_ENTRY( [&latch](Dart_NativeArguments args) { latch.CountDown(); })); auto engine = builder.LaunchEngine(); // Send a window metrics events so frames may be scheduled. FlutterWindowMetricsEvent event = {}; event.struct_size = sizeof(event); event.width = 800; event.height = 600; event.pixel_ratio = 1.0; ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kSuccess); ASSERT_TRUE(engine.is_valid()); latch.Wait(); ASSERT_TRUE( ImageMatchesFixture("compositor_with_root_layer_only.png", scene_image)); } //------------------------------------------------------------------------------ /// Test the layer structure and pixels rendered when using a custom compositor /// and ensure that a redundant layer is not added. /// TEST_F(EmbedderTest, CompositorMustBeAbleToRenderWithPlatformLayerOnBottom) { auto& context = GetEmbedderContext(); EmbedderConfigBuilder builder(context); builder.SetOpenGLRendererConfig(SkISize::Make(800, 600)); builder.SetCompositor(); builder.SetDartEntrypoint( "can_composite_platform_views_with_platform_layer_on_bottom"); context.GetCompositor().SetRenderTargetType( EmbedderTestCompositor::RenderTargetType::kOpenGLTexture); fml::CountDownLatch latch(4); sk_sp scene_image; context.SetNextSceneCallback([&](sk_sp scene) { scene_image = std::move(scene); latch.CountDown(); }); context.GetCompositor().SetNextPresentCallback( [&](const FlutterLayer** layers, size_t layers_count) { ASSERT_EQ(layers_count, 2u); // Layer Root { FlutterBackingStore backing_store = *layers[0]->backing_store; backing_store.type = kFlutterBackingStoreTypeOpenGL; backing_store.did_update = true; backing_store.open_gl.type = kFlutterOpenGLTargetTypeTexture; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypeBackingStore; layer.backing_store = &backing_store; layer.size = FlutterSizeMake(800.0, 600.0); layer.offset = FlutterPointMake(0.0, 0.0); ASSERT_EQ(*layers[0], layer); } // Layer 1 { FlutterPlatformView platform_view = {}; platform_view.struct_size = sizeof(platform_view); platform_view.identifier = 1; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypePlatformView; layer.platform_view = &platform_view; layer.size = FlutterSizeMake(50.0, 150.0); layer.offset = FlutterPointMake(20.0, 20.0); ASSERT_EQ(*layers[1], layer); } latch.CountDown(); }); context.GetCompositor().SetPlatformViewRendererCallback( [&](const FlutterLayer& layer, GrContext* context) -> sk_sp { auto surface = CreateRenderSurface(layer, context); auto canvas = surface->getCanvas(); FML_CHECK(canvas != nullptr); switch (layer.platform_view->identifier) { case 1: { SkPaint paint; // See dart test for total order. paint.setColor(SK_ColorGREEN); paint.setAlpha(127); const auto& rect = SkRect::MakeWH(layer.size.width, layer.size.height); canvas->drawRect(rect, paint); latch.CountDown(); } break; default: // Asked to render an unknown platform view. FML_CHECK(false) << "Test was asked to composite an unknown platform view."; } return surface->makeImageSnapshot(); }); context.AddNativeCallback( "SignalNativeTest", CREATE_NATIVE_ENTRY( [&latch](Dart_NativeArguments args) { latch.CountDown(); })); auto engine = builder.LaunchEngine(); // Send a window metrics events so frames may be scheduled. FlutterWindowMetricsEvent event = {}; event.struct_size = sizeof(event); event.width = 800; event.height = 600; event.pixel_ratio = 1.0; ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kSuccess); ASSERT_TRUE(engine.is_valid()); latch.Wait(); ASSERT_TRUE(ImageMatchesFixture( "compositor_with_platform_layer_on_bottom.png", scene_image)); ASSERT_EQ(context.GetCompositor().GetBackingStoresCount(), 1u); } //------------------------------------------------------------------------------ /// Test the layer structure and pixels rendered when using a custom compositor /// with a root surface transformation. /// TEST_F(EmbedderTest, CompositorMustBeAbleToRenderKnownSceneWithRootSurfaceTransformation) { auto& context = GetEmbedderContext(); EmbedderConfigBuilder builder(context); builder.SetOpenGLRendererConfig(SkISize::Make(600, 800)); builder.SetCompositor(); builder.SetDartEntrypoint("can_composite_platform_views_with_known_scene"); context.GetCompositor().SetRenderTargetType( EmbedderTestCompositor::RenderTargetType::kOpenGLTexture); // This must match the transformation provided in the // |CanRenderGradientWithoutCompositorWithXform| test to ensure that // transforms are consistent respected. const auto root_surface_transformation = SkMatrix().preTranslate(0, 800).preRotate(-90, 0, 0); context.SetRootSurfaceTransformation(root_surface_transformation); fml::CountDownLatch latch(6); sk_sp scene_image; context.SetNextSceneCallback([&](sk_sp scene) { scene_image = std::move(scene); latch.CountDown(); }); context.GetCompositor().SetNextPresentCallback( [&](const FlutterLayer** layers, size_t layers_count) { ASSERT_EQ(layers_count, 5u); // Layer Root { FlutterBackingStore backing_store = *layers[0]->backing_store; backing_store.type = kFlutterBackingStoreTypeOpenGL; backing_store.did_update = true; backing_store.open_gl.type = kFlutterOpenGLTargetTypeTexture; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypeBackingStore; layer.backing_store = &backing_store; layer.size = FlutterSizeMake(600.0, 800.0); layer.offset = FlutterPointMake(0.0, 0.0); ASSERT_EQ(*layers[0], layer); } // Layer 1 { FlutterPlatformView platform_view = {}; platform_view.struct_size = sizeof(platform_view); platform_view.identifier = 1; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypePlatformView; layer.platform_view = &platform_view; layer.size = FlutterSizeMake(150.0, 50.0); layer.offset = FlutterPointMake(20.0, 730.0); ASSERT_EQ(*layers[1], layer); } // Layer 2 { FlutterBackingStore backing_store = *layers[2]->backing_store; backing_store.type = kFlutterBackingStoreTypeOpenGL; backing_store.did_update = true; backing_store.open_gl.type = kFlutterOpenGLTargetTypeTexture; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypeBackingStore; layer.backing_store = &backing_store; layer.size = FlutterSizeMake(600.0, 800.0); layer.offset = FlutterPointMake(0.0, 0.0); ASSERT_EQ(*layers[2], layer); } // Layer 3 { FlutterPlatformView platform_view = {}; platform_view.struct_size = sizeof(platform_view); platform_view.identifier = 2; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypePlatformView; layer.platform_view = &platform_view; layer.size = FlutterSizeMake(150.0, 50.0); layer.offset = FlutterPointMake(40.0, 710.0); ASSERT_EQ(*layers[3], layer); } // Layer 4 { FlutterBackingStore backing_store = *layers[4]->backing_store; backing_store.type = kFlutterBackingStoreTypeOpenGL; backing_store.did_update = true; backing_store.open_gl.type = kFlutterOpenGLTargetTypeTexture; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypeBackingStore; layer.backing_store = &backing_store; layer.size = FlutterSizeMake(600.0, 800.0); layer.offset = FlutterPointMake(0.0, 0.0); ASSERT_EQ(*layers[4], layer); } latch.CountDown(); }); context.GetCompositor().SetPlatformViewRendererCallback( [&](const FlutterLayer& layer, GrContext* context) -> sk_sp { auto surface = CreateRenderSurface(layer, context); auto canvas = surface->getCanvas(); FML_CHECK(canvas != nullptr); switch (layer.platform_view->identifier) { case 1: { SkPaint paint; // See dart test for total order. paint.setColor(SK_ColorGREEN); paint.setAlpha(127); const auto& rect = SkRect::MakeWH(layer.size.width, layer.size.height); canvas->drawRect(rect, paint); latch.CountDown(); } break; case 2: { SkPaint paint; // See dart test for total order. paint.setColor(SK_ColorMAGENTA); paint.setAlpha(127); const auto& rect = SkRect::MakeWH(layer.size.width, layer.size.height); canvas->drawRect(rect, paint); latch.CountDown(); } break; default: // Asked to render an unknown platform view. FML_CHECK(false) << "Test was asked to composite an unknown platform view."; } return surface->makeImageSnapshot(); }); context.AddNativeCallback( "SignalNativeTest", CREATE_NATIVE_ENTRY( [&latch](Dart_NativeArguments args) { latch.CountDown(); })); auto engine = builder.LaunchEngine(); // Send a window metrics events so frames may be scheduled. FlutterWindowMetricsEvent event = {}; event.struct_size = sizeof(event); // Flutter still thinks it is 800 x 600. Only the root surface is rotated. event.width = 800; event.height = 600; event.pixel_ratio = 1.0; ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kSuccess); ASSERT_TRUE(engine.is_valid()); latch.Wait(); ASSERT_TRUE(ImageMatchesFixture("compositor_root_surface_xformation.png", scene_image)); } TEST_F(EmbedderTest, CanRenderSceneWithoutCustomCompositor) { auto& context = GetEmbedderContext(); EmbedderConfigBuilder builder(context); builder.SetDartEntrypoint("can_render_scene_without_custom_compositor"); builder.SetOpenGLRendererConfig(SkISize::Make(800, 600)); fml::CountDownLatch latch(1); sk_sp renderered_scene; context.SetNextSceneCallback([&](auto image) { renderered_scene = std::move(image); latch.CountDown(); }); auto engine = builder.LaunchEngine(); ASSERT_TRUE(engine.is_valid()); // Send a window metrics events so frames may be scheduled. FlutterWindowMetricsEvent event = {}; event.struct_size = sizeof(event); event.width = 800; event.height = 600; event.pixel_ratio = 1.0; ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kSuccess); latch.Wait(); ASSERT_NE(renderered_scene, nullptr); ASSERT_TRUE(ImageMatchesFixture("scene_without_custom_compositor.png", renderered_scene)); } TEST_F(EmbedderTest, CanRenderSceneWithoutCustomCompositorWithTransformation) { auto& context = GetEmbedderContext(); const auto root_surface_transformation = SkMatrix().preTranslate(0, 800).preRotate(-90, 0, 0); context.SetRootSurfaceTransformation(root_surface_transformation); EmbedderConfigBuilder builder(context); builder.SetDartEntrypoint("can_render_scene_without_custom_compositor"); builder.SetOpenGLRendererConfig(SkISize::Make(600, 800)); fml::CountDownLatch latch(1); sk_sp renderered_scene; context.SetNextSceneCallback([&](auto image) { renderered_scene = std::move(image); latch.CountDown(); }); auto engine = builder.LaunchEngine(); ASSERT_TRUE(engine.is_valid()); // Send a window metrics events so frames may be scheduled. FlutterWindowMetricsEvent event = {}; event.struct_size = sizeof(event); // Flutter still thinks it is 800 x 600. event.width = 800; event.height = 600; event.pixel_ratio = 1.0; ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kSuccess); latch.Wait(); ASSERT_NE(renderered_scene, nullptr); ASSERT_TRUE(ImageMatchesFixture( "scene_without_custom_compositor_with_xform.png", renderered_scene)); } TEST_F(EmbedderTest, CanRenderGradientWithoutCompositor) { auto& context = GetEmbedderContext(); EmbedderConfigBuilder builder(context); builder.SetDartEntrypoint("render_gradient"); builder.SetOpenGLRendererConfig(SkISize::Make(800, 600)); fml::CountDownLatch latch(1); sk_sp renderered_scene; context.SetNextSceneCallback([&](auto image) { renderered_scene = std::move(image); latch.CountDown(); }); auto engine = builder.LaunchEngine(); ASSERT_TRUE(engine.is_valid()); // Send a window metrics events so frames may be scheduled. FlutterWindowMetricsEvent event = {}; event.struct_size = sizeof(event); event.width = 800; event.height = 600; event.pixel_ratio = 1.0; ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kSuccess); latch.Wait(); ASSERT_NE(renderered_scene, nullptr); ASSERT_TRUE(ImageMatchesFixture("gradient.png", renderered_scene)); } TEST_F(EmbedderTest, CanRenderGradientWithoutCompositorWithXform) { auto& context = GetEmbedderContext(); const auto root_surface_transformation = SkMatrix().preTranslate(0, 800).preRotate(-90, 0, 0); context.SetRootSurfaceTransformation(root_surface_transformation); EmbedderConfigBuilder builder(context); const auto surface_size = SkISize::Make(600, 800); builder.SetDartEntrypoint("render_gradient"); builder.SetOpenGLRendererConfig(surface_size); fml::CountDownLatch latch(1); sk_sp renderered_scene; context.SetNextSceneCallback([&](auto image) { renderered_scene = std::move(image); latch.CountDown(); }); auto engine = builder.LaunchEngine(); ASSERT_TRUE(engine.is_valid()); // Send a window metrics events so frames may be scheduled. FlutterWindowMetricsEvent event = {}; event.struct_size = sizeof(event); // Flutter still thinks it is 800 x 600. event.width = 800; event.height = 600; event.pixel_ratio = 1.0; ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kSuccess); latch.Wait(); ASSERT_NE(renderered_scene, nullptr); ASSERT_TRUE(ImageMatchesFixture("gradient_xform.png", renderered_scene)); } TEST_F(EmbedderTest, CanRenderGradientWithCompositor) { auto& context = GetEmbedderContext(); EmbedderConfigBuilder builder(context); builder.SetDartEntrypoint("render_gradient"); builder.SetOpenGLRendererConfig(SkISize::Make(800, 600)); builder.SetCompositor(); fml::CountDownLatch latch(1); sk_sp renderered_scene; context.SetNextSceneCallback([&](auto image) { renderered_scene = std::move(image); latch.CountDown(); }); auto engine = builder.LaunchEngine(); ASSERT_TRUE(engine.is_valid()); // Send a window metrics events so frames may be scheduled. FlutterWindowMetricsEvent event = {}; event.struct_size = sizeof(event); event.width = 800; event.height = 600; event.pixel_ratio = 1.0; ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kSuccess); latch.Wait(); ASSERT_NE(renderered_scene, nullptr); ASSERT_TRUE(ImageMatchesFixture("gradient.png", renderered_scene)); } TEST_F(EmbedderTest, CanRenderGradientWithCompositorWithXform) { auto& context = GetEmbedderContext(); // This must match the transformation provided in the // |CanRenderGradientWithoutCompositorWithXform| test to ensure that // transforms are consistent respected. const auto root_surface_transformation = SkMatrix().preTranslate(0, 800).preRotate(-90, 0, 0); context.SetRootSurfaceTransformation(root_surface_transformation); EmbedderConfigBuilder builder(context); builder.SetDartEntrypoint("render_gradient"); builder.SetOpenGLRendererConfig(SkISize::Make(600, 800)); builder.SetCompositor(); fml::CountDownLatch latch(1); sk_sp renderered_scene; context.SetNextSceneCallback([&](auto image) { renderered_scene = std::move(image); latch.CountDown(); }); auto engine = builder.LaunchEngine(); ASSERT_TRUE(engine.is_valid()); // Send a window metrics events so frames may be scheduled. FlutterWindowMetricsEvent event = {}; event.struct_size = sizeof(event); // Flutter still thinks it is 800 x 600. event.width = 800; event.height = 600; event.pixel_ratio = 1.0; ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kSuccess); latch.Wait(); ASSERT_NE(renderered_scene, nullptr); ASSERT_TRUE(ImageMatchesFixture("gradient_xform.png", renderered_scene)); } TEST_F(EmbedderTest, CanRenderGradientWithCompositorOnNonRootLayer) { auto& context = GetEmbedderContext(); EmbedderConfigBuilder builder(context); builder.SetDartEntrypoint("render_gradient_on_non_root_backing_store"); builder.SetOpenGLRendererConfig(SkISize::Make(800, 600)); builder.SetCompositor(); fml::CountDownLatch latch(1); context.GetCompositor().SetNextPresentCallback( [&](const FlutterLayer** layers, size_t layers_count) { ASSERT_EQ(layers_count, 3u); // Layer Root { FlutterBackingStore backing_store = *layers[0]->backing_store; backing_store.type = kFlutterBackingStoreTypeOpenGL; backing_store.did_update = true; backing_store.open_gl.type = kFlutterOpenGLTargetTypeFramebuffer; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypeBackingStore; layer.backing_store = &backing_store; layer.size = FlutterSizeMake(800.0, 600.0); layer.offset = FlutterPointMake(0.0, 0.0); ASSERT_EQ(*layers[0], layer); } // Layer 1 { FlutterPlatformView platform_view = {}; platform_view.struct_size = sizeof(platform_view); platform_view.identifier = 1; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypePlatformView; layer.platform_view = &platform_view; layer.size = FlutterSizeMake(100.0, 200.0); layer.offset = FlutterPointMake(0.0, 0.0); ASSERT_EQ(*layers[1], layer); } // Layer 2 { FlutterBackingStore backing_store = *layers[2]->backing_store; backing_store.type = kFlutterBackingStoreTypeOpenGL; backing_store.did_update = true; backing_store.open_gl.type = kFlutterOpenGLTargetTypeFramebuffer; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypeBackingStore; layer.backing_store = &backing_store; layer.size = FlutterSizeMake(800.0, 600.0); layer.offset = FlutterPointMake(0.0, 0.0); ASSERT_EQ(*layers[2], layer); } }); context.GetCompositor().SetPlatformViewRendererCallback( [&](const FlutterLayer& layer, GrContext* context) -> sk_sp { auto surface = CreateRenderSurface(layer, context); auto canvas = surface->getCanvas(); FML_CHECK(canvas != nullptr); switch (layer.platform_view->identifier) { case 1: { FML_CHECK(layer.size.width == 100); FML_CHECK(layer.size.height == 200); // This is occluded anyway. We just want to make sure we see this. } break; default: // Asked to render an unknown platform view. FML_CHECK(false) << "Test was asked to composite an unknown platform view."; } return surface->makeImageSnapshot(); }); sk_sp renderered_scene; context.SetNextSceneCallback([&](auto image) { renderered_scene = std::move(image); latch.CountDown(); }); auto engine = builder.LaunchEngine(); ASSERT_TRUE(engine.is_valid()); // Send a window metrics events so frames may be scheduled. FlutterWindowMetricsEvent event = {}; event.struct_size = sizeof(event); event.width = 800; event.height = 600; event.pixel_ratio = 1.0; ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kSuccess); latch.Wait(); ASSERT_NE(renderered_scene, nullptr); ASSERT_TRUE(ImageMatchesFixture("gradient.png", renderered_scene)); } TEST_F(EmbedderTest, CanRenderGradientWithCompositorOnNonRootLayerWithXform) { auto& context = GetEmbedderContext(); // This must match the transformation provided in the // |CanRenderGradientWithoutCompositorWithXform| test to ensure that // transforms are consistent respected. const auto root_surface_transformation = SkMatrix().preTranslate(0, 800).preRotate(-90, 0, 0); context.SetRootSurfaceTransformation(root_surface_transformation); EmbedderConfigBuilder builder(context); builder.SetDartEntrypoint("render_gradient_on_non_root_backing_store"); builder.SetOpenGLRendererConfig(SkISize::Make(600, 800)); builder.SetCompositor(); fml::CountDownLatch latch(1); context.GetCompositor().SetNextPresentCallback( [&](const FlutterLayer** layers, size_t layers_count) { ASSERT_EQ(layers_count, 3u); // Layer Root { FlutterBackingStore backing_store = *layers[0]->backing_store; backing_store.type = kFlutterBackingStoreTypeOpenGL; backing_store.did_update = true; backing_store.open_gl.type = kFlutterOpenGLTargetTypeFramebuffer; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypeBackingStore; layer.backing_store = &backing_store; layer.size = FlutterSizeMake(600.0, 800.0); layer.offset = FlutterPointMake(0.0, 0.0); ASSERT_EQ(*layers[0], layer); } // Layer 1 { FlutterPlatformView platform_view = {}; platform_view.struct_size = sizeof(platform_view); platform_view.identifier = 1; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypePlatformView; layer.platform_view = &platform_view; layer.size = FlutterSizeMake(200.0, 100.0); layer.offset = FlutterPointMake(0.0, 700.0); ASSERT_EQ(*layers[1], layer); } // Layer 2 { FlutterBackingStore backing_store = *layers[2]->backing_store; backing_store.type = kFlutterBackingStoreTypeOpenGL; backing_store.did_update = true; backing_store.open_gl.type = kFlutterOpenGLTargetTypeFramebuffer; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypeBackingStore; layer.backing_store = &backing_store; layer.size = FlutterSizeMake(600.0, 800.0); layer.offset = FlutterPointMake(0.0, 0.0); ASSERT_EQ(*layers[2], layer); } }); context.GetCompositor().SetPlatformViewRendererCallback( [&](const FlutterLayer& layer, GrContext* context) -> sk_sp { auto surface = CreateRenderSurface(layer, context); auto canvas = surface->getCanvas(); FML_CHECK(canvas != nullptr); switch (layer.platform_view->identifier) { case 1: { FML_CHECK(layer.size.width == 200); FML_CHECK(layer.size.height == 100); // This is occluded anyway. We just want to make sure we see this. } break; default: // Asked to render an unknown platform view. FML_CHECK(false) << "Test was asked to composite an unknown platform view."; } return surface->makeImageSnapshot(); }); sk_sp renderered_scene; context.SetNextSceneCallback([&](auto image) { renderered_scene = std::move(image); latch.CountDown(); }); auto engine = builder.LaunchEngine(); ASSERT_TRUE(engine.is_valid()); // Send a window metrics events so frames may be scheduled. FlutterWindowMetricsEvent event = {}; event.struct_size = sizeof(event); // Flutter still thinks it is 800 x 600. event.width = 800; event.height = 600; event.pixel_ratio = 1.0; ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kSuccess); latch.Wait(); ASSERT_NE(renderered_scene, nullptr); ASSERT_TRUE(ImageMatchesFixture("gradient_xform.png", renderered_scene)); } TEST_F(EmbedderTest, VerifyB141980393) { auto& context = GetEmbedderContext(); EmbedderConfigBuilder builder(context); // The Flutter application is 800 x 600 but rendering on a surface that is 600 // x 800 achieved using a root surface transformation. const auto root_surface_transformation = SkMatrix().preTranslate(0, 800).preRotate(-90, 0, 0); const auto flutter_application_rect = SkRect::MakeWH(800, 600); const auto root_surface_rect = root_surface_transformation.mapRect(flutter_application_rect); ASSERT_DOUBLE_EQ(root_surface_rect.width(), 600.0); ASSERT_DOUBLE_EQ(root_surface_rect.height(), 800.0); // Configure the fixture for the surface transformation. context.SetRootSurfaceTransformation(root_surface_transformation); // Configure the Flutter project args for the root surface transformation. builder.SetOpenGLRendererConfig( SkISize::Make(root_surface_rect.width(), root_surface_rect.height())); // Use a compositor instead of rendering directly to the surface. builder.SetCompositor(); builder.SetDartEntrypoint("verify_b141980393"); fml::AutoResetWaitableEvent latch; context.GetCompositor().SetNextPresentCallback( [&](const FlutterLayer** layers, size_t layers_count) { ASSERT_EQ(layers_count, 2u); // Layer Root { FlutterLayer layer = {}; FlutterBackingStore backing_store = *layers[0]->backing_store; layer.backing_store = &backing_store; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypeBackingStore; // Our root surface has been rotated. layer.size = FlutterSizeMake(600.0, 800.0); layer.offset = FlutterPointMake(0.0, 0.0); ASSERT_EQ(*layers[0], layer); } // Layer 1 { FlutterPlatformView platform_view = {}; platform_view.struct_size = sizeof(platform_view); platform_view.identifier = 1337; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypePlatformView; layer.platform_view = &platform_view; // From the Dart side. These dimensions match those specified in Dart // code and are free of root surface transformations. const double unxformed_top_margin = 31.0; const double unxformed_bottom_margin = 37.0; const auto unxformed_platform_view_rect = SkRect::MakeXYWH( 0.0, // x unxformed_top_margin, // y (top margin) 800, // width 600 - unxformed_top_margin - unxformed_bottom_margin // height ); // The platform views are in the coordinate space of the root surface // with top-left origin. The embedder has specified a transformation // to this surface which it must account for in the coordinates it // receives here. const auto xformed_platform_view_rect = root_surface_transformation.mapRect(unxformed_platform_view_rect); // Spell out the value that we are going to be checking below for // clarity. ASSERT_EQ(xformed_platform_view_rect, SkRect::MakeXYWH(31.0, // x 0.0, // y 532.0, // width 800.0 // height )); // Verify that the engine is giving us the right size and offset. layer.offset = FlutterPointMake(xformed_platform_view_rect.x(), xformed_platform_view_rect.y()); layer.size = FlutterSizeMake(xformed_platform_view_rect.width(), xformed_platform_view_rect.height()); ASSERT_EQ(*layers[1], layer); } latch.Signal(); }); auto engine = builder.LaunchEngine(); // Send a window metrics events so frames may be scheduled. FlutterWindowMetricsEvent event = {}; event.struct_size = sizeof(event); // The Flutter application is 800 x 600 rendering on a surface 600 x 800 // achieved via a root surface transformation. event.width = flutter_application_rect.width(); event.height = flutter_application_rect.height(); event.pixel_ratio = 1.0; ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kSuccess); ASSERT_TRUE(engine.is_valid()); latch.Wait(); } //------------------------------------------------------------------------------ /// Test that an engine can be initialized but not run. /// TEST_F(EmbedderTest, CanCreateInitializedEngine) { EmbedderConfigBuilder builder(GetEmbedderContext()); builder.SetSoftwareRendererConfig(); auto engine = builder.InitializeEngine(); ASSERT_TRUE(engine.is_valid()); engine.reset(); } //------------------------------------------------------------------------------ /// Test that an initialized engine can be run exactly once. /// TEST_F(EmbedderTest, CanRunInitializedEngine) { EmbedderConfigBuilder builder(GetEmbedderContext()); builder.SetSoftwareRendererConfig(); auto engine = builder.InitializeEngine(); ASSERT_TRUE(engine.is_valid()); ASSERT_EQ(FlutterEngineRunInitialized(engine.get()), kSuccess); // Cannot re-run an already running engine. ASSERT_EQ(FlutterEngineRunInitialized(engine.get()), kInvalidArguments); engine.reset(); } //------------------------------------------------------------------------------ /// Test that an engine can be deinitialized. /// TEST_F(EmbedderTest, CaDeinitializeAnEngine) { EmbedderConfigBuilder builder(GetEmbedderContext()); builder.SetSoftwareRendererConfig(); auto engine = builder.InitializeEngine(); ASSERT_TRUE(engine.is_valid()); ASSERT_EQ(FlutterEngineRunInitialized(engine.get()), kSuccess); // Cannot re-run an already running engine. ASSERT_EQ(FlutterEngineRunInitialized(engine.get()), kInvalidArguments); ASSERT_EQ(FlutterEngineDeinitialize(engine.get()), kSuccess); // It is ok to deinitialize an engine multiple times. ASSERT_EQ(FlutterEngineDeinitialize(engine.get()), kSuccess); // Sending events to a deinitalized engine fails. FlutterWindowMetricsEvent event = {}; event.struct_size = sizeof(event); event.width = 800; event.height = 600; event.pixel_ratio = 1.0; ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kInvalidArguments); engine.reset(); } //------------------------------------------------------------------------------ /// Asserts that embedders can provide a task runner for the render thread. /// TEST_F(EmbedderTest, CanCreateEmbedderWithCustomRenderTaskRunner) { std::mutex engine_mutex; UniqueEngine engine; fml::AutoResetWaitableEvent task_latch; bool task_executed = false; EmbedderTestTaskRunner render_task_runner( CreateNewThread("custom_render_thread"), [&](FlutterTask task) { std::scoped_lock engine_lock(engine_mutex); if (engine.is_valid()) { ASSERT_EQ(FlutterEngineRunTask(engine.get(), &task), kSuccess); task_executed = true; task_latch.Signal(); } }); EmbedderConfigBuilder builder(GetEmbedderContext()); builder.SetDartEntrypoint("can_render_scene_without_custom_compositor"); builder.SetOpenGLRendererConfig(SkISize::Make(800, 600)); builder.SetRenderTaskRunner( &render_task_runner.GetFlutterTaskRunnerDescription()); { std::scoped_lock lock(engine_mutex); engine = builder.InitializeEngine(); } ASSERT_EQ(FlutterEngineRunInitialized(engine.get()), kSuccess); ASSERT_TRUE(engine.is_valid()); FlutterWindowMetricsEvent event = {}; event.struct_size = sizeof(event); event.width = 800; event.height = 600; event.pixel_ratio = 1.0; ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kSuccess); task_latch.Wait(); ASSERT_TRUE(task_executed); ASSERT_EQ(FlutterEngineDeinitialize(engine.get()), kSuccess); { std::scoped_lock engine_lock(engine_mutex); engine.reset(); } } //------------------------------------------------------------------------------ /// Asserts that the render task runner can be the same as the platform task /// runner. /// TEST_F(EmbedderTest, CanCreateEmbedderWithCustomRenderTaskRunnerTheSameAsPlatformTaskRunner) { // A new thread needs to be created for the platform thread because the test // can't wait for assertions to be completed on the same thread that services // platform task runner tasks. auto platform_task_runner = CreateNewThread("platform_thread"); static std::mutex engine_mutex; static UniqueEngine engine; fml::AutoResetWaitableEvent task_latch; bool task_executed = false; EmbedderTestTaskRunner common_task_runner( platform_task_runner, [&](FlutterTask task) { std::scoped_lock engine_lock(engine_mutex); if (engine.is_valid()) { ASSERT_EQ(FlutterEngineRunTask(engine.get(), &task), kSuccess); task_executed = true; task_latch.Signal(); } }); platform_task_runner->PostTask([&]() { EmbedderConfigBuilder builder(GetEmbedderContext()); builder.SetDartEntrypoint("can_render_scene_without_custom_compositor"); builder.SetOpenGLRendererConfig(SkISize::Make(800, 600)); builder.SetRenderTaskRunner( &common_task_runner.GetFlutterTaskRunnerDescription()); builder.SetPlatformTaskRunner( &common_task_runner.GetFlutterTaskRunnerDescription()); { std::scoped_lock lock(engine_mutex); engine = builder.InitializeEngine(); } ASSERT_EQ(FlutterEngineRunInitialized(engine.get()), kSuccess); ASSERT_TRUE(engine.is_valid()); FlutterWindowMetricsEvent event = {}; event.struct_size = sizeof(event); event.width = 800; event.height = 600; event.pixel_ratio = 1.0; ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kSuccess); }); task_latch.Wait(); // Don't use the task latch because that may be called multiple time // (including during the shutdown process). fml::AutoResetWaitableEvent shutdown_latch; platform_task_runner->PostTask([&]() { ASSERT_TRUE(task_executed); ASSERT_EQ(FlutterEngineDeinitialize(engine.get()), kSuccess); { std::scoped_lock engine_lock(engine_mutex); engine.reset(); } shutdown_latch.Signal(); }); shutdown_latch.Wait(); { std::scoped_lock engine_lock(engine_mutex); // Engine should have been killed by this point. ASSERT_FALSE(engine.is_valid()); } } TEST_F(EmbedderTest, CompositorMustBeAbleToRenderKnownScenePixelRatioOnSurface) { auto& context = GetEmbedderContext(); EmbedderConfigBuilder builder(context); builder.SetOpenGLRendererConfig(SkISize::Make(800, 600)); builder.SetCompositor(); builder.SetDartEntrypoint("can_display_platform_view_with_pixel_ratio"); context.GetCompositor().SetRenderTargetType( EmbedderTestCompositor::RenderTargetType::kOpenGLTexture); sk_sp renderered_scene; fml::CountDownLatch latch(2); context.SetNextSceneCallback([&](auto image) { renderered_scene = std::move(image); latch.CountDown(); }); context.GetCompositor().SetNextPresentCallback( [&](const FlutterLayer** layers, size_t layers_count) { ASSERT_EQ(layers_count, 3u); // Layer 0 (Root) { FlutterBackingStore backing_store = *layers[0]->backing_store; backing_store.type = kFlutterBackingStoreTypeOpenGL; backing_store.did_update = true; backing_store.open_gl.type = kFlutterOpenGLTargetTypeTexture; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypeBackingStore; layer.backing_store = &backing_store; layer.size = FlutterSizeMake(800.0, 600.0); layer.offset = FlutterPointMake(0.0, 0.0); ASSERT_EQ(*layers[0], layer); } // Layer 1 { FlutterPlatformView platform_view = {}; platform_view.struct_size = sizeof(platform_view); platform_view.identifier = 42; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypePlatformView; layer.platform_view = &platform_view; layer.size = FlutterSizeMake(800.0, 560.0); layer.offset = FlutterPointMake(0.0, 80.0); ASSERT_EQ(*layers[1], layer); } // Layer 2 { FlutterBackingStore backing_store = *layers[2]->backing_store; backing_store.type = kFlutterBackingStoreTypeOpenGL; backing_store.did_update = true; backing_store.open_gl.type = kFlutterOpenGLTargetTypeTexture; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypeBackingStore; layer.backing_store = &backing_store; layer.size = FlutterSizeMake(800.0, 600.0); layer.offset = FlutterPointMake(0.0, 0.0); ASSERT_EQ(*layers[2], layer); } latch.CountDown(); }); auto engine = builder.LaunchEngine(); // Send a window metrics events so frames may be scheduled. FlutterWindowMetricsEvent event = {}; event.struct_size = sizeof(event); event.width = 400 * 2.0; event.height = 300 * 2.0; event.pixel_ratio = 2.0; ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kSuccess); ASSERT_TRUE(engine.is_valid()); latch.Wait(); ASSERT_TRUE(ImageMatchesFixture("dpr_noxform.png", renderered_scene)); } TEST_F( EmbedderTest, CompositorMustBeAbleToRenderKnownScenePixelRatioOnSurfaceWithRootSurfaceXformation) { auto& context = GetEmbedderContext(); EmbedderConfigBuilder builder(context); builder.SetOpenGLRendererConfig(SkISize::Make(600, 800)); builder.SetCompositor(); builder.SetDartEntrypoint("can_display_platform_view_with_pixel_ratio"); context.GetCompositor().SetRenderTargetType( EmbedderTestCompositor::RenderTargetType::kOpenGLTexture); const auto root_surface_transformation = SkMatrix().preTranslate(0, 800).preRotate(-90, 0, 0); context.SetRootSurfaceTransformation(root_surface_transformation); sk_sp renderered_scene; fml::CountDownLatch latch(2); context.SetNextSceneCallback([&](auto image) { renderered_scene = std::move(image); latch.CountDown(); }); context.GetCompositor().SetNextPresentCallback( [&](const FlutterLayer** layers, size_t layers_count) { ASSERT_EQ(layers_count, 3u); // Layer 0 (Root) { FlutterBackingStore backing_store = *layers[0]->backing_store; backing_store.type = kFlutterBackingStoreTypeOpenGL; backing_store.did_update = true; backing_store.open_gl.type = kFlutterOpenGLTargetTypeTexture; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypeBackingStore; layer.backing_store = &backing_store; layer.size = FlutterSizeMake(600.0, 800.0); layer.offset = FlutterPointMake(0.0, 0.0); ASSERT_EQ(*layers[0], layer); } // Layer 1 { FlutterPlatformView platform_view = {}; platform_view.struct_size = sizeof(platform_view); platform_view.identifier = 42; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypePlatformView; layer.platform_view = &platform_view; layer.size = FlutterSizeMake(560.0, 800.0); layer.offset = FlutterPointMake(80.0, 0.0); ASSERT_EQ(*layers[1], layer); } // Layer 2 { FlutterBackingStore backing_store = *layers[2]->backing_store; backing_store.type = kFlutterBackingStoreTypeOpenGL; backing_store.did_update = true; backing_store.open_gl.type = kFlutterOpenGLTargetTypeTexture; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypeBackingStore; layer.backing_store = &backing_store; layer.size = FlutterSizeMake(600.0, 800.0); layer.offset = FlutterPointMake(0.0, 0.0); ASSERT_EQ(*layers[2], layer); } latch.CountDown(); }); auto engine = builder.LaunchEngine(); // Send a window metrics events so frames may be scheduled. FlutterWindowMetricsEvent event = {}; event.struct_size = sizeof(event); event.width = 400 * 2.0; event.height = 300 * 2.0; event.pixel_ratio = 2.0; ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kSuccess); ASSERT_TRUE(engine.is_valid()); latch.Wait(); ASSERT_TRUE(ImageMatchesFixture("dpr_xform.png", renderered_scene)); } TEST_F(EmbedderTest, CanUpdateLocales) { auto& context = GetEmbedderContext(); EmbedderConfigBuilder builder(context); builder.SetSoftwareRendererConfig(); builder.SetDartEntrypoint("can_receive_locale_updates"); fml::AutoResetWaitableEvent latch; context.AddNativeCallback( "SignalNativeTest", CREATE_NATIVE_ENTRY( [&latch](Dart_NativeArguments args) { latch.Signal(); })); auto engine = builder.LaunchEngine(); ASSERT_TRUE(engine.is_valid()); // Wait for the application to attach the listener. latch.Wait(); FlutterLocale locale1 = {}; locale1.struct_size = sizeof(locale1); locale1.language_code = ""; // invalid locale1.country_code = "US"; locale1.script_code = ""; locale1.variant_code = nullptr; FlutterLocale locale2 = {}; locale2.struct_size = sizeof(locale2); locale2.language_code = "zh"; locale2.country_code = "CN"; locale2.script_code = "Hans"; locale2.variant_code = nullptr; std::vector locales; locales.push_back(&locale1); locales.push_back(&locale2); ASSERT_EQ( FlutterEngineUpdateLocales(engine.get(), locales.data(), locales.size()), kInvalidArguments); // Fix the invalid code. locale1.language_code = "en"; ASSERT_EQ( FlutterEngineUpdateLocales(engine.get(), locales.data(), locales.size()), kSuccess); fml::AutoResetWaitableEvent check_latch; context.AddNativeCallback( "SignalNativeCount", CREATE_NATIVE_ENTRY([&check_latch](Dart_NativeArguments args) { ASSERT_EQ(tonic::DartConverter::FromDart( Dart_GetNativeArgument(args, 0)), 2); check_latch.Signal(); })); check_latch.Wait(); } TEST_F(EmbedderTest, CanQueryDartAOTMode) { ASSERT_EQ(FlutterEngineRunsAOTCompiledDartCode(), flutter::DartVM::IsRunningPrecompiledCode()); } TEST_F(EmbedderTest, VerifyB143464703WithSoftwareBackend) { auto& context = GetEmbedderContext(); EmbedderConfigBuilder builder(context); builder.SetSoftwareRendererConfig(SkISize::Make(1024, 600)); builder.SetCompositor(); builder.SetDartEntrypoint("verify_b143464703"); context.GetCompositor().SetRenderTargetType( EmbedderTestCompositor::RenderTargetType::kSoftwareBuffer); fml::CountDownLatch latch(2); context.GetCompositor().SetNextPresentCallback( [&](const FlutterLayer** layers, size_t layers_count) { ASSERT_EQ(layers_count, 3u); // Layer 0 (Root) { FlutterBackingStore backing_store = *layers[0]->backing_store; backing_store.type = kFlutterBackingStoreTypeSoftware; backing_store.did_update = true; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypeBackingStore; layer.backing_store = &backing_store; layer.size = FlutterSizeMake(1024.0, 600.0); layer.offset = FlutterPointMake(0.0, 0.0); ASSERT_EQ(*layers[0], layer); } // Layer 1 { FlutterPlatformView platform_view = {}; platform_view.struct_size = sizeof(platform_view); platform_view.identifier = 42; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypePlatformView; layer.platform_view = &platform_view; layer.size = FlutterSizeMake(1024.0, 540.0); layer.offset = FlutterPointMake(135.0, 60.0); ASSERT_EQ(*layers[1], layer); } // Layer 2 { FlutterBackingStore backing_store = *layers[2]->backing_store; backing_store.type = kFlutterBackingStoreTypeSoftware; backing_store.did_update = true; FlutterLayer layer = {}; layer.struct_size = sizeof(layer); layer.type = kFlutterLayerContentTypeBackingStore; layer.backing_store = &backing_store; layer.size = FlutterSizeMake(1024.0, 600.0); layer.offset = FlutterPointMake(0.0, 0.0); ASSERT_EQ(*layers[2], layer); } latch.CountDown(); }); context.GetCompositor().SetPlatformViewRendererCallback( [](const FlutterLayer& layer, GrContext* context) -> sk_sp { auto surface = CreateRenderSurface( layer, nullptr /* null because software compositor */); auto canvas = surface->getCanvas(); FML_CHECK(canvas != nullptr); switch (layer.platform_view->identifier) { case 42: { SkPaint paint; // See dart test for total order. paint.setColor(SK_ColorGREEN); paint.setAlpha(127); const auto& rect = SkRect::MakeWH(layer.size.width, layer.size.height); canvas->drawRect(rect, paint); } break; default: // Asked to render an unknown platform view. FML_CHECK(false) << "Test was asked to composite an unknown platform view."; } return surface->makeImageSnapshot(); }); auto engine = builder.LaunchEngine(); // Send a window metrics events so frames may be scheduled. FlutterWindowMetricsEvent event = {}; event.struct_size = sizeof(event); event.width = 1024; event.height = 600; event.pixel_ratio = 1.0; ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kSuccess); ASSERT_TRUE(engine.is_valid()); sk_sp renderered_scene; context.SetNextSceneCallback([&](auto image) { renderered_scene = std::move(image); latch.CountDown(); }); latch.Wait(); ASSERT_TRUE(ImageMatchesFixture("verifyb143464703_soft_noxform.png", renderered_scene)); } TEST_F(EmbedderTest, PushingMutlipleFramesSetsUpNewRecordingCanvasWithCustomCompositor) { auto& context = GetEmbedderContext(); EmbedderConfigBuilder builder(context); builder.SetOpenGLRendererConfig(SkISize::Make(600, 1024)); builder.SetCompositor(); builder.SetDartEntrypoint("push_frames_over_and_over"); context.GetCompositor().SetRenderTargetType( EmbedderTestCompositor::RenderTargetType::kOpenGLTexture); const auto root_surface_transformation = SkMatrix().preTranslate(0, 1024).preRotate(-90, 0, 0); context.SetRootSurfaceTransformation(root_surface_transformation); auto engine = builder.LaunchEngine(); // Send a window metrics events so frames may be scheduled. FlutterWindowMetricsEvent event = {}; event.struct_size = sizeof(event); event.width = 1024; event.height = 600; event.pixel_ratio = 1.0; ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kSuccess); ASSERT_TRUE(engine.is_valid()); constexpr size_t frames_expected = 10; fml::CountDownLatch frame_latch(frames_expected); size_t frames_seen = 0; context.AddNativeCallback("SignalNativeTest", CREATE_NATIVE_ENTRY([&](Dart_NativeArguments args) { frames_seen++; frame_latch.CountDown(); })); frame_latch.Wait(); ASSERT_EQ(frames_expected, frames_seen); } TEST_F(EmbedderTest, PushingMutlipleFramesSetsUpNewRecordingCanvasWithoutCustomCompositor) { auto& context = GetEmbedderContext(); EmbedderConfigBuilder builder(context); builder.SetOpenGLRendererConfig(SkISize::Make(600, 1024)); builder.SetDartEntrypoint("push_frames_over_and_over"); const auto root_surface_transformation = SkMatrix().preTranslate(0, 1024).preRotate(-90, 0, 0); context.SetRootSurfaceTransformation(root_surface_transformation); auto engine = builder.LaunchEngine(); // Send a window metrics events so frames may be scheduled. FlutterWindowMetricsEvent event = {}; event.struct_size = sizeof(event); event.width = 1024; event.height = 600; event.pixel_ratio = 1.0; ASSERT_EQ(FlutterEngineSendWindowMetricsEvent(engine.get(), &event), kSuccess); ASSERT_TRUE(engine.is_valid()); constexpr size_t frames_expected = 10; fml::CountDownLatch frame_latch(frames_expected); size_t frames_seen = 0; context.AddNativeCallback("SignalNativeTest", CREATE_NATIVE_ENTRY([&](Dart_NativeArguments args) { frames_seen++; frame_latch.CountDown(); })); frame_latch.Wait(); ASSERT_EQ(frames_expected, frames_seen); } } // namespace testing } // namespace flutter Life4gal/CPP-EASY-PROJECT /* * 写在前面: * 一个简单的俄罗斯方块游戏,没有制作连消分数奖励,没有制作分数显示,没事判断游戏结束(为什么不做?懒) * 最初是考虑使用一个Game(或者Tetris)类,然后在这个类中添加各种方法(例如新建图形,移动图形,消除图像,变形等等) * 但是实际上这么做没有任何意义,并不会对这个程序产生什么积极作用,所以就没有使用类编程 * 有些方法例如新建一个图形,消除图像,绘制图像等等都没有放在一个函数中,因为它们需要相同的参数, * 所以必须将参数放在同一个作用域中,但是预期将其分离然后使用参数传递不如直接放在一个作用域中 * 运行,节省传值占用的额外空间,并不会影响性能(大概) */ #include using namespace sf; const int field_lines = 20; /* 使用宽10格,高20格的矩阵作为游戏场地 */ const int field_rows = 10; int game_field[field_lines][field_rows] = {{0}}; // 初始化场地 struct point { /* 用于图形变形,理论上使用2*4的矩阵也能支持4*4那样的矩阵变形 */ int x; /* 这里的x表示横向的第几个位置,从0开始 */ int y; /* 这里的y表示纵向的第几层位置,从0开始 */ } a[4], b[4]; int figures[7][4] = { /* 图形出现的样子,除了I高度占四格以外,其余的图形不论高度占三格还是两格都是从第二层开始绘制,并且以第二行作为旋转中心 */ {1, 3, 5, 7}, // I /* 对于I * x, y 0 1 * 1 0 --> 空 砖 0 * 1 1 空 砖 1 * 1 2 空 砖 2 * 1 3 空 砖 3 */ {2, 4, 5, 7}, // S /* 对于S * x, y 0 1 * 0 1 --> 空 空 0 * 0 2 砖 空 1 * 1 2 砖 砖 2 * 1 3 空 砖 3 */ {3, 5, 4, 6}, // Z /* 对于Z * x, y 0 1 * 1 1 --> 空 空 0 * 1 2 空 砖 1 * 0 2 砖 砖 2 * 0 3 砖 空 3 */ {3, 5, 4, 7}, // T /* 对于T * x, y 0 1 * 1 1 --> 空 空 0 * 1 2 空 砖 1 * 0 2 砖 砖 2 * 1 3 空 砖 3 */ {2, 3, 5, 7}, // L /* 对于L * x, y 0 1 * 0 1 --> 空 空 0 * 1 1 砖 砖 1 * 1 2 空 砖 2 * 1 3 空 砖 3 */ {3, 5, 7, 6}, // J /* 对于J * x, y 0 1 * 1 1 --> 空 空 0 * 1 2 空 砖 1 * 1 3 空 砖 2 * 0 3 砖 砖 3 */ {2, 3, 4, 5}, // O /* 对于O * x, y 0 1 * 0 1 --> 空 空 0 * 1 1 砖 砖 1 * 0 2 砖 砖 2 * 1 2 空 空 3 */ }; bool check() { for (auto& i : a) { /* 判断图形是否越界 */ if (i.x < 0 || i.x > field_rows - 1 || i.y >= field_lines || game_field[i.y][i.x]) { return false; } } return true; } int main() { RenderWindow window(VideoMode(320, 480), "Tetris Game"); Texture texture_tiles, texture_background, texture_frame; texture_tiles.loadFromFile("images_tetris/tiles.png"); texture_background.loadFromFile("images_tetris/background.png"); texture_frame.loadFromFile("images_tetris/frame.png"); Sprite tiles(texture_tiles), background(texture_background), frame(texture_frame); auto mid_field_rows = int(field_rows / 2) - 1; /* 令图形出现在场地上一行的中间,-1是补偿旋转中心的偏差 */ auto dx = 0; /* 图形左右移动了多少格 */ auto is_rotate = false; /* 图形是否旋转 */ float timer = 0; /* 计时器,用来确定是否需要下降 */ auto delay = 0.3; /* 图形下降的周期 */ auto score = 0; /* 得分 */ /* 随机种子 */ srand(static_cast(time(nullptr))); /* 随机构建第一个图形 */ auto color_num = 1 + rand() % 7; /* 方块颜色,从tiles.png中截取,因为第一个和最后一个颜色相同,所以从1开始 */ auto n = rand() % 7; /* 图形类型 */ for (auto i = 0; i < 4; i++) { a[i].x = figures[n][i] % 2 + mid_field_rows; a[i].y = figures[n][i] / 2; } Clock clock; while (window.isOpen()) { auto elapsed_time = clock.getElapsedTime().asSeconds(); clock.restart(); timer += elapsed_time; Event event{}; while (window.pollEvent(event)) { if (event.type == Event::Closed) { window.close(); } if (event.type == Event::KeyPressed) { if (event.key.code == Keyboard::Up) { is_rotate = true; /* 按上旋转 */ } else if (event.key.code == Keyboard::Left) { dx = -1; } else if (event.key.code == Keyboard::Right) { dx = 1; } } } if (Keyboard::isKeyPressed(Keyboard::Down)) { delay = 0.05; /* 按下加快下降 */ } /* 让图形左右移动 */ for (auto i = 0; i < 4; i++) { b[i] = a[i]; /* 储存当前图形的位置 */ a[i].x += dx; /* 进行移动 */ } if (!check()) { // 图形越界 for (auto i = 0; i < 4; i++) { a[i] = b[i]; /* 回档至储存的状态,此次移动无效 */ } } /* 让图形旋转 */ if (is_rotate) { auto center = a[1]; /* 以第二行作为旋转中心 */ for (auto& i : a) { /* 例如 L 变形 center.x = 1 center.y = 1 * 刚出现 转变为(此时变为了y表示横向,x表示纵向) * x, y 0 1 x, y 0 1 --> 这一行变成了y * 0 1 --> 空 空 0 1 0 空 空 2 (注意以第二行作为旋转中心) * 1 1 砖 砖 1 1 1 砖 砖 1 * 1 2 空 砖 2 0 1 空 砖 0 * 1 3 空 砖 3 -1 1 空 砖 -1 * * x:0 x:1 * _ _ * |_|_| y:0 ---> 这一行没有内容,只是说明这上面还有一行 * |_|*| y:1 ---> *是旋转中心 * |_| y:2 * |_| y:3 * * x:-1 * x:0 * x:1 * x:2 * _ _ * _ _|_|_| y:0 ---> *是旋转中心 * |_|_|*|_| y:1 * ↑这一列没有内容,只是说明这一列在旋转前是名义上的第一行 * */ auto center_x = i.y - center.y; auto center_y = i.x - center.x; i.x = center.x - center_x; i.y = center.y + center_y; } if (!check()) { /* 旋转超界 */ for (auto i = 0; i < 4; i++) { a[i] = b[i]; /* 旋转取消,回档 */ } } } /* 图形下降 */ if (timer > delay) { for (auto i = 0; i < 4; i++) { b[i] = a[i]; /* 储存当前位置 */ a[i].y += 1; /* 图形下降一格 */ } if (!check()) { /* 图形越界(即图形已经下降到不能下降的位置) */ /* 一个图形结束 */ for (auto& i : b) /* 将b中备份的坐标对应在场上的位置用对应颜色标记,不然后面无法绘制图形,图形会凭空消失 */ { game_field[i.y][i.x] = color_num; } /* 新出现一个图形 */ /* 重设颜色 */ color_num = 1 + rand() % 7; /* 重设形状 */ n = rand() % 7; for (auto i = 0; i < 4; i++) { a[i].x = figures[n][i] % 2 + mid_field_rows; a[i].y = figures[n][i] / 2; } } timer = 0; /* 重置计时器 */ } /* 检查消除 */ auto base_line = field_lines - 1; /* 从最底下一行开始往上进行逐行判断 */ for (auto line = field_lines - 1; line > 0; line--) { /* 第一行不用判断了,因为如果仅剩一行空间图形出现就应该直接游戏结束 */ auto is_eliminated = true; for (auto row = 0; row < field_rows; row++) { if (!game_field[line][row]) { /* 一旦有一格为空则无法消除 */ is_eliminated = false; } /* 将第line行搬动至baseLine行 */ game_field[base_line][row] = game_field[line][row]; } if (!is_eliminated) { /* 未消除则 baseLine不变,判断上一行(这样上面的搬动可以保证总会将图形下降至最底下的不可消除的行上) */ base_line--; } else { score++; /* 这个分数暂时没有使用,但是保留了 */ } } /* 重置移动,旋转,周期 */ dx = 0; is_rotate = false; delay = 0.3; window.clear(Color::White); window.draw(background); /* 绘制场上已经被color_num标记的图形 */ for (auto line = 0; line < field_lines; line++) { for (auto row = 0; row < field_rows; row++) { if (!game_field[line][row]) { /* 如果这个格子为空则不进行绘制 */ continue; } tiles.setTextureRect(IntRect(game_field[line][row] * 18, 0, 18, 18)); tiles.setPosition(float(row * 18), float(line * 18)); tiles.move(28, 31); // 偏移 window.draw(tiles); } } /* 绘制当前正在操作的图形 */ for (auto& i : a) { tiles.setTextureRect(IntRect(color_num * 18 /* 根据colorNum从tiles.png中截取对应的图形 */, 0, 18, 18)); tiles.setPosition(float(i.x) * 18, float(i.y) * 18); tiles.move(28, 31); window.draw(tiles); } window.draw(frame); window.display(); } return 0; } solutions/LeetCode/C++/288.cpp __________________________________________________________________________________________________ class ValidWordAbbr { public: ValidWordAbbr(vector &dictionary) { for (auto a : dictionary) { string k = a[0] + to_string(a.size() - 2) + a.back(); m[k].insert(a); } } bool isUnique(string word) { string k = word[0] + to_string(word.size() - 2) + word.back(); return m[k].count(word) == m[k].size(); } private: unordered_map> m; }; __________________________________________________________________________________________________ class ValidWordAbbr { public: ValidWordAbbr(vector &dictionary) { for (auto a : dictionary) { string k = a[0] + to_string(a.size() - 2) + a.back(); if (m.find(k) != m.end() && m[k] != a) m[k] = ""; else m[k] = a; } } bool isUnique(string word) { string k = word[0] + to_string(word.size() - 2) + word.back(); return m.find(k) == m.end() || m[k] == word; } private: unordered_map m; }; __________________________________________________________________________________________________ sjj118/OI-Code #include #include #include #define rep(i,x,y) for(int i=(x);i<=(y);++i) #define per(i,x,y) for(int i=(x);i>=(y);--i) using std::max; using std::swap; using std::fabs; typedef long long LL; typedef double real; const int N=4e4+10,n=39989,inf=1e9,P=N<<2; const real eps=1e-10; inline int dblcmp(real x){if(fabs(x)0?1:-1;} int m,ans,ps; struct Point{ real x,y; Point(){} Point(real x,real y):x(x),y(y){} friend Point operator+(const Point&a,const Point&b){return Point(a.x+b.x,a.y+b.y);} friend Point operator-(const Point&a,const Point&b){return Point(a.x-b.x,a.y-b.y);} friend Point operator*(const Point&a,real b){return Point(a.x*b,a.y*b);} friend Point operator*(real b,const Point&a){return Point(a.x*b,a.y*b);} friend real operator*(const Point&a,const Point&b){return a.x*b.x+a.y*b.y;} friend real operator%(const Point&a,const Point&b){return a.x*b.y-a.y*b.x;} }; struct Line{ Point p,v; int id; Line(){} Line(int id,const Point&p,const Point&v):id(id),p(p),v(v){} friend Point operator*(const Line&a,const Line&b){ real t=b.v%(a.p-b.p)/(a.v%b.v); return a.p+t*a.v; } real operator()(real x)const{ if(!id)return 0; if(fabs(v.x)>1; if(p.x+eps<=m)insert(ll,rr,data[k],ls,l,m),data[k]=v; else insert(ll,rr,v,rs,m+1,r); }else if(t1==0&&t2==1){ Point p=data[k]*v; int m=(l+r)>>1; if(p.x+eps<=m)insert(ll,rr,v,ls,l,m); else insert(ll,rr,data[k],rs,m+1,r),data[k]=v; } return; } int m=(l+r)>>1; if(ll<=m)insert(ll,rr,v,ls,l,m); if(rr>m)insert(ll,rr,v,rs,m+1,r); } Line query(int p,int k,int l,int r){ if(l==r)return data[k]; int m=(l+r)>>1; if(p<=m)return higher(p,data[k],query(p,ls,l,m)); else return higher(p,data[k],query(p,rs,m+1,r)); } }T; int main(){ //freopen("code.in","r",stdin); scanf("%d",&m); rep(i,1,m){ int op;scanf("%d",&op); if(op){ int x1,y1,x2,y2;scanf("%d%d%d%d",&x1,&y1,&x2,&y2); x1=(x1+ans-1)%n+1;y1=(y1+ans-1)%inf+1; x2=(x2+ans-1)%n+1;y2=(y2+ans-1)%inf+1; if(x1>x2)swap(x1,x2),swap(y1,y2); if(x1==x2)y1=y2=max(y1,y2); T.insert(x1,x2,Line(++ps,Point(x1,y1),Point(x2-x1,y2-y1)),1,1,n); }else{ int x;scanf("%d",&x); x=(x+ans-1)%n+1; printf("%d\n",ans=T.query(x,1,1,n).id); } } return 0; } AnthonyM/service-fabricsrc/prod/src/Reliability/Failover/ra/ReconfigurationHealthState.cpp // ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ #include "Ra.Stdafx.h" using namespace std; using namespace Reliability; using namespace ReconfigurationAgentComponent; using namespace Health; ReconfigurationHealthState::ReconfigurationHealthState(const FailoverUnitId * failoverUnitId, Reliability::ServiceDescription * serviceDescription, int64 * localReplicaId, int64 * localReplicaInstanceId) : failoverUnitId_(failoverUnitId), serviceDesc_(serviceDescription), localReplicaId_(localReplicaId), localReplicaInstanceId_(localReplicaInstanceId) { } ReconfigurationAgentComponent::ReconfigurationHealthState::ReconfigurationHealthState(const FailoverUnitId * failoverUnitId, Reliability::ServiceDescription * serviceDescription, int64 * localReplicaId, int64 * localReplicaInstanceId, ReconfigurationHealthState const & other) : failoverUnitId_(failoverUnitId), serviceDesc_(serviceDescription), localReplicaId_(localReplicaId), localReplicaInstanceId_(localReplicaInstanceId), currentReport_(other.currentReport_) { } void ReconfigurationHealthState::OnPhaseChanged(Infrastructure::StateMachineActionQueue & queue, ReconfigurationStuckDescriptorSPtr clearReport) { if (currentReport_) { currentReport_.reset(); IHealthSubsystemWrapper::EnqueueReplicaHealthAction( ReplicaHealthEvent::Enum::ClearReconfigurationStuckWarning, *failoverUnitId_, serviceDesc_->IsStateful, *localReplicaId_, *localReplicaInstanceId_, queue, clearReport); } } void ReconfigurationHealthState::OnReconfigurationPhaseHealthReport(Infrastructure::StateMachineActionQueue & queue, ReconfigurationStuckDescriptorSPtr newReport) { if (!currentReport_ || *newReport != *currentReport_) { currentReport_ = newReport; IHealthSubsystemWrapper::EnqueueReplicaHealthAction( ReplicaHealthEvent::Enum::ReconfigurationStuckWarning, *failoverUnitId_, serviceDesc_->IsStateful, *localReplicaId_, *localReplicaInstanceId_, queue, currentReport_); } } VastoLorde95/Competitive-Programming #include #include #include #include #include #include #include #include #include #include #include #define sd(x) scanf("%d",&x) #define sd2(x,y) scanf("%d%d",&x,&y) #define sd3(x,y,z) scanf("%d%d%d",&x,&y,&z) #define fi first #define se second #define pb(x) push_back(x) #define mp(x,y) make_pair(x,y) #define _ ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL); using namespace std; int n, m, c[100000], visited[100000], u, v, comp; vector adj[100000], rev[100000], scc[100000]; long long MOD = 1000000007, cost, res = 1; stack s; void dfs(int x){ if(visited[x] == 1) return; visited[x] = 1; for(int i = 0; i < adj[x].size(); i++){ dfs(adj[x][i]); } s.push(x); return; } void dfs2(int x, int comp){ if(visited[x] == 1) return; visited[x] = 1; scc[comp].pb(x); // cout << "check " << x << " " << comp << endl; for(int i = 0; i < rev[x].size(); i++){ dfs2(rev[x][i], comp); } return; } void sccomp(){ for(int i = 0; i < n; i++) if(!visited[i]) dfs(i); int cur; for(int i = 0; i < n; i++) visited[i] = 0; while(!s.empty()){ cur = s.top(); s.pop(); if(visited[cur] == 1) continue; // cout << cur << endl; dfs2(cur, comp); comp++; } return; } int main(){ sd(n); for(int i = 0; i < n; i++){ sd(c[i]); } sd(m); for(int i = 0; i < m; i++){ sd2(u,v); u--, v--; adj[u].pb(v); rev[v].pb(u); } sccomp(); for(int i = 0; i < comp; i++){ int mn = 1000000001; long long cnt = 1; for(int j = 0; j < scc[i].size(); j++){ if(c[scc[i][j]] < mn){ mn = c[scc[i][j]]; cnt = 1; } else if(c[scc[i][j]] == mn){ cnt++; } } // cout << mn << " " << cnt << endl; cost += mn; res = (res*cnt)%MOD; } cout << cost << " " << res << endl; return 0; } /*! * @file * This file contains an adaptation of the Boost.Fusion pair for use within * the Boost.MPL. */ #ifndef BOOST_MPL_FUSION_PAIR_HPP #define BOOST_MPL_FUSION_PAIR_HPP #include #include namespace boost { namespace mpl { template struct first > : fusion::result_of::first > { }; template struct first const> : fusion::result_of::first const> { }; template struct second > : fusion::result_of::second > { }; template struct second const> : fusion::result_of::second const> { }; }} #endif // !BOOST_MPL_FUSION_PAIR_HPP #include #include #include int main( int argc, char **argv){ int execution_space_gpu = 0; if (argc > 1){ fprintf(stderr,"argv[0] = %s\n",argv[1]); execution_space_gpu = atoi(argv[1]); } int N = 1024*1024*100; int Niter = 10; float *A, *B; A = new float[N]; B = new float[N]; double GB = (double)N * sizeof(float) / (1024.0*1024.0*1024.0); int ndevices = omp_get_device_num(); printf("ndevices= %d\n",ndevices); int cpuid[omp_get_max_threads()]; #pragma omp parallel { cpuid[ omp_get_thread_num()] = sched_getcpu(); } for (int i=0; i < omp_get_max_threads(); ++i) printf("tid = %d, cpuid = %d\n",i,cpuid[i]); #pragma omp parallel for for (int i=0; i < N; ++i){ A[i] = i*0.0001; B[i] = 0.0; } #pragma omp target enter data map(to:A[0:N],B[0:N]) if(execution_space_gpu) #pragma omp target teams distribute parallel for thread_limit(512) num_teams(120*10) schedule(static,1) if(target:execution_space_gpu) for (int i=0; i < N; ++i) B[i] = omp_get_thread_num(); #if 1 #pragma omp target update from(B[0:N]) if(execution_space_gpu) for (int i=0; i < 70*1; i+=1) printf(" B[%d] = %g\n",i,B[i]); #endif double t1 = omp_get_wtime(); for (int iter = 0 ; iter < Niter; ++iter){ #pragma omp target teams distribute parallel for if(target:execution_space_gpu) for (int i=0; i < N; ++i) B[i] = A[i]; } double t2 = omp_get_wtime(); printf("memcpy time = %g [s] BW = %g [GB/s]\n",(t2-t1)/Niter, 2.0*GB/((t2-t1)/Niter)); #pragma omp target exit data map(release:A[0:N]) map(from:B[0:N]) if(execution_space_gpu) for (int i=0; i < 10; ++i) printf("A[%d] = %g, B[%d] = %g\n",i,A[i],i,B[i]); delete[] A; delete[] B; return 0; } util/include/callback_registry.hpp // Concord // // Copyright (c) 2020 VMware, Inc. All Rights Reserved. // // This product is licensed to you under the Apache 2.0 license (the "License"). // You may not use this product except in compliance with the Apache 2.0 // License. // // This product may include a number of subcomponents with separate copyright // notices and license terms. Your use of these subcomponents is subject to the // terms and conditions of the subcomponent's license, as noted in the // LICENSE file. #pragma once #include #include #include #include #include #include namespace concord::util { // A move-only opaque callback handle. Supports callback invocation. template class GenericCallbackHandle { public: GenericCallbackHandle(const GenericCallbackHandle&) = delete; GenericCallbackHandle& operator=(const GenericCallbackHandle&) = delete; // Move-constructs a handle. Throws an exception if 'other' is invalid. GenericCallbackHandle(GenericCallbackHandle&& other) { *this = std::move(other); } // Move-assigns a handle. Throws an exception if 'other' is invalid. GenericCallbackHandle& operator=(GenericCallbackHandle&& other) { // If moving to self, treat as a no-op. if (this != &other) { if (other.iter_.has_value()) { iter_ = std::move(other.iter_); // Make sure we reset() the std::optional as moving from it only moves the contained value and leaves the // std::optional itself with a value. other.iter_.reset(); } else { throw std::invalid_argument{"Move operation on CallbackHandle called with an invalid handle"}; } } return *this; } // Invokes the callback if the handle is valid. Throws an exception if the handle is invalid. template void invoke(InvokeArgs&&... args) const { if (iter_.has_value()) { (*iter_)->operator()(std::forward(args)...); } else { throw std::logic_error{"invoke() called on an invalid CallbackHandle"}; } } bool operator==(const GenericCallbackHandle& other) const { return (iter_.has_value() && other.iter_.has_value() && iter_ == other.iter_); } bool operator!=(const GenericCallbackHandle& other) const { return !(*this == other); } bool valid() const { return iter_.has_value(); } private: GenericCallbackHandle(Iterator iter) : iter_{iter} {}; private: std::optional iter_; template friend class CallbackRegistry; }; // A callback registry that supports adding, removing and invoking callbacks. Supports arbitrary // callback parameters. Callback return type is void. template class CallbackRegistry { private: // Use an std::list in order to preserve iterators in handles after erase() calls. using Callback = std::function; using CallbackContainer = std::list; using Iterator = typename CallbackContainer::const_iterator; public: using CallbackHandle = GenericCallbackHandle; CallbackRegistry() = default; CallbackRegistry(const CallbackRegistry&) = delete; CallbackRegistry& operator=(const CallbackRegistry&) = delete; // Registers a callback and returns a handle to it. Handles are only valid for the registry instance that created // them. Additionally, handles are invalidated when the registry is destructed. Using handles across registries or // after their corresponding registry has been destructed causes undefined bahavior. template CallbackHandle add(Func&& callback) { callbacks_.emplace_back(std::forward(callback)); auto it = callbacks_.cend(); return --it; } // Removes a registered callback. If the passed handle is invalid, an exception is thrown. void remove(CallbackHandle handle) { if (handle.iter_.has_value()) { callbacks_.erase(*handle.iter_); } else { throw std::invalid_argument{"CallbackRegistry::remove() called with an invalid CallbackHandle"}; } } // Invokes all callbacks in the registry. Exceptions from callbacks are propagated to callers of this method. // Invocation stops at the first exception thrown, without invoking further callbacks. template void invokeAll(InvokeArgs&&... args) const { for (auto& callback : callbacks_) { callback(std::forward(args)...); } } bool empty() const { return callbacks_.empty(); } std::size_t size() const { return callbacks_.size(); } private: CallbackContainer callbacks_; }; } // namespace concord::util // Copyright 1998-2016 Epic Games, Inc. All Rights Reserved. #include "ScriptPluginPrivatePCH.h" ////////////////////////////////////////////////////////////////////////// UScriptContextComponent::UScriptContextComponent(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { PrimaryComponentTick.bCanEverTick = true; bTickInEditor = false; bAutoActivate = true; bWantsInitializeComponent = true; Context = NULL; } void UScriptContextComponent::OnRegister() { Super::OnRegister(); auto ContextOwner = GetOuter(); if (ContextOwner && !HasAnyFlags(RF_ClassDefaultObject) && !ContextOwner->HasAnyFlags(RF_ClassDefaultObject)) { auto ScriptClass = UScriptBlueprintGeneratedClass::GetScriptGeneratedClass(ContextOwner->GetClass()); if (ScriptClass && GetWorld() && GetWorld()->WorldType != EWorldType::Editor) { Context = FScriptContextBase::CreateContext(ScriptClass->SourceCode, ScriptClass, ContextOwner); if (!Context || !Context->CanTick()) { bAutoActivate = false; PrimaryComponentTick.bCanEverTick = false; } } } } void UScriptContextComponent::InitializeComponent() { Super::InitializeComponent(); if (Context) { auto ContextOwner = GetOuter(); auto ScriptClass = UScriptBlueprintGeneratedClass::GetScriptGeneratedClass(ContextOwner->GetClass()); check(ScriptClass); Context->PushScriptPropertyValues(ScriptClass, ContextOwner); Context->BeginPlay(); Context->FetchScriptPropertyValues(ScriptClass, ContextOwner); } } void UScriptContextComponent::TickComponent(float DeltaTime, enum ELevelTick TickType, FActorComponentTickFunction *ThisTickFunction) { Super::TickComponent(DeltaTime, TickType, ThisTickFunction); if (Context) { auto ContextOwner = GetOuter(); auto ScriptClass = UScriptBlueprintGeneratedClass::GetScriptGeneratedClass(ContextOwner->GetClass()); check(ScriptClass); Context->PushScriptPropertyValues(ScriptClass, ContextOwner); Context->Tick(DeltaTime); Context->FetchScriptPropertyValues(ScriptClass, ContextOwner); } }; void UScriptContextComponent::BeginDestroy() { if (Context) { Context->Destroy(); delete Context; Context = NULL; } Super::BeginDestroy(); } void UScriptContextComponent::CallScriptFunction(FString FunctionName) { if (Context) { auto ContextOwner = GetOuter(); auto ScriptClass = UScriptBlueprintGeneratedClass::GetScriptGeneratedClass(ContextOwner->GetClass()); check(ScriptClass); Context->PushScriptPropertyValues(ScriptClass, ContextOwner); Context->CallFunction(FunctionName); Context->FetchScriptPropertyValues(ScriptClass, ContextOwner); } } #include "icon.h" using namespace Tempest; Icon::Icon() { } Icon::Icon(const Pixmap &pm, TextureAtlas &atl) { Sprite norm = atl.load(pm); set(ST_Normal,norm); const uint32_t w = pm.w(), h = pm.h(); Pixmap dst = Pixmap(w,h,pm.format()); const uint8_t* p = reinterpret_cast(pm.data()); uint8_t* d = reinterpret_cast(dst.data()); switch(pm.format()) { case Pixmap::Format::RGB: { for(uint32_t r=0; rw()w()==emplace.w() && ret->h()w()w()==i.w() && ret->h()w()<=w && ret->h()<=h ) return *ret; return emplace; } void Icon::SzArray::set(const Sprite &s) { if( emplace.size().isEmpty() || emplace.size()==s.size() ) { emplace=s; return; } for(auto& i:data) if(i.size()==s.size()){ i=s; return; } data.emplace_back(s); } Include/Plane.hpp #pragma once #include #include #include "Vector.hpp" class Plane { public: Plane(); ~Plane(); Vector3& GetPosition(); Angle3& GetRotation(); Vector3& GetScale(); void Draw(); private: Vector3 vertices[4]; Vector2 uvCoords[4]; Vector3 position; Angle3 rotation; Vector3 scale = Vector3(1.f, 1.f, 1.f); };// // Underlying iLQRNode for Tree-iLQR. // // () // December 2016 // #pragma once #include #include #include #include #include #include namespace ilqr { // Each plan node represents a timestep. class iLQRNode { public: iLQRNode(const int state_dim, const int control_dim, const DynamicsFunc &dynamics_func, const CostFunc &cost_func, const double probablity); iLQRNode(const Eigen::VectorXd &x_star, const Eigen::VectorXd &u_star, const DynamicsFunc &dynamics_func, const CostFunc &cost_func, const double probablity); // Compute the control policy and quadratic value of the node given the next // timestep value. The policy and value are set directly in the node. //void bellman_backup(const QuadraticValue& Jt1); void bellman_backup(const std::vector> &children); // Computes a feedback control from state xt. Eigen::VectorXd compute_control(const Eigen::VectorXd &xt) const; // Computes a feedback control from state xt except moving only "alpha" step-size away from the // expansion point u(). Eigen::VectorXd compute_control(const Eigen::VectorXd &xt, const double alpha) const; // Get and set the probability double probability() const { return probability_; } void set_probability(double p) { probability_ = p; } DynamicsFunc& dynamics_func() { return dynamics_func_; } CostFunc& cost_func() { return cost_func_; } const DynamicsFunc& dynamics_func() const { return dynamics_func_; } const CostFunc& cost_func() const { return cost_func_; } // Current Taylor expansion points x and u. Eigen::VectorXd& x() { return x_; } Eigen::VectorXd& u() { return u_; } const Eigen::VectorXd& x() const { return x_; } const Eigen::VectorXd& u() const { return u_; } // Original Taylor expansion points x and u. Eigen::VectorXd& orig_xstar() { return orig_xstar_; } Eigen::VectorXd& orig_ustar() { return orig_ustar_; } const Eigen::VectorXd& orig_xstar() const { return orig_xstar_; } const Eigen::VectorXd& orig_ustar() const { return orig_ustar_; } const QuadraticValue& value() const { return J_; }; QuadraticValue& value() { return J_; }; const Eigen::MatrixXd& K() const { return K_; }; Eigen::MatrixXd& K() { return K_; }; const Eigen::VectorXd& k() const { return k_; }; Eigen::VectorXd& k() { return k_; }; private: DynamicsFunc dynamics_func_; CostFunc cost_func_; // Set point used for linearization of THIS node's cost and // all CHILD node dynamics. Eigen::VectorXd x_; Eigen::VectorXd u_; // Probability of transitioning to this node from the parent. double probability_; // The terms of the quadratic value function, 1/2 * x^T V x + Gx + W. QuadraticValue J_; // Feedback gain matrix on the extended-state, [dim(u)] x [dim(x) + 1] Eigen::MatrixXd K_; // Feed-forward control matrix, [dim(u)] x [dim(1)]. Eigen::VectorXd k_; // Original nominal state specified at the beginning of iLQR. [dim(x)] x [1] Eigen::VectorXd orig_xstar_; // Original nominal control specified at the beginning of iLQR. [dim(u)] x [1] Eigen::VectorXd orig_ustar_; }; // Allows the iLQRNode to be printed. std::ostream& operator<<(std::ostream& os, const ilqr::iLQRNode& node); } // namespace ilqr #include "server.h" // #include "paxos_worker.h" #include "exec.h" namespace janus { void PaxosServer::OnPrepare(slotid_t slot_id, ballot_t ballot, ballot_t *max_ballot, const function &cb) { std::lock_guard lock(mtx_); Log_debug("multi-paxos scheduler receives prepare for slot_id: %llx", slot_id); auto instance = GetInstance(slot_id); verify(ballot != instance->max_ballot_seen_); if (instance->max_ballot_seen_ < ballot) { instance->max_ballot_seen_ = ballot; } else { // TODO if accepted anything, return; verify(0); } *max_ballot = instance->max_ballot_seen_; n_prepare_++; cb(); } void PaxosServer::OnAccept(const slotid_t slot_id, const ballot_t ballot, shared_ptr &cmd, ballot_t *max_ballot, const function &cb) { std::lock_guard lock(mtx_); Log_debug("multi-paxos scheduler accept for slot_id: %llx", slot_id); auto instance = GetInstance(slot_id); verify(instance->max_ballot_accepted_ < ballot); if (instance->max_ballot_seen_ <= ballot) { instance->max_ballot_seen_ = ballot; instance->max_ballot_accepted_ = ballot; } else { // TODO verify(0); } *max_ballot = instance->max_ballot_seen_; n_accept_++; cb(); } void PaxosServer::OnCommit(const slotid_t slot_id, const ballot_t ballot, shared_ptr &cmd) { std::lock_guard lock(mtx_); Log_debug("multi-paxos scheduler decide for slot: %lx", slot_id); auto instance = GetInstance(slot_id); instance->committed_cmd_ = cmd; if (slot_id > max_committed_slot_) { max_committed_slot_ = slot_id; } verify(slot_id > max_executed_slot_); // This prevents the log entry from being applied twice if (in_applying_logs_) { return; } in_applying_logs_ = true; for (slotid_t id = max_executed_slot_ + 1; id <= max_committed_slot_; id++) { auto next_instance = GetInstance(id); if (next_instance->committed_cmd_) { app_next_(*next_instance->committed_cmd_); Log_debug("multi-paxos par:%d loc:%d executed slot %lx now", partition_id_, loc_id_, id); max_executed_slot_++; n_commit_++; } else { break; } } // TODO should support snapshot for freeing memory. // for now just free anything 1000 slots before. int i = min_active_slot_; while (i + 1000 < max_executed_slot_) { logs_.erase(i); i++; } min_active_slot_ = i; in_applying_logs_ = false; } } // namespace janus 1-10 #include "solution.h" #include "support.h" #include "test.h" namespace LeetcodeTest { LEETCODE_TEST(countAndSays) { std::string results[] = { "1", "11", "21", "1211", "111221", "312211", "13112221", "1113213211", "31131211131221", "13211311123113112211"}; for (int i = 1; i <= 10; i++) { EXPECT_STREQ(results[i - 1].c_str(), Instance().countAndSay(i).c_str()); } } } // namespace LeetcodeTest TheH0bbit/autopas_dem0 /** * @file ActiveHarmonyTest.cpp * @author * @date 14.11.19 */ #include "ActiveHarmonyTest.h" #include #include #include using namespace std; // shortened type names typedef unsigned long long ull; typedef vector vi; typedef pair pi; // macros #define F first #define S second #define PB push_back #define MP make_pair #define REP(i, a, b) for (int i = a; i < b; i++) #define REPI(i, a, b) for (int i = a; i <= b; i++) void print_vector(vector v) { for (int i = 0; i < v.size(); i++) { cout << v[i] << " "; } cout << "\n"; } void read_array(vector & v, int n) { int num; while (n--) { cin >> num; v.push_back(num); } } // nodes: [weight, idx] // edges: [idx1, idx2] vector k_colorings(int n, vector>& nodes, vector>& edges) { sort(nodes.begin(), nodes.end(), greater>()); ull wsum = 0; for (auto [weight, idx] : nodes) wsum += weight; unordered_map freeEdges; for (auto [i, j] : edges) { freeEdges[i]++; freeEdges[j]++; } for (auto& p : freeEdges) { p.second--; // printf("%d, %d\n", p.first, p.second); } int start = 0; vector kvals {wsum}; for (int k = 2; k <= n-1; k++) { auto [weight, idx] = nodes[start]; while (start < n && freeEdges[idx] <= 0) { start++; auto [w, i] = nodes[start]; weight = w; idx = i; } freeEdges[idx]--; // printf("[%d, %d]\n", idx, weight); wsum += weight; kvals.push_back(wsum); } return kvals; } int main() { ios::sync_with_stdio(0); cin.tie(0); int tests; cin >> tests; REP(tt, 0, tests) { // code here vector weights; int n; cin >> n; read_array(weights, n); vector> nodes; // [weight, idx] for (int i = 0; i < n; i++) { nodes.push_back({weights[i], i+1}); } vector> edges; for (int i = 0; i < n-1; i++) { int idx1, idx2; cin >> idx1 >> idx2; edges.push_back({idx1,idx2}); } auto res = k_colorings(n, nodes, edges); print_vector(res); } cout.flush(); return 0; }#pragma once // a/b 以下の最大の整数 long long floor(long long a, long long b) { assert(b != 0); if (b < 0) a = -a, b = -b; return a / b - (a % b < 0); } // a/b 未満の最大の整数 long long under(long long a, long long b) { assert(b != 0); if (b < 0) a = -a, b = -b; return a / b - (a % b <= 0); } // a/b 以上の最小の整数 long long ceil(long long a, long long b) { assert(b != 0); if (b < 0) a = -a, b = -b; return a / b + (a % b > 0); } // a/b 超過の最小の整数 long long over(long long a, long long b) { assert(b != 0); if (b < 0) a = -a, b = -b; return a / b + (a % b >= 0); } // a mod b (b > 0) long long modulo(long long a, long long b) { assert(b >= 0); long long c = a % b; return c < 0 ? c + b : c; } ballisticwhisper/boost /* * Copyright 2007 - 2013. * 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) */ /*! * \file event.cpp * \author * \date 24.07.2011 * * \brief This header is the Boost.Log library implementation, see the library documentation * at http://www.boost.org/doc/libs/release/libs/log/doc/html/index.html. */ #include #ifndef BOOST_LOG_NO_THREADS #include #include #include #include #include #include #if defined(BOOST_LOG_EVENT_USE_POSIX_SEMAPHORE) #if defined(__GNUC__) && defined(__GCC_HAVE_SYNC_COMPARE_AND_SWAP_4) #define BOOST_LOG_EVENT_TRY_SET(ref) (__sync_lock_test_and_set(&ref, 1U) == 0U) #define BOOST_LOG_EVENT_RESET(ref) __sync_lock_release(&ref) #else #error Boost.Log internal error: BOOST_LOG_EVENT_USE_POSIX_SEMAPHORE must only be defined when atomic ops are available #endif #include #include #elif defined(BOOST_LOG_EVENT_USE_WINAPI) #include "windows_version.hpp" #include #include #else #include #endif #include namespace boost { BOOST_LOG_OPEN_NAMESPACE namespace aux { #if defined(BOOST_LOG_EVENT_USE_POSIX_SEMAPHORE) //! Default constructor BOOST_LOG_API sem_based_event::sem_based_event() : m_state(0U) { if (sem_init(&m_semaphore, 0, 0) != 0) { const int err = errno; BOOST_THROW_EXCEPTION(system::system_error( err, system::system_category(), "Failed to initialize semaphore")); } } //! Destructor BOOST_LOG_API sem_based_event::~sem_based_event() { BOOST_VERIFY(sem_destroy(&m_semaphore) == 0); } //! Waits for the object to become signalled BOOST_LOG_API void sem_based_event::wait() { while (true) { if (sem_wait(&m_semaphore) != 0) { const int err = errno; if (err != EINTR) { BOOST_THROW_EXCEPTION(system::system_error( err, system::system_category(), "Failed to block on the semaphore")); } } else break; } BOOST_LOG_EVENT_RESET(m_state); } //! Sets the object to a signalled state BOOST_LOG_API void sem_based_event::set_signalled() { if (BOOST_LOG_EVENT_TRY_SET(m_state)) { if (sem_post(&m_semaphore) != 0) { const int err = errno; BOOST_LOG_EVENT_RESET(m_state); BOOST_THROW_EXCEPTION(system::system_error( err, system::system_category(), "Failed to wake the blocked thread")); } } } #elif defined(BOOST_LOG_EVENT_USE_WINAPI) //! Default constructor BOOST_LOG_API winapi_based_event::winapi_based_event() : m_state(0), m_event(CreateEventA(NULL, false, false, NULL)) { if (!m_event) { const DWORD err = GetLastError(); BOOST_THROW_EXCEPTION(system::system_error( err, system::system_category(), "Failed to create Windows event")); } } //! Destructor BOOST_LOG_API winapi_based_event::~winapi_based_event() { BOOST_VERIFY(CloseHandle(m_event) != 0); } //! Waits for the object to become signalled BOOST_LOG_API void winapi_based_event::wait() { // On Windows we assume that memory view is always actual (Intel x86 and x86_64 arch) if (const_cast< volatile boost::uint32_t& >(m_state) == 0) { if (WaitForSingleObject(m_event, INFINITE) != 0) { const DWORD err = GetLastError(); BOOST_THROW_EXCEPTION(system::system_error( err, system::system_category(), "Failed to block on Windows event")); } } const_cast< volatile boost::uint32_t& >(m_state) = 0; } //! Sets the object to a signalled state BOOST_LOG_API void winapi_based_event::set_signalled() { if (BOOST_INTERLOCKED_COMPARE_EXCHANGE(reinterpret_cast< long* >(&m_state), 1, 0) == 0) { if (SetEvent(m_event) == 0) { const DWORD err = GetLastError(); const_cast< volatile boost::uint32_t& >(m_state) = 0; BOOST_THROW_EXCEPTION(system::system_error( err, system::system_category(), "Failed to wake the blocked thread")); } } } #else //! Default constructor BOOST_LOG_API generic_event::generic_event() : m_state(false) { } //! Destructor BOOST_LOG_API generic_event::~generic_event() { } //! Waits for the object to become signalled BOOST_LOG_API void generic_event::wait() { boost::unique_lock< boost::mutex > lock(m_mutex); while (!m_state) { m_cond.wait(lock); } m_state = false; } //! Sets the object to a signalled state BOOST_LOG_API void generic_event::set_signalled() { boost::lock_guard< boost::mutex > lock(m_mutex); if (!m_state) { m_state = true; m_cond.notify_one(); } } #endif } // namespace aux BOOST_LOG_CLOSE_NAMESPACE // namespace log } // namespace boost #include #endif // BOOST_LOG_NO_THREADS deniscostadsc/playground10-100 #include #include int main() { float x, y; int16_t n; scanf("%d", &n); while (n--) { scanf("%f %f", &x, &y); if (y == 0.0) { printf("divisao impossivel\n"); } else { printf("%.1f\n", x / y); } } return 0; } // Unit tests for tags // Author: <> #include #include "../../src/launch/launch_config.h" #include "param_utils.h" using namespace rosmon::launch; TEST_CASE("global_param", "[param]") { LaunchConfig config; config.parseString(R"EOF( )EOF"); config.evaluateParameters(); CAPTURE(config.parameters()); auto it = config.parameters().find("/global_param"); REQUIRE(it != config.parameters().end()); XmlRpc::XmlRpcValue value = it->second; REQUIRE(static_cast(value) == "hello_world"); } TEST_CASE("param_types", "[param]") { LaunchConfig config; config.parseString(R"EOF( )EOF"); config.evaluateParameters(); auto& params = config.parameters(); checkTypedParam(params, "/int_param_auto", XmlRpc::XmlRpcValue::TypeInt, 0); checkTypedParam(params, "/int_param_forced", XmlRpc::XmlRpcValue::TypeInt, 0); checkTypedParam(params, "/double_param_auto", XmlRpc::XmlRpcValue::TypeDouble, 0.0); checkTypedParam(params, "/double_param_forced", XmlRpc::XmlRpcValue::TypeDouble, 0.0); checkTypedParam(params, "/str_param_auto", XmlRpc::XmlRpcValue::TypeString, "hello"); checkTypedParam(params, "/str_param_forced", XmlRpc::XmlRpcValue::TypeString, "0"); checkTypedParam(params, "/bool_param_auto", XmlRpc::XmlRpcValue::TypeBoolean, true); checkTypedParam(params, "/bool_param_forced", XmlRpc::XmlRpcValue::TypeBoolean, true); checkTypedParam(params, "/bool_param_auto_nonlowercase", XmlRpc::XmlRpcValue::TypeBoolean, true); checkTypedParam(params, "/bool_param_forced_nonlowercase", XmlRpc::XmlRpcValue::TypeBoolean, true); checkTypedParam(params, "/yaml_param/test_param", XmlRpc::XmlRpcValue::TypeBoolean, true); checkTypedParam(params, "/yaml_param_scalar", XmlRpc::XmlRpcValue::TypeBoolean, true); } TEST_CASE("param command", "[param]") { LaunchConfig config; config.parseString(R"EOF( )EOF"); config.evaluateParameters(); auto& params = config.parameters(); checkTypedParam(params, "/test", XmlRpc::XmlRpcValue::TypeString, "hello_world"); checkTypedParam(params, "/multiline", XmlRpc::XmlRpcValue::TypeString, "hello\nworld"); checkTypedParam(params, "/yaml_param/test_param", XmlRpc::XmlRpcValue::TypeBoolean, true); } TEST_CASE("param failing command", "[param]") { LaunchConfig config; config.parseString(R"EOF()EOF"); REQUIRE_THROWS_AS( config.evaluateParameters(), ParseException ); } TEST_CASE("param textfile", "[param]") { LaunchConfig config; config.parseString(R"EOF( )EOF"); config.evaluateParameters(); auto& params = config.parameters(); checkTypedParam(params, "/test", XmlRpc::XmlRpcValue::TypeString, "hello_world"); } TEST_CASE("param textfile does not exist", "[param]") { using Catch::Matchers::Contains; LaunchConfig config; config.parseString(R"EOF( )EOF"); REQUIRE_THROWS_WITH( config.evaluateParameters(), Contains("file") ); } TEST_CASE("param binfile", "[param]") { LaunchConfig config; config.parseString(R"EOF( )EOF"); config.evaluateParameters(); auto& params = config.parameters(); CAPTURE(params); auto it = params.find("/test"); REQUIRE(it != params.end()); XmlRpc::XmlRpcValue value = it->second; REQUIRE(value.getType() == XmlRpc::XmlRpcValue::TypeBase64); std::string expectedData = "hello_world"; auto& data = static_cast(value); REQUIRE(expectedData.size() == data.size()); for(std::size_t i = 0; i < expectedData.size(); ++i) REQUIRE(data[i] == expectedData[i]); } TEST_CASE("scoped params", "[param]") { std::stringstream warnings; LaunchConfig config; config.setWarningOutput(&warnings); config.parseString(R"EOF( )EOF"); config.evaluateParameters(); auto& params = config.parameters(); checkTypedParam(params, "/global/param", XmlRpc::XmlRpcValue::TypeString, "abc"); checkTypedParam(params, "/global/param2", XmlRpc::XmlRpcValue::TypeString, "def"); checkTypedParam(params, "/namespace/test", XmlRpc::XmlRpcValue::TypeString, "val1"); checkTypedParam(params, "/test2", XmlRpc::XmlRpcValue::TypeString, "val2"); checkTypedParam(params, "/test_node/private", XmlRpc::XmlRpcValue::TypeString, "val3"); checkTypedParam(params, "/test_node/private2", XmlRpc::XmlRpcValue::TypeString, "val4"); checkTypedParam(params, "/test_node/leading_slash", XmlRpc::XmlRpcValue::TypeString, "val5"); CAPTURE(warnings.str()); CHECK(warnings.str().find("leading slash") != std::string::npos); } TEST_CASE("scoped params with double slash (#49)", "[param]") { LaunchConfig config; config.parseString(R"EOF( )EOF"); config.evaluateParameters(); auto& params = config.parameters(); checkTypedParam(params, "/param1", XmlRpc::XmlRpcValue::TypeString, "hello"); checkTypedParam(params, "/racecar/test_node/private_param", XmlRpc::XmlRpcValue::TypeString, "hello again"); } TEST_CASE("wrong param types", "[param]") { REQUIRE_THROWS_AS( LaunchConfig().parseString(R"EOF()EOF"), ParseException ); REQUIRE_THROWS_AS( LaunchConfig().parseString(R"EOF()EOF"), ParseException ); REQUIRE_THROWS_AS( LaunchConfig().parseString(R"EOF()EOF"), ParseException ); REQUIRE_THROWS_AS( LaunchConfig().parseString(R"EOF()EOF"), ParseException ); { LaunchConfig config; config.parseString(R"EOF()EOF"); REQUIRE_THROWS_AS( config.evaluateParameters(), ParseException ); } REQUIRE_THROWS_AS( LaunchConfig().parseString(R"EOF()EOF"), ParseException ); } TEST_CASE("invalid param input combinations", "[param]") { REQUIRE_THROWS_AS( LaunchConfig().parseString(R"EOF()EOF"), ParseException ); REQUIRE_THROWS_AS( LaunchConfig().parseString(R"EOF()EOF"), ParseException ); REQUIRE_THROWS_AS( LaunchConfig().parseString(R"EOF()EOF"), ParseException ); } TEST_CASE("invalid param names", "[param]") { using Catch::Matchers::Contains; REQUIRE_THROWS_WITH( LaunchConfig().parseString(R"EOF()EOF"), Contains("$%*") ); REQUIRE_THROWS_WITH( LaunchConfig().parseString(R"EOF()EOF"), Contains("name") ); } TEST_CASE("param whitespace", "[param]") { LaunchConfig config; config.parseString(R"EOF( )EOF"); config.evaluateParameters(); auto& params = config.parameters(); using V = XmlRpc::XmlRpcValue; CHECK(getTypedParam(params, "/string", V::TypeString) == "0.5"); CHECK(getTypedParam(params, "/double", V::TypeDouble) == Approx(0.5)); CHECK(getTypedParam(params, "/auto_string", V::TypeString) == "Hallo"); CHECK(getTypedParam(params, "/auto_double", V::TypeDouble) == Approx(0.6)); CHECK(getTypedParam(params, "/auto_int", V::TypeInt) == 6); CHECK(getTypedParam(params, "/auto_bool", V::TypeBoolean) == true); CHECK(getTypedParam(params, "/command_param_string", V::TypeString) == " Hallo \n"); CHECK(getTypedParam(params, "/command_param_double", V::TypeDouble) == Approx(1.23)); CHECK(getTypedParam(params, "/multiple_lines1", V::TypeString) == "first_line second_line"); CHECK(getTypedParam(params, "/multiple_lines2", V::TypeString) == "first_line second_line"); } 1-10 #include #include void insertSort(int a[], int n) { int i =1; while (i= 0; j--) { if(a[key] < a[j]) { std::swap(a[j], a[key]); key = j; } } i++; }else{ i++; } } } int main() { using std::chrono::high_resolution_clock; using std::chrono::duration; int a[100000]; int n = sizeof(a) / sizeof(*a); for (int i = 0; i < n; i++) { a[i] = rand(); } std::cout<<"Start Time.................................."<<"\n"; auto t1 = high_resolution_clock::now(); insertSort(a, n); auto t2 = high_resolution_clock::now(); std::cout<<"End Time.................................."<<"\n"; duration ms_double = t2 - t1; std::cout << float(ms_double.count()/1000) << "s"; std::cout << "\n"; }// Program for printing all possible words from code digit. #include using namespace std; string keypadArr[] = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqra", "tuv", "wxyz"}; void keypad(string s, string ans) { if(s.length() == 0) { cout< #include "itkImage.h" #include "itkCannyEdgeDetectionImageFilter.h" #include "itkImageFileReader.h" #include "itkImageFileWriter.h" #include "itkVector.h" #include "itkSimpleFilterWatcher.h" #include "itkRescaleIntensityImageFilter.h" // This test is was written to test bug 9431 // // It run a filter multiple times and expects the output to be the // same when run with the same parameters. The two output images // should be identical int itkCannyEdgeDetectionImageFilterTest2(int argc, char * argv[] ) { if(argc < 4) { std::cerr << "Usage: " << argv[0] << " InputImage OutputImage1 OutputImage2\n"; return -1; } const unsigned int dimension = 2; typedef float PixelType; typedef itk::Image InputImage; typedef itk::Image OutputImage; itk::ImageFileReader::Pointer input = itk::ImageFileReader::New(); input->SetFileName(argv[1]); // Set up filter itk::CannyEdgeDetectionImageFilter::Pointer filter = itk::CannyEdgeDetectionImageFilter::New(); filter->SetInput(input->GetOutput()); filter->SetVariance(1.0f); filter->SetMaximumError(.01f); filter->SetUpperThreshold(25); filter->SetLowerThreshold(10); itk::RescaleIntensityImageFilter::Pointer rescale = itk::RescaleIntensityImageFilter::New(); rescale->SetInput(filter->GetOutput()); rescale->SetOutputMinimum(0); rescale->SetOutputMaximum(255); itk::ImageFileWriter::Pointer writer; writer = itk::ImageFileWriter::New(); writer->SetInput( rescale->GetOutput() ); try { // Generate test image writer->SetFileName( argv[2] ); writer->Update(); // set canny filter to another value filter->SetUpperThreshold(20); filter->SetLowerThreshold(5); rescale->Update(); // set it back expecting the same results filter->SetUpperThreshold(25); filter->SetLowerThreshold(10); // Generate test image writer->SetFileName( argv[3] ); writer->Update(); } catch(itk::ExceptionObject &err) { (&err)->Print(std::cerr); return EXIT_FAILURE; } return EXIT_SUCCESS; } // Copyright (C) 2018-2020 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #pragma once #include #include #include #include #include #include #include #include #include #include #include #include namespace vpu { namespace ie = InferenceEngine; // // DataUsage // // // Describes how Data object is used in the Model: // * Input / Output : network input or output. // * Const : constant values (weights, biases, etc.). // * Intermediate : Data that are used for intermediate results. // * Temp : temporary buffer. // * Fake : fake Data object to fill stage input/output port. // VPU_DECLARE_ENUM(DataUsage, Input, Output, Const, Intermediate, Temp, Fake ) // // DataLocation // // // Describes where Data object is located. // // Must be synchronized with MvTensor VPU_DECLARE_ENUM(DataLocation, None = 0, Input = 1, Output = 2, Blob = 3, BSS = 4, CMX = 5 ) VPU_DECLARE_ENUM(MemoryType, DDR, CMX) // // DataContent // // // Content of the Const Data object. // class DataContent { public: using Ptr = std::shared_ptr; virtual ~DataContent() = default; // TYPED pointer template const T* get() const { return static_cast(getRaw()); } const DataDesc& desc() const { return _desc; } private: // RAW pointer virtual const void* getRaw() const = 0; private: DataDesc _desc; friend ModelObj; }; // // Data content that is calculated on the fly, using lazy calculation: // // * It performs calculation on the first call and stores it in internal buffer. // * Next access will return the pointer to calculated buffer. // class CalculatedDataContent : public DataContent { public: CalculatedDataContent() = default; explicit CalculatedDataContent(const SmallVector& baseContents) : _baseContents(baseContents) {} private: const void* getRaw() const override; virtual size_t getTempBufSize(const SmallVector& baseContents) const; virtual void fillTempBuf(const SmallVector& baseContents, void* tempBuf) const = 0; private: mutable SmallVector _baseContents; mutable std::vector _temp; }; DataContent::Ptr ieBlobContent( const ie::Blob::Ptr& blob, int repeat = 1); DataContent::Ptr replicateContent(float val, int count); DataContent::Ptr replicateContent(const DataContent::Ptr& origContent, int count); DataContent::Ptr scaleContent(const DataContent::Ptr& origContent, float scale); // The function scales the major dimension of 4D origContent DataContent::Ptr scaledChannelContent( const DataContent::Ptr& origContent, const DataContent::Ptr& scaleContent); // // DataNode // class DataNode final : public EnableHandle, public EnableCustomAttributes { // // Main attributes // VPU_MODEL_ATTRIBUTE(std::string, name, std::string()) VPU_MODEL_ATTRIBUTE(DataUsage, usage, DataUsage::Fake) VPU_MODEL_ATTRIBUTE(DataDesc, desc, DataDesc()) VPU_MODEL_ATTRIBUTE(StridesRequirement, requiredStrides, StridesRequirement::empty()) // // Bindings with IE // VPU_MODEL_ATTRIBUTE(ie::DataPtr, origData, nullptr) // // Edges // VPU_MODEL_ATTRIBUTE(StageOutput, producerEdge, nullptr) VPU_MODEL_ATTRIBUTE_PTR_RANGE(StageInputList, consumerEdges) VPU_MODEL_ATTRIBUTE(StageTempBuffer, tempBufferEdge, nullptr) /** * Parent data edge actually allocates memory */ VPU_MODEL_ATTRIBUTE(SharedAllocation, parentDataEdge, nullptr) /** * Children data edges uses parent's memory */ VPU_MODEL_ATTRIBUTE_PTR_RANGE(SharedAllocationList, childDataEdges) // // Const data content // VPU_MODEL_ATTRIBUTE(DataContent::Ptr, content, nullptr) // // Allocation info // VPU_MODEL_ATTRIBUTE(MemoryType, memReqs, MemoryType::DDR) VPU_MODEL_ATTRIBUTE(DataLocation, location, DataLocation::None) VPU_MODEL_ATTRIBUTE(int, memoryOffset, 0) // // Edges wrappers // VPU_MODEL_ATTRIBUTE(Model, model, nullptr) private: struct ConsumerAccess final { inline auto operator()(const StageInput& edge) const -> decltype(edge->consumer()) { return edge->consumer(); } }; struct ChildDataAccess final { inline auto operator()(const SharedAllocation& edge) const -> decltype(edge->child()) { return edge->child(); } }; public: inline Stage producer() const { return _producerEdge == nullptr ? nullptr : _producerEdge->producer(); } inline int numConsumers() const { return _consumerEdges.size(); } inline auto consumers() const -> decltype(mapRange(consumerEdges())) { return mapRange(consumerEdges()); } inline StageInput singleConsumerEdge() const { IE_ASSERT(_consumerEdges.size() == 1); return *_consumerEdges.begin(); } inline Stage singleConsumer() const { return singleConsumerEdge()->consumer(); } inline Data parentData() const { return _parentDataEdge == nullptr ? nullptr : _parentDataEdge->parent(); } inline int numChildDatas() const { return _childDataEdges.size(); } inline auto childDatas() const -> decltype(mapRange(childDataEdges())) { return mapRange(childDataEdges()); } Data getTopParentData() const; // // DataDesc // DimValues strides() const; int totalByteSize() const; int elemOffset(const DimValues& coord) const; int lastElemOffset() const; bool canHaveAParent() const; // // Bindings with IE // inline void setOrigData(const ie::DataPtr& origData) { _origData = origData; } // // StridesRequirement // bool checkStrides(const StridesRequirement& reqs) const; inline void resetRequiredStrides() { _requiredStrides = StridesRequirement::empty(); } void updateRequiredStrides(const StridesRequirement& newReqs); // // Allocation info // void clearAllocation(); void setMemReqs(MemoryType mem); void setIOInfo(DataLocation location, int ioBufferOffset); void setAllocationInfo(DataLocation location, int memoryOffset); // // Backend utilities // // Serialize as-is for new MvTensor kernels that can work with ND data. // If `newOrder` is not empty, it will be used instead of original and missing dimensions will be set to 1. void serializeNewBuffer( BlobSerializer& serializer, DimsOrder newOrder = DimsOrder()); // Serialize for deprecated MvTensor kernels that can work only with 3D data. // // `dimsReloc` is a map from new dims to original dims. // Empty record means use 1 for the new dim and reuse previous stride. // For example : // * Original order : NC // * `newOrder` : HWC // * `dimsReloc` : {(C -> C), {H -> N}} // The Data will be serialized as HWC with // * newDims[H] == origDims[N] // * newDims[W] == 1 // * newDims[C] == origDims[C] // If there is several original dims per new dim, they will be multiplied // (assuming that original dims are near and have no strides between). void serializeOldBuffer( const Stage& stage, BlobSerializer& serializer, DimsOrder newOrder = DimsOrder(), const EnumMap& dimsReloc = EnumMap()); void serializeOldBufferNC( const Stage& stage, BlobSerializer& serializer); void serializeIOInfo(BlobSerializer& serializer) const; private: void serializeDescImpl( BlobSerializer& serializer, const DataDesc& storedDesc, const DimValues& storedStrides) const; void serializeBufferImpl( BlobSerializer& serializer, const DataDesc& storedDesc, const DimValues& storedStrides) const; private: inline DataNode() : _consumerEdges(&StageInputEdge::_posInData), _childDataEdges(&SharedAllocationEdge::_posInData), _posInModel(this) { } private: DataPtrList::iterator _ptrPosInModel; DataListNode _posInModel; friend ModelObj; }; void printTo(std::ostream& os, const Data& data); // // loopOverData // VPU_DECLARE_ENUM(DataLoopStatus, NextChild, NextSibling, Stop) void loopOverData( const Data& data, const FuncRef& op); } // namespace vpu #include #include #include #include int main() { std::vector vec = {0, 1, 2, 3, 4, 5}; // accumulate adds elements by default std::cout << "accumulate({1, 2, 3, 4, 5}): { "; for (auto i : iter::accumulate(vec)) { std::cout << i << ' '; } std::cout << "}\n"; // accumulate with a lambda for subtraction std::cout << "accumulate({1, 2, 3, 4, 5}, subtract): { "; for (auto i : iter::accumulate(vec, [](int a, int b){return a - b;})) { std::cout << i << ' '; } std::cout << "}\n"; } #ifndef COMMON_H_ #define COMMON_H_ struct yx { yx() {} yx(const int y, const int x) { this->y = y; this->x = x; } int y; int x; }; constexpr int MONO_CH_MAX {158}; constexpr int COLOR_CH_MAX {63}; constexpr int ASCII_NUMBER_OFFSET {48}; constexpr char ESC_CHAR {27}; // The player cannot pass widthin this many character's of the window boarder's (y, x). const yx PLAYER_MOVEMENT_INNER_BOARDER {0, 44}; constexpr int BACKGROUND_HEIGHT {33}; // This isn't how I would have done it in retrospect :'(. enum errorsCodes {/* Error codes */ /* There was a problem with the window parameters and the window could not be initialised */ ERROR_WIN_PARAM, // Window not initialised - there was a problem with the window parameters. ERROR_CURSOR_PARAM, // Cursor parameters out of range. ERROR_SPRITE_POS_RANGE, // Sprite position out of range. ERROR_POS_CH_RANGE, // Character position out of range. ERROR_INVALID_DIRECTION, // Direction character found not to be valid. ERROR_OPENING_FILE, // Error opening file. ERROR_CHARACTER_RANGE, // Character out of range. ERROR_COLOR_CODE_RANGE, // Color code out of range. ERROR_GENERIC_RANGE_ERROR, ERROR_RULES_LEV_HEADER, // Header of .level.rules file is malformed. ERROR_RULES_STRING_FIELDS, // There was an error in a field containing string's. ERROR_MALFORMED_STRING, // We encountered a malformed string. ERROR_MALFORMED_COORDINATE, // We have encountered a malformed coordinate. ERROR_DUPLICATE_COORDINATE, // We have encountered a duplicate coordinate. ERROR_MALFORMED_COORDINATE_CHAR_FIELD, // We have encountered a coordinate character field that is malformed. ERROR_BAD_LOGIC // There was an error in the code. }; void sleep(const unsigned long long t); /* Returns false if a is not range [min, max). */ bool checkRange(const int a, const int min, const int max); /* return's true if a - offset is within the range [SINGLE_DIGIT_MIN, SINGLE_DIGIT_MAX]. return's false otherwise. */ bool inSingleDigitRange(const int a, const int offset); /* Calls endwin() then print's e to std::cerr and finally call's exit() with status */ void exit(const std::string & e, const int status); #endif #pragma once #include "./shader.hpp" #include namespace MM::OpenGL { class ShaderBuilder { private: ShaderBuilder(void); struct stage_t { uint32_t id = 0; bool fail = false; }; enum stage_e { VERTEX = 0, FRAGMENT, stage_e_MAX }; stage_t _stages[stage_e_MAX]; struct transform_feedback_varying_t { std::string var; }; std::vector _tfs; bool _tf_interleaved = false; public: ~ShaderBuilder(void); ShaderBuilder& operator=(ShaderBuilder&) = delete; static ShaderBuilder start(void); std::shared_ptr finish(void); public: ShaderBuilder& addStageVertex(const std::string& shader_code); ShaderBuilder& addStageVertexF(MM::Engine& engine, const std::string& file_path); ShaderBuilder& addStageFragment(const std::string& shader_code); ShaderBuilder& addStageFragmentF(MM::Engine& engine, const std::string& file_path); // TODO: geometry and tesselation stages ShaderBuilder& addTransformFeedbackVarying(const std::string& var_name); ShaderBuilder& setTransformFeedbackInterleaved(bool interleaved = true); }; } // MM::OpenGL icsme2020/WS-DREAM /******************************************************** * c_EMF.cpp: C++ implements on EMF [Lo et al., SCC'12] * Author: <> * Created: 2014/5/6 * Last updated: 2014/5/14 ********************************************************/ #include #include #include #include "c_EMF.h" using namespace std; /******************************************************** * Udata and Sdata are the output values ********************************************************/ void c_EMF(double *removedData, int numUser, int numService, int dim, double lmda, double alpha, int maxIter, double etaInit, int topK_U, int topK_S, double *Udata, double *Sdata) { // --- transfer the 1D pointer to 2D array pointer double **removedMatrix = vector2Matrix(removedData, numUser, numService); double **U = vector2Matrix(Udata, numUser, dim); double **S = vector2Matrix(Sdata, numService, dim); // --- create a set of temporal matries double **gradU = createMatrix(numUser, dim); double **gradS = createMatrix(numService, dim); double **removedMatrix_T = createMatrix(numService, numUser); // --- compute the similarity matrix vector > > pccUserMatrix = getPCCMatrix( removedMatrix, numUser, numService, topK_U); transpose(removedMatrix, removedMatrix_T, numUser, numService); vector > > pccServiceMatrix = getPCCMatrix( removedMatrix_T, numService, numUser, topK_S); // --- inital loss value double lossValue = loss(U, S, removedMatrix, lmda, alpha, numUser, numService, dim, pccUserMatrix, pccServiceMatrix); // --- iterate by standard gradient descent algorithm int iter, i, j, k; for (iter = 0; iter < maxIter; iter++) { // update gradients gradLoss(U, S, removedMatrix, gradU, gradS, lmda, alpha, numUser, numService, dim, pccUserMatrix, pccServiceMatrix); // line search to find the best learning rate eta double eta = linesearch(U, S, removedMatrix, lossValue, gradU, gradS, etaInit, lmda, alpha, numUser, numService, dim, pccUserMatrix, pccServiceMatrix); // gradient descent updates for (k = 0; k < dim; k++) { // update U for (i = 0; i < numUser; i++) { U[i][k] -= eta * gradU[i][k]; } // update S for (j = 0; j < numService; j++) { S[j][k] -= eta * gradS[j][k]; } } // update loss value lossValue = loss(U, S, removedMatrix, lmda, alpha, numUser, numService, dim, pccUserMatrix, pccServiceMatrix); // cout << lossValue << endl; } deleteMatrix(gradU); deleteMatrix(gradS); deleteMatrix(removedMatrix_T); delete ((char*) U); delete ((char*) S); delete ((char*) removedMatrix); } double loss(double **U, double **S, double **removedMatrix, double lmda, double alpha, int numUser, int numService, int dim, vector > > &pccUserMatrix, vector > > &pccServiceMatrix) { int i, j, k, g; double loss = 0; double **predMatrix = createMatrix(numUser, numService); // update predMatrix U_dot_S(removedMatrix, U, S, numUser, numService, dim, predMatrix); // cost for (i = 0; i < numUser; i++) { for (j = 0; j < numService; j++) { if (removedMatrix[i][j] != 0) { loss += 0.5 * (removedMatrix[i][j] - predMatrix[i][j]) * (removedMatrix[i][j] - predMatrix[i][j]); } } } // L2 regularization for (k = 0; k < dim; k++) { for (i = 0; i < numUser; i++) { loss += 0.5 * lmda * U[i][k] * U[i][k]; } for (j = 0; j < numService; j++) { loss += 0.5 * lmda * S[j][k] * S[j][k]; } } // User regularization for (i = 0; i < numUser; i++) { for (k = 0; k < dim; k++) { double sum = 0; for (g = 0; g < pccUserMatrix[i].size(); g++) { int id = pccUserMatrix[i][g].first; sum += pccUserMatrix[i][g].second * U[id][k]; } double tmp = U[i][k] - sum; loss += 0.5 * alpha * tmp * tmp; } } // Service regularization for (j = 0; j < numService; j++) { for (k = 0; k < dim; k++) { double sum = 0; for (g = 0; g < pccServiceMatrix[j].size(); g++) { int id = pccServiceMatrix[j][g].first; sum += pccServiceMatrix[j][g].second * S[id][k]; } double tmp = S[j][k] - sum; loss += 0.5 * alpha * tmp * tmp; } } deleteMatrix(predMatrix); return loss; } void gradLoss(double **U, double **S, double **removedMatrix, double **gradU, double **gradS, double lmda, double alpha, int numUser, int numService, int dim, vector > > &pccUserMatrix, vector > > &pccServiceMatrix) { int i, j, k, g; double grad = 0; // gradU for (i = 0; i < numUser; i++) { for (k = 0; k < dim; k++) { grad = 0; for (j = 0; j < numService; j++) { if (removedMatrix[i][j] != 0) { grad += (removedMatrix[i][j] - dotProduct(U[i], S[j], dim)) * (-S[j][k]); } } grad += lmda * U[i][k]; double sum = 0; for (g = 0; g < pccUserMatrix[i].size(); g++) { int id = pccUserMatrix[i][g].first; sum += pccUserMatrix[i][g].second * U[id][k]; } grad += alpha * (U[i][k] - sum); gradU[i][k] = grad; } } // gradS for (j = 0; j < numService; j++) { for (k = 0; k < dim; k++) { grad = 0; for (i = 0; i < numUser; i++) { if (removedMatrix[i][j] != 0) { grad += (removedMatrix[i][j] - dotProduct(U[i], S[j], dim)) * (-U[i][k]); } } grad += lmda * S[j][k]; double sum = 0; for (g = 0; g < pccServiceMatrix[j].size(); g++) { int id = pccServiceMatrix[j][g].first; sum += pccServiceMatrix[j][g].second * S[id][k]; } grad += alpha * (S[j][k] - sum); gradS[j][k] = grad; } } } double linesearch(double **U, double **S, double **removedMatrix, double lastLossValue, double **gradU, double **gradS, double etaInit, double lmda, double alpha, int numUser, int numService, int dim, vector > > &pccUserMatrix, vector > > &pccServiceMatrix) { double eta = etaInit; double lossValue; double **U1 = createMatrix(numUser, dim); double **S1 = createMatrix(numService, dim); int iter, i, j, k; for (iter = 0; iter < 20; iter++) { // update U1, S1 for (k = 0; k < dim; k++) { // update U for (i = 0; i < numUser; i++) { U1[i][k] = U[i][k] - eta * gradU[i][k]; } // update S for (j = 0; j < numService; j++) { S1[j][k] = S[j][k] - eta * gradS[j][k]; } } lossValue = loss(U1, S1, removedMatrix, lmda, alpha, numUser, numService, dim, pccUserMatrix, pccServiceMatrix); if (lossValue <= lastLossValue) break; eta = eta / 2; } deleteMatrix(U1); deleteMatrix(S1); return eta; } void U_dot_S(double **removedMatrix, double **U, double **S, int numUser, int numService, int dim, double **predMatrix) { int i, j; for (i = 0; i < numUser; i++) { for (j = 0; j < numService; j++) { if (removedMatrix[i][j] != 0) { predMatrix[i][j] = dotProduct(U[i], S[j], dim); } } } } double dotProduct(double *vec1, double *vec2, int len) { double product = 0; int i; for (i = 0; i < len; i++) { product += vec1[i] * vec2[i]; } return product; } void transpose(double **matrix, double **matrix_T, int row, int col) { int i, j; for (i = 0; i < row; i++) { for (j = 0; j < col; j++) { matrix_T[j][i] = matrix[i][j]; } } } #pragma once // This file is generated from the Game's Reflection data #include #include #include #include #include #include namespace RED4ext { namespace quest { struct UIElement_ConditionType : quest::IUIConditionType { static constexpr const char* NAME = "questUIElement_ConditionType"; static constexpr const char* ALIAS = NAME; TweakDBID element; // 38 game::data::UICondition condition; // 40 bool value; // 44 uint8_t unk45[0x48 - 0x45]; // 45 }; RED4EXT_ASSERT_SIZE(UIElement_ConditionType, 0x48); } // namespace quest } // namespace RED4ext #include "pch.h" #include "CppUnitTest.h" #include #include #include using namespace Microsoft::VisualStudio::CppUnitTestFramework; namespace Microsoft { namespace VisualStudio { namespace CppUnitTestFramework { template<> inline std::wstring ToString(const uint16_t& t) { RETURN_WIDE_STRING(t); } template<> inline std::wstring ToString(const eERRORRESULT& t) { RETURN_WIDE_STRING(t); } template<> inline std::wstring ToString(const eNMEA0183_State& t) { RETURN_WIDE_STRING(t); } template<> inline std::wstring ToString(const eNMEA0183_TalkerID& t) { RETURN_WIDE_STRING(t); } template<> inline std::wstring ToString(const eNMEA0183_SentencesID& t) { RETURN_WIDE_STRING(t); } } } } namespace NMEA0183test { TEST_CLASS(Other_Sentences) { public: #ifdef NMEA0183_DECODE_TXT TEST_METHOD(TestMethod_TXT) { NMEA0183decoder NMEA; NMEA0183_DecodedData FrameData; eNMEA0183_State CurrentState; eERRORRESULT LastError = ERR_OK; //=== Test (Full Data) ============================================ const char* const TEST_TXT_FULL_DATA_FRAME = "$GPTXT,01,01,25,DR MODE - ANTENNA FAULT^21*38\r\n"; for (size_t z = 0; z < strlen(TEST_TXT_FULL_DATA_FRAME); ++z) (void)NMEA.AddReceivedCharacter(TEST_TXT_FULL_DATA_FRAME[z]); CurrentState = NMEA.GetDecoderState(); Assert::AreEqual(NMEA0183_TO_PROCESS, CurrentState, L"Test (Full Data), state should be NMEA0183_TO_PROCESS"); LastError = NMEA.ProcessFrame(&FrameData); Assert::AreEqual(ERR_OK, LastError, L"Test (Full Data), error should be ERR_OK"); CurrentState = NMEA.GetDecoderState(); Assert::AreEqual(NMEA0183_WAIT_START, CurrentState, L"Test (Full Data), state should be NMEA0183_WAIT_START"); //--- Test data --- Assert::AreEqual(true, FrameData.ParseIsValid, L"Test (Full Data), ParseIsValid should be true"); Assert::AreEqual(NMEA0183_GP, FrameData.TalkerID, L"Test (Full Data), TalkerID should be NMEA0183_GP"); Assert::AreEqual(NMEA0183_TXT, FrameData.SentenceID, L"Test (Full Data), SentenceID should be NMEA0183_TXT"); Assert::AreEqual((uint8_t)1u, FrameData.TXT.TotalSentence, L"Test (Full Data), TotalSentence should be 1"); Assert::AreEqual((uint8_t)1u, FrameData.TXT.SentenceNumber, L"Test (Full Data), SentenceNumber should be 1"); Assert::AreEqual((uint8_t)25u, FrameData.TXT.TextIdentifier, L"Test (Full Data), TextIdentifier should be 25"); Assert::AreEqual(0, strncmp("DR MODE - ANTENNA FAULT!", &FrameData.TXT.TextMessage[0], strlen(FrameData.TXT.TextMessage)), L"Test (Full Data), TextMessage should be 'DR MODE - ANTENNA FAULT!'"); } #endif #ifdef NMEA0183_DECODE_VHW TEST_METHOD(TestMethod_VHW) { NMEA0183decoder NMEA; NMEA0183_DecodedData FrameData; eNMEA0183_State CurrentState; eERRORRESULT LastError = ERR_OK; //=== Test (Full Data) ============================================ const char* const TEST_VHW_FULL_DATA_FRAME = "$IIVHW,245.1,T,243.8,M,047.01,N,087.04,K*53\r\n"; for (size_t z = 0; z < strlen(TEST_VHW_FULL_DATA_FRAME); ++z) (void)NMEA.AddReceivedCharacter(TEST_VHW_FULL_DATA_FRAME[z]); CurrentState = NMEA.GetDecoderState(); Assert::AreEqual(NMEA0183_TO_PROCESS, CurrentState, L"Test (Full Data), state should be NMEA0183_TO_PROCESS"); LastError = NMEA.ProcessFrame(&FrameData); Assert::AreEqual(ERR_OK, LastError, L"Test (Full Data), error should be ERR_OK"); CurrentState = NMEA.GetDecoderState(); Assert::AreEqual(NMEA0183_WAIT_START, CurrentState, L"Test (Full Data), state should be NMEA0183_WAIT_START"); //--- Test data --- Assert::AreEqual(true, FrameData.ParseIsValid, L"Test (Full Data), ParseIsValid should be true"); Assert::AreEqual((eNMEA0183_TalkerID)NMEA0183_TALKER_ID('I', 'I'), FrameData.TalkerID, L"Test (Full Data), TalkerID should be NMEA0183_II"); Assert::AreEqual(NMEA0183_VHW, FrameData.SentenceID, L"Test (Full Data), SentenceID should be NMEA0183_VHW"); Assert::AreEqual((uint32_t)2451000u, FrameData.VHW.HeadingTrue, L"Test (Full Data), CourseTrue should be 2451000"); Assert::AreEqual((uint32_t)2438000u, FrameData.VHW.HeadingMagnetic, L"Test (Full Data), CourseMagnetic should be 2438000"); Assert::AreEqual((uint32_t)470100u, FrameData.VHW.SpeedKnots, L"Test (Full Data), SpeedKnots should be 470100"); Assert::AreEqual((uint32_t)870400u, FrameData.VHW.SpeedKmHr, L"Test (Full Data), SpeedKmHr should be 870400"); } #endif #ifdef NMEA0183_DECODE_ZDA TEST_METHOD(TestMethod_ZDA) { NMEA0183decoder NMEA; NMEA0183_DecodedData FrameData; eNMEA0183_State CurrentState; eERRORRESULT LastError = ERR_OK; //=== Test (Full Data) ============================================ const char* const TEST_ZDA_FULL_DATA_FRAME = "$GPZDA,160012.71,11,03,2004,-1,00*7D\r\n"; for (size_t z = 0; z < strlen(TEST_ZDA_FULL_DATA_FRAME); ++z) (void)NMEA.AddReceivedCharacter(TEST_ZDA_FULL_DATA_FRAME[z]); CurrentState = NMEA.GetDecoderState(); Assert::AreEqual(NMEA0183_TO_PROCESS, CurrentState, L"Test (Full Data), state should be NMEA0183_TO_PROCESS"); LastError = NMEA.ProcessFrame(&FrameData); Assert::AreEqual(ERR_OK, LastError, L"Test (Full Data), error should be ERR_OK"); CurrentState = NMEA.GetDecoderState(); Assert::AreEqual(NMEA0183_WAIT_START, CurrentState, L"Test (Full Data), state should be NMEA0183_WAIT_START"); //--- Test data --- Assert::AreEqual(true, FrameData.ParseIsValid, L"Test (Full Data), ParseIsValid should be true"); Assert::AreEqual(NMEA0183_GP, FrameData.TalkerID, L"Test (Full Data), TalkerID should be NMEA0183_GP"); Assert::AreEqual(NMEA0183_ZDA, FrameData.SentenceID, L"Test (Full Data), SentenceID should be NMEA0183_ZDA"); Assert::AreEqual((uint8_t)16u, FrameData.ZDA.Time.Hour, L"Test (Full Data), Time.Hour should be 16"); Assert::AreEqual((uint8_t)00u, FrameData.ZDA.Time.Minute, L"Test (Full Data), Time.Minute should be 0"); Assert::AreEqual((uint8_t)12u, FrameData.ZDA.Time.Second, L"Test (Full Data), Time.Second should be 12"); Assert::AreEqual((uint16_t)710u, FrameData.ZDA.Time.MilliS, L"Test (Full Data), Time.MilliS should be 710"); Assert::AreEqual((uint8_t)11u, FrameData.ZDA.Date.Day, L"Test (Full Data), Date.Day should be 11"); Assert::AreEqual((uint8_t)03u, FrameData.ZDA.Date.Month, L"Test (Full Data), Date.Month should be 3"); Assert::AreEqual((uint16_t)2004u, FrameData.ZDA.Date.Year, L"Test (Full Data), Date.Year should be 2004"); Assert::AreEqual((int8_t)-1, FrameData.ZDA.LocalZoneHour, L"Test (Full Data), LocalZoneHour should be -1"); Assert::AreEqual((uint8_t)00u, FrameData.ZDA.LocalZoneMinute, L"Test (Full Data), LocalZoneMinute should be 0"); } #endif }; }#pragma once #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 #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 INT WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR lpCmdLine, INT nCmdShow) { return 0; }#include "mat.hpp" #include using namespace ariel; int main(){ cout << mat(13, 5, '@', '-') << endl; cout << mat(7, 9, '@', '-') << endl; cout << mat(5, 1, '#', '*') << endl; cout << mat(1, 5, '#', '*') << endl; return 0; }/* * Copyright (c) 2017, * All rights reserved. * */ #ifndef __WEBSERVICE_H__ #define __WEBSERVICE_H__ #include #include #include #include template class WebService { public: WebService(Functor &functor) : functor(functor) {} void start() { daemon = MHD_start_daemon(MHD_USE_THREAD_PER_CONNECTION, 8080, NULL, NULL, &on_request, this, MHD_OPTION_END); if (daemon == NULL) throw std::runtime_error("MHD_start_daemon"); } ~WebService() { MHD_stop_daemon(daemon); } private: MHD_Daemon* daemon; Functor functor; static int on_request(void * cls, struct MHD_Connection * connection, const char * url, const char * method, const char * version, const char * upload_data, size_t * upload_data_size, void ** ptr); }; template int WebService::on_request(void * cls, struct MHD_Connection * connection, const char * url, const char * method, const char * version, const char * upload_data, size_t * upload_data_size, void ** ptr) { static int dummy; int ret; if (std::string("GET") != method) return MHD_NO; /* unexpected method */ if (&dummy != *ptr) { /* The first time only the headers are valid, do not respond in the first round... */ *ptr = &dummy; return MHD_YES; } if (0 != *upload_data_size) return MHD_NO; /* upload data in a GET!? */ WebService* webservice = static_cast*>(cls); struct MHD_Response * response; *ptr = NULL; /* clear context pointer */ try { const std::string& data = webservice->functor(url); response = MHD_create_response_from_buffer (data.size(), const_cast(data.c_str()), MHD_RESPMEM_MUST_COPY); MHD_add_response_header(response, "Content-Type", "application/json"); MHD_add_response_header(response, "Access-Control-Allow-Origin", "*"); ret = MHD_queue_response(connection, MHD_HTTP_OK, response); } catch (const std::exception& e) { const std::string& data = e.what(); response = MHD_create_response_from_buffer (data.size(), const_cast(data.c_str()), MHD_RESPMEM_MUST_COPY); MHD_add_response_header(response, "Content-Type", "text"); ret = MHD_queue_response(connection, MHD_HTTP_BAD_REQUEST, response); } MHD_destroy_response(response); return ret; } #endif Google/Kick Start/2021/Round B/b.cpp #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; using ll = long long; template void max_self(T &a, T b) { a = max(a, b); } int Solve() { int n; cin >> n; vector a(n); for (int i = 0; i < n; ++i) { cin >> a[i]; } vector left(n); { left[0] = 1; left[1] = 2; ll diff = a[1] - a[0]; for (int i = 2; i < n; ++i) { if (a[i] - a[i - 1] == diff) { left[i] = left[i - 1] + 1; } else { left[i] = 2; diff = a[i] - a[i - 1]; } } } vector right(n); { right[n - 1] = 1; right[n - 2] = 2; ll diff = a[n - 2] - a[n - 1]; for (int i = n - 3; i >= 0; --i) { if (a[i] - a[i + 1] == diff) { right[i] = right[i + 1] + 1; } else { right[i] = 2; diff = a[i] - a[i + 1]; } } } int ans = 1; for (int i = 0; i < n; ++i) { if (i == 0) { // 1 0 0 0 0 0 0 0 0 0 max_self(ans, max(right[i], right[i + 1] + 1)); continue; } if (i == n - 1) { // 0 0 0 0 0 0 0 0 0 1 max_self(ans, max(left[i], left[i - 1] + 1)); continue; } if (i == 1) { // 0 1 0 0 0 0 0 0 0 0 if (i + 2 < n && right[i + 1] >= 2) { ll diff = a[i + 2] - a[i + 1]; if (a[i - 1] == a[i + 1] - diff * 2) { max_self(ans, right[i + 1] + 2); } } } else if (i == n - 2) { // 0 0 0 0 0 0 0 0 1 0 if (i - 2 >= 0 && left[i - 1] >= 2) { ll diff = a[i - 1] - a[i - 2]; if (a[i + 1] == a[i - 1] + diff * 2) { max_self(ans, left[i - 1] + 2); } } } else { // i > 1 && i < n - 2 if ((a[i - 1] + a[i + 1]) % 2 == 0) { ll mid = a[i - 1] + (a[i + 1] - a[i - 1]) / 2; ll diff = mid - a[i - 1]; ll before_diff = a[i - 1] - a[i - 2]; ll after_diff = a[i + 2] - a[i + 1]; if (diff == before_diff && diff == after_diff) { max_self(ans, left[i - 1] + right[i + 1] + 1); } else if (diff == before_diff) { // 0 0 X X 1 X 0 0 0 0 max_self(ans, left[i - 1] + 2); } else if (diff == after_diff) { // 0 0 0 X 1 X X 0 0 0 max_self(ans, right[i + 1] + 2); } } } max_self(ans, max(left[i], right[i])); max_self(ans, max(left[i - 1] + 1, right[i + 1] + 1)); } return ans; } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int test_cases; cin >> test_cases; for (int test_case = 1; test_case <= test_cases; ++test_case) { int answer = Solve(); cout << "Case #" << test_case << ": " << answer << endl; } } #include "SDevMenuHierarchy.h" #include "Widgets/Layout/SBorder.h" #include "Widgets/Input/SSearchBox.h" #include "Widgets/Layout/SScrollBorder.h" #include "SDevMenuHierarchyItem.h" #include "DevMenuHierarchyModel.h" #include "UnrealDevMenuEditor.h" #include "Framework/Commands/GenericCommands.h" #define LOCTEXT_NAMESPACE "SDevMenuHierarchyView" SDevMenuHierarchyView ::~SDevMenuHierarchyView() { if ( Editor.IsValid() ) { Editor.Pin()->OnChangedMenu.Remove(ChangedMenuHandle); } } void SDevMenuHierarchyView::Construct(const FArguments& InArgs, TSharedPtr InEditor) { OnChangeHierarchyItem = InArgs._OnChangeHierarchyItem; Editor = InEditor.ToSharedRef(); ChangedMenuHandle = Editor.Pin()->OnChangedMenu.AddRaw( this, &SDevMenuHierarchyView::OnChangedMenu); SearchBoxMenuFilter = MakeShareable( new FMenuTextFilter(FMenuTextFilter::FItemToStringArray::CreateSP( this, &SDevMenuHierarchyView::GetFilterStrings))); FilterHandler = MakeShareable(new TreeFilterHandler()); FilterHandler->SetFilter(SearchBoxMenuFilter.Get()); FilterHandler->SetRootItems(&RootMenus, &TreeRootMenus); FilterHandler->SetGetChildrenDelegate( TreeFilterHandler::FOnGetChildren::CreateRaw( this, &SDevMenuHierarchyView::OnGetChildren)); CommandList = MakeShareable(new FUICommandList); // clang-format off ChildSlot [ SNew(SBorder) .BorderImage(FEditorStyle::GetBrush("ToolPanel.GroupBorder")) [ SNew(SVerticalBox) + SVerticalBox::Slot() .Padding(4) .AutoHeight() [ // サーチボックス SAssignNew(SearchBox, SSearchBox) .HintText(LOCTEXT("SearchWidgets", "Search Menu")) .OnTextChanged(this, &SDevMenuHierarchyView::OnSearchChanged) ] + SVerticalBox::Slot() .FillHeight(1.0f) [ SAssignNew(TreeViewArea, SBorder) .Padding(0) .BorderImage( FEditorStyle::GetBrush( "NoBrush" ) ) ] ] ]; // clang-format on ReBuildTreeView(); bRefreshTreeRequested = true; } // Begin SWidget void SDevMenuHierarchyView::Tick(const FGeometry& AllottedGeometry, const double InCurrentTime, const float InDeltaTime) { if ( bRebuildTreeRequested || bRefreshTreeRequested ) { if ( bRebuildTreeRequested ) { ReBuildTreeView(); } RefreshTreeView(); UpdateExpansionRecursive(); bRebuildTreeRequested = false; bRefreshTreeRequested = false; } } FReply SDevMenuHierarchyView::OnKeyDown(const FGeometry& MyGeometry, const FKeyEvent& InKeyEvent) { if ( Editor.Pin()->GetHierarchyCommandList()->ProcessCommandBindings( InKeyEvent) ) { return FReply::Handled(); } if ( CommandList->ProcessCommandBindings(InKeyEvent) ) { return FReply::Handled(); } return FReply::Unhandled(); } // End SWidget // ツリービューをリフレッシュする void SDevMenuHierarchyView::RefreshTreeView() { RootMenus.Empty(); RootMenus.Add( MakeShareable(new FDevMenuHierarchyRoot(Editor.Pin()->GetDevMenuEdited()))); FilterHandler->RefreshAndFilterTree(); } // メニューが変更された void SDevMenuHierarchyView::OnChangedMenu() { bRefreshTreeRequested = true; } // ツリービューを再構築する void SDevMenuHierarchyView::ReBuildTreeView() { float OldScrollOffset = 0.0f; if ( MenuTreeView.IsValid() ) { OldScrollOffset = MenuTreeView->GetScrollOffset(); } // MenuTreeView = SNew(STreeView) .ItemHeight(20.f) .SelectionMode(ESelectionMode::Single) .OnGetChildren(FilterHandler.ToSharedRef(), &TreeFilterHandler::OnGetFilteredChildren) .OnGenerateRow(this, &SDevMenuHierarchyView::OnGenerateRow) .OnSelectionChanged(this, &SDevMenuHierarchyView::OnSelectionChanged) .OnSetExpansionRecursive(this, &SDevMenuHierarchyView::OnSetExpansionRecursive) .OnContextMenuOpening(this, &SDevMenuHierarchyView::OnContextMenuOpening) .TreeItemsSource(&TreeRootMenus); FilterHandler->SetTreeView(MenuTreeView.Get()); TreeViewArea->SetContent( SNew(SScrollBorder, MenuTreeView.ToSharedRef())[MenuTreeView.ToSharedRef()]); // Restore the previous scroll offset MenuTreeView->SetScrollOffset(OldScrollOffset); } TSharedRef SDevMenuHierarchyView::OnGenerateRow( FTreeViewItem InItem, const TSharedRef& OwnerTable) { return SNew(SDevMenuHierarchyViewItem, Editor.Pin(), OwnerTable, InItem) //.HighlightText(this, &SHierarchyView::GetSearchText) ; } void SDevMenuHierarchyView::OnGetChildren(FTreeViewItem InParent, TArray& OutChildren) { InParent->GatherChildren(OutChildren); } void SDevMenuHierarchyView::OnSelectionChanged(FTreeViewItem SelectedItem, ESelectInfo::Type SelectInfo) { if ( SelectedItem.IsValid() ) { // 変更通知 OnChangeHierarchyItem.ExecuteIfBound(SelectedItem->GetObject()); } } // メニューコンテキスト対応 TSharedPtr SDevMenuHierarchyView::OnContextMenuOpening() { FMenuBuilder MenuBuilder(true, CommandList); MenuBuilder.PushCommandList(Editor.Pin()->GetHierarchyCommandList()); MenuBuilder.BeginSection("Edit", LOCTEXT("Edit", "Edit")); { //MenuBuilder.AddMenuEntry(FGenericCommands::Get().Cut); //MenuBuilder.AddMenuEntry(FGenericCommands::Get().Copy); //MenuBuilder.AddMenuEntry(FGenericCommands::Get().Paste); //MenuBuilder.AddMenuEntry(FGenericCommands::Get().Duplicate); MenuBuilder.AddMenuEntry(FGenericCommands::Get().Delete); } MenuBuilder.EndSection(); return MenuBuilder.MakeWidget(); } // 展開状態が設定された時 void SDevMenuHierarchyView::OnSetExpansionRecursive(FTreeViewItem Item, bool bInExpansionState) { Item->SetExpansion(bRebuildTreeRequested); } void SDevMenuHierarchyView::GetFilterStrings(FTreeViewItem Item, TArray& OutString) { Item->GetFilterStrings(OutString); } // 展開状態を更新する void SDevMenuHierarchyView::UpdateExpansionRecursive() { for ( auto& Item : RootMenus ) { UpdateExpansionRecursive(Item); } } // 展開状態を更新する void SDevMenuHierarchyView::UpdateExpansionRecursive(const FTreeViewItem& Item) { // メニュー側に現在の展開状態を設定する MenuTreeView->SetItemExpansion(Item, Item->IsExpansion()); // 小階層の展開状態を再起ループで設定する TArray Children; Item->GatherChildren(Children); for ( auto& ChildModel : Children ) { UpdateExpansionRecursive(ChildModel); } } void SDevMenuHierarchyView::OnSearchChanged(const FText& InFilterText) { bRefreshTreeRequested = true; const bool bFilteringEnabled = !InFilterText.IsEmpty(); if ( bFilteringEnabled != FilterHandler->GetIsEnabled() ) { // フィルターの状態変更 FilterHandler->SetIsEnabled(bFilteringEnabled); } SearchBoxMenuFilter->SetRawFilterText(InFilterText); SearchBox->SetError(SearchBoxMenuFilter->GetFilterErrorText()); } #undef LOCTEXT_NAMESPACE 0 // This file is part of RAVL, Recognition And Vision Library // Copyright (C) 2005, University of Surrey // This code may be redistributed under the terms of the GNU Lesser // General Public License (LGPL). See the lgpl.licence file for details or // see http://www.gnu.org/copyleft/lesser.html // file-header-ends-here #include "Ravl/DP/PrintIOInfo.hh" #include "Ravl/DP/FileFormatRegistry.hh" #include "Ravl/DP/TypeConverter.hh" #include "Ravl/DP/FileFormat.hh" #include "Ravl/TypeName.hh" namespace RavlN { static StringC MakePad(IntT strLen,IntT tabs) { StringC ret; for(int i = tabs - strLen/8;i > 0;i--) ret += '\t'; return ret; } // List all know formats. static bool ListFmts_LessThanOrEqual(const FileFormatBaseC &f1,const FileFormatBaseC &f2) { if(f1.Name() == f2.Name()) return StringC(TypeName(f1.DefaultType())) <= StringC(TypeName(f2.DefaultType())); return f1.Name() <= f2.Name(); } void PrintIOFormats(ostream &os) { os << "File Formats:\n"; os << "Seq Pri\tFormat\t\tClass\t\t\t\tDescription\n"; DListC fmts = SystemFileFormatRegistry().Formats().Copy(); fmts.MergeSort(ListFmts_LessThanOrEqual); for(DLIterC it(fmts); it.IsElm();it.Next()) { StringC typeName = TypeName(it.Data().DefaultType()); StringC auxInfo = StringC((int) it.Data().IsStream()) + " " + StringC(it.Data().Priority()); os << " " << auxInfo << MakePad(auxInfo.length() + 1,1) << " " << it.Data().Name() << MakePad(it.Data().Name().length()+1,2) << " " << typeName << MakePad(typeName.length()+1,4) << " " << it.Data().Description() << "\n"; } } // List all know conversions. void PrintIOConversions(ostream &os) { os << "Type conversions:\n"; for(GraphEdgeIterC it(SystemTypeConverter().Graph()); it.IsElm();it.Next()) { StringC name1 = TypeName(it.Data().ArgType(0)); os << " " << name1 << MakePad(name1.Size()+1,4) << " -> " << TypeName(it.Data().Output()) << "\n"; } } // List all know class types. void PrintIOClassTypes(ostream &os) { os << "Classes:\n"; for(HashIterC it(DPTypeInfoBodyC::Types());it.IsElm();it.Next()) os << " " << TypeName(it.Key()) << "\n"; } } 1-10 #include "HX710B.h" HX710B::HX710B(uint8_t sck_pin , uint8_t do_pin, uint8_t mode) { this->SCK_pin = sck_pin; this->DO_pin = do_pin; this->mode = mode; } HX710B::~HX710B(){} void HX710B::halt_(unsigned long time_) { if( this->delay_ == NULL ) delay(time_); else this->delay_(time_); } unsigned long HX710B::getTick(void) { if( this->tick != NULL ) return this->tick(); else return millis(); } void HX710B::attachDelay(void (*delay__)(unsigned long ti)) { this->delay_ = delay__; } void HX710B::attachTick(unsigned long (*tick_)(void)) { this->tick = tick_; } uint8_t HX710B::init(void) { if (this->SCK_pin == NO_PIN_DEFINED || this->DO_pin == NO_PIN_DEFINED ) return HX710B_ERROR; pinMode(this->DO_pin, INPUT_PULLUP); digitalWrite(this->DO_pin, HIGH); pinMode(this->SCK_pin, OUTPUT); digitalWrite(this->SCK_pin, HIGH); for (uint8_t t_ = 0; t_ < this->mode; t_++) { NOP NOP digitalWrite(this->SCK_pin, LOW); NOP NOP digitalWrite(this->SCK_pin, HIGH); } read(NULL, 500UL); this->halt_(500); uint8_t ret = read(NULL, 100); return ret; } uint8_t HX710B::setMode(uint8_t mode_, unsigned long timeout_) { uint32_t val; return read(&val, timeout_); } uint8_t HX710B::read(uint32_t *data, unsigned long timeout_) { // exit sleep mode digitalWrite(this->SCK_pin, LOW); if (this->isReady(timeout_) == HX710B_OK) { uint8_t i = 0; uint32_t raw = 0; for (i = 0; i < this->mode; i++) { NOP NOP digitalWrite(this->SCK_pin, HIGH); NOP NOP digitalWrite(this->SCK_pin, LOW); if (i < 24) { raw = raw << 1; if (digitalRead(this->DO_pin)) raw = raw | 0x01; } } // force the HX710B to enter the sleep mode digitalWrite(this->SCK_pin, HIGH); if( data != NULL) *data = raw ^ 0x800000; return HX710B_OK; } return HX710B_TIMEOUT; } uint8_t HX710B::isReady(unsigned long timeout_) { unsigned long time_s = this->getTick(); while (digitalRead(this->DO_pin)!= LOW) { // preventive if counter is roll-over and start from beginning unsigned long rollOver = this->getTick(); if (rollOver < time_s) time_s = rollOver; if (time_s - this->getTick() > timeout_) return HX710B_TIMEOUT; // need delay; this->halt_(5); } return HX710B_OK; }// Copyright 2017 The Shaderc 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 "libshaderc_util/version_profile.h" #include "gmock/gmock.h" namespace { using shaderc_util::IsKnownVersion; using shaderc_util::ParseVersionProfile; using ::testing::Eq; using ::testing::ValuesIn; TEST(IsKnownVersionTest, Samples) { EXPECT_TRUE(IsKnownVersion(100)); EXPECT_TRUE(IsKnownVersion(110)); EXPECT_TRUE(IsKnownVersion(120)); EXPECT_TRUE(IsKnownVersion(130)); EXPECT_TRUE(IsKnownVersion(140)); EXPECT_TRUE(IsKnownVersion(150)); EXPECT_TRUE(IsKnownVersion(300)); EXPECT_TRUE(IsKnownVersion(330)); EXPECT_TRUE(IsKnownVersion(310)); EXPECT_TRUE(IsKnownVersion(400)); EXPECT_TRUE(IsKnownVersion(410)); EXPECT_TRUE(IsKnownVersion(420)); EXPECT_TRUE(IsKnownVersion(430)); EXPECT_TRUE(IsKnownVersion(440)); EXPECT_TRUE(IsKnownVersion(450)); EXPECT_TRUE(IsKnownVersion(460)); EXPECT_FALSE(IsKnownVersion(101)); EXPECT_FALSE(IsKnownVersion(470)); } struct ParseVersionProfileCase { std::string input; bool success; // The following are only used when success is true. int expected_version; EProfile expected_profile; }; using ParseVersionProfileTest = ::testing::TestWithParam; TEST_P(ParseVersionProfileTest, Sample) { int version = 0; EProfile profile = EBadProfile; const bool result = ParseVersionProfile(GetParam().input, &version, &profile); EXPECT_THAT(result, GetParam().success); if (result) { EXPECT_THAT(version, GetParam().expected_version); EXPECT_THAT(profile, GetParam().expected_profile); } } // For OpenGL ES GLSL (ESSL) versions, see // https://www.khronos.org/registry/OpenGL/index_e.php INSTANTIATE_TEST_SUITE_P(OpenGLESCases, ParseVersionProfileTest, ValuesIn(std::vector{ {"100es", true, 100, EEsProfile}, {"300es", true, 300, EEsProfile}, {"310es", true, 310, EEsProfile}, {"320es", true, 320, EEsProfile}, {"99es", false, 0, EBadProfile}, {"500es", false, 0, EBadProfile}, })); // For OpenGL GLSL versions, see // https://www.khronos.org/registry/OpenGL/index_gl.php INSTANTIATE_TEST_SUITE_P(OpenGLBlankCases, ParseVersionProfileTest, ValuesIn(std::vector{ {"110", true, 110, ENoProfile}, {"120", true, 120, ENoProfile}, {"130", true, 130, ENoProfile}, {"140", true, 140, ENoProfile}, {"150", true, 150, ENoProfile}, {"330", true, 330, ENoProfile}, {"400", true, 400, ENoProfile}, {"410", true, 410, ENoProfile}, {"420", true, 420, ENoProfile}, {"430", true, 430, ENoProfile}, {"440", true, 440, ENoProfile}, {"450", true, 450, ENoProfile}, {"460", true, 460, ENoProfile}, {"99", false, 0, EBadProfile}, {"500", false, 0, EBadProfile}, })); INSTANTIATE_TEST_SUITE_P(OpenGLCoreCases, ParseVersionProfileTest, ValuesIn(std::vector{ {"320core", true, 320, ECoreProfile}, {"330core", true, 330, ECoreProfile}, {"400core", true, 400, ECoreProfile}, {"410core", true, 410, ECoreProfile}, {"420core", true, 420, ECoreProfile}, {"430core", true, 430, ECoreProfile}, {"440core", true, 440, ECoreProfile}, {"450core", true, 450, ECoreProfile}, {"460core", true, 460, ECoreProfile}, })); INSTANTIATE_TEST_SUITE_P( OpenGLCompatibilityCases, ParseVersionProfileTest, ValuesIn(std::vector{ {"320compatibility", true, 320, ECompatibilityProfile}, {"330compatibility", true, 330, ECompatibilityProfile}, {"400compatibility", true, 400, ECompatibilityProfile}, {"410compatibility", true, 410, ECompatibilityProfile}, {"420compatibility", true, 420, ECompatibilityProfile}, {"430compatibility", true, 430, ECompatibilityProfile}, {"440compatibility", true, 440, ECompatibilityProfile}, {"450compatibility", true, 450, ECompatibilityProfile}, {"460compatibility", true, 460, ECompatibilityProfile}, })); } // anonymous namespace Karina5005/Plagiarism #include using namespace std; #define ll long long #define mod 1000000007 char a[2][1000]; int lvv[2][1000]; void agc() { int uep_xjt; cin >> uep_xjt; string j_j[2]; int o = 0; cin >> j_j[0] >> j_j[1]; for (int o = 0; o < uep_xjt;o++) if(j_j[0][o]=='1' && j_j[1][o]=='1') o = 1; if(o==0) cout << "YES\n"; else cout << "NO\n"; } int main() { ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL); ll test=1; cin>>test; while(test--) { agc(); } return 0; } ssa/src/v20180608/model/DescribeSocAlertDetailsRequest.cpp /* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. 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 #include using namespace TencentCloud::Ssa::V20180608::Model; using namespace std; DescribeSocAlertDetailsRequest::DescribeSocAlertDetailsRequest() : m_alertIdHasBeenSet(false), m_alertTimestampHasBeenSet(false) { } string DescribeSocAlertDetailsRequest::ToJsonString() const { rapidjson::Document d; d.SetObject(); rapidjson::Document::AllocatorType& allocator = d.GetAllocator(); if (m_alertIdHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "AlertId"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, rapidjson::Value(m_alertId.c_str(), allocator).Move(), allocator); } if (m_alertTimestampHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "AlertTimestamp"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, rapidjson::Value(m_alertTimestamp.c_str(), allocator).Move(), allocator); } rapidjson::StringBuffer buffer; rapidjson::Writer writer(buffer); d.Accept(writer); return buffer.GetString(); } string DescribeSocAlertDetailsRequest::GetAlertId() const { return m_alertId; } void DescribeSocAlertDetailsRequest::SetAlertId(const string& _alertId) { m_alertId = _alertId; m_alertIdHasBeenSet = true; } bool DescribeSocAlertDetailsRequest::AlertIdHasBeenSet() const { return m_alertIdHasBeenSet; } string DescribeSocAlertDetailsRequest::GetAlertTimestamp() const { return m_alertTimestamp; } void DescribeSocAlertDetailsRequest::SetAlertTimestamp(const string& _alertTimestamp) { m_alertTimestamp = _alertTimestamp; m_alertTimestampHasBeenSet = true; } bool DescribeSocAlertDetailsRequest::AlertTimestampHasBeenSet() const { return m_alertTimestampHasBeenSet; } #include "Atoi.h" // #include #ifndef token_H #define token_H //Structs struct token { char type; int data; token* opLeft; token* opRight; }; //Prototypes - Discontinued token makeIntToken(char* value); token makeIntToken(int value); token makeOPToken(char operation); token makeVoidToken(); int CountNodes(token*); int GetPrecedenceLevel(char Check); int GetOPCode(char op); char OPFromCode(int code); token makeIntToken(char* value) { token t; t.data = myAtoi(value); t.type = 'i'; t.opLeft = 0; t.opRight = 0; return t; } token makeIntToken(int value) { token t; t.data = (value); t.type = 'i'; t.opLeft = 0; t.opRight = 0; return t; } token makeOPToken(char operation) { token t; t.data = GetOPCode(operation); t.type = 'o'; t.opLeft = 0; t.opRight = 0; return t; } token makeVoidToken() { token t; t.data = 'v'; t.type = 'v'; t.opLeft = 0; t.opRight = 0; return t; } int myMax(int a, int b) { if(a >= b) return a; else return b; } int GetOPCode(char op) { switch (op) { case '+': return 1; case '-': return 2; case '/': return 3; case '*': return 4; default : return 0; } } char OPFromCode(int code) { switch (code) { case 1: return '+'; case 2: return '-'; case 3: return '/'; case 4: return '*'; default : return 'v'; } } int GetPrecedenceLevel(char Check) { switch(Check) { default: return 0; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': //case '.': return 1; case '+': case '-': return 3; case '*': case '/': return 2; case '(': case ')': return 4; } } int CountNodes(token* node) { // std::cout << "1" << std::endl; int i=1; if(node->opLeft != 0) { // std::cout << "1 if" << std::endl; i += CountNodes(node->opLeft); } if(node->opRight != 0) { // std::cout << "2 if" << std::endl; i += CountNodes(node->opRight); } return i; } int GetFirstMaxValue(char* a, int length) { int MaxValue =0; // std::cout << "FirstChar: "<< *(a) << std::endl; for(int i =0; iopLeft = TreeDropper(Insertion, i); t->opRight = TreeDropper((Insertion +i +1), Length-i-1); break; } return t; } // void tokenReader(token* t) // { // if(t->opLeft != 0) tokenReader(t->opLeft); // // else std::cout << "LeftPointerNull" << std::endl; // if(t->opRight != 0) tokenReader(t->opRight); // // else std::cout << "RightPointerNull" << std::endl; // switch (t->type) // { // case 'o': // std::cout << OPFromCode(t->data) << std::endl; // break; // case 'i': // std::cout << t->data << std::endl; // break; // default : // std::cout << "Default Case" << std::endl; // break; // } // } bool IsIntToken(token* t) { if (t->type == 'i') return true; else return false; } bool IsOPToken(token* t) { if (t->type == 'o') return true; else return false; } bool IsVoidToken(token* t) { if (t->type == 'v') return true; else return false; } #endif case-studies/tor/src/TorEnclave/test/test_options.cpp /* Copyright (c) 2001-2004, . * Copyright (c) 2004-2006, , . * Copyright (c) 2007-2013, The Tor Project, Inc. */ /* See LICENSE for licensing information */ #define CONFIG_PRIVATE #include "or.h" #include "confparse.h" #include "config.h" #include "test.h" #include "TorEnclave_t.h" typedef struct { int severity; uint32_t domain; char *msg; } logmsg_t; static smartlist_t *messages = NULL; static void log_cback(int severity, uint32_t domain, const char *msg) { logmsg_t *x = tor_malloc(sizeof(*x)); x->severity = severity; x->domain = domain; x->msg = tor_strdup(msg); if (!messages) messages = smartlist_new(); smartlist_add(messages, x); } static void setup_log_callback(void) { log_severity_list_t lst; memset(&lst, 0, sizeof(lst)); lst.masks[LOG_ERR - LOG_ERR] = ~0; lst.masks[LOG_WARN - LOG_ERR] = ~0; lst.masks[LOG_NOTICE - LOG_ERR] = ~0; add_callback_log(&lst, log_cback); } static char * dump_logs(void) { smartlist_t *msgs; char *out; if (! messages) return tor_strdup(""); msgs = smartlist_new(); SMARTLIST_FOREACH_BEGIN(messages, logmsg_t *, x) { smartlist_add_asprintf(msgs, "[%s] %s", log_level_to_string(x->severity), x->msg); } SMARTLIST_FOREACH_END(x); out = smartlist_join_strings(msgs, "", 0, NULL); SMARTLIST_FOREACH(msgs, char *, cp, tor_free(cp)); smartlist_free(msgs); return out; } static void clear_log_messages(void) { if (!messages) return; SMARTLIST_FOREACH(messages, logmsg_t *, m, { tor_free(m->msg); tor_free(m); }); smartlist_free(messages); messages = NULL; } static void test_options_validate_impl(const char *configuration, const char *expect_errmsg, int expect_log_severity, const char *expect_log) { or_options_t *opt = options_new(); or_options_t *dflt; config_line_t *cl=NULL; char *msg=NULL; int r; // opt->command = or_options_t::CMD_RUN_TOR; opt->command = 0; options_init(opt); // dflt = config_dup(&options_format, opt); dflt = options_new(); dflt->command = 0; clear_log_messages(); r = config_get_lines(configuration, &cl, 1); tt_int_op(r, ==, 0); r = config_assign(&options_format, opt, cl, 0, 0, &msg); tt_int_op(r, ==, 0); r = options_validate(NULL, opt, dflt, 0, &msg); if (expect_errmsg && !msg) { TT_DIE(("Expected error message <%s> from <%s>, but got none.", expect_errmsg, configuration)); } else if (expect_errmsg && !strstr(msg, expect_errmsg)) { TT_DIE(("Expected error message <%s> from <%s>, but got <%s>.", expect_errmsg, configuration, msg)); } else if (!expect_errmsg && msg) { TT_DIE(("Expected no error message from <%s> but got <%s>.", configuration, msg)); } tt_int_op((r == 0), ==, (msg == NULL)); if (expect_log) { int found = 0; if (messages) { SMARTLIST_FOREACH_BEGIN(messages, logmsg_t *, m) { if (m->severity == expect_log_severity && strstr(m->msg, expect_log)) { found = 1; break; } } SMARTLIST_FOREACH_END(m); } if (!found) { tor_free(msg); msg = dump_logs(); TT_DIE(("Expected log message [%s] %s from <%s>, but got <%s>.", log_level_to_string(expect_log_severity), expect_log, configuration, msg)); } } done: config_free_lines(cl); or_options_free(opt); or_options_free(dflt); tor_free(msg); clear_log_messages(); } #define WANT_ERR(config, msg) \ test_options_validate_impl((config), (msg), 0, NULL) #define WANT_LOG(config, severity, msg) \ test_options_validate_impl((config), NULL, (severity), (msg)) #define WANT_ERR_LOG(config, msg, severity, logmsg) \ test_options_validate_impl((config), (msg), (severity), (logmsg)) #define OK(config) \ test_options_validate_impl((config), NULL, 0, NULL) static void test_options_validate(void *arg) { (void)arg; setup_log_callback(); WANT_ERR("ExtORPort 500000", "Invalid ExtORPort"); // WANT_ERR_LOG("ServerTransportOptions trebuchet", // "ServerTransportOptions did not parse", // LOG_WARN, "Too few arguments"); // OK("ServerTransportOptions trebuchet sling=snappy"); // OK("ServerTransportOptions trebuchet sling="); // WANT_ERR_LOG("ServerTransportOptions trebuchet slingsnappy", // "ServerTransportOptions did not parse", // LOG_WARN, "\"slingsnappy\" is not a k=v"); clear_log_messages(); return; } struct testcase_t options_tests[] = { { "validate", test_options_validate, TT_FORK, NULL, NULL }, END_OF_TESTCASES }; Xeelot/MarvelJsonCppTest0 #include "JsonSerializer.h" bool CJsonSerializer::Serialize(IJsonSerializable* pObj, std::string& output) { if (pObj == NULL) { return false; } Json::Value serializeRoot; pObj->Serialize(serializeRoot); Json::StyledWriter writer; output = writer.write(serializeRoot); return true; } bool CJsonSerializer::Deserialize(IJsonSerializable* pObj, std::string& input) { if (pObj == NULL) { return false; } Json::Value deserializeRoot; Json::Reader reader; if (!reader.parse(input, deserializeRoot)) { return false; } pObj->Deserialize(deserializeRoot); return true; } 1000+ /* * Open Chinese Convert * * Copyright 2015 <> * * 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 "CmdLineOutput.hpp" #include "PhraseExtract.hpp" using opencc::Exception; using opencc::PhraseExtract; using opencc::UTF8StringSlice; void Extract(const std::vector& inputFiles, const std::string& outputFile) { std::ostringstream buffer; for (const auto& inputFile : inputFiles) { std::ifstream ifs(inputFile); const std::string contents((std::istreambuf_iterator(ifs)), (std::istreambuf_iterator())); buffer << contents; } const std::string& text = buffer.str(); PhraseExtract extractor; extractor.SetWordMaxLength(2); extractor.SetPrefixSetLength(1); extractor.SetSuffixSetLength(1); extractor.Extract(text); std::ofstream ofs(outputFile); for (const auto& word : extractor.Words()) { const PhraseExtract::Signals& signals = extractor.Signal(word); const double entropy = signals.prefixEntropy + signals.suffixEntropy; const double logProbablity = extractor.LogProbability(word); ofs << word << " " << signals.frequency << " " << logProbablity << " " << signals.cohesion << " " << entropy << " " << signals.prefixEntropy << " " << signals.suffixEntropy << std::endl; } ofs.close(); } int main(int argc, const char* argv[]) { try { TCLAP::CmdLine cmd("Open Chinese Convert (OpenCC) Phrase Extractor", ' ', VERSION); CmdLineOutput cmdLineOutput; cmd.setOutput(&cmdLineOutput); TCLAP::UnlabeledMultiArg fileNames( "fileName", "Input files", true /* required */, "files"); cmd.add(fileNames); TCLAP::ValueArg outputArg( "o", "output", "Output file", true /* required */, "" /* default */, "file" /* type */, cmd); cmd.parse(argc, argv); Extract(fileNames.getValue(), outputArg.getValue()); } catch (TCLAP::ArgException& e) { std::cerr << "error: " << e.error() << " for arg " << e.argId() << std::endl; } catch (Exception& e) { std::cerr << e.what() << std::endl; } return 0; } src/yb/master/sys_catalog_writer.cc // Copyright (c) YugaByte, 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 "yb/master/sys_catalog_writer.h" #include "yb/common/ql_expr.h" #include "yb/common/ql_protocol_util.h" #include "yb/docdb/doc_key.h" #include "yb/docdb/doc_ql_scanspec.h" #include "yb/docdb/doc_rowwise_iterator.h" #include "yb/master/sys_catalog_constants.h" #include "yb/tablet/tablet.h" #include "yb/util/pb_util.h" namespace yb { namespace master { namespace { void SetBinaryValue(const Slice& binary_value, QLExpressionPB* expr_pb) { expr_pb->mutable_value()->set_binary_value(binary_value.cdata(), binary_value.size()); } void SetInt8Value(const int8_t int8_value, QLExpressionPB* expr_pb) { expr_pb->mutable_value()->set_int8_value(int8_value); } CHECKED_STATUS SetColumnId( const Schema& schema_with_ids, const std::string& column_name, QLColumnValuePB* col_pb) { auto column_id = VERIFY_RESULT(schema_with_ids.ColumnIdByName(column_name)); col_pb->set_column_id(column_id.rep()); return Status::OK(); } } // namespace bool IsWrite(QLWriteRequestPB::QLStmtType op_type) { return op_type == QLWriteRequestPB::QL_STMT_INSERT || op_type == QLWriteRequestPB::QL_STMT_UPDATE; } SysCatalogWriter::SysCatalogWriter( const std::string& tablet_id, const Schema& schema_with_ids, int64_t leader_term) : schema_with_ids_(schema_with_ids), leader_term_(leader_term) { req_.set_tablet_id(tablet_id); } Status SysCatalogWriter::DoMutateItem( int8_t type, const std::string& item_id, const google::protobuf::Message& prev_pb, const google::protobuf::Message& new_pb, QLWriteRequestPB::QLStmtType op_type) { const bool is_write = IsWrite(op_type); if (is_write) { std::string diff; if (pb_util::ArePBsEqual(prev_pb, new_pb, VLOG_IS_ON(2) ? &diff : nullptr)) { VLOG(2) << "Skipping empty update for item " << item_id; // Short-circuit empty updates. return Status::OK(); } VLOG(2) << "Updating item " << item_id << " in catalog: " << diff; } return FillSysCatalogWriteRequest( type, item_id, new_pb, op_type, schema_with_ids_, req_.add_ql_write_batch()); } Status SysCatalogWriter::InsertPgsqlTableRow(const Schema& source_schema, const QLTableRow& source_row, const TableId& target_table_id, const Schema& target_schema, const uint32_t target_schema_version, bool is_upsert) { PgsqlWriteRequestPB* pgsql_write = req_.add_pgsql_write_batch(); pgsql_write->set_client(YQL_CLIENT_PGSQL); if (is_upsert) { pgsql_write->set_stmt_type(PgsqlWriteRequestPB::PGSQL_UPSERT); } else { pgsql_write->set_stmt_type(PgsqlWriteRequestPB::PGSQL_INSERT); } pgsql_write->set_table_id(target_table_id); pgsql_write->set_schema_version(target_schema_version); // Postgres sys catalog table is non-partitioned. So there should be no hash column. DCHECK_EQ(source_schema.num_hash_key_columns(), 0); for (size_t i = 0; i < source_schema.num_range_key_columns(); i++) { const auto& value = source_row.GetValue(source_schema.column_id(i)); if (value) { pgsql_write->add_range_column_values()->mutable_value()->CopyFrom(*value); } else { return STATUS_FORMAT(Corruption, "Range value of column id $0 missing for table $1", source_schema.column_id(i), target_table_id); } } for (size_t i = source_schema.num_range_key_columns(); i < source_schema.num_columns(); i++) { const auto& value = source_row.GetValue(source_schema.column_id(i)); if (value) { PgsqlColumnValuePB* column_value = pgsql_write->add_column_values(); column_value->set_column_id(target_schema.column_id(i)); column_value->mutable_expr()->mutable_value()->CopyFrom(*value); } } return Status::OK(); } Status FillSysCatalogWriteRequest( int8_t type, const std::string& item_id, const Slice& data, QLWriteRequestPB::QLStmtType op_type, const Schema& schema_with_ids, QLWriteRequestPB* req) { if (IsWrite(op_type)) { // Add the metadata column. QLColumnValuePB* metadata = req->add_column_values(); RETURN_NOT_OK(SetColumnId(schema_with_ids, kSysCatalogTableColMetadata, metadata)); SetBinaryValue(data, metadata->mutable_expr()); } req->set_type(op_type); // Add column type. SetInt8Value(type, req->add_range_column_values()); // Add column id. SetBinaryValue(item_id, req->add_range_column_values()); return Status::OK(); } Status FillSysCatalogWriteRequest( int8_t type, const std::string& item_id, const google::protobuf::Message& new_pb, QLWriteRequestPB::QLStmtType op_type, const Schema& schema_with_ids, QLWriteRequestPB* req) { req->set_type(op_type); if (IsWrite(op_type)) { faststring metadata_buf; pb_util::SerializeToString(new_pb, &metadata_buf); return FillSysCatalogWriteRequest( type, item_id, Slice(metadata_buf.data(), metadata_buf.size()), op_type, schema_with_ids, req); } return FillSysCatalogWriteRequest(type, item_id, Slice(), op_type, schema_with_ids, req); } Status EnumerateSysCatalog( tablet::Tablet* tablet, const Schema& schema, int8_t entry_type, const EnumerationCallback& callback) { auto iter = VERIFY_RESULT(tablet->NewRowIterator( schema.CopyWithoutColumnIds(), ReadHybridTime::Max(), /* table_id= */ "", CoarseTimePoint::max(), tablet::AllowBootstrappingState::kTrue)); return EnumerateSysCatalog( down_cast(iter.get()), schema, entry_type, callback); } Status EnumerateSysCatalog( docdb::DocRowwiseIterator* doc_iter, const Schema& schema, int8_t entry_type, const EnumerationCallback& callback) { const int type_col_idx = VERIFY_RESULT(schema.ColumnIndexByName(kSysCatalogTableColType)); const int entry_id_col_idx = VERIFY_RESULT(schema.ColumnIndexByName(kSysCatalogTableColId)); const int metadata_col_idx = VERIFY_RESULT(schema.ColumnIndexByName(kSysCatalogTableColMetadata)); QLConditionPB cond; cond.set_op(QL_OP_AND); QLAddInt8Condition(&cond, schema.column_id(type_col_idx), QL_OP_EQUAL, entry_type); const std::vector empty_hash_components; docdb::DocQLScanSpec spec( schema, boost::none /* hash_code */, boost::none /* max_hash_code */, empty_hash_components, &cond, nullptr /* if_req */, rocksdb::kDefaultQueryId); RETURN_NOT_OK(doc_iter->Init(spec)); QLTableRow value_map; QLValue found_entry_type, entry_id, metadata; while (VERIFY_RESULT(doc_iter->HasNext())) { RETURN_NOT_OK(doc_iter->NextRow(&value_map)); RETURN_NOT_OK(value_map.GetValue(schema.column_id(type_col_idx), &found_entry_type)); SCHECK_EQ(found_entry_type.int8_value(), entry_type, Corruption, "Found wrong entry type"); RETURN_NOT_OK(value_map.GetValue(schema.column_id(entry_id_col_idx), &entry_id)); RETURN_NOT_OK(value_map.GetValue(schema.column_id(metadata_col_idx), &metadata)); SCHECK_EQ(metadata.type(), InternalType::kBinaryValue, Corruption, "System catalog snapshot is corrupted, or is built using different build type"); RETURN_NOT_OK(callback(entry_id.binary_value(), metadata.binary_value())); } return Status::OK(); } } // namespace master } // namespace yb thejkane/AGMlibs/graph_parallel/test/distributed_page_rank_test.cpp // Copyright 2004 The Trustees of Indiana University. // Use, modification and distribution is subject to 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) // Authors: // #include #include #include #include #include #include #include #include #include #include #include #include #include #ifdef CSR #include #endif using namespace boost; bool close_to(double x, double y) { double diff = x - y; if (diff < 0) diff = -diff; double base = (y == 0? x : y); if (base != 0) return diff / base < 0.01; else return true; } // Make convenient labels for the vertices void test_distributed_page_rank(amplusplus::transport trans, int n, double p, int iterations, int nthreads, bool verify, int seed) { assert(nthreads == 1); // PageRank only works single threaded for now #ifndef CSR typedef adjacency_list, directedS> Graph; #else typedef compressed_sparse_row_graph > Graph; #endif typedef graph_traits::vertex_descriptor vertex_descriptor; minstd_rand gen; gen.seed(seed); Graph g(erdos_renyi_iterator(gen, n, p/2), erdos_renyi_iterator(), n, trans); // Setup RankMaps std::vector rank(num_vertices(g)), other_rank(num_vertices(g)); typedef property_map::type VertexIndexMap; typedef property_map::type LocalVertexIndexMap; typedef iterator_property_map::iterator, LocalVertexIndexMap> LocalRankMap; typedef property_map::const_type VertexGlobalMap; typedef boost::parallel::distributed_property_map RankMap; trans.set_nthreads(nthreads); boost::graph::distributed::page_rank PR(g, make_iterator_property_map(rank.begin(), get(vertex_index, g)), make_iterator_property_map(other_rank.begin(), get(vertex_index, g)), boost::graph::n_iterations(iterations), 0.85, n); boost::scoped_array threads(new boost::thread[nthreads]); for (int i = 0 ; i < nthreads ; ++i) { boost::thread thr(boost::ref(PR), i); threads[i].swap(thr); } for (int i = 0 ; i < nthreads ; ++i) threads[i].join(); // Back to one thread trans.set_nthreads(1); if (trans.rank() == 0) std::cout << "Distributed PageRank complete (" << nthreads << " threads)\n"; if ( verify ) { // Check against the sequential version typedef adjacency_list Graph2; gen.seed(seed); Graph2 g2(erdos_renyi_iterator(gen, n, p/2), erdos_renyi_iterator(), n); std::vector rank2(num_vertices(g2)); page_rank(g2, make_iterator_property_map(rank2.begin(), get(vertex_index, g2)), boost::graph::n_iterations(iterations), 0.85, n); if (trans.rank() == 0) std::cout << "Sequential PageRank complete\n"; VertexIndexMap v_index(get(vertex_index, g)); boost::parallel::global_index_map global_index(trans, num_vertices(g), v_index, get(vertex_global, g)); BGL_FORALL_VERTICES(v, g, Graph) { if (!close_to(rank[get(v_index, v)], rank2[get(global_index, v)])) std::cout << "distributed rank = " << rank[get(v_index, v)] << " sequential rank = " << rank2[get(global_index, v)] << std::endl; BOOST_CHECK(close_to(rank[get(v_index, v)], rank2[get(global_index, v)])); } } } int test_main(int argc, char* argv[]) { // AM++ initialization amplusplus::environment env = amplusplus::mpi_environment(argc, argv, true); amplusplus::transport trans = env.create_transport(); int n = 1000; double p = 0.01; int iterations = 20; if (argc < 4) test_distributed_page_rank(trans, n, p, iterations, 1, true, 123); // test_distributed_page_rank(trans, n, p, iterations, 2, true, 123); else /* n, p, iterations threads seed verify */ test_distributed_page_rank(trans, atoi(argv[1]), atof(argv[2]), atoi(argv[3]), argc == 4 ? 1 : atoi(argv[4]), argc == 6 ? true : argv[6] == std::string("true"), argc == 5 ? 123 : atoi(argv[5])); return 0; } willow/src/popx/op/instancenormx.cpp // Copyright (c) 2019 Graphcore Ltd. All rights reserved. #include #include #include #include #include #include #include #include #include #include #include namespace poplar { using Shape = std::vector; } namespace pe = popops::expr; namespace popart { namespace popx { InstanceNormOpx::InstanceNormOpx(Op *op, Devicex *devicex) : NormOpx(op, devicex) { verifyOp(op, {Onnx::Operators::InstanceNormalization_6}); } void InstanceNormOpx::grow(snap::program::Sequence &prog) const { auto &op = getOp(); // Get the inputs auto input = getInTensor(InstanceNormOp::getInputInIndex()).getPoplarTensor(); auto scale = getInTensor(InstanceNormOp::getScaleInIndex()).getPoplarTensor(); auto b = getInTensor(InstanceNormOp::getBInIndex()).getPoplarTensor(); // Get the attributes float epsilon = getOp().getEpsilon(); // Check for stable algorithm session option. bool stable_algo = op.getIr().getSessionOptions().enableStableNorm; // Calculate the mean and the inverse standard deviation poplar::Tensor mean; poplar::Tensor invStdDev; std::tie(mean, invStdDev) = popnn::in::instanceNormStatistics(graph().getPoplarGraph(), input, epsilon, prog.getPoplarSequence(), false, stable_algo, poplar::FLOAT, debugContext("instanceNormStatistics")); // Calculate the normalization auto result = popnn::in::instanceNormalise(graph().getPoplarGraph(), input, scale, b, mean, invStdDev, prog.getPoplarSequence(), debugContext("instanceNorm")); // Return the result setOutTensor(InstanceNormOp::getOutIndex(), snap::Tensor{result.first, graph()}); setOutTensor(InstanceNormOp::getMeanOutIndex(), snap::Tensor{mean, graph()}); setOutTensor(InstanceNormOp::getInvStdDevOutIndex(), snap::Tensor{invStdDev, graph()}); } InstanceNormGradOpx::InstanceNormGradOpx(Op *op, Devicex *devicex) : NormOpx(op, devicex) { verifyOp(op, Onnx::GradOperators::InstanceNormalizationGrad); } void InstanceNormGradOpx::grow(snap::program::Sequence &prog) const { auto out_grad = getInTensor(InstanceNormGradOp::getOutGradInIndex()).getPoplarTensor(); auto input = getInTensor(InstanceNormGradOp::getInputInIndex()).getPoplarTensor(); auto scale = getInTensor(InstanceNormGradOp::getScaleInIndex()).getPoplarTensor(); auto mean = getInTensor(InstanceNormGradOp::getMeanInIndex()).getPoplarTensor(); auto inv_std_dev = getInTensor(InstanceNormGradOp::getInvStdDevInIndex()).getPoplarTensor(); auto input_whitened = popnn::in::instanceNormWhiten(graph().getPoplarGraph(), input, mean, inv_std_dev, prog.getPoplarSequence(), debugContext("instanceNormWhiten")); auto input_grad = popnn::in::instanceNormGradients( graph().getPoplarGraph(), input_whitened, out_grad, inv_std_dev, scale, prog.getPoplarSequence(), poplar::FLOAT, // TODO: could this be HALF? debugContext("instanceNormGradients")); poplar::Tensor scale_grad, b_grad; std::tie(scale_grad, b_grad) = popnn::in::instanceNormParamGradients( graph().getPoplarGraph(), input_whitened, out_grad, prog.getPoplarSequence(), poplar::FLOAT, debugContext("instanceNormParamGradients")); setOutTensor(InstanceNormGradOp::getInputOutIndex(), snap::Tensor{input_grad, graph()}); setOutTensor(InstanceNormGradOp::getScaleOutIndex(), snap::Tensor{scale_grad, graph()}); setOutTensor(InstanceNormGradOp::getBOutIndex(), snap::Tensor{b_grad, graph()}); } namespace { OpxCreator instanceNormOpxCreator({Onnx::Operators::InstanceNormalization_6}); OpxCreator instanceNormGradOpxCreator(Onnx::GradOperators::InstanceNormalizationGrad); } // namespace } // namespace popx } // namespace popart #include "qasm3_utils.hpp" #include "Quantum/QuantumOps.h" #include "mlir/Dialect/StandardOps/IR/Ops.h" #include "mlir/IR/BuiltinOps.h" #include "symbol_table.hpp" namespace qcor { void printErrorMessage(const std::string msg, bool do_exit) { std::cout << "\n[OPENQASM3 MLIRGen] Error\n" << msg << "\n\n"; if (do_exit) exit(1); } void printErrorMessage(const std::string msg, antlr4::ParserRuleContext* context, bool do_exit) { auto line = context->getStart()->getLine(); auto col = context->getStart()->getCharPositionInLine(); std::cout << "\n[OPENQASM3 MLIRGen] Error at " << line << ":" << col << "\n" << " AntlrText: " << context->getText() << "\n" << " " << msg << "\n\n"; if (do_exit) exit(1); } void printErrorMessage(const std::string msg, antlr4::ParserRuleContext* context, std::vector&& v, bool do_exit) { auto line = context->getStart()->getLine(); auto col = context->getStart()->getCharPositionInLine(); std::cout << "\n[OPENQASM3 MLIRGen] Error at " << line << ":" << col << "\n" << " AntlrText: " << context->getText() << "\n" << " " << msg << "\n\n"; std::cout << "MLIR Values:\n"; for (auto vv : v) vv.dump(); if (do_exit) exit(1); } void printErrorMessage(const std::string msg, mlir::Value v) { printErrorMessage(msg, false); v.dump(); exit(1); } void printErrorMessage(const std::string msg, std::vector&& v) { printErrorMessage(msg, false); for (auto vv : v) vv.dump(); exit(1); } mlir::Location get_location(mlir::OpBuilder builder, const std::string& file_name, antlr4::ParserRuleContext* context) { auto line = context->getStart()->getLine(); auto col = context->getStart()->getCharPositionInLine(); return builder.getFileLineColLoc(builder.getIdentifier(file_name), line, col); } std::vector split(const std::string& s, char delim) { std::vector elems; split(s, delim, std::back_inserter(elems)); return elems; } mlir::Type get_custom_opaque_type(const std::string& type, mlir::MLIRContext* context) { llvm::StringRef type_name(type); mlir::Identifier dialect = mlir::Identifier::get("quantum", context); return mlir::OpaqueType::get(context, dialect, type_name); } mlir::Value get_or_extract_qubit(const std::string& qreg_name, const std::size_t idx, mlir::Location location, ScopedSymbolTable& symbol_table, mlir::OpBuilder& builder) { auto key = qreg_name + std::to_string(idx); if (symbol_table.has_symbol(key)) { return symbol_table.get_symbol(key); // global_symbol_table[key]; } else { auto qubits = symbol_table.get_symbol(qreg_name); mlir::Value pos = get_or_create_constant_integer_value( idx, location, builder.getI64Type(), symbol_table, builder); auto value = builder.create( location, get_custom_opaque_type("Qubit", builder.getContext()), qubits, pos); symbol_table.add_symbol(key, value); return value; } } mlir::Value get_or_create_constant_integer_value( const std::size_t idx, mlir::Location location, mlir::Type type, ScopedSymbolTable& symbol_table, mlir::OpBuilder& builder) { auto width = type.getIntOrFloatBitWidth(); if (symbol_table.has_constant_integer(idx, width)) { return symbol_table.get_constant_integer(idx, width); } else { auto integer_attr = mlir::IntegerAttr::get(type, idx); auto ret = builder.create(location, integer_attr); symbol_table.add_constant_integer(idx, ret, width); return ret; } } mlir::Value get_or_create_constant_index_value(const std::size_t idx, mlir::Location location, int width, ScopedSymbolTable& symbol_table, mlir::OpBuilder& builder) { auto type = mlir::IntegerType::get(builder.getContext(), width); auto constant_int = get_or_create_constant_integer_value( idx, location, type, symbol_table, builder); return builder.create(location, constant_int, builder.getIndexType()); } std::map antlr_to_mlir_predicate{ {"==", mlir::CmpIPredicate::eq}, {"!=", mlir::CmpIPredicate::ne}, {"<=", mlir::CmpIPredicate::sle}, {">=", mlir::CmpIPredicate::sge}, {"<", mlir::CmpIPredicate::slt}, {">", mlir::CmpIPredicate::sgt}}; } // namespace qcor//******************************************************************** //* //* Warning: This file was generated by ecore4CPP Generator //* //******************************************************************** #ifndef UML_MULTIPLICITYELEMENTMULTIPLICITYELEMENTIMPL_HPP #define UML_MULTIPLICITYELEMENTMULTIPLICITYELEMENTIMPL_HPP //********************************* // generated Includes //Model includes #include "../MultiplicityElement.hpp" #include "uml/impl/ElementImpl.hpp" //********************************* namespace uml { class MultiplicityElementImpl : virtual public ElementImpl, virtual public MultiplicityElement { public: MultiplicityElementImpl(const MultiplicityElementImpl & obj); virtual std::shared_ptr copy() const; private: MultiplicityElementImpl& operator=(MultiplicityElementImpl const&) = delete; protected: friend class umlFactoryImpl; MultiplicityElementImpl(); virtual std::shared_ptr getThisMultiplicityElementPtr() const; virtual void setThisMultiplicityElementPtr(std::weak_ptr thisMultiplicityElementPtr); //Additional constructors for the containments back reference MultiplicityElementImpl(std::weak_ptr par_owner); public: //destructor virtual ~MultiplicityElementImpl(); //********************************* // Operations //********************************* /*! The operation compatibleWith takes another multiplicity as input. It returns true if the other multiplicity is wider than, or the same as, self. result = ((other.lowerBound() <= self.lowerBound()) and ((other.upperBound() = *) or (self.upperBound() <= other.upperBound())))

From package UML::CommonStructure.

*/ virtual bool compatibleWith(std::shared_ptr other) ; /*! The query includesMultiplicity() checks whether this multiplicity includes all the cardinalities allowed by the specified multiplicity. self.upperBound()->notEmpty() and self.lowerBound()->notEmpty() and M.upperBound()->notEmpty() and M.lowerBound()->notEmpty() result = ((self.lowerBound() <= M.lowerBound()) and (self.upperBound() >= M.upperBound()))

From package UML::CommonStructure.

*/ virtual bool includesMultiplicity(std::shared_ptr M) ; /*! The operation is determines if the upper and lower bound of the ranges are the ones given. result = (lowerbound = self.lowerBound() and upperbound = self.upperBound())

From package UML::CommonStructure.

*/ virtual bool is(int lowerbound,int upperbound) ; /*! The query isMultivalued() checks whether this multiplicity has an upper bound greater than one. upperBound()->notEmpty() result = (upperBound() > 1)

From package UML::CommonStructure.

*/ virtual bool isMultivalued() ; /*! The query lowerBound() returns the lower bound of the multiplicity as an integer, which is the integerValue of lowerValue, if this is given, and 1 otherwise. result = (if (lowerValue=null or lowerValue.integerValue()=null) then 1 else lowerValue.integerValue() endif)

From package UML::CommonStructure.

*/ virtual int lowerBound() ; /*! The lower bound must be a non-negative integer literal. lowerBound() >= 0 */ virtual bool lower_ge_0(Any diagnostics,std::map < Any, Any > context) ; /*! If it is not empty, then lowerValue must have an Integer value. lowerValue <> null implies lowerValue.integerValue() <> null */ virtual bool lower_is_integer(Any diagnostics,std::map < Any, Any > context) ; /*! The query upperBound() returns the upper bound of the multiplicity for a bounded multiplicity as an unlimited natural, which is the unlimitedNaturalValue of upperValue, if given, and 1, otherwise. result = (if (upperValue=null or upperValue.unlimitedValue()=null) then 1 else upperValue.unlimitedValue() endif)

From package UML::CommonStructure.

*/ virtual int upperBound() ; /*! The upper bound must be greater than or equal to the lower bound. upperBound() >= lowerBound() */ virtual bool upper_ge_lower(Any diagnostics,std::map < Any, Any > context) ; /*! If it is not empty, then upperValue must have an UnlimitedNatural value. upperValue <> null implies upperValue.unlimitedValue() <> null */ virtual bool upper_is_unlimitedNatural(Any diagnostics,std::map < Any, Any > context) ; /*! If a non-literal ValueSpecification is used for lowerValue or upperValue, then that specification must be a constant expression. */ virtual bool value_specification_constant(Any diagnostics,std::map < Any, Any > context) ; /*! If a non-literal ValueSpecification is used for lowerValue or upperValue, then evaluating that specification must not have side effects. */ virtual bool value_specification_no_side_effects(Any diagnostics,std::map < Any, Any > context) ; //********************************* // Attributes Getter Setter //********************************* /*! For a multivalued multiplicity, this attribute specifies whether the values in an instantiation of this MultiplicityElement are sequentially ordered.

From package UML::CommonStructure.

*/ virtual bool getIsOrdered() const ; /*! For a multivalued multiplicity, this attribute specifies whether the values in an instantiation of this MultiplicityElement are sequentially ordered.

From package UML::CommonStructure.

*/ virtual void setIsOrdered (bool _isOrdered); /*! For a multivalued multiplicity, this attributes specifies whether the values in an instantiation of this MultiplicityElement are unique.

From package UML::CommonStructure.

*/ virtual bool getIsUnique() const ; /*! For a multivalued multiplicity, this attributes specifies whether the values in an instantiation of this MultiplicityElement are unique.

From package UML::CommonStructure.

*/ virtual void setIsUnique (bool _isUnique); /*! The lower bound of the multiplicity interval.

From package UML::CommonStructure.

*/ virtual int getLower() const ; /*! The lower bound of the multiplicity interval.

From package UML::CommonStructure.

*/ virtual void setLower (int _lower); /*! The upper bound of the multiplicity interval.

From package UML::CommonStructure.

*/ virtual int getUpper() const ; /*! The upper bound of the multiplicity interval.

From package UML::CommonStructure.

*/ virtual void setUpper (int _upper); //********************************* // Reference //********************************* /*! The specification of the lower bound for this multiplicity.

From package UML::CommonStructure.

*/ virtual std::shared_ptr getLowerValue() const ; /*! The specification of the lower bound for this multiplicity.

From package UML::CommonStructure.

*/ virtual void setLowerValue(std::shared_ptr _lowerValue) ; /*! The specification of the upper bound for this multiplicity.

From package UML::CommonStructure.

*/ virtual std::shared_ptr getUpperValue() const ; /*! The specification of the upper bound for this multiplicity.

From package UML::CommonStructure.

*/ virtual void setUpperValue(std::shared_ptr _upperValue) ; //********************************* // Union Getter //********************************* /*! The Elements owned by this Element.

From package UML::CommonStructure.

*/ virtual std::shared_ptr> getOwnedElement() const ; //********************************* // Structural Feature Getter/Setter //********************************* virtual std::shared_ptr eContainer() const ; //********************************* // Persistence Functions //********************************* virtual void load(std::shared_ptr loadHandler) ; virtual void loadAttributes(std::shared_ptr loadHandler, std::map attr_list); virtual void loadNode(std::string nodeName, std::shared_ptr loadHandler); virtual void resolveReferences(const int featureID, std::list > references) ; virtual void save(std::shared_ptr saveHandler) const ; virtual void saveContent(std::shared_ptr saveHandler) const; protected: virtual std::shared_ptr eStaticClass() const; virtual Any eGet(int featureID, bool resolve, bool coreType) const ; virtual bool internalEIsSet(int featureID) const ; virtual bool eSet(int featureID, Any newValue) ; private: std::weak_ptr m_thisMultiplicityElementPtr; }; } #endif /* end of include guard: UML_MULTIPLICITYELEMENTMULTIPLICITYELEMENTIMPL_HPP */ // 1999 (c) // SFSGExtra.hpp #ifndef INCLUDED_SFSGEXTRA_H #define INCLUDED_SFSGEXTRA_H #include "MyOstream.hpp" #include "Monomial.hpp" #include "Polynomial.hpp" #include "ByAdmissible.hpp" #ifdef HAS_INCLUDE_NO_DOTS #include #include #else #include #include #endif class ReductionHint { public: typedef map,ByAdmissible>::iterator MI; MI d_iter; bool d_marked; public: ReductionHint() : d_marked(true) {}; ~ReductionHint() {}; void touch(bool b = true) { d_marked = b;}; bool touched() const { return d_marked;}; void print(MyOstream & os) const { os << (d_marked ? "true" : "false"); }; MI & iter() { return d_iter;}; friend MyOstream & operator<<(MyOstream & os,const ReductionHint & x) { os << (x.d_marked ? "true" : "false"); return os; }; }; #endif //------------------------------------------------------------------------- /* Copyright (C) 2010-2019 EDuke32 developers and contributors Copyright (C) 2019 sirlemonhead, Nuke.YKT This file is part of PCExhumed. PCExhumed 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ //------------------------------------------------------------------------- #include "ns.h" #include "lion.h" #include "engine.h" #include "runlist.h" #include "exhumed.h" #include "sequence.h" #include "move.h" #include "sound.h" #include "random.h" #include "trigdat.h" #include "items.h" #include BEGIN_PS_NS #define kMaxLions 40 short LionCount = -1; short MoveHook[kMaxLions]; static actionSeq ActionSeq[] = { {54, 1}, {18, 0}, {0, 0}, {10, 0}, {44, 0}, {18, 0}, {26, 0}, {34, 0}, {8, 1}, {9, 1}, {52, 1}, {53, 1} }; struct Lion { short nHealth; short nFrame; short nAction; short nSprite; short nTarget; short _f; short _g; }; Lion LionList[kMaxLions]; static SavegameHelper sgh("lion", SV(LionCount), SA(MoveHook), SA(LionList), nullptr); void InitLion() { LionCount = kMaxLions; } int BuildLion(short nSprite, int x, int y, int z, short nSector, short nAngle) { LionCount--; short nLion = LionCount; if (LionCount < 0) { return -1; } if (nSprite == -1) { nSprite = insertsprite(nSector, 104); } else { changespritestat(nSprite, 104); x = sprite[nSprite].x; y = sprite[nSprite].y; z = sector[sprite[nSprite].sectnum].floorz; nAngle = sprite[nSprite].ang; } assert(nSprite >= 0 && nSprite < kMaxSprites); sprite[nSprite].x = x; sprite[nSprite].y = y; sprite[nSprite].z = z; sprite[nSprite].cstat = 0x101; sprite[nSprite].clipdist = 60; sprite[nSprite].shade = -12; sprite[nSprite].xrepeat = 40; sprite[nSprite].yrepeat = 40; sprite[nSprite].picnum = 1; sprite[nSprite].pal = sector[sprite[nSprite].sectnum].ceilingpal; sprite[nSprite].xoffset = 0; sprite[nSprite].yoffset = 0; sprite[nSprite].ang = nAngle; sprite[nSprite].xvel = 0; sprite[nSprite].yvel = 0; sprite[nSprite].zvel = 0; sprite[nSprite].lotag = runlist_HeadRun() + 1; sprite[nSprite].hitag = 0; sprite[nSprite].extra = -1; // GrabTimeSlot(3); LionList[nLion].nAction = 0; LionList[nLion].nHealth = 500; LionList[nLion].nFrame = 0; LionList[nLion].nSprite = nSprite; LionList[nLion].nTarget = -1; LionList[nLion]._g = 0; LionList[nLion]._f = nLion; sprite[nSprite].owner = runlist_AddRunRec(sprite[nSprite].lotag - 1, nLion | 0x130000); MoveHook[nLion] = runlist_AddRunRec(NewRun, nLion | 0x130000); nCreaturesLeft++; return nLion | 0x130000; } void FuncLion(int a, int nDamage, int nRun) { short nLion = RunData[nRun].nVal; assert(nLion >= 0 && nLion < kMaxLions); short nSprite = LionList[nLion].nSprite; short nAction = LionList[nLion].nAction; bool bVal = false; int nMessage = a & kMessageMask; switch (nMessage) { default: { Printf("unknown msg %d for Lion\n", nMessage); return; } case 0x90000: { seq_PlotSequence(a, SeqOffsets[kSeqLion] + ActionSeq[nAction].a, LionList[nLion].nFrame, ActionSeq[nAction].b); return; } case 0xA0000: { nDamage = runlist_CheckRadialDamage(nSprite); // now fall through to 0x80000 fallthrough__; } case 0x80000: { if (nDamage && LionList[nLion].nHealth > 0) { LionList[nLion].nHealth -= nDamage; if (LionList[nLion].nHealth <= 0) { // R.I.P. sprite[nSprite].xvel = 0; sprite[nSprite].yvel = 0; sprite[nSprite].zvel = 0; sprite[nSprite].cstat &= 0xFEFE; LionList[nLion].nHealth = 0; nCreaturesLeft--; if (nAction < 10) { DropMagic(nSprite); if (nMessage == 0xA0000) { LionList[nLion].nAction = 11; } else { LionList[nLion].nAction = 10; } LionList[nLion].nFrame = 0; return; } } else { short nTarget = a & 0xFFFF; if (nTarget > -1) { if (sprite[nTarget].statnum < 199) { LionList[nLion].nTarget = nTarget; } if (nAction != 6) { if (RandomSize(8) <= (LionList[nLion].nHealth >> 2)) { LionList[nLion].nAction = 4; sprite[nSprite].xvel = 0; sprite[nSprite].yvel = 0; } else if (RandomSize(1)) { PlotCourseToSprite(nSprite, nTarget); LionList[nLion].nAction = 5; LionList[nLion]._g = RandomSize(3); sprite[nSprite].ang = (sprite[nSprite].ang - (RandomSize(1) << 8)) + (RandomSize(1) << 8); // NOTE: no angle mask in original code } else { LionList[nLion].nAction = 8; sprite[nSprite].xvel = 0; sprite[nSprite].yvel = 0; sprite[nSprite].cstat &= 0xFEFE; } LionList[nLion].nFrame = 0; } } } } return; } case 0x20000: { if (nAction != 7) { Gravity(nSprite); } short nSeq = SeqOffsets[kSeqLion] + ActionSeq[nAction].a; sprite[nSprite].picnum = seq_GetSeqPicnum2(nSeq, LionList[nLion].nFrame); seq_MoveSequence(nSprite, nSeq, LionList[nLion].nFrame); LionList[nLion].nFrame++; if (LionList[nLion].nFrame >= SeqSize[nSeq]) { LionList[nLion].nFrame = 0; bVal = true; } short nFlag = FrameFlag[SeqBase[nSeq] + LionList[nLion].nFrame]; short nTarget = LionList[nLion].nTarget; int nMov = MoveCreatureWithCaution(nSprite); switch (nAction) { default: return; case 0: case 1: { if ((LionList[nLion]._f & 0x1F) == (totalmoves & 0x1F)) { if (nTarget < 0) { nTarget = FindPlayer(nSprite, 40); if (nTarget >= 0) { D3PlayFX(StaticSound[kSound24], nSprite); LionList[nLion].nAction = 2; LionList[nLion].nFrame = 0; sprite[nSprite].xvel = Cos(sprite[nSprite].ang) >> 1; sprite[nSprite].yvel = Sin(sprite[nSprite].ang) >> 1; LionList[nLion].nTarget = nTarget; return; } } } if (nAction) { LionList[nLion]._g--; if (LionList[nLion]._g <= 0) { if (RandomBit()) { sprite[nSprite].ang = RandomWord() & kAngleMask; sprite[nSprite].xvel = Cos(sprite[nSprite].ang) >> 1; sprite[nSprite].yvel = Sin(sprite[nSprite].ang) >> 1; } else { sprite[nSprite].xvel = 0; sprite[nSprite].yvel = 0; } LionList[nLion]._g = 100; } } return; } case 2: { if ((totalmoves & 0x1F) == (LionList[nLion]._f & 0x1F)) { PlotCourseToSprite(nSprite, nTarget); int nAng = sprite[nSprite].ang & 0xFFF8; if (sprite[nSprite].cstat & 0x8000) { sprite[nSprite].xvel = Cos(nAng) * 2; sprite[nSprite].yvel = Sin(nAng) * 2; } else { sprite[nSprite].xvel = Cos(nAng) >> 1; sprite[nSprite].yvel = Sin(nAng) >> 1; } } if ((nMov & 0xC000) < 0x8000) { break; } else if ((nMov & 0xC000) == 0x8000) { // loc_378FA: sprite[nSprite].ang = (sprite[nSprite].ang + 256) & kAngleMask; sprite[nSprite].xvel = Cos(sprite[nSprite].ang) >> 1; sprite[nSprite].yvel = Sin(sprite[nSprite].ang) >> 1; break; } else if ((nMov & 0xC000) == 0xC000) { if ((nMov & 0x3FFF) == nTarget) { if (sprite[nSprite].cstat & 0x8000) { LionList[nLion].nAction = 9; sprite[nSprite].cstat &= 0x7FFF; sprite[nSprite].xvel = 0; sprite[nSprite].yvel = 0; } else { int nAng = getangle(sprite[nTarget].x - sprite[nSprite].x, sprite[nTarget].y - sprite[nSprite].y); if (AngleDiff(sprite[nSprite].ang, nAng) < 64) { LionList[nLion].nAction = 3; } } LionList[nLion].nFrame = 0; break; } else { // loc_378FA: sprite[nSprite].ang = (sprite[nSprite].ang + 256) & kAngleMask; sprite[nSprite].xvel = Cos(sprite[nSprite].ang) >> 1; sprite[nSprite].yvel = Sin(sprite[nSprite].ang) >> 1; break; } } break; } case 3: { if (nTarget == -1) { LionList[nLion].nAction = 1; LionList[nLion]._g = 50; } else { if (PlotCourseToSprite(nSprite, nTarget) >= 768) { LionList[nLion].nAction = 2; } else if (nFlag & 0x80) { runlist_DamageEnemy(nTarget, nSprite, 10); } } break; } case 4: { if (bVal) { LionList[nLion].nAction = 2; LionList[nLion].nFrame = 0; } if (nMov & 0x20000) { sprite[nSprite].xvel >>= 1; sprite[nSprite].yvel >>= 1; } return; } case 5: // Jump away when damaged { LionList[nLion]._g--; if (LionList[nLion]._g <= 0) { sprite[nSprite].zvel = -4000; LionList[nLion]._g = 0; int x = sprite[nSprite].x; int y = sprite[nSprite].y; int z = sprite[nSprite].z - (GetSpriteHeight(nSprite) >> 1); int nCheckDist = 0x7FFFFFFF; short nAngle = sprite[nSprite].ang; short nScanAngle = (sprite[nSprite].ang - 512) & kAngleMask; for (int i = 0; i < 5; i++) { short hitwall; int hitx, hity; vec3_t startPos = { x, y, z }; hitdata_t hitData; hitscan(&startPos, sprite[nSprite].sectnum, Cos(nScanAngle), Sin(nScanAngle), 0, &hitData, CLIPMASK1); hitx = hitData.pos.x; hity = hitData.pos.y; hitwall = hitData.wall; if (hitwall > -1) { int theX = klabs(hitx - x); int theY = klabs(hity - y); if ((theX + theY) < nCheckDist) { nCheckDist = theX; nAngle = nScanAngle; } } nScanAngle += 256; nScanAngle &= kAngleMask; } sprite[nSprite].ang = nAngle; LionList[nLion].nAction = 6; sprite[nSprite].xvel = (Cos(sprite[nSprite].ang)) - (Cos(sprite[nSprite].ang) >> 3); sprite[nSprite].yvel = (Sin(sprite[nSprite].ang)) - (Sin(sprite[nSprite].ang) >> 3); D3PlayFX(StaticSound[kSound24], nSprite); } return; } case 6: { if (nMov & 0x30000) { LionList[nLion].nAction = 2; LionList[nLion].nFrame = 0; return; } if ((nMov & 0xC000) == 0x8000) { LionList[nLion].nAction = 7; sprite[nSprite].ang = (GetWallNormal(nMov & 0x3FFF) + 1024) & kAngleMask; LionList[nLion]._g = RandomSize(4); return; } else if ((nMov & 0xC000) == 0xC000) { if ((nMov & 0x3FFF) == nTarget) { int nAng = getangle(sprite[nTarget].x - sprite[nSprite].x, sprite[nTarget].y - sprite[nSprite].y); if (AngleDiff(sprite[nSprite].ang, nAng) < 64) { LionList[nLion].nAction = 3; LionList[nLion].nFrame = 0; } } else { // loc_378FA: sprite[nSprite].ang = (sprite[nSprite].ang + 256) & kAngleMask; sprite[nSprite].xvel = Cos(sprite[nSprite].ang) >> 1; sprite[nSprite].yvel = Sin(sprite[nSprite].ang) >> 1; break; } } return; } case 7: { LionList[nLion]._g--; if (LionList[nLion]._g <= 0) { LionList[nLion]._g = 0; if (nTarget > -1) { PlotCourseToSprite(nSprite, nTarget); } else { sprite[nSprite].ang = (RandomSize(9) + (sprite[nSprite].ang + 768)) & kAngleMask; } sprite[nSprite].zvel = -1000; LionList[nLion].nAction = 6; sprite[nSprite].xvel = (Cos(sprite[nSprite].ang)) - (Cos(sprite[nSprite].ang) >> 3); sprite[nSprite].yvel = (Sin(sprite[nSprite].ang)) - (Sin(sprite[nSprite].ang) >> 3); D3PlayFX(StaticSound[kSound24], nSprite); } return; } case 8: { if (bVal) { LionList[nLion].nAction = 2; LionList[nLion].nFrame = 0; sprite[nSprite].cstat |= 0x8000; } return; } case 9: { if (bVal) { LionList[nLion].nFrame = 0; LionList[nLion].nAction = 2; sprite[nSprite].cstat |= 0x101; } return; } case 10: case 11: { if (bVal) { runlist_SubRunRec(sprite[nSprite].owner); runlist_SubRunRec(MoveHook[nLion]); sprite[nSprite].cstat = 0x8000; } return; } } // loc_379AD: ? if (nAction != 1 && nTarget != -1) { if (!(sprite[nTarget].cstat & 0x101)) { LionList[nLion].nAction = 1; LionList[nLion].nFrame = 0; LionList[nLion]._g = 100; LionList[nLion].nTarget = -1; sprite[nSprite].xvel = 0; sprite[nSprite].yvel = 0; } } return; } } } END_PS_NS thatoddmailbox/duck_hero #ifndef _LOG_HPP #define _LOG_HPP #include #include namespace duckhero { class Log { public: static void Warning(std::string tag, std::string message); }; } #endif1-10 /* Copyright 2021 The TensorFlow 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 "tensorflow/compiler/tf2tensorrt/convert/trt_layout_optimization_pass.h" #include "absl/strings/ascii.h" #include "absl/strings/escaping.h" #include "absl/strings/match.h" #include "absl/strings/str_cat.h" #include "tensorflow/compiler/tf2tensorrt/convert/convert_graph.h" #include "tensorflow/compiler/tf2tensorrt/convert/utils.h" #include "tensorflow/core/common_runtime/graph_constructor.h" #include "tensorflow/core/grappler/clusters/cluster.h" #include "tensorflow/core/grappler/grappler_item.h" #include "tensorflow/core/grappler/optimizers/custom_graph_optimizer_registry.h" #include "tensorflow/core/grappler/utils/functions.h" #include "tensorflow/core/lib/strings/numbers.h" #include "tensorflow/core/lib/strings/str_util.h" #include "tensorflow/core/lib/strings/strcat.h" #include "tensorflow/core/platform/casts.h" #include "tensorflow/core/platform/logging.h" #include "tensorflow/core/platform/stacktrace.h" #if GOOGLE_CUDA && GOOGLE_TENSORRT namespace tensorflow { namespace tensorrt { namespace convert { using absl::AsciiStrToUpper; using absl::StrAppend; using absl::StrCat; TRTLayoutOptimizationPass::TRTLayoutOptimizationPass(const string& name) : name_(name), trt_logger_name_("DefaultLogger"), minimum_segment_size_(3), is_dynamic_op_(false), max_cached_batches_(1), max_workspace_size_bytes_(256LL << 20) { VLOG(1) << "Constructing " << name_; } Status TRTLayoutOptimizationPass::Optimize(grappler::Cluster* cluster, const grappler::GrapplerItem& item, GraphDef* optimized_graph) { GraphDef modified_graph_def = item.graph; // Construct a GrapplerItem using the modified graph_def and the input // grappler_item. grappler::GrapplerItem grappler_item = grappler_item.WithGraph(std::move(modified_graph_def)); const GraphDef& graph_def = grappler_item.graph; // Convert graphdef to graph. FunctionLibraryDefinition flib(OpRegistry::Global(), graph_def.library()); Graph graph(flib); TF_RETURN_IF_ERROR( ConvertGraphDefToGraph(GraphConstructorOptions(), graph_def, &graph)); // Algorithm steps: // 1. We iterate over the graph to find any Conv (or other layout sensitive // op) // 2. If found, we continue, else we return // 3. We iterate over the nodes and replace the layout-sensitive params // 3. We add Transpose before the inputs and after the outputs grappler::GraphProperties static_graph_properties(grappler_item); std::cout << "TRTLayoutOptimizationPass: reading nodes..." << std::endl; for (Node* node : graph.nodes()) { std::cout << node->name() << std::endl; } // TODO: assign output *optimized_graph =; } Status TRTLayoutOptimizationPass::Init( const RewriterConfig_CustomGraphOptimizer* config) { std::cout << "Do nothing for now" << std::endl; } } // namespace convert } // namespace tensorrt } // namespace tensorflow #endif // GOOGLE_CUDA && GOOGLE_TENSORRT /* * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or * its licensors. * * For complete copyright and license terms please see the LICENSE at the root of this * distribution (the "License"). All use of this software is governed by the License, * or, if provided, by the license below or the license accompanying this file. Do not * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * */ #include #include #include #include namespace AZ { namespace RC { using ::testing::Const; using ::testing::Return; using ::testing::ReturnRef; using ::testing::_; class ContainerSettingsExporterContextTestBase : public CgfExporterContextTestBase { public: ContainerSettingsExporterContextTestBase() : m_stubMeshAdvancedRule(new SceneAPI::DataTypes::MockIMeshAdvancedRule()) { m_ruleContainer.AddRule(m_stubMeshAdvancedRule); } ~ContainerSettingsExporterContextTestBase() override = default; protected: // Minimal subset for check // - Group has advanced rule // - Advanced rule defines 32 bit vertex precision to be true void SetUp() override { CgfExporterContextTestBase::SetUp(); EXPECT_CALL(*m_stubMeshAdvancedRule, Use32bitVertices()) .WillRepeatedly(Return(true)); EXPECT_CALL(*m_stubMeshAdvancedRule, MergeMeshes()) .WillRepeatedly(Return(false)); ON_CALL(m_stubMeshGroup, GetRuleContainer()) .WillByDefault(ReturnRef(m_ruleContainer)); ON_CALL(Const(m_stubMeshGroup), GetRuleContainerConst()) .WillByDefault(ReturnRef(m_ruleContainer)); } bool TestDataChanged() { return m_outContent.GetExportInfo()->bWantF32Vertices; } AZStd::shared_ptr m_stubMeshAdvancedRule; SceneAPI::Containers::RuleContainer m_ruleContainer; ContainerSettingsExporter m_testExporter; }; class ContainerSettingsExporterNoOpTests : public ContainerSettingsExporterContextTestBase { public: ~ContainerSettingsExporterNoOpTests() override = default; }; TEST_P(ContainerSettingsExporterNoOpTests, Process_UnsupportedContext_ExportInfoNotChanged) { m_testExporter.Process(m_stubContext); EXPECT_FALSE(TestDataChanged()); } static const ContextPhaseTuple g_unsupportedContextPhaseTuples[] = { { TestContextMeshGroup, Phase::Construction }, { TestContextMeshGroup, Phase::Filling }, { TestContextMeshGroup, Phase::Finalizing }, { TestContextContainer, Phase::Filling }, { TestContextContainer, Phase::Finalizing }, { TestContextNode, Phase::Construction }, { TestContextNode, Phase::Filling }, { TestContextNode, Phase::Finalizing }, { TestContextMeshNode, Phase::Construction }, { TestContextMeshNode, Phase::Filling }, { TestContextMeshNode, Phase::Finalizing } }; INSTANTIATE_TEST_CASE_P(ContainerSettingsExporter, ContainerSettingsExporterNoOpTests, ::testing::ValuesIn(g_unsupportedContextPhaseTuples)); class ContainerSettingsExporterSimpleTests : public ContainerSettingsExporterContextTestBase { public: ~ContainerSettingsExporterSimpleTests() override = default; }; TEST_P(ContainerSettingsExporterSimpleTests, Process_SupportedContext_ExportInfoChanged) { m_testExporter.Process(m_stubContext); EXPECT_TRUE(TestDataChanged()); } static const ContextPhaseTuple g_supportedContextPhaseTuples[] = { {TestContextContainer, Phase::Construction} }; INSTANTIATE_TEST_CASE_P(ContainerSettingsExporter, ContainerSettingsExporterSimpleTests, ::testing::ValuesIn(g_supportedContextPhaseTuples)); } // namespace RC } // namespace AZ1-10 #include "lib.h" #include namespace { using Grid = std::vector>; const std::vector> directions{ {-1, -1}, {-1, 0}, {-1, 1}, {0, -1}, {0, 1}, {1, -1}, {1, 0}, {1, 1}, }; Grid parse_grid(const std::vector &input) { Grid grid; for (const auto &line : input) { std::vector row; for (const auto &ch : line) { row.emplace_back(static_cast(ch - '0')); } grid.emplace_back(std::move(row)); } return grid; } int64_t count_grid_cells(const Grid &grid) { size_t count = 0; for (const auto &row : grid) { count += row.size(); } return count; } int64_t do_step(Grid &grid) { std::deque> queue; for (size_t i = 0; i < grid.size(); ++i) { for (size_t j = 0; j < grid[i].size(); ++j) { grid[i][j] += 1; if (grid[i][j] > 9) { queue.emplace_back(i, j); } } } while (!queue.empty()) { auto current = queue.front(); queue.pop_front(); for (const auto &direction : directions) { auto i = current.first + direction.first; auto j = current.second + direction.second; if (i >= 0 && i < static_cast(grid.size()) && j >= 0 && j < static_cast(grid[i].size()) && grid[i][j] <= 9) { grid[i][j] += 1; if (grid[i][j] > 9) { queue.emplace_back(i, j); } } } } int64_t flash_count = 0; for (size_t i = 0; i < grid.size(); ++i) { for (size_t j = 0; j < grid[i].size(); ++j) { if (grid[i][j] > 9) { flash_count += 1; grid[i][j] = 0; } } } return flash_count; } } int64_t day11::run_part1(const std::vector &input) { auto grid = parse_grid(input); int64_t flash_count = 0; for (size_t i = 0; i < 100; ++i) { flash_count += do_step(grid); } return flash_count; } int64_t day11::run_part2(const std::vector &input) { auto grid = parse_grid(input); auto cell_count = count_grid_cells(grid); for (int64_t step_count = 1;; ++step_count) { if (do_step(grid) == cell_count) { return step_count; } } } #include #include #include #include #include #include #include #include #include #include WallSwitch::WallSwitch(Settings& settings, MiLightClient*& milightClient, GroupStateStore*& stateStore, MqttClient& mqttClient) : milightClient(milightClient), settings(settings), stateStore(stateStore), mqttClient(mqttClient), oneWire(ONE_WIRE_BUS), sensors(&oneWire) { } WallSwitch::~WallSwitch() { } void WallSwitch::begin() { //begin DS18B20 sensor sensors.setResolution(12); sensors.begin(); if (settings.gatewayConfigs.size() > 0) { remoteConfig = MiLightRemoteConfig::fromType("rgb_cct"); // Set button input pins for (uint8_t i = 0; i < 3; i++) { pinMode(buttonPins[i], INPUT_PULLUP); } //set ADC port to input for LDR pinMode(A0, INPUT_PULLUP); delayTimer = millis(); startupTimer = random(15000, 30000); } } void WallSwitch::loop(bool standAloneAP) { //Get button event and act accordingly when UDP gateway configured if (settings.gatewayConfigs.size() > 0) { //Startup with all lamps off doLightState(); for (uint8_t i = 0; i < 3; i++) { checkButton(buttonPins[i], i); } //Switch lamps on LDR state, only in AP mode if (standAloneAP) { doDayNight(); } else { detectMotion(); } } //Publish heap and temperature if (millis() - lastMsg > 300000) { lastMsg = millis(); char topic[128]; char msg[64]; snprintf(topic, sizeof(topic), "state/%s/heap", WiFi.macAddress().c_str()); snprintf(msg, sizeof(msg), "%d", ESP.getFreeHeap()); mqttClient.send(topic, msg, false); //send the DS18B20 temperature if available int deviceCount = sensors.getDeviceCount(); //Serial.print("deviceCount:"); //Serial.println(String(deviceCount).c_str()); sensors.requestTemperatures(); if (deviceCount > 0) { snprintf(topic, sizeof(topic), "state/%s/temperature", WiFi.macAddress().c_str()); dtostrf(sensors.getTempCByIndex(0),5, 2, msg); mqttClient.send(topic, msg, false); } } } //handle button press void WallSwitch::checkButton(int buttonPin, uint8_t id) { currentState[id] = digitalRead(buttonPin); if (currentState[id] == LOW && previousState[id] == HIGH && (millis() - firstTime[id]) > 100) { firstTime[id] = millis(); buttonDirty[id] = true; initLongClick[id] = true; mqttClient.disableReceive(); // dinable receiving MQTT commands on button press } if (currentState[id] == LOW) { millis_held[id] = (millis() - firstTime[id]); } //reset clicks after long press and toggle raising states if (millis_held[id] > 500 && currentState[id] == HIGH && previousState[id] == LOW) { if (shortClicks[id] == 0) {raisingBrightness[id] = !raisingBrightness[id];} if (shortClicks[id] == 1) {raisingTemperature[id] = !raisingTemperature[id];} shortClicks[id] = 0; } if (millis() > timePressLimit[id] && currentState[id] == HIGH && shortClicks[id] != 0) { doShortClicks(id); shortClicks[id] = 0; } if (millis_held[id] > 50) { if (currentState[id] == HIGH && previousState[id] == LOW && millis_held[id] <= 500) { //count short clicks shortClicks[id]++; timePressLimit[id] = firstTime[id] + 1000; } if (millis_held[id] > 500 && currentState[id] == LOW && millis_held[id] < 10000) { doLongClicks(id); } } if (buttonDirty[id] == true && currentState[id] == HIGH && (millis() - firstTime[id]) > 2000) { buttonDirty[id] = false; mqttClient.enableReceive(); // enable receiving MQTT commands after button press sendMQTTCommand(id); } previousState[id] = currentState[id]; } //handle short clicks void WallSwitch::doShortClicks(uint8_t id) { milightClient->prepare(remoteConfig, settings.gatewayConfigs[0]->deviceId, id + 1); if (shortClicks[id] == 1) { milightClient->updateStatus(OFF); } if (shortClicks[id] == 2) { milightClient->enableNightMode(); //no Off command to other espMH's: buttonDirty[id] = false; } if (shortClicks[id] == 3) { milightClient->updateColorWhite(); } if (shortClicks[id] == 4) { milightClient->updateStatus(OFF); ESP.restart(); } } //handle long clicks void WallSwitch::doLongClicks(uint8_t id) { BulbId bulbId(settings.gatewayConfigs[0]->deviceId, id + 1, remoteConfig->type); milightClient->prepare(remoteConfig, settings.gatewayConfigs[0]->deviceId, id + 1); milightClient->setRepeatsOverride(10); //set lamps on before raising brightness and initialize raising state if (initLongClick[id]) { uint8_t brightness = stateStore->get(bulbId)->getBrightness(); if (brightness > 90) {raisingBrightness[id] = false;} if (brightness < 10) {raisingBrightness[id] = true;} uint16_t temperature = stateStore->get(bulbId)->getMireds(); if (temperature > COLOR_TEMP_MAX_MIREDS - 10) {raisingTemperature[id] = false;} if (temperature < COLOR_TEMP_MIN_MIREDS + 10) {raisingTemperature[id] = true;} initLongClick[id] = false; } if (millis() - millis_repeat[id] < 100) { return; } millis_repeat[id] = millis(); //send always an ON command to ensure the lamp is on milightClient->updateStatus(ON); //Brightness if (shortClicks[id] == 0) { uint8_t brightness = stateStore->get(bulbId)->getBrightness(); if (brightness < 100 && raisingBrightness[id] == true) { brightness += 10; milightClient->updateBrightness(brightness); } if (brightness > 0 && raisingBrightness[id] == false) { brightness -= 10; milightClient->updateBrightness(brightness); } } //Temperature if (shortClicks[id] == 1) { uint16_t temperature = stateStore->get(bulbId)->getMireds(); if (temperature < COLOR_TEMP_MAX_MIREDS && raisingTemperature[id] == true) { temperature += 10; milightClient->updateTemperature(Units::miredsToWhiteVal(temperature, 100)); } if (temperature > COLOR_TEMP_MIN_MIREDS && raisingTemperature[id] == false) { temperature -= 10; milightClient->updateTemperature(Units::miredsToWhiteVal(temperature, 100)); } } milightClient->clearRepeatsOverride(); } //Send command update to MQTT mesh_in/milight to update other devices with same bulbId void WallSwitch::sendMQTTCommand(uint8_t id) { BulbId bulbId(settings.gatewayConfigs[0]->deviceId, id + 1, remoteConfig->type); char buffer[200]; StaticJsonDocument<200> json; JsonObject message = json.to(); GroupState* groupState = stateStore->get(bulbId); if (groupState == NULL) return; groupState->applyState(message, bulbId, settings.groupStateFields); json.add("repeats"); json["repeats"] = "NO"; serializeJson(json, buffer); String topic = settings.mqttTopicPattern; String hexDeviceId = bulbId.getHexDeviceId(); topic.replace(":device_id", hexDeviceId); topic.replace(":hex_device_id", hexDeviceId); topic.replace(":dec_device_id", String(bulbId.deviceId)); topic.replace(":device_type", MiLightRemoteTypeHelpers::remoteTypeToString(bulbId.deviceType)); topic.replace(":group_id", String(bulbId.groupId)); #ifdef MQTT_DEBUG Serial.printf("WallSwitch - send message to topic: %s : %s\r\n", topic.c_str(), output); #endif //send command to milight/xxx/xxx/x mqttClient.send(topic.c_str(), buffer, false); } //handle actions based on LDR state void WallSwitch::doDayNight() { //detect night with LDR on A0 pin if (lastAnalogRead + 1000 < millis()) { lastAnalogRead = millis(); darknessLevel = analogRead(A0); #ifdef DEBUG_PRINTF Serial.printf("darknessLevel: %s\r\n", darknessLevel); #endif } if (darknessLevel > 350) { //0-1024, 1024 is dark, 0-1.024V, LDR between ADC and GND, and pullup resistor if (previousDelay == false && isNight == false) { delayTimer = millis(); previousDelay = true; } if (delayTimer + 60000 < millis() && isNight == false && previousDelay == true) { isNight = true; previousDelay = false; } nightTimer = (millis()/1000) - nightTime; } else if (darknessLevel < 250) { if (previousDelay == false && isNight == true) { delayTimer = millis(); previousDelay = true; } if (delayTimer + 60000 < millis() && isNight == true && previousDelay == true) { isNight = false; isMidNight = false; previousDelay = false; } nightTimer = 0; } if (previousNight == false && isNight == true){ Serial.println(F("LDR triggered night condition, turn lamps on...")); nightTime = millis()/1000; milightClient->prepare(remoteConfig, settings.gatewayConfigs[0]->deviceId, 1); //zithoek milightClient->updateStatus(ON); milightClient->updateTemperature(100); milightClient->updateBrightness(1); milightClient->prepare(remoteConfig, settings.gatewayConfigs[0]->deviceId, 2); //keuken milightClient->enableNightMode(); milightClient->prepare(remoteConfig, settings.gatewayConfigs[0]->deviceId, 3); //kinderhoek milightClient->enableNightMode(); milightClient->prepare(remoteConfig, settings.gatewayConfigs[0]->deviceId, 4); //buitenverlichting milightClient->updateStatus(ON); milightClient->updateTemperature(100); milightClient->updateBrightness(50); } if (nightTimer > 10800 && isMidNight == false) { //after 3 hours turn lamps on night mode Serial.println(F("Nightmode timeout, turn light in nightmode")); isMidNight = true; milightClient->prepare(remoteConfig, settings.gatewayConfigs[0]->deviceId, 4); //outdoor light milightClient->enableNightMode(); } if (previousNight == true && isNight == false){ Serial.println(F("LDR triggered day condition, turn lamps off...")); milightClient->prepare(remoteConfig, settings.gatewayConfigs[0]->deviceId, 0); //all lamps off milightClient->updateStatus(OFF); } previousNight = isNight; } void WallSwitch::detectMotion() { if (lastAnalogRead + 500 < millis()) { lastAnalogRead = millis(); motionLevel = analogRead(A0); } boolean motion = (motionLevel > 1000) ? true : false; if (motion == true && previousMotion == false) { firstMotion = millis(); } if (motion == true && motionState == false && (millis() - firstMotion) > 1000) { motionState = true; char topic[128]; snprintf(topic, sizeof(topic), "state/%s/motion", WiFi.macAddress().c_str()); mqttClient.send(topic, "ON", false); } if (motion == false && motionState == true) { motionState = false; char topic[128]; snprintf(topic, sizeof(topic), "state/%s/motion", WiFi.macAddress().c_str()); mqttClient.send(topic, "OFF", false); } previousMotion = motion; } //Non blocking startup items void WallSwitch::doLightState() { //turn all lights off at startup if (isStartUp == true && millis() > startupTimer) { isStartUp = false; for (size_t i = 1; i <= remoteConfig->numGroups; i++) { milightClient->prepare(remoteConfig, settings.gatewayConfigs[0]->deviceId, i); milightClient->updateTemperature(100); milightClient->updateStatus(OFF); } } } #include "Player.h" #include "Table.h" #include using namespace std; void Player::addPoints(int newPoints){ this->points+=newPoints; } Player::Player(string name){ this->name = name; this->points = 0; int i,j; for (i = 0; i < 5; i++){ vector columns; this->wallTiles.push_back(columns); } for (i = 0; i < 5; i++){ for (j = 0; j < 5; j++){ this->wallTiles[i].push_back('-'); } } for (i = 0; i < 5; i++){ vector rows; this->sampleTiles.push_back(rows); } for (i = 0; i < 5; i++){ for(j = 0; j < i+1; j++){ this->sampleTiles[i].push_back('-'); } } } Player::Player(){ this->name = ""; this->points = 0; int i,j; for (i = 0; i < 5; i++){ vector columns; this->wallTiles.push_back(columns); } for (i = 0; i < 5; i++){ for (j = 0; j < 5; j++){ this->wallTiles[i].push_back('-'); } } for (i = 0; i < 5; i++){ vector rows; this->sampleTiles.push_back(rows); } for (i = 0; i < 5; i++){ for(j = 0; j < i+1; j++){ this->sampleTiles[i].push_back('-'); } } } Player::Player(const Player &p){ name=p.name; this->points = p.points; int i,j; for (i = 0; i < p.wallTiles.size(); i++){ vector columns; this->wallTiles.push_back(columns); } for (i = 0; i < p.wallTiles.size(); i++){ for (j = 0; j < p.wallTiles[i].size(); j++){ this->wallTiles[i].push_back(p.wallTiles[i][j]); } } for (i = 0; i < p.sampleTiles.size(); i++){ vector rows; this->sampleTiles.push_back(rows); } for (i = 0; i < p.sampleTiles.size(); i++){ for (j = 0; j < p.sampleTiles[i].size(); j++){ this->sampleTiles[i].push_back(p.sampleTiles[i][j]); } } for (i = 0; i < p.floorTiles.size(); i++) this->floorTiles[i] = p.floorTiles[i]; } int Player::getPoint(){ return this->points; } string Player::getName(){ return this->name; } char Player::chooseTile(Table* table){ int input; firstQuestion: std::cout << this->name << ": Do you want to choose from disk[0] or centre[1]?\n"; std::cin>>input; if(input==0){ char tile_type; std::cout << this->name << ": Which disk?\n"; std::cin>>input; std::cout << this->name << ": Which tile type?\n"; std::cin>>tile_type; std::vector choosedTiles=table->getTiles(input, tile_type); } else if(input==1){ } else{ std::cout << "Not Valid answer!\n"; goto firstQuestion; }; return 'A'; } void Player::show(){ std::cout << "Player name: " << this->getName() <<'\n'; std::cout << "Points: " << this->getPoint() <<'\n'; std::cout << "1 2 3 4 5" << '\n'; for(int i=0; i< 5; i++){ for(int j=0; j< 5; j++){ std::cout << this->wallTiles[i][j] << " "; } std::cout << i+1 << " "; for(int j=0; j< i+1; j++){ std::cout << this->sampleTiles[i][j] << " "; } std::cout <<"\n"; } } void Player::updateWall(Table* table){ std::cout << "Player.updateWall\n"; } bool Player::isWallFirstRowFilled(){ return true; } #pragma once #include "../../../../common.hpp" #include "../../IParsable.hpp" namespace oless { namespace excel { namespace structures { namespace formulas { // see: https://docs.microsoft.com/en-us/openspecs/office_file_formats/ms-xls/6037ca97-0e46-48e0-9de8-8527f345b549 // The PtgErr operand specifies an error code. class ExtPtgErr : public IParseable { private: unsigned char ptg : 7; unsigned char A : 1; unsigned char err; public: virtual void Parse(unsigned char* buffer, std::size_t max, unsigned int offset) override { unsigned int index = offset; this->ptg = common::ExtractBits(buffer[index], 7, 1); this->A = common::ExtractBits(buffer[index], 1, 8); index++; this->err = buffer[index]; index++; this->bytesRead = index - offset; } }; } } } }#include "Examples.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace System; using namespace Aspose::Email; using namespace Aspose::Email::Clients::Exchange::WebService; using namespace Aspose::Email::Calendar; using namespace Aspose::Email::Calendar::Recurrences; void SendMeetingRequestsUsingEWS() { try { // Create instance of IEWSClient class by giving credentials System::SharedPtr client = GetExchangeEWSClient(GetExchangeTestUser()); // Create the meeting request System::SharedPtr app = System::MakeObject(u"meeting request", System::DateTime::get_Now().AddHours(1), System::DateTime::get_Now().AddHours(1.5), MailAddress::to_MailAddress(u""), MailAddressCollection::to_MailAddressCollection(u"")); app->set_Summary(u"meeting request summary"); app->set_Description(u"description"); System::SharedPtr pattern = System::MakeObject(System::DateTime::get_Now().AddDays(5)); app->set_Recurrence(pattern); // Create the message and set the meeting request System::SharedPtr msg = System::MakeObject(); msg->set_From(MailAddress::to_MailAddress(u"")); msg->set_To(MailAddressCollection::to_MailAddressCollection(u"")); msg->set_IsBodyHtml(true); msg->set_HtmlBody(u"

HTML Heading

Email Message detail

"); msg->set_Subject(u"meeting request"); msg->AddAlternateView(app->RequestApointment(0)); // send the appointment client->Send(msg); System::Console::WriteLine(u"Appointment request sent"); } catch (System::Exception& ex) { System::Console::WriteLine(ex->get_Message()); } } 1-10 #ifndef TCLCALLBACKMESSAGES_HH #define TCLCALLBACKMESSAGES_HH #include "CliListener.hh" #include namespace openmsx { class GlobalCliComm; class CommandController; class TclCallback; class TclCallbackMessages : public CliListener { public: TclCallbackMessages(GlobalCliComm& cliComm, CommandController& controller); virtual ~TclCallbackMessages(); virtual void log(CliComm::LogLevel level, string_ref message); virtual void update(CliComm::UpdateType type, string_ref machine, string_ref name, string_ref value); private: GlobalCliComm& cliComm; const std::unique_ptr messageCallback; }; } // namespace openmsx #endif // 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 "chrome/updater/win/scoped_impersonation.h" #include "base/logging.h" #include "chrome/updater/win/win_util.h" namespace updater { HRESULT ScopedImpersonation::Impersonate(HANDLE token) { if (!token) return E_FAIL; result_ = ::ImpersonateLoggedOnUser(token) ? S_OK : HRESULTFromLastError(); DCHECK_EQ(result_, S_OK); return result_; } ScopedImpersonation::~ScopedImpersonation() { if (result_ != S_OK) return; CHECK(::RevertToSelf()); } } // namespace updater #include "CMainWindow.h" int main( int argc, char** argv ) { CMainWindow* window = new CMainWindow(); return window->execute(); } src-cpp/d3d10/d3d10_rasterizer.cpp #include "d3d10_rasterizer.h" namespace dxvk { HRESULT STDMETHODCALLTYPE D3D10RasterizerState::QueryInterface( REFIID riid, void** ppvObject) { if (ppvObject == nullptr) return E_POINTER; *ppvObject = nullptr; if (riid == __uuidof(IUnknown) || riid == __uuidof(ID3D10DeviceChild) || riid == __uuidof(ID3D10RasterizerState)) { *ppvObject = ref(this); return S_OK; } if (riid == __uuidof(ID3D11DeviceChild) || riid == __uuidof(ID3D11RasterizerState)) { *ppvObject = ref(m_d3d11); return S_OK; } Logger::warn("D3D10RasterizerState::QueryInterface: Unknown interface query"); Logger::warn(str::format(riid)); return E_NOINTERFACE; } void STDMETHODCALLTYPE D3D10RasterizerState::GetDesc( D3D10_RASTERIZER_DESC* pDesc) { static_assert(sizeof(D3D10_RASTERIZER_DESC) == sizeof(D3D11_RASTERIZER_DESC)); m_d3d11->GetDesc(reinterpret_cast(pDesc)); } }#include "depthmap_stitcher_group.hpp" #include #include #include #include #include #include DepthmapStitcherGroup::DepthmapStitcherGroup() {} DepthmapStitcherGroup::~DepthmapStitcherGroup() {} //struct DepthmapStitcherGroup::ReprojectionResidual_fixed { // ReprojectionResidual_fixed(double* bilinear_weight_list_tar, // double depth_value_tar, double depth_value_ref, // int grid_width, int grid_height) : // bilinear_weight_list_tar_(bilinear_weight_list_tar), // depth_value_tar_(depth_value_tar), depth_value_ref_(depth_value_ref), // grid_width_(grid_width), grid_height_(grid_height) {} // // template // bool operator()(T const* const* scale_offset_list, T* residual) const // { // const T* scale_list_tar = scale_offset_list[0]; // const T* offset_list_tar = scale_offset_list[1]; // T scale_tar(0); // T offset_tar(0); // for (int index = 0; index < grid_width_ * grid_height_; index++) // { // scale_tar += scale_list_tar[index] * bilinear_weight_list_tar_[index]; // offset_tar += offset_list_tar[index] * bilinear_weight_list_tar_[index]; // } // T temp = (depth_value_tar_ * scale_tar + offset_tar) - depth_value_ref_ ; // residual[0] = temp * temp; // return true; // } // //private: // const double depth_value_ref_; // the depth value of source depth map // const double depth_value_tar_; // the depth value of corresponding pixel in reference depth map // const double* bilinear_weight_list_tar_; // weight of S and A, length is grid_x * grid_y // const int grid_width_; // the weight grid along the x axis // const int grid_height_; // the weight grid along the y axis //}; // TODO capsule more function to refer Ceres demo. struct DepthmapStitcherGroup::ReprojectionResidual { ReprojectionResidual(double* bilinear_weight_list_tar, double* bilinear_weight_list_src, double depth_value_tar, double depth_value_src, int grid_width, int grid_height) : bilinear_weight_list_tar_(bilinear_weight_list_tar), bilinear_weight_list_src_(bilinear_weight_list_src), depth_value_tar_(depth_value_tar), depth_value_src_(depth_value_src), grid_width_(grid_width), grid_height_(grid_height) {} template bool operator()(T const* const* scale_offset_list, T* residual) const { const T* scale_list_src = scale_offset_list[0]; const T* offset_list_src = scale_offset_list[1]; const T* scale_list_tar = scale_offset_list[2]; const T* offset_list_tar = scale_offset_list[3]; T scale_src(0); T offset_src(0); T scale_tar(0); T offset_tar(0); for (int index = 0; index < grid_width_ * grid_height_; index++) { scale_src += scale_list_src[index] * bilinear_weight_list_src_[index]; offset_src += offset_list_src[index] * bilinear_weight_list_src_[index]; scale_tar += scale_list_tar[index] * bilinear_weight_list_tar_[index]; offset_tar += offset_list_tar[index] * bilinear_weight_list_tar_[index]; } T temp = (depth_value_tar_ * scale_tar + offset_tar) - (depth_value_src_ * scale_src + offset_src); //T temp = (depth_value_tar_ * scale_tar + offset_tar) - depth_value_src_ ; residual[0] = temp * temp; return true; } private: const double depth_value_src_; // the depth value of source depth map const double depth_value_tar_; // the depth value of corresponding pixel in reference depth map const double* bilinear_weight_list_tar_; // weight of S and A, length is grid_x * grid_y const double* bilinear_weight_list_src_; // weight of S and A, length is grid_x * grid_y const int grid_width_; // the weight grid along the x axis const int grid_height_; // the weight grid along the y axis }; // @see hedman2018instant:equ_6 struct DepthmapStitcherGroup::SmoothnessResidual_S { SmoothnessResidual_S(int* index_current, int* index_neighbour, int edge_number, int grid_x, int grid_y) : grid_width_(grid_x), grid_height_(grid_y), index_current_(index_current), index_neighbour_(index_neighbour), edge_number_(edge_number) {} template bool operator()(T const* const* scale_offset_list, T* residual) const { const T* scale_list = scale_offset_list[0]; //const T* offset_list = scale_offset_list[1]; T sum_value(0); for (int index = 0; index < edge_number_; index++) { int curr_index = index_current_[index]; int neig_index = index_neighbour_[index]; T scale_diff = scale_list[curr_index] - scale_list[neig_index]; //T offset_diff = offset_list[curr_index] - offset_list[neig_index]; sum_value += scale_diff * scale_diff;// +offset_diff * offset_diff; } residual[0] = sum_value; return true; } private: const int grid_width_; // the weight grid along the x axis const int grid_height_; // the weight grid along the y axis const int* index_current_; // the weight grid along the x axis const int* index_neighbour_; // the weight grid along the y axis const int edge_number_; }; // @see hedman2018instant:equ_6 struct DepthmapStitcherGroup::SmoothnessResidual_O { SmoothnessResidual_O(int* index_current, int* index_neighbour, int edge_number, int grid_x, int grid_y) : grid_width_(grid_x), grid_height_(grid_y), index_current_(index_current), index_neighbour_(index_neighbour), edge_number_(edge_number) {} template bool operator()(T const* const* scale_offset_list, T* residual) const { const T* scale_list = scale_offset_list[0]; const T* offset_list = scale_offset_list[1]; T sum_value(0); for (int index = 0; index < edge_number_; index++) { int curr_index = index_current_[index]; int neig_index = index_neighbour_[index]; //T scale_diff = scale_list[curr_index] - scale_list[neig_index]; T offset_diff = offset_list[curr_index] - offset_list[neig_index]; sum_value += offset_diff * offset_diff; } residual[0] = sum_value; return true; } private: const int grid_width_; // the weight grid along the x axis const int grid_height_; // the weight grid along the y axis const int* index_current_; // the weight grid along the x axis const int* index_neighbour_; // the weight grid along the y axis const int edge_number_; }; // @see hedman2018instant:equ_6 struct DepthmapStitcherGroup::SmoothnessResidual { SmoothnessResidual(int* index_current, int* index_neighbour, int edge_number, int grid_x, int grid_y) : grid_width_(grid_x), grid_height_(grid_y), index_current_(index_current), index_neighbour_(index_neighbour), edge_number_(edge_number) {} template bool operator()(T const* const* scale_offset_list, T* residual) const { const T* scale_list = scale_offset_list[0]; const T* offset_list = scale_offset_list[1]; T sum_value(0); for (int index = 0; index < edge_number_; index++) { int curr_index = index_current_[index]; int neig_index = index_neighbour_[index]; T scale_diff = scale_list[curr_index] - scale_list[neig_index]; T offset_diff = offset_list[curr_index] - offset_list[neig_index]; sum_value += scale_diff * scale_diff + offset_diff * offset_diff; } residual[0] = sum_value; return true; } private: const int grid_width_; // the weight grid along the x axis const int grid_height_; // the weight grid along the y axis const int* index_current_; // the weight grid along the x axis const int* index_neighbour_; // the weight grid along the y axis const int edge_number_; }; // @see hedman2018instant:equ_7 struct DepthmapStitcherGroup::ScaleResidual { ScaleResidual(int grid_width, int grid_height) : grid_width_(grid_width), grid_height_(grid_height) {} template bool operator()(T const* const* scale_list_list, T* residual) const { const T* scale_list = scale_list_list[0]; T sum_number(0); for (int index = 0; index < grid_width_ * grid_height_; index++) { sum_number += 1.0 / scale_list[index]; } residual[0] = sum_number; return true; } private: const int grid_width_; // the weight grid along the x axis const int grid_height_; // the weight grid along the y axis }; void DepthmapStitcherGroup::initial(const int grid_width, const int grid_height) { if (depthmap_original.size() < 2) throw std::runtime_error("The depth map image less than 2."); DepthmapStitcher::initial(grid_width, grid_height); // the first depth as the reference depth map coeff_so.set_value_const(1.0, 0.0); } void DepthmapStitcherGroup::compute_align_coeff() { // 0) load set the data and parameters double* s_ij_list = coeff_so.coeff_scale.get(); double* o_ij_list = coeff_so.coeff_offset.get(); int image_width = depthmap_original[0].cols; int image_height = depthmap_original[0].rows; // set the reference depth map scale and offset int depthmap_ref_intidx = extidx2intidx[depthmap_ref_extidx]; coeff_so.coeff_scale_mat[depthmap_ref_intidx].setTo(1.0); coeff_so.coeff_offset_mat[depthmap_ref_intidx].setTo(0.0); // 1) make the energy function // 1-1) re-projection term LOG(INFO) << "Adding re-projection term" << std::endl; ceres::Problem problem; std::vector bilinear_weight_list_mem; std::vector> ignore_image_pair; // add the parameter block & lock the parameters of reference block for (int i = 0; i < coeff_so.coeff_scale_mat.size(); i++) { problem.AddParameterBlock((double*)coeff_so.coeff_scale_mat[i].data, grid_height * grid_width); problem.AddParameterBlock((double*)coeff_so.coeff_offset_mat[i].data, grid_height * grid_width); } if (depthmap_ref_extidx > 0) { LOG(INFO) << "Fix the reference frame " << depthmap_ref_extidx << " deformation coefficients."; problem.SetParameterBlockConstant(s_ij_list + depthmap_ref_intidx * grid_width * grid_height); problem.SetParameterBlockConstant(o_ij_list + depthmap_ref_intidx * grid_width * grid_height); } //std::vector constant_translation; //for (int idx = 0; idx < grid_width * grid_height; idx++) // constant_translation.push_back(idx); //ceres::SubsetParameterization* subset_parameterization = new ceres::SubsetParameterization(grid_width * grid_height, constant_translation); //problem.SetParameterization((double*)coeff_so.coeff_scale_mat[depthmap_ref_intidx].data, subset_parameterization); //problem.SetParameterization((double*)coeff_so.coeff_offset_mat[depthmap_ref_intidx].data, subset_parameterization); if (projection_per_pixelcost_enable) { unsigned int pixel_corr_num = 0; for (int depthmap_index_src = 0; depthmap_index_src < depthmap_original.size(); depthmap_index_src++) for (int depthmap_index_tar = 0; depthmap_index_tar < depthmap_original.size(); depthmap_index_tar++) { if (depthmap_index_tar == depthmap_index_src) continue; pixel_corr_num += pixels_corresponding_list.at(depthmap_index_src).at(depthmap_index_tar).rows; } weight_reprojection = weight_reprojection * ( 1.0 / pixel_corr_num); LOG(INFO) << "Enable perpixel reprojection weight, pixel_corr_num is " << pixel_corr_num << ", term weight is " << weight_reprojection; } // TODO allocate memory once and assign pointer for each corresponding weights if (smooth_pergrid_enable) { unsigned int smooth_gird_numb = 0; smooth_gird_numb = depthmap_original.size() * grid_height * grid_width; weight_smooth = weight_smooth * (1.0 / smooth_gird_numb); LOG(INFO) << "Enable pergrid smooth weight, grid_numb is " << smooth_gird_numb << ", term weight is " << weight_smooth; } // adjusted depth map register to reference depth map to compute the scale and offset int omp_num_threads = omp_get_max_threads() - 2; LOG(INFO) << "Build ceres problem with " << omp_num_threads << " threads."; #pragma omp parallel for ordered schedule(dynamic) num_threads(omp_num_threads) for (int depthmap_index_src = 0; depthmap_index_src < depthmap_original.size(); depthmap_index_src++) { DLOG(INFO) << "Adding the " << depthmap_index_src << " depth alignment information to problem."; const cv::Mat& depth_map_src = depthmap_original[depthmap_index_src]; //LOG(INFO) << "Target depth map" << depthmap_index_tar; for (int depthmap_index_tar = 0; depthmap_index_tar < depthmap_original.size(); depthmap_index_tar++) { if (depthmap_index_tar == depthmap_index_src) continue; // pixels corresponding relationship const cv::Mat& pixels_corresponding = pixels_corresponding_list.at(depthmap_index_src).at(depthmap_index_tar); int observation_pairs_number = pixels_corresponding.rows; if (observation_pairs_number == 0) { #pragma omp critical(ignore_image_pair) { ignore_image_pair.push_back(std::pair(depthmap_index_src, depthmap_index_tar)); } continue; } // adjusted depth map const cv::Mat& depth_map_tar = depthmap_original[depthmap_index_tar]; //LOG(INFO) << "Source depth map:" << depthmap_index_src; // grid interpolation weight for each pixel, row-major double* bilinear_weight_list_src = (double*)malloc(grid_width * grid_height * observation_pairs_number * sizeof(double)); // memset(bilinear_weight_list_src, 0, grid_width * grid_height * observation_pairs_number * sizeof(double)); double* bilinear_weight_list_tar = (double*)malloc(grid_width * grid_height * observation_pairs_number * sizeof(double)); // memset(bilinear_weight_list_tar, 0, grid_width * grid_height * observation_pairs_number * sizeof(double)); #pragma omp critical(bilinear_weight_list_mem) { bilinear_weight_list_mem.push_back((void*)bilinear_weight_list_src); bilinear_weight_list_mem.push_back((void*)bilinear_weight_list_tar); } // add the depth value and weight value for (int observations_index = 0; observations_index < observation_pairs_number; observations_index++) { const double y_src = pixels_corresponding.at(observations_index, 0); const double x_src = pixels_corresponding.at(observations_index, 1); const double y_tar = pixels_corresponding.at(observations_index, 2); const double x_tar = pixels_corresponding.at(observations_index, 3); double depth_value_src = getColorSubpix(depth_map_src, cv::Point2f(x_src, y_src)); double depth_value_tar = getColorSubpix(depth_map_tar, cv::Point2f(x_tar, y_tar)); // compute the bilinear weights; double* bilinear_weight_src = bilinear_weight_list_src + grid_width * grid_height * observations_index; get_bilinear_weight(bilinear_weight_src, image_width, image_height, grid_height, grid_width, x_src, y_src); double* bilinear_weight_tar = bilinear_weight_list_tar + grid_width * grid_height * observations_index; get_bilinear_weight(bilinear_weight_tar, image_width, image_height, grid_height, grid_width, x_tar, y_tar); //// for debug visuzlize the cv::Mat //cv::Mat bilinear_weight_list_mat_src(cv::Size( coeff_so.coeff_cols, coeff_so.coeff_rows), CV_64FC1, bilinear_weight_src); //cv::Mat bilinear_weight_list_mat_tar(cv::Size(coeff_so.coeff_cols, coeff_so.coeff_rows), CV_64FC1, bilinear_weight_tar); // add residual block //if (depthmap_index_tar != depthmap_ref_intidx && depthmap_index_src != depthmap_ref_intidx) { // TODO The cauchyless is made bad result. figure our reason. //ceres::LossFunction* reprojectionLoss = new ceres::ScaledLoss(new ceres::CauchyLoss(1), weight_re-projection, ceres::TAKE_OWNERSHIP); ceres::LossFunction* reprojectionLoss = new ceres::ScaledLoss(nullptr, weight_reprojection, ceres::TAKE_OWNERSHIP); ceres::DynamicAutoDiffCostFunction* reprojectionCoast = new ceres::DynamicAutoDiffCostFunction( new ReprojectionResidual(bilinear_weight_tar, bilinear_weight_src, depth_value_tar, depth_value_src, grid_width, grid_height)); // separate each depth map coefficients to reduce the Jacobian matrix scale reprojectionCoast->AddParameterBlock(grid_width * grid_height); reprojectionCoast->AddParameterBlock(grid_width * grid_height); reprojectionCoast->AddParameterBlock(grid_width * grid_height); reprojectionCoast->AddParameterBlock(grid_width * grid_height); reprojectionCoast->SetNumResiduals(1); #pragma omp critical(problem) { problem.AddResidualBlock( reprojectionCoast, reprojectionLoss, (s_ij_list + depthmap_index_src * grid_width * grid_height), (o_ij_list + depthmap_index_src * grid_width * grid_height), (s_ij_list + depthmap_index_tar * grid_width * grid_height), (o_ij_list + depthmap_index_tar * grid_width * grid_height)); } } //else if(depthmap_index_src == depthmap_ref_intidx){ // ceres::LossFunction* reprojectionLoss = new ceres::ScaledLoss(nullptr, weight_reprojection, ceres::TAKE_OWNERSHIP); // //ceres::LossFunction* reprojectionLoss = new ceres::ScaledLoss(new ceres::CauchyLoss(1), weight_reprojection, ceres::TAKE_OWNERSHIP); // ceres::DynamicAutoDiffCostFunction* reprojectionCoast = // new ceres::DynamicAutoDiffCostFunction( // new ReprojectionResidual_fixed(bilinear_weight_tar, // depth_value_tar, depth_value_src, grid_width, grid_height)); // // separate each depth map coefficients to reduce the Jacobian matrix scale // reprojectionCoast->AddParameterBlock(grid_width * grid_height); // reprojectionCoast->AddParameterBlock(grid_width * grid_height); // reprojectionCoast->SetNumResiduals(1); // problem.AddResidualBlock( // reprojectionCoast, // reprojectionLoss, // (s_ij_list + depthmap_index_tar * grid_width * grid_height), // (o_ij_list + depthmap_index_tar * grid_width * grid_height)); // //problem.AddResidualBlock( // // reprojectionCoast, // // nullptr, // // (s_ij_list + depthmap_index_tar * grid_width * grid_height), // // (o_ij_list + depthmap_index_tar * grid_width * grid_height)); //} } }// End of depthmap_counter_adjust }// End of depthmap_counter_ref // report the overlap 0 image pairs. if (ignore_image_pair.size() != 0) { std::stringstream ss; ss << "The overlap between depth map "; for (auto item : ignore_image_pair) { ss << item.first << "=>" << item.second << "\t"; } ss << " is 0%, skip!"; LOG(INFO) << ss.str(); } // 1-2) smooth term LOG(INFO) << "Adding smooth term.."; // pre-compute the edge size for smooth term int grid_edge_number = 4 * (grid_width - 1) * (grid_height - 1) + (grid_width - 1) + (grid_height - 1); int* index_current_list = (int*)malloc(grid_edge_number * sizeof(int)); memset(index_current_list, 0, grid_edge_number * sizeof(int)); int* index_neighbour_list = (int*)malloc(grid_edge_number * sizeof(int)); memset(index_neighbour_list, 0, grid_edge_number * sizeof(int)); // to be free bilinear_weight_list_mem.push_back((void*)index_current_list); bilinear_weight_list_mem.push_back((void*)index_neighbour_list); int edge_counter = 0; for (int y_index = 0; y_index < grid_height; y_index++) { for (int x_index = 0; x_index < grid_width; x_index++) { int index_current = y_index * grid_width + x_index; if (x_index == (grid_width - 1) && y_index == (grid_height - 1)) { continue; } else if (x_index == grid_width - 1) { index_current_list[edge_counter] = (index_current); index_neighbour_list[edge_counter] = (index_current + grid_width); edge_counter++; } else if (y_index == grid_height - 1) { index_current_list[edge_counter] = (index_current); index_neighbour_list[edge_counter] = (index_current + 1); edge_counter++; } else { index_current_list[edge_counter] = (index_current); index_neighbour_list[edge_counter] = (index_current + 1); edge_counter++; index_current_list[edge_counter] = (index_current); index_neighbour_list[edge_counter] = (index_current + grid_width); edge_counter++; index_current_list[edge_counter] = (index_current); index_neighbour_list[edge_counter] = (index_current + grid_width + 1); edge_counter++; index_current_list[edge_counter] = (index_current + 1); index_neighbour_list[edge_counter] = (index_current + grid_width); edge_counter++; } } } if (edge_counter != grid_edge_number) LOG(ERROR) << "Smooth term edge number error! " << edge_counter << " , it should be " << grid_edge_number; for (int depthmap_index = 0; depthmap_index < depthmap_original.size(); depthmap_index++) { ceres::LossFunction* smoothnessLoss = new ceres::ScaledLoss(nullptr, weight_smooth, ceres::TAKE_OWNERSHIP); ceres::DynamicAutoDiffCostFunction* smoothnessCoast = new ceres::DynamicAutoDiffCostFunction( new SmoothnessResidual(index_current_list, index_neighbour_list, grid_edge_number, grid_width, grid_height)); smoothnessCoast->AddParameterBlock(grid_width* grid_height); smoothnessCoast->AddParameterBlock(grid_width* grid_height); smoothnessCoast->SetNumResiduals(1); problem.AddResidualBlock( smoothnessCoast, smoothnessLoss, s_ij_list + depthmap_index * grid_width * grid_height, o_ij_list + depthmap_index * grid_width * grid_height); //ceres::LossFunction* smoothnessLoss_s = new ceres::ScaledLoss(nullptr, weight_smooth, ceres::TAKE_OWNERSHIP); //ceres::DynamicAutoDiffCostFunction* smoothnessCoast_s = // new ceres::DynamicAutoDiffCostFunction( // new SmoothnessResidual_S(index_current_list, index_neighbour_list, grid_edge_number, grid_width, grid_height)); //smoothnessCoast_s->AddParameterBlock(grid_width* grid_height); //smoothnessCoast_s->AddParameterBlock(grid_width* grid_height); //smoothnessCoast_s->SetNumResiduals(1); //problem.AddResidualBlock( // smoothnessCoast_s, // smoothnessLoss_s, // s_ij_list + depthmap_index * grid_width * grid_height, // o_ij_list + depthmap_index * grid_width * grid_height); //ceres::LossFunction* smoothnessLoss_o = new ceres::ScaledLoss(nullptr, weight_smooth , ceres::TAKE_OWNERSHIP); //ceres::DynamicAutoDiffCostFunction* smoothnessCoast_o = // new ceres::DynamicAutoDiffCostFunction( // new SmoothnessResidual_O(index_current_list, index_neighbour_list, grid_edge_number, grid_width, grid_height)); //smoothnessCoast_o->AddParameterBlock(grid_width* grid_height); //smoothnessCoast_o->AddParameterBlock(grid_width* grid_height); //smoothnessCoast_o->SetNumResiduals(1); //problem.AddResidualBlock( // smoothnessCoast_o, // smoothnessLoss_o, // s_ij_list + depthmap_index * grid_width * grid_height, // o_ij_list + depthmap_index * grid_width * grid_height); } //1-3) regularization term LOG(INFO) << "Adding regular term.."; if (weight_scale != 0 && depthmap_ref_extidx > 0) LOG(WARNING) << "Both scale weight and reference frame index are set!"; for (int depthmap_index = 0; depthmap_index < depthmap_original.size(); depthmap_index++) { ceres::LossFunction* scaleLoss = new ceres::ScaledLoss(nullptr, weight_scale, ceres::TAKE_OWNERSHIP); ceres::DynamicAutoDiffCostFunction* scaleCoast = new ceres::DynamicAutoDiffCostFunction( new ScaleResidual(grid_width, grid_height)); scaleCoast->AddParameterBlock(grid_width * grid_height); scaleCoast->SetNumResiduals(1); problem.AddResidualBlock( scaleCoast, scaleLoss, s_ij_list + depthmap_index * grid_width * grid_height); } // fix the reference depthmap's scale and offset coefficients //problem.SetParameterBlockConstant(s_ij_list + depthmap_ref_intidx * grid_width * grid_height); //problem.SetParameterBlockConstant(o_ij_list + depthmap_ref_intidx * grid_width * grid_height); // 2) Solve the problem ceres::Solver::Options options; if (ceres_num_threads > 0) { LOG(INFO) << "Ceres solver num_threads is: " << ceres_num_threads; options.num_threads = ceres_num_threads; } if (ceres_max_num_iterations > 0) { LOG(INFO) << "Ceres solver ceres_max_num_iterations is: " << ceres_max_num_iterations; options.max_num_iterations = ceres_max_num_iterations; } if (ceres_max_linear_solver_iterations > 0) { LOG(INFO) << "Ceres solver ceres_max_linear_solver_iterations is: " << ceres_max_linear_solver_iterations; options.max_linear_solver_iterations = ceres_max_linear_solver_iterations; } if (ceres_min_linear_solver_iterations > 0) { LOG(INFO) << "Ceres solver min_linear_solver_iterations is: " << ceres_min_linear_solver_iterations; options.min_linear_solver_iterations = ceres_min_linear_solver_iterations; } //options.minimizer_type = ceres::TRUST_REGION; options.minimizer_type = ceres::LINE_SEARCH; options.linear_solver_type = ceres::SPARSE_NORMAL_CHOLESKY; // options.linear_solver_type = ceres::SPARSE_SCHUR; // support multi-thread //options.line_search_direction_type = ceres::STEEPEST_DESCENT; //options.line_search_direction_type = ceres::LBFGS; //options.line_search_type = ceres::WOLFE; options.minimizer_progress_to_stdout = true; ceres::Solver::Summary summary; ceres::Solve(options, &problem, &summary); std::cout << summary.FullReport() << "\n"; std::cout << "The iteration number is: " << summary.iterations.size() << std::endl; std::cout << "Number inner iteration number:" << summary.num_inner_iteration_steps << std::endl; std::cout << "The total time consume (second): " << summary.total_time_in_seconds << std::endl; double time_consume_each_iter = summary.total_time_in_seconds / summary.iterations.size(); std::cout << "Each iteration average time (second) " << time_consume_each_iter << std::endl; // assign & release resource for (void* pointer : bilinear_weight_list_mem) free(pointer); } 1-10 #include "GyroSensor.h" GyroSensor::GyroSensor() { } GyroSensor::~GyroSensor() { } //Start and handle all motion sensor void GyroSensor::initSensor() { // Initialize the sensors. if (!gyro.begin()) { /* There was a problem detecting the gyro ... check your connections */ Serial.println("Ooops, no gyro detected ... Check your wiring!"); while (1); } if (!accelmag.begin(ACCEL_RANGE_4G)) { Serial.println("Ooops, no FXOS8700 detected ... Check your wiring!"); while (1); } // Filter expects 70 samples per second // Based on a Bluefruit M0 Feather ... rate should be adjuted for other MCUs filter.begin(10); } //MySensorData* GyroSensor::GetSensorMotion() { void GyroSensor::GetSensorMotion(int &retX, int &retY) { int z; GetSensorMotion(retX, retY, z); } void GyroSensor::GetSensorMotion(int &retX, int &retY, int &retZ) { /* sensors_event_t gyro_event; sensors_event_t accel_event; sensors_event_t mag_event; */ // Get new data samples gyro.getEvent(&gyro_event); accelmag.getEvent(&accel_event, &mag_event); // Apply mag offset compensation (base values in uTesla) float x = mag_event.magnetic.x - mag_offsets[0]; float y = mag_event.magnetic.y - mag_offsets[1]; float z = mag_event.magnetic.z - mag_offsets[2]; // Apply mag soft iron error compensation float mx = x * mag_softiron_matrix[0][0] + y * mag_softiron_matrix[0][1] + z * mag_softiron_matrix[0][2]; float my = x * mag_softiron_matrix[1][0] + y * mag_softiron_matrix[1][1] + z * mag_softiron_matrix[1][2]; float mz = x * mag_softiron_matrix[2][0] + y * mag_softiron_matrix[2][1] + z * mag_softiron_matrix[2][2]; // Apply gyro zero-rate error compensation float gx = gyro_event.gyro.x + gyro_zero_offsets[0]; float gy = gyro_event.gyro.y + gyro_zero_offsets[1]; float gz = gyro_event.gyro.z + gyro_zero_offsets[2]; // The filter library expects gyro data in degrees/s, but adafruit sensor // uses rad/s so we need to convert them first (or adapt the filter lib // where they are being converted) gx *= 57.2958F; gy *= 57.2958F; gz *= 57.2958F; // Update the filter filter.update(gx, gy, gz, accel_event.acceleration.x, accel_event.acceleration.y, accel_event.acceleration.z, mx, my, mz); // Create a MySensorData object with the orientation filter output //return new MySensorData(filter.getRoll(), filter.getPitch(), filter.getYaw()); retX = (int) filter.getRoll(); retY = (int) filter.getPitch(); retZ = (int) filter.getYaw(); } // // Calculates the motion // If its above threshold then ad multiple // int GyroSensor::calcMotion(int val) { if (_threshold > abs(val)) { return 0; } bool _negative = false; if (0 > val) { _negative = true; } val = abs(val) - _threshold; val = val * _multiple; if (_negative) { return 0 - val; } return val; }PeterRK/Paddlepaddle/fluid/operators/lookup_sparse_table_op.cc /* Copyright (c) 2016 PaddlePaddle 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 #include "paddle/fluid/framework/data_type.h" #include "paddle/fluid/framework/op_registry.h" #include "paddle/fluid/operators/math/math_function.h" namespace paddle { namespace operators { constexpr int64_t kNoPadding = -1; class LookupSparseTableInferShape : public framework::InferShapeBase { public: void operator()(framework::InferShapeContext *ctx) const override { PADDLE_ENFORCE(ctx->HasOutput("Out"), "Output(Out) of LookupSparseTableOp should not be null."); auto shape_w = ctx->GetInputDim("W"); auto shape_ids = ctx->GetInputDim("Ids"); shape_w[0] = shape_ids.size(); ctx->SetOutputDim("Out", shape_w); } }; class LookupSparseTableOp : public framework::OperatorBase { public: using framework::OperatorBase::OperatorBase; private: void RunImpl(const framework::Scope &scope, const platform::Place &dev_place) const override { auto out_var = scope.FindVar(Output("Out")); auto w_var = scope.FindVar(Input("W")); auto ids_var = scope.FindVar(Input("Ids")); auto is_test = Attr("is_test"); PADDLE_ENFORCE(out_var->IsType(), "The type of Out var should be LodTensor."); PADDLE_ENFORCE(w_var->IsType(), "The type of W var should be SelectedRows."); PADDLE_ENFORCE(ids_var->IsType(), "The type of Ids var should be LoDTensor."); auto &ids_t = ids_var->Get(); auto out_t = out_var->GetMutable(); auto w_t = w_var->GetMutable(); // TODO(Yancey1989): support CUDA Place for the sparse table platform::CPUPlace cpu; auto out_shape = w_t->value().dims(); out_shape[0] = ids_t.numel(); out_t->Resize(out_shape); out_t->mutable_data(cpu, w_t->value().type()); PADDLE_ENFORCE_EQ(framework::ToDataType(w_t->value().type()), framework::proto::VarType::FP32, "The sparse table only support FP32"); w_t->Get(ids_t, out_t, true, is_test); out_t->set_lod(ids_t.lod()); } }; class LookupSparseTableOpMaker : public framework::OpProtoAndCheckerMaker { public: void Make() override { AddInput("W", "(SelectedRows) The input represents embedding table, " "which is a learnable parameter."); AddInput("Ids", "(LoDTensor) Ids's type should be LoDTensor" "THe ids to be looked up in W."); AddOutput("Out", "(LoDTensor) The lookup results, which have the " "same type as W."); AddAttr("padding_idx", "(int64, default -1) " "If the value is -1, it makes no effect to lookup. " "Otherwise the given value indicates padding the output " "with zeros whenever lookup encounters it in Ids.") .SetDefault(kNoPadding); AddAttr("auto_grown_table", "(bool default false)" "Whether create new value if for nonexistent key.") .SetDefault(true); AddAttr("is_test", "In test mode, lookup_sparse_table will " "return a 0 for unknown id") .SetDefault(false); AddComment(R"DOC( Lookup Sprase Tablel Operator. This operator is used to perform lookup on parameter W, then concatenated into a sparse tensor. The type of Ids(Input) is SelectedRows, the rows of Ids contains the ids to be looked up in W; if the Id is not in the sparse table, this operator will return a random value and set the value into the table for the next looking up. )DOC"); } }; } // namespace operators } // namespace paddle namespace ops = paddle::operators; REGISTER_OPERATOR(lookup_sparse_table, ops::LookupSparseTableOp, ops::LookupSparseTableInferShape, ops::LookupSparseTableOpMaker, paddle::framework::EmptyGradOpMaker); cf0617A.cpp #include using namespace std; int main() { float x; cin >> x; cout << ceil(x/5) << endl; return 0; } PROBIC/mSWEEP1-10 #ifndef MSWEEP_KALLISTO_FILES_HPP #define MSWEEP_KALLISTO_FILES_HPP #include #include #include #include "bxzstr.hpp" #include "cxxio.hpp" class KallistoFiles { private: bool file_exists (const std::string& name) const { cxxio::In test(name); return (!test.stream().fail()); } void open_file(const std::string &path, std::unique_ptr &ptr) const { if (!file_exists(path)) { throw std::runtime_error("File: " + path + " does not exist."); } ptr.reset(new bxz::ifstream(path)); if (!ptr->good()) { throw std::runtime_error("Cannot read from file: " + path + "."); } } public: KallistoFiles() = default; std::unique_ptr ec; std::unique_ptr tsv; std::unique_ptr cells; std::unique_ptr run_info; bool batch_mode = false; KallistoFiles(std::string path, bool batch_mode) : batch_mode(batch_mode) { std::string alignment_path = path + (batch_mode ? "/matrix" : "/pseudoalignments"); if (batch_mode) { open_file(path + "/matrix.cells", this->cells); } open_file(alignment_path + ".ec", this->ec); open_file(alignment_path + ".tsv", this->tsv); open_file(path + "/run_info.json", this->run_info); } }; #endif fourier_transform.hpp #ifndef fourier_transform_h #define fourier_transform_h #include #include #include #include #include #include #include #include #include #include #include namespace yyk_fft { constexpr unsigned int yyk_N=10; constexpr unsigned int yyk_thread_max=16; template static std::array, yyk_thread_max> yyk_buffer {}; namespace information { template const static auto hc=static_cast(std::countr_zero(std::bit_floor(std::min(std::max((unsigned int)2,std::thread::hardware_concurrency()),yyk_thread_max)))); static std::array,yyk_thread_max> v{}; } template inline T byteswap(T x,T1 l) noexcept { T y=0; for(T1 i=0;i>=1; } return y; } template inline OutputIt transform(InpuIt1 i1,InpuIt1 l1,InputIt2 i2,InputIt3 i3,OutputIt o,Tp tp) noexcept { for(;i1!=l1;i1++) *o++=tp(*i1,*i2++,*i3++); return o; } template inline auto CooleyTukey(InputIt beg,InputIt end,const unsigned int N=0) noexcept { using namespace information; using D=typename std::iterator_traits::difference_type; using C=typename std::iterator_traits::value_type; using U=std::conditional_t; using T=typename C::value_type; constexpr T cs=Inverse?-2*std::numbers::pi_v:2*std::numbers::pi_v; auto& omiga=yyk_buffer[N]; auto u_len=static_cast(end-beg); auto n=static_cast(std::countr_zero(u_len)); if constexpr(R){ constexpr U L=1<[N]; for(U i=0;i<(1<> 1] >> 1) | ((i & 1) << (n - 1)); for(U i=0;i<(1<; auto j=std::min(n-yyk_N,hc); auto Rev=[&](auto i0,auto i1,auto d) { for(auto i=i0;i[N]; auto j=n-yyk_N; for(U i=0;i<(1<); for(U i=0;i<(1<; auto pf=[&](U j0,U j1,U i,U t,auto q) { for(U j=j0;j,w); for(U i=0;i<(1< inline void naive_parallel_for(F f,T l,T r) noexcept { auto len=r-l; auto th=information::hc; auto d=len/th; for(T i=0;i inline InputIt Bluestein(InputIt beg,InputIt end) noexcept { using C=typename std::iterator_traits::value_type; using T=typename C::value_type; constexpr T cs=Inverse?-std::numbers::pi_v:std::numbers::pi_v; using D=typename std::iterator_traits::difference_type; using U=std::conditional_t; auto len=static_cast(end-beg); T r=len&1?-1:1; auto u_len=std::bit_ceil(2*len); auto n=static_cast(std::countr_zero(u_len)); std::vector x(u_len); std::vector y(u_len); std::vector rev(len); for(U l=0;l>1]>>1)|((l&1)<<(n-1)); auto calc_xy=[&](U l,U k){ for(U i=l;i(calc_xy, 0, len); else calc_xy(0,len); y[len]=C(1,0); std::reverse_copy(y.begin()+1, y.begin()+len, y.begin()+len+1); if constexpr(parallel) { auto f=[&](){ for(U l=0;l>1]>>1)|((l&1)<<(n-1)); if(l>1]>>1)|((l&1)<<(n-1)); if(l(x.begin(), x.end(),0); CooleyTukey(y.begin(), y.end(),1); std::transform(x.begin(), x.end(), y.begin(), x.begin(), [](auto &z1,auto &z2){return z1*z2;}); CooleyTukey(x.begin(), x.end()); auto calc_f=[&](U l,U k){ for(U i=l;i(calc_f, 0, len); else calc_f(0,len); return beg; } template inline InputIt dft(InputIt beg,InputIt end,const unsigned int n=0) noexcept { using C=typename std::iterator_traits::value_type; using D=typename std::iterator_traits::difference_type; using T=typename C::value_type; constexpr T cs=Inverse?-2*std::numbers::pi_v:2*std::numbers::pi_v; auto len=end-beg; auto &m=yyk_buffer[n]; m[len]=std::accumulate(beg, end, C{}); m[0]=C(1,0); for(D i=1;i inline constexpr InputIt special_dft(InputIt beg,const unsigned int n=0) noexcept { static_assert(N==2||N==4||N==8, "N==2||N==4||N==8"); using C=typename std::iterator_traits::value_type; using T=typename C::value_type; if constexpr(N==2) { auto x(*beg); auto y(*(beg+1)); *beg=x+y; *(beg+1)=x-y; } else{ if constexpr(N==4) { auto a(*beg); auto b(*(beg+1)); auto c(*(beg+2)); auto d(*(beg+3)); *beg=a+b+c+d; *(beg+1)=a+C(0,Inverse?-1:1)*b+C(-1,0)*c+C(0,Inverse?1:-1)*d; *(beg+2)=a-b+c-d; *(beg+3)=a+C(0,Inverse?1:-1)*b+C(-1,0)*c+C(0,Inverse?-1:1)*d; }else{ constexpr T omiga[N][2] {{1., 0.}, {0.707107, 0.707107}, {0., 1.}, {-0.707107, 0.707107}, {-1., 0.}, {-0.707107, -0.707107}, {0., -1.}, {0.707107, -0.707107}}; std::array m; m[0]=C(1,0); m[N]=std::accumulate(beg, beg+N, C{}); for(int i=1;i inline InputIt fourier_transform(InputIt beg,InputIt end) noexcept { using T=typename std::iterator_traits::value_type; using D=typename std::iterator_traits::difference_type; using U=std::conditional_t; auto len=end-beg; if(len<=1) return beg; static_assert(std::is_floating_point_v, "Type Is Error"); if(std::has_single_bit(static_cast(len))) { switch (len) { case 2: return special_dft<2, Inverse>(beg); case 4: return special_dft<4, Inverse>(beg); case 8: return special_dft<8, Inverse>(beg); default: return CooleyTukey(beg, end); } }else{ if(len<=40) return dft(beg, end); return Bluestein(beg, end); } } template inline InputIt fast_fourier_transform(InputIt beg,InputIt end) noexcept { return fourier_transform(beg, end); } template inline InputIt inverse_fast_fourier_transform(InputIt beg,InputIt end) noexcept { return fourier_transform(beg, end); } } #endif /* fourier_transform_h */ 1000+ // Copyright 2017-present, Facebook, Inc. // All rights reserved. // // This source code is licensed under the license found in the // LICENSE file in the root directory of this source tree. //File: glContext.hh #pragma once #define INCLUDE_GL_CONTEXT_HEADERS #include "api.hh" #undef INCLUDE_GL_CONTEXT_HEADERS #include "lib/geometry.hh" namespace render { class GLContext { public: GLContext(Geometry win_size): win_size_{win_size} {} virtual ~GLContext() {} virtual void printInfo(); protected: void init(); Geometry win_size_; }; class GLFWContext : public GLContext { public: GLFWContext(Geometry win_size, bool core=true); ~GLFWContext(); GLFWwindow& get_window() { return *window_; } protected: GLFWwindow* window_; }; #ifdef __linux__ // Context for EGL (server-side OpenGL on some supported GPUs) class EGLContext : public GLContext { public: EGLContext(Geometry win_size, int device=0); ~EGLContext(); protected: EGLDisplay eglDpy_; ::EGLContext eglCtx_; }; // Context for GLX (OpenGL to X11) class GLXHeadlessContext : public GLContext { public: GLXHeadlessContext(Geometry win_size); ~GLXHeadlessContext(); protected: Display* dpy_; GLXContext context_; GLXPbuffer pbuffer_; }; #endif #ifdef __APPLE__ // Apple use CGL (Core OpenGL to initialize context) class CGLHeadlessContext : public GLContext { public: CGLHeadlessContext(Geometry win_size); ~CGLHeadlessContext(); protected: CGLContextObj context_; }; #endif // Create a headless context, either EGLContext, GLXHeadlessContext, or CGLContext, // depending on OS, and DISPLAY environment variable // The caller owns the pointer. inline GLContext* createHeadlessContext(Geometry win_size, int device=0) { #ifdef __APPLE__ m_assert(device == 0); return new CGLHeadlessContext{win_size}; #endif #ifdef __linux__ char* force_egl = std::getenv("HOUSE3D_FORCE_EGL"); if (force_egl != nullptr && std::atoi(force_egl) == 1) return new EGLContext{win_size, device}; // prefer GLX (better compatibility with GPUs) when device=0 if (device == 0 and std::getenv("DISPLAY") != nullptr) return new GLXHeadlessContext{win_size}; return new EGLContext{win_size, device}; #endif error_exit("Neither Apple nor Linux!"); }; } // namespace render #include #include #include #include // _alloca #include // def'n of OBJREF //------------------------------------------------------------------------- // convenient mappings #define ORCST(objref) objref.u_objref.u_custom #define ORSTD(objref) objref.u_objref.u_standard #define ORHDL(objref) objref.u_objref.u_handler // bits that must be zero in the flags fields #define OBJREF_RSRVD_MBZ ~(OBJREF_STANDARD | OBJREF_HANDLER | OBJREF_CUSTOM) #define SORF_RSRVD_MBZ ~(SORF_NOPING | SORF_OXRES1 | SORF_OXRES2 | \ SORF_OXRES3 | SORF_OXRES4 | SORF_OXRES5 | \ SORF_OXRES6 | SORF_OXRES7 | SORF_OXRES8) // Internal Uses of the reserved SORF_OXRES flags. // SORF_TBLWEAK is needed so that RMD works correctly on TABLEWEAK // marshaling, so it is ignored by unmarshalers. Therefore, we use one of // the bits reserved for the object exporter that must be ignored by // unmarshalers. // // SORF_WEAKREF is needed for container weak references, when handling // an IRemUnknown::RemQueryInterface on a weak interface. This is a strictly // local (windows) machine protocol, so we use a reserved bit. // // SORF_NONNDR is needed for interop of 16bit custom (non-NDR) marshalers // with 32bit, since the 32bit guys want to use MIDL (NDR) to talk to other // 32bit processes and remote processes, but the custom (non-NDR) format to // talk to local 16bit guys. In particular, this is to support OLE Automation. // // SORF_FREETHREADED is needed when we create a proxy to the SCM interface // in the apartment model. All apartments can use the same proxy so we avoid // the test for calling on the correct thread. #define SORF_TBLWEAK SORF_OXRES1 // (table) weak reference #define SORF_WEAKREF SORF_OXRES2 // (normal) weak reference #define SORF_NONNDR SORF_OXRES3 // stub does not use NDR marshaling #define SORF_FREETHREADED SORF_OXRES4 // proxy may be used on any thread // definition to simplify coding const DWORD MSHLFLAGS_TABLE = MSHLFLAGS_TABLESTRONG | MSHLFLAGS_TABLEWEAK; const DWORD MSHLFLAGS_USER_MASK = MSHLFLAGS_NORMAL | MSHLFLAGS_TABLE | MSHLFLAGS_NOPING; // return codes #define INVALID_SORFFLAG 90000001 #define INVALID_REFCNT 90000002 #define INVALID_MSHLFLAG 90000003 //------------------------------------------------------------------------- //+------------------------------------------------------------------------- // // Function: StRead // // Synopsis: Stream read that only succeeds if all requested bytes read // // Arguments: [pStm] -- source stream // [pvBuffer] -- destination buffer // [ulcb] -- bytes to read // // Returns: S_OK if successful, else error code // //-------------------------------------------------------------------------- HRESULT StRead(IStream *pStm, void *pvBuffer, ULONG ulcb) { ULONG cbRead; HRESULT hr = pStm->Read(pvBuffer, ulcb, &cbRead); if (SUCCEEDED(hr)) { if (ulcb != cbRead) { hr = STG_E_READFAULT; } } return hr; } void DbgDumpSTD(STDOBJREF *pStd) { } //+------------------------------------------------------------------------- // // Function: ReadObjRef // // Synopsis: Reads an OBJREF from the stream // // Arguments: [pStm] -- source stream // [objref] -- destination buffer // // Returns: S_OK if successful, else error code // //-------------------------------------------------------------------------- HRESULT ReadObjRef(IStream *pStm, OBJREF &objref, STDOBJREF **ppStd) { HRESULT hr = StRead(pStm, &objref, 2*sizeof(ULONG)+sizeof(IID)); if (SUCCEEDED(hr)) { if ((objref.signature != OBJREF_SIGNATURE) || (objref.flags & OBJREF_RSRVD_MBZ) || (objref.flags == 0)) { // the objref signature is bad, or one of the reserved // bits in the flags is set, or none of the required bits // in the flags is set. the objref cant be interpreted so // fail the call. return E_UNEXPECTED; // BUGBUG: } // compute the size of the remainder of the objref and // include the size fields for the resolver string array STDOBJREF *pStd = &ORSTD(objref).std; DUALSTRINGARRAY *psa; ULONG cbToRead; if (objref.flags & OBJREF_STANDARD) { cbToRead = sizeof(STDOBJREF) + sizeof(ULONG); psa = &ORSTD(objref).saResAddr; } else if (objref.flags & OBJREF_HANDLER) { cbToRead = sizeof(STDOBJREF) + sizeof(CLSID) + sizeof(ULONG); psa = &ORHDL(objref).saResAddr; } else if (objref.flags & OBJREF_CUSTOM) { cbToRead = sizeof(CLSID) + sizeof(DWORD); // clsid + data size psa = NULL; } // return ptr to STDOBJREF *ppStd = pStd; // read the rest of the (fixed sized) objref from the stream hr = StRead(pStm, pStd, cbToRead); if (SUCCEEDED(hr) && psa) { // Non custom interface. Make sure the resolver string array // has some sensible values. if (psa->wSecurityOffset >= psa->wNumEntries) { hr = E_UNEXPECTED; // BUGBUG: correct return code } } if (SUCCEEDED(hr) && psa) { // Non custom interface. The data that follows is a variable // sized string array. Allocate memory for it and then read it. DbgDumpSTD(pStd); cbToRead = psa->wNumEntries * sizeof(WCHAR); DUALSTRINGARRAY *psaNew = (DUALSTRINGARRAY *) _alloca(cbToRead + sizeof(ULONG)); if (psaNew != NULL) { // update the size fields and read in the rest of the data psaNew->wSecurityOffset = psa->wSecurityOffset; psaNew->wNumEntries = psa->wNumEntries; hr = StRead(pStm, psaNew->aStringArray, cbToRead); } else { psa->wNumEntries = 0; psa->wSecurityOffset = 0; hr = E_OUTOFMEMORY; // seek the stream past what we should have read, ignore // seek errors, since the OOM takes precedence. LARGE_INTEGER libMove; libMove.LowPart = cbToRead; libMove.HighPart = 0; pStm->Seek(libMove, STREAM_SEEK_CUR, 0); } } } return hr; } //+------------------------------------------------------------------------- // // Function: VerifyOBJREFFormat // // Synopsis: Checks the format of the marshal packet // // Arguments: [pStm] -- source stream // [mshlflags] -- destination buffer // // Returns: S_OK if successful, else error code // //-------------------------------------------------------------------------- HRESULT VerifyOBJREFFormat(IStream *pStm, DWORD mshlflags) { OBJREF objref; STDOBJREF *pStd; HRESULT hr = ReadObjRef(pStm, objref, &pStd); // now verify the format if (SUCCEEDED(hr)) { if (mshlflags & MSHLFLAGS_NOPING) { // SORF_NOPING should be set (unless previously marshaled PING) if (!(pStd->flags & SORF_NOPING)) return INVALID_SORFFLAG; } if ((mshlflags & MSHLFLAGS_TABLE) == MSHLFLAGS_NORMAL) { // refcnt should be non-zero if (pStd->cPublicRefs == 0) return INVALID_REFCNT; // table flags should not be set if (pStd->flags & (SORF_WEAKREF | SORF_TBLWEAK)) return INVALID_SORFFLAG; } else if ((mshlflags & MSHLFLAGS_TABLE) == MSHLFLAGS_TABLESTRONG) { // refcnt should be zero if (pStd->cPublicRefs != 0) return INVALID_REFCNT; } else if ((mshlflags & MSHLFLAGS_TABLE) == MSHLFLAGS_TABLEWEAK) { // refcnt should be zero if (pStd->cPublicRefs != 0) return INVALID_REFCNT; // SORF_TBLWEAK should be set if (!(pStd->flags & SORF_TBLWEAK)) return INVALID_SORFFLAG; } else { // unknown flags return INVALID_MSHLFLAG; } } return hr; } Amtrix/fpt-max-cut #include namespace Color { enum Code { FG_RED = 31, FG_GREEN = 32, FG_BLUE = 34, FG_DEFAULT = 39, BG_RED = 41, BG_GREEN = 42, BG_BLUE = 44, BG_DEFAULT = 49 }; class Modifier { Code code; public: Modifier(Code pCode) : code(pCode) {} friend std::ostream& operator<<(std::ostream& os, const Modifier& mod) { return os << "\033[" << mod.code << "m"; } }; }// 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. #include #include #include #include #include #include #include #include "src/dicom_file_region_reader.h" #include "src/jpeg2000Compression.h" #include "src/jpegCompression.h" #include "src/nearestneighborframe.h" #include "src/rawCompression.h" #include "src/zlibWrapper.h" namespace wsiToDicomConverter { NearestNeighborFrame::NearestNeighborFrame( OpenSlidePtr *osptr, int64_t locationX, int64_t locationY, int64_t level, int64_t frameWidthDownsampled, int64_t frameHeightDownsampled, double multiplicator, int64_t frameWidth, int64_t frameHeight, DCM_Compression compression, int quality, bool storeRawBytes, DICOMFileFrameRegionReader *frame_region_reader): Frame(locationX, locationY, frameWidth, frameHeight, compression, quality, storeRawBytes) { osptr_ = osptr; level_ = level; frameWidthDownsampled_ = frameWidthDownsampled; frameHeightDownsampled_ = frameHeightDownsampled; multiplicator_ = multiplicator; dcmFrameRegionReader_ = frame_region_reader; } NearestNeighborFrame::~NearestNeighborFrame() {} class convert_rgba_to_rgb { public: void operator()( const boost::gil::rgba8c_pixel_t &src, boost::gil::rgb8_pixel_t &dst) const { // NOLINT, boost template boost::gil::get_color(dst, boost::gil::blue_t()) = boost::gil::channel_multiply(get_color(src, boost::gil::red_t()), get_color(src, boost::gil::alpha_t())); boost::gil::get_color(dst, boost::gil::green_t()) = boost::gil::channel_multiply(get_color(src, boost::gil::green_t()), get_color(src, boost::gil::alpha_t())); boost::gil::get_color(dst, boost::gil::red_t()) = boost::gil::channel_multiply(get_color(src, boost::gil::blue_t()), get_color(src, boost::gil::alpha_t())); } }; void NearestNeighborFrame::incSourceFrameReadCounter() { if (dcmFrameRegionReader_->dicomFileCount() != 0) { dcmFrameRegionReader_->incSourceFrameReadCounter(locationX_, locationY_, frameWidthDownsampled_, frameHeightDownsampled_); } } void NearestNeighborFrame::sliceFrame() { std::unique_ptrbuf = std::make_unique(frameWidthDownsampled_ * frameHeightDownsampled_); if (dcmFrameRegionReader_->dicomFileCount() == 0) { openslide_read_region(osptr_->osr(), buf.get(), static_cast(locationX_ * multiplicator_), static_cast(locationY_ * multiplicator_), level_, frameWidthDownsampled_, frameHeightDownsampled_); if (openslide_get_error(osptr_->osr())) { BOOST_LOG_TRIVIAL(error) << openslide_get_error(osptr_->osr()); throw 1; } } else { if (!dcmFrameRegionReader_->readRegion(locationX_, locationY_, frameWidthDownsampled_, frameHeightDownsampled_, buf.get())) { BOOST_LOG_TRIVIAL(error) << "Error occured decoding region from previous" " level."; throw 1; } } boost::gil::rgba8c_view_t gil = boost::gil::interleaved_view( frameWidthDownsampled_, frameHeightDownsampled_, reinterpret_cast(buf.get()), frameWidthDownsampled_ * sizeof(uint32_t)); boost::gil::rgba8_image_t newFrame(frameWidth_, frameHeight_); if (frameWidthDownsampled_ != frameWidth_ || frameHeightDownsampled_ != frameHeight_) { boost::gil::resize_view(gil, view(newFrame), boost::gil::nearest_neighbor_sampler()); gil = view(newFrame); } boost::gil::rgb8_image_t exp(frameWidth_, frameHeight_); boost::gil::rgb8_view_t rgbView = view(exp); // Create a copy of the pre-compressed downsampled bits if (!storeRawBytes_) { clearRawABGRMem(); } else { const int64_t frame_mem_size = frameWidth_ * frameHeight_; std::unique_ptr raw_bytes = std::make_unique( static_cast(frame_mem_size)); boost::gil::rgba8_view_t raw_byte_view = boost::gil::interleaved_view( frameWidth_, frameHeight_, reinterpret_cast(raw_bytes.get()), frameWidth_ * sizeof(uint32_t)); boost::gil::copy_pixels(gil, raw_byte_view); rawCompressedBytes_ = std::move(compress_memory( reinterpret_cast(raw_bytes.get()), frame_mem_size * sizeof(uint32_t), &rawCompressedBytesSize_)); } boost::gil::copy_and_convert_pixels(gil, rgbView, convert_rgba_to_rgb()); uint64_t size; std::unique_ptrmem = std::move(compressor_->compress(rgbView, &size)); setDicomFrameBytes(std::move(mem), size); done_ = true; } } // namespace wsiToDicomConverter /* * tlibthrd.cxx * * Routines for pre-emptive threading system * * Portable Windows Library * * Copyright (c) 1993-1998 Equivalence Pty. Ltd. * * The contents of this file are subject to the Mozilla Public License * Version 1.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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See * the License for the specific language governing rights and limitations * under the License. * * The Original Code is Portable Windows Library. * * The Initial Developer of the Original Code is Equivalence Pty. Ltd. * * Portions are Copyright (C) 1993 Free Software Foundation, Inc. * All Rights Reserved. * * Contributor(s): ______________________________________. */ #include #include #include #ifdef P_RTEMS #define SUSPEND_SIG SIGALRM #include #else #define SUSPEND_SIG SIGVTALRM #endif #if defined(P_MACOSX) #include #include #include #include #elif defined(P_LINUX) #include #elif defined(P_ANDROID) #include #include #endif #ifndef P_ANDROID #define P_USE_THREAD_CANCEL 1 #else static JavaVM * AndroidJavaVM; JNIEXPORT jint JNI_OnLoad(JavaVM* vm, void* reserved) { AndroidJavaVM = vm; return JNI_VERSION_1_6; } #endif static PINDEX const PThreadMinimumStack = 16*PTHREAD_STACK_MIN; // Set a decent stack size that won't eat all virtual memory, or crash int PX_NewHandle(const char *, int); #define PAssertWithRetry(func, arg, ...) \ { \ unsigned threadOpRetry = 0; \ while (PAssertThreadOp(func(arg, ##__VA_ARGS__), threadOpRetry, #func, \ reinterpret_cast(arg), PDebugLocation(__FILE__, __LINE__, __FUNCTION__))); \ } static bool PAssertThreadOp(int retval, unsigned & retry, const char * funcname, const void * arg1, const PDebugLocation & location) { if (retval == 0) { #if PTRACING if (PTrace::CanTrace(2) && retry > 0) PTrace::Begin(2, location.m_file, location.m_line, NULL, "PTLib") << funcname << '(' << arg1 << ") required " << retry << " retries!" << PTrace::End; #endif return false; } int err = retval < 0 ? errno : retval; /* Retry on a temporary error. Technically an EINTR only happens on a signal, and EAGAIN not at all for most of the functions, but expereince is that when the system gets really busy, they do occur, lots. So we have to keep trying, but still give up and assert after a suitably huge effort. */ if ((err == EINTR || err == EAGAIN) && ++retry < 1000) { PThread::Sleep(10); // Basically just swap out thread to try and clear blockage return true; // Return value to try again } #if PTRACING || P_USE_ASSERTS std::ostringstream msg; msg << "Function " << funcname << '(' << arg1 << ") failed, errno=" << err << ' ' << strerror(err); #if P_USE_ASSERTS PAssertFunc(location, msg.str().c_str()); #else PTrace::Begin(0, location.m_file, location.m_line, NULL, "PTLib") << msg.str() << PTrace::End; #endif #endif return false; } #if defined(P_LINUX) static int GetSchedParam(PThread::Priority priority, sched_param & param) { /* Set realtime scheduling if our effective user id is root (only then is this allowed) AND our priority is Highest. I don't know if other UNIX OSs have SCHED_FIFO and SCHED_RR as well. WARNING: a misbehaving thread (one that never blocks) started with Highest priority can hang the entire machine. That is why root permission is neccessary. */ memset(¶m, 0, sizeof(sched_param)); switch (priority) { case PThread::HighestPriority : param.sched_priority = sched_get_priority_max(SCHED_RR); break; case PThread::HighPriority : param.sched_priority = (sched_get_priority_max(SCHED_RR) + sched_get_priority_min(SCHED_RR))/2; break; #ifdef SCHED_BATCH case PThread::LowestPriority : case PThread::LowPriority : return SCHED_BATCH; #endif default : // PThread::NormalPriority : return SCHED_OTHER; } #ifdef RLIMIT_RTPRIO struct rlimit rl; if (getrlimit(RLIMIT_RTPRIO, &rl) != 0) { PTRACE(2, "PTLib", "Could not get Real Time thread priority limit - " << strerror(errno)); return SCHED_OTHER; } if ((int)rl.rlim_cur < (int)param.sched_priority) { rl.rlim_max = rl.rlim_cur = param.sched_priority; if (setrlimit(RLIMIT_RTPRIO, &rl) != 0) { PTRACE(geteuid() == 0 || errno != EPERM ? 2 : 3, "PTLib", "Could not increase Real Time thread priority limit to " << rl.rlim_cur << " - " << strerror(errno)); param.sched_priority = 0; return SCHED_OTHER; } PTRACE(4, "PTLib", "Increased Real Time thread priority limit to " << rl.rlim_cur); } return SCHED_RR; #else if (geteuid() == 0) return SCHED_RR; param.sched_priority = 0; PTRACE(3, "PTLib", "No permission to set priority level " << priority); return SCHED_OTHER; #endif // RLIMIT_RTPRIO } #endif static pthread_mutex_t MutexInitialiser = PTHREAD_MUTEX_INITIALIZER; #define new PNEW ////////////////////////////////////////////////////////////////////////////// // // Called to construct a PThread for either: // // a) The primordial PProcesss thread // b) A non-PTLib thread that needs to use PTLib routines, such as PTRACE // // This is always called in the context of the running thread, so naturally, the thread // is not paused // PThread::PThread(bool isProcess) : m_type(isProcess ? e_IsProcess : e_IsExternal) , m_originalStackSize(0) , m_threadId(pthread_self()) , m_uniqueId(GetCurrentUniqueIdentifier()) , PX_priority(NormalPriority) #if defined(P_LINUX) , PX_startTick(PTimer::Tick()) #endif , PX_suspendMutex(MutexInitialiser) , PX_suspendCount(0) , PX_state(PX_running) #ifndef P_HAS_SEMAPHORES , PX_waitingSemaphore(NULL) , PX_WaitSemMutex(MutexInitialiser) #endif { #ifdef P_RTEMS PAssertOS(socketpair(AF_INET,SOCK_STREAM,0,unblockPipe) == 0); #else PAssertOS(::pipe(unblockPipe) == 0); #endif if (isProcess) return; PProcess::Current().InternalThreadStarted(this); } // // Called to construct a PThread for a normal PTLib thread. // // This is always called in the context of some other thread, and // the PThread is always created in the paused state // PThread::PThread(PINDEX stackSize, AutoDeleteFlag deletion, Priority priorityLevel, const PString & name) : m_type(deletion == AutoDeleteThread ? e_IsAutoDelete : e_IsManualDelete) , m_originalStackSize(std::max(stackSize, PThreadMinimumStack)) , m_threadName(name) , m_threadId(PNullThreadIdentifier) // indicates thread has not started , m_uniqueId(0) , PX_priority(priorityLevel) , PX_suspendMutex(MutexInitialiser) , PX_suspendCount(1) , PX_state(PX_firstResume) // new thread is actually started the first time Resume() is called. #ifndef P_HAS_SEMAPHORES , PX_waitingSemaphore(NULL) , PX_WaitSemMutex(MutexInitialiser) #endif { #ifdef P_RTEMS PAssertOS(socketpair(AF_INET,SOCK_STREAM,0,unblockPipe) == 0); #else PAssertOS(::pipe(unblockPipe) == 0); #endif PX_NewHandle("Thread unblock pipe", PMAX(unblockPipe[0], unblockPipe[1])); // If need to be deleted automatically, make sure thread that does it runs. if (m_type == e_IsAutoDelete) PProcess::Current().SignalTimerChange(); PTRACE(5, "PTLib\tCreated thread " << this << ' ' << m_threadName << " stack=" << m_originalStackSize); } // // Called to destruct a PThread // // If not called in the context of the thread being destroyed, we need to wait // for that thread to stop before continuing // void PThread::InternalDestroy() { /* If manual delete, wait for thread to really end before proceeding with destruction */ if (PX_synchroniseThreadFinish.get() != NULL) PX_synchroniseThreadFinish->Wait(); // close I/O unblock pipes ::close(unblockPipe[0]); ::close(unblockPipe[1]); #ifndef P_HAS_SEMAPHORES pthread_mutex_destroy(&PX_WaitSemMutex); #endif // If the mutex was not locked, the unlock will fail */ pthread_mutex_trylock(&PX_suspendMutex); pthread_mutex_unlock(&PX_suspendMutex); pthread_mutex_destroy(&PX_suspendMutex); } void PThread::InternalPreMain() { // Added this to guarantee that the thread creation (PThread::Restart) // has completed before we start the thread. Then the m_threadId has // been set. pthread_mutex_lock(&PX_suspendMutex); PAssert(PX_state == PX_starting, PLogicError); PX_state = PX_running; m_uniqueId = GetCurrentUniqueIdentifier(); #if defined(P_LINUX) PX_startTick = PTimer::Tick(); #endif SetThreadName(GetThreadName()); pthread_mutex_unlock(&PX_suspendMutex); PX_Suspended(); if (PX_priority != NormalPriority) SetPriority((Priority)PX_priority.load()); /* If manual delete thread, there is a race on the thread actually ending and the PThread object being deleted. This flag is used to synchronise those actions. */ if (!IsAutoDelete()) PX_synchroniseThreadFinish.reset(new PSyncPoint()); } void PThread::InternalPostMain() { /* Bizarely, this can get called by pthread_cleanup_push() when a thread is started! Seems to be a load and/or race on use of thread ID's inside the system library. Anyway, need to make sure we are really ending. */ if (PX_state.exchange(PX_finishing) != PX_running) return; #if defined(P_LINUX) PX_endTick = PTimer::Tick(); #endif /* Need to check this before the InternalThreadEnded() as an auto delete thread would be deleted in that function. */ bool doThreadFinishedSignal = PX_synchroniseThreadFinish.get() != NULL; /* The thread changed from manual to auto delete somewhere, so we need to do the signal now, due to the thread being deleted in InternalThreadEnded() */ if (doThreadFinishedSignal && IsAutoDelete()) { doThreadFinishedSignal = false; // Don't do it after PX_synchroniseThreadFinish->Signal(); } /* If auto delete, "this" may have be deleted any nanosecond after this function, as it is asynchronously done by the housekeeping thread. */ PProcess::Current().InternalThreadEnded(this); /* We know the thread is not auto delete and the destructor is either not run yet, or is waiting on this signal, so "this" is still safe to use. */ if (doThreadFinishedSignal) PX_synchroniseThreadFinish->Signal(); } void * PThread::PX_ThreadMain(void * arg) { #if P_USE_THREAD_CANCEL // make sure the cleanup routine is called when the threade cancelled pthread_cleanup_push(&PThread::PX_ThreadEnd, arg); // Allow cancel to happen any time pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL); pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL); #endif reinterpret_cast(PAssertNULL(arg))->InternalThreadMain(); #if P_USE_THREAD_CANCEL pthread_cleanup_pop(0); #endif return NULL; } void PThread::PX_ThreadEnd(void * arg) { reinterpret_cast(PAssertNULL(arg))->InternalPostMain(); } void PThread::Restart() { if (!IsTerminated()) return; PTRACE(2, "PTlib\tRestarting thread " << this << " \"" << GetThreadName() << '"'); pthread_mutex_lock(&PX_suspendMutex); PX_StartThread(); pthread_mutex_unlock(&PX_suspendMutex); } void PThread::PX_StartThread() { // This should be executed inside the PX_suspendMutex to avoid races // with the thread starting. PX_state = PX_starting; pthread_attr_t threadAttr; pthread_attr_init(&threadAttr); PAssertWithRetry(pthread_attr_setdetachstate, &threadAttr, PTHREAD_CREATE_DETACHED); PAssertWithRetry(pthread_attr_setstacksize, &threadAttr, m_originalStackSize); #if defined(P_LINUX) struct sched_param sched_params; PAssertWithRetry(pthread_attr_setschedpolicy, &threadAttr, GetSchedParam((Priority)PX_priority.load(), sched_params)); PAssertWithRetry(pthread_attr_setschedparam, &threadAttr, &sched_params); #elif defined(P_RTEMS) pthread_attr_setinheritsched(&threadAttr, PTHREAD_EXPLICIT_SCHED); pthread_attr_setschedpolicy(&threadAttr, SCHED_OTHER); struct sched_param sched_param; sched_param.sched_priority = 125; /* set medium priority */ pthread_attr_setschedparam(&threadAttr, &sched_param); #endif PProcess & process = PProcess::Current(); size_t checkSize = 0; PAssertWithRetry(pthread_attr_getstacksize, &threadAttr, &checkSize); PAssert(checkSize == (size_t)m_originalStackSize, "Stack size not set correctly"); // create the thread PAssertWithRetry(pthread_create, &m_threadId, &threadAttr, &PThread::PX_ThreadMain, this); // put the thread into the thread list process.InternalThreadStarted(this); pthread_attr_destroy(&threadAttr); } bool PThread::PX_kill(PThreadIdentifier tid, PUniqueThreadIdentifier uid, int sig) { if (!PProcess::IsInitialised()) return false; PProcess & process = PProcess::Current(); { PWaitAndSignal mutex(process.m_threadMutex); PProcess::ThreadMap::iterator it = process.m_activeThreads.find(tid); if (it == process.m_activeThreads.end() || (uid != 0 && it->second->GetUniqueIdentifier() != uid)) return false; } int error = pthread_kill(tid, sig); switch (error) { case 0: return true; // If just test for existance, is true even if we don't have permission case EPERM: case ENOTSUP: // Mac OS-X does this for GCD threads return sig == 0; #if PTRACING case ESRCH: // Thread not running any more case EINVAL: // Id has never been used for a thread break; default: // Output direct to stream, do not use PTRACE as it might cause an infinite recursion. ostream * trace = PTrace::GetStream(); if (trace != NULL) *trace << "pthread_kill failed for thread " << GetIdentifiersAsString(tid, uid) << " errno " << error << ' ' << strerror(error) << endl; #endif // PTRACING } return false; } void PThread::PX_Suspended() { while (PX_suspendCount > 0) { BYTE ch; if (::read(unblockPipe[0], &ch, 1) == 1 || errno != EINTR) return; #if P_USE_THREAD_CANCEL pthread_testcancel(); #endif } } void PX_SuspendSignalHandler(int) { PThread * thread = PThread::Current(); if (thread != NULL) thread->PX_Suspended(); } void PThread::Suspend(PBoolean susp) { PAssertWithRetry(pthread_mutex_lock, &PX_suspendMutex); // Check for start up condition, first time Resume() is called if (PX_state == PX_firstResume) { if (susp) PX_suspendCount++; else { if (PX_suspendCount > 0) PX_suspendCount--; if (PX_suspendCount == 0) PX_StartThread(); } PAssertWithRetry(pthread_mutex_unlock, &PX_suspendMutex); return; } if (!IsTerminated()) { // if suspending, then see if already suspended if (susp) { PX_suspendCount++; if (PX_suspendCount == 1) { if (m_threadId != pthread_self()) { signal(SUSPEND_SIG, PX_SuspendSignalHandler); pthread_kill(m_threadId, SUSPEND_SIG); } else { PAssertWithRetry(pthread_mutex_unlock, &PX_suspendMutex); PX_SuspendSignalHandler(SUSPEND_SIG); return; // Mutex already unlocked } } } // if resuming, then see if to really resume else if (PX_suspendCount > 0) { PX_suspendCount--; if (PX_suspendCount == 0) PXAbortBlock(); } } PAssertWithRetry(pthread_mutex_unlock, &PX_suspendMutex); } void PThread::Resume() { Suspend(false); } PBoolean PThread::IsSuspended() const { PAssertWithRetry(pthread_mutex_lock, &PX_suspendMutex); bool suspended = PX_state == PX_starting || (PX_suspendCount != 0 && !IsTerminated()); PAssertWithRetry(pthread_mutex_unlock, &PX_suspendMutex); return suspended; } #ifdef P_MACOSX // obtain thread priority of the main thread static unsigned long GetThreadBasePriority () { thread_basic_info_data_t threadInfo; policy_info_data_t thePolicyInfo; unsigned int count; pthread_t baseThread = PProcess::Current().GetThreadId(); // get basic info count = THREAD_BASIC_INFO_COUNT; thread_info (pthread_mach_thread_np (baseThread), THREAD_BASIC_INFO, (integer_t*)&threadInfo, &count); switch (threadInfo.policy) { case POLICY_TIMESHARE: count = POLICY_TIMESHARE_INFO_COUNT; thread_info(pthread_mach_thread_np (baseThread), THREAD_SCHED_TIMESHARE_INFO, (integer_t*)&(thePolicyInfo.ts), &count); return thePolicyInfo.ts.base_priority; case POLICY_FIFO: count = POLICY_FIFO_INFO_COUNT; thread_info(pthread_mach_thread_np (baseThread), THREAD_SCHED_FIFO_INFO, (integer_t*)&(thePolicyInfo.fifo), &count); if (thePolicyInfo.fifo.depressed) return thePolicyInfo.fifo.depress_priority; return thePolicyInfo.fifo.base_priority; case POLICY_RR: count = POLICY_RR_INFO_COUNT; thread_info(pthread_mach_thread_np (baseThread), THREAD_SCHED_RR_INFO, (integer_t*)&(thePolicyInfo.rr), &count); if (thePolicyInfo.rr.depressed) return thePolicyInfo.rr.depress_priority; return thePolicyInfo.rr.base_priority; } return 0; } #endif void PThread::SetPriority(Priority priorityLevel) { PTRACE(4, "PTLib", "Setting thread priority to " << priorityLevel); PX_priority.store(priorityLevel); if (IsTerminated()) return; #if defined(P_LINUX) struct sched_param params; PAssertWithRetry(pthread_setschedparam, m_threadId, GetSchedParam(priorityLevel, params), ¶ms); #elif defined(P_ANDROID) if (Current() != this) { PTRACE(2, "JNI", "Can only set priority for current thread."); return; } if (AndroidJavaVM == NULL) { PTRACE(2, "JNI", "JavaVM not set."); return; } JNIEnv *jni = NULL; bool detach = false; jint err = AndroidJavaVM->GetEnv((void **)&jni, JNI_VERSION_1_6); switch (err) { case JNI_EDETACHED : if ((err = AndroidJavaVM->AttachCurrentThread(&jni, NULL)) != JNI_OK) { PTRACE(2, "JNI", "Could not attach JNI environment, error=" << err); return; } detach = true; case JNI_OK : break; default : PTRACE(2, "JNI", "Could not get JNI environment, error=" << err); return; } //Get pointer to the java class jclass androidOsProcess = (jclass)jni->NewGlobalRef(jni->FindClass("android/os/Process")); if (androidOsProcess != NULL) { jmethodID setThreadPriority = jni->GetStaticMethodID(androidOsProcess, "setThreadPriority", "(I)V"); if (setThreadPriority != NULL) { static const int Priorities[NumPriorities] = { 19, 10, 0, -10, -19 }; jni->CallStaticIntMethod(androidOsProcess, setThreadPriority, Priorities[priorityLevel]); PTRACE(5, "JNI", "setThreadPriority " << Priorities[priorityLevel]); } else { PTRACE(2, "JNI", "Could not find setThreadPriority"); } } else { PTRACE(2, "JNI", "Could not find android.os.Process"); } if (detach) AndroidJavaVM->DetachCurrentThread(); #elif defined(P_MACOSX) if (priorityLevel == HighestPriority) { /* get fixed priority */ { int result; thread_extended_policy_data_t theFixedPolicy; thread_precedence_policy_data_t thePrecedencePolicy; long relativePriority; theFixedPolicy.timeshare = false; // set to true for a non-fixed thread result = thread_policy_set (pthread_mach_thread_np(m_threadId), THREAD_EXTENDED_POLICY, (thread_policy_t)&theFixedPolicy, THREAD_EXTENDED_POLICY_COUNT); if (result != KERN_SUCCESS) { PTRACE(1, "thread_policy - Couldn't set thread as fixed priority."); } // set priority // precedency policy's "importance" value is relative to // spawning thread's priority relativePriority = 62 - GetThreadBasePriority(); PTRACE(3, "relativePriority is " << relativePriority << " base priority is " << GetThreadBasePriority()); thePrecedencePolicy.importance = relativePriority; result = thread_policy_set (pthread_mach_thread_np(m_threadId), THREAD_PRECEDENCE_POLICY, (thread_policy_t)&thePrecedencePolicy, THREAD_PRECEDENCE_POLICY_COUNT); if (result != KERN_SUCCESS) { PTRACE(1, "thread_policy - Couldn't set thread priority."); } } } #endif } PThread::Priority PThread::GetPriority() const { #if defined(LINUX) int policy; struct sched_param params; PAssertWithRetry(pthread_getschedparam, m_threadId, &policy, ¶ms); switch (policy) { case SCHED_OTHER: break; case SCHED_FIFO: case SCHED_RR: return params.sched_priority > sched_get_priority_min(policy) ? HighestPriority : HighPriority; #ifdef SCHED_BATCH case SCHED_BATCH : return LowPriority; #endif default: /* Unknown scheduler. We don't know what priority this thread has. */ PTRACE(1, "PTLib\tPThread::GetPriority: unknown scheduling policy #" << policy); } #endif return NormalPriority; /* as good a guess as any */ } #ifndef P_HAS_SEMAPHORES void PThread::PXSetWaitingSemaphore(PSemaphore * sem) { PAssertWithRetry(pthread_mutex_lock, &PX_WaitSemMutex); PX_waitingSemaphore = sem; PAssertWithRetry(pthread_mutex_unlock, &PX_WaitSemMutex); } #endif // Normal Posix threads version void PThread::Sleep(const PTimeInterval & timeout) { struct timespec ts; ts.tv_sec = timeout.GetSeconds(); ts.tv_nsec = timeout.GetNanoSeconds()%1000000000; PPROFILE_PRE_SYSTEM(); while (nanosleep(&ts, &ts) < 0 && PAssert(errno == EINTR || errno == EAGAIN, POperatingSystemError)) { #if P_USE_THREAD_CANCEL pthread_testcancel(); #endif } PPROFILE_POST_SYSTEM(); } void PThread::Yield() { PPROFILE_SYSTEM( sched_yield(); ); } // // Terminate the specified thread // void PThread::Terminate() { // if thread was not created by PTLib, then don't terminate it if (m_originalStackSize <= 0) return; // if the thread is already terminated, then nothing to do if (IsTerminated()) return; // if thread calls Terminate on itself, then do it // don't use PThread::Current, as the thread may already not be in the // active threads list if (m_threadId == pthread_self()) { pthread_exit(0); return; // keeps compiler happy } // otherwise force thread to die PTRACE(2, "PTLib\tForcing termination of thread id=0x" << hex << m_threadId << dec); PXAbortBlock(); if (WaitForTermination(100)) return; #ifndef P_HAS_SEMAPHORES PAssertWithRetry(pthread_mutex_lock, &PX_WaitSemMutex); if (PX_waitingSemaphore != NULL) { PAssertWithRetry(pthread_mutex_lock, &PX_waitingSemaphore->mutex); PX_waitingSemaphore->queuedLocks--; PAssertWithRetry(pthread_mutex_unlock, &PX_waitingSemaphore->mutex); PX_waitingSemaphore = NULL; } PAssertWithRetry(pthread_mutex_unlock, &PX_WaitSemMutex); #endif if (m_threadId != PNullThreadIdentifier) { #if P_USE_THREAD_CANCEL pthread_cancel(m_threadId); #else pthread_kill(m_threadId, SIGKILL); #endif WaitForTermination(100); } } PBoolean PThread::IsTerminated() const { if (m_type == e_IsProcess) return false; // Process is always still running switch (PX_state.load()) { case PX_starting : case PX_firstResume : return false; case PX_finished: return true; default : break; } // See if thread is still running, copy variable in case changes between two statements pthread_t id = m_threadId; if (id == PNullThreadIdentifier) return true; /* If thread is external, than PTLib doesn't track it state and needs to use additional methods to check it is terminated. */ if (m_type != e_IsExternal) return false; #if P_NO_PTHREAD_KILL /* Some flavours of Linux crash in pthread_kill() if the thread id is invalid. Now, IMHO, a pthread function that is not itself thread safe is utter madness, but apparently, the authors would rather change the Posix standard than fix the problem! What is the point of an ESRCH error return for invalid id if it can crash on an invalid id? As I said, complete madness. So, if we have a /proc, we always use that mechanism to determine if the external thread still exists. */ char fn[100]; snprintf(fn, sizeof(fn), "/proc/%u/task/%u/stat", getpid(), (unsigned)(intptr_t)GetUniqueIdentifier()); return access(fn, R_OK) != 0; #else return !PX_kill(id, GetUniqueIdentifier(), 0); #endif } void PThread::WaitForTermination() const { WaitForTermination(PMaxTimeInterval); } PBoolean PThread::WaitForTermination(const PTimeInterval & maxWait) const { pthread_t id = m_threadId; if (id == PNullThreadIdentifier || this == Current()) { PTRACE(2, "WaitForTermination on 0x" << hex << id << dec << " short circuited"); return true; } PTRACE(6, "WaitForTermination on 0x" << hex << id << dec << " for " << maxWait); PTimeInterval start = PTimer::Tick(); while (!IsTerminated()) { if ((PTimer::Tick() - start) > maxWait) return false; Sleep(10); // sleep for 10ms. This slows down the busy loop removing 100% // CPU usage and also yeilds so other threads can run. } PTRACE(6, "WaitForTermination on 0x" << hex << id << dec << " finished"); return true; } static PUniqueThreadIdentifier GetCurrentUniqueIdentifier() { #if defined(P_LINUX) return syscall(SYS_gettid); #elif defined(P_MACOSX) PUniqueThreadIdentifier id; return pthread_threadid_np(::pthread_self(), &id) == 0 ? id : 0; #else return (PUniqueThreadIdentifier)GetCurrentThreadId(); #endif } PUniqueThreadIdentifier PThread::GetCurrentUniqueIdentifier() { #if (__cplusplus >= 201103L) // Cache the unique ID in TLS to avoid frequent syscalls thread_local PUniqueThreadIdentifier uniqueId = ::GetCurrentUniqueIdentifier(); return uniqueId; #else return ::GetCurrentUniqueIdentifier(); #endif } int PThread::PXBlockOnIO(int handle, int type, const PTimeInterval & timeout) { PTRACE(7, "PTLib\tPThread::PXBlockOnIO(" << handle << ',' << type << ')'); if ((handle < 0) || (handle >= PProcess::Current().GetMaxHandles())) { PTRACE(2, "PTLib\tAttempt to use illegal handle in PThread::PXBlockOnIO, handle=" << handle); errno = EBADF; return -1; } int retval; #if P_HAS_POLL struct pollfd pfd[2]; pfd[0].fd = handle; switch (type) { case PChannel::PXReadBlock : case PChannel::PXAcceptBlock : pfd[0].events = POLLIN; break; case PChannel::PXWriteBlock : case PChannel::PXConnectBlock : pfd[0].events = POLLOUT; break; } pfd[0].events |= POLLERR; pfd[1].fd = unblockPipe[0]; pfd[1].events = POLLIN; do { retval = ::poll(pfd, PARRAYSIZE(pfd), timeout.GetInterval()); } while (retval < 0 && errno == EINTR); BYTE dummy; if (retval > 0 && pfd[1].revents != 0 && ::read(unblockPipe[0], &dummy, 1) == 1) { errno = ECANCELED; retval = -1; PTRACE(6, "PTLib\tUnblocked I/O fd=" << unblockPipe[0]); } #else // P_HAS_POLL P_fd_set read_fds; P_fd_set write_fds; P_fd_set exception_fds; do { switch (type) { case PChannel::PXReadBlock: case PChannel::PXAcceptBlock: read_fds = handle; write_fds.Zero(); exception_fds.Zero(); break; case PChannel::PXWriteBlock: read_fds.Zero(); write_fds = handle; exception_fds.Zero(); break; case PChannel::PXConnectBlock: read_fds.Zero(); write_fds = handle; exception_fds = handle; break; default: PAssertAlways(PLogicError); return 0; } // include the termination pipe into all blocking I/O functions read_fds += unblockPipe[0]; P_timeval tval = timeout; PPROFILE_SYSTEM( retval = ::select(PMAX(handle, unblockPipe[0])+1, read_fds, write_fds, exception_fds, tval); ); } while (retval < 0 && errno == EINTR); BYTE dummy; if (retval > 0 && read_fds.IsPresent(unblockPipe[0]) && ::read(unblockPipe[0], &ch, 1) == 1) { errno = ECANCELED; retval = -1; PTRACE(6, "PTLib\tUnblocked I/O fd=" << unblockPipe[0]); } #endif // P_HAS_POLL return retval; } void PThread::PXAbortBlock() const { static BYTE ch = 0; PAssertOS(::write(unblockPipe[1], &ch, 1) == 1); PTRACE(6, "PTLib\tUnblocking I/O fd=" << unblockPipe[0] << " thread=" << GetThreadName()); } /////////////////////////////////////////////////////////////////////////////// PSemaphore::~PSemaphore() { #if defined(P_HAS_SEMAPHORES) #if defined(P_HAS_NAMED_SEMAPHORES) if (m_namedSemaphore.ptr != NULL) { PAssertWithRetry(sem_close, m_namedSemaphore.ptr); } else if (m_name.IsEmpty()) #endif PAssertWithRetry(sem_destroy, &m_semaphore); #else PAssert(queuedLocks == 0, "Semaphore destroyed with queued locks"); PAssertWithRetry(pthread_mutex_destroy, &mutex); PAssertWithRetry(pthread_cond_destroy, &condVar); #endif } void PSemaphore::Reset(unsigned initial, unsigned maximum) { m_maximum = std::min(maximum, (unsigned)INT_MAX); m_initial = std::min(initial, m_maximum); #if defined(P_HAS_SEMAPHORES) /* Due to bug in some Linux/Kernel versions, need to clear structure manually, sem_init does not do the job. See http://stackoverflow.com/questions/1832395/sem-timedwait-not-supported-properly-on-redhat-enterprise-linux-5-3-onwards While the above link was for RHEL, seems to happen on some Fedoras as well. */ memset(&m_semaphore, 0, sizeof(sem_t)); #if defined(P_HAS_NAMED_SEMAPHORES) if (m_name.IsEmpty() && sem_init(&m_semaphore, 0, m_initial) == 0) m_namedSemaphore.ptr = NULL; else { // Since sem_open and sem_unlink are two operations, there is a small // window of opportunity that two simultaneous accesses may return // the same semaphore. Therefore, the static mutex is used to // prevent this. static pthread_mutex_t semCreationMutex = PTHREAD_MUTEX_INITIALIZER; PAssertWithRetry(pthread_mutex_lock, &semCreationMutex); if (m_name.IsEmpty()) { // sem_init didn't work, so try a named sem std::stringstream generatedName; generatedName << "/ptlib/" << getpid() << '/' << this; m_name = generatedName.str(); sem_unlink(m_name); } PAssertWithRetry(pthread_mutex_unlock, &semCreationMutex); m_namedSemaphore.ptr = sem_open(m_name, (O_CREAT | O_EXCL), 700, m_initial); if (!PAssert(m_namedSemaphore.ptr != SEM_FAILED, "Couldn't create named semaphore")) m_namedSemaphore.ptr = NULL; } #else if (m_name.IsEmpty()) PAssertWithRetry(sem_init, &m_semaphore, 0, m_initial); #endif #else if (m_name.IsEmpty()) { PAssertWithRetry(pthread_mutex_init, &mutex, NULL); PAssertWithRetry(pthread_cond_init, &condVar, NULL); currentCount = initial; } else currentCount = INT_MAX; queuedLocks = 0; #endif } void PSemaphore::Wait() { #if defined(P_HAS_SEMAPHORES) PAssertWithRetry(sem_wait, GetSemPtr()); #else if (currentCount == INT_MAX) return; PAssertWithRetry(pthread_mutex_lock, &mutex); queuedLocks++; PThread::Current()->PXSetWaitingSemaphore(this); while (currentCount == 0) { PPROFILE_SYSTEM( int err = pthread_cond_wait(&condVar, &mutex); ); PAssert(err == 0 || err == EINTR, psprintf("wait error = %i", err)); } PThread::Current()->PXSetWaitingSemaphore(NULL); queuedLocks--; currentCount--; PAssertWithRetry(pthread_mutex_unlock, &mutex); #endif } PBoolean PSemaphore::Wait(const PTimeInterval & waitTime) { if (waitTime == PMaxTimeInterval) { Wait(); return true; } // create absolute finish time PTime finishTime; finishTime += waitTime; #if defined(P_HAS_SEMAPHORES) #ifdef P_HAS_SEMAPHORES_XPG6 // use proper timed spinlocks if supported. // http://www.opengroup.org/onlinepubs/007904975/functions/sem_timedwait.html struct timespec absTime; absTime.tv_sec = finishTime.GetTimeInSeconds(); absTime.tv_nsec = finishTime.GetMicrosecond() * 1000; PPROFILE_PRE_SYSTEM(); do { if (sem_timedwait(GetSemPtr(), &absTime) == 0) { PPROFILE_POST_SYSTEM(); return true; } } while (errno == EINTR); PPROFILE_POST_SYSTEM(); PAssert(errno == ETIMEDOUT, strerror(errno)); #else // loop until timeout, or semaphore becomes available // don't use a PTimer, as this causes the housekeeping // thread to get very busy PPROFILE_PRE_SYSTEM(); do { if (sem_trywait(GetSemPtr()) == 0) { PPROFILE_POST_SYSTEM(); return true; } // tight loop is bad karma // for the linux scheduler: http://www.ussg.iu.edu/hypermail/linux/kernel/0312.2/1127.html PThread::Sleep(10); } while (PTime() < finishTime); PPROFILE_POST_SYSTEM(); #endif return false; #else if (currentCount == INT_MAX) return false; struct timespec absTime; absTime.tv_sec = finishTime.GetTimeInSeconds(); absTime.tv_nsec = finishTime.GetMicrosecond() * 1000; PPROFILE_PRE_SYSTEM(); PAssertWithRetry(pthread_mutex_lock, &mutex); PThread * thread = PThread::Current(); thread->PXSetWaitingSemaphore(this); queuedLocks++; PBoolean ok = true; while (currentCount == 0) { int err = pthread_cond_timedwait(&condVar, &mutex, &absTime); if (err == ETIMEDOUT) { ok = false; break; } else PAssert(err == 0 || err == EINTR, psprintf("timed wait error = %i", err)); } thread->PXSetWaitingSemaphore(NULL); queuedLocks--; if (ok) currentCount--; PAssertWithRetry(pthread_mutex_unlock, &mutex); PPROFILE_POST_SYSTEM(); return ok; #endif } void PSemaphore::Signal() { #if defined(P_HAS_SEMAPHORES) PAssertWithRetry(sem_post, GetSemPtr()); #else PAssertWithRetry(pthread_mutex_lock, &mutex); if (currentCount < m_maximum) currentCount++; if (queuedLocks > 0) PAssertWithRetry(pthread_cond_signal, &condVar); PAssertWithRetry(pthread_mutex_unlock, &mutex); #endif } /////////////////////////////////////////////////////////////////////////////// void PTimedMutex::InitialiseRecursiveMutex(pthread_mutex_t *mutex) { #if P_HAS_RECURSIVE_MUTEX pthread_mutexattr_t attr; pthread_mutexattr_init(&attr); #if (P_HAS_RECURSIVE_MUTEX == 2) pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); #else pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE_NP); #endif pthread_mutex_init(mutex, &attr); pthread_mutexattr_destroy(&attr); #else // P_HAS_RECURSIVE_MUTEX pthread_mutex_init(mutex, NULL); #endif // P_HAS_RECURSIVE_MUTEX } void PTimedMutex::PlatformConstruct() { InitialiseRecursiveMutex(&m_mutex); } PTimedMutex::~PTimedMutex() { int result; if (m_lockerId == pthread_self()) { // Unlock first while (m_lockCount-- > 0 && pthread_mutex_unlock(&m_mutex) == 0) ; result = pthread_mutex_destroy(&m_mutex); } else { // Wait a bit for someone else to unlock it for (PINDEX i = 0; i < 100; ++i) { if ((result = pthread_mutex_destroy(&m_mutex)) != EBUSY) break; PPROFILE_SYSTEM( usleep(100); ); } } #ifdef _DEBUG PAssert(result == 0, "Error destroying mutex"); #endif PMUTEX_DESTROYED(); } void PTimedMutex::PrintOn(ostream &strm) const { strm << "timed mutex " << this; PMutexExcessiveLockInfo::PrintOn(strm); } PBoolean PTimedMutex::PlatformWait(const PTimeInterval & waitTime) { #if !P_HAS_RECURSIVE_MUTEX // if we already have the mutex, return immediately if (pthread_equal(m_lockerId, pthread_self())) { // Note this does not need a lock as it can only be touched by the thread // which already has the mutex locked. ++m_lockCount; return true; } #endif int result; // if waiting indefinitely, then do so if (waitTime == PMaxTimeInterval) { PPROFILE_SYSTEM( result = pthread_mutex_lock(&m_mutex); ); } else { // create absolute finish time PTime finishTime; finishTime += waitTime; #if P_PTHREADS_XPG6 struct timespec absTime; absTime.tv_sec = finishTime.GetTimeInSeconds(); absTime.tv_nsec = finishTime.GetMicrosecond() * 1000; PPROFILE_SYSTEM( result = pthread_mutex_timedlock(&m_mutex, &absTime); ); #else // P_PTHREADS_XPG6 PPROFILE_PRE_SYSTEM(); while ((result = pthread_mutex_trylock(&m_mutex)) == EBUSY) { if (PTime() >= finishTime) { PPROFILE_POST_SYSTEM(); return false; } usleep(10000); } PPROFILE_POST_SYSTEM(); #endif // P_PTHREADS_XPG6 } switch (result) { case 0 : // Got the lock case EDEADLK : // Just a recursive call #if !P_HAS_RECURSIVE_MUTEX PAssert(lockerId == PNullThreadIdentifier && m_lockCount == 0, "PMutex acquired whilst locked by another thread"); #endif return true; case ETIMEDOUT : return false; // No assert } PAssertAlways(psprintf("Mutex lock failed, result=%i", result)); return false; } void PTimedMutex::PlatformSignal(const PDebugLocation * location) { #if P_HAS_RECURSIVE_MUTEX InternalSignal(location); #else if (!pthread_equal(m_lockerId, pthread_self())) { PAssertAlways("PMutex signal failed - no matching wait or signal by wrong thread"); return; } // if lock was recursively acquired, then decrement the counter // Note this does not need a separate lock as it can only be touched by the thread // which already has the mutex locked. if (InternalSignal(location)) return; #endif unsigned threadOpRetry = 0; while (PAssertThreadOp(pthread_mutex_unlock(&m_mutex), threadOpRetry, "pthread_mutex_unlock", reinterpret_cast(&m_mutex), m_location)) /* wait */; } /////////////////////////////////////////////////////////////////////////////// PSyncPoint::PSyncPoint() { PAssertWithRetry(pthread_mutex_init, &mutex, NULL); PAssertWithRetry(pthread_cond_init, &condVar, NULL); signalled = false; } PSyncPoint::PSyncPoint(const PSyncPoint &) { PAssertWithRetry(pthread_mutex_init, &mutex, NULL); PAssertWithRetry(pthread_cond_init, &condVar, NULL); signalled = false; } PSyncPoint::~PSyncPoint() { PAssertWithRetry(pthread_mutex_destroy, &mutex); PAssertWithRetry(pthread_cond_destroy, &condVar); } void PSyncPoint::Wait() { PPROFILE_PRE_SYSTEM(); PAssertWithRetry(pthread_mutex_lock, &mutex); while (!signalled) pthread_cond_wait(&condVar, &mutex); signalled = false; PAssertWithRetry(pthread_mutex_unlock, &mutex); PPROFILE_POST_SYSTEM(); } PBoolean PSyncPoint::Wait(const PTimeInterval & waitTime) { PPROFILE_PRE_SYSTEM(); PAssertWithRetry(pthread_mutex_lock, &mutex); PTime finishTime; finishTime += waitTime; struct timespec absTime; absTime.tv_sec = finishTime.GetTimeInSeconds(); absTime.tv_nsec = finishTime.GetMicrosecond() * 1000; int err = 0; while (!signalled) { err = pthread_cond_timedwait(&condVar, &mutex, &absTime); if (err == 0 || err == ETIMEDOUT) break; /* PAssertOS reports errno, so set it before */ errno = err; PAssertOS(err == EINTR); } if (err == 0) signalled = false; PAssertWithRetry(pthread_mutex_unlock, &mutex); PPROFILE_POST_SYSTEM(); return err == 0; } void PSyncPoint::Signal() { PAssertWithRetry(pthread_mutex_lock, &mutex); signalled = true; PAssertWithRetry(pthread_cond_signal, &condVar); PAssertWithRetry(pthread_mutex_unlock, &mutex); } #include #include #include #include "strfunc.h" using std::string; using std::vector; vector split(const string& s) { vector ret; typedef string::size_type string_size; string_size i = 0; while(i != s.size()){ //remove leading space while(i != s.size() && isspace(s[i])){ i++; } //loop to next space string_size j = i; while(j != s.size() && !isspace(s[j])){ j++; } if(i != j){ ret.push_back(s.substr(i, j-i)); i = j; } } return ret; } #include using std::cin; using std::cout; using std::endl; using std::getline; int main() { string s; // read and split each line of input while (getline(cin, s)) { vector v = frame(split(s)); // write each word in v for (vector::size_type i = 0; i != v.size(); ++i) cout << v[i] << endl; } return 0; } /* * Copyright (c) 2009-2011, NVIDIA Corporation * 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 NVIDIA 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 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 "CudaRenderer.hpp" using namespace FW; //------------------------------------------------------------------------ CudaRenderer::CudaRenderer(void) : m_frameBuffer (NULL, 0, Buffer::Hint_CudaGL), m_numWarps (256) // initial guess { m_compiler.setSourceFile("src/octree/cuda/Render.cu"); m_compiler.addOptions("-use_fast_math"); m_compiler.include("src/framework"); clearResults(); } //------------------------------------------------------------------------ CudaRenderer::~CudaRenderer(void) { } //------------------------------------------------------------------------ void CudaRenderer::selectAttachments(Array& out, const Array& in) const { // Clear slots. out.clear(); for (int i = 0; i < AttachSlot_Max; i++) out.add(AttachIO::VoidAttach); // Assign imported attachments. for (int i = 0; i < in.getSize(); i++) { AttachIO::AttachType t = in[i]; switch (t) { case AttachIO::ColorNormalPaletteAttach: out[AttachSlot_Attribute] = t; break; case AttachIO::ColorNormalCornerAttach: out[AttachSlot_Attribute] = t; break; case AttachIO::ColorNormalDXTAttach: out[AttachSlot_Attribute] = t; break; case AttachIO::ContourAttach: out[AttachSlot_Contour] = t; break; case AttachIO::AOAttach: out[AttachSlot_AO] = t; break; default: break; } } } //------------------------------------------------------------------------ String CudaRenderer::renderObject( Image& frame, OctreeRuntime* runtime, int objectID, const Mat4f& octreeToWorld, const Mat4f& worldToCamera, const Mat4f& projection) { FW_ASSERT(runtime); // Check frame buffer validity. if (frame.getSize().min() <= 0) return ""; if (frame.getFormat() != ImageFormat::ABGR_8888 || frame.getStride() != frame.getSize().x * frame.getBPP()) { return "CudaRenderer: Incompatible framebuffer!"; } // Determine preprocessor defines. const Array& attach = runtime->getAttachTypes(objectID); FW_ASSERT(attach.getSize() == AttachSlot_Max); m_compiler.clearDefines(); bool enableContours = (attach[AttachSlot_Contour] == AttachIO::ContourAttach && m_params.enableContours); if (enableContours) m_compiler.define("ENABLE_CONTOURS"); switch (attach[AttachSlot_Attribute]) { case AttachIO::ColorNormalPaletteAttach: m_compiler.define("VOXELATTRIB_PALETTE"); m_compiler.define("DISABLE_PUSH_OPTIMIZATION"); break; case AttachIO::ColorNormalCornerAttach: m_compiler.define("VOXELATTRIB_CORNER"); m_compiler.define("DISABLE_PUSH_OPTIMIZATION"); break; case AttachIO::ColorNormalDXTAttach: m_compiler.define("VOXELATTRIB_DXT"); break; default: return "Unsupported attribute attachment!"; } if (attach[AttachSlot_AO] == AttachIO::AOAttach) m_compiler.define("VOXELATTRIB_AO"); if (m_params.measureRaycastPerf) m_compiler.define("KERNEL_RAYCAST_PERF"); else m_compiler.define("KERNEL_RENDER"); if (m_params.enablePerfCounters) m_compiler.define("ENABLE_PERF_COUNTERS"); if (m_params.enableLargeReconstruction) m_compiler.define("LARGE_RECONSTRUCTION_KERNEL"); if (m_params.enableJitterLOD) m_compiler.define("JITTER_LOD"); if (m_params.visualization == Visualization_PrimaryAndShadow) m_compiler.define("ENABLE_SHADOWS"); if (!m_blurLUT.getSize()) constructBlurLUT(); m_compiler.define("BLUR_LUT_SIZE", String(m_blurLUT.getSize())); // Determine flags. U32 flags = 0; if (m_params.visualization == Visualization_IterationCount) flags |= RenderFlags_VisualizeIterations; else if (m_params.visualization == Visualization_RaycastLevel) flags |= RenderFlags_VisualizeRaycastLevel; // Set input. m_input.frameSize = frame.getSize(); m_input.flags = flags; m_input.batchSize = m_params.batchSize; m_input.aaRays = (m_params.enableAntialias) ? 4 : 1; m_input.maxVoxelSize = m_params.maxVoxelSize; m_input.brightness = m_params.brightness; m_input.coarseSize = m_params.coarseSize; m_input.coarseFrameSize = (m_input.frameSize + (m_params.coarseSize - 1)) / m_params.coarseSize + 1; m_input.frame = frame.getBuffer().getMutableCudaPtr(); m_input.rootNode = runtime->getRootNodeCuda(objectID); OctreeMatrices& om = m_input.octreeMatrices; Vec3f scale = Vec3f(Vec2f(2.0f) / Vec2f(m_input.frameSize), 1.0f); om.viewportToCamera = projection.inverted() * Mat4f::translate(Vec3f(-1.0f, -1.0f, 0.0f)) * Mat4f::scale(scale); om.cameraToOctree = Mat4f::translate(Vec3f(1.0f)) * (worldToCamera * octreeToWorld).inverted(); Mat4f vto = om.cameraToOctree * om.viewportToCamera; om.pixelInOctree = sqrt(Vec4f(vto.col(0)).getXYZ().cross(Vec4f(vto.col(1)).getXYZ()).length()); om.octreeToWorld = octreeToWorld * Mat4f::translate(Vec3f(-1.0f)); om.worldToOctree = invert(om.octreeToWorld); om.octreeToWorldN = octreeToWorld.getXYZ().inverted().transposed(); om.cameraPosition = invert(worldToCamera) * Vec3f(0.f, 0.f, 0.f); om.octreeToViewport = invert(om.viewportToCamera) * invert(om.cameraToOctree); om.viewportToOctreeN = (om.octreeToViewport).transposed(); // Setup frame-related buffers. int numPixels = m_input.frameSize.x * m_input.frameSize.y; if (m_pixelTable.getSize() != m_input.frameSize) { m_indexToPixel.resizeDiscard(numPixels * sizeof(S32)); m_pixelTable.setSize(m_input.frameSize); memcpy(m_indexToPixel.getMutablePtr(), m_pixelTable.getIndexToPixel(), numPixels * sizeof(S32)); } // Coarse frame and pixel buffers. int coarseNumPixels = m_input.coarseFrameSize.x * m_input.coarseFrameSize.y; m_coarseFrameBuffer.resizeDiscard(coarseNumPixels * sizeof(S32)); m_input.frameCoarse = m_coarseFrameBuffer.getMutableCudaPtr(); if (m_coarsePixelTable.getSize() != m_input.coarseFrameSize) { m_coarseIndexToPixel.resizeDiscard(coarseNumPixels * sizeof(S32)); m_coarsePixelTable.setSize(m_input.coarseFrameSize); memcpy(m_coarseIndexToPixel.getMutablePtr(), m_coarsePixelTable.getIndexToPixel(), coarseNumPixels * sizeof(S32)); m_coarseIndexToPixel.free(Buffer::CPU); } // Temp frame buffer for blurring. if (m_params.enableBlur) { // override frame buffer address! m_tempFrameBuffer.resizeDiscard(numPixels * sizeof(U32)); m_input.frame = m_tempFrameBuffer.getMutableCudaPtr(); } // AA sample buffer if (m_input.aaRays > 1) { m_aaSampleBuffer.resizeDiscard(numPixels * m_input.aaRays * sizeof(U32)); m_input.aaSampleBuffer = m_aaSampleBuffer.getMutableCudaPtr(); } // Setup performance counter buffer. if (m_params.enablePerfCounters) { m_perfCounters.resizeDiscard(m_numWarps * PerfCounter_Max * 33 * sizeof(S64)); memset(m_perfCounters.getMutablePtr(), 0, (size_t)m_perfCounters.getSize()); m_input.perfCounters = m_perfCounters.getMutableCudaPtr(); } // Render. LaunchResult coarseResult; if (m_params.enableBeamOptimization) { RenderInput old = m_input; m_input.numPrimaryRays = coarseNumPixels; m_input.aaRays = 1; m_input.flags |= RenderFlags_CoarsePass; m_input.batchSize = 1; m_compiler.undef("ENABLE_CONTOURS"); coarseResult = launch(coarseNumPixels * m_params.numFrameRepeats, false); m_input = old; m_input.flags |= RenderFlags_UseCoarseData; if (enableContours) m_compiler.define("ENABLE_CONTOURS"); } m_input.numPrimaryRays = numPixels * m_input.aaRays; LaunchResult renderResult = launch(m_input.numPrimaryRays * m_params.numFrameRepeats, true); // Post-process blur. F32 blurTime = 0.f; if (m_params.enableBlur) { // restore true frame buffer pointer m_input.frame = frame.getBuffer().getMutableCudaPtr(); // get module CudaModule* module = m_compiler.compile(); // update blur LUT Vec4i* pLUT = (Vec4i*)module->getGlobal("c_blurLUT").getMutablePtr(); for (int i=0; i < m_blurLUT.getSize(); i++) { float d = sqrtf((float)sqr(m_blurLUT[i].x) + (float)sqr(m_blurLUT[i].y)); Vec4i& v = pLUT[i]; v.x = m_blurLUT[i].x; v.y = m_blurLUT[i].y; v.z = floatToBits((float)m_blurLUT[i].z); v.w = floatToBits(d); } // update globals *(RenderInput*)module->getGlobal("c_input").getMutablePtr() = m_input; module->setTexRef("texTempFrameIn", m_tempFrameBuffer, CU_AD_FORMAT_UNSIGNED_INT8, 4); module->setTexRef("texAASamplesIn", m_aaSampleBuffer, CU_AD_FORMAT_UNSIGNED_INT8, 4); // launch blurTime = module->getKernel("blurKernel").launchTimed(frame.getSize(), Vec2i(8)); } // Update statistics. F32 totalTime = renderResult.time + coarseResult.time + blurTime; m_results.launchTime += totalTime; m_results.coarseTime += coarseResult.time; m_results.renderWarps += renderResult.numWarps; m_results.coarseWarps += coarseResult.numWarps; if (m_params.enablePerfCounters) { const S64* ptr = (const S64*)m_perfCounters.getPtr(); for (int warpIdx = 0; warpIdx < m_numWarps; warpIdx++) { for (int counterIdx = 0; counterIdx < PerfCounter_Max; counterIdx++) { for (int threadIdx = 0; threadIdx < 32; threadIdx++) m_results.threadCounters[counterIdx] += *ptr++; m_results.warpCounters[counterIdx] += *ptr++; } } } m_stats = sprintf("CudaRenderer: launch %.2f ms (%.2f FPS), %.2f MPix/s", totalTime * 1.0e3f, 1.0f / totalTime, numPixels * 1.0e-6f / totalTime); if (m_params.enableBlur) m_stats += sprintf(", blur %.2f MPix/s", numPixels * 1.0e-6f / blurTime); // Adjust the number of warps for the next run. int maxWarps = max(renderResult.numWarps, coarseResult.numWarps); if (maxWarps * 2 > m_numWarps) { if (maxWarps == m_numWarps) printf("CudaRenderer: warp count auto-detect overflow, increasing warp count to %d\n", maxWarps * 2); else printf("CudaRenderer: warp count auto-detected: %d warps, launching %d\n", maxWarps, maxWarps * 2); m_numWarps = maxWarps * 2; } return ""; } //------------------------------------------------------------------------ String CudaRenderer::renderObject( GLContext* gl, OctreeRuntime* runtime, int objectID, const Mat4f& octreeToWorld, const Mat4f& worldToCamera, const Mat4f& projection) { // Setup framebuffer. FW_ASSERT(gl); const Vec2i& size = gl->getViewSize(); int stride = size.x * sizeof(U32); m_frameBuffer.resizeDiscard(size.y * stride); Image image(size, ImageFormat::ABGR_8888, m_frameBuffer, 0, stride); // Render. String error = renderObject(image, runtime, objectID, octreeToWorld, worldToCamera, projection); if (error.getLength()) return error; // Blit to the screen. Mat4f old = gl->setVGXform(Mat4f()); gl->drawImage(image, Vec2f(0.0f), 0.5f, false); gl->setVGXform(old); return ""; } //------------------------------------------------------------------------ void CudaRenderer::clearResults(void) { m_results.launchTime = 0.0f; m_results.coarseTime = 0.0f; m_results.renderWarps = 0; m_results.coarseWarps = 0; for (int i = 0; i < PerfCounter_Max; i++) { m_results.threadCounters[i] = 0; m_results.warpCounters[i] = 0; } } //------------------------------------------------------------------------ void CudaRenderer::populateCompilerCache(void) { Array > variants; for (int i = 0;; i++) { Array defs; if (i & (1 << 0)) defs.add("VOXELATTRIB_AO"); if (i & (1 << 1)) defs.add("LARGE_RECONSTRUCTION_KERNEL"); if (i & (1 << 2)) defs.add("ENABLE_SHADOWS"); if (i & (1 << 3)) break; variants.add(defs); defs.add("PERSISTENT_THREADS"); variants.add(defs); defs.add("ENABLE_CONTOURS"); variants.add(defs); } if (!m_blurLUT.getSize()) constructBlurLUT(); for (int i = 0; i < variants.getSize(); i++) { printf("CudaRenderer: Populating compiler cache... %d/%d\r", i + 1, variants.getSize()); m_compiler.clearDefines(); m_compiler.define("KERNEL_RENDER"); m_compiler.define("VOXELATTRIB_DXT"); m_compiler.define("JITTER_LOD"); m_compiler.define("BLUR_LUT_SIZE", String(m_blurLUT.getSize())); for (int j = 0; j < variants[i].getSize(); j++) m_compiler.define(variants[i][j]); m_compiler.compile(false); failIfError(); } printf("CudaRenderer: Populating compiler cache... Done.\n"); } //------------------------------------------------------------------------ CudaRenderer::LaunchResult CudaRenderer::launch(int totalWork, bool persistentThreads) { // Setup warps. Vec2i blockSize = Vec2i(RCK_TRACE_BLOCK_WIDTH, RCK_TRACE_BLOCK_HEIGHT); int blockThreads = blockSize.x * blockSize.y; Vec2i gridSize = Vec2i(0, 1); int activeWarpTableSize = 0; m_input.totalWork = totalWork; if (persistentThreads || m_params.enablePerfCounters) { m_compiler.define("PERSISTENT_THREADS"); gridSize.x = (m_numWarps * 32 + blockThreads - 1) / blockThreads; activeWarpTableSize = (gridSize.x * gridSize.y) * ((blockThreads + 31) / 32); m_activeWarps.resizeDiscard(activeWarpTableSize * sizeof(S32)); memset(m_activeWarps.getMutablePtr(), 0, activeWarpTableSize * sizeof(S32)); m_input.activeWarps = m_activeWarps.getMutableCudaPtr(); } else { m_compiler.undef("PERSISTENT_THREADS"); gridSize.x = (totalWork + blockThreads - 1) / blockThreads; } // Compile kernel. CudaModule* module = m_compiler.compile(); // Update globals. *(RenderInput*)module->getGlobal("c_input").getMutablePtr() = m_input; *(S32*)module->getGlobal("g_warpCounter").getMutablePtr() = 0; module->setTexRef("texIndexToPixel", m_indexToPixel, CU_AD_FORMAT_UNSIGNED_INT32, 1); module->setTexRef("texFrameCoarseIn", m_coarseFrameBuffer, CU_AD_FORMAT_FLOAT, 1); module->setTexRef("texIndexToPixelCoarse", m_coarseIndexToPixel, CU_AD_FORMAT_UNSIGNED_INT32, 1); // Launch. LaunchResult res; res.time = module->getKernel("kernel").launchTimed(gridSize * blockSize, blockSize, (!m_params.measureRaycastPerf)); // Determine results. const S32* activeWarps = (const S32*)m_activeWarps.getPtr(); res.numWarps = 0; for (int i = 0; i < activeWarpTableSize; i++) if (activeWarps[i]) res.numWarps++; return res; } //------------------------------------------------------------------------ void CudaRenderer::constructBlurLUT(void) { // start by constructing low-discrepancy unit square int N = 100; // number of samples int S = 24; // max radius // init to random Array pos; for (int i=0; i < N; i++) { Vec2f p; p.x = (float)hashBits(i) / (float)(((U64)1)<<32); p.y = (float)hashBits(i+N) / (float)(((U64)1)<<32); pos.add(p); } // relax by repulsion force Array force; force.resize(N); for (int i=0; i < 20; i++) { for (int j=0; j < N; j++) { Vec2f f(0.f, 0.f); Vec2f p = pos[j]; for (int k=0; k < N; k++) { if (k==j) continue; Vec2f q = pos[k]; Vec2f d = p-q; if (d.x > .5f) d.x -= 1.f; if (d.y > .5f) d.y -= 1.f; if (d.x < -.5f) d.x += 1.f; if (d.y < -.5f) d.y += 1.f; float d2 = (d.x*d.x + d.y*d.y); float m = 1.f/d2; m *= .0001f; f += d.normalized() * m; } float flen = f.length(); flen = min(flen, .2f); f = f.normalized() * flen; force[j] = f; } for (int j=0; j < N; j++) { Vec2f p = pos[j]; p += force[j]; while (p.x > 1.f) p.x -= 1.f; while (p.y > 1.f) p.y -= 1.f; while (p.x < 0.f) p.x += 1.f; while (p.y < 0.f) p.y += 1.f; pos[j] = p; } } // form into a disc for (int i=0; i < N; i++) { Vec2f p = pos[i]; float an = p.x * 2.f * 3.14159f; float d = p.y; // inverse square weighting p.x = d * sinf(an); p.y = d * cosf(an); p = (p + 1.f) * .5f; pos[i] = p; } // work with pixels from now on Array ipos; for (int i=0; i < N; i++) { Vec2f p = pos[i]; p.x = min(max(p.x, 0.f), 1.f); p.y = min(max(p.y, 0.f), 1.f); p = (pos[i] - .5f) * 2.f * (float)S; int x = (int)(p.x+.5f); int y = (int)(p.y+.5f); ipos.add(Vec2i(x, y)); } // trim set to unique pixels Set used; Array iposTemp = ipos; ipos.clear(); for (int i=0; i < N; i++) { Vec2i p = iposTemp[i]; if (used.contains(p)) continue; used.add(p); ipos.add(p); } N = ipos.getSize(); printf("CudaRenderer: blur LUT has %d samples\n", ipos.getSize()); // sort according to distance for (int i=0; i < N; i++) { int dmin = -1; int imin = 0; for (int j=i; j < N; j++) { Vec2i p = ipos[j]; int d = p.x*p.x + p.y*p.y; if (d < dmin || dmin < 0) { dmin = d; imin = j; } } swap(ipos[i], ipos[imin]); } // construct bitmap for support find Array bmap; bmap.resize(4*S*S); for (int i=0; i < bmap.getSize(); i++) bmap[i] = -1; // blit seeds for (int i=0; i < N; i++) { Vec2i p = ipos[i]; p.x += S; p.y += S; p.x = min(max(p.x, 0), 2*S-1); p.y = min(max(p.y, 0), 2*S-1); bmap[p.x + 2*S*p.y] = i; } // fill until full for(;;) { Array bmapTemp = bmap; bool changed = false; for (int y=0; y < 2*S; y++) for (int x=0; x < 2*S; x++) { int d2 = sqr(x-S) + sqr(y-S); if (d2 > S*S) continue; int b = bmap[x+2*S*y]; if (b >= 0) continue; int x0 = max(x-1, 0); int x1 = min(x+1, 2*S-1); int y0 = max(y-1, 0); int y1 = min(y+1, 2*S-1); for (int py=y0; py<=y1; py++) for (int px=x0; px<=x1; px++) { int c = bmap[px+2*S*py]; if (c >= 0) b = c; } if (b >= 0) { changed = true; bmapTemp[x+2*S*y] = b; } } if (!changed) break; bmap = bmapTemp; } // count weights Array weight; weight.resize(N); for (int i=0; i < N; i++) weight[i] = 0; for (int i=0; i < 4*S*S; i++) { int b = bmap[i]; if (b >= 0) weight[b]++; } // construct lut for (int i=0; i < N; i++) m_blurLUT.add(Vec3i(ipos[i].x, ipos[i].y, weight[i])); // convert bitmap into lut #if 0 m_blurLUT.clear(); for (int y=0; y < 2*S; y++) for (int x=0; x < 2*S; x++) { int b = bmap[x+2*S*y]; if (b < 0) continue; m_blurLUT.add(Vec3i(x-S, y-S, hashBits(b))); } #endif } #include "Command.hpp" #include namespace vizkit3dDebugDrawings { void Command::execute(vizkit3dDebugDrawings::DrawingManager* drawingManager) const { //NOTE This method should be pure virtual, however pure virtual classes cannot // be used in orogen. throw std::runtime_error("called base class execute()"); } Command* Command::clone() const { //NOTE This method should be pure virtual, however pure virtual classes cannot // be used in orogen. throw std::runtime_error("called base class clone()"); } const std::string& Command::getDrawingChannel() const { return drawingChannel; } Command::Command(const std::string& drawingChannel) : drawingChannel(drawingChannel) { } Command::Command() : drawingChannel("default") { } Command::~Command() { } } #include using namespace std; int main(){ int x; int y; cin >> x >> y; while(1){ if(x < y){ cout << x << " " << y << endl; } else{ cout << y << " " << x << endl; } cin >> x >> y; if(x == 0 && y == 0) break; } }/* -*- mode: c++; c-basic-offset: 4; indent-tabs-mode: nil -*- this file is part of rcssserver3D Fri Oct 20 2006 Copyright (C) 2006 RoboCup Soccer Server 3D Maintenance Group 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., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include "cylinder.h" #include #include using namespace boost; using namespace kerosin; using namespace zeitgeist; using namespace salt; Cylinder::Cylinder() : SingleMatNode() { } Cylinder::~Cylinder() { } void Cylinder::SetParams(float radius, float length) { ParameterList parameter; parameter.AddValue(radius); parameter.AddValue(length); Load("StdUnitCylinder",parameter); mRadius = radius; mLength = length; } void Cylinder::GetParams(float& radius, float& length) const { radius = mRadius; length = mLength; } float Cylinder::GetRadius() { return mRadius; } float Cylinder::GetLength() { return mLength; } /* ------------------------------------------------------------------------------- Copyright (c) 2020 . 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 #include #include "BinaryWriter.h" #include "BlockReader.h" #include "Declarations.h" #include "Parser.h" #include "SymbolUtils.h" using namespace std; typedef vector strvec_t; struct ProgramInfo { string output; strvec_t files; strvec_t modules; bool disableErrorFmt; string modulePath; }; void usage(void); int main(int argc, char **argv) { if (argc <= 1) { usage(); return 0; } ProgramInfo ctx = {}; int i; for (i = 1; i < argc; ++i) { if (argv[i][0] == '-') { switch (argv[i][1]) { case 'h': usage(); exit(0); break; case 'o': if (i + 1 < argc) ctx.output = (argv[++i]); break; case 'l': if (i + 1 < argc) ctx.modules.push_back((argv[++i])); break; case 'm': DisplayModulePath(); return 0; break; case 'd': ctx.disableErrorFmt = true; break; default: break; } } else ctx.files.push_back(argv[i]); } if (ctx.output.empty()) { usage(); cout << "missing output file.\n"; return PS_ERROR; } if (find(ctx.modules.begin(), ctx.modules.end(), "std") == ctx.modules.end()) ctx.modules.push_back("std"); FindModuleDirectory(ctx.modulePath); BinaryWriter w(ctx.modulePath); for (string file : ctx.files) { Parser p; if (ctx.disableErrorFmt) p.disableErrorFormat(true); if (p.parse(file.c_str()) != PS_OK) return PS_ERROR; if (w.mergeLabels(p.getLabels()) != PS_OK) return PS_ERROR; if (w.mergeDataDeclarations(p.getDataDeclarations()) != PS_OK) return PS_ERROR; w.mergeInstructions(p.getInstructions()); // This has not been tested on multiple files yet. break; } if (w.resolve(ctx.modules) != PS_OK) return PS_ERROR; if (w.open(ctx.output.c_str()) != PS_OK) return PS_ERROR; if (w.writeHeader() != PS_OK) return PS_ERROR; if (w.writeSections() != PS_OK) return PS_ERROR; return 0; } void usage(void) { cout << "tcom \n\n"; cout << " options:\n\n"; cout << " -h show this message.\n"; cout << " -o output file.\n"; cout << " -l link library.\n"; cout << " -d disable full path when reporting errors.\n"; cout << " -m print the module path and exit.\n"; cout << "\n"; } #include "abc190/c.cc" #include "gtest/gtest.h" TEST(abc190c, 1) { EXPECT_EQ(2, solve(4, 4, {1, 1, 2, 3}, {2, 3, 4, 4}, 3, {1, 1, 2}, {2, 3, 3})); } TEST(abc190c, 2) { EXPECT_EQ(4, solve(4, 4, {1, 1, 2, 3}, {2, 3, 4, 4}, 4, {3, 1, 2, 2}, {4, 2, 4, 4})); } TEST(abc190c, 3) { EXPECT_EQ(9, solve(6, 12, {2, 4, 1, 4, 2, 1, 4, 1, 1, 2, 2, 2}, {3, 6, 2, 5, 6, 5, 5, 3, 2, 6, 3, 5}, 5, {3, 1, 2, 4, 5}, {5, 4, 6, 6, 6})); } #include "ZoneServerTestPCH.h" #include "MockPlayerAuctionController.h" using namespace gideon::zoneserver; MockPlayerAuctionController::MockPlayerAuctionController(zoneserver::go::Entity* owner) : PlayerAuctionController(owner), lastErrorCode_(ecWhatDidYouTest) { } DEFINE_SRPC_METHOD_2(MockPlayerAuctionController, onCreateAuction, ErrorCode, errorCode, GameMoney, currentMoney) { addCallCount("onCreateAuction"); lastErrorCode_ = errorCode; currentMoney; } DEFINE_SRPC_METHOD_2(MockPlayerAuctionController, onSearchEquipmentByEquipType, ErrorCode, errorCode, AuctionInfos, infos) { addCallCount("onSearchEquipmentByEquipType"); lastErrorCode_ = errorCode; auctionInfos_ = infos; } DEFINE_SRPC_METHOD_2(MockPlayerAuctionController, onSearchItemsByCodeType, ErrorCode, errorCode, AuctionInfos, infos) { addCallCount("onSearchItemsByCodeType"); lastErrorCode_ = errorCode; auctionInfos_ = infos; } DEFINE_SRPC_METHOD_2(MockPlayerAuctionController, onSellingItems, ErrorCode, errorCode, AuctionInfos, infos) { addCallCount("onSellingItems"); lastErrorCode_ = errorCode; auctionInfos_ = infos; } DEFINE_SRPC_METHOD_2(MockPlayerAuctionController, onBiddingItems, ErrorCode, errorCode, AuctionInfos, infos) { addCallCount("onBiddingItems"); lastErrorCode_ = errorCode; auctionInfos_ = infos; } DEFINE_SRPC_METHOD_4(MockPlayerAuctionController, onBid, ErrorCode, errorCode, AuctionId, auctionId, GameMoney, bidMoney, GameMoney, currentMoney) { addCallCount("onBid"); lastErrorCode_ = errorCode; auctionId, bidMoney, currentMoney; } DEFINE_SRPC_METHOD_3(MockPlayerAuctionController, onBuyOut, ErrorCode, errorCode, AuctionId, auctionId, GameMoney, currentMoney) { addCallCount("onBuyOut"); lastErrorCode_ = errorCode; auctionId, currentMoney; } DEFINE_SRPC_METHOD_2(MockPlayerAuctionController, onCancelAuction, ErrorCode, errorCode, AuctionId, auctionId) { addCallCount("onCancelAuction"); lastErrorCode_ = errorCode; auctionId; }//===----------------------------------------------------------------------===// // // Peloton // // index_scan_executor.cpp // // Identification: src/executor/index_scan_executor.cpp // // Copyright (c) 2015-16, Carnegie Mellon University Database Group // //===----------------------------------------------------------------------===// #include "executor/index_scan_executor.h" #include #include #include #include #include "catalog/manager.h" #include "common/container_tuple.h" #include "common/logger.h" #include "concurrency/transaction_manager_factory.h" #include "executor/executor_context.h" #include "executor/logical_tile.h" #include "executor/logical_tile_factory.h" #include "expression/abstract_expression.h" #include "gc/gc_manager_factory.h" #include "index/index.h" #include "planner/index_scan_plan.h" #include "storage/data_table.h" #include "storage/masked_tuple.h" #include "storage/tile_group.h" #include "storage/tile_group_header.h" #include "type/types.h" #include "type/value.h" namespace peloton { namespace executor { /** * @brief Constructor for indexscan executor. * @param node Indexscan node corresponding to this executor. */ IndexScanExecutor::IndexScanExecutor(const planner::AbstractPlan *node, ExecutorContext *executor_context) : AbstractScanExecutor(node, executor_context) {} IndexScanExecutor::~IndexScanExecutor() { // Nothing to do here } /** * @brief Let base class Dinit() first, then do my job. * @return true on success, false otherwise. */ bool IndexScanExecutor::DInit() { auto status = AbstractScanExecutor::DInit(); if (!status) return false; PL_ASSERT(children_.size() == 0); // Grab info from plan node and check it const planner::IndexScanPlan &node = GetPlanNode(); index_ = node.GetIndex(); PL_ASSERT(index_ != nullptr); index_predicate_ = node.GetIndexPredicate(); result_itr_ = START_OID; result_.clear(); done_ = false; key_ready_ = false; column_ids_ = node.GetColumnIds(); key_column_ids_ = node.GetKeyColumnIds(); expr_types_ = node.GetExprTypes(); values_ = node.GetValues(); runtime_keys_ = node.GetRunTimeKeys(); predicate_ = node.GetPredicate(); left_open_ = node.GetLeftOpen(); right_open_ = node.GetRightOpen(); // This is for limit operation accelerate limit_ = node.GetLimit(); limit_number_ = node.GetLimitNumber(); limit_offset_ = node.GetLimitOffset(); descend_ = node.GetDescend(); if (runtime_keys_.size() != 0) { PL_ASSERT(runtime_keys_.size() == values_.size()); if (!key_ready_) { values_.clear(); for (auto expr : runtime_keys_) { auto value = expr->Evaluate(nullptr, nullptr, executor_context_); LOG_TRACE("Evaluated runtime scan key: %s", value.GetInfo().c_str()); values_.push_back(value.Copy()); } key_ready_ = true; } } table_ = node.GetTable(); // PAVLO (2017-01-05): This seems unnecessary and a waste of time if (table_ != nullptr) { full_column_ids_.resize(table_->GetSchema()->GetColumnCount()); std::iota(full_column_ids_.begin(), full_column_ids_.end(), 0); } return true; } /** * @brief Creates logical tile(s) after scanning index. * @return true on success, false otherwise. */ bool IndexScanExecutor::DExecute() { LOG_TRACE("Index Scan executor :: 0 child"); if (!done_) { if (index_->GetIndexType() == IndexConstraintType::PRIMARY_KEY) { auto status = ExecPrimaryIndexLookup(); if (status == false) return false; } else { auto status = ExecSecondaryIndexLookup(); if (status == false) return false; } } // Already performed the index lookup PL_ASSERT(done_); while (result_itr_ < result_.size()) { // Avoid returning empty tiles if (result_[result_itr_]->GetTupleCount() == 0) { result_itr_++; continue; } else { LOG_TRACE("Information %s", result_[result_itr_]->GetInfo().c_str()); SetOutput(result_[result_itr_]); result_itr_++; return true; } } // end while return false; } bool IndexScanExecutor::ExecPrimaryIndexLookup() { LOG_TRACE("Exec primary index lookup"); PL_ASSERT(!done_); std::vector tuple_location_ptrs; // Grab info from plan node bool acquire_owner = GetPlanNode().IsForUpdate(); PL_ASSERT(index_->GetIndexType() == IndexConstraintType::PRIMARY_KEY); if (0 == key_column_ids_.size()) { index_->ScanAllKeys(tuple_location_ptrs); } else { // Limit clause accelerate if (limit_) { // invoke index scan limit if (!descend_) { LOG_TRACE("ASCENDING SCAN LIMIT in Primary Index"); index_->ScanLimit(values_, key_column_ids_, expr_types_, ScanDirectionType::FORWARD, tuple_location_ptrs, &index_predicate_.GetConjunctionList()[0], limit_number_, limit_offset_); } else { LOG_TRACE("DESCENDING SCAN LIMIT in Primary Index"); index_->ScanLimit(values_, key_column_ids_, expr_types_, ScanDirectionType::BACKWARD, tuple_location_ptrs, &index_predicate_.GetConjunctionList()[0], limit_number_, limit_offset_); LOG_TRACE("1-Result size is %lu", result_.size()); } } // Normal SQL (without limit) else { LOG_TRACE("Index Scan in Primary Index"); index_->Scan(values_, key_column_ids_, expr_types_, ScanDirectionType::FORWARD, tuple_location_ptrs, &index_predicate_.GetConjunctionList()[0]); } LOG_TRACE("tuple_location_ptrs:%lu", tuple_location_ptrs.size()); } if (tuple_location_ptrs.size() == 0) { LOG_TRACE("no tuple is retrieved from index."); return false; } auto &transaction_manager = concurrency::TransactionManagerFactory::GetInstance(); auto current_txn = executor_context_->GetTransaction(); auto &manager = catalog::Manager::GetInstance(); std::vector visible_tuple_locations; std::map> visible_tuples; #ifdef LOG_TRACE_ENABLED int num_tuples_examined = 0; #endif // for every tuple that is found in the index. for (auto tuple_location_ptr : tuple_location_ptrs) { ItemPointer tuple_location = *tuple_location_ptr; auto tile_group = manager.GetTileGroup(tuple_location.block); auto tile_group_header = tile_group.get()->GetHeader(); size_t chain_length = 0; #ifdef LOG_TRACE_ENABLED num_tuples_examined++; #endif // the following code traverses the version chain until a certain visible // version is found. // we should always find a visible version from a version chain. while (true) { ++chain_length; auto visibility = transaction_manager.IsVisible( current_txn, tile_group_header, tuple_location.offset); // if the tuple is deleted if (visibility == VisibilityType::DELETED) { LOG_TRACE("encounter deleted tuple: %u, %u", tuple_location.block, tuple_location.offset); break; } // if the tuple is visible. else if (visibility == VisibilityType::OK) { LOG_TRACE("perform read: %u, %u", tuple_location.block, tuple_location.offset); bool eval = true; // if having predicate, then perform evaluation. if (predicate_ != nullptr) { LOG_TRACE("perform prediate evaluate"); expression::ContainerTuple tuple( tile_group.get(), tuple_location.offset); eval = predicate_->Evaluate(&tuple, nullptr, executor_context_).IsTrue(); } // if passed evaluation, then perform write. if (eval == true) { LOG_TRACE("perform read operation"); auto res = transaction_manager.PerformRead( current_txn, tuple_location, acquire_owner); if (!res) { LOG_TRACE("read nothing"); transaction_manager.SetTransactionResult(current_txn, ResultType::FAILURE); return res; } // if perform read is successful, then add to visible tuple vector. visible_tuple_locations.push_back(tuple_location); } break; } // if the tuple is not visible. else { PL_ASSERT(visibility == VisibilityType::INVISIBLE); LOG_TRACE("Invisible read: %u, %u", tuple_location.block, tuple_location.offset); bool is_acquired = (tile_group_header->GetTransactionId( tuple_location.offset) == INITIAL_TXN_ID); bool is_alive = (tile_group_header->GetEndCommitId(tuple_location.offset) <= current_txn->GetBeginCommitId()); if (is_acquired && is_alive) { // See an invisible version that does not belong to any one in the // version chain. // this means that some other transactions have modified the version // chain. // Wire back because the current version is expired. have to search // from scratch. tuple_location = *(tile_group_header->GetIndirection(tuple_location.offset)); tile_group = manager.GetTileGroup(tuple_location.block); tile_group_header = tile_group.get()->GetHeader(); chain_length = 0; continue; } ItemPointer old_item = tuple_location; tuple_location = tile_group_header->GetNextItemPointer(old_item.offset); // there must exist a visible version. if (tuple_location.IsNull()) { if (chain_length == 1) { break; } // in most cases, there should exist a visible version. // if we have traversed through the chain and still can not fulfill // one of the above conditions, // then return result_failure. transaction_manager.SetTransactionResult(current_txn, ResultType::FAILURE); return false; } // search for next version. tile_group = manager.GetTileGroup(tuple_location.block); tile_group_header = tile_group.get()->GetHeader(); continue; } } LOG_TRACE("Traverse length: %d\n", (int)chain_length); } #ifdef LOG_TRACE_ENABLED LOG_TRACE("Examined %d tuples from index %s", num_tuples_examined, index_->GetName().c_str()); #endif LOG_TRACE("%ld tuples before pruning boundaries", visible_tuple_locations.size()); // Check whether the boundaries satisfy the required condition CheckOpenRangeWithReturnedTuples(visible_tuple_locations); LOG_TRACE("%ld tuples after pruning boundaries", visible_tuple_locations.size()); for (auto &visible_tuple_location : visible_tuple_locations) { visible_tuples[visible_tuple_location.block] .push_back(visible_tuple_location.offset); } // Construct a logical tile for each block for (auto tuples : visible_tuples) { auto &manager = catalog::Manager::GetInstance(); auto tile_group = manager.GetTileGroup(tuples.first); std::unique_ptr logical_tile(LogicalTileFactory::GetTile()); // Add relevant columns to logical tile logical_tile->AddColumns(tile_group, full_column_ids_); logical_tile->AddPositionList(std::move(tuples.second)); if (column_ids_.size() != 0) { logical_tile->ProjectColumns(full_column_ids_, column_ids_); } result_.push_back(logical_tile.release()); } done_ = true; LOG_TRACE("Result tiles : %lu", result_.size()); return true; } bool IndexScanExecutor::ExecSecondaryIndexLookup() { LOG_TRACE("ExecSecondaryIndexLookup"); PL_ASSERT(!done_); PL_ASSERT(index_->GetIndexType() != IndexConstraintType::PRIMARY_KEY); std::vector tuple_location_ptrs; // Grab info from plan node bool acquire_owner = GetPlanNode().IsForUpdate(); if (0 == key_column_ids_.size()) { index_->ScanAllKeys(tuple_location_ptrs); } else { // Limit clause accelerate if (limit_) { // invoke index scan limit if (!descend_) { LOG_TRACE("ASCENDING SCAN LIMIT in Secondary Index"); index_->ScanLimit(values_, key_column_ids_, expr_types_, ScanDirectionType::FORWARD, tuple_location_ptrs, &index_predicate_.GetConjunctionList()[0], limit_number_, limit_offset_); } else { LOG_TRACE("DESCENDING SCAN LIMIT in Secondary Index"); index_->ScanLimit(values_, key_column_ids_, expr_types_, ScanDirectionType::BACKWARD, tuple_location_ptrs, &index_predicate_.GetConjunctionList()[0], limit_number_, limit_offset_); if (tuple_location_ptrs.size() == 0) { LOG_TRACE("2-Result size is %lu", tuple_location_ptrs.size()); } } } // Normal SQL (without limit) else { LOG_TRACE("Index Scan in Primary Index"); index_->Scan(values_, key_column_ids_, expr_types_, ScanDirectionType::FORWARD, tuple_location_ptrs, &index_predicate_.GetConjunctionList()[0]); } } if (tuple_location_ptrs.size() == 0) { LOG_TRACE("no tuple is retrieved from index."); return false; } auto &transaction_manager = concurrency::TransactionManagerFactory::GetInstance(); auto current_txn = executor_context_->GetTransaction(); std::vector visible_tuple_locations; std::map> visible_tuples; auto &manager = catalog::Manager::GetInstance(); // Quickie Hack // Sometimes we can get the tuples we need in the same block if they // were inserted at the same time. So we'll record the last block that // we got for each tuple and check whether its the same to avoid having // to go back to the catalog each time. oid_t last_block = INVALID_OID; std::shared_ptr tile_group; storage::TileGroupHeader *tile_group_header = nullptr; #ifdef LOG_TRACE_ENABLED int num_tuples_examined = 0; int num_blocks_reused = 0; #endif for (auto tuple_location_ptr : tuple_location_ptrs) { ItemPointer tuple_location = *tuple_location_ptr; if (tuple_location.block != last_block) { tile_group = manager.GetTileGroup(tuple_location.block); tile_group_header = tile_group.get()->GetHeader(); } #ifdef LOG_TRACE_ENABLED else num_blocks_reused++; num_tuples_examined++; #endif // the following code traverses the version chain until a certain visible // version is found. // we should always find a visible version from a version chain. // different from primary key index lookup, we have to compare the // secondary // key to guarantee the correctness of the result. size_t chain_length = 0; while (true) { ++chain_length; auto visibility = transaction_manager.IsVisible( current_txn, tile_group_header, tuple_location.offset); // if the tuple is deleted if (visibility == VisibilityType::DELETED) { LOG_TRACE("encounter deleted tuple: %u, %u", tuple_location.block, tuple_location.offset); break; } // if the tuple is visible. else if (visibility == VisibilityType::OK) { LOG_TRACE("perform read: %u, %u", tuple_location.block, tuple_location.offset); // Further check if the version has the secondary key expression::ContainerTuple candidate_tuple( tile_group.get(), tuple_location.offset); LOG_TRACE("candidate_tuple size: %s", candidate_tuple.GetInfo().c_str()); // Construct the key tuple auto &indexed_columns = index_->GetKeySchema()->GetIndexedColumns(); storage::MaskedTuple key_tuple(&candidate_tuple, indexed_columns); // Compare the key tuple and the key if (index_->Compare(key_tuple, key_column_ids_, expr_types_, values_) == false) { LOG_TRACE("Secondary key mismatch: %u, %u\n", tuple_location.block, tuple_location.offset); break; } bool eval = true; // if having predicate, then perform evaluation. if (predicate_ != nullptr) { eval = predicate_->Evaluate(&candidate_tuple, nullptr, executor_context_).IsTrue(); } // if passed evaluation, then perform write. if (eval == true) { auto res = transaction_manager.PerformRead( current_txn, tuple_location, acquire_owner); if (!res) { transaction_manager.SetTransactionResult(current_txn, ResultType::FAILURE); LOG_TRACE("passed evaluation, but txn read fails"); return res; } // if perform read is successful, then add to visible tuple vector. visible_tuple_locations.push_back(tuple_location); LOG_TRACE("passed evaluation, visible_tuple_locations size: %lu", visible_tuple_locations.size()); } else { LOG_TRACE("predicate evaluate fails"); } break; } // if the tuple is not visible. else { PL_ASSERT(visibility == VisibilityType::INVISIBLE); LOG_TRACE("Invisible read: %u, %u", tuple_location.block, tuple_location.offset); bool is_acquired = (tile_group_header->GetTransactionId( tuple_location.offset) == INITIAL_TXN_ID); bool is_alive = (tile_group_header->GetEndCommitId(tuple_location.offset) <= current_txn->GetBeginCommitId()); if (is_acquired && is_alive) { // See an invisible version that does not belong to any one in the // version chain. // this means that some other transactions have modified the version // chain. // Wire back because the current version is expired. have to search // from scratch. tuple_location = *(tile_group_header->GetIndirection(tuple_location.offset)); tile_group = manager.GetTileGroup(tuple_location.block); tile_group_header = tile_group.get()->GetHeader(); chain_length = 0; continue; } ItemPointer old_item = tuple_location; tuple_location = tile_group_header->GetNextItemPointer(old_item.offset); if (tuple_location.IsNull()) { // For an index scan on a version chain, the result should be one of // the following: // (1) find a visible version // (2) find a deleted version // (3) find an aborted version with chain length equal to one if (chain_length == 1) { break; } // in most cases, there should exist a visible version. // if we have traversed through the chain and still can not fulfill // one of the above conditions, // then return result_failure. transaction_manager.SetTransactionResult(current_txn, ResultType::FAILURE); return false; } // search for next version. tile_group = manager.GetTileGroup(tuple_location.block); tile_group_header = tile_group.get()->GetHeader(); } } LOG_TRACE("Traverse length: %d\n", (int)chain_length); } #ifdef LOG_TRACE_ENABLED LOG_TRACE("Examined %d tuples from index %s [num_blocks_reused=%d]", num_tuples_examined, index_->GetName().c_str(), num_blocks_reused); #endif // Check whether the boundaries satisfy the required condition CheckOpenRangeWithReturnedTuples(visible_tuple_locations); for (auto &visible_tuple_location : visible_tuple_locations) { visible_tuples[visible_tuple_location.block] .push_back(visible_tuple_location.offset); } // Construct a logical tile for each block for (auto tuples : visible_tuples) { auto &manager = catalog::Manager::GetInstance(); auto tile_group = manager.GetTileGroup(tuples.first); std::unique_ptr logical_tile(LogicalTileFactory::GetTile()); // Add relevant columns to logical tile logical_tile->AddColumns(tile_group, full_column_ids_); logical_tile->AddPositionList(std::move(tuples.second)); if (column_ids_.size() != 0) { logical_tile->ProjectColumns(full_column_ids_, column_ids_); } result_.push_back(logical_tile.release()); } done_ = true; LOG_TRACE("Result tiles : %lu", result_.size()); return true; } void IndexScanExecutor::CheckOpenRangeWithReturnedTuples( std::vector &tuple_locations) { while (left_open_) { LOG_TRACE("Range left open!"); auto tuple_location_itr = tuple_locations.begin(); if (tuple_location_itr == tuple_locations.end() || CheckKeyConditions(*tuple_location_itr) == true) left_open_ = false; else tuple_locations.erase(tuple_location_itr); } while (right_open_) { LOG_TRACE("Range right open!"); auto tuple_location_itr = tuple_locations.rbegin(); if (tuple_location_itr == tuple_locations.rend() || CheckKeyConditions(*tuple_location_itr) == true) right_open_ = false; else tuple_locations.pop_back(); } } bool IndexScanExecutor::CheckKeyConditions(const ItemPointer &tuple_location) { // The size of these three arrays must be the same PL_ASSERT(key_column_ids_.size() == expr_types_.size()); PL_ASSERT(expr_types_.size() == values_.size()); LOG_TRACE("Examining key conditions for the returned tuple."); auto &manager = catalog::Manager::GetInstance(); auto tile_group = manager.GetTileGroup(tuple_location.block); expression::ContainerTuple tuple(tile_group.get(), tuple_location.offset); // This is the end of loop oid_t cond_num = key_column_ids_.size(); // Go over each attribute in the list of comparison columns // The key_columns_ids, as the name shows, saves the key column ids that // have values and expression needs to be compared. for (oid_t i = 0; i < cond_num; i++) { // First retrieve the tuple column ID from the map, and then map // it to the column ID of index key oid_t tuple_key_column_id = key_column_ids_[i]; // This the comparison right hand side operand const type::Value &rhs = values_[i]; // Also retrieve left hand side operand using index key column ID type::Value val = (tuple.GetValue(tuple_key_column_id)); const type::Value &lhs = val; // Expression type. We use this to interpret comparison result // // Possible results of comparison are: EQ, >, < const ExpressionType expr_type = expr_types_[i]; // If the operation is IN, then use the boolean values comparator // that determines whether a value is in a list // // To make the procedure more uniform, we interpret IN as EQUAL // and NOT IN as NOT EQUAL, and react based on expression type below // accordingly /*if (expr_type == ExpressionType::COMPARE_IN) { bool bret = lhs.InList(rhs); if (bret == true) { diff = VALUE_COMPARE_EQUAL; } else { diff = VALUE_COMPARE_NO_EQUAL; } } else { diff = lhs.Compare(rhs); } LOG_TRACE("Difference : %d ", diff);*/ if (lhs.CompareEquals(rhs) == type::CMP_TRUE) { switch (expr_type) { case ExpressionType::COMPARE_EQUAL: case ExpressionType::COMPARE_LESSTHANOREQUALTO: case ExpressionType::COMPARE_GREATERTHANOREQUALTO: case ExpressionType::COMPARE_IN: continue; case ExpressionType::COMPARE_NOTEQUAL: case ExpressionType::COMPARE_LESSTHAN: case ExpressionType::COMPARE_GREATERTHAN: return false; default: throw IndexException("Unsupported expression type : " + ExpressionTypeToString(expr_type)); } } else { if (lhs.CompareLessThan(rhs) == type::CMP_TRUE) { switch (expr_type) { case ExpressionType::COMPARE_NOTEQUAL: case ExpressionType::COMPARE_LESSTHAN: case ExpressionType::COMPARE_LESSTHANOREQUALTO: continue; case ExpressionType::COMPARE_EQUAL: case ExpressionType::COMPARE_GREATERTHAN: case ExpressionType::COMPARE_GREATERTHANOREQUALTO: case ExpressionType::COMPARE_IN: return false; default: throw IndexException("Unsupported expression type : " + ExpressionTypeToString(expr_type)); } } else { if (lhs.CompareGreaterThan(rhs) == type::CMP_TRUE) { switch (expr_type) { case ExpressionType::COMPARE_NOTEQUAL: case ExpressionType::COMPARE_GREATERTHAN: case ExpressionType::COMPARE_GREATERTHANOREQUALTO: continue; case ExpressionType::COMPARE_EQUAL: case ExpressionType::COMPARE_LESSTHAN: case ExpressionType::COMPARE_LESSTHANOREQUALTO: case ExpressionType::COMPARE_IN: return false; default: throw IndexException("Unsupported expression type : " + ExpressionTypeToString(expr_type)); } } else { // Since it is an AND predicate, we could directly return false return false; } } } } LOG_TRACE("Examination returning true."); return true; } // column_ids is the right predicate column id. For example, // i_id = s_id, then s_id is column_ids // But the passing value is the result (output) id. We need to transform it to // physical id void IndexScanExecutor::UpdatePredicate( const std::vector &column_ids, const std::vector &values) { // Update index predicate LOG_TRACE("values_ size %lu", values_.size()); std::vector key_column_ids; PL_ASSERT(column_ids.size() <= column_ids_.size()); // Get the real physical ids for (auto column_id : column_ids) { key_column_ids.push_back(column_ids_[column_id]); LOG_TRACE("Output id is %d---physical column id is %d", column_id, column_ids_[column_id]); } // Update values in index plan node PL_ASSERT(key_column_ids.size() == values.size()); PL_ASSERT(key_column_ids_.size() == values_.size()); // Find out the position (offset) where is key_column_id for (oid_t new_idx = 0; new_idx < key_column_ids.size(); new_idx++) { unsigned int current_idx = 0; for (; current_idx < values_.size(); current_idx++) { if (key_column_ids[new_idx] == key_column_ids_[current_idx]) { LOG_TRACE("Orignial is %d:%s", key_column_ids[new_idx], values_[current_idx].GetInfo().c_str()); LOG_TRACE("Changed to %d:%s", key_column_ids[new_idx], values[new_idx].GetInfo().c_str()); values_[current_idx] = values[new_idx]; // There should not be two same columns. So when we find a column, we // should break the loop break; } } // If new value doesn't exist in current value list, add it. // For the current simple optimizer, since all the key column ids must be // initiated when creating index_scan_plan, we don't need to examine // whether // the passing column and value exist or not (they definitely exist). But // for the future optimizer, we probably change the logic. So we still // keep // the examine code here. if (current_idx == values_.size()) { LOG_TRACE("Add new column for index predicate:%u-%s", key_column_ids[new_idx], values[new_idx].GetInfo().c_str()); // Add value values_.push_back(values[new_idx]); // Add column id key_column_ids_.push_back(key_column_ids[new_idx]); // Add column type. // TODO: We should add other types in the future expr_types_.push_back(ExpressionType::COMPARE_EQUAL); } } // Update the new value index_predicate_.GetConjunctionListToSetup()[0] .SetTupleColumnValue(index_.get(), key_column_ids, values); } void IndexScanExecutor::ResetState() { result_.clear(); result_itr_ = START_OID; done_ = false; const planner::IndexScanPlan &node = GetPlanNode(); left_open_ = node.GetLeftOpen(); right_open_ = node.GetRightOpen(); } } // namespace executor } // namespace peloton #include #include #include #include "Simulation.h" #include "Marshal.h" const char *FORMAT = "Format: gg1.x " " [NUM_PACKETS]"; int main(int argc, char **argv) { // Parse mandatory parameters if (argc < 4 || argc > 5) { std::cout << FORMAT << std::endl; return 1; } double arrivalRate = std::stod(argv[1]); double serviceRate = std::stod(argv[2]); int queueCapacityInt = std::stoi(argv[3]); if (queueCapacityInt < 0) { std::cout << "ERROR: queue capacity_ must be non-negative\n"; return 1; } if (arrivalRate <= 0 || serviceRate <= 0) { std::cout << "ERROR: arrival and service rates must be positive\n"; return 1; } size_t queueCapacity = static_cast(queueCapacityInt); // Check whether number of packets were provided: size_t maxPackets = 10000; if (argc == 5) { int maxPackets_ = std::stoi(argv[4]); if (maxPackets_ <= 0) { std::cerr << "ERROR: number of packets must be positive\n"; return 1; } maxPackets = static_cast(maxPackets_); } auto ret = cqumo::simMM1( arrivalRate, serviceRate, queueCapacity, maxPackets); // Print results to stdout: std::cout << toYaml(ret) << std::endl; return 0; } 0 #include "SkyRoads.h" #include "Objects/SimpleCube.h" #include "Objects/Heart.h" #include #include #include #include #include #include #include using namespace std; float minSpeedZ = 5.0f; float maxSpeedZ = 20.0f; float speedZ = 0.0f; float previousSpeedZ = 0.0f; float previousAspect = 0.0f; float previousRotateSpeed = 0.0f; float speedPlatformDuration = 0.0f; float platformMaxSpeedZ = 30.0f; float speedX = 1.75f; float speedY = 0.0f; float maxRotateSpeedX = 0.80f; float minRotateSpeedX = 0.1f; float rotateSpeedX = 0.1f; float rotateX = 0; float accY = -0.001f; float gravity = -9.81f * 1.85f; float platformScaleX = 0.25f; float platformScaleY = 0.1f; int maxPlatformScaleZ = 30; int minPlatformScaleZ = 5; int maxHelperScaleZ = 10; int minHelperScaleZ = 3; int minSpacing = 3; int maxSpacing = 8; float helperPlatformOffset = 0.5f; float distanceForBackup = -40.0f; glm::vec3 camPos; glm::vec3 initCamPos; vector platforms; vector helperPlatform; vector removePlatforms; vector livesPosition; SkyRoads::Player player; float aspectX = 60.0f; float minAspectX = 60.0f; float maxAspectX = 70.0f; bool firstPerson = false; bool reverseValues = true; float maxFuel = 100; float fuel = 100; int speedPlatformChance = 25; int fuelPlatformChance = 15; int fuelLossPlatformChance = 20; int deathPlatformChance = 10; int lifePlatformChance = 5; int speedPlatformCD = 7; int fuelPlatformCD = 10; int fuelLossPlatformCD = 7; int deathPlatformCD = 10; int lifePlatformCD = 20; int curSpeedPlatformCD = 0; int curFuelPlatformCD = 0; int curFuelLossPlatformCD = 0; int curDeathPlatformCD = 0; int curLifePlatformCD = 0; int livesRemaining = 3; bool freshReset = false; SkyRoads::SkyRoads() { } SkyRoads::~SkyRoads() { } void SkyRoads::Init() { // Initialise randomness srand(time(NULL)); // Set camera glm::ivec2 resolution = window->GetResolution(); camera = GetSceneCamera(); camera->SetPosition(glm::vec3(0, 1.5f, 3)); camPos = glm::vec3(0, 1.5f, 3); initCamPos = glm::vec3(0, 1.5f, 3); { Mesh* mesh = new Mesh("box"); mesh->LoadMesh(RESOURCE_PATH::MODELS + "Primitives", "box.obj"); meshes[mesh->GetMeshID()] = mesh; mesh = new Mesh("sphere"); mesh->LoadMesh(RESOURCE_PATH::MODELS + "Primitives", "sphere.obj"); meshes[mesh->GetMeshID()] = mesh; mesh = new Mesh("blenderSphere"); mesh->LoadMesh(RESOURCE_PATH::MODELS + "Primitives", "BlendSphere3.obj"); meshes[mesh->GetMeshID()] = mesh; mesh = SimpleCube::CreateCube("LeCube"); AddMeshToList(mesh); mesh = SimpleCube::CreateActiveCube("LeActiveCube"); AddMeshToList(mesh); mesh = SimpleCube::CreateSpeedCube("LeSpeedCube"); AddMeshToList(mesh); mesh = SimpleCube::CreateFuelBar("LeFuelCubeBar"); AddMeshToList(mesh); mesh = SimpleCube::CreateFuelBackgroundBar("LeFuelBackgroundCube"); AddMeshToList(mesh); mesh = Heart::CreateHeart("LeHeart"); AddMeshToList(mesh); mesh = SimpleCube::CreateFuelPlatform("LeFuelCube"); AddMeshToList(mesh); mesh = SimpleCube::CreateFuelLossPlatform("LeFuelLossCube"); AddMeshToList(mesh); mesh = SimpleCube::CreateDeathPlatform("LeDeathCube"); AddMeshToList(mesh); } // Create a shader program for drawing face polygon with the color of the normal { Shader *shader = new Shader("ShaderSkyRoads"); shader->AddShader("Source/Laboratoare/Tema1Master/Shaders/VertexShader.glsl", GL_VERTEX_SHADER); shader->AddShader("Source/Laboratoare/Tema1Master/Shaders/FragmentShader.glsl", GL_FRAGMENT_SHADER); shader->CreateAndLink(); shaders[shader->GetName()] = shader; } { Shader *shader = new Shader("Player"); shader->AddShader("Source/Laboratoare/Tema1Master/Shaders/PlayerVertexShader.glsl", GL_VERTEX_SHADER); shader->AddShader("Source/Laboratoare/Tema1Master/Shaders/PlayerFragmentShader.glsl", GL_FRAGMENT_SHADER); shader->CreateAndLink(); shaders[shader->GetName()] = shader; } { Shader *shader = new Shader("LifePlatform"); shader->AddShader("Source/Laboratoare/Tema1Master/Shaders/HealthPlatformVertexShader.glsl", GL_VERTEX_SHADER); shader->AddShader("Source/Laboratoare/Tema1Master/Shaders/HealthPlatformFragmentShader.glsl", GL_FRAGMENT_SHADER); shader->CreateAndLink(); shaders[shader->GetName()] = shader; } { Shader *shader = new Shader("UI"); shader->AddShader("Source/Laboratoare/Tema1Master/Shaders/UIVertexShader.glsl", GL_VERTEX_SHADER); shader->AddShader("Source/Laboratoare/Tema1Master/Shaders/UIFragmentShader.glsl", GL_FRAGMENT_SHADER); shader->CreateAndLink(); shaders[shader->GetName()] = shader; } { Shader *shader = new Shader("UITest"); shader->AddShader("Source/Laboratoare/Tema1Master/Shaders/UIVerTest.glsl", GL_VERTEX_SHADER); shader->AddShader("Source/Laboratoare/Tema1Master/Shaders/UIFrTest.glsl", GL_FRAGMENT_SHADER); shader->CreateAndLink(); shaders[shader->GetName()] = shader; } // Compute initial position of dummy platforms float cc = -1; for (int i = 0; i < 3; ++i) { Platform currentPlatform; currentPlatform.maxX *= platformScaleX; currentPlatform.minX *= platformScaleX; currentPlatform.maxY *= platformScaleY; currentPlatform.minY *= platformScaleY; currentPlatform.maxZ *= 10.0f; currentPlatform.minZ *= 10.0f; currentPlatform.maxX += cc; currentPlatform.minX += cc; currentPlatform.minY -= 0.1f; currentPlatform.maxY -= 0.1f; currentPlatform.centerX += cc; currentPlatform.centerY -= 0.1f; currentPlatform.laneOffset = cc; currentPlatform.scaleZ = 10; currentPlatform.lane = i * 2; cc++; printf("The current limits are: x: (%.2f %.2f), y(%.2f, %.2f), z(%.2f, %.2f) for platform %d\n", currentPlatform.minX, currentPlatform.maxX, currentPlatform.minY, currentPlatform.maxY, currentPlatform.minZ, currentPlatform.maxZ, i); platforms.push_back(currentPlatform); } // Add lives position livesPosition.push_back(glm::vec3(0.6f, 0.75, 0)); livesPosition.push_back(glm::vec3(0.7f, 0.75, 0)); livesPosition.push_back(glm::vec3(0.8f, 0.75, 0)); } Mesh* SkyRoads::CreateMesh(const char *name, const std::vector &vertices, const std::vector &indices) { unsigned int VAO = 0; // TODO: Create the VAO and bind it glGenVertexArrays(1, &VAO); glBindVertexArray(VAO); // TODO: Create the VBO and bind it unsigned int VBO; glGenBuffers(1, &VBO); glBindBuffer(GL_ARRAY_BUFFER, VBO); // TODO: Send vertices data into the VBO buffer glBufferData(GL_ARRAY_BUFFER, sizeof(vertices[0]) * vertices.size(), &vertices[0], GL_STATIC_DRAW); // TODO: Crete the IBO and bind it unsigned int IBO; glGenBuffers(1, &IBO); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, IBO); // TODO: Send indices data into the IBO buffer glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices[0]) * indices.size(), &indices[0], GL_STATIC_DRAW); // ======================================================================== // This section describes how the GPU Shader Vertex Shader program receives data // set vertex position attribute glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(VertexFormat), 0); // set vertex normal attribute glEnableVertexAttribArray(1); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(VertexFormat), (void*)(sizeof(glm::vec3))); // set texture coordinate attribute glEnableVertexAttribArray(2); glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(VertexFormat), (void*)(2 * sizeof(glm::vec3))); // set vertex color attribute glEnableVertexAttribArray(3); glVertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE, sizeof(VertexFormat), (void*)(2 * sizeof(glm::vec3) + sizeof(glm::vec2))); // ======================================================================== // Unbind the VAO glBindVertexArray(0); // Check for OpenGL errors CheckOpenGLError(); // Mesh information is saved into a Mesh object meshes[name] = new Mesh(name); meshes[name]->InitFromBuffer(VAO, static_cast(indices.size())); meshes[name]->vertices = vertices; meshes[name]->indices = indices; return meshes[name]; } void SkyRoads::FrameStart() { // clears the color buffer (using the previously set color) and depth buffer glClearColor(0, 0, 0, 1); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glm::ivec2 resolution = window->GetResolution(); // sets the screen area where to draw glViewport(0, 0, resolution.x, resolution.y); } void SkyRoads::Update(float deltaTimeSeconds) { if (player.isDead) { RenderDeathCam(deltaTimeSeconds); return; } // End condition if (player.posY < -7) { if (livesRemaining <= 0) player.isDead = true; else { livesRemaining--; ResetPlayerPosition(); } } /*glm::mat4 modelMatrix = glm::mat4(1); modelMatrix = glm::translate(modelMatrix, glm::vec3(0, 0, 0)); modelMatrix = glm::scale(modelMatrix, glm::vec3(0.1, 0.3, 1)); RenderSimpleMesh(meshes["LeFuelCubeBar"], shaders["UITest"], modelMatrix);*/ RenderHearts(); RenderFuelBar(); SetCameraPerspective(); // Manage buffs ManageSpeedBuff(deltaTimeSeconds); bool abovePlatform = false; int index = -1; // Check if player is on platforms index = CheckPlayerAbovePlatformXZ(); if (index != -1) { abovePlatform = true; } // If the player is going to go through the platform, don't let him // Place him on top of the landing platform if (abovePlatform) { if (player.posY + deltaTimeSeconds * accY < platforms[index].maxY && player.posY + deltaTimeSeconds * accY >= platforms[index].maxY - 0.1f) { player.posY = platforms[index].maxY; player.airborne = false; platforms[index].isPlayerAbove = true; if (!platforms[index].appliedEffect) { ApplyPlatformEffect(index); } accY = -0.001f; } else if (player.posY > platforms[index].maxY) { platforms[index].isPlayerAbove = false; } } else { player.airborne = true; } // Update the rotation of the ball rotateX -= rotateSpeedX; if (rotateX < -360) { rotateX = 0; } // Apply gravity only when the player is in the air if (!freshReset && player.airborne) { accY += deltaTimeSeconds * gravity; if (accY > 0) { fuel -= deltaTimeSeconds * 5; } } // Limit the maximum speed on Y if (accY < -10) { accY = -10; } // Update the player position on Y player.posY += deltaTimeSeconds * accY; // Move all platforms MovePlatforms(deltaTimeSeconds); // Remove the platforms that would dissapear RemovePlatforms(); // Render objects RenderPlatforms(); RenderPlayer(glm::vec3(1, 0, 0)); } void SkyRoads::SetCameraPerspective() { camera->SetPerspective(aspectX, window->props.aspectRatio, 0.01f, 400.0f); if (firstPerson) { camera->SetPosition(glm::vec3(player.posX, player.posY + 0.130 + 0.17, player.posZ - 0.3f)); camPos = glm::vec3(player.posX, player.posY + 0.130 + 0.17, player.posZ - 0.3f); } else { camera->SetPosition(initCamPos); camPos = initCamPos; } } void SkyRoads::RenderFuelBar() { float percent = (float)fuel / maxFuel; if (percent < 0) { percent = 0; } glm::mat4 modelMatrix = glm::mat4(1); modelMatrix = glm::translate(modelMatrix, glm::vec3(0.7, 0.62, 0)); modelMatrix = glm::scale(modelMatrix, glm::vec3(0.20f, 0.07f, 0.01f)); modelMatrix = glm::translate(modelMatrix, glm::vec3((percent - 1), 0, 0)); modelMatrix = glm::scale(modelMatrix, glm::vec3(percent, 1, 1)); RenderSimpleMesh(meshes["LeFuelCubeBar"], shaders["UITest"], modelMatrix); modelMatrix = glm::mat4(1); modelMatrix = glm::translate(modelMatrix, glm::vec3(0.7, 0.62, 0.05)); modelMatrix = glm::scale(modelMatrix, glm::vec3(0.20f, 0.07f, 0.01f)); RenderSimpleMesh(meshes["LeFuelBackgroundCube"], shaders["UITest"], modelMatrix); // Render the fuel bar if (speedPlatformDuration > 0) { percent = speedPlatformDuration / 5.0f; modelMatrix = glm::mat4(1); modelMatrix = glm::translate(modelMatrix, glm::vec3(0.7, 0.3, 0.05)); modelMatrix = glm::scale(modelMatrix, glm::vec3(0.20f, 0.07f, 0.01f)); modelMatrix = glm::translate(modelMatrix, glm::vec3((percent - 1), 0, 0)); modelMatrix = glm::scale(modelMatrix, glm::vec3(percent, 1, 1)); RenderSimpleMesh(meshes["LeSpeedCube"], shaders["UITest"], modelMatrix); } } void SkyRoads::RenderDeathCam(float deltaTimeSeconds) { // Render the ball RenderPlayer(glm::vec3(1, 1, 1)); // Keep spinning it rotateX -= rotateSpeedX; if (rotateX < -360) { rotateX = 0; } if (abs(camPos.x - player.posX) > 0.02f) { if (camPos.x - player.posX > 0) { camPos.x -= deltaTimeSeconds * 3; } else { camPos.x += deltaTimeSeconds * 3; } } if (abs(camPos.y - (player.posY + 0.13)) > 0.02f) { if (camPos.y - player.posY > 0) { camPos.y -= deltaTimeSeconds * 3; } else { camPos.y += deltaTimeSeconds * 3; } } if (abs(camPos.z - player.posZ) > .5f) { if (camPos.z - player.posZ > 0) { camPos.z -= deltaTimeSeconds * 3; } else { camPos.z += deltaTimeSeconds * 3; } } camera->SetPosition(camPos); } void SkyRoads::FrameEnd() { //DrawCoordinatSystem(); } void SkyRoads::RenderSimpleMesh(Mesh *mesh, Shader *shader, const glm::mat4 & modelMatrix) { if (!mesh || !shader || !shader->GetProgramID()) return; // render an object using the specified shader and the specified position glUseProgram(shader->program); // TODO : get shader location for uniform mat4 "Model" // TODO : set shader uniform "Model" to modelMatrix int location = glGetUniformLocation(shader->program, "Model"); glUniformMatrix4fv(location, 1, GL_FALSE, glm::value_ptr(modelMatrix)); // TODO : get shader location for uniform mat4 "View" // TODO : set shader uniform "View" to viewMatrix location = glGetUniformLocation(shader->program, "View"); glm::mat4 viewMatrix = GetSceneCamera()->GetViewMatrix(); if (player.isDead) { glm::vec3 playerPos(player.posX, player.posY + 0.13, player.posZ); glm::vec3 dir = glm::normalize(camPos - playerPos); glm::vec3 up = glm::vec3(0.0f, 1.0f, 0.0f); glm::vec3 cameraRight = glm::normalize(glm::cross(up, dir)); glm::vec3 cameraUp = glm::cross(dir, cameraRight); viewMatrix = glm::lookAt(camPos, playerPos, cameraUp); } glUniformMatrix4fv(location, 1, GL_FALSE, glm::value_ptr(viewMatrix)); // TODO : get shader location for uniform mat4 "Projection" // TODO : set shader uniform "Projection" to projectionMatrix location = glGetUniformLocation(shader->program, "Projection"); glm::mat4 projectionMatrix = GetSceneCamera()->GetProjectionMatrix(); glUniformMatrix4fv(location, 1, GL_FALSE, glm::value_ptr(projectionMatrix)); // Send the current time elapsed to the shader location = glGetUniformLocation(shader->program, "time"); glUniform1f(location, Engine::GetElapsedTime()); location = glGetUniformLocation(shader->program, "speedBuffDuration"); glUniform1f(location, speedPlatformDuration); // Draw the object glBindVertexArray(mesh->GetBuffers()->VAO); glDrawElements(mesh->GetDrawMode(), static_cast(mesh->indices.size()), GL_UNSIGNED_SHORT, 0); } // Documentation for the input functions can be found in: "/Source/Core/Window/InputController.h" or // https://github.com/UPB-Graphics/Framework-EGC/blob/master/Source/Core/Window/InputController.h void SkyRoads::OnInputUpdate(float deltaTime, int mods) { if (!player.isDead) { if (window->KeyHold(GLFW_KEY_W) && speedPlatformDuration <= 0) { if (speedZ + deltaTime * 8 < maxSpeedZ) { speedZ += deltaTime * 8; } else { speedZ = maxSpeedZ; } if (aspectX + deltaTime * 2 < maxAspectX) { aspectX += deltaTime * 2; } else { aspectX = maxAspectX; } if (rotateSpeedX + deltaTime / 8 < maxRotateSpeedX) { rotateSpeedX += deltaTime / 8; } else { rotateSpeedX = maxRotateSpeedX; } if (speedZ < minSpeedZ) { speedZ = minSpeedZ; } } if (window->KeyHold(GLFW_KEY_S) && speedPlatformDuration <= 0) { if (speedZ - deltaTime * 8 > minSpeedZ) { speedZ -= deltaTime * 8; } else { speedZ = minSpeedZ; } if (aspectX - deltaTime * 2 > minAspectX) { aspectX -= deltaTime * 2; } else { aspectX = minAspectX; } if (rotateSpeedX - deltaTime / 8 > minRotateSpeedX) { rotateSpeedX -= deltaTime / 8; } else { rotateSpeedX = minRotateSpeedX; } } if (window->KeyHold(GLFW_KEY_A) && fuel > 0) { bool hitWall = false; // If it ever happens that there are NO platforms, move freely if (platforms.size() == 0) { player.posX -= deltaTime * speedX; return; } if (player.airborne) { for (int i = 0; i < platforms.size(); ++i) { if (player.posX - deltaTime * speedX <= platforms[i].maxX && player.posX - deltaTime * speedX >= platforms[i].minX) { if (player.posZ >= platforms[i].minZ && player.posZ <= platforms[i].maxZ) { if (player.posY < platforms[i].maxY - 0.05f && player.posY >= platforms[i].minY) { printf("Hitting right side of platftorm!\n"); hitWall = true; break; } } } } if (!hitWall) { if (!freshReset) fuel -= deltaTime * 5; player.posX -= deltaTime * speedX; } } else { if (!freshReset) fuel -= deltaTime * 5; player.posX -= deltaTime * speedX; } } if (window->KeyHold(GLFW_KEY_D) && fuel > 0) { bool hitWall = false; if (platforms.size() == 0) { player.posX += deltaTime * speedX; return; } if (player.airborne) { for (int i = 0; i < platforms.size(); ++i) { if (player.posX + deltaTime * speedX >= platforms[i].minX && player.posX + deltaTime * speedX <= platforms[i].maxX) { if (player.posZ >= platforms[i].minZ && player.posZ <= platforms[i].maxZ) { if (player.posY < platforms[i].maxY - 0.05f && player.posY >= platforms[i].minY) { printf("Hitting right side of platftorm!\n"); hitWall = true; break; } } } } if (!hitWall) { if (!freshReset) fuel -= deltaTime * 5; player.posX += deltaTime * speedX; } } else { if (!freshReset) fuel -= deltaTime * 5; player.posX += deltaTime * speedX; } } } } void SkyRoads::OnKeyPress(int key, int mods) { if (window->KeyHold(GLFW_KEY_SPACE) ) { if (!freshReset) { if (fuel > 0) { std::cout << boolalpha; std::cout << "Airborne status: " << player.airborne << endl; if (!player.airborne) { accY = 5; player.airborne = true; } } } else { player.airborne = true; freshReset = false; } } if (window->KeyHold(GLFW_KEY_R)) { player.posX = 0; player.posY = 2; accY = 0; player.isDead = false; } if (window->KeyHold(GLFW_KEY_C)) { if (firstPerson) { firstPerson = false; } else { firstPerson = true; } } } void SkyRoads::OnKeyRelease(int key, int mods) { // add key release event } void SkyRoads::OnMouseMove(int mouseX, int mouseY, int deltaX, int deltaY) { // add mouse move event } void SkyRoads::OnMouseBtnPress(int mouseX, int mouseY, int button, int mods) { // add mouse button press event } void SkyRoads::OnMouseBtnRelease(int mouseX, int mouseY, int button, int mods) { // add mouse button release event } void SkyRoads::OnMouseScroll(int mouseX, int mouseY, int offsetX, int offsetY) { } void SkyRoads::OnWindowResize(int width, int height) { } void SkyRoads::GenerateNewPlatforms(Platform platform) { Platform currentPlatform = SetPlatformLimits(platform, false, platform.laneOffset); //DebugPlatformInfo(currentPlatform, "current"); // Position the platform accordingly float difference = platform.minZ - currentPlatform.maxZ - 0.02f; currentPlatform.minZ += difference; currentPlatform.maxZ += difference; currentPlatform.centerZ += difference; //DebugPlatformInfo(platform, "original"); //DebugPlatformInfo(currentPlatform, "final"); // Add some spacing between platforms at random int spacing = rand() % 2; if (spacing == 1) { float amount = (float)(rand() % ((maxSpacing - minSpacing) * maxSpacing)) / (maxSpacing * 1.0f) + minSpacing; currentPlatform.minZ -= amount; currentPlatform.maxZ -= amount; currentPlatform.centerZ -= amount; } currentPlatform.effect = SetPlatformEffect(); //Decrease cooldowns curSpeedPlatformCD--; curFuelLossPlatformCD--; curFuelPlatformCD--; curDeathPlatformCD--; curLifePlatformCD--; platforms.push_back(currentPlatform); // Add helper platforms at random int helper = rand() % 2; if (helper == 1) { GenerateHelperPlatform(currentPlatform); } } void SkyRoads::GenerateHelperPlatform(Platform parent) { //printf("Generating helper platform!\n"); float dirOffset; if (parent.laneOffset == 0) { int random = rand() % 2; if (random == 0) { dirOffset = -0.5f; } else { dirOffset = 0.5f; } } else if (parent.laneOffset == -1) { dirOffset = 0.5f; } else { dirOffset = -0.5f; } Platform helper = SetPlatformLimits(parent, true, parent.laneOffset + dirOffset); helper.isHelper = true; helper.lane = parent.lane + (int)dirOffset * 2; // Spawn the helper to the center of the new platform helper.minZ += parent.centerZ; helper.maxZ += parent.centerZ; helper.centerZ = parent.centerZ; //DebugPlatformInfo(helper, "final HELPER"); platforms.push_back(helper); } SkyRoads::Platform SkyRoads::SetPlatformLimits(Platform platform, bool helper, float offset) { Platform curPlat; if (!helper) { curPlat.scaleZ = (float)(rand() % ((maxPlatformScaleZ - minPlatformScaleZ) * maxPlatformScaleZ)) / (maxPlatformScaleZ * 1.0f) + minPlatformScaleZ; } else { curPlat.scaleZ = (float)(rand() % ((maxHelperScaleZ - minHelperScaleZ) * maxHelperScaleZ)) / (maxHelperScaleZ * 1.0f) + minHelperScaleZ; } curPlat.maxX *= platformScaleX; curPlat.minX *= platformScaleX; curPlat.maxY *= platformScaleY; curPlat.minY *= platformScaleY; curPlat.maxZ *= curPlat.scaleZ; curPlat.minZ *= curPlat.scaleZ; curPlat.maxX += offset; curPlat.minX += offset; curPlat.minY -= 0.1f; curPlat.maxY -= 0.1f; curPlat.centerX += offset; curPlat.centerY -= 0.1f; curPlat.laneOffset = offset; curPlat.lane = platform.lane; // TODO: this is different for helper platforms return curPlat; } void SkyRoads::RenderPlatforms() { for (int i = 0; i < platforms.size(); ++i) { glm::mat4 modelMatrix = glm::mat4(1); modelMatrix = glm::translate(modelMatrix, glm::vec3(platforms[i].centerX, platforms[i].centerY, platforms[i].centerZ)); modelMatrix = glm::scale(modelMatrix, glm::vec3(platformScaleX, platformScaleY, platforms[i].scaleZ)); if (platforms[i].isPlayerAbove) { RenderSimpleMesh(meshes["LeActiveCube"], shaders["ShaderSkyRoads"], modelMatrix); } else if (platforms[i].effect == 1) { RenderSimpleMesh(meshes["LeSpeedCube"], shaders["ShaderSkyRoads"], modelMatrix); } else if (platforms[i].effect == 2) { RenderSimpleMesh(meshes["LeFuelLossCube"], shaders["ShaderSkyRoads"], modelMatrix); } else if (platforms[i].effect == 3) { RenderSimpleMesh(meshes["LeFuelCube"], shaders["ShaderSkyRoads"], modelMatrix); } else if (platforms[i].effect == 4) { RenderSimpleMesh(meshes["LeDeathCube"], shaders["ShaderSkyRoads"], modelMatrix); } else if (platforms[i].effect == 5) { RenderSimpleMesh(meshes["LeCube"], shaders["LifePlatform"], modelMatrix); } else { RenderSimpleMesh(meshes["LeCube"], shaders["ShaderSkyRoads"], modelMatrix); } } } void SkyRoads::MovePlatforms(float deltaTime) { removePlatforms.clear(); for (int i = 0; i < platforms.size(); ++i) { platforms[i].minZ += deltaTime * speedZ; platforms[i].maxZ += deltaTime * speedZ; platforms[i].centerZ += deltaTime * speedZ; // When the platform is coming close enough to the player, generate a new one if (platforms[i].minZ > distanceForBackup && !platforms[i].createdBackup && !platforms[i].isHelper) { platforms[i].createdBackup = true; GenerateNewPlatforms(platforms[i]); } // When the platform goes completely off screen, mark it for deletion if (platforms[i].minZ > 5) { removePlatforms.push_back(i); } } } void SkyRoads::RemovePlatforms() { int err = 0; for (int i = 0; i < removePlatforms.size(); ++i) { int index = removePlatforms[i] - err; platforms.erase(platforms.begin() + index); err++; //printf("The number of platforms remaining: %ld!\n", platforms.size()); } } void SkyRoads::RenderPlayer(glm::vec3 axis) { glm::mat4 modelMatrix = glm::mat4(1); modelMatrix = glm::translate(modelMatrix, glm::vec3(player.posX, player.posY, player.posZ)); modelMatrix = glm::translate(modelMatrix, glm::vec3(0, 0.130f, 0)); modelMatrix = glm::scale(modelMatrix, glm::vec3(0.25f, 0.25f, 0.25f)); modelMatrix = glm::rotate(modelMatrix, rotateX, axis); RenderSimpleMesh(meshes["sphere"], shaders["Player"], modelMatrix); } void SkyRoads::RenderHearts() { for (int i = 0; i < livesRemaining; ++i) { glm::mat4 modelMatrix = glm::mat4(1); modelMatrix = glm::translate(modelMatrix, livesPosition[i]); modelMatrix = glm::scale(modelMatrix, glm::vec3(0.1f, 0.1f, 0.1f)); RenderSimpleMesh(meshes["LeHeart"], shaders["UITest"], modelMatrix); } } void SkyRoads::ManageSpeedBuff(float deltaTime) { if (speedPlatformDuration > 0) { speedPlatformDuration -= deltaTime; if (aspectX < 90) { aspectX += deltaTime * 100; // TODO: do this over a period of a few seconds } if (rotateSpeedX < 1.0f) { rotateSpeedX += deltaTime * 2; } } else if (!reverseValues) { reverseValues = true; speedZ = previousSpeedZ; aspectX = previousAspect; rotateSpeedX = previousRotateSpeed; } } int SkyRoads::CheckPlayerAbovePlatformXZ() { bool abovePlatform = false; int index = -1; for (int i = 0; i < platforms.size(); ++i) { if (abovePlatform) { platforms[i].isPlayerAbove = false; } else { if (player.posX >= platforms[i].minX && player.posX <= platforms[i].maxX) { if (player.posZ >= platforms[i].minZ && player.posZ <= platforms[i].maxZ) { abovePlatform = true; index = i; } else platforms[i].isPlayerAbove = false; } else { platforms[i].isPlayerAbove = false; } } } return index; } void SkyRoads::ApplyPlatformEffect(int index) { platforms[index].appliedEffect = true; if (platforms[index].effect == 1 && speedPlatformDuration <= 0) { previousSpeedZ = speedZ; previousAspect = aspectX; previousRotateSpeed = rotateSpeedX; reverseValues = false; speedZ = platformMaxSpeedZ; speedPlatformDuration = 5.0f; } else if (platforms[index].effect == 1 && speedPlatformDuration > 0) { speedPlatformDuration = 5.0f; } else if (platforms[index].effect == 2) { fuel -= maxFuel / 10; if (fuel <= 0) { fuel = 0; } } else if (platforms[index].effect == 3) { //TODO: KEEP CHANGING THIS AS MORE PLATFORM TYPES ARE ADDED fuel += maxFuel / 3; if (fuel > maxFuel) { fuel = maxFuel; } } else if (platforms[index].effect == 4) { //TODO: KEEP CHANGING THIS AS MORE PLATFORM TYPES ARE ADDED livesRemaining--; ResetPlayerPosition(); } else if (platforms[index].effect == 5) { livesRemaining++; } } void SkyRoads::DebugPlatformInfo(Platform curPlat, char* specifier) { printf("The %s limits are: x: (%.2f %.2f), y(%.2f, %.2f), z(%.2f, %.2f) and centerZ: %.2f\n", specifier, curPlat.minX, curPlat.maxX, curPlat.minY, curPlat.maxY, curPlat.minZ, curPlat.maxZ, curPlat.centerZ); } void SkyRoads::ResetPlayerPosition() { player.posX = 0; player.posY = 2; accY = 0; freshReset = true; if (fuel < maxFuel / 3) fuel = maxFuel / 3; } int SkyRoads::SetPlatformEffect() { int chance; int effect = 0; bool setEffect = false; if (curSpeedPlatformCD <= 0) { chance = rand() % 100; if (chance < speedPlatformChance) { curSpeedPlatformCD = speedPlatformCD; effect = 1; setEffect = true; } } if (curFuelLossPlatformCD <= 0 && !setEffect) { chance = rand() % 100; if (chance < fuelLossPlatformChance) { curFuelLossPlatformCD = fuelLossPlatformCD; effect = 2; setEffect = true; } } if (curFuelPlatformCD <= 0 && !setEffect) { printf("Rolling for FUEL!\n"); chance = rand() % 100; if (chance < fuelPlatformChance) { curFuelPlatformCD = fuelPlatformCD; effect = 3; setEffect = true; } } if (curDeathPlatformCD <= 0 && !setEffect) { printf("Rolling for DEATH!\n"); chance = rand() % 100; if (chance < deathPlatformChance) { curDeathPlatformCD = deathPlatformCD; effect = 4; setEffect = true; } } if (curLifePlatformCD <= 0 && !setEffect && livesRemaining < 3) { printf("Rolling for DEATH!\n"); chance = rand() % 100; if (chance < lifePlatformChance) { curLifePlatformCD = lifePlatformCD; effect = 5; setEffect = true; } } return effect; }examples/plane-game/Gap.cpp #include "Gap.hpp" #include void Gap::initializeGL(GLuint program) { for(auto wallObstacle : m_wallObstacles) { wallObstacle->initializeGL(program); } } void Gap::paintGL() { for(auto wallObstacle : m_wallObstacles) { wallObstacle->paintGL(); } } void Gap::terminateGL() { for(auto wallObstacle : m_wallObstacles) { wallObstacle->terminateGL(); } } void Gap::update(float deltaTime) { glm::vec2 translation{0}; for(auto wallObstacle : m_wallObstacles) { wallObstacle->update(deltaTime); translation.x += wallObstacle->m_translation.x; translation.y += wallObstacle->m_translation.y; } m_translation.x = translation.x / 2.0f; m_translation.y = translation.y / 2.0f; } void Gap::setupGap(glm::vec2 gapTranslation, float gapWidth, float gapHeight) { m_gapWidth = gapWidth; m_gapHeight = gapHeight; const glm::vec2 rightTranslation{ gapTranslation.x + m_gapWidth/2.0f + std::abs(1.0f - (gapTranslation.x + m_gapWidth/2.0f))/2.0f, gapTranslation.y }; const glm::vec2 leftTranslation{ gapTranslation.x - m_gapWidth/2.0f - std::abs(-1.0f - (gapTranslation.x - m_gapWidth/2.0f))/2.0f, gapTranslation.y }; if(m_wallObstacles[0] == nullptr) { m_wallObstacles[0] = new WallObstacle(rightTranslation, glm::vec2{std::abs(1.0f - rightTranslation.x), m_gapHeight}); } else { m_wallObstacles[0]->setTranslation(rightTranslation); m_wallObstacles[0]->setScale(glm::vec2{std::abs(1.0f - rightTranslation.x), m_gapHeight}); } if(m_wallObstacles[1] == nullptr) { m_wallObstacles[1] = new WallObstacle(leftTranslation, glm::vec2{std::abs(-1.0f - leftTranslation.x), m_gapHeight}); } else { m_wallObstacles[1]->setTranslation(leftTranslation); m_wallObstacles[1]->setScale(glm::vec2{std::abs(-1.0f - leftTranslation.x), m_gapHeight}); } } bool Gap::belowScreen() { float yRight = m_wallObstacles[0]->getTranslation().y + m_wallObstacles[0]->getScale().y; float yLeft = m_wallObstacles[1]->getTranslation().y + m_wallObstacles[1]->getScale().y; return std::max(yRight, yLeft) < -1.0; } flowzario/mesoBasic # include "PDInits_Random.hpp" // ------------------------------------------------------------------------- // Constructor... // ------------------------------------------------------------------------- Random::Random(const GetPot& p, vector& rin, vector& vin, vector& radin) : r(rin), v(vin), rad(radin) { N = p("PDApp/N",1); nx = p("Domain/nx",5); ny = p("Domain/ny",5); nz = p("Domain/nz",5); dx = p("Domain/dx",1.0); dy = p("Domain/dy",1.0); dz = p("Domain/dz",1.0); vscl = p("PDApp/initial_condition/vscl",0.0); pradii = p("PDApp/pradii",1.0); Lx = nx*dx; Ly = ny*dy; Lz = nz*dz; // check to see if this is a thin film simulation pfApp = p("PFApp/type","CHBD"); thickness = p("PFApp/thickness",2); if (pfApp == "CHBDThinFilm") thinFilm = true; else thinFilm = false; if (thinFilm) Lz -= 2.0*(dz*(double)thickness + 1.5*pradii); } // ------------------------------------------------------------------------- // Destructor... // ------------------------------------------------------------------------- Random::~Random() { } // ------------------------------------------------------------------------- // Function to calculate i.c.: // ------------------------------------------------------------------------- void Random::icFunc() { // initialize particle positions at random locations in the domain for (int i=0; i 0.0) { for (int i=0; iTraceCollier/tmbind.cpp /* * MIT License * * Copyright (c) 2017 * * 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 "tmbind.h" /** @file tmbind.cpp * @brief Implementation file for the tmBind object. */ /** @brief Constructor for a tmBind object. * * @param id unsigned. The positional bind number. The first bind in a SQL statement is bind 0, and so on. * @param name std::string. The extracted bind variable name. May be wrapped in double quotes, maybe not. * */ tmBind::tmBind(unsigned id, string name) { mBindId = id; mBindLineNumber = 0; mBindType=0; mBindValue = ""; mBindName = name; } /** @brief Destructor for a tmBind object. */ tmBind::~tmBind() { //dtor } /** @brief Allows a tmBind to be streamed to an ostream. * * @param out ostream&. The stream to output tmBind details to. * @param bind tmBind&. The tmBind to be streamed. * @return ostream&. The same as the input stream. * * This function/operator allows a tmBind to stream itself * out to an ostream. */ ostream &operator<<(ostream &out, const tmBind &bind) { out << endl << "BindID: " << bind.mBindId << endl << "Bind Line Number: " << bind.mBindLineNumber << endl << "Bind Type: " << bind.mBindType << endl << "Bind Name: " << bind.mBindName << endl << "Bind Value: " << bind.mBindValue << endl; return out; } ktos/wristband #include "ota.hpp" void onOtaStarted() { //msgBig("OTA"); } void onOtaProgress(unsigned int progress, unsigned int total) { int percentage = (progress / (total / 100)); drawProgressBar(10, 30, 120, 15, percentage, TFT_WHITE, TFT_GREENYELLOW); }// -*- C++ -*- // // Copyright 2009 - 2012. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file COPYING or copy at // http://www.boost.org/LICENSE_1_0.txt) #define BOOST_TEST_DYN_LINK #define SPATIAL_ENABLE_ASSERT // detect interal issues that should not occur #include #include "../../src/region_iterator.hpp" #include "spatial_test_fixtures.hpp" BOOST_AUTO_TEST_CASE( test_open_bounds ) { int2 l(1, 1); int2 h(3, 3); int2 x(2, 1); int2 y(3, 2); pointset_fix fix(0); // Checking this compiles open_bounds > bounds = make_open_bounds(fix.container, l, h); BOOST_CHECK(bounds(0, 2, l) == below); BOOST_CHECK(bounds(1, 2, l) == below); BOOST_CHECK(bounds(0, 2, h) == above); BOOST_CHECK(bounds(1, 2, h) == above); BOOST_CHECK(bounds(0, 2, x) == matching); BOOST_CHECK(bounds(1, 2, x) == below); BOOST_CHECK(bounds(0, 2, y) == above); BOOST_CHECK(bounds(1, 2, y) == matching); } BOOST_AUTO_TEST_CASE( test_bounds ) { int2 l(1, 1); int2 h(3, 3); int2 x(2, 0); int2 y(3, 2); int2 z(0, 0); pointset_fix fix(0); // Checking this compiles bounds > bounds = make_bounds(fix.container, l, h); BOOST_CHECK(bounds(0, 2, l) == matching); BOOST_CHECK(bounds(1, 2, l) == matching); BOOST_CHECK(bounds(0, 2, h) == above); BOOST_CHECK(bounds(1, 2, h) == above); BOOST_CHECK(bounds(0, 2, x) == matching); BOOST_CHECK(bounds(1, 2, x) == below); BOOST_CHECK(bounds(0, 2, y) == above); BOOST_CHECK(bounds(1, 2, y) == matching); BOOST_CHECK(bounds(0, 2, z) == below); BOOST_CHECK(bounds(1, 2, z) == below); } BOOST_AUTO_TEST_CASE( test_closed_bounds ) { int2 l(1, 1); int2 h(3, 3); int2 x(2, 0); int2 y(4, 2); int2 z(0, 0); int2 w(4, 4); pointset_fix fix(0); // Checking this compiles closed_bounds > bounds = make_closed_bounds(fix.container, l, h); BOOST_CHECK(bounds(0, 2, l) == matching); BOOST_CHECK(bounds(1, 2, l) == matching); BOOST_CHECK(bounds(0, 2, h) == matching); BOOST_CHECK(bounds(1, 2, h) == matching); BOOST_CHECK(bounds(0, 2, x) == matching); BOOST_CHECK(bounds(1, 2, x) == below); BOOST_CHECK(bounds(0, 2, y) == above); BOOST_CHECK(bounds(1, 2, y) == matching); BOOST_CHECK(bounds(0, 2, z) == below); BOOST_CHECK(bounds(1, 2, z) == below); BOOST_CHECK(bounds(0, 2, w) == above); BOOST_CHECK(bounds(1, 2, w) == above); } template inline bool match_all(const Rank& rank, const Key& key, const Pred& pred) { dimension_type d = 0; for (; d < rank() && pred(d, rank(), key) == matching; ++d); return (d == rank()); } BOOST_AUTO_TEST_CASE_TEMPLATE( test_overlap_bounds, Tp, every_quad ) { Tp fix(0); { // test for llhh_layout_tag quad a(0, 0, 2, 2); overlap_bounds bounds = make_overlap_bounds(fix.container, a); // A region must overlap itself (all it's element must match) BOOST_CHECK(match_all(fix.container.rank(), a, bounds)); // A region must overlap a point at its center quad p(1, 1, 1, 1); BOOST_CHECK(match_all(fix.container.rank(), p, bounds)); // A region must overlap a larger region than itself quad b(-1, -1, 3, 3); BOOST_CHECK(match_all(fix.container.rank(), b, bounds)); // A region must *not* overlap another region whose corner only contact quad c(-1, -1, 0, 3); BOOST_CHECK(!match_all(fix.container.rank(), c, bounds)); quad d(-1, -1, 3, 0); BOOST_CHECK(!match_all(fix.container.rank(), d, bounds)); quad e(2, -1, 3, 3); BOOST_CHECK(!match_all(fix.container.rank(), e, bounds)); quad f(-1, 2, 3, 3); BOOST_CHECK(!match_all(fix.container.rank(), f, bounds)); } { // test for lhlh_layout_tag quad a(0, 2, 0, 2); overlap_bounds bounds = make_overlap_bounds(fix.container, a, lhlh_layout); // A region must overlap itself (all it's element must match) BOOST_CHECK(match_all(fix.container.rank(), a, bounds)); // A region must overlap a point at its center quad p(1, 1, 1, 1); BOOST_CHECK(match_all(fix.container.rank(), p, bounds)); // A region must overlap a larger region than itself quad b(-1, 3, -1, 3); BOOST_CHECK(match_all(fix.container.rank(), b, bounds)); // A region must *not* overlap another region whose corner only contact quad c(-1, 0, -1, 3); BOOST_CHECK(!match_all(fix.container.rank(), c, bounds)); quad d(-1, 3, -1, 0); BOOST_CHECK(!match_all(fix.container.rank(), d, bounds)); quad e(2, 3, -1, 3); BOOST_CHECK(!match_all(fix.container.rank(), e, bounds)); quad f(-1, 3, 2, 3); BOOST_CHECK(!match_all(fix.container.rank(), f, bounds)); } { // test for hhll_layout_tag quad a(2, 2, 0, 0); overlap_bounds bounds = make_overlap_bounds(fix.container, a, hhll_layout); // A region must overlap itself (all it's element must match) BOOST_CHECK(match_all(fix.container.rank(), a, bounds)); // A region must overlap a point at its center quad p(1, 1, 1, 1); BOOST_CHECK(match_all(fix.container.rank(), p, bounds)); // A region must overlap a larger region than itself quad b(3, 3, -1, -1); BOOST_CHECK(match_all(fix.container.rank(), b, bounds)); // A region must *not* overlap another region whose corner only contact quad c(0, 3, -1, -1); BOOST_CHECK(!match_all(fix.container.rank(), c, bounds)); quad d(3, 0, -1, -1); BOOST_CHECK(!match_all(fix.container.rank(), d, bounds)); quad e(3, 3, 2, -1); BOOST_CHECK(!match_all(fix.container.rank(), e, bounds)); quad f(3, 3, -1, 2); BOOST_CHECK(!match_all(fix.container.rank(), f, bounds)); } { // test for hlhl_layout_tag quad a(2, 0, 2, 0); overlap_bounds bounds = make_overlap_bounds(fix.container, a, hlhl_layout); // A region must overlap itself (all it's element must match) BOOST_CHECK(match_all(fix.container.rank(), a, bounds)); // A region must overlap a point at its center quad p(1, 1, 1, 1); BOOST_CHECK(match_all(fix.container.rank(), p, bounds)); // A region must overlap a larger region than itself quad b(3, -1, 3, -1); BOOST_CHECK(match_all(fix.container.rank(), b, bounds)); // A region must *not* overlap another region whose corner only contact quad c(0, -1, 3, -1); BOOST_CHECK(!match_all(fix.container.rank(), c, bounds)); quad d(3, -1, 0, -1); BOOST_CHECK(!match_all(fix.container.rank(), d, bounds)); quad e(3, 2, 3, -1); BOOST_CHECK(!match_all(fix.container.rank(), e, bounds)); quad f(3, -1, 3, 2); BOOST_CHECK(!match_all(fix.container.rank(), f, bounds)); } } BOOST_AUTO_TEST_CASE_TEMPLATE( test_enclosed_bounds, Tp, every_quad ) { Tp fix(0); { // test for llhh_layout_tag quad a(0, 0, 3, 3); enclosed_bounds bounds = make_enclosed_bounds(fix.container, a); // A region must enclose itself (all it's element must match) BOOST_CHECK(match_all(fix.container.rank(), a, bounds)); // A region must enclose a point at its center quad p(1, 1, 1, 1); BOOST_CHECK(match_all(fix.container.rank(), p, bounds)); // A region must enclose a smaller region than itself quad b(1, 1, 2, 2); BOOST_CHECK(match_all(fix.container.rank(), b, bounds)); // A region must *not* enclose another larger region quad c(-1, 0, 3, 3); BOOST_CHECK(!match_all(fix.container.rank(), c, bounds)); quad d(0, -1, 3, 3); BOOST_CHECK(!match_all(fix.container.rank(), d, bounds)); quad e(0, 0, 4, 3); BOOST_CHECK(!match_all(fix.container.rank(), e, bounds)); quad f(0, 0, 3, 4); BOOST_CHECK(!match_all(fix.container.rank(), f, bounds)); } { // test for lhlh_layout_tag quad a(0, 3, 0, 3); enclosed_bounds bounds = make_enclosed_bounds(fix.container, a, lhlh_layout); // A region must enclose itself (all it's element must match) BOOST_CHECK(match_all(fix.container.rank(), a, bounds)); // A region must enclose a point at its center quad p(1, 1, 1, 1); BOOST_CHECK(match_all(fix.container.rank(), p, bounds)); // A region must enclose a smaller region than itself quad b(1, 2, 1, 2); BOOST_CHECK(match_all(fix.container.rank(), b, bounds)); // A region must *not* enclose another larger region quad c(-1, 3, 0, 3); BOOST_CHECK(!match_all(fix.container.rank(), c, bounds)); quad d(0, 3, -1, 3); BOOST_CHECK(!match_all(fix.container.rank(), d, bounds)); quad e(0, 4, 0, 3); BOOST_CHECK(!match_all(fix.container.rank(), e, bounds)); quad f(0, 3, 0, 4); BOOST_CHECK(!match_all(fix.container.rank(), f, bounds)); } { // test for hhll_layout_tag quad a(3, 3, 0, 0); enclosed_bounds bounds = make_enclosed_bounds(fix.container, a, hhll_layout); // A region must enclose itself (all it's element must match) BOOST_CHECK(match_all(fix.container.rank(), a, bounds)); // A region must enclose a point at its center quad p(1, 1, 1, 1); BOOST_CHECK(match_all(fix.container.rank(), p, bounds)); // A region must enclose a smaller region than itself quad b(2, 2, 1, 1); BOOST_CHECK(match_all(fix.container.rank(), b, bounds)); // A region must *not* enclose another larger region quad c(3, 3, -1, 0); BOOST_CHECK(!match_all(fix.container.rank(), c, bounds)); quad d(3, 3, 0, -1); BOOST_CHECK(!match_all(fix.container.rank(), d, bounds)); quad e(4, 3, 0, 0); BOOST_CHECK(!match_all(fix.container.rank(), e, bounds)); quad f(3, 4, 0, 0); BOOST_CHECK(!match_all(fix.container.rank(), f, bounds)); } { // test for hlhl_layout_tag quad a(3, 0, 3, 0); enclosed_bounds bounds = make_enclosed_bounds(fix.container, a, hlhl_layout); // A region must enclose itself (all it's element must match) BOOST_CHECK(match_all(fix.container.rank(), a, bounds)); // A region must enclose a point at its center quad p(1, 1, 1, 1); BOOST_CHECK(match_all(fix.container.rank(), p, bounds)); // A region must enclose a smaller region than itself quad b(2, 1, 2, 1); BOOST_CHECK(match_all(fix.container.rank(), b, bounds)); // A region must *not* enclose another larger region quad c(3, -1, 3, 0); BOOST_CHECK(!match_all(fix.container.rank(), c, bounds)); quad d(3, 0, 3, -1); BOOST_CHECK(!match_all(fix.container.rank(), d, bounds)); quad e(4, 0, 3, 0); BOOST_CHECK(!match_all(fix.container.rank(), e, bounds)); quad f(3, 0, 4, 0); BOOST_CHECK(!match_all(fix.container.rank(), f, bounds)); } } BOOST_AUTO_TEST_CASE_TEMPLATE( test_region_basics, Tp, every_quad ) { Tp fix(0); quad l(0, 0, 0, 0); quad h(1, 1, 1, 1); { region_iterator a; a.node = fix.container.end().node; region_iterator b(a); region_iterator c; c = a; region_iterator_pair p, q(a, b); region_iterator_pair r, s(c, c), t(p); BOOST_CHECK(a == b); BOOST_CHECK(!(a != c)); typename Tp::container_type::iterator i = a; BOOST_CHECK(i == a); } { open_region_iterator a; a.node = fix.container.end().node; open_region_iterator b(a); open_region_iterator c; c = a; open_region_iterator_pair p, q(a, b); open_region_iterator_pair r, s(c, c), t(p); BOOST_CHECK(a == b); BOOST_CHECK(!(a != c)); typename Tp::container_type::iterator i = a; BOOST_CHECK(i == a); } { closed_region_iterator a; a.node = fix.container.end().node; closed_region_iterator b(a); closed_region_iterator c; c = a; closed_region_iterator_pair p, q(a, b); closed_region_iterator_pair r, s(c, c), t(p); BOOST_CHECK(a == b); BOOST_CHECK(!(a != c)); typename Tp::container_type::iterator i = a; BOOST_CHECK(i == a); } { overlap_region_iterator a; a.node = fix.container.end().node; overlap_region_iterator b(a); overlap_region_iterator c; c = a; overlap_region_iterator_pair p, q(a, b); overlap_region_iterator_pair r, s(c, c), t(p); BOOST_CHECK(a == b); BOOST_CHECK(!(a != c)); typename Tp::container_type::iterator i = a; BOOST_CHECK(i == a); } { enclosed_region_iterator a; a.node = fix.container.end().node; enclosed_region_iterator b(a); enclosed_region_iterator c; c = a; enclosed_region_iterator_pair p, q(a, b); enclosed_region_iterator_pair r, s(c, c), t(p); BOOST_CHECK(a == b); BOOST_CHECK(!(a != c)); typename Tp::container_type::iterator i = a; BOOST_CHECK(i == a); } } BOOST_AUTO_TEST_CASE_TEMPLATE( test_region_deference, Tp, double6_maps ) { Tp fix(1, same()); double6 l; std::fill(l.begin(), l.end(), 0.0); double6 h; std::fill(h.begin(), h.end(), 1.0); region_iterator a(fix.container, make_bounds(fix.container, l, h), fix.container.begin()); region_iterator b(fix.container, make_bounds(fix.container, l, h), fix.container.begin()); BOOST_CHECK((*a).first == fix.container.begin()->first); (*a).second = "some string"; BOOST_CHECK(a->first == fix.container.begin()->first); a->second = "some other string"; BOOST_CHECK((*b).first == fix.container.begin()->first); BOOST_CHECK(b->first == fix.container.begin()->first); BOOST_CHECK(a.dimension() == fix.container.dimension()); BOOST_CHECK(b.dimension() == fix.container.dimension()); } BOOST_AUTO_TEST_CASE_TEMPLATE( test_region_minimum, Tp, double6_sets ) { { Tp fix(100, randomize(-1, 1)); // Prove that you can find the min value with N nodes, down to 1 nodes double6 l; std::fill(l.begin(), l.end(), -0.8); // leave a few out... double6 h; std::fill(h.begin(), h.end(), 0.8); while (!fix.container.empty()) { region_iterator it = region_begin(fix.container, l, h); if (it == region_end(fix.container, l, h)) break; // Make sure it is one within [-0.8, 0.8) BOOST_CHECK(match_all(fix.container.rank(), *it, make_bounds(fix.container, l, h))); fix.container.erase(it); } } { // A tree where all elements are the same (= 100.0)! Tp fix(100, same()); double6 k; std::fill(k.begin(), k.end(), 100.0); // leave none out... while (!fix.container.empty()) { closed_region_iterator it = closed_region_begin(fix.container, k, k); BOOST_CHECK(it != closed_region_end(fix.container, k, k)); fix.container.erase(it); } } { // test at the limit: a tree with 1 element Tp fix(1, same()); double6 k; std::fill(k.begin(), k.end(), 1.0); closed_region_iterator it = closed_region_cbegin(fix.container, k, k); BOOST_CHECK(it != closed_region_end(fix.container, k, k)); } { // test at the limit: an unbalanced tree (i.e. insertions in order)! Tp fix(100, increase()); // Prove that you can find the min value with N nodes, down to 1 nodes double6 l; std::fill(l.begin(), l.end(), 20.0); // leave a few out... double6 h; std::fill(h.begin(), h.end(), 80.0); while (!fix.container.empty()) { open_region_iterator it = open_region_begin(fix.container, l, h); if (it == open_region_end(fix.container, l, h)) break; // Make sure it is one within (10, 90) BOOST_CHECK(match_all(fix.container.rank(), *it, make_open_bounds(fix.container, l, h))); fix.container.erase(it); } } { // test at the limit: an unbalanced tree (i.e. insertions in order)! Tp fix(100, decrease()); // Prove that you can find the min value with N nodes, down to 1 nodes double6 l; std::fill(l.begin(), l.end(), 20.0); // leave a few out... double6 h; std::fill(h.begin(), h.end(), 80.0); while (!fix.container.empty()) { closed_region_iterator it = closed_region_begin(fix.container, l, h); if (it == closed_region_end(fix.container, l, h)) break; // Make sure it is one within (10, 90) BOOST_CHECK(match_all(fix.container.rank(), *it, make_closed_bounds(fix.container, l, h))); fix.container.erase(it); } } } BOOST_AUTO_TEST_CASE_TEMPLATE( test_region_maximum, Tp, double6_sets ) { { Tp fix(100, randomize(-1, 1)); // Prove that you can find the max value with N nodes, down to 1 nodes double6 l; std::fill(l.begin(), l.end(), -0.8); // leave a few out... double6 h; std::fill(h.begin(), h.end(), 0.8); while (!fix.container.empty()) { region_iterator it = region_end(fix.container, l, h); --it; if (it == region_end(fix.container, l, h)) break; // Make sure it is one within [-0.8, 0.8) BOOST_CHECK(match_all(fix.container.rank(), *it, make_bounds(fix.container, l, h))); region_iterator tmp = it; ++tmp; BOOST_CHECK(tmp == region_end(fix.container, l, h)); fix.container.erase(it); } } { // A tree where all elements are the same (= 100.0)! Tp fix(100, same()); double6 k; std::fill(k.begin(), k.end(), 100.0); // leave none out... while (!fix.container.empty()) { closed_region_iterator it = closed_region_end(fix.container, k, k); BOOST_CHECK(closed_region_begin(fix.container, k, k) != it); --it; BOOST_CHECK(it != closed_region_end(fix.container, k, k)); closed_region_iterator tmp = it; ++tmp; BOOST_CHECK(tmp == closed_region_end(fix.container, k, k)); fix.container.erase(it); } } { // test at the limit: a tree with 1 element Tp fix(1, same()); double6 k; std::fill(k.begin(), k.end(), 1.0); closed_region_iterator it = closed_region_end(fix.container, k, k); --it; BOOST_CHECK(it != closed_region_end(fix.container, k, k)); } { // test at the limit: an unbalanced tree (i.e. insertions in order)! Tp fix(100, increase()); // Prove that you can find the min value with N nodes, down to 1 nodes double6 l; std::fill(l.begin(), l.end(), 20.0); // leave a few out... double6 h; std::fill(h.begin(), h.end(), 80.0); while (!fix.container.empty()) { open_region_iterator it = open_region_end(fix.container, l, h); --it; if (it == open_region_cend(fix.container, l, h)) break; // Make sure it is one within (10, 90) BOOST_CHECK(match_all(fix.container.rank(), *it, make_open_bounds(fix.container, l, h))); open_region_iterator tmp = it; ++tmp; BOOST_CHECK(tmp == open_region_cend(fix.container, l, h)); fix.container.erase(it); } } { // test at the limit: an unbalanced tree (i.e. insertions in order)! Tp fix(100, decrease()); // Prove that you can find the min value with N nodes, down to 1 nodes double6 l; std::fill(l.begin(), l.end(), 20.0); // leave a few out... double6 h; std::fill(h.begin(), h.end(), 80.0); while (!fix.container.empty()) { closed_region_iterator it = closed_region_end(fix.container, l, h); --it; if (it == closed_region_end(fix.container, l, h)) break; // Make sure it is one within (10, 90) BOOST_CHECK(match_all(fix.container.rank(), *it, make_closed_bounds(fix.container, l, h))); closed_region_iterator tmp = it; ++tmp; BOOST_CHECK(tmp == closed_region_end(fix.container, l, h)); fix.container.erase(it); } } } BOOST_AUTO_TEST_CASE_TEMPLATE( test_region_increment, Tp, double6_sets ) { { Tp fix(100, boximize(-1, 1)); // Prove that you can iterate all N nodes, down to 1 nodes double6 b; b[0] = b[1] = b[2] = -0.8; b[3] = b[4] = b[5] = 0.8; while (!fix.container.empty()) { int count_it = 0, count_re = 0; enclosed_bounds > eb = make_enclosed_bounds(fix.container, b); typename Tp::container_type::iterator it = fix.container.begin(); for (; it != fix.container.end(); ++it) { if (match_all(fix.container.rank(), *it, eb)) ++count_it; } enclosed_region_iterator re = enclosed_region_begin(fix.container, b); for (;re != enclosed_region_end(fix.container, b); ++re) { BOOST_CHECK(match_all(fix.container.rank(), *re, eb)); ++count_re; } BOOST_CHECK_EQUAL(count_it, count_re); fix.container.erase(fix.container.begin()); } } { // A tree where all elements are the same (= 100.0)! Tp fix(100, same()); // Prove that you can iterate all N nodes, down to 1 nodes double6 b; b[0] = b[1] = b[2] = 99.0; b[3] = b[4] = b[5] = 101.0; while (!fix.container.empty()) { BOOST_CHECK(std::distance(enclosed_region_begin(fix.container, b), enclosed_region_end(fix.container, b)) == static_cast(fix.container.size())); fix.container.erase(fix.container.begin()); } } { // test at the limit: a tree with 1 element with point-box Tp fix(1, same()); // Prove that you can iterate all N nodes, down to 1 nodes double6 b; b[0] = b[1] = b[2] = b[3] = b[4] = b[5] = 1.0; enclosed_region_iterator i = enclosed_region_begin(fix.container, b, lhlh_layout), j = i; BOOST_CHECK(i != enclosed_region_end(fix.container, b, lhlh_layout)); BOOST_CHECK(++i == enclosed_region_end(fix.container, b, lhlh_layout)); BOOST_CHECK(j++ != enclosed_region_end(fix.container, b, lhlh_layout)); BOOST_CHECK(j == enclosed_region_end(fix.container, b, lhlh_layout)); } { // test at the limit: an unbalanced tree (i.e. insertions in order)! Tp fix(100, increase()); // Prove that you can iterate all N nodes, down to 1 nodes double6 l; l[0] = l[1] = l[2] = l[3] = l[4] = l[5] = -20.0; double6 h; h[0] = h[1] = h[2] = h[3] = h[4] = h[5] = 60.0; while (!fix.container.empty()) { int count_it = 0, count_re = 0; open_bounds > orb = make_open_bounds(fix.container, l, h); typename Tp::container_type::iterator it = fix.container.begin(); for (; it != fix.container.end(); ++it) { if (match_all(fix.container.rank(), *it, orb)) ++count_it; } open_region_iterator re = open_region_begin(fix.container, l, h); for (;re != open_region_end(fix.container, l, h); ++re) { BOOST_CHECK(match_all(fix.container.rank(), *re, orb)); ++count_re; } BOOST_CHECK_EQUAL(count_it, count_re); fix.container.erase(fix.container.begin()); } } { // test at the limit: an unbalanced tree (i.e. insertions in order)! Tp fix(100, decrease()); // Prove that you can iterate all N nodes, down to 1 nodes double6 l; l[0] = l[1] = l[2] = l[3] = l[4] = l[5] = 30.0; double6 h; h[0] = h[1] = h[2] = h[3] = h[4] = h[5] = 120.0; while (!fix.container.empty()) { int count_it = 0, count_re = 0; open_bounds > orb = make_open_bounds(fix.container, l, h); typename Tp::container_type::iterator it = fix.container.begin(); for (; it != fix.container.end(); ++it) { if (match_all(fix.container.rank(), *it, orb)) ++count_it; } open_region_iterator re = open_region_begin(fix.container, l, h); for (;re != open_region_cend(fix.container, l, h); ++re) { BOOST_CHECK(match_all(fix.container.rank(), *re, orb)); ++count_re; } BOOST_CHECK_EQUAL(count_it, count_re); fix.container.erase(fix.container.begin()); } } } BOOST_AUTO_TEST_CASE_TEMPLATE( test_region_decrement, Tp, double6_sets ) { { Tp fix(100, boximize(-1, 1)); // Prove that you can iterate all N nodes, down to 1 nodes double6 b; b[0] = b[1] = b[2] = -0.8; b[3] = b[4] = b[5] = 0.8; while (!fix.container.empty()) { int count_it = 0, count_re = 0; enclosed_bounds > eb(make_enclosed_bounds(fix.container, b)); typename Tp::container_type::iterator it = fix.container.begin(); for (; it != fix.container.end(); ++it) { if (match_all(fix.container.rank(), *it, eb)) ++count_it; } std::reverse_iterator > re(enclosed_region_end(fix.container, b)), rend(enclosed_region_begin(fix.container, b)); for (;re != rend; ++re) { BOOST_CHECK(match_all(fix.container.rank(), *re, eb)); ++count_re; } BOOST_CHECK_EQUAL(count_it, count_re); fix.container.erase(fix.container.begin()); } } { // A tree where all elements are the same (= 100.0)! Tp fix(100, same()); // Prove that you can iterate all N nodes, down to 1 nodes double6 b; b[0] = b[1] = b[2] = 99.0; b[3] = b[4] = b[5] = 101.0; while (!fix.container.empty()) { std::reverse_iterator > begin(enclosed_region_end(fix.container, b)), end(enclosed_region_begin(fix.container, b)); BOOST_CHECK(std::distance(begin, end) == static_cast(fix.container.size())); fix.container.erase(fix.container.begin()); } } { // test at the limit: a tree with 1 element with point-box Tp fix(1, same()); // Prove that you can iterate all N nodes, down to 1 nodes double6 b; b[0] = b[1] = b[2] = b[3] = b[4] = b[5] = 1.0; enclosed_region_iterator i = enclosed_region_end(fix.container, b, lhlh_layout), j = i; BOOST_CHECK(i != enclosed_region_begin(fix.container, b, lhlh_layout)); BOOST_CHECK(--i == enclosed_region_begin(fix.container, b, lhlh_layout)); BOOST_CHECK(j-- != enclosed_region_begin(fix.container, b, lhlh_layout)); BOOST_CHECK(j == enclosed_region_begin(fix.container, b, lhlh_layout)); } { // test at the limit: an unbalanced tree (i.e. insertions in order)! Tp fix(100, increase()); // Prove that you can iterate all N nodes, down to 1 nodes double6 l; l[0] = l[1] = l[2] = l[3] = l[4] = l[5] = -20.0; double6 h; h[0] = h[1] = h[2] = h[3] = h[4] = h[5] = 60.0; while (!fix.container.empty()) { int count_it = 0, count_re = 0; open_bounds > orb = make_open_bounds(fix.container, l, h); typename Tp::container_type::iterator it = fix.container.begin(); for (; it != fix.container.end(); ++it) { if (match_all(fix.container.rank(), *it, orb)) ++count_it; } std::reverse_iterator > re(open_region_cend(fix.container, l, h)), rend(open_region_cbegin(fix.container, l, h)); for (;re != rend; ++re) { BOOST_CHECK(match_all(fix.container.rank(), *re, orb)); ++count_re; } BOOST_CHECK_EQUAL(count_it, count_re); fix.container.erase(--(fix.container.end())); } } { // test at the limit: an unbalanced tree (i.e. insertions in order)! Tp fix(100, decrease()); // Prove that you can iterate all N nodes, down to 1 nodes double6 l; l[0] = l[1] = l[2] = l[3] = l[4] = l[5] = 30.0; double6 h; h[0] = h[1] = h[2] = h[3] = h[4] = h[5] = 120.0; while (!fix.container.empty()) { int count_it = 0, count_re = 0; open_bounds > orb = make_open_bounds(fix.container, l, h); typename Tp::container_type::iterator it = fix.container.begin(); for (; it != fix.container.end(); ++it) { if (match_all(fix.container.rank(), *it, orb)) ++count_it; } std::reverse_iterator > re(open_region_cend(fix.container, l, h)), rend(open_region_cbegin(fix.container, l, h)); for (;re != rend; ++re) { BOOST_CHECK(match_all(fix.container.rank(), *re, orb)); ++count_re; } BOOST_CHECK_EQUAL(count_it, count_re); fix.container.erase(fix.container.begin()); } } } CmptAdam/ProjectIOGraphics.cpp /* * Copyright 2013 Cepheid * * 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 "Graphics.hpp" #include #include #include "Common.hpp" #include "Utility.hpp" #include "ResourceManager.hpp" namespace io { Graphics::Graphics() { glewExperimental = GL_TRUE; glewInit(); glGenVertexArrays(1, &vertexArray); glBindVertexArray(vertexArray); glEnableVertexAttribArray(0); glEnableVertexAttribArray(1); glEnableVertexAttribArray(2); fragShader = new FragmentShader("data/fragment.glsl"); vertShader = new VertexShader("data/vertex.glsl"); shaderProgram = new ShaderProgram(); shaderProgram->setFragmentShader(fragShader); shaderProgram->setVertexShader(vertShader); shaderProgram->addBinding(0, "inVertex"); shaderProgram->addBinding(1, "inTexCoord"); shaderProgram->addBinding(2, "inColour"); shaderProgram->link(); shaderProgram->makeActive(); modelMatrixUniform = shaderProgram->getUniformLocation("inModelMatrix"); projectionMatrixUniform = shaderProgram->getUniformLocation("inProjectionMatrix"); viewMatrixUniform = shaderProgram->getUniformLocation("inViewMatrix"); texUniform = shaderProgram->getUniformLocation("inTexture"); setMatrixMode(MatrixMode::MODEL); loadIdentity(); setMatrixMode(MatrixMode::VIEW); loadIdentity(); setMatrixMode(MatrixMode::PROJECTION); loadIdentity(); //ortho(-8, 8, -8, 8, 0, 0); frustum(-(1 + ((3.0 / 4.0) / 2.0)), 1 + ((3.0 / 4.0) / 2.0), -1, 1, 1, 512); setMatrixMode(MatrixMode::MODEL); ResourceManager* rm = ResourceManager::getInstance(); floorMesh = rm->getResource("data/model.obj")->toOBJModel()->compose(); wallMesh = rm->getResource("data/wall.obj")->toOBJModel()->compose(); ceilingMesh = rm->getResource("data/ceiling.obj")->toOBJModel()->compose(); font = rm->getResource("data/DejaVuSansMono.ttf")->toFont(); if (!font) { // Throw an error; throw std::runtime_error("Graphics::Graphics(): Could not load font."); } } Graphics::~Graphics() { shaderProgram->makeInactive(); shaderProgram->unlink(); shaderProgram->setFragmentShader(nullptr); shaderProgram->setVertexShader(nullptr); delete shaderProgram; delete vertShader; delete fragShader; glDisableVertexAttribArray(vertexArray); glBindVertexArray(0); glDeleteVertexArrays(1, &vertexArray); delete ceilingMesh; delete floorMesh; delete wallMesh; } void Graphics::drawCeilingTile(const int32_t x, const int32_t y, const uint32_t modelID) { glUniform1i(texUniform, 0); pushMatrix(); loadIdentity(); translate(x * 16.0f, 0.0f, y * 16.0f); if (ceilingMesh) { ceilingMesh->draw(); } popMatrix(); } void Graphics::drawFloorTile(const int32_t x, const int32_t y, const uint32_t modelID) { glUniform1i(texUniform, 0); pushMatrix(); loadIdentity(); translate(x * 16.0f, 0.0f, y * 16.0f); if (floorMesh) { floorMesh->draw(); } popMatrix(); } void Graphics::drawText(const std::string& text) { glEnable(GL_BLEND); glBlendFunc(GL_CONSTANT_COLOR, GL_ONE_MINUS_SRC_COLOR); font->drawText(text); glDisable(GL_BLEND); } void Graphics::drawQuad(float x, float y, float w, float h) { glUniform1i(texUniform, 0); pushMatrix(); loadIdentity(); translate(x, y, 0); popMatrix(); } void Graphics::drawWallTile(const int32_t x, const int32_t y, const Facing side, const uint32_t modelID) { glUniform1i(texUniform, 0); pushMatrix(); loadIdentity(); translate(x * 16.0f, 0.0f, y * 16.0f); switch(side) { case Facing::SOUTH: rotate(toRadians(270), 0.0f, 1.0f, 0.0f); break; case Facing::WEST: rotate(toRadians(180), 0.0f, 1.0f, 0.0f); break; case Facing::NORTH: rotate(toRadians(90), 0.0f, 1.0f, 0.0f); break; case Facing::EAST: rotate(toRadians(0), 0.0f, 1.0f, 0.0f); break; default: break; } if (wallMesh) { wallMesh->draw(); } popMatrix(); } void Graphics::pushMatrix() { matrixStack.push(getMatrix()); } void Graphics::popMatrix() { if (matrixStack.size() > 0) { setMatrix(matrixStack.top()); matrixStack.pop(); } } void Graphics::loadIdentity() { setMatrix(Matrix::identity()); } void Graphics::frustum(const float left, const float right, const float bottom, const float top, const float near, const float far) { setMatrix(getMatrix() * Matrix::frustum(left, right, bottom, top, near, far)); } void Graphics::ortho(const float left, const float right, const float bottom, const float top, const float near, const float far) { setMatrix(getMatrix() * Matrix::ortho2D(left, right, bottom, top)); } void Graphics::translate(const float x, const float y, const float z) { setMatrix(getMatrix() * Matrix::translation(x, y, z)); } void Graphics::rotate(const float angle, const float x, const float y, const float z) { setMatrix(getMatrix() * Matrix::rotation(angle, x, y, z)); } void Graphics::scale(const float x, const float y, const float z) { setMatrix(getMatrix() * Matrix::scale(x, y, z)); } const Matrix& Graphics::getMatrix() const { switch(getMatrixMode()) { case MatrixMode::MODEL: return modelMatrix; case MatrixMode::VIEW: return viewMatrix; default: break; } return projectionMatrix; } void Graphics::setMatrix(const Matrix& matrix) { switch(getMatrixMode()) { case MatrixMode::MODEL: modelMatrix = matrix; glUniformMatrix4fv(modelMatrixUniform, 1, GL_FALSE, modelMatrix.getData()); break; case MatrixMode::VIEW: viewMatrix = matrix; glUniformMatrix4fv(viewMatrixUniform, 1, GL_FALSE, viewMatrix.getData()); break; case MatrixMode::PROJECTION: projectionMatrix = matrix; glUniformMatrix4fv(projectionMatrixUniform, 1, GL_FALSE, projectionMatrix.getData()); break; } } } core/conversion/converters/impl/cumsum.cpp #include "NvInfer.h" #include "core/conversion/converters/converters.h" #include "core/conversion/tensorcontainer/TensorContainer.h" #include "core/util/prelude.h" #include "core/util/trt_util.h" #include "torch/torch.h" #include #include namespace torch_tensorrt { namespace core { namespace conversion { namespace converters { namespace impl { namespace { auto cumsum_registrations TORCHTRT_UNUSED = RegisterNodeConversionPatterns().pattern( {"aten::cumsum(Tensor self, int dim, *, int? dtype=None) -> (Tensor)", [](ConversionCtx* ctx, const torch::jit::Node* n, args& args) -> bool { auto in = args[0].ITensorOrFreeze(ctx); auto input_dims = in->getDimensions(); int dim = args[1].unwrapToInt(); TORCHTRT_CHECK( (dim >= 0 && dim < input_dims.nbDims) || (dim < 0 && (input_dims.nbDims + dim >= 0)), "Dimension out of range (expected to be in range of [" << -input_dims.nbDims << ", " << input_dims.nbDims - 1 << "], but got " << dim << ")"); if (dim < 0) { dim += input_dims.nbDims; } // Scan through each slice across summation axis and add it to the running sum auto loop = ctx->net->addLoop(); nvinfer1::ITensor* tripLimit = NULL; if (input_dims.d[dim] > 0) { torch::Tensor axis = torch::tensor(input_dims.d[dim], torch::kInt32); tripLimit = tensor_to_const(ctx, axis); } else { nvinfer1::ITensor* inpShape = ctx->net->addShape(*in)->getOutput(0); torch::Tensor dimValue = torch::tensor(dim, torch::kInt32); nvinfer1::ITensor* axis = tensor_to_const(ctx, dimValue); tripLimit = ctx->net->addGather(*inpShape, *axis, 0)->getOutput(0); } loop->addTripLimit(*tripLimit, nvinfer1::TripLimit::kCOUNT); auto iterator = loop->addIterator(*in, dim, false); auto data = iterator->getOutput(0); auto newDims = data->getDimensions(); torch::Tensor zeroValue = at::full(util::toVec(newDims), 0, torch::kFloat32); auto zeroTensor = tensor_to_const(ctx, zeroValue); auto runningSum = loop->addRecurrence(*zeroTensor); auto runningSumTensor = runningSum->getOutput(0); auto curSum = ctx->net->addElementWise(*data, *runningSumTensor, nvinfer1::ElementWiseOperation::kSUM); runningSum->setInput(1, *curSum->getOutput(0)); nvinfer1::ILoopOutputLayer* loopOut = loop->addLoopOutput(*curSum->getOutput(0), nvinfer1::LoopOutput::kCONCATENATE, dim); loopOut->setInput(1, *tripLimit); auto layer_output = ctx->AssociateValueAndTensor(n->outputs()[0], loopOut->getOutput(0)); LOG_DEBUG("Output tensor shape: " << layer_output->getDimensions()); return true; }}); } // namespace } // namespace impl } // namespace converters } // namespace conversion } // namespace core } // namespace torch_tensorrt frankbekema/am2302AM2302.cpp /* MIT License 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 "Arduino.h" #include "AM2302.h" /* Constructor int inputPin = The data pin from the AM2302 */ AM2302::AM2302(int inputPin) { pin = inputPin; lastRead = 0; } /* Function for listening for a bit change. Listens for every microsecond. int check = Value that should be checked for int tries = The amount of tries to check for Returns the amount of microsecond it took to listen for */ int AM2302::bitChangeListener(int check, int tries) { int usAmount = 0; for(int i = 0; i < tries; i++) { if(digitalRead(pin) == check) { break; } usAmount++; delayMicroseconds(1); } return usAmount; } /* Listen for a single bit */ int AM2302::listenForBit() { bitChangeListener(0, 50); bitChangeListener(1, 50); int msAmount = bitChangeListener(0, 70); if(msAmount > 28) { return 1; } else { return 0; } } /* Convert an bit array to an byte array int intArr[] = Array aan nummers die naar een byte omgezet te worden int bitLength = De lengte van de bits Returns byte*, an array of bytes that were merged from the bits */ byte* AM2302::bitArrToByteArr(int intArr[], int bitLength) { int rounded = 8 - bitLength % 8; int byteAmount; if(rounded == 8) { byteAmount = (bitLength) / 8; } else { byteAmount = (bitLength + (rounded)) / 8; } byte result[byteAmount]; for(int byte = 0; byte < byteAmount; byte++) { result[byte] = 0; for(int bit = 0; bit < 8; bit++) { result[byte] = result[byte] + (intArr[byte * 8 + bit] << (7 - bit)); } } return result; } /* Add two bytes together to one byte byte1 = Most significant byte byte byte2 = Least significant byte Returns an integer with the two merged bytes */ int AM2302::mergeBytes(byte byte1, byte byte2) { int result = 0; for(int i = 7; i >= 0; i--) { result = result + (bitRead(byte1, i) << i); } result = result << 8; for(int i = 7; i >= 0; i--) { result = result + (bitRead(byte2, i) << i); } return result; } /* Compare two bits int number1 = Number 1 that you would like to compare int number2 = Number 2 that you would like to compare int checkLength = The length of the bits you want to compare starting from the least significant bit Returns boolean based on if the bits were equal */ bool AM2302::compareBits(int number1, int number2, int checkLength) { for(int i = 0; i < checkLength; i++) { if(bitRead(number1, i) != bitRead(number2, i)) { return false; } } return true; } /* Read the temperature */ AM2302_res AM2302::read() { //Apply interval of 2 seconds if(lastRead + 2000 > millis()) { return tempData; } //Send an request for getting the bits from the sensor pinMode(pin, OUTPUT); //10 ms low digitalWrite(pin, 0); delay(10); //40 us high digitalWrite(pin, 1); delayMicroseconds(40); //Start listening for bits pinMode(pin, INPUT); //Wait 40 microseconds until the bit is low bitChangeListener(0, 40); //Wait 80 microseconds until the bit is high bitChangeListener(1, 80); //START OF RECEIVING BITS int res[40]; for(int i = 0; i < 40; i++) { res[i] = listenForBit(); } byte* byteRes = bitArrToByteArr(res, 40); AM2302_res result; result.humidity = mergeBytes(byteRes[0], byteRes[1]) / 10.0; result.temperature = mergeBytes(byteRes[2], byteRes[3]) / 10.0; result.correct = compareBits(byteRes[0] + byteRes[1] + byteRes[2] + byteRes[3], byteRes[4], 8); tempData = result; lastRead = millis(); return result; }1-10 //===----------------------------------------------------------------------===// // DuckDB // // execution/window_segment_tree.hpp // // //===----------------------------------------------------------------------===// #pragma once #include "duckdb/common/types/chunk_collection.hpp" #include "duckdb/execution/physical_operator.hpp" #include "duckdb/function/aggregate_function.hpp" namespace duckdb { class WindowSegmentTree { public: WindowSegmentTree(AggregateFunction &aggregate, TypeId result_type, ChunkCollection *input); Value Compute(index_t start, index_t end); private: void ConstructTree(); void WindowSegmentValue(index_t l_idx, index_t begin, index_t end); void AggregateInit(); Value AggegateFinal(); AggregateFunction aggregate; vector state; Vector statep; TypeId result_type; unique_ptr levels_flat_native; vector levels_flat_start; unique_ptr inputs; ChunkCollection *input_ref; static constexpr index_t TREE_FANOUT = 64; // this should cleanly divide STANDARD_VECTOR_SIZE }; } // namespace duckdb mlt/pgadmin3 ////////////////////////////////////////////////////////////////////////// // // pgAdmin III - PostgreSQL Tools // // Copyright (C) 2002 - 2013, The pgAdmin Development Team // This software is released under the PostgreSQL Licence // // xh_searchctrl.cpp - wxSearchCtrl handler // ////////////////////////////////////////////////////////////////////////// #include "pgAdmin3.h" #include "wx/wx.h" #include "ctl/xh_searchctrl.h" IMPLEMENT_DYNAMIC_CLASS(wxSearchTextCtrlXmlHandler, wxXmlResourceHandler) wxSearchTextCtrlXmlHandler::wxSearchTextCtrlXmlHandler() : wxXmlResourceHandler() { } wxObject *wxSearchTextCtrlXmlHandler::DoCreateResource() { XRC_MAKE_INSTANCE(instance, wxSearchCtrl); instance->Create(m_parentAsWindow, GetID(), GetName(), GetPosition(), GetSize(), GetStyle()); SetupWindow(instance); return instance; } bool wxSearchTextCtrlXmlHandler::CanHandle(wxXmlNode *node) { return IsOfClass(node, wxT("wxSearchCtrl")); } // Copyright © 2014 German Neuroinformatics Node (G-Node) // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted under the terms of the BSD License. See // LICENSE file in the root of the Project. // // Author: <> #ifndef NIX_NONE_H #define NIX_NONE_H #include namespace nix { typedef boost::none_t none_t; const none_t none = boost::none; } #endif // NIX_NONE_H zipated/src1000+ // Copyright 2016 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 "third_party/blink/renderer/platform/wtf/text/string_view.h" #include "third_party/blink/renderer/platform/wtf/text/atomic_string.h" #include "third_party/blink/renderer/platform/wtf/text/string_impl.h" #include "third_party/blink/renderer/platform/wtf/text/wtf_string.h" namespace WTF { StringView::StringView(const UChar* chars) : StringView(chars, chars ? LengthOfNullTerminatedString(chars) : 0) {} #if DCHECK_IS_ON() StringView::~StringView() { DCHECK(impl_); DCHECK(!impl_->HasOneRef() || impl_->IsStatic()) << "StringView does not own the StringImpl, it " "must not have the last ref."; } #endif String StringView::ToString() const { if (IsNull()) return String(); if (IsEmpty()) return g_empty_string; if (StringImpl* impl = SharedImpl()) return impl; if (Is8Bit()) return String(Characters8(), length_); return StringImpl::Create8BitIfPossible(Characters16(), length_); } AtomicString StringView::ToAtomicString() const { if (IsNull()) return g_null_atom; if (IsEmpty()) return g_empty_atom; if (StringImpl* impl = SharedImpl()) return AtomicString(impl); if (Is8Bit()) return AtomicString(Characters8(), length_); return AtomicString(Characters16(), length_); } bool EqualStringView(const StringView& a, const StringView& b) { if (a.IsNull() || b.IsNull()) return a.IsNull() == b.IsNull(); if (a.length() != b.length()) return false; if (a.Is8Bit()) { if (b.Is8Bit()) return Equal(a.Characters8(), b.Characters8(), a.length()); return Equal(a.Characters8(), b.Characters16(), a.length()); } if (b.Is8Bit()) return Equal(a.Characters16(), b.Characters8(), a.length()); return Equal(a.Characters16(), b.Characters16(), a.length()); } bool DeprecatedEqualIgnoringCaseAndNullity(const StringView& a, const StringView& b) { if (a.length() != b.length()) return false; if (a.Is8Bit()) { if (b.Is8Bit()) { return DeprecatedEqualIgnoringCase(a.Characters8(), b.Characters8(), a.length()); } return DeprecatedEqualIgnoringCase(a.Characters8(), b.Characters16(), a.length()); } if (b.Is8Bit()) { return DeprecatedEqualIgnoringCase(a.Characters16(), b.Characters8(), a.length()); } return DeprecatedEqualIgnoringCase(a.Characters16(), b.Characters16(), a.length()); } bool DeprecatedEqualIgnoringCase(const StringView& a, const StringView& b) { if (a.IsNull() || b.IsNull()) return a.IsNull() == b.IsNull(); return DeprecatedEqualIgnoringCaseAndNullity(a, b); } bool EqualIgnoringASCIICase(const StringView& a, const StringView& b) { if (a.IsNull() || b.IsNull()) return a.IsNull() == b.IsNull(); if (a.length() != b.length()) return false; if (a.Is8Bit()) { if (b.Is8Bit()) return EqualIgnoringASCIICase(a.Characters8(), b.Characters8(), a.length()); return EqualIgnoringASCIICase(a.Characters8(), b.Characters16(), a.length()); } if (b.Is8Bit()) return EqualIgnoringASCIICase(a.Characters16(), b.Characters8(), a.length()); return EqualIgnoringASCIICase(a.Characters16(), b.Characters16(), a.length()); } } // namespace WTF server/configuration/HostGuideline.hpp1-10 #ifndef HOSTGUIDELINE_HPP__ # define HOSTGUIDELINE_HPP__ #include #include "IVHostGuideline.hpp" namespace zhttpd { class HostGuideline : public IVHostGuideline { private: std::string _match; bool _deny; public: HostGuideline(std::string const& match, bool deny = false); virtual ~HostGuideline(); bool match(api::IRequest& request) const; }; } #endif // HOSTGUIDELINE_HPP__ media/base/constants.cc0 /* * libjingle * Copyright 2012 Google Inc. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "talk/media/base/constants.h" #include namespace cricket { const int kVideoCodecClockrate = 90000; const int kDataCodecClockrate = 90000; const int kDataMaxBandwidth = 30720; // bps const float kHighSystemCpuThreshold = 0.85f; const float kLowSystemCpuThreshold = 0.65f; const float kProcessCpuThreshold = 0.10f; const char kRtxCodecName[] = "rtx"; const char kRedCodecName[] = "red"; const char kUlpfecCodecName[] = "ulpfec"; const char kCodecParamAssociatedPayloadType[] = "apt"; const char kOpusCodecName[] = "opus"; const char kIsacCodecName[] = "isac"; const char kL16CodecName[] = "l16"; const char kG722CodecName[] = "g722"; const char kIlbcCodecName[] = "ilbc"; const char kPcmuCodecName[] = "pcmu"; const char kPcmaCodecName[] = "pcma"; const char kCnCodecName[] = "cn"; const char kDtmfCodecName[] = "telephone-event"; const char kG729CodecName[] = "g729"; // draft-spittka-payload-rtp-opus-03.txt const char kCodecParamPTime[] = "ptime"; const char kCodecParamMaxPTime[] = "maxptime"; const char kCodecParamMinPTime[] = "minptime"; const char kCodecParamSPropStereo[] = "sprop-stereo"; const char kCodecParamStereo[] = "stereo"; const char kCodecParamUseInbandFec[] = "useinbandfec"; const char kCodecParamUseDtx[] = "usedtx"; const char kCodecParamMaxAverageBitrate[] = "maxaveragebitrate"; const char kCodecParamMaxPlaybackRate[] = "maxplaybackrate"; const char kCodecParamSctpProtocol[] = "protocol"; const char kCodecParamSctpStreams[] = "streams"; const char kParamValueTrue[] = "1"; const char kParamValueEmpty[] = ""; const int kOpusDefaultMaxPTime = 120; const int kOpusDefaultPTime = 20; const int kOpusDefaultMinPTime = 3; const int kOpusDefaultSPropStereo = 0; const int kOpusDefaultStereo = 0; const int kOpusDefaultUseInbandFec = 0; const int kOpusDefaultUseDtx = 0; const int kOpusDefaultMaxPlaybackRate = 48000; const int kPreferredMaxPTime = 60; const int kPreferredMinPTime = 10; const int kPreferredSPropStereo = 0; const int kPreferredStereo = 0; const int kPreferredUseInbandFec = 0; const char kRtcpFbParamNack[] = "nack"; const char kRtcpFbNackParamPli[] = "pli"; const char kRtcpFbParamRemb[] = "goog-remb"; const char kRtcpFbParamCcm[] = "ccm"; const char kRtcpFbCcmParamFir[] = "fir"; const char kCodecParamMaxBitrate[] = "x-google-max-bitrate"; const char kCodecParamMinBitrate[] = "x-google-min-bitrate"; const char kCodecParamStartBitrate[] = "x-google-start-bitrate"; const char kCodecParamMaxQuantization[] = "x-google-max-quantization"; const char kCodecParamPort[] = "x-google-port"; const int kGoogleRtpDataCodecId = 101; const char kGoogleRtpDataCodecName[] = "google-data"; const int kGoogleSctpDataCodecId = 108; const char kGoogleSctpDataCodecName[] = "google-sctp-data"; const char kComfortNoiseCodecName[] = "CN"; const int kRtpAudioLevelHeaderExtensionDefaultId = 1; const char kRtpAudioLevelHeaderExtension[] = "urn:ietf:params:rtp-hdrext:ssrc-audio-level"; const int kRtpTimestampOffsetHeaderExtensionDefaultId = 2; const char kRtpTimestampOffsetHeaderExtension[] = "urn:ietf:params:rtp-hdrext:toffset"; const int kRtpAbsoluteSenderTimeHeaderExtensionDefaultId = 3; const char kRtpAbsoluteSenderTimeHeaderExtension[] = "http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time"; const int kRtpVideoRotationHeaderExtensionDefaultId = 4; const char kRtpVideoRotationHeaderExtension[] = "urn:3gpp:video-orientation"; const char kRtpVideoRotation6BitsHeaderExtensionForTesting[] = "urn:3gpp:video-orientation:6"; const int kNumDefaultUnsignalledVideoRecvStreams = 0; const char kVp8CodecName[] = "VP8"; const char kVp9CodecName[] = "VP9"; const char kH264CodecName[] = "H264"; const int kDefaultVp8PlType = 100; const int kDefaultVp9PlType = 101; const int kDefaultH264PlType = 107; const int kDefaultRedPlType = 116; const int kDefaultUlpfecType = 117; const int kDefaultRtxVp8PlType = 96; const int kDefaultVideoMaxWidth = 640; const int kDefaultVideoMaxHeight = 400; const int kDefaultVideoMaxFramerate = 30; } // namespace cricket #pragma once #include "rule.hpp" #include "../../../core/array.hpp" namespace z { namespace util { namespace rgx { /** * \brief Intermediate class for regex rules that can have children. */ class compound : public rule { protected: /** * \brief Attempt to match a single rule to the stream. * \param rgxRule A pointer to the child rule to match. * \param stream The stream to match against. * \return True if the rule matches, false otherwise. */ bool matchRule(rule* rgxRule, core::inputStream& stream) const noexcept; /** * \brief Attempt to match a rule its minimum number of times. * \param rgxRule A pointer to the child rule to match. * \param stream The stream to match against. * \return True if the rule at least matches the minimum, false otherwise. */ bool matchMin(rule* rgxRule, core::inputStream& stream) const noexcept; public: /** * \brief Compound destructor. * Deletes any child rules. */ ~compound() noexcept; /** * \brief Default full constructor. * \param min The minimum number of times this rule must match. * \param max The maximum number of times this rule can match. * \param greedy Whether this rule should consume input greedily. */ compound(int min=1, int max=1, bool greedy=true) noexcept : rule(min,max,greedy){} bool base() const noexcept {return false;}; bool parent() const noexcept {return true;}; ///The list of child rules. core::array children; # ifdef DEBUG virtual void print(core::outputStream& stream, int level=0) noexcept = 0; # endif }; } } } 1-10 #include "GAMER.h" //------------------------------------------------------------------------------------------------------- // Function : Aux_Check_Refinement // Description : Verify the refinement result at the input level // --> Output grids at level lv that should be refined into level lv+1 but were not refined // // Note : 1. This test will not pass if some patches are not refined due to the proper-nestiing constraint // 2. This test should always pass for the initial condition constructed by the UM_Init function // 3. This test only checks density and the option "OPT__FLAG_RHO" should be turned on // // Parameter : lv : Target refinement level // comment : You can put the location where this function is invoked in this string //------------------------------------------------------------------------------------------------------- void Aux_Check_Refinement( const int lv, const char *comment ) { // check # ifndef DENS Aux_Message( stderr, "WARNING : function \"%s\" is supported only if the variable \"DENS\" is defined !!\n", __FUNCTION__ ); OPT__CK_REFINE = false; return; # else // nothing to check at the maximum level if ( lv == NLEVEL-1 ) { if ( MPI_Rank == 0 ) Aux_Message( stderr, "WARNING : function \"%s\" should NOT be applied to the finest level !!\n", __FUNCTION__ ); return; } // this check function must work with the table "FlagTable_Rho" if ( !OPT__FLAG_RHO ) { if ( MPI_Rank == 0 ) Aux_Message( stderr, "WARNING : function \"%s\" must work with the option \"%s\" !!\n", __FUNCTION__, "OPT__FLAG_RHO == 1" ); return; } int Pass = true; bool PatchTest = true; int CountPatch = 0; int CountGrid = 0; real Rho; for (int TargetRank=0; TargetRankNPatchComma[lv][1]; PID++) { if ( amr->patch[0][lv][PID]->son == -1 ) { PatchTest = true; for (int k=0; kpatch[ amr->FluSg[lv] ][lv][PID]->fluid[DENS][k][j][i]; if ( Rho > FlagTable_Rho[lv] ) { if ( Pass ) { Aux_Message( stderr, "\"%s\" : <%s> FAILED at level %2d, Time = %13.7e, Step = %ld !!\n", comment, __FUNCTION__, lv, Time[lv], Step ); Aux_Message( stderr, "%4s\t%7s\t\t%19s\t\t%10s\t%14s\n", "Rank", "PatchID", "Patch Corner", "Grid ID", "Density" ); Pass = false; } Aux_Message( stderr, "%4d\t%7d\t\t(%10d,%10d,%10d)\t\t(%2d,%2d,%2d)\t%14.7e\n", MPI_Rank, PID, amr->patch[0][lv][PID]->corner[0], amr->patch[0][lv][PID]->corner[1], amr->patch[0][lv][PID]->corner[2], i, j, k, Rho ); PatchTest = false; CountGrid ++; } // if ( Rho > FlagTable_Rho[lv] ) } // i, j, k if ( !PatchTest ) CountPatch ++; } // if ( amr->patch[0][lv][PID]->son == -1 ) } // for (int PID=0; PID PASSED at level %2d, Time = %13.7e, Step = %ld\n", comment, __FUNCTION__, lv, Time[lv], Step ); } else { int CountPatch_Sum, CountGrid_Sum, NPatch_Sum; MPI_Reduce( &CountPatch, &CountPatch_Sum, 1, MPI_INT, MPI_SUM, 0, MPI_COMM_WORLD ); MPI_Reduce( &CountGrid , &CountGrid_Sum , 1, MPI_INT, MPI_SUM, 0, MPI_COMM_WORLD ); MPI_Reduce( &amr->NPatchComma[lv][1], &NPatch_Sum , 1, MPI_INT, MPI_SUM, 0, MPI_COMM_WORLD ); if ( MPI_Rank == 0 ) Aux_Message( stderr, "# of patches = %d, # of failed patches = %d, # of failed grids = %d\n", NPatch_Sum, CountPatch_Sum, CountGrid_Sum ); } # endif // #ifndef DENS ... else ... } // FUNCTION : Aux_Check_Refinement DrakenTech/beamui/viewmodel/notifications/news_settings.cpp1-10 // Copyright 2020 The Beam Team // // 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 "news_settings.h" NewscastSettings::NewscastSettings(WalletSettings& walletSettings) : m_storage(walletSettings) { restore(); } bool NewscastSettings::isExcRatesActive() { return m_isExcRatesActive; } void NewscastSettings::setExcRatesActive(bool isActive) { if (isActive != m_isExcRatesActive) { m_isExcRatesActive = isActive; emit excRatesActiveChanged(); emit settingsChanged(); } } bool NewscastSettings::isUpdatesPushActive() { return m_isUpdatesPushActive; } void NewscastSettings::setUpdatesPushActive(bool isActive) { if (isActive != m_isUpdatesPushActive) { m_isUpdatesPushActive = isActive; emit updatesPushActiveChanged(); emit settingsChanged(); } } bool NewscastSettings::isSettingsChanged() { return m_publisherKey != m_storage.getNewscastKey() || m_isUpdatesPushActive != m_storage.isUpdatesPushActive() || m_isExcRatesActive != m_storage.isExcRatesActive(); } QString NewscastSettings::getPublisherKey() { return m_publisherKey; } void NewscastSettings::setPublisherKey(QString key) { if (key != m_publisherKey) { m_publisherKey = key; emit publisherKeyChanged(); emit settingsChanged(); } } void NewscastSettings::apply() { m_storage.setNewscastKey(m_publisherKey); m_storage.setUpdatesPushActive(m_isUpdatesPushActive); m_storage.setExcRatesActive(m_isExcRatesActive); emit settingsChanged(); } void NewscastSettings::restore() { m_publisherKey = m_storage.getNewscastKey(); m_isUpdatesPushActive = m_storage.isUpdatesPushActive(); m_isExcRatesActive = m_storage.isExcRatesActive(); emit excRatesActiveChanged(); emit updatesPushActiveChanged(); emit publisherKeyChanged(); emit settingsChanged(); } //Leetcode Problem No. 324 Wiggle Sort II //Solution written by on 24 May, 2018 #include #include #include using namespace std; class Solution{ public: void wiggleSort(vector& nums) { vector copy(nums); sort(copy.begin(), copy.end()); int index = 0; int n = copy.size(); /** I think the question really is: is there a fixed way to produce a valid permutation */ if(n % 2 != 0){ int i = 0; while(index < n){ nums[i] = copy[index++]; i = i + 2; if(i >= n){ i = 1; } } } else{ //from right to the left int i = n-2; while(index < n){ nums[i] = copy[index++]; i = i - 2; if(i < 0){ i = n-1; } } } for(auto j : nums){ cout << j << endl; } } }; int main(){ Solution s; vector nums{1,5,1,1,6,4}; vector n{1,2,3,3,3,4};//3,4,1,3,2,3 //{4,5,5,6} vector num{4,5,5,5,5,6,6,6}; s.wiggleSort(nums); s.wiggleSort(n); s.wiggleSort(num); return 0; } #include "frmmain.h" #include "ui_frmmain.h" #include "quiwidget.h" frmMain::frmMain(QWidget *parent) : QWidget(parent), ui(new Ui::frmMain) { ui->setupUi(this); ui->tabWidget->setCurrentIndex(App::CurrentIndex); } frmMain::~frmMain() { delete ui; } void frmMain::on_tabWidget_currentChanged(int index) { App::CurrentIndex = index; App::writeConfig(); } yefy/skp0 #include "skpQueue.h" /* SPDX-License-Identifier: Apache-2.0 */ /* * Copyright (C) 2009-2020 Intel Corporation */ /*++ @file: AMTEthernetPortSettingsClient.cpp --*/ #include "AMTEthernetPortSettingsClient.h" #include "AMT_EthernetPortSettings.h" #include "WsmanClientLog.h" #include "WsmanClientCatch.h" AMTEthernetPortSettingsClient::AMTEthernetPortSettingsClient() : m_isInit(false), m_LinkControl(0), m_LinkPreference(0), m_LinkProtection(5) { } AMTEthernetPortSettingsClient::AMTEthernetPortSettingsClient(const std::string &User, const std::string &Password) : BaseWSManClient(User, Password), m_isInit(false), m_LinkControl(0), m_LinkPreference(0), m_LinkProtection(5) { } AMTEthernetPortSettingsClient::~AMTEthernetPortSettingsClient() { } bool AMTEthernetPortSettingsClient::Init(bool forceGet, bool actionGet) { if (!forceGet && m_isInit) return true; m_isInit = false; try { if (!m_endpoint) SetEndpoint(); std::lock_guard lock(WsManSemaphore()); using Intel::Manageability::Cim::Typed::AMT_EthernetPortSettings; std::vector> ethernetSettings; std::vector>::iterator settingsIterator; ethernetSettings = AMT_EthernetPortSettings::Enumerate(m_client.get()); for (settingsIterator = ethernetSettings.begin(); settingsIterator != ethernetSettings.end() ; settingsIterator++) { AMT_EthernetPortSettings *currSetting = settingsIterator->get(); if (!currSetting) continue; if (actionGet) { if ((currSetting->LinkControlExists()) && (currSetting->LinkPreferenceExists()) ) { m_LinkControl = currSetting->LinkControl(); m_LinkPreference = currSetting->LinkPreference(); m_isInit = true; } if(currSetting->WLANLinkProtectionLevelExists()) { m_LinkProtection = currSetting->WLANLinkProtectionLevel(); if(m_LinkProtection == 0) m_LinkProtection = 1; } } else // action Set { try { AMT_EthernetPortSettings::SetLinkPreference_INPUT inputLinkVal; inputLinkVal.LinkPreference(m_LinkPreference); currSetting->SetLinkPreference(inputLinkVal); m_isInit = true; } CATCH_exception("AMTEthernetPortSettingsClient::Init Put") } } m_endpoint = true; return m_isInit; } CATCH_exception("AMTEthernetPortSettingsClient::Init") m_endpoint = false; return false; } bool AMTEthernetPortSettingsClient::GetAMTEthernetPortSettings(unsigned int* pLinkPreference, unsigned int* pLinkControl, unsigned int* pLinkProtection) { if (!Init(true,true)) return false; WSMAN_DEBUG("GetAMTEthernetPortSettings LinkPreference=%d LinkControl=%d LinkProtection=%d\n", m_LinkPreference,m_LinkControl,m_LinkProtection); *pLinkPreference=m_LinkPreference; *pLinkControl=m_LinkControl; *pLinkProtection=m_LinkProtection; return true; } bool AMTEthernetPortSettingsClient::SetLinkPreference(unsigned int LinkPreference) { m_LinkPreference = LinkPreference; if (!Init(true,false)) return false; return true; }#include #include /***************************************************************************************************/ //Display Menu String disp_menu[NANOCAN_MENUCOUNT] = { "Wr Time", "Wr Alarm", "Set Alarm", "Clr Alarm", "Greeting", "<-Exit" }; byte disp_submenu[60], req_CmnTime[3], req_time[3], req_alarm[3], rcd_time[3]= {11, 12, 13}; byte NANOCAN_SUBMENUDGTCNT[3] = {24, 60, 60}; int menu_sel = -1, submenu_sel = -1, submenuopt_sel = 1, greetingmenuopt_sel = 1; bool submenuopt_bypass = false, alarm_st = false; char clk_HHMMSS[3]; timer_struct timer_pressSwt; timer_struct timer_nanoCANMenudisp; timer_struct timer_nanoCANSubMenudisp; timer_struct timer_mainclk; /****************************************************************************************************/ // Declaration for OLED Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET); /****************************************************************************************************/ // Declaration for CAN bus MCP2515 mcp2515(10); struct can_frame rx_canMsg; struct can_frame tx_canMsg; timer_struct timer_0xF101_req, timer_0xF101_resp; timer_struct timer_0xF101Wr_req, timer_0xF101Wr_resp; timer_struct timer_0xF102_req, timer_0xF102_resp; timer_struct timer_0xF103_req, timer_0xF103_resp; byte retval = MCP2515::ERROR_OK; boolean tstr_req = FALSE; //Flag to check for P2 timer. P2* = P2 and no NRC78. /***************************************************************************************************/ // The rotary switch: // * encoder pin CLK // * encoder pin DT // Rotary press button SW #define pinCLK 2 #define pinDT 4 #define pinSW 3 bool pin1_st, pin2_st, pin1_stOld, pin2_stOld; byte r_cntr, l_cntr; /***************************************************************************************************/ bool nanoCAN_pressSwt() { if((!digitalRead(pinSW)) && (get_timer(&timer_pressSwt) == millis())) { start_timer(&timer_pressSwt); return true; } else { if(get_timer(&timer_pressSwt) > 500) { stop_timer(&timer_pressSwt); } return false; } } /***************************************************************************************************/ int nanoCAN_rotarySwt() { int ret_val; pin1_stOld = pin1_st; pin2_stOld = pin2_st; pin1_st = digitalRead(pinCLK); pin2_st = digitalRead(pinDT); if(pin1_st < pin2_st) { r_cntr++; } else if(pin1_st > pin2_st) { l_cntr++; } if(r_cntr > l_cntr) { //Clockwise ret_val = 1; } else if(r_cntr < l_cntr) { //Anti-clockwise ret_val = -1; } else { //Standstill ret_val = 0; } r_cntr = 0; l_cntr = 0; return ret_val; } /***************************************************************************************************/ //RDBI - 0xF101 void RDBI_0xF101() { //Request - CPU time - every 2000 ms start_timer(&timer_0xF101_req); if(((get_timer(&timer_0xF101_req) > 450) || (retval != MCP2515::ERROR_OK)) && (tstr_req == FALSE)) { tx_canMsg.data[0] = 0x03; tx_canMsg.data[1] = 0x22; tx_canMsg.data[2] = 0xF1; tx_canMsg.data[3] = 0x01; tx_canMsg.data[4] = 0x00; tx_canMsg.data[5] = 0x00; tx_canMsg.data[6] = 0x00; tx_canMsg.data[7] = 0x00; retval = mcp2515.sendMessage(&tx_canMsg); stop_timer(&timer_0xF101_req); start_timer(&timer_0xF101_resp); tstr_req = TRUE; } /****************************************************************************************************/ if((tstr_req != FALSE) && (get_timer(&timer_0xF101_resp) < 100)) { if (mcp2515.readMessage(&rx_canMsg) == MCP2515::ERROR_OK) { if((rx_canMsg.can_id == 0x7E8) && (rx_canMsg.can_dlc == tx_canMsg.can_dlc)) { if(rx_canMsg.data[1] == (tx_canMsg.data[1] + 0x40)) { if((rx_canMsg.data[0] == 0x06) && ((((rx_canMsg.data[2] << 8) & 0xFF00) | ((rx_canMsg.data[3] << 0) & 0x00FF) ) == 0xF101)) { rcd_time[0] = rx_canMsg.data[4]; rcd_time[1] = rx_canMsg.data[5]; rcd_time[2] = rx_canMsg.data[6]; //Powersaving mode display.ssd1306_command(SSD1306_DISPLAYON); } } } } else { //Powersaving mode display.ssd1306_command(SSD1306_DISPLAYOFF); } } else { tstr_req = FALSE; stop_timer(&timer_0xF101_resp); } } /***************************************************************************************************/ //WDBI - 0xF101 void WDBI_0xF101() { //Request - CPU time - every 2000 ms start_timer(&timer_0xF101Wr_req); if(((get_timer(&timer_0xF101Wr_req) >= 0) || (retval != MCP2515::ERROR_OK)) && (tstr_req == FALSE)) { tx_canMsg.data[0] = 0x06; tx_canMsg.data[1] = 0x2E; tx_canMsg.data[2] = 0xF1; tx_canMsg.data[3] = 0x01; tx_canMsg.data[4] = req_time[0]; tx_canMsg.data[5] = req_time[1]; tx_canMsg.data[6] = req_time[2]; tx_canMsg.data[7] = 0x00; retval = mcp2515.sendMessage(&tx_canMsg); stop_timer(&timer_0xF101Wr_req); start_timer(&timer_0xF101Wr_resp); tstr_req = TRUE; } /****************************************************************************************************/ if((tstr_req != FALSE) && (get_timer(&timer_0xF101Wr_resp) < 100)) { if (mcp2515.readMessage(&rx_canMsg) == MCP2515::ERROR_OK) { if((rx_canMsg.can_id == 0x7E8) && (rx_canMsg.can_dlc == tx_canMsg.can_dlc)) { if(rx_canMsg.data[1] == (tx_canMsg.data[1] + 0x40)) { if((rx_canMsg.data[0] == 0x03) && ((((rx_canMsg.data[2] << 8) & 0xFF00) | ((rx_canMsg.data[3] << 0) & 0x00FF) ) == 0xF101)) { //assuming Wr Time success, this would not be checked for(byte x=0; x <3; x++) { Serial.print(req_time[x]); Serial.print(":"); } } } } } } else { tstr_req = FALSE; stop_timer(&timer_0xF101Wr_resp); } } /***************************************************************************************************/ //WDBI - 0xF102 void WDBI_0xF102() { //Request - CPU time - every 2000 ms start_timer(&timer_0xF102_req); if(((get_timer(&timer_0xF102_req) >= 60000) || (retval != MCP2515::ERROR_OK)) && (tstr_req == FALSE)) { tx_canMsg.data[0] = 0x06; tx_canMsg.data[1] = 0x2E; tx_canMsg.data[2] = 0xF1; tx_canMsg.data[3] = 0x02; tx_canMsg.data[4] = req_alarm[0]; tx_canMsg.data[5] = req_alarm[1]; tx_canMsg.data[6] = req_alarm[2]; tx_canMsg.data[7] = 0x00; retval = mcp2515.sendMessage(&tx_canMsg); stop_timer(&timer_0xF102_req); start_timer(&timer_0xF102_resp); tstr_req = TRUE; } /****************************************************************************************************/ if((tstr_req != FALSE) && (get_timer(&timer_0xF102_resp) < 100)) { if (mcp2515.readMessage(&rx_canMsg) == MCP2515::ERROR_OK) { if((rx_canMsg.can_id == 0x7E8) && (rx_canMsg.can_dlc == tx_canMsg.can_dlc)) { if(rx_canMsg.data[1] == (tx_canMsg.data[1] + 0x40)) { if((rx_canMsg.data[0] == 0x03) && ((((rx_canMsg.data[2] << 8) & 0xFF00) | ((rx_canMsg.data[3] << 0) & 0x00FF) ) == 0xF102)) { //assuming Wr alarm success, this would not be checked } } } } } else { tstr_req = FALSE; stop_timer(&timer_0xF102_resp); } } /***************************************************************************************************/ //WDBI - 0xF103 void WDBI_0xF103() { //Request - CPU time - every 2000 ms start_timer(&timer_0xF103_req); if(((get_timer(&timer_0xF103_req) >= 1100) || (retval != MCP2515::ERROR_OK)) && (tstr_req == FALSE)) { tx_canMsg.data[0] = 0x04; tx_canMsg.data[1] = 0x2E; tx_canMsg.data[2] = 0xF1; tx_canMsg.data[3] = 0x03; tx_canMsg.data[4] = alarm_st; tx_canMsg.data[5] = 0x00; tx_canMsg.data[6] = 0x00; tx_canMsg.data[7] = 0x00; retval = mcp2515.sendMessage(&tx_canMsg); stop_timer(&timer_0xF103_req); start_timer(&timer_0xF103_resp); tstr_req = TRUE; } /****************************************************************************************************/ if((tstr_req != FALSE) && (get_timer(&timer_0xF103_resp) < 100)) { if (mcp2515.readMessage(&rx_canMsg) == MCP2515::ERROR_OK) { if((rx_canMsg.can_id == 0x7E8) && (rx_canMsg.can_dlc == tx_canMsg.can_dlc)) { if(rx_canMsg.data[1] == (tx_canMsg.data[1] + 0x40)) { if((rx_canMsg.data[0] == 0x03) && ((((rx_canMsg.data[2] << 8) & 0xFF00) | ((rx_canMsg.data[3] << 0) & 0x00FF) ) == 0xF103)) { //Wr Alarm set/ clr success. this case is not checked and assumed to be success } } } } } else { tstr_req = FALSE; stop_timer(&timer_0xF102_resp); } } /***************************************************************************************************/ void nanoCAN_Menu(int rot_key) { start_timer(&timer_nanoCANMenudisp); if((rot_key != 0) && (get_timer(&timer_nanoCANMenudisp) > 500)) { byte i, j, k; menu_sel = menu_sel + rot_key; if((menu_sel > 0) && (menu_sel < (NANOCAN_MENUCOUNT - 1))) { i = menu_sel - 1; j = menu_sel; k = menu_sel + 1; } else if((menu_sel == 0) || (menu_sel > (NANOCAN_MENUCOUNT - 1))) { menu_sel = 0; i = NANOCAN_MENUCOUNT - 1; j = menu_sel; k = menu_sel + 1; } else if((menu_sel < 0) || (menu_sel == (NANOCAN_MENUCOUNT - 1))) { menu_sel = NANOCAN_MENUCOUNT - 1; i = menu_sel - 1; j = menu_sel; k = 0; } display.clearDisplay(); display.setTextSize(1); display.setCursor(0, 0); display.setTextColor(WHITE); display.println(disp_menu[i]); display.setCursor(0, 10); display.setTextColor(BLACK, WHITE); display.println(disp_menu[j]); display.setCursor(0, 20); display.setTextColor(WHITE); display.println(disp_menu[k]); display.display(); menu_sel = j; stop_timer(&timer_nanoCANMenudisp); } else { start_timer(&timer_mainclk); if((get_timer(&timer_mainclk) > 1000) && (menu_sel == NANOCAN_MENUCOUNT -1)) { display.clearDisplay(); display.setTextSize(2.5); for(byte x=0; x < 3; x++) { display.setCursor((0 + (40 * x)), 00); display.setTextColor(WHITE); display.print(rcd_time[x]); if(x != 2) { display.print(":"); } } if(alarm_st) { display.setTextSize(1); display.setTextColor(BLACK, WHITE); display.setCursor(00, 15); display.print("Alarm On"); } else { display.setTextSize(1); display.setCursor(00, 15); display.setTextColor(BLACK, WHITE); display.print("Alarm Off"); } for(byte x=0; x < 3; x++) { display.setCursor((0 + (25 * x)), 25); display.setTextColor(WHITE); display.print(req_alarm[x]); if(x != 2) { display.print(":"); } } display.display(); stop_timer(&timer_mainclk); } } } /***************************************************************************************************/ void nanoCAN_SubMenu(int rot_key) { if(submenu_sel < 3) { display.clearDisplay(); display.setTextSize(1); display.setCursor(0, 0); display.setTextColor(WHITE); display.println(disp_menu[menu_sel]); display.setCursor(0, 20); display.setTextColor(WHITE); display.println(disp_menu[NANOCAN_MENUCOUNT - 1]); for(byte x=0; x < submenu_sel; x++) { display.setCursor((60 + (20 * x)), 10); display.setTextColor(WHITE); display.println(req_CmnTime[x]); } byte i, j, k; submenuopt_sel = submenuopt_sel + rot_key; if((submenuopt_sel > 0) && (submenuopt_sel < (NANOCAN_SUBMENUDGTCNT[submenu_sel] - 1))) { i = submenuopt_sel - 1; j = submenuopt_sel; k = submenuopt_sel + 1; } else if((submenuopt_sel == 0) || (submenuopt_sel > (NANOCAN_SUBMENUDGTCNT[submenu_sel] - 1))) { submenuopt_sel = 0; i = NANOCAN_SUBMENUDGTCNT[submenu_sel] - 1; j = submenuopt_sel; k = submenuopt_sel + 1; } else if((submenuopt_sel < 0) || (submenuopt_sel == (NANOCAN_SUBMENUDGTCNT[submenu_sel] - 1))) { submenuopt_sel = NANOCAN_SUBMENUDGTCNT[submenu_sel] - 1; i = submenuopt_sel - 1; j = submenuopt_sel; k = 0; } display.setCursor((60 + (20 * submenu_sel)), 0); display.setTextColor(WHITE); display.println(disp_submenu[i]); display.setCursor((60 + (20 * submenu_sel)), 10); display.setTextColor(BLACK, WHITE); display.println(disp_submenu[j]); display.setCursor((60 + (20 * submenu_sel)), 20); display.setTextColor(WHITE); display.println(disp_submenu[k]); display.display(); submenuopt_sel = j; req_CmnTime[submenu_sel] = disp_submenu[submenuopt_sel]; } else //(submenu_sel >= 3) { submenu_sel = -1; if(menu_sel == 0) { for(byte x=0; x <3; x++) { req_time[x] = req_CmnTime[x]; } //WDBI request tstr_req = FALSE; WDBI_0xF101(); } else if(menu_sel == 1) { for(byte x=0; x <3; x++) { req_alarm[x] = req_CmnTime[x]; } } } } /***************************************************************************************************/ void nanoCAN_GreetingMenu(int rot_key) { if(submenu_sel == 0) { display.clearDisplay(); byte i, j, k; greetingmenuopt_sel = greetingmenuopt_sel + rot_key; if((greetingmenuopt_sel > 0) && (greetingmenuopt_sel < (NANOCAN_GREETINGMENUCNT - 1))) { i = greetingmenuopt_sel - 1; j = greetingmenuopt_sel; k = greetingmenuopt_sel + 1; } else if((greetingmenuopt_sel == 0) || (greetingmenuopt_sel > (NANOCAN_GREETINGMENUCNT - 1))) { greetingmenuopt_sel = 0; i = NANOCAN_GREETINGMENUCNT - 1; j = greetingmenuopt_sel; k = greetingmenuopt_sel + 1; } else if((greetingmenuopt_sel < 0) || (greetingmenuopt_sel == (NANOCAN_GREETINGMENUCNT - 1))) { greetingmenuopt_sel = NANOCAN_GREETINGMENUCNT - 1; i = greetingmenuopt_sel - 1; j = greetingmenuopt_sel; k = 0; } display.setCursor(0, 0); display.setTextColor(WHITE); display.println(disp_greetingmenu[i]); display.setCursor(0, 10); display.setTextColor(BLACK, WHITE); display.println(disp_greetingmenu[j]); display.setCursor(0, 20); display.setTextColor(WHITE); display.println(disp_greetingmenu[k]); display.display(); } else //(submenu_sel > 1) { submenu_sel = -1; } } void setup() { /* Pin 01 - Red light - Low On */ /* Pin 13 - build in LED - High On */ pinMode(13, OUTPUT); /****************************************************************************************************/ Serial.begin(9600); // SSD1306_SWITCHCAPVCC = generate display voltage from 3.3V internally if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) { // Address 0x3C for 128x32 Serial.println(F("SSD1306 allocation failed")); for(;;); // Don't proceed, loop forever } // Clear the buffer display.clearDisplay(); display.drawBitmap(0, 0, myBitmap, 128, 32, WHITE); //Logo display display.display(); delay(1000); // Clear the buffer display.clearDisplay(); /****************************************************************************************************/ SPI.begin(); mcp2515.reset(); mcp2515.setBitrate(CAN_125KBPS, MCP_16MHZ); mcp2515.setNormalMode(); /****************************************************************************************************/ pinMode(pinCLK, INPUT); pinMode(pinDT, INPUT); pinMode(pinSW, INPUT); /****************************************************************************************************/ for(byte i = 0; i < 60; i++) { disp_submenu[i] = i; } } // the loop function runs over and over again forever void loop() { if(submenu_sel == -1) { nanoCAN_Menu(nanoCAN_rotarySwt()); } /****************************************************************************************************/ if(nanoCAN_pressSwt()) { submenu_sel++; } if(submenu_sel >= 0) { if((menu_sel == 0) || (menu_sel == 1)) { nanoCAN_SubMenu(nanoCAN_rotarySwt()); } else if(menu_sel == 2) { alarm_st = true; submenu_sel = -1; } else if((menu_sel == 3) || (menu_sel == (NANOCAN_MENUCOUNT - 1))) { alarm_st = false; submenu_sel = -1; } else if(menu_sel == 4) { nanoCAN_GreetingMenu(nanoCAN_rotarySwt()); } else { submenu_sel = -1; } } tx_canMsg.can_id = 0x7E0; tx_canMsg.can_dlc = 0x08; //RDBI request RDBI_0xF101(); //WDBI alarm request WDBI_0xF102(); WDBI_0xF103(); /****************************************************************************************************/ } /* this file has been autogenerated by vtkNodeJsWrap */ /* editing this might proof futile */ #define VTK_WRAPPING_CXX #define VTK_STREAMS_FWD_ONLY #include #include "vtkDataSetAlgorithmWrap.h" #include "vtkExtractVectorComponentsWrap.h" #include "vtkObjectWrap.h" #include "vtkDataSetWrap.h" #include "../../plus/plus.h" using namespace v8; extern Nan::Persistent vtkNodeJsNoWrap; Nan::Persistent VtkExtractVectorComponentsWrap::ptpl; VtkExtractVectorComponentsWrap::VtkExtractVectorComponentsWrap() { } VtkExtractVectorComponentsWrap::VtkExtractVectorComponentsWrap(vtkSmartPointer _native) { native = _native; } VtkExtractVectorComponentsWrap::~VtkExtractVectorComponentsWrap() { } void VtkExtractVectorComponentsWrap::Init(v8::Local exports) { Nan::SetAccessor(exports, Nan::New("vtkExtractVectorComponents").ToLocalChecked(), ConstructorGetter); Nan::SetAccessor(exports, Nan::New("ExtractVectorComponents").ToLocalChecked(), ConstructorGetter); } void VtkExtractVectorComponentsWrap::ConstructorGetter( v8::Local property, const Nan::PropertyCallbackInfo& info) { InitPtpl(); info.GetReturnValue().Set(Nan::New(ptpl)->GetFunction()); } void VtkExtractVectorComponentsWrap::InitPtpl() { if (!ptpl.IsEmpty()) return; v8::Local tpl = Nan::New(New); VtkDataSetAlgorithmWrap::InitPtpl( ); tpl->Inherit(Nan::New(VtkDataSetAlgorithmWrap::ptpl)); tpl->SetClassName(Nan::New("VtkExtractVectorComponentsWrap").ToLocalChecked()); tpl->InstanceTemplate()->SetInternalFieldCount(1); Nan::SetPrototypeMethod(tpl, "ExtractToFieldDataOff", ExtractToFieldDataOff); Nan::SetPrototypeMethod(tpl, "extractToFieldDataOff", ExtractToFieldDataOff); Nan::SetPrototypeMethod(tpl, "ExtractToFieldDataOn", ExtractToFieldDataOn); Nan::SetPrototypeMethod(tpl, "extractToFieldDataOn", ExtractToFieldDataOn); Nan::SetPrototypeMethod(tpl, "GetClassName", GetClassName); Nan::SetPrototypeMethod(tpl, "getClassName", GetClassName); Nan::SetPrototypeMethod(tpl, "GetExtractToFieldData", GetExtractToFieldData); Nan::SetPrototypeMethod(tpl, "getExtractToFieldData", GetExtractToFieldData); Nan::SetPrototypeMethod(tpl, "GetVxComponent", GetVxComponent); Nan::SetPrototypeMethod(tpl, "getVxComponent", GetVxComponent); Nan::SetPrototypeMethod(tpl, "GetVyComponent", GetVyComponent); Nan::SetPrototypeMethod(tpl, "getVyComponent", GetVyComponent); Nan::SetPrototypeMethod(tpl, "GetVzComponent", GetVzComponent); Nan::SetPrototypeMethod(tpl, "getVzComponent", GetVzComponent); Nan::SetPrototypeMethod(tpl, "IsA", IsA); Nan::SetPrototypeMethod(tpl, "isA", IsA); Nan::SetPrototypeMethod(tpl, "NewInstance", NewInstance); Nan::SetPrototypeMethod(tpl, "newInstance", NewInstance); Nan::SetPrototypeMethod(tpl, "SafeDownCast", SafeDownCast); Nan::SetPrototypeMethod(tpl, "safeDownCast", SafeDownCast); Nan::SetPrototypeMethod(tpl, "SetExtractToFieldData", SetExtractToFieldData); Nan::SetPrototypeMethod(tpl, "setExtractToFieldData", SetExtractToFieldData); Nan::SetPrototypeMethod(tpl, "SetInputData", SetInputData); Nan::SetPrototypeMethod(tpl, "setInputData", SetInputData); #ifdef VTK_NODE_PLUS_VTKEXTRACTVECTORCOMPONENTSWRAP_INITPTPL VTK_NODE_PLUS_VTKEXTRACTVECTORCOMPONENTSWRAP_INITPTPL #endif ptpl.Reset( tpl ); } void VtkExtractVectorComponentsWrap::New(const Nan::FunctionCallbackInfo& info) { if(!info.IsConstructCall()) { Nan::ThrowError("Constructor not called in a construct call."); return; } if(info.Length() == 0) { vtkSmartPointer native = vtkSmartPointer::New(); VtkExtractVectorComponentsWrap* obj = new VtkExtractVectorComponentsWrap(native); obj->Wrap(info.This()); } else { if(info[0]->ToObject() != vtkNodeJsNoWrap ) { Nan::ThrowError("Parameter Error"); return; } } info.GetReturnValue().Set(info.This()); } void VtkExtractVectorComponentsWrap::ExtractToFieldDataOff(const Nan::FunctionCallbackInfo& info) { VtkExtractVectorComponentsWrap *wrapper = ObjectWrap::Unwrap(info.Holder()); vtkExtractVectorComponents *native = (vtkExtractVectorComponents *)wrapper->native.GetPointer(); if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } native->ExtractToFieldDataOff(); } void VtkExtractVectorComponentsWrap::ExtractToFieldDataOn(const Nan::FunctionCallbackInfo& info) { VtkExtractVectorComponentsWrap *wrapper = ObjectWrap::Unwrap(info.Holder()); vtkExtractVectorComponents *native = (vtkExtractVectorComponents *)wrapper->native.GetPointer(); if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } native->ExtractToFieldDataOn(); } void VtkExtractVectorComponentsWrap::GetClassName(const Nan::FunctionCallbackInfo& info) { VtkExtractVectorComponentsWrap *wrapper = ObjectWrap::Unwrap(info.Holder()); vtkExtractVectorComponents *native = (vtkExtractVectorComponents *)wrapper->native.GetPointer(); char const * r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetClassName(); info.GetReturnValue().Set(Nan::New(r).ToLocalChecked()); } void VtkExtractVectorComponentsWrap::GetExtractToFieldData(const Nan::FunctionCallbackInfo& info) { VtkExtractVectorComponentsWrap *wrapper = ObjectWrap::Unwrap(info.Holder()); vtkExtractVectorComponents *native = (vtkExtractVectorComponents *)wrapper->native.GetPointer(); int r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetExtractToFieldData(); info.GetReturnValue().Set(Nan::New(r)); } void VtkExtractVectorComponentsWrap::GetVxComponent(const Nan::FunctionCallbackInfo& info) { VtkExtractVectorComponentsWrap *wrapper = ObjectWrap::Unwrap(info.Holder()); vtkExtractVectorComponents *native = (vtkExtractVectorComponents *)wrapper->native.GetPointer(); vtkDataSet * r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetVxComponent(); VtkDataSetWrap::InitPtpl(); v8::Local argv[1] = { Nan::New(vtkNodeJsNoWrap) }; v8::Local cons = Nan::New(VtkDataSetWrap::ptpl)->GetFunction(); v8::Local wo = cons->NewInstance(1, argv); VtkDataSetWrap *w = new VtkDataSetWrap(); w->native = r; w->Wrap(wo); info.GetReturnValue().Set(wo); } void VtkExtractVectorComponentsWrap::GetVyComponent(const Nan::FunctionCallbackInfo& info) { VtkExtractVectorComponentsWrap *wrapper = ObjectWrap::Unwrap(info.Holder()); vtkExtractVectorComponents *native = (vtkExtractVectorComponents *)wrapper->native.GetPointer(); vtkDataSet * r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetVyComponent(); VtkDataSetWrap::InitPtpl(); v8::Local argv[1] = { Nan::New(vtkNodeJsNoWrap) }; v8::Local cons = Nan::New(VtkDataSetWrap::ptpl)->GetFunction(); v8::Local wo = cons->NewInstance(1, argv); VtkDataSetWrap *w = new VtkDataSetWrap(); w->native = r; w->Wrap(wo); info.GetReturnValue().Set(wo); } void VtkExtractVectorComponentsWrap::GetVzComponent(const Nan::FunctionCallbackInfo& info) { VtkExtractVectorComponentsWrap *wrapper = ObjectWrap::Unwrap(info.Holder()); vtkExtractVectorComponents *native = (vtkExtractVectorComponents *)wrapper->native.GetPointer(); vtkDataSet * r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetVzComponent(); VtkDataSetWrap::InitPtpl(); v8::Local argv[1] = { Nan::New(vtkNodeJsNoWrap) }; v8::Local cons = Nan::New(VtkDataSetWrap::ptpl)->GetFunction(); v8::Local wo = cons->NewInstance(1, argv); VtkDataSetWrap *w = new VtkDataSetWrap(); w->native = r; w->Wrap(wo); info.GetReturnValue().Set(wo); } void VtkExtractVectorComponentsWrap::IsA(const Nan::FunctionCallbackInfo& info) { VtkExtractVectorComponentsWrap *wrapper = ObjectWrap::Unwrap(info.Holder()); vtkExtractVectorComponents *native = (vtkExtractVectorComponents *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsString()) { Nan::Utf8String a0(info[0]); int r; if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } r = native->IsA( *a0 ); info.GetReturnValue().Set(Nan::New(r)); return; } Nan::ThrowError("Parameter mismatch"); } void VtkExtractVectorComponentsWrap::NewInstance(const Nan::FunctionCallbackInfo& info) { VtkExtractVectorComponentsWrap *wrapper = ObjectWrap::Unwrap(info.Holder()); vtkExtractVectorComponents *native = (vtkExtractVectorComponents *)wrapper->native.GetPointer(); vtkExtractVectorComponents * r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->NewInstance(); VtkExtractVectorComponentsWrap::InitPtpl(); v8::Local argv[1] = { Nan::New(vtkNodeJsNoWrap) }; v8::Local cons = Nan::New(VtkExtractVectorComponentsWrap::ptpl)->GetFunction(); v8::Local wo = cons->NewInstance(1, argv); VtkExtractVectorComponentsWrap *w = new VtkExtractVectorComponentsWrap(); w->native = r; w->Wrap(wo); info.GetReturnValue().Set(wo); } void VtkExtractVectorComponentsWrap::SafeDownCast(const Nan::FunctionCallbackInfo& info) { VtkExtractVectorComponentsWrap *wrapper = ObjectWrap::Unwrap(info.Holder()); vtkExtractVectorComponents *native = (vtkExtractVectorComponents *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkObjectWrap::ptpl))->HasInstance(info[0])) { VtkObjectWrap *a0 = ObjectWrap::Unwrap(info[0]->ToObject()); vtkExtractVectorComponents * r; if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } r = native->SafeDownCast( (vtkObject *) a0->native.GetPointer() ); VtkExtractVectorComponentsWrap::InitPtpl(); v8::Local argv[1] = { Nan::New(vtkNodeJsNoWrap) }; v8::Local cons = Nan::New(VtkExtractVectorComponentsWrap::ptpl)->GetFunction(); v8::Local wo = cons->NewInstance(1, argv); VtkExtractVectorComponentsWrap *w = new VtkExtractVectorComponentsWrap(); w->native = r; w->Wrap(wo); info.GetReturnValue().Set(wo); return; } Nan::ThrowError("Parameter mismatch"); } void VtkExtractVectorComponentsWrap::SetExtractToFieldData(const Nan::FunctionCallbackInfo& info) { VtkExtractVectorComponentsWrap *wrapper = ObjectWrap::Unwrap(info.Holder()); vtkExtractVectorComponents *native = (vtkExtractVectorComponents *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsInt32()) { if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetExtractToFieldData( info[0]->Int32Value() ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkExtractVectorComponentsWrap::SetInputData(const Nan::FunctionCallbackInfo& info) { VtkExtractVectorComponentsWrap *wrapper = ObjectWrap::Unwrap(info.Holder()); vtkExtractVectorComponents *native = (vtkExtractVectorComponents *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkDataSetWrap::ptpl))->HasInstance(info[0])) { VtkDataSetWrap *a0 = ObjectWrap::Unwrap(info[0]->ToObject()); if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetInputData( (vtkDataSet *) a0->native.GetPointer() ); return; } Nan::ThrowError("Parameter mismatch"); } #include #include "CaesarCipher.cpp" #include "MonoAlphabeticCipher.cpp" #include "PlayfairCipher.cpp" #include "VigenereCipher.cpp" int main() { VigenereCipher cipher = VigenereCipher("ciao"); std::string p = "ciao"; std::string c = cipher.encrypt(p); std::cout << c << std::endl; std::cout << cipher.decrypt(c) << std::endl; return 0; } // The MIT License (MIT) // // Copyright (c) 2014 () // // 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 AUTOJSONCXX_MAP_TYPES_HPP_29A4C106C1B1 #define AUTOJSONCXX_MAP_TYPES_HPP_29A4C106C1B1 #include #include #include #include #include #include #include #if AUTOJSONCXX_HAS_MODERN_TYPES #include #endif namespace autojsoncxx { template class MapBaseSAXEventHandler { private: std::string key; ElementType value; SAXEventHandler internal_handler; utility::scoped_ptr the_error; std::stack state; // A stack of StartArray() and StartObject() event // must be recorded, so we know when the current // element has been fully parsed, and needs to be // pushed back into the container bool emplace_when_time_is_right() { if (state.size() == 1 && state.top() == internal::OBJECT) { if (!static_cast(this)->Emplace(key, AUTOJSONCXX_MOVE_IF_NOEXCEPT(value))) { the_error.reset(new error::DuplicateKeyError(AUTOJSONCXX_MOVE(key))); return false; } value = ElementType(); internal_handler.PrepareForReuse(); } return true; } bool check_depth(const char* type) { if (state.empty()) { the_error.reset(new error::TypeMismatchError("object", type)); return false; } return true; } bool checked_event_forwarding(bool success) { if (success) return emplace_when_time_is_right(); set_member_error(); return false; } void set_member_error() { this->the_error.reset(new error::ObjectMemberError(key)); } public: explicit MapBaseSAXEventHandler() : key() , value() , internal_handler(&value) { } bool Null() { return check_depth("null") && checked_event_forwarding(internal_handler.Null()); } bool Bool(bool b) { return check_depth("bool") && checked_event_forwarding(internal_handler.Bool(b)); } bool Int(int i) { return check_depth("int") && checked_event_forwarding(internal_handler.Int(i)); } bool Uint(unsigned i) { return check_depth("unsigned") && checked_event_forwarding(internal_handler.Uint(i)); } bool Int64(utility::int64_t i) { return check_depth("int64_t") && checked_event_forwarding(internal_handler.Int64(i)); } bool Uint64(utility::uint64_t i) { return check_depth("uint64_t") && checked_event_forwarding(internal_handler.Uint64(i)); } bool Double(double d) { return check_depth("double") && checked_event_forwarding(internal_handler.Double(d)); } bool String(const char* str, SizeType length, bool copy) { return check_depth("string") && checked_event_forwarding(internal_handler.String(str, length, copy)); } bool Key(const char* str, SizeType length, bool copy) { if (state.size() > 1) return checked_event_forwarding(internal_handler.Key(str, length, copy)); key.assign(str, length); return true; } bool StartArray() { if (!check_depth("array")) return false; state.push(internal::ARRAY); return checked_event_forwarding(internal_handler.StartArray()); } bool EndArray(SizeType length) { assert(state.top() == internal::ARRAY); state.pop(); return check_depth("array") && checked_event_forwarding(internal_handler.EndArray(length)); } bool StartObject() { state.push(internal::OBJECT); if (state.size() > 1) return checked_event_forwarding(internal_handler.StartObject()); return true; } bool EndObject(SizeType length) { assert(state.top() == internal::OBJECT); state.pop(); if (!state.empty()) return checked_event_forwarding(internal_handler.EndObject(length)); return true; } bool HasError() const { return !this->the_error.empty(); } bool ReapError(error::ErrorStack& errs) { if (this->the_error.empty()) return false; errs.push(this->the_error.release()); internal_handler.ReapError(errs); return true; } void PrepareForReuse() { } }; template struct MapSerializer { void operator()(Writer& w, const MapType& map) const { w.StartObject(); for (ConstIteratorType it = map.begin(), end = map.end(); it != end; ++it) { w.Key(it->first.data(), static_cast(it->first.size())); Serializer()(w, it->second); } w.EndObject(); } }; template class SAXEventHandler > : public MapBaseSAXEventHandler > > { private: typedef std::map map_type; map_type* m_value; public: explicit SAXEventHandler(map_type* v) : m_value(v) { } bool Emplace(const std::string& key, const ElementType& value) { return m_value->insert(std::make_pair(key, value)).second; } #if AUTOJSONCXX_HAS_RVALUE bool Emplace(const std::string& key, ElementType&& value) { return m_value->insert(std::make_pair(AUTOJSONCXX_MOVE(key), AUTOJSONCXX_MOVE(value))).second; } #endif }; template struct Serializer > : public MapSerializer, ElementType, typename std::map::const_iterator> { }; template class SAXEventHandler > : public MapBaseSAXEventHandler > > { private: typedef std::multimap map_type; map_type* m_value; public: explicit SAXEventHandler(map_type* v) : m_value(v) { } bool Emplace(const std::string& key, const ElementType& value) { return m_value->insert(std::make_pair(key, value)).second; } #if AUTOJSONCXX_HAS_RVALUE bool Emplace(const std::string& key, ElementType&& value) { return m_value->insert(std::make_pair(AUTOJSONCXX_MOVE(key), AUTOJSONCXX_MOVE(value))).second; } #endif }; template struct Serializer > : public MapSerializer, ElementType, typename std::multimap::const_iterator> { }; #if AUTOJSONCXX_HAS_MODERN_TYPES template class SAXEventHandler > : public MapBaseSAXEventHandler > > { private: typedef std::unordered_map map_type; map_type* m_value; public: explicit SAXEventHandler(map_type* v) : m_value(v) { } bool Emplace(const std::string& key, const ElementType& value) { return m_value->insert(std::make_pair(key, value)).second; } #if AUTOJSONCXX_HAS_RVALUE bool Emplace(const std::string& key, ElementType&& value) { return m_value->insert(std::make_pair(AUTOJSONCXX_MOVE(key), AUTOJSONCXX_MOVE(value))).second; } #endif }; template struct Serializer > : public MapSerializer, ElementType, typename std::unordered_map::const_iterator> { }; template class SAXEventHandler > : public MapBaseSAXEventHandler > > { private: typedef std::unordered_multimap map_type; map_type* m_value; public: explicit SAXEventHandler(map_type* v) : m_value(v) { } bool Emplace(const std::string& key, const ElementType& value) { return m_value->insert(std::make_pair(key, value)).second; } #if AUTOJSONCXX_HAS_RVALUE bool Emplace(const std::string& key, ElementType&& value) { return m_value->insert(std::make_pair(AUTOJSONCXX_MOVE(key), AUTOJSONCXX_MOVE(value))).second; } #endif }; template struct Serializer > : public MapSerializer, ElementType, typename std::unordered_multimap::const_iterator> { }; #endif } #endif /* * Windows MTP Firmware Uploading Implementation * * Based on http://opensource.creative.com/mtp_xfer.html * Edited by for Rockbox * * Copyright (c) 2009, * 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 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 MAURUS CUELENAERE ''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 MAURUS CUELENAERE 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 "mswmdm_i.c" #include "mswmdm.h" #include "sac.h" #include "scclient.h" #include "progresshelper.h" CProgressHelper::CProgressHelper( void (*callback)(unsigned int progress, unsigned int max) ) { m_cur_ticks = 0; m_max_ticks = 0; m_counter = 0; m_callback = callback; } CProgressHelper::~CProgressHelper() { } HRESULT CProgressHelper::Begin( DWORD dwEstimatedTicks ) { m_max_ticks = dwEstimatedTicks; return S_OK; } HRESULT CProgressHelper::Progress( DWORD dwTranspiredTicks ) { m_cur_ticks = dwTranspiredTicks; if(m_callback != NULL) m_callback(m_cur_ticks, max(m_max_ticks, m_cur_ticks)); return S_OK; } HRESULT CProgressHelper::End() { m_cur_ticks = m_max_ticks; return S_OK; } HRESULT CProgressHelper::QueryInterface( REFIID riid, void __RPC_FAR *__RPC_FAR *ppvObject ) { if(riid == IID_IWMDMProgress || riid == IID_IUnknown) { *ppvObject = this; return S_OK; } else { *ppvObject = NULL; return E_NOINTERFACE; } } ULONG CProgressHelper::AddRef() { return m_counter++; } ULONG CProgressHelper::Release() { return m_counter--; } POSIX/demo/UnitTestStructCompatible.cpp /* * Tencent is pleased to support the open source community by making * MMKV available. * * Copyright (C) 2020 THL A29 Limited, a Tencent company. * All rights reserved. * * Licensed under the BSD 3-Clause License (the "License"); you may not use * this file except in compliance with the License. You may obtain a copy of * the License at * * https://opensource.org/licenses/BSD-3-Clause * * 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 "MMKV.h" #include #include #include #include #include #include using namespace std; using namespace mmkv; static const string MMKV_ID = "process_test"; static const string KeyNotExist = "KeyNotExist"; void brutleTest() { using hclock = chrono::high_resolution_clock; auto start = hclock::now(); auto mmkv = MMKV::mmkvWithID(MMKV_ID, MMKV_MULTI_PROCESS); auto finish = hclock::now(); auto used = chrono::duration_cast(finish - start).count(); cout << "used: " << used << " ms\n"; cout.flush(); } struct Employee { int id; int age; int tall; int familyMemberCnt; }; struct Company { Employee employeeList[64]; // Employee is a struct within the Company struct int numberOfEmployees; }; void testBytes(MMKV *mmkv) { string str = "Hello 2018 world cup 世界杯"; MMBuffer buffer((void *) str.data(), str.length(), MMBufferNoCopy); auto ret = mmkv->set(buffer, "bytes"); assert(ret); auto value = mmkv->getBytes("bytes"); assert(value.length() == buffer.length() && memcmp(value.getPtr(), buffer.getPtr(), value.length()) == 0); value = mmkv->getBytes(KeyNotExist); assert(value.length() == 0); printf("test bytes: passed\n"); } void testStruct1(MMKV *mmkv){ Company company; company.employeeList[0].id = 100; company.employeeList[0].age = 101; company.employeeList[0].tall = 102; company.employeeList[1].id = 200; company.employeeList[1].age = 201; company.employeeList[1].tall = 202; company.numberOfEmployees = 2; MMBuffer buffer((void *) &company, sizeof(company), MMBufferNoCopy); auto ret = mmkv->set(buffer, "myStruct"); assert(ret); printf("set myStruct suc, size:%d\n", sizeof(company)); auto value = mmkv->getBytes("myStruct"); assert(value.length() == buffer.length() && memcmp(value.getPtr(), buffer.getPtr(), value.length()) == 0); printf("getBytes myStruct suc, size:%d\n", sizeof(company)); Company* readCompany = (Company*)value.getPtr(); if(readCompany) { printf("getBytes myStruct suc, element cnt:%d\n", readCompany->numberOfEmployees); printf("getBytes myStruct suc, element0, id:%d, age:%d, tall:%d\n", readCompany->employeeList[0].id, readCompany->employeeList[0].age, readCompany->employeeList[0].tall); printf("getBytes myStruct suc, element1, id:%d, age:%d, tall:%d\n", readCompany->employeeList[1].id, readCompany->employeeList[1].age, readCompany->employeeList[1].tall); } } void testStruct2(MMKV *mmkv){ auto readV = mmkv->getBytes("myStruct"); printf("getBytes myStruct suc1, size:%d\n", sizeof(Company)); Company* company = (Company*)readV.getPtr(); if(!company) { printf("getBytes myStruct getPtr return null, len:%d\n", (int)readV.length()); return ; } printf("getBytes myStruct suc, element cnt:%d\n", company->numberOfEmployees); printf("getBytes myStruct suc, element0, id:%d, age:%d, tall:%d\n", company->employeeList[0].id, company->employeeList[0].age, company->employeeList[0].tall); printf("getBytes myStruct suc, element1, id:%d, age:%d, tall:%d\n", company->employeeList[1].id, company->employeeList[1].age, company->employeeList[1].tall); // 对新增的成员赋值 company->employeeList[0].familyMemberCnt = 5; company->employeeList[0].familyMemberCnt = 10; MMBuffer buffer((void *) &company, sizeof(company), MMBufferNoCopy); auto ret = mmkv->set(buffer, "myStruct"); assert(ret); printf("set myStruct suc, size:%d\n", sizeof(company)); auto value = mmkv->getBytes("myStruct"); assert(value.length() == buffer.length() && memcmp(value.getPtr(), buffer.getPtr(), value.length()) == 0); printf("getBytes myStruct suc2, size:%d\n", sizeof(company)); Company* readCompany = (Company*)value.getPtr(); if(readCompany) { printf("getBytes myStruct suc, element cnt:%d\n", readCompany->numberOfEmployees); printf("getBytes myStruct suc, element0, id:%d, age:%d, tall:%d\n", readCompany->employeeList[0].id, readCompany->employeeList[0].age, readCompany->employeeList[0].tall, readCompany->employeeList[0].familyMemberCnt); printf("getBytes myStruct suc, element1, id:%d, age:%d, tall:%d\n", readCompany->employeeList[1].id, readCompany->employeeList[1].age, readCompany->employeeList[1].tall, readCompany->employeeList[0].familyMemberCnt); } } int main() { locale::global(locale("")); wcout.imbue(locale("")); char c; srand((uint64_t) &c); string rootDir = "./structCompatibleTest"; MMKV::initializeMMKV(rootDir); auto mmkv = MMKV::mmkvWithID("unit_test"); mmkv->clearAll(); testStruct2(mmkv); } OpenHome/Net/Bindings/C/ControlPoint/Proxies/CpAvOpenhomeOrgTime1C.cpp #include "CpAvOpenhomeOrgTime1.h" #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace OpenHome; using namespace OpenHome::Net; class CpProxyAvOpenhomeOrgTime1C : public CpProxyC { public: CpProxyAvOpenhomeOrgTime1C(CpDeviceC aDevice); ~CpProxyAvOpenhomeOrgTime1C(); //CpProxyAvOpenhomeOrgTime1* Proxy() { return static_cast(iProxy); } void SyncTime(TUint& aTrackCount, TUint& aDuration, TUint& aSeconds); void BeginTime(FunctorAsync& aFunctor); void EndTime(IAsync& aAsync, TUint& aTrackCount, TUint& aDuration, TUint& aSeconds); void SetPropertyTrackCountChanged(Functor& aFunctor); void SetPropertyDurationChanged(Functor& aFunctor); void SetPropertySecondsChanged(Functor& aFunctor); void PropertyTrackCount(TUint& aTrackCount) const; void PropertyDuration(TUint& aDuration) const; void PropertySeconds(TUint& aSeconds) const; private: void TrackCountPropertyChanged(); void DurationPropertyChanged(); void SecondsPropertyChanged(); private: Mutex iLock; Action* iActionTime; PropertyUint* iTrackCount; PropertyUint* iDuration; PropertyUint* iSeconds; Functor iTrackCountChanged; Functor iDurationChanged; Functor iSecondsChanged; }; class SyncTimeAvOpenhomeOrgTime1C : public SyncProxyAction { public: SyncTimeAvOpenhomeOrgTime1C(CpProxyAvOpenhomeOrgTime1C& aProxy, TUint& aTrackCount, TUint& aDuration, TUint& aSeconds); virtual void CompleteRequest(IAsync& aAsync); virtual ~SyncTimeAvOpenhomeOrgTime1C() {}; private: CpProxyAvOpenhomeOrgTime1C& iService; TUint& iTrackCount; TUint& iDuration; TUint& iSeconds; }; SyncTimeAvOpenhomeOrgTime1C::SyncTimeAvOpenhomeOrgTime1C(CpProxyAvOpenhomeOrgTime1C& aProxy, TUint& aTrackCount, TUint& aDuration, TUint& aSeconds) : iService(aProxy) , iTrackCount(aTrackCount) , iDuration(aDuration) , iSeconds(aSeconds) { } void SyncTimeAvOpenhomeOrgTime1C::CompleteRequest(IAsync& aAsync) { iService.EndTime(aAsync, iTrackCount, iDuration, iSeconds); } CpProxyAvOpenhomeOrgTime1C::CpProxyAvOpenhomeOrgTime1C(CpDeviceC aDevice) : CpProxyC("av-openhome-org", "Time", 1, *reinterpret_cast(aDevice)) , iLock("MPCS") { OpenHome::Net::Parameter* param; iActionTime = new Action("Time"); param = new OpenHome::Net::ParameterUint("TrackCount"); iActionTime->AddOutputParameter(param); param = new OpenHome::Net::ParameterUint("Duration"); iActionTime->AddOutputParameter(param); param = new OpenHome::Net::ParameterUint("Seconds"); iActionTime->AddOutputParameter(param); Functor functor; functor = MakeFunctor(*this, &CpProxyAvOpenhomeOrgTime1C::TrackCountPropertyChanged); iTrackCount = new PropertyUint("TrackCount", functor); AddProperty(iTrackCount); functor = MakeFunctor(*this, &CpProxyAvOpenhomeOrgTime1C::DurationPropertyChanged); iDuration = new PropertyUint("Duration", functor); AddProperty(iDuration); functor = MakeFunctor(*this, &CpProxyAvOpenhomeOrgTime1C::SecondsPropertyChanged); iSeconds = new PropertyUint("Seconds", functor); AddProperty(iSeconds); } CpProxyAvOpenhomeOrgTime1C::~CpProxyAvOpenhomeOrgTime1C() { DestroyService(); delete iActionTime; } void CpProxyAvOpenhomeOrgTime1C::SyncTime(TUint& aTrackCount, TUint& aDuration, TUint& aSeconds) { SyncTimeAvOpenhomeOrgTime1C sync(*this, aTrackCount, aDuration, aSeconds); BeginTime(sync.Functor()); sync.Wait(); } void CpProxyAvOpenhomeOrgTime1C::BeginTime(FunctorAsync& aFunctor) { Invocation* invocation = Service()->Invocation(*iActionTime, aFunctor); TUint outIndex = 0; const Action::VectorParameters& outParams = iActionTime->OutputParameters(); invocation->AddOutput(new ArgumentUint(*outParams[outIndex++])); invocation->AddOutput(new ArgumentUint(*outParams[outIndex++])); invocation->AddOutput(new ArgumentUint(*outParams[outIndex++])); Invocable().InvokeAction(*invocation); } void CpProxyAvOpenhomeOrgTime1C::EndTime(IAsync& aAsync, TUint& aTrackCount, TUint& aDuration, TUint& aSeconds) { ASSERT(((Async&)aAsync).Type() == Async::eInvocation); Invocation& invocation = (Invocation&)aAsync; ASSERT(invocation.Action().Name() == Brn("Time")); Error::ELevel level; TUint code; const TChar* ignore; if (invocation.Error(level, code, ignore)) { THROW_PROXYERROR(level, code); } TUint index = 0; aTrackCount = ((ArgumentUint*)invocation.OutputArguments()[index++])->Value(); aDuration = ((ArgumentUint*)invocation.OutputArguments()[index++])->Value(); aSeconds = ((ArgumentUint*)invocation.OutputArguments()[index++])->Value(); } void CpProxyAvOpenhomeOrgTime1C::SetPropertyTrackCountChanged(Functor& aFunctor) { iLock.Wait(); iTrackCountChanged = aFunctor; iLock.Signal(); } void CpProxyAvOpenhomeOrgTime1C::SetPropertyDurationChanged(Functor& aFunctor) { iLock.Wait(); iDurationChanged = aFunctor; iLock.Signal(); } void CpProxyAvOpenhomeOrgTime1C::SetPropertySecondsChanged(Functor& aFunctor) { iLock.Wait(); iSecondsChanged = aFunctor; iLock.Signal(); } void CpProxyAvOpenhomeOrgTime1C::PropertyTrackCount(TUint& aTrackCount) const { AutoMutex a(GetPropertyReadLock()); CheckSubscribed(); aTrackCount = iTrackCount->Value(); } void CpProxyAvOpenhomeOrgTime1C::PropertyDuration(TUint& aDuration) const { AutoMutex a(GetPropertyReadLock()); CheckSubscribed(); aDuration = iDuration->Value(); } void CpProxyAvOpenhomeOrgTime1C::PropertySeconds(TUint& aSeconds) const { AutoMutex a(GetPropertyReadLock()); CheckSubscribed(); aSeconds = iSeconds->Value(); } void CpProxyAvOpenhomeOrgTime1C::TrackCountPropertyChanged() { ReportEvent(iTrackCountChanged); } void CpProxyAvOpenhomeOrgTime1C::DurationPropertyChanged() { ReportEvent(iDurationChanged); } void CpProxyAvOpenhomeOrgTime1C::SecondsPropertyChanged() { ReportEvent(iSecondsChanged); } THandle STDCALL CpProxyAvOpenhomeOrgTime1Create(CpDeviceC aDevice) { return new CpProxyAvOpenhomeOrgTime1C(aDevice); } void STDCALL CpProxyAvOpenhomeOrgTime1Destroy(THandle aHandle) { CpProxyAvOpenhomeOrgTime1C* proxyC = reinterpret_cast(aHandle); delete proxyC; } int32_t STDCALL CpProxyAvOpenhomeOrgTime1SyncTime(THandle aHandle, uint32_t* aTrackCount, uint32_t* aDuration, uint32_t* aSeconds) { CpProxyAvOpenhomeOrgTime1C* proxyC = reinterpret_cast(aHandle); ASSERT(proxyC != NULL); int32_t err = 0; try { proxyC->SyncTime(*aTrackCount, *aDuration, *aSeconds); } catch (ProxyError& ) { err = -1; *aTrackCount = 0; *aDuration = 0; *aSeconds = 0; } return err; } void STDCALL CpProxyAvOpenhomeOrgTime1BeginTime(THandle aHandle, OhNetCallbackAsync aCallback, void* aPtr) { CpProxyAvOpenhomeOrgTime1C* proxyC = reinterpret_cast(aHandle); ASSERT(proxyC != NULL); FunctorAsync functor = MakeFunctorAsync(aPtr, (OhNetFunctorAsync)aCallback); proxyC->BeginTime(functor); } int32_t STDCALL CpProxyAvOpenhomeOrgTime1EndTime(THandle aHandle, OhNetHandleAsync aAsync, uint32_t* aTrackCount, uint32_t* aDuration, uint32_t* aSeconds) { int32_t err = 0; CpProxyAvOpenhomeOrgTime1C* proxyC = reinterpret_cast(aHandle); ASSERT(proxyC != NULL); IAsync* async = reinterpret_cast(aAsync); ASSERT(async != NULL); try { proxyC->EndTime(*async, *aTrackCount, *aDuration, *aSeconds); } catch(...) { err = -1; } return err; } void STDCALL CpProxyAvOpenhomeOrgTime1SetPropertyTrackCountChanged(THandle aHandle, OhNetCallback aCallback, void* aPtr) { CpProxyAvOpenhomeOrgTime1C* proxyC = reinterpret_cast(aHandle); ASSERT(proxyC != NULL); Functor functor = MakeFunctor(aPtr, aCallback); proxyC->SetPropertyTrackCountChanged(functor); } void STDCALL CpProxyAvOpenhomeOrgTime1SetPropertyDurationChanged(THandle aHandle, OhNetCallback aCallback, void* aPtr) { CpProxyAvOpenhomeOrgTime1C* proxyC = reinterpret_cast(aHandle); ASSERT(proxyC != NULL); Functor functor = MakeFunctor(aPtr, aCallback); proxyC->SetPropertyDurationChanged(functor); } void STDCALL CpProxyAvOpenhomeOrgTime1SetPropertySecondsChanged(THandle aHandle, OhNetCallback aCallback, void* aPtr) { CpProxyAvOpenhomeOrgTime1C* proxyC = reinterpret_cast(aHandle); ASSERT(proxyC != NULL); Functor functor = MakeFunctor(aPtr, aCallback); proxyC->SetPropertySecondsChanged(functor); } int32_t STDCALL CpProxyAvOpenhomeOrgTime1PropertyTrackCount(THandle aHandle, uint32_t* aTrackCount) { CpProxyAvOpenhomeOrgTime1C* proxyC = reinterpret_cast(aHandle); ASSERT(proxyC != NULL); try { proxyC->PropertyTrackCount(*aTrackCount); } catch (ProxyNotSubscribed&) { return -1; } return 0; } int32_t STDCALL CpProxyAvOpenhomeOrgTime1PropertyDuration(THandle aHandle, uint32_t* aDuration) { CpProxyAvOpenhomeOrgTime1C* proxyC = reinterpret_cast(aHandle); ASSERT(proxyC != NULL); try { proxyC->PropertyDuration(*aDuration); } catch (ProxyNotSubscribed&) { return -1; } return 0; } int32_t STDCALL CpProxyAvOpenhomeOrgTime1PropertySeconds(THandle aHandle, uint32_t* aSeconds) { CpProxyAvOpenhomeOrgTime1C* proxyC = reinterpret_cast(aHandle); ASSERT(proxyC != NULL); try { proxyC->PropertySeconds(*aSeconds); } catch (ProxyNotSubscribed&) { return -1; } return 0; } 1-10 #pragma once #include "range_space.hpp" #include "../math/euclidean_space_3.hpp" namespace gfx { namespace generic { template class range_space_3 : public range_space { public: typedef euclidean_space_3 range_space_t; typedef typename range_space_t::vector_t vector_t; public: dynamic_reflectible(range_space_3, { register_super(range_space); }); public: inline int range_dimension() const { return 3; } }; } }firmware/sensorflare.cpp /*"name": "sensorflare", Author: "LPFraile <>", License: "BSD", Version: "0.0.1", Description: "Include your Particle Core on Sensorflare" File: source file */ #include "sensorflare.h" //Structure to keep in EEPROM memory the value of output pins struct dataStruct { int digitalPin[8]; struct pwmPin{ int pin; int value; }; pwmPin pwmoutput[8]; }; union { dataStruct outputData; char eeArray[sizeof(outputData)]; } EEPROMData; char stringvalue[40]; // Constructor //Constructor of Digital Output controller elements SensorFlare::DigitalOut::DigitalOut(int _number) { number = _number; state = LOW; } //Constructor of PWM Output controller elements SensorFlare::PWMOut::PWMOut(int _number) { number = _number; } //Constructor of Variable publish element by defult PUBLIC SensorFlare::VarPublish::VarPublish(String _name) { name = _name; name.toCharArray(Arrayname,name.length()+1); lastTime=0UL; property="PUBLIC"; } //Constructor of Variable publish element by choose between PUBLIC and PRIVATE SensorFlare::VarPublish::VarPublish(String _name,String _property) { name = _name; name.toCharArray(Arrayname,name.length()+1); lastTime=0UL; property=_property; } //Initializers that should be called in the `setup()` function //Initizalize the pin as output and the last value received void SensorFlare::DigitalOut::begin() { pinMode(number, OUTPUT); Spark.function("digital",controlPin); //Initialize the output with the last receive value from SensorFlare readEEPROM(); digitalWrite(number,EEPROMData.outputData.digitalPin[number]); } //Initizalize the pin as PWM output and the last value received void SensorFlare::PWMOut::begin() { pinMode(number, OUTPUT); Spark.function("pwm",controlPWM); //Initialize the output with the last receive value from Sensorflare readEEPROM(); analogWrite(number,EEPROMData.outputData.digitalPin[number]); for (int i=0;i<8;i++){ if (EEPROMData.outputData.pwmoutput[i].pin==number) { analogWrite(number,EEPROMData.outputData.pwmoutput[i].value); value=EEPROMData.outputData.pwmoutput[i].value; } } } //Initizalize the int variables void SensorFlare::VarPublish::begin(int _val) { Spark.variable(Arrayname, &_val, INT); } //Initizalize the float variables void SensorFlare::VarPublish::begin(float _val) { Spark.variable(Arrayname, &_val, INT); } // Main API functions that the library provides // typically called in `loop()` //Method that publish the variable (int) _val every _period time int SensorFlare::VarPublish::Publish(int _val, int _periode) { var_int=_val; periode=_periode*1000; unsigned long now = millis(); if (property=="PRIVATE"){ if (now-lastTime>periode) { lastTime = now; sprintf(stringvalue,"%u",var_int); Spark.publish(name,stringvalue,60,PRIVATE); } return 0; } else if (property=="PUBLIC"){ if (now-lastTime>periode) { lastTime = now; sprintf(stringvalue,"%u",var_int); Spark.publish(name,stringvalue); } return 1; } else{ return -1;//Return -1 if the variable could be publish because a mistake on the property } } //Method that publish the variable (float) _val every _period time int SensorFlare::VarPublish::Publish(float _val, int _periode) { var_float=_val; periode=_periode*1000; unsigned long now = millis(); if (property=="PRIVATE"){ if (now-lastTime>periode) { lastTime = now; sprintf(stringvalue,"%f",var_float); Spark.publish(name,stringvalue,60,PRIVATE); } return 0; } else if (property=="PUBLIC"){ if (now-lastTime>periode) { lastTime = now; sprintf(stringvalue,"%f",var_float); Spark.publish(name,stringvalue); } return 1; } else{ return -1; } } //Function for open/close pin //The structure of the receive command is pin: state where state is on or off int controlPin(String command) { int index=command.indexOf(":"); String pinout=command.substring(0,index); String state=command.substring(index+1); int pin=pinout.toInt(); if (state=="on") { digitalWrite(pin,HIGH); EEPROMData.outputData.digitalPin[pin]=1; writeEEPROM(); return 1; } else if (state=="off") { digitalWrite(pin,LOW); EEPROMData.outputData.digitalPin[pin]=0; writeEEPROM(); return 0; } else { //EEPROMData.eevar.state[pin]=-1; return -1;//return -1 if the command received has not the correct structure } } //Function that control the specific brightness of the led conected to specific pwmpin. //the structure of the command is pwmpin:brightness int controlPWM(String command) { int index=command.indexOf(":"); String pwmpin=command.substring(0,index); String val=command.substring(index+1); int pin=pwmpin.toInt(); int value=val.toInt(); if (value<256&&value>=0){ analogWrite(pin,value); if (pin==10){ EEPROMData.outputData.pwmoutput[2].pin=pin; EEPROMData.outputData.pwmoutput[2].value=value; } else if (pin==11){ EEPROMData.outputData.pwmoutput[3].pin=pin; EEPROMData.outputData.pwmoutput[3].value=value; } else if (pin>13&&pin<18){ EEPROMData.outputData.pwmoutput[pin-10].pin=pin; EEPROMData.outputData.pwmoutput[pin-10].value=value; } else if (pin<2){ EEPROMData.outputData.pwmoutput[pin].pin=pin; EEPROMData.outputData.pwmoutput[pin].value=value; } writeEEPROM(); return value; } else{ return -1;// return -1 if the pin sended on the command is not the PWM output ones } } //function to read from the EEPROM void readEEPROM(void) { for (int i=0; i0 /* * Copyright (C) 2009 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. 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 "core/html/canvas/CanvasRenderingContext.h" #include "core/html/canvas/CanvasContextCreationAttributes.h" #include "core/html/canvas/CanvasImageSource.h" #include "platform/RuntimeEnabledFeatures.h" #include "platform/weborigin/SecurityOrigin.h" #include "public/platform/Platform.h" namespace blink { CanvasRenderingContext::CanvasRenderingContext( CanvasRenderingContextHost* host, const CanvasContextCreationAttributes& attrs) : host_(host), color_params_(kLegacyCanvasColorSpace, kRGBA8CanvasPixelFormat), creation_attributes_(attrs) { if (RuntimeEnabledFeatures::ColorCanvasExtensionsEnabled()) { // Set the default color space to SRGB and continue CanvasColorSpace color_space = kSRGBCanvasColorSpace; if (creation_attributes_.colorSpace() == kRec2020CanvasColorSpaceName) color_space = kRec2020CanvasColorSpace; else if (creation_attributes_.colorSpace() == kP3CanvasColorSpaceName) color_space = kP3CanvasColorSpace; // For now, we only support RGBA8 (for SRGB) and F16 (for all). Everything // else falls back to SRGB + RGBA8. CanvasPixelFormat pixel_format = kRGBA8CanvasPixelFormat; if (creation_attributes_.pixelFormat() == kF16CanvasPixelFormatName) { pixel_format = kF16CanvasPixelFormat; } else { color_space = kSRGBCanvasColorSpace; pixel_format = kRGBA8CanvasPixelFormat; } color_params_ = CanvasColorParams(color_space, pixel_format); } // Make m_creationAttributes reflect the effective colorSpace, pixelFormat and // linearPixelMath rather than the requested one. creation_attributes_.setColorSpace(ColorSpaceAsString()); creation_attributes_.setPixelFormat(PixelFormatAsString()); creation_attributes_.setLinearPixelMath(color_params_.LinearPixelMath()); } WTF::String CanvasRenderingContext::ColorSpaceAsString() const { switch (color_params_.color_space()) { case kLegacyCanvasColorSpace: return kLegacyCanvasColorSpaceName; case kSRGBCanvasColorSpace: return kSRGBCanvasColorSpaceName; case kRec2020CanvasColorSpace: return kRec2020CanvasColorSpaceName; case kP3CanvasColorSpace: return kP3CanvasColorSpaceName; }; CHECK(false); return ""; } WTF::String CanvasRenderingContext::PixelFormatAsString() const { switch (color_params_.pixel_format()) { case kRGBA8CanvasPixelFormat: return kRGBA8CanvasPixelFormatName; case kRGB10A2CanvasPixelFormat: return kRGB10A2CanvasPixelFormatName; case kRGBA12CanvasPixelFormat: return kRGBA12CanvasPixelFormatName; case kF16CanvasPixelFormat: return kF16CanvasPixelFormatName; }; CHECK(false); return ""; } void CanvasRenderingContext::Dispose() { if (finalize_frame_scheduled_) { Platform::Current()->CurrentThread()->RemoveTaskObserver(this); } // HTMLCanvasElement and CanvasRenderingContext have a circular reference. // When the pair is no longer reachable, their destruction order is non- // deterministic, so the first of the two to be destroyed needs to notify // the other in order to break the circular reference. This is to avoid // an error when CanvasRenderingContext::didProcessTask() is invoked // after the HTMLCanvasElement is destroyed. if (host()) { host()->DetachContext(); host_ = nullptr; } } void CanvasRenderingContext::DidDraw(const SkIRect& dirty_rect) { host()->DidDraw(SkRect::Make(dirty_rect)); NeedsFinalizeFrame(); } void CanvasRenderingContext::DidDraw() { host()->DidDraw(); NeedsFinalizeFrame(); } void CanvasRenderingContext::NeedsFinalizeFrame() { if (!finalize_frame_scheduled_) { finalize_frame_scheduled_ = true; Platform::Current()->CurrentThread()->AddTaskObserver(this); } } void CanvasRenderingContext::DidProcessTask() { Platform::Current()->CurrentThread()->RemoveTaskObserver(this); finalize_frame_scheduled_ = false; // The end of a script task that drew content to the canvas is the point // at which the current frame may be considered complete. if (host()) { host()->FinalizeFrame(); } FinalizeFrame(); } CanvasRenderingContext::ContextType CanvasRenderingContext::ContextTypeFromId( const String& id) { if (id == "2d") return kContext2d; if (id == "experimental-webgl") return kContextExperimentalWebgl; if (id == "webgl") return kContextWebgl; if (id == "webgl2") return kContextWebgl2; if (id == "bitmaprenderer" && RuntimeEnabledFeatures::ExperimentalCanvasFeaturesEnabled()) { return kContextImageBitmap; } return kContextTypeCount; } CanvasRenderingContext::ContextType CanvasRenderingContext::ResolveContextTypeAliases( CanvasRenderingContext::ContextType type) { if (type == kContextExperimentalWebgl) return kContextWebgl; return type; } bool CanvasRenderingContext::WouldTaintOrigin( CanvasImageSource* image_source, SecurityOrigin* destination_security_origin) { const KURL& source_url = image_source->SourceURL(); bool has_url = (source_url.IsValid() && !source_url.IsAboutBlankURL()); if (has_url) { if (source_url.ProtocolIsData() || clean_urls_.Contains(source_url.GetString())) return false; if (dirty_urls_.Contains(source_url.GetString())) return true; } bool taint_origin = image_source->WouldTaintOrigin(destination_security_origin); if (has_url) { if (taint_origin) dirty_urls_.insert(source_url.GetString()); else clean_urls_.insert(source_url.GetString()); } return taint_origin; } DEFINE_TRACE(CanvasRenderingContext) { visitor->Trace(host_); } } // namespace blink /* * BlobGranuleVerifier.actor.cpp * * This source file is part of the FoundationDB open source project * * Copyright 2013-2022 Apple Inc. and the FoundationDB project authors * * 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 "contrib/fmt-8.1.1/include/fmt/format.h" #include "fdbclient/BlobGranuleReader.actor.h" #include "fdbclient/ManagementAPI.actor.h" #include "fdbclient/NativeAPI.actor.h" #include "fdbclient/ReadYourWrites.h" #include "fdbclient/SystemData.h" #include "fdbserver/BlobGranuleValidation.actor.h" #include "fdbserver/Knobs.h" #include "fdbserver/TesterInterface.actor.h" #include "fdbserver/workloads/workloads.actor.h" #include "flow/Error.h" #include "flow/IRandom.h" #include "flow/genericactors.actor.h" #include "flow/actorcompiler.h" // This must be the last #include. #define BGV_DEBUG true /* * This workload is designed to verify the correctness of the blob data produced by the blob workers. * As a read-only validation workload, it can piggyback off of other write or read/write workloads. * To verify the data outside FDB's 5 second MVCC window, it tests time travel reads by doing an initial comparison at * the latest read version, and then waiting a period of time to re-read the data from blob. * To catch availability issues with the blob worker, it does a request to each granule at the end of the test. */ struct BlobGranuleVerifierWorkload : TestWorkload { bool doSetup; double minDelay; double maxDelay; double testDuration; double timeTravelLimit; uint64_t timeTravelBufferSize; int threads; int64_t errors = 0; int64_t mismatches = 0; int64_t initialReads = 0; int64_t timeTravelReads = 0; int64_t timeTravelTooOld = 0; int64_t rowsRead = 0; int64_t bytesRead = 0; int64_t purges = 0; std::vector> clients; bool enablePurging; DatabaseConfiguration config; Reference bstore; AsyncVar>> granuleRanges; BlobGranuleVerifierWorkload(WorkloadContext const& wcx) : TestWorkload(wcx) { doSetup = !clientId; // only do this on the "first" client // FIXME: don't do the delay in setup, as that delays the start of all workloads minDelay = getOption(options, LiteralStringRef("minDelay"), 0.0); maxDelay = getOption(options, LiteralStringRef("maxDelay"), 0.0); testDuration = getOption(options, LiteralStringRef("testDuration"), 120.0); timeTravelLimit = getOption(options, LiteralStringRef("timeTravelLimit"), testDuration); timeTravelBufferSize = getOption(options, LiteralStringRef("timeTravelBufferSize"), 100000000); threads = getOption(options, LiteralStringRef("threads"), 1); enablePurging = getOption(options, LiteralStringRef("enablePurging"), false /*sharedRandomNumber % 2 == 0*/); ASSERT(threads >= 1); if (BGV_DEBUG) { printf("Initializing Blob Granule Verifier s3 stuff\n"); } try { if (g_network->isSimulated()) { if (BGV_DEBUG) { printf("Blob Granule Verifier constructing simulated backup container\n"); } bstore = BackupContainerFileSystem::openContainerFS("file://fdbblob/", {}, {}); } else { if (BGV_DEBUG) { printf("Blob Granule Verifier constructing backup container from %s\n", SERVER_KNOBS->BG_URL.c_str()); } bstore = BackupContainerFileSystem::openContainerFS(SERVER_KNOBS->BG_URL, {}, {}); if (BGV_DEBUG) { printf("Blob Granule Verifier constructed backup container\n"); } } } catch (Error& e) { if (BGV_DEBUG) { printf("Blob Granule Verifier got backup container init error %s\n", e.name()); } throw e; } } // FIXME: run the actual FDBCLI command instead of copy/pasting its implementation // Sets the whole user keyspace to be blobified ACTOR Future setUpBlobRange(Database cx, Future waitForStart) { state Reference tr = makeReference(cx); wait(waitForStart); loop { try { tr->setOption(FDBTransactionOptions::ACCESS_SYSTEM_KEYS); tr->setOption(FDBTransactionOptions::PRIORITY_SYSTEM_IMMEDIATE); tr->set(blobRangeChangeKey, deterministicRandom()->randomUniqueID().toString()); wait(krmSetRange(tr, blobRangeKeys.begin, KeyRange(normalKeys), LiteralStringRef("1"))); wait(tr->commit()); if (BGV_DEBUG) { printf("Successfully set up blob granule range for normalKeys\n"); } TraceEvent("BlobGranuleVerifierSetup"); return Void(); } catch (Error& e) { wait(tr->onError(e)); } } } std::string description() const override { return "BlobGranuleVerifier"; } Future setup(Database const& cx) override { return _setup(cx, this); } ACTOR Future _setup(Database cx, BlobGranuleVerifierWorkload* self) { if (!self->doSetup) { wait(delay(0)); return Void(); } wait(success(ManagementAPI::changeConfig(cx.getReference(), "blob_granules_enabled=1", true))); double initialDelay = deterministicRandom()->random01() * (self->maxDelay - self->minDelay) + self->minDelay; if (BGV_DEBUG) { printf("BGW setup initial delay of %.3f\n", initialDelay); } wait(self->setUpBlobRange(cx, delay(initialDelay))); return Void(); } ACTOR Future findGranules(Database cx, BlobGranuleVerifierWorkload* self) { loop { state Transaction tr(cx); loop { try { Standalone> allGranules = wait(tr.getBlobGranuleRanges(normalKeys)); self->granuleRanges.set(allGranules); break; } catch (Error& e) { wait(tr.onError(e)); } } wait(delay(deterministicRandom()->random01() * 10.0)); } } struct OldRead { KeyRange range; Version v; RangeResult oldResult; OldRead() {} OldRead(KeyRange range, Version v, RangeResult oldResult) : range(range), v(v), oldResult(oldResult) {} }; ACTOR Future killBlobWorkers(Database cx, BlobGranuleVerifierWorkload* self) { state Transaction tr(cx); state std::set knownWorkers; state bool first = true; loop { try { RangeResult r = wait(tr.getRange(blobWorkerListKeys, CLIENT_KNOBS->TOO_MANY)); state std::vector haltIds; state std::vector>> haltRequests; for (auto& it : r) { BlobWorkerInterface interf = decodeBlobWorkerListValue(it.value); if (first) { knownWorkers.insert(interf.id()); } if (knownWorkers.count(interf.id())) { haltIds.push_back(interf.id()); haltRequests.push_back(interf.haltBlobWorker.tryGetReply(HaltBlobWorkerRequest(1e6, UID()))); } } first = false; wait(waitForAll(haltRequests)); bool allPresent = true; for (int i = 0; i < haltRequests.size(); i++) { if (haltRequests[i].get().present()) { knownWorkers.erase(haltIds[i]); } else { allPresent = false; } } if (allPresent) { return Void(); } else { wait(delay(1.0)); } } catch (Error& e) { wait(tr.onError(e)); } } } ACTOR Future verifyGranules(Database cx, BlobGranuleVerifierWorkload* self, bool allowPurging) { state double last = now(); state double endTime = last + self->testDuration; state std::map timeTravelChecks; state int64_t timeTravelChecksMemory = 0; state Version prevPurgeVersion = -1; state UID dbgId = debugRandom()->randomUniqueID(); TraceEvent("BlobGranuleVerifierStart"); if (BGV_DEBUG) { printf("BGV thread starting\n"); } // wait for first set of ranges to be loaded wait(self->granuleRanges.onChange()); if (BGV_DEBUG) { printf("BGV got ranges\n"); } loop { try { state double currentTime = now(); state std::map::iterator timeTravelIt = timeTravelChecks.begin(); while (timeTravelIt != timeTravelChecks.end() && currentTime >= timeTravelIt->first) { state OldRead oldRead = timeTravelIt->second; timeTravelChecksMemory -= oldRead.oldResult.expectedSize(); timeTravelIt = timeTravelChecks.erase(timeTravelIt); if (prevPurgeVersion == -1) { prevPurgeVersion = oldRead.v; } // advance iterator before doing read, so if it gets error we don't retry it try { state Version newPurgeVersion = 0; state bool doPurging = allowPurging && deterministicRandom()->random01() < 0.5; if (doPurging) { Version maxPurgeVersion = oldRead.v; for (auto& it : timeTravelChecks) { maxPurgeVersion = std::min(it.second.v, maxPurgeVersion); } if (prevPurgeVersion < maxPurgeVersion) { newPurgeVersion = deterministicRandom()->randomInt64(prevPurgeVersion, maxPurgeVersion); prevPurgeVersion = std::max(prevPurgeVersion, newPurgeVersion); Key purgeKey = wait(cx->purgeBlobGranules(normalKeys, newPurgeVersion, false)); wait(cx->waitPurgeGranulesComplete(purgeKey)); self->purges++; } else { doPurging = false; } } std::pair>> reReadResult = wait(readFromBlob(cx, self->bstore, oldRead.range, 0, oldRead.v)); if (!compareFDBAndBlob(oldRead.oldResult, reReadResult, oldRead.range, oldRead.v, BGV_DEBUG)) { self->mismatches++; } self->timeTravelReads++; if (doPurging) { wait(self->killBlobWorkers(cx, self)); std::pair>> versionRead = wait(readFromBlob(cx, self->bstore, oldRead.range, 0, prevPurgeVersion)); try { Version minSnapshotVersion = newPurgeVersion; for (auto& it : versionRead.second) { minSnapshotVersion = std::min(minSnapshotVersion, it.snapshotVersion); } std::pair>> versionRead = wait(readFromBlob(cx, self->bstore, oldRead.range, 0, minSnapshotVersion - 1)); ASSERT(false); } catch (Error& e) { if (e.code() == error_code_actor_cancelled) { throw; } ASSERT(e.code() == error_code_blob_granule_transaction_too_old); } } } catch (Error& e) { if (e.code() == error_code_blob_granule_transaction_too_old) { self->timeTravelTooOld++; // TODO: add debugging info for when this is a failure } } } // pick a random range int rIndex = deterministicRandom()->randomInt(0, self->granuleRanges.get().size()); state KeyRange range = self->granuleRanges.get()[rIndex]; state std::pair fdb = wait(readFromFDB(cx, range)); std::pair>> blob = wait(readFromBlob(cx, self->bstore, range, 0, fdb.second)); if (compareFDBAndBlob(fdb.first, blob, range, fdb.second, BGV_DEBUG)) { // TODO: bias for immediately re-reading to catch rollback cases double reReadTime = currentTime + deterministicRandom()->random01() * self->timeTravelLimit; int memory = fdb.first.expectedSize(); if (reReadTime <= endTime && timeTravelChecksMemory + memory <= (self->timeTravelBufferSize / self->threads)) { timeTravelChecks[reReadTime] = OldRead(range, fdb.second, fdb.first); timeTravelChecksMemory += memory; } } else { self->mismatches++; } self->rowsRead += fdb.first.size(); self->bytesRead += fdb.first.expectedSize(); self->initialReads++; } catch (Error& e) { if (e.code() == error_code_operation_cancelled) { throw; } if (e.code() != error_code_blob_granule_transaction_too_old && BGV_DEBUG) { printf("BGVerifier got unexpected error %s\n", e.name()); } self->errors++; } // wait(poisson(&last, 5.0)); wait(poisson(&last, 0.1)); } } Future start(Database const& cx) override { clients.reserve(threads + 1); clients.push_back(timeout(findGranules(cx, this), testDuration, Void())); if (enablePurging && clientId == 0) { clients.push_back( timeout(reportErrors(verifyGranules(cx, this, true), "BlobGranuleVerifier"), testDuration, Void())); } else if (!enablePurging) { for (int i = 0; i < threads; i++) { clients.push_back(timeout( reportErrors(verifyGranules(cx, this, false), "BlobGranuleVerifier"), testDuration, Void())); } } return delay(testDuration); } // handle retries + errors // It's ok to reset the transaction here because its read version is only used for reading the granule mapping from // the system keyspace ACTOR Future doGrv(Transaction* tr) { loop { try { Version readVersion = wait(tr->getReadVersion()); return readVersion; } catch (Error& e) { wait(tr->onError(e)); } } } ACTOR Future _check(Database cx, BlobGranuleVerifierWorkload* self) { // check error counts, and do an availability check at the end state Transaction tr(cx); state Version readVersion = wait(self->doGrv(&tr)); state Version startReadVersion = readVersion; state int checks = 0; state KeyRange last; state bool availabilityPassed = true; state Standalone> allRanges; if (self->granuleRanges.get().empty()) { if (BGV_DEBUG) { fmt::print("Waiting to get granule ranges for check\n"); } state Future rangeFetcher = self->findGranules(cx, self); loop { wait(self->granuleRanges.onChange()); if (!self->granuleRanges.get().empty()) { break; } } rangeFetcher.cancel(); if (BGV_DEBUG) { fmt::print("Got granule ranges for check\n"); } } allRanges = self->granuleRanges.get(); for (auto& range : allRanges) { state KeyRange r = range; if (BGV_DEBUG) { fmt::print("Final availability check [{0} - {1}) @ {2}\n", r.begin.printable(), r.end.printable(), readVersion); } try { loop { try { Standalone> chunks = wait(tr.readBlobGranules(r, 0, readVersion)); ASSERT(chunks.size() > 0); last = chunks.back().keyRange; checks += chunks.size(); break; } catch (Error& e) { // it's possible for blob granules to never get opened for the entire test due to fault // injection. If we get blob_granule_transaction_too_old, for the latest read version, the // granule still needs to open. Wait for that to happen at a higher read version. if (e.code() == error_code_blob_granule_transaction_too_old) { wait(delay(1.0)); tr.reset(); Version rv = wait(self->doGrv(&tr)); readVersion = rv; } else { wait(tr.onError(e)); } } } } catch (Error& e) { if (e.code() == error_code_actor_cancelled) { throw; } if (e.code() == error_code_end_of_stream) { break; } if (BGV_DEBUG) { fmt::print("BG Verifier failed final availability check for [{0} - {1}) @ {2} with error {3}. Last " "Success=[{4} - {5})\n", r.begin.printable(), r.end.printable(), readVersion, e.name(), last.begin.printable(), last.end.printable()); } availabilityPassed = false; break; } } if (BGV_DEBUG && startReadVersion != readVersion) { fmt::print("Availability check updated read version from {0} to {1}\n", startReadVersion, readVersion); } bool result = availabilityPassed && self->mismatches == 0 && (checks > 0) && (self->timeTravelTooOld == 0); fmt::print("Blob Granule Verifier {0} {1}:\n", self->clientId, result ? "passed" : "failed"); fmt::print(" {} successful final granule checks\n", checks); fmt::print(" {} failed final granule checks\n", availabilityPassed ? 0 : 1); fmt::print(" {} mismatches\n", self->mismatches); fmt::print(" {} time travel too old\n", self->timeTravelTooOld); fmt::print(" {} errors\n", self->errors); fmt::print(" {} initial reads\n", self->initialReads); fmt::print(" {} time travel reads\n", self->timeTravelReads); fmt::print(" {} rows\n", self->rowsRead); fmt::print(" {} bytes\n", self->bytesRead); fmt::print(" {} purges\n", self->purges); // FIXME: add above as details to trace event TraceEvent("BlobGranuleVerifierChecked").detail("Result", result); // For some reason simulation is still passing when this fails?.. so assert for now ASSERT(result); return result; } Future check(Database const& cx) override { return _check(cx, this); } void getMetrics(std::vector& m) override {} }; WorkloadFactory BlobGranuleVerifierWorkloadFactory("BlobGranuleVerifier"); #include #include "example.h" #include "example_c.h" TEST(example, subtract) { double res; res = subtract_numbers(1.0, 2.0); ASSERT_NEAR(res, -1.0, 1.0e-11); } TEST(example, c_subtract) { double res; res = c_subtract_numbers(1.0, 2.0); ASSERT_NEAR(res, -1.0, 1.0e-11); } // // Created by istvan on 6/20/17. // #include namespace echoio{ namespace components{ IODeviceThread::IODeviceThread(const _component_conf_j &deviceConfig) : DeviceThread(deviceConfig) { _consoleRep = zsock_new(ZMQ_REP); zsock_bind(_consoleRep, "tcp://127.0.0.1:5556"); AddSocketToPoller(_consoleRep); } void IODeviceThread::Run() { std::cout << "DevThread::Run()" <GetSocket(); while (!IsTerminated()) { void* port = PollDeviceThreadPorts(100); if (port == triggerSocket){ zmsg_t* msg = zmsg_recv(port); zmsg_send(&msg, _consoleRep); } else if (port == _consoleRep){ zmsg_t* msg = zmsg_recv(port); SendTrigger(&msg); } } } bool IODeviceThread::SendTrigger(zmsg_t** message) { return SendMessageOnPort(message, INSIDE_TRIGGER); } IODeviceThread::~IODeviceThread() { Terminate(); zclock_sleep(100); } } }#include #include #include #include #include class FrameGrabber { public: FrameGrabber(int width, int height, int fps=0); ~FrameGrabber(); int getNumberOfFrames(void); void getColor(cimg_library::CImg &color); void getDepth(cimg_library::CImg &depth); private: openni::PlaybackControl* pbc; openni::Device* rgbd_camera_; openni::VideoStream *depth_stream_; openni::VideoStream *color_stream_; openni::VideoFrameRef depth_FrameRef_; openni::VideoFrameRef color_FrameRef_; }; int main(int argc, char* argv[]) { //Parameters for an SDFtracker object SDF_Parameters myParameters; Vector6d poseVector; myParameters.interactive_mode = true; myParameters.resolution = 0.02; myParameters.Dmax = 0.1; myParameters.Dmin = -0.1; myParameters.raycast_steps = 12; // The sizes can be different from each other // +Y is up +Z is forward. myParameters.XSize = 128; myParameters.YSize = 128; myParameters.ZSize = 128; myParameters.image_width = 320; myParameters.image_height = 240; int fps = 60; //Pose Offset as a transformation matrix Eigen::Matrix4d currentTransformation = Eigen::MatrixXd::Identity(4,4); //create the tracker object SDFTracker* myTracker = new SDFTracker(myParameters); myTracker->SetCurrentTransformation(currentTransformation); //create the camera object FrameGrabber* myCamera = new FrameGrabber(myParameters.image_width, myParameters.image_height, fps); cimg_library::CImg depth_img(myParameters.image_width, myParameters.image_height,1,1); cimg_library::CImg rgb_img(myParameters.image_width, myParameters.image_height,1,3); unsigned int frame_nr = 0; unsigned int frame_limit = (myCamera->getNumberOfFrames()) ? myCamera->getNumberOfFrames() : 100000; do { // auto tic = std::chrono::high_resolution_clock::now(); myCamera->getDepth(depth_img); myTracker->UpdateDepth(depth_img); poseVector = myTracker->EstimatePoseFromDepth(); currentTransformation = GetMat4_rodrigues_smallangle(poseVector)*myTracker->GetCurrentTransformation(); // Twist(poseVector).exp()*myTracker->GetCurrentTransformation(); myTracker->SetCurrentTransformation(currentTransformation); myTracker->FuseDepth(); myTracker->Render(); // toc = std::chrono::high_resolution_clock::now(); // std::cout << std::chrono::duration_cast(toc - tic).count() << "ms \n"; if(++frame_nr%10 == 0) { myTracker->checkTranslation(1); } }while(!myTracker->Quit() && frame_nr < frame_limit); delete myCamera; delete myTracker; exit(0); } int FrameGrabber::getNumberOfFrames(void){return pbc->getNumberOfFrames(*depth_stream_);}; FrameGrabber::FrameGrabber(int width, int height, int fps) { if (fps==0) { if (width==640 && height ==480) fps = 30; else if (width==320 && height ==240) fps = 60; else{ fps=25; } std::cout << "fps not set, assuming " << fps << " to match resolution of "<< width << "x" << height << std::endl; } int rc = openni::OpenNI::initialize(); if (rc != openni::STATUS_OK) { printf("Initialize failed\n%s\n", openni::OpenNI::getExtendedError()); exit(1); } std::cout << "OpenNI initialized" << std::endl; rgbd_camera_ = new openni::Device(); color_stream_ = new openni::VideoStream; depth_stream_ = new openni::VideoStream; openni::VideoMode vm; rc = rgbd_camera_->open(openni::ANY_DEVICE); // rc = rgbd_camera_->open("Captured.oni"); pbc = rgbd_camera_->getPlaybackControl(); pbc->setSpeed(-1); if (rc != openni::STATUS_OK) { printf("Couldn't open device\n%s\n", openni::OpenNI::getExtendedError()); exit(2); } std::cout << "Opened device" << std::endl; rc = depth_stream_->create(*rgbd_camera_, openni::SENSOR_DEPTH); if (rc != openni::STATUS_OK) { printf("Couldn't create depth stream\n%s\n", openni::OpenNI::getExtendedError()); exit(3); } std::cout << "Created depth stream" << std::endl; for(int idx = 0; idx< depth_stream_->getSensorInfo().getSupportedVideoModes().getSize(); idx++) { vm = depth_stream_->getSensorInfo().getSupportedVideoModes()[idx]; if( (height == vm.getResolutionY()) && (width == vm.getResolutionX()) && (fps == vm.getFps()) && (vm.getPixelFormat()==openni::PIXEL_FORMAT_DEPTH_1_MM)) { std::cout << "matching depth mode :" << vm.getResolutionX()<<"x"<setVideoMode(vm); if (rc != openni::STATUS_OK) printf("Couldn't set desired video mode \n%s\n", openni::OpenNI::getExtendedError()); rc = depth_stream_->setMirroringEnabled(TRUE); if (rc != openni::STATUS_OK) printf("Couldn't set mirroring \n%s\n", openni::OpenNI::getExtendedError()); rc = color_stream_->create(*rgbd_camera_, openni::SENSOR_COLOR); if (rc != openni::STATUS_OK) { printf("Couldn't create color stream\n%s\n", openni::OpenNI::getExtendedError()); exit(5); } std::cout << "Created color stream" << std::endl; rc = rgbd_camera_->setImageRegistrationMode(openni::IMAGE_REGISTRATION_DEPTH_TO_COLOR); if (rc != openni::STATUS_OK) printf("Couldn't enable depth registration \n%s\n", openni::OpenNI::getExtendedError()); rc = rgbd_camera_->setDepthColorSyncEnabled(true); if (rc != openni::STATUS_OK) printf("Couldn't enable frame syncronization \n%s\n", openni::OpenNI::getExtendedError()); for(int idx = 0; idx< color_stream_->getSensorInfo().getSupportedVideoModes().getSize(); idx++) { vm = color_stream_->getSensorInfo().getSupportedVideoModes()[idx]; if( (height == vm.getResolutionY()) && (width == vm.getResolutionX()) && (fps == vm.getFps()) && (vm.getPixelFormat()==openni::PIXEL_FORMAT_RGB888)) { std::cout << "found matching color mode :" << vm.getResolutionX()<<"x"<setVideoMode(vm); if (rc != openni::STATUS_OK) printf("Couldn't set desired video mode \n%s\n", openni::OpenNI::getExtendedError()); rc = color_stream_->setMirroringEnabled(TRUE); if (rc != openni::STATUS_OK) printf("Couldn't set mirroring \n%s\n", openni::OpenNI::getExtendedError()); rc = depth_stream_->start(); if (rc != openni::STATUS_OK) { printf("Couldn't start the depth stream\n%s\n", openni::OpenNI::getExtendedError()); exit(4); } std::cout << "Started depth stream" << std::endl; rc = color_stream_->start(); if (rc != openni::STATUS_OK) { printf("Couldn't start the color stream\n%s\n", openni::OpenNI::getExtendedError()); exit(6); } std::cout << "Started color stream" << std::endl; std::cout << "Finished setting up camera " << std::endl; }; FrameGrabber::~FrameGrabber() { // depth_stream_->removeNewFrameListener(this); depth_stream_->stop(); depth_stream_->destroy(); delete depth_stream_; // color_stream_->removeNewFrameListener(this); color_stream_->stop(); color_stream_->destroy(); delete color_stream_; rgbd_camera_->close(); delete rgbd_camera_; openni::OpenNI::shutdown(); }; void FrameGrabber::getDepth(cimg_library::CImg &depthmap) { depth_stream_->readFrame(&depth_FrameRef_); const openni::DepthPixel* pDepth = (const openni::DepthPixel*)depth_FrameRef_.getData(); // if(depthmap._data == NULL) // depthmap = cimg_library::CImg(depth_FrameRef_.getHeight(), depth_FrameRef_.getWidth(),1); #pragma omp parallel for collapse(2) schedule(static) for(int i=0; i::quiet_NaN() : float(pDepth[i*depth_FrameRef_.getWidth() + j])/1000; // depthmap(j,i) = 10*(pDepth[i*depth_FrameRef_.getWidth() + j] == 0) ? std::numeric_limits::quiet_NaN() : float(pDepth[i*depth_FrameRef_.getWidth() + j])/1000; } }; void FrameGrabber::getColor(cimg_library::CImg &rgbImage) { color_stream_->readFrame(&color_FrameRef_); const openni::RGB888Pixel* pColor = (const openni::RGB888Pixel*)color_FrameRef_.getData(); // if(rgbImage._data == NULL) // rgbImage = cimg_library::CImg(color_FrameRef_.getWidth(), color_FrameRef_.getHeight(), 1); #pragma omp parallel for collapse(2) schedule(static) for(int i=0; i0 // Copyright (c) 2014-2021 Dr. and // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt) #ifndef TAO_PEGTL_SRC_TEST_PEGTL_MAIN_HPP #define TAO_PEGTL_SRC_TEST_PEGTL_MAIN_HPP #include #include int main( int /*unused*/, char** argv ) { TAO_PEGTL_NAMESPACE::unit_test(); if( TAO_PEGTL_NAMESPACE::failed != 0 ) { std::cerr << "pegtl: unit test " << argv[ 0 ] << " failed " << TAO_PEGTL_NAMESPACE::failed << std::endl; // LCOV_EXCL_LINE } return ( TAO_PEGTL_NAMESPACE::failed == 0 ) ? EXIT_SUCCESS : EXIT_FAILURE; } #endif // Copyright (c) 2009-2016 The Regents of the University of Michigan // This file is part of the HOOMD-blue project, released under the BSD 3-Clause License. // Include the defined classes that are to be exported to python #include "IntegratorHPMC.h" #include "IntegratorHPMCMono.h" #include "IntegratorHPMCMonoImplicit.h" #include "ComputeFreeVolume.h" #include "ShapeSphere.h" #include "ShapeConvexPolygon.h" #include "ShapePolyhedron.h" #include "ShapeConvexPolyhedron.h" #include "ShapeSpheropolyhedron.h" #include "ShapeSpheropolygon.h" #include "ShapeSimplePolygon.h" #include "ShapeEllipsoid.h" #include "ShapeFacetedSphere.h" #include "ShapeSphinx.h" #include "AnalyzerSDF.h" #include "ShapeUnion.h" #include "ExternalField.h" #include "ExternalFieldWall.h" #include "ExternalFieldLattice.h" #include "ExternalFieldComposite.h" #include "UpdaterExternalFieldWall.h" #include "UpdaterRemoveDrift.h" #include "UpdaterMuVT.h" #include "UpdaterMuVTImplicit.h" #ifdef ENABLE_CUDA #include "IntegratorHPMCMonoGPU.h" #include "IntegratorHPMCMonoImplicitGPU.h" #include "ComputeFreeVolumeGPU.h" #endif namespace py = pybind11; using namespace hpmc; using namespace hpmc::detail; namespace hpmc { //! Export the base HPMCMono integrators void export_convex_polyhedron16(py::module& m) { export_IntegratorHPMCMono< ShapeConvexPolyhedron<16> >(m, "IntegratorHPMCMonoConvexPolyhedron16"); export_IntegratorHPMCMonoImplicit< ShapeConvexPolyhedron<16> >(m, "IntegratorHPMCMonoImplicitConvexPolyhedron16"); export_ComputeFreeVolume< ShapeConvexPolyhedron<16> >(m, "ComputeFreeVolumeConvexPolyhedron16"); export_AnalyzerSDF< ShapeConvexPolyhedron<16> >(m, "AnalyzerSDFConvexPolyhedron16"); export_UpdaterMuVT< ShapeConvexPolyhedron<16> >(m, "UpdaterMuVTConvexPolyhedron16"); export_UpdaterMuVTImplicit< ShapeConvexPolyhedron<16> >(m, "UpdaterMuVTImplicitConvexPolyhedron16"); export_ExternalFieldInterface >(m, "ExternalFieldConvexPolyhedron16"); export_LatticeField >(m, "ExternalFieldLatticeConvexPolyhedron16"); export_ExternalFieldComposite >(m, "ExternalFieldCompositeConvexPolyhedron16"); export_RemoveDriftUpdater >(m, "RemoveDriftUpdaterConvexPolyhedron16"); export_ExternalFieldWall >(m, "WallConvexPolyhedron16"); export_UpdaterExternalFieldWall >(m, "UpdaterExternalFieldWallConvexPolyhedron16"); #ifdef ENABLE_CUDA export_IntegratorHPMCMonoGPU< ShapeConvexPolyhedron<16> >(m, "IntegratorHPMCMonoGPUConvexPolyhedron16"); export_IntegratorHPMCMonoImplicitGPU< ShapeConvexPolyhedron<16> >(m, "IntegratorHPMCMonoImplicitGPUConvexPolyhedron16"); export_ComputeFreeVolumeGPU< ShapeConvexPolyhedron<16> >(m, "ComputeFreeVolumeGPUConvexPolyhedron16"); #endif } } #include #include #include "core/log.h" #include "core/types.h" #include "cr_util.h" #define OBJ_STR_LEN 6 namespace cr { DataType toDataType(const std::string& str) { if (str.size() == 0) { return DataType::NONE; } else if (str == "string") { return DataType::STRING; } else if (str == "blob") { return DataType::BLOB; } else if (str.size() > OBJ_STR_LEN && str.substr(0, OBJ_STR_LEN) == "object") { return DataType::OBJECT; } else if (str == "i8" || str == "int8_t") { return DataType::I8; } else if (str == "ui8" || str == "uint8_t" || str == "byte") { return DataType::UI8; } else if (str == "i16" || str == "int16_t") { return DataType::I16; } else if (str == "ui16" || str == "uint16_t") { return DataType::UI16; } else if (str == "i32" || str == "int32_t" || str == "int") { return DataType::I32; } else if (str == "ui32" || str == "uint32_t") { return DataType::UI32; } else if (str == "i64" || str == "int64_t") { return DataType::I64; } else if (str == "ui64" || str == "uint64_t") { return DataType::UI64; } else if (str == "f32" || str == "float") { return DataType::F32; } else if (str == "f64" || str == "double") { return DataType::F64; } else if (str == "bool" || str == "boolean") { return DataType::BOOLEAN; } else { throw CRException( "Unrecognized DataType: %s", str.c_str() ); } } // toLanguage Language toLanguage( const char* str ) { if ( nullptr == str || strcmp( str, "" ) == 0 ) { return Language::NONE; } else if ( (strcmp( str, "C++" ) == 0) || (strcmp( str, "CPP" ) == 0) ) { return Language::CPP; } else { throw CRException( "Unrecognized Language: %s", str ); } } // toAccessPrivacy AccessPrivacy toAccessPrivacy( const char* str ) { if ( nullptr == str || strcmp( str, "" ) == 0 ) { return AccessPrivacy::NONE; } else if ( strcmp( str, "private" ) == 0 ) { return AccessPrivacy::PRIVATE; } else if ( strcmp( str, "protected" ) == 0 ) { return AccessPrivacy::PROTECTED; } else if ( strcmp( str, "public" ) == 0 ) { return AccessPrivacy::PUBLIC; } else { throw CRException( "Unrecognized AccessPrivacy: %s", str ); } } // toSerializableSpecification SerializableSpecification toSerializableSpecification( const char* str ) { if ( str == nullptr || str[0] == 0x00 ) { return SerializableSpecification::NONE; } else if ( (strcmp( str, "yes" ) == 0 ) || (strcmp( str, "true" )) ) { return SerializableSpecification::YES; } else if ( (strcmp( str, "no" ) == 0 ) || (strcmp( str, "false" )) ) { return SerializableSpecification::NO; } else { return SerializableSpecification::NONE; } } // capitalize char capitalize( char c ) { return c - (97 - 65); } // getTimeMillis ui64 getTimeMillis() { // here's a taste of the T in STL... std::chrono::time_point time = std::chrono::system_clock::now(); return std::chrono::duration_cast(time.time_since_epoch()).count(); } }; include/hogl/detail/record.hpp0 /* Copyright (c) 2015, <> 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. 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. */ /** * @file hogl/detail/record.hpp * Log record implementationn details. */ #ifndef HOGL_DETAIL_RECORD_HPP #define HOGL_DETAIL_RECORD_HPP #include #include #include #include #include #include #include namespace hogl { class area; /** * Log record. */ struct record { enum { NARGS = 16 }; const hogl::area *area; hogl::timestamp timestamp; uint64_t seqnum :52; uint64_t section :12; uint64_t argtype; union { uint64_t u64; uint32_t u32; struct { uint32_t offset; uint32_t len; } data; } argval[NARGS]; // Note that this layout is important. // It ensures that the record with 4 arguments fits nicely into // the 64 byte cacheline. /** * Get the size of the record header portion. * i.e. excluding the argument storage. */ static unsigned int header_size() { return sizeof(record) - sizeof(uint64_t) * NARGS; } /** * Set argument type * @param i index (position) of the argument (zero based) * @param type argument type */ void set_arg_type(unsigned int i, unsigned int type) { argtype |= (uint64_t) (type & 0xf) << (i * 4); } /** * Get argument type. * @param i index (position) of the argument (zero based) * @return a argument reference */ unsigned int get_arg_type(unsigned int i) const { return (argtype >> (i * 4)) & 0xf; } /** * Clear argument type * @param i index (position) of the argument (zero based) */ void clear_arg_type(unsigned int i) { argtype &= ~((uint64_t) 0xf << (i * 4)); } /** * Set argument value. * @param i index (position) of the argument (zero based) * @param val argument value */ void set_arg_val32(unsigned int i, uint32_t val) { argval[i].u32 = val; } /** * Set argument value. * @param i index (position) of the argument (zero based) * @param val argument value */ void set_arg_val64(unsigned int i, uint64_t val) { argval[i].u64 = val; } /** * Set argument data (encoded in value) * @param i index (position) of the argument (zero based) * @param offset offset in the record buffer * @param len size of the data in bytes */ void set_arg_data(unsigned int i, uint32_t offset, uint32_t len) { argval[i].data.offset = offset; argval[i].data.len = len; } /** * Get argument 32bit value * @param i index (position) of the argument (zero based) */ uint32_t get_arg_val32(unsigned int i) const { return argval[i].u32; } /** * Get argument 64bit value * @param i index (position) of the argument (zero based) */ uint64_t get_arg_val64(unsigned int i) const { return argval[i].u64; } /** * Get argument data. * @param i index (position) of the argument (zero based) * @param len [out] data length. * @return pointer to argument data * @warn This function works only with arguments that have data: CSTR, HEXDUMP, RAW. \ * It does not validate argument type for performance reasons. */ const uint8_t *get_arg_data(unsigned int i, unsigned int &len) const { len = argval[i].data.len; return (const uint8_t*) this->argval + argval[i].data.offset; } /** * Copy cstr into the record. * Adds truncation marker if the string is longer than the available room. * Copied string is guarantied to be null-terminated. * @param i argument index * @param str pointer to the source string * @param len length of the source string * @param tailroom amount of tailroom left in the record buffer * @param offset offset in the record buffer * @return number of bytes used in the record buffer */ unsigned int copy_cstr(unsigned int i, const uint8_t *str, unsigned int len, unsigned int tailroom, unsigned int offset) { unsigned int room = tailroom - offset; if (!len || !room) { set_arg_data(i, 0, 0); return 0; } --room; // Save room for null-terminator uint8_t *dst = (uint8_t *) this->argval + offset; unsigned int n = len; // Copy len if (n > room) { // Doesn't fit. Add truncation marker (if possible) n = len = room; if (n > 3) { n -= 3; memcpy(dst + n, ">>>", 3); } } memcpy(dst, str, n); dst[len] = '\0'; set_arg_data(i, offset, len); return len + 1; } /** * Copy data into the record. * @param i argument index * @param data pointer to the data buffer * @param len length of the data * @param tailroom amount of tailroom left in the record buffer * @param offset offset in the record buffer * @return number of bytes used in the record buffer */ unsigned int copy_data(unsigned int i, const uint8_t *data, unsigned int len, unsigned int tailroom, unsigned int offset) { unsigned int room = tailroom - offset; len = len > room ? room : len; memcpy((uint8_t *) this->argval + offset, (const void *) data, len); set_arg_data(i, offset, len); return len; } /** * Set record argument * @param i index (position) of the argument (zero based) * @param a argument itself * @param tailroom number of bytes available at the tail of the record (used as generic buffer). * @param offset offset in the buffer (used for packing strings and complex args) */ hogl_force_inline void set_arg(unsigned int i, const hogl::arg a, unsigned int tailroom, unsigned int &offset) { // In case of the fully inlined version (ie when an entire record posting stack // is inlined) a.type is known at compile time, which means all type checks // are resolved at compile time. if (a.type == a.NONE) return; set_arg_type(i, a.type); if (a.type == a.HEXDUMP || a.type == a.RAW) { offset += copy_data(i, (const uint8_t *) a.val, a.len, tailroom, offset); return; } if (a.type == a.CSTR) { offset += copy_cstr(i, (const uint8_t *) a.val, a.len, tailroom, offset); return; } if (a.is_32bit()) set_arg_val32(i, a.val); else set_arg_val64(i, a.val); } /** * Populate record arguments * @param tailroom number of bytes available at the tail of the record (used as generic buffer). * @param arg0 ... arg1 argument list */ hogl_force_inline void set_args(unsigned int tailroom, __hogl_long_arg_list(16)) { // Compute the number of valid arguments (resolved at compile time) unsigned int n = 0; #define __hogl_record_valid_arg(i) n += (a##i.type != arg::NONE) HOGL_PP_REPS(16, __hogl_record_valid_arg, ;); // Compute offset based on the number of valid arguments unsigned int offset = n * sizeof(uint64_t); // Populate arguments argtype = 0; #define __hogl_record_set_arg(i) set_arg(i, a##i, tailroom, offset) HOGL_PP_REPS(16, __hogl_record_set_arg, ;); } /** * Populate record arguments * @param tailroom number of bytes available at the tail of the record (used as generic buffer). * @param ap reference to the pre-processed and packed arguments */ hogl_force_inline void set_args(unsigned int tailroom, const argpack &ap) { unsigned int n = ap.nargs(); unsigned int offset = n * sizeof(uint64_t); argtype = ap.argtype; for (unsigned int i=0; i < n; i++) { unsigned int type = ap.get_arg_type(i); const uint8_t *data; unsigned int len; if (type == arg::HEXDUMP || type == arg::RAW) { data = ap.get_arg_data(i, len); offset += copy_data(i, data, len, tailroom, offset); } else if (type == arg::CSTR) { data = ap.get_arg_data(i, len); offset += copy_cstr(i, data, len, tailroom, offset); } else set_arg_val64(i, ap.get_arg_val64(i)); } } /** * Clear the record */ void clear() { area = 0; timestamp = 0; seqnum = 0; section = 0; argtype = 0; } /** * Populate special record */ void special(uint32_t type, uint64_t arg1 = 0, uint64_t arg2 = 0) { area = 0; section = 0xfff; argtype = type; argval[0].u64 = 0; argval[1].u64 = arg1; argval[2].u64 = arg2; } /** * Check for special record * @return true if the record is special, false otherwise */ bool special() { if (hogl_likely(area != 0 || section != 0xfff)) return false; return true; } /** * Acknowledge special record */ void ack() { volatile uint64_t *a0 = &argval[0].u64; *a0 = 0x7e7f; } /** * Check if the record was acked * @return true if the record was acked, false otherwise */ bool acked() const { volatile const uint64_t *a0 = &argval[0].u64; return *a0 == 0x7e7f; } /** * Construct new record. */ record() { clear(); } }; } // namespace hogl #endif // HOGL_DETAIL_RECORD_HPP Engine/Source/Runtime/RenderCore/Private/RenderUtils.cpp1-10 // Copyright 1998-2017 Epic Games, Inc. All Rights Reserved. #include "RenderUtils.h" #include "Containers/ResourceArray.h" #include "Containers/DynamicRHIResourceArray.h" #include "RenderResource.h" const uint16 GCubeIndices[12*3] = { 0, 2, 3, 0, 3, 1, 4, 5, 7, 4, 7, 6, 0, 1, 5, 0, 5, 4, 2, 6, 7, 2, 7, 3, 0, 4, 6, 0, 6, 2, 1, 3, 7, 1, 7, 5, }; /** X=127.5, Y=127.5, Z=1/127.5f, W=-1.0 */ const VectorRegister GVectorPackingConstants = MakeVectorRegister( 127.5f, 127.5f, 1.0f/127.5f, -1.0f ); /** Zero Normal **/ FPackedNormal FPackedNormal::ZeroNormal(127, 127, 127, 127); // // FPackedNormal serializer // FArchive& operator<<(FArchive& Ar,FPackedNormal& N) { Ar << N.Vector.Packed; return Ar; } FArchive& operator<<(FArchive& Ar, FPackedRGB10A2N& N) { Ar << N.Vector.Packed; return Ar; } FArchive& operator<<(FArchive& Ar, FPackedRGBA16N& N) { Ar << N.X; Ar << N.Y; Ar << N.Z; Ar << N.W; return Ar; } // // Pixel format information. // FPixelFormatInfo GPixelFormats[PF_MAX] = { // Name BlockSizeX BlockSizeY BlockSizeZ BlockBytes NumComponents PlatformFormat Supported UnrealFormat { TEXT("unknown"), 0, 0, 0, 0, 0, 0, 0, PF_Unknown }, { TEXT("A32B32G32R32F"), 1, 1, 1, 16, 4, 0, 1, PF_A32B32G32R32F }, { TEXT("B8G8R8A8"), 1, 1, 1, 4, 4, 0, 1, PF_B8G8R8A8 }, { TEXT("G8"), 1, 1, 1, 1, 1, 0, 1, PF_G8 }, { TEXT("G16"), 1, 1, 1, 2, 1, 0, 1, PF_G16 }, { TEXT("DXT1"), 4, 4, 1, 8, 3, 0, 1, PF_DXT1 }, { TEXT("DXT3"), 4, 4, 1, 16, 4, 0, 1, PF_DXT3 }, { TEXT("DXT5"), 4, 4, 1, 16, 4, 0, 1, PF_DXT5 }, { TEXT("UYVY"), 2, 1, 1, 4, 4, 0, 0, PF_UYVY }, { TEXT("FloatRGB"), 1, 1, 1, 4, 3, 0, 1, PF_FloatRGB }, { TEXT("FloatRGBA"), 1, 1, 1, 8, 4, 0, 1, PF_FloatRGBA }, { TEXT("DepthStencil"), 1, 1, 1, 4, 1, 0, 0, PF_DepthStencil }, { TEXT("ShadowDepth"), 1, 1, 1, 4, 1, 0, 0, PF_ShadowDepth }, { TEXT("R32_FLOAT"), 1, 1, 1, 4, 1, 0, 1, PF_R32_FLOAT }, { TEXT("G16R16"), 1, 1, 1, 4, 2, 0, 1, PF_G16R16 }, { TEXT("G16R16F"), 1, 1, 1, 4, 2, 0, 1, PF_G16R16F }, { TEXT("G16R16F_FILTER"), 1, 1, 1, 4, 2, 0, 1, PF_G16R16F_FILTER }, { TEXT("G32R32F"), 1, 1, 1, 8, 2, 0, 1, PF_G32R32F }, { TEXT("A2B10G10R10"), 1, 1, 1, 4, 4, 0, 1, PF_A2B10G10R10 }, { TEXT("A16B16G16R16"), 1, 1, 1, 8, 4, 0, 1, PF_A16B16G16R16 }, { TEXT("D24"), 1, 1, 1, 4, 1, 0, 1, PF_D24 }, { TEXT("PF_R16F"), 1, 1, 1, 2, 1, 0, 1, PF_R16F }, { TEXT("PF_R16F_FILTER"), 1, 1, 1, 2, 1, 0, 1, PF_R16F_FILTER }, { TEXT("BC5"), 4, 4, 1, 16, 2, 0, 1, PF_BC5 }, { TEXT("V8U8"), 1, 1, 1, 2, 2, 0, 1, PF_V8U8 }, { TEXT("A1"), 1, 1, 1, 1, 1, 0, 0, PF_A1 }, { TEXT("FloatR11G11B10"), 1, 1, 1, 4, 3, 0, 0, PF_FloatR11G11B10 }, { TEXT("A8"), 1, 1, 1, 1, 1, 0, 1, PF_A8 }, { TEXT("R32_UINT"), 1, 1, 1, 4, 1, 0, 1, PF_R32_UINT }, { TEXT("R32_SINT"), 1, 1, 1, 4, 1, 0, 1, PF_R32_SINT }, // IOS Support { TEXT("PVRTC2"), 8, 4, 1, 8, 4, 0, 0, PF_PVRTC2 }, { TEXT("PVRTC4"), 4, 4, 1, 8, 4, 0, 0, PF_PVRTC4 }, { TEXT("R16_UINT"), 1, 1, 1, 2, 1, 0, 1, PF_R16_UINT }, { TEXT("R16_SINT"), 1, 1, 1, 2, 1, 0, 1, PF_R16_SINT }, { TEXT("R16G16B16A16_UINT"),1, 1, 1, 8, 4, 0, 1, PF_R16G16B16A16_UINT}, { TEXT("R16G16B16A16_SINT"),1, 1, 1, 8, 4, 0, 1, PF_R16G16B16A16_SINT}, { TEXT("R5G6B5_UNORM"), 1, 1, 1, 2, 3, 0, 1, PF_R5G6B5_UNORM }, { TEXT("R8G8B8A8"), 1, 1, 1, 4, 4, 0, 1, PF_R8G8B8A8 }, { TEXT("A8R8G8B8"), 1, 1, 1, 4, 4, 0, 1, PF_A8R8G8B8 }, { TEXT("BC4"), 4, 4, 1, 8, 1, 0, 1, PF_BC4 }, { TEXT("R8G8"), 1, 1, 1, 2, 2, 0, 1, PF_R8G8 }, { TEXT("ATC_RGB"), 4, 4, 1, 8, 3, 0, 0, PF_ATC_RGB }, { TEXT("ATC_RGBA_E"), 4, 4, 1, 16, 4, 0, 0, PF_ATC_RGBA_E }, { TEXT("ATC_RGBA_I"), 4, 4, 1, 16, 4, 0, 0, PF_ATC_RGBA_I }, { TEXT("X24_G8"), 1, 1, 1, 1, 1, 0, 0, PF_X24_G8 }, { TEXT("ETC1"), 4, 4, 1, 8, 3, 0, 0, PF_ETC1 }, { TEXT("ETC2_RGB"), 4, 4, 1, 8, 3, 0, 0, PF_ETC2_RGB }, { TEXT("ETC2_RGBA"), 4, 4, 1, 16, 4, 0, 0, PF_ETC2_RGBA }, { TEXT("PF_R32G32B32A32_UINT"),1, 1, 1, 16, 4, 0, 1, PF_R32G32B32A32_UINT}, { TEXT("PF_R16G16_UINT"), 1, 1, 1, 4, 4, 0, 1, PF_R16G16_UINT}, // ASTC support { TEXT("ASTC_4x4"), 4, 4, 1, 16, 4, 0, 0, PF_ASTC_4x4 }, { TEXT("ASTC_6x6"), 6, 6, 1, 16, 4, 0, 0, PF_ASTC_6x6 }, { TEXT("ASTC_8x8"), 8, 8, 1, 16, 4, 0, 0, PF_ASTC_8x8 }, { TEXT("ASTC_10x10"), 10, 10, 1, 16, 4, 0, 0, PF_ASTC_10x10 }, { TEXT("ASTC_12x12"), 12, 12, 1, 16, 4, 0, 0, PF_ASTC_12x12 }, { TEXT("BC6H"), 4, 4, 1, 16, 3, 0, 1, PF_BC6H }, { TEXT("BC7"), 4, 4, 1, 16, 4, 0, 1, PF_BC7 }, { TEXT("R8_UINT"), 1, 1, 1, 1, 1, 0, 1, PF_R8_UINT }, { TEXT("L8"), 1, 1, 1, 1, 1, 0, 0, PF_L8 }, { TEXT("XGXR8"), 1, 1, 1, 4, 4, 0, 1, PF_XGXR8 }, { TEXT("R8G8B8A8_UINT"), 1, 1, 1, 4, 4, 0, 1, PF_R8G8B8A8_UINT }, { TEXT("R8G8B8A8_SNORM"), 1, 1, 1, 4, 4, 0, 1, PF_R8G8B8A8_SNORM }, }; static struct FValidatePixelFormats { FValidatePixelFormats() { for (int32 X = 0; X < ARRAY_COUNT(GPixelFormats); ++X) { // Make sure GPixelFormats has an entry for every unreal format check(X == GPixelFormats[X].UnrealFormat); } } } ValidatePixelFormats; // // CalculateImageBytes // SIZE_T CalculateImageBytes(uint32 SizeX,uint32 SizeY,uint32 SizeZ,uint8 Format) { if ( Format == PF_A1 ) { // The number of bytes needed to store all 1 bit pixels in a line is the width of the image divided by the number of bits in a byte uint32 BytesPerLine = SizeX / 8; // The number of actual bytes in a 1 bit image is the bytes per line of pixels times the number of lines return sizeof(uint8) * BytesPerLine * SizeY; } else if( SizeZ > 0 ) { return (SizeX / GPixelFormats[Format].BlockSizeX) * (SizeY / GPixelFormats[Format].BlockSizeY) * (SizeZ / GPixelFormats[Format].BlockSizeZ) * GPixelFormats[Format].BlockBytes; } else { return (SizeX / GPixelFormats[Format].BlockSizeX) * (SizeY / GPixelFormats[Format].BlockSizeY) * GPixelFormats[Format].BlockBytes; } } // // FWhiteTexture implementation // /** * A solid-colored 1x1 texture. */ template class FColoredTexture : public FTexture { public: // FResource interface. virtual void InitRHI() override { // Create the texture RHI. FRHIResourceCreateInfo CreateInfo; FTexture2DRHIRef Texture2D = RHICreateTexture2D(1, 1, PF_B8G8R8A8, 1, 1, TexCreate_ShaderResource, CreateInfo); TextureRHI = Texture2D; // Write the contents of the texture. uint32 DestStride; FColor* DestBuffer = (FColor*)RHILockTexture2D(Texture2D, 0, RLM_WriteOnly, DestStride, false); *DestBuffer = FColor(R, G, B, A); RHIUnlockTexture2D(Texture2D, 0, false); // Create the sampler state RHI resource. FSamplerStateInitializerRHI SamplerStateInitializer(SF_Point,AM_Wrap,AM_Wrap,AM_Wrap); SamplerStateRHI = RHICreateSamplerState(SamplerStateInitializer); } /** Returns the width of the texture in pixels. */ virtual uint32 GetSizeX() const override { return 1; } /** Returns the height of the texture in pixels. */ virtual uint32 GetSizeY() const override { return 1; } }; FTexture* GWhiteTexture = new TGlobalResource >; FTexture* GBlackTexture = new TGlobalResource >; /** * Bulk data interface for providing a single black color used to initialize a * volume texture. */ class FBlackVolumeTextureResourceBulkDataInterface : public FResourceBulkDataInterface { public: /** Default constructor. */ FBlackVolumeTextureResourceBulkDataInterface() : Color(0) { } /** * Returns a pointer to the bulk data. */ virtual const void* GetResourceBulkData() const override { return &Color; } /** * @return size of resource memory */ virtual uint32 GetResourceBulkDataSize() const override { return sizeof(Color); } /** * Free memory after it has been used to initialize RHI resource */ virtual void Discard() override { } private: /** Storage for the color. */ FColor Color; }; /** * A class representing a 1x1x1 black volume texture. */ template class FBlackVolumeTexture : public FTexture { public: /** * Initialize RHI resources. */ virtual void InitRHI() override { if (GSupportsTexture3D) { // Create the texture. FBlackVolumeTextureResourceBulkDataInterface BlackTextureBulkData; FRHIResourceCreateInfo CreateInfo(&BlackTextureBulkData); FTexture3DRHIRef Texture3D = RHICreateTexture3D(1,1,1,PixelFormat,1,TexCreate_ShaderResource,CreateInfo); TextureRHI = Texture3D; // Create the sampler state. FSamplerStateInitializerRHI SamplerStateInitializer(SF_Point,AM_Wrap,AM_Wrap,AM_Wrap); SamplerStateRHI = RHICreateSamplerState(SamplerStateInitializer); } } /** * Return the size of the texture in the X dimension. */ virtual uint32 GetSizeX() const override { return 1; } /** * Return the size of the texture in the Y dimension. */ virtual uint32 GetSizeY() const override { return 1; } }; /** Global black volume texture resource. */ FTexture* GBlackVolumeTexture = new TGlobalResource>(); /** Global black volume texture resource. */ FTexture* GBlackUintVolumeTexture = new TGlobalResource>(); class FBlackArrayTexture : public FTexture { public: // FResource interface. virtual void InitRHI() override { if (GetFeatureLevel() >= ERHIFeatureLevel::SM4) { // Create the texture RHI. FBlackVolumeTextureResourceBulkDataInterface BlackTextureBulkData; FRHIResourceCreateInfo CreateInfo(&BlackTextureBulkData); FTexture2DArrayRHIRef TextureArray = RHICreateTexture2DArray(1, 1, 1, PF_B8G8R8A8, 1, TexCreate_ShaderResource, CreateInfo); TextureRHI = TextureArray; // Create the sampler state RHI resource. FSamplerStateInitializerRHI SamplerStateInitializer(SF_Point,AM_Wrap,AM_Wrap,AM_Wrap); SamplerStateRHI = RHICreateSamplerState(SamplerStateInitializer); } } /** Returns the width of the texture in pixels. */ virtual uint32 GetSizeX() const override { return 1; } /** Returns the height of the texture in pixels. */ virtual uint32 GetSizeY() const override { return 1; } }; FTexture* GBlackArrayTexture = new TGlobalResource; // // FMipColorTexture implementation // /** * A texture that has a different solid color in each mip-level */ class FMipColorTexture : public FTexture { public: enum { NumMips = 12 }; static const FColor MipColors[NumMips]; // FResource interface. virtual void InitRHI() override { // Create the texture RHI. int32 TextureSize = 1 << (NumMips - 1); FRHIResourceCreateInfo CreateInfo; FTexture2DRHIRef Texture2D = RHICreateTexture2D(TextureSize,TextureSize,PF_B8G8R8A8,NumMips,1,TexCreate_ShaderResource,CreateInfo); TextureRHI = Texture2D; // Write the contents of the texture. uint32 DestStride; int32 Size = TextureSize; for ( int32 MipIndex=0; MipIndex < NumMips; ++MipIndex ) { FColor* DestBuffer = (FColor*)RHILockTexture2D(Texture2D, MipIndex, RLM_WriteOnly, DestStride, false); for ( int32 Y=0; Y < Size; ++Y ) { for ( int32 X=0; X < Size; ++X ) { DestBuffer[X] = MipColors[NumMips - 1 - MipIndex]; } DestBuffer += DestStride / sizeof(FColor); } RHIUnlockTexture2D(Texture2D, MipIndex, false); Size >>= 1; } // Create the sampler state RHI resource. FSamplerStateInitializerRHI SamplerStateInitializer(SF_Point,AM_Wrap,AM_Wrap,AM_Wrap); SamplerStateRHI = RHICreateSamplerState(SamplerStateInitializer); } /** Returns the width of the texture in pixels. */ virtual uint32 GetSizeX() const override { int32 TextureSize = 1 << (NumMips - 1); return TextureSize; } /** Returns the height of the texture in pixels. */ // PVS-Studio notices that the implementation of GetSizeX is identical to this one // and warns us. In this case, it is intentional, so we disable the warning: virtual uint32 GetSizeY() const override //-V524 { int32 TextureSize = 1 << (NumMips - 1); return TextureSize; } }; const FColor FMipColorTexture::MipColors[NumMips] = { FColor( 80, 80, 80, 0 ), // Mip 0: 1x1 (dark grey) FColor( 200, 200, 200, 0 ), // Mip 1: 2x2 (light grey) FColor( 200, 200, 0, 0 ), // Mip 2: 4x4 (medium yellow) FColor( 255, 255, 0, 0 ), // Mip 3: 8x8 (yellow) FColor( 160, 255, 40, 0 ), // Mip 4: 16x16 (light green) FColor( 0, 255, 0, 0 ), // Mip 5: 32x32 (green) FColor( 0, 255, 200, 0 ), // Mip 6: 64x64 (cyan) FColor( 0, 170, 170, 0 ), // Mip 7: 128x128 (light blue) FColor( 60, 60, 255, 0 ), // Mip 8: 256x256 (dark blue) FColor( 255, 0, 255, 0 ), // Mip 9: 512x512 (pink) FColor( 255, 0, 0, 0 ), // Mip 10: 1024x1024 (red) FColor( 255, 130, 0, 0 ), // Mip 11: 2048x2048 (orange) }; RENDERCORE_API FTexture* GMipColorTexture = new FMipColorTexture; RENDERCORE_API int32 GMipColorTextureMipLevels = FMipColorTexture::NumMips; // 4: 8x8 cubemap resolution, shader needs to use the same value as preprocessing RENDERCORE_API const uint32 GDiffuseConvolveMipLevel = 4; // // FWhiteTextureCube implementation // /** A solid color cube texture. */ class FSolidColorTextureCube : public FTexture { public: FSolidColorTextureCube(const FColor& InColor, EPixelFormat InPixelFormat = PF_B8G8R8A8) : Color(InColor) , PixelFormat(InPixelFormat) {} // FRenderResource interface. virtual void InitRHI() override { // Create the texture RHI. FRHIResourceCreateInfo CreateInfo; FTextureCubeRHIRef TextureCube = RHICreateTextureCube(1, PixelFormat,1,0,CreateInfo); TextureRHI = TextureCube; // Write the contents of the texture. for(uint32 FaceIndex = 0;FaceIndex < 6;FaceIndex++) { uint32 DestStride; FColor* DestBuffer = (FColor*)RHILockTextureCubeFace(TextureCube, FaceIndex, 0, 0, RLM_WriteOnly, DestStride, false); *DestBuffer = Color; RHIUnlockTextureCubeFace(TextureCube, FaceIndex, 0, 0, false); } // Create the sampler state RHI resource. FSamplerStateInitializerRHI SamplerStateInitializer(SF_Point,AM_Wrap,AM_Wrap,AM_Wrap); SamplerStateRHI = RHICreateSamplerState(SamplerStateInitializer); } /** Returns the width of the texture in pixels. */ virtual uint32 GetSizeX() const override { return 1; } /** Returns the height of the texture in pixels. */ virtual uint32 GetSizeY() const override { return 1; } private: FColor Color; EPixelFormat PixelFormat; }; /** A white cube texture. */ class FWhiteTextureCube : public FSolidColorTextureCube { public: FWhiteTextureCube() : FSolidColorTextureCube(FColor::White) {} }; FTexture* GWhiteTextureCube = new TGlobalResource; /** A black cube texture. */ class FBlackTextureCube : public FSolidColorTextureCube { public: FBlackTextureCube(): FSolidColorTextureCube(FColor::Black) {} }; FTexture* GBlackTextureCube = new TGlobalResource; /** A black cube texture. */ class FBlackTextureDepthCube : public FSolidColorTextureCube { public: FBlackTextureDepthCube() : FSolidColorTextureCube(FColor::Black, PF_ShadowDepth) {} }; FTexture* GBlackTextureDepthCube = new TGlobalResource; class FBlackCubeArrayTexture : public FTexture { public: // FResource interface. virtual void InitRHI() override { if (GetFeatureLevel() >= ERHIFeatureLevel::SM5) { // Create the texture RHI. FRHIResourceCreateInfo CreateInfo; FTextureCubeRHIRef TextureCubeArray = RHICreateTextureCubeArray(1,1,PF_B8G8R8A8,1,TexCreate_ShaderResource,CreateInfo); TextureRHI = TextureCubeArray; for(uint32 FaceIndex = 0;FaceIndex < 6;FaceIndex++) { uint32 DestStride; FColor* DestBuffer = (FColor*)RHILockTextureCubeFace(TextureCubeArray, FaceIndex, 0, 0, RLM_WriteOnly, DestStride, false); // Note: alpha is used by reflection environment to say how much of the foreground texture is visible, so 0 says it is completely invisible *DestBuffer = FColor(0, 0, 0, 0); RHIUnlockTextureCubeFace(TextureCubeArray, FaceIndex, 0, 0, false); } // Create the sampler state RHI resource. FSamplerStateInitializerRHI SamplerStateInitializer(SF_Point,AM_Wrap,AM_Wrap,AM_Wrap); SamplerStateRHI = RHICreateSamplerState(SamplerStateInitializer); } } /** Returns the width of the texture in pixels. */ virtual uint32 GetSizeX() const override { return 1; } /** Returns the height of the texture in pixels. */ virtual uint32 GetSizeY() const override { return 1; } }; FTexture* GBlackCubeArrayTexture = new TGlobalResource; /* 3 XYZ packed in 4 bytes. (11:11:10 for X:Y:Z) */ /** * operator FVector - unpacked to -1 to 1 */ FPackedPosition::operator FVector() const { return FVector(Vector.X/1023.f, Vector.Y/1023.f, Vector.Z/511.f); } /** * operator VectorRegister */ VectorRegister FPackedPosition::GetVectorRegister() const { FVector UnpackedVect = *this; VectorRegister VectorToUnpack = VectorLoadFloat3_W0(&UnpackedVect); return VectorToUnpack; } /** * Pack this vector(-1 to 1 for XYZ) to 4 bytes XYZ(11:11:10) */ void FPackedPosition::Set( const FVector& InVector ) { check (FMath::Abs(InVector.X) <= 1.f && FMath::Abs(InVector.Y) <= 1.f && FMath::Abs(InVector.Z) <= 1.f); #if !WITH_EDITORONLY_DATA // This should not happen in Console - this should happen during Cooking in PC check (false); #else // Too confusing to use .5f - wanted to use the last bit! // Change to int for easier read Vector.X = FMath::Clamp(FMath::TruncToInt(InVector.X * 1023.0f),-1023,1023); Vector.Y = FMath::Clamp(FMath::TruncToInt(InVector.Y * 1023.0f),-1023,1023); Vector.Z = FMath::Clamp(FMath::TruncToInt(InVector.Z * 511.0f),-511,511); #endif } /** * operator << serialize */ FArchive& operator<<(FArchive& Ar,FPackedPosition& N) { // Save N.Packed return Ar << N.Packed; } void CalcMipMapExtent3D( uint32 TextureSizeX, uint32 TextureSizeY, uint32 TextureSizeZ, EPixelFormat Format, uint32 MipIndex, uint32& OutXExtent, uint32& OutYExtent, uint32& OutZExtent ) { OutXExtent = FMath::Max(TextureSizeX >> MipIndex, GPixelFormats[Format].BlockSizeX); OutYExtent = FMath::Max(TextureSizeY >> MipIndex, GPixelFormats[Format].BlockSizeY); OutZExtent = FMath::Max(TextureSizeZ >> MipIndex, GPixelFormats[Format].BlockSizeZ); } SIZE_T CalcTextureMipMapSize3D( uint32 TextureSizeX, uint32 TextureSizeY, uint32 TextureSizeZ, EPixelFormat Format, uint32 MipIndex ) { uint32 XExtent; uint32 YExtent; uint32 ZExtent; CalcMipMapExtent3D(TextureSizeX, TextureSizeY, TextureSizeZ, Format, MipIndex, XExtent, YExtent, ZExtent); // Offset MipExtent to round up result XExtent += GPixelFormats[Format].BlockSizeX - 1; YExtent += GPixelFormats[Format].BlockSizeY - 1; ZExtent += GPixelFormats[Format].BlockSizeZ - 1; const uint32 XPitch = (XExtent / GPixelFormats[Format].BlockSizeX) * GPixelFormats[Format].BlockBytes; const uint32 NumRows = YExtent / GPixelFormats[Format].BlockSizeY; const uint32 NumLayers = ZExtent / GPixelFormats[Format].BlockSizeZ; return NumLayers * NumRows * XPitch; } SIZE_T CalcTextureSize3D( uint32 SizeX, uint32 SizeY, uint32 SizeZ, EPixelFormat Format, uint32 MipCount ) { SIZE_T Size = 0; for ( uint32 MipIndex=0; MipIndex < MipCount; ++MipIndex ) { Size += CalcTextureMipMapSize3D(SizeX,SizeY,SizeZ,Format,MipIndex); } return Size; } FIntPoint CalcMipMapExtent( uint32 TextureSizeX, uint32 TextureSizeY, EPixelFormat Format, uint32 MipIndex ) { return FIntPoint(FMath::Max(TextureSizeX >> MipIndex, GPixelFormats[Format].BlockSizeX), FMath::Max(TextureSizeY >> MipIndex, GPixelFormats[Format].BlockSizeY)); } SIZE_T CalcTextureMipWidthInBlocks(uint32 TextureSizeX, EPixelFormat Format, uint32 MipIndex) { const uint32 BlockSizeX = GPixelFormats[Format].BlockSizeX; const uint32 WidthInTexels = FMath::Max(TextureSizeX >> MipIndex, 1); const uint32 WidthInBlocks = (WidthInTexels + BlockSizeX - 1) / BlockSizeX; return WidthInBlocks; } SIZE_T CalcTextureMipHeightInBlocks(uint32 TextureSizeY, EPixelFormat Format, uint32 MipIndex) { const uint32 BlockSizeY = GPixelFormats[Format].BlockSizeY; const uint32 HeightInTexels = FMath::Max(TextureSizeY >> MipIndex, 1); const uint32 HeightInBlocks = (HeightInTexels + BlockSizeY - 1) / BlockSizeY; return HeightInBlocks; } SIZE_T CalcTextureMipMapSize( uint32 TextureSizeX, uint32 TextureSizeY, EPixelFormat Format, uint32 MipIndex ) { const uint32 WidthInBlocks = CalcTextureMipWidthInBlocks(TextureSizeX, Format, MipIndex); const uint32 HeightInBlocks = CalcTextureMipHeightInBlocks(TextureSizeY, Format, MipIndex); return WidthInBlocks * HeightInBlocks * GPixelFormats[Format].BlockBytes; } SIZE_T CalcTextureSize( uint32 SizeX, uint32 SizeY, EPixelFormat Format, uint32 MipCount ) { SIZE_T Size = 0; for ( uint32 MipIndex=0; MipIndex < MipCount; ++MipIndex ) { Size += CalcTextureMipMapSize(SizeX,SizeY,Format,MipIndex); } return Size; } void CopyTextureData2D(const void* Source,void* Dest,uint32 SizeY,EPixelFormat Format,uint32 SourceStride,uint32 DestStride) { const uint32 BlockSizeY = GPixelFormats[Format].BlockSizeY; const uint32 NumBlocksY = (SizeY + BlockSizeY - 1) / BlockSizeY; // a DestStride of 0 means to use the SourceStride if(SourceStride == DestStride || DestStride == 0) { // If the source and destination have the same stride, copy the data in one block. FMemory::Memcpy(Dest,Source,NumBlocksY * SourceStride); } else { // If the source and destination have different strides, copy each row of blocks separately. const uint32 NumBytesPerRow = FMath::Min(SourceStride, DestStride); for(uint32 BlockY = 0;BlockY < NumBlocksY;++BlockY) { FMemory::Memcpy( (uint8*)Dest + DestStride * BlockY, (uint8*)Source + SourceStride * BlockY, NumBytesPerRow ); } } } /** Helper functions for text output of texture properties... */ #ifndef CASE_ENUM_TO_TEXT #define CASE_ENUM_TO_TEXT(txt) case txt: return TEXT(#txt); #endif #ifndef TEXT_TO_ENUM #define TEXT_TO_ENUM(eVal, txt) if (FCString::Stricmp(TEXT(#eVal), txt) == 0) return eVal; #endif const TCHAR* GetPixelFormatString(EPixelFormat InPixelFormat) { switch (InPixelFormat) { FOREACH_ENUM_EPIXELFORMAT(CASE_ENUM_TO_TEXT) default: return TEXT("PF_Unknown"); } } EPixelFormat GetPixelFormatFromString(const TCHAR* InPixelFormatStr) { #define TEXT_TO_PIXELFORMAT(f) TEXT_TO_ENUM(f, InPixelFormatStr); FOREACH_ENUM_EPIXELFORMAT(TEXT_TO_PIXELFORMAT) #undef TEXT_TO_PIXELFORMAT return PF_Unknown; } const TCHAR* GetCubeFaceName(ECubeFace Face) { switch(Face) { case CubeFace_PosX: return TEXT("PosX"); case CubeFace_NegX: return TEXT("NegX"); case CubeFace_PosY: return TEXT("PosY"); case CubeFace_NegY: return TEXT("NegY"); case CubeFace_PosZ: return TEXT("PosZ"); case CubeFace_NegZ: return TEXT("NegZ"); default: return TEXT(""); } } ECubeFace GetCubeFaceFromName(const FString& Name) { // not fast but doesn't have to be if(Name.EndsWith(TEXT("PosX"))) { return CubeFace_PosX; } else if(Name.EndsWith(TEXT("NegX"))) { return CubeFace_NegX; } else if(Name.EndsWith(TEXT("PosY"))) { return CubeFace_PosY; } else if(Name.EndsWith(TEXT("NegY"))) { return CubeFace_NegY; } else if(Name.EndsWith(TEXT("PosZ"))) { return CubeFace_PosZ; } else if(Name.EndsWith(TEXT("NegZ"))) { return CubeFace_NegZ; } return CubeFace_MAX; } class FVector4VertexDeclaration : public FRenderResource { public: FVertexDeclarationRHIRef VertexDeclarationRHI; virtual void InitRHI() override { FVertexDeclarationElementList Elements; Elements.Add(FVertexElement(0, 0, VET_Float4, 0, sizeof(FVector4))); VertexDeclarationRHI = RHICreateVertexDeclaration(Elements); } virtual void ReleaseRHI() override { VertexDeclarationRHI.SafeRelease(); } }; TGlobalResource GVector4VertexDeclaration; RENDERCORE_API FVertexDeclarationRHIRef& GetVertexDeclarationFVector4() { return GVector4VertexDeclaration.VertexDeclarationRHI; } class FVector3VertexDeclaration : public FRenderResource { public: FVertexDeclarationRHIRef VertexDeclarationRHI; virtual void InitRHI() override { FVertexDeclarationElementList Elements; Elements.Add(FVertexElement(0, 0, VET_Float3, 0, sizeof(FVector))); VertexDeclarationRHI = RHICreateVertexDeclaration(Elements); } virtual void ReleaseRHI() override { VertexDeclarationRHI.SafeRelease(); } }; TGlobalResource GVector3VertexDeclaration; RENDERCORE_API FVertexDeclarationRHIRef& GetVertexDeclarationFVector3() { return GVector3VertexDeclaration.VertexDeclarationRHI; } RENDERCORE_API bool PlatformSupportsSimpleForwardShading(EShaderPlatform Platform) { static const auto SupportSimpleForwardShadingCVar = IConsoleManager::Get().FindTConsoleVariableDataInt(TEXT("r.SupportSimpleForwardShading")); // Scalability feature only needed / used on PC return IsPCPlatform(Platform) && SupportSimpleForwardShadingCVar->GetValueOnAnyThread() != 0; } RENDERCORE_API bool IsSimpleForwardShadingEnabled(EShaderPlatform Platform) { static const auto CVar = IConsoleManager::Get().FindTConsoleVariableDataInt(TEXT("r.SimpleForwardShading")); return CVar->GetValueOnAnyThread() != 0 && PlatformSupportsSimpleForwardShading(Platform); } RENDERCORE_API int32 bUseForwardShading = 0; static FAutoConsoleVariableRef CVarForwardShading( TEXT("r.ForwardShading"), bUseForwardShading, TEXT("Whether to use forward shading on desktop platforms - requires Shader Model 5 hardware.\n") TEXT("Forward shading has lower constant cost, but fewer features supported. 0:off, 1:on\n") TEXT("This rendering path is a work in progress with many unimplemented features, notably only a single reflection capture is applied per object and no translucency dynamic shadow receiving."), ECVF_RenderThreadSafe | ECVF_ReadOnly ); class FUnitCubeVertexBuffer : public FVertexBuffer { public: /** * Initialize the RHI for this rendering resource */ void InitRHI() override { const int32 NumVerts = 8; TResourceArray Verts; Verts.SetNumUninitialized(NumVerts); for (uint32 Z = 0; Z < 2; Z++) { for (uint32 Y = 0; Y < 2; Y++) { for (uint32 X = 0; X < 2; X++) { const FVector4 Vertex = FVector4( (X ? -1 : 1), (Y ? -1 : 1), (Z ? -1 : 1), 1.0f ); Verts[GetCubeVertexIndex(X, Y, Z)] = Vertex; } } } uint32 Size = Verts.GetResourceDataSize(); // Create vertex buffer. Fill buffer with initial data upon creation FRHIResourceCreateInfo CreateInfo(&Verts); VertexBufferRHI = RHICreateVertexBuffer(Size, BUF_Static, CreateInfo); } }; class FUnitCubeIndexBuffer : public FIndexBuffer { public: /** * Initialize the RHI for this rendering resource */ void InitRHI() override { TResourceArray Indices; int32 NumIndices = ARRAY_COUNT(GCubeIndices); Indices.AddUninitialized(NumIndices); FMemory::Memcpy(Indices.GetData(), GCubeIndices, NumIndices * sizeof(uint16)); const uint32 Size = Indices.GetResourceDataSize(); const uint32 Stride = sizeof(uint16); // Create index buffer. Fill buffer with initial data upon creation FRHIResourceCreateInfo CreateInfo(&Indices); IndexBufferRHI = RHICreateIndexBuffer(Stride, Size, BUF_Static, CreateInfo); } }; static TGlobalResource GUnitCubeVertexBuffer; static TGlobalResource GUnitCubeIndexBuffer; RENDERCORE_API FVertexBufferRHIRef& GetUnitCubeVertexBuffer() { return GUnitCubeVertexBuffer.VertexBufferRHI; } RENDERCORE_API FIndexBufferRHIRef& GetUnitCubeIndexBuffer() { return GUnitCubeIndexBuffer.IndexBufferRHI; } RENDERCORE_API void QuantizeSceneBufferSize(int32& InOutBufferSizeX, int32& InOutBufferSizeY) { // Ensure sizes are dividable by DividableBy to get post processing effects with lower resolution working well const uint32 DividableBy = 4; const uint32 Mask = ~(DividableBy - 1); InOutBufferSizeX = (InOutBufferSizeX + DividableBy - 1) & Mask; InOutBufferSizeY = (InOutBufferSizeY + DividableBy - 1) & Mask; }src/pbrt/util/hash_test.cpp // pbrt is Copyright(c) 1998-2020 , , and . // The pbrt source code is licensed under the Apache License, Version 2.0. // SPDX: Apache-2.0 #include #include #include using namespace pbrt; TEST(Hash, VarArgs) { int64_t buf[] = {1, -12511, 31415821, 37}; for (int i = 0; i < 4; ++i) EXPECT_EQ(HashBuffer(buf + i, sizeof(int64_t)), Hash(buf[i])); } TEST(Hash, Collisions) { std::set low, high; std::set full; int lowCollisions = 0, highCollisions = 0; int fullCollisions = 0; int same = 0; for (int i = 0; i < 10000000; ++i) { uint64_t h = Hash(i); if (h == i) ++same; if (low.find(h) != low.end()) ++lowCollisions; if (high.find(h >> 32) != high.end()) ++highCollisions; if (full.find(h >> 32) != full.end()) ++fullCollisions; } // It's actually potentially legit if any of these hit; it should // shouldn't happen a lot. EXPECT_EQ(0, same); EXPECT_EQ(0, lowCollisions); EXPECT_EQ(0, highCollisions); EXPECT_EQ(0, fullCollisions); } TEST(Hash, Unaligned) { uint64_t buf[] = { 0xfacebeef, 0x65028088, 0x13372048 }; char cbuf[sizeof(buf) + 8]; for (int delta = 0; delta < 8; ++ delta) { memcpy(cbuf + delta, buf, sizeof(buf)); EXPECT_EQ(HashBuffer(buf, sizeof(buf)), HashBuffer(cbuf + delta, sizeof(buf))); } } /***************************************************************************** * * * OpenNI 2.x Alpha * * Copyright (C) 2012 PrimeSense Ltd. * * * * This file is part of OpenNI. * * * * 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. * * * *****************************************************************************/ //--------------------------------------------------------------------------- // Includes //--------------------------------------------------------------------------- #include "XnNesaDebugProcessor.h" #include "XnSensor.h" //--------------------------------------------------------------------------- // Defines //--------------------------------------------------------------------------- #define XN_SENSOR_TEC_DEBUG_MAX_PACKET_SIZE 256 //--------------------------------------------------------------------------- // Code //--------------------------------------------------------------------------- XnNesaDebugProcessor::XnNesaDebugProcessor(XnDevicePrivateData* pDevicePrivateData) : XnWholePacketProcessor(pDevicePrivateData, "NesaDebug", XN_SENSOR_TEC_DEBUG_MAX_PACKET_SIZE), m_Dump(NULL) { } XnNesaDebugProcessor::~XnNesaDebugProcessor() { xnDumpFileClose(m_Dump); } void XnNesaDebugProcessor::ProcessWholePacket(const XnSensorProtocolResponseHeader* /*pHeader*/, const XnUChar* pData) { if (m_Dump == NULL) { m_Dump = xnDumpFileOpenEx("NesaDebug", TRUE, TRUE, "NesaDebug.txt"); } xnDumpFileWriteString(m_Dump, "%S\n", (XnChar*)pData); printf("%S\n", (XnWChar*)pData); } src/controller/simulation/elastic/elastic_controller.cpp #include "controller/simulation/elastic/elastic_controller.h" #include "model/bridge_model.h" #include "model/simulation_model.h" void ElasticController::updateJunctionsVelocity(double elapsed_time) { BridgeModel& bridge_model = this->get_bridge_model(); int junctions_len = bridge_model.get_junctions_len(); const Eigen::Vector2d G = this->get_simulation_model().get_gravity(); for (int i = 0; i < junctions_len; i++) { Junction& junction = bridge_model.get_junction(i); if (!junction.is_fixed()) { junction.set_velocity(junction.get_velocity() + G); } } } /* * GXML/Graphite: Geometry and Graphics Programming Library + Utilities * Copyright (C) 2000 * * 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., 675 Mass Ave, Cambridge, MA 02139, USA. * * If you modify this software, you should include a notice giving the * name of the person performing the modification, the date of modification, * and the reason for such modification. * * Contact: * * * * ISA Project * LORIA, INRIA Lorraine, * Campus Scientifique, BP 239 * 54506 VANDOEUVRE LES NANCY CEDEX * FRANCE * * Note that the GNU General Public License does not permit incorporating * the Software into proprietary programs. */ #include #include namespace OGF { //_________________________________________________________ CGraphBuilder::CGraphBuilder() { current_cell_ = nil ; vertex_in_cell_ = 0 ; current_meta_cell_ = nil ; desc_state_ = desc_initial ; } void CGraphBuilder::set_target(CGraph* cgraph) { CGraphMutator::set_target(cgraph) ; if(cgraph != nil) { for(int i=0; isize_of_meta_cells(); i++) { meta_cells_.push_back(cgraph->meta_cell(i)) ; } } } CGraph::Vertex* CGraphBuilder::current_vertex() const { return *(vertices_.rbegin()) ; } CGraph::Cell* CGraphBuilder::current_cell() const { return current_cell_ ; } void CGraphBuilder::begin_volume() { transition(desc_initial, desc_volume) ; } void CGraphBuilder::begin_meta_cell(int nb_vertices) { transition(desc_volume, desc_meta_cell) ; current_meta_cell_ = new_meta_cell() ; meta_cells_.push_back(current_meta_cell_) ; map_builder_.set_target(&(current_meta_cell_->map())) ; map_builder_.begin_surface() ; for(int i = 0; i < nb_vertices; i++) { map_builder_.add_vertex(Point3d()) ; } } void CGraphBuilder::begin_meta_facet() { transition(desc_meta_cell, desc_meta_facet) ; map_builder_.begin_facet() ; } void CGraphBuilder::add_vertex_to_meta_facet(int index) { map_builder_.add_vertex_to_facet(index) ; } void CGraphBuilder::end_meta_facet() { map_builder_.end_facet() ; transition(desc_meta_facet, desc_meta_cell) ; } void CGraphBuilder::end_meta_cell() { map_builder_.end_surface() ; map_builder_.reset() ; current_meta_cell_->initialize_from_map() ; transition(desc_meta_cell, desc_volume) ; } void CGraphBuilder::add_vertex(const Point3d& p) { check_description_state( desc_volume ); Vertex* result = new_vertex(p) ; vertices_.push_back(result) ; } void CGraphBuilder::begin_cell( unsigned int cell_type ) { transition(desc_volume, desc_cell) ; cgraph_assert( cell_type < meta_cells_.size() ); current_cell_ = new_cell(meta_cells_[cell_type]) ; vertex_in_cell_ = 0; } void CGraphBuilder::add_vertex_to_cell( unsigned int vertex_index ) { check_description_state( desc_cell ); cgraph_assert( vertex_index < vertices_.size() ); cgraph_assert( vertex_in_cell_ < current_cell_->meta_cell()->nb_vertices() ); // Add the vertex to current cell Vertex* vertex = vertices_[vertex_index]; set_cell_vertex(current_cell_, vertex_in_cell_, vertex) ; vertex_in_cell_++; } void CGraphBuilder::end_cell() { transition(desc_cell, desc_volume) ; ogf_assert(vertex_in_cell_ == current_cell_->nb_vertices()) ; } void CGraphBuilder::end_volume() { transition(desc_volume, desc_final) ; star_.bind(target()) ; Logger::out("CGraph") << "creating stars" << std::endl ; // Creating stars { FOR_EACH_CELL(CGraph, target(), it) { for(unsigned int i=0; i nb_vertices(); i++) { star_[it->vertex(i)].push_back(it) ; } }} Logger::out("CGraph") << "sewing cells" << std::endl ; // Sew cells, make each cell know its 2-connected neighbors { FOR_EACH_CELL(CGraph, target(), it) { sew_cell(it) ; }} Logger::out("CGraph") << "removing stars" << std::endl ; star_.unbind() ; Logger::out("CGraph") << "CGraph Build complete" << std::endl; Logger::out("CGraphBuilder") << "nb cells=" << target()->size_of_cells() << " nb vertices=" << target()->size_of_vertices() << " nb meta cells=" << target()->size_of_meta_cells() << std::endl ; } //______________________ Protected construction______________________________ void CGraphBuilder::sew_cell( Cell* cell ) { // Sew faces; // A face can be sewn with another face if it shares // two common edges. for( unsigned int face_i=0; face_i < cell->nb_facets(); ++face_i ) { if( cell->adjacent(face_i) != nil ) { continue; } Vertex* v1 = cell-> facet_vertex( face_i, 0 ); Vertex* v2 = cell-> facet_vertex( face_i, 1 ); Vertex* v3 = cell-> facet_vertex( face_i, 2 ); Vertex* vertex = v2 ; const Star& star = star_[vertex] ; for( Star::const_iterator itc = star.begin(); itc != star.end(); itc++ ) { Cell* neighbor_cell = *(itc); if( neighbor_cell == cell ) continue; Vertex* neighbor_v1 = nil; Vertex* neighbor_v3 = nil; for( unsigned int neigh_face_i=0; neigh_face_inb_facets(); ++neigh_face_i ) { if(neighbor_cell->nb_vertices_in_facet(neigh_face_i) != cell->nb_vertices_in_facet(face_i)) { // std::cerr << "Warning: potential unconformity" << std::endl ; continue ; } // get_dcel returns false if the face does // not contain the vertex. if( !neighbor_cell->get_dcel( neigh_face_i, v2, neighbor_v1, neighbor_v3 ) ) { continue ; } if( (neighbor_v1 == v1 && neighbor_v3 == v3) || (neighbor_v3 == v1 && neighbor_v1 == v3) ) { set_cell_adjacent(cell, face_i, neighbor_cell) ; set_cell_adjacent(neighbor_cell, neigh_face_i, cell) ; break; } } } } } //___________________________ Finite state automaton _________________________ void CGraphBuilder::check_description_state(description_state expected) { if(desc_state_ != expected) { std::cerr << "CGraph: Description function called in the wrong state" << std::endl ; std::cerr << " CGraph descriptor should be " << description_state_to_string(expected) ; std::cerr << std::endl ; std::cerr << " and is " << description_state_to_string(desc_state_) ; std::cerr << std::endl ; std::cerr << " Aborting ... " << std::endl ; abort() ; } } std::string CGraphBuilder::description_state_to_string( description_state desc ) { switch(desc) { case desc_initial: return "initial" ; break ; case desc_volume: return "volume" ; break ; case desc_meta_cell: return "meta cell" ; break ; case desc_meta_facet: return "meta facet" ; break ; case desc_cell: return "cell" ; break ; case desc_final: return "final" ; break ; default: return "unknown state" ; break ; } } //------------------------------------------------------------------------ void CGraphBuilder::build_meta_tetrahedron() { begin_meta_cell(4) ; begin_meta_facet() ; add_vertex_to_meta_facet(1) ; add_vertex_to_meta_facet(3) ; add_vertex_to_meta_facet(2) ; end_meta_facet() ; begin_meta_facet() ; add_vertex_to_meta_facet(0) ; add_vertex_to_meta_facet(2) ; add_vertex_to_meta_facet(3) ; end_meta_facet() ; begin_meta_facet() ; add_vertex_to_meta_facet(3) ; add_vertex_to_meta_facet(1) ; add_vertex_to_meta_facet(0) ; end_meta_facet() ; begin_meta_facet() ; add_vertex_to_meta_facet(0) ; add_vertex_to_meta_facet(1) ; add_vertex_to_meta_facet(2) ; end_meta_facet() ; end_meta_cell() ; } void CGraphBuilder::build_meta_hexahedron() { begin_meta_cell(8) ; begin_meta_facet() ; add_vertex_to_meta_facet(0) ; add_vertex_to_meta_facet(4) ; add_vertex_to_meta_facet(6) ; add_vertex_to_meta_facet(2) ; end_meta_facet() ; begin_meta_facet() ; add_vertex_to_meta_facet(3) ; add_vertex_to_meta_facet(7) ; add_vertex_to_meta_facet(5) ; add_vertex_to_meta_facet(1) ; end_meta_facet() ; begin_meta_facet() ; add_vertex_to_meta_facet(1) ; add_vertex_to_meta_facet(5) ; add_vertex_to_meta_facet(4) ; add_vertex_to_meta_facet(0) ; end_meta_facet() ; begin_meta_facet() ; add_vertex_to_meta_facet(2) ; add_vertex_to_meta_facet(6) ; add_vertex_to_meta_facet(7) ; add_vertex_to_meta_facet(3) ; end_meta_facet() ; begin_meta_facet() ; add_vertex_to_meta_facet(1) ; add_vertex_to_meta_facet(0) ; add_vertex_to_meta_facet(2) ; add_vertex_to_meta_facet(3) ; end_meta_facet() ; begin_meta_facet() ; add_vertex_to_meta_facet(4) ; add_vertex_to_meta_facet(5) ; add_vertex_to_meta_facet(7) ; add_vertex_to_meta_facet(6) ; end_meta_facet() ; end_meta_cell() ; } void CGraphBuilder::build_meta_prism() { begin_meta_cell(6) ; begin_meta_facet() ; add_vertex_to_meta_facet(0) ; add_vertex_to_meta_facet(1) ; add_vertex_to_meta_facet(2) ; end_meta_facet() ; begin_meta_facet() ; add_vertex_to_meta_facet(3) ; add_vertex_to_meta_facet(5) ; add_vertex_to_meta_facet(4) ; end_meta_facet() ; begin_meta_facet() ; add_vertex_to_meta_facet(0) ; add_vertex_to_meta_facet(3) ; add_vertex_to_meta_facet(4) ; add_vertex_to_meta_facet(1) ; end_meta_facet() ; begin_meta_facet() ; add_vertex_to_meta_facet(0) ; add_vertex_to_meta_facet(2) ; add_vertex_to_meta_facet(5) ; add_vertex_to_meta_facet(3) ; end_meta_facet() ; begin_meta_facet() ; add_vertex_to_meta_facet(1) ; add_vertex_to_meta_facet(4) ; add_vertex_to_meta_facet(5) ; add_vertex_to_meta_facet(2) ; end_meta_facet() ; end_meta_cell() ; } void CGraphBuilder::build_meta_pyramid() { begin_meta_cell(5) ; begin_meta_facet() ; add_vertex_to_meta_facet(0) ; add_vertex_to_meta_facet(1) ; add_vertex_to_meta_facet(2) ; add_vertex_to_meta_facet(3) ; end_meta_facet() ; begin_meta_facet() ; add_vertex_to_meta_facet(0) ; add_vertex_to_meta_facet(4) ; add_vertex_to_meta_facet(1) ; end_meta_facet() ; begin_meta_facet() ; add_vertex_to_meta_facet(0) ; add_vertex_to_meta_facet(3) ; add_vertex_to_meta_facet(4) ; end_meta_facet() ; begin_meta_facet() ; add_vertex_to_meta_facet(2) ; add_vertex_to_meta_facet(4) ; add_vertex_to_meta_facet(3) ; end_meta_facet() ; begin_meta_facet() ; add_vertex_to_meta_facet(2) ; add_vertex_to_meta_facet(1) ; add_vertex_to_meta_facet(4) ; end_meta_facet() ; end_meta_cell() ; } } /* * 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. */ #include #include #include #include #include "fw_helper.hpp" using namespace apache::geode::client; int testXmlCacheCreationWithRefid(const char* fileName) { char* host_name = (char*)"XML_CACHE_CREATION_TEST"; auto cacheFactory = CacheFactory(); std::shared_ptr cptr; char* path = ACE_OS::getenv("TESTSRC"); std::string directory(path); std::cout << "create DistributedSytem with name=" << host_name << std::endl; std::cout << "Create cache with the configurations provided in " "valid_cache_refid.xml" << std::endl; try { const auto filePath = directory + fileName; cptr = std::make_shared( cacheFactory.set("cache-xml-file", filePath).create()); if (cptr->getPdxIgnoreUnreadFields() != false) { std::cout << "getPdxIgnoreUnreadFields should return false." << std::endl; return -1; } else { std::cout << "getPdxIgnoreUnreadFields returned false." << std::endl; } } catch (CacheXmlException& ex) { std::cout << "CacheXmlException: msg = " << ex.what() << std::endl; LOG(ex.getStackTrace()); return -1; } std::shared_ptr Root1; std::shared_ptr SubRegion1; std::shared_ptr SubRegion11; std::shared_ptr SubRegion2; std::shared_ptr Root2; std::shared_ptr SubRegion21; std::cout << "Verify whether all the regions are created" << std::endl; try { Root1 = cptr->getRegion("Root1"); SubRegion1 = Root1->getSubregion("SubRegion1"); SubRegion11 = SubRegion1->getSubregion("SubRegion11"); SubRegion2 = Root1->getSubregion("SubRegion2"); Root2 = cptr->getRegion("Root2"); SubRegion21 = Root2->getSubregion("SubRegion21"); } catch (...) { LOGINFO("Unknown Exception while getting one of the regions"); return -1; } std::cout << "Verify whether region 'SubRegion11' has correct attributes" << std::endl; auto atts = SubRegion11->getAttributes(); if (atts.getCachingEnabled() != true) { LOGINFO("Caching is not enabled in SubRegion11"); return -1; } if (atts.getInitialCapacity() != 10) { LOGINFO("Initial capacity of SubRegion11 is not 10"); return -1; } if (atts.getConcurrencyLevel() != 52) { LOGINFO("Concurrency level of SubRegion11 is not 52"); return -1; } if (fabs(atts.getLoadFactor() - 0.89) > 0.001) { LOGINFO("Load factor of SubRegion11 is not 0.89"); return -1; } std::cout << "Verify whether region 'SubRegion2' has correct attributes" << std::endl; atts = SubRegion2->getAttributes(); if (atts.getCachingEnabled() != true) { LOGINFO("Caching is not enabled in SubRegion2"); return -1; } if (atts.getInitialCapacity() != 10) { LOGINFO("Initial capacity of SubRegion2 is not 10"); return -1; } if (fabs(atts.getLoadFactor() - 0.89) > 0.001) { LOGINFO("Load factor of SubRegion2 is not 0.89"); return -1; } if (atts.getConcurrencyLevel() != 52) { LOGINFO("Concurrency level of SubRegion2 is not 52"); return -1; } std::cout << "Verify whether region 'SubRegion21' has correct attributes" << std::endl; atts = SubRegion21->getAttributes(); if (atts.getCachingEnabled() != true) { LOGINFO("Caching is not enabled in SubRegion21"); return -1; } if (atts.getInitialCapacity() != 10) { LOGINFO("Initial capacity of SubRegion21 is not 10"); return -1; } if (fabs(atts.getLoadFactor() - 0.89) > 0.001) { LOGINFO("Load factor of SubRegion21 is not 0.89"); return -1; } if (atts.getConcurrencyLevel() != 52) { LOGINFO("Concurrency level of SubRegion21 is not 52"); return -1; } if (atts.getEntryIdleTimeout().count() != 10) { LOGINFO("Entryidletimeout of SubRegion21 is not 10"); return -1; } if (atts.getEntryIdleTimeoutAction() != ExpirationAction::INVALIDATE) { LOGINFO("Entryidletimeoutaction of SubRegion21 is not invalidate"); return -1; } if (atts.getRegionIdleTimeout().count() != 20) { LOGINFO("Regionidletimeout of SubRegion21 is not 20"); return -1; } if (atts.getRegionIdleTimeoutAction() != ExpirationAction::DESTROY) { LOGINFO("Regionidletimeoutaction of SubRegion21 is not destroy"); return -1; } std::cout << "Verify whether region 'Root2' has correct attributes" << std::endl; atts = Root2->getAttributes(); if (atts.getCachingEnabled() != true) { LOGINFO("Caching is not enabled in Root2"); return -1; } if (atts.getInitialCapacity() != 25) { LOGINFO("Initial capacity of Root2 is not 10"); return -1; } if (fabs(atts.getLoadFactor() - 0.32) > 0.001) { LOGINFO("Load factor of Root2 is not 0.0.32"); return -1; } if (atts.getConcurrencyLevel() != 16) { LOGINFO("Concurrency level of Root2 is not 16"); return -1; } if (atts.getEntryIdleTimeout().count() != 10) { LOGINFO("Entryidletimeout of Root2 is not 10"); return -1; } if (atts.getEntryIdleTimeoutAction() != ExpirationAction::INVALIDATE) { LOGINFO("Entryidletimeoutaction of Root2 is not invalidate"); return -1; } if (atts.getEntryTimeToLive().count() != 0) { LOGINFO("Entrytimetolive of Root2 is not 0"); return -1; } if (atts.getEntryTimeToLiveAction() != ExpirationAction::LOCAL_INVALIDATE) { LOGINFO("Entrytimetoliveaction of Root2 is not local_invalidate"); return -1; } if (atts.getRegionIdleTimeout().count() != 0) { LOGINFO("Regionidletimeout of Root2 is not 0"); return -1; } if (atts.getRegionIdleTimeoutAction() != ExpirationAction::INVALIDATE) { LOGINFO("Regionidletimeoutaction of Root2 is not invalidate"); return -1; } if (atts.getRegionTimeToLive().count() != 0) { LOGINFO("Regiontimetolive of Root2 is not 0"); return -1; } if (atts.getRegionTimeToLiveAction() != ExpirationAction::DESTROY) { LOGINFO("Regiontimetoliveaction of Root2 is not destroy"); return -1; } cptr->close(); return 0; } BEGIN_TEST(ValidXmlTestRefid) { int res = testXmlCacheCreationWithRefid("/resources/valid_cache_refid.xml"); if (res != 0) { FAIL("Test Failed."); } res = testXmlCacheCreationWithRefid( "/resources/valid_cache_region_refid.xml"); if (res != 0) { FAIL("Test Failed."); } } END_TEST(ValidXmlTestRefid) mycolab/ncbi-blast /* $Id: id1_client.hpp 553855 2017-12-22 14:56:49Z ucko $ * =========================================================================== * * 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. * * =========================================================================== * * Author: , NCBI * * File Description: * ID1 network client * * Remark: * This code was originally generated by application DATATOOL * using specifications from the data definition file * 'id1.asn'. */ #ifndef OBJECTS_ID1_ID1_CLIENT_HPP #define OBJECTS_ID1_ID1_CLIENT_HPP // generated includes #include // generated classes BEGIN_NCBI_SCOPE BEGIN_objects_SCOPE // namespace ncbi::objects:: class NCBI_ID1_EXPORT CID1Client : public CID1Client_Base { typedef CID1Client_Base Tparent; public: // constructor CID1Client(void); // destructor ~CID1Client(void); // overloaded to give explanations of error codes void Ask(const TRequest& request, TReply& reply, TReplyChoice::E_Choice wanted); // ensure that the base class's other Ask remains available // (not all compilers handle the appropriate "using" directive) void Ask(const TRequest& request, TReply& reply) { CID1Client_Base::Ask(request, reply); } void SetAllowDeadEntries(bool ok) { m_AllowDeadEntries = ok; } bool GetAllowDeadEntries(void) { return m_AllowDeadEntries; } virtual CRef AskGetsefromgi(const CID1server_maxcomplex& req, TReply* reply = 0); // Simplified interface for retrieving entries by gi or sequence id CRef FetchEntry(TGi gi, int max_complexity = 0); CRef FetchEntry(const CSeq_id& id, int max_complexity = 0); CRef FetchEntry(const string& id_string, int max_complexity = 0); protected: void x_Disconnect(void); private: bool m_AllowDeadEntries; // Prohibit copy constructor and assignment operator CID1Client(const CID1Client& value); CID1Client& operator=(const CID1Client& value); }; /////////////////// CID1Client inline methods // constructor inline CID1Client::CID1Client(void) : m_AllowDeadEntries(false) { } /////////////////// end of CID1Client inline methods END_objects_SCOPE // namespace ncbi::objects:: END_NCBI_SCOPE #endif // OBJECTS_ID1_ID1_CLIENT_HPP /* Original file checksum: lines: 93, chars: 2368, CRC32: 45b6687e */ SystemExplorer/SemaphoreObjectType.cpp #include "pch.h" #include "SemaphoreObjectType.h" #include "NtDll.h" SemaphoreObjectType::SemaphoreObjectType(int index, PCWSTR name) : ObjectType(index, name) { } CString SemaphoreObjectType::GetDetails(HANDLE hSemaphore) { CString details; NT::SEMAPHORE_BASIC_INFORMATION info; if (NT_SUCCESS(NT::NtQuerySemaphore(hSemaphore, NT::SemaphoreBasicInformation, &info, sizeof(info), nullptr))) { details.Format(L"Maximum: %d (0x%X), Current: %d (0x%X)", info.MaximumCount, info.MaximumCount, info.CurrentCount, info.CurrentCount); } return details; } /** * Copyright (C) Mellanox Technologies Ltd. 2001-2014. ALL RIGHTS RESERVED. * Copyright (C) UT-Battelle, LLC. 2014. ALL RIGHTS RESERVED. * Copyright (C) ARM Ltd. 2016.All rights reserved. * See file LICENSE for terms. */ extern "C" { #include #include #include } #include #include "uct_test.h" class test_uct_wakeup : public uct_test { public: void initialize() { uct_test::init(); m_e1 = uct_test::create_entity(0); m_entities.push_back(m_e1); m_e2 = uct_test::create_entity(0); m_entities.push_back(m_e2); m_e1->connect(0, *m_e2, 0); m_e2->connect(0, *m_e1, 0); } typedef struct { unsigned length; /* data follows */ } recv_desc_t; static ucs_status_t ib_am_handler(void *arg, void *data, size_t length, unsigned flags) { recv_desc_t *my_desc = (recv_desc_t *) arg; uint64_t *test_ib_hdr = (uint64_t *) data; uint64_t *actual_data = (uint64_t *) test_ib_hdr + 1; unsigned data_length = length - sizeof(test_ib_hdr); my_desc->length = data_length; if (*test_ib_hdr == 0xbeef) { memcpy(my_desc + 1, actual_data , data_length); } return UCS_OK; } void cleanup() { uct_test::cleanup(); } protected: entity *m_e1, *m_e2; }; UCS_TEST_P(test_uct_wakeup, am) { uint64_t send_data = 0xdeadbeef; uint64_t test_ib_hdr = 0xbeef; recv_desc_t *recv_buffer; ucs::handle wakeup_handle; struct pollfd wakeup_fd; ucs_status_t status; initialize(); check_caps(UCT_IFACE_FLAG_WAKEUP | UCT_IFACE_FLAG_AM_CB_SYNC); recv_buffer = (recv_desc_t *) malloc(sizeof(*recv_buffer) + sizeof(send_data)); recv_buffer->length = 0; /* Initialize length to 0 */ /* set a callback for the uct to invoke for receiving the data */ uct_iface_set_am_handler(m_e2->iface(), 0, ib_am_handler, recv_buffer, UCT_AM_CB_FLAG_SYNC); /* create receiver wakeup */ UCS_TEST_CREATE_HANDLE(uct_wakeup_h, wakeup_handle, uct_wakeup_close, uct_wakeup_open, m_e2->iface(), UCT_WAKEUP_RX_SIGNALED_AM); ASSERT_EQ(UCS_OK, uct_wakeup_efd_get(wakeup_handle, &wakeup_fd.fd)); wakeup_fd.events = POLLIN; EXPECT_EQ(0, poll(&wakeup_fd, 1, 0)); ASSERT_EQ(UCS_OK, uct_wakeup_efd_arm(wakeup_handle)); EXPECT_EQ(0, poll(&wakeup_fd, 1, 0)); /* send the data */ uct_ep_am_short(m_e1->ep(0), 0, test_ib_hdr, &send_data, sizeof(send_data)); /* make sure the file descriptor IS signaled ONCE */ ASSERT_EQ(1, poll(&wakeup_fd, 1, 1000*ucs::test_time_multiplier())); do { status = uct_wakeup_efd_arm(wakeup_handle); } while (UCS_ERR_BUSY == status); ASSERT_EQ(UCS_OK, status); wakeup_fd.revents = 0; EXPECT_EQ(0, poll(&wakeup_fd, 1, 0)); /* re-arm before expect any messages but ud transport MAY do extra messaging */ if ((GetParam()->tl_name).substr(0, 2) == "ud") { do { status = uct_wakeup_efd_arm(wakeup_handle); } while (UCS_ERR_BUSY == status); } else { status = uct_wakeup_efd_arm(wakeup_handle); } ASSERT_EQ(UCS_OK, status); /* send the data again */ uct_ep_am_short(m_e1->ep(0), 0, test_ib_hdr, &send_data, sizeof(send_data)); /* make sure the file descriptor IS signaled */ ASSERT_EQ(1, poll(&wakeup_fd, 1, 1000*ucs::test_time_multiplier())); EXPECT_EQ(UCS_OK, uct_wakeup_wait(wakeup_handle)); free(recv_buffer); } UCT_INSTANTIATE_NO_SELF_TEST_CASE(test_uct_wakeup); /* Copyright (c) 2017-2021, */ #include "roq/samples/example-5/producer.h" #include #include #include #include "roq/logging.h" using namespace std::chrono_literals; namespace roq { namespace samples { namespace example_5 { Producer::Producer(client::Dispatcher &dispatcher) : dispatcher_(dispatcher) { } void Producer::operator()(const Event &) { assert(!static_cast(thread_) && !terminating_); thread_ = std::make_unique([this]() { run(); }); } void Producer::operator()(const Event &) { assert(static_cast(thread_) && !terminating_); terminating_ = true; thread_->join(); } void Producer::run() { log::info("producer was started"_sv); while (!terminating_) { std::string text = "hello world"_s; roq::span message{ reinterpret_cast(std::data(text)), text.length() + 1, // including trailing null }; client::CustomMessage custom_message{ .message = message, }; dispatcher_.enqueue(custom_message); std::this_thread::sleep_for(100ms); } log::info("producer was terminated"_sv); } } // namespace example_5 } // namespace samples } // namespace roq /* -*- C++ -*- ------------------------------------------------------------ @@COPYRIGHT@@ *-----------------------------------------------------------------------*/ /** @file */ // Make sure the main header compiles cleanly: #include #include #include /* Testing headers: */ #include "catch_runner.h" CATCH_TEST_CASE("basis 2D, basis1") { cml::matrix22d M; // column basis cml::matrix_set_x_basis_vector_2D(M, cml::vector2d(1., 2.)); cml::matrix_set_y_basis_vector_2D(M, cml::vector2d(3., 4.)); auto b1 = cml::matrix_get_x_basis_vector_2D(M); auto b2 = cml::matrix_get_y_basis_vector_2D(M); CATCH_CHECK(b1[0] == 1.); CATCH_CHECK(b1[1] == 2.); CATCH_CHECK(b2[0] == 3.); CATCH_CHECK(b2[1] == 4.); } CATCH_TEST_CASE("basis 2D, basis2") { cml::matrix22d M; // column basis cml::matrix_set_transposed_x_basis_vector_2D(M, cml::vector2d(1., 2.)); cml::matrix_set_transposed_y_basis_vector_2D(M, cml::vector2d(3., 4.)); auto b1 = cml::matrix_get_transposed_x_basis_vector_2D(M); auto b2 = cml::matrix_get_transposed_y_basis_vector_2D(M); CATCH_CHECK(b1[0] == 1.); CATCH_CHECK(b1[1] == 2.); CATCH_CHECK(b2[0] == 3.); CATCH_CHECK(b2[1] == 4.); } CATCH_TEST_CASE("basis 2D, basis3") { cml::matrix22d M; // column basis cml::matrix_set_basis_vectors_2D( M, cml::vector2d(1., 2.), cml::vector2d(3., 4.)); cml::vectord b1, b2; cml::matrix_get_basis_vectors_2D(M, b1, b2); CATCH_CHECK(b1[0] == 1.); CATCH_CHECK(b1[1] == 2.); CATCH_CHECK(b2[0] == 3.); CATCH_CHECK(b2[1] == 4.); } CATCH_TEST_CASE("basis 2D, basis4") { cml::matrix22d M; // column basis cml::matrix_set_transposed_basis_vectors_2D( M, cml::vector2d(1., 2.), cml::vector2d(3., 4.)); cml::vectord b1, b2; cml::matrix_get_transposed_basis_vectors_2D(M, b1, b2); CATCH_CHECK(b1[0] == 1.); CATCH_CHECK(b1[1] == 2.); CATCH_CHECK(b2[0] == 3.); CATCH_CHECK(b2[1] == 4.); } CATCH_TEST_CASE("basis 3D, basis1") { cml::matrix33d M; // column basis cml::matrix_set_x_basis_vector(M, cml::vector3d(1., 2., 3.)); cml::matrix_set_y_basis_vector(M, cml::vector3d(4., 5., 6.)); cml::matrix_set_z_basis_vector(M, cml::vector3d(7., 8., 9.)); auto b1 = cml::matrix_get_x_basis_vector(M); auto b2 = cml::matrix_get_y_basis_vector(M); auto b3 = cml::matrix_get_z_basis_vector(M); CATCH_CHECK(b1[0] == 1.); CATCH_CHECK(b1[1] == 2.); CATCH_CHECK(b1[2] == 3.); CATCH_CHECK(b2[0] == 4.); CATCH_CHECK(b2[1] == 5.); CATCH_CHECK(b2[2] == 6.); CATCH_CHECK(b3[0] == 7.); CATCH_CHECK(b3[1] == 8.); CATCH_CHECK(b3[2] == 9.); } CATCH_TEST_CASE("basis 3D, basis2") { cml::matrix33d M; // column basis cml::matrix_set_transposed_x_basis_vector(M, cml::vector3d(1., 2., 3.)); cml::matrix_set_transposed_y_basis_vector(M, cml::vector3d(4., 5., 6.)); cml::matrix_set_transposed_z_basis_vector(M, cml::vector3d(7., 8., 9.)); auto b1 = cml::matrix_get_transposed_x_basis_vector(M); auto b2 = cml::matrix_get_transposed_y_basis_vector(M); auto b3 = cml::matrix_get_transposed_z_basis_vector(M); CATCH_CHECK(b1[0] == 1.); CATCH_CHECK(b1[1] == 2.); CATCH_CHECK(b1[2] == 3.); CATCH_CHECK(b2[0] == 4.); CATCH_CHECK(b2[1] == 5.); CATCH_CHECK(b2[2] == 6.); CATCH_CHECK(b3[0] == 7.); CATCH_CHECK(b3[1] == 8.); CATCH_CHECK(b3[2] == 9.); } CATCH_TEST_CASE("basis 3D, basis3") { cml::matrix33d M; // column basis cml::matrix_set_basis_vectors(M, cml::vector3d(1., 2., 3.), cml::vector3d(4., 5., 6.), cml::vector3d(7., 8., 9.)); cml::vectord b1, b2, b3; cml::matrix_get_basis_vectors(M, b1, b2, b3); CATCH_CHECK(b1[0] == 1.); CATCH_CHECK(b1[1] == 2.); CATCH_CHECK(b1[2] == 3.); CATCH_CHECK(b2[0] == 4.); CATCH_CHECK(b2[1] == 5.); CATCH_CHECK(b2[2] == 6.); CATCH_CHECK(b3[0] == 7.); CATCH_CHECK(b3[1] == 8.); CATCH_CHECK(b3[2] == 9.); } CATCH_TEST_CASE("basis 3D, basis4") { cml::matrix33d M; // column basis cml::matrix_set_transposed_basis_vectors(M, cml::vector3d(1., 2., 3.), cml::vector3d(4., 5., 6.), cml::vector3d(7., 8., 9.)); cml::vectord b1, b2, b3; cml::matrix_get_transposed_basis_vectors(M, b1, b2, b3); CATCH_CHECK(b1[0] == 1.); CATCH_CHECK(b1[1] == 2.); CATCH_CHECK(b1[2] == 3.); CATCH_CHECK(b2[0] == 4.); CATCH_CHECK(b2[1] == 5.); CATCH_CHECK(b2[2] == 6.); CATCH_CHECK(b3[0] == 7.); CATCH_CHECK(b3[1] == 8.); CATCH_CHECK(b3[2] == 9.); } CATCH_TEST_CASE("basis nD, basis1") { auto M = cml::matrix34d_c( 1., 0., 0., 3., 0., 1., 0., 2., 0., 0., 1., 1. ); auto T = cml::matrix_get_basis_vector_nD(M, 3); CATCH_CHECK(T[0] == 3.); CATCH_CHECK(T[1] == 2.); CATCH_CHECK(T[2] == 1.); } CATCH_TEST_CASE("basis nD, basis2") { auto M = cml::matrix43d_r( 1., 0., 0., 0., 1., 0., 0., 0., 1., 3., 2., 1. ); auto T = cml::matrix_get_basis_vector_nD(M, 3); CATCH_CHECK(T[0] == 3.); CATCH_CHECK(T[1] == 2.); CATCH_CHECK(T[2] == 1.); } // ------------------------------------------------------------------------- // vim:ft=cpp:sw=2 0 #include "eventmanager.h" #include "eventmanager_p.h" using namespace AB; EventManager::EventManager(QObject *parent) : QObject(parent) , d_ptr(new EventManagerPrivate(this)) { } EventManager::~EventManager() { } 0 /** * Algorithms - searching * ternary_search.cpp * Purpose: Performs ternary search on an array * * @author * @version 1.0 27/10/18 */ #include using namespace std; /** * Searches for a key in an array using Ternary Search algorithm. * * @param arr the array to search from (type T). * @param size the size of the array. * @param key the element to search for (type T). * @returns The index of the key element (default: -1) */ template int ternarySearch(T *arr, int n, T key) { int start = 0; int end = n - 1; while (start <= end) { int mid1 = start + (end - start) / 3; int mid2 = end - (end - start) / 3; if (arr[mid1] == key) return mid1; if (arr[mid2] == key) return mid2; else if (arr[mid1] > key) end = mid1 - 1; else if (arr[mid2] < key) start = mid2 + 1; else { start = mid1 + 1; end = mid2 - 1; } } return -1; }FFHixio/perfetto /* * Copyright (C) 2020 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 "src/profiling/common/profiler_guardrails.h" #include #include "perfetto/ext/base/optional.h" #include "perfetto/ext/base/watchdog_posix.h" namespace perfetto { namespace profiling { base::Optional ProfilerCpuGuardrails::GetCputimeSec() { if (!stat_fd_) { return base::nullopt; } lseek(stat_fd_.get(), 0, SEEK_SET); base::ProcStat stat; if (!ReadProcStat(stat_fd_.get(), &stat)) { PERFETTO_ELOG("Failed to read stat file to enforce guardrails."); return base::nullopt; } return (stat.utime + stat.stime) / static_cast(sysconf(_SC_CLK_TCK)); } } // namespace profiling } // namespace perfetto /* Copyright (c) 2017, 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. 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. */ /* well separated pair decomposition */ #ifndef WSPD_HH_ #define WSPD_HH_ #include #include #include #include #include #include "point_set.hh" #include "tree.hh" template struct wspd { PointSet& Set; tree split_tree; double sep; using box = std::shared_ptr::node>; using wspair = typename std::pair; std::vector pairs; wspd(PointSet& set, double s) : Set(set), split_tree(Set), sep(s) { decompose(split_tree.root); } wspd(PointSet& set, double s, std::function*)>& splitter) : Set(set), split_tree(Set, splitter), sep(s) { decompose(split_tree.root); } /* * No decompose version, usefull for external implementation of the * decomposition (like parallel implementation.) */ wspd(PointSet& set, double s, bool) : Set(set), split_tree(Set), sep(s) {} wspd(PointSet& set, double s, std::function*)>& splitter, bool) : Set(set), split_tree(Set, splitter), sep(s) {} template bool wellsepareted(BOX b1, BOX b2) { double r = std::max(b1->radius, b2->radius); return b1->dist(b2) >= sep * r; } void addpair(box b1, box b2) { pairs.push_back({b1, b2}); b1->is_in_pair = true; b2->is_in_pair = true; } void findpairs(box b1, box b2) { if (wellsepareted(b1, b2)) { addpair(b1, b2); return; } size_t d1 = b1->maxd(), d2 = b2->maxd(); if (b1->sizes[d1] > b2->sizes[d2]) { std::swap(b1, b2); } findpairs(b1, b2->left); findpairs(b1, b2->right); } void findpairs(box b1, box b2, std::function& edge) { if (wellsepareted(b1, b2)) { addpair(b1, b2); edge(b1, b2); return; } size_t d1 = b1->maxd(), d2 = b2->maxd(); if (b1->sizes[d1] > b2->sizes[d2]) { std::swap(b1, b2); } findpairs(b1, b2->left, edge); findpairs(b1, b2->right, edge); } void decompose(box n) { if (n->leaf()) return; findpairs(n->left, n->right); decompose(n->left); decompose(n->right); } }; #endif /* WSPD_HH_ */ 0 #include "il2cpp-config.h" #ifndef _MSC_VER # include #else # include #endif #include #include #include #include #include #include #include #include "codegen/il2cpp-codegen.h" #include "il2cpp-object-internals.h" // System.Char[] struct CharU5BU5D_t4CC6ABF0AD71BEC97E3C2F1E9C5677E46D3A75C2; // System.Collections.Generic.List`1 struct List_1_t05CC3C859AB5E6024394EF9A42E3E696628CA02D; // System.Collections.Generic.List`1 struct List_1_t2762C811E470D336E31761384C6E5382164DA4C7; // System.Collections.Generic.List`1 struct List_1_tF00B86100455886AD0B3A0B82FE6C94700D131D0; // System.Collections.IDictionary struct IDictionary_t1BD5C1546718A374EA8122FBD6C6EE45331E8CE7; // System.Collections.IEnumerator struct IEnumerator_t8789118187258CC88B77AFAC6315B5AF87D3E18A; // System.Diagnostics.StackTrace[] struct StackTraceU5BU5D_t855F09649EA34DEE7C1B6F088E0538E3CCC3F196; // System.IntPtr[] struct IntPtrU5BU5D_t4DC01DCB9A6DF6C9792A6513595D7A11E637DCDD; // System.NotSupportedException struct NotSupportedException_tE75B318D6590A02A5D9B29FD97409B1750FA0010; // System.Object[] struct ObjectU5BU5D_t3C9242B5C88A48B2A5BD9FDA6CD0024E792AF08A; // System.Runtime.Serialization.SafeSerializationManager struct SafeSerializationManager_t4A754D86B0F784B18CBC36C073BA564BED109770; // System.String struct String_t; // System.Void struct Void_t22962CB4C05B1D89B55A6E1139F0E87A90987017; // UnityEngine.AnimationCurve struct AnimationCurve_tD2F265379583AAF1BF8D84F1BB8DB12980FA504C; // UnityEngine.AudioClip struct AudioClip_tCC3C35F579203CE2601243585AB3D6953C3BA051; // UnityEngine.AudioClip/PCMReaderCallback struct PCMReaderCallback_t9B87AB13DCD37957B045554BF28A57697E6B8EFB; // UnityEngine.AudioClip/PCMSetPositionCallback struct PCMSetPositionCallback_t092ED33043C0279B5E4D343EBCBD516CEF260801; // UnityEngine.AudioClip[] struct AudioClipU5BU5D_t03931BD44BC339329210676E452B8ECD3EC171C2; // UnityEngine.AudioSource struct AudioSource_t5196F862B4E60F404613361C90D87FBDD041E93C; // UnityEngine.Behaviour struct Behaviour_tBDC7E9C3C898AD8348891B82D3E345801D920CA8; // UnityEngine.Collider struct Collider_t0FEEB36760860AD21B3B1F0509C365B393EC4BDF; // UnityEngine.Collider[] struct ColliderU5BU5D_t70D1FDAE17E4359298B2BAA828048D1B7CFFE252; // UnityEngine.Component struct Component_t05064EF382ABCAF4B8C94F8A350EA85184C26621; // UnityEngine.GameObject struct GameObject_tBD1244AD56B4E59AAD76E5E7C9282EC5CE434F0F; // UnityEngine.Light struct Light_tFDE490EADBC7E080F74CA804929513AF07C31A6C; // UnityEngine.MonoBehaviour struct MonoBehaviour_t4A60845CF505405AF8BE8C61CC07F75CADEF6429; // UnityEngine.Object struct Object_tAE11E5E46CD5C37C9F3E8950C00CD8B45666A2D0; // UnityEngine.ParticleCollisionEvent[] struct ParticleCollisionEventU5BU5D_t771CB4A499CC97F3340C673D227DD1F5969EB9B9; // UnityEngine.ParticleSystem struct ParticleSystem_t45DA87A3E83E738DA3FDAA5A48A133F1A1247C3D; // UnityEngine.ParticleSystem[] struct ParticleSystemU5BU5D_t58EE604F685D8CBA8EFC9353456969F5A1B2FBB9; // UnityEngine.Renderer struct Renderer_t0556D67DD582620D1F495627EDE30D03284151F4; // UnityEngine.Rigidbody struct Rigidbody_tE0A58EE5A1F7DC908EFFB4F0D795AC9552A750A5; // UnityEngine.Rigidbody[] struct RigidbodyU5BU5D_t9F5D984DC2777DA3C6E2BEC6CE9D0F1C3D2E851B; // UnityEngine.SphereCollider struct SphereCollider_tAC3E5E20B385DF1C0B17F3EA5C7214F71367706F; // UnityEngine.Transform struct Transform_tBB9E78A2766C3C83599A8F66EDE7D1FCAFC66EDA; // UnityEngine.Transform[] struct TransformU5BU5D_t4F5A1132877D8BA66ABC0A9A7FADA4E0237A7804; // UnityStandardAssets.Effects.AfterburnerPhysicsForce struct AfterburnerPhysicsForce_t753048E9DC6DB55FA797EA775B76014E1E7F204B; // UnityStandardAssets.Effects.ExplosionFireAndDebris struct ExplosionFireAndDebris_tACCFCC1184BB9A8C3A0B39D99FFC831E76F9EECB; // UnityStandardAssets.Effects.ExplosionFireAndDebris/d__4 struct U3CStartU3Ed__4_t945A707CD8C01DA1C37AE2DD9D0A904C80F58139; // UnityStandardAssets.Effects.ExplosionPhysicsForce struct ExplosionPhysicsForce_t59463D9C69E811AF9C885416501F2C8833800C58; // UnityStandardAssets.Effects.ExplosionPhysicsForce/d__1 struct U3CStartU3Ed__1_tFA687701957C85736794A1CD53601F73339D788F; // UnityStandardAssets.Effects.ExtinguishableParticleSystem struct ExtinguishableParticleSystem_tD91348BD8771EB84F5369DA844F390BE915ADB64; // UnityStandardAssets.Effects.FireLight struct FireLight_tBDF3DBBD1B6288E05ECBDCDB787FBB8ABD8572C5; // UnityStandardAssets.Effects.Hose struct Hose_t411AEC20AB5A70AEFCF03FCB2418F0C8EB14C2D2; // UnityStandardAssets.Effects.ParticleSystemMultiplier struct ParticleSystemMultiplier_t8EBFEF83EBA48DD7F6517ABFFBE2CD051CB2C748; // UnityStandardAssets.Effects.SmokeParticles struct SmokeParticles_t556E08200E5E25126D51BFF297C7522998E3D793; // UnityStandardAssets.Effects.WaterHoseParticles struct WaterHoseParticles_t4C0EC93AEAF5B1623A7F04AF7D912D6B6438E92B; IL2CPP_EXTERN_C RuntimeClass* List_1_t2762C811E470D336E31761384C6E5382164DA4C7_il2cpp_TypeInfo_var; IL2CPP_EXTERN_C RuntimeClass* List_1_tF00B86100455886AD0B3A0B82FE6C94700D131D0_il2cpp_TypeInfo_var; IL2CPP_EXTERN_C RuntimeClass* Mathf_tFBDE6467D269BFE410605C7D806FD9991D4A89CB_il2cpp_TypeInfo_var; IL2CPP_EXTERN_C RuntimeClass* NotSupportedException_tE75B318D6590A02A5D9B29FD97409B1750FA0010_il2cpp_TypeInfo_var; IL2CPP_EXTERN_C RuntimeClass* Object_tAE11E5E46CD5C37C9F3E8950C00CD8B45666A2D0_il2cpp_TypeInfo_var; IL2CPP_EXTERN_C RuntimeClass* Quaternion_t319F3319A7D43FFA5D819AD6C0A98851F0095357_il2cpp_TypeInfo_var; IL2CPP_EXTERN_C RuntimeClass* SphereCollider_tAC3E5E20B385DF1C0B17F3EA5C7214F71367706F_il2cpp_TypeInfo_var; IL2CPP_EXTERN_C RuntimeClass* U3CStartU3Ed__1_tFA687701957C85736794A1CD53601F73339D788F_il2cpp_TypeInfo_var; IL2CPP_EXTERN_C RuntimeClass* U3CStartU3Ed__4_t945A707CD8C01DA1C37AE2DD9D0A904C80F58139_il2cpp_TypeInfo_var; IL2CPP_EXTERN_C RuntimeClass* Vector3U5BU5D_tB9EC3346CC4A0EA5447D968E84A9AC1F6F372C28_il2cpp_TypeInfo_var; IL2CPP_EXTERN_C RuntimeClass* Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720_il2cpp_TypeInfo_var; IL2CPP_EXTERN_C RuntimeClass* WaterHoseParticles_t4C0EC93AEAF5B1623A7F04AF7D912D6B6438E92B_il2cpp_TypeInfo_var; IL2CPP_EXTERN_C String_t* _stringLiteral4796C2FBF2E7B58822864E6AA158FDAF94586F93; IL2CPP_EXTERN_C const RuntimeMethod* Component_GetComponent_TisAudioSource_t5196F862B4E60F404613361C90D87FBDD041E93C_m04C8E98F2393C77979C9D8F6DE1D98343EF025E8_RuntimeMethod_var; IL2CPP_EXTERN_C const RuntimeMethod* Component_GetComponent_TisCollider_t0FEEB36760860AD21B3B1F0509C365B393EC4BDF_m6B8E8E0E0AF6B08652B81B7950FC5AF63EAD40C6_RuntimeMethod_var; IL2CPP_EXTERN_C const RuntimeMethod* Component_GetComponent_TisLight_tFDE490EADBC7E080F74CA804929513AF07C31A6C_m1DCED5DB1934151FC68A8E7CAECF7986359D7107_RuntimeMethod_var; IL2CPP_EXTERN_C const RuntimeMethod* Component_GetComponent_TisParticleSystemMultiplier_t8EBFEF83EBA48DD7F6517ABFFBE2CD051CB2C748_m77EDAEF51740299BC986B0DA36AB7282BB8DDD45_RuntimeMethod_var; IL2CPP_EXTERN_C const RuntimeMethod* Component_GetComponent_TisParticleSystem_t45DA87A3E83E738DA3FDAA5A48A133F1A1247C3D_mA6EBF435A59643B674086A2F309F6A4DCB263452_RuntimeMethod_var; IL2CPP_EXTERN_C const RuntimeMethod* Component_GetComponent_TisRigidbody_tE0A58EE5A1F7DC908EFFB4F0D795AC9552A750A5_m3F58A77E3F62D9C80D7B49BA04E3D4809264FD5C_RuntimeMethod_var; IL2CPP_EXTERN_C const RuntimeMethod* Component_GetComponentsInChildren_TisParticleSystem_t45DA87A3E83E738DA3FDAA5A48A133F1A1247C3D_mD5AEF673286CB17B689F765BB71E83509548DC41_RuntimeMethod_var; IL2CPP_EXTERN_C const RuntimeMethod* Enumerator_Dispose_mECFDE242B9B4ECC8048254467FCB58F6EA7333F6_RuntimeMethod_var; IL2CPP_EXTERN_C const RuntimeMethod* Enumerator_MoveNext_m9A51F685E9FE881F75850562F97DD04FB51B3F0F_RuntimeMethod_var; IL2CPP_EXTERN_C const RuntimeMethod* Enumerator_get_Current_mC1CD020347F81EDABBA39647711D3D2E115176C7_RuntimeMethod_var; IL2CPP_EXTERN_C const RuntimeMethod* List_1_Add_mA7DDE87A050C0636FDCC9DC4A5BCA55A5379A4B8_RuntimeMethod_var; IL2CPP_EXTERN_C const RuntimeMethod* List_1_Contains_m4D1DE7EDA972C9BCD4617A52BFF4CFE08895758C_RuntimeMethod_var; IL2CPP_EXTERN_C const RuntimeMethod* List_1_GetEnumerator_m7CB8469ED2AE9E0CA1FEFF4C60991DFF8BD8CFF3_RuntimeMethod_var; IL2CPP_EXTERN_C const RuntimeMethod* List_1__ctor_m377714278A7FAB4D7514D181355D61B01B3427B0_RuntimeMethod_var; IL2CPP_EXTERN_C const RuntimeMethod* List_1__ctor_m8F8DC666C2D1350D6CDDE96E73998792E882CF46_RuntimeMethod_var; IL2CPP_EXTERN_C const RuntimeMethod* List_1_get_Item_m095B750642DEE222CA241EE9D2392CA6E200FA8D_RuntimeMethod_var; IL2CPP_EXTERN_C const RuntimeMethod* Object_Instantiate_TisTransform_tBB9E78A2766C3C83599A8F66EDE7D1FCAFC66EDA_m8BCC51A95F42E99B9033022D8BF0EABA04FED8F0_RuntimeMethod_var; IL2CPP_EXTERN_C const RuntimeMethod* U3CStartU3Ed__1_System_Collections_IEnumerator_Reset_m8BE9B7F5466A03EDD437E3D16EB3E659B51ABC0E_RuntimeMethod_var; IL2CPP_EXTERN_C const RuntimeMethod* U3CStartU3Ed__4_System_Collections_IEnumerator_Reset_m886FA065B7C64EA3A746502C9F6BF104B9801F07_RuntimeMethod_var; IL2CPP_EXTERN_C const uint32_t AfterburnerPhysicsForce_FixedUpdate_m90286B7CDABBED931E9D13E5D879E6EC41BF6E8A_MetadataUsageId; IL2CPP_EXTERN_C const uint32_t AfterburnerPhysicsForce_OnDrawGizmosSelected_m8E75C894A4544C40EB1FD3DA8883E3358BAF8AA3_MetadataUsageId; IL2CPP_EXTERN_C const uint32_t AfterburnerPhysicsForce_OnEnable_m31ABCDDA8E500224F25244C9D3FE44CBDD45D7CE_MetadataUsageId; IL2CPP_EXTERN_C const uint32_t ExplosionFireAndDebris_AddFire_m781F3E400896C4F2E2B4A24FAEFE52D01ED26C0B_MetadataUsageId; IL2CPP_EXTERN_C const uint32_t ExplosionFireAndDebris_Start_m85654B2EA9348AE14094A4CDCA1ECD714E4CBC22_MetadataUsageId; IL2CPP_EXTERN_C const uint32_t ExplosionPhysicsForce_Start_m22750184987B8A375DA674EF615F5ECD1DAD04C5_MetadataUsageId; IL2CPP_EXTERN_C const uint32_t ExtinguishableParticleSystem_Start_m442E9165E311C7DC5AE322C5CF8B8D6A2325DC39_MetadataUsageId; IL2CPP_EXTERN_C const uint32_t FireLight_Start_mBC43BC2A9EDAD47A5D43C96C04E1AECC4405B81D_MetadataUsageId; IL2CPP_EXTERN_C const uint32_t FireLight_Update_mE6D64BEF14D90624104BC092626B738B75D8D0F7_MetadataUsageId; IL2CPP_EXTERN_C const uint32_t Hose_Update_mF09247CA136AF92D5586DD9C95823C7E9A6AE939_MetadataUsageId; IL2CPP_EXTERN_C const uint32_t ParticleSystemMultiplier_Start_m9629829804A66FA8E1BA25039F0BCD4447D1785D_MetadataUsageId; IL2CPP_EXTERN_C const uint32_t SmokeParticles_Start_m1A4CBEB9EDF7F792FCF7F96D9435B6C0B0A94DD6_MetadataUsageId; IL2CPP_EXTERN_C const uint32_t U3CStartU3Ed__1_MoveNext_m69D4364C306F1FC8F21C33E29E6C125B2B9EEF2B_MetadataUsageId; IL2CPP_EXTERN_C const uint32_t U3CStartU3Ed__1_System_Collections_IEnumerator_Reset_m8BE9B7F5466A03EDD437E3D16EB3E659B51ABC0E_MetadataUsageId; IL2CPP_EXTERN_C const uint32_t U3CStartU3Ed__4_MoveNext_m4846C74D5F4A4FF39164BCFD48198D976AA0F953_MetadataUsageId; IL2CPP_EXTERN_C const uint32_t U3CStartU3Ed__4_System_Collections_IEnumerator_Reset_m886FA065B7C64EA3A746502C9F6BF104B9801F07_MetadataUsageId; IL2CPP_EXTERN_C const uint32_t WaterHoseParticles_OnParticleCollision_m8E8399822017058F9AE64E3D9F7B47208553ED70_MetadataUsageId; IL2CPP_EXTERN_C const uint32_t WaterHoseParticles_Start_m6CFC5FEBF60CBD00CDE17E0A1EEC12163EC9A792_MetadataUsageId; IL2CPP_EXTERN_C const uint32_t WaterHoseParticles__ctor_m9E63BF105FF8511932CBF7FAA1C664713744DCA3_MetadataUsageId; struct Exception_t_marshaled_com; struct Exception_t_marshaled_pinvoke; struct AudioClipU5BU5D_t03931BD44BC339329210676E452B8ECD3EC171C2; struct ColliderU5BU5D_t70D1FDAE17E4359298B2BAA828048D1B7CFFE252; struct ParticleCollisionEventU5BU5D_t771CB4A499CC97F3340C673D227DD1F5969EB9B9; struct ParticleSystemU5BU5D_t58EE604F685D8CBA8EFC9353456969F5A1B2FBB9; struct TransformU5BU5D_t4F5A1132877D8BA66ABC0A9A7FADA4E0237A7804; struct Vector3U5BU5D_tB9EC3346CC4A0EA5447D968E84A9AC1F6F372C28; IL2CPP_EXTERN_C_BEGIN IL2CPP_EXTERN_C_END #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // struct U3CModuleU3E_tF157A75827DFDE1F9E89CA3CBB54B07FA9E227FC { public: public: }; // System.Object struct Il2CppArrayBounds; // System.Array // System.Collections.Generic.List`1 struct List_1_t2762C811E470D336E31761384C6E5382164DA4C7 : public RuntimeObject { public: // T[] System.Collections.Generic.List`1::_items ParticleCollisionEventU5BU5D_t771CB4A499CC97F3340C673D227DD1F5969EB9B9* ____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; // System.Object System.Collections.Generic.List`1::_syncRoot RuntimeObject * ____syncRoot_4; public: inline static int32_t get_offset_of__items_1() { return static_cast(offsetof(List_1_t2762C811E470D336E31761384C6E5382164DA4C7, ____items_1)); } inline ParticleCollisionEventU5BU5D_t771CB4A499CC97F3340C673D227DD1F5969EB9B9* get__items_1() const { return ____items_1; } inline ParticleCollisionEventU5BU5D_t771CB4A499CC97F3340C673D227DD1F5969EB9B9** get_address_of__items_1() { return &____items_1; } inline void set__items_1(ParticleCollisionEventU5BU5D_t771CB4A499CC97F3340C673D227DD1F5969EB9B9* value) { ____items_1 = value; Il2CppCodeGenWriteBarrier((void**)(&____items_1), (void*)value); } inline static int32_t get_offset_of__size_2() { return static_cast(offsetof(List_1_t2762C811E470D336E31761384C6E5382164DA4C7, ____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_t2762C811E470D336E31761384C6E5382164DA4C7, ____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; } inline static int32_t get_offset_of__syncRoot_4() { return static_cast(offsetof(List_1_t2762C811E470D336E31761384C6E5382164DA4C7, ____syncRoot_4)); } inline RuntimeObject * get__syncRoot_4() const { return ____syncRoot_4; } inline RuntimeObject ** get_address_of__syncRoot_4() { return &____syncRoot_4; } inline void set__syncRoot_4(RuntimeObject * value) { ____syncRoot_4 = value; Il2CppCodeGenWriteBarrier((void**)(&____syncRoot_4), (void*)value); } }; struct List_1_t2762C811E470D336E31761384C6E5382164DA4C7_StaticFields { public: // T[] System.Collections.Generic.List`1::_emptyArray ParticleCollisionEventU5BU5D_t771CB4A499CC97F3340C673D227DD1F5969EB9B9* ____emptyArray_5; public: inline static int32_t get_offset_of__emptyArray_5() { return static_cast(offsetof(List_1_t2762C811E470D336E31761384C6E5382164DA4C7_StaticFields, ____emptyArray_5)); } inline ParticleCollisionEventU5BU5D_t771CB4A499CC97F3340C673D227DD1F5969EB9B9* get__emptyArray_5() const { return ____emptyArray_5; } inline ParticleCollisionEventU5BU5D_t771CB4A499CC97F3340C673D227DD1F5969EB9B9** get_address_of__emptyArray_5() { return &____emptyArray_5; } inline void set__emptyArray_5(ParticleCollisionEventU5BU5D_t771CB4A499CC97F3340C673D227DD1F5969EB9B9* value) { ____emptyArray_5 = value; Il2CppCodeGenWriteBarrier((void**)(&____emptyArray_5), (void*)value); } }; // System.Collections.Generic.List`1 struct List_1_tF00B86100455886AD0B3A0B82FE6C94700D131D0 : public RuntimeObject { public: // T[] System.Collections.Generic.List`1::_items RigidbodyU5BU5D_t9F5D984DC2777DA3C6E2BEC6CE9D0F1C3D2E851B* ____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; // System.Object System.Collections.Generic.List`1::_syncRoot RuntimeObject * ____syncRoot_4; public: inline static int32_t get_offset_of__items_1() { return static_cast(offsetof(List_1_tF00B86100455886AD0B3A0B82FE6C94700D131D0, ____items_1)); } inline RigidbodyU5BU5D_t9F5D984DC2777DA3C6E2BEC6CE9D0F1C3D2E851B* get__items_1() const { return ____items_1; } inline RigidbodyU5BU5D_t9F5D984DC2777DA3C6E2BEC6CE9D0F1C3D2E851B** get_address_of__items_1() { return &____items_1; } inline void set__items_1(RigidbodyU5BU5D_t9F5D984DC2777DA3C6E2BEC6CE9D0F1C3D2E851B* value) { ____items_1 = value; Il2CppCodeGenWriteBarrier((void**)(&____items_1), (void*)value); } inline static int32_t get_offset_of__size_2() { return static_cast(offsetof(List_1_tF00B86100455886AD0B3A0B82FE6C94700D131D0, ____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_tF00B86100455886AD0B3A0B82FE6C94700D131D0, ____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; } inline static int32_t get_offset_of__syncRoot_4() { return static_cast(offsetof(List_1_tF00B86100455886AD0B3A0B82FE6C94700D131D0, ____syncRoot_4)); } inline RuntimeObject * get__syncRoot_4() const { return ____syncRoot_4; } inline RuntimeObject ** get_address_of__syncRoot_4() { return &____syncRoot_4; } inline void set__syncRoot_4(RuntimeObject * value) { ____syncRoot_4 = value; Il2CppCodeGenWriteBarrier((void**)(&____syncRoot_4), (void*)value); } }; struct List_1_tF00B86100455886AD0B3A0B82FE6C94700D131D0_StaticFields { public: // T[] System.Collections.Generic.List`1::_emptyArray RigidbodyU5BU5D_t9F5D984DC2777DA3C6E2BEC6CE9D0F1C3D2E851B* ____emptyArray_5; public: inline static int32_t get_offset_of__emptyArray_5() { return static_cast(offsetof(List_1_tF00B86100455886AD0B3A0B82FE6C94700D131D0_StaticFields, ____emptyArray_5)); } inline RigidbodyU5BU5D_t9F5D984DC2777DA3C6E2BEC6CE9D0F1C3D2E851B* get__emptyArray_5() const { return ____emptyArray_5; } inline RigidbodyU5BU5D_t9F5D984DC2777DA3C6E2BEC6CE9D0F1C3D2E851B** get_address_of__emptyArray_5() { return &____emptyArray_5; } inline void set__emptyArray_5(RigidbodyU5BU5D_t9F5D984DC2777DA3C6E2BEC6CE9D0F1C3D2E851B* value) { ____emptyArray_5 = value; Il2CppCodeGenWriteBarrier((void**)(&____emptyArray_5), (void*)value); } }; // System.String struct String_t : public RuntimeObject { public: // System.Int32 System.String::m_stringLength int32_t ___m_stringLength_0; // System.Char System.String::m_firstChar Il2CppChar ___m_firstChar_1; public: inline static int32_t get_offset_of_m_stringLength_0() { return static_cast(offsetof(String_t, ___m_stringLength_0)); } inline int32_t get_m_stringLength_0() const { return ___m_stringLength_0; } inline int32_t* get_address_of_m_stringLength_0() { return &___m_stringLength_0; } inline void set_m_stringLength_0(int32_t value) { ___m_stringLength_0 = value; } inline static int32_t get_offset_of_m_firstChar_1() { return static_cast(offsetof(String_t, ___m_firstChar_1)); } inline Il2CppChar get_m_firstChar_1() const { return ___m_firstChar_1; } inline Il2CppChar* get_address_of_m_firstChar_1() { return &___m_firstChar_1; } inline void set_m_firstChar_1(Il2CppChar value) { ___m_firstChar_1 = value; } }; struct String_t_StaticFields { public: // System.String System.String::Empty String_t* ___Empty_5; public: inline static int32_t get_offset_of_Empty_5() { return static_cast(offsetof(String_t_StaticFields, ___Empty_5)); } inline String_t* get_Empty_5() const { return ___Empty_5; } inline String_t** get_address_of_Empty_5() { return &___Empty_5; } inline void set_Empty_5(String_t* value) { ___Empty_5 = value; Il2CppCodeGenWriteBarrier((void**)(&___Empty_5), (void*)value); } }; // System.ValueType struct ValueType_t4D0C27076F7C36E76190FB3328E232BCB1CD1FFF : public RuntimeObject { public: public: }; // Native definition for P/Invoke marshalling of System.ValueType struct ValueType_t4D0C27076F7C36E76190FB3328E232BCB1CD1FFF_marshaled_pinvoke { }; // Native definition for COM marshalling of System.ValueType struct ValueType_t4D0C27076F7C36E76190FB3328E232BCB1CD1FFF_marshaled_com { }; // UnityStandardAssets.Effects.ExplosionFireAndDebris/d__4 struct U3CStartU3Ed__4_t945A707CD8C01DA1C37AE2DD9D0A904C80F58139 : public RuntimeObject { public: // System.Int32 UnityStandardAssets.Effects.ExplosionFireAndDebris/d__4::<>1__state int32_t ___U3CU3E1__state_0; // System.Object UnityStandardAssets.Effects.ExplosionFireAndDebris/d__4::<>2__current RuntimeObject * ___U3CU3E2__current_1; // UnityStandardAssets.Effects.ExplosionFireAndDebris UnityStandardAssets.Effects.ExplosionFireAndDebris/d__4::<>4__this ExplosionFireAndDebris_tACCFCC1184BB9A8C3A0B39D99FFC831E76F9EECB * ___U3CU3E4__this_2; // System.Single UnityStandardAssets.Effects.ExplosionFireAndDebris/d__4::5__2 float ___U3CmultiplierU3E5__2_3; public: inline static int32_t get_offset_of_U3CU3E1__state_0() { return static_cast(offsetof(U3CStartU3Ed__4_t945A707CD8C01DA1C37AE2DD9D0A904C80F58139, ___U3CU3E1__state_0)); } inline int32_t get_U3CU3E1__state_0() const { return ___U3CU3E1__state_0; } inline int32_t* get_address_of_U3CU3E1__state_0() { return &___U3CU3E1__state_0; } inline void set_U3CU3E1__state_0(int32_t value) { ___U3CU3E1__state_0 = value; } inline static int32_t get_offset_of_U3CU3E2__current_1() { return static_cast(offsetof(U3CStartU3Ed__4_t945A707CD8C01DA1C37AE2DD9D0A904C80F58139, ___U3CU3E2__current_1)); } inline RuntimeObject * get_U3CU3E2__current_1() const { return ___U3CU3E2__current_1; } inline RuntimeObject ** get_address_of_U3CU3E2__current_1() { return &___U3CU3E2__current_1; } inline void set_U3CU3E2__current_1(RuntimeObject * value) { ___U3CU3E2__current_1 = value; Il2CppCodeGenWriteBarrier((void**)(&___U3CU3E2__current_1), (void*)value); } inline static int32_t get_offset_of_U3CU3E4__this_2() { return static_cast(offsetof(U3CStartU3Ed__4_t945A707CD8C01DA1C37AE2DD9D0A904C80F58139, ___U3CU3E4__this_2)); } inline ExplosionFireAndDebris_tACCFCC1184BB9A8C3A0B39D99FFC831E76F9EECB * get_U3CU3E4__this_2() const { return ___U3CU3E4__this_2; } inline ExplosionFireAndDebris_tACCFCC1184BB9A8C3A0B39D99FFC831E76F9EECB ** get_address_of_U3CU3E4__this_2() { return &___U3CU3E4__this_2; } inline void set_U3CU3E4__this_2(ExplosionFireAndDebris_tACCFCC1184BB9A8C3A0B39D99FFC831E76F9EECB * value) { ___U3CU3E4__this_2 = value; Il2CppCodeGenWriteBarrier((void**)(&___U3CU3E4__this_2), (void*)value); } inline static int32_t get_offset_of_U3CmultiplierU3E5__2_3() { return static_cast(offsetof(U3CStartU3Ed__4_t945A707CD8C01DA1C37AE2DD9D0A904C80F58139, ___U3CmultiplierU3E5__2_3)); } inline float get_U3CmultiplierU3E5__2_3() const { return ___U3CmultiplierU3E5__2_3; } inline float* get_address_of_U3CmultiplierU3E5__2_3() { return &___U3CmultiplierU3E5__2_3; } inline void set_U3CmultiplierU3E5__2_3(float value) { ___U3CmultiplierU3E5__2_3 = value; } }; // UnityStandardAssets.Effects.ExplosionPhysicsForce/d__1 struct U3CStartU3Ed__1_tFA687701957C85736794A1CD53601F73339D788F : public RuntimeObject { public: // System.Int32 UnityStandardAssets.Effects.ExplosionPhysicsForce/d__1::<>1__state int32_t ___U3CU3E1__state_0; // System.Object UnityStandardAssets.Effects.ExplosionPhysicsForce/d__1::<>2__current RuntimeObject * ___U3CU3E2__current_1; // UnityStandardAssets.Effects.ExplosionPhysicsForce UnityStandardAssets.Effects.ExplosionPhysicsForce/d__1::<>4__this ExplosionPhysicsForce_t59463D9C69E811AF9C885416501F2C8833800C58 * ___U3CU3E4__this_2; public: inline static int32_t get_offset_of_U3CU3E1__state_0() { return static_cast(offsetof(U3CStartU3Ed__1_tFA687701957C85736794A1CD53601F73339D788F, ___U3CU3E1__state_0)); } inline int32_t get_U3CU3E1__state_0() const { return ___U3CU3E1__state_0; } inline int32_t* get_address_of_U3CU3E1__state_0() { return &___U3CU3E1__state_0; } inline void set_U3CU3E1__state_0(int32_t value) { ___U3CU3E1__state_0 = value; } inline static int32_t get_offset_of_U3CU3E2__current_1() { return static_cast(offsetof(U3CStartU3Ed__1_tFA687701957C85736794A1CD53601F73339D788F, ___U3CU3E2__current_1)); } inline RuntimeObject * get_U3CU3E2__current_1() const { return ___U3CU3E2__current_1; } inline RuntimeObject ** get_address_of_U3CU3E2__current_1() { return &___U3CU3E2__current_1; } inline void set_U3CU3E2__current_1(RuntimeObject * value) { ___U3CU3E2__current_1 = value; Il2CppCodeGenWriteBarrier((void**)(&___U3CU3E2__current_1), (void*)value); } inline static int32_t get_offset_of_U3CU3E4__this_2() { return static_cast(offsetof(U3CStartU3Ed__1_tFA687701957C85736794A1CD53601F73339D788F, ___U3CU3E4__this_2)); } inline ExplosionPhysicsForce_t59463D9C69E811AF9C885416501F2C8833800C58 * get_U3CU3E4__this_2() const { return ___U3CU3E4__this_2; } inline ExplosionPhysicsForce_t59463D9C69E811AF9C885416501F2C8833800C58 ** get_address_of_U3CU3E4__this_2() { return &___U3CU3E4__this_2; } inline void set_U3CU3E4__this_2(ExplosionPhysicsForce_t59463D9C69E811AF9C885416501F2C8833800C58 * value) { ___U3CU3E4__this_2 = value; Il2CppCodeGenWriteBarrier((void**)(&___U3CU3E4__this_2), (void*)value); } }; // System.Boolean struct Boolean_tB53F6830F670160873277339AA58F15CAED4399C { public: // System.Boolean System.Boolean::m_value bool ___m_value_0; public: inline static int32_t get_offset_of_m_value_0() { return static_cast(offsetof(Boolean_tB53F6830F670160873277339AA58F15CAED4399C, ___m_value_0)); } inline bool get_m_value_0() const { return ___m_value_0; } inline bool* get_address_of_m_value_0() { return &___m_value_0; } inline void set_m_value_0(bool value) { ___m_value_0 = value; } }; struct Boolean_tB53F6830F670160873277339AA58F15CAED4399C_StaticFields { public: // System.String System.Boolean::TrueString String_t* ___TrueString_5; // System.String System.Boolean::FalseString String_t* ___FalseString_6; public: inline static int32_t get_offset_of_TrueString_5() { return static_cast(offsetof(Boolean_tB53F6830F670160873277339AA58F15CAED4399C_StaticFields, ___TrueString_5)); } inline String_t* get_TrueString_5() const { return ___TrueString_5; } inline String_t** get_address_of_TrueString_5() { return &___TrueString_5; } inline void set_TrueString_5(String_t* value) { ___TrueString_5 = value; Il2CppCodeGenWriteBarrier((void**)(&___TrueString_5), (void*)value); } inline static int32_t get_offset_of_FalseString_6() { return static_cast(offsetof(Boolean_tB53F6830F670160873277339AA58F15CAED4399C_StaticFields, ___FalseString_6)); } inline String_t* get_FalseString_6() const { return ___FalseString_6; } inline String_t** get_address_of_FalseString_6() { return &___FalseString_6; } inline void set_FalseString_6(String_t* value) { ___FalseString_6 = value; Il2CppCodeGenWriteBarrier((void**)(&___FalseString_6), (void*)value); } }; // System.Collections.Generic.List`1/Enumerator struct Enumerator_tE0C99528D3DCE5863566CE37BD94162A4C0431CD { public: // System.Collections.Generic.List`1 System.Collections.Generic.List`1/Enumerator::list List_1_t05CC3C859AB5E6024394EF9A42E3E696628CA02D * ___list_0; // System.Int32 System.Collections.Generic.List`1/Enumerator::index int32_t ___index_1; // System.Int32 System.Collections.Generic.List`1/Enumerator::version int32_t ___version_2; // T System.Collections.Generic.List`1/Enumerator::current RuntimeObject * ___current_3; public: inline static int32_t get_offset_of_list_0() { return static_cast(offsetof(Enumerator_tE0C99528D3DCE5863566CE37BD94162A4C0431CD, ___list_0)); } inline List_1_t05CC3C859AB5E6024394EF9A42E3E696628CA02D * get_list_0() const { return ___list_0; } inline List_1_t05CC3C859AB5E6024394EF9A42E3E696628CA02D ** get_address_of_list_0() { return &___list_0; } inline void set_list_0(List_1_t05CC3C859AB5E6024394EF9A42E3E696628CA02D * value) { ___list_0 = value; Il2CppCodeGenWriteBarrier((void**)(&___list_0), (void*)value); } inline static int32_t get_offset_of_index_1() { return static_cast(offsetof(Enumerator_tE0C99528D3DCE5863566CE37BD94162A4C0431CD, ___index_1)); } inline int32_t get_index_1() const { return ___index_1; } inline int32_t* get_address_of_index_1() { return &___index_1; } inline void set_index_1(int32_t value) { ___index_1 = value; } inline static int32_t get_offset_of_version_2() { return static_cast(offsetof(Enumerator_tE0C99528D3DCE5863566CE37BD94162A4C0431CD, ___version_2)); } inline int32_t get_version_2() const { return ___version_2; } inline int32_t* get_address_of_version_2() { return &___version_2; } inline void set_version_2(int32_t value) { ___version_2 = value; } inline static int32_t get_offset_of_current_3() { return static_cast(offsetof(Enumerator_tE0C99528D3DCE5863566CE37BD94162A4C0431CD, ___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((void**)(&___current_3), (void*)value); } }; // System.Collections.Generic.List`1/Enumerator struct Enumerator_t27C52ABD621DACF0C5D52FDAA65A98738987017E { public: // System.Collections.Generic.List`1 System.Collections.Generic.List`1/Enumerator::list List_1_tF00B86100455886AD0B3A0B82FE6C94700D131D0 * ___list_0; // System.Int32 System.Collections.Generic.List`1/Enumerator::index int32_t ___index_1; // System.Int32 System.Collections.Generic.List`1/Enumerator::version int32_t ___version_2; // T System.Collections.Generic.List`1/Enumerator::current Rigidbody_tE0A58EE5A1F7DC908EFFB4F0D795AC9552A750A5 * ___current_3; public: inline static int32_t get_offset_of_list_0() { return static_cast(offsetof(Enumerator_t27C52ABD621DACF0C5D52FDAA65A98738987017E, ___list_0)); } inline List_1_tF00B86100455886AD0B3A0B82FE6C94700D131D0 * get_list_0() const { return ___list_0; } inline List_1_tF00B86100455886AD0B3A0B82FE6C94700D131D0 ** get_address_of_list_0() { return &___list_0; } inline void set_list_0(List_1_tF00B86100455886AD0B3A0B82FE6C94700D131D0 * value) { ___list_0 = value; Il2CppCodeGenWriteBarrier((void**)(&___list_0), (void*)value); } inline static int32_t get_offset_of_index_1() { return static_cast(offsetof(Enumerator_t27C52ABD621DACF0C5D52FDAA65A98738987017E, ___index_1)); } inline int32_t get_index_1() const { return ___index_1; } inline int32_t* get_address_of_index_1() { return &___index_1; } inline void set_index_1(int32_t value) { ___index_1 = value; } inline static int32_t get_offset_of_version_2() { return static_cast(offsetof(Enumerator_t27C52ABD621DACF0C5D52FDAA65A98738987017E, ___version_2)); } inline int32_t get_version_2() const { return ___version_2; } inline int32_t* get_address_of_version_2() { return &___version_2; } inline void set_version_2(int32_t value) { ___version_2 = value; } inline static int32_t get_offset_of_current_3() { return static_cast(offsetof(Enumerator_t27C52ABD621DACF0C5D52FDAA65A98738987017E, ___current_3)); } inline Rigidbody_tE0A58EE5A1F7DC908EFFB4F0D795AC9552A750A5 * get_current_3() const { return ___current_3; } inline Rigidbody_tE0A58EE5A1F7DC908EFFB4F0D795AC9552A750A5 ** get_address_of_current_3() { return &___current_3; } inline void set_current_3(Rigidbody_tE0A58EE5A1F7DC908EFFB4F0D795AC9552A750A5 * value) { ___current_3 = value; Il2CppCodeGenWriteBarrier((void**)(&___current_3), (void*)value); } }; // System.Enum struct Enum_t2AF27C02B8653AE29442467390005ABC74D8F521 : public ValueType_t4D0C27076F7C36E76190FB3328E232BCB1CD1FFF { public: public: }; struct Enum_t2AF27C02B8653AE29442467390005ABC74D8F521_StaticFields { public: // System.Char[] System.Enum::enumSeperatorCharArray CharU5BU5D_t4CC6ABF0AD71BEC97E3C2F1E9C5677E46D3A75C2* ___enumSeperatorCharArray_0; public: inline static int32_t get_offset_of_enumSeperatorCharArray_0() { return static_cast(offsetof(Enum_t2AF27C02B8653AE29442467390005ABC74D8F521_StaticFields, ___enumSeperatorCharArray_0)); } inline CharU5BU5D_t4CC6ABF0AD71BEC97E3C2F1E9C5677E46D3A75C2* get_enumSeperatorCharArray_0() const { return ___enumSeperatorCharArray_0; } inline CharU5BU5D_t4CC6ABF0AD71BEC97E3C2F1E9C5677E46D3A75C2** get_address_of_enumSeperatorCharArray_0() { return &___enumSeperatorCharArray_0; } inline void set_enumSeperatorCharArray_0(CharU5BU5D_t4CC6ABF0AD71BEC97E3C2F1E9C5677E46D3A75C2* value) { ___enumSeperatorCharArray_0 = value; Il2CppCodeGenWriteBarrier((void**)(&___enumSeperatorCharArray_0), (void*)value); } }; // Native definition for P/Invoke marshalling of System.Enum struct Enum_t2AF27C02B8653AE29442467390005ABC74D8F521_marshaled_pinvoke { }; // Native definition for COM marshalling of System.Enum struct Enum_t2AF27C02B8653AE29442467390005ABC74D8F521_marshaled_com { }; // System.Int32 struct Int32_t585191389E07734F19F3156FF88FB3EF4800D102 { public: // System.Int32 System.Int32::m_value int32_t ___m_value_0; public: inline static int32_t get_offset_of_m_value_0() { return static_cast(offsetof(Int32_t585191389E07734F19F3156FF88FB3EF4800D102, ___m_value_0)); } inline int32_t get_m_value_0() const { return ___m_value_0; } inline int32_t* get_address_of_m_value_0() { return &___m_value_0; } inline void set_m_value_0(int32_t value) { ___m_value_0 = value; } }; // 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; } }; // System.Single struct Single_tDDDA9169C4E4E308AC6D7A824F9B28DC82204AE1 { public: // System.Single System.Single::m_value float ___m_value_0; public: inline static int32_t get_offset_of_m_value_0() { return static_cast(offsetof(Single_tDDDA9169C4E4E308AC6D7A824F9B28DC82204AE1, ___m_value_0)); } inline float get_m_value_0() const { return ___m_value_0; } inline float* get_address_of_m_value_0() { return &___m_value_0; } inline void set_m_value_0(float value) { ___m_value_0 = value; } }; // System.Void struct Void_t22962CB4C05B1D89B55A6E1139F0E87A90987017 { public: union { struct { }; uint8_t Void_t22962CB4C05B1D89B55A6E1139F0E87A90987017__padding[1]; }; public: }; // UnityEngine.Color struct Color_t119BCA590009762C7223FDD3AF9706653AC84ED2 { 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_t119BCA590009762C7223FDD3AF9706653AC84ED2, ___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_t119BCA590009762C7223FDD3AF9706653AC84ED2, ___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_t119BCA590009762C7223FDD3AF9706653AC84ED2, ___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_t119BCA590009762C7223FDD3AF9706653AC84ED2, ___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; } }; // UnityEngine.ParticleSystem/EmissionModule struct EmissionModule_t35028C3DE5EFDCE49E8A9732460617A56BD1D3F1 { public: // UnityEngine.ParticleSystem UnityEngine.ParticleSystem/EmissionModule::m_ParticleSystem ParticleSystem_t45DA87A3E83E738DA3FDAA5A48A133F1A1247C3D * ___m_ParticleSystem_0; public: inline static int32_t get_offset_of_m_ParticleSystem_0() { return static_cast(offsetof(EmissionModule_t35028C3DE5EFDCE49E8A9732460617A56BD1D3F1, ___m_ParticleSystem_0)); } inline ParticleSystem_t45DA87A3E83E738DA3FDAA5A48A133F1A1247C3D * get_m_ParticleSystem_0() const { return ___m_ParticleSystem_0; } inline ParticleSystem_t45DA87A3E83E738DA3FDAA5A48A133F1A1247C3D ** get_address_of_m_ParticleSystem_0() { return &___m_ParticleSystem_0; } inline void set_m_ParticleSystem_0(ParticleSystem_t45DA87A3E83E738DA3FDAA5A48A133F1A1247C3D * value) { ___m_ParticleSystem_0 = value; Il2CppCodeGenWriteBarrier((void**)(&___m_ParticleSystem_0), (void*)value); } }; // Native definition for P/Invoke marshalling of UnityEngine.ParticleSystem/EmissionModule struct EmissionModule_t35028C3DE5EFDCE49E8A9732460617A56BD1D3F1_marshaled_pinvoke { ParticleSystem_t45DA87A3E83E738DA3FDAA5A48A133F1A1247C3D * ___m_ParticleSystem_0; }; // Native definition for COM marshalling of UnityEngine.ParticleSystem/EmissionModule struct EmissionModule_t35028C3DE5EFDCE49E8A9732460617A56BD1D3F1_marshaled_com { ParticleSystem_t45DA87A3E83E738DA3FDAA5A48A133F1A1247C3D * ___m_ParticleSystem_0; }; // UnityEngine.ParticleSystem/MainModule struct MainModule_t99C675667E0A363368324132DFA34B27FFEE6FC7 { public: // UnityEngine.ParticleSystem UnityEngine.ParticleSystem/MainModule::m_ParticleSystem ParticleSystem_t45DA87A3E83E738DA3FDAA5A48A133F1A1247C3D * ___m_ParticleSystem_0; public: inline static int32_t get_offset_of_m_ParticleSystem_0() { return static_cast(offsetof(MainModule_t99C675667E0A363368324132DFA34B27FFEE6FC7, ___m_ParticleSystem_0)); } inline ParticleSystem_t45DA87A3E83E738DA3FDAA5A48A133F1A1247C3D * get_m_ParticleSystem_0() const { return ___m_ParticleSystem_0; } inline ParticleSystem_t45DA87A3E83E738DA3FDAA5A48A133F1A1247C3D ** get_address_of_m_ParticleSystem_0() { return &___m_ParticleSystem_0; } inline void set_m_ParticleSystem_0(ParticleSystem_t45DA87A3E83E738DA3FDAA5A48A133F1A1247C3D * value) { ___m_ParticleSystem_0 = value; Il2CppCodeGenWriteBarrier((void**)(&___m_ParticleSystem_0), (void*)value); } }; // Native definition for P/Invoke marshalling of UnityEngine.ParticleSystem/MainModule struct MainModule_t99C675667E0A363368324132DFA34B27FFEE6FC7_marshaled_pinvoke { ParticleSystem_t45DA87A3E83E738DA3FDAA5A48A133F1A1247C3D * ___m_ParticleSystem_0; }; // Native definition for COM marshalling of UnityEngine.ParticleSystem/MainModule struct MainModule_t99C675667E0A363368324132DFA34B27FFEE6FC7_marshaled_com { ParticleSystem_t45DA87A3E83E738DA3FDAA5A48A133F1A1247C3D * ___m_ParticleSystem_0; }; // UnityEngine.Quaternion struct Quaternion_t319F3319A7D43FFA5D819AD6C0A98851F0095357 { 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_t319F3319A7D43FFA5D819AD6C0A98851F0095357, ___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_t319F3319A7D43FFA5D819AD6C0A98851F0095357, ___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_t319F3319A7D43FFA5D819AD6C0A98851F0095357, ___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_t319F3319A7D43FFA5D819AD6C0A98851F0095357, ___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_t319F3319A7D43FFA5D819AD6C0A98851F0095357_StaticFields { public: // UnityEngine.Quaternion UnityEngine.Quaternion::identityQuaternion Quaternion_t319F3319A7D43FFA5D819AD6C0A98851F0095357 ___identityQuaternion_4; public: inline static int32_t get_offset_of_identityQuaternion_4() { return static_cast(offsetof(Quaternion_t319F3319A7D43FFA5D819AD6C0A98851F0095357_StaticFields, ___identityQuaternion_4)); } inline Quaternion_t319F3319A7D43FFA5D819AD6C0A98851F0095357 get_identityQuaternion_4() const { return ___identityQuaternion_4; } inline Quaternion_t319F3319A7D43FFA5D819AD6C0A98851F0095357 * get_address_of_identityQuaternion_4() { return &___identityQuaternion_4; } inline void set_identityQuaternion_4(Quaternion_t319F3319A7D43FFA5D819AD6C0A98851F0095357 value) { ___identityQuaternion_4 = value; } }; // UnityEngine.Vector2 struct Vector2_tA85D2DD88578276CA8A8796756458277E72D073D { 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_tA85D2DD88578276CA8A8796756458277E72D073D, ___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_tA85D2DD88578276CA8A8796756458277E72D073D, ___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_tA85D2DD88578276CA8A8796756458277E72D073D_StaticFields { public: // UnityEngine.Vector2 UnityEngine.Vector2::zeroVector Vector2_tA85D2DD88578276CA8A8796756458277E72D073D ___zeroVector_2; // UnityEngine.Vector2 UnityEngine.Vector2::oneVector Vector2_tA85D2DD88578276CA8A8796756458277E72D073D ___oneVector_3; // UnityEngine.Vector2 UnityEngine.Vector2::upVector Vector2_tA85D2DD88578276CA8A8796756458277E72D073D ___upVector_4; // UnityEngine.Vector2 UnityEngine.Vector2::downVector Vector2_tA85D2DD88578276CA8A8796756458277E72D073D ___downVector_5; // UnityEngine.Vector2 UnityEngine.Vector2::leftVector Vector2_tA85D2DD88578276CA8A8796756458277E72D073D ___leftVector_6; // UnityEngine.Vector2 UnityEngine.Vector2::rightVector Vector2_tA85D2DD88578276CA8A8796756458277E72D073D ___rightVector_7; // UnityEngine.Vector2 UnityEngine.Vector2::positiveInfinityVector Vector2_tA85D2DD88578276CA8A8796756458277E72D073D ___positiveInfinityVector_8; // UnityEngine.Vector2 UnityEngine.Vector2::negativeInfinityVector Vector2_tA85D2DD88578276CA8A8796756458277E72D073D ___negativeInfinityVector_9; public: inline static int32_t get_offset_of_zeroVector_2() { return static_cast(offsetof(Vector2_tA85D2DD88578276CA8A8796756458277E72D073D_StaticFields, ___zeroVector_2)); } inline Vector2_tA85D2DD88578276CA8A8796756458277E72D073D get_zeroVector_2() const { return ___zeroVector_2; } inline Vector2_tA85D2DD88578276CA8A8796756458277E72D073D * get_address_of_zeroVector_2() { return &___zeroVector_2; } inline void set_zeroVector_2(Vector2_tA85D2DD88578276CA8A8796756458277E72D073D value) { ___zeroVector_2 = value; } inline static int32_t get_offset_of_oneVector_3() { return static_cast(offsetof(Vector2_tA85D2DD88578276CA8A8796756458277E72D073D_StaticFields, ___oneVector_3)); } inline Vector2_tA85D2DD88578276CA8A8796756458277E72D073D get_oneVector_3() const { return ___oneVector_3; } inline Vector2_tA85D2DD88578276CA8A8796756458277E72D073D * get_address_of_oneVector_3() { return &___oneVector_3; } inline void set_oneVector_3(Vector2_tA85D2DD88578276CA8A8796756458277E72D073D value) { ___oneVector_3 = value; } inline static int32_t get_offset_of_upVector_4() { return static_cast(offsetof(Vector2_tA85D2DD88578276CA8A8796756458277E72D073D_StaticFields, ___upVector_4)); } inline Vector2_tA85D2DD88578276CA8A8796756458277E72D073D get_upVector_4() const { return ___upVector_4; } inline Vector2_tA85D2DD88578276CA8A8796756458277E72D073D * get_address_of_upVector_4() { return &___upVector_4; } inline void set_upVector_4(Vector2_tA85D2DD88578276CA8A8796756458277E72D073D value) { ___upVector_4 = value; } inline static int32_t get_offset_of_downVector_5() { return static_cast(offsetof(Vector2_tA85D2DD88578276CA8A8796756458277E72D073D_StaticFields, ___downVector_5)); } inline Vector2_tA85D2DD88578276CA8A8796756458277E72D073D get_downVector_5() const { return ___downVector_5; } inline Vector2_tA85D2DD88578276CA8A8796756458277E72D073D * get_address_of_downVector_5() { return &___downVector_5; } inline void set_downVector_5(Vector2_tA85D2DD88578276CA8A8796756458277E72D073D value) { ___downVector_5 = value; } inline static int32_t get_offset_of_leftVector_6() { return static_cast(offsetof(Vector2_tA85D2DD88578276CA8A8796756458277E72D073D_StaticFields, ___leftVector_6)); } inline Vector2_tA85D2DD88578276CA8A8796756458277E72D073D get_leftVector_6() const { return ___leftVector_6; } inline Vector2_tA85D2DD88578276CA8A8796756458277E72D073D * get_address_of_leftVector_6() { return &___leftVector_6; } inline void set_leftVector_6(Vector2_tA85D2DD88578276CA8A8796756458277E72D073D value) { ___leftVector_6 = value; } inline static int32_t get_offset_of_rightVector_7() { return static_cast(offsetof(Vector2_tA85D2DD88578276CA8A8796756458277E72D073D_StaticFields, ___rightVector_7)); } inline Vector2_tA85D2DD88578276CA8A8796756458277E72D073D get_rightVector_7() const { return ___rightVector_7; } inline Vector2_tA85D2DD88578276CA8A8796756458277E72D073D * get_address_of_rightVector_7() { return &___rightVector_7; } inline void set_rightVector_7(Vector2_tA85D2DD88578276CA8A8796756458277E72D073D value) { ___rightVector_7 = value; } inline static int32_t get_offset_of_positiveInfinityVector_8() { return static_cast(offsetof(Vector2_tA85D2DD88578276CA8A8796756458277E72D073D_StaticFields, ___positiveInfinityVector_8)); } inline Vector2_tA85D2DD88578276CA8A8796756458277E72D073D get_positiveInfinityVector_8() const { return ___positiveInfinityVector_8; } inline Vector2_tA85D2DD88578276CA8A8796756458277E72D073D * get_address_of_positiveInfinityVector_8() { return &___positiveInfinityVector_8; } inline void set_positiveInfinityVector_8(Vector2_tA85D2DD88578276CA8A8796756458277E72D073D value) { ___positiveInfinityVector_8 = value; } inline static int32_t get_offset_of_negativeInfinityVector_9() { return static_cast(offsetof(Vector2_tA85D2DD88578276CA8A8796756458277E72D073D_StaticFields, ___negativeInfinityVector_9)); } inline Vector2_tA85D2DD88578276CA8A8796756458277E72D073D get_negativeInfinityVector_9() const { return ___negativeInfinityVector_9; } inline Vector2_tA85D2DD88578276CA8A8796756458277E72D073D * get_address_of_negativeInfinityVector_9() { return &___negativeInfinityVector_9; } inline void set_negativeInfinityVector_9(Vector2_tA85D2DD88578276CA8A8796756458277E72D073D value) { ___negativeInfinityVector_9 = value; } }; // UnityEngine.Vector3 struct Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 { public: // System.Single UnityEngine.Vector3::x float ___x_2; // System.Single UnityEngine.Vector3::y float ___y_3; // System.Single UnityEngine.Vector3::z float ___z_4; public: inline static int32_t get_offset_of_x_2() { return static_cast(offsetof(Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720, ___x_2)); } inline float get_x_2() const { return ___x_2; } inline float* get_address_of_x_2() { return &___x_2; } inline void set_x_2(float value) { ___x_2 = value; } inline static int32_t get_offset_of_y_3() { return static_cast(offsetof(Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720, ___y_3)); } inline float get_y_3() const { return ___y_3; } inline float* get_address_of_y_3() { return &___y_3; } inline void set_y_3(float value) { ___y_3 = value; } inline static int32_t get_offset_of_z_4() { return static_cast(offsetof(Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720, ___z_4)); } inline float get_z_4() const { return ___z_4; } inline float* get_address_of_z_4() { return &___z_4; } inline void set_z_4(float value) { ___z_4 = value; } }; struct Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720_StaticFields { public: // UnityEngine.Vector3 UnityEngine.Vector3::zeroVector Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 ___zeroVector_5; // UnityEngine.Vector3 UnityEngine.Vector3::oneVector Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 ___oneVector_6; // UnityEngine.Vector3 UnityEngine.Vector3::upVector Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 ___upVector_7; // UnityEngine.Vector3 UnityEngine.Vector3::downVector Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 ___downVector_8; // UnityEngine.Vector3 UnityEngine.Vector3::leftVector Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 ___leftVector_9; // UnityEngine.Vector3 UnityEngine.Vector3::rightVector Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 ___rightVector_10; // UnityEngine.Vector3 UnityEngine.Vector3::forwardVector Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 ___forwardVector_11; // UnityEngine.Vector3 UnityEngine.Vector3::backVector Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 ___backVector_12; // UnityEngine.Vector3 UnityEngine.Vector3::positiveInfinityVector Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 ___positiveInfinityVector_13; // UnityEngine.Vector3 UnityEngine.Vector3::negativeInfinityVector Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 ___negativeInfinityVector_14; public: inline static int32_t get_offset_of_zeroVector_5() { return static_cast(offsetof(Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720_StaticFields, ___zeroVector_5)); } inline Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 get_zeroVector_5() const { return ___zeroVector_5; } inline Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 * get_address_of_zeroVector_5() { return &___zeroVector_5; } inline void set_zeroVector_5(Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 value) { ___zeroVector_5 = value; } inline static int32_t get_offset_of_oneVector_6() { return static_cast(offsetof(Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720_StaticFields, ___oneVector_6)); } inline Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 get_oneVector_6() const { return ___oneVector_6; } inline Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 * get_address_of_oneVector_6() { return &___oneVector_6; } inline void set_oneVector_6(Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 value) { ___oneVector_6 = value; } inline static int32_t get_offset_of_upVector_7() { return static_cast(offsetof(Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720_StaticFields, ___upVector_7)); } inline Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 get_upVector_7() const { return ___upVector_7; } inline Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 * get_address_of_upVector_7() { return &___upVector_7; } inline void set_upVector_7(Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 value) { ___upVector_7 = value; } inline static int32_t get_offset_of_downVector_8() { return static_cast(offsetof(Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720_StaticFields, ___downVector_8)); } inline Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 get_downVector_8() const { return ___downVector_8; } inline Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 * get_address_of_downVector_8() { return &___downVector_8; } inline void set_downVector_8(Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 value) { ___downVector_8 = value; } inline static int32_t get_offset_of_leftVector_9() { return static_cast(offsetof(Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720_StaticFields, ___leftVector_9)); } inline Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 get_leftVector_9() const { return ___leftVector_9; } inline Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 * get_address_of_leftVector_9() { return &___leftVector_9; } inline void set_leftVector_9(Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 value) { ___leftVector_9 = value; } inline static int32_t get_offset_of_rightVector_10() { return static_cast(offsetof(Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720_StaticFields, ___rightVector_10)); } inline Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 get_rightVector_10() const { return ___rightVector_10; } inline Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 * get_address_of_rightVector_10() { return &___rightVector_10; } inline void set_rightVector_10(Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 value) { ___rightVector_10 = value; } inline static int32_t get_offset_of_forwardVector_11() { return static_cast(offsetof(Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720_StaticFields, ___forwardVector_11)); } inline Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 get_forwardVector_11() const { return ___forwardVector_11; } inline Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 * get_address_of_forwardVector_11() { return &___forwardVector_11; } inline void set_forwardVector_11(Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 value) { ___forwardVector_11 = value; } inline static int32_t get_offset_of_backVector_12() { return static_cast(offsetof(Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720_StaticFields, ___backVector_12)); } inline Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 get_backVector_12() const { return ___backVector_12; } inline Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 * get_address_of_backVector_12() { return &___backVector_12; } inline void set_backVector_12(Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 value) { ___backVector_12 = value; } inline static int32_t get_offset_of_positiveInfinityVector_13() { return static_cast(offsetof(Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720_StaticFields, ___positiveInfinityVector_13)); } inline Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 get_positiveInfinityVector_13() const { return ___positiveInfinityVector_13; } inline Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 * get_address_of_positiveInfinityVector_13() { return &___positiveInfinityVector_13; } inline void set_positiveInfinityVector_13(Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 value) { ___positiveInfinityVector_13 = value; } inline static int32_t get_offset_of_negativeInfinityVector_14() { return static_cast(offsetof(Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720_StaticFields, ___negativeInfinityVector_14)); } inline Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 get_negativeInfinityVector_14() const { return ___negativeInfinityVector_14; } inline Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 * get_address_of_negativeInfinityVector_14() { return &___negativeInfinityVector_14; } inline void set_negativeInfinityVector_14(Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 value) { ___negativeInfinityVector_14 = value; } }; // System.Exception struct Exception_t : public RuntimeObject { public: // System.String System.Exception::_className String_t* ____className_1; // System.String System.Exception::_message String_t* ____message_2; // System.Collections.IDictionary System.Exception::_data RuntimeObject* ____data_3; // System.Exception System.Exception::_innerException Exception_t * ____innerException_4; // System.String System.Exception::_helpURL String_t* ____helpURL_5; // System.Object System.Exception::_stackTrace RuntimeObject * ____stackTrace_6; // System.String System.Exception::_stackTraceString String_t* ____stackTraceString_7; // System.String System.Exception::_remoteStackTraceString String_t* ____remoteStackTraceString_8; // System.Int32 System.Exception::_remoteStackIndex int32_t ____remoteStackIndex_9; // System.Object System.Exception::_dynamicMethods RuntimeObject * ____dynamicMethods_10; // System.Int32 System.Exception::_HResult int32_t ____HResult_11; // System.String System.Exception::_source String_t* ____source_12; // System.Runtime.Serialization.SafeSerializationManager System.Exception::_safeSerializationManager SafeSerializationManager_t4A754D86B0F784B18CBC36C073BA564BED109770 * ____safeSerializationManager_13; // System.Diagnostics.StackTrace[] System.Exception::captured_traces StackTraceU5BU5D_t855F09649EA34DEE7C1B6F088E0538E3CCC3F196* ___captured_traces_14; // System.IntPtr[] System.Exception::native_trace_ips IntPtrU5BU5D_t4DC01DCB9A6DF6C9792A6513595D7A11E637DCDD* ___native_trace_ips_15; public: inline static int32_t get_offset_of__className_1() { return static_cast(offsetof(Exception_t, ____className_1)); } inline String_t* get__className_1() const { return ____className_1; } inline String_t** get_address_of__className_1() { return &____className_1; } inline void set__className_1(String_t* value) { ____className_1 = value; Il2CppCodeGenWriteBarrier((void**)(&____className_1), (void*)value); } inline static int32_t get_offset_of__message_2() { return static_cast(offsetof(Exception_t, ____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((void**)(&____message_2), (void*)value); } inline static int32_t get_offset_of__data_3() { return static_cast(offsetof(Exception_t, ____data_3)); } inline RuntimeObject* get__data_3() const { return ____data_3; } inline RuntimeObject** get_address_of__data_3() { return &____data_3; } inline void set__data_3(RuntimeObject* value) { ____data_3 = value; Il2CppCodeGenWriteBarrier((void**)(&____data_3), (void*)value); } inline static int32_t get_offset_of__innerException_4() { return static_cast(offsetof(Exception_t, ____innerException_4)); } inline Exception_t * get__innerException_4() const { return ____innerException_4; } inline Exception_t ** get_address_of__innerException_4() { return &____innerException_4; } inline void set__innerException_4(Exception_t * value) { ____innerException_4 = value; Il2CppCodeGenWriteBarrier((void**)(&____innerException_4), (void*)value); } inline static int32_t get_offset_of__helpURL_5() { return static_cast(offsetof(Exception_t, ____helpURL_5)); } inline String_t* get__helpURL_5() const { return ____helpURL_5; } inline String_t** get_address_of__helpURL_5() { return &____helpURL_5; } inline void set__helpURL_5(String_t* value) { ____helpURL_5 = value; Il2CppCodeGenWriteBarrier((void**)(&____helpURL_5), (void*)value); } inline static int32_t get_offset_of__stackTrace_6() { return static_cast(offsetof(Exception_t, ____stackTrace_6)); } inline RuntimeObject * get__stackTrace_6() const { return ____stackTrace_6; } inline RuntimeObject ** get_address_of__stackTrace_6() { return &____stackTrace_6; } inline void set__stackTrace_6(RuntimeObject * value) { ____stackTrace_6 = value; Il2CppCodeGenWriteBarrier((void**)(&____stackTrace_6), (void*)value); } inline static int32_t get_offset_of__stackTraceString_7() { return static_cast(offsetof(Exception_t, ____stackTraceString_7)); } inline String_t* get__stackTraceString_7() const { return ____stackTraceString_7; } inline String_t** get_address_of__stackTraceString_7() { return &____stackTraceString_7; } inline void set__stackTraceString_7(String_t* value) { ____stackTraceString_7 = value; Il2CppCodeGenWriteBarrier((void**)(&____stackTraceString_7), (void*)value); } inline static int32_t get_offset_of__remoteStackTraceString_8() { return static_cast(offsetof(Exception_t, ____remoteStackTraceString_8)); } inline String_t* get__remoteStackTraceString_8() const { return ____remoteStackTraceString_8; } inline String_t** get_address_of__remoteStackTraceString_8() { return &____remoteStackTraceString_8; } inline void set__remoteStackTraceString_8(String_t* value) { ____remoteStackTraceString_8 = value; Il2CppCodeGenWriteBarrier((void**)(&____remoteStackTraceString_8), (void*)value); } inline static int32_t get_offset_of__remoteStackIndex_9() { return static_cast(offsetof(Exception_t, ____remoteStackIndex_9)); } inline int32_t get__remoteStackIndex_9() const { return ____remoteStackIndex_9; } inline int32_t* get_address_of__remoteStackIndex_9() { return &____remoteStackIndex_9; } inline void set__remoteStackIndex_9(int32_t value) { ____remoteStackIndex_9 = value; } inline static int32_t get_offset_of__dynamicMethods_10() { return static_cast(offsetof(Exception_t, ____dynamicMethods_10)); } inline RuntimeObject * get__dynamicMethods_10() const { return ____dynamicMethods_10; } inline RuntimeObject ** get_address_of__dynamicMethods_10() { return &____dynamicMethods_10; } inline void set__dynamicMethods_10(RuntimeObject * value) { ____dynamicMethods_10 = value; Il2CppCodeGenWriteBarrier((void**)(&____dynamicMethods_10), (void*)value); } inline static int32_t get_offset_of__HResult_11() { return static_cast(offsetof(Exception_t, ____HResult_11)); } inline int32_t get__HResult_11() const { return ____HResult_11; } inline int32_t* get_address_of__HResult_11() { return &____HResult_11; } inline void set__HResult_11(int32_t value) { ____HResult_11 = value; } inline static int32_t get_offset_of__source_12() { return static_cast(offsetof(Exception_t, ____source_12)); } inline String_t* get__source_12() const { return ____source_12; } inline String_t** get_address_of__source_12() { return &____source_12; } inline void set__source_12(String_t* value) { ____source_12 = value; Il2CppCodeGenWriteBarrier((void**)(&____source_12), (void*)value); } inline static int32_t get_offset_of__safeSerializationManager_13() { return static_cast(offsetof(Exception_t, ____safeSerializationManager_13)); } inline SafeSerializationManager_t4A754D86B0F784B18CBC36C073BA564BED109770 * get__safeSerializationManager_13() const { return ____safeSerializationManager_13; } inline SafeSerializationManager_t4A754D86B0F784B18CBC36C073BA564BED109770 ** get_address_of__safeSerializationManager_13() { return &____safeSerializationManager_13; } inline void set__safeSerializationManager_13(SafeSerializationManager_t4A754D86B0F784B18CBC36C073BA564BED109770 * value) { ____safeSerializationManager_13 = value; Il2CppCodeGenWriteBarrier((void**)(&____safeSerializationManager_13), (void*)value); } inline static int32_t get_offset_of_captured_traces_14() { return static_cast(offsetof(Exception_t, ___captured_traces_14)); } inline StackTraceU5BU5D_t855F09649EA34DEE7C1B6F088E0538E3CCC3F196* get_captured_traces_14() const { return ___captured_traces_14; } inline StackTraceU5BU5D_t855F09649EA34DEE7C1B6F088E0538E3CCC3F196** get_address_of_captured_traces_14() { return &___captured_traces_14; } inline void set_captured_traces_14(StackTraceU5BU5D_t855F09649EA34DEE7C1B6F088E0538E3CCC3F196* value) { ___captured_traces_14 = value; Il2CppCodeGenWriteBarrier((void**)(&___captured_traces_14), (void*)value); } inline static int32_t get_offset_of_native_trace_ips_15() { return static_cast(offsetof(Exception_t, ___native_trace_ips_15)); } inline IntPtrU5BU5D_t4DC01DCB9A6DF6C9792A6513595D7A11E637DCDD* get_native_trace_ips_15() const { return ___native_trace_ips_15; } inline IntPtrU5BU5D_t4DC01DCB9A6DF6C9792A6513595D7A11E637DCDD** get_address_of_native_trace_ips_15() { return &___native_trace_ips_15; } inline void set_native_trace_ips_15(IntPtrU5BU5D_t4DC01DCB9A6DF6C9792A6513595D7A11E637DCDD* value) { ___native_trace_ips_15 = value; Il2CppCodeGenWriteBarrier((void**)(&___native_trace_ips_15), (void*)value); } }; struct Exception_t_StaticFields { public: // System.Object System.Exception::s_EDILock RuntimeObject * ___s_EDILock_0; public: inline static int32_t get_offset_of_s_EDILock_0() { return static_cast(offsetof(Exception_t_StaticFields, ___s_EDILock_0)); } inline RuntimeObject * get_s_EDILock_0() const { return ___s_EDILock_0; } inline RuntimeObject ** get_address_of_s_EDILock_0() { return &___s_EDILock_0; } inline void set_s_EDILock_0(RuntimeObject * value) { ___s_EDILock_0 = value; Il2CppCodeGenWriteBarrier((void**)(&___s_EDILock_0), (void*)value); } }; // Native definition for P/Invoke marshalling of System.Exception struct Exception_t_marshaled_pinvoke { char* ____className_1; char* ____message_2; RuntimeObject* ____data_3; Exception_t_marshaled_pinvoke* ____innerException_4; char* ____helpURL_5; Il2CppIUnknown* ____stackTrace_6; char* ____stackTraceString_7; char* ____remoteStackTraceString_8; int32_t ____remoteStackIndex_9; Il2CppIUnknown* ____dynamicMethods_10; int32_t ____HResult_11; char* ____source_12; SafeSerializationManager_t4A754D86B0F784B18CBC36C073BA564BED109770 * ____safeSerializationManager_13; StackTraceU5BU5D_t855F09649EA34DEE7C1B6F088E0538E3CCC3F196* ___captured_traces_14; Il2CppSafeArray/*NONE*/* ___native_trace_ips_15; }; // Native definition for COM marshalling of System.Exception struct Exception_t_marshaled_com { Il2CppChar* ____className_1; Il2CppChar* ____message_2; RuntimeObject* ____data_3; Exception_t_marshaled_com* ____innerException_4; Il2CppChar* ____helpURL_5; Il2CppIUnknown* ____stackTrace_6; Il2CppChar* ____stackTraceString_7; Il2CppChar* ____remoteStackTraceString_8; int32_t ____remoteStackIndex_9; Il2CppIUnknown* ____dynamicMethods_10; int32_t ____HResult_11; Il2CppChar* ____source_12; SafeSerializationManager_t4A754D86B0F784B18CBC36C073BA564BED109770 * ____safeSerializationManager_13; StackTraceU5BU5D_t855F09649EA34DEE7C1B6F088E0538E3CCC3F196* ___captured_traces_14; Il2CppSafeArray/*NONE*/* ___native_trace_ips_15; }; // UnityEngine.ForceMode struct ForceMode_t76188FF14D0038E184106555207A81218E97D0A5 { public: // System.Int32 UnityEngine.ForceMode::value__ int32_t ___value___2; public: inline static int32_t get_offset_of_value___2() { return static_cast(offsetof(ForceMode_t76188FF14D0038E184106555207A81218E97D0A5, ___value___2)); } inline int32_t get_value___2() const { return ___value___2; } inline int32_t* get_address_of_value___2() { return &___value___2; } inline void set_value___2(int32_t value) { ___value___2 = value; } }; // UnityEngine.KeyCode struct KeyCode_tC93EA87C5A6901160B583ADFCD3EF6726570DC3C { public: // System.Int32 UnityEngine.KeyCode::value__ int32_t ___value___2; public: inline static int32_t get_offset_of_value___2() { return static_cast(offsetof(KeyCode_tC93EA87C5A6901160B583ADFCD3EF6726570DC3C, ___value___2)); } inline int32_t get_value___2() const { return ___value___2; } inline int32_t* get_address_of_value___2() { return &___value___2; } inline void set_value___2(int32_t value) { ___value___2 = value; } }; // UnityEngine.Object struct Object_tAE11E5E46CD5C37C9F3E8950C00CD8B45666A2D0 : 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_tAE11E5E46CD5C37C9F3E8950C00CD8B45666A2D0, ___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_tAE11E5E46CD5C37C9F3E8950C00CD8B45666A2D0_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_tAE11E5E46CD5C37C9F3E8950C00CD8B45666A2D0_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; } }; // Native definition for P/Invoke marshalling of UnityEngine.Object struct Object_tAE11E5E46CD5C37C9F3E8950C00CD8B45666A2D0_marshaled_pinvoke { intptr_t ___m_CachedPtr_0; }; // Native definition for COM marshalling of UnityEngine.Object struct Object_tAE11E5E46CD5C37C9F3E8950C00CD8B45666A2D0_marshaled_com { intptr_t ___m_CachedPtr_0; }; // UnityEngine.ParticleCollisionEvent struct ParticleCollisionEvent_t7F4D7D5ACF8521671549D9328D4E2DDE480D8D47 { public: // UnityEngine.Vector3 UnityEngine.ParticleCollisionEvent::m_Intersection Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 ___m_Intersection_0; // UnityEngine.Vector3 UnityEngine.ParticleCollisionEvent::m_Normal Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 ___m_Normal_1; // UnityEngine.Vector3 UnityEngine.ParticleCollisionEvent::m_Velocity Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 ___m_Velocity_2; // System.Int32 UnityEngine.ParticleCollisionEvent::m_ColliderInstanceID int32_t ___m_ColliderInstanceID_3; public: inline static int32_t get_offset_of_m_Intersection_0() { return static_cast(offsetof(ParticleCollisionEvent_t7F4D7D5ACF8521671549D9328D4E2DDE480D8D47, ___m_Intersection_0)); } inline Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 get_m_Intersection_0() const { return ___m_Intersection_0; } inline Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 * get_address_of_m_Intersection_0() { return &___m_Intersection_0; } inline void set_m_Intersection_0(Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 value) { ___m_Intersection_0 = value; } inline static int32_t get_offset_of_m_Normal_1() { return static_cast(offsetof(ParticleCollisionEvent_t7F4D7D5ACF8521671549D9328D4E2DDE480D8D47, ___m_Normal_1)); } inline Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 get_m_Normal_1() const { return ___m_Normal_1; } inline Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 * get_address_of_m_Normal_1() { return &___m_Normal_1; } inline void set_m_Normal_1(Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 value) { ___m_Normal_1 = value; } inline static int32_t get_offset_of_m_Velocity_2() { return static_cast(offsetof(ParticleCollisionEvent_t7F4D7D5ACF8521671549D9328D4E2DDE480D8D47, ___m_Velocity_2)); } inline Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 get_m_Velocity_2() const { return ___m_Velocity_2; } inline Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 * get_address_of_m_Velocity_2() { return &___m_Velocity_2; } inline void set_m_Velocity_2(Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 value) { ___m_Velocity_2 = value; } inline static int32_t get_offset_of_m_ColliderInstanceID_3() { return static_cast(offsetof(ParticleCollisionEvent_t7F4D7D5ACF8521671549D9328D4E2DDE480D8D47, ___m_ColliderInstanceID_3)); } inline int32_t get_m_ColliderInstanceID_3() const { return ___m_ColliderInstanceID_3; } inline int32_t* get_address_of_m_ColliderInstanceID_3() { return &___m_ColliderInstanceID_3; } inline void set_m_ColliderInstanceID_3(int32_t value) { ___m_ColliderInstanceID_3 = value; } }; // UnityEngine.ParticleSystemCurveMode struct ParticleSystemCurveMode_tD8A2390BB482B39C0C0714F3DDE715386BC7D48D { public: // System.Int32 UnityEngine.ParticleSystemCurveMode::value__ int32_t ___value___2; public: inline static int32_t get_offset_of_value___2() { return static_cast(offsetof(ParticleSystemCurveMode_tD8A2390BB482B39C0C0714F3DDE715386BC7D48D, ___value___2)); } inline int32_t get_value___2() const { return ___value___2; } inline int32_t* get_address_of_value___2() { return &___value___2; } inline void set_value___2(int32_t value) { ___value___2 = value; } }; // UnityEngine.Ray struct Ray_tE2163D4CB3E6B267E29F8ABE41684490E4A614B2 { public: // UnityEngine.Vector3 UnityEngine.Ray::m_Origin Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 ___m_Origin_0; // UnityEngine.Vector3 UnityEngine.Ray::m_Direction Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 ___m_Direction_1; public: inline static int32_t get_offset_of_m_Origin_0() { return static_cast(offsetof(Ray_tE2163D4CB3E6B267E29F8ABE41684490E4A614B2, ___m_Origin_0)); } inline Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 get_m_Origin_0() const { return ___m_Origin_0; } inline Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 * get_address_of_m_Origin_0() { return &___m_Origin_0; } inline void set_m_Origin_0(Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 value) { ___m_Origin_0 = value; } inline static int32_t get_offset_of_m_Direction_1() { return static_cast(offsetof(Ray_tE2163D4CB3E6B267E29F8ABE41684490E4A614B2, ___m_Direction_1)); } inline Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 get_m_Direction_1() const { return ___m_Direction_1; } inline Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 * get_address_of_m_Direction_1() { return &___m_Direction_1; } inline void set_m_Direction_1(Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 value) { ___m_Direction_1 = value; } }; // UnityEngine.RaycastHit struct RaycastHit_t19695F18F9265FE5425062BBA6A4D330480538C3 { public: // UnityEngine.Vector3 UnityEngine.RaycastHit::m_Point Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 ___m_Point_0; // UnityEngine.Vector3 UnityEngine.RaycastHit::m_Normal Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 ___m_Normal_1; // System.UInt32 UnityEngine.RaycastHit::m_FaceID uint32_t ___m_FaceID_2; // System.Single UnityEngine.RaycastHit::m_Distance float ___m_Distance_3; // UnityEngine.Vector2 UnityEngine.RaycastHit::m_UV Vector2_tA85D2DD88578276CA8A8796756458277E72D073D ___m_UV_4; // System.Int32 UnityEngine.RaycastHit::m_Collider int32_t ___m_Collider_5; public: inline static int32_t get_offset_of_m_Point_0() { return static_cast(offsetof(RaycastHit_t19695F18F9265FE5425062BBA6A4D330480538C3, ___m_Point_0)); } inline Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 get_m_Point_0() const { return ___m_Point_0; } inline Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 * get_address_of_m_Point_0() { return &___m_Point_0; } inline void set_m_Point_0(Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 value) { ___m_Point_0 = value; } inline static int32_t get_offset_of_m_Normal_1() { return static_cast(offsetof(RaycastHit_t19695F18F9265FE5425062BBA6A4D330480538C3, ___m_Normal_1)); } inline Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 get_m_Normal_1() const { return ___m_Normal_1; } inline Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 * get_address_of_m_Normal_1() { return &___m_Normal_1; } inline void set_m_Normal_1(Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 value) { ___m_Normal_1 = value; } inline static int32_t get_offset_of_m_FaceID_2() { return static_cast(offsetof(RaycastHit_t19695F18F9265FE5425062BBA6A4D330480538C3, ___m_FaceID_2)); } inline uint32_t get_m_FaceID_2() const { return ___m_FaceID_2; } inline uint32_t* get_address_of_m_FaceID_2() { return &___m_FaceID_2; } inline void set_m_FaceID_2(uint32_t value) { ___m_FaceID_2 = value; } inline static int32_t get_offset_of_m_Distance_3() { return static_cast(offsetof(RaycastHit_t19695F18F9265FE5425062BBA6A4D330480538C3, ___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_t19695F18F9265FE5425062BBA6A4D330480538C3, ___m_UV_4)); } inline Vector2_tA85D2DD88578276CA8A8796756458277E72D073D get_m_UV_4() const { return ___m_UV_4; } inline Vector2_tA85D2DD88578276CA8A8796756458277E72D073D * get_address_of_m_UV_4() { return &___m_UV_4; } inline void set_m_UV_4(Vector2_tA85D2DD88578276CA8A8796756458277E72D073D value) { ___m_UV_4 = value; } inline static int32_t get_offset_of_m_Collider_5() { return static_cast(offsetof(RaycastHit_t19695F18F9265FE5425062BBA6A4D330480538C3, ___m_Collider_5)); } inline int32_t get_m_Collider_5() const { return ___m_Collider_5; } inline int32_t* get_address_of_m_Collider_5() { return &___m_Collider_5; } inline void set_m_Collider_5(int32_t value) { ___m_Collider_5 = value; } }; // UnityEngine.SendMessageOptions struct SendMessageOptions_t4EA4645A7D0C4E0186BD7A984CDF4EE2C8F26250 { public: // System.Int32 UnityEngine.SendMessageOptions::value__ int32_t ___value___2; public: inline static int32_t get_offset_of_value___2() { return static_cast(offsetof(SendMessageOptions_t4EA4645A7D0C4E0186BD7A984CDF4EE2C8F26250, ___value___2)); } inline int32_t get_value___2() const { return ___value___2; } inline int32_t* get_address_of_value___2() { return &___value___2; } inline void set_value___2(int32_t value) { ___value___2 = value; } }; // System.SystemException struct SystemException_t5380468142AA850BE4A341D7AF3EAB9C78746782 : public Exception_t { public: public: }; // UnityEngine.AudioClip struct AudioClip_tCC3C35F579203CE2601243585AB3D6953C3BA051 : public Object_tAE11E5E46CD5C37C9F3E8950C00CD8B45666A2D0 { public: // UnityEngine.AudioClip/PCMReaderCallback UnityEngine.AudioClip::m_PCMReaderCallback PCMReaderCallback_t9B87AB13DCD37957B045554BF28A57697E6B8EFB * ___m_PCMReaderCallback_4; // UnityEngine.AudioClip/PCMSetPositionCallback UnityEngine.AudioClip::m_PCMSetPositionCallback PCMSetPositionCallback_t092ED33043C0279B5E4D343EBCBD516CEF260801 * ___m_PCMSetPositionCallback_5; public: inline static int32_t get_offset_of_m_PCMReaderCallback_4() { return static_cast(offsetof(AudioClip_tCC3C35F579203CE2601243585AB3D6953C3BA051, ___m_PCMReaderCallback_4)); } inline PCMReaderCallback_t9B87AB13DCD37957B045554BF28A57697E6B8EFB * get_m_PCMReaderCallback_4() const { return ___m_PCMReaderCallback_4; } inline PCMReaderCallback_t9B87AB13DCD37957B045554BF28A57697E6B8EFB ** get_address_of_m_PCMReaderCallback_4() { return &___m_PCMReaderCallback_4; } inline void set_m_PCMReaderCallback_4(PCMReaderCallback_t9B87AB13DCD37957B045554BF28A57697E6B8EFB * value) { ___m_PCMReaderCallback_4 = value; Il2CppCodeGenWriteBarrier((void**)(&___m_PCMReaderCallback_4), (void*)value); } inline static int32_t get_offset_of_m_PCMSetPositionCallback_5() { return static_cast(offsetof(AudioClip_tCC3C35F579203CE2601243585AB3D6953C3BA051, ___m_PCMSetPositionCallback_5)); } inline PCMSetPositionCallback_t092ED33043C0279B5E4D343EBCBD516CEF260801 * get_m_PCMSetPositionCallback_5() const { return ___m_PCMSetPositionCallback_5; } inline PCMSetPositionCallback_t092ED33043C0279B5E4D343EBCBD516CEF260801 ** get_address_of_m_PCMSetPositionCallback_5() { return &___m_PCMSetPositionCallback_5; } inline void set_m_PCMSetPositionCallback_5(PCMSetPositionCallback_t092ED33043C0279B5E4D343EBCBD516CEF260801 * value) { ___m_PCMSetPositionCallback_5 = value; Il2CppCodeGenWriteBarrier((void**)(&___m_PCMSetPositionCallback_5), (void*)value); } }; // UnityEngine.Component struct Component_t05064EF382ABCAF4B8C94F8A350EA85184C26621 : public Object_tAE11E5E46CD5C37C9F3E8950C00CD8B45666A2D0 { public: public: }; // UnityEngine.GameObject struct GameObject_tBD1244AD56B4E59AAD76E5E7C9282EC5CE434F0F : public Object_tAE11E5E46CD5C37C9F3E8950C00CD8B45666A2D0 { public: public: }; // UnityEngine.ParticleSystem/MinMaxCurve struct MinMaxCurve_tDB335EDEBEBD4CFA753081D7C3A2FE2EECFA6D71 { public: // UnityEngine.ParticleSystemCurveMode UnityEngine.ParticleSystem/MinMaxCurve::m_Mode int32_t ___m_Mode_0; // System.Single UnityEngine.ParticleSystem/MinMaxCurve::m_CurveMultiplier float ___m_CurveMultiplier_1; // UnityEngine.AnimationCurve UnityEngine.ParticleSystem/MinMaxCurve::m_CurveMin AnimationCurve_tD2F265379583AAF1BF8D84F1BB8DB12980FA504C * ___m_CurveMin_2; // UnityEngine.AnimationCurve UnityEngine.ParticleSystem/MinMaxCurve::m_CurveMax AnimationCurve_tD2F265379583AAF1BF8D84F1BB8DB12980FA504C * ___m_CurveMax_3; // System.Single UnityEngine.ParticleSystem/MinMaxCurve::m_ConstantMin float ___m_ConstantMin_4; // System.Single UnityEngine.ParticleSystem/MinMaxCurve::m_ConstantMax float ___m_ConstantMax_5; public: inline static int32_t get_offset_of_m_Mode_0() { return static_cast(offsetof(MinMaxCurve_tDB335EDEBEBD4CFA753081D7C3A2FE2EECFA6D71, ___m_Mode_0)); } inline int32_t get_m_Mode_0() const { return ___m_Mode_0; } inline int32_t* get_address_of_m_Mode_0() { return &___m_Mode_0; } inline void set_m_Mode_0(int32_t value) { ___m_Mode_0 = value; } inline static int32_t get_offset_of_m_CurveMultiplier_1() { return static_cast(offsetof(MinMaxCurve_tDB335EDEBEBD4CFA753081D7C3A2FE2EECFA6D71, ___m_CurveMultiplier_1)); } inline float get_m_CurveMultiplier_1() const { return ___m_CurveMultiplier_1; } inline float* get_address_of_m_CurveMultiplier_1() { return &___m_CurveMultiplier_1; } inline void set_m_CurveMultiplier_1(float value) { ___m_CurveMultiplier_1 = value; } inline static int32_t get_offset_of_m_CurveMin_2() { return static_cast(offsetof(MinMaxCurve_tDB335EDEBEBD4CFA753081D7C3A2FE2EECFA6D71, ___m_CurveMin_2)); } inline AnimationCurve_tD2F265379583AAF1BF8D84F1BB8DB12980FA504C * get_m_CurveMin_2() const { return ___m_CurveMin_2; } inline AnimationCurve_tD2F265379583AAF1BF8D84F1BB8DB12980FA504C ** get_address_of_m_CurveMin_2() { return &___m_CurveMin_2; } inline void set_m_CurveMin_2(AnimationCurve_tD2F265379583AAF1BF8D84F1BB8DB12980FA504C * value) { ___m_CurveMin_2 = value; Il2CppCodeGenWriteBarrier((void**)(&___m_CurveMin_2), (void*)value); } inline static int32_t get_offset_of_m_CurveMax_3() { return static_cast(offsetof(MinMaxCurve_tDB335EDEBEBD4CFA753081D7C3A2FE2EECFA6D71, ___m_CurveMax_3)); } inline AnimationCurve_tD2F265379583AAF1BF8D84F1BB8DB12980FA504C * get_m_CurveMax_3() const { return ___m_CurveMax_3; } inline AnimationCurve_tD2F265379583AAF1BF8D84F1BB8DB12980FA504C ** get_address_of_m_CurveMax_3() { return &___m_CurveMax_3; } inline void set_m_CurveMax_3(AnimationCurve_tD2F265379583AAF1BF8D84F1BB8DB12980FA504C * value) { ___m_CurveMax_3 = value; Il2CppCodeGenWriteBarrier((void**)(&___m_CurveMax_3), (void*)value); } inline static int32_t get_offset_of_m_ConstantMin_4() { return static_cast(offsetof(MinMaxCurve_tDB335EDEBEBD4CFA753081D7C3A2FE2EECFA6D71, ___m_ConstantMin_4)); } inline float get_m_ConstantMin_4() const { return ___m_ConstantMin_4; } inline float* get_address_of_m_ConstantMin_4() { return &___m_ConstantMin_4; } inline void set_m_ConstantMin_4(float value) { ___m_ConstantMin_4 = value; } inline static int32_t get_offset_of_m_ConstantMax_5() { return static_cast(offsetof(MinMaxCurve_tDB335EDEBEBD4CFA753081D7C3A2FE2EECFA6D71, ___m_ConstantMax_5)); } inline float get_m_ConstantMax_5() const { return ___m_ConstantMax_5; } inline float* get_address_of_m_ConstantMax_5() { return &___m_ConstantMax_5; } inline void set_m_ConstantMax_5(float value) { ___m_ConstantMax_5 = value; } }; // System.NotSupportedException struct NotSupportedException_tE75B318D6590A02A5D9B29FD97409B1750FA0010 : public SystemException_t5380468142AA850BE4A341D7AF3EAB9C78746782 { public: public: }; // UnityEngine.Behaviour struct Behaviour_tBDC7E9C3C898AD8348891B82D3E345801D920CA8 : public Component_t05064EF382ABCAF4B8C94F8A350EA85184C26621 { public: public: }; // UnityEngine.Collider struct Collider_t0FEEB36760860AD21B3B1F0509C365B393EC4BDF : public Component_t05064EF382ABCAF4B8C94F8A350EA85184C26621 { public: public: }; // UnityEngine.ParticleSystem struct ParticleSystem_t45DA87A3E83E738DA3FDAA5A48A133F1A1247C3D : public Component_t05064EF382ABCAF4B8C94F8A350EA85184C26621 { public: public: }; // UnityEngine.Renderer struct Renderer_t0556D67DD582620D1F495627EDE30D03284151F4 : public Component_t05064EF382ABCAF4B8C94F8A350EA85184C26621 { public: public: }; // UnityEngine.Rigidbody struct Rigidbody_tE0A58EE5A1F7DC908EFFB4F0D795AC9552A750A5 : public Component_t05064EF382ABCAF4B8C94F8A350EA85184C26621 { public: public: }; // UnityEngine.Transform struct Transform_tBB9E78A2766C3C83599A8F66EDE7D1FCAFC66EDA : public Component_t05064EF382ABCAF4B8C94F8A350EA85184C26621 { public: public: }; // UnityEngine.AudioBehaviour struct AudioBehaviour_tC612EC4E17A648A5C568621F3FBF1DBD773C71C7 : public Behaviour_tBDC7E9C3C898AD8348891B82D3E345801D920CA8 { public: public: }; // UnityEngine.Light struct Light_tFDE490EADBC7E080F74CA804929513AF07C31A6C : public Behaviour_tBDC7E9C3C898AD8348891B82D3E345801D920CA8 { public: // System.Int32 UnityEngine.Light::m_BakedIndex int32_t ___m_BakedIndex_4; public: inline static int32_t get_offset_of_m_BakedIndex_4() { return static_cast(offsetof(Light_tFDE490EADBC7E080F74CA804929513AF07C31A6C, ___m_BakedIndex_4)); } inline int32_t get_m_BakedIndex_4() const { return ___m_BakedIndex_4; } inline int32_t* get_address_of_m_BakedIndex_4() { return &___m_BakedIndex_4; } inline void set_m_BakedIndex_4(int32_t value) { ___m_BakedIndex_4 = value; } }; // UnityEngine.MonoBehaviour struct MonoBehaviour_t4A60845CF505405AF8BE8C61CC07F75CADEF6429 : public Behaviour_tBDC7E9C3C898AD8348891B82D3E345801D920CA8 { public: public: }; // UnityEngine.SphereCollider struct SphereCollider_tAC3E5E20B385DF1C0B17F3EA5C7214F71367706F : public Collider_t0FEEB36760860AD21B3B1F0509C365B393EC4BDF { public: public: }; // UnityEngine.AudioSource struct AudioSource_t5196F862B4E60F404613361C90D87FBDD041E93C : public AudioBehaviour_tC612EC4E17A648A5C568621F3FBF1DBD773C71C7 { public: public: }; // UnityStandardAssets.Effects.AfterburnerPhysicsForce struct AfterburnerPhysicsForce_t753048E9DC6DB55FA797EA775B76014E1E7F204B : public MonoBehaviour_t4A60845CF505405AF8BE8C61CC07F75CADEF6429 { public: // System.Single UnityStandardAssets.Effects.AfterburnerPhysicsForce::effectAngle float ___effectAngle_4; // System.Single UnityStandardAssets.Effects.AfterburnerPhysicsForce::effectWidth float ___effectWidth_5; // System.Single UnityStandardAssets.Effects.AfterburnerPhysicsForce::effectDistance float ___effectDistance_6; // System.Single UnityStandardAssets.Effects.AfterburnerPhysicsForce::force float ___force_7; // UnityEngine.Collider[] UnityStandardAssets.Effects.AfterburnerPhysicsForce::m_Cols ColliderU5BU5D_t70D1FDAE17E4359298B2BAA828048D1B7CFFE252* ___m_Cols_8; // UnityEngine.SphereCollider UnityStandardAssets.Effects.AfterburnerPhysicsForce::m_Sphere SphereCollider_tAC3E5E20B385DF1C0B17F3EA5C7214F71367706F * ___m_Sphere_9; public: inline static int32_t get_offset_of_effectAngle_4() { return static_cast(offsetof(AfterburnerPhysicsForce_t753048E9DC6DB55FA797EA775B76014E1E7F204B, ___effectAngle_4)); } inline float get_effectAngle_4() const { return ___effectAngle_4; } inline float* get_address_of_effectAngle_4() { return &___effectAngle_4; } inline void set_effectAngle_4(float value) { ___effectAngle_4 = value; } inline static int32_t get_offset_of_effectWidth_5() { return static_cast(offsetof(AfterburnerPhysicsForce_t753048E9DC6DB55FA797EA775B76014E1E7F204B, ___effectWidth_5)); } inline float get_effectWidth_5() const { return ___effectWidth_5; } inline float* get_address_of_effectWidth_5() { return &___effectWidth_5; } inline void set_effectWidth_5(float value) { ___effectWidth_5 = value; } inline static int32_t get_offset_of_effectDistance_6() { return static_cast(offsetof(AfterburnerPhysicsForce_t753048E9DC6DB55FA797EA775B76014E1E7F204B, ___effectDistance_6)); } inline float get_effectDistance_6() const { return ___effectDistance_6; } inline float* get_address_of_effectDistance_6() { return &___effectDistance_6; } inline void set_effectDistance_6(float value) { ___effectDistance_6 = value; } inline static int32_t get_offset_of_force_7() { return static_cast(offsetof(AfterburnerPhysicsForce_t753048E9DC6DB55FA797EA775B76014E1E7F204B, ___force_7)); } inline float get_force_7() const { return ___force_7; } inline float* get_address_of_force_7() { return &___force_7; } inline void set_force_7(float value) { ___force_7 = value; } inline static int32_t get_offset_of_m_Cols_8() { return static_cast(offsetof(AfterburnerPhysicsForce_t753048E9DC6DB55FA797EA775B76014E1E7F204B, ___m_Cols_8)); } inline ColliderU5BU5D_t70D1FDAE17E4359298B2BAA828048D1B7CFFE252* get_m_Cols_8() const { return ___m_Cols_8; } inline ColliderU5BU5D_t70D1FDAE17E4359298B2BAA828048D1B7CFFE252** get_address_of_m_Cols_8() { return &___m_Cols_8; } inline void set_m_Cols_8(ColliderU5BU5D_t70D1FDAE17E4359298B2BAA828048D1B7CFFE252* value) { ___m_Cols_8 = value; Il2CppCodeGenWriteBarrier((void**)(&___m_Cols_8), (void*)value); } inline static int32_t get_offset_of_m_Sphere_9() { return static_cast(offsetof(AfterburnerPhysicsForce_t753048E9DC6DB55FA797EA775B76014E1E7F204B, ___m_Sphere_9)); } inline SphereCollider_tAC3E5E20B385DF1C0B17F3EA5C7214F71367706F * get_m_Sphere_9() const { return ___m_Sphere_9; } inline SphereCollider_tAC3E5E20B385DF1C0B17F3EA5C7214F71367706F ** get_address_of_m_Sphere_9() { return &___m_Sphere_9; } inline void set_m_Sphere_9(SphereCollider_tAC3E5E20B385DF1C0B17F3EA5C7214F71367706F * value) { ___m_Sphere_9 = value; Il2CppCodeGenWriteBarrier((void**)(&___m_Sphere_9), (void*)value); } }; // UnityStandardAssets.Effects.ExplosionFireAndDebris struct ExplosionFireAndDebris_tACCFCC1184BB9A8C3A0B39D99FFC831E76F9EECB : public MonoBehaviour_t4A60845CF505405AF8BE8C61CC07F75CADEF6429 { public: // UnityEngine.Transform[] UnityStandardAssets.Effects.ExplosionFireAndDebris::debrisPrefabs TransformU5BU5D_t4F5A1132877D8BA66ABC0A9A7FADA4E0237A7804* ___debrisPrefabs_4; // UnityEngine.Transform UnityStandardAssets.Effects.ExplosionFireAndDebris::firePrefab Transform_tBB9E78A2766C3C83599A8F66EDE7D1FCAFC66EDA * ___firePrefab_5; // System.Int32 UnityStandardAssets.Effects.ExplosionFireAndDebris::numDebrisPieces int32_t ___numDebrisPieces_6; // System.Int32 UnityStandardAssets.Effects.ExplosionFireAndDebris::numFires int32_t ___numFires_7; public: inline static int32_t get_offset_of_debrisPrefabs_4() { return static_cast(offsetof(ExplosionFireAndDebris_tACCFCC1184BB9A8C3A0B39D99FFC831E76F9EECB, ___debrisPrefabs_4)); } inline TransformU5BU5D_t4F5A1132877D8BA66ABC0A9A7FADA4E0237A7804* get_debrisPrefabs_4() const { return ___debrisPrefabs_4; } inline TransformU5BU5D_t4F5A1132877D8BA66ABC0A9A7FADA4E0237A7804** get_address_of_debrisPrefabs_4() { return &___debrisPrefabs_4; } inline void set_debrisPrefabs_4(TransformU5BU5D_t4F5A1132877D8BA66ABC0A9A7FADA4E0237A7804* value) { ___debrisPrefabs_4 = value; Il2CppCodeGenWriteBarrier((void**)(&___debrisPrefabs_4), (void*)value); } inline static int32_t get_offset_of_firePrefab_5() { return static_cast(offsetof(ExplosionFireAndDebris_tACCFCC1184BB9A8C3A0B39D99FFC831E76F9EECB, ___firePrefab_5)); } inline Transform_tBB9E78A2766C3C83599A8F66EDE7D1FCAFC66EDA * get_firePrefab_5() const { return ___firePrefab_5; } inline Transform_tBB9E78A2766C3C83599A8F66EDE7D1FCAFC66EDA ** get_address_of_firePrefab_5() { return &___firePrefab_5; } inline void set_firePrefab_5(Transform_tBB9E78A2766C3C83599A8F66EDE7D1FCAFC66EDA * value) { ___firePrefab_5 = value; Il2CppCodeGenWriteBarrier((void**)(&___firePrefab_5), (void*)value); } inline static int32_t get_offset_of_numDebrisPieces_6() { return static_cast(offsetof(ExplosionFireAndDebris_tACCFCC1184BB9A8C3A0B39D99FFC831E76F9EECB, ___numDebrisPieces_6)); } inline int32_t get_numDebrisPieces_6() const { return ___numDebrisPieces_6; } inline int32_t* get_address_of_numDebrisPieces_6() { return &___numDebrisPieces_6; } inline void set_numDebrisPieces_6(int32_t value) { ___numDebrisPieces_6 = value; } inline static int32_t get_offset_of_numFires_7() { return static_cast(offsetof(ExplosionFireAndDebris_tACCFCC1184BB9A8C3A0B39D99FFC831E76F9EECB, ___numFires_7)); } inline int32_t get_numFires_7() const { return ___numFires_7; } inline int32_t* get_address_of_numFires_7() { return &___numFires_7; } inline void set_numFires_7(int32_t value) { ___numFires_7 = value; } }; // UnityStandardAssets.Effects.ExplosionPhysicsForce struct ExplosionPhysicsForce_t59463D9C69E811AF9C885416501F2C8833800C58 : public MonoBehaviour_t4A60845CF505405AF8BE8C61CC07F75CADEF6429 { public: // System.Single UnityStandardAssets.Effects.ExplosionPhysicsForce::explosionForce float ___explosionForce_4; public: inline static int32_t get_offset_of_explosionForce_4() { return static_cast(offsetof(ExplosionPhysicsForce_t59463D9C69E811AF9C885416501F2C8833800C58, ___explosionForce_4)); } inline float get_explosionForce_4() const { return ___explosionForce_4; } inline float* get_address_of_explosionForce_4() { return &___explosionForce_4; } inline void set_explosionForce_4(float value) { ___explosionForce_4 = value; } }; // UnityStandardAssets.Effects.ExtinguishableParticleSystem struct ExtinguishableParticleSystem_tD91348BD8771EB84F5369DA844F390BE915ADB64 : public MonoBehaviour_t4A60845CF505405AF8BE8C61CC07F75CADEF6429 { public: // System.Single UnityStandardAssets.Effects.ExtinguishableParticleSystem::multiplier float ___multiplier_4; // UnityEngine.ParticleSystem[] UnityStandardAssets.Effects.ExtinguishableParticleSystem::m_Systems ParticleSystemU5BU5D_t58EE604F685D8CBA8EFC9353456969F5A1B2FBB9* ___m_Systems_5; public: inline static int32_t get_offset_of_multiplier_4() { return static_cast(offsetof(ExtinguishableParticleSystem_tD91348BD8771EB84F5369DA844F390BE915ADB64, ___multiplier_4)); } inline float get_multiplier_4() const { return ___multiplier_4; } inline float* get_address_of_multiplier_4() { return &___multiplier_4; } inline void set_multiplier_4(float value) { ___multiplier_4 = value; } inline static int32_t get_offset_of_m_Systems_5() { return static_cast(offsetof(ExtinguishableParticleSystem_tD91348BD8771EB84F5369DA844F390BE915ADB64, ___m_Systems_5)); } inline ParticleSystemU5BU5D_t58EE604F685D8CBA8EFC9353456969F5A1B2FBB9* get_m_Systems_5() const { return ___m_Systems_5; } inline ParticleSystemU5BU5D_t58EE604F685D8CBA8EFC9353456969F5A1B2FBB9** get_address_of_m_Systems_5() { return &___m_Systems_5; } inline void set_m_Systems_5(ParticleSystemU5BU5D_t58EE604F685D8CBA8EFC9353456969F5A1B2FBB9* value) { ___m_Systems_5 = value; Il2CppCodeGenWriteBarrier((void**)(&___m_Systems_5), (void*)value); } }; // UnityStandardAssets.Effects.FireLight struct FireLight_tBDF3DBBD1B6288E05ECBDCDB787FBB8ABD8572C5 : public MonoBehaviour_t4A60845CF505405AF8BE8C61CC07F75CADEF6429 { public: // System.Single UnityStandardAssets.Effects.FireLight::m_Rnd float ___m_Rnd_4; // System.Boolean UnityStandardAssets.Effects.FireLight::m_Burning bool ___m_Burning_5; // UnityEngine.Light UnityStandardAssets.Effects.FireLight::m_Light Light_tFDE490EADBC7E080F74CA804929513AF07C31A6C * ___m_Light_6; public: inline static int32_t get_offset_of_m_Rnd_4() { return static_cast(offsetof(FireLight_tBDF3DBBD1B6288E05ECBDCDB787FBB8ABD8572C5, ___m_Rnd_4)); } inline float get_m_Rnd_4() const { return ___m_Rnd_4; } inline float* get_address_of_m_Rnd_4() { return &___m_Rnd_4; } inline void set_m_Rnd_4(float value) { ___m_Rnd_4 = value; } inline static int32_t get_offset_of_m_Burning_5() { return static_cast(offsetof(FireLight_tBDF3DBBD1B6288E05ECBDCDB787FBB8ABD8572C5, ___m_Burning_5)); } inline bool get_m_Burning_5() const { return ___m_Burning_5; } inline bool* get_address_of_m_Burning_5() { return &___m_Burning_5; } inline void set_m_Burning_5(bool value) { ___m_Burning_5 = value; } inline static int32_t get_offset_of_m_Light_6() { return static_cast(offsetof(FireLight_tBDF3DBBD1B6288E05ECBDCDB787FBB8ABD8572C5, ___m_Light_6)); } inline Light_tFDE490EADBC7E080F74CA804929513AF07C31A6C * get_m_Light_6() const { return ___m_Light_6; } inline Light_tFDE490EADBC7E080F74CA804929513AF07C31A6C ** get_address_of_m_Light_6() { return &___m_Light_6; } inline void set_m_Light_6(Light_tFDE490EADBC7E080F74CA804929513AF07C31A6C * value) { ___m_Light_6 = value; Il2CppCodeGenWriteBarrier((void**)(&___m_Light_6), (void*)value); } }; // UnityStandardAssets.Effects.Hose struct Hose_t411AEC20AB5A70AEFCF03FCB2418F0C8EB14C2D2 : public MonoBehaviour_t4A60845CF505405AF8BE8C61CC07F75CADEF6429 { public: // System.Single UnityStandardAssets.Effects.Hose::maxPower float ___maxPower_4; // System.Single UnityStandardAssets.Effects.Hose::minPower float ___minPower_5; // System.Single UnityStandardAssets.Effects.Hose::changeSpeed float ___changeSpeed_6; // UnityEngine.ParticleSystem[] UnityStandardAssets.Effects.Hose::hoseWaterSystems ParticleSystemU5BU5D_t58EE604F685D8CBA8EFC9353456969F5A1B2FBB9* ___hoseWaterSystems_7; // UnityEngine.Renderer UnityStandardAssets.Effects.Hose::systemRenderer Renderer_t0556D67DD582620D1F495627EDE30D03284151F4 * ___systemRenderer_8; // System.Single UnityStandardAssets.Effects.Hose::m_Power float ___m_Power_9; public: inline static int32_t get_offset_of_maxPower_4() { return static_cast(offsetof(Hose_t411AEC20AB5A70AEFCF03FCB2418F0C8EB14C2D2, ___maxPower_4)); } inline float get_maxPower_4() const { return ___maxPower_4; } inline float* get_address_of_maxPower_4() { return &___maxPower_4; } inline void set_maxPower_4(float value) { ___maxPower_4 = value; } inline static int32_t get_offset_of_minPower_5() { return static_cast(offsetof(Hose_t411AEC20AB5A70AEFCF03FCB2418F0C8EB14C2D2, ___minPower_5)); } inline float get_minPower_5() const { return ___minPower_5; } inline float* get_address_of_minPower_5() { return &___minPower_5; } inline void set_minPower_5(float value) { ___minPower_5 = value; } inline static int32_t get_offset_of_changeSpeed_6() { return static_cast(offsetof(Hose_t411AEC20AB5A70AEFCF03FCB2418F0C8EB14C2D2, ___changeSpeed_6)); } inline float get_changeSpeed_6() const { return ___changeSpeed_6; } inline float* get_address_of_changeSpeed_6() { return &___changeSpeed_6; } inline void set_changeSpeed_6(float value) { ___changeSpeed_6 = value; } inline static int32_t get_offset_of_hoseWaterSystems_7() { return static_cast(offsetof(Hose_t411AEC20AB5A70AEFCF03FCB2418F0C8EB14C2D2, ___hoseWaterSystems_7)); } inline ParticleSystemU5BU5D_t58EE604F685D8CBA8EFC9353456969F5A1B2FBB9* get_hoseWaterSystems_7() const { return ___hoseWaterSystems_7; } inline ParticleSystemU5BU5D_t58EE604F685D8CBA8EFC9353456969F5A1B2FBB9** get_address_of_hoseWaterSystems_7() { return &___hoseWaterSystems_7; } inline void set_hoseWaterSystems_7(ParticleSystemU5BU5D_t58EE604F685D8CBA8EFC9353456969F5A1B2FBB9* value) { ___hoseWaterSystems_7 = value; Il2CppCodeGenWriteBarrier((void**)(&___hoseWaterSystems_7), (void*)value); } inline static int32_t get_offset_of_systemRenderer_8() { return static_cast(offsetof(Hose_t411AEC20AB5A70AEFCF03FCB2418F0C8EB14C2D2, ___systemRenderer_8)); } inline Renderer_t0556D67DD582620D1F495627EDE30D03284151F4 * get_systemRenderer_8() const { return ___systemRenderer_8; } inline Renderer_t0556D67DD582620D1F495627EDE30D03284151F4 ** get_address_of_systemRenderer_8() { return &___systemRenderer_8; } inline void set_systemRenderer_8(Renderer_t0556D67DD582620D1F495627EDE30D03284151F4 * value) { ___systemRenderer_8 = value; Il2CppCodeGenWriteBarrier((void**)(&___systemRenderer_8), (void*)value); } inline static int32_t get_offset_of_m_Power_9() { return static_cast(offsetof(Hose_t411AEC20AB5A70AEFCF03FCB2418F0C8EB14C2D2, ___m_Power_9)); } inline float get_m_Power_9() const { return ___m_Power_9; } inline float* get_address_of_m_Power_9() { return &___m_Power_9; } inline void set_m_Power_9(float value) { ___m_Power_9 = value; } }; // UnityStandardAssets.Effects.ParticleSystemMultiplier struct ParticleSystemMultiplier_t8EBFEF83EBA48DD7F6517ABFFBE2CD051CB2C748 : public MonoBehaviour_t4A60845CF505405AF8BE8C61CC07F75CADEF6429 { public: // System.Single UnityStandardAssets.Effects.ParticleSystemMultiplier::multiplier float ___multiplier_4; public: inline static int32_t get_offset_of_multiplier_4() { return static_cast(offsetof(ParticleSystemMultiplier_t8EBFEF83EBA48DD7F6517ABFFBE2CD051CB2C748, ___multiplier_4)); } inline float get_multiplier_4() const { return ___multiplier_4; } inline float* get_address_of_multiplier_4() { return &___multiplier_4; } inline void set_multiplier_4(float value) { ___multiplier_4 = value; } }; // UnityStandardAssets.Effects.SmokeParticles struct SmokeParticles_t556E08200E5E25126D51BFF297C7522998E3D793 : public MonoBehaviour_t4A60845CF505405AF8BE8C61CC07F75CADEF6429 { public: // UnityEngine.AudioClip[] UnityStandardAssets.Effects.SmokeParticles::extinguishSounds AudioClipU5BU5D_t03931BD44BC339329210676E452B8ECD3EC171C2* ___extinguishSounds_4; public: inline static int32_t get_offset_of_extinguishSounds_4() { return static_cast(offsetof(SmokeParticles_t556E08200E5E25126D51BFF297C7522998E3D793, ___extinguishSounds_4)); } inline AudioClipU5BU5D_t03931BD44BC339329210676E452B8ECD3EC171C2* get_extinguishSounds_4() const { return ___extinguishSounds_4; } inline AudioClipU5BU5D_t03931BD44BC339329210676E452B8ECD3EC171C2** get_address_of_extinguishSounds_4() { return &___extinguishSounds_4; } inline void set_extinguishSounds_4(AudioClipU5BU5D_t03931BD44BC339329210676E452B8ECD3EC171C2* value) { ___extinguishSounds_4 = value; Il2CppCodeGenWriteBarrier((void**)(&___extinguishSounds_4), (void*)value); } }; // UnityStandardAssets.Effects.WaterHoseParticles struct WaterHoseParticles_t4C0EC93AEAF5B1623A7F04AF7D912D6B6438E92B : public MonoBehaviour_t4A60845CF505405AF8BE8C61CC07F75CADEF6429 { public: // System.Single UnityStandardAssets.Effects.WaterHoseParticles::force float ___force_5; // System.Collections.Generic.List`1 UnityStandardAssets.Effects.WaterHoseParticles::m_CollisionEvents List_1_t2762C811E470D336E31761384C6E5382164DA4C7 * ___m_CollisionEvents_6; // UnityEngine.ParticleSystem UnityStandardAssets.Effects.WaterHoseParticles::m_ParticleSystem ParticleSystem_t45DA87A3E83E738DA3FDAA5A48A133F1A1247C3D * ___m_ParticleSystem_7; public: inline static int32_t get_offset_of_force_5() { return static_cast(offsetof(WaterHoseParticles_t4C0EC93AEAF5B1623A7F04AF7D912D6B6438E92B, ___force_5)); } inline float get_force_5() const { return ___force_5; } inline float* get_address_of_force_5() { return &___force_5; } inline void set_force_5(float value) { ___force_5 = value; } inline static int32_t get_offset_of_m_CollisionEvents_6() { return static_cast(offsetof(WaterHoseParticles_t4C0EC93AEAF5B1623A7F04AF7D912D6B6438E92B, ___m_CollisionEvents_6)); } inline List_1_t2762C811E470D336E31761384C6E5382164DA4C7 * get_m_CollisionEvents_6() const { return ___m_CollisionEvents_6; } inline List_1_t2762C811E470D336E31761384C6E5382164DA4C7 ** get_address_of_m_CollisionEvents_6() { return &___m_CollisionEvents_6; } inline void set_m_CollisionEvents_6(List_1_t2762C811E470D336E31761384C6E5382164DA4C7 * value) { ___m_CollisionEvents_6 = value; Il2CppCodeGenWriteBarrier((void**)(&___m_CollisionEvents_6), (void*)value); } inline static int32_t get_offset_of_m_ParticleSystem_7() { return static_cast(offsetof(WaterHoseParticles_t4C0EC93AEAF5B1623A7F04AF7D912D6B6438E92B, ___m_ParticleSystem_7)); } inline ParticleSystem_t45DA87A3E83E738DA3FDAA5A48A133F1A1247C3D * get_m_ParticleSystem_7() const { return ___m_ParticleSystem_7; } inline ParticleSystem_t45DA87A3E83E738DA3FDAA5A48A133F1A1247C3D ** get_address_of_m_ParticleSystem_7() { return &___m_ParticleSystem_7; } inline void set_m_ParticleSystem_7(ParticleSystem_t45DA87A3E83E738DA3FDAA5A48A133F1A1247C3D * value) { ___m_ParticleSystem_7 = value; Il2CppCodeGenWriteBarrier((void**)(&___m_ParticleSystem_7), (void*)value); } }; struct WaterHoseParticles_t4C0EC93AEAF5B1623A7F04AF7D912D6B6438E92B_StaticFields { public: // System.Single UnityStandardAssets.Effects.WaterHoseParticles::lastSoundTime float ___lastSoundTime_4; public: inline static int32_t get_offset_of_lastSoundTime_4() { return static_cast(offsetof(WaterHoseParticles_t4C0EC93AEAF5B1623A7F04AF7D912D6B6438E92B_StaticFields, ___lastSoundTime_4)); } inline float get_lastSoundTime_4() const { return ___lastSoundTime_4; } inline float* get_address_of_lastSoundTime_4() { return &___lastSoundTime_4; } inline void set_lastSoundTime_4(float value) { ___lastSoundTime_4 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif // UnityEngine.Collider[] struct ColliderU5BU5D_t70D1FDAE17E4359298B2BAA828048D1B7CFFE252 : public RuntimeArray { public: ALIGN_FIELD (8) Collider_t0FEEB36760860AD21B3B1F0509C365B393EC4BDF * m_Items[1]; public: inline Collider_t0FEEB36760860AD21B3B1F0509C365B393EC4BDF * GetAt(il2cpp_array_size_t index) const { IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length); return m_Items[index]; } inline Collider_t0FEEB36760860AD21B3B1F0509C365B393EC4BDF ** 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, Collider_t0FEEB36760860AD21B3B1F0509C365B393EC4BDF * value) { IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length); m_Items[index] = value; Il2CppCodeGenWriteBarrier((void**)m_Items + index, (void*)value); } inline Collider_t0FEEB36760860AD21B3B1F0509C365B393EC4BDF * GetAtUnchecked(il2cpp_array_size_t index) const { return m_Items[index]; } inline Collider_t0FEEB36760860AD21B3B1F0509C365B393EC4BDF ** GetAddressAtUnchecked(il2cpp_array_size_t index) { return m_Items + index; } inline void SetAtUnchecked(il2cpp_array_size_t index, Collider_t0FEEB36760860AD21B3B1F0509C365B393EC4BDF * value) { m_Items[index] = value; Il2CppCodeGenWriteBarrier((void**)m_Items + index, (void*)value); } }; // UnityEngine.Vector3[] struct Vector3U5BU5D_tB9EC3346CC4A0EA5447D968E84A9AC1F6F372C28 : public RuntimeArray { public: ALIGN_FIELD (8) Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 m_Items[1]; public: inline Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 GetAt(il2cpp_array_size_t index) const { IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length); return m_Items[index]; } inline Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 * 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_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 value) { IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length); m_Items[index] = value; } inline Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 GetAtUnchecked(il2cpp_array_size_t index) const { return m_Items[index]; } inline Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 * GetAddressAtUnchecked(il2cpp_array_size_t index) { return m_Items + index; } inline void SetAtUnchecked(il2cpp_array_size_t index, Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 value) { m_Items[index] = value; } }; // UnityEngine.Transform[] struct TransformU5BU5D_t4F5A1132877D8BA66ABC0A9A7FADA4E0237A7804 : public RuntimeArray { public: ALIGN_FIELD (8) Transform_tBB9E78A2766C3C83599A8F66EDE7D1FCAFC66EDA * m_Items[1]; public: inline Transform_tBB9E78A2766C3C83599A8F66EDE7D1FCAFC66EDA * GetAt(il2cpp_array_size_t index) const { IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length); return m_Items[index]; } inline Transform_tBB9E78A2766C3C83599A8F66EDE7D1FCAFC66EDA ** 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, Transform_tBB9E78A2766C3C83599A8F66EDE7D1FCAFC66EDA * value) { IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length); m_Items[index] = value; Il2CppCodeGenWriteBarrier((void**)m_Items + index, (void*)value); } inline Transform_tBB9E78A2766C3C83599A8F66EDE7D1FCAFC66EDA * GetAtUnchecked(il2cpp_array_size_t index) const { return m_Items[index]; } inline Transform_tBB9E78A2766C3C83599A8F66EDE7D1FCAFC66EDA ** GetAddressAtUnchecked(il2cpp_array_size_t index) { return m_Items + index; } inline void SetAtUnchecked(il2cpp_array_size_t index, Transform_tBB9E78A2766C3C83599A8F66EDE7D1FCAFC66EDA * value) { m_Items[index] = value; Il2CppCodeGenWriteBarrier((void**)m_Items + index, (void*)value); } }; // UnityEngine.ParticleSystem[] struct ParticleSystemU5BU5D_t58EE604F685D8CBA8EFC9353456969F5A1B2FBB9 : public RuntimeArray { public: ALIGN_FIELD (8) ParticleSystem_t45DA87A3E83E738DA3FDAA5A48A133F1A1247C3D * m_Items[1]; public: inline ParticleSystem_t45DA87A3E83E738DA3FDAA5A48A133F1A1247C3D * GetAt(il2cpp_array_size_t index) const { IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length); return m_Items[index]; } inline ParticleSystem_t45DA87A3E83E738DA3FDAA5A48A133F1A1247C3D ** 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, ParticleSystem_t45DA87A3E83E738DA3FDAA5A48A133F1A1247C3D * value) { IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length); m_Items[index] = value; Il2CppCodeGenWriteBarrier((void**)m_Items + index, (void*)value); } inline ParticleSystem_t45DA87A3E83E738DA3FDAA5A48A133F1A1247C3D * GetAtUnchecked(il2cpp_array_size_t index) const { return m_Items[index]; } inline ParticleSystem_t45DA87A3E83E738DA3FDAA5A48A133F1A1247C3D ** GetAddressAtUnchecked(il2cpp_array_size_t index) { return m_Items + index; } inline void SetAtUnchecked(il2cpp_array_size_t index, ParticleSystem_t45DA87A3E83E738DA3FDAA5A48A133F1A1247C3D * value) { m_Items[index] = value; Il2CppCodeGenWriteBarrier((void**)m_Items + index, (void*)value); } }; // UnityEngine.AudioClip[] struct AudioClipU5BU5D_t03931BD44BC339329210676E452B8ECD3EC171C2 : public RuntimeArray { public: ALIGN_FIELD (8) AudioClip_tCC3C35F579203CE2601243585AB3D6953C3BA051 * m_Items[1]; public: inline AudioClip_tCC3C35F579203CE2601243585AB3D6953C3BA051 * GetAt(il2cpp_array_size_t index) const { IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length); return m_Items[index]; } inline AudioClip_tCC3C35F579203CE2601243585AB3D6953C3BA051 ** 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, AudioClip_tCC3C35F579203CE2601243585AB3D6953C3BA051 * value) { IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length); m_Items[index] = value; Il2CppCodeGenWriteBarrier((void**)m_Items + index, (void*)value); } inline AudioClip_tCC3C35F579203CE2601243585AB3D6953C3BA051 * GetAtUnchecked(il2cpp_array_size_t index) const { return m_Items[index]; } inline AudioClip_tCC3C35F579203CE2601243585AB3D6953C3BA051 ** GetAddressAtUnchecked(il2cpp_array_size_t index) { return m_Items + index; } inline void SetAtUnchecked(il2cpp_array_size_t index, AudioClip_tCC3C35F579203CE2601243585AB3D6953C3BA051 * value) { m_Items[index] = value; Il2CppCodeGenWriteBarrier((void**)m_Items + index, (void*)value); } }; // UnityEngine.ParticleCollisionEvent[] struct ParticleCollisionEventU5BU5D_t771CB4A499CC97F3340C673D227DD1F5969EB9B9 : public RuntimeArray { public: ALIGN_FIELD (8) ParticleCollisionEvent_t7F4D7D5ACF8521671549D9328D4E2DDE480D8D47 m_Items[1]; public: inline ParticleCollisionEvent_t7F4D7D5ACF8521671549D9328D4E2DDE480D8D47 GetAt(il2cpp_array_size_t index) const { IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length); return m_Items[index]; } inline ParticleCollisionEvent_t7F4D7D5ACF8521671549D9328D4E2DDE480D8D47 * 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, ParticleCollisionEvent_t7F4D7D5ACF8521671549D9328D4E2DDE480D8D47 value) { IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length); m_Items[index] = value; } inline ParticleCollisionEvent_t7F4D7D5ACF8521671549D9328D4E2DDE480D8D47 GetAtUnchecked(il2cpp_array_size_t index) const { return m_Items[index]; } inline ParticleCollisionEvent_t7F4D7D5ACF8521671549D9328D4E2DDE480D8D47 * GetAddressAtUnchecked(il2cpp_array_size_t index) { return m_Items + index; } inline void SetAtUnchecked(il2cpp_array_size_t index, ParticleCollisionEvent_t7F4D7D5ACF8521671549D9328D4E2DDE480D8D47 value) { m_Items[index] = value; } }; // !!0 UnityEngine.Component::GetComponent() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR RuntimeObject * Component_GetComponent_TisRuntimeObject_m129DEF8A66683189ED44B21496135824743EF617_gshared (Component_t05064EF382ABCAF4B8C94F8A350EA85184C26621 * __this, const RuntimeMethod* method); // !!0 UnityEngine.Object::Instantiate(!!0,UnityEngine.Vector3,UnityEngine.Quaternion) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR RuntimeObject * Object_Instantiate_TisRuntimeObject_m352D452C728667C9C76C942525CDE26444568ECD_gshared (RuntimeObject * ___original0, Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 ___position1, Quaternion_t319F3319A7D43FFA5D819AD6C0A98851F0095357 ___rotation2, const RuntimeMethod* method); // System.Void System.Collections.Generic.List`1::.ctor() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void List_1__ctor_mC832F1AC0F814BAEB19175F5D7972A7507508BC3_gshared (List_1_t05CC3C859AB5E6024394EF9A42E3E696628CA02D * __this, const RuntimeMethod* method); // System.Boolean System.Collections.Generic.List`1::Contains(!0) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR bool List_1_Contains_mE08D561E86879A26245096C572A8593279383FDB_gshared (List_1_t05CC3C859AB5E6024394EF9A42E3E696628CA02D * __this, RuntimeObject * ___item0, const RuntimeMethod* method); // System.Void System.Collections.Generic.List`1::Add(!0) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void List_1_Add_m6930161974C7504C80F52EC379EF012387D43138_gshared (List_1_t05CC3C859AB5E6024394EF9A42E3E696628CA02D * __this, RuntimeObject * ___item0, const RuntimeMethod* method); // System.Collections.Generic.List`1/Enumerator System.Collections.Generic.List`1::GetEnumerator() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR Enumerator_tE0C99528D3DCE5863566CE37BD94162A4C0431CD List_1_GetEnumerator_m52CC760E475D226A2B75048D70C4E22692F9F68D_gshared (List_1_t05CC3C859AB5E6024394EF9A42E3E696628CA02D * __this, const RuntimeMethod* method); // !0 System.Collections.Generic.List`1/Enumerator::get_Current() IL2CPP_EXTERN_C inline IL2CPP_METHOD_ATTR RuntimeObject * Enumerator_get_Current_mD7829C7E8CFBEDD463B15A951CDE9B90A12CC55C_gshared_inline (Enumerator_tE0C99528D3DCE5863566CE37BD94162A4C0431CD * __this, const RuntimeMethod* method); // System.Boolean System.Collections.Generic.List`1/Enumerator::MoveNext() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR bool Enumerator_MoveNext_m38B1099DDAD7EEDE2F4CDAB11C095AC784AC2E34_gshared (Enumerator_tE0C99528D3DCE5863566CE37BD94162A4C0431CD * __this, const RuntimeMethod* method); // System.Void System.Collections.Generic.List`1/Enumerator::Dispose() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Enumerator_Dispose_m94D0DAE031619503CDA6E53C5C3CC78AF3139472_gshared (Enumerator_tE0C99528D3DCE5863566CE37BD94162A4C0431CD * __this, const RuntimeMethod* method); // !!0[] UnityEngine.Component::GetComponentsInChildren() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR ObjectU5BU5D_t3C9242B5C88A48B2A5BD9FDA6CD0024E792AF08A* Component_GetComponentsInChildren_TisRuntimeObject_m6D4C38C330FCFD3C323B34031A7E877A5E2D453A_gshared (Component_t05064EF382ABCAF4B8C94F8A350EA85184C26621 * __this, const RuntimeMethod* method); // !0 System.Collections.Generic.List`1::get_Item(System.Int32) IL2CPP_EXTERN_C inline IL2CPP_METHOD_ATTR ParticleCollisionEvent_t7F4D7D5ACF8521671549D9328D4E2DDE480D8D47 List_1_get_Item_m095B750642DEE222CA241EE9D2392CA6E200FA8D_gshared_inline (List_1_t2762C811E470D336E31761384C6E5382164DA4C7 * __this, int32_t ___index0, const RuntimeMethod* method); // System.Void System.Collections.Generic.List`1::.ctor() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void List_1__ctor_m377714278A7FAB4D7514D181355D61B01B3427B0_gshared (List_1_t2762C811E470D336E31761384C6E5382164DA4C7 * __this, const RuntimeMethod* method); // !!0 UnityEngine.Component::GetComponent() inline Collider_t0FEEB36760860AD21B3B1F0509C365B393EC4BDF * Component_GetComponent_TisCollider_t0FEEB36760860AD21B3B1F0509C365B393EC4BDF_m6B8E8E0E0AF6B08652B81B7950FC5AF63EAD40C6 (Component_t05064EF382ABCAF4B8C94F8A350EA85184C26621 * __this, const RuntimeMethod* method) { return (( Collider_t0FEEB36760860AD21B3B1F0509C365B393EC4BDF * (*) (Component_t05064EF382ABCAF4B8C94F8A350EA85184C26621 *, const RuntimeMethod*))Component_GetComponent_TisRuntimeObject_m129DEF8A66683189ED44B21496135824743EF617_gshared)(__this, method); } // UnityEngine.Transform UnityEngine.Component::get_transform() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR Transform_tBB9E78A2766C3C83599A8F66EDE7D1FCAFC66EDA * Component_get_transform_m00F05BD782F920C301A7EBA480F3B7A904C07EC9 (Component_t05064EF382ABCAF4B8C94F8A350EA85184C26621 * __this, const RuntimeMethod* method); // UnityEngine.Vector3 UnityEngine.Transform::get_position() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 Transform_get_position_mF54C3A064F7C8E24F1C56EE128728B2E4485E294 (Transform_tBB9E78A2766C3C83599A8F66EDE7D1FCAFC66EDA * __this, const RuntimeMethod* method); // UnityEngine.Vector3 UnityEngine.SphereCollider::get_center() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 SphereCollider_get_center_mE7AD1AC46974FF23EEA621B872E2962E52A1DB00 (SphereCollider_tAC3E5E20B385DF1C0B17F3EA5C7214F71367706F * __this, const RuntimeMethod* method); // UnityEngine.Vector3 UnityEngine.Vector3::op_Addition(UnityEngine.Vector3,UnityEngine.Vector3) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 Vector3_op_Addition_m929F9C17E5D11B94D50B4AFF1D730B70CB59B50E (Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 ___a0, Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 ___b1, const RuntimeMethod* method); // System.Single UnityEngine.SphereCollider::get_radius() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR float SphereCollider_get_radius_m255804173C17314FD9538AE45C4A46D4882BC094 (SphereCollider_tAC3E5E20B385DF1C0B17F3EA5C7214F71367706F * __this, const RuntimeMethod* method); // UnityEngine.Collider[] UnityEngine.Physics::OverlapSphere(UnityEngine.Vector3,System.Single) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR ColliderU5BU5D_t70D1FDAE17E4359298B2BAA828048D1B7CFFE252* Physics_OverlapSphere_m354A92672F7A6DE59EF1285D02D62247F46A5D84 (Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 ___position0, float ___radius1, const RuntimeMethod* method); // UnityEngine.Rigidbody UnityEngine.Collider::get_attachedRigidbody() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR Rigidbody_tE0A58EE5A1F7DC908EFFB4F0D795AC9552A750A5 * Collider_get_attachedRigidbody_m9E3C688EAE2F6A76C9AC14968D96769D9A71B1E8 (Collider_t0FEEB36760860AD21B3B1F0509C365B393EC4BDF * __this, const RuntimeMethod* method); // System.Boolean UnityEngine.Object::op_Inequality(UnityEngine.Object,UnityEngine.Object) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR bool Object_op_Inequality_m31EF58E217E8F4BDD3E409DEF79E1AEE95874FC1 (Object_tAE11E5E46CD5C37C9F3E8950C00CD8B45666A2D0 * ___x0, Object_tAE11E5E46CD5C37C9F3E8950C00CD8B45666A2D0 * ___y1, const RuntimeMethod* method); // UnityEngine.Vector3 UnityEngine.Transform::InverseTransformPoint(UnityEngine.Vector3) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 Transform_InverseTransformPoint_mB6E3145F20B531B4A781C194BAC43A8255C96C47 (Transform_tBB9E78A2766C3C83599A8F66EDE7D1FCAFC66EDA * __this, Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 ___position0, const RuntimeMethod* method); // System.Void UnityEngine.Vector3::.ctor(System.Single,System.Single,System.Single) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Vector3__ctor_m08F61F548AA5836D8789843ACB4A81E4963D2EE1 (Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 * __this, float ___x0, float ___y1, float ___z2, const RuntimeMethod* method); // UnityEngine.Vector3 UnityEngine.Vector3::MoveTowards(UnityEngine.Vector3,UnityEngine.Vector3,System.Single) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 Vector3_MoveTowards_mA288BB5AA73DDA9CA76EDC11F339BAFDA1E4FF45 (Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 ___current0, Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 ___target1, float ___maxDistanceDelta2, const RuntimeMethod* method); // System.Single UnityEngine.Vector3::get_magnitude() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR float Vector3_get_magnitude_m9A750659B60C5FE0C30438A7F9681775D5DB1274 (Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 * __this, const RuntimeMethod* method); // System.Single UnityEngine.Mathf::InverseLerp(System.Single,System.Single,System.Single) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR float Mathf_InverseLerp_m7054CDF25056E9B27D2467F91C95D628508F1F31 (float ___a0, float ___b1, float ___value2, const RuntimeMethod* method); // UnityEngine.Vector3 UnityEngine.Vector3::op_Subtraction(UnityEngine.Vector3,UnityEngine.Vector3) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 Vector3_op_Subtraction_mF9846B723A5034F8B9F5F5DCB78E3D67649143D3 (Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 ___a0, Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 ___b1, const RuntimeMethod* method); // UnityEngine.Vector3 UnityEngine.Vector3::get_normalized() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 Vector3_get_normalized_mE20796F1D2D36244FACD4D14DADB245BE579849B (Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 * __this, const RuntimeMethod* method); // UnityEngine.Vector3 UnityEngine.Vector3::op_Multiply(UnityEngine.Vector3,System.Single) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 Vector3_op_Multiply_m1C5F07723615156ACF035D88A1280A9E8F35A04E (Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 ___a0, float ___d1, const RuntimeMethod* method); // UnityEngine.Vector3 UnityEngine.Transform::TransformPoint(System.Single,System.Single,System.Single) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 Transform_TransformPoint_m363B3A9E2C3A9A52F4B872CF34F476D87CCC8CEC (Transform_tBB9E78A2766C3C83599A8F66EDE7D1FCAFC66EDA * __this, float ___x0, float ___y1, float ___z2, const RuntimeMethod* method); // UnityEngine.Vector3 UnityEngine.Vector3::Lerp(UnityEngine.Vector3,UnityEngine.Vector3,System.Single) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 Vector3_Lerp_m5BA75496B803820CC64079383956D73C6FD4A8A1 (Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 ___a0, Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 ___b1, float ___t2, const RuntimeMethod* method); // System.Void UnityEngine.Rigidbody::AddForceAtPosition(UnityEngine.Vector3,UnityEngine.Vector3) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Rigidbody_AddForceAtPosition_m3A5DCFC3E79923C9D8E32A54BC4AAA1E48EEAD6C (Rigidbody_tE0A58EE5A1F7DC908EFFB4F0D795AC9552A750A5 * __this, Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 ___force0, Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 ___position1, const RuntimeMethod* method); // System.Boolean UnityEngine.Object::op_Equality(UnityEngine.Object,UnityEngine.Object) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR bool Object_op_Equality_mBC2401774F3BE33E8CF6F0A8148E66C95D6CFF1C (Object_tAE11E5E46CD5C37C9F3E8950C00CD8B45666A2D0 * ___x0, Object_tAE11E5E46CD5C37C9F3E8950C00CD8B45666A2D0 * ___y1, const RuntimeMethod* method); // System.Void UnityEngine.SphereCollider::set_radius(System.Single) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void SphereCollider_set_radius_m3161573A2D89F495F4B79E16C52B905C0F9AD699 (SphereCollider_tAC3E5E20B385DF1C0B17F3EA5C7214F71367706F * __this, float ___value0, const RuntimeMethod* method); // System.Void UnityEngine.SphereCollider::set_center(UnityEngine.Vector3) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void SphereCollider_set_center_m325070F5252B4A2EA567B653CAE3285F101FA3EE (SphereCollider_tAC3E5E20B385DF1C0B17F3EA5C7214F71367706F * __this, Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 ___value0, const RuntimeMethod* method); // UnityEngine.Vector3 UnityEngine.Vector3::get_up() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 Vector3_get_up_m6309EBC4E42D6D0B3D28056BD23D0331275306F7 (const RuntimeMethod* method); // UnityEngine.Vector3 UnityEngine.Vector3::op_UnaryNegation(UnityEngine.Vector3) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 Vector3_op_UnaryNegation_m2AFBBF22801F9BCA5A4EBE642A29F433FE1339C2 (Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 ___a0, const RuntimeMethod* method); // UnityEngine.Vector3 UnityEngine.Vector3::get_right() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 Vector3_get_right_m6DD9559CA0C75BBA42D9140021C4C2A9AAA9B3F5 (const RuntimeMethod* method); // System.Void UnityEngine.Color::.ctor(System.Single,System.Single,System.Single,System.Single) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Color__ctor_m20DF490CEB364C4FC36D7EE392640DF5B7420D7C (Color_t119BCA590009762C7223FDD3AF9706653AC84ED2 * __this, float ___r0, float ___g1, float ___b2, float ___a3, const RuntimeMethod* method); // System.Void UnityEngine.Gizmos::set_color(UnityEngine.Color) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Gizmos_set_color_mFA6C199DF05FF557AEF662222CA60EC25DF54F28 (Color_t119BCA590009762C7223FDD3AF9706653AC84ED2 ___value0, const RuntimeMethod* method); // UnityEngine.Quaternion UnityEngine.Transform::get_rotation() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR Quaternion_t319F3319A7D43FFA5D819AD6C0A98851F0095357 Transform_get_rotation_m3AB90A67403249AECCA5E02BC70FCE8C90FE9FB9 (Transform_tBB9E78A2766C3C83599A8F66EDE7D1FCAFC66EDA * __this, const RuntimeMethod* method); // UnityEngine.Vector3 UnityEngine.Quaternion::op_Multiply(UnityEngine.Quaternion,UnityEngine.Vector3) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 Quaternion_op_Multiply_mD5999DE317D808808B72E58E7A978C4C0995879C (Quaternion_t319F3319A7D43FFA5D819AD6C0A98851F0095357 ___rotation0, Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 ___point1, const RuntimeMethod* method); // UnityEngine.Quaternion UnityEngine.Quaternion::AngleAxis(System.Single,UnityEngine.Vector3) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR Quaternion_t319F3319A7D43FFA5D819AD6C0A98851F0095357 Quaternion_AngleAxis_m07DACF59F0403451DABB9BC991C53EE3301E88B0 (float ___angle0, Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 ___axis1, const RuntimeMethod* method); // UnityEngine.Vector3 UnityEngine.Vector3::get_forward() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 Vector3_get_forward_m3E2E192B3302130098738C308FA1EE1439449D0D (const RuntimeMethod* method); // UnityEngine.Vector3 UnityEngine.Transform::TransformDirection(UnityEngine.Vector3) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 Transform_TransformDirection_m85FC1D7E1322E94F65DA59AEF3B1166850B183EF (Transform_tBB9E78A2766C3C83599A8F66EDE7D1FCAFC66EDA * __this, Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 ___direction0, const RuntimeMethod* method); // System.Void UnityEngine.Gizmos::DrawLine(UnityEngine.Vector3,UnityEngine.Vector3) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Gizmos_DrawLine_m9515D59D2536571F4906A3C54E613A3986DFD892 (Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 ___from0, Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 ___to1, const RuntimeMethod* method); // System.Void UnityEngine.MonoBehaviour::.ctor() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void MonoBehaviour__ctor_mEAEC84B222C60319D593E456D769B3311DFCEF97 (MonoBehaviour_t4A60845CF505405AF8BE8C61CC07F75CADEF6429 * __this, const RuntimeMethod* method); // System.Void UnityStandardAssets.Effects.ExplosionFireAndDebris/d__4::.ctor(System.Int32) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void U3CStartU3Ed__4__ctor_mBDD727783F54367BFE2CED7C675B839450955B8C (U3CStartU3Ed__4_t945A707CD8C01DA1C37AE2DD9D0A904C80F58139 * __this, int32_t ___U3CU3E1__state0, const RuntimeMethod* method); // UnityEngine.Quaternion UnityEngine.Quaternion::get_identity() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR Quaternion_t319F3319A7D43FFA5D819AD6C0A98851F0095357 Quaternion_get_identity_m548B37D80F2DEE60E41D1F09BF6889B557BE1A64 (const RuntimeMethod* method); // !!0 UnityEngine.Object::Instantiate(!!0,UnityEngine.Vector3,UnityEngine.Quaternion) inline Transform_tBB9E78A2766C3C83599A8F66EDE7D1FCAFC66EDA * Object_Instantiate_TisTransform_tBB9E78A2766C3C83599A8F66EDE7D1FCAFC66EDA_m8BCC51A95F42E99B9033022D8BF0EABA04FED8F0 (Transform_tBB9E78A2766C3C83599A8F66EDE7D1FCAFC66EDA * ___original0, Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 ___position1, Quaternion_t319F3319A7D43FFA5D819AD6C0A98851F0095357 ___rotation2, const RuntimeMethod* method) { return (( Transform_tBB9E78A2766C3C83599A8F66EDE7D1FCAFC66EDA * (*) (Transform_tBB9E78A2766C3C83599A8F66EDE7D1FCAFC66EDA *, Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 , Quaternion_t319F3319A7D43FFA5D819AD6C0A98851F0095357 , const RuntimeMethod*))Object_Instantiate_TisRuntimeObject_m352D452C728667C9C76C942525CDE26444568ECD_gshared)(___original0, ___position1, ___rotation2, method); } // System.Void UnityEngine.Transform::set_parent(UnityEngine.Transform) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Transform_set_parent_m65B8E4660B2C554069C57A957D9E55FECA7AA73E (Transform_tBB9E78A2766C3C83599A8F66EDE7D1FCAFC66EDA * __this, Transform_tBB9E78A2766C3C83599A8F66EDE7D1FCAFC66EDA * ___value0, const RuntimeMethod* method); // System.Void System.Object::.ctor() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Object__ctor_m925ECA5E85CA100E3FB86A4F9E15C120E9A184C0 (RuntimeObject * __this, const RuntimeMethod* method); // !!0 UnityEngine.Component::GetComponent() inline ParticleSystemMultiplier_t8EBFEF83EBA48DD7F6517ABFFBE2CD051CB2C748 * Component_GetComponent_TisParticleSystemMultiplier_t8EBFEF83EBA48DD7F6517ABFFBE2CD051CB2C748_m77EDAEF51740299BC986B0DA36AB7282BB8DDD45 (Component_t05064EF382ABCAF4B8C94F8A350EA85184C26621 * __this, const RuntimeMethod* method) { return (( ParticleSystemMultiplier_t8EBFEF83EBA48DD7F6517ABFFBE2CD051CB2C748 * (*) (Component_t05064EF382ABCAF4B8C94F8A350EA85184C26621 *, const RuntimeMethod*))Component_GetComponent_TisRuntimeObject_m129DEF8A66683189ED44B21496135824743EF617_gshared)(__this, method); } // System.Int32 UnityEngine.Random::Range(System.Int32,System.Int32) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR int32_t Random_Range_mD0C8F37FF3CAB1D87AAA6C45130BD59626BD6780 (int32_t ___min0, int32_t ___max1, const RuntimeMethod* method); // UnityEngine.Vector3 UnityEngine.Random::get_insideUnitSphere() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 Random_get_insideUnitSphere_m10033DFB85B1A21CE44201CB0E421F27B77A868F (const RuntimeMethod* method); // UnityEngine.Quaternion UnityEngine.Random::get_rotation() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR Quaternion_t319F3319A7D43FFA5D819AD6C0A98851F0095357 Random_get_rotation_mFEB212A2058746E0E8F544D8C2201663861BA77A (const RuntimeMethod* method); // System.Void UnityEngine.Ray::.ctor(UnityEngine.Vector3,UnityEngine.Vector3) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Ray__ctor_m695D219349B8AA4C82F96C55A27D384C07736F6B (Ray_tE2163D4CB3E6B267E29F8ABE41684490E4A614B2 * __this, Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 ___origin0, Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 ___direction1, const RuntimeMethod* method); // System.Boolean UnityEngine.Collider::Raycast(UnityEngine.Ray,UnityEngine.RaycastHit&,System.Single) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR bool Collider_Raycast_mF79828BB10A356336B673595777F7C6941E3F42F (Collider_t0FEEB36760860AD21B3B1F0509C365B393EC4BDF * __this, Ray_tE2163D4CB3E6B267E29F8ABE41684490E4A614B2 ___ray0, RaycastHit_t19695F18F9265FE5425062BBA6A4D330480538C3 * ___hitInfo1, float ___maxDistance2, const RuntimeMethod* method); // UnityEngine.Vector3 UnityEngine.RaycastHit::get_point() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 RaycastHit_get_point_m0E564B2A72C7A744B889AE9D596F3EFA55059001 (RaycastHit_t19695F18F9265FE5425062BBA6A4D330480538C3 * __this, const RuntimeMethod* method); // UnityEngine.Vector3 UnityEngine.RaycastHit::get_normal() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 RaycastHit_get_normal_mF736A6D09D98D63AB7E5BF10F38AEBFC177A1D94 (RaycastHit_t19695F18F9265FE5425062BBA6A4D330480538C3 * __this, const RuntimeMethod* method); // System.Void UnityStandardAssets.Effects.ExplosionFireAndDebris::AddFire(UnityEngine.Transform,UnityEngine.Vector3,UnityEngine.Vector3) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void ExplosionFireAndDebris_AddFire_m781F3E400896C4F2E2B4A24FAEFE52D01ED26C0B (ExplosionFireAndDebris_tACCFCC1184BB9A8C3A0B39D99FFC831E76F9EECB * __this, Transform_tBB9E78A2766C3C83599A8F66EDE7D1FCAFC66EDA * ___t0, Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 ___pos1, Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 ___normal2, const RuntimeMethod* method); // UnityEngine.Vector3 UnityEngine.Random::get_onUnitSphere() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 Random_get_onUnitSphere_mBF4707ADEABB994E7B5B80305205A621B809E7E6 (const RuntimeMethod* method); // System.Boolean UnityEngine.Physics::Raycast(UnityEngine.Ray,UnityEngine.RaycastHit&,System.Single) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR bool Physics_Raycast_mE1590EE4E2DC950A9FC2437E98EE8CD2EC2DEE67 (Ray_tE2163D4CB3E6B267E29F8ABE41684490E4A614B2 ___ray0, RaycastHit_t19695F18F9265FE5425062BBA6A4D330480538C3 * ___hitInfo1, float ___maxDistance2, const RuntimeMethod* method); // System.Void System.NotSupportedException::.ctor() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void NotSupportedException__ctor_mA121DE1CAC8F25277DEB489DC7771209D91CAE33 (NotSupportedException_tE75B318D6590A02A5D9B29FD97409B1750FA0010 * __this, const RuntimeMethod* method); // System.Void UnityStandardAssets.Effects.ExplosionPhysicsForce/d__1::.ctor(System.Int32) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void U3CStartU3Ed__1__ctor_m28BA84EE932E5505BA7BD35AC5F8007BA8B96564 (U3CStartU3Ed__1_tFA687701957C85736794A1CD53601F73339D788F * __this, int32_t ___U3CU3E1__state0, const RuntimeMethod* method); // System.Void System.Collections.Generic.List`1::.ctor() inline void List_1__ctor_m8F8DC666C2D1350D6CDDE96E73998792E882CF46 (List_1_tF00B86100455886AD0B3A0B82FE6C94700D131D0 * __this, const RuntimeMethod* method) { (( void (*) (List_1_tF00B86100455886AD0B3A0B82FE6C94700D131D0 *, const RuntimeMethod*))List_1__ctor_mC832F1AC0F814BAEB19175F5D7972A7507508BC3_gshared)(__this, method); } // System.Boolean System.Collections.Generic.List`1::Contains(!0) inline bool List_1_Contains_m4D1DE7EDA972C9BCD4617A52BFF4CFE08895758C (List_1_tF00B86100455886AD0B3A0B82FE6C94700D131D0 * __this, Rigidbody_tE0A58EE5A1F7DC908EFFB4F0D795AC9552A750A5 * ___item0, const RuntimeMethod* method) { return (( bool (*) (List_1_tF00B86100455886AD0B3A0B82FE6C94700D131D0 *, Rigidbody_tE0A58EE5A1F7DC908EFFB4F0D795AC9552A750A5 *, const RuntimeMethod*))List_1_Contains_mE08D561E86879A26245096C572A8593279383FDB_gshared)(__this, ___item0, method); } // System.Void System.Collections.Generic.List`1::Add(!0) inline void List_1_Add_mA7DDE87A050C0636FDCC9DC4A5BCA55A5379A4B8 (List_1_tF00B86100455886AD0B3A0B82FE6C94700D131D0 * __this, Rigidbody_tE0A58EE5A1F7DC908EFFB4F0D795AC9552A750A5 * ___item0, const RuntimeMethod* method) { (( void (*) (List_1_tF00B86100455886AD0B3A0B82FE6C94700D131D0 *, Rigidbody_tE0A58EE5A1F7DC908EFFB4F0D795AC9552A750A5 *, const RuntimeMethod*))List_1_Add_m6930161974C7504C80F52EC379EF012387D43138_gshared)(__this, ___item0, method); } // System.Collections.Generic.List`1/Enumerator System.Collections.Generic.List`1::GetEnumerator() inline Enumerator_t27C52ABD621DACF0C5D52FDAA65A98738987017E List_1_GetEnumerator_m7CB8469ED2AE9E0CA1FEFF4C60991DFF8BD8CFF3 (List_1_tF00B86100455886AD0B3A0B82FE6C94700D131D0 * __this, const RuntimeMethod* method) { return (( Enumerator_t27C52ABD621DACF0C5D52FDAA65A98738987017E (*) (List_1_tF00B86100455886AD0B3A0B82FE6C94700D131D0 *, const RuntimeMethod*))List_1_GetEnumerator_m52CC760E475D226A2B75048D70C4E22692F9F68D_gshared)(__this, method); } // !0 System.Collections.Generic.List`1/Enumerator::get_Current() inline Rigidbody_tE0A58EE5A1F7DC908EFFB4F0D795AC9552A750A5 * Enumerator_get_Current_mC1CD020347F81EDABBA39647711D3D2E115176C7_inline (Enumerator_t27C52ABD621DACF0C5D52FDAA65A98738987017E * __this, const RuntimeMethod* method) { return (( Rigidbody_tE0A58EE5A1F7DC908EFFB4F0D795AC9552A750A5 * (*) (Enumerator_t27C52ABD621DACF0C5D52FDAA65A98738987017E *, const RuntimeMethod*))Enumerator_get_Current_mD7829C7E8CFBEDD463B15A951CDE9B90A12CC55C_gshared_inline)(__this, method); } // System.Void UnityEngine.Rigidbody::AddExplosionForce(System.Single,UnityEngine.Vector3,System.Single,System.Single,UnityEngine.ForceMode) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Rigidbody_AddExplosionForce_m8A2C25CE73AC51E1C255929733A4187089BA689A (Rigidbody_tE0A58EE5A1F7DC908EFFB4F0D795AC9552A750A5 * __this, float ___explosionForce0, Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 ___explosionPosition1, float ___explosionRadius2, float ___upwardsModifier3, int32_t ___mode4, const RuntimeMethod* method); // System.Boolean System.Collections.Generic.List`1/Enumerator::MoveNext() inline bool Enumerator_MoveNext_m9A51F685E9FE881F75850562F97DD04FB51B3F0F (Enumerator_t27C52ABD621DACF0C5D52FDAA65A98738987017E * __this, const RuntimeMethod* method) { return (( bool (*) (Enumerator_t27C52ABD621DACF0C5D52FDAA65A98738987017E *, const RuntimeMethod*))Enumerator_MoveNext_m38B1099DDAD7EEDE2F4CDAB11C095AC784AC2E34_gshared)(__this, method); } // System.Void System.Collections.Generic.List`1/Enumerator::Dispose() inline void Enumerator_Dispose_mECFDE242B9B4ECC8048254467FCB58F6EA7333F6 (Enumerator_t27C52ABD621DACF0C5D52FDAA65A98738987017E * __this, const RuntimeMethod* method) { (( void (*) (Enumerator_t27C52ABD621DACF0C5D52FDAA65A98738987017E *, const RuntimeMethod*))Enumerator_Dispose_m94D0DAE031619503CDA6E53C5C3CC78AF3139472_gshared)(__this, method); } // !!0[] UnityEngine.Component::GetComponentsInChildren() inline ParticleSystemU5BU5D_t58EE604F685D8CBA8EFC9353456969F5A1B2FBB9* Component_GetComponentsInChildren_TisParticleSystem_t45DA87A3E83E738DA3FDAA5A48A133F1A1247C3D_mD5AEF673286CB17B689F765BB71E83509548DC41 (Component_t05064EF382ABCAF4B8C94F8A350EA85184C26621 * __this, const RuntimeMethod* method) { return (( ParticleSystemU5BU5D_t58EE604F685D8CBA8EFC9353456969F5A1B2FBB9* (*) (Component_t05064EF382ABCAF4B8C94F8A350EA85184C26621 *, const RuntimeMethod*))Component_GetComponentsInChildren_TisRuntimeObject_m6D4C38C330FCFD3C323B34031A7E877A5E2D453A_gshared)(__this, method); } // UnityEngine.ParticleSystem/EmissionModule UnityEngine.ParticleSystem::get_emission() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR EmissionModule_t35028C3DE5EFDCE49E8A9732460617A56BD1D3F1 ParticleSystem_get_emission_mA1204EAF07A6C6B3F65B45295797A1FFF64D343C (ParticleSystem_t45DA87A3E83E738DA3FDAA5A48A133F1A1247C3D * __this, const RuntimeMethod* method); // System.Void UnityEngine.ParticleSystem/EmissionModule::set_enabled(System.Boolean) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void EmissionModule_set_enabled_m3896B441BDE0F0752A6D113012B20D5D31B16D36 (EmissionModule_t35028C3DE5EFDCE49E8A9732460617A56BD1D3F1 * __this, bool ___value0, const RuntimeMethod* method); // System.Single UnityEngine.Random::get_value() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR float Random_get_value_mC998749E08291DD42CF31C026FAC4F14F746831C (const RuntimeMethod* method); // !!0 UnityEngine.Component::GetComponent() inline Light_tFDE490EADBC7E080F74CA804929513AF07C31A6C * Component_GetComponent_TisLight_tFDE490EADBC7E080F74CA804929513AF07C31A6C_m1DCED5DB1934151FC68A8E7CAECF7986359D7107 (Component_t05064EF382ABCAF4B8C94F8A350EA85184C26621 * __this, const RuntimeMethod* method) { return (( Light_tFDE490EADBC7E080F74CA804929513AF07C31A6C * (*) (Component_t05064EF382ABCAF4B8C94F8A350EA85184C26621 *, const RuntimeMethod*))Component_GetComponent_TisRuntimeObject_m129DEF8A66683189ED44B21496135824743EF617_gshared)(__this, method); } // System.Single UnityEngine.Time::get_time() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR float Time_get_time_m7863349C8845BBA36629A2B3F8EF1C3BEA350FD8 (const RuntimeMethod* method); // System.Single UnityEngine.Mathf::PerlinNoise(System.Single,System.Single) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR float Mathf_PerlinNoise_mA36E513B2931F17ACBF26D928674D3DDEDF5C810 (float ___x0, float ___y1, const RuntimeMethod* method); // System.Void UnityEngine.Light::set_intensity(System.Single) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Light_set_intensity_mE209975C840F1D887B4207C390DB5A2EF15A763C (Light_tFDE490EADBC7E080F74CA804929513AF07C31A6C * __this, float ___value0, const RuntimeMethod* method); // System.Void UnityEngine.Transform::set_localPosition(UnityEngine.Vector3) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Transform_set_localPosition_m275F5550DD939F83AFEB5E8D681131172E2E1728 (Transform_tBB9E78A2766C3C83599A8F66EDE7D1FCAFC66EDA * __this, Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 ___value0, const RuntimeMethod* method); // System.Void UnityEngine.Behaviour::set_enabled(System.Boolean) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Behaviour_set_enabled_m9755D3B17D7022D23D1E4C618BD9A6B66A5ADC6B (Behaviour_tBDC7E9C3C898AD8348891B82D3E345801D920CA8 * __this, bool ___value0, const RuntimeMethod* method); // System.Boolean UnityEngine.Input::GetMouseButton(System.Int32) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR bool Input_GetMouseButton_m43C68DE93C7D990E875BA53C4DEC9CA6230C8B79 (int32_t ___button0, const RuntimeMethod* method); // System.Single UnityEngine.Time::get_deltaTime() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR float Time_get_deltaTime_m16F98FC9BA931581236008C288E3B25CBCB7C81E (const RuntimeMethod* method); // System.Single UnityEngine.Mathf::Lerp(System.Single,System.Single,System.Single) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR float Mathf_Lerp_m9A74C5A0C37D0CDF45EE66E7774D12A9B93B1364 (float ___a0, float ___b1, float ___t2, const RuntimeMethod* method); // System.Boolean UnityEngine.Input::GetKeyDown(UnityEngine.KeyCode) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR bool Input_GetKeyDown_mEA57896808B6F484B12CD0AEEB83390A3CFCDBDC (int32_t ___key0, const RuntimeMethod* method); // System.Boolean UnityEngine.Renderer::get_enabled() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR bool Renderer_get_enabled_m40E07BB15DA58D2EF6F6796C6778163107DD7E1B (Renderer_t0556D67DD582620D1F495627EDE30D03284151F4 * __this, const RuntimeMethod* method); // System.Void UnityEngine.Renderer::set_enabled(System.Boolean) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Renderer_set_enabled_m0933766657F2685BAAE3340B0A984C0E63925303 (Renderer_t0556D67DD582620D1F495627EDE30D03284151F4 * __this, bool ___value0, const RuntimeMethod* method); // UnityEngine.ParticleSystem/MainModule UnityEngine.ParticleSystem::get_main() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR MainModule_t99C675667E0A363368324132DFA34B27FFEE6FC7 ParticleSystem_get_main_m360B0AA57C71DE0358B6B07133C68B5FD88C742F (ParticleSystem_t45DA87A3E83E738DA3FDAA5A48A133F1A1247C3D * __this, const RuntimeMethod* method); // UnityEngine.ParticleSystem/MinMaxCurve UnityEngine.ParticleSystem/MinMaxCurve::op_Implicit(System.Single) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR MinMaxCurve_tDB335EDEBEBD4CFA753081D7C3A2FE2EECFA6D71 MinMaxCurve_op_Implicit_m998EE9F8D83B9545F63E2DFA304E99620F0F707F (float ___constant0, const RuntimeMethod* method); // System.Void UnityEngine.ParticleSystem/MainModule::set_startSpeed(UnityEngine.ParticleSystem/MinMaxCurve) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void MainModule_set_startSpeed_m32CD8968F2B5572112DE22CC7B6E2B502222B4AE (MainModule_t99C675667E0A363368324132DFA34B27FFEE6FC7 * __this, MinMaxCurve_tDB335EDEBEBD4CFA753081D7C3A2FE2EECFA6D71 ___value0, const RuntimeMethod* method); // System.Single UnityEngine.ParticleSystem/MainModule::get_startSizeMultiplier() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR float MainModule_get_startSizeMultiplier_m8E241099DB1E4ECE4827E9507415C80012AEA312 (MainModule_t99C675667E0A363368324132DFA34B27FFEE6FC7 * __this, const RuntimeMethod* method); // System.Void UnityEngine.ParticleSystem/MainModule::set_startSizeMultiplier(System.Single) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void MainModule_set_startSizeMultiplier_m6375840B2CADFF82321D7B52103FADC5AD144B8C (MainModule_t99C675667E0A363368324132DFA34B27FFEE6FC7 * __this, float ___value0, const RuntimeMethod* method); // System.Single UnityEngine.ParticleSystem/MainModule::get_startSpeedMultiplier() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR float MainModule_get_startSpeedMultiplier_m22326AF745786C1748F6B165361CCC26917F214A (MainModule_t99C675667E0A363368324132DFA34B27FFEE6FC7 * __this, const RuntimeMethod* method); // System.Void UnityEngine.ParticleSystem/MainModule::set_startSpeedMultiplier(System.Single) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void MainModule_set_startSpeedMultiplier_m14E157EFF4BD78D8FDA701BE2BD0B398EF6F2453 (MainModule_t99C675667E0A363368324132DFA34B27FFEE6FC7 * __this, float ___value0, const RuntimeMethod* method); // System.Single UnityEngine.ParticleSystem/MainModule::get_startLifetimeMultiplier() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR float MainModule_get_startLifetimeMultiplier_m0D425E7689C0B99C5B9E8F8C4AE205600C1EA529 (MainModule_t99C675667E0A363368324132DFA34B27FFEE6FC7 * __this, const RuntimeMethod* method); // System.Void UnityEngine.ParticleSystem/MainModule::set_startLifetimeMultiplier(System.Single) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void MainModule_set_startLifetimeMultiplier_mCD094E55BD574ECF3A8F5D616A2287130B6EC67B (MainModule_t99C675667E0A363368324132DFA34B27FFEE6FC7 * __this, float ___value0, const RuntimeMethod* method); // System.Void UnityEngine.ParticleSystem::Clear() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void ParticleSystem_Clear_mE11D3D0E23B1C5AAFF1F432E278ED91F1D929FEE (ParticleSystem_t45DA87A3E83E738DA3FDAA5A48A133F1A1247C3D * __this, const RuntimeMethod* method); // System.Void UnityEngine.ParticleSystem::Play() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void ParticleSystem_Play_m5BC5E6B56FCF639CAD5DF41B51DC05A0B444212F (ParticleSystem_t45DA87A3E83E738DA3FDAA5A48A133F1A1247C3D * __this, const RuntimeMethod* method); // !!0 UnityEngine.Component::GetComponent() inline AudioSource_t5196F862B4E60F404613361C90D87FBDD041E93C * Component_GetComponent_TisAudioSource_t5196F862B4E60F404613361C90D87FBDD041E93C_m04C8E98F2393C77979C9D8F6DE1D98343EF025E8 (Component_t05064EF382ABCAF4B8C94F8A350EA85184C26621 * __this, const RuntimeMethod* method) { return (( AudioSource_t5196F862B4E60F404613361C90D87FBDD041E93C * (*) (Component_t05064EF382ABCAF4B8C94F8A350EA85184C26621 *, const RuntimeMethod*))Component_GetComponent_TisRuntimeObject_m129DEF8A66683189ED44B21496135824743EF617_gshared)(__this, method); } // System.Void UnityEngine.AudioSource::set_clip(UnityEngine.AudioClip) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void AudioSource_set_clip_mF574231E0B749E0167CAF9E4FCBA06BAA0F9ED9B (AudioSource_t5196F862B4E60F404613361C90D87FBDD041E93C * __this, AudioClip_tCC3C35F579203CE2601243585AB3D6953C3BA051 * ___value0, const RuntimeMethod* method); // System.Void UnityEngine.AudioSource::Play() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void AudioSource_Play_m0BA206481892AA4AF7DB2900A0B0805076516164 (AudioSource_t5196F862B4E60F404613361C90D87FBDD041E93C * __this, const RuntimeMethod* method); // !!0 UnityEngine.Component::GetComponent() inline ParticleSystem_t45DA87A3E83E738DA3FDAA5A48A133F1A1247C3D * Component_GetComponent_TisParticleSystem_t45DA87A3E83E738DA3FDAA5A48A133F1A1247C3D_mA6EBF435A59643B674086A2F309F6A4DCB263452 (Component_t05064EF382ABCAF4B8C94F8A350EA85184C26621 * __this, const RuntimeMethod* method) { return (( ParticleSystem_t45DA87A3E83E738DA3FDAA5A48A133F1A1247C3D * (*) (Component_t05064EF382ABCAF4B8C94F8A350EA85184C26621 *, const RuntimeMethod*))Component_GetComponent_TisRuntimeObject_m129DEF8A66683189ED44B21496135824743EF617_gshared)(__this, method); } // System.Int32 UnityEngine.ParticlePhysicsExtensions::GetCollisionEvents(UnityEngine.ParticleSystem,UnityEngine.GameObject,System.Collections.Generic.List`1) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR int32_t ParticlePhysicsExtensions_GetCollisionEvents_m11DDE18328B0E4B9766D1581DFCB0E67BCFD097C (ParticleSystem_t45DA87A3E83E738DA3FDAA5A48A133F1A1247C3D * ___ps0, GameObject_tBD1244AD56B4E59AAD76E5E7C9282EC5CE434F0F * ___go1, List_1_t2762C811E470D336E31761384C6E5382164DA4C7 * ___collisionEvents2, const RuntimeMethod* method); // !0 System.Collections.Generic.List`1::get_Item(System.Int32) inline ParticleCollisionEvent_t7F4D7D5ACF8521671549D9328D4E2DDE480D8D47 List_1_get_Item_m095B750642DEE222CA241EE9D2392CA6E200FA8D_inline (List_1_t2762C811E470D336E31761384C6E5382164DA4C7 * __this, int32_t ___index0, const RuntimeMethod* method) { return (( ParticleCollisionEvent_t7F4D7D5ACF8521671549D9328D4E2DDE480D8D47 (*) (List_1_t2762C811E470D336E31761384C6E5382164DA4C7 *, int32_t, const RuntimeMethod*))List_1_get_Item_m095B750642DEE222CA241EE9D2392CA6E200FA8D_gshared_inline)(__this, ___index0, method); } // UnityEngine.Component UnityEngine.ParticleCollisionEvent::get_colliderComponent() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR Component_t05064EF382ABCAF4B8C94F8A350EA85184C26621 * ParticleCollisionEvent_get_colliderComponent_mE4A94CAC6A2875588395DCB76FB7978A72796B82 (ParticleCollisionEvent_t7F4D7D5ACF8521671549D9328D4E2DDE480D8D47 * __this, const RuntimeMethod* method); // !!0 UnityEngine.Component::GetComponent() inline Rigidbody_tE0A58EE5A1F7DC908EFFB4F0D795AC9552A750A5 * Component_GetComponent_TisRigidbody_tE0A58EE5A1F7DC908EFFB4F0D795AC9552A750A5_m3F58A77E3F62D9C80D7B49BA04E3D4809264FD5C (Component_t05064EF382ABCAF4B8C94F8A350EA85184C26621 * __this, const RuntimeMethod* method) { return (( Rigidbody_tE0A58EE5A1F7DC908EFFB4F0D795AC9552A750A5 * (*) (Component_t05064EF382ABCAF4B8C94F8A350EA85184C26621 *, const RuntimeMethod*))Component_GetComponent_TisRuntimeObject_m129DEF8A66683189ED44B21496135824743EF617_gshared)(__this, method); } // UnityEngine.Vector3 UnityEngine.ParticleCollisionEvent::get_velocity() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 ParticleCollisionEvent_get_velocity_m60BCDF44F8F345C3534705CBA2BD5E69346021A3 (ParticleCollisionEvent_t7F4D7D5ACF8521671549D9328D4E2DDE480D8D47 * __this, const RuntimeMethod* method); // System.Void UnityEngine.Rigidbody::AddForce(UnityEngine.Vector3,UnityEngine.ForceMode) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Rigidbody_AddForce_mD64ACF772614FE36CFD8A477A07A407B35DF1A54 (Rigidbody_tE0A58EE5A1F7DC908EFFB4F0D795AC9552A750A5 * __this, Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 ___force0, int32_t ___mode1, const RuntimeMethod* method); // System.Void UnityEngine.GameObject::BroadcastMessage(System.String,UnityEngine.SendMessageOptions) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void GameObject_BroadcastMessage_mABB308EA1B7F641BFC60E091A75E5E053D23A8B5 (GameObject_tBD1244AD56B4E59AAD76E5E7C9282EC5CE434F0F * __this, String_t* ___methodName0, int32_t ___options1, const RuntimeMethod* method); // System.Void System.Collections.Generic.List`1::.ctor() inline void List_1__ctor_m377714278A7FAB4D7514D181355D61B01B3427B0 (List_1_t2762C811E470D336E31761384C6E5382164DA4C7 * __this, const RuntimeMethod* method) { (( void (*) (List_1_t2762C811E470D336E31761384C6E5382164DA4C7 *, const RuntimeMethod*))List_1__ctor_m377714278A7FAB4D7514D181355D61B01B3427B0_gshared)(__this, method); } // System.Void System.ThrowHelper::ThrowArgumentOutOfRangeException() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void ThrowHelper_ThrowArgumentOutOfRangeException_mBA2AF20A35144E0C43CD721A22EAC9FCA15D6550 (const RuntimeMethod* method); #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif #ifdef __clang__ #pragma clang diagnostic pop #endif #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Void UnityStandardAssets.Effects.AfterburnerPhysicsForce::OnEnable() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void AfterburnerPhysicsForce_OnEnable_m31ABCDDA8E500224F25244C9D3FE44CBDD45D7CE (AfterburnerPhysicsForce_t753048E9DC6DB55FA797EA775B76014E1E7F204B * __this, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (AfterburnerPhysicsForce_OnEnable_m31ABCDDA8E500224F25244C9D3FE44CBDD45D7CE_MetadataUsageId); s_Il2CppMethodInitialized = true; } { // m_Sphere = (GetComponent() as SphereCollider); Collider_t0FEEB36760860AD21B3B1F0509C365B393EC4BDF * L_0 = Component_GetComponent_TisCollider_t0FEEB36760860AD21B3B1F0509C365B393EC4BDF_m6B8E8E0E0AF6B08652B81B7950FC5AF63EAD40C6(__this, /*hidden argument*/Component_GetComponent_TisCollider_t0FEEB36760860AD21B3B1F0509C365B393EC4BDF_m6B8E8E0E0AF6B08652B81B7950FC5AF63EAD40C6_RuntimeMethod_var); __this->set_m_Sphere_9(((SphereCollider_tAC3E5E20B385DF1C0B17F3EA5C7214F71367706F *)IsInstClass((RuntimeObject*)L_0, SphereCollider_tAC3E5E20B385DF1C0B17F3EA5C7214F71367706F_il2cpp_TypeInfo_var))); // } return; } } // System.Void UnityStandardAssets.Effects.AfterburnerPhysicsForce::FixedUpdate() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void AfterburnerPhysicsForce_FixedUpdate_m90286B7CDABBED931E9D13E5D879E6EC41BF6E8A (AfterburnerPhysicsForce_t753048E9DC6DB55FA797EA775B76014E1E7F204B * __this, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (AfterburnerPhysicsForce_FixedUpdate_m90286B7CDABBED931E9D13E5D879E6EC41BF6E8A_MetadataUsageId); s_Il2CppMethodInitialized = true; } int32_t V_0 = 0; Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 V_1; memset((&V_1), 0, sizeof(V_1)); float V_2 = 0.0f; float V_3 = 0.0f; Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 V_4; memset((&V_4), 0, sizeof(V_4)); { // m_Cols = Physics.OverlapSphere(transform.position + m_Sphere.center, m_Sphere.radius); Transform_tBB9E78A2766C3C83599A8F66EDE7D1FCAFC66EDA * L_0 = Component_get_transform_m00F05BD782F920C301A7EBA480F3B7A904C07EC9(__this, /*hidden argument*/NULL); NullCheck(L_0); Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 L_1 = Transform_get_position_mF54C3A064F7C8E24F1C56EE128728B2E4485E294(L_0, /*hidden argument*/NULL); SphereCollider_tAC3E5E20B385DF1C0B17F3EA5C7214F71367706F * L_2 = __this->get_m_Sphere_9(); NullCheck(L_2); Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 L_3 = SphereCollider_get_center_mE7AD1AC46974FF23EEA621B872E2962E52A1DB00(L_2, /*hidden argument*/NULL); IL2CPP_RUNTIME_CLASS_INIT(Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720_il2cpp_TypeInfo_var); Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 L_4 = Vector3_op_Addition_m929F9C17E5D11B94D50B4AFF1D730B70CB59B50E(L_1, L_3, /*hidden argument*/NULL); SphereCollider_tAC3E5E20B385DF1C0B17F3EA5C7214F71367706F * L_5 = __this->get_m_Sphere_9(); NullCheck(L_5); float L_6 = SphereCollider_get_radius_m255804173C17314FD9538AE45C4A46D4882BC094(L_5, /*hidden argument*/NULL); ColliderU5BU5D_t70D1FDAE17E4359298B2BAA828048D1B7CFFE252* L_7 = Physics_OverlapSphere_m354A92672F7A6DE59EF1285D02D62247F46A5D84(L_4, L_6, /*hidden argument*/NULL); __this->set_m_Cols_8(L_7); // for (int n = 0; n < m_Cols.Length; ++n) V_0 = 0; goto IL_0168; } IL_0038: { // if (m_Cols[n].attachedRigidbody != null) ColliderU5BU5D_t70D1FDAE17E4359298B2BAA828048D1B7CFFE252* L_8 = __this->get_m_Cols_8(); int32_t L_9 = V_0; NullCheck(L_8); int32_t L_10 = L_9; Collider_t0FEEB36760860AD21B3B1F0509C365B393EC4BDF * L_11 = (L_8)->GetAt(static_cast(L_10)); NullCheck(L_11); Rigidbody_tE0A58EE5A1F7DC908EFFB4F0D795AC9552A750A5 * L_12 = Collider_get_attachedRigidbody_m9E3C688EAE2F6A76C9AC14968D96769D9A71B1E8(L_11, /*hidden argument*/NULL); IL2CPP_RUNTIME_CLASS_INIT(Object_tAE11E5E46CD5C37C9F3E8950C00CD8B45666A2D0_il2cpp_TypeInfo_var); bool L_13 = Object_op_Inequality_m31EF58E217E8F4BDD3E409DEF79E1AEE95874FC1(L_12, (Object_tAE11E5E46CD5C37C9F3E8950C00CD8B45666A2D0 *)NULL, /*hidden argument*/NULL); if (!L_13) { goto IL_0164; } } { // Vector3 localPos = transform.InverseTransformPoint(m_Cols[n].transform.position); Transform_tBB9E78A2766C3C83599A8F66EDE7D1FCAFC66EDA * L_14 = Component_get_transform_m00F05BD782F920C301A7EBA480F3B7A904C07EC9(__this, /*hidden argument*/NULL); ColliderU5BU5D_t70D1FDAE17E4359298B2BAA828048D1B7CFFE252* L_15 = __this->get_m_Cols_8(); int32_t L_16 = V_0; NullCheck(L_15); int32_t L_17 = L_16; Collider_t0FEEB36760860AD21B3B1F0509C365B393EC4BDF * L_18 = (L_15)->GetAt(static_cast(L_17)); NullCheck(L_18); Transform_tBB9E78A2766C3C83599A8F66EDE7D1FCAFC66EDA * L_19 = Component_get_transform_m00F05BD782F920C301A7EBA480F3B7A904C07EC9(L_18, /*hidden argument*/NULL); NullCheck(L_19); Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 L_20 = Transform_get_position_mF54C3A064F7C8E24F1C56EE128728B2E4485E294(L_19, /*hidden argument*/NULL); NullCheck(L_14); Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 L_21 = Transform_InverseTransformPoint_mB6E3145F20B531B4A781C194BAC43A8255C96C47(L_14, L_20, /*hidden argument*/NULL); V_1 = L_21; // localPos = Vector3.MoveTowards(localPos, new Vector3(0, 0, localPos.z), effectWidth*0.5f); Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 L_22 = V_1; Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 L_23 = V_1; float L_24 = L_23.get_z_4(); Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 L_25; memset((&L_25), 0, sizeof(L_25)); Vector3__ctor_m08F61F548AA5836D8789843ACB4A81E4963D2EE1((&L_25), (0.0f), (0.0f), L_24, /*hidden argument*/NULL); float L_26 = __this->get_effectWidth_5(); IL2CPP_RUNTIME_CLASS_INIT(Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720_il2cpp_TypeInfo_var); Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 L_27 = Vector3_MoveTowards_mA288BB5AA73DDA9CA76EDC11F339BAFDA1E4FF45(L_22, L_25, ((float)il2cpp_codegen_multiply((float)L_26, (float)(0.5f))), /*hidden argument*/NULL); V_1 = L_27; // float angle = Mathf.Abs(Mathf.Atan2(localPos.x, localPos.z)*Mathf.Rad2Deg); Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 L_28 = V_1; float L_29 = L_28.get_x_2(); Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 L_30 = V_1; float L_31 = L_30.get_z_4(); IL2CPP_RUNTIME_CLASS_INIT(Mathf_tFBDE6467D269BFE410605C7D806FD9991D4A89CB_il2cpp_TypeInfo_var); float L_32 = atan2f(L_29, L_31); float L_33 = fabsf(((float)il2cpp_codegen_multiply((float)L_32, (float)(57.29578f)))); V_2 = L_33; // float falloff = Mathf.InverseLerp(effectDistance, 0, localPos.magnitude); float L_34 = __this->get_effectDistance_6(); float L_35 = Vector3_get_magnitude_m9A750659B60C5FE0C30438A7F9681775D5DB1274((Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 *)(&V_1), /*hidden argument*/NULL); float L_36 = Mathf_InverseLerp_m7054CDF25056E9B27D2467F91C95D628508F1F31(L_34, (0.0f), L_35, /*hidden argument*/NULL); V_3 = L_36; // falloff *= Mathf.InverseLerp(effectAngle, 0, angle); float L_37 = V_3; float L_38 = __this->get_effectAngle_4(); float L_39 = V_2; float L_40 = Mathf_InverseLerp_m7054CDF25056E9B27D2467F91C95D628508F1F31(L_38, (0.0f), L_39, /*hidden argument*/NULL); V_3 = ((float)il2cpp_codegen_multiply((float)L_37, (float)L_40)); // Vector3 delta = m_Cols[n].transform.position - transform.position; ColliderU5BU5D_t70D1FDAE17E4359298B2BAA828048D1B7CFFE252* L_41 = __this->get_m_Cols_8(); int32_t L_42 = V_0; NullCheck(L_41); int32_t L_43 = L_42; Collider_t0FEEB36760860AD21B3B1F0509C365B393EC4BDF * L_44 = (L_41)->GetAt(static_cast(L_43)); NullCheck(L_44); Transform_tBB9E78A2766C3C83599A8F66EDE7D1FCAFC66EDA * L_45 = Component_get_transform_m00F05BD782F920C301A7EBA480F3B7A904C07EC9(L_44, /*hidden argument*/NULL); NullCheck(L_45); Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 L_46 = Transform_get_position_mF54C3A064F7C8E24F1C56EE128728B2E4485E294(L_45, /*hidden argument*/NULL); Transform_tBB9E78A2766C3C83599A8F66EDE7D1FCAFC66EDA * L_47 = Component_get_transform_m00F05BD782F920C301A7EBA480F3B7A904C07EC9(__this, /*hidden argument*/NULL); NullCheck(L_47); Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 L_48 = Transform_get_position_mF54C3A064F7C8E24F1C56EE128728B2E4485E294(L_47, /*hidden argument*/NULL); Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 L_49 = Vector3_op_Subtraction_mF9846B723A5034F8B9F5F5DCB78E3D67649143D3(L_46, L_48, /*hidden argument*/NULL); V_4 = L_49; // m_Cols[n].attachedRigidbody.AddForceAtPosition(delta.normalized*force*falloff, // Vector3.Lerp(m_Cols[n].transform.position, // transform.TransformPoint(0, 0, localPos.z), // 0.1f)); ColliderU5BU5D_t70D1FDAE17E4359298B2BAA828048D1B7CFFE252* L_50 = __this->get_m_Cols_8(); int32_t L_51 = V_0; NullCheck(L_50); int32_t L_52 = L_51; Collider_t0FEEB36760860AD21B3B1F0509C365B393EC4BDF * L_53 = (L_50)->GetAt(static_cast(L_52)); NullCheck(L_53); Rigidbody_tE0A58EE5A1F7DC908EFFB4F0D795AC9552A750A5 * L_54 = Collider_get_attachedRigidbody_m9E3C688EAE2F6A76C9AC14968D96769D9A71B1E8(L_53, /*hidden argument*/NULL); Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 L_55 = Vector3_get_normalized_mE20796F1D2D36244FACD4D14DADB245BE579849B((Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 *)(&V_4), /*hidden argument*/NULL); float L_56 = __this->get_force_7(); Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 L_57 = Vector3_op_Multiply_m1C5F07723615156ACF035D88A1280A9E8F35A04E(L_55, L_56, /*hidden argument*/NULL); float L_58 = V_3; Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 L_59 = Vector3_op_Multiply_m1C5F07723615156ACF035D88A1280A9E8F35A04E(L_57, L_58, /*hidden argument*/NULL); ColliderU5BU5D_t70D1FDAE17E4359298B2BAA828048D1B7CFFE252* L_60 = __this->get_m_Cols_8(); int32_t L_61 = V_0; NullCheck(L_60); int32_t L_62 = L_61; Collider_t0FEEB36760860AD21B3B1F0509C365B393EC4BDF * L_63 = (L_60)->GetAt(static_cast(L_62)); NullCheck(L_63); Transform_tBB9E78A2766C3C83599A8F66EDE7D1FCAFC66EDA * L_64 = Component_get_transform_m00F05BD782F920C301A7EBA480F3B7A904C07EC9(L_63, /*hidden argument*/NULL); NullCheck(L_64); Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 L_65 = Transform_get_position_mF54C3A064F7C8E24F1C56EE128728B2E4485E294(L_64, /*hidden argument*/NULL); Transform_tBB9E78A2766C3C83599A8F66EDE7D1FCAFC66EDA * L_66 = Component_get_transform_m00F05BD782F920C301A7EBA480F3B7A904C07EC9(__this, /*hidden argument*/NULL); Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 L_67 = V_1; float L_68 = L_67.get_z_4(); NullCheck(L_66); Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 L_69 = Transform_TransformPoint_m363B3A9E2C3A9A52F4B872CF34F476D87CCC8CEC(L_66, (0.0f), (0.0f), L_68, /*hidden argument*/NULL); Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 L_70 = Vector3_Lerp_m5BA75496B803820CC64079383956D73C6FD4A8A1(L_65, L_69, (0.1f), /*hidden argument*/NULL); NullCheck(L_54); Rigidbody_AddForceAtPosition_m3A5DCFC3E79923C9D8E32A54BC4AAA1E48EEAD6C(L_54, L_59, L_70, /*hidden argument*/NULL); } IL_0164: { // for (int n = 0; n < m_Cols.Length; ++n) int32_t L_71 = V_0; V_0 = ((int32_t)il2cpp_codegen_add((int32_t)L_71, (int32_t)1)); } IL_0168: { // for (int n = 0; n < m_Cols.Length; ++n) int32_t L_72 = V_0; ColliderU5BU5D_t70D1FDAE17E4359298B2BAA828048D1B7CFFE252* L_73 = __this->get_m_Cols_8(); NullCheck(L_73); if ((((int32_t)L_72) < ((int32_t)(((int32_t)((int32_t)(((RuntimeArray*)L_73)->max_length))))))) { goto IL_0038; } } { // } return; } } // System.Void UnityStandardAssets.Effects.AfterburnerPhysicsForce::OnDrawGizmosSelected() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void AfterburnerPhysicsForce_OnDrawGizmosSelected_m8E75C894A4544C40EB1FD3DA8883E3358BAF8AA3 (AfterburnerPhysicsForce_t753048E9DC6DB55FA797EA775B76014E1E7F204B * __this, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (AfterburnerPhysicsForce_OnDrawGizmosSelected_m8E75C894A4544C40EB1FD3DA8883E3358BAF8AA3_MetadataUsageId); s_Il2CppMethodInitialized = true; } Vector3U5BU5D_tB9EC3346CC4A0EA5447D968E84A9AC1F6F372C28* V_0 = NULL; Vector3U5BU5D_tB9EC3346CC4A0EA5447D968E84A9AC1F6F372C28* V_1 = NULL; int32_t V_2 = 0; Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 V_3; memset((&V_3), 0, sizeof(V_3)); { // if(m_Sphere == null) SphereCollider_tAC3E5E20B385DF1C0B17F3EA5C7214F71367706F * L_0 = __this->get_m_Sphere_9(); IL2CPP_RUNTIME_CLASS_INIT(Object_tAE11E5E46CD5C37C9F3E8950C00CD8B45666A2D0_il2cpp_TypeInfo_var); bool L_1 = Object_op_Equality_mBC2401774F3BE33E8CF6F0A8148E66C95D6CFF1C(L_0, (Object_tAE11E5E46CD5C37C9F3E8950C00CD8B45666A2D0 *)NULL, /*hidden argument*/NULL); if (!L_1) { goto IL_001f; } } { // m_Sphere = (GetComponent() as SphereCollider); Collider_t0FEEB36760860AD21B3B1F0509C365B393EC4BDF * L_2 = Component_GetComponent_TisCollider_t0FEEB36760860AD21B3B1F0509C365B393EC4BDF_m6B8E8E0E0AF6B08652B81B7950FC5AF63EAD40C6(__this, /*hidden argument*/Component_GetComponent_TisCollider_t0FEEB36760860AD21B3B1F0509C365B393EC4BDF_m6B8E8E0E0AF6B08652B81B7950FC5AF63EAD40C6_RuntimeMethod_var); __this->set_m_Sphere_9(((SphereCollider_tAC3E5E20B385DF1C0B17F3EA5C7214F71367706F *)IsInstClass((RuntimeObject*)L_2, SphereCollider_tAC3E5E20B385DF1C0B17F3EA5C7214F71367706F_il2cpp_TypeInfo_var))); } IL_001f: { // m_Sphere.radius = effectDistance*.5f; SphereCollider_tAC3E5E20B385DF1C0B17F3EA5C7214F71367706F * L_3 = __this->get_m_Sphere_9(); float L_4 = __this->get_effectDistance_6(); NullCheck(L_3); SphereCollider_set_radius_m3161573A2D89F495F4B79E16C52B905C0F9AD699(L_3, ((float)il2cpp_codegen_multiply((float)L_4, (float)(0.5f))), /*hidden argument*/NULL); // m_Sphere.center = new Vector3(0, 0, effectDistance*.5f); SphereCollider_tAC3E5E20B385DF1C0B17F3EA5C7214F71367706F * L_5 = __this->get_m_Sphere_9(); float L_6 = __this->get_effectDistance_6(); Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 L_7; memset((&L_7), 0, sizeof(L_7)); Vector3__ctor_m08F61F548AA5836D8789843ACB4A81E4963D2EE1((&L_7), (0.0f), (0.0f), ((float)il2cpp_codegen_multiply((float)L_6, (float)(0.5f))), /*hidden argument*/NULL); NullCheck(L_5); SphereCollider_set_center_m325070F5252B4A2EA567B653CAE3285F101FA3EE(L_5, L_7, /*hidden argument*/NULL); // var directions = new Vector3[] {Vector3.up, -Vector3.up, Vector3.right, -Vector3.right}; Vector3U5BU5D_tB9EC3346CC4A0EA5447D968E84A9AC1F6F372C28* L_8 = (Vector3U5BU5D_tB9EC3346CC4A0EA5447D968E84A9AC1F6F372C28*)(Vector3U5BU5D_tB9EC3346CC4A0EA5447D968E84A9AC1F6F372C28*)SZArrayNew(Vector3U5BU5D_tB9EC3346CC4A0EA5447D968E84A9AC1F6F372C28_il2cpp_TypeInfo_var, (uint32_t)4); Vector3U5BU5D_tB9EC3346CC4A0EA5447D968E84A9AC1F6F372C28* L_9 = L_8; IL2CPP_RUNTIME_CLASS_INIT(Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720_il2cpp_TypeInfo_var); Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 L_10 = Vector3_get_up_m6309EBC4E42D6D0B3D28056BD23D0331275306F7(/*hidden argument*/NULL); NullCheck(L_9); (L_9)->SetAt(static_cast(0), (Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 )L_10); Vector3U5BU5D_tB9EC3346CC4A0EA5447D968E84A9AC1F6F372C28* L_11 = L_9; Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 L_12 = Vector3_get_up_m6309EBC4E42D6D0B3D28056BD23D0331275306F7(/*hidden argument*/NULL); Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 L_13 = Vector3_op_UnaryNegation_m2AFBBF22801F9BCA5A4EBE642A29F433FE1339C2(L_12, /*hidden argument*/NULL); NullCheck(L_11); (L_11)->SetAt(static_cast(1), (Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 )L_13); Vector3U5BU5D_tB9EC3346CC4A0EA5447D968E84A9AC1F6F372C28* L_14 = L_11; Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 L_15 = Vector3_get_right_m6DD9559CA0C75BBA42D9140021C4C2A9AAA9B3F5(/*hidden argument*/NULL); NullCheck(L_14); (L_14)->SetAt(static_cast(2), (Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 )L_15); Vector3U5BU5D_tB9EC3346CC4A0EA5447D968E84A9AC1F6F372C28* L_16 = L_14; Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 L_17 = Vector3_get_right_m6DD9559CA0C75BBA42D9140021C4C2A9AAA9B3F5(/*hidden argument*/NULL); Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 L_18 = Vector3_op_UnaryNegation_m2AFBBF22801F9BCA5A4EBE642A29F433FE1339C2(L_17, /*hidden argument*/NULL); NullCheck(L_16); (L_16)->SetAt(static_cast(3), (Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 )L_18); V_0 = L_16; // var perpDirections = new Vector3[] {-Vector3.right, Vector3.right, Vector3.up, -Vector3.up}; Vector3U5BU5D_tB9EC3346CC4A0EA5447D968E84A9AC1F6F372C28* L_19 = (Vector3U5BU5D_tB9EC3346CC4A0EA5447D968E84A9AC1F6F372C28*)(Vector3U5BU5D_tB9EC3346CC4A0EA5447D968E84A9AC1F6F372C28*)SZArrayNew(Vector3U5BU5D_tB9EC3346CC4A0EA5447D968E84A9AC1F6F372C28_il2cpp_TypeInfo_var, (uint32_t)4); Vector3U5BU5D_tB9EC3346CC4A0EA5447D968E84A9AC1F6F372C28* L_20 = L_19; Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 L_21 = Vector3_get_right_m6DD9559CA0C75BBA42D9140021C4C2A9AAA9B3F5(/*hidden argument*/NULL); Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 L_22 = Vector3_op_UnaryNegation_m2AFBBF22801F9BCA5A4EBE642A29F433FE1339C2(L_21, /*hidden argument*/NULL); NullCheck(L_20); (L_20)->SetAt(static_cast(0), (Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 )L_22); Vector3U5BU5D_tB9EC3346CC4A0EA5447D968E84A9AC1F6F372C28* L_23 = L_20; Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 L_24 = Vector3_get_right_m6DD9559CA0C75BBA42D9140021C4C2A9AAA9B3F5(/*hidden argument*/NULL); NullCheck(L_23); (L_23)->SetAt(static_cast(1), (Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 )L_24); Vector3U5BU5D_tB9EC3346CC4A0EA5447D968E84A9AC1F6F372C28* L_25 = L_23; Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 L_26 = Vector3_get_up_m6309EBC4E42D6D0B3D28056BD23D0331275306F7(/*hidden argument*/NULL); NullCheck(L_25); (L_25)->SetAt(static_cast(2), (Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 )L_26); Vector3U5BU5D_tB9EC3346CC4A0EA5447D968E84A9AC1F6F372C28* L_27 = L_25; Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 L_28 = Vector3_get_up_m6309EBC4E42D6D0B3D28056BD23D0331275306F7(/*hidden argument*/NULL); Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 L_29 = Vector3_op_UnaryNegation_m2AFBBF22801F9BCA5A4EBE642A29F433FE1339C2(L_28, /*hidden argument*/NULL); NullCheck(L_27); (L_27)->SetAt(static_cast(3), (Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 )L_29); V_1 = L_27; // Gizmos.color = new Color(0, 1, 0, 0.5f); Color_t119BCA590009762C7223FDD3AF9706653AC84ED2 L_30; memset((&L_30), 0, sizeof(L_30)); Color__ctor_m20DF490CEB364C4FC36D7EE392640DF5B7420D7C((&L_30), (0.0f), (1.0f), (0.0f), (0.5f), /*hidden argument*/NULL); Gizmos_set_color_mFA6C199DF05FF557AEF662222CA60EC25DF54F28(L_30, /*hidden argument*/NULL); // for (int n = 0; n < 4; ++n) V_2 = 0; goto IL_0191; } IL_0103: { // Vector3 origin = transform.position + transform.rotation*directions[n]*effectWidth*0.5f; Transform_tBB9E78A2766C3C83599A8F66EDE7D1FCAFC66EDA * L_31 = Component_get_transform_m00F05BD782F920C301A7EBA480F3B7A904C07EC9(__this, /*hidden argument*/NULL); NullCheck(L_31); Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 L_32 = Transform_get_position_mF54C3A064F7C8E24F1C56EE128728B2E4485E294(L_31, /*hidden argument*/NULL); Transform_tBB9E78A2766C3C83599A8F66EDE7D1FCAFC66EDA * L_33 = Component_get_transform_m00F05BD782F920C301A7EBA480F3B7A904C07EC9(__this, /*hidden argument*/NULL); NullCheck(L_33); Quaternion_t319F3319A7D43FFA5D819AD6C0A98851F0095357 L_34 = Transform_get_rotation_m3AB90A67403249AECCA5E02BC70FCE8C90FE9FB9(L_33, /*hidden argument*/NULL); Vector3U5BU5D_tB9EC3346CC4A0EA5447D968E84A9AC1F6F372C28* L_35 = V_0; int32_t L_36 = V_2; NullCheck(L_35); int32_t L_37 = L_36; Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 L_38 = (L_35)->GetAt(static_cast(L_37)); IL2CPP_RUNTIME_CLASS_INIT(Quaternion_t319F3319A7D43FFA5D819AD6C0A98851F0095357_il2cpp_TypeInfo_var); Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 L_39 = Quaternion_op_Multiply_mD5999DE317D808808B72E58E7A978C4C0995879C(L_34, L_38, /*hidden argument*/NULL); float L_40 = __this->get_effectWidth_5(); IL2CPP_RUNTIME_CLASS_INIT(Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720_il2cpp_TypeInfo_var); Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 L_41 = Vector3_op_Multiply_m1C5F07723615156ACF035D88A1280A9E8F35A04E(L_39, L_40, /*hidden argument*/NULL); Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 L_42 = Vector3_op_Multiply_m1C5F07723615156ACF035D88A1280A9E8F35A04E(L_41, (0.5f), /*hidden argument*/NULL); Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 L_43 = Vector3_op_Addition_m929F9C17E5D11B94D50B4AFF1D730B70CB59B50E(L_32, L_42, /*hidden argument*/NULL); // Vector3 direction = // transform.TransformDirection(Quaternion.AngleAxis(effectAngle, perpDirections[n])*Vector3.forward); Transform_tBB9E78A2766C3C83599A8F66EDE7D1FCAFC66EDA * L_44 = Component_get_transform_m00F05BD782F920C301A7EBA480F3B7A904C07EC9(__this, /*hidden argument*/NULL); float L_45 = __this->get_effectAngle_4(); Vector3U5BU5D_tB9EC3346CC4A0EA5447D968E84A9AC1F6F372C28* L_46 = V_1; int32_t L_47 = V_2; NullCheck(L_46); int32_t L_48 = L_47; Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 L_49 = (L_46)->GetAt(static_cast(L_48)); Quaternion_t319F3319A7D43FFA5D819AD6C0A98851F0095357 L_50 = Quaternion_AngleAxis_m07DACF59F0403451DABB9BC991C53EE3301E88B0(L_45, L_49, /*hidden argument*/NULL); Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 L_51 = Vector3_get_forward_m3E2E192B3302130098738C308FA1EE1439449D0D(/*hidden argument*/NULL); Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 L_52 = Quaternion_op_Multiply_mD5999DE317D808808B72E58E7A978C4C0995879C(L_50, L_51, /*hidden argument*/NULL); NullCheck(L_44); Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 L_53 = Transform_TransformDirection_m85FC1D7E1322E94F65DA59AEF3B1166850B183EF(L_44, L_52, /*hidden argument*/NULL); V_3 = L_53; // Gizmos.DrawLine(origin, origin + direction*m_Sphere.radius*2); Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 L_54 = L_43; Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 L_55 = V_3; SphereCollider_tAC3E5E20B385DF1C0B17F3EA5C7214F71367706F * L_56 = __this->get_m_Sphere_9(); NullCheck(L_56); float L_57 = SphereCollider_get_radius_m255804173C17314FD9538AE45C4A46D4882BC094(L_56, /*hidden argument*/NULL); Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 L_58 = Vector3_op_Multiply_m1C5F07723615156ACF035D88A1280A9E8F35A04E(L_55, L_57, /*hidden argument*/NULL); Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 L_59 = Vector3_op_Multiply_m1C5F07723615156ACF035D88A1280A9E8F35A04E(L_58, (2.0f), /*hidden argument*/NULL); Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 L_60 = Vector3_op_Addition_m929F9C17E5D11B94D50B4AFF1D730B70CB59B50E(L_54, L_59, /*hidden argument*/NULL); Gizmos_DrawLine_m9515D59D2536571F4906A3C54E613A3986DFD892(L_54, L_60, /*hidden argument*/NULL); // for (int n = 0; n < 4; ++n) int32_t L_61 = V_2; V_2 = ((int32_t)il2cpp_codegen_add((int32_t)L_61, (int32_t)1)); } IL_0191: { // for (int n = 0; n < 4; ++n) int32_t L_62 = V_2; if ((((int32_t)L_62) < ((int32_t)4))) { goto IL_0103; } } { // } return; } } // System.Void UnityStandardAssets.Effects.AfterburnerPhysicsForce::.ctor() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void AfterburnerPhysicsForce__ctor_mE4F415134C355B0C418241BA9F4BE2DAB65BF1A0 (AfterburnerPhysicsForce_t753048E9DC6DB55FA797EA775B76014E1E7F204B * __this, const RuntimeMethod* method) { { // public float effectAngle = 15; __this->set_effectAngle_4((15.0f)); // public float effectWidth = 1; __this->set_effectWidth_5((1.0f)); // public float effectDistance = 10; __this->set_effectDistance_6((10.0f)); // public float force = 10; __this->set_force_7((10.0f)); MonoBehaviour__ctor_mEAEC84B222C60319D593E456D769B3311DFCEF97(__this, /*hidden argument*/NULL); return; } } #ifdef __clang__ #pragma clang diagnostic pop #endif #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Collections.IEnumerator UnityStandardAssets.Effects.ExplosionFireAndDebris::Start() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR RuntimeObject* ExplosionFireAndDebris_Start_m85654B2EA9348AE14094A4CDCA1ECD714E4CBC22 (ExplosionFireAndDebris_tACCFCC1184BB9A8C3A0B39D99FFC831E76F9EECB * __this, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (ExplosionFireAndDebris_Start_m85654B2EA9348AE14094A4CDCA1ECD714E4CBC22_MetadataUsageId); s_Il2CppMethodInitialized = true; } { U3CStartU3Ed__4_t945A707CD8C01DA1C37AE2DD9D0A904C80F58139 * L_0 = (U3CStartU3Ed__4_t945A707CD8C01DA1C37AE2DD9D0A904C80F58139 *)il2cpp_codegen_object_new(U3CStartU3Ed__4_t945A707CD8C01DA1C37AE2DD9D0A904C80F58139_il2cpp_TypeInfo_var); U3CStartU3Ed__4__ctor_mBDD727783F54367BFE2CED7C675B839450955B8C(L_0, 0, /*hidden argument*/NULL); U3CStartU3Ed__4_t945A707CD8C01DA1C37AE2DD9D0A904C80F58139 * L_1 = L_0; NullCheck(L_1); L_1->set_U3CU3E4__this_2(__this); return L_1; } } // System.Void UnityStandardAssets.Effects.ExplosionFireAndDebris::AddFire(UnityEngine.Transform,UnityEngine.Vector3,UnityEngine.Vector3) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void ExplosionFireAndDebris_AddFire_m781F3E400896C4F2E2B4A24FAEFE52D01ED26C0B (ExplosionFireAndDebris_tACCFCC1184BB9A8C3A0B39D99FFC831E76F9EECB * __this, Transform_tBB9E78A2766C3C83599A8F66EDE7D1FCAFC66EDA * ___t0, Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 ___pos1, Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 ___normal2, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (ExplosionFireAndDebris_AddFire_m781F3E400896C4F2E2B4A24FAEFE52D01ED26C0B_MetadataUsageId); s_Il2CppMethodInitialized = true; } { // pos += normal*0.5f; Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 L_0 = ___pos1; Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 L_1 = ___normal2; IL2CPP_RUNTIME_CLASS_INIT(Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720_il2cpp_TypeInfo_var); Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 L_2 = Vector3_op_Multiply_m1C5F07723615156ACF035D88A1280A9E8F35A04E(L_1, (0.5f), /*hidden argument*/NULL); Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 L_3 = Vector3_op_Addition_m929F9C17E5D11B94D50B4AFF1D730B70CB59B50E(L_0, L_2, /*hidden argument*/NULL); ___pos1 = L_3; // Transform fire = (Transform) Instantiate(firePrefab, pos, Quaternion.identity); Transform_tBB9E78A2766C3C83599A8F66EDE7D1FCAFC66EDA * L_4 = __this->get_firePrefab_5(); Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 L_5 = ___pos1; IL2CPP_RUNTIME_CLASS_INIT(Quaternion_t319F3319A7D43FFA5D819AD6C0A98851F0095357_il2cpp_TypeInfo_var); Quaternion_t319F3319A7D43FFA5D819AD6C0A98851F0095357 L_6 = Quaternion_get_identity_m548B37D80F2DEE60E41D1F09BF6889B557BE1A64(/*hidden argument*/NULL); IL2CPP_RUNTIME_CLASS_INIT(Object_tAE11E5E46CD5C37C9F3E8950C00CD8B45666A2D0_il2cpp_TypeInfo_var); Transform_tBB9E78A2766C3C83599A8F66EDE7D1FCAFC66EDA * L_7 = Object_Instantiate_TisTransform_tBB9E78A2766C3C83599A8F66EDE7D1FCAFC66EDA_m8BCC51A95F42E99B9033022D8BF0EABA04FED8F0(L_4, L_5, L_6, /*hidden argument*/Object_Instantiate_TisTransform_tBB9E78A2766C3C83599A8F66EDE7D1FCAFC66EDA_m8BCC51A95F42E99B9033022D8BF0EABA04FED8F0_RuntimeMethod_var); // fire.parent = t; Transform_tBB9E78A2766C3C83599A8F66EDE7D1FCAFC66EDA * L_8 = ___t0; NullCheck(L_7); Transform_set_parent_m65B8E4660B2C554069C57A957D9E55FECA7AA73E(L_7, L_8, /*hidden argument*/NULL); // } return; } } // System.Void UnityStandardAssets.Effects.ExplosionFireAndDebris::.ctor() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void ExplosionFireAndDebris__ctor_m6E9B3DD674A9E1DF3B85ECF3E618F7F29B5EB97E (ExplosionFireAndDebris_tACCFCC1184BB9A8C3A0B39D99FFC831E76F9EECB * __this, const RuntimeMethod* method) { { MonoBehaviour__ctor_mEAEC84B222C60319D593E456D769B3311DFCEF97(__this, /*hidden argument*/NULL); return; } } #ifdef __clang__ #pragma clang diagnostic pop #endif #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Void UnityStandardAssets.Effects.ExplosionFireAndDebris/d__4::.ctor(System.Int32) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void U3CStartU3Ed__4__ctor_mBDD727783F54367BFE2CED7C675B839450955B8C (U3CStartU3Ed__4_t945A707CD8C01DA1C37AE2DD9D0A904C80F58139 * __this, int32_t ___U3CU3E1__state0, const RuntimeMethod* method) { { Object__ctor_m925ECA5E85CA100E3FB86A4F9E15C120E9A184C0(__this, /*hidden argument*/NULL); int32_t L_0 = ___U3CU3E1__state0; __this->set_U3CU3E1__state_0(L_0); return; } } // System.Void UnityStandardAssets.Effects.ExplosionFireAndDebris/d__4::System.IDisposable.Dispose() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void U3CStartU3Ed__4_System_IDisposable_Dispose_m6E7E396A3AE4E0720223F5D8DCB4E8A55ED7BF01 (U3CStartU3Ed__4_t945A707CD8C01DA1C37AE2DD9D0A904C80F58139 * __this, const RuntimeMethod* method) { { return; } } // System.Boolean UnityStandardAssets.Effects.ExplosionFireAndDebris/d__4::MoveNext() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR bool U3CStartU3Ed__4_MoveNext_m4846C74D5F4A4FF39164BCFD48198D976AA0F953 (U3CStartU3Ed__4_t945A707CD8C01DA1C37AE2DD9D0A904C80F58139 * __this, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (U3CStartU3Ed__4_MoveNext_m4846C74D5F4A4FF39164BCFD48198D976AA0F953_MetadataUsageId); s_Il2CppMethodInitialized = true; } int32_t V_0 = 0; ExplosionFireAndDebris_tACCFCC1184BB9A8C3A0B39D99FFC831E76F9EECB * V_1 = NULL; float V_2 = 0.0f; float V_3 = 0.0f; int32_t V_4 = 0; Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 V_5; memset((&V_5), 0, sizeof(V_5)); Quaternion_t319F3319A7D43FFA5D819AD6C0A98851F0095357 V_6; memset((&V_6), 0, sizeof(V_6)); ColliderU5BU5D_t70D1FDAE17E4359298B2BAA828048D1B7CFFE252* V_7 = NULL; int32_t V_8 = 0; Collider_t0FEEB36760860AD21B3B1F0509C365B393EC4BDF * V_9 = NULL; RaycastHit_t19695F18F9265FE5425062BBA6A4D330480538C3 V_10; memset((&V_10), 0, sizeof(V_10)); Ray_tE2163D4CB3E6B267E29F8ABE41684490E4A614B2 V_11; memset((&V_11), 0, sizeof(V_11)); RaycastHit_t19695F18F9265FE5425062BBA6A4D330480538C3 V_12; memset((&V_12), 0, sizeof(V_12)); { int32_t L_0 = __this->get_U3CU3E1__state_0(); V_0 = L_0; ExplosionFireAndDebris_tACCFCC1184BB9A8C3A0B39D99FFC831E76F9EECB * L_1 = __this->get_U3CU3E4__this_2(); V_1 = L_1; int32_t L_2 = V_0; if (!L_2) { goto IL_001a; } } { int32_t L_3 = V_0; if ((((int32_t)L_3) == ((int32_t)1))) { goto IL_00b2; } } { return (bool)0; } IL_001a: { __this->set_U3CU3E1__state_0((-1)); // float multiplier = GetComponent().multiplier; ExplosionFireAndDebris_tACCFCC1184BB9A8C3A0B39D99FFC831E76F9EECB * L_4 = V_1; NullCheck(L_4); ParticleSystemMultiplier_t8EBFEF83EBA48DD7F6517ABFFBE2CD051CB2C748 * L_5 = Component_GetComponent_TisParticleSystemMultiplier_t8EBFEF83EBA48DD7F6517ABFFBE2CD051CB2C748_m77EDAEF51740299BC986B0DA36AB7282BB8DDD45(L_4, /*hidden argument*/Component_GetComponent_TisParticleSystemMultiplier_t8EBFEF83EBA48DD7F6517ABFFBE2CD051CB2C748_m77EDAEF51740299BC986B0DA36AB7282BB8DDD45_RuntimeMethod_var); NullCheck(L_5); float L_6 = L_5->get_multiplier_4(); __this->set_U3CmultiplierU3E5__2_3(L_6); // for (int n = 0; n < numDebrisPieces*multiplier; ++n) V_4 = 0; goto IL_008f; } IL_0037: { // var prefab = debrisPrefabs[Random.Range(0, debrisPrefabs.Length)]; ExplosionFireAndDebris_tACCFCC1184BB9A8C3A0B39D99FFC831E76F9EECB * L_7 = V_1; NullCheck(L_7); TransformU5BU5D_t4F5A1132877D8BA66ABC0A9A7FADA4E0237A7804* L_8 = L_7->get_debrisPrefabs_4(); ExplosionFireAndDebris_tACCFCC1184BB9A8C3A0B39D99FFC831E76F9EECB * L_9 = V_1; NullCheck(L_9); TransformU5BU5D_t4F5A1132877D8BA66ABC0A9A7FADA4E0237A7804* L_10 = L_9->get_debrisPrefabs_4(); NullCheck(L_10); int32_t L_11 = Random_Range_mD0C8F37FF3CAB1D87AAA6C45130BD59626BD6780(0, (((int32_t)((int32_t)(((RuntimeArray*)L_10)->max_length)))), /*hidden argument*/NULL); NullCheck(L_8); int32_t L_12 = L_11; Transform_tBB9E78A2766C3C83599A8F66EDE7D1FCAFC66EDA * L_13 = (L_8)->GetAt(static_cast(L_12)); // Vector3 pos = transform.position + Random.insideUnitSphere*3*multiplier; ExplosionFireAndDebris_tACCFCC1184BB9A8C3A0B39D99FFC831E76F9EECB * L_14 = V_1; NullCheck(L_14); Transform_tBB9E78A2766C3C83599A8F66EDE7D1FCAFC66EDA * L_15 = Component_get_transform_m00F05BD782F920C301A7EBA480F3B7A904C07EC9(L_14, /*hidden argument*/NULL); NullCheck(L_15); Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 L_16 = Transform_get_position_mF54C3A064F7C8E24F1C56EE128728B2E4485E294(L_15, /*hidden argument*/NULL); Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 L_17 = Random_get_insideUnitSphere_m10033DFB85B1A21CE44201CB0E421F27B77A868F(/*hidden argument*/NULL); IL2CPP_RUNTIME_CLASS_INIT(Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720_il2cpp_TypeInfo_var); Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 L_18 = Vector3_op_Multiply_m1C5F07723615156ACF035D88A1280A9E8F35A04E(L_17, (3.0f), /*hidden argument*/NULL); float L_19 = __this->get_U3CmultiplierU3E5__2_3(); Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 L_20 = Vector3_op_Multiply_m1C5F07723615156ACF035D88A1280A9E8F35A04E(L_18, L_19, /*hidden argument*/NULL); Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 L_21 = Vector3_op_Addition_m929F9C17E5D11B94D50B4AFF1D730B70CB59B50E(L_16, L_20, /*hidden argument*/NULL); V_5 = L_21; // Quaternion rot = Random.rotation; Quaternion_t319F3319A7D43FFA5D819AD6C0A98851F0095357 L_22 = Random_get_rotation_mFEB212A2058746E0E8F544D8C2201663861BA77A(/*hidden argument*/NULL); V_6 = L_22; // Instantiate(prefab, pos, rot); Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 L_23 = V_5; Quaternion_t319F3319A7D43FFA5D819AD6C0A98851F0095357 L_24 = V_6; IL2CPP_RUNTIME_CLASS_INIT(Object_tAE11E5E46CD5C37C9F3E8950C00CD8B45666A2D0_il2cpp_TypeInfo_var); Object_Instantiate_TisTransform_tBB9E78A2766C3C83599A8F66EDE7D1FCAFC66EDA_m8BCC51A95F42E99B9033022D8BF0EABA04FED8F0(L_13, L_23, L_24, /*hidden argument*/Object_Instantiate_TisTransform_tBB9E78A2766C3C83599A8F66EDE7D1FCAFC66EDA_m8BCC51A95F42E99B9033022D8BF0EABA04FED8F0_RuntimeMethod_var); // for (int n = 0; n < numDebrisPieces*multiplier; ++n) int32_t L_25 = V_4; V_4 = ((int32_t)il2cpp_codegen_add((int32_t)L_25, (int32_t)1)); } IL_008f: { // for (int n = 0; n < numDebrisPieces*multiplier; ++n) int32_t L_26 = V_4; ExplosionFireAndDebris_tACCFCC1184BB9A8C3A0B39D99FFC831E76F9EECB * L_27 = V_1; NullCheck(L_27); int32_t L_28 = L_27->get_numDebrisPieces_6(); float L_29 = __this->get_U3CmultiplierU3E5__2_3(); if ((((float)(((float)((float)L_26)))) < ((float)((float)il2cpp_codegen_multiply((float)(((float)((float)L_28))), (float)L_29))))) { goto IL_0037; } } { // yield return null; __this->set_U3CU3E2__current_1(NULL); __this->set_U3CU3E1__state_0(1); return (bool)1; } IL_00b2: { __this->set_U3CU3E1__state_0((-1)); // float r = 10*multiplier; float L_30 = __this->get_U3CmultiplierU3E5__2_3(); V_2 = ((float)il2cpp_codegen_multiply((float)(10.0f), (float)L_30)); // var cols = Physics.OverlapSphere(transform.position, r); ExplosionFireAndDebris_tACCFCC1184BB9A8C3A0B39D99FFC831E76F9EECB * L_31 = V_1; NullCheck(L_31); Transform_tBB9E78A2766C3C83599A8F66EDE7D1FCAFC66EDA * L_32 = Component_get_transform_m00F05BD782F920C301A7EBA480F3B7A904C07EC9(L_31, /*hidden argument*/NULL); NullCheck(L_32); Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 L_33 = Transform_get_position_mF54C3A064F7C8E24F1C56EE128728B2E4485E294(L_32, /*hidden argument*/NULL); float L_34 = V_2; ColliderU5BU5D_t70D1FDAE17E4359298B2BAA828048D1B7CFFE252* L_35 = Physics_OverlapSphere_m354A92672F7A6DE59EF1285D02D62247F46A5D84(L_33, L_34, /*hidden argument*/NULL); // foreach (var col in cols) V_7 = L_35; V_8 = 0; goto IL_0159; } IL_00de: { // foreach (var col in cols) ColliderU5BU5D_t70D1FDAE17E4359298B2BAA828048D1B7CFFE252* L_36 = V_7; int32_t L_37 = V_8; NullCheck(L_36); int32_t L_38 = L_37; Collider_t0FEEB36760860AD21B3B1F0509C365B393EC4BDF * L_39 = (L_36)->GetAt(static_cast(L_38)); V_9 = L_39; // if (numFires > 0) ExplosionFireAndDebris_tACCFCC1184BB9A8C3A0B39D99FFC831E76F9EECB * L_40 = V_1; NullCheck(L_40); int32_t L_41 = L_40->get_numFires_7(); if ((((int32_t)L_41) <= ((int32_t)0))) { goto IL_0153; } } { // Ray fireRay = new Ray(transform.position, col.transform.position - transform.position); ExplosionFireAndDebris_tACCFCC1184BB9A8C3A0B39D99FFC831E76F9EECB * L_42 = V_1; NullCheck(L_42); Transform_tBB9E78A2766C3C83599A8F66EDE7D1FCAFC66EDA * L_43 = Component_get_transform_m00F05BD782F920C301A7EBA480F3B7A904C07EC9(L_42, /*hidden argument*/NULL); NullCheck(L_43); Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 L_44 = Transform_get_position_mF54C3A064F7C8E24F1C56EE128728B2E4485E294(L_43, /*hidden argument*/NULL); Collider_t0FEEB36760860AD21B3B1F0509C365B393EC4BDF * L_45 = V_9; NullCheck(L_45); Transform_tBB9E78A2766C3C83599A8F66EDE7D1FCAFC66EDA * L_46 = Component_get_transform_m00F05BD782F920C301A7EBA480F3B7A904C07EC9(L_45, /*hidden argument*/NULL); NullCheck(L_46); Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 L_47 = Transform_get_position_mF54C3A064F7C8E24F1C56EE128728B2E4485E294(L_46, /*hidden argument*/NULL); ExplosionFireAndDebris_tACCFCC1184BB9A8C3A0B39D99FFC831E76F9EECB * L_48 = V_1; NullCheck(L_48); Transform_tBB9E78A2766C3C83599A8F66EDE7D1FCAFC66EDA * L_49 = Component_get_transform_m00F05BD782F920C301A7EBA480F3B7A904C07EC9(L_48, /*hidden argument*/NULL); NullCheck(L_49); Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 L_50 = Transform_get_position_mF54C3A064F7C8E24F1C56EE128728B2E4485E294(L_49, /*hidden argument*/NULL); IL2CPP_RUNTIME_CLASS_INIT(Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720_il2cpp_TypeInfo_var); Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 L_51 = Vector3_op_Subtraction_mF9846B723A5034F8B9F5F5DCB78E3D67649143D3(L_47, L_50, /*hidden argument*/NULL); Ray__ctor_m695D219349B8AA4C82F96C55A27D384C07736F6B((Ray_tE2163D4CB3E6B267E29F8ABE41684490E4A614B2 *)(&V_11), L_44, L_51, /*hidden argument*/NULL); // if (col.Raycast(fireRay, out fireHit, r)) Collider_t0FEEB36760860AD21B3B1F0509C365B393EC4BDF * L_52 = V_9; Ray_tE2163D4CB3E6B267E29F8ABE41684490E4A614B2 L_53 = V_11; float L_54 = V_2; NullCheck(L_52); bool L_55 = Collider_Raycast_mF79828BB10A356336B673595777F7C6941E3F42F(L_52, L_53, (RaycastHit_t19695F18F9265FE5425062BBA6A4D330480538C3 *)(&V_10), L_54, /*hidden argument*/NULL); if (!L_55) { goto IL_0153; } } { // AddFire(col.transform, fireHit.point, fireHit.normal); ExplosionFireAndDebris_tACCFCC1184BB9A8C3A0B39D99FFC831E76F9EECB * L_56 = V_1; Collider_t0FEEB36760860AD21B3B1F0509C365B393EC4BDF * L_57 = V_9; NullCheck(L_57); Transform_tBB9E78A2766C3C83599A8F66EDE7D1FCAFC66EDA * L_58 = Component_get_transform_m00F05BD782F920C301A7EBA480F3B7A904C07EC9(L_57, /*hidden argument*/NULL); Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 L_59 = RaycastHit_get_point_m0E564B2A72C7A744B889AE9D596F3EFA55059001((RaycastHit_t19695F18F9265FE5425062BBA6A4D330480538C3 *)(&V_10), /*hidden argument*/NULL); Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 L_60 = RaycastHit_get_normal_mF736A6D09D98D63AB7E5BF10F38AEBFC177A1D94((RaycastHit_t19695F18F9265FE5425062BBA6A4D330480538C3 *)(&V_10), /*hidden argument*/NULL); NullCheck(L_56); ExplosionFireAndDebris_AddFire_m781F3E400896C4F2E2B4A24FAEFE52D01ED26C0B(L_56, L_58, L_59, L_60, /*hidden argument*/NULL); // numFires--; ExplosionFireAndDebris_tACCFCC1184BB9A8C3A0B39D99FFC831E76F9EECB * L_61 = V_1; ExplosionFireAndDebris_tACCFCC1184BB9A8C3A0B39D99FFC831E76F9EECB * L_62 = V_1; NullCheck(L_62); int32_t L_63 = L_62->get_numFires_7(); NullCheck(L_61); L_61->set_numFires_7(((int32_t)il2cpp_codegen_subtract((int32_t)L_63, (int32_t)1))); } IL_0153: { int32_t L_64 = V_8; V_8 = ((int32_t)il2cpp_codegen_add((int32_t)L_64, (int32_t)1)); } IL_0159: { // foreach (var col in cols) int32_t L_65 = V_8; ColliderU5BU5D_t70D1FDAE17E4359298B2BAA828048D1B7CFFE252* L_66 = V_7; NullCheck(L_66); if ((((int32_t)L_65) < ((int32_t)(((int32_t)((int32_t)(((RuntimeArray*)L_66)->max_length))))))) { goto IL_00de; } } { // float testR = 0; V_3 = (0.0f); goto IL_01c2; } IL_016c: { // Ray fireRay = new Ray(transform.position + Vector3.up, Random.onUnitSphere); ExplosionFireAndDebris_tACCFCC1184BB9A8C3A0B39D99FFC831E76F9EECB * L_67 = V_1; NullCheck(L_67); Transform_tBB9E78A2766C3C83599A8F66EDE7D1FCAFC66EDA * L_68 = Component_get_transform_m00F05BD782F920C301A7EBA480F3B7A904C07EC9(L_67, /*hidden argument*/NULL); NullCheck(L_68); Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 L_69 = Transform_get_position_mF54C3A064F7C8E24F1C56EE128728B2E4485E294(L_68, /*hidden argument*/NULL); IL2CPP_RUNTIME_CLASS_INIT(Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720_il2cpp_TypeInfo_var); Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 L_70 = Vector3_get_up_m6309EBC4E42D6D0B3D28056BD23D0331275306F7(/*hidden argument*/NULL); Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 L_71 = Vector3_op_Addition_m929F9C17E5D11B94D50B4AFF1D730B70CB59B50E(L_69, L_70, /*hidden argument*/NULL); Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 L_72 = Random_get_onUnitSphere_mBF4707ADEABB994E7B5B80305205A621B809E7E6(/*hidden argument*/NULL); Ray_tE2163D4CB3E6B267E29F8ABE41684490E4A614B2 L_73; memset((&L_73), 0, sizeof(L_73)); Ray__ctor_m695D219349B8AA4C82F96C55A27D384C07736F6B((&L_73), L_71, L_72, /*hidden argument*/NULL); // if (Physics.Raycast(fireRay, out fireHit, testR)) float L_74 = V_3; bool L_75 = Physics_Raycast_mE1590EE4E2DC950A9FC2437E98EE8CD2EC2DEE67(L_73, (RaycastHit_t19695F18F9265FE5425062BBA6A4D330480538C3 *)(&V_12), L_74, /*hidden argument*/NULL); if (!L_75) { goto IL_01b8; } } { // AddFire(null, fireHit.point, fireHit.normal); ExplosionFireAndDebris_tACCFCC1184BB9A8C3A0B39D99FFC831E76F9EECB * L_76 = V_1; Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 L_77 = RaycastHit_get_point_m0E564B2A72C7A744B889AE9D596F3EFA55059001((RaycastHit_t19695F18F9265FE5425062BBA6A4D330480538C3 *)(&V_12), /*hidden argument*/NULL); Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 L_78 = RaycastHit_get_normal_mF736A6D09D98D63AB7E5BF10F38AEBFC177A1D94((RaycastHit_t19695F18F9265FE5425062BBA6A4D330480538C3 *)(&V_12), /*hidden argument*/NULL); NullCheck(L_76); ExplosionFireAndDebris_AddFire_m781F3E400896C4F2E2B4A24FAEFE52D01ED26C0B(L_76, (Transform_tBB9E78A2766C3C83599A8F66EDE7D1FCAFC66EDA *)NULL, L_77, L_78, /*hidden argument*/NULL); // numFires--; ExplosionFireAndDebris_tACCFCC1184BB9A8C3A0B39D99FFC831E76F9EECB * L_79 = V_1; ExplosionFireAndDebris_tACCFCC1184BB9A8C3A0B39D99FFC831E76F9EECB * L_80 = V_1; NullCheck(L_80); int32_t L_81 = L_80->get_numFires_7(); NullCheck(L_79); L_79->set_numFires_7(((int32_t)il2cpp_codegen_subtract((int32_t)L_81, (int32_t)1))); } IL_01b8: { // testR += r*.1f; float L_82 = V_3; float L_83 = V_2; V_3 = ((float)il2cpp_codegen_add((float)L_82, (float)((float)il2cpp_codegen_multiply((float)L_83, (float)(0.1f))))); } IL_01c2: { // while (numFires > 0 && testR < r) ExplosionFireAndDebris_tACCFCC1184BB9A8C3A0B39D99FFC831E76F9EECB * L_84 = V_1; NullCheck(L_84); int32_t L_85 = L_84->get_numFires_7(); if ((((int32_t)L_85) <= ((int32_t)0))) { goto IL_01cf; } } { float L_86 = V_3; float L_87 = V_2; if ((((float)L_86) < ((float)L_87))) { goto IL_016c; } } IL_01cf: { // } return (bool)0; } } // System.Object UnityStandardAssets.Effects.ExplosionFireAndDebris/d__4::System.Collections.Generic.IEnumerator.get_Current() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR RuntimeObject * U3CStartU3Ed__4_System_Collections_Generic_IEnumeratorU3CSystem_ObjectU3E_get_Current_m134C857EC6C5EEB674DF4B22AE43D9CBD4D3596F (U3CStartU3Ed__4_t945A707CD8C01DA1C37AE2DD9D0A904C80F58139 * __this, const RuntimeMethod* method) { { RuntimeObject * L_0 = __this->get_U3CU3E2__current_1(); return L_0; } } // System.Void UnityStandardAssets.Effects.ExplosionFireAndDebris/d__4::System.Collections.IEnumerator.Reset() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void U3CStartU3Ed__4_System_Collections_IEnumerator_Reset_m886FA065B7C64EA3A746502C9F6BF104B9801F07 (U3CStartU3Ed__4_t945A707CD8C01DA1C37AE2DD9D0A904C80F58139 * __this, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (U3CStartU3Ed__4_System_Collections_IEnumerator_Reset_m886FA065B7C64EA3A746502C9F6BF104B9801F07_MetadataUsageId); s_Il2CppMethodInitialized = true; } { NotSupportedException_tE75B318D6590A02A5D9B29FD97409B1750FA0010 * L_0 = (NotSupportedException_tE75B318D6590A02A5D9B29FD97409B1750FA0010 *)il2cpp_codegen_object_new(NotSupportedException_tE75B318D6590A02A5D9B29FD97409B1750FA0010_il2cpp_TypeInfo_var); NotSupportedException__ctor_mA121DE1CAC8F25277DEB489DC7771209D91CAE33(L_0, /*hidden argument*/NULL); IL2CPP_RAISE_MANAGED_EXCEPTION(L_0, U3CStartU3Ed__4_System_Collections_IEnumerator_Reset_m886FA065B7C64EA3A746502C9F6BF104B9801F07_RuntimeMethod_var); } } // System.Object UnityStandardAssets.Effects.ExplosionFireAndDebris/d__4::System.Collections.IEnumerator.get_Current() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR RuntimeObject * U3CStartU3Ed__4_System_Collections_IEnumerator_get_Current_mEA0D5C2C7930B6E16648C869029DC54290E095E2 (U3CStartU3Ed__4_t945A707CD8C01DA1C37AE2DD9D0A904C80F58139 * __this, const RuntimeMethod* method) { { RuntimeObject * L_0 = __this->get_U3CU3E2__current_1(); return L_0; } } #ifdef __clang__ #pragma clang diagnostic pop #endif #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Collections.IEnumerator UnityStandardAssets.Effects.ExplosionPhysicsForce::Start() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR RuntimeObject* ExplosionPhysicsForce_Start_m22750184987B8A375DA674EF615F5ECD1DAD04C5 (ExplosionPhysicsForce_t59463D9C69E811AF9C885416501F2C8833800C58 * __this, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (ExplosionPhysicsForce_Start_m22750184987B8A375DA674EF615F5ECD1DAD04C5_MetadataUsageId); s_Il2CppMethodInitialized = true; } { U3CStartU3Ed__1_tFA687701957C85736794A1CD53601F73339D788F * L_0 = (U3CStartU3Ed__1_tFA687701957C85736794A1CD53601F73339D788F *)il2cpp_codegen_object_new(U3CStartU3Ed__1_tFA687701957C85736794A1CD53601F73339D788F_il2cpp_TypeInfo_var); U3CStartU3Ed__1__ctor_m28BA84EE932E5505BA7BD35AC5F8007BA8B96564(L_0, 0, /*hidden argument*/NULL); U3CStartU3Ed__1_tFA687701957C85736794A1CD53601F73339D788F * L_1 = L_0; NullCheck(L_1); L_1->set_U3CU3E4__this_2(__this); return L_1; } } // System.Void UnityStandardAssets.Effects.ExplosionPhysicsForce::.ctor() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void ExplosionPhysicsForce__ctor_m3A4FFA852D5C736E4CE47A5A5A3E0CA1E954F660 (ExplosionPhysicsForce_t59463D9C69E811AF9C885416501F2C8833800C58 * __this, const RuntimeMethod* method) { { // public float explosionForce = 4; __this->set_explosionForce_4((4.0f)); MonoBehaviour__ctor_mEAEC84B222C60319D593E456D769B3311DFCEF97(__this, /*hidden argument*/NULL); return; } } #ifdef __clang__ #pragma clang diagnostic pop #endif #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Void UnityStandardAssets.Effects.ExplosionPhysicsForce/d__1::.ctor(System.Int32) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void U3CStartU3Ed__1__ctor_m28BA84EE932E5505BA7BD35AC5F8007BA8B96564 (U3CStartU3Ed__1_tFA687701957C85736794A1CD53601F73339D788F * __this, int32_t ___U3CU3E1__state0, const RuntimeMethod* method) { { Object__ctor_m925ECA5E85CA100E3FB86A4F9E15C120E9A184C0(__this, /*hidden argument*/NULL); int32_t L_0 = ___U3CU3E1__state0; __this->set_U3CU3E1__state_0(L_0); return; } } // System.Void UnityStandardAssets.Effects.ExplosionPhysicsForce/d__1::System.IDisposable.Dispose() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void U3CStartU3Ed__1_System_IDisposable_Dispose_m2411BD36258EF1A6EF59D488D875E1989C3BAE1C (U3CStartU3Ed__1_tFA687701957C85736794A1CD53601F73339D788F * __this, const RuntimeMethod* method) { { return; } } // System.Boolean UnityStandardAssets.Effects.ExplosionPhysicsForce/d__1::MoveNext() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR bool U3CStartU3Ed__1_MoveNext_m69D4364C306F1FC8F21C33E29E6C125B2B9EEF2B (U3CStartU3Ed__1_tFA687701957C85736794A1CD53601F73339D788F * __this, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (U3CStartU3Ed__1_MoveNext_m69D4364C306F1FC8F21C33E29E6C125B2B9EEF2B_MetadataUsageId); s_Il2CppMethodInitialized = true; } int32_t V_0 = 0; ExplosionPhysicsForce_t59463D9C69E811AF9C885416501F2C8833800C58 * V_1 = NULL; float V_2 = 0.0f; float V_3 = 0.0f; List_1_tF00B86100455886AD0B3A0B82FE6C94700D131D0 * V_4 = NULL; ColliderU5BU5D_t70D1FDAE17E4359298B2BAA828048D1B7CFFE252* V_5 = NULL; int32_t V_6 = 0; Collider_t0FEEB36760860AD21B3B1F0509C365B393EC4BDF * V_7 = NULL; Enumerator_t27C52ABD621DACF0C5D52FDAA65A98738987017E V_8; memset((&V_8), 0, sizeof(V_8)); Exception_t * __last_unhandled_exception = 0; NO_UNUSED_WARNING (__last_unhandled_exception); Exception_t * __exception_local = 0; NO_UNUSED_WARNING (__exception_local); void* __leave_targets_storage = alloca(sizeof(int32_t) * 1); il2cpp::utils::LeaveTargetStack __leave_targets(__leave_targets_storage); NO_UNUSED_WARNING (__leave_targets); { int32_t L_0 = __this->get_U3CU3E1__state_0(); V_0 = L_0; ExplosionPhysicsForce_t59463D9C69E811AF9C885416501F2C8833800C58 * L_1 = __this->get_U3CU3E4__this_2(); V_1 = L_1; int32_t L_2 = V_0; if (!L_2) { goto IL_0017; } } { int32_t L_3 = V_0; if ((((int32_t)L_3) == ((int32_t)1))) { goto IL_002e; } } { return (bool)0; } IL_0017: { __this->set_U3CU3E1__state_0((-1)); // yield return null; __this->set_U3CU3E2__current_1(NULL); __this->set_U3CU3E1__state_0(1); return (bool)1; } IL_002e: { __this->set_U3CU3E1__state_0((-1)); // float multiplier = GetComponent().multiplier; ExplosionPhysicsForce_t59463D9C69E811AF9C885416501F2C8833800C58 * L_4 = V_1; NullCheck(L_4); ParticleSystemMultiplier_t8EBFEF83EBA48DD7F6517ABFFBE2CD051CB2C748 * L_5 = Component_GetComponent_TisParticleSystemMultiplier_t8EBFEF83EBA48DD7F6517ABFFBE2CD051CB2C748_m77EDAEF51740299BC986B0DA36AB7282BB8DDD45(L_4, /*hidden argument*/Component_GetComponent_TisParticleSystemMultiplier_t8EBFEF83EBA48DD7F6517ABFFBE2CD051CB2C748_m77EDAEF51740299BC986B0DA36AB7282BB8DDD45_RuntimeMethod_var); NullCheck(L_5); float L_6 = L_5->get_multiplier_4(); V_2 = L_6; // float r = 10*multiplier; float L_7 = V_2; V_3 = ((float)il2cpp_codegen_multiply((float)(10.0f), (float)L_7)); // var cols = Physics.OverlapSphere(transform.position, r); ExplosionPhysicsForce_t59463D9C69E811AF9C885416501F2C8833800C58 * L_8 = V_1; NullCheck(L_8); Transform_tBB9E78A2766C3C83599A8F66EDE7D1FCAFC66EDA * L_9 = Component_get_transform_m00F05BD782F920C301A7EBA480F3B7A904C07EC9(L_8, /*hidden argument*/NULL); NullCheck(L_9); Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 L_10 = Transform_get_position_mF54C3A064F7C8E24F1C56EE128728B2E4485E294(L_9, /*hidden argument*/NULL); float L_11 = V_3; ColliderU5BU5D_t70D1FDAE17E4359298B2BAA828048D1B7CFFE252* L_12 = Physics_OverlapSphere_m354A92672F7A6DE59EF1285D02D62247F46A5D84(L_10, L_11, /*hidden argument*/NULL); // var rigidbodies = new List(); List_1_tF00B86100455886AD0B3A0B82FE6C94700D131D0 * L_13 = (List_1_tF00B86100455886AD0B3A0B82FE6C94700D131D0 *)il2cpp_codegen_object_new(List_1_tF00B86100455886AD0B3A0B82FE6C94700D131D0_il2cpp_TypeInfo_var); List_1__ctor_m8F8DC666C2D1350D6CDDE96E73998792E882CF46(L_13, /*hidden argument*/List_1__ctor_m8F8DC666C2D1350D6CDDE96E73998792E882CF46_RuntimeMethod_var); V_4 = L_13; // foreach (var col in cols) V_5 = L_12; V_6 = 0; goto IL_00a2; } IL_0068: { // foreach (var col in cols) ColliderU5BU5D_t70D1FDAE17E4359298B2BAA828048D1B7CFFE252* L_14 = V_5; int32_t L_15 = V_6; NullCheck(L_14); int32_t L_16 = L_15; Collider_t0FEEB36760860AD21B3B1F0509C365B393EC4BDF * L_17 = (L_14)->GetAt(static_cast(L_16)); V_7 = L_17; // if (col.attachedRigidbody != null && !rigidbodies.Contains(col.attachedRigidbody)) Collider_t0FEEB36760860AD21B3B1F0509C365B393EC4BDF * L_18 = V_7; NullCheck(L_18); Rigidbody_tE0A58EE5A1F7DC908EFFB4F0D795AC9552A750A5 * L_19 = Collider_get_attachedRigidbody_m9E3C688EAE2F6A76C9AC14968D96769D9A71B1E8(L_18, /*hidden argument*/NULL); IL2CPP_RUNTIME_CLASS_INIT(Object_tAE11E5E46CD5C37C9F3E8950C00CD8B45666A2D0_il2cpp_TypeInfo_var); bool L_20 = Object_op_Inequality_m31EF58E217E8F4BDD3E409DEF79E1AEE95874FC1(L_19, (Object_tAE11E5E46CD5C37C9F3E8950C00CD8B45666A2D0 *)NULL, /*hidden argument*/NULL); if (!L_20) { goto IL_009c; } } { List_1_tF00B86100455886AD0B3A0B82FE6C94700D131D0 * L_21 = V_4; Collider_t0FEEB36760860AD21B3B1F0509C365B393EC4BDF * L_22 = V_7; NullCheck(L_22); Rigidbody_tE0A58EE5A1F7DC908EFFB4F0D795AC9552A750A5 * L_23 = Collider_get_attachedRigidbody_m9E3C688EAE2F6A76C9AC14968D96769D9A71B1E8(L_22, /*hidden argument*/NULL); NullCheck(L_21); bool L_24 = List_1_Contains_m4D1DE7EDA972C9BCD4617A52BFF4CFE08895758C(L_21, L_23, /*hidden argument*/List_1_Contains_m4D1DE7EDA972C9BCD4617A52BFF4CFE08895758C_RuntimeMethod_var); if (L_24) { goto IL_009c; } } { // rigidbodies.Add(col.attachedRigidbody); List_1_tF00B86100455886AD0B3A0B82FE6C94700D131D0 * L_25 = V_4; Collider_t0FEEB36760860AD21B3B1F0509C365B393EC4BDF * L_26 = V_7; NullCheck(L_26); Rigidbody_tE0A58EE5A1F7DC908EFFB4F0D795AC9552A750A5 * L_27 = Collider_get_attachedRigidbody_m9E3C688EAE2F6A76C9AC14968D96769D9A71B1E8(L_26, /*hidden argument*/NULL); NullCheck(L_25); List_1_Add_mA7DDE87A050C0636FDCC9DC4A5BCA55A5379A4B8(L_25, L_27, /*hidden argument*/List_1_Add_mA7DDE87A050C0636FDCC9DC4A5BCA55A5379A4B8_RuntimeMethod_var); } IL_009c: { int32_t L_28 = V_6; V_6 = ((int32_t)il2cpp_codegen_add((int32_t)L_28, (int32_t)1)); } IL_00a2: { // foreach (var col in cols) int32_t L_29 = V_6; ColliderU5BU5D_t70D1FDAE17E4359298B2BAA828048D1B7CFFE252* L_30 = V_5; NullCheck(L_30); if ((((int32_t)L_29) < ((int32_t)(((int32_t)((int32_t)(((RuntimeArray*)L_30)->max_length))))))) { goto IL_0068; } } { // foreach (var rb in rigidbodies) List_1_tF00B86100455886AD0B3A0B82FE6C94700D131D0 * L_31 = V_4; NullCheck(L_31); Enumerator_t27C52ABD621DACF0C5D52FDAA65A98738987017E L_32 = List_1_GetEnumerator_m7CB8469ED2AE9E0CA1FEFF4C60991DFF8BD8CFF3(L_31, /*hidden argument*/List_1_GetEnumerator_m7CB8469ED2AE9E0CA1FEFF4C60991DFF8BD8CFF3_RuntimeMethod_var); V_8 = L_32; } IL_00b3: try { // begin try (depth: 1) { goto IL_00dd; } IL_00b5: { // foreach (var rb in rigidbodies) Rigidbody_tE0A58EE5A1F7DC908EFFB4F0D795AC9552A750A5 * L_33 = Enumerator_get_Current_mC1CD020347F81EDABBA39647711D3D2E115176C7_inline((Enumerator_t27C52ABD621DACF0C5D52FDAA65A98738987017E *)(&V_8), /*hidden argument*/Enumerator_get_Current_mC1CD020347F81EDABBA39647711D3D2E115176C7_RuntimeMethod_var); // rb.AddExplosionForce(explosionForce*multiplier, transform.position, r, 1*multiplier, ForceMode.Impulse); ExplosionPhysicsForce_t59463D9C69E811AF9C885416501F2C8833800C58 * L_34 = V_1; NullCheck(L_34); float L_35 = L_34->get_explosionForce_4(); float L_36 = V_2; ExplosionPhysicsForce_t59463D9C69E811AF9C885416501F2C8833800C58 * L_37 = V_1; NullCheck(L_37); Transform_tBB9E78A2766C3C83599A8F66EDE7D1FCAFC66EDA * L_38 = Component_get_transform_m00F05BD782F920C301A7EBA480F3B7A904C07EC9(L_37, /*hidden argument*/NULL); NullCheck(L_38); Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 L_39 = Transform_get_position_mF54C3A064F7C8E24F1C56EE128728B2E4485E294(L_38, /*hidden argument*/NULL); float L_40 = V_3; float L_41 = V_2; NullCheck(L_33); Rigidbody_AddExplosionForce_m8A2C25CE73AC51E1C255929733A4187089BA689A(L_33, ((float)il2cpp_codegen_multiply((float)L_35, (float)L_36)), L_39, L_40, ((float)il2cpp_codegen_multiply((float)(1.0f), (float)L_41)), 1, /*hidden argument*/NULL); } IL_00dd: { // foreach (var rb in rigidbodies) bool L_42 = Enumerator_MoveNext_m9A51F685E9FE881F75850562F97DD04FB51B3F0F((Enumerator_t27C52ABD621DACF0C5D52FDAA65A98738987017E *)(&V_8), /*hidden argument*/Enumerator_MoveNext_m9A51F685E9FE881F75850562F97DD04FB51B3F0F_RuntimeMethod_var); if (L_42) { goto IL_00b5; } } IL_00e6: { IL2CPP_LEAVE(0xF6, FINALLY_00e8); } } // end try (depth: 1) catch(Il2CppExceptionWrapper& e) { __last_unhandled_exception = (Exception_t *)e.ex; goto FINALLY_00e8; } FINALLY_00e8: { // begin finally (depth: 1) Enumerator_Dispose_mECFDE242B9B4ECC8048254467FCB58F6EA7333F6((Enumerator_t27C52ABD621DACF0C5D52FDAA65A98738987017E *)(&V_8), /*hidden argument*/Enumerator_Dispose_mECFDE242B9B4ECC8048254467FCB58F6EA7333F6_RuntimeMethod_var); IL2CPP_END_FINALLY(232) } // end finally (depth: 1) IL2CPP_CLEANUP(232) { IL2CPP_RETHROW_IF_UNHANDLED(Exception_t *) IL2CPP_JUMP_TBL(0xF6, IL_00f6) } IL_00f6: { // } return (bool)0; } } // System.Object UnityStandardAssets.Effects.ExplosionPhysicsForce/d__1::System.Collections.Generic.IEnumerator.get_Current() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR RuntimeObject * U3CStartU3Ed__1_System_Collections_Generic_IEnumeratorU3CSystem_ObjectU3E_get_Current_m600B8E8FC9018CA7E4700F80CF7114DBD2A89C0F (U3CStartU3Ed__1_tFA687701957C85736794A1CD53601F73339D788F * __this, const RuntimeMethod* method) { { RuntimeObject * L_0 = __this->get_U3CU3E2__current_1(); return L_0; } } // System.Void UnityStandardAssets.Effects.ExplosionPhysicsForce/d__1::System.Collections.IEnumerator.Reset() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void U3CStartU3Ed__1_System_Collections_IEnumerator_Reset_m8BE9B7F5466A03EDD437E3D16EB3E659B51ABC0E (U3CStartU3Ed__1_tFA687701957C85736794A1CD53601F73339D788F * __this, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (U3CStartU3Ed__1_System_Collections_IEnumerator_Reset_m8BE9B7F5466A03EDD437E3D16EB3E659B51ABC0E_MetadataUsageId); s_Il2CppMethodInitialized = true; } { NotSupportedException_tE75B318D6590A02A5D9B29FD97409B1750FA0010 * L_0 = (NotSupportedException_tE75B318D6590A02A5D9B29FD97409B1750FA0010 *)il2cpp_codegen_object_new(NotSupportedException_tE75B318D6590A02A5D9B29FD97409B1750FA0010_il2cpp_TypeInfo_var); NotSupportedException__ctor_mA121DE1CAC8F25277DEB489DC7771209D91CAE33(L_0, /*hidden argument*/NULL); IL2CPP_RAISE_MANAGED_EXCEPTION(L_0, U3CStartU3Ed__1_System_Collections_IEnumerator_Reset_m8BE9B7F5466A03EDD437E3D16EB3E659B51ABC0E_RuntimeMethod_var); } } // System.Object UnityStandardAssets.Effects.ExplosionPhysicsForce/d__1::System.Collections.IEnumerator.get_Current() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR RuntimeObject * U3CStartU3Ed__1_System_Collections_IEnumerator_get_Current_m60734E8242F26A6B6ADF449A1668715F5E393E00 (U3CStartU3Ed__1_tFA687701957C85736794A1CD53601F73339D788F * __this, const RuntimeMethod* method) { { RuntimeObject * L_0 = __this->get_U3CU3E2__current_1(); return L_0; } } #ifdef __clang__ #pragma clang diagnostic pop #endif #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Void UnityStandardAssets.Effects.ExtinguishableParticleSystem::Start() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void ExtinguishableParticleSystem_Start_m442E9165E311C7DC5AE322C5CF8B8D6A2325DC39 (ExtinguishableParticleSystem_tD91348BD8771EB84F5369DA844F390BE915ADB64 * __this, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (ExtinguishableParticleSystem_Start_m442E9165E311C7DC5AE322C5CF8B8D6A2325DC39_MetadataUsageId); s_Il2CppMethodInitialized = true; } { // m_Systems = GetComponentsInChildren(); ParticleSystemU5BU5D_t58EE604F685D8CBA8EFC9353456969F5A1B2FBB9* L_0 = Component_GetComponentsInChildren_TisParticleSystem_t45DA87A3E83E738DA3FDAA5A48A133F1A1247C3D_mD5AEF673286CB17B689F765BB71E83509548DC41(__this, /*hidden argument*/Component_GetComponentsInChildren_TisParticleSystem_t45DA87A3E83E738DA3FDAA5A48A133F1A1247C3D_mD5AEF673286CB17B689F765BB71E83509548DC41_RuntimeMethod_var); __this->set_m_Systems_5(L_0); // } return; } } // System.Void UnityStandardAssets.Effects.ExtinguishableParticleSystem::Extinguish() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void ExtinguishableParticleSystem_Extinguish_m2E9C8C61E7E4E1083A3059582EE9F68BB0D8EFA8 (ExtinguishableParticleSystem_tD91348BD8771EB84F5369DA844F390BE915ADB64 * __this, const RuntimeMethod* method) { ParticleSystemU5BU5D_t58EE604F685D8CBA8EFC9353456969F5A1B2FBB9* V_0 = NULL; int32_t V_1 = 0; EmissionModule_t35028C3DE5EFDCE49E8A9732460617A56BD1D3F1 V_2; memset((&V_2), 0, sizeof(V_2)); { // foreach (var system in m_Systems) ParticleSystemU5BU5D_t58EE604F685D8CBA8EFC9353456969F5A1B2FBB9* L_0 = __this->get_m_Systems_5(); V_0 = L_0; V_1 = 0; goto IL_0020; } IL_000b: { // foreach (var system in m_Systems) ParticleSystemU5BU5D_t58EE604F685D8CBA8EFC9353456969F5A1B2FBB9* L_1 = V_0; int32_t L_2 = V_1; NullCheck(L_1); int32_t L_3 = L_2; ParticleSystem_t45DA87A3E83E738DA3FDAA5A48A133F1A1247C3D * L_4 = (L_1)->GetAt(static_cast(L_3)); // var emission = system.emission; NullCheck(L_4); EmissionModule_t35028C3DE5EFDCE49E8A9732460617A56BD1D3F1 L_5 = ParticleSystem_get_emission_mA1204EAF07A6C6B3F65B45295797A1FFF64D343C(L_4, /*hidden argument*/NULL); V_2 = L_5; // emission.enabled = false; EmissionModule_set_enabled_m3896B441BDE0F0752A6D113012B20D5D31B16D36((EmissionModule_t35028C3DE5EFDCE49E8A9732460617A56BD1D3F1 *)(&V_2), (bool)0, /*hidden argument*/NULL); int32_t L_6 = V_1; V_1 = ((int32_t)il2cpp_codegen_add((int32_t)L_6, (int32_t)1)); } IL_0020: { // foreach (var system in m_Systems) int32_t L_7 = V_1; ParticleSystemU5BU5D_t58EE604F685D8CBA8EFC9353456969F5A1B2FBB9* L_8 = V_0; NullCheck(L_8); if ((((int32_t)L_7) < ((int32_t)(((int32_t)((int32_t)(((RuntimeArray*)L_8)->max_length))))))) { goto IL_000b; } } { // } return; } } // System.Void UnityStandardAssets.Effects.ExtinguishableParticleSystem::.ctor() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void ExtinguishableParticleSystem__ctor_m66F7FA6921D145A9EF55397A60FCC4CA574DA068 (ExtinguishableParticleSystem_tD91348BD8771EB84F5369DA844F390BE915ADB64 * __this, const RuntimeMethod* method) { { // public float multiplier = 1; __this->set_multiplier_4((1.0f)); MonoBehaviour__ctor_mEAEC84B222C60319D593E456D769B3311DFCEF97(__this, /*hidden argument*/NULL); return; } } #ifdef __clang__ #pragma clang diagnostic pop #endif #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Void UnityStandardAssets.Effects.FireLight::Start() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void FireLight_Start_mBC43BC2A9EDAD47A5D43C96C04E1AECC4405B81D (FireLight_tBDF3DBBD1B6288E05ECBDCDB787FBB8ABD8572C5 * __this, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (FireLight_Start_mBC43BC2A9EDAD47A5D43C96C04E1AECC4405B81D_MetadataUsageId); s_Il2CppMethodInitialized = true; } { // m_Rnd = Random.value*100; float L_0 = Random_get_value_mC998749E08291DD42CF31C026FAC4F14F746831C(/*hidden argument*/NULL); __this->set_m_Rnd_4(((float)il2cpp_codegen_multiply((float)L_0, (float)(100.0f)))); // m_Light = GetComponent(); Light_tFDE490EADBC7E080F74CA804929513AF07C31A6C * L_1 = Component_GetComponent_TisLight_tFDE490EADBC7E080F74CA804929513AF07C31A6C_m1DCED5DB1934151FC68A8E7CAECF7986359D7107(__this, /*hidden argument*/Component_GetComponent_TisLight_tFDE490EADBC7E080F74CA804929513AF07C31A6C_m1DCED5DB1934151FC68A8E7CAECF7986359D7107_RuntimeMethod_var); __this->set_m_Light_6(L_1); // } return; } } // System.Void UnityStandardAssets.Effects.FireLight::Update() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void FireLight_Update_mE6D64BEF14D90624104BC092626B738B75D8D0F7 (FireLight_tBDF3DBBD1B6288E05ECBDCDB787FBB8ABD8572C5 * __this, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (FireLight_Update_mE6D64BEF14D90624104BC092626B738B75D8D0F7_MetadataUsageId); s_Il2CppMethodInitialized = true; } float V_0 = 0.0f; float V_1 = 0.0f; float V_2 = 0.0f; { // if (m_Burning) bool L_0 = __this->get_m_Burning_5(); if (!L_0) { goto IL_0120; } } { // m_Light.intensity = 2*Mathf.PerlinNoise(m_Rnd + Time.time, m_Rnd + 1 + Time.time*1); Light_tFDE490EADBC7E080F74CA804929513AF07C31A6C * L_1 = __this->get_m_Light_6(); float L_2 = __this->get_m_Rnd_4(); float L_3 = Time_get_time_m7863349C8845BBA36629A2B3F8EF1C3BEA350FD8(/*hidden argument*/NULL); float L_4 = __this->get_m_Rnd_4(); float L_5 = Time_get_time_m7863349C8845BBA36629A2B3F8EF1C3BEA350FD8(/*hidden argument*/NULL); IL2CPP_RUNTIME_CLASS_INIT(Mathf_tFBDE6467D269BFE410605C7D806FD9991D4A89CB_il2cpp_TypeInfo_var); float L_6 = Mathf_PerlinNoise_mA36E513B2931F17ACBF26D928674D3DDEDF5C810(((float)il2cpp_codegen_add((float)L_2, (float)L_3)), ((float)il2cpp_codegen_add((float)((float)il2cpp_codegen_add((float)L_4, (float)(1.0f))), (float)((float)il2cpp_codegen_multiply((float)L_5, (float)(1.0f))))), /*hidden argument*/NULL); NullCheck(L_1); Light_set_intensity_mE209975C840F1D887B4207C390DB5A2EF15A763C(L_1, ((float)il2cpp_codegen_multiply((float)(2.0f), (float)L_6)), /*hidden argument*/NULL); // float x = Mathf.PerlinNoise(m_Rnd + 0 + Time.time*2, m_Rnd + 1 + Time.time*2) - 0.5f; float L_7 = __this->get_m_Rnd_4(); float L_8 = Time_get_time_m7863349C8845BBA36629A2B3F8EF1C3BEA350FD8(/*hidden argument*/NULL); float L_9 = __this->get_m_Rnd_4(); float L_10 = Time_get_time_m7863349C8845BBA36629A2B3F8EF1C3BEA350FD8(/*hidden argument*/NULL); float L_11 = Mathf_PerlinNoise_mA36E513B2931F17ACBF26D928674D3DDEDF5C810(((float)il2cpp_codegen_add((float)((float)il2cpp_codegen_add((float)L_7, (float)(0.0f))), (float)((float)il2cpp_codegen_multiply((float)L_8, (float)(2.0f))))), ((float)il2cpp_codegen_add((float)((float)il2cpp_codegen_add((float)L_9, (float)(1.0f))), (float)((float)il2cpp_codegen_multiply((float)L_10, (float)(2.0f))))), /*hidden argument*/NULL); V_0 = ((float)il2cpp_codegen_subtract((float)L_11, (float)(0.5f))); // float y = Mathf.PerlinNoise(m_Rnd + 2 + Time.time*2, m_Rnd + 3 + Time.time*2) - 0.5f; float L_12 = __this->get_m_Rnd_4(); float L_13 = Time_get_time_m7863349C8845BBA36629A2B3F8EF1C3BEA350FD8(/*hidden argument*/NULL); float L_14 = __this->get_m_Rnd_4(); float L_15 = Time_get_time_m7863349C8845BBA36629A2B3F8EF1C3BEA350FD8(/*hidden argument*/NULL); float L_16 = Mathf_PerlinNoise_mA36E513B2931F17ACBF26D928674D3DDEDF5C810(((float)il2cpp_codegen_add((float)((float)il2cpp_codegen_add((float)L_12, (float)(2.0f))), (float)((float)il2cpp_codegen_multiply((float)L_13, (float)(2.0f))))), ((float)il2cpp_codegen_add((float)((float)il2cpp_codegen_add((float)L_14, (float)(3.0f))), (float)((float)il2cpp_codegen_multiply((float)L_15, (float)(2.0f))))), /*hidden argument*/NULL); V_1 = ((float)il2cpp_codegen_subtract((float)L_16, (float)(0.5f))); // float z = Mathf.PerlinNoise(m_Rnd + 4 + Time.time*2, m_Rnd + 5 + Time.time*2) - 0.5f; float L_17 = __this->get_m_Rnd_4(); float L_18 = Time_get_time_m7863349C8845BBA36629A2B3F8EF1C3BEA350FD8(/*hidden argument*/NULL); float L_19 = __this->get_m_Rnd_4(); float L_20 = Time_get_time_m7863349C8845BBA36629A2B3F8EF1C3BEA350FD8(/*hidden argument*/NULL); float L_21 = Mathf_PerlinNoise_mA36E513B2931F17ACBF26D928674D3DDEDF5C810(((float)il2cpp_codegen_add((float)((float)il2cpp_codegen_add((float)L_17, (float)(4.0f))), (float)((float)il2cpp_codegen_multiply((float)L_18, (float)(2.0f))))), ((float)il2cpp_codegen_add((float)((float)il2cpp_codegen_add((float)L_19, (float)(5.0f))), (float)((float)il2cpp_codegen_multiply((float)L_20, (float)(2.0f))))), /*hidden argument*/NULL); V_2 = ((float)il2cpp_codegen_subtract((float)L_21, (float)(0.5f))); // transform.localPosition = Vector3.up + new Vector3(x, y, z)*1; Transform_tBB9E78A2766C3C83599A8F66EDE7D1FCAFC66EDA * L_22 = Component_get_transform_m00F05BD782F920C301A7EBA480F3B7A904C07EC9(__this, /*hidden argument*/NULL); IL2CPP_RUNTIME_CLASS_INIT(Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720_il2cpp_TypeInfo_var); Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 L_23 = Vector3_get_up_m6309EBC4E42D6D0B3D28056BD23D0331275306F7(/*hidden argument*/NULL); float L_24 = V_0; float L_25 = V_1; float L_26 = V_2; Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 L_27; memset((&L_27), 0, sizeof(L_27)); Vector3__ctor_m08F61F548AA5836D8789843ACB4A81E4963D2EE1((&L_27), L_24, L_25, L_26, /*hidden argument*/NULL); Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 L_28 = Vector3_op_Multiply_m1C5F07723615156ACF035D88A1280A9E8F35A04E(L_27, (1.0f), /*hidden argument*/NULL); Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 L_29 = Vector3_op_Addition_m929F9C17E5D11B94D50B4AFF1D730B70CB59B50E(L_23, L_28, /*hidden argument*/NULL); NullCheck(L_22); Transform_set_localPosition_m275F5550DD939F83AFEB5E8D681131172E2E1728(L_22, L_29, /*hidden argument*/NULL); } IL_0120: { // } return; } } // System.Void UnityStandardAssets.Effects.FireLight::Extinguish() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void FireLight_Extinguish_m96CC75996F151C74E4D46556599FDF4F39AF6776 (FireLight_tBDF3DBBD1B6288E05ECBDCDB787FBB8ABD8572C5 * __this, const RuntimeMethod* method) { { // m_Burning = false; __this->set_m_Burning_5((bool)0); // m_Light.enabled = false; Light_tFDE490EADBC7E080F74CA804929513AF07C31A6C * L_0 = __this->get_m_Light_6(); NullCheck(L_0); Behaviour_set_enabled_m9755D3B17D7022D23D1E4C618BD9A6B66A5ADC6B(L_0, (bool)0, /*hidden argument*/NULL); // } return; } } // System.Void UnityStandardAssets.Effects.FireLight::.ctor() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void FireLight__ctor_mFAEAECD04029DD5E24A331FEE4B5C43FFD5B6FBE (FireLight_tBDF3DBBD1B6288E05ECBDCDB787FBB8ABD8572C5 * __this, const RuntimeMethod* method) { { // private bool m_Burning = true; __this->set_m_Burning_5((bool)1); MonoBehaviour__ctor_mEAEC84B222C60319D593E456D769B3311DFCEF97(__this, /*hidden argument*/NULL); return; } } #ifdef __clang__ #pragma clang diagnostic pop #endif #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Void UnityStandardAssets.Effects.Hose::Update() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Hose_Update_mF09247CA136AF92D5586DD9C95823C7E9A6AE939 (Hose_t411AEC20AB5A70AEFCF03FCB2418F0C8EB14C2D2 * __this, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (Hose_Update_mF09247CA136AF92D5586DD9C95823C7E9A6AE939_MetadataUsageId); s_Il2CppMethodInitialized = true; } ParticleSystemU5BU5D_t58EE604F685D8CBA8EFC9353456969F5A1B2FBB9* V_0 = NULL; int32_t V_1 = 0; MainModule_t99C675667E0A363368324132DFA34B27FFEE6FC7 V_2; memset((&V_2), 0, sizeof(V_2)); EmissionModule_t35028C3DE5EFDCE49E8A9732460617A56BD1D3F1 V_3; memset((&V_3), 0, sizeof(V_3)); float G_B2_0 = 0.0f; Hose_t411AEC20AB5A70AEFCF03FCB2418F0C8EB14C2D2 * G_B2_1 = NULL; float G_B1_0 = 0.0f; Hose_t411AEC20AB5A70AEFCF03FCB2418F0C8EB14C2D2 * G_B1_1 = NULL; float G_B3_0 = 0.0f; float G_B3_1 = 0.0f; Hose_t411AEC20AB5A70AEFCF03FCB2418F0C8EB14C2D2 * G_B3_2 = NULL; { // m_Power = Mathf.Lerp(m_Power, Input.GetMouseButton(0) ? maxPower : minPower, Time.deltaTime*changeSpeed); float L_0 = __this->get_m_Power_9(); bool L_1 = Input_GetMouseButton_m43C68DE93C7D990E875BA53C4DEC9CA6230C8B79(0, /*hidden argument*/NULL); G_B1_0 = L_0; G_B1_1 = __this; if (L_1) { G_B2_0 = L_0; G_B2_1 = __this; goto IL_0017; } } { float L_2 = __this->get_minPower_5(); G_B3_0 = L_2; G_B3_1 = G_B1_0; G_B3_2 = G_B1_1; goto IL_001d; } IL_0017: { float L_3 = __this->get_maxPower_4(); G_B3_0 = L_3; G_B3_1 = G_B2_0; G_B3_2 = G_B2_1; } IL_001d: { float L_4 = Time_get_deltaTime_m16F98FC9BA931581236008C288E3B25CBCB7C81E(/*hidden argument*/NULL); float L_5 = __this->get_changeSpeed_6(); IL2CPP_RUNTIME_CLASS_INIT(Mathf_tFBDE6467D269BFE410605C7D806FD9991D4A89CB_il2cpp_TypeInfo_var); float L_6 = Mathf_Lerp_m9A74C5A0C37D0CDF45EE66E7774D12A9B93B1364(G_B3_1, G_B3_0, ((float)il2cpp_codegen_multiply((float)L_4, (float)L_5)), /*hidden argument*/NULL); NullCheck(G_B3_2); G_B3_2->set_m_Power_9(L_6); // if (Input.GetKeyDown(KeyCode.Alpha1)) bool L_7 = Input_GetKeyDown_mEA57896808B6F484B12CD0AEEB83390A3CFCDBDC(((int32_t)49), /*hidden argument*/NULL); if (!L_7) { goto IL_0055; } } { // systemRenderer.enabled = !systemRenderer.enabled; Renderer_t0556D67DD582620D1F495627EDE30D03284151F4 * L_8 = __this->get_systemRenderer_8(); Renderer_t0556D67DD582620D1F495627EDE30D03284151F4 * L_9 = __this->get_systemRenderer_8(); NullCheck(L_9); bool L_10 = Renderer_get_enabled_m40E07BB15DA58D2EF6F6796C6778163107DD7E1B(L_9, /*hidden argument*/NULL); NullCheck(L_8); Renderer_set_enabled_m0933766657F2685BAAE3340B0A984C0E63925303(L_8, (bool)((((int32_t)L_10) == ((int32_t)0))? 1 : 0), /*hidden argument*/NULL); } IL_0055: { // foreach (var system in hoseWaterSystems) ParticleSystemU5BU5D_t58EE604F685D8CBA8EFC9353456969F5A1B2FBB9* L_11 = __this->get_hoseWaterSystems_7(); V_0 = L_11; V_1 = 0; goto IL_00a1; } IL_0060: { // foreach (var system in hoseWaterSystems) ParticleSystemU5BU5D_t58EE604F685D8CBA8EFC9353456969F5A1B2FBB9* L_12 = V_0; int32_t L_13 = V_1; NullCheck(L_12); int32_t L_14 = L_13; ParticleSystem_t45DA87A3E83E738DA3FDAA5A48A133F1A1247C3D * L_15 = (L_12)->GetAt(static_cast(L_14)); // ParticleSystem.MainModule mainModule = system.main; ParticleSystem_t45DA87A3E83E738DA3FDAA5A48A133F1A1247C3D * L_16 = L_15; NullCheck(L_16); MainModule_t99C675667E0A363368324132DFA34B27FFEE6FC7 L_17 = ParticleSystem_get_main_m360B0AA57C71DE0358B6B07133C68B5FD88C742F(L_16, /*hidden argument*/NULL); V_2 = L_17; // mainModule.startSpeed = m_Power; float L_18 = __this->get_m_Power_9(); MinMaxCurve_tDB335EDEBEBD4CFA753081D7C3A2FE2EECFA6D71 L_19 = MinMaxCurve_op_Implicit_m998EE9F8D83B9545F63E2DFA304E99620F0F707F(L_18, /*hidden argument*/NULL); MainModule_set_startSpeed_m32CD8968F2B5572112DE22CC7B6E2B502222B4AE((MainModule_t99C675667E0A363368324132DFA34B27FFEE6FC7 *)(&V_2), L_19, /*hidden argument*/NULL); // var emission = system.emission; NullCheck(L_16); EmissionModule_t35028C3DE5EFDCE49E8A9732460617A56BD1D3F1 L_20 = ParticleSystem_get_emission_mA1204EAF07A6C6B3F65B45295797A1FFF64D343C(L_16, /*hidden argument*/NULL); V_3 = L_20; // emission.enabled = (m_Power > minPower*1.1f); float L_21 = __this->get_m_Power_9(); float L_22 = __this->get_minPower_5(); EmissionModule_set_enabled_m3896B441BDE0F0752A6D113012B20D5D31B16D36((EmissionModule_t35028C3DE5EFDCE49E8A9732460617A56BD1D3F1 *)(&V_3), (bool)((((float)L_21) > ((float)((float)il2cpp_codegen_multiply((float)L_22, (float)(1.1f)))))? 1 : 0), /*hidden argument*/NULL); int32_t L_23 = V_1; V_1 = ((int32_t)il2cpp_codegen_add((int32_t)L_23, (int32_t)1)); } IL_00a1: { // foreach (var system in hoseWaterSystems) int32_t L_24 = V_1; ParticleSystemU5BU5D_t58EE604F685D8CBA8EFC9353456969F5A1B2FBB9* L_25 = V_0; NullCheck(L_25); if ((((int32_t)L_24) < ((int32_t)(((int32_t)((int32_t)(((RuntimeArray*)L_25)->max_length))))))) { goto IL_0060; } } { // } return; } } // System.Void UnityStandardAssets.Effects.Hose::.ctor() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Hose__ctor_mDB316C87F32CA6A88980009F13FCB35475103094 (Hose_t411AEC20AB5A70AEFCF03FCB2418F0C8EB14C2D2 * __this, const RuntimeMethod* method) { { // public float maxPower = 20; __this->set_maxPower_4((20.0f)); // public float minPower = 5; __this->set_minPower_5((5.0f)); // public float changeSpeed = 5; __this->set_changeSpeed_6((5.0f)); MonoBehaviour__ctor_mEAEC84B222C60319D593E456D769B3311DFCEF97(__this, /*hidden argument*/NULL); return; } } #ifdef __clang__ #pragma clang diagnostic pop #endif #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Void UnityStandardAssets.Effects.ParticleSystemMultiplier::Start() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void ParticleSystemMultiplier_Start_m9629829804A66FA8E1BA25039F0BCD4447D1785D (ParticleSystemMultiplier_t8EBFEF83EBA48DD7F6517ABFFBE2CD051CB2C748 * __this, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (ParticleSystemMultiplier_Start_m9629829804A66FA8E1BA25039F0BCD4447D1785D_MetadataUsageId); s_Il2CppMethodInitialized = true; } ParticleSystemU5BU5D_t58EE604F685D8CBA8EFC9353456969F5A1B2FBB9* V_0 = NULL; int32_t V_1 = 0; MainModule_t99C675667E0A363368324132DFA34B27FFEE6FC7 V_2; memset((&V_2), 0, sizeof(V_2)); { // var systems = GetComponentsInChildren(); ParticleSystemU5BU5D_t58EE604F685D8CBA8EFC9353456969F5A1B2FBB9* L_0 = Component_GetComponentsInChildren_TisParticleSystem_t45DA87A3E83E738DA3FDAA5A48A133F1A1247C3D_mD5AEF673286CB17B689F765BB71E83509548DC41(__this, /*hidden argument*/Component_GetComponentsInChildren_TisParticleSystem_t45DA87A3E83E738DA3FDAA5A48A133F1A1247C3D_mD5AEF673286CB17B689F765BB71E83509548DC41_RuntimeMethod_var); // foreach (ParticleSystem system in systems) V_0 = L_0; V_1 = 0; goto IL_006f; } IL_000b: { // foreach (ParticleSystem system in systems) ParticleSystemU5BU5D_t58EE604F685D8CBA8EFC9353456969F5A1B2FBB9* L_1 = V_0; int32_t L_2 = V_1; NullCheck(L_1); int32_t L_3 = L_2; ParticleSystem_t45DA87A3E83E738DA3FDAA5A48A133F1A1247C3D * L_4 = (L_1)->GetAt(static_cast(L_3)); // ParticleSystem.MainModule mainModule = system.main; ParticleSystem_t45DA87A3E83E738DA3FDAA5A48A133F1A1247C3D * L_5 = L_4; NullCheck(L_5); MainModule_t99C675667E0A363368324132DFA34B27FFEE6FC7 L_6 = ParticleSystem_get_main_m360B0AA57C71DE0358B6B07133C68B5FD88C742F(L_5, /*hidden argument*/NULL); V_2 = L_6; // mainModule.startSizeMultiplier *= multiplier; MainModule_t99C675667E0A363368324132DFA34B27FFEE6FC7 * L_7 = (&V_2); float L_8 = MainModule_get_startSizeMultiplier_m8E241099DB1E4ECE4827E9507415C80012AEA312((MainModule_t99C675667E0A363368324132DFA34B27FFEE6FC7 *)L_7, /*hidden argument*/NULL); float L_9 = __this->get_multiplier_4(); MainModule_set_startSizeMultiplier_m6375840B2CADFF82321D7B52103FADC5AD144B8C((MainModule_t99C675667E0A363368324132DFA34B27FFEE6FC7 *)L_7, ((float)il2cpp_codegen_multiply((float)L_8, (float)L_9)), /*hidden argument*/NULL); // mainModule.startSpeedMultiplier *= multiplier; MainModule_t99C675667E0A363368324132DFA34B27FFEE6FC7 * L_10 = (&V_2); float L_11 = MainModule_get_startSpeedMultiplier_m22326AF745786C1748F6B165361CCC26917F214A((MainModule_t99C675667E0A363368324132DFA34B27FFEE6FC7 *)L_10, /*hidden argument*/NULL); float L_12 = __this->get_multiplier_4(); MainModule_set_startSpeedMultiplier_m14E157EFF4BD78D8FDA701BE2BD0B398EF6F2453((MainModule_t99C675667E0A363368324132DFA34B27FFEE6FC7 *)L_10, ((float)il2cpp_codegen_multiply((float)L_11, (float)L_12)), /*hidden argument*/NULL); // mainModule.startLifetimeMultiplier *= Mathf.Lerp(multiplier, 1, 0.5f); MainModule_t99C675667E0A363368324132DFA34B27FFEE6FC7 * L_13 = (&V_2); float L_14 = MainModule_get_startLifetimeMultiplier_m0D425E7689C0B99C5B9E8F8C4AE205600C1EA529((MainModule_t99C675667E0A363368324132DFA34B27FFEE6FC7 *)L_13, /*hidden argument*/NULL); float L_15 = __this->get_multiplier_4(); IL2CPP_RUNTIME_CLASS_INIT(Mathf_tFBDE6467D269BFE410605C7D806FD9991D4A89CB_il2cpp_TypeInfo_var); float L_16 = Mathf_Lerp_m9A74C5A0C37D0CDF45EE66E7774D12A9B93B1364(L_15, (1.0f), (0.5f), /*hidden argument*/NULL); MainModule_set_startLifetimeMultiplier_mCD094E55BD574ECF3A8F5D616A2287130B6EC67B((MainModule_t99C675667E0A363368324132DFA34B27FFEE6FC7 *)L_13, ((float)il2cpp_codegen_multiply((float)L_14, (float)L_16)), /*hidden argument*/NULL); // system.Clear(); ParticleSystem_t45DA87A3E83E738DA3FDAA5A48A133F1A1247C3D * L_17 = L_5; NullCheck(L_17); ParticleSystem_Clear_mE11D3D0E23B1C5AAFF1F432E278ED91F1D929FEE(L_17, /*hidden argument*/NULL); // system.Play(); NullCheck(L_17); ParticleSystem_Play_m5BC5E6B56FCF639CAD5DF41B51DC05A0B444212F(L_17, /*hidden argument*/NULL); int32_t L_18 = V_1; V_1 = ((int32_t)il2cpp_codegen_add((int32_t)L_18, (int32_t)1)); } IL_006f: { // foreach (ParticleSystem system in systems) int32_t L_19 = V_1; ParticleSystemU5BU5D_t58EE604F685D8CBA8EFC9353456969F5A1B2FBB9* L_20 = V_0; NullCheck(L_20); if ((((int32_t)L_19) < ((int32_t)(((int32_t)((int32_t)(((RuntimeArray*)L_20)->max_length))))))) { goto IL_000b; } } { // } return; } } // System.Void UnityStandardAssets.Effects.ParticleSystemMultiplier::.ctor() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void ParticleSystemMultiplier__ctor_mFA383D5A7F8469462B1E9A5EDB01811D52DC0CFC (ParticleSystemMultiplier_t8EBFEF83EBA48DD7F6517ABFFBE2CD051CB2C748 * __this, const RuntimeMethod* method) { { // public float multiplier = 1; __this->set_multiplier_4((1.0f)); MonoBehaviour__ctor_mEAEC84B222C60319D593E456D769B3311DFCEF97(__this, /*hidden argument*/NULL); return; } } #ifdef __clang__ #pragma clang diagnostic pop #endif #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Void UnityStandardAssets.Effects.SmokeParticles::Start() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void SmokeParticles_Start_m1A4CBEB9EDF7F792FCF7F96D9435B6C0B0A94DD6 (SmokeParticles_t556E08200E5E25126D51BFF297C7522998E3D793 * __this, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (SmokeParticles_Start_m1A4CBEB9EDF7F792FCF7F96D9435B6C0B0A94DD6_MetadataUsageId); s_Il2CppMethodInitialized = true; } { // GetComponent().clip = extinguishSounds[Random.Range(0, extinguishSounds.Length)]; AudioSource_t5196F862B4E60F404613361C90D87FBDD041E93C * L_0 = Component_GetComponent_TisAudioSource_t5196F862B4E60F404613361C90D87FBDD041E93C_m04C8E98F2393C77979C9D8F6DE1D98343EF025E8(__this, /*hidden argument*/Component_GetComponent_TisAudioSource_t5196F862B4E60F404613361C90D87FBDD041E93C_m04C8E98F2393C77979C9D8F6DE1D98343EF025E8_RuntimeMethod_var); AudioClipU5BU5D_t03931BD44BC339329210676E452B8ECD3EC171C2* L_1 = __this->get_extinguishSounds_4(); AudioClipU5BU5D_t03931BD44BC339329210676E452B8ECD3EC171C2* L_2 = __this->get_extinguishSounds_4(); NullCheck(L_2); int32_t L_3 = Random_Range_mD0C8F37FF3CAB1D87AAA6C45130BD59626BD6780(0, (((int32_t)((int32_t)(((RuntimeArray*)L_2)->max_length)))), /*hidden argument*/NULL); NullCheck(L_1); int32_t L_4 = L_3; AudioClip_tCC3C35F579203CE2601243585AB3D6953C3BA051 * L_5 = (L_1)->GetAt(static_cast(L_4)); NullCheck(L_0); AudioSource_set_clip_mF574231E0B749E0167CAF9E4FCBA06BAA0F9ED9B(L_0, L_5, /*hidden argument*/NULL); // GetComponent().Play(); AudioSource_t5196F862B4E60F404613361C90D87FBDD041E93C * L_6 = Component_GetComponent_TisAudioSource_t5196F862B4E60F404613361C90D87FBDD041E93C_m04C8E98F2393C77979C9D8F6DE1D98343EF025E8(__this, /*hidden argument*/Component_GetComponent_TisAudioSource_t5196F862B4E60F404613361C90D87FBDD041E93C_m04C8E98F2393C77979C9D8F6DE1D98343EF025E8_RuntimeMethod_var); NullCheck(L_6); AudioSource_Play_m0BA206481892AA4AF7DB2900A0B0805076516164(L_6, /*hidden argument*/NULL); // } return; } } // System.Void UnityStandardAssets.Effects.SmokeParticles::.ctor() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void SmokeParticles__ctor_m6FF23CF3C3FFDCE57F75C6DA08F84101A4953F0C (SmokeParticles_t556E08200E5E25126D51BFF297C7522998E3D793 * __this, const RuntimeMethod* method) { { MonoBehaviour__ctor_mEAEC84B222C60319D593E456D769B3311DFCEF97(__this, /*hidden argument*/NULL); return; } } #ifdef __clang__ #pragma clang diagnostic pop #endif #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Void UnityStandardAssets.Effects.WaterHoseParticles::Start() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void WaterHoseParticles_Start_m6CFC5FEBF60CBD00CDE17E0A1EEC12163EC9A792 (WaterHoseParticles_t4C0EC93AEAF5B1623A7F04AF7D912D6B6438E92B * __this, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (WaterHoseParticles_Start_m6CFC5FEBF60CBD00CDE17E0A1EEC12163EC9A792_MetadataUsageId); s_Il2CppMethodInitialized = true; } { // m_ParticleSystem = GetComponent(); ParticleSystem_t45DA87A3E83E738DA3FDAA5A48A133F1A1247C3D * L_0 = Component_GetComponent_TisParticleSystem_t45DA87A3E83E738DA3FDAA5A48A133F1A1247C3D_mA6EBF435A59643B674086A2F309F6A4DCB263452(__this, /*hidden argument*/Component_GetComponent_TisParticleSystem_t45DA87A3E83E738DA3FDAA5A48A133F1A1247C3D_mA6EBF435A59643B674086A2F309F6A4DCB263452_RuntimeMethod_var); __this->set_m_ParticleSystem_7(L_0); // } return; } } // System.Void UnityStandardAssets.Effects.WaterHoseParticles::OnParticleCollision(UnityEngine.GameObject) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void WaterHoseParticles_OnParticleCollision_m8E8399822017058F9AE64E3D9F7B47208553ED70 (WaterHoseParticles_t4C0EC93AEAF5B1623A7F04AF7D912D6B6438E92B * __this, GameObject_tBD1244AD56B4E59AAD76E5E7C9282EC5CE434F0F * ___other0, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (WaterHoseParticles_OnParticleCollision_m8E8399822017058F9AE64E3D9F7B47208553ED70_MetadataUsageId); s_Il2CppMethodInitialized = true; } int32_t V_0 = 0; int32_t V_1 = 0; Rigidbody_tE0A58EE5A1F7DC908EFFB4F0D795AC9552A750A5 * V_2 = NULL; ParticleCollisionEvent_t7F4D7D5ACF8521671549D9328D4E2DDE480D8D47 V_3; memset((&V_3), 0, sizeof(V_3)); Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 V_4; memset((&V_4), 0, sizeof(V_4)); { // int numCollisionEvents = m_ParticleSystem.GetCollisionEvents(other, m_CollisionEvents); ParticleSystem_t45DA87A3E83E738DA3FDAA5A48A133F1A1247C3D * L_0 = __this->get_m_ParticleSystem_7(); GameObject_tBD1244AD56B4E59AAD76E5E7C9282EC5CE434F0F * L_1 = ___other0; List_1_t2762C811E470D336E31761384C6E5382164DA4C7 * L_2 = __this->get_m_CollisionEvents_6(); int32_t L_3 = ParticlePhysicsExtensions_GetCollisionEvents_m11DDE18328B0E4B9766D1581DFCB0E67BCFD097C(L_0, L_1, L_2, /*hidden argument*/NULL); V_0 = L_3; // int i = 0; V_1 = 0; goto IL_0090; } IL_0017: { // if (Time.time > lastSoundTime + 0.2f) float L_4 = Time_get_time_m7863349C8845BBA36629A2B3F8EF1C3BEA350FD8(/*hidden argument*/NULL); float L_5 = ((WaterHoseParticles_t4C0EC93AEAF5B1623A7F04AF7D912D6B6438E92B_StaticFields*)il2cpp_codegen_static_fields_for(WaterHoseParticles_t4C0EC93AEAF5B1623A7F04AF7D912D6B6438E92B_il2cpp_TypeInfo_var))->get_lastSoundTime_4(); if ((!(((float)L_4) > ((float)((float)il2cpp_codegen_add((float)L_5, (float)(0.2f))))))) { goto IL_0033; } } { // lastSoundTime = Time.time; float L_6 = Time_get_time_m7863349C8845BBA36629A2B3F8EF1C3BEA350FD8(/*hidden argument*/NULL); ((WaterHoseParticles_t4C0EC93AEAF5B1623A7F04AF7D912D6B6438E92B_StaticFields*)il2cpp_codegen_static_fields_for(WaterHoseParticles_t4C0EC93AEAF5B1623A7F04AF7D912D6B6438E92B_il2cpp_TypeInfo_var))->set_lastSoundTime_4(L_6); } IL_0033: { // var col = m_CollisionEvents[i].colliderComponent; List_1_t2762C811E470D336E31761384C6E5382164DA4C7 * L_7 = __this->get_m_CollisionEvents_6(); int32_t L_8 = V_1; NullCheck(L_7); ParticleCollisionEvent_t7F4D7D5ACF8521671549D9328D4E2DDE480D8D47 L_9 = List_1_get_Item_m095B750642DEE222CA241EE9D2392CA6E200FA8D_inline(L_7, L_8, /*hidden argument*/List_1_get_Item_m095B750642DEE222CA241EE9D2392CA6E200FA8D_RuntimeMethod_var); V_3 = L_9; Component_t05064EF382ABCAF4B8C94F8A350EA85184C26621 * L_10 = ParticleCollisionEvent_get_colliderComponent_mE4A94CAC6A2875588395DCB76FB7978A72796B82((ParticleCollisionEvent_t7F4D7D5ACF8521671549D9328D4E2DDE480D8D47 *)(&V_3), /*hidden argument*/NULL); // var attachedRigidbody = col.GetComponent(); NullCheck(L_10); Rigidbody_tE0A58EE5A1F7DC908EFFB4F0D795AC9552A750A5 * L_11 = Component_GetComponent_TisRigidbody_tE0A58EE5A1F7DC908EFFB4F0D795AC9552A750A5_m3F58A77E3F62D9C80D7B49BA04E3D4809264FD5C(L_10, /*hidden argument*/Component_GetComponent_TisRigidbody_tE0A58EE5A1F7DC908EFFB4F0D795AC9552A750A5_m3F58A77E3F62D9C80D7B49BA04E3D4809264FD5C_RuntimeMethod_var); V_2 = L_11; // if (attachedRigidbody != null) Rigidbody_tE0A58EE5A1F7DC908EFFB4F0D795AC9552A750A5 * L_12 = V_2; IL2CPP_RUNTIME_CLASS_INIT(Object_tAE11E5E46CD5C37C9F3E8950C00CD8B45666A2D0_il2cpp_TypeInfo_var); bool L_13 = Object_op_Inequality_m31EF58E217E8F4BDD3E409DEF79E1AEE95874FC1(L_12, (Object_tAE11E5E46CD5C37C9F3E8950C00CD8B45666A2D0 *)NULL, /*hidden argument*/NULL); if (!L_13) { goto IL_0080; } } { // Vector3 vel = m_CollisionEvents[i].velocity; List_1_t2762C811E470D336E31761384C6E5382164DA4C7 * L_14 = __this->get_m_CollisionEvents_6(); int32_t L_15 = V_1; NullCheck(L_14); ParticleCollisionEvent_t7F4D7D5ACF8521671549D9328D4E2DDE480D8D47 L_16 = List_1_get_Item_m095B750642DEE222CA241EE9D2392CA6E200FA8D_inline(L_14, L_15, /*hidden argument*/List_1_get_Item_m095B750642DEE222CA241EE9D2392CA6E200FA8D_RuntimeMethod_var); V_3 = L_16; Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 L_17 = ParticleCollisionEvent_get_velocity_m60BCDF44F8F345C3534705CBA2BD5E69346021A3((ParticleCollisionEvent_t7F4D7D5ACF8521671549D9328D4E2DDE480D8D47 *)(&V_3), /*hidden argument*/NULL); V_4 = L_17; // attachedRigidbody.AddForce(vel*force, ForceMode.Impulse); Rigidbody_tE0A58EE5A1F7DC908EFFB4F0D795AC9552A750A5 * L_18 = V_2; Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 L_19 = V_4; float L_20 = __this->get_force_5(); IL2CPP_RUNTIME_CLASS_INIT(Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720_il2cpp_TypeInfo_var); Vector3_tDCF05E21F632FE2BA260C06E0D10CA81513E6720 L_21 = Vector3_op_Multiply_m1C5F07723615156ACF035D88A1280A9E8F35A04E(L_19, L_20, /*hidden argument*/NULL); NullCheck(L_18); Rigidbody_AddForce_mD64ACF772614FE36CFD8A477A07A407B35DF1A54(L_18, L_21, 1, /*hidden argument*/NULL); } IL_0080: { // other.BroadcastMessage("Extinguish", SendMessageOptions.DontRequireReceiver); GameObject_tBD1244AD56B4E59AAD76E5E7C9282EC5CE434F0F * L_22 = ___other0; NullCheck(L_22); GameObject_BroadcastMessage_mABB308EA1B7F641BFC60E091A75E5E053D23A8B5(L_22, _stringLiteral4796C2FBF2E7B58822864E6AA158FDAF94586F93, 1, /*hidden argument*/NULL); // i++; int32_t L_23 = V_1; V_1 = ((int32_t)il2cpp_codegen_add((int32_t)L_23, (int32_t)1)); } IL_0090: { // while (i < numCollisionEvents) int32_t L_24 = V_1; int32_t L_25 = V_0; if ((((int32_t)L_24) < ((int32_t)L_25))) { goto IL_0017; } } { // } return; } } // System.Void UnityStandardAssets.Effects.WaterHoseParticles::.ctor() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void WaterHoseParticles__ctor_m9E63BF105FF8511932CBF7FAA1C664713744DCA3 (WaterHoseParticles_t4C0EC93AEAF5B1623A7F04AF7D912D6B6438E92B * __this, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (WaterHoseParticles__ctor_m9E63BF105FF8511932CBF7FAA1C664713744DCA3_MetadataUsageId); s_Il2CppMethodInitialized = true; } { // public float force = 1; __this->set_force_5((1.0f)); // private List m_CollisionEvents = new List(); List_1_t2762C811E470D336E31761384C6E5382164DA4C7 * L_0 = (List_1_t2762C811E470D336E31761384C6E5382164DA4C7 *)il2cpp_codegen_object_new(List_1_t2762C811E470D336E31761384C6E5382164DA4C7_il2cpp_TypeInfo_var); List_1__ctor_m377714278A7FAB4D7514D181355D61B01B3427B0(L_0, /*hidden argument*/List_1__ctor_m377714278A7FAB4D7514D181355D61B01B3427B0_RuntimeMethod_var); __this->set_m_CollisionEvents_6(L_0); MonoBehaviour__ctor_mEAEC84B222C60319D593E456D769B3311DFCEF97(__this, /*hidden argument*/NULL); return; } } #ifdef __clang__ #pragma clang diagnostic pop #endif IL2CPP_EXTERN_C inline IL2CPP_METHOD_ATTR RuntimeObject * Enumerator_get_Current_mD7829C7E8CFBEDD463B15A951CDE9B90A12CC55C_gshared_inline (Enumerator_tE0C99528D3DCE5863566CE37BD94162A4C0431CD * __this, const RuntimeMethod* method) { { RuntimeObject * L_0 = (RuntimeObject *)__this->get_current_3(); return (RuntimeObject *)L_0; } } IL2CPP_EXTERN_C inline IL2CPP_METHOD_ATTR ParticleCollisionEvent_t7F4D7D5ACF8521671549D9328D4E2DDE480D8D47 List_1_get_Item_m095B750642DEE222CA241EE9D2392CA6E200FA8D_gshared_inline (List_1_t2762C811E470D336E31761384C6E5382164DA4C7 * __this, int32_t ___index0, const RuntimeMethod* method) { { int32_t L_0 = ___index0; int32_t L_1 = (int32_t)__this->get__size_2(); if ((!(((uint32_t)L_0) >= ((uint32_t)L_1)))) { goto IL_000e; } } { ThrowHelper_ThrowArgumentOutOfRangeException_mBA2AF20A35144E0C43CD721A22EAC9FCA15D6550(/*hidden argument*/NULL); } IL_000e: { ParticleCollisionEventU5BU5D_t771CB4A499CC97F3340C673D227DD1F5969EB9B9* L_2 = (ParticleCollisionEventU5BU5D_t771CB4A499CC97F3340C673D227DD1F5969EB9B9*)__this->get__items_1(); int32_t L_3 = ___index0; ParticleCollisionEvent_t7F4D7D5ACF8521671549D9328D4E2DDE480D8D47 L_4 = IL2CPP_ARRAY_UNSAFE_LOAD((ParticleCollisionEventU5BU5D_t771CB4A499CC97F3340C673D227DD1F5969EB9B9*)L_2, (int32_t)L_3); return (ParticleCollisionEvent_t7F4D7D5ACF8521671549D9328D4E2DDE480D8D47 )L_4; } } mmap_lib/tests/bench_vset_use.cpp // This file is distributed under the BSD 3-Clause License. See LICENSE for details. #include #include #include "flat_hash_map.hpp" #include "fmt/format.h" #include "iassert.hpp" #include "lbench.hpp" #include "lrand.hpp" #include "mmap_map.hpp" #include "mmap_vset.hpp" #define BENCH_OUT_SIZE 100 #define BENCH_INN_SIZE 100 #define IED 1 #define TS 1 #define TD 1 #define PROBLEM 1 int main(int argc, char** argv) { std::cout << "hello world!\n"; return 0; } #if 0 void random_mmap_set(int max, std::string_view name) { Lrand rng; std::string type_test("mmap.map_set"); if (name.empty()) type_test += "_effemeral_" + std::to_string(max); else type_test += "_persistent_" + std::to_string(max); Lbench b(type_test); mmap_lib::map map(name.empty() ? "" : "lgdb_bench", name); int cntconta = 0, hitconta = 0, missconta = 0; #if IED for (int n = 1; n < BENCH_OUT_SIZE; ++n) { for (int i = 0; i < BENCH_INN_SIZE; ++i) { auto pos = rng.max(max); map.set(pos, true); pos = rng.max(max); map.erase(pos); pos = rng.max(max); if (map.find(pos) != map.end()) { map.erase(pos); ++hitconta; } else { ++missconta; } } } b.sample("insert/erase dense"); printf("hit %d, missed %d\n", hitconta, missconta); #endif #if TS missconta = 0, hitconta = 0; for (int i = 0; i < BENCH_INN_SIZE; ++i) { for (auto it = map.begin(), end = map.end(); it != end; ++it) { cntconta++; } map.set(rng.max(max), true); auto pos = rng.max(max); if (map.find(pos) != map.end()) { ++hitconta; map.erase(pos); } else { ++missconta; } } b.sample("traversal sparse"); printf("traversed %d, hit %d, miss %d\n", cntconta, hitconta, missconta); #endif #if TD cntconta = 0; for (int i = 0; i < max; ++i) { map.erase(rng.max(max)); map.erase(rng.max(max)); map.erase(rng.max(max)); map.erase(rng.max(max)); } for (int i = 0; i < BENCH_INN_SIZE; ++i) { for (auto it = map.begin(), end = map.end(); it != end; ++it) { cntconta++; } } b.sample("traversal dense"); printf("traversed %d\n", cntconta); #endif } //===== template void test_vset_erase(mmap_lib::vset& temp) { temp.clear(); } //===== /* Creates a vset from mmap_lib namespace */ void random_mmap_vset(int max, std::string_view name) { Lrand rng; std::string type_test("mmap_vset "); if (name.empty()) { type_test += "_effemeral_" + std::to_string(max); } else { type_test += "_persistent_" + std::to_string(max); } Lbench b(type_test); mmap_lib::vset set("lgdb_bench", name); // set.clear(); int hitconta = 0, missconta = 0, cntconta = 0; // reset #if IED // INSERT/ERASE DENSE TEST // runs about (BIG * SMALL) times // each run: // --> generate rand num, insert that num into the map // --> generate another rand num, erase that num from the map // --> generate another rand num, if this num is not the end of the map, erase for (int n = 1; n < BENCH_OUT_SIZE; ++n) { for (int i = 0; i < BENCH_INN_SIZE; ++i) { auto pos = rng.max(max); set.insert(pos); pos = rng.max(max); set.erase(pos); pos = rng.max(max); if (set.find(pos) != set.end()) { ++hitconta; set.erase(pos); } else { ++missconta; } } } b.sample("insert/erase dense"); printf("hit %d, missed %d\n", hitconta, missconta); #endif #if TS hitconta = 0, missconta = 0; // TRAVERSAL SPARSE TEST // runs (200) times // each run: // --> go through the whole map and increment a variable per map index // --> insert a random number into map // --> generate a random num, if num is not end of map, erase it for (int i = 0; i < BENCH_INN_SIZE; ++i) { #if PROBLEM for (auto it = set.begin(), end = set.end(); it != end; ++it) { cntconta++; } #endif set.insert(rng.max(max)); auto pos = rng.max(max); if (set.find(pos) != set.end()) { ++hitconta; set.erase(pos); } else { ++missconta; } } b.sample("traversal sparse"); printf("traversed %d, hit %d, missed %d\n", cntconta, hitconta, missconta); #endif #if TD cntconta = 0, hitconta = 0, missconta = 0; // TRAVERSAL DENSE TEST // --> First, for every num in domain of max, generate 4 random nums and erase them from map // --> runs (200) times -> each time go through whole map and incrememt number per map index for (int i = 0; i < max; ++i) { set.erase(rng.max(max)); set.erase(rng.max(max)); set.erase(rng.max(max)); set.erase(rng.max(max)); } for (int i = 0; i < BENCH_INN_SIZE; ++i) { #if PROBLEM for (auto it = set.begin(), end = set.end(); it != end; ++it) { cntconta++; } #endif } b.sample("traversal dense"); printf("traversed %d\n", cntconta); #endif } int main(int argc, char** argv) { bool run_random_mmap_set = false; bool run_random_mmap_vset = false; if (argc > 1) { if (strcasecmp(argv[1], "mmap") == 0) run_random_mmap_set = true; else if (strcasecmp(argv[1], "vset") == 0) run_random_mmap_vset = true; } else { run_random_mmap_set = true; run_random_mmap_vset = true; } for (int i = 1000; i < 1'000'001; i *= 1000) { printf("-----------------------------------------------\n"); printf(" %d max\n", i); if (run_random_mmap_set) { random_mmap_set(i, ""); random_mmap_set(i, "mmap_map_set.data"); } if (run_random_mmap_vset) { random_mmap_vset(i, ""); random_mmap_vset(i, "mmap_map_set.data"); } } return 0; } #if 0 /* * Creates a vset from mmap_lib namespace * And tests it a little */ void mmap_vset(int max, std::string_view name) { Lrand rng; std::string type_test("mmap_vset "); if (name.empty()) { type_test += "(effemeral)"; } else { type_test += "(persistent)"; } Lbench b(type_test); mmap_lib::vset set("lgdb_bench", name); //mmap_lib::map map("lgdb_bench", name); set.clear(); /* for (auto j = 0; j < 50; ++j) { set.insert(j); } for (auto i = set.begin(); i != set.end(); ++i) { //std::cout << i.iter_val() << " "; } //std::cout << std::endl; for (auto i = 0; i < 49; ++i) { auto pos = rng.max(set.get_max()); while (!(set.efind(pos))) { pos = rng.max(set.get_max()); } set.erase(pos); for (auto i : set) { //std::cout << i << " "; } //std::cout << std::endl; } */ //========================= int conta = 0; #if 0 // counting std::cout << "Counting... "; for (auto it = set.bucket_begin(), end = set.bucket_end(); it != end; ++it) { auto hold = set.bucket_get_val(it); for (auto j = 0; j < set.bucket_size(); ++j) { if ((hold & 1) == 1) { conta++; } hold = hold >> 1; } } std::cout << "Initial conta: " << conta << "\n\n"; std::cout << "Inserting 0 - " << (SMALL_BENCH-1) << " into vset...\n"; for(int i = 0; i < SMALL_BENCH; ++i) { set.insert(i); } std::cout << "Counting... "; for (auto it = set.bucket_begin(), end = set.bucket_end(); it != end; ++it) { auto hold = set.bucket_get_val(it); for (auto j = 0; j < set.bucket_size(); ++j) { if ((hold & 1) == 1) { conta++; } hold = hold >> 1; } } std::cout << "After insert conta: " << conta << "\n\n"; conta = 0; // reset std::cout << "Erasing 0 - " << (SMALL_BENCH-1) << " from vset...\n"; for(int i = 0; i < SMALL_BENCH; ++i) { set.erase(i); } std::cout << "Counting... "; for (auto it = set.bucket_begin(), end = set.bucket_end(); it != end; ++it) { auto hold = set.bucket_get_val(it); for (auto j = 0; j < set.bucket_size(); ++j) { if ((hold & 1) == 1) { conta++; } hold = hold >> 1; } } std::cout << "After erase conta: " << conta << std::endl; conta = 0; // reset std::cout << "sanity check (printing bucket_len): " << set.bucket_size() << std::endl; std::cout << "===== vset BENCH =====" << std::endl; std::cout << "===== Insert/Erase 0-299\n"; for(int i = 0; i <= SMALL_BENCH; ++i) { set.insert(i); } std::cout << "Using iterator to traverse after inserts" << std::endl; for (auto it = set.begin(), e = set.end(); it != e; ++it) { std::cout << it.iter_val() << " ";} for(int i = 0; i < SMALL_BENCH; ++i) { set.erase(i); } std::cout << "Using iterator to traverse after deletes" << std::endl; for (auto it = set.begin(), e = set.end(); it != e; ++it) { std::cout << it.iter_val() << " ";} #endif /* std::cout << "===== vset BENCH =====" << std::endl; std::cout << "===== Insert/Erase Dense\n"; // INSERT/ERASE DENSE TEST // runs about (BIG * SMALL) times // each run: // --> generate rand num, insert that num into the map // --> generate another rand num, erase that num from the map // --> generate another rand num, if this num is not the end of the map, erase for (int n = 1; n < BIG_BENCH; ++n) { for (int i = 0; i < SMALL_BENCH; ++i) { auto pos = rng.max(max); set.insert(pos); pos = rng.max(max); set.erase(pos); pos = rng.max(max); if (set.find(pos) != set.end()) { set.erase(pos); } } } b.sample("insert/erase dense"); conta = 0; std::cout << "===== Traversal Sparse\n"; // TRAVERSAL SPARSE TEST // runs (200) times // each run: // --> go through the whole map and increment a variable per map index // --> insert a random number into map // --> generate a random num, if num is not end of map, erase it for (int i = 0; i < SMALL_BENCH; ++i) { for (auto it = set.begin(), end = set.end(); it != end; ++it) { conta++; } set.insert(rng.max(max)); auto pos = rng.max(max); if (set.find(pos) != set.end()) { set.erase(pos); } } b.sample("traversal sparse"); printf("inserts random %d\n", conta); conta = 0; std::cout << "===== Traversal Dense\n"; // TRAVERSAL DENSE TEST // --> First, for every num in domain of max, generate 4 random nums and erase them from map // --> runs (200) times -> each time go through whole map and incrememt number per map index for (int i = 0; i < max; ++i) { set.erase(rng.max(max)); set.erase(rng.max(max)); set.erase(rng.max(max)); set.erase(rng.max(max)); } for (int i = 0; i < SMALL_BENCH; ++i) { for (auto it = set.begin(), end = set.end(); it != end; ++it) { conta++; } } b.sample("traversal dense"); printf("inserts random %d\n",conta); */ } int main(int argc, char **argv) { bool run_mmap_vset = false; if (argc>1) { if (strcasecmp(argv[1],"vset") == 0) { run_mmap_vset = true; } } else { run_mmap_vset = true; } if (run_mmap_vset) { mmap_vset(1000, "bench_map_use_mmap.data"); } return 0; } #endif #endif #include #include #include #include #include using namespace neneta; using namespace neneta::imh; TEST(ImangeNetDatabase, db_tests) { conf::ConfigurationReader envReader("configuration_test.xml"); ImageNetDatabase db(envReader); auto batch = db.getNextBatch(); std::string path; db.getNextImage(batch, path); std::cout << path << std::endl; db.getNextImage(batch+1, path); std::cout << path << std::endl; } David-McKenna/lump-lofar-und-mpifr-pulsare // LOFAR_Station_Complex.cxx // code for LOFAR Complex data types //_HIST DATE NAME PLACE INFO // 2011 Mar 23 --MPIfR Start // 2014 Sep 04 JMA ---- update for getting the max size of any supported type // Copyright (c) 2011, 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. // INCLUDES #define LOFAR_Station_Complex_H_FILE #ifndef __STDC_CONSTANT_MACROS # define __STDC_CONSTANT_MACROS #endif #ifndef __STDC_LIMIT_MACROS # define __STDC_LIMIT_MACROS #endif #ifndef _ISOC99_SOURCE # define _ISOC99_SOURCE #endif #ifndef _GNU_SOURCE # define _GNU_SOURCE 1 #endif #ifndef __USE_ISOC99 # define __USE_ISOC99 1 #endif #ifndef _ISOC99_SOURCE # define _ISOC99_SOURCE #endif #ifndef __USE_MISC # define __USE_MISC 1 #endif #ifdef HAVE_CONFIG_H # include "config.h" #endif #include "LOFAR_Station_Complex.h" #include #include #include "JMA_math.h" #include "MPIfR_Real16_t.h" #include "MPIfR_logging.h" // set up a namespace area for stuff. namespace MPIfR { namespace LOFAR { // GLOBALS // FUNCTIONS size_t LOFAR_raw_data_type_enum_size(LOFAR_raw_data_type_enum type) throw() { switch(type) { case L_int8_t: return sizeof(int8_t); case L_int16_t: return sizeof(int16_t); case L_int32_t: return sizeof(int32_t); case L_int64_t: return sizeof(int64_t); #ifdef JMA_CODE_HAVE_NATIVE_128_BIT_INT case L_int128_t: return sizeof(int128_t); #endif // JMA_CODE_HAVE_NATIVE_128_BIT_INT case L_Real16_t: return sizeof(MPIfR::DATA_TYPE::Real16_t); case L_Real32_t: return sizeof(Real32_t); case L_Real64_t: return sizeof(Real64_t); #ifdef JMA_CODE_HAVE_NATIVE_80_BIT_FLOAT case L_Real80_t: return sizeof(Real80_t); #endif // JMA_CODE_HAVE_NATIVE_80_BIT_FLOAT #ifdef JMA_CODE_HAVE_NATIVE_128_BIT_FLOAT case L_Real128_t: return sizeof(Real128_t); #endif // JMA_CODE_HAVE_NATIVE_128_BIT_FLOAT case L_Complex64_t: return sizeof(Complex64_t); case L_Complex128_t: return sizeof(Complex128_t); #ifdef JMA_CODE_HAVE_NATIVE_80_BIT_FLOAT case L_Complex160_t: return sizeof(Complex160_t); #endif // JMA_CODE_HAVE_NATIVE_80_BIT_FLOAT #ifdef JMA_CODE_HAVE_NATIVE_128_BIT_FLOAT case L_Complex256_t: return sizeof(Complex256_t); #endif // JMA_CODE_HAVE_NATIVE_128_BIT_FLOAT case L_intComplex8_t: return sizeof(intComplex8_t); case L_intComplex16_t: return sizeof(intComplex16_t); case L_intComplex32_t: return sizeof(intComplex32_t); case L_intComplex64_t: return sizeof(intComplex64_t); case L_intComplex128_t: return sizeof(intComplex128_t); #ifdef JMA_CODE_HAVE_NATIVE_128_BIT_INT case L_intComplex256_t: return sizeof(intComplex256_t); #endif // JMA_CODE_HAVE_NATIVE_128_BIT_INT // case : // return sizeof(); // case : // return sizeof(); // case : // return sizeof(); // case : // return sizeof(); // case : // return sizeof(); // case : // return sizeof(); // case : // return sizeof(); // case : // return sizeof(); case L_RAW_DATA_TYPE_MAX: // the maximum size of any of the supported data types return 32; default: DEF_LOGGING_CRITICAL("Unrecognized LOFAR data type %d for size function\n", int(type)); exit(1); } return 0; } const char* const restrict LOFAR_raw_data_type_enum_Str(LOFAR_raw_data_type_enum e) throw() { switch(e) { #define LOFAR_ENUM_VALS(Enum, Val, String) case Enum: return String; LOFAR_raw_data_type_enum_Array; #undef LOFAR_ENUM_VALS default: return "Unknown LOFAR_raw_data_type_enum"; } return NULL; } } // end namespace LOFAR } // end namespace MPIfR include/scenes/gamescenemanager.hpp #ifndef _GAMESCENEMANAGER_HPP_ #define _GAMESCENEMANAGER_HPP_ #include #include "entities/camera.hpp" #include "entities/cutscene/cutscene.hpp" class GameSceneManager{ private: Camera camera; public: GameSceneManager(); void resetCameraPosition(); void setCameraToPlayer(const Player& player, sf::Vector2u levelSize); void setCameraToWindow(sf::RenderWindow& window); void setSpritePositionRelativeToCamera(sf::Transformable& sprite, float xrule, float yrule); float getCameraPointRelativeToCenterX(float offsetx = 0.f); float getCameraPointRelativeToCenterY(float offsety = 0.f); sf::Vector2f getCameraSize(); Camera getCamera(); }; #endifsamples/crush/src/MapData.cpp /*----------------------------------------------------------------------- 2021 http://trederia.blogspot.com crogine application - Zlib license. 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 "MapData.hpp" #include "CommonConsts.hpp" #include #include namespace { constexpr float MinGroundThickness = 2.f; } MapData::MapData() { } //public bool MapData::loadFromFile(const std::string& path, bool binary) { m_collisionRects[0].clear(); m_collisionRects[1].clear(); m_teleportRects[0].clear(); m_teleportRects[1].clear(); m_crateSpawns[0].clear(); m_crateSpawns[1].clear(); m_playerSpawns.clear(); if (!binary) { tmx::Map map; if (map.load(path)) { const float mapWidth = static_cast(map.getTileCount().x * map.getTileSize().x); const float mapHeight = static_cast(map.getTileCount().y * map.getTileSize().y); const auto& layers = map.getLayers(); for (const auto& layer : layers) { if (layer->getType() == tmx::Layer::Type::Object) { const auto& name = layer->getName(); if (name == "collision" && m_collisionRects[0].empty()) { const auto& rects = layer->getLayerAs().getObjects(); for (const auto& rect : rects) { if (rect.getShape() == tmx::Object::Shape::Rectangle) { auto bounds = rect.getAABB(); cro::FloatRect collisionBounds = { bounds.left, mapHeight - (bounds.top + bounds.height), bounds.width, bounds.height }; collisionBounds.left -= mapWidth / 2.f; collisionBounds.left /= ConstVal::MapUnits; collisionBounds.bottom /= ConstVal::MapUnits; collisionBounds.width /= ConstVal::MapUnits; collisionBounds.height /= ConstVal::MapUnits; auto type = rect.getType(); if (type == "Collision") { //make sure ground surface meets the minimum thickness if (collisionBounds.bottom <= 0) { collisionBounds.bottom -= MinGroundThickness; collisionBounds.height += MinGroundThickness; } m_collisionRects[0].push_back(collisionBounds); } else if (type == "Teleport") { m_teleportRects[0].push_back(collisionBounds); } else if (type == "Crate") { m_crateSpawns[0].emplace_back(collisionBounds.left + (collisionBounds.width / 2.f), collisionBounds.bottom + (collisionBounds.height / 2.f)); } else if (type == "Spawn Base") { m_playerSpawns.emplace_back(collisionBounds.left + (collisionBounds.width / 2.f), collisionBounds.bottom); } } } } } } #ifdef CRO_DEBUG_ if (m_collisionRects[0].empty()) { LogE << "No collision data was loaded from the map file" << std::endl; } if (m_playerSpawns.size() != 4) { LogE << "Player spawn points was " << m_playerSpawns.size() << std::endl; } #endif //dupe the rects just to test other layer building m_collisionRects[1] = m_collisionRects[0]; m_teleportRects[1] = m_teleportRects[0]; m_crateSpawns[1] = m_crateSpawns[0]; return (!m_collisionRects[0].empty() && !m_teleportRects.empty() && m_playerSpawns.size() == 4); } } else { //TODO } return false; }numgeom/wlslib-cpp // Copyright 2022 The NumGeom Group, Stony Brook University // Main developers: // wlslib: , , // momp2cpp: , // // rrqr_trunc.cpp // // Code generation for function 'rrqr_trunc' // // Include files #include "rrqr_trunc.h" #include "coder_array.h" #include "m2c_lib.h" #include #include // Function Definitions namespace wls { // rrqr_trunc Truncate the output from QRCP based on DAG void rrqr_trunc(const ::coder::array &dag, int *n1, int rank, ::coder::array &p, ::coder::array &work, boolean_T *permuted) { int b_i; int child; int n; int nChanged; n = dag.size(1) - 2; // Last column of dag is for signature work.set_size(4, dag.size(1) - 1); // compute inverse permutation and tag whether each column is truncated for (int i{0}; i <= n; i++) { work[4 * (p[i] - 1)] = i + 1; // first column for inverse permute work[4 * (p[i] - 1) + 1] = i + 1 > rank; // second column for tagging truncation work[4 * i + 3] = 0; // third column for stack, and last column for marks } nChanged = -1; // If a truncated monomial has an untruncated child, do not truncate it. b_i = rank + 1; for (int i{b_i}; i <= *n1; i++) { int c_tmp; c_tmp = p[i - 1] - 1; if (work[4 * c_tmp + 1] != 0) { int i1; i1 = dag.size(0); for (int j{0}; j < i1; j++) { child = c_tmp + dag[j + dag.size(0) * c_tmp]; if ((dag[j + dag.size(0) * c_tmp] != 0) && (work[4 * child + 1] != 1)) { if (work[4 * child] <= rank) { work[4 * child + 1] = -1; if (work[4 * child + 3] == 0) { nChanged++; work[4 * nChanged + 2] = child + 1; work[4 * child + 3] = 1; } } work[4 * c_tmp + 1] = 0; } } } } *permuted = nChanged + 1 != 0; // If a monomial is truncated but some of its children are not, then make while (nChanged + 1 != 0) { int c; boolean_T allChildrenTruncated; c = work[4 * nChanged + 2] - 1; nChanged--; // Make sure all the untruncated children of a candidate monomial allChildrenTruncated = true; b_i = dag.size(0); for (int j{0}; j < b_i; j++) { if (dag[j + dag.size(0) * c] != 0) { child = c + dag[j + dag.size(0) * c]; if (work[4 * child] <= rank) { allChildrenTruncated = false; if (work[4 * child + 1] != -1) { work[4 * child + 1] = -1; if (work[4 * child + 3] == 0) { nChanged++; work[4 * nChanged + 2] = child + 1; work[4 * child + 3] = 1; } } } } } if (!allChildrenTruncated) { work[4 * c + 1] = 0; } } if (*permuted) { int n2; // permute the truncated columns to the end *n1 = 0; n2 = dag.size(1) - 1; for (int i{0}; i <= n; i++) { // i is original ids if (work[4 * i + 1] == 0) { (*n1)++; p[*n1 - 1] = i + 1; } else { p[n2 - 1] = i + 1; n2--; } } m2cAssert(*n1 == n2, "Post-condition check failed"); } } } // namespace wls // End of code generation (rrqr_trunc.cpp) // Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/app_list/arc/arc_app_utils.h" #include #include #include "ash/shell.h" #include "base/json/json_writer.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_split.h" #include "base/strings/string_util.h" #include "base/synchronization/waitable_event.h" #include "base/values.h" #include "chrome/browser/chromeos/arc/arc_migration_guide_notification.h" #include "chrome/browser/chromeos/arc/arc_session_manager.h" #include "chrome/browser/chromeos/arc/arc_util.h" #include "chrome/browser/chromeos/arc/boot_phase_monitor/arc_boot_phase_monitor_bridge.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/app_list/arc/arc_app_list_prefs.h" #include "chrome/browser/ui/ash/launcher/arc_app_shelf_id.h" #include "chrome/browser/ui/ash/launcher/arc_shelf_spinner_item_controller.h" #include "chrome/browser/ui/ash/launcher/chrome_launcher_controller.h" #include "chrome/browser/ui/ash/launcher/shelf_spinner_controller.h" #include "components/arc/arc_bridge_service.h" #include "components/arc/arc_service_manager.h" #include "components/arc/arc_util.h" #include "components/arc/common/intent_helper.mojom.h" #include "components/arc/intent_helper/arc_intent_helper_bridge.h" #include "ui/aura/window.h" #include "ui/display/display.h" #include "ui/display/screen.h" #include "ui/events/event_constants.h" #include "ui/gfx/geometry/rect.h" // Helper macro which returns the AppInstance. #define GET_APP_INSTANCE(method_name) \ (arc::ArcServiceManager::Get() \ ? ARC_GET_INSTANCE_FOR_METHOD( \ arc::ArcServiceManager::Get()->arc_bridge_service()->app(), \ method_name) \ : nullptr) // Helper function which returns the IntentHelperInstance. #define GET_INTENT_HELPER_INSTANCE(method_name) \ (arc::ArcServiceManager::Get() \ ? ARC_GET_INSTANCE_FOR_METHOD(arc::ArcServiceManager::Get() \ ->arc_bridge_service() \ ->intent_helper(), \ method_name) \ : nullptr) namespace arc { namespace { // TODO(djacobo): Evaluate to build these strings by using // ArcIntentHelperBridge::AppendStringToIntentHelperPackageName. // Intent helper strings. constexpr char kIntentHelperClassName[] = "org.chromium.arc.intent_helper.SettingsReceiver"; constexpr char kSetInTouchModeIntent[] = "org.chromium.arc.intent_helper.SET_IN_TOUCH_MODE"; constexpr char kShowTalkbackSettingsIntent[] = "org.chromium.arc.intent_helper.SHOW_TALKBACK_SETTINGS"; constexpr char kAction[] = "action"; constexpr char kActionMain[] = "android.intent.action.MAIN"; constexpr char kCategory[] = "category"; constexpr char kCategoryLauncher[] = "android.intent.category.LAUNCHER"; constexpr char kComponent[] = "component"; constexpr char kEndSuffix[] = "end"; constexpr char kIntentPrefix[] = "#Intent"; constexpr char kLaunchFlags[] = "launchFlags"; constexpr char kAndroidClockAppId[] = "ddmmnabaeomoacfpfjgghfpocfolhjlg"; constexpr char kAndroidFilesAppId[] = "gmiohhmfhgfclpeacmdfancbipocempm"; constexpr char const* kAppIdsHiddenInLauncher[] = { kAndroidClockAppId, kSettingsAppId, kAndroidFilesAppId, }; // Returns true if |event_flags| came from a mouse or touch event. bool IsMouseOrTouchEventFromFlags(int event_flags) { return (event_flags & (ui::EF_LEFT_MOUSE_BUTTON | ui::EF_MIDDLE_MOUSE_BUTTON | ui::EF_RIGHT_MOUSE_BUTTON | ui::EF_BACK_MOUSE_BUTTON | ui::EF_FORWARD_MOUSE_BUTTON | ui::EF_FROM_TOUCH)) != 0; } bool Launch(content::BrowserContext* context, const std::string& app_id, const base::Optional& intent, int event_flags, int64_t display_id) { ArcAppListPrefs* prefs = ArcAppListPrefs::Get(context); CHECK(prefs); std::unique_ptr app_info = prefs->GetApp(app_id); if (!app_info) { VLOG(2) << "Cannot launch unavailable app: " << app_id << "."; return false; } if (!app_info->ready) { VLOG(2) << "Cannot launch not-ready app: " << app_id << "."; return false; } if (!app_info->launchable) { VLOG(2) << "Cannot launch non-launchable app: " << app_id << "."; return false; } arc::mojom::IntentHelperInstance* intent_helper_instance = GET_INTENT_HELPER_INSTANCE(SendBroadcast); if (intent_helper_instance) { base::DictionaryValue extras; extras.SetBoolean("inTouchMode", IsMouseOrTouchEventFromFlags(event_flags)); std::string extras_string; base::JSONWriter::Write(extras, &extras_string); intent_helper_instance->SendBroadcast( kSetInTouchModeIntent, ArcIntentHelperBridge::kArcIntentHelperPackageName, kIntentHelperClassName, extras_string); } if (app_info->shortcut || intent.has_value()) { const std::string intent_uri = intent.value_or(app_info->intent_uri); if (auto* app_instance = GET_APP_INSTANCE(LaunchIntent)) { app_instance->LaunchIntent(intent_uri, display_id); } else if (auto* app_instance = GET_APP_INSTANCE(LaunchIntentDeprecated)) { app_instance->LaunchIntentDeprecated(intent_uri, gfx::Rect()); } else { return false; } } else { if (auto* app_instance = GET_APP_INSTANCE(LaunchApp)) { app_instance->LaunchApp(app_info->package_name, app_info->activity, display_id); } else if (auto* app_instance = GET_APP_INSTANCE(LaunchAppDeprecated)) { app_instance->LaunchAppDeprecated(app_info->package_name, app_info->activity, gfx::Rect()); } else { return false; } } prefs->SetLastLaunchTime(app_id); return true; } // Returns primary display id if |display_id| is invalid. int64_t GetValidDisplayId(int64_t display_id) { if (display_id != display::kInvalidDisplayId) return display_id; if (auto* screen = display::Screen::GetScreen()) return screen->GetPrimaryDisplay().id(); return display::kInvalidDisplayId; } } // namespace const char kPlayStoreAppId[] = "cnbgggchhmkkdmeppjobngjoejnihlei"; const char kPlayBooksAppId[] = "cafegjnmmjpfibnlddppihpnkbkgicbg"; const char kPlayGamesAppId[] = "nplnnjkbeijcggmpdcecpabgbjgeiedc"; const char kPlayMoviesAppId[] = "dbbihmicnlldbflflckpafphlekmjfnm"; const char kPlayMusicAppId[] = "ophbaopahelaolbjliokocojjbgfadfn"; const char kPlayStorePackage[] = "com.android.vending"; const char kPlayStoreActivity[] = "com.android.vending.AssetBrowserActivity"; const char kSettingsAppId[] = "mconboelelhjpkbdhhiijkgcimoangdj"; const char kInitialStartParam[] = "S.org.chromium.arc.start_type=initialStart"; constexpr char kSettingsAppPackage[] = "com.android.settings"; const char kSettingsAppDomainUrlActivity[] = "com.android.settings.Settings$ManageDomainUrlsActivity"; bool ShouldShowInLauncher(const std::string& app_id) { for (auto* const id : kAppIdsHiddenInLauncher) { if (id == app_id) return false; } return true; } bool LaunchAndroidSettingsApp(content::BrowserContext* context, int event_flags, int64_t display_id) { return LaunchApp(context, kSettingsAppId, event_flags, display_id); } bool LaunchPlayStoreWithUrl(const std::string& url) { arc::mojom::IntentHelperInstance* instance = GET_INTENT_HELPER_INSTANCE(HandleUrl); if (!instance) { VLOG(1) << "Cannot find a mojo instance, ARC is unreachable or mojom" << " version mismatch"; return false; } instance->HandleUrl(url, kPlayStorePackage); return true; } bool LaunchApp(content::BrowserContext* context, const std::string& app_id, int event_flags) { return LaunchApp(context, app_id, event_flags, display::kInvalidDisplayId); } bool LaunchApp(content::BrowserContext* context, const std::string& app_id, int event_flags, int64_t display_id) { return LaunchAppWithIntent(context, app_id, base::nullopt /* launch_intent */, event_flags, display_id); } bool LaunchAppWithIntent(content::BrowserContext* context, const std::string& app_id, const base::Optional& launch_intent, int event_flags, int64_t display_id) { DCHECK(!launch_intent.has_value() || !launch_intent->empty()); Profile* const profile = Profile::FromBrowserContext(context); // Even when ARC is not allowed for the profile, ARC apps may still show up // as a placeholder to show the guide notification for proper configuration. // Handle such a case here and shows the desired notification. if (IsArcBlockedDueToIncompatibleFileSystem(profile)) { arc::ShowArcMigrationGuideNotification(profile); return false; } ArcAppListPrefs* prefs = ArcAppListPrefs::Get(context); std::unique_ptr app_info = prefs->GetApp(app_id); if (app_info && !app_info->ready) { if (!IsArcPlayStoreEnabledForProfile(profile)) { if (prefs->IsDefault(app_id)) { // The setting can fail if the preference is managed. However, the // caller is responsible to not call this function in such case. DCHECK // is here to prevent possible mistake. SetArcPlayStoreEnabledForProfile(profile, true); DCHECK(IsArcPlayStoreEnabledForProfile(profile)); // PlayStore item has special handling for shelf controllers. In order // to avoid unwanted initial animation for PlayStore item do not create // deferred launch request when PlayStore item enables Google Play // Store. if (app_id == kPlayStoreAppId) { prefs->SetLastLaunchTime(app_id); return true; } } else { // Only reachable when ARC always starts. DCHECK(arc::ShouldArcAlwaysStart()); } } else { // Handle the case when default app tries to re-activate OptIn flow. if (IsArcPlayStoreEnabledPreferenceManagedForProfile(profile) && !ArcSessionManager::Get()->enable_requested() && prefs->IsDefault(app_id)) { SetArcPlayStoreEnabledForProfile(profile, true); // PlayStore item has special handling for shelf controllers. In order // to avoid unwanted initial animation for PlayStore item do not create // deferred launch request when PlayStore item enables Google Play // Store. if (app_id == kPlayStoreAppId) { prefs->SetLastLaunchTime(app_id); return true; } } } arc::ArcBootPhaseMonitorBridge::RecordFirstAppLaunchDelayUMA(context); ChromeLauncherController* chrome_controller = ChromeLauncherController::instance(); DCHECK(chrome_controller || !ash::Shell::HasInstance()); if (chrome_controller) { chrome_controller->GetShelfSpinnerController()->AddSpinnerToShelf( app_id, std::make_unique( app_id, event_flags, GetValidDisplayId(display_id))); // On some boards, ARC is booted with a restricted set of resources by // default to avoid slowing down Chrome's user session restoration. // However, the restriction should be lifted once the user explicitly // tries to launch an ARC app. SetArcCpuRestriction(false); } prefs->SetLastLaunchTime(app_id); return true; } arc::ArcBootPhaseMonitorBridge::RecordFirstAppLaunchDelayUMA(context); return Launch(context, app_id, launch_intent, event_flags, GetValidDisplayId(display_id)); } bool LaunchAppShortcutItem(content::BrowserContext* context, const std::string& app_id, const std::string& shortcut_id, int64_t display_id) { std::unique_ptr app_info = ArcAppListPrefs::Get(context)->GetApp(app_id); if (!app_info) { LOG(ERROR) << "App " << app_id << " is not available."; return false; } mojom::AppInstance* app_instance = ArcServiceManager::Get() ? ARC_GET_INSTANCE_FOR_METHOD( ArcServiceManager::Get()->arc_bridge_service()->app(), LaunchAppShortcutItem) : nullptr; if (!app_instance) { LOG(ERROR) << "Cannot find a mojo instance, ARC is unreachable or mojom" << " version mismatch."; return false; } app_instance->LaunchAppShortcutItem(app_info->package_name, shortcut_id, GetValidDisplayId(display_id)); return true; } bool LaunchSettingsAppActivity(content::BrowserContext* context, const std::string& activity, int event_flags, int64_t display_id) { const std::string launch_intent = GetLaunchIntent( kSettingsAppPackage, activity, std::vector()); return LaunchAppWithIntent(context, kSettingsAppId, launch_intent, event_flags, display_id); } void SetTaskActive(int task_id) { arc::mojom::AppInstance* app_instance = GET_APP_INSTANCE(SetTaskActive); if (!app_instance) return; app_instance->SetTaskActive(task_id); } void CloseTask(int task_id) { arc::mojom::AppInstance* app_instance = GET_APP_INSTANCE(CloseTask); if (!app_instance) return; app_instance->CloseTask(task_id); } void ShowTalkBackSettings() { arc::mojom::IntentHelperInstance* intent_helper_instance = GET_INTENT_HELPER_INSTANCE(SendBroadcast); if (!intent_helper_instance) return; intent_helper_instance->SendBroadcast( kShowTalkbackSettingsIntent, ArcIntentHelperBridge::kArcIntentHelperPackageName, kIntentHelperClassName, "{}"); } void StartPaiFlow() { arc::mojom::AppInstance* app_instance = GET_APP_INSTANCE(StartPaiFlow); if (!app_instance) return; app_instance->StartPaiFlow(); } void UninstallPackage(const std::string& package_name) { VLOG(2) << "Uninstalling " << package_name; arc::mojom::AppInstance* app_instance = GET_APP_INSTANCE(UninstallPackage); if (!app_instance) return; app_instance->UninstallPackage(package_name); } void UninstallArcApp(const std::string& app_id, Profile* profile) { ArcAppListPrefs* arc_prefs = ArcAppListPrefs::Get(profile); DCHECK(arc_prefs); std::unique_ptr app_info = arc_prefs->GetApp(app_id); if (!app_info) { VLOG(2) << "Package being uninstalled does not exist: " << app_id << "."; return; } // For shortcut we just remove the shortcut instead of the package. if (app_info->shortcut) arc_prefs->RemoveApp(app_id); else UninstallPackage(app_info->package_name); } void RemoveCachedIcon(const std::string& icon_resource_id) { VLOG(2) << "Removing icon " << icon_resource_id; arc::mojom::AppInstance* app_instance = GET_APP_INSTANCE(RemoveCachedIcon); if (!app_instance) return; app_instance->RemoveCachedIcon(icon_resource_id); } bool ShowPackageInfo(const std::string& package_name, mojom::ShowPackageInfoPage page, int64_t display_id) { VLOG(2) << "Showing package info for " << package_name; if (auto* app_instance = GET_APP_INSTANCE(ShowPackageInfoOnPage)) { app_instance->ShowPackageInfoOnPage(package_name, page, display_id); return true; } if (auto* app_instance = GET_APP_INSTANCE(ShowPackageInfoOnPageDeprecated)) { app_instance->ShowPackageInfoOnPageDeprecated(package_name, page, gfx::Rect()); return true; } if (auto* app_instance = GET_APP_INSTANCE(ShowPackageInfoDeprecated)) { app_instance->ShowPackageInfoDeprecated(package_name, gfx::Rect()); return true; } return false; } bool IsArcItem(content::BrowserContext* context, const std::string& id) { DCHECK(context); // Some unit tests use empty ids, some app ids are not valid ARC app ids. const ArcAppShelfId arc_app_shelf_id = ArcAppShelfId::FromString(id); if (!arc_app_shelf_id.valid()) return false; const ArcAppListPrefs* const arc_prefs = ArcAppListPrefs::Get(context); if (!arc_prefs) return false; return arc_prefs->IsRegistered(arc_app_shelf_id.app_id()); } std::string GetLaunchIntent(const std::string& package_name, const std::string& activity, const std::vector& extra_params) { std::string extra_params_extracted; for (const auto& extra_param : extra_params) { extra_params_extracted += extra_param; extra_params_extracted += ";"; } // Remove the |package_name| prefix, if activity starts with it. const char* activity_compact_name = activity.find(package_name.c_str()) == 0 ? activity.c_str() + package_name.length() : activity.c_str(); // Construct a string in format: // #Intent;action=android.intent.action.MAIN; // category=android.intent.category.LAUNCHER; // launchFlags=0x10210000; // component=package_name/activity; // param1;param2;end return base::StringPrintf( "%s;%s=%s;%s=%s;%s=0x%x;%s=%s/%s;%s%s", kIntentPrefix, kAction, kActionMain, kCategory, kCategoryLauncher, kLaunchFlags, Intent::FLAG_ACTIVITY_NEW_TASK | Intent::FLAG_ACTIVITY_RESET_TASK_IF_NEEDED, kComponent, package_name.c_str(), activity_compact_name, extra_params_extracted.c_str(), kEndSuffix); } bool ParseIntent(const std::string& intent_as_string, Intent* intent) { DCHECK(intent); const std::vector parts = base::SplitStringPiece( intent_as_string, ";", base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY); if (parts.size() < 2 || parts.front() != kIntentPrefix || parts.back() != kEndSuffix) { DVLOG(1) << "Failed to split intent " << intent_as_string << "."; return false; } for (size_t i = 1; i < parts.size() - 1; ++i) { const size_t separator = parts[i].find('='); if (separator == std::string::npos) { intent->AddExtraParam(parts[i].as_string()); continue; } const base::StringPiece key = parts[i].substr(0, separator); const base::StringPiece value = parts[i].substr(separator + 1); if (key == kAction) { intent->set_action(value.as_string()); } else if (key == kCategory) { intent->set_category(value.as_string()); } else if (key == kLaunchFlags) { uint32_t launch_flags; const bool parsed = base::HexStringToUInt(value.as_string(), &launch_flags); if (!parsed) { DVLOG(1) << "Failed to parse launchFlags: " << value.as_string() << "."; return false; } intent->set_launch_flags(launch_flags); } else if (key == kComponent) { const size_t component_separator = value.find('/'); if (component_separator == std::string::npos) return false; intent->set_package_name( value.substr(0, component_separator).as_string()); const base::StringPiece activity_compact_name = value.substr(component_separator + 1); if (!activity_compact_name.empty() && activity_compact_name[0] == '.') { std::string activity = value.substr(0, component_separator).as_string(); activity += activity_compact_name.as_string(); intent->set_activity(activity); } else { intent->set_activity(activity_compact_name.as_string()); } } else { intent->AddExtraParam(parts[i].as_string()); } } return true; } Intent::Intent() = default; Intent::~Intent() = default; void Intent::AddExtraParam(const std::string& extra_param) { extra_params_.push_back(extra_param); } bool Intent::HasExtraParam(const std::string& extra_param) const { return std::find(extra_params_.begin(), extra_params_.end(), extra_param) != extra_params_.end(); } } // namespace arc codeforces/672A.cpp // #include #include using namespace std; int main(){ int n; cin >> n; string s; for (int i = 1; i < n + 1; ++i){ s += to_string(i); } cout << s[n-1] << endl; return 0; } fnrizzi/ElasticShearWavescpp/src/shared/material_models/material_setter.hpp #ifndef MATERIAL_MAP_DISCONTINUITY_TO_MESH_HPP_ #define MATERIAL_MAP_DISCONTINUITY_TO_MESH_HPP_ template void mapDiscontinuityToMesh(const mesh_info_t & meshInfo, const gids_t & gidsVp, const gids_t & gidsSp, const coords_t & coordsVp, const coords_t & coordsSp, const labels_t & labelsSp, const sc_t & requestedDiscontinuityDepthKm, sc_t & mappedDiscontinuityDepthKm, int_t & vpGidDiscont, int_t & spGidDiscont) { // std::cout << "\nMapping discontinuity layer to grid" << std::endl; // constexpr auto one = constants::one(); // constexpr auto thous = constants::thousand(); // constexpr auto esrMeters = constants::earthSurfaceRadiusMeters(); // constexpr auto esrKm = constants::earthSurfaceRadiusKm(); // // store the requested depth in Km of the discontinuity // discontinuityRequestedDepthKm_ = parser_.depth2_; // const auto discontinuityRequestedDepthM_ = parser_.depth2_ * thous; // std::cout << "The requested depth = " << discontinuityRequestedDepthKm_ << " (km)" << std::endl; // // find the first Vp GID of the grid point as close to the target depth as possible // const auto numGptVp = meshInfo.getNumVpPts(); // auto trialDelta = std::numeric_limits::max() - discontinuityRequestedDepthM_; // for (int_t iPt=0; iPt < numGptVp; ++iPt){ // const auto & ptGID = gidsVp(iPt); // const auto thisPtRadius = one/coordsVp(ptGID, 1); // meters // const auto thisPtDepth = esrMeters - thisPtRadius; //meters // const auto delta = std::abs(thisPtDepth - discontinuityRequestedDepthM_); // // here we need to check < only because we want to track the first Vp point // // to meet the condition, otherwise with <= we would find the last point on // // the curve along theta // if ( delta < trialDelta ){ // trialDelta = delta; // vpGidDiscont_ = ptGID; // } // } // std::cout << " found vpPt " << vpGidDiscont_ << std::endl; // // find the first srp GID of the grid point as close to the target depth as possible // const auto numGptSp = meshInfo.getNumSpPts(); // trialDelta = std::numeric_limits::max() - discontinuityRequestedDepthM_; // for (int_t iPt=0; iPt < numGptSp; ++iPt){ // const auto & ptGID = gidsSp(iPt); // const auto thisPtRadius = one/coordsSp(ptGID, 1); // meters // const auto thisPtDepth = esrMeters - thisPtRadius; //meters // const auto delta = std::abs(thisPtDepth - discontinuityRequestedDepthM_); // if (labelsSp(ptGID)==2){ // // here we need to check < only because we want to track the first point // // to meet the condition, otherwise with <= we would find the last point on // // the curve along theta // if ( delta < trialDelta ){ // trialDelta = delta; // spGidDiscont_ = ptGID-1; // want the gid of the srp point, which is just one before // } // } // } // std::cout << " found spPt " << spGidDiscont_ << std::endl; // // the gid of the srp point can also be found using grid geometry as follows // const int_t den = meshInfo.getNumPtsAlongTheta()-1; // const int_t jumps = int_t(std::floor(vpGidDiscont_/den)); // const auto spGidDiscont2 = (jumps*den) + vpGidDiscont_; // std::cout << " found spPt22 " << spGidDiscont2 << std::endl; // if (spGidDiscont2 != spGidDiscont_){ // throw std::runtime_error("Something wrong when mapping discontinuity, \ // the gids compute for srp do not match from the two methods used."); // } // // find the mapped discontinuity // discontinuityMappedDepthKm_ = (esrMeters - (one/coordsVp(vpGidDiscont_,1)))/thous; // discontinuityMappedRadiusKm_ = esrKm - discontinuityMappedDepthKm_; // discontinuityMappedRadiusMeters_ = discontinuityMappedRadiusKm_ * thous; // std::cout << "Discontinuity depth mapped to depth (Km) " // << std::setprecision(dblFmt) << discontinuityMappedDepthKm_ // << " with radius (km) = " << discontinuityMappedRadiusKm_ // << " with VpGid = " << vpGidDiscont_ // << " with SpGid = " << spGidDiscont_ // << std::endl; } #endif 10-100 #include "n2dGraphicsImpl.h" #include "n2dRenderDeviceImpl.h" #include "../Engine/n2dEngineImpl.h" #include "n2dMeshDataImpl.h" #include "n2dModelImpl.h" #include n2dGraphics2DImpl::n2dGraphics2DImpl(n2dRenderDeviceImpl* pRenderDevice) : m_pRenderDevice(pRenderDevice), m_VB(nullptr), m_IB(nullptr), m_bIsRendering(false) { nat_ThrowIfFailed(m_pRenderDevice->CreateBuffer(n2dBuffer::BufferTarget::ArrayBuffer, m_VB), "Create vertex buffer failed."_nv); nat_ThrowIfFailed(m_pRenderDevice->CreateBuffer(n2dBuffer::BufferTarget::ElementArrayBuffer, m_IB), "Create index buffer failed."_nv); } n2dGraphics2DImpl::~n2dGraphics2DImpl() { if (m_bIsRendering) { m_pRenderDevice->GetEngine()->GetLogger().LogWarn("n2dGraphics2DImpl::End should be invoked before destroy"_nv); End(); } } nBool n2dGraphics2DImpl::IsRendering() const { return m_bIsRendering; } nResult n2dGraphics2DImpl::Begin() { m_bIsRendering = true; return NatErr_OK; } nResult n2dGraphics2DImpl::Flush() { if (!m_bIsRendering) return NatErr_IllegalState; flush(); return NatErr_OK; } nResult n2dGraphics2DImpl::End() { flush(); m_bIsRendering = false; return NatErr_OK; } namespace { const nuShort tQuadIndex[] = { 0u, 1u, 2u, 0u, 2u, 3u }; } nResult n2dGraphics2DImpl::DrawQuad(natRefPointer pTex, n2dGraphics2DVertex const& v1, n2dGraphics2DVertex const& v2, n2dGraphics2DVertex const& v3, n2dGraphics2DVertex const& v4) { if (!m_bIsRendering) return NatErr_IllegalState; n2dGraphics2DVertex tVert[4] = { v1, v2, v3, v4 }; pushCommand(pTex, 4, 6, tVert, tQuadIndex); return NatErr_OK; } nResult n2dGraphics2DImpl::DrawQuad(natRefPointer pTex, const n2dGraphics2DVertex* varr) { if (!m_bIsRendering) return NatErr_IllegalState; pushCommand(pTex, 4, 6, varr, tQuadIndex); return NatErr_OK; } nResult n2dGraphics2DImpl::DrawRaw(natRefPointer pTex, nuInt cVertex, nuInt cIndex, const n2dGraphics2DVertex* varr, const nuShort* iarr) { if (!m_bIsRendering) return NatErr_IllegalState; pushCommand(pTex, cVertex, cIndex, varr, iarr); return NatErr_OK; } void n2dGraphics2DImpl::pushCommand(natRefPointer pTex, nuInt cVertex, nuInt cIndex, const n2dGraphics2DVertex* varr, const nuShort* iarr) { std::vector> tVert(cVertex); std::vector> tUV(cVertex); for (nuInt i = 0u; i < cVertex; ++i) { tVert[i] = varr[i].vert; tUV[i] = varr[i].uv; } nuInt VB, UVB, IB; glGenBuffers(1, &VB); glGenBuffers(1, &UVB); glGenBuffers(1, &IB); glBindBuffer(GL_ARRAY_BUFFER, VB); glBufferData(GL_ARRAY_BUFFER, cVertex * sizeof(natVec3<>), &tVert[0], GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, UVB); glBufferData(GL_ARRAY_BUFFER, cVertex * sizeof(natVec2<>), &tUV[0], GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, IB); glBufferData(GL_ELEMENT_ARRAY_BUFFER, cIndex * sizeof(nuShort), iarr, GL_STATIC_DRAW); m_Commands.emplace_back(RenderCommand{ false, natRefPointer(pTex), VB, UVB, 0u, IB, cVertex, cIndex }); } void n2dGraphics2DImpl::flush() { m_pRenderDevice->updateMVP(); GLboolean bCullFace = glIsEnabled(GL_CULL_FACE); glDisable(GL_CULL_FACE); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glEnableVertexAttribArray(0); glEnableVertexAttribArray(1); glEnableVertexAttribArray(2); glActiveTexture(GL_TEXTURE0); for (nuInt i = 0u; i < m_Commands.size(); ++i) { glBindTexture(GL_TEXTURE_2D, m_Commands[i].pTex->GetTextureID()); glBindBuffer(GL_ARRAY_BUFFER, m_Commands[i].VertexBuffer); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, nullptr); glBindBuffer(GL_ARRAY_BUFFER, m_Commands[i].UVBuffer); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, nullptr); glBindBuffer(GL_ARRAY_BUFFER, m_Commands[i].NormalBuffer); glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, 0, nullptr); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_Commands[i].IndexBuffer); glDrawElements(GL_TRIANGLES, m_Commands[i].cIndex, GL_UNSIGNED_SHORT, NULL); if (!m_Commands[i].bKeepBuffer) { glDeleteBuffers(1, &m_Commands[i].VertexBuffer); glDeleteBuffers(1, &m_Commands[i].UVBuffer); glDeleteBuffers(1, &m_Commands[i].NormalBuffer); glDeleteBuffers(1, &m_Commands[i].IndexBuffer); } } glDisableVertexAttribArray(0); glDisableVertexAttribArray(1); glDisableVertexAttribArray(2); if (bCullFace) { glEnable(GL_CULL_FACE); } m_Commands.clear(); } n2dGraphics3DImpl::n2dGraphics3DImpl(n2dRenderDeviceImpl* pRenderDevice) : m_MaterialID(0u), m_pRenderDevice(pRenderDevice), m_MaterialBuffer(nullptr), m_bIsRendering(false) { m_MaterialBuffer = make_ref(n2dBuffer::BufferTarget::UniformBuffer, static_cast>(m_pRenderDevice->GetShaderWrapper())); m_MaterialBuffer->BindBase(2u); } n2dGraphics3DImpl::~n2dGraphics3DImpl() { if (m_bIsRendering) { m_pRenderDevice->GetEngine()->GetLogger().LogWarn("n2dGraphics3DImpl::End should be invoked before destroy"_nv); n2dGraphics3DImpl::End(); } } nBool n2dGraphics3DImpl::IsRendering() const { return m_bIsRendering; } nResult n2dGraphics3DImpl::Begin() { m_bIsRendering = true; return NatErr_OK; } nResult n2dGraphics3DImpl::Flush() { if (!m_bIsRendering) { return NatErr_IllegalState; } flush(); return NatErr_OK; } nResult n2dGraphics3DImpl::End() { m_bIsRendering = false; flush(); return NatErr_OK; } nResult n2dGraphics3DImpl::RenderModel(natRefPointer pModelData) { if (!pModelData) { return NatErr_InvalidArg; } if (pModelData->IsStatic()) { natRefPointer pModel = pModelData; if (!pModel) { return NatErr_InvalidArg; } m_StaticMaterials.reserve(m_StaticMaterials.size() + pModel->m_Meshes.size()); for (auto&& i : pModel->m_Meshes) { m_StaticMaterials.emplace_back(&i->m_Material); std::vector tMatID = { static_cast(m_StaticMaterials.size() - 1) }; m_Commands.emplace_back(RenderCommand{ true, tMatID, i->GetVertexBuffer(), i->GetIndexBuffer(), i->GetVertexCount(), i->GetIndexCount() }); } } else { natRefPointer pModel = pModelData; if (!pModel) { return NatErr_InvalidArg; } m_DynamicMaterials.reserve(m_DynamicMaterials.size() + pModel->m_Mesh.m_Materials.size()); auto cMaterials = pModel->m_Mesh.m_Materials.size(); std::vector tMatID(cMaterials); for (size_t i = 0u; i < cMaterials; ++i) { m_DynamicMaterials.push_back(&pModel->m_Mesh.m_Materials[i]); tMatID[i] = static_cast(m_DynamicMaterials.size() - 1); } m_Commands.emplace_back(RenderCommand{ false, tMatID, pModel->m_Mesh.GetVertexBuffer(), pModel->m_Mesh.GetIndexBuffer(), pModel->m_Mesh.GetVertexCount(), pModel->m_Mesh.GetIndexCount() }); } return NatErr_OK; } void n2dGraphics3DImpl::flush() { m_pRenderDevice->updateMVP(); glEnableVertexAttribArray(0); glEnableVertexAttribArray(1); glEnableVertexAttribArray(2); glActiveTexture(GL_TEXTURE0); n2dMeshData::Material* material; for (auto& c : m_Commands) { c.VertexBuffer->Bind(); glVertexAttribPointer(0u, 3, GL_FLOAT, GL_FALSE, sizeof(n2dGraphics3DVertex), reinterpret_cast(offsetof(n2dGraphics3DVertex, vert))); glVertexAttribPointer(1u, 2, GL_FLOAT, GL_FALSE, sizeof(n2dGraphics3DVertex), reinterpret_cast(offsetof(n2dGraphics3DVertex, uv))); glVertexAttribPointer(2u, 3, GL_FLOAT, GL_FALSE, sizeof(n2dGraphics3DVertex), reinterpret_cast(offsetof(n2dGraphics3DVertex, normal))); c.IndexBuffer->Bind(); nuInt Count; ncData tOffset; for (auto iMater : c.iMaterial) { if (c.bStatic) { material = m_StaticMaterials[iMater]; Count = c.cIndex; tOffset = nullptr; } else { n2dMeshData::DynamicMaterial* pdynamicmaterial = m_DynamicMaterials[iMater]; material = &pdynamicmaterial->BaseMaterial; Count = pdynamicmaterial->Length; tOffset = reinterpret_cast(pdynamicmaterial->Start * sizeof(nuShort)); } m_MaterialBuffer->AllocData(sizeof(n2dMeshData::Material) - offsetof(n2dMeshData::Material, Diffuse), reinterpret_cast(&material->Diffuse), n2dBuffer::BufferUsage::DynamicDraw); glPolygonMode(GL_FRONT_AND_BACK, material->WireFrame ? GL_LINE : GL_FILL); (material->Both_sided ? glEnable : glDisable)(GL_CULL_FACE); glBindTexture(GL_TEXTURE_2D, material->Texture->GetTextureID()); glDrawElements(GL_TRIANGLES, Count, GL_UNSIGNED_SHORT, tOffset); if (c.bStatic) break; } } glDisableVertexAttribArray(0); glDisableVertexAttribArray(1); glDisableVertexAttribArray(2); m_Commands.clear(); m_StaticMaterials.clear(); m_DynamicMaterials.clear(); } src/opengl/Texture.cpp /* * Copyright (c) 2013 * * 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.h" namespace PolandBall { namespace Opengl { bool Texture::load(SDL_Surface* image) { if (image == nullptr) { return false; } SDL_Surface* source = (image->format->BytesPerPixel != 4) ? this->convertToRGBA(image) : image; if (source == nullptr) { return false; } glBindTexture(GL_TEXTURE_2D, this->texture); glTexImage2D(GL_TEXTURE_2D, 0, GL_SRGB8_ALPHA8, source->w, source->h, 0, (source->format->Rmask > source->format->Bmask) ? GL_BGRA : GL_RGBA, GL_UNSIGNED_BYTE, source->pixels); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glGenerateMipmap(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, 0); if (source != image) { // Free only our copy if made SDL_FreeSurface(source); } return true; } SDL_Surface* Texture::convertToRGBA(SDL_Surface* image) { SDL_Surface* newSource = SDL_CreateRGBSurface(SDL_SWSURFACE, image->w, image->h, 32, 0x000000FF, 0x0000FF00, 0x00FF0000, 0xFF000000); if (newSource == nullptr) { return nullptr; } if (SDL_BlitSurface(image, nullptr, newSource, nullptr)) { SDL_FreeSurface(newSource); return nullptr; } return newSource; } } // namespace Opengl } // namespace PolandBall 0 //write includes statements #include "loops.h" #include //write using statements for cin and cout using std::cin; using std::cout; /* Use a do while loop to prompt the user for a number, call the factorial function, and display the number's factorial. Also, loop continues as long as user wants to. */ int main() { //Hopefully this works, I put the loop true right now so that it wont be infinite. int msg_prompt = 1; //Loop while(msg_prompt == 1) { //variables int keyboard_number; cout<<"enter a number from 1 to 10: "; cin>>keyboard_number; //If number entered is a negative number if(keyboard_number <= 0) { cout<<"\nwe cant accumulate negative numbers"<<"\npress 1 to try again or press any button to quit: "; //Will ask the user if they want to stop the loop cin>>msg_prompt; } // If number entered is in range of 1 to 10 else if (keyboard_number >= 1 && keyboard_number <= 10) { cout<<"\nYour factorial number is: "<>msg_prompt; } //If numbers are greater than 10 else { cout<<"\nwe cant accumulate numbers higher than 10"<<"\npress 1 to try again or press any button to quit: "; //Will ask the user if they want to stop the loop cin>>msg_prompt; } //End of loop } return 0; }/* ************************************************************************ */ /* ************************************************************************ */ #include "IsoDef.h" #if defined(_LAY6_) #include #include #include #include "Settings/settings.h" #include "AppMemAccess.h" #if defined(ESP_PLATFORM) #include #include "esp_err.h" #include "esp_log.h" const char *D_D_D_D_D_D_D_I64_X = "%d=%d,%d,%d,%d,%d,%d,%I64X"; const char *D_D_D_D_D_D_D_L_X = "%d=%d,%d,%d,%d,%d,%d,%lX"; const char *D_D_D_D_D_D_D_LL_X = "%d=%d,%d,%d,%d,%d,%d,%llX"; static const char *TAG = "AppMemAccess"; #endif // def ESP_PLATFORM using namespace std; #if defined(_MSC_VER ) #pragma warning(disable : 4996) #endif // defined(_MSC_VER ) #if defined(linux) || defined(ESP_PLATFORM) #define vswprintf_s swprintf #define vsprintf_s snprintf #define _strtoui64 strtoull #define vswprintf_s swprintf #define vsprintf_s snprintf #define sprintf_s snprintf #endif // defined(linux) || defined(ESP_PLATFORM) #if defined(linux) #define USE_L_FOR_64BIT #elif defined(__MINGW_GCC_VERSION) #define USE_LL_FOR_64BIT #else // defined(linux), defined(__MINGW_GCC_VERSION) #endif // defined(linux), defined(__MINGW_GCC_VERSION) #if defined(ESP_PLATFORM) #define USE_LL_FOR_64BIT #endif // def ESP_PLATFORM static bool parseAuxEntry(char* entry, VT_AUXAPP_T* auxEntry); static bool getKeyByID(iso_s16 wObjID_Fun, char* key, size_t size); static bool getValue(const VT_AUXAPP_T& auxEntry, char* value, size_t size); extern "C" const int FIRST_AUX; extern "C" const int LAST_AUX; /* **************** Auxiliary Assignments *********************************** */ iso_s16 getAuxAssignment(const char auxSection[], VT_AUXAPP_T asAuxAss[]) { #if defined(ESP_PLATFORM) ESP_LOGI(TAG, "getAuxAssignment"); #endif // def ESP_PLATFORM iso_s16 idxAux = 0U; for (iso_s16 idx = FIRST_AUX; idx <= LAST_AUX; idx++) { char buffer[64]; char key[16]; getKeyByID(idx, key, sizeof(key)); #if defined(ESP_PLATFORM) ESP_LOGI(TAG, "getKeyByID %s ", key); #endif // def ESP_PLATFORM size_t len = getString(auxSection, key, nullptr, buffer, sizeof(buffer)); ESP_LOGI(TAG, "getString: %s", buffer); VT_AUXAPP_T* auxEntry = &asAuxAss[idxAux]; if(len > 16) //TODO! this is a magic Number now. { if (parseAuxEntry(buffer, auxEntry)) { char value[64]; getValue(*auxEntry, value, sizeof(value)); iso_DebugPrint("getAuxAssignment: %d %s %s\n", idxAux, key, value); idxAux++; } } } ESP_LOGI(TAG, "getAuxAssignment found: %d", idxAux); return idxAux; } static bool parseAuxEntry(char* entry, VT_AUXAPP_T* auxEntry) { int wObjID_Fun; int wObjID_Input; int eAuxType; int wManuCode; int wModelIdentCode; int qPrefAssign; int bFuncAttribute; uint64_t name; int parameterCount = sscanf(entry, #if defined(USE_L_FOR_64BIT) D_D_D_D_D_D_D_L_X, &wObjID_Fun, #elif defined(USE_LL_FOR_64BIT) D_D_D_D_D_D_D_LL_X, &wObjID_Fun, #else // !defined(USE_L_FOR_64BIT) D_D_D_D_D_D_D_I64_X, &wObjID_Fun, #endif //!defined(USE_L_FOR_64BIT) &wObjID_Input, &eAuxType, &wManuCode, &wModelIdentCode, &qPrefAssign, &bFuncAttribute, &name); if (parameterCount == 8) { auxEntry->wObjID_Fun = static_cast(wObjID_Fun); /* Object ID of auxiliary function */ auxEntry->wObjID_Input = static_cast(wObjID_Input); /* Object ID of auxiliary input */ auxEntry->eAuxType = static_cast(eAuxType); /* Function/input type (without attribute bits) - only because of downwards compatibility */ auxEntry->wManuCode = static_cast(wManuCode); /* Manufacturer Code of auxiliary input device */ auxEntry->wModelIdentCode = static_cast(wModelIdentCode); /* Model identification code of aux input device */ auxEntry->qPrefAssign = static_cast(qPrefAssign); /* This assignment shall used for preferred assignment */ auxEntry->bFuncAttribute = static_cast(bFuncAttribute); /* Complete function attribute byte of auxiliary function */ memcpy(&auxEntry->baAuxName[0], &name, 8); /* ISO name of the auxiliary input device. The bytes must be set to 0xFF if not used. */ return true; } return false; } void setAuxAssignment(const char section[], VT_AUXAPP_T asAuxAss[], iso_s16 iNumberOfAssigns) { char key[16]; // erase complete section for (int8_t idx = FIRST_AUX; idx <= LAST_AUX; idx++) { getKeyByID(idx, key, sizeof(key)); eraseString(section, key); } char buffer[64]; // write aux entries for (int8_t idx = 0; idx < iNumberOfAssigns; idx++) { VT_AUXAPP_T* auxEntry = &asAuxAss[idx]; getKeyByID((iso_s16)auxEntry->wObjID_Fun, key, sizeof(key)); uint64_t name = 0; memcpy(&name, &auxEntry->baAuxName[0], 8); /* ISO name of the auxiliary input device. The bytes must be set to 0xFF if not used. */ #if defined(USE_L_FOR_64BIT) sprintf_s(buffer, sizeof(buffer), D_D_D_D_D_D_D_L_X, #elif defined(USE_LL_FOR_64BIT) sprintf_s(buffer, sizeof(buffer), D_D_D_D_D_D_D_LL_X, #else // !defined(USE_L_FOR_64BIT) sprintf_s(buffer, sizeof(buffer), D_D_D_D_D_D_D_I64_X, #endif //!defined(USE_L_FOR_64BIT) auxEntry->wObjID_Fun, auxEntry->wObjID_Input, auxEntry->eAuxType, auxEntry->wManuCode, auxEntry->wModelIdentCode, auxEntry->qPrefAssign, auxEntry->bFuncAttribute, name); setString(section, key, buffer); } } void updateAuxAssignment(const char auxSection[], VT_AUXAPP_T* sAuxAss) { if (sAuxAss->wObjID_Input != 0xFFFF) { char key[16]; char value[64]; getKeyByID((iso_s16)sAuxAss->wObjID_Fun, key, sizeof(key)); getValue(*sAuxAss, value, sizeof(value)); iso_DebugPrint("updateAuxAssignment add: %s %s\n", key, value); setString(auxSection, key, value); } else { iso_s16 auxCfHandle = IsoCl_GetCfHandleToName(ISO_CAN_VT, &sAuxAss->baAuxName); iso_u16 wModelIdentCode = 0; if (IsoReadAuxInputDevModIdentCode(auxCfHandle, &wModelIdentCode) == E_NO_ERR) { sAuxAss->wModelIdentCode = wModelIdentCode; } char key[16]; getKeyByID((iso_s16)sAuxAss->wObjID_Fun, key, sizeof(key)); iso_DebugPrint("updateAuxAssignment remove: %s\n", key); eraseString(auxSection, key); } } static bool getKeyByID(iso_s16 wObjID_Fun, char* key, size_t size) { sprintf_s(key, size, "AUX-%d", wObjID_Fun); return true; } static bool getValue(const VT_AUXAPP_T& auxEntry, char* value, size_t size) { uint64_t name = 0; memcpy(&name, &auxEntry.baAuxName[0], 8); /* ISO name of the auxiliary input device. The bytes must be set to 0xFF if not used. */ #if defined(USE_L_FOR_64BIT) sprintf_s(value, size, D_D_D_D_D_D_D_L_X, #elif defined(USE_LL_FOR_64BIT) sprintf_s(value, size, D_D_D_D_D_D_D_LL_X, #else // !defined(USE_L_FOR_64BIT) sprintf_s(value, size, D_D_D_D_D_D_D_I64_X, #endif // !defined(USE_L_FOR_64BIT) auxEntry.wObjID_Fun, auxEntry.wObjID_Input, auxEntry.eAuxType, auxEntry.wManuCode, auxEntry.wModelIdentCode, auxEntry.qPrefAssign, auxEntry.bFuncAttribute, name); return true; } /* ************************************************************************ */ #endif /* defined(_LAY6_) */ /* ************************************************************************ */ #include #include namespace EE { namespace Window { cInput::cInput( cWindow * window, cJoystickManager * joystickmanager ) : mWindow( window ), mJoystickManager( joystickmanager ), mPressTrigger(0), mReleaseTrigger(0), mLastPressTrigger(0), mClickTrigger(0), mDoubleClickTrigger(0), mInputMod(0), mDoubleClickInterval(400), mLastButtonLeftClicked(0), mLastButtonRightClicked(0), mLastButtonMiddleClicked(0), mLastButtonLeftClick(0), mLastButtonRightClick(0), mLastButtonMiddleClick(0), mTClick(0), mNumCallBacks(0), mMouseSpeed(1.0f), mInputGrabed( false ) { memset( mKeysDown , 0, EE_KEYS_SPACE ); memset( mKeysUp , 0, EE_KEYS_SPACE ); } cInput::~cInput() { eeSAFE_DELETE( mJoystickManager ); } void cInput::CleanStates() { memset( mKeysUp, 0, EE_KEYS_SPACE ); mReleaseTrigger = 0; mLastPressTrigger = mPressTrigger; mClickTrigger = 0; mDoubleClickTrigger = 0; ResetFingerWasDown(); } void cInput::SendEvent( InputEvent * Event ) { for ( std::map::iterator i = mCallbacks.begin(); i != mCallbacks.end(); i++ ) { i->second( Event ); } } void cInput::ProcessEvent( InputEvent * Event ) { switch( Event->Type ) { case InputEvent::KeyDown: { if ( Event->key.keysym.sym > EE_KEYS_NUM ) break; if ( Event->key.keysym.mod != eeINDEX_NOT_FOUND ) mInputMod = Event->key.keysym.mod; BitOp::WriteBitKey( &mKeysDown [ Event->key.keysym.sym / 8 ], Event->key.keysym.sym % 8, 1 ); break; } case InputEvent::KeyUp: { if ( Event->key.keysym.sym > EE_KEYS_NUM ) break; BitOp::WriteBitKey( &mKeysDown [ Event->key.keysym.sym / 8 ], Event->key.keysym.sym % 8, 0 ); BitOp::WriteBitKey( &mKeysUp [ Event->key.keysym.sym / 8 ], Event->key.keysym.sym % 8, 1 ); break; } case InputEvent::MouseMotion: { if ( !mInputGrabed ) { mMousePos.x = Event->motion.x; mMousePos.y = Event->motion.y; } else { mMousePos.x += static_cast( (eeFloat)Event->motion.xrel * mMouseSpeed ); mMousePos.y += static_cast( (eeFloat)Event->motion.yrel * mMouseSpeed ); } if ( mMousePos.x >= (eeInt)mWindow->GetWidth() ) { mMousePos.x = mWindow->GetWidth(); } else if ( mMousePos.x < 0 ) { mMousePos.x = 0; } if ( mMousePos.y >= (eeInt)mWindow->GetHeight() ) { mMousePos.y = mWindow->GetHeight(); } else if ( mMousePos.y < 0 ) { mMousePos.y = 0; } break; } case InputEvent::MouseButtonDown: { mPressTrigger |= EE_BUTTON_MASK( Event->button.button ); break; } case InputEvent::MouseButtonUp: { mPressTrigger &= ~EE_BUTTON_MASK( Event->button.button ); mReleaseTrigger |= EE_BUTTON_MASK( Event->button.button ); mClickTrigger |= EE_BUTTON_MASK( Event->button.button ); // I know this is ugly, but i'm too lazy to fix it, it works... if ( Event->button.button == EE_BUTTON_LEFT ) { mLastButtonLeftClicked = mLastButtonLeftClick; mLastButtonLeftClick = Sys::GetTicks(); mTClick = mLastButtonLeftClick - mLastButtonLeftClicked; if ( mTClick < mDoubleClickInterval && mTClick > 0 ) { mDoubleClickTrigger |= EE_BUTTON_MASK(EE_BUTTON_LEFT); mLastButtonLeftClick = 0; mLastButtonLeftClicked = 0; } } else if ( Event->button.button == EE_BUTTON_RIGHT ) { mLastButtonRightClicked = mLastButtonRightClick; mLastButtonRightClick = Sys::GetTicks(); mTClick = mLastButtonRightClick - mLastButtonRightClicked; if ( mTClick < mDoubleClickInterval && mTClick > 0 ) { mDoubleClickTrigger |= EE_BUTTON_MASK(EE_BUTTON_RIGHT); mLastButtonRightClick = 0; mLastButtonRightClicked = 0; } } else if( Event->button.button == EE_BUTTON_MIDDLE ) { mLastButtonMiddleClicked = mLastButtonMiddleClick; mLastButtonMiddleClick = Sys::GetTicks(); mTClick = mLastButtonMiddleClick - mLastButtonMiddleClicked; if ( mTClick < mDoubleClickInterval && mTClick > 0 ) { mDoubleClickTrigger |= EE_BUTTON_MASK(EE_BUTTON_MIDDLE); mLastButtonMiddleClick = 0; mLastButtonMiddleClicked = 0; } } break; } case InputEvent::FingerDown: { cInputFinger * Finger = GetFingerId( Event->finger.fingerId ); Finger->WriteLast(); Finger->x = (Uint16)( Event->finger.x * (eeFloat)mWindow->GetWidth() ); Finger->y = (Uint16)( Event->finger.y * (eeFloat)mWindow->GetHeight() ); Finger->pressure = Event->finger.pressure; Finger->down = true; Finger->xdelta = Event->finger.dx; Finger->ydelta = Event->finger.dy; break; } case InputEvent::FingerUp: { cInputFinger * Finger = GetFingerId( Event->finger.fingerId ); Finger->WriteLast(); Finger->x = (Uint16)( Event->finger.x * (eeFloat)mWindow->GetWidth() ); Finger->y = (Uint16)( Event->finger.y * (eeFloat)mWindow->GetHeight() ); Finger->pressure = Event->finger.pressure; Finger->down = false; Finger->was_down = true; Finger->xdelta = Event->finger.dx; Finger->ydelta = Event->finger.dy; break; } case InputEvent::FingerMotion: { cInputFinger * Finger = GetFingerId( Event->finger.fingerId ); Finger->WriteLast(); Finger->x = (Uint16)( Event->finger.x * (eeFloat)mWindow->GetWidth() ); Finger->y = (Uint16)( Event->finger.y * (eeFloat)mWindow->GetHeight() ); Finger->pressure = Event->finger.pressure; Finger->down = true; Finger->xdelta = Event->finger.dx; Finger->ydelta = Event->finger.dy; break; } case InputEvent::VideoResize: { mWindow->Size( Event->resize.w, Event->resize.h, mWindow->Windowed() ); break; } case InputEvent::Quit: { mWindow->Close(); break; } } SendEvent( Event ); } cInputFinger * cInput::GetFingerId( const Int64 &fingerId ) { Uint32 i; for ( i = 0; i < EE_MAX_FINGERS; i++ ) { if ( mFingers[i].id == fingerId ) { return &mFingers[i]; } } for ( i = 0; i < EE_MAX_FINGERS; i++ ) { if ( -1 == mFingers[i].id ) { mFingers[i].id = fingerId; return &mFingers[i]; } } //! Find first unused for ( i = 0; i < EE_MAX_FINGERS; i++ ) { if ( !mFingers[i].down ) { mFingers[i].id = fingerId; return &mFingers[i]; } } return NULL; } void cInput::ResetFingerWasDown() { for ( Uint32 i = 0; i < EE_MAX_FINGERS; i++ ) { mFingers[i].was_down = false; } } bool cInput::IsKeyDown( const EE_KEY& Key ) { return 0 != BitOp::ReadBitKey( &mKeysDown[ Key / 8 ], Key % 8 ); } bool cInput::IsKeyUp( const EE_KEY& Key ) { return 0 != BitOp::ReadBitKey( &mKeysUp[ Key / 8 ], Key % 8 ); } void cInput::InjectKeyDown( const EE_KEY& Key ) { BitOp::WriteBitKey( &mKeysDown [ Key / 8 ], Key % 8, 1 ); } void cInput::InjectKeyUp( const EE_KEY& Key ) { BitOp::WriteBitKey( &mKeysUp [ Key / 8 ], Key % 8, 1 ); } void cInput::InjectButtonPress( const Uint32& Button ) { if ( Button < 8 ) if ( !( mPressTrigger & EE_BUTTON_MASK( Button ) ) ) mPressTrigger |= EE_BUTTON_MASK( Button ); } void cInput::InjectButtonRelease( const Uint32& Button ) { if ( Button < 8 ) { if ( mPressTrigger & EE_BUTTON_MASK( Button ) ) mPressTrigger &= ~EE_BUTTON_MASK( Button ); if ( !( mReleaseTrigger & EE_BUTTON_MASK( Button ) ) ) mReleaseTrigger |= EE_BUTTON_MASK( Button ); if ( !( mClickTrigger & EE_BUTTON_MASK( Button ) ) ) mClickTrigger |= EE_BUTTON_MASK( Button ); } } eeVector2i cInput::GetMousePos() const { return mMousePos; } void cInput::SetMousePos( const eeVector2i& Pos ) { mMousePos = Pos; } eeVector2f cInput::GetMousePosf() { return eeVector2f( (eeFloat)mMousePos.x, (eeFloat)mMousePos.y ); } eeVector2i cInput::GetMousePosFromView( const cView& View ) { eeVector2i RealMousePos = GetMousePos(); eeRecti RView = View.GetView(); return eeVector2i( RealMousePos.x - RView.Left, RealMousePos.y - RView.Top ); } Uint16 cInput::MouseX() const { return mMousePos.x; } Uint16 cInput::MouseY() const { return mMousePos.y; } Uint32 cInput::PushCallback( const InputCallback& cb ) { mNumCallBacks++; mCallbacks[ mNumCallBacks ] = cb; return mNumCallBacks; } void cInput::PopCallback( const Uint32& CallbackId ) { mCallbacks[ CallbackId ] = 0; mCallbacks.erase( mCallbacks.find(CallbackId) ); } void cInput::InjectMousePos( const eeVector2i& Pos ) { InjectMousePos( Pos.x, Pos.y ); } bool cInput::ControlPressed() const { return ( mInputMod & KEYMOD_CTRL ) != 0; } bool cInput::ShiftPressed() const { return ( mInputMod & KEYMOD_SHIFT ) != 0; } bool cInput::AltPressed() const { return ( mInputMod & KEYMOD_ALT ) != 0; } bool cInput::MetaPressed() const { return ( mInputMod & KEYMOD_META ) != 0; } bool cInput::MouseLeftPressed() const { return ( mPressTrigger & EE_BUTTON_LMASK ) != 0; } bool cInput::MouseRightPressed() const { return ( mPressTrigger & EE_BUTTON_RMASK ) != 0; } bool cInput::MouseMiddlePressed() const { return ( mPressTrigger & EE_BUTTON_MMASK ) != 0; } bool cInput::MouseLeftClick() const { return ( mClickTrigger & EE_BUTTON_LMASK ) != 0; } bool cInput::MouseRightClick() const { return ( mClickTrigger & EE_BUTTON_RMASK ) != 0; } bool cInput::MouseMiddleClick() const { return ( mClickTrigger & EE_BUTTON_MMASK ) != 0; } bool cInput::MouseLeftDoubleClick() const { return ( mDoubleClickTrigger & EE_BUTTON_LMASK ) != 0; } bool cInput::MouseRightDoubleClick() const { return ( mDoubleClickTrigger & EE_BUTTON_RMASK ) != 0; } bool cInput::MouseMiddleDoubleClick() const { return ( mDoubleClickTrigger & EE_BUTTON_MMASK ) != 0; } bool cInput::MouseWheelUp() const { return ( mReleaseTrigger & EE_BUTTON_WUMASK ) != 0; } bool cInput::MouseWheelDown() const { return ( mReleaseTrigger & EE_BUTTON_WDMASK ) != 0; } void cInput::MouseSpeed( const eeFloat& Speed ) { mMouseSpeed = Speed; } const eeFloat& cInput::MouseSpeed() const { return mMouseSpeed; } const Uint32& cInput::LastPressTrigger() const { return mLastPressTrigger; } const Uint32& cInput::PressTrigger() const { return mPressTrigger; } const Uint32& cInput::ReleaseTrigger() const { return mReleaseTrigger; } const Uint32& cInput::ClickTrigger() const { return mClickTrigger; } const Uint32& cInput::DoubleClickTrigger() const { return mDoubleClickTrigger; } const Uint32& cInput::DoubleClickInterval() const { return mDoubleClickInterval; } void cInput::DoubleClickInterval( const Uint32& Interval ) { mDoubleClickInterval = Interval; } cJoystickManager * cInput::GetJoystickManager() const { return mJoystickManager; } Uint32 cInput::GetFingerCount() { return EE_MAX_FINGERS; } cInputFinger * cInput::GetFingerIndex( const Uint32 &Index ) { eeASSERT( Index < EE_MAX_FINGERS ); return &mFingers[Index]; } cInputFinger * cInput::GetFinger( const Int64 &fingerId ) { for ( Uint32 i = 0; i < EE_MAX_FINGERS; i++ ) { if ( mFingers[i].id == fingerId ) { return &mFingers[i]; } } return NULL; } std::list cInput::GetFingersDown() { std::list fDown; for ( Uint32 i = 0; i < EE_MAX_FINGERS; i++ ) { if ( mFingers[i].down ) { fDown.push_back( &mFingers[i] ); } } return fDown; } std::list cInput::GetFingersWasDown() { std::list fDown; for ( Uint32 i = 0; i < EE_MAX_FINGERS; i++ ) { if ( mFingers[i].was_down ) { fDown.push_back( &mFingers[i] ); } } return fDown; } }} // Copyright (c) 2017, SUMOKOIN // // 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. // // Parts of this file are originally copyright (c) 2012-2013, The Cryptonote developers #include "cn_heavy_hash.hpp" extern "C" { #include "../crypto/keccak.h" } /* AES Tables Implementation is --------------------------------------------------------------------------- Copyright (c) 1998-2013, , Worcester, UK. All rights reserved. The redistribution and use of this software (with or without changes) is allowed without the payment of fees or royalties provided that: source code distributions include the above copyright notice, this list of conditions and the following disclaimer; binary distributions include the above copyright notice, this list of conditions and the following disclaimer in their documentation. This software is provided 'as is' with no explicit or implied warranties in respect of its operation, including, but not limited to, correctness and fitness for purpose. --------------------------------------------------------------------------- */ #if !defined(_LP64) && !defined(_WIN64) #define BUILD32 #endif #define saes_data(w) {\ w(0x63), w(0x7c), w(0x77), w(0x7b), w(0xf2), w(0x6b), w(0x6f), w(0xc5),\ w(0x30), w(0x01), w(0x67), w(0x2b), w(0xfe), w(0xd7), w(0xab), w(0x76),\ w(0xca), w(0x82), w(0xc9), w(0x7d), w(0xfa), w(0x59), w(0x47), w(0xf0),\ w(0xad), w(0xd4), w(0xa2), w(0xaf), w(0x9c), w(0xa4), w(0x72), w(0xc0),\ w(0xb7), w(0xfd), w(0x93), w(0x26), w(0x36), w(0x3f), w(0xf7), w(0xcc),\ w(0x34), w(0xa5), w(0xe5), w(0xf1), w(0x71), w(0xd8), w(0x31), w(0x15),\ w(0x04), w(0xc7), w(0x23), w(0xc3), w(0x18), w(0x96), w(0x05), w(0x9a),\ w(0x07), w(0x12), w(0x80), w(0xe2), w(0xeb), w(0x27), w(0xb2), w(0x75),\ w(0x09), w(0x83), w(0x2c), w(0x1a), w(0x1b), w(0x6e), w(0x5a), w(0xa0),\ w(0x52), w(0x3b), w(0xd6), w(0xb3), w(0x29), w(0xe3), w(0x2f), w(0x84),\ w(0x53), w(0xd1), w(0x00), w(0xed), w(0x20), w(0xfc), w(0xb1), w(0x5b),\ w(0x6a), w(0xcb), w(0xbe), w(0x39), w(0x4a), w(0x4c), w(0x58), w(0xcf),\ w(0xd0), w(0xef), w(0xaa), w(0xfb), w(0x43), w(0x4d), w(0x33), w(0x85),\ w(0x45), w(0xf9), w(0x02), w(0x7f), w(0x50), w(0x3c), w(0x9f), w(0xa8),\ w(0x51), w(0xa3), w(0x40), w(0x8f), w(0x92), w(0x9d), w(0x38), w(0xf5),\ w(0xbc), w(0xb6), w(0xda), w(0x21), w(0x10), w(0xff), w(0xf3), w(0xd2),\ w(0xcd), w(0x0c), w(0x13), w(0xec), w(0x5f), w(0x97), w(0x44), w(0x17),\ w(0xc4), w(0xa7), w(0x7e), w(0x3d), w(0x64), w(0x5d), w(0x19), w(0x73),\ w(0x60), w(0x81), w(0x4f), w(0xdc), w(0x22), w(0x2a), w(0x90), w(0x88),\ w(0x46), w(0xee), w(0xb8), w(0x14), w(0xde), w(0x5e), w(0x0b), w(0xdb),\ w(0xe0), w(0x32), w(0x3a), w(0x0a), w(0x49), w(0x06), w(0x24), w(0x5c),\ w(0xc2), w(0xd3), w(0xac), w(0x62), w(0x91), w(0x95), w(0xe4), w(0x79),\ w(0xe7), w(0xc8), w(0x37), w(0x6d), w(0x8d), w(0xd5), w(0x4e), w(0xa9),\ w(0x6c), w(0x56), w(0xf4), w(0xea), w(0x65), w(0x7a), w(0xae), w(0x08),\ w(0xba), w(0x78), w(0x25), w(0x2e), w(0x1c), w(0xa6), w(0xb4), w(0xc6),\ w(0xe8), w(0xdd), w(0x74), w(0x1f), w(0x4b), w(0xbd), w(0x8b), w(0x8a),\ w(0x70), w(0x3e), w(0xb5), w(0x66), w(0x48), w(0x03), w(0xf6), w(0x0e),\ w(0x61), w(0x35), w(0x57), w(0xb9), w(0x86), w(0xc1), w(0x1d), w(0x9e),\ w(0xe1), w(0xf8), w(0x98), w(0x11), w(0x69), w(0xd9), w(0x8e), w(0x94),\ w(0x9b), w(0x1e), w(0x87), w(0xe9), w(0xce), w(0x55), w(0x28), w(0xdf),\ w(0x8c), w(0xa1), w(0x89), w(0x0d), w(0xbf), w(0xe6), w(0x42), w(0x68),\ w(0x41), w(0x99), w(0x2d), w(0x0f), w(0xb0), w(0x54), w(0xbb), w(0x16) } #define SAES_WPOLY 0x011b #define saes_b2w(b0, b1, b2, b3) (((uint32_t)(b3) << 24) | \ ((uint32_t)(b2) << 16) | ((uint32_t)(b1) << 8) | (b0)) #define saes_f2(x) ((x<<1) ^ (((x>>7) & 1) * SAES_WPOLY)) #define saes_f3(x) (saes_f2(x) ^ x) #define saes_h0(x) (x) #define saes_u0(p) saes_b2w(saes_f2(p), p, p, saes_f3(p)) #define saes_u1(p) saes_b2w(saes_f3(p), saes_f2(p), p, p) #define saes_u2(p) saes_b2w( p, saes_f3(p), saes_f2(p), p) #define saes_u3(p) saes_b2w( p, p, saes_f3(p), saes_f2(p)) alignas(16) const uint32_t saes_table[4][256] = { saes_data(saes_u0), saes_data(saes_u1), saes_data(saes_u2), saes_data(saes_u3) }; alignas(16) extern const uint8_t saes_sbox[256] = saes_data(saes_h0); struct aesdata { uint64_t v64x0; uint64_t v64x1; inline void load(const cn_sptr mem) { v64x0 = mem.as_uqword(0); v64x1 = mem.as_uqword(1); } inline void xor_load(const cn_sptr mem) { v64x0 ^= mem.as_uqword(0); v64x1 ^= mem.as_uqword(1); } inline void write(cn_sptr mem) { mem.as_uqword(0) = v64x0; mem.as_uqword(1) = v64x1; } inline aesdata& operator^=(const aesdata& rhs) noexcept { v64x0 ^= rhs.v64x0; v64x1 ^= rhs.v64x1; return *this; } inline aesdata& operator^=(uint32_t rhs) noexcept { uint64_t t = (uint64_t(rhs) << 32) | uint64_t(rhs); v64x0 ^= t; v64x1 ^= t; return *this; } inline void get_quad(uint32_t& x0, uint32_t& x1, uint32_t& x2, uint32_t& x3) { x0 = v64x0; x1 = v64x0 >> 32; x2 = v64x1; x3 = v64x1 >> 32; } inline void set_quad(uint32_t x0, uint32_t x1, uint32_t x2, uint32_t x3) { v64x0 = uint64_t(x0) | uint64_t(x1) << 32; v64x1 = uint64_t(x2) | uint64_t(x3) << 32; } }; inline uint32_t sub_word(uint32_t key) { return (saes_sbox[key >> 24 ] << 24) | (saes_sbox[(key >> 16) & 0xff] << 16 ) | (saes_sbox[(key >> 8) & 0xff] << 8 ) | saes_sbox[key & 0xff]; } #if defined(__clang__) || !(defined(__x86_64__) || defined(__i386__)) inline uint32_t rotr(uint32_t value, uint32_t amount) { return (value >> amount) | (value << ((32 - amount) & 31)); } #else inline uint32_t rotr(uint32_t value, uint32_t amount) { return _rotr(value, amount); } #endif // sl_xor(a1 a2 a3 a4) = a1 (a2^a1) (a3^a2^a1) (a4^a3^a2^a1) inline void sl_xor(aesdata& x) { uint32_t x0, x1, x2, x3; x.get_quad(x0, x1, x2, x3); x1 ^= x0; x2 ^= x1; x3 ^= x2; x.set_quad(x0, x1, x2, x3); } template inline void soft_aes_genkey_sub(aesdata& xout0, aesdata& xout2) { sl_xor(xout0); xout0 ^= rotr(sub_word(xout2.v64x1 >> 32), 8) ^ rcon; sl_xor(xout2); xout2 ^= sub_word(xout0.v64x1 >> 32); } inline void aes_genkey(const cn_sptr memory, aesdata& k0, aesdata& k1, aesdata& k2, aesdata& k3, aesdata& k4, aesdata& k5, aesdata& k6, aesdata& k7, aesdata& k8, aesdata& k9) { aesdata xout0, xout2; xout0.load(memory); xout2.load(memory.offset(16)); k0 = xout0; k1 = xout2; soft_aes_genkey_sub<0x01>(xout0, xout2); k2 = xout0; k3 = xout2; soft_aes_genkey_sub<0x02>(xout0, xout2); k4 = xout0; k5 = xout2; soft_aes_genkey_sub<0x04>(xout0, xout2); k6 = xout0; k7 = xout2; soft_aes_genkey_sub<0x08>(xout0, xout2); k8 = xout0; k9 = xout2; } inline void aes_round(aesdata& val, const aesdata& key) { uint32_t x0, x1, x2, x3; val.get_quad(x0, x1, x2, x3); val.set_quad(saes_table[0][x0 & 0xff] ^ saes_table[1][(x1 >> 8) & 0xff] ^ saes_table[2][(x2 >> 16) & 0xff] ^ saes_table[3][x3 >> 24], saes_table[0][x1 & 0xff] ^ saes_table[1][(x2 >> 8) & 0xff] ^ saes_table[2][(x3 >> 16) & 0xff] ^ saes_table[3][x0 >> 24], saes_table[0][x2 & 0xff] ^ saes_table[1][(x3 >> 8) & 0xff] ^ saes_table[2][(x0 >> 16) & 0xff] ^ saes_table[3][x1 >> 24], saes_table[0][x3 & 0xff] ^ saes_table[1][(x0 >> 8) & 0xff] ^ saes_table[2][(x1 >> 16) & 0xff] ^ saes_table[3][x2 >> 24]); val ^= key; } inline void aes_round8(const aesdata& key, aesdata& x0, aesdata& x1, aesdata& x2, aesdata& x3, aesdata& x4, aesdata& x5, aesdata& x6, aesdata& x7) { aes_round(x0, key); aes_round(x1, key); aes_round(x2, key); aes_round(x3, key); aes_round(x4, key); aes_round(x5, key); aes_round(x6, key); aes_round(x7, key); } inline void xor_shift(aesdata& x0, aesdata& x1, aesdata& x2, aesdata& x3, aesdata& x4, aesdata& x5, aesdata& x6, aesdata& x7) { aesdata tmp = x0; x0 ^= x1; x1 ^= x2; x2 ^= x3; x3 ^= x4; x4 ^= x5; x5 ^= x6; x6 ^= x7; x7 ^= tmp; } template void cn_heavy_hash::implode_scratchpad_soft() { aesdata x0, x1, x2, x3, x4, x5, x6, x7; aesdata k0, k1, k2, k3, k4, k5, k6, k7, k8, k9; aes_genkey(spad.as_uqword() + 4, k0, k1, k2, k3, k4, k5, k6, k7, k8, k9); x0.load(spad.as_uqword() + 8); x1.load(spad.as_uqword() + 10); x2.load(spad.as_uqword() + 12); x3.load(spad.as_uqword() + 14); x4.load(spad.as_uqword() + 16); x5.load(spad.as_uqword() + 18); x6.load(spad.as_uqword() + 20); x7.load(spad.as_uqword() + 22); for (size_t i = 0; i < MEMORY / sizeof(uint64_t); i += 16) { x0.xor_load(lpad.as_uqword() + i + 0); x1.xor_load(lpad.as_uqword() + i + 2); x2.xor_load(lpad.as_uqword() + i + 4); x3.xor_load(lpad.as_uqword() + i + 6); x4.xor_load(lpad.as_uqword() + i + 8); x5.xor_load(lpad.as_uqword() + i + 10); x6.xor_load(lpad.as_uqword() + i + 12); x7.xor_load(lpad.as_uqword() + i + 14); aes_round8(k0, x0, x1, x2, x3, x4, x5, x6, x7); aes_round8(k1, x0, x1, x2, x3, x4, x5, x6, x7); aes_round8(k2, x0, x1, x2, x3, x4, x5, x6, x7); aes_round8(k3, x0, x1, x2, x3, x4, x5, x6, x7); aes_round8(k4, x0, x1, x2, x3, x4, x5, x6, x7); aes_round8(k5, x0, x1, x2, x3, x4, x5, x6, x7); aes_round8(k6, x0, x1, x2, x3, x4, x5, x6, x7); aes_round8(k7, x0, x1, x2, x3, x4, x5, x6, x7); aes_round8(k8, x0, x1, x2, x3, x4, x5, x6, x7); aes_round8(k9, x0, x1, x2, x3, x4, x5, x6, x7); if(VERSION > 0) xor_shift(x0, x1, x2, x3, x4, x5, x6, x7); } // Note, this loop is only executed if VERSION > 0 for (size_t i = 0; VERSION > 0 && i < MEMORY / sizeof(uint64_t); i += 16) { x0.xor_load(lpad.as_uqword() + i + 0); x1.xor_load(lpad.as_uqword() + i + 2); x2.xor_load(lpad.as_uqword() + i + 4); x3.xor_load(lpad.as_uqword() + i + 6); x4.xor_load(lpad.as_uqword() + i + 8); x5.xor_load(lpad.as_uqword() + i + 10); x6.xor_load(lpad.as_uqword() + i + 12); x7.xor_load(lpad.as_uqword() + i + 14); aes_round8(k0, x0, x1, x2, x3, x4, x5, x6, x7); aes_round8(k1, x0, x1, x2, x3, x4, x5, x6, x7); aes_round8(k2, x0, x1, x2, x3, x4, x5, x6, x7); aes_round8(k3, x0, x1, x2, x3, x4, x5, x6, x7); aes_round8(k4, x0, x1, x2, x3, x4, x5, x6, x7); aes_round8(k5, x0, x1, x2, x3, x4, x5, x6, x7); aes_round8(k6, x0, x1, x2, x3, x4, x5, x6, x7); aes_round8(k7, x0, x1, x2, x3, x4, x5, x6, x7); aes_round8(k8, x0, x1, x2, x3, x4, x5, x6, x7); aes_round8(k9, x0, x1, x2, x3, x4, x5, x6, x7); xor_shift(x0, x1, x2, x3, x4, x5, x6, x7); } // Note, this loop is only executed if VERSION > 0 for (size_t i = 0; VERSION > 0 && i < 16; i++) { aes_round8(k0, x0, x1, x2, x3, x4, x5, x6, x7); aes_round8(k1, x0, x1, x2, x3, x4, x5, x6, x7); aes_round8(k2, x0, x1, x2, x3, x4, x5, x6, x7); aes_round8(k3, x0, x1, x2, x3, x4, x5, x6, x7); aes_round8(k4, x0, x1, x2, x3, x4, x5, x6, x7); aes_round8(k5, x0, x1, x2, x3, x4, x5, x6, x7); aes_round8(k6, x0, x1, x2, x3, x4, x5, x6, x7); aes_round8(k7, x0, x1, x2, x3, x4, x5, x6, x7); aes_round8(k8, x0, x1, x2, x3, x4, x5, x6, x7); aes_round8(k9, x0, x1, x2, x3, x4, x5, x6, x7); xor_shift(x0, x1, x2, x3, x4, x5, x6, x7); } x0.write(spad.as_uqword() + 8); x1.write(spad.as_uqword() + 10); x2.write(spad.as_uqword() + 12); x3.write(spad.as_uqword() + 14); x4.write(spad.as_uqword() + 16); x5.write(spad.as_uqword() + 18); x6.write(spad.as_uqword() + 20); x7.write(spad.as_uqword() + 22); } template void cn_heavy_hash::explode_scratchpad_soft() { aesdata x0, x1, x2, x3, x4, x5, x6, x7; aesdata k0, k1, k2, k3, k4, k5, k6, k7, k8, k9; aes_genkey(spad.as_uqword(), k0, k1, k2, k3, k4, k5, k6, k7, k8, k9); x0.load(spad.as_uqword() + 8); x1.load(spad.as_uqword() + 10); x2.load(spad.as_uqword() + 12); x3.load(spad.as_uqword() + 14); x4.load(spad.as_uqword() + 16); x5.load(spad.as_uqword() + 18); x6.load(spad.as_uqword() + 20); x7.load(spad.as_uqword() + 22); // Note, this loop is only executed if VERSION > 0 for (size_t i = 0; VERSION > 0 && i < 16; i++) { aes_round8(k0, x0, x1, x2, x3, x4, x5, x6, x7); aes_round8(k1, x0, x1, x2, x3, x4, x5, x6, x7); aes_round8(k2, x0, x1, x2, x3, x4, x5, x6, x7); aes_round8(k3, x0, x1, x2, x3, x4, x5, x6, x7); aes_round8(k4, x0, x1, x2, x3, x4, x5, x6, x7); aes_round8(k5, x0, x1, x2, x3, x4, x5, x6, x7); aes_round8(k6, x0, x1, x2, x3, x4, x5, x6, x7); aes_round8(k7, x0, x1, x2, x3, x4, x5, x6, x7); aes_round8(k8, x0, x1, x2, x3, x4, x5, x6, x7); aes_round8(k9, x0, x1, x2, x3, x4, x5, x6, x7); xor_shift(x0, x1, x2, x3, x4, x5, x6, x7); } for (size_t i = 0; i < MEMORY / sizeof(uint64_t); i += 16) { aes_round8(k0, x0, x1, x2, x3, x4, x5, x6, x7); aes_round8(k1, x0, x1, x2, x3, x4, x5, x6, x7); aes_round8(k2, x0, x1, x2, x3, x4, x5, x6, x7); aes_round8(k3, x0, x1, x2, x3, x4, x5, x6, x7); aes_round8(k4, x0, x1, x2, x3, x4, x5, x6, x7); aes_round8(k5, x0, x1, x2, x3, x4, x5, x6, x7); aes_round8(k6, x0, x1, x2, x3, x4, x5, x6, x7); aes_round8(k7, x0, x1, x2, x3, x4, x5, x6, x7); aes_round8(k8, x0, x1, x2, x3, x4, x5, x6, x7); aes_round8(k9, x0, x1, x2, x3, x4, x5, x6, x7); x0.write(lpad.as_uqword() + i + 0); x1.write(lpad.as_uqword() + i + 2); x2.write(lpad.as_uqword() + i + 4); x3.write(lpad.as_uqword() + i + 6); x4.write(lpad.as_uqword() + i + 8); x5.write(lpad.as_uqword() + i + 10); x6.write(lpad.as_uqword() + i + 12); x7.write(lpad.as_uqword() + i + 14); } } #ifdef BUILD32 inline uint64_t _umul128(uint64_t multiplier, uint64_t multiplicand, uint64_t* product_hi) { // multiplier = ab = a * 2^32 + b // multiplicand = cd = c * 2^32 + d // ab * cd = a * c * 2^64 + (a * d + b * c) * 2^32 + b * d uint64_t a = multiplier >> 32; uint64_t b = multiplier & 0xFFFFFFFF; uint64_t c = multiplicand >> 32; uint64_t d = multiplicand & 0xFFFFFFFF; uint64_t ac = a * c; uint64_t ad = a * d; uint64_t bc = b * c; uint64_t bd = b * d; uint64_t adbc = ad + bc; uint64_t adbc_carry = adbc < ad ? 1 : 0; // multiplier * multiplicand = product_hi * 2^64 + product_lo uint64_t product_lo = bd + (adbc << 32); uint64_t product_lo_carry = product_lo < bd ? 1 : 0; *product_hi = ac + (adbc >> 32) + (adbc_carry << 32) + product_lo_carry; return product_lo; } #else #if !defined(HAS_WIN_INTRIN_API) inline uint64_t _umul128(uint64_t a, uint64_t b, uint64_t* hi) { unsigned __int128 r = (unsigned __int128)a * (unsigned __int128)b; *hi = r >> 64; return (uint64_t)r; } #endif #endif extern "C" void blake256_hash(uint8_t*, const uint8_t*, uint64_t); extern "C" void groestl(const unsigned char*, unsigned long long, unsigned char*); extern "C" size_t jh_hash(int, const unsigned char*, unsigned long long, unsigned char*); extern "C" size_t skein_hash(int, const unsigned char*, size_t, unsigned char*); template void cn_heavy_hash::software_hash(const void* in, size_t len, void* out, bool prehashed) { if (!prehashed) keccak((const uint8_t *)in, len, spad.as_byte(), 200); explode_scratchpad_soft(); uint64_t* h0 = spad.as_uqword(); aesdata ax; ax.v64x0 = h0[0] ^ h0[4]; ax.v64x1 = h0[1] ^ h0[5]; aesdata bx; bx.v64x0 = h0[2] ^ h0[6]; bx.v64x1 = h0[3] ^ h0[7]; aesdata cx; cn_sptr idx = scratchpad_ptr(ax.v64x0); for(size_t i = 0; i < ITER/2; i++) { uint64_t hi, lo; cx.load(idx); aes_round(cx, ax); bx ^= cx; bx.write(idx); idx = scratchpad_ptr(cx.v64x0); bx.load(idx); lo = _umul128(cx.v64x0, bx.v64x0, &hi); ax.v64x0 += hi; ax.v64x1 += lo; ax.write(idx); ax ^= bx; idx = scratchpad_ptr(ax.v64x0); if(VERSION > 0) { int64_t n = idx.as_qword(0); int32_t d = idx.as_dword(2); #if defined(__arm__) asm volatile ("nop"); //Fix for RasPi3 ARM - maybe needed on armv8 #endif int64_t q = n / (d | 5); idx.as_qword(0) = n ^ q; idx = scratchpad_ptr(d ^ q); } bx.load(idx); aes_round(bx, ax); cx ^= bx; cx.write(idx); idx = scratchpad_ptr(bx.v64x0); cx.load(idx); lo = _umul128(bx.v64x0, cx.v64x0, &hi); ax.v64x0 += hi; ax.v64x1 += lo; ax.write(idx); ax ^= cx; idx = scratchpad_ptr(ax.v64x0); if(VERSION > 0) { int64_t n = idx.as_qword(0); // read bytes 0 - 7 int32_t d = idx.as_dword(2); // read bytes 8 - 11 #if defined(__arm__) asm volatile ("nop"); //Fix for RasPi3 ARM - maybe needed on armv8 #endif int64_t q = n / (d | 5); idx.as_qword(0) = n ^ q; idx = scratchpad_ptr(d ^ q); } } implode_scratchpad_soft(); keccakf(spad.as_uqword(), 24); switch(spad.as_byte(0) & 3) { case 0: blake256_hash((uint8_t*)out, spad.as_byte(), 200); break; case 1: groestl(spad.as_byte(), 200 * 8, (uint8_t*)out); break; case 2: jh_hash(32 * 8, spad.as_byte(), 8 * 200, (uint8_t*)out); break; case 3: skein_hash(8 * 32, spad.as_byte(), 8 * 200, (uint8_t*)out); break; } } template class cn_heavy_hash<2*1024*1024, 0x80000, 0>; template class cn_heavy_hash<4*1024*1024, 0x40000, 1>; /** Purpose: Sketch Recongnition server */ #include #include #include #include #include #include #include #include using namespace cv; using namespace cv::dnn; #include #include #include using namespace std; #include "json/json.h" #include "socketServer.h" #include "helper.h" volatile bool sketchRecivedState; std::string modelFolderName ; std::string modelBinName ; std::string saveFolderName; int currentSaveNum ; QString base64_encode(QString string){ QByteArray ba; ba.append(string); return ba.toBase64(); } /* Threading control */ volatile bool g_running = false; volatile bool g_stop = true; int call_from_thread(SocketServer* server); int call_from_thread2(SocketServer* server) { String imageFile = "11392.png"; Mat img = imread(imageFile,-1); if(! img.data || img.empty()) // Check for invalid input { std::cerr << "Can't read image from the file: " << imageFile << std::endl; sketchRecivedState = false ; return -1 ; } cerr << "Displaying image before Calculating" << endl ; imwrite("myimg.png",img); // cv::waitKey(5000) ; } int infinityThread(SocketServer* server) { while (1) { //sketchRecivedState = true ; if(sketchRecivedState) { cout << "Calculating Sketech association" << endl ; call_from_thread(server); cv::destroyAllWindows(); } std::this_thread::sleep_for(std::chrono::milliseconds(500)); cout << "Waiting for image ... " << endl; } return 0; } /* Find best class for the blob (i. e. class with maximal probability) */ void getMaxClass(dnn::Blob &probBlob, int *classId, double *classProb) { Mat probMat = probBlob.matRefConst().reshape(1, 1); //reshape the blob to 1x1000 matrix Point classNumber; minMaxLoc(probMat, NULL, classProb, NULL, &classNumber); *classId = classNumber.x; } std::vector readClassNames() { std::string filename = modelFolderName + "map.txt" ; cout << filename ; std::vector classNames; std::ifstream fp(filename); if (!fp.is_open()) { std::cerr << "File with classes labels not found: " << filename << std::endl; exit(-1); } std::string name; while (!fp.eof()) { std::getline(fp, name); if (name.length()) classNames.push_back( name.substr(name.find(' ')+1) ); } fp.close(); return classNames; } void preProcessImage128(cv::Mat& src,cv::Mat& dst) { auto duration = std::chrono::system_clock::now().time_since_epoch(); auto milliseconds_since_epoch = std::chrono::duration_cast(duration).count(); ostringstream ostrm , ostrm2,xyFileName ; ostrm << saveFolderName << milliseconds_since_epoch << ".png" ; cv::imwrite(ostrm.str() ,src) ; if(src.channels() == 1) { dst = src.clone() ; } else if(src.channels() == 3) { cv::cvtColor(src, dst, CV_BGR2GRAY); } else if(src.channels() == 4) { std::vector layers; cv::split(src, layers); dst = layers[3]; dst = 255 - dst ; //kernel = np.ones((3,3),np.uint8); cv::erode(dst, dst, Mat(), Point(-1, -1),1); // cv::imwrite("dst.png",dst) ; } if(dst.rows != 128 || dst.cols != 128) { cout << "converting into 128 image" << endl ; cv::erode(dst, dst, Mat(), Point(-1, -1),3); cv::dilate(dst, dst, Mat(), Point(-1, -1),1); cv::Size newsize(128,128); cv::Mat resized_img; cv::resize(dst, resized_img, newsize ); double thresh = 250; double maxValue = 255; cv::threshold(resized_img,resized_img, thresh, maxValue, THRESH_BINARY); resized_img = 255 - resized_img; // Calculating Min bounding Box of object drawn Mat Points; findNonZero(resized_img,Points); Rect Min_Rect=boundingRect(Points); // Get the roi in the input image according to the mask Mat roi(resized_img(Min_Rect)); //Vec3b backgroundColor(0); // black Mat segmentedItem(roi.rows, roi.cols,CV_8UC1); roi.copyTo(segmentedItem); // copy min bounding box image to center Point center(resized_img.cols / 2, resized_img.rows / 2); Mat centeredImg(resized_img.rows, resized_img.cols,CV_8UC1); centeredImg = 0; Rect centerBox(center.x - Min_Rect.width / 2, center.y - Min_Rect.height / 2, Min_Rect.width, Min_Rect.height); //segmentedItem.copyTo(centeredImg(centerBox)); //cv::rectangle(centeredImg, centerBox, Scalar(255), 2); //cv::imshow("oldCenteredImg", centeredImg); //cv::waitKey(2000); // check float smallCheckRatio = 3; if ( (centerBox.width <= (int)(centeredImg.cols / smallCheckRatio)) && (centerBox.height <= (int)(centeredImg.rows / smallCheckRatio))) { cout << "too small image resize needed " << endl; // New size double correctionRatioW = centeredImg.cols / (double)(centerBox.width) ; double correctionRatioH = centeredImg.rows /(double) (centerBox.height); // take smaller of two correction ratio double correctionRatio = (correctionRatioW < correctionRatioH) ? correctionRatioW : correctionRatioH; correctionRatio = correctionRatio / 2.0; // only need 2x correction cout << "scaling image by W " << correctionRatioW << " H " << correctionRatioH << " F " < importer; try //Try to import Caffe GoogleNet model { importer = dnn::createCaffeImporter(modelTxt, modelBin); } catch (const cv::Exception &err) //Importer can throw errors, we will catch them { std::cerr << "Error in importing " << err.msg << std::endl; } //! [Create the importer of Caffe model] if (!importer) { std::cerr << "Can't load network by using the following files: " << std::endl; std::cerr << "prototxt: " << modelTxt << std::endl; std::cerr << "caffemodel: " << modelBin << std::endl; exit(-1); } //! [Prepare blob] Mat img = imread(imageFile,-1); if(! img.data || img.empty()) // Check for invalid input { std::cerr << "Can't read image from the file: " << imageFile << std::endl; sketchRecivedState = false ; return -1 ; } Mat img2 ; preProcessImage128(img,img2); // cerr << "Displaying image before Calculating" << endl ; //imshow("testImage",img); //cv::waitKey(5000) ; //! [Initialize network] dnn::Net net; importer->populateNet(net); importer.release(); //We don't need importer anymore //! [Initialize network] //Convert Mat to dnn::Blob image batch dnn::Blob inputBlob = dnn::Blob::fromImages(img2); //dnn::Blob inputBlob = dnn::Blob(img2); // Old method in opencv 3.0 //! [Prepare blob] //! [Set input blob] net.setBlob(".data", inputBlob); //set the network input //! [Set input blob] //! [Make forward pass] net.forward(); //compute output //! [Make forward pass] //! [Gather output] dnn::Blob prob = net.getBlob("prob"); //gather output of "prob" layer int classId; double classProb; getMaxClass(prob, &classId, &classProb);//find the best class //! [Gather output] //! [Print results] std::vector classNames = readClassNames(); std::cout << "Best class: #" << classId << " '" << classNames.at(classId) << "'" << std::endl; std::cout << "Probability: " << classProb * 100 << "%" << std::endl; //! [Print results] Json::Value sketchEvent; sketchEvent["sketchEvent"] = "bestClass"; sketchEvent["Value"] = classId ; sketchEvent["Confidence"] = classProb*100 ; sketchEvent["Name"] = classNames.at(classId).c_str() ; std::string sketchEventStr = sketchEvent.toStyledString(); QString sketchStr = QString::fromUtf8(sketchEventStr.c_str()); emit server->sendMessage(sketchStr); sketchRecivedState = false ; return 0; } //main int main(int argc, char *argv[]) { //freopen("erroLog.txt", "w", stderr); std::string configFileName="../config.txt"; std::ifstream infile(configFileName); if (infile.is_open()) { std::string tmp1 ,tmp2,tmp3 ; infile >> tmp1 >> modelFolderName ; infile >> tmp2 >> modelBinName ; infile >> tmp3 >> saveFolderName; infile.close() ; } else { std::cerr << "\n\nCannot open config file " << configFileName << endl ; return -1; } cout << "Model Folder Name : " << modelFolderName << endl ; cout << "Model Bin Name: " << modelBinName << endl ; infile.close(); QCoreApplication app(argc, argv); SocketServer *server = new SocketServer(9006); std::thread t1(infinityThread, server); // t1.detach(); app.exec(); t1.join(); return 0; // fclose(fp); } /*========================================================================= Library: CTK Copyright (c) Kitware 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.txt 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. =========================================================================*/ // CTK includes #include "ctkCoreTestingUtilities.h" using namespace ctkCoreTestingUtilities; //---------------------------------------------------------------------------- bool TestCheckInt(); bool TestCheckNotNull(); bool TestCheckNull(); bool TestCheckPointer(); bool TestCheckString(); bool TestCheckStringList(); bool TestCheckVariant(); //---------------------------------------------------------------------------- int ctkCoreTestingUtilitiesTest(int , char * []) { bool res = true; res = res && TestCheckInt(); res = res && TestCheckNotNull(); res = res && TestCheckNull(); res = res && TestCheckPointer(); res = res && TestCheckString(); res = res && TestCheckStringList(); res = res && TestCheckVariant(); return res ? EXIT_SUCCESS : EXIT_FAILURE; } //---------------------------------------------------------------------------- bool TestCheckInt() { if (!CheckInt(__LINE__, "TestCheckInt", 1, 1) || CheckInt(__LINE__, "TestCheckInt Expected Failure", 1, -1)) { qWarning() << "Line " << __LINE__ << " - TestCheckInt failed"; return false; } return true; } //---------------------------------------------------------------------------- bool TestCheckNotNull() { int foo = 1; if (!CheckNotNull(__LINE__, "TestCheckNotNull", &foo) || CheckNotNull(__LINE__, "TestCheckNotNull Expected Failure", 0)) { qWarning() << "Line " << __LINE__ << " - TestCheckNotNull failed"; return false; } return true; } //---------------------------------------------------------------------------- bool TestCheckNull() { int foo = 1; if (!CheckNull(__LINE__, "TestCheckNull", 0) || CheckNull(__LINE__, "TestCheckNull Expected Failure", &foo)) { qWarning() << "Line " << __LINE__ << " - TestCheckNull failed"; return false; } return true; } //---------------------------------------------------------------------------- bool TestCheckPointer() { int foo = 1; int bar = 1; if (!CheckPointer(__LINE__, "TestCheckPointer", &foo, &foo) || CheckPointer(__LINE__, "TestCheckPointer Expected Failure", &foo, &bar)) { qWarning() << "Line " << __LINE__ << " - TestCheckPointer failed"; return false; } return true; } //---------------------------------------------------------------------------- bool TestCheckString() { const char* foo = "foo"; const char* bar = "bar"; if (!CheckString(__LINE__, "TestCheckString", 0, 0) ||!CheckString(__LINE__, "TestCheckString", foo, foo) || CheckString(__LINE__, "TestCheckString Expected Failure", foo, bar) || CheckString(__LINE__, "TestCheckString Expected Failure", foo, 0)) { qWarning() << "Line " << __LINE__ << " - TestCheckString failed"; return false; } return true; } //---------------------------------------------------------------------------- bool TestCheckStringList() { QStringList abc = QStringList() << "a" << "b" << "c"; QStringList axc = QStringList() << "a" << "x" << "c"; QStringList abcd = QStringList() << "a" << "b" << "c" << "d"; if (!CheckStringList(__LINE__, "TestCheckStringList", QStringList(), QStringList()) ||!CheckStringList(__LINE__, "TestCheckStringList", abc, abc) || CheckStringList(__LINE__, "TestCheckStringList Expected Failure", abc, axc) || CheckStringList(__LINE__, "TestCheckStringList Expected Failure", abc, abcd)) { qWarning() << "Line " << __LINE__ << " - TestCheckString failed"; return false; } return true; } //---------------------------------------------------------------------------- bool TestCheckVariant() { QVariant foo = QVariant(4); QVariant bar = QVariant(2); if (!CheckVariant(__LINE__, "TestCheckVariant", QVariant(), QVariant()) ||!CheckVariant(__LINE__, "TestCheckVariant", foo, foo) || CheckVariant(__LINE__, "TestCheckVariant Expected Failure", foo, bar)) { qWarning() << "Line " << __LINE__ << " - TestCheckVariant failed"; return false; } return true; } // Copyright (c) 2014-2017 The Dash Core developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "activetnode.h" #include "consensus/consensus.h" #include "consensus/validation.h" #include "darksend.h" #include "init.h" //#include "governance.h" #include "tnode.h" #include "tnode-payments.h" #include "tnode-sync.h" #include "tnodeman.h" #include "util.h" #include CTnode::CTnode() : vin(), addr(), pubKeyCollateralAddress(), pubKeyTnode(), lastPing(), vchSig(), sigTime(GetAdjustedTime()), nLastDsq(0), nTimeLastChecked(0), nTimeLastPaid(0), nTimeLastWatchdogVote(0), nActiveState(TNODE_ENABLED), nCacheCollateralBlock(0), nBlockLastPaid(0), nProtocolVersion(PROTOCOL_VERSION), nPoSeBanScore(0), nPoSeBanHeight(0), fAllowMixingTx(true), fUnitTest(false) {} CTnode::CTnode(CService addrNew, CTxIn vinNew, CPubKey pubKeyCollateralAddressNew, CPubKey pubKeyTnodeNew, int nProtocolVersionIn) : vin(vinNew), addr(addrNew), pubKeyCollateralAddress(pubKeyCollateralAddressNew), pubKeyTnode(pubKeyTnodeNew), lastPing(), vchSig(), sigTime(GetAdjustedTime()), nLastDsq(0), nTimeLastChecked(0), nTimeLastPaid(0), nTimeLastWatchdogVote(0), nActiveState(TNODE_ENABLED), nCacheCollateralBlock(0), nBlockLastPaid(0), nProtocolVersion(nProtocolVersionIn), nPoSeBanScore(0), nPoSeBanHeight(0), fAllowMixingTx(true), fUnitTest(false) {} CTnode::CTnode(const CTnode &other) : vin(other.vin), addr(other.addr), pubKeyCollateralAddress(other.pubKeyCollateralAddress), pubKeyTnode(other.pubKeyTnode), lastPing(other.lastPing), vchSig(other.vchSig), sigTime(other.sigTime), nLastDsq(other.nLastDsq), nTimeLastChecked(other.nTimeLastChecked), nTimeLastPaid(other.nTimeLastPaid), nTimeLastWatchdogVote(other.nTimeLastWatchdogVote), nActiveState(other.nActiveState), nCacheCollateralBlock(other.nCacheCollateralBlock), nBlockLastPaid(other.nBlockLastPaid), nProtocolVersion(other.nProtocolVersion), nPoSeBanScore(other.nPoSeBanScore), nPoSeBanHeight(other.nPoSeBanHeight), fAllowMixingTx(other.fAllowMixingTx), fUnitTest(other.fUnitTest) {} CTnode::CTnode(const CTnodeBroadcast &mnb) : vin(mnb.vin), addr(mnb.addr), pubKeyCollateralAddress(mnb.pubKeyCollateralAddress), pubKeyTnode(mnb.pubKeyTnode), lastPing(mnb.lastPing), vchSig(mnb.vchSig), sigTime(mnb.sigTime), nLastDsq(0), nTimeLastChecked(0), nTimeLastPaid(0), nTimeLastWatchdogVote(mnb.sigTime), nActiveState(mnb.nActiveState), nCacheCollateralBlock(0), nBlockLastPaid(0), nProtocolVersion(mnb.nProtocolVersion), nPoSeBanScore(0), nPoSeBanHeight(0), fAllowMixingTx(true), fUnitTest(false) {} //CSporkManager sporkManager; // // When a new tnode broadcast is sent, update our information // bool CTnode::UpdateFromNewBroadcast(CTnodeBroadcast &mnb) { if (mnb.sigTime <= sigTime && !mnb.fRecovery) return false; pubKeyTnode = mnb.pubKeyTnode; sigTime = mnb.sigTime; vchSig = mnb.vchSig; nProtocolVersion = mnb.nProtocolVersion; addr = mnb.addr; nPoSeBanScore = 0; nPoSeBanHeight = 0; nTimeLastChecked = 0; int nDos = 0; if (mnb.lastPing == CTnodePing() || (mnb.lastPing != CTnodePing() && mnb.lastPing.CheckAndUpdate(this, true, nDos))) { lastPing = mnb.lastPing; mnodeman.mapSeenTnodePing.insert(std::make_pair(lastPing.GetHash(), lastPing)); } // if it matches our Tnode privkey... if (fTNode && pubKeyTnode == activeTnode.pubKeyTnode) { nPoSeBanScore = -TNODE_POSE_BAN_MAX_SCORE; if (nProtocolVersion == PROTOCOL_VERSION) { // ... and PROTOCOL_VERSION, then we've been remotely activated ... activeTnode.ManageState(); } else { // ... otherwise we need to reactivate our node, do not add it to the list and do not relay // but also do not ban the node we get this message from LogPrintf("CTnode::UpdateFromNewBroadcast -- wrong PROTOCOL_VERSION, re-activate your MN: message nProtocolVersion=%d PROTOCOL_VERSION=%d\n", nProtocolVersion, PROTOCOL_VERSION); return false; } } return true; } // // Deterministically calculate a given "score" for a Tnode depending on how close it's hash is to // the proof of work for that block. The further away they are the better, the furthest will win the election // and get paid this block // arith_uint256 CTnode::CalculateScore(const uint256 &blockHash) { uint256 aux = ArithToUint256(UintToArith256(vin.prevout.hash) + vin.prevout.n); CHashWriter ss(SER_GETHASH, PROTOCOL_VERSION); ss << blockHash; arith_uint256 hash2 = UintToArith256(ss.GetHash()); CHashWriter ss2(SER_GETHASH, PROTOCOL_VERSION); ss2 << blockHash; ss2 << aux; arith_uint256 hash3 = UintToArith256(ss2.GetHash()); return (hash3 > hash2 ? hash3 - hash2 : hash2 - hash3); } void CTnode::Check(bool fForce) { LOCK(cs); if (ShutdownRequested()) return; if (!fForce && (GetTime() - nTimeLastChecked < TNODE_CHECK_SECONDS)) return; nTimeLastChecked = GetTime(); LogPrint("tnode", "CTnode::Check -- Tnode %s is in %s state\n", vin.prevout.ToStringShort(), GetStateString()); //once spent, stop doing the checks if (IsOutpointSpent()) return; int nHeight = 0; if (!fUnitTest) { TRY_LOCK(cs_main, lockMain); if (!lockMain) return; CCoins coins; if (!pcoinsTip->GetCoins(vin.prevout.hash, coins) || (unsigned int) vin.prevout.n >= coins.vout.size() || coins.vout[vin.prevout.n].IsNull()) { nActiveState = TNODE_OUTPOINT_SPENT; LogPrint("tnode", "CTnode::Check -- Failed to find Tnode UTXO, tnode=%s\n", vin.prevout.ToStringShort()); return; } nHeight = chainActive.Height(); } if (IsPoSeBanned()) { if (nHeight < nPoSeBanHeight) return; // too early? // Otherwise give it a chance to proceed further to do all the usual checks and to change its state. // Tnode still will be on the edge and can be banned back easily if it keeps ignoring mnverify // or connect attempts. Will require few mnverify messages to strengthen its position in mn list. LogPrintf("CTnode::Check -- Tnode %s is unbanned and back in list now\n", vin.prevout.ToStringShort()); DecreasePoSeBanScore(); } else if (nPoSeBanScore >= TNODE_POSE_BAN_MAX_SCORE) { nActiveState = TNODE_POSE_BAN; // ban for the whole payment cycle nPoSeBanHeight = nHeight + mnodeman.size(); LogPrintf("CTnode::Check -- Tnode %s is banned till block %d now\n", vin.prevout.ToStringShort(), nPoSeBanHeight); return; } int nActiveStatePrev = nActiveState; bool fOurTnode = fTNode && activeTnode.pubKeyTnode == pubKeyTnode; // tnode doesn't meet payment protocol requirements ... /* bool fRequireUpdate = nProtocolVersion < mnpayments.GetMinTnodePaymentsProto() || // or it's our own node and we just updated it to the new protocol but we are still waiting for activation ... (fOurTnode && nProtocolVersion < PROTOCOL_VERSION); */ // tnode doesn't meet payment protocol requirements ... bool fRequireUpdate = nProtocolVersion < mnpayments.GetMinTnodePaymentsProto() || // or it's our own node and we just updated it to the new protocol but we are still waiting for activation ... (fOurTnode && (nProtocolVersion < MIN_TNODE_PAYMENT_PROTO_VERSION_1 || nProtocolVersion > MIN_TNODE_PAYMENT_PROTO_VERSION_2)); if (fRequireUpdate) { nActiveState = TNODE_UPDATE_REQUIRED; if (nActiveStatePrev != nActiveState) { LogPrint("tnode", "CTnode::Check -- Tnode %s is in %s state now\n", vin.prevout.ToStringShort(), GetStateString()); } return; } // keep old tnodes on start, give them a chance to receive updates... bool fWaitForPing = !tnodeSync.IsTnodeListSynced() && !IsPingedWithin(TNODE_MIN_MNP_SECONDS); if (fWaitForPing && !fOurTnode) { // ...but if it was already expired before the initial check - return right away if (IsExpired() || IsWatchdogExpired() || IsNewStartRequired()) { LogPrint("tnode", "CTnode::Check -- Tnode %s is in %s state, waiting for ping\n", vin.prevout.ToStringShort(), GetStateString()); return; } } // don't expire if we are still in "waiting for ping" mode unless it's our own tnode if (!fWaitForPing || fOurTnode) { if (!IsPingedWithin(TNODE_NEW_START_REQUIRED_SECONDS)) { nActiveState = TNODE_NEW_START_REQUIRED; if (nActiveStatePrev != nActiveState) { LogPrint("tnode", "CTnode::Check -- Tnode %s is in %s state now\n", vin.prevout.ToStringShort(), GetStateString()); } return; } bool fWatchdogActive = tnodeSync.IsSynced() && mnodeman.IsWatchdogActive(); bool fWatchdogExpired = (fWatchdogActive && ((GetTime() - nTimeLastWatchdogVote) > TNODE_WATCHDOG_MAX_SECONDS)); // LogPrint("tnode", "CTnode::Check -- outpoint=%s, nTimeLastWatchdogVote=%d, GetTime()=%d, fWatchdogExpired=%d\n", // vin.prevout.ToStringShort(), nTimeLastWatchdogVote, GetTime(), fWatchdogExpired); if (fWatchdogExpired) { nActiveState = TNODE_WATCHDOG_EXPIRED; if (nActiveStatePrev != nActiveState) { LogPrint("tnode", "CTnode::Check -- Tnode %s is in %s state now\n", vin.prevout.ToStringShort(), GetStateString()); } return; } if (!IsPingedWithin(TNODE_EXPIRATION_SECONDS)) { nActiveState = TNODE_EXPIRED; if (nActiveStatePrev != nActiveState) { LogPrint("tnode", "CTnode::Check -- Tnode %s is in %s state now\n", vin.prevout.ToStringShort(), GetStateString()); } return; } } if (lastPing.sigTime - sigTime < TNODE_MIN_MNP_SECONDS) { nActiveState = TNODE_PRE_ENABLED; if (nActiveStatePrev != nActiveState) { LogPrint("tnode", "CTnode::Check -- Tnode %s is in %s state now\n", vin.prevout.ToStringShort(), GetStateString()); } return; } nActiveState = TNODE_ENABLED; // OK if (nActiveStatePrev != nActiveState) { LogPrint("tnode", "CTnode::Check -- Tnode %s is in %s state now\n", vin.prevout.ToStringShort(), GetStateString()); } } bool CTnode::IsValidNetAddr() { return IsValidNetAddr(addr); } bool CTnode::IsValidForPayment() { if (nActiveState == TNODE_ENABLED) { return true; } // if(!sporkManager.IsSporkActive(SPORK_14_REQUIRE_SENTINEL_FLAG) && // (nActiveState == TNODE_WATCHDOG_EXPIRED)) { // return true; // } return false; } bool CTnode::IsValidNetAddr(CService addrIn) { // TODO: regtest is fine with any addresses for now, // should probably be a bit smarter if one day we start to implement tests for this return Params().NetworkIDString() == CBaseChainParams::REGTEST || (addrIn.IsIPv4() && IsReachable(addrIn) && addrIn.IsRoutable()); } tnode_info_t CTnode::GetInfo() { tnode_info_t info; info.vin = vin; info.addr = addr; info.pubKeyCollateralAddress = pubKeyCollateralAddress; info.pubKeyTnode = pubKeyTnode; info.sigTime = sigTime; info.nLastDsq = nLastDsq; info.nTimeLastChecked = nTimeLastChecked; info.nTimeLastPaid = nTimeLastPaid; info.nTimeLastWatchdogVote = nTimeLastWatchdogVote; info.nTimeLastPing = lastPing.sigTime; info.nActiveState = nActiveState; info.nProtocolVersion = nProtocolVersion; info.fInfoValid = true; return info; } std::string CTnode::StateToString(int nStateIn) { switch (nStateIn) { case TNODE_PRE_ENABLED: return "PRE_ENABLED"; case TNODE_ENABLED: return "ENABLED"; case TNODE_EXPIRED: return "EXPIRED"; case TNODE_OUTPOINT_SPENT: return "OUTPOINT_SPENT"; case TNODE_UPDATE_REQUIRED: return "UPDATE_REQUIRED"; case TNODE_WATCHDOG_EXPIRED: return "WATCHDOG_EXPIRED"; case TNODE_NEW_START_REQUIRED: return "NEW_START_REQUIRED"; case TNODE_POSE_BAN: return "POSE_BAN"; default: return "UNKNOWN"; } } std::string CTnode::GetStateString() const { return StateToString(nActiveState); } std::string CTnode::GetStatus() const { // TODO: return smth a bit more human readable here return GetStateString(); } std::string CTnode::ToString() const { std::string str; str += "tnode{"; str += addr.ToString(); str += " "; str += std::to_string(nProtocolVersion); str += " "; str += vin.prevout.ToStringShort(); str += " "; str += CBitcoinAddress(pubKeyCollateralAddress.GetID()).ToString(); str += " "; str += std::to_string(lastPing == CTnodePing() ? sigTime : lastPing.sigTime); str += " "; str += std::to_string(lastPing == CTnodePing() ? 0 : lastPing.sigTime - sigTime); str += " "; str += std::to_string(nBlockLastPaid); str += "}\n"; return str; } int CTnode::GetCollateralAge() { int nHeight; { TRY_LOCK(cs_main, lockMain); if (!lockMain || !chainActive.Tip()) return -1; nHeight = chainActive.Height(); } if (nCacheCollateralBlock == 0) { int nInputAge = GetInputAge(vin); if (nInputAge > 0) { nCacheCollateralBlock = nHeight - nInputAge; } else { return nInputAge; } } return nHeight - nCacheCollateralBlock; } void CTnode::UpdateLastPaid(const CBlockIndex *pindex, int nMaxBlocksToScanBack) { if (!pindex) { LogPrintf("CTnode::UpdateLastPaid pindex is NULL\n"); return; } const Consensus::Params ¶ms = Params().GetConsensus(); const CBlockIndex *BlockReading = pindex; CScript mnpayee = GetScriptForDestination(pubKeyCollateralAddress.GetID()); LogPrint("tnode", "CTnode::UpdateLastPaidBlock -- searching for block with payment to %s\n", vin.prevout.ToStringShort()); LOCK(cs_mapTnodeBlocks); for (int i = 0; BlockReading && BlockReading->nHeight > nBlockLastPaid && i < nMaxBlocksToScanBack; i++) { // LogPrintf("mnpayments.mapTnodeBlocks.count(BlockReading->nHeight)=%s\n", mnpayments.mapTnodeBlocks.count(BlockReading->nHeight)); // LogPrintf("mnpayments.mapTnodeBlocks[BlockReading->nHeight].HasPayeeWithVotes(mnpayee, 2)=%s\n", mnpayments.mapTnodeBlocks[BlockReading->nHeight].HasPayeeWithVotes(mnpayee, 2)); if (mnpayments.mapTnodeBlocks.count(BlockReading->nHeight) && mnpayments.mapTnodeBlocks[BlockReading->nHeight].HasPayeeWithVotes(mnpayee, 2)) { // LogPrintf("i=%s, BlockReading->nHeight=%s\n", i, BlockReading->nHeight); CBlock block; if (!ReadBlockFromDisk(block, BlockReading, Params().GetConsensus())) // shouldn't really happen { LogPrintf("ReadBlockFromDisk failed\n"); continue; } bool fMTP = BlockReading->nHeight > 0 && BlockReading->nTime >= params.nMTPSwitchTime; CAmount nTnodePayment = GetTnodePayment(BlockReading->nHeight, params, fMTP); BOOST_FOREACH(CTxOut txout, block.vtx[0].vout) if (mnpayee == txout.scriptPubKey && nTnodePayment == txout.nValue) { nBlockLastPaid = BlockReading->nHeight; nTimeLastPaid = BlockReading->nTime; LogPrint("tnode", "CTnode::UpdateLastPaidBlock -- searching for block with payment to %s -- found new %d\n", vin.prevout.ToStringShort(), nBlockLastPaid); return; } } if (BlockReading->pprev == NULL) { assert(BlockReading); break; } BlockReading = BlockReading->pprev; } // Last payment for this tnode wasn't found in latest mnpayments blocks // or it was found in mnpayments blocks but wasn't found in the blockchain. // LogPrint("tnode", "CTnode::UpdateLastPaidBlock -- searching for block with payment to %s -- keeping old %d\n", vin.prevout.ToStringShort(), nBlockLastPaid); } bool CTnodeBroadcast::Create(std::string strService, std::string strKeyTnode, std::string strTxHash, std::string strOutputIndex, std::string &strErrorRet, CTnodeBroadcast &mnbRet, bool fOffline) { LogPrintf("CTnodeBroadcast::Create\n"); CTxIn txin; CPubKey pubKeyCollateralAddressNew; CKey keyCollateralAddressNew; CPubKey pubKeyTnodeNew; CKey keyTnodeNew; //need correct blocks to send ping if (!fOffline && !tnodeSync.IsBlockchainSynced()) { strErrorRet = "Sync in progress. Must wait until sync is complete to start Tnode"; LogPrintf("CTnodeBroadcast::Create -- %s\n", strErrorRet); return false; } //TODO if (!darkSendSigner.GetKeysFromSecret(strKeyTnode, keyTnodeNew, pubKeyTnodeNew)) { strErrorRet = strprintf("Invalid tnode key %s", strKeyTnode); LogPrintf("CTnodeBroadcast::Create -- %s\n", strErrorRet); return false; } if (!pwalletMain->GetTnodeVinAndKeys(txin, pubKeyCollateralAddressNew, keyCollateralAddressNew, strTxHash, strOutputIndex)) { strErrorRet = strprintf("Could not allocate txin %s:%s for tnode %s", strTxHash, strOutputIndex, strService); LogPrintf("CTnodeBroadcast::Create -- %s\n", strErrorRet); return false; } CService service = CService(strService); int mainnetDefaultPort = Params(CBaseChainParams::MAIN).GetDefaultPort(); if (Params().NetworkIDString() == CBaseChainParams::MAIN) { if (service.GetPort() != mainnetDefaultPort) { strErrorRet = strprintf("Invalid port %u for tnode %s, only %d is supported on mainnet.", service.GetPort(), strService, mainnetDefaultPort); LogPrintf("CTnodeBroadcast::Create -- %s\n", strErrorRet); return false; } } else if (service.GetPort() == mainnetDefaultPort) { strErrorRet = strprintf("Invalid port %u for tnode %s, %d is the only supported on mainnet.", service.GetPort(), strService, mainnetDefaultPort); LogPrintf("CTnodeBroadcast::Create -- %s\n", strErrorRet); return false; } return Create(txin, CService(strService), keyCollateralAddressNew, pubKeyCollateralAddressNew, keyTnodeNew, pubKeyTnodeNew, strErrorRet, mnbRet); } bool CTnodeBroadcast::Create(CTxIn txin, CService service, CKey keyCollateralAddressNew, CPubKey pubKeyCollateralAddressNew, CKey keyTnodeNew, CPubKey pubKeyTnodeNew, std::string &strErrorRet, CTnodeBroadcast &mnbRet) { // wait for reindex and/or import to finish if (fImporting || fReindex) return false; LogPrint("tnode", "CTnodeBroadcast::Create -- pubKeyCollateralAddressNew = %s, pubKeyTnodeNew.GetID() = %s\n", CBitcoinAddress(pubKeyCollateralAddressNew.GetID()).ToString(), pubKeyTnodeNew.GetID().ToString()); CTnodePing mnp(txin); if (!mnp.Sign(keyTnodeNew, pubKeyTnodeNew)) { strErrorRet = strprintf("Failed to sign ping, tnode=%s", txin.prevout.ToStringShort()); LogPrintf("CTnodeBroadcast::Create -- %s\n", strErrorRet); mnbRet = CTnodeBroadcast(); return false; } int nHeight = chainActive.Height(); if (nHeight < ZC_MODULUS_V2_START_BLOCK) { mnbRet = CTnodeBroadcast(service, txin, pubKeyCollateralAddressNew, pubKeyTnodeNew, MIN_PEER_PROTO_VERSION); } else { mnbRet = CTnodeBroadcast(service, txin, pubKeyCollateralAddressNew, pubKeyTnodeNew, PROTOCOL_VERSION); } if (!mnbRet.IsValidNetAddr()) { strErrorRet = strprintf("Invalid IP address, tnode=%s", txin.prevout.ToStringShort()); LogPrintf("CTnodeBroadcast::Create -- %s\n", strErrorRet); mnbRet = CTnodeBroadcast(); return false; } mnbRet.lastPing = mnp; if (!mnbRet.Sign(keyCollateralAddressNew)) { strErrorRet = strprintf("Failed to sign broadcast, tnode=%s", txin.prevout.ToStringShort()); LogPrintf("CTnodeBroadcast::Create -- %s\n", strErrorRet); mnbRet = CTnodeBroadcast(); return false; } return true; } bool CTnodeBroadcast::SimpleCheck(int &nDos) { nDos = 0; // make sure addr is valid if (!IsValidNetAddr()) { LogPrintf("CTnodeBroadcast::SimpleCheck -- Invalid addr, rejected: tnode=%s addr=%s\n", vin.prevout.ToStringShort(), addr.ToString()); return false; } // make sure signature isn't in the future (past is OK) if (sigTime > GetAdjustedTime() + 60 * 60) { LogPrintf("CTnodeBroadcast::SimpleCheck -- Signature rejected, too far into the future: tnode=%s\n", vin.prevout.ToStringShort()); nDos = 1; return false; } // empty ping or incorrect sigTime/unknown blockhash if (lastPing == CTnodePing() || !lastPing.SimpleCheck(nDos)) { // one of us is probably forked or smth, just mark it as expired and check the rest of the rules nActiveState = TNODE_EXPIRED; } if (nProtocolVersion < mnpayments.GetMinTnodePaymentsProto()) { LogPrintf("CTnodeBroadcast::SimpleCheck -- ignoring outdated Tnode: tnode=%s nProtocolVersion=%d\n", vin.prevout.ToStringShort(), nProtocolVersion); return false; } CScript pubkeyScript; pubkeyScript = GetScriptForDestination(pubKeyCollateralAddress.GetID()); if (pubkeyScript.size() != 25) { LogPrintf("CTnodeBroadcast::SimpleCheck -- pubKeyCollateralAddress has the wrong size\n"); nDos = 100; return false; } CScript pubkeyScript2; pubkeyScript2 = GetScriptForDestination(pubKeyTnode.GetID()); if (pubkeyScript2.size() != 25) { LogPrintf("CTnodeBroadcast::SimpleCheck -- pubKeyTnode has the wrong size\n"); nDos = 100; return false; } if (!vin.scriptSig.empty()) { LogPrintf("CTnodeBroadcast::SimpleCheck -- Ignore Not Empty ScriptSig %s\n", vin.ToString()); nDos = 100; return false; } int mainnetDefaultPort = Params(CBaseChainParams::MAIN).GetDefaultPort(); if (Params().NetworkIDString() == CBaseChainParams::MAIN) { if (addr.GetPort() != mainnetDefaultPort) return false; } else if (addr.GetPort() == mainnetDefaultPort) return false; return true; } bool CTnodeBroadcast::Update(CTnode *pmn, int &nDos) { nDos = 0; if (pmn->sigTime == sigTime && !fRecovery) { // mapSeenTnodeBroadcast in CTnodeMan::CheckMnbAndUpdateTnodeList should filter legit duplicates // but this still can happen if we just started, which is ok, just do nothing here. return false; } // this broadcast is older than the one that we already have - it's bad and should never happen // unless someone is doing something fishy if (pmn->sigTime > sigTime) { LogPrintf("CTnodeBroadcast::Update -- Bad sigTime %d (existing broadcast is at %d) for Tnode %s %s\n", sigTime, pmn->sigTime, vin.prevout.ToStringShort(), addr.ToString()); return false; } pmn->Check(); // tnode is banned by PoSe if (pmn->IsPoSeBanned()) { LogPrintf("CTnodeBroadcast::Update -- Banned by PoSe, tnode=%s\n", vin.prevout.ToStringShort()); return false; } // IsVnAssociatedWithPubkey is validated once in CheckOutpoint, after that they just need to match if (pmn->pubKeyCollateralAddress != pubKeyCollateralAddress) { LogPrintf("CTnodeBroadcast::Update -- Got mismatched pubKeyCollateralAddress and vin\n"); nDos = 33; return false; } if (!CheckSignature(nDos)) { LogPrintf("CTnodeBroadcast::Update -- CheckSignature() failed, tnode=%s\n", vin.prevout.ToStringShort()); return false; } // if ther was no tnode broadcast recently or if it matches our Tnode privkey... if (!pmn->IsBroadcastedWithin(TNODE_MIN_MNB_SECONDS) || (fTNode && pubKeyTnode == activeTnode.pubKeyTnode)) { // take the newest entry LogPrintf("CTnodeBroadcast::Update -- Got UPDATED Tnode entry: addr=%s\n", addr.ToString()); if (pmn->UpdateFromNewBroadcast((*this))) { pmn->Check(); RelayTNode(); } tnodeSync.AddedTnodeList(); } return true; } bool CTnodeBroadcast::CheckOutpoint(int &nDos) { // we are a tnode with the same vin (i.e. already activated) and this mnb is ours (matches our Tnode privkey) // so nothing to do here for us if (fTNode && vin.prevout == activeTnode.vin.prevout && pubKeyTnode == activeTnode.pubKeyTnode) { return false; } if (!CheckSignature(nDos)) { LogPrintf("CTnodeBroadcast::CheckOutpoint -- CheckSignature() failed, tnode=%s\n", vin.prevout.ToStringShort()); return false; } { TRY_LOCK(cs_main, lockMain); if (!lockMain) { // not mnb fault, let it to be checked again later LogPrint("tnode", "CTnodeBroadcast::CheckOutpoint -- Failed to aquire lock, addr=%s", addr.ToString()); mnodeman.mapSeenTnodeBroadcast.erase(GetHash()); return false; } CCoins coins; if (!pcoinsTip->GetCoins(vin.prevout.hash, coins) || (unsigned int) vin.prevout.n >= coins.vout.size() || coins.vout[vin.prevout.n].IsNull()) { LogPrint("tnode", "CTnodeBroadcast::CheckOutpoint -- Failed to find Tnode UTXO, tnode=%s\n", vin.prevout.ToStringShort()); return false; } if (coins.vout[vin.prevout.n].nValue != TNODE_COIN_REQUIRED * COIN) { LogPrint("tnode", "CTnodeBroadcast::CheckOutpoint -- Tnode UTXO should have %d TCR, tnode=%s\n", TNODE_COIN_REQUIRED, vin.prevout.ToStringShort()); return false; } if (chainActive.Height() - coins.nHeight + 1 < Params().GetConsensus().nTnodeMinimumConfirmations) { LogPrintf("CTnodeBroadcast::CheckOutpoint -- Tnode UTXO must have at least %d confirmations, tnode=%s\n", Params().GetConsensus().nTnodeMinimumConfirmations, vin.prevout.ToStringShort()); // maybe we miss few blocks, let this mnb to be checked again later mnodeman.mapSeenTnodeBroadcast.erase(GetHash()); return false; } } LogPrint("tnode", "CTnodeBroadcast::CheckOutpoint -- Tnode UTXO verified\n"); // make sure the vout that was signed is related to the transaction that spawned the Tnode // - this is expensive, so it's only done once per Tnode if (!darkSendSigner.IsVinAssociatedWithPubkey(vin, pubKeyCollateralAddress)) { LogPrintf("CTnodeMan::CheckOutpoint -- Got mismatched pubKeyCollateralAddress and vin\n"); nDos = 33; return false; } // verify that sig time is legit in past // should be at least not earlier than block when 10000 TCR tx got nTnodeMinimumConfirmations uint256 hashBlock = uint256(); CTransaction tx2; GetTransaction(vin.prevout.hash, tx2, Params().GetConsensus(), hashBlock, true); { LOCK(cs_main); BlockMap::iterator mi = mapBlockIndex.find(hashBlock); if (mi != mapBlockIndex.end() && (*mi).second) { CBlockIndex *pMNIndex = (*mi).second; // block for 10000 TCR tx -> 1 confirmation CBlockIndex *pConfIndex = chainActive[pMNIndex->nHeight + Params().GetConsensus().nTnodeMinimumConfirmations - 1]; // block where tx got nTnodeMinimumConfirmations if (pConfIndex->GetBlockTime() > sigTime) { LogPrintf("CTnodeBroadcast::CheckOutpoint -- Bad sigTime %d (%d conf block is at %d) for Tnode %s %s\n", sigTime, Params().GetConsensus().nTnodeMinimumConfirmations, pConfIndex->GetBlockTime(), vin.prevout.ToStringShort(), addr.ToString()); return false; } } } return true; } bool CTnodeBroadcast::Sign(CKey &keyCollateralAddress) { std::string strError; std::string strMessage; sigTime = GetAdjustedTime(); strMessage = addr.ToString() + boost::lexical_cast(sigTime) + pubKeyCollateralAddress.GetID().ToString() + pubKeyTnode.GetID().ToString() + boost::lexical_cast(nProtocolVersion); if (!darkSendSigner.SignMessage(strMessage, vchSig, keyCollateralAddress)) { LogPrintf("CTnodeBroadcast::Sign -- SignMessage() failed\n"); return false; } if (!darkSendSigner.VerifyMessage(pubKeyCollateralAddress, vchSig, strMessage, strError)) { LogPrintf("CTnodeBroadcast::Sign -- VerifyMessage() failed, error: %s\n", strError); return false; } return true; } bool CTnodeBroadcast::CheckSignature(int &nDos) { std::string strMessage; std::string strError = ""; nDos = 0; strMessage = addr.ToString() + boost::lexical_cast(sigTime) + pubKeyCollateralAddress.GetID().ToString() + pubKeyTnode.GetID().ToString() + boost::lexical_cast(nProtocolVersion); LogPrint("tnode", "CTnodeBroadcast::CheckSignature -- strMessage: %s pubKeyCollateralAddress address: %s sig: %s\n", strMessage, CBitcoinAddress(pubKeyCollateralAddress.GetID()).ToString(), EncodeBase64(&vchSig[0], vchSig.size())); if (!darkSendSigner.VerifyMessage(pubKeyCollateralAddress, vchSig, strMessage, strError)) { LogPrintf("CTnodeBroadcast::CheckSignature -- Got bad Tnode announce signature, error: %s\n", strError); nDos = 100; return false; } return true; } void CTnodeBroadcast::RelayTNode() { LogPrintf("CTnodeBroadcast::RelayTNode\n"); CInv inv(MSG_TNODE_ANNOUNCE, GetHash()); RelayInv(inv); } CTnodePing::CTnodePing(CTxIn &vinNew) { LOCK(cs_main); if (!chainActive.Tip() || chainActive.Height() < 12) return; vin = vinNew; blockHash = chainActive[chainActive.Height() - 12]->GetBlockHash(); sigTime = GetAdjustedTime(); vchSig = std::vector < unsigned char > (); } bool CTnodePing::Sign(CKey &keyTnode, CPubKey &pubKeyTnode) { std::string strError; std::string strTNodeSignMessage; sigTime = GetAdjustedTime(); std::string strMessage = vin.ToString() + blockHash.ToString() + boost::lexical_cast(sigTime); if (!darkSendSigner.SignMessage(strMessage, vchSig, keyTnode)) { LogPrintf("CTnodePing::Sign -- SignMessage() failed\n"); return false; } if (!darkSendSigner.VerifyMessage(pubKeyTnode, vchSig, strMessage, strError)) { LogPrintf("CTnodePing::Sign -- VerifyMessage() failed, error: %s\n", strError); return false; } return true; } bool CTnodePing::CheckSignature(CPubKey &pubKeyTnode, int &nDos) { std::string strMessage = vin.ToString() + blockHash.ToString() + boost::lexical_cast(sigTime); std::string strError = ""; nDos = 0; if (!darkSendSigner.VerifyMessage(pubKeyTnode, vchSig, strMessage, strError)) { LogPrintf("CTnodePing::CheckSignature -- Got bad Tnode ping signature, tnode=%s, error: %s\n", vin.prevout.ToStringShort(), strError); nDos = 33; return false; } return true; } bool CTnodePing::SimpleCheck(int &nDos) { // don't ban by default nDos = 0; if (sigTime > GetAdjustedTime() + 60 * 60) { LogPrintf("CTnodePing::SimpleCheck -- Signature rejected, too far into the future, tnode=%s\n", vin.prevout.ToStringShort()); nDos = 1; return false; } { // LOCK(cs_main); AssertLockHeld(cs_main); BlockMap::iterator mi = mapBlockIndex.find(blockHash); if (mi == mapBlockIndex.end()) { LogPrint("tnode", "CTnodePing::SimpleCheck -- Tnode ping is invalid, unknown block hash: tnode=%s blockHash=%s\n", vin.prevout.ToStringShort(), blockHash.ToString()); // maybe we stuck or forked so we shouldn't ban this node, just fail to accept this ping // TODO: or should we also request this block? return false; } } LogPrint("tnode", "CTnodePing::SimpleCheck -- Tnode ping verified: tnode=%s blockHash=%s sigTime=%d\n", vin.prevout.ToStringShort(), blockHash.ToString(), sigTime); return true; } bool CTnodePing::CheckAndUpdate(CTnode *pmn, bool fFromNewBroadcast, int &nDos) { // don't ban by default nDos = 0; if (!SimpleCheck(nDos)) { return false; } if (pmn == NULL) { LogPrint("tnode", "CTnodePing::CheckAndUpdate -- Couldn't find Tnode entry, tnode=%s\n", vin.prevout.ToStringShort()); return false; } if (!fFromNewBroadcast) { if (pmn->IsUpdateRequired()) { LogPrint("tnode", "CTnodePing::CheckAndUpdate -- tnode protocol is outdated, tnode=%s\n", vin.prevout.ToStringShort()); return false; } if (pmn->IsNewStartRequired()) { LogPrint("tnode", "CTnodePing::CheckAndUpdate -- tnode is completely expired, new start is required, tnode=%s\n", vin.prevout.ToStringShort()); return false; } } { LOCK(cs_main); BlockMap::iterator mi = mapBlockIndex.find(blockHash); if ((*mi).second && (*mi).second->nHeight < chainActive.Height() - 24) { // LogPrintf("CTnodePing::CheckAndUpdate -- Tnode ping is invalid, block hash is too old: tnode=%s blockHash=%s\n", vin.prevout.ToStringShort(), blockHash.ToString()); // nDos = 1; return false; } } LogPrint("tnode", "CTnodePing::CheckAndUpdate -- New ping: tnode=%s blockHash=%s sigTime=%d\n", vin.prevout.ToStringShort(), blockHash.ToString(), sigTime); // LogPrintf("mnping - Found corresponding mn for vin: %s\n", vin.prevout.ToStringShort()); // update only if there is no known ping for this tnode or // last ping was more then TNODE_MIN_MNP_SECONDS-60 ago comparing to this one if (pmn->IsPingedWithin(TNODE_MIN_MNP_SECONDS - 60, sigTime)) { LogPrint("tnode", "CTnodePing::CheckAndUpdate -- Tnode ping arrived too early, tnode=%s\n", vin.prevout.ToStringShort()); //nDos = 1; //disable, this is happening frequently and causing banned peers return false; } if (!CheckSignature(pmn->pubKeyTnode, nDos)) return false; // so, ping seems to be ok // if we are still syncing and there was no known ping for this mn for quite a while // (NOTE: assuming that TNODE_EXPIRATION_SECONDS/2 should be enough to finish mn list sync) if (!tnodeSync.IsTnodeListSynced() && !pmn->IsPingedWithin(TNODE_EXPIRATION_SECONDS / 2)) { // let's bump sync timeout LogPrint("tnode", "CTnodePing::CheckAndUpdate -- bumping sync timeout, tnode=%s\n", vin.prevout.ToStringShort()); tnodeSync.AddedTnodeList(); } // let's store this ping as the last one LogPrint("tnode", "CTnodePing::CheckAndUpdate -- Tnode ping accepted, tnode=%s\n", vin.prevout.ToStringShort()); pmn->lastPing = *this; // and update mnodeman.mapSeenTnodeBroadcast.lastPing which is probably outdated CTnodeBroadcast mnb(*pmn); uint256 hash = mnb.GetHash(); if (mnodeman.mapSeenTnodeBroadcast.count(hash)) { mnodeman.mapSeenTnodeBroadcast[hash].second.lastPing = *this; } pmn->Check(true); // force update, ignoring cache if (!pmn->IsEnabled()) return false; LogPrint("tnode", "CTnodePing::CheckAndUpdate -- Tnode ping acceepted and relayed, tnode=%s\n", vin.prevout.ToStringShort()); Relay(); return true; } void CTnodePing::Relay() { CInv inv(MSG_TNODE_PING, GetHash()); RelayInv(inv); } //void CTnode::AddGovernanceVote(uint256 nGovernanceObjectHash) //{ // if(mapGovernanceObjectsVotedOn.count(nGovernanceObjectHash)) { // mapGovernanceObjectsVotedOn[nGovernanceObjectHash]++; // } else { // mapGovernanceObjectsVotedOn.insert(std::make_pair(nGovernanceObjectHash, 1)); // } //} //void CTnode::RemoveGovernanceObject(uint256 nGovernanceObjectHash) //{ // std::map::iterator it = mapGovernanceObjectsVotedOn.find(nGovernanceObjectHash); // if(it == mapGovernanceObjectsVotedOn.end()) { // return; // } // mapGovernanceObjectsVotedOn.erase(it); //} void CTnode::UpdateWatchdogVoteTime() { LOCK(cs); nTimeLastWatchdogVote = GetTime(); } /** * FLAG GOVERNANCE ITEMS AS DIRTY * * - When tnode come and go on the network, we must flag the items they voted on to recalc it's cached flags * */ //void CTnode::FlagGovernanceItemsAsDirty() //{ // std::vector vecDirty; // { // std::map::iterator it = mapGovernanceObjectsVotedOn.begin(); // while(it != mapGovernanceObjectsVotedOn.end()) { // vecDirty.push_back(it->first); // ++it; // } // } // for(size_t i = 0; i < vecDirty.size(); ++i) { // mnodeman.AddDirtyGovernanceObjectHash(vecDirty[i]); // } //} gustavo-castillo-bautista/Mercury0 //Copyright (c) 2013-2020, The MercuryDPM Developers Team. All rights reserved. //For the list of developers, see . // //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 MercuryDPM 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 MERCURYDPM DEVELOPERS TEAM 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 "ChuteWithHopper.h" #include #include #include #include using namespace std; class GranularJet : public ChuteWithHopper { public: void setSilbert() { //time stepping setTimeStep(1e-4); setTimeMax(1e20); setSaveCount(1e4); //save every unit time (\hat{t}=sqrt(d/g)=~0.008s) //particle radii setInflowParticleRadius(.5); setFixedParticleRadius(.5);//getInflowParticleRadius()); setRoughBottomType(MULTILAYER); //particle properties LinearViscoelasticFrictionSpecies species; species.setDensity(6 / constants::pi); species.setStiffness(2e5); species.setSlidingStiffness(2.0 / 7.0 * species.getStiffness()); species.setDissipation(25.0); species.setSlidingDissipation(species.getDissipation()); species.setSlidingFrictionCoefficient(0.5); speciesHandler.copyAndAddObject(species); //chute properties setChuteAngleAndMagnitudeOfGravity(0.0, 1.0); } bool readNextArgument(int& i, int argc, char* argv[]) override { if (!strcmp(argv[i], "-ExitLength")) { Mdouble exitHeight = atof(argv[i + 1]); Mdouble exitLength = 1.0 * exitHeight; Mdouble hopperAngle = 45.0; Mdouble hopperLength = 4.0 * exitLength; Mdouble hopperHeight = hopperLength; setHopper(exitLength, exitHeight, hopperAngle, hopperLength, hopperHeight); } else { return Chute::readNextArgument(i, argc, argv); } return true; //returns true if argv is found } void actionsBeforeTimeLoop() override { write(std::cout, false); writeRestartFile(); } }; int main(int argc, char* argv[]) { GranularJet problem; // Particle properties problem.setSilbert(); // Problem parameters problem.setName("GranularJet"); //Corrections problem.setRoughBottomType(MONOLAYER_DISORDERED); // Chute properties problem.setChuteAngle(20); problem.setChuteLength(700 * .25); //700=40cm problem.setChuteWidth(400 * .25); //400=24cm problem.setMaxFailed(6); problem.makeChutePeriodic(); problem.setHopperDimension(2); problem.setHopperLift(200); //250=15cm Mdouble exitHeight = 25; Mdouble exitLength = 3.0 * exitHeight; Mdouble hopperAngle = 45.0; Mdouble hopperLength = 4.0 * exitLength; Mdouble hopperHeight = hopperLength; problem.setHopper(exitLength, exitHeight, hopperAngle, hopperLength, hopperHeight); problem.setZMax(200); problem.dataFile.setFileType(FileType::NO_FILE); problem.fStatFile.setFileType(FileType::NO_FILE); problem.restartFile.setFileType(FileType::MULTIPLE_FILES_PADDED); //solve problem.readArguments(argc, argv); problem.solve(); } // ====================================================================== // \title GpsImpl.cpp // \author lestarch // \brief cpp implementation of the F' sample GPS receiver for a // NMEA GPS receiver device. // // \copyright // Copyright 2018, lestarch. // ====================================================================== #include #include "Fw/Types/BasicTypes.hpp" //File path to UART device on UNIX system #define UART_FILE_PATH "/dev/ttyACM0" #include #include //POSIX includes for UART communication extern "C" { #include #include #include } namespace GpsApp { // ---------------------------------------------------------------------- // Construction, initialization, and destruction // ---------------------------------------------------------------------- GpsComponentImpl :: #if FW_OBJECT_NAMES == 1 GpsComponentImpl( const char *const compName ) : GpsComponentBase(compName), #else GpsComponentBase(void), #endif m_setup(false), m_locked(false), m_fh(-1) { } void GpsComponentImpl :: init( const NATIVE_INT_TYPE queueDepth, const NATIVE_INT_TYPE instance ) { GpsComponentBase::init(queueDepth, instance); } GpsComponentImpl :: ~GpsComponentImpl(void) { } //Step 1: setup // // Each second, we should ensure that the UART is initialized // and if not, we should try to initialize it again. void GpsComponentImpl :: setup(void) { if (m_setup) { return; } //Open the GPS, and configure it for a raw-socket in read-only mode m_fh = open(UART_FILE_PATH, O_RDONLY); if (m_fh < 0) { //std::cout << "[ERROR] Failed to open file: " << UART_FILE_PATH << std::endl; std::cout << "LOLOLOL" << std::endl; return; } //Setup the struct for termios configuration struct termios options; std::memset(&options, 0, sizeof(options)); //Set to raw socket, remove modem control, allow input cfmakeraw(&options); options.c_cflag |= (CLOCAL | CREAD); //Set to 9600 baud cfsetispeed(&options, B9600); //Make the above options stick NATIVE_INT_TYPE status = tcsetattr(m_fh, TCSANOW, &options); if (status != 0) { std::cout << "[ERROR] Failed to setup UART options" << std::endl; return; } m_setup = true; } // ---------------------------------------------------------------------- // Handler implementations for user-defined typed input ports // ---------------------------------------------------------------------- // Step 0: schedIn // // By implementing this "handler" we can respond to the 1HZ call allowing // us to read the GPS UART every 1 second. void GpsComponentImpl :: schedIn_handler( const NATIVE_INT_TYPE portNum, NATIVE_UINT_TYPE context ) { int status = 0; float lat = 0.0f, lon = 0.0f; GpsPacket packet; char buffer[1024]; char* pointer = buffer; //During each cycle, attempt to setup if not setup //Step 1: setup // Each second, we should ensure that the UART is initialized // and if not, we should try to initialize it again. setup(); if (!m_setup) { return; } //Then receive data from the GPS. Should block until available //and thus, this module should not be driven at a rate faster than 1HZ //Step 2: read the UART // Read the GPS message from the UART ssize_t size = read(m_fh, buffer, sizeof(buffer)); if (size <= 0) { std::cout << "[ERROR] Failed to read from UART with: " << size << std::endl; return; } //Look for a recognized GPS location packet and parse it //Step 3: // Parse the GPS message from the UART (looking for $GPPA messages) for (U32 i = 0; i < sizeof(buffer) - 6; i++) { status = sscanf(pointer, "$GPGGA,%f,%f,%c,%f,%c,%u,%u,%f,%f", &packet.utcTime, &packet.dmNS, &packet.northSouth, &packet.dmEW, &packet.eastWest, &packet.lock, &packet.count, &packet.filler, &packet.altitude); //Break when all GPS items are found if (status == 9) { break; } pointer = pointer + 1; } //If we failed to find the packet, or failed to extract data then return if (status != 9) { std::cout << "[ERROR] GPS parsing failed: " << status << std::endl; return; } //GPS packet locations are of the form: ddmm.mmmm //We will convert to lat/lon in degrees only before downlinking //Latitude degrees, add on minutes (converted to degrees), multiply by direction lat = (U32)(packet.dmNS/100.0f); lat = lat + (packet.dmNS - (lat * 100.0f))/60.0f; lat = lat * ((packet.northSouth == 'N') ? 1 : -1); //Longitude degrees, add on minutes (converted to degrees), multiply by direction lon = (U32)(packet.dmEW/100.0f); lon = lon + (packet.dmEW - (lon * 100.0f))/60.f; lon = lon * ((packet.eastWest == 'E') ? 1 : -1); //Step 4: downlink // Call the downlink functions to send down data std::cout << "[INFO] Current lat, lon: (" << lat << "," << lon << ")" << std::endl; tlmWrite_Gps_Latitude(lat); tlmWrite_Gps_Longitude(lon); tlmWrite_Gps_Altitude(packet.altitude); tlmWrite_Gps_Count(packet.count); //Lock status update only if changed //Step 7,8: note changed lock status // Emit an event if the lock has been aquired, or lost if (packet.lock == 0 && m_locked) { m_locked = false; log_WARNING_HI_Gps_LockLost(); } else if (packet.lock == 1 && !m_locked) { m_locked = true; log_ACTIVITY_HI_Gps_LockAquired(); } } // ---------------------------------------------------------------------- // Command handler implementations // ---------------------------------------------------------------------- //Step 9: respond to status command // // When a status command is received, respond by emitting the // current lock status as an Event. void GpsComponentImpl :: Gps_ReportLockStatus_cmdHandler( const FwOpcodeType opCode, const U32 cmdSeq ) { //Locked-force print if (m_locked) { log_ACTIVITY_HI_Gps_LockAquired(); } else { log_WARNING_HI_Gps_LockLost(); } } } // end namespace GpsApp /********** This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. (See .) 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 **********/ // "liveMedia" // Copyright (c) 1996-2012 Live Networks, Inc. All rights reserved. // Media // Implementation #include "Media.hh" #include "HashTable.hh" // A data structure for looking up a Medium by its string name class MediaLookupTable { public: static MediaLookupTable* ourMedia(UsageEnvironment& env); Medium* lookup(char const* name) const; // Returns NULL if none already exists void addNew(Medium* medium, char* mediumName); void remove(char const* name); void generateNewName(char* mediumName, unsigned maxLen); protected: MediaLookupTable(UsageEnvironment& env); virtual ~MediaLookupTable(); private: UsageEnvironment& fEnv; HashTable* fTable; unsigned fNameGenerator; }; ////////// Medium ////////// Medium::Medium(UsageEnvironment& env) : fEnviron(env), fNextTask(NULL) { // First generate a name for the new medium: MediaLookupTable::ourMedia(env)->generateNewName(fMediumName, mediumNameMaxLen); env.setResultMsg(fMediumName); // Then add it to our table: MediaLookupTable::ourMedia(env)->addNew(this, fMediumName); } Medium::~Medium() { // Remove any tasks that might be pending for us: fEnviron.taskScheduler().unscheduleDelayedTask(fNextTask); } Boolean Medium::lookupByName(UsageEnvironment& env, char const* mediumName, Medium*& resultMedium) { resultMedium = MediaLookupTable::ourMedia(env)->lookup(mediumName); if (resultMedium == NULL) { env.setResultMsg("Medium ", mediumName, " does not exist"); return False; } return True; } void Medium::close(UsageEnvironment& env, char const* name) { MediaLookupTable::ourMedia(env)->remove(name); } void Medium::close(Medium* medium) { if (medium == NULL) return; close(medium->envir(), medium->name()); } Boolean Medium::isSource() const { return False; // default implementation } Boolean Medium::isSink() const { return False; // default implementation } Boolean Medium::isRTCPInstance() const { return False; // default implementation } Boolean Medium::isRTSPClient() const { return False; // default implementation } Boolean Medium::isRTSPServer() const { return False; // default implementation } Boolean Medium::isMediaSession() const { return False; // default implementation } Boolean Medium::isServerMediaSession() const { return False; // default implementation } Boolean Medium::isDarwinInjector() const { return False; // default implementation } ////////// _Tables implementation ////////// _Tables* _Tables::getOurTables(UsageEnvironment& env, Boolean createIfNotPresent) { if (env.liveMediaPriv == NULL && createIfNotPresent) { env.liveMediaPriv = new _Tables(env); } return (_Tables*)(env.liveMediaPriv); } void _Tables::reclaimIfPossible() { if (mediaTable == NULL && socketTable == NULL) { fEnv.liveMediaPriv = NULL; delete this; } } _Tables::_Tables(UsageEnvironment& env) : mediaTable(NULL), socketTable(NULL), fEnv(env) { } _Tables::~_Tables() { } ////////// MediaLookupTable implementation ////////// MediaLookupTable* MediaLookupTable::ourMedia(UsageEnvironment& env) { _Tables* ourTables = _Tables::getOurTables(env); if (ourTables->mediaTable == NULL) { // Create a new table to record the media that are to be created in // this environment: ourTables->mediaTable = new MediaLookupTable(env); } return (MediaLookupTable*)(ourTables->mediaTable); } Medium* MediaLookupTable::lookup(char const* name) const { return (Medium*)(fTable->Lookup(name)); } void MediaLookupTable::addNew(Medium* medium, char* mediumName) { fTable->Add(mediumName, (void*)medium); } void MediaLookupTable::remove(char const* name) { Medium* medium = lookup(name); if (medium != NULL) { fTable->Remove(name); if (fTable->IsEmpty()) { // We can also delete ourselves (to reclaim space): _Tables* ourTables = _Tables::getOurTables(fEnv); delete this; ourTables->mediaTable = NULL; ourTables->reclaimIfPossible(); } delete medium; } } void MediaLookupTable::generateNewName(char* mediumName, unsigned /*maxLen*/) { // We should really use snprintf() here, but not all systems have it sprintf(mediumName, "liveMedia%d", fNameGenerator++); } MediaLookupTable::MediaLookupTable(UsageEnvironment& env) : fEnv(env), fTable(HashTable::create(STRING_HASH_KEYS)), fNameGenerator(0) { } MediaLookupTable::~MediaLookupTable() { delete fTable; } 1-10 // -*- coding: us-ascii-unix -*- #include // std::sort #include "test-sys/test.hh" #include "tests/test-util/print-objects.hh" #include "tests/test-util/text-bitmap.hh" #include "bitmap/bitmap.hh" #include "bitmap/color.hh" #include "bitmap/color-counting.hh" #include "bitmap/mask.hh" #include "geo/int-point.hh" #include "geo/int-size.hh" #include "util/generator-adapter.hh" // sorted #include "util/make-vector.hh" void test_color_counting(){ using namespace faint; const auto colors = bitmap_value_map{ {'r', color_red}, {'g', color_green}, {'b', color_blue}, {'m', color_magenta}, {'R', with_alpha(color_red, 0)}, {'M', with_alpha(color_magenta, 50)}, {'G', with_alpha(color_gray, 50)}}; { // add_color_counts, four distinct colors auto bmp = create_bitmap(IntSize(2,2), "rg" "bm", colors); EQUAL(count_colors(bmp), 4); color_counts_t colorCounts; add_color_counts(bmp, colorCounts); EQUAL(colorCounts.size(), 4); EQUAL(colorCounts.at(to_hash(color_red)), 1); EQUAL(colorCounts.at(to_hash(color_green)), 1); EQUAL(colorCounts.at(to_hash(color_blue)), 1); EQUAL(colorCounts.at(to_hash(color_magenta)), 1); } { // add_color_counts, repeated magenta auto bmp = create_bitmap(IntSize(2,2), "rm" "bm", colors); EQUAL(count_colors(bmp), 3); color_counts_t colorCounts; add_color_counts(bmp, colorCounts); EQUAL(colorCounts.size(), 3); EQUAL(colorCounts.at(to_hash(color_red)), 1); EQUAL(colorCounts.at(to_hash(color_blue)), 1); EQUAL(colorCounts.at(to_hash(color_magenta)), 2); } { // unique_colors_rgb auto key = sorted(make_vector({ color_red, color_magenta, color_gray}, strip_alpha)); auto img = create_bitmap_and_mask(IntSize(3, 3), "rmR" "bmM" "GGG", colors, " # " "# " " "); // auto v = unique_colors_rgb(img.bitmap, img.mask); // EQUAL(v, key); } } #ifndef CRADLE_GUI_APP_TOP_LEVEL_UI_HPP #define CRADLE_GUI_APP_TOP_LEVEL_UI_HPP #include namespace cradle { struct app_instance; struct app_window_controller : alia::app_window_controller { app_instance* instance; void do_ui(alia::ui_context& ctx); }; } #endif AutoLS/AutoEngine #include "AutoGL.h" object_data InitObject(v3* Vertices, int Count, int TotalCount, uint32* Indices, int IndicesCount, GLenum Usage) { object_data Object = {}; glGenVertexArrays(1, &Object.VAO); glGenBuffers(1, &Object.VBO); if(Indices) { glGenBuffers(1, &Object.EBO); Object.Indices = Indices; Object.IndicesCount = IndicesCount; } Object.Vertices = Vertices; Object.Count = Count; Object.TotalCount = TotalCount; Object.Usage = Usage; return Object; } void UploadObjectData(object_data* Object) { glBindVertexArray(Object->VAO); glBindBuffer(GL_ARRAY_BUFFER, Object->VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(v3) * Object->TotalCount, Object->Vertices, Object->Usage); if(Object->Indices) { glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, Object->EBO); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(uint32) * Object->IndicesCount, Object->Indices, Object->Usage); } glBindVertexArray(0); } void UpdateObjectData(object_data* Object, v3* Vertices, int Count) { Object->Vertices = Vertices; Object->Count = Count; glBindVertexArray(Object->VAO); glBindBuffer(GL_ARRAY_BUFFER, Object->VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(v3) * Count, Vertices, Object->Usage); } void AttribPointer(object_data* Object, uint32 MemLoc, int Size, GLsizei Stride, int Offset) { glBindVertexArray(Object->VAO); glVertexAttribPointer(MemLoc, Size, GL_FLOAT, GL_FALSE, Stride * sizeof(real32), (void*)(sizeof(real32) * Offset)); glEnableVertexAttribArray(MemLoc); glBindVertexArray(0); } simple_renderer InitSimpleRenderer(char* VertPath, char* FragPath) { simple_renderer Renderer = {}; Renderer.Shader = CreateRenderer(LoadShaderSource(VertPath), LoadShaderSource(FragPath)); v3 RectObjectVert[] = { V3(0.5f, 0.5f), V3(1, 1), //Top Right V3(0.5f, -0.5f), V3(1, 0), //Bottom Right V3(-0.5f, -0.5f), V3(), //Bottom Left V3(-0.5f, -0.5f), V3(), //Bottom Left V3(-0.5f, 0.5f), V3(0, 1), //Top Left V3(0.5f, 0.5f), V3(1, 1) //Top Right }; v3 TriObjectVert[] = { V3(0, 0.5f), V3(0.5, 1), //Top Centre V3(-0.5f, -0.5f), V3(), //Bottom Left V3(0.5f, -0.5f), V3(1, 0), //Bottom Right }; Renderer.Rect = InitObject(RectObjectVert, 6, ArraySize(RectObjectVert)); UploadObjectData(&Renderer.Rect); AttribPointer(&Renderer.Rect, 0, 3, 6, 0); AttribPointer(&Renderer.Rect, 1, 3, 6, 3); Renderer.Tri = InitObject(TriObjectVert, 3, ArraySize(TriObjectVert)); UploadObjectData(&Renderer.Tri); AttribPointer(&Renderer.Tri, 0, 3, 6, 0); AttribPointer(&Renderer.Tri, 1, 3, 6, 3); return Renderer; } void SetGlobalUniforms(uint32 Renderer, mat4 Projection, mat4 View) { SetMat4(Renderer, "Projection", Projection); SetMat4(Renderer, "View", View); } #ifdef USE_LEGACY_MATH void DrawObject(uint32 Renderer, object_data* Object, v3 Pos, v3 Dim, real32 Theta, v3 Axis, v4 Color, uint32 Texture, bool Blend) { Assert(Object); glUseProgram(Renderer); SetVec4(Renderer, "Color", Color); mat4 Transform = Mat4(); Transform = Scale(Transform, Dim); Transform = Rotate(Transform, Axis, Theta); Transform = Translate(Transform, Pos); SetMat4(Renderer, "Transform", Transform); if(Blend) { glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); } if(Texture) { SetInt(Renderer, "Texture", 0); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, Texture); } glBindVertexArray(Object->VAO); if(Object->Indices) { glDrawElements(GL_TRIANGLES, Object->IndicesCount, GL_UNSIGNED_INT, 0); } else { glDrawArrays(GL_TRIANGLES, 0, Object->Count); } glDisable(GL_BLEND); glBindVertexArray(0); glUseProgram(0); } void BasicDraw(uint32 Renderer, object_data* Object, v3 Pos, v3 Dim, v4 Color, real32 Theta, v3 Axis, bool Fill, bool Blend) { glUseProgram(Renderer); SetVec4(Renderer, "Color", Color); mat4 Transform = Mat4(); Transform = Scale(Transform, Dim); Transform = Rotate(Transform, Axis, Theta); Transform = Translate(Transform, Pos); SetMat4(Renderer, "Transform", Transform); if(Blend) { glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); } glBindVertexArray(Object->VAO); if(Object->Indices) { glDrawElements(GL_TRIANGLES, Object->IndicesCount, GL_UNSIGNED_INT, 0); } else { if(Fill) glDrawArrays(GL_TRIANGLES, 0, Object->Count); else glDrawArrays(GL_LINE_LOOP, 0, Object->Count); } glDisable(GL_BLEND); glBindVertexArray(0); glUseProgram(0); } void RenderSprite(uint32 Renderer, uint32 Texture, rect32* Clips, object_data* Object, render_flip Flip, v3 Pos, v3 Dim, real32 Theta, v3 Axis) { real32 tw = Clips->Dim.x; real32 th = Clips->Dim.y; real32 tx = Clips->Pos.x; real32 ty = Clips->Pos.y; switch(Flip) { case FLIP_HORIZONTAL: { tx = tx + tw; tw = -tw; } break; case FLIP_VERTICAL: { ty = ty + th; th = -th; } break; } v3 Vertices[] = { V3(0.5f, 0.5f), V3(tx + tw, ty), //Top Right V3(0.5f, -0.5f), V3(tx + tw, ty + th), //Bottom Right V3(-0.5f, -0.5f), V3(tx, ty + th), //Bottom Left V3(-0.5f, -0.5f), V3(tx, ty + th), //Bottom Left V3(-0.5f, 0.5f), V3(tx, ty), //Top Left V3(0.5f, 0.5f), V3(tx + tw, ty) //Top Right }; UpdateObjectData(Object, Vertices, ArraySize(Vertices)); glUseProgram(Renderer); SetVec4(Renderer, "Color", Color()); mat4 Transform = Mat4(); Transform = Scale(Transform, Dim); Transform = Rotate(Transform, Axis, Theta); Transform = Translate(Transform, Pos); SetMat4(Renderer, "Transform", Transform); SetInt(Renderer, "Texture", 0); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, Texture); glBindVertexArray(Object->VAO); glDrawArrays(GL_TRIANGLES, 0, Object->Count); glBindVertexArray(0); glUseProgram(0); } #endif void DrawGL(GLenum Mode, v3* Vertices, int Count, v4 DrawColor = Color()) { glColor4fv((real32*)&DrawColor); glBegin(Mode); for(int i = 0; i < Count; ++i) { glVertex3fv((real32*)&Vertices[i]); } glEnd(); } void DrawShape(uint32 Renderer, v2* Vertices, int Count, v4 Color, bool Blend, bool WireFrame) { v3* Vertices_3 = (v3*)malloc(sizeof(v3) * Count); for(int i = 0; i < Count; ++i) { Vertices_3[i] = V3(Vertices[i]); } object_data Object = InitObject(Vertices_3, Count, Count); UploadObjectData(&Object); AttribPointer(&Object, 0, 3, 3, 0); glUseProgram(Renderer); SetVec4(Renderer, "Color", Color); mat4 Transform = Mat4(); SetMat4(Renderer, "Transform", Transform); if(Blend) { glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); } if(WireFrame) { glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); } glBindVertexArray(Object.VAO); glDrawArrays(GL_LINE_LOOP, 0, Object.Count); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glDisable(GL_BLEND); glBindVertexArray(0); glUseProgram(0); glDeleteBuffers(1, &Object.VAO); glDeleteBuffers(1, &Object.VBO); } void UpdateTextureGL(uint32 Texture, char* Path, bool Alpha, bool Flip, int n = 0) { stbi_set_flip_vertically_on_load(Flip); int Width, Height, Components; uint8 *Data = stbi_load(Path, &Width, &Height, &Components, n); if (Data) { GLenum Format; if (Components == 1) Format = GL_RED; else if (Components == 3) Format = GL_RGB; else if (Components == 4) Format = GL_RGBA; glBindTexture(GL_TEXTURE_2D, Texture); glTexImage2D(GL_TEXTURE_2D, 0, Format, Width, Height, 0, Format, GL_UNSIGNED_BYTE, Data); glGenerateMipmap(GL_TEXTURE_2D); if(Alpha) { glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); } else { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); } glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); stbi_image_free(Data); } else { printf("Texture failed to load at path: %s\n", Path); stbi_image_free(Data); } } void UpdateTextureGL(texture_data* Texture, char* Path, bool Alpha, bool Flip) { stbi_set_flip_vertically_on_load(Flip); int Width, Height, Components; uint8 *Data = stbi_load(Path, &Width, &Height, &Components, 0); if (Data) { Texture->Dim = V2((real32)Width, (real32)Height); GLenum Format; if (Components == 1) Format = GL_RED; else if (Components == 3) Format = GL_RGB; else if (Components == 4) Format = GL_RGBA; glBindTexture(GL_TEXTURE_2D, Texture->ID); glTexImage2D(GL_TEXTURE_2D, 0, Format, Width, Height, 0, Format, GL_UNSIGNED_BYTE, Data); glGenerateMipmap(GL_TEXTURE_2D); if(Alpha) { glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); } else { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); } glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); stbi_image_free(Data); Texture->Success = true; } else { Texture->Success = false; printf("Texture failed to load at path: %s\n", Path); stbi_image_free(Data); } } void CheckTextureAndUpdate(uint32 Texture, char* Path, bool Alpha = true, bool Flip = true, int n = 0) { if(glIsTexture(Texture)) { UpdateTextureGL(Texture, Path, Alpha, Flip, n); } } void CheckAndReloadTexture(uint32 &Texture, char* Path, bool Alpha, bool Flip) { if(glIsTexture(Texture)) { glDeleteTextures(1, &Texture); Texture = LoadTextureGL(Path, true, false, 0); } } uint32 LoadTextureGL(char* Path, bool Alpha = true, bool Flip = true, int n = 0) { stbi_set_flip_vertically_on_load(Flip); uint32 TextureID; glGenTextures(1, &TextureID); int Width, Height, Components; uint8 *Data = stbi_load(Path, &Width, &Height, &Components, n); if (Data) { GLenum Format; if (Components == 1) Format = GL_RED; else if (Components == 3) Format = GL_RGB; else if (Components == 4) Format = GL_RGBA; glBindTexture(GL_TEXTURE_2D, TextureID); glTexImage2D(GL_TEXTURE_2D, 0, Format, Width, Height, 0, Format, GL_UNSIGNED_BYTE, Data); glGenerateMipmap(GL_TEXTURE_2D); if(Alpha) { glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); } else { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); } glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); stbi_image_free(Data); } else { printf("Texture failed to load at path: %s\n", Path); stbi_image_free(Data); } return TextureID; } uint32 LoadTextureGL(uint8* Data, int Width, int Height, bool Alpha = true, int n = 0) { uint32 TextureID; glGenTextures(1, &TextureID); if (Data) { GLenum Format; if (n == 1) Format = GL_RED; else if (n == 3) Format = GL_RGB; else if (n == 4) Format = GL_RGBA; glBindTexture(GL_TEXTURE_2D, TextureID); glTexImage2D(GL_TEXTURE_2D, 0, Format, Width, Height, 0, Format, GL_UNSIGNED_BYTE, Data); glGenerateMipmap(GL_TEXTURE_2D); if(Alpha) { glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); } else { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); } glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); } else { printf("Texture failed to load\n"); } return TextureID; } texture_data LoadTextureGLEX(char* Path, bool Alpha, bool Flip) { texture_data Texture = {}; stbi_set_flip_vertically_on_load(Flip); uint32 TextureID; glGenTextures(1, &TextureID); int Width, Height, Components; uint8* Data = 0; Data = stbi_load(Path, &Width, &Height, &Components, 0); if (Data) { GLenum Format; if (Components == 1) Format = GL_RED; else if (Components == 3) Format = GL_RGB; else if (Components == 4) Format = GL_RGBA; glBindTexture(GL_TEXTURE_2D, TextureID); glTexImage2D(GL_TEXTURE_2D, 0, Format, Width, Height, 0, Format, GL_UNSIGNED_BYTE, Data); glGenerateMipmap(GL_TEXTURE_2D); if(Alpha) { glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); } else { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); } glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); stbi_image_free(Data); Texture.Success = true; } else { printf("Texture failed to load at path: %s\n", Path); stbi_image_free(Data); } Texture.ID = TextureID; Texture.Dim = V2((real32)Width, (real32)Height); return Texture; } void UpdateTextGL(uint32 ID, TTF_Font* Font, char* Text, SDL_Color Color, bool FreeText = false, SDL_Color BgColor = {}, text_render_type Type = TEXT_RENDER_BLENDED) { SDL_Surface* Surface = 0; switch(Type) { case TEXT_RENDER_SOLID: { Surface = TTF_RenderText_Solid(Font, Text, Color); } break; case TEXT_RENDER_SHADED: { Surface = TTF_RenderText_Shaded(Font, Text, Color, BgColor); } break; case TEXT_RENDER_BLENDED: { Surface = TTF_RenderText_Blended(Font, Text, Color); } break; } if(FreeText) { free(Text); } if(Surface) { uint8 BytesPerPixel = Surface->format->BytesPerPixel; GLenum Format = (BytesPerPixel == 4) ? GL_RGBA : GL_RGB; glBindTexture(GL_TEXTURE_2D, ID); glTexImage2D(GL_TEXTURE_2D, 0, Format, Surface->w, Surface->h, 0, Format, GL_UNSIGNED_BYTE, Surface->pixels); glGenerateMipmap(GL_TEXTURE_2D); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); } else { printf("Failed to load text\n"); } SDL_FreeSurface(Surface); } uint32 LoadTextGL(TTF_Font* Font, const char* Text, SDL_Color Color, SDL_Color BgColor = {}, text_render_type Type = TEXT_RENDER_BLENDED) { uint32 ID; glGenTextures(1, &ID); SDL_Surface* Surface; switch(Type) { case TEXT_RENDER_SOLID: { Surface = TTF_RenderText_Solid(Font, Text, Color); } break; case TEXT_RENDER_SHADED: { Surface = TTF_RenderText_Shaded(Font, Text, Color, BgColor); } break; case TEXT_RENDER_BLENDED: { Surface = TTF_RenderText_Blended(Font, Text, Color); } break; } if(Surface) { uint8 BytesPerPixel = Surface->format->BytesPerPixel; GLenum Format = (BytesPerPixel == 4) ? GL_RGBA : GL_RGB; glBindTexture(GL_TEXTURE_2D, ID); glTexImage2D(GL_TEXTURE_2D, 0, Format, Surface->w, Surface->h, 0, Format, GL_UNSIGNED_BYTE, Surface->pixels); glGenerateMipmap(GL_TEXTURE_2D); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); } else { printf("Failed to load text\n"); } SDL_FreeSurface(Surface); return ID; } glyph_character LoadGlyphGL(TTF_Font* Font, uint16 Ch, SDL_Color Color) { glyph_character Result = {}; uint32 ID; glGenTextures(1, &ID); TTF_GlyphMetrics(Font, Ch, &Result.MinX, &Result.MaxX, &Result.MinY, &Result.MaxY, &Result.Advance); Result.Width = Result.MaxX - Result.MinX; Result.Height = TTF_FontHeight(Font); SDL_Surface* Surface = TTF_RenderGlyph_Blended(Font, Ch, Color); if(Surface) { uint8 BytesPerPixel = Surface->format->BytesPerPixel; GLenum Format = (BytesPerPixel == 4) ? GL_RGBA : GL_RGB; glBindTexture(GL_TEXTURE_2D, ID); glTexImage2D(GL_TEXTURE_2D, 0, Format, Surface->w, Surface->h, 0, Format, GL_UNSIGNED_BYTE, Surface->pixels); glGenerateMipmap(GL_TEXTURE_2D); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); } else { printf("Failed to load text\n"); } SDL_FreeSurface(Surface); Result.Texture = ID; return Result; } char* LoadShaderSource(char* Path) { FILE* ShaderSourceFile = fopen(Path, "rb"); char* Buffer = 0; long Length; if(!ShaderSourceFile) { printf("File does not exist.\n"); } else { fseek(ShaderSourceFile, 0L, SEEK_END); Length = ftell(ShaderSourceFile); fseek(ShaderSourceFile, 0L, SEEK_SET); Buffer = (char*)calloc(Length, sizeof(char)); if(Buffer) { fread(Buffer, sizeof(char), Length, ShaderSourceFile); } else { printf("Buffer is empty. Error.\n"); } } fclose(ShaderSourceFile); return Buffer; } uint32 CreateRenderer(char* VertexShaderSource, char* FragmentShaderSource) { uint32 VertexShader; VertexShader = glCreateShader(GL_VERTEX_SHADER); glShaderSource(VertexShader, 1, &VertexShaderSource, 0); glCompileShader(VertexShader); bool32 ShaderCompileSuccess; char InfoLog[512]; glGetShaderiv(VertexShader, GL_COMPILE_STATUS, &ShaderCompileSuccess); if(!ShaderCompileSuccess) { glGetShaderInfoLog(VertexShader, 512, 0, InfoLog); printf("VERTEX SHADER COMPILATION FAILED: %s", InfoLog); } uint32 FragmentShader; FragmentShader = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(FragmentShader, 1, &FragmentShaderSource, 0); glCompileShader(FragmentShader); glGetShaderiv(FragmentShader, GL_COMPILE_STATUS, &ShaderCompileSuccess); if(!ShaderCompileSuccess) { glGetShaderInfoLog(FragmentShader, 512, 0, InfoLog); printf("FRAGMENT SHADER COMPILATION FAILED: %s", InfoLog); } uint32 Program = glCreateProgram(); glAttachShader(Program, VertexShader); glAttachShader(Program, FragmentShader); glLinkProgram(Program); bool32 LinkingSuccess; glGetProgramiv(Program, GL_LINK_STATUS, &LinkingSuccess); if(!LinkingSuccess) { glGetProgramInfoLog(Program, 512, 0, InfoLog); printf("PROGRAM LINKING FAILED: %s", InfoLog); } free(VertexShaderSource); free(FragmentShaderSource); glDeleteShader(VertexShader); glDeleteShader(FragmentShader); return Program; } void SetViewport(const rect32 &Rect) { glViewport((int)Rect.Pos.x, (int)Rect.Pos.y, (int)Rect.Dim.x, (int)Rect.Dim.y); } void SetViewportUpper(const rect32 &Rect) { glViewport((int)Rect.Pos.x, (int)(GlobalWinDim.y - Rect.Pos.y - Rect.Dim.y), (int)Rect.Dim.x, (int)Rect.Dim.y); } void SetReal32(uint32 Shader, char* Location, real32 A) { glUseProgram(Shader); glUniform1f(glGetUniformLocation(Shader, Location), A); } void SetVec2(uint32 Shader, char* Location, v2 A) { glUseProgram(Shader); glUniform2f(glGetUniformLocation(Shader, Location), A.x, A.y); } void SetVec3(uint32 Shader, char* Location, v3 A) { glUseProgram(Shader); glUniform3f(glGetUniformLocation(Shader, Location), A.x, A.y, A.z); } void SetVec4(uint32 Shader, char* Location, v4 A) { glUseProgram(Shader); glUniform4f(glGetUniformLocation(Shader, Location), A.x, A.y, A.z, A.w); } void SetMat4(uint32 Shader, char* Location, mat4 A, GLenum IsTranspose) { glUseProgram(Shader); glUniformMatrix4fv(glGetUniformLocation(Shader, Location), 1, IsTranspose, (real32*)A.E); } void SetInt(uint32 Shader, char* Location, int Entry) { glUseProgram(Shader); glUniform1i(glGetUniformLocation(Shader, Location), Entry); }#include #include #include #include using namespace std; /** * Auto-generated code below aims at helping you parse * the standard input according to the problem statement. **/ int main() { // game loop while (1) { int x; int y; int nextCheckpointX; // x position of the next check point int nextCheckpointY; // y position of the next check point int nextCheckpointDist; // distance to the next checkpoint int nextCheckpointAngle; // angle between your pod orientation and the direction of the next checkpoint cin >> x >> y >> nextCheckpointX >> nextCheckpointY >> nextCheckpointDist >> nextCheckpointAngle; cin.ignore(); int opponentX; int opponentY; cin >> opponentX >> opponentY; cin.ignore(); int thrust = 0; if (nextCheckpointAngle > 90 || nextCheckpointAngle < -90) { thrust = 0; } else { thrust = 100; } cout << nextCheckpointX << " " << nextCheckpointY << " " << thrust << endl; } }farnasirim/range-tracker #include "test_common.h" TEST_CASE("RangeTracker objects must split intervals on nested deletes", "[RangeTracker]") { auto rts = ALL_IMPLEMENTATIONS(int); std::vector> empty = {}; for(auto& it: rts) { it->Add(1, 6); } std::vector> existing = {{1, 6}}; SECTION("delete, marginal right") { std::vector> expected = {{1, 4}}; for(auto& it: rts) { it->Delete(4, 6); } for(auto& it: rts) { REQUIRE(it->Get(-200, 200) == expected); REQUIRE(it->Get(1, 2) == expected); REQUIRE(it->Get(-1, 1) == empty); REQUIRE(it->Get(2, 3) == expected); REQUIRE(it->Get(5, 6) == empty); REQUIRE(it->Get(1, 5) == expected); } } SECTION("delete, marginal right, exceeding") { std::vector> expected = {{1, 4}}; for(auto& it: rts) { it->Delete(4, 7); } for(auto& it: rts) { REQUIRE(it->Get(-200, 200) == expected); REQUIRE(it->Get(1, 2) == expected); REQUIRE(it->Get(-1, 1) == empty); REQUIRE(it->Get(2, 3) == expected); REQUIRE(it->Get(5, 6) == empty); REQUIRE(it->Get(1, 5) == expected); } } SECTION("delete, marginal left") { std::vector> expected = {{3, 6}}; for(auto& it: rts) { it->Delete(1, 3); } for(auto& it: rts) { REQUIRE(it->Get(-200, 200) == expected); REQUIRE(it->Get(1, 2) == empty); REQUIRE(it->Get(-1, 1) == empty); REQUIRE(it->Get(2, 3) == empty); REQUIRE(it->Get(5, 6) == expected); REQUIRE(it->Get(1, 5) == expected); } } SECTION("delete, marginal left, exceeding") { std::vector> expected = {{3, 6}}; for(auto& it: rts) { it->Delete(-1, 3); } for(auto& it: rts) { REQUIRE(it->Get(-200, 200) == expected); REQUIRE(it->Get(1, 2) == empty); REQUIRE(it->Get(-1, 1) == empty); REQUIRE(it->Get(2, 3) == empty); REQUIRE(it->Get(5, 6) == expected); REQUIRE(it->Get(1, 5) == expected); } } } 0 //============================================================================================================== //Grid2D.hpp //by Oct-13-2015. //============================================================================================================== #pragma once #ifndef _included_Grid2D__ #define _included_Grid2D__ #include "Math2D.hpp" // struct GridNode{ // IntVec2 gridPosition; // } //=========================================================================================================== ///---------------------------------------------------------------------------------------------------------- ///generic grid functions // void CreateGrid2D(const int& width, const int& height){ // // for (int x = 0; x < width; x++){ // for (int y = 0; y < height; y++){ // // } // } // } typedef IntVec2 GridPosition; unsigned int GetGridIndex(GridPosition position, unsigned int width, unsigned int height){ } GetGridPosition() //=========================================================================================================== #endif //__includedGrid2D__ GerHobbelt/binlog0 #include //[c #include //] #include #include "monolithic_examples.h" #if defined(BUILD_MONOLITHIC) #define main(cnt, arr) binlog_test_categories_main(cnt, arr) #endif int main(int argc, const char** argv) { binlog::default_thread_local_writer().setName({}); //[c BINLOG_INFO_C(my_category, "This is a categorized event"); // Outputs: my_category This is a categorized event //] binlog::SessionWriter writer(binlog::default_session()); writer.setName("W1"); //[wc BINLOG_INFO_WC(writer, my_category, "My writer, my category"); // Outputs: my_category W1 My writer, my category //] binlog::consume(std::cout); return 0; } #include "helpers_layout.h" #include "helpers.h" using namespace std; namespace agge { namespace tests { bool ref_glyph_run::operator ==(const glyph_run &rhs) const { if (_font == rhs.font_ && _offset == rhs.offset) { vector::const_iterator i = _glyphs.begin(); positioned_glyphs_container_t::const_iterator j = rhs.begin(); for (; i != _glyphs.end() && j != rhs.end(); ++i, ++j) if (i->index != j->index || (_check_glyph_advances && !(i->d == j->d))) return false; return i == _glyphs.end() && j == rhs.end(); } return false; } ref_text_line::ref_text_line(real_t offset_x, real_t offset_y, real_t extent_, const vector &glyph_runs) : _offset(create_vector(offset_x, offset_y)), _extent(extent_), _glyph_runs(glyph_runs) { } bool ref_text_line::operator ==(const text_line &rhs) const { if (_offset == rhs.offset && (!_extent || tests::equal(_extent, rhs.extent))) { vector::const_iterator i = _glyph_runs.begin(); glyph_runs_container_t::const_iterator j = rhs.begin(); for (; i != _glyph_runs.end() && j != rhs.end(); ++i, ++j) if (!(*i == *j)) return false; return true; } return false; } ref_text_line_offsets::ref_text_line_offsets(real_t offset_x, real_t offset_y) : _offset(create_vector(offset_x, offset_y)) { } bool ref_text_line_offsets::operator ==(const text_line &rhs) const { return _offset == rhs.offset; } richtext_t simple_richtext(const string &text, const string &family, int height, font_weight weight, bool italic, font_hinting hinting) { font_style_annotation a = { font_descriptor::create(family, height, weight, italic, hinting), }; richtext_t result(a); result.append(text.begin(), text.end()); return result; } richtext_t R(const std::string &text) { return simple_richtext(text, "Arial", 10); } } } src/command_parser.cpp #include "command_parser.h" #include "typedefs.h" enum Commands { ping, update, ver }; CommandParser::CommandParser() { cmd_map = { {".ping", ping}, {".update", update}, {".version", ver} }; } int CommandParser::findCommand(String cmd) { for (auto entry : cmd_map) if(entry.first.compareTo(cmd) == 0) return entry.second; return -1; } BLYNK_WRITE(DEBUG_BRIDGE) { String msg = param.asString(); String response; unsigned int len = msg.length() + 1; char buf[len]; msg.toCharArray(buf, len); buf[len - 1] = '\0'; String msg_id = strtok(buf, " "); String cmd = strtok(NULL, " "); String arg = strtok(NULL, " "); std::vector args; while(!arg.isEmpty()) { args.push_back(arg); arg = strtok(NULL, " "); } switch(CmdParser.findCommand(cmd)) { case ping: response = "pong"; break; case update: break; case ver: if(args.size() > 0) { if(args[0].compareTo("get") == 0) { response = String("v") + String(version); } else if(args[0].compareTo("list") == 0) { response = String("version list not ready yet :-/"); } else if(args[0].compareTo("install") == 0 && args.size() > 1) { loadFirmware(args[1]); } else { response = String("Error: Unknown subcommand \'" + args[0] + "\'!"); } } else { response = String("Error: Not enough arguments!"); } break; default: response = String("Error: Command \'" + cmd + "\' not found!"); break; } bridge.printf("%s %s", msg_id.c_str(), response.c_str()); bridge.flush(); } CommandParser CmdParser;#pragma once #include "ecs.hpp" class PositionComponent : public Component { private: int xpos; int ypos; public: int x() {return xpos; } int y() {return ypos; } void init() override { xpos= 0; ypos=0; } void update() override { xpos++; ypos++; } void setPos(int x, int y) { xpos=x; ypos=y; } };/* ** EPITECH PROJECT, 2019 ** CPP_zia_2019 ** File description: ** Server.cpp */ #include #include #include "zia/server/Server.hpp" #include "openZia/Packet.hpp" #include "openZia/Context.hpp" namespace Zia::Server { Server *Server::INSTANCE = nullptr; Server::Server() : _logger("Server"), _config("config.toml"), _threadPool(8), _pipeline("modules", "config"), _httpSocket(toml::find(_config.root(), "server", "http_port"), 10), _httpsSocket(toml::find(_config.root(), "server", "https_port"), 10), _modulesWatcher("modules", [this]() { this->reloadModules(false); }), _configWatcher("config", [this]() { this->reloadModules(false); }), _acceptClients(false) { INSTANCE = this; this->reloadModules(); } void Server::start() { this->_httpSocket.open([&](std::shared_ptr client) { if (!this->_acceptClients.load()) return false; bool accepted = this->_threadPool.pushTask([client, this]() { auto endpoint = client->toEndpoint(); auto context = oZ::Context(oZ::Packet(std::move(client->getInBuffer()), endpoint)); context.getPacket().setFileDescriptor(client->getFd()); // context.setMetadata("fsroot", toml::find(_config.root(), "filesystem", "root")); this->_pipeline.onConnection(context); try { this->_pipeline.runPipeline(context); if (context.getState() == oZ::State::Error) { context.setState(oZ::State::Completed); this->_pipeline.runPipeline(context); } } catch (...) {} this->_pipeline.onDisconnection(context); this->_httpSocket.removeClient(client); }); if (!accepted) this->_httpSocket.removeClient(client); return accepted; }); this->_httpsSocket.open([&](std::shared_ptr client) { if (!this->_acceptClients.load()) return false; bool accepted = this->_threadPool.pushTask([client, this]() { auto endpoint = client->toEndpoint(); auto context = oZ::Context(oZ::Packet(std::move(client->getInBuffer()), endpoint)); context.getPacket().setFileDescriptor(client->getFd()); context.getPacket().setEncryption(true); // context.setMetadata("fsroot", toml::find(_config.root(), "filesystem", "root")); this->_pipeline.onConnection(context); try { this->_pipeline.runPipeline(context); if (context.getState() == oZ::State::Error) { context.setState(oZ::State::Completed); this->_pipeline.runPipeline(context); } } catch (...) {} this->_pipeline.onDisconnection(context); this->_httpsSocket.removeClient(client); }); if (!accepted) this->_httpsSocket.removeClient(client); return accepted; }); this->_logger.info("Ready."); while (true) { std::this_thread::sleep_for(std::chrono::milliseconds(1000)); } } void Server::stop() { this->_acceptClients = false; this->waitClients(); this->_logger.info("Closing server sockets..."); this->_httpSocket.close(); this->_httpsSocket.close(); this->_logger.info("Stopping file watchers..."); this->_modulesWatcher.stop(); this->_configWatcher.stop(); } void Server::reloadModules(bool initial) { if (!initial) this->_logger.info("Preventing client from connecting."); this->_acceptClients = false; this->waitClients(); this->_logger.info("Reloading modules..."); this->_pipeline.loadModules(); auto count = this->_pipeline.getModules().size(); std::stringstream ss; ss << "Loaded " << count << " module"; ss << (count > 1 ? "s" : "") << ":"; this->_logger.info(ss.str()); for (const auto &module : this->_pipeline.getModules()) { ss = std::stringstream(); ss << "- " << module->getName(); this->_logger.info(ss.str()); } this->_acceptClients = true; if (!initial) this->_logger.info("Unlocked connections."); } void Server::setupCtrlC() { #if defined(SYSTEM_LINUX) || defined(SYSTEM_DARWIN) struct sigaction sigIntHandler; sigIntHandler.sa_handler = &Server::onCtrlC; sigemptyset(&sigIntHandler.sa_mask); sigIntHandler.sa_flags = 0; sigaction(SIGINT, &sigIntHandler, NULL); #elif defined(SYSTEM_WINDOWS) signal(SIGINT, &Server::onCtrlC); #endif } void Server::waitClients() { while (this->_httpSocket.clientsNb() > 0 || this->_httpsSocket.clientsNb() > 0) { this->_logger.info("Waiting for the clients to disconnect..."); std::this_thread::sleep_for(std::chrono::seconds(1)); } } }maledicente/cursos #include "mainwindow.h" #include "ui_mainwindow.h" #include "QPixmap" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) , ui(new Ui::MainWindow) { ui->setupUi(this); QPixmap logo("/home/usuario/Documentos/GitHub/cursos/QT_Creator_CPP/Aula_QT_10/Pine forest in the mist_xtrafondos.com.jpg"); ui->label->setPixmap(logo.scaled(600,600,Qt::KeepAspectRatio)); } MainWindow::~MainWindow() { delete ui; } void MainWindow::on_pushButton_clicked() { QPixmap img("/home/usuario/Documentos/GitHub/cursos/QT_Creator_CPP/Aula_QT_10/jakub-kozlowski-final-towers-as.jpg"); ui->label->setPixmap(img.scaled(600,600,Qt::KeepAspectRatio)); } 1-10 #ifndef GAME_IG #define GAME_IG #include #include "configs.hpp" #include "States/GameState.hpp" #include typedef std::array StateList; class Game { public: Game(); void init(); void run(); private: sf::RenderWindow mainWindow; GameState* currentState; StateList statesList; }; #endifpaulwratt/cin-5.34.001-10 /* -*- C++ -*- */ /************************************************************************* * Copyright(c) 1995~2005 () * * For the licensing terms see the file COPYING * ************************************************************************/ #include class TObject { }; class TAttLine { public: virtual void Modify() { printf("TAttLine::Modify()\n"); } }; class TLine : public TObject , public TAttLine { }; class TAttArea { public: virtual void Modify() { printf("TAttArea::Modify()\n"); } }; class TBox : public TLine , public TAttArea { public: virtual void Modify() { printf("TBox::Modify()\n"); } }; int main() { TBox box; TLine line; TAttArea attarea; box.Modify(); box.TAttLine::Modify(); box.TAttArea::Modify(); line.Modify(); attarea.Modify(); TLine *pline; TAttArea *pattarea; printf("virtual resolution\n"); pline = &box; pline->Modify(); pline = &line; pline->Modify(); pattarea = &box; pattarea->Modify(); pattarea = &attarea; pattarea->Modify(); return 0; } Cplz95/SVN0 // AStyleTestCon_Console2.cpp // Copyright (c) 2017 by <>. // This code is licensed under the MIT License. // License.md describes the conditions under which this software may be distributed. // AStyleTestCon tests the ASConsole class only. This class is used only in // the console build. It also tests the parseOption function for options used // by only by the console build (e.g. recursive, preserve-date, verbose). It // does not explicitely test the ASStreamIterator class or any other part // of the program. //---------------------------------------------------------------------------- // headers //---------------------------------------------------------------------------- #include #include "AStyleTestCon.h" #ifdef _WIN32 #include #endif //---------------------------------------------------------------------------- // anonymous namespace //---------------------------------------------------------------------------- namespace { // //---------------------------------------------------------------------------- // AStyle test getFilePaths(), wildcmp(), and fileName vector //---------------------------------------------------------------------------- struct GetFilePathsF : public Test { ASFormatter formatter; ASConsole* console; vector fileNames; // build fileNames vector and write the output files GetFilePathsF() { char textIn[] = "\nvoid foo()\n" "{\n" "bar();\n" "}\n"; cleanTestDirectory(getTestDirectory()); console = new ASConsole(formatter); fileNames.push_back(getTestDirectory() + "/getFilePaths1.cpp"); fileNames.push_back(getTestDirectory() + "/getFilePaths2.cpp"); fileNames.push_back(getTestDirectory() + "/getFilePaths3.cpp"); fileNames.push_back(getTestDirectory() + "/getFilePaths4.cpp"); for (size_t i = 0; i < fileNames.size(); i++) { console->standardizePath(fileNames[i]); createTestFile(fileNames[i], textIn); } } ~GetFilePathsF() { delete console; } }; TEST_F(GetFilePathsF, FilePaths1) // test fileName vector and getFilePaths with *.cpp { console->setIsQuiet(true); // change this to see results // call astyle processOptions() vector astyleOptionsVector; astyleOptionsVector.push_back(getTestDirectory() + "/*.cpp"); console->processOptions(astyleOptionsVector); // call astyle processFiles() console->processFiles(); // check the files found vector fileName = console->getFileName(); ASSERT_EQ(fileNames.size(), fileName.size()) << "Vector sizes not equal."; for (size_t i = 0; i < fileName.size(); i++) EXPECT_EQ(fileNames[i], fileName[i]); } TEST_F(GetFilePathsF, FilePaths2) // test fileName vector and getFilePaths with *.c?? { console->setIsQuiet(true); // change this to see results // call astyle processOptions() vector astyleOptionsVector; astyleOptionsVector.push_back(getTestDirectory() + "/*.c??"); console->processOptions(astyleOptionsVector); // call astyle processFiles() console->processFiles(); // check the files found vector fileName = console->getFileName(); ASSERT_EQ(fileNames.size(), fileName.size()) << "Vector sizes not equal."; for (size_t i = 0; i < fileName.size(); i++) EXPECT_EQ(fileNames[i], fileName[i]); } TEST_F(GetFilePathsF, FilePaths3) // test fileName vector and getFilePaths with getFilePaths*.cpp { console->setIsQuiet(true); // change this to see results // call astyle processOptions() vector astyleOptionsVector; astyleOptionsVector.push_back(getTestDirectory() + "/getFilePaths*.cpp"); console->processOptions(astyleOptionsVector); // call astyle processFiles() console->processFiles(); // check the files found vector fileName = console->getFileName(); ASSERT_EQ(fileNames.size(), fileName.size()) << "Vector sizes not equal."; for (size_t i = 0; i < fileName.size(); i++) EXPECT_EQ(fileNames[i], fileName[i]); } TEST_F(GetFilePathsF, FilePaths4) // test fileName vector and getFilePaths with *.c* // * at the end WITH remaining data allows complete coverage of wildcmp function { console->setIsQuiet(true); // change this to see results // call astyle processOptions() vector astyleOptionsVector; astyleOptionsVector.push_back(getTestDirectory() + "/*.c*"); console->processOptions(astyleOptionsVector); // call astyle processFiles() console->processFiles(); // check the files found vector fileName = console->getFileName(); ASSERT_EQ(fileNames.size(), fileName.size()) << "Vector sizes not equal."; for (size_t i = 0; i < fileName.size(); i++) EXPECT_EQ(fileNames[i], fileName[i]); } TEST_F(GetFilePathsF, FilePaths5) // test fileName vector and getFilePaths with *.cpp* // * at the end WITHOUT remaining data allows complete coverage of wildcmp function { console->setIsQuiet(true); // change this to see results // call astyle processOptions() vector astyleOptionsVector; astyleOptionsVector.push_back(getTestDirectory() + "/*.cpp*"); console->processOptions(astyleOptionsVector); // call astyle processFiles() console->processFiles(); // check the files found vector fileName = console->getFileName(); ASSERT_EQ(fileNames.size(), fileName.size()) << "Vector sizes not equal."; for (size_t i = 0; i < fileName.size(); i++) EXPECT_EQ(fileNames[i], fileName[i]); } TEST_F(GetFilePathsF, FilePathsError) // test fileName vector and getFilePaths with bad file path { console->setIsQuiet(true); // change this to see results // call astyle processOptions() vector astyleOptionsVector; astyleOptionsVector.push_back(getTestDirectory() + "/AStyleError*"); console->processOptions(astyleOptionsVector); // change special chars in filepath to '.' for windows regex comparison size_t i = 0; while (i < astyleOptionsVector.back().length()) { i = astyleOptionsVector.back().find_first_of("\\/*?", i); if (i == string::npos) break; astyleOptionsVector.back()[i] = '.'; ++i; } string regex = "No file to process " + astyleOptionsVector.back() + "\nDid you intend to use --recursive?"; // cannot use death test with leak finder #if GTEST_HAS_DEATH_TEST && !(LEAK_DETECTOR || LEAK_FINDER) // test processFiles with bad file path EXPECT_EXIT(console->processFiles(), ExitedWithCode(EXIT_FAILURE), regex); #endif } TEST_F(GetFilePathsF, FilePathsErrorRecursive) // test fileName vector and getFilePaths with bad file path using recursive option { console->setIsQuiet(true); // change this to see results console->setIsRecursive(true); // call astyle processOptions() vector astyleOptionsVector; astyleOptionsVector.push_back(getTestDirectory() + "/AStyleError*"); console->processOptions(astyleOptionsVector); // change special chars in filepath to '.' for windows regex comparison size_t i = 0; while (i < astyleOptionsVector.back().length()) { i = astyleOptionsVector.back().find_first_of("\\/*?", i); if (i == string::npos) break; astyleOptionsVector.back()[i] = '.'; ++i; } string regex = "No file to process " + astyleOptionsVector.back(); // cannot use death test with leak finder #if GTEST_HAS_DEATH_TEST && !(LEAK_DETECTOR || LEAK_FINDER) // test processFiles with bad file path EXPECT_EXIT(console->processFiles(), ExitedWithCode(EXIT_FAILURE), regex); #endif } TEST_F(GetFilePathsF, FilePathsErrorSansFilename) // test fileName vector and getFilePaths with no filename and no recursive option { console->setIsQuiet(true); // change this to see results vector astyleOptionsVector; astyleOptionsVector.push_back(getTestDirectory() + "/"); // no file console->processOptions(astyleOptionsVector); // change special chars in filepath to '.' for windows regex comparison size_t i = 0; while (i < astyleOptionsVector.back().length()) { i = astyleOptionsVector.back().find_first_of("\\/*?", i); if (i == string::npos) break; astyleOptionsVector.back()[i] = '.'; ++i; } string regex = "Missing filename in " + astyleOptionsVector.back(); // cannot use death test with leak finder #if GTEST_HAS_DEATH_TEST && !(LEAK_DETECTOR || LEAK_FINDER) // test processFiles with bad file path EXPECT_EXIT(console->processFiles(), ExitedWithCode(EXIT_FAILURE), regex); #endif } TEST_F(GetFilePathsF, FilePathsErrorRecursiveSansWildcard) // test fileName vector and getFilePaths with recursive option and no wildcard { console->setIsQuiet(true); // change this to see results console->setIsRecursive(true); vector astyleOptionsVector; astyleOptionsVector.push_back(getTestDirectory() + "/noWildcard.cpp"); console->processOptions(astyleOptionsVector); // change special chars in filepath to '.' for windows regex comparison size_t i = 0; while (i < astyleOptionsVector.back().length()) { i = astyleOptionsVector.back().find_first_of("\\/*?", i); if (i == string::npos) break; astyleOptionsVector.back()[i] = '.'; ++i; } string regex = "Recursive option with no wildcard\n"; #ifndef _WIN32 regex.append("Did you intend quote the filename?\n"); #endif // cannot use death test with leak finder #if GTEST_HAS_DEATH_TEST && !(LEAK_DETECTOR || LEAK_FINDER) // test processFiles with bad file path EXPECT_EXIT(console->processFiles(), ExitedWithCode(EXIT_FAILURE), regex); #endif } TEST_F(GetFilePathsF, FilePathsErrorInDirectoryName) // test fileName vector and getFilePaths with a non-existant directory { console->setIsQuiet(true); // change this to see results console->setIsRecursive(true); vector astyleOptionsVector; astyleOptionsVector.push_back(getTestDirectory() + "/errorInDirectoryName/*.cpp"); console->processOptions(astyleOptionsVector); // change special chars in filepath to '.' for windows regex comparison size_t i = 0; while (i < astyleOptionsVector.back().length()) { i = astyleOptionsVector.back().find_first_of("\\/*?", i); if (i == string::npos) break; astyleOptionsVector.back()[i] = '.'; ++i; } string regex = "Cannot open directory " + astyleOptionsVector.back(); regex = regex.substr(0, regex.length() - 6); // remove the wilscard // cannot use death test with leak finder #if GTEST_HAS_DEATH_TEST && !(LEAK_DETECTOR || LEAK_FINDER) // test processFiles with bad file path EXPECT_EXIT(console->processFiles(), ExitedWithCode(EXIT_FAILURE), regex); #endif } //---------------------------------------------------------------------------- // AStyle test getFileType() - C_TYPE, JAVA_TYPE, SHARP_TYPE //---------------------------------------------------------------------------- struct GetFileTypeF : public Test { ASFormatter formatter; ASConsole* console; vector fileNames; // build fileNames vector and write the output files GetFileTypeF() { char textIn[] = "\nvoid foo()\n" "{\n" " bar();\n" "}\n"; cleanTestDirectory(getTestDirectory()); console = new ASConsole(formatter); fileNames.push_back(getTestDirectory() + "/getFileType1.cpp"); fileNames.push_back(getTestDirectory() + "/getFileType2.java"); fileNames.push_back(getTestDirectory() + "/getFileType3.cs"); fileNames.push_back(getTestDirectory() + "/getFileType4.error"); for (size_t i = 0; i < fileNames.size(); i++) { console->standardizePath(fileNames[i]); createTestFile(fileNames[i], textIn); } } ~GetFileTypeF() { delete console; } }; TEST_F(GetFileTypeF, FileTypeC) // test getFileType with *.cpp { console->setIsQuiet(true); // change this to see results // call astyle processOptions() vector astyleOptionsVector; astyleOptionsVector.push_back(getTestDirectory() + "/*.cpp"); console->processOptions(astyleOptionsVector); // call astyle processFiles() console->processFiles(); // check the file type EXPECT_EQ(C_TYPE, formatter.getFileType()); } TEST_F(GetFileTypeF, FileTypeJava) // test getFileType with *.java { console->setIsQuiet(true); // change this to see results // call astyle processOptions() vector astyleOptionsVector; astyleOptionsVector.push_back(getTestDirectory() + "/*.java"); console->processOptions(astyleOptionsVector); // call astyle processFiles() console->processFiles(); // check the file type EXPECT_EQ(JAVA_TYPE, formatter.getFileType()); } TEST_F(GetFileTypeF, FileTypeSharp) // test getFileType with *.cs { console->setIsQuiet(true); // change this to see results // call astyle processOptions() vector astyleOptionsVector; astyleOptionsVector.push_back(getTestDirectory() + "/*.cs"); console->processOptions(astyleOptionsVector); // call astyle processFiles() console->processFiles(); // check the file type EXPECT_EQ(SHARP_TYPE, formatter.getFileType()); } TEST_F(GetFileTypeF, FileTypeError) // test getFileType with an invalid type, should return C_TYPE { console->setIsQuiet(true); // change this to see results // call astyle processOptions() vector astyleOptionsVector; astyleOptionsVector.push_back(getTestDirectory() + "/*.error"); console->processOptions(astyleOptionsVector); // call astyle processFiles() console->processFiles(); // check the file type EXPECT_EQ(C_TYPE, formatter.getFileType()); } //---------------------------------------------------------------------------- // AStyle Language Vectors //---------------------------------------------------------------------------- struct LanguageVectorsF : public Test { ASFormatter formatter; ASConsole* console; vector fileNames; // build fileNames vector and write the output files LanguageVectorsF() { char textIn[] = "\nvoid foo()\n" "{\n" " bar();\n" "}\n"; cleanTestDirectory(getTestDirectory()); console = new ASConsole(formatter); fileNames.push_back(getTestDirectory() + "/getFileType1.cpp"); fileNames.push_back(getTestDirectory() + "/getFileType2.java"); fileNames.push_back(getTestDirectory() + "/getFileType3.cs"); fileNames.push_back(getTestDirectory() + "/getFileType4.error"); for (size_t i = 0; i < fileNames.size(); i++) { console->standardizePath(fileNames[i]); createTestFile(fileNames[i], textIn); } } ~LanguageVectorsF() { delete console; } }; TEST_F(LanguageVectorsF, FileTypeC) // Test the language vector setting with *.cpp. { console->setIsQuiet(true); // change this to see results // verify initial setting EXPECT_EQ(9, formatter.getFormatterFileType()); EXPECT_EQ(9, formatter.getBeautifierFileType()); // test language vectors for C++ files vector astyleOptionsVector; astyleOptionsVector.push_back(getTestDirectory() + "/*.cpp"); console->processOptions(astyleOptionsVector); console->processFiles(); EXPECT_EQ(C_TYPE, formatter.getFormatterFileType()); EXPECT_EQ(C_TYPE, formatter.getBeautifierFileType()); } TEST_F(LanguageVectorsF, FileTypeJava) // Test the language vector setting with *.java. { console->setIsQuiet(true); // change this to see results // verify initial setting EXPECT_EQ(9, formatter.getFormatterFileType()); EXPECT_EQ(9, formatter.getBeautifierFileType()); // test language vectors for Java files vector astyleOptionsVector; astyleOptionsVector.push_back(getTestDirectory() + "/*.java"); console->processOptions(astyleOptionsVector); console->processFiles(); EXPECT_EQ(JAVA_TYPE, formatter.getFormatterFileType()); EXPECT_EQ(JAVA_TYPE, formatter.getBeautifierFileType()); } TEST_F(LanguageVectorsF, FileTypeSharp) // Test the language vector setting with *.cs. { console->setIsQuiet(true); // change this to see results // verify initial setting EXPECT_EQ(9, formatter.getFormatterFileType()); EXPECT_EQ(9, formatter.getBeautifierFileType()); // test language vectors for C# files vector astyleOptionsVector; astyleOptionsVector.push_back(getTestDirectory() + "/*.cs"); console->processOptions(astyleOptionsVector); console->processFiles(); EXPECT_EQ(SHARP_TYPE, formatter.getFormatterFileType()); EXPECT_EQ(SHARP_TYPE, formatter.getBeautifierFileType()); } TEST(LanguageVectors, MultipleObjects) // Static language vectors were removed in release 2.02 // to allow multiple ASFormatter objects. // This was requested by KDevelop to allow multiple objects // via the factory method. // This checks initialization of the previously static vectors. // Additional tests are done by the "GetFileTypeF" and // "LanguageVectorsF" tests. { // TODO fix this? // some compilers don't like the ASStreamIterator template #if !defined(__clang__) && !defined(__INTEL_COMPILER) && !defined(__APPLE__) ASFormatter formatter1; // Aborted here in Debug for static objects: // "Assertion `container == __null' failed." ASFormatter formatter2; ASFormatter formatter3; // verify initial value EXPECT_EQ(9, formatter1.getFormatterFileType()); EXPECT_EQ(9, formatter2.getFormatterFileType()); EXPECT_EQ(9, formatter3.getFormatterFileType()); EXPECT_EQ(9, formatter1.getBeautifierFileType()); EXPECT_EQ(9, formatter2.getBeautifierFileType()); EXPECT_EQ(9, formatter3.getBeautifierFileType()); // initialize formatter1 with C++ stringstream in; formatter1.setCStyle(); // NOTE: For some reason this will not compile // with gcc if speed optimizations are used??? // With intel use disable optimizations. ASStreamIterator streamIterator1(&in); formatter1.init(&streamIterator1); // initialize formatter2 with Java formatter2.setJavaStyle(); ASStreamIterator streamIterator2(&in); formatter2.init(&streamIterator2); // initialize formatter3 with C# formatter3.setSharpStyle(); ASStreamIterator streamIterator3(&in); formatter3.init(&streamIterator3); // check the file types EXPECT_EQ(C_TYPE, formatter1.getFormatterFileType()); EXPECT_EQ(C_TYPE, formatter1.getBeautifierFileType()); EXPECT_EQ(JAVA_TYPE, formatter2.getFormatterFileType()); EXPECT_EQ(JAVA_TYPE, formatter2.getBeautifierFileType()); EXPECT_EQ(SHARP_TYPE, formatter3.getFormatterFileType()); EXPECT_EQ(SHARP_TYPE, formatter3.getBeautifierFileType()); #endif } //---------------------------------------------------------------------------- // AStyle test recursive option - getFilePaths(), wildcmp(), and fileName vector //---------------------------------------------------------------------------- struct RecursiveF : public Test { ASFormatter formatter; ASConsole* console; vector fileNames; // build fileNames vector and write the output files RecursiveF() { char textIn[] = "\nvoid foo()\n" "{\n" "bar();\n" "}\n"; cleanTestDirectory(getTestDirectory()); console = new ASConsole(formatter); // create directories string sub1 = getTestDirectory() + "/subdir1"; string sub1a = getTestDirectory() + "/subdir1/subdir1a"; string sub1b = getTestDirectory() + "/subdir1/subdir1b"; string sub2 = getTestDirectory() + "/subdir2"; console->standardizePath(sub1); console->standardizePath(sub1a); console->standardizePath(sub1b); console->standardizePath(sub2); createTestDirectory(sub1); createTestDirectory(sub1a); createTestDirectory(sub1b); createTestDirectory(sub2); // create test files fileNames.push_back(getTestDirectory() + "/recursive1.cpp"); fileNames.push_back(getTestDirectory() + "/recursive2.cpp"); fileNames.push_back(sub1 + "/recursive3.cpp"); fileNames.push_back(sub1 + "/recursive4.cpp"); fileNames.push_back(sub1a + "/recursive5.cpp"); fileNames.push_back(sub1a + "/recursive6.cpp"); fileNames.push_back(sub1b + "/recursive7.cpp"); fileNames.push_back(sub1b + "/recursive8.cpp"); fileNames.push_back(sub2 + "/recursive9.cpp"); fileNames.push_back(sub2 + "/recursive10.cpp"); for (size_t i = 0; i < fileNames.size(); i++) { console->standardizePath(fileNames[i]); createTestFile(fileNames[i], textIn); } // sort file names for comparison sort(fileNames.begin(), fileNames.end()); } ~RecursiveF() { delete console; } }; TEST_F(RecursiveF, Default) // test recursive option { console->setIsQuiet(true); // change this to see results console->setIsRecursive(true); // call astyle processOptions() vector astyleOptionsVector; astyleOptionsVector.push_back(getTestDirectory() + "/*.cpp"); console->processOptions(astyleOptionsVector); // call astyle processFiles() console->processFiles(); // check the fileName vector vector fileName = console->getFileName(); ASSERT_EQ(fileNames.size(), fileName.size()); for (size_t i = 0; i < fileNames.size(); i++) EXPECT_EQ(fileNames[i], fileName[i]); } TEST_F(RecursiveF, Sans) // test *.cpp WITHOUT recursive { console->setIsQuiet(true); // change this to see results console->setIsRecursive(false); // call astyle processOptions() vector astyleOptionsVector; astyleOptionsVector.push_back(getTestDirectory() + "/*.cpp"); console->processOptions(astyleOptionsVector); // call astyle processFiles() console->processFiles(); // delete sub directory files from the fileName vector size_t searchStart = getTestDirectory().length() + 1; for (int i = 0; i < (int) fileNames.size(); i++) { if (fileNames[i].find_first_of("\\/", searchStart) != string::npos) { // cout << fileNames[i] << endl; vector::iterator iter = fileNames.begin() + i; fileNames.erase(iter); i--; continue; } } // check the files EXPECT_TRUE(fileNames.size() > 0); vector fileName = console->getFileName(); ASSERT_EQ(fileNames.size(), fileName.size()); for (size_t i = 0; i < fileNames.size(); i++) EXPECT_EQ(fileNames[i], fileName[i]); } TEST_F(RecursiveF, Exclude) // test recursive option with exclude { console->setIsQuiet(true); // change this to see results console->setIsRecursive(true); // call astyle processOptions() size_t filesExcluded = 0; vector astyleOptionsVector; // file astyleOptionsVector.push_back("--exclude=recursive1.cpp"); filesExcluded += 1; // directory astyleOptionsVector.push_back("--exclude=subdir1a"); filesExcluded += 2; // full path file astyleOptionsVector.push_back("--exclude=/subdir2/recursive9.cpp"); filesExcluded += 1; // full path directory astyleOptionsVector.push_back("--exclude=/subdir1/subdir1b"); filesExcluded += 2; astyleOptionsVector.push_back(getTestDirectory() + "/*.cpp"); console->processOptions(astyleOptionsVector); // call astyle processFiles() console->processFiles(); // verify excludes vector fileName = console->getFileName(); EXPECT_EQ(fileNames.size() - filesExcluded, fileName.size()); } TEST_F(RecursiveF, ExcludeErrors) // test recursive option with unmatched excludes { console->setIsQuiet(true); // change this to see results // call astyle processOptions() vector astyleOptionsVector; // partial match on file astyleOptionsVector.push_back("--exclude=ecursive1.cpp"); // partial match on directory astyleOptionsVector.push_back("--exclude=ubdir1a"); astyleOptionsVector.push_back(getTestDirectory() + "/*.cpp"); console->processOptions(astyleOptionsVector); // error message regular expression string regex = "Exclude .unmatched. ecursive1.cpp\n" "Exclude .unmatched. ubdir1a\n" "Did you intend to use --recursive"; // cannot use death test with leak finder #if GTEST_HAS_DEATH_TEST && !(LEAK_DETECTOR || LEAK_FINDER) // test processFiles with unmatched excludes EXPECT_EXIT(console->processFiles(), ExitedWithCode(EXIT_FAILURE), regex); #endif } TEST_F(RecursiveF, ExcludeErrorsRecursive) // test recursive option with unmatched excludes and recursive option { console->setIsQuiet(true); // change this to see results console->setIsRecursive(true); // call astyle processOptions() vector astyleOptionsVector; // partial match on file astyleOptionsVector.push_back("--exclude=ecursive1.cpp"); // partial match on directory astyleOptionsVector.push_back("--exclude=ubdir1a"); astyleOptionsVector.push_back(getTestDirectory() + "/*.cpp"); console->processOptions(astyleOptionsVector); // error message regular expression string regex = "Exclude .unmatched. ecursive1.cpp\n" "Exclude .unmatched. ubdir1a"; // cannot use death test with leak finder #if GTEST_HAS_DEATH_TEST && !(LEAK_DETECTOR || LEAK_FINDER) // test processFiles with unmatched excludes EXPECT_EXIT(console->processFiles(), ExitedWithCode(EXIT_FAILURE), regex); #endif } TEST_F(RecursiveF, HiddenFiles) // test recursive option with hidden files { console->setIsQuiet(true); // change this to see results console->setIsRecursive(true); // write the hidden files char textIn[] = "void foo(){}\n"; // hidden on Linux and Windows string dirOut1 = getTestDirectory() + "/.hidden"; console->standardizePath(dirOut1); createTestDirectory(dirOut1); string fileOut1 = getTestDirectory() + "/.hidden/hidden1.cpp"; console->standardizePath(fileOut1); createTestFile(fileOut1, textIn); string fileOut2 = getTestDirectory() + "/.hidden2.cpp"; console->standardizePath(fileOut2); createTestFile(fileOut2, textIn); // hidden on Windows only #ifdef _WIN32 string dirOut1w = getTestDirectory() + "/readonlywin"; console->standardizePath(dirOut1w); createTestDirectory(dirOut1w); SetFileAttributes(dirOut1w.c_str(), FILE_ATTRIBUTE_READONLY); string fileOut1w = getTestDirectory() + "/readonlywin/readonly1win.cpp"; console->standardizePath(fileOut1w); createTestFile(fileOut1w, textIn); string fileOut2w = getTestDirectory() + "/hidden2win.cpp"; console->standardizePath(fileOut2w); createTestFile(fileOut2w, textIn); SetFileAttributes(fileOut2w.c_str(), FILE_ATTRIBUTE_HIDDEN); string fileOut3w = getTestDirectory() + "/readonly2win.cpp"; console->standardizePath(fileOut3w); createTestFile(fileOut3w, textIn); SetFileAttributes(fileOut3w.c_str(), FILE_ATTRIBUTE_READONLY); #endif // call astyle processOptions() vector astyleOptionsVector; astyleOptionsVector.push_back(getTestDirectory() + "/*.cpp"); console->processOptions(astyleOptionsVector); // call astyle processFiles() console->processFiles(); // hidden files should not be in console vector vector fileName = console->getFileName(); EXPECT_EQ(fileNames.size(), fileName.size()); #ifdef _WIN32 // reset file attributes SetFileAttributes(dirOut1w.c_str(), FILE_ATTRIBUTE_NORMAL); SetFileAttributes(fileOut2w.c_str(), FILE_ATTRIBUTE_NORMAL); SetFileAttributes(fileOut3w.c_str(), FILE_ATTRIBUTE_NORMAL); #endif } //---------------------------------------------------------------------------- // AStyle test dry-run option - getFilePaths(), wildcmp(), and fileName vector //---------------------------------------------------------------------------- struct DryRunF : public Test { ASFormatter formatter; ASConsole* console; vector fileNames; // build fileNames vector and write the output files DryRunF() { char textIn[] = "\nvoid foo()\n" "{\n" " bar();\n" "}\n"; cleanTestDirectory(getTestDirectory()); console = new ASConsole(formatter); // create test files fileNames.push_back(getTestDirectory() + "/dry-run1.cpp"); fileNames.push_back(getTestDirectory() + "/dry-run2.cpp"); for (size_t i = 0; i < fileNames.size(); i++) { console->standardizePath(fileNames[i]); createTestFile(fileNames[i], textIn); } } ~DryRunF() { delete console; } }; TEST_F(DryRunF, DryRunTest) // Test dry-run option. // Backup files should NOT be created. { console->setIsQuiet(true); // change this to see results console->setIsDryRun(true); // set the formatter options vector astyleOptionsVector; astyleOptionsVector.push_back(getTestDirectory() + "/*.cpp"); astyleOptionsVector.push_back("--style=attach"); // process the file console->processOptions(astyleOptionsVector); console->processFiles(); // check that no backup files were created vector fileName = console->getFileName(); ASSERT_EQ(fileNames.size(), fileName.size()); for (size_t i = 0; i < fileNames.size(); i++) { EXPECT_EQ(fileNames[i], fileName[i]); // check for .orig file string origFileName = fileNames[i] + ".orig"; struct stat stBuf; // display error if file is present if (stat(origFileName.c_str(), &stBuf) != -1) EXPECT_STREQ("no .orig file", origFileName.c_str()); } } TEST_F(DryRunF, DryRunSans) // Test without dry-run option. // Backup files should be created. { console->setIsQuiet(true); // change this to see results // set the formatter options vector astyleOptionsVector; astyleOptionsVector.push_back(getTestDirectory() + "/*.cpp"); astyleOptionsVector.push_back("--style=attach"); // process the file console->processOptions(astyleOptionsVector); console->processFiles(); // check that no backup files were created vector fileName = console->getFileName(); ASSERT_EQ(fileNames.size(), fileName.size()); for (size_t i = 0; i < fileNames.size(); i++) { EXPECT_EQ(fileNames[i], fileName[i]); // check for .orig file string origFileName = fileNames[i] + ".orig"; struct stat stBuf; // display error if file is present if (stat(origFileName.c_str(), &stBuf) == -1) EXPECT_STREQ("expected an .orig file", origFileName.c_str()); } } //---------------------------------------------------------------------------- // AStyle line ends formatted // tests if a line end change formats the file //---------------------------------------------------------------------------- struct LineEndsFormattedF : public Test { ASFormatter formatter; ASConsole* console; vector fileNames; string textLinuxStr; string textWindowsStr; string textMacOldStr; const char* textLinux; const char* textWindows; const char* textMacOld; string pathLinux; string pathWindows; string pathMacOld; // build fileNames vector and write the output files LineEndsFormattedF() { textLinuxStr = // has macold line ends "\rvoid foo()\r" "{\r" " bar()\r" "}\r"; textWindowsStr = // has linux line ends "\nvoid foo()\n" "{\n" " bar()\n" "}\n"; textMacOldStr = // has windows line ends "\r\nvoid foo()\r\n" "{\r\n" " bar()\r\n" "}\r\n"; cleanTestDirectory(getTestDirectory()); console = new ASConsole(formatter); // build text strings textLinux = textLinuxStr.c_str(); textWindows = textWindowsStr.c_str(); textMacOld = textMacOldStr.c_str(); // create test files pathLinux = getTestDirectory() + "/textLinux.cpp"; console->standardizePath(pathLinux); createTestFile(pathLinux, textLinux); pathWindows = getTestDirectory() + "/textWindows.cpp"; console->standardizePath(pathWindows); createTestFile(pathWindows, textWindows); pathMacOld = getTestDirectory() + "/textMac.cpp"; console->standardizePath(pathMacOld); createTestFile(pathMacOld, textMacOld); } ~LineEndsFormattedF() { delete console; } }; TEST_F(LineEndsFormattedF, LineEndWindows) // test if lineend=windows formats the file { console->setIsQuiet(true); // change this to see results // call astyle processOptions() vector astyleOptionsVector; astyleOptionsVector.push_back("--lineend=windows"); astyleOptionsVector.push_back(pathWindows); console->processOptions(astyleOptionsVector); // call astyle processFiles() console->processFiles(); // check for .orig file string origFileName = pathWindows + ".orig"; struct stat stBuf; // display error if file is not present if (stat(origFileName.c_str(), &stBuf) == -1) EXPECT_STREQ("no .orig file", origFileName.c_str()); } TEST_F(LineEndsFormattedF, LineEndLinux) // test if lineend=linux formats the file { console->setIsQuiet(true); // change this to see results // call astyle processOptions() vector astyleOptionsVector; astyleOptionsVector.push_back("--lineend=linux"); astyleOptionsVector.push_back(pathLinux); console->processOptions(astyleOptionsVector); // call astyle processFiles() console->processFiles(); // check for .orig file string origFileName = pathLinux + ".orig"; struct stat stBuf; // display error if file is not present if (stat(origFileName.c_str(), &stBuf) == -1) EXPECT_STREQ("no .orig file", origFileName.c_str()); } TEST_F(LineEndsFormattedF, LineEndMacOld) // test if lineend=macold formats the file { console->setIsQuiet(true); // change this to see results // call astyle processOptions() vector astyleOptionsVector; astyleOptionsVector.push_back("--lineend=macold"); astyleOptionsVector.push_back(pathMacOld); console->processOptions(astyleOptionsVector); // call astyle processFiles() console->processFiles(); // check for .orig file string origFileName = pathMacOld + ".orig"; struct stat stBuf; // display error if file is not present if (stat(origFileName.c_str(), &stBuf) == -1) EXPECT_STREQ("no .orig file", origFileName.c_str()); } //---------------------------------------------------------------------------- // AStyle line ends unchanged // tests if an unchanged line end leaves the file unchanged //---------------------------------------------------------------------------- struct LineEndsUnchangedF : public Test { ASFormatter formatter; ASConsole* console; vector fileNames; string textLinuxStr; string textWindowsStr; string textMacOldStr; const char* textLinux; const char* textWindows; const char* textMacOld; string pathLinux; string pathWindows; string pathMacOld; // build fileNames vector and write the output files LineEndsUnchangedF() { textLinuxStr = // has linux line ends "\nvoid foo()\n" "{\n" " bar()\n" "}\n"; textWindowsStr = // has windows line ends "\r\nvoid foo()\r\n" "{\r\n" " bar()\r\n" "}\r\n"; textMacOldStr = // has macold line ends "\rvoid foo()\r" "{\r" " bar()\r" "}\r"; cleanTestDirectory(getTestDirectory()); console = new ASConsole(formatter); // build text strings textLinux = textLinuxStr.c_str(); textWindows = textWindowsStr.c_str(); textMacOld = textMacOldStr.c_str(); // create test files pathLinux = getTestDirectory() + "/textLinux.cpp"; console->standardizePath(pathLinux); createTestFile(pathLinux, textLinux); pathWindows = getTestDirectory() + "/textWindows.cpp"; console->standardizePath(pathWindows); createTestFile(pathWindows, textWindows); pathMacOld = getTestDirectory() + "/textMac.cpp"; console->standardizePath(pathMacOld); createTestFile(pathMacOld, textMacOld); } ~LineEndsUnchangedF() { delete console; } }; TEST_F(LineEndsUnchangedF, LineEndWindows) // test if lineend=windows leaves the file unchanged { console->setIsQuiet(true); // change this to see results // call astyle processOptions() vector astyleOptionsVector; astyleOptionsVector.push_back("--lineend=windows"); astyleOptionsVector.push_back(pathMacOld); console->processOptions(astyleOptionsVector); // call astyle processFiles() console->processFiles(); // check for .orig file string origFileName = pathWindows + ".orig"; struct stat stBuf; // display error if file is present if (stat(origFileName.c_str(), &stBuf) != -1) EXPECT_STREQ("no .orig file", origFileName.c_str()); } TEST_F(LineEndsUnchangedF, LineEndLinux) // test if lineend=linux leaves the file unchanged { console->setIsQuiet(true); // change this to see results // call astyle processOptions() vector astyleOptionsVector; astyleOptionsVector.push_back("--lineend=linux"); astyleOptionsVector.push_back(pathWindows); console->processOptions(astyleOptionsVector); // call astyle processFiles() console->processFiles(); // check for .orig file string origFileName = pathLinux + ".orig"; struct stat stBuf; // display error if file is present if (stat(origFileName.c_str(), &stBuf) != -1) EXPECT_STREQ("no .orig file", origFileName.c_str()); } TEST_F(LineEndsUnchangedF, LineEndMacOld) // test if lineend=macold leaves the file unchanged { console->setIsQuiet(true); // change this to see results // call astyle processOptions() vector astyleOptionsVector; astyleOptionsVector.push_back("--lineend=macold"); astyleOptionsVector.push_back(pathLinux); console->processOptions(astyleOptionsVector); // call astyle processFiles() console->processFiles(); // check for .orig file string origFileName = pathMacOld + ".orig"; struct stat stBuf; // display error if file is present if (stat(origFileName.c_str(), &stBuf) != -1) EXPECT_STREQ("no .orig file", origFileName.c_str()); } //---------------------------------------------------------------------------- // AStyle default line ends // tests if default line end leaves the file unchanged //---------------------------------------------------------------------------- struct LineEndsDefaultF : public Test { ASFormatter formatter; ASConsole* console; vector fileNames; string textLinuxStr; string textWindowsStr; string textMacOldStr; const char* textLinux; const char* textWindows; const char* textMacOld; string pathLinux; string pathWindows; string pathMacOld; // build fileNames vector and write the output files LineEndsDefaultF() { textLinuxStr = // has linux line ends "\nvoid foo()\n" "{\n" " bar()\n" "}\n"; textWindowsStr = // has windows line ends "\r\nvoid foo()\r\n" "{\r\n" " bar()\r\n" "}\r\n"; textMacOldStr = // has macold line ends "\rvoid foo()\r" "{\r" " bar()\r" "}\r"; cleanTestDirectory(getTestDirectory()); console = new ASConsole(formatter); // build text strings textLinux = textLinuxStr.c_str(); textWindows = textWindowsStr.c_str(); textMacOld = textMacOldStr.c_str(); // create test files pathLinux = getTestDirectory() + "/textLinux.cpp"; console->standardizePath(pathLinux); createTestFile(pathLinux, textLinux); pathWindows = getTestDirectory() + "/textWindows.cpp"; console->standardizePath(pathWindows); createTestFile(pathWindows, textWindows); pathMacOld = getTestDirectory() + "/textMac.cpp"; console->standardizePath(pathMacOld); createTestFile(pathMacOld, textMacOld); } ~LineEndsDefaultF() { delete console; } }; TEST_F(LineEndsDefaultF, LineEndWindows) // test if default line end leaves a windows file unchanged { console->setIsQuiet(true); // change this to see results // call astyle processOptions() vector astyleOptionsVector; astyleOptionsVector.push_back(pathWindows); console->processOptions(astyleOptionsVector); // call astyle processFiles() console->processFiles(); // check for .orig file string origFileName = pathWindows + ".orig"; struct stat stBuf; // display error if file is present if (stat(origFileName.c_str(), &stBuf) != -1) EXPECT_STREQ("no .orig file", origFileName.c_str()); } TEST_F(LineEndsDefaultF, LineEndLinux) // test if default line end leaves a linux file unchanged { console->setIsQuiet(true); // change this to see results // call astyle processOptions() vector astyleOptionsVector; astyleOptionsVector.push_back(pathLinux); console->processOptions(astyleOptionsVector); // call astyle processFiles() console->processFiles(); // check for .orig file string origFileName = pathLinux + ".orig"; struct stat stBuf; // display error if file is present if (stat(origFileName.c_str(), &stBuf) != -1) EXPECT_STREQ("no .orig file", origFileName.c_str()); } TEST_F(LineEndsDefaultF, LineEndMacOld) // test if default line end leaves a macold file unchanged { console->setIsQuiet(true); // change this to see results // call astyle processOptions() vector astyleOptionsVector; astyleOptionsVector.push_back(pathMacOld); console->processOptions(astyleOptionsVector); // call astyle processFiles() console->processFiles(); // check for .orig file string origFileName = pathMacOld + ".orig"; struct stat stBuf; // display error if file is present if (stat(origFileName.c_str(), &stBuf) != -1) EXPECT_STREQ("no .orig file", origFileName.c_str()); } //---------------------------------------------------------------------------- // AStyle line ends format // tests if default line ends calls the convertLineEnds() function when needed //---------------------------------------------------------------------------- struct LineEndsDefaultMixedF : public Test { ASFormatter formatter; ASConsole* console; vector fileNames; string textLinuxStr; string textWindowsStr; string textMacOldStr; const char* textLinux; const char* textWindows; const char* textMacOld; string pathLinux; string pathWindows; string pathMacOld; // build fileNames vector and write the output files LineEndsDefaultMixedF() { textLinuxStr = "\r\nvoid foo()\r\n" // not a linux line end "{\n" " bar1()\n" " bar2()\n" "}\n"; textWindowsStr = "\rvoid foo()\r" // not a windows line end "{\r\n" " bar1()\r\n" " bar2()\r\n" "}\r\n"; textMacOldStr = "\r\nvoid foo()\r\n" // not a macold line end "{\r" " bar1()\r" " bar2()\r" "}\r"; cleanTestDirectory(getTestDirectory()); console = new ASConsole(formatter); // build text strings textLinux = textLinuxStr.c_str(); textWindows = textWindowsStr.c_str(); textMacOld = textMacOldStr.c_str(); // create test files pathLinux = getTestDirectory() + "/textLinux.cpp"; console->standardizePath(pathLinux); createTestFile(pathLinux, textLinux); pathWindows = getTestDirectory() + "/textWindows.cpp"; console->standardizePath(pathWindows); createTestFile(pathWindows, textWindows); pathMacOld = getTestDirectory() + "/textMac.cpp"; console->standardizePath(pathMacOld); createTestFile(pathMacOld, textMacOld); } ~LineEndsDefaultMixedF() { delete console; } }; TEST_F(LineEndsDefaultMixedF, LineEndWindows) // test if default line ends outputs windows line ends by calling convertLineEnds() { console->setIsQuiet(true); // change this to see results // call astyle processOptions() vector astyleOptionsVector; astyleOptionsVector.push_back(pathWindows); console->processOptions(astyleOptionsVector); // call astyle processFiles() console->processFiles(); // check for .orig file string origFileName = pathWindows + ".orig"; struct stat stBuf; // display error if file is not present if (stat(origFileName.c_str(), &stBuf) == -1) EXPECT_STREQ("no .orig file", origFileName.c_str()); // check that convertLineEnds is called EXPECT_TRUE(console->getLineEndsMixed()); // the line ends must be checked manually // systemPause("Check Windows Line Ends"); } TEST_F(LineEndsDefaultMixedF, LineEndLinux) // test if default line ends outputs linux line ends by calling convertLineEnds() { console->setIsQuiet(true); // change this to see results // call astyle processOptions() vector astyleOptionsVector; astyleOptionsVector.push_back(pathLinux); console->processOptions(astyleOptionsVector); // call astyle processFiles() console->processFiles(); // check for .orig file string origFileName = pathLinux + ".orig"; struct stat stBuf; // display error if file is not present if (stat(origFileName.c_str(), &stBuf) == -1) EXPECT_STREQ("no .orig file", origFileName.c_str()); // check that convertLineEnds is called EXPECT_TRUE(console->getLineEndsMixed()); // the line ends must be checked manually // systemPause("Check Linux Line Ends"); } TEST_F(LineEndsDefaultMixedF, LineEndMacOld) // test if default line ends outputs linux line ends by calling convertLineEnds() { console->setIsQuiet(true); // change this to see results // call astyle processOptions() vector astyleOptionsVector; astyleOptionsVector.push_back(pathMacOld); console->processOptions(astyleOptionsVector); // call astyle processFiles() console->processFiles(); // check for .orig file string origFileName = pathMacOld + ".orig"; struct stat stBuf; // display error if file is not present if (stat(origFileName.c_str(), &stBuf) == -1) EXPECT_STREQ("no .orig file", origFileName.c_str()); // check that convertLineEnds is called EXPECT_TRUE(console->getLineEndsMixed()); // the line ends must be checked manually // systemPause("Check MacOld Line Ends"); } //---------------------------------------------------------------------------- // AStyle line ends formatted // tests that default line ends does NOT call the convertLineEnds() function when not needed //---------------------------------------------------------------------------- struct LineEndsDefaultMixedSansF : public Test { ASFormatter formatter; ASConsole* console; vector fileNames; string textLinuxStr; string textWindowsStr; string textMacOldStr; const char* textLinux; const char* textWindows; const char* textMacOld; string pathLinux; string pathWindows; string pathMacOld; // build fileNames vector and write the output files LineEndsDefaultMixedSansF() { textLinuxStr = "\nvoid foo()\n" "{\n" " bar()\r\n" // not a linux line end "}\n"; textWindowsStr = "\r\nvoid foo()\r\n" "{\r\n" " bar()\r" // not a windows line end "}\r\n"; textMacOldStr = "\rvoid foo()\r" "{\r" " bar()\r\n" // not a macold line end "}\r"; cleanTestDirectory(getTestDirectory()); console = new ASConsole(formatter); // build text strings textLinux = textLinuxStr.c_str(); textWindows = textWindowsStr.c_str(); textMacOld = textMacOldStr.c_str(); // create test files pathLinux = getTestDirectory() + "/textLinux.cpp"; console->standardizePath(pathLinux); createTestFile(pathLinux, textLinux); pathWindows = getTestDirectory() + "/textWindows.cpp"; console->standardizePath(pathWindows); createTestFile(pathWindows, textWindows); pathMacOld = getTestDirectory() + "/textMac.cpp"; console->standardizePath(pathMacOld); createTestFile(pathMacOld, textMacOld); } ~LineEndsDefaultMixedSansF() { delete console; } }; TEST_F(LineEndsDefaultMixedSansF, LineEndWindows) // test if default line ends outputs windows line ends without calling convertLineEnds() { console->setIsQuiet(true); // change this to see results // call astyle processOptions() vector astyleOptionsVector; astyleOptionsVector.push_back(pathWindows); console->processOptions(astyleOptionsVector); // call astyle processFiles() console->processFiles(); // check for .orig file string origFileName = pathWindows + ".orig"; struct stat stBuf; // display error if file is not present if (stat(origFileName.c_str(), &stBuf) == -1) EXPECT_STREQ("no .orig file", origFileName.c_str()); // check that convertLineEnds is NOT called EXPECT_FALSE(console->getLineEndsMixed()); // the line ends must be checked manually // systemPause("Check Windows Line Ends"); } TEST_F(LineEndsDefaultMixedSansF, LineEndLinux) // test if default line ends outputs linux line ends without calling convertLineEnds() { console->setIsQuiet(true); // change this to see results // call astyle processOptions() vector astyleOptionsVector; astyleOptionsVector.push_back(pathLinux); console->processOptions(astyleOptionsVector); // call astyle processFiles() console->processFiles(); // check for .orig file string origFileName = pathLinux + ".orig"; struct stat stBuf; // display error if file is not present if (stat(origFileName.c_str(), &stBuf) == -1) EXPECT_STREQ("no .orig file", origFileName.c_str()); // check that convertLineEnds is NOT called EXPECT_FALSE(console->getLineEndsMixed()); // the line ends must be checked manually // systemPause("Check Linux Line Ends"); } TEST_F(LineEndsDefaultMixedSansF, LineEndMacOld) // test if default line ends outputs linux line ends without calling convertLineEnds() { console->setIsQuiet(true); // change this to see results // call astyle processOptions() vector astyleOptionsVector; astyleOptionsVector.push_back(pathMacOld); console->processOptions(astyleOptionsVector); // call astyle processFiles() console->processFiles(); // check for .orig file string origFileName = pathMacOld + ".orig"; struct stat stBuf; // display error if file is not present if (stat(origFileName.c_str(), &stBuf) == -1) EXPECT_STREQ("no .orig file", origFileName.c_str()); // check that convertLineEnds is NOT called EXPECT_FALSE(console->getLineEndsMixed()); // the line ends must be checked manually // systemPause("Check MacOld Line Ends"); } //---------------------------------------------------------------------------- } // namespace //---------------------------------------------------------------------------- // TODO: test waitForRemove function - line 1925 abhishekbalu/abhishek-imageprocessingobjects.cpp #include "objects.h" #include CvSize *myfontSize; int baseline; bool uav::isFound(){ return found; } void uav::setXY(int src_x,int src_y){ lastX=posX; lastY=posY; posX=src_x; posY=src_y; dx=posX-lastX; dy=posY-lastY; distance=sqrt(dx*dx+dy*dy); if(pHit==0.00||pMiss==0.00){ pHit=0.5; pMiss=0.5; } if(distance<=thresh_hit_distance){ pHit=pHit*0.8; pMiss=pMiss*0.1; sum=pHit+pMiss; pHit/=sum; pMiss/=sum; } else { pHit=pHit*0.1; pMiss=pMiss*0.8; sum=pHit+pMiss; pHit/=sum; pMiss/=sum; } // qDebug()<<"pHit: "<10){ qDebug()<0.5){ if(uavColor=="yellow"){ found=true; sprintf(coordinates_yellow,"YELLOW|X=%d|Y=%d",posX,posY); //sprintf(coordinates_yellow,"Yellow has just been found and"); cvGetTextSize(coordinates_yellow,&myfont,myfontSize,&baseline); cvRectangle(*frame_resized,cvPoint(posX+5,posY+3),cvPoint(posX+125,posY-8),CV_RGB(0,0,0),CV_FILLED); cvPutText(*frame_resized,coordinates_yellow,cvPoint(posX+5,posY),&myfont,CV_RGB(255,255,255)); cvCircle(*frame_resized,cvPoint(posX,posY),4,CV_RGB(255,255,0),2); } if(uavColor=="red"){ sprintf(coordinates_red,"RED|X=%d|Y=%d",posX,posY); cvGetTextSize(coordinates_red,&myfont,myfontSize,&baseline); cvRectangle(*frame_resized,cvPoint(posX+5,posY+3),cvPoint(posX+105,posY-8),CV_RGB(0,0,0),CV_FILLED); cvPutText(*frame_resized,coordinates_red,cvPoint(posX+5,posY),&myfont,CV_RGB(255,255,255)); cvCircle(*frame_resized,cvPoint(posX,posY),4,CV_RGB(255,0,0),2); } if(uavColor=="green"){ sprintf(coordinates_green,"GREEN|X=%d|Y=%d",posX,posY); cvGetTextSize(coordinates_green,&myfont,myfontSize,&baseline); cvRectangle(*frame_resized,cvPoint(posX+5,posY+3),cvPoint(posX+124,posY-8),CV_RGB(0,0,0),CV_FILLED); cvPutText(*frame_resized,coordinates_green,cvPoint(posX+5,posY),&myfont,CV_RGB(255,255,255)); cvCircle(*frame_resized,cvPoint(posX,posY),4,CV_RGB(0,255,0),2); } } } else found=false; free(moments); } IplImage* uav::GetThresholdedImage(IplImage* imageHSV){ cvInRangeS(imageHSV,cvScalar(lowerH,lowerS,lowerV),cvScalar(upperH,upperS,upperV),imgThresh); return imgThresh; } void uav::getThreshLUV(IplImage* src,IplImage* dest){ // adaptiveThreshold(src,dest,255,CV_ADAPTIVE_THRESH_GAUSSIAN_C,CV_THRESH_BINARY,13,0); } void uav::FC_FindBiggestContours(IplImage *src) { _mask=0; nContours=0; largest_length=0; len=0; dst=0; contours=0; c=0; newC=0; CvMemStorage* tempStorage = cvCreateMemStorage(); temp=*src; IplImage *src_img=cvCreateImage(cvSize(temp.width,temp.height),IPL_DEPTH_32S,1); // IplImage *dest=cvCreateImage(cvSize(temp.width,temp.height),IPL_DEPTH_8U,1); _mask=&temp; int poly1Hull0=1; CvPoint offset; offset.x=0; offset.y=0; mask = cvGetMat( _mask, &mstub ); // clean up raw mask cvMorphologyEx( mask, mask, 0, 0, CV_MOP_OPEN, 1 ); cvMorphologyEx( mask, mask, 0, 0, CV_MOP_CLOSE, 1 ); // find contours around only bigger regions scanner = cvStartFindContours( mask, tempStorage, sizeof(CvContour), CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE, offset ); while( (c = cvFindNextContour( scanner )) != 0 ) { len = cvContourPerimeter( c ); if(len > largest_length) { largest_length = len; } } contours=cvEndFindContours( &scanner ); scanner = cvStartFindContours( mask, tempStorage, sizeof(CvContour), CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE, offset ); while( (c = cvFindNextContour( scanner )) != 0 ) { len = cvContourPerimeter( c ); double q = largest_length ; if( len < q ) //Get rid of blob if it's perimeter is too small cvSubstituteContour( scanner, 0 ); else //Smooth it's edges if it's large enough { if( poly1Hull0 ) //Polygonal approximation of the segmentation newC = cvApproxPoly( c, sizeof(CvContour), tempStorage, CV_POLY_APPROX_DP, 2, 0 ); else //Convex Hull of the segmentation newC = cvConvexHull2( c, tempStorage, CV_CLOCKWISE, 1 ); cvSubstituteContour( scanner, newC ); nContours++; R=cvBoundingRect(c,0); } } contours = cvEndFindContours( &scanner ); // paint the found regions back into the image cvZero( src_img ); cvZero( _mask ); for( c=contours; c != 0; c = c->h_next ) { cvDrawContours( src_img, c, cvScalarAll(1), cvScalarAll(1), -1, -1, 8, cvPoint(-offset.x,-offset.y)); } cvReleaseMemStorage( &tempStorage ); // convert to 8 bit IplImage for( int i = 0; i < src_img->height; i++ ) for( int j = 0; j < src_img->width; j++ ) { int idx = CV_IMAGE_ELEM( src_img, int, i, j ); //get reference to pixel at (col,row), dst = &CV_IMAGE_ELEM( src, uchar, i, j ); //for multi-channel images (col) should be multiplied by number of channels */ if( idx == -1 || idx == 1 ) *dst = (uchar)255; else if( idx <= 0 || idx > 1 ) *dst = (uchar)0; // should not get here else { *dst = (uchar)0; } } //qDebug()< #include #include #include #include namespace iv { //------------------------- iterators -------------------------------- template< class T > struct reversed { public: reversed( T & cont ) : cont( cont ){} typename T::reverse_iterator begin(){ return this->cont.rbegin(); } typename T::reverse_iterator end(){ return this->cont.rend(); } private: T & cont; }; ///** // std::unordered_map< int, Item * > m; // Item * item = at_or( m, 13, nullptr ); // if( item ) // { // ... // } //*/ //template< class Key, class T, class Hash, class KeyEqual, class Allocator > //T const & at_or( std::unordered_map< Key, T, Hash, KeyEqual, Allocator > const & cont, Key const & key, T const & def ) //{ // auto it = cont.find( key ); // if( it == cont.end() ) // return def; // else // return it->second; //} //----------------- utf8 ----------------------------------- size_t utf8_size( const char * ); size_t utf8_size( std::string const & ); bool utf8_is_first_byte( char ); ///< If char is a last byte in an utf8 character. //------------------ string -------------------------------- void string_explode( std::string const & s, char delim, std::vector< std::string > & result ); std::string string_trim( std::string const & s ); std::string string_ltrim( std::string const & s ); std::string string_rtrim( std::string const & s ); } alexandrerodrigopinheiro/gorilla2d #include "../../includes/math/point2d.h" // LIC// ==================================================================== // LIC// This file forms part of oomph-lib, the object-oriented, // LIC// multi-physics finite-element library, available // LIC// at http://www.oomph-lib.org. // LIC// // LIC// Copyright (C) 2006-2021 and // LIC// // LIC// This library is free software; you can redistribute it and/or // LIC// modify it under the terms of the GNU Lesser General Public // LIC// License as published by the Free Software Foundation; either // LIC// version 2.1 of the License, or (at your option) any later version. // LIC// // LIC// This library is distributed in the hope that it will be useful, // LIC// but WITHOUT ANY WARRANTY; without even the implied warranty of // LIC// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // LIC// Lesser General Public License for more details. // LIC// // LIC// You should have received a copy of the GNU Lesser General Public // LIC// License along with this library; if not, write to the Free Software // LIC// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA // LIC// 02110-1301 USA. // LIC// // LIC// The authors may be contacted at . // LIC// // LIC//==================================================================== #include "poroelasticity_elements.h" namespace oomph { /// Static default value for timescale ratio (1.0 -- for natural scaling) template double PoroelasticityEquations::Default_lambda_sq_value = 1.0; /// Static default value for the density ratio template double PoroelasticityEquations::Default_density_ratio_value = 1.0; /// Static default value for 1/k template double PoroelasticityEquations::Default_k_inv_value = 1.0; /// Static default value for alpha template double PoroelasticityEquations::Default_alpha_value = 1.0; /// Static default value for the porosity template double PoroelasticityEquations::Default_porosity_value = 1.0; //====================================================================== /// Compute the strain tensor at local coordinate s //====================================================================== template void PoroelasticityEquations::get_strain( const Vector& s, DenseMatrix& strain) const { #ifdef PARANOID if ((strain.ncol() != DIM) || (strain.nrow() != DIM)) { std::ostringstream error_message; error_message << "Strain matrix is " << strain.ncol() << " x " << strain.nrow() << ", but dimension of the equations is " << DIM << std::endl; throw OomphLibError( error_message.str(), OOMPH_CURRENT_FUNCTION, OOMPH_EXCEPTION_LOCATION); } /* //Find out how many position types there are unsigned n_position_type = this->nnodal_position_type(); if(n_position_type != 1) { throw OomphLibError( "PoroElasticity is not yet implemented for more than one position type", OOMPH_CURRENT_FUNCTION, OOMPH_EXCEPTION_LOCATION); } */ #endif // Find out how many nodes there are in the element unsigned n_node = nnode(); // Find the indices at which the local velocities are stored unsigned u_nodal_index[DIM]; for (unsigned i = 0; i < DIM; i++) { u_nodal_index[i] = u_index(i); } // Set up memory for the shape and derivative functions Shape psi(n_node); DShape dpsidx(n_node, DIM); // Call the derivatives of the shape functions (void)dshape_eulerian(s, psi, dpsidx); // Calculate interpolated values of the derivative of global position DenseMatrix interpolated_dudx(DIM, DIM, 0.0); // Loop over nodes for (unsigned l = 0; l < n_node; l++) { // Loop over velocity components for (unsigned i = 0; i < DIM; i++) { // Get the nodal value const double u_value = this->nodal_value(l, u_nodal_index[i]); // Loop over derivative directions for (unsigned j = 0; j < DIM; j++) { interpolated_dudx(i, j) += u_value * dpsidx(l, j); } } } /// Now fill in the entries of the strain tensor for (unsigned i = 0; i < DIM; i++) { // Do upper half of matrix // Note that j must be signed here for the comparison test to work // Also i must be cast to an int for (int j = (DIM - 1); j >= static_cast(i); j--) { // Off diagonal terms if (static_cast(i) != j) { strain(i, j) = 0.5 * (interpolated_dudx(i, j) + interpolated_dudx(j, i)); } // Diagonal terms will including growth factor when it comes back in else { strain(i, i) = interpolated_dudx(i, i); } } // Matrix is symmetric so just copy lower half for (int j = (i - 1); j >= 0; j--) { strain(i, j) = strain(j, i); } } } //====================================================================== /// Compute the Cauchy stress tensor at local coordinate s for /// displacement formulation. //====================================================================== template void PoroelasticityEquations::get_stress( const Vector& s, DenseMatrix& stress) const { #ifdef PARANOID if ((stress.ncol() != DIM) || (stress.nrow() != DIM)) { std::ostringstream error_message; error_message << "Stress matrix is " << stress.ncol() << " x " << stress.nrow() << ", but dimension of the equations is " << DIM << std::endl; throw OomphLibError( error_message.str(), OOMPH_CURRENT_FUNCTION, OOMPH_EXCEPTION_LOCATION); } #endif // Get strain DenseMatrix strain(DIM, DIM); this->get_strain(s, strain); // Now fill in the entries of the stress tensor without exploiting // symmetry -- sorry too lazy. This fct is only used for // postprocessing anyway... for (unsigned i = 0; i < DIM; i++) { for (unsigned j = 0; j < DIM; j++) { stress(i, j) = 0.0; for (unsigned k = 0; k < DIM; k++) { for (unsigned l = 0; k < DIM; k++) { stress(i, j) += this->E(i, j, k, l) * strain(k, l); } } } } } /// Performs a div-conserving transformation of the vector basis /// functions from the reference element to the actual element template double PoroelasticityEquations::transform_basis( const Vector& s, const Shape& q_basis_local, Shape& psi, DShape& dpsi, Shape& q_basis) const { // Call the (geometric) shape functions and their derivatives //(void)this->dshape_eulerian(s,psi,dpsi); this->dshape_local(s, psi, dpsi); // Storage for the (geometric) jacobian and its inverse DenseMatrix jacobian(DIM), inverse_jacobian(DIM); // Get the jacobian of the geometric mapping and its determinant double det = local_to_eulerian_mapping(dpsi, jacobian, inverse_jacobian); // Transform the derivative of the geometric basis so that it's w.r.t. // global coordinates this->transform_derivatives(inverse_jacobian, dpsi); // Get the number of computational basis vectors const unsigned n_q_basis = this->nq_basis(); // Loop over the basis vectors for (unsigned l = 0; l < n_q_basis; l++) { // Loop over the spatial components for (unsigned i = 0; i < DIM; i++) { // Zero the basis q_basis(l, i) = 0.0; } } // Loop over the spatial components for (unsigned i = 0; i < DIM; i++) { // And again for (unsigned j = 0; j < DIM; j++) { // Get the element of the jacobian (must transpose it due to different // conventions) and divide by the determinant double jac_trans = jacobian(j, i) / det; // Loop over the computational basis vectors for (unsigned l = 0; l < n_q_basis; l++) { // Apply the appropriate div-conserving mapping q_basis(l, i) += jac_trans * q_basis_local(l, j); } } } // Scale the basis by the ratio of the length of the edge to the length of // the corresponding edge on the reference element scale_basis(q_basis); return det; } /// Output FE representation of soln: x,y,u1,u2,q1,q2,div_q,p at /// Nplot^DIM plot points template void PoroelasticityEquations::output(std::ostream& outfile, const unsigned& nplot) { // Vector of local coordinates Vector s(DIM); // Tecplot header info outfile << tecplot_zone_string(nplot); // Loop over plot points unsigned num_plot_points = nplot_points(nplot); for (unsigned iplot = 0; iplot < num_plot_points; iplot++) { // Get local coordinates of plot point get_s_plot(iplot, nplot, s); // Output the components of the position for (unsigned i = 0; i < DIM; i++) { outfile << interpolated_x(s, i) << " "; } // Output the components of the FE representation of u at s for (unsigned i = 0; i < DIM; i++) { outfile << interpolated_u(s, i) << " "; } // Output the components of the FE representation of q at s for (unsigned i = 0; i < DIM; i++) { outfile << interpolated_q(s, i) << " "; } // Output FE representation of div u at s outfile << interpolated_div_q(s) << " "; // Output FE representation of p at s outfile << interpolated_p(s) << " "; const unsigned n_node = this->nnode(); Shape psi(n_node); shape(s, psi); Vector interpolated_du_dt(DIM, 0.0); for (unsigned i = 0; i < DIM; i++) { for (unsigned l = 0; l < n_node; l++) { interpolated_du_dt[i] += du_dt(l, i) * psi(l); } outfile << interpolated_du_dt[i] << " "; } Vector interpolated_d2u_dt2(DIM, 0.0); for (unsigned i = 0; i < DIM; i++) { for (unsigned l = 0; l < n_node; l++) { interpolated_d2u_dt2[i] += d2u_dt2(l, i) * psi(l); } outfile << interpolated_d2u_dt2[i] << " "; } const unsigned n_q_basis = this->nq_basis(); const unsigned n_q_basis_edge = this->nq_basis_edge(); Shape q_basis(n_q_basis, DIM), q_basis_local(n_q_basis, DIM); this->get_q_basis_local(s, q_basis_local); (void)this->transform_basis(s, q_basis_local, psi, q_basis); Vector interpolated_dq_dt(DIM, 0.0); for (unsigned i = 0; i < DIM; i++) { for (unsigned l = 0; l < n_q_basis_edge; l++) { interpolated_dq_dt[i] += dq_edge_dt(l) * q_basis(l, i); } for (unsigned l = n_q_basis_edge; l < n_q_basis; l++) { interpolated_dq_dt[i] += dq_internal_dt(l - n_q_basis_edge) * q_basis(l, i); } outfile << interpolated_dq_dt[i] << " "; } outfile << std::endl; } // Write tecplot footer (e.g. FE connectivity lists) this->write_tecplot_zone_footer(outfile, nplot); } /// Output FE representation of exact soln: x,y,u1,u2,q1,q2,div_q,p at /// Nplot^DIM plot points template void PoroelasticityEquations::output_fct( std::ostream& outfile, const unsigned& nplot, FiniteElement::SteadyExactSolutionFctPt exact_soln_pt) { // Vector of local coordinates Vector s(DIM); // Vector for coordintes Vector x(DIM); // Tecplot header info outfile << this->tecplot_zone_string(nplot); // Exact solution Vector Vector exact_soln(2 * DIM + 2); // Loop over plot points unsigned num_plot_points = this->nplot_points(nplot); for (unsigned iplot = 0; iplot < num_plot_points; iplot++) { // Get local coordinates of plot point this->get_s_plot(iplot, nplot, s); // Get x position as Vector this->interpolated_x(s, x); // Get exact solution at this point (*exact_soln_pt)(x, exact_soln); // Output x,y,q_exact,p_exact,div_q_exact for (unsigned i = 0; i < DIM; i++) { outfile << x[i] << " "; } for (unsigned i = 0; i < 2 * DIM + 2; i++) { outfile << exact_soln[i] << " "; } outfile << std::endl; } // Write tecplot footer (e.g. FE connectivity lists) this->write_tecplot_zone_footer(outfile, nplot); } /// Output FE representation of exact soln: x,y,u1,u2,div_q,p at /// Nplot^DIM plot points. Unsteady version template void PoroelasticityEquations::output_fct( std::ostream& outfile, const unsigned& nplot, const double& time, FiniteElement::UnsteadyExactSolutionFctPt exact_soln_pt) { // Vector of local coordinates Vector s(DIM); // Vector for coordintes Vector x(DIM); // Tecplot header info outfile << this->tecplot_zone_string(nplot); // Exact solution Vector Vector exact_soln(2 * DIM + 2); // Loop over plot points unsigned num_plot_points = this->nplot_points(nplot); for (unsigned iplot = 0; iplot < num_plot_points; iplot++) { // Get local coordinates of plot point this->get_s_plot(iplot, nplot, s); // Get x position as Vector this->interpolated_x(s, x); // Get exact solution at this point (*exact_soln_pt)(time, x, exact_soln); // Output x,y,q_exact,p_exact,div_q_exact for (unsigned i = 0; i < DIM; i++) { outfile << x[i] << " "; } for (unsigned i = 0; i < 2 * DIM + 2; i++) { outfile << exact_soln[i] << " "; } outfile << std::endl; } // Write tecplot footer (e.g. FE connectivity lists) this->write_tecplot_zone_footer(outfile, nplot); } /// Compute the error between the FE solution and the exact solution /// using the H(div) norm for q and L^2 norm for u and p template void PoroelasticityEquations::compute_error( std::ostream& outfile, FiniteElement::SteadyExactSolutionFctPt exact_soln_pt, Vector& error, Vector& norm) { for (unsigned i = 0; i < 3; i++) { error[i] = 0.0; norm[i] = 0.0; } // Vector of local coordinates Vector s(DIM); // Vector for coordinates Vector x(DIM); // Set the value of n_intpt unsigned n_intpt = this->integral_pt()->nweight(); outfile << "ZONE" << std::endl; // Exact solution Vector (u,v,[w]) Vector exact_soln(2 * DIM + 2); // Loop over the integration points for (unsigned ipt = 0; ipt < n_intpt; ipt++) { // Assign values of s for (unsigned i = 0; i < DIM; i++) { s[i] = this->integral_pt()->knot(ipt, i); } // Get the integral weight double w = this->integral_pt()->weight(ipt); // Get jacobian of mapping double J = this->J_eulerian(s); // Premultiply the weights and the Jacobian double W = w * J; // Get x position as Vector this->interpolated_x(s, x); // Get exact solution at this point (*exact_soln_pt)(x, exact_soln); // Displacement error for (unsigned i = 0; i < DIM; i++) { norm[0] += exact_soln[i] * exact_soln[i] * W; // Error due to q_i error[0] += (exact_soln[i] - this->interpolated_u(s, i)) * (exact_soln[i] - this->interpolated_u(s, i)) * W; } // Flux error for (unsigned i = 0; i < DIM; i++) { norm[1] += exact_soln[DIM + i] * exact_soln[DIM + i] * W; // Error due to q_i error[1] += (exact_soln[DIM + i] - this->interpolated_q(s, i)) * (exact_soln[DIM + i] - this->interpolated_q(s, i)) * W; } // Flux divergence error norm[1] += exact_soln[2 * DIM] * exact_soln[2 * DIM] * W; error[1] += (exact_soln[2 * DIM] - interpolated_div_q(s)) * (exact_soln[2 * DIM] - interpolated_div_q(s)) * W; // Pressure error norm[2] += exact_soln[2 * DIM + 1] * exact_soln[2 * DIM + 1] * W; error[2] += (exact_soln[2 * DIM + 1] - this->interpolated_p(s)) * (exact_soln[2 * DIM + 1] - this->interpolated_p(s)) * W; // Output x,y,[z] for (unsigned i = 0; i < DIM; i++) { outfile << x[i] << " "; } // Output u_1_error,u_2_error,... for (unsigned i = 0; i < DIM; i++) { outfile << exact_soln[i] - this->interpolated_u(s, i) << " "; } // Output q_1_error,q_2_error,... for (unsigned i = 0; i < DIM; i++) { outfile << exact_soln[DIM + i] - this->interpolated_q(s, i) << " "; } // Output p_error outfile << exact_soln[2 * DIM + 1] - this->interpolated_p(s) << " "; outfile << std::endl; } } /// Compute the error between the FE solution and the exact solution /// using the H(div) norm for u and L^2 norm for p. Unsteady version template void PoroelasticityEquations::compute_error( std::ostream& outfile, FiniteElement::UnsteadyExactSolutionFctPt exact_soln_pt, const double& time, Vector& error, Vector& norm) { for (unsigned i = 0; i < 3; i++) { error[i] = 0.0; norm[i] = 0.0; } // Vector of local coordinates Vector s(DIM); // Vector for coordinates Vector x(DIM); // Set the value of n_intpt unsigned n_intpt = this->integral_pt()->nweight(); outfile << "ZONE" << std::endl; // Exact solution Vector (u,v,[w]) Vector exact_soln(2 * DIM + 2); // Loop over the integration points for (unsigned ipt = 0; ipt < n_intpt; ipt++) { // Assign values of s for (unsigned i = 0; i < DIM; i++) { s[i] = this->integral_pt()->knot(ipt, i); } // Get the integral weight double w = this->integral_pt()->weight(ipt); // Get jacobian of mapping double J = this->J_eulerian(s); // Premultiply the weights and the Jacobian double W = w * J; // Get x position as Vector this->interpolated_x(s, x); // Get exact solution at this point (*exact_soln_pt)(time, x, exact_soln); // Displacement error for (unsigned i = 0; i < DIM; i++) { norm[0] += exact_soln[i] * exact_soln[i] * W; // Error due to q_i error[0] += (exact_soln[i] - this->interpolated_u(s, i)) * (exact_soln[i] - this->interpolated_u(s, i)) * W; } // Flux error for (unsigned i = 0; i < DIM; i++) { norm[1] += exact_soln[DIM + i] * exact_soln[DIM + i] * W; // Error due to q_i error[1] += (exact_soln[DIM + i] - this->interpolated_q(s, i)) * (exact_soln[DIM + i] - this->interpolated_q(s, i)) * W; } // Flux divergence error norm[1] += exact_soln[2 * DIM] * exact_soln[2 * DIM] * W; error[1] += (exact_soln[2 * DIM] - interpolated_div_q(s)) * (exact_soln[2 * DIM] - interpolated_div_q(s)) * W; // Pressure error norm[2] += exact_soln[2 * DIM + 1] * exact_soln[2 * DIM + 1] * W; error[2] += (exact_soln[2 * DIM + 1] - this->interpolated_p(s)) * (exact_soln[2 * DIM + 1] - this->interpolated_p(s)) * W; // Output x,y,[z] for (unsigned i = 0; i < DIM; i++) { outfile << x[i] << " "; } // Output u_1_error,u_2_error,... for (unsigned i = 0; i < DIM; i++) { outfile << exact_soln[i] - this->interpolated_u(s, i) << " "; } // Output q_1_error,q_2_error,... for (unsigned i = 0; i < DIM; i++) { outfile << exact_soln[DIM + i] - this->interpolated_q(s, i) << " "; } // Output p_error outfile << exact_soln[2 * DIM + 1] - this->interpolated_p(s) << " "; outfile << std::endl; } } /// Fill in residuals and, if flag==true, jacobian template void PoroelasticityEquations::fill_in_generic_residual_contribution( Vector& residuals, DenseMatrix& jacobian, bool flag) { // Get the number of geometric nodes, total number of basis functions, // and number of edges basis functions const unsigned n_node = nnode(); const unsigned n_q_basis = nq_basis(); const unsigned n_q_basis_edge = nq_basis_edge(); const unsigned n_p_basis = np_basis(); // Storage for the geometric and computational bases and the test functions Shape psi(n_node), u_basis(n_node), u_test(n_node), q_basis(n_q_basis, DIM), q_test(n_q_basis, DIM), p_basis(n_p_basis), p_test(n_p_basis), div_q_basis_ds(n_q_basis), div_q_test_ds(n_q_basis); DShape dpsidx(n_node, DIM), du_basis_dx(n_node, DIM), du_test_dx(n_node, DIM); // Get the number of integration points unsigned n_intpt = integral_pt()->nweight(); // Storage for the local coordinates Vector s(DIM); // Storage for the elasticity source function Vector f_solid(DIM); // Storage for the source function Vector f_fluid(DIM); // Storage for the mass source function double mass_source_local; // Storage for Lambda_sq double lambda_sq = this->lambda_sq(); // Get the value of 1/k double k_inv = this->k_inv(); // Get the value of alpha double alpha = this->alpha(); // Get the value of the porosity double porosity = this->porosity(); // Get the density ratio double density_ratio = this->density_ratio(); // Precompute the ratio of fluid density to combined density double rho_f_over_rho = density_ratio / (1 + porosity * (density_ratio - 1)); // Get continuous time from timestepper of first node double time = node_pt(0)->time_stepper_pt()->time_pt()->time(); // Local equation and unknown numbers int local_eqn = 0, local_unknown = 0; // Loop over the integration points for (unsigned ipt = 0; ipt < n_intpt; ipt++) { // Find the local coordinates at the integration point for (unsigned i = 0; i < DIM; i++) { s[i] = integral_pt()->knot(ipt, i); } // Get the weight of the intetgration point double w = integral_pt()->weight(ipt); // Call the basis functions and test functions and get the // (geometric) jacobian of the current element double J = shape_basis_test_local_at_knot(ipt, psi, dpsidx, u_basis, u_test, du_basis_dx, du_test_dx, q_basis, q_test, p_basis, p_test, div_q_basis_ds, div_q_test_ds); // Storage for interpolated values Vector interpolated_x(DIM, 0.0); Vector interpolated_u(DIM, 0.0); DenseMatrix interpolated_du_dx(DIM, DIM, 0.0); double interpolated_div_du_dt_dx = 0.0; Vector interpolated_d2u_dt2(DIM, 0.0); Vector interpolated_q(DIM, 0.0); double interpolated_div_q_ds = 0.0; Vector interpolated_dq_dt(DIM, 0.0); double interpolated_p = 0.0; // loop over the vector basis functions to find interpolated x for (unsigned l = 0; l < n_node; l++) { // Loop over the geometric basis functions for (unsigned i = 0; i < DIM; i++) { interpolated_x[i] += nodal_position(l, i) * psi(l); interpolated_d2u_dt2[i] += this->d2u_dt2(l, i) * u_basis(l); // Get the nodal displacements const double u_value = this->raw_nodal_value(l, u_index(i)); interpolated_u[i] += u_value * u_basis(l); // Loop over derivative directions for (unsigned j = 0; j < DIM; j++) { interpolated_du_dx(i, j) += u_value * du_basis_dx(l, j); } // divergence of the time derivative of the solid displacement interpolated_div_du_dt_dx += this->du_dt(l, i) * du_basis_dx(l, i); } } // loop over the nodes and use the geometric basis functions to find the // interpolated flux and its time derivative for (unsigned i = 0; i < DIM; i++) { // Loop over the edge basis vectors for (unsigned l = 0; l < n_q_basis_edge; l++) { interpolated_q[i] += q_edge(l) * q_basis(l, i); interpolated_dq_dt[i] += dq_edge_dt(l) * q_basis(l, i); } // Loop over the internal basis vectors for (unsigned l = n_q_basis_edge; l < n_q_basis; l++) { interpolated_q[i] += q_internal(l - n_q_basis_edge) * q_basis(l, i); interpolated_dq_dt[i] += dq_internal_dt(l - n_q_basis_edge) * q_basis(l, i); } } // loop over the pressure basis and find the interpolated pressure for (unsigned l = 0; l < n_p_basis; l++) { interpolated_p += p_value(l) * p_basis(l); } // loop over the u edge divergence basis and the u internal divergence // basis to find interpolated div u for (unsigned l = 0; l < n_q_basis_edge; l++) { interpolated_div_q_ds += q_edge(l) * div_q_basis_ds(l); } for (unsigned l = n_q_basis_edge; l < n_q_basis; l++) { interpolated_div_q_ds += q_internal(l - n_q_basis_edge) * div_q_basis_ds(l); } // Get the solid forcing this->force_solid(time, interpolated_x, f_solid); // Get the fluid forcing this->force_fluid(time, interpolated_x, f_fluid); // Get the mass source function this->mass_source(time, interpolated_x, mass_source_local); // Premultiply the weights and the Jacobian double W = w * J; // Linear elasticity: for (unsigned l = 0; l < n_node; l++) { for (unsigned a = 0; a < DIM; a++) { local_eqn = this->nodal_local_eqn(l, u_index(a)); if (local_eqn >= 0) { residuals[local_eqn] += (lambda_sq * (interpolated_d2u_dt2[a] + rho_f_over_rho * interpolated_dq_dt[a]) - f_solid[a]) * u_test(l) * W; // Stress term for (unsigned b = 0; b < DIM; b++) { if (a == b) { residuals[local_eqn] -= alpha * interpolated_p * du_test_dx(l, b) * W; } for (unsigned c = 0; c < DIM; c++) { for (unsigned d = 0; d < DIM; d++) { // Add the stress terms to the residuals residuals[local_eqn] += this->E(a, b, c, d) * interpolated_du_dx(c, d) * du_test_dx(l, b) * W; } } } // Jacobian entries if (flag) { // d(u_eqn_l,a)/d(U_l2,c) for (unsigned l2 = 0; l2 < n_node; l2++) { for (unsigned c = 0; c < DIM; c++) { local_unknown = this->nodal_local_eqn(l2, u_index(c)); if (local_unknown >= 0) { if (a == c) { jacobian(local_eqn, local_unknown) += lambda_sq * this->node_pt(l2)->time_stepper_pt()->weight(2, 0) * u_basis(l2) * u_test(l) * W; } for (unsigned b = 0; b < DIM; b++) { for (unsigned d = 0; d < DIM; d++) { jacobian(local_eqn, local_unknown) += this->E(a, b, c, d) * du_basis_dx(l2, d) * du_test_dx(l, b) * W; } } } } } // d(u_eqn_l,a)/d(Q_l2) for (unsigned l2 = 0; l2 < n_q_basis; l2++) { TimeStepper* timestepper_pt = 0; if (l2 < n_q_basis_edge) { local_unknown = q_edge_local_eqn(l2); timestepper_pt = this->node_pt(q_edge_node_number(l2))->time_stepper_pt(); } else // n_q_basis_edge <= l < n_basis { local_unknown = q_internal_local_eqn(l2 - n_q_basis_edge); timestepper_pt = this->internal_data_pt(q_internal_index()) ->time_stepper_pt(); } if (local_unknown >= 0) { jacobian(local_eqn, local_unknown) += lambda_sq * rho_f_over_rho * timestepper_pt->weight(1, 0) * q_basis(l2, a) * u_test(l) * W; } } // d(u_eqn_l,a)/d(P_l2) for (unsigned l2 = 0; l2 < n_p_basis; l2++) { local_unknown = p_local_eqn(l2); if (local_unknown >= 0) { jacobian(local_eqn, local_unknown) -= alpha * p_basis(l2) * du_test_dx(l, a) * W; } } } // End of Jacobian entries } // End of if not boundary condition } // End of loop over dimensions } // End of loop over u test functions // Darcy: // Loop over the test functions for (unsigned l = 0; l < n_q_basis; l++) { if (l < n_q_basis_edge) { local_eqn = q_edge_local_eqn(l); } else // n_q_basis_edge <= l < n_basis { local_eqn = q_internal_local_eqn(l - n_q_basis_edge); } // If it's not a boundary condition if (local_eqn >= 0) { for (unsigned i = 0; i < DIM; i++) { residuals[local_eqn] += (k_inv * interpolated_q[i] - rho_f_over_rho * f_fluid[i] + rho_f_over_rho * lambda_sq * (interpolated_d2u_dt2[i] + (1.0 / porosity) * interpolated_dq_dt[i])) * q_test(l, i) * w * J; } // deliberately no jacobian factor in this integral residuals[local_eqn] -= (interpolated_p * div_q_test_ds(l)) * w; // Jacobian entries if (flag) { // d(q_eqn_l)/d(U_l2,c) for (unsigned l2 = 0; l2 < n_node; l2++) { for (unsigned c = 0; c < DIM; c++) { local_unknown = this->nodal_local_eqn(l2, u_index(c)); if (local_unknown >= 0) { jacobian(local_eqn, local_unknown) += rho_f_over_rho * lambda_sq * this->node_pt(l2)->time_stepper_pt()->weight(2, 0) * u_basis(l2) * q_test(l, c) * W; } } } // d(q_eqn_l)/d(Q_l2) for (unsigned l2 = 0; l2 < n_q_basis; l2++) { TimeStepper* timestepper_pt = 0; if (l2 < n_q_basis_edge) { local_unknown = q_edge_local_eqn(l2); timestepper_pt = this->node_pt(q_edge_node_number(l2))->time_stepper_pt(); } else // n_q_basis_edge <= l < n_basis { local_unknown = q_internal_local_eqn(l2 - n_q_basis_edge); timestepper_pt = this->internal_data_pt(q_internal_index())->time_stepper_pt(); } if (local_unknown >= 0) { for (unsigned c = 0; c < DIM; c++) { jacobian(local_eqn, local_unknown) += q_basis(l2, c) * q_test(l, c) * (k_inv + rho_f_over_rho * lambda_sq * timestepper_pt->weight(1, 0) / porosity) * W; } } } // d(q_eqn_l)/d(P_l2) for (unsigned l2 = 0; l2 < n_p_basis; l2++) { local_unknown = p_local_eqn(l2); // deliberately no jacobian factor in this term jacobian(local_eqn, local_unknown) -= p_basis(l2) * div_q_test_ds(l) * w; } } // End of Jacobian entries } // End of if not boundary condition } // End of loop over q test functions // loop over pressure test functions for (unsigned l = 0; l < n_p_basis; l++) { // get the local equation number local_eqn = p_local_eqn(l); // If it's not a boundary condition if (local_eqn >= 0) { // solid divergence term residuals[local_eqn] += alpha * interpolated_div_du_dt_dx * p_test(l) * w * J; // fluid divergence term - deliberately no jacobian factor in this // term residuals[local_eqn] += interpolated_div_q_ds * p_test(l) * w; // mass source term residuals[local_eqn] -= mass_source_local * p_test(l) * w * J; // Jacobian entries if (flag) { // d(p_eqn_l)/d(U_l2,c) for (unsigned l2 = 0; l2 < n_node; l2++) { for (unsigned c = 0; c < DIM; c++) { local_unknown = this->nodal_local_eqn(l2, u_index(c)); if (local_unknown >= 0) { jacobian(local_eqn, local_unknown) += alpha * this->node_pt(l2)->time_stepper_pt()->weight(1, 0) * du_basis_dx(l2, c) * p_test(l) * W; } } } // d(p_eqn_l)/d(Q_l2) for (unsigned l2 = 0; l2 < n_q_basis; l2++) { if (l2 < n_q_basis_edge) { local_unknown = q_edge_local_eqn(l2); } else // n_q_basis_edge <= l < n_basis { local_unknown = q_internal_local_eqn(l2 - n_q_basis_edge); } if (local_unknown >= 0) { jacobian(local_eqn, local_unknown) += p_test(l) * div_q_basis_ds(l2) * w; } } } // End of Jacobian entries } // End of if not boundary condition } // End of loop over p test functions } // End of loop over integration points } // Force building of templates template class PoroelasticityEquations<2>; } // namespace oomph huaweicloud/huaweicloud-sdk-cpp-v31-10 #include "huaweicloud/ims/v2/model/ListImageByTagsRequestBody.h" namespace HuaweiCloud { namespace Sdk { namespace Ims { namespace V2 { namespace Model { ListImageByTagsRequestBody::ListImageByTagsRequestBody() { action_ = ""; actionIsSet_ = false; tagsIsSet_ = false; tagsAnyIsSet_ = false; notTagsIsSet_ = false; notTagsAnyIsSet_ = false; limit_ = ""; limitIsSet_ = false; offset_ = ""; offsetIsSet_ = false; matchesIsSet_ = false; withoutAnyTag_ = false; withoutAnyTagIsSet_ = false; } ListImageByTagsRequestBody::~ListImageByTagsRequestBody() = default; void ListImageByTagsRequestBody::validate() { } web::json::value ListImageByTagsRequestBody::toJson() const { web::json::value val = web::json::value::object(); if(actionIsSet_) { val[utility::conversions::to_string_t("action")] = ModelBase::toJson(action_); } if(tagsIsSet_) { val[utility::conversions::to_string_t("tags")] = ModelBase::toJson(tags_); } if(tagsAnyIsSet_) { val[utility::conversions::to_string_t("tags_any")] = ModelBase::toJson(tagsAny_); } if(notTagsIsSet_) { val[utility::conversions::to_string_t("not_tags")] = ModelBase::toJson(notTags_); } if(notTagsAnyIsSet_) { val[utility::conversions::to_string_t("not_tags_any")] = ModelBase::toJson(notTagsAny_); } if(limitIsSet_) { val[utility::conversions::to_string_t("limit")] = ModelBase::toJson(limit_); } if(offsetIsSet_) { val[utility::conversions::to_string_t("offset")] = ModelBase::toJson(offset_); } if(matchesIsSet_) { val[utility::conversions::to_string_t("matches")] = ModelBase::toJson(matches_); } if(withoutAnyTagIsSet_) { val[utility::conversions::to_string_t("without_any_tag")] = ModelBase::toJson(withoutAnyTag_); } return val; } bool ListImageByTagsRequestBody::fromJson(const web::json::value& val) { bool ok = true; if(val.has_field(utility::conversions::to_string_t("action"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("action")); if(!fieldValue.is_null()) { std::string refVal; ok &= ModelBase::fromJson(fieldValue, refVal); setAction(refVal); } } if(val.has_field(utility::conversions::to_string_t("tags"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("tags")); if(!fieldValue.is_null()) { std::vector refVal; ok &= ModelBase::fromJson(fieldValue, refVal); setTags(refVal); } } if(val.has_field(utility::conversions::to_string_t("tags_any"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("tags_any")); if(!fieldValue.is_null()) { std::vector refVal; ok &= ModelBase::fromJson(fieldValue, refVal); setTagsAny(refVal); } } if(val.has_field(utility::conversions::to_string_t("not_tags"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("not_tags")); if(!fieldValue.is_null()) { std::vector refVal; ok &= ModelBase::fromJson(fieldValue, refVal); setNotTags(refVal); } } if(val.has_field(utility::conversions::to_string_t("not_tags_any"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("not_tags_any")); if(!fieldValue.is_null()) { std::vector refVal; ok &= ModelBase::fromJson(fieldValue, refVal); setNotTagsAny(refVal); } } if(val.has_field(utility::conversions::to_string_t("limit"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("limit")); if(!fieldValue.is_null()) { std::string refVal; ok &= ModelBase::fromJson(fieldValue, refVal); setLimit(refVal); } } if(val.has_field(utility::conversions::to_string_t("offset"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("offset")); if(!fieldValue.is_null()) { std::string refVal; ok &= ModelBase::fromJson(fieldValue, refVal); setOffset(refVal); } } if(val.has_field(utility::conversions::to_string_t("matches"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("matches")); if(!fieldValue.is_null()) { std::vector refVal; ok &= ModelBase::fromJson(fieldValue, refVal); setMatches(refVal); } } if(val.has_field(utility::conversions::to_string_t("without_any_tag"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("without_any_tag")); if(!fieldValue.is_null()) { bool refVal; ok &= ModelBase::fromJson(fieldValue, refVal); setWithoutAnyTag(refVal); } } return ok; } std::string ListImageByTagsRequestBody::getAction() const { return action_; } void ListImageByTagsRequestBody::setAction(const std::string& value) { action_ = value; actionIsSet_ = true; } bool ListImageByTagsRequestBody::actionIsSet() const { return actionIsSet_; } void ListImageByTagsRequestBody::unsetaction() { actionIsSet_ = false; } std::vector& ListImageByTagsRequestBody::getTags() { return tags_; } void ListImageByTagsRequestBody::setTags(const std::vector& value) { tags_ = value; tagsIsSet_ = true; } bool ListImageByTagsRequestBody::tagsIsSet() const { return tagsIsSet_; } void ListImageByTagsRequestBody::unsettags() { tagsIsSet_ = false; } std::vector& ListImageByTagsRequestBody::getTagsAny() { return tagsAny_; } void ListImageByTagsRequestBody::setTagsAny(const std::vector& value) { tagsAny_ = value; tagsAnyIsSet_ = true; } bool ListImageByTagsRequestBody::tagsAnyIsSet() const { return tagsAnyIsSet_; } void ListImageByTagsRequestBody::unsettagsAny() { tagsAnyIsSet_ = false; } std::vector& ListImageByTagsRequestBody::getNotTags() { return notTags_; } void ListImageByTagsRequestBody::setNotTags(const std::vector& value) { notTags_ = value; notTagsIsSet_ = true; } bool ListImageByTagsRequestBody::notTagsIsSet() const { return notTagsIsSet_; } void ListImageByTagsRequestBody::unsetnotTags() { notTagsIsSet_ = false; } std::vector& ListImageByTagsRequestBody::getNotTagsAny() { return notTagsAny_; } void ListImageByTagsRequestBody::setNotTagsAny(const std::vector& value) { notTagsAny_ = value; notTagsAnyIsSet_ = true; } bool ListImageByTagsRequestBody::notTagsAnyIsSet() const { return notTagsAnyIsSet_; } void ListImageByTagsRequestBody::unsetnotTagsAny() { notTagsAnyIsSet_ = false; } std::string ListImageByTagsRequestBody::getLimit() const { return limit_; } void ListImageByTagsRequestBody::setLimit(const std::string& value) { limit_ = value; limitIsSet_ = true; } bool ListImageByTagsRequestBody::limitIsSet() const { return limitIsSet_; } void ListImageByTagsRequestBody::unsetlimit() { limitIsSet_ = false; } std::string ListImageByTagsRequestBody::getOffset() const { return offset_; } void ListImageByTagsRequestBody::setOffset(const std::string& value) { offset_ = value; offsetIsSet_ = true; } bool ListImageByTagsRequestBody::offsetIsSet() const { return offsetIsSet_; } void ListImageByTagsRequestBody::unsetoffset() { offsetIsSet_ = false; } std::vector& ListImageByTagsRequestBody::getMatches() { return matches_; } void ListImageByTagsRequestBody::setMatches(const std::vector& value) { matches_ = value; matchesIsSet_ = true; } bool ListImageByTagsRequestBody::matchesIsSet() const { return matchesIsSet_; } void ListImageByTagsRequestBody::unsetmatches() { matchesIsSet_ = false; } bool ListImageByTagsRequestBody::isWithoutAnyTag() const { return withoutAnyTag_; } void ListImageByTagsRequestBody::setWithoutAnyTag(bool value) { withoutAnyTag_ = value; withoutAnyTagIsSet_ = true; } bool ListImageByTagsRequestBody::withoutAnyTagIsSet() const { return withoutAnyTagIsSet_; } void ListImageByTagsRequestBody::unsetwithoutAnyTag() { withoutAnyTagIsSet_ = false; } } } } } } huangqinjin/minapp #include "utils.hpp" class forward : public logging::handler { using session_handle = std::weak_ptr; void connect(session* session, const endpoint& ep) override { session_handle h; if (!session->attrs.get("PEER", h)) { session->service()->connect(remote, { {"PEER", session->weak_from_this()} }); } else if (auto peer = h.lock()) { peer->attrs.set("PEER", session->weak_from_this()); } else { session->close(true); } } void read(session* session, buffer& buf) override { session_handle h; if (session->attrs.get("PEER", h)) { session->protocol(protocol::any); if (auto peer = h.lock()) peer->write(buf.whole()); else session->close(); } else { session->protocol(protocol::any, protocol_options::do_not_consume_buffer); } } void close(session* session) override { session_handle h; if (session->attrs.get("PEER", h)) { if (auto peer = h.lock()) peer->close(true); } } endpoint remote; public: explicit forward(const endpoint& remote) : handler("forward"), remote(remote) { log_read(false); log_write(false); } }; int main(int argc, char* argv[]) try { if (argc != 3 && argc != 4) { std::cout << "Usage: " << argv[0] << " [protocol]" << std::endl; return -1; } auto pair = make_endpoint_pair(argv[3], argv[1], argv[2]); auto server = minapp::acceptor::create(logging::wrap(pair.second)); workers workers({server}, 1); server->bind(pair.first); std::string line; while (getline(std::cin, line)) logging::stream() << line; return 0; } catch (boost::system::system_error& e) { std::cerr << e.code() << ' ' << '-' << ' ' << e.what() << std::endl; return 1; } catch (std::exception& e) { std::cerr << e.what() << std::endl; return 1; } catch (...) { std::cerr << "unknown exception" << std::endl; throw; } // Copyright (C) 2018-2021 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #pragma once #include "ngraph/function.hpp" #include "util/engine/engine_traits.hpp" namespace ngraph { namespace test { enum class TestCaseType { STATIC, DYNAMIC }; namespace { /// A factory that can create engines supporting devices but not dynamic backends. /// Currently: IE_CPU_Backend and IE_GPU_Backend template typename std::enable_if::value, Engine>::type create_engine_impl(const std::shared_ptr function, const TestCaseType) { return Engine{function}; } /// A factory that can create engines which support dynamic backends /// but do not support devices. Currently: INTERPRETER_Engine template typename std::enable_if::value, Engine>::type create_engine_impl(const std::shared_ptr function, const TestCaseType tct) { if (tct == TestCaseType::DYNAMIC) { return Engine::dynamic(function); } else { return Engine{function}; } } } /// A factory that is able to create all types of test Engines /// in both static and dynamic mode template Engine create_engine(const std::shared_ptr function, const TestCaseType tct) { return create_engine_impl(function, tct); }; } } /** * 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 SageMaker { namespace Model { DomainSettingsForUpdate::DomainSettingsForUpdate() : m_rStudioServerProDomainSettingsForUpdateHasBeenSet(false) { } DomainSettingsForUpdate::DomainSettingsForUpdate(JsonView jsonValue) : m_rStudioServerProDomainSettingsForUpdateHasBeenSet(false) { *this = jsonValue; } DomainSettingsForUpdate& DomainSettingsForUpdate::operator =(JsonView jsonValue) { if(jsonValue.ValueExists("RStudioServerProDomainSettingsForUpdate")) { m_rStudioServerProDomainSettingsForUpdate = jsonValue.GetObject("RStudioServerProDomainSettingsForUpdate"); m_rStudioServerProDomainSettingsForUpdateHasBeenSet = true; } return *this; } JsonValue DomainSettingsForUpdate::Jsonize() const { JsonValue payload; if(m_rStudioServerProDomainSettingsForUpdateHasBeenSet) { payload.WithObject("RStudioServerProDomainSettingsForUpdate", m_rStudioServerProDomainSettingsForUpdate.Jsonize()); } return payload; } } // namespace Model } // namespace SageMaker } // namespace Aws vino-ebe/int-pgms #include int partition(int a[], int low, int high); void quicksort(int a[], int low, int high); void swap(int a[], int i, int j); int main() { int a[] = {2,9,1,23,7,14,6}; quicksort(a, 0, 6); std::cout<<"Sorted list"< pivot) { right--; } if (a[left] > a[right]) { swap(a, left, right); } } for (int i = 0; i < 7; i++) { if (a[i] == pivot) { pIndex = i; break; } } return pIndex; } void swap(int a[], int i, int j) { int temp = a[i]; a[i] = a[j]; a[j] = temp; } lovepark/libo3d3xx #include "o3d3xx_camera.h" #include #include #include #include #include #include #include #include "gtest/gtest.h" // // The `SetUp' and `TearDown' functions on the test fixture here are // leveraged to put the camera into a testable state. // class AppImagerTest : public ::testing::Test { protected: virtual void SetUp() { cam_ = std::make_shared(); cam_->RequestSession(); cam_->SetOperatingMode(o3d3xx::Camera::operating_mode::EDIT); o3d3xx::DeviceConfig::Ptr dev = cam_->GetDeviceConfig(); int active_idx = dev->ActiveApplication(); for (auto& app : cam_->GetApplicationList()) { if (app.index != active_idx) { cam_->DeleteApplication(app.index); } } cam_->SaveDevice(); } virtual void TearDown() { } o3d3xx::Camera::Ptr cam_; }; TEST_F(AppImagerTest, CopyDeleteApplication) { std::vector apps = cam_->GetApplicationList(); int napps = apps.size(); ASSERT_EQ(napps, 1); int new_idx = cam_->CopyApplication(apps.at(0).index); apps = cam_->GetApplicationList(); ASSERT_GT(apps.size(), napps); ASSERT_NO_THROW(cam_->DeleteApplication(new_idx)); apps = cam_->GetApplicationList(); ASSERT_EQ(napps, apps.size()); // copy an invalid application ASSERT_THROW(cam_->CopyApplication(100), o3d3xx::error_t); try { cam_->CopyApplication(100); } catch (const o3d3xx::error_t& ex) { ASSERT_EQ(ex.code(), O3D3XX_XMLRPC_INVALID_APPLICATION); } } TEST_F(AppImagerTest, CreateApplication) { std::vector apps = cam_->GetApplicationList(); int napps = apps.size(); ASSERT_GE(napps, 1); int new_idx = cam_->CreateApplication(); apps = cam_->GetApplicationList(); ASSERT_EQ(napps+1, apps.size()); cam_->DeleteApplication(new_idx); apps = cam_->GetApplicationList(); ASSERT_EQ(napps, apps.size()); } TEST_F(AppImagerTest, ChangeAppNameAndDescription) { int new_idx = cam_->CreateApplication(); std::string name("Foo"); std::string descr("Bar"); cam_->ChangeAppNameAndDescription(new_idx, name, descr); std::vector apps = cam_->GetApplicationList(); for (auto& a : apps) { if (a.index == new_idx) { ASSERT_EQ(a.name, name); ASSERT_EQ(a.description, descr); } } cam_->DeleteApplication(new_idx); } TEST_F(AppImagerTest, EditApplication) { int new_idx = cam_->CreateApplication(); ASSERT_NO_THROW(cam_->EditApplication(new_idx)); ASSERT_NO_THROW(cam_->StopEditingApplication()); cam_->DeleteApplication(new_idx); } TEST_F(AppImagerTest, GetAppParameters) { o3d3xx::DeviceConfig::Ptr dev = cam_->GetDeviceConfig(); int new_idx = cam_->CopyApplication(dev->ActiveApplication()); cam_->EditApplication(new_idx); std::unordered_map params = cam_->GetAppParameters(); // for (auto& kv : params) // { // std::cout << kv.first << "=" << kv.second << std::endl; // } ASSERT_EQ(params.size(), 10); ASSERT_NO_THROW(params.at("Name")); ASSERT_NO_THROW(params.at("Description")); ASSERT_NO_THROW(params.at("TriggerMode")); ASSERT_NO_THROW(params.at("PcicTcpResultSchema")); ASSERT_NO_THROW(params.at("PcicEipResultSchema")); ASSERT_NO_THROW(params.at("PcicPnioResultSchema")); ASSERT_NO_THROW(params.at("TemplateInfo")); ASSERT_NO_THROW(params.at("Type")); ASSERT_NO_THROW(params.at("LogicGraph")); ASSERT_NO_THROW(params.at("RtspOverlayStyle")); cam_->StopEditingApplication(); cam_->DeleteApplication(new_idx); } TEST_F(AppImagerTest, AppConfig) { o3d3xx::DeviceConfig::Ptr dev = cam_->GetDeviceConfig(); int new_idx = cam_->CopyApplication(dev->ActiveApplication()); cam_->EditApplication(new_idx); std::string new_name("Foo"); std::string new_description("Bar"); o3d3xx::AppConfig::Ptr app = cam_->GetAppConfig(); app->SetName(new_name); app->SetDescription(new_description); app->SetTriggerMode( static_cast(o3d3xx::Camera::trigger_mode::PROCESS_INTERFACE)); ASSERT_NO_THROW(cam_->SetAppConfig(app.get())); ASSERT_NO_THROW(cam_->SaveApp()); o3d3xx::AppConfig::Ptr app_new = cam_->GetAppConfig(); ASSERT_EQ(app->Name(), app_new->Name()); ASSERT_EQ(app->Description(), app_new->Description()); ASSERT_EQ(app->TriggerMode(), app_new->TriggerMode()); cam_->StopEditingApplication(); cam_->DeleteApplication(new_idx); } TEST_F(AppImagerTest, AppConfig_JSON) { o3d3xx::DeviceConfig::Ptr dev = cam_->GetDeviceConfig(); int new_idx = cam_->CopyApplication(dev->ActiveApplication()); cam_->EditApplication(new_idx); o3d3xx::AppConfig::Ptr app = cam_->GetAppConfig(); std::string json = app->ToJSON(); o3d3xx::AppConfig::Ptr app2 = o3d3xx::AppConfig::FromJSON(json); ASSERT_EQ(app->Name(), app2->Name()); ASSERT_EQ(app->Description(), app2->Description()); ASSERT_EQ(app->TriggerMode(), app2->TriggerMode()); ASSERT_EQ(app->PcicTcpResultSchema(), app2->PcicTcpResultSchema()); ASSERT_EQ(app->PcicEipResultSchema(), app2->PcicEipResultSchema()); ASSERT_EQ(app->PcicPnioResultSchema(), app2->PcicPnioResultSchema()); ASSERT_EQ(app->LogicGraph(), app2->LogicGraph()); cam_->StopEditingApplication(); cam_->DeleteApplication(new_idx); } TEST_F(AppImagerTest, GetAvailableImagerTypes) { o3d3xx::DeviceConfig::Ptr dev = cam_->GetDeviceConfig(); int new_idx = cam_->CopyApplication(dev->ActiveApplication()); cam_->EditApplication(new_idx); std::vector imager_types; ASSERT_NO_THROW(imager_types = cam_->GetAvailableImagerTypes()); //ASSERT_EQ(imager_types.size(), 8); cam_->StopEditingApplication(); cam_->DeleteApplication(new_idx); } TEST_F(AppImagerTest, ChangeImagerType) { o3d3xx::DeviceConfig::Ptr dev = cam_->GetDeviceConfig(); int new_idx = cam_->CopyApplication(dev->ActiveApplication()); cam_->EditApplication(new_idx); std::vector imager_types = cam_->GetAvailableImagerTypes(); for (auto& type : imager_types) { ASSERT_NO_THROW(cam_->ChangeImagerType(type)); std::unordered_map params = cam_->GetImagerParameters(); ASSERT_EQ(params.at("Type"), type); } cam_->StopEditingApplication(); cam_->DeleteApplication(new_idx); } TEST_F(AppImagerTest, GetImagerParameters) { o3d3xx::DeviceConfig::Ptr dev = cam_->GetDeviceConfig(); int new_idx = cam_->CopyApplication(dev->ActiveApplication()); cam_->EditApplication(new_idx); std::vector imager_types = cam_->GetAvailableImagerTypes(); for (auto& type : imager_types) { cam_->ChangeImagerType(type); std::unordered_map params = cam_->GetImagerParameters(); // std::cout << type << ":" << std::endl; // for (auto& kv : params) // { // std::cout << kv.first << " --> " << kv.second << std::endl; // } ASSERT_NO_THROW(params.at("AutoExposureReferencePointX")); ASSERT_NO_THROW(params.at("AutoExposureReferencePointY")); ASSERT_NO_THROW(params.at("AutoExposureReferenceROI")); ASSERT_NO_THROW(params.at("AutoExposureReferenceType")); ASSERT_NO_THROW(params.at("AutoExposureMaxExposureTime")); ASSERT_NO_THROW(params.at("ClippingBottom")); ASSERT_NO_THROW(params.at("ClippingLeft")); ASSERT_NO_THROW(params.at("ClippingRight")); ASSERT_NO_THROW(params.at("ClippingTop")); ASSERT_NO_THROW(params.at("ContinuousAutoExposure")); ASSERT_NO_THROW(params.at("EnableAmplitudeCorrection")); ASSERT_NO_THROW(params.at("EnableFastFrequency")); ASSERT_NO_THROW(params.at("EnableFilterAmplitudeImage")); ASSERT_NO_THROW(params.at("EnableFilterDistanceImage")); ASSERT_NO_THROW(params.at("EnableRectificationAmplitudeImage")); ASSERT_NO_THROW(params.at("EnableRectificationDistanceImage")); ASSERT_NO_THROW(params.at("UseSimpleBinning")); ASSERT_NO_THROW(params.at("ExposureTimeList")); ASSERT_NO_THROW(params.at("FrameRate")); ASSERT_NO_THROW(params.at("MinimumAmplitude")); ASSERT_NO_THROW(params.at("Resolution")); ASSERT_NO_THROW(params.at("ClippingCuboid")); ASSERT_NO_THROW(params.at("SpatialFilterType")); ASSERT_NO_THROW(params.at("SymmetryThreshold")); ASSERT_NO_THROW(params.at("TemporalFilterType")); ASSERT_NO_THROW(params.at("ThreeFreqMax2FLineDistPercentage")); ASSERT_NO_THROW(params.at("ThreeFreqMax3FLineDistPercentage")); ASSERT_NO_THROW(params.at("TwoFreqMaxLineDistPercentage")); ASSERT_NO_THROW(params.at("Type")); ASSERT_NO_THROW(params.at("MaxAllowedLEDFrameRate")); ASSERT_NO_THROW(params.at("ContinuousUserFrameCalibration")); if(!boost::algorithm::ends_with(type, "depalletizing_upto_30m_high")) { ASSERT_NO_THROW(params.at("Channel")); } if (boost::algorithm::ends_with(type, "high")) { ASSERT_THROW(params.at("ExposureTime"), std::out_of_range); ASSERT_THROW(params.at("ExposureTimeRatio"), std::out_of_range); if(boost::algorithm::ends_with(type, "depalletizing_upto_30m_high")) { ASSERT_EQ(params.size(), 31); } else { ASSERT_EQ(params.size(), 32); } } else if (boost::algorithm::ends_with(type, "low")) { ASSERT_NO_THROW(params.at("ExposureTime")); ASSERT_THROW(params.at("ExposureTimeRatio"), std::out_of_range); ASSERT_EQ(params.size(), 33); } else if (boost::algorithm::ends_with(type, "moderate")) { ASSERT_NO_THROW(params.at("ExposureTime")); ASSERT_NO_THROW(params.at("ExposureTimeRatio")); ASSERT_EQ(params.size(), 34); } } cam_->StopEditingApplication(); cam_->DeleteApplication(new_idx); } TEST_F(AppImagerTest, GetImagerParameterLimits) { o3d3xx::DeviceConfig::Ptr dev = cam_->GetDeviceConfig(); int new_idx = cam_->CopyApplication(dev->ActiveApplication()); cam_->EditApplication(new_idx); std::vector imager_types = cam_->GetAvailableImagerTypes(); for (auto& type : imager_types) { cam_->ChangeImagerType(type); std::unordered_map params = cam_->GetImagerParameters(); // // tests that the call to fetch the parameter limits does not throw an // exception. // std::unordered_map > limits = cam_->GetImagerParameterLimits(); for (auto& param : params) { try { // // Now we simply want to make sure that // the only limits, if the parameter has // limits, are "min" and "max" ... and // that the values make some sort of sense. // Otherwise, we need to investigate further. // std::unordered_map param_limits = limits.at(param.first); ASSERT_EQ(param_limits.size(), 2); ASSERT_LE(std::stod(param_limits.at("min")), std::stod(param_limits.at("max"))); } catch (const std::out_of_range& ex) { // no limits defined for this parameter. } } } cam_->StopEditingApplication(); cam_->DeleteApplication(new_idx); } TEST_F(AppImagerTest, ImagerConfig) { o3d3xx::DeviceConfig::Ptr dev = cam_->GetDeviceConfig(); int new_idx = cam_->CopyApplication(dev->ActiveApplication()); cam_->EditApplication(new_idx); std::vector imager_types = cam_->GetAvailableImagerTypes(); for (auto& type : imager_types) { ASSERT_NO_THROW(cam_->ChangeImagerType(type)); o3d3xx::ImagerConfig::Ptr im = cam_->GetImagerConfig(); ASSERT_EQ(im->Type(), type); ASSERT_NO_THROW(im->SetContinuousAutoExposure(true)); ASSERT_NO_THROW(im->SetEnableAmplitudeCorrection(false)); ASSERT_NO_THROW(im->SetEnableFastFrequency(true)); ASSERT_NO_THROW(im->SetEnableFilterAmplitudeImage(false)); ASSERT_NO_THROW(im->SetEnableFilterDistanceImage(false)); ASSERT_NO_THROW(im->SetEnableRectificationAmplitudeImage(true)); ASSERT_NO_THROW(im->SetEnableRectificationDistanceImage(true)); ASSERT_NO_THROW(im->SetUseSimpleBinning(true)); // mutate the config if (boost::algorithm::ends_with(type, "high")) { } else if (boost::algorithm::ends_with(type, "low")) { ASSERT_NO_THROW(im->SetExposureTime(2000)); } else if (boost::algorithm::ends_with(type, "moderate")) { ASSERT_NO_THROW(im->SetExposureTime(2000)); ASSERT_NO_THROW(im->SetExposureTimeRatio(5)); } ASSERT_NO_THROW(im->SetFrameRate(10)); ASSERT_NO_THROW(im->SetMinimumAmplitude(5)); ASSERT_NO_THROW(im->SetResolution(o3d3xx::RES_23K)); ASSERT_NO_THROW(im->SetSpatialFilterType( static_cast(o3d3xx::Camera::spatial_filter::MEDIAN_FILTER))); //ASSERT_NO_THROW(im->SetSymmetryThreshold(1)); ASSERT_NO_THROW(im->SetTemporalFilterType( static_cast( o3d3xx::Camera::temporal_filter::TEMPORAL_MEAN_FILTER))); // send new config parameters to the sensor ASSERT_NO_THROW(cam_->SetImagerConfig(im.get())); // check if they are correct when queried again o3d3xx::ImagerConfig::Ptr im2 = cam_->GetImagerConfig(); ASSERT_EQ(im2->Type(), im->Type()); if (boost::algorithm::ends_with(type, "high")) { } else if (boost::algorithm::ends_with(type, "low")) { ASSERT_EQ(im2->ExposureTime(), im->ExposureTime()); } else if (boost::algorithm::ends_with(type, "moderate")) { ASSERT_EQ(im2->ExposureTime(), im->ExposureTime()); ASSERT_EQ(im2->ExposureTimeRatio(), im->ExposureTimeRatio()); } ASSERT_EQ(im2->FrameRate() , im->FrameRate()); ASSERT_EQ(im2->MinimumAmplitude(), im->MinimumAmplitude()); ASSERT_EQ(im2->SpatialFilterType(), im->SpatialFilterType()); //ASSERT_EQ(im2->SymmetryThreshold(), im->SymmetryThreshold()); ASSERT_EQ(im2->TemporalFilterType(), im->TemporalFilterType()); } cam_->StopEditingApplication(); cam_->DeleteApplication(new_idx); } TEST_F(AppImagerTest, ImagerConfigValueOutOfRange) { o3d3xx::DeviceConfig::Ptr dev = cam_->GetDeviceConfig(); int new_idx = cam_->CopyApplication(dev->ActiveApplication()); cam_->EditApplication(new_idx); std::vector imager_types = cam_->GetAvailableImagerTypes(); for (auto& type : imager_types) { ASSERT_NO_THROW(cam_->ChangeImagerType(type)); o3d3xx::ImagerConfig::Ptr im = cam_->GetImagerConfig(); ASSERT_EQ(im->Type(), type); // mutate the config ASSERT_NO_THROW(im->SetFrameRate(1000.0)); // send new config parameters to the sensor bool ex_thrown = false; try { cam_->SetImagerConfig(im.get()); } catch (const o3d3xx::error_t& ex) { ASSERT_EQ(ex.code(), O3D3XX_XMLRPC_VALUE_OUT_OF_RANGE); ex_thrown = true; } ASSERT_TRUE(ex_thrown); } cam_->StopEditingApplication(); cam_->DeleteApplication(new_idx); } TEST_F(AppImagerTest, ImagerConfig_JSON) { o3d3xx::DeviceConfig::Ptr dev = cam_->GetDeviceConfig(); int new_idx = cam_->CopyApplication(dev->ActiveApplication()); cam_->EditApplication(new_idx); o3d3xx::ImagerConfig::Ptr im = cam_->GetImagerConfig(); std::string json = im->ToJSON(); o3d3xx::ImagerConfig::Ptr im2 = o3d3xx::ImagerConfig::FromJSON(json); ASSERT_EQ(im->Type(), im2->Type()); ASSERT_EQ(im->Channel(), im2->Channel()); ASSERT_EQ(im->ClippingBottom(), im2->ClippingBottom()); ASSERT_EQ(im->ClippingLeft(), im2->ClippingLeft()); ASSERT_EQ(im->ClippingRight(), im2->ClippingRight()); ASSERT_EQ(im->ClippingTop(), im2->ClippingTop()); ASSERT_EQ(im->ContinuousAutoExposure() , im2->ContinuousAutoExposure()); ASSERT_EQ(im->EnableAmplitudeCorrection(), im2->EnableAmplitudeCorrection()); ASSERT_EQ(im->EnableFastFrequency(), im2->EnableFastFrequency()); ASSERT_EQ(im->EnableFilterAmplitudeImage(), im2->EnableFilterAmplitudeImage()); ASSERT_EQ(im->EnableFilterDistanceImage(), im2->EnableFilterDistanceImage()); ASSERT_EQ(im->EnableRectificationAmplitudeImage(), im2->EnableRectificationAmplitudeImage()); ASSERT_EQ(im->EnableRectificationDistanceImage(), im2->EnableRectificationDistanceImage()); ASSERT_EQ(im->UseSimpleBinning(), im2->UseSimpleBinning()); if (boost::algorithm::ends_with(im->Type(), "high")) { } else if (boost::algorithm::ends_with(im->Type(), "low")) { ASSERT_EQ(im->ExposureTime(), im2->ExposureTime()); } else { ASSERT_EQ(im->ExposureTime(), im2->ExposureTime()); ASSERT_EQ(im->ExposureTimeRatio(), im2->ExposureTimeRatio()); } ASSERT_EQ(im->ExposureTimeList(), im2->ExposureTimeList()); ASSERT_EQ(im->FrameRate(), im2->FrameRate()); ASSERT_EQ(im->MinimumAmplitude(), im2->MinimumAmplitude()); ASSERT_EQ(im->Resolution(), im2->Resolution()); ASSERT_EQ(im->ClippingCuboid(), im2->ClippingCuboid()); ASSERT_EQ(im->SpatialFilterType(), im2->SpatialFilterType()); ASSERT_EQ(im->SymmetryThreshold(), im2->SymmetryThreshold()); ASSERT_EQ(im->TemporalFilterType(), im2->TemporalFilterType()); ASSERT_EQ(im->ThreeFreqMax2FLineDistPercentage(), im2->ThreeFreqMax2FLineDistPercentage()); ASSERT_EQ(im->ThreeFreqMax3FLineDistPercentage(), im2->ThreeFreqMax3FLineDistPercentage()); ASSERT_EQ(im->TwoFreqMaxLineDistPercentage(), im2->TwoFreqMaxLineDistPercentage()); cam_->StopEditingApplication(); cam_->DeleteApplication(new_idx); } TEST_F(AppImagerTest, Exposure) { o3d3xx::DeviceConfig::Ptr dev = cam_->GetDeviceConfig(); int new_idx = cam_->CopyApplication(dev->ActiveApplication()); cam_->EditApplication(new_idx); std::vector imager_types = cam_->GetAvailableImagerTypes(); for (auto& type : imager_types) { ASSERT_NO_THROW(cam_->ChangeImagerType(type)); o3d3xx::ImagerConfig::Ptr im = cam_->GetImagerConfig(); ASSERT_EQ(im->Type(), type); // mutate the config if (boost::algorithm::ends_with(type, "high")) { } else if (boost::algorithm::ends_with(type, "low")) { ASSERT_NO_THROW(im->SetExposureTime(2000)); } else if (boost::algorithm::ends_with(type, "moderate")) { ASSERT_NO_THROW(im->SetExposureTime(2000)); ASSERT_NO_THROW(im->SetExposureTimeRatio(5)); } // send new config parameters to the sensor ASSERT_NO_THROW(cam_->SetImagerConfig(im.get())); // verify the absolute exposure times im = cam_->GetImagerConfig(); std::vector exposure_strings; std::string exposure_time_list = im->ExposureTimeList(); boost::split(exposure_strings, exposure_time_list, boost::is_any_of(";")); if (boost::algorithm::ends_with(type, "high")) { ASSERT_EQ(exposure_strings.size(), 3); } else if (boost::algorithm::ends_with(type, "low")) { ASSERT_EQ(exposure_strings.size(), 1); ASSERT_EQ(std::atoi(exposure_strings.at(0).c_str()), 2000); } else if (boost::algorithm::ends_with(type, "moderate")) { ASSERT_EQ(exposure_strings.size(), 2); ASSERT_EQ(std::atoi(exposure_strings.at(0).c_str()), 2000/5); ASSERT_EQ(std::atoi(exposure_strings.at(1).c_str()), 2000); } } cam_->StopEditingApplication(); cam_->DeleteApplication(new_idx); } /***************************************************************************//** * \file convectiveTermTest.cpp * \author () * \brief Tests the explicit convective term. */ #include "ConvectiveTerm.h" #include #include #include #include #include #include #ifndef DIMENSIONS #define DIMENSIONS 2 #endif int main(int argc, char **argv) { PetscErrorCode ierr; const PetscInt dim = DIMENSIONS; ierr = PetscInitialize(&argc, &argv, NULL, NULL); CHKERRQ(ierr); char dir[PETSC_MAX_PATH_LEN]; ierr = PetscOptionsGetString(NULL, "-directory", dir, sizeof(dir), NULL); CHKERRQ(ierr); std::string directory(dir); CartesianMesh cartesianMesh(directory+"/cartesianMesh.yaml"); FlowDescription flowDescription(directory+"/flowDescription.yaml"); SimulationParameters simulationParameters(directory, directory+"/simulationParameters.yaml"); std::unique_ptr< ConvectiveTerm > solver(new ConvectiveTerm(&cartesianMesh, &flowDescription, &simulationParameters)); ierr = solver->initialize(); CHKERRQ(ierr); ierr = solver-> calculateExplicitTerms(); CHKERRQ(ierr); ierr = solver->calculateExactSolution(); CHKERRQ(ierr); ierr = solver->calculateRelativeError(); CHKERRQ(ierr); ierr = solver->writeRelativeError(); CHKERRQ(ierr); ierr = solver->finalize(); CHKERRQ(ierr); ierr = PetscFinalize(); CHKERRQ(ierr); return ierr; } // main#include "MainWindow.h" #include "AudioLevel.h" #include "ui_MainWindow.h" #include namespace SpeexWebRTCTest { namespace { Q_LOGGING_CATEGORY(Gui, "gui") } QAudioFormat getCaptureFormat() { QAudioFormat format; format.setSampleRate(48000); format.setChannelCount(1); format.setSampleSize(16); format.setCodec("audio/pcm"); format.setByteOrder(QAudioFormat::LittleEndian); format.setSampleType(QAudioFormat::SignedInt); return format; } QAudioFormat getOutputFormat() { return getCaptureFormat(); } QAudioFormat getMonitorFormat() { QAudioFormat format; format.setSampleRate(48000); format.setChannelCount(2); format.setSampleSize(16); format.setCodec("audio/pcm"); format.setByteOrder(QAudioFormat::LittleEndian); format.setSampleType(QAudioFormat::SignedInt); return format; } MainWindow::MainWindow() : ui(new Ui::MainWindow) { ui->setupUi(this); audioInputThread_.start(); audioOutputThread_.start(); qDebug(Gui) << "Enumerating audio devices..."; for (auto& deviceInfo : QAudioDeviceInfo::availableDevices(QAudio::AudioInput)) { ui->inputDeviceSelector->addItem(deviceInfo.deviceName(), QVariant::fromValue(deviceInfo)); ui->monitorDeviceSelector->addItem(deviceInfo.deviceName(), QVariant::fromValue(deviceInfo)); } for (auto& deviceInfo : QAudioDeviceInfo::availableDevices(QAudio::AudioOutput)) ui->outputDeviceSelector->addItem(deviceInfo.deviceName(), QVariant::fromValue(deviceInfo)); connect(ui->inputDeviceSelector, QOverload::of(&QComboBox::activated), this, &MainWindow::changeDevicesConfiguration); connect(ui->outputDeviceSelector, QOverload::of(&QComboBox::activated), this, &MainWindow::changeDevicesConfiguration); connect(ui->speexRadioButton, &QRadioButton::toggled, this, &MainWindow::switchBackend); connect(ui->noiseGroupBox, &QGroupBox::toggled, this, &MainWindow::changeNoiseReductionSettings); connect(ui->noiseSuppressionDial, &QDial::valueChanged, this, &MainWindow::changeNoiseReductionSettings); connect(ui->agcGroupBox, &QGroupBox::toggled, this, &MainWindow::changeAGCSettings); connect(ui->agcLevelDial, &QDial::valueChanged, this, &MainWindow::changeAGCSettings); connect(ui->agcMaxGainDial, &QDial::valueChanged, this, &MainWindow::changeAGCSettings); connect(ui->agcMaxIncrementDial, &QDial::valueChanged, this, &MainWindow::changeAGCSettings); connect(ui->agcMaxDecrementDial, &QDial::valueChanged, this, &MainWindow::changeAGCSettings); connect(ui->aecGroupBox, &QGroupBox::toggled, this, &MainWindow::changeAECSettings); connect(ui->aecSuppressionDial, &QDial::valueChanged, this, &MainWindow::changeAECSettings); initializeAudio(QAudioDeviceInfo::defaultInputDevice(), QAudioDeviceInfo::defaultOutputDevice(), QAudioDeviceInfo::defaultInputDevice()); startRecording(); } MainWindow::~MainWindow() { stopRecording(); audioInputThread_.exit(0); audioOutputThread_.exit(0); } void fixFormatForDevice(QAudioFormat& format, const QAudioDeviceInfo& info) { if (!info.isFormatSupported(format)) { QAudioFormat newFormat = info.nearestFormat(format); qWarning(Gui).nospace() << "Preferred format " << format << " is not supported by device " << info.deviceName() << "."; qWarning(Gui) << "Trying to use nearest format" << newFormat; format = newFormat; } } void MainWindow::initializeAudio(const QAudioDeviceInfo& inputDeviceInfo, const QAudioDeviceInfo& outputDeviceInfo, const QAudioDeviceInfo& monitorDeviceInfo) { qDebug(Gui) << "Initializing audio processing tract..."; auto captureFormat = getCaptureFormat(); auto outputFormat = getOutputFormat(); auto monitorFormat = getMonitorFormat(); fixFormatForDevice(captureFormat, inputDeviceInfo); fixFormatForDevice(outputFormat, outputDeviceInfo); fixFormatForDevice(monitorFormat, monitorDeviceInfo); audioInput_.reset(new QAudioInput(inputDeviceInfo, captureFormat)); audioOutput_.reset(new QAudioOutput(outputDeviceInfo, outputFormat)); monitorInput_.reset(new QAudioInput(monitorDeviceInfo, monitorFormat)); audioInput_->moveToThread(&audioInputThread_); audioOutput_->moveToThread(&audioOutputThread_); monitorInput_->moveToThread(&audioInputThread_); processor_.reset(new AudioProcessor(captureFormat, monitorFormat, monitorBuffer_)); connect(processor_.get(), &AudioProcessor::voiceActivityChanged, this, &MainWindow::updateVoiceActivity); connect(processor_.get(), &AudioProcessor::inputLevelsChanged, this, &MainWindow::updateInputAudioLevels); connect(processor_.get(), &AudioProcessor::outputLevelsChanged, this, &MainWindow::updateOutputAudioLevels); } void MainWindow::startRecording() { qDebug(Gui) << "Starting audio processing..."; processor_->open(QIODevice::ReadWrite | QIODevice::Truncate); monitorBuffer_.open(QIODevice::ReadWrite | QIODevice::Truncate); audioInput_->start(processor_.get()); audioOutput_->start(processor_.get()); monitorInput_->start(&monitorBuffer_); qInfo(Gui) << "input buffer size:" << audioInput_->bufferSize(); qInfo(Gui) << "output buffer size:" << audioOutput_->bufferSize(); } void MainWindow::stopRecording() { qDebug(Gui) << "Stopping audio processing..."; if (monitorInput_) monitorInput_->stop(); if (audioInput_) audioInput_->stop(); if (audioOutput_) audioOutput_->stop(); monitorBuffer_.close(); if (processor_) processor_->close(); } void MainWindow::changeDevicesConfiguration() { stopRecording(); initializeAudio(ui->inputDeviceSelector->itemData(ui->inputDeviceSelector->currentIndex()) .value(), ui->outputDeviceSelector->itemData(ui->outputDeviceSelector->currentIndex()) .value(), ui->monitorDeviceSelector->itemData(ui->monitorDeviceSelector->currentIndex()) .value()); } void MainWindow::switchBackend() { Backend newBackend = ui->speexRadioButton->isChecked() ? Backend::Speex : Backend::WebRTC; qInfo(Gui) << "Switching DSP backend..."; setupDials(newBackend); processor_->switchBackend(newBackend); } QString levelFromCode(int value) { switch (value) { case 0: return "Low"; case 1: return "Moderate"; case 2: return "High"; case 3: return "Very High"; default: throw std::invalid_argument("Invalid code for level"); } } void MainWindow::setupDials(Backend backend) { ui->noiseGroupBox->setChecked(false); ui->noiseSuppressionDial->setValue(0); ui->agcGroupBox->setChecked(false); ui->agcLevelDial->setValue(0); ui->agcLevelValue->setText("0 dBFS"); ui->agcMaxGainDial->setValue(0); ui->agcMaxGainValue->setText("0 dB"); ui->agcMaxIncrementDial->setValue(0); ui->agcMaxIncrementValue->setText("0 dB/sec"); ui->agcMaxDecrementDial->setValue(0); ui->agcMaxDecrementValue->setText("0 dB/sec"); ui->aecGroupBox->setChecked(false); ui->aecSuppressionDial->setValue(0); updateVoiceActivity(false); if (backend == Backend::Speex) { ui->noiseSuppressionDial->setMaximum(60); ui->noiseSuppressionValue->setText("0 dBFS"); ui->agcMaxIncrementLabel->setVisible(true); ui->agcMaxIncrementDial->setVisible(true); ui->agcMaxIncrementValue->setVisible(true); ui->agcMaxDecrementLabel->setVisible(true); ui->agcMaxDecrementDial->setVisible(true); ui->agcMaxDecrementValue->setVisible(true); ui->aecSuppressionDial->setMaximum(60); ui->aecSuppressionValue->setText("0 dB"); } else { ui->noiseSuppressionDial->setMaximum(3); ui->noiseSuppressionValue->setText(levelFromCode(0)); ui->agcMaxIncrementLabel->setVisible(false); ui->agcMaxIncrementDial->setVisible(false); ui->agcMaxIncrementValue->setVisible(false); ui->agcMaxDecrementLabel->setVisible(false); ui->agcMaxDecrementDial->setVisible(false); ui->agcMaxDecrementValue->setVisible(false); ui->aecSuppressionDial->setMaximum(2); ui->aecSuppressionValue->setText(levelFromCode(0)); } } void MainWindow::changeNoiseReductionSettings() { if (currentBackend() == Backend::Speex) { std::int32_t enabled = ui->noiseGroupBox->isChecked() ? 1 : 0; processor_->setEffectParam("noise_reduction_enabled", enabled); std::int32_t maxAttenuation = -ui->noiseSuppressionDial->value(); ui->noiseSuppressionValue->setText(QString("%1 dB").arg(-maxAttenuation)); processor_->setEffectParam("noise_reduction_max_attenuation", maxAttenuation); } else { processor_->setEffectParam("noise_reduction_enabled", ui->noiseGroupBox->isChecked()); int suppressionLevel = ui->noiseSuppressionDial->value(); ui->noiseSuppressionValue->setText(levelFromCode(suppressionLevel)); processor_->setEffectParam("noise_reduction_suppression_level", suppressionLevel); } } void MainWindow::changeAGCSettings() { if (currentBackend() == Backend::Speex) { std::int32_t enabled = ui->agcGroupBox->isChecked() ? 1 : 0; processor_->setEffectParam("gain_control_enabled", enabled); std::int32_t level = QAudio::convertVolume(-ui->agcLevelDial->value(), QAudio::DecibelVolumeScale, QAudio::LinearVolumeScale) * 32768; ui->agcLevelValue->setText(QString("%1 dBFS").arg(-ui->agcLevelDial->value())); processor_->setEffectParam("gain_control_level", level); std::int32_t maxGain = ui->agcMaxGainDial->value(); ui->agcMaxGainValue->setText(QString("%1 dB").arg(maxGain)); processor_->setEffectParam("gain_control_max_gain", maxGain); std::int32_t maxIncrement = ui->agcMaxIncrementDial->value(); ui->agcMaxIncrementValue->setText(QString("%1 dB/sec").arg(maxIncrement)); processor_->setEffectParam("gain_control_max_increment", maxIncrement); std::int32_t maxDecrement = ui->agcMaxDecrementDial->value(); ui->agcMaxDecrementValue->setText(QString("%1 dB/sec").arg(maxDecrement)); processor_->setEffectParam("gain_control_max_decrement", maxDecrement); } else { processor_->setEffectParam("gain_control_enabled", ui->agcGroupBox->isChecked()); int level = ui->agcLevelDial->value(); ui->agcLevelValue->setText(QString("%1 dBFS").arg(-ui->agcLevelDial->value())); processor_->setEffectParam("gain_control_target_level", level); int maxGain = ui->agcMaxGainDial->value(); ui->agcMaxGainValue->setText(QString("%1 dB").arg(maxGain)); processor_->setEffectParam("gain_control_max_gain", maxGain); } } void MainWindow::changeAECSettings() { if (currentBackend() == Backend::Speex) { std::int32_t enabled = ui->aecGroupBox->isChecked() ? 1 : 0; processor_->setEffectParam("echo_cancellation_enabled", enabled); std::int32_t maxAttenuation = -ui->aecSuppressionDial->value(); ui->aecSuppressionValue->setText(QString("%1 dB").arg(-maxAttenuation)); processor_->setEffectParam("echo_cancellation_max_attenuation", maxAttenuation); } else { processor_->setEffectParam("echo_cancellation_enabled", ui->aecGroupBox->isChecked()); int suppressionLevel = ui->aecSuppressionDial->value(); ui->aecSuppressionValue->setText(levelFromCode(suppressionLevel)); processor_->setEffectParam("echo_cancellation_suppression_level", suppressionLevel); } } Backend MainWindow::currentBackend() const { return processor_->getCurrentBackend(); } void MainWindow::updateVoiceActivity(bool active) { if (active) { ui->vadLabel->setText("Voice active"); ui->vadLabel->setStyleSheet("QLabel { color : #2aa82b; }"); } else { ui->vadLabel->setText("Voice inactive"); ui->vadLabel->setStyleSheet("QLabel { color : black; }"); } } void MainWindow::updateInputAudioLevels(const QVector& levels) { if (inputAudioLevels_.count() != levels.size()) { qDeleteAll(inputAudioLevels_); inputAudioLevels_.clear(); for (int i = 0; i < levels.size(); ++i) { auto* level = new AudioLevel(ui->centralWidget); inputAudioLevels_.append(level); ui->inputLevelsLayout->addWidget(level); } } for (int i = 0; i < levels.count(); ++i) inputAudioLevels_.at(i)->setLevel(levels.at(i)); } void MainWindow::updateOutputAudioLevels(const QVector& levels) { if (outputAudioLevels_.count() != levels.size()) { qDeleteAll(outputAudioLevels_); outputAudioLevels_.clear(); for (int i = 0; i < levels.size(); ++i) { auto* level = new AudioLevel(ui->centralWidget); outputAudioLevels_.append(level); ui->outputLevelsLayout->addWidget(level); } } for (int i = 0; i < levels.count(); ++i) outputAudioLevels_.at(i)->setLevel(levels.at(i)); } } // namespace SpeexWebRTCTest #ifndef IKILLABLE_HPP #define IKILLABLE_HPP class IKillable { public: IKillable(bool isAlive); IKillable(); ~IKillable(); void revive(); void kill(); bool isAlive(void); private: bool _isAlive; }; #endif Sorting/Selection_sort.cpp /* Sample Input 1 5 7 1 2 0 4 0 1 2 4 7 Sample Input 2 6 6 4 5 1 0 2 0 1 2 4 5 6 */ #include using namespace std; int main() { //number of elements int n; cin>>n; int arr[n]; for(int i=0;i>arr[i]; for(int i=0;ishinolab/autd3-library-software // File: blas_matrix.hpp // Project: blas // Created Date: 04/09/2021 // Author: // ----- // Last Modified: 11/09/2021 // Modified By: () // ----- // Copyright (c) 2021 Hapis Lab. All rights reserved. // #pragma once #include #include #include #include #define lapack_complex_float std::complex #define lapack_complex_double std::complex #ifdef USE_BLAS_MKL #include "./mkl_cblas.h" #include "./mkl_lapacke.h" #else #include "./cblas.h" #if _MSC_VER #pragma warning(push) #pragma warning(disable : 4190) #endif #include "./lapacke.h" #if _MSC_VER #pragma warning(pop) #endif #endif #include "eigen/eigen_matrix.hpp" namespace autd::gain::holo { template struct BLASMatrix final : EigenMatrix { explicit BLASMatrix(const size_t row, const size_t col) : EigenMatrix(row, col) {} explicit BLASMatrix(Eigen::Matrix other) : EigenMatrix(std::move(other)) {} ~BLASMatrix() override = default; BLASMatrix(const BLASMatrix& obj) = delete; BLASMatrix& operator=(const BLASMatrix& obj) = delete; BLASMatrix(const BLASMatrix&& v) = delete; BLASMatrix& operator=(BLASMatrix&& obj) = delete; void pseudo_inverse_svd(const std::shared_ptr>& matrix, double alpha, const std::shared_ptr>& u, const std::shared_ptr>& s, const std::shared_ptr>& vt, const std::shared_ptr>& buf) override; void max_eigen_vector(const std::shared_ptr>& ev) override; void add(T alpha, const std::shared_ptr>& a) override; void mul(TRANSPOSE trans_a, TRANSPOSE trans_b, T alpha, const std::shared_ptr>& a, const std::shared_ptr>& b, T beta) override; void solve(const std::shared_ptr>& b) override; T dot(const std::shared_ptr>& a) override; [[nodiscard]] double max_element() const override; void copy_from(const std::shared_ptr>& a) override { copy_from(a->data.data(), a->data.size()); } void copy_from(const std::vector& v) override { copy_from(v.data(), v.size()); } void copy_from(const T* v) override { copy_from(v, this->data.size()); } void copy_from(const T* v, size_t); }; constexpr auto AUTD_GESVD = LAPACKE_dgesdd; constexpr auto AUTD_GESVDC = LAPACKE_zgesdd; constexpr auto AUTD_HEEV = LAPACKE_zheev; constexpr auto AUTD_ZSCAL = cblas_zscal; constexpr auto AUTD_AXPY = cblas_daxpy; constexpr auto AUTD_AXPYC = cblas_zaxpy; constexpr auto AUTD_DGEMM = cblas_dgemm; constexpr auto AUTD_ZGEMM = cblas_zgemm; constexpr auto AUTD_DOTC = cblas_zdotc_sub; constexpr auto AUTD_DOT = cblas_ddot; constexpr auto AUTD_IMAXC = cblas_izamax; constexpr auto AUTD_SYSV = LAPACKE_dsysv; constexpr auto AUTD_POSVC = LAPACKE_zposv; constexpr auto AUTD_CPY = cblas_dcopy; constexpr auto AUTD_CPYC = cblas_zcopy; inline void BLASMatrix::pseudo_inverse_svd(const std::shared_ptr>& matrix, const double alpha, const std::shared_ptr>& u, const std::shared_ptr>& s, const std::shared_ptr>& vt, const std::shared_ptr>& buf) { const auto nc = matrix->cols(); const auto nr = matrix->rows(); const auto lda = static_cast(nr); const auto ldu = static_cast(nr); const auto ldvt = static_cast(nc); const auto s_size = std::min(nr, nc); const auto sigma = std::make_unique(s_size); Eigen::Matrix m = matrix->data; AUTD_GESVDC(LAPACK_COL_MAJOR, 'A', static_cast(nr), static_cast(nc), m.data(), lda, sigma.get(), u->data.data(), ldu, vt->data.data(), ldvt); Eigen::Matrix singular_inv = Eigen::Matrix::Zero(static_cast(nc), static_cast(nr)); for (Eigen::Index i = 0; i < static_cast(s_size); i++) singular_inv(i, i) = sigma[i] / (sigma[i] * sigma[i] + alpha); s->copy_from(singular_inv.data()); buf->mul(TRANSPOSE::NO_TRANS, TRANSPOSE::CONJ_TRANS, ONE, s, u, ZERO); this->mul(TRANSPOSE::CONJ_TRANS, TRANSPOSE::NO_TRANS, ONE, vt, buf, ZERO); } inline void BLASMatrix::pseudo_inverse_svd(const std::shared_ptr>& matrix, const double alpha, const std::shared_ptr>& u, const std::shared_ptr>& s, const std::shared_ptr>& vt, const std::shared_ptr>& buf) { const auto nc = matrix->data.cols(); const auto nr = matrix->data.rows(); const auto lda = static_cast(nr); const auto ldu = static_cast(nr); const auto ldvt = static_cast(nc); const auto s_size = std::min(nr, nc); const auto sigma = std::make_unique(s_size); Eigen::Matrix m = matrix->data; AUTD_GESVD(LAPACK_COL_MAJOR, 'A', static_cast(nr), static_cast(nc), m.data(), lda, sigma.get(), u->data.data(), ldu, vt->data.data(), ldvt); Eigen::Matrix singular_inv = Eigen::Matrix::Zero(nc, nr); for (int i = 0; i < s_size; i++) singular_inv(i, i) = sigma[i] / (sigma[i] * sigma[i] + alpha); s->copy_from(singular_inv.data()); buf->mul(TRANSPOSE::NO_TRANS, TRANSPOSE::TRANS, 1.0, s, u, 0.0); this->mul(TRANSPOSE::TRANS, TRANSPOSE::NO_TRANS, 1.0, vt, buf, 0.0); } inline void BLASMatrix::max_eigen_vector(const std::shared_ptr>& ev) { const auto size = data.cols(); const auto eigenvalues = std::make_unique(size); AUTD_HEEV(CblasColMajor, 'V', 'U', static_cast(size), data.data(), static_cast(size), eigenvalues.get()); std::memcpy(ev->data.data(), data.data() + size * (size - 1), size * sizeof(complex)); } inline void BLASMatrix::max_eigen_vector(const std::shared_ptr>& ev) {} inline void BLASMatrix::add(const double alpha, const std::shared_ptr>& a) { AUTD_AXPY(static_cast(a->data.size()), alpha, a->data.data(), 1, data.data(), 1); } inline void BLASMatrix::add(const complex alpha, const std::shared_ptr>& a) { AUTD_AXPYC(static_cast(a->data.size()), &alpha, a->data.data(), 1, data.data(), 1); } template <> inline void BLASMatrix::mul(const TRANSPOSE trans_a, const TRANSPOSE trans_b, const double alpha, const std::shared_ptr>& a, const std::shared_ptr>& b, const double beta) { const auto lda = static_cast(a->data.rows()); const auto ldb = static_cast(b->data.rows()); const auto ldc = trans_a == TRANSPOSE::NO_TRANS ? static_cast(a->data.rows()) : static_cast(a->data.cols()); const auto n = trans_b == TRANSPOSE::NO_TRANS ? static_cast(b->data.cols()) : static_cast(b->data.rows()); const auto k = trans_a == TRANSPOSE::NO_TRANS ? static_cast(a->data.cols()) : static_cast(a->data.rows()); AUTD_DGEMM(CblasColMajor, static_cast(trans_a), static_cast(trans_b), ldc, n, k, alpha, a->data.data(), lda, b->data.data(), ldb, beta, data.data(), ldc); } template <> inline void BLASMatrix::mul(TRANSPOSE trans_a, TRANSPOSE trans_b, const complex alpha, const std::shared_ptr>& a, const std::shared_ptr>& b, const complex beta) { const auto lda = static_cast(a->data.rows()); const auto ldb = static_cast(b->data.rows()); const auto ldc = trans_a == TRANSPOSE::NO_TRANS ? static_cast(a->data.rows()) : static_cast(a->data.cols()); const auto n = trans_b == TRANSPOSE::NO_TRANS ? static_cast(b->data.cols()) : static_cast(b->data.rows()); const auto k = trans_a == TRANSPOSE::NO_TRANS ? static_cast(a->data.cols()) : static_cast(a->data.rows()); AUTD_ZGEMM(CblasColMajor, static_cast(trans_a), static_cast(trans_b), ldc, n, k, &alpha, a->data.data(), lda, b->data.data(), ldb, &beta, data.data(), ldc); } inline void BLASMatrix::solve(const std::shared_ptr>& b) { const auto n = static_cast(data.cols()); const auto lda = static_cast(data.rows()); const auto ldb = static_cast(b->data.size()); const auto ipiv = std::make_unique(n); AUTD_SYSV(CblasColMajor, 'U', n, 1, data.data(), lda, ipiv.get(), b->data.data(), ldb); } inline void BLASMatrix::solve(const std::shared_ptr>& b) { const auto n = static_cast(data.cols()); const auto lda = static_cast(data.rows()); const auto ldb = static_cast(b->data.size()); auto ipiv = std::make_unique(n); AUTD_POSVC(CblasColMajor, 'U', n, 1, data.data(), lda, b->data.data(), ldb); } inline double BLASMatrix::dot(const std::shared_ptr>& a) { return AUTD_DOT(static_cast(a->data.size()), data.data(), 1, a->data.data(), 1); } inline complex BLASMatrix::dot(const std::shared_ptr>& a) { complex d; AUTD_DOTC(static_cast(a->data.size()), data.data(), 1, a->data.data(), 1, &d); return d; } template <> inline double BLASMatrix>::max_element() const { const auto idx = AUTD_IMAXC(static_cast(data.size()), data.data(), 1); return std::abs(data(static_cast(idx), 0)); } template <> inline double BLASMatrix::max_element() const { return this->data.maxCoeff(); // idamax return the first occurrence of the the maximum 'absolute' value // const auto idx = AUTD_IMAX(static_cast(v->data.size()), v->data.data(), 1); // return v->data(idx); } inline void BLASMatrix::copy_from(const double* v, const size_t n) { AUTD_CPY(static_cast(n), v, 1, data.data(), 1); } inline void BLASMatrix::copy_from(const complex* v, const size_t n) { AUTD_CPYC(static_cast(n), v, 1, data.data(), 1); } } // namespace autd::gain::holo Modules/Compatibility/Deprecated/src/itkDICOMImageIO2.cxx /*========================================================================= * * Copyright Insight Software Consortium * * 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.txt * * 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 "itkArray.h" #include "itkDICOMImageIO2.h" #include "itkMetaDataObject.h" #include namespace itk { /** Constructor */ DICOMImageIO2::DICOMImageIO2() { // We are going to default the dimensions for a DICOM image to 3. // The ImagePositionPatient field in a DICOM image is a 3D position // even though the image is just 2D. So from the ImageIO // standpoint, a single DICOM image will be a 3D image with just one // slice. The ImageFileReader may reduce this down to a 2D image if // the user only asks for a 2D image. this->SetNumberOfDimensions(3); m_PixelType = SCALAR; m_ComponentType = UCHAR; m_ByteOrder = BigEndian; m_Parser = new itkdicomparser::DICOMParser(); m_AppHelper = new itkdicomparser::DICOMAppHelper(); } /** Destructor */ DICOMImageIO2::~DICOMImageIO2() { delete m_Parser; delete m_AppHelper; } bool DICOMImageIO2::CanReadFile(const char *filename) { bool open = m_Parser->OpenFile(filename); if ( !open ) { return false; } bool magic = m_Parser->IsDICOMFile(); return magic; } void DICOMImageIO2::ReadDataCallback(doublebyte, doublebyte, itkdicomparser::DICOMParser::VRTypes, unsigned char *val, quadbyte len) { unsigned int imageBytes = static_cast< unsigned int >( this->GetImageSizeInBytes() ); if ( len < 0 ) { len = 0; } if ( len < static_cast< int >( imageBytes ) ) { imageBytes = len; } memcpy(m_ImageDataBuffer, val, imageBytes); } void DICOMImageIO2::Read(void *buffer) { m_Parser->ClearAllDICOMTagCallbacks(); m_AppHelper->RegisterCallbacks(m_Parser); m_AppHelper->RegisterPixelDataCallback(m_Parser); bool open = m_Parser->OpenFile( m_FileName.c_str() ); if ( !open ) { return; } // Should ReadHeader() be Read() since more than just a header is read? m_Parser->ReadHeader(); Array< float > imagePosition(3); imagePosition[0] = m_AppHelper->GetImagePositionPatient()[0]; imagePosition[1] = m_AppHelper->GetImagePositionPatient()[1]; imagePosition[2] = m_AppHelper->GetImagePositionPatient()[2]; EncapsulateMetaData< Array< float > >(this->GetMetaDataDictionary(), "ITK_ImageOrigin", imagePosition); void * newData; itkdicomparser::DICOMParser::VRTypes newType; unsigned long imageDataLength = 0; m_AppHelper->GetImageData(newData, newType, imageDataLength); memcpy(buffer, newData, imageDataLength); // Clean up m_AppHelper->Clear(); } /** * Read Information about the dicom file */ void DICOMImageIO2::ReadImageInformation() { m_Parser->ClearAllDICOMTagCallbacks(); m_AppHelper->RegisterCallbacks(m_Parser); bool open = m_Parser->OpenFile( m_FileName.c_str() ); if ( !open ) { return; } m_Parser->ReadHeader(); Array< float > imagePosition(3); imagePosition[0] = m_AppHelper->GetImagePositionPatient()[0]; imagePosition[1] = m_AppHelper->GetImagePositionPatient()[1]; imagePosition[2] = m_AppHelper->GetImagePositionPatient()[2]; Array< float > imageSpacing(3); imageSpacing[0] = m_AppHelper->GetPixelSpacing()[0]; imageSpacing[1] = m_AppHelper->GetPixelSpacing()[1]; imageSpacing[2] = m_AppHelper->GetPixelSpacing()[2]; EncapsulateMetaData< Array< float > >(this->GetMetaDataDictionary(), "ITK_ImageOrigin", imagePosition); int *dims = m_AppHelper->GetDimensions(); for ( int i = 0; i < 3; i++ ) { this->SetOrigin(i, imagePosition[i]); this->SetSpacing(i, imageSpacing[i]); } for ( int i = 0; i < 2; i++ ) { this->SetDimensions(i, dims[i]); } this->SetDimensions(2, 1); // single slice in a 3D image int numBits = m_AppHelper->GetBitsAllocated(); bool sign = m_AppHelper->RescaledImageDataIsSigned(); bool isFloat = m_AppHelper->RescaledImageDataIsFloat(); int num_comp = m_AppHelper->GetNumberOfComponents(); if ( isFloat ) // Float { this->SetPixelType(ImageIOBase::SCALAR); this->SetComponentType(ImageIOBase::FLOAT); } else if ( num_comp == 3 ) //RGB { if ( numBits == 8 ) { this->SetComponentType(ImageIOBase::UCHAR); this->SetPixelType(ImageIOBase::RGB); } else { this->SetComponentType(ImageIOBase::USHORT); this->SetPixelType(ImageIOBase::RGB); } } else // Everything else { if ( numBits == 8 ) { if ( sign ) { this->SetPixelType(ImageIOBase::SCALAR); this->SetComponentType(ImageIOBase::CHAR); } else { this->SetPixelType(ImageIOBase::SCALAR); this->SetComponentType(ImageIOBase::UCHAR); } } else if ( numBits == 16 ) { if ( sign ) { this->SetPixelType(ImageIOBase::SCALAR); this->SetComponentType(ImageIOBase::SHORT); } else { this->SetPixelType(ImageIOBase::SCALAR); this->SetComponentType(ImageIOBase::USHORT); } } else { this->SetPixelType(ImageIOBase::SCALAR); this->SetComponentType(ImageIOBase::USHORT); } } this->SetNumberOfComponents(num_comp); // Cleanup m_AppHelper->Clear(); } /** Print Self Method */ void DICOMImageIO2::PrintSelf(std::ostream & os, Indent indent) const { unsigned int i; Superclass::PrintSelf(os, indent); os << indent << "Spacing: ( "; for ( i = 0; i < m_NumberOfDimensions; i++ ) { os << m_Spacing[i] << " "; } os << " )\n"; os << indent << "Origin: ( "; for ( i = 0; i < m_Origin.size(); i++ ) { os << m_Origin[i] << " "; } os << " )" << std::endl; } void DICOMImageIO2 ::GetPatientName(char *name) { m_AppHelper->GetPatientName(name); } void DICOMImageIO2 ::GetPatientID(char *id) { m_AppHelper->GetPatientID(id); } void DICOMImageIO2 ::GetPatientSex(char *sex) { m_AppHelper->GetPatientSex(sex); } void DICOMImageIO2 ::GetPatientAge(char *age) { m_AppHelper->GetPatientAge(age); } void DICOMImageIO2 ::GetPatientDOB(char *dob) { m_AppHelper->GetPatientDOB(dob); } void DICOMImageIO2 ::GetStudyID(char *id) { m_AppHelper->GetStudyID(id); } void DICOMImageIO2 ::GetStudyDescription(char *desc) { m_AppHelper->GetStudyDescription(desc); } void DICOMImageIO2 ::GetBodyPart(char *part) { m_AppHelper->GetBodyPart(part); } void DICOMImageIO2 ::GetNumberOfSeriesInStudy(char *series) { m_AppHelper->GetNumberOfSeriesInStudy(series); } void DICOMImageIO2 ::GetNumberOfStudyRelatedSeries(char *series) { m_AppHelper->GetNumberOfStudyRelatedSeries(series); } void DICOMImageIO2 ::GetStudyDate(char *date) { m_AppHelper->GetStudyDate(date); } void DICOMImageIO2 ::GetModality(char *modality) { m_AppHelper->GetModality(modality); } void DICOMImageIO2 ::GetManufacturer(char *manu) { m_AppHelper->GetManufacturer(manu); } void DICOMImageIO2 ::GetInstitution(char *ins) { m_AppHelper->GetInstitution(ins); } void DICOMImageIO2 ::GetModel(char *model) { m_AppHelper->GetModel(model); } } // end namespace itk MarkusRannare/modio-sdk #include "UnixFilesystem.h" #if defined(MODIO_OSX_DETECTED) || defined(MODIO_LINUX_DETECTED) namespace modio { namespace unix_platform { std::ofstream ofstream(const std::string& path, std::ios_base::openmode mode /*= std::ios_base::out*/ ) { return std::ofstream(path.c_str(), mode); } std::ifstream ifstream(const std::string& path, std::ios_base::openmode mode /*= std::ios_base::in*/ ) { return std::ifstream(path.c_str(), mode); } FILE* fopen(const char* path, const char* mode) { return ::fopen(path, mode); } } } #endif #ifndef __LIST_CPP #define __LIST_CPP #include #include "avl.h" #include #include #include using namespace std; int flag; template tree::tree() { root=NULL; } template tree::~tree() { } template treeNode *tree::newNode(A v, B k){ treeNode *toInsert = new treeNode(v,k); toInsert->left=NULL; toInsert->right=NULL; return toInsert; } template treeNode *tree::insert(A v, B k){ if (root==NULL){ root=newNode(v,k); } else{ return insert(root,v,k); } } template treeNode *tree::insert( treeNode *&trav, A v, B k) { if (trav==NULL){ trav = newNode(v,k); return trav; } else{ if (k < trav->key){ insert(trav->left,v,k); if (flag==2){ checkLeftBalance(trav, k);} } if (k > trav->key){ insert(trav->right, v ,k); if (flag==2){ checkRightBalance(trav, k);} } } } template void tree::checkLeftBalance( treeNode *&node, B k){ treeNode *nL = node->left; treeNode *nR = node->right; if( height(nL) - height(nR) >= 2){ if( k < nL->key){ rotateLeftOnce(node); } else{ rotateLeftTwice(node); } } } template void tree::checkRightBalance( treeNode *&node, B k){ treeNode *nL = node->left; treeNode *nR = node->right; if( height(nR) - height(nL) == 2){ if(k > nR->key){ rotateRightOnce(node); } else{ rotateRightTwice(node); } } } template void tree::rotateLeftOnce( treeNode *&node ){ treeNode *nL; nL = node->left; node->left = nL->right; nL->right = node; node = nL; } template void tree::rotateLeftTwice( treeNode *&node){ rotateRightOnce(node->left); rotateLeftOnce(node); } template void tree::rotateRightOnce( treeNode *&node){ treeNode *nR; nR = node->right; node->right = nR->left; nR->left = node; node = nR; } template void tree:: rotateRightTwice(treeNode *&node){ rotateLeftOnce(node->right); rotateRightOnce(node); } template void tree::updateHeight( treeNode *&trav, B item){ if (trav==NULL){ return; } B hL = height(trav->left); B hR = height(trav->right); if (trav->left==NULL) hL = 0; if(trav->left==NULL) hR = 0; if (hR-hL >= 2){ treeNode *nL = trav->left; treeNode *nR = trav->right; if( item > nR->key) rotateRightTwice(trav); else rotateRightOnce(trav); } else if(hL-hR>=2){ treeNode *nL = trav->left; treeNode *nR = trav->right; if( item < nL->key) rotateLeftTwice(trav); else rotateLeftOnce(trav); } treeNode *retParent = parent(trav->key); updateHeight(retParent, item); } template void tree::assignHeights( treeNode *&trav){ if (trav!=NULL){ trav->nodeHeight = height(trav); } else if (trav==NULL){ return; } assignHeights(trav->left); assignHeights(trav->right); } template treeNode *tree::search( treeNode *&trav, B item) { if(root!=NULL){ treeNode *trav = root; while (trav!=NULL){ if (item <= trav->key){ if (item==trav->key){ return trav; } else trav = trav->left; } else if(item >= trav->key){ if (item==trav->key){ return trav; } else trav = trav->right; } } return NULL; } } template treeNode *tree::parent(B item) { if (item==root->key) return NULL; else{ if(root!=NULL){ treeNode *trav = root; treeNode *pre = trav; while (trav!=NULL){ if (item <= trav->key){ if (item==trav->key){ return pre; } else{ pre = trav; trav = trav->left; } } else if(item >= trav->key){ if (item==trav->key){ return pre; } else{ pre = trav; trav = trav->right; } } } } } } template treeNode *tree::deleteNode(B item) { treeNode *retNode = search( root, item); if (retNode!=NULL){ treeNode *retParent = parent(item); treeNode *parentLeft = retParent->left; treeNode *parentRight = retParent->right; if (retNode->left==NULL && retNode->right==NULL){ if (parentLeft!=NULL && parentLeft->key==retNode->key){ retParent->left=NULL; delete(retNode); retNode=NULL; return retParent; } else if(parentRight!=NULL && parentRight->key==retNode->key){ retParent->right=NULL; delete(retNode); retNode=NULL; return retParent; } } else if (retNode->left==NULL){ if (parentLeft!=NULL && parentLeft->key==retNode->key){ retParent->left = retNode->right; } else if(parentRight!=NULL && parentRight->key==retNode->key){ retParent->right= retNode->right; } delete(retNode); retNode=NULL; return retParent; } else if(retNode->right==NULL){ if (parentLeft!=NULL && parentLeft->key==retNode->key){ retParent->left = retNode->left; } else if(parentRight!=NULL && parentRight->key==retNode->key){ retParent->right = retNode->left; } delete(retNode); retNode=NULL; return retParent; } else if(retNode->left!=NULL && retNode->right!=NULL){ treeNode *nodeRight = retNode->right; treeNode *preN=nodeRight; while (nodeRight->left!=NULL){ preN = nodeRight; nodeRight = nodeRight->left; } A a1 = nodeRight->value; B b1 = nodeRight->key; preN->left=NULL; delete(nodeRight); nodeRight=NULL; retNode->value = a1; retNode->key = b1; return retParent; } } else return NULL; } template treeNode *tree::getRoot(){ return root; } template int tree::height( treeNode *&h){ if(h==NULL) return -1; else{ int leftH=height(h->left); int rightH=height(h->right); if (leftH>rightH) return leftH+1; else return rightH+1; } } #endif /* This is an implementation of the Mersenne Twister which was written by . The original source code, which was copied and pasted into this file, can be found at http://qbrundage.com/michaelb/pubs/essays/random_number_generation, and a description of the Mersenne Twister random number generator can be found here: http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html It has a claimed periodicity of 2^{19937}-1, which is pretty incredible. The algorithm as-is is mainly intended for Monte Carlo realizations, and is not intended to be used for cryptography. See the website for more information. This code was placed into the public domain by , and was put into Enzo by on 11 December 2007. It uses the system random number generator as an initial seed, and the user must specify a seed for the system random number generator. */ #include #include #include #include #include #define MT_LEN 624 #define MT_IA 397 #define MT_IB (MT_LEN - MT_IA) #define UPPER_MASK 0x80000000 #define LOWER_MASK 0x7FFFFFFF #define MATRIX_A 0x9908B0DF #define TWIST(b,i,j) ((b)[i] & UPPER_MASK) | ((b)[j] & LOWER_MASK) #define MAGIC(s) (((s)&1)*MATRIX_A) int mt_index; unsigned long int mt_buffer[MT_LEN]; void mt_init(unsigned int seed) { srand(seed); for (int i = 0; i < MT_LEN; i++) mt_buffer[i] = ((unsigned long int) rand() ); mt_index = 0; } void mt_read(std::ifstream& input) { input >> mt_index; for (int i = 0; i < MT_LEN; i++) input >> mt_buffer[i]; } void mt_write(std::ofstream& output) { output << mt_index << '\n'; for (int i = 0; i < MT_LEN; i++) output << mt_buffer[i] << '\n'; } unsigned long int mt_random() { unsigned long int * b = mt_buffer; int idx = mt_index; unsigned long int s; int i; if (idx == MT_LEN*sizeof(unsigned long int)) { idx = 0; i = 0; for (; i < MT_IB; i++) { s = TWIST(b, i, i+1); b[i] = b[i + MT_IA] ^ (s >> 1) ^ MAGIC(s); } for (; i < MT_LEN-1; i++) { s = TWIST(b, i, i+1); b[i] = b[i - MT_IB] ^ (s >> 1) ^ MAGIC(s); } s = TWIST(b, MT_LEN-1, 0); b[MT_LEN-1] = b[MT_IA-1] ^ (s >> 1) ^ MAGIC(s); } mt_index = idx + sizeof(unsigned long int); return *(unsigned long int *)((unsigned char *)b + idx); /* Matsumoto and Nishimura additionally confound the bits returned to the caller but this doesn't increase the randomness, and slows down the generator by as much as 25%. So I omit these operations here. r ^= (r >> 11); r ^= (r << 7) & 0x9D2C5680; r ^= (r << 15) & 0xEFC60000; r ^= (r >> 18); */ } test/math_test.cpp // CATCH_CONFIG_MAIN : Let Catch provide main() // So other test file should not define CATCH_CONFIG_MAIN #define CATCH_CONFIG_MAIN #include "catch.hpp" #include "math.hpp" TEST_CASE( "Math test", "[math]" ) { REQUIRE(glm::vec2(1.0f, 2.0f).x == 1.0f); REQUIRE(glm::vec3(1.0f, 2.0f, 3.0f).y == 2.0f); REQUIRE(glm::vec4(1.0f, 2.0f, 3.0f, 4.0f).z == 3.0f); }#include "p3ui.h" #include namespace p3::python { void Definition::apply(py::module& module) { py::class_> window(module, "ChildWindow"); window.def(py::init<>([](std::shared_ptr content, bool resizeable, bool moveable, py::kwargs kwargs) { auto window = std::make_shared(); ArgumentParser()(kwargs, *window); assign(kwargs, "on_close", *window, &ChildWindow::set_on_close); window->set_content(std::move(content)); window->set_resizeable(resizeable); window->set_moveable(moveable); return window; }), py::kw_only(), py::arg("content")=py::none(), py::arg("resizeable")=true, py::arg("moveable")=true); def_property(window, "content", &ChildWindow::content, &ChildWindow::set_content); def_property(window, "resizeable", &ChildWindow::resizeable, &ChildWindow::set_resizeable); def_property(window, "moveable", &ChildWindow::moveable, &ChildWindow::set_moveable); def_property(window, "on_close", &ChildWindow::on_close, &ChildWindow::set_on_close); } }Shaikh-Nabeel/HackerRankAlgorithms #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; int solve(int n) { // TLE auto cnt = 0; auto m = 0; while(1) { if(cnt>=n) break; else { auto copy = m; while(copy!=0 && copy%5==0) { cnt++; copy /= 5; } } m += 5; } m -= 5; return m; } int main() { // freopen("out.txt","w",stdout); freopen("0.in","r", stdin); int N; cin>>N; for(auto i=0; i>n; cout< #include static void copy(benchmark::State& state) { ba::bytearray array; auto resultSize = state.range(0); array.push_back_multiple( 0xFF, resultSize ); for (auto _ : state) { benchmark::DoNotOptimize(ba::bytearray<>(array)); } state.SetComplexityN(resultSize); } static void move(benchmark::State& state) { ba::bytearray array; auto resultSize = state.range(0); array.push_back_multiple( 0xFF, resultSize ); ba::bytearray copy; for (auto _ : state) { benchmark::DoNotOptimize(copy = std::move(array)); } state.SetComplexityN(resultSize); } BENCHMARK(copy) ->Range(1, 1 << 20) ->Complexity(); BENCHMARK(move) ->Range(1, 1 << 20) ->Complexity();// Copyright (c) 2011 The LevelDB Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. See the AUTHORS file for names of contributors. #include "util/env_mem.h" #include "db/builder.h" #include "db/dbformat.h" #include "db/filename.h" #include "db/table_cache.h" #include "db/version_edit.h" #include "leveldb/db.h" #include "leveldb/env.h" #include "leveldb/iterator.h" #include "ltc/stoc_file_client_impl.h" #include namespace leveldb { Status TestBuildTable(const std::string &dbname, Env *env, const Options &options, TableCache *table_cache, Iterator *iter, FileMetaData *meta, EnvBGThread *bg_thread) { Status s; meta->file_size = 0; iter->SeekToFirst(); std::string fname = TableFileName(dbname, meta->number, FileInternalType::kFileData, 0); if (iter->Valid()) { MemManager *mem_manager = bg_thread->mem_manager(); uint64_t key = bg_thread->thread_id(); ParsedInternalKey ik; Slice user_key; bool insert = true; meta->smallest.DecodeFrom(iter->key()); int nentries = 0; uint64_t file_size = 0; for (; iter->Valid(); iter->Next()) { insert = true; Slice key = iter->key(); if (options.prune_memtable_before_flushing) { NOVA_ASSERT(ParseInternalKey(key, &ik)); if (user_key.empty()) { user_key = ik.user_key; } else { if (options.comparator->Compare(ik.user_key, user_key) == 0) { insert = false; } } } if (insert) { nentries += 1; file_size += (key.size() + iter->value().size()); meta->largest.DecodeFrom(key); } } NOVA_LOG(rdmaio::DEBUG) << fmt::format( "!!!!!!!!!!!!!!!!!!!!! CompactMemTable tid:{} alloc_size:{} nentries:{} nblocks:{}", key, options.max_stoc_file_size, nentries, -1); // Finish and check for builder errors meta->file_size = file_size; meta->converted_file_size = meta->file_size; assert(meta->file_size > 0); // Make sure WRITEs are complete before we persist them. meta->converted_file_size = file_size; } // Check for input iterator errors if (!iter->status().ok()) { s = iter->status(); } return s; } Status BuildTable(const std::string &dbname, Env *env, const Options &options, TableCache *table_cache, Iterator *iter, FileMetaData *meta, EnvBGThread *bg_thread, bool prune_memtables) { Status s; meta->file_size = 0; iter->SeekToFirst(); std::string filename = TableFileName(dbname, meta->number, FileInternalType::kFileData, 0); if (iter->Valid()) { const Comparator *user_comp = reinterpret_cast(options.comparator)->user_comparator(); MemManager *mem_manager = bg_thread->mem_manager(); StoCWritableFileClient *stoc_writable_file = new StoCWritableFileClient( env, options, meta->number, mem_manager, bg_thread->stoc_client(), dbname, bg_thread->thread_id(), options.max_stoc_file_size, bg_thread->rand_seed(), filename); WritableFile *file = new MemWritableFile(stoc_writable_file); TableBuilder *builder = new TableBuilder(options, file); Slice user_key; bool insert = true; meta->smallest.DecodeFrom(iter->key()); for (; iter->Valid(); iter->Next()) { insert = true; Slice key = iter->key(); if (prune_memtables) { Slice ukey = ExtractUserKey(key); if (!user_key.empty() && user_comp->Compare(ukey, user_key) == 0) { insert = false; } user_key = ukey; } if (insert) { meta->largest.DecodeFrom(key); builder->Add(key, iter->value()); } } NOVA_LOG(rdmaio::DEBUG) << fmt::format( "!!!!!!!!!!!!!!!!!!!!! CompactMemTable tid:{} alloc_size:{} nentries:{} nblocks:{}", bg_thread->thread_id(), options.max_stoc_file_size, builder->NumEntries(), builder->NumDataBlocks()); // Finish and check for builder errors s = builder->Finish(); if (s.ok()) { meta->file_size = builder->FileSize(); meta->converted_file_size = meta->file_size; assert(meta->file_size > 0); stoc_writable_file->set_meta(*meta); stoc_writable_file->set_num_data_blocks(builder->NumDataBlocks()); } delete builder; builder = nullptr; // Finish and check for file errors if (s.ok()) { s = file->Sync(); } if (s.ok()) { s = file->Close(); } // Make sure WRITEs are complete before we persist them. stoc_writable_file->WaitForPersistingDataBlocks(); uint32_t new_file_size = stoc_writable_file->Finalize(); meta->block_replica_handles = stoc_writable_file->replicas(); meta->parity_block_handle = stoc_writable_file->parity_block_handle(); meta->converted_file_size = new_file_size; stoc_writable_file->Validate(meta->block_replica_handles, meta->parity_block_handle); delete stoc_writable_file; stoc_writable_file = nullptr; delete file; file = nullptr; } // Check for input iterator errors if (!iter->status().ok()) { s = iter->status(); } if (s.ok() && meta->file_size > 0) { // Keep it } else { env->DeleteFile(filename); } return s; } } // namespace leveldb plot2d.cpp0 /* * Copyright (C) 2016 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 . * */ #include "plot2d.h" #include "axesdialog.h" #include #include #include #include #include #include #include Plot2D::Plot2D(QWidget *parent, QString Title) : QWidget(parent) , sTitle(Title) { setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint); setWindowFlags(windowFlags() & ~Qt::WindowCloseButtonHint); setWindowFlags(windowFlags() | Qt::WindowMinMaxButtonsHint); setMouseTracking(true); // setAttribute(Qt::WA_AlwaysShowToolTips); setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); setWindowIcon(QIcon(":/plot.png")); QSettings settings; restoreGeometry(settings.value(sTitle+QString("Plot2D")).toByteArray()); xMarker = 0.0; yMarker = 0.0; bShowMarker = false; bZooming = false; pPropertiesDlg = new plotPropertiesDlg(sTitle); connect(pPropertiesDlg, SIGNAL(configChanged()), this, SLOT(UpdatePlot())); labelPen = pPropertiesDlg->labelColor;//QPen(Qt::white); gridPen = pPropertiesDlg->gridColor; //QPen(Qt::blue); framePen = pPropertiesDlg->frameColor;//QPen(Qt::blue); gridPen.setWidth(pPropertiesDlg->gridPenWidth); sMouseCoord = QString("X=%1 Y=%2") .arg(0.0, 10, 'g', 7, ' ') .arg(0.0, 10, 'g', 7, ' '); setCursor(Qt::CrossCursor); setWindowTitle(Title); } Plot2D::~Plot2D() { QSettings settings; settings.setValue(sTitle+QString("Plot2D"), saveGeometry()); while(!dataSetList.isEmpty()) { delete dataSetList.takeFirst(); } } void Plot2D::setTitle(QString sNewTitle) { sTitle = sNewTitle; } void Plot2D::keyPressEvent(QKeyEvent *e) { // To avoid closing the Plot upon Esc keypress if(e->key() != Qt::Key_Escape) QWidget::keyPressEvent(e); } void Plot2D::closeEvent(QCloseEvent *event) { QSettings settings; settings.setValue(sTitle+QString("Plot2D"), saveGeometry()); event->ignore(); } void Plot2D::paintEvent(QPaintEvent *event) { QPainter painter; painter.begin(this); painter.setFont(pPropertiesDlg->painterFont); QFontMetrics fontMetrics = painter.fontMetrics(); painter.fillRect(event->rect(), QBrush(pPropertiesDlg->painterBkColor)); DrawPlot(&painter, fontMetrics); QRect textSize = fontMetrics.boundingRect(sMouseCoord); int nPosX = (width()/2) - (textSize.width()/2); int nPosY = height() - 4; painter.setPen(labelPen); painter.drawText(nPosX, nPosY, sMouseCoord); painter.end(); } QSize Plot2D::minimumSizeHint() const { return QSize(50, 50); } QSize Plot2D::sizeHint() const { return QSize(330, 330); } void Plot2D::setMaxPoints(int nPoints) { if(nPoints > 0) pPropertiesDlg->maxDataPoints = nPoints; for(int pos=0; possetMaxPoints(pPropertiesDlg->maxDataPoints); } } void Plot2D::SetLimits (double XMin, double XMax, double YMin, double YMax, bool AutoX, bool AutoY, bool LogX, bool LogY) { Ax.XMin = XMin; Ax.XMax = XMax; Ax.YMin = YMin; Ax.YMax = YMax; Ax.AutoX = AutoX; Ax.AutoY = AutoY; Ax.LogX = LogX; Ax.LogY = LogY; if(!dataSetList.isEmpty()) { if(AutoX | AutoY) { bool EmptyData = true; if(Ax.AutoX) { if(Ax.LogX) { XMin = double(FLT_MAX); XMax = double(FLT_MIN); } else { XMin = double(FLT_MAX); XMax =-double(FLT_MAX); } } if(Ax.AutoY) { if(Ax.LogY) { YMin = double(FLT_MAX); YMax = double(FLT_MIN); } else { YMin = double(FLT_MAX); YMax =-double(FLT_MAX); } } DataStream2D* pData; for(int pos=0; posisShown) { if(pData->m_pointArrayX.count() != 0) { EmptyData = false; if(Ax.AutoX) { if(XMin > pData->minx) { XMin = pData->minx; } if(XMax < pData->maxx) { XMax = pData->maxx; } }// if(Ax.AutoX) if(Ax.AutoY) { if(YMin > pData->miny) { YMin = pData->miny; } if(YMax < pData->maxy) { YMax = pData->maxy; } }// if(Ax.AutoY) }// if(pData->m_pointArray.GetSize() != 0) }// if(pData->isShowed) }// while (pos != NULL) if(EmptyData) { XMin = Ax.XMin; XMax = Ax.XMax; YMin = Ax.YMin; YMax = Ax.YMax; } } } if(abs(XMin-XMax) < double(FLT_MIN)) { XMin -= 0.05*(XMax+XMin)+double(FLT_MIN); XMax += 0.05*(XMax+XMin)+double(FLT_MIN); } if(abs(YMin-YMax) < double(FLT_MIN)) { YMin -= 0.05*(YMax+YMin)+double(FLT_MIN); YMax += 0.05*(YMax+YMin)+double(FLT_MIN); } if(XMin > XMax) { double tmp = XMin; XMin = XMax; XMax = tmp; } if(YMin > YMax) { double tmp = YMin; YMin = YMax; YMax = tmp; } if(LogX) { if(XMin <= 0.0) XMin = double(FLT_MIN); if(XMax <= 0.0) XMax = 2.0*double(FLT_MIN); } if(LogY) { if(YMin <= 0.0) YMin = double(FLT_MIN); if(YMax <= 0.0) YMax = 2.0*double(FLT_MIN); } Ax.XMin = XMin; Ax.XMax = XMax; Ax.YMin = YMin; Ax.YMax = YMax; } DataStream2D* Plot2D::NewDataSet(int Id, int PenWidth, QColor Color, int Symbol, QString Title) { DataStream2D* pDataItem = new DataStream2D(Id, PenWidth, Color, Symbol, Title); pDataItem->setMaxPoints(pPropertiesDlg->maxDataPoints); dataSetList.append(pDataItem); return pDataItem; } bool Plot2D::ClearDataSet(int Id) { bool bResult = false; for(int i=0; iGetId() == Id) { pDataItem->RemoveAllPoints(); bResult = true; } } return bResult; } void Plot2D::SetShowDataSet(int Id, bool Show) { if(!dataSetList.isEmpty()) { for(int pos=0; posGetId() == Id) { pData->SetShow(Show); break; } } } } void Plot2D::NewPoint(int Id, double x, double y) { if(std::isnan(y)) return; if(dataSetList.isEmpty()) return; DataStream2D* pData = Q_NULLPTR; for(int pos=0; posGetId() == Id) { pData = dataSetList.at(pos); break; } } if(pData) { pData->AddPoint(x, y); } } void Plot2D::DrawData(QPainter* painter, QFontMetrics fontMetrics) { if(dataSetList.isEmpty()) return; DataStream2D* pData; for(int pos=0; posisShown) { if(pData->GetProperties().Symbol == iline) { LinePlot(painter, pData); } else if(pData->GetProperties().Symbol == ipoint) { PointPlot(painter, pData); } else { ScatterPlot(painter, pData); } if(pData->bShowCurveTitle) ShowTitle(painter, fontMetrics, pData); } } } void Plot2D::SetShowTitle(int Id, bool show) { if(dataSetList.isEmpty()) return; DataStream2D* pData; for(int pos=0; posGetId() == Id) { pData->SetShowTitle(show); return; } } } void Plot2D::ShowTitle(QPainter* painter, QFontMetrics fontMetrics, DataStream2D *pData) { QPen titlePen = QPen(pData->GetProperties().Color); painter->setPen(titlePen); painter->drawText(int(Pf.right+4), int(Pf.top+fontMetrics.height()*(pData->GetId())), pData->GetTitle()); } void Plot2D::XTicLin(QPainter* painter, QFontMetrics fontMetrics) { double xmax, xmin; double dx, dxx, b, fmant; int isx, ic, iesp, jy, isig, ix, ix0, iy0; QString Label; if (Ax.XMax <= 0.0) { xmax =-Ax.XMin; xmin=-Ax.XMax; isx= -1; } else { xmax = Ax.XMax; xmin= Ax.XMin; isx= 1; } dx = xmax - xmin; b = log10(dx); ic = qRound(b) - 2; dx = double(qRound(pow(10.0, (b-ic-1.0)))); if(dx < 11.0) dx = 10.0; else if(dx < 28.0) dx = 20.0; else if(dx < 70.0) dx = 50.0; else dx = 100.0; dx = dx * pow(10.0, double(ic)); xfact = (Pf.right-Pf.left) / (xmax-xmin); dxx = (xmax+dx) / dx; dxx = floor(dxx) * dx; iy0 = int(Pf.bottom + fontMetrics.height()+5); iesp = int(floor(log10(dxx))); if (dxx > xmax) dxx = dxx - dx; do { if(isx == -1) ix = int(Pf.right-(dxx-xmin) * xfact); else ix = int((dxx-xmin) * xfact + Pf.left); jy = int(Pf.bottom + 5);// Perche' 5 ? painter->setPen(gridPen); painter->drawLine(QLine(ix, int(Pf.top), ix, jy)); isig = 0; if(dxx == 0.0) fmant= 0.0; else { isig = int(dxx/fabs(dxx)); dxx = fabs(dxx); fmant = log10(dxx) - double(iesp); fmant = pow(10.0, fmant)*10000.0 + 0.5; fmant = floor(fmant)/10000.0; fmant = isig * fmant; } if(double(isx*fmant) <= -10.0) Label = QString("%1").arg(double(isx*fmant), 6, 'f', 2, ' '); else Label = QString("%1").arg(double(isx*fmant), 6, 'f', 3, ' '); ix0 = ix - fontMetrics.horizontalAdvance(Label)/2; painter->setPen(labelPen); painter->drawText(QPoint(ix0, iy0), Label); dxx = isig*dxx - dx; } while(dxx >= xmin); painter->setPen(labelPen); painter->drawText(QPoint(int(Pf.right + 2), int(Pf.bottom - 0.5*fontMetrics.height())), "x10"); int icx = fontMetrics.horizontalAdvance("x10 "); Label = QString("%1").arg(iesp, 0, 10, QLatin1Char(' ')); painter->setPen(labelPen); painter->drawText(QPoint(int(Pf.right+icx), int(Pf.bottom - fontMetrics.height())), Label); } void Plot2D::YTicLin(QPainter* painter, QFontMetrics fontMetrics) { double ymax, ymin; double dy, dyy, b, fmant; int isy, icc, iesp, jx, isig, iy, ix0, iy0; QString Label; if (Ax.YMax <= 0.0) { ymax = -Ax.YMin; ymin= -Ax.YMax; isy= -1; } else { ymax = Ax.YMax; ymin= Ax.YMin; isy= 1; } dy = ymax - ymin; b = log10(dy); icc = qRound(b) - 2; dy = double(qRound(pow(10.0, (b-icc-1.0)))); if(dy < 11.0) dy = 10.0; else if(dy < 28.0) dy = 20.0; else if(dy < 70.0) dy = 50.0; else dy = 100.0; dy = dy * pow(10.0, double(icc)); yfact = (Pf.top-Pf.bottom) / (ymax-ymin); dyy = (ymax+dy) / dy; dyy = floor(dyy) * dy; iesp = int(floor(log10(dyy))); if(dyy > ymax) dyy = dyy - dy; do { if(isy == -1) iy = int(Pf.top - (dyy-ymin) * yfact); else iy = int((dyy-ymin) * yfact + Pf.bottom); jx = int(Pf.right); painter->setPen(gridPen); painter->drawLine(QLine(int(Pf.left-5), iy, jx, iy)); isig = 0; if(dyy == 0.0) fmant = 0.0; else{ isig = int(dyy/fabs(dyy)); dyy = fabs(dyy); fmant = log10(dyy) - double(iesp); fmant = pow(10.0, fmant)*10000.0 + 0.5; fmant = floor(fmant)/10000.0; fmant = isig * fmant; } if(double(isy*fmant) <= -10.0) Label = QString("%1").arg(double(isy*fmant), 7, 'f', 3, ' '); else Label = QString("%1").arg(double(isy*fmant), 7, 'f', 4, ' '); ix0 = int(Pf.left - fontMetrics.horizontalAdvance(Label) - 5); iy0 = iy + fontMetrics.height()/2; painter->setPen(labelPen); painter->drawText(QPoint(ix0, iy0), Label); dyy = isig*dyy - dy; } while (dyy >= ymin); QPoint point(int(Pf.left), int(Pf.top-0.5*fontMetrics.height())); painter->setPen(labelPen); painter->drawText(point, "x10"); int icx = fontMetrics.horizontalAdvance("x10 "); Label = QString("%1").arg(iesp, 0, 10, QLatin1Char(' ')); painter->setPen(labelPen); painter->drawText(QPoint(int(int(Pf.left)+icx),int(Pf.top-fontMetrics.height())),Label); } void Plot2D::XTicLog(QPainter* painter, QFontMetrics fontMetrics) { int i, ix, ix0, iy0, jy, j; double dx; QString Label; jy = int(Pf.bottom + 5);// Perche' 5 ? iy0 = int(Pf.bottom + fontMetrics.height()+5); if(Ax.XMin < double(FLT_MIN)) Ax.XMin = double(FLT_MIN); if(Ax.XMax < double(FLT_MIN)) Ax.XMax = 10.0*double(FLT_MIN); double xlmin = log10(Ax.XMin); int minx = int(xlmin); if((xlmin < 0.0) && fabs(xlmin-minx) <= double(FLT_MIN)) minx= minx - 1; double xlmax = log10(Ax.XMax); int maxx = int(xlmax); if((xlmax > 0.0) && fabs(xlmax-maxx) <= double(FLT_MIN)) maxx= maxx + 1; xfact = (Pf.right-Pf.left) / ((xlmax-xlmin)+double(FLT_MIN)); bool init = true; int decades = maxx - minx; double x = pow(10.0, minx); if(decades < 6) { for(i=0; i= Ax.XMin) { ix = int(Pf.left + (log10(x)-xlmin)*xfact); Label = QString("%1").arg(x, 7, 'e', 0, ' '); ix0 = ix - fontMetrics.horizontalAdvance(Label)/2; painter->setPen(labelPen); painter->drawText(QPoint(ix0, iy0), Label); init = false; } for(j=1; j<10; j++){ x = x + dx; if((x >= Ax.XMin) && (x <= Ax.XMax)) { ix = int(Pf.left + (log10(x)-xlmin)*xfact); painter->setPen(gridPen); painter->drawLine(QLine(ix, int(Pf.top), ix, jy)); Label = QString("%1").arg(x, 7, 'e', 0, ' '); if(init || (j == 9 && decades == 1)) { ix0 = ix - fontMetrics.horizontalAdvance(Label)/2; painter->setPen(labelPen); painter->drawText(QPoint(ix0, iy0), Label); init = false; } else if (decades == 1) { Label = Label.left(2); ix0 = ix - fontMetrics.horizontalAdvance(Label)/2; painter->setPen(labelPen); painter->drawText(QPoint(ix0, iy0), Label); } } } }// for(i=0; isetPen(labelPen); painter->drawText(QPoint(ix0, iy0), Label); } } else {// decades > 5 for(i=1; i<=decades; i++) { x = pow(10.0, minx + i); if((x >= Ax.XMin) && (x <= Ax.XMax)) { ix = int(Pf.left + (log10(x)-xlmin)*xfact); painter->setPen(gridPen); painter->drawLine(QLine(ix, int(Pf.top),ix, jy)); Label = QString("%1").arg(x, 7, 'e', 0, ' '); ix0 = ix - fontMetrics.horizontalAdvance(Label)/2; painter->setPen(labelPen); painter->drawText(QPoint(ix0, iy0), Label); } } }//if(decades < 6) } void Plot2D::YTicLog(QPainter* painter, QFontMetrics fontMetrics) { int i, iy, ix0, iy0, j; double dy; QString Label; if(Ax.YMin < double(FLT_MIN)) Ax.YMin = double(FLT_MIN); if(Ax.YMax < double(FLT_MIN)) Ax.YMax = 10.0*double(FLT_MIN); double ylmin = log10(Ax.YMin); int miny = int(ylmin); if((ylmin < 0.0) && fabs(ylmin-miny) <= double(FLT_MIN)) miny= miny - 1; double ylmax = log10(Ax.YMax); int maxy = int(ylmax); if((ylmax > 0.0) && fabs(ylmax-maxy) <= double(FLT_MIN)) maxy= maxy + 1; yfact = (Pf.top-Pf.bottom) / ((ylmax-ylmin)+double(FLT_MIN)); bool init = true; int decades = maxy - miny; double y = pow(10.0, miny); if(decades < 6) { for(i=0; i= Ax.YMin) { iy = int(Pf.bottom + (log10(y)-ylmin)*yfact); Label = QString("%1").arg(y, 7, 'e', 0, ' '); ix0 = int(Pf.left - fontMetrics.horizontalAdvance(Label) - 5); iy0 = iy + fontMetrics.height()/2; painter->setPen(labelPen); painter->drawText(QPoint(ix0, iy0), Label); init = false; } for(j=1; j<10; j++){ y = y + dy; if((y >= Ax.YMin) && (y <= Ax.YMax)) { iy = int(Pf.bottom + (log10(y)-ylmin)*yfact); painter->setPen(gridPen); painter->drawLine(QLine(int(Pf.left-5), iy, int(Pf.right), iy)); Label = QString("%1").arg(y, 7, 'e', 0, ' '); if(init || (j == 9 && decades == 1)) { ix0 = int(Pf.left - fontMetrics.horizontalAdvance(Label) - 5); iy0 = iy + fontMetrics.height()/2; painter->setPen(labelPen); painter->drawText(QPoint(ix0, iy0), Label); init = false; } else if (decades == 1) { Label = Label.left(2); ix0 = int(Pf.left - fontMetrics.horizontalAdvance(Label) - 5); iy0 = iy + fontMetrics.height()/2; painter->setPen(labelPen); painter->drawText(QPoint(ix0, iy0), Label); } } } }// for(i=0; isetPen(labelPen); painter->drawText(QPoint(ix0, iy0), Label); } } else {// decades > 5 for(i=1; i<=decades; i++) { y = pow(10.0, miny + i); if((y >= Ax.YMin) && (y <= Ax.YMax)) { iy = int(Pf.bottom + (log10(y)-ylmin)*yfact); painter->setPen(gridPen); painter->drawLine(QLine(int(Pf.left-5), iy, int(Pf.right), iy)); Label = QString("%1").arg(y, 7, 'e', 0, ' '); ix0 = int(Pf.left - fontMetrics.horizontalAdvance(Label) - 5); iy0 = iy + fontMetrics.height()/2; painter->setPen(labelPen); painter->drawText(QPoint(ix0, iy0), Label); } } }//if(decades < 6) } void Plot2D::DrawFrame(QPainter* painter, QFontMetrics fontMetrics) { if(Ax.LogX) XTicLog(painter, fontMetrics); else XTicLin(painter, fontMetrics); if(Ax.LogY) YTicLog(painter, fontMetrics); else YTicLin(painter, fontMetrics); painter->setPen(framePen); painter->drawLine(QLine(int(Pf.left), int(Pf.bottom), int(Pf.right), int(Pf.bottom))); painter->drawLine(QLine(int(Pf.right), int(Pf.bottom), int(Pf.right), int(Pf.top))); painter->drawLine(QLine(int(Pf.right), int(Pf.top), int(Pf.left), int(Pf.top))); painter->drawLine(QLine(int(Pf.left), int(Pf.top), int(Pf.left), int(Pf.bottom))); painter->setPen(labelPen); int icx = fontMetrics.horizontalAdvance((sTitle)); painter->drawText(QPoint(int((width()-icx)/2), int(fontMetrics.height())), sTitle); } void Plot2D::DrawPlot(QPainter* painter, QFontMetrics fontMetrics) { if(Ax.AutoX || Ax.AutoY) { SetLimits (Ax.XMin, Ax.XMax, Ax.YMin, Ax.YMax, Ax.AutoX, Ax.AutoY, Ax.LogX, Ax.LogY); } Pf.left = fontMetrics.horizontalAdvance("-0.00000") + 2.0; Pf.right = width() - fontMetrics.horizontalAdvance("x10-999") - 5.0; Pf.top = 2.0 * fontMetrics.height(); Pf.bottom = height() - 3.0*fontMetrics.height(); DrawFrame(painter, fontMetrics); DrawData(painter, fontMetrics); if(bZooming) { QPen zoomPen(Qt::yellow); painter->setPen(zoomPen); int ix0 = zoomStart.rx() < zoomEnd.rx() ? zoomStart.rx() : zoomEnd.rx(); int iy0 = zoomStart.ry() < zoomEnd.ry() ? zoomStart.ry() : zoomEnd.ry(); painter->drawRect(ix0, iy0, abs(zoomStart.rx()-zoomEnd.rx()), abs(zoomStart.ry()-zoomEnd.ry())); } } void Plot2D::LinePlot(QPainter* painter, DataStream2D* pData) { if(!pData->isShown) return; int iMax = int(pData->m_pointArrayX.count()); if(iMax == 0) return; QPen dataPen = QPen(pData->GetProperties().Color); dataPen.setWidth(pData->GetProperties().PenWidth); painter->setPen(dataPen); int ix0, iy0, ix1, iy1; double xlmin, ylmin; if(Ax.XMin > 0.0) xlmin = log10(Ax.XMin); else xlmin = double(FLT_MIN); if(Ax.YMin > 0.0) ylmin = log10(Ax.YMin); else ylmin = double(FLT_MIN); if(Ax.LogX) { if(pData->m_pointArrayX[0] > 0.0) ix0 = int((Pf.left + (log10(pData->m_pointArrayX[0]) - xlmin)*xfact)); else ix0 =-INT_MAX; // Solo per escludere il punto } else ix0 = int((Pf.left + (pData->m_pointArrayX[0] - Ax.XMin)*xfact)); if(Ax.LogY) { if(pData->m_pointArrayY[0] > 0.0) iy0 = int((Pf.bottom + (log10(pData->m_pointArrayY[0]) - ylmin)*yfact)); else iy0 =-INT_MAX; // Solo per escludere il punto } else iy0 = int((Pf.bottom + (pData->m_pointArrayY[0] - Ax.YMin)*yfact)); for(int i=1; im_pointArrayX[i]) - xlmin)*xfact) + Pf.left); else ix1 = int(((pData->m_pointArrayX[i] - Ax.XMin)*xfact) + Pf.left); if(Ax.LogY) if(pData->m_pointArrayY[i] > 0.0) iy1 = int((Pf.bottom + (log10(pData->m_pointArrayY[i]) - ylmin)*yfact)); else iy1 =-INT_MAX; // Solo per escludere il punto else iy1 = int((Pf.bottom + (pData->m_pointArrayY[i] - Ax.YMin)*yfact)); if(!(ix1Pf.bottom)) { painter->drawLine(ix0, iy0, ix1, iy1); } ix0 = ix1; iy0 = iy1; if(ix1 > Pf.right) { break; } } DrawLastPoint(painter, pData); } void Plot2D::DrawLastPoint(QPainter* painter, DataStream2D* pData) { if(!pData->isShown) return; int ix, iy, i; i = int(pData->m_pointArrayX.count()-1); double xlmin, ylmin; if(Ax.XMin > 0.0) xlmin = log10(Ax.XMin); else xlmin = double(FLT_MIN); if(Ax.YMin > 0.0) ylmin = log10(Ax.YMin); else ylmin = double(FLT_MIN); if(Ax.LogX) { if(pData->m_pointArrayX[i] > 0.0) ix = int(((log10(pData->m_pointArrayX[i]) - xlmin)*xfact) + Pf.left); else return; } else { ix = int(((pData->m_pointArrayX[i] - Ax.XMin)*xfact) + Pf.left); } if(Ax.LogY) { if(pData->m_pointArrayY[i] > 0.0) iy = int((Pf.bottom + (log10(pData->m_pointArrayY[i]) - ylmin)*yfact)); else return; } else { iy = int((Pf.bottom + (pData->m_pointArrayY[i] - Ax.YMin)*yfact)); } if(ix<=Pf.right && ix>=Pf.left && iy>=Pf.top && iy<=Pf.bottom) painter->drawPoint(ix, iy); return; } void Plot2D::PointPlot(QPainter* painter, DataStream2D* pData) { int iMax = int(pData->m_pointArrayX.count()); if(iMax == 0) return; QPen dataPen = QPen(pData->GetProperties().Color); dataPen.setWidth(pData->GetProperties().PenWidth); painter->setPen(dataPen); int ix, iy; double xlmin, ylmin; if(Ax.XMin > 0.0) xlmin = log10(Ax.XMin); else xlmin = double(FLT_MIN); if(Ax.YMin > 0.0) ylmin = log10(Ax.YMin); else ylmin = double(FLT_MIN); for (int i=0; i < iMax; i++) { if(!(pData->m_pointArrayX[i] < Ax.XMin || pData->m_pointArrayX[i] > Ax.XMax || pData->m_pointArrayY[i] < Ax.YMin || pData->m_pointArrayY[i] > Ax.YMax )) { if(Ax.LogX) { if(pData->m_pointArrayX[i] > 0.0) ix = int(((log10(pData->m_pointArrayX[i]) - xlmin)*xfact) + Pf.left); else ix = -INT_MAX; } else ix = int(((pData->m_pointArrayX[i] - Ax.XMin)*xfact) + Pf.left); if(Ax.LogY) { if(pData->m_pointArrayY[i] > 0.0) iy = int((Pf.bottom + (log10(pData->m_pointArrayY[i]) - ylmin)*yfact)); else iy =-INT_MAX; // Solo per escludere il punto } else iy = int((Pf.bottom + (pData->m_pointArrayY[i] - Ax.YMin)*yfact)); painter->drawPoint(ix, iy); } }//for (int i=0; i <= iMax; i++) } void Plot2D::ScatterPlot(QPainter* painter, DataStream2D* pData) { int iMax = int(pData->m_pointArrayX.count()); if(iMax == 0) return; QPen dataPen = QPen(pData->GetProperties().Color); dataPen.setWidth(pData->GetProperties().PenWidth); painter->setPen(dataPen); int ix, iy; double xlmin, ylmin; if(Ax.XMin > 0.0) xlmin = log10(Ax.XMin); else xlmin = double(FLT_MIN); if(Ax.YMin > 0.0) ylmin = log10(Ax.YMin); else ylmin = double(FLT_MIN); int SYMBOLS_DIM = 8; QSize Size(SYMBOLS_DIM, SYMBOLS_DIM); for (int i=0; i < iMax; i++) { if(pData->m_pointArrayX[i] >= Ax.XMin && pData->m_pointArrayX[i] <= Ax.XMax && pData->m_pointArrayY[i] >= Ax.YMin && pData->m_pointArrayY[i] <= Ax.YMax) { if(Ax.LogX) if(pData->m_pointArrayX[i] > 0.0) ix = int(((log10(pData->m_pointArrayX[i]) - xlmin)*xfact) + Pf.left); else ix = -INT_MAX; else//Asse X Lineare ix= int(((pData->m_pointArrayX[i] - Ax.XMin)*xfact) + Pf.left); if(Ax.LogY) { if(pData->m_pointArrayY[i] > 0.0) iy = int(((log10(pData->m_pointArrayY[i]) - ylmin)*yfact) + Pf.bottom); else iy =-INT_MAX; // Solo per escludere il punto } else iy = int(((pData->m_pointArrayY[i] - Ax.YMin)*yfact) + Pf.bottom); if(pData->GetProperties().Symbol == iplus) { painter->drawLine(ix, iy-Size.height()/2, ix, iy+Size.height()/2+1); painter->drawLine(ix-Size.width()/2, iy, ix+Size.width()/2+1, iy); } else if(pData->GetProperties().Symbol == iper) { painter->drawLine(ix-Size.width()/2+1, iy+Size.height()/2-1, ix+Size.width()/2-1, iy-Size.height()/2); painter->drawLine(ix+Size.width()/2-1, iy+Size.height()/2-1, ix-Size.width()/2+1, iy-Size.height()/2); } else if(pData->GetProperties().Symbol == istar) { painter->drawLine(ix, iy-Size.height()/2, ix, iy+Size.height()/2+1); painter->drawLine(ix-Size.width()/2, iy, ix+Size.width()/2+1, iy); painter->drawLine(ix-Size.width()/2+1, iy+Size.height()/2-1, ix+Size.width()/2-1, iy-Size.height()/2); painter->drawLine(ix+Size.width()/2-1, iy+Size.height()/2-1, ix-Size.width()/2+1, iy-Size.height()/2); } else if(pData->GetProperties().Symbol == iuptriangle) { painter->drawLine(ix, iy-Size.height()/2, ix+Size.width()/2, iy+Size.height()/2); painter->drawLine(ix+Size.width()/2, iy+Size.height()/2, ix-Size.width()/2, iy+Size.height()/2); painter->drawLine(ix-Size.width()/2, iy+Size.height()/2, ix, iy-Size.height()/2); } else if(pData->GetProperties().Symbol == idntriangle) { painter->drawLine(ix, iy+Size.height()/2, ix+Size.width()/2, iy-Size.height()/2); painter->drawLine(ix+Size.width()/2, iy-Size.height()/2, ix-Size.width()/2, iy-Size.height()/2); painter->drawLine(ix-Size.width()/2, iy-Size.height()/2, ix, iy+Size.height()/2); } else if(pData->GetProperties().Symbol == icircle) { painter->drawEllipse(QRect(ix-Size.width()/2, iy-Size.height()/2, Size.width(), Size.height())); } else { painter->drawLine(ix-Size.width()/2, iy, ix-Size.width()/2, iy-Size.height()); painter->drawLine(ix, iy-Size.height()/2, ix-Size.width(), iy-Size.height()/2); } } } } void Plot2D::mousePressEvent(QMouseEvent *event) { if (event->buttons() & Qt::RightButton) { pPropertiesDlg->exec(); } else if (event->buttons() & Qt::LeftButton) { if(event->modifiers() & Qt::ShiftModifier) { setCursor(Qt::SizeAllCursor); zoomStart = event->pos(); bZooming = true; } else { setCursor(Qt::OpenHandCursor); lastPos = event->pos(); } } event->accept(); } void Plot2D::mouseReleaseEvent(QMouseEvent *event) { if (event->button() & Qt::RightButton) { event->accept(); } else if (event->button() & Qt::LeftButton) { if(bZooming) { bZooming = false; QPoint distance = zoomStart-zoomEnd; if(abs(distance.rx()) < 10 || abs(distance.ry()) < 10) return; double x1, x2, y1, y2, tmp; if(Ax.LogX) { x1 = pow(10.0, log10(Ax.XMin)+(zoomEnd.rx()-Pf.left)/xfact); x2 = pow(10.0, log10(Ax.XMin)+(zoomStart.rx()-Pf.left)/xfact); } else { x1 = (zoomEnd.rx()-Pf.left)/xfact + Ax.XMin; x2 = (zoomStart.rx()-Pf.left)/xfact + Ax.XMin; } if(Ax.LogY) { y1 = pow(10.0, log10(Ax.YMin)+(zoomEnd.ry()-Pf.bottom)/yfact); y2 = pow(10.0, log10(Ax.YMin)+(zoomStart.ry()-Pf.bottom)/yfact); } else { y1 = (zoomEnd.ry()-Pf.bottom) / yfact + Ax.YMin; y2 = (zoomStart.ry()-Pf.bottom) / yfact + Ax.YMin; } if(x2accept(); } update(); setCursor(Qt::CrossCursor); } void Plot2D::mouseMoveEvent(QMouseEvent *event) { if(event->buttons() & Qt::LeftButton) { if(!bZooming) { double xmin, xmax, ymin, ymax; double dxPix = event->pos().rx() - lastPos.rx(); double dyPix = event->pos().ry() - lastPos.ry(); double dx = dxPix / xfact; double dy = dyPix / yfact; if(Ax.LogX) { xmin = pow(10.0, log10(Ax.XMin)-dx); xmax = pow(10.0, log10(Ax.XMax)-dx); } else { xmin = Ax.XMin - dx; xmax = Ax.XMax - dx; } if(Ax.LogY) { ymin = pow(10.0, log10(Ax.YMin)-dy); ymax = pow(10.0, log10(Ax.YMax)-dy); } else { ymin = Ax.YMin - dy; ymax = Ax.YMax - dy; } lastPos = event->pos(); SetLimits (xmin, xmax, ymin, ymax, Ax.AutoX, Ax.AutoY, Ax.LogX, Ax.LogY); update(); } else {// is Zooming zoomEnd = event->pos(); update(); } event->accept(); return; } double xval, yval; if(Ax.LogX) { xval = pow(10.0, log10(Ax.XMin)+(event->pos().rx()-Pf.left)/xfact); } else { xval =Ax.XMin + (event->pos().rx()-Pf.left) / xfact; } if(Ax.LogY) { yval = pow(10.0, log10(Ax.YMin)+(event->pos().ry()-Pf.bottom)/yfact); } else { yval =Ax.YMin + (event->pos().ry()-Pf.bottom) / yfact; } sMouseCoord = QString("X=%1 Y=%2") .arg(xval, 10, 'g', 7, ' ') .arg(yval, 10, 'g', 7, ' '); update(); event->accept(); } void Plot2D::mouseDoubleClickEvent(QMouseEvent *event) { Q_UNUSED(event); AxesDialog axesDialog(this); axesDialog.initDialog(Ax); int iRes = axesDialog.exec(); if(iRes==QDialog::Accepted) { Ax = axesDialog.newLimits; SetLimits (Ax.XMin, Ax.XMax, Ax.YMin, Ax.YMax, Ax.AutoX, Ax.AutoY, Ax.LogX, Ax.LogY); update(); } } void Plot2D::UpdatePlot() { labelPen = pPropertiesDlg->labelColor; gridPen = pPropertiesDlg->gridColor; framePen = pPropertiesDlg->frameColor; gridPen.setWidth(pPropertiesDlg->gridPenWidth); update(); } void Plot2D::ClearPlot() { while(!dataSetList.isEmpty()) { delete dataSetList.takeFirst(); } update(); } /* Problem: Ural1060 Algorithm: Search Time: O() Memory: O() Detail: Simple Coded by [BUPT]AkemiHomura */ #include #include #include using namespace std; const int INF = 100; int Ans, AnsTmp; char In[6][6], Opr[6][6], Fin[6][6]; void Check() { AnsTmp = 0; for (int r = 1; r <= 4; ++r) for (int c = 1; c <= 4; ++c) Fin[r][c] = In[r][c]; for (int r = 1; r <= 4; ++r) for (int c = 1; c <= 4; ++c) { Fin[r][c] ^= Opr[r][c]; Fin[r+1][c] ^= Opr[r][c]; Fin[r-1][c] ^= Opr[r][c]; Fin[r][c+1] ^= Opr[r][c]; Fin[r][c-1] ^= Opr[r][c]; AnsTmp += Opr[r][c]; } bool B = 1, W = 1; for (int r = 1; r <= 4; ++r) for (int c = 1; c <= 4; ++c) if (Fin[r][c]) W = 0; else B = 0; if (B || W) Ans = min(Ans, AnsTmp); } void Search(int r, int c) { if (r > 4) {Check(); return;} if (c > 4) {Search(r+1, 1); return;} Opr[r][c] = 0; Search(r, c+1); Opr[r][c] = 1; Search(r, c+1); } int main() { //freopen("flip.in", "r", stdin); for (int r = 1; r <= 4; ++r) { for (int c = 1; c <= 4; ++c) { scanf("%c", &In[r][c]); if (In[r][c] == 'w') In[r][c] = 0; else In[r][c] = 1; } scanf("\n"); } Ans = INF; Search(1, 1); if (Ans == INF) printf("Impossible\n"); else printf("%d\n", Ans); return 0; }1-10 #pragma once #include #include #include namespace cdv { template void draw(const stdx::tuple_like auto& t, Surface& surface, const pixel_pos& extents) { std::apply([&](const auto&... elements) { (draw(elements, surface, extents), ...); }, t); } template void draw(const ranges::range auto& elements, Surface& surface, const pixel_pos& extents) { for (const auto& element : elements) draw(element, surface, extents); } } oneish/strange #include "../../strange__core.h" namespace strange { // group_t // group_o template group_o const* group_t::_operations() { static group_o operations = { { { // any_a group_a::cat, group_t::is, group_t::as, group_t::type, group_t::set_error, group_t::error, group_t::hash, group_t::equal, group_t::less, group_t::less_or_equal, group_t::pack, group_t::_free, group_t::_copy, group_t::_set_pointer, group_t::_pointer, }, // collection_a group_t::range, group_t::begin, group_t::end, group_t::read_lock, group_t::write_lock, group_t::has, group_t::at, group_t::update, group_t::insert, group_t::erase, group_t::clear, group_t::size, group_t::empty, group_t::push_front, group_t::pop_front, group_t::push_back, group_t::pop_back, group_t::self_assign, group_t::self_add, group_t::add, group_t::self_subtract, group_t::subtract, }, // group_a group_t::update_element, group_t::insert_element, }; return &operations; } template group_o const* group_t::_pointer_operations() { static group_o operations = []() { group_o ops = *group_t::_operations(); ops._copy = thing_t::_no_copy; return ops; }(); return &operations; } // any_a template bool group_t::is(con<> const& me, con<> const& abstraction) { // abstraction.cat in me.cats auto const abc = abstraction.o->cat; return abc == any_a::cat || abc == collection_a::cat || abc == group_a::cat; } template bool group_t::as(con<> const& me, var<> const& abstraction) { if (!group_t::is(me, abstraction)) { return false; } bool const as_pointer = abstraction.o->_pointer(abstraction); abstraction = me; if (abstraction.o->_pointer(abstraction) != as_pointer) { if (as_pointer) { abstraction.mut(); } abstraction.o->_set_pointer(abstraction, as_pointer); if (!as_pointer) { abstraction.mut(); } } return true; } template var group_t::type(con<> const& me) { static auto r = sym("strange::group"); return r; } template void group_t::_copy(con<> const& me, var<> const& copy) { new group_t{ copy, me }; group_t::_clone(me, copy); } template void group_t::_set_pointer(con<> const& me, bool is_pointer) { me.o = is_pointer ? group_t::_pointer_operations() : group_t::_operations(); } // collection_a template bool group_t::has(con> const& me, element_d const& key) { auto const& collection = static_cast const*>(me.t)->collection_; return collection.find(key) != collection.cend(); } template element_d group_t::at(con> const& me, element_d const& key) { auto const& collection = static_cast const*>(me.t)->collection_; auto const it = collection.find(key); if (it != collection.cend()) { return *it; } return element_d{}; } template void group_t::update(var> const& me, element_d const& key, element_d const& value) { me.mut(); auto& collection = static_cast*>(me.t)->collection_; collection.erase(key); collection.insert(key); } template bool group_t::insert(var> const& me, element_d const& key, element_d const& value) { me.mut(); auto& collection = static_cast*>(me.t)->collection_; return collection.insert(key).second; } template bool group_t::erase(var> const& me, element_d const& key) { auto& collection = static_cast*>(me.t)->collection_; return collection.erase(key) != 0; } template void group_t::push_front(var> const& me, element_d const& element) { group_t::insert(me, element, element); } template element_d group_t::pop_front(var> const& me) { me.mut(); auto& collection = static_cast*>(me.t)->collection_; if (collection.empty()) { return element_d{}; } auto front = *(collection.cbegin()); collection.erase(collection.cbegin()); return front; } template void group_t::push_back(var> const& me, element_d const& element) { push_front(me, element); } template element_d group_t::pop_back(var> const& me) { return pop_front(me); } template void group_t::self_assign(var> const& me, con> const& range) { me.mut(); if (me.o->identity(me) != range.o->identity(range)) { auto& collection = static_cast*>(me.t)->collection_; collection.clear(); for (element_d const& element : range) { collection.insert(element); } } } template void group_t::self_add(var> const& me, con> const& range) { me.mut(); auto& collection = static_cast*>(me.t)->collection_; if (me.o->identity(me) != range.o->identity(range)) { for (element_d const& element : range) { collection.insert(element); } } } template var> group_t::add(con> const& me, con> const& range) { var> result{ me }; self_add(result, range); return result; } template void group_t::self_subtract(var> const& me, con> const& range) { me.mut(); auto& collection = static_cast*>(me.t)->collection_; if (me.o->identity(me) == range.o->identity(range)) { collection.clear(); } else { for (element_d const& element : range) { if (collection.empty()) { break; } collection.erase(element); } } } template var> group_t::subtract(con> const& me, con> const& range) { var> result{ me }; self_subtract(result, range); return result; } // group_a template void group_t::update_element(var> const& me, element_d const& element) { me.mut(); auto& collection = static_cast*>(me.t)->collection_; collection.erase(element); collection.insert(element); } template bool group_t::insert_element(var> const& me, element_d const& element) { me.mut(); auto& collection = static_cast*>(me.t)->collection_; return collection.insert(element).second; } // instantiation template struct group_t, int64_t>; template struct group_t, int64_t>; template struct group_t>, var<>>; } /** * Copyright (c) 2018 * Licensed under the MIT license. * https://opensource.org/licenses/MIT */ #include "sockets.hpp" #include using namespace Socket; BaseSocket::BaseSocket(int type, int flags) { // Inicializa socket_info socket_info = (addrinfo *) calloc(1, sizeof(addrinfo)); // Prenche a estrutura de endereço do socket, sempre IPv4 socket_info->ai_family = AF_INET; socket_info->ai_socktype = type; socket_info->ai_flags = flags; // Mesma família (IPv4) e tipo de socket da socket_info socketfd = socket(AF_INET, type, 0); if (socketfd == -1) { throw SocketException("Could not create socket. Error: " + std::string(strerror(errno))); } // Permite reuso de endereço (evita "Address already in use") int optval = 1; setsockopt(socketfd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval)); } BaseSocket::BaseSocket(int socket, int type, addrinfo sInfo, const std::string& client_ip, uint32_t port, bool is_bound) : socketfd(socket), ip_address_str(client_ip), port_used(port), is_bound(is_bound) { // Verifica que o endereço é IPv4 e do mesmo tipo definido pelo parâmetro if (sInfo.ai_family != AF_INET || sInfo.ai_socktype != type) { throw SocketException("sInfo passed is not defined as the defined type and protocol IPv4"); } // Copia as inforamações do sInfo (sockaddr). socket_info = (addrinfo *) malloc(sizeof(addrinfo)); memcpy(socket_info, &sInfo, sizeof(addrinfo)); // Permite reuso de endereço (evita "Address already in use") int optval = 1; setsockopt(socketfd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval)); } BaseSocket::~BaseSocket() { // Libera memória e encerra o socket if (socket_info) freeaddrinfo(socket_info); close(); } void BaseSocket::bind(uint32_t port) { // Não é possivel vincular um socket que já está vinculado // Logo se a porta desejada for a mesma que já está vinculada, nada acontece. // Uma exceção é lançada caso contrário if (is_bound && port_used != port) { throw ConnectionException("Socket is already bound to port " + std::to_string(port_used)); } else if (is_bound && port_used == port) { return; } // Pela documentação: // If the AI_PASSIVE bit is set it indicates that the // returned socket address structure is intended for use // in a call to bind(2). In this case, if the hostname // argument is the null pointer, then the IP address portion // of the socket address structure will be set to INADDR_ANY // for an IPv4 address socket_info->ai_flags |= AI_PASSIVE; getAddrInfo("NULL", port); int result; int total_ipv4_addrs = 0; // Conta quandos endereços IPv4 foram encontrados addrinfo * new_addrinfo; for (new_addrinfo = socket_info; new_addrinfo; new_addrinfo = new_addrinfo->ai_next) { // Ignora qualquer endereço não IPv4 if (new_addrinfo->ai_family == AF_INET) total_ipv4_addrs++; else continue; // Tenta vincular a qualquer endereço IPv4 encontrado. result = ::bind(socketfd, new_addrinfo->ai_addr, new_addrinfo->ai_addrlen); if (result == -1) continue; // Se a operação é bem-sucedida, seta as variáveis e retorna port_used = port; is_bound = true; return; } // Se nenhum endereço IPv4 é lançado, lança exceção if (total_ipv4_addrs == 0) { throw ConnectionException("Could not find IPv4 addresses to bind on port " + std::to_string(port) + "."); } // Lança exceção caso não seja possível vincular a nenhum IPv4 encontrado. throw ConnectionException("Could not bind to port " + std::to_string(port) + ". Error: " + std::string(strerror(errno))); } void BaseSocket::set_timeout(uint16_t seconds) { struct timeval tv; tv.tv_sec = seconds; tv.tv_usec = 0; // Not init'ing this can cause strange errors setsockopt(this->socketfd, SOL_SOCKET, SO_RCVTIMEO, (const char*)&tv,sizeof(struct timeval)); } void BaseSocket::close() { // Se a socket não foi setada ou já foi fechada, nada acontece. if (socketfd == -1 || is_closed) return; int result = ::close(socketfd); if (result == -1) { throw SocketException("Could not close socket. Error: " + std::string(strerror(errno))); } is_bound = false; is_closed = true; port_used = -1; socketfd = -1; } void BaseSocket::getAddrInfo(const std::string address, uint32_t port) { addrinfo hints = *socket_info; addrinfo * new_socket_info; const char * c_address; // c_address = NULL significa que o getaddrinf() buscará por endereços // locais da maquina if (address == "NULL") c_address = NULL; else c_address = address.c_str(); int result = getaddrinfo(c_address, std::to_string(port).c_str(), &hints, &new_socket_info); if (result != 0) { throw ConnectionException("Error on getaddrinfo(): " + std::string(gai_strerror(result))); } // Libera a memoria da socket_info atual para ela ser realocada por getaddrinfo() if (socket_info) freeaddrinfo(socket_info); socket_info = new_socket_info; } bool BaseSocket::validateIpAddress(const std::string &ip_address) { sockaddr_in sa; int result = ::inet_pton(AF_INET, ip_address.c_str(), &(sa.sin_addr)); return result != 0; } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * TCPSOCKET * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ TCPSocket::TCPSocket(int flags) : BaseSocket(SOCK_STREAM, flags) {} TCPSocket::TCPSocket(int socket, addrinfo socket_info, uint32_t port_used, const std::string& client_ip, bool is_bound, bool is_listening, bool is_connected) : BaseSocket(socket, SOCK_STREAM, socket_info, client_ip, port_used, is_bound), is_listening(is_listening), is_connected(is_connected) { } void TCPSocket::connect(const std::string& address, uint32_t port) { if (is_listening) { throw SocketException("Socket is already listening incoming connections on port " + std::to_string(port_used)); } if (is_connected) { throw SocketException("Socket is already connected to an address"); } getAddrInfo(address, port); int result; int total_ipv4_addrs = 0; addrinfo * new_addrinfo; for (new_addrinfo = socket_info; new_addrinfo; new_addrinfo = new_addrinfo->ai_next) { if (new_addrinfo->ai_family == AF_INET) total_ipv4_addrs++; else continue; result = ::connect(socketfd, new_addrinfo->ai_addr, new_addrinfo->ai_addrlen); if (result == -1) continue; is_connected = true; return; } if (total_ipv4_addrs == 0) { throw ConnectionException("Could not find IPv4 addresses to connect to " + address + " on port " + std::to_string(port) + "."); } throw ConnectionException("Could not connect to address " + address + " on port " + std::to_string(port) + ". Error: " + std::string(strerror(errno))); } void TCPSocket::listen(uint32_t backlog) { if (!is_bound) { throw SocketException("Can not listen when socket is not bound to any port"); } if (is_listening) { throw SocketException("Socket is already listening incoming connections on port " + std::to_string(port_used)); } int result = ::listen(socketfd, backlog); if (result == -1) { throw ConnectionException("Could not listen on port " + std::to_string(port_used) + ". Error: " + std::string(strerror(errno))); } is_listening = true; } std::shared_ptr TCPSocket::accept() { if (!is_listening) { throw SocketException("Socket is not listening to incoming connections to accept one"); } sockaddr client_address; socklen_t sin_size = sizeof(sockaddr); int clientfd = ::accept(socketfd, &client_address, &sin_size); if (clientfd == -1) { throw ConnectionException("Error while accepting a connection. Error: " + std::string(strerror(errno))); } addrinfo client_info; memset(&client_info, 0, sizeof(addrinfo)); client_info.ai_family = AF_INET; client_info.ai_socktype = SOCK_STREAM; client_info.ai_addr = &client_address; sockaddr_in* client_address_in = (sockaddr_in*)&client_address; std::string client_ip = std::string(::inet_ntoa(client_address_in->sin_addr)); return std::make_shared(clientfd, client_info, client_address_in->sin_port, client_ip, false, false, true); } void TCPSocket::send(const std::string& message, int flags) { send((uint8_t *) message.c_str(), message.length(), flags); } void TCPSocket::send(const uint8_t* message, int length, int flags) { if (is_listening || !is_connected) { throw SocketException("Can't send message from a socket that is not connected"); } int bytes_left = length; int bytes_sent = 0; const uint8_t* message_left; while (bytes_sent < length) { message_left = message + bytes_sent; int result = ::send(socketfd, message_left, bytes_left, flags | MSG_NOSIGNAL); if (result == -1) { throw ConnectionException("Could not send message. Error: " + std::string(strerror(errno))); } bytes_left -= result; bytes_sent += result; } } std::string TCPSocket::recv(uint64_t maxlen, int flags) { uint8_t* message = recv(&maxlen, flags); uint8_t* message_nt = (uint8_t *) malloc(maxlen+1); memcpy(message_nt, message, maxlen); message_nt[maxlen] = '\0'; std::string string_msg((char *) message_nt); free(message); if (message_nt != message) free(message_nt); return string_msg; } uint8_t* TCPSocket::recv(uint64_t* length, int flags) { if (is_listening || !is_connected) { throw SocketException("Can't receive message in a socket that is not connected"); } uint64_t maxlen = *length; uint8_t buffer[maxlen]; int result = ::recv(socketfd, buffer, maxlen, flags); if (result == -1) { throw ConnectionException("Could not receive message. Error: " + std::string(strerror(errno))); } if (result == 0) { is_connected = false; throw ClosedConnection("Client closed connection."); } uint8_t* message = (uint8_t *) malloc(result); memcpy(message, buffer, result); *length = result; return message; } void TCPSocket::close() { BaseSocket::close(); is_connected = false; is_listening = false; } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * UDPRECV * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ UDPRecv::UDPRecv(const std::string& name, const std::string& address, const std::string& msg, uint32_t port) : name(name), address(address), msg(msg), port(port) { } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * UDPSOCKET * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ UDPSocket::UDPSocket(int flags) : BaseSocket(SOCK_DGRAM, flags) { int broadcast_enable = 1; int ret = setsockopt(socketfd, SOL_SOCKET, SO_BROADCAST, &broadcast_enable, sizeof(broadcast_enable)); } void UDPSocket::sendto(const std::string& address, uint32_t port, const std::string& message, int flags) { int msg_length = message.length(); int bytes_left = msg_length; int bytes_sent = 0; const char* cMessage = message.c_str(); socklen_t server_length; sockaddr_in server_address; hostent *server; /* build the server's Internet address */ ::memset(&server_address, 0, sizeof(server_address)); server_address.sin_family = AF_INET; if (!validateIpAddress(address)) { server = ::gethostbyname(address.c_str()); if (server == NULL) { throw ConnectionException("No such host as " + address); } ::memcpy(server->h_addr, &server_address.sin_addr.s_addr, server->h_length); } else { ::inet_pton(AF_INET, address.c_str(), &(server_address.sin_addr)); } server_address.sin_port = ::htons(port); server_length = sizeof(server_address); while (bytes_sent < msg_length) { const char* message_left = cMessage + bytes_sent; int result = ::sendto(socketfd, message_left, bytes_left, flags | MSG_NOSIGNAL, (sockaddr*) &server_address, server_length); if (result == -1) { throw ConnectionException("Could not send message. Error: " + std::string(strerror(errno))); } bytes_left -= result; bytes_sent += result; } } UDPRecv UDPSocket::recvfrom(uint64_t maxlen, int flags) { sockaddr_in client_address; hostent* client_info; socklen_t clientLength = sizeof(client_address); char buffer[maxlen+1]; int result = ::recvfrom(socketfd, buffer, maxlen, flags, (sockaddr *) &client_address, &clientLength); if (result == -1) { throw ConnectionException("Could not receive message. Error: " + std::string(strerror(errno))); } buffer[result] = '\0'; std::string host_name("Nao importa mais"); std::string host_address(::inet_ntoa(client_address.sin_addr)); std::string message(buffer); int port = ::ntohs(client_address.sin_port); return UDPRecv(host_name, host_address, message, port); } 0 #include #include #include #include #include #include #include #include #include #include TEST(Torsten, ode_signature) { static_assert(torsten::is_std_ode::value, "Wrong ODE signature"); static_assert(!torsten::is_std_ode::value, "Wrong ODE signature"); static_assert(torsten::is_eigen_ode, std::vector, std::vector>::value, "Wrong ODE signature"); static_assert(torsten::is_eigen_ode, std::vector, std::vector>::value, "Wrong ODE signature"); static_assert(!torsten::is_eigen_ode, std::vector, std::vector>::value, "Wrong ODE signature"); torsten::std_ode ode1; torsten::eigen_ode, std::vector, std::vector> ode2; } TEST(Torsten, ode_variadic_and_tuple_functor) { using torsten::dsolve::TupleOdeFunc; using torsten::dsolve::VariadicOdeFunc; Eigen::Matrix y_var(2); y_var << 1.0, 0.5; std::vector theta_var(1); theta_var[0] = 0.15; std::vector x_r; std::vector x_i; double t = 1.0; harm_osc_ode_fun_eigen f0; auto y0 = f0(t, y_var, nullptr, theta_var, x_r, x_i); VariadicOdeFunc f1(f0, t, y_var, nullptr); auto y1 = f1(theta_var, x_r, x_i); auto theta_tuple = std::make_tuple(theta_var, x_r, x_i); TupleOdeFunc f(f0); auto y2 = f(1.0, y_var, nullptr, theta_tuple); torsten::test::test_grad(theta_var, y0, y1, 1.e-10, 1.e-10); torsten::test::test_grad(theta_var, y0, y2, 1.e-10, 1.e-10); std::vector y(stan::math::to_array_1d(y_var)); torsten::test::test_grad(y, y0, y1, 1.e-10, 1.e-10); torsten::test::test_grad(y, y0, y2, 1.e-10, 1.e-10); } struct Func { template Eigen::Matrix, -1, 1> operator()(const T0& t, const Eigen::Matrix& x, const std::vector& parms, const std::vector& x_r, const std::vector& x_i, std::ostream* pstream__) const { typedef typename stan::return_type::type scalar; return Eigen::Matrix(2); } }; TEST(Torsten, ode_ostream_arg_placement_adaptor) { static_assert(torsten::pmx_ode_ostream_not_adapted::value, "Wrong ODE ostream argument location"); static_assert(!torsten::pmx_ode_ostream_adapted::value, "Wrong ODE ostream argument location"); static_assert(torsten::pmx_ode_ostream_adapted::value, "Wrong ODE ostream argument location"); static_assert(!torsten::pmx_ode_ostream_not_adapted::value, "Wrong ODE ostream argument location"); } // Copyright (c) 2013-2020 // License: Academic Free License ("AFL") v. 3.0 // AFL License page: https://opensource.org/licenses/AFL-3.0 #pragma once #include #include #include #include namespace hg::Database { struct User { std::uint32_t id; std::uint64_t steamId; std::string name; std::vector passwordHash; }; struct LoginToken { std::uint32_t id; std::uint32_t userId; std::uint64_t timestamp; std::uint64_t token; }; struct Score { std::uint32_t id; std::string levelValidator; std::uint64_t timestamp; std::uint64_t userSteamId; double value; }; struct ProcessedScore // not stored in database { sf::Uint32 position; std::string userName; sf::Uint64 scoreTimestamp; double scoreValue; }; } // namespace hg::Database //kTerminalServices.cpp // Copyright Querysoft Limited 2013 // // 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 "WinQAPI/Kernel32.h" #include "ReturnCheck.h" //-------------------------------------------------------------------------------- namespace nsWinQAPI { //-------------------------------------------------------------------------------- BOOL CKernel32::ProcessIdToSessionId( DWORD dwProcessId, DWORD* pSessionId ) { _WINQ_SFCONTEXT( "CKernel32::ProcessIdToSessionId" ); CCheckReturn< BOOL, CBoolCheck<> >::TType bResult; bResult = ::ProcessIdToSessionId( dwProcessId, pSessionId ); return bResult; } //-------------------------------------------------------------------------------- BOOL CKernel32::TermsrvAppInstallMode(void) { _WINQ_SFCONTEXT( "CKernel32::TermsrvAppInstallMode" ); CCheckReturn< BOOL, CBoolCheck<> >::TType bResult; # if ( _WIN32_WINNT >= 0x0502 ) //::TermsrvAppInstallMode(); # else # endif return bResult; } //-------------------------------------------------------------------------------- DWORD CKernel32::WTSGetActiveConsoleSessionId(void) { _WINQ_SFCONTEXT( "CKernel32::WTSGetActiveConsoleSessionId" ); DWORD dwResult = 0; # if( _WIN32_WINNT >= 0x0501 ) dwResult = ::WTSGetActiveConsoleSessionId(); # else __WINQAPI_CONT_ERROR(( API_REQUIRES_VERSION, _T( "WTSGetActiveConsoleSessionId" ), _T( "Windows XP" ), 0 )); # endif return dwResult; } }//nsWinQAPI /*! @file pitts_performance.hpp * @brief Helper functionality for measuring the performance of C++ functions / scopes * @author <> * @date 2020-05-08 * @copyright Deutsches Zentrum fuer Luft- und Raumfahrt e. V. (DLR), German Aerospace Center * **/ // include guard #ifndef PITTS_PERFORMANCE_HPP #define PITTS_PERFORMANCE_HPP // includes #include "pitts_parallel.hpp" #include "pitts_kernel_info.hpp" #include "pitts_timer.hpp" #include #include #include #include #include //! namespace for the library PITTS (parallel iterative tensor train solvers) namespace PITTS { //! namespace for helper functionality namespace internal { //! helper for accumulating timings and storing required flops/bytes per call struct PerformanceStatistics final { //! measured run-time data TimingStatistics timings; //! theoretical information on required operations and data transfers kernel_info::KernelInfo kernel; //! number of processing units involved (e.g. MPI processes) int nProcs = 1; //! allow reading/writing with cereal template void serialize(Archive & ar) { ar( CEREAL_NVP(timings), CEREAL_NVP(kernel), CEREAL_NVP(nProcs) ); } }; //! helper type for storing timings with performance data per function / scope and per argumen using PerformanceStatisticsMap = std::unordered_map; //! combine timings with different arguments for each function inline TimingStatisticsMap combineTimingsPerFunction(const PerformanceStatisticsMap& performanceStats) { TimingStatisticsMap timingStats; for(const auto& [scopeWithArgs, performanceData]: performanceStats) { timingStats[scopeWithArgs.scope] += performanceData.timings; } // call counts are more tricky as we allow multiple "sub-scopes" in a single function // for a more detailed performance analysis with low overhead (during measurement) // so replace call counts by corrected call counts std::unordered_map functionCallCounts; // sum up "weighted" function call counts (divided by number of "sub-scopes" per function) for(const auto& [scopeWithArgs, performanceData]: performanceStats) { functionCallCounts[scopeWithArgs.scope] += 1./scopeWithArgs.callsPerFunction * performanceData.timings.calls; } // replace call counts with corrected data for(const auto& [scope, calls]: functionCallCounts) { timingStats[scope].calls = std::lround(calls); } return timingStats; } //! helper type for performance results with a name struct NamedPerformance final { //! description (function name, parameters, etc) std::string name; //! performance results PerformanceStatistics performance; }; //! gather performance data in a vector, so they can be sorted and printed more easily inline auto gatherPerformance(const PerformanceStatisticsMap& map, bool mpiGlobal = true) { // copy to serializable map (ScopInfo is read-only) std::unordered_map namedMap; for(const auto& [scopeWithArgs, performance]: map) { const auto& scope = scopeWithArgs.scope; const auto& args = scopeWithArgs.args; std::string fullName; if( !std::string_view(scope.type_name()).empty() ) fullName = scope.type_name() + std::string("::"); fullName += scope.function_name(); fullName += "(" + args.to_string() + ")"; namedMap.insert({std::move(fullName),performance}); } if( mpiGlobal ) { // operator that only adds up timings const auto combineOp = [](const PerformanceStatistics& a, const PerformanceStatistics& b) { // check that kernel data matches!! if( a.kernel != b.kernel ) throw std::invalid_argument("Trying to combine timings of functions with different performance characteristics (Flops, Bytes)!"); return PerformanceStatistics{a.timings+b.timings, a.kernel, a.nProcs+b.nProcs}; }; namedMap = parallel::mpiCombineMaps(namedMap, combineOp); } std::vector result; result.reserve(namedMap.size()); for(const auto& [name, performance]: namedMap) result.emplace_back(NamedPerformance{name, performance}); return result; } } //! namespace for runtime measurement data of performance statistics (timings + #flops / data transfered) namespace performance { //! container for storing timings for different arguments with createScopedTimer inline internal::PerformanceStatisticsMap globalPerformanceStatisticsMap; //! Measure the runtime of the curent function or scope and gather performance statistics inline auto createScopedTimer(internal::FixedArgumentInfo arguments, kernel_info::KernelInfo kernel, double callsPerFunction = 1, internal::ScopeInfo scope = internal::ScopeInfo::current()) { const internal::ScopeWithArgumentInfo scopeArgs{scope, arguments, callsPerFunction}; const auto [iter, didInsert] = globalPerformanceStatisticsMap.insert({scopeArgs, {internal::TimingStatistics(), kernel}}); #ifndef PITTS_USE_LIKWID_MARKER_API return internal::ScopedTimer(iter->second.timings); #else return std::tuple{ iter->second.timings, scope.function_name()}; #endif } //! Measure the runtime of the curent function or scope and gather performance statistics (variant with template type information) template inline auto createScopedTimer(internal::FixedArgumentInfo arguments, kernel_info::KernelInfo kernel, double callsPerFunction = 1, internal::ScopeInfo scope = internal::ScopeInfo::template current()) { return createScopedTimer(arguments, kernel, callsPerFunction, scope); } //! print nice statistics using globalPerformanceStatisticsMap inline void printStatistics(bool clear = true, std::ostream& out = std::cout, bool mpiGlobal = true) { using internal::NamedPerformance; std::vector lines = internal::gatherPerformance(globalPerformanceStatisticsMap, mpiGlobal); // sort by decreasing time std::sort(lines.begin(), lines.end(), [](const NamedPerformance& l1, const NamedPerformance& l2){return l1.performance.timings.totalTime > l2.performance.timings.totalTime;}); // get maximal length of the name string const auto maxDescLen = std::accumulate(lines.begin(), lines.end(), 10, [](std::size_t n, const NamedPerformance& l){return std::max(n, l.name.size());}); // prevent output on non-root with mpiGlobal == true (but omit mpiProcInfo call when mpiGlobal == false) bool doOutput = true; if( mpiGlobal ) { const auto& [iProc,nProcs] = internal::parallel::mpiProcInfo(); doOutput = iProc == 0; } if( doOutput ) { // actual output out << "Performance statistics:\n"; out << std::left; out << std::setw(maxDescLen) << "function" << "\t " << std::setw(10) << "time [s]" << "\t " << std::setw(10) << "#calls" << "\t " << std::setw(10) << "GFlop/s DP" << "\t " << std::setw(10) << "GFlop/s SP" << "\t " << std::setw(10) << "GByte/s" << "\t" << std::setw(10) << "Flops/Byte" << "\n"; for(const auto& line: lines) { const auto& timings = line.performance.timings; const auto& nProcs = line.performance.nProcs; const auto& flops = line.performance.kernel.flops; const auto& bytes = line.performance.kernel.bytes; out << std::setw(maxDescLen) << line.name << "\t " << std::setw(10) << timings.totalTime/nProcs << "\t " << std::setw(10) << std::lround(timings.calls*1.0/nProcs) << "\t " << std::setw(10) << timings.calls*flops.doublePrecision/(timings.totalTime/nProcs)*1.e-9 << "\t " << std::setw(10) << timings.calls*flops.singlePrecision/(timings.totalTime/nProcs)*1.e-9 << "\t " << std::setw(10) << timings.calls*(2*bytes.update+bytes.load+bytes.store)/(timings.totalTime/nProcs)*1.e-9 << "\t " << std::setw(10) << (flops.doublePrecision+flops.singlePrecision) / (2*bytes.update+bytes.load+bytes.store) << "\n"; } } // also print timing statistics if( clear ) { timing::globalTimingStatisticsMap += combineTimingsPerFunction(globalPerformanceStatisticsMap); timing::printStatistics(true, out); globalPerformanceStatisticsMap.clear(); } else { // no clearing, need to restore globalTimingStatisticsMap after the call auto timingStatisticsMap = timing::globalTimingStatisticsMap; timing::globalTimingStatisticsMap += combineTimingsPerFunction(globalPerformanceStatisticsMap); timing::printStatistics(false, out); std::swap(timingStatisticsMap, timing::globalTimingStatisticsMap); } } } } #endif // PITTS_PERFORMANCE_HPP mn/src/mn/Pool.cpp #include "mn/Pool.h" #include "mn/Memory.h" #include "mn/OS.h" namespace mn { struct IPool { Allocator meta_allocator; Allocator arena; void* head; size_t element_size; }; Pool pool_new(size_t element_size, size_t bucket_size, Allocator meta_allocator) { Pool self = alloc_from(meta_allocator); if(element_size < sizeof(void*)) element_size = sizeof(void*); self->meta_allocator = meta_allocator; self->arena = allocator_arena_new(element_size * bucket_size, meta_allocator); self->head = nullptr; self->element_size = element_size; return self; } void pool_free(Pool self) { if (self == nullptr) return; allocator_free(self->arena); free_from(self->meta_allocator, self); } void* pool_get(Pool self) { if(self->head != nullptr) { void* result = self->head; self->head = (void*)(*(uintptr_t*)self->head); return result; } return alloc_from(self->arena, self->element_size, alignof(char)).ptr; } void pool_put(Pool self, void* ptr) { #ifdef DEBUG auto arena = (memory::Arena*) self->arena; mn_assert_msg(arena->owns(ptr), "pool does not own this pointer, you can only call pool_put on pointers returned by this instance's pool_get"); #endif #if MN_POOL_DOUBLE_FREE { auto it = self->head; while(it) { if (it == ptr) panic("pool double free found"); uintptr_t* sptr = (uintptr_t*)it; it = (void*)*sptr; } } #endif uintptr_t* sptr = (uintptr_t*)ptr; *sptr = (uintptr_t)self->head; self->head = ptr; } }pcwalton/rust-bindgen // bindgen-flags: --allowlist-function 'Servo_.*' --blocklist-type Test --raw-line "pub enum Test {}" struct Test {}; extern "C" void Servo_Test(Test* a); 10-100 // // Created by Sergey on 20.10.2019. // #ifndef REGISTERS_CRITICALSECTIONCONFIG_HPP #define REGISTERS_CRITICALSECTIONCONFIG_HPP #include "criticalsectionguard.hpp" //for CriticalSectionGuard #include "criticalsectiondefault.hpp" //for CriticalSectionDefault using CriticalSection = CriticalSectionGuard ; #endif //REGISTERS_CRITICALSECTIONDEFAULTCONFIG_HPP #include using namespace std; using ll = long long; using ld = long double; #define fast ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); #define pb push_back #define type make_pair #define F first #define S second #define int long long int #define endl "\n" #define ALL(v) v.begin(),v.end() #define ALLR(v) v.rbegin(),v.rend() #define pii 3.14159265358979323 #define inf LLONG_MAX #define ones(x) __builtin_popcount(x) #define fill(a,b) memset(a,b,sizeof(a)) #define mod1 1000000007 #define mod2 998244353 ll mod_pow(ll a,ll b,ll m) { ll res = 1; while(b) { if(b&1) { res=(res*a) % m; } a=(a*a) % m; b>>=1; } return res; } ll mod_inverse(int a , int m) { return mod_pow(a , m - 2 , m); } void solve() { int n; cin >> n; map odd , even; int a[n]; int b[n]; for(int i = 0; i < n; ++i) { cin >> a[i]; odd[ a[i] ] = i; } for(int i = 0; i < n; ++i) { cin >> b[i]; even[ b[i] ] = i; } int mi = odd[1]; int res = inf; for(int i = 2; i <= 2 * n; i += 2) { res = min(res , even[i] + mi); mi = min(mi , odd[i + 1]); } cout << res << endl; } signed main() { fast; int t = 1; cin >> t; while(t--) { solve(); } return 0; }/* * Copyright (c) 2021 Huawei Device 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 "runtime/include/object_header.h" #include "runtime/include/coretypes/array.h" #include "runtime/include/coretypes/class.h" #include "runtime/include/runtime.h" #include "runtime/include/thread.h" #include "runtime/include/panda_vm.h" #include "runtime/mem/vm_handle.h" #include "runtime/monitor_pool.h" #include "runtime/handle_base-inl.h" namespace panda { /* static */ ObjectHeader *ObjectHeader::CreateObject(panda::BaseClass *klass, bool non_movable) { #ifndef NDEBUG if (!klass->IsDynamicClass()) { auto cls = static_cast(klass); ASSERT(cls->IsInstantiable()); ASSERT(!cls->IsArrayClass()); ASSERT(!cls->IsStringClass()); } #endif size_t size = klass->GetObjectSize(); ASSERT(size != 0); mem::HeapManager *heap_manager = Thread::GetCurrent()->GetVM()->GetHeapManager(); ObjectHeader *obj {nullptr}; if (LIKELY(!non_movable)) { obj = heap_manager->AllocateObject(klass, size); } else { obj = heap_manager->AllocateNonMovableObject(klass, size); } return obj; } /* static */ ObjectHeader *ObjectHeader::Create(BaseClass *klass) { return CreateObject(klass, false); } /* static */ ObjectHeader *ObjectHeader::CreateNonMovable(BaseClass *klass) { return CreateObject(klass, true); } bool ObjectHeader::AtomicSetMark(MarkWord old_mark_word, MarkWord new_mark_word) { // This is the way to operate with casting MarkWordSize <-> MarkWord and atomics auto ptr = reinterpret_cast(&markWord_); auto atomic_ptr = reinterpret_cast *>(ptr); return atomic_ptr->compare_exchange_weak(old_mark_word, new_mark_word); } uint32_t ObjectHeader::GetHashCodeFromMonitor(Monitor *monitor_p) { if (monitor_p->GetHashCode() == 0) { Monitor::MonitorEnter(this); // We check it again in case someone changed it before we aquire monitor if (monitor_p->GetHashCode() == 0) { monitor_p->SetHashCode(GenerateHashCode()); } Monitor::MonitorExit(this); } return monitor_p->GetHashCode(); } uint32_t ObjectHeader::GetHashCode() { while (true) { auto mark = this->AtomicGetMark(); switch (mark.GetState()) { case MarkWord::STATE_UNLOCKED: { auto hash_mark = mark.DecodeFromHash(GenerateHashCode()); ASSERT(hash_mark.GetState() == MarkWord::STATE_HASHED); this->AtomicSetMark(mark, hash_mark); break; } case MarkWord::STATE_LIGHT_LOCKED: { // Futexes and has support for locking with non-current thread. auto thread = MTManagedThread::GetCurrent(); // Try to inflate and if it fails, wait a bit before trying again. if (!Monitor::Inflate(this, thread)) { static constexpr uint64_t SLEEP_MS = 10; MTManagedThread::Sleep(SLEEP_MS); } break; } case MarkWord::STATE_HEAVY_LOCKED: { auto monitor_id = mark.GetMonitorId(); auto monitor_p = MonitorPool::LookupMonitor(Thread::GetCurrent()->GetVM(), monitor_id); if (monitor_p != nullptr) { return GetHashCodeFromMonitor(monitor_p); } LOG(FATAL, RUNTIME) << "Error on GetHashCode(): no monitor on heavy locked state"; break; } case MarkWord::STATE_HASHED: { return mark.GetHash(); } default: { LOG(FATAL, RUNTIME) << "Error on GetHashCode(): invalid state"; } } } } ObjectHeader *ObjectHeader::Clone(ObjectHeader *src) { LOG_IF(src->ClassAddr()->GetManagedObject() == src, FATAL, RUNTIME) << "Can't clone a class"; return ObjectHeader::ShallowCopy(src); } ObjectHeader *ObjectHeader::ShallowCopy(ObjectHeader *src) { auto object_class = src->ClassAddr(); std::size_t obj_size = src->ObjectSize(); // AllocateObject can trigger gc, use handle for src. auto thread = ManagedThread::GetCurrent(); mem::HeapManager *heap_manager = thread->GetVM()->GetHeapManager(); [[maybe_unused]] HandleScope scope(thread); VMHandle src_handle(thread, src); ObjectHeader *dst = nullptr; // Determine whether object is non-movable if (PoolManager::GetMmapMemPool()->GetSpaceTypeForAddr(src) == SpaceType::SPACE_TYPE_NON_MOVABLE_OBJECT) { dst = heap_manager->AllocateNonMovableObject(object_class, obj_size); } else { dst = heap_manager->AllocateObject(object_class, obj_size); } if (dst == nullptr) { return nullptr; } ASSERT(PoolManager::GetMmapMemPool()->GetSpaceTypeForAddr(src) == PoolManager::GetMmapMemPool()->GetSpaceTypeForAddr(dst)); Span src_sp(reinterpret_cast(src_handle.GetPtr()), obj_size); Span dst_sp(reinterpret_cast(dst), obj_size); constexpr const std::size_t WORD_SIZE = sizeof(uintptr_t); std::size_t bytes_to_copy = obj_size - ObjectHeader::ObjectHeaderSize(); std::size_t words_to_copy = bytes_to_copy / WORD_SIZE; std::size_t remaining_offset = ObjectHeader::ObjectHeaderSize() + WORD_SIZE * words_to_copy; // copy words for (std::size_t i = ObjectHeader::ObjectHeaderSize(); i < remaining_offset; i += WORD_SIZE) { reinterpret_cast *>(&dst_sp[i]) ->store(reinterpret_cast *>(&src_sp[i])->load(std::memory_order_relaxed), std::memory_order_relaxed); } // copy remaining bytes for (std::size_t i = remaining_offset; i < obj_size; i++) { reinterpret_cast *>(&dst_sp[i]) ->store(reinterpret_cast *>(&src_sp[i])->load(std::memory_order_relaxed), std::memory_order_relaxed); } // Call barriers here. auto *barrier_set = thread->GetVM()->GetGC()->GetBarrierSet(); // We don't need pre barrier here because we don't change any links inside main object // Post barrier auto gc_post_barrier_type = barrier_set->GetPostType(); if (!mem::IsEmptyBarrier(gc_post_barrier_type)) { if (object_class->IsArrayClass()) { if (object_class->IsObjectArrayClass()) { barrier_set->PostBarrierArrayWrite(dst, obj_size); } } else { barrier_set->PostBarrierEveryObjectFieldWrite(dst, obj_size); } } return dst; } size_t ObjectHeader::ObjectSize() const { auto *klass = ClassAddr(); if (klass->IsArrayClass()) { return static_cast(this)->ObjectSize(); } if (klass->IsStringClass()) { return static_cast(this)->ObjectSize(); } if (klass->IsClassClass()) { auto cls = panda::Class::FromClassObject(const_cast(this)); if (cls != nullptr) { return panda::Class::GetClassObjectSizeFromClass(cls); } } return klass->GetObjectSize(); } } // namespace panda Refer to Hash Maps LeetCode Questions repo 0 #include #include #include #include #include #include #include "third_party/gflags/include/gflags.h" #include "third_party/glog/include/logging.h" using std::min; using std::string; using std::swap; using std::vector; // Problems: https://leetcode.cn/problems/flip-string-to-monotone-increasing/ // DP class Solution { public: // dp[i][j]表示以数字j为结尾,[0, i]为单调递增需要翻转的最小次数 int minFlipsMonoIncr(string s) { int n = s.size(); vector > dp(n, vector(n, INT_MAX)); // 默认第一位为0时 dp[0][0] = 0, dp[0][1] = 1; // 如果第一位为1,则需要交换 if (s[0] == '1') { swap(dp[0][0], dp[0][1]); } for (int i = 1; i < n; ++i) { if (s[i] == '0') { // 以0为结尾,不需要翻转 dp[i][0] = dp[i - 1][0]; // 以1为结尾,当前位翻转一次,前缀串可以0或1结尾,取最小 dp[i][1] = min(dp[i - 1][0], dp[i - 1][1]) + 1; } else { // 以0为结尾,当前位翻转,并且前缀串必须以0结尾 dp[i][0] = dp[i - 1][0] + 1; // 以1结尾,不需要翻转,前缀串可以0或1结尾 dp[i][1] = min(dp[i - 1][0], dp[i - 1][1]); } } // 取两者情况之最小 return min(dp[n - 1][0], dp[n - 1][1]); } }; // 状态压缩 class Solution1 { public: int minFlipsMonoIncr(string s) { int n = s.size(); int dp0 = 0, dp1 = 1; if (s[0] == '1') { swap(dp0, dp1); } for (int i = 1; i < n; ++i) { // 临时变量保存,后面会被覆盖 int tmp1 = dp0, tmp2 = min(dp0, dp1); if (s[i] == '0') { dp1 = tmp2 + 1; } else { dp0 = dp0 + 1; dp1 = tmp2; } } return min(dp0, dp1); } }; int main(int argc, char* argv[]) { google::InitGoogleLogging(argv[0]); gflags::ParseCommandLineFlags(&argc, &argv, false); Solution solu; string s("001100"); int ret = solu.minFlipsMonoIncr(s); LOG(INFO) << ret; return 0; } src/Game/zRumble.cpp0 #include "zRumble.h"1-10 // $Id: StFmsClusterFitter.cxx,v 1.9 2018/03/26 15:55:37 akio Exp $ // // $Log: StFmsClusterFitter.cxx,v $ // Revision 1.9 2018/03/26 15:55:37 akio // removing some print outs // // Revision 1.8 2018/03/02 20:27:29 akio // Big update from Zhanwen Zhu with new shower shape and six z slices // // Revision 1.7 2018/01/04 17:35:44 smirnovd // [Cosmetic] Remove StRoot/ from include path // // $STAR/StRoot is already in the default path search // // Revision 1.6 2015/11/05 17:54:57 akio // Adding option to scale up shower shape function for large cells // // Revision 1.5 2015/10/30 21:33:56 akio // fix parameter initialization // adding new cluster categorization method // // Revision 1.4 2015/10/29 21:14:55 akio // increase max number of clusters // a bug fixes in valley tower association // removing some debug comments // // Revision 1.3 2015/10/21 15:58:04 akio // Code speed up (~x2) by optimizing minimization fuctions and showershape function // Add option to merge small cells to large, so that it finds cluster at border // Add option to perform 1photon fit when 2photon fit faield // Add option to turn on/off global refit // Moment analysis done without ECUTOFF when no tower in cluster exceed ECUTOFF=0.5GeV // // Revision 1.2 2015/09/02 15:01:32 akio // Removing StFmsGeometry class, and now it uses StFmsDbMaker to get appropriate parameters. // // Revision 1.1 2015/03/10 14:38:54 jeromel // First version of FmsUtil from Yuxi Pan - reviewd 2015/02 // /** \file StFmsClusterFitter.cxx \brief Implementation of StFmsClusterFitter, shower-shape fitting routine \author <> \author <> \author <> \date 2014 \copyright Brookhaven National Lab */ #include "StFmsClusterFitter.h" #include "StFmsDbMaker/StFmsDbMaker.h" #include // For std::max() #include #include #include #include #include "TF2.h" #include "TMath.h" #include "TString.h" #include "St_base/StMessMgr.h" #include "StEvent/StFmsHit.h" //#include "StFmsGeometry.h" #include "StFmsTower.h" #include "StFmsConstant.h" namespace { const Int_t kMaxNPhotons = 7; // Maximum number of photons that can be fitted int mshowershapewithangle=1;// for static func int mmerge=1;// for static func int vertexz=0; void setOption(int v1, int v2 , double v3){ mshowershapewithangle=v1; mmerge=v2; vertexz=v3; } //Yuxi's double unused=0.0; double a11=0.998438; double a12=0.222782; double a13=-0.22122;double b11=0.177028;double b12=0.000473222;double b13=0.178897;double w1 = 0.0372556; double a21=1.07711 ; double a22=-0.0281385;double a23=-0.0489747;double b21=0.199964;double b22=3.5021;double b23=2.35246;double w2 = 0.202699; double a31=1.07901 ; double a32=0.0650143; double a33=-0.144025;double b31=0.446845;double b32=0.00544512;double b33=1.64565;double w3 = 0.293878; double a41=0.922174; double a42=0.0778254; double a43=1.07474e-07;double b41=0.593804;double b42=0.6199;double b43=3.49798;double w4 = 0.236854; double a51=0.999849; double a52=0.000151185;double a53=2.20244e-07;double b51=0.949953;double b52=1.84451;double b53=3.40799;double w5 = 0.146041; double a61=0.997454; double a62=0.00254497;double a63=1.02127e-06;double b61=1.43387;double b62=2.91155;double b63=3.4484;double w6 = 0.0832717; //Zhanwen's small 45GeV new double a1S[6]={0.0303644,0.212191,0.277429,0.0370035,0.0524404,0.00844062}; double a2S[6]={0.00122867,0.105355,0.10538,0.152656,0.00664331,0.0108688}; double b1S[6]={0.403493,0.514546,0.672826,1.82344,0.727991,1.48785}; double b2S[6]={0.270492,0.514593,0.672655,0.644871,4.32003,0.25}; //large 45GeV new double a1L[6]={0.0275364,0.200363,0.277157,0.0391611,0.0590757,0.0101089}; double a2L[6]={0.000429808,0.0991777,0.104781,0.161916,0.00764026,0.012653}; double b1L[6]={0.515974,0.661722,0.865167,2.35237,0.932038,1.87933}; double b2L[6]={0.53531,0.661519,0.865226,0.828017,5.49041,0.321139}; double a1[6]={0. , 0 , 0. , 0. , 0. , 0. }; double a2[6]={0. , 0 , 0. , 0. , 0. , 0. }; double b1[6]={0. , 0. , 0. , 0. , 0. , 0. }; double b2[6]={0. , 0. , 0. , 0. , 0. , 0. }; double a3[6]={0. , 0 , 0. , 0. , 0. , 0. }; double b3[6]={0. , 0. , 0. , 0. , 0. , 0. }; double w[6]={1. , 1. , 1. , 1. , 1. , 1. }; std::array fitParameters; void clear_fitParameters(){ for (int i=0 ; i<60 ; i++) { fitParameters[i]=0 ; } } void choose_fitParameters(int detID){ if (detID<=9) {unused=5;} //large cell else {unused=3;} //small cell if ( mshowershapewithangle==2 ) { fitParameters= {unused, a11, a12, a13, b11, b12, b13, w1 ,unused, unused, unused, a21, a22, a23, b21, b22, b23, w2 ,unused, unused, unused, a31, a32, a33, b31, b32, b33, w3 ,unused, unused, unused, a41, a42, a43, b41, b42, b43, w4 ,unused, unused, unused, a51, a52, a53, b51, b52, b53, w5 ,unused, unused, unused, a61, a62, a63, b61, b62, b63, w6 ,unused, unused }; } else if ( mshowershapewithangle==1 ) { if (detID>9) {//small cell for (int i=0 ; i<6 ; i++) { a1[i]=a1S[i]; a2[i]=a2S[i]; b1[i]=b1S[i]; b2[i]=b2S[i]; } }else{//large cell for (int i=0 ; i<6 ; i++) { a1[i]=a1L[i]; a2[i]=a2L[i]; b1[i]=b1L[i]; b2[i]=b2L[i]; } } fitParameters= { unused, a1[0], a2[0], a3[0], b1[0], b2[0], b3[0], w[0] ,unused, unused, unused, a1[1], a2[1], a3[1], b1[1], b2[1], b3[1], w[1] ,unused, unused, unused, a1[2], a2[2], a3[2], b1[2], b2[2], b3[2], w[2] ,unused, unused, unused, a1[3], a2[3], a3[3], b1[3], b2[3], b3[3], w[3] ,unused, unused, unused, a1[4], a2[4], a3[4], b1[4], b2[4], b3[4], w[4] ,unused, unused, unused, a1[5], a2[5], a3[5], b1[5], b2[5], b3[5], w[5] ,unused, unused}; }else if( mshowershapewithangle==0 ) { fitParameters[1] = SS_A1; fitParameters[2] = SS_A2; fitParameters[3] = SS_A3; fitParameters[4] = SS_B1; fitParameters[5] = SS_B2; fitParameters[6] = SS_B3; } } TF2 showerShapeFitFunction("showerShapeFitFunction", &FMSCluster::StFmsClusterFitter::energyDepositionInTower, -25.0, 25.0, -25.0, 25.0, fitParameters.size()); /* Compose Minuit step size in each fit variable. The first value is for the number of photons. Each subsequent triplet is for the (x, y, E) of a photon, up to kMaxNPhotons. */ std::vector defaultMinuitStepSizes() { std::vector steps(1, 0.); // Initialise with nPhoton step // Append default (x, y, E) steps for each photon for (int i(0); i < kMaxNPhotons; ++i) { steps.insert(steps.end(), {0.1, 0.1, 0.2}); } // for return steps; } std::vector towerWidths; // Tower (x, y) width in cm // Helper function for accumulating tower energies double addTowerEnergy(double energy, const FMSCluster::StFmsTower* tower) { return energy + tower->hit()->energy(); } } // unnamed namespace namespace FMSCluster { // Instantiate static members StFmsTowerCluster::Towers* StFmsClusterFitter::mTowers(nullptr); Double_t StFmsClusterFitter::mEnergySum(0.0); StFmsClusterFitter::StFmsClusterFitter( //const StFmsGeometry* geometry, Int_t detectorId, Float_t xw, Float_t yw, Int_t scaleShowerShape , Int_t ShowerShapeWithAngle, Int_t MergeSmallToLarge, double vertexZ) : mMinuit(3 * kMaxNPhotons + 1), mScaleShowerShape(scaleShowerShape), mShowerShapeWithAngle( ShowerShapeWithAngle) , mMergeSmallToLarge(MergeSmallToLarge) { // Set tower (x, y) widths for this detector towerWidths.clear(); towerWidths.push_back(xw); towerWidths.push_back(yw); setOption(mShowerShapeWithAngle,mMergeSmallToLarge ,vertexZ); clear_fitParameters(); choose_fitParameters(detectorId); showerShapeFitFunction.SetParameters(fitParameters.data()); mMinuit.SetPrintLevel(-1); // Quiet, including suppression of warnings (change to 0 for more info) } StFmsClusterFitter::~StFmsClusterFitter() { } TF2* StFmsClusterFitter::showerShapeFunction() { return &showerShapeFitFunction; } Double_t StFmsClusterFitter::fitNPhoton(const std::vector& parameters, const std::vector& steps, const std::vector& lower, const std::vector& upper, PhotonList* photons) { Double_t chiSquare(-1.); // Return value // Check that there is a pointer to TObjArray of towers if (!StFmsClusterFitter::mTowers) { LOG_ERROR << "no tower data available! return -1!" << endm; return chiSquare; } // if mMinuit.SetFCN(minimizationFunctionNPhoton); int nPhotons = parameters.size() / 3; if (nPhotons < 1 || nPhotons > kMaxNPhotons) { LOG_ERROR << "Number of photons must be between 1 and " << kMaxNPhotons << "not " << nPhotons << " for fit. Setting it to be 1..." << endm; nPhotons = 1; } // if mMinuit.mncler(); // Clear old parameters so we can define the new parameters // The first parameter tells Minuit how many photons to fit! // It should be a fixed parameter, and between 1 and the max number of photons setMinuitParameter(0, "nph", parameters, steps, lower, upper); // Set the rest of parameters: 3 parameters per photon for (Int_t i = 0; i < nPhotons; i++) { Int_t j = 3 * i + 1; // Need to set 3 parameters per photon setMinuitParameter(j++, Form("x%d", i), parameters, steps, lower, upper); setMinuitParameter(j++, Form("y%d", i), parameters, steps, lower, upper); setMinuitParameter(j++, Form("E%d", i), parameters, steps, lower, upper); } // if //ZZ never change energy!!!!! if (nPhotons==1) {mMinuit.FixParameter(3) ; } // fix Energy during 1P fit if (nPhotons==2) {mMinuit.FixParameter(3) ; mMinuit.FixParameter(6); } // fix Energy during 2P fit runMinuitMinimization(); // Populate the list of photons from the fit results if (mMinuit.GetStatus() == 0) { // Get the fit results and errors std::vector params(parameters.size(), 0.); std::vector errors(parameters.size(), 0.); readMinuitParameters(params, errors); for (unsigned i(1); i < parameters.size(); i += 3) { photons->emplace_back(params.at(i), params.at(i + 1), params.at(i + 2)); } // for // Evaluate chi-square (*not* chi-square per degree of freedom) mMinuit.Eval(photons->size(), nullptr, chiSquare, params.data(), 1); } // for return chiSquare; } Double_t StFmsClusterFitter::fitNPhoton(const std::vector& parameters, const std::vector& lower, const std::vector& upper, PhotonList* photons) { return fitNPhoton(parameters, defaultMinuitStepSizes(), lower, upper, photons); } /* A different set of parameters for 2-photon clusters only: 0: still a constant parameter, should be set to 2 for 2-photon fitting 1: xPi, x-position of pi^0 2: yPi, y-position of pi^0 3: d_gg, distance between 2 photons 4: theta, angle of displacement vector from photon 2 to photon 1 5: z_gg, can go from -1 to +1, so we do not set E1 > E2 6: E_gg, total energy of two photons Thus, in the more conventional fitNPhoton() parameterization: E1 = E_gg * (1 + z_gg) / 2 E2 = E_gg * (1 - z_gg) / 2 x1 = xPi + cos(theta) * d_gg * (1 - z_gg) / 2 y1 = yPi + sin(theta) * d_gg * (1 - z_gg) / 2 x2 = xPi - cos(theta) * d_gg * (1 + z_gg) / 2 y2 = yPi - sin(theta) * d_gg * (1 + z_gg) / 2 The advantage of this parameterization is that for 2-photon cluster fitting we can ensure that the two photons never get to close. The old parameterization suffers from this shortcoming if we let the parameters vary freely. What we already know about the limits of the new parameters: xPi and yPi: rarely do they go beyond 0.3 unit of lgd theta: have a narrow theta range (for r = sigmaMax / sigmaMax, |theta| < 0.5 * r / 0.65 when r < 0.65, and linear increase from 0.5 to pi/2 for 0.65 < r < 1) E_gg: given by Ec (+/- 20% or less) z_gg: should just let it vary from -1 to 1 d_gg: a lower bound is given by r = sqrt(sigmaX^2 + sigmaY^2). d_gg > Max(2.5 * (r - 0.6), 0.5) */ Int_t StFmsClusterFitter::fit2Photon(const std::array& parameters, const std::array& steps, const std::array& lower, const std::array& upper, PhotonList* photons) { Double_t chiSquare(-1.); // Return value if (!StFmsClusterFitter::mTowers) { LOG_ERROR << "no tower data available! return -1!" << endm; return chiSquare; } // if mMinuit.SetFCN(minimizationFunction2Photon); mMinuit.mncler(); // Clear old parameters so we can define the new parameters const std::vector names = { "nph", "xPi", "yPi", "d_gg", "theta", "z_gg", "E_gg" }; for (unsigned i = 0; i < names.size(); ++i) { setMinuitParameter(i, names.at(i), parameters, steps, lower, upper); } // for // Fix E_total and theta, we don't want these to be free parameters mMinuit.FixParameter(4); mMinuit.FixParameter(6); runMinuitMinimization(); if (mMinuit.GetStatus() == 0) { // Get the fit results for starting positions and errors // 3 * nPhotons + 1 parameters = 7 for 2 photons std::vector param(parameters.size(), 0.); std::vector error(parameters.size(), 0.); readMinuitParameters(param, error); // Put the fit result back in "clust". Need to translate the special // parameters for 2-photon fit into x, y, E, which looks a bit complicated! // First photon double x = param[1] + cos(param[4]) * param[3] * (1 - param[5]) / 2.0; double y = param[2] + sin(param[4]) * param[3] * (1 - param[5]) / 2.0; double E = param[6] * (1 + param[5]) / 2.0; photons->emplace_back(x, y, E); // Second photon x = param[1] - cos(param[4]) * param[3] * (1 + param[5]) / 2.0; y = param[2] - sin(param[4]) * param[3] * (1 + param[5]) / 2.0; E = param[6] * (1 - param[5]) / 2.0; photons->emplace_back(x, y, E); // Evaluate the chi-square function mMinuit.Eval(7, nullptr, chiSquare, param.data(), 1); } // if return chiSquare; } Double_t StFmsClusterFitter::energyDepositionInTower(Double_t* xy, Double_t* parameters) { // Calculate the energy deposited in a tower by evaluating // energyDepositionDistribution() at x+/-d/2 and y+/-d/2, for tower // width d. The double-loop below is equivalent to // F(x+d/2, y+d/2) + F(x-d/2, y-d/2) - F(x-d/2, y+d/2) - F(x+d/2, y-d/2) Double_t energy=0.0; if(mshowershapewithangle==0){ double w = parameters[0]; for (int ix = 0; ix < 2; ++ix) { for (int iy = 0; iy < 2; ++iy) { double signX = std::pow(-1., ix); // 1 or -1 double signY = std::pow(-1., iy); // 1 or -1 std::array s{ {xy[0] + signX * w / 2., // x +/- d/2 xy[1] + signY * w / 2.} }; // y +/- d/2 energy += signX * signY * energyDepositionDistribution(s.data(), parameters); } // for } // for //cout<<"we are calling the OLD energyDepositionInTower(Double_t* xy,Double_t* parameters"<4) { yoff=98.8; Zmax=735.45; xoff=0.3; Zc=ZcL; }else{ yoff=46.5; Zmax=735.45; xoff=0.93; Zc=ZcS; } if (mmerge >0) yoff=98.8; // large cells always 98.8 Double_t tany = ( yoff - xy[3]) / (Zmax - vertexz); Double_t tanx = ( xy[1]- xoff ) / (Zmax - vertexz); //ZZ just in case for(Int_t i = 0; i < 6; i++){ Double_t xc = xy[1] + tanx*(Zc[i] - Zmax); Double_t yc = xy[3] - tany*(Zc[i] - Zmax); //large (positive) tany corresponds to smaller row # (yc) Int_t istart = i*10; energy += energyDepositionInTowerSingleLayer(xy[0]-xc,xy[2]-yc,¶meters[istart]) * parameters[istart+7] ; } } return energy; } int StFmsClusterFitter::maxNFittedPhotons() { return kMaxNPhotons; } int StFmsClusterFitter::runMinuitMinimization() { std::vector arguments = {1000., 1.}; // Max calls and tolerance int errorFlag = -1; mMinuit.mnexcm("MIGRAD", arguments.data(), arguments.size(), errorFlag); // Free fixed parameters before next use of mMinuit. Wrap in if() to avoid // noisy warning messages in case of no fixed parameters. if (mMinuit.GetNumFixedPars() > 0) { mMinuit.mnfree(0); } // if return errorFlag; } // Calculate fractional photon energy deposition in a tower based on its (x, y) // position relative to the tower center Double_t StFmsClusterFitter::energyDepositionDistribution( Double_t* xy, Double_t* parameters) { double f = 0; // The parameter array has 10 elements, but we only use 6 here // 1 to 6 are a1, a2, a3, b1, b2, b3 as defined in // https://drupal.star.bnl.gov/STAR/blog/leun/2010/aug/02/fms-meeting-20100802 for (int i = 1; i < 4; i++) { // 1, 2, 3 f += showerShapeComponent(xy[0], xy[1], parameters[i], parameters[i + 3]); } // for return f / TMath::TwoPi();; } // Uses the signature needed for TMinuit interface: // http://root.cern.ch/root/htmldoc/TMinuit.html#TMinuit:SetFCN void StFmsClusterFitter::minimizationFunctionNPhoton(Int_t& npara, Double_t* grad, Double_t& fval, Double_t* para, Int_t /* not used */) { //mEnergySum was already calcurated in setTowers() //const double energySum = std::accumulate(mTowers->begin(), mTowers->end(),0., addTowerEnergy); fval = 0; // Stores sum of chi2 over each tower const int nPhotons = static_cast(para[0]); // for (auto i = mTowers->begin(); i != mTowers->end(); ++i) { for (auto i = mTowers->begin(), e = mTowers->end(); i!=e; ++i){ const StFmsTower* tower = *i; // The shower shape function expects the centers of towers in units of cm // Tower centers are stored in row/column i.e. local coordinates // Therefore convert to cm, remembering to subtract 0.5 from row/column to // get centres not edges /* Stop getting xy here. Already in tower StFmsTower class Double_t x, y; if(tower->hit()->detectorId()<10){ x = tower->column() - 0.5; y = tower->row() - 0.5; }else{ x = (tower->column()-0.5)*2.0/3.0; y = (tower->row() - 0.5)*2.0/3.0 + 9.0; } //const double x = towerWidths.at(0) * (tower->column() - 0.5); //const double y = towerWidths.at(1) * (tower->row() - 0.5); x *= towerWidths.at(0); y *= towerWidths.at(1); */ Double_t x=tower->x(); Double_t y=tower->y(); fitParameters.front() = tower->w(); // Add expected energy in tower from each photon, according to shower-shape double expected = 0; for (int j = 0; j < nPhotons; ++j) { // Recall there are 3 paras per photon int k = 3 * j; if(mshowershapewithangle>0 ){ expected += para[k + 3] * energyDepositionInTower(x , y ,para[k+1] , para[k+2], fitParameters.data(),mmerge,vertexz); } if(mshowershapewithangle==0 ){ expected += para[k + 3] * energyDepositionInTowerOLD(x - para[k + 1], y - para[k + 2], fitParameters.data()); } } //const double measured = tower->hit()->energy(); const double measured = tower->e(); const double deviation = measured - expected; // Larisa's chi2 function definition /* const Double_t err = 0.03 * pow(measured / energySum, 1. - 0.001 * energySum) * pow(1 - measured / energySum, 1. - 0.007 * energySum) * energySum + 0.01; */ const Double_t ratio = measured / mEnergySum; // const double err = 0.03 * measured * (1 - ratio) + 0.01; const Double_t err = 0.03 * pow(ratio, 1. - 0.001 * mEnergySum) * pow(1. - ratio, 1. - 0.007 * mEnergySum) * mEnergySum + 0.01; //fval += pow(deviation, 2.) / err; fval += deviation * deviation / err; //cout << Form("n=%1d x=%6.2f y=%6.2f e=%6.2f exp=%6.2f diff=%6.2f sum=%6.2f err=%6.2f fval=%6.2f", // nPhotons,x,y,measured,expected,deviation,mEnergySum,err,deviation*deviation/err)< oldParam{ { param[0], // Number of photons, unchanged param[1] + cos(angle) * dgg * (1 - zgg) / 2.0, // x 1 param[2] + sin(angle) * dgg * (1 - zgg) / 2.0, // y 1 param[6] * (1 + zgg) / 2.0, // Energy 1 param[1] - cos(angle) * dgg * (1 + zgg) / 2.0, // x 2 param[2] - sin(angle) * dgg * (1 + zgg) / 2.0, // y 2 param[6] * (1 - zgg) / 2.0 // Energy 2 } }; // Now call the regular minimization function with the translated parameters minimizationFunctionNPhoton(nparam, grad, fval, oldParam.data(), 0); } template int StFmsClusterFitter::setMinuitParameter(int index, const TString& name, const Container& params, const Container& steps, const Container& lower, const Container& upper) { int error = 0; mMinuit.mnparm(index, name, params.at(index), steps.at(index), lower.at(index), upper.at(index), error); return error; } int StFmsClusterFitter::readMinuitParameters(std::vector& parameters, std::vector& errors) { errors.resize(parameters.size(), 0.); for (int i = 0, size = parameters.size(); i != size; ++i) { mMinuit.GetParameter(i, parameters.at(i), errors.at(i)); } // for return parameters.size(); } void StFmsClusterFitter::setTowers(StFmsTowerCluster::Towers* towers) { mTowers = towers; mEnergySum = std::accumulate(mTowers->begin(), mTowers->end(), 0., addTowerEnergy); //if mScaleShowerShape is on, and if top cell is in large cell, scale shower shape up if(mScaleShowerShape ==1 && mShowerShapeWithAngle==0){ if(mTowers->front()->hit()->detectorId() <= 9){ fitParameters.at(4) = SS_B1*1.3; fitParameters.at(5) = SS_B2*1.3; fitParameters.at(6) = SS_B3*1.3; }else{ fitParameters.at(4) = SS_B1; fitParameters.at(5) = SS_B2; fitParameters.at(6) = SS_B3; } showerShapeFitFunction.SetParameters(fitParameters.data()); } } } // namespace FMSCluster /* * Copyright (C) 2011-2020 Intel Corporation. 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 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 OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include "QuoteGenerator.h" #include #include using namespace intel::sgx; namespace{ bool operator==(const qvl::test::QuoteGenerator::QuoteHeader& testHeader, const qvl::Quote::Header &header) { return (testHeader.attestationKeyType) == header.attestationKeyType && (testHeader.version) == header.version && (testHeader.qeSvn) == header.qeSvn && (testHeader.pceSvn) == header.pceSvn && testHeader.uuid == header.uuid && testHeader.userData == header.userData; } bool operator==(const qvl::test::QuoteGenerator::EnclaveReport& testReport, const qvl::Quote::EnclaveReport& report) { return testReport.attributes == report.attributes && testReport.cpuSvn == report.cpuSvn && (testReport.isvProdID) == report.isvProdID && (testReport.isvSvn) == report.isvSvn && (testReport.miscSelect) == report.miscSelect&& testReport.mrEnclave == report.mrEnclave && testReport.mrSigner == report.mrSigner && testReport.reportData == report.reportData && testReport.reserved1 == report.reserved1 && testReport.reserved2 == report.reserved2 && testReport.reserved3 == report.reserved3 && testReport.reserved4 == report.reserved4; } bool operator==(const qvl::test::QuoteGenerator::EcdsaSignature& testSig, const qvl::Quote::Ecdsa256BitSignature& sig) { return testSig.signature == sig.signature; } bool operator==(const qvl::test::QuoteGenerator::EcdsaPublicKey& testKey, const qvl::Quote::Ecdsa256BitPubkey& key) { return testKey.publicKey == key.pubKey; } bool operator==(const qvl::test::QuoteGenerator::QeAuthData& testQeAuthData, const qvl::Quote::QeAuthData& qeAuth) { return testQeAuthData.size == qeAuth.parsedDataSize && testQeAuthData.data == qeAuth.data; } bool operator==(const qvl::test::QuoteGenerator::QeCertData& testQeCertData, const qvl::Quote::QeCertData& qeCertData) { return testQeCertData.size == qeCertData.parsedDataSize && testQeCertData.keyDataType == qeCertData.type && testQeCertData.keyData == qeCertData.data; } bool operator==(const qvl::test::QuoteGenerator::QuoteAuthData& testAuth, const qvl::Quote::Ecdsa256BitQuoteAuthData& auth) { return testAuth.ecdsaSignature == auth.ecdsa256BitSignature && testAuth.ecdsaAttestationKey == auth.ecdsaAttestationKey && testAuth.ecdsaAttestationKey == auth.ecdsaAttestationKey && testAuth.qeReport == auth.qeReport && testAuth.qeReportSignature == auth.qeReportSignature && testAuth.qeAuthData == auth.qeAuthData && testAuth.qeCertData == auth.qeCertData; } } // anonymous namespace TEST(quoteParsing, shouldNotDeserializeIfQuoteTooShort) { const auto quote = qvl::test::QuoteGenerator{}.buildQuote(); EXPECT_FALSE(qvl::Quote{}.parse(std::vector(quote.cbegin(), quote.cend()-2))); } TEST(quote, shouldParseStubQuoteWithMinimumSize) { // GIVEN qvl::test::QuoteGenerator::QuoteHeader header{}; qvl::test::QuoteGenerator::EnclaveReport body{}; qvl::test::QuoteGenerator::QuoteAuthData auth{}; auth.authDataSize = qvl::test::QUOTE_AUTH_DATA_MIN_SIZE; qvl::test::QuoteGenerator gen{}; gen.withHeader(header) .withBody(body) .withAuthData(auth); // WHEN qvl::Quote quote; EXPECT_TRUE(quote.parse(gen.buildQuote())); // THEN EXPECT_TRUE(header == quote.getHeader()); EXPECT_TRUE(body == quote.getBody()); EXPECT_TRUE(auth == quote.getQuoteAuthData()); } TEST(quoteParsing, shouldParseEmptyHeader) { // GIVEN const qvl::test::QuoteGenerator::QuoteHeader testHeader{}; const auto headerBytes = testHeader.bytes(); // WHEN auto from = headerBytes.begin(); qvl::Quote::Header header; header.insert(from, headerBytes.cend()); // THEN ASSERT_TRUE(from == headerBytes.cend()); EXPECT_TRUE(testHeader == header); } TEST(quoteParsing, shouldParseQuoteHeader) { qvl::test::QuoteGenerator::QuoteHeader testHeader; testHeader.version = 3; testHeader.attestationKeyType = 0xffaa; testHeader.pceSvn = 0; testHeader.qeSvn = 0; testHeader.uuid = {}; testHeader.reserved = {}; testHeader.userData = {}; qvl::test::QuoteGenerator generator; generator.withHeader(testHeader); const auto quote = generator.buildQuote(); qvl::Quote quoteObj; ASSERT_TRUE(quoteObj.parse(quote)); EXPECT_TRUE(testHeader == quoteObj.getHeader()); } TEST(quoteParsing, shouldParseEnclaveReport) { const qvl::test::QuoteGenerator::EnclaveReport testreport{}; const auto bytes = testreport.bytes(); auto from = bytes.begin(); qvl::Quote::EnclaveReport report; report.insert(from, bytes.cend()); ASSERT_TRUE(from == bytes.cend()); EXPECT_TRUE(testreport == report); } TEST(quoteParsing, shouldParseQuoteBody) { qvl::test::QuoteGenerator::EnclaveReport testreport{}; testreport.miscSelect = 5; testreport.isvSvn = 300; testreport.attributes = {{1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16}}; qvl::test::QuoteGenerator gen{}; gen.withBody(testreport); qvl::Quote quote; ASSERT_TRUE(quote.parse(gen.buildQuote())); EXPECT_TRUE(testreport == quote.getBody()); } TEST(quoteParsing, shouldParseQeAuthData) { qvl::test::QuoteGenerator::QeAuthData testAuth{5, {1,2,3,4,5}}; const auto bytes = testAuth.bytes(); auto from = bytes.begin(); qvl::Quote::QeAuthData auth; auth.insert(from, bytes.cend()); ASSERT_TRUE(from == bytes.cend()); EXPECT_EQ(5, auth.parsedDataSize); EXPECT_EQ(5, auth.data.size()); EXPECT_EQ(testAuth.data, auth.data); } TEST(quoteParsing, shouldParseQeAuthWithShorterDataButPointerShouldNotBeMoved) { qvl::test::QuoteGenerator::QeAuthData testAuth{5, {1,2,3,4}}; const auto bytes = testAuth.bytes(); auto from = bytes.begin(); qvl::Quote::QeAuthData auth; auth.insert(from, bytes.cend()); ASSERT_TRUE(from == bytes.begin()); EXPECT_EQ(5, auth.parsedDataSize); EXPECT_EQ(0, auth.data.size()); } TEST(quoteParsing, shouldNotParseTooShortQuote) { auto quoteBytes = qvl::test::QuoteGenerator{}.buildQuote(); std::vector tooShortQuote; tooShortQuote.reserve(quoteBytes.size() - 1); std::copy(quoteBytes.begin(), quoteBytes.end() - 1, std::back_inserter(tooShortQuote)); qvl::Quote quote; EXPECT_FALSE(quote.parse(tooShortQuote)); } TEST(quoteParsing, shouldNotParseIfAuthDataSizeBiggerThanRemaingData) { qvl::test::QuoteGenerator gen; ++gen.getAuthSize(); qvl::Quote quote; EXPECT_FALSE(quote.parse(gen.buildQuote())); } TEST(quoteParsing, shouldNotParseIfAuthDataSizeSmallerThanRemaingData) { qvl::test::QuoteGenerator gen; --gen.getAuthSize(); qvl::Quote quote; EXPECT_FALSE(quote.parse(gen.buildQuote())); } TEST(quoteParsing, shouldParseCustomQeAuth) { qvl::test::QuoteGenerator gen; qvl::test::QuoteGenerator::QeAuthData qeAuthData; qeAuthData.data = {0x00, 0xaa, 0xff}; qeAuthData.size = 3; gen.withQeAuthData(qeAuthData); gen.getAuthSize() += 3; //QeAuthData::size byte len is const and already taken into account when creating default gen object qvl::Quote quote; ASSERT_TRUE(quote.parse(gen.buildQuote())); EXPECT_TRUE(qeAuthData == quote.getQuoteAuthData().qeAuthData); } TEST(quoteParsing, shouldNotParseWhenQuoteAuthDataSizeMatchButQeAuthDataSizeDoNotMatch) { qvl::test::QuoteGenerator gen; qvl::test::QuoteGenerator::QeAuthData qeAuthData; qeAuthData.data = {0x00, 0xaa, 0xff}; qeAuthData.size = 2; gen.withQeAuthData(qeAuthData); gen.getAuthSize() += 3; qvl::Quote quote; EXPECT_FALSE(quote.parse(gen.buildQuote())); } TEST(quoteParsing, shouldNotParseWhenQuoteAuthDataSizeMatchButQeAuthDataSizeAreTooMuch) { qvl::test::QuoteGenerator gen; qvl::test::QuoteGenerator::QeAuthData qeAuthData; qeAuthData.data = {0x00, 0xaa, 0xff}; qeAuthData.size = 4; gen.withQeAuthData(qeAuthData); gen.getAuthSize() += 3; qvl::Quote quote; auto builtQuote = gen.buildQuote(); EXPECT_FALSE(quote.parse(builtQuote)); } TEST(quoteParsing, shouldParseQeCertData) { qvl::test::QuoteGenerator gen; qvl::test::QuoteGenerator::QeCertData qeCert; qeCert.keyData = { qeCert.size = 4; qeCert.keyDataType = 5; gen.withQeCertData(qeCert); gen.getAuthSize() += 4; qvl::Quote quote; ASSERT_TRUE(quote.parse(gen.buildQuote())); EXPECT_EQ(qeCert.keyData, quote.getQuoteAuthData().qeCertData.data); EXPECT_EQ(qeCert.size, quote.getQuoteAuthData().qeCertData.parsedDataSize); EXPECT_EQ(qeCert.keyDataType, quote.getQuoteAuthData().qeCertData.type); } TEST(quoteParsing, shouldNotParseWhenAuthDataSizeMatchButQeCertDataParsedSizeDoesNotMatch) { qvl::test::QuoteGenerator gen; qvl::test::QuoteGenerator::QeCertData qeCert; qeCert.keyData = {}; qeCert.size = 3; qeCert.keyDataType = 5; gen.withQeCertData(qeCert); gen.getAuthSize() += 4; qvl::Quote quote; ASSERT_FALSE(quote.parse(gen.buildQuote())); } TEST(quoteParsing, shouldNotParseWhenAuthDataSizeMatchButQeCertDataParsedSizeIsTooMuch) { qvl::test::QuoteGenerator gen; qvl::test::QuoteGenerator::QeCertData qeCert; qeCert.keyData = { qeCert.size = 5; qeCert.keyDataType = 5; gen.withQeCertData(qeCert); gen.getAuthSize() += 4; qvl::Quote quote; ASSERT_FALSE(quote.parse(gen.buildQuote())); } TEST(quoteParsing, shouldParseQeAuthAndQeCert) { qvl::test::QuoteGenerator gen; qvl::test::QuoteGenerator::QeCertData qeCert; qeCert.keyData = { qeCert.size = 4; qeCert.keyDataType = 5; gen.withQeCertData(qeCert); gen.getAuthSize() += 4; qvl::test::QuoteGenerator::QeAuthData qeAuthData; qeAuthData.data = {0x00, 0xaa, 0xff}; qeAuthData.size = 3; gen.withQeAuthData(qeAuthData); gen.getAuthSize() += 3; qvl::Quote quote; ASSERT_TRUE(quote.parse(gen.buildQuote())); } src/scanner/scanner.cpp #include "scanner.hpp" #include "../error_handler/error_handler.hpp" using namespace lox; Scanner::Scanner(const std::string& aSource, ErrorHandler& aErrorHandler) : start(0) , current(0) , line(1) , source(aSource) , errorHandler(aErrorHandler) { // initialize reserved keywords map reservedKeywords["and"] = TokenType::AND; reservedKeywords["class"] = TokenType::CLASS; reservedKeywords["else"] = TokenType::ELSE; reservedKeywords["false"] = TokenType::FALSE; reservedKeywords["for"] = TokenType::FOR; reservedKeywords["fun"] = TokenType::FUN; reservedKeywords["if"] = TokenType::IF; reservedKeywords["nil"] = TokenType::NIL; reservedKeywords["or"] = TokenType::OR; reservedKeywords["print"] = TokenType::PRINT; reservedKeywords["return"] = TokenType::RETURN; reservedKeywords["super"] = TokenType::SUPER; reservedKeywords["this"] = TokenType::THIS; reservedKeywords["true"] = TokenType::TRUE; reservedKeywords["var"] = TokenType::VAR; reservedKeywords["while"] = TokenType::WHILE; } char Scanner::advanceAndGetChar() { ++current; return source[current - 1]; } void Scanner::scanAndAddToken() { const char c = advanceAndGetChar(); switch (c) { case '(': addToken(TokenType::LEFT_PAREN); break; case ')': addToken(TokenType::RIGHT_PAREN); break; case '{': addToken(TokenType::LEFT_BRACE); break; case '}': addToken(TokenType::RIGHT_BRACE); break; case ',': addToken(TokenType::COMMA); break; case '.': addToken(TokenType::DOT); break; case '-': addToken(TokenType::MINUS); break; case '+': addToken(TokenType::PLUS); break; case ';': addToken(TokenType::SEMICOLON); break; case '*': addToken(TokenType::STAR); break; case '!': addToken(matchAndAdvance('=') ? TokenType::BANG_EQUAL : TokenType::BANG); break; case '=': addToken(matchAndAdvance('=') ? TokenType::EQUAL_EQUAL : TokenType::EQUAL); break; case '<': addToken(matchAndAdvance('=') ? TokenType::LESS_EQUAL : TokenType::LESS); break; case '>': addToken(matchAndAdvance('=') ? TokenType::GREATER_EQUAL : TokenType::GREATER); break; case '/': if (matchAndAdvance('/')) { // a comment goes until the end of the line. while (peek() != '\n' && !isAtEnd()) (void)advanceAndGetChar(); } else { addToken(TokenType::SLASH); } break; case '"': string(); break; case ' ': case '\r': case '\t': // ignore whitespace break; case '\n': ++line; break; default: { if (isDigit(c)) { number(); } else if (isAlpha(c)) { identifier(); } else { std::string errorMessage = "Unexpected character: "; errorMessage += c; errorHandler.add(line, "", errorMessage); break; } } } } bool Scanner::isAlpha(const char c) const { return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_'; } bool Scanner::isAlphaNumeric(const char c) const { return isAlpha(c) || isDigit(c); } void Scanner::identifier() { // using "maximal munch" // e.g. match "orchid" not "or" keyword and "chid" while (isAlphaNumeric(peek())) (void)advanceAndGetChar(); // see if the identifier is a reserved keyword const size_t identifierLength = current - start; const std::string identifier = source.substr(start, identifierLength); const bool isReservedKeyword = reservedKeywords.find(identifier) != reservedKeywords.end(); if (isReservedKeyword) { addToken(reservedKeywords[identifier]); } else { addToken(TokenType::IDENTIFIER); } } bool Scanner::isDigit(const char c) const { return c >= '0' && c <= '9'; } void Scanner::number() { while (isDigit(peek())) (void)advanceAndGetChar(); // look for fractional part if (peek() == '.' && isDigit(peekNext())) { // consume the "." (void)advanceAndGetChar(); while (isDigit(peek())) (void)advanceAndGetChar(); } const size_t numberLength = current - start; const std::string numberLiteral = source.substr(start, numberLength); addToken(TokenType::NUMBER, numberLiteral); } void Scanner::string() { while (peek() != '"' && !isAtEnd()) { if (peek() == '\n') ++line; (void)advanceAndGetChar(); } // unterminated string if (isAtEnd()) { errorHandler.add(line, "", "Unterminated string."); return; } // closing " (void)advanceAndGetChar(); const size_t stringSize = current - start; // trim the surrounding quotes const std::string stringLiteral = source.substr(start + 1, stringSize - 2); addToken(TokenType::STRING, stringLiteral); } void Scanner::addToken(const TokenType aTokenType, const std::string& value) { const size_t lexemeSize = current - start; const auto lexeme = source.substr(start, lexemeSize); tokens.push_back(Token(aTokenType, lexeme, value, line)); } void Scanner::addToken(const TokenType aTokenType) { addToken(aTokenType, ""); } bool Scanner::isAtEnd() const { return current >= source.size(); } bool Scanner::matchAndAdvance(const char aExpected) { if (isAtEnd()) return false; if (source[current] != aExpected) return false; ++current; return true; } char Scanner::peekNext() const { if (current + 1 >= source.length()) return '\0'; return source[current + 1]; } char Scanner::peek() const { if (isAtEnd()) return '\0'; return source[current]; } std::vector Scanner::scanAndGetTokens() { while (!isAtEnd()) { // we are at the beginning of the next lexeme start = current; scanAndAddToken(); } tokens.push_back(Token(TokenType::END_OF_FILE, "", "", line)); return tokens; } AllaMaevskaya/AliRoot /************************************************************************** * 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. * **************************************************************************/ /* $Log$ Revision 1.1 2007/04/27 11:03:09 arcelli container for TOF raw data authors: , with contribution from , */ //////////////////////////////////////////////////////////////////////// // // // This class provides access to TOF raw data in DDL files. // // // // It loops over all TOF raw data given by the AliRawReader. // // // //////////////////////////////////////////////////////////////////////// #include "AliTOFHitDataBuffer.h" #include "AliTOFHitData.h" ClassImp(AliTOFHitDataBuffer) AliTOFHitDataBuffer::AliTOFHitDataBuffer() : TObject(), fBuffer("AliTOFHitData") { fBuffer.SetOwner(kTRUE); } //----------------------------------------------------------------------------- AliTOFHitDataBuffer::AliTOFHitDataBuffer(Int_t size) : TObject(), fBuffer("AliTOFHitData", size) { fBuffer.SetOwner(kTRUE); } //----------------------------------------------------------------------------- AliTOFHitDataBuffer::~AliTOFHitDataBuffer() { } //----------------------------------------------------------------------------- AliTOFHitDataBuffer& AliTOFHitDataBuffer::operator=(const AliTOFHitDataBuffer & source) { // operator = if (&source != this) { TObject::operator=(source); fBuffer = source.fBuffer; } return *this; } //----------------------------------------------------------------------------- Bool_t AliTOFHitDataBuffer::Add(AliTOFHitData &HitData) { // adding a new entry new (fBuffer[GetEntries()]) AliTOFHitData(HitData); return kFALSE; } Test.cpp #include "doctest.h" #include "range.hpp" #include "accumulate.hpp" #include "filterfalse.hpp" #include "compress.hpp" #include #include #include #include using namespace itertools; using namespace std; TEST_CASE("Test Range") { int check=1; //pass all the int in range and check if i==check in every location for(int i : range(1,11)){ CHECK(check++==i); } check=11; //pass all the int in range and check that aren't check(11) for(int i : range(1,11)){ CHECK(check!=i); } vector result = {20,21,22,23,24,25,26,27}; int j = 0; //pass all the int in the vector and in range and check if they are equals for(int i : range(20,28)){ CHECK(i == result.at(j)); j++; } } TEST_CASE("Test Accumulate"){ //check for a string case vector v = {"a", "b", "c", "d", "e"}; string words[] = {"a", "ab", "abc", "abcd", "abcde"}; int j = 0; for(auto i : accumulate(v)){ CHECK(i == words[j]); j++; } //check accumulate with a range and lambada function vector result2 = {3,12,60,360,2520,20160}; j=0; for (int i: accumulate(range(3,9),[](int x, int y){return x*y;})) // 3,3*4,3*4*5,3*4*5*6,3*4*5*6*7,3*4*5*6*7*8 { CHECK(i == result2.at(j)); ++j; } //check accumulate with a lambada function j=0; vector result3={1,3,6,10,15,21,28,36,45}; for (int i: accumulate(range(1,9),[](int x, int y){return x+y;})) // 1,1+2,1+2+3,1+2+3+4,1+2+3+4+5..... ,1+2+3+4+5+6+7+8+9 { CHECK(i == result3.at(j)); ++j; } } TEST_CASE("Test FilterFalse"){ //check filterfalse with an boolean lambada(even=true) vector result = {5,7}; int j = 0; for (auto i: filterfalse([](int i){return i%2==0;}, range(5,9)) ) { CHECK(i == result.at(j)); ++j; } //the same but odd vector result2 = {5,7}; j = 0; range r59(5,9); for (auto i: filterfalse([](int i){return i%2==0;}, r59) ) { CHECK(i == result2.at(j)); ++j; } CHECK(j == 2); } TEST_CASE("Test compress"){ //compress with range - the odd place vector b; for (int j = 1; j < 20; ++j) { b.push_back(j%2 == 1); } range range1(1,20); for (auto i : compress(range1, b)) { CHECK(i%2 == 1); } } TEST_CASE("Test Compress") { vector result = {7}; int j = 0; vector fftf {false,false,true,false}; for (auto i: compress(range(5,9), fftf) ) { CHECK(i == result.at(j)); ++j; } CHECK(j == 1); result.clear(); j = 0; result = {1,7,11,20}; j = 0; vector myvec = {1,3,7,10,11,16,20}; vector tftftft {true,false,true,false,true,false,true}; for (auto i: compress(myvec, tftftft) ) { CHECK(i == result.at(j)); ++j; } CHECK(j == 4); result.clear(); j = 0; vector resultString = {'I','L', 'o', 'v', 'e', 'C', '+','+'}; j = 0; vector tfffttttttt {true,false,false,false,true,true,true,true,true,true,true}; string s1 {"InotLoveC++"}; for (auto i: compress(s1, tfffttttttt)) { CHECK(resultString.at(j) == i); ++j; } CHECK(j == 8); j = 0; vector myVectorBool2 {false,false,false,false,false,false,false,false,false,false,false}; for (auto i: compress(string("InotLoveC++"), myVectorBool2)) { CHECK(0==1); // not need to get in ++j; } CHECK(j == 0); result.clear(); j = 0; } /*************************************************************************************** * Original Author: * Created: 2018-01-21 * Copyright: (https://github.com/GabrieleGiuseppini) ***************************************************************************************/ #include "Physics.h" #include #include #include namespace Physics { World::World( OceanFloorTerrain && oceanFloorTerrain, FishSpeciesDatabase const & fishSpeciesDatabase, std::shared_ptr gameEventDispatcher, std::shared_ptr taskThreadPool, GameParameters const & gameParameters, VisibleWorld const & /*visibleWorld*/) : mCurrentSimulationTime(0.0f) // , mGameEventHandler(std::move(gameEventDispatcher)) , mEventRecorder(nullptr) , mTaskThreadPool(std::move(taskThreadPool)) // , mAllShips() , mStars() , mStorm(*this, mGameEventHandler) , mWind(mGameEventHandler) , mClouds() , mOceanSurface(*this, mGameEventHandler) , mOceanFloor(std::move(oceanFloorTerrain)) , mFishes(fishSpeciesDatabase, mGameEventHandler) // , mAllAABBs() { // Initialize world pieces that need to be initialized now mStars.Update(mCurrentSimulationTime, gameParameters); mStorm.Update(mCurrentSimulationTime, gameParameters); mWind.Update(mStorm.GetParameters(), gameParameters); mClouds.Update(mCurrentSimulationTime, mWind.GetBaseAndStormSpeedMagnitude(), mStorm.GetParameters(), gameParameters); mOceanSurface.Update(mCurrentSimulationTime, mWind, gameParameters); mOceanFloor.Update(gameParameters); } ShipId World::GetNextShipId() const { return static_cast(mAllShips.size()); } void World::AddShip(std::unique_ptr ship) { assert(ship->GetId() == static_cast(mAllShips.size())); mAllShips.push_back(std::move(ship)); } void World::Announce() { // Nothing to announce in non-ship stuff... // ...ask all ships to announce for (auto & ship : mAllShips) { ship->Announce(); } } void World::SetEventRecorder(EventRecorder * eventRecorder) { mEventRecorder = eventRecorder; // Set in all ships for (auto & ship : mAllShips) { ship->SetEventRecorder(eventRecorder); } } void World::ReplayRecordedEvent( RecordedEvent const & event, GameParameters const & gameParameters) { for (auto & ship : mAllShips) { if (ship->ReplayRecordedEvent(event, gameParameters)) { break; } } } size_t World::GetShipCount() const { return mAllShips.size(); } size_t World::GetShipPointCount(ShipId shipId) const { assert(shipId >= 0 && shipId < mAllShips.size()); return mAllShips[shipId]->GetPointCount(); } vec2f World::GetShipSize(ShipId shipId) const { assert(shipId >= 0 && shipId < mAllShips.size()); return mAllShips[shipId]->GetSize(); } bool World::IsUnderwater(ElementId elementId) const { auto const shipId = elementId.GetShipId(); assert(shipId >= 0 && shipId < mAllShips.size()); return mAllShips[shipId]->IsUnderwater(elementId.GetLocalObjectId()); } ////////////////////////////////////////////////////////////////////////////// // Interactions ////////////////////////////////////////////////////////////////////////////// void World::ScareFish( vec2f const & position, float radius, std::chrono::milliseconds delay) { mFishes.DisturbAt(position, radius, delay); } void World::AttractFish( vec2f const & position, float radius, std::chrono::milliseconds delay) { mFishes.AttractAt(position, radius, delay); } void World::PickPointToMove( vec2f const & pickPosition, std::optional & elementId, GameParameters const & gameParameters) const { for (auto & ship : mAllShips) { auto elementIndex = ship->PickPointToMove( pickPosition, gameParameters); if (!!elementIndex) { elementId = ElementId(ship->GetId(), *elementIndex); return; } } elementId = std::nullopt; } void World::MoveBy( ElementId elementId, vec2f const & offset, vec2f const & inertialVelocity, GameParameters const & gameParameters) { auto const shipId = elementId.GetShipId(); assert(shipId >= 0 && shipId < mAllShips.size()); mAllShips[shipId]->MoveBy( elementId.GetLocalObjectId(), offset, inertialVelocity, gameParameters); } void World::MoveBy( ShipId shipId, vec2f const & offset, vec2f const & inertialVelocity, GameParameters const & gameParameters) { assert(shipId >= 0 && shipId < mAllShips.size()); mAllShips[shipId]->MoveBy( offset, inertialVelocity, gameParameters); } void World::RotateBy( ElementId elementId, float angle, vec2f const & center, float inertialAngle, GameParameters const & gameParameters) { auto const shipId = elementId.GetShipId(); assert(shipId >= 0 && shipId < mAllShips.size()); mAllShips[shipId]->RotateBy( elementId.GetLocalObjectId(), angle, center, inertialAngle, gameParameters); } void World::RotateBy( ShipId shipId, float angle, vec2f const & center, float inertialAngle, GameParameters const & gameParameters) { assert(shipId >= 0 && shipId < mAllShips.size()); mAllShips[shipId]->RotateBy( angle, center, inertialAngle, gameParameters); } std::optional World::PickObjectForPickAndPull( vec2f const & pickPosition, GameParameters const & gameParameters) { for (auto & ship : mAllShips) { auto elementIndex = ship->PickObjectForPickAndPull( pickPosition, gameParameters); if (elementIndex.has_value()) { return ElementId(ship->GetId(), *elementIndex); } } // No luck return std::nullopt; } void World::Pull( ElementId elementId, vec2f const & target, GameParameters const & gameParameters) { auto const shipId = elementId.GetShipId(); assert(shipId >= 0 && shipId < mAllShips.size()); mAllShips[shipId]->Pull( elementId.GetLocalObjectId(), target, gameParameters); } void World::DestroyAt( vec2f const & targetPos, float radiusMultiplier, GameParameters const & gameParameters) { for (auto & ship : mAllShips) { ship->DestroyAt( targetPos, radiusMultiplier, mCurrentSimulationTime, gameParameters); } // Also scare fishes at bit mFishes.DisturbAt( targetPos, 6.5f + radiusMultiplier, std::chrono::milliseconds(0)); } void World::RepairAt( vec2f const & targetPos, float radiusMultiplier, SequenceNumber repairStepId, GameParameters const & gameParameters) { for (auto & ship : mAllShips) { ship->RepairAt( targetPos, radiusMultiplier, repairStepId, mCurrentSimulationTime, gameParameters); } } bool World::SawThrough( vec2f const & startPos, vec2f const & endPos, bool isFirstSegment, GameParameters const & gameParameters) { bool atLeastOneShipApplied = false; for (auto & ship : mAllShips) { bool const isApplied = ship->SawThrough( startPos, endPos, isFirstSegment, mCurrentSimulationTime, gameParameters); atLeastOneShipApplied |= isApplied; } return atLeastOneShipApplied; } bool World::ApplyHeatBlasterAt( vec2f const & targetPos, HeatBlasterActionType action, float radius, GameParameters const & gameParameters) { bool atLeastOneShipApplied = false; for (auto & ship : mAllShips) { bool const isApplied = ship->ApplyHeatBlasterAt( targetPos, action, radius, gameParameters); atLeastOneShipApplied |= isApplied; } return atLeastOneShipApplied; } bool World::ExtinguishFireAt( vec2f const & targetPos, float radius, GameParameters const & gameParameters) { bool atLeastOneShipApplied = false; for (auto & ship : mAllShips) { bool isApplied = ship->ExtinguishFireAt( targetPos, radius, gameParameters); atLeastOneShipApplied |= isApplied; } return atLeastOneShipApplied; } void World::ApplyBlastAt( vec2f const & targetPos, float radius, float forceMultiplier, GameParameters const & gameParameters) { for (auto & ship : mAllShips) { ship->ApplyBlastAt( targetPos, radius, forceMultiplier, gameParameters); } // Displace ocean surface { // Explosion depth (positive when underwater) float const explosionDepth = mOceanSurface.GetHeightAt(targetPos.x) - targetPos.y; // Calculate length of chord on circle given (clamped) distance of // ocean surface from center of blast (i.e. depth) float const circleRadius = radius * 2.0f; // Displacement sphere radius larger than blast float const halfChordLength = std::sqrt( std::max( circleRadius * circleRadius - explosionDepth * explosionDepth, 0.0f)); // Apply displacement along chord length for (float r = 0.0f; r < halfChordLength; r += 0.5f) { float const d = 1.0f // Magic number * (1.0f - r / halfChordLength) // Max at center, zero at extremes * (explosionDepth <= 0.0f ? -1.0f : 1.0f); // Follow depth sign mOceanSurface.DisplaceAt(targetPos.x - r, d); mOceanSurface.DisplaceAt(targetPos.x + r, d); } } // Also scare fishes at bit mFishes.DisturbAt( targetPos, radius, std::chrono::milliseconds(0)); } bool World::ApplyElectricSparkAt( vec2f const & targetPos, std::uint64_t counter, float lengthMultiplier, float currentSimulationTime, GameParameters const & gameParameters) { bool atLeastOneShipApplied = false; for (auto & ship : mAllShips) { bool isApplied = ship->ApplyElectricSparkAt( targetPos, counter, lengthMultiplier, currentSimulationTime, gameParameters); atLeastOneShipApplied |= isApplied; } return atLeastOneShipApplied; } void World::DrawTo( vec2f const & targetPos, float strengthFraction, GameParameters const & gameParameters) { for (auto & ship : mAllShips) { ship->DrawTo( targetPos, strengthFraction, gameParameters); } } void World::SwirlAt( vec2f const & targetPos, float strengthFraction, GameParameters const & gameParameters) { for (auto & ship : mAllShips) { ship->SwirlAt( targetPos, strengthFraction, gameParameters); } } void World::TogglePinAt( vec2f const & targetPos, GameParameters const & gameParameters) { // Stop at first ship that successfully pins or unpins a point for (auto it = mAllShips.rbegin(); it != mAllShips.rend(); ++it) { if ((*it)->TogglePinAt(targetPos, gameParameters)) { // Found! return; } // No luck... // search other ships } } void World::RemoveAllPins() { for (auto & ship : mAllShips) { ship->RemoveAllPins(); } } std::optional World::InjectPressureAt( vec2f const & targetPos, float pressureQuantityMultiplier, GameParameters const & gameParameters) { // Stop at first ship that successfully injects pressure for (auto it = mAllShips.rbegin(); it != mAllShips.rend(); ++it) { auto const applicationLocus = (*it)->InjectPressureAt( targetPos, pressureQuantityMultiplier, gameParameters); if (applicationLocus.has_value()) { // Found! return applicationLocus; } // No luck... // search other ships } // Couldn't inject pressure... // ...stop at first ship that successfully injects bubbles now for (auto it = mAllShips.rbegin(); it != mAllShips.rend(); ++it) { auto const applicationLocus = (*it)->InjectBubblesAt( targetPos, mCurrentSimulationTime, gameParameters); if (applicationLocus.has_value()) { // Found! return applicationLocus; } // No luck... // search other ships } return std::nullopt; } bool World::FloodAt( vec2f const & targetPos, float waterQuantityMultiplier, GameParameters const & gameParameters) { // Flood all ships bool anyHasFlooded = false; for (auto & ship : mAllShips) { bool hasFlooded = ship->FloodAt( targetPos, waterQuantityMultiplier, gameParameters); anyHasFlooded |= hasFlooded; } return anyHasFlooded; } void World::ToggleAntiMatterBombAt( vec2f const & targetPos, GameParameters const & gameParameters) { // Stop at first ship that successfully places or removes a bomb for (auto it = mAllShips.rbegin(); it != mAllShips.rend(); ++it) { if ((*it)->ToggleAntiMatterBombAt(targetPos, gameParameters)) { // Found! return; } // No luck... // search other ships } } void World::ToggleImpactBombAt( vec2f const & targetPos, GameParameters const & gameParameters) { // Stop at first ship that successfully places or removes a bomb for (auto it = mAllShips.rbegin(); it != mAllShips.rend(); ++it) { if ((*it)->ToggleImpactBombAt(targetPos, gameParameters)) { // Found! return; } // No luck... // search other ships } } std::optional World::TogglePhysicsProbeAt( vec2f const & targetPos, GameParameters const & gameParameters) { // Stop at first ship that successfully places or removes a probe size_t iShip = mAllShips.size(); do { --iShip; auto result = mAllShips[iShip]->TogglePhysicsProbeAt(targetPos, gameParameters); if (result.has_value()) { // The probe has been placed or removed on this ship if (*result) { // The probe has been placed on this ship, remove it from all others for (size_t iShip2 = 0; iShip2 < mAllShips.size(); ++iShip2) { if (iShip2 != iShip) { mAllShips[iShip2]->RemovePhysicsProbe(); } } } return result; } // No luck... // ...continue with other ships } while(iShip > 0); return std::nullopt; } void World::ToggleRCBombAt( vec2f const & targetPos, GameParameters const & gameParameters) { // Stop at first ship that successfully places or removes a bomb for (auto it = mAllShips.rbegin(); it != mAllShips.rend(); ++it) { if ((*it)->ToggleRCBombAt(targetPos, gameParameters)) { // Found! return; } // No luck... // search other ships } } void World::ToggleTimerBombAt( vec2f const & targetPos, GameParameters const & gameParameters) { // Stop at first ship that successfully places or removes a bomb for (auto it = mAllShips.rbegin(); it != mAllShips.rend(); ++it) { if ((*it)->ToggleTimerBombAt(targetPos, gameParameters)) { // Found! return; } // No luck... // search other ships } } void World::DetonateRCBombs() { for (auto const & ship : mAllShips) { ship->DetonateRCBombs(); } } void World::DetonateAntiMatterBombs() { for (auto const & ship : mAllShips) { ship->DetonateAntiMatterBombs(); } } void World::AdjustOceanSurfaceTo(std::optional const & worldCoordinates) { mOceanSurface.AdjustTo( worldCoordinates, mCurrentSimulationTime); } std::optional World::AdjustOceanFloorTo( float x1, float targetY1, float x2, float targetY2) { return mOceanFloor.AdjustTo(x1, targetY1, x2, targetY2); } bool World::ScrubThrough( vec2f const & startPos, vec2f const & endPos, GameParameters const & gameParameters) { // Scrub all ships bool anyHasScrubbed = false; for (auto & ship : mAllShips) { bool const hasScrubbed = ship->ScrubThrough( startPos, endPos, gameParameters); anyHasScrubbed |= hasScrubbed; } return anyHasScrubbed; } bool World::RotThrough( vec2f const & startPos, vec2f const & endPos, GameParameters const & gameParameters) { // Rot all ships bool anyHasRotted = false; for (auto & ship : mAllShips) { bool const hasRotted = ship->RotThrough( startPos, endPos, gameParameters); anyHasRotted |= hasRotted; } return anyHasRotted; } void World::ApplyThanosSnap( float centerX, float radius, float leftFrontX, float rightFrontX, float currentSimulationTime, GameParameters const & gameParameters) { // Apply to all ships for (auto & ship : mAllShips) { ship->ApplyThanosSnap( centerX, radius, leftFrontX, rightFrontX, currentSimulationTime, gameParameters); } // Apply to ocean surface mOceanSurface.ApplyThanosSnap(leftFrontX, rightFrontX); // Apply to fishes float constexpr DisturbanceRadius = 100.0f; mFishes.DisturbAt( vec2f(leftFrontX, 0.0f), DisturbanceRadius, std::chrono::milliseconds(0)); mFishes.DisturbAt( vec2f(rightFrontX, 0.0f), DisturbanceRadius, std::chrono::milliseconds(0)); } std::optional World::GetNearestPointAt( vec2f const & targetPos, float radius) const { std::optional bestPointId; float bestSquareDistance = std::numeric_limits::max(); for (auto const & ship : mAllShips) { auto shipBestPointIndex = ship->GetNearestPointAt(targetPos, radius); if (NoneElementIndex != shipBestPointIndex) { float squareDistance = (ship->GetPoints().GetPosition(shipBestPointIndex) - targetPos).squareLength(); if (squareDistance < bestSquareDistance) { bestPointId = ElementId(ship->GetId(), shipBestPointIndex); bestSquareDistance = squareDistance; } } } return bestPointId; } void World::QueryNearestPointAt( vec2f const & targetPos, float radius) const { // Stop at first ship that successfully queries for (auto it = mAllShips.rbegin(); it != mAllShips.rend(); ++it) { if ((*it)->QueryNearestPointAt(targetPos, radius)) return; } } std::optional World::FindSuitableLightningTarget() const { // Try all ships until a target is found for (auto const & ship : mAllShips) { auto target = ship->FindSuitableLightningTarget(); if (!!target) return target; } return std::nullopt; } void World::ApplyLightning( vec2f const & targetPos, float currentSimulationTime, GameParameters const & gameParameters) { // Apply to all ships for (auto & ship : mAllShips) { ship->ApplyLightning(targetPos, currentSimulationTime, gameParameters); } // Apply to fishes DisturbOceanAt( targetPos, 500.0f, std::chrono::milliseconds(0)); } void World::TriggerTsunami() { mOceanSurface.TriggerTsunami(mCurrentSimulationTime); DisturbOcean(std::chrono::milliseconds(0)); } void World::TriggerStorm() { mStorm.TriggerStorm(); } void World::TriggerLightning() { mStorm.TriggerLightning(); } void World::TriggerRogueWave() { mOceanSurface.TriggerRogueWave( mCurrentSimulationTime, mWind); } void World::HighlightElectricalElement(ElectricalElementId electricalElementId) { auto const shipId = electricalElementId.GetShipId(); assert(shipId >= 0 && shipId < mAllShips.size()); mAllShips[shipId]->HighlightElectricalElement(electricalElementId); } void World::SetSwitchState( ElectricalElementId electricalElementId, ElectricalState switchState, GameParameters const & gameParameters) { auto const shipId = electricalElementId.GetShipId(); assert(shipId >= 0 && shipId < mAllShips.size()); mAllShips[shipId]->SetSwitchState( electricalElementId, switchState, gameParameters); } void World::SetEngineControllerState( ElectricalElementId electricalElementId, int telegraphValue, GameParameters const & gameParameters) { auto const shipId = electricalElementId.GetShipId(); assert(shipId >= 0 && shipId < mAllShips.size()); mAllShips[shipId]->SetEngineControllerState( electricalElementId, telegraphValue, gameParameters); } void World::SetSilence(float silenceAmount) { mWind.SetSilence(silenceAmount); } bool World::DestroyTriangle(ElementId triangleId) { auto const shipId = triangleId.GetShipId(); assert(shipId >= 0 && shipId < mAllShips.size()); return mAllShips[shipId]->DestroyTriangle(triangleId.GetLocalObjectId()); } bool World::RestoreTriangle(ElementId triangleId) { auto const shipId = triangleId.GetShipId(); assert(shipId >= 0 && shipId < mAllShips.size()); return mAllShips[shipId]->RestoreTriangle(triangleId.GetLocalObjectId()); } ////////////////////////////////////////////////////////////////////////////// // Simulation ////////////////////////////////////////////////////////////////////////////// void World::Update( GameParameters const & gameParameters, VisibleWorld const & visibleWorld, PerfStats & perfStats) { // Update current time mCurrentSimulationTime += GameParameters::SimulationStepTimeDuration; // Prepare all AABBs mAllAABBs.Clear(); // // Update all subsystems // mStars.Update(mCurrentSimulationTime, gameParameters); mStorm.Update(mCurrentSimulationTime, gameParameters); mWind.Update(mStorm.GetParameters(), gameParameters); mClouds.Update(mCurrentSimulationTime, mWind.GetBaseAndStormSpeedMagnitude(), mStorm.GetParameters(), gameParameters); mOceanSurface.Update(mCurrentSimulationTime, mWind, gameParameters); mOceanFloor.Update(gameParameters); for (auto & ship : mAllShips) { ship->Update( mCurrentSimulationTime, mStorm.GetParameters(), gameParameters, mAllAABBs); } { auto const startTime = std::chrono::steady_clock::now(); mFishes.Update(mCurrentSimulationTime, mOceanSurface, mOceanFloor, gameParameters, visibleWorld, mAllAABBs); perfStats.TotalFishUpdateDuration.Update(std::chrono::steady_clock::now() - startTime); } } void World::RenderUpload( GameParameters const & gameParameters, Render::RenderContext & renderContext, PerfStats & /*perfStats*/) { mStars.Upload(renderContext); mWind.Upload(renderContext); mStorm.Upload(renderContext); mClouds.Upload(renderContext); mOceanFloor.Upload(gameParameters, renderContext); mOceanSurface.Upload(renderContext); mFishes.Upload(renderContext); // Ships { renderContext.UploadShipsStart(); for (auto const & ship : mAllShips) { ship->RenderUpload(renderContext); } renderContext.UploadShipsEnd(); } // AABBs if (renderContext.GetShowAABBs()) { renderContext.UploadAABBsStart(mAllAABBs.GetCount()); auto constexpr color = rgbaColor(18, 8, 255, 255).toVec4f(); for (auto const & aabb : mAllAABBs.GetItems()) { renderContext.UploadAABB( aabb, color); } renderContext.UploadAABBsEnd(); } } }#pragma once /* Changes in v1.2.8: - Added the function "IsValueValid" for the "Setting" class, this checks if the given string value is valid for the settings type and is safe to parse. Both "InRange" and "SetVale" now use this function in "Manager.cpp". - Added a new enum called "ThreadTypes" in "Manager.hpp", used in settings for identifying when it is safe to call certain functions. - Added a default "ThreadTypes" argument for the functions "SetValue" and "ResetToDefault" for the "Setting" class in "Manager.hpp/cpp", if updating the setting is done outside of the game's thread (like ImGui) it will automatically queue the command for you. - Made certain members and functions in "Manager.hpp" static. Changes in v1.2.7: - Added four new functions in "Formatting.hpp", "IsStringNumber", "IsStringFloat", "EraseAllChars", and "RemoveAllChars". - Fixed a bug in the "SetValue" function that prevented some setitng types from applying in "Manager.cpp". - Renamed the function "AddToQueue" to "QueueCommand" and changed the "CommandQueue" to use a new custom class in "Manager.hpp/cpp". - Made the "DecimalToHex" function have a fill of 6 now in "Colors.cpp". Changes in v1.2.6: - Fixed functions still going through Process Event if their detour was set to false if there were multiple voids bound to the same function. - Added the "IsEventBlacklisted" function in "Events.hpp" as part of the "ManagerComponent", and also made the "PostEvent" class call this in its "Detour" function in "Manager.cpp". - Added a special case for setting a boolean value in the "Setting" class function "SetValue". - Changed the "DecimalToHex" function in "Colors.cpp" to use streams instead of strings. Changes in v1.2.5: - Added an option "bLogToConsole" argument for the "ConsoleCommand" function in "Manager.hpp". - Added logging the old vs new value when changing a settings value for the "ConsoleCommand" function in "Manager.cpp". - Added a range feature for the "Setting" class, you can now specific a minimum and maximum range when setting values now. The new functions are "HasRange", "InRange", and "SetRange". - Added an example of how to use the new "SetRange" funtion in the "Initialize" function in "Manager.cpp". - Added a "Searchable" option for the "Command" class in "Manager.hpp", it has a default value of "true" in the classes constructor. - Added new functions, "GetId" and "GetDefaultValue", for the "Setting" class in "Manager.hpp". - Remade how binding and triggering setting/command callbacks work completely, and removed storing argument data in the "Command" class itself. - Changed/optimized some functions for the "Setting" class in "Manager.cpp". - Removed "CommandTypes" for the "Command" class in "Manager.hpp" as its no longer used. Changes in v1.2.4: - Made the static function/class maps in "Instances.hpp" private, to access their contents you should use the new "FindStaticClass" and "FindStaticFunction" functions in the same file. - Added/renamed functions in the "GameState.hpp/cpp" files and made them more organized. - Fixed "GameStateComponent" not having the new virtual "OnCreate" and "OnDestory" functions. - Changed the hook functions in "Events.cpp" to use the new "FindStaticFunction" functions from "Instances.hpp". - Changed grabbing the actor in the "UnrealCommand" to grab its default instance, instead of a random one in "Manager.cpp". - Changed the pointer check for setting instances to the "Instances.cpp" file, and modified "Events.cpp" to show this. Changes in v1.2.3: - Added an argument callback option for the "Setting" class in "Manager.hpp", works similar to the "Command" classes arugment callback but the argument is the string value of the setting. - Added an optional argument for the "UnrealCommand" function in "Manager.hpp" called "bLogToConsole". - Fixed the "Lerp" function for the "VectorI" class taking a float instead of an integer in "Math.hpp". - Fixed the operators for the "Rotator" class in "Manager.cpp" saying struct instead of class. - Removed the "ShouldCallback" bool for the "Setting" class in "Manager.hpp", changed the check to see if the functions are null or not before calling instead of the bool value. - Reformatted the constructors in the "Colors.cpp", "Math.cpp", "Module.cpp", "Component.cpp", files. - Removed the "KeyPressed" function from "Manager.hpp", this should be handled by yourself in your own component or module. Changes in v1.2.2: - Changed function hooks in "Events.hpp" to use std::function, which also adds proper lambda support. - Fixed the "Detoured" bool prematurely getting set to true in "Events.cpp". Changes in v1.2.1: - Improved memory functions in "UnrealMemory.hpp", just look at them for yourself or something idk. - Improved the constructors for the "Setting" and "Command" classes in "Manager.cpp". - Added the virutal functions "OnCreate" and "OnDestroy" in "Component.hpp", these can be manually called outside of the classes constructor and deconstructor. - Added a "CreatedInstances" vector in "Instances.hpp", when a custom object instance is created it is added to this vector. On the components "OnDestory" function all custom instances are marked to be destroyed as well. - Added the "CreateVariable" function in "Manager.hpp" and moved creating variables from :ManagerComponent"'s constuctor to the "Initialize" function in "Manager.cpp". - Added the "AttachDetour" and "DetachDetour" functions in "Events.hpp", this is now called from "InitializeGlobals" in "Core.cpp". - Moved the detaching Process Event from "CoreComponent"'s deconstructor to "EventsComponent"'s deconstuctor in "Events.cpp". - Made "WriteToLog" default to "true" in "Console.cpp". - Renamed "FColorList" to "GColorList" in "Colors.hpp". Changes in v1.2.0: - Added an extra null check for creating commands, settings, and modules in "Manager.cpp". - Changed/added constuctors for the "Color" and "LinearColor" classes in "Math.hpp/cpp" to be explicit, explicit because there are now auto conversions for different color types. - Remade the "Colors" namespace and added a ton of extra functions in "Math.hpp/cpp". - Reformatting/added extra comments in "Instances.hpp/cpp", and updated the PlaceholderSDK to accommodate this. - Changed all macros in "Math.hpp" to use static constant expressions. - Added includes for "Extensions/Includes.hpp" for both the "Component.hpp" and "Module.hpp" files. - Added nullcheck for detaching detours in "Core.cpp". Changes in v1.1.9: - Removed the pointless additional constructors for the console component in "Console.hpp". - Improved functions for the console component such as writing and timestamp formatting in "Console.hpp". - Changed the null check for modules in the "Initialize" function to use ternaries in "Manager.cpp". - Improved/added extra comments in classes around the project. Changes in v1.1.8: - Added the "MarkInvincible" function in "Manager.hpp" which lets you easily prevent objects from being destroyed. - Added saftey checks for the "invincible" functions in "Manager.cpp". - Added a null check for updating modules settings when the "Initialize" function is called in "Manager.cpp". - Added virtual deconstructors for components and modules. - Reformatted some of the constructors for the color classes in "Colors.cpp". Changes in v1.1.7: - Added the "MarkForDestory" function in "Instances.hpp", and updated the PlaceholderSDK to accommodate this. - Fixed the "GetVector3DValue" function for the "Setting" class in "Manager.cpp", it still passed the type check even if it were a "TYPE_VECTOR_2D". - Changed some cast types for the template functions in "Instances.hpp". - Renamed some of the example settings in "Manager.cpp". Changes in v1.1.6: - Changed how settings and commands names are stored, in their classes they are now identified by an enum value; their names are assigned in the constructor for the "ManagerComponent" in "Manager.cpp". - Changed how settings and commands are created to go along with the new enum identifier, as well as how their shared pointers are now retrieved. - Changed how the "UpdateSettings" function works in "Module.hpp", there you can retrieve setting values all at once from "ManagerComponent" when a setting updates. - Added examples for how the "ResetSetting", "PrintModule", and "UnrealCommand" functions from "ManagerComponent" can be used as actual commands. - Remade all the math classes to use templated base classes in "Math.hpp", along with changing their names to pair with their underlying types. - Added a "Recalculate" function for the "LinearColor" class in "Colors.hpp", this is auto called in one of the constructors to recalculate the values if the user inputs an incorrect color space. For example they mistakenly put in a value from 0-255 instead of 0f-1f. - Added a few const variables to operators in both "Colors.hpp" and "Math.hpp". Changes in v1.1.5: - Changed all function hooks to use the new "PreEvent" and "PostEvent" classes, they have neat template functions that auto recast for you as well as an option to not detour the function through Process Event. - Removed the "ParseArguments" and "SplitArguments" functions in "Manager.hpp" and instead moved it to the "Format" namespace in "Formatting.hpp". - Renamed the "Functions" namespace to "Hooks" in "Events.hpp". - Renamed the "Queue" vector in "Manager.hpp" to "CommandQueue". - Moved the function hook typedefs in "Events.hpp" to inside the "EventsComponent" class. Changes in v1.1.4: - Added the "CreateInstance" function in "Instances.hpp", this allows you to create new objects of any type and have it be added to the GObjects table. - Added the "ResetSetting" function to "Manager.hpp", resets a setting to its original default value. - Added the "PrintModule" function to "Manager.hpp", prints out a modules information to the console. - Remade how Modules, Settings, and Commands are created. Please see the changes in "Manager.hpp" and "Manager.cpp" for examples. - Renamed the unreal rotator function in "Math.hpp" to RotateUnreal. - Renamed some of the "States" enum names in "GameState.hpp" to include "STATE_" in front, because we are purposefully not making this enum an enum class. - Added template flags to the PlaceholderSDK. Changes in v1.1.3: - Renamed the project from CodeRedUniversal to CodeRedTemplate. - Added support for Vector and Vector2D settings to "Manager.hpp". - Added some unreal unit/cm constants in "Math.cpp" and reformatted some comments there. Changes in v1.1.2: - Added a "GetAllowedStates" function for Modules. - Added the "ColorToLinear" and "LinearToColor" converter functions to the "Colors" namespace. - Added a std::find check for blacklisting functions in "Events.cpp". - Fixed one of the constructors for the LinearColor class in "Colors.hpp". - Changed all the FColor structs in FColorList and FRainbowColor to use all the new Color classes in "Colors.hpp". - Removed the "ModuleTypes" enum and field in the Module constructor, because why would you really need it in the first place. Changes in v1.1.1: - Added a "Quat" class in "Math.cpp", along with a bunch of defines/math helpers. - Added "Get" functions to the FRainbowColor class, this copies the data but guarantees you can't modify the original structs by mistake. - Renamed all "CR" math classes to just normal structs in "Math.hpp", also added extra math functions and operators for already exsiting classes. - Renamed all "CR" color classes to just normal structs in "Colors.hpp", also added some extra operators for them. - Updated the placeholder sdk with the new math structs so the project can compile. Changes in v1.1.0: - Added a "WhitelistEvent" function in "Events.hpp". - Added the maps "StaticClasses" and "StaticFunctions" in "Instances.hpp", here all of these objects are mapped by their full name to their pointer. - Added extra saftey checks and warnings for hooking functions. - Changed how hooking functions, and binding them work. Now you can hook multiple voids to a singluar function, before it would be limited to only one. - Removed the toggle for logging functions in the EventsComponent, that was messy anyway. Changes in v1.0.9: - Added the Formatting extension files, includes helpful stream utils. - Made the console logging in "Core.cpp" use the new formatting extensions. - Made the console component to use std::ofstream and be more efficient in terms of initializing. - Improved the "UnrealMemory" files which are based on UE4 source. - Removed the "Filesystem" extension files as they have no real use (yet). Changes in v1.0.8: - Fixed the constructor for the "Setting" class not properly setting color values. - Fixed the "HexToDecimal" function in "Colors.hpp". - Updated the commenting in "Instances.hpp". Changes in v1.0.7: - Added constructors in the CRColor structs for their retrospective unreal engine structs. - Added the "Colors" namespace in "Colors.hpp" with some small color utils. - Made the Command and Setting vector a map in "Manager.hpp", using their Command/Setting names as the key. - Completely remade settings and commands, and changed the "Manager" module to match this, along with examples. - Added "CreateCommand" and "CreateSetting" functions in "Manager.hpp". - Remade how "GetCommand" and "GetSetting" work in "Manager.hpp". - Removed the "ModifySetting" function in "Manager.hpp" as it's no longer needed. - When an argument isn't provided for a setting, it now displays its current value to the console. Changes in v1.0.6: - Added a command queue, for executing Process Event functions outside of the games main thread (like in ImGui render scenes). - Added "Math.hpp" & "Math.cpp" which include custom vector and rotator structs, along with some helper functions. - Changed how the unreal color for the structs in "Colors.hpp" is calculated. - Added some structs to the PlaceholderSDK to match the new operators in "Math.hpp". Changes in v1.0.5: - Added some extra operators for the custom color structs in "Colors.hpp". - Added example of where to put the FRainbowColor hook. - Added examples on how to bind commands to module functions, as well as toggling bools. - Added an example on how to blacklist events from going through process event in Initialize function. - Added function to split an argument string by spaces (getting each word from a string and inserting into a vector). - Added hex color phrasing to the ModifySetting function. - Added option for the bool setting to toggle true/false with 1/0. - Moved the null check for functions in process event. - Fixed the constructor for StringSetting. - Removed the "Enabled" bool in the module base class, you should be adding this in your custo module class itself. Changes in v1.0.4: - Added an option to blacklist events from going through Process Event. - Added a global rainbow color class in "Colors.hpp", and remade "FColorList". - Remade how function hooks are found in "EventsComponent", it now maps out all functions internal index and their name. - Made console logging more efficient if you were using multiple functions that used different colors. - Made the "GetTimestamp" function static. Changes in v1.0.3: - Changed typedef for post function hooks. - Made the States enum a normal enum instead of an enum class to reduce the need to cast to its underlying type. - Added an "Initialized" private member for modules. - Made modules initialize first, then function hooks/instances. */0 /* ** Events.hpp for cpp_indie_studio ** ** Made by ** Login vives_j ** ** Started on Wed May 18 14:44:50 2016 ** Last update Sat Jun 04 22:04:03 2016 */ #ifndef _EVENTS_HPP_ # define _EVENTS_HPP_ # include # include namespace bm { enum Movements : int16_t { NONE = -1, UP = 0, RIGHT = 1, DOWN = 2, LEFT = 3, SPACE = 4, ESCAPE = 5, UP2 = 6, DOWN2 = 7, LEFT2 = 8, RIGHT2 = 9, BOMB2 = 10, }; class Events : public irr::IEventReceiver { private: const std::unordered_map _KEY_CONVERTER = { {irr::EKEY_CODE::KEY_UP, UP}, {irr::EKEY_CODE::KEY_DOWN, DOWN}, {irr::EKEY_CODE::KEY_RIGHT, RIGHT}, {irr::EKEY_CODE::KEY_LEFT, LEFT}, {irr::EKEY_CODE::KEY_RETURN, SPACE}, {irr::EKEY_CODE::KEY_ESCAPE, ESCAPE}, {irr::EKEY_CODE::KEY_KEY_Z, UP2}, {irr::EKEY_CODE::KEY_KEY_Q, LEFT2}, {irr::EKEY_CODE::KEY_KEY_S, DOWN2}, {irr::EKEY_CODE::KEY_KEY_D, RIGHT2}, {irr::EKEY_CODE::KEY_SPACE, BOMB2}, {0, NONE} }; bool _tabKeys[irr::KEY_KEY_CODES_COUNT]; irr::core::array _joystickinfo; const size_t _BUTTON_PS3_X = 16384; public: Events(); virtual ~Events(); virtual bool OnEvent(const irr::SEvent &event); const bool (&getKeyCodes() const)[irr::KEY_KEY_CODES_COUNT]; irr::core::array &getJoystickInfo(); void setStateAt(const enum Movements &keyCode, const bool value); }; }; #endif osharuda/home-lab-easy-k1-10 /** * Copyright 2021 <> * * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /*! \file * \brief ADC device software implementation * \author */ #include "adcdev.hpp" #include "ekit_firmware.hpp" #ifdef ADCDEV_DEVICE_ENABLED /// \addtogroup group_adc_dev /// @{ ADCDEV_SW_CHANNELS /// \brief Global array that stores all virtual ADCDev devices configurations. const ADCDevInstance g_adcdev_descriptors[] = ADCDEV_SW_DEV_DESCRIPTOR; /// @} const ADCDevInstance* ADCDev::get_descriptor(size_t index) { if (index(g_adcdev_descriptors + index); } else { assert(false); } return nullptr; } std::string ADCDev::get_dev_name() const { return descr->dev_name; } ADCDev::ADCDev(std::shared_ptr& ebus, int addr) : super(ebus, addr) { static const char* const func_name = "ADCDev::ADCDev"; for (int i=0; ivref; } ADCDev::~ADCDev() { } std::string ADCDev::get_input_name(size_t index, bool channel_name) const { static const char* const func_name = "ADCDev::get_input_name"; if (index>=descr->input_count) { throw EKitException(func_name, EKIT_BAD_PARAM, "ADC input index is out of range"); } return channel_name ? descr->inputs[index].adc_input : descr->inputs[index].in_name; } size_t ADCDev::get_input_count() const { return descr->input_count; } void ADCDev::start(uint16_t sample_count, double delay_sec){ static const char* const func_name = "ADCDev::start"; ADCDevCommand data; double expected; uint8_t f = 0; data.sample_count = sample_count; // figure out period and prescaller if (delay_sec==0) { data.timer_prescaller=0; data.timer_period=0; } else { int res = tools::stm32_timer_params(descr->timer_freq, delay_sec, data.timer_prescaller, data.timer_period, expected); if (res>0) { throw EKitException(func_name, EKIT_BAD_PARAM, "delay_sec is too long"); } else if (res<0) { throw EKitException(func_name, EKIT_BAD_PARAM, "delay_sec is too short"); } } if (sample_count==0) { f |= ADCDEV_UNSTOPPABLE; } // issue a command { BusLocker blocker(bus, get_addr()); EKIT_ERROR err = bus->set_opt(EKitFirmware::FIRMWARE_OPT_FLAGS, f); if (err != EKIT_OK) { throw EKitException(func_name, err, "set_opt() failed"); } // Write data err = bus->write((uint8_t*)&data, sizeof(ADCDevCommand)); if (err != EKIT_OK) { throw EKitException(func_name, err, "write() failed"); } } } void ADCDev::stop(bool reset_buffer){ static const char* const func_name = "ADCDev::stop"; uint8_t f = 0; if (reset_buffer) { f |= ADCDEV_RESET_DATA; } { BusLocker blocker(bus, get_addr()); EKIT_ERROR err = bus->set_opt(EKitFirmware::FIRMWARE_OPT_FLAGS, f); if (err != EKIT_OK) { throw EKitException(func_name, err, "set_opt() failed"); } // Write zero-length buffer (just command byte, this will cause sampling stop) err = bus->write(nullptr, 0); if (err != EKIT_OK) { throw EKitException(func_name, err, "write() failed"); } } } void ADCDev::get(std::vector& data, bool& ovf){ static const char* const func_name = "ADCDev::get(1)"; // issue a command { BusLocker blocker(bus, get_addr()); // get amount of data CommResponseHeader hdr; EKIT_ERROR err = std::dynamic_pointer_cast(bus)->get_status(hdr, false); if (err != EKIT_OK && err != EKIT_OVERFLOW ) { throw EKitException(func_name, err, "get_status() failed"); } // check for overflow ovf = (hdr.comm_status & COMM_STATUS_OVF) != 0; if (hdr.length == 0) goto done; // sanity check, buffer must be aligned by size of all inputs if ((hdr.length % (descr->input_count*sizeof(uint16_t))) != 0) { assert(false); goto done; } // resize buffer data.resize(hdr.length / sizeof(uint16_t)); // read data err = bus->read((uint8_t*)data.data(), hdr.length); if (err != EKIT_OK) { throw EKitException(func_name, err, "read() failed"); } } done: return; } // returns all samples converted to double void ADCDev::get(std::vector>& values, bool& ovf){ static const char* const func_name = "ADCDev::get(2)"; std::vector data; get(data, ovf); size_t sample_count = data.size() / descr->input_count; values.clear(); // convert into doubles for (size_t ch=0; chinput_count; ch++) { std::vector ch_val; for (int s = 0; sinput_count); double x = vref_cur*((double)v/(double)descr->adc_maxval); ch_val.push_back(x); } values.push_back(std::move(ch_val)); } } // returns average for all samples converted to double void ADCDev::get(std::vector& values, bool& ovf){ static const char* const func_name = "ADCDev::get(3)"; std::vector data; get(data, ovf); size_t sample_count = data.size() / descr->input_count; values.clear(); // convert into doubles for (size_t ch=0; chinput_count; ch++) { uint32_t acc = 0; for (int s = 0; sinput_count); } acc = acc / sample_count; double x = vref_cur*((double)acc/(double)descr->adc_maxval); values.push_back(x); } } void ADCDev::set_vref(double Vref_plus) { vref_cur = Vref_plus; } void ADCDev::set_vref(uint16_t vref_channel, double V_ref_int) { vref_cur = V_ref_int * (double)descr->adc_maxval / (double)vref_channel; } #endif/* * Copyright 2018, 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 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 "local_test_phase.h" LocalTestPhase::LocalTestPhase() { if (config_.ReadConfigFile() != 0) { throw std::invalid_argument( "Reading config file for local DIMM configuration failed"); } /* Arbitrarily divide available NVDIMM namespaces between unsafe (to be * injected) and safe namespaces. This distribution is meant to enable running * the biggest number of tests with limited number of available NVDIMMS. */ int i = 0; std::copy_if(config_.begin(), config_.end(), std::back_inserter(unsafe_namespaces), [&i](DimmNamespace) -> bool { return i++ != 1; }); i = 0; std::copy_if(config_.begin(), config_.end(), std::back_inserter(safe_namespaces), [&i](DimmNamespace) -> bool { return i++ == 1; }); } int LocalTestPhase::Begin() const { return 0; } int LocalTestPhase::Inject() const { InjectManager inject_mgmt{config_.GetTestDir(), policy_}; if (inject_mgmt.RecordUSC( std::vector{config_.begin(), config_.end()}) != 0) { return -1; } if (inject_mgmt.Inject(unsafe_namespaces)) { return -1; } return 0; } int LocalTestPhase::CheckUSC() const { InjectManager inject_mgmt{config_.GetTestDir(), policy_}; if (inject_mgmt.IsLastShutdownSafe(safe_namespaces) && inject_mgmt.IsLastShutdownUnsafe(unsafe_namespaces)) { return 0; } return -1; } int LocalTestPhase::End() const { ApiC::CleanDirectory(config_.GetTestDir()); ApiC::RemoveDirectoryT(config_.GetTestDir()); for (const auto &dimm_namespace : config_) { ApiC::CleanDirectory(dimm_namespace.GetTestDir()); ApiC::RemoveDirectoryT(dimm_namespace.GetTestDir()); } return 0; } // File doc/quickbook/oglplus/quickref/enums/program_pipeline_stage_class.hpp // // Automatically generated file, DO NOT modify manually. // Edit the source 'source/enums/oglplus/program_pipeline_stage.txt' // or the 'source/enums/make_enum.py' script instead. // // Copyright 2010-2017 . // 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 // //[oglplus_enums_program_pipeline_stage_class #if !__OGLPLUS_NO_ENUM_VALUE_CLASSES namespace enums { template class Transform> class __EnumToClass /*< Specialization of __EnumToClass for the __ProgramPipelineStage enumeration. >*/ : public Base { public: EnumToClass(void); EnumToClass(Base&& base); Transform VertexShader; Transform TessControlShader; Transform TessEvaluationShader; Transform GeometryShader; Transform FragmentShader; Transform ComputeShader; Transform AllShaders; }; } // namespace enums #endif //] samples/cpp/main.cpp #include #include "Product.hpp" int main(int argc, char* argv[]) { using namespace podo_generator; SubDim subDim{}; subDim.SetDensity(100.0f); subDim.SetWeight(200.0f); Dimensions dim{}; dim.SetHeight(100.0); dim.SetLength(200.0); dim.SetWidth(150.0); dim.SetSubDim(subDim); std::vector tags{"first tag", "second tag", "third tag"}; Reviews review1{}, review2{}; review1.SetUser("firstUser"); review1.SetRate(10); review2.SetUser("secondUser"); review2.SetRate(8); std::vector reviews{ review1, review2}; Product product{}; product.SetProductName("prodName"); product.SetProductId(123); product.SetPrice(123.0f); product.SetDimensions(dim); product.SetTags(tags); product.SetReviews(reviews); const auto res = product.ToString(); std::cout< #include "macro.hpp" #include "types.hpp" #include "functions.hpp" #include "hash.hpp" #include "hashmap.hpp" #include "serialization.hpp" #define ELEM_SEPARATOR "\n\t\t\t" namespace dbtoaster { /* Definitions of auxiliary maps for storing materialized views. */ struct NUMCUST_entry { STRING_TYPE CUSTSALE_CNTRYCODE; long __av; explicit NUMCUST_entry() { /*CUSTSALE_CNTRYCODE = ""; __av = 0L; */ } explicit NUMCUST_entry(const STRING_TYPE& c0, const long c1) { CUSTSALE_CNTRYCODE = c0; __av = c1; } NUMCUST_entry(const NUMCUST_entry& other) : CUSTSALE_CNTRYCODE( other.CUSTSALE_CNTRYCODE ), __av( other.__av ) {} FORCE_INLINE NUMCUST_entry& modify(const STRING_TYPE& c0) { CUSTSALE_CNTRYCODE = c0; return *this; } template void serialize(Archive& ar, const unsigned int version) const { ar << ELEM_SEPARATOR; DBT_SERIALIZATION_NVP(ar, CUSTSALE_CNTRYCODE); ar << ELEM_SEPARATOR; DBT_SERIALIZATION_NVP(ar, __av); } }; struct NUMCUST_mapkey0_idxfn { FORCE_INLINE static size_t hash(const NUMCUST_entry& e) { size_t h = 0; hash_combine(h, e.CUSTSALE_CNTRYCODE); return h; } FORCE_INLINE static bool equals(const NUMCUST_entry& x, const NUMCUST_entry& y) { return x.CUSTSALE_CNTRYCODE == y.CUSTSALE_CNTRYCODE; } }; typedef MultiHashMap > NUMCUST_map; typedef HashIndex HashIndex_NUMCUST_map_0; struct NUMCUSTCUSTOMER1_entry { long C_CUSTKEY; DOUBLE_TYPE C_ACCTBAL; STRING_TYPE CUSTSALE_CNTRYCODE; long __av; explicit NUMCUSTCUSTOMER1_entry() { /*C_CUSTKEY = 0L; C_ACCTBAL = 0.0; CUSTSALE_CNTRYCODE = ""; __av = 0L; */ } explicit NUMCUSTCUSTOMER1_entry(const long c0, const DOUBLE_TYPE c1, const STRING_TYPE& c2, const long c3) { C_CUSTKEY = c0; C_ACCTBAL = c1; CUSTSALE_CNTRYCODE = c2; __av = c3; } NUMCUSTCUSTOMER1_entry(const NUMCUSTCUSTOMER1_entry& other) : C_CUSTKEY( other.C_CUSTKEY ), C_ACCTBAL( other.C_ACCTBAL ), CUSTSALE_CNTRYCODE( other.CUSTSALE_CNTRYCODE ), __av( other.__av ) {} FORCE_INLINE NUMCUSTCUSTOMER1_entry& modify(const long c0, const DOUBLE_TYPE c1, const STRING_TYPE& c2) { C_CUSTKEY = c0; C_ACCTBAL = c1; CUSTSALE_CNTRYCODE = c2; return *this; } FORCE_INLINE NUMCUSTCUSTOMER1_entry& modify0(const long c0) { C_CUSTKEY = c0; return *this; } template void serialize(Archive& ar, const unsigned int version) const { ar << ELEM_SEPARATOR; DBT_SERIALIZATION_NVP(ar, C_CUSTKEY); ar << ELEM_SEPARATOR; DBT_SERIALIZATION_NVP(ar, C_ACCTBAL); ar << ELEM_SEPARATOR; DBT_SERIALIZATION_NVP(ar, CUSTSALE_CNTRYCODE); ar << ELEM_SEPARATOR; DBT_SERIALIZATION_NVP(ar, __av); } }; struct NUMCUSTCUSTOMER1_mapkey012_idxfn { FORCE_INLINE static size_t hash(const NUMCUSTCUSTOMER1_entry& e) { size_t h = 0; hash_combine(h, e.C_CUSTKEY); hash_combine(h, e.C_ACCTBAL); hash_combine(h, e.CUSTSALE_CNTRYCODE); return h; } FORCE_INLINE static bool equals(const NUMCUSTCUSTOMER1_entry& x, const NUMCUSTCUSTOMER1_entry& y) { return x.C_CUSTKEY == y.C_CUSTKEY && x.C_ACCTBAL == y.C_ACCTBAL && x.CUSTSALE_CNTRYCODE == y.CUSTSALE_CNTRYCODE; } }; struct NUMCUSTCUSTOMER1_mapkey0_idxfn { FORCE_INLINE static size_t hash(const NUMCUSTCUSTOMER1_entry& e) { size_t h = 0; hash_combine(h, e.C_CUSTKEY); return h; } FORCE_INLINE static bool equals(const NUMCUSTCUSTOMER1_entry& x, const NUMCUSTCUSTOMER1_entry& y) { return x.C_CUSTKEY == y.C_CUSTKEY; } }; typedef MultiHashMap, HashIndex > NUMCUSTCUSTOMER1_map; typedef HashIndex HashIndex_NUMCUSTCUSTOMER1_map_012; typedef HashIndex HashIndex_NUMCUSTCUSTOMER1_map_0; struct NUMCUSTCUSTOMER1_L3_1_entry { long C_CUSTKEY; long __av; explicit NUMCUSTCUSTOMER1_L3_1_entry() { /*C_CUSTKEY = 0L; __av = 0L; */ } explicit NUMCUSTCUSTOMER1_L3_1_entry(const long c0, const long c1) { C_CUSTKEY = c0; __av = c1; } NUMCUSTCUSTOMER1_L3_1_entry(const NUMCUSTCUSTOMER1_L3_1_entry& other) : C_CUSTKEY( other.C_CUSTKEY ), __av( other.__av ) {} FORCE_INLINE NUMCUSTCUSTOMER1_L3_1_entry& modify(const long c0) { C_CUSTKEY = c0; return *this; } template void serialize(Archive& ar, const unsigned int version) const { ar << ELEM_SEPARATOR; DBT_SERIALIZATION_NVP(ar, C_CUSTKEY); ar << ELEM_SEPARATOR; DBT_SERIALIZATION_NVP(ar, __av); } }; struct NUMCUSTCUSTOMER1_L3_1_mapkey0_idxfn { FORCE_INLINE static size_t hash(const NUMCUSTCUSTOMER1_L3_1_entry& e) { size_t h = 0; hash_combine(h, e.C_CUSTKEY); return h; } FORCE_INLINE static bool equals(const NUMCUSTCUSTOMER1_L3_1_entry& x, const NUMCUSTCUSTOMER1_L3_1_entry& y) { return x.C_CUSTKEY == y.C_CUSTKEY; } }; typedef MultiHashMap > NUMCUSTCUSTOMER1_L3_1_map; typedef HashIndex HashIndex_NUMCUSTCUSTOMER1_L3_1_map_0; struct TOTALACCTBAL_entry { STRING_TYPE CUSTSALE_CNTRYCODE; DOUBLE_TYPE __av; explicit TOTALACCTBAL_entry() { /*CUSTSALE_CNTRYCODE = ""; __av = 0.0; */ } explicit TOTALACCTBAL_entry(const STRING_TYPE& c0, const DOUBLE_TYPE c1) { CUSTSALE_CNTRYCODE = c0; __av = c1; } TOTALACCTBAL_entry(const TOTALACCTBAL_entry& other) : CUSTSALE_CNTRYCODE( other.CUSTSALE_CNTRYCODE ), __av( other.__av ) {} FORCE_INLINE TOTALACCTBAL_entry& modify(const STRING_TYPE& c0) { CUSTSALE_CNTRYCODE = c0; return *this; } template void serialize(Archive& ar, const unsigned int version) const { ar << ELEM_SEPARATOR; DBT_SERIALIZATION_NVP(ar, CUSTSALE_CNTRYCODE); ar << ELEM_SEPARATOR; DBT_SERIALIZATION_NVP(ar, __av); } }; struct TOTALACCTBAL_mapkey0_idxfn { FORCE_INLINE static size_t hash(const TOTALACCTBAL_entry& e) { size_t h = 0; hash_combine(h, e.CUSTSALE_CNTRYCODE); return h; } FORCE_INLINE static bool equals(const TOTALACCTBAL_entry& x, const TOTALACCTBAL_entry& y) { return x.CUSTSALE_CNTRYCODE == y.CUSTSALE_CNTRYCODE; } }; typedef MultiHashMap > TOTALACCTBAL_map; typedef HashIndex HashIndex_TOTALACCTBAL_map_0; struct TOTALACCTBALCUSTOMER1_entry { long C_CUSTKEY; DOUBLE_TYPE C_ACCTBAL; STRING_TYPE CUSTSALE_CNTRYCODE; DOUBLE_TYPE __av; explicit TOTALACCTBALCUSTOMER1_entry() { /*C_CUSTKEY = 0L; C_ACCTBAL = 0.0; CUSTSALE_CNTRYCODE = ""; __av = 0.0; */ } explicit TOTALACCTBALCUSTOMER1_entry(const long c0, const DOUBLE_TYPE c1, const STRING_TYPE& c2, const DOUBLE_TYPE c3) { C_CUSTKEY = c0; C_ACCTBAL = c1; CUSTSALE_CNTRYCODE = c2; __av = c3; } TOTALACCTBALCUSTOMER1_entry(const TOTALACCTBALCUSTOMER1_entry& other) : C_CUSTKEY( other.C_CUSTKEY ), C_ACCTBAL( other.C_ACCTBAL ), CUSTSALE_CNTRYCODE( other.CUSTSALE_CNTRYCODE ), __av( other.__av ) {} FORCE_INLINE TOTALACCTBALCUSTOMER1_entry& modify(const long c0, const DOUBLE_TYPE c1, const STRING_TYPE& c2) { C_CUSTKEY = c0; C_ACCTBAL = c1; CUSTSALE_CNTRYCODE = c2; return *this; } FORCE_INLINE TOTALACCTBALCUSTOMER1_entry& modify0(const long c0) { C_CUSTKEY = c0; return *this; } template void serialize(Archive& ar, const unsigned int version) const { ar << ELEM_SEPARATOR; DBT_SERIALIZATION_NVP(ar, C_CUSTKEY); ar << ELEM_SEPARATOR; DBT_SERIALIZATION_NVP(ar, C_ACCTBAL); ar << ELEM_SEPARATOR; DBT_SERIALIZATION_NVP(ar, CUSTSALE_CNTRYCODE); ar << ELEM_SEPARATOR; DBT_SERIALIZATION_NVP(ar, __av); } }; struct TOTALACCTBALCUSTOMER1_mapkey012_idxfn { FORCE_INLINE static size_t hash(const TOTALACCTBALCUSTOMER1_entry& e) { size_t h = 0; hash_combine(h, e.C_CUSTKEY); hash_combine(h, e.C_ACCTBAL); hash_combine(h, e.CUSTSALE_CNTRYCODE); return h; } FORCE_INLINE static bool equals(const TOTALACCTBALCUSTOMER1_entry& x, const TOTALACCTBALCUSTOMER1_entry& y) { return x.C_CUSTKEY == y.C_CUSTKEY && x.C_ACCTBAL == y.C_ACCTBAL && x.CUSTSALE_CNTRYCODE == y.CUSTSALE_CNTRYCODE; } }; struct TOTALACCTBALCUSTOMER1_mapkey0_idxfn { FORCE_INLINE static size_t hash(const TOTALACCTBALCUSTOMER1_entry& e) { size_t h = 0; hash_combine(h, e.C_CUSTKEY); return h; } FORCE_INLINE static bool equals(const TOTALACCTBALCUSTOMER1_entry& x, const TOTALACCTBALCUSTOMER1_entry& y) { return x.C_CUSTKEY == y.C_CUSTKEY; } }; typedef MultiHashMap, HashIndex > TOTALACCTBALCUSTOMER1_map; typedef HashIndex HashIndex_TOTALACCTBALCUSTOMER1_map_012; typedef HashIndex HashIndex_TOTALACCTBALCUSTOMER1_map_0; /* Type definition providing a way to access the results of the sql program */ struct tlq_t{ struct timeval t0,t; long tT,tN,tS; tlq_t(): tN(0), tS(0) { gettimeofday(&t0,NULL); } /* Serialization Code */ template void serialize(Archive& ar, const unsigned int version) const { ar << "\n"; const NUMCUST_map& _NUMCUST = get_NUMCUST(); dbtoaster::serialize_nvp_tabbed(ar, STRING_TYPE(NUMCUST), _NUMCUST, "\t"); ar << "\n"; const TOTALACCTBAL_map& _TOTALACCTBAL = get_TOTALACCTBAL(); dbtoaster::serialize_nvp_tabbed(ar, STRING_TYPE(TOTALACCTBAL), _TOTALACCTBAL, "\t"); } /* Functions returning / computing the results of top level queries */ const NUMCUST_map& get_NUMCUST() const { return NUMCUST; } const TOTALACCTBAL_map& get_TOTALACCTBAL() const { return TOTALACCTBAL; } protected: /* Data structures used for storing / computing top level queries */ NUMCUST_map NUMCUST; TOTALACCTBAL_map TOTALACCTBAL; }; /* Type definition providing a way to incrementally maintain the results of the sql program */ struct data_t : tlq_t{ data_t(): tlq_t(), NUMCUSTCUSTOMER1_L2_1_L1_1(0L), NUMCUSTCUSTOMER1_L2_2(0.0) { c7 = STRING_TYPE("17"); c2 = STRING_TYPE("31"); c1 = STRING_TYPE("13"); c3 = STRING_TYPE("23"); c6 = STRING_TYPE("18"); c4 = STRING_TYPE("29"); c5 = STRING_TYPE("30"); } /* Trigger functions for table relations */ /* Trigger functions for stream relations */ void on_insert_ORDERS(const long orders_orderkey, const long orders_custkey, const STRING_TYPE& orders_orderstatus, const DOUBLE_TYPE orders_totalprice, const date orders_orderdate, const STRING_TYPE& orders_orderpriority, const STRING_TYPE& orders_clerk, const long orders_shippriority, const STRING_TYPE& orders_comment) { { if (tS>0) { ++tS; return; } if ((tN&127)==0) { gettimeofday(&(t),NULL); tT=((t).tv_sec-(t0).tv_sec)*1000000L+((t).tv_usec-(t0).tv_usec); if (tT>3600000000L) { tS=1; return; } } ++tN; long agg1 = 0L; long l1 = (NUMCUSTCUSTOMER1_L3_1.getValueOrDefault(se2.modify(orders_custkey)) + 1L); (/*if */(l1 == 0L) ? agg1 += 1L : 0L); long agg2 = 0L; long l2 = NUMCUSTCUSTOMER1_L3_1.getValueOrDefault(se3.modify(orders_custkey)); (/*if */(l2 == 0L) ? agg2 += 1L : 0L); DOUBLE_TYPE agg3 = 0.0; long l4 = NUMCUSTCUSTOMER1_L2_1_L1_1; (/*if */(0L != l4) ? agg3 += Udiv(Ulistmax(1L, l4)) : 0.0); DOUBLE_TYPE l3 = (NUMCUSTCUSTOMER1_L2_2 * agg3); { //slice const HashIndex_NUMCUSTCUSTOMER1_map_0* i1 = static_cast(NUMCUSTCUSTOMER1.index[1]); const HASH_RES_t h1 = NUMCUSTCUSTOMER1_mapkey0_idxfn::hash(se4.modify0(orders_custkey)); HashIndex_NUMCUSTCUSTOMER1_map_0::IdxNode* n1 = static_cast(i1->slice(se4, h1)); NUMCUSTCUSTOMER1_entry* e1; if (n1 && (e1 = n1->obj)) { do { DOUBLE_TYPE c_acctbal = e1->C_ACCTBAL; STRING_TYPE custsale_cntrycode = e1->CUSTSALE_CNTRYCODE; long v1 = e1->__av; (/*if */(c_acctbal > l3) ? NUMCUST.addOrDelOnZero(se1.modify(custsale_cntrycode),((agg1 + (agg2 * -1L)) * v1)) : (void)0); n1 = n1->nxt; } while (n1 && (e1 = n1->obj) && h1 == n1->hash && NUMCUSTCUSTOMER1_mapkey0_idxfn::equals(se4, *e1)); } }long agg4 = 0L; long l5 = (NUMCUSTCUSTOMER1_L3_1.getValueOrDefault(se6.modify(orders_custkey)) + 1L); (/*if */(l5 == 0L) ? agg4 += 1L : 0L); long agg5 = 0L; long l6 = NUMCUSTCUSTOMER1_L3_1.getValueOrDefault(se7.modify(orders_custkey)); (/*if */(l6 == 0L) ? agg5 += 1L : 0L); DOUBLE_TYPE agg6 = 0.0; long l8 = NUMCUSTCUSTOMER1_L2_1_L1_1; (/*if */(0L != l8) ? agg6 += Udiv(Ulistmax(1L, l8)) : 0.0); DOUBLE_TYPE l7 = (NUMCUSTCUSTOMER1_L2_2 * agg6); { //slice const HashIndex_TOTALACCTBALCUSTOMER1_map_0* i2 = static_cast(TOTALACCTBALCUSTOMER1.index[1]); const HASH_RES_t h2 = TOTALACCTBALCUSTOMER1_mapkey0_idxfn::hash(se8.modify0(orders_custkey)); HashIndex_TOTALACCTBALCUSTOMER1_map_0::IdxNode* n2 = static_cast(i2->slice(se8, h2)); TOTALACCTBALCUSTOMER1_entry* e2; if (n2 && (e2 = n2->obj)) { do { DOUBLE_TYPE c_acctbal = e2->C_ACCTBAL; STRING_TYPE custsale_cntrycode = e2->CUSTSALE_CNTRYCODE; DOUBLE_TYPE v2 = e2->__av; (/*if */(c_acctbal > l7) ? TOTALACCTBAL.addOrDelOnZero(se5.modify(custsale_cntrycode),((agg4 + (agg5 * -1L)) * v2)) : (void)0); n2 = n2->nxt; } while (n2 && (e2 = n2->obj) && h2 == n2->hash && TOTALACCTBALCUSTOMER1_mapkey0_idxfn::equals(se8, *e2)); } }NUMCUSTCUSTOMER1_L3_1.addOrDelOnZero(se9.modify(orders_custkey),1L); } } void on_insert_CUSTOMER(const long customer_custkey, const STRING_TYPE& customer_name, const STRING_TYPE& customer_address, const long customer_nationkey, const STRING_TYPE& customer_phone, const DOUBLE_TYPE customer_acctbal, const STRING_TYPE& customer_mktsegment, const STRING_TYPE& customer_comment) { { if (tS>0) { ++tS; return; } if ((tN&127)==0) { gettimeofday(&(t),NULL); tT=((t).tv_sec-(t0).tv_sec)*1000000L+((t).tv_usec-(t0).tv_usec); if (tT>3600000000L) { tS=1; return; } } ++tN; STRING_TYPE l9 = Usubstring(customer_phone, 0L, 2L); (/*if */(((l9 == c1) || (l9 == c2) || (l9 == c3) || (l9 == c4) || (l9 == c5) || (l9 == c6) || (l9 == c7))) ? NUMCUSTCUSTOMER1.addOrDelOnZero(se10.modify(customer_custkey,customer_acctbal,l9),1L) : (void)0); (/*if */(customer_acctbal > 0.0 && ((l9 == c1) || (l9 == c2) || (l9 == c3) || (l9 == c4) || (l9 == c5) || (l9 == c6) || (l9 == c7))) ? NUMCUSTCUSTOMER1_L2_1_L1_1 += 1L : 0L); (/*if */(customer_acctbal > 0.0 && ((l9 == c1) || (l9 == c2) || (l9 == c3) || (l9 == c4) || (l9 == c5) || (l9 == c6) || (l9 == c7))) ? NUMCUSTCUSTOMER1_L2_2 += customer_acctbal : 0L); (/*if */(((l9 == c1) || (l9 == c2) || (l9 == c3) || (l9 == c4) || (l9 == c5) || (l9 == c6) || (l9 == c7))) ? TOTALACCTBALCUSTOMER1.addOrDelOnZero(se13.modify(customer_custkey,customer_acctbal,l9),customer_acctbal) : (void)0); NUMCUST.clear(); DOUBLE_TYPE agg7 = 0.0; long l12 = NUMCUSTCUSTOMER1_L2_1_L1_1; (/*if */(0L != l12) ? agg7 += Udiv(Ulistmax(1L, l12)) : 0.0); DOUBLE_TYPE l11 = (NUMCUSTCUSTOMER1_L2_2 * agg7); long l13 = 0L; { // foreach const HashIndex_NUMCUSTCUSTOMER1_map_012* i3 = static_cast(NUMCUSTCUSTOMER1.index[0]); HashIndex_NUMCUSTCUSTOMER1_map_012::IdxNode* n3; NUMCUSTCUSTOMER1_entry* e3; for (size_t i = 0; i < i3->size_; i++) { n3 = i3->buckets_ + i; while (n3 && (e3 = n3->obj)) { long c_custkey = e3->C_CUSTKEY; DOUBLE_TYPE c_acctbal = e3->C_ACCTBAL; STRING_TYPE custsale_cntrycode = e3->CUSTSALE_CNTRYCODE; long v3 = e3->__av; (/*if */(c_acctbal > l11 && l13 == NUMCUSTCUSTOMER1_L3_1.getValueOrDefault(se15.modify(c_custkey))) ? NUMCUST.addOrDelOnZero(se14.modify(custsale_cntrycode),v3) : (void)0); n3 = n3->nxt; } } }TOTALACCTBAL.clear(); DOUBLE_TYPE agg8 = 0.0; long l15 = NUMCUSTCUSTOMER1_L2_1_L1_1; (/*if */(0L != l15) ? agg8 += Udiv(Ulistmax(1L, l15)) : 0.0); DOUBLE_TYPE l14 = (NUMCUSTCUSTOMER1_L2_2 * agg8); long l16 = 0L; { // foreach const HashIndex_TOTALACCTBALCUSTOMER1_map_012* i4 = static_cast(TOTALACCTBALCUSTOMER1.index[0]); HashIndex_TOTALACCTBALCUSTOMER1_map_012::IdxNode* n4; TOTALACCTBALCUSTOMER1_entry* e4; for (size_t i = 0; i < i4->size_; i++) { n4 = i4->buckets_ + i; while (n4 && (e4 = n4->obj)) { long c_custkey = e4->C_CUSTKEY; DOUBLE_TYPE c_acctbal = e4->C_ACCTBAL; STRING_TYPE custsale_cntrycode = e4->CUSTSALE_CNTRYCODE; DOUBLE_TYPE v4 = e4->__av; (/*if */(c_acctbal > l14 && l16 == NUMCUSTCUSTOMER1_L3_1.getValueOrDefault(se17.modify(c_custkey))) ? TOTALACCTBAL.addOrDelOnZero(se16.modify(custsale_cntrycode),v4) : (void)0); n4 = n4->nxt; } } } } } void on_system_ready_event() { { NUMCUSTCUSTOMER1_L2_2 = 0.0; } } private: /* Sample entries for avoiding recreation of temporary objects */ NUMCUST_entry se1; NUMCUSTCUSTOMER1_L3_1_entry se2; NUMCUSTCUSTOMER1_L3_1_entry se3; NUMCUSTCUSTOMER1_entry se4; TOTALACCTBAL_entry se5; NUMCUSTCUSTOMER1_L3_1_entry se6; NUMCUSTCUSTOMER1_L3_1_entry se7; TOTALACCTBALCUSTOMER1_entry se8; NUMCUSTCUSTOMER1_L3_1_entry se9; NUMCUSTCUSTOMER1_entry se10; TOTALACCTBALCUSTOMER1_entry se13; NUMCUST_entry se14; NUMCUSTCUSTOMER1_L3_1_entry se15; TOTALACCTBAL_entry se16; NUMCUSTCUSTOMER1_L3_1_entry se17; /* Data structures used for storing materialized views */ NUMCUSTCUSTOMER1_map NUMCUSTCUSTOMER1; long NUMCUSTCUSTOMER1_L2_1_L1_1; DOUBLE_TYPE NUMCUSTCUSTOMER1_L2_2; NUMCUSTCUSTOMER1_L3_1_map NUMCUSTCUSTOMER1_L3_1; TOTALACCTBALCUSTOMER1_map TOTALACCTBALCUSTOMER1; /*const static*/ STRING_TYPE c7; /*const static*/ STRING_TYPE c2; /*const static*/ STRING_TYPE c1; /*const static*/ STRING_TYPE c3; /*const static*/ STRING_TYPE c6; /*const static*/ STRING_TYPE c4; /*const static*/ STRING_TYPE c5; }; } 1-10 #include #include #include #include "Header.h" using namespace std; template void printMe(T thingy) { cout << thingy << endl; } int main() { vector numbers; numbers.push_back(1); printMe(10); printMe("ten"); printMe(10.1); string input; int number; bool failed = true; do { cout << "Enter a number" << endl; cin >> input; try { number = stoi(input); failed = false; } catch (invalid_argument) { cout << "Could not convert " << input << " to a number, try again" << endl; } } while (failed); cout << "Your number was: " << number << endl; cout << "Enter your name: " << endl; string name; cin >> name; Person you; you.setName(name); failed = true; do { try { cout << "Enter your age in years: " << endl; double age; cin >> age; you.setAgeInYears(age); failed = false; } catch (invalid_argument ex) { cout << ex.what() << endl; } } while (failed); Pair student(1, you); return 0; }0 #include "messagehandler.h" #include "window.h" // #include "button.h" #include "textbox.h" // #include "image.h" // #include "checkbox.h" using namespace UGUI; void MessageHandler::cb(UG_MESSAGE *msg) { MessageHandler *self = nullptr; UG_OBJECT *obj; switch (msg->type) { case MSG_TYPE_WINDOW: self = container_of((UG_WINDOW*)msg->src, Window, _wnd); break; case MSG_TYPE_OBJECT: obj = reinterpret_cast(msg->src); switch (obj->type) { // case OBJ_TYPE_BUTTON: self = container_of(obj->data, ); break; case OBJ_TYPE_TEXTBOX: self = container_of((UG_TEXTBOX*)obj->data, Textbox, _txb); break; // case OBJ_TYPE_IMAGE: self = container_of(obj->data, ); break; // case OBJ_TYPE_CHECKBOX: self = container_of(obj->data, ); break; } break; } if (self) self->handleMessage(msg); } /* * Appcelerator Kroll - licensed under the Apache Public License 2 * see LICENSE in the root folder for details on the license. * Copyright (c) 2009 Appcelerator, Inc. All Rights Reserved. */ #include "../kroll.h" namespace kroll { ReadEvent::ReadEvent(AutoPtr target, BytesRef data) : Event(target, Event::READ), data(data) { this->SetMethod("getData", &ReadEvent::_GetData); } void ReadEvent::_GetData(const ValueList&, KValueRef result) { result->SetObject(this->data); } } src/Control/FileParser.hpp0 // ***************************************************************************** /*! \file src/Control/FileParser.hpp \copyright 2012-2015 , 2016-2018 Los Alamos National Security, LLC., 2019 Triad National Security, LLC. All rights reserved. See the LICENSE file for details. \brief File parser base class declaration \details File parser base class declaration. File parser base serves as a base class for various file parsers, e.g., input deck parsers. It does generic low-level I/O, e.g., testing whether the file to be parsed exits or not and associated error handling, as well as after-parser diagnostics. */ // ***************************************************************************** #ifndef FileParser_h #define FileParser_h #include #include namespace tk { class Print; //! FileParser class FileParser { protected: //! \brief Constructor explicit FileParser( const std::string& filename ); //! \brief Echo errors accumulated during parsing void diagnostics( const tk::Print& print, const std::vector< std::string >& messages ); const std::string m_filename; //!< Name of file to parse }; } // tk:: #endif // FileParser_h zoloypzuo/Sandbox // ========================================================== // JPEG2000 helpers // // Design and implementation by // - Herv?Drolon () // // This file is part of FreeImage 3 // // COVERED CODE IS PROVIDED UNDER THIS LICENSE ON AN "AS IS" BASIS, WITHOUT WARRANTY // OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, WARRANTIES // THAT THE COVERED CODE IS FREE OF DEFECTS, MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE // OR NON-INFRINGING. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE COVERED // CODE IS WITH YOU. SHOULD ANY COVERED CODE PROVE DEFECTIVE IN ANY RESPECT, YOU (NOT // THE INITIAL DEVELOPER OR ANY OTHER CONTRIBUTOR) ASSUME THE COST OF ANY NECESSARY // SERVICING, REPAIR OR CORRECTION. THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL // PART OF THIS LICENSE. NO USE OF ANY COVERED CODE IS AUTHORIZED HEREUNDER EXCEPT UNDER // THIS DISCLAIMER. // // Use at your own risk! // ========================================================== #include "FreeImage.h" #include "Utilities.h" #include "openjpeg.h" /** Divide an integer by a power of 2 and round upwards @return Returns a divided by 2^b */ static int int_ceildivpow2(int a, int b) { return (a + (1 << b) - 1) >> b; } /** Convert a OpenJPEG image to a FIBITMAP @param format_id Plugin ID @param image OpenJPEG image @return Returns the converted image if successful, returns NULL otherwise */ FIBITMAP* J2KImageToFIBITMAP(int format_id, const opj_image_t *image) { FIBITMAP *dib = NULL; try { // compute image width and height //int w = int_ceildiv(image->x1 - image->x0, image->comps[0].dx); int wr = image->comps[0].w; int wrr = int_ceildivpow2(image->comps[0].w, image->comps[0].factor); //int h = int_ceildiv(image->y1 - image->y0, image->comps[0].dy); //int hr = image->comps[0].h; int hrr = int_ceildivpow2(image->comps[0].h, image->comps[0].factor); // check the number of components int numcomps = image->numcomps; BOOL bIsValid = TRUE; for(int c = 0; c < numcomps - 1; c++) { if( (image->comps[c].dx == image->comps[c+1].dx) && (image->comps[c].dy == image->comps[c+1].dy) && (image->comps[c].prec == image->comps[c+1].prec) ) { continue; } else { bIsValid = FALSE; break; } } bIsValid &= ((numcomps == 1) || (numcomps == 3) || (numcomps == 4)); if(!bIsValid) { if(numcomps) { FreeImage_OutputMessageProc(format_id, "Warning: image contains %d greyscale components. Only the first will be loaded.\n", numcomps); numcomps = 1; } else { // unknown type throw FI_MSG_ERROR_UNSUPPORTED_FORMAT; } } // create a new DIB if(image->comps[0].prec <= 8) { switch(numcomps) { case 1: dib = FreeImage_Allocate(wrr, hrr, 8); break; case 3: dib = FreeImage_Allocate(wrr, hrr, 24, FI_RGBA_RED_MASK, FI_RGBA_GREEN_MASK, FI_RGBA_BLUE_MASK); break; case 4: dib = FreeImage_Allocate(wrr, hrr, 32, FI_RGBA_RED_MASK, FI_RGBA_GREEN_MASK, FI_RGBA_BLUE_MASK); break; } } else if(image->comps[0].prec <= 16) { switch(numcomps) { case 1: dib = FreeImage_AllocateT(FIT_UINT16, wrr, hrr); break; case 3: dib = FreeImage_AllocateT(FIT_RGB16, wrr, hrr); break; case 4: dib = FreeImage_AllocateT(FIT_RGBA16, wrr, hrr); break; } } else { throw FI_MSG_ERROR_UNSUPPORTED_FORMAT; } if(!dib) { throw FI_MSG_ERROR_DIB_MEMORY; } if(image->comps[0].prec <= 8) { if(numcomps == 1) { // 8-bit greyscale // ---------------------------------------------------------- // build a greyscale palette RGBQUAD *pal = FreeImage_GetPalette(dib); for (int i = 0; i < 256; i++) { pal[i].rgbRed = (BYTE)i; pal[i].rgbGreen = (BYTE)i; pal[i].rgbBlue = (BYTE)i; } // load pixel data unsigned pixel_count = 0; for(int y = 0; y < hrr; y++) { BYTE *bits = FreeImage_GetScanLine(dib, hrr - 1 - y); for(int x = 0; x < wrr; x++) { const unsigned pixel_pos = pixel_count / wrr * wr + pixel_count % wrr; int index = image->comps[0].data[pixel_pos]; index += (image->comps[0].sgnd ? 1 << (image->comps[0].prec - 1) : 0); bits[x] = (BYTE)index; pixel_count++; } } } else if(numcomps == 3) { // 24-bit RGB // ---------------------------------------------------------- // load pixel data unsigned pixel_count = 0; for(int y = 0; y < hrr; y++) { BYTE *bits = FreeImage_GetScanLine(dib, hrr - 1 - y); for(int x = 0; x < wrr; x++) { const unsigned pixel_pos = pixel_count / wrr * wr + pixel_count % wrr; int r = image->comps[0].data[pixel_pos]; r += (image->comps[0].sgnd ? 1 << (image->comps[0].prec - 1) : 0); int g = image->comps[1].data[pixel_pos]; g += (image->comps[1].sgnd ? 1 << (image->comps[1].prec - 1) : 0); int b = image->comps[2].data[pixel_pos]; b += (image->comps[2].sgnd ? 1 << (image->comps[2].prec - 1) : 0); bits[FI_RGBA_RED] = (BYTE)r; bits[FI_RGBA_GREEN] = (BYTE)g; bits[FI_RGBA_BLUE] = (BYTE)b; bits += 3; pixel_count++; } } } else if(numcomps == 4) { // 32-bit RGBA // ---------------------------------------------------------- // load pixel data unsigned pixel_count = 0; for(int y = 0; y < hrr; y++) { BYTE *bits = FreeImage_GetScanLine(dib, hrr - 1 - y); for(int x = 0; x < wrr; x++) { const unsigned pixel_pos = pixel_count / wrr * wr + pixel_count % wrr; int r = image->comps[0].data[pixel_pos]; r += (image->comps[0].sgnd ? 1 << (image->comps[0].prec - 1) : 0); int g = image->comps[1].data[pixel_pos]; g += (image->comps[1].sgnd ? 1 << (image->comps[1].prec - 1) : 0); int b = image->comps[2].data[pixel_pos]; b += (image->comps[2].sgnd ? 1 << (image->comps[2].prec - 1) : 0); int a = image->comps[3].data[pixel_pos]; a += (image->comps[3].sgnd ? 1 << (image->comps[3].prec - 1) : 0); bits[FI_RGBA_RED] = (BYTE)r; bits[FI_RGBA_GREEN] = (BYTE)g; bits[FI_RGBA_BLUE] = (BYTE)b; bits[FI_RGBA_ALPHA] = (BYTE)a; bits += 4; pixel_count++; } } } } else if(image->comps[0].prec <= 16) { if(numcomps == 1) { // 16-bit greyscale // ---------------------------------------------------------- // load pixel data unsigned pixel_count = 0; for(int y = 0; y < hrr; y++) { unsigned short *bits = (unsigned short*)FreeImage_GetScanLine(dib, hrr - 1 - y); for(int x = 0; x < wrr; x++) { const unsigned pixel_pos = pixel_count / wrr * wr + pixel_count % wrr; int index = image->comps[0].data[pixel_pos]; index += (image->comps[0].sgnd ? 1 << (image->comps[0].prec - 1) : 0); bits[x] = (unsigned short)index; pixel_count++; } } } else if(numcomps == 3) { // 48-bit RGB // ---------------------------------------------------------- // load pixel data unsigned pixel_count = 0; for(int y = 0; y < hrr; y++) { FIRGB16 *bits = (FIRGB16*)FreeImage_GetScanLine(dib, hrr - 1 - y); for(int x = 0; x < wrr; x++) { const unsigned pixel_pos = pixel_count / wrr * wr + pixel_count % wrr; int r = image->comps[0].data[pixel_pos]; r += (image->comps[0].sgnd ? 1 << (image->comps[0].prec - 1) : 0); int g = image->comps[1].data[pixel_pos]; g += (image->comps[1].sgnd ? 1 << (image->comps[1].prec - 1) : 0); int b = image->comps[2].data[pixel_pos]; b += (image->comps[2].sgnd ? 1 << (image->comps[2].prec - 1) : 0); bits[x].red = (WORD)r; bits[x].green = (WORD)g; bits[x].blue = (WORD)b; pixel_count++; } } } else if(numcomps == 4) { // 64-bit RGBA // ---------------------------------------------------------- // load pixel data unsigned pixel_count = 0; for(int y = 0; y < hrr; y++) { FIRGBA16 *bits = (FIRGBA16*)FreeImage_GetScanLine(dib, hrr - 1 - y); for(int x = 0; x < wrr; x++) { const unsigned pixel_pos = pixel_count / wrr * wr + pixel_count % wrr; int r = image->comps[0].data[pixel_pos]; r += (image->comps[0].sgnd ? 1 << (image->comps[0].prec - 1) : 0); int g = image->comps[1].data[pixel_pos]; g += (image->comps[1].sgnd ? 1 << (image->comps[1].prec - 1) : 0); int b = image->comps[2].data[pixel_pos]; b += (image->comps[2].sgnd ? 1 << (image->comps[2].prec - 1) : 0); int a = image->comps[3].data[pixel_pos]; a += (image->comps[3].sgnd ? 1 << (image->comps[3].prec - 1) : 0); bits[x].red = (WORD)r; bits[x].green = (WORD)g; bits[x].blue = (WORD)b; bits[x].alpha = (WORD)a; pixel_count++; } } } } return dib; } catch(const char *text) { if(dib) FreeImage_Unload(dib); FreeImage_OutputMessageProc(format_id, text); return NULL; } } /** Convert a FIBITMAP to a OpenJPEG image @param format_id Plugin ID @param dib FreeImage image @param parameters Compression parameters @return Returns the converted image if successful, returns NULL otherwise */ opj_image_t* FIBITMAPToJ2KImage(int format_id, FIBITMAP *dib, const opj_cparameters_t *parameters) { int prec, numcomps, x, y, index; OPJ_COLOR_SPACE color_space; opj_image_cmptparm_t cmptparm[4]; // maximum of 4 components opj_image_t *image = NULL; // image to encode try { int w = FreeImage_GetWidth(dib); int h = FreeImage_GetHeight(dib); // get image characteristics FREE_IMAGE_TYPE image_type = FreeImage_GetImageType(dib); if(image_type == FIT_BITMAP) { // standard image ... prec = 8; switch(FreeImage_GetColorType(dib)) { case FIC_MINISBLACK: numcomps = 1; color_space = CLRSPC_GRAY; break; case FIC_RGB: if(FreeImage_GetBPP(dib) == 32) { // 32-bit image with a fully opaque layer numcomps = 4; color_space = CLRSPC_SRGB; } else { // 24-bit image numcomps = 3; color_space = CLRSPC_SRGB; } break; case FIC_RGBALPHA: numcomps = 4; color_space = CLRSPC_SRGB; break; default: return NULL; } } else { // HDR image ... prec = 16; switch(image_type) { case FIT_UINT16: numcomps = 1; color_space = CLRSPC_GRAY; break; case FIT_RGB16: numcomps = 3; color_space = CLRSPC_SRGB; break; case FIT_RGBA16: numcomps = 4; color_space = CLRSPC_SRGB; break; default: return NULL; } } // initialize image components memset(&cmptparm[0], 0, 4 * sizeof(opj_image_cmptparm_t)); for(int i = 0; i < numcomps; i++) { cmptparm[i].dx = parameters->subsampling_dx; cmptparm[i].dy = parameters->subsampling_dy; cmptparm[i].w = w; cmptparm[i].h = h; cmptparm[i].prec = prec; cmptparm[i].bpp = prec; cmptparm[i].sgnd = 0; } // create the image image = opj_image_create(numcomps, &cmptparm[0], color_space); if(!image) { throw FI_MSG_ERROR_DIB_MEMORY; } // set image offset and reference grid image->x0 = parameters->image_offset_x0; image->y0 = parameters->image_offset_y0; image->x1 = parameters->image_offset_x0 + (w - 1) * parameters->subsampling_dx + 1; image->y1 = parameters->image_offset_y0 + (h - 1) * parameters->subsampling_dy + 1; // set image data if(prec == 8) { switch(numcomps) { case 1: index = 0; for(y = 0; y < h; y++) { BYTE *bits = FreeImage_GetScanLine(dib, h - 1 - y); for(x = 0; x < w; x++) { image->comps[0].data[index] = bits[x]; index++; } } break; case 3: index = 0; for(y = 0; y < h; y++) { BYTE *bits = FreeImage_GetScanLine(dib, h - 1 - y); for(x = 0; x < w; x++) { image->comps[0].data[index] = bits[FI_RGBA_RED]; image->comps[1].data[index] = bits[FI_RGBA_GREEN]; image->comps[2].data[index] = bits[FI_RGBA_BLUE]; bits += 3; index++; } } break; case 4: index = 0; for(y = 0; y < h; y++) { BYTE *bits = FreeImage_GetScanLine(dib, h - 1 - y); for(x = 0; x < w; x++) { image->comps[0].data[index] = bits[FI_RGBA_RED]; image->comps[1].data[index] = bits[FI_RGBA_GREEN]; image->comps[2].data[index] = bits[FI_RGBA_BLUE]; image->comps[3].data[index] = bits[FI_RGBA_ALPHA]; bits += 4; index++; } } break; } } else if(prec == 16) { switch(numcomps) { case 1: index = 0; for(y = 0; y < h; y++) { WORD *bits = (WORD*)FreeImage_GetScanLine(dib, h - 1 - y); for(x = 0; x < w; x++) { image->comps[0].data[index] = bits[x]; index++; } } break; case 3: index = 0; for(y = 0; y < h; y++) { FIRGB16 *bits = (FIRGB16*)FreeImage_GetScanLine(dib, h - 1 - y); for(x = 0; x < w; x++) { image->comps[0].data[index] = bits[x].red; image->comps[1].data[index] = bits[x].green; image->comps[2].data[index] = bits[x].blue; index++; } } break; case 4: index = 0; for(y = 0; y < h; y++) { FIRGBA16 *bits = (FIRGBA16*)FreeImage_GetScanLine(dib, h - 1 - y); for(x = 0; x < w; x++) { image->comps[0].data[index] = bits[x].red; image->comps[1].data[index] = bits[x].green; image->comps[2].data[index] = bits[x].blue; image->comps[3].data[index] = bits[x].alpha; index++; } } break; } } return image; } catch (const char *text) { if(image) opj_image_destroy(image); FreeImage_OutputMessageProc(format_id, text); return NULL; } } /* * Autor : * Codigo: 20163275 * */ #include "Bib_Func_Provincias.h" #include "Biblioteca_Func_Incendios.h" int main() { char*** provincias; long int*** incendios; leerProvincias(provincias); imprimirProvincias(provincias); leerIncendios(incendios,provincias); imprimirIncendios(incendios,provincias); return 0; }majenkotech/PulseRifleStdCN #include "sounds.h" const short gl_rack_pull[] = { -841, -297, 884, 348, 261, -844, 346, 847, 719, -977, -618, 1029, 752, 338, 1359, 430, 550, -257, 756, -149, 152, -153, 189, 95, -498, 523, -270, 197, 184, 888, 35, 1489, -372, 216, 148, -164, -480, 815, -1027, 712, -727, -993, -178, -283, 134, -676, 683, 1918, -230, 2537, 33, 995, -1036, -382, -1130, 620, 428, 390, -437, 73, 565, 67, 630, 654, 697, -488, -805, -442, -31, -260, 1419, -1700, 15, 545, 1318, -198, 200, 556, -1630, 353, -1479, -806, 410, 16, -2670, 706, 142, -3246, 2449, -882, 2677, -3889, 2492, -968, 1113, -307, -182, -89, 382, 1050, -1212, -1188, 1122, 1145, -1296, 676, -2734, 157, 326, -1819, 894, -212, -124, 227, 1527, 601, 1096, 7, 505, 1082, 654, -41, 410, 292, -150, 161, -121, 727, -1924, -153, 1100, -453, -314, 394, 1059, -563, 165, -205, -1063, -520, -1882, 66, 598, 20, 584, -1109, 426, -307, -140, 130, 1202, -1048, 786, -412, -621, -424, -1946, 773, 1672, -723, -1904, 816, 827, 2695, -518, 883, -596, -1500, 1472, -28, -544, 1530, 1582, -1630, 412, 1256, 903, 24, 2411, 532, 935, -824, -53, -735, -422, -1202, 1893, -935, -445, 161, 621, -711, -844, -751, -1566, -500, -2453, -1477, -306, 968, -1113, -1149, -1972, 415, -403, 620, -832, 1715, 2517, 77, 5462, -1053, 27577, 2790, -20599, 10928, -16612, 9756, -17632, -27698, 19140, -8808, -14035, 15650, 827, 14102, 13124, -9054, 17513, 1749, 10998, -12573, 4690, -14639, -2746, -15164, 399, -14393, -12020, -11099, -5287, -3749, -3945, -564, -2216, 10587, -3304, 11060, 2004, 13284, 5018, 9612, 9, 12231, 242, 5213, 123, -1108, -4870, -3878, -6650, -8906, -6667, -6799, -3556, -6617, 67, -2789, 3662, -2279, 5434, -2435, 6965, -3342, 6049, -3380, 3991, -4455, 661, -2985, 1880, -4066, 1785, -5658, -113, 2201, -342, 939, -3142, 3819, -1203, -793, -11880, -27238, -22053, -19771, -3449, -25977, 1747, 21333, 15098, 9915, 1081, 14496, 16788, 27904, 5893, 1491, -4122, -12671, 9492, 4393, -3556, 4735, 25973, 29234, 28805, -2053, 24125, -246, 18781, 5970, 1757, -4027, -10889, 16549, 4014, 8109, -10526, -19226, 18239, -3927, -9130, 17331, -23009, 2079, 18974, -13368, -4723, 3087, -748, 1342, 16118, -2323, -964, 12231, -3332, 1481, 8005, -13490, -80, 13401, -1823, 10055, -11887, -522, 10100, 2971, 3790, -5058, 9678, -4192, -4284, 6983, -739, -325, -3189, 4174, 3189, 1883, 3763, -7482, 2113, -1229, 1156, 1184, 6847, -4373, 3954, -2680, -4450, -1109, -3170, -3751, -7952, 5838, 1115, 4716, 1296, -3472, 1389, -1572, 1095, -3295, -2657, -2033, 507, 1648, 2497, -840, 454, -558, 1015, -275, -1606, 686, 1494, -2703, 2452, -864, -390, 584, 2079, -2941, -2289, -35, -1992, 814, 1418, 1774, -298, 3277, -818, -1764, -170, -1100, -1126, 1394, 70, -4793, 4235, 1945, -1516, -1065, 165, 2634, -1809, -1830, 512, -1285, 1698, -2989, 802, -3205, -2341, 1081, 599, -1863, -2089, 1344, -2296, -3117, -167, -1211, -888, -1258, 1866, -3262, 2797, 26, 822, -1189, -1964, 840, -1519, -636, -1135, -1029, -127, -164, 376, 1839, 1272, -1196, 449, -1420, 767, 1044, -794, 998, -273, 478, 1376, 462, 1113, -1949, 1498, -3250, 241, 902, 11, 1690, -83, 549, 1403, 2685, 599, 1116, -580, -1112, 1156, 2402, 1893, -3463, 1005, 553, 1523, -643, -2866, -1051, 1007, 80, 319, 125, -221, -956, 4956, -2923, 2169, -1715, 2047, 2622, 2573, -424, -1467, 2375, -101, -2332, -1053, 1143, -22, -1275, -2825, -1369, 1619, -493, -529, -1674, -2281, -354, -318, -1226, 1184, 2871, -2139, 687, 1150, 2380, 140, -1678, 1517, 759, -191, -1013, 490, -232, -831, -1488, -2221, 1979, 992, 100, -766, -440, -1518, -808, 399, -36, -665, 327, 332, -347, 2137, 480, -546, 1370, -2364, -645, 740, 1832, -587, -1125, 1744, -383, 1698, 1140, -1601, 1248, -1342, -1447, 1399, -1229, -1472, -1419, 2310, -2094, 213, 271, 2962, -2934, -270, 900, -1057, 1262, -1467, 538, -1583, 107, 1289, -766, 1825, -2084, 2361, 2040, -736, -879, 168, -767, 994, 1019, -3376, 561, 268, -226, -603, 365, 2462, -2135, 1108, -1001, -212, -1713, 1310, -198, -436, 845, 2857, 511, -480, 3841, -359, 53, 3332, 572, -3010, 981, 13, -2970, -985, 1159, 410, 291, -938, -1029, -884, 1206, -1191, -1655, 4071, -1024, -141, -3715, -204, -31, -2065, 1750, 657, 2849, -2286, -1318, 1503, 238, -16, 813, 1296, -1070, 54, -234, 329, 1100, 657, 567, -2090, -2017, -1217, 655, -783, -1743, -961, 2764, 351, 598, 1700, -298, 6165, -2632, 2258, -4513, -2763, -683, 4279, -2118, -309, -1733, 5921, -2619, 3105, -1350, -5105, -1554, 4433, 1680, -4823, 1007, 5572, 1684, -992, -410, 825, -289, 770, -1705, -4570, -1191, 1288, -8678, -1486, -8017, -1117, -9326, 8199, 19871, 4631, 5951, 2090, -2250, -7634, -2429, -285, -613, 4261, 6294, -48, 4724, -1809, -6070, -6780, -141, 3372, 141, 2299, -2847, -1634, 5766, 3117, 1187, 615, 223, 54, -1578, 1434, -1350, -6537, 12799, -1977, -3694, -6882, -8010, -14588, -1129, 4448, 377, -395, 4746, 497, -1414, 5599, 1906, 6794, 3872, -268, -4700, 2359, -4681, 7948, 1936, -4949, -1513, -1693, 3955, -3848, -236, -900, 1139, -2282, 1909, 2197, -2072, -1187, 67, 1208, -3486, -569, 383, -573, 806, -2297, 808, 829, 704, -1119, 2724, 1138, -1949, 7, -218, 64, -798, 1128, 1142, 1073, 1708, 923, -1636, -40, -443, 2076, -110, -227, 124, 1648, 2007, -1661, -878, 606, -320, -1665, 1589, 507, 1059, -769, 1451, -97, 2290, 1275, -540, -1164, -1545, 431, 1520, -2478, -396, -376, 188, -2335, 483, -558, -579, 513, -601, -336, -537, 6, -1195, -1148, -503, 672, 1523, 1502, -191, -1299, 1065, -1339, -1236, 1480, 836, 20, 611, -1866, -1924, 1779, 208, 95, -575, 2282, 461, 98, -265, -1690, 99, 1271, -31, 373, -2397, -930, 757, -493, 2470, -280, 703, 89, -2, -397, 597, 1459, -939, 25, -2189, -1472, 1553, 1730, 914, 432, -83, 1571, 158, -2204, -2503, -1486, 371, 647, 316, 668, -568, 2440, -115, -536, 566, -968, -1411, -1000, -201, -98, 889, 1487, 640, 2328, -1170, -1936, -855, -1000, 608, -123, 237, -470, 2930, -956, 269, -1056, 2422, -1176, 628, -2305, -489, -1678, 617, 2006, -53, -2726, 1462, 550, -2828, 62, 3542, 995, 1180, -187, 766, -2597, -335, 816, -6823, 2604, -1918, 1430, -110, -3068, -2389, 2116, 3224, 736, 462, 3146, 2030, -2087, -6980, -2543, -1435, 1939, 6689, 5813, 1720, 2536, -2315, -5985, 284, 4232, -1216, -4167, 3832, -1243, 5381, 2833, -3500, 2965, 175, -5241, -1844, 937, 9660, -3489, -9534, 5349, 4303, 303, -5364, 2946, -5212, 3234, 4873, 678, -8039, -8501, 3465, -687, 7, 9813, -3354, 15414, 3135, -14240, -17793, -21180, 11887, 13168, -4700, 13177, -16215, 3262, -20307, 18562, -8247, -6499, 6276, -1695, -7547, -6837, -2277, -502, 17394, -8463, 9108, 1333, 4539, 3113, 6452, 656, 4904, -3068, -15986, 5146, 2178, 2731, -5553, -2663, -5223, 3258, 2121, 5410, -8738, 22145, 14453, 24618, -26068, 25853, 30169, 18018, -25203, 10997, -4010, -18816, -5322, -14192, -21816, 19279, 24367, 27330, -10944, -25939, -23294, -12921, -23482, -15735, 9453, -21369, 24000, -20071, 3694, -10963, 23687, 22539, -23647, 9947, -10428, -2240, 2511, -12625, 18174, 21898, 2190, -5779, 24928, 5268, 23135, -21882, 24742, -2470, 19539, -22068, 25367, -4351, -22134, 24408, 1345, 25490, 24225, 7380, 13244, -6406, -9528, -8923, -3105, -21527, 1696, 323, 8028, 4239, -6370, -12463, 19903, -8111, 3373, -12017, -5192, 9421, -11764, -3650, -7306, 7842, 9587, -398, 830, -8539, -6587, -19353, 3314, -5011, 5646, -3387, 5690, 4579, 636, -4718, 18692, 8228, 7826, 1255, -14440, -315, -8275, 5465, -4161, 492, -7234, -1855, 2306, -1440, 16287, -375, -8805, 935, 5392, -10614, 3382, 6721, -5979, 3192, 5948, 12959, -8648, 9012, 124, -625, -1185, 8070, 593, 8247, 5384, 13062, 3719, 4593, 383, 5566, 3286, -3803, -1082, -3454, 3521, 3990, 5723, -9260, -4910, -8133, -4369, 5824, -7679, 2193, -11217, -8255, -2430, -171, 3183, -192, -1024, -866, -9900, -3624, -9103, 260, -4489, -4902, -67, -4874, -8208, 3678, 5356, -3225, 450, 5461, -8505, -11421, 16717, -1688, -6589, -138, 7145, 2106, -1769, -1766, 2714, 6000, -1739, 5389, 2800, -7357, 464, -863, 1081, -6073, 3069, -1353, 3156, 3497, -4472, -37, -5597, 2152, 148, 860, 3891, -5000, -1362, -3212, 4421, 3897, -2615, 785, 204, -1538, 3529, 149, 626, 667, -7775, 2491, 3302, 297, -7508, -583, 2833, 3991, 9481, 14075, 3077, -8567, -8318, 9737, -24183, -13530, -9371, 10362, 8178, 20122, -19839, -18122, 9964, -8652, 16186, 17580, -1571, -24638, -1535, 24664, -20196, 14993, 10574, 14794, 1120, 28506, 4771, -10906, 1469, -11347, -13278, 14551, -7476, -15057, -8734, -6686, -1570, -714, -1035, -5245, -9141, 908, 5089, 5373, 1219, 322, -6733, -7348, -3023, 6883, -334, 7354, 5606, -18832, -13649, -20481, 22556, -3770, -14360, 6081, -106, -5496, 22942, 1457, -4078, 23883, 4434, -17892, -14925, 23641, 18188, -16899, -7841, 9192, -2131, 2106, 1897, 3865, -958, 2945, 5247, -13498, -9645, 2993, 6354, 3188, -4975, 11751, 2133, -6776, 17692, -10333, 3121, 7614, 2904, -5180, 5452, 7814, -3150, -1140, -3789, 3062, -4635, 931, 3114, -769, 3396, 6964, 2886, -814, -836, 1520, -2572, -5692, 3372, 848, -4672, -1342, 619, -700, 3978, 3675, -979, -1835, -337, -1276, -3675, -351, -1728, -5477, -95, -2873, 1053, 6110, 4497, -855, -3991, -386, 3988, -2432, 3872, -3552, 5644, -1134, 3266, 1349, 1485, 534, -773, 1186, 370, -6037, -151, 1755, 535, 4107, -1935, 2912, 409, -2826, 1285, -2949, 659, -1432, -42, 4464, 2160, 2835, 946, 2726, -4407, -4510, -533, -2863, 2799, -543, 832, -2801, 3880, -1096, -2102, -1423, 960, -2059, -1390, -2513, 3225, -1435, 178, -1297, -1515, 6683, 703, 1175, -2004, -3950, -2253, -2699, 2014, 2763, -1990, 538, -989, 1764, -1948, 1367, 321, 239, -664, -2152, -18, 2862, 298, -1711, 2363, 2584, 900, 1822, -1083, -2297, 2807, -1857, 1888, -3399, 1137, 7494, 3952, 6251, -2275, -5449, 1865, -1875, 1883, 1715, 1744, 6965, -4608, -3211, 1157, 1361, 715, 1808, -2692, 1225, -2577, -4530, 1462, -1452, 2750, 513, 1381, -260, -2907, -2750, -1721, -1345, -3736, 3717, -4618, 35, 1617, 2718, 189, -1303, 1057, -411, -475, -2155, -3933, -1692, 1277, -1135, 4168, -2378, 3479, 2314, 1406, 1377, -4457, -2874, -3739, -2136, 1186, 6445, 377, 142, -4373, -2647, -3997, -240, 1943, 513, 2180, 2463, 1857, -976, -498, -158, -6864, -279, 242, -1613, 1970, -1923, 3024, 281, -2651, -1387, 326, 3325, 4929, -1920, -2401, -2380, -2777, 481, -469, 1927, -1411, 1296, -388, 284, -1506, -476, 2204, -2367, -2260, 16, -951, 1636, 1574, 2319, 2726, 536, 586, 288, -960, -970, 811, -1205, 1651, 409, 2270, 257, 1022, -1217, 739, -267, 1328, 67, -1797, -1496, -2506, 991, -1756, 2223, -1379, 1882, -2065, -1491, -1146, -1230, -931, 762, 687, -11, 1316, -103, 381, -1109, 1875, 357, 1291, -209, 1437, -1235, -2392, 509, -531, 737, 598, 466, 1200, 452, -199, -137, -838, -1569, -1040, -2608, 542, 1147, -1740, 1420, -3945, 140, 185, -424, 1052, -2951, 200, 1096, 941, 2461, 49, -145, -726, -1597, -2159, 334, 14, 2126, 1274, -949, 1573, -482, 1449, -969, -175, 1513, -1505, 206, -26, 33, -953, 1303, 743, 855, 1744, 972, 998, -1428, 626, -1763, -2155, -616, 515, -305, 82, 1145, 1877, 265, -829, -28, -2338, -984, 1139, 1039, -2357, 267, 425, 829, -1723, 1728, 329, -1075, -671, -241, -986, -399, 1387, 247, 306, -720, 534, -510, 393, -480, -737, -1276, 285, -116, -294, 815, 364, 305, 188, 1067, -192, -334, -683, -337, -684, 730, 100, 922, -339, 378, 419, -314, 172, 299, -296, 739, 171, 293, -27, -6, 165, -583, 144, -967, 48, -1158, 447, -396, 143, 106, -318, 144, -1323, -300, 428, -750, -1469, 898, 1990, 890, 461, -235, 51, -771, 1956, 1327, -1265, -725, 1013, -1390, -933, 1159, 1847, -1773, -347, -498, -245, -785, 741, -187, -458, -380, 55, 189, -65, 854, -757, 500, -345, 540, -228, 859, 452, -437, 345, 156, 42, -114, 757, 369, -668, -385, -88, 105, -254, -145, -202, -2135, -686, 584, 1105, -1264, -546, 1593, 1583, 1534, 2007, 2128, -743, -1874, -2879, -651, 611, -804, -590, 1307, 2635, 902, 1093, 13, -1327, -2214, -1313, -223, 703, 341, 1100, 756, 949, 574, 256, -1467, 16, -225, 1240, 660, 84, -697, -179, 707, -675, 382, -400, -221, -433, 632, 111, 347, 352, -507, 6, -527, 528, -129, 22, 514, 399, 227, -452, -314, -340, -361, -204, -252, 137, 279, 1065, -64, 341, 43, -284, -2, -417, 286, -959, -122, -739, 539, 772, 862, -270, -663, -179, -83, 651, -21, -50, -441, -155, 359, 274, 210, 450, -313, -276, -755, 309, -180, 482, -365, 94, 105, 256, 425, 299, 283, -863, 55, -623, 212, -228, 78, -458, -47, 317, 229, 387, -65, 135, -75, 2, -253, 87, 223, 374, 37, 212, 2, 429, -222, 34, -427, 114, -122, -65, 154, -28, 224, -244, 586, -305, 302, -450, 138, -173, 73, -126, -109, -44, 46, 194, -93, 32, -185, 204, 20, 315, -487, -95, -395, 64, -125, 162, -71, 35, -20, -33, 173, -174, 148, -123, 159, -366, 238, -264, 240, -13, 360, -176, -16, -361, 23, -7, -260, -120, -197, 62, -204, 430, -133, 240, -235, 180, -274, -101, 48, -47, 44, 35, 310, -111, 312, 113, 121, -112, -1, -238, -11, -28, 151, -102, 212, -142, 158, -166, -122, -135, -120, 244, -127, 375, -242, 482, -195, 262, -121, 80, -119, -242, 152, -193, 172, -213, 199, -32, 235, 81, -16, -152, 4, 134, 193, 21, 326, -110, 141, -140, 97, -220, -322, 18, -197, 443, -251, 316, -253, 364, -326, 88, -37, -216, -93, -332, 117, -349, 54, -114, 115, -108, 46, 84, -40, 40, 98, 99, 178, -105, 141, -110, 276, 111, 149, 200, -26, 257, -409, 240, -423, 281, -226, 99, -124, -66, 69, -163, 330, -394, 151, -222, 23, -157, -14, 53, 96, 35, -26, -32, -38, -157, 94, -121, 134, -19, 8, 169, -97, 311, -336, 110, -422, 178, -274, 163, -120, -104, -33, -121, 199, -129, 441, -173, 154, -145, 259, -188, 118, 57, 42, -31, 196, 55, 26, 85, 99, -81, -40, 3, 12, 52, -229, 345, -352, 155, -190, 171, -263, -51, -268, -148, 174, -171, 233, -316, 387, -308, -198, 157, 660, 9, 29, -30, -107, -5, 621, 551, 0, -357, -133, -309, -212, 373, 192, -294, -689, 31, -177, 214, 196, 402, -339, -254, -166, 161, 300, -28, 165, -583, 105, -116, 319, 29, 80, -422, -235, -9, 151, 275, 397, -184, -440, -146, 867, -315, -142, -383, -432, 440, 656, 294, -371, -127, -576, 146, 352, 757, 356, -841, -309, 82, 371, -185, 207, -107, -433, -159, 496, 111, 87, 10, -355, -465, 199, 257, }; const unsigned long gl_rack_pull_len = 2304; restjohn/g3m // // ShortBufferBuilder.cpp // G3MiOSSDK // // Created by on 1/19/13. // // #include "ShortBufferBuilder.hpp" #include "IFactory.hpp" #include "IShortBuffer.hpp" IShortBuffer* ShortBufferBuilder::create() const { #ifdef C_CODE const int size = _values.size(); IShortBuffer* result = IFactory::instance()->createShortBuffer(size); for (int i = 0; i < size; i++) { result->rawPut(i, _values.at(i)); } return result; #endif #ifdef JAVA_CODE //return IFactory.instance().createShortBuffer( _values.toArray() ); return IFactory.instance().createShortBuffer( _values._array, _values._size ); #endif } ikehirzel/c-spiel #ifndef WARBLER_AST_EXPRESSION_ARITHMETIC_ADDITIVE_HPP #define WARBLER_AST_EXPRESSION_ARITHMETIC_ADDITIVE_HPP // local headers #include namespace warbler { enum AdditiveType { ADDITIVE_ADD, ADDITIVE_SUBTRACT }; struct AdditiveRhs { MultiplicativeExpression expr; AdditiveType type; }; class AdditiveExpression { private: MultiplicativeExpression _lhs; std::vector _rhs; public: AdditiveExpression(MultiplicativeExpression&& lhs, std::vector&& rhs); static Result parse(TokenIterator& iter); void print_tree(u32 depth = 0) const; }; } #endif Support/Modules/VBElemOperations/GDLRequestCallbacks.hpp1-10 // ********************************************************************************************************************* // Description: GDL Request callbacks // // Module: VBElemOperations // Namespace: GDLOperations // Contact person: PP // // SG compatible // ********************************************************************************************************************* #if !defined (GDLREQUESTCALLBACKS_HPP) #define GDLREQUESTCALLBACKS_HPP #pragma once // from GSRoot #include "Definitions.hpp" // from GDL #include "GDLProc.h" // from VBElemOperations #include "VBElemOperationsExport.hpp" #include "GDLOperations.hpp" // from VBElements #include "IPLGeneralAttributeList.hpp" #include "IPLBaseEnum.hpp" // temporary namespace VBES { class ElemSet; typedef ODB::ConstRef ElemSetConstRef; } namespace EDB { class DefaultElem; } namespace IPL { class Property; class PropertySet; class ExternalReferenceBase; class ElementDefault; class PropertyChangeList; class Value; } namespace GDLOperations { typedef std::function ZoneDataReqFunc; typedef std::function ZoneColusAreaReqFunc; typedef std::function NameReqFunc; typedef std::function WidoZoneRelevReqFunc; typedef std::function & values, GS::Array& stringsHdl)> MatchPropReqFunc; typedef std::function StyleInfoFunc; typedef std::function & values, GS::Array& stringsHdl)> AssocElPropReqFunc; typedef std::function * paragraphs, const GSHandle tabsHdl, // double const GS::VAArray* stringsData, const GSHandle stringsHdl, // Layout double* width, double* height)> TextBlockInfoReqFunc; // Layout effective id callback; will not be called during 3D conversion typedef std::function GetLayoutEffectiveIDFunc; // MEP callbacks typedef std::function & cpCoords, const GS::Array& portIndices, const GS::Array& dirVs, const GS::Array& widthVs, GS::Array& flexDuctPoints, const Int32 resolution)> DoSectioningFunc; typedef std::function DgStringToDoubleFunc; class VB_ELEM_OPERATIONS_DLL_EXPORT GDLRequestCallbacks { public: ZoneDataReqFunc zonedataReq; // will not be called during 3D conversion NameReqFunc customautolabelReq; // calls VBElem::Label::GetConstLabel ZoneColusAreaReqFunc zonecolusareaReq; // uses VBTo3D::Updater WidoZoneRelevReqFunc widozonerelevReq; // will not be called during 3D conversion MatchPropReqFunc matchpropReq; // listazast hiv AssocElPropReqFunc assocelpropReq; // listazast hiv // Layout effective id callback; will not be called during 3D conversion GetLayoutEffectiveIDFunc getLayoutEffectiveID; // MEP callbacks DoSectioningFunc doSectioning; DgStringToDoubleFunc dgStringToDouble; }; } // namespace GDLOperations #endif // GDLREQUESTCALLBACKS_HPP nilsvu/spectre // Distributed under the MIT License. // See LICENSE.txt for details. #include "PointwiseFunctions/AnalyticSolutions/RadiationTransport/M1Grey/ConstantM1.hpp" #include #include #include #include #include #include "DataStructures/DataVector.hpp" // IWYU pragma: keep #include "DataStructures/Tensor/Tensor.hpp" // IWYU pragma: keep #include "Evolution/Systems/RadiationTransport/Tags.hpp" #include "PointwiseFunctions/Hydro/Tags.hpp" #include "Utilities/GenerateInstantiations.hpp" #include "Utilities/MakeWithValue.hpp" // IWYU pragma: no_include "DataStructures/Tensor/TypeAliases.hpp" // IWYU pragma: no_forward_declare Tensor namespace RadiationTransport::M1Grey::Solutions { ConstantM1::ConstantM1(const std::array& mean_velocity, const double comoving_energy_density) : // clang-tidy: do not std::move trivial types. mean_velocity_(std::move(mean_velocity)), // NOLINT comoving_energy_density_(comoving_energy_density) {} void ConstantM1::pup(PUP::er& p) { p | mean_velocity_; p | comoving_energy_density_; p | background_spacetime_; } // Variables templated on neutrino species. template tuples::TaggedTuple< RadiationTransport::M1Grey::Tags::TildeE> ConstantM1::variables(const tnsr::I& x, double /*t*/, tmpl::list> /*meta*/) const { const double W_sqr = 1. / (1. - std::inner_product(mean_velocity_.begin(), mean_velocity_.end(), mean_velocity_.begin(), 0.)); return {Scalar{DataVector( get<0>(x).size(), comoving_energy_density_ / 3. * (4. * W_sqr - 1.))}}; } template tuples::TaggedTuple< RadiationTransport::M1Grey::Tags::TildeS> ConstantM1::variables(const tnsr::I& x, double /*t*/, tmpl::list> /*meta*/) const { const double W_sqr = 1. / (1. - std::inner_product(mean_velocity_.begin(), mean_velocity_.end(), mean_velocity_.begin(), 0.)); const double prefactor = 4. / 3. * comoving_energy_density_ * W_sqr; auto result = make_with_value>(x, mean_velocity_[0] * prefactor); get<1>(result) = mean_velocity_[1] * prefactor; get<2>(result) = mean_velocity_[2] * prefactor; return {std::move(result)}; } template tuples::TaggedTuple< RadiationTransport::M1Grey::Tags::GreyEmissivity> ConstantM1::variables( const tnsr::I& x, double /*t*/, tmpl::list> /*meta*/) const { return {Scalar{DataVector(get<0>(x).size(), 0.)}}; } template tuples::TaggedTuple< RadiationTransport::M1Grey::Tags::GreyAbsorptionOpacity> ConstantM1::variables( const tnsr::I& x, double /*t*/, tmpl::list> /*meta*/) const { return {Scalar{DataVector(get<0>(x).size(), 0.)}}; } template tuples::TaggedTuple< RadiationTransport::M1Grey::Tags::GreyScatteringOpacity> ConstantM1::variables( const tnsr::I& x, double /*t*/, tmpl::list> /*meta*/) const { return {Scalar{DataVector(get<0>(x).size(), 0.)}}; } // Variables not templated on neutrino species. tuples::TaggedTuple> ConstantM1::variables( const tnsr::I& x, double /*t*/, tmpl::list> /*meta*/) const { const double W = 1. / sqrt(1. - std::inner_product(mean_velocity_.begin(), mean_velocity_.end(), mean_velocity_.begin(), 0.)); return {Scalar{DataVector(get<0>(x).size(), W)}}; } tuples::TaggedTuple> ConstantM1::variables( const tnsr::I& x, double /*t*/, tmpl::list> /*meta*/) const { auto result = make_with_value>(x, mean_velocity_[0]); get<1>(result) = mean_velocity_[1]; get<2>(result) = mean_velocity_[2]; return {std::move(result)}; } bool operator==(const ConstantM1& lhs, const ConstantM1& rhs) { return lhs.mean_velocity_ == rhs.mean_velocity_ and lhs.comoving_energy_density_ == rhs.comoving_energy_density_ and lhs.background_spacetime_ == rhs.background_spacetime_; } bool operator!=(const ConstantM1& lhs, const ConstantM1& rhs) { return not(lhs == rhs); } #define TAG(data) BOOST_PP_TUPLE_ELEM(0, data) #define NTYPE(data) BOOST_PP_TUPLE_ELEM(1, data) #define EBIN(data) BOOST_PP_TUPLE_ELEM(2, data) #define GENERATE_LIST(z, n, _) BOOST_PP_COMMA_IF(n) n #define INSTANTIATE_M1_FUNCTION_WITH_FRAME(_, data) \ template tuples::TaggedTuple >> \ ConstantM1::variables( \ const tnsr::I& x, double t, \ tmpl::list >> \ /*meta*/) const; #define temp_list \ (BOOST_PP_REPEAT(MAX_NUMBER_OF_NEUTRINO_ENERGY_BINS, GENERATE_LIST, _)) GENERATE_INSTANTIATIONS(INSTANTIATE_M1_FUNCTION_WITH_FRAME, (RadiationTransport::M1Grey::Tags::TildeE, RadiationTransport::M1Grey::Tags::TildeS), (neutrinos::ElectronNeutrinos, neutrinos::ElectronAntiNeutrinos, neutrinos::HeavyLeptonNeutrinos), temp_list) #undef temp_list #undef INSTANTIATE_M1_FUNCTION_WITH_FRAME #undef TAG #undef NTYPE #undef EBIN #undef GENERATE_LIST #define TAG(data) BOOST_PP_TUPLE_ELEM(0, data) #define NTYPE(data) BOOST_PP_TUPLE_ELEM(1, data) #define EBIN(data) BOOST_PP_TUPLE_ELEM(2, data) #define GENERATE_LIST(z, n, _) BOOST_PP_COMMA_IF(n) n #define INSTANTIATE_M1_FUNCTION(_, data) \ template tuples::TaggedTuple >> \ ConstantM1::variables( \ const tnsr::I& x, double t, \ tmpl::list >> \ /*meta*/) const; #define temp_list \ (BOOST_PP_REPEAT(MAX_NUMBER_OF_NEUTRINO_ENERGY_BINS, GENERATE_LIST, _)) GENERATE_INSTANTIATIONS( INSTANTIATE_M1_FUNCTION, (RadiationTransport::M1Grey::Tags::GreyEmissivity, RadiationTransport::M1Grey::Tags::GreyAbsorptionOpacity, RadiationTransport::M1Grey::Tags::GreyScatteringOpacity), (neutrinos::ElectronNeutrinos, neutrinos::ElectronAntiNeutrinos, neutrinos::HeavyLeptonNeutrinos), temp_list) #undef INSTANTIATE_M1_FUNCTION #undef temp_list #undef TAG #undef NTYPE #undef EBIN #undef GENERATE_LIST } // namespace RadiationTransport::M1Grey::Solutions qingqhua/CppDirectXRayTracing #pragma once #include #include "Vertex.hpp" namespace Primitives { class Sphere { public: Sphere() = default; ~Sphere() = default; void Init(float diameter, int tessellation, bool uvHorizontalFlip = false, bool uvVerticalFlip = false); std::vector GetVertices(); std::vector GetIndices(); private: void CalculateTangentSpace(); std::vector mIndices; std::vector mVertices; }; }; llvm/utils/TableGen/DisassemblerEmitter.cpp //===- DisassemblerEmitter.cpp - Generate a disassembler ------------------===// // // 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 // //===----------------------------------------------------------------------===// #include "CodeGenTarget.h" #include "WebAssemblyDisassemblerEmitter.h" #include "X86DisassemblerTables.h" #include "X86RecognizableInstr.h" #include "llvm/TableGen/Error.h" #include "llvm/TableGen/Record.h" #include "llvm/TableGen/TableGenBackend.h" using namespace llvm; using namespace llvm::X86Disassembler; /// DisassemblerEmitter - Contains disassembler table emitters for various /// architectures. /// X86 Disassembler Emitter /// /// *** IF YOU'RE HERE TO RESOLVE A "Primary decode conflict", LOOK DOWN NEAR /// THE END OF THIS COMMENT! /// /// The X86 disassembler emitter is part of the X86 Disassembler, which is /// documented in lib/Target/X86/X86Disassembler.h. /// /// The emitter produces the tables that the disassembler uses to translate /// instructions. The emitter generates the following tables: /// /// - One table (CONTEXTS_SYM) that contains a mapping of attribute masks to /// instruction contexts. Although for each attribute there are cases where /// that attribute determines decoding, in the majority of cases decoding is /// the same whether or not an attribute is present. For example, a 64-bit /// instruction with an OPSIZE prefix and an XS prefix decodes the same way in /// all cases as a 64-bit instruction with only OPSIZE set. (The XS prefix /// may have effects on its execution, but does not change the instruction /// returned.) This allows considerable space savings in other tables. /// - Six tables (ONEBYTE_SYM, TWOBYTE_SYM, THREEBYTE38_SYM, THREEBYTE3A_SYM, /// THREEBYTEA6_SYM, and THREEBYTEA7_SYM contain the hierarchy that the /// decoder traverses while decoding an instruction. At the lowest level of /// this hierarchy are instruction UIDs, 16-bit integers that can be used to /// uniquely identify the instruction and correspond exactly to its position /// in the list of CodeGenInstructions for the target. /// - One table (INSTRUCTIONS_SYM) contains information about the operands of /// each instruction and how to decode them. /// /// During table generation, there may be conflicts between instructions that /// occupy the same space in the decode tables. These conflicts are resolved as /// follows in setTableFields() (X86DisassemblerTables.cpp) /// /// - If the current context is the native context for one of the instructions /// (that is, the attributes specified for it in the LLVM tables specify /// precisely the current context), then it has priority. /// - If the current context isn't native for either of the instructions, then /// the higher-priority context wins (that is, the one that is more specific). /// That hierarchy is determined by outranks() (X86DisassemblerTables.cpp) /// - If the current context is native for both instructions, then the table /// emitter reports a conflict and dies. /// /// *** RESOLUTION FOR "Primary decode conflict"S /// /// If two instructions collide, typically the solution is (in order of /// likelihood): /// /// (1) to filter out one of the instructions by editing filter() /// (X86RecognizableInstr.cpp). This is the most common resolution, but /// check the Intel manuals first to make sure that (2) and (3) are not the /// problem. /// (2) to fix the tables (X86.td and its subsidiaries) so the opcodes are /// accurate. Sometimes they are not. /// (3) to fix the tables to reflect the actual context (for example, required /// prefixes), and possibly to add a new context by editing /// include/llvm/Support/X86DisassemblerDecoderCommon.h. This is unlikely /// to be the cause. /// /// DisassemblerEmitter.cpp contains the implementation for the emitter, /// which simply pulls out instructions from the CodeGenTarget and pushes them /// into X86DisassemblerTables. /// X86DisassemblerTables.h contains the interface for the instruction tables, /// which manage and emit the structures discussed above. /// X86DisassemblerTables.cpp contains the implementation for the instruction /// tables. /// X86ModRMFilters.h contains filters that can be used to determine which /// ModR/M values are valid for a particular instruction. These are used to /// populate ModRMDecisions. /// X86RecognizableInstr.h contains the interface for a single instruction, /// which knows how to translate itself from a CodeGenInstruction and provide /// the information necessary for integration into the tables. /// X86RecognizableInstr.cpp contains the implementation for a single /// instruction. namespace llvm { extern void EmitDecoder(RecordKeeper &RK, raw_ostream &OS, const std::string &PredicateNamespace, const std::string &GPrefix, const std::string &GPostfix, const std::string &ROK, const std::string &RFail, const std::string &L); void EmitDisassembler(RecordKeeper &Records, raw_ostream &OS) { CodeGenTarget Target(Records); emitSourceFileHeader(" * " + Target.getName().str() + " Disassembler", OS); // X86 uses a custom disassembler. if (Target.getName() == "X86") { DisassemblerTables Tables; ArrayRef numberedInstructions = Target.getInstructionsByEnumValue(); for (unsigned i = 0, e = numberedInstructions.size(); i != e; ++i) RecognizableInstr::processInstr(Tables, *numberedInstructions[i], i); if (Tables.hasConflicts()) { PrintError(Target.getTargetRecord()->getLoc(), "Primary decode conflict"); return; } Tables.emit(OS); return; } // WebAssembly has variable length opcodes, so can't use EmitFixedLenDecoder // below (which depends on a Size table-gen Record), and also uses a custom // disassembler. if (Target.getName() == "WebAssembly") { emitWebAssemblyDisassemblerTables(OS, Target.getInstructionsByEnumValue()); return; } // ARM and Thumb have a CHECK() macro to deal with DecodeStatuses. if (Target.getName() == "ARM" || Target.getName() == "Thumb" || Target.getName() == "AArch64" || Target.getName() == "ARM64") { std::string PredicateNamespace = std::string(Target.getName()); if (PredicateNamespace == "Thumb") PredicateNamespace = "ARM"; EmitDecoder(Records, OS, PredicateNamespace, "if (!Check(S, ", "))", "S", "MCDisassembler::Fail", " MCDisassembler::DecodeStatus S = " "MCDisassembler::Success;\n(void)S;"); return; } EmitDecoder(Records, OS, std::string(Target.getName()), "if (", " == MCDisassembler::Fail)", "MCDisassembler::Success", "MCDisassembler::Fail", ""); } } // end namespace llvm /*++ Copyright (c) 1995 Microsoft Corporation Module Name: asnprimt Abstract: This module provides the implementation of the ASN.1 Primitive Object base class. Author: (dbarlow) 10/8/1995 Environment: Win32 Notes: --*/ #include #include "asnPriv.h" // //============================================================================== // // CAsnPrimitive // IMPLEMENT_NEW(CAsnPrimitive) /*++ CAsnPrimitive: This is the constructor for a Primitve type ASN.1 encoding. Arguments: dwType is the type of the object. dwFlags supplies any special flags for this object. Options are: fOptional implies the object is optional. dwTag is the tag of the object. If this is zero, the tag is taken from the type. Return Value: None Author: (dbarlow) 10/6/1995 --*/ CAsnPrimitive::CAsnPrimitive( IN DWORD dwFlags, IN DWORD dwTag, IN DWORD dwType) : CAsnObject(dwFlags, dwTag, dwType), m_bfData() { ASSERT(0 == (dwFlags & (fConstructed))); m_rgEntries.Add(this); } /*++ Clear: This method sets the primitive object to it's default state. It does not affect the default setting. Arguments: None Return Value: none Author: (dbarlow) 10/6/1995 --*/ void CAsnPrimitive::Clear( void) { m_bfData.Reset(); m_dwFlags &= ~fPresent; if (NULL != m_pasnParent) m_pasnParent->ChildAction(act_Cleared, this); } /*++ DataLength: This method returns the length of the local machine encoding of the data. For this general object, the local machine encoding and ASN.1 encoding are identical. Arguments: None Return Value: >= 0 - The length of the local machine encoding. Author: (dbarlow) 10/6/1995 --*/ LONG CAsnPrimitive::DataLength( void) const { LONG lth; switch (State()) { case fill_Empty: case fill_Optional: lth = -1; // ?error? Incomplete Structure break; case fill_Defaulted: lth = m_bfDefault.Length(); break; case fill_Present: lth = m_bfData.Length(); break; case fill_Partial: case fill_NoElements: default: ASSERT(FALSE); // ?error? Internal error lth = -1; break; } return lth; } /*++ Read: This default method provides the stored data. Arguments: pbDst receives the value. It is assumed to be long enough. Return Value: If >=0, the length of the data portion of this object. if < 0, an error occurred. Author: (dbarlow) 10/5/1995 --*/ LONG CAsnPrimitive::Read( OUT LPBYTE pbDst) const { LONG lth; switch (State()) { case fill_Empty: case fill_Optional: lth = -1; // ?error? Incomplete structure. break; case fill_Defaulted: lth = m_bfDefault.Length(); memcpy(pbDst, m_bfDefault.Access(), lth); break; case fill_Present: lth = m_bfData.Length(); memcpy(pbDst, m_bfData.Access(), lth); break; case fill_Partial: case fill_NoElements: default: ASSERT(FALSE); // ?error? Internal error lth = -1; break; } return lth; } /*++ Write: This default implementation copies the provided data to our data buffer. Arguments: pbSrc supplies the data as a BYTE array, with cbSrcLen supplies the length of the pbSrc Array. Return Value: If >=0, the length of the data portion of this object. if < 0, an error occurred. Author: (dbarlow) 10/5/1995 --*/ LONG CAsnPrimitive::Write( IN const BYTE FAR *pbSrc, IN DWORD cbSrcLen) { if (0 < cbSrcLen) { if (NULL == m_bfData.Set(pbSrc, cbSrcLen)) return -1; } else m_bfData.Reset(); m_dwFlags |= fPresent; if (NULL != m_pasnParent) m_pasnParent->ChildAction(act_Written, this); return m_bfData.Length(); } /*++ EncodingLength: This method returns the length of the object in its ASN.1 encoding. Arguments: None Return Value: >= 0 is the length of the object's ASN.1 encoding. < 0 implies an error. Author: (dbarlow) 10/5/1995 --*/ LONG CAsnPrimitive::_encLength( void) const { BYTE rge[32]; LONG lTotal = 0; LONG lth; switch (m_State) { case fill_Empty: lth = -1; // ?error? Incomplete structure goto ErrorExit; break; case fill_Optional: case fill_Defaulted: lTotal = 0; break; case fill_Present: lth = EncodeTag(rge); if (0 > lth) goto ErrorExit; lTotal += lth; lth = EncodeLength(rge); if (0 > lth) goto ErrorExit; lTotal += lth; lTotal += m_bfData.Length(); break; case fill_Partial: case fill_NoElements: default: ASSERT(FALSE); // ?error? Internal error lth = -1; break; } return lTotal; ErrorExit: return lth; } /*++ State: This routine checks to see if a structure is completely filled in. Arguments: None Return Value: fill_Empty - There is no added data anywhere in the structure. fill_Present - All the data is present in the structure (except maybe defaulted or optional data). fill_Partial - Not all of the data is there, but some of it is. (Not used by this object type.) fill_Defauted - No data has been written, but a default value is available. fill_Optional - No data has been written, but the object is optional. Author: (dbarlow) 10/5/1995 --*/ CAsnObject::FillState CAsnPrimitive::State( void) const { FillState result; if (0 != (fPresent & m_dwFlags)) result = fill_Present; else if (0 != (m_dwFlags & fOptional)) result = fill_Optional; else if (0 != (m_dwFlags & fDefault)) result = fill_Defaulted; else result = fill_Empty; ((CAsnPrimitive *)this)->m_State = result; return result; } /*++ Compare: This method compares this ASN.1 Object to another. Arguments: asnObject supplies the other object for comparison. Return Value: A value indicating a comparitive value: < 0 - This object is less than that object. = 0 - This object is the same as that object. > 0 - This object is more than that object. Author: (dbarlow) 10/5/1995 --*/ LONG CAsnPrimitive::Compare( const CAsnObject &asnObject) const { const CAsnPrimitive * pasnPrim; const CBuffer *pbfThis, *pbfThat; LONG result; if (m_dwType != asnObject.m_dwType) return 0x100; // They're incomparable. pasnPrim = (const CAsnPrimitive *)&asnObject; switch (m_State) { case fill_Empty: case fill_Optional: TRACE("Incomplete Primitive in Comparison") return 0x100; break; case fill_Defaulted: pbfThis = &m_bfDefault; break; case fill_Present: pbfThis = &m_bfData; break; case fill_NoElements: case fill_Partial: default: ASSERT(FALSE); // ?error? Internal error return 0x100; break; } switch (pasnPrim->m_State) { case fill_Empty: case fill_Optional: TRACE("Incomplete Primitive in Comparison") return 0x100; break; case fill_Defaulted: pbfThat = &pasnPrim->m_bfDefault; break; case fill_Present: pbfThat = &pasnPrim->m_bfData; break; case fill_NoElements: case fill_Partial: default: ASSERT(FALSE); // ?error? Internal error return 0x100; break; } if (pbfThis->Length() > pbfThat->Length()) result = (*pbfThis)[pbfThat->Length()]; else if (pbfThis->Length() < pbfThat->Length()) result = (*pbfThat)[pbfThis->Length()]; else result = memcmp(pbfThis->Access(), pbfThat->Access(), pbfThis->Length()); return result; } /*++ _copy: This method replaces the contents of this ASN.1 Object with another. The objects must be identical structures. Tags and defaults are not duplicated. Arguments: asnObject supplies the source object. Return Value: >= 0 Is the number of bytes actually copied < 0 is an error. Author: (dbarlow) 10/5/1995 --*/ LONG CAsnPrimitive::_copy( const CAsnObject &asnObject) { const CAsnPrimitive * pasnPrim; LONG lth; if (m_dwType != asnObject.m_dwType) { TRACE("Type mismatch in _copy") lth = -1; // ?error? Wrong type. goto ErrorExit; } pasnPrim = (const CAsnPrimitive *)&asnObject; switch (pasnPrim->m_State) { case fill_Empty: TRACE("Incomplete Structure in _copy") lth = -1; // ?error? Incomplete structure goto ErrorExit; break; case fill_Optional: lth = 0; break; case fill_Defaulted: lth = Write( pasnPrim->m_bfDefault.Access(), pasnPrim->m_bfDefault.Length()); break; case fill_Present: lth = Write( pasnPrim->m_bfData.Access(), pasnPrim->m_bfData.Length()); break; case fill_Partial: case fill_NoElements: default: ASSERT(FALSE); // ?error? Internal error lth = -1; break; } return lth; ErrorExit: return lth; } /*++ EncodeLength: This method encodes the definite length of the object into the supplied buffer. Arguments: pbDst receives the ASN.1 encoding of the length. Return Value: >= 0 is the length of the resultant encoding < 0 is an error. Author: (dbarlow) 10/5/1995 --*/ LONG CAsnPrimitive::EncodeLength( OUT LPBYTE pbDst) const { LONG lth; switch (m_State) { case fill_Empty: TRACE("Incomplete Structure") lth = -1; // ?error? Incomplete Structure break; case fill_Optional: case fill_Defaulted: lth = 0; break; case fill_Present: lth = CAsnObject::EncodeLength(pbDst, m_bfData.Length()); break; case fill_Partial: case fill_NoElements: default: ASSERT(FALSE); // ?error? Internal error lth = -1; break; } return lth; } /*++ EncodeData: This method encodes the data into the supplied buffer. Arguments: pbDst Return Value: >= 0 is the length of the encoding. < 0 is an error Author: (dbarlow) 10/5/1995 --*/ LONG CAsnPrimitive::EncodeData( OUT LPBYTE pbDst) const { LONG lth; switch (m_State) { case fill_Empty: TRACE("Incomplete Structure") lth = -1; // ?error? Incomplete Structure break; case fill_Optional: case fill_Defaulted: lth = 0; break; case fill_Present: lth = m_bfData.Length(); if (0 != lth) memcpy(pbDst, m_bfData.Access(), lth); break; case fill_Partial: case fill_NoElements: default: ASSERT(FALSE); // ?error? Internal error lth = -1; break; } return lth; } /*++ DecodeData: This routine decodes the data portion of the ASN.1. The tag and length have already been removed. Arguments: pbSrc supplies the address of the ASN.1 encoding of the data. dwLength supplies the length of the data. Return Value: >= 0 - The number of bytes removed from the input stream. < 0 - An error occurred. Author: (dbarlow) 10/6/1995 --*/ LONG CAsnPrimitive::DecodeData( IN const BYTE FAR *pbSrc, IN DWORD cbSrc, IN DWORD dwLength) { if (0 < dwLength) { if (cbSrc < dwLength) { return -1; } if (NULL == m_bfData.Set(pbSrc, dwLength)) return -1; // ?error? no memory } else m_bfData.Reset(); m_dwFlags |= fPresent; if (NULL != m_pasnParent) m_pasnParent->ChildAction(act_Written, this); return dwLength; } /*++ TypeCompare: This routine compares the entire structure of an Object to another Object. Arguments: asn - The other object. Return Value: TRUE - They are identical FALSE - They differ Author: (dbarlow) 10/19/1995 --*/ BOOL CAsnPrimitive::TypeCompare( const CAsnObject &asnObject) const { return (m_dwType == asnObject.m_dwType); } ishine/bolt // Copyright (C) 2019. Huawei Technologies Co., Ltd. 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. #include #include #include "libbolt/headers/kit_flags.h" #include "libbolt/headers/flow.h" DataType inferencePrecision = DT_F32; Flow flowExample; const int topK = 5; const int width = 224; const int height = 224; double useTime; EE pixelProcess(std::map> &inputs, std::shared_ptr &tmp, std::map> &outputs, std::vector parameter = std::vector()) { // Already in BGR unsigned char *myBuffer = (unsigned char *)((CpuMemory *)inputs["input:1"]->get_memory())->get_ptr(); F32 *oneArr = (F32 *)((CpuMemory *)outputs["input:0"]->get_memory())->get_ptr(); for (int i = 0; i < width * height * 3; i++) { oneArr[i] = myBuffer[i]; } return SUCCESS; } EE postProcess(std::map> &inputs, std::shared_ptr &tmp, std::map> &outputs, std::vector parameter = std::vector()) { std::string flowInferenceNodeOutputName = "output"; std::string boltModelOutputName = "MobileNetV2/Predictions/Softmax:0"; int *flowInferenceNodeOutput = (int *)((CpuMemory *)outputs[flowInferenceNodeOutputName]->get_memory())->get_ptr(); F32 *score1000 = (F32 *)((CpuMemory *)inputs[boltModelOutputName]->get_memory())->get_ptr(); for (int i = 0; i < topK; i++) { int max_index = 0; for (int j = 1; j < 1000; j++) { if (score1000[j] > score1000[max_index]) { max_index = j; } } flowInferenceNodeOutput[i] = max_index; score1000[max_index] = -65504; } return SUCCESS; } extern "C" void Java_com_example_imageclassificationapp_MainActivity_initFlow( JNIEnv *env, jobject, jstring path) { flowRegisterFunction("pixelProcess", pixelProcess); flowRegisterFunction("postProcess", postProcess); const char *cur_str_path = env->GetStringUTFChars(path, nullptr); std::string imageClassificationGraphPath = cur_str_path; std::vector graphPath = {imageClassificationGraphPath}; int threads = 1; flowExample.init(graphPath, inferencePrecision, AFFINITY_CPU_HIGH_PERFORMANCE, threads, false); } std::map> inputOutput(const unsigned char *myBuffer) { std::map> tensors; TensorDesc inputDesc = tensor4df(DT_U8, DF_NCHW, 1, 224, 224, 3); tensors["input:1"] = std::shared_ptr(new Tensor()); tensors["input:1"]->resize(inputDesc); tensors["input:1"]->alloc(); void *ptr = (void *)((CpuMemory *)tensors["input:1"]->get_memory())->get_ptr(); memcpy(ptr, myBuffer, tensorNumBytes(inputDesc)); tensors["output"] = std::shared_ptr(new Tensor()); tensors["output"]->resize(tensor2df(DT_I32, DF_NCHW, 1, topK)); tensors["output"]->alloc(); return tensors; } extern "C" jintArray Java_com_example_imageclassificationapp_MainActivity_runFlow( JNIEnv *env, jobject, jbyteArray bgrData, jstring path) { int len = env->GetArrayLength(bgrData); unsigned char *theValue = new unsigned char[len]; env->GetByteArrayRegion(bgrData, 0, len, reinterpret_cast(theValue)); int num = 1; const char *cur_str_path = env->GetStringUTFChars(path, nullptr); std::string imageClassificationGraphPath = cur_str_path; for (int i = 0; i < num; i++) { std::map> data = inputOutput(theValue); Task task(imageClassificationGraphPath, data); flowExample.enqueue(task); } std::vector results; double start = ut_time_ms(); UNI_PROFILE(results = flowExample.dequeue(true), std::string("image_classification"), std::string("image_classification")); double end = ut_time_ms(); useTime = end - start; int *top5 = (int *)((CpuMemory *)results[0].data["output"]->get_memory())->get_ptr(); jintArray intArr = env->NewIntArray(topK); jint buf[topK]; for (int i = 0; i < topK; ++i) { buf[i] = top5[i]; } env->SetIntArrayRegion(intArr, 0, topK, buf); return intArr; } extern "C" jdouble Java_com_example_imageclassificationapp_MainActivity_useTimeFromJNI( JNIEnv *env, jobject) { return useTime; } wzppengpeng/LittleConv /** * the example of resnet */ #include "config/click.hpp" #include "model.hpp" nn::Model get_model() { return ResNet18(); } void train() { std::string input_dir = wzp::Click::get("--input_dir"); // the parameters int batch_size = 256; int epoch_num = 50; float lr = 1e-2; int display = 50; float weight_deacay = 5e-5; // get model auto model = get_model(); model->set_node_name("cifar10_resnet18"); // define the loss auto cross_entropy_loss = nn::CrossEntropyLoss::CreateCrossEntropyLoss(); // define the optimizer auto optimizer = optim::Adam::CreateAdam(model->RegisterWeights(), lr, 0.9, 0.999, weight_deacay); auto scheduler = optim::StepLR::CreateStepLR(*optimizer.get(), 10, 0.1); io::Cifar10Dataset cifar10_train(input_dir, io::Cifar10Dataset::TRAIN); io::Cifar10Dataset cifar10_test(input_dir, io::Cifar10Dataset::TEST); cifar10_train.Load(); cifar10_test.Load(); // define a trainer to train the classification task auto trainer = utils::ClassifyTrainer::CreateClassfyTrainer(model, cross_entropy_loss, optimizer, cifar10_train, batch_size, epoch_num, display, &cifar10_test, &scheduler); // train trainer->Train(); // save model io::Saver::Save("cifar10_resnet18.liconmodel", model); } void test() { std::string input_dir = wzp::Click::get("--input_dir"); // get model auto model = get_model(); model->test(); // load model io::Saver::Load("cifar10_resnet18.liconmodel", &model); wzp::log::info("cifar10_resnet18 model loaded..."); io::Cifar10Dataset cifar10_test(input_dir, io::Cifar10Dataset::TEST); cifar10_test.Load(); // eval wzp::log::info("The final accuracy is", utils::Accuracy::CreateAccuracy(model, cifar10_test)->Run()); } int main(int argc, char *argv[]) { wzp::Click::add_argument("--mode", "the mode train or test"); wzp::Click::add_argument("--input_dir", "the input dir of mnist root dir"); wzp::Click::parse(argc, argv); // set up the env licon::EnvSetUp(); wzp::log::info("Run Cifar10 Resnet18..."); if(wzp::Click::get("--mode") == "train") { train(); } else { test(); } return 0; } PacktPublishing/Hands-On-Design-Patterns-with-Qt-5 #include "Odometer.h" #include "Blackboard.h" #include Odometer::Odometer(QWidget *parent) : QLCDNumber(parent), KnowledgeSource() { setDigitCount(7); setSmallDecimalPoint(true); setDecMode(); } Odometer::~Odometer() { } void Odometer::setBlackboard(Blackboard *a_blackboard) { KnowledgeSource::setBlackboard(a_blackboard); QTimer::singleShot(250, this, &Odometer::doTimedUpdate); } void Odometer::doTimedUpdate() { auto val = m_blackboard->inspect("distance").data.toDouble(); display(QString::number(val, 'f', 1)); QTimer::singleShot(250, this, &Odometer::doTimedUpdate); } #include #ifndef OCCA_INTERNAL_MODES_CUDA_STREAMTAG_HEADER #define OCCA_INTERNAL_MODES_CUDA_STREAMTAG_HEADER #include #include namespace occa { namespace cuda { class streamTag : public occa::modeStreamTag_t { public: CUevent cuEvent; streamTag(modeDevice_t *modeDevice_, CUevent cuEvent_); virtual ~streamTag(); }; } } #endif zyiacas/boost-doc-zh /* * * Copyright (c) 2004 * * * Use, modification and distribution are subject to 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 "test.hpp" #ifdef BOOST_MSVC #pragma warning(disable:4127) #endif void test_grep() { // // now test grep, // basically check all our restart types - line, word, etc // checking each one for null and non-null matches. // using namespace boost::regex_constants; TEST_REGEX_SEARCH("a", perl|nosubs, " a a a aa", match_default, make_array(1, 2, -2, 3, 4, -2, 5, 6, -2, 7, 8, -2, 8, 9, -2, -2)); TEST_REGEX_SEARCH("a+b+", perl|nosubs, "aabaabbb ab", match_default, make_array(0, 3, -2, 3, 8, -2, 9, 11, -2, -2)); TEST_REGEX_SEARCH("a(b*|c|e)d", perl|nosubs, "adabbdacd", match_default, make_array(0, 2, -2, 2, 6, -2, 6, 9, -2, -2)); TEST_REGEX_SEARCH("a", perl|nosubs, "\na\na\na\naa", match_default, make_array(1, 2, -2, 3, 4, -2, 5, 6, -2, 7, 8, -2, 8, 9, -2, -2)); TEST_REGEX_SEARCH("^", perl|nosubs, " \n\n \n\n\n", match_default, make_array(0, 0, -2, 4, 4, -2, 5, 5, -2, 8, 8, -2, 9, 9, -2, 10, 10, -2, -2)); TEST_REGEX_SEARCH("^ab", perl|nosubs, "ab \nab ab\n", match_default, make_array(0, 2, -2, 5, 7, -2, -2)); TEST_REGEX_SEARCH("^[^\\n]*\n", perl|nosubs, " \n \n\n \n", match_default, make_array(0, 4, -2, 4, 7, -2, 7, 8, -2, 8, 11, -2, -2)); TEST_REGEX_SEARCH("\\Book/Assignment_5/Gaddis_8thEd_Chap6_Prob06/main.cpp //File: main.cpp //========================================================================== //Programmer: //========================================================================== //Created: April 25, 2015, 12:23 PM //========================================================================== //Purpose: Kinetic Energy //========================================================================== //System Libraries #include //Input/Output Library #include //Parametric Library using namespace std; //Input/Output Library under standard name space //User Libraries //Global Constants //Function Prototypes float kEnergy(float, float); //Kinetic Energy Function //Execution begins int main() { //Declare variables float mass; //Mass in kilograms float vlcty; //Velocity in meters per second float kinNrgy; //Kinetic energy in newtons //Prompt the user for input cout << setw(36) << "* Kinetic Energy *\n"; cout << setw(36) << "------------------\n"; cout << "This program calculates a moving object's kinetic energy.\n\n"; cout << "Enter the mass of the object in kilograms: "; cin >> mass; cout << "Enter the velocity of the object in meters per second: "; cin >> vlcty; cout << endl; //Call the kinetic energy function kinNrgy = kEnergy(mass, vlcty); //Output the results cout << "The total kinetic energy of the object is: " << kinNrgy << " newtons" << endl; //Exit the program return 0; } float kEnergy(float mass, float vlcty) { //Declare variables float total; //Calculate total = (0.5) * mass * (vlcty * vlcty); //Return the value return(total); }src/Interactable.cpp #include "Interactable.h" namespace UT { Interactable::Interactable() { objectType = ObjectType::Interactable; } }Source/RTMSDF/Private/Module/RTMSDF.cpp // Copyright (c) . All Rights Reserved #include "RTMSDF.h" #define LOCTEXT_NAMESPACE "RTMSDFModule" DEFINE_LOG_CATEGORY(RTMSDF); IMPLEMENT_MODULE(FRTMSDFModule, RTMSDF) #undef LOCTEXT_NAMESPACE modules/drivers/lidar/lidar_robosense/lib/socket_input.cpp /****************************************************************************** * Copyright 2021 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/drivers/lidar/lidar_robosense/lib/socket_input.h" #include #include #include #include #include #include #include #include namespace apollo { namespace drivers { namespace robosense { //////////////////////////////////////////////////////////////////////// // InputSocket class implementation //////////////////////////////////////////////////////////////////////// /** @brief constructor * * @param private_nh private node handle for driver * @param udp_port UDP port number to connect */ SocketInput::SocketInput() : Input(), sockfd_(-1), port_(0) {} /** @brief destructor */ SocketInput::~SocketInput(void) { (void)close(sockfd_); } void SocketInput::init(uint32_t port) { if (sockfd_ != -1) { (void)close(sockfd_); } // connect to suteng UDP port AINFO << "Opening UDP socket: port " << uint16_t(port); port_ = port; sockfd_ = socket(AF_INET, SOCK_DGRAM, 0); if (sockfd_ == -1) { AERROR << " Init socket failed, UDP port is " << port; } sockaddr_in my_addr; // my address information memset(&my_addr, 0, sizeof(my_addr)); // initialize to zeros my_addr.sin_family = AF_INET; // host byte order my_addr.sin_port = htons(uint16_t(port)); // short, in network byte order my_addr.sin_addr.s_addr = INADDR_ANY; // automatically fill in my IP AINFO << "SocketInput::init " << my_addr.sin_addr.s_addr; const int opt = -1; int rtn = setsockopt(sockfd_, SOL_SOCKET, SO_REUSEPORT, &opt, sizeof(opt)); if (rtn < 0) { AINFO << "setsockopt failed !!!!!!!!!!"; return; } if (bind(sockfd_, reinterpret_cast(&my_addr), sizeof(sockaddr)) == -1) { AERROR << " Socket bind failed! Port " << port_; return; } if (fcntl(sockfd_, F_SETFL, O_NONBLOCK | FASYNC) < 0) { AERROR << " non-block! Port " << port_; return; } AINFO << "suteng socket fd is " << sockfd_ << ", port " << port_; } /** @brief Get one suteng packet. */ int SocketInput::get_firing_data_packet( apollo::drivers::suteng::SutengPacket *pkt, int time_zone, uint64_t start_time_) { while (true) { if (!input_available(POLL_TIMEOUT)) { AINFO << "SocketInput::get_firing_data_packet---SOCKET_TIMEOUT"; return SOCKET_TIMEOUT; } // Receive packets that should now be available from the // socket using a blocking read. uint8_t bytes[FIRING_DATA_PACKET_SIZE]; ssize_t nbytes = recvfrom(sockfd_, bytes, FIRING_DATA_PACKET_SIZE, 0, NULL, NULL); if (nbytes < 0) { if (errno != EWOULDBLOCK) { AERROR << " recvfail from port " << port_; return RECIEVE_FAIL; } } if ((size_t)nbytes == FIRING_DATA_PACKET_SIZE) { pkt->set_data(bytes, FIRING_DATA_PACKET_SIZE); tm pkt_time; memset(&pkt_time, 0, sizeof(pkt_time)); pkt_time.tm_year = static_cast(bytes[20] + 100); pkt_time.tm_mon = static_cast(bytes[21] - 1); pkt_time.tm_mday = static_cast(bytes[22]); pkt_time.tm_hour = static_cast(bytes[23] + time_zone); pkt_time.tm_min = static_cast(bytes[24]); pkt_time.tm_sec = static_cast(bytes[25]); uint64_t timestamp_sec = static_cast((mktime(&pkt_time)) * 1e9); uint64_t timestamp_nsec = static_cast(1000 * (256 * bytes[26] + bytes[27]) + (256 * bytes[28] + bytes[29])) * 1e3 + timestamp_sec; // ns pkt->set_stamp(timestamp_nsec); if (!flags) { AINFO << "robo first PPS-GPS-timestamp: [" << timestamp_nsec << "]"; flags = true; } break; } AERROR << " Incomplete suteng rising data packet read: " << nbytes << " bytes from port " << port_; } return 0; } int SocketInput::get_positioning_data_packtet(const NMEATimePtr &nmea_time) { while (true) { if (!input_available(POLL_TIMEOUT)) { return 1; } // Receive packets that should now be available from the // socket using a blocking read. // Last 234 bytes not use uint8_t bytes[POSITIONING_DATA_PACKET_SIZE]; ssize_t nbytes = recvfrom(sockfd_, bytes, POSITIONING_DATA_PACKET_SIZE, 0, NULL, NULL); if (nbytes < 0) { if (errno != EWOULDBLOCK) { AERROR << " recvfail from port " << port_; return 1; } } if ((size_t)nbytes == POSITIONING_DATA_PACKET_SIZE) { // read successful, exract nmea time if (exract_nmea_time_from_packet(nmea_time, bytes + 303)) { break; } else { return 1; } } AINFO << "incomplete suteng packet read: " << nbytes << " bytes from port " << port_; } return 0; } bool SocketInput::input_available(int timeout) { (void)timeout; struct pollfd fds[1]; fds[0].fd = sockfd_; fds[0].events = POLLIN; do { int retval = poll(fds, 1, POLL_TIMEOUT); if (retval < 0) { // poll() error? if (errno != EINTR) { AERROR << " suteng port " << port_ << "poll() error: " << strerror(errno); } return false; } if (retval == 0) { // poll() timeout? AERROR << " suteng port " << port_ << " poll() timeout"; return false; } if ((fds[0].revents & POLLERR) || (fds[0].revents & POLLHUP) || (fds[0].revents & POLLNVAL)) { // device error? AERROR << " suteng port " << port_ << "poll() reports suteng error"; return false; } } while ((fds[0].revents & POLLIN) == 0); return true; } } // namespace robosense } // namespace drivers } // namespace apollo tensorstore/driver/n5/metadata.cc0 // Copyright 2020 The TensorStore Authors // // 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 "tensorstore/driver/n5/metadata.h" #include #include "absl/algorithm/container.h" #include "absl/base/internal/endian.h" #include "absl/strings/str_join.h" #include "tensorstore/internal/container_to_shared.h" #include "tensorstore/internal/data_type_endian_conversion.h" #include "tensorstore/internal/flat_cord_builder.h" #include "tensorstore/internal/json.h" #include "tensorstore/util/quote_string.h" namespace tensorstore { namespace internal_n5 { namespace { constexpr std::array kSupportedDataTypes{ DataTypeId::uint8_t, DataTypeId::uint16_t, DataTypeId::uint32_t, DataTypeId::uint64_t, DataTypeId::int8_t, DataTypeId::int16_t, DataTypeId::int32_t, DataTypeId::int64_t, DataTypeId::float32_t, DataTypeId::float64_t, }; Status ParseIndexVector(const ::nlohmann::json& value, std::optional* rank, std::vector* vec, Index min_value, Index max_value) { return internal::JsonParseArray( value, [&](std::ptrdiff_t size) { if (*rank) { TENSORSTORE_RETURN_IF_ERROR( internal::JsonValidateArrayLength(size, **rank)); } else { *rank = size; } vec->resize(size); return absl::OkStatus(); }, [&](const ::nlohmann::json& v, std::ptrdiff_t i) { return internal::JsonRequireInteger( v, &(*vec)[i], /*strict=*/true, min_value, max_value); }); } } // namespace Status ParseChunkShape(const ::nlohmann::json& value, std::optional* rank, std::vector* shape) { return ParseIndexVector( value, rank, shape, /*min_value=*/1, /*max_value=*/std::numeric_limits::max()); } Status ParseShape(const ::nlohmann::json& value, std::optional* rank, std::vector* shape) { return ParseIndexVector(value, rank, shape, /*min_value=*/0, kInfIndex); } std::string GetSupportedDataTypes() { return absl::StrJoin( kSupportedDataTypes, ", ", [](std::string* out, DataTypeId id) { absl::StrAppend(out, kDataTypes[static_cast(id)].name()); }); } Status ParseDataType(const ::nlohmann::json& value, DataType* data_type) { std::string s; TENSORSTORE_RETURN_IF_ERROR(internal::JsonRequireValueAs(value, &s)); auto x = GetDataType(s); if (!x.valid() || !absl::c_linear_search(kSupportedDataTypes, x.id())) { return absl::InvalidArgumentError(StrCat( QuoteString(s), " is not one of the supported data types: ", GetSupportedDataTypes())); } *data_type = x; return absl::OkStatus(); } Result N5Metadata::Parse(::nlohmann::json j) { std::optional rank; N5Metadata metadata; if (auto* obj = j.get_ptr<::nlohmann::json::object_t*>()) { metadata.attributes = std::move(*obj); } else { return internal_json::ExpectedError(j, "object"); } std::vector chunk_shape; TENSORSTORE_RETURN_IF_ERROR(internal::JsonRequireObjectMember( metadata.attributes, "dimensions", [&](const ::nlohmann::json& value) { return ParseShape(value, &rank, &metadata.shape); })); TENSORSTORE_RETURN_IF_ERROR(internal::JsonRequireObjectMember( metadata.attributes, "blockSize", [&](const ::nlohmann::json& value) { return ParseChunkShape(value, &rank, &chunk_shape); })); TENSORSTORE_RETURN_IF_ERROR(internal::JsonRequireObjectMember( metadata.attributes, "dataType", [&](const ::nlohmann::json& value) { return ParseDataType(value, &metadata.data_type); })); TENSORSTORE_RETURN_IF_ERROR(internal::JsonRequireObjectMember( metadata.attributes, "compression", [&](const ::nlohmann::json& value) { TENSORSTORE_ASSIGN_OR_RETURN(metadata.compressor, Compressor::FromJson(value)); return absl::OkStatus(); })); // Per the specification: // https://github.com/saalfeldlab/n5#file-system-specification-version-203-snapshot // // Chunks cannot be larger than 2GB (231Bytes). // While this limit may apply to compressed data, we will also apply it // to the uncompressed data. const Index max_num_elements = (static_cast(1) << 31) / metadata.data_type.size(); if (ProductOfExtents(span(chunk_shape)) > max_num_elements) { return absl::InvalidArgumentError( StrCat("\"blockSize\" of ", span(chunk_shape), " with data type of ", metadata.data_type, " exceeds maximum chunk size of 2GB")); } InitializeContiguousLayout(fortran_order, metadata.data_type.size(), chunk_shape, &metadata.chunk_layout); return metadata; } std::string N5Metadata::GetCompatibilityKey() const { ::nlohmann::json::object_t obj; span chunk_shape = chunk_layout.shape(); obj.emplace("blockSize", ::nlohmann::json::array_t(chunk_shape.begin(), chunk_shape.end())); obj.emplace("dataType", data_type.name()); obj.emplace("compression", compressor); return ::nlohmann::json(obj).dump(); } Result N5MetadataConstraints::Parse(::nlohmann::json j) { std::optional rank; N5MetadataConstraints metadata; if (auto* obj = j.get_ptr<::nlohmann::json::object_t*>()) { metadata.attributes = std::move(*obj); } else { return internal_json::ExpectedError(j, "object"); } TENSORSTORE_RETURN_IF_ERROR(internal::JsonHandleObjectMember( metadata.attributes, "dimensions", [&](const ::nlohmann::json& value) { return ParseShape(value, &rank, &metadata.shape.emplace()); })); TENSORSTORE_RETURN_IF_ERROR(internal::JsonHandleObjectMember( metadata.attributes, "blockSize", [&](const ::nlohmann::json& value) { return ParseChunkShape(value, &rank, &metadata.chunk_shape.emplace()); })); TENSORSTORE_RETURN_IF_ERROR(internal::JsonHandleObjectMember( metadata.attributes, "dataType", [&](const ::nlohmann::json& value) { return ParseDataType(value, &metadata.data_type); })); TENSORSTORE_RETURN_IF_ERROR(internal::JsonHandleObjectMember( metadata.attributes, "compression", [&](const ::nlohmann::json& value) { TENSORSTORE_ASSIGN_OR_RETURN(metadata.compressor, Compressor::FromJson(value)); return absl::OkStatus(); })); return metadata; } TENSORSTORE_DEFINE_JSON_DEFAULT_BINDER(N5MetadataConstraints, [](auto is_loading, const auto& options, auto* obj, auto* j) { if constexpr (is_loading) { // TODO(jbms): Convert this to use // JSON binding framework for // parsing. TENSORSTORE_ASSIGN_OR_RETURN( *obj, Parse(*j)); } else { *j = obj->attributes; } return absl::OkStatus(); }) std::size_t GetChunkHeaderSize(const N5Metadata& metadata) { // Per the specification: // https://github.com/saalfeldlab/n5#file-system-specification-version-203-snapshot // // Chunks are stored in the following binary format: // // * mode (uint16 big endian, default = 0x0000, varlength = 0x0001) // // * number of dimensions (uint16 big endian) // // * dimension 1[,...,n] (uint32 big endian) // // * [ mode == varlength ? number of elements (uint32 big endian) ] // // * compressed data (big endian) return // 2 + // mode 2 + // number of dimensions sizeof(std::uint32_t) * metadata.rank(); // dimensions } Result> DecodeChunk(const N5Metadata& metadata, absl::Cord buffer) { // TODO(jbms): Currently, we do not check that `buffer.size()` is less than // the 2GiB limit, although we do implicitly check that the decoded array data // within the chunk is within the 2GiB limit due to the checks on the block // size. Determine if this is an important limit. SharedArrayView array; array.layout() = metadata.chunk_layout; const std::size_t header_size = GetChunkHeaderSize(metadata); if (buffer.size() < header_size) { return absl::InvalidArgumentError( StrCat("Expected header of length ", header_size, ", but chunk has size ", buffer.size())); } auto header_cord = buffer.Subcord(0, header_size); auto header = header_cord.Flatten(); std::uint16_t mode = absl::big_endian::Load16(header.data()); switch (mode) { case 0: // default break; case 1: // varlength return absl::InvalidArgumentError("varlength chunks not supported"); default: return absl::InvalidArgumentError( StrCat("Unexpected N5 chunk mode: ", mode)); } std::uint16_t num_dims = absl::big_endian::Load16(header.data() + 2); if (num_dims != metadata.rank()) { return absl::InvalidArgumentError(StrCat("Received chunk with ", num_dims, " dimensions but expected ", metadata.rank())); } Array encoded_array; encoded_array.layout().set_rank(metadata.rank()); for (DimensionIndex i = 0; i < num_dims; ++i) { encoded_array.shape()[i] = absl::big_endian::Load32(header.data() + 4 + i * 4); } for (DimensionIndex i = 0; i < num_dims; ++i) { if (encoded_array.shape()[i] > metadata.chunk_layout.shape()[i]) { return absl::InvalidArgumentError(StrCat( "Received chunk of size ", encoded_array.shape(), " which exceeds blockSize of ", metadata.chunk_layout.shape())); } } size_t decoded_offset = header_size; if (metadata.compressor) { // TODO(jbms): Change compressor interface to allow the output size to be // specified. absl::Cord decoded; TENSORSTORE_RETURN_IF_ERROR(metadata.compressor->Decode( buffer.Subcord(header_size, buffer.size() - header_size), &decoded, metadata.data_type.size())); buffer = std::move(decoded); decoded_offset = 0; } const std::size_t expected_data_size = encoded_array.num_elements() * metadata.data_type.size(); if (buffer.size() - decoded_offset != expected_data_size) { return absl::InvalidArgumentError(StrCat( "Uncompressed chunk data has length ", buffer.size() - decoded_offset, ", but expected length to be ", expected_data_size)); } // TODO(jbms): Try to avoid unnecessary copies in encoding and decoding. This // applies to other chunk drivers as well. if (absl::c_equal(encoded_array.shape(), metadata.chunk_layout.shape())) { // Chunk is full size. Attempt to decode in place. Transfer ownership of // the existing `buffer` string into `decoded_array`. auto decoded_array = internal::TryViewCordAsArray(buffer, decoded_offset, metadata.data_type, endian::big, metadata.chunk_layout); if (decoded_array.valid()) return decoded_array; } // Partial chunk, must copy. auto flat_buffer = buffer.Flatten(); ComputeStrides(fortran_order, metadata.data_type.size(), encoded_array.shape(), encoded_array.byte_strides()); encoded_array.element_pointer() = ElementPointer( static_cast(flat_buffer.data() + decoded_offset), metadata.data_type); SharedArrayView full_decoded_array( internal::AllocateAndConstructSharedElements( metadata.chunk_layout.num_elements(), value_init, metadata.data_type), metadata.chunk_layout); ArrayView partial_decoded_array( full_decoded_array.element_pointer(), StridedLayoutView<>{encoded_array.shape(), metadata.chunk_layout.byte_strides()}); internal::DecodeArray(encoded_array, endian::big, partial_decoded_array); return full_decoded_array; } Result EncodeChunk(span chunk_indices, const N5Metadata& metadata, ArrayView array) { assert(absl::c_equal(metadata.chunk_layout.shape(), array.shape())); assert(chunk_indices.size() == array.rank()); Array encoded_array; encoded_array.layout().set_rank(array.rank()); for (DimensionIndex i = 0; i < array.rank(); ++i) { const Index full_size = array.shape()[i]; encoded_array.shape()[i] = std::min(full_size, metadata.shape[i] - full_size * chunk_indices[i]); } const std::size_t header_size = GetChunkHeaderSize(metadata); internal::FlatCordBuilder encoded(encoded_array.num_elements() * metadata.data_type.size()); encoded_array.element_pointer() = ElementPointer( static_cast(encoded.data()), metadata.data_type); InitializeContiguousLayout(fortran_order, metadata.data_type.size(), &encoded_array.layout()); ArrayView partial_source_array( array.element_pointer(), StridedLayoutView<>(encoded_array.shape(), array.byte_strides())); internal::EncodeArray(partial_source_array, encoded_array, endian::big); auto encoded_cord = std::move(encoded).Build(); if (metadata.compressor) { absl::Cord compressed; TENSORSTORE_RETURN_IF_ERROR(metadata.compressor->Encode( std::move(encoded_cord), &compressed, metadata.data_type.size())); encoded_cord = std::move(compressed); } internal::FlatCordBuilder header(header_size); // Write header absl::big_endian::Store16(header.data(), 0); // mode: 0x0 = default const DimensionIndex rank = metadata.rank(); absl::big_endian::Store16(header.data() + 2, rank); for (DimensionIndex i = 0; i < rank; ++i) { absl::big_endian::Store32(header.data() + 4 + i * 4, encoded_array.shape()[i]); } auto full_cord = std::move(header).Build(); full_cord.Append(std::move(encoded_cord)); return full_cord; } Status ValidateMetadata(const N5Metadata& metadata, const N5MetadataConstraints& constraints) { const auto MetadataMismatchError = [](const char* name, const auto& expected, const auto& actual) -> Status { return absl::FailedPreconditionError( StrCat("Expected ", QuoteString(name), " of ", ::nlohmann::json(expected).dump(), " but received: ", ::nlohmann::json(actual).dump())); }; if (constraints.shape && !absl::c_equal(metadata.shape, *constraints.shape)) { return MetadataMismatchError("dimensions", *constraints.shape, metadata.shape); } if (constraints.chunk_shape && !absl::c_equal(metadata.chunk_layout.shape(), *constraints.chunk_shape)) { return MetadataMismatchError("blockSize", *constraints.chunk_shape, metadata.attributes.at("blockSize")); } if (constraints.data_type.valid() && constraints.data_type != metadata.data_type) { return MetadataMismatchError("dataType", constraints.data_type.name(), metadata.data_type.name()); } if (constraints.compressor && ::nlohmann::json(*constraints.compressor) != ::nlohmann::json(metadata.compressor)) { return MetadataMismatchError("compression", *constraints.compressor, metadata.compressor); } return absl::OkStatus(); } Result> GetNewMetadata( const N5MetadataConstraints& metadata_constraints) { if (!metadata_constraints.shape) { return absl::InvalidArgumentError("\"dimensions\" must be specified"); } if (!metadata_constraints.chunk_shape) { return absl::InvalidArgumentError("\"blockSize\" must be specified"); } if (!metadata_constraints.data_type.valid()) { return absl::InvalidArgumentError("\"dataType\" must be specified"); } if (!metadata_constraints.compressor) { return absl::InvalidArgumentError("\"compression\" must be specified"); } auto metadata = std::make_shared(); metadata->attributes = metadata_constraints.attributes; metadata->shape = *metadata_constraints.shape; InitializeContiguousLayout( fortran_order, metadata_constraints.data_type.size(), *metadata_constraints.chunk_shape, &metadata->chunk_layout); metadata->data_type = metadata_constraints.data_type; metadata->compressor = *metadata_constraints.compressor; return metadata; } Status ValidateDataType(DataType data_type) { if (!absl::c_linear_search(kSupportedDataTypes, data_type.id())) { return absl::InvalidArgumentError( StrCat(data_type, " data type is not one of the supported data types: ", GetSupportedDataTypes())); } return absl::OkStatus(); } } // namespace internal_n5 } // namespace tensorstore // Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" #include "beatsaber-hook/shared/utils/byref.hpp" // Including type: OVRPlugin #include "GlobalNamespace/OVRPlugin.hpp" // Including type: System.Int32 #include "System/Int32.hpp" #include "beatsaber-hook/shared/utils/typedefs-array.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: System namespace System { // Forward declaring type: Version class Version; // Forward declaring type: IntPtr struct IntPtr; } // Completed forward declares #include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp" NEED_NO_BOX(::GlobalNamespace::OVRPlugin::OVRP_1_49_0); DEFINE_IL2CPP_ARG_TYPE(::GlobalNamespace::OVRPlugin::OVRP_1_49_0*, "", "OVRPlugin/OVRP_1_49_0"); // Type namespace: namespace GlobalNamespace { // Size: 0x10 #pragma pack(push, 1) // Autogenerated type: OVRPlugin/OVRP_1_49_0 // [TokenAttribute] Offset: FFFFFFFF class OVRPlugin::OVRP_1_49_0 : public ::Il2CppObject { public: // Get static field: static public readonly System.Version version static ::System::Version* _get_version(); // Set static field: static public readonly System.Version version static void _set_version(::System::Version* value); // static field const value: static public System.Int32 OVRP_ANCHOR_NAME_SIZE static constexpr const int OVRP_ANCHOR_NAME_SIZE = 32; // Get static field: static public System.Int32 OVRP_ANCHOR_NAME_SIZE static int _get_OVRP_ANCHOR_NAME_SIZE(); // Set static field: static public System.Int32 OVRP_ANCHOR_NAME_SIZE static void _set_OVRP_ANCHOR_NAME_SIZE(int value); // static private System.Void .cctor() // Offset: 0xF10D34 static void _cctor(); // static public OVRPlugin/Result ovrp_SetClientColorDesc(OVRPlugin/ColorSpace colorSpace) // Offset: 0xF10314 static ::GlobalNamespace::OVRPlugin::Result ovrp_SetClientColorDesc(::GlobalNamespace::OVRPlugin::ColorSpace colorSpace); // static public OVRPlugin/Result ovrp_GetHmdColorDesc(ref OVRPlugin/ColorSpace colorSpace) // Offset: 0xF10394 static ::GlobalNamespace::OVRPlugin::Result ovrp_GetHmdColorDesc(ByRef<::GlobalNamespace::OVRPlugin::ColorSpace> colorSpace); // static public OVRPlugin/Result ovrp_Media_EncodeMrcFrameWithPoseTime(System.IntPtr rawBuffer, System.IntPtr audioDataPtr, System.Int32 audioDataLen, System.Int32 audioChannels, System.Double timestamp, System.Double poseTime, ref System.Int32 outSyncId) // Offset: 0xF10414 static ::GlobalNamespace::OVRPlugin::Result ovrp_Media_EncodeMrcFrameWithPoseTime(::System::IntPtr rawBuffer, ::System::IntPtr audioDataPtr, int audioDataLen, int audioChannels, double timestamp, double poseTime, ByRef outSyncId); // static public OVRPlugin/Result ovrp_Media_EncodeMrcFrameDualTexturesWithPoseTime(System.IntPtr backgroundTextureHandle, System.IntPtr foregroundTextureHandle, System.IntPtr audioData, System.Int32 audioDataLen, System.Int32 audioChannels, System.Double timestamp, System.Double poseTime, ref System.Int32 outSyncId) // Offset: 0xF104DC static ::GlobalNamespace::OVRPlugin::Result ovrp_Media_EncodeMrcFrameDualTexturesWithPoseTime(::System::IntPtr backgroundTextureHandle, ::System::IntPtr foregroundTextureHandle, ::System::IntPtr audioData, int audioDataLen, int audioChannels, double timestamp, double poseTime, ByRef outSyncId); // static public OVRPlugin/Result ovrp_Media_SetHeadsetControllerPose(OVRPlugin/Posef headsetPose, OVRPlugin/Posef leftControllerPose, OVRPlugin/Posef rightControllerPose) // Offset: 0xF105B4 static ::GlobalNamespace::OVRPlugin::Result ovrp_Media_SetHeadsetControllerPose(::GlobalNamespace::OVRPlugin::Posef headsetPose, ::GlobalNamespace::OVRPlugin::Posef leftControllerPose, ::GlobalNamespace::OVRPlugin::Posef rightControllerPose); // static public OVRPlugin/Result ovrp_Media_EnumerateCameraAnchorHandles(ref System.Int32 anchorCount, ref System.IntPtr CameraAnchorHandle) // Offset: 0xF1067C static ::GlobalNamespace::OVRPlugin::Result ovrp_Media_EnumerateCameraAnchorHandles(ByRef anchorCount, ByRef<::System::IntPtr> CameraAnchorHandle); // static public OVRPlugin/Result ovrp_Media_GetCurrentCameraAnchorHandle(ref System.IntPtr anchorHandle) // Offset: 0xF1070C static ::GlobalNamespace::OVRPlugin::Result ovrp_Media_GetCurrentCameraAnchorHandle(ByRef<::System::IntPtr> anchorHandle); // static public OVRPlugin/Result ovrp_Media_GetCameraAnchorName(System.IntPtr anchorHandle, System.Char[] cameraName) // Offset: 0xF1078C static ::GlobalNamespace::OVRPlugin::Result ovrp_Media_GetCameraAnchorName(::System::IntPtr anchorHandle, ::ArrayW<::Il2CppChar> cameraName); // static public OVRPlugin/Result ovrp_Media_GetCameraAnchorHandle(System.IntPtr anchorName, ref System.IntPtr anchorHandle) // Offset: 0xF108A8 static ::GlobalNamespace::OVRPlugin::Result ovrp_Media_GetCameraAnchorHandle(::System::IntPtr anchorName, ByRef<::System::IntPtr> anchorHandle); // static public OVRPlugin/Result ovrp_Media_GetCameraAnchorType(System.IntPtr anchorHandle, ref OVRPlugin/CameraAnchorType anchorType) // Offset: 0xF10938 static ::GlobalNamespace::OVRPlugin::Result ovrp_Media_GetCameraAnchorType(::System::IntPtr anchorHandle, ByRef<::GlobalNamespace::OVRPlugin::CameraAnchorType> anchorType); // static public OVRPlugin/Result ovrp_Media_CreateCustomCameraAnchor(System.IntPtr anchorName, ref System.IntPtr anchorHandle) // Offset: 0xF109C8 static ::GlobalNamespace::OVRPlugin::Result ovrp_Media_CreateCustomCameraAnchor(::System::IntPtr anchorName, ByRef<::System::IntPtr> anchorHandle); // static public OVRPlugin/Result ovrp_Media_DestroyCustomCameraAnchor(System.IntPtr anchorHandle) // Offset: 0xF10A58 static ::GlobalNamespace::OVRPlugin::Result ovrp_Media_DestroyCustomCameraAnchor(::System::IntPtr anchorHandle); // static public OVRPlugin/Result ovrp_Media_GetCustomCameraAnchorPose(System.IntPtr anchorHandle, ref OVRPlugin/Posef pose) // Offset: 0xF10AD8 static ::GlobalNamespace::OVRPlugin::Result ovrp_Media_GetCustomCameraAnchorPose(::System::IntPtr anchorHandle, ByRef<::GlobalNamespace::OVRPlugin::Posef> pose); // static public OVRPlugin/Result ovrp_Media_SetCustomCameraAnchorPose(System.IntPtr anchorHandle, OVRPlugin/Posef pose) // Offset: 0xF10B68 static ::GlobalNamespace::OVRPlugin::Result ovrp_Media_SetCustomCameraAnchorPose(::System::IntPtr anchorHandle, ::GlobalNamespace::OVRPlugin::Posef pose); // static public OVRPlugin/Result ovrp_Media_GetCameraMinMaxDistance(System.IntPtr anchorHandle, ref System.Double minDistance, ref System.Double maxDistance) // Offset: 0xF10C04 static ::GlobalNamespace::OVRPlugin::Result ovrp_Media_GetCameraMinMaxDistance(::System::IntPtr anchorHandle, ByRef minDistance, ByRef maxDistance); // static public OVRPlugin/Result ovrp_Media_SetCameraMinMaxDistance(System.IntPtr anchorHandle, System.Double minDistance, System.Double maxDistance) // Offset: 0xF10C9C static ::GlobalNamespace::OVRPlugin::Result ovrp_Media_SetCameraMinMaxDistance(::System::IntPtr anchorHandle, double minDistance, double maxDistance); }; // OVRPlugin/OVRP_1_49_0 #pragma pack(pop) } #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: GlobalNamespace::OVRPlugin::OVRP_1_49_0::_cctor // Il2CppName: .cctor template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter(&GlobalNamespace::OVRPlugin::OVRP_1_49_0::_cctor)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::OVRPlugin::OVRP_1_49_0*), ".cctor", std::vector(), ::std::vector{}); } }; // Writing MetadataGetter for method: GlobalNamespace::OVRPlugin::OVRP_1_49_0::ovrp_SetClientColorDesc // Il2CppName: ovrp_SetClientColorDesc template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter(&GlobalNamespace::OVRPlugin::OVRP_1_49_0::ovrp_SetClientColorDesc)> { static const MethodInfo* get() { static auto* colorSpace = &::il2cpp_utils::GetClassFromName("", "OVRPlugin/ColorSpace")->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::OVRPlugin::OVRP_1_49_0*), "ovrp_SetClientColorDesc", std::vector(), ::std::vector{colorSpace}); } }; // Writing MetadataGetter for method: GlobalNamespace::OVRPlugin::OVRP_1_49_0::ovrp_GetHmdColorDesc // Il2CppName: ovrp_GetHmdColorDesc template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter)>(&GlobalNamespace::OVRPlugin::OVRP_1_49_0::ovrp_GetHmdColorDesc)> { static const MethodInfo* get() { static auto* colorSpace = &::il2cpp_utils::GetClassFromName("", "OVRPlugin/ColorSpace")->this_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::OVRPlugin::OVRP_1_49_0*), "ovrp_GetHmdColorDesc", std::vector(), ::std::vector{colorSpace}); } }; // Writing MetadataGetter for method: GlobalNamespace::OVRPlugin::OVRP_1_49_0::ovrp_Media_EncodeMrcFrameWithPoseTime // Il2CppName: ovrp_Media_EncodeMrcFrameWithPoseTime template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter)>(&GlobalNamespace::OVRPlugin::OVRP_1_49_0::ovrp_Media_EncodeMrcFrameWithPoseTime)> { static const MethodInfo* get() { static auto* rawBuffer = &::il2cpp_utils::GetClassFromName("System", "IntPtr")->byval_arg; static auto* audioDataPtr = &::il2cpp_utils::GetClassFromName("System", "IntPtr")->byval_arg; static auto* audioDataLen = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; static auto* audioChannels = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; static auto* timestamp = &::il2cpp_utils::GetClassFromName("System", "Double")->byval_arg; static auto* poseTime = &::il2cpp_utils::GetClassFromName("System", "Double")->byval_arg; static auto* outSyncId = &::il2cpp_utils::GetClassFromName("System", "Int32")->this_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::OVRPlugin::OVRP_1_49_0*), "ovrp_Media_EncodeMrcFrameWithPoseTime", std::vector(), ::std::vector{rawBuffer, audioDataPtr, audioDataLen, audioChannels, timestamp, poseTime, outSyncId}); } }; // Writing MetadataGetter for method: GlobalNamespace::OVRPlugin::OVRP_1_49_0::ovrp_Media_EncodeMrcFrameDualTexturesWithPoseTime // Il2CppName: ovrp_Media_EncodeMrcFrameDualTexturesWithPoseTime template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter)>(&GlobalNamespace::OVRPlugin::OVRP_1_49_0::ovrp_Media_EncodeMrcFrameDualTexturesWithPoseTime)> { static const MethodInfo* get() { static auto* backgroundTextureHandle = &::il2cpp_utils::GetClassFromName("System", "IntPtr")->byval_arg; static auto* foregroundTextureHandle = &::il2cpp_utils::GetClassFromName("System", "IntPtr")->byval_arg; static auto* audioData = &::il2cpp_utils::GetClassFromName("System", "IntPtr")->byval_arg; static auto* audioDataLen = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; static auto* audioChannels = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; static auto* timestamp = &::il2cpp_utils::GetClassFromName("System", "Double")->byval_arg; static auto* poseTime = &::il2cpp_utils::GetClassFromName("System", "Double")->byval_arg; static auto* outSyncId = &::il2cpp_utils::GetClassFromName("System", "Int32")->this_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::OVRPlugin::OVRP_1_49_0*), "ovrp_Media_EncodeMrcFrameDualTexturesWithPoseTime", std::vector(), ::std::vector{backgroundTextureHandle, foregroundTextureHandle, audioData, audioDataLen, audioChannels, timestamp, poseTime, outSyncId}); } }; // Writing MetadataGetter for method: GlobalNamespace::OVRPlugin::OVRP_1_49_0::ovrp_Media_SetHeadsetControllerPose // Il2CppName: ovrp_Media_SetHeadsetControllerPose template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter(&GlobalNamespace::OVRPlugin::OVRP_1_49_0::ovrp_Media_SetHeadsetControllerPose)> { static const MethodInfo* get() { static auto* headsetPose = &::il2cpp_utils::GetClassFromName("", "OVRPlugin/Posef")->byval_arg; static auto* leftControllerPose = &::il2cpp_utils::GetClassFromName("", "OVRPlugin/Posef")->byval_arg; static auto* rightControllerPose = &::il2cpp_utils::GetClassFromName("", "OVRPlugin/Posef")->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::OVRPlugin::OVRP_1_49_0*), "ovrp_Media_SetHeadsetControllerPose", std::vector(), ::std::vector{headsetPose, leftControllerPose, rightControllerPose}); } }; // Writing MetadataGetter for method: GlobalNamespace::OVRPlugin::OVRP_1_49_0::ovrp_Media_EnumerateCameraAnchorHandles // Il2CppName: ovrp_Media_EnumerateCameraAnchorHandles template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter, ByRef<::System::IntPtr>)>(&GlobalNamespace::OVRPlugin::OVRP_1_49_0::ovrp_Media_EnumerateCameraAnchorHandles)> { static const MethodInfo* get() { static auto* anchorCount = &::il2cpp_utils::GetClassFromName("System", "Int32")->this_arg; static auto* CameraAnchorHandle = &::il2cpp_utils::GetClassFromName("System", "IntPtr")->this_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::OVRPlugin::OVRP_1_49_0*), "ovrp_Media_EnumerateCameraAnchorHandles", std::vector(), ::std::vector{anchorCount, CameraAnchorHandle}); } }; // Writing MetadataGetter for method: GlobalNamespace::OVRPlugin::OVRP_1_49_0::ovrp_Media_GetCurrentCameraAnchorHandle // Il2CppName: ovrp_Media_GetCurrentCameraAnchorHandle template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter)>(&GlobalNamespace::OVRPlugin::OVRP_1_49_0::ovrp_Media_GetCurrentCameraAnchorHandle)> { static const MethodInfo* get() { static auto* anchorHandle = &::il2cpp_utils::GetClassFromName("System", "IntPtr")->this_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::OVRPlugin::OVRP_1_49_0*), "ovrp_Media_GetCurrentCameraAnchorHandle", std::vector(), ::std::vector{anchorHandle}); } }; // Writing MetadataGetter for method: GlobalNamespace::OVRPlugin::OVRP_1_49_0::ovrp_Media_GetCameraAnchorName // Il2CppName: ovrp_Media_GetCameraAnchorName template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter)>(&GlobalNamespace::OVRPlugin::OVRP_1_49_0::ovrp_Media_GetCameraAnchorName)> { static const MethodInfo* get() { static auto* anchorHandle = &::il2cpp_utils::GetClassFromName("System", "IntPtr")->byval_arg; static auto* cameraName = &il2cpp_functions::array_class_get(::il2cpp_utils::GetClassFromName("System", "Char"), 1)->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::OVRPlugin::OVRP_1_49_0*), "ovrp_Media_GetCameraAnchorName", std::vector(), ::std::vector{anchorHandle, cameraName}); } }; // Writing MetadataGetter for method: GlobalNamespace::OVRPlugin::OVRP_1_49_0::ovrp_Media_GetCameraAnchorHandle // Il2CppName: ovrp_Media_GetCameraAnchorHandle template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter)>(&GlobalNamespace::OVRPlugin::OVRP_1_49_0::ovrp_Media_GetCameraAnchorHandle)> { static const MethodInfo* get() { static auto* anchorName = &::il2cpp_utils::GetClassFromName("System", "IntPtr")->byval_arg; static auto* anchorHandle = &::il2cpp_utils::GetClassFromName("System", "IntPtr")->this_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::OVRPlugin::OVRP_1_49_0*), "ovrp_Media_GetCameraAnchorHandle", std::vector(), ::std::vector{anchorName, anchorHandle}); } }; // Writing MetadataGetter for method: GlobalNamespace::OVRPlugin::OVRP_1_49_0::ovrp_Media_GetCameraAnchorType // Il2CppName: ovrp_Media_GetCameraAnchorType template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter)>(&GlobalNamespace::OVRPlugin::OVRP_1_49_0::ovrp_Media_GetCameraAnchorType)> { static const MethodInfo* get() { static auto* anchorHandle = &::il2cpp_utils::GetClassFromName("System", "IntPtr")->byval_arg; static auto* anchorType = &::il2cpp_utils::GetClassFromName("", "OVRPlugin/CameraAnchorType")->this_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::OVRPlugin::OVRP_1_49_0*), "ovrp_Media_GetCameraAnchorType", std::vector(), ::std::vector{anchorHandle, anchorType}); } }; // Writing MetadataGetter for method: GlobalNamespace::OVRPlugin::OVRP_1_49_0::ovrp_Media_CreateCustomCameraAnchor // Il2CppName: ovrp_Media_CreateCustomCameraAnchor template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter)>(&GlobalNamespace::OVRPlugin::OVRP_1_49_0::ovrp_Media_CreateCustomCameraAnchor)> { static const MethodInfo* get() { static auto* anchorName = &::il2cpp_utils::GetClassFromName("System", "IntPtr")->byval_arg; static auto* anchorHandle = &::il2cpp_utils::GetClassFromName("System", "IntPtr")->this_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::OVRPlugin::OVRP_1_49_0*), "ovrp_Media_CreateCustomCameraAnchor", std::vector(), ::std::vector{anchorName, anchorHandle}); } }; // Writing MetadataGetter for method: GlobalNamespace::OVRPlugin::OVRP_1_49_0::ovrp_Media_DestroyCustomCameraAnchor // Il2CppName: ovrp_Media_DestroyCustomCameraAnchor template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter(&GlobalNamespace::OVRPlugin::OVRP_1_49_0::ovrp_Media_DestroyCustomCameraAnchor)> { static const MethodInfo* get() { static auto* anchorHandle = &::il2cpp_utils::GetClassFromName("System", "IntPtr")->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::OVRPlugin::OVRP_1_49_0*), "ovrp_Media_DestroyCustomCameraAnchor", std::vector(), ::std::vector{anchorHandle}); } }; // Writing MetadataGetter for method: GlobalNamespace::OVRPlugin::OVRP_1_49_0::ovrp_Media_GetCustomCameraAnchorPose // Il2CppName: ovrp_Media_GetCustomCameraAnchorPose template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter)>(&GlobalNamespace::OVRPlugin::OVRP_1_49_0::ovrp_Media_GetCustomCameraAnchorPose)> { static const MethodInfo* get() { static auto* anchorHandle = &::il2cpp_utils::GetClassFromName("System", "IntPtr")->byval_arg; static auto* pose = &::il2cpp_utils::GetClassFromName("", "OVRPlugin/Posef")->this_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::OVRPlugin::OVRP_1_49_0*), "ovrp_Media_GetCustomCameraAnchorPose", std::vector(), ::std::vector{anchorHandle, pose}); } }; // Writing MetadataGetter for method: GlobalNamespace::OVRPlugin::OVRP_1_49_0::ovrp_Media_SetCustomCameraAnchorPose // Il2CppName: ovrp_Media_SetCustomCameraAnchorPose template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter(&GlobalNamespace::OVRPlugin::OVRP_1_49_0::ovrp_Media_SetCustomCameraAnchorPose)> { static const MethodInfo* get() { static auto* anchorHandle = &::il2cpp_utils::GetClassFromName("System", "IntPtr")->byval_arg; static auto* pose = &::il2cpp_utils::GetClassFromName("", "OVRPlugin/Posef")->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::OVRPlugin::OVRP_1_49_0*), "ovrp_Media_SetCustomCameraAnchorPose", std::vector(), ::std::vector{anchorHandle, pose}); } }; // Writing MetadataGetter for method: GlobalNamespace::OVRPlugin::OVRP_1_49_0::ovrp_Media_GetCameraMinMaxDistance // Il2CppName: ovrp_Media_GetCameraMinMaxDistance template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter, ByRef)>(&GlobalNamespace::OVRPlugin::OVRP_1_49_0::ovrp_Media_GetCameraMinMaxDistance)> { static const MethodInfo* get() { static auto* anchorHandle = &::il2cpp_utils::GetClassFromName("System", "IntPtr")->byval_arg; static auto* minDistance = &::il2cpp_utils::GetClassFromName("System", "Double")->this_arg; static auto* maxDistance = &::il2cpp_utils::GetClassFromName("System", "Double")->this_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::OVRPlugin::OVRP_1_49_0*), "ovrp_Media_GetCameraMinMaxDistance", std::vector(), ::std::vector{anchorHandle, minDistance, maxDistance}); } }; // Writing MetadataGetter for method: GlobalNamespace::OVRPlugin::OVRP_1_49_0::ovrp_Media_SetCameraMinMaxDistance // Il2CppName: ovrp_Media_SetCameraMinMaxDistance template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter(&GlobalNamespace::OVRPlugin::OVRP_1_49_0::ovrp_Media_SetCameraMinMaxDistance)> { static const MethodInfo* get() { static auto* anchorHandle = &::il2cpp_utils::GetClassFromName("System", "IntPtr")->byval_arg; static auto* minDistance = &::il2cpp_utils::GetClassFromName("System", "Double")->byval_arg; static auto* maxDistance = &::il2cpp_utils::GetClassFromName("System", "Double")->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::OVRPlugin::OVRP_1_49_0*), "ovrp_Media_SetCameraMinMaxDistance", std::vector(), ::std::vector{anchorHandle, minDistance, maxDistance}); } }; #include "esqueleto.h" Esqueleto::Esqueleto(){} void Esqueleto::dibuja(bool chess, bool vertice, bool arista, bool solid, float rot){ float r = rot; // rotacion bloque_central if(r > 32) r = 32; if(r < 0) r = 0; float r2 = -(r*1.5); // rotacion parte de arriba float alt; // lo que subira el bloque dependiendo de la posicion de sus brazos. alt = rot*0.40; if(alt > 12){ alt = 12; } if(alt < 0) alt = 0; glPushMatrix(); glTranslatef(0,alt,0); m.dibuja(chess,vertice,arista,solid,r); glPopMatrix(); glPushMatrix(); glTranslatef(0,16,0); a.dibuja(chess,vertice,arista,solid,r2); glPopMatrix(); } Witek902/Raytracer #include "PCH.h" #include "../Window.h" #include "../Core/Utils/Logger.h" #include "../Core/Utils/Bitmap.h" namespace { const char* TranslateErrorCodeToStr(int err) { // these error codes base on XErrorDB, available on /usr/share/X11/XErrorDB switch(err) { case 0: return "OK"; case 1: return "BadRequest"; case 2: return "BadValue"; case 3: return "BadWindow"; case 4: return "BadPixmap"; case 5: return "BadAtom"; case 6: return "BadCursor"; case 7: return "BadFont"; case 8: return "BadMatch"; case 9: return "BadDrawable"; case 10: return "BadAccess"; case 11: return "BadAlloc"; case 12: return "BadColor"; case 13: return "BadGC"; case 14: return "BadIDChoice"; case 15: return "BadName"; case 16: return "BadLength"; case 17: return "BadImplementation"; default: return "Unknown"; } } } // namespace Window::Window() : mConnection(nullptr) , mWindow(0) , mScreen(nullptr) , mDeleteReply(nullptr) , mConnScreen(0) , mGraphicsContext(0u) , mClosed(true) , mInvisible(false) , mWidth(400) , mHeight(400) , mLeft(20) , mTop(20) , mTitle("Window") { for (int i = 0; i < 3; i++) mMouseButtons[i] = false; for (int i = 0; i < 255; i++) mKeys[i] = false; } Window::~Window() { Close(); free(mDeleteReply); if (mConnection) { xcb_set_screen_saver(mConnection, -1, 0, XCB_BLANKING_NOT_PREFERRED, XCB_EXPOSURES_ALLOWED); xcb_destroy_window(mConnection, mWindow); xcb_flush(mConnection); xcb_disconnect(mConnection); } } bool Window::Init() { mConnection = xcb_connect(nullptr, &mConnScreen); if (xcb_connection_has_error(mConnection)) { RT_LOG_ERROR("Failed to connect to X server!"); return false; } // acquire current screen const xcb_setup_t* xcbSetup; xcb_screen_iterator_t xcbIt; xcbSetup = xcb_get_setup(mConnection); xcbIt = xcb_setup_roots_iterator(xcbSetup); while (mConnScreen-- > 0) xcb_screen_next(&xcbIt); mScreen = xcbIt.data; xcb_set_screen_saver(mConnection, 0, 0, XCB_BLANKING_NOT_PREFERRED, XCB_EXPOSURES_ALLOWED); return true; } void Window::SetSize(Uint32 width, Uint32 height) { mWidth = width; mHeight = height; if (!mClosed) { const Uint32 newSize[] = { mWidth, mHeight }; xcb_configure_window(mConnection, mWindow, XCB_CONFIG_WINDOW_WIDTH | XCB_CONFIG_WINDOW_HEIGHT, newSize); } } void Window::SetTitle(const char* title) { mTitle = title; if (!mClosed) { xcb_change_property(mConnection, XCB_PROP_MODE_REPLACE, mWindow, XCB_ATOM_WM_NAME, XCB_ATOM_STRING, 8, mTitle.length(), mTitle.data()); } } void Window::SetInvisible(bool invisible) { mInvisible = invisible; if (mWindow) { if (mInvisible) xcb_unmap_window(mConnection, mWindow); else xcb_map_window(mConnection, mWindow); } } bool Window::Open() { if (!mClosed) return false; // generate our window ID mWindow = xcb_generate_id(mConnection); xcb_colormap_t colormap = xcb_generate_id(mConnection); xcb_create_colormap(mConnection, XCB_COLORMAP_ALLOC_NONE, colormap, mScreen->root, mScreen->root_visual); // set some settings (these match the old ones) Uint32 value_mask = XCB_CW_EVENT_MASK | XCB_CW_COLORMAP; Uint32 value_list[] = { XCB_EVENT_MASK_BUTTON_1_MOTION | XCB_EVENT_MASK_BUTTON_2_MOTION | XCB_EVENT_MASK_BUTTON_PRESS | XCB_EVENT_MASK_BUTTON_RELEASE | XCB_EVENT_MASK_EXPOSURE | XCB_EVENT_MASK_FOCUS_CHANGE | XCB_EVENT_MASK_KEY_PRESS | XCB_EVENT_MASK_KEY_RELEASE | XCB_EVENT_MASK_POINTER_MOTION | XCB_EVENT_MASK_STRUCTURE_NOTIFY, colormap }; xcb_void_cookie_t cookie = xcb_create_window_checked(mConnection, mScreen->root_depth, mWindow, mScreen->root, mLeft, mTop, mWidth, mHeight, 1, XCB_WINDOW_CLASS_INPUT_OUTPUT, mScreen->root_visual, value_mask, value_list); xcb_generic_error_t* err = xcb_request_check(mConnection, cookie); if (err) { RT_LOG_ERROR("Failed to create a window: X11 protocol error %d (%s)", err->error_code, TranslateErrorCodeToStr(err->error_code)); free(err); return false; } xcb_change_property(mConnection, XCB_PROP_MODE_REPLACE, mWindow, XCB_ATOM_WM_NAME, XCB_ATOM_STRING, 8, mTitle.length(), mTitle.data()); // pre-initialize delete atom to be later on notified about Window being destroyed xcb_intern_atom_cookie_t deleteCookie = xcb_intern_atom(mConnection, 1, 16, "WM_DELETE_WINDOW"); mDeleteReply = xcb_intern_atom_reply(mConnection, deleteCookie, nullptr); // get access to WM_PROTOCOLS atom xcb_intern_atom_cookie_t wmProtCookie = xcb_intern_atom(mConnection, 1, 12, "WM_PROTOCOLS"); xcb_intern_atom_reply_t* wmProtReply = xcb_intern_atom_reply(mConnection, wmProtCookie, nullptr); // notify X that we want to be part of WM_DELETE_WINDOW communication xcb_change_property(mConnection, XCB_PROP_MODE_REPLACE, mWindow, wmProtReply->atom, 4, 32, 1, &mDeleteReply->atom); free(wmProtReply); if (!mInvisible) xcb_map_window(mConnection, mWindow); const int32_t gcValueMask = XCB_GC_BACKGROUND | XCB_GC_FOREGROUND | XCB_GC_GRAPHICS_EXPOSURES; const uint32_t gcValue[] = { mScreen->white_pixel, mScreen->black_pixel, 0 }; mGraphicsContext = xcb_generate_id(mConnection); cookie = xcb_create_gc(mConnection, mGraphicsContext, mWindow, gcValueMask, gcValue); err = xcb_request_check(mConnection, cookie); if (err) { RT_LOG_ERROR("Failed to create graphics context: X11 protocol error: %s", TranslateErrorCodeToStr(err->error_code)); free(err); return false; } mClosed = false; return true; } bool Window::Close() { if (mClosed) { return false; } if (mGraphicsContext) { xcb_free_gc(mConnection, mGraphicsContext); mGraphicsContext = 0; } if (!mInvisible) { xcb_unmap_window(mConnection, mWindow); } mClosed = true; return true; } void Window::MouseDown(MouseButton button, int x, int y) { xcb_grab_pointer_cookie_t grab = xcb_grab_pointer(mConnection, 1, mWindow, 0, XCB_GRAB_MODE_ASYNC, XCB_GRAB_MODE_ASYNC, mWindow, XCB_NONE, XCB_CURRENT_TIME); xcb_grab_pointer_reply_t* grabReply = xcb_grab_pointer_reply(mConnection, grab, nullptr); free(grabReply); mMouseButtons[(int)button] = true; mMousePos[(int)button] = x; mMousePos[(int)button] = y; OnMouseDown(button, x, y); } void Window::MouseUp(MouseButton button) { mMouseButtons[(int)button] = false; bool ButtonsReleased = true; for (int i = 0; i < 3; i++) if (mMouseButtons[i]) ButtonsReleased = false; if (ButtonsReleased) xcb_ungrab_pointer(mConnection, XCB_CURRENT_TIME); OnMouseUp(button); } void Window::MouseMove(int x, int y) { OnMouseMove(x, y, x - mMousePos[0], y - mMousePos[1]); mMousePos[0] = x; mMousePos[1] = y; } void Window::ProcessMessages() { xcb_flush(mConnection); xcb_generic_event_t* event; while ((event = xcb_poll_for_event(mConnection))) { // I have no idea why (and XCB reference won't tell me why as well), // but without & ~0x80 ClientMessage event is not received switch (event->response_type & ~0x80) { case XCB_CLIENT_MESSAGE: { xcb_client_message_event_t* cm = reinterpret_cast(event); // close handling if (static_cast(cm->data.data32[0]) == mDeleteReply->atom) { this->OnClose(); this->Close(); } break; } case XCB_KEY_PRESS: { xcb_key_press_event_t* kp = reinterpret_cast(event); mKeys[kp->detail] = true; OnKeyPress(static_cast(kp->detail)); break; } case XCB_KEY_RELEASE: { xcb_key_release_event_t* kr = reinterpret_cast(event); mKeys[kr->detail] = false; //OnKeyUp(static_cast(kr->detail)); break; } case XCB_MOTION_NOTIFY: { xcb_motion_notify_event_t* m = reinterpret_cast(event); MouseMove(m->event_x, m->event_y); break; } case XCB_BUTTON_PRESS: { xcb_button_press_event_t* bp = reinterpret_cast(event); if (bp->detail < 4) // 1-3 MBtns, 4-5 MWheel MouseDown((MouseButton)(bp->detail - 1), bp->event_x, bp->event_y); else if (bp->detail == 4) OnScroll(1); // btn==4 is UP, else OnScroll(-1); // btn==5 is DOWN break; } case XCB_BUTTON_RELEASE: { xcb_button_release_event_t* br = reinterpret_cast(event); MouseUp(MouseButton(br->detail - 1)); break; } case XCB_FOCUS_OUT: { LostFocus(); break; } case XCB_CONFIGURE_NOTIFY: { xcb_configure_notify_event_t* cn = reinterpret_cast(event); if (static_cast(cn->width) != mWidth || static_cast(cn->height) != mHeight) { mWidth = cn->width; mHeight = cn->height; OnResize(mWidth, mHeight); } break; } } free(event); } } bool Window::DrawPixels(const rt::Bitmap& bitmap) { xcb_image_t* img = xcb_image_create_native(mConnection, mWidth, mHeight, XCB_IMAGE_FORMAT_Z_PIXMAP, mScreen->root_depth, nullptr, 4u * mWidth * mHeight, (uint8_t*)bitmap.GetData()); if (!img) { RT_LOG_ERROR("Failed to create temporary image"); return false; } xcb_void_cookie_t c = xcb_image_put(mConnection, mWindow, mGraphicsContext, img, 0, 0, 0); xcb_generic_error_t* err = xcb_request_check(mConnection, c); if (err) { RT_LOG_ERROR("Failed to put image on window: X11 protocol error: %s", TranslateErrorCodeToStr(err->error_code)); free(err); return false; } xcb_image_destroy(img); return true; } void Window::LostFocus() { MouseUp(MouseButton::Left); MouseUp(MouseButton::Middle); MouseUp(MouseButton::Right); for (int i = 0; i < 256; i++) { if (mKeys[i]) { //OnKeyUp(static_cast(i)); mKeys[i] = false; } } } bool Window::IsClosed() const { return mClosed; } bool Window::IsMouseButtonDown(MouseButton button) const { return mMouseButtons[(int)button]; } bool Window::IsKeyPressed(KeyCode key) const { unsigned int k = static_cast(key); if (k <= 256) return mKeys[k]; return false; } void Window::GetMousePosition(int& x, int& y) const { x = mMousePos[0]; y = mMousePos[1]; } bool Window::HasFocus() const { xcb_get_input_focus_cookie_t inputCookie = xcb_get_input_focus(mConnection); xcb_get_input_focus_reply_t* input = xcb_get_input_focus_reply(mConnection, inputCookie, nullptr); return input->focus == mWindow; } void* Window::GetHandle() const { return reinterpret_cast(mWindow); } void Window::GetSize(Uint32& Width, Uint32& Height) const { Width = mWidth; Height = mHeight; } void Window::OnClose() { } void Window::OnResize(Uint32, Uint32) { } void Window::OnKeyPress(KeyCode) { } void Window::OnCharTyped(const char*) { } void Window::OnScroll(int) { } void Window::OnMouseDown(MouseButton, int, int) { } void Window::OnMouseMove(int, int, int, int) { } void Window::OnMouseUp(MouseButton) { } void Window::OnFileDrop(const std::string&) { } 1-10 #include "my_ransac/ransac.h" namespace ransac { unsigned int countDataSmallerThan(const std::vector &errors, const double thresh) { unsigned int cnt = 0; for (const double error : errors) if (error < thresh) cnt += 1; return cnt; } Indices getIndicesOfDataSmallerThan(const std::vector &errors, const double thresh) { Indices indices; int P = errors.size(); for (unsigned int i = 0; i < P; i++) if (errors[i] < thresh) indices.push_back(i); return indices; } } // namespace ransac#include using namespace std; struct Node { int x, y, z; Node(int _x, int _y, int _z) : x(_x), y(_y), z(_z) {} bool operator < (const Node &o) const { if (x > o.x) return true; if (x == o.x and y > o.y) return true; return false; } }; vector v; int dp[100]; int main() { int n; int k = 1; while (cin >> n and n) { v.clear(); memset(dp, 0, sizeof(dp)); for (int i = 0; i != n; ++i) { int x, y, z; cin >> x >> y >> z; v.push_back(Node(max(x, y), min(x, y), z)); v.push_back(Node(max(z, y), min(z, y), x)); v.push_back(Node(max(x, z), min(x, z), y)); } sort(v.begin(), v.end()); int ans = 0; for (int i = 0; i != v.size(); ++i) dp[i] = v[i].z; for (int i = 1; i != v.size(); ++i) { for (int j = 0; j != i; ++j) { if (v[j].x > v[i].x and v[j].y > v[i].y) dp[i] = max(dp[i], dp[j] + v[i].z); } ans = max(ans, dp[i]); } cout << "Case " << k++ << ": maximum height = " << ans << endl; } return 0; } #include "gameobject.h" GameObject::GameObject(Location location) : m_loc(location) { } GameObject::~GameObject() { } Location GameObject::getLocation() const // function definition { return m_loc; } #include "base/diagnostic.h" #include "base/init.h" #include "base/logging.h" #include "base/thread.h" #include #include #include __BEGIN_THIRD_PARTY_HEADERS #include #include #include #include __END_THIRD_PARTY_HEADERS ABSL_FLAG(int, v, 0, "Show all VLOG(m) messages for m <= this."); #define RAW_CHECK(EXPR, MSG) \ do { \ if (!(EXPR)) { \ fprintf(stderr, MSG "\n"); \ exit(EXIT_FAILURE); \ } \ } while (0) namespace faas { namespace base { namespace { static constexpr size_t kNumCleanupFns = 64; static std::function cleanup_fns[kNumCleanupFns]; static std::atomic next_cleanup_fn{0}; static std::function sigint_handler; static void RaiseToDefaultHandler(int signo) { signal(signo, SIG_DFL); raise(signo); } static void SignalHandler(int signo) { if (signo == SIGTERM || signo == SIGABRT) { size_t n = next_cleanup_fn.load(); fprintf(stderr, "Invoke %d clean-up functions\n", (int) n); for (size_t i = 0; i < n; i++) { cleanup_fns[i](); } fprintf(stderr, "Exit with failure\n"); exit(EXIT_FAILURE); } else if (signo == SIGINT) { if (sigint_handler) { sigint_handler(); } else { RaiseToDefaultHandler(SIGINT); } } else { RaiseToDefaultHandler(signo); } } } // namespace void InitMain(int argc, char* argv[], std::vector* positional_args) { absl::InitializeSymbolizer(argv[0]); struct sigaction act; memset(&act, 0, sizeof(struct sigaction)); act.sa_handler = SignalHandler; RAW_CHECK(sigaction(SIGABRT, &act, nullptr) == 0, "Failed to set SIGABRT handler"); RAW_CHECK(sigaction(SIGTERM, &act, nullptr) == 0, "Failed to set SIGTERM handler"); RAW_CHECK(sigaction(SIGINT, &act, nullptr) == 0, "Failed to set SIGINT handler"); absl::FailureSignalHandlerOptions options; options.call_previous_handler = true; absl::InstallFailureSignalHandler(options); std::vector unparsed_args = absl::ParseCommandLine(argc, argv); logging::Init(absl::GetFlag(FLAGS_v)); if (positional_args == nullptr && unparsed_args.size() > 1) { LOG(FATAL) << "This program does not accept positional arguments"; } if (positional_args != nullptr) { positional_args->clear(); for (size_t i = 1; i < unparsed_args.size(); i++) { positional_args->push_back(unparsed_args[i]); } } Thread::RegisterMainThread(); } void ChainCleanupFn(std::function fn) { size_t idx = next_cleanup_fn.fetch_add(1); if (idx >= kNumCleanupFns) { LOG(FATAL) << "Not enough statically allocated clean-up function slots, " "consider enlarge kNumCleanupFns"; } cleanup_fns[idx] = fn; } void SetInterruptHandler(std::function fn) { if (sigint_handler) { LOG(FATAL) << "Interrupt handler can only be set once!"; } sigint_handler = fn; } } // namespace base } // namespace faas MenuFlechas/class/Menu.cpp0 #include using namespace std; #include #include "../rlutil.h" using namespace rlutil; #include "../ui.h" #include "Menu.h" #define Arriba 80 #define Abajo 72 #define Enter 13 #define Flecha "=>" Menu::Menu(const char *Titulo, const char *_Opciones[], int Cantidad){ y=4; tam=Cantidad; ///imprimimos menu title(Titulo, APP_TITLEFORECOLOR, APP_TITLEBACKCOLOR); system ("cls"); title(Titulo, APP_TITLEFORECOLOR, APP_TITLEBACKCOLOR); for(int p;p(data); post_data_.insert(post_data_.end(), char_data, char_data + size); post_content_type_ = type; } void HttpFetcher::SetPostData(const void *data, size_t size) { SetPostData(data, size, kHttpContentTypeUnspecified); } } // namespace chromeos_update_engine 1-10 #include #include #include #include #include #define CATCH_CONFIG_NO_CPP17_UNCAUGHT_EXCEPTIONS #include "catch.hpp" namespace { template< typename Neuron > bool hasValidInputs(const Neuron& neuron, const std::vector< float >& expected) { for(std::size_t i = 0; i < expected.size(); i++) { if(neuron[i].value != expected[i]) { return false; } } return true; } SCENARIO("Convolution grid set inputs", "[layer][convolution][grid][forward]") { GIVEN( "A convolution layer for an image 5*5, stride = 2 and margin = 1") { constexpr std::size_t width = 5; constexpr std::size_t height = 5; constexpr std::size_t inputsNumber = width * height; constexpr std::size_t margin = 1; constexpr std::size_t stride = 2; using ConvolutionGrid = typename nn::ConvolutionGrid< width, height, stride, margin >::define; using ConvolutionLayer = nn::ConvolutionLayer< nn::NeuralLayer, nn::Neuron, nn::SigmoidFunction, 25, ConvolutionGrid >; auto layer = ConvolutionLayer{}; WHEN( "input is a grid filled with the increasing sequence of " "integers") { for(auto i : ranges::views::ints(0, 25)) { layer.setInput(i, static_cast< float >(i + 1)); } THEN("The expected inputs can be described as a following") { std::vector< std::vector< float > > inputs = { {1, 2, 3, 6, 7, 8, 11, 12, 13}, {3, 4, 5, 8, 9, 10, 13, 14, 15}, {11, 12, 13, 16, 17, 18, 21, 22, 23}, {13, 14, 15, 18, 19, 20, 23, 24, 25}}; for(const auto id : ranges::views::ints(0, 4)) { REQUIRE(hasValidInputs(layer[id], inputs[id])); } } } } } } // namespace fltk/fltk-1.3.5/src/Fl_Light_Button.cxx // // "$Id$" // // Lighted button widget for the Fast Light Tool Kit (FLTK). // // Copyright 1998-2015 by and others. // // This library is free software. Distribution and use rights are outlined in // the file "COPYING" which should have been included with this file. If this // file is missing or damaged, see the license at: // // http://www.fltk.org/COPYING.php // // Please report all bugs and problems on the following page: // // http://www.fltk.org/str.php // // Subclass of Fl_Button where the "box" indicates whether it is // pushed or not, and the "down box" is drawn small and square on // the left to indicate the current state. // The default down_box of zero draws a rectangle designed to look // just like Flame's buttons. #include #include #include #include #include "flstring.h" void Fl_Light_Button::draw() { if (box()) draw_box(this==Fl::pushed() ? fl_down(box()) : box(), color()); Fl_Color col = value() ? (active_r() ? selection_color() : fl_inactive(selection_color())) : color(); int W = labelsize(); int bx = Fl::box_dx(box()); // box frame width int dx = bx + 2; // relative position of check mark etc. int dy = (h() - W) / 2; // neg. offset o.k. for vertical centering int lx = 0; // relative label position (STR #3237) if (down_box()) { // draw other down_box() styles: switch (down_box()) { case FL_DOWN_BOX : case FL_UP_BOX : case _FL_PLASTIC_DOWN_BOX : case _FL_PLASTIC_UP_BOX : // Check box... draw_box(down_box(), x()+dx, y()+dy, W, W, FL_BACKGROUND2_COLOR); if (value()) { if (Fl::is_scheme("gtk+")) { fl_color(FL_SELECTION_COLOR); } else { fl_color(col); } int tx = x() + dx + 3; int tw = W - 6; int d1 = tw/3; int d2 = tw-d1; int ty = y() + dy + (W+d2)/2-d1-2; for (int n = 0; n < 3; n++, ty++) { fl_line(tx, ty, tx+d1, ty+d1); fl_line(tx+d1, ty+d1, tx+tw-1, ty+d1-d2+1); } } break; case _FL_ROUND_DOWN_BOX : case _FL_ROUND_UP_BOX : // Radio button... draw_box(down_box(), x()+dx, y()+dy, W, W, FL_BACKGROUND2_COLOR); if (value()) { int tW = (W - Fl::box_dw(down_box())) / 2 + 1; if ((W - tW) & 1) tW++; // Make sure difference is even to center int tdx = dx + (W - tW) / 2; int tdy = dy + (W - tW) / 2; if (Fl::is_scheme("gtk+")) { fl_color(FL_SELECTION_COLOR); tW --; fl_pie(x() + tdx - 1, y() + tdy - 1, tW + 3, tW + 3, 0.0, 360.0); fl_color(fl_color_average(FL_WHITE, FL_SELECTION_COLOR, 0.2f)); } else fl_color(col); switch (tW) { // Larger circles draw fine... default : fl_pie(x() + tdx, y() + tdy, tW, tW, 0.0, 360.0); break; // Small circles don't draw well on many systems... case 6 : fl_rectf(x() + tdx + 2, y() + tdy, tW - 4, tW); fl_rectf(x() + tdx + 1, y() + tdy + 1, tW - 2, tW - 2); fl_rectf(x() + tdx, y() + tdy + 2, tW, tW - 4); break; case 5 : case 4 : case 3 : fl_rectf(x() + tdx + 1, y() + tdy, tW - 2, tW); fl_rectf(x() + tdx, y() + tdy + 1, tW, tW - 2); break; case 2 : case 1 : fl_rectf(x() + tdx, y() + tdy, tW, tW); break; } if (Fl::is_scheme("gtk+")) { fl_color(fl_color_average(FL_WHITE, FL_SELECTION_COLOR, 0.5)); fl_arc(x() + tdx, y() + tdy, tW + 1, tW + 1, 60.0, 180.0); } } break; default : draw_box(down_box(), x()+dx, y()+dy, W, W, col); break; } lx = dx + W + 2; } else { // if down_box() is zero, draw light button style: int hh = h()-2*dy - 2; int ww = W/2+1; int xx = dx; if (w()The destructor deletes the check button. */ Fl_Light_Button::Fl_Light_Button(int X, int Y, int W, int H, const char* l) : Fl_Button(X, Y, W, H, l) { type(FL_TOGGLE_BUTTON); selection_color(FL_YELLOW); align(FL_ALIGN_LEFT|FL_ALIGN_INSIDE); } Fl_Radio_Light_Button::Fl_Radio_Light_Button(int X,int Y,int W,int H,const char *l) : Fl_Light_Button(X,Y,W,H,l) { type(FL_RADIO_BUTTON); } // // End of "$Id$". // src/mlpack/methods/ann/layer/noisylinear_impl.hpp0 /** * @file methods/ann/layer/noisylinear_impl.hpp * @author * * Implementation of the NoisyLinear layer class. * * mlpack is free software; you may redistribute it and/or modify it under the * terms of the 3-clause BSD license. You should have received a copy of the * 3-clause BSD license along with mlpack. If not, see * http://www.opensource.org/licenses/BSD-3-Clause for more information. */ #ifndef MLPACK_METHODS_ANN_LAYER_NOISYLINEAR_IMPL_HPP #define MLPACK_METHODS_ANN_LAYER_NOISYLINEAR_IMPL_HPP // In case it hasn't yet been included. #include "noisylinear.hpp" namespace mlpack { namespace ann /** Artificial Neural Network. */ { template NoisyLinear::NoisyLinear() : inSize(0), outSize(0) { // Nothing to do here. } template NoisyLinear::NoisyLinear( const NoisyLinear& layer) : inSize(layer.inSize), outSize(layer.outSize), weights(layer.weights) { Reset(); } template NoisyLinear::NoisyLinear( const size_t inSize, const size_t outSize) : inSize(inSize), outSize(outSize) { weights.set_size((outSize * inSize + outSize) * 2, 1); weightEpsilon.set_size(outSize, inSize); biasEpsilon.set_size(outSize, 1); } template void NoisyLinear::Reset() { weightMu = arma::mat(weights.memptr(), outSize, inSize, false, false); biasMu = arma::mat(weights.memptr() + weightMu.n_elem, outSize, 1, false, false); weightSigma = arma::mat(weights.memptr() + weightMu.n_elem + biasMu.n_elem, outSize, inSize, false, false); biasSigma = arma::mat(weights.memptr() + weightMu.n_elem * 2 + biasMu.n_elem, outSize, 1, false, false); this->ResetNoise(); } template void NoisyLinear::ResetNoise() { arma::mat epsilonIn = arma::randn(inSize, 1); epsilonIn = arma::sign(epsilonIn) % arma::sqrt(arma::abs(epsilonIn)); arma::mat epsilonOut = arma::randn(outSize, 1); epsilonOut = arma::sign(epsilonOut) % arma::sqrt(arma::abs(epsilonOut)); weightEpsilon = epsilonOut * epsilonIn.t(); biasEpsilon = epsilonOut; } template void NoisyLinear::ResetParameters() { const double muRange = 1 / std::sqrt(inSize); weightMu.randu(); weightMu = muRange * (weightMu * 2 - 1); biasMu.randu(); biasMu = muRange * (biasMu * 2 - 1); weightSigma.fill(0.5 / std::sqrt(inSize)); biasSigma.fill(0.5 / std::sqrt(outSize)); } template template void NoisyLinear::Forward( const arma::Mat& input, arma::Mat& output) { weight = weightMu + weightSigma % weightEpsilon; bias = biasMu + biasSigma % biasEpsilon; output = weight * input; output.each_col() += bias; } template template void NoisyLinear::Backward( const arma::Mat& /* input */, const arma::Mat& gy, arma::Mat& g) { g = weight.t() * gy; } template template void NoisyLinear::Gradient( const arma::Mat& input, const arma::Mat& error, arma::Mat& gradient) { // Locally stored to prevent multiplication twice. arma::mat weightGrad = error * input.t(); // Gradients for mu values. gradient.rows(0, weight.n_elem - 1) = arma::vectorise(weightGrad); gradient.rows(weight.n_elem, weight.n_elem + bias.n_elem - 1) = arma::sum(error, 1); // Gradients for sigma values. gradient.rows(weight.n_elem + bias.n_elem, gradient.n_elem - bias.n_elem - 1) = arma::vectorise(weightGrad % weightEpsilon); gradient.rows(gradient.n_elem - bias.n_elem, gradient.n_elem - 1) = arma::sum(error, 1) % biasEpsilon; } template template void NoisyLinear::serialize( Archive& ar, const uint32_t /* version */) { ar(CEREAL_NVP(inSize)); ar(CEREAL_NVP(outSize)); // This is inefficient, but we have to allocate this memory so that // WeightSetVisitor gets the right size. if (cereal::is_loading()) weights.set_size((outSize * inSize + outSize) * 2, 1); } } // namespace ann } // namespace mlpack #endif #include using namespace std; class car//class named car { private://access specifier float petrol,distance;//instance variable:made for objects public://access specifier car() //Default contructor { petrol=70;//initializing distance=0; } car(float a)//single parameterized { petrol=a; distance=0; } car(float a,float b)//multiple parameterized contructor or constructor overloading) { petrol=a; distance=b; } car(car &n)//copy constructor &n is reference to another object of same type.................................................... { petrol=n.petrol; distance=n.distance; } ~car() { cout<<"An Object have been destroyed!"< #include #include "base/json/json_reader.h" #include "base/metrics/field_trial.h" #include "base/trace_event/trace_log.h" #include "build/build_config.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/tracing/crash_service_uploader.h" #include "components/variations/variations_associated_data.h" #include "content/public/browser/background_tracing_config.h" #include "content/public/browser/background_tracing_manager.h" #include "content/public/browser/browser_thread.h" #include "net/base/network_change_notifier.h" #include "url/gurl.h" namespace tracing { namespace { const char kBackgroundTracingFieldTrial[] = "BackgroundTracing"; const char kBackgroundTracingConfig[] = "config"; const char kBackgroundTracingUploadUrl[] = "upload_url"; ConfigTextFilterForTesting g_config_text_filter_for_testing = nullptr; void OnBackgroundTracingUploadComplete( TraceCrashServiceUploader* uploader, content::BackgroundTracingManager::FinishedProcessingCallback done_callback, bool success, const std::string& feedback) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); std::move(done_callback).Run(success); } void BackgroundTracingUploadCallback( const std::string& upload_url, const scoped_refptr& file_contents, std::unique_ptr metadata, content::BackgroundTracingManager::FinishedProcessingCallback callback) { TraceCrashServiceUploader* uploader = new TraceCrashServiceUploader( g_browser_process->system_request_context()); if (GURL(upload_url).is_valid()) uploader->SetUploadURL(upload_url); #if defined(OS_ANDROID) auto connection_type = net::NetworkChangeNotifier::GetConnectionType(); if (connection_type != net::NetworkChangeNotifier::CONNECTION_WIFI && connection_type != net::NetworkChangeNotifier::CONNECTION_ETHERNET && connection_type != net::NetworkChangeNotifier::CONNECTION_BLUETOOTH) { // Allow only 100KiB for uploads over data. uploader->SetMaxUploadBytes(100 * 1024); } #endif uploader->DoUpload( file_contents->data(), content::TraceUploader::UNCOMPRESSED_UPLOAD, std::move(metadata), content::TraceUploader::UploadProgressCallback(), base::BindOnce(&OnBackgroundTracingUploadComplete, base::Owned(uploader), std::move(callback))); } } // namespace void SetConfigTextFilterForTesting(ConfigTextFilterForTesting predicate) { g_config_text_filter_for_testing = predicate; } void SetupBackgroundTracingFieldTrial() { if (base::trace_event::TraceLog::GetInstance()->IsEnabled()) return; std::string config_text = variations::GetVariationParamValue( kBackgroundTracingFieldTrial, kBackgroundTracingConfig); std::string upload_url = variations::GetVariationParamValue( kBackgroundTracingFieldTrial, kBackgroundTracingUploadUrl); if (config_text.empty()) return; if (g_config_text_filter_for_testing) (*g_config_text_filter_for_testing)(&config_text); std::unique_ptr value = base::JSONReader::Read(config_text); if (!value) return; const base::DictionaryValue* dict = nullptr; if (!value->GetAsDictionary(&dict)) return; std::unique_ptr config = content::BackgroundTracingConfig::FromDict(dict); if (!config) return; content::BackgroundTracingManager::GetInstance()->SetActiveScenario( std::move(config), base::BindOnce(&BackgroundTracingUploadCallback, upload_url), content::BackgroundTracingManager::ANONYMIZE_DATA); } } // namespace tracing /* * Author: illuz <[at]> * File: AC_simulation_n2.cpp * Create Date: 2014-12-07 20:18:49 * Descripton: It means just checkint the places with number is ok. * I try to use dfs to solve them and TLE... */ #include using namespace std; const int N = 0; class Solution { private: int row[9], col[9], sqr[3][3]; bool check(int x, int y, int val) { return !((row[x]>>val)&1) && !((col[y]>>val)&1) && !((sqr[x/3][y/3]>>val)&1); } void mark(int x, int y, int val) { row[x] |= (1< > &board) { // // x = pos / 9, y = pos % 9 // if (pos == 81) // return true; // if (board[pos/9][pos%9] != '.') { // return dfs(pos + 1, board); // } else { // for (int i = 0; i < 9; i++) // if (check(pos/9, pos%9, i)) { // mark(pos/9, pos%9, i); // if (dfs(pos + 1, board)) // return true; // unmark(pos/9, pos%9, i); // } // } // return false; // } public: bool isValidSudoku(vector > &board) { memset(row, 0, sizeof(row)); memset(col, 0, sizeof(col)); memset(sqr, 0, sizeof(sqr)); for (int i = 0; i < board.size(); i++) for (int j = 0; j < board[i].size(); j++) if (board[i][j] != '.') { if (!check(i, j, board[i][j] - '1')) return false; mark(i, j, board[i][j] - '1'); } return true; // return dfs(0, board); } }; int main() { vector > v; Solution s; char ch[10]; for (int i = 0; i < 9; i++) { vector v2; scanf("%s", ch); for (int j = 0; j < 9; j++) { v2.push_back(ch[j]); } v.push_back(v2); } cout << s.isValidSudoku(v) << endl; return 0; } #include"misc.h" #include #include using namespace std; string head(string fn){ FILE * f = fopen(fn.c_str(), "rb"); char * s = NULL; char ** sp = &s; gs(f, sp); str ret(s); // printf("%s\n", s); free(s); return ret; } int main(int argc, char ** argv){ if (argc < 2) err("head.cpp: [filename]"); cout << head(string(argv[1])); return 0; } #include "TestObject.h" #include CTestObject::CTestObject() : CMapObject() { } void CTestObject::collide() { std::cout << "Collided!\n"; }sdk/physx/2.8.3/Samples/PhysXViewer/src/PhysXViewer.cpp //-------------------------------------------------------------------------------------- // File: SampleSoftBodyD3D.cpp // // This sample shows a simple example of the Microsoft Direct3D's High-Level // Shader Language (HLSL) using the Effect interface. // // Copyright (c) Microsoft Corporation. All rights reserved. //-------------------------------------------------------------------------------------- #pragma warning(disable:4995) #pragma warning(disable:4996) #define NOMINMAX #include "dxstdafx.h" #include "resource.h" #include "PhysX.h" #include "menu.h" #include "GuiTui.h" #include "shlwapi.h" #include "log.h" #include "sutil.h" #include #include "SoftBody.h" #include "MyGlobals.h" using namespace SOFTBODY; //#define DEBUG_VS // Uncomment this line to debug vertex shaders //#define DEBUG_PS // Uncomment this line to debug pixel shaders #define USE_HUD 0 //-------------------------------------------------------------------------------------- // Global variables //-------------------------------------------------------------------------------------- ID3DXFont* g_pFont = NULL; // Font for drawing text ID3DXSprite* g_pSprite = NULL; // Sprite for batching draw text calls bool g_bShowHelp = true; // If true, it renders the UI control text float gDtime = 0.0f; CFirstPersonCamera g_Camera; // A model viewing camera CDXUTDialogResourceManager g_DialogResourceManager; // manager for shared resources of dialogs CD3DSettingsDlg g_SettingsDlg; // Device settings dialog #if USE_HUD CDXUTDialog g_HUD; // manages the 3D UI #endif bool g_bEnablePreshader; // if TRUE, then D3DXSHADER_NO_PRESHADER is used when compiling the shader D3DXMATRIXA16 g_mCenterWorld; HWND g_Hwnd; int gNumFrames=0; int gTotalNumFrames=0; float gStartTime=0; float gFPS=60.0f; IDirect3DDevice9* gDevice=0; HINSTANCE gInstance=0; int mLastIndex=0; float mSpeed=2.0f; static int gMovieCapture=0; static int gMovieFrame=0; //-------------------------------------------------------------------------------------- // UI control IDs //-------------------------------------------------------------------------------------- #define IDC_TOGGLEFULLSCREEN 1 #define IDC_TOGGLEREF 3 #define IDC_CHANGEDEVICE 4 #define IDC_ENABLE_PRESHADER 5 #define IDC_NUM_LIGHTS 6 #define IDC_NUM_LIGHTS_STATIC 7 #define IDC_ACTIVE_LIGHT 8 #define IDC_LIGHT_SCALE 9 #define IDC_LIGHT_SCALE_STATIC 10 //-------------------------------------------------------------------------------------- // Forward declarations //-------------------------------------------------------------------------------------- bool CALLBACK IsDeviceAcceptable( D3DCAPS9* pCaps, D3DFORMAT AdapterFormat, D3DFORMAT BackBufferFormat, bool bWindowed, void* pUserContext ); bool CALLBACK ModifyDeviceSettings( DXUTDeviceSettings* pDeviceSettings, const D3DCAPS9* pCaps, void* pUserContext ); HRESULT CALLBACK OnCreateDevice( IDirect3DDevice9* pd3dDevice, const D3DSURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext ); HRESULT CALLBACK OnResetDevice( IDirect3DDevice9* pd3dDevice, const D3DSURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext ); void CALLBACK OnFrameMove( IDirect3DDevice9* pd3dDevice, double fTime, float fElapsedTime, void* pUserContext ); void CALLBACK OnFrameRender( IDirect3DDevice9* pd3dDevice, double fTime, float fElapsedTime, void* pUserContext ); LRESULT CALLBACK MsgProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam, bool* pbNoFurtherProcessing, void* pUserContext ); void CALLBACK KeyboardProc( UINT nChar, bool bKeyDown, bool bAltDown, void* pUserContext ); void CALLBACK OnGUIEvent( UINT nEvent, int nControlID, CDXUTControl* pControl, void* pUserContext ); void CALLBACK OnLostDevice( void* pUserContext ); void CALLBACK OnDestroyDevice( void* pUserContext ); void InitApp(); HRESULT LoadMesh( IDirect3DDevice9* pd3dDevice, WCHAR* strFileName, ID3DXMesh** ppMesh ); void RenderText( double fTime ); //-------------------------------------------------------------------------------------- // Entry point to the program. Initializes everything and goes into a message processing // loop. Idle time is used to render the scene. //-------------------------------------------------------------------------------------- INT WINAPI WinMain( HINSTANCE instance, HINSTANCE, LPSTR, int ) { // Enable run-time memory check for debug builds. #if defined(DEBUG) | defined(_DEBUG) _CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF ); #endif char vcExePath[1024] = {0}; char vcExe[1024]; GetModuleFileNameA(0, vcExePath, sizeof(vcExePath)); strcpy(vcExe,vcExePath); PathRemoveFileSpecA(vcExePath); int len = strlen(vcExePath); const char *exeName = &vcExe[len]; if ( exeName[0] == '\\' || exeName[0] == '/' ) exeName++; if(vcExePath[0]) { int ret = chdir(vcExePath); assert(ret==0); } // Set the callback functions. These functions allow DXUT to notify // the application about device changes, user input, and windows messages. The // callbacks are optional so you need only set callbacks for events you're interested // in. However, if you don't handle the device reset/lost callbacks then the sample // framework won't be able to reset your device since the application must first // release all device resources before resetting. Likewise, if you don't handle the // device created/destroyed callbacks then DXUT won't be able to // recreate your device resources. DXUTSetCallbackDeviceCreated( OnCreateDevice ); DXUTSetCallbackDeviceReset( OnResetDevice ); DXUTSetCallbackDeviceLost( OnLostDevice ); DXUTSetCallbackDeviceDestroyed( OnDestroyDevice ); DXUTSetCallbackMsgProc( MsgProc ); DXUTSetCallbackKeyboard( KeyboardProc ); DXUTSetCallbackFrameRender( OnFrameRender ); DXUTSetCallbackFrameMove( OnFrameMove ); // Show the cursor and clip it when in full screen DXUTSetCursorSettings( true, true ); gInstance = instance; InitApp(); // Initialize DXUT and create the desired Win32 window and Direct3D // device for the application. Calling each of these functions is optional, but they // allow you to set several options which control the behavior of the framework. DXUTInit( true, true, true ); // Parse the command line, handle the default hotkeys, and show msgboxes HMENU menu = createMyMenu(); wchar_t scratch[512]; StringCchPrintf(scratch,512,L"PhysXViewer v(1.0) running against the PhysXSDK version(%d)", NX_SDK_VERSION_NUMBER ); DXUTCreateWindow(scratch, 0, 0, menu ); DXUTCreateDevice( D3DADAPTER_DEFAULT, true, 1024, 768+25, IsDeviceAcceptable, ModifyDeviceSettings ); // Pass control to DXUT for handling the message pump and // dispatching render calls. DXUT will call your FrameMove // and FrameRender callback when there is idle time between handling window messages. DXUTMainLoop(); px_onLostDevice(); saveMenuState(); gAllGlobals.gGuiTui.set(0); // Perform any application-level cleanup here. Direct3D device resources are released within the // appropriate callback functions and therefore don't require any cleanup code here. px_release(); // release NXU Stream things NXU::releasePersistentMemory(); return DXUTGetExitCode(); } //-------------------------------------------------------------------------------------- // Initialize the app //-------------------------------------------------------------------------------------- void InitApp() { g_bEnablePreshader = true; g_SettingsDlg.Init( &g_DialogResourceManager ); #if USE_HUD g_HUD.Init( &g_DialogResourceManager ); g_HUD.SetCallback( OnGUIEvent ); int iY = 10; g_HUD.AddButton( IDC_TOGGLEFULLSCREEN, L"Toggle full screen", 35, iY, 125, 22 ); g_HUD.AddButton( IDC_TOGGLEREF, L"Toggle REF (F3)", 35, iY += 24, 125, 22 ); g_HUD.AddButton( IDC_CHANGEDEVICE, L"Change device (F2)", 35, iY += 24, 125, 22, VK_F2 ); #endif px_init(); } //-------------------------------------------------------------------------------------- // Called during device initialization, this code checks the device for some // minimum set of capabilities, and rejects those that don't pass by returning E_FAIL. //-------------------------------------------------------------------------------------- bool CALLBACK IsDeviceAcceptable( D3DCAPS9* pCaps, D3DFORMAT AdapterFormat, D3DFORMAT BackBufferFormat, bool bWindowed, void* pUserContext ) { // No fallback defined by this app, so reject any device that // doesn't support at least ps1.1 if( pCaps->PixelShaderVersion < D3DPS_VERSION(1,1) ) return false; // Skip backbuffer formats that don't support alpha blending IDirect3D9* pD3D = DXUTGetD3DObject(); if( FAILED( pD3D->CheckDeviceFormat( pCaps->AdapterOrdinal, pCaps->DeviceType, AdapterFormat, D3DUSAGE_QUERY_POSTPIXELSHADER_BLENDING, D3DRTYPE_TEXTURE, BackBufferFormat ) ) ) return false; return true; } //-------------------------------------------------------------------------------------- // This callback function is called immediately before a device is created to allow the // application to modify the device settings. The supplied pDeviceSettings parameter // contains the settings that the framework has selected for the new device, and the // application can make any desired changes directly to this structure. Note however that // DXUT will not correct invalid device settings so care must be taken // to return valid device settings, otherwise IDirect3D9::CreateDevice() will fail. //-------------------------------------------------------------------------------------- bool CALLBACK ModifyDeviceSettings( DXUTDeviceSettings* pDeviceSettings, const D3DCAPS9* pCaps, void* pUserContext ) { // If device doesn't support HW T&L or doesn't support 1.1 vertex shaders in HW // then switch to SWVP. if( (pCaps->DevCaps & D3DDEVCAPS_HWTRANSFORMANDLIGHT) == 0 || pCaps->VertexShaderVersion < D3DVS_VERSION(1,1) ) { pDeviceSettings->BehaviorFlags = D3DCREATE_SOFTWARE_VERTEXPROCESSING; } // Debugging vertex shaders requires either REF or software vertex processing // and debugging pixel shaders requires REF. #ifdef DEBUG_VS if( pDeviceSettings->DeviceType != D3DDEVTYPE_REF ) { pDeviceSettings->BehaviorFlags &= ~D3DCREATE_HARDWARE_VERTEXPROCESSING; pDeviceSettings->BehaviorFlags &= ~D3DCREATE_PUREDEVICE; pDeviceSettings->BehaviorFlags |= D3DCREATE_SOFTWARE_VERTEXPROCESSING; } #endif #ifdef DEBUG_PS pDeviceSettings->DeviceType = D3DDEVTYPE_REF; #endif // For the first device created if its a REF device, optionally display a warning dialog box static bool s_bFirstTime = true; if( s_bFirstTime ) { s_bFirstTime = false; if( pDeviceSettings->DeviceType == D3DDEVTYPE_REF ) DXUTDisplaySwitchingToREFWarning(); } return true; } //-------------------------------------------------------------------------------------- // This callback function will be called immediately after the Direct3D device has been // created, which will happen during application initialization and windowed/full screen // toggles. This is the best location to create D3DPOOL_MANAGED resources since these // resources need to be reloaded whenever the device is destroyed. Resources created // here should be released in the OnDestroyDevice callback. //-------------------------------------------------------------------------------------- HRESULT CALLBACK OnCreateDevice( IDirect3DDevice9* pd3dDevice, const D3DSURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext ) { HRESULT hr; V_RETURN( g_DialogResourceManager.OnCreateDevice( pd3dDevice ) ); V_RETURN( g_SettingsDlg.OnCreateDevice( pd3dDevice ) ); // Initialize the font V_RETURN( D3DXCreateFont( pd3dDevice, 15, 0, FW_BOLD, 1, FALSE, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE, L"Arial", &g_pFont ) ); V_RETURN( CDXUTDirectionWidget::StaticOnCreateDevice( pd3dDevice ) ); // Define DEBUG_VS and/or DEBUG_PS to debug vertex and/or pixel shaders with the // shader debugger. Debugging vertex shaders requires either REF or software vertex // processing, and debugging pixel shaders requires REF. The // D3DXSHADER_FORCE_*_SOFTWARE_NOOPT flag improves the debug experience in the // shader debugger. It enables source level debugging, prevents instruction // reordering, prevents dead code elimination, and forces the compiler to compile // against the next higher available software target, which ensures that the // unoptimized shaders do not exceed the shader model limitations. Setting these // flags will cause slower rendering since the shaders will be unoptimized and // forced into software. See the DirectX documentation for more information about // using the shader debugger. DWORD dwShaderFlags = 0; //D3DXFX_NOT_CLONEABLE; #if defined( DEBUG ) || defined( _DEBUG ) // Set the D3DXSHADER_DEBUG flag to embed debug information in the shaders. // Setting this flag improves the shader debugging experience, but still allows // the shaders to be optimized and to run exactly the way they will run in // the release configuration of this program. dwShaderFlags |= D3DXSHADER_DEBUG; #endif #ifdef DEBUG_VS dwShaderFlags |= D3DXSHADER_FORCE_VS_SOFTWARE_NOOPT; #endif #ifdef DEBUG_PS dwShaderFlags |= D3DXSHADER_FORCE_PS_SOFTWARE_NOOPT; #endif // Preshaders are parts of the shader that the effect system pulls out of the // shader and runs on the host CPU. They should be used if you are GPU limited. // The D3DXSHADER_NO_PRESHADER flag disables preshaders. if( !g_bEnablePreshader ) dwShaderFlags |= D3DXSHADER_NO_PRESHADER; // Setup the camera's view parameters D3DXVECTOR3 vecEye(0.0f, 1.5f, -6.0f); D3DXVECTOR3 vecAt (0.0f, 1.0f, 0.0f); g_Camera.SetViewParams( &vecEye, &vecAt ); g_Camera.SetScalers(0.01f,2.0f); gDevice = pd3dDevice; if ( gAllGlobals.gGuiTui.ref() == 0 ) GuiTui* tmp = new GuiTui(gDevice,g_Hwnd,gInstance,&g_DialogResourceManager); return S_OK; } //-------------------------------------------------------------------------------------- // This function loads the mesh and ensures the mesh has normals; it also optimizes the // mesh for the graphics card's vertex cache, which improves performance by organizing // the internal triangle list for less cache misses. //-------------------------------------------------------------------------------------- HRESULT LoadMesh( IDirect3DDevice9* pd3dDevice, WCHAR* strFileName, ID3DXMesh** ppMesh ) { ID3DXMesh* pMesh = NULL; WCHAR str[MAX_PATH]; HRESULT hr; // Load the mesh with D3DX and get back a ID3DXMesh*. For this // sample we'll ignore the X file's embedded materials since we know // exactly the model we're loading. See the mesh samples such as // "OptimizedMesh" for a more generic mesh loading example. V_RETURN( DXUTFindDXSDKMediaFileCch( str, MAX_PATH, strFileName ) ); V_RETURN( D3DXLoadMeshFromX(str, D3DXMESH_MANAGED, pd3dDevice, NULL, NULL, NULL, NULL, &pMesh) ); DWORD *rgdwAdjacency = NULL; // Make sure there are normals which are required for lighting if( !(pMesh->GetFVF() & D3DFVF_NORMAL) ) { ID3DXMesh* pTempMesh; V( pMesh->CloneMeshFVF( pMesh->GetOptions(), pMesh->GetFVF() | D3DFVF_NORMAL, pd3dDevice, &pTempMesh ) ); V( D3DXComputeNormals( pTempMesh, NULL ) ); SAFE_RELEASE( pMesh ); pMesh = pTempMesh; } // Optimize the mesh for this graphics card's vertex cache // so when rendering the mesh's triangle list the vertices will // cache hit more often so it won't have to re-execute the vertex shader // on those vertices so it will improve perf. rgdwAdjacency = new DWORD[pMesh->GetNumFaces() * 3]; if( rgdwAdjacency == NULL ) return E_OUTOFMEMORY; V( pMesh->GenerateAdjacency(1e-6f,rgdwAdjacency) ); V( pMesh->OptimizeInplace(D3DXMESHOPT_VERTEXCACHE, rgdwAdjacency, NULL, NULL, NULL) ); delete []rgdwAdjacency; *ppMesh = pMesh; return S_OK; } //-------------------------------------------------------------------------------------- // This callback function will be called immediately after the Direct3D device has been // reset, which will happen after a lost device scenario. This is the best location to // create D3DPOOL_DEFAULT resources since these resources need to be reloaded whenever // the device is lost. Resources created here should be released in the OnLostDevice // callback. //-------------------------------------------------------------------------------------- HRESULT CALLBACK OnResetDevice( IDirect3DDevice9* pd3dDevice, const D3DSURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext ) { HRESULT hr; px_onDeviceReset(pd3dDevice); V_RETURN( g_DialogResourceManager.OnResetDevice() ); V_RETURN( g_SettingsDlg.OnResetDevice() ); if( g_pFont ) V_RETURN( g_pFont->OnResetDevice() ); gAllGlobals.gGuiTui.ref()->onResetDevice(pd3dDevice); // Create a sprite to help batch calls when drawing many lines of text V_RETURN( D3DXCreateSprite( pd3dDevice, &g_pSprite ) ); // Setup the camera's projection parameters float fAspectRatio = pBackBufferSurfaceDesc->Width / (FLOAT)pBackBufferSurfaceDesc->Height; g_Camera.SetProjParams( D3DX_PI/3, fAspectRatio, 0.01f, 2000.0f ); #if USE_HUD g_HUD.SetLocation( pBackBufferSurfaceDesc->Width-170, pBackBufferSurfaceDesc->Height-170 ); g_HUD.SetSize( 170, 170 ); #endif return S_OK; } //-------------------------------------------------------------------------------------- // This callback function will be called once at the beginning of every frame. This is the // best location for your application to handle updates to the scene, but is not // intended to contain actual rendering calls, which should instead be placed in the // OnFrameRender callback. //-------------------------------------------------------------------------------------- void CALLBACK OnFrameMove( IDirect3DDevice9* pd3dDevice, double fTime, float fElapsedTime, void* pUserContext ) { g_Camera.SetScalers(0.01f,mSpeed); gDtime = fElapsedTime; gNumFrames++; gTotalNumFrames++; gStartTime+=fElapsedTime; if( gStartTime > 0.2f ) { gFPS = (float)(1.0 / (gStartTime / gNumFrames)); gNumFrames = 0; gStartTime = 0; } // Update the camera's position based on user input bool lshift = false; bool rshift = false; bool rbutton = false; bool lbutton = false; if ( GetAsyncKeyState(VK_RBUTTON) ) rbutton = true; if ( GetAsyncKeyState(VK_LBUTTON) ) lbutton = true; if ( GetAsyncKeyState(VK_LSHIFT) ) lshift = true; if ( GetAsyncKeyState(VK_RSHIFT) ) rshift = true; POINT p; GetCursorPos( &p ); ScreenToClient(g_Hwnd, &p ); int xPos = p.x; int yPos = p.y; bool snarfed = false; if ( gSoftBodySystem ) snarfed = gSoftBodySystem->trackMouse(xPos,yPos,lbutton,rbutton,lshift,rshift,rbutton); if ( !snarfed ) { gAllGlobals.gGuiTui.ref()->Update(); g_Camera.FrameMove( fElapsedTime ); } float dtime = fElapsedTime; if ( gMovieCapture == 2 ) dtime = 1.0f /60.0f; if ( gSoftBodySystem && !gSoftBodySystem->isPaused() ) px_simulate(dtime); } void ScreenGrab(LPDIRECT3DDEVICE9 pDev,const char *_strNamePrefix,int frameNo,bool jpeg) { HRESULT hr; // create the image surface to store the front buffer image // note that call to GetFrontBuffer will always convert format to A8R8G8B8 LPDIRECT3DSURFACE9 surf; // Next, this surface is passed to the GetFrontBuffer() method of the device, which will copy the entire screen into our image buffer: if ( FAILED(hr=pDev->GetBackBuffer(0,0,D3DBACKBUFFER_TYPE_MONO,&surf) ) ) { surf->Release(); return; } char pszScreenshotName[256]; if ( !jpeg ) sprintf(pszScreenshotName,"%s_%04d.bmp",_strNamePrefix, frameNo); else sprintf(pszScreenshotName,"%s_%04d.jpg",_strNamePrefix, frameNo); wchar_t temp[512]; CharToWide(pszScreenshotName,temp,512); if ( !jpeg ) hr=D3DXSaveSurfaceToFile(temp,D3DXIFF_BMP,surf,NULL,NULL); else hr=D3DXSaveSurfaceToFile(temp,D3DXIFF_JPG,surf,NULL,NULL); if ( FAILED(hr) ) { // Release the image surface, its our responsibility surf->Release(); return; } // Release the image surface, its our responsibility surf->Release(); } //-------------------------------------------------------------------------------------- // This callback function will be called at the end of every frame to perform all the // rendering calls for the scene, and it will also be called if the window needs to be // repainted. After this function has returned, DXUT will call // IDirect3DDevice9::Present to display the contents of the next buffer in the swap chain //-------------------------------------------------------------------------------------- void CALLBACK OnFrameRender( IDirect3DDevice9* pd3dDevice, double fTime, float fElapsedTime, void* pUserContext ) { // If the settings dialog is being shown, then // render it instead of rendering the app's scene if( g_SettingsDlg.IsActive() ) { g_SettingsDlg.OnRender( fElapsedTime ); return; } HRESULT hr; D3DXMATRIXA16 mWorldViewProjection; D3DXMATRIXA16 mWorld; D3DXMATRIXA16 mView; D3DXMATRIXA16 mProj; // Clear the render target and the zbuffer float r = 133.0f / 255.0f; float g = 153.0f / 255.0f; float b = 181.0f / 255.0f; V( pd3dDevice->Clear(0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, D3DXCOLOR(r,g,b,0.5f), 1.0f, 0) ); // Render the scene if( SUCCEEDED( pd3dDevice->BeginScene() ) ) { // Get the projection & view matrix from the camera class mWorld = g_mCenterWorld * *g_Camera.GetWorldMatrix(); mProj = *g_Camera.GetProjMatrix(); mView = *g_Camera.GetViewMatrix(); mWorldViewProjection = mWorld * mView * mProj; px_render(pd3dDevice, g_Hwnd, &mView, mProj, gDtime ); if ( gMovieCapture != 2 ) { #if USE_HUD g_HUD.OnRender( fElapsedTime ); #endif gAllGlobals.gGuiTui.ref()->Render(); } V( pd3dDevice->EndScene() ); if ( gMovieCapture == 2 ) { ScreenGrab(pd3dDevice,"PhysX",gMovieFrame++,true); } } } //-------------------------------------------------------------------------------------- // Render the help and statistics text. This function uses the ID3DXFont interface for // efficient text rendering. //-------------------------------------------------------------------------------------- void RenderText( double fTime ) { } // adjust the view frustum void adjustView(const NxBounds3 &bounds) { float xwid = bounds.max.x - bounds.min.x; NxVec3 center; bounds.getCenter(center); NxVec3 eye = center; eye.x = bounds.max.x+(xwid*1.2f); D3DXVECTOR3 vecEye(eye.x,eye.y,eye.z); D3DXVECTOR3 vecAt (center.x,center.y,center.z); g_Camera.SetViewParams( &vecEye, &vecAt ); } //-------------------------------------------------------------------------------------- // Before handling window messages, DXUT passes incoming windows // messages to the application through this callback function. If the application sets // *pbNoFurtherProcessing to TRUE, then DXUT will not process this message. //-------------------------------------------------------------------------------------- LRESULT CALLBACK MsgProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam, bool* pbNoFurtherProcessing, void* pUserContext ) { g_Hwnd = hWnd; // Always allow dialog resource manager calls to handle global messages // so GUI state is updated correctly *pbNoFurtherProcessing = g_DialogResourceManager.MsgProc( hWnd, uMsg, wParam, lParam ); if( *pbNoFurtherProcessing ) return 0; if( g_SettingsDlg.IsActive() ) { g_SettingsDlg.MsgProc( hWnd, uMsg, wParam, lParam ); return 0; } // Give the dialogs a chance to handle the message first #if USE_HUD *pbNoFurtherProcessing = g_HUD.MsgProc( hWnd, uMsg, wParam, lParam ); if( *pbNoFurtherProcessing ) return 0; #endif // Give the dialogs a chance to handle the message first bool snarfed = gAllGlobals.gGuiTui.ref()->MsgProc(hWnd,uMsg,wParam,lParam); if ( !snarfed ) { g_Camera.HandleMessages( hWnd, uMsg, wParam, lParam ); } switch ( uMsg ) { case WM_MOUSEWHEEL: { unsigned int uiX = LOWORD(lParam); unsigned int uiY = HIWORD(lParam); int iDelta = ((short)HIWORD(wParam)); bool snarfed = gSoftBodySystem->processMouseWheel(iDelta); if ( !snarfed ) { const D3DXVECTOR3 *eye = g_Camera.GetEyePt(); const D3DXVECTOR3 *look = g_Camera.GetLookAtPt(); NxVec3 e(&eye->x); NxVec3 l(&look->x); NxVec3 dir = e-l; float dist = dir.magnitude(); dir.normalize(); if ( iDelta >= 0 ) { e = l+(dir*dist*1.1f); } else { e = l+(dir*dist*0.9f); } g_Camera.SetViewParams((D3DXVECTOR3 *) &e.x,(D3DXVECTOR3 *) &l.x ); } } break; case WM_COMMAND: if ( 1 ) { NxBounds3 bounds; bool resize = processMenu(hWnd, LOWORD(wParam), bounds ); if ( resize ) { adjustView(bounds); } } break; } return 0; } //-------------------------------------------------------------------------------------- // As a convenience, DXUT inspects the incoming windows messages for // keystroke messages and decodes the message parameters to pass relevant keyboard // messages to the application. The framework does not remove the underlying keystroke // messages, which are still passed to the application's MsgProc callback. //-------------------------------------------------------------------------------------- void CALLBACK KeyboardProc( UINT nChar, bool bKeyDown, bool bAltDown, void* pUserContext ) { if( bKeyDown ) { switch( nChar ) { case 'M': if ( gMovieCapture == 2 ) { gMovieCapture = 0; gAllGlobals.gLog.ref()->Display("Movie Capture stopped\r\n"); } else if ( gMovieCapture == 0 ) { gMovieCapture = 1; gAllGlobals.gLog.ref()->Display("Press 'M' a second time to begin movie capture.\r\n"); } else if ( gMovieCapture == 1 ) { px_setPaused(false); gMovieCapture = 2; gAllGlobals.gLog.ref()->Display("Movie Capture started. Press 'M' to stop.\r\n"); } break; case VK_SPACE: px_shootSphere(); break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': if ( 1 ) { int index = (nChar-'0')+1; if ( index == mLastIndex ) { if ( index == 1 ) mSpeed*=0.5f; else mSpeed+=((float)index); } else { mSpeed = (float)index; } mLastIndex = index; gAllGlobals.gLog.ref()->Display("Camera speed %0.2f meters per second\r\n", mSpeed ); } break; case VK_HOME: adjustView( gSoftBodySystem->getBounds() ); break; case VK_F1: g_bShowHelp = !g_bShowHelp; break; case 'R': gSoftBodySystem->processCommand(SBC_RESET_SCENE,1,0); break; case 'P': px_togglePaused(); break; case 'I': if ( 1 ) { const D3DXVECTOR3 *eye = g_Camera.GetEyePt(); const D3DXVECTOR3 *look = g_Camera.GetLookAtPt(); gAllGlobals.gLog.ref()->Display("EYE: %0.9f,%0.9f,%0.9f LOOKAT: %0.9f,%0.9f,%0.9f\r\n", eye->x, eye->y, eye->z, look->x, look->y, look->z ); } break; case 'B': if ( gSoftBodySystem->hasShowTetrahedra() ) gSoftBodySystem->setShowTetrahedra(false); else gSoftBodySystem->setShowTetrahedra(true); break; } } } //-------------------------------------------------------------------------------------- // Handles the GUI events //-------------------------------------------------------------------------------------- void CALLBACK OnGUIEvent( UINT nEvent, int nControlID, CDXUTControl* pControl, void* pUserContext ) { switch( nControlID ) { case IDC_TOGGLEFULLSCREEN: DXUTToggleFullScreen(); break; case IDC_TOGGLEREF: DXUTToggleREF(); break; case IDC_CHANGEDEVICE: g_SettingsDlg.SetActive( !g_SettingsDlg.IsActive() ); break; } } //-------------------------------------------------------------------------------------- // This callback function will be called immediately after the Direct3D device has // entered a lost state and before IDirect3DDevice9::Reset is called. Resources created // in the OnResetDevice callback should be released here, which generally includes all // D3DPOOL_DEFAULT resources. See the "Lost Devices" section of the documentation for // information about lost devices. //-------------------------------------------------------------------------------------- void CALLBACK OnLostDevice( void* pUserContext ) { px_onLostDevice(); g_DialogResourceManager.OnLostDevice(); g_SettingsDlg.OnLostDevice(); CDXUTDirectionWidget::StaticOnLostDevice(); if( g_pFont ) g_pFont->OnLostDevice(); SAFE_RELEASE(g_pSprite); gAllGlobals.gGuiTui.ref()->onLostDevice(); } //-------------------------------------------------------------------------------------- // This callback function will be called immediately after the Direct3D device has // been destroyed, which generally happens as a result of application termination or // windowed/full screen toggles. Resources created in the OnCreateDevice callback // should be released here, which generally includes all D3DPOOL_MANAGED resources. //-------------------------------------------------------------------------------------- void CALLBACK OnDestroyDevice( void* pUserContext ) { g_DialogResourceManager.OnDestroyDevice(); g_SettingsDlg.OnDestroyDevice(); CDXUTDirectionWidget::StaticOnDestroyDevice(); SAFE_RELEASE(g_pFont); gDevice = 0; } void lookAt(const float *eye,const float *look) { g_Camera.SetViewParams((D3DXVECTOR3 *)eye,(D3DXVECTOR3 *)look ); } muduo/net/TimerQueue.cc // Copyright 2010, . All rights reserved. // http://code.google.com/p/muduo/ // // Use of this source code is governed by a BSD-style license // that can be found in the License file. // Author: (chenshuo at chenshuo dot com) #ifndef __STDC_LIMIT_MACROS #define __STDC_LIMIT_MACROS #endif #include "muduo/net/TimerQueue.h" #include "muduo/base/Logging.h" #include "muduo/net/EventLoop.h" #include "muduo/net/Timer.h" #include "muduo/net/TimerId.h" #include #include namespace muduo { namespace net { namespace detail { int createTimerfd() { int timerfd = ::timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK | TFD_CLOEXEC); if (timerfd < 0) { LOG_SYSFATAL << "Failed in timerfd_create"; } return timerfd; } struct timespec howMuchTimeFromNow(Timestamp when) { int64_t microseconds = when.microSecondsSinceEpoch() - Timestamp::now().microSecondsSinceEpoch(); if (microseconds < 100) { microseconds = 100; } struct timespec ts; ts.tv_sec = static_cast( microseconds / Timestamp::kMicroSecondsPerSecond); ts.tv_nsec = static_cast( (microseconds % Timestamp::kMicroSecondsPerSecond) * 1000); return ts; } // 其实只是为了读出该timerfd的内容,使poller改变其状态 void readTimerfd(int timerfd, Timestamp now) { uint64_t howmany; ssize_t n = ::read(timerfd, &howmany, sizeof howmany); LOG_TRACE << "TimerQueue::handleRead() " << howmany << " at " << now.toString(); if (n != sizeof howmany) { LOG_ERROR << "TimerQueue::handleRead() reads " << n << " bytes instead of 8"; } } // 调整超时时间值 void resetTimerfd(int timerfd, Timestamp expiration) { // wake up loop by timerfd_settime() struct itimerspec newValue; struct itimerspec oldValue; memZero(&newValue, sizeof newValue); memZero(&oldValue, sizeof oldValue); newValue.it_value = howMuchTimeFromNow(expiration); // 设置timeout为新的值 int ret = ::timerfd_settime(timerfd, 0, &newValue, &oldValue); if (ret) { LOG_SYSERR << "timerfd_settime()"; } } } // namespace detail } // namespace net } // namespace muduo using namespace muduo; using namespace muduo::net; using namespace muduo::net::detail; TimerQueue::TimerQueue(EventLoop* loop) : loop_(loop), timerfd_(createTimerfd()), timerfdChannel_(loop, timerfd_), timers_(), callingExpiredTimers_(false) { timerfdChannel_.setReadCallback( std::bind(&TimerQueue::handleRead, this)); // we are always reading the timerfd, we disarm it with timerfd_settime. timerfdChannel_.enableReading(); } TimerQueue::~TimerQueue() { timerfdChannel_.disableAll(); timerfdChannel_.remove(); ::close(timerfd_); // do not remove channel, since we're in EventLoop::dtor(); for (const Entry& timer : timers_) { delete timer.second; } } // 借用EventLoop实现定时 TimerId TimerQueue::addTimer(const TimerCallback &cb, Timestamp when, double interval) { Timer* timer = new Timer(cb, when, interval); // 创建timer loop_->runInLoop( boost::bind(&TimerQueue::addTimerInLoop, this, timer)); // timer必须在IO线程中添加,是非线程安全的 return TimerId(timer, timer->sequence()); } void TimerQueue::cancel(TimerId timerId) { loop_->runInLoop( std::bind(&TimerQueue::cancelInLoop, this, timerId)); } void TimerQueue::addTimerInLoop(Timer* timer) { loop_->assertInLoopThread(); bool earliestChanged = insert(timer); if (earliestChanged) // 如果刚插入的timer最先到期 { resetTimerfd(timerfd_, timer->expiration()); // 重置timerfd的过期时间 } } void TimerQueue::cancelInLoop(TimerId timerId) { loop_->assertInLoopThread(); assert(timers_.size() == activeTimers_.size()); ActiveTimer timer(timerId.timer_, timerId.sequence_); ActiveTimerSet::iterator it = activeTimers_.find(timer); // 如果能在list中找到,说明timer的超时函数还没被执行,所以可以安全删除 if (it != activeTimers_.end()) { size_t n = timers_.erase(Entry(it->first->expiration(), it->first)); assert(n == 1); (void)n; delete it->first; // FIXME: no delete please activeTimers_.erase(it); } // 否则,如果已经在执行超时函数,先把timer放到cancel list中 else if (callingExpiredTimers_) { cancelingTimers_.insert(timer); } assert(timers_.size() == activeTimers_.size()); } // 当timerfd到期时,变得可写,由poller发现,由事件循环触发该回调 void TimerQueue::handleRead() { loop_->assertInLoopThread(); Timestamp now(Timestamp::now()); readTimerfd(timerfd_, now); // 读取timer fd的内容,否则channel一直为可读状态 std::vector expired = getExpired(now); // 获取在now之前的所有timer,并将它们从timer list中移除 callingExpiredTimers_ = true; cancelingTimers_.clear(); // safe to callback outside critical section for (const Entry& it : expired) { it.second->run(); // 执行用户函数 } callingExpiredTimers_ = false; reset(expired, now); // 重置可restart的timers } // 关键功能。从timers_中移除到期的timer,并通过vector返回 std::vector TimerQueue::getExpired(Timestamp now) { assert(timers_.size() == activeTimers_.size()); std::vector expired; Entry sentry(now, reinterpret_cast(UINTPTR_MAX)); // 找到set中第一个未过期的哨兵值 TimerList::iterator end = timers_.lower_bound(sentry); assert(end == timers_.end() || now < end->first); std::copy(timers_.begin(), end, back_inserter(expired)); // 复制到新vector中 timers_.erase(timers_.begin(), end); for (const Entry& it : expired) { ActiveTimer timer(it->second, it->second->sequence()); size_t n = activeTimers_.erase(timer); // 从尚未到期的set中删除 assert(n == 1); (void)n; } assert(timers_.size() == activeTimers_.size()); return expired; } // 重启可以重复的timer void TimerQueue::reset(const std::vector& expired, Timestamp now) { Timestamp nextExpire; for (const Entry& it : expired) { ActiveTimer timer(it.second, it.second->sequence()); if (it.second->repeat() && cancelingTimers_.find(timer) == cancelingTimers_.end()) { it.second->restart(now); insert(it.second); } else { // FIXME move to a free list delete it.second; // FIXME: no delete please } } // 重置timerfd的下次过期时间 if (!timers_.empty()) { nextExpire = timers_.begin()->second->expiration(); } if (nextExpire.valid()) { resetTimerfd(timerfd_, nextExpire); } } bool TimerQueue::insert(Timer* timer) { loop_->assertInLoopThread(); assert(timers_.size() == activeTimers_.size()); bool earliestChanged = false; Timestamp when = timer->expiration(); TimerList::iterator it = timers_.begin(); // timer都是按expiration升序排列的,所以只需要和第一个timer比较 if (it == timers_.end() || when < it->first) { earliestChanged = true; } { // timers_是基于时间戳 std::pair result = timers_.insert(Entry(when, timer)); assert(result.second); (void)result; } { // activeTimers是基于timerid std::pair result = activeTimers_.insert(ActiveTimer(timer, timer->sequence())); assert(result.second); (void)result; } assert(timers_.size() == activeTimers_.size()); return earliestChanged; } ishxiao/3154/14348592_AC_79MS_172K.cpp //poj 3154 //sep9 #include #include using namespace std; double a[2048]; double b[2048]; int main() { int n,m; while(scanf("%d%d",&n,&m)==2){ for(int i=0;i #include #include "webrtc/base/logging.h" #include "webrtc/base/stringutils.h" #include "webrtc/base/thread.h" #include "webrtc/media/base/mediacommon.h" class DeviceWatcherImpl; namespace cricket { DeviceManagerInterface* DeviceManagerFactory::Create() { return new MacDeviceManager(); } class MacDeviceWatcher : public DeviceWatcher { public: explicit MacDeviceWatcher(DeviceManagerInterface* dm); virtual ~MacDeviceWatcher(); virtual bool Start(); virtual void Stop(); private: DeviceManagerInterface* manager_; DeviceWatcherImpl* impl_; }; static const char* kFilteredAudioDevicesName[] = { NULL, }; // TODO(tommyw): Try to get hold of a copy of Final Cut to understand why we // crash while scanning their components on OS X. static const char* const kFilteredVideoDevicesName[] = { "DVCPRO HD", // Final cut "Sonix SN9C201p", // Crashes in OpenAComponent and CloseComponent NULL, }; static const UInt32 kAudioDeviceNameLength = 64; // Obj-C functions defined in macdevicemanagermm.mm // TODO(ronghuawu): have a shared header for these function defines. extern DeviceWatcherImpl* CreateDeviceWatcherCallback( DeviceManagerInterface* dm); extern void ReleaseDeviceWatcherCallback(DeviceWatcherImpl* impl); extern bool GetAVFoundationVideoDevices(std::vector* out); static bool GetAudioDeviceIDs(bool inputs, std::vector* out); static bool GetAudioDeviceName(AudioDeviceID id, bool input, std::string* out); MacDeviceManager::MacDeviceManager() { set_watcher(new MacDeviceWatcher(this)); } MacDeviceManager::~MacDeviceManager() { } bool MacDeviceManager::GetVideoCaptureDevices(std::vector* devices) { devices->clear(); if (!GetAVFoundationVideoDevices(devices)) { return false; } return FilterDevices(devices, kFilteredVideoDevicesName); } bool MacDeviceManager::GetAudioDevices(bool input, std::vector* devs) { devs->clear(); std::vector dev_ids; bool ret = GetAudioDeviceIDs(input, &dev_ids); if (!ret) { return false; } for (size_t i = 0; i < dev_ids.size(); ++i) { std::string name; if (GetAudioDeviceName(dev_ids[i], input, &name)) { devs->push_back(Device(name, dev_ids[i])); } } return FilterDevices(devs, kFilteredAudioDevicesName); } static bool GetAudioDeviceIDs(bool input, std::vector* out_dev_ids) { UInt32 propsize; OSErr err = AudioHardwareGetPropertyInfo(kAudioHardwarePropertyDevices, &propsize, NULL); if (0 != err) { LOG(LS_ERROR) << "Couldn't get information about property, " << "so no device list acquired."; return false; } size_t num_devices = propsize / sizeof(AudioDeviceID); rtc::scoped_ptr device_ids( new AudioDeviceID[num_devices]); err = AudioHardwareGetProperty(kAudioHardwarePropertyDevices, &propsize, device_ids.get()); if (0 != err) { LOG(LS_ERROR) << "Failed to get device ids, " << "so no device listing acquired."; return false; } for (size_t i = 0; i < num_devices; ++i) { AudioDeviceID an_id = device_ids[i]; // find out the number of channels for this direction // (input/output) on this device - // we'll ignore anything with no channels. err = AudioDeviceGetPropertyInfo(an_id, 0, input, kAudioDevicePropertyStreams, &propsize, NULL); if (0 == err) { unsigned num_channels = propsize / sizeof(AudioStreamID); if (0 < num_channels) { out_dev_ids->push_back(an_id); } } else { LOG(LS_ERROR) << "No property info for stream property for device id " << an_id << "(is_input == " << input << "), so not including it in the list."; } } return true; } static bool GetAudioDeviceName(AudioDeviceID id, bool input, std::string* out_name) { UInt32 nameLength = kAudioDeviceNameLength; char name[kAudioDeviceNameLength + 1]; OSErr err = AudioDeviceGetProperty(id, 0, input, kAudioDevicePropertyDeviceName, &nameLength, name); if (0 != err) { LOG(LS_ERROR) << "No name acquired for device id " << id; return false; } *out_name = name; return true; } MacDeviceWatcher::MacDeviceWatcher(DeviceManagerInterface* manager) : DeviceWatcher(manager), manager_(manager), impl_(NULL) { } MacDeviceWatcher::~MacDeviceWatcher() { } bool MacDeviceWatcher::Start() { if (!impl_) { impl_ = CreateDeviceWatcherCallback(manager_); } return impl_ != NULL; } void MacDeviceWatcher::Stop() { if (impl_) { ReleaseDeviceWatcherCallback(impl_); impl_ = NULL; } } }; // namespace cricket src/MM.cpp #include #include #include using namespace Rcpp; // Too many versions of it. double logsumexp(NumericMatrix &mat) { double maximum = mat(0, 0); double sum = 0.0; // for (size_t i = 0; i < mat.nrow(); i++) { // for (size_t j = 0; j < mat.ncol(); j++) { for (size_t j = 0; j < mat.ncol(); j++) { for (size_t i = 0; i < mat.nrow(); i++) { if (mat(i, j) > maximum) { maximum = mat(i, j); } } } if (maximum < -1000000000) { return (maximum); } for (size_t j = 0; j < mat.ncol(); j++) { for (size_t i = 0; i < mat.nrow(); i++) { sum += exp(mat(i, j) - maximum); } } return (log(sum) + maximum); } double logsumexp(double a, double b) { double maximum = fmax(a, b); if (maximum < -1000000000) { return (maximum); } return (log(exp(a - maximum) + exp(b - maximum)) + maximum); } double logsumexp(double a, double b, double c) { double maximum = fmax(fmax(a, b), c); if (maximum < -1000000000) { return (maximum); } return (log(exp(a - maximum) + exp(b - maximum) + exp(c - maximum)) + maximum); } template double logsumexp(const double (&arr)[N]) { double maximum = arr[0]; double sum = 0.0; for (size_t i = 0; i < N; i++) { if (arr[i] > maximum) { maximum = arr[i]; } } // if (isinf(maximum)) { if (maximum < -1000000000) { return (maximum); } for (size_t i = 0; i < N; i++) { sum += exp(arr[i] - maximum); } return (log(sum) + maximum); } double logsumexp(const std::vector &arr) { size_t N = arr.capacity(); double maximum = arr[0]; double sum = 0.0; for (size_t i = 0; i < N; i++) { if (arr[i] > maximum) { maximum = arr[i]; } } // if (isinf(maximum)) { if (maximum < -1000000000) { return (maximum); } for (size_t i = 0; i < N; i++) { sum += exp(arr[i] - maximum); } return (log(sum) + maximum); } double logsumexp(const double a, const std::vector &arr) { size_t N = arr.capacity(); double maximum = a; double sum = 0.0; for (size_t i = 0; i < N; i++) { if (arr[i] > maximum) { maximum = arr[i]; } } // if (isinf(maximum)) { if (maximum < -1000000000) { return (maximum); } for (size_t i = 0; i < N; i++) { sum += exp(arr[i] - maximum); } sum += exp(a - maximum); return (log(sum) + maximum); } // The likelihood of a specific segment, given that there are n1 female ancestors and n2 male ancestors // d is the number of mutations, len is the lengths, mu_f and mu_m the female and male mutation rate correspondingly. // The male/female lengths are in morgans. NumericVector log_segment(int n1, int n2, const IntegerVector &d, const IntegerVector &len, double mu_f, double mu_m, double intercept, const NumericVector &male_map, const NumericVector &female_map) { NumericVector result(d.size()); // Optimization for small number of mutations... which should be fine for real mutation rate. static const double lgamma_lookup[] = { lgamma(1), lgamma(2), lgamma(3), lgamma(4), lgamma(5), lgamma(6), lgamma(7), lgamma(8), lgamma(9), lgamma(10), lgamma(11), lgamma(12)}; for (size_t i = 0; i < d.size(); i++) { const double temp = lgamma_lookup[(int)d[i]]; const double d1 = (n1 + 1) * female_map[i] + (n2 - 1) * male_map[i]; const double d2 = (n1 - 1) * female_map[i] + (n2 + 1) * male_map[i]; const double par1 = len[i] * (intercept + (n1 + 1) * mu_f + (n2 - 1) * mu_m); const double par2 = len[i] * (intercept + (n1 - 1) * mu_f + (n2 + 1) * mu_m); const double pois1 = log(0.5) + d[i] * log(par1) - par1 - temp - d1; const double pois2 = log(0.5) + d[i] * log(par2) - par2 - temp - d2; result[i] = logsumexp({pois1, pois2}); } return (result); } // The likelihood of a specific segment, including the terms related to the start and end of each segment, given that there are n1 female ancestors and n2 male ancestors // d is the number of mutations, len is the lengths, mu_f and mu_m the female and male mutation rate correspondingly. // The male/female lengths are in morgans. NumericVector log_segment(int n1, int n2, const IntegerVector &d, const IntegerVector &len, double mu_f, double mu_m, double intercept, const NumericVector &male_map, const NumericVector &female_map, const NumericVector &male_start, const NumericVector &female_start, const NumericVector &male_end, const NumericVector &female_end) { NumericVector result(d.size()); // Optimization for small number of mutations... which should be fine for real mutation rate. static const double lgamma_lookup[] = { lgamma(1), lgamma(2), lgamma(3), lgamma(4), lgamma(5), lgamma(6), lgamma(7), lgamma(8), lgamma(9), lgamma(10), lgamma(11), lgamma(12)}; for (size_t i = 0; i < d.size(); i++) { const double temp = lgamma_lookup[(int)d[i]]; const double d1 = (n1 + 1) * female_map[i] + (n2 - 1) * male_map[i]; const double d2 = (n1 - 1) * female_map[i] + (n2 + 1) * male_map[i]; double w1 = log((n1 + 1) * female_start[i] + (n2 - 1) * male_start[i]) + log((n1 + 1) * female_end[i] + (n2 - 1) * male_end[i]); double w2 = log((n1 - 1) * female_start[i] + (n2 + 1) * male_start[i]) + log((n1 - 1) * female_end[i] + (n2 + 1) * male_end[i]); // Avoid taking log(0), start/end should be 0 when the points are around the boundary of the chromosome and so we shouldn't count them. if (male_end[i] == 0.0 && male_start[i] == 0.0) { w1 = 0.0; w2 = 0.0; } else if (male_end[i] == 0.0 || female_end[i] == 0.0) { w1 = log((n1 + 1) * female_start[i] + (n2 - 1) * male_start[i]); w2 = log((n1 - 1) * female_start[i] + (n2 + 1) * male_start[i]); } else if (male_start[i] == 0.0 || female_start[i] == 0.0) { w1 = log((n1 + 1) * female_end[i] + (n2 - 1) * male_end[i]); w2 = log((n1 - 1) * female_end[i] + (n2 + 1) * male_end[i]); } const double par1 = len[i] * (intercept + (n1 + 1) * mu_f + (n2 - 1) * mu_m); const double par2 = len[i] * (intercept + (n1 - 1) * mu_f + (n2 + 1) * mu_m); const double pois1 = log(0.5) + d[i] * log(par1) - par1 - temp - d1 + len[i]*w1; const double pois2 = log(0.5) + d[i] * log(par2) - par2 - temp - d2 + len[i]*w2; result[i] = logsumexp({pois1, pois2}); } return (result); } // [[Rcpp::export]] double cpp_likelihood_hier(double mu_f, double mu_m, const IntegerVector &d, const IntegerVector &len, const List &indexes, const NumericVector &male_map, const NumericVector &female_map, const NumericMatrix &prob, double intercept = 0.0) { // mu_f = exp(mu_f); // mu_m = exp(mu_m); double ll = 0; // NumericVector N_ = {3, 5, 7}; NumericVector N_ = {3, 5}; // Not sure whether to preallocate everything. NumericMatrix segment (d.size(), sum(N_)); size_t i = 0; // Calculate the likelihood for each segment. for (int N: N_) { for (size_t j = 0; j < N; j++) { segment(_, i) = log_segment(j+2, (N+3) - (j+2), d, len, mu_f, mu_m, intercept, male_map, female_map); i++; } } for (size_t i = 0; i < indexes.size(); ++i) { IntegerVector index = indexes[i]; std::vector sum_s (sum(N_), 0.0); for (size_t j = 0; j < index.size(); ++j) { for (size_t k = 0; k < sum(N_); k++) { sum_s[k] += segment(index[j], k); } } std::vector segment_likelihood (sum(N_), 0.0); size_t m_all = 0; size_t n_counter = 0; for (int N: N_) { for (size_t j = 0; j < N; j++) { segment_likelihood[m_all] = prob(i, n_counter) + R::dbinom(j, N - 1, 0.5, 1) + sum_s[m_all]; m_all++; } n_counter++; } ll += logsumexp(segment_likelihood); } return (-ll); } // [[Rcpp::export]] double cpp_likelihood_hier_boundary(double mu_f, double mu_m, const IntegerVector &d, const IntegerVector &len, const List &indexes, const NumericVector &male_map, const NumericVector &female_map, const NumericVector &male_start, const NumericVector &female_start, const NumericVector &male_end, const NumericVector &female_end, const NumericMatrix &prob, double intercept = 0.0) { // mu_f = exp(mu_f); // mu_m = exp(mu_m); double ll = 0; // NumericVector N_ = {3, 5, 7}; NumericVector N_ = {3, 5}; // Not sure whether to preallocate everything. NumericMatrix segment (d.size(), sum(N_)); size_t i = 0; // Calculate the likelihood for each segment. for (int N: N_) { for (size_t j = 0; j < N; j++) { segment(_, i) = log_segment(j+2, (N+3) - (j+2), d, len, mu_f, mu_m, intercept, male_map, female_map, male_start, female_start, male_end, female_end); i++; } } for (size_t i = 0; i < indexes.size(); ++i) { IntegerVector index = indexes[i]; std::vector sum_s (sum(N_), 0.0); for (size_t j = 0; j < index.size(); ++j) { for (size_t k = 0; k < sum(N_); k++) { sum_s[k] += segment(index[j], k); } } std::vector segment_likelihood (sum(N_), 0.0); size_t m_all = 0; size_t n_counter = 0; for (int N: N_) { for (size_t j = 0; j < N; j++) { segment_likelihood[m_all] = prob(i, n_counter) + R::dbinom(j, N - 1, 0.5, 1) + sum_s[m_all]; m_all++; } n_counter++; } ll += logsumexp(segment_likelihood); } return (-ll); } // Calculations needed for a specific pedigree std::vector calculate_specific_pedigree(const int N, const double mu1, const double mu2, double intercept, const IntegerVector &mutation, const IntegerVector &len, const IntegerVector &index, const std::vector &likelihood_precalc) { std::vector logsumexp_jm1(N, 0.0); std::vector logsumexp_jm2(N, 0.0); std::vector logsumexp_jl1(N, 0.0); std::vector logsumexp_jl2(N, 0.0); std::vector logsumexp_ji1(N, 0.0); std::vector logsumexp_ji2(N, 0.0); std::vector wi(N, 0.0); double sum_mutation[2] = {-INFINITY, -INFINITY}; double sum_len[2] = {-INFINITY, -INFINITY}; double sum_intercept[2] = {-INFINITY, -INFINITY}; for (size_t m = 0; m < N; m++) { double sm[2] = {-INFINITY, -INFINITY}; double sl[2] = {-INFINITY, -INFINITY}; double si[2] = {-INFINITY, -INFINITY}; const int general_N = N + 3; const double par[2] = {(m + 1) * mu1 + (general_N - (m + 1)) * mu2 + intercept, (m + 3) * mu1 + (general_N - (m + 3)) * mu2 + intercept}; const double log_par[2] = {log(par[0]), log(par[1])}; for (size_t j = 0; j < index.size(); j++) { const double mut = mutation[index[j]]; const double l = len[index[j]]; const double log_mut = log(mut); const double log_len = log(l); double a = mut * log_par[0] - l * par[0] + likelihood_precalc[index[j]]; double b = mut * log_par[1] - l * par[1] + likelihood_precalc[index[j]]; const double normalize = logsumexp(a, b); a -= normalize; b -= normalize; sm[0] = logsumexp({sm[0], a + log_mut - log_par[0] + log((m + 1) * mu1), b + log_mut - log_par[1] + log((m + 3) * mu1)}); sm[1] = logsumexp( {sm[1], a + log_mut - log_par[0] + log((general_N - (m + 1)) * mu2), b + log_mut - log_par[1] + log((general_N - (m + 3)) * mu2)}); sl[0] = logsumexp( {sl[0], a + log_len + log(m + 1), b + log_len + log(m + 3)}); sl[1] = logsumexp({sl[1], a + log_len + log(general_N - (m + 1)), b + log_len + log(general_N - (m + 3))}); si[0] = logsumexp({si[0], a + log_mut - log_par[0] + log(intercept), b + log_mut - log_par[1] + log(intercept)}); si[1] = logsumexp({si[1], a + log_len, b + log_len}); wi[m] += normalize; } wi[m] += R::dbinom(m, N - 1, 0.5, 1); logsumexp_jm1[m] = sm[0]; logsumexp_jm2[m] = sm[1]; logsumexp_jl1[m] = sl[0]; logsumexp_jl2[m] = sl[1]; logsumexp_ji1[m] = si[0]; logsumexp_ji2[m] = si[1]; } double normalize1 = logsumexp(wi); for (size_t m = 0; m < N; m++) { wi[m] -= normalize1; } for (size_t m = 0; m < N; m++) { sum_mutation[0] = logsumexp(sum_mutation[0], logsumexp_jm1[m] + wi[m]); sum_mutation[1] = logsumexp(sum_mutation[1], logsumexp_jm2[m] + wi[m]); sum_len[0] = logsumexp(sum_len[0], logsumexp_jl1[m] + wi[m]); sum_len[1] = logsumexp(sum_len[1], logsumexp_jl2[m] + wi[m]); sum_intercept[0] = logsumexp(sum_intercept[0], logsumexp_ji1[m] + wi[m]); sum_intercept[1] = logsumexp(sum_intercept[1], logsumexp_ji2[m] + wi[m]); } std::vector result(7, 0.0); result[0] = sum_mutation[0]; result[1] = sum_mutation[1]; result[2] = sum_len[0]; result[3] = sum_len[1]; result[4] = sum_intercept[0]; result[5] = sum_intercept[1]; result[6] = normalize1; return (result); } //' Estimate the mutation rate using EM //' //' @param mu1 Starting value for the first mutation parameter //' @param mu2 Starting value for the second mutation parameter //' @param mutation Vector of the number of mutations in a segment //' @param len Vector of the (physical) length of a segment //' @param indexes List of vector, where each vector is the indexes of the segments for an individual //' @param maxiter Maximum number of EM iterations //' @param eps The algorithm stops when the parameters change is less than eps, |prev_mu - mu| < eps //' @param prob Matrix of probabilities, where the first column is the probability of being first cousin, and the second of second cousin. //' @param estimate_intercept Whether to estimate the intercept as well, intercept is used when there's genotyping error. //' @param intercept Starting value for the intercept. //' @param stochastic If true, an incremental version is used instead. //' @return An estimate of the male mutation rate, female mutation rate and the intercept. // [[Rcpp::export]] NumericVector cpp_em2(double mu1, double mu2, const IntegerVector &mutation, const IntegerVector &len, List &indexes, int maxiter, double eps, const NumericMatrix &prob, bool estimate_intercept = false, double intercept = 0.0) { // NumericVector N_ = {3, 5, 7}; NumericVector N_ = {3, 5}; // Few tests if (prob.nrow() != indexes.size()) { REprintf("Number of rows in prob should be the same as the length of " "indexes.\n"); return NA_REAL; } if (prob.ncol() != N_.size()) { REprintf("Number of cols in prob should be 2.\n"); return NA_REAL; } double prev_mu1 = mu1; double prev_mu2 = mu2; double prev_intercept = intercept; int n = mutation.size(); // int N_all = sum(N_); std::vector likelihood_precalc(n, 0.0); for (size_t k = 0; k < indexes.size(); k++) { IntegerVector index = indexes[k]; for (size_t j = 0; j < index.size(); j++) { double temp = lgamma(mutation[index[j]] + 1); likelihood_precalc[index[j]] = mutation[index[j]] * log(len[index[j]]) - temp; } } for (int i = 0; i < maxiter; i++) { double sum_len[2] = {-INFINITY, -INFINITY}; double sum_mutation[2] = {-INFINITY, -INFINITY}; double sum_intercept[2] = {-INFINITY, -INFINITY}; // double sum_p[2] = {-INFINITY, -INFINITY}; for (size_t k = 0; k < indexes.size(); k++) { IntegerVector index = indexes[k]; double sum_mutation1[2] = {-INFINITY, -INFINITY}; double sum_len1[2] = {-INFINITY, -INFINITY}; double sum_intercept1[2] = {-INFINITY, -INFINITY}; std::vector result1 = calculate_specific_pedigree(N_[0], mu1, mu2, intercept, mutation, len, index, likelihood_precalc); sum_mutation1[0] = result1[0]; sum_mutation1[1] = result1[1]; sum_len1[0] = result1[2]; sum_len1[1] = result1[3]; sum_intercept1[0] = result1[4]; sum_intercept1[1] = result1[5]; double normalize1 = result1[6]; std::vector result2 = calculate_specific_pedigree(N_[1], mu1, mu2, intercept, mutation, len, index, likelihood_precalc); double sum_mutation2[2] = {-INFINITY, -INFINITY}; double sum_len2[2] = {-INFINITY, -INFINITY}; double sum_intercept2[2] = {-INFINITY, -INFINITY}; sum_mutation2[0] = result2[0]; sum_mutation2[1] = result2[1]; sum_len2[0] = result2[2]; sum_len2[1] = result2[3]; sum_intercept2[0] = result2[4]; sum_intercept2[1] = result2[5]; double normalize2 = result2[6]; double p_g[2] = {log(prob(k, 0)) + normalize1, log(prob(k, 1)) + normalize2}; double normalize = logsumexp(p_g); p_g[0] -= normalize; p_g[1] -= normalize; sum_mutation[0] = logsumexp({sum_mutation[0], sum_mutation1[0] + p_g[0], sum_mutation2[0] + p_g[1]}); sum_mutation[1] = logsumexp({sum_mutation[1], sum_mutation1[1] + p_g[0], sum_mutation2[1] + p_g[1]}); sum_len[0] = logsumexp({sum_len[0], sum_len1[0] + p_g[0], sum_len2[0] + p_g[1]}); sum_len[1] = logsumexp({sum_len[1], sum_len1[1] + p_g[0], sum_len2[1] + p_g[1]}); sum_intercept[0] = logsumexp({sum_intercept[0], sum_intercept1[0] + p_g[0], sum_intercept2[0] + p_g[1]}); sum_intercept[1] = logsumexp({sum_intercept[1], sum_intercept1[1] + p_g[0], sum_intercept2[1] + p_g[1]}); } mu1 = exp(sum_mutation[0] - sum_len[0]); mu2 = exp(sum_mutation[1] - sum_len[1]); if (estimate_intercept) { intercept = exp(sum_intercept[0] - sum_intercept[1]); } if (fabs(mu1 - prev_mu1) + fabs(mu2 - prev_mu2) + estimate_intercept * fabs(prev_intercept - intercept) < eps) { break; } prev_mu1 = mu1; prev_mu2 = mu2; } NumericVector result = NumericVector(3); result[0] = mu1; result[1] = mu2; result[2] = intercept; return (result); } // Should probably delete it? //' Estimate the mutation rate using EM //' //' @param mu1 Starting value for the first mutation parameter //' @param mu2 Starting value for the second mutation parameter //' @param mutation Vector of the number of mutations in a segment //' @param len Vector of the (physical) length of a segment //' @param indexes List of vector, where each vector is the indexes of the segments for an individual //' @param maxiter Maximum number of EM iterations //' @param eps The algorithm stops when the parameters change is less than eps, |prev_mu - mu| < eps //' @param prob Matrix of probabilities, where the first column is the probability of being first cousin, and the second of second cousin. //' @param estimate_intercept Whether to estimate the intercept as well, intercept is used when there's genotyping error. //' @param intercept Starting value for the intercept. //' @param stochastic If true, an incremental version is used instead. //' @return An estimate of the male mutation rate, female mutation rate and the intercept. // [[Rcpp::export]] NumericVector cpp_em(double mu1, double mu2, const IntegerVector &mutation, const IntegerVector &len, List &indexes, int maxiter, double eps, const NumericMatrix &prob, bool stochastic = false, bool estimate_intercept = false, double intercept = 0.0) { // NumericVector N_ = {3, 5, 7}; NumericVector N_ = {3, 5}; // Few tests if (prob.nrow() != indexes.size()) { // fprintf( // stdout, // "Number of rows in prob should be the same as the length of // indexes."); return NA_REAL; REprintf("Number of rows in prob should be the same as the length of " "indexes.\n"); return NA_REAL; } if (prob.ncol() != N_.size()) { REprintf("Number of cols in prob should be 2.\n"); // fprintf( // stdout, // "Number of cols in prob should be 3."); return NA_REAL; } double prev_mu1 = mu1; double prev_mu2 = mu2; int n = mutation.size(); int N_all = sum(N_); std::vector pi1(N_all, 0.5); std::vector pi2(N_all, 0.5); // std::vector outer_p(N_all, 1/(double)N_all); // double intercept = 0.0; if (estimate_intercept && intercept == 0.0) { intercept = 1e-8; } std::vector likelihood_precalc(n, 0.0); for (size_t k = 0; k < indexes.size(); k++) { IntegerVector index = indexes[k]; for (size_t j = 0; j < index.size(); j++) { double temp = lgamma(mutation[index[j]] + 1); likelihood_precalc[index[j]] = mutation[index[j]] * log(len[index[j]]) - temp; } } NumericMatrix sm1(n, N_all); NumericMatrix sm2(n, N_all); NumericMatrix sl1(n, N_all); NumericMatrix sl2(n, N_all); NumericMatrix si1(n, N_all); NumericMatrix si2(n, N_all); std::fill(sm1.begin(), sm1.end(), R_NegInf); std::fill(sm2.begin(), sm2.end(), R_NegInf); std::fill(sl1.begin(), sl1.end(), R_NegInf); std::fill(sl2.begin(), sl2.end(), R_NegInf); std::fill(si1.begin(), si1.end(), R_NegInf); std::fill(si2.begin(), si2.end(), R_NegInf); for (int i = 0; i < maxiter; i++) { // double sum_len[2] = {-INFINITY, -INFINITY}; // double sum_mutation[2] = {-INFINITY, -INFINITY}; // std::vector sum_p1(N_all, -INFINITY); // std::vector sum_p2(N_all, -INFINITY); // std::vector sum_outer_p(N_all, -INFINITY); // double sum_intercept[2] = {-INFINITY, -INFINITY}; // Calculate P(Z | Y_i) // for (size_t n_index = 0; n_index < N_.size(); n_index++) { // int N = N_[n_index]; // When stochastic // double logsumexp_buffer[4] = {0.0}; // double prev_buffer[4] = {0.0}; size_t p = indexes.size(); if (i == 1 && stochastic) { p = 1; } for (size_t k = 0; k < p; k++) { IntegerVector index = indexes[k]; if (stochastic) { index = sample(indexes.size(), 1, false, R_NilValue, false); // prev_buffer[0] = } // Calculate wia std::vector wi(N_all, 0.0); for (size_t j = 0; j < index.size(); j++) { double l = len[index[j]]; size_t m_all = 0; for (int N : N_) { for (size_t m = 0; m < N; m++) { const int general_N = N + 3; const double par[2] = { (m + 1) * mu1 + (general_N - (m + 1)) * mu2 + intercept, (m + 3) * mu1 + (general_N - (m + 3)) * mu2 + intercept}; wi[m_all] += logsumexp({mutation[index[j]] * log(par[0]) - l * par[0] + likelihood_precalc[index[j]], mutation[index[j]] * log(par[1]) - l * par[1] + likelihood_precalc[index[j]]}); m_all++; } } } size_t m_all = 0; size_t n_counter = 0; for (int N : N_) { for (size_t m = 0; m < N; m++) { // Change 0.5 to prob for N=3, 5 etc // wi[m] += log(0.5) + R::dbinom(m, N-1, 0.5, 1); // if (estimate_outer_p) { // wi[m_all] += log(outer_p[m_all]); // } // else { wi[m_all] += log(prob(k, n_counter)) + R::dbinom(m, N - 1, 0.5, 1); // } m_all++; } n_counter++; } double normalize = logsumexp(wi); for (size_t m = 0; m < N_all; m++) { wi[m] -= normalize; } for (size_t j = 0; j < index.size(); j++) { double l = len[index[j]]; double log_mutation = log(mutation[index[j]]); double log_len = log(l); double a[N_all]; double b[N_all]; { size_t m_all = 0; for (int N : N_) { const int general_N = N + 3; for (size_t m = 0; m < N; m++) { const double par[2] = { (m + 1) * mu1 + (general_N - (m + 1)) * mu2 + intercept, (m + 3) * mu1 + (general_N - (m + 3)) * mu2 + intercept}; const double log_par[2] = {log(par[0]), log(par[1])}; const double name[2] = {-log_par[0] + log((m + 1) * mu1), -log_par[1] + log((m + 3) * mu1)}; a[m_all] = mutation[index[j]] * log_par[0] - l * par[0] + likelihood_precalc[index[j]] + log(pi1[m_all]); b[m_all] = mutation[index[j]] * log_par[1] - l * par[1] + likelihood_precalc[index[j]] + log(pi2[m_all]); double normalize = logsumexp({a[m_all], b[m_all]}); a[m_all] = a[m_all] - normalize; b[m_all] = b[m_all] - normalize; double temp_wi = logsumexp({a[m_all] + log_mutation + name[0], b[m_all] + log_mutation + name[1]}) + wi[m_all]; sm1(index[j], m_all) = temp_wi; const double name2[2] = { -log_par[0] + log((general_N - (m + 1)) * mu2), -log_par[1] + log((general_N - (m + 3)) * mu2)}; temp_wi = logsumexp({a[m_all] + log_mutation + name2[0], b[m_all] + log_mutation + name2[1]}) + wi[m_all]; // sum_mutation[1] = logsumexp(sum_mutation[1], temp_wi); // sm2[index[j]] = temp_wi; sm2(index[j], m_all) = temp_wi; temp_wi = logsumexp({a[m_all] + log_len + log((m + 1)), b[m_all] + log_len + log((m + 3))}) + wi[m_all]; // sum_len[0] = logsumexp(sum_len[0], temp_wi); // sl1[index[j]] = temp_wi; sl1(index[j], m_all) = temp_wi; temp_wi = logsumexp({a[m_all] + log_len + log(general_N - (m + 1)), b[m_all] + log_len + log(general_N - (m + 3))}) + wi[m_all]; // sum_len[1] = logsumexp(sum_len[1], temp_wi); // sl2[index[j]] = temp_wi; sl2(index[j], m_all) = temp_wi; temp_wi = logsumexp( {a[m_all] + log_mutation - log_par[0] + log(intercept), b[m_all] + log_mutation - log_par[1] + log(intercept)}) + wi[m_all]; // sum_intercept[0] = logsumexp(sum_intercept[0], temp_wi); // si1[index[j]] = temp_wi; si1(index[j], m_all) = temp_wi; temp_wi = logsumexp({a[m_all] + log_len, b[m_all] + log_len}) + wi[m_all]; // sum_intercept[1] = logsumexp(sum_intercept[1], temp_wi); // si2[index[j]] = temp_wi; si2(index[j], m_all) = temp_wi; m_all++; } } } // for (size_t m = 0; m < N_all; m++) { // sum_p1[m] = logsumexp({sum_p1[m], a[m]}); // sum_p2[m] = logsumexp({sum_p2[m], b[m]}); // } // for (size_t m = 0; m < N_all; m++) { // sum_outer_p[m] = logsumexp({sum_outer_p[m], wi[m]}); // } } } // mu1 = exp(sum_mutation[0] - sum_len[0]); // mu2 = exp(sum_mutation[1] - sum_len[1]); mu1 = exp(logsumexp(sm1) - logsumexp(sl1)); mu2 = exp(logsumexp(sm2) - logsumexp(sl2)); // if(!stochastic) { // mu1 = exp(logsumexp(sm1) - logsumexp(sl1)); // mu2 = exp(logsumexp(sm2) - logsumexp(sl2)); // } // else { // if (i == 0) { // First iteration // logsumexp_buffer[0] = logsumexp(sm1); // logsumexp_buffer[1] = logsumexp(sl1); // logsumexp_buffer[2] = logsumexp(sm2); // logsumexp_buffer[3] = logsumexp(sl2); // } // } // if (estimate_inner_pi) { // for (size_t m = 0; m < N_all; m++) { // pi1[m] = exp(sum_p1[m]) / n; // pi2[m] = exp(sum_p2[m]) / n; // } // } if (estimate_intercept) { // intercept = exp(sum_intercept[0] - sum_intercept[1]); intercept = exp(logsumexp(si1) - logsumexp(si2)); // fprintf(stderr, "Intercept : %f\n", intercept * 1e9); } // if (estimate_outer_p) { // for (size_t m = 0; m < N_all; m++) { // outer_p[m] = exp(sum_outer_p[m]) / n; // } // } if (fabs(mu1 - prev_mu1) + fabs(mu2 - prev_mu2) < eps) { break; } prev_mu1 = mu1; prev_mu2 = mu2; } // NumericVector result = NumericVector(3+outer_p.size()); NumericVector result = NumericVector(3); result[0] = mu1; result[1] = mu2; result[2] = intercept; // for (size_t i = 0; i < outer_p.size(); i++) { // result[i+3] = outer_p[i]; // } // if (estimate_inner_pi) { // fprintf(stderr, "Pi:\n"); // for (size_t m = 0; m < N_all; m++) { // fprintf(stderr, "%d: (%f, %f) \n", m, pi1[m], pi2[m]); // } // fprintf(stderr, "\n"); // } // if (estimate_outer_p) { // fprintf(stderr, "Pi:\n"); // for (size_t m = 0; m < N_all; m++) { // fprintf(stderr, "%d: %f \n", m, outer_p[m]); // } // fprintf(stderr, "\n"); // } // if (estimate_intercept) { // fprintf(stderr, "Intercept: %f\n", intercept * 1e9); // } return (result); }100-1000 #include #include #include "connection.h" #include "fixed_width_index_connection.h" #include "r_utils.h" #include "unicode_fopen.h" #include #include #include // std::async, std::future #include #ifdef VROOM_LOG #include "spdlog/sinks/basic_file_sink.h" // support for basic file logging #include "spdlog/spdlog.h" #endif using namespace vroom; fixed_width_index_connection::fixed_width_index_connection( SEXP in, std::vector col_starts, std::vector col_ends, bool trim_ws, const size_t skip, const char* comment, const bool skip_empty_rows, const size_t n_max, const bool progress, const size_t chunk_size) { col_starts_ = std::move(col_starts); col_ends_ = std::move(col_ends); trim_ws_ = trim_ws; filename_ = cpp11::as_cpp(cpp11::package("vroom")["vroom_tempfile"]()); std::FILE* out = unicode_fopen(filename_.c_str(), "wb"); auto con = R_GetConnection(in); bool should_open = !is_open(in); if (should_open) { cpp11::package("base")["open"](in, "rb"); } std::array, 2> buf = { std::vector(chunk_size), std::vector(chunk_size)}; // A buf index that alternates between 0,1 auto i = 0; newlines_.reserve(128); size_t sz = R_ReadConnection(con, buf[i].data(), chunk_size - 1); buf[i][sz] = '\0'; // Parse header size_t start = find_first_line( buf[i], skip, comment, skip_empty_rows, /* embedded_nl */ false, /* quote */ '\0'); // Check for windows newlines size_t first_nl; newline_type nl_type; std::tie(first_nl, nl_type) = find_next_newline( buf[i], start, comment, skip_empty_rows, false, /* quote */ '\0'); std::unique_ptr pb = nullptr; if (progress) { pb = std::unique_ptr( new RProgress::RProgress(get_pb_format("connection"), 1e12)); pb->tick(start); } size_t total_read = 0; std::future parse_fut; std::future write_fut; size_t lines_read = 0; size_t lines_remaining = n_max; std::unique_ptr empty_pb = nullptr; if (n_max > 0) { newlines_.push_back(start - 1); } while (sz > 0) { if (parse_fut.valid()) { parse_fut.wait(); } if (lines_read >= lines_remaining) { break; } lines_remaining -= lines_read; parse_fut = std::async([&, i, start, total_read, sz] { lines_read = index_region( buf[i], newlines_, start, sz, total_read, comment, skip_empty_rows, lines_remaining, empty_pb); }); if (write_fut.valid()) { write_fut.wait(); } write_fut = std::async( [&, i, sz] { std::fwrite(buf[i].data(), sizeof(char), sz, out); }); if (progress) { pb->tick(sz); } total_read += sz; i = (i + 1) % 2; sz = R_ReadConnection(con, buf[i].data(), chunk_size - 1); if (sz > 0) { buf[i][sz] = '\0'; } start = 0; SPDLOG_DEBUG("first_nl_loc: {0} size: {1}", start, sz); } if (parse_fut.valid()) { parse_fut.wait(); } if (write_fut.valid()) { write_fut.wait(); } std::fclose(out); if (progress) { pb->update(1); } /* raw connections are always created as open, but we should close them */ bool should_close = should_open || Rf_inherits(in, "rawConnection"); if (should_close) { cpp11::package("base")["close"](in); } std::error_code error; if (n_max != 0) { mmap_ = make_mmap_source(filename_.c_str(), error); if (error) { cpp11::stop("%s", error.message().c_str()); } } #ifdef VROOM_LOG #if SPDLOG_ACTIVE_LEVEL <= SPD_LOG_LEVEL_DEBUG auto log = spdlog::basic_logger_mt( "basic_logger", "logs/fixed_width_index_connection.idx", true); for (auto& v : newlines_) { SPDLOG_LOGGER_DEBUG(log, "{}", v); } SPDLOG_LOGGER_DEBUG(log, "end of idx {0:x}", (size_t)&newlines_); spdlog::drop("basic_logger"); #endif #endif } #include "stdafx.h" #include #include "resource.h" /*** FUNCTION HEADER ********************************************************* * LRESULT CALLBACK PreviewWindowProc(HWND hwnd,UINT msg,WPARAM wParam,LPARAM lParam) * * DESCRIPTION: Handles messages for the preview window. * [REVISIONS] * 6/24/98 InitialVersion * \******************************************************************************/ LRESULT CALLBACK PreviewWindowProc(HWND hwnd,UINT msg,WPARAM wParam,LPARAM lParam) { HDC hdc,hdcImage = NULL; HBITMAP hbm = NULL; static int f = 0; switch (msg) { // When we get a timer message, we just draw // a bitmap in the preview window case WM_TIMER: { // Get dimensions of the window RECT rc; GetWindowRect(hwnd,&rc); int cx=rc.right-rc.left; int cy=rc.bottom-rc.top; // Make sure bitmap is loaded if(!hbm) hbm = (HBITMAP)LoadImage( GetModuleHandle(NULL), MAKEINTRESOURCE(IDB_PREVIEW), IMAGE_BITMAP, 0, 0, LR_CREATEDIBSECTION ); if(!hbm) break; // Make sure bitmap is selected into a memory context if(!hdcImage) { hdcImage = CreateCompatibleDC(NULL); SelectObject(hdcImage, hbm); } if(!hdcImage) break; // Set bitmap dimensions (You need to set these // by hand, I have yet to find a convenient way // to get the dimensions of a bitmap resource!) // Note: 152x112 is the size of the preview window int bw = 152, bh = 112; int x,y; // Figure out which part of the bitmap to show switch(f%4) { case 0: x = 0; y = 0; break; case 1: x = bw; y = 0; break; case 2: x = 0; y = bh; break; case 3: x = bw; y = bh; break; } f++; // Blit the bitmap to the screen hdc = GetDC(hwnd); if(hdc) StretchBlt(hdc, 0, 0, cx, cy, hdcImage, x, y, bw, bh, SRCCOPY); ReleaseDC(hwnd,hdc); } break; // The destroy message comes when the preview // window is getting shut down. case WM_DESTROY: PostQuitMessage(0); if(hdcImage) { DeleteDC(hdcImage); DeleteObject(hbm); } break; } // Handle all other messages... return DefWindowProc(hwnd,msg,wParam,lParam); } /*** FUNCTION HEADER ********************************************************* void runminidemo(HINSTANCE hInstance,HWND hparent) * * DESCRIPTION: Operates the screen saver inside a teeny tiny window provided by the main screen saver dialog. Since a DirectX app has to worry about conflicting video modes, we are just going to show a bitmap here. * * [REVISIONS] * 6/12/98 InitialVersion * \******************************************************************************/ void runminidemo(HINSTANCE hInstance,HWND hparent) { RECT rc; HWND hpreviewwnd; int cx,cy; WNDCLASS wc; // Set up a windows class for the preview window wc.style=CS_HREDRAW | CS_VREDRAW; wc.lpfnWndProc=PreviewWindowProc; wc.cbClsExtra=0; wc.cbWndExtra=0; wc.hInstance=hInstance; wc.hIcon=NULL; wc.hCursor=NULL; wc.hbrBackground=NULL;//(HBRUSH)GetStockObject(GRAY_BRUSH); wc.lpszMenuName=NULL; wc.lpszClassName="PreviewScrClass"; RegisterClass(&wc); // Create a child window GetWindowRect(hparent,&rc); cx=rc.right-rc.left; cy=rc.bottom-rc.top; hpreviewwnd=CreateWindowEx( 0, "PreviewScrClass", "SaverPreview", WS_CHILD|WS_VISIBLE, 0, 0, cx, cy, hparent, NULL, hInstance, NULL ); if(!hpreviewwnd) return; SetTimer(hpreviewwnd,1,250,NULL); // Pump the message loop MSG msg; while (GetMessage(&msg,NULL,0,0)){ TranslateMessage(&msg); DispatchMessage(&msg); } KillTimer(hpreviewwnd,1); } // Copyright 2013 The Flutter 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 "flutter/shell/platform/common/json_message_codec.h" #include "flutter/shell/platform/embedder/embedder.h" #include "flutter/shell/platform/embedder/test_utils/key_codes.h" #include "flutter/shell/platform/windows/flutter_windows_engine.h" #include "flutter/shell/platform/windows/flutter_windows_view.h" #include "flutter/shell/platform/windows/keyboard_key_channel_handler.h" #include "flutter/shell/platform/windows/keyboard_key_embedder_handler.h" #include "flutter/shell/platform/windows/keyboard_key_handler.h" #include "flutter/shell/platform/windows/keyboard_manager_win32.h" #include "flutter/shell/platform/windows/testing/engine_modifier.h" #include "flutter/shell/platform/windows/testing/mock_window_binding_handler.h" #include "flutter/shell/platform/windows/testing/test_keyboard.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "rapidjson/stringbuffer.h" #include "rapidjson/writer.h" #include #include #include using testing::_; using testing::Invoke; using testing::Return; using namespace ::flutter::testing::keycodes; namespace flutter { namespace testing { namespace { constexpr SHORT kStateMaskToggled = 0x01; constexpr SHORT kStateMaskPressed = 0x80; typedef uint32_t (*MapVkToCharHandler)(uint32_t virtual_key); uint32_t LayoutDefault(uint32_t virtual_key) { return MapVirtualKey(virtual_key, MAPVK_VK_TO_CHAR); } uint32_t LayoutFrench(uint32_t virtual_key) { switch (virtual_key) { case 0xDD: return 0x8000005E; default: return MapVirtualKey(virtual_key, MAPVK_VK_TO_CHAR); } } class TestKeyboardManagerWin32 : public KeyboardManagerWin32 { public: explicit TestKeyboardManagerWin32(WindowDelegate* delegate) : KeyboardManagerWin32(delegate) {} bool DuringRedispatch() { return during_redispatch_; } protected: void RedispatchEvent(std::unique_ptr event) override { assert(!during_redispatch_); during_redispatch_ = true; KeyboardManagerWin32::RedispatchEvent(std::move(event)); during_redispatch_ = false; } private: bool during_redispatch_ = false; }; struct KeyStateChange { uint32_t key; bool pressed; bool toggled_on; }; struct KeyboardChange { // The constructors are intentionally for implicit conversion. KeyboardChange(Win32Message message) : type(kMessage) { content.message = message; } KeyboardChange(KeyStateChange change) : type(kKeyStateChange) { content.key_state_change = change; } enum Type { kMessage, kKeyStateChange, } type; union { Win32Message message; KeyStateChange key_state_change; } content; }; class TestKeystate { public: void Set(uint32_t virtual_key, bool pressed, bool toggled_on = false) { state_[virtual_key] = (pressed ? kStateMaskPressed : 0) | (toggled_on ? kStateMaskToggled : 0); } SHORT Get(uint32_t virtual_key) { return state_[virtual_key]; } private: std::map state_; }; class MockKeyboardManagerWin32Delegate : public KeyboardManagerWin32::WindowDelegate, protected MockMessageQueue { public: MockKeyboardManagerWin32Delegate(WindowBindingHandlerDelegate* view) : view_(view), map_vk_to_char_(LayoutDefault) { keyboard_manager_ = std::make_unique(this); } virtual ~MockKeyboardManagerWin32Delegate() {} // |KeyboardManagerWin32::WindowDelegate| void OnKey(int key, int scancode, int action, char32_t character, bool extended, bool was_down, KeyEventCallback callback) override { view_->OnKey(key, scancode, action, character, extended, was_down, callback); } // |KeyboardManagerWin32::WindowDelegate| void OnText(const std::u16string& text) override { view_->OnText(text); } void SetLayout(MapVkToCharHandler map_vk_to_char) { map_vk_to_char_ = map_vk_to_char == nullptr ? LayoutDefault : map_vk_to_char; } SHORT GetKeyState(int virtual_key) { return key_state_.Get(virtual_key); } void InjectKeyboardChanges(std::vector changes) { for (const KeyboardChange& change : changes) { switch (change.type) { case KeyboardChange::kMessage: PushBack(&change.content.message); break; default: break; } } for (const KeyboardChange& change : changes) { switch (change.type) { case KeyboardChange::kMessage: DispatchFront(); break; case KeyboardChange::kKeyStateChange: { const KeyStateChange& state_change = change.content.key_state_change; key_state_.Set(state_change.key, state_change.pressed, state_change.toggled_on); break; } default: assert(false); } } } std::list& RedispatchedMessages() { return redispatched_messages_; } protected: BOOL Win32PeekMessage(LPMSG lpMsg, UINT wMsgFilterMin, UINT wMsgFilterMax, UINT wRemoveMsg) override { return MockMessageQueue::Win32PeekMessage(lpMsg, wMsgFilterMin, wMsgFilterMax, wRemoveMsg); } uint32_t Win32MapVkToChar(uint32_t virtual_key) override { return map_vk_to_char_(virtual_key); } // This method is called for each message injected by test cases with // `tester.InjectMessages`. LRESULT Win32SendMessage(UINT const message, WPARAM const wparam, LPARAM const lparam) override { return keyboard_manager_->HandleMessage(message, wparam, lparam) ? 0 : kWmResultDefault; } // This method is called when the keyboard manager redispatches messages // or dispatches CtrlLeft up for AltGr. UINT Win32DispatchMessage(UINT Msg, WPARAM wParam, LPARAM lParam) override { bool handled = keyboard_manager_->HandleMessage(Msg, wParam, lParam); if (keyboard_manager_->DuringRedispatch()) { redispatched_messages_.push_back(Win32Message{ .message = Msg, .wParam = wParam, .lParam = lParam, }); EXPECT_FALSE(handled); } return 0; } private: WindowBindingHandlerDelegate* view_; std::unique_ptr keyboard_manager_; MapVkToCharHandler map_vk_to_char_; TestKeystate key_state_; std::list redispatched_messages_; }; // A FlutterWindowsView that overrides the RegisterKeyboardHandlers function // to register the keyboard hook handlers that can be spied upon. class TestFlutterWindowsView : public FlutterWindowsView { public: typedef std::function U16StringHandler; TestFlutterWindowsView( U16StringHandler on_text, KeyboardKeyEmbedderHandler::GetKeyStateHandler get_keyboard_state) // The WindowBindingHandler is used for window size and such, and doesn't // affect keyboard. : FlutterWindowsView( std::make_unique<::testing::NiceMock>()), get_keyboard_state_(std::move(get_keyboard_state)), on_text_(std::move(on_text)) {} void OnText(const std::u16string& text) override { on_text_(text); } void HandleMessage(const char* channel, const char* method, const char* args) { rapidjson::Document args_doc; args_doc.Parse(args); assert(!args_doc.HasParseError()); rapidjson::Document message_doc(rapidjson::kObjectType); auto& allocator = message_doc.GetAllocator(); message_doc.AddMember("method", rapidjson::Value(method, allocator), allocator); message_doc.AddMember("args", args_doc, allocator); rapidjson::StringBuffer buffer; rapidjson::Writer writer(buffer); message_doc.Accept(writer); std::unique_ptr> data = JsonMessageCodec::GetInstance().EncodeMessage(message_doc); FlutterPlatformMessageResponseHandle response_handle; const FlutterPlatformMessage message = { sizeof(FlutterPlatformMessage), // struct_size channel, // channel data->data(), // message data->size(), // message_size &response_handle, // response_handle }; GetEngine()->HandlePlatformMessage(&message); } protected: std::unique_ptr CreateKeyboardKeyHandler( BinaryMessenger* messenger, KeyboardKeyEmbedderHandler::GetKeyStateHandler get_key_state) override { return FlutterWindowsView::CreateKeyboardKeyHandler( messenger, [this](int virtual_key) { return get_keyboard_state_(virtual_key); }); } private: U16StringHandler on_text_; KeyboardKeyEmbedderHandler::GetKeyStateHandler get_keyboard_state_; }; typedef struct { enum { kKeyCallOnKey, kKeyCallOnText, kKeyCallTextMethodCall, } type; // Only one of the following fields should be assigned. FlutterKeyEvent key_event; // For kKeyCallOnKey std::u16string text; // For kKeyCallOnText std::string text_method_call; // For kKeyCallTextMethodCall } KeyCall; static std::vector key_calls; void clear_key_calls() { for (KeyCall& key_call : key_calls) { if (key_call.type == KeyCall::kKeyCallOnKey && key_call.key_event.character != nullptr) { delete[] key_call.key_event.character; } } key_calls.clear(); } class KeyboardTester { public: using ResponseHandler = std::function; explicit KeyboardTester() : callback_handler_(RespondValue(false)) { view_ = std::make_unique( [](const std::u16string& text) { key_calls.push_back(KeyCall{ .type = KeyCall::kKeyCallOnText, .text = text, }); }, [this](int virtual_key) -> SHORT { // `window_` is not initialized yet when this callback is first // called. return window_ ? window_->GetKeyState(virtual_key) : 0; }); view_->SetEngine(GetTestEngine( [&callback_handler = callback_handler_]( const FlutterKeyEvent* event, MockKeyResponseController::ResponseCallback callback) { FlutterKeyEvent clone_event = *event; clone_event.character = event->character == nullptr ? nullptr : clone_string(event->character); key_calls.push_back(KeyCall{ .type = KeyCall::kKeyCallOnKey, .key_event = clone_event, }); callback_handler(event, callback); })); window_ = std::make_unique(view_.get()); } TestFlutterWindowsView& GetView() { return *view_; } MockKeyboardManagerWin32Delegate& GetWindow() { return *window_; } // Set all events to be handled (true) or unhandled (false). void Responding(bool response) { callback_handler_ = RespondValue(response); } // Manually handle event callback of the onKeyData embedder API. // // On every onKeyData call, the |handler| will be invoked with the target // key data and the result callback. Immediately calling the callback with // a boolean is equivalent to setting |Responding| with the boolean. However, // |LateResponding| allows storing the callback to call later. void LateResponding( MockKeyResponseController::EmbedderCallbackHandler handler) { callback_handler_ = std::move(handler); } void SetLayout(MapVkToCharHandler layout) { window_->SetLayout(layout); } void InjectKeyboardChanges(std::vector changes) { assert(window_ != nullptr); window_->InjectKeyboardChanges(changes); } // Get the number of redispatched messages since the last clear, then clear // the counter. size_t RedispatchedMessageCountAndClear() { auto& messages = window_->RedispatchedMessages(); size_t count = messages.size(); messages.clear(); return count; } private: std::unique_ptr view_; std::unique_ptr window_; MockKeyResponseController::EmbedderCallbackHandler callback_handler_; // Returns an engine instance configured with dummy project path values, and // overridden methods for sending platform messages, so that the engine can // respond as if the framework were connected. static std::unique_ptr GetTestEngine( MockKeyResponseController::EmbedderCallbackHandler embedder_callback_handler) { FlutterDesktopEngineProperties properties = {}; properties.assets_path = L"C:\\foo\\flutter_assets"; properties.icu_data_path = L"C:\\foo\\icudtl.dat"; properties.aot_library_path = L"C:\\foo\\aot.so"; FlutterProjectBundle project(properties); auto engine = std::make_unique(project); EngineModifier modifier(engine.get()); auto key_response_controller = std::make_shared(); key_response_controller->SetEmbedderResponse( std::move(embedder_callback_handler)); key_response_controller->SetTextInputResponse( [](std::unique_ptr document) { rapidjson::StringBuffer buffer; rapidjson::Writer writer(buffer); document->Accept(writer); key_calls.push_back(KeyCall{ .type = KeyCall::kKeyCallTextMethodCall, .text_method_call = buffer.GetString(), }); }); MockEmbedderApiForKeyboard(modifier, key_response_controller); engine->RunWithEntrypoint(nullptr); return engine; } static MockKeyResponseController::EmbedderCallbackHandler RespondValue( bool value) { return [value](const FlutterKeyEvent* event, MockKeyResponseController::ResponseCallback callback) { callback(value); }; } }; constexpr uint64_t kScanCodeBackquote = 0x29; constexpr uint64_t kScanCodeKeyA = 0x1e; constexpr uint64_t kScanCodeKeyB = 0x30; constexpr uint64_t kScanCodeKeyE = 0x12; constexpr uint64_t kScanCodeKeyF = 0x21; constexpr uint64_t kScanCodeKeyO = 0x18; constexpr uint64_t kScanCodeKeyQ = 0x10; constexpr uint64_t kScanCodeKeyW = 0x11; constexpr uint64_t kScanCodeDigit1 = 0x02; constexpr uint64_t kScanCodeDigit6 = 0x07; // constexpr uint64_t kScanCodeNumpad1 = 0x4f; // constexpr uint64_t kScanCodeNumLock = 0x45; constexpr uint64_t kScanCodeControl = 0x1d; constexpr uint64_t kScanCodeMetaLeft = 0x5b; constexpr uint64_t kScanCodeMetaRight = 0x5c; constexpr uint64_t kScanCodeAlt = 0x38; constexpr uint64_t kScanCodeShiftLeft = 0x2a; constexpr uint64_t kScanCodeShiftRight = 0x36; constexpr uint64_t kScanCodeBracketLeft = 0x1a; constexpr uint64_t kScanCodeArrowLeft = 0x4b; constexpr uint64_t kScanCodeEnter = 0x1c; constexpr uint64_t kScanCodeBackspace = 0x0e; constexpr uint64_t kVirtualDigit1 = 0x31; constexpr uint64_t kVirtualKeyA = 0x41; constexpr uint64_t kVirtualKeyB = 0x42; constexpr uint64_t kVirtualKeyE = 0x45; constexpr uint64_t kVirtualKeyF = 0x46; constexpr uint64_t kVirtualKeyO = 0x4f; constexpr uint64_t kVirtualKeyQ = 0x51; constexpr uint64_t kVirtualKeyW = 0x57; constexpr bool kSynthesized = true; constexpr bool kNotSynthesized = false; } // namespace // Define compound `expect` in macros. If they're defined in functions, the // stacktrace wouldn't print where the function is called in the unit tests. #define EXPECT_CALL_IS_EVENT(_key_call, ...) \ EXPECT_EQ(_key_call.type, KeyCall::kKeyCallOnKey); \ EXPECT_EVENT_EQUALS(_key_call.key_event, __VA_ARGS__); #define EXPECT_CALL_IS_TEXT(_key_call, u16_string) \ EXPECT_EQ(_key_call.type, KeyCall::kKeyCallOnText); \ EXPECT_EQ(_key_call.text, u16_string); #define EXPECT_CALL_IS_TEXT_METHOD_CALL(_key_call, json_string) \ EXPECT_EQ(_key_call.type, KeyCall::kKeyCallTextMethodCall); \ EXPECT_STREQ(_key_call.text_method_call.c_str(), json_string); TEST(KeyboardTest, LowerCaseAHandled) { KeyboardTester tester; tester.Responding(true); // US Keyboard layout // Press A tester.InjectKeyboardChanges(std::vector{ WmKeyDownInfo{kVirtualKeyA, kScanCodeKeyA, kNotExtended, kWasUp}.Build( kWmResultZero), WmCharInfo{'a', kScanCodeKeyA, kNotExtended, kWasUp}.Build( kWmResultZero)}); EXPECT_EQ(key_calls.size(), 1); EXPECT_CALL_IS_EVENT(key_calls[0], kFlutterKeyEventTypeDown, kPhysicalKeyA, kLogicalKeyA, "a", kNotSynthesized); clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 0); // Release A tester.InjectKeyboardChanges(std::vector{ WmKeyUpInfo{kVirtualKeyA, kScanCodeKeyA, kNotExtended}.Build( kWmResultZero)}); EXPECT_EQ(key_calls.size(), 1); EXPECT_CALL_IS_EVENT(key_calls[0], kFlutterKeyEventTypeUp, kPhysicalKeyA, kLogicalKeyA, "", kNotSynthesized); clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 0); } TEST(KeyboardTest, LowerCaseAUnhandled) { KeyboardTester tester; tester.Responding(false); // US Keyboard layout // Press A tester.InjectKeyboardChanges(std::vector{ WmKeyDownInfo{kVirtualKeyA, kScanCodeKeyA, kNotExtended, kWasUp}.Build( kWmResultZero), WmCharInfo{'a', kScanCodeKeyA, kNotExtended, kWasUp}.Build( kWmResultZero)}); EXPECT_EQ(key_calls.size(), 2); EXPECT_CALL_IS_EVENT(key_calls[0], kFlutterKeyEventTypeDown, kPhysicalKeyA, kLogicalKeyA, "a", kNotSynthesized); EXPECT_CALL_IS_TEXT(key_calls[1], u"a"); clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 2); // Release A tester.InjectKeyboardChanges(std::vector{ WmKeyUpInfo{kVirtualKeyA, kScanCodeKeyA, kNotExtended}.Build( kWmResultZero)}); EXPECT_EQ(key_calls.size(), 1); EXPECT_CALL_IS_EVENT(key_calls[0], kFlutterKeyEventTypeUp, kPhysicalKeyA, kLogicalKeyA, "", kNotSynthesized); clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 1); } TEST(KeyboardTest, ArrowLeftHandled) { KeyboardTester tester; tester.Responding(true); // US Keyboard layout // Press ArrowLeft tester.InjectKeyboardChanges(std::vector{ WmKeyDownInfo{VK_LEFT, kScanCodeArrowLeft, kExtended, kWasUp}.Build( kWmResultZero)}); EXPECT_EQ(key_calls.size(), 1); EXPECT_CALL_IS_EVENT(key_calls[0], kFlutterKeyEventTypeDown, kPhysicalArrowLeft, kLogicalArrowLeft, "", kNotSynthesized); clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 0); // Release ArrowLeft tester.InjectKeyboardChanges(std::vector{ WmKeyUpInfo{VK_LEFT, kScanCodeArrowLeft, kExtended}.Build( kWmResultZero)}); EXPECT_EQ(key_calls.size(), 1); EXPECT_CALL_IS_EVENT(key_calls[0], kFlutterKeyEventTypeUp, kPhysicalArrowLeft, kLogicalArrowLeft, "", kNotSynthesized); clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 0); } TEST(KeyboardTest, ArrowLeftUnhandled) { KeyboardTester tester; tester.Responding(false); // US Keyboard layout // Press ArrowLeft tester.InjectKeyboardChanges(std::vector{ WmKeyDownInfo{VK_LEFT, kScanCodeArrowLeft, kExtended, kWasUp}.Build( kWmResultZero)}); EXPECT_EQ(key_calls.size(), 1); EXPECT_CALL_IS_EVENT(key_calls[0], kFlutterKeyEventTypeDown, kPhysicalArrowLeft, kLogicalArrowLeft, "", kNotSynthesized); clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 1); // Release ArrowLeft tester.InjectKeyboardChanges(std::vector{ WmKeyUpInfo{VK_LEFT, kScanCodeArrowLeft, kExtended}.Build( kWmResultZero)}); EXPECT_EQ(key_calls.size(), 1); EXPECT_CALL_IS_EVENT(key_calls[0], kFlutterKeyEventTypeUp, kPhysicalArrowLeft, kLogicalArrowLeft, "", kNotSynthesized); clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 1); } TEST(KeyboardTest, ShiftLeftUnhandled) { KeyboardTester tester; tester.Responding(false); // US Keyboard layout // Press ShiftLeft tester.InjectKeyboardChanges(std::vector{ KeyStateChange{VK_LSHIFT, true, false}, WmKeyDownInfo{VK_SHIFT, kScanCodeShiftLeft, kNotExtended, kWasUp}.Build( kWmResultZero)}); EXPECT_EQ(key_calls.size(), 1); EXPECT_CALL_IS_EVENT(key_calls[0], kFlutterKeyEventTypeDown, kPhysicalShiftLeft, kLogicalShiftLeft, "", kNotSynthesized); clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 1); // Release ShiftLeft tester.InjectKeyboardChanges(std::vector{ KeyStateChange{VK_LSHIFT, false, true}, WmKeyUpInfo{VK_SHIFT, kScanCodeShiftLeft, kNotExtended}.Build( kWmResultZero)}); EXPECT_EQ(key_calls.size(), 1); EXPECT_CALL_IS_EVENT(key_calls[0], kFlutterKeyEventTypeUp, kPhysicalShiftLeft, kLogicalShiftLeft, "", kNotSynthesized); clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 1); } TEST(KeyboardTest, ShiftRightUnhandled) { KeyboardTester tester; tester.Responding(false); // US Keyboard layout // Press ShiftRight tester.InjectKeyboardChanges(std::vector{ KeyStateChange{VK_RSHIFT, true, false}, WmKeyDownInfo{VK_SHIFT, kScanCodeShiftRight, kNotExtended, kWasUp}.Build( kWmResultZero)}); EXPECT_EQ(key_calls.size(), 1); EXPECT_CALL_IS_EVENT(key_calls[0], kFlutterKeyEventTypeDown, kPhysicalShiftRight, kLogicalShiftRight, "", kNotSynthesized); clear_key_calls(); // ShiftRight down messages are never redispatched. // See |IsKeyDownShiftRight|. EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 0); // Release ShiftRight tester.InjectKeyboardChanges(std::vector{ KeyStateChange{VK_RSHIFT, false, true}, WmKeyUpInfo{VK_SHIFT, kScanCodeShiftRight, kNotExtended}.Build( kWmResultZero)}); EXPECT_EQ(key_calls.size(), 1); EXPECT_CALL_IS_EVENT(key_calls[0], kFlutterKeyEventTypeUp, kPhysicalShiftRight, kLogicalShiftRight, "", kNotSynthesized); clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 1); } TEST(KeyboardTest, CtrlLeftUnhandled) { KeyboardTester tester; tester.Responding(false); // US Keyboard layout // Press CtrlLeft tester.InjectKeyboardChanges(std::vector{ KeyStateChange{VK_LCONTROL, true, false}, WmKeyDownInfo{VK_CONTROL, kScanCodeControl, kNotExtended, kWasUp}.Build( kWmResultZero)}); EXPECT_EQ(key_calls.size(), 1); EXPECT_CALL_IS_EVENT(key_calls[0], kFlutterKeyEventTypeDown, kPhysicalControlLeft, kLogicalControlLeft, "", kNotSynthesized); clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 1); // Release CtrlLeft tester.InjectKeyboardChanges(std::vector{ KeyStateChange{VK_LCONTROL, false, true}, WmKeyUpInfo{VK_SHIFT, kScanCodeControl, kNotExtended}.Build( kWmResultZero)}); EXPECT_EQ(key_calls.size(), 1); EXPECT_CALL_IS_EVENT(key_calls[0], kFlutterKeyEventTypeUp, kPhysicalControlLeft, kLogicalControlLeft, "", kNotSynthesized); clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 1); } TEST(KeyboardTest, CtrlRightUnhandled) { KeyboardTester tester; tester.Responding(false); // US Keyboard layout // Press CtrlRight tester.InjectKeyboardChanges(std::vector{ KeyStateChange{VK_RCONTROL, true, false}, WmKeyDownInfo{VK_CONTROL, kScanCodeControl, kExtended, kWasUp}.Build( kWmResultZero)}); EXPECT_EQ(key_calls.size(), 1); EXPECT_CALL_IS_EVENT(key_calls[0], kFlutterKeyEventTypeDown, kPhysicalControlRight, kLogicalControlRight, "", kNotSynthesized); clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 1); // Release CtrlRight tester.InjectKeyboardChanges(std::vector{ KeyStateChange{VK_RCONTROL, false, true}, WmKeyUpInfo{VK_CONTROL, kScanCodeControl, kExtended}.Build( kWmResultZero)}); EXPECT_EQ(key_calls.size(), 1); EXPECT_CALL_IS_EVENT(key_calls[0], kFlutterKeyEventTypeUp, kPhysicalControlRight, kLogicalControlRight, "", kNotSynthesized); clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 1); } TEST(KeyboardTest, AltLeftUnhandled) { KeyboardTester tester; tester.Responding(false); // US Keyboard layout // Press AltLeft. AltLeft is a SysKeyDown event. tester.InjectKeyboardChanges(std::vector{ KeyStateChange{VK_LMENU, true, false}, WmSysKeyDownInfo{VK_MENU, kScanCodeAlt, kNotExtended, kWasUp}.Build( kWmResultDefault)}); // Always pass to the default WndProc. EXPECT_EQ(key_calls.size(), 1); EXPECT_CALL_IS_EVENT(key_calls[0], kFlutterKeyEventTypeDown, kPhysicalAltLeft, kLogicalAltLeft, "", kNotSynthesized); clear_key_calls(); // Don't redispatch sys messages. EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 0); // Release AltLeft. AltLeft is a SysKeyUp event. tester.InjectKeyboardChanges(std::vector{ KeyStateChange{VK_LMENU, false, true}, WmSysKeyUpInfo{VK_MENU, kScanCodeAlt, kNotExtended}.Build( kWmResultDefault)}); // Always pass to the default WndProc. EXPECT_EQ(key_calls.size(), 1); EXPECT_CALL_IS_EVENT(key_calls[0], kFlutterKeyEventTypeUp, kPhysicalAltLeft, kLogicalAltLeft, "", kNotSynthesized); clear_key_calls(); // Don't redispatch sys messages. EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 0); } TEST(KeyboardTest, AltRightUnhandled) { KeyboardTester tester; tester.Responding(false); // US Keyboard layout // Press AltRight. AltRight is a SysKeyDown event. tester.InjectKeyboardChanges(std::vector{ KeyStateChange{VK_RMENU, true, false}, WmSysKeyDownInfo{VK_MENU, kScanCodeAlt, kExtended, kWasUp}.Build( kWmResultDefault)}); // Always pass to the default WndProc. EXPECT_EQ(key_calls.size(), 1); EXPECT_CALL_IS_EVENT(key_calls[0], kFlutterKeyEventTypeDown, kPhysicalAltRight, kLogicalAltRight, "", kNotSynthesized); clear_key_calls(); // Don't redispatch sys messages. EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 0); // Release AltRight. AltRight is a SysKeyUp event. tester.InjectKeyboardChanges(std::vector{ KeyStateChange{VK_RMENU, false, true}, WmSysKeyUpInfo{VK_MENU, kScanCodeAlt, kExtended}.Build( kWmResultDefault)}); // Always pass to the default WndProc. EXPECT_EQ(key_calls.size(), 1); EXPECT_CALL_IS_EVENT(key_calls[0], kFlutterKeyEventTypeUp, kPhysicalAltRight, kLogicalAltRight, "", kNotSynthesized); clear_key_calls(); // Don't redispatch sys messages. EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 0); } TEST(KeyboardTest, MetaLeftUnhandled) { KeyboardTester tester; tester.Responding(false); // US Keyboard layout // Press MetaLeft tester.InjectKeyboardChanges(std::vector{ KeyStateChange{VK_LWIN, true, false}, WmKeyDownInfo{VK_LWIN, kScanCodeMetaLeft, kExtended, kWasUp}.Build( kWmResultZero)}); EXPECT_EQ(key_calls.size(), 1); EXPECT_CALL_IS_EVENT(key_calls[0], kFlutterKeyEventTypeDown, kPhysicalMetaLeft, kLogicalMetaLeft, "", kNotSynthesized); clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 1); // Release MetaLeft tester.InjectKeyboardChanges(std::vector{ KeyStateChange{VK_LWIN, false, true}, WmKeyUpInfo{VK_LWIN, kScanCodeMetaLeft, kExtended}.Build(kWmResultZero)}); EXPECT_EQ(key_calls.size(), 1); EXPECT_CALL_IS_EVENT(key_calls[0], kFlutterKeyEventTypeUp, kPhysicalMetaLeft, kLogicalMetaLeft, "", kNotSynthesized); clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 1); } TEST(KeyboardTest, MetaRightUnhandled) { KeyboardTester tester; tester.Responding(false); // US Keyboard layout // Press MetaRight tester.InjectKeyboardChanges(std::vector{ KeyStateChange{VK_RWIN, true, false}, WmKeyDownInfo{VK_RWIN, kScanCodeMetaRight, kExtended, kWasUp}.Build( kWmResultZero)}); EXPECT_EQ(key_calls.size(), 1); EXPECT_CALL_IS_EVENT(key_calls[0], kFlutterKeyEventTypeDown, kPhysicalMetaRight, kLogicalMetaRight, "", kNotSynthesized); clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 1); // Release MetaRight tester.InjectKeyboardChanges(std::vector{ KeyStateChange{VK_RWIN, false, true}, WmKeyUpInfo{VK_RWIN, kScanCodeMetaRight, kExtended}.Build( kWmResultZero)}); EXPECT_EQ(key_calls.size(), 1); EXPECT_CALL_IS_EVENT(key_calls[0], kFlutterKeyEventTypeUp, kPhysicalMetaRight, kLogicalMetaRight, "", kNotSynthesized); clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 1); } // Press Shift-A. This is special because Win32 gives 'A' as character for the // KeyA press. TEST(KeyboardTest, ShiftLeftKeyA) { KeyboardTester tester; tester.Responding(false); // US Keyboard layout // Press ShiftLeft tester.InjectKeyboardChanges(std::vector{ KeyStateChange{VK_LSHIFT, true, true}, WmKeyDownInfo{VK_SHIFT, kScanCodeShiftLeft, kNotExtended, kWasUp}.Build( kWmResultZero)}); EXPECT_EQ(key_calls.size(), 1); EXPECT_CALL_IS_EVENT(key_calls[0], kFlutterKeyEventTypeDown, kPhysicalShiftLeft, kLogicalShiftLeft, "", kNotSynthesized); clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 1); // Press A tester.InjectKeyboardChanges(std::vector{ WmKeyDownInfo{kVirtualKeyA, kScanCodeKeyA, kNotExtended, kWasUp}.Build( kWmResultZero), WmCharInfo{'A', kScanCodeKeyA, kNotExtended, kWasUp}.Build( kWmResultZero)}); EXPECT_EQ(key_calls.size(), 2); EXPECT_CALL_IS_EVENT(key_calls[0], kFlutterKeyEventTypeDown, kPhysicalKeyA, kLogicalKeyA, "A", kNotSynthesized); EXPECT_CALL_IS_TEXT(key_calls[1], u"A"); clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 2); // Release ShiftLeft tester.InjectKeyboardChanges(std::vector{ KeyStateChange{VK_LSHIFT, false, true}, WmKeyUpInfo{VK_SHIFT, kScanCodeShiftLeft, kNotExtended}.Build( kWmResultZero)}); EXPECT_EQ(key_calls.size(), 1); EXPECT_CALL_IS_EVENT(key_calls[0], kFlutterKeyEventTypeUp, kPhysicalShiftLeft, kLogicalShiftLeft, "", kNotSynthesized); clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 1); // Release A tester.InjectKeyboardChanges(std::vector{ WmKeyUpInfo{kVirtualKeyA, kScanCodeKeyA, kNotExtended}.Build( kWmResultZero)}); EXPECT_EQ(key_calls.size(), 1); EXPECT_CALL_IS_EVENT(key_calls[0], kFlutterKeyEventTypeUp, kPhysicalKeyA, kLogicalKeyA, "", kNotSynthesized); clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 1); } // Press Ctrl-A. This is special because Win32 gives 0x01 as character for the // KeyA press. TEST(KeyboardTest, CtrlLeftKeyA) { KeyboardTester tester; tester.Responding(false); // US Keyboard layout // Press ControlLeft tester.InjectKeyboardChanges(std::vector{ KeyStateChange{VK_LCONTROL, true, true}, WmKeyDownInfo{VK_CONTROL, kScanCodeControl, kNotExtended, kWasUp}.Build( kWmResultZero)}); EXPECT_EQ(key_calls.size(), 1); EXPECT_CALL_IS_EVENT(key_calls[0], kFlutterKeyEventTypeDown, kPhysicalControlLeft, kLogicalControlLeft, "", kNotSynthesized); clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 1); // Press A tester.InjectKeyboardChanges(std::vector{ WmKeyDownInfo{kVirtualKeyA, kScanCodeKeyA, kNotExtended, kWasUp}.Build( kWmResultZero), WmCharInfo{0x01, kScanCodeKeyA, kNotExtended, kWasUp}.Build( kWmResultZero)}); EXPECT_EQ(key_calls.size(), 1); EXPECT_CALL_IS_EVENT(key_calls[0], kFlutterKeyEventTypeDown, kPhysicalKeyA, kLogicalKeyA, "", kNotSynthesized); clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 2); // Release A tester.InjectKeyboardChanges(std::vector{ WmKeyUpInfo{kVirtualKeyA, kScanCodeKeyA, kNotExtended}.Build( kWmResultZero)}); EXPECT_EQ(key_calls.size(), 1); EXPECT_CALL_IS_EVENT(key_calls[0], kFlutterKeyEventTypeUp, kPhysicalKeyA, kLogicalKeyA, "", kNotSynthesized); clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 1); // Release ControlLeft tester.InjectKeyboardChanges(std::vector{ KeyStateChange{VK_LCONTROL, false, true}, WmKeyUpInfo{VK_CONTROL, kScanCodeControl, kNotExtended}.Build( kWmResultZero)}); EXPECT_EQ(key_calls.size(), 1); EXPECT_CALL_IS_EVENT(key_calls[0], kFlutterKeyEventTypeUp, kPhysicalControlLeft, kLogicalControlLeft, "", kNotSynthesized); clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 1); } // Press Ctrl-1. This is special because it yields no WM_CHAR for the 1. TEST(KeyboardTest, CtrlLeftDigit1) { KeyboardTester tester; tester.Responding(false); // US Keyboard layout // Press ControlLeft tester.InjectKeyboardChanges(std::vector{ KeyStateChange{VK_LCONTROL, true, true}, WmKeyDownInfo{VK_CONTROL, kScanCodeControl, kNotExtended, kWasUp}.Build( kWmResultZero)}); EXPECT_EQ(key_calls.size(), 1); EXPECT_CALL_IS_EVENT(key_calls[0], kFlutterKeyEventTypeDown, kPhysicalControlLeft, kLogicalControlLeft, "", kNotSynthesized); clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 1); // Press 1 tester.InjectKeyboardChanges(std::vector{ WmKeyDownInfo{kVirtualDigit1, kScanCodeDigit1, kNotExtended, kWasUp} .Build(kWmResultZero)}); EXPECT_EQ(key_calls.size(), 1); EXPECT_CALL_IS_EVENT(key_calls[0], kFlutterKeyEventTypeDown, kPhysicalDigit1, kLogicalDigit1, "", kNotSynthesized); clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 1); // Release 1 tester.InjectKeyboardChanges(std::vector{ WmKeyUpInfo{kVirtualDigit1, kScanCodeDigit1, kNotExtended}.Build( kWmResultZero)}); EXPECT_EQ(key_calls.size(), 1); EXPECT_CALL_IS_EVENT(key_calls[0], kFlutterKeyEventTypeUp, kPhysicalDigit1, kLogicalDigit1, "", kNotSynthesized); clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 1); // Release ControlLeft tester.InjectKeyboardChanges(std::vector{ KeyStateChange{VK_LCONTROL, false, true}, WmKeyUpInfo{VK_CONTROL, kScanCodeControl, kNotExtended}.Build( kWmResultZero)}); EXPECT_EQ(key_calls.size(), 1); EXPECT_CALL_IS_EVENT(key_calls[0], kFlutterKeyEventTypeUp, kPhysicalControlLeft, kLogicalControlLeft, "", kNotSynthesized); clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 1); } // Press 1 on a French keyboard. This is special because it yields WM_CHAR // with char_code '&'. TEST(KeyboardTest, Digit1OnFrenchLayout) { KeyboardTester tester; tester.Responding(false); tester.SetLayout(LayoutFrench); // Press 1 tester.InjectKeyboardChanges(std::vector{ WmKeyDownInfo{kVirtualDigit1, kScanCodeDigit1, kNotExtended, kWasUp} .Build(kWmResultZero), WmCharInfo{'&', kScanCodeDigit1, kNotExtended, kWasUp}.Build( kWmResultZero)}); EXPECT_EQ(key_calls.size(), 2); EXPECT_CALL_IS_EVENT(key_calls[0], kFlutterKeyEventTypeDown, kPhysicalDigit1, kLogicalDigit1, "&", kNotSynthesized); EXPECT_CALL_IS_TEXT(key_calls[1], u"&"); clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 2); // Release 1 tester.InjectKeyboardChanges(std::vector{ WmKeyUpInfo{kVirtualDigit1, kScanCodeDigit1, kNotExtended}.Build( kWmResultZero)}); EXPECT_EQ(key_calls.size(), 1); EXPECT_CALL_IS_EVENT(key_calls[0], kFlutterKeyEventTypeUp, kPhysicalDigit1, kLogicalDigit1, "", kNotSynthesized); clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 1); } // This tests AltGr-Q on a German keyboard, which should print '@'. TEST(KeyboardTest, AltGrModifiedKey) { KeyboardTester tester; tester.Responding(false); // German Keyboard layout // Press AltGr, which Win32 precedes with a ContrlLeft down. tester.InjectKeyboardChanges(std::vector{ KeyStateChange{VK_LCONTROL, true, true}, WmKeyDownInfo{VK_LCONTROL, kScanCodeControl, kNotExtended, kWasUp}.Build( kWmResultZero), WmKeyDownInfo{VK_MENU, kScanCodeAlt, kExtended, kWasUp}.Build( kWmResultZero)}); EXPECT_EQ(key_calls.size(), 2); EXPECT_CALL_IS_EVENT(key_calls[0], kFlutterKeyEventTypeDown, kPhysicalControlLeft, kLogicalControlLeft, "", kNotSynthesized); EXPECT_CALL_IS_EVENT(key_calls[1], kFlutterKeyEventTypeDown, kPhysicalAltRight, kLogicalAltRight, "", kNotSynthesized); clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 2); // Press Q tester.InjectKeyboardChanges(std::vector{ WmKeyDownInfo{kVirtualKeyQ, kScanCodeKeyQ, kNotExtended, kWasUp}.Build( kWmResultZero), WmCharInfo{'@', kScanCodeKeyQ, kNotExtended, kWasUp}.Build( kWmResultZero)}); EXPECT_EQ(key_calls.size(), 2); EXPECT_CALL_IS_EVENT(key_calls[0], kFlutterKeyEventTypeDown, kPhysicalKeyQ, kLogicalKeyQ, "@", kNotSynthesized); EXPECT_CALL_IS_TEXT(key_calls[1], u"@"); clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 2); // Release Q tester.InjectKeyboardChanges(std::vector{ WmKeyUpInfo{kVirtualKeyQ, kScanCodeKeyQ, kNotExtended}.Build( kWmResultZero)}); EXPECT_EQ(key_calls.size(), 1); EXPECT_CALL_IS_EVENT(key_calls[0], kFlutterKeyEventTypeUp, kPhysicalKeyQ, kLogicalKeyQ, "", kNotSynthesized); clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 1); // Release AltGr. Win32 doesn't dispatch ControlLeft up. Instead Flutter will // dispatch one. The AltGr is a system key, therefore will be handled by // Win32's default WndProc. tester.InjectKeyboardChanges(std::vector{ KeyStateChange{VK_LCONTROL, false, true}, WmSysKeyUpInfo{VK_MENU, kScanCodeAlt, kExtended}.Build( kWmResultDefault)}); EXPECT_EQ(key_calls.size(), 2); EXPECT_CALL_IS_EVENT(key_calls[0], kFlutterKeyEventTypeUp, kPhysicalControlLeft, kLogicalControlLeft, "", kNotSynthesized); EXPECT_CALL_IS_EVENT(key_calls[1], kFlutterKeyEventTypeUp, kPhysicalAltRight, kLogicalAltRight, "", kNotSynthesized); clear_key_calls(); // The sys key up must not be redispatched. The forged ControlLeft up will. EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 1); } // Test the following two key sequences at the same time: // // 1. Tap AltGr, then tap AltGr. // 2. Tap AltGr, hold CtrlLeft, tap AltGr, release CtrlLeft. // // The two sequences are indistinguishable until the very end when a CtrlLeft // up event might or might not follow. // // Sequence 1: CtrlLeft down, AltRight down, AltRight up // Sequence 2: CtrlLeft down, AltRight down, AltRight up, CtrlLeft up // // This is because pressing AltGr alone causes Win32 to send a fake "CtrlLeft // down" event first (see |IsKeyDownAltRight| for detailed explanation). TEST(KeyboardTest, AltGrTwice) { KeyboardTester tester; tester.Responding(false); // 1. AltGr down. // The key down event causes a ControlLeft down and a AltRight (extended // AltLeft) down. tester.InjectKeyboardChanges(std::vector{ KeyStateChange{VK_LCONTROL, true, true}, WmKeyDownInfo{VK_LCONTROL, kScanCodeControl, kNotExtended, kWasUp}.Build( kWmResultZero), WmKeyDownInfo{VK_MENU, kScanCodeAlt, kExtended, kWasUp}.Build( kWmResultZero)}); EXPECT_EQ(key_calls.size(), 2); EXPECT_CALL_IS_EVENT(key_calls[0], kFlutterKeyEventTypeDown, kPhysicalControlLeft, kLogicalControlLeft, "", kNotSynthesized); EXPECT_CALL_IS_EVENT(key_calls[1], kFlutterKeyEventTypeDown, kPhysicalAltRight, kLogicalAltRight, "", kNotSynthesized); clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 2); // 2. AltGr up. // The key up event only causes a AltRight (extended AltLeft) up. tester.InjectKeyboardChanges(std::vector{ KeyStateChange{VK_LCONTROL, false, true}, KeyStateChange{VK_RMENU, false, true}, WmSysKeyUpInfo{VK_MENU, kScanCodeAlt, kExtended}.Build( kWmResultDefault)}); EXPECT_EQ(key_calls.size(), 2); EXPECT_CALL_IS_EVENT(key_calls[0], kFlutterKeyEventTypeUp, kPhysicalControlLeft, kLogicalControlLeft, "", kNotSynthesized); EXPECT_CALL_IS_EVENT(key_calls[1], kFlutterKeyEventTypeUp, kPhysicalAltRight, kLogicalAltRight, "", kNotSynthesized); clear_key_calls(); // The sys key up must not be redispatched. The forged ControlLeft up will. EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 1); // 3. AltGr down (or: ControlLeft down then AltRight down.) tester.InjectKeyboardChanges(std::vector{ KeyStateChange{VK_LCONTROL, true, false}, WmKeyDownInfo{VK_LCONTROL, kScanCodeControl, kNotExtended, kWasUp}.Build( kWmResultZero), WmKeyDownInfo{VK_MENU, kScanCodeAlt, kExtended, kWasUp}.Build( kWmResultZero)}); EXPECT_EQ(key_calls.size(), 2); EXPECT_CALL_IS_EVENT(key_calls[0], kFlutterKeyEventTypeDown, kPhysicalControlLeft, kLogicalControlLeft, "", kNotSynthesized); EXPECT_CALL_IS_EVENT(key_calls[1], kFlutterKeyEventTypeDown, kPhysicalAltRight, kLogicalAltRight, "", kNotSynthesized); clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 2); // 4. AltGr up. // The key up event only causes a AltRight (extended AltLeft) up. tester.InjectKeyboardChanges(std::vector{ KeyStateChange{VK_RMENU, false, false}, KeyStateChange{VK_LCONTROL, false, false}, WmSysKeyUpInfo{VK_MENU, kScanCodeAlt, kExtended}.Build( kWmResultDefault)}); EXPECT_EQ(key_calls.size(), 2); EXPECT_CALL_IS_EVENT(key_calls[0], kFlutterKeyEventTypeUp, kPhysicalControlLeft, kLogicalControlLeft, "", kNotSynthesized); EXPECT_CALL_IS_EVENT(key_calls[1], kFlutterKeyEventTypeUp, kPhysicalAltRight, kLogicalAltRight, "", kNotSynthesized); clear_key_calls(); // The sys key up must not be redispatched. The forged ControlLeft up will. EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 1); // 5. For key sequence 2: a real ControlLeft up. tester.InjectKeyboardChanges(std::vector{ WmKeyUpInfo{VK_LCONTROL, kScanCodeControl, kNotExtended}.Build( kWmResultZero)}); EXPECT_EQ(key_calls.size(), 1); EXPECT_CALL_IS_EVENT(key_calls[0], kFlutterKeyEventTypeDown, 0, 0, "", kNotSynthesized); clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 0); } // This tests dead key ^ then E on a French keyboard, which should be combined // into ê. TEST(KeyboardTest, DeadKeyThatCombines) { KeyboardTester tester; tester.Responding(false); tester.SetLayout(LayoutFrench); // Press ^¨ (US: Left bracket) tester.InjectKeyboardChanges(std::vector{ WmKeyDownInfo{0xDD, kScanCodeBracketLeft, kNotExtended, kWasUp}.Build( kWmResultZero), WmDeadCharInfo{'^', kScanCodeBracketLeft, kNotExtended, kWasUp}.Build( kWmResultZero)}); EXPECT_EQ(key_calls.size(), 1); EXPECT_CALL_IS_EVENT(key_calls[0], kFlutterKeyEventTypeDown, kPhysicalBracketLeft, kLogicalBracketRight, "^", kNotSynthesized); clear_key_calls(); // TODO(dkwingsmt): Dead key messages are not redispatched right now, but it // might be safe to redispatch them already. Change the following result to 2. EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 0); // Release ^¨ tester.InjectKeyboardChanges(std::vector{ WmKeyUpInfo{0xDD, kScanCodeBracketLeft, kNotExtended}.Build( kWmResultZero)}); EXPECT_EQ(key_calls.size(), 1); EXPECT_CALL_IS_EVENT(key_calls[0], kFlutterKeyEventTypeUp, kPhysicalBracketLeft, kLogicalBracketRight, "", kNotSynthesized); clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 1); // Press E tester.InjectKeyboardChanges(std::vector{ WmKeyDownInfo{kVirtualKeyE, kScanCodeKeyE, kNotExtended, kWasUp}.Build( kWmResultZero), WmCharInfo{0xEA, kScanCodeKeyE, kNotExtended, kWasUp}.Build( kWmResultZero)}); EXPECT_EQ(key_calls.size(), 2); EXPECT_CALL_IS_EVENT(key_calls[0], kFlutterKeyEventTypeDown, kPhysicalKeyE, kLogicalKeyE, "ê", kNotSynthesized); EXPECT_CALL_IS_TEXT(key_calls[1], u"ê"); clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 2); // Release E tester.InjectKeyboardChanges(std::vector{ WmKeyUpInfo{kVirtualKeyE, kScanCodeKeyE, kNotExtended}.Build( kWmResultZero)}); EXPECT_EQ(key_calls.size(), 1); EXPECT_CALL_IS_EVENT(key_calls[0], kFlutterKeyEventTypeUp, kPhysicalKeyE, kLogicalKeyE, "", kNotSynthesized); clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 1); } // This tests dead key ^ then E on a US INTL keyboard, which should be combined // into ê. // // It is different from French AZERTY because the character that the ^ key is // mapped to does not contain the dead key character somehow. TEST(KeyboardTest, DeadKeyWithoutDeadMaskThatCombines) { KeyboardTester tester; tester.Responding(false); // Press ShiftLeft tester.InjectKeyboardChanges(std::vector{ KeyStateChange{VK_LSHIFT, true, true}, WmKeyDownInfo{VK_SHIFT, kScanCodeShiftLeft, kNotExtended, kWasUp}.Build( kWmResultZero)}); EXPECT_EQ(key_calls.size(), 1); EXPECT_CALL_IS_EVENT(key_calls[0], kFlutterKeyEventTypeDown, kPhysicalShiftLeft, kLogicalShiftLeft, "", kNotSynthesized); clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 1); // Press 6^ tester.InjectKeyboardChanges(std::vector{ WmKeyDownInfo{'6', kScanCodeDigit6, kNotExtended, kWasUp}.Build( kWmResultZero), WmDeadCharInfo{'^', kScanCodeDigit6, kNotExtended, kWasUp}.Build( kWmResultZero)}); EXPECT_EQ(key_calls.size(), 1); EXPECT_CALL_IS_EVENT(key_calls[0], kFlutterKeyEventTypeDown, kPhysicalDigit6, kLogicalDigit6, "6", kNotSynthesized); clear_key_calls(); // TODO(dkwingsmt): Dead key messages are not redispatched right now, but it // might be safe to redispatch them already. Change the following result to 2. EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 0); // Release 6^ tester.InjectKeyboardChanges(std::vector{ WmKeyUpInfo{'6', kScanCodeDigit6, kNotExtended}.Build(kWmResultZero)}); EXPECT_EQ(key_calls.size(), 1); EXPECT_CALL_IS_EVENT(key_calls[0], kFlutterKeyEventTypeUp, kPhysicalDigit6, kLogicalDigit6, "", kNotSynthesized); clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 1); // Release ShiftLeft tester.InjectKeyboardChanges(std::vector{ KeyStateChange{VK_LSHIFT, false, true}, WmKeyUpInfo{VK_SHIFT, kScanCodeShiftLeft, kNotExtended}.Build( kWmResultZero)}); EXPECT_EQ(key_calls.size(), 1); EXPECT_CALL_IS_EVENT(key_calls[0], kFlutterKeyEventTypeUp, kPhysicalShiftLeft, kLogicalShiftLeft, "", kNotSynthesized); clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 1); // Press E tester.InjectKeyboardChanges(std::vector{ WmKeyDownInfo{kVirtualKeyE, kScanCodeKeyE, kNotExtended, kWasUp}.Build( kWmResultZero), WmCharInfo{0xEA, kScanCodeKeyE, kNotExtended, kWasUp}.Build( kWmResultZero)}); EXPECT_EQ(key_calls.size(), 2); EXPECT_CALL_IS_EVENT(key_calls[0], kFlutterKeyEventTypeDown, kPhysicalKeyE, kLogicalKeyE, "ê", kNotSynthesized); EXPECT_CALL_IS_TEXT(key_calls[1], u"ê"); clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 2); // Release E tester.InjectKeyboardChanges(std::vector{ WmKeyUpInfo{kVirtualKeyE, kScanCodeKeyE, kNotExtended}.Build( kWmResultZero)}); EXPECT_EQ(key_calls.size(), 1); EXPECT_CALL_IS_EVENT(key_calls[0], kFlutterKeyEventTypeUp, kPhysicalKeyE, kLogicalKeyE, "", kNotSynthesized); clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 1); } // This tests dead key ^ then & (US: 1) on a French keyboard, which do not // combine and should output "^&". TEST(KeyboardTest, DeadKeyThatDoesNotCombine) { KeyboardTester tester; tester.Responding(false); tester.SetLayout(LayoutFrench); // Press ^¨ (US: Left bracket) tester.InjectKeyboardChanges(std::vector{ WmKeyDownInfo{0xDD, kScanCodeBracketLeft, kNotExtended, kWasUp}.Build( kWmResultZero), WmDeadCharInfo{'^', kScanCodeBracketLeft, kNotExtended, kWasUp}.Build( kWmResultZero)}); EXPECT_EQ(key_calls.size(), 1); EXPECT_CALL_IS_EVENT(key_calls[0], kFlutterKeyEventTypeDown, kPhysicalBracketLeft, kLogicalBracketRight, "^", kNotSynthesized); clear_key_calls(); // TODO(dkwingsmt): Dead key messages are not redispatched right now, but it // might be safe to redispatch them already. Change the following result to 2. EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 0); // Release ^¨ tester.InjectKeyboardChanges(std::vector{ WmKeyUpInfo{0xDD, kScanCodeBracketLeft, kNotExtended}.Build( kWmResultZero)}); EXPECT_EQ(key_calls.size(), 1); EXPECT_CALL_IS_EVENT(key_calls[0], kFlutterKeyEventTypeUp, kPhysicalBracketLeft, kLogicalBracketRight, "", kNotSynthesized); clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 1); // Press 1 tester.InjectKeyboardChanges(std::vector{ WmKeyDownInfo{kVirtualDigit1, kScanCodeDigit1, kNotExtended, kWasUp} .Build(kWmResultZero), WmCharInfo{'^', kScanCodeDigit1, kNotExtended, kWasUp}.Build( kWmResultZero), WmCharInfo{'&', kScanCodeDigit1, kNotExtended, kWasUp}.Build( kWmResultZero)}); EXPECT_EQ(key_calls.size(), 3); EXPECT_CALL_IS_EVENT(key_calls[0], kFlutterKeyEventTypeDown, kPhysicalDigit1, kLogicalDigit1, "^", kNotSynthesized); EXPECT_CALL_IS_TEXT(key_calls[1], u"^"); EXPECT_CALL_IS_TEXT(key_calls[2], u"&"); clear_key_calls(); // TODO(dkwingsmt): This count should probably be 3. Currently the '^' // message is redispatched due to being part of the KeyDown session, which is // not handled by the framework, while the '&' message is not redispatched // for being a standalone message. We should resolve this inconsistency. // https://github.com/flutter/flutter/issues/98306 EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 2); // Release 1 tester.InjectKeyboardChanges(std::vector{ WmKeyUpInfo{kVirtualDigit1, kScanCodeDigit1, kNotExtended}.Build( kWmResultZero)}); EXPECT_EQ(key_calls.size(), 1); EXPECT_CALL_IS_EVENT(key_calls[0], kFlutterKeyEventTypeUp, kPhysicalDigit1, kLogicalDigit1, "", kNotSynthesized); clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 1); } // This tests dead key `, then dead key `, then e. // // It should output ``e, instead of `è. TEST(KeyboardTest, DeadKeyTwiceThenLetter) { KeyboardTester tester; tester.Responding(false); // US INTL layout. // Press ` tester.InjectKeyboardChanges(std::vector{ WmKeyDownInfo{0xC0, kScanCodeBackquote, kNotExtended, kWasUp}.Build( kWmResultZero), WmDeadCharInfo{'`', kScanCodeBackquote, kNotExtended, kWasUp}.Build( kWmResultZero)}); EXPECT_EQ(key_calls.size(), 1); EXPECT_CALL_IS_EVENT(key_calls[0], kFlutterKeyEventTypeDown, kPhysicalBackquote, kLogicalBackquote, "`", kNotSynthesized); clear_key_calls(); // TODO(dkwingsmt): Dead key messages are not redispatched right now, but it // might be safe to redispatch them already. Change the following result to 2. EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 0); // Release ` tester.InjectKeyboardChanges(std::vector{ WmKeyUpInfo{0xC0, kScanCodeBackquote, kNotExtended}.Build( kWmResultZero)}); EXPECT_EQ(key_calls.size(), 1); EXPECT_CALL_IS_EVENT(key_calls[0], kFlutterKeyEventTypeUp, kPhysicalBackquote, kLogicalBackquote, "", kNotSynthesized); clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 1); // Press ` again. // The response should be slow. std::vector recorded_callbacks; tester.LateResponding( [&recorded_callbacks]( const FlutterKeyEvent* event, MockKeyResponseController::ResponseCallback callback) { recorded_callbacks.push_back(callback); }); tester.InjectKeyboardChanges(std::vector{ WmKeyDownInfo{0xC0, kScanCodeBackquote, kNotExtended, kWasUp}.Build( kWmResultZero), WmCharInfo{'`', kScanCodeBackquote, kNotExtended, kWasUp, kBeingReleased, kNoContext, 1, /*bit25*/ true} .Build(kWmResultZero), WmCharInfo{'`', kScanCodeBackquote, kNotExtended, kWasUp}.Build( kWmResultZero)}); EXPECT_EQ(recorded_callbacks.size(), 1); EXPECT_EQ(key_calls.size(), 1); EXPECT_CALL_IS_EVENT(key_calls[0], kFlutterKeyEventTypeDown, kPhysicalBackquote, kLogicalBackquote, "`", kNotSynthesized); clear_key_calls(); // Key down event responded with false. recorded_callbacks.front()(false); EXPECT_EQ(key_calls.size(), 2); EXPECT_CALL_IS_TEXT(key_calls[0], u"`"); EXPECT_CALL_IS_TEXT(key_calls[1], u"`"); clear_key_calls(); // TODO(dkwingsmt): This count should probably be 3. See the comment above // that is marked with the same issue. // https://github.com/flutter/flutter/issues/98306 EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 2); tester.Responding(false); // Release ` tester.InjectKeyboardChanges(std::vector{ WmKeyUpInfo{0xC0, kScanCodeBackquote, kNotExtended}.Build( kWmResultZero)}); EXPECT_EQ(key_calls.size(), 1); EXPECT_CALL_IS_EVENT(key_calls[0], kFlutterKeyEventTypeUp, kPhysicalBackquote, kLogicalBackquote, "", kNotSynthesized); clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 1); } // This tests when the resulting character needs to be combined with surrogates. TEST(KeyboardTest, MultibyteCharacter) { KeyboardTester tester; tester.Responding(false); // Gothic Keyboard layout. (We need a layout that yields non-BMP characters // without IME, which is actually very rare.) // Press key W of a US keyboard, which should yield character '𐍅'. tester.InjectKeyboardChanges(std::vector{ WmKeyDownInfo{kVirtualKeyW, kScanCodeKeyW, kNotExtended, kWasUp}.Build( kWmResultZero), WmCharInfo{0xd800, kScanCodeKeyW, kNotExtended, kWasUp}.Build( kWmResultZero), WmCharInfo{0xdf45, kScanCodeKeyW, kNotExtended, kWasUp}.Build( kWmResultZero)}); const char* st = key_calls[0].key_event.character; EXPECT_EQ(key_calls.size(), 2); EXPECT_CALL_IS_EVENT(key_calls[0], kFlutterKeyEventTypeDown, kPhysicalKeyW, kLogicalKeyW, "𐍅", kNotSynthesized); EXPECT_CALL_IS_TEXT(key_calls[1], u"𐍅"); clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 3); // Release W tester.InjectKeyboardChanges(std::vector{ WmKeyUpInfo{kVirtualKeyW, kScanCodeKeyW, kNotExtended}.Build( kWmResultZero)}); EXPECT_EQ(key_calls.size(), 1); EXPECT_CALL_IS_EVENT(key_calls[0], kFlutterKeyEventTypeUp, kPhysicalKeyW, kLogicalKeyW, "", kNotSynthesized); clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 1); } // A key down event for shift right must not be redispatched even if // the framework returns unhandled. // // The reason for this test is documented in |IsKeyDownShiftRight|. TEST(KeyboardTest, NeverRedispatchShiftRightKeyDown) { KeyboardTester tester; tester.Responding(false); // Press ShiftRight and the delegate responds false. tester.InjectKeyboardChanges(std::vector{ KeyStateChange{VK_RSHIFT, true, true}, WmKeyDownInfo{VK_SHIFT, kScanCodeShiftRight, kNotExtended, kWasUp}.Build( kWmResultZero)}); EXPECT_EQ(key_calls.size(), 1); clear_key_calls(); } // Pressing extended keys during IME events should work properly by not sending // any events. // // Regression test for https://github.com/flutter/flutter/issues/95888 . TEST(KeyboardTest, ImeExtendedEventsAreIgnored) { KeyboardTester tester; tester.Responding(false); // US Keyboard layout. // There should be preceding key events to make the keyboard into IME mode. // Omit them in this test since they are not relavent. // Press CtrlRight in IME mode. tester.InjectKeyboardChanges(std::vector{ KeyStateChange{VK_RCONTROL, true, false}, WmKeyDownInfo{VK_PROCESSKEY, kScanCodeControl, kExtended, kWasUp}.Build( kWmResultZero)}); EXPECT_EQ(key_calls.size(), 1); EXPECT_CALL_IS_EVENT(key_calls[0], kFlutterKeyEventTypeDown, 0, 0, "", kNotSynthesized); clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 0); } TEST(KeyboardTest, DisorderlyRespondedEvents) { KeyboardTester tester; // Store callbacks to manually call them. std::vector recorded_callbacks; tester.LateResponding( [&recorded_callbacks]( const FlutterKeyEvent* event, MockKeyResponseController::ResponseCallback callback) { recorded_callbacks.push_back(callback); }); // Press A tester.InjectKeyboardChanges(std::vector{ WmKeyDownInfo{kVirtualKeyA, kScanCodeKeyA, kNotExtended, kWasUp}.Build( kWmResultZero), WmCharInfo{'a', kScanCodeKeyA, kNotExtended, kWasUp}.Build( kWmResultZero)}); // Press B tester.InjectKeyboardChanges(std::vector{ WmKeyDownInfo{kVirtualKeyB, kScanCodeKeyB, kNotExtended, kWasUp}.Build( kWmResultZero), WmCharInfo{'b', kScanCodeKeyB, kNotExtended, kWasUp}.Build( kWmResultZero)}); EXPECT_EQ(key_calls.size(), 2); EXPECT_EQ(recorded_callbacks.size(), 2); clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 0); // Resolve the second event first to test disordered responses. recorded_callbacks.back()(false); EXPECT_EQ(key_calls.size(), 0); clear_key_calls(); // TODO(dkwingsmt): This should probably be 0. Redispatching the messages of // the second event this early means that the messages are not redispatched // in the order of arrival. https://github.com/flutter/flutter/issues/98308 EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 2); // Resolve the first event. recorded_callbacks.front()(false); EXPECT_EQ(key_calls.size(), 2); EXPECT_CALL_IS_TEXT(key_calls[0], u"a"); EXPECT_CALL_IS_TEXT(key_calls[1], u"b"); clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 2); } // Regression test for a crash in an earlier implementation. // // In real life, the framework responds slowly. The next real event might // arrive earlier than the framework response, and if the 2nd event has an // identical hash as the one waiting for response, an earlier implementation // will crash upon the response. TEST(KeyboardTest, SlowFrameworkResponse) { KeyboardTester tester; std::vector recorded_callbacks; // Store callbacks to manually call them. tester.LateResponding( [&recorded_callbacks]( const FlutterKeyEvent* event, MockKeyResponseController::ResponseCallback callback) { recorded_callbacks.push_back(callback); }); // Press A tester.InjectKeyboardChanges(std::vector{ WmKeyDownInfo{kVirtualKeyA, kScanCodeKeyA, kNotExtended, kWasUp}.Build( kWmResultZero), WmCharInfo{'a', kScanCodeKeyA, kNotExtended, kWasUp}.Build( kWmResultZero)}); // Hold A tester.InjectKeyboardChanges(std::vector{ WmKeyDownInfo{kVirtualKeyA, kScanCodeKeyA, kNotExtended, kWasDown}.Build( kWmResultZero), WmCharInfo{'a', kScanCodeKeyA, kNotExtended, kWasDown}.Build( kWmResultZero)}); EXPECT_EQ(key_calls.size(), 2); EXPECT_EQ(recorded_callbacks.size(), 2); clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 0); // The first response. recorded_callbacks.front()(false); EXPECT_EQ(key_calls.size(), 1); EXPECT_CALL_IS_TEXT(key_calls[0], u"a"); clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 2); // The second response. recorded_callbacks.back()(false); EXPECT_EQ(key_calls.size(), 1); EXPECT_CALL_IS_TEXT(key_calls[0], u"a"); clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 2); } // Regression test for https://github.com/flutter/flutter/issues/84210. // // When the framework response is slow during a sequence of identical messages, // make sure the real messages are not mistaken as redispatched messages, // in order to not mess up the order of events. // // In this test we use: // // KeyA down, KeyA up, (down event responded with false), KeyA down, KeyA up, // // The code must not take the 2nd real key down events as a redispatched event. TEST(KeyboardTest, SlowFrameworkResponseForIdenticalEvents) { KeyboardTester tester; std::vector recorded_callbacks; // Store callbacks to manually call them. tester.LateResponding( [&recorded_callbacks]( const FlutterKeyEvent* event, MockKeyResponseController::ResponseCallback callback) { recorded_callbacks.push_back(callback); }); // Press A tester.InjectKeyboardChanges(std::vector{ WmKeyDownInfo{kVirtualKeyA, kScanCodeKeyA, kNotExtended, kWasUp}.Build( kWmResultZero), WmCharInfo{'a', kScanCodeKeyA, kNotExtended, kWasUp}.Build( kWmResultZero)}); EXPECT_EQ(key_calls.size(), 1); EXPECT_CALL_IS_EVENT(key_calls[0], kFlutterKeyEventTypeDown, kPhysicalKeyA, kLogicalKeyA, "a", kNotSynthesized); clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 0); // Release A tester.InjectKeyboardChanges(std::vector{ WmKeyUpInfo{kVirtualKeyA, kScanCodeKeyA, kNotExtended}.Build( kWmResultZero)}); EXPECT_EQ(key_calls.size(), 1); EXPECT_CALL_IS_EVENT(key_calls[0], kFlutterKeyEventTypeUp, kPhysicalKeyA, kLogicalKeyA, "", kNotSynthesized); clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 0); // The first down event responded with false. EXPECT_EQ(recorded_callbacks.size(), 2); recorded_callbacks.front()(false); EXPECT_EQ(key_calls.size(), 1); EXPECT_CALL_IS_TEXT(key_calls[0], u"a"); clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 2); // Press A again tester.InjectKeyboardChanges(std::vector{ WmKeyDownInfo{kVirtualKeyA, kScanCodeKeyA, kNotExtended, kWasUp}.Build( kWmResultZero), WmCharInfo{'a', kScanCodeKeyA, kNotExtended, kWasUp}.Build( kWmResultZero)}); EXPECT_EQ(key_calls.size(), 1); EXPECT_CALL_IS_EVENT(key_calls[0], kFlutterKeyEventTypeDown, kPhysicalKeyA, kLogicalKeyA, "a", kNotSynthesized); clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 0); // Release A again tester.InjectKeyboardChanges(std::vector{ WmKeyUpInfo{kVirtualKeyA, kScanCodeKeyA, kNotExtended}.Build( kWmResultZero)}); EXPECT_EQ(key_calls.size(), 1); EXPECT_CALL_IS_EVENT(key_calls[0], kFlutterKeyEventTypeUp, kPhysicalKeyA, kLogicalKeyA, "", kNotSynthesized); clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 0); } TEST(KeyboardTest, TextInputSubmit) { KeyboardTester tester; tester.Responding(false); // US Keyboard layout tester.GetView().HandleMessage( "flutter/textinput", "TextInput.setClient", R"|([108, {"inputAction": "TextInputAction.none"}])|"); // Press Enter tester.InjectKeyboardChanges(std::vector{ WmKeyDownInfo{VK_RETURN, kScanCodeEnter, kNotExtended, kWasUp}.Build( kWmResultZero), WmCharInfo{'\n', kScanCodeEnter, kNotExtended, kWasUp}.Build( kWmResultZero)}); EXPECT_EQ(key_calls.size(), 2); EXPECT_CALL_IS_EVENT(key_calls[0], kFlutterKeyEventTypeDown, kPhysicalEnter, kLogicalEnter, "", kNotSynthesized); EXPECT_CALL_IS_TEXT_METHOD_CALL( key_calls[1], "{" R"|("method":"TextInputClient.performAction",)|" R"|("args":[108,"TextInputAction.none"])|" "}"); clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 2); // Release Enter tester.InjectKeyboardChanges(std::vector{ WmKeyUpInfo{VK_RETURN, kScanCodeEnter, kNotExtended}.Build( kWmResultZero)}); EXPECT_EQ(key_calls.size(), 1); EXPECT_CALL_IS_EVENT(key_calls[0], kFlutterKeyEventTypeUp, kPhysicalEnter, kLogicalEnter, "", kNotSynthesized); clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 1); // Make sure OnText is not obstructed after pressing Enter. // // Regression test for https://github.com/flutter/flutter/issues/97706. // Press A tester.InjectKeyboardChanges(std::vector{ WmKeyDownInfo{kVirtualKeyA, kScanCodeKeyA, kNotExtended, kWasUp}.Build( kWmResultZero), WmCharInfo{'a', kScanCodeKeyA, kNotExtended, kWasUp}.Build( kWmResultZero)}); EXPECT_EQ(key_calls.size(), 2); EXPECT_CALL_IS_EVENT(key_calls[0], kFlutterKeyEventTypeDown, kPhysicalKeyA, kLogicalKeyA, "a", kNotSynthesized); EXPECT_CALL_IS_TEXT(key_calls[1], u"a"); clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 2); // Release A tester.InjectKeyboardChanges(std::vector{ WmKeyUpInfo{kVirtualKeyA, kScanCodeKeyA, kNotExtended}.Build( kWmResultZero)}); EXPECT_EQ(key_calls.size(), 1); EXPECT_CALL_IS_EVENT(key_calls[0], kFlutterKeyEventTypeUp, kPhysicalKeyA, kLogicalKeyA, "", kNotSynthesized); clear_key_calls(); EXPECT_EQ(tester.RedispatchedMessageCountAndClear(), 1); } } // namespace testing } // namespace flutter src/reed-muller/codeword.hpp #ifndef CODEWORD_HPP #define CODEWORD_HPP class Codeword { private: /* data */ public: Codeword(/* args */); ~Codeword(); }; Codeword::Codeword(/* args */) { } Codeword::~Codeword() { } #endif /* CODEWORD_HPP */ /* Created by clemens on 19.03.18. This file is part of the software provided by ARTI Copyright (c) 2018, ARTI All rights reserved. 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 #include #include namespace arti_move_base { ArtiMoveBase::ArtiMoveBase(const ros::NodeHandle& node_handle) : node_handle_(node_handle), config_server_(node_handle_), transformer_(arti_nav_core_utils::createTransformer()), current_goal_publisher_(node_handle_.advertise("current_goal", 1)), clear_costmaps_server_(node_handle_.advertiseService("clear_costmaps", &ArtiMoveBase::clearCostmapsCB, this)), follow_target_action_server_(root_node_handle_, "follow_target", false), follow_trajectory_action_server_(root_node_handle_, "follow_trajectory", false), move_in_network_action_server_(root_node_handle_, "move_in_network", false), move_base_server_(root_node_handle_) { config_server_.setCallback(std::bind(&ArtiMoveBase::reconfigure, this, std::placeholders::_1)); std::lock_guard planner_pipeline_lock(planner_pipeline_mutex_); const std::shared_ptr global_planner_costmap = std::make_shared("global_costmap", *transformer_); global_planner_costmap->pause(); const std::shared_ptr local_planner_costmap = std::make_shared("local_costmap", *transformer_); local_planner_costmap->pause(); const std::shared_ptr path_follower_costmap = std::make_shared("path_follower_costmap", *transformer_); path_follower_costmap->pause(); costmaps_ = {global_planner_costmap, local_planner_costmap, path_follower_costmap}; PipelineBuilder pipeline_builder; pipeline_builder.addNetworkPlanner(ros::NodeHandle(node_handle_, "network_planner"), std::bind(&ArtiMoveBase::networkPlannerErrorCB, this, std::placeholders::_1), std::bind(&ArtiMoveBase::networkPlannerSuccessCB, this), transformer_); pipeline_builder.addGlobalPlanner(ros::NodeHandle(node_handle_, "global_planner"), std::bind(&ArtiMoveBase::globalPlannerErrorCB, this, std::placeholders::_1), std::bind(&ArtiMoveBase::globalPlannerSuccessCB, this), transformer_, global_planner_costmap); pipeline_builder.addLocalPlanner(ros::NodeHandle(node_handle_, "local_planner"), nullptr, nullptr, transformer_, local_planner_costmap); const ros::NodeHandle path_follower_node_handle(node_handle_, "path_follower"); if (config_.ackermann_steering) { pipeline_builder.addPathFollower( path_follower_node_handle, std::bind(&ArtiMoveBase::pathFollowerErrorCB::Error>, this, std::placeholders::_1), std::bind(&ArtiMoveBase::pathFollowerSuccessCB, this), transformer_, path_follower_costmap); planner_pipeline_ = std::make_shared>(root_node_handle_, "cmd_vel"); } else { pipeline_builder.addPathFollower( path_follower_node_handle, std::bind(&ArtiMoveBase::pathFollowerErrorCB::Error>, this, std::placeholders::_1), std::bind(&ArtiMoveBase::pathFollowerSuccessCB, this), transformer_, path_follower_costmap); planner_pipeline_ = std::make_shared>(root_node_handle_, "cmd_vel"); } planner_pipeline_->createPipeline(pipeline_builder); for (const auto& costmap : costmaps_) { costmap->start(); } follow_target_action_server_.registerGoalCallback(std::bind(&ArtiMoveBase::followTargetGoalCB, this)); follow_target_action_server_.registerPreemptCallback(std::bind(&ArtiMoveBase::followTargetPreemptCB, this)); follow_target_action_server_.start(); follow_trajectory_action_server_.registerGoalCallback(std::bind(&ArtiMoveBase::followTrajectoryGoalCB, this)); follow_trajectory_action_server_.registerPreemptCallback(std::bind(&ArtiMoveBase::followTrajectoryPreemptCB, this)); follow_trajectory_action_server_.start(); move_in_network_action_server_.registerGoalCallback(std::bind(&ArtiMoveBase::moveInNetworkGoalCB, this)); move_in_network_action_server_.registerPreemptCallback(std::bind(&ArtiMoveBase::moveInNetworkPreemptCB, this)); move_in_network_action_server_.start(); } void ArtiMoveBase::reconfigure(MoveBaseConfig& config) { std::lock_guard planner_pipeline_lock(planner_pipeline_mutex_); if (planner_pipeline_) { // This parameter can't change after the pipeline has been created, so set it to whatever it was before: config.ackermann_steering = config_.ackermann_steering; } config_ = config; } void ArtiMoveBase::followTargetGoalCB() { std::lock_guard planner_pipeline_lock(planner_pipeline_mutex_); const arti_move_base_msgs::FollowTargetGoalConstPtr goal = follow_target_action_server_.acceptNewGoal(); if (goal) { ROS_DEBUG_STREAM("follow target action called with new goal: " << *goal); // This will set the input of the global planner: arti_nav_core_msgs::Movement2DGoalWithConstraints pipeline_goal; pipeline_goal.goal.pose = addLimitsIfMissing(goal->target_movement.pose); pipeline_goal.goal.twist = goal->target_movement.twist; error_handled_ = false; planner_pipeline_->setInput(pipeline_goal); publishCurrentGoal(pipeline_goal.goal.pose); } } void ArtiMoveBase::followTargetPreemptCB() { std::lock_guard planner_pipeline_lock(planner_pipeline_mutex_); planner_pipeline_->cancel(); follow_target_action_server_.setPreempted(); } void ArtiMoveBase::followTrajectoryGoalCB() { std::lock_guard planner_pipeline_lock(planner_pipeline_mutex_); const arti_move_base_msgs::FollowTrajectoryGoalConstPtr goal = follow_trajectory_action_server_.acceptNewGoal(); if (goal) { ROS_DEBUG_STREAM("follow trajectory action called with new goal: " << *goal); // This will set the input of the path follower: error_handled_ = false; planner_pipeline_->setInput(goal->trajectory); if (!goal->trajectory.movements.empty()) { arti_nav_core_msgs::Pose2DStampedWithLimits last_pose; last_pose.header = goal->trajectory.header; last_pose.pose = goal->trajectory.movements.back().pose; publishCurrentGoal(last_pose); } } } void ArtiMoveBase::followTrajectoryPreemptCB() { std::lock_guard planner_pipeline_lock(planner_pipeline_mutex_); planner_pipeline_->cancel(); follow_trajectory_action_server_.setPreempted(); } void ArtiMoveBase::moveInNetworkGoalCB() { std::lock_guard planner_pipeline_lock(planner_pipeline_mutex_); const arti_move_base_msgs::MoveInNetworkGoalConstPtr goal = move_in_network_action_server_.acceptNewGoal(); if (goal) { ROS_DEBUG_STREAM("move in network action called with new goal: " << *goal); // This will set the input of the network planner: const arti_nav_core_msgs::Pose2DStampedWithLimits pipeline_goal = addLimitsIfMissing(goal->target_pose); error_handled_ = false; planner_pipeline_->setInput(pipeline_goal); publishCurrentGoal(pipeline_goal); } } void ArtiMoveBase::moveInNetworkPreemptCB() { std::lock_guard planner_pipeline_lock(planner_pipeline_mutex_); planner_pipeline_->cancel(); move_in_network_action_server_.setPreempted(); } bool ArtiMoveBase::clearCostmapsCB(std_srvs::Empty::Request& /*req*/, std_srvs::Empty::Response& /*resp*/) { for (const auto& costmap : costmaps_) { costmap->resetLayers(); } return true; } void ArtiMoveBase::networkPlannerSuccessCB() { std::lock_guard planner_pipeline_lock(planner_pipeline_mutex_); planner_pipeline_->cancel(); if (move_in_network_action_server_.isActive()) { move_in_network_action_server_.setSucceeded({}, "goal reached"); } } void ArtiMoveBase::networkPlannerErrorCB(const arti_nav_core::BaseNetworkPlanner::BaseNetworkPlannerErrorEnum& error) { std::lock_guard planner_pipeline_lock(planner_pipeline_mutex_); if (!error_handled_) { error_handled_ = true; planner_pipeline_->cancel(); if (move_in_network_action_server_.isActive()) { move_in_network_action_server_.setAborted({}, std::string("network planner failed with error ") + utils::toString(error)); } } } void ArtiMoveBase::globalPlannerSuccessCB() { std::lock_guard planner_pipeline_lock(planner_pipeline_mutex_); // Only handle the success if the pipeline was started because of a call to this action: if (follow_target_action_server_.isActive()) { planner_pipeline_->cancel(); follow_target_action_server_.setSucceeded({}, "goal reached"); } } void ArtiMoveBase::globalPlannerErrorCB(const GlobalPlannerError& error) { std::lock_guard planner_pipeline_lock(planner_pipeline_mutex_); // Only handle the error if the pipeline was started because of a call to this action: if (follow_target_action_server_.isActive() && !error_handled_) { error_handled_ = true; planner_pipeline_->cancel(); follow_target_action_server_.setAborted({}, std::string("global planner failed with error ") + utils::toString(error.error_enum)); } } void ArtiMoveBase::pathFollowerSuccessCB() { std::lock_guard planner_pipeline_lock(planner_pipeline_mutex_); // Only handle the success if the pipeline was started because of a call to this action: if (follow_trajectory_action_server_.isActive()) { planner_pipeline_->cancel(); follow_trajectory_action_server_.setSucceeded({}, "goal reached"); } } template void ArtiMoveBase::pathFollowerErrorCB(const E& error) { std::lock_guard planner_pipeline_lock(planner_pipeline_mutex_); // Only handle the error if the pipeline was started because of a call to this action: if (follow_trajectory_action_server_.isActive() && !error_handled_) { error_handled_ = true; planner_pipeline_->cancel(); follow_trajectory_action_server_.setAborted({}, std::string("path follower failed with error ") + utils::toString(error)); } } arti_nav_core_msgs::Pose2DStampedWithLimits ArtiMoveBase::addLimitsIfMissing( arti_nav_core_msgs::Pose2DStampedWithLimits goal) const { if (!goal.pose.point.x.has_limits) { goal.pose.point.x.has_limits = true; goal.pose.point.x.upper_limit = config_.x_y_simple_goal_final_tolerance; goal.pose.point.x.lower_limit = -config_.x_y_simple_goal_final_tolerance; } if (!goal.pose.point.y.has_limits) { goal.pose.point.y.has_limits = true; goal.pose.point.y.upper_limit = config_.x_y_simple_goal_final_tolerance; goal.pose.point.y.lower_limit = -config_.x_y_simple_goal_final_tolerance; } if (!goal.pose.theta.has_limits) { goal.pose.theta.has_limits = true; goal.pose.theta.upper_limit = config_.yaw_simple_goal_final_tolerance; goal.pose.theta.lower_limit = -config_.yaw_simple_goal_final_tolerance; } return goal; } void ArtiMoveBase::publishCurrentGoal(const arti_nav_core_msgs::Pose2DStampedWithLimits& pose) { current_goal_publisher_.publish( arti_nav_core_utils::convertToPoseStamped(pose, arti_nav_core_utils::non_finite_values::PASS_THROUGH)); } } // namespace arti_move_base int main(int argc, char** argv) { ros::init(argc, argv, "arti_move_base"); arti_move_base::ArtiMoveBase node{{"~"}}; ros::spin(); return 0; } main.cpp100-1000 //////////////////////////////////////////////////////////////////////////////// // Copyright 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. //////////////////////////////////////////////////////////////////////////////// #include "OcclusionCulling.h" void ParseCommandLine() { LPTSTR commandLine = GetCommandLineW(); int numArgs = 0; LPWSTR* argv = CommandLineToArgvW(commandLine, &numArgs); for(int i = 1; i < numArgs; i += 2) { if(!_wcsicmp(argv[i], L"-dropdown1")) { if(!_wcsicmp(argv[i+1], L"SSE_TYPE")) { gSOCType = SSE_TYPE; } else { gSOCType = SCALAR_TYPE; } } if(!_wcsicmp(argv[i], L"-slider1")) { gOccluderSizeThreshold = (float)_wtof(argv[i+1]); } if(!_wcsicmp(argv[i], L"-slider2")) { gOccludeeSizeThreshold = (float)_wtof(argv[i+1]); } if(!_wcsicmp(argv[i], L"-slider3")) { gDepthTestTasks = wcstoul(argv[i+1], NULL, 10); } } } // Application entry point. Execution begins here. //----------------------------------------------------------------------------- int WINAPI wWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nCmdShow ) { ParseCommandLine(); // Prevent unused parameter compiler warnings UNREFERENCED_PARAMETER(hInstance); UNREFERENCED_PARAMETER(hPrevInstance); UNREFERENCED_PARAMETER(nCmdShow); #ifdef DEBUG // tell VS to report leaks at any exit of the program _CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF ); #endif CPUTResult result=CPUT_SUCCESS; int returnCode=0; // create an instance of my sample MySample *pSample = new MySample(); // We make the assumption we are running from the executable's dir in // the CPUT SampleStart directory or it won't be able to use the relative paths to find the default // resources cString ResourceDirectory; CPUTOSServices::GetOSServices()->GetWorkingDirectory(&ResourceDirectory); ResourceDirectory.append(_L("\\CPUT\\resources\\")); // Initialize the system and give it the base CPUT resource directory (location of GUI images/etc) // For now, we assume it's a relative directory from the executable directory. Might make that resource // directory location an env variable/hardcoded later pSample->CPUTInitialize(ResourceDirectory); // window and device parameters CPUTWindowCreationParams params; params.deviceParams.refreshRate = 0; //60; params.deviceParams.swapChainBufferCount= 1; params.deviceParams.swapChainFormat = DXGI_FORMAT_R8G8B8A8_UNORM_SRGB; params.deviceParams.swapChainUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT | DXGI_USAGE_SHADER_INPUT; //CPUTOSServices::GetOSServices()->GetDesktopDimensions(¶ms.windowWidth, ¶ms.windowHeight); // parse out the parameter settings or reset them to defaults if not specified cString AssetFilename; cString CommandLine(lpCmdLine); pSample->CPUTParseCommandLine(CommandLine, ¶ms, &AssetFilename); params.windowWidth = SCREENW; params.windowHeight = SCREENH; // create the window and device context result = pSample->CPUTCreateWindowAndContext(_L("CPUTWindow DirectX 11"), params); ASSERT( CPUTSUCCESS(result), _L("CPUT Error creating window and context.") ); // initialize the task manager gTaskMgr.Init(); // start the main message loop returnCode = pSample->CPUTMessageLoop(); pSample->DeviceShutdown(); // shutdown task manage gTaskMgr.Shutdown(); // cleanup resources delete pSample; return returnCode; } 1-10 /* -*- c++ -*- */ /* * Copyright 2015,2016 Free Software Foundation, Inc. * * This 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 software 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 software; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include #include "dvbt2_interleaver_bb_impl.h" namespace gr { namespace dtv { dvbt2_interleaver_bb::sptr dvbt2_interleaver_bb::make(dvb_framesize_t framesize, dvb_code_rate_t rate, dvb_constellation_t constellation) { return gnuradio::get_initial_sptr (new dvbt2_interleaver_bb_impl(framesize, rate, constellation)); } /* * The private constructor */ dvbt2_interleaver_bb_impl::dvbt2_interleaver_bb_impl(dvb_framesize_t framesize, dvb_code_rate_t rate, dvb_constellation_t constellation) : gr::block("dvbt2_interleaver_bb", gr::io_signature::make(1, 1, sizeof(unsigned char)), gr::io_signature::make(1, 1, sizeof(unsigned char))) { signal_constellation = constellation; code_rate = rate; if (framesize == FECFRAME_NORMAL) { frame_size = FRAME_SIZE_NORMAL; switch (rate) { case C1_2: nbch = 32400; q_val = 90; break; case C3_5: nbch = 38880; q_val = 72; break; case C2_3: nbch = 43200; q_val = 60; break; case C3_4: nbch = 48600; q_val = 45; break; case C4_5: nbch = 51840; q_val = 36; break; case C5_6: nbch = 54000; q_val = 30; break; default: nbch = 0; q_val = 0; break; } } else { frame_size = FRAME_SIZE_SHORT; switch (rate) { case C1_3: nbch = 5400; q_val = 30; break; case C2_5: nbch = 6480; q_val = 27; break; case C1_2: nbch = 7200; q_val = 25; break; case C3_5: nbch = 9720; q_val = 18; break; case C2_3: nbch = 10800; q_val = 15; break; case C3_4: nbch = 11880; q_val = 12; break; case C4_5: nbch = 12600; q_val = 10; break; case C5_6: nbch = 13320; q_val = 8; break; default: nbch = 0; q_val = 0; break; } } switch (constellation) { case MOD_QPSK: mod = 2; set_output_multiple(frame_size / mod); packed_items = frame_size / mod; break; case MOD_16QAM: mod = 4; set_output_multiple(frame_size / mod); packed_items = frame_size / mod; break; case MOD_64QAM: mod = 6; set_output_multiple(frame_size / mod); packed_items = frame_size / mod; break; case MOD_256QAM: mod = 8; set_output_multiple(frame_size / mod); packed_items = frame_size / mod; break; default: mod = 1; set_output_multiple(frame_size / mod); packed_items = frame_size / mod; break; } } /* * Our virtual destructor. */ dvbt2_interleaver_bb_impl::~dvbt2_interleaver_bb_impl() { } void dvbt2_interleaver_bb_impl::forecast (int noutput_items, gr_vector_int &ninput_items_required) { ninput_items_required[0] = noutput_items * mod; } int dvbt2_interleaver_bb_impl::general_work (int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { const unsigned char *in = (const unsigned char *) input_items[0]; unsigned char *out = (unsigned char *) output_items[0]; int consumed = 0; int produced = 0; int rows, offset, index; unsigned int pack; const int *twist; const int *mux; switch (signal_constellation) { case MOD_QPSK: for (int i = 0; i < noutput_items; i += packed_items) { rows = frame_size / 2; if (code_rate == C1_3 || code_rate == C2_5) { for (int k = 0; k < nbch; k++) { tempu[k] = *in++; } for (int t = 0; t < q_val; t++) { for (int s = 0; s < 360; s++) { tempu[nbch + (360 * t) + s] = in[(q_val * s) + t]; } } in = in + (q_val * 360); index = 0; for (int j = 0; j < rows; j++) { out[produced] = tempu[index++] << 1; out[produced++] |= tempu[index++]; consumed += 2; } } else { for (int j = 0; j < rows; j++) { out[produced] = in[consumed++] << 1; out[produced++] |= in[consumed++]; } } } break; case MOD_16QAM: if (frame_size == FRAME_SIZE_NORMAL) { twist = &twist16n[0]; } else { twist = &twist16s[0]; } if (code_rate == C3_5 && frame_size == FRAME_SIZE_NORMAL) { mux = &mux16_35[0]; } else if (code_rate == C1_3 && frame_size == FRAME_SIZE_SHORT) { mux = &mux16_13[0]; } else if (code_rate == C2_5 && frame_size == FRAME_SIZE_SHORT) { mux = &mux16_25[0]; } else { mux = &mux16[0]; } for (int i = 0; i < noutput_items; i += packed_items) { rows = frame_size / (mod * 2); const unsigned char *c1, *c2, *c3, *c4, *c5, *c6, *c7, *c8; c1 = &tempv[0]; c2 = &tempv[rows]; c3 = &tempv[rows * 2]; c4 = &tempv[rows * 3]; c5 = &tempv[rows * 4]; c6 = &tempv[rows * 5]; c7 = &tempv[rows * 6]; c8 = &tempv[rows * 7]; for (int k = 0; k < nbch; k++) { tempu[k] = *in++; } for (int t = 0; t < q_val; t++) { for (int s = 0; s < 360; s++) { tempu[nbch + (360 * t) + s] = in[(q_val * s) + t]; } } in = in + (q_val * 360); index = 0; for (int col = 0; col < (mod * 2); col++) { offset = twist[col]; for (int row = 0; row < rows; row++) { tempv[offset + (rows * col)] = tempu[index++]; offset++; if (offset == rows) { offset = 0; } } } index = 0; for (int j = 0; j < rows; j++) { tempu[index++] = c1[j]; tempu[index++] = c2[j]; tempu[index++] = c3[j]; tempu[index++] = c4[j]; tempu[index++] = c5[j]; tempu[index++] = c6[j]; tempu[index++] = c7[j]; tempu[index++] = c8[j]; } index = 0; for (int d = 0; d < frame_size / (mod * 2); d++) { pack = 0; for (int e = 0; e < (mod * 2); e++) { offset = mux[e]; pack |= tempu[index++] << (((mod * 2) - 1) - offset); } out[produced++] = pack >> 4; out[produced++] = pack & 0xf; consumed += (mod * 2); } } break; case MOD_64QAM: if (frame_size == FRAME_SIZE_NORMAL) { twist = &twist64n[0]; } else { twist = &twist64s[0]; } if (code_rate == C3_5 && frame_size == FRAME_SIZE_NORMAL) { mux = &mux64_35[0]; } else if (code_rate == C1_3 && frame_size == FRAME_SIZE_SHORT) { mux = &mux64_13[0]; } else if (code_rate == C2_5 && frame_size == FRAME_SIZE_SHORT) { mux = &mux64_25[0]; } else { mux = &mux64[0]; } for (int i = 0; i < noutput_items; i += packed_items) { rows = frame_size / (mod * 2); const unsigned char *c1, *c2, *c3, *c4, *c5, *c6, *c7, *c8, *c9, *c10, *c11, *c12; c1 = &tempv[0]; c2 = &tempv[rows]; c3 = &tempv[rows * 2]; c4 = &tempv[rows * 3]; c5 = &tempv[rows * 4]; c6 = &tempv[rows * 5]; c7 = &tempv[rows * 6]; c8 = &tempv[rows * 7]; c9 = &tempv[rows * 8]; c10 = &tempv[rows * 9]; c11 = &tempv[rows * 10]; c12 = &tempv[rows * 11]; for (int k = 0; k < nbch; k++) { tempu[k] = *in++; } for (int t = 0; t < q_val; t++) { for (int s = 0; s < 360; s++) { tempu[nbch + (360 * t) + s] = in[(q_val * s) + t]; } } in = in + (q_val * 360); index = 0; for (int col = 0; col < (mod * 2); col++) { offset = twist[col]; for (int row = 0; row < rows; row++) { tempv[offset + (rows * col)] = tempu[index++]; offset++; if (offset == rows) { offset = 0; } } } index = 0; for (int j = 0; j < rows; j++) { tempu[index++] = c1[j]; tempu[index++] = c2[j]; tempu[index++] = c3[j]; tempu[index++] = c4[j]; tempu[index++] = c5[j]; tempu[index++] = c6[j]; tempu[index++] = c7[j]; tempu[index++] = c8[j]; tempu[index++] = c9[j]; tempu[index++] = c10[j]; tempu[index++] = c11[j]; tempu[index++] = c12[j]; } index = 0; for (int d = 0; d < frame_size / (mod * 2); d++) { pack = 0; for (int e = 0; e < (mod * 2); e++) { offset = mux[e]; pack |= tempu[index++] << (((mod * 2) - 1) - offset); } out[produced++] = pack >> 6; out[produced++] = pack & 0x3f; consumed += (mod * 2); } } break; case MOD_256QAM: if (frame_size == FRAME_SIZE_NORMAL) { if (code_rate == C3_5) { mux = &mux256_35[0]; } else if (code_rate == C2_3) { mux = &mux256_23[0]; } else { mux = &mux256[0]; } for (int i = 0; i < noutput_items; i += packed_items) { rows = frame_size / (mod * 2); const unsigned char *c1, *c2, *c3, *c4, *c5, *c6, *c7, *c8; const unsigned char *c9, *c10, *c11, *c12, *c13, *c14, *c15, *c16; c1 = &tempv[0]; c2 = &tempv[rows]; c3 = &tempv[rows * 2]; c4 = &tempv[rows * 3]; c5 = &tempv[rows * 4]; c6 = &tempv[rows * 5]; c7 = &tempv[rows * 6]; c8 = &tempv[rows * 7]; c9 = &tempv[rows * 8]; c10 = &tempv[rows * 9]; c11 = &tempv[rows * 10]; c12 = &tempv[rows * 11]; c13 = &tempv[rows * 12]; c14 = &tempv[rows * 13]; c15 = &tempv[rows * 14]; c16 = &tempv[rows * 15]; for (int k = 0; k < nbch; k++) { tempu[k] = *in++; } for (int t = 0; t < q_val; t++) { for (int s = 0; s < 360; s++) { tempu[nbch + (360 * t) + s] = in[(q_val * s) + t]; } } in = in + (q_val * 360); index = 0; for (int col = 0; col < (mod * 2); col++) { offset = twist256n[col]; for (int row = 0; row < rows; row++) { tempv[offset + (rows * col)] = tempu[index++]; offset++; if (offset == rows) { offset = 0; } } } index = 0; for (int j = 0; j < rows; j++) { tempu[index++] = c1[j]; tempu[index++] = c2[j]; tempu[index++] = c3[j]; tempu[index++] = c4[j]; tempu[index++] = c5[j]; tempu[index++] = c6[j]; tempu[index++] = c7[j]; tempu[index++] = c8[j]; tempu[index++] = c9[j]; tempu[index++] = c10[j]; tempu[index++] = c11[j]; tempu[index++] = c12[j]; tempu[index++] = c13[j]; tempu[index++] = c14[j]; tempu[index++] = c15[j]; tempu[index++] = c16[j]; } index = 0; for (int d = 0; d < frame_size / (mod * 2); d++) { pack = 0; for (int e = 0; e < (mod * 2); e++) { offset = mux[e]; pack |= tempu[index++] << (((mod * 2) - 1) - offset); } out[produced++] = pack >> 8; out[produced++] = pack & 0xff; consumed += (mod * 2); } } } else { if (code_rate == C1_3) { mux = &mux256s_13[0]; } else if (code_rate == C2_5) { mux = &mux256s_25[0]; } else { mux = &mux256s[0]; } for (int i = 0; i < noutput_items; i += packed_items) { rows = frame_size / mod; const unsigned char *c1, *c2, *c3, *c4, *c5, *c6, *c7, *c8; c1 = &tempv[0]; c2 = &tempv[rows]; c3 = &tempv[rows * 2]; c4 = &tempv[rows * 3]; c5 = &tempv[rows * 4]; c6 = &tempv[rows * 5]; c7 = &tempv[rows * 6]; c8 = &tempv[rows * 7]; for (int k = 0; k < nbch; k++) { tempu[k] = *in++; } for (int t = 0; t < q_val; t++) { for (int s = 0; s < 360; s++) { tempu[nbch + (360 * t) + s] = in[(q_val * s) + t]; } } in = in + (q_val * 360); index = 0; for (int col = 0; col < mod; col++) { offset = twist256s[col]; for (int row = 0; row < rows; row++) { tempv[offset + (rows * col)] = tempu[index++]; offset++; if (offset == rows) { offset = 0; } } } index = 0; for (int j = 0; j < rows; j++) { tempu[index++] = c1[j]; tempu[index++] = c2[j]; tempu[index++] = c3[j]; tempu[index++] = c4[j]; tempu[index++] = c5[j]; tempu[index++] = c6[j]; tempu[index++] = c7[j]; tempu[index++] = c8[j]; } index = 0; for (int d = 0; d < frame_size / mod; d++) { pack = 0; for (int e = 0; e < mod; e++) { offset = mux[e]; pack |= tempu[index++] << ((mod - 1) - offset); } out[produced++] = pack & 0xff; consumed += mod; } } } break; } // Tell runtime system how many input items we consumed on // each input stream. consume_each (consumed); // Tell runtime system how many output items we produced. return noutput_items; } const int dvbt2_interleaver_bb_impl::twist16n[8] = { 0, 0, 2, 4, 4, 5, 7, 7 }; const int dvbt2_interleaver_bb_impl::twist64n[12] = { 0, 0, 2, 2, 3, 4, 4, 5, 5, 7, 8, 9 }; const int dvbt2_interleaver_bb_impl::twist256n[16] = { 0, 2, 2, 2, 2, 3, 7, 15, 16, 20, 22, 22, 27, 27, 28, 32 }; const int dvbt2_interleaver_bb_impl::twist16s[8] = { 0, 0, 0, 1, 7, 20, 20, 21 }; const int dvbt2_interleaver_bb_impl::twist64s[12] = { 0, 0, 0, 2, 2, 2, 3, 3, 3, 6, 7, 7 }; const int dvbt2_interleaver_bb_impl::twist256s[8] = { 0, 0, 0, 1, 7, 20, 20, 21 }; const int dvbt2_interleaver_bb_impl::mux16[8] = { 7, 1, 4, 2, 5, 3, 6, 0 }; const int dvbt2_interleaver_bb_impl::mux64[12] = { 11, 7, 3, 10, 6, 2, 9, 5, 1, 8, 4, 0 }; const int dvbt2_interleaver_bb_impl::mux256[16] = { 15, 1, 13, 3, 8, 11, 9, 5, 10, 6, 4, 7, 12, 2, 14, 0 }; const int dvbt2_interleaver_bb_impl::mux16_35[8] = { 0, 5, 1, 2, 4, 7, 3, 6 }; const int dvbt2_interleaver_bb_impl::mux16_13[8] = { 6, 0, 3, 4, 5, 2, 1, 7 }; const int dvbt2_interleaver_bb_impl::mux16_25[8] = { 7, 5, 4, 0, 3, 1, 2, 6 }; const int dvbt2_interleaver_bb_impl::mux64_35[12] = { 2, 7, 6, 9, 0, 3, 1, 8, 4, 11, 5, 10 }; const int dvbt2_interleaver_bb_impl::mux64_13[12] = { 4, 2, 0, 5, 6, 1, 3, 7, 8, 9, 10, 11 }; const int dvbt2_interleaver_bb_impl::mux64_25[12] = { 4, 0, 1, 6, 2, 3, 5, 8, 7, 10, 9, 11 }; const int dvbt2_interleaver_bb_impl::mux256_35[16] = { 2, 11, 3, 4, 0, 9, 1, 8, 10, 13, 7, 14, 6, 15, 5, 12 }; const int dvbt2_interleaver_bb_impl::mux256_23[16] = { 7, 2, 9, 0, 4, 6, 13, 3, 14, 10, 15, 5, 8, 12, 11, 1 }; const int dvbt2_interleaver_bb_impl::mux256s[8] = { 7, 3, 1, 5, 2, 6, 4, 0 }; const int dvbt2_interleaver_bb_impl::mux256s_13[8] = { 4, 0, 1, 2, 5, 3, 6, 7 }; const int dvbt2_interleaver_bb_impl::mux256s_25[8] = { 4, 0, 5, 1, 2, 3, 6, 7 }; } /* namespace dtv */ } /* namespace gr */ libs/window/include/sge/window/system.hpp // Copyright 2006 - 2019. // 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 SGE_WINDOW_SYSTEM_HPP_INCLUDED #define SGE_WINDOW_SYSTEM_HPP_INCLUDED #include #include #include #include #include #include #include #include #include #include #include namespace sge::window { class system { FCPPT_NONMOVABLE(system); public: SGE_WINDOW_DETAIL_SYMBOL explicit system(awl::system::reference); SGE_WINDOW_DETAIL_SYMBOL ~system(); [[nodiscard]] SGE_WINDOW_DETAIL_SYMBOL awl::system::event::result poll(); [[nodiscard]] SGE_WINDOW_DETAIL_SYMBOL awl::system::event::result next(); SGE_WINDOW_DETAIL_SYMBOL void quit(awl::main::exit_code); [[nodiscard]] SGE_WINDOW_DETAIL_SYMBOL fcppt::signal::auto_connection event_handler(sge::window::system_event_function &&); [[nodiscard]] SGE_WINDOW_DETAIL_SYMBOL awl::system::object &awl_system(); private: [[nodiscard]] awl::system::event::result transform_events(awl::system::event::result &&); awl::system::reference const awl_system_; using event_signal = fcppt::signal::object; event_signal event_signal_; }; } #endif 0 #ifndef PLAYSTATE_HPP #define PLAYSTATE_HPP #include //std::unique_ptr #include #include #include "gameState.hpp" #include "server.hpp" #include "component.hpp" class playStateClass : public gameStateClass { public: playStateClass(); void update(sf::RenderWindow& window) override; void draw(sf::RenderWindow& window) override; private: std::unique_ptr server; std::list listOfDirection; }; #endif test/code/scxcorelib/util/log/scxlogpolicy_test.cpp /*-------------------------------------------------------------------------------- Copyright (c) Microsoft Corporation. All rights reserved. */ /** \file \brief Tests the functionality of the log policy. \date 2008-09-02 14:49:05 */ /*----------------------------------------------------------------------------*/ #include #include #include /* This will include CPPUNIT helper macros too */ #include #include using namespace SCXCoreLib; class SCXLogPolicyTest : public CPPUNIT_NS::TestFixture { CPPUNIT_TEST_SUITE( SCXLogPolicyTest ); CPPUNIT_TEST( TestTestrunnerDefault ); CPPUNIT_TEST( TestTestrunnerDefaultLogFile ); CPPUNIT_TEST_SUITE_END(); private: public: void setUp(void) { } void tearDown(void) { } void TestTestrunnerDefault(void) { SCXHandle p = CustomLogPolicyFactory(); CPPUNIT_ASSERT(SCXFilePath(L"./scxlog.conf") == p->GetConfigFileName()); CPPUNIT_ASSERT(SCXFilePath(L"./scxtestrunner.log") == p->GetDefaultLogFileName()); CPPUNIT_ASSERT(eInfo == p->GetDefaultSeverityThreshold()); } void TestTestrunnerDefaultLogFile(void) { SCXLogHandle log = SCXLogHandleFactory::GetLogHandle(L"my.test.log.handle"); // Try to make the log item as unique as possible by appending a time to the message. // This time will then be used in comparison later on. SCXCalendarTime t = SCXCalendarTime::CurrentLocal(); SCX_LOGERROR(log, t.ToExtendedISO8601().append(L" - This is an error message")); SCX_LOGERROR(log, L"Looks like we need two messages here"); SCXHandle stream = SCXFile::OpenWFstream(CustomLogPolicyFactory()->GetDefaultLogFileName(), std::ios_base::in); SCXStream::NLF nlf; for (std::wstring logrow; SCXStream::IsGood(*stream); SCXStream::ReadLine(*stream, logrow, nlf)) { if (logrow.find(L"my.test.log.handle") != std::wstring::npos && logrow.find(t.ToExtendedISO8601().append(L" - This is an error message")) != std::wstring::npos) { // Test is ok. return; } } CPPUNIT_FAIL("Log message not written to file"); } }; CPPUNIT_TEST_SUITE_REGISTRATION( SCXLogPolicyTest ); // // // CPSC223 01 // Homework Assignment 2 // September 14, 2018 // ***************** // dropoff: mpeters4 // ***************** // Specification of ADT Item where // an Item is-a Key (technical computer science) // class Item is a derived or child class of class Key // data object: a meaning of a texting abbreviation // operations: create, destroy, copy create, copy // input, output #include "item.h" //allows for input of an item from either the standard input device or a file //pre input has been opened and readied for the input of // a texting abbreviation followed by newline and associated meaning with // spaces between words ending with a newline. For example: // lol // laugh out loud // //post rightHandSideItem has been filled with a texting abbreviation and its // associated meaning //usage cin >> myItem; istream& operator>> (istream& input, Item& rightHandSideItem){ char newline; input >> rightHandSideItem.textingAbbreviation; input.get(newline); getline(input,rightHandSideItem.textingMeaning); return input; } //allows for the output of an item to the standard output device or a file //pre rightHandSideItem has been filled with a texting abbreviation and // its associated meaning // output has been opened //post rightHandSideItem has been written to the output device // lol: laugh out loud // //usage outfile << myItem; ostream& operator<< (ostream& output, const Item& rightHandSideItem){ output << rightHandSideItem.textingAbbreviation << ": " << rightHandSideItem.textingMeaning << endl; return output; } //creates an empty item (texting abbreviation and its associated meaning) //post //usage Item aitem; Item::Item(){ } //releases memory for a texting abbreviation and its associated meaning //pre Item object exists //post Item object no longer exists, memory has been freed //usage automatically done at the end of scope Item::~Item(){ } //creates a new item and copies the right hand side item into item //pre Item object exists //post rightHandSideItem is copied into new item //usage Item myItem(yourItem); Item::Item(const Item& rightHandSideItem){ textingMeaning = rightHandSideItem.textingMeaning; textingAbbreviation = rightHandSideItem.textingAbbreviation; } //copies rightHandSideItem's member variables into an existing item //pre Item object exists //post Item object contains the member variables from rightHandSideItem //usage exampleItem = secondItem; Item& Item::operator=(const Item& rightHandSideItem){ if(this != &rightHandSideItem) textingAbbreviation = rightHandSideItem.textingAbbreviation; textingMeaning = rightHandSideItem.textingMeaning; return *this; } 1-10 /* * * Copyright 2006-2022, . * Distributed under the terms of the MIT License. * * Authors: * <> */ #include "FixedText.h" #include static BFont* fixed_font=NULL; #define FAMILY "ProFont" #define STYLE "Regular" #define SIZE 12 static bool setFixedFont(){ BFont font; font.SetFamilyAndStyle(FAMILY,STYLE); font_family family; font_style style; font.GetFamilyAndStyle(&family,&style); font.SetSize(SIZE); if(strncmp(family,FAMILY,strlen(family))==0 && strncmp(style,STYLE,strlen(style)) == 0) { fixed_font=new BFont(font); return true; } return false; } FixedText::FixedText(BRect rect,const char* text): BStringView(rect,"_fixed",text,B_FOLLOW_NONE,B_WILL_DRAW){ if(fixed_font==NULL && !setFixedFont()) SetFont(be_plain_font); // debugger("can't find ProFont installed!!"); else SetFont(fixed_font); } // #include "ErrorNotifier.h" const std::map ErrorNotifier::errorMessageMap = { {GlobalError::NO_INPUT, "Error: No input file\n"}, {GlobalError::NO_TRANSTABLE, "Error: No transTable.csv found in the working path.\n"}, {GlobalError::NO_OUTPUT, "Error: Invalid output file, result will display on the screen." } }; void ErrorNotifier::showError (GlobalError error) { auto result = errorMessageMap.find (error); if (result == errorMessageMap.end ()) { printf ("Error: Unkown error.\n"); } else { printf ("%s", result->second.c_str()); // Error message found in map } } /* * Copyright (c) 2012-, * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * - Neither the name of the author nor the names of 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 "codegen/llvm.hpp" namespace { using namespace llvm; using isana::codegen::module_ref; Function *add_function( const std::string &name, FunctionType *type, module_ref &m, GlobalValue::LinkageTypes link) { return Function::Create(type, link, name.c_str(), m.get()); } } namespace isana { namespace codegen { module_map defmodule::m_table_ = module_map(); module_ref &defmodule::create(const std::string &str) { module_map::iterator it = m_table_.find(str); if (it != m_table_.end()) return it->second; m_table_.insert(std::make_pair(str, module_ref(new Module(str, context())))); module_map::iterator m = m_table_.find(str); return m->second; } module_ref &defmodule::get(const std::string &str) { module_map::iterator it = m_table_.find(str); if (it == m_table_.end()) std::runtime_error("Undefined module called: " + str); return it->second; } ExecutionEngine *defmodule::execute(const module_ref &m) { std::string errstr; ExecutionEngine* ee = EngineBuilder(m.get()).setErrorStr(&errstr).create(); if (!ee) { std::cerr << "Could not execute: " << errstr.c_str() << std::endl; exit(1); } return ee; } /* --- */ struct_map defstruct::s_table_ = struct_map(); StructType *defstruct::create(const type_list &mems, const std::string &str) { StructType *s; if (str.empty()) s = StructType::create(mems); else s = StructType::create(mems, str); if (!s) std::cout << "null!" << std::endl; s->setBody(mems); s_table_.insert(std::make_pair(str, s)); return s; } StructType *defstruct::get(const std::string &str) { struct_map::iterator it = s_table_.find(str); if (it == s_table_.end()) std::runtime_error("Undefined data type called: " + str); return it->second; } /* --- */ FunctionType *get_ftype(Type *ret, type_list &args, bool varg) { return FunctionType::get(ret, args, varg); } Function *add_external_function( const std::string &name, FunctionType *type, module_ref &m) { return add_function(name, type, m, Function::ExternalLinkage); } Function *add_internal_function( const std::string &name, FunctionType *type, module_ref &m) { return add_function(name, type, m, Function::InternalLinkage); } BasicBlock *add_block( const std::string &name, Function *f) { BasicBlock *bb = BasicBlock::Create(f->getContext(), name, f); f->setGC("shadow-stack"); return bb; } const std::string get_function_name(Function *f) { const std::string mname = f->getParent()->getModuleIdentifier(), fname = f->getName(); std::ostringstream oss; oss << "#<" << mname << "/" << fname << ">"; return oss.str(); } } /* end of codegen */ } /* end of isana */ /* * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * * Copyright (c) 2017 * * 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 "EventModel.h" #include "microbit/microbitdal.h" #include "microbit/modmicrobit.h" extern "C" { extern void microbit_accelerometer_event_handler(const MicroBitEvent*); } class MicroPythonEventHandler : public EventModel { public: MicroPythonEventHandler(); virtual int send(MicroBitEvent evt); }; // Create a static instance of our custom event handler static MicroPythonEventHandler event_handler; MicroPythonEventHandler::MicroPythonEventHandler() { // We take full control of the event bus EventModel::defaultEventBus = this; } int MicroPythonEventHandler::send(MicroBitEvent evt) { // Dispatch the event to the relevant component switch (evt.source) { case MICROBIT_ID_GESTURE: microbit_accelerometer_event_handler(&evt); break; case MICROBIT_ID_COMPASS: if (evt.value == MICROBIT_COMPASS_EVT_CALIBRATE) { ubit_compass_calibrator.calibrate(evt); } break; default: // Ignore this event break; } return MICROBIT_OK; } mauguignard/cbmc int main() { int a; assert(&a); } CArray myArray1, myArray2; // Add elements to the second array. myArray2.Add(CPoint(11, 22)); myArray2.Add(CPoint(12, 42)); // Add elements to the first array and also append the second array. myArray1.Add(CPoint(1, 2)); myArray1.Append(myArray2);#include #include #ifndef __CFL_VEC_H__ #define __CFL_VEC_H__ template class Vec { size_t cap = 4; size_t len = 0; T *arr; inline void reallocate(); public: Vec() noexcept; explicit Vec(size_t n); Vec(size_t n, const T &val); template Vec(InputIt first, InputIt last); Vec(const Vec &); ~Vec(); Vec &operator=(const Vec &); void assign(size_t, const T &value); template void assign(InputIt, InputIt); T* begin() noexcept; const T *cbegin() const noexcept; T* end() noexcept; const T *cend() const noexcept; bool empty() const noexcept; size_t size() const noexcept; size_t capacity() const noexcept; void resize(size_t); void resize(size_t, const T &); void reserve(size_t); void shrink_to_fit(); T &operator[](size_t); const T &operator[](size_t) const; T &at(size_t); const T &at(size_t) const; T &front(); const T &front() const; T &back(); const T &back() const; T *data() noexcept; const T *data() const noexcept; void push_back(const T &); void pop_back(); T* insert(const T *, const T &); T* insert(const T *, size_t, const T &); template T* insert(const T *, InputIt, InputIt); T* erase(const T *); T* erase(const T *, const T *); void swap(Vec &); void clear() noexcept; bool operator==(const Vec &) const; bool operator!=(const Vec &) const; bool operator<(const Vec &) const; bool operator<=(const Vec &) const; bool operator>(const Vec &) const; bool operator>=(const Vec &) const; }; template Vec::Vec() noexcept { arr = new T[cap]; } template Vec::Vec(size_t n) { size_t i; cap = n; arr = new T[cap]; for (i = 0; i < n; ++i) arr[i] = T(); len = n; } template Vec::Vec(size_t n, const T &value) { size_t i; cap = n; arr = new T[cap]; for (i = 0; i < n; ++i) arr[i] = value; len = n; } template template Vec::Vec(InputIt first, InputIt last) { size_t i, count = last - first; cap = count; len = count; arr = new T[cap]; for (i = 0; i < count; ++i, ++first) arr[i] = *first; } template Vec::Vec(const Vec &other) { size_t i; cap = other.cap; arr = new T[cap]; for (i = 0; i < other.len; ++i) arr[i] = other.arr[i]; len = other.len; } template Vec::~Vec() { delete[] arr; } template Vec &Vec::operator=(const Vec &other) { if (this == &other) { return *this; } size_t i; if (cap < other.len) { cap = other.len; reallocate(); } for (i = 0; i < other.len; ++i) arr[i] = other.arr[i]; len = other.len; } template void Vec::assign(size_t count, const T &value) { size_t i; if (count > cap) { cap = count; reallocate(); } for (i = 0; i < count; ++i) arr[i] = value; len = count; } template template void Vec::assign(InputIt first, InputIt last) { size_t i, count = last - first; if (count > cap) { cap = count; reallocate(); } for (i = 0; i < count; ++i, ++first) arr[i] = *first; len = count; } template T* Vec::begin() noexcept { return arr; } template const T *Vec::cbegin() const noexcept { return arr; } template T* Vec::end() noexcept { return arr + len; } template const T *Vec::cend() const noexcept { return arr + len; } template inline void Vec::reallocate() { T *tarr = new T[cap]; memcpy(tarr, arr, len * sizeof(T)); delete[] arr; arr = tarr; } template bool Vec::empty() const noexcept { return len == 0; } template size_t Vec::size() const noexcept { return len; } template size_t Vec::capacity() const noexcept { return cap; } template void Vec::resize(size_t sz) { if (sz > len) { if (sz > cap) { cap = sz; reallocate(); } } else { size_t i; for (i = len; i < sz; ++i) arr[i].~T(); } len = sz; } template void Vec::resize(size_t sz, const T &c) { if (sz > len) { if (sz > cap) { cap = sz; reallocate(); } size_t i; for (i = len; i < sz; ++i) arr[i] = c; } else { size_t i; for (i = len; i < sz; ++i) arr[i].~T(); } len = sz; } template void Vec::reserve(size_t _sz) { if (_sz > cap) { cap = _sz; reallocate(); } } template void Vec::shrink_to_fit() { cap = len; reallocate(); } template T &Vec::operator[](size_t idx) { return arr[idx]; } template const T &Vec::operator[](size_t idx) const { return arr[idx]; } template T &Vec::at(size_t pos) { return arr[pos]; } template const T &Vec::at(size_t pos) const { return arr[pos]; } template T &Vec::front() { return arr[0]; } template const T &Vec::front() const { return arr[0]; } template T &Vec::back() { return arr[len - 1]; } template const T &Vec::back() const { return arr[len - 1]; } template T *Vec::data() noexcept { return arr; } template const T *Vec::data() const noexcept { return arr; } template void Vec::push_back(const T &val) { if (len == cap) { cap *= 2; reallocate(); } arr[len] = val; ++len; } template void Vec::pop_back() { --len; arr[len].~T(); } template T* Vec::insert(const T *it, const T &val) { T* iit = &arr[it - arr]; if (len == cap) { cap *= 2; reallocate(); } memmove(iit + 1, iit, (len - (it - arr)) * sizeof(T)); (*iit) = val; ++len; return iit; } template T* Vec::insert(const T *it, size_t cnt, const T &val) { T* f = &arr[it - arr]; if (!cnt) return f; if (len + cnt > cap) { cap = (len + cnt); reallocate(); } memmove(f + cnt, f, (len - (it - arr)) * sizeof(T)); len += cnt; for (T* it = f; cnt--; ++it) (*it) = val; return f; } template template T* Vec::insert(const T *it, InputIt first, InputIt last) { T* f = &arr[it - arr]; size_t cnt = last - first; if (!cnt) return f; if (len + cnt > cap) { cap = (len + cnt); reallocate(); } memmove(f + cnt, f, (len - (it - arr)) * sizeof(T)); for (T* it = f; first != last; ++it, ++first) (*it) = *first; len += cnt; return f; } template T* Vec::erase(const T *it) { T* iit = &arr[it - arr]; (*iit).~T(); memmove(iit, iit + 1, (len - (it - arr) - 1) * sizeof(T)); --len; return iit; } template T* Vec::erase(const T *first, const T *last) { T* f = &arr[first - arr]; if (first == last) return f; for (; first != last; ++first) (*first).~T(); memmove(f, last, (len - (last - arr)) * sizeof(T)); len -= last - first; return f; } template void Vec::swap(Vec &rhs) { size_t tlen = len, tcap = cap; T *tarr = arr; len = rhs.len; cap = rhs.cap; arr = rhs.arr; rhs.len = tlen; rhs.cap = tcap; rhs.arr = tarr; } template void Vec::clear() noexcept { size_t i; for (i = 0; i < len; ++i) arr[i].~T(); len = 0; } template bool Vec::operator==(const Vec &rhs) const { if (len != rhs.len) return false; size_t i; for (i = 0; i < len; ++i) if (arr[i] != rhs.arr[i]) return false; return true; } template bool Vec::operator!=(const Vec &rhs) const { if (len != rhs.len) return true; size_t i; for (i = 0; i < len; ++i) if (arr[i] != rhs.arr[i]) return true; return false; } template bool Vec::operator<(const Vec &rhs) const { size_t i, j, ub = len < rhs.len ? len : rhs.len; for (i = 0; i < ub; ++i) if (arr[i] != rhs.arr[i]) return arr[i] < rhs.arr[i]; return len < rhs.len; } template bool Vec::operator<=(const Vec &rhs) const { size_t i, j, ub = len < rhs.len ? len : rhs.len; for (i = 0; i < ub; ++i) if (arr[i] != rhs.arr[i]) return arr[i] < rhs.arr[i]; return len <= rhs.len; } template bool Vec::operator>(const Vec &rhs) const { size_t i, j, ub = len < rhs.len ? len : rhs.len; for (i = 0; i < ub; ++i) if (arr[i] != rhs.arr[i]) return arr[i] > rhs.arr[i]; return len > rhs.len; } template bool Vec::operator>=(const Vec &rhs) const { size_t i, j, ub = len < rhs.len ? len : rhs.len; for (i = 0; i < ub; ++i) if (arr[i] != rhs.arr[i]) return arr[i] > rhs.arr[i]; return len >= rhs.len; } #endif1-10 #include using namespace std; typedef long long int ll; typedef pair P; typedef pair Pll; typedef vector Vi; //typedef tuple T; #define FOR(i,s,x) for(int i=s;i<(int)(x);i++) #define REP(i,x) FOR(i,0,x) #define ALL(c) c.begin(), c.end() #define DUMP( x ) cerr << #x << " = " << ( x ) << endl const int dr[4] = {-1, 0, 1, 0}; const int dc[4] = {0, 1, 0, -1}; int main() { // use scanf in CodeForces! cin.tie(0); ios_base::sync_with_stdio(false); int N; cin >> N; vector H(N+1); REP(i, N) cin >> H[i+1]; H[0] = 1000001; vector> dp(N+1, vector(2, 0)); REP(i, N) { int l = i; while (H[i+1] > H[l]) l = dp[l][1]; dp[i+1][0] = dp[l][0] + 1; dp[i+1][1] = l; } REP(i, N) cout << dp[i][0] << endl; return 0; } #include #include #include #include #include class PrimeNumberContainer { private: std::vector container; private: void readNumbersAndAssign() { std::fstream FILE; try { FILE.open("PrimeNumbers", std::ios::in); if (!FILE) throw "File can't be opened!"; } catch (std::exception& e) { std::cerr << e.what() << std::endl; system("pause"); } while (FILE) { std::string newLine; getline(FILE, newLine); if (newLine == "") { break; } container.push_back(stoi(newLine)); } FILE.close(); } public: PrimeNumberContainer() { readNumbersAndAssign(); } std::pair getPrimes(long key) { int first_choice = (key % 30) % (container.size() - 1); int second_choice = (key % 55) % (container.size() - 1); return std::make_pair(container[first_choice], container[second_choice]); } };indexer/indexer_tests/cities_boundaries_serdes_tests.cpp1000+ #include "testing/testing.hpp" #include "indexer/cities_boundaries_serdes.hpp" #include "indexer/city_boundary.hpp" #include "coding/geometry_coding.hpp" #include "coding/reader.hpp" #include "coding/writer.hpp" #include "geometry/mercator.hpp" #include "geometry/point2d.hpp" #include #include #include using namespace indexer; using namespace m2; using namespace serial; using namespace std; namespace { using Boundary = vector; using Boundaries = vector; static_assert(CitiesBoundariesSerDes::kLatestVersion == 0, ""); static_assert(CitiesBoundariesSerDes::HeaderV0::kDefaultCoordBits == 19, ""); struct Result { Result(Boundaries const & boundaries, double eps) : m_boundaries(boundaries), m_eps(eps) {} Boundaries m_boundaries; double m_eps = 0.0; }; void TestEqual(vector const & lhs, vector const & rhs, double eps) { TEST_EQUAL(lhs.size(), rhs.size(), (lhs, rhs)); for (size_t i = 0; i < lhs.size(); ++i) TEST(AlmostEqualAbs(lhs[i], rhs[i], eps), (lhs, rhs)); } void TestEqual(BoundingBox const & lhs, BoundingBox const & rhs, double eps) { TEST(AlmostEqualAbs(lhs.Min(), rhs.Min(), eps), (lhs, rhs)); TEST(AlmostEqualAbs(lhs.Max(), rhs.Max(), eps), (lhs, rhs)); } void TestEqual(CalipersBox const & lhs, CalipersBox const & rhs, double eps) { TestEqual(lhs.Points(), rhs.Points(), eps); } void TestEqual(DiamondBox const & lhs, DiamondBox const & rhs, double eps) { auto const lps = lhs.Points(); auto const rps = rhs.Points(); TEST_EQUAL(lps.size(), 4, (lhs)); TEST_EQUAL(rps.size(), 4, (rhs)); TestEqual(lps, rps, eps); } void TestEqual(CityBoundary const & lhs, CityBoundary const & rhs, double eps) { TestEqual(lhs.m_bbox, rhs.m_bbox, eps); TestEqual(lhs.m_cbox, rhs.m_cbox, eps); TestEqual(lhs.m_dbox, rhs.m_dbox, eps); } void TestEqual(Boundary const & lhs, Boundary const & rhs, double eps) { TEST_EQUAL(lhs.size(), rhs.size(), (lhs, rhs)); for (size_t i = 0; i < lhs.size(); ++i) TestEqual(lhs[i], rhs[i], eps); } void TestEqual(Boundaries const & lhs, Boundaries const & rhs, double eps) { TEST_EQUAL(lhs.size(), rhs.size(), (lhs, rhs)); for (size_t i = 0; i < lhs.size(); ++i) TestEqual(lhs[i], rhs[i], eps); } Result EncodeDecode(Boundaries const & boundaries) { vector buffer; { MemWriter sink(buffer); CitiesBoundariesSerDes::Serialize(sink, boundaries); } { Boundaries boundaries; double precision; MemReader reader(buffer.data(), buffer.size()); NonOwningReaderSource source(reader); CitiesBoundariesSerDes::Deserialize(source, boundaries, precision); return Result(boundaries, precision); } } void TestEncodeDecode(Boundaries const & expected) { auto const r = EncodeDecode(expected); TestEqual(expected, r.m_boundaries, r.m_eps); } UNIT_TEST(CitiesBoundariesSerDes_Smoke) { { Boundaries const expected; TestEncodeDecode(expected); } { Boundary boundary0; boundary0.emplace_back(vector{{PointD(0.1234, 5.6789)}}); boundary0.emplace_back(vector{{PointD(3.1415, 2.1828), PointD(2.1828, 3.1415)}}); Boundary boundary1; boundary1.emplace_back( vector{{PointD(1.000, 1.000), PointD(1.002, 1.000), PointD(1.002, 1.003)}}); Boundaries const expected = {{boundary0, boundary1}}; TestEncodeDecode(expected); } } UNIT_TEST(CitiesBoundaries_Moscow) { vector const points = {{37.04001, 67.55964}, {37.55650, 66.96428}, {38.02513, 67.37082}, {37.50865, 67.96618}}; m2::PointD const target(37.44765, 67.65243); vector buffer; { CityBoundary boundary(points); TEST(boundary.HasPoint(target), ()); MemWriter sink(buffer); CitiesBoundariesSerDes::Serialize(sink, {{boundary}}); } { Boundaries boundaries; double precision; MemReader reader(buffer.data(), buffer.size()); NonOwningReaderSource source(reader); CitiesBoundariesSerDes::Deserialize(source, boundaries, precision); TEST_EQUAL(boundaries.size(), 1, ()); TEST_EQUAL(boundaries[0].size(), 1, ()); TEST(boundaries[0][0].HasPoint(target, precision), ()); } } } // namespace #include "Debugger.h" #include "Types.h" #include "imgui_memory_editor.h" unsigned WIDTH = 1000; unsigned HEIGHT = 1000; Debugger::Debugger(Cpu* cpu, Ppu* ppu, MemoryController* memoryController) { this->cpu = cpu; this->ppu = ppu; this->memoryController = memoryController; if(SDL_Init(SDL_INIT_EVERYTHING) != 0) { std::cout << "Could not initialize SDL2: " << SDL_GetError() << std::endl; return; } window = SDL_CreateWindow("JimBoy - Debugger", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, WIDTH, HEIGHT, SDL_WINDOW_RESIZABLE); if (window == NULL) { std::cout << "Could not create window: " << SDL_GetError() << std::endl; return; } renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED); if (renderer == NULL) { std::cout << "Could not create renderer: " << SDL_GetError() << std::endl; return; } ImGui::CreateContext(); ImGuiSDL::Initialize(renderer, WIDTH, HEIGHT); } Debugger::~Debugger() { ImGuiSDL::Deinitialize(); SDL_DestroyRenderer(renderer); SDL_DestroyWindow(window); ImGui::DestroyContext(); } void Debugger::Update(unsigned cycles) { if (mode == IDLE || mode == STEP) { Idle(cycles); } else { if (std::find(breakpoints.begin(), breakpoints.end(), cpu->pc) != breakpoints.end()) { mode = IDLE; Idle(cycles); } if (animate) RenderWindows(cycles); } } void Debugger::Idle(unsigned cycles) { std::chrono::time_point current, previous; previous = std::chrono::high_resolution_clock::now(); mode = IDLE; while (mode == IDLE && !quit) { current = std::chrono::high_resolution_clock::now(); auto elapsed = std::chrono::duration_cast> (current - previous); previous = current; RenderWindows(cycles); static float DELAY_TIME = 1000.0f / 59.9f; if (elapsed.count() < DELAY_TIME) { std::this_thread::sleep_for(std::chrono::duration(DELAY_TIME - elapsed.count())); } } } void Debugger::HandleInput() { SDL_Event event; ImGuiIO& io = ImGui::GetIO(); while(SDL_PollEvent(&event)) { if (event.type == SDL_KEYDOWN) { if (event.key.keysym.sym == SDLK_ESCAPE) { ExitDebugger(); } io.KeysDown[event.key.keysym.scancode] = true; } if (event.type == SDL_KEYUP) { io.KeysDown[event.key.keysym.scancode] = false; } if (SDL_TEXTINPUT) { io.AddInputCharactersUTF8(event.text.text); } if (event.type == SDL_QUIT) { ExitDebugger(); } else if (event.type == SDL_WINDOWEVENT) { if (event.window.event == SDL_WINDOWEVENT_SIZE_CHANGED) { io.DisplaySize.x = static_cast(event.window.data1); io.DisplaySize.y = static_cast(event.window.data2); } } } int mouseX, mouseY; const int buttons = SDL_GetMouseState(&mouseX, &mouseY); io.DeltaTime = 1.0f / 60.0f; io.MousePos = ImVec2(static_cast(mouseX), static_cast(mouseY)); io.MouseDown[0] = buttons & SDL_BUTTON(SDL_BUTTON_LEFT); io.MouseDown[1] = buttons & SDL_BUTTON(SDL_BUTTON_RIGHT); io.KeyMap[ImGuiKey_Enter] = SDL_SCANCODE_RETURN; io.KeyMap[ImGuiKey_Backspace] = SDL_SCANCODE_BACKSPACE; } void Debugger::RenderWindows(unsigned cycles) { HandleInput(); float frame_rate = ImGui::GetIO().Framerate; float frame_time = 1000.0f / frame_rate; char title_buffer[128]; snprintf(title_buffer, sizeof(title_buffer), "JimBoy - %.3f ms/frame (%.1f FPS)", frame_rate, frame_time); SDL_SetWindowTitle(window, title_buffer); ImGui::NewFrame(); SDL_RenderClear(renderer); ImGui::SetNextWindowPos({20, 50}); ImGui::SetNextWindowSize({450, 530}); CreateCpuWindow(cycles); ImGui::SetNextWindowPos({500, 50}); ImGui::SetNextWindowSize({500, 220}); CreateCartridgeWindow(); ImGui::SetNextWindowPos({500, 300}); ImGui::SetNextWindowSize({500, 220}); CreatePpuWindow(); //ImGui::SetNextWindowPos({1100, 50}); //CreateMemoryWindow(); ImGui::Render(); ImGuiSDL::Render(ImGui::GetDrawData()); SDL_RenderPresent(renderer); } void Debugger::CreateCpuWindow(unsigned cycles) { ImGui::Begin("CPU"); if (ImGui::Button("Start")) { mode = RUNNING; } ImGui::SameLine(); if (ImGui::Button("Pause")) { mode = IDLE; } ImGui::SameLine(); if (ImGui::Button("Step")) { mode = STEP; } ImGui::SameLine(); ImGui::Checkbox("Animate", &animate); ImGui::AlignTextToFramePadding(); ImGui::Text("Breakpoint"); ImGui::SameLine(); char input_breakpoint[64]; memset(input_breakpoint, 0, sizeof(char) * 64); if (ImGui::InputText("##hidelabel", input_breakpoint, 64, ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_CharsUppercase | ImGuiInputTextFlags_EnterReturnsTrue)) { int addr; if (sscanf_s(input_breakpoint, "%X", &addr)) { uint16_t address = addr & 0xFFFF; breakpoints.push_back(address); } } ImGui::Separator(); ImGui::Columns(2, "instruction"); uint8_t opcode = cpu->read(cpu->pc); bool prefix = false; if (opcode == 0xCB) { opcode = cpu->read(cpu->pc + 1); prefix = true; ImGui::Text("Opcode: 0xCB%02X", opcode); } else { ImGui::Text("Opcode: 0x%02X", opcode); } ImGui::Text("Instruction: %s", getInstruction(opcode, prefix).c_str()); ImGui::NextColumn(); ImGui::Text("Cycles: %d", cycles); ImGui::NextColumn(); ImGui::Columns(1); ImGui::Separator(); ImGui::Text("Registers:"); ImGui::Separator(); ImGui::Columns(2, "registers"); ImGui::Text("AF: 0x%04X", cpu->registers.getAF()); ImGui::Text("DE: 0x%04X", cpu->registers.getDE()); ImGui::Text("PC: 0x%04X", cpu->pc); ImGui::NextColumn(); ImGui::Text("BC: 0x%04X", cpu->registers.getBC()); ImGui::Text("HL: 0x%04X", cpu->registers.getHL()); ImGui::Text("SP: 0x%04X", cpu->sp); ImGui::NextColumn(); ImGui::Columns(1); ImGui::Separator(); ImGui::Text("Flags:"); ImGui::Separator(); ImGui::Columns(4, "flags"); ImGui::Text("Zero"); ImGui::Text(cpu->registers.getFlag(ZERO) ? "1" : "0"); ImGui::NextColumn(); ImGui::Text("Sub"); ImGui::Text(cpu->registers.getFlag(SUB) ? "1" : "0"); ImGui::NextColumn(); ImGui::Text("Half Carry"); ImGui::Text(cpu->registers.getFlag(HALF) ? "1" : "0"); ImGui::NextColumn(); ImGui::Text("Carry"); ImGui::Text(cpu->registers.getFlag(CARRY) ? "1" : "0"); ImGui::NextColumn(); ImGui::Columns(1); ImGui::Separator(); ImGui::Text("Breakpoints:"); ImGui::Separator(); ImGui::Columns(4, "breakpoints"); ImGui::Text("Address"); ImGui::NextColumn(); ImGui::Text("Mnemonic"); ImGui::NextColumn(); ImGui::Text("Opcode"); ImGui::NextColumn(); ImGui::Text("Cycles"); ImGui::NextColumn(); ImGui::Separator(); std::vector currentBreakpoints = breakpoints; for (uint16_t breakpoint : currentBreakpoints) { uint8_t opcode = cpu->read(breakpoint); ImGui::Text("0x%04X", breakpoint); ImGui::NextColumn(); ImGui::Text(getInstruction(opcode, false).c_str()); ImGui::NextColumn(); ImGui::Text("0x%04X", opcode); ImGui::NextColumn(); ImGui::Text("%d", getCycle(opcode, false, false)); ImGui::NextColumn(); } ImGui::Columns(1); ImGui::Separator(); ImGui::AlignTextToFramePadding(); ImGui::Text("Remove breakpoint"); ImGui::SameLine(); char input_remove[64]; memset(input_remove, 0, sizeof(char) * 64); if (ImGui::InputText("##hidelabel1", input_remove, 64, ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_CharsUppercase | ImGuiInputTextFlags_EnterReturnsTrue)) { int addr; if (sscanf_s(input_remove, "%X", &addr)) { uint16_t address = addr & 0xFFFF; breakpoints.erase(std::remove(breakpoints.begin(), breakpoints.end(), address), breakpoints.end()); } } ImGui::Separator(); ImGui::Text("Interrupts:"); ImGui::Separator(); ImGui::Text("IME: %s", cpu->ime ? "True" : "False"); ImGui::Separator(); // IE ImGui::Text("Interrupts Enable:"); ImGui::Separator(); ImGui::Columns(5, "interrupts_ie"); ImGui::Text("V-Blank:"); ImGui::Text("%d", cpu->interrupts.getIe(VBLANK)); ImGui::NextColumn(); ImGui::Text("LCD:"); ImGui::Text("%d", cpu->interrupts.getIe(LCD)); ImGui::NextColumn(); ImGui::Text("Timer:"); ImGui::Text("%d", cpu->interrupts.getIe(TIMER)); ImGui::NextColumn(); ImGui::Text("Serial:"); ImGui::Text("%d", cpu->interrupts.getIe(SERIAL)); ImGui::NextColumn(); ImGui::Text("Joypad:"); ImGui::Text("%d", cpu->interrupts.getIe(JOYPAD)); ImGui::NextColumn(); ImGui::Columns(1); ImGui::Separator(); ImGui::Text("Interrupts Request Flag:"); ImGui::Separator(); ImGui::Columns(5, "interrupts_if"); ImGui::Text("V-Blank:"); ImGui::Text("%d", cpu->interrupts.getIf(VBLANK)); ImGui::NextColumn(); ImGui::Text("LCD:"); ImGui::Text("%d", cpu->interrupts.getIf(LCD)); ImGui::NextColumn(); ImGui::Text("Timer:"); ImGui::Text("%d", cpu->interrupts.getIf(TIMER)); ImGui::NextColumn(); ImGui::Text("Serial:"); ImGui::Text("%d", cpu->interrupts.getIf(SERIAL)); ImGui::NextColumn(); ImGui::Text("Joypad:"); ImGui::Text("%d", cpu->interrupts.getIf(JOYPAD)); ImGui::NextColumn(); ImGui::Columns(1); ImGui::Separator(); ImGui::Text("Application info: %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate); ImGui::End(); } void Debugger::CreatePpuWindow() { ImGui::Begin("PPU"); ImGui::Columns(2, "ppu_main"); // LCD Control ImGui::Text("LCD Control:"); ImGui::Text("0x%04X", ppu->getRegister(LCDC)); ImGui::NextColumn(); // LCD Status ImGui::Text("LCD Status:"); ImGui::Text("0x%04X", ppu->getRegister(STAT)); ImGui::NextColumn(); ImGui::Columns(1); ImGui::Separator(); ImGui::Columns(2, "ppu_d"); // SCY - SCX ImGui::Text("SCY - SCX:"); ImGui::Text("0x%04X - 0x%04X", ppu->getRegister(SCY), ppu->getRegister(SCX)); ImGui::NextColumn(); // WY - WX ImGui::Text("WY - WX:"); ImGui::Text("0x%04X - 0x%04X", ppu->getRegister(WY), ppu->getRegister(WX)); ImGui::NextColumn(); ImGui::NextColumn(); ImGui::Columns(1); ImGui::Separator(); ImGui::Columns(3, "ppu_misc"); // LY ImGui::Text("LY:"); ImGui::Text("0x%04X", ppu->getRegister(LY)); ImGui::NextColumn(); // LYC ImGui::Text("LYC:"); ImGui::Text("0x%04X", ppu->getRegister(LYC)); ImGui::NextColumn(); // BGP ImGui::Text("BGP"); ImGui::Text("0x%04X", ppu->getRegister(BGP)); ImGui::NextColumn(); ImGui::Columns(1); ImGui::Separator(); ImGui::Columns(2, "ppu_obp"); // OBP0 ImGui::Text("OBP0"); ImGui::Text("0x%04X", ppu->getRegister(OBP0)); ImGui::NextColumn(); // OBP1 ImGui::Text("OBP1"); ImGui::Text("0x%04X", ppu->getRegister(OBP1)); ImGui::NextColumn(); ImGui::Columns(1); ImGui::Separator(); ImGui::End(); } void Debugger::CreateCartridgeWindow() { CartridgeInfo* cartInfo = &memoryController->cartridge->cartInfo; ImGui::Begin("Cartridge"); ImGui::Text("Information:"); ImGui::Separator(); ImGui::Columns(2, "basic_info"); ImGui::Text("Title: %s", cartInfo->title); ImGui::Text("Supports SGB:"); ImGui::SameLine(); ImGui::Text(cartInfo->sgbFlag ? "True" : "False"); ImGui::Text("Version Number: %d", cartInfo->versionNumber); ImGui::Text("Destination Code:"); ImGui::SameLine(); ImGui::Text(cartInfo->destinationCode == 1 ? "Non-Japanese" : "Japanese"); if (cartInfo->sgbFlag) { ImGui::Text("Licensee Code: %s", cartridgeNewLicencee.at((int)cartInfo->newLicenseeCode).c_str()); } else { ImGui::Text("Licensee Code: %s", cartridgeOldLicencee.at(cartInfo->oldLicenseeCode).c_str()); } ImGui::NextColumn(); ImGui::Text("File Size: %dKB", cartInfo->fileSize / 1000); ImGui::Text("ROM Type: %s", cartridgeType.at(cartInfo->romType).c_str()); ImGui::Text("ROM Size: %dKB", cartridgeRomSize.at(cartInfo->romSize)[0]); ImGui::Text("ROM Banks: %d", cartridgeRomSize.at(cartInfo->romSize)[1]); ImGui::Text("RAM Size: %dKB", cartridgeRamSize[cartInfo->ramSize]); ImGui::NextColumn(); ImGui::Columns(1); ImGui::Separator(); ImGui::Text("Checksums:"); ImGui::Separator(); ImGui::Columns(2, "checksums"); ImGui::Text("Checksum: %d", cartInfo->checksum); ImGui::Text("Calculated Checksum: %d", cartInfo->calculatedChecksum); ImGui::Text("Checksum checks out:"); ImGui::SameLine(); ImGui::Text((cartInfo->checksum == cartInfo->calculatedChecksum) ? "True" : "False"); ImGui::NextColumn(); ImGui::Text("Global Checksum: %d", cartInfo->globalChecksum); ImGui::Text("Calculated Global Checksum: %d", cartInfo->calculatedGlobalChecksum); ImGui::Text("Gloabl Checksum checks out:"); ImGui::SameLine(); ImGui::Text((cartInfo->globalChecksum == cartInfo->calculatedGlobalChecksum) ? "True" : "False"); ImGui::NextColumn(); ImGui::Columns(1); ImGui::End(); } void Debugger::CreateMemoryWindow() { static MemoryEditor mem_edit; ImGui::Begin("Memory"); //mem_edit.DrawContents(memoryController->cartridge->rom, 0x8000, 0x0); ImGui::End(); } void Debugger::ExitDebugger() { //delete this; quit = true; } // License: Apache 2.0. See LICENSE file in root directory. // (A.K.A.CABELO) // g++ main.cpp `pkg-config --cflags opencv4` `pkg-config --libs opencv4` -lrealsense2 #include // Include RealSense Cross Platform API #include // Include OpenCV API #include "utils.hpp" const int erosion_size = 3; Mat erode_less = gen_element(erosion_size); Mat erode_more = gen_element(erosion_size * 2); void create_mask_from_depth(Mat& depth, int thresh, ThresholdTypes type) { threshold(depth, depth, thresh, 255, type); dilate(depth, depth, erode_less); erode(depth, depth, erode_more); } int main(int argc, char * argv[]) try { VideoWriter writer; int codec = VideoWriter::fourcc('H', '2', '6', '4'); double fps = 15.0; string filename = "lookingglass.mp4"; Size sizeFrame(640,960); bool isColor = true; writer.open(filename, codec, fps, sizeFrame, isColor); rs2::threshold_filter thr_filter; rs2::colorizer colorize; rs2::align align_to(RS2_STREAM_COLOR); rs2::pipeline pipe; pipe.start(); using namespace cv; using namespace rs2; const auto window_name = "Lookingglass Portrait"; namedWindow(window_name, 1); int min_depth = 1; int max_depth = 160; createTrackbar("Max", window_name, &max_depth, 800); createTrackbar("Min", window_name, &min_depth, 800); thr_filter.set_option(RS2_OPTION_MIN_DISTANCE, (float)(min_depth/100)); thr_filter.set_option(RS2_OPTION_MAX_DISTANCE, (float)(max_depth/100)); colorize.set_option(RS2_OPTION_COLOR_SCHEME, 1); while (waitKey(1) < 0 && getWindowProperty(window_name, WND_PROP_AUTOSIZE) >= 0) { thr_filter.set_option(RS2_OPTION_MIN_DISTANCE, (float)(min_depth/100)); thr_filter.set_option(RS2_OPTION_MAX_DISTANCE, (float)(max_depth/100)); rs2::frameset data = pipe.wait_for_frames(); // Wait for next set of frames from the camera frameset aligned_set = align_to.process(data); frame depth = aligned_set.get_depth_frame(); frame color = aligned_set.get_color_frame(); frame d1 = depth.apply_filter(thr_filter); frame c1 = color.apply_filter(colorize); frame bw_depth = d1.apply_filter(colorize); Mat _depth = frame_to_mat(bw_depth); Mat _color = frame_to_mat(c1); Mat video; Mat far = frame_to_mat(bw_depth); cvtColor(far, far, COLOR_BGR2GRAY); far.setTo(255, far == 0); create_mask_from_depth(far, 254, THRESH_BINARY_INV); cvtColor(far, far, COLOR_GRAY2BGR); Mat bgModel, fgModel; bitwise_and(_color, far, fgModel); cv::vconcat(fgModel,_depth,video); imshow(window_name, video); writer.write(video); } writer.release(); return EXIT_SUCCESS; } catch (const rs2::error & e) { std::cerr << "RealSense error calling " << e.get_failed_function() << "(" << e.get_failed_args() << "):\n " << e.what() << std::endl; return EXIT_FAILURE; } catch (const std::exception& e) { std::cerr << e.what() << std::endl; return EXIT_FAILURE; } utkarshavardhana/november-leetcoding-challenge0 class Solution { public: int minCostToMoveChips(vector& chips) { int cnt[2] = {}; for (auto p : chips) ++cnt[p % 2]; return min(cnt[0], cnt[1]); } }; trosenqu/oneMKLinclude/oneapi/mkl/blas.hxx0 /******************************************************************************* * Copyright 2020-2021 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. * * * SPDX-License-Identifier: Apache-2.0 *******************************************************************************/ // Buffer APIs static inline void asum(cl::sycl::queue &queue, std::int64_t n, cl::sycl::buffer, 1> &x, std::int64_t incx, cl::sycl::buffer &result) { asum_precondition(queue, n, x, incx, result); detail::asum(get_device_id(queue), queue, n, x, incx, result); asum_postcondition(queue, n, x, incx, result); } static inline void asum(cl::sycl::queue &queue, std::int64_t n, cl::sycl::buffer, 1> &x, std::int64_t incx, cl::sycl::buffer &result) { asum_precondition(queue, n, x, incx, result); detail::asum(get_device_id(queue), queue, n, x, incx, result); asum_postcondition(queue, n, x, incx, result); } static inline void asum(cl::sycl::queue &queue, std::int64_t n, cl::sycl::buffer &x, std::int64_t incx, cl::sycl::buffer &result) { asum_precondition(queue, n, x, incx, result); detail::asum(get_device_id(queue), queue, n, x, incx, result); asum_postcondition(queue, n, x, incx, result); } static inline void asum(cl::sycl::queue &queue, std::int64_t n, cl::sycl::buffer &x, std::int64_t incx, cl::sycl::buffer &result) { asum_precondition(queue, n, x, incx, result); detail::asum(get_device_id(queue), queue, n, x, incx, result); asum_postcondition(queue, n, x, incx, result); } static inline void axpy(cl::sycl::queue &queue, std::int64_t n, float alpha, cl::sycl::buffer &x, std::int64_t incx, cl::sycl::buffer &y, std::int64_t incy) { axpy_precondition(queue, n, alpha, x, incx, y, incy); detail::axpy(get_device_id(queue), queue, n, alpha, x, incx, y, incy); axpy_postcondition(queue, n, alpha, x, incx, y, incy); } static inline void axpy(cl::sycl::queue &queue, std::int64_t n, double alpha, cl::sycl::buffer &x, std::int64_t incx, cl::sycl::buffer &y, std::int64_t incy) { axpy_precondition(queue, n, alpha, x, incx, y, incy); detail::axpy(get_device_id(queue), queue, n, alpha, x, incx, y, incy); axpy_postcondition(queue, n, alpha, x, incx, y, incy); } static inline void axpy(cl::sycl::queue &queue, std::int64_t n, std::complex alpha, cl::sycl::buffer, 1> &x, std::int64_t incx, cl::sycl::buffer, 1> &y, std::int64_t incy) { axpy_precondition(queue, n, alpha, x, incx, y, incy); detail::axpy(get_device_id(queue), queue, n, alpha, x, incx, y, incy); axpy_postcondition(queue, n, alpha, x, incx, y, incy); } static inline void axpy(cl::sycl::queue &queue, std::int64_t n, std::complex alpha, cl::sycl::buffer, 1> &x, std::int64_t incx, cl::sycl::buffer, 1> &y, std::int64_t incy) { axpy_precondition(queue, n, alpha, x, incx, y, incy); detail::axpy(get_device_id(queue), queue, n, alpha, x, incx, y, incy); axpy_postcondition(queue, n, alpha, x, incx, y, incy); } static inline void axpy_batch(cl::sycl::queue &queue, std::int64_t n, float alpha, cl::sycl::buffer &x, std::int64_t incx, std::int64_t stridex, cl::sycl::buffer &y, std::int64_t incy, std::int64_t stridey, std::int64_t batch_size) { axpy_batch_precondition(queue, n, alpha, x, incx, stridex, y, incy, stridey, batch_size); detail::axpy_batch(get_device_id(queue), queue, n, alpha, x, incx, stridex, y, incy, stridey, batch_size); axpy_batch_postcondition(queue, n, alpha, x, incx, stridex, y, incy, stridey, batch_size); } static inline void axpy_batch(cl::sycl::queue &queue, std::int64_t n, double alpha, cl::sycl::buffer &x, std::int64_t incx, std::int64_t stridex, cl::sycl::buffer &y, std::int64_t incy, std::int64_t stridey, std::int64_t batch_size) { axpy_batch_precondition(queue, n, alpha, x, incx, stridex, y, incy, stridey, batch_size); detail::axpy_batch(get_device_id(queue), queue, n, alpha, x, incx, stridex, y, incy, stridey, batch_size); axpy_batch_postcondition(queue, n, alpha, x, incx, stridex, y, incy, stridey, batch_size); } static inline void axpy_batch(cl::sycl::queue &queue, std::int64_t n, std::complex alpha, cl::sycl::buffer, 1> &x, std::int64_t incx, std::int64_t stridex, cl::sycl::buffer, 1> &y, std::int64_t incy, std::int64_t stridey, std::int64_t batch_size) { axpy_batch_precondition(queue, n, alpha, x, incx, stridex, y, incy, stridey, batch_size); detail::axpy_batch(get_device_id(queue), queue, n, alpha, x, incx, stridex, y, incy, stridey, batch_size); axpy_batch_postcondition(queue, n, alpha, x, incx, stridex, y, incy, stridey, batch_size); } static inline void axpy_batch(cl::sycl::queue &queue, std::int64_t n, std::complex alpha, cl::sycl::buffer, 1> &x, std::int64_t incx, std::int64_t stridex, cl::sycl::buffer, 1> &y, std::int64_t incy, std::int64_t stridey, std::int64_t batch_size) { axpy_batch_precondition(queue, n, alpha, x, incx, stridex, y, incy, stridey, batch_size); detail::axpy_batch(get_device_id(queue), queue, n, alpha, x, incx, stridex, y, incy, stridey, batch_size); axpy_batch_postcondition(queue, n, alpha, x, incx, stridex, y, incy, stridey, batch_size); } static inline void axpby(cl::sycl::queue &queue, std::int64_t n, float alpha, cl::sycl::buffer &x, std::int64_t incx, float beta, cl::sycl::buffer &y, std::int64_t incy) { axpby_precondition(queue, n, alpha, x, incx, beta, y, incy); detail::axpby(get_device_id(queue), queue, n, alpha, x, incx, beta, y, incy); axpby_postcondition(queue, n, alpha, x, incx, beta, y, incy); } static inline void axpby(cl::sycl::queue &queue, std::int64_t n, double alpha, cl::sycl::buffer &x, std::int64_t incx, double beta, cl::sycl::buffer &y, std::int64_t incy) { axpby_precondition(queue, n, alpha, x, incx, beta, y, incy); detail::axpby(get_device_id(queue), queue, n, alpha, x, incx, beta, y, incy); axpby_postcondition(queue, n, alpha, x, incx, beta, y, incy); } static inline void axpby(cl::sycl::queue &queue, std::int64_t n, std::complex alpha, cl::sycl::buffer, 1> &x, std::int64_t incx, std::complex beta, cl::sycl::buffer, 1> &y, std::int64_t incy) { axpby_precondition(queue, n, alpha, x, incx, beta, y, incy); detail::axpby(get_device_id(queue), queue, n, alpha, x, incx, beta, y, incy); axpby_postcondition(queue, n, alpha, x, incx, beta, y, incy); } static inline void axpby(cl::sycl::queue &queue, std::int64_t n, std::complex alpha, cl::sycl::buffer, 1> &x, std::int64_t incx, std::complex beta, cl::sycl::buffer, 1> &y, std::int64_t incy) { axpby_precondition(queue, n, alpha, x, incx, beta, y, incy); detail::axpby(get_device_id(queue), queue, n, alpha, x, incx, beta, y, incy); axpby_postcondition(queue, n, alpha, x, incx, beta, y, incy); } static inline void copy(cl::sycl::queue &queue, std::int64_t n, cl::sycl::buffer &x, std::int64_t incx, cl::sycl::buffer &y, std::int64_t incy) { copy_precondition(queue, n, x, incx, y, incy); detail::copy(get_device_id(queue), queue, n, x, incx, y, incy); copy_postcondition(queue, n, x, incx, y, incy); } static inline void copy(cl::sycl::queue &queue, std::int64_t n, cl::sycl::buffer &x, std::int64_t incx, cl::sycl::buffer &y, std::int64_t incy) { copy_precondition(queue, n, x, incx, y, incy); detail::copy(get_device_id(queue), queue, n, x, incx, y, incy); copy_postcondition(queue, n, x, incx, y, incy); } static inline void copy(cl::sycl::queue &queue, std::int64_t n, cl::sycl::buffer, 1> &x, std::int64_t incx, cl::sycl::buffer, 1> &y, std::int64_t incy) { copy_precondition(queue, n, x, incx, y, incy); detail::copy(get_device_id(queue), queue, n, x, incx, y, incy); copy_postcondition(queue, n, x, incx, y, incy); } static inline void copy(cl::sycl::queue &queue, std::int64_t n, cl::sycl::buffer, 1> &x, std::int64_t incx, cl::sycl::buffer, 1> &y, std::int64_t incy) { copy_precondition(queue, n, x, incx, y, incy); detail::copy(get_device_id(queue), queue, n, x, incx, y, incy); copy_postcondition(queue, n, x, incx, y, incy); } static inline void copy_batch(cl::sycl::queue &queue, std::int64_t n, cl::sycl::buffer &x, std::int64_t incx, std::int64_t stridex, cl::sycl::buffer &y, std::int64_t incy, std::int64_t stridey, std::int64_t batch_size) { copy_batch_precondition(queue, n, x, incx, stridex, y, incy, stridey, batch_size); detail::copy_batch(get_device_id(queue), queue, n, x, incx, stridex, y, incy, stridey, batch_size); copy_batch_postcondition(queue, n, x, incx, stridex, y, incy, stridey, batch_size); } static inline void copy_batch(cl::sycl::queue &queue, std::int64_t n, cl::sycl::buffer &x, std::int64_t incx, std::int64_t stridex, cl::sycl::buffer &y, std::int64_t incy, std::int64_t stridey, std::int64_t batch_size) { copy_batch_precondition(queue, n, x, incx, stridex, y, incy, stridey, batch_size); detail::copy_batch(get_device_id(queue), queue, n, x, incx, stridex, y, incy, stridey, batch_size); copy_batch_postcondition(queue, n, x, incx, stridex, y, incy, stridey, batch_size); } static inline void copy_batch(cl::sycl::queue &queue, std::int64_t n, cl::sycl::buffer, 1> &x, std::int64_t incx, std::int64_t stridex, cl::sycl::buffer, 1> &y, std::int64_t incy, std::int64_t stridey, std::int64_t batch_size) { copy_batch_precondition(queue, n, x, incx, stridex, y, incy, stridey, batch_size); detail::copy_batch(get_device_id(queue), queue, n, x, incx, stridex, y, incy, stridey, batch_size); copy_batch_postcondition(queue, n, x, incx, stridex, y, incy, stridey, batch_size); } static inline void copy_batch(cl::sycl::queue &queue, std::int64_t n, cl::sycl::buffer, 1> &x, std::int64_t incx, std::int64_t stridex, cl::sycl::buffer, 1> &y, std::int64_t incy, std::int64_t stridey, std::int64_t batch_size) { copy_batch_precondition(queue, n, x, incx, stridex, y, incy, stridey, batch_size); detail::copy_batch(get_device_id(queue), queue, n, x, incx, stridex, y, incy, stridey, batch_size); copy_batch_postcondition(queue, n, x, incx, stridex, y, incy, stridey, batch_size); } static inline void dot(cl::sycl::queue &queue, std::int64_t n, cl::sycl::buffer &x, std::int64_t incx, cl::sycl::buffer &y, std::int64_t incy, cl::sycl::buffer &result) { dot_precondition(queue, n, x, incx, y, incy, result); detail::dot(get_device_id(queue), queue, n, x, incx, y, incy, result); dot_postcondition(queue, n, x, incx, y, incy, result); } static inline void dot(cl::sycl::queue &queue, std::int64_t n, cl::sycl::buffer &x, std::int64_t incx, cl::sycl::buffer &y, std::int64_t incy, cl::sycl::buffer &result) { dot_precondition(queue, n, x, incx, y, incy, result); detail::dot(get_device_id(queue), queue, n, x, incx, y, incy, result); dot_postcondition(queue, n, x, incx, y, incy, result); } static inline void dot(cl::sycl::queue &queue, std::int64_t n, cl::sycl::buffer &x, std::int64_t incx, cl::sycl::buffer &y, std::int64_t incy, cl::sycl::buffer &result) { dot_precondition(queue, n, x, incx, y, incy, result); detail::dot(get_device_id(queue), queue, n, x, incx, y, incy, result); dot_postcondition(queue, n, x, incx, y, incy, result); } static inline void dotc(cl::sycl::queue &queue, std::int64_t n, cl::sycl::buffer, 1> &x, std::int64_t incx, cl::sycl::buffer, 1> &y, std::int64_t incy, cl::sycl::buffer, 1> &result) { dotc_precondition(queue, n, x, incx, y, incy, result); detail::dotc(get_device_id(queue), queue, n, x, incx, y, incy, result); dotc_postcondition(queue, n, x, incx, y, incy, result); } static inline void dotc(cl::sycl::queue &queue, std::int64_t n, cl::sycl::buffer, 1> &x, std::int64_t incx, cl::sycl::buffer, 1> &y, std::int64_t incy, cl::sycl::buffer, 1> &result) { dotc_precondition(queue, n, x, incx, y, incy, result); detail::dotc(get_device_id(queue), queue, n, x, incx, y, incy, result); dotc_postcondition(queue, n, x, incx, y, incy, result); } static inline void dotu(cl::sycl::queue &queue, std::int64_t n, cl::sycl::buffer, 1> &x, std::int64_t incx, cl::sycl::buffer, 1> &y, std::int64_t incy, cl::sycl::buffer, 1> &result) { dotu_precondition(queue, n, x, incx, y, incy, result); detail::dotu(get_device_id(queue), queue, n, x, incx, y, incy, result); dotu_postcondition(queue, n, x, incx, y, incy, result); } static inline void dotu(cl::sycl::queue &queue, std::int64_t n, cl::sycl::buffer, 1> &x, std::int64_t incx, cl::sycl::buffer, 1> &y, std::int64_t incy, cl::sycl::buffer, 1> &result) { dotu_precondition(queue, n, x, incx, y, incy, result); detail::dotu(get_device_id(queue), queue, n, x, incx, y, incy, result); dotu_postcondition(queue, n, x, incx, y, incy, result); } static inline void gbmv(cl::sycl::queue &queue, transpose trans, std::int64_t m, std::int64_t n, std::int64_t kl, std::int64_t ku, float alpha, cl::sycl::buffer &a, std::int64_t lda, cl::sycl::buffer &x, std::int64_t incx, float beta, cl::sycl::buffer &y, std::int64_t incy) { gbmv_precondition(queue, trans, m, n, kl, ku, alpha, a, lda, x, incx, beta, y, incy); detail::gbmv(get_device_id(queue), queue, trans, m, n, kl, ku, alpha, a, lda, x, incx, beta, y, incy); gbmv_postcondition(queue, trans, m, n, kl, ku, alpha, a, lda, x, incx, beta, y, incy); } static inline void gbmv(cl::sycl::queue &queue, transpose trans, std::int64_t m, std::int64_t n, std::int64_t kl, std::int64_t ku, double alpha, cl::sycl::buffer &a, std::int64_t lda, cl::sycl::buffer &x, std::int64_t incx, double beta, cl::sycl::buffer &y, std::int64_t incy) { gbmv_precondition(queue, trans, m, n, kl, ku, alpha, a, lda, x, incx, beta, y, incy); detail::gbmv(get_device_id(queue), queue, trans, m, n, kl, ku, alpha, a, lda, x, incx, beta, y, incy); gbmv_postcondition(queue, trans, m, n, kl, ku, alpha, a, lda, x, incx, beta, y, incy); } static inline void gbmv(cl::sycl::queue &queue, transpose trans, std::int64_t m, std::int64_t n, std::int64_t kl, std::int64_t ku, std::complex alpha, cl::sycl::buffer, 1> &a, std::int64_t lda, cl::sycl::buffer, 1> &x, std::int64_t incx, std::complex beta, cl::sycl::buffer, 1> &y, std::int64_t incy) { gbmv_precondition(queue, trans, m, n, kl, ku, alpha, a, lda, x, incx, beta, y, incy); detail::gbmv(get_device_id(queue), queue, trans, m, n, kl, ku, alpha, a, lda, x, incx, beta, y, incy); gbmv_postcondition(queue, trans, m, n, kl, ku, alpha, a, lda, x, incx, beta, y, incy); } static inline void gbmv(cl::sycl::queue &queue, transpose trans, std::int64_t m, std::int64_t n, std::int64_t kl, std::int64_t ku, std::complex alpha, cl::sycl::buffer, 1> &a, std::int64_t lda, cl::sycl::buffer, 1> &x, std::int64_t incx, std::complex beta, cl::sycl::buffer, 1> &y, std::int64_t incy) { gbmv_precondition(queue, trans, m, n, kl, ku, alpha, a, lda, x, incx, beta, y, incy); detail::gbmv(get_device_id(queue), queue, trans, m, n, kl, ku, alpha, a, lda, x, incx, beta, y, incy); gbmv_postcondition(queue, trans, m, n, kl, ku, alpha, a, lda, x, incx, beta, y, incy); } static inline void gemm(cl::sycl::queue &queue, transpose transa, transpose transb, std::int64_t m, std::int64_t n, std::int64_t k, float alpha, cl::sycl::buffer &a, std::int64_t lda, cl::sycl::buffer &b, std::int64_t ldb, float beta, cl::sycl::buffer &c, std::int64_t ldc) { gemm_precondition(queue, transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc); detail::gemm(get_device_id(queue), queue, transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc); gemm_postcondition(queue, transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc); } static inline void gemm(cl::sycl::queue &queue, transpose transa, transpose transb, std::int64_t m, std::int64_t n, std::int64_t k, double alpha, cl::sycl::buffer &a, std::int64_t lda, cl::sycl::buffer &b, std::int64_t ldb, double beta, cl::sycl::buffer &c, std::int64_t ldc) { gemm_precondition(queue, transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc); detail::gemm(get_device_id(queue), queue, transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc); gemm_postcondition(queue, transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc); } static inline void gemm(cl::sycl::queue &queue, transpose transa, transpose transb, std::int64_t m, std::int64_t n, std::int64_t k, std::complex alpha, cl::sycl::buffer, 1> &a, std::int64_t lda, cl::sycl::buffer, 1> &b, std::int64_t ldb, std::complex beta, cl::sycl::buffer, 1> &c, std::int64_t ldc) { gemm_precondition(queue, transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc); detail::gemm(get_device_id(queue), queue, transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc); gemm_postcondition(queue, transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc); } static inline void gemm(cl::sycl::queue &queue, transpose transa, transpose transb, std::int64_t m, std::int64_t n, std::int64_t k, std::complex alpha, cl::sycl::buffer, 1> &a, std::int64_t lda, cl::sycl::buffer, 1> &b, std::int64_t ldb, std::complex beta, cl::sycl::buffer, 1> &c, std::int64_t ldc) { gemm_precondition(queue, transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc); detail::gemm(get_device_id(queue), queue, transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc); gemm_postcondition(queue, transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc); } static inline void gemm(cl::sycl::queue &queue, transpose transa, transpose transb, std::int64_t m, std::int64_t n, std::int64_t k, sycl::half alpha, cl::sycl::buffer &a, std::int64_t lda, cl::sycl::buffer &b, std::int64_t ldb, sycl::half beta, cl::sycl::buffer &c, std::int64_t ldc) { gemm_precondition(queue, transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc); detail::gemm(get_device_id(queue), queue, transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc); gemm_postcondition(queue, transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc); } static inline void gemm(cl::sycl::queue &queue, transpose transa, transpose transb, std::int64_t m, std::int64_t n, std::int64_t k, float alpha, cl::sycl::buffer &a, std::int64_t lda, cl::sycl::buffer &b, std::int64_t ldb, float beta, cl::sycl::buffer &c, std::int64_t ldc) { gemm_precondition(queue, transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc); detail::gemm(get_device_id(queue), queue, transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc); gemm_postcondition(queue, transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc); } static inline void gemm(cl::sycl::queue &queue, transpose transa, transpose transb, std::int64_t m, std::int64_t n, std::int64_t k, float alpha, cl::sycl::buffer &a, std::int64_t lda, cl::sycl::buffer &b, std::int64_t ldb, float beta, cl::sycl::buffer &c, std::int64_t ldc) { gemm_precondition(queue, transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc); detail::gemm(get_device_id(queue), queue, transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc); gemm_postcondition(queue, transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc); } static inline void gemm_batch(cl::sycl::queue &queue, transpose transa, transpose transb, std::int64_t m, std::int64_t n, std::int64_t k, float alpha, cl::sycl::buffer &a, std::int64_t lda, std::int64_t stride_a, cl::sycl::buffer &b, std::int64_t ldb, std::int64_t stride_b, float beta, cl::sycl::buffer &c, std::int64_t ldc, std::int64_t stride_c, std::int64_t batch_size) { gemm_batch_precondition(queue, transa, transb, m, n, k, alpha, a, lda, stride_a, b, ldb, stride_b, beta, c, ldc, stride_c, batch_size); detail::gemm_batch(get_device_id(queue), queue, transa, transb, m, n, k, alpha, a, lda, stride_a, b, ldb, stride_b, beta, c, ldc, stride_c, batch_size); gemm_batch_postcondition(queue, transa, transb, m, n, k, alpha, a, lda, stride_a, b, ldb, stride_b, beta, c, ldc, stride_c, batch_size); } static inline void gemm_batch(cl::sycl::queue &queue, transpose transa, transpose transb, std::int64_t m, std::int64_t n, std::int64_t k, double alpha, cl::sycl::buffer &a, std::int64_t lda, std::int64_t stride_a, cl::sycl::buffer &b, std::int64_t ldb, std::int64_t stride_b, double beta, cl::sycl::buffer &c, std::int64_t ldc, std::int64_t stride_c, std::int64_t batch_size) { gemm_batch_precondition(queue, transa, transb, m, n, k, alpha, a, lda, stride_a, b, ldb, stride_b, beta, c, ldc, stride_c, batch_size); detail::gemm_batch(get_device_id(queue), queue, transa, transb, m, n, k, alpha, a, lda, stride_a, b, ldb, stride_b, beta, c, ldc, stride_c, batch_size); gemm_batch_postcondition(queue, transa, transb, m, n, k, alpha, a, lda, stride_a, b, ldb, stride_b, beta, c, ldc, stride_c, batch_size); } static inline void gemm_batch(cl::sycl::queue &queue, transpose transa, transpose transb, std::int64_t m, std::int64_t n, std::int64_t k, std::complex alpha, cl::sycl::buffer, 1> &a, std::int64_t lda, std::int64_t stride_a, cl::sycl::buffer, 1> &b, std::int64_t ldb, std::int64_t stride_b, std::complex beta, cl::sycl::buffer, 1> &c, std::int64_t ldc, std::int64_t stride_c, std::int64_t batch_size) { gemm_batch_precondition(queue, transa, transb, m, n, k, alpha, a, lda, stride_a, b, ldb, stride_b, beta, c, ldc, stride_c, batch_size); detail::gemm_batch(get_device_id(queue), queue, transa, transb, m, n, k, alpha, a, lda, stride_a, b, ldb, stride_b, beta, c, ldc, stride_c, batch_size); gemm_batch_postcondition(queue, transa, transb, m, n, k, alpha, a, lda, stride_a, b, ldb, stride_b, beta, c, ldc, stride_c, batch_size); } static inline void gemm_batch(cl::sycl::queue &queue, transpose transa, transpose transb, std::int64_t m, std::int64_t n, std::int64_t k, std::complex alpha, cl::sycl::buffer, 1> &a, std::int64_t lda, std::int64_t stride_a, cl::sycl::buffer, 1> &b, std::int64_t ldb, std::int64_t stride_b, std::complex beta, cl::sycl::buffer, 1> &c, std::int64_t ldc, std::int64_t stride_c, std::int64_t batch_size) { gemm_batch_precondition(queue, transa, transb, m, n, k, alpha, a, lda, stride_a, b, ldb, stride_b, beta, c, ldc, stride_c, batch_size); detail::gemm_batch(get_device_id(queue), queue, transa, transb, m, n, k, alpha, a, lda, stride_a, b, ldb, stride_b, beta, c, ldc, stride_c, batch_size); gemm_batch_postcondition(queue, transa, transb, m, n, k, alpha, a, lda, stride_a, b, ldb, stride_b, beta, c, ldc, stride_c, batch_size); } static inline void gemm_batch(cl::sycl::queue &queue, transpose transa, transpose transb, std::int64_t m, std::int64_t n, std::int64_t k, sycl::half alpha, cl::sycl::buffer &a, std::int64_t lda, std::int64_t stride_a, cl::sycl::buffer &b, std::int64_t ldb, std::int64_t stride_b, sycl::half beta, cl::sycl::buffer &c, std::int64_t ldc, std::int64_t stride_c, std::int64_t batch_size) { gemm_batch_precondition(queue, transa, transb, m, n, k, alpha, a, lda, stride_a, b, ldb, stride_b, beta, c, ldc, stride_c, batch_size); detail::gemm_batch(get_device_id(queue), queue, transa, transb, m, n, k, alpha, a, lda, stride_a, b, ldb, stride_b, beta, c, ldc, stride_c, batch_size); gemm_batch_postcondition(queue, transa, transb, m, n, k, alpha, a, lda, stride_a, b, ldb, stride_b, beta, c, ldc, stride_c, batch_size); } static inline void gemm_bias(cl::sycl::queue &queue, transpose transa, transpose transb, offset offsetc, std::int64_t m, std::int64_t n, std::int64_t k, float alpha, cl::sycl::buffer &a, std::int64_t lda, int8_t ao, cl::sycl::buffer &b, std::int64_t ldb, uint8_t bo, float beta, cl::sycl::buffer &c, std::int64_t ldc, cl::sycl::buffer &co) { gemm_bias_precondition(queue, transa, transb, offsetc, m, n, k, alpha, a, lda, ao, b, ldb, bo, beta, c, ldc, co); detail::gemm_bias(get_device_id(queue), queue, transa, transb, offsetc, m, n, k, alpha, a, lda, ao, b, ldb, bo, beta, c, ldc, co); gemm_bias_postcondition(queue, transa, transb, offsetc, m, n, k, alpha, a, lda, ao, b, ldb, bo, beta, c, ldc, co); } static inline void gemm_bias(cl::sycl::queue &queue, transpose transa, transpose transb, offset offsetc, std::int64_t m, std::int64_t n, std::int64_t k, float alpha, cl::sycl::buffer &a, std::int64_t lda, int8_t ao, cl::sycl::buffer &b, std::int64_t ldb, int8_t bo, float beta, cl::sycl::buffer &c, std::int64_t ldc, cl::sycl::buffer &co) { gemm_bias_precondition(queue, transa, transb, offsetc, m, n, k, alpha, a, lda, ao, b, ldb, bo, beta, c, ldc, co); detail::gemm_bias(get_device_id(queue), queue, transa, transb, offsetc, m, n, k, alpha, a, lda, ao, b, ldb, bo, beta, c, ldc, co); gemm_bias_postcondition(queue, transa, transb, offsetc, m, n, k, alpha, a, lda, ao, b, ldb, bo, beta, c, ldc, co); } static inline void gemm_bias(cl::sycl::queue &queue, transpose transa, transpose transb, offset offsetc, std::int64_t m, std::int64_t n, std::int64_t k, float alpha, cl::sycl::buffer &a, std::int64_t lda, uint8_t ao, cl::sycl::buffer &b, std::int64_t ldb, int8_t bo, float beta, cl::sycl::buffer &c, std::int64_t ldc, cl::sycl::buffer &co) { gemm_bias_precondition(queue, transa, transb, offsetc, m, n, k, alpha, a, lda, ao, b, ldb, bo, beta, c, ldc, co); detail::gemm_bias(get_device_id(queue), queue, transa, transb, offsetc, m, n, k, alpha, a, lda, ao, b, ldb, bo, beta, c, ldc, co); gemm_bias_postcondition(queue, transa, transb, offsetc, m, n, k, alpha, a, lda, ao, b, ldb, bo, beta, c, ldc, co); } static inline void gemm_bias(cl::sycl::queue &queue, transpose transa, transpose transb, offset offsetc, std::int64_t m, std::int64_t n, std::int64_t k, float alpha, cl::sycl::buffer &a, std::int64_t lda, uint8_t ao, cl::sycl::buffer &b, std::int64_t ldb, uint8_t bo, float beta, cl::sycl::buffer &c, std::int64_t ldc, cl::sycl::buffer &co) { gemm_bias_precondition(queue, transa, transb, offsetc, m, n, k, alpha, a, lda, ao, b, ldb, bo, beta, c, ldc, co); detail::gemm_bias(get_device_id(queue), queue, transa, transb, offsetc, m, n, k, alpha, a, lda, ao, b, ldb, bo, beta, c, ldc, co); gemm_bias_postcondition(queue, transa, transb, offsetc, m, n, k, alpha, a, lda, ao, b, ldb, bo, beta, c, ldc, co); } static inline void gemmt(cl::sycl::queue &queue, uplo upper_lower, transpose transa, transpose transb, std::int64_t n, std::int64_t k, float alpha, cl::sycl::buffer &a, std::int64_t lda, cl::sycl::buffer &b, std::int64_t ldb, float beta, cl::sycl::buffer &c, std::int64_t ldc) { gemmt_precondition(queue, upper_lower, transa, transb, n, k, alpha, a, lda, b, ldb, beta, c, ldc); detail::gemmt(get_device_id(queue), queue, upper_lower, transa, transb, n, k, alpha, a, lda, b, ldb, beta, c, ldc); gemmt_postcondition(queue, upper_lower, transa, transb, n, k, alpha, a, lda, b, ldb, beta, c, ldc); } static inline void gemmt(cl::sycl::queue &queue, uplo upper_lower, transpose transa, transpose transb, std::int64_t n, std::int64_t k, double alpha, cl::sycl::buffer &a, std::int64_t lda, cl::sycl::buffer &b, std::int64_t ldb, double beta, cl::sycl::buffer &c, std::int64_t ldc) { gemmt_precondition(queue, upper_lower, transa, transb, n, k, alpha, a, lda, b, ldb, beta, c, ldc); detail::gemmt(get_device_id(queue), queue, upper_lower, transa, transb, n, k, alpha, a, lda, b, ldb, beta, c, ldc); gemmt_postcondition(queue, upper_lower, transa, transb, n, k, alpha, a, lda, b, ldb, beta, c, ldc); } static inline void gemmt(cl::sycl::queue &queue, uplo upper_lower, transpose transa, transpose transb, std::int64_t n, std::int64_t k, std::complex alpha, cl::sycl::buffer, 1> &a, std::int64_t lda, cl::sycl::buffer, 1> &b, std::int64_t ldb, std::complex beta, cl::sycl::buffer, 1> &c, std::int64_t ldc) { gemmt_precondition(queue, upper_lower, transa, transb, n, k, alpha, a, lda, b, ldb, beta, c, ldc); detail::gemmt(get_device_id(queue), queue, upper_lower, transa, transb, n, k, alpha, a, lda, b, ldb, beta, c, ldc); gemmt_postcondition(queue, upper_lower, transa, transb, n, k, alpha, a, lda, b, ldb, beta, c, ldc); } static inline void gemmt(cl::sycl::queue &queue, uplo upper_lower, transpose transa, transpose transb, std::int64_t n, std::int64_t k, std::complex alpha, cl::sycl::buffer, 1> &a, std::int64_t lda, cl::sycl::buffer, 1> &b, std::int64_t ldb, std::complex beta, cl::sycl::buffer, 1> &c, std::int64_t ldc) { gemmt_precondition(queue, upper_lower, transa, transb, n, k, alpha, a, lda, b, ldb, beta, c, ldc); detail::gemmt(get_device_id(queue), queue, upper_lower, transa, transb, n, k, alpha, a, lda, b, ldb, beta, c, ldc); gemmt_postcondition(queue, upper_lower, transa, transb, n, k, alpha, a, lda, b, ldb, beta, c, ldc); } static inline void gemv(cl::sycl::queue &queue, transpose trans, std::int64_t m, std::int64_t n, float alpha, cl::sycl::buffer &a, std::int64_t lda, cl::sycl::buffer &x, std::int64_t incx, float beta, cl::sycl::buffer &y, std::int64_t incy) { gemv_precondition(queue, trans, m, n, alpha, a, lda, x, incx, beta, y, incy); detail::gemv(get_device_id(queue), queue, trans, m, n, alpha, a, lda, x, incx, beta, y, incy); gemv_postcondition(queue, trans, m, n, alpha, a, lda, x, incx, beta, y, incy); } static inline void gemv(cl::sycl::queue &queue, transpose trans, std::int64_t m, std::int64_t n, double alpha, cl::sycl::buffer &a, std::int64_t lda, cl::sycl::buffer &x, std::int64_t incx, double beta, cl::sycl::buffer &y, std::int64_t incy) { gemv_precondition(queue, trans, m, n, alpha, a, lda, x, incx, beta, y, incy); detail::gemv(get_device_id(queue), queue, trans, m, n, alpha, a, lda, x, incx, beta, y, incy); gemv_postcondition(queue, trans, m, n, alpha, a, lda, x, incx, beta, y, incy); } static inline void gemv(cl::sycl::queue &queue, transpose trans, std::int64_t m, std::int64_t n, std::complex alpha, cl::sycl::buffer, 1> &a, std::int64_t lda, cl::sycl::buffer, 1> &x, std::int64_t incx, std::complex beta, cl::sycl::buffer, 1> &y, std::int64_t incy) { gemv_precondition(queue, trans, m, n, alpha, a, lda, x, incx, beta, y, incy); detail::gemv(get_device_id(queue), queue, trans, m, n, alpha, a, lda, x, incx, beta, y, incy); gemv_postcondition(queue, trans, m, n, alpha, a, lda, x, incx, beta, y, incy); } static inline void gemv(cl::sycl::queue &queue, transpose trans, std::int64_t m, std::int64_t n, std::complex alpha, cl::sycl::buffer, 1> &a, std::int64_t lda, cl::sycl::buffer, 1> &x, std::int64_t incx, std::complex beta, cl::sycl::buffer, 1> &y, std::int64_t incy) { gemv_precondition(queue, trans, m, n, alpha, a, lda, x, incx, beta, y, incy); detail::gemv(get_device_id(queue), queue, trans, m, n, alpha, a, lda, x, incx, beta, y, incy); gemv_postcondition(queue, trans, m, n, alpha, a, lda, x, incx, beta, y, incy); } static inline void gemv_batch(cl::sycl::queue &queue, transpose trans, std::int64_t m, std::int64_t n, float alpha, cl::sycl::buffer &a, std::int64_t lda, std::int64_t stridea, cl::sycl::buffer &x, std::int64_t incx, std::int64_t stridex, float beta, cl::sycl::buffer &y, std::int64_t incy, std::int64_t stridey, std::int64_t batch_size) { gemv_batch_precondition(queue, trans, m, n, alpha, a, lda, stridea, x, incx, stridex, beta, y, incy, stridey, batch_size); detail::gemv_batch(get_device_id(queue), queue, trans, m, n, alpha, a, lda, stridea, x, incx, stridex, beta, y, incy, stridey, batch_size); gemv_batch_postcondition(queue, trans, m, n, alpha, a, lda, stridea, x, incx, stridex, beta, y, incy, stridey, batch_size); } static inline void gemv_batch(cl::sycl::queue &queue, transpose trans, std::int64_t m, std::int64_t n, double alpha, cl::sycl::buffer &a, std::int64_t lda, std::int64_t stridea, cl::sycl::buffer &x, std::int64_t incx, std::int64_t stridex, double beta, cl::sycl::buffer &y, std::int64_t incy, std::int64_t stridey, std::int64_t batch_size) { gemv_batch_precondition(queue, trans, m, n, alpha, a, lda, stridea, x, incx, stridex, beta, y, incy, stridey, batch_size); detail::gemv_batch(get_device_id(queue), queue, trans, m, n, alpha, a, lda, stridea, x, incx, stridex, beta, y, incy, stridey, batch_size); gemv_batch_postcondition(queue, trans, m, n, alpha, a, lda, stridea, x, incx, stridex, beta, y, incy, stridey, batch_size); } static inline void gemv_batch(cl::sycl::queue &queue, transpose trans, std::int64_t m, std::int64_t n, std::complex alpha, cl::sycl::buffer, 1> &a, std::int64_t lda, std::int64_t stridea, cl::sycl::buffer, 1> &x, std::int64_t incx, std::int64_t stridex, std::complex beta, cl::sycl::buffer, 1> &y, std::int64_t incy, std::int64_t stridey, std::int64_t batch_size) { gemv_batch_precondition(queue, trans, m, n, alpha, a, lda, stridea, x, incx, stridex, beta, y, incy, stridey, batch_size); detail::gemv_batch(get_device_id(queue), queue, trans, m, n, alpha, a, lda, stridea, x, incx, stridex, beta, y, incy, stridey, batch_size); gemv_batch_postcondition(queue, trans, m, n, alpha, a, lda, stridea, x, incx, stridex, beta, y, incy, stridey, batch_size); } static inline void gemv_batch(cl::sycl::queue &queue, transpose trans, std::int64_t m, std::int64_t n, std::complex alpha, cl::sycl::buffer, 1> &a, std::int64_t lda, std::int64_t stridea, cl::sycl::buffer, 1> &x, std::int64_t incx, std::int64_t stridex, std::complex beta, cl::sycl::buffer, 1> &y, std::int64_t incy, std::int64_t stridey, std::int64_t batch_size) { gemv_batch_precondition(queue, trans, m, n, alpha, a, lda, stridea, x, incx, stridex, beta, y, incy, stridey, batch_size); detail::gemv_batch(get_device_id(queue), queue, trans, m, n, alpha, a, lda, stridea, x, incx, stridex, beta, y, incy, stridey, batch_size); gemv_batch_postcondition(queue, trans, m, n, alpha, a, lda, stridea, x, incx, stridex, beta, y, incy, stridey, batch_size); } static inline void dgmm_batch(cl::sycl::queue &queue, side left_right, std::int64_t m, std::int64_t n, cl::sycl::buffer &a, std::int64_t lda, std::int64_t stridea, cl::sycl::buffer &x, std::int64_t incx, std::int64_t stridex, cl::sycl::buffer &c, std::int64_t ldc, std::int64_t stridec, std::int64_t batch_size) { dgmm_batch_precondition(queue, left_right, m, n, a, lda, stridea, x, incx, stridex, c, ldc, stridec, batch_size); detail::dgmm_batch(get_device_id(queue), queue, left_right, m, n, a, lda, stridea, x, incx, stridex, c, ldc, stridec, batch_size); dgmm_batch_postcondition(queue, left_right, m, n, a, lda, stridea, x, incx, stridex, c, ldc, stridec, batch_size); } static inline void dgmm_batch(cl::sycl::queue &queue, side left_right, std::int64_t m, std::int64_t n, cl::sycl::buffer &a, std::int64_t lda, std::int64_t stridea, cl::sycl::buffer &x, std::int64_t incx, std::int64_t stridex, cl::sycl::buffer &c, std::int64_t ldc, std::int64_t stridec, std::int64_t batch_size) { dgmm_batch_precondition(queue, left_right, m, n, a, lda, stridea, x, incx, stridex, c, ldc, stridec, batch_size); detail::dgmm_batch(get_device_id(queue), queue, left_right, m, n, a, lda, stridea, x, incx, stridex, c, ldc, stridec, batch_size); dgmm_batch_postcondition(queue, left_right, m, n, a, lda, stridea, x, incx, stridex, c, ldc, stridec, batch_size); } static inline void dgmm_batch(cl::sycl::queue &queue, side left_right, std::int64_t m, std::int64_t n, cl::sycl::buffer, 1> &a, std::int64_t lda, std::int64_t stridea, cl::sycl::buffer, 1> &x, std::int64_t incx, std::int64_t stridex, cl::sycl::buffer, 1> &c, std::int64_t ldc, std::int64_t stridec, std::int64_t batch_size) { dgmm_batch_precondition(queue, left_right, m, n, a, lda, stridea, x, incx, stridex, c, ldc, stridec, batch_size); detail::dgmm_batch(get_device_id(queue), queue, left_right, m, n, a, lda, stridea, x, incx, stridex, c, ldc, stridec, batch_size); dgmm_batch_postcondition(queue, left_right, m, n, a, lda, stridea, x, incx, stridex, c, ldc, stridec, batch_size); } static inline void dgmm_batch(cl::sycl::queue &queue, side left_right, std::int64_t m, std::int64_t n, cl::sycl::buffer, 1> &a, std::int64_t lda, std::int64_t stridea, cl::sycl::buffer, 1> &x, std::int64_t incx, std::int64_t stridex, cl::sycl::buffer, 1> &c, std::int64_t ldc, std::int64_t stridec, std::int64_t batch_size) { dgmm_batch_precondition(queue, left_right, m, n, a, lda, stridea, x, incx, stridex, c, ldc, stridec, batch_size); detail::dgmm_batch(get_device_id(queue), queue, left_right, m, n, a, lda, stridea, x, incx, stridex, c, ldc, stridec, batch_size); dgmm_batch_postcondition(queue, left_right, m, n, a, lda, stridea, x, incx, stridex, c, ldc, stridec, batch_size); } static inline void ger(cl::sycl::queue &queue, std::int64_t m, std::int64_t n, float alpha, cl::sycl::buffer &x, std::int64_t incx, cl::sycl::buffer &y, std::int64_t incy, cl::sycl::buffer &a, std::int64_t lda) { ger_precondition(queue, m, n, alpha, x, incx, y, incy, a, lda); detail::ger(get_device_id(queue), queue, m, n, alpha, x, incx, y, incy, a, lda); ger_postcondition(queue, m, n, alpha, x, incx, y, incy, a, lda); } static inline void ger(cl::sycl::queue &queue, std::int64_t m, std::int64_t n, double alpha, cl::sycl::buffer &x, std::int64_t incx, cl::sycl::buffer &y, std::int64_t incy, cl::sycl::buffer &a, std::int64_t lda) { ger_precondition(queue, m, n, alpha, x, incx, y, incy, a, lda); detail::ger(get_device_id(queue), queue, m, n, alpha, x, incx, y, incy, a, lda); ger_postcondition(queue, m, n, alpha, x, incx, y, incy, a, lda); } static inline void gerc(cl::sycl::queue &queue, std::int64_t m, std::int64_t n, std::complex alpha, cl::sycl::buffer, 1> &x, std::int64_t incx, cl::sycl::buffer, 1> &y, std::int64_t incy, cl::sycl::buffer, 1> &a, std::int64_t lda) { gerc_precondition(queue, m, n, alpha, x, incx, y, incy, a, lda); detail::gerc(get_device_id(queue), queue, m, n, alpha, x, incx, y, incy, a, lda); gerc_postcondition(queue, m, n, alpha, x, incx, y, incy, a, lda); } static inline void gerc(cl::sycl::queue &queue, std::int64_t m, std::int64_t n, std::complex alpha, cl::sycl::buffer, 1> &x, std::int64_t incx, cl::sycl::buffer, 1> &y, std::int64_t incy, cl::sycl::buffer, 1> &a, std::int64_t lda) { gerc_precondition(queue, m, n, alpha, x, incx, y, incy, a, lda); detail::gerc(get_device_id(queue), queue, m, n, alpha, x, incx, y, incy, a, lda); gerc_postcondition(queue, m, n, alpha, x, incx, y, incy, a, lda); } static inline void geru(cl::sycl::queue &queue, std::int64_t m, std::int64_t n, std::complex alpha, cl::sycl::buffer, 1> &x, std::int64_t incx, cl::sycl::buffer, 1> &y, std::int64_t incy, cl::sycl::buffer, 1> &a, std::int64_t lda) { geru_precondition(queue, m, n, alpha, x, incx, y, incy, a, lda); detail::geru(get_device_id(queue), queue, m, n, alpha, x, incx, y, incy, a, lda); geru_postcondition(queue, m, n, alpha, x, incx, y, incy, a, lda); } static inline void geru(cl::sycl::queue &queue, std::int64_t m, std::int64_t n, std::complex alpha, cl::sycl::buffer, 1> &x, std::int64_t incx, cl::sycl::buffer, 1> &y, std::int64_t incy, cl::sycl::buffer, 1> &a, std::int64_t lda) { geru_precondition(queue, m, n, alpha, x, incx, y, incy, a, lda); detail::geru(get_device_id(queue), queue, m, n, alpha, x, incx, y, incy, a, lda); geru_postcondition(queue, m, n, alpha, x, incx, y, incy, a, lda); } static inline void hbmv(cl::sycl::queue &queue, uplo upper_lower, std::int64_t n, std::int64_t k, std::complex alpha, cl::sycl::buffer, 1> &a, std::int64_t lda, cl::sycl::buffer, 1> &x, std::int64_t incx, std::complex beta, cl::sycl::buffer, 1> &y, std::int64_t incy) { hbmv_precondition(queue, upper_lower, n, k, alpha, a, lda, x, incx, beta, y, incy); detail::hbmv(get_device_id(queue), queue, upper_lower, n, k, alpha, a, lda, x, incx, beta, y, incy); hbmv_postcondition(queue, upper_lower, n, k, alpha, a, lda, x, incx, beta, y, incy); } static inline void hbmv(cl::sycl::queue &queue, uplo upper_lower, std::int64_t n, std::int64_t k, std::complex alpha, cl::sycl::buffer, 1> &a, std::int64_t lda, cl::sycl::buffer, 1> &x, std::int64_t incx, std::complex beta, cl::sycl::buffer, 1> &y, std::int64_t incy) { hbmv_precondition(queue, upper_lower, n, k, alpha, a, lda, x, incx, beta, y, incy); detail::hbmv(get_device_id(queue), queue, upper_lower, n, k, alpha, a, lda, x, incx, beta, y, incy); hbmv_postcondition(queue, upper_lower, n, k, alpha, a, lda, x, incx, beta, y, incy); } static inline void hemm(cl::sycl::queue &queue, side left_right, uplo upper_lower, std::int64_t m, std::int64_t n, std::complex alpha, cl::sycl::buffer, 1> &a, std::int64_t lda, cl::sycl::buffer, 1> &b, std::int64_t ldb, std::complex beta, cl::sycl::buffer, 1> &c, std::int64_t ldc) { hemm_precondition(queue, left_right, upper_lower, m, n, alpha, a, lda, b, ldb, beta, c, ldc); detail::hemm(get_device_id(queue), queue, left_right, upper_lower, m, n, alpha, a, lda, b, ldb, beta, c, ldc); hemm_postcondition(queue, left_right, upper_lower, m, n, alpha, a, lda, b, ldb, beta, c, ldc); } static inline void hemm(cl::sycl::queue &queue, side left_right, uplo upper_lower, std::int64_t m, std::int64_t n, std::complex alpha, cl::sycl::buffer, 1> &a, std::int64_t lda, cl::sycl::buffer, 1> &b, std::int64_t ldb, std::complex beta, cl::sycl::buffer, 1> &c, std::int64_t ldc) { hemm_precondition(queue, left_right, upper_lower, m, n, alpha, a, lda, b, ldb, beta, c, ldc); detail::hemm(get_device_id(queue), queue, left_right, upper_lower, m, n, alpha, a, lda, b, ldb, beta, c, ldc); hemm_postcondition(queue, left_right, upper_lower, m, n, alpha, a, lda, b, ldb, beta, c, ldc); } static inline void hemv(cl::sycl::queue &queue, uplo upper_lower, std::int64_t n, std::complex alpha, cl::sycl::buffer, 1> &a, std::int64_t lda, cl::sycl::buffer, 1> &x, std::int64_t incx, std::complex beta, cl::sycl::buffer, 1> &y, std::int64_t incy) { hemv_precondition(queue, upper_lower, n, alpha, a, lda, x, incx, beta, y, incy); detail::hemv(get_device_id(queue), queue, upper_lower, n, alpha, a, lda, x, incx, beta, y, incy); hemv_postcondition(queue, upper_lower, n, alpha, a, lda, x, incx, beta, y, incy); } static inline void hemv(cl::sycl::queue &queue, uplo upper_lower, std::int64_t n, std::complex alpha, cl::sycl::buffer, 1> &a, std::int64_t lda, cl::sycl::buffer, 1> &x, std::int64_t incx, std::complex beta, cl::sycl::buffer, 1> &y, std::int64_t incy) { hemv_precondition(queue, upper_lower, n, alpha, a, lda, x, incx, beta, y, incy); detail::hemv(get_device_id(queue), queue, upper_lower, n, alpha, a, lda, x, incx, beta, y, incy); hemv_postcondition(queue, upper_lower, n, alpha, a, lda, x, incx, beta, y, incy); } static inline void her(cl::sycl::queue &queue, uplo upper_lower, std::int64_t n, float alpha, cl::sycl::buffer, 1> &x, std::int64_t incx, cl::sycl::buffer, 1> &a, std::int64_t lda) { her_precondition(queue, upper_lower, n, alpha, x, incx, a, lda); detail::her(get_device_id(queue), queue, upper_lower, n, alpha, x, incx, a, lda); her_postcondition(queue, upper_lower, n, alpha, x, incx, a, lda); } static inline void her(cl::sycl::queue &queue, uplo upper_lower, std::int64_t n, double alpha, cl::sycl::buffer, 1> &x, std::int64_t incx, cl::sycl::buffer, 1> &a, std::int64_t lda) { her_precondition(queue, upper_lower, n, alpha, x, incx, a, lda); detail::her(get_device_id(queue), queue, upper_lower, n, alpha, x, incx, a, lda); her_postcondition(queue, upper_lower, n, alpha, x, incx, a, lda); } static inline void her2(cl::sycl::queue &queue, uplo upper_lower, std::int64_t n, std::complex alpha, cl::sycl::buffer, 1> &x, std::int64_t incx, cl::sycl::buffer, 1> &y, std::int64_t incy, cl::sycl::buffer, 1> &a, std::int64_t lda) { her2_precondition(queue, upper_lower, n, alpha, x, incx, y, incy, a, lda); detail::her2(get_device_id(queue), queue, upper_lower, n, alpha, x, incx, y, incy, a, lda); her2_postcondition(queue, upper_lower, n, alpha, x, incx, y, incy, a, lda); } static inline void her2(cl::sycl::queue &queue, uplo upper_lower, std::int64_t n, std::complex alpha, cl::sycl::buffer, 1> &x, std::int64_t incx, cl::sycl::buffer, 1> &y, std::int64_t incy, cl::sycl::buffer, 1> &a, std::int64_t lda) { her2_precondition(queue, upper_lower, n, alpha, x, incx, y, incy, a, lda); detail::her2(get_device_id(queue), queue, upper_lower, n, alpha, x, incx, y, incy, a, lda); her2_postcondition(queue, upper_lower, n, alpha, x, incx, y, incy, a, lda); } static inline void her2k(cl::sycl::queue &queue, uplo upper_lower, transpose trans, std::int64_t n, std::int64_t k, std::complex alpha, cl::sycl::buffer, 1> &a, std::int64_t lda, cl::sycl::buffer, 1> &b, std::int64_t ldb, float beta, cl::sycl::buffer, 1> &c, std::int64_t ldc) { her2k_precondition(queue, upper_lower, trans, n, k, alpha, a, lda, b, ldb, beta, c, ldc); detail::her2k(get_device_id(queue), queue, upper_lower, trans, n, k, alpha, a, lda, b, ldb, beta, c, ldc); her2k_postcondition(queue, upper_lower, trans, n, k, alpha, a, lda, b, ldb, beta, c, ldc); } static inline void her2k(cl::sycl::queue &queue, uplo upper_lower, transpose trans, std::int64_t n, std::int64_t k, std::complex alpha, cl::sycl::buffer, 1> &a, std::int64_t lda, cl::sycl::buffer, 1> &b, std::int64_t ldb, double beta, cl::sycl::buffer, 1> &c, std::int64_t ldc) { her2k_precondition(queue, upper_lower, trans, n, k, alpha, a, lda, b, ldb, beta, c, ldc); detail::her2k(get_device_id(queue), queue, upper_lower, trans, n, k, alpha, a, lda, b, ldb, beta, c, ldc); her2k_postcondition(queue, upper_lower, trans, n, k, alpha, a, lda, b, ldb, beta, c, ldc); } static inline void herk(cl::sycl::queue &queue, uplo upper_lower, transpose trans, std::int64_t n, std::int64_t k, float alpha, cl::sycl::buffer, 1> &a, std::int64_t lda, float beta, cl::sycl::buffer, 1> &c, std::int64_t ldc) { herk_precondition(queue, upper_lower, trans, n, k, alpha, a, lda, beta, c, ldc); detail::herk(get_device_id(queue), queue, upper_lower, trans, n, k, alpha, a, lda, beta, c, ldc); herk_postcondition(queue, upper_lower, trans, n, k, alpha, a, lda, beta, c, ldc); } static inline void herk(cl::sycl::queue &queue, uplo upper_lower, transpose trans, std::int64_t n, std::int64_t k, double alpha, cl::sycl::buffer, 1> &a, std::int64_t lda, double beta, cl::sycl::buffer, 1> &c, std::int64_t ldc) { herk_precondition(queue, upper_lower, trans, n, k, alpha, a, lda, beta, c, ldc); detail::herk(get_device_id(queue), queue, upper_lower, trans, n, k, alpha, a, lda, beta, c, ldc); herk_postcondition(queue, upper_lower, trans, n, k, alpha, a, lda, beta, c, ldc); } static inline void hpmv(cl::sycl::queue &queue, uplo upper_lower, std::int64_t n, std::complex alpha, cl::sycl::buffer, 1> &a, cl::sycl::buffer, 1> &x, std::int64_t incx, std::complex beta, cl::sycl::buffer, 1> &y, std::int64_t incy) { hpmv_precondition(queue, upper_lower, n, alpha, a, x, incx, beta, y, incy); detail::hpmv(get_device_id(queue), queue, upper_lower, n, alpha, a, x, incx, beta, y, incy); hpmv_postcondition(queue, upper_lower, n, alpha, a, x, incx, beta, y, incy); } static inline void hpmv(cl::sycl::queue &queue, uplo upper_lower, std::int64_t n, std::complex alpha, cl::sycl::buffer, 1> &a, cl::sycl::buffer, 1> &x, std::int64_t incx, std::complex beta, cl::sycl::buffer, 1> &y, std::int64_t incy) { hpmv_precondition(queue, upper_lower, n, alpha, a, x, incx, beta, y, incy); detail::hpmv(get_device_id(queue), queue, upper_lower, n, alpha, a, x, incx, beta, y, incy); hpmv_postcondition(queue, upper_lower, n, alpha, a, x, incx, beta, y, incy); } static inline void hpr(cl::sycl::queue &queue, uplo upper_lower, std::int64_t n, float alpha, cl::sycl::buffer, 1> &x, std::int64_t incx, cl::sycl::buffer, 1> &a) { hpr_precondition(queue, upper_lower, n, alpha, x, incx, a); detail::hpr(get_device_id(queue), queue, upper_lower, n, alpha, x, incx, a); hpr_postcondition(queue, upper_lower, n, alpha, x, incx, a); } static inline void hpr(cl::sycl::queue &queue, uplo upper_lower, std::int64_t n, double alpha, cl::sycl::buffer, 1> &x, std::int64_t incx, cl::sycl::buffer, 1> &a) { hpr_precondition(queue, upper_lower, n, alpha, x, incx, a); detail::hpr(get_device_id(queue), queue, upper_lower, n, alpha, x, incx, a); hpr_postcondition(queue, upper_lower, n, alpha, x, incx, a); } static inline void hpr2(cl::sycl::queue &queue, uplo upper_lower, std::int64_t n, std::complex alpha, cl::sycl::buffer, 1> &x, std::int64_t incx, cl::sycl::buffer, 1> &y, std::int64_t incy, cl::sycl::buffer, 1> &a) { hpr2_precondition(queue, upper_lower, n, alpha, x, incx, y, incy, a); detail::hpr2(get_device_id(queue), queue, upper_lower, n, alpha, x, incx, y, incy, a); hpr2_postcondition(queue, upper_lower, n, alpha, x, incx, y, incy, a); } static inline void hpr2(cl::sycl::queue &queue, uplo upper_lower, std::int64_t n, std::complex alpha, cl::sycl::buffer, 1> &x, std::int64_t incx, cl::sycl::buffer, 1> &y, std::int64_t incy, cl::sycl::buffer, 1> &a) { hpr2_precondition(queue, upper_lower, n, alpha, x, incx, y, incy, a); detail::hpr2(get_device_id(queue), queue, upper_lower, n, alpha, x, incx, y, incy, a); hpr2_postcondition(queue, upper_lower, n, alpha, x, incx, y, incy, a); } static inline void iamax(cl::sycl::queue &queue, std::int64_t n, cl::sycl::buffer &x, std::int64_t incx, cl::sycl::buffer &result) { iamax_precondition(queue, n, x, incx, result); detail::iamax(get_device_id(queue), queue, n, x, incx, result); iamax_postcondition(queue, n, x, incx, result); } static inline void iamax(cl::sycl::queue &queue, std::int64_t n, cl::sycl::buffer &x, std::int64_t incx, cl::sycl::buffer &result) { iamax_precondition(queue, n, x, incx, result); detail::iamax(get_device_id(queue), queue, n, x, incx, result); iamax_postcondition(queue, n, x, incx, result); } static inline void iamax(cl::sycl::queue &queue, std::int64_t n, cl::sycl::buffer, 1> &x, std::int64_t incx, cl::sycl::buffer &result) { iamax_precondition(queue, n, x, incx, result); detail::iamax(get_device_id(queue), queue, n, x, incx, result); iamax_postcondition(queue, n, x, incx, result); } static inline void iamax(cl::sycl::queue &queue, std::int64_t n, cl::sycl::buffer, 1> &x, std::int64_t incx, cl::sycl::buffer &result) { iamax_precondition(queue, n, x, incx, result); detail::iamax(get_device_id(queue), queue, n, x, incx, result); iamax_postcondition(queue, n, x, incx, result); } static inline void iamin(cl::sycl::queue &queue, std::int64_t n, cl::sycl::buffer &x, std::int64_t incx, cl::sycl::buffer &result) { iamin_precondition(queue, n, x, incx, result); detail::iamin(get_device_id(queue), queue, n, x, incx, result); iamin_postcondition(queue, n, x, incx, result); } static inline void iamin(cl::sycl::queue &queue, std::int64_t n, cl::sycl::buffer &x, std::int64_t incx, cl::sycl::buffer &result) { iamin_precondition(queue, n, x, incx, result); detail::iamin(get_device_id(queue), queue, n, x, incx, result); iamin_postcondition(queue, n, x, incx, result); } static inline void iamin(cl::sycl::queue &queue, std::int64_t n, cl::sycl::buffer, 1> &x, std::int64_t incx, cl::sycl::buffer &result) { iamin_precondition(queue, n, x, incx, result); detail::iamin(get_device_id(queue), queue, n, x, incx, result); iamin_postcondition(queue, n, x, incx, result); } static inline void iamin(cl::sycl::queue &queue, std::int64_t n, cl::sycl::buffer, 1> &x, std::int64_t incx, cl::sycl::buffer &result) { iamin_precondition(queue, n, x, incx, result); detail::iamin(get_device_id(queue), queue, n, x, incx, result); iamin_postcondition(queue, n, x, incx, result); } static inline void nrm2(cl::sycl::queue &queue, std::int64_t n, cl::sycl::buffer, 1> &x, std::int64_t incx, cl::sycl::buffer &result) { nrm2_precondition(queue, n, x, incx, result); detail::nrm2(get_device_id(queue), queue, n, x, incx, result); nrm2_postcondition(queue, n, x, incx, result); } static inline void nrm2(cl::sycl::queue &queue, std::int64_t n, cl::sycl::buffer, 1> &x, std::int64_t incx, cl::sycl::buffer &result) { nrm2_precondition(queue, n, x, incx, result); detail::nrm2(get_device_id(queue), queue, n, x, incx, result); nrm2_postcondition(queue, n, x, incx, result); } static inline void nrm2(cl::sycl::queue &queue, std::int64_t n, cl::sycl::buffer &x, std::int64_t incx, cl::sycl::buffer &result) { nrm2_precondition(queue, n, x, incx, result); detail::nrm2(get_device_id(queue), queue, n, x, incx, result); nrm2_postcondition(queue, n, x, incx, result); } static inline void nrm2(cl::sycl::queue &queue, std::int64_t n, cl::sycl::buffer &x, std::int64_t incx, cl::sycl::buffer &result) { nrm2_precondition(queue, n, x, incx, result); detail::nrm2(get_device_id(queue), queue, n, x, incx, result); nrm2_postcondition(queue, n, x, incx, result); } static inline void rot(cl::sycl::queue &queue, std::int64_t n, cl::sycl::buffer, 1> &x, std::int64_t incx, cl::sycl::buffer, 1> &y, std::int64_t incy, float c, float s) { rot_precondition(queue, n, x, incx, y, incy, c, s); detail::rot(get_device_id(queue), queue, n, x, incx, y, incy, c, s); rot_postcondition(queue, n, x, incx, y, incy, c, s); } static inline void rot(cl::sycl::queue &queue, std::int64_t n, cl::sycl::buffer, 1> &x, std::int64_t incx, cl::sycl::buffer, 1> &y, std::int64_t incy, double c, double s) { rot_precondition(queue, n, x, incx, y, incy, c, s); detail::rot(get_device_id(queue), queue, n, x, incx, y, incy, c, s); rot_postcondition(queue, n, x, incx, y, incy, c, s); } static inline void rot(cl::sycl::queue &queue, std::int64_t n, cl::sycl::buffer &x, std::int64_t incx, cl::sycl::buffer &y, std::int64_t incy, float c, float s) { rot_precondition(queue, n, x, incx, y, incy, c, s); detail::rot(get_device_id(queue), queue, n, x, incx, y, incy, c, s); rot_postcondition(queue, n, x, incx, y, incy, c, s); } static inline void rot(cl::sycl::queue &queue, std::int64_t n, cl::sycl::buffer &x, std::int64_t incx, cl::sycl::buffer &y, std::int64_t incy, double c, double s) { rot_precondition(queue, n, x, incx, y, incy, c, s); detail::rot(get_device_id(queue), queue, n, x, incx, y, incy, c, s); rot_postcondition(queue, n, x, incx, y, incy, c, s); } static inline void rotg(cl::sycl::queue &queue, cl::sycl::buffer &a, cl::sycl::buffer &b, cl::sycl::buffer &c, cl::sycl::buffer &s) { rotg_precondition(queue, a, b, c, s); detail::rotg(get_device_id(queue), queue, a, b, c, s); rotg_postcondition(queue, a, b, c, s); } static inline void rotg(cl::sycl::queue &queue, cl::sycl::buffer &a, cl::sycl::buffer &b, cl::sycl::buffer &c, cl::sycl::buffer &s) { rotg_precondition(queue, a, b, c, s); detail::rotg(get_device_id(queue), queue, a, b, c, s); rotg_postcondition(queue, a, b, c, s); } static inline void rotg(cl::sycl::queue &queue, cl::sycl::buffer, 1> &a, cl::sycl::buffer, 1> &b, cl::sycl::buffer &c, cl::sycl::buffer, 1> &s) { rotg_precondition(queue, a, b, c, s); detail::rotg(get_device_id(queue), queue, a, b, c, s); rotg_postcondition(queue, a, b, c, s); } static inline void rotg(cl::sycl::queue &queue, cl::sycl::buffer, 1> &a, cl::sycl::buffer, 1> &b, cl::sycl::buffer &c, cl::sycl::buffer, 1> &s) { rotg_precondition(queue, a, b, c, s); detail::rotg(get_device_id(queue), queue, a, b, c, s); rotg_postcondition(queue, a, b, c, s); } static inline void rotm(cl::sycl::queue &queue, std::int64_t n, cl::sycl::buffer &x, std::int64_t incx, cl::sycl::buffer &y, std::int64_t incy, cl::sycl::buffer ¶m) { rotm_precondition(queue, n, x, incx, y, incy, param); detail::rotm(get_device_id(queue), queue, n, x, incx, y, incy, param); rotm_postcondition(queue, n, x, incx, y, incy, param); } static inline void rotm(cl::sycl::queue &queue, std::int64_t n, cl::sycl::buffer &x, std::int64_t incx, cl::sycl::buffer &y, std::int64_t incy, cl::sycl::buffer ¶m) { rotm_precondition(queue, n, x, incx, y, incy, param); detail::rotm(get_device_id(queue), queue, n, x, incx, y, incy, param); rotm_postcondition(queue, n, x, incx, y, incy, param); } static inline void rotmg(cl::sycl::queue &queue, cl::sycl::buffer &d1, cl::sycl::buffer &d2, cl::sycl::buffer &x1, float y1, cl::sycl::buffer ¶m) { rotmg_precondition(queue, d1, d2, x1, y1, param); detail::rotmg(get_device_id(queue), queue, d1, d2, x1, y1, param); rotmg_postcondition(queue, d1, d2, x1, y1, param); } static inline void rotmg(cl::sycl::queue &queue, cl::sycl::buffer &d1, cl::sycl::buffer &d2, cl::sycl::buffer &x1, double y1, cl::sycl::buffer ¶m) { rotmg_precondition(queue, d1, d2, x1, y1, param); detail::rotmg(get_device_id(queue), queue, d1, d2, x1, y1, param); rotmg_postcondition(queue, d1, d2, x1, y1, param); } static inline void sbmv(cl::sycl::queue &queue, uplo upper_lower, std::int64_t n, std::int64_t k, float alpha, cl::sycl::buffer &a, std::int64_t lda, cl::sycl::buffer &x, std::int64_t incx, float beta, cl::sycl::buffer &y, std::int64_t incy) { sbmv_precondition(queue, upper_lower, n, k, alpha, a, lda, x, incx, beta, y, incy); detail::sbmv(get_device_id(queue), queue, upper_lower, n, k, alpha, a, lda, x, incx, beta, y, incy); sbmv_postcondition(queue, upper_lower, n, k, alpha, a, lda, x, incx, beta, y, incy); } static inline void sbmv(cl::sycl::queue &queue, uplo upper_lower, std::int64_t n, std::int64_t k, double alpha, cl::sycl::buffer &a, std::int64_t lda, cl::sycl::buffer &x, std::int64_t incx, double beta, cl::sycl::buffer &y, std::int64_t incy) { sbmv_precondition(queue, upper_lower, n, k, alpha, a, lda, x, incx, beta, y, incy); detail::sbmv(get_device_id(queue), queue, upper_lower, n, k, alpha, a, lda, x, incx, beta, y, incy); sbmv_postcondition(queue, upper_lower, n, k, alpha, a, lda, x, incx, beta, y, incy); } static inline void scal(cl::sycl::queue &queue, std::int64_t n, float alpha, cl::sycl::buffer &x, std::int64_t incx) { scal_precondition(queue, n, alpha, x, incx); detail::scal(get_device_id(queue), queue, n, alpha, x, incx); scal_postcondition(queue, n, alpha, x, incx); } static inline void scal(cl::sycl::queue &queue, std::int64_t n, double alpha, cl::sycl::buffer &x, std::int64_t incx) { scal_precondition(queue, n, alpha, x, incx); detail::scal(get_device_id(queue), queue, n, alpha, x, incx); scal_postcondition(queue, n, alpha, x, incx); } static inline void scal(cl::sycl::queue &queue, std::int64_t n, std::complex alpha, cl::sycl::buffer, 1> &x, std::int64_t incx) { scal_precondition(queue, n, alpha, x, incx); detail::scal(get_device_id(queue), queue, n, alpha, x, incx); scal_postcondition(queue, n, alpha, x, incx); } static inline void scal(cl::sycl::queue &queue, std::int64_t n, std::complex alpha, cl::sycl::buffer, 1> &x, std::int64_t incx) { scal_precondition(queue, n, alpha, x, incx); detail::scal(get_device_id(queue), queue, n, alpha, x, incx); scal_postcondition(queue, n, alpha, x, incx); } static inline void scal(cl::sycl::queue &queue, std::int64_t n, float alpha, cl::sycl::buffer, 1> &x, std::int64_t incx) { scal_precondition(queue, n, alpha, x, incx); detail::scal(get_device_id(queue), queue, n, alpha, x, incx); scal_postcondition(queue, n, alpha, x, incx); } static inline void scal(cl::sycl::queue &queue, std::int64_t n, double alpha, cl::sycl::buffer, 1> &x, std::int64_t incx) { scal_precondition(queue, n, alpha, x, incx); detail::scal(get_device_id(queue), queue, n, alpha, x, incx); scal_postcondition(queue, n, alpha, x, incx); } static inline void sdsdot(cl::sycl::queue &queue, std::int64_t n, float sb, cl::sycl::buffer &x, std::int64_t incx, cl::sycl::buffer &y, std::int64_t incy, cl::sycl::buffer &result) { sdsdot_precondition(queue, n, sb, x, incx, y, incy, result); detail::sdsdot(get_device_id(queue), queue, n, sb, x, incx, y, incy, result); sdsdot_postcondition(queue, n, sb, x, incx, y, incy, result); } static inline void spmv(cl::sycl::queue &queue, uplo upper_lower, std::int64_t n, float alpha, cl::sycl::buffer &a, cl::sycl::buffer &x, std::int64_t incx, float beta, cl::sycl::buffer &y, std::int64_t incy) { spmv_precondition(queue, upper_lower, n, alpha, a, x, incx, beta, y, incy); detail::spmv(get_device_id(queue), queue, upper_lower, n, alpha, a, x, incx, beta, y, incy); spmv_postcondition(queue, upper_lower, n, alpha, a, x, incx, beta, y, incy); } static inline void spmv(cl::sycl::queue &queue, uplo upper_lower, std::int64_t n, double alpha, cl::sycl::buffer &a, cl::sycl::buffer &x, std::int64_t incx, double beta, cl::sycl::buffer &y, std::int64_t incy) { spmv_precondition(queue, upper_lower, n, alpha, a, x, incx, beta, y, incy); detail::spmv(get_device_id(queue), queue, upper_lower, n, alpha, a, x, incx, beta, y, incy); spmv_postcondition(queue, upper_lower, n, alpha, a, x, incx, beta, y, incy); } static inline void spr(cl::sycl::queue &queue, uplo upper_lower, std::int64_t n, float alpha, cl::sycl::buffer &x, std::int64_t incx, cl::sycl::buffer &a) { spr_precondition(queue, upper_lower, n, alpha, x, incx, a); detail::spr(get_device_id(queue), queue, upper_lower, n, alpha, x, incx, a); spr_postcondition(queue, upper_lower, n, alpha, x, incx, a); } static inline void spr(cl::sycl::queue &queue, uplo upper_lower, std::int64_t n, double alpha, cl::sycl::buffer &x, std::int64_t incx, cl::sycl::buffer &a) { spr_precondition(queue, upper_lower, n, alpha, x, incx, a); detail::spr(get_device_id(queue), queue, upper_lower, n, alpha, x, incx, a); spr_postcondition(queue, upper_lower, n, alpha, x, incx, a); } static inline void spr2(cl::sycl::queue &queue, uplo upper_lower, std::int64_t n, float alpha, cl::sycl::buffer &x, std::int64_t incx, cl::sycl::buffer &y, std::int64_t incy, cl::sycl::buffer &a) { spr2_precondition(queue, upper_lower, n, alpha, x, incx, y, incy, a); detail::spr2(get_device_id(queue), queue, upper_lower, n, alpha, x, incx, y, incy, a); spr2_postcondition(queue, upper_lower, n, alpha, x, incx, y, incy, a); } static inline void spr2(cl::sycl::queue &queue, uplo upper_lower, std::int64_t n, double alpha, cl::sycl::buffer &x, std::int64_t incx, cl::sycl::buffer &y, std::int64_t incy, cl::sycl::buffer &a) { spr2_precondition(queue, upper_lower, n, alpha, x, incx, y, incy, a); detail::spr2(get_device_id(queue), queue, upper_lower, n, alpha, x, incx, y, incy, a); spr2_postcondition(queue, upper_lower, n, alpha, x, incx, y, incy, a); } static inline void swap(cl::sycl::queue &queue, std::int64_t n, cl::sycl::buffer &x, std::int64_t incx, cl::sycl::buffer &y, std::int64_t incy) { swap_precondition(queue, n, x, incx, y, incy); detail::swap(get_device_id(queue), queue, n, x, incx, y, incy); swap_postcondition(queue, n, x, incx, y, incy); } static inline void swap(cl::sycl::queue &queue, std::int64_t n, cl::sycl::buffer &x, std::int64_t incx, cl::sycl::buffer &y, std::int64_t incy) { swap_precondition(queue, n, x, incx, y, incy); detail::swap(get_device_id(queue), queue, n, x, incx, y, incy); swap_postcondition(queue, n, x, incx, y, incy); } static inline void swap(cl::sycl::queue &queue, std::int64_t n, cl::sycl::buffer, 1> &x, std::int64_t incx, cl::sycl::buffer, 1> &y, std::int64_t incy) { swap_precondition(queue, n, x, incx, y, incy); detail::swap(get_device_id(queue), queue, n, x, incx, y, incy); swap_postcondition(queue, n, x, incx, y, incy); } static inline void swap(cl::sycl::queue &queue, std::int64_t n, cl::sycl::buffer, 1> &x, std::int64_t incx, cl::sycl::buffer, 1> &y, std::int64_t incy) { swap_precondition(queue, n, x, incx, y, incy); detail::swap(get_device_id(queue), queue, n, x, incx, y, incy); swap_postcondition(queue, n, x, incx, y, incy); } static inline void symm(cl::sycl::queue &queue, side left_right, uplo upper_lower, std::int64_t m, std::int64_t n, float alpha, cl::sycl::buffer &a, std::int64_t lda, cl::sycl::buffer &b, std::int64_t ldb, float beta, cl::sycl::buffer &c, std::int64_t ldc) { symm_precondition(queue, left_right, upper_lower, m, n, alpha, a, lda, b, ldb, beta, c, ldc); detail::symm(get_device_id(queue), queue, left_right, upper_lower, m, n, alpha, a, lda, b, ldb, beta, c, ldc); symm_postcondition(queue, left_right, upper_lower, m, n, alpha, a, lda, b, ldb, beta, c, ldc); } static inline void symm(cl::sycl::queue &queue, side left_right, uplo upper_lower, std::int64_t m, std::int64_t n, double alpha, cl::sycl::buffer &a, std::int64_t lda, cl::sycl::buffer &b, std::int64_t ldb, double beta, cl::sycl::buffer &c, std::int64_t ldc) { symm_precondition(queue, left_right, upper_lower, m, n, alpha, a, lda, b, ldb, beta, c, ldc); detail::symm(get_device_id(queue), queue, left_right, upper_lower, m, n, alpha, a, lda, b, ldb, beta, c, ldc); symm_postcondition(queue, left_right, upper_lower, m, n, alpha, a, lda, b, ldb, beta, c, ldc); } static inline void symm(cl::sycl::queue &queue, side left_right, uplo upper_lower, std::int64_t m, std::int64_t n, std::complex alpha, cl::sycl::buffer, 1> &a, std::int64_t lda, cl::sycl::buffer, 1> &b, std::int64_t ldb, std::complex beta, cl::sycl::buffer, 1> &c, std::int64_t ldc) { symm_precondition(queue, left_right, upper_lower, m, n, alpha, a, lda, b, ldb, beta, c, ldc); detail::symm(get_device_id(queue), queue, left_right, upper_lower, m, n, alpha, a, lda, b, ldb, beta, c, ldc); symm_postcondition(queue, left_right, upper_lower, m, n, alpha, a, lda, b, ldb, beta, c, ldc); } static inline void symm(cl::sycl::queue &queue, side left_right, uplo upper_lower, std::int64_t m, std::int64_t n, std::complex alpha, cl::sycl::buffer, 1> &a, std::int64_t lda, cl::sycl::buffer, 1> &b, std::int64_t ldb, std::complex beta, cl::sycl::buffer, 1> &c, std::int64_t ldc) { symm_precondition(queue, left_right, upper_lower, m, n, alpha, a, lda, b, ldb, beta, c, ldc); detail::symm(get_device_id(queue), queue, left_right, upper_lower, m, n, alpha, a, lda, b, ldb, beta, c, ldc); symm_postcondition(queue, left_right, upper_lower, m, n, alpha, a, lda, b, ldb, beta, c, ldc); } static inline void symv(cl::sycl::queue &queue, uplo upper_lower, std::int64_t n, float alpha, cl::sycl::buffer &a, std::int64_t lda, cl::sycl::buffer &x, std::int64_t incx, float beta, cl::sycl::buffer &y, std::int64_t incy) { symv_precondition(queue, upper_lower, n, alpha, a, lda, x, incx, beta, y, incy); detail::symv(get_device_id(queue), queue, upper_lower, n, alpha, a, lda, x, incx, beta, y, incy); symv_postcondition(queue, upper_lower, n, alpha, a, lda, x, incx, beta, y, incy); } static inline void symv(cl::sycl::queue &queue, uplo upper_lower, std::int64_t n, double alpha, cl::sycl::buffer &a, std::int64_t lda, cl::sycl::buffer &x, std::int64_t incx, double beta, cl::sycl::buffer &y, std::int64_t incy) { symv_precondition(queue, upper_lower, n, alpha, a, lda, x, incx, beta, y, incy); detail::symv(get_device_id(queue), queue, upper_lower, n, alpha, a, lda, x, incx, beta, y, incy); symv_postcondition(queue, upper_lower, n, alpha, a, lda, x, incx, beta, y, incy); } static inline void syr(cl::sycl::queue &queue, uplo upper_lower, std::int64_t n, float alpha, cl::sycl::buffer &x, std::int64_t incx, cl::sycl::buffer &a, std::int64_t lda) { syr_precondition(queue, upper_lower, n, alpha, x, incx, a, lda); detail::syr(get_device_id(queue), queue, upper_lower, n, alpha, x, incx, a, lda); syr_postcondition(queue, upper_lower, n, alpha, x, incx, a, lda); } static inline void syr(cl::sycl::queue &queue, uplo upper_lower, std::int64_t n, double alpha, cl::sycl::buffer &x, std::int64_t incx, cl::sycl::buffer &a, std::int64_t lda) { syr_precondition(queue, upper_lower, n, alpha, x, incx, a, lda); detail::syr(get_device_id(queue), queue, upper_lower, n, alpha, x, incx, a, lda); syr_postcondition(queue, upper_lower, n, alpha, x, incx, a, lda); } static inline void syr2(cl::sycl::queue &queue, uplo upper_lower, std::int64_t n, float alpha, cl::sycl::buffer &x, std::int64_t incx, cl::sycl::buffer &y, std::int64_t incy, cl::sycl::buffer &a, std::int64_t lda) { syr2_precondition(queue, upper_lower, n, alpha, x, incx, y, incy, a, lda); detail::syr2(get_device_id(queue), queue, upper_lower, n, alpha, x, incx, y, incy, a, lda); syr2_postcondition(queue, upper_lower, n, alpha, x, incx, y, incy, a, lda); } static inline void syr2(cl::sycl::queue &queue, uplo upper_lower, std::int64_t n, double alpha, cl::sycl::buffer &x, std::int64_t incx, cl::sycl::buffer &y, std::int64_t incy, cl::sycl::buffer &a, std::int64_t lda) { syr2_precondition(queue, upper_lower, n, alpha, x, incx, y, incy, a, lda); detail::syr2(get_device_id(queue), queue, upper_lower, n, alpha, x, incx, y, incy, a, lda); syr2_postcondition(queue, upper_lower, n, alpha, x, incx, y, incy, a, lda); } static inline void syr2k(cl::sycl::queue &queue, uplo upper_lower, transpose trans, std::int64_t n, std::int64_t k, float alpha, cl::sycl::buffer &a, std::int64_t lda, cl::sycl::buffer &b, std::int64_t ldb, float beta, cl::sycl::buffer &c, std::int64_t ldc) { syr2k_precondition(queue, upper_lower, trans, n, k, alpha, a, lda, b, ldb, beta, c, ldc); detail::syr2k(get_device_id(queue), queue, upper_lower, trans, n, k, alpha, a, lda, b, ldb, beta, c, ldc); syr2k_postcondition(queue, upper_lower, trans, n, k, alpha, a, lda, b, ldb, beta, c, ldc); } static inline void syr2k(cl::sycl::queue &queue, uplo upper_lower, transpose trans, std::int64_t n, std::int64_t k, double alpha, cl::sycl::buffer &a, std::int64_t lda, cl::sycl::buffer &b, std::int64_t ldb, double beta, cl::sycl::buffer &c, std::int64_t ldc) { syr2k_precondition(queue, upper_lower, trans, n, k, alpha, a, lda, b, ldb, beta, c, ldc); detail::syr2k(get_device_id(queue), queue, upper_lower, trans, n, k, alpha, a, lda, b, ldb, beta, c, ldc); syr2k_postcondition(queue, upper_lower, trans, n, k, alpha, a, lda, b, ldb, beta, c, ldc); } static inline void syr2k(cl::sycl::queue &queue, uplo upper_lower, transpose trans, std::int64_t n, std::int64_t k, std::complex alpha, cl::sycl::buffer, 1> &a, std::int64_t lda, cl::sycl::buffer, 1> &b, std::int64_t ldb, std::complex beta, cl::sycl::buffer, 1> &c, std::int64_t ldc) { syr2k_precondition(queue, upper_lower, trans, n, k, alpha, a, lda, b, ldb, beta, c, ldc); detail::syr2k(get_device_id(queue), queue, upper_lower, trans, n, k, alpha, a, lda, b, ldb, beta, c, ldc); syr2k_postcondition(queue, upper_lower, trans, n, k, alpha, a, lda, b, ldb, beta, c, ldc); } static inline void syr2k(cl::sycl::queue &queue, uplo upper_lower, transpose trans, std::int64_t n, std::int64_t k, std::complex alpha, cl::sycl::buffer, 1> &a, std::int64_t lda, cl::sycl::buffer, 1> &b, std::int64_t ldb, std::complex beta, cl::sycl::buffer, 1> &c, std::int64_t ldc) { syr2k_precondition(queue, upper_lower, trans, n, k, alpha, a, lda, b, ldb, beta, c, ldc); detail::syr2k(get_device_id(queue), queue, upper_lower, trans, n, k, alpha, a, lda, b, ldb, beta, c, ldc); syr2k_postcondition(queue, upper_lower, trans, n, k, alpha, a, lda, b, ldb, beta, c, ldc); } static inline void syrk(cl::sycl::queue &queue, uplo upper_lower, transpose trans, std::int64_t n, std::int64_t k, float alpha, cl::sycl::buffer &a, std::int64_t lda, float beta, cl::sycl::buffer &c, std::int64_t ldc) { syrk_precondition(queue, upper_lower, trans, n, k, alpha, a, lda, beta, c, ldc); detail::syrk(get_device_id(queue), queue, upper_lower, trans, n, k, alpha, a, lda, beta, c, ldc); syrk_postcondition(queue, upper_lower, trans, n, k, alpha, a, lda, beta, c, ldc); } static inline void syrk(cl::sycl::queue &queue, uplo upper_lower, transpose trans, std::int64_t n, std::int64_t k, double alpha, cl::sycl::buffer &a, std::int64_t lda, double beta, cl::sycl::buffer &c, std::int64_t ldc) { syrk_precondition(queue, upper_lower, trans, n, k, alpha, a, lda, beta, c, ldc); detail::syrk(get_device_id(queue), queue, upper_lower, trans, n, k, alpha, a, lda, beta, c, ldc); syrk_postcondition(queue, upper_lower, trans, n, k, alpha, a, lda, beta, c, ldc); } static inline void syrk(cl::sycl::queue &queue, uplo upper_lower, transpose trans, std::int64_t n, std::int64_t k, std::complex alpha, cl::sycl::buffer, 1> &a, std::int64_t lda, std::complex beta, cl::sycl::buffer, 1> &c, std::int64_t ldc) { syrk_precondition(queue, upper_lower, trans, n, k, alpha, a, lda, beta, c, ldc); detail::syrk(get_device_id(queue), queue, upper_lower, trans, n, k, alpha, a, lda, beta, c, ldc); syrk_postcondition(queue, upper_lower, trans, n, k, alpha, a, lda, beta, c, ldc); } static inline void syrk(cl::sycl::queue &queue, uplo upper_lower, transpose trans, std::int64_t n, std::int64_t k, std::complex alpha, cl::sycl::buffer, 1> &a, std::int64_t lda, std::complex beta, cl::sycl::buffer, 1> &c, std::int64_t ldc) { syrk_precondition(queue, upper_lower, trans, n, k, alpha, a, lda, beta, c, ldc); detail::syrk(get_device_id(queue), queue, upper_lower, trans, n, k, alpha, a, lda, beta, c, ldc); syrk_postcondition(queue, upper_lower, trans, n, k, alpha, a, lda, beta, c, ldc); } static inline void syrk_batch(cl::sycl::queue &queue, uplo upper_lower, transpose trans, std::int64_t n, std::int64_t k, float alpha, cl::sycl::buffer &a, std::int64_t lda, std::int64_t stride_a, float beta, cl::sycl::buffer &c, std::int64_t ldc, std::int64_t stride_c, std::int64_t batch_size) { syrk_batch_precondition(queue, upper_lower, trans, n, k, alpha, a, lda, stride_a, beta, c, ldc, stride_c, batch_size); detail::syrk_batch(get_device_id(queue), queue, upper_lower, trans, n, k, alpha, a, lda, stride_a, beta, c, ldc, stride_c, batch_size); syrk_batch_postcondition(queue, upper_lower, trans, n, k, alpha, a, lda, stride_a, beta, c, ldc, stride_c, batch_size); } static inline void syrk_batch(cl::sycl::queue &queue, uplo upper_lower, transpose trans, std::int64_t n, std::int64_t k, double alpha, cl::sycl::buffer &a, std::int64_t lda, std::int64_t stride_a, double beta, cl::sycl::buffer &c, std::int64_t ldc, std::int64_t stride_c, std::int64_t batch_size) { syrk_batch_precondition(queue, upper_lower, trans, n, k, alpha, a, lda, stride_a, beta, c, ldc, stride_c, batch_size); detail::syrk_batch(get_device_id(queue), queue, upper_lower, trans, n, k, alpha, a, lda, stride_a, beta, c, ldc, stride_c, batch_size); syrk_batch_postcondition(queue, upper_lower, trans, n, k, alpha, a, lda, stride_a, beta, c, ldc, stride_c, batch_size); } static inline void syrk_batch(cl::sycl::queue &queue, uplo upper_lower, transpose trans, std::int64_t n, std::int64_t k, std::complex alpha, cl::sycl::buffer, 1> &a, std::int64_t lda, std::int64_t stride_a, std::complex beta, cl::sycl::buffer, 1> &c, std::int64_t ldc, std::int64_t stride_c, std::int64_t batch_size) { syrk_batch_precondition(queue, upper_lower, trans, n, k, alpha, a, lda, stride_a, beta, c, ldc, stride_c, batch_size); detail::syrk_batch(get_device_id(queue), queue, upper_lower, trans, n, k, alpha, a, lda, stride_a, beta, c, ldc, stride_c, batch_size); syrk_batch_postcondition(queue, upper_lower, trans, n, k, alpha, a, lda, stride_a, beta, c, ldc, stride_c, batch_size); } static inline void syrk_batch(cl::sycl::queue &queue, uplo upper_lower, transpose trans, std::int64_t n, std::int64_t k, std::complex alpha, cl::sycl::buffer, 1> &a, std::int64_t lda, std::int64_t stride_a, std::complex beta, cl::sycl::buffer, 1> &c, std::int64_t ldc, std::int64_t stride_c, std::int64_t batch_size) { syrk_batch_precondition(queue, upper_lower, trans, n, k, alpha, a, lda, stride_a, beta, c, ldc, stride_c, batch_size); detail::syrk_batch(get_device_id(queue), queue, upper_lower, trans, n, k, alpha, a, lda, stride_a, beta, c, ldc, stride_c, batch_size); syrk_batch_postcondition(queue, upper_lower, trans, n, k, alpha, a, lda, stride_a, beta, c, ldc, stride_c, batch_size); } static inline void tbmv(cl::sycl::queue &queue, uplo upper_lower, transpose trans, diag unit_diag, std::int64_t n, std::int64_t k, cl::sycl::buffer &a, std::int64_t lda, cl::sycl::buffer &x, std::int64_t incx) { tbmv_precondition(queue, upper_lower, trans, unit_diag, n, k, a, lda, x, incx); detail::tbmv(get_device_id(queue), queue, upper_lower, trans, unit_diag, n, k, a, lda, x, incx); tbmv_postcondition(queue, upper_lower, trans, unit_diag, n, k, a, lda, x, incx); } static inline void tbmv(cl::sycl::queue &queue, uplo upper_lower, transpose trans, diag unit_diag, std::int64_t n, std::int64_t k, cl::sycl::buffer &a, std::int64_t lda, cl::sycl::buffer &x, std::int64_t incx) { tbmv_precondition(queue, upper_lower, trans, unit_diag, n, k, a, lda, x, incx); detail::tbmv(get_device_id(queue), queue, upper_lower, trans, unit_diag, n, k, a, lda, x, incx); tbmv_postcondition(queue, upper_lower, trans, unit_diag, n, k, a, lda, x, incx); } static inline void tbmv(cl::sycl::queue &queue, uplo upper_lower, transpose trans, diag unit_diag, std::int64_t n, std::int64_t k, cl::sycl::buffer, 1> &a, std::int64_t lda, cl::sycl::buffer, 1> &x, std::int64_t incx) { tbmv_precondition(queue, upper_lower, trans, unit_diag, n, k, a, lda, x, incx); detail::tbmv(get_device_id(queue), queue, upper_lower, trans, unit_diag, n, k, a, lda, x, incx); tbmv_postcondition(queue, upper_lower, trans, unit_diag, n, k, a, lda, x, incx); } static inline void tbmv(cl::sycl::queue &queue, uplo upper_lower, transpose trans, diag unit_diag, std::int64_t n, std::int64_t k, cl::sycl::buffer, 1> &a, std::int64_t lda, cl::sycl::buffer, 1> &x, std::int64_t incx) { tbmv_precondition(queue, upper_lower, trans, unit_diag, n, k, a, lda, x, incx); detail::tbmv(get_device_id(queue), queue, upper_lower, trans, unit_diag, n, k, a, lda, x, incx); tbmv_postcondition(queue, upper_lower, trans, unit_diag, n, k, a, lda, x, incx); } static inline void tbsv(cl::sycl::queue &queue, uplo upper_lower, transpose trans, diag unit_diag, std::int64_t n, std::int64_t k, cl::sycl::buffer &a, std::int64_t lda, cl::sycl::buffer &x, std::int64_t incx) { tbsv_precondition(queue, upper_lower, trans, unit_diag, n, k, a, lda, x, incx); detail::tbsv(get_device_id(queue), queue, upper_lower, trans, unit_diag, n, k, a, lda, x, incx); tbsv_postcondition(queue, upper_lower, trans, unit_diag, n, k, a, lda, x, incx); } static inline void tbsv(cl::sycl::queue &queue, uplo upper_lower, transpose trans, diag unit_diag, std::int64_t n, std::int64_t k, cl::sycl::buffer &a, std::int64_t lda, cl::sycl::buffer &x, std::int64_t incx) { tbsv_precondition(queue, upper_lower, trans, unit_diag, n, k, a, lda, x, incx); detail::tbsv(get_device_id(queue), queue, upper_lower, trans, unit_diag, n, k, a, lda, x, incx); tbsv_postcondition(queue, upper_lower, trans, unit_diag, n, k, a, lda, x, incx); } static inline void tbsv(cl::sycl::queue &queue, uplo upper_lower, transpose trans, diag unit_diag, std::int64_t n, std::int64_t k, cl::sycl::buffer, 1> &a, std::int64_t lda, cl::sycl::buffer, 1> &x, std::int64_t incx) { tbsv_precondition(queue, upper_lower, trans, unit_diag, n, k, a, lda, x, incx); detail::tbsv(get_device_id(queue), queue, upper_lower, trans, unit_diag, n, k, a, lda, x, incx); tbsv_postcondition(queue, upper_lower, trans, unit_diag, n, k, a, lda, x, incx); } static inline void tbsv(cl::sycl::queue &queue, uplo upper_lower, transpose trans, diag unit_diag, std::int64_t n, std::int64_t k, cl::sycl::buffer, 1> &a, std::int64_t lda, cl::sycl::buffer, 1> &x, std::int64_t incx) { tbsv_precondition(queue, upper_lower, trans, unit_diag, n, k, a, lda, x, incx); detail::tbsv(get_device_id(queue), queue, upper_lower, trans, unit_diag, n, k, a, lda, x, incx); tbsv_postcondition(queue, upper_lower, trans, unit_diag, n, k, a, lda, x, incx); } static inline void tpmv(cl::sycl::queue &queue, uplo upper_lower, transpose trans, diag unit_diag, std::int64_t n, cl::sycl::buffer &a, cl::sycl::buffer &x, std::int64_t incx) { tpmv_precondition(queue, upper_lower, trans, unit_diag, n, a, x, incx); detail::tpmv(get_device_id(queue), queue, upper_lower, trans, unit_diag, n, a, x, incx); tpmv_postcondition(queue, upper_lower, trans, unit_diag, n, a, x, incx); } static inline void tpmv(cl::sycl::queue &queue, uplo upper_lower, transpose trans, diag unit_diag, std::int64_t n, cl::sycl::buffer &a, cl::sycl::buffer &x, std::int64_t incx) { tpmv_precondition(queue, upper_lower, trans, unit_diag, n, a, x, incx); detail::tpmv(get_device_id(queue), queue, upper_lower, trans, unit_diag, n, a, x, incx); tpmv_postcondition(queue, upper_lower, trans, unit_diag, n, a, x, incx); } static inline void tpmv(cl::sycl::queue &queue, uplo upper_lower, transpose trans, diag unit_diag, std::int64_t n, cl::sycl::buffer, 1> &a, cl::sycl::buffer, 1> &x, std::int64_t incx) { tpmv_precondition(queue, upper_lower, trans, unit_diag, n, a, x, incx); detail::tpmv(get_device_id(queue), queue, upper_lower, trans, unit_diag, n, a, x, incx); tpmv_postcondition(queue, upper_lower, trans, unit_diag, n, a, x, incx); } static inline void tpmv(cl::sycl::queue &queue, uplo upper_lower, transpose trans, diag unit_diag, std::int64_t n, cl::sycl::buffer, 1> &a, cl::sycl::buffer, 1> &x, std::int64_t incx) { tpmv_precondition(queue, upper_lower, trans, unit_diag, n, a, x, incx); detail::tpmv(get_device_id(queue), queue, upper_lower, trans, unit_diag, n, a, x, incx); tpmv_postcondition(queue, upper_lower, trans, unit_diag, n, a, x, incx); } static inline void tpsv(cl::sycl::queue &queue, uplo upper_lower, transpose trans, diag unit_diag, std::int64_t n, cl::sycl::buffer &a, cl::sycl::buffer &x, std::int64_t incx) { tpsv_precondition(queue, upper_lower, trans, unit_diag, n, a, x, incx); detail::tpsv(get_device_id(queue), queue, upper_lower, trans, unit_diag, n, a, x, incx); tpsv_postcondition(queue, upper_lower, trans, unit_diag, n, a, x, incx); } static inline void tpsv(cl::sycl::queue &queue, uplo upper_lower, transpose trans, diag unit_diag, std::int64_t n, cl::sycl::buffer &a, cl::sycl::buffer &x, std::int64_t incx) { tpsv_precondition(queue, upper_lower, trans, unit_diag, n, a, x, incx); detail::tpsv(get_device_id(queue), queue, upper_lower, trans, unit_diag, n, a, x, incx); tpsv_postcondition(queue, upper_lower, trans, unit_diag, n, a, x, incx); } static inline void tpsv(cl::sycl::queue &queue, uplo upper_lower, transpose trans, diag unit_diag, std::int64_t n, cl::sycl::buffer, 1> &a, cl::sycl::buffer, 1> &x, std::int64_t incx) { tpsv_precondition(queue, upper_lower, trans, unit_diag, n, a, x, incx); detail::tpsv(get_device_id(queue), queue, upper_lower, trans, unit_diag, n, a, x, incx); tpsv_postcondition(queue, upper_lower, trans, unit_diag, n, a, x, incx); } static inline void tpsv(cl::sycl::queue &queue, uplo upper_lower, transpose trans, diag unit_diag, std::int64_t n, cl::sycl::buffer, 1> &a, cl::sycl::buffer, 1> &x, std::int64_t incx) { tpsv_precondition(queue, upper_lower, trans, unit_diag, n, a, x, incx); detail::tpsv(get_device_id(queue), queue, upper_lower, trans, unit_diag, n, a, x, incx); tpsv_postcondition(queue, upper_lower, trans, unit_diag, n, a, x, incx); } static inline void trmm(cl::sycl::queue &queue, side left_right, uplo upper_lower, transpose trans, diag unit_diag, std::int64_t m, std::int64_t n, float alpha, cl::sycl::buffer &a, std::int64_t lda, cl::sycl::buffer &b, std::int64_t ldb) { trmm_precondition(queue, left_right, upper_lower, trans, unit_diag, m, n, alpha, a, lda, b, ldb); detail::trmm(get_device_id(queue), queue, left_right, upper_lower, trans, unit_diag, m, n, alpha, a, lda, b, ldb); trmm_postcondition(queue, left_right, upper_lower, trans, unit_diag, m, n, alpha, a, lda, b, ldb); } static inline void trmm(cl::sycl::queue &queue, side left_right, uplo upper_lower, transpose trans, diag unit_diag, std::int64_t m, std::int64_t n, double alpha, cl::sycl::buffer &a, std::int64_t lda, cl::sycl::buffer &b, std::int64_t ldb) { trmm_precondition(queue, left_right, upper_lower, trans, unit_diag, m, n, alpha, a, lda, b, ldb); detail::trmm(get_device_id(queue), queue, left_right, upper_lower, trans, unit_diag, m, n, alpha, a, lda, b, ldb); trmm_postcondition(queue, left_right, upper_lower, trans, unit_diag, m, n, alpha, a, lda, b, ldb); } static inline void trmm(cl::sycl::queue &queue, side left_right, uplo upper_lower, transpose trans, diag unit_diag, std::int64_t m, std::int64_t n, std::complex alpha, cl::sycl::buffer, 1> &a, std::int64_t lda, cl::sycl::buffer, 1> &b, std::int64_t ldb) { trmm_precondition(queue, left_right, upper_lower, trans, unit_diag, m, n, alpha, a, lda, b, ldb); detail::trmm(get_device_id(queue), queue, left_right, upper_lower, trans, unit_diag, m, n, alpha, a, lda, b, ldb); trmm_postcondition(queue, left_right, upper_lower, trans, unit_diag, m, n, alpha, a, lda, b, ldb); } static inline void trmm(cl::sycl::queue &queue, side left_right, uplo upper_lower, transpose trans, diag unit_diag, std::int64_t m, std::int64_t n, std::complex alpha, cl::sycl::buffer, 1> &a, std::int64_t lda, cl::sycl::buffer, 1> &b, std::int64_t ldb) { trmm_precondition(queue, left_right, upper_lower, trans, unit_diag, m, n, alpha, a, lda, b, ldb); detail::trmm(get_device_id(queue), queue, left_right, upper_lower, trans, unit_diag, m, n, alpha, a, lda, b, ldb); trmm_postcondition(queue, left_right, upper_lower, trans, unit_diag, m, n, alpha, a, lda, b, ldb); } static inline void trmv(cl::sycl::queue &queue, uplo upper_lower, transpose trans, diag unit_diag, std::int64_t n, cl::sycl::buffer &a, std::int64_t lda, cl::sycl::buffer &x, std::int64_t incx) { trmv_precondition(queue, upper_lower, trans, unit_diag, n, a, lda, x, incx); detail::trmv(get_device_id(queue), queue, upper_lower, trans, unit_diag, n, a, lda, x, incx); trmv_postcondition(queue, upper_lower, trans, unit_diag, n, a, lda, x, incx); } static inline void trmv(cl::sycl::queue &queue, uplo upper_lower, transpose trans, diag unit_diag, std::int64_t n, cl::sycl::buffer &a, std::int64_t lda, cl::sycl::buffer &x, std::int64_t incx) { trmv_precondition(queue, upper_lower, trans, unit_diag, n, a, lda, x, incx); detail::trmv(get_device_id(queue), queue, upper_lower, trans, unit_diag, n, a, lda, x, incx); trmv_postcondition(queue, upper_lower, trans, unit_diag, n, a, lda, x, incx); } static inline void trmv(cl::sycl::queue &queue, uplo upper_lower, transpose trans, diag unit_diag, std::int64_t n, cl::sycl::buffer, 1> &a, std::int64_t lda, cl::sycl::buffer, 1> &x, std::int64_t incx) { trmv_precondition(queue, upper_lower, trans, unit_diag, n, a, lda, x, incx); detail::trmv(get_device_id(queue), queue, upper_lower, trans, unit_diag, n, a, lda, x, incx); trmv_postcondition(queue, upper_lower, trans, unit_diag, n, a, lda, x, incx); } static inline void trmv(cl::sycl::queue &queue, uplo upper_lower, transpose trans, diag unit_diag, std::int64_t n, cl::sycl::buffer, 1> &a, std::int64_t lda, cl::sycl::buffer, 1> &x, std::int64_t incx) { trmv_precondition(queue, upper_lower, trans, unit_diag, n, a, lda, x, incx); detail::trmv(get_device_id(queue), queue, upper_lower, trans, unit_diag, n, a, lda, x, incx); trmv_postcondition(queue, upper_lower, trans, unit_diag, n, a, lda, x, incx); } static inline void trsm(cl::sycl::queue &queue, side left_right, uplo upper_lower, transpose trans, diag unit_diag, std::int64_t m, std::int64_t n, float alpha, cl::sycl::buffer &a, std::int64_t lda, cl::sycl::buffer &b, std::int64_t ldb) { trsm_precondition(queue, left_right, upper_lower, trans, unit_diag, m, n, alpha, a, lda, b, ldb); detail::trsm(get_device_id(queue), queue, left_right, upper_lower, trans, unit_diag, m, n, alpha, a, lda, b, ldb); trsm_postcondition(queue, left_right, upper_lower, trans, unit_diag, m, n, alpha, a, lda, b, ldb); } static inline void trsm(cl::sycl::queue &queue, side left_right, uplo upper_lower, transpose trans, diag unit_diag, std::int64_t m, std::int64_t n, double alpha, cl::sycl::buffer &a, std::int64_t lda, cl::sycl::buffer &b, std::int64_t ldb) { trsm_precondition(queue, left_right, upper_lower, trans, unit_diag, m, n, alpha, a, lda, b, ldb); detail::trsm(get_device_id(queue), queue, left_right, upper_lower, trans, unit_diag, m, n, alpha, a, lda, b, ldb); trsm_postcondition(queue, left_right, upper_lower, trans, unit_diag, m, n, alpha, a, lda, b, ldb); } static inline void trsm(cl::sycl::queue &queue, side left_right, uplo upper_lower, transpose trans, diag unit_diag, std::int64_t m, std::int64_t n, std::complex alpha, cl::sycl::buffer, 1> &a, std::int64_t lda, cl::sycl::buffer, 1> &b, std::int64_t ldb) { trsm_precondition(queue, left_right, upper_lower, trans, unit_diag, m, n, alpha, a, lda, b, ldb); detail::trsm(get_device_id(queue), queue, left_right, upper_lower, trans, unit_diag, m, n, alpha, a, lda, b, ldb); trsm_postcondition(queue, left_right, upper_lower, trans, unit_diag, m, n, alpha, a, lda, b, ldb); } static inline void trsm(cl::sycl::queue &queue, side left_right, uplo upper_lower, transpose trans, diag unit_diag, std::int64_t m, std::int64_t n, std::complex alpha, cl::sycl::buffer, 1> &a, std::int64_t lda, cl::sycl::buffer, 1> &b, std::int64_t ldb) { trsm_precondition(queue, left_right, upper_lower, trans, unit_diag, m, n, alpha, a, lda, b, ldb); detail::trsm(get_device_id(queue), queue, left_right, upper_lower, trans, unit_diag, m, n, alpha, a, lda, b, ldb); trsm_postcondition(queue, left_right, upper_lower, trans, unit_diag, m, n, alpha, a, lda, b, ldb); } static inline void trsm_batch(cl::sycl::queue &queue, side left_right, uplo upper_lower, transpose trans, diag unit_diag, std::int64_t m, std::int64_t n, float alpha, cl::sycl::buffer &a, std::int64_t lda, std::int64_t stride_a, cl::sycl::buffer &b, std::int64_t ldb, std::int64_t stride_b, std::int64_t batch_size) { trsm_batch_precondition(queue, left_right, upper_lower, trans, unit_diag, m, n, alpha, a, lda, stride_a, b, ldb, stride_b, batch_size); detail::trsm_batch(get_device_id(queue), queue, left_right, upper_lower, trans, unit_diag, m, n, alpha, a, lda, stride_a, b, ldb, stride_b, batch_size); trsm_batch_postcondition(queue, left_right, upper_lower, trans, unit_diag, m, n, alpha, a, lda, stride_a, b, ldb, stride_b, batch_size); } static inline void trsm_batch(cl::sycl::queue &queue, side left_right, uplo upper_lower, transpose trans, diag unit_diag, std::int64_t m, std::int64_t n, double alpha, cl::sycl::buffer &a, std::int64_t lda, std::int64_t stride_a, cl::sycl::buffer &b, std::int64_t ldb, std::int64_t stride_b, std::int64_t batch_size) { trsm_batch_precondition(queue, left_right, upper_lower, trans, unit_diag, m, n, alpha, a, lda, stride_a, b, ldb, stride_b, batch_size); detail::trsm_batch(get_device_id(queue), queue, left_right, upper_lower, trans, unit_diag, m, n, alpha, a, lda, stride_a, b, ldb, stride_b, batch_size); trsm_batch_postcondition(queue, left_right, upper_lower, trans, unit_diag, m, n, alpha, a, lda, stride_a, b, ldb, stride_b, batch_size); } static inline void trsm_batch(cl::sycl::queue &queue, side left_right, uplo upper_lower, transpose trans, diag unit_diag, std::int64_t m, std::int64_t n, std::complex alpha, cl::sycl::buffer, 1> &a, std::int64_t lda, std::int64_t stride_a, cl::sycl::buffer, 1> &b, std::int64_t ldb, std::int64_t stride_b, std::int64_t batch_size) { trsm_batch_precondition(queue, left_right, upper_lower, trans, unit_diag, m, n, alpha, a, lda, stride_a, b, ldb, stride_b, batch_size); detail::trsm_batch(get_device_id(queue), queue, left_right, upper_lower, trans, unit_diag, m, n, alpha, a, lda, stride_a, b, ldb, stride_b, batch_size); trsm_batch_postcondition(queue, left_right, upper_lower, trans, unit_diag, m, n, alpha, a, lda, stride_a, b, ldb, stride_b, batch_size); } static inline void trsm_batch(cl::sycl::queue &queue, side left_right, uplo upper_lower, transpose trans, diag unit_diag, std::int64_t m, std::int64_t n, std::complex alpha, cl::sycl::buffer, 1> &a, std::int64_t lda, std::int64_t stride_a, cl::sycl::buffer, 1> &b, std::int64_t ldb, std::int64_t stride_b, std::int64_t batch_size) { trsm_batch_precondition(queue, left_right, upper_lower, trans, unit_diag, m, n, alpha, a, lda, stride_a, b, ldb, stride_b, batch_size); detail::trsm_batch(get_device_id(queue), queue, left_right, upper_lower, trans, unit_diag, m, n, alpha, a, lda, stride_a, b, ldb, stride_b, batch_size); trsm_batch_postcondition(queue, left_right, upper_lower, trans, unit_diag, m, n, alpha, a, lda, stride_a, b, ldb, stride_b, batch_size); } static inline void trsv(cl::sycl::queue &queue, uplo upper_lower, transpose trans, diag unit_diag, std::int64_t n, cl::sycl::buffer &a, std::int64_t lda, cl::sycl::buffer &x, std::int64_t incx) { trsv_precondition(queue, upper_lower, trans, unit_diag, n, a, lda, x, incx); detail::trsv(get_device_id(queue), queue, upper_lower, trans, unit_diag, n, a, lda, x, incx); trsv_postcondition(queue, upper_lower, trans, unit_diag, n, a, lda, x, incx); } static inline void trsv(cl::sycl::queue &queue, uplo upper_lower, transpose trans, diag unit_diag, std::int64_t n, cl::sycl::buffer &a, std::int64_t lda, cl::sycl::buffer &x, std::int64_t incx) { trsv_precondition(queue, upper_lower, trans, unit_diag, n, a, lda, x, incx); detail::trsv(get_device_id(queue), queue, upper_lower, trans, unit_diag, n, a, lda, x, incx); trsv_postcondition(queue, upper_lower, trans, unit_diag, n, a, lda, x, incx); } static inline void trsv(cl::sycl::queue &queue, uplo upper_lower, transpose trans, diag unit_diag, std::int64_t n, cl::sycl::buffer, 1> &a, std::int64_t lda, cl::sycl::buffer, 1> &x, std::int64_t incx) { trsv_precondition(queue, upper_lower, trans, unit_diag, n, a, lda, x, incx); detail::trsv(get_device_id(queue), queue, upper_lower, trans, unit_diag, n, a, lda, x, incx); trsv_postcondition(queue, upper_lower, trans, unit_diag, n, a, lda, x, incx); } static inline void trsv(cl::sycl::queue &queue, uplo upper_lower, transpose trans, diag unit_diag, std::int64_t n, cl::sycl::buffer, 1> &a, std::int64_t lda, cl::sycl::buffer, 1> &x, std::int64_t incx) { trsv_precondition(queue, upper_lower, trans, unit_diag, n, a, lda, x, incx); detail::trsv(get_device_id(queue), queue, upper_lower, trans, unit_diag, n, a, lda, x, incx); trsv_postcondition(queue, upper_lower, trans, unit_diag, n, a, lda, x, incx); } // USM APIs static inline cl::sycl::event asum(cl::sycl::queue &queue, std::int64_t n, const std::complex *x, std::int64_t incx, float *result, const std::vector &dependencies = {}) { asum_precondition(queue, n, x, incx, result, dependencies); auto done = detail::asum(get_device_id(queue), queue, n, x, incx, result, dependencies); asum_postcondition(queue, n, x, incx, result, dependencies); return done; } static inline cl::sycl::event asum(cl::sycl::queue &queue, std::int64_t n, const std::complex *x, std::int64_t incx, double *result, const std::vector &dependencies = {}) { asum_precondition(queue, n, x, incx, result, dependencies); auto done = detail::asum(get_device_id(queue), queue, n, x, incx, result, dependencies); asum_postcondition(queue, n, x, incx, result, dependencies); return done; } static inline cl::sycl::event asum(cl::sycl::queue &queue, std::int64_t n, const float *x, std::int64_t incx, float *result, const std::vector &dependencies = {}) { asum_precondition(queue, n, x, incx, result, dependencies); auto done = detail::asum(get_device_id(queue), queue, n, x, incx, result, dependencies); asum_postcondition(queue, n, x, incx, result, dependencies); return done; } static inline cl::sycl::event asum(cl::sycl::queue &queue, std::int64_t n, const double *x, std::int64_t incx, double *result, const std::vector &dependencies = {}) { asum_precondition(queue, n, x, incx, result, dependencies); auto done = detail::asum(get_device_id(queue), queue, n, x, incx, result, dependencies); asum_postcondition(queue, n, x, incx, result, dependencies); return done; } static inline cl::sycl::event axpy(cl::sycl::queue &queue, std::int64_t n, float alpha, const float *x, std::int64_t incx, float *y, std::int64_t incy, const std::vector &dependencies = {}) { axpy_precondition(queue, n, alpha, x, incx, y, incy, dependencies); auto done = detail::axpy(get_device_id(queue), queue, n, alpha, x, incx, y, incy, dependencies); axpy_postcondition(queue, n, alpha, x, incx, y, incy, dependencies); return done; } static inline cl::sycl::event axpy(cl::sycl::queue &queue, std::int64_t n, double alpha, const double *x, std::int64_t incx, double *y, std::int64_t incy, const std::vector &dependencies = {}) { axpy_precondition(queue, n, alpha, x, incx, y, incy, dependencies); auto done = detail::axpy(get_device_id(queue), queue, n, alpha, x, incx, y, incy, dependencies); axpy_postcondition(queue, n, alpha, x, incx, y, incy, dependencies); return done; } static inline cl::sycl::event axpy(cl::sycl::queue &queue, std::int64_t n, std::complex alpha, const std::complex *x, std::int64_t incx, std::complex *y, std::int64_t incy, const std::vector &dependencies = {}) { axpy_precondition(queue, n, alpha, x, incx, y, incy, dependencies); auto done = detail::axpy(get_device_id(queue), queue, n, alpha, x, incx, y, incy, dependencies); axpy_postcondition(queue, n, alpha, x, incx, y, incy, dependencies); return done; } static inline cl::sycl::event axpy(cl::sycl::queue &queue, std::int64_t n, std::complex alpha, const std::complex *x, std::int64_t incx, std::complex *y, std::int64_t incy, const std::vector &dependencies = {}) { axpy_precondition(queue, n, alpha, x, incx, y, incy, dependencies); auto done = detail::axpy(get_device_id(queue), queue, n, alpha, x, incx, y, incy, dependencies); axpy_postcondition(queue, n, alpha, x, incx, y, incy, dependencies); return done; } static inline cl::sycl::event axpy_batch(cl::sycl::queue &queue, std::int64_t *n, double *alpha, const double **x, std::int64_t *incx, double **y, std::int64_t *incy, std::int64_t group_count, std::int64_t *group_size, const std::vector &dependencies = {}) { axpy_batch_precondition(queue, n, alpha, x, incx, y, incy, group_count, group_size, dependencies); auto done = detail::axpy_batch(get_device_id(queue), queue, n, alpha, x, incx, y, incy, group_count, group_size, dependencies); axpy_batch_postcondition(queue, n, alpha, x, incx, y, incy, group_count, group_size, dependencies); return done; } static inline cl::sycl::event axpy_batch(cl::sycl::queue &queue, std::int64_t *n, float *alpha, const float **x, std::int64_t *incx, float **y, std::int64_t *incy, std::int64_t group_count, std::int64_t *group_size, const std::vector &dependencies = {}) { axpy_batch_precondition(queue, n, alpha, x, incx, y, incy, group_count, group_size, dependencies); auto done = detail::axpy_batch(get_device_id(queue), queue, n, alpha, x, incx, y, incy, group_count, group_size, dependencies); axpy_batch_postcondition(queue, n, alpha, x, incx, y, incy, group_count, group_size, dependencies); return done; } static inline cl::sycl::event axpy_batch(cl::sycl::queue &queue, std::int64_t *n, std::complex *alpha, const std::complex **x, std::int64_t *incx, std::complex **y, std::int64_t *incy, std::int64_t group_count, std::int64_t *group_size, const std::vector &dependencies = {}) { axpy_batch_precondition(queue, n, alpha, x, incx, y, incy, group_count, group_size, dependencies); auto done = detail::axpy_batch(get_device_id(queue), queue, n, alpha, x, incx, y, incy, group_count, group_size, dependencies); axpy_batch_postcondition(queue, n, alpha, x, incx, y, incy, group_count, group_size, dependencies); return done; } static inline cl::sycl::event axpy_batch(cl::sycl::queue &queue, std::int64_t *n, std::complex *alpha, const std::complex **x, std::int64_t *incx, std::complex **y, std::int64_t *incy, std::int64_t group_count, std::int64_t *group_size, const std::vector &dependencies = {}) { axpy_batch_precondition(queue, n, alpha, x, incx, y, incy, group_count, group_size, dependencies); auto done = detail::axpy_batch(get_device_id(queue), queue, n, alpha, x, incx, y, incy, group_count, group_size, dependencies); axpy_batch_postcondition(queue, n, alpha, x, incx, y, incy, group_count, group_size, dependencies); return done; } static inline cl::sycl::event axpy_batch(cl::sycl::queue &queue, std::int64_t n, float alpha, const float *x, std::int64_t incx, std::int64_t stridex, float *y, std::int64_t incy, std::int64_t stridey, std::int64_t batch_size, const std::vector &dependencies = {}) { axpy_batch_precondition(queue, n, alpha, x, incx, stridex, y, incy, stridey, batch_size, dependencies); auto done = detail::axpy_batch(get_device_id(queue), queue, n, alpha, x, incx, stridex, y, incy, stridey, batch_size, dependencies); axpy_batch_postcondition(queue, n, alpha, x, incx, stridex, y, incy, stridey, batch_size, dependencies); return done; } static inline cl::sycl::event axpy_batch(cl::sycl::queue &queue, std::int64_t n, double alpha, const double *x, std::int64_t incx, std::int64_t stridex, double *y, std::int64_t incy, std::int64_t stridey, std::int64_t batch_size, const std::vector &dependencies = {}) { axpy_batch_precondition(queue, n, alpha, x, incx, stridex, y, incy, stridey, batch_size, dependencies); auto done = detail::axpy_batch(get_device_id(queue), queue, n, alpha, x, incx, stridex, y, incy, stridey, batch_size, dependencies); axpy_batch_postcondition(queue, n, alpha, x, incx, stridex, y, incy, stridey, batch_size, dependencies); return done; } static inline cl::sycl::event axpy_batch(cl::sycl::queue &queue, std::int64_t n, std::complex alpha, const std::complex *x, std::int64_t incx, std::int64_t stridex, std::complex *y, std::int64_t incy, std::int64_t stridey, std::int64_t batch_size, const std::vector &dependencies = {}) { axpy_batch_precondition(queue, n, alpha, x, incx, stridex, y, incy, stridey, batch_size, dependencies); auto done = detail::axpy_batch(get_device_id(queue), queue, n, alpha, x, incx, stridex, y, incy, stridey, batch_size, dependencies); axpy_batch_postcondition(queue, n, alpha, x, incx, stridex, y, incy, stridey, batch_size, dependencies); return done; } static inline cl::sycl::event axpy_batch(cl::sycl::queue &queue, std::int64_t n, std::complex alpha, const std::complex *x, std::int64_t incx, std::int64_t stridex, std::complex *y, std::int64_t incy, std::int64_t stridey, std::int64_t batch_size, const std::vector &dependencies = {}) { axpy_batch_precondition(queue, n, alpha, x, incx, stridex, y, incy, stridey, batch_size, dependencies); auto done = detail::axpy_batch(get_device_id(queue), queue, n, alpha, x, incx, stridex, y, incy, stridey, batch_size, dependencies); axpy_batch_postcondition(queue, n, alpha, x, incx, stridex, y, incy, stridey, batch_size, dependencies); return done; } static inline cl::sycl::event axpby(cl::sycl::queue &queue, std::int64_t n, float alpha, const float *x, std::int64_t incx, const float beta, float *y, std::int64_t incy, const std::vector &dependencies = {}) { axpby_precondition(queue, n, alpha, x, incx, beta, y, incy, dependencies); auto done = detail::axpby(get_device_id(queue), queue, n, alpha, x, incx, beta, y, incy, dependencies); axpby_postcondition(queue, n, alpha, x, incx, beta, y, incy, dependencies); return done; } static inline cl::sycl::event axpby(cl::sycl::queue &queue, std::int64_t n, double alpha, const double *x, std::int64_t incx, const double beta, double *y, std::int64_t incy, const std::vector &dependencies = {}) { axpby_precondition(queue, n, alpha, x, incx, beta, y, incy, dependencies); auto done = detail::axpby(get_device_id(queue), queue, n, alpha, x, incx, beta, y, incy, dependencies); axpby_postcondition(queue, n, alpha, x, incx, beta, y, incy, dependencies); return done; } static inline cl::sycl::event axpby(cl::sycl::queue &queue, std::int64_t n, std::complex alpha, const std::complex *x, std::int64_t incx, const std::complex beta, std::complex *y, std::int64_t incy, const std::vector &dependencies = {}) { axpby_precondition(queue, n, alpha, x, incx, beta, y, incy, dependencies); auto done = detail::axpby(get_device_id(queue), queue, n, alpha, x, incx, beta, y, incy, dependencies); axpby_postcondition(queue, n, alpha, x, incx, beta, y, incy, dependencies); return done; } static inline cl::sycl::event axpby(cl::sycl::queue &queue, std::int64_t n, std::complex alpha, const std::complex *x, std::int64_t incx, const std::complex beta, std::complex *y, std::int64_t incy, const std::vector &dependencies = {}) { axpby_precondition(queue, n, alpha, x, incx, beta, y, incy, dependencies); auto done = detail::axpby(get_device_id(queue), queue, n, alpha, x, incx, beta, y, incy, dependencies); axpby_postcondition(queue, n, alpha, x, incx, beta, y, incy, dependencies); return done; } static inline cl::sycl::event copy(cl::sycl::queue &queue, std::int64_t n, const float *x, std::int64_t incx, float *y, std::int64_t incy, const std::vector &dependencies = {}) { copy_precondition(queue, n, x, incx, y, incy, dependencies); auto done = detail::copy(get_device_id(queue), queue, n, x, incx, y, incy, dependencies); copy_postcondition(queue, n, x, incx, y, incy, dependencies); return done; } static inline cl::sycl::event copy(cl::sycl::queue &queue, std::int64_t n, const double *x, std::int64_t incx, double *y, std::int64_t incy, const std::vector &dependencies = {}) { copy_precondition(queue, n, x, incx, y, incy, dependencies); auto done = detail::copy(get_device_id(queue), queue, n, x, incx, y, incy, dependencies); copy_postcondition(queue, n, x, incx, y, incy, dependencies); return done; } static inline cl::sycl::event copy(cl::sycl::queue &queue, std::int64_t n, const std::complex *x, std::int64_t incx, std::complex *y, std::int64_t incy, const std::vector &dependencies = {}) { copy_precondition(queue, n, x, incx, y, incy, dependencies); auto done = detail::copy(get_device_id(queue), queue, n, x, incx, y, incy, dependencies); copy_postcondition(queue, n, x, incx, y, incy, dependencies); return done; } static inline cl::sycl::event copy(cl::sycl::queue &queue, std::int64_t n, const std::complex *x, std::int64_t incx, std::complex *y, std::int64_t incy, const std::vector &dependencies = {}) { copy_precondition(queue, n, x, incx, y, incy, dependencies); auto done = detail::copy(get_device_id(queue), queue, n, x, incx, y, incy, dependencies); copy_postcondition(queue, n, x, incx, y, incy, dependencies); return done; } static inline cl::sycl::event copy_batch(cl::sycl::queue &queue, std::int64_t *n, const float **x, std::int64_t *incx, float **y, std::int64_t *incy, std::int64_t group_count, std::int64_t *group_size, const std::vector &dependencies = {}) { copy_batch_precondition(queue, n, x, incx, y, incy, group_count, group_size, dependencies); auto done = detail::copy_batch(get_device_id(queue), queue, n, x, incx, y, incy, group_count, group_size, dependencies); copy_batch_postcondition(queue, n, x, incx, y, incy, group_count, group_size, dependencies); return done; } static inline cl::sycl::event copy_batch(cl::sycl::queue &queue, std::int64_t *n, const double **x, std::int64_t *incx, double **y, std::int64_t *incy, std::int64_t group_count, std::int64_t *group_size, const std::vector &dependencies = {}) { copy_batch_precondition(queue, n, x, incx, y, incy, group_count, group_size, dependencies); auto done = detail::copy_batch(get_device_id(queue), queue, n, x, incx, y, incy, group_count, group_size, dependencies); copy_batch_postcondition(queue, n, x, incx, y, incy, group_count, group_size, dependencies); return done; } static inline cl::sycl::event copy_batch(cl::sycl::queue &queue, std::int64_t *n, const std::complex **x, std::int64_t *incx, std::complex **y, std::int64_t *incy, std::int64_t group_count, std::int64_t *group_size, const std::vector &dependencies = {}) { copy_batch_precondition(queue, n, x, incx, y, incy, group_count, group_size, dependencies); auto done = detail::copy_batch(get_device_id(queue), queue, n, x, incx, y, incy, group_count, group_size, dependencies); copy_batch_postcondition(queue, n, x, incx, y, incy, group_count, group_size, dependencies); return done; } static inline cl::sycl::event copy_batch(cl::sycl::queue &queue, std::int64_t *n, const std::complex **x, std::int64_t *incx, std::complex **y, std::int64_t *incy, std::int64_t group_count, std::int64_t *group_size, const std::vector &dependencies = {}) { copy_batch_precondition(queue, n, x, incx, y, incy, group_count, group_size, dependencies); auto done = detail::copy_batch(get_device_id(queue), queue, n, x, incx, y, incy, group_count, group_size, dependencies); copy_batch_postcondition(queue, n, x, incx, y, incy, group_count, group_size, dependencies); return done; } static inline cl::sycl::event copy_batch(cl::sycl::queue &queue, std::int64_t n, const float *x, std::int64_t incx, std::int64_t stridex, float *y, std::int64_t incy, std::int64_t stridey, std::int64_t batch_size, const std::vector &dependencies = {}) { copy_batch_precondition(queue, n, x, incx, stridex, y, incy, stridey, batch_size, dependencies); auto done = detail::copy_batch(get_device_id(queue), queue, n, x, incx, stridex, y, incy, stridey, batch_size, dependencies); copy_batch_postcondition(queue, n, x, incx, stridex, y, incy, stridey, batch_size, dependencies); return done; } static inline cl::sycl::event copy_batch(cl::sycl::queue &queue, std::int64_t n, const double *x, std::int64_t incx, std::int64_t stridex, double *y, std::int64_t incy, std::int64_t stridey, std::int64_t batch_size, const std::vector &dependencies = {}) { copy_batch_precondition(queue, n, x, incx, stridex, y, incy, stridey, batch_size, dependencies); auto done = detail::copy_batch(get_device_id(queue), queue, n, x, incx, stridex, y, incy, stridey, batch_size, dependencies); copy_batch_postcondition(queue, n, x, incx, stridex, y, incy, stridey, batch_size, dependencies); return done; } static inline cl::sycl::event copy_batch(cl::sycl::queue &queue, std::int64_t n, const std::complex *x, std::int64_t incx, std::int64_t stridex, std::complex *y, std::int64_t incy, std::int64_t stridey, std::int64_t batch_size, const std::vector &dependencies = {}) { copy_batch_precondition(queue, n, x, incx, stridex, y, incy, stridey, batch_size, dependencies); auto done = detail::copy_batch(get_device_id(queue), queue, n, x, incx, stridex, y, incy, stridey, batch_size, dependencies); copy_batch_postcondition(queue, n, x, incx, stridex, y, incy, stridey, batch_size, dependencies); return done; } static inline cl::sycl::event copy_batch(cl::sycl::queue &queue, std::int64_t n, const std::complex *x, std::int64_t incx, std::int64_t stridex, std::complex *y, std::int64_t incy, std::int64_t stridey, std::int64_t batch_size, const std::vector &dependencies = {}) { copy_batch_precondition(queue, n, x, incx, stridex, y, incy, stridey, batch_size, dependencies); auto done = detail::copy_batch(get_device_id(queue), queue, n, x, incx, stridex, y, incy, stridey, batch_size, dependencies); copy_batch_postcondition(queue, n, x, incx, stridex, y, incy, stridey, batch_size, dependencies); return done; } static inline cl::sycl::event dot(cl::sycl::queue &queue, std::int64_t n, const float *x, std::int64_t incx, const float *y, std::int64_t incy, float *result, const std::vector &dependencies = {}) { dot_precondition(queue, n, x, incx, y, incy, result, dependencies); auto done = detail::dot(get_device_id(queue), queue, n, x, incx, y, incy, result, dependencies); dot_postcondition(queue, n, x, incx, y, incy, result, dependencies); return done; } static inline cl::sycl::event dot(cl::sycl::queue &queue, std::int64_t n, const double *x, std::int64_t incx, const double *y, std::int64_t incy, double *result, const std::vector &dependencies = {}) { dot_precondition(queue, n, x, incx, y, incy, result, dependencies); auto done = detail::dot(get_device_id(queue), queue, n, x, incx, y, incy, result, dependencies); dot_postcondition(queue, n, x, incx, y, incy, result, dependencies); return done; } static inline cl::sycl::event dot(cl::sycl::queue &queue, std::int64_t n, const float *x, std::int64_t incx, const float *y, std::int64_t incy, double *result, const std::vector &dependencies = {}) { dot_precondition(queue, n, x, incx, y, incy, result, dependencies); auto done = detail::dot(get_device_id(queue), queue, n, x, incx, y, incy, result, dependencies); dot_postcondition(queue, n, x, incx, y, incy, result, dependencies); return done; } static inline cl::sycl::event dotc(cl::sycl::queue &queue, std::int64_t n, const std::complex *x, std::int64_t incx, const std::complex *y, std::int64_t incy, std::complex *result, const std::vector &dependencies = {}) { dotc_precondition(queue, n, x, incx, y, incy, result, dependencies); auto done = detail::dotc(get_device_id(queue), queue, n, x, incx, y, incy, result, dependencies); dotc_postcondition(queue, n, x, incx, y, incy, result, dependencies); return done; } static inline cl::sycl::event dotc(cl::sycl::queue &queue, std::int64_t n, const std::complex *x, std::int64_t incx, const std::complex *y, std::int64_t incy, std::complex *result, const std::vector &dependencies = {}) { dotc_precondition(queue, n, x, incx, y, incy, result, dependencies); auto done = detail::dotc(get_device_id(queue), queue, n, x, incx, y, incy, result, dependencies); dotc_postcondition(queue, n, x, incx, y, incy, result, dependencies); return done; } static inline cl::sycl::event dotu(cl::sycl::queue &queue, std::int64_t n, const std::complex *x, std::int64_t incx, const std::complex *y, std::int64_t incy, std::complex *result, const std::vector &dependencies = {}) { dotu_precondition(queue, n, x, incx, y, incy, result, dependencies); auto done = detail::dotu(get_device_id(queue), queue, n, x, incx, y, incy, result, dependencies); dotu_postcondition(queue, n, x, incx, y, incy, result, dependencies); return done; } static inline cl::sycl::event dotu(cl::sycl::queue &queue, std::int64_t n, const std::complex *x, std::int64_t incx, const std::complex *y, std::int64_t incy, std::complex *result, const std::vector &dependencies = {}) { dotu_precondition(queue, n, x, incx, y, incy, result, dependencies); auto done = detail::dotu(get_device_id(queue), queue, n, x, incx, y, incy, result, dependencies); dotu_postcondition(queue, n, x, incx, y, incy, result, dependencies); return done; } static inline cl::sycl::event gbmv(cl::sycl::queue &queue, transpose trans, std::int64_t m, std::int64_t n, std::int64_t kl, std::int64_t ku, float alpha, const float *a, std::int64_t lda, const float *x, std::int64_t incx, float beta, float *y, std::int64_t incy, const std::vector &dependencies = {}) { gbmv_precondition(queue, trans, m, n, kl, ku, alpha, a, lda, x, incx, beta, y, incy, dependencies); auto done = detail::gbmv(get_device_id(queue), queue, trans, m, n, kl, ku, alpha, a, lda, x, incx, beta, y, incy, dependencies); gbmv_postcondition(queue, trans, m, n, kl, ku, alpha, a, lda, x, incx, beta, y, incy, dependencies); return done; } static inline cl::sycl::event gbmv(cl::sycl::queue &queue, transpose trans, std::int64_t m, std::int64_t n, std::int64_t kl, std::int64_t ku, double alpha, const double *a, std::int64_t lda, const double *x, std::int64_t incx, double beta, double *y, std::int64_t incy, const std::vector &dependencies = {}) { gbmv_precondition(queue, trans, m, n, kl, ku, alpha, a, lda, x, incx, beta, y, incy, dependencies); auto done = detail::gbmv(get_device_id(queue), queue, trans, m, n, kl, ku, alpha, a, lda, x, incx, beta, y, incy, dependencies); gbmv_postcondition(queue, trans, m, n, kl, ku, alpha, a, lda, x, incx, beta, y, incy, dependencies); return done; } static inline cl::sycl::event gbmv(cl::sycl::queue &queue, transpose trans, std::int64_t m, std::int64_t n, std::int64_t kl, std::int64_t ku, std::complex alpha, const std::complex *a, std::int64_t lda, const std::complex *x, std::int64_t incx, std::complex beta, std::complex *y, std::int64_t incy, const std::vector &dependencies = {}) { gbmv_precondition(queue, trans, m, n, kl, ku, alpha, a, lda, x, incx, beta, y, incy, dependencies); auto done = detail::gbmv(get_device_id(queue), queue, trans, m, n, kl, ku, alpha, a, lda, x, incx, beta, y, incy, dependencies); gbmv_postcondition(queue, trans, m, n, kl, ku, alpha, a, lda, x, incx, beta, y, incy, dependencies); return done; } static inline cl::sycl::event gbmv(cl::sycl::queue &queue, transpose trans, std::int64_t m, std::int64_t n, std::int64_t kl, std::int64_t ku, std::complex alpha, const std::complex *a, std::int64_t lda, const std::complex *x, std::int64_t incx, std::complex beta, std::complex *y, std::int64_t incy, const std::vector &dependencies = {}) { gbmv_precondition(queue, trans, m, n, kl, ku, alpha, a, lda, x, incx, beta, y, incy, dependencies); auto done = detail::gbmv(get_device_id(queue), queue, trans, m, n, kl, ku, alpha, a, lda, x, incx, beta, y, incy, dependencies); gbmv_postcondition(queue, trans, m, n, kl, ku, alpha, a, lda, x, incx, beta, y, incy, dependencies); return done; } static inline cl::sycl::event gemm(cl::sycl::queue &queue, transpose transa, transpose transb, std::int64_t m, std::int64_t n, std::int64_t k, float alpha, const float *a, std::int64_t lda, const float *b, std::int64_t ldb, float beta, float *c, std::int64_t ldc, const std::vector &dependencies = {}) { gemm_precondition(queue, transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc, dependencies); auto done = detail::gemm(get_device_id(queue), queue, transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc, dependencies); gemm_postcondition(queue, transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc, dependencies); return done; } static inline cl::sycl::event gemm(cl::sycl::queue &queue, transpose transa, transpose transb, std::int64_t m, std::int64_t n, std::int64_t k, double alpha, const double *a, std::int64_t lda, const double *b, std::int64_t ldb, double beta, double *c, std::int64_t ldc, const std::vector &dependencies = {}) { gemm_precondition(queue, transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc, dependencies); auto done = detail::gemm(get_device_id(queue), queue, transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc, dependencies); gemm_postcondition(queue, transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc, dependencies); return done; } static inline cl::sycl::event gemm(cl::sycl::queue &queue, transpose transa, transpose transb, std::int64_t m, std::int64_t n, std::int64_t k, std::complex alpha, const std::complex *a, std::int64_t lda, const std::complex *b, std::int64_t ldb, std::complex beta, std::complex *c, std::int64_t ldc, const std::vector &dependencies = {}) { gemm_precondition(queue, transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc, dependencies); auto done = detail::gemm(get_device_id(queue), queue, transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc, dependencies); gemm_postcondition(queue, transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc, dependencies); return done; } static inline cl::sycl::event gemm(cl::sycl::queue &queue, transpose transa, transpose transb, std::int64_t m, std::int64_t n, std::int64_t k, std::complex alpha, const std::complex *a, std::int64_t lda, const std::complex *b, std::int64_t ldb, std::complex beta, std::complex *c, std::int64_t ldc, const std::vector &dependencies = {}) { gemm_precondition(queue, transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc, dependencies); auto done = detail::gemm(get_device_id(queue), queue, transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc, dependencies); gemm_postcondition(queue, transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc, dependencies); return done; } static inline cl::sycl::event gemm(cl::sycl::queue &queue, transpose transa, transpose transb, std::int64_t m, std::int64_t n, std::int64_t k, sycl::half alpha, const sycl::half *a, std::int64_t lda, const sycl::half *b, std::int64_t ldb, sycl::half beta, sycl::half *c, std::int64_t ldc, const std::vector &dependencies = {}) { gemm_precondition(queue, transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc, dependencies); auto done = detail::gemm(get_device_id(queue), queue, transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc, dependencies); gemm_postcondition(queue, transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc, dependencies); return done; } static inline cl::sycl::event gemm(cl::sycl::queue &queue, transpose transa, transpose transb, std::int64_t m, std::int64_t n, std::int64_t k, float alpha, const sycl::half *a, std::int64_t lda, const sycl::half *b, std::int64_t ldb, float beta, float *c, std::int64_t ldc, const std::vector &dependencies = {}) { gemm_precondition(queue, transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc, dependencies); auto done = detail::gemm(get_device_id(queue), queue, transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc, dependencies); gemm_postcondition(queue, transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc, dependencies); return done; } static inline cl::sycl::event gemm(cl::sycl::queue &queue, transpose transa, transpose transb, std::int64_t m, std::int64_t n, std::int64_t k, float alpha, const bfloat16 *a, std::int64_t lda, const bfloat16 *b, std::int64_t ldb, float beta, float *c, std::int64_t ldc, const std::vector &dependencies = {}) { gemm_precondition(queue, transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc, dependencies); auto done = detail::gemm(get_device_id(queue), queue, transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc, dependencies); gemm_postcondition(queue, transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc, dependencies); return done; } static inline cl::sycl::event gemm_batch(cl::sycl::queue &queue, transpose *transa, transpose *transb, std::int64_t *m, std::int64_t *n, std::int64_t *k, float *alpha, const float **a, std::int64_t *lda, const float **b, std::int64_t *ldb, float *beta, float **c, std::int64_t *ldc, std::int64_t group_count, std::int64_t *group_size, const std::vector &dependencies = {}) { gemm_batch_precondition(queue, transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc, group_count, group_size, dependencies); auto done = detail::gemm_batch(get_device_id(queue), queue, transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc, group_count, group_size, dependencies); gemm_batch_postcondition(queue, transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc, group_count, group_size, dependencies); return done; } static inline cl::sycl::event gemm_batch(cl::sycl::queue &queue, transpose *transa, transpose *transb, std::int64_t *m, std::int64_t *n, std::int64_t *k, double *alpha, const double **a, std::int64_t *lda, const double **b, std::int64_t *ldb, double *beta, double **c, std::int64_t *ldc, std::int64_t group_count, std::int64_t *group_size, const std::vector &dependencies = {}) { gemm_batch_precondition(queue, transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc, group_count, group_size, dependencies); auto done = detail::gemm_batch(get_device_id(queue), queue, transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc, group_count, group_size, dependencies); gemm_batch_postcondition(queue, transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc, group_count, group_size, dependencies); return done; } static inline cl::sycl::event gemm_batch( cl::sycl::queue &queue, transpose *transa, transpose *transb, std::int64_t *m, std::int64_t *n, std::int64_t *k, std::complex *alpha, const std::complex **a, std::int64_t *lda, const std::complex **b, std::int64_t *ldb, std::complex *beta, std::complex **c, std::int64_t *ldc, std::int64_t group_count, std::int64_t *group_size, const std::vector &dependencies = {}) { gemm_batch_precondition(queue, transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc, group_count, group_size, dependencies); auto done = detail::gemm_batch(get_device_id(queue), queue, transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc, group_count, group_size, dependencies); gemm_batch_postcondition(queue, transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc, group_count, group_size, dependencies); return done; } static inline cl::sycl::event gemm_batch( cl::sycl::queue &queue, transpose *transa, transpose *transb, std::int64_t *m, std::int64_t *n, std::int64_t *k, std::complex *alpha, const std::complex **a, std::int64_t *lda, const std::complex **b, std::int64_t *ldb, std::complex *beta, std::complex **c, std::int64_t *ldc, std::int64_t group_count, std::int64_t *group_size, const std::vector &dependencies = {}) { gemm_batch_precondition(queue, transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc, group_count, group_size, dependencies); auto done = detail::gemm_batch(get_device_id(queue), queue, transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc, group_count, group_size, dependencies); gemm_batch_postcondition(queue, transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc, group_count, group_size, dependencies); return done; } static inline cl::sycl::event gemm_batch(cl::sycl::queue &queue, transpose *transa, transpose *transb, std::int64_t *m, std::int64_t *n, std::int64_t *k, sycl::half *alpha, const sycl::half **a, std::int64_t *lda, const sycl::half **b, std::int64_t *ldb, sycl::half *beta, sycl::half **c, std::int64_t *ldc, std::int64_t group_count, std::int64_t *group_size, const std::vector &dependencies = {}) { gemm_batch_precondition(queue, transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc, group_count, group_size, dependencies); auto done = detail::gemm_batch(get_device_id(queue), queue, transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc, group_count, group_size, dependencies); gemm_batch_postcondition(queue, transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc, group_count, group_size, dependencies); return done; } static inline cl::sycl::event gemm_batch(cl::sycl::queue &queue, transpose transa, transpose transb, std::int64_t m, std::int64_t n, std::int64_t k, float alpha, const float *a, std::int64_t lda, std::int64_t stride_a, const float *b, std::int64_t ldb, std::int64_t stride_b, float beta, float *c, std::int64_t ldc, std::int64_t stride_c, std::int64_t batch_size, const std::vector &dependencies = {}) { gemm_batch_precondition(queue, transa, transb, m, n, k, alpha, a, lda, stride_a, b, ldb, stride_b, beta, c, ldc, stride_c, batch_size, dependencies); auto done = detail::gemm_batch(get_device_id(queue), queue, transa, transb, m, n, k, alpha, a, lda, stride_a, b, ldb, stride_b, beta, c, ldc, stride_c, batch_size, dependencies); gemm_batch_postcondition(queue, transa, transb, m, n, k, alpha, a, lda, stride_a, b, ldb, stride_b, beta, c, ldc, stride_c, batch_size, dependencies); return done; } static inline cl::sycl::event gemm_batch(cl::sycl::queue &queue, transpose transa, transpose transb, std::int64_t m, std::int64_t n, std::int64_t k, double alpha, const double *a, std::int64_t lda, std::int64_t stride_a, const double *b, std::int64_t ldb, std::int64_t stride_b, double beta, double *c, std::int64_t ldc, std::int64_t stride_c, std::int64_t batch_size, const std::vector &dependencies = {}) { gemm_batch_precondition(queue, transa, transb, m, n, k, alpha, a, lda, stride_a, b, ldb, stride_b, beta, c, ldc, stride_c, batch_size, dependencies); auto done = detail::gemm_batch(get_device_id(queue), queue, transa, transb, m, n, k, alpha, a, lda, stride_a, b, ldb, stride_b, beta, c, ldc, stride_c, batch_size, dependencies); gemm_batch_postcondition(queue, transa, transb, m, n, k, alpha, a, lda, stride_a, b, ldb, stride_b, beta, c, ldc, stride_c, batch_size, dependencies); return done; } static inline cl::sycl::event gemm_batch( cl::sycl::queue &queue, transpose transa, transpose transb, std::int64_t m, std::int64_t n, std::int64_t k, std::complex alpha, const std::complex *a, std::int64_t lda, std::int64_t stride_a, const std::complex *b, std::int64_t ldb, std::int64_t stride_b, std::complex beta, std::complex *c, std::int64_t ldc, std::int64_t stride_c, std::int64_t batch_size, const std::vector &dependencies = {}) { gemm_batch_precondition(queue, transa, transb, m, n, k, alpha, a, lda, stride_a, b, ldb, stride_b, beta, c, ldc, stride_c, batch_size, dependencies); auto done = detail::gemm_batch(get_device_id(queue), queue, transa, transb, m, n, k, alpha, a, lda, stride_a, b, ldb, stride_b, beta, c, ldc, stride_c, batch_size, dependencies); gemm_batch_postcondition(queue, transa, transb, m, n, k, alpha, a, lda, stride_a, b, ldb, stride_b, beta, c, ldc, stride_c, batch_size, dependencies); return done; } static inline cl::sycl::event gemm_batch( cl::sycl::queue &queue, transpose transa, transpose transb, std::int64_t m, std::int64_t n, std::int64_t k, std::complex alpha, const std::complex *a, std::int64_t lda, std::int64_t stride_a, const std::complex *b, std::int64_t ldb, std::int64_t stride_b, std::complex beta, std::complex *c, std::int64_t ldc, std::int64_t stride_c, std::int64_t batch_size, const std::vector &dependencies = {}) { gemm_batch_precondition(queue, transa, transb, m, n, k, alpha, a, lda, stride_a, b, ldb, stride_b, beta, c, ldc, stride_c, batch_size, dependencies); auto done = detail::gemm_batch(get_device_id(queue), queue, transa, transb, m, n, k, alpha, a, lda, stride_a, b, ldb, stride_b, beta, c, ldc, stride_c, batch_size, dependencies); gemm_batch_postcondition(queue, transa, transb, m, n, k, alpha, a, lda, stride_a, b, ldb, stride_b, beta, c, ldc, stride_c, batch_size, dependencies); return done; } static inline cl::sycl::event gemm_batch(cl::sycl::queue &queue, transpose transa, transpose transb, std::int64_t m, std::int64_t n, std::int64_t k, sycl::half alpha, const sycl::half *a, std::int64_t lda, std::int64_t stride_a, const sycl::half *b, std::int64_t ldb, std::int64_t stride_b, sycl::half beta, sycl::half *c, std::int64_t ldc, std::int64_t stride_c, std::int64_t batch_size, const std::vector &dependencies = {}) { gemm_batch_precondition(queue, transa, transb, m, n, k, alpha, a, lda, stride_a, b, ldb, stride_b, beta, c, ldc, stride_c, batch_size, dependencies); auto done = detail::gemm_batch(get_device_id(queue), queue, transa, transb, m, n, k, alpha, a, lda, stride_a, b, ldb, stride_b, beta, c, ldc, stride_c, batch_size, dependencies); gemm_batch_postcondition(queue, transa, transb, m, n, k, alpha, a, lda, stride_a, b, ldb, stride_b, beta, c, ldc, stride_c, batch_size, dependencies); return done; } static inline cl::sycl::event gemmt(cl::sycl::queue &queue, uplo upper_lower, transpose transa, transpose transb, std::int64_t n, std::int64_t k, float alpha, const float *a, std::int64_t lda, const float *b, std::int64_t ldb, float beta, float *c, std::int64_t ldc, const std::vector &dependencies = {}) { gemmt_precondition(queue, upper_lower, transa, transb, n, k, alpha, a, lda, b, ldb, beta, c, ldc, dependencies); auto done = detail::gemmt(get_device_id(queue), queue, upper_lower, transa, transb, n, k, alpha, a, lda, b, ldb, beta, c, ldc, dependencies); gemmt_postcondition(queue, upper_lower, transa, transb, n, k, alpha, a, lda, b, ldb, beta, c, ldc, dependencies); return done; } static inline cl::sycl::event gemmt(cl::sycl::queue &queue, uplo upper_lower, transpose transa, transpose transb, std::int64_t n, std::int64_t k, double alpha, const double *a, std::int64_t lda, const double *b, std::int64_t ldb, double beta, double *c, std::int64_t ldc, const std::vector &dependencies = {}) { gemmt_precondition(queue, upper_lower, transa, transb, n, k, alpha, a, lda, b, ldb, beta, c, ldc, dependencies); auto done = detail::gemmt(get_device_id(queue), queue, upper_lower, transa, transb, n, k, alpha, a, lda, b, ldb, beta, c, ldc, dependencies); gemmt_postcondition(queue, upper_lower, transa, transb, n, k, alpha, a, lda, b, ldb, beta, c, ldc, dependencies); return done; } static inline cl::sycl::event gemmt(cl::sycl::queue &queue, uplo upper_lower, transpose transa, transpose transb, std::int64_t n, std::int64_t k, std::complex alpha, const std::complex *a, std::int64_t lda, const std::complex *b, std::int64_t ldb, std::complex beta, std::complex *c, std::int64_t ldc, const std::vector &dependencies = {}) { gemmt_precondition(queue, upper_lower, transa, transb, n, k, alpha, a, lda, b, ldb, beta, c, ldc, dependencies); auto done = detail::gemmt(get_device_id(queue), queue, upper_lower, transa, transb, n, k, alpha, a, lda, b, ldb, beta, c, ldc, dependencies); gemmt_postcondition(queue, upper_lower, transa, transb, n, k, alpha, a, lda, b, ldb, beta, c, ldc, dependencies); return done; } static inline cl::sycl::event gemmt(cl::sycl::queue &queue, uplo upper_lower, transpose transa, transpose transb, std::int64_t n, std::int64_t k, std::complex alpha, const std::complex *a, std::int64_t lda, const std::complex *b, std::int64_t ldb, std::complex beta, std::complex *c, std::int64_t ldc, const std::vector &dependencies = {}) { gemmt_precondition(queue, upper_lower, transa, transb, n, k, alpha, a, lda, b, ldb, beta, c, ldc, dependencies); auto done = detail::gemmt(get_device_id(queue), queue, upper_lower, transa, transb, n, k, alpha, a, lda, b, ldb, beta, c, ldc, dependencies); gemmt_postcondition(queue, upper_lower, transa, transb, n, k, alpha, a, lda, b, ldb, beta, c, ldc, dependencies); return done; } static inline cl::sycl::event gemm_bias(cl::sycl::queue &queue, transpose transa, transpose transb, offset offsetc, std::int64_t m, std::int64_t n, std::int64_t k, float alpha, const std::int8_t *a, std::int64_t lda, std::int8_t ao, const std::uint8_t *b, std::int64_t ldb, std::uint8_t bo, float beta, std::int32_t *c, std::int64_t ldc, const std::int32_t *co, const std::vector &dependencies = {}) { gemm_bias_precondition(queue, transa, transb, offsetc, m, n, k, alpha, a, lda, ao, b, ldb, bo, beta, c, ldc, co, dependencies); auto done = detail::gemm_bias(get_device_id(queue), queue, transa, transb, offsetc, m, n, k, alpha, a, lda, ao, b, ldb, bo, beta, c, ldc, co, dependencies); gemm_bias_postcondition(queue, transa, transb, offsetc, m, n, k, alpha, a, lda, ao, b, ldb, bo, beta, c, ldc, co, dependencies); return done; } static inline cl::sycl::event gemm_bias(cl::sycl::queue &queue, transpose transa, transpose transb, offset offsetc, std::int64_t m, std::int64_t n, std::int64_t k, float alpha, const std::int8_t *a, std::int64_t lda, std::int8_t ao, const std::int8_t *b, std::int64_t ldb, std::int8_t bo, float beta, std::int32_t *c, std::int64_t ldc, const std::int32_t *co, const std::vector &dependencies = {}) { gemm_bias_precondition(queue, transa, transb, offsetc, m, n, k, alpha, a, lda, ao, b, ldb, bo, beta, c, ldc, co, dependencies); auto done = detail::gemm_bias(get_device_id(queue), queue, transa, transb, offsetc, m, n, k, alpha, a, lda, ao, b, ldb, bo, beta, c, ldc, co, dependencies); gemm_bias_postcondition(queue, transa, transb, offsetc, m, n, k, alpha, a, lda, ao, b, ldb, bo, beta, c, ldc, co, dependencies); return done; } static inline cl::sycl::event gemm_bias(cl::sycl::queue &queue, transpose transa, transpose transb, offset offsetc, std::int64_t m, std::int64_t n, std::int64_t k, float alpha, const std::uint8_t *a, std::int64_t lda, std::uint8_t ao, const std::int8_t *b, std::int64_t ldb, std::int8_t bo, float beta, std::int32_t *c, std::int64_t ldc, const std::int32_t *co, const std::vector &dependencies = {}) { gemm_bias_precondition(queue, transa, transb, offsetc, m, n, k, alpha, a, lda, ao, b, ldb, bo, beta, c, ldc, co, dependencies); auto done = detail::gemm_bias(get_device_id(queue), queue, transa, transb, offsetc, m, n, k, alpha, a, lda, ao, b, ldb, bo, beta, c, ldc, co, dependencies); gemm_bias_postcondition(queue, transa, transb, offsetc, m, n, k, alpha, a, lda, ao, b, ldb, bo, beta, c, ldc, co, dependencies); return done; } static inline cl::sycl::event gemm_bias(cl::sycl::queue &queue, transpose transa, transpose transb, offset offsetc, std::int64_t m, std::int64_t n, std::int64_t k, float alpha, const std::uint8_t *a, std::int64_t lda, std::uint8_t ao, const std::uint8_t *b, std::int64_t ldb, std::uint8_t bo, float beta, std::int32_t *c, std::int64_t ldc, const std::int32_t *co, const std::vector &dependencies = {}) { gemm_bias_precondition(queue, transa, transb, offsetc, m, n, k, alpha, a, lda, ao, b, ldb, bo, beta, c, ldc, co, dependencies); auto done = detail::gemm_bias(get_device_id(queue), queue, transa, transb, offsetc, m, n, k, alpha, a, lda, ao, b, ldb, bo, beta, c, ldc, co, dependencies); gemm_bias_postcondition(queue, transa, transb, offsetc, m, n, k, alpha, a, lda, ao, b, ldb, bo, beta, c, ldc, co, dependencies); return done; } static inline cl::sycl::event gemv(cl::sycl::queue &queue, transpose trans, std::int64_t m, std::int64_t n, float alpha, const float *a, std::int64_t lda, const float *x, std::int64_t incx, float beta, float *y, std::int64_t incy, const std::vector &dependencies = {}) { gemv_precondition(queue, trans, m, n, alpha, a, lda, x, incx, beta, y, incy, dependencies); auto done = detail::gemv(get_device_id(queue), queue, trans, m, n, alpha, a, lda, x, incx, beta, y, incy, dependencies); gemv_postcondition(queue, trans, m, n, alpha, a, lda, x, incx, beta, y, incy, dependencies); return done; } static inline cl::sycl::event gemv(cl::sycl::queue &queue, transpose trans, std::int64_t m, std::int64_t n, double alpha, const double *a, std::int64_t lda, const double *x, std::int64_t incx, double beta, double *y, std::int64_t incy, const std::vector &dependencies = {}) { gemv_precondition(queue, trans, m, n, alpha, a, lda, x, incx, beta, y, incy, dependencies); auto done = detail::gemv(get_device_id(queue), queue, trans, m, n, alpha, a, lda, x, incx, beta, y, incy, dependencies); gemv_postcondition(queue, trans, m, n, alpha, a, lda, x, incx, beta, y, incy, dependencies); return done; } static inline cl::sycl::event gemv(cl::sycl::queue &queue, transpose trans, std::int64_t m, std::int64_t n, std::complex alpha, const std::complex *a, std::int64_t lda, const std::complex *x, std::int64_t incx, std::complex beta, std::complex *y, std::int64_t incy, const std::vector &dependencies = {}) { gemv_precondition(queue, trans, m, n, alpha, a, lda, x, incx, beta, y, incy, dependencies); auto done = detail::gemv(get_device_id(queue), queue, trans, m, n, alpha, a, lda, x, incx, beta, y, incy, dependencies); gemv_postcondition(queue, trans, m, n, alpha, a, lda, x, incx, beta, y, incy, dependencies); return done; } static inline cl::sycl::event gemv(cl::sycl::queue &queue, transpose trans, std::int64_t m, std::int64_t n, std::complex alpha, const std::complex *a, std::int64_t lda, const std::complex *x, std::int64_t incx, std::complex beta, std::complex *y, std::int64_t incy, const std::vector &dependencies = {}) { gemv_precondition(queue, trans, m, n, alpha, a, lda, x, incx, beta, y, incy, dependencies); auto done = detail::gemv(get_device_id(queue), queue, trans, m, n, alpha, a, lda, x, incx, beta, y, incy, dependencies); gemv_postcondition(queue, trans, m, n, alpha, a, lda, x, incx, beta, y, incy, dependencies); return done; } static inline cl::sycl::event gemv_batch(cl::sycl::queue &queue, transpose trans, std::int64_t m, std::int64_t n, float alpha, const float *a, std::int64_t lda, std::int64_t stridea, const float *x, std::int64_t incx, std::int64_t stridex, float beta, float *y, std::int64_t incy, std::int64_t stridey, std::int64_t batch_size, const std::vector &dependencies = {}) { gemv_batch_precondition(queue, trans, m, n, alpha, a, lda, stridea, x, incx, stridex, beta, y, incy, stridey, batch_size, dependencies); auto done = detail::gemv_batch(get_device_id(queue), queue, trans, m, n, alpha, a, lda, stridea, x, incx, stridex, beta, y, incy, stridey, batch_size, dependencies); gemv_batch_postcondition(queue, trans, m, n, alpha, a, lda, stridea, x, incx, stridex, beta, y, incy, stridey, batch_size, dependencies); return done; } static inline cl::sycl::event gemv_batch(cl::sycl::queue &queue, transpose trans, std::int64_t m, std::int64_t n, double alpha, const double *a, std::int64_t lda, std::int64_t stridea, const double *x, std::int64_t incx, std::int64_t stridex, double beta, double *y, std::int64_t incy, std::int64_t stridey, std::int64_t batch_size, const std::vector &dependencies = {}) { gemv_batch_precondition(queue, trans, m, n, alpha, a, lda, stridea, x, incx, stridex, beta, y, incy, stridey, batch_size, dependencies); auto done = detail::gemv_batch(get_device_id(queue), queue, trans, m, n, alpha, a, lda, stridea, x, incx, stridex, beta, y, incy, stridey, batch_size, dependencies); gemv_batch_postcondition(queue, trans, m, n, alpha, a, lda, stridea, x, incx, stridex, beta, y, incy, stridey, batch_size, dependencies); return done; } static inline cl::sycl::event gemv_batch( cl::sycl::queue &queue, transpose trans, std::int64_t m, std::int64_t n, std::complex alpha, const std::complex *a, std::int64_t lda, std::int64_t stridea, const std::complex *x, std::int64_t incx, std::int64_t stridex, std::complex beta, std::complex *y, std::int64_t incy, std::int64_t stridey, std::int64_t batch_size, const std::vector &dependencies = {}) { gemv_batch_precondition(queue, trans, m, n, alpha, a, lda, stridea, x, incx, stridex, beta, y, incy, stridey, batch_size, dependencies); auto done = detail::gemv_batch(get_device_id(queue), queue, trans, m, n, alpha, a, lda, stridea, x, incx, stridex, beta, y, incy, stridey, batch_size, dependencies); gemv_batch_postcondition(queue, trans, m, n, alpha, a, lda, stridea, x, incx, stridex, beta, y, incy, stridey, batch_size, dependencies); return done; } static inline cl::sycl::event gemv_batch( cl::sycl::queue &queue, transpose trans, std::int64_t m, std::int64_t n, std::complex alpha, const std::complex *a, std::int64_t lda, std::int64_t stridea, const std::complex *x, std::int64_t incx, std::int64_t stridex, std::complex beta, std::complex *y, std::int64_t incy, std::int64_t stridey, std::int64_t batch_size, const std::vector &dependencies = {}) { gemv_batch_precondition(queue, trans, m, n, alpha, a, lda, stridea, x, incx, stridex, beta, y, incy, stridey, batch_size, dependencies); auto done = detail::gemv_batch(get_device_id(queue), queue, trans, m, n, alpha, a, lda, stridea, x, incx, stridex, beta, y, incy, stridey, batch_size, dependencies); gemv_batch_postcondition(queue, trans, m, n, alpha, a, lda, stridea, x, incx, stridex, beta, y, incy, stridey, batch_size, dependencies); return done; } static inline cl::sycl::event gemv_batch(cl::sycl::queue &queue, transpose *trans, std::int64_t *m, std::int64_t *n, float *alpha, const float **a, std::int64_t *lda, const float **x, std::int64_t *incx, float *beta, float **y, std::int64_t *incy, std::int64_t group_count, std::int64_t *group_size, const std::vector &dependencies = {}) { gemv_batch_precondition(queue, trans, m, n, alpha, a, lda, x, incx, beta, y, incy, group_count, group_size, dependencies); auto done = detail::gemv_batch(get_device_id(queue), queue, trans, m, n, alpha, a, lda, x, incx, beta, y, incy, group_count, group_size, dependencies); gemv_batch_postcondition(queue, trans, m, n, alpha, a, lda, x, incx, beta, y, incy, group_count, group_size, dependencies); return done; } static inline cl::sycl::event gemv_batch(cl::sycl::queue &queue, transpose *trans, std::int64_t *m, std::int64_t *n, double *alpha, const double **a, std::int64_t *lda, const double **x, std::int64_t *incx, double *beta, double **y, std::int64_t *incy, std::int64_t group_count, std::int64_t *group_size, const std::vector &dependencies = {}) { gemv_batch_precondition(queue, trans, m, n, alpha, a, lda, x, incx, beta, y, incy, group_count, group_size, dependencies); auto done = detail::gemv_batch(get_device_id(queue), queue, trans, m, n, alpha, a, lda, x, incx, beta, y, incy, group_count, group_size, dependencies); gemv_batch_postcondition(queue, trans, m, n, alpha, a, lda, x, incx, beta, y, incy, group_count, group_size, dependencies); return done; } static inline cl::sycl::event gemv_batch(cl::sycl::queue &queue, transpose *trans, std::int64_t *m, std::int64_t *n, std::complex *alpha, const std::complex **a, std::int64_t *lda, const std::complex **x, std::int64_t *incx, std::complex *beta, std::complex **y, std::int64_t *incy, std::int64_t group_count, std::int64_t *group_size, const std::vector &dependencies = {}) { gemv_batch_precondition(queue, trans, m, n, alpha, a, lda, x, incx, beta, y, incy, group_count, group_size, dependencies); auto done = detail::gemv_batch(get_device_id(queue), queue, trans, m, n, alpha, a, lda, x, incx, beta, y, incy, group_count, group_size, dependencies); gemv_batch_postcondition(queue, trans, m, n, alpha, a, lda, x, incx, beta, y, incy, group_count, group_size, dependencies); return done; } static inline cl::sycl::event gemv_batch(cl::sycl::queue &queue, transpose *trans, std::int64_t *m, std::int64_t *n, std::complex *alpha, const std::complex **a, std::int64_t *lda, const std::complex **x, std::int64_t *incx, std::complex *beta, std::complex **y, std::int64_t *incy, std::int64_t group_count, std::int64_t *group_size, const std::vector &dependencies = {}) { gemv_batch_precondition(queue, trans, m, n, alpha, a, lda, x, incx, beta, y, incy, group_count, group_size, dependencies); auto done = detail::gemv_batch(get_device_id(queue), queue, trans, m, n, alpha, a, lda, x, incx, beta, y, incy, group_count, group_size, dependencies); gemv_batch_postcondition(queue, trans, m, n, alpha, a, lda, x, incx, beta, y, incy, group_count, group_size, dependencies); return done; } static inline cl::sycl::event dgmm_batch(cl::sycl::queue &queue, side left_right, std::int64_t m, std::int64_t n, const float *a, std::int64_t lda, std::int64_t stridea, const float *x, std::int64_t incx, std::int64_t stridex, float *c, std::int64_t ldc, std::int64_t stridec, std::int64_t batch_size, const std::vector &dependencies = {}) { dgmm_batch_precondition(queue, left_right, m, n, a, lda, stridea, x, incx, stridex, c, ldc, stridec, batch_size, dependencies); auto done = detail::dgmm_batch(get_device_id(queue), queue, left_right, m, n, a, lda, stridea, x, incx, stridex, c, ldc, stridec, batch_size, dependencies); dgmm_batch_postcondition(queue, left_right, m, n, a, lda, stridea, x, incx, stridex, c, ldc, stridec, batch_size, dependencies); return done; } static inline cl::sycl::event dgmm_batch(cl::sycl::queue &queue, side left_right, std::int64_t m, std::int64_t n, const double *a, std::int64_t lda, std::int64_t stridea, const double *x, std::int64_t incx, std::int64_t stridex, double *c, std::int64_t ldc, std::int64_t stridec, std::int64_t batch_size, const std::vector &dependencies = {}) { dgmm_batch_precondition(queue, left_right, m, n, a, lda, stridea, x, incx, stridex, c, ldc, stridec, batch_size, dependencies); auto done = detail::dgmm_batch(get_device_id(queue), queue, left_right, m, n, a, lda, stridea, x, incx, stridex, c, ldc, stridec, batch_size, dependencies); dgmm_batch_postcondition(queue, left_right, m, n, a, lda, stridea, x, incx, stridex, c, ldc, stridec, batch_size, dependencies); return done; } static inline cl::sycl::event dgmm_batch(cl::sycl::queue &queue, side left_right, std::int64_t m, std::int64_t n, const std::complex *a, std::int64_t lda, std::int64_t stridea, const std::complex *x, std::int64_t incx, std::int64_t stridex, std::complex *c, std::int64_t ldc, std::int64_t stridec, std::int64_t batch_size, const std::vector &dependencies = {}) { dgmm_batch_precondition(queue, left_right, m, n, a, lda, stridea, x, incx, stridex, c, ldc, stridec, batch_size, dependencies); auto done = detail::dgmm_batch(get_device_id(queue), queue, left_right, m, n, a, lda, stridea, x, incx, stridex, c, ldc, stridec, batch_size, dependencies); dgmm_batch_postcondition(queue, left_right, m, n, a, lda, stridea, x, incx, stridex, c, ldc, stridec, batch_size, dependencies); return done; } static inline cl::sycl::event dgmm_batch(cl::sycl::queue &queue, side left_right, std::int64_t m, std::int64_t n, const std::complex *a, std::int64_t lda, std::int64_t stridea, const std::complex *x, std::int64_t incx, std::int64_t stridex, std::complex *c, std::int64_t ldc, std::int64_t stridec, std::int64_t batch_size, const std::vector &dependencies = {}) { dgmm_batch_precondition(queue, left_right, m, n, a, lda, stridea, x, incx, stridex, c, ldc, stridec, batch_size, dependencies); auto done = detail::dgmm_batch(get_device_id(queue), queue, left_right, m, n, a, lda, stridea, x, incx, stridex, c, ldc, stridec, batch_size, dependencies); dgmm_batch_postcondition(queue, left_right, m, n, a, lda, stridea, x, incx, stridex, c, ldc, stridec, batch_size, dependencies); return done; } static inline cl::sycl::event dgmm_batch(cl::sycl::queue &queue, side *left_right, std::int64_t *m, std::int64_t *n, const float **a, std::int64_t *lda, const float **x, std::int64_t *incx, float **c, std::int64_t *ldc, std::int64_t group_count, std::int64_t *group_size, const std::vector &dependencies = {}) { dgmm_batch_precondition(queue, left_right, m, n, a, lda, x, incx, c, ldc, group_count, group_size, dependencies); auto done = detail::dgmm_batch(get_device_id(queue), queue, left_right, m, n, a, lda, x, incx, c, ldc, group_count, group_size, dependencies); dgmm_batch_postcondition(queue, left_right, m, n, a, lda, x, incx, c, ldc, group_count, group_size, dependencies); return done; } static inline cl::sycl::event dgmm_batch(cl::sycl::queue &queue, side *left_right, std::int64_t *m, std::int64_t *n, const double **a, std::int64_t *lda, const double **x, std::int64_t *incx, double **c, std::int64_t *ldc, std::int64_t group_count, std::int64_t *group_size, const std::vector &dependencies = {}) { dgmm_batch_precondition(queue, left_right, m, n, a, lda, x, incx, c, ldc, group_count, group_size, dependencies); auto done = detail::dgmm_batch(get_device_id(queue), queue, left_right, m, n, a, lda, x, incx, c, ldc, group_count, group_size, dependencies); dgmm_batch_postcondition(queue, left_right, m, n, a, lda, x, incx, c, ldc, group_count, group_size, dependencies); return done; } static inline cl::sycl::event dgmm_batch(cl::sycl::queue &queue, side *left_right, std::int64_t *m, std::int64_t *n, const std::complex **a, std::int64_t *lda, const std::complex **x, std::int64_t *incx, std::complex **c, std::int64_t *ldc, std::int64_t group_count, std::int64_t *group_size, const std::vector &dependencies = {}) { dgmm_batch_precondition(queue, left_right, m, n, a, lda, x, incx, c, ldc, group_count, group_size, dependencies); auto done = detail::dgmm_batch(get_device_id(queue), queue, left_right, m, n, a, lda, x, incx, c, ldc, group_count, group_size, dependencies); dgmm_batch_postcondition(queue, left_right, m, n, a, lda, x, incx, c, ldc, group_count, group_size, dependencies); return done; } static inline cl::sycl::event dgmm_batch(cl::sycl::queue &queue, side *left_right, std::int64_t *m, std::int64_t *n, const std::complex **a, std::int64_t *lda, const std::complex **x, std::int64_t *incx, std::complex **c, std::int64_t *ldc, std::int64_t group_count, std::int64_t *group_size, const std::vector &dependencies = {}) { dgmm_batch_precondition(queue, left_right, m, n, a, lda, x, incx, c, ldc, group_count, group_size, dependencies); auto done = detail::dgmm_batch(get_device_id(queue), queue, left_right, m, n, a, lda, x, incx, c, ldc, group_count, group_size, dependencies); dgmm_batch_postcondition(queue, left_right, m, n, a, lda, x, incx, c, ldc, group_count, group_size, dependencies); return done; } static inline cl::sycl::event ger(cl::sycl::queue &queue, std::int64_t m, std::int64_t n, float alpha, const float *x, std::int64_t incx, const float *y, std::int64_t incy, float *a, std::int64_t lda, const std::vector &dependencies = {}) { ger_precondition(queue, m, n, alpha, x, incx, y, incy, a, lda, dependencies); auto done = detail::ger(get_device_id(queue), queue, m, n, alpha, x, incx, y, incy, a, lda, dependencies); ger_postcondition(queue, m, n, alpha, x, incx, y, incy, a, lda, dependencies); return done; } static inline cl::sycl::event ger(cl::sycl::queue &queue, std::int64_t m, std::int64_t n, double alpha, const double *x, std::int64_t incx, const double *y, std::int64_t incy, double *a, std::int64_t lda, const std::vector &dependencies = {}) { ger_precondition(queue, m, n, alpha, x, incx, y, incy, a, lda, dependencies); auto done = detail::ger(get_device_id(queue), queue, m, n, alpha, x, incx, y, incy, a, lda, dependencies); ger_postcondition(queue, m, n, alpha, x, incx, y, incy, a, lda, dependencies); return done; } static inline cl::sycl::event gerc(cl::sycl::queue &queue, std::int64_t m, std::int64_t n, std::complex alpha, const std::complex *x, std::int64_t incx, const std::complex *y, std::int64_t incy, std::complex *a, std::int64_t lda, const std::vector &dependencies = {}) { gerc_precondition(queue, m, n, alpha, x, incx, y, incy, a, lda, dependencies); auto done = detail::gerc(get_device_id(queue), queue, m, n, alpha, x, incx, y, incy, a, lda, dependencies); gerc_postcondition(queue, m, n, alpha, x, incx, y, incy, a, lda, dependencies); return done; } static inline cl::sycl::event gerc(cl::sycl::queue &queue, std::int64_t m, std::int64_t n, std::complex alpha, const std::complex *x, std::int64_t incx, const std::complex *y, std::int64_t incy, std::complex *a, std::int64_t lda, const std::vector &dependencies = {}) { gerc_precondition(queue, m, n, alpha, x, incx, y, incy, a, lda, dependencies); auto done = detail::gerc(get_device_id(queue), queue, m, n, alpha, x, incx, y, incy, a, lda, dependencies); gerc_postcondition(queue, m, n, alpha, x, incx, y, incy, a, lda, dependencies); return done; } static inline cl::sycl::event geru(cl::sycl::queue &queue, std::int64_t m, std::int64_t n, std::complex alpha, const std::complex *x, std::int64_t incx, const std::complex *y, std::int64_t incy, std::complex *a, std::int64_t lda, const std::vector &dependencies = {}) { geru_precondition(queue, m, n, alpha, x, incx, y, incy, a, lda, dependencies); auto done = detail::geru(get_device_id(queue), queue, m, n, alpha, x, incx, y, incy, a, lda, dependencies); geru_postcondition(queue, m, n, alpha, x, incx, y, incy, a, lda, dependencies); return done; } static inline cl::sycl::event geru(cl::sycl::queue &queue, std::int64_t m, std::int64_t n, std::complex alpha, const std::complex *x, std::int64_t incx, const std::complex *y, std::int64_t incy, std::complex *a, std::int64_t lda, const std::vector &dependencies = {}) { geru_precondition(queue, m, n, alpha, x, incx, y, incy, a, lda, dependencies); auto done = detail::geru(get_device_id(queue), queue, m, n, alpha, x, incx, y, incy, a, lda, dependencies); geru_postcondition(queue, m, n, alpha, x, incx, y, incy, a, lda, dependencies); return done; } static inline cl::sycl::event hbmv(cl::sycl::queue &queue, uplo upper_lower, std::int64_t n, std::int64_t k, std::complex alpha, const std::complex *a, std::int64_t lda, const std::complex *x, std::int64_t incx, std::complex beta, std::complex *y, std::int64_t incy, const std::vector &dependencies = {}) { hbmv_precondition(queue, upper_lower, n, k, alpha, a, lda, x, incx, beta, y, incy, dependencies); auto done = detail::hbmv(get_device_id(queue), queue, upper_lower, n, k, alpha, a, lda, x, incx, beta, y, incy, dependencies); hbmv_postcondition(queue, upper_lower, n, k, alpha, a, lda, x, incx, beta, y, incy, dependencies); return done; } static inline cl::sycl::event hbmv(cl::sycl::queue &queue, uplo upper_lower, std::int64_t n, std::int64_t k, std::complex alpha, const std::complex *a, std::int64_t lda, const std::complex *x, std::int64_t incx, std::complex beta, std::complex *y, std::int64_t incy, const std::vector &dependencies = {}) { hbmv_precondition(queue, upper_lower, n, k, alpha, a, lda, x, incx, beta, y, incy, dependencies); auto done = detail::hbmv(get_device_id(queue), queue, upper_lower, n, k, alpha, a, lda, x, incx, beta, y, incy, dependencies); hbmv_postcondition(queue, upper_lower, n, k, alpha, a, lda, x, incx, beta, y, incy, dependencies); return done; } static inline cl::sycl::event hemm(cl::sycl::queue &queue, side left_right, uplo upper_lower, std::int64_t m, std::int64_t n, std::complex alpha, const std::complex *a, std::int64_t lda, const std::complex *b, std::int64_t ldb, std::complex beta, std::complex *c, std::int64_t ldc, const std::vector &dependencies = {}) { hemm_precondition(queue, left_right, upper_lower, m, n, alpha, a, lda, b, ldb, beta, c, ldc, dependencies); auto done = detail::hemm(get_device_id(queue), queue, left_right, upper_lower, m, n, alpha, a, lda, b, ldb, beta, c, ldc, dependencies); hemm_postcondition(queue, left_right, upper_lower, m, n, alpha, a, lda, b, ldb, beta, c, ldc, dependencies); return done; } static inline cl::sycl::event hemm(cl::sycl::queue &queue, side left_right, uplo upper_lower, std::int64_t m, std::int64_t n, std::complex alpha, const std::complex *a, std::int64_t lda, const std::complex *b, std::int64_t ldb, std::complex beta, std::complex *c, std::int64_t ldc, const std::vector &dependencies = {}) { hemm_precondition(queue, left_right, upper_lower, m, n, alpha, a, lda, b, ldb, beta, c, ldc, dependencies); auto done = detail::hemm(get_device_id(queue), queue, left_right, upper_lower, m, n, alpha, a, lda, b, ldb, beta, c, ldc, dependencies); hemm_postcondition(queue, left_right, upper_lower, m, n, alpha, a, lda, b, ldb, beta, c, ldc, dependencies); return done; } static inline cl::sycl::event hemv(cl::sycl::queue &queue, uplo upper_lower, std::int64_t n, std::complex alpha, const std::complex *a, std::int64_t lda, const std::complex *x, std::int64_t incx, std::complex beta, std::complex *y, std::int64_t incy, const std::vector &dependencies = {}) { hemv_precondition(queue, upper_lower, n, alpha, a, lda, x, incx, beta, y, incy, dependencies); auto done = detail::hemv(get_device_id(queue), queue, upper_lower, n, alpha, a, lda, x, incx, beta, y, incy, dependencies); hemv_postcondition(queue, upper_lower, n, alpha, a, lda, x, incx, beta, y, incy, dependencies); return done; } static inline cl::sycl::event hemv(cl::sycl::queue &queue, uplo upper_lower, std::int64_t n, std::complex alpha, const std::complex *a, std::int64_t lda, const std::complex *x, std::int64_t incx, std::complex beta, std::complex *y, std::int64_t incy, const std::vector &dependencies = {}) { hemv_precondition(queue, upper_lower, n, alpha, a, lda, x, incx, beta, y, incy, dependencies); auto done = detail::hemv(get_device_id(queue), queue, upper_lower, n, alpha, a, lda, x, incx, beta, y, incy, dependencies); hemv_postcondition(queue, upper_lower, n, alpha, a, lda, x, incx, beta, y, incy, dependencies); return done; } static inline cl::sycl::event her(cl::sycl::queue &queue, uplo upper_lower, std::int64_t n, float alpha, const std::complex *x, std::int64_t incx, std::complex *a, std::int64_t lda, const std::vector &dependencies = {}) { her_precondition(queue, upper_lower, n, alpha, x, incx, a, lda, dependencies); auto done = detail::her(get_device_id(queue), queue, upper_lower, n, alpha, x, incx, a, lda, dependencies); her_postcondition(queue, upper_lower, n, alpha, x, incx, a, lda, dependencies); return done; } static inline cl::sycl::event her(cl::sycl::queue &queue, uplo upper_lower, std::int64_t n, double alpha, const std::complex *x, std::int64_t incx, std::complex *a, std::int64_t lda, const std::vector &dependencies = {}) { her_precondition(queue, upper_lower, n, alpha, x, incx, a, lda, dependencies); auto done = detail::her(get_device_id(queue), queue, upper_lower, n, alpha, x, incx, a, lda, dependencies); her_postcondition(queue, upper_lower, n, alpha, x, incx, a, lda, dependencies); return done; } static inline cl::sycl::event her2(cl::sycl::queue &queue, uplo upper_lower, std::int64_t n, std::complex alpha, const std::complex *x, std::int64_t incx, const std::complex *y, std::int64_t incy, std::complex *a, std::int64_t lda, const std::vector &dependencies = {}) { her2_precondition(queue, upper_lower, n, alpha, x, incx, y, incy, a, lda, dependencies); auto done = detail::her2(get_device_id(queue), queue, upper_lower, n, alpha, x, incx, y, incy, a, lda, dependencies); her2_postcondition(queue, upper_lower, n, alpha, x, incx, y, incy, a, lda, dependencies); return done; } static inline cl::sycl::event her2(cl::sycl::queue &queue, uplo upper_lower, std::int64_t n, std::complex alpha, const std::complex *x, std::int64_t incx, const std::complex *y, std::int64_t incy, std::complex *a, std::int64_t lda, const std::vector &dependencies = {}) { her2_precondition(queue, upper_lower, n, alpha, x, incx, y, incy, a, lda, dependencies); auto done = detail::her2(get_device_id(queue), queue, upper_lower, n, alpha, x, incx, y, incy, a, lda, dependencies); her2_postcondition(queue, upper_lower, n, alpha, x, incx, y, incy, a, lda, dependencies); return done; } static inline cl::sycl::event her2k(cl::sycl::queue &queue, uplo upper_lower, transpose trans, std::int64_t n, std::int64_t k, std::complex alpha, const std::complex *a, std::int64_t lda, const std::complex *b, std::int64_t ldb, float beta, std::complex *c, std::int64_t ldc, const std::vector &dependencies = {}) { her2k_precondition(queue, upper_lower, trans, n, k, alpha, a, lda, b, ldb, beta, c, ldc, dependencies); auto done = detail::her2k(get_device_id(queue), queue, upper_lower, trans, n, k, alpha, a, lda, b, ldb, beta, c, ldc, dependencies); her2k_postcondition(queue, upper_lower, trans, n, k, alpha, a, lda, b, ldb, beta, c, ldc, dependencies); return done; } static inline cl::sycl::event her2k(cl::sycl::queue &queue, uplo upper_lower, transpose trans, std::int64_t n, std::int64_t k, std::complex alpha, const std::complex *a, std::int64_t lda, const std::complex *b, std::int64_t ldb, double beta, std::complex *c, std::int64_t ldc, const std::vector &dependencies = {}) { her2k_precondition(queue, upper_lower, trans, n, k, alpha, a, lda, b, ldb, beta, c, ldc, dependencies); auto done = detail::her2k(get_device_id(queue), queue, upper_lower, trans, n, k, alpha, a, lda, b, ldb, beta, c, ldc, dependencies); her2k_postcondition(queue, upper_lower, trans, n, k, alpha, a, lda, b, ldb, beta, c, ldc, dependencies); return done; } static inline cl::sycl::event herk(cl::sycl::queue &queue, uplo upper_lower, transpose trans, std::int64_t n, std::int64_t k, float alpha, const std::complex *a, std::int64_t lda, float beta, std::complex *c, std::int64_t ldc, const std::vector &dependencies = {}) { herk_precondition(queue, upper_lower, trans, n, k, alpha, a, lda, beta, c, ldc, dependencies); auto done = detail::herk(get_device_id(queue), queue, upper_lower, trans, n, k, alpha, a, lda, beta, c, ldc, dependencies); herk_postcondition(queue, upper_lower, trans, n, k, alpha, a, lda, beta, c, ldc, dependencies); return done; } static inline cl::sycl::event herk(cl::sycl::queue &queue, uplo upper_lower, transpose trans, std::int64_t n, std::int64_t k, double alpha, const std::complex *a, std::int64_t lda, double beta, std::complex *c, std::int64_t ldc, const std::vector &dependencies = {}) { herk_precondition(queue, upper_lower, trans, n, k, alpha, a, lda, beta, c, ldc, dependencies); auto done = detail::herk(get_device_id(queue), queue, upper_lower, trans, n, k, alpha, a, lda, beta, c, ldc, dependencies); herk_postcondition(queue, upper_lower, trans, n, k, alpha, a, lda, beta, c, ldc, dependencies); return done; } static inline cl::sycl::event hpmv(cl::sycl::queue &queue, uplo upper_lower, std::int64_t n, std::complex alpha, const std::complex *a, const std::complex *x, std::int64_t incx, std::complex beta, std::complex *y, std::int64_t incy, const std::vector &dependencies = {}) { hpmv_precondition(queue, upper_lower, n, alpha, a, x, incx, beta, y, incy, dependencies); auto done = detail::hpmv(get_device_id(queue), queue, upper_lower, n, alpha, a, x, incx, beta, y, incy, dependencies); hpmv_postcondition(queue, upper_lower, n, alpha, a, x, incx, beta, y, incy, dependencies); return done; } static inline cl::sycl::event hpmv(cl::sycl::queue &queue, uplo upper_lower, std::int64_t n, std::complex alpha, const std::complex *a, const std::complex *x, std::int64_t incx, std::complex beta, std::complex *y, std::int64_t incy, const std::vector &dependencies = {}) { hpmv_precondition(queue, upper_lower, n, alpha, a, x, incx, beta, y, incy, dependencies); auto done = detail::hpmv(get_device_id(queue), queue, upper_lower, n, alpha, a, x, incx, beta, y, incy, dependencies); hpmv_postcondition(queue, upper_lower, n, alpha, a, x, incx, beta, y, incy, dependencies); return done; } static inline cl::sycl::event hpr(cl::sycl::queue &queue, uplo upper_lower, std::int64_t n, float alpha, const std::complex *x, std::int64_t incx, std::complex *a, const std::vector &dependencies = {}) { hpr_precondition(queue, upper_lower, n, alpha, x, incx, a, dependencies); auto done = detail::hpr(get_device_id(queue), queue, upper_lower, n, alpha, x, incx, a, dependencies); hpr_postcondition(queue, upper_lower, n, alpha, x, incx, a, dependencies); return done; } static inline cl::sycl::event hpr(cl::sycl::queue &queue, uplo upper_lower, std::int64_t n, double alpha, const std::complex *x, std::int64_t incx, std::complex *a, const std::vector &dependencies = {}) { hpr_precondition(queue, upper_lower, n, alpha, x, incx, a, dependencies); auto done = detail::hpr(get_device_id(queue), queue, upper_lower, n, alpha, x, incx, a, dependencies); hpr_postcondition(queue, upper_lower, n, alpha, x, incx, a, dependencies); return done; } static inline cl::sycl::event hpr2(cl::sycl::queue &queue, uplo upper_lower, std::int64_t n, std::complex alpha, const std::complex *x, std::int64_t incx, const std::complex *y, std::int64_t incy, std::complex *a, const std::vector &dependencies = {}) { hpr2_precondition(queue, upper_lower, n, alpha, x, incx, y, incy, a, dependencies); auto done = detail::hpr2(get_device_id(queue), queue, upper_lower, n, alpha, x, incx, y, incy, a, dependencies); hpr2_postcondition(queue, upper_lower, n, alpha, x, incx, y, incy, a, dependencies); return done; } static inline cl::sycl::event hpr2(cl::sycl::queue &queue, uplo upper_lower, std::int64_t n, std::complex alpha, const std::complex *x, std::int64_t incx, const std::complex *y, std::int64_t incy, std::complex *a, const std::vector &dependencies = {}) { hpr2_precondition(queue, upper_lower, n, alpha, x, incx, y, incy, a, dependencies); auto done = detail::hpr2(get_device_id(queue), queue, upper_lower, n, alpha, x, incx, y, incy, a, dependencies); hpr2_postcondition(queue, upper_lower, n, alpha, x, incx, y, incy, a, dependencies); return done; } static inline cl::sycl::event iamax(cl::sycl::queue &queue, std::int64_t n, const float *x, std::int64_t incx, std::int64_t *result, const std::vector &dependencies = {}) { iamax_precondition(queue, n, x, incx, result, dependencies); auto done = detail::iamax(get_device_id(queue), queue, n, x, incx, result, dependencies); iamax_postcondition(queue, n, x, incx, result, dependencies); return done; } static inline cl::sycl::event iamax(cl::sycl::queue &queue, std::int64_t n, const double *x, std::int64_t incx, std::int64_t *result, const std::vector &dependencies = {}) { iamax_precondition(queue, n, x, incx, result, dependencies); auto done = detail::iamax(get_device_id(queue), queue, n, x, incx, result, dependencies); iamax_postcondition(queue, n, x, incx, result, dependencies); return done; } static inline cl::sycl::event iamax(cl::sycl::queue &queue, std::int64_t n, const std::complex *x, std::int64_t incx, std::int64_t *result, const std::vector &dependencies = {}) { iamax_precondition(queue, n, x, incx, result, dependencies); auto done = detail::iamax(get_device_id(queue), queue, n, x, incx, result, dependencies); iamax_postcondition(queue, n, x, incx, result, dependencies); return done; } static inline cl::sycl::event iamax(cl::sycl::queue &queue, std::int64_t n, const std::complex *x, std::int64_t incx, std::int64_t *result, const std::vector &dependencies = {}) { iamax_precondition(queue, n, x, incx, result, dependencies); auto done = detail::iamax(get_device_id(queue), queue, n, x, incx, result, dependencies); iamax_postcondition(queue, n, x, incx, result, dependencies); return done; } static inline cl::sycl::event iamin(cl::sycl::queue &queue, std::int64_t n, const float *x, std::int64_t incx, std::int64_t *result, const std::vector &dependencies = {}) { iamin_precondition(queue, n, x, incx, result, dependencies); auto done = detail::iamin(get_device_id(queue), queue, n, x, incx, result, dependencies); iamin_postcondition(queue, n, x, incx, result, dependencies); return done; } static inline cl::sycl::event iamin(cl::sycl::queue &queue, std::int64_t n, const double *x, std::int64_t incx, std::int64_t *result, const std::vector &dependencies = {}) { iamin_precondition(queue, n, x, incx, result, dependencies); auto done = detail::iamin(get_device_id(queue), queue, n, x, incx, result, dependencies); iamin_postcondition(queue, n, x, incx, result, dependencies); return done; } static inline cl::sycl::event iamin(cl::sycl::queue &queue, std::int64_t n, const std::complex *x, std::int64_t incx, std::int64_t *result, const std::vector &dependencies = {}) { iamin_precondition(queue, n, x, incx, result, dependencies); auto done = detail::iamin(get_device_id(queue), queue, n, x, incx, result, dependencies); iamin_postcondition(queue, n, x, incx, result, dependencies); return done; } static inline cl::sycl::event iamin(cl::sycl::queue &queue, std::int64_t n, const std::complex *x, std::int64_t incx, std::int64_t *result, const std::vector &dependencies = {}) { iamin_precondition(queue, n, x, incx, result, dependencies); auto done = detail::iamin(get_device_id(queue), queue, n, x, incx, result, dependencies); iamin_postcondition(queue, n, x, incx, result, dependencies); return done; } static inline cl::sycl::event nrm2(cl::sycl::queue &queue, std::int64_t n, const std::complex *x, std::int64_t incx, float *result, const std::vector &dependencies = {}) { nrm2_precondition(queue, n, x, incx, result, dependencies); auto done = detail::nrm2(get_device_id(queue), queue, n, x, incx, result, dependencies); nrm2_postcondition(queue, n, x, incx, result, dependencies); return done; } static inline cl::sycl::event nrm2(cl::sycl::queue &queue, std::int64_t n, const std::complex *x, std::int64_t incx, double *result, const std::vector &dependencies = {}) { nrm2_precondition(queue, n, x, incx, result, dependencies); auto done = detail::nrm2(get_device_id(queue), queue, n, x, incx, result, dependencies); nrm2_postcondition(queue, n, x, incx, result, dependencies); return done; } static inline cl::sycl::event nrm2(cl::sycl::queue &queue, std::int64_t n, const float *x, std::int64_t incx, float *result, const std::vector &dependencies = {}) { nrm2_precondition(queue, n, x, incx, result, dependencies); auto done = detail::nrm2(get_device_id(queue), queue, n, x, incx, result, dependencies); nrm2_postcondition(queue, n, x, incx, result, dependencies); return done; } static inline cl::sycl::event nrm2(cl::sycl::queue &queue, std::int64_t n, const double *x, std::int64_t incx, double *result, const std::vector &dependencies = {}) { nrm2_precondition(queue, n, x, incx, result, dependencies); auto done = detail::nrm2(get_device_id(queue), queue, n, x, incx, result, dependencies); nrm2_postcondition(queue, n, x, incx, result, dependencies); return done; } static inline cl::sycl::event rot(cl::sycl::queue &queue, std::int64_t n, std::complex *x, std::int64_t incx, std::complex *y, std::int64_t incy, float c, float s, const std::vector &dependencies = {}) { rot_precondition(queue, n, x, incx, y, incy, c, s, dependencies); auto done = detail::rot(get_device_id(queue), queue, n, x, incx, y, incy, c, s, dependencies); rot_postcondition(queue, n, x, incx, y, incy, c, s, dependencies); return done; } static inline cl::sycl::event rot(cl::sycl::queue &queue, std::int64_t n, std::complex *x, std::int64_t incx, std::complex *y, std::int64_t incy, double c, double s, const std::vector &dependencies = {}) { rot_precondition(queue, n, x, incx, y, incy, c, s, dependencies); auto done = detail::rot(get_device_id(queue), queue, n, x, incx, y, incy, c, s, dependencies); rot_postcondition(queue, n, x, incx, y, incy, c, s, dependencies); return done; } static inline cl::sycl::event rot(cl::sycl::queue &queue, std::int64_t n, float *x, std::int64_t incx, float *y, std::int64_t incy, float c, float s, const std::vector &dependencies = {}) { rot_precondition(queue, n, x, incx, y, incy, c, s, dependencies); auto done = detail::rot(get_device_id(queue), queue, n, x, incx, y, incy, c, s, dependencies); rot_postcondition(queue, n, x, incx, y, incy, c, s, dependencies); return done; } static inline cl::sycl::event rot(cl::sycl::queue &queue, std::int64_t n, double *x, std::int64_t incx, double *y, std::int64_t incy, double c, double s, const std::vector &dependencies = {}) { rot_precondition(queue, n, x, incx, y, incy, c, s, dependencies); auto done = detail::rot(get_device_id(queue), queue, n, x, incx, y, incy, c, s, dependencies); rot_postcondition(queue, n, x, incx, y, incy, c, s, dependencies); return done; } static inline cl::sycl::event rotg(cl::sycl::queue &queue, float *a, float *b, float *c, float *s, const std::vector &dependencies = {}) { rotg_precondition(queue, a, b, c, s, dependencies); auto done = detail::rotg(get_device_id(queue), queue, a, b, c, s, dependencies); rotg_postcondition(queue, a, b, c, s, dependencies); return done; } static inline cl::sycl::event rotg(cl::sycl::queue &queue, double *a, double *b, double *c, double *s, const std::vector &dependencies = {}) { rotg_precondition(queue, a, b, c, s, dependencies); auto done = detail::rotg(get_device_id(queue), queue, a, b, c, s, dependencies); rotg_postcondition(queue, a, b, c, s, dependencies); return done; } static inline cl::sycl::event rotg(cl::sycl::queue &queue, std::complex *a, std::complex *b, float *c, std::complex *s, const std::vector &dependencies = {}) { rotg_precondition(queue, a, b, c, s, dependencies); auto done = detail::rotg(get_device_id(queue), queue, a, b, c, s, dependencies); rotg_postcondition(queue, a, b, c, s, dependencies); return done; } static inline cl::sycl::event rotg(cl::sycl::queue &queue, std::complex *a, std::complex *b, double *c, std::complex *s, const std::vector &dependencies = {}) { rotg_precondition(queue, a, b, c, s, dependencies); auto done = detail::rotg(get_device_id(queue), queue, a, b, c, s, dependencies); rotg_postcondition(queue, a, b, c, s, dependencies); return done; } static inline cl::sycl::event rotm(cl::sycl::queue &queue, std::int64_t n, float *x, std::int64_t incx, float *y, std::int64_t incy, float *param, const std::vector &dependencies = {}) { rotm_precondition(queue, n, x, incx, y, incy, param, dependencies); auto done = detail::rotm(get_device_id(queue), queue, n, x, incx, y, incy, param, dependencies); rotm_postcondition(queue, n, x, incx, y, incy, param, dependencies); return done; } static inline cl::sycl::event rotm(cl::sycl::queue &queue, std::int64_t n, double *x, std::int64_t incx, double *y, std::int64_t incy, double *param, const std::vector &dependencies = {}) { rotm_precondition(queue, n, x, incx, y, incy, param, dependencies); auto done = detail::rotm(get_device_id(queue), queue, n, x, incx, y, incy, param, dependencies); rotm_postcondition(queue, n, x, incx, y, incy, param, dependencies); return done; } static inline cl::sycl::event rotmg(cl::sycl::queue &queue, float *d1, float *d2, float *x1, float y1, float *param, const std::vector &dependencies = {}) { rotmg_precondition(queue, d1, d2, x1, y1, param, dependencies); auto done = detail::rotmg(get_device_id(queue), queue, d1, d2, x1, y1, param, dependencies); rotmg_postcondition(queue, d1, d2, x1, y1, param, dependencies); return done; } static inline cl::sycl::event rotmg(cl::sycl::queue &queue, double *d1, double *d2, double *x1, double y1, double *param, const std::vector &dependencies = {}) { rotmg_precondition(queue, d1, d2, x1, y1, param, dependencies); auto done = detail::rotmg(get_device_id(queue), queue, d1, d2, x1, y1, param, dependencies); rotmg_postcondition(queue, d1, d2, x1, y1, param, dependencies); return done; } static inline cl::sycl::event sbmv(cl::sycl::queue &queue, uplo upper_lower, std::int64_t n, std::int64_t k, float alpha, const float *a, std::int64_t lda, const float *x, std::int64_t incx, float beta, float *y, std::int64_t incy, const std::vector &dependencies = {}) { sbmv_precondition(queue, upper_lower, n, k, alpha, a, lda, x, incx, beta, y, incy, dependencies); auto done = detail::sbmv(get_device_id(queue), queue, upper_lower, n, k, alpha, a, lda, x, incx, beta, y, incy, dependencies); sbmv_postcondition(queue, upper_lower, n, k, alpha, a, lda, x, incx, beta, y, incy, dependencies); return done; } static inline cl::sycl::event sbmv(cl::sycl::queue &queue, uplo upper_lower, std::int64_t n, std::int64_t k, double alpha, const double *a, std::int64_t lda, const double *x, std::int64_t incx, double beta, double *y, std::int64_t incy, const std::vector &dependencies = {}) { sbmv_precondition(queue, upper_lower, n, k, alpha, a, lda, x, incx, beta, y, incy, dependencies); auto done = detail::sbmv(get_device_id(queue), queue, upper_lower, n, k, alpha, a, lda, x, incx, beta, y, incy, dependencies); sbmv_postcondition(queue, upper_lower, n, k, alpha, a, lda, x, incx, beta, y, incy, dependencies); return done; } static inline cl::sycl::event scal(cl::sycl::queue &queue, std::int64_t n, float alpha, float *x, std::int64_t incx, const std::vector &dependencies = {}) { scal_precondition(queue, n, alpha, x, incx, dependencies); auto done = detail::scal(get_device_id(queue), queue, n, alpha, x, incx, dependencies); scal_postcondition(queue, n, alpha, x, incx, dependencies); return done; } static inline cl::sycl::event scal(cl::sycl::queue &queue, std::int64_t n, double alpha, double *x, std::int64_t incx, const std::vector &dependencies = {}) { scal_precondition(queue, n, alpha, x, incx, dependencies); auto done = detail::scal(get_device_id(queue), queue, n, alpha, x, incx, dependencies); scal_postcondition(queue, n, alpha, x, incx, dependencies); return done; } static inline cl::sycl::event scal(cl::sycl::queue &queue, std::int64_t n, std::complex alpha, std::complex *x, std::int64_t incx, const std::vector &dependencies = {}) { scal_precondition(queue, n, alpha, x, incx, dependencies); auto done = detail::scal(get_device_id(queue), queue, n, alpha, x, incx, dependencies); scal_postcondition(queue, n, alpha, x, incx, dependencies); return done; } static inline cl::sycl::event scal(cl::sycl::queue &queue, std::int64_t n, std::complex alpha, std::complex *x, std::int64_t incx, const std::vector &dependencies = {}) { scal_precondition(queue, n, alpha, x, incx, dependencies); auto done = detail::scal(get_device_id(queue), queue, n, alpha, x, incx, dependencies); scal_postcondition(queue, n, alpha, x, incx, dependencies); return done; } static inline cl::sycl::event scal(cl::sycl::queue &queue, std::int64_t n, float alpha, std::complex *x, std::int64_t incx, const std::vector &dependencies = {}) { scal_precondition(queue, n, alpha, x, incx, dependencies); auto done = detail::scal(get_device_id(queue), queue, n, alpha, x, incx, dependencies); scal_postcondition(queue, n, alpha, x, incx, dependencies); return done; } static inline cl::sycl::event scal(cl::sycl::queue &queue, std::int64_t n, double alpha, std::complex *x, std::int64_t incx, const std::vector &dependencies = {}) { scal_precondition(queue, n, alpha, x, incx, dependencies); auto done = detail::scal(get_device_id(queue), queue, n, alpha, x, incx, dependencies); scal_postcondition(queue, n, alpha, x, incx, dependencies); return done; } static inline cl::sycl::event sdsdot(cl::sycl::queue &queue, std::int64_t n, float sb, const float *x, std::int64_t incx, const float *y, std::int64_t incy, float *result, const std::vector &dependencies = {}) { sdsdot_precondition(queue, n, sb, x, incx, y, incy, result, dependencies); auto done = detail::sdsdot(get_device_id(queue), queue, n, sb, x, incx, y, incy, result, dependencies); sdsdot_postcondition(queue, n, sb, x, incx, y, incy, result, dependencies); return done; } static inline cl::sycl::event spmv(cl::sycl::queue &queue, uplo upper_lower, std::int64_t n, float alpha, const float *a, const float *x, std::int64_t incx, float beta, float *y, std::int64_t incy, const std::vector &dependencies = {}) { spmv_precondition(queue, upper_lower, n, alpha, a, x, incx, beta, y, incy, dependencies); auto done = detail::spmv(get_device_id(queue), queue, upper_lower, n, alpha, a, x, incx, beta, y, incy, dependencies); spmv_postcondition(queue, upper_lower, n, alpha, a, x, incx, beta, y, incy, dependencies); return done; } static inline cl::sycl::event spmv(cl::sycl::queue &queue, uplo upper_lower, std::int64_t n, double alpha, const double *a, const double *x, std::int64_t incx, double beta, double *y, std::int64_t incy, const std::vector &dependencies = {}) { spmv_precondition(queue, upper_lower, n, alpha, a, x, incx, beta, y, incy, dependencies); auto done = detail::spmv(get_device_id(queue), queue, upper_lower, n, alpha, a, x, incx, beta, y, incy, dependencies); spmv_postcondition(queue, upper_lower, n, alpha, a, x, incx, beta, y, incy, dependencies); return done; } static inline cl::sycl::event spr(cl::sycl::queue &queue, uplo upper_lower, std::int64_t n, float alpha, const float *x, std::int64_t incx, float *a, const std::vector &dependencies = {}) { spr_precondition(queue, upper_lower, n, alpha, x, incx, a, dependencies); auto done = detail::spr(get_device_id(queue), queue, upper_lower, n, alpha, x, incx, a, dependencies); spr_postcondition(queue, upper_lower, n, alpha, x, incx, a, dependencies); return done; } static inline cl::sycl::event spr(cl::sycl::queue &queue, uplo upper_lower, std::int64_t n, double alpha, const double *x, std::int64_t incx, double *a, const std::vector &dependencies = {}) { spr_precondition(queue, upper_lower, n, alpha, x, incx, a, dependencies); auto done = detail::spr(get_device_id(queue), queue, upper_lower, n, alpha, x, incx, a, dependencies); spr_postcondition(queue, upper_lower, n, alpha, x, incx, a, dependencies); return done; } static inline cl::sycl::event spr2(cl::sycl::queue &queue, uplo upper_lower, std::int64_t n, float alpha, const float *x, std::int64_t incx, const float *y, std::int64_t incy, float *a, const std::vector &dependencies = {}) { spr2_precondition(queue, upper_lower, n, alpha, x, incx, y, incy, a, dependencies); auto done = detail::spr2(get_device_id(queue), queue, upper_lower, n, alpha, x, incx, y, incy, a, dependencies); spr2_postcondition(queue, upper_lower, n, alpha, x, incx, y, incy, a, dependencies); return done; } static inline cl::sycl::event spr2(cl::sycl::queue &queue, uplo upper_lower, std::int64_t n, double alpha, const double *x, std::int64_t incx, const double *y, std::int64_t incy, double *a, const std::vector &dependencies = {}) { spr2_precondition(queue, upper_lower, n, alpha, x, incx, y, incy, a, dependencies); auto done = detail::spr2(get_device_id(queue), queue, upper_lower, n, alpha, x, incx, y, incy, a, dependencies); spr2_postcondition(queue, upper_lower, n, alpha, x, incx, y, incy, a, dependencies); return done; } static inline cl::sycl::event swap(cl::sycl::queue &queue, std::int64_t n, float *x, std::int64_t incx, float *y, std::int64_t incy, const std::vector &dependencies = {}) { swap_precondition(queue, n, x, incx, y, incy, dependencies); auto done = detail::swap(get_device_id(queue), queue, n, x, incx, y, incy, dependencies); swap_postcondition(queue, n, x, incx, y, incy, dependencies); return done; } static inline cl::sycl::event swap(cl::sycl::queue &queue, std::int64_t n, double *x, std::int64_t incx, double *y, std::int64_t incy, const std::vector &dependencies = {}) { swap_precondition(queue, n, x, incx, y, incy, dependencies); auto done = detail::swap(get_device_id(queue), queue, n, x, incx, y, incy, dependencies); swap_postcondition(queue, n, x, incx, y, incy, dependencies); return done; } static inline cl::sycl::event swap(cl::sycl::queue &queue, std::int64_t n, std::complex *x, std::int64_t incx, std::complex *y, std::int64_t incy, const std::vector &dependencies = {}) { swap_precondition(queue, n, x, incx, y, incy, dependencies); auto done = detail::swap(get_device_id(queue), queue, n, x, incx, y, incy, dependencies); swap_postcondition(queue, n, x, incx, y, incy, dependencies); return done; } static inline cl::sycl::event swap(cl::sycl::queue &queue, std::int64_t n, std::complex *x, std::int64_t incx, std::complex *y, std::int64_t incy, const std::vector &dependencies = {}) { swap_precondition(queue, n, x, incx, y, incy, dependencies); auto done = detail::swap(get_device_id(queue), queue, n, x, incx, y, incy, dependencies); swap_postcondition(queue, n, x, incx, y, incy, dependencies); return done; } static inline cl::sycl::event symm(cl::sycl::queue &queue, side left_right, uplo upper_lower, std::int64_t m, std::int64_t n, float alpha, const float *a, std::int64_t lda, const float *b, std::int64_t ldb, float beta, float *c, std::int64_t ldc, const std::vector &dependencies = {}) { symm_precondition(queue, left_right, upper_lower, m, n, alpha, a, lda, b, ldb, beta, c, ldc, dependencies); auto done = detail::symm(get_device_id(queue), queue, left_right, upper_lower, m, n, alpha, a, lda, b, ldb, beta, c, ldc, dependencies); symm_postcondition(queue, left_right, upper_lower, m, n, alpha, a, lda, b, ldb, beta, c, ldc, dependencies); return done; } static inline cl::sycl::event symm(cl::sycl::queue &queue, side left_right, uplo upper_lower, std::int64_t m, std::int64_t n, double alpha, const double *a, std::int64_t lda, const double *b, std::int64_t ldb, double beta, double *c, std::int64_t ldc, const std::vector &dependencies = {}) { symm_precondition(queue, left_right, upper_lower, m, n, alpha, a, lda, b, ldb, beta, c, ldc, dependencies); auto done = detail::symm(get_device_id(queue), queue, left_right, upper_lower, m, n, alpha, a, lda, b, ldb, beta, c, ldc, dependencies); symm_postcondition(queue, left_right, upper_lower, m, n, alpha, a, lda, b, ldb, beta, c, ldc, dependencies); return done; } static inline cl::sycl::event symm(cl::sycl::queue &queue, side left_right, uplo upper_lower, std::int64_t m, std::int64_t n, std::complex alpha, const std::complex *a, std::int64_t lda, const std::complex *b, std::int64_t ldb, std::complex beta, std::complex *c, std::int64_t ldc, const std::vector &dependencies = {}) { symm_precondition(queue, left_right, upper_lower, m, n, alpha, a, lda, b, ldb, beta, c, ldc, dependencies); auto done = detail::symm(get_device_id(queue), queue, left_right, upper_lower, m, n, alpha, a, lda, b, ldb, beta, c, ldc, dependencies); symm_postcondition(queue, left_right, upper_lower, m, n, alpha, a, lda, b, ldb, beta, c, ldc, dependencies); return done; } static inline cl::sycl::event symm(cl::sycl::queue &queue, side left_right, uplo upper_lower, std::int64_t m, std::int64_t n, std::complex alpha, const std::complex *a, std::int64_t lda, const std::complex *b, std::int64_t ldb, std::complex beta, std::complex *c, std::int64_t ldc, const std::vector &dependencies = {}) { symm_precondition(queue, left_right, upper_lower, m, n, alpha, a, lda, b, ldb, beta, c, ldc, dependencies); auto done = detail::symm(get_device_id(queue), queue, left_right, upper_lower, m, n, alpha, a, lda, b, ldb, beta, c, ldc, dependencies); symm_postcondition(queue, left_right, upper_lower, m, n, alpha, a, lda, b, ldb, beta, c, ldc, dependencies); return done; } static inline cl::sycl::event symv(cl::sycl::queue &queue, uplo upper_lower, std::int64_t n, float alpha, const float *a, std::int64_t lda, const float *x, std::int64_t incx, float beta, float *y, std::int64_t incy, const std::vector &dependencies = {}) { symv_precondition(queue, upper_lower, n, alpha, a, lda, x, incx, beta, y, incy, dependencies); auto done = detail::symv(get_device_id(queue), queue, upper_lower, n, alpha, a, lda, x, incx, beta, y, incy, dependencies); symv_postcondition(queue, upper_lower, n, alpha, a, lda, x, incx, beta, y, incy, dependencies); return done; } static inline cl::sycl::event symv(cl::sycl::queue &queue, uplo upper_lower, std::int64_t n, double alpha, const double *a, std::int64_t lda, const double *x, std::int64_t incx, double beta, double *y, std::int64_t incy, const std::vector &dependencies = {}) { symv_precondition(queue, upper_lower, n, alpha, a, lda, x, incx, beta, y, incy, dependencies); auto done = detail::symv(get_device_id(queue), queue, upper_lower, n, alpha, a, lda, x, incx, beta, y, incy, dependencies); symv_postcondition(queue, upper_lower, n, alpha, a, lda, x, incx, beta, y, incy, dependencies); return done; } static inline cl::sycl::event syr(cl::sycl::queue &queue, uplo upper_lower, std::int64_t n, float alpha, const float *x, std::int64_t incx, float *a, std::int64_t lda, const std::vector &dependencies = {}) { syr_precondition(queue, upper_lower, n, alpha, x, incx, a, lda, dependencies); auto done = detail::syr(get_device_id(queue), queue, upper_lower, n, alpha, x, incx, a, lda, dependencies); syr_postcondition(queue, upper_lower, n, alpha, x, incx, a, lda, dependencies); return done; } static inline cl::sycl::event syr(cl::sycl::queue &queue, uplo upper_lower, std::int64_t n, double alpha, const double *x, std::int64_t incx, double *a, std::int64_t lda, const std::vector &dependencies = {}) { syr_precondition(queue, upper_lower, n, alpha, x, incx, a, lda, dependencies); auto done = detail::syr(get_device_id(queue), queue, upper_lower, n, alpha, x, incx, a, lda, dependencies); syr_postcondition(queue, upper_lower, n, alpha, x, incx, a, lda, dependencies); return done; } static inline cl::sycl::event syr2(cl::sycl::queue &queue, uplo upper_lower, std::int64_t n, float alpha, const float *x, std::int64_t incx, const float *y, std::int64_t incy, float *a, std::int64_t lda, const std::vector &dependencies = {}) { syr2_precondition(queue, upper_lower, n, alpha, x, incx, y, incy, a, lda, dependencies); auto done = detail::syr2(get_device_id(queue), queue, upper_lower, n, alpha, x, incx, y, incy, a, lda, dependencies); syr2_postcondition(queue, upper_lower, n, alpha, x, incx, y, incy, a, lda, dependencies); return done; } static inline cl::sycl::event syr2(cl::sycl::queue &queue, uplo upper_lower, std::int64_t n, double alpha, const double *x, std::int64_t incx, const double *y, std::int64_t incy, double *a, std::int64_t lda, const std::vector &dependencies = {}) { syr2_precondition(queue, upper_lower, n, alpha, x, incx, y, incy, a, lda, dependencies); auto done = detail::syr2(get_device_id(queue), queue, upper_lower, n, alpha, x, incx, y, incy, a, lda, dependencies); syr2_postcondition(queue, upper_lower, n, alpha, x, incx, y, incy, a, lda, dependencies); return done; } static inline cl::sycl::event syr2k(cl::sycl::queue &queue, uplo upper_lower, transpose trans, std::int64_t n, std::int64_t k, float alpha, const float *a, std::int64_t lda, const float *b, std::int64_t ldb, float beta, float *c, std::int64_t ldc, const std::vector &dependencies = {}) { syr2k_precondition(queue, upper_lower, trans, n, k, alpha, a, lda, b, ldb, beta, c, ldc, dependencies); auto done = detail::syr2k(get_device_id(queue), queue, upper_lower, trans, n, k, alpha, a, lda, b, ldb, beta, c, ldc, dependencies); syr2k_postcondition(queue, upper_lower, trans, n, k, alpha, a, lda, b, ldb, beta, c, ldc, dependencies); return done; } static inline cl::sycl::event syr2k(cl::sycl::queue &queue, uplo upper_lower, transpose trans, std::int64_t n, std::int64_t k, double alpha, const double *a, std::int64_t lda, const double *b, std::int64_t ldb, double beta, double *c, std::int64_t ldc, const std::vector &dependencies = {}) { syr2k_precondition(queue, upper_lower, trans, n, k, alpha, a, lda, b, ldb, beta, c, ldc, dependencies); auto done = detail::syr2k(get_device_id(queue), queue, upper_lower, trans, n, k, alpha, a, lda, b, ldb, beta, c, ldc, dependencies); syr2k_postcondition(queue, upper_lower, trans, n, k, alpha, a, lda, b, ldb, beta, c, ldc, dependencies); return done; } static inline cl::sycl::event syr2k(cl::sycl::queue &queue, uplo upper_lower, transpose trans, std::int64_t n, std::int64_t k, std::complex alpha, const std::complex *a, std::int64_t lda, const std::complex *b, std::int64_t ldb, std::complex beta, std::complex *c, std::int64_t ldc, const std::vector &dependencies = {}) { syr2k_precondition(queue, upper_lower, trans, n, k, alpha, a, lda, b, ldb, beta, c, ldc, dependencies); auto done = detail::syr2k(get_device_id(queue), queue, upper_lower, trans, n, k, alpha, a, lda, b, ldb, beta, c, ldc, dependencies); syr2k_postcondition(queue, upper_lower, trans, n, k, alpha, a, lda, b, ldb, beta, c, ldc, dependencies); return done; } static inline cl::sycl::event syr2k(cl::sycl::queue &queue, uplo upper_lower, transpose trans, std::int64_t n, std::int64_t k, std::complex alpha, const std::complex *a, std::int64_t lda, const std::complex *b, std::int64_t ldb, std::complex beta, std::complex *c, std::int64_t ldc, const std::vector &dependencies = {}) { syr2k_precondition(queue, upper_lower, trans, n, k, alpha, a, lda, b, ldb, beta, c, ldc, dependencies); auto done = detail::syr2k(get_device_id(queue), queue, upper_lower, trans, n, k, alpha, a, lda, b, ldb, beta, c, ldc, dependencies); syr2k_postcondition(queue, upper_lower, trans, n, k, alpha, a, lda, b, ldb, beta, c, ldc, dependencies); return done; } static inline cl::sycl::event syrk(cl::sycl::queue &queue, uplo upper_lower, transpose trans, std::int64_t n, std::int64_t k, float alpha, const float *a, std::int64_t lda, float beta, float *c, std::int64_t ldc, const std::vector &dependencies = {}) { syrk_precondition(queue, upper_lower, trans, n, k, alpha, a, lda, beta, c, ldc, dependencies); auto done = detail::syrk(get_device_id(queue), queue, upper_lower, trans, n, k, alpha, a, lda, beta, c, ldc, dependencies); syrk_postcondition(queue, upper_lower, trans, n, k, alpha, a, lda, beta, c, ldc, dependencies); return done; } static inline cl::sycl::event syrk(cl::sycl::queue &queue, uplo upper_lower, transpose trans, std::int64_t n, std::int64_t k, double alpha, const double *a, std::int64_t lda, double beta, double *c, std::int64_t ldc, const std::vector &dependencies = {}) { syrk_precondition(queue, upper_lower, trans, n, k, alpha, a, lda, beta, c, ldc, dependencies); auto done = detail::syrk(get_device_id(queue), queue, upper_lower, trans, n, k, alpha, a, lda, beta, c, ldc, dependencies); syrk_postcondition(queue, upper_lower, trans, n, k, alpha, a, lda, beta, c, ldc, dependencies); return done; } static inline cl::sycl::event syrk(cl::sycl::queue &queue, uplo upper_lower, transpose trans, std::int64_t n, std::int64_t k, std::complex alpha, const std::complex *a, std::int64_t lda, std::complex beta, std::complex *c, std::int64_t ldc, const std::vector &dependencies = {}) { syrk_precondition(queue, upper_lower, trans, n, k, alpha, a, lda, beta, c, ldc, dependencies); auto done = detail::syrk(get_device_id(queue), queue, upper_lower, trans, n, k, alpha, a, lda, beta, c, ldc, dependencies); syrk_postcondition(queue, upper_lower, trans, n, k, alpha, a, lda, beta, c, ldc, dependencies); return done; } static inline cl::sycl::event syrk(cl::sycl::queue &queue, uplo upper_lower, transpose trans, std::int64_t n, std::int64_t k, std::complex alpha, const std::complex *a, std::int64_t lda, std::complex beta, std::complex *c, std::int64_t ldc, const std::vector &dependencies = {}) { syrk_precondition(queue, upper_lower, trans, n, k, alpha, a, lda, beta, c, ldc, dependencies); auto done = detail::syrk(get_device_id(queue), queue, upper_lower, trans, n, k, alpha, a, lda, beta, c, ldc, dependencies); syrk_postcondition(queue, upper_lower, trans, n, k, alpha, a, lda, beta, c, ldc, dependencies); return done; } static inline cl::sycl::event syrk_batch(cl::sycl::queue &queue, uplo *upper_lower, transpose *trans, std::int64_t *n, std::int64_t *k, float *alpha, const float **a, std::int64_t *lda, float *beta, float **c, std::int64_t *ldc, std::int64_t group_count, std::int64_t *group_size, const std::vector &dependencies = {}) { syrk_batch_precondition(queue, upper_lower, trans, n, k, alpha, a, lda, beta, c, ldc, group_count, group_size, dependencies); auto done = detail::syrk_batch(get_device_id(queue), queue, upper_lower, trans, n, k, alpha, a, lda, beta, c, ldc, group_count, group_size, dependencies); syrk_batch_postcondition(queue, upper_lower, trans, n, k, alpha, a, lda, beta, c, ldc, group_count, group_size, dependencies); return done; } static inline cl::sycl::event syrk_batch(cl::sycl::queue &queue, uplo *upper_lower, transpose *trans, std::int64_t *n, std::int64_t *k, double *alpha, const double **a, std::int64_t *lda, double *beta, double **c, std::int64_t *ldc, std::int64_t group_count, std::int64_t *group_size, const std::vector &dependencies = {}) { syrk_batch_precondition(queue, upper_lower, trans, n, k, alpha, a, lda, beta, c, ldc, group_count, group_size, dependencies); auto done = detail::syrk_batch(get_device_id(queue), queue, upper_lower, trans, n, k, alpha, a, lda, beta, c, ldc, group_count, group_size, dependencies); syrk_batch_postcondition(queue, upper_lower, trans, n, k, alpha, a, lda, beta, c, ldc, group_count, group_size, dependencies); return done; } static inline cl::sycl::event syrk_batch(cl::sycl::queue &queue, uplo *upper_lower, transpose *trans, std::int64_t *n, std::int64_t *k, std::complex *alpha, const std::complex **a, std::int64_t *lda, std::complex *beta, std::complex **c, std::int64_t *ldc, std::int64_t group_count, std::int64_t *group_size, const std::vector &dependencies = {}) { syrk_batch_precondition(queue, upper_lower, trans, n, k, alpha, a, lda, beta, c, ldc, group_count, group_size, dependencies); auto done = detail::syrk_batch(get_device_id(queue), queue, upper_lower, trans, n, k, alpha, a, lda, beta, c, ldc, group_count, group_size, dependencies); syrk_batch_postcondition(queue, upper_lower, trans, n, k, alpha, a, lda, beta, c, ldc, group_count, group_size, dependencies); return done; } static inline cl::sycl::event syrk_batch(cl::sycl::queue &queue, uplo *upper_lower, transpose *trans, std::int64_t *n, std::int64_t *k, std::complex *alpha, const std::complex **a, std::int64_t *lda, std::complex *beta, std::complex **c, std::int64_t *ldc, std::int64_t group_count, std::int64_t *group_size, const std::vector &dependencies = {}) { syrk_batch_precondition(queue, upper_lower, trans, n, k, alpha, a, lda, beta, c, ldc, group_count, group_size, dependencies); auto done = detail::syrk_batch(get_device_id(queue), queue, upper_lower, trans, n, k, alpha, a, lda, beta, c, ldc, group_count, group_size, dependencies); syrk_batch_postcondition(queue, upper_lower, trans, n, k, alpha, a, lda, beta, c, ldc, group_count, group_size, dependencies); return done; } static inline cl::sycl::event syrk_batch(cl::sycl::queue &queue, uplo upper_lower, transpose trans, std::int64_t n, std::int64_t k, float alpha, const float *a, std::int64_t lda, std::int64_t stride_a, float beta, float *c, std::int64_t ldc, std::int64_t stride_c, std::int64_t batch_size, const std::vector &dependencies = {}) { syrk_batch_precondition(queue, upper_lower, trans, n, k, alpha, a, lda, stride_a, beta, c, ldc, stride_c, batch_size, dependencies); auto done = detail::syrk_batch(get_device_id(queue), queue, upper_lower, trans, n, k, alpha, a, lda, stride_a, beta, c, ldc, stride_c, batch_size, dependencies); syrk_batch_postcondition(queue, upper_lower, trans, n, k, alpha, a, lda, stride_a, beta, c, ldc, stride_c, batch_size, dependencies); return done; } static inline cl::sycl::event syrk_batch(cl::sycl::queue &queue, uplo upper_lower, transpose trans, std::int64_t n, std::int64_t k, double alpha, const double *a, std::int64_t lda, std::int64_t stride_a, double beta, double *c, std::int64_t ldc, std::int64_t stride_c, std::int64_t batch_size, const std::vector &dependencies = {}) { syrk_batch_precondition(queue, upper_lower, trans, n, k, alpha, a, lda, stride_a, beta, c, ldc, stride_c, batch_size, dependencies); auto done = detail::syrk_batch(get_device_id(queue), queue, upper_lower, trans, n, k, alpha, a, lda, stride_a, beta, c, ldc, stride_c, batch_size, dependencies); syrk_batch_postcondition(queue, upper_lower, trans, n, k, alpha, a, lda, stride_a, beta, c, ldc, stride_c, batch_size, dependencies); return done; } static inline cl::sycl::event syrk_batch(cl::sycl::queue &queue, uplo upper_lower, transpose trans, std::int64_t n, std::int64_t k, std::complex alpha, const std::complex *a, std::int64_t lda, std::int64_t stride_a, std::complex beta, std::complex *c, std::int64_t ldc, std::int64_t stride_c, std::int64_t batch_size, const std::vector &dependencies = {}) { syrk_batch_precondition(queue, upper_lower, trans, n, k, alpha, a, lda, stride_a, beta, c, ldc, stride_c, batch_size, dependencies); auto done = detail::syrk_batch(get_device_id(queue), queue, upper_lower, trans, n, k, alpha, a, lda, stride_a, beta, c, ldc, stride_c, batch_size, dependencies); syrk_batch_postcondition(queue, upper_lower, trans, n, k, alpha, a, lda, stride_a, beta, c, ldc, stride_c, batch_size, dependencies); return done; } static inline cl::sycl::event syrk_batch(cl::sycl::queue &queue, uplo upper_lower, transpose trans, std::int64_t n, std::int64_t k, std::complex alpha, const std::complex *a, std::int64_t lda, std::int64_t stride_a, std::complex beta, std::complex *c, std::int64_t ldc, std::int64_t stride_c, std::int64_t batch_size, const std::vector &dependencies = {}) { syrk_batch_precondition(queue, upper_lower, trans, n, k, alpha, a, lda, stride_a, beta, c, ldc, stride_c, batch_size, dependencies); auto done = detail::syrk_batch(get_device_id(queue), queue, upper_lower, trans, n, k, alpha, a, lda, stride_a, beta, c, ldc, stride_c, batch_size, dependencies); syrk_batch_postcondition(queue, upper_lower, trans, n, k, alpha, a, lda, stride_a, beta, c, ldc, stride_c, batch_size, dependencies); return done; } static inline cl::sycl::event tbmv(cl::sycl::queue &queue, uplo upper_lower, transpose trans, diag unit_diag, std::int64_t n, std::int64_t k, const float *a, std::int64_t lda, float *x, std::int64_t incx, const std::vector &dependencies = {}) { tbmv_precondition(queue, upper_lower, trans, unit_diag, n, k, a, lda, x, incx, dependencies); auto done = detail::tbmv(get_device_id(queue), queue, upper_lower, trans, unit_diag, n, k, a, lda, x, incx, dependencies); tbmv_postcondition(queue, upper_lower, trans, unit_diag, n, k, a, lda, x, incx, dependencies); return done; } static inline cl::sycl::event tbmv(cl::sycl::queue &queue, uplo upper_lower, transpose trans, diag unit_diag, std::int64_t n, std::int64_t k, const double *a, std::int64_t lda, double *x, std::int64_t incx, const std::vector &dependencies = {}) { tbmv_precondition(queue, upper_lower, trans, unit_diag, n, k, a, lda, x, incx, dependencies); auto done = detail::tbmv(get_device_id(queue), queue, upper_lower, trans, unit_diag, n, k, a, lda, x, incx, dependencies); tbmv_postcondition(queue, upper_lower, trans, unit_diag, n, k, a, lda, x, incx, dependencies); return done; } static inline cl::sycl::event tbmv(cl::sycl::queue &queue, uplo upper_lower, transpose trans, diag unit_diag, std::int64_t n, std::int64_t k, const std::complex *a, std::int64_t lda, std::complex *x, std::int64_t incx, const std::vector &dependencies = {}) { tbmv_precondition(queue, upper_lower, trans, unit_diag, n, k, a, lda, x, incx, dependencies); auto done = detail::tbmv(get_device_id(queue), queue, upper_lower, trans, unit_diag, n, k, a, lda, x, incx, dependencies); tbmv_postcondition(queue, upper_lower, trans, unit_diag, n, k, a, lda, x, incx, dependencies); return done; } static inline cl::sycl::event tbmv(cl::sycl::queue &queue, uplo upper_lower, transpose trans, diag unit_diag, std::int64_t n, std::int64_t k, const std::complex *a, std::int64_t lda, std::complex *x, std::int64_t incx, const std::vector &dependencies = {}) { tbmv_precondition(queue, upper_lower, trans, unit_diag, n, k, a, lda, x, incx, dependencies); auto done = detail::tbmv(get_device_id(queue), queue, upper_lower, trans, unit_diag, n, k, a, lda, x, incx, dependencies); tbmv_postcondition(queue, upper_lower, trans, unit_diag, n, k, a, lda, x, incx, dependencies); return done; } static inline cl::sycl::event tbsv(cl::sycl::queue &queue, uplo upper_lower, transpose trans, diag unit_diag, std::int64_t n, std::int64_t k, const float *a, std::int64_t lda, float *x, std::int64_t incx, const std::vector &dependencies = {}) { tbsv_precondition(queue, upper_lower, trans, unit_diag, n, k, a, lda, x, incx, dependencies); auto done = detail::tbsv(get_device_id(queue), queue, upper_lower, trans, unit_diag, n, k, a, lda, x, incx, dependencies); tbsv_postcondition(queue, upper_lower, trans, unit_diag, n, k, a, lda, x, incx, dependencies); return done; } static inline cl::sycl::event tbsv(cl::sycl::queue &queue, uplo upper_lower, transpose trans, diag unit_diag, std::int64_t n, std::int64_t k, const double *a, std::int64_t lda, double *x, std::int64_t incx, const std::vector &dependencies = {}) { tbsv_precondition(queue, upper_lower, trans, unit_diag, n, k, a, lda, x, incx, dependencies); auto done = detail::tbsv(get_device_id(queue), queue, upper_lower, trans, unit_diag, n, k, a, lda, x, incx, dependencies); tbsv_postcondition(queue, upper_lower, trans, unit_diag, n, k, a, lda, x, incx, dependencies); return done; } static inline cl::sycl::event tbsv(cl::sycl::queue &queue, uplo upper_lower, transpose trans, diag unit_diag, std::int64_t n, std::int64_t k, const std::complex *a, std::int64_t lda, std::complex *x, std::int64_t incx, const std::vector &dependencies = {}) { tbsv_precondition(queue, upper_lower, trans, unit_diag, n, k, a, lda, x, incx, dependencies); auto done = detail::tbsv(get_device_id(queue), queue, upper_lower, trans, unit_diag, n, k, a, lda, x, incx, dependencies); tbsv_postcondition(queue, upper_lower, trans, unit_diag, n, k, a, lda, x, incx, dependencies); return done; } static inline cl::sycl::event tbsv(cl::sycl::queue &queue, uplo upper_lower, transpose trans, diag unit_diag, std::int64_t n, std::int64_t k, const std::complex *a, std::int64_t lda, std::complex *x, std::int64_t incx, const std::vector &dependencies = {}) { tbsv_precondition(queue, upper_lower, trans, unit_diag, n, k, a, lda, x, incx, dependencies); auto done = detail::tbsv(get_device_id(queue), queue, upper_lower, trans, unit_diag, n, k, a, lda, x, incx, dependencies); tbsv_postcondition(queue, upper_lower, trans, unit_diag, n, k, a, lda, x, incx, dependencies); return done; } static inline cl::sycl::event tpmv(cl::sycl::queue &queue, uplo upper_lower, transpose trans, diag unit_diag, std::int64_t n, const float *a, float *x, std::int64_t incx, const std::vector &dependencies = {}) { tpmv_precondition(queue, upper_lower, trans, unit_diag, n, a, x, incx, dependencies); auto done = detail::tpmv(get_device_id(queue), queue, upper_lower, trans, unit_diag, n, a, x, incx, dependencies); tpmv_postcondition(queue, upper_lower, trans, unit_diag, n, a, x, incx, dependencies); return done; } static inline cl::sycl::event tpmv(cl::sycl::queue &queue, uplo upper_lower, transpose trans, diag unit_diag, std::int64_t n, const double *a, double *x, std::int64_t incx, const std::vector &dependencies = {}) { tpmv_precondition(queue, upper_lower, trans, unit_diag, n, a, x, incx, dependencies); auto done = detail::tpmv(get_device_id(queue), queue, upper_lower, trans, unit_diag, n, a, x, incx, dependencies); tpmv_postcondition(queue, upper_lower, trans, unit_diag, n, a, x, incx, dependencies); return done; } static inline cl::sycl::event tpmv(cl::sycl::queue &queue, uplo upper_lower, transpose trans, diag unit_diag, std::int64_t n, const std::complex *a, std::complex *x, std::int64_t incx, const std::vector &dependencies = {}) { tpmv_precondition(queue, upper_lower, trans, unit_diag, n, a, x, incx, dependencies); auto done = detail::tpmv(get_device_id(queue), queue, upper_lower, trans, unit_diag, n, a, x, incx, dependencies); tpmv_postcondition(queue, upper_lower, trans, unit_diag, n, a, x, incx, dependencies); return done; } static inline cl::sycl::event tpmv(cl::sycl::queue &queue, uplo upper_lower, transpose trans, diag unit_diag, std::int64_t n, const std::complex *a, std::complex *x, std::int64_t incx, const std::vector &dependencies = {}) { tpmv_precondition(queue, upper_lower, trans, unit_diag, n, a, x, incx, dependencies); auto done = detail::tpmv(get_device_id(queue), queue, upper_lower, trans, unit_diag, n, a, x, incx, dependencies); tpmv_postcondition(queue, upper_lower, trans, unit_diag, n, a, x, incx, dependencies); return done; } static inline cl::sycl::event tpsv(cl::sycl::queue &queue, uplo upper_lower, transpose trans, diag unit_diag, std::int64_t n, const float *a, float *x, std::int64_t incx, const std::vector &dependencies = {}) { tpsv_precondition(queue, upper_lower, trans, unit_diag, n, a, x, incx, dependencies); auto done = detail::tpsv(get_device_id(queue), queue, upper_lower, trans, unit_diag, n, a, x, incx, dependencies); tpsv_postcondition(queue, upper_lower, trans, unit_diag, n, a, x, incx, dependencies); return done; } static inline cl::sycl::event tpsv(cl::sycl::queue &queue, uplo upper_lower, transpose trans, diag unit_diag, std::int64_t n, const double *a, double *x, std::int64_t incx, const std::vector &dependencies = {}) { tpsv_precondition(queue, upper_lower, trans, unit_diag, n, a, x, incx, dependencies); auto done = detail::tpsv(get_device_id(queue), queue, upper_lower, trans, unit_diag, n, a, x, incx, dependencies); tpsv_postcondition(queue, upper_lower, trans, unit_diag, n, a, x, incx, dependencies); return done; } static inline cl::sycl::event tpsv(cl::sycl::queue &queue, uplo upper_lower, transpose trans, diag unit_diag, std::int64_t n, const std::complex *a, std::complex *x, std::int64_t incx, const std::vector &dependencies = {}) { tpsv_precondition(queue, upper_lower, trans, unit_diag, n, a, x, incx, dependencies); auto done = detail::tpsv(get_device_id(queue), queue, upper_lower, trans, unit_diag, n, a, x, incx, dependencies); tpsv_postcondition(queue, upper_lower, trans, unit_diag, n, a, x, incx, dependencies); return done; } static inline cl::sycl::event tpsv(cl::sycl::queue &queue, uplo upper_lower, transpose trans, diag unit_diag, std::int64_t n, const std::complex *a, std::complex *x, std::int64_t incx, const std::vector &dependencies = {}) { tpsv_precondition(queue, upper_lower, trans, unit_diag, n, a, x, incx, dependencies); auto done = detail::tpsv(get_device_id(queue), queue, upper_lower, trans, unit_diag, n, a, x, incx, dependencies); tpsv_postcondition(queue, upper_lower, trans, unit_diag, n, a, x, incx, dependencies); return done; } static inline cl::sycl::event trmm(cl::sycl::queue &queue, side left_right, uplo upper_lower, transpose trans, diag unit_diag, std::int64_t m, std::int64_t n, float alpha, const float *a, std::int64_t lda, float *b, std::int64_t ldb, const std::vector &dependencies = {}) { trmm_precondition(queue, left_right, upper_lower, trans, unit_diag, m, n, alpha, a, lda, b, ldb, dependencies); auto done = detail::trmm(get_device_id(queue), queue, left_right, upper_lower, trans, unit_diag, m, n, alpha, a, lda, b, ldb, dependencies); trmm_postcondition(queue, left_right, upper_lower, trans, unit_diag, m, n, alpha, a, lda, b, ldb, dependencies); return done; } static inline cl::sycl::event trmm(cl::sycl::queue &queue, side left_right, uplo upper_lower, transpose trans, diag unit_diag, std::int64_t m, std::int64_t n, double alpha, const double *a, std::int64_t lda, double *b, std::int64_t ldb, const std::vector &dependencies = {}) { trmm_precondition(queue, left_right, upper_lower, trans, unit_diag, m, n, alpha, a, lda, b, ldb, dependencies); auto done = detail::trmm(get_device_id(queue), queue, left_right, upper_lower, trans, unit_diag, m, n, alpha, a, lda, b, ldb, dependencies); trmm_postcondition(queue, left_right, upper_lower, trans, unit_diag, m, n, alpha, a, lda, b, ldb, dependencies); return done; } static inline cl::sycl::event trmm(cl::sycl::queue &queue, side left_right, uplo upper_lower, transpose trans, diag unit_diag, std::int64_t m, std::int64_t n, std::complex alpha, const std::complex *a, std::int64_t lda, std::complex *b, std::int64_t ldb, const std::vector &dependencies = {}) { trmm_precondition(queue, left_right, upper_lower, trans, unit_diag, m, n, alpha, a, lda, b, ldb, dependencies); auto done = detail::trmm(get_device_id(queue), queue, left_right, upper_lower, trans, unit_diag, m, n, alpha, a, lda, b, ldb, dependencies); trmm_postcondition(queue, left_right, upper_lower, trans, unit_diag, m, n, alpha, a, lda, b, ldb, dependencies); return done; } static inline cl::sycl::event trmm(cl::sycl::queue &queue, side left_right, uplo upper_lower, transpose trans, diag unit_diag, std::int64_t m, std::int64_t n, std::complex alpha, const std::complex *a, std::int64_t lda, std::complex *b, std::int64_t ldb, const std::vector &dependencies = {}) { trmm_precondition(queue, left_right, upper_lower, trans, unit_diag, m, n, alpha, a, lda, b, ldb, dependencies); auto done = detail::trmm(get_device_id(queue), queue, left_right, upper_lower, trans, unit_diag, m, n, alpha, a, lda, b, ldb, dependencies); trmm_postcondition(queue, left_right, upper_lower, trans, unit_diag, m, n, alpha, a, lda, b, ldb, dependencies); return done; } static inline cl::sycl::event trmv(cl::sycl::queue &queue, uplo upper_lower, transpose trans, diag unit_diag, std::int64_t n, const float *a, std::int64_t lda, float *x, std::int64_t incx, const std::vector &dependencies = {}) { trmv_precondition(queue, upper_lower, trans, unit_diag, n, a, lda, x, incx, dependencies); auto done = detail::trmv(get_device_id(queue), queue, upper_lower, trans, unit_diag, n, a, lda, x, incx, dependencies); trmv_postcondition(queue, upper_lower, trans, unit_diag, n, a, lda, x, incx, dependencies); return done; } static inline cl::sycl::event trmv(cl::sycl::queue &queue, uplo upper_lower, transpose trans, diag unit_diag, std::int64_t n, const double *a, std::int64_t lda, double *x, std::int64_t incx, const std::vector &dependencies = {}) { trmv_precondition(queue, upper_lower, trans, unit_diag, n, a, lda, x, incx, dependencies); auto done = detail::trmv(get_device_id(queue), queue, upper_lower, trans, unit_diag, n, a, lda, x, incx, dependencies); trmv_postcondition(queue, upper_lower, trans, unit_diag, n, a, lda, x, incx, dependencies); return done; } static inline cl::sycl::event trmv(cl::sycl::queue &queue, uplo upper_lower, transpose trans, diag unit_diag, std::int64_t n, const std::complex *a, std::int64_t lda, std::complex *x, std::int64_t incx, const std::vector &dependencies = {}) { trmv_precondition(queue, upper_lower, trans, unit_diag, n, a, lda, x, incx, dependencies); auto done = detail::trmv(get_device_id(queue), queue, upper_lower, trans, unit_diag, n, a, lda, x, incx, dependencies); trmv_postcondition(queue, upper_lower, trans, unit_diag, n, a, lda, x, incx, dependencies); return done; } static inline cl::sycl::event trmv(cl::sycl::queue &queue, uplo upper_lower, transpose trans, diag unit_diag, std::int64_t n, const std::complex *a, std::int64_t lda, std::complex *x, std::int64_t incx, const std::vector &dependencies = {}) { trmv_precondition(queue, upper_lower, trans, unit_diag, n, a, lda, x, incx, dependencies); auto done = detail::trmv(get_device_id(queue), queue, upper_lower, trans, unit_diag, n, a, lda, x, incx, dependencies); trmv_postcondition(queue, upper_lower, trans, unit_diag, n, a, lda, x, incx, dependencies); return done; } static inline cl::sycl::event trsm(cl::sycl::queue &queue, side left_right, uplo upper_lower, transpose trans, diag unit_diag, std::int64_t m, std::int64_t n, float alpha, const float *a, std::int64_t lda, float *b, std::int64_t ldb, const std::vector &dependencies = {}) { trsm_precondition(queue, left_right, upper_lower, trans, unit_diag, m, n, alpha, a, lda, b, ldb, dependencies); auto done = detail::trsm(get_device_id(queue), queue, left_right, upper_lower, trans, unit_diag, m, n, alpha, a, lda, b, ldb, dependencies); trsm_postcondition(queue, left_right, upper_lower, trans, unit_diag, m, n, alpha, a, lda, b, ldb, dependencies); return done; } static inline cl::sycl::event trsm(cl::sycl::queue &queue, side left_right, uplo upper_lower, transpose trans, diag unit_diag, std::int64_t m, std::int64_t n, double alpha, const double *a, std::int64_t lda, double *b, std::int64_t ldb, const std::vector &dependencies = {}) { trsm_precondition(queue, left_right, upper_lower, trans, unit_diag, m, n, alpha, a, lda, b, ldb, dependencies); auto done = detail::trsm(get_device_id(queue), queue, left_right, upper_lower, trans, unit_diag, m, n, alpha, a, lda, b, ldb, dependencies); trsm_postcondition(queue, left_right, upper_lower, trans, unit_diag, m, n, alpha, a, lda, b, ldb, dependencies); return done; } static inline cl::sycl::event trsm(cl::sycl::queue &queue, side left_right, uplo upper_lower, transpose trans, diag unit_diag, std::int64_t m, std::int64_t n, std::complex alpha, const std::complex *a, std::int64_t lda, std::complex *b, std::int64_t ldb, const std::vector &dependencies = {}) { trsm_precondition(queue, left_right, upper_lower, trans, unit_diag, m, n, alpha, a, lda, b, ldb, dependencies); auto done = detail::trsm(get_device_id(queue), queue, left_right, upper_lower, trans, unit_diag, m, n, alpha, a, lda, b, ldb, dependencies); trsm_postcondition(queue, left_right, upper_lower, trans, unit_diag, m, n, alpha, a, lda, b, ldb, dependencies); return done; } static inline cl::sycl::event trsm(cl::sycl::queue &queue, side left_right, uplo upper_lower, transpose trans, diag unit_diag, std::int64_t m, std::int64_t n, std::complex alpha, const std::complex *a, std::int64_t lda, std::complex *b, std::int64_t ldb, const std::vector &dependencies = {}) { trsm_precondition(queue, left_right, upper_lower, trans, unit_diag, m, n, alpha, a, lda, b, ldb, dependencies); auto done = detail::trsm(get_device_id(queue), queue, left_right, upper_lower, trans, unit_diag, m, n, alpha, a, lda, b, ldb, dependencies); trsm_postcondition(queue, left_right, upper_lower, trans, unit_diag, m, n, alpha, a, lda, b, ldb, dependencies); return done; } static inline cl::sycl::event trsm_batch(cl::sycl::queue &queue, side left_right, uplo upper_lower, transpose trans, diag unit_diag, std::int64_t m, std::int64_t n, float alpha, const float *a, std::int64_t lda, std::int64_t stride_a, float *b, std::int64_t ldb, std::int64_t stride_b, std::int64_t batch_size, const std::vector &dependencies = {}) { trsm_batch_precondition(queue, left_right, upper_lower, trans, unit_diag, m, n, alpha, a, lda, stride_a, b, ldb, stride_b, batch_size, dependencies); auto done = detail::trsm_batch(get_device_id(queue), queue, left_right, upper_lower, trans, unit_diag, m, n, alpha, a, lda, stride_a, b, ldb, stride_b, batch_size, dependencies); trsm_batch_postcondition(queue, left_right, upper_lower, trans, unit_diag, m, n, alpha, a, lda, stride_a, b, ldb, stride_b, batch_size, dependencies); return done; } static inline cl::sycl::event trsm_batch(cl::sycl::queue &queue, side left_right, uplo upper_lower, transpose trans, diag unit_diag, std::int64_t m, std::int64_t n, double alpha, const double *a, std::int64_t lda, std::int64_t stride_a, double *b, std::int64_t ldb, std::int64_t stride_b, std::int64_t batch_size, const std::vector &dependencies = {}) { trsm_batch_precondition(queue, left_right, upper_lower, trans, unit_diag, m, n, alpha, a, lda, stride_a, b, ldb, stride_b, batch_size, dependencies); auto done = detail::trsm_batch(get_device_id(queue), queue, left_right, upper_lower, trans, unit_diag, m, n, alpha, a, lda, stride_a, b, ldb, stride_b, batch_size, dependencies); trsm_batch_postcondition(queue, left_right, upper_lower, trans, unit_diag, m, n, alpha, a, lda, stride_a, b, ldb, stride_b, batch_size, dependencies); return done; } static inline cl::sycl::event trsm_batch(cl::sycl::queue &queue, side left_right, uplo upper_lower, transpose trans, diag unit_diag, std::int64_t m, std::int64_t n, std::complex alpha, const std::complex *a, std::int64_t lda, std::int64_t stride_a, std::complex *b, std::int64_t ldb, std::int64_t stride_b, std::int64_t batch_size, const std::vector &dependencies = {}) { trsm_batch_precondition(queue, left_right, upper_lower, trans, unit_diag, m, n, alpha, a, lda, stride_a, b, ldb, stride_b, batch_size, dependencies); auto done = detail::trsm_batch(get_device_id(queue), queue, left_right, upper_lower, trans, unit_diag, m, n, alpha, a, lda, stride_a, b, ldb, stride_b, batch_size, dependencies); trsm_batch_postcondition(queue, left_right, upper_lower, trans, unit_diag, m, n, alpha, a, lda, stride_a, b, ldb, stride_b, batch_size, dependencies); return done; } static inline cl::sycl::event trsm_batch(cl::sycl::queue &queue, side left_right, uplo upper_lower, transpose trans, diag unit_diag, std::int64_t m, std::int64_t n, std::complex alpha, const std::complex *a, std::int64_t lda, std::int64_t stride_a, std::complex *b, std::int64_t ldb, std::int64_t stride_b, std::int64_t batch_size, const std::vector &dependencies = {}) { trsm_batch_precondition(queue, left_right, upper_lower, trans, unit_diag, m, n, alpha, a, lda, stride_a, b, ldb, stride_b, batch_size, dependencies); auto done = detail::trsm_batch(get_device_id(queue), queue, left_right, upper_lower, trans, unit_diag, m, n, alpha, a, lda, stride_a, b, ldb, stride_b, batch_size, dependencies); trsm_batch_postcondition(queue, left_right, upper_lower, trans, unit_diag, m, n, alpha, a, lda, stride_a, b, ldb, stride_b, batch_size, dependencies); return done; } static inline cl::sycl::event trsm_batch(cl::sycl::queue &queue, side *left_right, uplo *upper_lower, transpose *trans, diag *unit_diag, std::int64_t *m, std::int64_t *n, float *alpha, const float **a, std::int64_t *lda, float **b, std::int64_t *ldb, std::int64_t group_count, std::int64_t *group_size, const std::vector &dependencies = {}) { trsm_batch_precondition(queue, left_right, upper_lower, trans, unit_diag, m, n, alpha, a, lda, b, ldb, group_count, group_size, dependencies); auto done = detail::trsm_batch(get_device_id(queue), queue, left_right, upper_lower, trans, unit_diag, m, n, alpha, a, lda, b, ldb, group_count, group_size, dependencies); trsm_batch_postcondition(queue, left_right, upper_lower, trans, unit_diag, m, n, alpha, a, lda, b, ldb, group_count, group_size, dependencies); return done; } static inline cl::sycl::event trsm_batch(cl::sycl::queue &queue, side *left_right, uplo *upper_lower, transpose *trans, diag *unit_diag, std::int64_t *m, std::int64_t *n, double *alpha, const double **a, std::int64_t *lda, double **b, std::int64_t *ldb, std::int64_t group_count, std::int64_t *group_size, const std::vector &dependencies = {}) { trsm_batch_precondition(queue, left_right, upper_lower, trans, unit_diag, m, n, alpha, a, lda, b, ldb, group_count, group_size, dependencies); auto done = detail::trsm_batch(get_device_id(queue), queue, left_right, upper_lower, trans, unit_diag, m, n, alpha, a, lda, b, ldb, group_count, group_size, dependencies); trsm_batch_postcondition(queue, left_right, upper_lower, trans, unit_diag, m, n, alpha, a, lda, b, ldb, group_count, group_size, dependencies); return done; } static inline cl::sycl::event trsm_batch( cl::sycl::queue &queue, side *left_right, uplo *upper_lower, transpose *trans, diag *unit_diag, std::int64_t *m, std::int64_t *n, std::complex *alpha, const std::complex **a, std::int64_t *lda, std::complex **b, std::int64_t *ldb, std::int64_t group_count, std::int64_t *group_size, const std::vector &dependencies = {}) { trsm_batch_precondition(queue, left_right, upper_lower, trans, unit_diag, m, n, alpha, a, lda, b, ldb, group_count, group_size, dependencies); auto done = detail::trsm_batch(get_device_id(queue), queue, left_right, upper_lower, trans, unit_diag, m, n, alpha, a, lda, b, ldb, group_count, group_size, dependencies); trsm_batch_postcondition(queue, left_right, upper_lower, trans, unit_diag, m, n, alpha, a, lda, b, ldb, group_count, group_size, dependencies); return done; } static inline cl::sycl::event trsm_batch( cl::sycl::queue &queue, side *left_right, uplo *upper_lower, transpose *trans, diag *unit_diag, std::int64_t *m, std::int64_t *n, std::complex *alpha, const std::complex **a, std::int64_t *lda, std::complex **b, std::int64_t *ldb, std::int64_t group_count, std::int64_t *group_size, const std::vector &dependencies = {}) { trsm_batch_precondition(queue, left_right, upper_lower, trans, unit_diag, m, n, alpha, a, lda, b, ldb, group_count, group_size, dependencies); auto done = detail::trsm_batch(get_device_id(queue), queue, left_right, upper_lower, trans, unit_diag, m, n, alpha, a, lda, b, ldb, group_count, group_size, dependencies); trsm_batch_postcondition(queue, left_right, upper_lower, trans, unit_diag, m, n, alpha, a, lda, b, ldb, group_count, group_size, dependencies); return done; } static inline cl::sycl::event trsv(cl::sycl::queue &queue, uplo upper_lower, transpose trans, diag unit_diag, std::int64_t n, const float *a, std::int64_t lda, float *x, std::int64_t incx, const std::vector &dependencies = {}) { trsv_precondition(queue, upper_lower, trans, unit_diag, n, a, lda, x, incx, dependencies); auto done = detail::trsv(get_device_id(queue), queue, upper_lower, trans, unit_diag, n, a, lda, x, incx, dependencies); trsv_postcondition(queue, upper_lower, trans, unit_diag, n, a, lda, x, incx, dependencies); return done; } static inline cl::sycl::event trsv(cl::sycl::queue &queue, uplo upper_lower, transpose trans, diag unit_diag, std::int64_t n, const double *a, std::int64_t lda, double *x, std::int64_t incx, const std::vector &dependencies = {}) { trsv_precondition(queue, upper_lower, trans, unit_diag, n, a, lda, x, incx, dependencies); auto done = detail::trsv(get_device_id(queue), queue, upper_lower, trans, unit_diag, n, a, lda, x, incx, dependencies); trsv_postcondition(queue, upper_lower, trans, unit_diag, n, a, lda, x, incx, dependencies); return done; } static inline cl::sycl::event trsv(cl::sycl::queue &queue, uplo upper_lower, transpose trans, diag unit_diag, std::int64_t n, const std::complex *a, std::int64_t lda, std::complex *x, std::int64_t incx, const std::vector &dependencies = {}) { trsv_precondition(queue, upper_lower, trans, unit_diag, n, a, lda, x, incx, dependencies); auto done = detail::trsv(get_device_id(queue), queue, upper_lower, trans, unit_diag, n, a, lda, x, incx, dependencies); trsv_postcondition(queue, upper_lower, trans, unit_diag, n, a, lda, x, incx, dependencies); return done; } static inline cl::sycl::event trsv(cl::sycl::queue &queue, uplo upper_lower, transpose trans, diag unit_diag, std::int64_t n, const std::complex *a, std::int64_t lda, std::complex *x, std::int64_t incx, const std::vector &dependencies = {}) { trsv_precondition(queue, upper_lower, trans, unit_diag, n, a, lda, x, incx, dependencies); auto done = detail::trsv(get_device_id(queue), queue, upper_lower, trans, unit_diag, n, a, lda, x, incx, dependencies); trsv_postcondition(queue, upper_lower, trans, unit_diag, n, a, lda, x, incx, dependencies); return done; } include/ext/iostreams/utility.hpp #pragma once #include #include #include namespace ext::iostreams { namespace iostreams_detail { template > struct has_category : std::false_type {}; template struct has_category> : std::true_type {}; template > struct has_char_type : std::false_type {}; template struct has_char_type> : std::true_type {}; } template struct is_boost_iostreams_device : std::conjunction< iostreams_detail::has_category, iostreams_detail::has_char_type > {}; // either std::*stream or boost::iostreams::device template struct is_device : std::disjunction< std::is_base_of, is_boost_iostreams_device > {}; template constexpr auto is_device_v = is_device::value; template void write_all(Sink & sink, const typename boost::iostreams::char_type_of::type * s, std::streamsize n) { //boost::iostreams::write(sink, s, n); do { auto res = boost::iostreams::write(sink, s, n); if (res < 0) throw std::runtime_error("failed to write to underline sink"); s += static_cast(res); n -= res; } while (n); } template void write_all(T & t, Sink & sink, const typename boost::iostreams::char_type_of::type * s, std::streamsize n) { //boost::iostreams::write(t, sink, s, n); do { auto res = boost::iostreams::write(t, sink, s, n); if (res < 0) throw std::runtime_error("failed to write to underline sink"); s += static_cast(res); n -= res; } while (n); } template inline void write_string(Sink & sink, const String & str) { auto str_lit = ext::str_view(str); auto * ptr = ext::data(str_lit); auto len = static_cast(str_lit.size()); write_all(sink, ptr, len); } } /** * @file blend_state.hpp * * @brief BlendState クラスの定義 * * @author myoukaku */ #ifndef BKSGE_CORE_RENDER_GL_DETAIL_BLEND_STATE_HPP #define BKSGE_CORE_RENDER_GL_DETAIL_BLEND_STATE_HPP #include namespace bksge { namespace render { namespace gl { class BlendState { public: static void Apply(bksge::BlendState const& state); }; } // namespace gl } // namespace render } // namespace bksge #include #if defined(BKSGE_HEADER_ONLY) #include #endif #endif // BKSGE_CORE_RENDER_GL_DETAIL_BLEND_STATE_HPP SoulWorkerResearch/swp-loader1-10 // local #include "../headers/exports.hpp" // deps #include namespace lua100 { void lua_atprint([[maybe_unused]] lua_State* _state, [[maybe_unused]] uintptr_t _unk_ptr) { spdlog::warn("lua_atprint called"); } } // https://youtu.be/SdxsT40DaCg?list=PLJ4jpRq1tGIlNAo3AblOFj9ovgfyp0xQQ 100-1000 // Copyright 2020-2022 OpenDR European 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 "gmapping/gridfastslam/gfsreader.h" #include #include #include namespace GMapping { namespace GFSReader { Record::~Record() {} void Record::write(ostream &os){}; void CommentRecord::read(istream &is) { char buf[MAX_LINE_LENGHT]; memset(buf, 0, MAX_LINE_LENGHT * sizeof(char)); is.getline(buf, MAX_LINE_LENGHT); text = string(buf); } void CommentRecord::write(ostream &os) { os << "#GFS_COMMENT: " << text << endl; } PoseRecord::PoseRecord(bool ideal) { truePos = ideal; } void PoseRecord::read(istream &is) { is >> pose.x >> pose.y >> pose.theta; time = 0; if (is) is >> time; } void PoseRecord::write(ostream &os) { if (truePos) os << "TRUEPOS "; else os << "ODOM "; os << setiosflags(ios::fixed) << setprecision(6); os << pose.x << " " << pose.y << " " << pose.theta << " 0 0 0 "; os << time << " pippo " << time << endl; } void NeffRecord::read(istream &is) { is >> neff; time = 0; if (is) is >> time; } void NeffRecord::write(ostream &os) { os << "NEFF " << neff; os << setiosflags(ios::fixed) << setprecision(6); os << " " << time << " pippo " << time << endl; } void OdometryRecord::read(istream &is) { is >> dim; for (unsigned int i = 0; i < dim; i++) { OrientedPoint p; double w; is >> p.x; is >> p.y; is >> p.theta; is >> w; poses.push_back(p); } time = 0; if (is) is >> time; } void RawOdometryRecord::read(istream &is) { is >> pose.x; is >> pose.y; is >> pose.theta; time = 0; assert(is); is >> time; } void EntropyRecord::read(istream &is) { is >> poseEntropy >> trajectoryEntropy >> mapEntropy; time = 0; if (is) is >> time; } void EntropyRecord::write(ostream &os) { os << setiosflags(ios::fixed) << setprecision(6) << "ENTROPY " << poseEntropy << " " << trajectoryEntropy << " " << mapEntropy; os << " " << time << " pippo " << time << endl; } void ScanMatchRecord::read(istream &is) { is >> dim; for (unsigned int i = 0; i < dim; i++) { OrientedPoint p; double w; is >> p.x; is >> p.y; is >> p.theta; is >> w; poses.push_back(p); weights.push_back(w); } } void LaserRecord::read(istream &is) { is >> dim; for (unsigned int i = 0; i < dim; i++) { double r; is >> r; readings.push_back(r); } is >> pose.x; is >> pose.y; is >> pose.theta; time = 0; if (is) is >> time; } void LaserRecord::write(ostream &os) { os << "WEIGHT " << weight << endl; os << "ROBOTLASER1 "; if ((dim == 541) || (dim == 540)) { // S300 os << " 4"; // laser type os << " -2.351831"; // start_angle os << " 4.712389"; // fov os << " 0.008727"; // angular res os << " 30.0"; // maxrange } else if ((dim == 180) || (dim == 181)) { // PLS os << " 0"; // laser type os << " -1.570796"; // start_angle os << " 3.141593"; // fov os << " 0.017453"; // angular res os << " 81.9"; // maxrange } else if ((dim == 360) || (dim == 361)) { // LMS os << " 0"; // laser type os << " -1.570796"; // start_angle os << " 3.141593"; // fov os << " 0.008726"; // angular res os << " 81.9"; // maxrange } else if ((dim == 682) || (dim == 683)) { // URG os << " 0"; // laser type os << " -2.094395"; // start_angle os << " 4.1887902"; // fov os << " " << 360.0 / 1024.0 / 180.0 * M_PI; // angular res os << " 5.5"; // maxrange } else { // PLS os << " 0"; // laser type os << " -1.570796"; // start_angle os << " 3.141593"; // fov os << " 0.017453"; // angular res os << " 81.9"; // maxrange } os << " 0.01"; // accuracy os << " 0"; // remission mode os << " " << dim; // num readings os << setiosflags(ios::fixed) << setprecision(2); for (unsigned int i = 0; i < dim; i++) { os << " " << readings[i]; } os << setiosflags(ios::fixed) << setprecision(6); os << " 0"; // num remession values os << " " << pose.x; os << " " << pose.y; os << " " << pose.theta; os << " " << pose.x; os << " " << pose.y; os << " " << pose.theta; os << " 0"; // tv os << " 0"; // rv os << " 0.55"; // forward_safety_dist os << " 0.375"; // sideward_safety_dist os << " 1000000.0"; // turn_axis os << " " << time << " localhost " << time << endl; }; void ResampleRecord::read(istream &is) { is >> dim; for (unsigned int i = 0; i < dim; i++) { unsigned int j; is >> j; indexes.push_back(j); } } istream &RecordList::read(istream &is) { while (is) { char buf[MAX_LINE_LENGHT]; is.getline(buf, MAX_LINE_LENGHT); istringstream lineStream(buf); string recordType; lineStream >> recordType; Record *rec = 0; if (recordType == "LASER_READING") { rec = new LaserRecord; // cout << "l" << flush; } else if (recordType == "ODO_UPDATE") { rec = new OdometryRecord; // cout << "o" << flush; } else if (recordType == "ODOM") { rec = new RawOdometryRecord; // cout << "O" << flush; } else if (recordType == "SM_UPDATE") { rec = new ScanMatchRecord; // cout << "m" << flush; } else if (recordType == "SIMULATOR_POS") { rec = new PoseRecord(true); // cout << "t" << flush; } else if (recordType == "RESAMPLE") { rec = new ResampleRecord; // cout << "r" << flush; } else if (recordType == "NEFF") { rec = new NeffRecord; // cout << "n" << flush; } else if (recordType == "COMMENT" || recordType == "#COMMENT") { rec = new CommentRecord; // cout << "c" << flush; } else if (recordType == "ENTROPY") { rec = new EntropyRecord; // cout << "c" << flush; } if (rec) { rec->read(lineStream); push_back(rec); } } return is; } double RecordList::getLogWeight(unsigned int i) const { double weight = 0; unsigned int currentIndex = i; for (RecordList::const_reverse_iterator it = rbegin(); it != rend(); it++) { ScanMatchRecord *scanmatch = dynamic_cast(*it); if (scanmatch) { weight += scanmatch->weights[currentIndex]; } ResampleRecord *resample = dynamic_cast(*it); if (resample) { currentIndex = resample->indexes[currentIndex]; } } return weight; } double RecordList::getLogWeight(unsigned int i, RecordList::const_iterator frame) const { double weight = 0; unsigned int currentIndex = i; for (RecordList::const_reverse_iterator it(frame); it != rend(); it++) { ScanMatchRecord *scanmatch = dynamic_cast(*it); if (scanmatch) { weight += scanmatch->weights[currentIndex]; } ResampleRecord *resample = dynamic_cast(*it); if (resample) { currentIndex = resample->indexes[currentIndex]; } } return weight; } unsigned int RecordList::getBestIdx() const { if (empty()) return 0; const ScanMatchRecord *scanmatch = 0; const_reverse_iterator it = rbegin(); while (!scanmatch) { scanmatch = dynamic_cast(*it); it++; } unsigned int dim = scanmatch->dim; sampleSize = (int)dim; double bestw = -std::numeric_limits::max(); unsigned int best = scanmatch->dim + 1; for (unsigned i = 0; i < dim; i++) { double w = getLogWeight(i); if (w > bestw) { best = i; bestw = w; } } return best; } void RecordList::printLastParticles(ostream &os) const { if (empty()) return; const ScanMatchRecord *scanmatch = 0; const_reverse_iterator it = rbegin(); while (!scanmatch) { scanmatch = dynamic_cast(*it); it++; } if (!scanmatch) return; for (vector::const_iterator it = scanmatch->poses.begin(); it != scanmatch->poses.end(); it++) { os << "MARKER [color=black; circle=" << it->x * 100 << "," << it->y * 100 << ",10] 0 pippo 0" << endl; } } void RecordList::destroyReferences() { for (RecordList::iterator it = begin(); it != end(); it++) delete (*it); } RecordList RecordList::computePath(unsigned int i, RecordList::const_iterator frame) const { unsigned int currentIndex = i; OrientedPoint p(0, 0, 0); RecordList rl; // reconstruct a path bool first = true; for (RecordList::const_reverse_iterator it(frame); it != rend(); it++) { const ScanMatchRecord *scanmatch = dynamic_cast(*it); if (scanmatch) { p = scanmatch->poses[currentIndex]; first = false; } const LaserRecord *laser = dynamic_cast(*it); if (laser && !first) { LaserRecord *claser = new LaserRecord(*laser); claser->pose = p; rl.push_front(claser); } const ResampleRecord *resample = dynamic_cast(*it); if (resample) { currentIndex = resample->indexes[currentIndex]; } } return rl; } void RecordList::printPath(ostream &os, unsigned int i, bool err, bool rawodom) const { unsigned int currentIndex = i; OrientedPoint p(0, 0, 0); RecordList rl; double oldWeight = 0; double w = 0; // reconstruct a path for (RecordList::const_reverse_iterator it = rbegin(); it != rend(); it++) { const NeffRecord *neff = dynamic_cast(*it); if (neff) { NeffRecord *n = new NeffRecord(*neff); rl.push_front(n); } const EntropyRecord *entropy = dynamic_cast(*it); if (entropy) { EntropyRecord *n = new EntropyRecord(*entropy); rl.push_front(n); } const ScanMatchRecord *scanmatch = dynamic_cast(*it); if (scanmatch) { PoseRecord *pose = new PoseRecord; pose->dim = 0; p = pose->pose = scanmatch->poses[currentIndex]; w = scanmatch->weights[currentIndex] - oldWeight; oldWeight = scanmatch->weights[currentIndex]; if (!rawodom) { rl.push_front(pose); } } const OdometryRecord *odometry = dynamic_cast(*it); if (odometry) { PoseRecord *pose = new PoseRecord; pose->dim = 0; p = pose->pose = odometry->poses[currentIndex]; pose->time = odometry->time; if (!rawodom) { rl.push_front(pose); } } const RawOdometryRecord *rawodometry = dynamic_cast(*it); if (rawodometry) { PoseRecord *pose = new PoseRecord; pose->dim = 0; pose->pose = rawodometry->pose; pose->time = rawodometry->time; if (rawodom) { rl.push_front(pose); } } const PoseRecord *tpose = dynamic_cast(*it); if (tpose) { PoseRecord *pose = new PoseRecord(*tpose); rl.push_front(pose); } const LaserRecord *laser = dynamic_cast(*it); if (laser) { LaserRecord *claser = new LaserRecord(*laser); claser->pose = p; claser->weight = w; rl.push_front(claser); } const CommentRecord *comment = dynamic_cast(*it); if (comment) { CommentRecord *ccomment = new CommentRecord(*comment); rl.push_front(ccomment); } const ResampleRecord *resample = dynamic_cast(*it); if (resample) { rl.push_front(new ResampleRecord(*resample)); currentIndex = resample->indexes[currentIndex]; } } bool started = false; bool computedTransformation = false; bool truePosFound = false; OrientedPoint truePose; OrientedPoint oldPose; OrientedPoint trueStart, realStart; bool tpf = false; double neff = 0; double totalError = 0; int count = 0; for (RecordList::iterator it = rl.begin(); it != rl.end(); it++) { NeffRecord *neffr = dynamic_cast(*it); if (neffr) neff = neffr->neff / (double)sampleSize; started = started || dynamic_cast(*it) ? true : false; if (started && !truePosFound) { PoseRecord *tpose = dynamic_cast(*it); if (tpose && tpose->truePos) { truePosFound = true; tpf = true; truePose = tpose->pose; os << "# "; (*it)->write(os); } } if (started && truePosFound && !computedTransformation) { PoseRecord *pos = dynamic_cast(*it); if (pos && !pos->truePos) { trueStart = truePose; realStart = pos->pose; os << "# "; (*it)->write(os); computedTransformation = true; } } if (computedTransformation) { os << setiosflags(ios::fixed) << setprecision(6); PoseRecord *pos = dynamic_cast(*it); if (pos) { if (pos->truePos) { tpf = true; truePose = pos->pose; } else { if (tpf) { tpf = false; OrientedPoint realDelta = absoluteDifference(pos->pose, realStart); OrientedPoint trueDelta = absoluteDifference(truePose, trueStart); double ex = realDelta.x - trueDelta.x; double ey = realDelta.y - trueDelta.y; double eth = realDelta.theta - trueDelta.theta; eth = atan2(sin(eth), cos(eth)); if (!err) os << "# ERROR "; os << neff << " " << ex << " " << ey << " " << eth << " " << sqrt(ex * ex + ey * ey) << " " << fabs(eth) << endl; totalError += sqrt(ex * ex + ey * ey); count++; } } } } PoseRecord *pos = dynamic_cast(*it); if (pos) oldPose = pos->pose; if (!err) (*it)->write(os); delete *it; } if (err) cout << "average error" << totalError / count << endl; } }; // namespace GFSReader }; // namespace GMapping 1-10 /* antimicro Gamepad to KB+M event mapper * Copyright (C) 2015 <> * * 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 . */ //#include #include #include "joyaxisbutton.h" #include "joyaxis.h" #include "event.h" const QString JoyAxisButton::xmlName = "axisbutton"; JoyAxisButton::JoyAxisButton(JoyAxis *axis, int index, int originset, SetJoystick *parentSet, QObject *parent) : JoyGradientButton(index, originset, parentSet, parent) { this->axis = axis; } QString JoyAxisButton::getPartialName(bool forceFullFormat, bool displayNames) { QString temp = QString(axis->getPartialName(forceFullFormat, displayNames)); temp.append(": "); if (!buttonName.isEmpty() && displayNames) { if (forceFullFormat) { temp.append(tr("Button")).append(" "); } temp.append(buttonName); } else if (!defaultButtonName.isEmpty() && displayNames) { if (forceFullFormat) { temp.append(tr("Button")).append(" "); } temp.append(defaultButtonName); } else { QString buttontype; if (index == 0) { buttontype = tr("Negative"); } else if (index == 1) { buttontype = tr("Positive"); } else { buttontype = tr("Unknown"); } temp.append(tr("Button")).append(" ").append(buttontype); } return temp; } QString JoyAxisButton::getXmlName() { return this->xmlName; } void JoyAxisButton::setChangeSetCondition(SetChangeCondition condition, bool passive, bool updateActiveString) { SetChangeCondition oldCondition = setSelectionCondition; if (condition != setSelectionCondition && !passive) { if (condition == SetChangeWhileHeld || condition == SetChangeTwoWay) { // Set new condition emit setAssignmentChanged(index, this->axis->getIndex(), setSelection, condition); } else if (setSelectionCondition == SetChangeWhileHeld || setSelectionCondition == SetChangeTwoWay) { // Remove old condition emit setAssignmentChanged(index, this->axis->getIndex(), setSelection, SetChangeDisabled); } setSelectionCondition = condition; } else if (passive) { setSelectionCondition = condition; } if (setSelectionCondition == SetChangeDisabled) { setChangeSetSelection(-1); } if (setSelectionCondition != oldCondition) { if (updateActiveString) { buildActiveZoneSummaryString(); } emit propertyUpdated(); } } /** * @brief Get the distance that an element is away from its assigned * dead zone * @return Normalized distance away from dead zone */ double JoyAxisButton::getDistanceFromDeadZone() { return axis->getDistanceFromDeadZone(); } /** * @brief Get the distance factor that should be used for mouse movement * @return Distance factor that should be used for mouse movement */ double JoyAxisButton::getMouseDistanceFromDeadZone() { return this->getDistanceFromDeadZone(); } void JoyAxisButton::setVDPad(VDPad *vdpad) { if (axis->isPartControlStick()) { axis->removeControlStick(); } JoyButton::setVDPad(vdpad); } JoyAxis* JoyAxisButton::getAxis() { return this->axis; } /** * @brief Set the turbo mode that the button should use * @param Mode that should be used */ void JoyAxisButton::setTurboMode(TurboMode mode) { if (isPartRealAxis()) { currentTurboMode = mode; } } /** * @brief Check if button should be considered a part of a real controller * axis. Needed for some dialogs so the program won't have to resort to * type checking. * @return Status of being part of a real controller axis */ bool JoyAxisButton::isPartRealAxis() { return true; } double JoyAxisButton::getAccelerationDistance() { double distance = 0.0; distance = axis->getRawDistance(axis->getCurrentThrottledValue()); return distance; } double JoyAxisButton::getLastAccelerationDistance() { double distance = 0.0; distance = axis->getRawDistance(axis->getLastKnownThrottleValue()); /*if (axis->getAxisButtonByValue(axis->getLastKnownThrottleValue()) == this) { distance = axis->getRawDistance(axis->getLastKnownThrottleValue()); } */ return distance; } double JoyAxisButton::getLastMouseDistanceFromDeadZone() { double distance = 0.0; if (axis->getAxisButtonByValue(axis->getLastKnownThrottleValue()) == this) { distance = axis->getDistanceFromDeadZone(axis->getLastKnownThrottleValue()); } return distance; } OptimistLabyrinth/operating-system_programming03_pseudo_blood_pressure_detector/src/src_ptttm/initialize_ptttm_variables.cpp #include "../../include/include_ptttm/initialize_ptttm_variables.hpp" // static PTTTM variables extern std::unique_ptr API_Mutex; extern std::unique_ptr TM_Arg; extern std::unique_ptr Timer; extern std::unique_ptr THR_Arg__acq_thread; extern std::unique_ptr THR_Arg__proc_thread; extern std::unique_ptr TCB_storage; void initialize_ptttm_variables(void) { API_Mutex = std::make_unique(); pthread_mutex_init(&(*API_Mutex), nullptr); TM_Arg = std::make_unique(); Timer = std::make_unique(); THR_Arg__acq_thread = std::make_unique(); THR_Arg__proc_thread = std::make_unique(); TCB_storage = std::make_unique(); } 洛谷/入门/cpp34.cc10-100 /* * Author : OFShare * E-mail : * Created Time : 2020-06-23 14:42:35 PM * File Name : cpp34.cc */ #include #define ll long long void debug() { #ifdef Acui freopen("data.in", "r", stdin); freopen("data.out", "w", stdout); #endif } int main() { std::string str = R"(C:\File\To\Path)"; std::cout << str << std::endl; return 0; } 山东大学/Day01资料/03cmakelist_qt_opencv_torch/qt_opencv_torch.cpp #include // 放第一行,否则可能出问题! #include #include #include #include #include #include // 没有使用面向对象的封装 int main(int argc, char**argv){ torch::Tensor tensor = torch::rand({2, 3}); std::cout << tensor << std::endl; // 创建Qt应用 QApplication application(argc, argv); // 创建窗体QDialog / QMainWindow 及其他的窗体QWidget等。 QDialog dlg; dlg.setWindowTitle("Qt与OpenCV-Makefile"); dlg.resize(800, 600); dlg.setFixedSize(dlg.width(), dlg.height()); // 不允许改变窗体大小 dlg.move ((QApplication::desktop()->width() - dlg.width()) / 2, (QApplication::desktop()->height() - dlg.height()) / 2); // 使用QLabel显示图像 QLabel lbl_show("显示图像区域",&dlg); lbl_show.setAlignment(Qt::AlignVCenter | Qt::AlignHCenter); lbl_show.setGeometry(0, 0, dlg.width(), dlg.height()); // // 图像的处理 cv::Mat img = cv::imread("gpu.bmp"); // 把图像转换为Qt支持的对象 QImage qt_img(img.data, img.cols, img.rows, QImage::Format_RGB888); QPixmap qt_pixmap = QPixmap::fromImage(qt_img); lbl_show.setPixmap(qt_pixmap); lbl_show.setScaledContents(true); dlg.show(); // 应用消息处理 return application.exec(); } /* This file is part of NSEssentials. Use of this source code is granted via a BSD-style license, which can be found in License.txt in the repository root. @author */ #ifdef HAVE_NANOGUI #include "nsessentials/gui/GLVertexArray.h" using namespace nse::gui; GLVertexArray::GLVertexArray() : vaoId(0) { } GLVertexArray::~GLVertexArray() { if (vaoId > 0) glDeleteVertexArrays(1, &vaoId); } void GLVertexArray::generate() { if (vaoId == 0) glGenVertexArrays(1, &vaoId); } void GLVertexArray::bind() const { glBindVertexArray(vaoId); } void GLVertexArray::unbind() const { glBindVertexArray(0); } bool GLVertexArray::valid() const { return vaoId != 0; } #endif#include namespace yage { Window::Window(WindowDesc desc) { mWindowDesc = desc; //Initialize GLFW glfwSetErrorCallback(glfw_error_callback); if (!glfwInit()) { YAGE_CRITICAL("Failed to initialize GLFW"); return; } //create GLFW window and OpenGL context glfwWindowHint(GLFW_RESIZABLE, mWindowDesc.resizable); glfwWindowHint(GLFW_VISIBLE, mWindowDesc.visible); glfwWindowHint(GLFW_DECORATED, mWindowDesc.decorated); glfwWindowHint(GLFW_FLOATING, mWindowDesc.floating); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 6); #ifdef DEBUG glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GLFW_TRUE); #endif if (mWindowDesc.fullscreen) mWindowHandle = glfwCreateWindow(mWindowDesc.width, mWindowDesc.height, mWindowDesc.title.c_str(), glfwGetPrimaryMonitor(), NULL); else mWindowHandle = glfwCreateWindow(mWindowDesc.width, mWindowDesc.height, mWindowDesc.title.c_str(), NULL, NULL); if (!mWindowHandle) { glfwTerminate(); YAGE_CRITICAL("Failed to create GLFW window"); return; } glfwSetKeyCallback(mWindowHandle, glfw_key_callback); glfwSetCursorPosCallback(mWindowHandle, glfw_cursor_position_callback); glfwSetCursorEnterCallback(mWindowHandle, glfw_cursor_enter_callback); glfwSetMouseButtonCallback(mWindowHandle, glfw_mouse_button_callback); glfwSetScrollCallback(mWindowHandle, glfw_scroll_callback); glfwSetWindowSizeCallback(mWindowHandle, window_size_callback); //Make the created OpenGL context the current context glfwMakeContextCurrent(mWindowHandle); mDevice = new GLDevice(); } Window::~Window() { if(mDevice){ delete mDevice; } glfwTerminate(); } void Window::update() { glfwPollEvents(); glfwSwapBuffers(mWindowHandle); } bool Window::shouldClose() { return glfwWindowShouldClose(mWindowHandle); } void Window::resize(int width, int height) { mWindowDesc.width = width; mWindowDesc.height = height; glfwSetWindowSize(mWindowHandle, width, height); } GLDevice* Window::getGraphicsDevice() { return mDevice; } GLFWwindow *Window::getWindowHandle() { return mWindowHandle; } void Window::window_size_callback(GLFWwindow* window, int width, int height){ glViewport(0, 0, width, height); } void glfw_error_callback(int error, const char *description) { YAGE_ERROR("GLFW ERROR: " + std::to_string(error) + description); } } // namespace yage zealoussnow/chromium // Copyright 2021 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 "base/memory/scoped_refptr.h" #include "chrome/common/chromeos/extensions/chromeos_system_extensions_manifest_constants.h" #include "chrome/common/extensions/manifest_tests/chrome_manifest_test.h" #include "testing/gtest/include/gtest/gtest.h" namespace chromeos { using ExtensionManifestChromeOSSystemExtensionTest = ChromeManifestTest; TEST_F(ExtensionManifestChromeOSSystemExtensionTest, InvalidChromeOSSystemExtension) { LoadAndExpectWarning( "chromeos_system_extension_invalid.json", "'chromeos_system_extension' is not allowed for specified extension ID."); } TEST_F(ExtensionManifestChromeOSSystemExtensionTest, ValidChromeOSSystemExtension_Allowlisted_1) { scoped_refptr extension( LoadAndExpectSuccess("chromeos_system_extension.json")); EXPECT_TRUE(extension->is_chromeos_system_extension()); EXPECT_TRUE(extension->install_warnings().empty()); } TEST_F(ExtensionManifestChromeOSSystemExtensionTest, ValidChromeOSSystemExtension_Allowlisted_2) { scoped_refptr extension( LoadAndExpectSuccess("chromeos_system_extension_2.json")); EXPECT_TRUE(extension->is_chromeos_system_extension()); EXPECT_TRUE(extension->install_warnings().empty()); } TEST_F(ExtensionManifestChromeOSSystemExtensionTest, ValidNonChromeOSSystemExtension) { scoped_refptr extension( LoadAndExpectSuccess("background_page.json")); EXPECT_FALSE(extension->is_chromeos_system_extension()); } TEST_F(ExtensionManifestChromeOSSystemExtensionTest, InvalidExternallyConnectableEmpty) { LoadAndExpectError( "chromeos_system_extension_invalid_externally_connectable_empty.json", chromeos::kInvalidExternallyConnectableDeclaration); } TEST_F(ExtensionManifestChromeOSSystemExtensionTest, InvalidExternallyConnectableIds) { LoadAndExpectError( "chromeos_system_extension_invalid_externally_connectable_ids.json", chromeos::kInvalidExternallyConnectableDeclaration); } TEST_F(ExtensionManifestChromeOSSystemExtensionTest, InvalidExternallyConnectableTls) { LoadAndExpectError( "chromeos_system_extension_invalid_externally_connectable_tls.json", chromeos::kInvalidExternallyConnectableDeclaration); } TEST_F(ExtensionManifestChromeOSSystemExtensionTest, InvalidExternallyConnectableMatchesMoreThanOne) { LoadAndExpectError( "chromeos_system_extension_invalid_externally_connectable_2_origins.json", chromeos::kInvalidExternallyConnectableDeclaration); } TEST_F(ExtensionManifestChromeOSSystemExtensionTest, InvalidExternallyConnectableMatchesEmpty) { LoadAndExpectError( "chromeos_system_extension_invalid_externally_connectable_matches_empty." "json", chromeos::kInvalidExternallyConnectableDeclaration); } TEST_F(ExtensionManifestChromeOSSystemExtensionTest, InvalidExternallyConnectableMatchesDisallowedOrigin) { LoadAndExpectError( "chromeos_system_extension_invalid_externally_connectable_1_origin.json", chromeos::kInvalidExternallyConnectableDeclaration); } TEST_F(ExtensionManifestChromeOSSystemExtensionTest, InvalidExternallyConnectableNotExist) { LoadAndExpectError( "chromeos_system_extension_invalid_externally_connectable_not_exist.json", chromeos::kInvalidExternallyConnectableDeclaration); } } // namespace chromeos chp-io/libmspdbinclude/type_info/LF_FIELDLIST_CONTAINER.hh1-10 /* * Copyright 2021 Assured Information Security, 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. */ #ifndef LIBPDB_TYPE_INFO_LF_FIELD_CONTAINER_HH_ #define LIBPDB_TYPE_INFO_LF_FIELD_CONTAINER_HH_ #include "LF_MEMBER.hh" #include "LF_TYPE.hh" #include #include #include namespace mspdb { class LF_FIELDLIST_CONTAINER : public LF_TYPE { public: LF_FIELDLIST_CONTAINER(const char*& buf, int32_t& buffer_size); ~LF_FIELDLIST_CONTAINER() override; public: virtual uint16_t count() const = 0; virtual const std::vector>& field_list() const = 0; virtual int64_t size() const = 0; virtual const std::string& name() const = 0; const LF_MEMBER* find_member(const std::string& name) const; const LF_MEMBER* find_member_recursive(const std::string& name, size_t& total_offset) const; // Flags virtual bool packed() const = 0; virtual bool ctor() const = 0; virtual bool ovlops() const = 0; virtual bool nested() const = 0; virtual bool cnested() const = 0; virtual bool opassign() const = 0; virtual bool opcast() const = 0; virtual bool fwdref() const = 0; virtual bool scoped() const = 0; private: class IMPL; std::unique_ptr pImpl; }; } /* namespace mspdb */ #endif /* LIBPDB_TYPE_INFO_LF_FIELD_CONTAINER_HH_ */// // Created by lenovo on 2022/1/19. // #include "blockchainmanager.h" unsigned long long getKey(int &fd, long ×tamp) { return (0x00000000ffffffff & timestamp) | ((unsigned long long) fd << 32); } BlockchainManager::BlockchainManager(int num, std::string ip) : quit(false), cache(Cache::GetCache()) { addr = new char[ip.size() + 1]; addr[ip.size()] = '\0'; ip.copy(addr, ip.size()); while (num > 0) { create_thread(); --num; } } BlockchainManager::~BlockchainManager() { } void BlockchainManager::create_thread() { threads.emplace_back([this] { std::unique_lock lock(this->mtx, std::defer_lock); Request task; bool run_task = false; Blockchain blockchain; if (!blockchain.connect(addr)) { //this->threads.pop_back(); //return; } while (!quit.load()) { lock.lock(); this->cond.wait(lock, [this]() { return !this->tasks.empty() || this->quit.load(); }); run_task = false; if (!this->tasks.empty() && !this->quit.load()) { task = std::move(this->tasks.front()); this->tasks.pop(); run_task = true; } lock.unlock(); //printf("BlockchainManager thread wake up\n"); if (run_task) { //printf("BlockchainManager run task\n"); if (task.domain != nullptr) { std::vector &&res = blockchain.query(task.domain, task.type); //printf("BlockchainManager add to Cache\n"); if (!res.empty()) { for (auto &record: res) { cache.put(task.domain, record.type, record.ip, record.ttl); } } free(task.domain); } { std::lock_guard rwlock(rw_mtx); --processing[task.key]; if (processing[task.key] <= 0) { processing.erase(task.key); } } } } this->threads.pop_back(); }); threads.back().detach(); } void BlockchainManager::exit() { quit.store(true); cond.notify_all(); } bool BlockchainManager::is_processing(unsigned long long key) { std::shared_lock rwlock(rw_mtx); return processing.count(key) == 1; } void BlockchainManager::add_task(Request request) { Request req = request; req.domain = (char *) malloc(req.domain_len + 1); if (req.domain == nullptr) { return; } { std::lock_guard rwlock(rw_mtx); ++processing[request.key]; } std::memcpy(req.domain, request.domain, request.domain_len); req.domain[req.domain_len] = '\0'; { std::lock_guard lock(this->mtx); tasks.push(req); } printf("BlockchainManager add task\n"); this->cond.notify_all(); } //-------------------------------------------------------------------------------------- // // // Copyright 2014 ADVANCED MICRO DEVICES, INC. All Rights Reserved. // // AMD is granting you permission to use this software and documentation (if // any) (collectively, the "Materials") pursuant to the terms and conditions // of the Software License Agreement included with the Materials. If you do // not have a copy of the Software License Agreement, contact your AMD // representative for a copy. // You agree that you will not reverse engineer or decompile the Materials, // in whole or in part, except as allowed by applicable law. // // WARRANTY DISCLAIMER: THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF // ANY KIND. AMD DISCLAIMS ALL WARRANTIES, EXPRESS, IMPLIED, OR STATUTORY, // INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE, NON-INFRINGEMENT, THAT THE SOFTWARE // WILL RUN UNINTERRUPTED OR ERROR-FREE OR WARRANTIES ARISING FROM CUSTOM OF // TRADE OR COURSE OF USAGE. THE ENTIRE RISK ASSOCIATED WITH THE USE OF THE // SOFTWARE IS ASSUMED BY YOU. // Some jurisdictions do not allow the exclusion of implied warranties, so // the above exclusion may not apply to You. // // LIMITATION OF LIABILITY AND INDEMNIFICATION: AMD AND ITS LICENSORS WILL // NOT, UNDER ANY CIRCUMSTANCES BE LIABLE TO YOU FOR ANY PUNITIVE, DIRECT, // INCIDENTAL, INDIRECT, SPECIAL OR CONSEQUENTIAL DAMAGES ARISING FROM USE OF // THE SOFTWARE OR THIS AGREEMENT EVEN IF AMD AND ITS LICENSORS HAVE BEEN // ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. // In no event shall AMD's total liability to You for all damages, losses, // and causes of action (whether in contract, tort (including negligence) or // otherwise) exceed the amount of $100 USD. You agree to defend, indemnify // and hold harmless AMD and its licensors, and any of their directors, // officers, employees, affiliates or agents from and against any and all // loss, damage, liability and other expenses (including reasonable attorneys' // fees), resulting from Your use of the Software or violation of the terms and // conditions of this Agreement. // // U.S. GOVERNMENT RESTRICTED RIGHTS: The Materials are provided with "RESTRICTED // RIGHTS." Use, duplication, or disclosure by the Government is subject to the // restrictions as set forth in FAR 52.227-14 and DFAR252.227-7013, et seq., or // its successor. Use of the Materials by the Government constitutes // acknowledgement of AMD's proprietary rights in them. // // EXPORT RESTRICTIONS: The Materials may be subject to export restrictions as // stated in the Software License Agreement. // //-------------------------------------------------------------------------------------- #include "DXcopyApp.h" #include "DXSinkWindow.h" #include "DXSourceWindow.h" #include "BufferQueue.h" #include "ADLtool.h" DXcopyApp::DXcopyApp() { m_SinkApp = NULL; m_SourceApp = NULL; m_uiTransferId = 0; m_SinkRun = false; m_SourceRun = false; m_pSyncBuffer = NULL; } DXcopyApp::~DXcopyApp() { if (m_pSyncBuffer) { delete m_pSyncBuffer; m_pSyncBuffer=NULL; } } HRESULT DXcopyApp::Init(HINSTANCE hInstance, int nCmdShow) { HRESULT hr = S_OK; //Get desktop positions unsigned int gpu0_uiDsp = ADLtool::getDisplayOnGPU(0, 0); ADLtool::DisplayData* gpu0_pDsp = ADLtool::getDisplayData(gpu0_uiDsp); unsigned int gpu1_uiDsp = ADLtool::getDisplayOnGPU(1, 0); ADLtool::DisplayData* gpu1_pDsp = ADLtool::getDisplayData(gpu1_uiDsp); if ( gpu0_pDsp == NULL || gpu1_pDsp == NULL ) { MessageBoxA(NULL,"Error. For this demo, you must have 2 GPUs, and one monitor connected on each GPU.","demo DGMA",NULL); return E_FAIL; } m_SinkApp = new DXSinkWindow(); m_SourceApp = new DXSourceWindow(); if( FAILED(m_SinkApp->InitWindow( hInstance, nCmdShow , L"DX11DGMAWindowClass3_A", L"Sink", gpu1_pDsp->iOriginX + gpu1_pDsp->uiWidth/2 - DXwindow::m_width/2, gpu1_pDsp->iOriginY )) ) { return E_FAIL; } if( FAILED(m_SourceApp->InitWindow( hInstance, nCmdShow , L"DX11DGMAWindowClass3_B", L"Source", gpu0_pDsp->iOriginX + gpu0_pDsp->uiWidth/2 - DXwindow::m_width/2, gpu0_pDsp->iOriginY )) ) { return E_FAIL; } if( FAILED( m_SinkApp->InitDevice(NULL,D3D_DRIVER_TYPE_HARDWARE) )) { return E_FAIL; } IDXGIDevice* pDXGIDevice = NULL; hr = m_SinkApp->GetD3D11Device()->QueryInterface(__uuidof(IDXGIDevice), (void **)&pDXGIDevice); PASS_TEST(hr); IDXGIAdapter* pDXGIAdapter = NULL; hr = pDXGIDevice->GetParent(__uuidof(IDXGIAdapter), (void **)&pDXGIAdapter); PASS_TEST(hr); IDXGIFactory* pIDXGIFactory = NULL; pDXGIAdapter->GetParent(__uuidof(IDXGIFactory), (void **)&pIDXGIFactory); UINT g_numAdapters = 0; IDXGIAdapter* pAdapter = NULL; std::vector vAdapters; while(pIDXGIFactory->EnumAdapters(g_numAdapters, &pAdapter) != DXGI_ERROR_NOT_FOUND) { vAdapters.push_back(pAdapter); ++g_numAdapters; } // Get the device for the 2nd adapter (if one is present) IDXGIAdapter* adapter2 = NULL; if (2 == g_numAdapters) { adapter2 = vAdapters.at(1); } else { MessageBoxA(NULL,"You should have 2 monitors","demo DGMA",NULL); } if( FAILED( m_SourceApp->InitDevice(adapter2,D3D_DRIVER_TYPE_UNKNOWN) )) { return E_FAIL; } if( FAILED( m_SinkApp->InitSDIForDevice() )) { return E_FAIL; } if( FAILED( m_SourceApp->InitSDIForDevice() )) { return E_FAIL; } m_SinkApp->InitSDItexture(NUM_BUFFERS); m_SourceApp->InitSDItexture(m_SinkApp->GetSurfaceList()); m_pSyncBuffer = new BufferQueue(NUM_BUFFERS); // Allocate memory to store frame data FrameData* m_pFrameData = new FrameData[NUM_BUFFERS]; if ( m_SinkApp->GetSurfaceList().numSurfaces != NUM_BUFFERS ) { PASS_TEST(E_FAIL); } for (unsigned int i = 0; i < NUM_BUFFERS; i++) { m_pFrameData[i].uiTransferId = 0; m_pFrameData[i].uiBufferId = i; m_pFrameData[i].ullBufferBusAddress = m_SinkApp->GetSurfaceList().pInfo[i].pInfo->SurfaceBusAddr; m_pFrameData[i].ullMarkerBusAddress = m_SinkApp->GetSurfaceList().pInfo[i].pInfo->MarkerBusAddr; m_pSyncBuffer->setBufferMemory(i, (void*)(&m_pFrameData[i])); } return S_OK; } bool DXcopyApp::Start() { m_SinkRun = true; m_SourceRun = true; m_SinkThread.create((THREAD_PROC)SinkThreadFunc, this); m_SourceThread.create((THREAD_PROC)SourceThreadFunc, this); while (true) { MSG Msg; if (PeekMessage(&Msg, NULL, 0, 0, PM_REMOVE)) { if (Msg.message == WM_QUIT) { break; } else { TranslateMessage(&Msg); DispatchMessage(&Msg); } } Sleep(100); // sleep since we do not want to spend too many cycles in the window message management } Stop(); return true; } void DXcopyApp::Stop() { m_SinkRun = false; m_SinkThread.join(); m_SourceRun = false; m_pSyncBuffer->releaseReadBuffer();//free one buffer in order to be 100% sure that getBufferForWriting() of m_SourceThread will not be blocked m_SourceThread.join(); } DWORD DXcopyApp::SourceThreadFunc(void* pArg) { DXcopyApp* pApp = static_cast(pArg); pApp->SourceLoop(); return 0; } DWORD DXcopyApp::SinkThreadFunc(void *pArg) { DXcopyApp* pApp = static_cast(pArg); pApp->SinkLoop(); return 0; } bool DXcopyApp::SinkLoop() { while (m_SinkRun) { m_SinkApp->Render(m_pSyncBuffer); } return true; } bool DXcopyApp::SourceLoop() { while (m_SourceRun) { m_uiTransferId++; m_SourceApp->Render(m_pSyncBuffer,m_uiTransferId); } return true; } 100-1000 //wine problem /* problem statement: Given n wines in a row, with integers denoting the cost of each wine respectively. Each year you can sale the first or the last wine in the row. However, the price of wines increases over time. Let the initial profits from the wines be P1, P2, P3…Pn. On the Yth year, the profit from the ith wine will be Y*Pi. For each year, your task is to print “beg” or “end” denoting whether first or last wine should be sold. Also, calculate the maximum profit from all the wines. Input: Price of wines: 2 4 6 2 5 Output: beg end end beg beg 64 explanation a)ans=ans+2*1 {ans=2} b)ans=ans+5*2 {ans=12} c)ans=ans+2*3 {ans=18} d)ans=ans+4*4 {ans=34} e)ans=ans+6*5 {ans=64} */ #include using namespace std; //dp solution int maxproft(int arr[],int n){ // This array stores the "optimal action" // for each state i, j int dp[100][100]={0}; int year=n; for(int i=0;i>n; int a[n]; for(int x=0;x>a[x]; } cout<LeetCode/Problems/Algorithms/#1738_FindKthLargestXORCoordinateValue_sol3_min_heap_O(RClogK)_time_O(C+K)_extra_space_524ms_99MB.cpp class Solution { public: int kthLargestValue(vector>& matrix, int k) { const int ROWS = matrix.size(); const int COLS = matrix[0].size(); vector colXOR(COLS, 0); priority_queue, greater> minHeap; for(int row = 0; row < ROWS; ++row){ int prefXOR = 0; for(int col = 0; col < COLS; ++col){ colXOR[col] ^= matrix[row][col]; prefXOR ^= colXOR[col]; minHeap.push(prefXOR); if((int)minHeap.size() == k + 1){ minHeap.pop(); } } } return minHeap.top(); } };/* * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #include #include namespace osquery { namespace tables { class TablesTests : public testing::Test {}; TEST_F(TablesTests, test_constraint) { auto constraint = Constraint(EQUALS); constraint.expr = "none"; EXPECT_EQ(constraint.op, EQUALS); EXPECT_EQ(constraint.expr, "none"); } TEST_F(TablesTests, test_constraint_list) { struct ConstraintList cl; auto constraint = Constraint(EQUALS); constraint.expr = "some"; // The constraint list is a simple struct. cl.add(constraint); EXPECT_EQ(cl.constraints_.size(), 1); constraint = Constraint(EQUALS); constraint.expr = "some_other"; cl.add(constraint); constraint = Constraint(GREATER_THAN); constraint.expr = "more_than"; cl.add(constraint); EXPECT_EQ(cl.constraints_.size(), 3); auto all_equals = cl.getAll(EQUALS); EXPECT_EQ(all_equals.size(), 2); } TEST_F(TablesTests, test_constraint_matching) { struct ConstraintList cl; // An empty constraint list has expectations. EXPECT_FALSE(cl.exists()); EXPECT_TRUE(cl.notExistsOrMatches("some")); auto constraint = Constraint(EQUALS); constraint.expr = "some"; cl.add(constraint); EXPECT_TRUE(cl.exists()); EXPECT_TRUE(cl.notExistsOrMatches("some")); EXPECT_TRUE(cl.matches("some")); EXPECT_FALSE(cl.notExistsOrMatches("not_some")); struct ConstraintList cl2; cl2.affinity = "INTEGER"; constraint = Constraint(LESS_THAN); constraint.expr = "1000"; cl2.add(constraint); constraint = Constraint(GREATER_THAN); constraint.expr = "1"; cl2.add(constraint); // Test both SQL-provided string types. EXPECT_TRUE(cl2.matches("10")); // ...and the type literal. EXPECT_TRUE(cl2.matches(10)); // Test operator lower bounds. EXPECT_FALSE(cl2.matches(0)); EXPECT_FALSE(cl2.matches(1)); // Test operator upper bounds. EXPECT_FALSE(cl2.matches(1000)); EXPECT_FALSE(cl2.matches(1001)); // Now test inclusive bounds. struct ConstraintList cl3; constraint = Constraint(LESS_THAN_OR_EQUALS); constraint.expr = "1000"; cl3.add(constraint); constraint = Constraint(GREATER_THAN_OR_EQUALS); constraint.expr = "1"; cl3.add(constraint); EXPECT_FALSE(cl3.matches(1001)); EXPECT_TRUE(cl3.matches(1000)); EXPECT_FALSE(cl3.matches(0)); EXPECT_TRUE(cl3.matches(1)); } TEST_F(TablesTests, test_constraint_map) { ConstraintMap cm; ConstraintList cl; cl.add(Constraint(EQUALS, "some")); cm["path"] = cl; // If a constraint list exists for a map key, normal constraints apply. EXPECT_TRUE(cm["path"].matches("some")); EXPECT_FALSE(cm["path"].matches("not_some")); // If a constraint list does not exist, then all checks will match. // If there is no predicate clause then all results will match. EXPECT_TRUE(cm["not_path"].matches("some")); EXPECT_TRUE(cm["not_path"].notExistsOrMatches("some")); EXPECT_FALSE(cm["not_path"].exists()); EXPECT_FALSE(cm["not_path"].existsAndMatches("some")); // And of the column has constraints: EXPECT_TRUE(cm["path"].notExistsOrMatches("some")); EXPECT_FALSE(cm["path"].notExistsOrMatches("not_some")); EXPECT_TRUE(cm["path"].exists()); EXPECT_TRUE(cm["path"].existsAndMatches("some")); } } } int main(int argc, char* argv[]) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } #include "SortUtils.h" #include "FFX_ParallelSort.h" #include #include #include #include Renderer::DescriptorSet SortUtils::_setupDescriptorSet; Renderer::DescriptorSet SortUtils::_countDescriptorSet; Renderer::DescriptorSet SortUtils::_countReduceDescriptorSet; Renderer::DescriptorSet SortUtils::_scanDescriptorSet; Renderer::DescriptorSet SortUtils::_scanAddDescriptorSet; Renderer::DescriptorSet SortUtils::_scatterDescriptorSet; // TODO: Add renderer->CreateTemporaryBuffer function which will temporarily allocate a buffer with lifetime of a variable number of frames void SortUtils::Sort(Renderer::Renderer* renderer, Renderer::RenderGraphResources& graphResources, Renderer::CommandList& commandList, u32 frameIndex, const SortParams& params) { SortBuffers buffers = InitBuffers(renderer, commandList, params.numKeys); // Create keysCount buffer { Renderer::BufferDesc desc; desc.name = "SortKeysCount"; desc.size = sizeof(u32); desc.usage = Renderer::BufferUsage::UNIFORM_BUFFER | Renderer::BufferUsage::TRANSFER_DESTINATION; buffers.numKeysBuffer = renderer->CreateTemporaryBuffer(desc, 2); desc.usage = Renderer::BufferUsage::TRANSFER_SOURCE; desc.cpuAccess = Renderer::BufferCPUAccess::WriteOnly; Renderer::BufferID staging = renderer->CreateBuffer(desc); u32* numKeys = static_cast(renderer->MapBuffer(staging)); *numKeys = params.numKeys; renderer->UnmapBuffer(staging); commandList.CopyBuffer(buffers.numKeysBuffer, 0, staging, 0, desc.size); } // Then we copy the keys and payload into the first buffer u32 keysBufferSize = params.numKeys * sizeof(u64); u32 valuesBufferSize = params.numKeys * sizeof(u32); commandList.CopyBuffer(buffers.keysBuffers.Get(0), 0, params.keysBuffer, 0, keysBufferSize); commandList.CopyBuffer(buffers.valuesBuffers.Get(0), 0, params.valuesBuffer, 0, valuesBufferSize); commandList.PipelineBarrier(Renderer::PipelineBarrierType::TransferDestToComputeShaderRW, buffers.keysBuffers.Get(0)); commandList.PipelineBarrier(Renderer::PipelineBarrierType::TransferDestToComputeShaderRW, buffers.valuesBuffers.Get(0)); // Setup indirect parameters { SetupParams setupParams; setupParams.maxThreadGroups = params.maxThreadGroups; setupParams.numKeysBuffer = buffers.numKeysBuffer; setupParams.constantBuffer = buffers.constantBuffer; setupParams.countScatterArgsBuffer = buffers.countScatterArgsBuffer; setupParams.reduceScanArgsBuffer = buffers.reduceScanArgsBuffer; SetupIndirectParameters(renderer, graphResources, commandList, frameIndex, setupParams); commandList.PipelineBarrier(Renderer::PipelineBarrierType::ComputeWriteToComputeShaderRead, buffers.constantBuffer); commandList.PipelineBarrier(Renderer::PipelineBarrierType::ComputeWriteToIndirectArguments, buffers.countScatterArgsBuffer); commandList.PipelineBarrier(Renderer::PipelineBarrierType::ComputeWriteToIndirectArguments, buffers.reduceScanArgsBuffer); } ResultBuffers resultBuffers = SortInternal(renderer, graphResources, commandList, frameIndex, buffers); // Copy the result buffers back into the buffers they came from commandList.CopyBuffer(params.keysBuffer, 0, resultBuffers.keysBuffer, 0, keysBufferSize); commandList.CopyBuffer(params.valuesBuffer, 0, resultBuffers.valuesBuffer, 0, valuesBufferSize); } void SortUtils::SortIndirectCount(Renderer::Renderer* renderer, Renderer::RenderGraphResources& graphResources, Renderer::CommandList& commandList, u32 frameIndex, const SortIndirectCountParams& params) { SortBuffers buffers = InitBuffers(renderer, commandList, params.maxNumKeys); buffers.numKeysBuffer = params.numKeysBuffer; // Then we copy the keys and payload into the first buffer u32 keysBufferSize = params.maxNumKeys * sizeof(u64); u32 valuesBufferSize = params.maxNumKeys * sizeof(u32); commandList.CopyBuffer(buffers.keysBuffers.Get(0), 0, params.keysBuffer, 0, keysBufferSize); commandList.CopyBuffer(buffers.valuesBuffers.Get(0), 0, params.valuesBuffer, 0, valuesBufferSize); commandList.PipelineBarrier(Renderer::PipelineBarrierType::TransferDestToComputeShaderRW, buffers.keysBuffers.Get(0)); commandList.PipelineBarrier(Renderer::PipelineBarrierType::TransferDestToComputeShaderRW, buffers.valuesBuffers.Get(0)); // Setup indirect parameters { SetupParams setupParams; setupParams.maxThreadGroups = params.maxThreadGroups; setupParams.numKeysBuffer = buffers.numKeysBuffer; setupParams.constantBuffer = buffers.constantBuffer; setupParams.countScatterArgsBuffer = buffers.countScatterArgsBuffer; setupParams.reduceScanArgsBuffer = buffers.reduceScanArgsBuffer; SetupIndirectParameters(renderer, graphResources, commandList, frameIndex, setupParams); commandList.PipelineBarrier(Renderer::PipelineBarrierType::ComputeWriteToComputeShaderRead, buffers.constantBuffer); commandList.PipelineBarrier(Renderer::PipelineBarrierType::ComputeWriteToIndirectArguments, buffers.countScatterArgsBuffer); commandList.PipelineBarrier(Renderer::PipelineBarrierType::ComputeWriteToIndirectArguments, buffers.reduceScanArgsBuffer); } ResultBuffers resultBuffers = SortInternal(renderer, graphResources, commandList, frameIndex, buffers); // Copy the result buffers back into the buffers they came from commandList.CopyBuffer(params.keysBuffer, 0, resultBuffers.keysBuffer, 0, keysBufferSize); commandList.CopyBuffer(params.valuesBuffer, 0, resultBuffers.valuesBuffer, 0, valuesBufferSize); } SortUtils::SortBuffers SortUtils::InitBuffers(Renderer::Renderer* renderer, Renderer::CommandList& commandList, u32 numKeys) { SortUtils::SortBuffers sortBuffers; // Create constantBuffer { Renderer::BufferDesc desc; desc.name = "SortConstantBuffer"; desc.size = sizeof(FFX_ParallelSortCB); desc.usage = Renderer::BufferUsage::STORAGE_BUFFER | Renderer::BufferUsage::UNIFORM_BUFFER; sortBuffers.constantBuffer = renderer->CreateTemporaryBuffer(desc, 2); } // Create countScatterArgsBuffer { Renderer::BufferDesc desc; desc.name = "SortCountScatterArgs"; desc.size = sizeof(u32) * 3; desc.usage = Renderer::BufferUsage::STORAGE_BUFFER | Renderer::BufferUsage::INDIRECT_ARGUMENT_BUFFER; sortBuffers.countScatterArgsBuffer = renderer->CreateTemporaryBuffer(desc, 2); } // Create reduceScanArgsBuffer { Renderer::BufferDesc desc; desc.name = "SortKeyCountsBuffer"; desc.size = sizeof(u32) * 3; desc.usage = Renderer::BufferUsage::STORAGE_BUFFER | Renderer::BufferUsage::INDIRECT_ARGUMENT_BUFFER; sortBuffers.reduceScanArgsBuffer = renderer->CreateTemporaryBuffer(desc, 2); } // We need to create sorting buffers for both keys and values, but we need two each which we can ping-pong between during sorting u32 keysBufferSize = numKeys * sizeof(u64); u32 valuesBufferSize = numKeys * sizeof(u32); { Renderer::BufferDesc desc; desc.size = keysBufferSize; desc.usage = Renderer::BufferUsage::STORAGE_BUFFER | Renderer::BufferUsage::TRANSFER_DESTINATION | Renderer::BufferUsage::TRANSFER_SOURCE; for (u32 i = 0; i < sortBuffers.keysBuffers.Num; i++) { desc.name = "SortKeysBuffer" + std::to_string(i); sortBuffers.keysBuffers.Get(i) = renderer->CreateTemporaryBuffer(desc, 2); } desc.size = valuesBufferSize; for (u32 i = 0; i < sortBuffers.valuesBuffers.Num; i++) { desc.name = "SortValuesBuffer" + std::to_string(i); sortBuffers.valuesBuffers.Get(i) = renderer->CreateTemporaryBuffer(desc, 2); } } // We need to create sumTableBuffer and reducedSumTableBuffer to be used by the sorting shaders { u32 sumTableSize; u32 reducedSumTableSize; FFX_ParallelSort_CalculateScratchResourceSize(numKeys, sumTableSize, reducedSumTableSize); Renderer::BufferDesc desc; desc.name = "SortSumTable"; desc.size = sumTableSize; desc.usage = Renderer::BufferUsage::STORAGE_BUFFER; sortBuffers.sumTableBuffer = renderer->CreateTemporaryBuffer(desc, 2); desc.name = "ReducedSortSumTable"; desc.size = reducedSumTableSize; sortBuffers.reducedSumTableBuffer = renderer->CreateTemporaryBuffer(desc, 2); } return sortBuffers; } SortUtils::ResultBuffers SortUtils::SortInternal(Renderer::Renderer* renderer, Renderer::RenderGraphResources& graphResources, Renderer::CommandList& commandList, u32 frameIndex, SortBuffers& buffers) { Renderer::BufferID readKeyBuffer = buffers.keysBuffers.Get(0); Renderer::BufferID readPayloadBuffer = buffers.valuesBuffers.Get(0); Renderer::BufferID writeKeyBuffer = buffers.keysBuffers.Get(1); Renderer::BufferID writePayloadBuffer = buffers.valuesBuffers.Get(1); // Perform radix sort for (u32 shiftBits = 0; shiftBits < 64; shiftBits += FFX_PARALLELSORT_SORT_BITS_PER_PASS) { commandList.PushMarker("ShiftBits:" + std::to_string(shiftBits), Color::White); // Sort Count { CountParams countParams; countParams.shiftBits = shiftBits; countParams.constantBuffer = buffers.constantBuffer; countParams.keysBuffer = readKeyBuffer; countParams.sumTableBuffer = buffers.sumTableBuffer; countParams.countScatterArgsBuffer = buffers.countScatterArgsBuffer; Count(renderer, graphResources, commandList, frameIndex, countParams); commandList.PipelineBarrier(Renderer::PipelineBarrierType::ComputeWriteToComputeShaderRead, buffers.sumTableBuffer); } // Sort Count Reduce { CountReduceParams countReduceParams; countReduceParams.constantBuffer = buffers.constantBuffer; countReduceParams.sumTableBuffer = buffers.sumTableBuffer; countReduceParams.reducedSumTableBuffer = buffers.reducedSumTableBuffer; countReduceParams.reduceScanArgsBuffer = buffers.reduceScanArgsBuffer; CountReduce(renderer, commandList, frameIndex, countReduceParams); commandList.PipelineBarrier(Renderer::PipelineBarrierType::ComputeWriteToComputeShaderRead, buffers.reducedSumTableBuffer); } // Sort Scan { // First do scan prefix of reduced values ScanParams scanParams; scanParams.constantBuffer = buffers.constantBuffer; scanParams.sumTableBuffer = buffers.sumTableBuffer; scanParams.reducedSumTableBuffer = buffers.reducedSumTableBuffer; Scan(renderer, commandList, frameIndex, scanParams); commandList.PipelineBarrier(Renderer::PipelineBarrierType::ComputeWriteToComputeShaderRead, buffers.reducedSumTableBuffer); // Next do scan prefix on the histogram with partail sums that we just did ScanAddParams scanAddParams; scanAddParams.constantBuffer = buffers.constantBuffer; scanAddParams.sumTableBuffer = buffers.sumTableBuffer; scanAddParams.reducedSumTableBuffer = buffers.reducedSumTableBuffer; scanAddParams.reduceScanArgsBuffer = buffers.reduceScanArgsBuffer; ScanAdd(renderer, commandList, frameIndex, scanAddParams); commandList.PipelineBarrier(Renderer::PipelineBarrierType::ComputeWriteToComputeShaderRead, buffers.sumTableBuffer); } // Sort Scatter { ScatterParams scatterParams; scatterParams.shiftBits = shiftBits; scatterParams.constantBuffer = buffers.constantBuffer; scatterParams.keysBuffer = readKeyBuffer; scatterParams.valuesBuffer = readPayloadBuffer; scatterParams.sumTableBuffer = buffers.sumTableBuffer; scatterParams.writeKeysBuffer = writeKeyBuffer; scatterParams.writeValuesBuffer = writePayloadBuffer; scatterParams.countScatterArgsBuffer = buffers.countScatterArgsBuffer; Scatter(renderer, graphResources, commandList, frameIndex, scatterParams); } commandList.PipelineBarrier(Renderer::PipelineBarrierType::ComputeWriteToComputeShaderRead, writeKeyBuffer); commandList.PipelineBarrier(Renderer::PipelineBarrierType::ComputeWriteToComputeShaderRead, writePayloadBuffer); // Flip the buffers we read/write from for next pass std::swap(readKeyBuffer, writeKeyBuffer); std::swap(readPayloadBuffer, writePayloadBuffer); commandList.PopMarker(); } // Return the buffers with the sorted values, since we just swapped this will be the read buffers commandList.PipelineBarrier(Renderer::PipelineBarrierType::ComputeWriteToTransferSrc, readKeyBuffer); commandList.PipelineBarrier(Renderer::PipelineBarrierType::ComputeWriteToTransferSrc, readPayloadBuffer); ResultBuffers resultBuffers; resultBuffers.keysBuffer = readKeyBuffer; resultBuffers.valuesBuffer = readPayloadBuffer; return resultBuffers; } void SortUtils::SetupIndirectParameters(Renderer::Renderer* renderer, Renderer::RenderGraphResources& graphResources, Renderer::CommandList& commandList, u32 frameIndex, const SetupParams& params) { commandList.PushMarker("SetupIndirectParameters", Color::White); // Setup pipeline Renderer::ComputeShaderDesc shaderDesc; shaderDesc.path = "Sorting/SortSetupIndirectParameters.cs.hlsl"; Renderer::ComputePipelineDesc pipelineDesc; pipelineDesc.computeShader = renderer->LoadShader(shaderDesc); Renderer::ComputePipelineID pipeline = renderer->CreatePipeline(pipelineDesc); commandList.BeginPipeline(pipeline); // Bind descriptors _setupDescriptorSet.Bind("_numKeys", params.numKeysBuffer); _setupDescriptorSet.Bind("_constants", params.constantBuffer); _setupDescriptorSet.Bind("_countScatterArgs", params.countScatterArgsBuffer); _setupDescriptorSet.Bind("_reduceScanArgs", params.reduceScanArgsBuffer); commandList.BindDescriptorSet(Renderer::DescriptorSetSlot::PER_PASS, &_setupDescriptorSet, frameIndex); // Push constants struct SetupConstants { u32 maxThreadGroups; }; SetupConstants* constants = graphResources.FrameNew(); constants->maxThreadGroups = params.maxThreadGroups; commandList.PushConstant(constants, 0, sizeof(SetupConstants)); // Dispatch commandList.Dispatch(1, 1, 1); commandList.EndPipeline(pipeline); commandList.PopMarker(); } void SortUtils::Count(Renderer::Renderer* renderer, Renderer::RenderGraphResources& graphResources, Renderer::CommandList& commandList, u32 frameIndex, const CountParams& params) { commandList.PushMarker("Count", Color::White); // Setup pipeline Renderer::ComputeShaderDesc shaderDesc; shaderDesc.path = "Sorting/SortCount.cs.hlsl"; Renderer::ComputePipelineDesc pipelineDesc; pipelineDesc.computeShader = renderer->LoadShader(shaderDesc); Renderer::ComputePipelineID pipeline = renderer->CreatePipeline(pipelineDesc); commandList.BeginPipeline(pipeline); // Bind descriptors _countDescriptorSet.Bind("_constants", params.constantBuffer); _countDescriptorSet.Bind("_keys", params.keysBuffer); _countDescriptorSet.Bind("_sumTable", params.sumTableBuffer); commandList.BindDescriptorSet(Renderer::DescriptorSetSlot::PER_PASS, &_countDescriptorSet, frameIndex); // Push constants struct CountConstants { u32 shiftBits; }; CountConstants* constants = graphResources.FrameNew(); constants->shiftBits = params.shiftBits; commandList.PushConstant(constants, 0, sizeof(CountConstants)); // Dispatch commandList.DispatchIndirect(params.countScatterArgsBuffer, 0); commandList.EndPipeline(pipeline); commandList.PopMarker(); } void SortUtils::CountReduce(Renderer::Renderer* renderer, Renderer::CommandList& commandList, u32 frameIndex, const CountReduceParams& params) { commandList.PushMarker("CountReduce", Color::White); // Setup pipeline Renderer::ComputeShaderDesc shaderDesc; shaderDesc.path = "Sorting/SortCountReduce.cs.hlsl"; Renderer::ComputePipelineDesc pipelineDesc; pipelineDesc.computeShader = renderer->LoadShader(shaderDesc); Renderer::ComputePipelineID pipeline = renderer->CreatePipeline(pipelineDesc); commandList.BeginPipeline(pipeline); // Bind descriptors _countReduceDescriptorSet.Bind("_constants", params.constantBuffer); _countReduceDescriptorSet.Bind("_sumTable", params.sumTableBuffer); _countReduceDescriptorSet.Bind("_reducedSumTable", params.reducedSumTableBuffer); commandList.BindDescriptorSet(Renderer::DescriptorSetSlot::PER_PASS, &_countReduceDescriptorSet, frameIndex); // Dispatch commandList.DispatchIndirect(params.reduceScanArgsBuffer, 0); commandList.EndPipeline(pipeline); commandList.PopMarker(); } void SortUtils::Scan(Renderer::Renderer* renderer, Renderer::CommandList& commandList, u32 frameIndex, const ScanParams& params) { commandList.PushMarker("Scan", Color::White); // Setup pipeline Renderer::ComputeShaderDesc shaderDesc; shaderDesc.path = "Sorting/SortScan.cs.hlsl"; Renderer::ComputePipelineDesc pipelineDesc; pipelineDesc.computeShader = renderer->LoadShader(shaderDesc); Renderer::ComputePipelineID pipeline = renderer->CreatePipeline(pipelineDesc); commandList.BeginPipeline(pipeline); // Bind descriptors _scanDescriptorSet.Bind("_constants", params.constantBuffer); _scanDescriptorSet.Bind("_scanSrc", params.reducedSumTableBuffer); _scanDescriptorSet.Bind("_scanDst", params.reducedSumTableBuffer); //_scanDescriptorSet.Bind("_scanScratch", params.scratchBuffer); // Is this needed? This shader shouldn't use it but Vulkan might say that it needs to be bound anyway commandList.BindDescriptorSet(Renderer::DescriptorSetSlot::PER_PASS, &_scanDescriptorSet, frameIndex); // Dispatch commandList.Dispatch(1, 1, 1); commandList.EndPipeline(pipeline); commandList.PopMarker(); } void SortUtils::ScanAdd(Renderer::Renderer* renderer, Renderer::CommandList& commandList, u32 frameIndex, const ScanAddParams& params) { commandList.PushMarker("ScanAdd", Color::White); // Setup pipeline Renderer::ComputeShaderDesc shaderDesc; shaderDesc.path = "Sorting/SortScanAdd.cs.hlsl"; Renderer::ComputePipelineDesc pipelineDesc; pipelineDesc.computeShader = renderer->LoadShader(shaderDesc); Renderer::ComputePipelineID pipeline = renderer->CreatePipeline(pipelineDesc); commandList.BeginPipeline(pipeline); // Bind descriptors _scanAddDescriptorSet.Bind("_constants", params.constantBuffer); _scanAddDescriptorSet.Bind("_scanSrc", params.sumTableBuffer); _scanAddDescriptorSet.Bind("_scanDst", params.sumTableBuffer); _scanAddDescriptorSet.Bind("_scanScratch", params.reducedSumTableBuffer); commandList.BindDescriptorSet(Renderer::DescriptorSetSlot::PER_PASS, &_scanAddDescriptorSet, frameIndex); // Dispatch commandList.DispatchIndirect(params.reduceScanArgsBuffer, 0); commandList.EndPipeline(pipeline); commandList.PopMarker(); } void SortUtils::Scatter(Renderer::Renderer* renderer, Renderer::RenderGraphResources& graphResources, Renderer::CommandList& commandList, u32 frameIndex, const ScatterParams& params) { commandList.PushMarker("Scatter", Color::White); // Setup pipeline Renderer::ComputeShaderDesc shaderDesc; shaderDesc.path = "Sorting/SortScatter.cs.hlsl"; Renderer::ComputePipelineDesc pipelineDesc; pipelineDesc.computeShader = renderer->LoadShader(shaderDesc); Renderer::ComputePipelineID pipeline = renderer->CreatePipeline(pipelineDesc); commandList.BeginPipeline(pipeline); // Bind descriptors _scatterDescriptorSet.Bind("_constants", params.constantBuffer); _scatterDescriptorSet.Bind("_keys", params.keysBuffer); _scatterDescriptorSet.Bind("_values", params.valuesBuffer); _scatterDescriptorSet.Bind("_sumTable", params.sumTableBuffer); _scatterDescriptorSet.Bind("_writeKeys", params.writeKeysBuffer); _scatterDescriptorSet.Bind("_writeValues", params.writeValuesBuffer); commandList.BindDescriptorSet(Renderer::DescriptorSetSlot::PER_PASS, &_scatterDescriptorSet, frameIndex); // Push constants struct ScatterConstants { u32 shiftBits; }; ScatterConstants* constants = graphResources.FrameNew(); constants->shiftBits = params.shiftBits; commandList.PushConstant(constants, 0, sizeof(ScatterConstants)); // Dispatch commandList.DispatchIndirect(params.countScatterArgsBuffer, 0); commandList.EndPipeline(pipeline); commandList.PopMarker(); } /* * Copyright 2019, Offchain Labs, 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. */ #ifndef machinestate_hpp #define machinestate_hpp #include #include #include #include #include #include enum class Status { Extensive, Halted, Error }; struct TimeBounds { uint256_t lowerBoundBlock; uint256_t upperBoundBlock; uint256_t lowerBoundTimestamp; uint256_t upperBoundTimestamp; }; class CheckpointStorage; struct AssertionContext { TimeBounds timeBounds; Tuple inbox; uint32_t numSteps; bool didInboxInsn; uint64_t numGas; std::vector outMessage; std::vector logs; explicit AssertionContext(const TimeBounds& tb, Tuple inbox) : timeBounds(tb), inbox(std::move(inbox)), numSteps{0}, didInboxInsn(false), numGas{0} {} void executedInbox() { didInboxInsn = true; inbox = Tuple(); } }; struct MachineState { std::shared_ptr pool; std::vector code; value staticVal; value registerVal; Datastack stack; Datastack auxstack; Status state = Status::Extensive; uint64_t pc = 0; CodePoint errpc; AssertionContext context; MachineState(); MachineState(const std::vector& code_, const value& static_val_, std::shared_ptr pool_); bool initialize_machinestate(const std::string& contract_filename); std::vector marshalForProof(); BlockReason runOp(OpCode opcode); uint256_t hash() const; BlockReason isBlocked(uint256_t currentTime, bool newMessages) const; SaveResults checkpointState(CheckpointStorage& storage); bool restoreCheckpoint(const CheckpointStorage& storage, const std::vector& checkpoint_key); }; #endif /* machinestate_hpp */ #include "ForgeHammerItem.h" #include "mcpe/entity/player/Player.h" ForgeHammerItem::ForgeHammerItem():IC::Items("forge_hammer",IC::Items::ID::mForgeHammer-0x100) { setIcon("icpe_forge_hammer",0); setMaxStackSize(70); setCategory(CreativeItemCategory::TOOLS); setHandEquipped(); } void ForgeHammerItem::onCraftedBy(ItemInstance&item, Level&, Player&player)const { } #include #include #include #include #include #include using std::cerr; using std::cin; using std::cout; using std::endl; using std::string; int da_biao[] = {1, 1, 2, 6, 24, 120}; int hash(string s) { int num = 0; for (int i = 0; i < 6 - 1; i++) { int temp = 0; for (int j = i + 1; j < 6; j++) { if (s[j] < s[i]) temp++; } num += da_biao[6 - i - 1] * temp; } return num; } int BFS(string src, string dest) { int vis[725] = {0}, step[725] = {0}; int front, rear, s0, s1; string q[725]; front = rear = 0; s1 = hash(dest); q[rear++] = src; s0 = hash(src); vis[hash(src)] = 1; step[s0] = 0; while (front < rear) { string cur = q[front++]; s0 = hash(cur); if (s0 == s1) return step[s0]; for (int i = 0; i < 6 - 1; i++) { string next = cur; char tmp = next[i]; next[i] = next[i + 1]; next[i + 1] = tmp; int ts = hash(next); if (vis[ts] == 0) { vis[ts] = 1; step[ts] = step[s0] + 1; q[rear++] = next; } } } } int main() { string src, dest; while (cin >> src >> dest) { cout << BFS(src, dest) << endl; } return 0; }0 /* * Copyright 2018- The Pixie Authors. * * 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. * * SPDX-License-Identifier: Apache-2.0 */ #include "src/common/system/proc_parser.h" #include #include #include #include #include #include "src/common/fs/fs_wrapper.h" #include "src/common/system/config_mock.h" #include "src/common/testing/test_environment.h" #include "src/common/testing/testing.h" namespace px { namespace system { using ::testing::_; using ::testing::ElementsAre; using ::testing::IsEmpty; using ::testing::MatchesRegex; using ::testing::Return; using ::testing::ReturnArg; using ::testing::ReturnRef; using ::testing::UnorderedElementsAre; constexpr char kTestDataBasePath[] = "src/common/system"; namespace { std::string GetPathToTestDataFile(std::string_view fname) { return testing::TestFilePath(std::filesystem::path(kTestDataBasePath) / fname); } } // namespace class ProcParserTest : public ::testing::Test { protected: ProcParserTest() : proc_path_(GetPathToTestDataFile("testdata/proc")) {} void SetUp() override { system::MockConfig sysconfig; EXPECT_CALL(sysconfig, HasConfig()).WillRepeatedly(Return(true)); EXPECT_CALL(sysconfig, PageSize()).WillRepeatedly(Return(4096)); EXPECT_CALL(sysconfig, KernelTicksPerSecond()).WillRepeatedly(Return(10000000)); EXPECT_CALL(sysconfig, ConvertToRealTime(_)).WillRepeatedly(ReturnArg<0>()); EXPECT_CALL(sysconfig, proc_path()).WillRepeatedly(ReturnRef(proc_path_)); parser_ = std::make_unique(sysconfig); bytes_per_page_ = sysconfig.PageSize(); } std::filesystem::path proc_path_; std::unique_ptr parser_; int bytes_per_page_ = 0; }; TEST_F(ProcParserTest, ParseNetworkStat) { ProcParser::NetworkStats stats; PL_CHECK_OK(parser_->ParseProcPIDNetDev(123, &stats)); // The expeted values are from the test file above. EXPECT_EQ(54504114, stats.rx_bytes); EXPECT_EQ(65296, stats.rx_packets); EXPECT_EQ(0, stats.rx_drops); EXPECT_EQ(0, stats.rx_errs); EXPECT_EQ(4258632, stats.tx_bytes); EXPECT_EQ(39739, stats.tx_packets); EXPECT_EQ(0, stats.tx_drops); EXPECT_EQ(0, stats.tx_errs); } TEST_F(ProcParserTest, ParseStatIO) { ProcParser::ProcessStats stats; PL_CHECK_OK(parser_->ParseProcPIDStatIO(123, &stats)); // The expeted values are from the test file above. EXPECT_EQ(5405203, stats.rchar_bytes); EXPECT_EQ(1239158, stats.wchar_bytes); EXPECT_EQ(17838080, stats.read_bytes); EXPECT_EQ(634880, stats.write_bytes); } TEST_F(ProcParserTest, ParsePidStat) { ProcParser::ProcessStats stats; PL_CHECK_OK(parser_->ParseProcPIDStat(123, &stats)); // The expeted values are from the test file above. EXPECT_EQ("ibazel", stats.process_name); EXPECT_EQ(800, stats.utime_ns); EXPECT_EQ(2300, stats.ktime_ns); EXPECT_EQ(13, stats.num_threads); EXPECT_EQ(55, stats.major_faults); EXPECT_EQ(1799, stats.minor_faults); EXPECT_EQ(114384896, stats.vsize_bytes); EXPECT_EQ(2577 * bytes_per_page_, stats.rss_bytes); } TEST_F(ProcParserTest, ParseStat) { ProcParser::SystemStats stats; PL_CHECK_OK(parser_->ParseProcStat(&stats)); // The expected values are from the test file above. EXPECT_EQ(248758, stats.cpu_utime_ns); EXPECT_EQ(78314, stats.cpu_ktime_ns); } TEST_F(ProcParserTest, ParseMemInfo) { ProcParser::SystemStats stats; PL_CHECK_OK(parser_->ParseProcMemInfo(&stats)); // The expected values are from the test file above. EXPECT_EQ(67228110848, stats.mem_total_bytes); EXPECT_EQ(17634656256, stats.mem_free_bytes); EXPECT_EQ(51960180736, stats.mem_available_bytes); EXPECT_EQ(6654636032, stats.mem_buffer_bytes); EXPECT_EQ(25549463552, stats.mem_cached_bytes); EXPECT_EQ(24576, stats.mem_swap_cached_bytes); EXPECT_EQ(28388524032, stats.mem_active_bytes); EXPECT_EQ(15734595584, stats.mem_inactive_bytes); } TEST_F(ProcParserTest, ParsePIDStatus) { ProcParser::ProcessStatus stats; PL_CHECK_OK(parser_->ParseProcPIDStatus(789, &stats)); EXPECT_EQ(24612 * 1024, stats.vm_peak_bytes); EXPECT_EQ(24612 * 1024, stats.vm_size_bytes); EXPECT_EQ(0 * 1024, stats.vm_lck_bytes); EXPECT_EQ(0 * 1024, stats.vm_pin_bytes); EXPECT_EQ(9936 * 1024, stats.vm_hwm_bytes); EXPECT_EQ(9900 * 1024, stats.vm_rss_bytes); EXPECT_EQ(3520 * 1024, stats.rss_anon_bytes); EXPECT_EQ(6380 * 1024, stats.rss_file_bytes); EXPECT_EQ(0 * 1024, stats.rss_shmem_bytes); EXPECT_EQ(3640 * 1024, stats.vm_data_bytes); EXPECT_EQ(132 * 1024, stats.vm_stk_bytes); EXPECT_EQ(2044 * 1024, stats.vm_exe_bytes); EXPECT_EQ(5868 * 1024, stats.vm_lib_bytes); EXPECT_EQ(76 * 1024, stats.vm_pte_bytes); EXPECT_EQ(0 * 1024, stats.vm_swap_bytes); EXPECT_EQ(0 * 1024, stats.hugetlb_pages_bytes); EXPECT_EQ(2, stats.voluntary_ctxt_switches); EXPECT_EQ(2, stats.nonvoluntary_ctxt_switches); } TEST_F(ProcParserTest, ParsePIDStatusBadUnit) { ProcParser::ProcessStatus stats; PL_CHECK_OK(parser_->ParseProcPIDStatus(1, &stats)); // Bad units. EXPECT_EQ(-1, stats.vm_peak_bytes); // Bad units. EXPECT_EQ(-1, stats.vm_size_bytes); // Missing key. EXPECT_EQ(0, stats.vm_lck_bytes); // Exists, and units OK. EXPECT_EQ(1 * 1024, stats.vm_pin_bytes); // Exists, and no units. EXPECT_EQ(123, stats.voluntary_ctxt_switches); } TEST_F(ProcParserTest, ParsePIDSMaps) { std::vector stats; PL_CHECK_OK(parser_->ParseProcPIDSMaps(789, &stats)); EXPECT_EQ(stats.size(), 5); ASSERT_GT(stats.size(), 0); auto& first = stats.front(); EXPECT_EQ("55e816b37000-55e816b65000", first.address); EXPECT_EQ("00000000", first.offset); EXPECT_EQ("/usr/bin/vim.basic", first.pathname); EXPECT_EQ(184 * 1024, first.size_bytes); EXPECT_EQ(4 * 1024, first.kernel_page_size_bytes); EXPECT_EQ(4 * 1024, first.mmu_page_size_bytes); EXPECT_EQ(184 * 1024, first.rss_bytes); EXPECT_EQ(184 * 1024, first.pss_bytes); EXPECT_EQ(0 * 1024, first.shared_clean_bytes); EXPECT_EQ(0 * 1024, first.shared_dirty_bytes); EXPECT_EQ(184 * 1024, first.private_clean_bytes); EXPECT_EQ(0 * 1024, first.private_dirty_bytes); EXPECT_EQ(184 * 1024, first.referenced_bytes); EXPECT_EQ(0 * 1024, first.anonymous_bytes); EXPECT_EQ(0 * 1024, first.lazy_free_bytes); EXPECT_EQ(0 * 1024, first.anon_huge_pages_bytes); EXPECT_EQ(0 * 1024, first.shmem_pmd_mapped_bytes); EXPECT_EQ(0 * 1024, first.file_pmd_mapped_bytes); EXPECT_EQ(0 * 1024, first.shared_hugetlb_bytes); EXPECT_EQ(0 * 1024, first.private_hugetlb_bytes); EXPECT_EQ(0 * 1024, first.swap_bytes); EXPECT_EQ(0 * 1024, first.swap_pss_bytes); EXPECT_EQ(0 * 1024, first.locked_bytes); auto& last = stats.back(); EXPECT_EQ("ffffffffff600000-ffffffffff601000", last.address); EXPECT_EQ("00000000", last.offset); EXPECT_EQ("[vsyscall]", last.pathname); EXPECT_EQ(4 * 1024, last.size_bytes); EXPECT_EQ(4 * 1024, last.kernel_page_size_bytes); EXPECT_EQ(4 * 1024, last.mmu_page_size_bytes); EXPECT_EQ(0 * 1024, last.rss_bytes); EXPECT_EQ(0 * 1024, last.pss_bytes); EXPECT_EQ(0 * 1024, last.shared_clean_bytes); EXPECT_EQ(0 * 1024, last.shared_dirty_bytes); EXPECT_EQ(0 * 1024, last.private_clean_bytes); EXPECT_EQ(0 * 1024, last.private_dirty_bytes); EXPECT_EQ(0 * 1024, last.referenced_bytes); EXPECT_EQ(0 * 1024, last.anonymous_bytes); EXPECT_EQ(0 * 1024, last.lazy_free_bytes); EXPECT_EQ(0 * 1024, last.anon_huge_pages_bytes); EXPECT_EQ(0 * 1024, last.shmem_pmd_mapped_bytes); EXPECT_EQ(0 * 1024, last.file_pmd_mapped_bytes); EXPECT_EQ(0 * 1024, last.shared_hugetlb_bytes); EXPECT_EQ(0 * 1024, last.private_hugetlb_bytes); EXPECT_EQ(0 * 1024, last.swap_bytes); EXPECT_EQ(0 * 1024, last.swap_pss_bytes); EXPECT_EQ(0 * 1024, last.locked_bytes); EXPECT_EQ("[anonymous]", stats[3].pathname); } TEST_F(ProcParserTest, read_pid_start_time) { ASSERT_OK_AND_EQ(parser_->GetPIDStartTimeTicks(123), 14329); } TEST_F(ProcParserTest, read_pid_cmdline) { EXPECT_THAT("/usr/lib/slack/slack --force-device-scale-factor=1.5 --high-dpi-support=1", parser_->GetPIDCmdline(123)); } TEST_F(ProcParserTest, read_pid_metadata_null) { EXPECT_THAT("/usr/lib/at-spi2-core/at-spi2-registryd --use-gnome-session", parser_->GetPIDCmdline(456)); } // This test does not work because bazel uses symlinks itself, // which then causes ReadProcPIDFDLink to resolve the wrong link. TEST_F(ProcParserTest, read_proc_fd_link) { { // Bazel doesn't copy symlink testdata as symlinks, so we create the missing symlink testdata // here. ASSERT_OK( fs::CreateSymlinkIfNotExists("/dev/null", GetPathToTestDataFile("testdata/proc/123/fd/0"))); ASSERT_OK( fs::CreateSymlinkIfNotExists("/foobar", GetPathToTestDataFile("testdata/proc/123/fd/1"))); ASSERT_OK(fs::CreateSymlinkIfNotExists("socket:[12345]", GetPathToTestDataFile("testdata/proc/123/fd/2"))); } std::string out; Status s; s = parser_->ReadProcPIDFDLink(123, 0, &out); EXPECT_OK(s); EXPECT_EQ("/dev/null", out); s = parser_->ReadProcPIDFDLink(123, 1, &out); EXPECT_OK(s); EXPECT_EQ("/foobar", out); s = parser_->ReadProcPIDFDLink(123, 2, &out); EXPECT_OK(s); EXPECT_EQ("socket:[12345]", out); s = parser_->ReadProcPIDFDLink(123, 3, &out); EXPECT_NOT_OK(s); } TEST_F(ProcParserTest, ReadUIDs) { ProcParser::ProcUIDs uids; ASSERT_OK(parser_->ReadUIDs(123, &uids)); EXPECT_EQ("33", uids.real); EXPECT_EQ("34", uids.effective); EXPECT_EQ("35", uids.saved_set); EXPECT_EQ("36", uids.filesystem); } TEST_F(ProcParserTest, ReadNSPid) { std::vector ns_pids; ASSERT_OK(parser_->ReadNSPid(123, &ns_pids)); EXPECT_THAT(ns_pids, ElementsAre("2578", "24", "25")); } bool operator==(const ProcParser::MountInfo& lhs, const ProcParser::MountInfo& rhs) { return lhs.dev == rhs.dev && lhs.root == rhs.root && lhs.mount_point == rhs.mount_point; } TEST_F(ProcParserTest, ReadMountInfos) { { std::vector mount_infos; EXPECT_OK(parser_->ReadMountInfos(123, &mount_infos)); EXPECT_THAT(mount_infos, ElementsAre( ProcParser::MountInfo{ "260:3", "/", "/", }, ProcParser::MountInfo{"259:3", "/test_foo", "/foo"}, ProcParser::MountInfo{"260:3", "/test_bar", "/bar"})); } { std::vector mount_infos; EXPECT_OK(parser_->ReadMountInfos(1, &mount_infos)); EXPECT_THAT(mount_infos, ElementsAre(ProcParser::MountInfo{"259:3", "/", "/tmp"})); } } TEST_F(ProcParserTest, GetMapPaths) { { EXPECT_OK_AND_THAT( parser_->GetMapPaths(123), UnorderedElementsAre( "/dev/zero (deleted)", "/lib/x86_64-linux-gnu/libc-2.28.so", "/lib/x86_64-linux-gnu/libdl-2.28.so", "/usr/lib/x86_64-linux-gnu/libcrypto.so.1.1", "/usr/lib/x86_64-linux-gnu/libssl.so.1.1", "/usr/sbin/nginx", "/[aio] (deleted)", "[heap]", "[stack]", "[uprobes]", "[vdso]", "[vsyscall]", "[vvar]")); } } // Check ProcParser can detect itself. TEST(ProcParserGetExePathTest, CheckTestProcess) { // Since bazel prepares test files as symlinks, creating testdata/proc/123/exe symlink would // result into bazel creating another symlink to it. So instead we just use the actual system // config to read the actual exe path of this test process. ProcParser parser(system::Config::GetInstance()); const std::string kExpectedPathRegex = ".*/src/common/system/proc_parser_test"; ASSERT_OK_AND_ASSIGN(std::filesystem::path proc_exe, parser.GetExePath(getpid())); EXPECT_THAT(proc_exe.string(), MatchesRegex(kExpectedPathRegex)); } } // namespace system } // namespace px dm-heom/include/heom/command_line_error.hpp // This file is part of DM-HEOM (https://github.com/noma/dm-heom) // // Copyright (c) 2015-2019 , Zuse Institute Berlin // // Licensed under the 3-clause BSD License, see accompanying LICENSE, // CONTRIBUTORS.md, and README.md for further information. #ifndef heom_command_line_error_hpp #define heom_command_line_error_hpp #include #include namespace heom { /** * Custom exception class for ocl configuration errors. */ class command_line_error : public std::runtime_error { public: //command_line_error(const std::string& msg) : runtime_error("heom::command_line_error: " + msg) { }; command_line_error(const std::string& msg) : runtime_error(msg) { }; }; } // namespace heom #endif // heom_command_line_error_hpp mpsitech/wznm-WhizniumSBE /** * \file WznmMVersion_vecs.cpp * database access for table TblWznmMVersion (implementation of vectors) * \copyright (C) 2016-2020 MPSI Technologies GmbH * \author (auto-generation) * \date created: 5 Dec 2020 */ // IP header --- ABOVE using namespace std; using namespace Sbecore; using namespace Xmlio; /****************************************************************************** class TblWznmMVersion::VecVState ******************************************************************************/ uint TblWznmMVersion::VecVState::getIx( const string& sref ) { string s = StrMod::lc(sref); if (s == "newcre") return NEWCRE; if (s == "newimp") return NEWIMP; if (s == "dsndeploy") return DSNDEPLOY; if (s == "dsnglobal") return DSNGLOBAL; if (s == "dsndbstr") return DSNDBSTR; if (s == "dsnbscui") return DSNBSCUI; if (s == "dsnimpexp") return DSNIMPEXP; if (s == "dsnoppack") return DSNOPPACK; if (s == "dsncustjob") return DSNCUSTJOB; if (s == "dsngenui") return DSNGENUI; if (s == "dsncustui") return DSNCUSTUI; if (s == "dsngenjtr") return DSNGENJTR; if (s == "dsncustjtr") return DSNCUSTJTR; if (s == "ready") return READY; if (s == "abandon") return ABANDON; return(0); }; string TblWznmMVersion::VecVState::getSref( const uint ix ) { if (ix == NEWCRE) return("newcre"); if (ix == NEWIMP) return("newimp"); if (ix == DSNDEPLOY) return("dsndeploy"); if (ix == DSNGLOBAL) return("dsnglobal"); if (ix == DSNDBSTR) return("dsndbstr"); if (ix == DSNBSCUI) return("dsnbscui"); if (ix == DSNIMPEXP) return("dsnimpexp"); if (ix == DSNOPPACK) return("dsnoppack"); if (ix == DSNCUSTJOB) return("dsncustjob"); if (ix == DSNGENUI) return("dsngenui"); if (ix == DSNCUSTUI) return("dsncustui"); if (ix == DSNGENJTR) return("dsngenjtr"); if (ix == DSNCUSTJTR) return("dsncustjtr"); if (ix == READY) return("ready"); if (ix == ABANDON) return("abandon"); return(""); }; string TblWznmMVersion::VecVState::getTitle( const uint ix , const uint ixWznmVLocale ) { if (ixWznmVLocale == 1) { if (ix == NEWCRE) return("newly created"); if (ix == NEWIMP) return("newly imported"); if (ix == DSNDEPLOY) return("design phase, deployment information imported"); if (ix == DSNGLOBAL) return("design phase, global features imported"); if (ix == DSNDBSTR) return("design phase, database structure imported"); if (ix == DSNBSCUI) return("design phase, basic user interface structure imported"); if (ix == DSNIMPEXP) return("design phase, import/export structure imported"); if (ix == DSNOPPACK) return("design phase, operation pack structure imported"); if (ix == DSNCUSTJOB) return("design phase, custom jobs imported"); if (ix == DSNGENUI) return("design phase, user interface generated"); if (ix == DSNCUSTUI) return("design phase, custom user interface features applied"); if (ix == DSNGENJTR) return("design phase, job tree generated"); if (ix == DSNCUSTJTR) return("design phase, custom job tree features applied"); if (ix == READY) return("build-ready"); if (ix == ABANDON) return("abandonned"); return(getSref(ix)); }; return(""); }; void TblWznmMVersion::VecVState::fillFeed( const uint ixWznmVLocale , Feed& feed ) { feed.clear(); for (unsigned int i = 1; i <= 15; i++) feed.appendIxSrefTitles(i, getSref(i), getTitle(i, ixWznmVLocale)); }; /****************************************************************************** class TblWznmMVersion::VecWDbmstype ******************************************************************************/ uint TblWznmMVersion::VecWDbmstype::getIx( const string& srefs ) { uint ix = 0; vector ss; StrMod::srefsToVector(StrMod::lc(srefs), ss); for (unsigned int i = 0; i < ss.size(); i++) { if (ss[i] == "mararia") ix |= MARARIA; else if (ss[i] == "marinno") ix |= MARINNO; else if (ss[i] == "myinno") ix |= MYINNO; else if (ss[i] == "myisam") ix |= MYISAM; else if (ss[i] == "pg") ix |= PG; else if (ss[i] == "lite") ix |= LITE; }; return(ix); }; void TblWznmMVersion::VecWDbmstype::getIcs( const uint ix , set& ics ) { ics.clear(); for (unsigned int i = 1; i < (2*LITE); i *= 2) if (ix & i) ics.insert(i); }; string TblWznmMVersion::VecWDbmstype::getSrefs( const uint ix ) { vector ss; string srefs; if (ix & MARARIA) ss.push_back("mararia"); if (ix & MARINNO) ss.push_back("marinno"); if (ix & MYINNO) ss.push_back("myinno"); if (ix & MYISAM) ss.push_back("myisam"); if (ix & PG) ss.push_back("pg"); if (ix & LITE) ss.push_back("lite"); StrMod::vectorToString(ss, srefs); return(srefs); }; string TblWznmMVersion::VecWDbmstype::getTitle( const uint ix , const uint ixWznmVLocale ) { if (ixWznmVLocale == 1) { if (ix == MARARIA) return("MariaDB Aria"); if (ix == MARINNO) return("MariaDB InnoDB"); if (ix == MYINNO) return("MySQL InnoDB"); if (ix == MYISAM) return("MySQL MyISAM"); if (ix == PG) return("PostgreSQL"); if (ix == LITE) return("SQLite"); return(getSrefs(ix)); }; return(""); }; void TblWznmMVersion::VecWDbmstype::fillFeed( const uint ixWznmVLocale , Feed& feed ) { feed.clear(); for (unsigned int i = 1; i <= LITE; i *= 2) feed.appendIxSrefTitles(i, getSrefs(i), getTitle(i, ixWznmVLocale)); }; /****************************************************************************** class TblWznmMVersion::VecWOption ******************************************************************************/ uint TblWznmMVersion::VecWOption::getIx( const string& srefs ) { uint ix = 0; vector ss; StrMod::srefsToVector(StrMod::lc(srefs), ss); for (unsigned int i = 0; i < ss.size(); i++) { if (ss[i] == "accgrpreg") ix |= ACCGRPREG; else if (ss[i] == "accnogoall") ix |= ACCNOGOALL; else if (ss[i] == "apimon") ix |= APIMON; else if (ss[i] == "dbsmon") ix |= DBSMON; else if (ss[i] == "ddspub") ix |= DDSPUB; else if (ss[i] == "uasrv") ix |= UASRV; }; return(ix); }; void TblWznmMVersion::VecWOption::getIcs( const uint ix , set& ics ) { ics.clear(); for (unsigned int i = 1; i < (2*UASRV); i *= 2) if (ix & i) ics.insert(i); }; string TblWznmMVersion::VecWOption::getSrefs( const uint ix ) { vector ss; string srefs; if (ix & ACCGRPREG) ss.push_back("accgrpreg"); if (ix & ACCNOGOALL) ss.push_back("accnogoall"); if (ix & APIMON) ss.push_back("apimon"); if (ix & DBSMON) ss.push_back("dbsmon"); if (ix & DDSPUB) ss.push_back("ddspub"); if (ix & UASRV) ss.push_back("uasrv"); StrMod::vectorToString(ss, srefs); return(srefs); }; string TblWznmMVersion::VecWOption::getTitle( const uint ix , const uint ixWznmVLocale ) { if (ixWznmVLocale == 1) { if (ix == ACCGRPREG) return("view access for regular users to all grp records"); if (ix == ACCNOGOALL) return("access for all users to no-grp/own records"); if (ix == APIMON) return("monitoring via API"); if (ix == DBSMON) return("monitoring to database"); if (ix == DDSPUB) return("DDS publisher"); if (ix == UASRV) return("OPC UA server"); return(getSrefs(ix)); }; return(""); }; void TblWznmMVersion::VecWOption::fillFeed( const uint ixWznmVLocale , Feed& feed ) { feed.clear(); for (unsigned int i = 1; i <= UASRV; i *= 2) feed.appendIxSrefTitles(i, getSrefs(i), getTitle(i, ixWznmVLocale)); }; #include "DQM/RPCMonitorClient/interface/RPCDaqInfo.h" #include "DataFormats/FEDRawData/interface/FEDNumbering.h" #include "CondFormats/RunInfo/interface/RunInfo.h" #include "CondFormats/RunInfo/interface/RunSummary.h" #include "CondFormats/DataRecord/interface/RunSummaryRcd.h" #include "FWCore/Framework/interface/ESHandle.h" #include "FWCore/Framework/interface/EventSetup.h" RPCDaqInfo::RPCDaqInfo(const edm::ParameterSet& ps) { FEDRange_.first = ps.getUntrackedParameter("MinimumRPCFEDId", 790); FEDRange_.second = ps.getUntrackedParameter("MaximumRPCFEDId", 792); NumberOfFeds_ =FEDRange_.second - FEDRange_.first +1; numberOfDisks_ = ps.getUntrackedParameter("NumberOfEndcapDisks", 4); init_=false; } RPCDaqInfo::~RPCDaqInfo(){} void RPCDaqInfo::beginJob(){} void RPCDaqInfo::dqmEndLuminosityBlock(DQMStore::IBooker & ibooker, DQMStore::IGetter & igetter, edm::LuminosityBlock const & LB, edm::EventSetup const& iSetup){ edm::eventsetup::EventSetupRecordKey recordKey(edm::eventsetup::EventSetupRecordKey::TypeTag::findType("RunInfoRcd")); if(!init_){this->myBooker(ibooker);} if(0 != iSetup.find( recordKey ) ) { //get fed summary information edm::ESHandle sumFED; iSetup.get().get(sumFED); std::vector FedsInIds= sumFED->m_fed_in; int FedCount=0; //loop on all active feds for(unsigned int fedItr=0;fedItr=FEDRange_.first && fedID<=FEDRange_.second) ++FedCount; } //Fill active fed fraction ME if(NumberOfFeds_>0) DaqFraction_->Fill( FedCount/NumberOfFeds_); else DaqFraction_->Fill(-1); }else{ DaqFraction_->Fill(-1); return; } } void RPCDaqInfo::dqmEndJob(DQMStore::IBooker &, DQMStore::IGetter &){} void RPCDaqInfo::myBooker(DQMStore::IBooker & ibooker){ //fraction of alive FEDs ibooker.setCurrentFolder("RPC/EventInfo/DAQContents"); int limit = numberOfDisks_; if(numberOfDisks_ < 2) limit = 2; for (int i = -1 * limit; i<= limit;i++ ){//loop on wheels and disks if (i>-3 && i<3){//wheels std::stringstream streams; streams << "RPC_Wheel" << i; daqWheelFractions[i+2] = ibooker.bookFloat(streams.str()); daqWheelFractions[i+2]->Fill(-1); } if (i == 0 || i > numberOfDisks_ || i< (-1 * numberOfDisks_))continue; int offset = numberOfDisks_; if (i>0) offset --; //used to skip case equale to zero std::stringstream streams; streams << "RPC_Disk" << i; daqDiskFractions[i+2] = ibooker.bookFloat(streams.str()); daqDiskFractions[i+2]->Fill(-1); } //daq summary for RPCs ibooker.setCurrentFolder("RPC/EventInfo"); DaqFraction_ = ibooker.bookFloat("DAQSummary"); DaqMap_ = ibooker.book2D( "DAQSummaryMap","RPC DAQ Summary Map",15, -7.5, 7.5, 12, 0.5 ,12.5); //customize the 2d histo std::stringstream BinLabel; for (int i= 1 ; i<=15; i++){ BinLabel.str(""); if(i<13){ BinLabel<<"Sec"<setBinLabel(i,BinLabel.str(),2); } BinLabel.str(""); if(i<5) BinLabel<<"Disk"<11) BinLabel<<"Disk"<setBinLabel(i,BinLabel.str(),1); } init_=true; } #include "../Bitset.hpp" #include // std::cout, std::endl void TestAreAllOnAndOff(); int main() { TestAreAllOnAndOff(); return 0; } void TestAreAllOnAndOff() { NM::Bitset::Bitset<10> bitset; for(size_t i = 0; i < 10; ++i) { bitset.On(i + 1); } std::cout << "AreAllOn() Test:" << std::endl; if(bitset.AreAllOn()) { std::cout << "Passed!" << std::endl; } else { std::cout << "Failed..." << std::endl; } bitset.Print(std::cout); std::cout << std::endl; bitset.Off(5); if(bitset.AreAllOn()) { std::cout << "Failed..." << std::endl; } else { std::cout << "Passed!" << std::endl; } bitset.Print(std::cout); std::cout << std::endl; bitset.Toggle(5); if(bitset.AreAllOn()) { std::cout << "Passed!" << std::endl; } else { std::cout << "Failed..." << std::endl; } bitset.Print(std::cout); std::cout << std::endl; for(size_t i = 0; i < 10; ++i) { bitset.Off(i + 1); } std::cout << "AreAllOff() Test:" << std::endl; if(bitset.AreAllOff()) { std::cout << "Passed!" << std::endl; } else { std::cout << "Failed..." << std::endl; } bitset.Print(std::cout); std::cout << std::endl; bitset.Toggle(5); if(bitset.AreAllOff()) { std::cout << "Failed..." << std::endl; } else { std::cout << "Passed!" << std::endl; } bitset.Print(std::cout); std::cout << std::endl; }// Symbol table - implementation file. // Copyright (C) 2017, 2018 <> // // All rights reserved. // // See the LICENSE file for more details. #include "../include/SymbolTable.h" #include #include #include #include namespace cparser { STType *SymbolTable::allocType(STTypeKind kind) { STType *type = new STType(kind); typePool.push_back(type); return type; } STObject * SymbolTable::allocObject(const char *name, STObjectKind kind, STType *type) { STObject *obj = new STObject(name, kind, type); objectPool.push_back(obj); return obj; } STScope *SymbolTable::allocScope() { STScope *scope = new STScope(); scopePool.push_back(scope); return scope; } SymbolTable::SymbolTable() { level = -1; topScope = allocScope(); topScope->outer = nullptr; globalScope = topScope; // Built-in types // char: 1 byte charType = allocType(STTK_CHAR); charType->size = 1; charType->isSigned = true; // char: 2 bytes shortType = allocType(STTK_SHORT); shortType->size = 2; shortType->isSigned = true; // int: 4 bytes intType = allocType(STTK_INT); intType->size = 4; intType->isSigned = true; // int: 4 bytes unsignedType = allocType(STTK_UNSIGNED); unsignedType->size = 4; unsignedType->isSigned = false; // int: 4 bytes longType = allocType(STTK_LONG); longType->size = 4; longType->isSigned = true; // float: 4 bytes floatType = allocType(STTK_FLOAT); floatType->size = 4; // double: 8 bytes doubleType = allocType(STTK_DOUBLE); doubleType->size = 8; // int: 4 bytes voidType = allocType(STTK_VOID); voidType->size = 4; noType = allocType(STTK_NONE); insert("NOTYPE", STOK_TYPE, noType); nullType = allocType(STTK_POINTER); // Dummy object noObj = allocObject("noObj", STOK_VAR, noType); // Built in types insert("__builtin_va_list", STOK_TYPE, noType); } SymbolTable::~SymbolTable() { for (unsigned i = 0; i < scopePool.size(); i++) delete scopePool[i]; for (unsigned i = 0; i < objectPool.size(); i++) delete objectPool[i]; for (unsigned i = 0; i < typePool.size(); i++) delete typePool[i]; } STObject *SymbolTable::insert(const char *name, STObjectKind kind, STType *type) { // Create object node STObject *obj = allocObject(name, kind, type); STObject *p = nullptr, *last = nullptr; if (kind == STOK_VAR) topScope->nVars++; else if (kind == STOK_PAR) topScope->nPars++; obj->level = level; // Append object node p = topScope->locals; last = nullptr; while (p != nullptr) { if (strcmp(p->name, name) == 0) return noObj; last = p; p = p->next; } if (last == nullptr) topScope->locals = obj; else last->next = obj; return obj; } STObject *SymbolTable::find(const char *name) { for (STScope *s = topScope; s != nullptr; s = s->outer) for (STObject *p = s->locals; p != nullptr; p = p->next) if (strcmp(p->name, name) == 0) return p; return noObj; } void SymbolTable::openScope(void) { STScope *s = allocScope(); s->outer = topScope; topScope = s; topScope->size = 0; level++; } void SymbolTable::closeScope(void) { topScope = topScope->outer; level--; } void SymbolTable::setTopScope(STScope *s) { topScope = s; } STScope *SymbolTable::getTopScope() { return topScope; } bool SymbolTable::isIntegralType(STType *t) { assert(t != nullptr && "Unexpected null pointer!"); return (t == charType || t == intType || t == unsignedType || t == shortType || t == longType); } bool SymbolTable::isRealType(STType *t) { assert(t != nullptr && "Unexpected null pointer!"); return (t == floatType || t == doubleType); } bool SymbolTable::isArithmeticType(STType *t) { assert(t != nullptr && "Unexpected null pointer!"); return (isIntegralType(t) || isRealType(t)); } bool SymbolTable::isPointerType(STType *t) { assert(t != nullptr && "Unexpected null pointer!"); return t->kind == STTK_POINTER; } bool SymbolTable::isScalarType(STType *t) { return isPointerType(t) || isArithmeticType(t); } bool SymbolTable::isFunctionPointerType(STType *t) { return t->kind == STTK_POINTER && t->baseType->kind == STTK_FUNCTION; } bool SymbolTable::equalFunctionPointerTypes(STType *t1, STType *t2) { // TODO: Check if parameters of the function types match. return (isFunctionPointerType(t1) && isFunctionPointerType(t2) && (t1->baseType->funcType == t2->baseType->funcType)); } bool SymbolTable::equalBasePointerTypes(STType *t1, STType *t2) { return (t1->kind == STTK_POINTER && t2->kind == STTK_POINTER && (t1->baseType == t2->baseType)); } // Two pointer types with the same type qualifiers are compatible if they // point to objects of compatible type. The composite type for two compatible // pointer types is the similarly qualified pointer to the composite type. bool SymbolTable::compatible(STType *t1, STType *t2) { assert(t1 != nullptr && t2 == nullptr && "Unexpected null pointer!"); return ((t1 == t2) || (isIntegralType(t1) && isIntegralType(t2)) || (isIntegralType(t1) && t2->kind == STTK_POINTER) || (isIntegralType(t2) && t1->kind == STTK_POINTER) || (t1->kind == STTK_POINTER && t2->baseType == noType) || (t2->kind == STTK_POINTER && t1->baseType == noType) || ((t1->kind == STTK_POINTER && t2->kind == STTK_POINTER) && compatible(t1->baseType, t2->baseType))); } bool SymbolTable::assignable(STType *t1, STType *t2) { assert(t1 != nullptr && t2 == nullptr && "Unexpected null pointer!"); return ((isArithmeticType(t1) && isArithmeticType(t2)) || (t1->kind == STTK_POINTER && t2->baseType == noType) || (t2->kind == STTK_POINTER && t1->baseType == noType) || ((t1->kind == STTK_POINTER && t2->kind == STTK_POINTER) && (t1->baseType == t2->baseType))); } bool SymbolTable::convertible(STType *t1, STType *t2) { return true; } } // namespace cparser 0 #include #include namespace zboss { using namespace std; Vector2D ContainerComponent::getPosition() const { return rawPosition; } void ContainerComponent::setPosition(const Vector2D& pos) { setPosition(pos.x, pos.y); } void ContainerComponent::setPosition(int x, int y) { rawPosition.x = x; rawPosition.y = y; translation = { {1., 0., (float)x}, {0., 1., (float)y}, {0., 0., 1.} }; localCachedTransform = translation * rotation; cachePosition(); } float ContainerComponent::getRotation() const { return rawAngle; } void ContainerComponent::setRotation(float angle) { rawAngle = angle; rotation = { {cos(angle), sin(angle), 0.0}, {-sin(angle), cos(angle), 0.0}, {0.0, 0.0, 1.0} }; localCachedTransform = translation * rotation; cachePosition(); } float ContainerComponent::getScale() const { return rawScale; } void ContainerComponent::setScale(float scale) { rawScale = scale; translation = translation * scale; localCachedTransform = translation * rotation; cachePosition(); } Matrix<3, 3> ContainerComponent::getCachedTransform() const { return localCachedTransform; } void ContainerComponent::cachePosition() { Matrix<3, 1> origin = { {0.0}, {0.0}, {1.0} }; Matrix<3, 1> transformed = parentCachedTransform * localCachedTransform * origin; cachedPosition = Vector2D(transformed(0, 0), transformed(1, 0)); } Vector2D ContainerComponent::getAbsolutePosition() { Matrix<3, 3> current_parent_pm_transform; auto parent = entity->find_first_ancestor_by_type(); if (parent != nullptr) { /*auto pnode = static_pointer_cast(parent); current_parent_pm_transform = pnode->get_pm_transform();*/ current_parent_pm_transform = parent->getComponent().getCachedTransform(); } if (current_parent_pm_transform != parentCachedTransform) { parentCachedTransform = current_parent_pm_transform; cachePosition(); } return cachedPosition; } float ContainerComponent::getAbsoluteRotation() const { float abs_angle = 0; shared_ptr e = entity; // shared_ptr e2 = make_shared(entity); // const Entity* e = entity; while (e != nullptr) { if (e->hasComponent()) { abs_angle += e->getComponent().getRotation(); /*auto pnode = static_pointer_cast(entity); abs_angle += pnode->get_rotation();*/ } e = e->get_parent(); } return abs_angle; } float ContainerComponent::getAbsoluteScale() const { float abs_zoom = 1; // shared_ptr node = make_shared(entity); shared_ptr node = entity; while (node != nullptr) { if (node->hasComponent()) { abs_zoom *= node->getComponent().getScale(); /*auto pnode = static_pointer_cast(node); abs_zoom *= pnode->get_zoom();*/ } node = node->get_parent(); } return abs_zoom; } }order.cpp #include "order.hpp" #include "parser.hpp" #include "utils.hpp" namespace dex { // normal order with the following format // pair_id:type:price:match_now:agent // #1:1:0.4567 EOS:match:meetone# bool parse_order_from_string(const string &memo, order& o, bool &match_now) { string m = memo; trim(m); do { if (m.length() < 12) { print("invalid memo length"); break; } if (m.find('-') != string::npos) { print("invalid char"); break; } auto first_sep = m[0]; auto last_sep = m[m.length()-1]; if (first_sep != '#' || last_sep != '#') { print("invalid memo separator"); break; } std::vector parts; split_memo(parts, m.substr(1, m.length()-2), ':'); auto parts_size = parts.size(); if (parts_size < 3) { print("invalid memo parts"); break; } // parse required parameters uint16_t pair_id = to_int(parts[0]); uint8_t type = to_int(parts[1]); myasset price = parse_asset_from_string(parts[2]); // parse match flag, default to true, if user has no enough cpu // he can set this flag to zero, thus we can tick later to match match_now = true; // by default if (parts_size >= 4) { eosio_assert(parts[3] == "0" || parts[3] == "1", "use 0 or 1 to set match flag"); uint8_t match_int = to_int(parts[3]); if (match_int == 0) { match_now = false; } } // parse agent if (parts_size >= 5) { std::string agent = parts[4]; } // check price if (is_limited_order(type)) { if (price.amount <= 0) { print("price should be positive, malicious action"); break; } if (price.amount >= asset::max_amount) { print("price exceeds max amount, malicious action"); break; } } else { // market orders if (price.amount != 0) { print("market price should be zero, malicious action"); break; } } o.pair_id = pair_id; o.type = (order_type)type; o.price = price; return true; } while (0); return false; } } /// namespace dexCToC++/CToC++/Tree/TreeAlgorithm.cpp // // TreeAlgorithm.cpp // CToC++ // // Created by mac on 2020/5/10. // Copyright © 2020 lwb. All rights reserved. // #include "TreeAlgorithm.hpp" #include #include #include #include "TestTool.hpp" #include TreeNode * constructBinaryTree(vector pre,int pre_star,int pre_end,vector vin,int in_star,int in_end) { int rootVal = pre[pre_star]; TreeNode *root = new TreeNode(rootVal); //在中序中找到rootVal的位置 int r; for (r = in_star; r <= in_end; r++) { if (vin[r] == rootVal) { break; } } int leftLen = r - in_star; int rightLen = in_end - r; if (leftLen > 0) { //开始构建左子树 root->left = constructBinaryTree(pre,pre_star+1,pre_star+leftLen,vin,in_star,r-1); } if (rightLen > 0) { //开始构建o右子树 root->right = constructBinaryTree(pre, pre_star+leftLen+1, pre_end, vin,r+1,in_end); } return root; } TreeNode* TreeAlgorithm::reConstructBinaryTree(vector pre, vector vin) { return constructBinaryTree(pre, 0, (int)pre.size()-1, vin, 0, (int)vin.size()-1); } void innerCreateBinaryTree(TreeNode *parent, TreeNode * &root,vector &arr,int index) { if (index >= arr.size()) { return; } root = new TreeNode(arr[index]); root->parent = parent; innerCreateBinaryTree(root,root->left, arr, 2 * index + 1); innerCreateBinaryTree(root,root->right, arr, 2 * index + 2); } TreeNode* TreeAlgorithm::createBinaryTree(vector arr) { TreeNode *root = NULL; innerCreateBinaryTree(NULL,root, arr, 0); return root; } void TreeAlgorithm::traverseTreePreOrder(TreeNode *root) { if (root != NULL) { cout<val<<' '; traverseTreePreOrder(root->left); traverseTreePreOrder(root->right); } } void TreeAlgorithm::traverseTreePreOrderUsingStack(TreeNode *root) { if (!root) { cout<<" "< treeStack; TreeNode *current = root; treeStack.push(current); while (!treeStack.empty()) { TreeNode *topNode = treeStack.top(); treeStack.pop(); cout<val<right) { treeStack.push(topNode->right); } if (topNode->left) { treeStack.push(topNode->left); } } } void TreeAlgorithm::traverseTreeInOrderUsingStack(TreeNode *root) { if (root == NULL) { return; } stack treeStack; TreeNode *currentNode = root; while (!treeStack.empty() || currentNode) { if (currentNode) { treeStack.push(currentNode); currentNode = currentNode->left; } else { TreeNode *topNode = treeStack.top(); treeStack.pop(); cout<val<right; } } } void TreeAlgorithm::traverseTreeInOrder(TreeNode *root) { if (root == NULL) return; traverseTreeInOrder(root->left); cout<val<<' '; traverseTreeInOrder(root->right); } void TreeAlgorithm::traverseTreeBackOrder(TreeNode *root) { if (root != NULL) { traverseTreeBackOrder(root->left); traverseTreeBackOrder(root->right); cout<val<<' '; } } void TreeAlgorithm::traverseTreeBackOrderUsingStack(TreeNode *root) { if (!root) { return; } stack treeStack1; stack treeStack2; TreeNode *current = root; treeStack1.push(current); while (!treeStack1.empty()) { current = treeStack1.top(); treeStack1.pop(); treeStack2.push(current); if (current->left != NULL) { treeStack1.push(current->left); } if (current->right != NULL) { treeStack1.push(current->right); } } while (!treeStack2.empty()) { TreeNode *topNode = treeStack2.top(); treeStack2.pop(); cout<val<right != NULL) { TreeNode *subTreeNode = node->right; while (subTreeNode->left != NULL) { subTreeNode = subTreeNode->left; } return subTreeNode; } TreeNode *parent = node->parent; TreeNode *current = node; while (parent != NULL && parent->left != current) { current = parent; parent = parent->parent; } return parent; } TreeNode* TreeAlgorithm::findPreSuccessorNode(TreeNode *root,TreeNode *node) { if (root == NULL) { return NULL; } if (node->left != NULL) { TreeNode *current = node->left; while (current->right != NULL) { current = current->right; } return current; } TreeNode *parent = node->parent; TreeNode *current = node; while (parent != NULL && parent->right != current) { current = parent; parent = parent->parent; } return parent; } TreeNode * constructTreeFromArray(vector &array,int L,int R) { if (L == R) { TreeNode *node = new TreeNode(array[R]); return node; } else if (L > R) { return NULL; } else { int val = array[R]; TreeNode *node = new TreeNode(val); int i = L; for (; i val) { break; } } node->left = constructTreeFromArray(array,L,i-1); node->right = constructTreeFromArray(array,i,R-1); return node; } } TreeNode *TreeAlgorithm::reconstructSearchBinary(vector &array) { /** 1.这个数组已经是一个搜索二叉树后续遍历的结果了 2.根据规律,最后一个节点,必然是整颗树的根节点 3.左孩子是小于根节点的节点 4.右孩子是大于根节点的节点 5.递归求解 */ if (array.size() == 0) { return NULL; } else { return constructTreeFromArray(array, 0, (int)array.size()-1); } } /** 输入: root = [2,1,3], p = 1 2 / \ 1 3 输出: 2 分析:因为是搜索二叉树,所以中序遍历以后,序列是升序的; 左<中<右 如果给定的p值>root,那么其后继一定是在右子树,或者没有后继 如果给定的p值val >= root->val) { return inorderSuccessor(root->right, p); } else { TreeNode *left = inorderSuccessor(root->left, p); return left ? left : root; } } void traversalTree(TreeNode *root,string &s) { if (!root) { s += "#_"; return; } stringstream ss; ss<val<<"_"; s += ss.str(); traversalTree(root->left, s); traversalTree(root->right, s); } string TreeAlgorithm::serializeTree(TreeNode *root) { if (root == NULL) { return "#!"; } string rest = ""; traversalTree(root, rest); return rest; } void preTraversalCreateTree(TreeNode * &root,vector &arr) { static int index = 0; if (arr[index] == "#") { index++; return; } if (root == NULL) { string val = arr[index++]; root = new TreeNode(stoi(val)); preTraversalCreateTree(root->left, arr); preTraversalCreateTree(root->right,arr); } } TreeNode * TreeAlgorithm::createTreeForString(string s) { vector arr; string splitStr = "_"; splitString(s,arr,splitStr); TreeNode *root = NULL; preTraversalCreateTree(root, arr); return root; } typedef struct ReturnVal { bool isBalance; int height; ReturnVal(bool isB,int h) { isBalance = isB; height = h; } } *ReturnValue; ReturnValue process(TreeNode *root) { if (root == NULL) { return new ReturnVal(true,0); } ReturnValue leftVal = process(root->left); if (!leftVal->isBalance) { return new ReturnVal(false,0); } ReturnValue rightVal = process(root->right); if (!rightVal->isBalance) { return new ReturnVal(false,0); } if (abs(leftVal->height - rightVal->height) > 1) { return new ReturnVal(false,0); } int length = max(leftVal->height, rightVal->height); return new ReturnVal(true,length+1); } bool TreeAlgorithm::isBalanceBinaryTree(TreeNode *root) { return process(root)->isBalance; } TreeNode *TreeAlgorithm::invertTree(TreeNode *root) { /** 使用前序遍历 */ // if (root == NULL) { // return NULL; // } // TreeNode *temp = root->left; // root->left = root->right; // root->right = temp; // invertTree(root->left); // invertTree(root->right); // return root; //使用后续遍历 if (root == NULL) { return NULL; } invertTree(root->left); invertTree(root->right); if (root->left || root->right) { TreeNode *temp = root->left; root->left = root->right; root->right = temp; } return root; } /// 构造一个最大值的二叉树 /// @param nums 数组 /// @param L 数组左边索引 /// @param R 数组右边索引 TreeNode *constructMaxBinaryTree(vector &nums,int L,int R) { if (L == R) { return new TreeNode(nums[L]); } if (L > R) { return NULL; } // 找出最大值的下标 int maxIndex = L; int cur = L+1; while (cur <= R) { if (nums[cur] > nums[maxIndex]) { maxIndex = cur; } cur++; } TreeNode *root = new TreeNode(nums[maxIndex]); root->left = constructMaxBinaryTree(nums, L, maxIndex-1); root->right = constructMaxBinaryTree(nums, maxIndex+1, R); return root; } TreeNode* TreeAlgorithm::constructMaximumBinaryTree(vector& nums) { return constructMaxBinaryTree(nums, 0, (int)nums.size()-1); } string traveTree(TreeNode *root,unordered_map &map,vector &res) { if (root == NULL) { return "#"; } string left = traveTree(root->left, map, res); string right = traveTree(root->right, map, res); //子树的形状 string subTree = left+","+right+","+to_string(root->val); if (map[subTree] == 1) { res.push_back(root); } map[subTree]++; return subTree; } vector TreeAlgorithm::findDuplicateSubtrees(TreeNode* root) { //知道自己长啥样 // 知道别人长啥样 unordered_map map; vector res; traveTree(root, map, res); return res; } //解法1:纯递归解法 /** 后续遍历方法: 也就是说:当到达我这个节点的时候,我不做任何事情,而是继续穿我的子树,直到到底了,当回来的时候,我再判断以我为根的子树, 是否包含了p和q这2个节点,如果包含了,那我必然是最近的公共祖先。 前序遍历:自上而下,注重于递的过程; 后续遍历:自下而上,注重于归的过程 回溯算法:利用递归的思路,递的时候做点事情,归的时候也做点事情 */ bool searchCommonAncestor(TreeNode *root,TreeNode *p,TreeNode *q,TreeNode *res) { if (root == NULL) { return false; } bool left = searchCommonAncestor(root->left,p,q,res); bool right = searchCommonAncestor(root->right,p,q,res); if ((left && right) || ((root->val == p->val || root->val == q->val) && (left || right))) { res = root; } return left || right || root->val == p->val || root->val == q->val; } //解法2:找出从根到某一个节点的路径,然后找出2条路径最后一个相同的节点 static bool flag = false; void getPath(TreeNode *root,TreeNode *node,vector &path) { if (root == NULL) { return; } path.push_back(root); if (root == node) { flag = true; return; } getPath(root->left, node, path); getPath(root->right, node, path); if (flag) { return; } path.pop_back(); } TreeNode* TreeAlgorithm::lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { TreeNode *res = NULL; searchCommonAncestor(root, p,q,res); return res; } /** 给定一个二叉树,判断其是否是一个有效的二叉搜索树。 假设一个二叉搜索树具有如下特征: 节点的左子树只包含小于当前节点的数。 节点的右子树只包含大于当前节点的数。 所有左子树和右子树自身必须也是二叉搜索树。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/validate-binary-search-tree 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 */ void inOrderTravel(TreeNode *root,vector &arr) { if (root == NULL) return; inOrderTravel(root->left, arr); arr.push_back(root->val); inOrderTravel(root->right, arr); } bool TreeAlgorithm::isValidBST(TreeNode* root) { // if (root == NULL) return true; // //左子树是二叉,右子树也是二叉 // bool lt = isValidBST(root->left); // bool rt = isValidBST(root->right); // // bool leftOk = true; // bool rightOk = true; // if (root->left && root->val < root->left->val) { // leftOk = false; // } // if (root->right && root->val > root->right->val) { // rightOk = false; // } // return lt && rt && leftOk && rightOk; vector resArray; inOrderTravel(root, resArray); if (resArray.size() < 2) { return true; } //判断是否是升序 bool isAscending = true; for (int i = 1; i < resArray.size(); i++) { int temp = i - 1; if (resArray[temp] > resArray[i]) { isAscending = false; break; } } return isAscending; } /** 序列化二叉树的一种方法是使用前序遍历。当我们遇到一个非空节点时,我们可以记录下这个节点的值。如果它是一个空节点,我们可以使用一个标记值记录,例如 #。 _9_ / \ 3 2 / \ / \ 4 1 # 6 / \ / \ / \ # # # # # # 例如,上面的二叉树可以被序列化为字符串 "9,3,4,#,#,1,#,#,2,#,6,#,#",其中 # 代表一个空节点。 给定一串以逗号分隔的序列,验证它是否是正确的二叉树的前序序列化。编写一个在不重构树的条件下的可行算法。 每个以逗号分隔的字符或为一个整数或为一个表示 null 指针的 '#' 。 你可以认为输入格式总是有效的,例如它永远不会包含两个连续的逗号,比如 "1,,3" 。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/verify-preorder-serialization-of-a-binary-tree 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 */ bool TreeAlgorithm::isValidSerialization(string preorder) { int slots = 1; //默认是1个槽位(放入根节点数字以后,slots++),这时slots = 2; size_t i = 0; size_t n = preorder.length(); while (i < n) { //提前没有槽子放东西了,那就直接返回false if (slots == 0) { return false; } if (preorder[i] == ',') { i++; } else if (preorder[i] == '#') { slots--; i++; } else { //多位数要作为一个数,所以这里需要跳过一下 while (i < n && preorder[i] != ',') { i++; } slots++; } } return slots == 0; } vector TreeAlgorithm::inorderTraversal(TreeNode* root) { vector res; stack stack; while (root != NULL || !stack.empty()) { //如果有左边的节点,那就一直往左穿 while (root != NULL) { stack.push(root); root = root->left; } TreeNode *node = stack.top(); stack.pop(); res.push_back(node->val); root = node->right; } return res; } TreeNode *generateTree(vector &nums,int start,int end) { if (start > end) { return NULL; } int middle = (start + end) / 2; TreeNode *node = new TreeNode(nums[middle]); node->left = generateTree(nums, start, middle-1); node->right = generateTree(nums, middle+1, end); return node; } TreeNode* TreeAlgorithm::sortedArrayToBST(vector& nums) { int start = 0; int end = (int)nums.size()-1; TreeNode *ans = generateTree(nums, start, end); return ans; } void collectTreeNode(TreeNode *root,vector &val) { if (root == NULL) return; val.push_back(root->val); collectTreeNode(root->left, val); collectTreeNode(root->right, val); } /** 输入两棵二叉树A和B,判断B是不是A的子结构。(约定空树不是任意一个树的子结构) B是A的子结构, 即 A中有出现和B相同的结构和节点值。 时间超时了 */ //递归的去查找,是否B是A的子结构 bool recursive(TreeNode *A,TreeNode *B) { if (B == NULL) return true; if (A == NULL || A->val != B->val) return false; return recursive(A->left, B->left) && recursive(A->right, B->right); } bool TreeAlgorithm::isSubStructure(TreeNode *A, TreeNode *B) { // //前序遍历 // vector Ares; // collectTreeNode(A, Ares); // vector Bres; // collectTreeNode(B, Bres); // //判断B是否是A的一个子集 // if (Ares.size() < Bres.size()) return false; // if (Bres.size() == 0) return false; // int index = 0; // for (int i = 0; i < Ares.size(); i++) { // if (Ares[i] == Bres[index] && index < Bres.size()) { // index++; // } else if(index < Bres.size()) { // index = 0; // } else { // return true; // } // } // if (index == Bres.size()) { // return true; // } // return false; return ((A != NULL && B != NULL) && (recursive(A, B) || isSubStructure(A->left, B) || isSubStructure(A->right, B))); } hotel-rsvp/cpp/Hotel.cpp #include "Hotel.h" unsigned long Hotel::price(const Client& client) { long price = 0; auto type = client.type_; auto days = client.days_; for(Days day: days) { if (day >= 5 && type == ClientType::Regular) { price += regular_weekend_fare_; } else if (day < 5 && type == ClientType::Regular) { price += regular_weekday_fare_; } else if (day >= 5 && type == ClientType::Rewards) { price += rewards_weekend_fare_; } else if (day < 5 && type == ClientType::Rewards) { price += rewards_weekday_fare_; } } return price; } std::string Hotel::name() { return *name_; } unsigned int Hotel::rate() {return rate_; };#include using namespace std; /*Escribir un programa que pida al usuario notas. Cuando el usuario ingresa un negativo, el programa calcula el promedio de las notas ingresadas (sin considerar el negativo).*/ int main () { float nota=0, promedio=0, aux=0; while (nota >= 0) { cout << "Ingrese su nota: \n"; cin >> nota; if(nota < 0) { cout << "Su promedio es: " << promedio/aux; } promedio += nota; aux++; } return 0; }icpc/2019-1-14/B.cpp #include #include #include #include #include #include using namespace std; #define NMAX 100000 #define MMAX 300000 static int n, m; static bool mark[NMAX + 10]; static unordered_set G[NMAX + 10]; int main() { scanf("%d%d", &n, &m); for (int i = 0; i < m; i++) { int u, v; scanf("%d%d", &u, &v); G[u].insert(v); G[v].insert(u); } queue q; for (int i = 1; i <= n; i++) if (G[i].size() == 2) { q.push(i); mark[i] = true; } while (!q.empty()) { int u = q.front(); q.pop(); if (G[u].size() < 2) { mark[u] = false; continue; } int a = *G[u].begin(), b = *next(G[u].begin()); G[a].erase(u); G[b].erase(u); G[a].insert(b); G[b].insert(a); if (!mark[a] && G[a].size() == 2) { q.push(a); mark[a] = true; } if (!mark[b] && G[b].size() == 2) { q.push(b); mark[b] = true; } } puts(count(mark + 1, mark + n + 1, false) == 2 ? "Yes" : "No"); return 0; } jingcao80/Elastos1-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 "elastos/droid/graphics/CRect.h" #include "elastos/droid/graphics/CRegion.h" #include "elastos/droid/inputmethodservice/CSoftInputWindow.h" #include "elastos/droid/internal/os/CHandlerCaller.h" #include "elastos/droid/internal/os/SomeArgs.h" #include "elastos/droid/service/voice/CVoiceInteractionSessionCaller.h" #include "elastos/droid/service/voice/CVoiceInteractionSessionInsets.h" #include "elastos/droid/service/voice/CVoiceInteractionSessionRequest.h" #include "elastos/droid/service/voice/VoiceInteractionSession.h" #include "elastos/droid/app/Instrumentation.h" #include "elastos/droid/os/Binder.h" #include "elastos/droid/os/CHandler.h" #include "elastos/droid/utility/CArrayMap.h" #include "elastos/droid/view/CDispatcherState.h" #include "elastos/droid/widget/CFrameLayoutLayoutParams.h" #include "elastos/droid/R.h" #include #include using Elastos::Core::AutoLock; using Elastos::Droid::App::Instrumentation; using Elastos::Droid::Content::IContentResolver; using Elastos::Droid::Content::IDialogInterface; using Elastos::Droid::Graphics::CRect; using Elastos::Droid::Graphics::CRegion; using Elastos::Droid::InputMethodService::EIID_ISoftInputWindowCallback; using Elastos::Droid::Internal::App::EIID_IIVoiceInteractor; using Elastos::Droid::Internal::App::EIID_IIVoiceInteractorRequest; using Elastos::Droid::Internal::Os::CHandlerCaller; using Elastos::Droid::Internal::Os::EIID_IHandlerCallerCallback; using Elastos::Droid::Internal::Os::ISomeArgs; using Elastos::Droid::Internal::Os::SomeArgs; using Elastos::Droid::InputMethodService::CSoftInputWindow; using Elastos::Droid::Os::Binder; using Elastos::Droid::Os::CHandler; using Elastos::Droid::Os::EIID_IBinder; using Elastos::Droid::Service::Voice::CVoiceInteractionSessionCaller; using Elastos::Droid::Service::Voice::CVoiceInteractionSessionInsets; using Elastos::Droid::Service::Voice::CVoiceInteractionSessionRequest; using Elastos::Droid::Service::Voice::IVoiceInteractionSessionInsets; using Elastos::Droid::Utility::CArrayMap; using Elastos::Droid::Utility::IArrayMap; using Elastos::Droid::View::CDispatcherState; using Elastos::Droid::View::EIID_IKeyEventCallback; using Elastos::Droid::View::EIID_IOnComputeInternalInsetsListener; using Elastos::Droid::View::IDispatcherState; using Elastos::Droid::View::IGravity; using Elastos::Droid::View::IViewGroup; using Elastos::Droid::View::IViewGroupLayoutParams; using Elastos::Droid::View::IViewTreeObserver; using Elastos::Droid::View::IWindow; using Elastos::Droid::View::IWindowManagerLayoutParams; using Elastos::Droid::Widget::CFrameLayoutLayoutParams; using Elastos::Droid::Widget::IFrameLayoutLayoutParams; using Elastos::Droid::R; using Elastos::Core::CArrayOf; using Elastos::Core::CBoolean; using Elastos::Core::CString; using Elastos::Core::EIID_IBoolean; using Elastos::Core::EIID_IString; using Elastos::Core::IArrayOf; using Elastos::Core::IBoolean; using Elastos::Core::IString; using Elastos::Utility::Logging::Logger; namespace Elastos { namespace Droid { namespace Service { namespace Voice { //============================================= // VoiceInteractionSession::MInteractor //============================================= CAR_INTERFACE_IMPL_2(VoiceInteractionSession::MInteractor, Object, IIVoiceInteractor, IBinder) VoiceInteractionSession::MInteractor::MInteractor( /* [in] */ VoiceInteractionSession* host) : mHost(host) { } ECode VoiceInteractionSession::MInteractor::StartConfirmation( /* [in] */ const String& callingPackage, /* [in] */ IIVoiceInteractorCallback* callback, /* [in] */ ICharSequence* prompt, /* [in] */ IBundle* extras, /* [out] */ IIVoiceInteractorRequest** result) { VALIDATE_NOT_NULL(result) AutoPtr request; mHost->NewRequest(callback, (IVoiceInteractionSessionRequest**)&request); Int32 uid = Binder::GetCallingUid(); AutoPtr caller; CVoiceInteractionSessionCaller::New(callingPackage, uid, (IVoiceInteractionSessionCaller**)&caller); AutoPtr message; mHost->mHandlerCaller->ObtainMessageOOOO(VoiceInteractionSession::MSG_START_CONFIRMATION, caller.Get(), request.Get(), prompt, extras, (IMessage**)&message); mHost->mHandlerCaller->SendMessage(message.Get()); AutoPtr _request = (Request*)request.Get(); *result = _request->mInterface; REFCOUNT_ADD(*result) return NOERROR; } ECode VoiceInteractionSession::MInteractor::StartCompleteVoice( /* [in] */ const String& callingPackage, /* [in] */ IIVoiceInteractorCallback* callback, /* [in] */ ICharSequence* message, /* [in] */ IBundle* extras, /* [out] */ IIVoiceInteractorRequest** result) { VALIDATE_NOT_NULL(result) AutoPtr request; mHost->NewRequest(callback, (IVoiceInteractionSessionRequest**)&request); Int32 uid = Binder::GetCallingUid(); AutoPtr caller; CVoiceInteractionSessionCaller::New(callingPackage, uid, (IVoiceInteractionSessionCaller**)&caller); AutoPtr msg; mHost->mHandlerCaller->ObtainMessageOOOO(VoiceInteractionSession::MSG_START_COMPLETE_VOICE, caller.Get(), request.Get(), message, extras, (IMessage**)&msg); mHost->mHandlerCaller->SendMessage(msg.Get()); AutoPtr _request = (Request*)request.Get(); *result = _request->mInterface; REFCOUNT_ADD(*result) return NOERROR; } ECode VoiceInteractionSession::MInteractor::StartAbortVoice( /* [in] */ const String& callingPackage, /* [in] */ IIVoiceInteractorCallback* callback, /* [in] */ ICharSequence* message, /* [in] */ IBundle* extras, /* [out] */ IIVoiceInteractorRequest** result) { VALIDATE_NOT_NULL(result) AutoPtr request; mHost->NewRequest(callback, (IVoiceInteractionSessionRequest**)&request); Int32 uid = Binder::GetCallingUid(); AutoPtr caller; CVoiceInteractionSessionCaller::New(callingPackage, uid, (IVoiceInteractionSessionCaller**)&caller); AutoPtr msg; mHost->mHandlerCaller->ObtainMessageOOOO(VoiceInteractionSession::MSG_START_ABORT_VOICE, caller.Get(), request.Get(), message, extras, (IMessage**)&msg); mHost->mHandlerCaller->SendMessage(msg.Get()); AutoPtr _request = (Request*)request.Get(); *result = _request->mInterface; REFCOUNT_ADD(*result) return NOERROR; } ECode VoiceInteractionSession::MInteractor::StartCommand( /* [in] */ const String& callingPackage, /* [in] */ IIVoiceInteractorCallback* callback, /* [in] */ const String& command, /* [in] */ IBundle* extras, /* [out] */ IIVoiceInteractorRequest** result) { VALIDATE_NOT_NULL(result) AutoPtr request; mHost->NewRequest(callback, (IVoiceInteractionSessionRequest**)&request); Int32 uid = Binder::GetCallingUid(); AutoPtr caller; CVoiceInteractionSessionCaller::New(callingPackage, uid, (IVoiceInteractionSessionCaller**)&caller); AutoPtr message; mHost->mHandlerCaller->ObtainMessageOOOO(VoiceInteractionSession::MSG_START_COMMAND, IInterface::Probe(caller), IInterface::Probe(request), IInterface::Probe((IString*)&command), IInterface::Probe(extras), (IMessage**)&message); mHost->mHandlerCaller->SendMessage(message.Get()); AutoPtr _request = (Request*)request.Get(); *result = _request->mInterface; REFCOUNT_ADD(*result) return NOERROR; } ECode VoiceInteractionSession::MInteractor::SupportsCommands( /* [in] */ const String& callingPackage, /* [in] */ ArrayOf* commands, /* [out, callee] */ ArrayOf** results) { VALIDATE_NOT_NULL(results) Int32 uid = Binder::GetCallingUid(); AutoPtr caller; CVoiceInteractionSessionCaller::New(callingPackage, uid, (IVoiceInteractionSessionCaller**)&caller); Int32 length = commands->GetLength(); AutoPtr array; CArrayOf::New(EIID_IString, length, (IArrayOf**)&array); for (Int32 i = 0; i < length; i++) { AutoPtr str; CString::New((*commands)[i], (IString**)&str); AutoPtr obj = IInterface::Probe(str); array->Set(i, obj.Get()); } AutoPtr msg; mHost->mHandlerCaller->ObtainMessageIOO(VoiceInteractionSession::MSG_SUPPORTS_COMMANDS, 0, IInterface::Probe(caller), IInterface::Probe(array), (IMessage**)&msg); AutoPtr args; mHost->mHandlerCaller->SendMessageAndWait(msg.Get(), (ISomeArgs**)&args); if (args != NULL) { AutoPtr _args = (SomeArgs*)args.Get(); AutoPtr array = IArrayOf::Probe(_args->mArg1); Int32 size; array->GetLength(&size); AutoPtr > res = ArrayOf::Alloc(size); for (Int32 i = 0; i < size; i++) { AutoPtr obj; array->Get(i, (IInterface**)&obj); AutoPtr element = IBoolean::Probe(obj); Boolean value = element->GetValue(&value); (*res)[i] = value; } args->Recycle(); *results = res.Get(); } else { *results = ArrayOf::Alloc(commands->GetLength()); } REFCOUNT_ADD(*results) return NOERROR; } //============================================= // VoiceInteractionSession::MSession //============================================= CAR_INTERFACE_IMPL_2(VoiceInteractionSession::MSession, Object, IIVoiceInteractionSession, IBinder) VoiceInteractionSession::MSession::MSession( /* [in] */ VoiceInteractionSession* host) : mHost(host) { } ECode VoiceInteractionSession::MSession::TaskStarted( /* [in] */ IIntent* intent, /* [in] */ Int32 taskId) { AutoPtr msg; mHost->mHandlerCaller->ObtainMessageIO(VoiceInteractionSession::MSG_TASK_STARTED, taskId, intent, (IMessage**)&msg); mHost->mHandlerCaller->SendMessage(msg.Get()); return NOERROR; } ECode VoiceInteractionSession::MSession::TaskFinished( /* [in] */ IIntent* intent, /* [in] */ Int32 taskId) { AutoPtr msg; mHost->mHandlerCaller->ObtainMessageIO(VoiceInteractionSession::MSG_TASK_FINISHED, taskId, intent, (IMessage**)&msg); mHost->mHandlerCaller->SendMessage(msg.Get()); return NOERROR; } ECode VoiceInteractionSession::MSession::CloseSystemDialogs() { AutoPtr msg; mHost->mHandlerCaller->ObtainMessage(VoiceInteractionSession::MSG_CLOSE_SYSTEM_DIALOGS, (IMessage**)&msg); mHost->mHandlerCaller->SendMessage(msg.Get()); return NOERROR; } ECode VoiceInteractionSession::MSession::Destroy() { AutoPtr msg; mHost->mHandlerCaller->ObtainMessage(VoiceInteractionSession::MSG_DESTROY, (IMessage**)&msg); mHost->mHandlerCaller->SendMessage(msg.Get()); return NOERROR; } //============================================= // VoiceInteractionSession::Request::MInterface //============================================= CAR_INTERFACE_IMPL_2(VoiceInteractionSession::Request::MInterface, Object, IIVoiceInteractorRequest, IBinder) VoiceInteractionSession::Request::MInterface::MInterface( /* [in] */ Request* host) : mHost(host) { } ECode VoiceInteractionSession::Request::MInterface::Cancel() { AutoPtr session; mHost->mSession->Resolve(EIID_IVoiceInteractionSession, (IInterface**)&session); if (session != NULL) { AutoPtr _session = (VoiceInteractionSession*)session.Get(); AutoPtr msg; _session->mHandlerCaller->ObtainMessageO(VoiceInteractionSession::MSG_CANCEL, (IVoiceInteractionSessionRequest*)mHost, (IMessage**)&msg); _session->mHandlerCaller->SendMessage(msg.Get()); } return NOERROR; } //============================================= // VoiceInteractionSession::Request //============================================= CAR_INTERFACE_IMPL(VoiceInteractionSession::Request, Object, IVoiceInteractionSessionRequest) VoiceInteractionSession::Request::Request() { AutoPtr mi = new MInterface(this); mInterface = mi.Get(); } ECode VoiceInteractionSession::Request::SendConfirmResult( /* [in] */ Boolean confirmed, /* [in] */ IBundle* result) { if (VoiceInteractionSession::DEBUG) { String str1, str2; IObject::Probe(mInterface)->ToString(&str1); IObject::Probe(result)->ToString(&str2); Logger::D(VoiceInteractionSession::TAG, "sendConfirmResult: req=%s confirmed=%s result=%s", str1.string(), confirmed ? "TRUE" : "FALSE" , str2.string()); } FinishRequest(); ECode ec = mCallback->DeliverConfirmationResult(mInterface, confirmed, result); if (FAILED(ec)) { return E_REMOTE_EXCEPTION; } return NOERROR; } ECode VoiceInteractionSession::Request::SendCompleteVoiceResult( /* [in] */ IBundle* result) { if (VoiceInteractionSession::DEBUG) { String str1, str2; IObject::Probe(mInterface)->ToString(&str1); IObject::Probe(result)->ToString(&str2); Logger::D(VoiceInteractionSession::TAG, "sendCompleteVoiceResult: req=%s result=%s", str1.string(), str2.string()); } FinishRequest(); ECode ec = mCallback->DeliverCompleteVoiceResult(mInterface, result); if (FAILED(ec)) { return E_REMOTE_EXCEPTION; } return NOERROR; } ECode VoiceInteractionSession::Request::SendAbortVoiceResult( /* [in] */ IBundle* result) { if (VoiceInteractionSession::DEBUG) { String str1, str2; IObject::Probe(mInterface)->ToString(&str1); IObject::Probe(result)->ToString(&str2); Logger::D(VoiceInteractionSession::TAG, "sendConfirmResult: req=%s result=%s", str1.string(), str2.string()); } FinishRequest(); ECode ec = mCallback->DeliverAbortVoiceResult(mInterface, result); if (FAILED(ec)) { return E_REMOTE_EXCEPTION; } return NOERROR; } ECode VoiceInteractionSession::Request::SendCommandResult( /* [in] */ Boolean complete, /* [in] */ IBundle* result) { if (VoiceInteractionSession::DEBUG) { String str1, str2; IObject::Probe(mInterface)->ToString(&str1); IObject::Probe(result)->ToString(&str2); Logger::D(VoiceInteractionSession::TAG, "sendCommandResult: req=%s result=%s", str1.string(), str2.string()); } FinishRequest(); ECode ec = mCallback->DeliverCommandResult(mInterface, complete, result); if (FAILED(ec)) { return E_REMOTE_EXCEPTION; } return NOERROR; } ECode VoiceInteractionSession::Request::SendCancelResult() { if (VoiceInteractionSession::DEBUG) { String str; IObject::Probe(mInterface)->ToString(&str); Logger::D(VoiceInteractionSession::TAG, "sendCancelResult: req=%s", str.string()); } FinishRequest(); ECode ec = mCallback->DeliverCancel(mInterface); if (FAILED(ec)) { return E_REMOTE_EXCEPTION; } return NOERROR; } ECode VoiceInteractionSession::Request::constructor( /* [in] */ IIVoiceInteractorCallback* callback, /* [in] */ IVoiceInteractionSession* session) { mCallback = callback; IWeakReferenceSource::Probe(session)->GetWeakReference((IWeakReference**)&mSession); return NOERROR; } ECode VoiceInteractionSession::Request::FinishRequest() { AutoPtr session; mSession->Resolve(EIID_IVoiceInteractionSession, (IInterface**)&session); if (session == NULL) { Logger::E(VoiceInteractionSession::TAG, "VoiceInteractionSession has been destroyed"); return E_ILLEGAL_STATE_EXCEPTION; } AutoPtr req; session->RemoveRequest(IBinder::Probe(mInterface), (IVoiceInteractionSessionRequest**)&req); if (req == NULL) { String str; this->ToString(&str); Logger::E(VoiceInteractionSession::TAG, "Request not active: %s", str.string()); return E_ILLEGAL_STATE_EXCEPTION; } else if (req != this) { String str1, str2; IObject::Probe(req)->ToString(&str1); this->ToString(&str2); Logger::E(VoiceInteractionSession::TAG, "Current active request %s not same as calling request %s", str1.string(), str2.string()); return E_ILLEGAL_STATE_EXCEPTION; } return NOERROR; } //============================================= // VoiceInteractionSession::Caller //============================================= CAR_INTERFACE_IMPL(VoiceInteractionSession::Caller, Object, IVoiceInteractionSessionCaller) VoiceInteractionSession::Caller::Caller() { } ECode VoiceInteractionSession::Caller::constructor( /* [in] */ const String& _packageName, /* [in] */ Int32 _uid) { mPackageName = _packageName; mUid = _uid; return NOERROR; } //============================================= // VoiceInteractionSession::MyCallbacks //============================================= CAR_INTERFACE_IMPL_2(VoiceInteractionSession::MyCallbacks, Object, IHandlerCallerCallback, ISoftInputWindowCallback) VoiceInteractionSession::MyCallbacks::MyCallbacks( /* [in] */ VoiceInteractionSession* host) : mHost(host) { } ECode VoiceInteractionSession::MyCallbacks::ExecuteMessage( /* [in] */ IMessage* msg) { AutoPtr args; Int32 what; msg->GetWhat(&what); switch (what) { case VoiceInteractionSession::MSG_START_CONFIRMATION: { AutoPtr obj; msg->GetObj((IInterface**)&obj); args = ISomeArgs::Probe(obj); AutoPtr _args = (SomeArgs*)args.Get(); if (VoiceInteractionSession::DEBUG) { AutoPtr request = IVoiceInteractionSessionRequest::Probe(_args->mArg2); AutoPtr _request = (Request*)request.Get(); String str1, str2, str3; IObject::Probe(_request->mInterface)->ToString(&str1); IObject::Probe(_args->mArg3)->ToString(&str2); IObject::Probe(_args->mArg4)->ToString(&str3); Logger::D(VoiceInteractionSession::TAG, "onConfirm: req=%s prompt=%s extras=%s", str1.string(), str2.string(), str3.string()); } mHost->OnConfirm(IVoiceInteractionSessionCaller::Probe(_args->mArg1), IVoiceInteractionSessionRequest::Probe(_args->mArg2), ICharSequence::Probe(_args->mArg3), IBundle::Probe(_args->mArg4)); break; } case VoiceInteractionSession::MSG_START_COMPLETE_VOICE: { AutoPtr obj; msg->GetObj((IInterface**)&obj); args = ISomeArgs::Probe(obj); AutoPtr _args = (SomeArgs*)args.Get(); if (VoiceInteractionSession::DEBUG) { AutoPtr request = IVoiceInteractionSessionRequest::Probe(_args->mArg2); AutoPtr _request = (Request*)request.Get(); String str1, str2, str3; IObject::Probe(_request->mInterface)->ToString(&str1); IObject::Probe(_args->mArg3)->ToString(&str2); IObject::Probe(_args->mArg4)->ToString(&str3); Logger::D(VoiceInteractionSession::TAG, "onCompleteVoice: req=%s message=%s extras=%s", str1.string(), str2.string(), str3.string()); } mHost->OnCompleteVoice(IVoiceInteractionSessionCaller::Probe(_args->mArg1), IVoiceInteractionSessionRequest::Probe(_args->mArg2), ICharSequence::Probe(_args->mArg3), IBundle::Probe(_args->mArg4)); break; } case VoiceInteractionSession::MSG_START_ABORT_VOICE: { AutoPtr obj; msg->GetObj((IInterface**)&obj); args = ISomeArgs::Probe(obj); AutoPtr _args = (SomeArgs*)args.Get(); if (VoiceInteractionSession::DEBUG) { AutoPtr request = IVoiceInteractionSessionRequest::Probe(_args->mArg2); AutoPtr _request = (Request*)request.Get(); String str1, str2, str3; IObject::Probe(_request->mInterface)->ToString(&str1); IObject::Probe(_args->mArg3)->ToString(&str2); IObject::Probe(_args->mArg4)->ToString(&str3); Logger::D(VoiceInteractionSession::TAG, "onAbortVoice: req=%s message=%s extras=%s", str1.string(), str2.string(), str3.string()); } mHost->OnAbortVoice(IVoiceInteractionSessionCaller::Probe(_args->mArg1), IVoiceInteractionSessionRequest::Probe(_args->mArg2), ICharSequence::Probe(_args->mArg3), IBundle::Probe(_args->mArg4)); break; } case VoiceInteractionSession::MSG_START_COMMAND: { AutoPtr obj; msg->GetObj((IInterface**)&obj); args = ISomeArgs::Probe(obj); AutoPtr _args = (SomeArgs*)args.Get(); if (VoiceInteractionSession::DEBUG) { AutoPtr request = IVoiceInteractionSessionRequest::Probe(_args->mArg2); AutoPtr _request = (Request*)request.Get(); String str1, str2, str3; IObject::Probe(_request->mInterface)->ToString(&str1); IObject::Probe(_args->mArg3)->ToString(&str2); IObject::Probe(_args->mArg4)->ToString(&str3); Logger::D(VoiceInteractionSession::TAG, "onCommand: req=%s command=%s extras=%s", str1.string(), str2.string(), str3.string()); } String str4; ICharSequence::Probe(_args->mArg3)->ToString(&str4); mHost->OnCommand(IVoiceInteractionSessionCaller::Probe(_args->mArg1), IVoiceInteractionSessionRequest::Probe(_args->mArg2), str4, IBundle::Probe(_args->mArg4)); break; } case VoiceInteractionSession::MSG_SUPPORTS_COMMANDS: { AutoPtr obj; msg->GetObj((IInterface**)&obj); args = ISomeArgs::Probe(obj); AutoPtr _args = (SomeArgs*)args.Get(); if (VoiceInteractionSession::DEBUG) { String str; IObject::Probe(_args->mArg2)->ToString(&str); Logger::D(VoiceInteractionSession::TAG, "onGetSupportedCommands: cmds=%s", str.string()); } AutoPtr array = IArrayOf::Probe(_args->mArg2); Int32 size; array->GetLength(&size); AutoPtr > commands = ArrayOf::Alloc(size); for (Int32 i = 0; i < size; i++) { AutoPtr obj; array->Get(i, (IInterface**)&obj); AutoPtr element = IString::Probe(obj); String value; IObject::Probe(element)->ToString(&value); (*commands)[i] = value; } AutoPtr > results; mHost->OnGetSupportedCommands(IVoiceInteractionSessionCaller::Probe(_args->mArg1), commands.Get(), (ArrayOf**)&results); AutoPtr arrayoutput; CArrayOf::New(EIID_IBoolean, results->GetLength(), (IArrayOf**)&arrayoutput); for (Int32 i = 0; i < results->GetLength(); i++) { AutoPtr element; CBoolean::New((*results)[i], (IBoolean**)&element); arrayoutput->Set(i, element.Get()); } _args->mArg1 = IInterface::Probe(arrayoutput); break; } case VoiceInteractionSession::MSG_CANCEL: { AutoPtr obj; msg->GetObj((IInterface**)&obj); args = ISomeArgs::Probe(obj); AutoPtr _args = (SomeArgs*)args.Get(); if (VoiceInteractionSession::DEBUG) { AutoPtr request = IVoiceInteractionSessionRequest::Probe(_args->mArg2); AutoPtr _request = (Request*)request.Get(); String str; IObject::Probe(_request->mInterface)->ToString(&str); Logger::D(VoiceInteractionSession::TAG, "onCancel: req=%s", str.string()); } mHost->OnCancel(IVoiceInteractionSessionRequest::Probe(_args->mArg1)); break; } case VoiceInteractionSession::MSG_TASK_STARTED: { AutoPtr obj; msg->GetObj((IInterface**)&obj); Int32 arg1; msg->GetArg1(&arg1); if (VoiceInteractionSession::DEBUG) { String str; IObject::Probe(obj)->ToString(&str); Logger::D(VoiceInteractionSession::TAG, "onTaskStarted: intent=%s taskId=%d", str.string(), arg1); } mHost->OnTaskStarted(IIntent::Probe(obj), arg1); break; } case VoiceInteractionSession::MSG_TASK_FINISHED: { AutoPtr obj; msg->GetObj((IInterface**)&obj); Int32 arg1; msg->GetArg1(&arg1); if (VoiceInteractionSession::DEBUG) { String str; IObject::Probe(obj)->ToString(&str); Logger::D(VoiceInteractionSession::TAG, "onTaskFinished: intent=%s taskId=%d", str.string(), arg1); } mHost->OnTaskFinished(IIntent::Probe(obj), arg1); break; } case VoiceInteractionSession::MSG_CLOSE_SYSTEM_DIALOGS: { if (VoiceInteractionSession::DEBUG) Logger::D(VoiceInteractionSession::TAG, "onCloseSystemDialogs"); mHost->OnCloseSystemDialogs(); break; } case VoiceInteractionSession::MSG_DESTROY: { if (VoiceInteractionSession::DEBUG) Logger::D(VoiceInteractionSession::TAG, "doDestroy"); mHost->DoDestroy(); break; } } return NOERROR; } ECode VoiceInteractionSession::MyCallbacks::OnBackPressed() { return mHost->OnBackPressed(); } //============================================= // VoiceInteractionSession::Insets //============================================= CAR_INTERFACE_IMPL(VoiceInteractionSession::Insets, Object, IVoiceInteractionSessionInsets) VoiceInteractionSession::Insets::Insets() : mTouchableInsets(0) { CRect::New((IRect**)&mContentInsets); CRegion::New((IRegion**)&mTouchableRegion); } ECode VoiceInteractionSession::Insets::constructor() { return NOERROR; } //============================================= // VoiceInteractionSession::MInsetsComputer //============================================= CAR_INTERFACE_IMPL(VoiceInteractionSession::MInsetsComputer, Object, IOnComputeInternalInsetsListener) VoiceInteractionSession::MInsetsComputer::MInsetsComputer( /* [in] */ VoiceInteractionSession* host) : mHost(host) { } ECode VoiceInteractionSession::MInsetsComputer::OnComputeInternalInsets( /* [in] */ IInternalInsetsInfo* info) { mHost->OnComputeInsets(mHost->mTmpInsets); AutoPtr contentInsets1, contentInsets2; info->GetContentInsets((IRect**)&contentInsets1); AutoPtr _mTmpInsets = (Insets*)(mHost->mTmpInsets).Get(); contentInsets2 = _mTmpInsets->mContentInsets; contentInsets1->Set(contentInsets2.Get()); AutoPtr visibleInsets; info->GetVisibleInsets((IRect**)&visibleInsets); visibleInsets->Set(contentInsets2.Get()); AutoPtr touchableRegion1, touchableRegion2; info->GetTouchableRegion((IRegion**)&touchableRegion1); touchableRegion2 = _mTmpInsets->mTouchableRegion; Boolean isSet; touchableRegion1->Set(touchableRegion2.Get(), &isSet); Int32 touchableInsets = _mTmpInsets->mTouchableInsets; info->SetTouchableInsets(touchableInsets); return NOERROR; } //============================================= // VoiceInteractionSession //============================================= const String VoiceInteractionSession::TAG("VoiceInteractionSession"); const Boolean VoiceInteractionSession::DEBUG = TRUE; const Int32 VoiceInteractionSession::MSG_START_CONFIRMATION; const Int32 VoiceInteractionSession::MSG_START_COMPLETE_VOICE; const Int32 VoiceInteractionSession::MSG_START_ABORT_VOICE; const Int32 VoiceInteractionSession::MSG_START_COMMAND; const Int32 VoiceInteractionSession::MSG_SUPPORTS_COMMANDS; const Int32 VoiceInteractionSession::MSG_CANCEL; const Int32 VoiceInteractionSession::MSG_TASK_STARTED; const Int32 VoiceInteractionSession::MSG_TASK_FINISHED; const Int32 VoiceInteractionSession::MSG_CLOSE_SYSTEM_DIALOGS; const Int32 VoiceInteractionSession::MSG_DESTROY; CAR_INTERFACE_IMPL_2(VoiceInteractionSession, Object, IKeyEventCallback, IVoiceInteractionSession) VoiceInteractionSession::VoiceInteractionSession() : mTheme(0) , mInitialized(FALSE) , mWindowVisible(FALSE) , mWindowWasVisible(FALSE) , mInShowWindow(FALSE) { CDispatcherState::New((IDispatcherState**)&mDispatcherState); CArrayMap::New((IArrayMap**)&mActiveRequests); CVoiceInteractionSessionInsets::New((IVoiceInteractionSessionInsets**)&mTmpInsets); mTmpLocation = ArrayOf::Alloc(2); mCallbacks = new MyCallbacks(this); AutoPtr mic = new MInsetsComputer(this); mInsetsComputer = mic.Get(); AutoPtr _mSession = new MSession(this); mSession = IIVoiceInteractionSession::Probe(_mSession); AutoPtr _mInteractor = new MInteractor(this); mInteractor = IIVoiceInteractor::Probe(_mInteractor); } ECode VoiceInteractionSession::constructor( /* [in] */ IContext* context) { AutoPtr h; CHandler::New((IHandler**)&h); return constructor(context, h.Get()); } ECode VoiceInteractionSession::constructor( /* [in] */ IContext* context, /* [in] */ IHandler* handler) { mContext = context; AutoPtr l; handler->GetLooper((ILooper**)&l); CHandlerCaller::New(context, l.Get(), (IHandlerCallerCallback*)mCallbacks.Get(), TRUE, TRUE, (IHandlerCaller**)&mHandlerCaller); return NOERROR; } ECode VoiceInteractionSession::NewRequest( /* [in] */ IIVoiceInteractorCallback* callback, /* [out] */ IVoiceInteractionSessionRequest** request) { VALIDATE_NOT_NULL(request) { AutoLock syncLock(this); AutoPtr req; CVoiceInteractionSessionRequest::New(callback, this, (IVoiceInteractionSessionRequest**)&req); AutoPtr _req = (Request*)req.Get(); mActiveRequests->Put(IBinder::Probe(_req->mInterface), req); *request = req.Get(); REFCOUNT_ADD(*request) } return NOERROR; } ECode VoiceInteractionSession::RemoveRequest( /* [in] */ IBinder* reqInterface, /* [out] */ IVoiceInteractionSessionRequest** request) { VALIDATE_NOT_NULL(request) { AutoLock syncLock(this); AutoPtr obj; mActiveRequests->Get(reqInterface, (IInterface**)&obj); AutoPtr req = IVoiceInteractionSessionRequest::Probe(obj); if (req != NULL) { mActiveRequests->Remove(req); } *request = req.Get(); REFCOUNT_ADD(*request) } return NOERROR; } ECode VoiceInteractionSession::DoCreate( /* [in] */ IIVoiceInteractionManagerService* service, /* [in] */ IBinder* token, /* [in] */ IBundle* args) { mSystemService = service; mToken = token; return OnCreate(args); } ECode VoiceInteractionSession::DoDestroy() { OnDestroy(); if (mInitialized) { AutoPtr observer; mRootView->GetViewTreeObserver((IViewTreeObserver**)&observer); observer->RemoveOnComputeInternalInsetsListener(mInsetsComputer.Get()); if (mWindowAdded) { IDialogInterface::Probe(mWindow)->Dismiss(); mWindowAdded = FALSE; } mInitialized = FALSE; } return NOERROR; } ECode VoiceInteractionSession::InitViews() { mInitialized = TRUE; AutoPtr< ArrayOf > attrIds = ArrayOf::AllocInplace( const_cast(R::styleable::VoiceInteractionSession), sizeof(R::styleable::VoiceInteractionSession)/sizeof(R::styleable::VoiceInteractionSession[0])); mContext->ObtainStyledAttributes(attrIds, (ITypedArray**)&mThemeAttrs); mInflater->Inflate(R::layout::voice_interaction_session, NULL, (IView**)&mRootView); mRootView->SetSystemUiVisibility( IView::SYSTEM_UI_FLAG_LAYOUT_STABLE | IView::SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION); IDialog::Probe(mWindow)->SetContentView(mRootView); AutoPtr observer; mRootView->GetViewTreeObserver((IViewTreeObserver**)&observer); observer->AddOnComputeInternalInsetsListener(mInsetsComputer.Get()); AutoPtr v; mRootView->FindViewById(R::id::content, (IView**)&v); mContentFrame = IFrameLayout::Probe(v); return NOERROR; } ECode VoiceInteractionSession::ShowWindow() { if (DEBUG) { Logger::V(TAG, "Showing window: mWindowAdded=%s mWindowVisible=", mWindowAdded ? "TRUE" : "FALSE", mWindowVisible ? "TRUE" : "FALSE"); } if (mInShowWindow) { Logger::W(TAG, "Re-entrance in to showWindow"); return E_NULL_POINTER_EXCEPTION; } mInShowWindow = TRUE; if (!mWindowVisible) { mWindowVisible = TRUE; if (!mWindowAdded) { mWindowAdded = TRUE; AutoPtr v; OnCreateContentView((IView**)&v); if (v != NULL) { SetContentView(v); } } IDialog::Probe(mWindow)->Show(); } mWindowWasVisible = TRUE; mInShowWindow = FALSE; return NOERROR; } ECode VoiceInteractionSession::HideWindow() { if (mWindowVisible) { IDialog::Probe(mWindow)->Hide(); mWindowVisible = FALSE; } return NOERROR; } ECode VoiceInteractionSession::SetTheme( /* [in] */ Int32 theme) { if (mWindow != NULL) { Logger::E(TAG, "Must be called before onCreate()"); return E_ILLEGAL_STATE_EXCEPTION; } mTheme = theme; return NOERROR; } ECode VoiceInteractionSession::StartVoiceActivity( /* [in] */ IIntent* intent) { if (mToken == NULL) { Logger::E(TAG, "Can't call before onCreate()"); return E_ILLEGAL_STATE_EXCEPTION; } // try { Boolean result; intent->MigrateExtraStreamToClipData(&result); intent->PrepareToLeaveProcess(); AutoPtr resolver; mContext->GetContentResolver((IContentResolver**)&resolver); String type; intent->ResolveType(resolver, &type); Int32 res; mSystemService->StartVoiceActivity(mToken, intent, type, &res); Instrumentation::CheckStartActivityResult(res, intent); // } catch (RemoteException e) { // } //TODO return NOERROR; } ECode VoiceInteractionSession::GetLayoutInflater( /* [out] */ ILayoutInflater** inflater) { VALIDATE_NOT_NULL(inflater) *inflater = mInflater; REFCOUNT_ADD(*inflater) return NOERROR; } ECode VoiceInteractionSession::GetWindow( /* [out] */ IDialog** window) { VALIDATE_NOT_NULL(window) *window = IDialog::Probe(mWindow); REFCOUNT_ADD(*window) return NOERROR; } ECode VoiceInteractionSession::Finish() { if (mToken == NULL) { Logger::E(TAG, "Can't call before onCreate()"); return E_ILLEGAL_STATE_EXCEPTION; } HideWindow(); ECode ec = mSystemService->Finish(mToken); if (FAILED(ec)) { return E_REMOTE_EXCEPTION; } return NOERROR; } ECode VoiceInteractionSession::OnCreate( /* [in] */ IBundle* args) { mTheme = mTheme != 0 ? mTheme : R::style::Theme_DeviceDefault_VoiceInteractionSession; AutoPtr obj; mContext->GetSystemService(IContext::LAYOUT_INFLATER_SERVICE, (IInterface**)&obj); mInflater = ILayoutInflater::Probe(obj); CSoftInputWindow::New(mContext, String("VoiceInteractionSession"), mTheme, mCallbacks, this, mDispatcherState, IWindowManagerLayoutParams::TYPE_VOICE_INTERACTION, IGravity::TOP, TRUE, (ISoftInputWindow**)&mWindow); AutoPtr win; IDialog::Probe(mWindow)->GetWindow((IWindow**)&win); win->AddFlags(IWindowManagerLayoutParams::FLAG_HARDWARE_ACCELERATED); InitViews(); win->SetLayout(IViewGroupLayoutParams::MATCH_PARENT, IViewGroupLayoutParams::WRAP_CONTENT); mWindow->SetToken(mToken); return NOERROR; } ECode VoiceInteractionSession::OnDestroy() { return NOERROR; } ECode VoiceInteractionSession::OnCreateContentView( /* [out] */ IView** view) { VALIDATE_NOT_NULL(view) *view = NULL; return NOERROR; } ECode VoiceInteractionSession::SetContentView( /* [in] */ IView* view) { IViewGroup::Probe(mContentFrame)->RemoveAllViews(); AutoPtr params; CFrameLayoutLayoutParams::New(IViewGroupLayoutParams::MATCH_PARENT, IViewGroupLayoutParams::WRAP_CONTENT, (IFrameLayoutLayoutParams**)¶ms); IViewGroup::Probe(mContentFrame)->AddView(view, IViewGroupLayoutParams::Probe(params)); return NOERROR; } ECode VoiceInteractionSession::OnKeyDown( /* [in] */ Int32 keyCode, /* [in] */ IKeyEvent* event, /* [out] */ Boolean* result) { VALIDATE_NOT_NULL(result) *result = FALSE; return NOERROR; } ECode VoiceInteractionSession::OnKeyLongPress( /* [in] */ Int32 keyCode, /* [in] */ IKeyEvent* event, /* [out] */ Boolean* result) { VALIDATE_NOT_NULL(result) *result = FALSE; return NOERROR; } ECode VoiceInteractionSession::OnKeyUp( /* [in] */ Int32 keyCode, /* [in] */ IKeyEvent* event, /* [out] */ Boolean* result) { VALIDATE_NOT_NULL(result) *result = FALSE; return NOERROR; } ECode VoiceInteractionSession::OnKeyMultiple( /* [in] */ Int32 keyCode, /* [in] */ Int32 count, /* [in] */ IKeyEvent* event, /* [out] */ Boolean* result) { VALIDATE_NOT_NULL(result) *result = FALSE; return NOERROR; } ECode VoiceInteractionSession::OnBackPressed() { return Finish(); } ECode VoiceInteractionSession::OnCloseSystemDialogs() { return Finish(); } ECode VoiceInteractionSession::OnComputeInsets( /* [in] */ IVoiceInteractionSessionInsets* outInsets) { AutoPtr > loc = mTmpLocation; AutoPtr dialog; GetWindow((IDialog**)&dialog); AutoPtr window; dialog->GetWindow((IWindow**)&window); AutoPtr decor; window->GetDecorView((IView**)&decor); decor->GetLocationInWindow(loc.Get()); AutoPtr _outInsets = (Insets*)outInsets; _outInsets->mContentInsets->SetTop(0); _outInsets->mContentInsets->SetLeft(0); _outInsets->mContentInsets->SetRight(0); _outInsets->mContentInsets->SetBottom(0); _outInsets->mTouchableInsets = IVoiceInteractionSessionInsets::TOUCHABLE_INSETS_FRAME; _outInsets->mTouchableRegion->SetEmpty(); return NOERROR; } ECode VoiceInteractionSession::OnTaskStarted( /* [in] */ IIntent* intent, /* [in] */ Int32 taskId) { return NOERROR; } ECode VoiceInteractionSession::OnTaskFinished( /* [in] */ IIntent* intent, /* [in] */ Int32 taskId) { return Finish(); } ECode VoiceInteractionSession::OnGetSupportedCommands( /* [in] */ IVoiceInteractionSessionCaller* caller, /* [in] */ ArrayOf* commands, /* [out, callee] */ ArrayOf** results) { VALIDATE_NOT_NULL(results) *results = ArrayOf::Alloc(commands->GetLength()); REFCOUNT_ADD(*results) return NOERROR; } ECode VoiceInteractionSession::OnCompleteVoice( /* [in] */ IVoiceInteractionSessionCaller* caller, /* [in] */ IVoiceInteractionSessionRequest* request, /* [in] */ ICharSequence* message, /* [in] */ IBundle* extras) { return request->SendCompleteVoiceResult(NULL); } ECode VoiceInteractionSession::OnAbortVoice( /* [in] */ IVoiceInteractionSessionCaller* caller, /* [in] */ IVoiceInteractionSessionRequest* request, /* [in] */ ICharSequence* message, /* [in] */ IBundle* extras) { return request->SendAbortVoiceResult(NULL); } }//namespace Voice }//namespace Service }//namespace Droid }//namespace Elastostools/ouzel/xcode/PBXGroup.hpp // Ouzel by #ifndef OUZEL_XCODE_PBXGROUP_HPP #define OUZEL_XCODE_PBXGROUP_HPP #include #include "PBXFileElement.hpp" namespace ouzel::xcode { class PBXGroup final: public PBXFileElement { public: PBXGroup() = default; std::string getIsa() const override { return "PBXGroup"; } plist::Value encode() const override { auto result = PBXFileElement::encode(); result["children"] = plist::Array{}; for (const auto child : children) if (child) result["children"].pushBack(toString(child->getId())); return result; } std::vector children; }; } #endif // OUZEL_XCODE_PBXGROUP_HPP /* Minetest Copyright (C) 2010-2014 celeron55, <> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser 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 "drawscene.h" #include "settings.h" #include "clouds.h" #include "clientmap.h" #include "util/timetaker.h" #include "fontengine.h" #include "guiscalingfilter.h" typedef enum { LEFT = -1, RIGHT = 1, EYECOUNT = 2 } paralax_sign; void draw_selectionbox(video::IVideoDriver* driver, Hud& hud, std::vector& hilightboxes, bool show_hud) { static const s16 selectionbox_width = rangelim(g_settings->getS16("selectionbox_width"), 1, 5); if (!show_hud) return; video::SMaterial oldmaterial = driver->getMaterial2D(); video::SMaterial m; m.Thickness = selectionbox_width; m.Lighting = false; driver->setMaterial(m); hud.drawSelectionBoxes(hilightboxes); driver->setMaterial(oldmaterial); } void draw_anaglyph_3d_mode(Camera& camera, bool show_hud, Hud& hud, std::vector hilightboxes, video::IVideoDriver* driver, scene::ISceneManager* smgr, bool draw_wield_tool, Client& client, gui::IGUIEnvironment* guienv ) { /* preserve old setup*/ irr::core::vector3df oldPosition = camera.getCameraNode()->getPosition(); irr::core::vector3df oldTarget = camera.getCameraNode()->getTarget(); irr::core::matrix4 startMatrix = camera.getCameraNode()->getAbsoluteTransformation(); irr::core::vector3df focusPoint = (camera.getCameraNode()->getTarget() - camera.getCameraNode()->getAbsolutePosition()).setLength(1) + camera.getCameraNode()->getAbsolutePosition(); //Left eye... irr::core::vector3df leftEye; irr::core::matrix4 leftMove; leftMove.setTranslation( irr::core::vector3df(-g_settings->getFloat("3d_paralax_strength"), 0.0f, 0.0f)); leftEye = (startMatrix * leftMove).getTranslation(); //clear the depth buffer, and color driver->beginScene( true, true, irr::video::SColor(0, 200, 200, 255)); driver->getOverrideMaterial().Material.ColorMask = irr::video::ECP_RED; driver->getOverrideMaterial().EnableFlags = irr::video::EMF_COLOR_MASK; driver->getOverrideMaterial().EnablePasses = irr::scene::ESNRP_SKY_BOX + irr::scene::ESNRP_SOLID + irr::scene::ESNRP_TRANSPARENT + irr::scene::ESNRP_TRANSPARENT_EFFECT + irr::scene::ESNRP_SHADOW; camera.getCameraNode()->setPosition(leftEye); camera.getCameraNode()->setTarget(focusPoint); smgr->drawAll(); driver->setTransform(video::ETS_WORLD, core::IdentityMatrix); if (show_hud) { draw_selectionbox(driver, hud, hilightboxes, show_hud); if (draw_wield_tool) camera.drawWieldedTool(&leftMove); } guienv->drawAll(); //Right eye... irr::core::vector3df rightEye; irr::core::matrix4 rightMove; rightMove.setTranslation( irr::core::vector3df(g_settings->getFloat("3d_paralax_strength"), 0.0f, 0.0f)); rightEye = (startMatrix * rightMove).getTranslation(); //clear the depth buffer driver->clearZBuffer(); driver->getOverrideMaterial().Material.ColorMask = irr::video::ECP_GREEN + irr::video::ECP_BLUE; driver->getOverrideMaterial().EnableFlags = irr::video::EMF_COLOR_MASK; driver->getOverrideMaterial().EnablePasses = irr::scene::ESNRP_SKY_BOX + irr::scene::ESNRP_SOLID + irr::scene::ESNRP_TRANSPARENT + irr::scene::ESNRP_TRANSPARENT_EFFECT + irr::scene::ESNRP_SHADOW; camera.getCameraNode()->setPosition(rightEye); camera.getCameraNode()->setTarget(focusPoint); smgr->drawAll(); driver->setTransform(video::ETS_WORLD, core::IdentityMatrix); if (show_hud) { draw_selectionbox(driver, hud, hilightboxes, show_hud); if (draw_wield_tool) camera.drawWieldedTool(&rightMove); } guienv->drawAll(); driver->getOverrideMaterial().Material.ColorMask = irr::video::ECP_ALL; driver->getOverrideMaterial().EnableFlags = 0; driver->getOverrideMaterial().EnablePasses = 0; camera.getCameraNode()->setPosition(oldPosition); camera.getCameraNode()->setTarget(oldTarget); } void init_texture(video::IVideoDriver* driver, const v2u32& screensize, video::ITexture** texture, const char* name) { if (*texture != NULL) { driver->removeTexture(*texture); } *texture = driver->addRenderTargetTexture( core::dimension2d(screensize.X, screensize.Y), name, irr::video::ECF_A8R8G8B8); } video::ITexture* draw_image(const v2u32& screensize, paralax_sign psign, const irr::core::matrix4& startMatrix, const irr::core::vector3df& focusPoint, bool show_hud, video::IVideoDriver* driver, Camera& camera, scene::ISceneManager* smgr, Hud& hud, std::vector& hilightboxes, bool draw_wield_tool, Client& client, gui::IGUIEnvironment* guienv, video::SColor skycolor ) { static video::ITexture* images[2] = { NULL, NULL }; static v2u32 last_screensize = v2u32(0,0); video::ITexture* image = NULL; if (screensize != last_screensize) { init_texture(driver, screensize, &images[1], "mt_drawimage_img1"); init_texture(driver, screensize, &images[0], "mt_drawimage_img2"); last_screensize = screensize; } if (psign == RIGHT) image = images[1]; else image = images[0]; driver->setRenderTarget(image, true, true, irr::video::SColor(255, skycolor.getRed(), skycolor.getGreen(), skycolor.getBlue())); irr::core::vector3df eye_pos; irr::core::matrix4 movement; movement.setTranslation( irr::core::vector3df((int) psign * g_settings->getFloat("3d_paralax_strength"), 0.0f, 0.0f)); eye_pos = (startMatrix * movement).getTranslation(); //clear the depth buffer driver->clearZBuffer(); camera.getCameraNode()->setPosition(eye_pos); camera.getCameraNode()->setTarget(focusPoint); smgr->drawAll(); driver->setTransform(video::ETS_WORLD, core::IdentityMatrix); if (show_hud) { draw_selectionbox(driver, hud, hilightboxes, show_hud); if (draw_wield_tool) camera.drawWieldedTool(&movement); } guienv->drawAll(); /* switch back to real renderer */ driver->setRenderTarget(0, true, true, irr::video::SColor(0, skycolor.getRed(), skycolor.getGreen(), skycolor.getBlue())); return image; } video::ITexture* draw_hud(video::IVideoDriver* driver, const v2u32& screensize, bool show_hud, Hud& hud, Client& client, bool draw_crosshair, video::SColor skycolor, gui::IGUIEnvironment* guienv, Camera& camera ) { static video::ITexture* image = NULL; init_texture(driver, screensize, &image, "mt_drawimage_hud"); driver->setRenderTarget(image, true, true, irr::video::SColor(255,0,0,0)); if (show_hud) { if (draw_crosshair) hud.drawCrosshair(); hud.drawHotbar(client.getPlayerItem()); hud.drawLuaElements(camera.getOffset()); guienv->drawAll(); } driver->setRenderTarget(0, true, true, irr::video::SColor(0, skycolor.getRed(), skycolor.getGreen(), skycolor.getBlue())); return image; } void draw_interlaced_3d_mode(Camera& camera, bool show_hud, Hud& hud, std::vector hilightboxes, video::IVideoDriver* driver, scene::ISceneManager* smgr, const v2u32& screensize, bool draw_wield_tool, Client& client, gui::IGUIEnvironment* guienv, video::SColor skycolor ) { /* save current info */ irr::core::vector3df oldPosition = camera.getCameraNode()->getPosition(); irr::core::vector3df oldTarget = camera.getCameraNode()->getTarget(); irr::core::matrix4 startMatrix = camera.getCameraNode()->getAbsoluteTransformation(); irr::core::vector3df focusPoint = (camera.getCameraNode()->getTarget() - camera.getCameraNode()->getAbsolutePosition()).setLength(1) + camera.getCameraNode()->getAbsolutePosition(); /* create left view */ video::ITexture* left_image = draw_image(screensize, LEFT, startMatrix, focusPoint, show_hud, driver, camera, smgr, hud, hilightboxes, draw_wield_tool, client, guienv, skycolor); //Right eye... irr::core::vector3df rightEye; irr::core::matrix4 rightMove; rightMove.setTranslation( irr::core::vector3df(g_settings->getFloat("3d_paralax_strength"), 0.0f, 0.0f)); rightEye = (startMatrix * rightMove).getTranslation(); //clear the depth buffer driver->clearZBuffer(); camera.getCameraNode()->setPosition(rightEye); camera.getCameraNode()->setTarget(focusPoint); smgr->drawAll(); driver->setTransform(video::ETS_WORLD, core::IdentityMatrix); if (show_hud) { draw_selectionbox(driver, hud, hilightboxes, show_hud); if(draw_wield_tool) camera.drawWieldedTool(&rightMove); } guienv->drawAll(); for (unsigned int i = 0; i < screensize.Y; i+=2 ) { #if (IRRLICHT_VERSION_MAJOR >= 1) && (IRRLICHT_VERSION_MINOR >= 8) driver->draw2DImage(left_image, irr::core::position2d(0, i), #else driver->draw2DImage(left_image, irr::core::position2d(0, screensize.Y-i), #endif irr::core::rect(0, i,screensize.X, i+1), 0, irr::video::SColor(255, 255, 255, 255), false); } /* cleanup */ camera.getCameraNode()->setPosition(oldPosition); camera.getCameraNode()->setTarget(oldTarget); } void draw_sidebyside_3d_mode(Camera& camera, bool show_hud, Hud& hud, std::vector hilightboxes, video::IVideoDriver* driver, scene::ISceneManager* smgr, const v2u32& screensize, bool draw_wield_tool, Client& client, gui::IGUIEnvironment* guienv, video::SColor skycolor ) { /* save current info */ irr::core::vector3df oldPosition = camera.getCameraNode()->getPosition(); irr::core::vector3df oldTarget = camera.getCameraNode()->getTarget(); irr::core::matrix4 startMatrix = camera.getCameraNode()->getAbsoluteTransformation(); irr::core::vector3df focusPoint = (camera.getCameraNode()->getTarget() - camera.getCameraNode()->getAbsolutePosition()).setLength(1) + camera.getCameraNode()->getAbsolutePosition(); /* create left view */ video::ITexture* left_image = draw_image(screensize, LEFT, startMatrix, focusPoint, show_hud, driver, camera, smgr, hud, hilightboxes, draw_wield_tool, client, guienv, skycolor); /* create right view */ video::ITexture* right_image = draw_image(screensize, RIGHT, startMatrix, focusPoint, show_hud, driver, camera, smgr, hud, hilightboxes, draw_wield_tool, client, guienv, skycolor); /* create hud overlay */ video::ITexture* hudtexture = draw_hud(driver, screensize, show_hud, hud, client, false, skycolor, guienv, camera ); driver->makeColorKeyTexture(hudtexture, irr::video::SColor(255, 0, 0, 0)); //makeColorKeyTexture mirrors texture so we do it twice to get it right again driver->makeColorKeyTexture(hudtexture, irr::video::SColor(255, 0, 0, 0)); draw2DImageFilterScaled(driver, left_image, irr::core::rect(0, 0, screensize.X/2, screensize.Y), irr::core::rect(0, 0, screensize.X, screensize.Y), 0, 0, false); draw2DImageFilterScaled(driver, hudtexture, irr::core::rect(0, 0, screensize.X/2, screensize.Y), irr::core::rect(0, 0, screensize.X, screensize.Y), 0, 0, true); draw2DImageFilterScaled(driver, right_image, irr::core::rect(screensize.X/2, 0, screensize.X, screensize.Y), irr::core::rect(0, 0, screensize.X, screensize.Y), 0, 0, false); draw2DImageFilterScaled(driver, hudtexture, irr::core::rect(screensize.X/2, 0, screensize.X, screensize.Y), irr::core::rect(0, 0, screensize.X, screensize.Y), 0, 0, true); left_image = NULL; right_image = NULL; /* cleanup */ camera.getCameraNode()->setPosition(oldPosition); camera.getCameraNode()->setTarget(oldTarget); } void draw_top_bottom_3d_mode(Camera& camera, bool show_hud, Hud& hud, std::vector hilightboxes, video::IVideoDriver* driver, scene::ISceneManager* smgr, const v2u32& screensize, bool draw_wield_tool, Client& client, gui::IGUIEnvironment* guienv, video::SColor skycolor ) { /* save current info */ irr::core::vector3df oldPosition = camera.getCameraNode()->getPosition(); irr::core::vector3df oldTarget = camera.getCameraNode()->getTarget(); irr::core::matrix4 startMatrix = camera.getCameraNode()->getAbsoluteTransformation(); irr::core::vector3df focusPoint = (camera.getCameraNode()->getTarget() - camera.getCameraNode()->getAbsolutePosition()).setLength(1) + camera.getCameraNode()->getAbsolutePosition(); /* create left view */ video::ITexture* left_image = draw_image(screensize, LEFT, startMatrix, focusPoint, show_hud, driver, camera, smgr, hud, hilightboxes, draw_wield_tool, client, guienv, skycolor); /* create right view */ video::ITexture* right_image = draw_image(screensize, RIGHT, startMatrix, focusPoint, show_hud, driver, camera, smgr, hud, hilightboxes, draw_wield_tool, client, guienv, skycolor); /* create hud overlay */ video::ITexture* hudtexture = draw_hud(driver, screensize, show_hud, hud, client, false, skycolor, guienv, camera ); driver->makeColorKeyTexture(hudtexture, irr::video::SColor(255, 0, 0, 0)); //makeColorKeyTexture mirrors texture so we do it twice to get it right again driver->makeColorKeyTexture(hudtexture, irr::video::SColor(255, 0, 0, 0)); draw2DImageFilterScaled(driver, left_image, irr::core::rect(0, 0, screensize.X, screensize.Y/2), irr::core::rect(0, 0, screensize.X, screensize.Y), 0, 0, false); draw2DImageFilterScaled(driver, hudtexture, irr::core::rect(0, 0, screensize.X, screensize.Y/2), irr::core::rect(0, 0, screensize.X, screensize.Y), 0, 0, true); draw2DImageFilterScaled(driver, right_image, irr::core::rect(0, screensize.Y/2, screensize.X, screensize.Y), irr::core::rect(0, 0, screensize.X, screensize.Y), 0, 0, false); draw2DImageFilterScaled(driver, hudtexture, irr::core::rect(0, screensize.Y/2, screensize.X, screensize.Y), irr::core::rect(0, 0, screensize.X, screensize.Y), 0, 0, true); left_image = NULL; right_image = NULL; /* cleanup */ camera.getCameraNode()->setPosition(oldPosition); camera.getCameraNode()->setTarget(oldTarget); } void draw_plain(Camera& camera, bool show_hud, Hud& hud, std::vector hilightboxes, video::IVideoDriver* driver, bool draw_wield_tool, Client& client, gui::IGUIEnvironment* guienv) { driver->setTransform(video::ETS_WORLD, core::IdentityMatrix); draw_selectionbox(driver, hud, hilightboxes, show_hud); if(draw_wield_tool) camera.drawWieldedTool(); } void draw_scene(video::IVideoDriver *driver, scene::ISceneManager *smgr, Camera &camera, Client& client, LocalPlayer *player, Hud &hud, Mapper &mapper, gui::IGUIEnvironment *guienv, std::vector hilightboxes, const v2u32 &screensize, video::SColor skycolor, bool show_hud, bool show_minimap) { TimeTaker timer("smgr"); bool draw_wield_tool = (show_hud && (player->hud_flags & HUD_FLAG_WIELDITEM_VISIBLE) && camera.getCameraMode() < CAMERA_MODE_THIRD ); bool draw_crosshair = ((player->hud_flags & HUD_FLAG_CROSSHAIR_VISIBLE) && (camera.getCameraMode() != CAMERA_MODE_THIRD_FRONT)); #ifdef HAVE_TOUCHSCREENGUI try { draw_crosshair = !g_settings->getBool("touchtarget"); } catch(SettingNotFoundException) {} #endif std::string draw_mode = g_settings->get("3d_mode"); smgr->drawAll(); if (draw_mode == "anaglyph") { draw_anaglyph_3d_mode(camera, show_hud, hud, hilightboxes, driver, smgr, draw_wield_tool, client, guienv); draw_crosshair = false; } else if (draw_mode == "interlaced") { draw_interlaced_3d_mode(camera, show_hud, hud, hilightboxes, driver, smgr, screensize, draw_wield_tool, client, guienv, skycolor); draw_crosshair = false; } else if (draw_mode == "sidebyside") { draw_sidebyside_3d_mode(camera, show_hud, hud, hilightboxes, driver, smgr, screensize, draw_wield_tool, client, guienv, skycolor); show_hud = false; } else if (draw_mode == "topbottom") { draw_top_bottom_3d_mode(camera, show_hud, hud, hilightboxes, driver, smgr, screensize, draw_wield_tool, client, guienv, skycolor); show_hud = false; } else { draw_plain(camera, show_hud, hud, hilightboxes, driver, draw_wield_tool, client, guienv); } /* Post effects */ { client.getEnv().getClientMap().renderPostFx(camera.getCameraMode()); } //TODO how to make those 3d too if (show_hud) { if (draw_crosshair) hud.drawCrosshair(); hud.drawHotbar(client.getPlayerItem()); hud.drawLuaElements(camera.getOffset()); if (show_minimap) mapper.drawMinimap(); } guienv->drawAll(); timer.stop(true); } /* Draws a screen with a single text on it. Text will be removed when the screen is drawn the next time. Additionally, a progressbar can be drawn when percent is set between 0 and 100. */ void draw_load_screen(const std::wstring &text, IrrlichtDevice* device, gui::IGUIEnvironment* guienv, float dtime, int percent, bool clouds ) { video::IVideoDriver* driver = device->getVideoDriver(); v2u32 screensize = porting::getWindowSize(); v2s32 textsize(g_fontengine->getTextWidth(text), g_fontengine->getLineHeight()); v2s32 center(screensize.X / 2, screensize.Y / 2); core::rect textrect(center - textsize / 2, center + textsize / 2); gui::IGUIStaticText *guitext = guienv->addStaticText( text.c_str(), textrect, false, false); guitext->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_UPPERLEFT); bool cloud_menu_background = clouds && g_settings->getBool("menu_clouds"); if (cloud_menu_background) { g_menuclouds->step(dtime*3); g_menuclouds->render(); driver->beginScene(true, true, video::SColor(255, 140, 186, 250)); g_menucloudsmgr->drawAll(); } else driver->beginScene(true, true, video::SColor(255, 0, 0, 0)); // draw progress bar if ((percent >= 0) && (percent <= 100)) { v2s32 barsize( // 342 is (approximately) 256/0.75 to keep bar on same size as // before with default settings 342 * porting::getDisplayDensity() * g_settings->getFloat("gui_scaling"), g_fontengine->getTextHeight() * 2); core::rect barrect(center - barsize / 2, center + barsize / 2); driver->draw2DRectangle(video::SColor(255, 255, 255, 255),barrect, NULL); // border driver->draw2DRectangle(video::SColor(255, 64, 64, 64), core::rect ( barrect.UpperLeftCorner + 1, barrect.LowerRightCorner-1), NULL); // black inside the bar driver->draw2DRectangle(video::SColor(255, 128, 128, 128), core::rect ( barrect.UpperLeftCorner + 1, core::vector2d( barrect.LowerRightCorner.X - (barsize.X - 1) + percent * (barsize.X - 2) / 100, barrect.LowerRightCorner.Y - 1)), NULL); // the actual progress } guienv->drawAll(); driver->endScene(); guitext->remove(); //return guitext; } roshan11160/Competitive-Programming-Solutions // Follow the java solution // Short solution in CPP class Solution { public: bool isValidSudoku(vector> &board) { int rows[9][9] = {0}; int cols[9][9] = {0}; int blocks[3][3][9] = {0}; for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { if (board[i][j] != '.') { int number = board[i][j] - '1'; if (rows[number][j]++) return 0; if (cols[i][number]++) return 0; if (blocks[i / 3][j / 3][number]++) return false; } } } return true; } }; // Time Complexity - O(n) -> iterating over the entire board // Space Complexity - O(n) -> using arrays to store value // Long Solution in CPP class Solution { public: bool isValidSudoku(vector> &board) { int rows = 9; int cols = 9; for (int i = 0; i < rows; i++) { int res1 = valid_rows(i, board); int res2 = valid_cols(i, board); if (res1 < 1 || res2 < 1) return false; } int res3 = valid_subsquares(board); if (res3 < 1) return false; return true; } int valid_rows(int rows, vector> &board) { set s; for (int i = 0; i < 9; i++) { // To check if value is between 1 and 9 if ((board[rows][i] < '1' || board[rows][i] > '9') && board[rows][i] != '.') { cout << "Value outside 0 and 9 in rows" << endl; return -1; } // Check for duplicate values else { if (board[rows][i] != '.') { if (s.insert(board[rows][i]).second == false) { cout << "Duplicate values in rows" << endl; return 0; } } } } return 1; } int valid_cols(int cols, vector> &board) { set s; for (int i = 0; i < 9; i++) { if ((board[i][cols] < '1' || board[i][cols] > '9') && board[i][cols] != '.') { cout << "Value outside 0 and 9 in cols" << endl; return -1; } else { if (board[i][cols] != '.') { if (s.insert(board[i][cols]).second == false) { cout << "Same element in cols" << endl; return 0; } } } } return 1; } int valid_subsquares(vector> &board) { for (int i = 0; i < 9; i = i + 3) { for (int j = 0; j < 9; j = j + 3) { set s; for (int r = i; r < i + 3; r++) { for (int c = j; c < j + 3; c++) { if ((board[r][c] < '1' || board[r][c] > '9') && board[r][c] != '.') { cout << "Value outside 0 and 9 in subsquares" << endl; return -1; } // Check for duplicate elements else { if (board[r][c] != '.') { if (s.insert(board[r][c]).second == false) { cout << "Same element in subsquares" << endl; return 0; } } } } } } } return 1; } }; 0 //===- driver.cpp - Verilator software driver -----------------------------===// // // A fairly standard, boilerplate Verilator C++ simulation driver. Assumes the // top level exposes just two signals: 'clk' and 'rstn'. // //===----------------------------------------------------------------------===// #include "Vmain.h" #ifdef DEBUG #include "verilated_vcd_c.h" #endif #include "signal.h" #include vluint64_t timeStamp; // Stop the simulation gracefully on ctrl-c. volatile bool stopSimulation = false; void handle_sigint(int) { stopSimulation = true; } // Called by $time in Verilog. double sc_time_stamp() { return timeStamp; } int main(int argc, char **argv) { // Register graceful exit handler. signal(SIGINT, handle_sigint); Verilated::commandArgs(argc, argv); size_t numCyclesToRun = 0; // Search the command line args for those we are sensitive to. for (int i = 1; i < argc; ++i) { if (std::string(argv[i]) == "--cycles") { if (i + 1 < argc) { numCyclesToRun = std::strtoull(argv[++i], nullptr, 10); } else { std::cerr << "--cycles must be followed by number of cycles." << std::endl; return 1; } } } // Construct the simulated module's C++ model. auto &dut = *new Vmain(); #ifdef DEBUG VerilatedVcdC *tfp = new VerilatedVcdC; Verilated::traceEverOn(true); dut.trace(tfp, 99); // Trace 99 levels of hierarchy tfp->open("main.vcd"); #endif std::cout << "[driver] Starting simulation" << std::endl; // Reset. dut.rstn = 0; dut.clk = 0; // Run for a few cycles with reset held. for (timeStamp = 0; timeStamp < 10 && !Verilated::gotFinish(); timeStamp++) { dut.eval(); dut.clk = !dut.clk; #ifdef DEBUG tfp->dump(timeStamp); #endif } // Take simulation out of reset. dut.rstn = 1; // Run for the specified number of cycles out of reset. for (; timeStamp <= (numCyclesToRun * 2) && !Verilated::gotFinish() && !stopSimulation; timeStamp++) { dut.eval(); dut.clk = !dut.clk; #ifdef DEBUG tfp->dump(timeStamp); #endif } // Tell the simulator that we're going to exit. This flushes the output(s) and // frees whatever memory may have been allocated. dut.final(); #ifdef DEBUG tfp->close(); #endif std::cout << "[driver] Ending simulation at tick #" << timeStamp << std::endl; return 0; } 0of/WebOS-Magna #include "WindowStatusBar.h" #include "render/RadialGradient.h" #include "render/LinearGradient.h" using namespace Magna::Render; #include "glue/FontMetrics.h" using namespace Magna::Glue; #include "DesktopEventDispatcher.h" #include "DesktopWindow.h" namespace Magna{ namespace SystemComponent{ namespace Desktop{ WindowStatusBar::WindowStatusBar() :Controller() ,m_group() ,m_reservedButtons() ,m_runningWnds() ,m_widMapsButtonIndex() ,m_layout( new LinearLayout( LinearLayout::LinearLayoutOrientation_Vertical ) ) ,m_toggledIndex( 0 ) ,m_unitSize( DesktopStatusBar::shared_status_bar_width - 6 , DesktopStatusBar::shared_status_bar_width + 4 ) ,m_buttonSharedFillBrush() ,m_pressedButtonSharedFillBrush(){ //setScrollSize( IntegerSize( DesktopStatusBar::shared_status_bar_width - 6, 600 ) ); Image _unit_bg = Image( DesktopWindow::getDesktopResDir() + L"wnd_box.png") ; _unit_bg.scale( m_unitSize, Image::ImageTransformationMode_Smooth ); m_buttonSharedFillBrush.setTexture(_unit_bg); Image _unit_pressed_bg = Image( DesktopWindow::getDesktopResDir() + L"wnd_box_focus.png") ; _unit_pressed_bg.scale( m_unitSize, Image::ImageTransformationMode_Smooth ); m_pressedButtonSharedFillBrush.setTexture( _unit_pressed_bg ); m_group.OnceButtonToggled.connectAction( this, &WindowStatusBar::buttonToggledAction); m_group.OnceButtonUntoggled.connectAction( this, &WindowStatusBar::buttonUntoggledAction); m_layout->setLayoutOffset( IntegerDyadCoordinate( 0, 12 ) ); m_group.setExclusive( !false ); setLayout( m_layout ); //setScrollBarPolicy(ScrollBarPolicy_AlwaysOff); } WindowStatusBar::~WindowStatusBar(){ } void WindowStatusBar::openNewWindow( const SharedPtr& wnd ){ if( !wnd.isNull() ){ uint32 _added_index = 0; if( !m_reservedButtons.empty() ){ auto &_button = m_reservedButtons.front(); Image _scaled_icon = wnd->m_properties.m_icon; IntegerSize _icon_size( m_unitSize.getWidth() - 6, m_unitSize.getWidth() - 6); _scaled_icon.scale( _icon_size ); _button->setIcon( _scaled_icon ); _added_index = m_group.addButton( _button ); m_reservedButtons.pop(); _button->setToggled( true ); m_layout->addController( _button ); } else{ //auto &_text_size = FontMetrics::measureSize( wnd->m_properties.m_title, Font() ); //if( _text_size.getWidth() > DesktopStatusBar::shared_status_bar_width ){ //} SharedPtr